Skip to content

feat(qwp): add per-query timeout to the query client - #105

Merged
bluestreak01 merged 16 commits into
mainfrom
vi_query_timeout
Dec 1, 2026
Merged

bluestreak01 merged 16 commits into
mainfrom
vi_query_timeout

Conversation

@bluestreak01

@bluestreak01 bluestreak01 commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

Tandem: questdb/questdb#7768 (server side).

Purpose

Let users override the server's default query timeout (query.timeout) for a single query or for a whole connection.

Impact

  • query_timeout_ms overrides the server default for every query on the connection; Query.timeout() overrides it for one query.
  • Needs a server with feat(qwp): add per-query timeouts for queries over QWP questdb#7768; older servers keep their default.
  • Fix: the next query on a connection no longer receives rows left over from a failed or interrupted query.
  • Breaking: custom implementations of the Query interface must add timeout().

How

The client sends the timeout with the query, only to servers that advertise CAP_QUERY_TIMEOUT. The server enforces it instead of query.timeout and reports STATUS_QUERY_TIMEOUT, which QueryException.isTimeout() tests.

When execute() returns early because the handler threw or the caller was interrupted, the client cancels that query and drops its remaining results. A cancel that arrives before the pool starts the query is no longer lost.

Adds a query timeout to QwpQueryClient and the QuestDB facade:
query_timeout_ms (connection-string default), Query.timeout(...) per
handle, and an execute() overload with an explicit timeout. A timed-out
query ends with the new STATUS_QUERY_TIMEOUT (QueryException.isTimeout())
on a connection that stays open and authenticated for the next query.

- A server advertising the new CAP_QUERY_TIMEOUT (0x08) capability gets
  the remaining budget as a timeout_ms field after query_flags
  (QUERY_FLAG_TIMEOUT, 0x02) and ends the query itself with
  STATUS_QUERY_TIMEOUT (0x0E). Older servers are cancelled by the client
  at the deadline; the cancellation is reported as the same status.
- Once the deadline passes no further result batch reaches the handler.
  Discarded batches are still decoded, keeping the connection-scoped
  SYMBOL dict in step with the server.
- If the server does not end the query within the grace period
  (query_close_timeout_ms on the facade), the caller is released anyway
  and the connection drains the aborted query in the background. Only a
  connection that stays silent through a second grace period is closed.
- The deadline spans failover: replays carry the remaining budget, the
  backoff and every reconnect step are bounded by it, and a reconnect it
  cut short is retried by the next execute() instead of leaving the
  client disconnected.

Pool: Query.close() waits for a worker still draining a timed-out query
before returning it, discards a worker whose connection failed, and a
cancel issued while a submission waits behind such a drain is no longer
lost.

The server side (decoding timeout_ms, the breaker timeout, the status
mapping and the capability advert) lands in a tandem questdb PR.
A query that ended early on the client side left its remaining frames
on the connection, and the next query read them as its own result.
This fixes the three ways in.

Handler throws on a query timeout. At the end of the grace period
execute() reports the timeout through onError while the aborted query
still runs on the connection. If onError threw, execute() skipped the
drain that follows. FailoverProbeHandler now holds the exception,
executeOnce keeps draining as it does for a handler that returns, and
executeImpl rethrows the original throwable once the drain ends or the
connection is given up.

The facade worker reports an exception that escapes execute() as the
outcome of the current submission. Rethrown after the drain, it could
land after the caller, already released by the timeout, had submitted
again on the same Query, and complete that newer submission with the
old exception. QueryImpl now numbers submissions, and runOn() reports
an escaping exception only while its own submission is current. The
check and the report share doneLock with submit(). This also closes
the same race, until now microseconds wide, for a handler that throws
from onEnd or onExecDone.

Handler throws from onBatch, or the thread is interrupted. The I/O
thread now stamps every event of a query with that query's request id;
connection-level events carry QueryEvent.ANY_REQUEST and still reach
whichever query waits. executeOnce skips the events of other queries,
so the next query no longer receives the leftovers of an abandoned
one, and it handles its own deadline even while leftovers keep coming.
An attempt that ends before its query's last event now cancels that
query, so the leftovers stop coming.

While the I/O thread still works through an abandoned query, the next
query can be queued and cancelled. The I/O thread sent that CANCEL at
once, ahead of the query itself, and the server drops a cancel of a
query it does not know, so the cancel was lost. drainPendingCancel now
sends only a cancel of the query it serves, holds one of a later
query, and drops one of a query that has already ended.

