diff --git a/.gitleaks.toml b/.gitleaks.toml new file mode 100644 index 000000000..cd2a3f3c9 --- /dev/null +++ b/.gitleaks.toml @@ -0,0 +1,16 @@ +# Gitleaks configuration, picked up from the repository root by the Gitleaks workflow. +# +# Keep every default rule and only add narrow exceptions for known false positives. + +[extend] +useDefault = true + +[allowlist] +description = "Known false positives" +regexTarget = "secret" +regexes = [ + # The example Sec-WebSocket-Key value from RFC 6455 section 1.3, base64 of + # "the sample nonce". Tests send it in hand-written WebSocket upgrade requests. + # It is a public handshake nonce, not a credential. + '''dGhlIHNhbXBsZSBub25jZQ==''', +] diff --git a/README.md b/README.md index 311c985d6..09d4a2676 100644 --- a/README.md +++ b/README.md @@ -219,8 +219,34 @@ try (Query q = db.borrowQuery()) { ### Cancel or Time Out a Query -`submit()` returns a `Completion`. `await(timeout, unit)` returns `false` if the query is still in flight; `cancel()` -stops it. +Give a query a timeout with `timeout(...)`, or every query a default with `query_timeout_ms` in the configuration +string. It overrides the server's default query timeout (`query.timeout`) for that query: the client sends it with the +query, and the server stops the query when it can. `await()` then throws a `QueryException` whose `isTimeout()` is +`true`, and the pooled connection stays open for the next query. + +```java +import io.questdb.client.QueryException; + +try (Query q = db.borrowQuery()) { + q.sql("SELECT * FROM big_table ORDER BY ts") + .handler(handler) + .timeout(5, TimeUnit.SECONDS); + try { + q.submit().await(); + } catch (QueryException e) { + if (!e.isTimeout()) { + throw e; + } + // the server stopped the query after 5 seconds + } +} +``` + +The client keeps no deadline of its own: it waits for the server's answer however long it takes. Some statements +cannot be stopped and run to completion. A server that does not support per-query timeouts applies its own default. + +`submit()` returns a `Completion`. `await(timeout, unit)` only bounds the wait: it returns `false` while the query keeps +running. `cancel()` stops the query. ```java import io.questdb.client.Completion; @@ -713,6 +739,7 @@ schema::key1=value1;key2=value2; | `query_pool_min` | `1` | Minimum query connections kept warm (`0` under `lazy_connect`) | | `query_pool_max` | `4` | Maximum query connections | | `acquire_timeout_ms` | `5000` | How long `borrowSender()`/`borrowQuery()` waits for a free slot | +| `query_close_timeout_ms` | `5000` | How long `Query.close()` waits for a running query | | `idle_timeout_ms` | `60000` | How long a pooled connection may stay idle before it is reaped | | `max_lifetime_ms` | `1800000` | Maximum lifetime of a pooled connection before it is recycled | @@ -727,6 +754,12 @@ Applied by the query pool to select and fail over between the nodes in the `addr | `zone` | | Prefer same-zone endpoints for `target=any`/`replica` (opaque, case-insensitive) | | `client_id` | | Opaque client identifier surfaced server-side for observability | +### Query keys + +| Key | Default | Description | +| ------------------ | ------- | ------------------------------------------------------------------------------------------ | +| `query_timeout_ms` | `0` | Default per-query server timeout in milliseconds (`0` = server default); override per query with `timeout()` | + The ingest side also accepts store-and-forward and reconnection tuning keys (`auto_flush_*`, `initial_connect_retry`, `reconnect_*`, `request_durable_ack`, `sf_*`, `max_frame_rejections`, `poison_min_escalation_window_millis`, …). `sf_max_total_bytes` caps the unacknowledged data all pooled senders buffer together — 128 MiB of memory by default, diff --git a/core/src/main/java/io/questdb/client/Completion.java b/core/src/main/java/io/questdb/client/Completion.java index 615799e07..7ddd5edd1 100644 --- a/core/src/main/java/io/questdb/client/Completion.java +++ b/core/src/main/java/io/questdb/client/Completion.java @@ -63,6 +63,11 @@ public interface Completion { /** * Blocks up to the given timeout. Returns {@code true} if the query * completed, {@code false} on timeout. + *

