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..2d8a973910 --- /dev/null +++ b/.claude/skills/verify-jdbc-poll-ahead/SKILL.md @@ -0,0 +1,205 @@ +--- +name: verify-jdbc-poll-ahead +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 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 + +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. | +| `FailedQueueInert` | After the queue recorded a failure, `addEndpoints` queues, reserves and opens nothing. | Endpoints and reservations pile up on a dead queue, and `moreExpected` could be set again after `fail()` cleared it. | +| `CancelStopsPolling` | No poll is sent after `Statement.cancel()`, the deadline, or `close()` has finished stopping the poller. | Server work continues after the user cancelled. | +| `Backpressure` | The poller does not poll while unread endpoints are at `pollInfoPrefetch`. | The driver runs ahead of a slow reader without bound. | +| `OpenWithinLimit` | Open, opening and unread `DoGet` streams never exceed the limit. The stream the application is reading counts until it is read to the end. | More open streams, each buffering up to 5 batches, than the setting promises. | +| `SlotFreedOnExhaust` | A stream's slot is freed in the step where the application's own `stream.next()` returns false. No finished stream still holds a slot while the application reads another one. | The poller stays paused, and pending endpoints stay unopened, behind a stream nobody reads. This is a progress rule, not a safety rule: see finding 3. | +| `NoSpin` | No poll is sent straight after an answer that added nothing. | A busy loop against servers that answer at once. | +| `Terminates` | Every result eventually ends or throws, if nobody cancels. | `next()` hangs forever. | +| `InlineMeansPoller` | Structural: when the reader runs the poller inline, the poller is not paused or orphaned. | Two threads drive one continuation chain. | + +## Scope, bounds, assumptions + +- Bounds: up to `N` endpoints per query (default 3; also checked with `N=4`), `Limit=2`. One `ResultSet`. Two or more results sharing the poller pool are not modeled, except that a rejected start (`Init`) and a rejected resume (`ReaderResumeRejected`) are free choices: the pool may be busy or not. +- Rows are abstracted: an endpoint is taken (`AppTake`) and later read to the end (`AppExhaust`), and nothing between is tracked. An endpoint is either empty (its future yields `null`, `AppReadEmpty`) or not. PollInfo is modeled as a count of endpoints so far, so the append-only rule shows up as "never fewer than before". +- Time is abstracted: a backoff is one step. Its length (100 ms doubling up to `pollInfoMaxBackoff`) is not checked, and neither are the 10 x 100 us resubmit retries (only their outcome). +- The server may answer a poll at any moment, including at once with nothing new. +- 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. The application thread runs it in two places: `Q.endpointExhausted` when its own `stream.next()` returned false (`AppExhaust`, read to the end and free in one step), and `awaitNext` consuming a null future (`AppReadEmpty`). Closing the finished stream and opening the reserved endpoints happen after the unlock and are not part of the step. + - `Q.awaitNext`'s lock-protected check and the start of the wait (`AppEnd`, `AppIdle`, `ReaderWait`). +- Steps the model splits because the code does not do them atomically: + - taking a ready stream (`AppTake`, no slot change) and reading it to the end (`AppExhaust`, slot freed): the stream keeps its slot in between, as `openUnread` does; + - the resume after unlocking (`ReaderResume`, `ReaderResumeRejected`), against the poller's `owned` flag; + - stream opening outside the lock into reserved slots (`OpenReserved`, `OpenFails`); + - the orphaned poller run inline by the reader (`AppIdle`, `InlineExit`, `PollerApplyHandBack`). A poller starts orphaned when the pool rejects `start()`, as it becomes orphaned after a rejected resume or hand-back, and the same three actions serve all three; + - `Statement.cancel()`: `PollInfoOperation.cancel()` first (`CancelOp`: an open poll ends `CANCELLED`, so the poller can record "Statement canceled" as the queue failure before `cancelled` is set), then `ResultSet.cancel()`: the `cancelled` flag, then stop, cancel the operation and close the queue (`AppCancel`, `CancelStop`). `CancelOp` is optional: `close()` and a direct `ResultSet.cancel()` start at `AppCancel`; + - the reader's idle hook and its wait (`idleTried`). +- Over-approximations (safe, they only add behaviors): any step may open a reserved stream (the code opens it on the thread that reserved it, before that thread goes on); `AppExhaust` is allowed after a failure or cancel (the stream's `next()` would usually throw `CANCELLED` first); `PollerCrash` may hit the poller in any of `running`, `polling`, `received`, `backoff`; a started `Statement.cancel()` always reaches `ResultSet.cancel()` (fairness on `AppCancel`). +- Not tracked: the rows between `AppTake` and `AppExhaust`. Each `next()` call starts with the `cancelled` and `queue.failure()` checks, which the model treats as `AppThrow`, so `FailFast` only watches the hand-over of a stream. A row already buffered when cancel or a failure starts can still reach the application from a `next()` call that was already running (the next call throws). +- Not modeled, by design: the cleanup RPC that follows a failed poll (`afterFailure`: `cancel()` or `terminate()`, then `finishPollInfoOperation`; `CancelFlightInfo` has a 1 s timeout). The model has no time, so it cannot say how long a failure takes to reach the reader. It records the failure in the step that takes the answer, which is what `onPollFailed` now does. +- The model covers the poll-ahead path only. It does not cover `executeQuery`'s first poll, the `UNIMPLEMENTED` fallback, metadata calls, parameter upload, the timed first wait (`SQLTimeoutException`), the reader pool's size and the other results that share it (and the poller pool they share: a rejected start, resume or hand-back is a free choice, not a function of other results' load), `endpointExhausted` on a queue without an opener (it re-enqueues), a cancel during `executeQuery` before the `ResultSet` exists, the backoff timing, or the check of the `pollInfoPrefetch` value at connect (a connection property check, not a result action). The reader-side fallback of the first POC (`disablePollAhead`, `pollNextAvailable`, polling inside `next()`) no longer exists since `b19d8370a`: a rejected start leaves the poller orphaned instead. +- Answer validation (`validateAppendOnly`, schema change, no continuation to poll) and an interrupted backoff are not modeled as such. They all end the poller with a queue failure, which is `PollerCrash`. +- **The implementation corresponds to `EagerOpen = FALSE`** for continuations: a queue built with `maxOpen = pollInfoPrefetch`, which is at least 1 (`0` and values below `-1` are rejected at connect). **A complete first answer** (no continuation) **uses the unlimited eager queue** (`maxOpen = Integer.MAX_VALUE`, no poller, nothing to poll); the model does not cover that path, which has no background party. `EagerOpen = TRUE` is kept only to show the old finding. +- The first load (`populateData` -> `getNextEndpointStream(true, false)` -> `Q.nextAvailable`) is not a separate action. It runs the same `awaitNext` loop and only differs by returning null where `next()` would idle, wait or end. The model starts when `P.start()` has run: the poller is running on a pool thread, or orphaned because the pool rejected the task (`Init` chooses). The reader is at the top of that loop with `idleTried` false, which is also the state of a fresh `next()` call; every state after the first load is one the model reaches from there. + +## Coverage record + +Abbreviations, all under `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/`: **P** = `EndpointPoller.java`, **Q** = `utils/FlightEndpointDataQueue.java`, **R** = `ArrowFlightJdbcFlightStreamResultSet.java`, **O** = `client/PollInfoOperation.java`. + +Sync commit: `b19d8370a` (branch `bdx-645-pollinfo-poc`, rebased on apache/arrow-java `10c55b9c8`). The model matches the main code there, including the idle-flag fix (`IdleFix = TRUE`), the slot release on exhaustion, and the orphaned start. The main-code changes after `4b831553c` are `436156f29` and `b19d8370a` (see below); only the second one is a model change. + +The diff `2574a511c..b19d8370a` of the main code (commits `b618dbc14` and `c77fa206b` between them changed docs only) removed the first POC's reader-side polling: + +1. `EndpointPoller.start()` is `void`: `owned.set(true); handBack();`. Before, it returned false when the pool rejected the task, and the result set then dropped the poller (`poller = null`, `setResumeAction(null)`, `setIdleAction(null)`) and called `Q.disablePollAhead()`, which lifted the limit and cleared `moreExpected`, so `next()` polled by itself (`O.pollNextAvailable`, with `setMaxBackoffMillis`). All of that is deleted. A rejected start now leaves the poller orphaned (`orphaned` set, `Q.wakeReader()`), exactly like a rejected resume. Model: `Init` starts the poller `running` or `orphaned`, a free choice; `AppIdle`, `InlineExit` and `PollerApplyHandBack` are reused unchanged, as the code reuses `runInlineIfOrphaned` and `handBack`. The state space grows by about 4 percent (27,569 to 28,658 distinct states for `deferred-open` at `N=3`). +2. `R.loadNextPublishedEndpoint` has no `poller == null` polling branch: with no poller, no continuation was left after the first answer, so every endpoint was read (the result ends). `R.shouldPollAhead` no longer tests `pollInfoPrefetch > 0`: every progressive result with a continuation has a poller. `validatePollInfoPrefetch()` rejects `0` and anything below `-1` when the connection is created (not a model action). +3. New broken variant `rejectedStartUnused`: the old `start()` without its fallback, a rejected start leaves the poller stopped and unused while more endpoints are expected. `Terminates` catches it (TLC's trace has 4 steps: the application finishes the first endpoint, `AppIdle` finds the poller not orphaned and sets `idleTried`, `ReaderWait`; nobody ever wakes the reader). No safety rule sees it: `next()` hangs instead of returning wrong data. + +Earlier syncs: the diff `d7c3ed4ab..dadd45d8a` of the main code has two changes: the `idleTried = false` line in `awaitNext` (mirrored, see finding 1) and a rethrow of `queue.failure()` in `ResultSet.next()`'s `FlightRuntimeException` catch (not a model action: it only picks the exception thrown while the reader is blocked in a stream). + +The diff `dadd45d8a..4b831553c` of the main code (four files: **R**, **P**, **O**, **Q**) changed these behaviors. Findings 3 and 4 say what each one did to the model: + +1. A finished endpoint's slot is freed by `Q.endpointExhausted` when the application's own `stream.next()` returns false (model: `AppRead` split into `AppTake` and `AppExhaust`). +2. The first load uses `Q.nextAvailable` (waitForMore = false), so `executeQuery` does not wait for unpublished endpoints (no model change). +3. The queue is failed before the operation's blocking `cancel()` / `terminate()` (no model change). +4. A cancel that races a poll is recorded as the queue failure "Statement canceled" (model: `CancelOp`). +5. A failed queue is inert: `addEndpoints` is a no-op and `openReserved` stops opening (model: `ApplyQ`, `OpenReserved`, `ReadFree`). +6. Any `Throwable` on the poller fails the queue (model: `PollerCrash`). +7. The fallback path loops while a continuation remains (not modeled; the path was removed in `b19d8370a`, see above). + +Not a model action: `Thread.currentThread().interrupt()` before wrapping an `InterruptedException`, `volatile` on `R.poller`, and the new public `O.isCancelled()` (it is read by `mapContinuationFailure`, see `CancelOp`). + +Reviewed after the sync, not a model action: `436156f29` (`ArrowFlightConnection` shuts the poller pool down with `shutdown()` and a 2 s grace before `shutdownNow()`, so a poller's `CancelFlightInfo` is not interrupted). A rejected submit after the shutdown is already the free choice `ReaderResumeRejected`, and, per the commit message, the statements are closed (pollers stopped) before the pool goes. Checked against the code at `2574a511c`, whose main code differs from `4b831553c` only by this change, so the sync commit moved there. + +| Model action | Code at the sync commit | +| --- | --- | +| `Init` (`poller = running` or `orphaned`) | R `startPoller` -> P `start`: `owned.set(true)`, then `handBack` (`submit`, 10 attempts). Accepted: the task runs `drive(false)` on a pool thread (`running`). Rejected: `orphaned.set(true)`, `queue.wakeReader()` (`orphaned`), the state a rejected resume leaves. The reader then runs the poller inline from `AppIdle` when it would otherwise wait, and `handBack` re-submits it after an answer adds endpoints. Broken variant `rejectedStartUnused`: the poller is `unused` (the old `start()`: `owned.set(false)`, `STOPPED`, no fallback). | +| `PollerSend`, `PollerTake` | P `drive` -> O `pollOnce` -> `poll`. The poll runs on a pool thread, or on the reader's thread when run inline. | +| `PollerApplyBackoff`, `PollerApplyGo` | O `remember` (inside `pollOnce`: `validateAppendOnly`, new continuation), then R `appendEndpoints` -> Q `addEndpoints`; then P `drive`: `operation.backoff` (backoff) or the next loop iteration (go). On a failed queue Q `addEndpoints` returns at its `failure != null` check and changes nothing (`ApplyQ`, `FailedQueueInert`); P `drive` then stops at its loop-top check (`PollerSeesFail`). | +| `PollerApplyHandBack` | The same, run inline: P `drive(true)` after an answer that added endpoints calls `handBack` (`submit`, or orphaned again, the same step as in `start()`). | +| `PollerApplyFinish` | Q `addEndpoints(list, false)` and P `drive`: `FINISHED`, `onFinished`. | +| `PollerPause`, `PollerPauseEnd`, `PollerCheck` | Q `pauseIfFull` with P `drive`'s `onPaused` (paused flag and `owned.set(false)` under the lock). `PollerPauseEnd` and `PollerCheck` exist only for the broken variants. | +| `PollerSeesFail`, `PollerDrop` | P `drive`: the loop-top check and the check after `pollOnce`. | +| `BackoffElapses` | O `backoff` (cancellable wait), P `drive` `BACKOFF` state. | +| `OpenReserved`, `OpenFails` | Q `openReserved`, `register`, `releaseReservations`, `fail`. The `opening` count is `resv`. `openReserved` stops at `shutdown \|\| failure != null` and releases the rest, and `register` drops a stream opened after a failure or close: in both cases the reservation is released and no stream is registered (`OpenReserved` leaves `opened` unchanged once `failSeen` or `gated`). | +| `AppTake` | R `populateData` (first load: Q `nextAvailable`), `next` and `loadNextPublishedEndpoint` -> Q `awaitNext` returning a ready future (`ready != null`, after `throwIfFailed`). No slot changes: the stream stays in `openUnread` and `endpointsToClose`. | +| `AppExhaust` | R `next`: `currentEndpointData.getStream().next()` returned false, then R `endpointExhausted` -> Q `endpointExhausted` -> `onStreamFinished(finished)`: under the lock `endpointsToClose.remove`, `openUnread--`, `reserveSlotsLocked`, paused flag cleared (`ReadFree`); after the unlock `closeQuietly`, the resume action (`ReaderResume`), `openReserved`. Only R `next` calls it, on the application thread. | +| `AppReadEmpty` | Q `awaitNext` taking a `null` future (a stream that ended inside the pool task without rows) -> `onStreamFinished` (same locked step as `AppExhaust`). | +| `ReadFree` (the shared locked step) | Q `onStreamFinished`. On a failed or closed queue `pending` is empty (`fail()` and `close()` clear it), so it reserves nothing. | +| `ReaderResume`, `ReaderResumeRejected` | The resume action `onStreamFinished` runs after `lock.unlock()`: P `resume` (`owned` compare-and-set), `handBack` (`submit`, 10 attempts, then `orphaned.set(true)`, `wakeReader`). The rejected start is the same `handBack`, modeled in `Init`. A resume of an orphaned poller finds `owned` set and does nothing (`ReaderResume` leaves a poller that is not `paused` alone). | +| `AppIdle`, `InlineExit` | Q `awaitNext`'s idle hook -> P `runInlineIfOrphaned` (`drive(true)`), for a poller orphaned by a rejected start, resume or hand-back. `idleTried` is the local variable in `awaitNext`; it is cleared after a wait and after every consumed future (`AppReadEmpty`, `IdleFix`). | +| `ReaderWait` and the wakes (`WakeRd`) | Q `awaitNext` -> `awaitChange`; `signalAll` in `addEndpoints`, `register`, `releaseReservations`, `fail`, `close`, `wakeReader`. | +| `AppEnd` | Q `awaitNext` returning `null` (futures empty, pending empty, `opening == 0`, `!moreExpected`, under the lock), R `next` returning false. | +| `AppThrow` | Q `awaitNext` -> `checkOpen`, `throwIfFailed`; R `next` top-of-call checks of `cancelled` and `queue.failure()`. | +| `CancelOp` | `ArrowFlightStatement.cancel` and `ArrowFlightPreparedStatement.cancel`: `operation.cancel()` runs before `super.cancel()` reaches `R.cancel`. O `cancel` sets `cancelled`, cancels the gRPC context (an open poll ends `CANCELLED`, O `call` refuses new RPCs). | +| `AppCancel`, `CancelStop` | R `cancel` and `close`: `cancelled = true`; then P `stop`, O `cancel`, Q `close`. | +| `SrvAnswer` failure branch, `PollerTake` error branch | P `onPollFailed` -> `queue.fail(failureMapper.apply(e))` (R `mapContinuationFailure`), then `afterFailure` (not modeled). If the poller is not stopped and the queue is not closed yet, a poll that `CancelOp` ended is recorded as the failure "Statement canceled" (O `isCancelled`). If `stopped` or the queue is closed, `onPollFailed` returns without a failure (`PollerDrop`). | +| `PollerCrash` | P `runOnPool` and `runInlineIfOrphaned`: `catch (Throwable)` -> P `fail(Throwable)` -> Q `fail` (an `Error` is rethrown afterwards). Also P `drive`'s `queue.fail` for a sink `SQLException`, a missing continuation, and an interrupted backoff. | + +## When to use it + +Run it when a diff touches any covered file: + +```sh +git --no-pager diff --name-only b19d8370a..HEAD -- \ + flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java \ + flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java \ + flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java \ + 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 class that polls or opens streams on a background thread. Read the code diff itself with `git --no-pager diff b19d8370a..HEAD -- ` (or `git show`, or `rtk proxy git diff`): a hook may summarize plain `git diff` output. + +## How to check a change + +1. **Mirror the change in the model.** The model is a hand-written design model, so TLC cannot read Java. Use the coverage record to find the action that corresponds to the code you changed, and edit that action so it does what the new code does. Keep each atomic step in the model atomic in the code: a step under one lock, or one RPC answer, is one action. +2. **Run every check** (23 checks, about 35 seconds a run; needs Java 11+ and `tla2tools.jar` v1.7.4, found through `TLA2TOOLS` or the mise install path): + + ```sh + formal/pollinfo-poll-ahead/run.sh + N=4 formal/pollinfo-poll-ahead/run.sh + ``` + + The script exits 0 only when every line says `ok`. The design checks must pass. `finding-open-streams` fails on `OpenWithinLimit` by design: it is the old `EagerOpen = TRUE` proposal, which the implementation does not follow. `deferred-open` is the code as written, with `IdleFix = TRUE`, every safety rule and `Terminates`; it must pass. Every design check also covers the rejected start, because `Init` chooses between a running and an orphaned poller. Every broken variant must fail on its rule; they run with `IdleFix = TRUE` so the stale-idle bug cannot hide a variant that no longer fails. `staleIdle` is the exception: it runs with `IdleFix = FALSE` and must fail on `Terminates`. `openNotReserved` only fails from `N=4` on. `rejectedStartUnused` fails on `Terminates`. `lateRelease-old-rules` is the other exception, on purpose: it runs `lateRelease` against the rules that existed before `SlotFreedOnExhaust` and must pass, which records that the late release is invisible to them (finding 3). A variant that suddenly passes means the model lost the ability to catch that bug: fix the model before you trust any pass. +3. **Read any failure with the pstack `/statechart` skill** (type `/pstack:statechart`). Give it a copy of `PollAhead.tla` and a config with the failing rule, in a scratch folder outside the repo. It prints the shortest path to the violation as numbered steps in plain words. When the model passes, it can draw how a result moves between states. +4. **Decide whether it is a bug or a modeling error.** Replay the path against the real code, one model action per step: as a unit test with a scripted Flight SQL producer (see `PollingMockFlightSqlProducer` in the JDBC tests), or against the Go conformance server (branch `bdx-645-pollinfo-conformance-server` of `dremio-employees/helder.gregorio`). If the code does the same thing, it is a real bug: report it with the path in the code's words, and do not weaken the rule. If the code cannot take that path, the model is wrong: fix the action, and say what you fixed. +5. **When a behavior change is intended**, change the action and, if a rule no longer applies, change that rule in a separate commit that explains why. Add a broken variant (a new `Mutation` value plus a `check` line in `run.sh`) for any new rule, and confirm it fails. +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. Stale `idleTried`: `next()` could hang after a rejected resume (found by the model, fixed in `dadd45d8a`) + +`Terminates` failed on the model of the code at `d7c3ed4ab` (check `finding-stale-idle`, now the broken variant `staleIdle` with `IdleFix = FALSE`, which still fails). `FlightEndpointDataQueue.awaitNext` keeps a local `idleTried` flag. It set it when the idle hook returned false and cleared it only after a wait. If an endpoint finished between those two, the flag stayed set. Shortest path, with a limit of 2 (16 steps): + +1. The application has read the first endpoint. `awaitNext` finds nothing queued, `moreExpected` true. It calls the idle hook (`EndpointPoller.runInlineIfOrphaned`), which returns false because the poller is not orphaned, so `idleTried = true`. +2. Before the reader takes the lock again, the poller's open poll answers with two new endpoints. `addEndpoints` reserves both slots, `openReserved` registers the streams (futures not empty), and the poller pauses at the limit (`pauseIfFull`). +3. The reader takes the first new stream's future. It yields `null` (an endpoint with no rows). `onStreamFinished` frees a slot, clears the paused flag and runs the resume (`EndpointPoller.resume` -> `handBack`). The pool rejects the submit 10 times, so the poller is orphaned (`orphaned.set(true)`, `wakeReader()` on the reader's own thread, so nobody is waiting). +4. The second new stream also yields `null`. The loop reaches the empty-futures branch with nothing queued and `moreExpected` true. `!idleTried` is false, so the reader does not run the orphaned poller. It waits for a signal nobody will send. + +The path was narrow: the poller had to answer and register a stream inside the reader's few instructions between the idle hook and the next lock, the connection's poller pool had to reject a resume (all `pollInfoPollerThreads` busy with other results, or the pool shut down), and the new endpoints had to have no rows. When it happened, `next()` hung until `cancel()` or `close()`. + +Fix, in `dadd45d8a`: `awaitNext` sets `idleTried = false` right after `onStreamFinished(source)`. This is exactly `IdleFix = TRUE` (`AppReadEmpty` clears `idleTried`; `AppTake` returns to the application, where the local flag ends). Regression test: `rejectedResumeDuringTheIdleHookDoesNotStrandTheReader` in `FlightEndpointDataQueueDeferredOpenTest`. The same commit also makes `next()` rethrow `queue.failure()` before the CANCELLED mapping. That changes only which exception a blocked reader throws, not any model action. + +### 2. `finding-open-streams`: the first proposal (`EagerOpen = TRUE`, resolved) + +`OpenWithinLimit` fails for the proposal as first written. The limit is checked before a poll, but one answer can publish several endpoints, and their streams all open at once. With a limit of 2: one stream is open, the poller sends the continuation, and an answer with three endpoints opens two more, leaving three open streams. The implementation does not do this: `reserveSlotsLocked` opens only while fewer than `maxOpen` streams are open or opening (`EagerOpen = FALSE`, check `deferred-open`). + +### 3. Late slot release: found by a reviewer, not by the model checker (fixed in `4b831553c`) + +**What the code did** (`dadd45d8a`). When the application read a stream to its end, `ResultSet.next()` re-enqueued it (`enqueueEndpointData` -> `Q.enqueue`). A reader-pool task then ran `stream.next()`, got false and returned `null`, and the slot (`openUnread`) was freed only when a later `awaitNext` took that `null` future (`onStreamFinished`). Three consequences: + +- The slot of a finished stream stayed taken while the application read another one, because `awaitNext` takes the first completed future, whichever stream it belongs to. +- So the poller stayed paused, and pending endpoints stayed unopened, behind a stream nobody reads. With `pollInfoPrefetch = 2`, a finished stream plus the stream being read fill the window. +- The release needed a free thread in the connection's fixed-size reader pool, which every statement of the connection shares. A pool full of tasks blocked on slow streams of other results delays the release of an unrelated stream. + +**Why the model did not see it.** The old `AppRead` took a ready future and freed its slot in the same step, at hand-over, before the application read anything. That is not an over-approximation of the old code, it is a different point in time, and it was wrong in both directions: + +- Too tight: no state had "the application finished a stream, its slot is still taken", so the late release could not occur. +- Too loose: while the application held a stream the model had already freed its slot, so `Unread`, `Backpressure` and `OpenWithinLimit` ignored it. The model's poller could run one endpoint further ahead than the code's (`pauseIfFull` counts `openUnread`, which includes the stream being read), and the model's number of open streams, the one being read included, could reach `Limit + 1` without any rule noticing. + +No rule could have caught it, and none does: `lateRelease-old-rules` shows that the late-release model passes every rule that existed before this change, `Terminates` included. It is a progress problem (the poller is blocked by a stream that is already finished), not a safety or termination problem. + +**What the model does now.** `AppRead` is split into `AppTake` (hand-over, no slot change) and `AppExhaust` (the application's own `stream.next()` returned false, and the slot is freed under the lock in the same step, on the application thread). The held stream counts as unread and open, as `openUnread` does. The new rule `SlotFreedOnExhaust` says "no finished stream holds a slot while the application reads another one", which is the "poller is not blocked by an unrelated stream" property. The broken variant `lateRelease` reproduces the old code: `AppExhaust` only marks the stream as spent, and the slot is freed when `AppReadEmpty` takes its null future. It fails `SlotFreedOnExhaust` in 9 steps, with a limit of 2: + +1. The server publishes a second endpoint. The poller polls and the answer lists two endpoints. +2. The poller applies the answer, the second endpoint is reserved, and its stream is opened. Two streams are open: the limit. +3. The application takes the first stream (`AppTake`), reads it to the end (`AppExhaust`): its slot stays taken. +4. The reader takes the second stream's ready future first (`AppTake`, completion order) while the first stream's slot is still taken. The poller cannot prefetch anything while the application reads the second stream. + +**Limits of this check.** `SlotFreedOnExhaust` holds in the faithful model by the construction of `AppExhaust`: it guards the action against being split again, it does not look at Java. The code is guarded by Java tests such as `FlightEndpointDataQueueDeferredOpenTest.endpointExhaustedFreesTheSlotOnTheCallingThread`: after `endpointExhausted`, `openUnreadCount()` has dropped on the calling thread. The third consequence (the reader pool) is not modeled: pool threads and other results are not in the model, so no rule can say that a release depends on a free thread. + +### 4. The other review fixes in `4b831553c` + +None of these was found by TLC. Each row says what the model did about it. + +| Change | Model | Rule or variant | +| --- | --- | --- | +| 2. The first load does not wait for unpublished endpoints | None. The first load is the same `awaitNext` loop (see the scope section), and the model starts at its top. A first endpoint without rows leaves no stream, and the following `next()` does the waiting: states the model already has. | None. A "`executeQuery` does not block on the poller" rule would need time or an uncooperative server. | +| 3. The queue is failed before the blocking `cancel()` / `terminate()` | None. The model already records the failure in the step that takes the answer, so the old code was the one that did not match. The delay was bounded by the 1 s timeout of `cancelFlightInfoBestEffort`, a latency problem. | None, for the same reason: no time in the model. | +| 4. A cancel that races a poll is recorded as the failure "Statement canceled" | New action `CancelOp` (`PollInfoOperation.cancel()` before `ResultSet.cancel()`), `SrvAnswer` answers `CANCELLED` once `opCancelled`, and `PollerTake` records it as `failSeen` while `cancelled` is still false. Reachable (checked), and every rule holds: the reader throws either way, only the exception differs. | No new rule. `FailFast` and `CancelStopsPolling` hold with the extra step. | +| 5. A failed queue is inert | `ApplyQ` is a no-op once `failSeen`; `OpenReserved` registers nothing once `failSeen` or `gated`; `ReadFree` finds no pending endpoint after a failure or close (the model derives pending from `known - opened - resv`, so it is masked by `failSeen \/ gated`). | New rule `FailedQueueInert`, variant `applyAfterFail`. The check in `openReserved` is a `volatile` read outside the lock, so "no `DoGet` starts after a failure" is not a rule: a race window remains and only the locked part is atomic. | +| 6. Any `Throwable` on the poller fails the queue | New action `PollerCrash`. Before this, the model listed an `Error` killing the poller as not modeled. | Variant `errorNotReported`: an `Error` leaves the poller dead and the queue not failed, so `next()` waits forever (`Terminates`). The old code did exactly this for an `Error`. | +| 7. The fallback path loops while a continuation remains | None at the time: the path was outside the model. | None. Its old defect belonged to the class of `NoPrematureEnd`. The path was removed in `b19d8370a` (the rejected start is now an orphaned poller, which the model covers), so no follow-up remains. | + +No rule failed on the model of `4b831553c`: every line of `run.sh` says `ok` at `N=3` and `N=4`, and the design checks also pass with a limit of 1 and of 3. + +## Files + +- `formal/pollinfo-poll-ahead/PollAhead.tla`: the model, with the code map in its header. +- `formal/pollinfo-poll-ahead/run.sh`: all design checks and broken variants, with their expected results. Variants: `staleIdle`, `endWhenQueueEmpty`, `endIgnoresOpening`, `finishBeforeEnqueue`, `enqueueWholeList`, `reuseContinuation`, `readAfterFail`, `cancelIgnoresPoller`, `noLimit`, `openNotReserved`, `noBackoff`, `noWake`, `pauseNotAtomic`, `ownedClearedLate`, `noIdleHook`, `lateRelease`, `applyAfterFail`, `errorNotReported`, `rejectedStartUnused`, plus the gap check `lateRelease-old-rules`. 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"); diff --git a/bom/pom.xml b/bom/pom.xml index 1ad11264c2..dc53ad4d19 100644 --- a/bom/pom.xml +++ b/bom/pom.xml @@ -218,7 +218,7 @@ under the License. org.codehaus.mojo versions-maven-plugin - 2.25.1 + 2.25.2 diff --git a/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 diff --git a/compression/pom.xml b/compression/pom.xml index 5f3786bce0..220c3d3a87 100644 --- a/compression/pom.xml +++ b/compression/pom.xml @@ -55,12 +55,12 @@ under the License. com.github.luben zstd-jni - 1.5.7-26 + 1.5.7-28 at.yawk.lz4 lz4-java - 1.14.0 + 1.14.1 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-core/pom.xml b/flight/flight-core/pom.xml index 6e28679301..15e10e62db 100644 --- a/flight/flight-core/pom.xml +++ b/flight/flight-core/pom.xml @@ -133,7 +133,7 @@ under the License. com.google.api.grpc proto-google-common-protos - 2.81.0 + 2.82.0 test 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()); + } +} diff --git a/flight/flight-sql-jdbc-core/pom.xml b/flight/flight-sql-jdbc-core/pom.xml index f2a2d08816..f5abf537fb 100644 --- a/flight/flight-sql-jdbc-core/pom.xml +++ b/flight/flight-sql-jdbc-core/pom.xml @@ -94,6 +94,12 @@ under the License. protobuf-java + + com.fasterxml.jackson.core + jackson-databind + test + + org.hamcrest hamcrest diff --git a/flight/flight-sql-jdbc-core/src/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..2b778327c8 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java @@ -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<>(); @@ -104,12 +111,19 @@ 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); + config.validatePollInfoPrefetch(); + 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 +131,32 @@ 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()) + .withPollInfo(config.usePollInfo()) + .withDriverVersion(driverVersion) + .withOAuthConfiguration(config.getOauthConfiguration()) + .build(); } void reset() throws SQLException { @@ -192,6 +198,56 @@ 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 + * poller is run by the result set's reader inside {@code next()} instead. + */ + 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 of a progressive result; at least 1. */ + 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) { + // The statements were closed, so every poller is ending. One that failed the result on a + // deadline is still sending its CancelFlightInfo (bounded to 1 s): interrupting it now would + // drop the cancel, so give the pollers a moment before interrupting them. + executor.shutdown(); + if (!executor.awaitTermination(2, TimeUnit.SECONDS)) { + executor.shutdownNow(); + if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { + LOGGER.warn("PollFlightInfo poller threads did not terminate within 5 seconds"); + } + } + } + } + /** * Registers a new metadata ResultSet and assigns it a unique ID. Metadata ResultSets are those * created without an associated Statement. @@ -264,6 +320,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/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/ArrowFlightJdbcFlightStreamResultSet.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java index 2ab807e78f..a199cb3416 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java @@ -16,22 +16,26 @@ */ 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; +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; import org.apache.arrow.flight.FlightStream; import org.apache.arrow.util.AutoCloseables; import org.apache.arrow.vector.VectorSchemaRoot; @@ -51,7 +55,12 @@ public final class ArrowFlightJdbcFlightStreamResultSet extends ArrowFlightJdbcVectorSchemaRootResultSet { private final ArrowFlightConnection connection; - private final FlightInfo flightInfo; + private volatile FlightInfo flightInfo; + private final PollInfoOperation pollInfoOperation; + // Written by whichever party currently owns polling (the poller, or the reader inline). + private volatile int consumedEndpointCount; + private volatile EndpointPoller poller; + private int pollerQueryTimeoutSeconds; private CloseableEndpointStreamPair currentEndpointData; private FlightEndpointDataQueue flightEndpointDataQueue; private volatile boolean cancelled; @@ -73,7 +82,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(); + this.pollInfoOperation = activePollInfoOperation(statement); + } 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. */ @@ -89,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); } @@ -126,16 +149,32 @@ static ArrowFlightJdbcFlightStreamResultSet fromFlightInfo( return resultSet; } - private void loadNewQueue() { + // A progressive result that still has a continuation is polled in the background. + private boolean shouldPollAhead() { + return pollInfoOperation != null && pollInfoOperation.hasContinuation(); + } + + private void loadNewQueue(final boolean pollAhead) { + if (poller != null) { + poller.stop(); + poller = null; + } Optional.ofNullable(flightEndpointDataQueue).ifPresent(AutoCloseables::closeNoChecked); - flightEndpointDataQueue = createNewQueue(connection.getExecutorService()); + // Without a continuation 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 { if (currentEndpointData != null) { AutoCloseables.closeNoChecked(currentEndpointData); } - this.currentEndpointData = getNextEndpointStream(true); + // The first load must not wait for endpoints that were not published yet. + this.currentEndpointData = getNextEndpointStream(true, false); } @Override @@ -148,14 +187,35 @@ protected AvaticaResultSet execute() throws SQLException { } private void populateData() throws SQLException { - loadNewQueue(); - enqueueEndpointData( - flightEndpointDataQueue, connection.getClientHandler().getStreams(flightInfo)); - loadNewFlightStream(); - - // Ownership of the root will be passed onto the cursor. - if (currentEndpointData != null) { - populateDataForCurrentFlightStream(); + 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(); + // Ownership of the root will be passed onto the cursor. Without a stream yet, next() waits + // for the first endpoint that has rows. + if (currentEndpointData != null) { + populateDataForCurrentFlightStream(); + } + } catch (final SQLException | RuntimeException e) { + if (poller != null) { + poller.stop(); + } + try { + flightEndpointDataQueue.close(); + } catch (final Exception closeException) { + e.addSuppressed(closeException); + } + // No ResultSet will be returned to close an unfinished operation: end it here. + if (pollInfoOperation != null && !pollInfoOperation.isComplete()) { + pollInfoOperation.cancel(); + } + finishPollInfoOperation(); + throw e; } } @@ -182,8 +242,18 @@ 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) { - return false; + if (!loadNextPublishedEndpoint()) { + return false; + } } while (true) { final boolean hasNext = super.next(); @@ -207,17 +277,28 @@ public boolean next() throws SQLException { continue; } - enqueueEndpointData(currentEndpointData); + // The slot is freed here, on the application thread, not when a reader task later + // consumes the end of the stream. + final CloseableEndpointStreamPair exhausted = currentEndpointData; + currentEndpointData = null; + endpointExhausted(exhausted); } - currentEndpointData = getNextEndpointStream(false); + currentEndpointData = getNextEndpointStream(false, true); } catch (final FlightRuntimeException e) { // A concurrent statement.cancel() (or close) cancels in-flight FlightStreams, - // which surface here as CANCELLED. Normalize to Avatica's "Statement canceled". + // which surface here as CANCELLED. Normalize to Avatica's "Statement canceled". This wins + // over a failure recorded by a poll that the cancel ended. if ((cancelled || flightEndpointDataQueue.isClosed()) && e.status().code() == CallStatus.CANCELLED.code()) { throw AvaticaConnection.HELPER.createException("Statement canceled"); } + // A failed continuation poll cancels the open streams, which surface here as CANCELLED + // while the reader is blocked on one: report the recorded failure, not the cancel. + final SQLException recordedFailure = flightEndpointDataQueue.failure(); + if (recordedFailure != null) { + throw recordedFailure; + } throw e; } @@ -231,6 +312,10 @@ public boolean next() throws SQLException { throw AvaticaConnection.HELPER.createException("Statement canceled"); } + if (loadNextPublishedEndpoint()) { + continue; + } + if (statement != null && statement.isCloseOnCompletion()) { statement.close(); } @@ -242,6 +327,13 @@ public boolean next() throws SQLException { @Override protected void cancel() { cancelled = true; + if (poller != null) { + poller.stop(); + } + if (pollInfoOperation != null && !pollInfoOperation.isComplete()) { + pollInfoOperation.cancel(); + } + finishPollInfoOperation(); super.cancel(); final CloseableEndpointStreamPair currentEndpoint = this.currentEndpointData; if (currentEndpoint != null) { @@ -265,6 +357,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(); @@ -276,26 +371,59 @@ public synchronized void close() { } catch (final Exception e) { throw new RuntimeException(e); } finally { + if (pollInfoOperation != null && !pollInfoOperation.isComplete()) { + pollInfoOperation.cancel(); + } + finishPollInfoOperation(); super.close(); } } - private CloseableEndpointStreamPair getNextEndpointStream(final boolean canTimeout) - throws SQLException { + private CloseableEndpointStreamPair getNextEndpointStream( + final boolean canTimeout, final boolean waitForMore) 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 waitForMore + ? flightEndpointDataQueue.next(remainingTimeoutNanos, TimeUnit.NANOSECONDS) + : flightEndpointDataQueue.nextAvailable( + remainingTimeoutNanos, TimeUnit.NANOSECONDS); + } catch (SQLTimeoutException e) { + if (statement != null && e.getMessage().startsWith("Query timed out after")) { + final SQLTimeoutException jdbcTimeout = + new SQLTimeoutException( + String.format( + "Query timed out after %d %s", + statement.getQueryTimeout(), TimeUnit.SECONDS)); + jdbcTimeout.initCause(e); + throw jdbcTimeout; + } + throw e; + } + } } + return waitForMore ? flightEndpointDataQueue.next() : flightEndpointDataQueue.nextAvailable(); } 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) @@ -314,10 +442,10 @@ static void enqueueEndpointData( } } - private void enqueueEndpointData(final CloseableEndpointStreamPair endpointRequest) + private void endpointExhausted(final CloseableEndpointStreamPair endpointRequest) throws SQLException { try { - flightEndpointDataQueue.enqueue(endpointRequest); + flightEndpointDataQueue.endpointExhausted(endpointRequest); } catch (final IllegalStateException e) { throw normalizeClosedQueueException(flightEndpointDataQueue, e); } @@ -339,4 +467,121 @@ private static SQLException normalizeClosedQueueException( } throw exception; } + + 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::endPollInfoOperationAfterFailure, + this::finishPollInfoOperation, + connection.getPollInfoMaxBackoffMs()); + flightEndpointDataQueue.setResumeAction(newPoller::resume); + flightEndpointDataQueue.setIdleAction(newPoller::runInlineIfOrphaned); + poller = newPoller; + // A busy poller pool leaves the poller orphaned: the reader runs it inline when it would wait. + newPoller.start(); + } + + /** Records the endpoints a poll answer appended, and whether more may follow, in one step. */ + 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"); + } + final Schema updatedSchema = updatedFlightInfo.getSchemaOptional().orElse(schema); + if (schema != null && updatedSchema != null && !schema.equals(updatedSchema)) { + throw new SQLException("PollInfo changed the result schema"); + } + final List appendedEndpoints = + new ArrayList<>( + updatedFlightInfo.getEndpoints().subList(consumedEndpointCount, updatedEndpointCount)); + 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) { + // A cancel that ended this poll is not a failure: Statement.cancel() cancels the operation + // before ResultSet.cancel() raises the flag, so the poller can get here first. + if (pollInfoOperation.isCancelled()) { + return AvaticaConnection.HELPER.createException("Statement canceled"); + } + 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); + } + + // Runs after the queue recorded the failure, because cancel() is a blocking RPC. + private void endPollInfoOperationAfterFailure(final FlightRuntimeException e) { + if (e.status().code() == FlightStatusCode.CANCELLED + || e.status().code() == FlightStatusCode.TIMED_OUT) { + pollInfoOperation.cancel(); + } else { + pollInfoOperation.terminate(); + } + finishPollInfoOperation(); + } + + private boolean loadNextPublishedEndpoint() throws SQLException { + if (poller == null) { + // No continuation was left after the first answer: every endpoint was read. + finishPollInfoOperation(); + return false; + } + // The queue is the single source of truth. It waits while more may arrive, and null means every + // endpoint was read and the poller finished. + try { + currentEndpointData = getNextEndpointStream(false, true); + } catch (final FlightRuntimeException e) { + if ((cancelled || flightEndpointDataQueue.isClosed()) + && e.status().code() == CallStatus.CANCELLED.code()) { + throw AvaticaConnection.HELPER.createException("Statement canceled"); + } + throw e; + } + if (currentEndpointData != null) { + populateDataForCurrentFlightStream(); + return true; + } + if (cancelled || flightEndpointDataQueue.isClosed()) { + throw AvaticaConnection.HELPER.createException("Statement canceled"); + } + finishPollInfoOperation(); + return false; + } + + 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 30878ad8b9..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 @@ -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,52 @@ ExecuteBatchResult executeBatchWithTypedValues( @Override public FlightInfo executeFlightInfoQuery() throws SQLException { ensurePrepared(); - return preparedStatement.executeQuery(); + final PollInfoOperation operation = new PollInfoOperation(getQueryTimeout(), true); + activeOperation.set(operation); + lastOperation = operation; + try { + final FlightInfo flightInfo = preparedStatement.executeQuery(operation); + if (!operation.hasContinuation()) { + finishPollInfoOperation(operation); + } + return flightInfo; + } catch (RuntimeException | SQLException e) { + finishPollInfoOperation(operation); + throw e; + } + } + + @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(); + } + } + + PollInfoOperation activePollInfoOperation() { + return activeOperation.get(); + } + + void finishPollInfoOperation(final PollInfoOperation operation) { + if (operation != null && activeOperation.compareAndSet(operation, null)) { + operation.close(); + } } 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..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 @@ -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,72 @@ 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(), true); + activeOperation.set(operation); + lastOperation = operation; + final FlightInfo flightInfo; + try { + flightInfo = connection.getClientHandler().getInfo(signature.sql, operation); + if (!operation.hasContinuation()) { + finishPollInfoOperation(operation); + } + } catch (RuntimeException e) { + finishPollInfoOperation(operation); + throw e; + } 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; + } + + 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 + ? (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/EndpointPoller.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java new file mode 100644 index 0000000000..1a2b74bc4d --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java @@ -0,0 +1,287 @@ +/* + * 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.Consumer; +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 the pool is busy + * when the poller starts or resumes, the poller is orphaned: the reader runs it inline when it + * would otherwise wait for more endpoints, and hands it back to the pool after an answer adds + * endpoints. + */ +final class EndpointPoller { + private static final Logger LOGGER = LoggerFactory.getLogger(EndpointPoller.class); + 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 Consumer afterFailure; + 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 Consumer afterFailure, + final Runnable onFinished, + final long maxBackoffMillis) { + this.queue = queue; + this.operation = operation; + this.executor = executor; + this.sink = sink; + this.failureMapper = failureMapper; + this.afterFailure = afterFailure; + this.onFinished = onFinished; + this.backoff = new PollBackoff(maxBackoffMillis); + } + + State state() { + return state; + } + + /** + * Starts polling on the executor. If the pool rejects the task, the poller is orphaned: the + * reader runs it inline when it would otherwise wait for more endpoints. + */ + void start() { + owned.set(true); + handBack(); + } + + /** 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 Throwable t) { + fail(t); + if (t instanceof Error) { + throw (Error) t; + } + } + 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 Throwable t) { + // Whatever ends the poller must reach the reader, or next() would wait forever. + fail(t); + if (t instanceof Error) { + throw (Error) t; + } + } + } + + 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; + // The queue fails first, so the reader sees the failure at once; the cleanup (a blocking + // CancelFlightInfo RPC) follows. + queue.fail(failureMapper.apply(e)); + afterFailure.accept(e); + } + + private void fail(final Throwable e) { + LOGGER.debug("PollFlightInfo poller failed unexpectedly", e); + state = State.FAILED; + queue.fail(new SQLException("Continuation PollFlightInfo failed", e)); + } +} diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java index 97108e599b..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 @@ -17,6 +17,9 @@ 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; import java.io.IOException; @@ -32,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; @@ -40,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; @@ -50,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; @@ -120,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; } @@ -148,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 { @@ -269,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. * @@ -279,6 +308,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. * @@ -291,6 +337,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 +358,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); - } } /** @@ -382,6 +433,14 @@ public interface PreparedStatement extends AutoCloseable { */ FlightInfo executeQuery() 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. * @@ -479,6 +538,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()); @@ -675,6 +744,135 @@ 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)) { + 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 PollInfo pollInfo = operation.poll(descriptor); + operation.remember(pollInfo); + if (operation.isComplete() + || (operation.isProgressive() + && !pollInfo.getFlightInfo().getEndpoints().isEmpty())) { + return pollInfo.getFlightInfo(); + } + descriptor = operation.continuationDescriptor(); + initialPoll = false; + } + } catch (FlightRuntimeException e) { + if (initialPoll && e.status().code() == FlightStatusCode.UNIMPLEMENTED) { + unsupportedFamilies.add(family); + final FlightInfo flightInfo = + operation.call(() -> client.getInfo(originalDescriptor, operation.options(options))); + operation.complete(flightInfo); + return flightInfo; + } + 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"; @@ -721,6 +919,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 @@ -764,6 +964,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; @@ -1079,6 +1280,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. * @@ -1125,6 +1332,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 +1400,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 +1436,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/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 new file mode 100644 index 0000000000..8f7e8dac75 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java @@ -0,0 +1,297 @@ +/* + * 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.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; +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 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 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 CountDownLatch cancelLatch = new CountDownLatch(1); + 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(); + } + + /** 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); + cancelLatch.countDown(); + context.cancel(null); + final Runnable cleanup = cancelFlightInfo; + if (cleanup != null) { + cleanup.run(); + } + } + + /** Whether {@link #cancel()} was called, by the statement, the deadline handling or close. */ + public boolean isCancelled() { + return cancelled.get(); + } + + 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 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; + } + + 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); + } + + /** 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; + } + + 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/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..2879e277ad 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java @@ -37,6 +37,8 @@ /** A {@link ConnectionConfig} for the {@link ArrowFlightConnection}. */ public final class ArrowFlightConnectionConfigImpl extends ConnectionConfigImpl { + private static final int POLL_INFO_PREFETCH_AUTO = -1; + public ArrowFlightConnectionConfigImpl(final Properties properties) { super(properties); } @@ -206,6 +208,49 @@ 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); + } + + /** + * Most queued, unread endpoints during progressive PollFlightInfo execution. {@code -1} (the + * default) means auto: {@code max(2, threadPoolSize)}; a positive value is the limit. The value + * is checked when the connection is created, see {@link #validatePollInfoPrefetch()}. + */ + public int pollInfoPrefetch() { + final int configured = ArrowFlightConnectionProperty.POLL_INFO_PREFETCH.getInteger(properties); + return configured == POLL_INFO_PREFETCH_AUTO ? Math.max(2, threadPoolSize()) : configured; + } + + /** + * Checks the {@code pollInfoPrefetch} property: {@code -1} (auto) or a positive number. Zero and + * anything below {@code -1} are rejected, because a progressive result always polls ahead. + * + * @throws SQLException if the value is not allowed. + */ + public void validatePollInfoPrefetch() throws SQLException { + final int configured = ArrowFlightConnectionProperty.POLL_INFO_PREFETCH.getInteger(properties); + if (configured != POLL_INFO_PREFETCH_AUTO && configured < 1) { + throw new SQLException( + String.format( + "Invalid pollInfoPrefetch value %d: use -1 (auto) or a positive number of endpoints.", + configured)); + } + } + + /** Size of the connection's pool of background PollFlightInfo pollers. */ + 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}. * @@ -292,6 +337,10 @@ 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), + 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..f729e7b895 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java @@ -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,44 +135,476 @@ 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(); + } } - private CloseableEndpointStreamPair next(final EndpointStreamSupplier endpointStreamSupplier) + /** 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 { - checkOpen(); - while (!futures.isEmpty()) { - final Future future = endpointStreamSupplier.get(); - futures.remove(future); + checkState(opener != null, "This queue has no endpoint opener"); + final List toOpen; + lock.lock(); + try { + checkOpen(); + if (failure != null) { + // Fail fast: nothing is queued or opened after a failure; the reader rethrows it. + return; + } + pending.addAll(endpoints); + this.moreExpected = moreExpected; + toOpen = reserveSlotsLocked(); + 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 { - final CloseableEndpointStreamPair endpoint = future.get(); - // Get the next FlightStream that has a root with content. - if (endpoint != null) { - return endpoint; + 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, or once the queue failed or closed, the + // reservations that were not handed to register() are released, even for an Error. + private void openReserved(final List reserved) throws SQLException { + int settled = 0; + try { + while (settled < reserved.size()) { + if (shutdown || failure != null) { + return; + } + final CloseableEndpointStreamPair stream; + try { + stream = opener.open(reserved.get(settled)); + } catch (final SQLException | RuntimeException e) { + final SQLException cause = + e instanceof SQLException ? (SQLException) e : new SQLException(e); + fail(cause); + throw cause; + } + // From here register() settles this endpoint's reservation, even when it throws. + settled++; + try { + register(stream); + } catch (final RuntimeException e) { + fail(new SQLException("Failed to start reading an endpoint stream", e)); + throw e; + } + } + } finally { + if (settled < reserved.size()) { + releaseReservations(reserved.size() - settled); + } + } + } + + 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 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 application read an endpoint's stream to its end. Frees the endpoint's slot at once, on the + * calling thread, under the queue lock: the open-unread count drops, the stream is closed, + * pending endpoints open, and a paused poller resumes. Nothing is re-enqueued, so a slot does not + * wait for a reader task or for the completion order of other endpoints. + * + * @param finished the stream the application just exhausted; it is closed here. + * @throws SQLException if opening a pending endpoint fails; the queue is then failed with it. + */ + public void endpointExhausted(final CloseableEndpointStreamPair finished) throws SQLException { + checkNotNull(finished); + if (opener == null) { + // A queue without an opener has no slots; the reader task consumes the end of the stream. + enqueue(finished); + return; + } + onStreamFinished(finished); + } + + // The reader finished an endpoint: free its slot, open pending endpoints, and wake the poller. + private void onStreamFinished(final CloseableEndpointStreamPair finished) throws SQLException { + final List toOpen; + 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, + final boolean waitForMore) + throws SQLException { + final long deadlineNanos = timed ? System.nanoTime() + timeoutUnit.toNanos(timeoutValue) : 0L; + boolean idleTried = false; + while (true) { + boolean runIdle = false; + BooleanSupplier idle = null; + lock.lock(); + try { + checkOpen(); + throwIfFailed(); + if (futures.isEmpty()) { + final boolean nothingQueued = pending.isEmpty() && opening == 0; + if (nothingQueued && (!moreExpected || !waitForMore)) { + 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) { throw (FlightRuntimeException) cause; } throw AvaticaConnection.HELPER.wrap(e.getMessage(), e); - } catch (InterruptedException | CancellationException e) { + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + throw AvaticaConnection.HELPER.wrap(e.getMessage(), e); + } catch (final CancellationException e) { throw AvaticaConnection.HELPER.wrap(e.getMessage(), e); } + // Get the next FlightStream that has a root with content. + if (ready != null) { + throwIfFailed(); + 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; + } + } + + // 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) { + Thread.currentThread().interrupt(); + 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) { + Thread.currentThread().interrupt(); + 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 +616,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, true); } /** @@ -153,18 +625,28 @@ 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, true); + } + + /** + * Like {@link #next(long, TimeUnit)}, but returns {@code null} instead of waiting for endpoints + * that were not published yet: it waits only while a queued endpoint may still produce a batch. + * The first load of a result uses it, so that {@code executeQuery} does not wait for the poller. + * + * @return a FlightStream that is ready to consume, or null if no queued endpoint is left. + */ + public CloseableEndpointStreamPair nextAvailable( + final long timeoutValue, final TimeUnit timeoutUnit) throws SQLException { + return awaitNext(true, timeoutValue, timeoutUnit, false); + } + + /** Untimed variant of {@link #nextAvailable(long, TimeUnit)}. */ + public CloseableEndpointStreamPair nextAvailable() throws SQLException { + return awaitNext(false, 0L, TimeUnit.NANOSECONDS, false); } /** Checks if this queue is open. */ - public synchronized void checkOpen() { + public void checkOpen() { checkState(!isClosed(), format("%s closed", this.getClass().getSimpleName())); } @@ -174,21 +656,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 +675,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/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/EndpointPollerTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/EndpointPollerTest.java new file mode 100644 index 0000000000..e1893590aa --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/EndpointPollerTest.java @@ -0,0 +1,125 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.arrow.driver.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.sql.SQLException; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.apache.arrow.driver.jdbc.client.PollInfoOperation; +import org.apache.arrow.driver.jdbc.utils.FlightEndpointDataQueue; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +/** Tests how {@link EndpointPoller} ends: whatever stops the poller must reach the reader. */ +@Timeout(60) +public class EndpointPollerTest { + private static final long WAIT_MS = 10_000; + + private ExecutorService readers; + private ExecutorService pollerPool; + + @BeforeEach + public void setUp() { + readers = Executors.newCachedThreadPool(daemonThreads()); + // An Error escapes the pool task by design; keep it out of the test output. + pollerPool = Executors.newCachedThreadPool(daemonThreads()); + } + + @AfterEach + public void tearDown() { + readers.shutdownNow(); + pollerPool.shutdownNow(); + } + + private static ThreadFactory daemonThreads() { + return runnable -> { + final Thread thread = new Thread(runnable, "endpoint-poller-test"); + thread.setDaemon(true); + thread.setUncaughtExceptionHandler((t, e) -> {}); + return thread; + }; + } + + // F2. An Error on the poller thread used to leave next() waiting forever. + @Test + public void anErrorOnThePollerThreadFailsTheQueueInsteadOfHangingTheReader() throws Exception { + final StackOverflowError error = new StackOverflowError("scripted"); + final PollInfoOperation operation = mock(PollInfoOperation.class); + when(operation.pollOnce()).thenThrow(error); + try (FlightEndpointDataQueue queue = + FlightEndpointDataQueue.createNewQueue( + readers, + 2, + endpoint -> { + throw new AssertionError("no endpoint is expected"); + })) { + queue.addEndpoints(Collections.emptyList(), true); + final EndpointPoller poller = + new EndpointPoller( + queue, + operation, + pollerPool, + answer -> {}, + exception -> new SQLException(exception), + exception -> {}, + () -> {}, + 100); + poller.start(); + + final CompletableFuture next = new CompletableFuture<>(); + final Thread reader = + new Thread( + () -> { + try { + next.complete(queue.next()); + } catch (final Throwable t) { + next.completeExceptionally(t); + } + }); + reader.setDaemon(true); + reader.start(); + + final ExecutionException thrown; + try { + next.get(WAIT_MS, TimeUnit.MILLISECONDS); + throw new AssertionError("next() returned instead of failing"); + } catch (final TimeoutException e) { + throw new AssertionError("next() hung after an Error on the poller thread", e); + } catch (final ExecutionException e) { + thrown = e; + } + final SQLException failure = assertInstanceOf(SQLException.class, thrown.getCause()); + assertEquals("Continuation PollFlightInfo failed", failure.getMessage()); + assertSame(error, failure.getCause()); + assertEquals(EndpointPoller.State.FAILED, poller.state()); + } + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/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/PollAheadTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java new file mode 100644 index 0000000000..b0e2b86fea --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java @@ -0,0 +1,1189 @@ +/* + * 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 java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.LockSupport; +import java.util.stream.Collectors; +import org.apache.arrow.driver.jdbc.utils.PollingMockFlightSqlProducer; +import org.apache.arrow.driver.jdbc.utils.ScriptedPollQuery; +import org.apache.arrow.driver.jdbc.utils.ScriptedPollQuery.Answer; +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 long POLL_PARK_NANOS = TimeUnit.MILLISECONDS.toNanos(1); + + 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()); + // An answer that adds endpoints is followed at once: no wait after answers 0 and 3. The + // shortest backoff wait is 100 ms, so anything below that is no wait at all. + assertGapBetween(polls, 0, 1, 0, 100); + assertGapBetween(polls, 3, 4, 0, 100); + // Answers 1 and 2 are empty: waits of 100 ms, then 200 ms. + assertGapBetween(polls, 1, 2, 100, 1500); + assertGapBetween(polls, 2, 3, 200, 1500); + // After answer 4 (empty, after an answer that added endpoints) the wait starts at 100 ms + // again, not at 400 ms. + assertGapBetween(polls, 4, 5, 100, 350); + } + + // 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. Uncapped they would be + // 100, 200 and 400 ms, so only the last gap tells the cap from no cap. + assertGapBetween(polls, 1, 2, 100, 350); + assertGapBetween(polls, 2, 3, 150, 350); + assertGapBetween(polls, 3, 4, 150, 350); + } + + // 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 { + // The failing answer waits for the test, so that the first next() cannot race it. + final CountDownLatch failNow = new CountDownLatch(1); + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.fail().gatedBy(failNow)) + .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)); + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + failNow.countDown(); + // fail() records the failure first and then cancels every open stream. + assertTrue(script.awaitStream(EventType.DOGET_CANCELLED, 0, WAIT_MS)); + assertTrue(script.awaitStream(EventType.DOGET_CANCELLED, 1, WAIT_MS)); + + // 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)); + } + 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 (it ended on the server) and now waits for the done answer. + // awaitBlocked cannot tell the queue wait from a read blocked in FlightStream.next(); + // either way, releasing the gate must deliver both final endpoints. + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + assertTrue(script.awaitStream(EventType.DOGET_END, 0, WAIT_MS)); + reader.awaitBlocked(); + 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()); + } + + // Decision: an answer with no continuation opens every endpoint at once, as the driver always + // did. + @Test + public void completeFirstAnswerOpensEveryEndpointEagerly() throws Exception { + final ScriptedPollQuery script = scripted(Answer.done(4)).holdAllEnds(4); + 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()); + } + + // pollInfoPrefetch is -1 (auto) or positive: a progressive result always polls ahead. + @ParameterizedTest + @ValueSource(strings = {"0", "-2", "-100"}) + public void anInvalidPollInfoPrefetchIsRejectedWhenTheConnectionIsCreated(final String value) { + final SQLException failure = + assertThrows(SQLException.class, () -> connect("pollInfoPrefetch=" + value)); + assertEquals( + "Invalid pollInfoPrefetch value " + + value + + ": use -1 (auto) or a positive number of endpoints.", + failure.getMessage()); + } + + // 11. Poller pool busy: the second result's poller starts orphaned and the reader runs it inline. + @Test + public void busyPollerPoolMakesTheReaderRunTheSecondResultsPollerInline() throws Exception { + final CountDownLatch releaseA = new CountDownLatch(1); + final CountDownLatch releaseB = new CountDownLatch(1); + final ScriptedPollQuery scriptA = + scripted(Answer.endpoints(1), Answer.endpoints(1).gatedBy(releaseA), Answer.done(1)); + final ScriptedPollQuery scriptB = + scripted(Answer.endpoints(1), Answer.endpoints(1).gatedBy(releaseB), Answer.done(1)) + .holdEnd(0); + try (Connection connection = connect("pollInfoPollerThreads=1&pollInfoPrefetch=2"); + Statement statementA = connection.createStatement(); + Statement statementB = connection.createStatement()) { + 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's poller has no thread. It is orphaned: nobody polls C1 while the reader still has + // an open stream to read. + assertFalse(scriptB.awaitPollCount(2, QUIET_MS), "B polled ahead without a poller"); + + try (AsyncReader reader = new AsyncReader(() -> readAll(resultSetB))) { + scriptB.releaseEnd(0); + // The reader has nothing left to read, so it polls C1 itself, on its own thread, while + // A's poller still holds the pool thread inside A's C1. + assertTrue(scriptB.awaitBlockedPoll(WAIT_MS), "B's C1 was never polled"); + assertEquals(2, scriptB.pollCount()); + assertEquals(2, scriptA.pollCount(), "A's poller moved on"); + assertEquals( + 1, + connection.unwrap(ArrowFlightConnection.class).getPollerExecutor().getActiveCount(), + "B's poll must not be running on the pool"); + assertTrue( + reader.isInside("runInlineIfOrphaned"), "B's poll is not made by the reader"); + + releaseB.countDown(); + // Every poll of B ran inline: the pool stayed busy with A the whole time. + assertEquals(List.of(100, 200), reader.rows()); + } + assertEquals(List.of(0, 1, 2), scriptB.pollIndices()); + } + assertEquals(2, scriptA.pollCount()); + + releaseA.countDown(); + assertEquals(List.of(0, 100, 200), sorted(readAll(resultSetA))); + } + } + } + + // 11b. The orphaned poller goes back to the pool once an inline answer finds it free again. + @Test + public void anOrphanedStartIsHandedBackToThePoolWhenItFreesUp() throws Exception { + final CountDownLatch releaseA = new CountDownLatch(1); + final CountDownLatch releaseB1 = new CountDownLatch(1); + final CountDownLatch releaseB2 = new CountDownLatch(1); + final ScriptedPollQuery scriptA = + scripted(Answer.endpoints(1), Answer.endpoints(1).gatedBy(releaseA), Answer.done(1)); + final ScriptedPollQuery scriptB = + scripted( + Answer.endpoints(1), + Answer.endpoints(1).gatedBy(releaseB1), + Answer.endpoints(1).gatedBy(releaseB2), + Answer.done(1)); + try (Connection connection = connect("pollInfoPollerThreads=1&pollInfoPrefetch=2"); + Statement statementA = connection.createStatement(); + Statement statementB = connection.createStatement(); + ResultSet resultSetA = statementA.executeQuery(scriptA.query())) { + assertTrue(scriptA.awaitBlockedPoll(WAIT_MS)); + try (ResultSet resultSetB = statementB.executeQuery(scriptB.query())) { + assertTrue(resultSetB.next()); + assertEquals(0, resultSetB.getInt(1)); + try (AsyncReader reader = new AsyncReader(() -> readAll(resultSetB))) { + // The reader polls B's C1 inline, because the pool is busy with A. + assertTrue(scriptB.awaitBlockedPoll(WAIT_MS)); + assertTrue(reader.isInside("runInlineIfOrphaned")); + + // Let A finish, which frees the pool thread, then answer B's C1. + releaseA.countDown(); + assertEquals(List.of(0, 100, 200), sorted(readAllWithin(resultSetA))); + awaitPollerPoolIdle(connection); + releaseB1.countDown(); + + // The answer added an endpoint, so the poller went back to the pool: C2 is polled by a + // pool thread, not by the reader. + assertTrue(scriptB.awaitPollCount(3, WAIT_MS), "B's C2 was never polled"); + assertEquals( + 1, + connection.unwrap(ArrowFlightConnection.class).getPollerExecutor().getActiveCount(), + "B's poller was not handed back to the pool"); + releaseB2.countDown(); + assertEquals(List.of(100, 200, 300), sorted(reader.rows())); + } + } + } + } + + // 13. Orphaned poller: a resume finds the pool busy; the reader runs the poller inline. + @Test + public void anOrphanedPollerIsRunInlineByTheReader() throws Exception { + 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. + @Test + public void queryTimeoutEndsAtAReadBoundary() throws Exception { + final ScriptedPollQuery script = scripted(Answer.endpoints(1), Answer.hang()); + final long startNanos = System.nanoTime(); + try (Connection connection = connect("pollInfoPrefetch=2"); + 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()); + // The deadline cancels the operation once; closing the result must not cancel again. + assertTrue( + script.awaitCancelFlightInfo(1, WAIT_MS), "the deadline sent no CancelFlightInfo"); + } + } + final long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); + assertTrue(elapsedMillis >= 850, "the deadline fired too early: " + elapsedMillis); + assertTrue(script.awaitPollTerminated(WAIT_MS)); + assertFalse(script.awaitCancelFlightInfo(2, QUIET_MS)); + assertEquals(2, script.pollCount()); + assertEquals(1, script.cancelFlightInfoCount()); + } + + // Decision: a schema change fails the queue as a plain SQLException. + @Test + public void schemaChangeFailsTheResultAsAPlainSqlException() throws Exception { + final CountDownLatch changeNow = new CountDownLatch(1); + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.schemaChange().gatedBy(changeNow)).rowsPerEndpoint(2); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + changeNow.countDown(); + final SQLException failure = assertThrows(SQLException.class, () -> readAllWithin(resultSet)); + assertEquals(SQLException.class, failure.getClass()); + assertEquals("PollInfo changed the result schema", failure.getMessage()); + } + } + + // F1. A finished endpoint frees its slot when the application finishes it, not when a reader + // task later consumes the end of the stream. + @Test + public void steadyStateOverlapPollsWhileTheNextEndpointIsStillUnread() throws Exception { + // E0 is held after its row, so E1's batch is ready (and its future completed) before the + // application finishes E0. Completion order would hand E1 to the application first and keep + // E0's slot until E1 was fully read. + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.endpoints(1), Answer.done(0)) + .holdEnd(0) + .holdEnd(1) + .holdStart(1); + final List rows = new ArrayList<>(); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertEquals(0, resultSet.getInt(1)); + rows.add(0); + assertTrue(script.awaitPollCount(2, WAIT_MS)); + assertFalse(script.awaitPollCount(3, QUIET_MS), "polled past the limit"); + + script.releaseStart(1); + assertTrue(script.awaitStream(EventType.BATCH_SENT, 1, WAIT_MS)); + // Let the client's reader task receive E1's batch. + Thread.sleep(QUIET_MS); + + try (AsyncReader reader = + new AsyncReader(() -> List.of(resultSet.next() ? resultSet.getInt(1) : -1))) { + script.releaseEnd(0); + rows.addAll(reader.rows()); + } + // The application is now reading E1 (unread, still held on the server) and has not asked for + // more: finishing E0 alone must have resumed the poller. + assertTrue(script.awaitPollCount(3, WAIT_MS), "C2 waited for the application to go idle"); + assertFalse(script.hasEvent(EventType.DOGET_END, 1)); + + script.releaseEnd(1); + rows.addAll(readAll(resultSet)); + } + assertEquals(List.of(0, 100, 200), sorted(rows)); + assertEquals(List.of(0, 1, 2, 3), script.pollIndices()); + } + + @Test + public void singleReaderThreadStillFreesAFinishedEndpointsSlot() throws Exception { + // threadPoolSize=1: E1's reader task, held before its first batch, occupies the only reader + // thread, so a marker task for the finished E0 could never run. + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.endpoints(1), Answer.done(0)) + .holdStart(1); + final List rows = new ArrayList<>(); + try (Connection connection = connect(1, "pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertEquals(0, resultSet.getInt(1)); + rows.add(0); + assertTrue(script.awaitPollCount(2, WAIT_MS)); + assertFalse(script.awaitPollCount(3, QUIET_MS), "polled past the limit"); + + try (AsyncReader reader = + new AsyncReader(() -> List.of(resultSet.next() ? resultSet.getInt(1) : -1))) { + // E0 is done: its slot is freed on the application thread and the poller polls C2, while + // the application waits for E1 and the only reader thread is stuck on E1. + assertTrue( + script.awaitPollCount(3, WAIT_MS), "the slot of a finished endpoint stayed held"); + reader.awaitBlocked(); + script.releaseStart(1); + rows.addAll(reader.rows()); + } + rows.addAll(readAll(resultSet)); + } + assertEquals(List.of(0, 100, 200), sorted(rows)); + assertEquals(List.of(0, 1, 2, 3), script.pollIndices()); + } + + // F3. executeQuery returns once the first endpoint exists; it does not wait for later ones. + @Test + public void executeQueryDoesNotWaitForFutureEndpointsWhenTheFirstHasNoRows() throws Exception { + final CountDownLatch gate = new CountDownLatch(1); + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.done(1).gatedBy(gate)).emptyEndpoints(0); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement()) { + final AtomicReference opened = new AtomicReference<>(); + try (AsyncReader execute = + new AsyncReader( + () -> { + opened.set(statement.executeQuery(script.query())); + return List.of(); + })) { + execute.rows(); + } + try (ResultSet resultSet = opened.get(); + AsyncReader reader = new AsyncReader(() -> readAll(resultSet))) { + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + reader.awaitBlocked(); + gate.countDown(); + assertEquals(List.of(100), reader.rows()); + } + } + } + + // F3, held first stream: the first batch is enough; executeQuery does not wait for the stream to + // end or for the continuation. + @Test + public void executeQueryReturnsWhileTheFirstStreamIsHeldAfterItsFirstBatch() throws Exception { + final ScriptedPollQuery script = scripted(Answer.endpoints(1), Answer.hang()).holdEnd(0); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement()) { + final AtomicReference opened = new AtomicReference<>(); + try (AsyncReader execute = + new AsyncReader( + () -> { + opened.set(statement.executeQuery(script.query())); + return List.of(); + })) { + execute.rows(); + } + try (ResultSet resultSet = opened.get()) { + assertTrue(resultSet.next()); + assertEquals(0, resultSet.getInt(1)); + } + } + } + + // F4. An endpoint without rows must not end the result while a continuation remains. + @Test + public void anEndpointWithoutRowsDoesNotEndTheResultWhileAContinuationRemains() throws Exception { + final CountDownLatch gate = new CountDownLatch(1); + // E1 has no rows and is the last endpoint published until the gated done answer arrives. + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.done(1).gatedBy(gate)) + .emptyEndpoints(1); + 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(() -> readAll(resultSet))) { + // E0 and E1 are read to their end; only the unanswered poll of the continuation is left. + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + assertTrue(script.awaitStream(EventType.DOGET_END, 1, WAIT_MS)); + reader.awaitBlocked(); + assertFalse(reader.isDone(), "the result ended while a continuation remained"); + gate.countDown(); + assertEquals(List.of(200), reader.rows()); + } + } + assertEquals(List.of(0, 1, 2), script.pollIndices()); + } + + // F5. A cancel that races a poll in flight reports "Statement canceled", not a poll failure. + @Test + public void cancelRacingAPollInFlightReportsStatementCanceled() throws Exception { + // The server holds its CancelFlightInfo answer, so Statement.cancel() is still inside + // operation.cancel() (before ResultSet.cancel() raises its flag) when the poll ends. + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.hang()).holdCancelFlightInfo(); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + try (AsyncReader reader = new AsyncReader(() -> readAll(resultSet)); + AsyncReader canceller = + new AsyncReader( + () -> { + statement.cancel(); + return List.of(); + }, + false)) { + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + reader.awaitBlocked(); + canceller.start(); + final SQLException failure = reader.failure(); + assertTrue(failure.getMessage().contains("Statement canceled"), failure.getMessage()); + script.releaseCancelFlightInfo(); + canceller.rows(); + } finally { + script.releaseCancelFlightInfo(); + } + } + } + + // S2. Backoff against cancel, deadline and close. Six empty answers after the first endpoint: + // the waits are 100, 200, 400, 800 and then 1600 ms (cap 5000 ms), so once poll 5 arrived the + // poller sleeps for another 1.6 s, much longer than anything asserted below. + private static ScriptedPollQuery backingOff() { + return scripted( + Answer.endpoints(1), + Answer.empty(), + Answer.empty(), + Answer.empty(), + Answer.empty(), + Answer.empty(), + Answer.empty(), + Answer.empty()) + .rowsPerEndpoint(2); + } + + // Returns once the poller sleeps in the long backoff wait that follows poll 5. The server only + // sees a poll arrive, so the answer and the start of the wait are given a moment: a cancel that + // came during the RPC would end the poll, not the wait, and prove nothing about the backoff. + private static void awaitBackoffWait(final ScriptedPollQuery script, final Connection connection) + throws Exception { + assertTrue(script.awaitPollCount(6, WAIT_MS)); + Thread.sleep(QUIET_MS); + assertEquals( + 1, + connection.unwrap(ArrowFlightConnection.class).getPollerExecutor().getActiveCount(), + "the poller is not waiting in its backoff"); + assertEquals(6, script.pollCount(), "the poller polled again before the wait ended"); + } + + @Test + public void cancelDuringABackoffWaitEndsItAndSendsNoMorePolls() throws Exception { + final ScriptedPollQuery script = backingOff(); + try (Connection connection = connect("pollInfoPrefetch=2&pollInfoMaxBackoffMs=5000"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + awaitBackoffWait(script, connection); + final long cancelNanos = System.nanoTime(); + statement.cancel(); + final SQLException canceled = assertThrows(SQLException.class, resultSet::next); + assertTrue(canceled.getMessage().contains("Statement canceled"), canceled.getMessage()); + // Cancel ends the wait: the poller leaves its thread long before the 1.6 s are over. + awaitPollerPoolIdle(connection, 1000); + assertTrue( + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - cancelNanos) < 1000, + "the backoff wait outlived the cancel"); + assertTrue(script.awaitCancelFlightInfo(1, WAIT_MS)); + assertFalse(script.awaitCancelFlightInfo(2, QUIET_MS)); + } + assertEquals(6, script.pollCount()); + assertEquals(1, script.cancelFlightInfoCount()); + } + + @Test + public void closeDuringABackoffWaitReturnsPromptlyAndSendsNoMorePolls() throws Exception { + final ScriptedPollQuery script = backingOff(); + try (Connection connection = connect("pollInfoPrefetch=2&pollInfoMaxBackoffMs=5000")) { + final Statement statement = connection.createStatement(); + final ResultSet resultSet = statement.executeQuery(script.query()); + assertTrue(resultSet.next()); + awaitBackoffWait(script, connection); + final long closeNanos = System.nanoTime(); + resultSet.close(); + statement.close(); + assertTrue( + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - closeNanos) < 1000, + "close waited for the backoff"); + // The close ends the wait itself (it cancels the operation); nothing interrupts the poller. + awaitPollerPoolIdle(connection, 1000); + assertTrue(script.awaitCancelFlightInfo(1, WAIT_MS)); + assertFalse(script.awaitCancelFlightInfo(2, QUIET_MS)); + } + assertEquals(6, script.pollCount()); + assertEquals(1, script.cancelFlightInfoCount()); + } + + @Test + public void theDeadlineEndsABackoffWaitAndSendsOneCancelFlightInfo() throws Exception { + final ScriptedPollQuery script = backingOff(); + try (Connection connection = connect("pollInfoPrefetch=2&pollInfoMaxBackoffMs=5000"); + Statement statement = connection.createStatement()) { + statement.setQueryTimeout(1); + final long startNanos = System.nanoTime(); + try (ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertTrue(resultSet.next()); + final SQLTimeoutException timeout = + assertThrows(SQLTimeoutException.class, resultSet::next); + final long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); + assertEquals("Query timed out after 1 SECONDS", timeout.getMessage()); + assertInstanceOf(FlightRuntimeException.class, timeout.getCause()); + assertEquals( + FlightStatusCode.TIMED_OUT, + ((FlightRuntimeException) timeout.getCause()).status().code()); + // The polls are at 0, 0, 100, 300 and 700 ms; the wait after the last one is cut to the + // deadline (1000 ms) instead of 800 ms, so the next poll is not at 1500 ms. + assertTrue(elapsedMillis >= 850, "the deadline fired too early: " + elapsedMillis); + assertTrue(elapsedMillis < 1400, "the wait ran past the deadline: " + elapsedMillis); + assertTrue( + script.awaitCancelFlightInfo(1, WAIT_MS), "the deadline sent no CancelFlightInfo"); + } + assertFalse(script.awaitCancelFlightInfo(2, QUIET_MS)); + } + assertEquals(1, script.cancelFlightInfoCount()); + } + + // S6. Append-only violations fail the result and cancel the open streams. + @Test + public void anAnswerWithFewerEndpointsFailsTheResultAndCancelsTheStreams() throws Exception { + final CountDownLatch breakNow = new CountDownLatch(1); + final ScriptedPollQuery script = + scripted(Answer.endpoints(2), Answer.shrink().gatedBy(breakNow)) + .rowsPerEndpoint(2) + .holdAllEnds(2); + assertAppendOnlyViolation(script, breakNow, "PollInfo removed previously published endpoints"); + } + + @Test + public void anAnswerWithAChangedTicketFailsTheResultAndCancelsTheStreams() throws Exception { + final CountDownLatch breakNow = new CountDownLatch(1); + final ScriptedPollQuery script = + scripted(Answer.endpoints(2), Answer.changedTicket().gatedBy(breakNow)) + .rowsPerEndpoint(2) + .holdAllEnds(2); + assertAppendOnlyViolation(script, breakNow, "PollInfo mutated previously published endpoint 0"); + } + + private static void assertAppendOnlyViolation( + final ScriptedPollQuery script, final CountDownLatch breakNow, final String description) + throws Exception { + try (Connection connection = connect("pollInfoPrefetch=4"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + assertTrue(script.awaitDoGetStarted(2, WAIT_MS)); + breakNow.countDown(); + assertTrue(script.awaitStream(EventType.DOGET_CANCELLED, 0, WAIT_MS)); + assertTrue(script.awaitStream(EventType.DOGET_CANCELLED, 1, WAIT_MS)); + final SQLException failure = assertThrows(SQLException.class, resultSet::next); + assertEquals(SQLException.class, failure.getClass()); + assertEquals("Continuation PollFlightInfo failed", failure.getMessage()); + assertInstanceOf(FlightRuntimeException.class, failure.getCause()); + final FlightRuntimeException cause = (FlightRuntimeException) failure.getCause(); + assertEquals(FlightStatusCode.INTERNAL, cause.status().code()); + assertEquals(description, cause.status().description()); + } + assertFalse(script.hasEvent(EventType.DOGET_END, 0)); + assertFalse(script.hasEvent(EventType.DOGET_END, 1)); + } + + // Mock fidelity: endpoints that name a location (the server itself, or "reuse the connection") + // take the single-endpoint open path that resolves locations. + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void endpointsWithLocationsAreOpenedAndRead(final boolean reuseConnection) + throws Exception { + final Location location = reuseConnection ? Location.reuseConnection() : server.getLocation(); + final ScriptedPollQuery script = + scripted(Answer.endpoints(2), Answer.empty(), Answer.done(1)) + .endpointLocations(location) + .rowsPerEndpoint(2); + final List rows; + try (Connection connection = connect("pollInfoPrefetch=2&pollInfoMaxBackoffMs=20"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + rows = readAll(resultSet); + } + assertEquals(List.of(0, 1, 100, 101, 200, 201), sorted(rows)); + assertEquals(3, script.doGetStarted()); + assertEquals(List.of(0, 1, 2), script.pollIndices()); + } + + // Mock fidelity: streams with several batches and an empty batch in front of the data. The next + // batch of an endpoint must not free its slot; the end of its stream must. + @Test + public void multiBatchStreamsWithAnEmptyLeadingBatchAreReadInOrder() throws Exception { + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.done(1)) + .rowsPerEndpoint(2) + .batchesPerEndpoint(3) + .leadingEmptyBatch(); + final List rows; + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + rows = readAll(resultSet); + } + assertEquals( + List.of(0, 1, 2, 3, 4, 5, 100, 101, 102, 103, 104, 105, 200, 201, 202, 203, 204, 205), + sorted(rows)); + for (int endpoint = 0; endpoint < 3; endpoint++) { + final int first = endpoint * 100; + assertEquals( + List.of(first, first + 1, first + 2, first + 3, first + 4, first + 5), + rows.stream().filter(row -> row / 100 == first / 100).collect(Collectors.toList()), + "the batches of endpoint " + endpoint + " arrived out of order"); + } + assertEquals(List.of(0, 1, 2), script.pollIndices()); + assertTrue(script.maxOpenStreams() <= 2); + } + + // Reproduction of a dropped CancelFlightInfo: the poller records the failure first and sends + // the (blocking) cancel after it, so a connection that is closed as soon as next() threw used + // to interrupt the cancel before it reached the server. + @Test + public void closingRightAfterTheDeadlineFailureStillSendsTheCancelFlightInfo() throws Exception { + final ScriptedPollQuery script = scripted(Answer.endpoints(1), Answer.hang()); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement()) { + statement.setQueryTimeout(1); + try (ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertThrows(SQLTimeoutException.class, resultSet::next); + } + } + assertTrue(script.awaitCancelFlightInfo(1, WAIT_MS), "the CancelFlightInfo was dropped"); + assertFalse(script.awaitCancelFlightInfo(2, QUIET_MS)); + assertEquals(1, script.cancelFlightInfoCount()); + } + + // ---- helpers ---------------------------------------------------------------------------- + + private static ScriptedPollQuery scripted(final Answer... answers) { + 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 connect(4, properties); + } + + private static Connection connect(final int threadPoolSize, final String properties) + throws SQLException { + return DriverManager.getConnection( + String.format( + "jdbc:arrow-flight-sql://localhost:%d?useEncryption=false&usePollInfo=true" + + "&threadPoolSize=%d&%s", + server.getPort(), threadPoolSize, 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 { + awaitPollerPoolIdle(connection, WAIT_MS); + } + + private static void awaitPollerPoolIdle(final Connection connection, final long millis) + throws Exception { + final ThreadPoolExecutor pool = + connection.unwrap(ArrowFlightConnection.class).getPollerExecutor(); + final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(millis); + while (pool.getActiveCount() > 0) { + assertTrue( + System.nanoTime() < deadline, "the poller pool was not idle within " + millis + " ms"); + LockSupport.parkNanos(POLL_PARK_NANOS); + } + } + + /** 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) { + this(call, true); + } + + /** With {@code start} false, the thread runs only once {@link #start()} is called. */ + AsyncReader(final Callable call, final boolean start) { + thread = + new Thread( + () -> { + 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); + if (start) { + thread.start(); + } + } + + void start() { + thread.start(); + } + + boolean isDone() { + return result.isDone(); + } + + /** Whether the thread's stack is inside a method with this name, e.g. a poll made inline. */ + boolean isInside(final String methodName) { + for (final StackTraceElement frame : thread.getStackTrace()) { + if (frame.getMethodName().equals(methodName)) { + return true; + } + } + return false; + } + + @SuppressWarnings("unchecked") + private static List castList(final Object value) { + return (List) value; + } + + /** + * Waits until the thread is parked, i.e. blocked inside the driver. It cannot tell the cause: a + * reader blocked in {@code FlightStream.next()} looks the same as one waiting in the queue. + * Tests that need one of the two pin it with server state (held or gated streams and polls). + */ + void awaitBlocked() throws InterruptedException { + final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(WAIT_MS); + while (thread.getState() != Thread.State.WAITING + && thread.getState() != Thread.State.TIMED_WAITING) { + assertTrue(System.nanoTime() < deadline, "the reader never blocked"); + assertFalse(result.isDone(), "the reader finished instead of blocking"); + LockSupport.parkNanos(POLL_PARK_NANOS); + } + } + + 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/PollInfoExecutionTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java new file mode 100644 index 0000000000..87ce5f4ee0 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java @@ -0,0 +1,468 @@ +/* + * 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.SQLException; +import java.sql.SQLTimeoutException; +import java.sql.Statement; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +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 multiStepSendsEachContinuationOnceAndInOrder() 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()); + 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 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); + 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)); + assertFalse(resultSet.next()); + } + } + 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); + // The background poller would otherwise fail before or after the first next(); the failing + // answer waits until the first row was read. + producer.holdContinuationFailure(); + try (Connection connection = connect(true); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { + assertTrue(resultSet.next()); + assertEquals(42, resultSet.getInt(1)); + assertTrue(producer.awaitActivePoll(5, TimeUnit.SECONDS), "the poller never polled C1"); + producer.releaseContinuationFailure(); + final SQLException failure = assertThrows(SQLException.class, resultSet::next); + assertEquals(SQLException.class, failure.getClass()); + assertEquals("Continuation PollFlightInfo failed", failure.getMessage()); + assertTrue(failure.getCause() instanceof FlightRuntimeException, failure.toString()); + assertEquals( + FlightStatusCode.UNIMPLEMENTED, + ((FlightRuntimeException) failure.getCause()).status().code()); + } finally { + producer.releaseContinuationFailure(); + } + assertEquals(2, producer.pollDescriptors().size()); + assertEquals(0, producer.getFlightInfoCount()); + } + + @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); + 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); + 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 statementCancelInterruptsContinuationAtReadBoundary() 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 CountDownLatch firstRowRead = new CountDownLatch(1); + final Thread execution = + new Thread( + () -> { + try (ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { + resultSetCreated.set(true); + if (!resultSet.next() || resultSet.getInt(1) != 42) { + throw new AssertionError("missing published row"); + } + firstRowRead.countDown(); + resultSet.next(); + } catch (Throwable e) { + failure.set(e); + } + }, + "jdbc-pollinfo-cancellation-test"); + execution.start(); + // The background poller polls C1 as soon as the result exists; cancel once the application + // is waiting for more endpoints. + assertTrue(firstRowRead.await(5, TimeUnit.SECONDS), "the first row was never read"); + assertTrue(producer.awaitActivePoll(2, TimeUnit.SECONDS)); + assertNotNull(statement.getResultSet()); + final long cancelStart = System.nanoTime(); + 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()); + assertTrue(resultSetCreated.get(), "ResultSet should expose the first published endpoint"); + assertNotNull(failure.get()); + assertTrue(failure.get() instanceof SQLException, failure.get().toString()); + assertTrue( + failure.get().getMessage().contains("Statement canceled"), failure.get().toString()); + assertTrue(cancelMillis < 1000, "cancellation was not prompt: " + cancelMillis); + assertTrue(producer.awaitPollTerminated(1, TimeUnit.SECONDS)); + assertEquals(1, producer.cancelFlightInfoCount()); + 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/SharedServerLock.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerLock.java new file mode 100644 index 0000000000..3165b8949c --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerLock.java @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.arrow.driver.jdbc; + +import java.io.IOException; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.channels.OverlappingFileLockException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.LockSupport; + +/** + * A cross-JVM lock that serializes the test classes sharing the one standalone conformance server. + * + *

    The root POM runs Surefire with several reused forks, and every shared-server class resets the + * server and asserts its global counters, so two classes running in two forks would corrupt each + * other. A class takes the lock in {@code @BeforeAll} and releases it in {@code @AfterAll}. The + * lock file lives in {@code java.io.tmpdir} (Surefire points it at {@code target/}), named after + * the control port, so every fork of one build agrees on it. + */ +final class SharedServerLock implements AutoCloseable { + private static final long TIMEOUT_MINUTES = 10; + private static final long RETRY_PARK_NANOS = TimeUnit.MILLISECONDS.toNanos(50); + + private final FileChannel channel; + private final FileLock lock; + + private SharedServerLock(final FileChannel channel, final FileLock lock) { + this.channel = channel; + this.lock = lock; + } + + /** Blocks until no other class, in this JVM or another, holds the lock for {@code port}. */ + static SharedServerLock acquire(final int controlPort) throws IOException { + final Path file = + Paths.get(System.getProperty("java.io.tmpdir"), "pollinfo-shared-server-" + controlPort) + .toAbsolutePath(); + Files.createDirectories(file.getParent()); + final FileChannel channel = + FileChannel.open(file, StandardOpenOption.CREATE, StandardOpenOption.WRITE); + final long deadline = System.nanoTime() + TimeUnit.MINUTES.toNanos(TIMEOUT_MINUTES); + try { + while (true) { + try { + final FileLock lock = channel.tryLock(); + if (lock != null) { + return new SharedServerLock(channel, lock); + } + } catch (final OverlappingFileLockException e) { + // Held by another class of this JVM: wait like for another process. + } + if (System.nanoTime() > deadline) { + throw new IOException( + "Timed out waiting for the shared conformance server lock: " + file); + } + LockSupport.parkNanos(RETRY_PARK_NANOS); + } + } catch (final IOException | RuntimeException e) { + channel.close(); + throw e; + } + } + + @Override + public void close() throws IOException { + try { + lock.release(); + } finally { + channel.close(); + } + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollAheadTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollAheadTest.java new file mode 100644 index 0000000000..520cf926ab --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollAheadTest.java @@ -0,0 +1,623 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.arrow.driver.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import org.apache.arrow.flight.FlightRuntimeException; +import org.apache.arrow.flight.FlightStatusCode; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +/** + * End-to-end poll-ahead checks (BDX-645) against the standalone conformance server. The assertions + * are on what the server observed: stream concurrency, the order of polls relative to held streams, + * the gaps between polls, and which streams were cancelled. + * + *

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

    Every shared-server class resets the server and asserts its global counters, so two of them + * must never run at once. Surefire runs several forks, hence each class holds the cross-JVM {@link + * SharedServerLock} from {@code @BeforeAll} to {@code @AfterAll} and leaves the server reset. + */ +@EnabledIfSystemProperty(named = "pollinfo.shared.enabled", matches = "true") +public class SharedServerPollAheadTest { + private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); + private static final ObjectMapper JSON = new ObjectMapper(); + private static final int FLIGHT_PORT = Integer.getInteger("pollinfo.shared.flightPort", 32347); + private static final int CONTROL_PORT = Integer.getInteger("pollinfo.shared.controlPort", 32348); + private static final Duration WAIT = Duration.ofSeconds(10); + // Negative assertions ("nothing happens") hold for this long while /state is polled. + private static final Duration QUIET = Duration.ofMillis(400); + private static final String CONTINUATION = "continuation"; + + private static SharedServerLock serverLock; + + private ExecutorService background; + + @BeforeAll + public static void lockServer() throws Exception { + serverLock = SharedServerLock.acquire(CONTROL_PORT); + } + + @AfterAll + public static void resetAndUnlockServer() throws Exception { + try { + awaitUntil("no open streams before reset", () -> counter("do_get_active") == 0); + post("/reset", ""); + } finally { + serverLock.close(); + } + } + + @BeforeEach + public void resetServer() throws Exception { + background = + Executors.newCachedThreadPool( + runnable -> { + final Thread thread = new Thread(runnable, "shared-server-poll-ahead"); + thread.setDaemon(true); + return thread; + }); + // The previous test closed its connections; wait until the server saw its streams end, because + // /reset must not run with streams open. + awaitUntil("no open streams before reset", () -> counter("do_get_active") == 0); + post("/reset", ""); + } + + @AfterEach + public void printServerState(final TestInfo testInfo) throws Exception { + background.shutdownNow(); + System.out.println("SHARED_SERVER_STATE " + testInfo.getDisplayName()); + System.out.println(state()); + } + + @Test + public void burstDeliversAllRowsWithinThePrefetchLimit() throws Exception { + final List rows; + try (Connection connection = connect(true, "pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("burst")) { + rows = values(resultSet, "burst"); + } + assertEquals(range(1, 8), sorted(rows)); + awaitUntil("streams ended", () -> counter("do_get_active") == 0); + assertTrue(counter("do_get_max_concurrent") <= 2, state()); + assertEquals(4, counter("do_get"), state()); + assertEquals(List.of("1", "2"), continuationOrderSuffixes()); + assertEquals(2, continuationPolls().size()); + assertEquals(0, counter("get_flight_info")); + assertEquals(0, counter("cancellation")); + } + + @Test + public void heldStreamsNeverExceedThePrefetchLimit() throws Exception { + for (int endpoint = 1; endpoint <= 4; endpoint++) { + post("/hold", "{\"endpoint\":" + endpoint + "}"); + } + try (Connection connection = connect(true, "pollInfoPrefetch=2"); + Statement statement = connection.createStatement()) { + final Future execution = executeAsync(statement, "burst"); + awaitUntil("E1 held", () -> hasHold(1, "held")); + awaitUntil("E2 held", () -> hasHold(2, "held")); + // Four endpoints are known and three streams could be opened, but only two may be. + awaitUntil("C1 polled", () -> continuationPolls().size() >= 1); + assertQuiet( + "a third stream opened at the limit", + () -> counter("do_get") == 2 && counter("do_get_max_concurrent") == 2); + for (int endpoint = 1; endpoint <= 4; endpoint++) { + post("/release-endpoint", "{\"endpoint\":" + endpoint + "}"); + } + try (ResultSet resultSet = result(execution)) { + assertEquals(range(1, 8), sorted(values(resultSet, "burst"))); + } + } + awaitUntil("streams ended", () -> counter("do_get_active") == 0); + assertEquals(2, counter("do_get_max_concurrent"), state()); + assertEquals(4, counter("do_get"), state()); + } + + @Test + public void continuationIsPolledWhileTheFirstStreamIsStillHeld() throws Exception { + post("/hold", "{\"endpoint\":1}"); + try (Connection connection = connect(true, "pollInfoPrefetch=2"); + Statement statement = connection.createStatement()) { + final Future execution = executeAsync(statement, "burst"); + awaitUntil("E1 held", () -> hasHold(1, "held")); + awaitUntil("C1 polled", () -> continuationPolls().size() >= 1); + assertTrue( + events("DoGet.end").stream().noneMatch(event -> event.path("endpoint").asInt() == 1), + "E1 must still be open: " + state()); + post("/release-endpoint", "{\"endpoint\":1}"); + try (ResultSet resultSet = result(execution)) { + assertEquals(range(1, 8), sorted(values(resultSet, "burst"))); + } + } + final long firstContinuationPoll = continuationPolls().get(0).path("sequence").asLong(); + final JsonNode endOfFirstStream = single(events("DoGet.end"), 1); + assertTrue( + firstContinuationPoll < endOfFirstStream.path("sequence").asLong(), + "C1 must be polled before E1 ends: " + state()); + } + + @Test + public void trickleStopsPollingAtTheLimitAndResumesAfterTheStreamsAreReleased() throws Exception { + post("/hold", "{\"endpoint\":1}"); + post("/hold", "{\"endpoint\":2}"); + final List rows; + try (Connection connection = connect(true, "pollInfoPrefetch=2"); + Statement statement = connection.createStatement()) { + final Future execution = executeAsync(statement, "trickle"); + awaitUntil("E1 held", () -> hasHold(1, "held")); + awaitUntil("E2 held", () -> hasHold(2, "held")); + // E1 and E2 are queued and unread, so C2 must not be polled. + assertQuiet( + "polled past the limit", + () -> continuationPolls().size() == 1 && counter("do_get_max_concurrent") == 2); + post("/release-endpoint", "{\"endpoint\":1}"); + post("/release-endpoint", "{\"endpoint\":2}"); + try (ResultSet resultSet = result(execution)) { + rows = values(resultSet, "trickle"); + } + } + assertEquals(range(1, 12), sorted(rows)); + assertEquals(List.of("1", "2", "3", "4", "5"), continuationOrderSuffixes()); + assertEquals(5, continuationPolls().size()); + final long lastRelease = + events("control.release-endpoint").stream() + .mapToLong(event -> event.path("sequence").asLong()) + .max() + .orElseThrow(); + assertTrue( + continuationPolls().get(1).path("sequence").asLong() > lastRelease, + "C2 was polled before the held endpoints were released: " + state()); + assertTrue(counter("do_get_max_concurrent") <= 2, state()); + } + + @Test + public void emptyAnswersBackOffExponentiallyUpToTheCap() throws Exception { + final List rows; + try (Connection connection = connect(true, "pollInfoMaxBackoffMs=250"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("empty-answers")) { + rows = values(resultSet, "empty-answers"); + } + assertEquals(range(1, 4), sorted(rows)); + final List polls = continuationPolls(); + assertEquals(4, polls.size(), state()); + final long gap1 = gapMillis(polls.get(0), polls.get(1)); + final long gap2 = gapMillis(polls.get(1), polls.get(2)); + final long gap3 = gapMillis(polls.get(2), polls.get(3)); + System.out.printf("SHARED_BACKOFF_GAPS_MILLIS %d %d %d%n", gap1, gap2, gap3); + // Lower bounds are the configured delays (with a little slack); the upper bounds are generous, + // except that the third gap must show the cap: 400 ms uncapped, 250 ms capped, so 350 ms + // leaves 100 ms of headroom above the cap and 50 ms below the uncapped wait. + assertTrue(gap1 >= 90 && gap1 < 1000, "gap1=" + gap1); + assertTrue(gap2 >= 180 && gap2 < 1000, "gap2=" + gap2); + assertTrue(gap3 >= 225 && gap3 < 350, "gap3=" + gap3); + } + + @Test + public void lateFailureCancelsTheBufferedStreamsAndSurfacesFromNext() throws Exception { + post("/hold", "{\"endpoint\":1}"); + post("/hold", "{\"endpoint\":2}"); + // The failing poll (the second continuation) is held, so the failure cannot be recorded + // before executeQuery returns: it must surface from next(). + holdPoll(2); + try (Connection connection = connect(true, ""); + Statement statement = connection.createStatement()) { + final Future execution = executeAsync(statement, "late-error-buffered"); + try (ResultSet resultSet = result(execution)) { + awaitUntil("E1 held", () -> hasHold(1, "held")); + awaitUntil("E2 held", () -> hasHold(2, "held")); + awaitUntil("C2 held", () -> hasPollHold(2, "held")); + releasePoll(2); + // The failure cancels every buffered stream by itself, before anything is read or closed. + awaitUntil("E1 cancelled", () -> hasEnd(1, "cancelled")); + awaitUntil("E2 cancelled", () -> hasEnd(2, "cancelled")); + + final SQLException failure = assertThrows(SQLException.class, resultSet::next); + assertContinuationFailure(failure); + // The failure is sticky, and no row is delivered. + assertContinuationFailure(assertThrows(SQLException.class, resultSet::next)); + } + } + awaitUntil("streams ended", () -> counter("do_get_active") == 0); + final List ends = events("DoGet.end"); + assertTrue( + ends.stream().noneMatch(event -> "completed".equals(event.path("outcome").asText())), + "no stream may complete: " + state()); + assertFalse(hasHold(1, "released"), state()); + assertFalse(hasHold(2, "released"), state()); + assertTrue(hasPollHold(2, "released"), state()); + assertEquals(2, continuationPolls().size(), state()); + // The server already ended the query, so the driver sends no CancelFlightInfo. + assertEquals(0, counter("cancellation"), state()); + } + + // The driver's own failure for a continuation the server failed: the exact class, the message, + // and the server's status as the cause. + private static void assertContinuationFailure(final SQLException failure) { + assertEquals(SQLException.class, failure.getClass()); + assertEquals("Continuation PollFlightInfo failed", failure.getMessage()); + assertTrue(failure.getCause() instanceof FlightRuntimeException, failure.toString()); + final FlightRuntimeException cause = (FlightRuntimeException) failure.getCause(); + assertEquals(FlightStatusCode.INTERNAL, cause.status().code()); + assertTrue( + String.valueOf(cause.status().description()).contains("deterministic late query failure"), + cause.toString()); + } + + @Test + public void cancelWhileAPollIsOpenSendsNoMorePollsAndOneCancelFlightInfo() throws Exception { + // burst: [E1]+C1, then [E1..E4]+C2; the poll of C2 is held, so four endpoints are readable + // while a poll is open. A prefetch above 4 keeps the poller polling. + holdPoll(2); + try (Connection connection = connect(true, "pollInfoPrefetch=8"); + Statement statement = connection.createStatement()) { + final Future execution = executeAsync(statement, "burst"); + try (ResultSet resultSet = result(execution)) { + awaitUntil("C2 poll held", () -> hasPollHold(2, "held")); + final List rows = new ArrayList<>(); + for (int row = 0; row < 4; row++) { + assertTrue(resultSet.next()); + rows.add(resultSet.getLong("value")); + } + assertEquals(4, new HashSet<>(rows).size(), "rows were read twice: " + rows); + assertTrue(range(1, 8).containsAll(rows), rows.toString()); + + statement.cancel(); + final SQLException canceled = assertThrows(SQLException.class, resultSet::next); + assertTrue(canceled.getMessage().contains("Statement canceled"), canceled.getMessage()); + awaitUntil("CancelFlightInfo", () -> counter("cancellation") >= 1); + awaitUntil("the open poll ended", () -> hasPollHoldEnded(2)); + } + } + awaitUntil("streams ended", () -> counter("do_get_active") == 0); + assertQuiet( + "a poll or a cancel after the cancel", + () -> counter("cancellation") == 1 && counter("poll_flight_info") == 3); + assertEquals(2, continuationPolls().size(), state()); + assertFalse(hasPollHold(2, "released"), state()); + } + + @Test + public void closingAnUnfinishedResultWhileAPollIsOpenCancelsOnceAndPollsNoMore() + throws Exception { + holdPoll(2); + try (Connection connection = connect(true, "pollInfoPrefetch=8"); + Statement statement = connection.createStatement()) { + final Future execution = executeAsync(statement, "burst"); + try (ResultSet resultSet = result(execution)) { + awaitUntil("C2 poll held", () -> hasPollHold(2, "held")); + assertTrue(resultSet.next()); + } + awaitUntil("CancelFlightInfo", () -> counter("cancellation") >= 1); + awaitUntil("the open poll ended", () -> hasPollHoldEnded(2)); + } + // The statement and the connection are closed now; none of it may cancel or poll again. + awaitUntil("streams ended", () -> counter("do_get_active") == 0); + assertQuiet( + "a poll or a cancel after the close", + () -> counter("cancellation") == 1 && counter("poll_flight_info") == 3); + assertEquals(2, continuationPolls().size(), state()); + assertFalse(hasPollHold(2, "released"), state()); + } + + @Test + public void closingAnUnfinishedResultWhilePollingIsPausedCancelsOnceAndPollsNoMore() + throws Exception { + try (Connection connection = connect(true, "pollInfoPrefetch=2"); + Statement statement = connection.createStatement()) { + final Future execution = executeAsync(statement, "burst"); + try (ResultSet resultSet = result(execution)) { + // E1..E4 are queued and unread, which is above the limit: the poller pauses before C2. + awaitUntil("C1 polled", () -> continuationPolls().size() >= 1); + assertQuiet("polled past the limit", () -> continuationPolls().size() == 1); + assertTrue(resultSet.next()); + } + awaitUntil("CancelFlightInfo", () -> counter("cancellation") >= 1); + } + awaitUntil("streams ended", () -> counter("do_get_active") == 0); + assertQuiet( + "a poll or a cancel after the close", + () -> counter("cancellation") == 1 && counter("poll_flight_info") == 2); + assertEquals(1, continuationPolls().size(), state()); + } + + @Test + public void cancelWhileAStreamIsHeldCancelsItAndPollsNoMore() throws Exception { + post("/hold", "{\"endpoint\":1}"); + try (Connection connection = connect(true, "pollInfoPrefetch=2"); + Statement statement = connection.createStatement()) { + final Future execution = executeAsync(statement, "burst"); + awaitUntil("E1 held", () -> hasHold(1, "held")); + // E1..E4 are known and the poller is paused at the limit, so the poll count is settled. + awaitUntil("C1 polled", () -> continuationPolls().size() >= 1); + assertQuiet("polled past the limit", () -> continuationPolls().size() == 1); + // E2 is readable while E1 is held, so execution has returned its result set. + try (ResultSet resultSet = result(execution)) { + statement.cancel(); + final SQLException canceled = assertThrows(SQLException.class, resultSet::next); + assertTrue(canceled.getMessage().contains("Statement canceled"), canceled.getMessage()); + awaitUntil("E1 cancelled", () -> hasEnd(1, "cancelled")); + awaitUntil("CancelFlightInfo", () -> counter("cancellation") >= 1); + } + awaitUntil("streams ended", () -> counter("do_get_active") == 0); + } + assertEquals(2, counter("poll_flight_info"), state()); + assertEquals(1, counter("cancellation"), state()); + // The held stream was cancelled, never completed. + assertFalse(hasEnd(1, "completed"), state()); + } + + @Test + public void preparedStatementBindsOnceAndDeliversAllRows() throws Exception { + final List rows; + try (Connection connection = connect(true, "pollInfoPrefetch=2"); + PreparedStatement statement = connection.prepareStatement("burst")) { + statement.setLong(1, 7); + try (ResultSet resultSet = statement.executeQuery()) { + rows = values(resultSet, "burst"); + } + } + assertEquals(range(1, 8), sorted(rows)); + assertEquals(1, counter("parameter_binding"), state()); + assertEquals(1, counter("original_descriptors"), state()); + assertEquals(2, counter("continuation_descriptors"), state()); + assertEquals(3, familyCounter("prepared", "poll_flight_info"), state()); + assertEquals(0, counter("get_flight_info"), state()); + } + + @Test + public void optOutUsesGetFlightInfoOnly() throws Exception { + final List rows; + try (Connection connection = connect(false, ""); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("burst")) { + rows = values(resultSet, "burst"); + } + assertEquals(range(1, 8), sorted(rows)); + assertEquals(1, counter("get_flight_info"), state()); + assertEquals(0, counter("poll_flight_info"), state()); + assertEquals(4, counter("do_get"), state()); + assertTrue(events("PollFlightInfo").isEmpty(), state()); + } + + private Future executeAsync(final Statement statement, final String query) { + return background.submit(() -> statement.executeQuery(query)); + } + + private static ResultSet result(final Future execution) throws Exception { + final ResultSet resultSet = execution.get(WAIT.toSeconds(), TimeUnit.SECONDS); + assertNotNull(resultSet); + return resultSet; + } + + private static Connection connect(final boolean usePollInfo, final String extraProperties) + throws Exception { + return DriverManager.getConnection( + String.format( + "jdbc:arrow-flight-sql://127.0.0.1:%d/?useEncryption=false&usePollInfo=%s" + + "&threadPoolSize=4%s", + FLIGHT_PORT, usePollInfo, extraProperties.isEmpty() ? "" : "&" + extraProperties)); + } + + private static List values(final ResultSet resultSet, final String scenario) + throws Exception { + final List values = new ArrayList<>(); + while (resultSet.next()) { + assertEquals(scenario, resultSet.getString("scenario")); + values.add(resultSet.getLong("value")); + } + return values; + } + + private static List range(final int firstInclusive, final int lastInclusive) { + return IntStream.rangeClosed(firstInclusive, lastInclusive) + .mapToObj(Long::valueOf) + .collect(Collectors.toList()); + } + + private static List sorted(final List values) { + final List copy = new ArrayList<>(values); + Collections.sort(copy); + return copy; + } + + private static long gapMillis(final JsonNode earlier, final JsonNode later) { + return TimeUnit.NANOSECONDS.toMillis( + later.path("elapsed_ns").asLong() - earlier.path("elapsed_ns").asLong()); + } + + // Events, filtered by method; lifecycle events sit between requests, so never go by position. + private static List events(final String method) { + final List matching = new ArrayList<>(); + for (final JsonNode event : stateJson().path("events")) { + if (method.equals(event.path("method").asText())) { + matching.add(event); + } + } + return matching; + } + + private static List continuationPolls() { + return events("PollFlightInfo").stream() + .filter(event -> CONTINUATION.equals(event.path("descriptor_kind").asText())) + .collect(Collectors.toList()); + } + + private static List continuationOrderSuffixes() { + final List suffixes = new ArrayList<>(); + for (final JsonNode descriptor : stateJson().path("continuation_order")) { + final String text = descriptor.asText(); + suffixes.add(text.substring(text.lastIndexOf('/') + 1)); + } + return suffixes; + } + + private static boolean hasHold(final int endpoint, final String outcome) { + return events("DoGet.hold").stream() + .anyMatch( + event -> + event.path("endpoint").asInt() == endpoint + && outcome.equals(event.path("outcome").asText())); + } + + private static void holdPoll(final int continuation) { + post("/hold-poll", "{\"continuation\":" + continuation + "}"); + } + + private static void releasePoll(final int continuation) { + post("/release-poll", "{\"continuation\":" + continuation + "}"); + } + + private static boolean hasPollHold(final int continuation, final String outcome) { + return events("PollFlightInfo.hold").stream() + .anyMatch( + event -> + event.path(CONTINUATION).asInt() == continuation + && outcome.equals(event.path("outcome").asText())); + } + + // A held poll ended by the client: CancelFlightInfo, or the cancelled call (context). + private static boolean hasPollHoldEnded(final int continuation) { + return hasPollHold(continuation, "cancel-terminated") + || hasPollHold(continuation, "context-terminated"); + } + + private static boolean hasEnd(final int endpoint, final String outcome) { + return events("DoGet.end").stream() + .anyMatch( + event -> + event.path("endpoint").asInt() == endpoint + && outcome.equals(event.path("outcome").asText())); + } + + private static JsonNode single(final List events, final int endpoint) { + final List matching = + events.stream() + .filter(event -> event.path("endpoint").asInt() == endpoint) + .collect(Collectors.toList()); + assertEquals(1, matching.size(), "endpoint " + endpoint + ": " + matching); + return matching.get(0); + } + + private static int counter(final String name) { + return stateJson().path("counters").path(name).asInt(); + } + + private static int familyCounter(final String family, final String name) { + return stateJson().path("counters_by_family").path(family).path(name).asInt(); + } + + private static void awaitUntil(final String description, final BooleanSupplier condition) + throws Exception { + final long deadline = System.nanoTime() + WAIT.toNanos(); + while (!condition.getAsBoolean()) { + if (System.nanoTime() > deadline) { + throw new AssertionError("Timed out waiting for: " + description + "\n" + state()); + } + Thread.sleep(10); + } + } + + // The condition must stay true for the whole quiet window. + private static void assertQuiet(final String message, final BooleanSupplier condition) + throws Exception { + final long end = System.nanoTime() + QUIET.toNanos(); + do { + assertTrue(condition.getAsBoolean(), message + "\n" + state()); + Thread.sleep(25); + } while (System.nanoTime() < end); + } + + private static JsonNode stateJson() { + try { + return JSON.readTree(state()); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static String state() { + return request("GET", "/state", ""); + } + + private static void post(final String path, final String body) { + request("POST", path, body); + } + + private static String request(final String method, final String path, final String body) { + try { + final HttpRequest.Builder builder = + HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + CONTROL_PORT + path)) + .timeout(Duration.ofSeconds(2)); + if ("POST".equals(method)) { + builder.header("Content-Type", "application/json"); + builder.POST(HttpRequest.BodyPublishers.ofString(body)); + } else { + builder.GET(); + } + final HttpResponse response = + HTTP_CLIENT.send(builder.build(), HttpResponse.BodyHandlers.ofString()); + assertEquals("POST".equals(method) ? 204 : 200, response.statusCode(), response.body()); + return response.body(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java new file mode 100644 index 0000000000..6a6aa59bd8 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java @@ -0,0 +1,467 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.arrow.driver.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLTimeoutException; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +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.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; +import org.junit.jupiter.api.Order; +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. + * + *

    Enable with {@code -Dpollinfo.shared.enabled=true}. Every shared-server class resets the + * server and asserts its global counters, so two of them must never run at once. Surefire runs + * several forks, hence each class holds the cross-JVM {@link SharedServerLock} from + * {@code @BeforeAll} to {@code @AfterAll} and leaves the server reset. + */ +@EnabledIfSystemProperty(named = "pollinfo.shared.enabled", matches = "true") +@TestMethodOrder(OrderAnnotation.class) +public class SharedServerPollInfoExecutionTest { + private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); + private static final ObjectMapper JSON = new ObjectMapper(); + private static final int FLIGHT_PORT = Integer.getInteger("pollinfo.shared.flightPort", 32347); + private static final int CONTROL_PORT = Integer.getInteger("pollinfo.shared.controlPort", 32348); + + private static SharedServerLock serverLock; + + @BeforeAll + public static void lockServer() throws Exception { + serverLock = SharedServerLock.acquire(CONTROL_PORT); + } + + @AfterAll + public static void resetAndUnlockServer() throws Exception { + try { + resetWhenIdle(); + } finally { + serverLock.close(); + } + } + + @BeforeEach + public void resetServer() throws Exception { + resetWhenIdle(); + } + + // The previous test closed its connections; /reset must not run while the server still has + // streams open. + private static void resetWhenIdle() throws Exception { + awaitCounterEquals("do_get_active", 0, Duration.ofSeconds(10)); + post("/reset", ""); + } + + @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/")); + // Each continuation is sent once, and C1 before C2. + 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, 2); + } + + @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 t7LateErrorSurfacesAtNextReadBoundary() throws Exception { + // The failing continuation is held, so the poller cannot record the failure before the first + // row was read: it surfaces at the next read. + post("/hold-poll", "{\"continuation\":1}"); + try (Connection connection = connect(true); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("late-error")) { + assertTrue(resultSet.next()); + assertEquals(1L, resultSet.getLong("value")); + awaitPollHeld(1); + post("/release-poll", "{\"continuation\":1}"); + final Throwable failure = assertThrows(Throwable.class, resultSet::next); + assertEquals("Continuation PollFlightInfo failed", failure.getMessage()); + assertTrue(hasFlightStatus(failure, FlightStatusCode.INTERNAL), failure.toString()); + } + assertCounters(2, 0, 0, 1, 1, 0, 0, 1); + } + + @Test + @Order(9) + 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(10) + public void t9CancelWhileResultSetWaitsForMoreEndpoints() throws Exception { + try (Connection connection = connect(true); + Statement statement = connection.createStatement()) { + final AtomicReference failure = new AtomicReference<>(); + final AtomicBoolean resultSetCreated = new AtomicBoolean(); + final CountDownLatch rowsRead = new CountDownLatch(1); + final Thread execution = + new Thread( + () -> { + 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")); + rowsRead.countDown(); + resultSet.next(); + } catch (Throwable e) { + failure.set(e); + } + }, + "shared-server-jdbc-cancel"); + execution.start(); + // The poller polls C1 in the background; the application waits for more endpoints. + assertTrue(rowsRead.await(5, TimeUnit.SECONDS), "the rows were never read"); + awaitCounter("poll_flight_info", 2, Duration.ofSeconds(3)); + assertTrue(resultSetCreated.get()); + assertNotNull(statement.getResultSet()); + 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()); + assertNotNull(failure.get()); + assertTrue(failure.get() instanceof SQLException, failure.get().toString()); + assertTrue( + failure.get().getMessage().contains("Statement canceled"), 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, 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")); + // The background poller has C1 open (the server answers it only when cancelled); closing + // the result ends that poll and sends one CancelFlightInfo. + awaitCounter("poll_flight_info", 2, Duration.ofSeconds(3)); + } + awaitCounter("cancellation", 1, Duration.ofSeconds(2)); + awaitCounter("active_call_terminations", 1, Duration.ofSeconds(2)); + assertCounters(2, 0, 0, 1, 1, 1, 1, 1); + } + + private static Connection connect(final boolean usePollInfo) throws Exception { + return 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()); + } + + // Waits until the server holds the given continuation poll (set with POST /hold-poll). + private static void awaitPollHeld(final int continuation) throws Exception { + final long deadline = System.nanoTime() + Duration.ofSeconds(5).toNanos(); + while (true) { + final JsonNode events = JSON.readTree(state()).path("events"); + for (final JsonNode event : events) { + if ("PollFlightInfo.hold".equals(event.path("method").asText()) + && event.path("continuation").asInt() == continuation + && "held".equals(event.path("outcome").asText())) { + return; + } + } + assertTrue(System.nanoTime() < deadline, "continuation " + continuation + " was not held"); + Thread.sleep(20); + } + } + + private static void awaitCounterEquals( + final String name, final int expected, final Duration timeout) throws Exception { + final long deadline = System.nanoTime() + timeout.toNanos(); + 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.header("Content-Type", "application/json"); + builder.POST(HttpRequest.BodyPublishers.ofString(body)); + } else { + builder.GET(); + } + final HttpResponse response = + HTTP_CLIENT.send(builder.build(), HttpResponse.BodyHandlers.ofString()); + 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/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}, }; } } diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/PollBackoffTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/PollBackoffTest.java new file mode 100644 index 0000000000..399ec71b50 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/PollBackoffTest.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.arrow.driver.jdbc.client; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +public class PollBackoffTest { + private static List delays(final PollBackoff backoff, final int count) { + final List delays = new ArrayList<>(); + for (int i = 0; i < count; i++) { + delays.add(backoff.nextDelayMillis()); + } + return delays; + } + + @Test + public void doublesFromOneHundredMillisecondsUpToTheCap() { + assertEquals( + List.of(100L, 200L, 400L, 800L, 1600L, 3200L, 5000L, 5000L), + delays(new PollBackoff(PollBackoff.DEFAULT_MAX_MILLIS), 8)); + } + + @Test + public void capBetweenTwoStepsCutsTheLaterStepAndStaysThere() { + assertEquals(List.of(100L, 150L, 150L, 150L), delays(new PollBackoff(150), 4)); + } + + @Test + public void capBelowTheInitialDelayIsTheOnlyDelay() { + assertEquals(List.of(50L, 50L, 50L), delays(new PollBackoff(50), 3)); + } + + @Test + public void capBelowOneMillisecondIsRaisedToOne() { + assertEquals(List.of(1L, 1L), delays(new PollBackoff(0), 2)); + assertEquals(List.of(1L, 1L), delays(new PollBackoff(-5), 2)); + } + + @Test + public void resetStartsAgainFromTheInitialDelay() { + final PollBackoff backoff = new PollBackoff(5000); + assertEquals(List.of(100L, 200L, 400L), delays(backoff, 3)); + backoff.reset(); + assertEquals(List.of(100L, 200L), delays(backoff, 2)); + } + + @Test + public void resetAfterReachingTheCapStartsAgainFromTheInitialDelay() { + final PollBackoff backoff = new PollBackoff(300); + assertEquals(List.of(100L, 200L, 300L, 300L), delays(backoff, 4)); + backoff.reset(); + assertEquals(List.of(100L, 200L, 300L), delays(backoff, 3)); + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueDeferredOpenTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueDeferredOpenTest.java new file mode 100644 index 0000000000..7234d0405c --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueDeferredOpenTest.java @@ -0,0 +1,745 @@ +/* + * 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 java.util.concurrent.locks.LockSupport; +import org.apache.arrow.driver.jdbc.client.CloseableEndpointStreamPair; +import org.apache.arrow.flight.CallStatus; +import org.apache.arrow.flight.FlightEndpoint; +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; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * 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 static final long POLL_PARK_NANOS = TimeUnit.MILLISECONDS.toNanos(1); + + 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()); + } + } + + // F2. An Error from the opener used to leave the reservations held. + @Test + public void anErrorFromTheOpenerReleasesTheReservations() throws Exception { + final AssertionError error = new AssertionError("scripted"); + try (FlightEndpointDataQueue queue = + FlightEndpointDataQueue.createNewQueue( + readers, + 2, + endpoint -> { + throw error; + })) { + assertSame( + error, assertThrows(AssertionError.class, () -> queue.addEndpoints(endpoints(2), true))); + assertEquals(0, queue.openUnreadCount()); + assertEquals(0, queue.unreadCount()); + } + } + + // F7. Nothing is queued or opened after a failure. + @Test + public void addEndpointsAfterAFailureOpensNothing() throws Exception { + try (FlightEndpointDataQueue queue = queue(2)) { + final SQLException cause = new SQLException("continuation failed"); + queue.fail(cause); + queue.addEndpoints(endpoints(2), true); + assertEquals(List.of(), opened); + assertEquals(0, queue.unreadCount()); + assertSame(cause, assertThrows(SQLException.class, queue::next)); + } + } + + @Test + public void failureWhileOpeningStopsOpeningTheRestOfTheBatch() throws Exception { + final AtomicReference queueRef = new AtomicReference<>(); + final SQLException cause = new SQLException("continuation failed"); + try (FlightEndpointDataQueue queue = + FlightEndpointDataQueue.createNewQueue( + readers, + 3, + endpoint -> { + final CloseableEndpointStreamPair stream = recordingOpener().open(endpoint); + queueRef.get().fail(cause); + return stream; + })) { + queueRef.set(queue); + queue.addEndpoints(endpoints(3), true); + assertEquals(List.of(fake(0)), opened); + assertEquals(0, queue.openUnreadCount()); + assertSame(cause, queue.failure()); + } + } + + // F1. The application finishing an endpoint frees its slot at once, with no reader task. + @Test + public void endpointExhaustedFreesTheSlotOnTheCallingThread() throws Exception { + try (FlightEndpointDataQueue queue = queue(2)) { + final AtomicInteger resumes = new AtomicInteger(); + queue.setResumeAction(resumes::incrementAndGet); + queue.addEndpoints(endpoints(3), true); + assertTrue(queue.pauseIfFull(() -> {})); + fake(0).ready(); + final CloseableEndpointStreamPair first = queue.next(); + assertSame(fake(0).pair, first); + assertEquals(List.of(fake(0), fake(1)), opened); + + queue.endpointExhausted(first); + + // All of it happened before the call returned: the stream closed and the pending endpoint + // opened. The limit is full again, so the poller stays paused. + verify(fake(0).pair).close(); + assertEquals(List.of(fake(0), fake(1), fake(2)), opened); + assertEquals(2, queue.openUnreadCount()); + assertEquals(0, resumes.get()); + + fake(1).ready(); + final CloseableEndpointStreamPair second = queue.next(); + assertSame(fake(1).pair, second); + queue.endpointExhausted(second); + assertEquals(1, queue.openUnreadCount()); + assertEquals(1, resumes.get()); + } + } + + // F3. The first load waits for queued endpoints only, never for endpoints not published yet. + @Test + public void nextAvailableDoesNotWaitForEndpointsThatWereNotPublished() throws Exception { + try (FlightEndpointDataQueue queue = queue(2)) { + queue.addEndpoints(emptyEndpoints(1), true); + // The one queued endpoint ends without a row; more may arrive, but nextAvailable() returns. + final Waiter reader = new Waiter(queue::nextAvailable); + assertNull(reader.value()); + assertTrue(queue.isMoreExpected()); + } + } + + @Test + public void closeWakesAReaderWaitingForMoreEndpoints() throws Exception { + final FlightEndpointDataQueue queue = queue(2); + 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"); + LockSupport.parkNanos(POLL_PARK_NANOS); + } + 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"); + LockSupport.parkNanos(POLL_PARK_NANOS); + } + 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()); + } + } + + // S5. fail() and close() do not wait for an opener that is blocked in an RPC; the stream it + // opens late is closed and never read, and its reservation is released. + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void anOpenerBlockedWhileTheQueueFailsOrClosesDoesNotBlockItAndTheLateStreamIsNeverRead( + final boolean closeInsteadOfFail) throws Exception { + final CountDownLatch entered = new CountDownLatch(1); + final CountDownLatch release = new CountDownLatch(1); + try (FlightEndpointDataQueue queue = + FlightEndpointDataQueue.createNewQueue( + readers, + 2, + endpoint -> { + entered.countDown(); + try { + release.await(); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + throw new SQLException(e); + } + return recordingOpener().open(endpoint); + })) { + final Waiter adder = + new Waiter( + () -> { + queue.addEndpoints(endpoints(1), true); + return null; + }); + assertTrue(entered.await(WAIT_MS, TimeUnit.MILLISECONDS), "the opener was never called"); + assertEquals(1, queue.openUnreadCount()); + + // The opener is blocked and holds no queue lock: both calls return without it. + final Waiter ender = + new Waiter( + () -> { + if (closeInsteadOfFail) { + queue.close(); + } else { + queue.fail(new SQLException("continuation failed")); + } + return null; + }); + assertNull(ender.value()); + assertFalse(adder.isDone(), "addEndpoints returned before its opener did"); + + release.countDown(); + assertNull(adder.value()); + // The late stream was handed back: closed, never read, and its slot is free again. + verify(fake(0).pair).close(); + assertEquals(0, fake(0).reads.get()); + assertFalse(fake(0).cancelled.get()); + assertEquals(0, queue.openUnreadCount()); + assertEquals(0, queue.unreadCount()); + } + } + + /** Runs a queue call on its own thread, so that a missing wake-up fails instead of hanging. */ + private final class Waiter { + private final CompletableFuture result = new CompletableFuture<>(); + private final Thread thread; + + Waiter(final Callable call) { + thread = + new Thread( + () -> { + try { + result.complete(call.call()); + } catch (final Throwable t) { + result.completeExceptionally(t); + } + }, + "queue-test-reader"); + thread.setDaemon(true); + thread.start(); + } + + Thread thread() { + return thread; + } + + boolean isDone() { + return result.isDone(); + } + + void awaitWaiting() { + final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(WAIT_MS); + while (thread.getState() != Thread.State.WAITING + && thread.getState() != Thread.State.TIMED_WAITING) { + assertTrue(System.nanoTime() < deadline, "the reader never waited"); + assertFalse(result.isDone(), "the reader returned instead of waiting"); + LockSupport.parkNanos(POLL_PARK_NANOS); + } + } + + Object value() throws Exception { + try { + return result.get(WAIT_MS, TimeUnit.MILLISECONDS); + } catch (final TimeoutException e) { + throw new AssertionError("the reader hung", e); + } + } + + SQLException failure() throws Exception { + return (SQLException) failureOf(SQLException.class); + } + + Throwable failureOf(final Class expected) throws Exception { + try { + result.get(WAIT_MS, TimeUnit.MILLISECONDS); + } catch (final ExecutionException e) { + assertInstanceOf(expected, e.getCause()); + return e.getCause(); + } catch (final TimeoutException e) { + throw new AssertionError("the reader hung", e); + } + throw new AssertionError("expected the reader to fail"); + } + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/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..1b099d1d6b --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java @@ -0,0 +1,325 @@ +/* + * 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.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.arrow.driver.jdbc.utils.ScriptedPollQuery.Answer; +import org.apache.arrow.flight.CallStatus; +import org.apache.arrow.flight.CancelFlightInfoRequest; +import org.apache.arrow.flight.CancelStatus; +import org.apache.arrow.flight.FlightDescriptor; +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 final List scriptedQueries = new CopyOnWriteArrayList<>(); + 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); + private volatile CountDownLatch continuationFailureGate; + + 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); + continuationFailureGate = null; + } + + /** + * Makes the failing continuation of {@link Scenario#CONTINUATION_UNIMPLEMENTED} wait, once it + * arrives, until {@link #releaseContinuationFailure()}. {@link #awaitActivePoll} reports that it + * arrived. Call it after {@link #configure}. + */ + public void holdContinuationFailure() { + continuationFailureGate = new CountDownLatch(1); + } + + public void releaseContinuationFailure() { + final CountDownLatch gate = continuationFailureGate; + if (gate != null) { + gate.countDown(); + } + } + + @Override + public FlightInfo getFlightInfo(final CallContext context, final FlightDescriptor descriptor) { + getFlightInfoCount.incrementAndGet(); + lastGetFlightInfoFamily = commandFamily(descriptor); + return super.getFlightInfo(context, descriptor); + } + + /** + * Serves {@code query} (sent as a statement query) from a script of poll answers, bypassing the + * canned scenarios. The returned handle holds and releases streams and records what the server + * saw. + */ + public ScriptedPollQuery scripted(final String query, final Answer... answers) { + final ScriptedPollQuery scripted = new ScriptedPollQuery(query, List.of(answers)); + scriptedQueries.add(scripted); + return scripted; + } + + @Override + public void getStream( + final CallContext context, final Ticket ticket, final ServerStreamListener listener) { + for (final ScriptedPollQuery scripted : scriptedQueries) { + if (scripted.ownsTicket(ticket)) { + scripted.doGet(ticket, listener); + return; + } + } + super.getStream(context, ticket, listener); + } + + @Override + public PollInfo pollFlightInfo(final CallContext context, final FlightDescriptor descriptor) { + pollDescriptors.add(descriptor); + for (final ScriptedPollQuery scripted : scriptedQueries) { + if (scripted.matches(descriptor)) { + return scripted.poll(context, 0); + } + final int index = scripted.continuationIndex(descriptor); + if (index >= 0) { + return scripted.poll(context, index); + } + } + final boolean initial = isFlightSqlCommand(descriptor); + if (initial) { + finalFlightInfo = super.getFlightInfo(context, descriptor); + 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); + } + final CountDownLatch gate = continuationFailureGate; + if (gate != null) { + activePoll.countDown(); + try { + while (!gate.await(10, TimeUnit.MILLISECONDS)) { + if (context.isCancelled()) { + throw CallStatus.CANCELLED.toRuntimeException(); + } + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw CallStatus.CANCELLED.withCause(e).toRuntimeException(); + } + } + throw CallStatus.UNIMPLEMENTED.toRuntimeException(); + } + if (selectedFamily && scenario == Scenario.TIMEOUT) { + 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(); + for (final ScriptedPollQuery scripted : scriptedQueries) { + if (scripted.matches(request.getInfo().getDescriptor())) { + scripted.recordCancelFlightInfo(); + } + } + 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(), + new ArrayList<>(finalInfo.getEndpoints()), + -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-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ScriptedPollQuery.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ScriptedPollQuery.java new file mode 100644 index 0000000000..4ce48ea476 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ScriptedPollQuery.java @@ -0,0 +1,679 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.arrow.driver.jdbc.utils; + +import com.google.protobuf.Any; +import com.google.protobuf.InvalidProtocolBufferException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Predicate; +import org.apache.arrow.flight.CallStatus; +import org.apache.arrow.flight.FlightDescriptor; +import org.apache.arrow.flight.FlightEndpoint; +import org.apache.arrow.flight.FlightInfo; +import org.apache.arrow.flight.FlightProducer.CallContext; +import org.apache.arrow.flight.FlightProducer.ServerStreamListener; +import org.apache.arrow.flight.Location; +import org.apache.arrow.flight.PollInfo; +import org.apache.arrow.flight.Ticket; +import org.apache.arrow.flight.sql.impl.FlightSql.CommandStatementQuery; +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.memory.RootAllocator; +import org.apache.arrow.vector.IntVector; +import org.apache.arrow.vector.VectorSchemaRoot; +import org.apache.arrow.vector.types.pojo.ArrowType; +import org.apache.arrow.vector.types.pojo.Field; +import org.apache.arrow.vector.types.pojo.Schema; + +/** + * One scripted progressive query served by {@link PollingMockFlightSqlProducer}. + * + *

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

    The query records every poll, DoGet start/end/cancel and CancelFlightInfo with a nanosecond + * timestamp, and counts concurrently open streams and in-flight polls. + */ +public final class ScriptedPollQuery { + /** Schema of every endpoint stream. */ + public static final Schema SCHEMA = + new Schema(Collections.singletonList(Field.nullable("answer", new ArrowType.Int(32, true)))); + + /** A schema a continuation answer can switch to by mistake. */ + static final Schema CHANGED_SCHEMA = + new Schema( + List.of( + Field.nullable("answer", new ArrowType.Int(32, true)), + Field.nullable("extra", new ArrowType.Int(32, true)))); + + private static final AtomicInteger KEYS = new AtomicInteger(); + + /** What the server records. */ + public enum EventType { + POLL, + POLL_CANCELLED, + DOGET_START, + BATCH_SENT, + DOGET_END, + DOGET_CANCELLED, + CANCEL_FLIGHT_INFO + } + + /** One recorded server-side event. */ + public static final class Event { + private final EventType type; + private final int index; + private final long nanos; + + Event(final EventType type, final int index, final long nanos) { + this.type = type; + this.index = index; + this.nanos = nanos; + } + + public EventType type() { + return type; + } + + /** The answer index of a poll, or the endpoint id of a stream. */ + public int index() { + return index; + } + + public long nanos() { + return nanos; + } + + @Override + public String toString() { + return type + ":" + index; + } + } + + /** How an answer breaks the append-only rule for the endpoints published so far. */ + private enum Tamper { + NONE, + /** Publishes one endpoint fewer than the previous answer did. */ + SHRINK, + /** Publishes as many endpoints as before, with the first one's ticket replaced. */ + CHANGED_TICKET + } + + /** The server's answer to one poll. */ + public static final class Answer { + private final int newEndpoints; + private final boolean done; + private final boolean failure; + private final boolean schemaChange; + private final Tamper tamper; + private final CountDownLatch gate; + + private Answer( + final int newEndpoints, + final boolean done, + final boolean failure, + final boolean schemaChange, + final Tamper tamper, + final CountDownLatch gate) { + this.newEndpoints = newEndpoints; + this.done = done; + this.failure = failure; + this.schemaChange = schemaChange; + this.tamper = tamper; + this.gate = gate; + } + + /** Publishes {@code count} more endpoints; the query keeps running. */ + public static Answer endpoints(final int count) { + return new Answer(count, false, false, false, Tamper.NONE, null); + } + + /** Publishes {@code count} more endpoints and completes the query. */ + public static Answer done(final int count) { + return new Answer(count, true, false, false, Tamper.NONE, null); + } + + /** Publishes nothing; the query keeps running. */ + public static Answer empty() { + return endpoints(0); + } + + /** Fails the poll with INTERNAL. */ + public static Answer fail() { + return new Answer(0, false, true, false, Tamper.NONE, null); + } + + /** Publishes one more endpoint but announces a different schema. */ + public static Answer schemaChange() { + return new Answer(1, false, false, true, Tamper.NONE, null); + } + + /** Publishes one endpoint fewer than before: an append-only violation. */ + public static Answer shrink() { + return new Answer(0, false, false, false, Tamper.SHRINK, null); + } + + /** Publishes the same number of endpoints, with the first one's ticket changed. */ + public static Answer changedTicket() { + return new Answer(0, false, false, false, Tamper.CHANGED_TICKET, null); + } + + /** Never answers; the poll ends only when the client cancels it or its deadline expires. */ + public static Answer hang() { + return empty().gatedBy(new CountDownLatch(1)); + } + + /** Holds the answer until {@code gate} is released, or the client cancels the poll. */ + public Answer gatedBy(final CountDownLatch gate) { + return new Answer(newEndpoints, done, failure, schemaChange, tamper, gate); + } + } + + private final int key = KEYS.incrementAndGet(); + private final String query; + private final List answers; + private final FlightDescriptor descriptor; + private volatile int rowsPerEndpoint = 1; + private volatile int batchesPerEndpoint = 1; + private volatile boolean leadingEmptyBatch; + private volatile Location[] endpointLocations = new Location[0]; + + private final List events = new ArrayList<>(); + private final Map startGates = new HashMap<>(); + private final Map endGates = new HashMap<>(); + private final Set emptyEndpoints = new HashSet<>(); + private volatile CountDownLatch cancelFlightInfoGate; + private final CountDownLatch blockedPoll = new CountDownLatch(1); + private final CountDownLatch pollTerminated = new CountDownLatch(1); + private int openStreams; + private int maxOpenStreams; + private int inFlightPolls; + private int maxInFlightPolls; + + ScriptedPollQuery(final String query, final List answers) { + this.query = query; + this.answers = new ArrayList<>(answers); + this.descriptor = + FlightDescriptor.command( + Any.pack(CommandStatementQuery.newBuilder().setQuery(query).build()).toByteArray()); + } + + public String query() { + return query; + } + + /** Streams {@code rows} rows per endpoint, in one batch. */ + public ScriptedPollQuery rowsPerEndpoint(final int rows) { + this.rowsPerEndpoint = rows; + return this; + } + + /** + * Streams {@code batches} batches of {@link #rowsPerEndpoint(int)} rows per endpoint. Row {@code + * r} of batch {@code b} holds {@code id * 100 + b * rowsPerEndpoint + r}. + */ + public ScriptedPollQuery batchesPerEndpoint(final int batches) { + this.batchesPerEndpoint = batches; + return this; + } + + /** Every endpoint stream sends one batch with no rows before its data. */ + public ScriptedPollQuery leadingEmptyBatch() { + this.leadingEmptyBatch = true; + return this; + } + + /** Publishes every endpoint with these locations, like a server that names itself. */ + public ScriptedPollQuery endpointLocations(final Location... locations) { + this.endpointLocations = locations.clone(); + return this; + } + + private Location[] locations() { + return endpointLocations; + } + + /** The listed endpoints stream a single batch with no rows, then complete. */ + public ScriptedPollQuery emptyEndpoints(final int... ids) { + synchronized (this) { + for (final int id : ids) { + emptyEndpoints.add(id); + } + } + return this; + } + + /** Makes the server hold its CancelFlightInfo answer until {@link #releaseCancelFlightInfo()}. */ + public ScriptedPollQuery holdCancelFlightInfo() { + cancelFlightInfoGate = new CountDownLatch(1); + return this; + } + + public void releaseCancelFlightInfo() { + final CountDownLatch gate = cancelFlightInfoGate; + if (gate != null) { + gate.countDown(); + } + } + + // ---- hold and release ------------------------------------------------------------------- + + /** Holds the listed streams before they send anything. */ + public ScriptedPollQuery holdStart(final int... ids) { + synchronized (this) { + for (final int id : ids) { + startGates.put(id, new CountDownLatch(1)); + } + } + return this; + } + + /** Holds the listed streams after they sent their batch, before they complete. */ + public ScriptedPollQuery holdEnd(final int... ids) { + synchronized (this) { + for (final int id : ids) { + endGates.put(id, new CountDownLatch(1)); + } + } + return this; + } + + /** Holds the end of streams {@code 0..count-1}. */ + public ScriptedPollQuery holdAllEnds(final int count) { + for (int id = 0; id < count; id++) { + holdEnd(id); + } + return this; + } + + public void releaseStart(final int id) { + final CountDownLatch gate; + synchronized (this) { + gate = startGates.get(id); + } + if (gate != null) { + gate.countDown(); + } + } + + public void releaseEnd(final int id) { + final CountDownLatch gate; + synchronized (this) { + gate = endGates.get(id); + } + if (gate != null) { + gate.countDown(); + } + } + + /** Releases every held stream. */ + public void releaseAll() { + synchronized (this) { + startGates.values().forEach(CountDownLatch::countDown); + endGates.values().forEach(CountDownLatch::countDown); + } + } + + // ---- observations ----------------------------------------------------------------------- + + public synchronized List events() { + return new ArrayList<>(events); + } + + /** The events of the given types, as {@code TYPE:index} strings, in arrival order. */ + public List eventNames(final EventType... types) { + final List wanted = List.of(types); + final List names = new ArrayList<>(); + for (final Event event : events()) { + if (wanted.contains(event.type)) { + names.add(event.toString()); + } + } + return names; + } + + public synchronized int count(final EventType type) { + int count = 0; + for (final Event event : events) { + if (event.type == type) { + count++; + } + } + return count; + } + + public synchronized boolean hasEvent(final EventType type, final int index) { + return events.stream().anyMatch(event -> event.type == type && event.index == index); + } + + public int pollCount() { + return count(EventType.POLL); + } + + public int doGetStarted() { + return count(EventType.DOGET_START); + } + + public int cancelFlightInfoCount() { + return count(EventType.CANCEL_FLIGHT_INFO); + } + + /** The answer indices of the polls, in arrival order. */ + public List pollIndices() { + final List indices = new ArrayList<>(); + for (final Event event : events()) { + if (event.type == EventType.POLL) { + indices.add(event.index); + } + } + return indices; + } + + /** The arrival times, in nanoseconds, of the polls, in arrival order. */ + public List pollNanos() { + final List nanos = new ArrayList<>(); + for (final Event event : events()) { + if (event.type == EventType.POLL) { + nanos.add(event.nanos); + } + } + return nanos; + } + + public synchronized int maxOpenStreams() { + return maxOpenStreams; + } + + public synchronized int maxInFlightPolls() { + return maxInFlightPolls; + } + + public boolean awaitPollCount(final int count, final long millis) throws InterruptedException { + return awaitEvents(events -> countOf(events, EventType.POLL) >= count, millis); + } + + public boolean awaitDoGetStarted(final int count, final long millis) throws InterruptedException { + return awaitEvents(events -> countOf(events, EventType.DOGET_START) >= count, millis); + } + + public boolean awaitStream(final EventType type, final int id, final long millis) + throws InterruptedException { + return awaitEvents( + events -> events.stream().anyMatch(e -> e.type == type && e.index == id), millis); + } + + public boolean awaitCancelFlightInfo(final int count, final long millis) + throws InterruptedException { + return awaitEvents(events -> countOf(events, EventType.CANCEL_FLIGHT_INFO) >= count, millis); + } + + /** Waits until a poll is blocked on a gate (or a hang). */ + public boolean awaitBlockedPoll(final long millis) throws InterruptedException { + return blockedPoll.await(millis, TimeUnit.MILLISECONDS); + } + + /** Waits until a blocked poll ended because the client cancelled it. */ + public boolean awaitPollTerminated(final long millis) throws InterruptedException { + return pollTerminated.await(millis, TimeUnit.MILLISECONDS); + } + + private static int countOf(final List events, final EventType type) { + int count = 0; + for (final Event event : events) { + if (event.type == type) { + count++; + } + } + return count; + } + + private synchronized boolean awaitEvents( + final Predicate> condition, final long millis) throws InterruptedException { + final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(millis); + while (!condition.test(events)) { + final long remaining = deadline - System.nanoTime(); + if (remaining <= 0) { + return false; + } + TimeUnit.NANOSECONDS.timedWait(this, remaining); + } + return true; + } + + private synchronized void record(final EventType type, final int index) { + events.add(new Event(type, index, System.nanoTime())); + notifyAll(); + } + + // ---- server side ------------------------------------------------------------------------ + + FlightDescriptor descriptor() { + return descriptor; + } + + /** Whether {@code candidate} is this query's statement command (the initial poll). */ + boolean matches(final FlightDescriptor candidate) { + if (!candidate.isCommand()) { + return false; + } + try { + final Any command = Any.parseFrom(candidate.getCommand()); + return command.is(CommandStatementQuery.class) + && query.equals(command.unpack(CommandStatementQuery.class).getQuery()); + } catch (final InvalidProtocolBufferException e) { + return false; + } + } + + void recordCancelFlightInfo() { + record(EventType.CANCEL_FLIGHT_INFO, 0); + final CountDownLatch gate = cancelFlightInfoGate; + if (gate != null) { + try { + gate.await(10, TimeUnit.SECONDS); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } + + private FlightDescriptor continuation(final int index) { + return FlightDescriptor.command( + ("jdbc-continuation-s" + key + "-" + index).getBytes(StandardCharsets.UTF_8)); + } + + /** The answer index a continuation descriptor stands for, or -1 for another query's. */ + int continuationIndex(final FlightDescriptor candidate) { + if (!candidate.isCommand()) { + return -1; + } + final String prefix = "jdbc-continuation-s" + key + "-"; + final String text = new String(candidate.getCommand(), StandardCharsets.UTF_8); + if (!text.startsWith(prefix)) { + return -1; + } + return Integer.parseInt(text.substring(prefix.length())); + } + + boolean ownsTicket(final Ticket ticket) { + return new String(ticket.getBytes(), StandardCharsets.UTF_8).startsWith(ticketPrefix()); + } + + private String ticketPrefix() { + return "jdbc-script-" + key + "-"; + } + + PollInfo poll(final CallContext context, final int index) { + if (index >= answers.size()) { + throw CallStatus.INTERNAL + .withDescription("Script exhausted at poll " + index + " of " + query) + .toRuntimeException(); + } + final Answer answer = answers.get(index); + record(EventType.POLL, index); + synchronized (this) { + inFlightPolls++; + maxInFlightPolls = Math.max(maxInFlightPolls, inFlightPolls); + } + try { + if (answer.gate != null) { + blockedPoll.countDown(); + while (!awaitGate(answer.gate)) { + if (context.isCancelled()) { + record(EventType.POLL_CANCELLED, index); + pollTerminated.countDown(); + throw CallStatus.CANCELLED.withDescription("poll cancelled").toRuntimeException(); + } + } + } + if (answer.failure) { + throw CallStatus.INTERNAL.withDescription("scripted failure").toRuntimeException(); + } + int published = 0; + boolean schemaChanged = false; + for (int i = 0; i <= index; i++) { + published += answers.get(i).newEndpoints; + schemaChanged |= answers.get(i).schemaChange; + } + if (answer.tamper == Tamper.SHRINK) { + published = Math.max(0, published - 1); + } + final List endpoints = new ArrayList<>(); + for (int id = 0; id < published; id++) { + final String ticket = + answer.tamper == Tamper.CHANGED_TICKET && id == 0 + ? ticketPrefix() + "changed" + : ticketPrefix() + id; + endpoints.add( + new FlightEndpoint(new Ticket(ticket.getBytes(StandardCharsets.UTF_8)), locations())); + } + final FlightInfo info = + new FlightInfo(schemaChanged ? CHANGED_SCHEMA : SCHEMA, descriptor, endpoints, -1, -1); + final FlightDescriptor next = answer.done ? null : continuation(index + 1); + return new PollInfo(info, next, answer.done ? 1.0 : 0.5, null); + } finally { + synchronized (this) { + inFlightPolls--; + } + } + } + + private static boolean awaitGate(final CountDownLatch gate) { + try { + return gate.await(10, TimeUnit.MILLISECONDS); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + throw CallStatus.CANCELLED.withCause(e).toRuntimeException(); + } + } + + void doGet(final Ticket ticket, final ServerStreamListener listener) { + final int id = + Integer.parseInt( + new String(ticket.getBytes(), StandardCharsets.UTF_8) + .substring(ticketPrefix().length())); + record(EventType.DOGET_START, id); + synchronized (this) { + openStreams++; + maxOpenStreams = Math.max(maxOpenStreams, openStreams); + } + boolean open = true; + try { + if (!awaitStreamGate(startGates, id, listener)) { + return; + } + sendBatch(id, listener); + record(EventType.BATCH_SENT, id); + if (!awaitStreamGate(endGates, id, listener)) { + return; + } + // The stream stops being open before the client can see it complete. + synchronized (this) { + openStreams--; + } + open = false; + record(EventType.DOGET_END, id); + listener.completed(); + } finally { + if (open) { + synchronized (this) { + openStreams--; + } + } + } + } + + // Returns false (after recording it) if the client cancelled the stream while it was held. + private boolean awaitStreamGate( + final Map gates, final int id, final ServerStreamListener listener) { + final CountDownLatch gate; + synchronized (this) { + gate = gates.get(id); + } + if (gate == null) { + return true; + } + while (!awaitGate(gate)) { + if (listener.isCancelled()) { + record(EventType.DOGET_CANCELLED, id); + return false; + } + } + return true; + } + + private void sendBatch(final int id, final ServerStreamListener listener) { + try (BufferAllocator allocator = new RootAllocator(); + VectorSchemaRoot root = VectorSchemaRoot.create(SCHEMA, allocator)) { + root.allocateNew(); + final IntVector vector = (IntVector) root.getVector("answer"); + final boolean empty; + synchronized (this) { + empty = emptyEndpoints.contains(id); + } + final int rows = empty ? 0 : rowsPerEndpoint; + listener.start(root); + if (empty || leadingEmptyBatch) { + root.setRowCount(0); + listener.putNext(); + } + if (empty) { + return; + } + for (int batch = 0; batch < batchesPerEndpoint; batch++) { + for (int row = 0; row < rows; row++) { + vector.setSafe(row, id * 100 + batch * rows + row); + } + root.setRowCount(rows); + listener.putNext(); + } + } + } +} diff --git a/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/formal/pollinfo-poll-ahead/PollAhead.tla b/formal/pollinfo-poll-ahead/PollAhead.tla new file mode 100644 index 0000000000..14665b34bb --- /dev/null +++ b/formal/pollinfo-poll-ahead/PollAhead.tla @@ -0,0 +1,724 @@ +----------------------------- MODULE PollAhead ----------------------------- +(***************************************************************************) +(* Bounded poll-ahead for the Arrow Flight SQL JDBC driver (BDX-645). *) +(* *) +(* One progressive JDBC ResultSet that has a continuation, from the moment *) +(* its poller has started: the first PollInfo published endpoint E1 and *) +(* continuation C1, and C1 has been handed to the poller (P.start: owned *) +(* is set, then handBack). The pool either took the task (the poller is *) +(* "running") or rejected it (the poller is "orphaned", which is the same *) +(* state a rejected resume leaves); Init chooses either. The application *) +(* thread is in executeQuery's first load (Q.nextAvailable) or in *) +(* ResultSet.next(); both run the same awaitNext loop, and the first load *) +(* only differs by returning null instead of waiting, so the model does not*) +(* tell them apart.*) +(* *) +(* Parties that run concurrently: *) +(* - the Flight SQL server, which publishes endpoints and finishes or *) +(* fails the query, and answers PollFlightInfo at any moment (a server *) +(* that does not long-poll may answer at once with nothing new); *) +(* - the poller (EndpointPoller), which chains continuations. It runs on *) +(* a pool thread, or, if the pool rejected its start or a resume, *) +(* inline on the reader's thread; *) +(* - the reader: the application thread inside ResultSet.next(), which *) +(* is inside FlightEndpointDataQueue.awaitNext, takes a ready stream, *) +(* reads it to the end (and frees its slot), ends the results, or *) +(* throws; *) +(* - another application thread that may call Statement.cancel(). *) +(* *) +(* Code map (sync commit in .claude/skills/verify-jdbc-poll-ahead/SKILL.md;*) +(* "Q" = utils/FlightEndpointDataQueue, "P" = EndpointPoller, "R" = *) +(* ArrowFlightJdbcFlightStreamResultSet, "O" = client/PollInfoOperation): *) +(* Init (poller) R.startPoller -> P.start: owned.set(true); *) +(* handBack(). The pool accepts: "running". *) +(* The pool rejects 10 submits: orphaned set, *) +(* Q.wakeReader: "orphaned", exactly as after *) +(* a rejected resume *) +(* PollerSend / PollerTake P.drive -> O.pollOnce -> O.poll *) +(* PollerApply* O.remember (inside pollOnce) and *) +(* R.appendEndpoints -> Q.addEndpoints, one *) +(* 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) *) +(* AppTake Q.awaitNext returning a ready stream to R. *) +(* The stream keeps its slot while the *) +(* application reads it *) +(* AppExhaust R.next: the application's own stream.next()*) +(* returned false -> Q.endpointExhausted -> *) +(* Q.onStreamFinished: under the lock free *) +(* the slot, reserve pending endpoints, clear *) +(* the paused flag (one step on the reader) *) +(* AppReadEmpty Q.awaitNext taking a null future (a stream *) +(* that ended inside the pool task without *) +(* rows) -> Q.onStreamFinished, same locked *) +(* step *) +(* ReaderResume the resume action Q.onStreamFinished runs *) +(* AFTER unlocking: P.resume (claim owned, *) +(* resubmit; 10 rejected submits orphan P) *) +(* AppIdle, ReaderWait, Q.awaitNext, empty-futures branch: end, *) +(* AppEnd, AppThrow idle hook (P.runInlineIfOrphaned), or wait *) +(* InlineExit P.runInlineIfOrphaned returning *) +(* PollerApplyHandBack P.drive(true) -> handBack after an answer *) +(* that added endpoints (submit, or orphaned) *) +(* CancelOp, AppCancel, Statement.cancel: O.cancel first (an open *) +(* CancelStop poll ends CANCELLED), then R.cancel: the *) +(* cancelled flag, then P.stop + O.cancel + *) +(* Q.close *) +(* PollerCrash P.runOnPool / P.runInlineIfOrphaned catch *) +(* any Throwable -> P.fail -> Q.fail; also *) +(* the answer-validation failures *) +(* PollerSeesFail, PollerDrop P.drive loop top and the check after the *) +(* poll *) +(* *) +(* The implementation corresponds to EagerOpen = FALSE (a Q built with *) +(* maxOpen = pollInfoPrefetch, which must be >= 1). A result whose first *) +(* answer has no continuation uses an unlimited eager queue and never *) +(* starts a poller; the model does not cover it. There is no fallback that *) +(* polls inside next(): a poller the pool did not accept is orphaned. *) +(* *) +(* Rows are abstracted: an endpoint is taken (AppTake, its first batch *) +(* reaches the application) and later read to the end (AppExhaust, which *) +(* frees its slot); nothing in between is tracked. Endpoint i is the i-th *) +(* endpoint the server publishes; PollInfo is cumulative, so an answer is *) +(* just how many endpoints exist so far. An endpoint is either empty (no *) +(* rows: its future yields null, AppReadEmpty) or not. *) +(***************************************************************************) +EXTENDS Naturals + +CONSTANTS + N, \* most endpoints the query can publish + Limit, \* pollInfoPrefetch: the poller polls only while queued, unread endpoints < Limit + EagerOpen, \* TRUE: every enqueued endpoint takes a stream slot at once (the proposal as first written) + IdleFix, \* TRUE: the code (awaitNext clears idleTried after a wait and after every consumed + \* future, dadd45d8a); FALSE: the stale-idle bug, kept to show that the model catches it + Mutation \* "none", or the name of a deliberately broken variant (see run.sh) + +VARIABLES + published, \* endpoints the server has published + server, \* "running" | "done" | "failed" + 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" (at the top of its loop) | "polling" | "received" | "backoff" + \* | "paused" | "pausing" | "orphaned" | "finished" | "failed" | "stopped" + \* | "dead" | "unused" (rejectedStartUnused only) + lastEmpty, \* the last applied answer added no endpoints while the query was running + waited, \* a backoff has elapsed since that empty answer + sawFull, \* pauseNotAtomic only: the poller saw the limit reached and has not paused yet + rd, \* the reader: "run" (top of the awaitNext loop) | "resume" | "waiting" | "inline" + idleTried, \* awaitNext's local idleTried flag + held, \* the application holds a stream (currentEndpointData) that still has its slot + spent, \* lateRelease only: streams the application finished, slot not freed yet + app, \* "reading" | "ended" | "threw" + failSeen, \* the queue recorded a failure + opCancelled, \* Statement.cancel called PollInfoOperation.cancel: an open poll ends CANCELLED + cancelled, \* ResultSet.cancelled: next() throws from now on + gated, \* cancel finished: poller stopped, operation cancelled, queue closed + badApply, \* addEndpoints queued endpoints on a queue that had already failed + badRow, \* a row was handed to the application after a failure or cancel + badPoll, \* a poll was sent after cancel finished + polledAtLimit, \* a poll was sent while queued, unread endpoints were at the limit + resent, \* a continuation was sent twice + spun \* a poll was sent right after an empty answer, without backoff + +srvV == <> +qV == <> +rpcV == <> +polV == <> +rdV == <> +appV == <> +flag5 == <> +flagV == <> + +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 \* pending + open-unread (a held stream is still open-unread) +Futs == opened - read - (IF held THEN 1 ELSE 0) \* futures in the completion queue +NoFutures == Futs = 0 \* the queue's `futures` map is empty +NothingQueued == known = opened /\ resv = 0 \* pending empty and opening == 0 + +\* The reader is woken (signalAll) only if it is waiting; then it clears its idle flag. +WakeRd == /\ rd' = IF rd = "waiting" THEN "run" ELSE rd + /\ idleTried' = IF rd = "waiting" THEN FALSE ELSE idleTried + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +Init == + /\ 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 + /\ resp = NoAnswer + /\ got = NoAnswer + \* P.start: the pool accepts the task ("running") or rejects it and the poller is orphaned, + \* the state a rejected resume leaves too. Broken variant rejectedStartUnused: a rejected + \* start leaves the poller stopped and unused, nobody runs it ("unused"). + /\ poller \in {"running", IF Mutation = "rejectedStartUnused" THEN "unused" ELSE "orphaned"} + /\ lastEmpty = FALSE + /\ waited = FALSE + /\ sawFull = FALSE + /\ rd = "run" + /\ idleTried = FALSE + /\ held = FALSE + /\ spent = 0 + /\ app = "reading" + /\ failSeen = FALSE + /\ opCancelled = FALSE + /\ cancelled = FALSE + /\ gated = FALSE + /\ badApply = FALSE + /\ badRow = FALSE + /\ badPoll = FALSE + /\ polledAtLimit = FALSE + /\ resent = FALSE + /\ spun = 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. +\* Once Statement.cancel has cancelled the operation's context (opCancelled, which comes before +\* R.cancel sets `cancelled`), the open poll ends with CANCELLED. +SrvAnswer == + /\ inflight + /\ ~resp.has + /\ resp' = IF opCancelled \/ gated \/ server = "failed" + THEN [has |-> TRUE, count |-> 0, more |-> FALSE, err |-> TRUE] + ELSE [has |-> TRUE, count |-> published, more |-> server = "running", err |-> FALSE] + /\ inflight' = FALSE + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +(* Poller (EndpointPoller.drive, on the poller pool or inline on the reader) *) + +\* Poll the held continuation, after pauseIfFull said no. +PollerSend == + /\ poller = "running" + /\ contHeld + /\ ~inflight + /\ Mutation = "noLimit" \/ Unread < Limit + /\ inflight' = TRUE + /\ poller' = "polling" + /\ contUsed' = TRUE + /\ resent' = (resent \/ contUsed) + /\ spun' = (spun \/ (lastEmpty /\ ~waited)) + /\ badPoll' = (badPoll \/ gated) + /\ polledAtLimit' = (polledAtLimit \/ Unread >= Limit) + /\ waited' = FALSE + /\ UNCHANGED <> + +\* Q.pauseIfFull: at the limit, the poller sets the paused flag and gives its thread back. +\* The count check, the flag and P's owned=false are one step under the queue lock. +\* 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 + /\ pflag' = TRUE + /\ poller' = IF Mutation = "ownedClearedLate" THEN "pausing" ELSE "paused" + /\ sawFull' = FALSE + /\ 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 <> + +\* 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; the +\* operation's own cancel/terminate RPC runs afterwards and is not modeled). An answer to a poll +\* that Statement.cancel ended (opCancelled, but P.stop and Q.close have not run yet) is recorded +\* as a failure too: the failure mapper turns it into "Statement canceled". +PollerTake == + /\ poller = "polling" + /\ resp.has + /\ resp' = NoAnswer + /\ IF resp.err + THEN /\ poller' = "failed" + /\ failSeen' = TRUE + /\ contHeld' = FALSE + /\ 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' = "received" + /\ more' = IF Mutation = "finishBeforeEnqueue" /\ ~resp.more THEN FALSE ELSE more + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* Anything unexpected ends the poller (a RuntimeException or an Error from the RPC layer or the +\* sink, a protocol violation in an answer, an interrupted backoff): P.runOnPool and +\* P.runInlineIfOrphaned catch every Throwable and fail the queue (P.fail -> Q.fail). The poller +\* never keeps a half-applied answer. Broken variant errorNotReported: only a RuntimeException +\* failed the queue, an Error silently killed the pool thread (the poller is "dead"). +PollerCrash == + /\ poller \in {"running", "polling", "received", "backoff"} + /\ IF Mutation = "errorNotReported" + THEN /\ rd # "inline" + /\ poller' = "dead" + /\ UNCHANGED <> + ELSE /\ poller' = "failed" + /\ failSeen' = TRUE + /\ rd' = IF rd \in {"waiting", "inline"} THEN "run" ELSE rd + /\ idleTried' = IF rd \in {"waiting", "inline"} THEN FALSE ELSE idleTried + /\ contHeld' = FALSE + /\ inflight' = FALSE + /\ resp' = NoAnswer + /\ got' = NoAnswer + /\ UNCHANGED <> + +\* Slots addEndpoints can reserve: fewer than Limit streams open or opening and unread. +\* EagerOpen: every new endpoint takes a slot at once. +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. On a failed queue it is a +\* no-op: nothing is queued or opened, the reader rethrows the failure (broken variant +\* applyAfterFail: the old code queued and reserved anyway). +ApplyQ == + /\ got.has + /\ poller = "received" + /\ IF failSeen /\ Mutation # "applyAfterFail" + THEN /\ UNCHANGED <> + ELSE /\ enq' = [i \in 1..N |-> + IF i >= (IF Mutation = "enqueueWholeList" THEN 1 ELSE known + 1) + /\ i <= got.count + THEN Min(enq[i] + 1, 2) ELSE enq[i]] + /\ known' = got.count + /\ resv' = resv + ApplyRsv + /\ more' = got.more + /\ badApply' = (badApply \/ failSeen) + /\ got' = NoAnswer + +\* An answer that adds nothing while the query runs: back off, then poll again. +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 <> + +\* A stopped poller discards the answer to the poll that cancel interrupted. +PollerDrop == + /\ poller = "stopped" + /\ resp.has + /\ resp' = NoAnswer + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +(* 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. On a failed or closed queue + openReserved stops opening and register() drops a stream that was already open: either way the + reservation is released and no stream is registered. *) + +OpenReserved == + /\ resv > 0 + /\ resv' = resv - 1 + /\ opened' = IF failSeen \/ gated THEN opened ELSE 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 <> + +----------------------------------------------------------------------------- +(* The reader: ResultSet.next() inside Q.awaitNext, and the application between calls *) + +\* onStreamFinished, the part under the lock: free the slot, reserve pending endpoints for +\* opening, and clear the paused flag if unread endpoints are below the limit. The resume +\* action runs after unlocking (ReaderResume). A failed or closed queue has no pending endpoints +\* (fail() and close() clear them). +ReadFree == + LET read1 == read + 1 + pend == IF failSeen \/ gated THEN 0 ELSE known - opened - resv + free == Max(0, Limit - (opened - read1) + - (IF Mutation = "openNotReserved" THEN 0 ELSE resv)) + rsv == IF EagerOpen THEN 0 ELSE Min(pend, free) + 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" + +\* awaitNext returns a ready stream (a future with rows) to the application. The stream keeps its +\* slot (openUnread) until the application has read it to the end (AppExhaust). Rows reach the +\* application from here on; later next() calls start with the cancelled and failure checks. +AppTake == + /\ app = "reading" + /\ rd = "run" + /\ ~held + /\ Futs - spent > 0 + /\ (Mutation = "readAfterFail" \/ (~failSeen /\ ~cancelled)) + /\ held' = TRUE + /\ badRow' = (badRow \/ failSeen \/ cancelled) + /\ idleTried' = FALSE + /\ UNCHANGED <> + +\* R.next: the application's own stream.next() returned false. It frees the slot at once, on the +\* application thread, under the queue lock (Q.endpointExhausted -> onStreamFinished): read and +\* free are one step. The resume action runs after unlocking (ReaderResume). Broken variant +\* lateRelease is the old code: the stream was re-enqueued and the slot was freed only when a +\* later awaitNext consumed its null future, in completion order. +AppExhaust == + /\ app = "reading" + /\ rd = "run" + /\ held + /\ held' = FALSE + /\ IF Mutation = "lateRelease" + THEN /\ spent' = spent + 1 + /\ UNCHANGED <> + ELSE /\ spent' = spent + /\ ReadFree + /\ UNCHANGED <> + +\* Take a null future (a stream that ended inside the pool task without rows) and finish it. +\* awaitNext loops without returning to the application. The code clears idleTried right after +\* onStreamFinished (IdleFix); without it the flag would stay set (the bug fixed in dadd45d8a). +\* In the lateRelease variant the null future may be the one of a stream the application finished. +AppReadEmpty == + /\ app = "reading" + /\ rd = "run" + /\ ~held + /\ Futs > 0 + /\ ~failSeen /\ ~cancelled + /\ \/ spent > 0 /\ spent' = spent - 1 + \/ Futs > spent /\ spent' = spent + /\ 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" + /\ ~held + /\ ~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" + /\ ~held + /\ ~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" + /\ ~held + /\ ~failSeen + /\ ~cancelled + /\ NoFutures + /\ known = opened + resv + /\ (resv = 0 \/ Mutation = "endIgnoresOpening") + /\ (~more \/ Mutation = "endWhenQueueEmpty") + /\ app' = "ended" + /\ UNCHANGED <> + +\* next() throws: the top-of-call checks of `cancelled` and queue.failure(), or awaitNext's +\* checkOpen and throwIfFailed. The application may hold a stream while it does. +AppThrow == + /\ app = "reading" + /\ rd = "run" + /\ failSeen \/ cancelled + /\ app' = "threw" + /\ UNCHANGED <> + +\* Statement.cancel, step 0: PollInfoOperation.cancel. An open poll ends with CANCELLED and no +\* new RPC starts. This runs before R.cancel sets `cancelled`, so the poller can record the ended +\* poll as the queue failure "Statement canceled" first. +CancelOp == + /\ app = "reading" + /\ ~opCancelled + /\ opCancelled' = TRUE + /\ UNCHANGED <> + +\* R.cancel, step 1: the cancelled flag. next() throws from the next call on. +AppCancel == + /\ app = "reading" + /\ ~cancelled + /\ cancelled' = TRUE + /\ UNCHANGED <> + +\* 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 + /\ opCancelled' = TRUE + /\ poller' = IF poller \in {"finished", "failed"} \/ Mutation = "cancelIgnoresPoller" + THEN poller ELSE "stopped" + /\ contHeld' = IF Mutation = "cancelIgnoresPoller" THEN contHeld ELSE FALSE + /\ WakeRd + /\ 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 \/ PollerPauseEnd \/ PollerSeesFail + \/ PollerTake \/ PollerCrash \/ PollerApplyBackoff \/ PollerApplyGo \/ PollerApplyHandBack + \/ PollerApplyFinish \/ BackoffElapses \/ PollerDrop + \/ OpenReserved \/ OpenFails + \/ AppTake \/ AppExhaust \/ AppReadEmpty \/ ReaderResume \/ ReaderResumeRejected \/ AppIdle + \/ InlineExit \/ ReaderWait \/ AppEnd \/ AppThrow \/ CancelOp \/ AppCancel \/ CancelStop + \/ Done + +\* The server eventually finishes; the driver, the cancel call and the application keep going. +\* A started Statement.cancel always reaches R.cancel. +Fairness == + /\ WF_vars(SrvComplete) /\ WF_vars(SrvAnswer) + /\ WF_vars(PollerSend) /\ WF_vars(PollerPause) /\ WF_vars(PollerPauseEnd) + /\ 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(AppTake \/ AppReadEmpty) /\ WF_vars(AppExhaust) + /\ WF_vars(ReaderResume \/ ReaderResumeRejected) + /\ WF_vars(AppIdle) /\ WF_vars(InlineExit) /\ WF_vars(ReaderWait) + /\ WF_vars(AppEnd) /\ WF_vars(AppThrow) /\ WF_vars(AppCancel /\ opCancelled) + /\ WF_vars(CancelStop) + +Spec == Init /\ [][Next]_vars /\ Fairness + +----------------------------------------------------------------------------- +(* Rules *) + +TypeOK == + /\ published \in 1..N + /\ server \in {"running", "done", "failed"} + /\ read + (IF held THEN 1 ELSE 0) <= opened /\ opened + resv <= known /\ known <= published + /\ held \in BOOLEAN /\ spent \in 0..N /\ spent <= Futs + /\ gated => opCancelled + /\ enq \in [1..N -> 0..2] + /\ resp \in Answer /\ got \in Answer + /\ poller \in {"running", "polling", "received", "backoff", "paused", "pausing", + "orphaned", "finished", "failed", "stopped", "dead", "unused"} + /\ 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 + +\* 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 has finished (stopped, operation cancelled, queue closed). +CancelStopsPolling == ~badPoll + +\* The poller never polls while queued, unread endpoints are at the limit. +Backpressure == ~polledAtLimit + +\* No slot stays held by a stream the application has read to the end while the application reads +\* another one: the poller and the pending endpoints must not wait for a finished stream. +SlotFreedOnExhaust == ~(held /\ spent > 0) + +\* A failed queue takes nothing more: addEndpoints queues and opens nothing after a failure. +FailedQueueInert == ~badApply + +\* Open, opening and unread DoGet streams never exceed the limit. +OpenWithinLimit == opened + resv - read <= Limit + +\* 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..c91a537936 --- /dev/null +++ b/formal/pollinfo-poll-ahead/run.sh @@ -0,0 +1,102 @@ +#!/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 (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 +# 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/" + +# The rules before the slot-release change (4b831553c): no rule says when a finished stream's slot is freed. +OLD_RULES="TypeOK InlineMeansPoller EachEndpointOnce ContinuationsOnce NoPrematureEnd FailFast CancelStopsPolling Backpressure NoSpin OpenWithinLimit" +SAFE="TypeOK InlineMeansPoller EachEndpointOnce ContinuationsOnce NoPrematureEnd FailFast CancelStopsPolling Backpressure NoSpin SlotFreedOnExhaust FailedQueueInert" +ALL="$SAFE OpenWithinLimit" +unexpected=0 + +# check NAME EAGER_OPEN IDLE_FIX MUTATION "INVARIANTS" LIVENESS(yes|no) EXPECT(pass|invariant:Name|deadlock|liveness) NOTE +check() { + 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 IdleFix = $idlefix 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 (IdleFix = TRUE is the code: awaitNext clears idleTried after every consumed future)" +echo "(every check starts the poller either accepted by the pool or rejected, which leaves it orphaned)" +check proposal-as-written TRUE TRUE none "$SAFE" yes pass "streams open as soon as endpoints are enqueued" +check finding-open-streams TRUE TRUE none "OpenWithinLimit" no invariant:OpenWithinLimit "KNOWN FINDING: one answer can add more streams than the limit" +check deferred-open FALSE TRUE none "$ALL" yes pass "the code as written: every safety rule and Terminates hold" +echo +echo "Broken variants (each must fail on the rule it targets; the idle fix is on, so only the variant is at fault," +echo "except staleIdle, which turns the idle fix off: the bug fixed in dadd45d8a)" +check endWhenQueueEmpty FALSE TRUE endWhenQueueEmpty "$ALL" no invariant:NoPrematureEnd "next() ends when the queue is empty" +check endIgnoresOpening FALSE TRUE endIgnoresOpening "$ALL" no invariant:NoPrematureEnd "end test forgets streams still opening" +check finishBeforeEnqueue FALSE TRUE finishBeforeEnqueue "$ALL" no invariant:NoPrematureEnd "moreExpected cleared before the final endpoints are queued" +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" +check staleIdle FALSE FALSE none "$SAFE" yes liveness "idleTried not cleared after a consumed future (rejected resume strands next())" +check lateRelease FALSE TRUE lateRelease "$ALL" no invariant:SlotFreedOnExhaust "slot freed only when a later awaitNext consumes the null future, not when the application finishes the stream" +check applyAfterFail FALSE TRUE applyAfterFail "$ALL" no invariant:FailedQueueInert "addEndpoints queues and reserves on a queue that already failed" +check errorNotReported FALSE TRUE errorNotReported "$ALL" yes liveness "an Error kills the poller thread without failing the queue (next() waits forever)" +check rejectedStartUnused FALSE TRUE rejectedStartUnused "$ALL" yes liveness "a rejected poller start leaves the poller unused instead of orphaned (next() waits forever)" +echo +echo "Gap check: lateRelease passes every rule that existed before SlotFreedOnExhaust. The late release is a progress" +echo "problem (a finished stream blocks the poller), not a safety or termination one, and only the new rule sees it." +check lateRelease-old-rules FALSE TRUE lateRelease "$OLD_RULES" yes pass "NOT a bug in the model: shows what the old rule set could not express" + +echo +if [ "$unexpected" -eq 0 ]; then echo "All checks matched their expectations."; else echo "Some checks did not match. See above."; fi +exit "$unexpected" diff --git a/pom.xml b/pom.xml index 6b70f92415..506f62c37d 100644 --- a/pom.xml +++ b/pom.xml @@ -98,7 +98,7 @@ under the License. 6.1.3 2.0.20 33.8.0-jre - 4.2.20.Final + 4.2.21.Final 1.85.1 4.36.2 2.23.0 @@ -111,9 +111,9 @@ under the License. 2 10.23.0 true - 2.52.0 + 2.53.0 4.4.0 - 1.6.6 + 1.6.8 none -Xdoclint:none @@ -520,7 +520,7 @@ under the License. org.codehaus.mojo versions-maven-plugin - 2.25.1 + 2.25.2 io.github.git-commit-id diff --git a/reports/call-site-inventory.md b/reports/call-site-inventory.md new file mode 100644 index 0000000000..db3c346008 --- /dev/null +++ b/reports/call-site-inventory.md @@ -0,0 +1,29 @@ +# 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. + +| # | 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..3fab5a4f11 --- /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","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 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 -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 new file mode 100644 index 0000000000..d6ddb433ca --- /dev/null +++ b/reports/jdbc-report.md @@ -0,0 +1,196 @@ +# 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** + +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 is published for review on branch `bdx-645-pollinfo-poc` in `xborder/arrow-java` PR #21. + +## 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. 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. + +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. + +## Request flow + +```mermaid +sequenceDiagram + participant App as JDBC application + participant Driver as JDBC driver + participant Server as Flight SQL server + 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 +``` + +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 + +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 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 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 progressive changes: 1,269 tests, zero failures/errors, 56 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; 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,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 | + +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 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 + +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/` diff --git a/reports/poll-ahead-implementation-plan.md b/reports/poll-ahead-implementation-plan.md new file mode 100644 index 0000000000..f2ce1f3320 --- /dev/null +++ b/reports/poll-ahead-implementation-plan.md @@ -0,0 +1,108 @@ +# BDX-645 JDBC poll-ahead: implementation plan + +> **Revision (2026-11-26).** The first POC's reader-side polling is removed (`b19d8370a`). Every progressive result with a continuation gets an `EndpointPoller`. A busy poller pool leaves the poller orphaned, and the reader runs it inline when it would otherwise wait. `pollInfoPrefetch` must be `-1` or positive. Behavior 2 and 9, the configuration table and U1/U2 below are updated to match. + +Goal: during progressive `PollFlightInfo` execution, poll continuations in the background while the application reads, without changing the JDBC API. The design was agreed in review and model-checked in `formal/pollinfo-poll-ahead/` (skill: `.claude/skills/verify-jdbc-poll-ahead/SKILL.md`). The implementation must match the model's **deferred-open** configuration (`EagerOpen = FALSE`). + +All paths below are relative to `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/` unless shown in full. + +## Behavior + +1. `executeQuery` is unchanged. It polls until the first endpoint exists and returns the `ResultSet`. +2. If a continuation is pending, the `ResultSet` hands it to an `EndpointPoller`. If the poller pool rejects the task, the poller starts orphaned: the reader runs it inline, through the queue's idle hook, when it would otherwise wait, and hands it back to the pool after an answer adds endpoints. There is no other polling path. +3. The poller polls the held continuation once, in the execution's `PollInfoOperation` context (one deadline, one cancel). It checks append-only, queues only the appended endpoints, and continues with the next continuation. +4. Backpressure: + - The poller does not poll while queued, unread endpoints (opened-unread plus not-yet-opened) are at or above the limit. It pauses and holds no thread. + - 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. Unlimited eager queue: a first answer that is already complete (no continuation) uses the queue without an open limit, so every endpoint opens at once, as it always did. The limit applies only while a poller exists. +10. Metadata calls, `executeQuery`'s first poll, the `UNIMPLEMENTED` fallback, and `usePollInfo=false` are unchanged. + +## Configuration (connection properties) + +| Property | Type | Default | Meaning | +| --- | --- | --- | --- | +| `pollInfoPrefetch` | number | `-1` = auto: `max(2, threadPoolSize)` | Most queued, unread endpoints. The poller polls only below it, and streams open only below it. Must be `-1` or positive; other values are rejected when the connection is created. | +| `pollInfoPollerThreads` | number | `4` | Size of the connection's poller pool. When all threads are busy, a new result's poller runs inline on the reader until a pool thread is free. | +| `pollInfoMaxBackoffMs` | number | `5000` | Longest wait between answers that add nothing. | + +Deviation from the review decision: the review set the prefetch default to `threadPoolSize`, but `threadPoolSize` defaults to 1. A limit of 1 never polls while an endpoint is being read, so the default is `max(2, threadPoolSize)`. Follow the naming and type conventions of the existing properties in `utils/ArrowFlightConnectionConfigImpl.java`. If they use a different suffix for durations, use theirs and record the name here. + +## 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~~ Removed in the revision, with the fallback path. + - Keep `validateAppendOnly`. +- New `EndpointPoller` (package `org.apache.arrow.driver.jdbc`, package-private), started by the result set. + - States: running, polling, paused, backoff, finished, failed, stopped. + - 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. + - A rejected start orphans the poller (revision; the POC path for prefetch `0` or a rejected submit was removed). Keep cancel and close semantics. +- Keep every existing test green. Tests that asserted the POC request order (`Poll, DoGet, Poll, DoGet`) were rewritten in the revision to assert poll-ahead behavior, with answers gated where order matters. +- Do not change the TLA+ model. + +### U2. Unit tests (after U1) + +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.~~ Revision: `pollInfoPrefetch=0` is rejected when the connection is created. +11. Poller pool busy (`pollInfoPollerThreads=1`, two concurrent results): the second result's poller runs inline on the reader, is handed back to the pool once a thread is free, and both return correct rows. +12. `FlightEndpointDataQueue` unit tests for deferred open, wait-for-more, fail, and close. + +### U3. End-to-end tests against the conformance server (after U2 and the server additions) + +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. diff --git a/reports/production-recommendation.md b/reports/production-recommendation.md new file mode 100644 index 0000000000..2d8f72dca5 --- /dev/null +++ b/reports/production-recommendation.md @@ -0,0 +1,156 @@ +# 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 works, and since 2026-11-26 a background poller fetches continuations while the application reads (see "Poll-ahead" below). + +The branch has been rebased onto current upstream `main` (see "Rebase onto upstream main" below). It is still not ready to merge, because of the public API: + +1. **The public API surface is accidental.** The POC adds a protected `FlightSqlClient.getInfo(FlightDescriptor, CallOption...)` in the published `flight-sql` artifact. That method can collide with subclasses that already exist downstream. It also adds a public `PollInfoOperation` and public handler and builder methods in `flight-sql-jdbc-core`. All of this needs an intentional design and an upstream Apache discussion before it lands. + +Contract item 12 (a delay between answers that add nothing) was missing from the first POC. It is now implemented: the poller waits 100 ms after such an answer, doubling up to `pollInfoMaxBackoffMs` (default 5000), never past the deadline. Cancel and close end the wait. + +## Documented limitations (behavioral) + +- **Late errors move to `ResultSet.next()`.** In progressive mode, `executeQuery` returns once the first endpoint is published. A query that fails afterwards raises `SQLException` from `next()`, not from `executeQuery`. JDBC allows this, but applications that treat a successful `executeQuery` as a successful query will see different behavior. With poll-ahead the failure is found in the background, so it can also be thrown before the first row is read: buffered rows are dropped and the next `next()` throws. Production needs an explicit decision here, because the ticket rules out an opt-in: either progressive by default, or final-only by default with progressive behind a property. +- **The deadline excludes schema preparation.** The single deadline and cancellable context cover the parameter `DoPut`, every poll and the first endpoint wait. They do not cover the earlier schema/prepare action. +- **CancelFlightInfo needs a payload.** Best-effort `CancelFlightInfo` is only possible after at least one `PollInfo` has returned a `FlightInfo`. Cancelling a blocked initial poll terminates the RPC but sends no server-side cancel. +- **Cleanup is synchronous.** The cancel cleanup call is bounded to one second, but it runs on the caller's thread. A slow server can delay the delivery of a timeout or cancel by up to that second. +- **The capability cache is scoped to the handler.** Unsupported families are cached per `ArrowFlightSqlClientHandler`, keyed by Flight SQL command `type_url`. Pooled or reused physical connections have not been tested. +- **Poll-ahead uses threads per connection.** Each connection can start up to `pollInfoPollerThreads` (default 4) daemon poller threads. When they are all busy, a new result's poller runs inline on the application's thread inside `next()` until a pool thread is free. Several results sharing one pool are covered by unit tests, not by the model. +- **The opt-out name differs from the ticket.** The ticket suggested `usePollFlightInfo=false`; the POC implements `usePollInfo=false`. Pick one name before release and document it. + +## GetFlightInfo call-site coverage + +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).~~ Done with poll-ahead (`PollBackoff`). + +### JDBC (`flight-sql-jdbc-core`) +4. Replace the POC's `ArrowFlightStatement` → prepared-delegate lookup through `statementMap` (used for cancel, timeout and operation lookup on the `Statement.execute(String)` path) with an explicit owner reference. +5. Make `PollInfoOperation` and the handler and builder additions package-private. Keep only the documented connection property. +6. Decide the default behavior for late errors (progressive or final-only). Decide whether the operation deadline should start at `prepareAndExecute` entry so that it includes schema preparation. +7. Run best-effort `CancelFlightInfo` off the caller's thread, or with a tighter bound, so it can never delay a timeout or cancel. +8. Add tests for pooled connections and the family cache. Races between cancel, close and an in-flight poll are now covered by the poll-ahead tests and the model. +9. Add PollInfo black-box scenarios for at least one more metadata family (for example `getTables`) once the fixture supports it. +10. Keep the POC's regression tests: direct select and update, OAuth on `POLL_FLIGHT_INFO`, the exact timeout message, prepared single-bind, pre-`ResultSet` cancel, and close of an incomplete result. + +## Poll-ahead (2026-11-26) + +The first POC polled the next continuation only after the application had read every published endpoint, so endpoints were found and downloaded one at a time. Poll-ahead removes that wait without changing the JDBC API. The design was agreed in review, model-checked before it was written, and implemented from [`poll-ahead-implementation-plan.md`](poll-ahead-implementation-plan.md). + +- `executeQuery` is unchanged: it returns once the first endpoint exists. +- An `EndpointPoller` on the connection's poller pool then polls each continuation once, in the same operation (one deadline, one cancel), checks append-only, and queues only the new endpoints. +- Backpressure: the poller pauses while unread endpoints reach `pollInfoPrefetch`, and holds no thread while paused. Streams open only while fewer than the limit are open and unread. The reader frees a slot and resumes the poller when it finishes an endpoint. +- Backoff as described above. +- Fail fast: a failed continuation closes every stream, drops buffered batches, and makes the next `next()` throw, with the existing exception mapping. +- Cancel, the deadline, and closing an unfinished result stop the poller and send `CancelFlightInfo` once. +- Every result with a continuation has a poller. If the poller pool is busy, the poller starts orphaned: the reader runs it inline when it would otherwise wait, and hands it back to the pool after an answer adds endpoints. The first POC's reader-side polling path was removed in `b19d8370a`. A first answer that is already complete opens every endpoint at once, as before. + +| Property | Default | Meaning | +| --- | --- | --- | +| `pollInfoPrefetch` | `-1` = `max(2, threadPoolSize)` | Most queued, unread endpoints. Must be `-1` or positive; `0` is rejected when the connection is created. | +| `pollInfoPollerThreads` | `4` | Size of the connection's poller pool. | +| `pollInfoMaxBackoffMs` | `5000` | Longest wait between answers that add nothing. | + +The review set the prefetch default to `threadPoolSize`, but `threadPoolSize` defaults to 1, and a limit of 1 never polls while an endpoint is being read. + +Verification: + +- **Model.** `formal/pollinfo-poll-ahead/PollAhead.tla`, checked with TLC 2.19 by `run.sh`: 23 checks match at 3 and 4 endpoints, including a broken variant for each rule. The poller may start on the pool or orphaned (pool busy), and both starts are checked. How to recheck after a change: `.claude/skills/verify-jdbc-poll-ahead/SKILL.md`. +- **Bugs found before release.** The model found a hang after a rejected poller resume (`dadd45d8a`). A code review found a late slot release that made poll-ahead fall back to the first POC's timing, plus error, fallback and cancel edge cases (`4b831553c`). The tests found a raw `CANCELLED` error leaking from `next()` (`dadd45d8a`) and a lost `CancelFlightInfo` when the connection closed right after a deadline failure (`436156f29`). +- **Tests.** `PollAheadTest` (36 runs), `FlightEndpointDataQueueDeferredOpenTest` (26), `EndpointPollerTest` (1) and `PollBackoffTest` (6) against scripted mock servers, and `SharedServerPollAheadTest` (12) against the conformance server's poll-ahead scenarios (`burst`, `trickle`, `empty-answers`, `late-error-buffered`), which check the server's maximum concurrent streams, poll timing against held streams, backoff gaps and cancellation. Existing tests that asserted the first POC's exact request order now assert poll-ahead behavior, with answers held back where order matters. + +Not covered by the model: `executeQuery`'s first poll, the `UNIMPLEMENTED` fallback, metadata, several results sharing one pool, and backoff timing. + +## 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. + +## Re-validation with poll-ahead (2026-11-26) + +Same environment. Conformance server at commit `5d0d11c` (adds the poll-ahead scenarios, holds and counters) on Flight `127.0.0.1:31337` and control `127.0.0.1:31338`. Use path-style `-Dtest` patterns so top-level test classes are included: + +```sh +mvn -pl flight/flight-sql,flight/flight-sql-jdbc-core -am install \ + -Dtest='org/apache/arrow/flight/sql/**/*.java,org/apache/arrow/driver/jdbc/**/*.java' -Dsurefire.failIfNoSpecifiedTests=false \ + -Dpollinfo.shared.enabled=true -Dpollinfo.shared.flightPort=31337 -Dpollinfo.shared.controlPort=31338 \ + -Dmaven.gitcommitid.skip=true +formal/pollinfo-poll-ahead/run.sh && N=4 formal/pollinfo-poll-ahead/run.sh +``` + +| Run | Result | +| --- | --- | +| Flight SQL suite | 97/97 | +| JDBC core suite, shared-server tests enabled | 1,456 run, 0 failures, 49 skipped (after removing the first POC's path in `b19d8370a`) | +| `SharedServerPollAheadTest` / `SharedServerPollInfoExecutionTest` | 12/12 and 11/11 | +| `install` (Spotless, Checkstyle, `dependency:analyze`) | passes | +| Model checks | all 23 match at N=3 and N=4 | 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/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/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/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/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()); + } + } + } +} 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 = 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 =