Interrupt before the I/O thread encodes the request. execute()
returned while the I/O thread could still read the request holder,
the bind buffer and the caller's SQL text, and the next execute()
overwrote them: the interrupted query was never sent and the next one
was sent twice, possibly mixing the two queries' SQL and binds. With
leftovers of an abandoned query on the connection, the next execute()
could also block forever on the single request slot, while the I/O
thread waited for it to release a leftover batch. An interrupted
execute() now withdraws a request the I/O thread has not picked up
yet, or waits for the encoding the I/O thread has started, before it
reports the interrupt. An I/O thread still not done after
shutdownJoinMs gives up the connection, as on a query timeout.

Behavior visible to callers: an exception from onError at the end of
the grace period now surfaces when the drain ends, up to one more
grace period later, which is when execute() already returns for a
handler that does not throw. A handler that throws from onBatch, or
an interrupt, now cancels its query, and the next query skips that
query's leftovers instead of returning them. A handler that does not
throw sees no change, and the per-batch path gains only one field
store on the I/O thread and one comparison on the reading thread.

New tests drive each path against the scripted mock server, through
both QwpQueryClient and the QuestDB facade.
glasstiger added a commit to questdb/nodejs-questdb-client that referenced this pull request Oct 8, 2026
A query timeout rejected the caller the moment it expired, then
cancelled the query. A statement that completed just past the deadline
had taken effect but was reported as timed out, which invites a retry
that applies it twice. The Java client's per-query timeout
(questdb/java-questdb-client#105) waits for the server instead, and this
client now does the same:

- Once the timeout expires no further batch reaches the consumer and
  the query is cancelled, but the outcome waits up to one grace period,
  cancelDrainTimeoutMs, for the server's terminal response. EXEC_DONE,
  and a RESULT_END after which nothing was withheld, still succeed. A
  CANCELLED reply, or a result that lost a batch to the timeout,
  rejects with QwpEgressQueryTimeoutError. A server still silent after
  the grace period releases the caller with the timeout, and the
  session gives the connection up one period later.
- The timeout runs from the query() call, so waiting for SERVER_INFO,
  for a previous query to drain or for a reconnect counts against it.
  A request whose timeout expires while a reconnect holds it is
  released at the deadline and never sent.
- On a lost connection, a query past its timeout or whose consumer has
  retired is settled at once instead of being replayed only to be
  cancelled, and the cancel drain no longer runs without a connection.
  A reconnect longer than cancelDrainTimeoutMs used to fail the session.
- A cancel the application issued before the timeout is reported as a
  cancellation, a query sends at most one CANCEL, and query() waits for
  a released query to finish draining instead of throwing "a QWP query
  is already active", which it did even right after breaking out of
  for await.

The reconnecting egress connection now tells the session when it loses
its connection, lets it drop a query from the replay and withdraw a
request a reconnect still holds, and reports whether a terminal
response is still queued: one that arrived before the connection went
still decides the outcome.

The session tests cover each outcome past the deadline, both grace
periods, withheld materialized batches and views, an application
cancel, the single CANCEL, the clock starting at query() and the wait
behind a drain. The reconnect tests cover a timeout during an outage, a
connection lost during the grace period, a draining query, a replayed
application cancel, a terminal queued before the loss and a withdrawn
request. README.md and QWP.md describe the behaviour, and
query_close_timeout_ms is documented as the grace period too.

The timeout is still enforced by the client alone; sending it to the
server waits for questdb/questdb#7768.

BREAKING CHANGE: a timed-out query is reported when the server ends it
or after cancelDrainTimeoutMs, rather than at the deadline; a statement
that completes past its timeout succeeds; the timeout includes the wait
before the request is sent; and query() waits for a query that is still
draining instead of throwing.
… acks

TestWebSocketServer.ClientHandler.close(), called from a handler callback
to script "ack N frames, then drop the wire", closed the socket while the
client's pipelined frames were still unread. Linux then aborts the
connection with an RST and discards everything not yet transmitted,
including the acks the handler had just written (byte at a time, with
Nagle on, so usually still queued). The client saw ECONNRESET without the
acks. That made BackgroundDrainerMidDrainCapabilityGapTest
.testDeliveringBetweenTwoGapWindowsGrantsAFreshSettleBudget fail
intermittently in CI: with no durable-ack progress the settle budget
never reset and the drainer quarantined the slot (FAILED, attempts=20).

close() also joined its own read thread for 5s while the caller held the
synchronized handler's monitor, stalling every other connection.

A drop from the read thread now half-closes (shutdownOutput, so the FIN
queues behind every frame already written), skips the self-join, and the
read thread drains the client until it hangs up before closing the
socket. Closing from any other thread is unchanged.

TestWebSocketServerHandlerDropTest forces the race deterministically
(unread inbound bytes plus acks queued behind a full client window). On
Linux it fails without the fix with "framesReceived=0 of 2: Connection
reset". In a stress run the original test failed 6/90 before the fix and
0/900 after; test classes that script drops lose their 5s stalls.
TestWebSocketServerHandlerDropTest sends a hand-written WebSocket upgrade
request with the example Sec-WebSocket-Key from RFC 6455 section 1.3
(base64 of "the sample nonce"). Gitleaks' generic-api-key rule reads
"...Key: <high-entropy token>" as a hardcoded API key and fails the PR.

Add a .gitleaks.toml that extends the default config and allowlists only
that exact value. All default rules stay active, and any other value in
the same header is still reported. An allowlist in config is used instead
of a .gitleaksignore fingerprint because fingerprints embed the commit SHA
and stop matching after a squash merge.
No test pinned five of the ways a timed-out query can end: breaking any
of them in QwpQueryClient.executeOnce left every test passing.

- RESULT_END after a batch was withheld from the handler must report
  the timeout. Without the !discardedBatch check, a cut-off result is
  reported as complete: against a real server, onEnd(200000) fired
  after only 16,384 rows had reached the handler.
- RESULT_END, EXEC_DONE or a connection failure that arrives while the
  connection drains, after the grace period released the caller, must
  not reach the handler. A second terminal callback completes the
  pooled submission queued behind the drain with the previous query's
  outcome: a later statement the server rejects is reported as done,
  or a later query fails with the old one's timeout.
- A connection failure past the deadline, within the grace period,
  must still report the timeout. Without that callback a pooled
  Completion.await() never returns.

The scripted server sends no frame on a timer. The handler that falls
behind holds its first batch for the whole timeout, counted from inside
onBatch(): execute() fixes the deadline on entry, so the hold always
ends past it. Where the phase matters, the server ends the query in
reply to the client's own CANCEL. The client sends an older server that
CANCEL only once the deadline has passed, and a server that enforces
the timeout only once the grace period has ended, so the reply always
reaches the client in the phase under test.

Breaking any of the five now fails exactly one new test. The new tests
passed 20 sequential runs and 16 runs under full CPU load, and the
timeout test classes pass on JDK 8 and JDK 25.
A query's terminal callback releases the caller while the worker thread
is still returning from the job, and the worker clears its running flag
only after that return. Query.close() waited for that flag on every
close, with what was left of query_close_timeout_ms, and discarded the
worker if the wait gave up. With query_close_timeout_ms=0, or with the
caller's interrupt flag set, the wait gives up at once. A close that
landed in that window shut a healthy worker down inside close(), and
the next borrow reconnected (TCP, upgrade, auth). Over 2,000
borrow/await/close cycles on a one-worker pool, that opened 2 to 15
connections where the base branch opens 1.

The wait is needed in one case only: after a query timeout, the client
keeps draining the aborted query once the grace period has released the
caller. QwpQueryClient now flags that drain. drainingTimedOutQuery is
set right before the callback that releases the caller, so a close()
that sees the query finished also sees the drain, and executeOnce()
clears it when the drain ends. A drain that gives up on the connection
latches the terminal failure before the flag clears, so the
hasTerminalFailure() check still catches a dead connection.

close() now waits only while that flag is set. Any other worker goes
back to the pool at once, as it did before the query timeout. The run
loop already runs a job dispatched while the previous one returns, and
a finished job can no longer change the lease's state. Nothing new is
written per query, and the common close() path drops two
System.nanoTime() calls and a lock round-trip. Query.close() now
documents the drain wait and the discard of a failed connection.

Two QueryCloseDrainTest cases simulated a drain with running=true alone
and now mark the client draining as well. New tests:

- A zero-budget close and an interrupted close return a worker that is
  still returning from a completed job. Both fail deterministically
  without the fix.
- An interrupted close still discards a worker that is draining.
- 2,000 borrow/await/close cycles keep one connection, with no close
  budget and with the interrupt set. Without the fix they opened 8 and
  10 connections.

The touched test classes passed 5 runs in a row, the full core suite
passes, the code compiles on JDK 8, and the javadoc builds on JDK 25.
mtopolnik pushed a commit to questdb/c-questdb-client that referenced this pull request Oct 20, 2026
* feat(qwp): add per-query timeout to the reader

Wires the protocol of questdb/questdb#7768 (server, open; tandem client
semantics in questdb/java-questdb-client#105) through the Rust core, the
C ABI and the C++ wrapper, so a caller can give one query its own budget
instead of living with the server-wide `query.timeout` (60 s by default).
dbt-style transforms — CTAS, `INSERT … SELECT`, `UPDATE` — routinely run
longer than that, and raising `query.timeout` server-wide also changes
behaviour for PGWire and HTTP clients.

Protocol, as the server PR defines it:

  CAP_QUERY_TIMEOUT      SERVER_INFO capability bit   0x08
  QUERY_FLAG_TIMEOUT     query_flags bit              0x02
  timeout_ms             varint, right after query_flags
  STATUS_QUERY_TIMEOUT   QUERY_ERROR status           0x0E

API:

- `ReaderQuery::timeout(Duration)` per query, `query_timeout_ms` in the
  connect string as the per-reader default (`0` = none, the default).
- C: `qwp_reader_query_set_timeout_ms`. C++: `query::timeout_ms(uint64_t)`
  and `query::timeout(std::chrono::duration)`.
- New `ErrorCode::QueryTimeout` / `line_sender_error_query_timeout` (38),
  mirrored into the C and C++ headers and `ClientErrorCode`.

Three decisions worth calling out:

- **A timeout does not silently degrade.** `reset_symbol_dict` quietly
  no-ops against a server without `CAP_QUERY_FLAGS`; a timeout cannot,
  because dropping it leaves the caller believing it has a long budget
  while the server kills the query at `query.timeout`. `execute()`
  instead fails before anything reaches the wire, naming the missing
  capability and pointing at the server-side knob. This is the one
  deliberate divergence from #105, which keeps its own deadline and
  enforces the timeout client-side against an older server.
- **"No timeout" is the field's absence, never a zero.** The server
  rejects a zero or negative `timeout_ms` with `STATUS_PARSE_ERROR`, so
  `build()` refuses a flag bit and a value that disagree rather than
  letting a malformed frame leave the process.
- **A sub-millisecond duration rounds up to 1 ms.** Truncating it to
  zero would mean "no timeout" — the opposite of the ask. Matches
  `QueryImpl.setTimeout` in #105.

`QueryTimeout` is not failover-eligible: a timeout is the server doing
what it was told, and replaying a write risks applying a statement the
first attempt may already have applied. A failover replay re-sends the
original budget rather than the remainder, since this client keeps no
deadline of its own; documented on `ReaderQuery::timeout` and pinned by
a test.

Tests: 21 Rust unit tests (capability predicates and bit distinctness,
status-code round-trip and wire values, encoder trailer layout alone and
combined with `QUERY_FLAG_RESET_DICT`, flag/value consistency, the
request_id span surviving the trailer, duration conversion, the
capability-gating truth table, status mapping, failover ineligibility,
connect-string parsing); 10 C++ mock-server cases (byte-exact baseline
with no timeout, the field on the wire, chrono rounding and zero,
connect-string default applied per query, per-query override and clear,
fail-fast with no request sent for both capability shapes, connection
reuse after a timeout, failover replay budget); 2 pure-C cases (the
appended error code's value and distinctness, and the new symbol
linking and tolerating a NULL handle from plain C).

* docs(egress): note what bounds a replayed timeout

* style(egress): format the replay trailer assertion

* fix(egress): enforce query timeouts during failover

Reject timed query replay when the replacement server lacks the required
capabilities instead of silently using its default timeout. Preserve the
first terminal error when manual credit grants trigger failover.

Cover replay rejection, persistent credit errors, and real Rust
sub-millisecond timeout conversion with regression tests.

* fix(egress): validate query timeout durations

Reject non-finite chrono durations before integer conversion and
saturate oversized timeouts to the server's signed wire range.

Exercise production flag derivation from the capability matrix, add
numeric regression tests, and clarify that the failover budget limits
retry eligibility rather than end-to-end query duration.

* chore(ci): install numpy 2 from pip on the hetzner agents

pyarrow 26 requires NumPy 2, but the hetzner fuzz jobs installed
Ubuntu's python3-numpy 1.26, so every Arrow suite failed to import.
Install numpy from pip alongside pyarrow and polars instead.

* fix(egress): refuse unsupported query timeouts as UnsupportedServer

A server without CAP_QUERY_TIMEOUT now refuses a timed query with
UnsupportedServer instead of QueryTimeout, so a caller that retries a
timeout with a larger budget cannot loop against a server that ignores
every budget. The refusal happens before anything is written, at
execute() and before a failover replay, and leaves the connection
usable.

A stale-plan replay whose write fails now closes the connection, and
connection_reusable() reports false for a cursor ended mid-stream by a
client-side error, so a pool never recycles a transport that Drop is
about to tear down.

The C++ chrono timeout() rejects negative durations; only zero clears
the timeout. Document ROWS_AFFECTED_UNKNOWN for statements that report
no row count.

* Add more tests

* fix(ingress): shut down the original socket before cancelling I/O in the Windows traffic gate

* test(e2e): stabilize orphan drainer failover replay

---------

Co-authored-by: bluestreak <bluestreak@gmail.com>
Co-authored-by: Vlad Ilyushchenko <bluestreak01@users.noreply.github.com>
kafka1991 and others added 6 commits October 21, 2026 20:19
# Conflicts:
#	core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpQueryClient.java
#	core/src/main/java/io/questdb/client/impl/QueryWorker.java
Brings in the query options from #129 (row window, row counts,
statistics, error positions) alongside the per-query timeout.