+ * This bounds only how long the caller waits: on {@code false} the query + * keeps running. To have the server stop queries that run too long, set a + * query timeout ({@link Query#timeout(long, TimeUnit)} or + * {@code query_timeout_ms}). * * @throws QueryException if the server reported an error or * {@link #cancel()} won the race diff --git a/core/src/main/java/io/questdb/client/Query.java b/core/src/main/java/io/questdb/client/Query.java index 216cbe278..c31d0d71d 100644 --- a/core/src/main/java/io/questdb/client/Query.java +++ b/core/src/main/java/io/questdb/client/Query.java @@ -28,8 +28,10 @@ import io.questdb.client.cutlass.qwp.client.QwpColumnBatchHandler; import io.questdb.client.cutlass.qwp.client.QwpQueryOptions; import io.questdb.client.cutlass.qwp.client.QwpServerInfo; +import io.questdb.client.cutlass.qwp.protocol.QwpConstants; import java.io.Closeable; +import java.util.concurrent.TimeUnit; /** * A query handle leased from the {@link QuestDB} pool via @@ -44,12 +46,13 @@ * creates one small lease handle per borrow (often scalar-replaced by the JIT * when used with try-with-resources). *

- * Lifecycle: configure with {@link #sql}, optional {@link #binds} and - * {@link #options}, and {@link #handler}, then call {@link #submit()} to obtain - * a {@link Completion} and {@code await()} it before the next {@link #submit()}. - * The query reads its SQL text, binds and handler while it runs, so do not - * change them before {@code await()} returns. It takes its options when it is - * submitted, so {@link #options} may set up the next query in the meantime. + * Lifecycle: configure with {@link #sql}, optional {@link #binds}, + * {@link #timeout} and {@link #options}, and {@link #handler}, then call + * {@link #submit()} to obtain a {@link Completion} and {@code await()} it before + * the next {@link #submit()}. The query reads its SQL text, binds and handler + * while it runs, so do not change them before {@code await()} returns. It takes + * its timeout and options when it is submitted, so {@link #timeout} and + * {@link #options} may set up the next query in the meantime. *

* Thread safety: not thread-safe and single-flight -- one in-flight query per * handle. To run queries concurrently, borrow one handle per concurrent query. @@ -84,6 +87,9 @@ public interface Query extends Closeable { * therefore never blocks the caller unbounded, even when the server is slow * to honor the cancel. *

+ * A client whose connection failed is discarded. Any other client whose + * query has ended is returned to the pool at once. + *

* Must NOT be called from a result handler: handlers run on the worker * thread, so {@code close()} would block waiting for a terminal event that * only that thread can deliver. Calling it there throws @@ -148,4 +154,33 @@ public interface Query extends Closeable { * before the first successful bind */ QwpServerInfo serverInfo(); + + /** + * Sets the query timeout for subsequent {@link #submit()} calls on this + * handle, overriding the {@code query_timeout_ms} default from the + * connection string. It stays in effect until changed, and every borrow + * starts from the configured default. + *

+ * The timeout overrides the server's default query timeout + * ({@code query.timeout}) for this query; the client sends it with the query + * and keeps no deadline of its own. The server stops the query when it can: + * the handler's {@code onError} then receives + * {@link QwpConstants#STATUS_QUERY_TIMEOUT}, {@link Completion#await()} + * throws a {@link QueryException} whose {@link QueryException#isTimeout()} + * is {@code true}, and the pooled connection serves the next query. Some + * statements cannot be stopped and run to completion. A server that does + * not support per-query timeouts applies its own default. + *

+ * To bound how long the caller waits, use + * {@link Completion#await(long, TimeUnit)}, and {@link Completion#cancel()} + * to stop the query from the client side. + * + * @param timeout the timeout, {@code 0} to send none so the server's default + * applies; a positive value below one millisecond counts as + * one millisecond + * @param unit the unit of {@code timeout} + * @return this handle + * @throws IllegalArgumentException when {@code timeout} is negative + */ + Query timeout(long timeout, TimeUnit unit); } diff --git a/core/src/main/java/io/questdb/client/QueryException.java b/core/src/main/java/io/questdb/client/QueryException.java index 4fbff9928..d584d955e 100644 --- a/core/src/main/java/io/questdb/client/QueryException.java +++ b/core/src/main/java/io/questdb/client/QueryException.java @@ -26,6 +26,7 @@ import io.questdb.client.cutlass.qwp.client.QwpEgressMsgKind; import io.questdb.client.cutlass.qwp.client.QwpQueryOptions; +import io.questdb.client.cutlass.qwp.protocol.QwpConstants; /** * Thrown from {@link Completion#await()} / {@link Completion#await(long, java.util.concurrent.TimeUnit)} @@ -35,9 +36,12 @@ *

* The original wire-level status byte is exposed via {@link #getStatus()} so * callers can distinguish cancellation from schema errors etc. without - * string-matching the message. When the query asked for the error position - * with {@link QwpQueryOptions#errorPosition(boolean)}, {@link #getPosition()} - * points at the offending character of the SQL text. + * string-matching the message. A query that ran past its timeout (see + * {@link Query#timeout(long, java.util.concurrent.TimeUnit)}) reports + * {@link QwpConstants#STATUS_QUERY_TIMEOUT}; {@link #isTimeout()} tests for it. + * When the query asked for the error position with + * {@link QwpQueryOptions#errorPosition(boolean)}, {@link #getPosition()} points + * at the offending character of the SQL text. */ public class QueryException extends RuntimeException { @@ -79,4 +83,12 @@ public int getPosition() { public byte getStatus() { return status; } + + /** + * Returns {@code true} when the server stopped the query because it ran + * past its timeout. The connection that ran it stays usable. + */ + public boolean isTimeout() { + return status == QwpConstants.STATUS_QUERY_TIMEOUT; + } } diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QueryEvent.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QueryEvent.java index 75b617354..2c99ea46d 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QueryEvent.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QueryEvent.java @@ -29,9 +29,21 @@ * One event per {@code RESULT_BATCH} / {@code RESULT_END} / {@code QUERY_ERROR} * received from the server, plus a synthetic error event if the connection drops * mid-query. + *

+ * The I/O thread stamps the events of a query with that query's id + * ({@link #requestId}), so {@code execute()} can tell its own events from the + * leftovers of an earlier query that its {@code execute()} stopped waiting for. + * Connection-level events -- the connection failed, the I/O thread stopped, the + * client closed -- carry {@link #ANY_REQUEST} and reach whichever query waits. */ public class QueryEvent { + /** + * {@link #requestId} of an event that belongs to no query in particular, such + * as a connection failure. Whichever query waits for events must see it. + */ + public static final long ANY_REQUEST = -1L; + public static final int KIND_BATCH = 0; public static final int KIND_END = 1; public static final int KIND_ERROR = 2; @@ -54,12 +66,14 @@ public class QueryEvent { public byte errorStatus; // valid for KIND_ERROR public int kind; public short opType; // valid for KIND_EXEC_DONE (matches CompiledQuery.SELECT/INSERT/etc.) + public long requestId = ANY_REQUEST; // query the event belongs to; see forRequest() public long rowsAffected; // valid for KIND_EXEC_DONE public long totalRows; // valid for KIND_END public QueryEvent asBatch(QwpBatchBuffer buffer) { this.kind = KIND_BATCH; this.buffer = buffer; + this.requestId = ANY_REQUEST; return this; } @@ -68,6 +82,7 @@ public QueryEvent asEnd(long totalRows) { this.buffer = null; this.totalRows = totalRows; this.details.clear(); + this.requestId = ANY_REQUEST; return this; } @@ -81,6 +96,7 @@ public QueryEvent asError(byte status, String message, int position) { this.errorStatus = status; this.errorMessage = message; this.errorPosition = position; + this.requestId = ANY_REQUEST; return this; } @@ -90,6 +106,7 @@ public QueryEvent asExecDone(short opType, long rowsAffected) { this.opType = opType; this.rowsAffected = rowsAffected; this.details.clear(); + this.requestId = ANY_REQUEST; return this; } @@ -99,9 +116,29 @@ public QueryEvent asTransportError(byte status, String message) { this.errorStatus = status; this.errorMessage = message; this.errorPosition = QwpEgressMsgKind.NO_ERROR_POSITION; + this.requestId = ANY_REQUEST; + return this; + } + + /** + * Ties the event to the query with id {@code requestId}. Call it after the + * {@code asX()} builder, which leaves the event at {@link #ANY_REQUEST}. + */ + public QueryEvent forRequest(long requestId) { + this.requestId = requestId; return this; } + /** + * Returns {@code true} when the event belongs to a query other than + * {@code requestId}: a leftover of an earlier query that its + * {@code execute()} stopped waiting for. An {@link #ANY_REQUEST} event + * belongs to every query. + */ + public boolean isForOtherRequest(long requestId) { + return this.requestId != ANY_REQUEST && this.requestId != requestId; + } + /** * Clears object references and resets primitive fields so a pooled event is * safe to reuse across queries. The I/O thread calls the {@code asX(...)} @@ -119,6 +156,7 @@ public void reset() { this.opType = 0; this.rowsAffected = 0; this.totalRows = 0; + this.requestId = ANY_REQUEST; this.details.clear(); } diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpColumnBatchHandler.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpColumnBatchHandler.java index ce809df61..c63bb421e 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpColumnBatchHandler.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpColumnBatchHandler.java @@ -47,7 +47,9 @@ * Exception contract: if any callback method throws, the * exception propagates out of the {@link QwpQueryClient#execute} call on the * caller's thread and no further callbacks fire for that query. The connection - * remains usable for subsequent queries. + * remains usable for subsequent queries: when {@link #onBatch} throws while the + * query is still running, {@code execute} cancels the query, and the next query + * skips whatever the cancelled one still sends. */ public interface QwpColumnBatchHandler { diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpEgressIoThread.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpEgressIoThread.java index 7fd63f923..87efdb29c 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpEgressIoThread.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpEgressIoThread.java @@ -90,8 +90,9 @@ public class QwpEgressIoThread implements Runnable, WebSocketFrameHandler { // reads the fields synchronously in {@link #sendQueryRequest} and does not // retain a reference past that call. Reuse avoids a per-submit allocation // -- one in-flight query per client makes this safe: the worker that - // mutates pendingRequest is blocked on the events queue until the I/O - // thread has finished consuming the previous instance. + // mutates pendingRequest does not return from execute() before the I/O + // thread has encoded the previous instance, or it was withdrawn + // (withdrawRequest). private final QueryRequest pendingRequest = new QueryRequest(); // Single-slot request queue (Phase-1 allows one in-flight query). private final BlockingQueue requests = new ArrayBlockingQueue<>(1); @@ -118,7 +119,15 @@ public class QwpEgressIoThread implements Runnable, WebSocketFrameHandler { // client dropped the bits the server does not advertise. Tells the // terminator decoders which trailers to read. I/O thread only. private long currentQueryFlags; + // Query being served. Stamped on the events of that query (QueryEvent.requestId); + // connection-level events stay at QueryEvent.ANY_REQUEST. private long currentRequestId = -1L; + // requestId of the last QUERY_REQUEST fully encoded into sendScratch. Once a + // request's id is published here the I/O thread no longer reads the caller's + // SQL text or bind scratch for it, so the caller may reuse them even while the + // query itself is still running. -1 until the first request. Written by the + // I/O thread only; volatile so the executing thread observes it. + private volatile long encodedRequestId = -1L; private volatile boolean shutdown; public QwpEgressIoThread(WebSocketClient wsClient, int bufferPoolSize, TerminalFailureListener terminalFailureListener) { @@ -372,9 +381,11 @@ public void releaseEvent(QueryEvent event) { /** * Queues a CANCEL frame for {@code requestId} to be sent by the I/O thread * between the next two {@code receiveFrame} iterations (typically within - * {@link #POLL_TIMEOUT_MS}). Safe to call from any thread. If a CANCEL for - * the same (or another) requestId is already pending, the newer id wins -- - * multiple concurrent cancels coalesce into one send. + * {@link #POLL_TIMEOUT_MS}) once it serves that query. Safe to call from any + * thread. If a CANCEL for the same (or another) requestId is already pending, + * the newer id wins -- multiple concurrent cancels coalesce into one send. + * See {@link #drainPendingCancel()} for a cancel of a query that has not been + * sent yet, or has already ended. */ public void requestCancel(long requestId) { pendingCancelRequestId.set(requestId); @@ -439,6 +450,15 @@ public void run() { } } + /** + * Returns {@code true} once the {@code QUERY_REQUEST} for {@code requestId} + * has been encoded, after which the I/O thread no longer reads the SQL text or + * bind payload that {@link #submitQuery} handed it. + */ + public boolean isRequestEncoded(long requestId) { + return encodedRequestId == requestId; + } + /** * Signals shutdown. Does not join the thread -- caller handles that. */ @@ -462,10 +482,11 @@ public void shutdown() { * payload contains; zero when the user supplied no binds. *

* {@code queryFlags} are the bits the request carries, which the server - * must advertise; zero sends no {@code query_flags} trailer. {@code skipRows} - * goes on the wire only with {@link QwpEgressMsgKind#QUERY_FLAG_SKIP_ROWS} - * and {@code maxRows} only with {@link QwpEgressMsgKind#QUERY_FLAG_MAX_ROWS}; - * both must be non-negative. + * must advertise; zero sends no {@code query_flags} trailer. {@code timeoutMs} + * goes on the wire only with {@link QwpEgressMsgKind#QUERY_FLAG_TIMEOUT}, + * {@code skipRows} only with {@link QwpEgressMsgKind#QUERY_FLAG_SKIP_ROWS} and + * {@code maxRows} only with {@link QwpEgressMsgKind#QUERY_FLAG_MAX_ROWS}; all + * must be non-negative. */ public void submitQuery( CharSequence sql, @@ -475,6 +496,7 @@ public void submitQuery( long bindPayloadPtr, long bindPayloadLen, long queryFlags, + long timeoutMs, long skipRows, long maxRows ) throws InterruptedException { @@ -485,6 +507,7 @@ public void submitQuery( pendingRequest.bindPayloadPtr = bindPayloadPtr; pendingRequest.bindPayloadLen = bindPayloadLen; pendingRequest.queryFlags = queryFlags; + pendingRequest.timeoutMs = timeoutMs; pendingRequest.skipRows = skipRows; pendingRequest.maxRows = maxRows; requests.put(pendingRequest); @@ -497,6 +520,29 @@ public QueryEvent takeEvent() throws InterruptedException { return events.take(); } + /** + * Pops the next event, waiting at most until the absolute + * {@link System#nanoTime()} {@code deadlineNanos}. Returns {@code null} when + * the deadline passes with no event available. Called by the user thread + * while it stops an I/O thread it gave up on, releasing what that thread + * still publishes. + */ + public QueryEvent takeEvent(long deadlineNanos) throws InterruptedException { + return events.take(deadlineNanos); + } + + /** + * Takes back the request {@code requestId} that {@link #submitQuery} queued, + * provided this thread has not picked it up yet. Returns {@code true} when it + * was still queued: it is never sent, and the caller may reuse its SQL text + * and bind payload at once. Returns {@code false} when this thread has it; + * it reads them until {@link #isRequestEncoded} holds. Removal and pick-up + * are atomic with respect to each other. + */ + public boolean withdrawRequest(long requestId) { + return pendingRequest.requestId == requestId && requests.remove(pendingRequest); + } + /** * Reads the statistics block of {@link QwpEgressMsgKind#QUERY_FLAG_STATS}: * {@code compile_ns, execute_ns, count_ns, client_wait_ns} as varints and @@ -531,7 +577,7 @@ private QueryEvent borrowEvent() { private void decodeAndEmitError(long payload, int payloadLen) { QueryEvent ev = decodeError(payload, payloadLen, currentQueryFlags); - events.offer(ev); + events.offer(ev.forRequest(currentRequestId)); } /** @@ -543,7 +589,7 @@ private void decodeAndEmitError(long payload, int payloadLen) { */ private void decodeAndEmitExecDone(long payload, int payloadLen) { try { - events.offer(decodeExecDone(borrowEvent(), payload, payloadLen, currentQueryFlags)); + events.offer(decodeExecDone(borrowEvent(), payload, payloadLen, currentQueryFlags).forRequest(currentRequestId)); } catch (QwpDecodeException e) { emitTerminalTransportError(e.getMessage()); } @@ -558,7 +604,7 @@ private void decodeAndEmitExecDone(long payload, int payloadLen) { */ private void decodeAndEmitResultEnd(long payload, int payloadLen) { try { - events.offer(decodeResultEnd(borrowEvent(), payload, payloadLen, currentQueryFlags)); + events.offer(decodeResultEnd(borrowEvent(), payload, payloadLen, currentQueryFlags).forRequest(currentRequestId)); } catch (QwpDecodeException e) { emitTerminalTransportError(e.getMessage()); } @@ -569,10 +615,22 @@ private void decodeAndEmitResultEnd(long payload, int payloadLen) { * thread at every loop boundary so a cancel set by a user thread reaches * the server regardless of whether the I/O thread was waiting on a frame * or on a free buffer. + *

+ * Only a cancel of the query being served goes out. One for a later query + * stays pending: the user thread can queue that query, and cancel it, while + * this thread still works through an earlier query whose {@code execute()} + * stopped waiting for it. Sent now, the CANCEL would reach the server before + * the query does, and the server drops a cancel of a query it does not know. + * One for an earlier query, which has already ended, is dropped. Request ids + * only grow, so comparing them tells the three apart. */ private void drainPendingCancel() { - long id = pendingCancelRequestId.getAndSet(-1L); - if (id >= 0L) { + long id = pendingCancelRequestId.get(); + if (id < 0L || id > currentRequestId) { + return; + } + // The CAS keeps a cancel the user thread set meanwhile, which is newer. + if (pendingCancelRequestId.compareAndSet(id, -1L) && id == currentRequestId) { sendCancel(id); } } @@ -671,7 +729,7 @@ private void handleResultBatch(long payloadPtr, int payloadLen) { currentQueryDone = true; return; } - events.offer(borrowEvent().asBatch(buf)); + events.offer(borrowEvent().asBatch(buf).forRequest(currentRequestId)); // Park on the release latch. Returning sooner would let receiveFrame // compact the WebSocket recv buffer, overwriting the bytes that the // user-visible column pointers still reference. User thread's @@ -762,9 +820,14 @@ private void sendQueryRequest(QueryRequest req) { } // Optional query_flags trailer; omitted when zero so a baseline frame // stays byte-identical and the server defaults the flags to 0. The - // row-window values follow the flags in ascending order of their bits. + // timeout and row-window values follow the flags in ascending order of + // their bits. if (req.queryFlags != 0) { sendScratch.putVarint(req.queryFlags); + // Flag-gated fields follow the flags in flag-bit order. + if ((req.queryFlags & QwpEgressMsgKind.QUERY_FLAG_TIMEOUT) != 0) { + sendScratch.putVarint(req.timeoutMs); + } if ((req.queryFlags & QwpEgressMsgKind.QUERY_FLAG_SKIP_ROWS) != 0) { sendScratch.putVarint(req.skipRows); } @@ -772,6 +835,8 @@ private void sendQueryRequest(QueryRequest req) { sendScratch.putVarint(req.maxRows); } } + // The request no longer references the caller's SQL text or bind scratch. + encodedRequestId = req.requestId; wsClient.sendBinary(sendScratch.getBufferPtr(), sendScratch.getPosition()); sendScratch.reset(); } @@ -821,9 +886,10 @@ public interface TerminalFailureListener { /** * Mutable request holder reused across submits. Safe to reuse because at * most one query is in flight per client: the worker thread mutates fields - * and offers the instance into {@link #requests}, then blocks on the events - * queue until the I/O thread has fully consumed the previous instance and - * delivered a terminal event. + * and offers the instance into {@link #requests}, and does not return from + * {@code execute()} before this thread has encoded the instance (see + * {@link #isRequestEncoded}) or the worker withdrew it + * ({@link #withdrawRequest}). */ private static final class QueryRequest { int bindCount; @@ -835,6 +901,7 @@ private static final class QueryRequest { long requestId; long skipRows; CharSequence sql; + long timeoutMs; } /** diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpEgressMsgKind.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpEgressMsgKind.java index 571e1d633..7eb00b08c 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpEgressMsgKind.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpEgressMsgKind.java @@ -56,11 +56,16 @@ public final class QwpEgressMsgKind { */ public static final int CAP_QUERY_FLAGS = 0x00000002; /** - * {@code SERVER_INFO.capabilities} bit reserved for per-query timeouts, which - * this client does not send. Released clients (c-questdb-client 7.2.0 and - * later, and the Python client built on it) read the bit as "the server - * honours {@link #QUERY_FLAG_TIMEOUT}", so no other capability may take it. - * Mirrors the server-side constant + * {@code SERVER_INFO.capabilities} bit: the server enforces a per-query + * timeout carried on {@code QUERY_REQUEST}. When set (together with + * {@link #CAP_QUERY_FLAGS}), a client that wants a timeout sets + * {@link #QUERY_FLAG_TIMEOUT} and appends {@code timeout_ms:varint} after the + * {@code query_flags} trailer; the server then ends an over-budget query with + * a {@code QUERY_ERROR} carrying + * {@link io.questdb.client.cutlass.qwp.protocol.QwpConstants#STATUS_QUERY_TIMEOUT}, + * leaving the connection open. Released clients (c-questdb-client 7.2.0 and + * later, and the Python client built on it) read the bit the same way, so no + * other capability may take it. Mirrors the server-side constant * {@code io.questdb.cutlass.qwp.codec.QwpEgressMsgKind#CAP_QUERY_TIMEOUT}. */ public static final int CAP_QUERY_TIMEOUT = 0x00000008; @@ -127,7 +132,8 @@ public final class QwpEgressMsgKind { * {@code QUERY_REQUEST.query_flags} bit: leave out the first * {@code skip_rows} rows of the result set. The request carries * {@code skip_rows:varint} after {@code query_flags}, behind the fields of - * the lower flag bits, of which this client sends none. Statements that do + * the lower flag bits: after {@code timeout_ms} when + * {@link #QUERY_FLAG_TIMEOUT} is set too. Statements that do * not produce rows ignore it. Sent only when the server advertised * {@link #CAP_QUERY_DETAILS}. */ @@ -143,14 +149,13 @@ public final class QwpEgressMsgKind { */ public static final int QUERY_FLAG_STATS = 0x08; /** - * {@code QUERY_REQUEST.query_flags} bit reserved for per-query timeouts, which - * this client does not send. Released clients (c-questdb-client 7.2.0 and - * later, and the Python client built on it) send it, followed by a - * {@code timeout_ms:varint}, to a server that advertises - * {@link #CAP_QUERY_TIMEOUT}, so no other flag may take this bit. A flag that - * carries a field appends it after {@code query_flags} in ascending order of - * the flag bits, so {@code timeout_ms} goes ahead of {@code skip_rows} and - * {@code max_rows}. Mirrors the server-side constant + * {@code QUERY_REQUEST.query_flags} bit: a {@code timeout_ms:varint} field + * follows the {@code query_flags} varint. A flag that carries a field appends + * it after {@code query_flags} in ascending order of the flag bits, so + * {@code timeout_ms} goes ahead of {@code skip_rows} and {@code max_rows}. + * The server runs the query under that timeout instead of its default + * {@code query.timeout}. Sent only when the server advertised + * {@link #CAP_QUERY_TIMEOUT}. Mirrors the server-side constant * {@code io.questdb.cutlass.qwp.codec.QwpEgressMsgKind#QUERY_FLAG_TIMEOUT}. */ public static final int QUERY_FLAG_TIMEOUT = 0x02; diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpQueryClient.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpQueryClient.java index 20caf9a23..34b71e46a 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpQueryClient.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpQueryClient.java @@ -48,8 +48,10 @@ import java.util.Base64; import java.util.List; import java.util.Random; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.LockSupport; /** * QWP egress (query results) client. @@ -92,11 +94,21 @@ * query {@code QUERY_ERROR} responses are NOT terminal -- the connection * remains usable for the next query. *

+ * Query timeout: {@code query_timeout_ms=} (or {@link #withQueryTimeout} / + * the {@code timeoutMs} argument of {@link #execute}) overrides the server's + * default query timeout ({@code query.timeout}) for each query. The client + * only sends it; the server stops the query when it can and reports + * {@link QwpConstants#STATUS_QUERY_TIMEOUT}, and the connection stays open for + * the next query. The client keeps no deadline of its own: it waits for the + * server's answer however long that takes. A server that does not advertise + * {@link QwpEgressMsgKind#CAP_QUERY_TIMEOUT} never receives the timeout and + * applies its own default. + *

* Status byte convention on {@link QwpColumnBatchHandler#onError}: server- * emitted {@code QUERY_ERROR} frames surface with the server's status code * ({@link WebSocketResponse#STATUS_PARSE_ERROR}, {@code STATUS_INTERNAL_ERROR}, * {@link QwpConstants#STATUS_CANCELLED}, {@link QwpConstants#STATUS_LIMIT_EXCEEDED}, - * etc.). Failures detected client-side (closed client, bind encoding error, + * {@link QwpConstants#STATUS_QUERY_TIMEOUT}, etc.). Failures detected client-side (closed client, bind encoding error, * truncated / unknown frame, decoder out of sync, I/O thread interrupt) all * surface with {@link WebSocketResponse#STATUS_INTERNAL_ERROR} and the * specific cause in the message. @@ -169,6 +181,9 @@ public class QwpQueryClient implements QuietCloseable { | QwpEgressMsgKind.QUERY_FLAG_COUNT_ROWS | QwpEgressMsgKind.QUERY_FLAG_SKIP_ROWS | QwpEgressMsgKind.QUERY_FLAG_MAX_ROWS; + // How often an interrupted execute() checks whether the I/O thread has + // encoded its request (see retractRequest). + private static final long REQUEST_ENCODED_POLL_NANOS = TimeUnit.MICROSECONDS.toNanos(100); // query_flags bits of the row window, which change what the server streams private static final int ROW_WINDOW_QUERY_FLAGS = QwpEgressMsgKind.QUERY_FLAG_SKIP_ROWS | QwpEgressMsgKind.QUERY_FLAG_MAX_ROWS; @@ -299,6 +314,11 @@ public class QwpQueryClient implements QuietCloseable { // re-clamp) so a misconfigured server is observable from user code. private int negotiatedZstdLevel; private long nextRequestId = 1; + // Default per-query timeout, in milliseconds, applied by the execute() + // overloads that take no explicit timeout. 0 (the default) sends none, so the + // server's own query.timeout applies. Set via query_timeout_ms or + // withQueryTimeout(); read once per execute(). + private volatile long queryTimeoutMs; // Cancel intent latched between {@link #cancel} and the point where // {@link #executeOnce} assigns {@link #currentRequestId}. Without this // latch, a cancel arriving in the dispatch window (after the user thread's @@ -375,6 +395,10 @@ private QwpQueryClient(String host, int port) { * {@link #execute}, reconnect to another endpoint and re-submit the query. * The user handler sees {@link QwpColumnBatchHandler#onFailoverReset} before * replayed batches begin arriving (batch_seq restarts at 0 on the new node). + *

  • {@code query_timeout_ms=N} -- default per-query timeout in milliseconds, + * applied by every {@link #execute} overload that takes no explicit timeout. + * {@code 0} (the default) sends none, so the server's default applies. + * See {@link #withQueryTimeout(long)}.
  • *
  • {@code username=;password=} -- HTTP Basic authentication. The client builds the * {@code Authorization: Basic } header from these. Server verifies the credentials * against the same user store the Postgres wire protocol uses, so a user created via @@ -450,6 +474,7 @@ public static QwpQueryClient fromConfig(CharSequence configurationString) { // over-int value must reject, not wrap. Integer connectTimeout = view.has("connect_timeout") ? view.getInt("connect_timeout", 0) : null; Long initialCredit = view.has("initial_credit") ? view.getLong("initial_credit", 0) : null; + Long queryTimeoutMs = view.has("query_timeout_ms") ? view.getLong("query_timeout_ms", 0) : null; int poolSize = view.getInt("buffer_pool_size", DEFAULT_IO_BUFFER_POOL_SIZE); String compression = view.getEnum("compression"); if (compression == null) { @@ -510,6 +535,9 @@ public static QwpQueryClient fromConfig(CharSequence configurationString) { if (initialCredit != null) { client.withInitialCredit(initialCredit); } + if (queryTimeoutMs != null) { + client.withQueryTimeout(queryTimeoutMs); + } client.withBufferPoolSize(poolSize); client.withCompression(compression, compressionLevel); if (tls) { @@ -814,7 +842,39 @@ public void execute(CharSequence sql, QwpBindSetter binds, QwpColumnBatchHandler * {@link QwpEgressMsgKind#CAP_QUERY_FLAGS}; otherwise it is silently ignored. */ public void execute(CharSequence sql, QwpBindSetter binds, QwpColumnBatchHandler handler, boolean resetSymbolDict) { - executeExclusive(sql, binds, handler, resetSymbolDict ? QwpEgressMsgKind.QUERY_FLAG_RESET_DICT : 0, 0, Long.MAX_VALUE); + execute(sql, binds, handler, resetSymbolDict, queryTimeoutMs); + } + + /** + * As {@link #execute(CharSequence, QwpBindSetter, QwpColumnBatchHandler, boolean)}, + * with an explicit query timeout that overrides the client default + * ({@link #withQueryTimeout(long)}, {@code query_timeout_ms}). + *

    + * The timeout overrides the server's default query timeout + * ({@code query.timeout}) for this query. When the server advertises + * {@link QwpEgressMsgKind#CAP_QUERY_TIMEOUT}, the timeout travels with the + * query, and every failover replay sends it again. The server stops the + * query when it can and ends it with a {@code QUERY_ERROR} carrying + * {@link QwpConstants#STATUS_QUERY_TIMEOUT}; the connection stays open for + * the next query. Some statements cannot be stopped and run to completion. + * An older server never receives the timeout and applies its own default. + *

    + * The client does not enforce the timeout: this call waits for the server's + * answer however long it takes. Use {@link #cancel()} to stop a query from + * the client side. + * + * @param timeoutMs query timeout in milliseconds; {@code 0} sends none, so + * the server's default applies + * @throws IllegalArgumentException when {@code timeoutMs} is negative + */ + public void execute( + CharSequence sql, + QwpBindSetter binds, + QwpColumnBatchHandler handler, + boolean resetSymbolDict, + long timeoutMs + ) { + executeExclusive(sql, binds, handler, resetSymbolDict ? QwpEgressMsgKind.QUERY_FLAG_RESET_DICT : 0, 0, Long.MAX_VALUE, timeoutMs); } /** @@ -839,10 +899,30 @@ public void execute(CharSequence sql, QwpBindSetter binds, QwpColumnBatchHandler * new server again. */ public void execute(CharSequence sql, QwpBindSetter binds, QwpColumnBatchHandler handler, QwpQueryOptions options) { + execute(sql, binds, handler, options, queryTimeoutMs); + } + + /** + * As {@link #execute(CharSequence, QwpBindSetter, QwpColumnBatchHandler, QwpQueryOptions)}, + * with an explicit query timeout that overrides the client default. See + * {@link #execute(CharSequence, QwpBindSetter, QwpColumnBatchHandler, boolean, long)} + * for how the timeout works. + * + * @param timeoutMs query timeout in milliseconds; {@code 0} sends none, so + * the server's default applies + * @throws IllegalArgumentException when {@code timeoutMs} is negative + */ + public void execute( + CharSequence sql, + QwpBindSetter binds, + QwpColumnBatchHandler handler, + QwpQueryOptions options, + long timeoutMs + ) { if (options == null) { - executeExclusive(sql, binds, handler, 0, 0, Long.MAX_VALUE); + executeExclusive(sql, binds, handler, 0, 0, Long.MAX_VALUE, timeoutMs); } else { - executeExclusive(sql, binds, handler, options.toQueryFlags(), options.getSkipRows(), options.getMaxRows()); + executeExclusive(sql, binds, handler, options.toQueryFlags(), options.getSkipRows(), options.getMaxRows(), timeoutMs); } } @@ -887,6 +967,7 @@ public java.util.Map configSnapshotForTest() { m.put("failover_max_duration_ms", failoverMaxDurationMs); m.put("max_batch_rows", maxBatchRows); m.put("initial_credit", initialCreditBytes); + m.put("query_timeout_ms", queryTimeoutMs); m.put("buffer_pool_size", bufferPoolSize); m.put("compression", compressionPreference); m.put("compression_level", compressionLevel); @@ -957,6 +1038,16 @@ public int getNegotiatedZstdLevel() { return negotiatedZstdLevel; } + /** + * Returns the default per-query timeout in milliseconds, {@code 0} when + * queries send none and the server's default applies. + * + * @see #withQueryTimeout(long) + */ + public long getQueryTimeoutMs() { + return queryTimeoutMs; + } + /** * Returns the {@link QwpServerInfo} decoded from the currently-bound * server's {@code SERVER_INFO} frame, or {@code null} if the client is not @@ -966,6 +1057,19 @@ public QwpServerInfo getServerInfo() { return serverInfo; } + /** + * Returns {@code true} when the bound connection has latched a terminal + * transport failure: the server closed it, a protocol fault occurred, or the + * I/O thread stopped responding. The next {@link #execute} then + * reconnects ({@code failover=on}) or reports the stored failure + * ({@code failover=off}). A query error reported by the server, including a + * query timeout, is not a terminal failure: the connection stays usable. + */ + public boolean hasTerminalFailure() { + GenerationListener listener = currentGenerationListener; + return listener != null && listener.get() != null; + } + /** * Connection health (design/qwp-token-provider-spec.md, section 8.4). A query client connects on demand, so * {@link ConnectionHealth.State#RECONNECTING} means its last connect or failover reconnect failed and the next @@ -1313,6 +1417,24 @@ public QwpQueryClient withMaxBatchRows(int rows) { return this; } + /** + * Sets the default per-query timeout, in milliseconds, applied by every + * {@link #execute} overload that takes no explicit timeout; {@code 0} (the + * default) sends none, so the server's default applies. Programmatic equivalent of the + * {@code query_timeout_ms=} connection-string key. Unlike the connection + * settings it may be changed at any time; it applies to subsequent + * {@code execute()} calls. See + * {@link #execute(CharSequence, QwpBindSetter, QwpColumnBatchHandler, boolean, long)} + * for the timeout semantics. + */ + public QwpQueryClient withQueryTimeout(long timeoutMs) { + if (timeoutMs < 0) { + throw new IllegalArgumentException("query timeout must be >= 0"); + } + this.queryTimeoutMs = timeoutMs; + return this; + } + /** * Overrides the {@link #DEFAULT_SERVER_INFO_TIMEOUT_MS} wait for the * {@code SERVER_INFO} frame. Must be called before {@link #connect}. @@ -1425,6 +1547,22 @@ private static void deliverClientError(QwpColumnBatchHandler handler, long reque handler.onError(requestId, status, message, QwpEgressMsgKind.NO_ERROR_POSITION); } + /** + * Hands an event the executing thread does not deliver back to the I/O + * thread, with its batch buffer: the I/O thread waits for each published + * batch to be released. + */ + private static void discardEvent(QwpEgressIoThread io, QueryEvent ev) { + if (ev.kind == QueryEvent.KIND_BATCH && ev.buffer != null) { + io.releaseBuffer(ev.buffer); + } + io.releaseEvent(ev); + } + + private static boolean isPast(long deadlineNanos) { + return System.nanoTime() - deadlineNanos >= 0; + } + @SuppressWarnings("BooleanMethodIsAlwaysInverted") private static boolean matchesTarget(byte role, String target) { if (TARGET_ANY.equals(target)) { @@ -1444,7 +1582,9 @@ private static boolean matchesTarget(byte role, String target) { /** * Returns the bits of {@code queryFlags} a server with {@code capabilities} * honours: {@link QwpEgressMsgKind#QUERY_FLAG_RESET_DICT} needs - * {@link QwpEgressMsgKind#CAP_QUERY_FLAGS}, and the query-details bits need + * {@link QwpEgressMsgKind#CAP_QUERY_FLAGS}, + * {@link QwpEgressMsgKind#QUERY_FLAG_TIMEOUT} needs + * {@link QwpEgressMsgKind#CAP_QUERY_TIMEOUT}, and the query-details bits need * {@link QwpEgressMsgKind#CAP_QUERY_DETAILS}. */ private static long resolveQueryFlags(long queryFlags, int capabilities) { @@ -1452,12 +1592,63 @@ private static long resolveQueryFlags(long queryFlags, int capabilities) { if ((capabilities & QwpEgressMsgKind.CAP_QUERY_FLAGS) == 0) { resolved &= ~QwpEgressMsgKind.QUERY_FLAG_RESET_DICT; } + if ((capabilities & QwpEgressMsgKind.CAP_QUERY_TIMEOUT) == 0) { + resolved &= ~QwpEgressMsgKind.QUERY_FLAG_TIMEOUT; + } if ((capabilities & QwpEgressMsgKind.CAP_QUERY_DETAILS) == 0) { resolved &= ~QUERY_DETAILS_FLAGS; } return resolved; } + /** + * Gives up on the connection. Latches a terminal failure carrying + * {@code failureMessage}, so the next {@link #execute} replaces the + * connection ({@code failover=on}) or reports the failure + * ({@code failover=off}) and a pool discards the client, then stops the I/O + * thread. + *

    + * Runs on the executing thread, the sole consumer of the event queue, and + * keeps releasing every batch the I/O thread still publishes while it winds + * down: the I/O thread waits uninterruptibly for each published batch to be + * released, and would otherwise outlive the joins in {@link #close()} and + * {@link #cleanupFailedConnect()}. + */ + private void abandonConnection(QwpEgressIoThread io, String failureMessage) { + GenerationListener listener = currentGenerationListener; + if (listener != null) { + listener.onTerminalFailure(WebSocketResponse.STATUS_INTERNAL_ERROR, failureMessage); + } + io.shutdown(); + Thread handle = ioThreadHandle; + if (handle == null) { + return; + } + handle.interrupt(); + final long stopDeadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(shutdownJoinMs); + boolean interrupted = false; + while (handle.isAlive() && !isPast(stopDeadlineNanos)) { + long pollDeadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(10); + if (pollDeadlineNanos - stopDeadlineNanos > 0) { + pollDeadlineNanos = stopDeadlineNanos; + } + QueryEvent ev; + try { + ev = io.takeEvent(pollDeadlineNanos); + } catch (InterruptedException e) { + // Finish stopping the I/O thread first; the flag is restored below. + interrupted = true; + continue; + } + if (ev != null) { + discardEvent(io, ev); + } + } + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + private static TokenProviderSpec validateConfigAndResolveTokenProvider(ConfigView view, boolean tls) { view.getHostPorts("addr", DEFAULT_WS_PORT, (h, p) -> { }); @@ -1480,6 +1671,7 @@ private static TokenProviderSpec validateConfigAndResolveTokenProvider(ConfigVie long backoffMax = view.getLong("failover_backoff_max_ms", -1); view.getLong("failover_max_duration_ms", -1); view.getLong("initial_credit", -1); + view.getLong("query_timeout_ms", -1); view.getLong("auth_timeout_ms", -1); // getInt: connect_timeout feeds an int API, so validation must also // reject values that fit a long but not an int. @@ -1801,8 +1993,12 @@ private void executeExclusive( QwpColumnBatchHandler handler, long queryFlags, long skipRows, - long maxRows + long maxRows, + long timeoutMs ) { + if (timeoutMs < 0) { + throw new IllegalArgumentException("timeoutMs must be >= 0"); + } if (!executing.compareAndSet(false, true)) { throw new IllegalStateException( "QwpQueryClient.execute called while another execute is in flight; one query at a time per client"); @@ -1814,7 +2010,7 @@ private void executeExclusive( // is intentionally NOT cleared inside executeOnce(). pendingCancel = false; try { - executeImpl(sql, binds, handler, queryFlags, skipRows, maxRows); + executeImpl(sql, binds, handler, queryFlags, skipRows, maxRows, timeoutMs); } finally { executing.set(false); } @@ -1826,7 +2022,8 @@ private void executeImpl( QwpColumnBatchHandler handler, long queryFlags, long skipRows, - long maxRows + long maxRows, + long timeoutMs ) { if (closedFlag.get() || isShutdownRequested) { throw new IllegalStateException("QwpQueryClient is closed"); @@ -1868,7 +2065,14 @@ private void executeImpl( } attempt++; FailoverProbeHandler probe = new FailoverProbeHandler(handler); - executeOnce(sql, binds, probe, queryFlags, skipRows, maxRows); + executeOnce(sql, binds, probe, queryFlags, skipRows, maxRows, timeoutMs); + // An interrupted attempt can end without a failover after giving up on a stuck I/O thread. + if (probe.transportFailureIntercepted || hasTerminalFailure()) { + healthTracker.connectionLost(); + if (!failoverEnabled || failoverMaxAttempts <= 1) { + healthTracker.failed(); + } + } if (!probe.transportFailureIntercepted) { return; } @@ -1882,19 +2086,10 @@ private void executeImpl( } if (!failoverEnabled) { // With failover off the transport failure stays latched: every later execute() reports it. - healthTracker.connectionLost(); - healthTracker.failed(); deliverClientError(handler, probe.interceptedRequestId, probe.interceptedStatus, probe.interceptedMessage); return; } if (attempt >= failoverMaxAttempts || System.nanoTime() - failoverDeadlineNanos >= 0) { - // The connection is dead: its generation latched the transport failure, so no later query runs on - // it. Record the loss, as the exits below do. With a single attempt per execute(), every later - // execute() ends here on that same latch and never reconnects: terminal, as with failover off. - healthTracker.connectionLost(); - if (failoverMaxAttempts <= 1) { - healthTracker.failed(); - } int failovers = Math.max(0, attempt - 1); deliverClientError(handler, probe.interceptedRequestId, probe.interceptedStatus, "transport failure after " + attempt + " execute attempt" @@ -1910,7 +2105,6 @@ private void executeImpl( } cleanupFailedConnect(); connected = false; - healthTracker.connectionLost(); // Every exit from here on - an exhausted deadline, an interrupted backoff, a failed reconnect - leaves // the client disconnected; the next execute() reconnects rather than throw "not connected". isReconnectOnNextExecute = true; @@ -2003,6 +2197,19 @@ private void executeImpl( * Inner loop for a single query attempt. Driven by {@link #execute}; wraps * the user's handler in a {@link FailoverProbeHandler} so that the outer * loop can intercept transport failures before they reach the user. + *

    + * A timeout ({@code timeoutMs > 0}) only goes on the wire, to a server that + * advertises {@link QwpEgressMsgKind#CAP_QUERY_TIMEOUT}. The attempt keeps + * no deadline of its own and waits for the query's last frame. + *

    + * An attempt that ends before its query's last frame -- the handler threw + * from {@code onBatch}, or the thread was interrupted -- leaves the query + * running on the connection, and cancels it. The I/O thread still works + * through it before it sends the next query, so the next attempt skips the + * leftover events: each event carries the id of its query (see + * {@link QueryEvent#requestId}). An interrupt that comes before the I/O + * thread has encoded the request takes the request back, or waits for the + * encoding, before the caller hears about it (see {@link #retractRequest}). */ private void executeOnce( CharSequence sql, @@ -2010,7 +2217,8 @@ private void executeOnce( FailoverProbeHandler probe, long queryFlags, long skipRows, - long maxRows + long maxRows, + long timeoutMs ) { // Cache the I/O thread reference at entry: close() may null the field while // we are inside this loop, so reading the field per-iteration would NPE @@ -2034,7 +2242,13 @@ private void executeOnce( // could clear it, and then no flag goes out. final QwpServerInfo info = serverInfo; final int capabilities = info != null ? info.getCapabilities() : 0; - final long wireQueryFlags = resolveQueryFlags(queryFlags, capabilities); + // A server without CAP_QUERY_TIMEOUT never sees the timeout and applies + // its own default (see resolveQueryFlags). + final long requestedQueryFlags = timeoutMs > 0 + ? queryFlags | QwpEgressMsgKind.QUERY_FLAG_TIMEOUT + : queryFlags & ~QwpEgressMsgKind.QUERY_FLAG_TIMEOUT; + final long wireQueryFlags = resolveQueryFlags(requestedQueryFlags, capabilities); + final long wireTimeoutMs = (wireQueryFlags & QwpEgressMsgKind.QUERY_FLAG_TIMEOUT) != 0 ? timeoutMs : 0L; if ((wireQueryFlags & ROW_WINDOW_QUERY_FLAGS) != (queryFlags & ROW_WINDOW_QUERY_FLAGS)) { // A server that does not know the row window would stream every // row of the result set. Like a bind error, this is deterministic @@ -2073,12 +2287,28 @@ private void executeOnce( if (pendingCancel) { io.requestCancel(requestId); } + boolean submitted = false; + // Set once the attempt has taken its query's last event, or given up on + // the connection: the query no longer runs on it. + boolean settled = false; try { io.submitQuery(sql, requestId, initialCreditBytes, bindValues.count(), bindValues.bufferPtr(), bindValues.bufferLen(), - wireQueryFlags, skipRows, maxRows); + wireQueryFlags, wireTimeoutMs, skipRows, maxRows); + submitted = true; boolean isBatchSkipped = false; while (true) { QueryEvent ev = io.takeEvent(); + if (ev.isForOtherRequest(requestId)) { + // A leftover of an earlier query whose attempt ended before that + // query did. Not this query's; skip it. + discardEvent(io, ev); + continue; + } + if (ev.kind != QueryEvent.KIND_BATCH) { + // Every other event ends the query on the connection, and the + // attempt returns once the switch below handles it. + settled = true; + } try { switch (ev.kind) { case QueryEvent.KIND_BATCH: @@ -2107,6 +2337,7 @@ private void executeOnce( probe.onExecDone(requestId, ev.opType, ev.rowsAffected, ev.details); return; case QueryEvent.KIND_ERROR: + // Includes the server's own STATUS_QUERY_TIMEOUT report. probe.onError(requestId, ev.errorStatus, ev.errorMessage, ev.errorPosition); return; case QueryEvent.KIND_TRANSPORT_ERROR: @@ -2128,9 +2359,20 @@ private void executeOnce( } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); + // Before the caller hears about the interrupt: the I/O thread must be + // done with the request (see retractRequest). + if (submitted && !io.isRequestEncoded(requestId) && retractRequest(io, requestId)) { + settled = true; + } // Interrupt on the user thread is not a transport failure; surface directly. probe.deliverFinal(requestId, "interrupted while waiting for server response"); } finally { + if (submitted && !settled) { + // The attempt ends while its query still runs: the handler threw, + // or the thread was interrupted. Cancel the query, so the leftovers + // the next attempt skips stop coming. + io.requestCancel(requestId); + } currentRequestId = -1L; } } @@ -2359,6 +2601,54 @@ private String resolveAuthorizationHeader() { return authorizationHeader; } + /** + * Makes sure the I/O thread no longer reads the request {@code requestId}, + * which an interrupted {@code execute()} stops waiting for before the I/O + * thread has encoded it. Until then the I/O thread reads the caller's SQL + * text, which the caller may change once it learns about the interrupt, and + * this client's request holder and bind buffer, which the next query reuses. + *

    + * A request the I/O thread has not picked up yet is withdrawn: it is never + * sent. One it has picked up is awaited -- encoding is CPU work, done + * microseconds after the pick-up -- without regard to interrupts. An I/O + * thread that is still not done after {@link #shutdownJoinMs} is stuck, and + * the connection is given up. + * + * @return {@code true} when the query does not run on the connection: it was + * withdrawn, or the connection was given up + */ + private boolean retractRequest(QwpEgressIoThread io, long requestId) { + if (io.withdrawRequest(requestId)) { + return true; + } + final Thread handle = ioThreadHandle; + // parkNanos() returns at once while the interrupt flag is set, so clear it + // for the wait, and restore it after. + boolean interrupted = Thread.interrupted(); + try { + final long deadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(shutdownJoinMs); + while (!io.isRequestEncoded(requestId)) { + if (handle == null || !handle.isAlive()) { + // A stopped I/O thread reads nothing more. + return true; + } + if (isPast(deadlineNanos)) { + LOG.warn("QwpQueryClient I/O thread did not finish sending an interrupted query within {}ms; " + + "closing the connection", shutdownJoinMs); + abandonConnection(io, "I/O thread stopped responding"); + return true; + } + LockSupport.parkNanos(REQUEST_ENCODED_POLL_NANOS); + interrupted |= Thread.interrupted(); + } + return false; + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } + private void runUpgradeWithTimeout(Endpoint ep, String authHeader) { // Connect first, OUTSIDE the upgrade try. A connect-phase failure -- // including a connect_timeout overage flagged via flagAsTimeout() -- must @@ -2531,6 +2821,7 @@ void markTransportFailure(long requestId, byte status, String message) { interceptedStatus = status; interceptedMessage = message; } + } /** diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpSpscQueue.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpSpscQueue.java index c5c292d32..f8fb6c3a7 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpSpscQueue.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpSpscQueue.java @@ -146,4 +146,47 @@ public T take() throws InterruptedException { consumerThread = null; } } + + /** + * Spin-then-park take bounded by an absolute {@link System#nanoTime()} + * deadline. Returns the next value, or {@code null} once the deadline has + * passed with the ring still empty. A deadline already in the past + * degenerates to a single {@link #poll()}: a value that is already + * available is still returned. Allocation-free, like {@link #take()}. + * + * @throws InterruptedException when the consumer thread was interrupted + * while waiting + */ + public T take(long deadlineNanos) throws InterruptedException { + T value = poll(); + if (value != null) { + return value; + } + if (deadlineNanos - System.nanoTime() <= 0) { + return null; + } + for (int i = 0; i < SPIN_ITERATIONS; i++) { + Compat.onSpinWait(); + if ((value = poll()) != null) { + return value; + } + } + // Same publish-then-re-poll handshake as take(); see the comment there. + consumerThread = Thread.currentThread(); + try { + while ((value = poll()) == null) { + if (Thread.interrupted()) { + throw new InterruptedException(); + } + final long remainingNanos = deadlineNanos - System.nanoTime(); + if (remainingNanos <= 0) { + return null; + } + LockSupport.parkNanos(remainingNanos); + } + return value; + } finally { + consumerThread = null; + } + } } diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpConstants.java b/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpConstants.java index 0fa7a6455..8c0794148 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpConstants.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpConstants.java @@ -121,6 +121,15 @@ public final class QwpConstants { * the ingress {@code STATUS_*} namespace (0x00-0x09). */ public static final byte STATUS_LIMIT_EXCEEDED = 0x0B; + /** + * Status byte on a {@code QUERY_ERROR} frame: the query ran past its + * per-query timeout. Sent by a server that enforces the timeout carried on + * {@code QUERY_REQUEST} (see {@code QwpEgressMsgKind#CAP_QUERY_TIMEOUT}). + * The connection stays usable for the next query. Egress extension of the + * ingress {@code STATUS_*} namespace; the next free value after + * {@code STATUS_DICTIONARY_GAP} (0x0D). + */ + public static final byte STATUS_QUERY_TIMEOUT = 0x0E; /** * Column type: BINARY (length-prefixed opaque bytes). * Wire format: identical to VARCHAR — (N+1) x uint32 offsets + concatenated bytes. diff --git a/core/src/main/java/io/questdb/client/impl/ConfigSchema.java b/core/src/main/java/io/questdb/client/impl/ConfigSchema.java index 79830ece0..1f692eb86 100644 --- a/core/src/main/java/io/questdb/client/impl/ConfigSchema.java +++ b/core/src/main/java/io/questdb/client/impl/ConfigSchema.java @@ -115,6 +115,7 @@ public final class ConfigSchema { longRange("failover_max_duration_ms", Side.EGRESS, 0, OPEN_MAX, false, false); // >= 0 intRange("max_batch_rows", Side.EGRESS, 1, 1_048_576, false, false); // [1, 1048576] longRange("initial_credit", Side.EGRESS, 0, OPEN_MAX, false, false); // >= 0 + longRange("query_timeout_ms", Side.EGRESS, 0, OPEN_MAX, false, false); // >= 0; 0 = no timeout intRange("buffer_pool_size", Side.EGRESS, 1, OPEN_MAX, false, false); // >= 1 enumKey("compression", Side.EGRESS, "zstd", "raw", "auto"); intRange("compression_level", Side.EGRESS, 1, 22, false, false); // [1, 22] diff --git a/core/src/main/java/io/questdb/client/impl/QueryImpl.java b/core/src/main/java/io/questdb/client/impl/QueryImpl.java index 54b8c12af..fb6b27e0f 100644 --- a/core/src/main/java/io/questdb/client/impl/QueryImpl.java +++ b/core/src/main/java/io/questdb/client/impl/QueryImpl.java @@ -84,10 +84,26 @@ final class QueryImpl { private final QueryWorker worker; private final QwpBindSetter wireBinds = this::applyBinds; private final WrappingHandler wrappingHandler = new WrappingHandler(); + // Set when this lease cancels its current submission; cleared by submit(). + // applyBinds() re-applies it from inside execute(), so a cancel issued while + // the submission still waits for the worker is not lost. See requestCancel(). + private volatile boolean cancelRequested; private volatile boolean done = true; private volatile String resultMessage; private volatile int resultPosition = QwpEgressMsgKind.NO_ERROR_POSITION; private volatile byte resultStatus; + // Counts submit() calls. Written under doneLock; volatile so runOn() can read + // it without the lock. Lets runOn() tell its own submission from a later one, + // see signalUnexpected(long, Throwable). + private volatile long submissionSeq; + // Stamped by submit() for the worker thread: the timeout the query sends to + // the server (0 = none, the server's default applies). Published by + // worker.dispatch(). + private long submitTimeoutMillis; + // Query timeout set on this handle, in milliseconds: -1 = the pooled client's + // default (query_timeout_ms), 0 = none. Kept across submits like the other + // builder state; abandon() and resetForBorrow() restore -1. + private long timeoutMillis = -1; private volatile Throwable unexpectedError; private QwpBindSetter userBinds; private QwpColumnBatchHandler userHandler; @@ -106,6 +122,7 @@ void abandon(long gen) { userHandler = null; options.clear(); sqlBuffer.clear(); + timeoutMillis = -1; } void await(long gen) throws InterruptedException { @@ -189,6 +206,12 @@ void close(long gen) { return; } } + // A connection that failed -- the server closed it, or the client gave + // up on a stuck I/O thread -- must not go back to the pool. + if (worker.client().hasTerminalFailure()) { + worker.discardFromPool(gen); + return; + } worker.releaseToPool(gen); } @@ -232,6 +255,29 @@ void setSql(long gen, CharSequence sql) { sqlBuffer.put(sql); } + /** + * Records that the current submission was cancelled. Called by + * {@link QueryWorker#cancelInFlight()} under the pool lock, after the lease + * generation was validated, so a stale handle cannot mark a later borrower's + * query. Needed because {@code execute()} starts by clearing the client's + * cancel latch: a cancel that lands while the submission still waits for the + * worker -- for instance while the worker thread is still returning from the + * previous query's {@code runOn()} -- would otherwise be dropped. + */ + void requestCancel() { + cancelRequested = true; + } + + void setTimeout(long gen, long timeout, TimeUnit unit) { + checkLive(gen); + if (timeout < 0) { + throw new IllegalArgumentException("timeout must be >= 0"); + } + long millis = unit.toMillis(timeout); + // A positive timeout below one millisecond must not round down to "none". + this.timeoutMillis = millis == 0 && timeout > 0 ? 1 : millis; + } + void submit(long gen) { checkLive(gen); if (sqlBuffer.length() == 0) { @@ -243,11 +289,14 @@ void submit(long gen) { if (!done) { throw new IllegalStateException("a previous submit() is still in flight; await the Completion first"); } + submitTimeoutMillis = timeoutMillis >= 0 ? timeoutMillis : worker.client().getQueryTimeoutMs(); + cancelRequested = false; // Reset terminal state under the lock so a stale signal from a prior // run can't be observed by the upcoming await(). doneLock.lock(); try { done = false; + submissionSeq++; resultStatus = 0; resultMessage = null; resultPosition = QwpEgressMsgKind.NO_ERROR_POSITION; @@ -259,7 +308,19 @@ void submit(long gen) { worker.dispatch(this); } + private static String describe(Throwable t) { + String message = t.getMessage(); + return message != null ? message : t.getClass().getSimpleName(); + } + private void applyBinds(QwpBindValues binds) { + // Runs inside execute() after it cleared the client's cancel latch for + // this query, and before the request is sent: set the latch again if the + // lease cancelled the submission meanwhile, so the query goes out with + // its CANCEL right behind it. + if (cancelRequested) { + worker.client().cancel(); + } QwpBindSetter setter = userBinds; if (setter != null) { setter.apply(binds); @@ -337,6 +398,29 @@ private void signalDone(byte status, String message, int position, Throwable une } } + /** + * Signals an error that escaped the run of {@code submission}, unless a later + * {@link #submit} has taken that submission's place. A run can end with an + * exception after it signalled its outcome: when a terminal handler callback + * throws, {@link WrappingHandler} signals the outcome before the exception + * leaves {@code execute()}, and the caller, already released, may have + * submitted again meanwhile. That exception must not become the newer submission's outcome. + * The check and the signal share {@code doneLock}, which {@code submit()} + * takes to start a submission. + */ + private void signalUnexpected(long submission, Throwable t) { + // getMessage() may be user code: run it before taking the lock submit() needs. + final String message = describe(t); + doneLock.lock(); + try { + if (submission == submissionSeq) { + signalDone((byte) 0, message, t); + } + } finally { + doneLock.unlock(); + } + } + private void throwIfFailed() { Throwable unexpected = unexpectedError; if (unexpected != null) { @@ -352,14 +436,18 @@ private void throwIfFailed() { * {@link QueryWorker#lease()} when {@link QuestDBImpl#borrowQuery()} hands a * freshly stamped {@link QueryLease} out, so each borrow starts from the * documented "reset to empty" contract on {@link io.questdb.client.Query}. - * The leased worker is idle at this point (just acquired from the pool), so - * the reset is unconditional. + * The reset is unconditional: the worker was just acquired from the pool, so + * its previous job, if any, is past its terminal callback and can no longer + * change this state -- even while the worker thread is still returning from + * that job's {@code runOn()}. */ void resetForBorrow() { userBinds = null; userHandler = null; options.clear(); sqlBuffer.clear(); + timeoutMillis = -1; + cancelRequested = false; resultStatus = 0; resultMessage = null; resultPosition = QwpEgressMsgKind.NO_ERROR_POSITION; @@ -368,15 +456,22 @@ void resetForBorrow() { } void runOn(QwpQueryClient client) { + // The submission this run executes. No later submit() can happen before + // the run signals this one's outcome, so the value is stable until then. + final long submission = submissionSeq; // Pass the StringSink directly as a CharSequence -- the wire encoder // reads chars and writes UTF-8 bytes straight into the send buffer. // The query reads sqlBuffer, the binds and the handler while it runs; // the Query contract tells the caller not to change them before - // await() returns, but nothing enforces it. The options come from - // submittedOptions instead, which submit() filled: execute() reads them - // once, when it starts, and options() may change the handle's options - // for the next query meanwhile. - client.execute(sqlBuffer, wireBinds, wrappingHandler, submittedOptions); + // await() returns, but nothing enforces it. The options come from submittedOptions + // instead, which submit() filled: execute() reads them once, when it + // starts, and options() may change the handle's options for the next + // query meanwhile. + try { + client.execute(sqlBuffer, wireBinds, wrappingHandler, submittedOptions, submitTimeoutMillis); + } catch (Throwable t) { + signalUnexpected(submission, t); + } } /** @@ -384,7 +479,7 @@ void runOn(QwpQueryClient client) { * exception escaping {@code execute()} before any handler callback). */ void signalUnexpected(Throwable t) { - signalDone((byte) 0, t.getMessage() != null ? t.getMessage() : t.getClass().getSimpleName(), t); + signalDone((byte) 0, describe(t), t); } private final class WrappingHandler implements QwpColumnBatchHandler { diff --git a/core/src/main/java/io/questdb/client/impl/QueryLease.java b/core/src/main/java/io/questdb/client/impl/QueryLease.java index 398596c40..d0ece91bc 100644 --- a/core/src/main/java/io/questdb/client/impl/QueryLease.java +++ b/core/src/main/java/io/questdb/client/impl/QueryLease.java @@ -120,4 +120,10 @@ public Completion submit() { public QwpServerInfo serverInfo() { return impl.serverInfo(generation); } + + @Override + public Query timeout(long timeout, TimeUnit unit) { + impl.setTimeout(generation, timeout, unit); + return this; + } } diff --git a/core/src/main/java/io/questdb/client/impl/QueryWorker.java b/core/src/main/java/io/questdb/client/impl/QueryWorker.java index 4a8608f67..80162ed81 100644 --- a/core/src/main/java/io/questdb/client/impl/QueryWorker.java +++ b/core/src/main/java/io/questdb/client/impl/QueryWorker.java @@ -153,6 +153,10 @@ void markIdleAt(long nowMillis) { * generation first. Lease code must use {@link #cancelInFlight(long)}. */ void cancelInFlight() { + // Remembered on the lease too: a submission still waiting for this worker + // (its thread still returning from the previous job) has not reached the + // client yet. + query.requestCancel(); try { client.cancel(); } catch (RuntimeException ignored) { diff --git a/core/src/test/java/io/questdb/client/test/QueryTimeoutFacadeTest.java b/core/src/test/java/io/questdb/client/test/QueryTimeoutFacadeTest.java new file mode 100644 index 000000000..cbd7cabad --- /dev/null +++ b/core/src/test/java/io/questdb/client/test/QueryTimeoutFacadeTest.java @@ -0,0 +1,576 @@ +/*+***************************************************************************** + * ___ _ ____ ____ + * / _ \ _ _ ___ ___| |_| _ \| __ ) + * | | | | | | |/ _ \/ __| __| | | | _ \ + * | |_| | |_| | __/\__ \ |_| |_| | |_) | + * \__\_\\__,_|\___||___/\__|____/|____/ + * + * Copyright (c) 2014-2019 Appsicle + * Copyright (c) 2019-2026 QuestDB + * + * Licensed 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 io.questdb.client.test; + +import io.questdb.client.Completion; +import io.questdb.client.Query; +import io.questdb.client.QueryException; +import io.questdb.client.QuestDB; +import io.questdb.client.cutlass.qwp.client.QwpColumnBatch; +import io.questdb.client.cutlass.qwp.client.QwpColumnBatchHandler; +import io.questdb.client.cutlass.qwp.client.QwpEgressMsgKind; +import io.questdb.client.cutlass.qwp.protocol.QwpConstants; +import io.questdb.client.impl.QuestDBImpl; +import io.questdb.client.test.cutlass.qwp.client.QwpEgressFrames; +import io.questdb.client.test.cutlass.qwp.websocket.TestWebSocketServer; +import io.questdb.client.test.tools.TestUtils; +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * {@link Query#timeout} through the {@link QuestDB} facade: the timeout goes to + * the server as an override of its default, and the client keeps no deadline of + * its own. A query the server stops is reported as a {@link QueryException} + * whose {@link QueryException#isTimeout()} holds, however late the server + * reports it, while the pooled, authenticated connection stays open and serves + * the following queries. A worker whose connection failed is replaced rather + * than reused, while one whose query has ended goes back to the pool at once -- + * even when close() has no budget or the caller's interrupt flag is set. A + * handler that throws -- on the timeout, or mid-result -- fails only its own + * submission. + */ +public class QueryTimeoutFacadeTest { + + @Test(timeout = 30_000) + public void testAbandonRestoresTheDefaultTimeout() throws Exception { + TestUtils.assertMemoryLeak(() -> { + Script script = new Script(); + script.onQuery = (s, c, id, n) -> s.send(c, QwpEgressFrames.resultEnd(id, 0, 0).toFrame()); + try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT); + QuestDB db = QuestDB.connect(config(server) + "query_timeout_ms=100;")) { + try (Query q = db.borrowQuery()) { + q.sql("SELECT a()").handler(new NoopHandler()).timeout(7, TimeUnit.MILLISECONDS); + q.abandon(); + q.sql("SELECT b()").handler(new NoopHandler()).submit().await(); + Assert.assertEquals("abandon() must drop the handle's timeout", 100L, (long) script.timeouts.take()); + } + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testAwaitWaitsForTheServerPastTheTimeout() throws Exception { + TestUtils.assertMemoryLeak(() -> { + final long timeoutMs = 100; + final long replyDelayMs = 1_500; + Script script = new Script(); + script.onQuery = (s, c, id, n) -> { + if (n == 1) { + s.sendLater(c, replyDelayMs, QwpEgressFrames.queryError(id, QwpConstants.STATUS_QUERY_TIMEOUT, + "timeout, query aborted").toFrame()); + } else { + s.send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame()); + } + }; + // failover=off and a short close budget: a client that gave up on the + // slow query would fail every later query on this connection. + try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT); + QuestDB db = QuestDB.connect(config(server) + "query_close_timeout_ms=200;failover=off;")) { + try (Query q = db.borrowQuery()) { + q.sql("SELECT slow()").handler(new NoopHandler()).timeout(timeoutMs, TimeUnit.MILLISECONDS); + long start = System.nanoTime(); + QueryException e = assertTimesOut(q); + long awaitMs = elapsedMs(start); + Assert.assertEquals("timeout, query aborted", e.getMessage()); + Assert.assertTrue("await() must wait for the server's report, returned after " + awaitMs + "ms", + awaitMs >= replyDelayMs); + } + try (Query q = db.borrowQuery()) { + q.sql("INSERT INTO t VALUES (1)").handler(new NoopHandler()); + assertOwnOutcome(q); + } + Assert.assertEquals("a slow query must not cost the connection", 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testCancelOfASubmissionWaitingForTheWorkerIsNotLost() throws Exception { + TestUtils.assertMemoryLeak(() -> { + Script script = new Script(); + script.onQuery = (s, c, id, n) -> { + if (n == 1) { + s.send(c, QwpEgressFrames.resultEnd(id, 0, 0).toFrame()); + } + // n == 2: held; only a CANCEL ends it + }; + script.onCancel = (s, c, id) -> s.send(c, + QwpEgressFrames.queryError(id, QwpConstants.STATUS_CANCELLED, "cancelled by client").toFrame()); + try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT); + QuestDB db = QuestDB.connect(config(server)); + Query q = db.borrowQuery()) { + // Park the worker thread once, after the first query, so the second + // submission waits for it and is cancelled before execute() starts. + CountDownLatch release = new CountDownLatch(1); + AtomicBoolean isParkPending = new AtomicBoolean(true); + ((QuestDBImpl) db).getQueryPoolForTesting().setBusyWorkerHookForTesting(() -> { + if (isParkPending.compareAndSet(true, false)) { + try { + release.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + }); + q.sql("SELECT s FROM t").handler(new NoopHandler()); + Completion waiting; + try { + q.submit().await(); + waiting = q.submit(); + waiting.cancel(); + } finally { + release.countDown(); + } + try { + Assert.assertTrue("the cancelled query must end", waiting.await(10, TimeUnit.SECONDS)); + Assert.fail("the cancelled query must not complete"); + } catch (QueryException e) { + Assert.assertEquals("the cancel must reach the query: " + e.getMessage(), + QwpConstants.STATUS_CANCELLED, e.getStatus()); + } + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testCloseWithoutBudgetKeepsTheConnectionOfCompletedQueries() throws Exception { + assertCloseKeepsTheConnectionOfCompletedQueries("query_close_timeout_ms=0;", false); + } + + @Test(timeout = 30_000) + public void testConfiguredDefaultAppliesAndHandleCanOverrideIt() throws Exception { + TestUtils.assertMemoryLeak(() -> { + Script script = new Script(); + script.onQuery = (s, c, id, n) -> s.send(c, QwpEgressFrames.resultEnd(id, 0, 0).toFrame()); + try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT); + QuestDB db = QuestDB.connect(config(server) + "query_timeout_ms=100;")) { + try (Query q = db.borrowQuery()) { + q.sql("SELECT 1").handler(new NoopHandler()); + q.submit().await(); + Assert.assertEquals("the configured default must go on the wire", 100L, (long) script.timeouts.take()); + + q.timeout(250, TimeUnit.MILLISECONDS).submit().await(); + Assert.assertEquals("the handle's timeout must override the default", 250L, (long) script.timeouts.take()); + + q.timeout(1, TimeUnit.MICROSECONDS).submit().await(); + Assert.assertEquals("a positive timeout below 1ms must not become none", 1L, (long) script.timeouts.take()); + + q.timeout(0, TimeUnit.MILLISECONDS).submit().await(); + Assert.assertEquals("timeout 0 must send none, so the server's default applies", + -1L, (long) script.timeouts.take()); + } + // A fresh borrow starts from the configured default again. + try (Query q = db.borrowQuery()) { + q.sql("SELECT 1").handler(new NoopHandler()).submit().await(); + Assert.assertEquals(100L, (long) script.timeouts.take()); + } + Assert.assertEquals("all queries must share one connection", 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testInterruptedCloseKeepsTheConnectionOfCompletedQueries() throws Exception { + assertCloseKeepsTheConnectionOfCompletedQueries("", true); + } + + @Test(timeout = 30_000) + public void testThrowingBatchHandlerFailsOnlyItsOwnSubmission() throws Exception { + TestUtils.assertMemoryLeak(() -> { + Script script = new Script(); + script.onQuery = (s, c, id, n) -> { + if (n == 1) { + s.send(c, QwpEgressFrames.resultBatchOfLongs(id, 0, 1)); + // The rest of the result arrives after the handler has thrown. + s.sendLater(c, 300, QwpEgressFrames.resultBatchOfLongs(id, 1, 2)); + s.sendLater(c, 300, QwpEgressFrames.resultEnd(id, 1, 2).toFrame()); + } else { + s.send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame()); + } + }; + try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT); + QuestDB db = QuestDB.connect(config(server)); + Query q = db.borrowQuery()) { + final IllegalStateException failure = new IllegalStateException("handler failed"); + q.sql("SELECT s FROM t").handler(new QwpColumnBatchHandler() { + @Override + public void onBatch(QwpColumnBatch batch) { + throw failure; + } + + @Override + public void onEnd(long totalRows) { + } + + @Override + public void onError(byte status, String message) { + } + }); + try { + q.submit().await(); + Assert.fail("the submission whose handler threw must fail"); + } catch (QueryException e) { + Assert.assertSame("the handler's exception must be its own submission's outcome", + failure, e.getCause()); + } + + RecordingHandler next = new RecordingHandler(); + q.sql("INSERT INTO t VALUES (1)").handler(next); + assertOwnOutcome(q); + Assert.assertTrue("the next submission must get its own reply", next.execDone); + Assert.assertEquals("the abandoned query's rows must not reach the next submission", + 0, next.batches.get()); + Assert.assertEquals("the connection must be reused", 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testThrowingHandlerLeavesTheNextSubmissionIntact() throws Exception { + TestUtils.assertMemoryLeak(() -> { + Script script = new Script(); + script.onQuery = (s, c, id, n) -> { + if (n == 1) { + s.sendLater(c, 150, QwpEgressFrames.queryError(id, QwpConstants.STATUS_QUERY_TIMEOUT, + "timeout, query aborted").toFrame()); + } else { + s.send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame()); + } + }; + try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT); + QuestDB db = QuestDB.connect(config(server))) { + try (Query q = db.borrowQuery()) { + q.sql("SELECT slow()").handler(new QwpColumnBatchHandler() { + @Override + public void onBatch(QwpColumnBatch batch) { + } + + @Override + public void onEnd(long totalRows) { + } + + @Override + public void onError(byte status, String message) { + throw new IllegalStateException("handler failed: " + message); + } + }).timeout(100, TimeUnit.MILLISECONDS); + // onError releases the caller before its exception leaves the + // worker's execute(), so the next submission can race that exception. + assertTimesOut(q); + + q.sql("INSERT INTO t VALUES (1)").handler(new NoopHandler()).timeout(0, TimeUnit.MILLISECONDS); + assertOwnOutcome(q); + } + try (Query q = db.borrowQuery()) { + q.sql("INSERT INTO t VALUES (2)").handler(new NoopHandler()); + assertOwnOutcome(q); + } + Assert.assertEquals("the connection must be reused", 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testTimedOutQueryKeepsThePooledConnection() throws Exception { + TestUtils.assertMemoryLeak(() -> { + Script script = new Script(); + script.onQuery = (s, c, id, n) -> { + if (n == 1) { + s.sendLater(c, 150, QwpEgressFrames.queryError(id, QwpConstants.STATUS_QUERY_TIMEOUT, + "timeout, query aborted [runtime=150ms, timeout=100ms]").toFrame()); + } else { + s.send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame()); + } + }; + try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT); + QuestDB db = QuestDB.connect(config(server))) { + try (Query q = db.borrowQuery()) { + q.sql("SELECT slow()").handler(new NoopHandler()).timeout(100, TimeUnit.MILLISECONDS); + QueryException e = assertTimesOut(q); + Assert.assertTrue("the server's report must reach the caller: " + e.getMessage(), + e.getMessage().startsWith("timeout, query aborted")); + + // The same handle, and so the same connection, runs the next query. + q.sql("INSERT INTO t VALUES (1)").submit().await(); + } + try (Query q = db.borrowQuery()) { + q.sql("INSERT INTO t VALUES (2)").handler(new NoopHandler()).submit().await(); + } + Assert.assertEquals("the authenticated connection must be kept across the timeout", + 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testWorkerWhoseConnectionFailedIsReplaced() throws Exception { + TestUtils.assertMemoryLeak(() -> { + Script script = new Script(); + script.onQuery = (s, c, id, n) -> { + if (n == 1) { + s.closeConnection(c); + } else { + s.send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame()); + } + }; + // failover=off: the client cannot replace the connection by itself, so + // the next query succeeds only if the pool discarded the worker. + try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT); + QuestDB db = QuestDB.connect(config(server) + "failover=off;")) { + try (Query q = db.borrowQuery()) { + q.sql("SELECT slow()").handler(new NoopHandler()).timeout(100, TimeUnit.MILLISECONDS); + try { + q.submit().await(); + Assert.fail("the query must fail with its connection"); + } catch (QueryException e) { + Assert.assertFalse("a failed connection is not a timeout: " + e.getMessage(), e.isTimeout()); + } + } + try (Query q = db.borrowQuery()) { + q.sql("INSERT INTO t VALUES (1)").handler(new NoopHandler()); + assertOwnOutcome(q); + } + Assert.assertEquals("the failed connection must be replaced by a new one", 2, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + /** + * The terminal callback releases the caller while the worker thread is + * still returning from the job, so close() regularly lands in that + * window. close() must return the worker there without waiting for the + * thread: with no budget, or with the caller's interrupt flag set, a wait + * would give up at once and discard a healthy worker, and each discard + * would show as one more connection. Hitting the window is a matter of + * timing, hence the 2,000 cycles. + */ + private static void assertCloseKeepsTheConnectionOfCompletedQueries( + String extraConfig, + boolean interruptBeforeClose + ) throws Exception { + TestUtils.assertMemoryLeak(() -> { + Script script = new Script(); + script.onQuery = (s, c, id, n) -> s.send(c, QwpEgressFrames.resultEnd(id, 0, 0).toFrame()); + try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT); + QuestDB db = QuestDB.connect(config(server) + extraConfig)) { + NoopHandler handler = new NoopHandler(); + for (int i = 0; i < 2_000; i++) { + try (Query q = db.borrowQuery()) { + q.sql("SELECT 1").handler(handler).submit().await(); + if (interruptBeforeClose) { + Thread.currentThread().interrupt(); + } + } + if (interruptBeforeClose) { + Assert.assertTrue("close() must preserve the caller's interrupt flag", Thread.interrupted()); + } + } + Assert.assertEquals("closing a handle whose query has ended must keep its connection", + 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + private static void assertOwnOutcome(Query q) throws InterruptedException { + try { + q.submit().await(); + } catch (QueryException e) { + Assert.fail("the submission must get its own outcome, got status=" + e.getStatus() + + ", message=" + e.getMessage() + ", cause=" + e.getCause()); + } + } + + private static QueryException assertTimesOut(Query q) throws InterruptedException { + try { + q.submit().await(); + } catch (QueryException e) { + Assert.assertTrue("expected a query timeout, got status=" + e.getStatus() + ": " + e.getMessage(), + e.isTimeout()); + return e; + } + Assert.fail("the query must time out"); + return null; + } + + private static String config(TestWebSocketServer server) { + return "ws::addr=localhost:" + server.getPort() + + ";auth_timeout_ms=2000;sender_pool_min=0;query_pool_min=1;query_pool_max=1;"; + } + + private static long elapsedMs(long startNanos) { + return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); + } + + private static TestWebSocketServer startServer(Script script, int capabilities) throws Exception { + TestWebSocketServer server = new TestWebSocketServer(script); + server.setSendServerInfo(true); + server.setCapabilities(capabilities); + server.start(); + Assert.assertTrue(server.awaitStart(5, TimeUnit.SECONDS)); + return server; + } + + @FunctionalInterface + private interface OnCancel { + void run(Script script, TestWebSocketServer.ClientHandler client, long requestId); + } + + @FunctionalInterface + private interface OnQuery { + void run(Script script, TestWebSocketServer.ClientHandler client, long requestId, int queryNumber); + } + + private static final class NoopHandler implements QwpColumnBatchHandler { + @Override + public void onBatch(QwpColumnBatch batch) { + } + + @Override + public void onEnd(long totalRows) { + } + + @Override + public void onError(byte status, String message) { + } + } + + private static final class RecordingHandler implements QwpColumnBatchHandler { + final AtomicInteger batches = new AtomicInteger(); + volatile boolean execDone; + + @Override + public void onBatch(QwpColumnBatch batch) { + batches.incrementAndGet(); + } + + @Override + public void onEnd(long totalRows) { + } + + @Override + public void onError(byte status, String message) { + } + + @Override + public void onExecDone(short opType, long rowsAffected) { + execDone = true; + } + } + + /** + * Scripted egress server. Records the {@code timeout_ms} of every + * {@code QUERY_REQUEST} and answers queries and cancels as each test scripts. + */ + private static final class Script implements TestWebSocketServer.WebSocketServerHandler, AutoCloseable { + // timeout_ms of each QUERY_REQUEST, in order; -1 when the request carries none. + final LinkedBlockingQueue timeouts = new LinkedBlockingQueue<>(); + private final AtomicInteger queryCount = new AtomicInteger(); + private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "scripted-egress-server"); + t.setDaemon(true); + return t; + }); + volatile OnCancel onCancel; + volatile OnQuery onQuery; + + @Override + public void close() { + scheduler.shutdownNow(); + } + + @Override + public void onBinaryMessage(TestWebSocketServer.ClientHandler client, byte[] data) { + if (data.length == 0) { + return; + } + if (data[0] == QwpEgressMsgKind.CANCEL) { + OnCancel cancelScript = onCancel; + if (cancelScript != null) { + cancelScript.run(this, client, ByteBuffer.wrap(data, 1, 8).order(ByteOrder.LITTLE_ENDIAN).getLong()); + } + return; + } + if (data[0] != QwpEgressMsgKind.QUERY_REQUEST) { + return; + } + QwpEgressFrames.QueryRequest request = QwpEgressFrames.parseQueryRequest(data); + timeouts.add(request.timeoutMs); + OnQuery script = onQuery; + if (script != null) { + script.run(this, client, request.requestId, queryCount.incrementAndGet()); + } + } + + void closeConnection(TestWebSocketServer.ClientHandler client) { + try { + client.sendClose(1011, "scripted failure"); + } catch (IOException ignore) { + // the client went away; the test's assertions report the outcome + } + } + + void send(TestWebSocketServer.ClientHandler client, byte[] frame) { + try { + client.sendBinary(frame); + } catch (IOException ignore) { + // the client went away; the test's assertions report the outcome + } + } + + void sendLater(TestWebSocketServer.ClientHandler client, long delayMs, byte[] frame) { + scheduler.schedule(() -> send(client, frame), delayMs, TimeUnit.MILLISECONDS); + } + } +} diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpEgressFrames.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpEgressFrames.java index 5ad80e279..dc88738d7 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpEgressFrames.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpEgressFrames.java @@ -61,8 +61,8 @@ public static Body execDone(long requestId, int opType, long rowsAffected) { /** * Parses a {@code QUERY_REQUEST} payload. Supports the LONG binds tests - * send; the {@code query_flags} trailer and the row-window values follow - * the binds. + * send; the {@code query_flags} trailer, the timeout and the row-window + * values follow the binds. */ public static QueryRequest parseQueryRequest(byte[] payload) { Reader rd = new Reader(payload); @@ -79,9 +79,10 @@ public static QueryRequest parseQueryRequest(byte[] payload) { } boolean hasQueryFlags = rd.remaining() > 0; long queryFlags = hasQueryFlags ? rd.varint() : 0; + long timeoutMs = (queryFlags & QwpEgressMsgKind.QUERY_FLAG_TIMEOUT) != 0 ? rd.varint() : -1; long skipRows = (queryFlags & QwpEgressMsgKind.QUERY_FLAG_SKIP_ROWS) != 0 ? rd.varint() : -1; long maxRows = (queryFlags & QwpEgressMsgKind.QUERY_FLAG_MAX_ROWS) != 0 ? rd.varint() : -1; - return new QueryRequest(payload, requestId, sql, longBinds, hasQueryFlags, queryFlags, skipRows, maxRows, rd.remaining()); + return new QueryRequest(payload, requestId, sql, longBinds, hasQueryFlags, queryFlags, timeoutMs, skipRows, maxRows, rd.remaining()); } /** @@ -212,6 +213,7 @@ public static final class QueryRequest { public final long requestId; public final long skipRows; public final String sql; + public final long timeoutMs; public final int trailingBytes; QueryRequest( @@ -221,6 +223,7 @@ public static final class QueryRequest { long[] longBinds, boolean hasQueryFlags, long queryFlags, + long timeoutMs, long skipRows, long maxRows, int trailingBytes @@ -231,6 +234,7 @@ public static final class QueryRequest { this.longBinds = longBinds; this.hasQueryFlags = hasQueryFlags; this.queryFlags = queryFlags; + this.timeoutMs = timeoutMs; this.skipRows = skipRows; this.maxRows = maxRows; this.trailingBytes = trailingBytes; @@ -246,6 +250,7 @@ public String toString() { + ", sql='" + sql + '\'' + ", hasQueryFlags=" + hasQueryFlags + ", queryFlags=0x" + Long.toHexString(queryFlags) + + ", timeoutMs=" + timeoutMs + ", skipRows=" + skipRows + ", maxRows=" + maxRows + ", trailingBytes=" + trailingBytes diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpQueryClientQueryFlagsTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpQueryClientQueryFlagsTest.java index 41e7ad9ff..3d063e787 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpQueryClientQueryFlagsTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpQueryClientQueryFlagsTest.java @@ -307,6 +307,40 @@ public void testSkipRowsOnTheWire() throws Exception { Assert.assertEquals(10, r.maxRows); } + @Test + public void testTimeoutGoesAheadOfTheRowWindow() throws Exception { + TestUtils.assertMemoryLeak(() -> { + try (QwpEgressMockServer server = new QwpEgressMockServer( + ALL_CAPABILITIES | QwpEgressMsgKind.CAP_QUERY_TIMEOUT, QwpQueryClientQueryFlagsTest::execDone); + QwpQueryClient client = newClient(server)) { + client.connect(); + // The server gets the timeout as given, up to the largest one: a + // time left that the client counted down would never come back as + // Long.MAX_VALUE. + final long[] timeouts = {30_000, Long.MAX_VALUE - 1, Long.MAX_VALUE}; + RecordingQueryHandler handler = new RecordingQueryHandler(); + for (long timeoutMs : timeouts) { + client.execute(SQL, null, handler, new QwpQueryOptions().skipRows(300).maxRows(16_384), timeoutMs); + } + Assert.assertEquals("the queries must complete", timeouts.length, handler.execDoneCount); + server.assertNoFailure(); + List requests = server.getRequests(); + Assert.assertEquals(timeouts.length, requests.size()); + for (int i = 0; i < timeouts.length; i++) { + QwpEgressFrames.QueryRequest r = requests.get(i); + Assert.assertEquals(QwpEgressMsgKind.QUERY_FLAG_TIMEOUT | QwpEgressMsgKind.QUERY_FLAG_SKIP_ROWS + | QwpEgressMsgKind.QUERY_FLAG_MAX_ROWS, r.queryFlags); + // fields follow the flags in ascending order of their bits: + // timeout_ms, skip_rows, max_rows + Assert.assertEquals(timeouts[i], r.timeoutMs); + Assert.assertEquals(300, r.skipRows); + Assert.assertEquals(16_384, r.maxRows); + Assert.assertEquals(0, r.trailingBytes); + } + } + }); + } + /** * Each capability and each query flag is a bit of its own, and the query * details leave alone the per-query timeout bits that released clients diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpQueryClientQueryTimeoutTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpQueryClientQueryTimeoutTest.java new file mode 100644 index 000000000..cd462f962 --- /dev/null +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpQueryClientQueryTimeoutTest.java @@ -0,0 +1,1068 @@ +/*+***************************************************************************** + * ___ _ ____ ____ + * / _ \ _ _ ___ ___| |_| _ \| __ ) + * | | | | | | |/ _ \/ __| __| | | | _ \ + * | |_| | |_| | __/\__ \ |_| |_| | |_) | + * \__\_\\__,_|\___||___/\__|____/|____/ + * + * Copyright (c) 2014-2019 Appsicle + * Copyright (c) 2019-2026 QuestDB + * + * Licensed 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 io.questdb.client.test.cutlass.qwp.client; + +import io.questdb.client.ConnectionHealth; +import io.questdb.client.cutlass.qwp.client.QwpColumnBatch; +import io.questdb.client.cutlass.qwp.client.QwpColumnBatchHandler; +import io.questdb.client.cutlass.qwp.client.QwpEgressMsgKind; +import io.questdb.client.cutlass.qwp.client.QwpQueryClient; +import io.questdb.client.cutlass.qwp.client.QwpServerInfo; +import io.questdb.client.cutlass.qwp.client.WebSocketResponse; +import io.questdb.client.cutlass.qwp.protocol.QwpConstants; +import io.questdb.client.test.cutlass.qwp.websocket.TestWebSocketServer; +import io.questdb.client.test.tools.TestUtils; +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.LockSupport; + +/** + * Per-query timeout of {@link QwpQueryClient}, against a scripted mock server. + * Pins the wire contract (the capability-gated {@code timeout_ms} field after + * {@code query_flags}) and the central promise of the feature: the timeout only + * overrides the server's default. The client keeps no deadline of its own, never + * cancels or drops a connection because a query is slow, and the server's + * {@link QwpConstants#STATUS_QUERY_TIMEOUT} ends the query on a connection that + * stays open for the next query. A query its caller abandons -- the handler + * throws, or the thread is interrupted -- before the query ends never leaks its + * leftovers into the next query. + *

    + * The server-side enforcement (breaker timeout, status mapping) is covered + * against a live server in the questdb repository. + */ +public class QwpQueryClientQueryTimeoutTest { + + private static final int CAPS_FLAGS_ONLY = QwpEgressMsgKind.CAP_QUERY_FLAGS; + private static final int CAPS_WITH_TIMEOUT = QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT; + + @Test(timeout = 30_000) + public void testBatchesSentPastTheTimeoutReachTheHandler() throws Exception { + TestUtils.assertMemoryLeak(() -> { + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> { + long id = requestIdOf(frame); + if (n == 1) { + send(c, QwpEgressFrames.resultBatchOfLongs(id, 0, 1)); + s.sendLater(c, 400, + QwpEgressFrames.resultBatchOfLongs(id, 1, 2), + QwpEgressFrames.resultBatchOfLongs(id, 2, 3), + QwpEgressFrames.queryError(id, QwpConstants.STATUS_QUERY_TIMEOUT, + "timeout, query aborted").toFrame()); + } else { + send(c, QwpEgressFrames.resultBatchOfLongs(id, 0, 1)); + send(c, QwpEgressFrames.resultEnd(id, 0, 1).toFrame()); + } + }; + try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, "")) { + RecordingHandler h = new RecordingHandler(); + client.execute("SELECT s FROM t", null, h, false, 150); + Assert.assertEquals("the client withholds no batch the server sends, however late", + 3, h.batches.get()); + h.assertTimedOut(); + Assert.assertEquals("timeout, query aborted", h.errorMessage); + Assert.assertTrue("the client must leave the timeout to the server", script.cancels.isEmpty()); + + RecordingHandler next = new RecordingHandler(); + client.execute("SELECT s FROM t", null, next, false, 0); + Assert.assertTrue("the next query must complete on the same connection", next.ended); + Assert.assertEquals(1, next.batches.get()); + Assert.assertEquals("the connection must be reused, not replaced", 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testCancelOfAQueryQueuedBehindLeftoversIsNotLost() throws Exception { + TestUtils.assertMemoryLeak(() -> { + final Set received = ConcurrentHashMap.newKeySet(); + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> { + long id = requestIdOf(frame); + if (n == 1) { + send(c, QwpEgressFrames.resultBatchOfLongs(id, 0, 1)); + // The rest arrives after the handler has thrown. + s.sendLater(c, 300, + QwpEgressFrames.resultBatchOfLongs(id, 1, 2), + QwpEgressFrames.resultEnd(id, 1, 2).toFrame()); + } else { + // Held: only a CANCEL ends it. + received.add(id); + } + }; + // Like a real server, ignores a cancel of a query it has not received. + script.onCancel = (s, c, frame, n) -> { + long id = requestIdOf(frame); + if (received.contains(id)) { + s.replyOnce(c, id, 0, QwpEgressFrames.queryError(id, QwpConstants.STATUS_CANCELLED, + "cancelled by client").toFrame()); + } + }; + try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, "")) { + try { + client.execute("SELECT s FROM t", null, failingOnBatch(new IllegalStateException("handler failed")), false, 0); + Assert.fail("the handler's exception must propagate out of execute()"); + } catch (IllegalStateException expected) { + // the first query is abandoned, its rest still on the way + } + + // Cancelled before it is sent: the I/O thread still works through the + // abandoned query, and must send the CANCEL only after this query. + RecordingHandler next = new RecordingHandler(); + client.execute("SELECT s FROM t", binds -> client.cancel(), next, false, 2_000); + Assert.assertEquals("the cancel must reach the server after its query, got message=" + next.errorMessage, + QwpConstants.STATUS_CANCELLED, next.errorStatus); + Assert.assertEquals("the abandoned query's rows must not reach the next query", 0, next.batches.get()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testCancelledLeftoverDoesNotAnswerTheNextQuery() throws Exception { + TestUtils.assertMemoryLeak(() -> { + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> { + long id = requestIdOf(frame); + if (n == 1) { + // Streams one batch; only a CANCEL ends it. + send(c, QwpEgressFrames.resultBatchOfLongs(id, 0, 1)); + } else { + send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame()); + } + }; + // Like a real server, answers the CANCEL of the abandoned query with STATUS_CANCELLED. + script.onCancel = (s, c, frame, n) -> { + long id = requestIdOf(frame); + s.replyOnce(c, id, 0, QwpEgressFrames.queryError(id, QwpConstants.STATUS_CANCELLED, + "cancelled by client").toFrame()); + }; + try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, "")) { + final IllegalStateException failure = new IllegalStateException("handler failed"); + try { + client.execute("SELECT s FROM t", null, failingOnBatch(failure), false, 0); + Assert.fail("the handler's exception must propagate out of execute()"); + } catch (IllegalStateException e) { + Assert.assertSame(failure, e); + } + long firstId = script.takeQuery().requestId; + byte[] cancel = script.cancels.poll(5, TimeUnit.SECONDS); + Assert.assertNotNull("the abandoned query must be cancelled", cancel); + Assert.assertEquals(firstId, requestIdOf(cancel)); + + RecordingHandler next = new RecordingHandler(); + client.execute("INSERT INTO t VALUES (1)", null, next, false, 0); + Assert.assertTrue("the next statement must get its own reply, got status=" + next.errorStatus + + ", message=" + next.errorMessage, next.execDone); + Assert.assertEquals("the abandoned query's error must not reach the next statement", 1, next.terminals.get()); + Assert.assertEquals("the connection must be reused, not replaced", 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testClientWaitsForTheServerPastTheTimeout() throws Exception { + // The timeout only overrides the server's default: the client has no + // deadline of its own, so a server that ends the query long after the + // timeout leaves a healthy connection, with failover on or off. + for (String config : new String[]{"", "failover=off;"}) { + TestUtils.assertMemoryLeak(() -> { + final long timeoutMs = 100; + final long replyDelayMs = 1_500; + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> { + long id = requestIdOf(frame); + if (n == 1) { + s.sendLater(c, replyDelayMs, QwpEgressFrames.queryError(id, QwpConstants.STATUS_QUERY_TIMEOUT, + "timeout, query aborted").toFrame()); + } else { + send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame()); + } + }; + try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, config)) { + RecordingHandler h = new RecordingHandler(); + long start = System.nanoTime(); + client.execute("SELECT slow()", null, h, false, timeoutMs); + long elapsed = elapsedMs(start); + + h.assertTimedOut(); + Assert.assertEquals("config=" + config + ": the server's own report must reach the handler", + "timeout, query aborted", h.errorMessage); + Assert.assertEquals("one terminal callback per query", 1, h.terminals.get()); + Assert.assertTrue("config=" + config + ": execute() must wait for the server, returned after " + + elapsed + "ms", elapsed >= replyDelayMs); + Assert.assertTrue("the client must leave the timeout to the server", script.cancels.isEmpty()); + Assert.assertFalse("config=" + config + ": a slow query must not fail the connection", + client.hasTerminalFailure()); + Assert.assertEquals(ConnectionHealth.State.CONNECTED, client.health().getState()); + + RecordingHandler next = new RecordingHandler(); + client.execute("INSERT INTO t VALUES (1)", null, next, false, 0); + Assert.assertTrue("config=" + config + ": the next statement must get its own reply, got status=" + + next.errorStatus + ", message=" + next.errorMessage, next.execDone); + Assert.assertEquals(0, next.failoverResets.get()); + Assert.assertEquals("the connection must be reused, not replaced", 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + } + + @Test(timeout = 30_000) + public void testCompleteResultPastTheTimeoutIsASuccess() throws Exception { + TestUtils.assertMemoryLeak(() -> { + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> { + long id = requestIdOf(frame); + // A server cannot stop every statement: some run to completion and + // answer long after the timeout. + s.sendLater(c, 1_200, n == 1 + ? QwpEgressFrames.resultEnd(id, 0, 0).toFrame() + : QwpEgressFrames.execDone(id, 0, 0).toFrame()); + }; + try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, "")) { + RecordingHandler select = new RecordingHandler(); + client.execute("SELECT 1 WHERE false", null, select, false, 100); + Assert.assertTrue("a complete result past the timeout is a success", select.ended); + Assert.assertEquals(0, select.errorStatus); + + RecordingHandler insert = new RecordingHandler(); + client.execute("INSERT INTO t SELECT slow()", null, insert, false, 100); + Assert.assertTrue("a statement that completed past the timeout took effect and must say so", + insert.execDone); + Assert.assertEquals(0, insert.errorStatus); + Assert.assertTrue(script.cancels.isEmpty()); + Assert.assertEquals("the connection must be reused, not replaced", 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testFailoverReplayCarriesTheSameTimeout() throws Exception { + TestUtils.assertMemoryLeak(() -> { + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> { + if (n == 1) { + // A transport failure mid-query: the client fails over and replays. + s.closeLater(c, 200); + } else { + send(c, QwpEgressFrames.execDone(requestIdOf(frame), 0, 0).toFrame()); + } + }; + try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, + "failover_backoff_initial_ms=0;failover_backoff_max_ms=0;")) { + RecordingHandler h = new RecordingHandler(); + client.execute("INSERT INTO t VALUES (1)", null, h, false, 10_000); + Assert.assertTrue("the replay must complete", h.execDone); + Assert.assertEquals(1, h.failoverResets.get()); + + Assert.assertEquals(10_000, script.takeQuery().timeoutMs); + Assert.assertEquals("the replay overrides the server default with the same timeout", + 10_000, script.takeQuery().timeoutMs); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testInterruptReleasesTheCallerOnlyOnceItsRequestIsEncoded() throws Exception { + TestUtils.assertMemoryLeak(() -> { + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> send(c, QwpEgressFrames.execDone(requestIdOf(frame), 0, 0).toFrame()); + try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, "")) { + // The I/O thread picks the request up, and stops inside its SQL text. + CountDownLatch reading = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CharSequence sql = new BlockingSql("INSERT INTO t VALUES (1)", reading, release); + RecordingHandler interrupted = new RecordingHandler(); + Thread caller = new Thread(() -> client.execute(sql, null, interrupted, false, 0)); + caller.start(); + try { + Assert.assertTrue("the I/O thread must start encoding the request", reading.await(5, TimeUnit.SECONDS)); + caller.interrupt(); + // The caller may change the SQL text once released, and the next + // query reuses the bind buffer: not before the I/O thread is done. + caller.join(300); + Assert.assertTrue("execute() must wait for the I/O thread to finish reading the request", + caller.isAlive()); + } finally { + release.countDown(); + } + caller.join(5_000); + Assert.assertFalse("execute() must return once the request is encoded", caller.isAlive()); + Assert.assertEquals(WebSocketResponse.STATUS_INTERNAL_ERROR, interrupted.errorStatus); + + RecordingHandler next = new RecordingHandler(); + client.execute("INSERT INTO t VALUES (2)", null, next, false, 0); + Assert.assertTrue("the next statement must get its own reply", next.execDone); + Assert.assertEquals("the connection must be reused, not replaced", 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testInterruptWithAStuckIoThreadGivesUpTheConnection() throws Exception { + TestUtils.assertMemoryLeak(() -> { + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> send(c, QwpEgressFrames.execDone(requestIdOf(frame), 0, 0).toFrame()); + try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, "")) { + final long shutdownJoinMs = 300; + setShutdownJoinMs(client, shutdownJoinMs); + // The I/O thread picks the request up, and stays inside its SQL text + // until it is interrupted: stuck. + CountDownLatch reading = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CharSequence sql = new BlockingSql("INSERT INTO t VALUES (1)", reading, release); + RecordingHandler interrupted = new RecordingHandler(); + Thread caller = new Thread(() -> client.execute(sql, null, interrupted, false, 0)); + caller.start(); + long elapsed; + try { + Assert.assertTrue("the I/O thread must start encoding the request", reading.await(5, TimeUnit.SECONDS)); + long start = System.nanoTime(); + caller.interrupt(); + caller.join(10_000); + elapsed = elapsedMs(start); + } finally { + release.countDown(); + } + Assert.assertFalse("execute() must return", caller.isAlive()); + Assert.assertEquals(WebSocketResponse.STATUS_INTERNAL_ERROR, interrupted.errorStatus); + Assert.assertTrue("execute() must first wait for the I/O thread, returned after " + elapsed + "ms", + elapsed >= shutdownJoinMs); + Assert.assertTrue("a connection whose I/O thread is stuck must be given up", client.hasTerminalFailure()); + + // failover=on (the default) replaces the connection for the next query. + RecordingHandler next = new RecordingHandler(); + client.execute("INSERT INTO t VALUES (2)", null, next, false, 0); + Assert.assertTrue("the next statement must get its own reply", next.execDone); + Assert.assertEquals("a replacement connection must have been opened", 2, server.handshakeCount()); + Assert.assertEquals(ConnectionHealth.State.CONNECTED, client.health().getState()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testInterruptedQueryDoesNotAnswerTheNextQuery() throws Exception { + TestUtils.assertMemoryLeak(() -> { + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> { + long id = requestIdOf(frame); + if (n == 1) { + // Answers only after its caller has stopped waiting. + s.sendLater(c, 500, + QwpEgressFrames.resultBatchOfLongs(id, 0, 1), + QwpEgressFrames.resultEnd(id, 0, 1).toFrame()); + } else { + send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame()); + } + }; + try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, "")) { + RecordingHandler first = new RecordingHandler(); + Thread caller = new Thread(() -> client.execute("SELECT s FROM t", null, first, false, 0)); + caller.start(); + long firstId = script.takeQuery().requestId; + caller.interrupt(); + caller.join(5_000); + Assert.assertFalse("execute() must return when its thread is interrupted", caller.isAlive()); + Assert.assertEquals(WebSocketResponse.STATUS_INTERNAL_ERROR, first.errorStatus); + byte[] cancel = script.cancels.poll(5, TimeUnit.SECONDS); + Assert.assertNotNull("the abandoned query must be cancelled", cancel); + Assert.assertEquals(firstId, requestIdOf(cancel)); + + RecordingHandler next = new RecordingHandler(); + client.execute("INSERT INTO t VALUES (1)", null, next, false, 0); + Assert.assertTrue("the next statement must get its own reply, got status=" + next.errorStatus + + ", message=" + next.errorMessage, next.execDone); + Assert.assertEquals("the abandoned query's rows must not reach the next statement", 0, next.batches.get()); + Assert.assertEquals("the connection must be reused, not replaced", 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testInterruptedQueryNotYetSentIsWithdrawn() throws Exception { + TestUtils.assertMemoryLeak(() -> { + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> { + long id = requestIdOf(frame); + if (n == 1) { + send(c, QwpEgressFrames.resultBatchOfLongs(id, 0, 1)); + // The rest arrives late; until then the I/O thread does not pick up + // the next request. + s.sendLater(c, 500, + QwpEgressFrames.resultBatchOfLongs(id, 1, 2), + QwpEgressFrames.resultEnd(id, 1, 2).toFrame()); + } else { + send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame()); + } + }; + try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, "")) { + try { + client.execute("SELECT s FROM t", null, failingOnBatch(new IllegalStateException("handler failed")), false, 0); + Assert.fail("the handler's exception must propagate out of execute()"); + } catch (IllegalStateException expected) { + // the first query is abandoned, its rest still on the way + } + + // Queued behind the abandoned query's leftovers, and interrupted there. + RecordingHandler interrupted = new RecordingHandler(); + Thread caller = new Thread(() -> client.execute("INSERT INTO t VALUES (2)", null, interrupted, false, 0)); + caller.start(); + awaitParked(caller); + caller.interrupt(); + caller.join(5_000); + Assert.assertFalse("execute() must return when its thread is interrupted", caller.isAlive()); + Assert.assertEquals(WebSocketResponse.STATUS_INTERNAL_ERROR, interrupted.errorStatus); + + RecordingHandler next = new RecordingHandler(); + client.execute("INSERT INTO t VALUES (3)", null, next, false, 0); + Assert.assertTrue("the next statement must get its own reply", next.execDone); + RecordingHandler last = new RecordingHandler(); + client.execute("INSERT INTO t VALUES (4)", null, last, false, 0); + Assert.assertTrue("the last statement must get its own reply", last.execDone); + + // The interrupted statement, withdrawn before it was sent, never reaches + // the server; every other statement reaches it exactly once. + List received = new ArrayList<>(); + for (byte[] frame : script.queries) { + received.add(QwpEgressFrames.parseQueryRequest(frame).sql); + } + Assert.assertEquals(Arrays.asList("SELECT s FROM t", "INSERT INTO t VALUES (3)", "INSERT INTO t VALUES (4)"), + received); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testInterruptedStatementDoesNotAnswerTheNextStatement() throws Exception { + TestUtils.assertMemoryLeak(() -> { + ScriptedServer script = new ScriptedServer(); + // Each statement reports a row count of its own, so a reply that answers + // the wrong statement shows. + script.onQuery = (s, c, frame, n) -> { + long id = requestIdOf(frame); + if (n == 1) { + // Answers only after its caller has stopped waiting. + s.sendLater(c, 500, QwpEgressFrames.execDone(id, 0, 7).toFrame()); + } else { + send(c, QwpEgressFrames.execDone(id, 0, n).toFrame()); + } + }; + try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, "")) { + RecordingHandler first = new RecordingHandler(); + Thread caller = new Thread(() -> client.execute("INSERT INTO t VALUES (1)", null, first, false, 0)); + caller.start(); + script.takeQuery(); + caller.interrupt(); + caller.join(5_000); + Assert.assertFalse("execute() must return when its thread is interrupted", caller.isAlive()); + Assert.assertEquals(WebSocketResponse.STATUS_INTERNAL_ERROR, first.errorStatus); + Assert.assertFalse("the interrupted statement must not complete", first.execDone); + + RecordingHandler second = new RecordingHandler(); + client.execute("INSERT INTO t VALUES (2)", null, second, false, 0); + Assert.assertTrue("the next statement must complete, got status=" + second.errorStatus + + ", message=" + second.errorMessage, second.execDone); + Assert.assertEquals("the interrupted statement's reply must not answer the next statement", + 2, second.rowsAffected); + Assert.assertEquals(1, second.terminals.get()); + + RecordingHandler third = new RecordingHandler(); + client.execute("INSERT INTO t VALUES (3)", null, third, false, 0); + Assert.assertTrue(third.execDone); + Assert.assertEquals("each statement must get its own reply", 3, third.rowsAffected); + Assert.assertEquals(1, third.terminals.get()); + Assert.assertEquals("the connection must be reused, not replaced", 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testNoTimeoutFieldWithoutTheCapabilityOrTimeout() throws Exception { + TestUtils.assertMemoryLeak(() -> { + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> send(c, QwpEgressFrames.execDone(requestIdOf(frame), 0, 0).toFrame()); + try (TestWebSocketServer server = startServer(script, CAPS_FLAGS_ONLY); + QwpQueryClient client = connect(server, "")) { + client.execute("SELECT 1", null, new RecordingHandler(), false, 30_000); + Assert.assertFalse("a server without CAP_QUERY_TIMEOUT must get no timeout field", + script.takeQuery().hasQueryFlags); + } finally { + script.close(); + } + + ScriptedServer script2 = new ScriptedServer(); + script2.onQuery = (s, c, frame, n) -> send(c, QwpEgressFrames.execDone(requestIdOf(frame), 0, 0).toFrame()); + try (TestWebSocketServer server = startServer(script2, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, "")) { + client.execute("SELECT 1", null, new RecordingHandler(), false, 0); + Assert.assertFalse("a query without a timeout must send no timeout field", + script2.takeQuery().hasQueryFlags); + } finally { + script2.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testOlderServerGetsNoTimeoutAndNoCancel() throws Exception { + TestUtils.assertMemoryLeak(() -> { + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> + s.sendLater(c, 500, QwpEgressFrames.execDone(requestIdOf(frame), 0, 0).toFrame()); + try (TestWebSocketServer server = startServer(script, CAPS_FLAGS_ONLY); + QwpQueryClient client = connect(server, "")) { + RecordingHandler h = new RecordingHandler(); + client.execute("INSERT INTO t SELECT slow()", null, h, false, 100); + + // A server without CAP_QUERY_TIMEOUT applies its own default; the + // client does not stand in for it. + Assert.assertTrue("got status=" + h.errorStatus + ", message=" + h.errorMessage, h.execDone); + Assert.assertFalse("the timeout must not go on the wire", script.takeQuery().hasQueryFlags); + Assert.assertTrue("the client must not cancel in the server's place", script.cancels.isEmpty()); + Assert.assertFalse(client.hasTerminalFailure()); + Assert.assertEquals(1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testServerReportedTimeoutKeepsTheConnectionOpen() throws Exception { + TestUtils.assertMemoryLeak(() -> { + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> { + long id = requestIdOf(frame); + if (n == 1) { + s.sendLater(c, 150, QwpEgressFrames.queryError(id, QwpConstants.STATUS_QUERY_TIMEOUT, + "timeout, query aborted [runtime=150ms, timeout=100ms]").toFrame()); + } else { + send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame()); + } + }; + try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, "")) { + RecordingHandler h = new RecordingHandler(); + client.execute("SELECT slow()", null, h, false, 100); + + h.assertTimedOut(); + Assert.assertTrue("the server's own report must reach the handler: " + h.errorMessage, + h.errorMessage.startsWith("timeout, query aborted")); + Assert.assertTrue("the client must leave a server-enforced timeout to the server", + script.cancels.isEmpty()); + Assert.assertFalse(client.hasTerminalFailure()); + + RecordingHandler next = new RecordingHandler(); + client.execute("INSERT INTO t VALUES (1)", null, next, false, 0); + Assert.assertTrue(next.execDone); + Assert.assertEquals("the authenticated connection must be reused", 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testSlowHandlerPastTheTimeoutGetsTheWholeResult() throws Exception { + TestUtils.assertMemoryLeak(() -> { + final long timeoutMs = 100; + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> { + long id = requestIdOf(frame); + if (n == 1) { + send(c, QwpEgressFrames.resultBatchOfLongs(id, 0, 1)); + send(c, QwpEgressFrames.resultBatchOfLongs(id, 1, 2)); + send(c, QwpEgressFrames.resultEnd(id, 1, 2).toFrame()); + } else { + send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame()); + } + }; + try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, "")) { + // The handler holds its first batch far past the timeout. + RecordingHandler h = new RecordingHandler(1_200); + client.execute("SELECT s FROM t", null, h, false, timeoutMs); + + Assert.assertTrue("got status=" + h.errorStatus + ", message=" + h.errorMessage, h.ended); + Assert.assertEquals("every batch the server sent must reach the handler", 2, h.batches.get()); + Assert.assertEquals(1, h.terminals.get()); + Assert.assertTrue(script.cancels.isEmpty()); + Assert.assertFalse(client.hasTerminalFailure()); + + RecordingHandler next = new RecordingHandler(); + client.execute("INSERT INTO t VALUES (1)", null, next, false, 0); + Assert.assertTrue(next.execDone); + Assert.assertEquals("the connection must be reused, not replaced", 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testThrowingBatchHandlerDoesNotLeakRowsIntoTheNextQuery() throws Exception { + TestUtils.assertMemoryLeak(() -> { + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> { + long id = requestIdOf(frame); + if (n == 1) { + send(c, QwpEgressFrames.resultBatchOfLongs(id, 0, 1)); + // The rest of the result arrives after the handler has thrown. + s.sendLater(c, 300, + QwpEgressFrames.resultBatchOfLongs(id, 1, 2), + QwpEgressFrames.resultEnd(id, 1, 2).toFrame()); + } else { + send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame()); + } + }; + try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, "")) { + final IllegalStateException failure = new IllegalStateException("handler failed"); + try { + client.execute("SELECT s FROM t", null, failingOnBatch(failure), false, 0); + Assert.fail("the handler's exception must propagate out of execute()"); + } catch (IllegalStateException e) { + Assert.assertSame(failure, e); + } + long firstId = script.takeQuery().requestId; + byte[] cancel = script.cancels.poll(5, TimeUnit.SECONDS); + Assert.assertNotNull("the abandoned query must be cancelled", cancel); + Assert.assertEquals(firstId, requestIdOf(cancel)); + + RecordingHandler next = new RecordingHandler(); + client.execute("INSERT INTO t VALUES (1)", null, next, false, 0); + Assert.assertEquals("the abandoned query's rows must not reach the next statement", 0, next.batches.get()); + Assert.assertTrue("the next statement must get its own reply, got status=" + next.errorStatus + + ", message=" + next.errorMessage, next.execDone); + Assert.assertFalse(next.ended); + Assert.assertEquals("the connection must be reused, not replaced", 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testTimeoutFieldCarriesTheTimeout() throws Exception { + TestUtils.assertMemoryLeak(() -> { + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> send(c, QwpEgressFrames.execDone(requestIdOf(frame), 0, 0).toFrame()); + try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, "query_timeout_ms=20000;")) { + Assert.assertEquals(20_000, client.getQueryTimeoutMs()); + + // A bind setter that takes a while: the timeout is not a budget the + // client spends, so the server gets the value as given. + client.execute("SELECT 1", binds -> LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(50)), + new RecordingHandler(), false, 30_000); + QwpEgressFrames.QueryRequest request = script.takeQuery(); + Assert.assertEquals(QwpEgressMsgKind.QUERY_FLAG_TIMEOUT, request.queryFlags); + Assert.assertEquals(30_000, request.timeoutMs); + + // The overloads without a timeout apply the configured default, and + // the field composes with the other query flags. + client.execute("SELECT 1", new RecordingHandler(), true); + request = script.takeQuery(); + Assert.assertEquals(QwpEgressMsgKind.QUERY_FLAG_RESET_DICT | QwpEgressMsgKind.QUERY_FLAG_TIMEOUT, + request.queryFlags); + Assert.assertEquals("the configured default must apply", 20_000, request.timeoutMs); + } finally { + script.close(); + } + }); + } + + @Test(timeout = 30_000) + public void testUserCancelIsReportedAsCancel() throws Exception { + TestUtils.assertMemoryLeak(() -> { + ScriptedServer script = new ScriptedServer(); + script.onQuery = (s, c, frame, n) -> { + long id = requestIdOf(frame); + if (n == 1) { + // Streams one batch; only a CANCEL ends it. + send(c, QwpEgressFrames.resultBatchOfLongs(id, 0, 1)); + } else { + send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame()); + } + }; + // Like a real server, answers a CANCEL of a streaming query with STATUS_CANCELLED. + script.onCancel = (s, c, frame, n) -> s.replyOnce(c, requestIdOf(frame), 0, + QwpEgressFrames.queryError(requestIdOf(frame), QwpConstants.STATUS_CANCELLED, + "cancelled by client").toFrame()); + try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT); + QwpQueryClient client = connect(server, "")) { + RecordingHandler h = new RecordingHandler(); + Thread canceller = new Thread(() -> { + try { + script.queries.take(); + client.cancel(); + } catch (InterruptedException ignore) { + Thread.currentThread().interrupt(); + } + }); + canceller.start(); + client.execute("SELECT slow()", null, h, false, 0); + canceller.join(); + + Assert.assertEquals("the batch sent before the cancel must reach the handler", 1, h.batches.get()); + Assert.assertEquals("the user's cancel must be reported as such: " + h.errorMessage, + QwpConstants.STATUS_CANCELLED, h.errorStatus); + Assert.assertEquals("cancelled by client", h.errorMessage); + Assert.assertEquals("one terminal callback per query", 1, h.terminals.get()); + + RecordingHandler next = new RecordingHandler(); + client.execute("INSERT INTO t VALUES (1)", null, next, false, 0); + Assert.assertTrue("the next statement must get its own reply", next.execDone); + Assert.assertEquals("the connection must be reused, not replaced", 1, server.handshakeCount()); + } finally { + script.close(); + } + }); + } + + /** + * Waits until {@code thread} blocks, here: parked waiting for its query's + * events, with the request queued. + */ + private static void awaitParked(Thread thread) throws InterruptedException { + final long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (thread.getState() != Thread.State.WAITING && thread.getState() != Thread.State.TIMED_WAITING) { + Assert.assertTrue("the thread must block", System.nanoTime() - deadlineNanos < 0); + Thread.sleep(1); + } + } + + private static byte[] closeFrame() { + // Marker understood by ScriptedServer's send(): close the connection. + return new byte[0]; + } + + private static QwpQueryClient connect(TestWebSocketServer server, String extraConfig) { + QwpQueryClient client = QwpQueryClient.fromConfig( + "ws::addr=localhost:" + server.getPort() + ";auth_timeout_ms=2000;" + extraConfig); + try { + client.connect(); + } catch (RuntimeException e) { + client.close(); + throw e; + } + return client; + } + + private static long elapsedMs(long startNanos) { + return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); + } + + private static QwpColumnBatchHandler failingOnBatch(RuntimeException failure) { + return new QwpColumnBatchHandler() { + @Override + public void onBatch(QwpColumnBatch batch) { + throw failure; + } + + @Override + public void onEnd(long totalRows) { + } + + @Override + public void onError(byte status, String message) { + } + }; + } + + private static long requestIdOf(byte[] clientFrame) { + return ByteBuffer.wrap(clientFrame, 1, 8).order(ByteOrder.LITTLE_ENDIAN).getLong(); + } + + private static void send(TestWebSocketServer.ClientHandler client, byte[] frame) { + try { + if (frame.length == 0) { + client.sendClose(1011, "scripted failure"); + } else { + client.sendBinary(frame); + } + } catch (IOException ignore) { + // the client went away; the test's assertions report the outcome + } + } + + private static void setShutdownJoinMs(QwpQueryClient client, long millis) throws Exception { + Field field = QwpQueryClient.class.getDeclaredField("shutdownJoinMs"); + field.setAccessible(true); + field.setLong(client, millis); + } + + private static TestWebSocketServer startServer(ScriptedServer script, int capabilities) throws Exception { + TestWebSocketServer server = new TestWebSocketServer(script); + server.setSendServerInfo(true); + server.setCapabilities(capabilities); + server.start(); + Assert.assertTrue(server.awaitStart(5, TimeUnit.SECONDS)); + return server; + } + + @FunctionalInterface + private interface Script { + void run(ScriptedServer server, TestWebSocketServer.ClientHandler client, byte[] frame, int queryNumber); + } + + /** + * SQL text that holds up whoever reads its first character -- the I/O + * thread, which reads it while encoding the request -- until released or + * interrupted. + */ + private static final class BlockingSql implements CharSequence { + private final CountDownLatch reading; + private final CountDownLatch release; + private final String text; + + BlockingSql(String text, CountDownLatch reading, CountDownLatch release) { + this.text = text; + this.reading = reading; + this.release = release; + } + + @Override + public char charAt(int index) { + if (index == 0) { + reading.countDown(); + try { + release.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + return text.charAt(index); + } + + @Override + public int length() { + return text.length(); + } + + @Override + public CharSequence subSequence(int start, int end) { + return text.subSequence(start, end); + } + + @Override + public String toString() { + return text; + } + } + + private static final class RecordingHandler implements QwpColumnBatchHandler { + final AtomicInteger batches = new AtomicInteger(); + final AtomicInteger failoverResets = new AtomicInteger(); + final AtomicInteger terminals = new AtomicInteger(); + volatile boolean ended; + volatile String errorMessage; + volatile byte errorStatus; + volatile boolean execDone; + volatile long rowsAffected = -1; + private final long firstBatchHoldNanos; + + RecordingHandler() { + this(0); + } + + /** + * A handler that falls behind: its first {@code onBatch} holds the + * caller's thread for {@code firstBatchHoldMs}. + */ + RecordingHandler(long firstBatchHoldMs) { + this.firstBatchHoldNanos = TimeUnit.MILLISECONDS.toNanos(firstBatchHoldMs); + } + + @Override + public void onBatch(QwpColumnBatch batch) { + if (batches.incrementAndGet() == 1 && firstBatchHoldNanos > 0) { + final long holdEndNanos = System.nanoTime() + firstBatchHoldNanos; + long left; + while ((left = holdEndNanos - System.nanoTime()) > 0) { + LockSupport.parkNanos(left); + } + } + } + + @Override + public void onEnd(long totalRows) { + ended = true; + terminal(); + } + + @Override + public void onError(byte status, String message) { + errorStatus = status; + errorMessage = message; + terminal(); + } + + @Override + public void onExecDone(short opType, long rowsAffected) { + this.rowsAffected = rowsAffected; + execDone = true; + terminal(); + } + + @Override + public void onFailoverReset(QwpServerInfo newNode) { + failoverResets.incrementAndGet(); + } + + void assertTimedOut() { + Assert.assertEquals("expected a query timeout, got status=" + errorStatus + ", message=" + errorMessage, + QwpConstants.STATUS_QUERY_TIMEOUT, errorStatus); + Assert.assertFalse("a timed-out query must not also complete", ended || execDone); + } + + private void terminal() { + terminals.incrementAndGet(); + } + } + + /** + * Mock egress server scripted per test. Records every {@code QUERY_REQUEST} + * and {@code CANCEL}, and replies like a real server: one terminal frame per + * request, so a cancel of a query that already ended gets no reply. + */ + private static final class ScriptedServer implements TestWebSocketServer.WebSocketServerHandler, AutoCloseable { + final LinkedBlockingQueue cancels = new LinkedBlockingQueue<>(); + final LinkedBlockingQueue queries = new LinkedBlockingQueue<>(); + final AtomicInteger queryCount = new AtomicInteger(); + private final Set answered = ConcurrentHashMap.newKeySet(); + private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "scripted-egress-server"); + t.setDaemon(true); + return t; + }); + volatile Script onCancel; + volatile Script onQuery; + + @Override + public void close() { + scheduler.shutdownNow(); + } + + @Override + public void onBinaryMessage(TestWebSocketServer.ClientHandler client, byte[] data) { + if (data.length == 0) { + return; + } + if (data[0] == QwpEgressMsgKind.QUERY_REQUEST) { + int n = queryCount.incrementAndGet(); + queries.add(data); + Script script = onQuery; + if (script != null) { + script.run(this, client, data, n); + } + } else if (data[0] == QwpEgressMsgKind.CANCEL) { + cancels.add(data); + Script script = onCancel; + if (script != null) { + script.run(this, client, data, 0); + } + } + } + + void closeLater(TestWebSocketServer.ClientHandler client, long delayMs) { + sendLater(client, delayMs, closeFrame()); + } + + // Sends the terminal frame for requestId unless one was already sent. + void replyOnce(TestWebSocketServer.ClientHandler client, long requestId, long delayMs, byte[] frame) { + if (answered.add(requestId)) { + sendLater(client, delayMs, frame); + } + } + + void sendLater(TestWebSocketServer.ClientHandler client, long delayMs, byte[]... frames) { + scheduler.schedule(() -> { + for (byte[] frame : frames) { + send(client, frame); + } + }, delayMs, TimeUnit.MILLISECONDS); + } + + /** + * Takes the next recorded {@code QUERY_REQUEST} and decodes it on the + * calling thread, so a malformed request fails the test, not the + * server's read thread. + */ + QwpEgressFrames.QueryRequest takeQuery() throws InterruptedException { + QwpEgressFrames.QueryRequest request = QwpEgressFrames.parseQueryRequest(queries.take()); + Assert.assertEquals("the trailer must end the frame", 0, request.trailingBytes); + return request; + } + } +} diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpSpscQueueTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpSpscQueueTest.java index 50a930b19..9bbab56d5 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpSpscQueueTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpSpscQueueTest.java @@ -209,6 +209,75 @@ public void testNoUnparkWhenConsumerNotParked() { Assert.assertNull(q.poll()); } + @Test + public void testTimedTakeReturnsNullAtTheDeadline() throws InterruptedException { + QwpSpscQueue q = new QwpSpscQueue<>(4); + long start = System.nanoTime(); + Assert.assertNull("an empty queue must yield null once the deadline passes", + q.take(start + TimeUnit.MILLISECONDS.toNanos(100))); + long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); + Assert.assertTrue("timed take must wait until the deadline, waited " + elapsedMs + " ms", elapsedMs >= 100); + // The queue stays fully usable afterwards. + Assert.assertTrue(q.offer("after")); + Assert.assertEquals("after", q.take(System.nanoTime() + TimeUnit.SECONDS.toNanos(5))); + } + + @Test + public void testTimedTakeWithPastDeadlineStillReturnsAvailableValue() throws InterruptedException { + QwpSpscQueue q = new QwpSpscQueue<>(4); + long past = System.nanoTime() - TimeUnit.SECONDS.toNanos(1); + Assert.assertNull("a past deadline on an empty queue must not block", q.take(past)); + Assert.assertTrue(q.offer("ready")); + Assert.assertEquals("a value already available is returned even past the deadline", "ready", q.take(past)); + } + + @Test + public void testTimedTakeWakesOnOfferBeforeTheDeadline() throws Exception { + QwpSpscQueue q = new QwpSpscQueue<>(4); + AtomicReference taken = new AtomicReference<>(); + CountDownLatch done = new CountDownLatch(1); + Thread consumer = new Thread(() -> { + try { + taken.set(q.take(System.nanoTime() + TimeUnit.SECONDS.toNanos(30))); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + done.countDown(); + } + }, "spsc-timed-consumer"); + consumer.start(); + // Past the spin window, so the consumer is parked in parkNanos. + Thread.sleep(100); + Assert.assertTrue(q.offer("delivered")); + Assert.assertTrue("the producer's offer must unpark a timed take", done.await(5, TimeUnit.SECONDS)); + Assert.assertEquals("delivered", taken.get()); + consumer.join(1_000); + } + + @Test + public void testTimedTakeInterruptedThrows() throws Exception { + QwpSpscQueue q = new QwpSpscQueue<>(4); + AtomicReference caught = new AtomicReference<>(); + CountDownLatch done = new CountDownLatch(1); + Thread consumer = new Thread(() -> { + try { + q.take(System.nanoTime() + TimeUnit.SECONDS.toNanos(30)); + caught.set(new AssertionError("expected InterruptedException")); + } catch (Throwable t) { + caught.set(t); + } finally { + done.countDown(); + } + }, "spsc-timed-interrupt"); + consumer.start(); + Thread.sleep(100); + consumer.interrupt(); + Assert.assertTrue(done.await(5, TimeUnit.SECONDS)); + Assert.assertTrue("expected InterruptedException, got " + caught.get(), + caught.get() instanceof InterruptedException); + consumer.join(1_000); + } + @Test public void testCapacityOneIsRoundedToOne() { // Edge case: requesting capacity 1 still yields a power-of-two ring (1). diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/websocket/TestWebSocketServer.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/websocket/TestWebSocketServer.java index b93bc2b61..04f77fd88 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/websocket/TestWebSocketServer.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/websocket/TestWebSocketServer.java @@ -57,6 +57,9 @@ * Uses plain Java heap buffers - no native memory. */ public class TestWebSocketServer implements Closeable { + // Upper bound on how long a connection a handler dropped keeps draining the client, waiting for it to hang + // up, before its read thread closes the socket anyway. See ClientHandler.lingerThenClose(). + private static final long HANDLER_DROP_LINGER_MILLIS = 5_000; private static final Logger LOG = LoggerFactory.getLogger(TestWebSocketServer.class); private static final String WEBSOCKET_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // Number of upgrades the authorization validator rejected, over the server's lifetime. @@ -616,6 +619,9 @@ public class ClientHandler implements Closeable { private final ByteBuffer recvBuffer = ByteBuffer.allocate(65_536).order(ByteOrder.BIG_ENDIAN); private final AtomicBoolean running = new AtomicBoolean(false); private final Socket socket; + // Set by close() when a handler drops this connection from inside one of its own callbacks, i.e. on the + // read thread. Read only by that thread, which then lingers and closes the socket itself. + private boolean droppedByHandler; private InputStream in; private boolean isClosed; private OutputStream out; @@ -630,9 +636,33 @@ public class ClientHandler implements Closeable { recvBuffer.flip(); // start with nothing readable } + /** + * Closes this connection. Called from a handler callback -- the scripted mid-stream wire drop -- it + * delivers every frame the handler already wrote and then ends the stream with an orderly FIN; called + * from any other thread (server teardown) it closes the socket immediately and joins the read thread. + */ @Override public void close() { running.set(false); + if (Thread.currentThread() == readThread) { + // A handler is dropping the connection from one of its own callbacks: "ack, then drop the + // wire". A plain socket.close() here aborts the connection with an RST whenever the client has + // frames in flight that this thread has not read yet - the normal case mid-stream, as clients + // pipeline - and the kernel then also discards everything it has not transmitted yet, i.e. the + // frames this handler wrote a moment ago. The client sees "connection reset" instead of its + // acks, so the script silently degrades to "drop". Half-close instead: the FIN queues behind + // every frame already written. The read loop stops once the callback returns, and + // lingerThenClose() drains the client until it hangs up before closing the socket. No join + // either: it would wait on this very thread for its whole timeout, while the caller may hold a + // lock (a synchronized handler) that every other connection's callbacks need. + droppedByHandler = true; + try { + socket.shutdownOutput(); + } catch (IOException e) { + // already shut down, or the client is gone; lingerThenClose() still closes the socket + } + return; + } try { // FIN after the frames already written, never an RST: closing with unread input // resets the connection and purges anything still queued for the peer. @@ -812,6 +842,35 @@ private void handleRead() { recvBuffer.flip(); } + // Runs on the read thread once a handler has dropped the connection (see close()). The FIN is already + // queued behind the frames the handler wrote; keep reading - and discarding - whatever the client still + // sends until it closes its side, so the final close() never finds unread input, the condition that turns + // it into an RST and throws away frames still on their way out. Bounded, so a client that never hangs up + // cannot pin the thread; the server's close() cuts it short by closing the socket under the read. + private void lingerThenClose() { + final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(HANDLER_DROP_LINGER_MILLIS); + final byte[] discard = new byte[8192]; + try { + while (System.nanoTime() < deadline) { + try { + if (in.read(discard) < 0) { + break; + } + } catch (SocketTimeoutException e) { + // the SO_TIMEOUT tick; keep waiting for the client's FIN + } + } + } catch (IOException e) { + // reset by the client, or closed by the server's close(): nothing left to deliver + } finally { + try { + socket.close(); + } catch (IOException e) { + // ignore + } + } + } + private boolean performHandshake() throws IOException { StringBuilder request = new StringBuilder(); byte[] buf = new byte[1]; @@ -1077,6 +1136,10 @@ void start() { if (running.get()) { LOG.error("Client error", e); } + } finally { + if (droppedByHandler) { + lingerThenClose(); + } } }, "WebSocket-Client-" + socket.getPort()); readThread.start(); diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/websocket/TestWebSocketServerHandlerDropTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/websocket/TestWebSocketServerHandlerDropTest.java new file mode 100644 index 000000000..a66380a9d --- /dev/null +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/websocket/TestWebSocketServerHandlerDropTest.java @@ -0,0 +1,193 @@ +/*+***************************************************************************** + * ___ _ ____ ____ + * / _ \ _ _ ___ ___| |_| _ \| __ ) + * | | | | | | |/ _ \/ __| __| | | | _ \ + * | |_| | |_| | __/\__ \ |_| |_| | |_) | + * \__\_\\__,_|\___||___/\__|____/|____/ + * + * Copyright (c) 2014-2019 Appsicle + * Copyright (c) 2019-2026 QuestDB + * + * Licensed 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 io.questdb.client.test.cutlass.qwp.websocket; + +import io.questdb.client.cutlass.qwp.websocket.WebSocketOpcode; +import io.questdb.client.test.tools.TestUtils; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * Pins what a client observes when a {@link TestWebSocketServer.WebSocketServerHandler} drops the connection + * from inside its own callback -- the "send the acks, then {@code client.close()}" script that reconnect, + * failover and drainer tests use to model a mid-stream wire drop. + *

    + * Every frame the handler wrote before the drop must reach the client, followed by an orderly end of stream. + * The condition that breaks this is ordinary: the client still has frames in flight. They sit unread in the + * server's receive queue when the handler drops, and closing a socket with unread input aborts the connection + * with an RST, which also discards whatever the kernel has not transmitted yet -- the frames the handler wrote + * a moment earlier. The client then sees "connection reset" instead of the acks, so "ack N frames, then drop" + * quietly becomes "drop", and anything that depends on those acks (a drainer's progress-based escalation + * budget, for one) fails at random. + *

    + * The test forces both halves of that race rather than waiting for the scheduler to produce them: the trailing + * client frame is larger than one server read, so its tail is still unread when the handler acts, and the + * filler ahead of the ack is larger than the client's receive window, so the ack is still queued on the server + * at the moment of the drop. + */ +public class TestWebSocketServerHandlerDropTest { + + private static final byte[] ACK = "ack-written-before-drop".getBytes(StandardCharsets.US_ASCII); + // Applied before connect(), so it caps the window the client advertises. + private static final int CLIENT_RECEIVE_BUFFER_BYTES = 4096; + // Several times the client's receive window: most of it, and the ack queued behind it, has not left the + // server when the handler drops. + private static final int FILLER_BYTES = 32 * 1024; + // Several times the server's 8 KiB socket read, so the frame that triggers the drop is dispatched while the + // tail of this one is still unread in the server's receive queue. + private static final int TRAILING_FRAME_BYTES = 32 * 1024; + + @Test + public void testFramesWrittenBeforeHandlerDropReachClientAheadOfEndOfStream() throws Exception { + TestUtils.assertMemoryLeak(() -> { + final byte[] filler = new byte[FILLER_BYTES]; + Arrays.fill(filler, (byte) 'f'); + TestWebSocketServer.WebSocketServerHandler handler = new TestWebSocketServer.WebSocketServerHandler() { + private boolean dropped; + + @Override + public synchronized void onBinaryMessage(TestWebSocketServer.ClientHandler client, byte[] data) { + if (dropped) { + return; + } + dropped = true; + try { + client.sendBinary(filler); + client.sendBinary(ACK); + } catch (IOException e) { + throw new AssertionError("server could not queue its frames", e); + } + client.close(); // the scripted mid-stream wire drop + } + }; + try (TestWebSocketServer server = new TestWebSocketServer(handler)) { + server.start(); + assertTrue(server.awaitStart(5, TimeUnit.SECONDS)); + try (Socket socket = new Socket()) { + socket.setReceiveBufferSize(CLIENT_RECEIVE_BUFFER_BYTES); + socket.setSoTimeout(10_000); + socket.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), server.getPort()), 5_000); + OutputStream out = socket.getOutputStream(); + DataInputStream in = new DataInputStream(socket.getInputStream()); + upgrade(out, in); + + // A single write, so both frames are on the wire before the server reads anything. + ByteArrayOutputStream frames = new ByteArrayOutputStream(); + writeMaskedBinaryFrame(frames, new byte[]{1}); + writeMaskedBinaryFrame(frames, new byte[TRAILING_FRAME_BYTES]); + out.write(frames.toByteArray()); + out.flush(); + + int framesReceived = 0; + try { + assertFrame(in, filler, "filler"); + framesReceived++; + assertFrame(in, ACK, "ack"); + framesReceived++; + assertEquals("the drop must end the stream right after the frames written before it", + -1, in.read()); + } catch (IOException e) { + fail("the handler's drop lost frames it had written before dropping [framesReceived=" + + framesReceived + " of 2]: " + e); + } + } + } + }); + } + + private static void assertFrame(DataInputStream in, byte[] expectedPayload, String what) throws IOException { + assertEquals(what + ": FIN + BINARY", 0x80 | WebSocketOpcode.BINARY, in.readUnsignedByte()); + int lengthByte = in.readUnsignedByte(); + assertEquals(what + ": server frames are unmasked", 0, lengthByte & 0x80); + int length = lengthByte & 0x7F; + if (length == 126) { + length = in.readUnsignedShort(); + } else if (length == 127) { + long longLength = in.readLong(); + assertTrue(what + ": implausible frame length " + longLength, longLength <= Integer.MAX_VALUE); + length = (int) longLength; + } + assertEquals(what + ": payload length", expectedPayload.length, length); + byte[] payload = new byte[length]; + in.readFully(payload); + assertArrayEquals(what + ": payload", expectedPayload, payload); + } + + private static void upgrade(OutputStream out, DataInputStream in) throws IOException { + String request = "GET /write/v4 HTTP/1.1\r\n" + + "Host: localhost\r\n" + + "Upgrade: websocket\r\n" + + "Connection: Upgrade\r\n" + + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" + + "Sec-WebSocket-Version: 13\r\n" + + "\r\n"; + out.write(request.getBytes(StandardCharsets.US_ASCII)); + out.flush(); + StringBuilder response = new StringBuilder(); + while (response.indexOf("\r\n\r\n") < 0) { + int b = in.read(); + if (b < 0) { + fail("server closed the connection during the upgrade [response=" + response + ']'); + } + response.append((char) b); + } + assertTrue("upgrade rejected: " + response, response.toString().startsWith("HTTP/1.1 101")); + } + + private static void writeMaskedBinaryFrame(ByteArrayOutputStream out, byte[] payload) { + int length = payload.length; + out.write(0x80 | WebSocketOpcode.BINARY); + if (length <= 125) { + out.write(0x80 | length); + } else if (length <= 0xFFFF) { + out.write(0x80 | 126); + out.write(length >>> 8); + out.write(length & 0xFF); + } else { + throw new IllegalArgumentException("frame too large for this helper: " + length); + } + // Client frames must be masked; an all-zero key leaves the payload bytes unchanged. + out.write(0); + out.write(0); + out.write(0); + out.write(0); + out.write(payload, 0, length); + } +} diff --git a/core/src/test/java/io/questdb/client/test/impl/QueryImplResetTest.java b/core/src/test/java/io/questdb/client/test/impl/QueryImplResetTest.java index bedbba92f..5ce9841d9 100644 --- a/core/src/test/java/io/questdb/client/test/impl/QueryImplResetTest.java +++ b/core/src/test/java/io/questdb/client/test/impl/QueryImplResetTest.java @@ -71,10 +71,12 @@ public void testResetForBorrowClearsBuilderState() throws Exception { Field bindsF = queryImplClass.getDeclaredField("userBinds"); Field sqlBufF = queryImplClass.getDeclaredField("sqlBuffer"); Field doneF = queryImplClass.getDeclaredField("done"); + Field timeoutF = queryImplClass.getDeclaredField("timeoutMillis"); handlerF.setAccessible(true); bindsF.setAccessible(true); sqlBufF.setAccessible(true); doneF.setAccessible(true); + timeoutF.setAccessible(true); // Seed builder state as a prior borrow would have left it. handlerF.set(q, new NoopHandler()); @@ -82,6 +84,7 @@ public void testResetForBorrowClearsBuilderState() throws Exception { // no-op }); ((StringSink) sqlBufF.get(q)).put("SELECT 1"); + timeoutF.setLong(q, 0L); // a prior borrow disabled the timeout doneF.setBoolean(q, false); Method reset = queryImplClass.getDeclaredMethod("resetForBorrow"); @@ -97,6 +100,8 @@ public void testResetForBorrowClearsBuilderState() throws Exception { 0, sqlBuffer.length()); Assert.assertTrue("done must be true so the handle starts idle, not in flight", doneF.getBoolean(q)); + Assert.assertEquals("the query timeout must fall back to the configured default (-1)", + -1L, timeoutF.getLong(q)); }); } diff --git a/core/src/test/java/io/questdb/client/test/impl/QwpQueryClientConfigHonoredTest.java b/core/src/test/java/io/questdb/client/test/impl/QwpQueryClientConfigHonoredTest.java index 3e02f327e..dad288477 100644 --- a/core/src/test/java/io/questdb/client/test/impl/QwpQueryClientConfigHonoredTest.java +++ b/core/src/test/java/io/questdb/client/test/impl/QwpQueryClientConfigHonoredTest.java @@ -63,6 +63,7 @@ public void testEveryEgressKeyIsHonored() throws Exception { assertHonored("failover_max_duration_ms=56000", "failover_max_duration_ms", 56000L); assertHonored("max_batch_rows=512", "max_batch_rows", 512); assertHonored("initial_credit=65536", "initial_credit", 65536L); + assertHonored("query_timeout_ms=1500", "query_timeout_ms", 1500L); assertHonored("buffer_pool_size=3", "buffer_pool_size", 3); assertHonored("compression=zstd", "compression", "zstd"); assertHonored("compression_level=9", "compression_level", 9); diff --git a/examples/src/main/java/com/example/query/QueryCancellationExample.java b/examples/src/main/java/com/example/query/QueryCancellationExample.java index b9def4bb9..57bda2880 100644 --- a/examples/src/main/java/com/example/query/QueryCancellationExample.java +++ b/examples/src/main/java/com/example/query/QueryCancellationExample.java @@ -19,6 +19,9 @@ * blocking {@link Completion#await()} throws {@link QueryException} carrying * that status. If the query finished before the cancel landed, {@code await()} * returns normally -- {@code cancel()} is a no-op on an already-terminal query. + *

    + * To stop queries that run too long without driving the cancel yourself, give + * them a timeout instead; see {@link QueryTimeoutExample}. */ public class QueryCancellationExample { diff --git a/examples/src/main/java/com/example/query/QueryTimeoutExample.java b/examples/src/main/java/com/example/query/QueryTimeoutExample.java new file mode 100644 index 000000000..cc2d3fae3 --- /dev/null +++ b/examples/src/main/java/com/example/query/QueryTimeoutExample.java @@ -0,0 +1,68 @@ +package com.example.query; + +import io.questdb.client.Query; +import io.questdb.client.QueryException; +import io.questdb.client.QuestDB; +import io.questdb.client.cutlass.qwp.client.QwpColumnBatch; +import io.questdb.client.cutlass.qwp.client.QwpColumnBatchHandler; + +import java.util.concurrent.TimeUnit; + +/** + * Giving a query a timeout. + *

    + * {@link Query#timeout(long, TimeUnit)} overrides the server's default query + * timeout ({@code query.timeout}) for one query; {@code query_timeout_ms} in the + * connection string sets a default for every query. The client sends the + * timeout with the query and keeps no deadline of its own. The server stops + * the query when it can, and {@code await()} throws a {@link QueryException} + * whose {@link QueryException#isTimeout()} is {@code true}. The pooled + * connection stays open, so the same handle goes on to run the next query on + * it. Some statements cannot be stopped and run to completion. A server that + * does not support per-query timeouts applies its own default. + *

    + * Compare {@link QueryCancellationExample}: {@code await(timeout)} only bounds + * how long the caller waits, the query keeps running until cancelled. + */ +public class QueryTimeoutExample { + + public static void main(String[] args) throws InterruptedException { + // query_timeout_ms: default timeout for every query of this handle's pool. + try (QuestDB db = QuestDB.connect("ws::addr=localhost:9000;query_timeout_ms=30000;"); + Query q = db.borrowQuery()) { + + q.sql("SELECT * FROM trades ORDER BY price") + .handler(new PrintingHandler()) + // Tighter than the default, for this handle only. + .timeout(5, TimeUnit.SECONDS); + try { + q.submit().await(); + System.out.println("finished within the timeout"); + } catch (QueryException e) { + if (!e.isTimeout()) { + throw e; + } + System.out.println("timed out: " + e.getMessage()); + } + + // The connection survived the timeout; run the next query on it. + q.sql("SELECT count() FROM trades").timeout(0, TimeUnit.SECONDS).submit().await(); + } + } + + private static final class PrintingHandler implements QwpColumnBatchHandler { + @Override + public void onBatch(QwpColumnBatch batch) { + // Process rows... kept minimal here. + } + + @Override + public void onEnd(long totalRows) { + System.out.println("done: " + totalRows + " rows"); + } + + @Override + public void onError(byte status, String message) { + } + } +}