- QwpQueryClient keeps both APIs: execute(..., boolean, long timeoutMs)
  and execute(..., QwpQueryOptions) plus a new
  execute(..., QwpQueryOptions, long timeoutMs) overload that
  QueryImpl uses to send the submitted options under the timeout.
- resolveQueryFlags() also drops QUERY_FLAG_TIMEOUT when the server
  does not advertise CAP_QUERY_TIMEOUT.
- QwpEgressIoThread encodes timeout_ms ahead of skip_rows and
  max_rows, in ascending order of the flag bits, and stamps the
  request id on the pooled terminator events.
- Client-detected timeout errors go through deliverClientError(), so
  they reach the position-aware onError overload.
- The test frame parser reads timeout_ms, and a new test pins the
  order of timeout_ms and the row window on the wire.
A failover reconnect made for a query with a timeout bounds each
endpoint step by the time the query has left. The steps count whole
milliseconds and can give up to 1ms before their bound: the native
connect truncates its remaining time to whole milliseconds and treats
0 as expired. A step cut to the query's last millisecond could then
fail just before the deadline, isPast() was still false, and execute()
reported a failed reconnect (status 6) instead of the query timeout.
testTimeoutWhileFailingOverIsReportedAsTimeout failed this way on
Linux CI, where a loopback connect returns EINPROGRESS.

boundToConnectDeadline() now adds 1ms to the time left, so a step the
deadline cuts short ends past the deadline. A new test pins that
invariant without depending on connect timing.
The client treated the query timeout as a deadline the server had to
meet: past it, it discarded result batches, sent its own CANCEL, and
after two grace periods dropped a healthy connection and blamed the
server. A server cannot always stop a query, so a slow query broke
the connection, and with failover=off left the client unusable.

The timeout now only travels with the query to a server that
advertises CAP_QUERY_TIMEOUT, overriding its query.timeout. The client
keeps no deadline of its own and waits for the server's answer however
long it takes; every batch, EXEC_DONE or error the server sends reaches
the handler. Failover replays send the same timeout. An older server
gets no timeout and applies its own default.

Removed the grace period (withQueryTimeoutGrace), the drain state and
the facade's wait for it, the client-side CANCEL and timeout errors,
and the deadline bound on failover reconnects. Kept the skipping of an
abandoned query's leftovers, giving up on a stuck I/O thread after an
interrupt, and Query.close() discarding a failed connection.
6856c34 removed the client's own query deadline: the timeout only
travels with the query, and the server gets it as given. Two tests
this branch added still assumed the deadline.

testTimeoutGoesAheadOfTheRowWindow accepted any timeout_ms in
(29_000, 30_000] as "the budget left", so a client that sent the time
left instead of the timeout passed it. It now asserts the exact value
for 30_000, Long.MAX_VALUE - 1 and Long.MAX_VALUE. A time left that
the client counts down never comes back as Long.MAX_VALUE, so the two
largest values catch that regression even when no millisecond passes
before the request goes out. The javadoc that merge 61d6bed left on
this test moves back onto the test it describes,
testWireBitsAreDistinctAndLeaveTimeoutBitsFree.

testUserCancelIsReportedAsCancel sent a 200 ms timeout to a server
without CAP_QUERY_TIMEOUT and acknowledged the cancel 400 ms later,
to race the cancel against the client deadline. Without the deadline
the timeout never reached the wire, and nothing raced. The test now
sends no timeout to a server that supports one, and the mock streams
one batch, then answers the CANCEL at once: the real server acts on a
CANCEL only while the query streams. Besides the CANCELLED status the
test asserts the batch, the server's message, a single terminal
callback, and that the same connection runs the next statement.

A client that sends the timeout less 500 ms fails the first test,
which the old range let pass. A client that sends a rounded-up time
left fails it on Long.MAX_VALUE - 1, while every test of
QwpQueryClientQueryTimeoutTest and QueryTimeoutFacadeTest passes.
Reporting the cancel with another status, changing its message, or
dropping the CANCEL from cancel() fails the second test.
QwpQueryClientQueryTimeoutTest and QueryTimeoutFacadeTest encoded the
egress server frames (EXEC_DONE, QUERY_ERROR, RESULT_BATCH, RESULT_END)
and decoded the client's QUERY_REQUEST with private copies of what the
shared QwpEgressFrames helper provides, and duplicated each other's
VARCHAR batch builder. Both classes predate QwpEgressFrames (client PR
#129); the merge that brought it in did not move them onto it, so the
egress wire layout lived in three places.

Both classes now build their frames inline with QwpEgressFrames and
decode requests with QwpEgressFrames.parseQueryRequest, as
QwpQueryClientQueryFlagsTest does; QwpEgressFrames itself does not
change. The timeout test gains ScriptedServer.takeQuery(), which
decodes on the test thread and keeps the old "the trailer must end the
frame" check (trailingBytes == 0). Its server thread still reads only
the request id (requestIdOf), which QwpEgressFrames has no reader for.
The facade's Script decodes on the server read thread, where timeoutOf
ran. The mocks now send LONG batches and a RESULT_END whose final_seq
is the last batch_seq, as the server does; no test reads a column,
final_seq or total_rows. trailerOf's "test frames carry no binds"
check goes away with trailerOf: it was the helper's own precondition,
since it could not skip binds, while parseQueryRequest decodes them.

QueryTimeoutFacadeTest also rewrites the javadoc of
assertCloseKeepsTheConnectionOfCompletedQueries, which named
QueryCloseDrainTest cases that 6856c34 deleted, to say what the 2,000
cycles guard; adds the missing blank lines between members; and drops
the unused Completion import.

Tests: the 16 + 8 rewritten tests pass, as do
QwpQueryClientQueryFlagsTest and QwpEgressTerminatorDecodeTest, and the
two classes pass 20 repeated runs. Mutations of the client fail them:
the timeout value, the CAP_QUERY_TIMEOUT gating, trailing bytes after
the trailer, batch delivery, the error status and message, RESET_DICT,
timeout 0, the CANCEL's request id and the SQL text each fail the
rewritten assertion they target; a broken withdraw fails
testInterruptedQueryNotYetSentIsWithdrawn. Both files compile with
javac --release 8.
ideoma added a commit to questdb/questdb that referenced this pull request Dec 1, 2026
Point java-questdb-client at the head of questdb/java-questdb-client#105,
which now carries the fixed timeout tests: exact timeout assertions, a
plain cancel test, and request decoding through QwpEgressFrames.
Query.abandon() discards the handle's configuration, but it kept the
timeout set with Query.timeout(), so the next query still sent it.
QueryImpl.abandon() now restores the client default, like
resetForBorrow() does.

Also add regression tests for two paths no test covered:
- a cancel issued while the submission waits for the worker must still
  reach its query (QueryImpl.applyBinds re-applies it);
- the server's STATUS_CANCELLED reply to an abandoned query must not
  become the next query's outcome (QwpEgressIoThread tags errors with
  their request id).
Each test fails when its production line is removed.
QueryTimeoutExample described the removed client-side deadline. It now
says the client only sends the timeout and the server enforces it.
@ideoma

ideoma commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Review (level 3)

Verdict: approve with comments. Reviewed at 870305fd (base 91b3a8a4); the javadoc fix below is pushed as 2fb5031e.

Critical

None.

Moderate

1. No test fails if the request id is dropped from EXEC_DONE replies

  • Problem: the request-id stamp on EXEC_DONE (QwpEgressIoThread.java:592) has no test that would catch its removal.
  • Net impact: if it regressed, the statement after an interrupted INSERT or DDL would get the interrupted statement's reply and row count.
  • Evidence: removing .forRequest(currentRequestId) from that line leaves QwpQueryClientQueryTimeoutTest, QueryTimeoutFacadeTest and QwpQueryClient*Test all green.
  • Cause: testInterruptReleasesTheCallerOnlyOnceItsRequestIsEncoded only checks next.execDone, which is true even when the old reply answers the next statement.
  • Fix: have the next statement return a different rowsAffected and assert that value. Also run a third statement to check that no reply is left over for it.

Fixed (pushed in 2fb5031e)

  • QueryTimeoutExample said an older server gets a cancel from the client and that the timeout counts from submit(). It now matches the README: the client only sends the timeout, and the server enforces it. I also removed "as on a query timeout" from the retractRequest javadoc.

Coverage

The test gate passes, with one coverage gap (item 1). QwpQueryClientQueryTimeoutTest (17 tests) and QueryTimeoutFacadeTest (10 tests) pass at 870305fd.

Notes

No test failed when EXEC_DONE lost its request id. The new test checks
that each statement after an interrupted one gets its own row count.
@mtopolnik

Copy link
Copy Markdown
Contributor

[PR Coverage check]

😍 pass : 170 / 180 (94.44%)

file detail

path covered line new line coverage
🔵 io/questdb/client/cutlass/qwp/client/QwpQueryClient.java 86 95 90.53%
🔵 io/questdb/client/impl/QueryImpl.java 33 34 97.06%
🔵 io/questdb/client/cutlass/qwp/client/QwpSpscQueue.java 20 20 100.00%
🔵 io/questdb/client/QueryException.java 1 1 100.00%
🔵 io/questdb/client/impl/ConfigSchema.java 1 1 100.00%
🔵 io/questdb/client/cutlass/qwp/client/QueryEvent.java 10 10 100.00%
🔵 io/questdb/client/cutlass/qwp/client/QwpEgressIoThread.java 16 16 100.00%
🔵 io/questdb/client/impl/QueryLease.java 2 2 100.00%
🔵 io/questdb/client/impl/QueryWorker.java 1 1 100.00%

@glasstiger

Copy link
Copy Markdown
Contributor

Review (level 3)

Verdict: approve with comments. Reviewed at 91529f6e (base 91b3a8a4). Nothing blocks the merge; three test gaps are worth fixing.

Scope

  • Submodules and binaries: the PR moves no submodule pointers and commits no binaries.

  • OSS tandem: feat(qwp): add per-query timeouts for queries over QWP questdb#7768 uses the same branch name and both PRs link to each other. Its head pins this client at 91529f6e and its CI is green. Its QwpEgressQueryTimeoutTest covers the timeout against a real server, including through the QuestDB facade. Its description is out of date: it still names the pin c35a3dd9 and says the client enforces the timeout itself.

  • No Enterprise tandem. The changes near high availability are:

    • the order of the health updates in the failover loop;
    • the timeout being sent again when a failed-over query is replayed;
    • discarding pooled clients whose connection failed.

    They end in the same states as base and have mock-server tests, so I'm not counting this as a gap.

  • PR description:

    • "Query.timeout() overrides it for one query" is inaccurate: the setting stays on the handle until it is changed or the handle is closed.
    • Two user-visible effects are missing:
      • Query.close() now discards a pooled client whose connection failed. With failover=off, such a client used to fail every later query.
      • An exception thrown by a handler's onError, onEnd or onExecDone no longer becomes the next submission's outcome.

Critical

None.

Moderate

1. The test for the late handler exception fix passes without the fix

  • Problem: testThrowingHandlerLeavesTheNextSubmissionIntact (QueryTimeoutFacadeTest.java:273) never forces the race it targets.
  • Net impact: if the guard were removed, one query's handler exception would fail the next query.
  • Evidence: at 91529f6e with the guard removed (base behaviour), the test passed all 50 runs, including runs under CPU stress and a full-suite run. A deterministic version failed 14 of 14 runs without the guard and passed 9 of 9 with it.

How it happens: WrappingHandler.onError signals the outcome in its finally, which releases the caller. The handler's exception then unwinds to the catch in QueryImpl.runOn (QueryImpl.java:470-474). If the caller has already called submit() again, only if (submission == submissionSeq) (:416) stops the stale exception from becoming the new submission's outcome. The worker unwinds in microseconds, so the test's caller practically never gets there first. Parking the worker for 200 ms before the catch, without the guard, makes the test fail with got status=0, message=handler failed: timeout, query aborted. Base has this bug, because QueryWorker.runLoop signals unconditionally. The PR fixes the bug; only its test is weak.

Fix: signalUnexpected reads the exception's message before it takes doneLock, both at base and at head. A message that blocks until the caller has submitted again forces the interleaving without any production test hook:

final CountDownLatch nextSubmitted = new CountDownLatch(1);
final RuntimeException failure = new IllegalStateException() {
    @Override
    public String getMessage() { // held until the caller has submitted the next query
        try {
            nextSubmitted.await(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return "handler failed";
    }
};
// onError throws `failure`; after assertTimesOut(q):
q.sql("INSERT INTO t VALUES (1)").handler(new NoopHandler());
Completion next = q.submit();
nextSubmitted.countDown();
next.await(); // without the guard this throws QueryException(cause = failure)

2. No test fails if a cancel carries over to the next query on the same handle

  • Problem: deleting cancelRequested = false; from QueryImpl.submit() (:293) keeps the whole suite green.
  • Net impact: if that line were dropped, every query after a cancelled one on that handle would fail as cancelled.
  • Evidence: at 91529f6e with that line deleted, the full core suite passed (3,965 tests, 0 failures). A cancel-then-resubmit test failed 4 of 4 runs with status=10, cancelled by client, and passed 6 of 6 runs at head.

How it happens:

  • QueryWorker.cancelInFlight() sets the flag (:268).
  • applyBinds() (:321) applies it again on every execute() of the handle.
  • Within one borrow, only submit() clears it.

The only facade test that cancels (QueryTimeoutFacadeTest.java:158) stops after the cancel and never submits again. The Completion Javadoc documents cancel-then-resubmit as a supported flow. At base the flag does not exist and resubmitting after a cancel works.

Fix: add this test. The scripted server holds query 1 until it receives a CANCEL. It answers query 2 with EXEC_DONE after about 1 s, unless a CANCEL for query 2 arrives first.

Completion first = q.sql("SELECT s FROM t").handler(new NoopHandler()).submit();
script.timeouts.take();   // the server has query 1
first.cancel();           // then await() -> QueryException, STATUS_CANCELLED
q.sql("INSERT INTO t VALUES (1)");
assertOwnOutcome(q);      // fails with status=10 if the cancel carries over

3. TestWebSocketServerHandlerDropTest passes against the old mock server

  • Problem: the new drop test also passes with the base TestWebSocketServer.
  • Net impact: affects developers only. The fix that keeps the mock server reading after a scripted drop (lingerThenClose()) has no test that fails without it.
  • Evidence: with TestWebSocketServer.java from 91b3a8a4, the test passed 25 of 25 runs on darwin-aarch64, 10 of them under CPU stress. I did not run it on Linux.

Why it passes at base:

  • When called on the read thread, base close() already calls shutdownOutput() and then drainInput(). That drain stops after 20 ms with no data, or after 200 ms at most.
  • The test's client sends both frames in one write and then sends nothing more. Base reads the whole 32 KiB tail and closes with nothing unread, so the connection ends with a normal FIN rather than a reset.
  • The race the test's Javadoc describes (:60) needs the client to keep sending after base's drain gives up.

Fix: have a second thread keep writing frames for more than 200 ms after the drop while the main thread reads. I expect base to reset the connection then, but I have not run that variant.

Minor

  • Member ordering:
    • QwpEgressIoThread.isRequestEncoded (:458) sits between run() and shutdown(); it belongs before onBinaryMessage.
    • QwpQueryClient.abandonConnection (:1617) is an instance method placed inside the private static block.
    • The queryTimeoutMs field (:321) comes before pendingCancel (:329).
    • QueryImpl.requestCancel() (:267) sits between setSql and setTimeout, and the new static describe (:311) sits among instance methods.
  • Dead code: in TestWebSocketServer.java, the branch if (readThread == Thread.currentThread()) drainInput(); (:670-672) and drainInput() itself (:690) can no longer run after the new early return at :647.
  • Wrong comment: ConfigSchema.java:118 says 0 = no timeout. In fact 0 means the server's default query.timeout applies, as README.md:761 says.

Coverage

The test gate passes, with one coverage gap (Moderate #2):

Change Test Search and failure link
QueryImpl.submit() clears cancelRequested none Searched core/src/test for facade cancels: QueryTimeoutFacadeTest:158 has no resubmit, QueryLeaseGenerationTest calls cancel by reflection and runs no query, and QuestDBExamples has no @Test. With the line deleted the full suite is green and the proposed test fails with status 10.

Summary

  • Please address Moderate ci(build): set file encoding to utf-8 for logging #1 and chore(conf): update JDK version from 17 to 11 and change tag to 1.0.0 #2; each is one small test. Moderate build: 1.0.0 #3 only affects developers.
  • Severity: 0 Critical, 3 Moderate (all in this diff, in test code and the mock server), 3 Minor.
  • CI: green on all platforms, and the OSS tandem's CI is green at the pinned head.
  • Tradeoffs the PR makes:
    • The next query on a connection now waits until an abandoned query's remaining results have arrived and been discarded. Before, it received those results as its own.
    • An interrupted execute() can block for up to twice shutdownJoinMs (5 s each) when the I/O thread has picked up the request but not yet encoded it. Normally this takes microseconds.
    • A pooled client with a failed connection is now discarded at Query.close(). With failover on and its attempts used up, the next borrowQuery() opens a new connection and can throw failed to create query client. Before, the same failure came from await() after a failover attempt.
    • Adding Query.timeout() breaks custom Query implementations. The PR body states this, and feat(qwp): add paging, row counts, timings and error positions to the query client #129 added options() the same way.

@bluestreak01
bluestreak01 merged commit 589f19f into main Dec 1, 2026
20 checks passed
@bluestreak01
bluestreak01 deleted the vi_query_timeout branch December 1, 2026 22:48
glasstiger added a commit that referenced this pull request Dec 2, 2026
Brings in the per-query timeout of the query client (#105).

QwpQueryClient conflicted where both sides added constants after
QUERY_DETAILS_FLAGS: this branch added QUERY_FLAG_DESIGNATED_TIMESTAMP
and QUERY_FLAG_OMIT_BINARY_VALUES to the query-details flags, and main
added REQUEST_ENCODED_POLL_NANOS. The resolution keeps both.

The new flag bits (0x80, 0x100) do not collide with QUERY_FLAG_TIMEOUT
(0x02), and carry no QUERY_REQUEST field, so timeout_ms, skip_rows and
max_rows keep their order on the wire.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants