From a0a0d892f0531434eab6690552c51f3f08ec20b4 Mon Sep 17 00:00:00 2001 From: bluestreak Date: Wed, 11 Nov 2026 23:24:11 +0000 Subject: [PATCH 01/20] Let QWP senders send batches of any size The WebSocket sender's default byte trigger now sizes every batch to 90% of the frame the connection can carry: the smaller of the server's advertised X-QWP-Max-Batch-Size and the store-and-forward segment payload, or the server's default cap when nothing is advertised. Rows wider than about 2 KiB no longer fail with BatchTooLargeForCapException, in streaming and in transactional mode. auto_flush_bytes=off and a sender with every auto-flush trigger off keep the old behaviour. New symbols count toward the trigger, since their strings ride in the frame's dictionary section. Add strict transactional mode: transaction=strict, or auto_flush=off on WebSocket. Rows go out as deferred frames sized for the connection and only flush() commits, so a transaction can be any size, but it never commits in parts: a row that would take a table to the server's qwp.max.uncommitted.rows (advertised in X-QWP-Max-Uncommitted-Rows, or the 1M default) and a transaction that outgrows sf_max_total_bytes are refused with TransactionTooLargeException before anything reaches the server, leaving the transaction open. close() without flush() discards a strict transaction, and a pooled strict lease discards it on return. Add Sender.rollback() and the QWP rollback control frame. The sender asks for it with X-QWP-Request-Rollback and sends the frame only to a server that confirmed X-QWP-Rollback: enabled; rollback() waits for the ack, so a reconnect can never replay the rolled-back frames. reset() in transactional mode now rolls back frames already sent when the server supports it. Without server support rollback() aborts the transaction, and a strict reset() does too; a non-strict reset() keeps committing those frames on the next flush, as before. --- .../main/java/io/questdb/client/Sender.java | 100 ++- .../cutlass/http/client/WebSocketClient.java | 89 ++ .../qwp/client/QwpWebSocketEncoder.java | 20 + .../qwp/client/QwpWebSocketSender.java | 680 ++++++++++++++-- .../client/TransactionTooLargeException.java | 49 ++ .../client/sf/cursor/CursorSendEngine.java | 11 + .../qwp/client/sf/cursor/SegmentManager.java | 8 + .../cutlass/qwp/protocol/QwpConstants.java | 20 + .../cutlass/qwp/protocol/QwpTableBuffer.java | 18 + .../io/questdb/client/impl/PooledSender.java | 20 +- .../client/test/QuestDBBuilderTest.java | 10 +- .../http/client/WebSocketClientTest.java | 32 + .../qwp/client/DeltaDictRecoveryTest.java | 8 +- .../LineSenderBuilderWebSocketTest.java | 9 +- .../qwp/client/QwpLargeTransactionTest.java | 759 ++++++++++++++++++ .../qwp/client/SelfSufficientFramesTest.java | 4 +- .../qwp/websocket/TestWebSocketServer.java | 46 ++ .../test/impl/WsSenderConfigHonoredTest.java | 7 +- 18 files changed, 1802 insertions(+), 88 deletions(-) create mode 100644 core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java create mode 100644 core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java diff --git a/core/src/main/java/io/questdb/client/Sender.java b/core/src/main/java/io/questdb/client/Sender.java index d16e97804..b3ffb3484 100644 --- a/core/src/main/java/io/questdb/client/Sender.java +++ b/core/src/main/java/io/questdb/client/Sender.java @@ -780,6 +780,26 @@ default void resetSymbolDictionary() { */ void reset(); + /** + * Discard the open transaction: the rows buffered since the last flush and, in + * WebSocket transactional mode ({@code transaction=on} or {@code strict}), the + * rows of the transaction that auto-flush already sent to the server, which + * the server discards on request. Blocks until the server confirms. + *
+ * Discarding rows already sent needs a server that supports QWP rollback. When + * the server does not, this method throws and aborts the transaction: every + * later flush throws too, and closing the sender discards the rows, because the + * server rolls back uncommitted rows when the connection closes. + *
+ * Only the WebSocket transport supports this method. + * + * @throws LineSenderException if the transport does not support rollback, or the + * server cannot discard rows already sent + */ + default void rollback() { + throw new LineSenderException("rollback is only supported for WebSocket transport"); + } + /** * Add a column with a 16-bit signed integer value. * @@ -1075,7 +1095,10 @@ final class LineSenderBuilder { private static final int DEFAULT_TCP_PORT = 9009; private static final int DEFAULT_UDP_PORT = 9007; private static final int DEFAULT_WEBSOCKET_PORT = 9000; - private static final int DEFAULT_WS_AUTO_FLUSH_BYTES = 0; + // Unset auto_flush_bytes on WebSocket sizes the byte trigger from what one + // frame can carry, so no batch outgrows a frame; see + // QwpWebSocketSender.AUTO_FLUSH_BYTES_AUTO. + private static final int DEFAULT_WS_AUTO_FLUSH_BYTES = QwpWebSocketSender.AUTO_FLUSH_BYTES_AUTO; private static final long DEFAULT_WS_AUTO_FLUSH_INTERVAL_NANOS = 100_000_000L; // 100ms private static final int DEFAULT_WS_AUTO_FLUSH_ROWS = 1_000; // Cadence at which the SF cursor I/O loop sends a keepalive PING @@ -1234,7 +1257,12 @@ public int getConnectTimeout() { private long reconnectMaxDurationMillis = PARAMETER_NOT_SET_EXPLICITLY; private int durableAckTiers = DurableAckTiers.NONE; private int retryTimeoutMillis = PARAMETER_NOT_SET_EXPLICITLY; + private boolean strictTransactional; private boolean transactional; + // True once transaction=... (or transactional()/strictTransactional()) + // set the mode explicitly, so auto_flush=off can refuse to override an + // explicit transaction=off. + private boolean transactionModeSet; private String senderId = DEFAULT_SENDER_ID; // Per-append deadline for SF appendBlocking spin-then-throw. Used to // be a hardcoded 30s constant; expose so tight-SLA users can lower @@ -1868,9 +1896,11 @@ public LineSenderBuilder connectionListenerInboxCapacity(int capacity) { *

* It is essential to ensure the maximum buffer capacity is sufficient to accommodate all locally buffered data. *

- * This method should only be used when communicating via the HTTP protocol. Calling this method is illegal when - * communicating over the TCP or WebSocket protocol. On WebSocket, {@code auto_flush_interval=off} turns off - * only the time-based trigger. + * This method can be used with the HTTP and WebSocket protocols; calling it is illegal when communicating over + * the TCP protocol. On WebSocket it selects strict transactional mode (see + * {@link #strictTransactional(boolean)}): rows still go to the server in frames sized for the connection, so a + * batch can be any size, but only {@code flush()} commits them, and closing without a flush discards them. + * There, {@code auto_flush_interval=off} alone turns off only the time-based trigger. * * @return this instance for method chaining * @see #autoFlushRows(int) @@ -2757,12 +2787,43 @@ private LineSenderBuilder requestDurableAckTiers(int tiers) { return this; } + /** + * Enables strict transactional mode, the builder form of + * {@code transaction=strict}. Like {@link #transactional(boolean)}, auto-flush + * sends rows to the server without committing them and {@code flush()} + * commits, so a transaction can be any size. In addition the transaction + * never commits in parts: a row that would take a table past the server's + * {@code qwp.max.uncommitted.rows}, or a transaction that outgrows + * {@code sf_max_total_bytes}, throws + * {@link io.questdb.client.cutlass.qwp.client.TransactionTooLargeException} + * and leaves the transaction open, and {@code close()} without + * {@code flush()} discards the transaction instead of committing it. + * {@code auto_flush=off} selects the same mode. WebSocket transport only. + * + * @param enabled true to enable strict transactional mode; false leaves + * {@link #transactional(boolean) transactional} mode as set + * @return this instance for method chaining + */ + public LineSenderBuilder strictTransactional(boolean enabled) { + if (protocol != PARAMETER_NOT_SET_EXPLICITLY && protocol != PROTOCOL_WEBSOCKET) { + throw new LineSenderException("transactional is only supported for WebSocket transport"); + } + this.strictTransactional = enabled; + if (enabled) { + this.transactional = true; + } + this.transactionModeSet = true; + return this; + } + /** * Enables transactional mode. Auto-flush sends data to the server * with {@code FLAG_DEFER_COMMIT}; only an explicit {@code flush()} - * triggers the server-side WAL commit. This allows accumulating - * datasets larger than the server's recv buffer while committing - * atomically per table. + * (or {@code close()}) triggers the server-side WAL commit. This allows + * accumulating datasets larger than the server's recv buffer while + * committing atomically per table. The server commits a table on its own + * once {@code qwp.max.uncommitted.rows} of its rows are uncommitted; use + * {@link #strictTransactional(boolean)} to fail instead. * * @param enabled true to enable transactional mode * @return this instance for method chaining @@ -2772,6 +2833,10 @@ public LineSenderBuilder transactional(boolean enabled) { throw new LineSenderException("transactional is only supported for WebSocket transport"); } this.transactional = enabled; + if (!enabled) { + this.strictTransactional = false; + } + this.transactionModeSet = true; return this; } @@ -3822,6 +3887,11 @@ private QwpWebSocketSender buildWebSocket(HttpTokenProvider tokenProvider) { // dispatcher daemon, drainer pool, microbatch buffers and // WebSocketClient inside the abandoned `connected`. connected.setTransactional(transactional); + // auto_flush=off on WebSocket means "commit only when I flush()": a + // strict transaction of any size. + if (strictTransactional || autoFlushDisabled) { + connected.setStrictTransactional(true); + } try { final String rebuildSfDir = sfDir; final String rebuildSenderId = senderId; @@ -4230,8 +4300,10 @@ private LineSenderBuilder fromConfig(CharSequence configurationString) { transactional(true); } else if (Chars.equalsIgnoreCase("off", sink)) { transactional(false); + } else if (Chars.equalsIgnoreCase("strict", sink)) { + strictTransactional(true); } else { - throw new LineSenderException("invalid transaction [value=").put(sink).put(", allowed-values=[on, off]]"); + throw new LineSenderException("invalid transaction [value=").put(sink).put(", allowed-values=[on, off, strict]]"); } } else if (Chars.equals("sf_dir", sink)) { if (protocol != PROTOCOL_WEBSOCKET) { @@ -4682,8 +4754,10 @@ private LineSenderBuilder fromConfigWebSocket(CharSequence configurationString) transactional(true); } else if (s.equalsIgnoreCase("off")) { transactional(false); + } else if (s.equalsIgnoreCase("strict")) { + strictTransactional(true); } else { - throw new LineSenderException("invalid transaction [value=").put(s).put(", allowed-values=[on, off]]"); + throw new LineSenderException("invalid transaction [value=").put(s).put(", allowed-values=[on, off, strict]]"); } } s = view.getStr("request_durable_ack"); @@ -4821,7 +4895,7 @@ public java.util.Map wsConfigSnapshotForTest() { m.put("auto_flush_bytes", autoFlushBytes); m.put("auto_flush_interval", autoFlushIntervalMillis); m.put("max_name_len", maxNameLength); - m.put("transaction", transactional); + m.put("transaction", strictTransactional ? "strict" : transactional ? "on" : "off"); m.put("request_durable_ack", DurableAckTiers.configValue(durableAckTiers)); m.put("sender_id", senderId); m.put("sf_dir", sfDir); @@ -5068,8 +5142,10 @@ private void validateParameters() { if (protocolVersion != PARAMETER_NOT_SET_EXPLICITLY) { throw new LineSenderException("protocol version is not supported for WebSocket protocol"); } - if (autoFlushDisabled) { - throw new LineSenderException("disabling auto-flush is not supported for WebSocket protocol"); + if (autoFlushDisabled && transactionModeSet && !transactional) { + // On WebSocket, auto_flush=off is strict transactional mode. + throw new LineSenderException("auto_flush=off selects strict transactional mode on WebSocket " + + "and cannot be combined with transaction=off"); } if ((sfDurability == SfDurability.FLUSH || sfDurability == SfDurability.APPEND)) { throw new LineSenderException( diff --git a/core/src/main/java/io/questdb/client/cutlass/http/client/WebSocketClient.java b/core/src/main/java/io/questdb/client/cutlass/http/client/WebSocketClient.java index 938d51752..ab479d602 100644 --- a/core/src/main/java/io/questdb/client/cutlass/http/client/WebSocketClient.java +++ b/core/src/main/java/io/questdb/client/cutlass/http/client/WebSocketClient.java @@ -84,6 +84,11 @@ public abstract class WebSocketClient implements QuietCloseable { private static final String QWP_CONTENT_ENCODING_HEADER_NAME = "X-QWP-Content-Encoding:"; private static final String QWP_DURABLE_ACK_HEADER_NAME = "X-QWP-Durable-Ack:"; private static final String QWP_MAX_BATCH_SIZE_HEADER_NAME = "X-QWP-Max-Batch-Size:"; + private static final String QWP_MAX_UNCOMMITTED_ROWS_HEADER_NAME = "X-QWP-Max-Uncommitted-Rows:"; + private static final String QWP_ROLLBACK_HEADER_NAME = "X-QWP-Rollback:"; + // Token the server echoes in X-QWP-Rollback when it accepts the rollback + // control frame on this connection. + private static final String QWP_ROLLBACK_TOKEN_ENABLED = "enabled"; private static final String QWP_VERSION_HEADER_NAME = "X-QWP-Version:"; private static final ThreadLocal SHA1_DIGEST = ThreadLocal.withInitial(() -> { try { @@ -148,6 +153,9 @@ public abstract class WebSocketClient implements QuietCloseable { // Requested durable-ack tier set (DurableAckTiers bitmask), sent as // X-QWP-Request-Durable-Ack: private int qwpDurableAckTiers = DurableAckTiers.NONE; + // When true, the upgrade request carries X-QWP-Request-Rollback: true, asking + // the server to confirm that it accepts the rollback control frame. + private boolean qwpRequestRollback; // Receive buffer (native memory) private long recvBufPtr; private int recvBufSize; @@ -170,6 +178,11 @@ public abstract class WebSocketClient implements QuietCloseable { // not advertise the header (older builds), in which case the sender falls // back to its locally configured budget. private int serverMaxBatchSize; + // Server's per-table cap on rows a deferred-commit group may hold before the + // server commits them on its own (qwp.max.uncommitted.rows), extracted from + // X-QWP-Max-Uncommitted-Rows on the 101 upgrade response. 0 when the server + // did not advertise it (older builds). + private long serverMaxUncommittedRows; // Zstd compression level the server actually applied for this connection, // extracted from the echoed X-QWP-Content-Encoding response header. // 0 means "no zstd" -- either the server picked raw, the header was absent @@ -178,6 +191,11 @@ public abstract class WebSocketClient implements QuietCloseable { // the wire said without re-clamping so a misconfigured server is observable. private int serverNegotiatedZstdLevel; private int serverQwpVersion = 1; + // Set during upgrade response validation when the client asked for rollback + // (qwpRequestRollback) and the server confirmed it with X-QWP-Rollback: + // enabled. A server that does not confirm treats the rollback control frame + // as an empty deferred frame, so the client must never send it there. + private boolean serverRollbackEnabled; private String upgradeRejectRole; // WWW-Authenticate value(s) from the most recent rejected upgrade, joined with ", " when the server sent // several, or null when absent. Lets a 401 carrying "Bearer error=insufficient_scope" be told apart from an @@ -412,6 +430,16 @@ public int getServerMaxBatchSize() { return serverMaxBatchSize; } + /** + * Server's per-table limit on rows a deferred-commit group may hold before + * the server commits them on its own ({@code qwp.max.uncommitted.rows}), taken + * from the {@code X-QWP-Max-Uncommitted-Rows} response header on the 101 + * upgrade. Returns {@code 0} when the server did not advertise the header. + */ + public long getServerMaxUncommittedRows() { + return serverMaxUncommittedRows; + } + /** * Zstd level the server actually applied for this connection, parsed * from the echoed {@code X-QWP-Content-Encoding} response header. @@ -494,6 +522,16 @@ public boolean isServerDurableAckEnabled() { return serverDurableAckEnabled; } + /** + * Returns true when the client asked for rollback support via + * {@link #setQwpRequestRollback} and the 101 upgrade response confirmed it + * with {@code X-QWP-Rollback: enabled}. Meaningful only after + * {@link #upgrade} returns. + */ + public boolean isServerRollbackEnabled() { + return serverRollbackEnabled; + } + /** * Receives and processes WebSocket frames. * @@ -670,6 +708,16 @@ public void setQwpMaxVersion(int maxVersion) { this.qwpMaxVersion = maxVersion; } + /** + * When {@code true}, the upgrade request carries + * {@code X-QWP-Request-Rollback: true}. A server that accepts the rollback + * control frame confirms it with {@code X-QWP-Rollback: enabled}; see + * {@link #isServerRollbackEnabled()}. + */ + public void setQwpRequestRollback(boolean requestRollback) { + this.qwpRequestRollback = requestRollback; + } + /** * Sets the requested durable-ack tier set ({@link DurableAckTiers} * bitmask) for the opt-in X-QWP-Request-Durable-Ack upgrade header. When @@ -795,6 +843,9 @@ public void upgrade(CharSequence path, int timeout, CharSequence authorizationHe sendBuffer.putAscii(DurableAckTiers.requestHeaderValue(qwpDurableAckTiers)); sendBuffer.putAscii("\r\n"); } + if (qwpRequestRollback) { + sendBuffer.putAscii("X-QWP-Request-Rollback: true\r\n"); + } if (authorizationHeader != null) { sendBuffer.putAscii("Authorization: "); sendBuffer.putAscii(authorizationHeader); @@ -912,6 +963,22 @@ private static String extractDurableAckEcho(String response) { return null; } + private static String extractHeaderValue(String response, String headerName) { + int headerLen = headerName.length(); + int responseLen = response.length(); + for (int i = 0; i <= responseLen - headerLen; i++) { + if (response.regionMatches(true, i, headerName, 0, headerLen)) { + int valueStart = i + headerLen; + int lineEnd = response.indexOf('\r', valueStart); + if (lineEnd < 0) { + lineEnd = responseLen; + } + return response.substring(valueStart, lineEnd).trim(); + } + } + return null; + } + private static int extractMaxBatchSize(String response) { int headerLen = QWP_MAX_BATCH_SIZE_HEADER_NAME.length(); int responseLen = response.length(); @@ -934,6 +1001,18 @@ private static int extractMaxBatchSize(String response) { return 0; } + private static long extractMaxUncommittedRows(String response) { + String value = extractHeaderValue(response, QWP_MAX_UNCOMMITTED_ROWS_HEADER_NAME); + if (value == null) { + return 0; + } + try { + return Math.max(Long.parseLong(value), 0); + } catch (NumberFormatException e) { + return 0; + } + } + private static int extractQwpVersion(String response) { int headerLen = QWP_VERSION_HEADER_NAME.length(); int responseLen = response.length(); @@ -1541,6 +1620,16 @@ private void validateUpgradeResponse(int headerEnd) { // sender falls back to its locally configured byte budget in that case. serverMaxBatchSize = extractMaxBatchSize(response); + // Extract X-QWP-Max-Uncommitted-Rows (optional). Older servers omit it; + // a strict transaction then assumes the server's default. + serverMaxUncommittedRows = extractMaxUncommittedRows(response); + + // Extract the X-QWP-Rollback confirmation (optional). Only a client that + // asked for rollback may treat it as granted: the server echoes it only + // on request, and an older server never sends it. + serverRollbackEnabled = qwpRequestRollback + && QWP_ROLLBACK_TOKEN_ENABLED.equalsIgnoreCase(extractHeaderValue(response, QWP_ROLLBACK_HEADER_NAME)); + // Extract X-QWP-Content-Encoding (optional). Surfaces what level the // server actually applied -- which may differ from what this client // asked for if the server has qwp.egress.compression.force.level set diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketEncoder.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketEncoder.java index f38d9e93d..68c338662 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketEncoder.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketEncoder.java @@ -184,6 +184,26 @@ public int encodeWithDeltaDict( return finishMessage(); } + /** + * Encodes the rollback control frame into the buffer: a bare header with + * {@code ROLLBACK_FRAME_FLAGS}, no table blocks and an empty payload. The + * server matches it on exactly that shape. + * + * @return the frame size in bytes + */ + public int encodeRollbackMessage() { + buffer.reset(); + buffer.putByte((byte) 'Q'); + buffer.putByte((byte) 'W'); + buffer.putByte((byte) 'P'); + buffer.putByte((byte) '1'); + buffer.putByte(version); + buffer.putByte(ROLLBACK_FRAME_FLAGS); + buffer.putShort((short) 0); + buffer.putInt(0); + return buffer.getPosition(); + } + public int finishMessage() { int payloadLength = buffer.getPosition() - payloadStart; buffer.patchInt(8, payloadLength); diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java index 1fc434840..7d94dc702 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java @@ -72,6 +72,7 @@ import io.questdb.client.std.NumericException; import io.questdb.client.std.ObjList; import io.questdb.client.std.QuietCloseable; +import io.questdb.client.std.Unsafe; import io.questdb.client.std.bytes.DirectByteSlice; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; @@ -135,6 +136,15 @@ */ public class QwpWebSocketSender implements Sender { + /** + * {@code autoFlushBytes} value that sizes the byte trigger from the frames the + * connection can carry: 90% of the smaller of the server's advertised + * {@code X-QWP-Max-Batch-Size} and the store-and-forward segment. It is the + * builder default, so a batch never grows past what one frame can hold. A pure + * manual-flush sender (non-transactional, row and interval triggers off) keeps + * no byte trigger, as before. + */ + public static final int AUTO_FLUSH_BYTES_AUTO = -1; public static final long DEFAULT_AUTH_TIMEOUT_MS = 15_000L; // Soft per-batch byte budget. Trips a flush when raw column-buffer bytes // cross the threshold, well before the server's 16 MB wire cap. Wide-row @@ -176,6 +186,17 @@ public class QwpWebSocketSender implements Sender { public static final int DEFAULT_SYMBOL_DICT_RESET_THRESHOLD_SYMBOLS = 100_000; private static final int DEFAULT_BUFFER_SIZE = 8192; private static final int DEFAULT_MICROBATCH_BUFFER_SIZE = 1024 * 1024; // 1MB + // How long rollback() waits for the server to acknowledge the rollback frame. + private static final long DEFAULT_ROLLBACK_ACK_TIMEOUT_MILLIS = 30_000L; + // Frames of at most the frame cap that a strict transaction keeps room for in + // the client buffer, so the commit that ends it can always be published. + private static final int STRICT_COMMIT_RESERVE_FRAMES = 3; + // Frame cap the byte trigger assumes when the server does not advertise + // X-QWP-Max-Batch-Size: the server's default 2 MiB recv buffer minus the + // worst-case WebSocket frame header, the same value such a server would have + // advertised. Sizes only the soft trigger, never the hard per-frame guard, so an + // older server with a larger buffer still accepts every frame it used to. + private static final int FALLBACK_SERVER_MAX_BATCH_SIZE = 2 * 1024 * 1024 - 14; private static final Logger LOG = LoggerFactory.getLogger(QwpWebSocketSender.class); private static final int MAX_TABLE_NAME_LENGTH = 127; // sf-client.md section 4.4 floor: drop-oldest under bursts needs a wide @@ -678,6 +699,50 @@ public class QwpWebSocketSender implements Sender { // refresh this from the cursor I/O thread on a mid-stream reconnect while // sendRow reads it on the producer thread with no synchronization. private volatile int serverMaxBatchSize; + // Byte length of the symbol-dictionary entries the pending batch introduced: + // the rows reference these ids, so the batch's next frame must carry the + // entries too. Counted toward the byte trigger alongside pendingBytes. Reset + // with pendingBytes. + private long pendingSymbolDictBytes; + // Rollback-ack wait bound; see rollbackOpenTransaction. + private long rollbackAckTimeoutMillis = DEFAULT_ROLLBACK_ACK_TIMEOUT_MILLIS; + // Server's per-table cap on rows a deferred-commit group may hold before it + // commits them on its own (X-QWP-Max-Uncommitted-Rows), 0 when not advertised. + // Captured on each FOREGROUND handshake, like serverMaxBatchSize. + private volatile long serverMaxUncommittedRows; + // True when the current foreground connection confirmed X-QWP-Rollback, so the + // rollback control frame may go out. Captured on each FOREGROUND handshake. + private volatile boolean serverRollbackEnabled; + // Strict transactional mode (transaction=strict, or auto_flush=off on this + // transport): implies transactional, never lets an open transaction commit in + // parts, and close() discards instead of committing. See setStrictTransactional. + private boolean strictTransactional; + // Set once the open transaction can no longer be rolled back or committed as + // one: rollback()/reset() could not undo frames already sent because the + // server does not support rollback. Every later flush throws, and close() + // discards; only closing the sender ends this state. + private boolean txnAborted; + // Strict mode only: set when the client buffer cannot take another deferred + // frame of the open transaction and still commit it. Rejects further rows + // until flush() or rollback() ends the transaction. + private boolean txnBufferFull; + // Strict mode only: simulation of how the ring packs the open transaction's + // frames, mirroring MmapSegment's append rule. txnSimSegments counts the + // segments the transaction's frames occupy (0 = no frame yet) and + // txnSimRemaining is the raw space left in the last of them. + private long txnSimRemaining; + private int txnSimSegments; + // Tables with rows in deferred frames of the open transaction, so a commit + // or rollback resets only those tables' counters. Producer thread only. + private final ObjList txnTables = new ObjList<>(); + // Logs the reset()-cannot-roll-back warning once per sender. + private boolean isResetRollbackWarned; + // Strict mode only: payload bytes of the open transaction's frames on the + // ring, for the error message. Reset with the transaction. + private long txnBytes; + // Scratch for ensureStrictTransactionRoom: the frame sizes a flush will + // publish. Producer thread only. + private final IntList strictFrameSizes = new IntList(); private QwpWebSocketSender( List endpoints, @@ -703,11 +768,12 @@ private QwpWebSocketSender( this.closed = false; this.autoFlushRows = autoFlushRows; this.autoFlushBytes = autoFlushBytes; - // Until the handshake completes, honor the configured budget verbatim. - // applyServerBatchSizeLimit() clamps this on connect once the server's - // X-QWP-Max-Batch-Size is known. - this.effectiveAutoFlushBytes = autoFlushBytes; this.autoFlushIntervalNanos = autoFlushIntervalNanos; + // Until the handshake completes, size the byte trigger without a server + // cap. applyServerBatchSizeLimit() re-sizes it on connect once the + // server's X-QWP-Max-Batch-Size is known, and setCursorEngine() once the + // segment size is. + recomputeFrameBudget(); this.globalSymbolDictionary = new GlobalSymbolDictionary(); int microbatchBufferSize = Math.max(DEFAULT_MICROBATCH_BUFFER_SIZE, autoFlushBytes * 2); @@ -1795,29 +1861,51 @@ private void close0(boolean[] restoreInterrupt) { // sender to discard the batch, so honour that: // discard it, remember the error, and let the rest of // close() run. rethrowTerminal below still surfaces it. - try { - flushPendingRows(deferCommit); - } catch (BatchTooLargeForCapException e) { - resetTableBuffersAfterFlush(); - terminalError = captureCloseError(terminalError, e); - } catch (Throwable t) { - // Same reasoning as the pre-flight rejection above, for the - // failures a size check cannot see: sealAndSwapBuffer's - // buffer-recycle timeout and appendBlocking's backpressure - // deadline. Letting those escape to the outer catch skipped - // sendCommitMessage, sealAndSwapBuffer and drainOnClose -- so a - // flush that had already published deferred dictionary chunks - // left their group open forever, and every row an EARLIER - // successful flush published was abandoned unacked. The batch is - // NOT discarded here (unlike the over-cap case, this failure is - // not a verdict on the batch's contents), but the rest of close() - // must still run. rethrowTerminal below surfaces it. - terminalError = captureCloseError(terminalError, t); - } - if (!deferCommit && hasDeferredMessages) { - sendCommitMessage(); + if (strictTransactional || txnAborted) { + // A strict transaction commits only on an explicit flush(), so + // closing without one discards it, and an aborted one must never + // commit. The pending rows never left the client. The frames of + // the open transaction already sent stay uncommitted: a server + // with rollback support discards them on the rollback frame, whose + // ack the drain below waits for; any other server rolls them back + // when the connection closes, and a recovered slot retires them + // as an aborted transaction. + discardPendingRows(); + if (hasDeferredMessages && serverRollbackEnabled && !txnAborted) { + try { + publishRollbackFrame(); + hasDeferredMessages = false; + lastCommitBoundaryFsn = cursorEngine.publishedFsn(); + clearTransactionState(); + } catch (Throwable t) { + terminalError = captureCloseError(terminalError, t); + } + } + } else { + try { + flushPendingRows(deferCommit); + } catch (BatchTooLargeForCapException e) { + resetTableBuffersAfterFlush(); + terminalError = captureCloseError(terminalError, e); + } catch (Throwable t) { + // Same reasoning as the pre-flight rejection above, for the + // failures a size check cannot see: sealAndSwapBuffer's + // buffer-recycle timeout and appendBlocking's backpressure + // deadline. Letting those escape to the outer catch skipped + // sendCommitMessage, sealAndSwapBuffer and drainOnClose -- so a + // flush that had already published deferred dictionary chunks + // left their group open forever, and every row an EARLIER + // successful flush published was abandoned unacked. The batch is + // NOT discarded here (unlike the over-cap case, this failure is + // not a verdict on the batch's contents), but the rest of close() + // must still run. rethrowTerminal below surfaces it. + terminalError = captureCloseError(terminalError, t); + } + if (!deferCommit && hasDeferredMessages) { + sendCommitMessage(); + } } - if (activeBuffer != null && activeBuffer.hasData()) { + if (!strictTransactional && !txnAborted && activeBuffer != null && activeBuffer.hasData()) { sealAndSwapBuffer(); if (!deferCommit) { lastCommitBoundaryFsn = cursorEngine.publishedFsn(); @@ -2272,6 +2360,11 @@ public void flush() { public long flushAndGetSequence() { checkNotClosed(); checkRecycleFailure(); + if (txnAborted) { + // Committing now would commit the frames a failed rollback left on + // the server together with whatever came after them. + throw transactionAbortedError(); + } if (cursorEngine != null) { cursorEngine.checkDurability(); } @@ -2618,7 +2711,16 @@ public SenderError getLastTerminalError() { * @return the global symbol ID */ public int getOrAddGlobalSymbol(CharSequence symbol) { + int sizeBefore = globalSymbolDictionary.size(); int globalId = globalSymbolDictionary.getOrAddSymbol(symbol); + if (globalId >= sizeBefore) { + // A new entry: the batch's next frame carries it in the dictionary + // section ([len varint][utf8]), which the column bytes behind + // pendingBytes do not count. Without this a batch of new long symbols + // could pass the byte trigger and still outgrow the frame cap. + int len = NativeBufferWriter.utf8Length(symbol); + pendingSymbolDictBytes += NativeBufferWriter.varintSize(len) + len; + } if (globalId > currentBatchMaxSymbolId) { currentBatchMaxSymbolId = globalId; } @@ -2687,6 +2789,37 @@ public int getServerMaxBatchSize() { return serverMaxBatchSize; } + /** + * The server's per-table {@code qwp.max.uncommitted.rows} from the last + * foreground handshake ({@code X-QWP-Max-Uncommitted-Rows}), or 0 when the + * server did not advertise it. + */ + public long getServerMaxUncommittedRows() { + return serverMaxUncommittedRows; + } + + /** + * True when the server of the last foreground handshake confirmed QWP + * rollback support, so {@link #rollback()} can discard frames already sent. + */ + public boolean isServerRollbackEnabled() { + return serverRollbackEnabled; + } + + /** + * True in strict transactional mode; see {@link #setStrictTransactional(boolean)}. + */ + public boolean isStrictTransactional() { + return strictTransactional; + } + + /** + * True in transactional mode (strict or not); see {@link #setTransactional(boolean)}. + */ + public boolean isTransactional() { + return transactional; + } + /** Resolved value of {@code symbol_dict_reset_max_wait_millis}. */ @TestOnly public long getSymbolDictResetMaxWaitMillis() { @@ -3250,9 +3383,91 @@ public void setCloseStartedHook(Runnable hook) { this.closeStartedHook = hook; } + /** + * Discards the rows buffered since the last flush, like before. In + * transactional mode it also discards the open transaction's frames already + * sent, when the server supports QWP rollback (see {@link #rollback()}). + * Without that support a strict transaction is aborted -- the next flush + * throws and only closing the sender ends it -- while a non-strict one keeps + * the frames already sent, and the next flush commits them, as before. + */ @Override public void reset() { checkNotClosed(); + discardPendingRows(); + if (transactional && hasDeferredMessages && !txnAborted) { + if (serverRollbackEnabled) { + rollbackOpenTransaction(); + } else if (strictTransactional) { + txnAborted = true; + } else if (!isResetRollbackWarned) { + isResetRollbackWarned = true; + LOG.warn("reset() discarded the rows not yet sent, but the server does not support QWP " + + "rollback, so the open transaction's rows already sent stay on the server and the " + + "next flush() commits them. Close the sender to discard them instead"); + } + } + } + + /** + * Discards the open transaction: the rows buffered since the last flush, + * and the transaction's frames already sent, which the server rolls back on + * the rollback control frame. Blocks until the server acknowledges the + * rollback. Without an open transaction this only discards the buffered + * rows. + * + * @throws LineSenderException when frames of the open transaction were already + * sent and the server does not support QWP rollback + * (the transaction is then aborted: the next flush + * throws, and only closing the sender ends it), or + * when the server does not acknowledge the rollback + * in time + */ + @Override + public void rollback() { + checkNotClosed(); + checkRecycleFailure(); + discardPendingRows(); + if (txnAborted) { + throw transactionAbortedError(); + } + if (!hasDeferredMessages) { + clearTransactionState(); + return; + } + if (!serverRollbackEnabled) { + txnAborted = true; + throw transactionAbortedError(); + } + rollbackOpenTransaction(); + } + + /** + * Pool hook for a strict-mode lease being returned: discards what the + * borrower left uncommitted, so the next borrower starts with no open + * transaction. Returns {@code false} when frames already sent could not be + * rolled back -- the server does not support QWP rollback, or the transaction + * was already aborted -- and the pool must retire the connection instead; the + * server rolls those frames back when the connection closes. + */ + public boolean discardTransactionForReuse() { + checkNotClosed(); + discardPendingRows(); + if (txnAborted) { + return false; + } + if (!hasDeferredMessages) { + clearTransactionState(); + return true; + } + if (!serverRollbackEnabled) { + return false; + } + rollbackOpenTransaction(); + return true; + } + + private void discardPendingRows() { // Reset ALL table buffers, not just the current one ObjList keys = tableBuffers.keys(); for (int i = 0, n = keys.size(); i < n; i++) { @@ -3273,6 +3488,7 @@ public void reset() { currentBatchMaxSymbolId = -1; reclaimUnsentSymbolIds(); pendingBytes = 0; + pendingSymbolDictBytes = 0; pendingRowCount = 0; firstPendingRowTimeNanos = 0; currentTableBuffer = null; @@ -3282,6 +3498,58 @@ public void reset() { cachedTimestampNanosColumn = null; } + /** + * Publishes the rollback control frame behind the open transaction's + * frames: a bare header the server answers by rolling back every row this + * connection holds uncommitted. Sent only to a server that confirmed + * X-QWP-Rollback. + */ + private void publishRollbackFrame() { + int messageSize = encoder.encodeRollbackMessage(); + QwpBufferWriter buffer = encoder.getBuffer(); + ensureActiveBufferReady(); + activeBuffer.ensureCapacity(messageSize); + activeBuffer.write(buffer.getBufferPtr(), messageSize); + activeBuffer.incrementRowCount(); + sealAndSwapBuffer(); + } + + /** + * Rolls back the open transaction on the server and waits for the ack. + *

+ * The wait is what makes the rollback safe across reconnects. Until the + * server acknowledges the rollback frame, a reconnect replays the + * transaction's frames together with it, and a server reached by failover + * that does not support rollback would keep those frames for the next + * commit. Once acknowledged, the frames are trimmed and can never be + * replayed. A rollback that is not acknowledged in time aborts the + * transaction (see {@link #txnAborted}). + */ + private void rollbackOpenTransaction() { + long previousBoundaryFsn = lastCommitBoundaryFsn; + publishRollbackFrame(); + long rollbackFsn = cursorEngine.publishedFsn(); + hasDeferredMessages = false; + // The rollback frame gets an OK ack covering the transaction's frames, so + // close-time drains may wait for it like for a commit. + lastCommitBoundaryFsn = rollbackFsn; + clearTransactionState(); + boolean isAcked = false; + try { + isAcked = awaitAckedFsn(fsnEpochBase + rollbackFsn, rollbackAckTimeoutMillis); + } finally { + if (!isAcked) { + txnAborted = true; + lastCommitBoundaryFsn = previousBoundaryFsn; + } + } + if (!isAcked) { + throw new LineSenderException("rollback not acknowledged by the server [timeoutMillis=") + .put(rollbackAckTimeoutMillis) + .put("]; the transaction is aborted: close the sender to discard it"); + } + } + /** * Advisory request to start a fresh symbol-dictionary epoch. Sets * {@link #manualResetRequested}; if no flush is in flight @@ -3400,6 +3668,8 @@ public void setCursorEngine(CursorSendEngine engine, boolean takeOwnership) { engine.adoptCounters(counters); engine.setSlotLockReleaseListener(this::onSlotLockReleased); } + // The segment size bounds every frame; re-size the byte trigger for it. + recomputeFrameBudget(); } /** @@ -3549,8 +3819,40 @@ public void setRecycleDeferredCloseMaxWaitMillisForTesting(long millis) { this.recycleDeferredCloseMaxWaitMillis = millis; } + @TestOnly + public void setRollbackAckTimeoutMillisForTesting(long millis) { + this.rollbackAckTimeoutMillis = millis; + } + + /** + * Strict transactional mode: auto-flush ships rows as FLAG_DEFER_COMMIT frames + * like {@link #setTransactional(boolean) transactional} mode, only an explicit + * flush commits, and the open transaction never commits in parts. A row that + * would push a table past the server's {@code qwp.max.uncommitted.rows}, or a + * frame the client buffer could not hold alongside the commit, throws + * {@link TransactionTooLargeException} instead. {@link #close()} discards an + * uncommitted transaction rather than committing it. Enabling it enables + * transactional mode; disabling it leaves transactional mode on. + */ + public void setStrictTransactional(boolean strict) { + this.strictTransactional = strict; + if (strict) { + this.transactional = true; + } + recomputeFrameBudget(); + } + + /** + * Transactional mode: auto-flush ships rows as FLAG_DEFER_COMMIT frames and + * only an explicit flush (or close) commits. Disabling it also disables + * {@link #setStrictTransactional(boolean) strict} mode. + */ public void setTransactional(boolean transactional) { this.transactional = transactional; + if (!transactional) { + this.strictTransactional = false; + } + recomputeFrameBudget(); } /** @@ -3886,44 +4188,30 @@ private static List singleEndpoint(String host, int port) { } /** - * Clamps the soft-flush byte budget to fit under the server's advertised - * X-QWP-Max-Batch-Size minus a safety margin for encoding overhead - * (schema, dict deltas, framing). A 0 advertisement means the server did - * not send the header (older build) and the configured budget is kept - * verbatim. Called on every successful connect because a rolling upgrade - * can leave neighbouring endpoints with different caps. + * Records the server's advertised X-QWP-Max-Batch-Size and re-sizes the + * byte trigger from it. A 0 advertisement means the server did not send + * the header (older build). Called on every successful connect because a + * rolling upgrade can leave neighbouring endpoints with different caps. *

- * Always updates {@link #serverMaxBatchSize} so the single-row hard guard - * in {@link #sendRow} fires against the freshly advertised value. The - * byte trigger, however, is only adjusted when the user left it enabled: - * an explicit {@code auto_flush_bytes=off} (autoFlushBytes == 0) is - * preserved even when the server advertises a cap, so applications that - * opted out keep the contract they asked for. + * Always updates {@link #serverMaxBatchSize}, so the single-row guard in + * {@link #sendRow} fires against the freshly advertised value. See + * {@link #recomputeFrameBudget()} for the byte trigger. */ @TestOnly public void applyServerBatchSizeLimit(int advertisedMaxBatchSize) { serverMaxBatchSize = advertisedMaxBatchSize; - if (autoFlushBytes <= 0) { - // User opted out of byte-based auto-flush; respect that even when - // the server advertises a cap. The single-row guard still protects - // against oversize individual rows via serverMaxBatchSize. - effectiveAutoFlushBytes = 0; - return; - } - if (advertisedMaxBatchSize <= 0) { - effectiveAutoFlushBytes = autoFlushBytes; - return; - } - // Cap at 90% of the server's hard limit. Raw column-buffer bytes are - // a conservative proxy for wire size (compression usually shrinks the - // payload), but schema and dict-delta overhead can push the wire size - // above the raw total in pathological cases. - long safeBudget = (long) advertisedMaxBatchSize * 9 / 10; - if (autoFlushBytes < safeBudget) { - effectiveAutoFlushBytes = autoFlushBytes; - } else { - effectiveAutoFlushBytes = (int) safeBudget; - } + recomputeFrameBudget(); + } + + /** + * Records the transaction limits the server advertised on the last + * foreground handshake: its per-table {@code qwp.max.uncommitted.rows} + * ({@code 0} when not advertised) and whether it confirmed rollback support. + */ + @TestOnly + public void applyServerTransactionLimits(long maxUncommittedRows, boolean rollbackEnabled) { + serverMaxUncommittedRows = maxUncommittedRows; + serverRollbackEnabled = rollbackEnabled; } private void atMicros(long timestampMicros) { @@ -4256,6 +4544,9 @@ private WebSocketClient connectWalk(ReconnectSupplier ctx, CursorWebSocketSendLo newClient.setQwpMaxVersion(QwpConstants.VERSION); newClient.setQwpClientId(QwpConstants.CLIENT_ID); newClient.setQwpDurableAckTiers(durableAckTiers); + // Ask every server whether it accepts the rollback control frame; + // only one that confirms ever receives it. + newClient.setQwpRequestRollback(true); newClient.setConnectTimeout(effectiveConnectTimeoutMs(background, connectTimeoutMs)); if (cancellation != null) { // Publish the client we are about to block on so a @@ -4460,6 +4751,8 @@ private WebSocketClient connectWalk(ReconnectSupplier ctx, CursorWebSocketSendLo // endpoint's cap; an oversize row then escapes the producer-side // guard and trips a wire-level ws-close[1009] downstream. applyServerBatchSizeLimit(newClient.getServerMaxBatchSize()); + applyServerTransactionLimits( + newClient.getServerMaxUncommittedRows(), newClient.isServerRollbackEnabled()); return newClient; } catch (Error e) { closeQuietlyOnError(newClient); @@ -5202,6 +5495,7 @@ private void flushPendingRows(boolean deferCommit) { if (tableCount == 0) { clearPendingTables(); pendingBytes = 0; + pendingSymbolDictBytes = 0; currentTableBufferSnapshotBytes = currentTableBuffer == null ? 0 : currentTableBuffer.getBufferedBytes(); pendingRowCount = 0; @@ -5233,6 +5527,13 @@ private void flushPendingRows(boolean deferCommit) { int combinedBodyStart = encodeCombinedFrame(tableCount, deferCommit, deltaBaseline); int messageSize = encoder.finishMessage(); + // A strict transaction must be able to commit as one: refuse, before any + // frame of this flush reaches the ring, a flush the client buffer could not + // hold together with the commit that has to follow it. + if (strictTransactional && cursorEngine != null) { + ensureStrictTransactionRoom(cap, deltaBaseline, messageSize, deferCommit); + } + // Full-dict over-cap fallback. A full-dictionary frame carries the whole // dictionary from id 0, so its fixed overhead grows with lifetime symbol // cardinality: eventually the section alone fills the cap, and before that @@ -5302,6 +5603,7 @@ && splitFramesFit(cap, currentBatchMaxSymbolId)) { if (!deferCommit) { lastCommitBoundaryFsn = cursorEngine.publishedFsn(); } + accountTransactionRows(deferCommit); resetTableBuffersAfterFlush(); } catch (Throwable t) { @@ -5531,6 +5833,7 @@ private void flushPendingRowsSplit( // committed the whole group. lastCommitBoundaryFsn = cursorEngine.publishedFsn(); } + accountTransactionRows(deferCommit); resetTableBuffersAfterFlush(); } @@ -5554,6 +5857,7 @@ private void resetTableBuffersAfterFlush() { flushTableBuffers.setPos(0); currentBatchMaxSymbolId = -1; pendingBytes = 0; + pendingSymbolDictBytes = 0; currentTableBufferSnapshotBytes = 0; pendingRowCount = 0; firstPendingRowTimeNanos = 0; @@ -6461,6 +6765,7 @@ private void sendCommitMessage() { sealAndSwapBuffer(); hasDeferredMessages = false; lastCommitBoundaryFsn = cursorEngine.publishedFsn(); + clearTransactionState(); } private SenderErrorHandler userErrorHandler() { @@ -7110,7 +7415,17 @@ private void sealAndSwapBuffer() { // (durable mmap append, returns once published). try { toSend.markSending(); + // Strict mode tracks how the open transaction's frames pack into + // segments; the first frame's placement depends on the active + // segment's room before the append. + boolean isTxnFrame = strictTransactional + && isTransactionFrame(toSend.getBufferPtr(), toSend.getBufferPos()); + long activeRemaining = isTxnFrame && txnSimSegments == 0 + ? cursorEngine.activeSegment().capacityRemaining() : 0; cursorEngine.appendBlocking(toSend.getBufferPtr(), toSend.getBufferPos()); + if (isTxnFrame) { + recordTransactionFrame(toSend.getBufferPos(), activeRemaining); + } toSend.markRecycled(); } catch (Throwable t) { // appendBlocking failed synchronously on the user thread — the @@ -7135,6 +7450,245 @@ private void sealAndSwapBuffer() { } } + /** + * Adds the rows a just-published FLAG_DEFER_COMMIT flush shipped to each + * flushed table's open-transaction count, or forgets the open transaction + * when the flush committed it. + */ + private void accountTransactionRows(boolean deferred) { + if (!deferred) { + clearTransactionState(); + return; + } + for (int i = 0, n = flushTableBuffers.size(); i < n; i++) { + QwpTableBuffer table = flushTableBuffers.getQuick(i); + long sentRows = table.getTxnSentRows(); + if (sentRows == 0) { + txnTables.add(table); + } + table.setTxnSentRows(sentRows + table.getRowCount()); + } + } + + private void checkTransactionAcceptsRow() { + if (txnAborted) { + throw transactionAbortedError(); + } + if (!strictTransactional) { + return; + } + if (txnBufferFull) { + throw new TransactionTooLargeException("transaction too large for the client buffer") + .put(" [transactionBytes=").put(txnBytes) + .put("]; the buffer cannot hold another frame of the open transaction and still " + + "commit it, so the row was not added. Commit the transaction with flush() or " + + "discard it with rollback() before adding rows"); + } + long maxRows = serverMaxUncommittedRows; + if (maxRows <= 0) { + maxRows = QwpConstants.DEFAULT_SERVER_MAX_UNCOMMITTED_ROWS; + } + // The server commits a table on its own once its uncommitted rows reach + // maxRows, so a strict transaction holds at most maxRows - 1 rows per table. + long rows = currentTableBuffer.getTxnSentRows() + currentTableBuffer.getRowCount() + 1; + if (rows >= maxRows) { + throw new TransactionTooLargeException("transaction too large for the server") + .put(" [table=").put(currentTableName) + .put(", rows=").put(rows) + .put(", maxUncommittedRows=").put(maxRows) + .put("]; the server commits a table's rows on its own once qwp.max.uncommitted.rows " + + "of them are uncommitted, which would split the transaction, so the row was " + + "not added. Commit the transaction with flush() or discard it with rollback(), " + + "then send smaller transactions or raise qwp.max.uncommitted.rows on the server"); + } + } + + /** + * Forgets the open transaction: its tables' row counts, the client-buffer + * simulation and the buffer-full latch. Called when a frame commits it or + * the rollback frame discards it; O(tables in the transaction). + */ + private void clearTransactionState() { + for (int i = 0, n = txnTables.size(); i < n; i++) { + txnTables.getQuick(i).setTxnSentRows(0); + } + txnTables.setPos(0); + txnBufferFull = false; + txnBytes = 0; + txnSimSegments = 0; + txnSimRemaining = 0; + } + + /** + * Strict mode: refuses a flush whose frames, together with the open + * transaction's frames already on the ring and (for a deferred flush) room + * for the commit that must follow, would not fit the ring under + * {@code sf_max_total_bytes}. The server acks none of a transaction's frames + * before its commit, so the ring cannot trim them; a transaction that does + * not fit would block its own commit. + *

+ * Mirrors how the ring packs frames: frames never span segments, and a frame + * that does not fit the current segment opens the next one. The flush's + * frame sizes are derived the way flushPendingRows and the split publish + * them; dictionary chunks of the full-dictionary fallback count as full + * frames. Runs before anything of the flush is published, so a refusal + * leaves the batch pending and the ring untouched. + */ + private void ensureStrictTransactionRoom(int cap, int deltaBaseline, int messageSize, boolean deferCommit) { + CursorSendEngine engine = cursorEngine; + long segmentPayload = segmentPayloadCapacity(); + strictFrameSizes.clear(); + if (cap <= 0 || messageSize <= cap) { + strictFrameSizes.add(messageSize); + } else { + int baseline = deltaBaseline; + if (!deltaDictEnabled && currentBatchMaxSymbolId > deltaBaseline + && !splitFramesFit(cap, deltaBaseline) + && splitFramesFit(cap, currentBatchMaxSymbolId)) { + // The full-dictionary fallback ships the section as chunks of at + // most cap bytes ahead of the table frames. + long dictBytes = encoder.getSplitMessageSize(0, deltaBaseline, currentBatchMaxSymbolId) + - QwpConstants.HEADER_SIZE; + long chunkPayload = Math.max(1, cap - QwpConstants.HEADER_SIZE - 16); + for (long chunks = dictBytes / chunkPayload + 1; chunks > 0; chunks--) { + strictFrameSizes.add(cap); + } + baseline = currentBatchMaxSymbolId; + } + for (int i = 0, n = splitFrameBodyBytes.size(); i < n; i++) { + strictFrameSizes.add(encoder.getSplitMessageSize( + splitFrameBodyBytes.getQuick(i), baseline, currentBatchMaxSymbolId)); + if (deltaDictEnabled && currentBatchMaxSymbolId > baseline) { + baseline = currentBatchMaxSymbolId; + } + } + } + int segments = txnSimSegments; + long remaining = segments == 0 ? engine.activeSegment().capacityRemaining() : txnSimRemaining; + long bytes = txnBytes; + for (int i = 0, n = strictFrameSizes.size(); i < n; i++) { + long size = strictFrameSizes.getQuick(i); + bytes += size; + if (segments == 0 || size > remaining) { + if (segments > 0 || size > remaining) { + remaining = segmentPayload; + } + segments++; + } + remaining = Math.max(0, remaining - size - MmapSegment.FRAME_HEADER_SIZE); + } + if (deferCommit) { + // Keep room for the commit: the rows pending when this transaction + // ends are at most a frame's worth plus one row, which a split + // ships as a few frames of at most cap bytes. + long reserve = cap > 0 ? Math.min(cap, segmentPayload) : segmentPayload; + for (int i = 0; i < STRICT_COMMIT_RESERVE_FRAMES; i++) { + if (reserve > remaining) { + remaining = segmentPayload; + segments++; + } + remaining = Math.max(0, remaining - reserve - MmapSegment.FRAME_HEADER_SIZE); + } + } + long ringCapacity = engine.ringCapacityBytes(); + long maxSegments = Math.max(2, ringCapacity / engine.segmentSizeBytes()); + if (segments > maxSegments) { + if (deferCommit) { + txnBufferFull = true; + } + throw new TransactionTooLargeException("transaction too large for the client buffer") + .put(" [transactionBytes=").put(bytes) + .put(", ringCapacityBytes=").put(ringCapacity) + .put(", segmentBytes=").put(engine.segmentSizeBytes()) + .put("]; the client holds an uncommitted transaction until the server commits it, so " + + "the transaction must fit sf_max_total_bytes. This flush was not sent: commit " + + "the transaction with flush() or discard it with rollback(), then send smaller " + + "transactions, raise sf_max_total_bytes, or set sf_dir to keep it on disk"); + } + } + + /** + * True for a QWP frame that joins the open transaction: FLAG_DEFER_COMMIT + * set, and not the rollback control frame (which also carries the flag). + */ + private static boolean isTransactionFrame(long payloadAddr, int payloadLen) { + if (payloadLen < QwpConstants.HEADER_SIZE + || Unsafe.getUnsafe().getInt(payloadAddr) != QwpConstants.MAGIC_MESSAGE) { + return false; + } + byte flags = Unsafe.getUnsafe().getByte(payloadAddr + QwpConstants.HEADER_OFFSET_FLAGS); + return (flags & QwpConstants.FLAG_DEFER_COMMIT) != 0 && (flags & QwpConstants.FLAG_ROLLBACK) == 0; + } + + /** + * Re-sizes the byte trigger {@link #effectiveAutoFlushBytes} from the frame + * size the connection can carry: the smaller of the advertised + * X-QWP-Max-Batch-Size and the payload a store-and-forward segment can hold. + *

+ */ + private void recomputeFrameBudget() { + long segmentPayload = segmentPayloadCapacity(); + int advertised = serverMaxBatchSize; + long frameSize = Math.min(advertised > 0 ? advertised : FALLBACK_SERVER_MAX_BATCH_SIZE, segmentPayload); + long budget = frameSize * 9 / 10; + if (autoFlushBytes > 0) { + long limit = advertised > 0 ? budget + : (segmentPayload == Long.MAX_VALUE ? Long.MAX_VALUE : segmentPayload * 9 / 10); + effectiveAutoFlushBytes = (int) Math.min(autoFlushBytes, limit); + } else if (autoFlushBytes == AUTO_FLUSH_BYTES_AUTO + && (transactional || autoFlushRows > 0 || autoFlushIntervalNanos > 0)) { + effectiveAutoFlushBytes = (int) budget; + } else { + effectiveAutoFlushBytes = 0; + } + } + + /** + * Strict mode: advances the client-buffer simulation by one open-transaction + * frame that just reached the ring. {@code activeRemaining} is the active + * segment's room before the append, needed for the transaction's first frame. + */ + private void recordTransactionFrame(int payloadLen, long activeRemaining) { + txnBytes += payloadLen; + if (txnSimSegments == 0) { + txnSimRemaining = payloadLen > activeRemaining ? segmentPayloadCapacity() : activeRemaining; + txnSimSegments = 1; + } else if (payloadLen > txnSimRemaining) { + txnSimRemaining = segmentPayloadCapacity(); + txnSimSegments++; + } + txnSimRemaining = Math.max(0, txnSimRemaining - payloadLen - MmapSegment.FRAME_HEADER_SIZE); + } + + /** + * Largest frame payload a store-and-forward segment can hold, or + * {@link Long#MAX_VALUE} before an engine is attached. + */ + private long segmentPayloadCapacity() { + CursorSendEngine engine = cursorEngine; + return engine == null + ? Long.MAX_VALUE + : engine.segmentSizeBytes() - MmapSegment.HEADER_SIZE - MmapSegment.FRAME_HEADER_SIZE; + } + + private LineSenderException transactionAbortedError() { + return new LineSenderException("transaction aborted: rollback could not undo the frames of the " + + "open transaction already sent, because the server does not support QWP rollback. Close " + + "the sender to discard them; the server rolls them back when the connection closes"); + } + /** * Accumulates the current row. * Rows buffer until flush (explicit or auto-flush). @@ -7142,6 +7696,12 @@ private void sealAndSwapBuffer() { private void sendRow() { checkRecycleFailure(); ensureConnected(); + if (transactional) { + // Before nextRow(): a refusal leaves the row uncommitted, so the + // at()/atNow() error path discards it and the transaction keeps the + // rows accepted before it. + checkTransactionAcceptsRow(); + } // Hard guard: a single row whose bytes exceed the server's wire cap // would flush as an oversize WS frame the server closes with @@ -7193,7 +7753,7 @@ private boolean shouldAutoFlush() { if (autoFlushRows > 0 && pendingRowCount >= autoFlushRows) { return true; } - if (effectiveAutoFlushBytes > 0 && getPendingBytes() >= effectiveAutoFlushBytes) { + if (effectiveAutoFlushBytes > 0 && pendingBytes + pendingSymbolDictBytes >= effectiveAutoFlushBytes) { return true; } // pendingRowCount == 1: sendRow() just timestamped this very row, so its diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java new file mode 100644 index 000000000..4374b7337 --- /dev/null +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java @@ -0,0 +1,49 @@ +/*+***************************************************************************** + * ___ _ ____ ____ + * / _ \ _ _ ___ ___| |_| _ \| __ ) + * | | | | | | |/ _ \/ __| __| | | | _ \ + * | |_| | |_| | __/\__ \ |_| |_| | |_) | + * \__\_\\__,_|\___||___/\__|____/|____/ + * + * 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.cutlass.qwp.client; + +import io.questdb.client.cutlass.line.LineSenderException; + +/** + * A strict transaction ({@code transaction=strict} or {@code auto_flush=off} on the + * WebSocket transport) grew past a limit that would stop it from committing as one + * transaction: the server's per-table {@code qwp.max.uncommitted.rows}, past which + * the server commits the rows on its own, or the client's {@code sf_max_total_bytes}, + * which must hold the whole uncommitted transaction until the server commits it. + *

+ * Thrown before anything that would cross the limit reaches the server, and the + * transaction stays open: the caller can still commit the rows accepted so far + * with {@code flush()}, or discard them with {@code rollback()}. A row rejected at + * the per-table limit is not part of the transaction. When the client buffer is + * the limit, the row being added when the buffer filled up stays in the + * transaction, and every further row is rejected until {@code flush()} or + * {@code rollback()} ends the transaction. + */ +public class TransactionTooLargeException extends LineSenderException { + + public TransactionTooLargeException(CharSequence message) { + super(message); + } +} diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorSendEngine.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorSendEngine.java index ba46365af..16d9296de 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorSendEngine.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorSendEngine.java @@ -1900,6 +1900,17 @@ public int sealedSegmentsSnapshot(MmapSegment[] target) { return ring.snapshotSealedSegments(target); } + /** + * Bytes of segments the ring may hold under {@code sf_max_total_bytes}: the + * budget's capacity minus the side-file bytes it also charges (disk mode). + * In a sender pool the budget is shared, so this bounds the rings of all + * pooled senders together, not this ring alone. + */ + public long ringCapacityBytes() { + SegmentBudget budget = manager.getBudget(); + return budget.getCapacityBytes() - budget.getSideFileBytes(); + } + /** * Configured per-segment size in bytes. */ diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentManager.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentManager.java index 7d3f5f56d..ba4000168 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentManager.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentManager.java @@ -472,6 +472,14 @@ public synchronized boolean isWorkerReaped() { return workerThread == null; } + /** + * The {@code sf_max_total_bytes} budget this manager charges its rings' + * segments to; shared with other managers in a sender pool. + */ + public SegmentBudget getBudget() { + return budget; + } + /** * Stop tracking {@code ring}. Idempotent; safe to call from any thread. *

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..ba1ee0e5f 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 @@ -36,6 +36,13 @@ public final class QwpConstants { * Client identifier sent in the X-QWP-Client-Id upgrade header. */ public static final String CLIENT_ID = "java/1.0.2"; + /** + * Default of the server's {@code qwp.max.uncommitted.rows}: the per-table + * count of rows a deferred-commit group may hold before the server commits + * them on its own. A strict transaction assumes this value when the server + * does not advertise {@code X-QWP-Max-Uncommitted-Rows}. + */ + public static final long DEFAULT_SERVER_MAX_UNCOMMITTED_ROWS = 1_000_000L; /** * Flag bit: defer WAL commit. The server appends rows to WAL writers * but skips the commit until a subsequent message without this flag. @@ -50,6 +57,12 @@ public final class QwpConstants { * Flag bit: Gorilla timestamp encoding enabled. */ public static final byte FLAG_GORILLA = 0x04; + /** + * Flag bit: roll back the connection's open deferred-commit group. Only ever + * set on the rollback control frame (see {@link #ROLLBACK_FRAME_FLAGS}), which + * the client sends only after the server confirmed {@code X-QWP-Rollback}. + */ + public static final byte FLAG_ROLLBACK = 0x20; /** * Flag bit: payload region after the prelude is zstd-compressed. Set only * when the handshake negotiated zstd compression. Mirror of the server-side @@ -108,6 +121,13 @@ public final class QwpConstants { * constant; used by the decoder to reject malformed wire bytes. */ public static final int MAX_TABLE_NAME_LENGTH = 127; + /** + * Flags byte of the rollback control frame: a bare 12-byte header with no + * table blocks and no payload. It carries {@link #FLAG_DEFER_COMMIT} too, so a + * server that does not know {@link #FLAG_ROLLBACK} treats it as an empty + * deferred frame instead of a commit. + */ + public static final byte ROLLBACK_FRAME_FLAGS = FLAG_ROLLBACK | FLAG_DEFER_COMMIT; /** * Status byte on a {@code QUERY_ERROR} frame: the query was cancelled, * either by a client {@code CANCEL} frame or by explicit server-side diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpTableBuffer.java b/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpTableBuffer.java index 02f95b914..7e7ce99b6 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpTableBuffer.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpTableBuffer.java @@ -78,6 +78,9 @@ public class QwpTableBuffer implements QuietCloseable { // buffer is listed once. Producer thread only. private boolean listedPending; private int rowCount; + // Rows of this table the sender already shipped in FLAG_DEFER_COMMIT frames + // of the open transaction. Producer thread only. + private long txnSentRows; public QwpTableBuffer(String tableName) { this(tableName, null); @@ -282,6 +285,14 @@ public String getTableName() { return tableName; } + /** + * Rows of this table already shipped in FLAG_DEFER_COMMIT frames of the + * sender's open transaction; 0 outside a transaction. + */ + public long getTxnSentRows() { + return txnSentRows; + } + /** * Returns true if a row is partially built (columns written but not yet committed * via {@link #nextRow()}). @@ -426,6 +437,13 @@ public void setListedPending(boolean listedPending) { this.listedPending = listedPending; } + /** + * Sets the count reported by {@link #getTxnSentRows()}. + */ + public void setTxnSentRows(long txnSentRows) { + this.txnSentRows = txnSentRows; + } + private static void assertColumnType(CharSequence name, byte type, ColumnBuffer column) { if (column.type != type) { throw new LineSenderException( diff --git a/core/src/main/java/io/questdb/client/impl/PooledSender.java b/core/src/main/java/io/questdb/client/impl/PooledSender.java index a9ef418af..1c49b3099 100644 --- a/core/src/main/java/io/questdb/client/impl/PooledSender.java +++ b/core/src/main/java/io/questdb/client/impl/PooledSender.java @@ -28,6 +28,7 @@ import io.questdb.client.Sender; import io.questdb.client.cutlass.line.array.DoubleArray; import io.questdb.client.cutlass.line.array.LongArray; +import io.questdb.client.cutlass.qwp.client.QwpWebSocketSender; import io.questdb.client.std.Decimal128; import io.questdb.client.std.Decimal256; import io.questdb.client.std.Decimal64; @@ -167,8 +168,18 @@ public void close() { // above. A stale duplicate throws here, and the finally routes it // to discardBroken, which drops it on the same stale-generation // check under the pool lock. - slot.live(generation).flush(); - flushed = true; + Sender live = slot.live(generation); + if (live instanceof QwpWebSocketSender && ((QwpWebSocketSender) live).isStrictTransactional()) { + // A strict transaction commits only on an explicit flush(), so + // returning the lease discards whatever the borrower left open. + // The next borrower must not inherit it, so a transaction the + // server cannot roll back retires the connection instead (the + // server rolls it back when the connection closes). + flushed = ((QwpWebSocketSender) live).discardTransactionForReuse(); + } else { + live.flush(); + flushed = true; + } } finally { if (flushed) { slot.pool().giveBack(this); @@ -341,6 +352,11 @@ public void reset() { slot.live(generation).reset(); } + @Override + public void rollback() { + slot.live(generation).rollback(); + } + @Override public void resetSymbolDictionary() { slot.live(generation).resetSymbolDictionary(); diff --git a/core/src/test/java/io/questdb/client/test/QuestDBBuilderTest.java b/core/src/test/java/io/questdb/client/test/QuestDBBuilderTest.java index e304df951..4dc06fcd6 100644 --- a/core/src/test/java/io/questdb/client/test/QuestDBBuilderTest.java +++ b/core/src/test/java/io/questdb/client/test/QuestDBBuilderTest.java @@ -229,18 +229,16 @@ public void testMalformedIngressConfigRejectedAtBuildWithMinZero() { // Sender -- yet it must still reject a malformed ingress key in the // single cluster config up front. Covers a typed enum (tls_verify), a // registry-STRING value that only the real Sender parse validates - // (auto_flush_rows), and WebSocket build-time checks: auto_flush=off disables - // auto-flush (unsupported on WebSocket), also when auto_flush_bytes is set, and + // (auto_flush_rows), and WebSocket build-time checks: auto_flush=off selects + // strict transactional mode, so it cannot combine with transaction=off, and // sf_durability=flush is not yet supported. assertBuildRejected( "wss::addr=127.0.0.1:1;tls_verify=strict;sender_pool_min=0;query_pool_min=0;", "tls_verify"); assertBuildRejected( "ws::addr=127.0.0.1:1;auto_flush_rows=abc;sender_pool_min=0;query_pool_min=0;", "auto_flush_rows"); assertBuildRejected( - "ws::addr=127.0.0.1:1;auto_flush=off;sender_pool_min=0;query_pool_min=0;", "auto-flush"); - assertBuildRejected( - "ws::addr=127.0.0.1:1;auto_flush=off;auto_flush_bytes=65536;sender_pool_min=0;query_pool_min=0;", - "auto-flush"); + "ws::addr=127.0.0.1:1;auto_flush=off;transaction=off;sender_pool_min=0;query_pool_min=0;", + "auto_flush=off selects strict transactional mode"); assertBuildRejected( "ws::addr=127.0.0.1:1;sf_durability=flush;sender_pool_min=0;query_pool_min=0;", "not yet supported"); } diff --git a/core/src/test/java/io/questdb/client/test/cutlass/http/client/WebSocketClientTest.java b/core/src/test/java/io/questdb/client/test/cutlass/http/client/WebSocketClientTest.java index cc8c78aa4..fdde0e563 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/http/client/WebSocketClientTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/http/client/WebSocketClientTest.java @@ -189,6 +189,32 @@ public void testExtractMaxBatchSizeParsesPositive() throws Exception { Assert.assertEquals(16 * 1024 * 1024, invokeExtractMaxBatchSize(response)); } + @Test + public void testExtractMaxUncommittedRowsAbsentHeaderReturnsZero() throws Exception { + String response = "HTTP/1.1 101 Switching Protocols\r\n" + + "X-QWP-Version: 1\r\n" + + "X-QWP-Max-Batch-Size: 16777216\r\n" + + "\r\n"; + Assert.assertEquals(0, invokeExtractMaxUncommittedRows(response)); + } + + @Test + public void testExtractMaxUncommittedRowsMalformedOrNegativeReturnsZero() throws Exception { + // 0 means "not advertised": a strict transaction then assumes the default. + Assert.assertEquals(0, invokeExtractMaxUncommittedRows("HTTP/1.1 101 Switching Protocols\r\n" + + "X-QWP-Max-Uncommitted-Rows: lots\r\n\r\n")); + Assert.assertEquals(0, invokeExtractMaxUncommittedRows("HTTP/1.1 101 Switching Protocols\r\n" + + "X-QWP-Max-Uncommitted-Rows: -5\r\n\r\n")); + } + + @Test + public void testExtractMaxUncommittedRowsParsesBeyondIntRange() throws Exception { + String response = "HTTP/1.1 101 Switching Protocols\r\n" + + "x-qwp-max-uncommitted-rows: 5000000000 \r\n" + + "\r\n"; + Assert.assertEquals(5_000_000_000L, invokeExtractMaxUncommittedRows(response)); + } + @Test public void testFrameBurstIsParsedInPlace() throws Exception { assertFrameBurstIsParsedInPlace(false); @@ -602,6 +628,12 @@ private static int invokeExtractMaxBatchSize(String response) throws Exception { return (int) m.invoke(null, response); } + private static long invokeExtractMaxUncommittedRows(String response) throws Exception { + Method m = WebSocketClient.class.getDeclaredMethod("extractMaxUncommittedRows", String.class); + m.setAccessible(true); + return (long) m.invoke(null, response); + } + private static void setUpgradedTrue(Object obj) throws Exception { Class clazz = obj.getClass(); while (clazz != null) { diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/DeltaDictRecoveryTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/DeltaDictRecoveryTest.java index fbc833d86..390168fda 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/DeltaDictRecoveryTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/DeltaDictRecoveryTest.java @@ -1052,7 +1052,10 @@ public void testFailedPublishDoesNotDuplicatePersistedSymbols() throws Exception // Small segment; a heavily padded row's frame cannot fit, so // appendBlocking throws PAYLOAD_TOO_LARGE deterministically -- no // backpressure timing needed. The server never acks (SilentHandler). - String cfg = "ws::addr=localhost:" + port + ";sf_dir=" + sfDir + ";sf_max_segment_bytes=1024;"; + // auto_flush_bytes=off: the oversized row must reach flush() whole, + // as the byte trigger would otherwise publish it from at(). + String cfg = "ws::addr=localhost:" + port + ";sf_dir=" + sfDir + + ";sf_max_segment_bytes=1024;auto_flush_bytes=off;"; String pad = TestUtils.repeat("x", 2000); // frame >> 1024-byte segment Sender sender = Sender.fromConfig(cfg); try { @@ -1187,9 +1190,12 @@ public void testRecoveryAfterFailedPublishReplaysGapFree() throws Exception { int port = silent.getPort(); silent.start(); Assert.assertTrue(silent.awaitStart(5, TimeUnit.SECONDS)); + // auto_flush_bytes=off: the oversized row must reach flush() whole, + // as the byte trigger would otherwise publish it from at(). String cfg = "ws::addr=localhost:" + port + ";sf_dir=" + sfDir + ";sf_max_segment_bytes=4096" + + ";auto_flush_bytes=off" + ";close_flush_timeout_millis=0;"; Sender s1 = Sender.fromConfig(cfg); try { diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/LineSenderBuilderWebSocketTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/LineSenderBuilderWebSocketTest.java index 1d83dff2a..0fd081389 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/LineSenderBuilderWebSocketTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/LineSenderBuilderWebSocketTest.java @@ -425,12 +425,15 @@ public void testDefaultIsAsync() { } @Test - public void testDisableAutoFlush_notSupportedForWebSocket() { + public void testDisableAutoFlush_rejectsTransactionOffForWebSocket() { + // On WebSocket, disabling auto-flush selects strict transactional mode, + // which an explicit transactional(false) contradicts. assertThrowsAny( Sender.builder(Sender.Transport.WEBSOCKET) .address(LOCALHOST) - .disableAutoFlush(), - "not supported for WebSocket"); + .disableAutoFlush() + .transactional(false), + "cannot be combined with transaction=off"); } @Test diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java new file mode 100644 index 000000000..4b96c8196 --- /dev/null +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -0,0 +1,759 @@ +/*+***************************************************************************** + * ___ _ ____ ____ + * / _ \ _ _ ___ ___| |_| _ \| __ ) + * | | | | | | |/ _ \/ __| __| | | | _ \ + * | |_| | |_| | __/\__ \ |_| |_| | |_) | + * \__\_\\__,_|\___||___/\__|____/|____/ + * + * 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.QuestDB; +import io.questdb.client.Sender; +import io.questdb.client.cutlass.line.LineSenderException; +import io.questdb.client.cutlass.qwp.client.BatchTooLargeForCapException; +import io.questdb.client.cutlass.qwp.client.QwpWebSocketSender; +import io.questdb.client.cutlass.qwp.client.TransactionTooLargeException; +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.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; + +import static io.questdb.client.test.tools.TestUtils.assertMemoryLeak; + +/** + * Batches of any size over QWP/WebSocket: the byte trigger that keeps every batch + * within one frame, transactional and strict transactional mode, and rollback. + *

+ * {@link TxnServer} answers frames the way the QuestDB server does: a + * FLAG_DEFER_COMMIT frame gets no ack until a commit frame closes its group, a + * commit frame gets a cumulative OK ack, and the rollback control frame gets a + * cumulative OK ack once the server negotiated rollback. + */ +public class QwpLargeTransactionTest { + private static final int CAP = 32 * 1024; + // ~100 encoded bytes per row: 1000 rows (the default row trigger) are ~100 KB, + // three times the 32 KiB cap. + private static final String PAD = TestUtils.repeat("x", 90); + + @Test + public void testAutoFlushOffIsStrictTransactionOfAnySize() throws Exception { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "auto_flush=off;")) { + Assert.assertTrue(((QwpWebSocketSender) s).isStrictTransactional()); + writeRows(s, "t", 0, 2_000); + // ~200 KB went out as deferred frames before flush(); none commits. + Assert.assertTrue(h.awaitFrames(5)); + Assert.assertEquals(0, h.commitFrames()); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + assertFramesWithinCap(h, CAP); + assertOneTransaction(h); + } + }); + } + + @Test + public void testAutoFlushOffRejectsTransactionOff() throws Exception { + assertMemoryLeak(() -> { + try { + Sender.fromConfig("ws::addr=localhost:1;auto_flush=off;transaction=off;").close(); + Assert.fail("auto_flush=off must not combine with transaction=off"); + } catch (LineSenderException e) { + TestUtils.assertContains(e.getMessage(), + "auto_flush=off selects strict transactional mode on WebSocket"); + } + }); + } + + @Test + public void testDefaultSenderSplitsWideRowsIntoFrames() throws Exception { + // Before: no byte trigger by default, so the 1000-row batch outgrew the cap + // and flush threw BatchTooLargeForCapException. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server))) { + writeRows(s, "t", 0, 2_000); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + QwpWebSocketSender ws = (QwpWebSocketSender) s; + Assert.assertEquals((long) CAP * 9 / 10, ws.getEffectiveAutoFlushBytes()); + } + assertFramesWithinCap(h, CAP); + Assert.assertTrue("rows must span frames: " + h.frames, h.frames.size() >= 7); + // Not transactional: every frame commits on its own. + Assert.assertEquals(h.frames.size(), h.commitFrames()); + } + }); + } + + @Test + public void testExplicitAutoFlushBytesOffKeepsNoByteTrigger() throws Exception { + // auto_flush_bytes=off still opts out of the byte trigger, as documented. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "auto_flush_bytes=off;")) { + Assert.assertEquals(0, ((QwpWebSocketSender) s).getEffectiveAutoFlushBytes()); + try { + writeRows(s, "t", 0, 1_000); + Assert.fail("a 1000-row batch over the cap must be rejected"); + } catch (BatchTooLargeForCapException expected) { + TestUtils.assertContains(expected.getMessage(), "serverMaxBatchSize=" + CAP); + } + s.reset(); + } + Assert.assertEquals(0, h.frames.size()); + } + }); + } + + @Test + public void testByteTriggerFollowsSegmentSize() throws Exception { + // The server accepts 48 KiB frames, but a 16 KiB segment cannot hold them: + // batches must be sized to the segment, not fail at the append. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, 48 * 1024)) { + try (Sender s = Sender.fromConfig(conf(server) + "sf_max_segment_bytes=16k;")) { + writeRows(s, "t", 0, 600); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + int segmentPayload = 16 * 1024 - 24 - 8; + Assert.assertEquals(segmentPayload * 9 / 10, ((QwpWebSocketSender) s).getEffectiveAutoFlushBytes()); + } + assertFramesWithinCap(h, 16 * 1024 - 24 - 8); + Assert.assertTrue(h.frames.size() >= 4); + } + }); + } + + @Test + public void testManualFlushKeepsOneCommitPerFlush() throws Exception { + // A non-transactional sender with every auto-flush trigger off keeps its + // flush as one commit: no byte trigger splits the batch early. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "auto_flush_rows=off;auto_flush_interval=off;")) { + Assert.assertEquals(0, ((QwpWebSocketSender) s).getEffectiveAutoFlushBytes()); + writeRows(s, "a", 0, 250); + writeRows(s, "b", 0, 250); + Assert.assertEquals(0, h.frames.size()); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + // The 50 KB batch splits per table at flush: one deferred frame, one commit. + Assert.assertEquals(2, h.frames.size()); + Assert.assertTrue(h.frames.get(0).isDeferred()); + Assert.assertTrue(h.frames.get(1).isCommit()); + } + }); + } + + @Test + public void testNewSymbolsCountTowardByteTrigger() throws Exception { + // Symbol columns buffer 4-byte ids; the 300-byte strings ride in the frame's + // dictionary section. Counting them keeps the frame within the cap. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server))) { + String prefix = TestUtils.repeat("s", 290); + for (int i = 0; i < 1_000; i++) { + s.table("t").symbol("sym", prefix + i).longColumn("v", i).atNow(); + } + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + assertFramesWithinCap(h, CAP); + Assert.assertTrue(h.frames.size() >= 10); + } + }); + } + + @Test + public void testPooledStrictLeaseCloseRetiresConnectionWithoutServerRollback() throws Exception { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (QuestDB db = QuestDB.connect(conf(server) + "transaction=strict;query_pool_min=0;")) { + Sender lease = db.borrowSender(); + writeRows(lease, "t", 0, 1_000); + Assert.assertTrue(h.awaitFrames(2)); + // The frames already sent cannot be rolled back: the pool retires + // the connection, which makes the server discard them. + lease.close(); + Sender next = db.borrowSender(); + writeRows(next, "t", 0, 10); + next.flush(); + Assert.assertTrue(next.drain(5_000)); + next.close(); + } + Assert.assertEquals(1, h.commitFrames()); + Assert.assertEquals(0, h.rollbackFrames()); + } + }); + } + + @Test + public void testPooledStrictLeaseCloseRollsBackUncommitted() throws Exception { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(true); + try (QuestDB db = QuestDB.connect(conf(server) + "transaction=strict;query_pool_min=0;")) { + Sender lease = db.borrowSender(); + writeRows(lease, "t", 0, 1_000); + Assert.assertTrue(h.awaitFrames(2)); + // Returning a strict lease without flush() discards the transaction. + lease.close(); + Assert.assertTrue(h.frames.get(h.frames.size() - 1).isRollback()); + Sender next = db.borrowSender(); + writeRows(next, "t", 0, 10); + next.flush(); + Assert.assertTrue(next.drain(5_000)); + next.close(); + } + Assert.assertEquals(1, h.commitFrames()); + Assert.assertEquals(1, h.rollbackFrames()); + } + }); + } + + @Test + public void testResetAbortsStrictTransactionWithoutServerRollback() throws Exception { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(h.awaitFrames(2)); + s.reset(); + assertAborted(s::flush); + assertAborted(() -> s.table("t").longColumn("v", 1).atNow()); + } + Assert.assertEquals("the reset transaction must never commit", 0, h.commitFrames()); + } + }); + } + + @Test + public void testResetKeepsLegacyBehaviourWithoutServerRollback() throws Exception { + // transaction=on against a server without rollback: reset() cannot reach the + // frames already sent, and the next flush() commits them, as before. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "transaction=on;")) { + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(h.awaitFrames(2)); + s.reset(); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + // The frames sent before reset() are deferred, and the flush after it + // committed them with an empty commit frame. + assertOneTransaction(h); + } + }); + } + + @Test + public void testResetRollsBackSentFramesWhenServerSupportsIt() throws Exception { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(true); + try (Sender s = Sender.fromConfig(conf(server) + "transaction=on;")) { + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(h.awaitFrames(2)); + s.reset(); + // reset() returned after the server acked the rollback frame, which + // follows every frame of the transaction. + int rollbackIndex = h.frames.size() - 1; + Assert.assertTrue(h.frames.get(rollbackIndex).isRollback()); + for (int i = 0; i < rollbackIndex; i++) { + Assert.assertTrue(h.frames.get(i).isDeferred()); + } + Assert.assertEquals(1, h.rolledBackGroups); + // The sender stays usable for the next transaction. + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + Assert.assertTrue(h.frames.get(h.frames.size() - 1).isCommit()); + } + } + }); + } + + @Test + public void testRollbackAckTimeoutAbortsTransaction() throws Exception { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + h.isAckingRollback = false; + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(true); + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { + ((QwpWebSocketSender) s).setRollbackAckTimeoutMillisForTesting(300); + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(h.awaitFrames(2)); + try { + s.rollback(); + Assert.fail("an unacknowledged rollback must fail"); + } catch (LineSenderException e) { + TestUtils.assertContains(e.getMessage(), "rollback not acknowledged by the server"); + } + assertAborted(s::flush); + } + Assert.assertEquals(0, h.commitFrames()); + } + }); + } + + @Test + public void testRollbackDiscardsSentFrames() throws Exception { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(true); + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { + QwpWebSocketSender ws = (QwpWebSocketSender) s; + Assert.assertTrue(ws.isServerRollbackEnabled()); + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(h.awaitFrames(2)); + Assert.assertEquals(0, h.commitFrames()); + s.rollback(); + // rollback() returned after the ack, so the frame is on the server, + // behind every frame of the transaction. + int sent = h.frames.size() - 1; + TxnFrame rollback = h.frames.get(sent); + Assert.assertTrue(rollback.isRollback()); + for (int i = 0; i < sent; i++) { + Assert.assertTrue(h.frames.get(i).isDeferred()); + } + Assert.assertEquals(QwpConstants.HEADER_SIZE, rollback.size); + Assert.assertEquals(1, h.rolledBackGroups); + Assert.assertFalse(ws.hasDeferredMessagesForTesting()); + // Nothing pending is left behind: an empty flush sends nothing. + s.flush(); + Assert.assertEquals(sent + 1, h.frames.size()); + // The next transaction starts clean and commits. + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + Assert.assertTrue(h.frames.get(h.frames.size() - 1).isCommit()); + } + } + }); + } + + @Test + public void testRollbackOnNonWebSocketSenderThrows() throws Exception { + assertMemoryLeak(() -> { + try (Sender s = Sender.fromConfig("http::addr=localhost:1;protocol_version=2;")) { + s.rollback(); + Assert.fail("rollback must be WebSocket-only"); + } catch (LineSenderException e) { + TestUtils.assertContains(e.getMessage(), "rollback is only supported for WebSocket transport"); + } + }); + } + + @Test + public void testRollbackUnsupportedAbortsTransaction() throws Exception { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "transaction=on;")) { + Assert.assertFalse(((QwpWebSocketSender) s).isServerRollbackEnabled()); + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(h.awaitFrames(2)); + assertAborted(s::rollback); + assertAborted(s::flush); + assertAborted(() -> s.table("t").longColumn("v", 1).atNow()); + assertAborted(s::rollback); + } + // close() of an aborted transaction must not commit it either. + Assert.assertEquals(0, h.commitFrames()); + Assert.assertEquals(0, h.rollbackFrames()); + } + }); + } + + @Test + public void testRollbackWithoutSentFramesSendsNothing() throws Exception { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(true); + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { + writeRows(s, "t", 0, 10); + s.rollback(); + s.flush(); + writeRows(s, "t", 0, 5); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + // Only the second transaction reached the server, as one commit frame. + Assert.assertEquals(1, h.frames.size()); + Assert.assertTrue(h.frames.get(0).isCommit()); + } + }); + } + + @Test + public void testServerLimitsReachTheSender() throws Exception { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setAdvertisedMaxUncommittedRows(12_345); + server.setRollbackSupported(true); + try (Sender s = Sender.fromConfig(conf(server))) { + QwpWebSocketSender ws = (QwpWebSocketSender) s; + Assert.assertEquals(12_345, ws.getServerMaxUncommittedRows()); + Assert.assertTrue(ws.isServerRollbackEnabled()); + } + Assert.assertEquals("true", server.pollRollbackRequest(5, TimeUnit.SECONDS)); + + // A server that does not confirm rollback, nor advertise its row limit. + server.setAdvertisedMaxUncommittedRows(0); + server.setRollbackSupported(false); + try (Sender s = Sender.fromConfig(conf(server))) { + QwpWebSocketSender ws = (QwpWebSocketSender) s; + Assert.assertEquals(0, ws.getServerMaxUncommittedRows()); + Assert.assertFalse(ws.isServerRollbackEnabled()); + } + } + }); + } + + @Test + public void testStrictCloseWithoutFlushDiscardsTransaction() throws Exception { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;close_flush_timeout_millis=1000;")) { + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(h.awaitFrames(2)); + } + Assert.assertEquals("close() must not commit a strict transaction", 0, h.commitFrames()); + Assert.assertEquals(0, h.rollbackFrames()); + } + }); + } + + @Test + public void testStrictCloseWithoutFlushRollsBackWhenServerSupportsIt() throws Exception { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(true); + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(h.awaitFrames(2)); + } + // close() drained until the rollback frame's ack. + Assert.assertTrue(h.frames.get(h.frames.size() - 1).isRollback()); + Assert.assertEquals(0, h.commitFrames()); + Assert.assertEquals(1, h.rolledBackGroups); + } + }); + } + + @Test + public void testStrictRowLimitFromServer() throws Exception { + // The server advertises 100: a strict transaction holds at most 99 rows + // of a table, since the server would commit the 100th on its own. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, 4_096)) { + server.setAdvertisedMaxUncommittedRows(100); + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { + // 4 KiB frames: the 99 rows of "a" go out over several deferred frames. + writeRows(s, "a", 0, 99); + Assert.assertTrue(h.awaitFrames(2)); + try { + writeRows(s, "a", 99, 1); + Assert.fail("the 100th row of a table must be refused"); + } catch (TransactionTooLargeException e) { + TestUtils.assertContains(e.getMessage(), + "transaction too large for the server [table=a, rows=100, maxUncommittedRows=100]"); + } + // Other tables keep their own count. + writeRows(s, "b", 0, 99); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + // A new transaction starts from zero again. + writeRows(s, "a", 0, 99); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + Assert.assertEquals(0, h.rollbackFrames()); + Assert.assertEquals(2, h.commitFrames()); + } + }); + } + + @Test + public void testStrictRowLimitDefaultsWhenNotAdvertised() throws Exception { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { + QwpWebSocketSender ws = (QwpWebSocketSender) s; + Assert.assertEquals(0, ws.getServerMaxUncommittedRows()); + // Pretend the server default is small to keep the test fast: the + // assumed default applies only while nothing is advertised. + ws.applyServerTransactionLimits(10, false); + writeRows(s, "a", 0, 9); + try { + writeRows(s, "a", 9, 1); + Assert.fail("the 10th row must be refused"); + } catch (TransactionTooLargeException e) { + TestUtils.assertContains(e.getMessage(), "maxUncommittedRows=10"); + } + ws.applyServerTransactionLimits(0, false); + // 0 means "not advertised": the server default applies. + writeRows(s, "a", 9, 1); + s.flush(); + } + } + }); + } + + @Test + public void testStrictTransactionTooLargeForClientBufferFailsFast() throws Exception { + // 64 KiB segments, 256 KiB budget: four segments. A strict transaction keeps + // room for its commit, so it must refuse the flush that would take that room + // instead of blocking for sf_append_deadline_millis. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;" + + "sf_max_segment_bytes=64k;sf_max_total_bytes=256k;sf_append_deadline_millis=30000;")) { + long start = System.nanoTime(); + int row = 0; + try { + for (; row < 100_000; row++) { + s.table("t").longColumn("v", row).stringColumn("s", PAD).atNow(); + } + Assert.fail("a transaction larger than the client buffer must be refused"); + } catch (TransactionTooLargeException e) { + TestUtils.assertContains(e.getMessage(), "transaction too large for the client buffer"); + } + Assert.assertTrue("must fail fast, not wait for the append deadline", + System.nanoTime() - start < TimeUnit.SECONDS.toNanos(10)); + // The row being added stays in the transaction; further rows are refused. + try { + s.table("t").longColumn("v", -1).stringColumn("s", PAD).atNow(); + Assert.fail("a full transaction must refuse rows"); + } catch (TransactionTooLargeException e) { + TestUtils.assertContains(e.getMessage(), "the row was not added"); + } + // The reserved room lets the transaction commit. + s.flush(); + Assert.assertTrue(s.drain(5_000)); + Assert.assertTrue(h.frames.get(h.frames.size() - 1).isCommit()); + Assert.assertEquals(1, h.commitFrames()); + // And the next transaction starts with an empty buffer. + writeRows(s, "t", 0, 100); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + } + }); + } + + @Test + public void testTransactionalDefaultTriggersSplitWideRows() throws Exception { + // Before: transaction=on with the default triggers threw + // BatchTooLargeForCapException at the 1000th wide row. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "transaction=on;")) { + writeRows(s, "t", 0, 2_000); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + assertFramesWithinCap(h, CAP); + assertOneTransaction(h); + } + }); + } + + private static void assertAborted(ThrowingRunnable r) { + try { + r.run(); + Assert.fail("expected the aborted-transaction error"); + } catch (LineSenderException e) { + TestUtils.assertContains(e.getMessage(), "transaction aborted"); + } + } + + private static void assertFramesWithinCap(TxnServer h, int cap) { + for (TxnFrame f : h.frames) { + Assert.assertTrue("frame of " + f.size + " bytes exceeds " + cap, f.size <= cap); + } + } + + private static void assertOneTransaction(TxnServer h) { + Assert.assertTrue(h.frames.size() > 1); + for (int i = 0, n = h.frames.size() - 1; i < n; i++) { + Assert.assertTrue("frame " + i + " must be deferred", h.frames.get(i).isDeferred()); + } + Assert.assertTrue(h.frames.get(h.frames.size() - 1).isCommit()); + } + + private static String conf(TestWebSocketServer server) { + return "ws::addr=localhost:" + server.getPort() + ";"; + } + + private static TestWebSocketServer start(TxnServer h, int cap) throws Exception { + TestWebSocketServer server = new TestWebSocketServer(h); + server.setAdvertisedMaxBatchSize(cap); + server.start(); + Assert.assertTrue(server.awaitStart(5, TimeUnit.SECONDS)); + return server; + } + + private static void writeRows(Sender s, String table, int from, int count) { + for (int i = from, n = from + count; i < n; i++) { + s.table(table).longColumn("v", i).stringColumn("s", PAD).atNow(); + } + } + + @FunctionalInterface + private interface ThrowingRunnable { + void run(); + } + + private static final class TxnFrame { + final byte flags; + final int size; + + TxnFrame(byte flags, int size) { + this.flags = flags; + this.size = size; + } + + boolean isCommit() { + return (flags & QwpConstants.FLAG_DEFER_COMMIT) == 0; + } + + boolean isDeferred() { + return !isRollback() && (flags & QwpConstants.FLAG_DEFER_COMMIT) != 0; + } + + boolean isRollback() { + return size == QwpConstants.HEADER_SIZE && flags == QwpConstants.ROLLBACK_FRAME_FLAGS; + } + + @Override + public String toString() { + return (isRollback() ? "R" : isDeferred() ? "D" : "C") + size; + } + } + + /** + * Acks frames the way the QuestDB server does for one connection: deferred + * frames wait for the commit frame that closes their group, which acks them + * cumulatively; the rollback frame discards the group and acks it too. + */ + private static final class TxnServer implements TestWebSocketServer.WebSocketServerHandler { + final List frames = new CopyOnWriteArrayList<>(); + volatile boolean isAckingRollback = true; + volatile int rolledBackGroups; + private long nextSeq; + + @Override + public synchronized void onBinaryMessage(TestWebSocketServer.ClientHandler client, byte[] data) { + long seq = nextSeq++; + TxnFrame frame = new TxnFrame(data[QwpConstants.HEADER_OFFSET_FLAGS], data.length); + frames.add(frame); + notifyAll(); + try { + if (frame.isRollback()) { + rolledBackGroups++; + if (isAckingRollback) { + client.sendBinary(ack(seq)); + } + } else if (frame.isCommit()) { + client.sendBinary(ack(seq)); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + synchronized boolean awaitFrames(int count) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (frames.size() < count) { + long left = deadline - System.nanoTime(); + if (left <= 0) { + return false; + } + TimeUnit.NANOSECONDS.timedWait(this, left); + } + return true; + } + + synchronized int commitFrames() { + int n = 0; + for (TxnFrame f : frames) { + if (f.isCommit()) { + n++; + } + } + return n; + } + + synchronized int rollbackFrames() { + int n = 0; + for (TxnFrame f : frames) { + if (f.isRollback()) { + n++; + } + } + return n; + } + + private static byte[] ack(long seq) { + byte[] buf = new byte[1 + 8 + 2]; + ByteBuffer bb = ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN); + bb.put((byte) 0x00); + bb.putLong(seq); + bb.putShort((short) 0); + return buf; + } + } +} diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/SelfSufficientFramesTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/SelfSufficientFramesTest.java index 44ceb6d42..16f8a3bff 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/SelfSufficientFramesTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/SelfSufficientFramesTest.java @@ -487,8 +487,10 @@ public void testFileModeSplitPersistsDictBeforeAFAILEDPublish() throws Exception server.start(); Assert.assertTrue(server.awaitStart(5, TimeUnit.SECONDS)); + // auto_flush_bytes=off: the batch must reach flush() whole, as the + // byte trigger would otherwise publish it from at(). String config = "ws::addr=localhost:" + port + ";sf_dir=" + sfDir - + ";sf_max_segment_bytes=64;"; + + ";sf_max_segment_bytes=64;auto_flush_bytes=off;"; String pad = TestUtils.repeat("x", 60); Sender sender = Sender.fromConfig(config); try { 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 102922d6b..ee6b1f4a7 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 @@ -146,6 +146,16 @@ public class TestWebSocketServer implements Closeable { // builds. Lets a test force the delta-dictionary catch-up to split across // several frames. Live-updatable via setAdvertisedMaxBatchSize(). private volatile int advertisedMaxBatchSize; + // When > 0, 101 upgrade responses advertise this value as the + // X-QWP-Max-Uncommitted-Rows header. Live-updatable. + private volatile long advertisedMaxUncommittedRows; + // X-QWP-Request-Rollback header value captured from each well-formed upgrade + // request ("" when absent). + private final BlockingQueue capturedRollbackRequests = new LinkedBlockingQueue<>(); + // When true, a 101 upgrade response to a request carrying + // X-QWP-Request-Rollback: true confirms it with X-QWP-Rollback: enabled. + // Live-updatable. + private volatile boolean rollbackSupported; public TestWebSocketServer(WebSocketServerHandler handler) throws IOException { this(handler, false); @@ -349,6 +359,31 @@ public void setAdvertisedMaxBatchSize(int maxBatchSize) { this.advertisedMaxBatchSize = maxBatchSize; } + /** + * Advertises {@code X-QWP-Max-Uncommitted-Rows: } on subsequent + * handshakes (live update). Pass {@code 0} to stop advertising it. + */ + public void setAdvertisedMaxUncommittedRows(long rows) { + this.advertisedMaxUncommittedRows = rows; + } + + /** + * When {@code true}, subsequent handshakes that request rollback + * ({@code X-QWP-Request-Rollback: true}) are confirmed with + * {@code X-QWP-Rollback: enabled} (live update). + */ + public void setRollbackSupported(boolean supported) { + this.rollbackSupported = supported; + } + + /** + * Blocks up to {@code timeout} for the next captured X-QWP-Request-Rollback + * header value ("" when the upgrade request carried none). + */ + public String pollRollbackRequest(long timeout, TimeUnit unit) throws InterruptedException { + return capturedRollbackRequests.poll(timeout, unit); + } + /** * Replaces the advertised role for subsequent handshakes (live update). */ @@ -762,6 +797,7 @@ private boolean performHandshake() throws IOException { String key = null; String authorization = ""; String durableAckRequest = ""; + String rollbackRequest = ""; String[] lines = request.toString().split("\r\n"); if (lines.length > 0) { // GET HTTP/1.1 @@ -778,6 +814,8 @@ private boolean performHandshake() throws IOException { authorization = line.substring("authorization:".length()).trim(); } else if (lower.startsWith("x-qwp-request-durable-ack:")) { durableAckRequest = line.substring("x-qwp-request-durable-ack:".length()).trim(); + } else if (lower.startsWith("x-qwp-request-rollback:")) { + rollbackRequest = line.substring("x-qwp-request-rollback:".length()).trim(); } } @@ -787,6 +825,7 @@ private boolean performHandshake() throws IOException { upgradeRequestCount.incrementAndGet(); capturedAuthHeaders.add(authorization); capturedDurableAckRequests.add(durableAckRequest); + capturedRollbackRequests.add(rollbackRequest); // Read-path reject: drop the egress upgrade before the 101 so the // query pool's connect fails fast, while ingest write-path upgrades @@ -866,6 +905,13 @@ private boolean performHandshake() throws IOException { if (maxBatch > 0) { sb.append("X-QWP-Max-Batch-Size: ").append(maxBatch).append("\r\n"); } + long maxUncommittedRows = advertisedMaxUncommittedRows; + if (maxUncommittedRows > 0) { + sb.append("X-QWP-Max-Uncommitted-Rows: ").append(maxUncommittedRows).append("\r\n"); + } + if (rollbackSupported && "true".equalsIgnoreCase(rollbackRequest)) { + sb.append("X-QWP-Rollback: enabled\r\n"); + } sb.append("\r\n"); out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); out.flush(); diff --git a/core/src/test/java/io/questdb/client/test/impl/WsSenderConfigHonoredTest.java b/core/src/test/java/io/questdb/client/test/impl/WsSenderConfigHonoredTest.java index 39695ec22..d9190ba6b 100644 --- a/core/src/test/java/io/questdb/client/test/impl/WsSenderConfigHonoredTest.java +++ b/core/src/test/java/io/questdb/client/test/impl/WsSenderConfigHonoredTest.java @@ -54,11 +54,12 @@ public void testEveryIngressKeyIsHonored() { assertHonored("auto_flush_interval=250", "auto_flush_interval", 250); // auto_flush=off reaches disableAutoFlush(), which sets the interval to // MAX_VALUE; auto_flush_rows=off leaves the interval unset, so this field - // distinguishes the two. That config is build-rejected on WebSocket; see - // QuestDBBuilderTest.testMalformedIngressConfigRejectedAtBuildWithMinZero. + // distinguishes the two. On WebSocket it selects strict transactional mode + // at build(); see QwpLargeTransactionTest. assertHonored("auto_flush=off", "auto_flush_interval", Integer.MAX_VALUE); assertHonored("max_name_len=99", "max_name_len", 99); - assertHonored("transaction=on", "transaction", true); + assertHonored("transaction=on", "transaction", "on"); + assertHonored("transaction=strict", "transaction", "strict"); assertHonored("request_durable_ack=on", "request_durable_ack", "on"); assertHonored("request_durable_ack=local", "request_durable_ack", "local"); assertHonored("request_durable_ack=replicated", "request_durable_ack", "replicated"); From d5028e534556d261e34df49277f55ac65e54cbdc Mon Sep 17 00:00:00 2001 From: bluestreak Date: Wed, 11 Nov 2026 23:45:23 +0000 Subject: [PATCH 02/20] Test strict split frames and pooled lease reuse Cover a strict transaction whose batch splits per table within the cap, and a strict pooled lease returned with only unsent rows, which keeps its connection and sends no rollback frame. --- .../qwp/client/QwpLargeTransactionTest.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index 4b96c8196..191ab3912 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -249,6 +249,56 @@ public void testPooledStrictLeaseCloseRollsBackUncommitted() throws Exception { }); } + @Test + public void testPooledStrictLeaseCloseWithOnlyPendingRowsKeepsConnection() throws Exception { + // Nothing reached the server yet: returning the lease drops the pending + // rows without a rollback frame and keeps the connection pooled. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (QuestDB db = QuestDB.connect(conf(server) + "transaction=strict;query_pool_min=0;")) { + Sender lease = db.borrowSender(); + writeRows(lease, "t", 0, 10); + lease.close(); + Sender next = db.borrowSender(); + writeRows(next, "t", 0, 5); + next.flush(); + Assert.assertTrue(next.drain(5_000)); + next.close(); + } + Assert.assertEquals(1, h.frames.size()); + Assert.assertTrue(h.frames.get(0).isCommit()); + Assert.assertEquals(1, server.upgradeRequestCount()); + } + }); + } + + @Test + public void testStrictMultiTableFlushSplitsWithinTheCap() throws Exception { + // Ten tables in one batch carry ten schemas, so the batch the byte trigger + // cuts outgrows the cap and splits per table. Every split frame of the + // open transaction stays deferred. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, 4_096)) { + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { + for (int i = 0; i < 400; i++) { + s.table("table_with_a_long_name_" + (i % 10)) + .longColumn("first_long_column_name", i) + .longColumn("second_long_column_name", i) + .stringColumn("s", "abc") + .atNow(); + } + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + assertFramesWithinCap(h, 4_096); + assertOneTransaction(h); + Assert.assertTrue(h.frames.size() > 10); + } + }); + } + @Test public void testResetAbortsStrictTransactionWithoutServerRollback() throws Exception { assertMemoryLeak(() -> { From ce20002c0966eb7660a95d34718b1ed418acde33 Mon Sep 17 00:00:00 2001 From: Vlad Ilyushchenko Date: Thu, 12 Nov 2026 11:59:35 +0000 Subject: [PATCH 03/20] Test discarding a transaction during an outage reset(), rollback() and returning a strict pooled lease discard the open transaction by publishing the rollback frame. During a server outage they wait up to 30 s for its ack, then throw and leave the sender aborted: every later row, flush, drain and rollback throws, even after the server comes back and acks the replayed rollback frame. Store-and-forward promises that an outage never fails a producer call. The new tests take the server down after a transaction's first frames went out, discard the transaction, commit the next one and bring the server back on the same endpoint. They fail until discarding stops waiting for the server. TxnServer now models the server per connection: wire sequences restart on every connection, and it records which frames a commit frame commits, so a test can assert that discarded rows never commit. A connection that did not confirm rollback reads the rollback frame as an empty deferred frame, as a server without rollback support does. TestWebSocketServer records which connections confirmed rollback. --- .../qwp/client/QwpLargeTransactionTest.java | 185 ++++++++++++++++-- .../qwp/websocket/TestWebSocketServer.java | 11 ++ 2 files changed, 185 insertions(+), 11 deletions(-) diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index 191ab3912..14692d7e8 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -39,9 +39,13 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; +import java.util.ArrayList; +import java.util.IdentityHashMap; import java.util.List; +import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; import static io.questdb.client.test.tools.TestUtils.assertMemoryLeak; @@ -200,6 +204,39 @@ public void testNewSymbolsCountTowardByteTrigger() throws Exception { }); } + @Test + public void testPooledStrictLeaseCloseDuringOutageKeepsTheConnection() throws Exception { + // Returning a strict lease discards its open transaction. During an outage that + // must neither wait for the server nor cost the pool its connection: the next + // borrower's transaction goes out behind the rollback frame once the server is back. + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + TxnServer before = new TxnServer(); + TxnServer after = new TxnServer(); + TestWebSocketServer revived = null; + try (TestWebSocketServer first = start(before, CAP, port, true)) { + try (QuestDB db = QuestDB.connect(outageConf(port) + "transaction=strict;query_pool_min=0;")) { + Sender lease = db.borrowSender(); + writeRows(lease, "t", 0, 1_000); + Assert.assertTrue(before.awaitFrames(2)); + first.close(); + lease.close(); + Sender next = db.borrowSender(); + writeRows(next, "t", 0, 10); + next.flush(); + revived = start(after, CAP, port, true); + Assert.assertTrue(next.drain(10_000)); + next.close(); + } + } finally { + if (revived != null) { + revived.close(); + } + } + assertDiscardedThenCommitted(before, after); + }); + } + @Test public void testPooledStrictLeaseCloseRetiresConnectionWithoutServerRollback() throws Exception { assertMemoryLeak(() -> { @@ -316,6 +353,14 @@ public void testResetAbortsStrictTransactionWithoutServerRollback() throws Excep }); } + @Test + public void testResetDuringOutageDoesNotStallTheSender() throws Exception { + // Store-and-forward keeps every producer call working through an outage. reset() + // used to wait 30 s for the rollback ack and then abort the transaction, so every + // later row and flush threw, even after the server came back. + assertDiscardDuringOutage("transaction=on;", Sender::reset); + } + @Test public void testResetKeepsLegacyBehaviourWithoutServerRollback() throws Exception { // transaction=on against a server without rollback: reset() cannot reach the @@ -389,6 +434,11 @@ public void testRollbackAckTimeoutAbortsTransaction() throws Exception { }); } + @Test + public void testRollbackDuringOutageDoesNotStallTheSender() throws Exception { + assertDiscardDuringOutage("transaction=strict;", Sender::rollback); + } + @Test public void testRollbackDiscardsSentFrames() throws Exception { assertMemoryLeak(() -> { @@ -684,10 +734,69 @@ private static void assertOneTransaction(TxnServer h) { Assert.assertTrue(h.frames.get(h.frames.size() - 1).isCommit()); } + // Asserts what the server that came back after an outage received and committed: the + // discarded transaction's frames, replayed and then rolled back, and behind the rollback + // frame the next transaction, which alone commits. + private static void assertDiscardedThenCommitted(TxnServer before, TxnServer after) { + Assert.assertEquals("nothing commits before the outage", 0, before.committedFrames().size()); + Assert.assertEquals("one connection after the outage: " + after.frames, 1, after.connectionCount()); + int rollbackAt = -1; + for (int i = 0, n = after.frames.size(); i < n; i++) { + if (after.frames.get(i).isRollback()) { + Assert.assertEquals("one rollback frame: " + after.frames, -1, rollbackAt); + rollbackAt = i; + } + } + Assert.assertTrue("the discarded transaction is replayed ahead of the rollback frame: " + after.frames, + rollbackAt >= 2); + for (int i = 0; i < rollbackAt; i++) { + Assert.assertTrue("frame " + i + " must be deferred: " + after.frames, after.frames.get(i).isDeferred()); + } + Assert.assertEquals(1, after.rolledBackGroups); + Assert.assertTrue(after.frames.get(after.frames.size() - 1).isCommit()); + Assert.assertEquals("only the next transaction commits", + after.frames.subList(rollbackAt + 1, after.frames.size()), after.committedFrames()); + } + + // The server confirmed rollback, received the first frames of a transaction and went + // away. The transaction is discarded during the outage, the next one is committed, and + // the server comes back on the same endpoint. + private static void assertDiscardDuringOutage(String mode, Consumer discard) throws Exception { + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + TxnServer before = new TxnServer(); + TxnServer after = new TxnServer(); + TestWebSocketServer revived = null; + try (TestWebSocketServer first = start(before, CAP, port, true)) { + try (Sender s = Sender.fromConfig(outageConf(port) + mode)) { + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(before.awaitFrames(2)); + first.close(); + // Must neither wait for the server nor fail: the server is away. + discard.accept(s); + writeRows(s, "t", 0, 10); + s.flush(); + revived = start(after, CAP, port, true); + Assert.assertTrue(s.drain(10_000)); + } + } finally { + if (revived != null) { + revived.close(); + } + } + assertDiscardedThenCommitted(before, after); + }); + } + private static String conf(TestWebSocketServer server) { return "ws::addr=localhost:" + server.getPort() + ";"; } + // Reconnects within milliseconds once the server is back. + private static String outageConf(int port) { + return "ws::addr=localhost:" + port + ";reconnect_initial_backoff_millis=10;reconnect_max_backoff_millis=50;"; + } + private static TestWebSocketServer start(TxnServer h, int cap) throws Exception { TestWebSocketServer server = new TestWebSocketServer(h); server.setAdvertisedMaxBatchSize(cap); @@ -696,6 +805,17 @@ private static TestWebSocketServer start(TxnServer h, int cap) throws Exception return server; } + // A server on a fixed port, so a test can take it down and bring it back on the same + // endpoint, as one that supports rollback or as one that predates it. + private static TestWebSocketServer start(TxnServer h, int cap, int port, boolean isRollbackSupported) throws Exception { + TestWebSocketServer server = new TestWebSocketServer(h, false, null, port); + server.setAdvertisedMaxBatchSize(cap); + server.setRollbackSupported(isRollbackSupported); + server.start(); + Assert.assertTrue(server.awaitStart(5, TimeUnit.SECONDS)); + return server; + } + private static void writeRows(Sender s, String table, int from, int count) { for (int i = from, n = from + count; i < n; i++) { s.table(table).longColumn("v", i).stringColumn("s", PAD).atNow(); @@ -708,12 +828,15 @@ private interface ThrowingRunnable { } private static final class TxnFrame { + // Index of the connection the frame arrived on, in connection order. + final int connection; final byte flags; final int size; - TxnFrame(byte flags, int size) { + TxnFrame(byte flags, int size, int connection) { this.flags = flags; this.size = size; + this.connection = connection; } boolean isCommit() { @@ -730,41 +853,70 @@ boolean isRollback() { @Override public String toString() { - return (isRollback() ? "R" : isDeferred() ? "D" : "C") + size; + return connection + ":" + (isRollback() ? "R" : isDeferred() ? "D" : "C") + size; } } /** - * Acks frames the way the QuestDB server does for one connection: deferred - * frames wait for the commit frame that closes their group, which acks them - * cumulatively; the rollback frame discards the group and acks it too. + * Acks frames the way the QuestDB server does, per connection: wire sequences + * restart at 0 on every connection, deferred frames wait for the commit frame + * that closes their group, which acks them cumulatively, and the rollback frame + * discards the group and acks it too. + *

+ * It also models what the server commits: a commit frame commits the group open + * on its connection, while a rollback frame or a closed connection leaves that + * group uncommitted. On a connection that did not confirm rollback the rollback + * frame is what a server without rollback support makes of it, an empty deferred + * frame: the group stays open, and the next commit on the connection commits it. */ private static final class TxnServer implements TestWebSocketServer.WebSocketServerHandler { + // Every frame received, over all connections, in arrival order. final List frames = new CopyOnWriteArrayList<>(); volatile boolean isAckingRollback = true; volatile int rolledBackGroups; - private long nextSeq; + // Frames a commit frame committed, in commit order. + private final List committed = new ArrayList<>(); + private final Map connections = new IdentityHashMap<>(); @Override public synchronized void onBinaryMessage(TestWebSocketServer.ClientHandler client, byte[] data) { - long seq = nextSeq++; - TxnFrame frame = new TxnFrame(data[QwpConstants.HEADER_OFFSET_FLAGS], data.length); + Connection connection = connections.get(client); + if (connection == null) { + connection = new Connection(connections.size()); + connections.put(client, connection); + } + long seq = connection.nextSeq++; + TxnFrame frame = new TxnFrame(data[QwpConstants.HEADER_OFFSET_FLAGS], data.length, connection.index); frames.add(frame); notifyAll(); try { - if (frame.isRollback()) { + if (frame.isCommit()) { + committed.addAll(connection.group); + committed.add(frame); + connection.group.clear(); + client.sendBinary(ack(seq)); + } else if (frame.isRollback() && client.isRollbackConfirmed()) { rolledBackGroups++; + connection.group.clear(); if (isAckingRollback) { client.sendBinary(ack(seq)); } - } else if (frame.isCommit()) { - client.sendBinary(ack(seq)); + } else { + connection.group.add(frame); } } catch (IOException e) { throw new RuntimeException(e); } } + synchronized List committedFrames() { + return new ArrayList<>(committed); + } + + synchronized int connectionCount() { + return connections.size(); + } + synchronized boolean awaitFrames(int count) throws InterruptedException { long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); while (frames.size() < count) { @@ -805,5 +957,16 @@ private static byte[] ack(long seq) { bb.putShort((short) 0); return buf; } + + private static final class Connection { + // Deferred frames the connection holds uncommitted. + final List group = new ArrayList<>(); + final int index; + long nextSeq; + + Connection(int index) { + this.index = index; + } + } } } 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 ee6b1f4a7..81bf01442 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 @@ -583,6 +583,8 @@ public class ClientHandler implements Closeable { private final Socket socket; private InputStream in; private boolean isClosed; + // True once this connection's 101 response confirmed X-QWP-Rollback: enabled. + private volatile boolean isRollbackConfirmed; private OutputStream out; private Thread readThread; // Request path from the WebSocket upgrade GET line (e.g. /write/v4, @@ -637,6 +639,14 @@ private void drainInput() throws IOException { } } + /** + * Whether this connection's upgrade confirmed {@code X-QWP-Rollback: enabled}, so + * the client may send it the rollback control frame. + */ + public boolean isRollbackConfirmed() { + return isRollbackConfirmed; + } + public synchronized void sendBinary(byte[] data) throws IOException { writeFrame(WebSocketOpcode.BINARY, data, data.length); } @@ -911,6 +921,7 @@ private boolean performHandshake() throws IOException { } if (rollbackSupported && "true".equalsIgnoreCase(rollbackRequest)) { sb.append("X-QWP-Rollback: enabled\r\n"); + isRollbackConfirmed = true; } sb.append("\r\n"); out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); From fa1c788a1d76dae58411de8668a8aee39eb1a430 Mon Sep 17 00:00:00 2001 From: Vlad Ilyushchenko Date: Thu, 12 Nov 2026 13:33:15 +0000 Subject: [PATCH 04/20] Discard transactions without waiting on the server reset(), rollback() and returning a strict pooled lease waited up to 30 s for the rollback frame's ack, then latched the transaction as aborted: every later row, flush, drain and rollback threw, even after the server came back and acked the replayed rollback frame, and the error blamed missing server rollback support. A transient outage broke the producer for good, which store-and-forward must never do. The wait stood in for a guarantee the producer cannot see: a reconnect that reaches a server without rollback support, such as an older node after a failover, must not replay the rolled-back frames there, as that server reads the rollback frame as an empty deferred frame and commits the frames with the next commit. The I/O loop knows which server each connection reached, so the guarantee moves there. The store-and-forward log already orders the rollback frame ahead of every later frame on every connection. On a connection whose server did not confirm X-QWP-Rollback the loop never sends a rollback frame: once the server acked every commit-bearing frame sent before it, the loop acknowledges the frame itself and recycles the connection. Closing the connection discards the rolled-back frames server-side, as every server does with what a closed connection leaves uncommitted, and the next connection starts past the frame, the way the orphaned-tail retirement already works. Replays after a restart and background drains run through the same loop, so they get the same guard. rollbackOpenTransaction() now only publishes the frame; the timeout, its test setter and the abort on timeout are gone. Sender.rollback() no longer promises to block, and Sender.reset() documents the transactional discard. On a connection that confirmed rollback, trySendBatch adds one cached boolean check per frame and no extra writes. CursorWebSocketSendLoopRollbackTest drives the loop against a model of the server's commits that drops what a closed connection had in flight: the rollback frame never reaches a server without rollback support, the loop waits for commit acks (durable ones in durable-ack mode) before recycling, only the exact rollback frame is held back, consecutive rollbacks, a recovered log, the background drainer, a per-connection capability, and a fuzz test over random transactions and mixed servers (questdb.fuzz.rollback.iterations). A sender-level test fails over to a server without rollback support. testRollbackAckTimeoutAbortsTransaction asserted the abort this commit removes; testUnacknowledgedRollbackDoesNotStallTheSender replaces it. Tests that read the server's frames right after reset(), rollback() or a lease close now wait with drain() or for the rollback frame, since those calls no longer block, and assert what the server committed. --- .../main/java/io/questdb/client/Sender.java | 15 +- .../qwp/client/QwpWebSocketSender.java | 77 +- .../sf/cursor/CursorWebSocketSendLoop.java | 86 ++ .../qwp/client/QwpLargeTransactionTest.java | 157 +++- .../CursorWebSocketSendLoopRollbackTest.java | 802 ++++++++++++++++++ 5 files changed, 1057 insertions(+), 80 deletions(-) create mode 100644 core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoopRollbackTest.java diff --git a/core/src/main/java/io/questdb/client/Sender.java b/core/src/main/java/io/questdb/client/Sender.java index b3ffb3484..bb5709e69 100644 --- a/core/src/main/java/io/questdb/client/Sender.java +++ b/core/src/main/java/io/questdb/client/Sender.java @@ -773,8 +773,11 @@ default void resetSymbolDictionary() { * data format) and want to continue sending new data without retrying the problematic data. * After calling this method, you can start building a new row by calling {@link #table(CharSequence)}. *
- * Note: This method is only available for HTTP transport. TCP transport doesn't support - * this operation. + * In WebSocket transactional mode ({@code transaction=on} or {@code strict}) it also + * discards the rows of the open transaction that auto-flush already sent, as + * {@link #rollback()} does, when the server supports QWP rollback. + *
+ * Note: the ILP TCP and UDP transports don't support this operation. * * @see #flush() */ @@ -784,7 +787,13 @@ default void resetSymbolDictionary() { * Discard the open transaction: the rows buffered since the last flush and, in * WebSocket transactional mode ({@code transaction=on} or {@code strict}), the * rows of the transaction that auto-flush already sent to the server, which - * the server discards on request. Blocks until the server confirms. + * the server discards on request. + *
+ * Like {@link #flush()}, this returns without waiting for the server, so a + * server outage makes it fail only when the store-and-forward buffer is full, + * as it would a flush. The request goes out ahead of anything sent later, so + * later rows never commit the discarded ones, even across reconnects. Call + * {@link #drain(long)} to wait until the server confirms. *
* Discarding rows already sent needs a server that supports QWP rollback. When * the server does not, this method throws and aborts the transaction: every diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java index 7d94dc702..0e0b28c02 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java @@ -186,8 +186,6 @@ public class QwpWebSocketSender implements Sender { public static final int DEFAULT_SYMBOL_DICT_RESET_THRESHOLD_SYMBOLS = 100_000; private static final int DEFAULT_BUFFER_SIZE = 8192; private static final int DEFAULT_MICROBATCH_BUFFER_SIZE = 1024 * 1024; // 1MB - // How long rollback() waits for the server to acknowledge the rollback frame. - private static final long DEFAULT_ROLLBACK_ACK_TIMEOUT_MILLIS = 30_000L; // Frames of at most the frame cap that a strict transaction keeps room for in // the client buffer, so the commit that ends it can always be published. private static final int STRICT_COMMIT_RESERVE_FRAMES = 3; @@ -704,8 +702,6 @@ public class QwpWebSocketSender implements Sender { // entries too. Counted toward the byte trigger alongside pendingBytes. Reset // with pendingBytes. private long pendingSymbolDictBytes; - // Rollback-ack wait bound; see rollbackOpenTransaction. - private long rollbackAckTimeoutMillis = DEFAULT_ROLLBACK_ACK_TIMEOUT_MILLIS; // Server's per-table cap on rows a deferred-commit group may hold before it // commits them on its own (X-QWP-Max-Uncommitted-Rows), 0 when not advertised. // Captured on each FOREGROUND handshake, like serverMaxBatchSize. @@ -3386,10 +3382,11 @@ public void setCloseStartedHook(Runnable hook) { /** * Discards the rows buffered since the last flush, like before. In * transactional mode it also discards the open transaction's frames already - * sent, when the server supports QWP rollback (see {@link #rollback()}). - * Without that support a strict transaction is aborted -- the next flush - * throws and only closing the sender ends it -- while a non-strict one keeps - * the frames already sent, and the next flush commits them, as before. + * sent, when the server supports QWP rollback (see {@link #rollback()}), and + * like {@link #rollback()} it does not wait for the server. Without that + * support a strict transaction is aborted -- the next flush throws and only + * closing the sender ends it -- while a non-strict one keeps the frames + * already sent, and the next flush commits them, as before. */ @Override public void reset() { @@ -3412,16 +3409,21 @@ public void reset() { /** * Discards the open transaction: the rows buffered since the last flush, * and the transaction's frames already sent, which the server rolls back on - * the rollback control frame. Blocks until the server acknowledges the - * rollback. Without an open transaction this only discards the buffered - * rows. + * the rollback control frame. Without an open transaction this only discards + * the buffered rows. + *

+ * Like {@link #flush()}, it hands the rollback frame to store-and-forward and + * returns without waiting for the server, so a server outage makes it fail + * only when the store-and-forward buffer is full, as it would a flush. The + * frame goes out behind the transaction's frames and ahead of anything sent + * later, on every connection and after a restart, so nothing sent later can + * commit the discarded rows. Call {@link #drain(long)} to wait for the server + * to confirm. * * @throws LineSenderException when frames of the open transaction were already * sent and the server does not support QWP rollback * (the transaction is then aborted: the next flush - * throws, and only closing the sender ends it), or - * when the server does not acknowledge the rollback - * in time + * throws, and only closing the sender ends it) */ @Override public void rollback() { @@ -3515,39 +3517,29 @@ private void publishRollbackFrame() { } /** - * Rolls back the open transaction on the server and waits for the ack. + * Rolls back the open transaction: publishes the rollback frame behind its + * frames and ends it, without waiting for the server. *

- * The wait is what makes the rollback safe across reconnects. Until the - * server acknowledges the rollback frame, a reconnect replays the - * transaction's frames together with it, and a server reached by failover - * that does not support rollback would keep those frames for the next - * commit. Once acknowledged, the frames are trimmed and can never be - * replayed. A rollback that is not acknowledged in time aborts the - * transaction (see {@link #txnAborted}). + * No wait is needed to keep the rolled-back frames from ever committing. The + * store-and-forward log orders the rollback frame ahead of every frame + * published later, and every connection replays the log in that order, so a + * server that receives a later commit has rolled the transaction back first. + * Only a server that does not support rollback, reached by a reconnect + * before the frame was acked, could commit them: it would read the frame as + * an empty deferred frame. The I/O loop never sends it there; it discards + * the transaction by closing that connection instead (see + * {@code CursorWebSocketSendLoop.retireRollbackFrame}). The same holds for + * frames replayed after a restart or by a background drainer, which use the + * same loop. */ private void rollbackOpenTransaction() { - long previousBoundaryFsn = lastCommitBoundaryFsn; publishRollbackFrame(); - long rollbackFsn = cursorEngine.publishedFsn(); hasDeferredMessages = false; - // The rollback frame gets an OK ack covering the transaction's frames, so + // The rollback frame gets an OK ack covering the transaction's frames, or the + // I/O loop acknowledges it when it discards the transaction itself, so // close-time drains may wait for it like for a commit. - lastCommitBoundaryFsn = rollbackFsn; + lastCommitBoundaryFsn = cursorEngine.publishedFsn(); clearTransactionState(); - boolean isAcked = false; - try { - isAcked = awaitAckedFsn(fsnEpochBase + rollbackFsn, rollbackAckTimeoutMillis); - } finally { - if (!isAcked) { - txnAborted = true; - lastCommitBoundaryFsn = previousBoundaryFsn; - } - } - if (!isAcked) { - throw new LineSenderException("rollback not acknowledged by the server [timeoutMillis=") - .put(rollbackAckTimeoutMillis) - .put("]; the transaction is aborted: close the sender to discard it"); - } } /** @@ -3819,11 +3811,6 @@ public void setRecycleDeferredCloseMaxWaitMillisForTesting(long millis) { this.recycleDeferredCloseMaxWaitMillis = millis; } - @TestOnly - public void setRollbackAckTimeoutMillisForTesting(long millis) { - this.rollbackAckTimeoutMillis = millis; - } - /** * Strict transactional mode: auto-flush ships rows as FLAG_DEFER_COMMIT frames * like {@link #setTransactional(boolean) transactional} mode, only an explicit diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java index 8a76edcc3..e45e53c8a 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java @@ -591,6 +591,16 @@ public final class CursorWebSocketSendLoop implements QuietCloseable { // and by the I/O thread afterwards -- never concurrently. private long orphanSkipStartFsn = -1L; private long orphanSkipTipFsn = -1L; + // Whether the current connection's server confirmed X-QWP-Rollback, so a rollback + // control frame may go out on it. setWireBaselineWithCatchUp sets it for every + // connection from the client it runs on; false until then, the safe side (see + // retireRollbackFrame). Written by start() on the user thread before the I/O thread + // exists, and by the I/O thread afterwards -- never concurrently. + private boolean isRollbackConfirmed; + // FSN of the last commit-bearing frame sent on the current connection, -1 when none. + // Tracked only while !isRollbackConfirmed, for retireRollbackFrame. Reset with + // isRollbackConfirmed; same threading. + private long lastSentCommitBearingFsn = -1L; // Poison-frame detector state (I/O thread only). poisonFsn is the FSN of the // frame implicated by the most recent server-active rejection: the NACK-named // frame, or the OK-level head-of-line frame (highestOkFsn+1) for a @@ -3198,6 +3208,10 @@ private void setWireBaselineWithCatchUp(long replayStart) { // handleServerRejection can tell "only the catch-up went out" from "the // head data frame went out". dataFrameSentThisConnection = false; + // The server this connection reached decides whether a rollback frame may go + // out on it; until a client exists no frame goes out at all. + isRollbackConfirmed = client != null && client.isServerRollbackEnabled(); + lastSentCommitBearingFsn = -1L; // Do not gate solely on isDeltaDictEnabled(): a recovered delta slot can // lose access to its side-file while its on-disk frames still start above // zero. hasReplayDictionaryDependency preserves that distinction while @@ -3230,6 +3244,26 @@ private int frameDeltaStart(long payloadAddr, int payloadLen) { return encoded < 0L ? -1 : (int) (encoded >>> 3); } + // True for a QWP frame carrying FLAG_DEFER_COMMIT. A short or foreign payload counts + // as commit-bearing, so retireRollbackFrame waits for its ack: the safe side, and the + // rule RecoveredFrameAnalysis applies to the orphaned deferred tail. + private static boolean isDeferredFrame(long payloadAddr, int payloadLen) { + return payloadLen >= QwpConstants.HEADER_SIZE + && Unsafe.getUnsafe().getInt(payloadAddr) == QwpConstants.MAGIC_MESSAGE + && (Unsafe.getUnsafe().getByte(payloadAddr + QwpConstants.HEADER_OFFSET_FLAGS) + & QwpConstants.FLAG_DEFER_COMMIT) != 0; + } + + // True only for the rollback control frame (QwpWebSocketEncoder.encodeRollbackMessage): + // a bare QWP header whose flags byte equals ROLLBACK_FRAME_FLAGS, compared whole as the + // server matches it. + private static boolean isRollbackFrame(long payloadAddr, int payloadLen) { + return payloadLen == QwpConstants.HEADER_SIZE + && Unsafe.getUnsafe().getInt(payloadAddr) == QwpConstants.MAGIC_MESSAGE + && Unsafe.getUnsafe().getByte(payloadAddr + QwpConstants.HEADER_OFFSET_FLAGS) + == QwpConstants.ROLLBACK_FRAME_FLAGS; + } + // True only for a well-formed QWP frame this encoder produced that carries a // delta symbol-dict section. The magic check keeps the dict logic from // misreading non-QWP payloads (e.g. synthetic frames injected by tests) whose @@ -4001,6 +4035,16 @@ private boolean trySendBatch() { break; // fixed byte cap: the next call carries on from this frame } long frameAddr = base + sendOffset + MmapSegment.FRAME_HEADER_SIZE; + if (!isRollbackConfirmed && isRollbackFrame(frameAddr, payloadLen)) { + if (batchFrames > 0) { + break; + } + // This server cannot roll back, so the frame never goes out on this + // connection: the loop waits for acks, or it discarded the rolled-back + // transaction and recycled. + retireRollbackFrame(); + return false; + } // Torn-dictionary guard. sentDictCount is this loop's model of how many ids the // CURRENT server has been told about. A frame whose delta starts ABOVE that // coverage references ids the server was never given, and the server now rejects @@ -4063,6 +4107,9 @@ private boolean trySendBatch() { sendOffset = frameEnd; long fsnSent = fsnAtZero + nextWireSeq; nextWireSeq++; + if (!isRollbackConfirmed && !isDeferredFrame(frameAddr, payloadLen)) { + lastSentCommitBearingFsn = fsnSent; + } batchFrames++; batchBytes += wireLen; if (replayTargetFsn >= 0) { @@ -4114,6 +4161,45 @@ void positionCursorForStart() { positionCursorAt(replayStart); } + /** + * Retires the rollback control frame at the send cursor of a connection whose + * server did not confirm X-QWP-Rollback. The producer sends that frame only after + * a server confirmed rollback, so this connection is a reconnect that reached a + * server without rollback support, such as an older node after a failover, with + * the frame not yet acked. That server would read the frame as an empty deferred + * frame and commit the rolled-back transaction, whose frames it holds uncommitted + * on this connection, with the next commit frame. So the frame never goes out: + * closing the connection discards those frames instead, as every server does with + * the rows a closed connection leaves uncommitted. + *

+ * The close waits until the server acks every commit-bearing frame sent on this + * connection before the rollback frame: the self-acknowledge below covers those + * frames too, so a commit the server had not yet processed would be lost with the + * connection. Until then this returns without doing anything, and tryReceiveAcks + * runs every loop iteration. Once they are acked, the frames this connection holds + * unacked are exactly the rolled-back transaction's deferred frames. The cumulative + * self-acknowledge of the rollback frame retires them, and the recycle discards + * them server-side and re-anchors the next connection past the rollback frame, the + * way {@link #tryRetireOrphanTail} handles an orphaned deferred tail. + */ + private void retireRollbackFrame() { + long rollbackFsn = fsnAtZero + nextWireSeq; + long ackedFsn = engine.ackedFsn(); + if (ackedFsn < lastSentCommitBearingFsn) { + return; + } + LOG.info("server does not support QWP rollback: discarding the rolled-back transaction " + + "[fsn {}..{}] by closing the connection that holds it uncommitted", + externalFsnBase + ackedFsn + 1L, externalFsnBase + rollbackFsn); + boolean isAdvanced = engine.acknowledge(rollbackFsn); + // Every ack is clamped to the frames this loop sent, and the cursor stands on + // the rollback frame, so the self-acknowledge always advances the watermark. + assert isAdvanced : "rollback frame already acknowledged [fsn=" + rollbackFsn + ']'; + dispatchProgress(rollbackFsn); + fail(new LineSenderException( + "recycling connection to discard a rolled-back transaction the server cannot roll back")); + } + /** * Retires the recovered orphaned deferred tail once retirable. *

diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index 14692d7e8..1bdfa9718 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -271,8 +271,10 @@ public void testPooledStrictLeaseCloseRollsBackUncommitted() throws Exception { Sender lease = db.borrowSender(); writeRows(lease, "t", 0, 1_000); Assert.assertTrue(h.awaitFrames(2)); - // Returning a strict lease without flush() discards the transaction. + // Returning a strict lease without flush() discards the transaction, + // without waiting for the server. lease.close(); + Assert.assertTrue(h.awaitRollbackFrames(1)); Assert.assertTrue(h.frames.get(h.frames.size() - 1).isRollback()); Sender next = db.borrowSender(); writeRows(next, "t", 0, 10); @@ -282,6 +284,7 @@ public void testPooledStrictLeaseCloseRollsBackUncommitted() throws Exception { } Assert.assertEquals(1, h.commitFrames()); Assert.assertEquals(1, h.rollbackFrames()); + assertRolledBackThenCommitted(h); } }); } @@ -392,8 +395,9 @@ public void testResetRollsBackSentFramesWhenServerSupportsIt() throws Exception writeRows(s, "t", 0, 1_000); Assert.assertTrue(h.awaitFrames(2)); s.reset(); - // reset() returned after the server acked the rollback frame, which - // follows every frame of the transaction. + // reset() does not wait for the server; drain() returns once the server + // acked the rollback frame, which follows every frame of the transaction. + Assert.assertTrue(s.drain(5_000)); int rollbackIndex = h.frames.size() - 1; Assert.assertTrue(h.frames.get(rollbackIndex).isRollback()); for (int i = 0; i < rollbackIndex; i++) { @@ -406,31 +410,61 @@ public void testResetRollsBackSentFramesWhenServerSupportsIt() throws Exception Assert.assertTrue(s.drain(5_000)); Assert.assertTrue(h.frames.get(h.frames.size() - 1).isCommit()); } + assertRolledBackThenCommitted(h); } }); } @Test - public void testRollbackAckTimeoutAbortsTransaction() throws Exception { + public void testRollbackFrameNeverReachesServerWithoutRollbackSupport() throws Exception { + // The transaction is discarded while the server that confirmed rollback is away, + // and the endpoint comes back as a server without rollback support, as after a + // failover to an older node. That server would read the rollback frame as an + // empty deferred frame and commit the discarded rows with the next transaction. + // The client closes the connection that holds them instead, and sends the next + // transaction on a new one. assertMemoryLeak(() -> { - TxnServer h = new TxnServer(); - h.isAckingRollback = false; - try (TestWebSocketServer server = start(h, CAP)) { - server.setRollbackSupported(true); - try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { - ((QwpWebSocketSender) s).setRollbackAckTimeoutMillisForTesting(300); + int port = TestPorts.findUnusedPort(); + TxnServer before = new TxnServer(); + TxnServer after = new TxnServer(); + TestWebSocketServer revived = null; + try (TestWebSocketServer first = start(before, CAP, port, true)) { + try (Sender s = Sender.fromConfig(outageConf(port) + "transaction=on;")) { writeRows(s, "t", 0, 1_000); - Assert.assertTrue(h.awaitFrames(2)); - try { - s.rollback(); - Assert.fail("an unacknowledged rollback must fail"); - } catch (LineSenderException e) { - TestUtils.assertContains(e.getMessage(), "rollback not acknowledged by the server"); - } - assertAborted(s::flush); + Assert.assertTrue(before.awaitFrames(2)); + first.close(); + s.rollback(); + writeRows(s, "t", 0, 10); + s.flush(); + revived = start(after, CAP, port, false); + Assert.assertTrue(s.drain(10_000)); + Assert.assertFalse(((QwpWebSocketSender) s).isServerRollbackEnabled()); } - Assert.assertEquals(0, h.commitFrames()); + } finally { + if (revived != null) { + revived.close(); + } + } + Assert.assertEquals(0, before.committedFrames().size()); + Assert.assertEquals("the rollback frame must not reach a server without rollback support: " + + after.frames, 0, after.rollbackFrames()); + List> connections = after.framesByConnection(); + Assert.assertEquals("one connection for the discarded transaction, one for the next: " + + after.frames, 2, connections.size()); + // The reader threads of the two connections may log their first frames in + // either order: tell them apart by what they carry. + List discarded = connections.get(0); + List next = connections.get(1); + if (next.get(next.size() - 1).isDeferred()) { + discarded = connections.get(1); + next = connections.get(0); + } + Assert.assertTrue("the discarded transaction is replayed: " + after.frames, discarded.size() >= 2); + for (TxnFrame f : discarded) { + Assert.assertTrue("frame must be deferred: " + after.frames, f.isDeferred()); } + Assert.assertTrue(next.get(next.size() - 1).isCommit()); + Assert.assertEquals("only the next transaction commits", next, after.committedFrames()); }); } @@ -452,8 +486,10 @@ public void testRollbackDiscardsSentFrames() throws Exception { Assert.assertTrue(h.awaitFrames(2)); Assert.assertEquals(0, h.commitFrames()); s.rollback(); - // rollback() returned after the ack, so the frame is on the server, - // behind every frame of the transaction. + // rollback() does not wait for the server; drain() returns once the + // server acked the rollback frame, which follows every frame of the + // transaction. + Assert.assertTrue(s.drain(5_000)); int sent = h.frames.size() - 1; TxnFrame rollback = h.frames.get(sent); Assert.assertTrue(rollback.isRollback()); @@ -472,6 +508,7 @@ public void testRollbackDiscardsSentFrames() throws Exception { Assert.assertTrue(s.drain(5_000)); Assert.assertTrue(h.frames.get(h.frames.size() - 1).isCommit()); } + assertRolledBackThenCommitted(h); } }); } @@ -693,6 +730,30 @@ public void testStrictTransactionTooLargeForClientBufferFailsFast() throws Excep }); } + @Test + public void testUnacknowledgedRollbackDoesNotStallTheSender() throws Exception { + // The server never acks the rollback frame on its own. rollback() used to wait + // for that ack and abort the transaction when it did not come. Nothing waits for + // it now: the next transaction goes out behind it, and the commit's cumulative + // ack covers it. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + h.isAckingRollback = false; + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(true); + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(h.awaitFrames(2)); + s.rollback(); + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + assertRolledBackThenCommitted(h); + } + }); + } + @Test public void testTransactionalDefaultTriggersSplitWideRows() throws Exception { // Before: transaction=on with the default triggers threw @@ -739,23 +800,29 @@ private static void assertOneTransaction(TxnServer h) { // frame the next transaction, which alone commits. private static void assertDiscardedThenCommitted(TxnServer before, TxnServer after) { Assert.assertEquals("nothing commits before the outage", 0, before.committedFrames().size()); - Assert.assertEquals("one connection after the outage: " + after.frames, 1, after.connectionCount()); + assertRolledBackThenCommitted(after); + } + + // Asserts what one connection received: a transaction's frames, the rollback frame + // that discarded them, and behind it the next transaction, which alone commits. + private static void assertRolledBackThenCommitted(TxnServer h) { + Assert.assertEquals("one connection: " + h.frames, 1, h.connectionCount()); int rollbackAt = -1; - for (int i = 0, n = after.frames.size(); i < n; i++) { - if (after.frames.get(i).isRollback()) { - Assert.assertEquals("one rollback frame: " + after.frames, -1, rollbackAt); + for (int i = 0, n = h.frames.size(); i < n; i++) { + if (h.frames.get(i).isRollback()) { + Assert.assertEquals("one rollback frame: " + h.frames, -1, rollbackAt); rollbackAt = i; } } - Assert.assertTrue("the discarded transaction is replayed ahead of the rollback frame: " + after.frames, + Assert.assertTrue("the discarded transaction goes out ahead of the rollback frame: " + h.frames, rollbackAt >= 2); for (int i = 0; i < rollbackAt; i++) { - Assert.assertTrue("frame " + i + " must be deferred: " + after.frames, after.frames.get(i).isDeferred()); + Assert.assertTrue("frame " + i + " must be deferred: " + h.frames, h.frames.get(i).isDeferred()); } - Assert.assertEquals(1, after.rolledBackGroups); - Assert.assertTrue(after.frames.get(after.frames.size() - 1).isCommit()); + Assert.assertEquals(1, h.rolledBackGroups); + Assert.assertTrue(h.frames.get(h.frames.size() - 1).isCommit()); Assert.assertEquals("only the next transaction commits", - after.frames.subList(rollbackAt + 1, after.frames.size()), after.committedFrames()); + h.frames.subList(rollbackAt + 1, h.frames.size()), h.committedFrames()); } // The server confirmed rollback, received the first frames of a transaction and went @@ -792,9 +859,11 @@ private static String conf(TestWebSocketServer server) { return "ws::addr=localhost:" + server.getPort() + ";"; } - // Reconnects within milliseconds once the server is back. + // Reconnects within milliseconds once the server is back. Each test drains before it + // closes, so the short close drain only bounds how long a failing test takes. private static String outageConf(int port) { - return "ws::addr=localhost:" + port + ";reconnect_initial_backoff_millis=10;reconnect_max_backoff_millis=50;"; + return "ws::addr=localhost:" + port + + ";reconnect_initial_backoff_millis=10;reconnect_max_backoff_millis=50;close_flush_timeout_millis=1000;"; } private static TestWebSocketServer start(TxnServer h, int cap) throws Exception { @@ -909,6 +978,18 @@ public synchronized void onBinaryMessage(TestWebSocketServer.ClientHandler clien } } + synchronized boolean awaitRollbackFrames(int count) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (rollbackFrames() < count) { + long left = deadline - System.nanoTime(); + if (left <= 0) { + return false; + } + TimeUnit.NANOSECONDS.timedWait(this, left); + } + return true; + } + synchronized List committedFrames() { return new ArrayList<>(committed); } @@ -917,6 +998,18 @@ synchronized int connectionCount() { return connections.size(); } + // The frames of each connection, in arrival order, by connection index. + synchronized List> framesByConnection() { + List> byConnection = new ArrayList<>(); + for (int i = 0, n = connections.size(); i < n; i++) { + byConnection.add(new ArrayList<>()); + } + for (TxnFrame f : frames) { + byConnection.get(f.connection).add(f); + } + return byConnection; + } + synchronized boolean awaitFrames(int count) throws InterruptedException { long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); while (frames.size() < count) { diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoopRollbackTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoopRollbackTest.java new file mode 100644 index 000000000..7468fde72 --- /dev/null +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoopRollbackTest.java @@ -0,0 +1,802 @@ +/*+***************************************************************************** + * ___ _ ____ ____ + * / _ \ _ _ ___ ___| |_| _ \| __ ) + * | | | | | | |/ _ \/ __| __| | | | _ \ + * | |_| | |_| | __/\__ \ |_| |_| | |_) | + * \__\_\\__,_|\___||___/\__|____/|____/ + * + * 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.sf.cursor; + +import io.questdb.client.DefaultHttpClientConfiguration; +import io.questdb.client.cutlass.http.client.WebSocketFrameHandler; +import io.questdb.client.cutlass.qwp.client.DurableAckTiers; +import io.questdb.client.cutlass.qwp.client.WebSocketResponse; +import io.questdb.client.cutlass.qwp.client.sf.cursor.BackgroundDrainer; +import io.questdb.client.cutlass.qwp.client.sf.cursor.CursorSendEngine; +import io.questdb.client.cutlass.qwp.client.sf.cursor.CursorWebSocketSendLoop; +import io.questdb.client.cutlass.qwp.protocol.QwpConstants; +import io.questdb.client.network.PlainSocketFactory; +import io.questdb.client.std.MemoryTag; +import io.questdb.client.std.Rnd; +import io.questdb.client.std.Unsafe; +import io.questdb.client.test.tools.TestUtils; +import io.questdb.client.test.tools.TestWebSocketClient; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; + +/** + * The rollback control frame on a connection whose server did not confirm + * {@code X-QWP-Rollback}. The producer publishes the frame without waiting for + * its ack, so a reconnect can reach a server without rollback support, such as + * an older node after a failover, before the frame is acked. That server would + * read it as an empty deferred frame and commit the rolled-back transaction + * with the next commit frame. + *

+ * Contract under test: the I/O loop never sends the rollback frame to such a + * server. Once the server acked every commit-bearing frame sent before it, the + * loop acknowledges the rollback frame itself and recycles the connection, + * which discards the rolled-back frames server-side, and the next connection + * starts past the rollback frame. A server that confirmed rollback receives the + * frame. The same holds for a log recovered after a restart and for the + * background drainer, which replay through the same loop. + *

+ * {@link ServerModel} is the oracle: it commits what the QuestDB server commits, + * and drops the frames a closed connection still had in flight, so a recycle + * before the acks of earlier commits shows as a lost commit. + */ +public class CursorWebSocketSendLoopRollbackTest { + // Random transaction logs per run of the fuzz test; raise it for a local soak. + private static final int FUZZ_ITERATIONS = Integer.getInteger("questdb.fuzz.rollback.iterations", 100); + private static final long SEGMENT_SIZE_BYTES = 64 * 1024; + private static final String TABLE = "t"; + + @Rule + public final TemporaryFolder temporaryFolder = TemporaryFolder.builder().assureDeletion().build(); + + @Test + public void testBackgroundDrainerRetiresRollbackOnServerWithoutRollback() throws Exception { + // An orphaned slot whose producer rolled back a transaction and committed the + // next one before it went away, with nothing acked yet. + String slotPath = temporaryFolder.newFolder("slot").getAbsolutePath(); + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = new CursorSendEngine(slotPath, SEGMENT_SIZE_BYTES)) { + appendCommit(engine, 1); + appendDeferred(engine, 2); + appendRollback(engine); + appendDeferred(engine, 3); + appendCommit(engine, 4); + } + ServerModel server = new ServerModel(); + List clients = new ArrayList<>(); + BackgroundDrainer drainer = new BackgroundDrainer( + slotPath, + SEGMENT_SIZE_BYTES, + 1L << 20, + () -> newClient(server, clients, false, false), + 5_000L, + 1L, + 5L, + DurableAckTiers.NONE, + 200L); + + // A drainer retries until it drains, so bound the run: a slot that never + // drains fails the test instead of hanging it. + Thread drain = new Thread(drainer::run, "rollback-drainer"); + drain.start(); + drain.join(10_000); + if (drain.isAlive()) { + drainer.requestStop(); + drain.join(); + Assert.fail("the slot did not drain: " + server.received()); + } + + Assert.assertEquals(BackgroundDrainer.DrainOutcome.SUCCESS, drainer.outcome()); + Assert.assertEquals(Arrays.asList("0:C1", "0:D2", "1:D3", "1:C4"), server.received()); + Assert.assertEquals(Arrays.asList("C1", "D3", "C4"), server.committed()); + Assert.assertEquals(2, clientCount(clients)); + }); + } + + @Test + public void testConsecutiveRollbacksRecycleOnceEach() throws Exception { + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendDeferred(engine, 1); + appendRollback(engine); + appendDeferred(engine, 2); + appendRollback(engine); + appendDeferred(engine, 3); + appendCommit(engine, 4); + ServerModel server = new ServerModel(); + List clients = new ArrayList<>(); + runToAck(engine, newLoop(engine, server, clients, false), 5L); + Assert.assertEquals(Arrays.asList("0:D1", "1:D2", "2:D3", "2:C4"), server.received()); + Assert.assertEquals(Arrays.asList("D3", "C4"), server.committed()); + Assert.assertEquals(3, clientCount(clients)); + } + }); + } + + @Test + public void testRandomTransactionsOverServersWithAndWithoutRollback() throws Exception { + // Transactions of zero to three deferred frames, each closed by a commit frame or + // a rollback frame, over connections that reach a server with or without rollback + // support at random. Each rollback frame goes out to a server that confirmed + // rollback, or costs exactly one recycle; only committed transactions commit, + // each once. + long s0 = System.nanoTime(); + long s1 = System.currentTimeMillis(); + Rnd rnd = TestUtils.generateRandom(null, s0, s1); + try { + TestUtils.assertMemoryLeak(() -> { + for (int iteration = 0; iteration < FUZZ_ITERATIONS; iteration++) { + runRandomTransactions(rnd); + } + }); + } catch (Throwable t) { + throw new AssertionError("seeds=" + s0 + "L, " + s1 + "L", t); + } + } + + @Test + public void testRecoveredLogRetiresRollbackOnServerWithoutRollback() throws Exception { + // A restart recovers the log with the rollback frame between two transactions, so + // the orphaned-tail retirement does not apply: the frame is replayed like any other. + String dir = temporaryFolder.newFolder("recovered").getAbsolutePath(); + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = new CursorSendEngine(dir, SEGMENT_SIZE_BYTES)) { + appendCommit(engine, 1); + appendDeferred(engine, 2); + appendRollback(engine); + appendDeferred(engine, 3); + appendCommit(engine, 4); + } + try (CursorSendEngine engine = new CursorSendEngine(dir, SEGMENT_SIZE_BYTES)) { + Assert.assertTrue(engine.wasRecoveredFromDisk()); + Assert.assertEquals("no orphaned tail", -1L, engine.recoveredOrphanTipFsn()); + ServerModel server = new ServerModel(); + List clients = new ArrayList<>(); + runToAck(engine, newLoop(engine, server, clients, false), 4L); + Assert.assertEquals(Arrays.asList("0:C1", "0:D2", "1:D3", "1:C4"), server.received()); + Assert.assertEquals(Arrays.asList("C1", "D3", "C4"), server.committed()); + Assert.assertEquals(2, clientCount(clients)); + } + }); + } + + @Test + public void testRollbackAtReplayStartRetiresBeforeSendingAnything() throws Exception { + // The frames ahead of the rollback frame are acked already, as when the server + // committed the transaction's rows itself at its uncommitted-row cap, so the + // rollback frame is the first frame of the connection. + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendDeferred(engine, 1); + appendRollback(engine); + appendDeferred(engine, 2); + appendCommit(engine, 3); + engine.acknowledge(0L); + ServerModel server = new ServerModel(); + List clients = new ArrayList<>(); + runToAck(engine, newLoop(engine, server, clients, false), 3L); + Assert.assertEquals(Arrays.asList("1:D2", "1:C3"), server.received()); + Assert.assertEquals(Arrays.asList("D2", "C3"), server.committed()); + Assert.assertEquals(2, clientCount(clients)); + } + }); + } + + @Test + public void testRollbackFrameGoesToServerWithRollback() throws Exception { + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendCommit(engine, 1); + appendDeferred(engine, 2); + appendDeferred(engine, 3); + appendRollback(engine); + appendDeferred(engine, 4); + appendCommit(engine, 5); + ServerModel server = new ServerModel(); + List clients = new ArrayList<>(); + runToAck(engine, newLoop(engine, server, clients, true), 5L); + Assert.assertEquals(Arrays.asList("0:C1", "0:D2", "0:D3", "0:R", "0:D4", "0:C5"), server.received()); + Assert.assertEquals(Arrays.asList("C1", "D4", "C5"), server.committed()); + Assert.assertEquals(1, clientCount(clients)); + // Nothing changes on this path: the whole log goes out in one write. + Assert.assertEquals(1, clients.get(0).flushes); + } + }); + } + + @Test + public void testRollbackFrameNeverReachesServerWithoutRollback() throws Exception { + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendCommit(engine, 1); + appendDeferred(engine, 2); + appendDeferred(engine, 3); + appendRollback(engine); + appendDeferred(engine, 4); + appendCommit(engine, 5); + ServerModel server = new ServerModel(); + List clients = new ArrayList<>(); + runToAck(engine, newLoop(engine, server, clients, false), 5L); + // The frames ahead of the rollback frame went out in one batch with it + // held back; closing the connection discarded 2 and 3, and the next + // connection starts past the rollback frame. + Assert.assertEquals(Arrays.asList("0:C1", "0:D2", "0:D3", "1:D4", "1:C5"), server.received()); + Assert.assertEquals(Arrays.asList("C1", "D4", "C5"), server.committed()); + Assert.assertEquals(2, clientCount(clients)); + Assert.assertEquals(1, clients.get(0).flushes); + Assert.assertEquals(1, clients.get(1).flushes); + } + }); + } + + @Test + public void testRollbackSupportIsDecidedPerConnection() throws Exception { + // The first connection reaches a server without rollback support, the second one + // a server with it: the second rollback frame goes out. + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendDeferred(engine, 1); + appendRollback(engine); + appendDeferred(engine, 2); + appendRollback(engine); + appendDeferred(engine, 3); + appendCommit(engine, 4); + ServerModel server = new ServerModel(); + List clients = new ArrayList<>(); + boolean[] isRollbackConfirmed = {false, true}; + CursorWebSocketSendLoop loop = new CursorWebSocketSendLoop( + null, engine, 0L, + () -> newClient(server, clients, isRollbackConfirmed[clientCount(clients)], false), + 1L, 5L); + runToAck(engine, loop, 5L); + Assert.assertEquals(Arrays.asList("0:D1", "1:D2", "1:R", "1:D3", "1:C4"), server.received()); + Assert.assertEquals(Arrays.asList("D3", "C4"), server.committed()); + Assert.assertEquals(2, clientCount(clients)); + } + }); + } + + @Test + public void testOnlyTheRollbackFrameIsHeldBack() throws Exception { + // Bare 12-byte headers that are not the rollback frame -- an empty commit, an empty + // deferred frame and a foreign payload -- go out like any frame. Mistaking the + // empty commit for a rollback frame would discard the transaction it commits. + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendDeferred(engine, 1); + appendHeader(engine, QwpConstants.MAGIC_MESSAGE, (byte) 0); + appendHeader(engine, QwpConstants.MAGIC_MESSAGE, QwpConstants.FLAG_DEFER_COMMIT); + appendHeader(engine, 0, QwpConstants.ROLLBACK_FRAME_FLAGS); + appendDeferred(engine, 2); + appendRollback(engine); + appendDeferred(engine, 3); + appendCommit(engine, 4); + ServerModel server = new ServerModel(); + List clients = new ArrayList<>(); + runToAck(engine, newLoop(engine, server, clients, false), 7L); + Assert.assertEquals(Arrays.asList("0:D1", "0:C0", "0:D0", "0:X12", "0:D2", "1:D3", "1:C4"), + server.received()); + Assert.assertEquals(Arrays.asList("D1", "C0", "D0", "X12", "D3", "C4"), server.committed()); + Assert.assertEquals(2, clientCount(clients)); + } + }); + } + + @Test + public void testRollbackWaitsForCommitAcksBeforeRecycling() throws Exception { + // The server holds the frames ahead of the rollback frame unprocessed. Recycling + // now would lose commit 1 with the connection: the self-acknowledge of the + // rollback frame covers it, so it would never be replayed. + assertRollbackWaitsForAckOf(false, engine -> appendCommit(engine, 1), "C1"); + } + + @Test + public void testRollbackWaitsForDurableAckBeforeRecycling() throws Exception { + // In durable-ack mode the trim watermark advances only on the durable ack, which + // the server holds back. The OK of commit 1 alone must not let the loop recycle, + // or it would trim commit 1 before the server made it durable. + assertRollbackWaitsForAckOf(true, engine -> appendCommit(engine, 1), "C1"); + } + + @Test + public void testRollbackWaitsForForeignFrameAck() throws Exception { + // A payload that is not a QWP message cannot be told to be deferred, so the loop + // waits for its ack like for a commit's: the safe side. + assertRollbackWaitsForAckOf(false, engine -> appendForeign(engine, 16), "X16"); + } + + @Test + public void testRollbackWaitsForShortFrameAck() throws Exception { + // Same for a payload too short to hold a QWP header. + assertRollbackWaitsForAckOf(false, engine -> appendForeign(engine, 8), "X8"); + } + + private static void appendCommit(CursorSendEngine engine, int id) { + appendFrame(engine, (byte) 0, id); + } + + private static void appendDeferred(CursorSendEngine engine, int id) { + appendFrame(engine, QwpConstants.FLAG_DEFER_COMMIT, id); + } + + // A payload without the QWP magic. + private static void appendForeign(CursorSendEngine engine, int size) { + long buf = Unsafe.malloc(size, MemoryTag.NATIVE_DEFAULT); + try { + Unsafe.getUnsafe().setMemory(buf, size, (byte) 'x'); + engine.appendBlocking(buf, size); + } finally { + Unsafe.free(buf, size, MemoryTag.NATIVE_DEFAULT); + } + } + + // A QWP header whose flags byte says what the frame is, followed by its id. + private static void appendFrame(CursorSendEngine engine, byte flags, int id) { + int size = QwpConstants.HEADER_SIZE + 4; + long buf = Unsafe.malloc(size, MemoryTag.NATIVE_DEFAULT); + try { + Unsafe.getUnsafe().setMemory(buf, size, (byte) 0); + Unsafe.getUnsafe().putInt(buf, QwpConstants.MAGIC_MESSAGE); + Unsafe.getUnsafe().putByte(buf + 4, QwpConstants.VERSION); + Unsafe.getUnsafe().putByte(buf + QwpConstants.HEADER_OFFSET_FLAGS, flags); + Unsafe.getUnsafe().putInt(buf + QwpConstants.HEADER_SIZE, id); + engine.appendBlocking(buf, size); + } finally { + Unsafe.free(buf, size, MemoryTag.NATIVE_DEFAULT); + } + } + + // A bare 12-byte header: no table blocks, no payload. + private static void appendHeader(CursorSendEngine engine, int magic, byte flags) { + int size = QwpConstants.HEADER_SIZE; + long buf = Unsafe.malloc(size, MemoryTag.NATIVE_DEFAULT); + try { + Unsafe.getUnsafe().setMemory(buf, size, (byte) 0); + Unsafe.getUnsafe().putInt(buf, magic); + Unsafe.getUnsafe().putByte(buf + 4, QwpConstants.VERSION); + Unsafe.getUnsafe().putByte(buf + QwpConstants.HEADER_OFFSET_FLAGS, flags); + engine.appendBlocking(buf, size); + } finally { + Unsafe.free(buf, size, MemoryTag.NATIVE_DEFAULT); + } + } + + // The rollback control frame, as QwpWebSocketEncoder.encodeRollbackMessage writes it. + private static void appendRollback(CursorSendEngine engine) { + appendHeader(engine, QwpConstants.MAGIC_MESSAGE, QwpConstants.ROLLBACK_FRAME_FLAGS); + } + + // The frame appendAhead writes is the only commit-bearing frame ahead of the rolled-back + // transaction, and the server holds it unprocessed, or in durable mode holds back its + // durable ack. The loop must not recycle until that ack arrives. + private static void assertRollbackWaitsForAckOf( + boolean isDurable, + Consumer appendAhead, + String ahead + ) throws Exception { + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendAhead.accept(engine); + appendDeferred(engine, 2); + appendDeferred(engine, 3); + appendRollback(engine); + appendDeferred(engine, 4); + appendCommit(engine, 5); + ServerModel server = new ServerModel(); + List clients = new ArrayList<>(); + ModelClient first = newClient(server, clients, false, isDurable); + // Durable mode: the server processes and OKs at once, but holds back the + // durable ack. Otherwise it holds back processing, OKs included. + first.isHoldingAcks = true; + AtomicBoolean isFirstConnect = new AtomicBoolean(true); + CursorWebSocketSendLoop loop = new CursorWebSocketSendLoop( + null, engine, 0L, + () -> isFirstConnect.getAndSet(false) ? first : newClient(server, clients, false, isDurable), + 1L, 5L, isDurable ? DurableAckTiers.REPLICATED : DurableAckTiers.NONE, 0L); + try { + loop.start(); + awaitTrue("the frames ahead of the rollback frame go out", () -> first.flushedFrames == 3); + // The loop keeps polling the first connection while it waits for the acks. + int polls = first.polls; + awaitTrue("the loop keeps waiting on its connection", () -> first.polls >= polls + 50); + Assert.assertEquals("no recycle while " + ahead + " is not acked", 1, clientCount(clients)); + Assert.assertEquals(-1L, engine.ackedFsn()); + first.releaseAcks(); + awaitAckedFsn(engine, 5L); + } finally { + loop.close(); + } + Assert.assertEquals(Arrays.asList("0:" + ahead, "0:D2", "0:D3", "1:D4", "1:C5"), server.received()); + Assert.assertEquals(Arrays.asList(ahead, "D4", "C5"), server.committed()); + Assert.assertEquals(2, clientCount(clients)); + } + }); + } + + private static void awaitAckedFsn(CursorSendEngine engine, long target) throws InterruptedException { + awaitTrue("ackedFsn reaches " + target, () -> engine.ackedFsn() >= target); + Assert.assertEquals(target, engine.ackedFsn()); + } + + private static void awaitTrue(String what, BooleanSupplier condition) throws InterruptedException { + long deadline = System.nanoTime() + 10_000_000_000L; + while (!condition.getAsBoolean()) { + if (System.nanoTime() > deadline) { + Assert.fail("timed out: " + what); + } + Thread.sleep(1); + } + } + + private static int clientCount(List clients) { + synchronized (clients) { + return clients.size(); + } + } + + private static ModelClient newClient(ServerModel server, List clients, boolean isRollbackConfirmed, boolean isDurable) { + synchronized (clients) { + ModelClient client = new ModelClient(server, clients.size(), isRollbackConfirmed, isDurable); + clients.add(client); + return client; + } + } + + private static CursorSendEngine newEngine() { + return new CursorSendEngine(null, SEGMENT_SIZE_BYTES); + } + + private static CursorWebSocketSendLoop newLoop(CursorSendEngine engine, ServerModel server, List clients, boolean isRollbackConfirmed) { + return new CursorWebSocketSendLoop( + null, engine, 0L, + () -> newClient(server, clients, isRollbackConfirmed, false), + 1L, 5L); + } + + private static void runRandomTransactions(Rnd rnd) throws Exception { + try (CursorSendEngine engine = newEngine()) { + List expectedCommitted = new ArrayList<>(); + List transaction = new ArrayList<>(); + int rollbacks = 0; + int nextId = 1; + // Appended before the loop starts, the rest while it runs. + List appends = new ArrayList<>(); + for (int t = 0, n = 1 + rnd.nextInt(12); t < n; t++) { + transaction.clear(); + for (int i = 0, k = rnd.nextInt(4); i < k; i++) { + int id = nextId++; + transaction.add("D" + id); + appends.add(() -> appendDeferred(engine, id)); + } + if (rnd.nextInt(5) < 3) { + int id = nextId++; + transaction.add("C" + id); + expectedCommitted.addAll(transaction); + appends.add(() -> appendCommit(engine, id)); + } else { + rollbacks++; + appends.add(() -> appendRollback(engine)); + } + } + int beforeStart = rnd.nextInt(appends.size() + 1); + for (int i = 0; i < beforeStart; i++) { + appends.get(i).run(); + } + ServerModel server = new ServerModel(); + List clients = new ArrayList<>(); + Rnd ioRnd = new Rnd(rnd.nextLong(), rnd.nextLong()); + CursorWebSocketSendLoop loop = new CursorWebSocketSendLoop( + null, engine, 0L, + () -> newClient(server, clients, ioRnd.nextBoolean(), false), + 1L, 5L); + int retired; + try { + loop.start(); + for (int i = beforeStart, n = appends.size(); i < n; i++) { + appends.get(i).run(); + } + awaitAckedFsn(engine, appends.size() - 1L); + // Every rollback frame is received or retired by now. A retired one acks + // itself before its recycle connects, so when it is the last frame the + // recycle may still be under way. + retired = rollbacks - server.rollbacksReceived(); + awaitTrue("one recycle per retired rollback frame", () -> clientCount(clients) == 1 + retired); + } finally { + loop.close(); + } + String shape = "frames=" + appends.size() + ", received=" + server.received(); + Assert.assertEquals(shape, expectedCommitted, server.committed()); + Assert.assertEquals(shape, 0, server.rollbacksToServerWithoutRollback()); + Assert.assertEquals(shape, 1 + retired, clientCount(clients)); + } + } + + private static void runToAck(CursorSendEngine engine, CursorWebSocketSendLoop loop, long lastFsn) throws Exception { + try { + loop.start(); + awaitAckedFsn(engine, lastFsn); + } finally { + loop.close(); + } + } + + /** + * One connection to {@link ServerModel}: frames a batch flush hands over are in + * flight until the I/O loop polls, which is when the server processes them, unless + * it holds its acks. Acks are cumulative, so only the highest pending one goes out. + */ + private static final class ModelClient extends TestWebSocketClient { + private final List batch = new ArrayList<>(); + private final int connection; + private final ArrayDeque inFlight = new ArrayDeque<>(); + private final boolean isDurable; + private final boolean isRollbackConfirmed; + private final ServerModel server; + volatile int flushedFrames; + volatile int flushes; + volatile boolean isHoldingAcks; + volatile int polls; + private long durableReported; + private long nextSeq; + private long pendingOkSeq = -1L; + private long pendingOkSeqTxn; + + ModelClient(ServerModel server, int connection, boolean isRollbackConfirmed, boolean isDurable) { + super(DefaultHttpClientConfiguration.INSTANCE, PlainSocketFactory.INSTANCE); + this.server = server; + this.connection = connection; + this.isRollbackConfirmed = isRollbackConfirmed; + this.isDurable = isDurable; + } + + @Override + public synchronized void batchAppendBinary(long dataPtr, int length) { + batch.add(Frame.read(dataPtr, length)); + } + + @Override + public synchronized void batchFlush() { + inFlight.addAll(batch); + flushedFrames += batch.size(); + flushes++; + batch.clear(); + } + + @Override + public synchronized void close() { + // Whatever the server has not processed yet never arrives. + inFlight.clear(); + server.close(connection); + super.close(); + } + + @Override + public boolean isServerRollbackEnabled() { + return isRollbackConfirmed; + } + + synchronized void releaseAcks() { + isHoldingAcks = false; + } + + @Override + public void sendPing() { + } + + @Override + public synchronized boolean tryReceiveFrame(WebSocketFrameHandler handler) { + polls++; + // Durable mode: the server processes and OKs at once and holds back the + // durable ack. Otherwise holding back the acks means not processing at all. + if (isDurable || !isHoldingAcks) { + for (Frame frame; (frame = inFlight.pollFirst()) != null; ) { + long seq = nextSeq++; + if (server.process(connection, isRollbackConfirmed, frame)) { + pendingOkSeq = seq; + pendingOkSeqTxn = frame.kind == 'R' ? 0 : server.seqTxn(); + } + } + } + if (pendingOkSeq >= 0) { + sendOk(handler, pendingOkSeq, isDurable && pendingOkSeqTxn > 0 ? pendingOkSeqTxn : 0); + pendingOkSeq = -1L; + return true; + } + if (isDurable && !isHoldingAcks && server.seqTxn() > durableReported) { + durableReported = server.seqTxn(); + sendDurableAck(handler, durableReported); + return true; + } + return false; + } + + // STATUS_DURABLE_ACK: status, then the table entries. + private static void sendDurableAck(WebSocketFrameHandler handler, long seqTxn) { + byte[] name = TABLE.getBytes(StandardCharsets.UTF_8); + int size = 1 + 2 + 2 + name.length + 8; + long ptr = Unsafe.malloc(size, MemoryTag.NATIVE_DEFAULT); + try { + Unsafe.getUnsafe().putByte(ptr, WebSocketResponse.STATUS_DURABLE_ACK); + putTableEntry(ptr + 1, name, seqTxn); + handler.onBinaryMessage(ptr, size); + } finally { + Unsafe.free(ptr, size, MemoryTag.NATIVE_DEFAULT); + } + } + + // STATUS_OK: status, cumulative wire sequence, then the table entries -- one for + // a commit in durable mode, so the OK waits for the durable ack covering it. + private static void sendOk(WebSocketFrameHandler handler, long seq, long seqTxn) { + byte[] name = TABLE.getBytes(StandardCharsets.UTF_8); + int size = 1 + 8 + 2 + (seqTxn > 0 ? 2 + name.length + 8 : 0); + long ptr = Unsafe.malloc(size, MemoryTag.NATIVE_DEFAULT); + try { + Unsafe.getUnsafe().putByte(ptr, WebSocketResponse.STATUS_OK); + Unsafe.getUnsafe().putLong(ptr + 1, seq); + if (seqTxn > 0) { + putTableEntry(ptr + 9, name, seqTxn); + } else { + Unsafe.getUnsafe().putShort(ptr + 9, (short) 0); + } + handler.onBinaryMessage(ptr, size); + } finally { + Unsafe.free(ptr, size, MemoryTag.NATIVE_DEFAULT); + } + } + + private static void putTableEntry(long p, byte[] name, long seqTxn) { + Unsafe.getUnsafe().putShort(p, (short) 1); + Unsafe.getUnsafe().putShort(p + 2, (short) name.length); + for (int i = 0; i < name.length; i++) { + Unsafe.getUnsafe().putByte(p + 4 + i, name[i]); + } + Unsafe.getUnsafe().putLong(p + 4 + name.length, seqTxn); + } + + @Override + protected void ioWait(int timeout, int op) { + } + + @Override + protected void setupIoWait() { + } + } + + // A frame as the server sees it: D (deferred), C (commit), R (the rollback frame), or + // X, a payload that is not a QWP message, labelled with its size. A frame's id + // follows its header; a bare header has id 0. + private static final class Frame { + final char kind; + final String label; + + Frame(char kind, String label) { + this.kind = kind; + this.label = label; + } + + static Frame read(long ptr, int length) { + if (length < QwpConstants.HEADER_SIZE || Unsafe.getUnsafe().getInt(ptr) != QwpConstants.MAGIC_MESSAGE) { + return new Frame('X', "X" + length); + } + byte flags = Unsafe.getUnsafe().getByte(ptr + QwpConstants.HEADER_OFFSET_FLAGS); + if (length == QwpConstants.HEADER_SIZE && flags == QwpConstants.ROLLBACK_FRAME_FLAGS) { + return new Frame('R', "R"); + } + char kind = (flags & QwpConstants.FLAG_DEFER_COMMIT) != 0 ? 'D' : 'C'; + int id = length > QwpConstants.HEADER_SIZE ? Unsafe.getUnsafe().getInt(ptr + QwpConstants.HEADER_SIZE) : 0; + return new Frame(kind, kind + Integer.toString(id)); + } + + @Override + public String toString() { + return label; + } + } + + /** + * What the QuestDB server makes of the frames, per connection: a deferred frame + * joins the connection's open group; a commit frame commits the group and itself + * and is acked; the rollback frame discards the group and is acked on a connection + * that confirmed rollback. A server without rollback support reads the rollback + * frame as an empty deferred frame, so the group stays open and the next commit on + * the connection commits it. A closed connection leaves its group uncommitted. A + * foreign payload is acked like a commit, so the loop's wait for it ends. + */ + private static final class ServerModel { + private final List committed = new ArrayList<>(); + private final List> groups = new ArrayList<>(); + private final List received = new ArrayList<>(); + private int rollbacksReceived; + private int rollbacksToServerWithoutRollback; + private long seqTxn; + + synchronized void close(int connection) { + group(connection).clear(); + } + + synchronized List committed() { + return new ArrayList<>(committed); + } + + // Whether the server acks the frame. + synchronized boolean process(int connection, boolean isRollbackConfirmed, Frame frame) { + received.add(connection + ":" + frame); + List group = group(connection); + switch (frame.kind) { + case 'C': + case 'X': + committed.addAll(group); + committed.add(frame.label); + group.clear(); + seqTxn++; + return true; + case 'R': + rollbacksReceived++; + if (isRollbackConfirmed) { + group.clear(); + return true; + } + rollbacksToServerWithoutRollback++; + return false; + default: + group.add(frame.label); + return false; + } + } + + synchronized List received() { + return new ArrayList<>(received); + } + + synchronized int rollbacksReceived() { + return rollbacksReceived; + } + + synchronized int rollbacksToServerWithoutRollback() { + return rollbacksToServerWithoutRollback; + } + + synchronized long seqTxn() { + return seqTxn; + } + + private List group(int connection) { + while (groups.size() <= connection) { + groups.add(new ArrayList<>()); + } + return groups.get(connection); + } + } +} From 4749d5d5b7067521bb92660a85e4e72628564e09 Mon Sep 17 00:00:00 2001 From: Vlad Ilyushchenko Date: Thu, 12 Nov 2026 16:20:01 +0000 Subject: [PATCH 05/20] Decide strict mode from the auto-flush triggers auto_flush=off made a WebSocket sender a strict transaction of any size, while auto_flush_rows=off with auto_flush_interval=off, the same trigger state, built a non-transactional sender with no byte trigger: each flush went out as one batch, which failed past about 2 MiB per table, and close() committed. The builder keyed the mode on the auto_flush=off spelling, and recomputeFrameBudget() turned the byte trigger off for exactly that non-transactional sender. HTTP already treats both spellings alike. The builder now reads the trigger state. A sender with no auto-flush trigger (no row or interval trigger, no positive auto_flush_bytes) is in strict transactional mode unless transaction= picks the mode. transaction=on keeps it non-strict, so close() commits; auto_flush=off used to override it to strict. transaction=off is rejected for every spelling, as nothing but flush() could commit and a non-transactional flush must fit one frame. auto_flush=off with a positive auto_flush_bytes is rejected, as auto_flush=off with auto_flush_rows=N already was. auto_flush_bytes=off keeps its contract: no frame sizing, so each batch must fit one frame per table. recomputeFrameBudget() no longer special-cases the manual-flush sender, which the builder can no longer build. Behaviour change: a sender, or a pool, configured with auto_flush_rows=off and auto_flush_interval=off now discards the rows it did not flush when it closes or returns a lease, like HTTP and auto_flush=off, where it used to commit them. close() and lease return now log a WARN with the row count when they discard an uncommitted strict transaction, so a caller that relied on close() to commit sees it. A lease returned without server rollback support now aborts its transaction before the pool retires the connection, so the retiring close() does not report the same rows again. QwpLargeTransactionTest runs every spelling of "no trigger" (both config strings and both builder forms) through the same strict transaction of any size and the close() discard, and covers transaction=on committing on close, the rejections, auto_flush_bytes as the only trigger, auto_flush_bytes=off, one trigger left, the WARN on close and on lease return with and without server rollback, and an aborted lease retiring quietly. It replaces testManualFlushKeepsOneCommitPerFlush, which pinned the old split. LineSenderBuilderWebSocketTest and QuestDBBuilderTest cover the builder and the pool config paths. --- .../main/java/io/questdb/client/QuestDB.java | 6 +- .../main/java/io/questdb/client/Sender.java | 80 +++- .../qwp/client/QwpWebSocketSender.java | 50 +- .../client/TransactionTooLargeException.java | 11 +- .../io/questdb/client/impl/PooledSender.java | 4 +- .../client/test/QuestDBBuilderTest.java | 26 +- .../LineSenderBuilderWebSocketTest.java | 71 ++- .../qwp/client/QwpLargeTransactionTest.java | 429 ++++++++++++++++-- 8 files changed, 583 insertions(+), 94 deletions(-) diff --git a/core/src/main/java/io/questdb/client/QuestDB.java b/core/src/main/java/io/questdb/client/QuestDB.java index 8cfc437b7..02a0cb6de 100644 --- a/core/src/main/java/io/questdb/client/QuestDB.java +++ b/core/src/main/java/io/questdb/client/QuestDB.java @@ -139,7 +139,11 @@ static QuestDB connect(CharSequence configurationString, HttpTokenProvider token * {@link Sender#close()} on the returned instance to release it back to * the pool. {@code close()} on a pooled Sender flushes pending rows * before returning to the pool; a real disconnect only happens at - * {@link #close()} on this {@code QuestDB} handle. + * {@link #close()} on this {@code QuestDB} handle. A Sender in strict + * transactional mode ({@code transaction=strict}, or a WebSocket config + * with no auto-flush trigger, such as {@code auto_flush=off}) commits only + * on {@link Sender#flush()}, so its {@code close()} discards the rows it + * did not flush instead. *

* Allocation: zero at steady state -- the returned instance is a * pre-allocated decorator backed by a pre-allocated underlying Sender. diff --git a/core/src/main/java/io/questdb/client/Sender.java b/core/src/main/java/io/questdb/client/Sender.java index bb5709e69..c65f15412 100644 --- a/core/src/main/java/io/questdb/client/Sender.java +++ b/core/src/main/java/io/questdb/client/Sender.java @@ -1150,10 +1150,12 @@ final class LineSenderBuilder { private final IntList ports = new IntList(); private long authTimeoutMillis = QwpWebSocketSender.DEFAULT_AUTH_TIMEOUT_MS; private int autoFlushBytes = PARAMETER_NOT_SET_EXPLICITLY; - // Set by disableAutoFlush(). auto_flush_interval=off also stores the interval as - // Integer.MAX_VALUE, so the WebSocket validation keys on this flag to reject only the - // full disable and accept the interval-only opt-out. - private boolean autoFlushDisabled; + // disableAutoFlush() (auto_flush=off) sets it. That call turns off every + // auto-flush trigger, so a positive auto_flush_bytes contradicts it, and only + // that conflict check reads this flag. auto_flush_rows=off with + // auto_flush_interval=off reaches the same trigger state, which is what + // hasAutoFlushTrigger() reads to pick the sender's mode. + private boolean isAutoFlushDisabled; private int autoFlushIntervalMillis = PARAMETER_NOT_SET_EXPLICITLY; private int autoFlushRows = PARAMETER_NOT_SET_EXPLICITLY; private int bufferCapacity = PARAMETER_NOT_SET_EXPLICITLY; @@ -1422,7 +1424,13 @@ public LineSenderBuilder authTimeoutMillis(long millis) { *
* This is only used when communicating over WebSocket transport. *
- * Default value is 0, which disables byte-based auto-flush. + * By default the byte trigger fires at 90% of the largest frame the connection can carry: the server's + * advertised maximum batch size, or the store-and-forward segment when that is smaller. A positive value sets + * the trigger, capped at that size, and counts as an auto-flush trigger: unless the sender is transactional, + * every batch it sends commits. 0 turns the byte trigger off, and then every batch must fit one frame per + * table. + *
+ * You cannot set a positive value when auto-flush is disabled. See {@link #disableAutoFlush()}. * * @param bytes maximum bytes per batch * @return this instance for method chaining @@ -1434,6 +1442,8 @@ public LineSenderBuilder autoFlushBytes(int bytes) { if (this.autoFlushBytes != PARAMETER_NOT_SET_EXPLICITLY) { throw new LineSenderException("auto flush bytes was already configured") .put("[bytes=").put(this.autoFlushBytes).put("]"); + } else if (isAutoFlushDisabled && bytes > 0) { + throw new LineSenderException("cannot set auto flush bytes when auto-flush is already disabled"); } if (bytes < 0) { throw new LineSenderException("auto flush bytes cannot be negative") @@ -1492,7 +1502,9 @@ public LineSenderBuilder autoFlushIntervalMillis(int autoFlushIntervalMillis) { * Setting this to 1 means that the Sender will send each row to a server immediately after it is added. This * effectively disables batching and may lead to a significant performance degradation. *
- * Setting this to 0 disables row-based auto-flush. Interval-based auto-flush remains enabled. + * Setting this to 0 disables row-based auto-flush. Interval-based auto-flush remains enabled. On WebSocket, a + * sender whose interval trigger is off too, and that has no positive {@link #autoFlushBytes(int)}, has no + * auto-flush trigger left and works like one built with {@link #disableAutoFlush()}. *

* You cannot set this value when auto-flush is disabled. See {@link #disableAutoFlush()}. * @@ -1906,10 +1918,16 @@ public LineSenderBuilder connectionListenerInboxCapacity(int capacity) { * It is essential to ensure the maximum buffer capacity is sufficient to accommodate all locally buffered data. *

* This method can be used with the HTTP and WebSocket protocols; calling it is illegal when communicating over - * the TCP protocol. On WebSocket it selects strict transactional mode (see - * {@link #strictTransactional(boolean)}): rows still go to the server in frames sized for the connection, so a - * batch can be any size, but only {@code flush()} commits them, and closing without a flush discards them. - * There, {@code auto_flush_interval=off} alone turns off only the time-based trigger. + * the TCP protocol. Turning off both the row and the interval trigger ({@code auto_flush_rows=off} and + * {@code auto_flush_interval=off}) has the same effect. + *

+ * On WebSocket, a sender with no auto-flush trigger is in strict transactional mode (see + * {@link #strictTransactional(boolean)}) unless {@link #transactional(boolean)} selects the mode: rows still go + * to the server in frames sized for the connection, so a batch can be any size, but only {@code flush()} + * commits them, and closing the sender or returning a pooled sender without a flush discards them. + * {@code transactional(true)} keeps such a sender non-strict, so closing it commits, and + * {@code transactional(false)} cannot be combined with it. Nor can a positive {@link #autoFlushBytes(int)}, + * which is an auto-flush trigger. * * @return this instance for method chaining * @see #autoFlushRows(int) @@ -1924,10 +1942,14 @@ public LineSenderBuilder disableAutoFlush() { throw new LineSenderException("auto flush interval was already configured ") .put("[autoFlushIntervalMillis=").put(this.autoFlushIntervalMillis).put("]"); } + if (this.autoFlushBytes > 0) { + throw new LineSenderException("auto flush bytes was already configured ") + .put("[autoFlushBytes=").put(this.autoFlushBytes).put("]"); + } this.autoFlushRows = AUTO_FLUSH_DISABLED; this.autoFlushIntervalMillis = Integer.MAX_VALUE; - this.autoFlushDisabled = true; + this.isAutoFlushDisabled = true; return this; } @@ -2807,7 +2829,9 @@ private LineSenderBuilder requestDurableAckTiers(int tiers) { * {@link io.questdb.client.cutlass.qwp.client.TransactionTooLargeException} * and leaves the transaction open, and {@code close()} without * {@code flush()} discards the transaction instead of committing it. - * {@code auto_flush=off} selects the same mode. WebSocket transport only. + * A sender with no auto-flush trigger (see {@link #disableAutoFlush()}) is + * in this mode unless {@link #transactional(boolean)} selects the mode. + * WebSocket transport only. * * @param enabled true to enable strict transactional mode; false leaves * {@link #transactional(boolean) transactional} mode as set @@ -2833,6 +2857,11 @@ public LineSenderBuilder strictTransactional(boolean enabled) { * committing atomically per table. The server commits a table on its own * once {@code qwp.max.uncommitted.rows} of its rows are uncommitted; use * {@link #strictTransactional(boolean)} to fail instead. + *

+ * A sender with no auto-flush trigger (see {@link #disableAutoFlush()}) is + * in strict transactional mode unless this method selects the mode: + * {@code true} keeps it in this non-strict mode, and {@code false} cannot + * be combined with it. * * @param enabled true to enable transactional mode * @return this instance for method chaining @@ -3896,9 +3925,9 @@ private QwpWebSocketSender buildWebSocket(HttpTokenProvider tokenProvider) { // dispatcher daemon, drainer pool, microbatch buffers and // WebSocketClient inside the abandoned `connected`. connected.setTransactional(transactional); - // auto_flush=off on WebSocket means "commit only when I flush()": a - // strict transaction of any size. - if (strictTransactional || autoFlushDisabled) { + // With no auto-flush trigger only flush() commits: a strict transaction of + // any size, unless transaction= chose the mode. + if (strictTransactional || (!transactionModeSet && !hasAutoFlushTrigger())) { connected.setStrictTransactional(true); } try { @@ -4948,6 +4977,16 @@ public java.util.Map wsConfigSnapshotForTest() { return m; } + // True when a configured trigger flushes rows on its own: the row or interval + // trigger, or a positive auto_flush_bytes. auto_flush=off, and + // auto_flush_rows=off with auto_flush_interval=off, leave none. The WebSocket + // default byte trigger does not count: it only sizes frames. + private boolean hasAutoFlushTrigger() { + return autoFlushRows != AUTO_FLUSH_DISABLED + || autoFlushIntervalMillis != Integer.MAX_VALUE + || autoFlushBytes > 0; + } + /** * Use HTTP protocol as transport. *
@@ -5151,10 +5190,13 @@ private void validateParameters() { if (protocolVersion != PARAMETER_NOT_SET_EXPLICITLY) { throw new LineSenderException("protocol version is not supported for WebSocket protocol"); } - if (autoFlushDisabled && transactionModeSet && !transactional) { - // On WebSocket, auto_flush=off is strict transactional mode. - throw new LineSenderException("auto_flush=off selects strict transactional mode on WebSocket " - + "and cannot be combined with transaction=off"); + if (transactionModeSet && !transactional && !hasAutoFlushTrigger()) { + // Only flush() can commit this sender's rows, and a non-transactional + // flush has to fit one frame per table. + throw new LineSenderException("auto-flush is off (auto_flush=off, or auto_flush_rows=off and " + + "auto_flush_interval=off), which on WebSocket selects strict transactional mode and " + + "cannot be combined with transaction=off; set transaction=on or turn on an auto-flush " + + "trigger"); } if ((sfDurability == SfDurability.FLUSH || sfDurability == SfDurability.APPEND)) { throw new LineSenderException( diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java index 0e0b28c02..624d2bc80 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java @@ -140,9 +140,7 @@ public class QwpWebSocketSender implements Sender { * {@code autoFlushBytes} value that sizes the byte trigger from the frames the * connection can carry: 90% of the smaller of the server's advertised * {@code X-QWP-Max-Batch-Size} and the store-and-forward segment. It is the - * builder default, so a batch never grows past what one frame can hold. A pure - * manual-flush sender (non-transactional, row and interval triggers off) keeps - * no byte trigger, as before. + * builder default, so a batch never grows past what one frame can hold. */ public static final int AUTO_FLUSH_BYTES_AUTO = -1; public static final long DEFAULT_AUTH_TIMEOUT_MS = 15_000L; @@ -709,8 +707,8 @@ public class QwpWebSocketSender implements Sender { // True when the current foreground connection confirmed X-QWP-Rollback, so the // rollback control frame may go out. Captured on each FOREGROUND handshake. private volatile boolean serverRollbackEnabled; - // Strict transactional mode (transaction=strict, or auto_flush=off on this - // transport): implies transactional, never lets an open transaction commit in + // Strict transactional mode (transaction=strict, or a sender with no auto-flush + // trigger): implies transactional, never lets an open transaction commit in // parts, and close() discards instead of committing. See setStrictTransactional. private boolean strictTransactional; // Set once the open transaction can no longer be rolled back or committed as @@ -1866,6 +1864,9 @@ private void close0(boolean[] restoreInterrupt) { // ack the drain below waits for; any other server rolls them back // when the connection closes, and a recovered slot retires them // as an aborted transaction. + if (!txnAborted) { + warnDiscardedTransaction("close()"); + } discardPendingRows(); if (hasDeferredMessages && serverRollbackEnabled && !txnAborted) { try { @@ -3454,6 +3455,9 @@ public void rollback() { */ public boolean discardTransactionForReuse() { checkNotClosed(); + if (!txnAborted) { + warnDiscardedTransaction("returning the sender to the pool"); + } discardPendingRows(); if (txnAborted) { return false; @@ -3463,6 +3467,10 @@ public boolean discardTransactionForReuse() { return true; } if (!serverRollbackEnabled) { + // Only closing the connection discards the frames already sent, so the + // transaction is over. Aborting it also keeps the close() that retires + // the connection from warning about the same rows again. + txnAborted = true; return false; } rollbackOpenTransaction(); @@ -3826,7 +3834,6 @@ public void setStrictTransactional(boolean strict) { if (strict) { this.transactional = true; } - recomputeFrameBudget(); } /** @@ -3839,7 +3846,6 @@ public void setTransactional(boolean transactional) { if (!transactional) { this.strictTransactional = false; } - recomputeFrameBudget(); } /** @@ -7620,9 +7626,9 @@ private static boolean isTransactionFrame(long payloadAddr, int payloadLen) { * trigger off. *

  • {@link #AUTO_FLUSH_BYTES_AUTO} sets the trigger to 90% of the frame * size, assuming the server's default cap when nothing is advertised, so - * that a batch never grows past what one frame can carry. A pure - * manual-flush sender (not transactional, row and interval triggers off) - * keeps no byte trigger, so its flush stays one commit as before.
  • + * that a batch never grows past what one frame can carry. The builder makes + * a sender with no other auto-flush trigger transactional, so this trigger + * never splits such a sender's flush into several commits. * */ private void recomputeFrameBudget() { @@ -7634,8 +7640,7 @@ private void recomputeFrameBudget() { long limit = advertised > 0 ? budget : (segmentPayload == Long.MAX_VALUE ? Long.MAX_VALUE : segmentPayload * 9 / 10); effectiveAutoFlushBytes = (int) Math.min(autoFlushBytes, limit); - } else if (autoFlushBytes == AUTO_FLUSH_BYTES_AUTO - && (transactional || autoFlushRows > 0 || autoFlushIntervalNanos > 0)) { + } else if (autoFlushBytes == AUTO_FLUSH_BYTES_AUTO) { effectiveAutoFlushBytes = (int) budget; } else { effectiveAutoFlushBytes = 0; @@ -7676,6 +7681,27 @@ private LineSenderException transactionAbortedError() { + "the sender to discard them; the server rolls them back when the connection closes"); } + /** + * Strict mode commits only on flush(), so closing the sender or returning a + * pooled lease discards the open transaction. Logs it when the transaction holds + * rows: a caller that relied on close() to commit, as a sender with auto-flush + * triggers does, would otherwise lose them without a trace. Counts the rows + * already sent in deferred frames and those still buffered; call it before + * discardPendingRows() clears the latter. + */ + private void warnDiscardedTransaction(String action) { + long rows = pendingRowCount; + for (int i = 0, n = txnTables.size(); i < n; i++) { + rows += txnTables.getQuick(i).getTxnSentRows(); + } + if (rows > 0) { + LOG.warn("{} discarded an uncommitted transaction of {} rows: a strict transactional sender " + + "(transaction=strict, or one with no auto-flush trigger) commits only on flush(). Call " + + "flush() before close() to keep the rows, or ignore this if the discard is intentional", + action, rows); + } + } + /** * Accumulates the current row. * Rows buffer until flush (explicit or auto-flush). diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java index 4374b7337..2c2b0fc8f 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java @@ -27,11 +27,12 @@ import io.questdb.client.cutlass.line.LineSenderException; /** - * A strict transaction ({@code transaction=strict} or {@code auto_flush=off} on the - * WebSocket transport) grew past a limit that would stop it from committing as one - * transaction: the server's per-table {@code qwp.max.uncommitted.rows}, past which - * the server commits the rows on its own, or the client's {@code sf_max_total_bytes}, - * which must hold the whole uncommitted transaction until the server commits it. + * A strict transaction ({@code transaction=strict}, or a sender with no auto-flush + * trigger such as {@code auto_flush=off}, on the WebSocket transport) grew past a + * limit that would stop it from committing as one transaction: the server's + * per-table {@code qwp.max.uncommitted.rows}, past which the server commits the + * rows on its own, or the client's {@code sf_max_total_bytes}, which must hold the + * whole uncommitted transaction until the server commits it. *

    * Thrown before anything that would cross the limit reaches the server, and the * transaction stays open: the caller can still commit the rows accepted so far diff --git a/core/src/main/java/io/questdb/client/impl/PooledSender.java b/core/src/main/java/io/questdb/client/impl/PooledSender.java index 1c49b3099..e25bad14f 100644 --- a/core/src/main/java/io/questdb/client/impl/PooledSender.java +++ b/core/src/main/java/io/questdb/client/impl/PooledSender.java @@ -48,7 +48,9 @@ *

    * Behaviour difference from a raw Sender: {@link #close()} flushes the buffer * and returns the slot to the pool. The underlying Sender is only truly closed - * when {@link io.questdb.client.QuestDB#close()} shuts the pool down. + * when {@link io.questdb.client.QuestDB#close()} shuts the pool down. A + * WebSocket Sender in strict transactional mode commits only on flush(), so + * there close() discards the open transaction instead of flushing it. *

    * Because the slot is reused across borrows, this wrapper -- not the slot -- * carries the lease identity. A stale handle (held after {@link #close()}, with diff --git a/core/src/test/java/io/questdb/client/test/QuestDBBuilderTest.java b/core/src/test/java/io/questdb/client/test/QuestDBBuilderTest.java index 4dc06fcd6..d15713900 100644 --- a/core/src/test/java/io/questdb/client/test/QuestDBBuilderTest.java +++ b/core/src/test/java/io/questdb/client/test/QuestDBBuilderTest.java @@ -215,12 +215,20 @@ public void testMalformedEgressConfigRejectedAtBuildWithMinZero() { @Test public void testAutoFlushIntervalOffAcceptedAtBuildWithMinZero() { // auto_flush_interval=off turns off only the time-based trigger and is legal on - // WebSocket, alone or with the row trigger off too (only auto_flush=off is rejected). + // WebSocket: alone, with the row trigger off too (a sender with no auto-flush + // trigger, in strict transactional mode), and with a byte trigger left as the + // only one. QuestDB.builder().fromConfig( "ws::addr=127.0.0.1:1;auto_flush_interval=off;sender_pool_min=0;query_pool_min=0;").build().close(); + QuestDB.builder().fromConfig( + "ws::addr=127.0.0.1:1;auto_flush_rows=off;auto_flush_interval=off;" + + "sender_pool_min=0;query_pool_min=0;").build().close(); QuestDB.builder().fromConfig( "ws::addr=127.0.0.1:1;auto_flush_rows=off;auto_flush_interval=off;auto_flush_bytes=65536;" + "sender_pool_min=0;query_pool_min=0;").build().close(); + QuestDB.builder().fromConfig( + "ws::addr=127.0.0.1:1;auto_flush=off;auto_flush_bytes=off;sender_pool_min=0;query_pool_min=0;") + .build().close(); } @Test @@ -229,16 +237,24 @@ public void testMalformedIngressConfigRejectedAtBuildWithMinZero() { // Sender -- yet it must still reject a malformed ingress key in the // single cluster config up front. Covers a typed enum (tls_verify), a // registry-STRING value that only the real Sender parse validates - // (auto_flush_rows), and WebSocket build-time checks: auto_flush=off selects - // strict transactional mode, so it cannot combine with transaction=off, and - // sf_durability=flush is not yet supported. + // (auto_flush_rows), and WebSocket build-time checks: a sender with no + // auto-flush trigger is in strict transactional mode, so it cannot combine + // with transaction=off, auto_flush=off cannot combine with a byte trigger, + // and sf_durability=flush is not yet supported. assertBuildRejected( "wss::addr=127.0.0.1:1;tls_verify=strict;sender_pool_min=0;query_pool_min=0;", "tls_verify"); assertBuildRejected( "ws::addr=127.0.0.1:1;auto_flush_rows=abc;sender_pool_min=0;query_pool_min=0;", "auto_flush_rows"); assertBuildRejected( "ws::addr=127.0.0.1:1;auto_flush=off;transaction=off;sender_pool_min=0;query_pool_min=0;", - "auto_flush=off selects strict transactional mode"); + "which on WebSocket selects strict transactional mode and cannot be combined with transaction=off"); + assertBuildRejected( + "ws::addr=127.0.0.1:1;auto_flush_rows=off;auto_flush_interval=off;transaction=off;" + + "sender_pool_min=0;query_pool_min=0;", + "which on WebSocket selects strict transactional mode and cannot be combined with transaction=off"); + assertBuildRejected( + "ws::addr=127.0.0.1:1;auto_flush=off;auto_flush_bytes=65536;sender_pool_min=0;query_pool_min=0;", + "auto flush bytes was already configured [autoFlushBytes=65536]"); assertBuildRejected( "ws::addr=127.0.0.1:1;sf_durability=flush;sender_pool_min=0;query_pool_min=0;", "not yet supported"); } diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/LineSenderBuilderWebSocketTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/LineSenderBuilderWebSocketTest.java index 0fd081389..f69a58516 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/LineSenderBuilderWebSocketTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/LineSenderBuilderWebSocketTest.java @@ -425,15 +425,28 @@ public void testDefaultIsAsync() { } @Test - public void testDisableAutoFlush_rejectsTransactionOffForWebSocket() { - // On WebSocket, disabling auto-flush selects strict transactional mode, - // which an explicit transactional(false) contradicts. - assertThrowsAny( - Sender.builder(Sender.Transport.WEBSOCKET) + public void testDisableAutoFlush_rejectsPositiveAutoFlushBytes() { + // disableAutoFlush() turns every auto-flush trigger off, so a byte trigger + // contradicts it in either order, as a row or interval trigger does. + assertThrows("cannot set auto flush bytes when auto-flush is already disabled", + () -> Sender.builder(Sender.Transport.WEBSOCKET) .address(LOCALHOST) .disableAutoFlush() - .transactional(false), - "cannot be combined with transaction=off"); + .autoFlushBytes(65_536)); + assertThrows("auto flush bytes was already configured [autoFlushBytes=65536]", + () -> Sender.builder(Sender.Transport.WEBSOCKET) + .address(LOCALHOST) + .autoFlushBytes(65_536) + .disableAutoFlush()); + // 0 turns the byte trigger off, which agrees with it. + Assert.assertNotNull(Sender.builder(Sender.Transport.WEBSOCKET) + .address(LOCALHOST) + .disableAutoFlush() + .autoFlushBytes(0)); + Assert.assertNotNull(Sender.builder(Sender.Transport.WEBSOCKET) + .address(LOCALHOST) + .autoFlushBytes(0) + .disableAutoFlush()); } @Test @@ -793,6 +806,50 @@ public void testNoAddress_fails() { "address not set"); } + @Test + public void testNoAutoFlushTrigger_rejectsTransactionOff() { + // A WebSocket sender with no auto-flush trigger commits only on flush(): it is + // strict unless transactional(true) says otherwise, and transactional(false) + // contradicts it, however the triggers were turned off. + String expected = "auto-flush is off (auto_flush=off, or auto_flush_rows=off and auto_flush_interval=off), " + + "which on WebSocket selects strict transactional mode and cannot be combined with " + + "transaction=off; set transaction=on or turn on an auto-flush trigger"; + assertThrowsAny( + Sender.builder(Sender.Transport.WEBSOCKET) + .address(LOCALHOST) + .disableAutoFlush() + .transactional(false), + expected); + assertThrowsAny( + Sender.builder(Sender.Transport.WEBSOCKET) + .address(LOCALHOST) + .transactional(false) + .disableAutoFlush(), + expected); + assertThrowsAny( + Sender.builder(Sender.Transport.WEBSOCKET) + .address(LOCALHOST) + .autoFlushRows(0) + .autoFlushIntervalMillis(Integer.MAX_VALUE) + .transactional(false), + expected); + assertThrowsAny( + Sender.builder(Sender.Transport.WEBSOCKET) + .address(LOCALHOST) + .autoFlushRows(0) + .autoFlushIntervalMillis(Integer.MAX_VALUE) + .autoFlushBytes(0) + .transactional(false), + expected); + // strictTransactional(false) keeps transactional mode as set: off here. + assertThrowsAny( + Sender.builder(Sender.Transport.WEBSOCKET) + .address(LOCALHOST) + .disableAutoFlush() + .strictTransactional(false), + expected); + } + @Test public void testPortMismatch_fails() { assertThrowsAny( diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index 1bdfa9718..8393c2f6a 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -24,6 +24,10 @@ package io.questdb.client.test.cutlass.qwp.client; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import io.questdb.client.QuestDB; import io.questdb.client.Sender; import io.questdb.client.cutlass.line.LineSenderException; @@ -35,17 +39,20 @@ import io.questdb.client.test.tools.TestUtils; import org.junit.Assert; import org.junit.Test; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; +import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; +import java.util.function.Function; import static io.questdb.client.test.tools.TestUtils.assertMemoryLeak; @@ -60,40 +67,62 @@ */ public class QwpLargeTransactionTest { private static final int CAP = 32 * 1024; + // What closing a sender or returning a pooled lease logs when it discards an open + // strict transaction of 1000 rows, behind the action that discarded it. + private static final String DISCARD_WARNING = " discarded an uncommitted transaction of 1000 rows: a strict " + + "transactional sender (transaction=strict, or one with no auto-flush trigger) commits only on " + + "flush(). Call flush() before close() to keep the rows, or ignore this if the discard is intentional"; + private static final String NO_TRIGGER_TRANSACTION_OFF_ERROR = "auto-flush is off (auto_flush=off, or " + + "auto_flush_rows=off and auto_flush_interval=off), which on WebSocket selects strict transactional " + + "mode and cannot be combined with transaction=off; set transaction=on or turn on an auto-flush trigger"; // ~100 encoded bytes per row: 1000 rows (the default row trigger) are ~100 KB, // three times the 32 KiB cap. private static final String PAD = TestUtils.repeat("x", 90); @Test - public void testAutoFlushOffIsStrictTransactionOfAnySize() throws Exception { + public void testAutoFlushBytesAloneCommitsEachBatch() throws Exception { + // A positive auto_flush_bytes is an auto-flush trigger: with the row and + // interval triggers off, every batch it cuts commits on its own, as before. + // transaction=off may say so explicitly. assertMemoryLeak(() -> { - TxnServer h = new TxnServer(); - try (TestWebSocketServer server = start(h, CAP)) { - try (Sender s = Sender.fromConfig(conf(server) + "auto_flush=off;")) { - Assert.assertTrue(((QwpWebSocketSender) s).isStrictTransactional()); - writeRows(s, "t", 0, 2_000); - // ~200 KB went out as deferred frames before flush(); none commits. - Assert.assertTrue(h.awaitFrames(5)); - Assert.assertEquals(0, h.commitFrames()); - s.flush(); - Assert.assertTrue(s.drain(5_000)); + String[] configs = { + "auto_flush_rows=off;auto_flush_interval=off;auto_flush_bytes=8192;", + "auto_flush_rows=off;auto_flush_interval=off;auto_flush_bytes=8192;transaction=off;" + }; + for (String config : configs) { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + config)) { + QwpWebSocketSender ws = (QwpWebSocketSender) s; + Assert.assertFalse(config, ws.isTransactional()); + Assert.assertEquals(config, 8_192, ws.getEffectiveAutoFlushBytes()); + // ~20 KB: the byte trigger sends at least two batches, and each + // commits before any flush(). + writeRows(s, "t", 0, 200); + Assert.assertTrue(config, h.awaitFrames(2)); + for (TxnFrame f : h.frames) { + Assert.assertTrue(config + ": " + h.frames, f.isCommit()); + } + } + // close() commits the rest. + Assert.assertEquals(config, h.frames, h.committedFrames()); } - assertFramesWithinCap(h, CAP); - assertOneTransaction(h); } }); } @Test - public void testAutoFlushOffRejectsTransactionOff() throws Exception { + public void testAutoFlushOffRejectsPositiveAutoFlushBytes() throws Exception { + // auto_flush=off turns every auto-flush trigger off, so a byte trigger + // contradicts it, as a row or interval trigger already does. The ws:: parser + // applies the trigger keys before auto_flush, whatever their order. + // auto_flush_bytes=off is no trigger; see + // testNoAutoFlushTriggerWithAutoFlushBytesOffSendsOneFramePerFlush. assertMemoryLeak(() -> { - try { - Sender.fromConfig("ws::addr=localhost:1;auto_flush=off;transaction=off;").close(); - Assert.fail("auto_flush=off must not combine with transaction=off"); - } catch (LineSenderException e) { - TestUtils.assertContains(e.getMessage(), - "auto_flush=off selects strict transactional mode on WebSocket"); - } + assertConfigRejected("auto_flush=off;auto_flush_bytes=65536;", + "auto flush bytes was already configured [autoFlushBytes=65536]"); + assertConfigRejected("auto_flush_bytes=65536;auto_flush=off;", + "auto flush bytes was already configured [autoFlushBytes=65536]"); }); } @@ -160,29 +189,6 @@ public void testByteTriggerFollowsSegmentSize() throws Exception { }); } - @Test - public void testManualFlushKeepsOneCommitPerFlush() throws Exception { - // A non-transactional sender with every auto-flush trigger off keeps its - // flush as one commit: no byte trigger splits the batch early. - assertMemoryLeak(() -> { - TxnServer h = new TxnServer(); - try (TestWebSocketServer server = start(h, CAP)) { - try (Sender s = Sender.fromConfig(conf(server) + "auto_flush_rows=off;auto_flush_interval=off;")) { - Assert.assertEquals(0, ((QwpWebSocketSender) s).getEffectiveAutoFlushBytes()); - writeRows(s, "a", 0, 250); - writeRows(s, "b", 0, 250); - Assert.assertEquals(0, h.frames.size()); - s.flush(); - Assert.assertTrue(s.drain(5_000)); - } - // The 50 KB batch splits per table at flush: one deferred frame, one commit. - Assert.assertEquals(2, h.frames.size()); - Assert.assertTrue(h.frames.get(0).isDeferred()); - Assert.assertTrue(h.frames.get(1).isCommit()); - } - }); - } - @Test public void testNewSymbolsCountTowardByteTrigger() throws Exception { // Symbol columns buffer 4-byte ids; the 300-byte strings ride in the frame's @@ -204,6 +210,225 @@ public void testNewSymbolsCountTowardByteTrigger() throws Exception { }); } + @Test + public void testNoAutoFlushTriggerIsStrictTransactionOfAnySize() throws Exception { + // Every way to turn off all auto-flush triggers builds the same sender: a + // strict transaction of any size, which only flush() commits. + // auto_flush_rows=off with auto_flush_interval=off used to send each flush as + // one batch, which failed past the frame cap, and to commit on close(). + assertMemoryLeak(() -> { + for (NoTriggerSpelling spelling : noTriggerSpellings()) { + TxnServer h = new TxnServer(); + List committed = null; + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = spelling.build(conf(server))) { + QwpWebSocketSender ws = (QwpWebSocketSender) s; + Assert.assertTrue(spelling.name, ws.isStrictTransactional()); + Assert.assertEquals(spelling.name, CAP * 9 / 10, ws.getEffectiveAutoFlushBytes()); + writeRows(s, "t", 0, 2_000); + // ~200 KB went out as deferred frames before flush(); none commits. + Assert.assertTrue(spelling.name, h.awaitFrames(5)); + Assert.assertEquals(spelling.name, 0, h.commitFrames()); + s.flush(); + Assert.assertTrue(spelling.name, s.drain(5_000)); + assertFramesWithinCap(h, CAP); + assertOneTransaction(h); + committed = h.committedFrames(); + Assert.assertEquals(spelling.name, h.frames, committed); + // close() without flush() discards the next transaction, its + // frames already sent included. + writeRows(s, "t", 2_000, 1_000); + Assert.assertTrue(spelling.name, h.awaitFrames(committed.size() + 2)); + } + Assert.assertEquals(spelling.name, committed, h.committedFrames()); + } + } + }); + } + + @Test + public void testNoAutoFlushTriggerRejectsTransactionOff() throws Exception { + // With no auto-flush trigger only flush() commits, and a non-transactional + // flush has to fit one frame, so every spelling refuses transaction=off. + assertMemoryLeak(() -> { + assertConfigRejected("auto_flush=off;transaction=off;", NO_TRIGGER_TRANSACTION_OFF_ERROR); + assertConfigRejected("auto_flush_rows=off;auto_flush_interval=off;transaction=off;", + NO_TRIGGER_TRANSACTION_OFF_ERROR); + assertConfigRejected("auto_flush_rows=off;auto_flush_interval=off;auto_flush_bytes=off;transaction=off;", + NO_TRIGGER_TRANSACTION_OFF_ERROR); + }); + } + + @Test + public void testNoAutoFlushTriggerWithAutoFlushBytesOffSendsOneFramePerFlush() throws Exception { + // auto_flush_bytes=off opts out of sizing batches to the frame: the + // transaction still commits only on flush(), but the application keeps it + // within one frame per table, and a flush past the cap is refused and keeps + // the rows, as auto_flush_bytes=off documents. + assertMemoryLeak(() -> { + String[] configs = { + "auto_flush=off;auto_flush_bytes=off;", + "auto_flush_rows=off;auto_flush_interval=off;auto_flush_bytes=off;" + }; + for (String config : configs) { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + config)) { + QwpWebSocketSender ws = (QwpWebSocketSender) s; + Assert.assertTrue(config, ws.isStrictTransactional()); + Assert.assertEquals(config, 0, ws.getEffectiveAutoFlushBytes()); + // ~20 KB fits the 32 KiB cap: one frame, which commits. + writeRows(s, "t", 0, 200); + s.flush(); + Assert.assertTrue(config, s.drain(5_000)); + Assert.assertEquals(config, 1, h.frames.size()); + Assert.assertTrue(config, h.frames.get(0).isCommit()); + // ~100 KB does not. + writeRows(s, "t", 200, 1_000); + try { + s.flush(); + Assert.fail(config + ": a flush past the cap must be refused"); + } catch (BatchTooLargeForCapException e) { + TestUtils.assertContains(e.getMessage(), "serverMaxBatchSize=" + CAP); + } + s.reset(); + } + Assert.assertEquals(config, 1, h.frames.size()); + } + } + }); + } + + @Test + public void testNoAutoFlushTriggerWithTransactionOnCommitsOnClose() throws Exception { + // An explicit transaction=on wins over the strict mode a sender with no + // auto-flush trigger otherwise gets: close() commits, as transaction=on does. + assertMemoryLeak(() -> { + for (NoTriggerSpelling spelling : noTriggerSpellings()) { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = spelling.build(conf(server) + "transaction=on;")) { + QwpWebSocketSender ws = (QwpWebSocketSender) s; + Assert.assertTrue(spelling.name, ws.isTransactional()); + Assert.assertFalse(spelling.name, ws.isStrictTransactional()); + writeRows(s, "t", 0, 2_000); + Assert.assertTrue(spelling.name, h.awaitFrames(5)); + Assert.assertEquals(spelling.name, 0, h.commitFrames()); + } + assertFramesWithinCap(h, CAP); + assertOneTransaction(h); + Assert.assertEquals(spelling.name, h.frames, h.committedFrames()); + } + } + }); + } + + @Test + public void testOneAutoFlushTriggerLeftKeepsEveryBatchCommitting() throws Exception { + // Turning off the row or the interval trigger alone leaves the other one, so + // the sender is not transactional: every batch it sends commits on its own. + assertMemoryLeak(() -> { + String[] configs = {"auto_flush_rows=off;", "auto_flush_interval=off;"}; + for (String config : configs) { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + config)) { + QwpWebSocketSender ws = (QwpWebSocketSender) s; + Assert.assertFalse(config, ws.isTransactional()); + Assert.assertEquals(config, CAP * 9 / 10, ws.getEffectiveAutoFlushBytes()); + // ~100 KB: the byte trigger sends at least three batches before + // any flush(), and each commits. + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(config, h.awaitFrames(3)); + for (TxnFrame f : h.frames) { + Assert.assertTrue(config + ": " + h.frames, f.isCommit()); + } + } + Assert.assertEquals(config, h.frames, h.committedFrames()); + } + } + }); + } + + @Test + public void testPooledLeaseWithAbortedTransactionRetiresQuietly() throws Exception { + // reset() could not undo the frames already sent, so the transaction is + // aborted and every flush already said so. Returning the lease retires the + // connection, which discards the frames, without warning about them again. + assertMemoryLeak(() -> { + ListAppender log = captureSenderLog(); + try { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (QuestDB db = QuestDB.connect(conf(server) + + "auto_flush_rows=off;auto_flush_interval=off;query_pool_min=0;")) { + Sender lease = db.borrowSender(); + writeRows(lease, "t", 0, 1_000); + lease.reset(); + assertAborted(lease::flush); + lease.close(); + Sender next = db.borrowSender(); + writeRows(next, "t", 0, 10); + next.flush(); + Assert.assertTrue(next.drain(5_000)); + next.close(); + } + List committed = h.committedFrames(); + Assert.assertEquals("only the next lease commits", 1, committed.size()); + Assert.assertTrue(committed.get(0).isCommit()); + Assert.assertEquals("the aborted lease's connection was retired", 2, server.upgradeRequestCount()); + } + Assert.assertEquals(Collections.emptyList(), discardWarnings(log)); + } finally { + releaseSenderLog(log); + } + }); + } + + @Test + public void testPooledLeaseWithoutAutoFlushTriggerDiscardsOnReturn() throws Exception { + // Returning a lease of a pool with no auto-flush trigger used to commit its rows. + // The lease now holds a strict transaction, which only flush() commits, so + // returning it discards the rows, and says so once: whether the server rolls + // back the frames already sent, or the pool retires the connection to discard them. + assertMemoryLeak(() -> { + ListAppender log = captureSenderLog(); + try { + String[] spellings = {"auto_flush=off;", "auto_flush_rows=off;auto_flush_interval=off;"}; + for (String spelling : spellings) { + for (boolean isRollbackSupported : new boolean[]{false, true}) { + String name = spelling + " rollback=" + isRollbackSupported; + clearLog(log); + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(isRollbackSupported); + try (QuestDB db = QuestDB.connect(conf(server) + spelling + "query_pool_min=0;")) { + Sender lease = db.borrowSender(); + writeRows(lease, "t", 0, 1_000); + Assert.assertTrue(name, h.awaitFrames(2)); + lease.close(); + Sender next = db.borrowSender(); + writeRows(next, "t", 0, 10); + next.flush(); + Assert.assertTrue(name, next.drain(5_000)); + next.close(); + } + List committed = h.committedFrames(); + Assert.assertEquals(name + ": only the next lease commits", 1, committed.size()); + Assert.assertTrue(name, committed.get(0).isCommit()); + Assert.assertEquals(name, isRollbackSupported ? 1 : 0, h.rollbackFrames()); + } + Assert.assertEquals(name, + Collections.singletonList("returning the sender to the pool" + DISCARD_WARNING), + discardWarnings(log)); + } + } + } finally { + releaseSenderLog(log); + } + }); + } + @Test public void testPooledStrictLeaseCloseDuringOutageKeepsTheConnection() throws Exception { // Returning a strict lease discards its open transaction. During an outage that @@ -608,6 +833,44 @@ public void testStrictCloseWithoutFlushDiscardsTransaction() throws Exception { }); } + @Test + public void testStrictCloseWithoutFlushWarnsOfDiscardedRows() throws Exception { + // A sender with no auto-flush trigger used to commit on close(). Now close() + // discards its open transaction, and says so once, counting the rows already + // sent with those still buffered. A committed transaction leaves nothing to + // discard, and an aborted one already failed every flush. + assertMemoryLeak(() -> { + ListAppender log = captureSenderLog(); + try { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "auto_flush_rows=off;auto_flush_interval=off;")) { + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(h.awaitFrames(2)); + } + Assert.assertEquals(Collections.singletonList("close()" + DISCARD_WARNING), discardWarnings(log)); + clearLog(log); + + try (Sender s = Sender.fromConfig(conf(server) + "auto_flush_rows=off;auto_flush_interval=off;")) { + writeRows(s, "t", 0, 1_000); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { + writeRows(s, "t", 0, 1_000); + // Frames went out and the server cannot roll them back. + s.reset(); + assertAborted(s::flush); + } + Assert.assertEquals(Collections.emptyList(), discardWarnings(log)); + Assert.assertEquals(1, h.commitFrames()); + } + } finally { + releaseSenderLog(log); + } + }); + } + @Test public void testStrictCloseWithoutFlushRollsBackWhenServerSupportsIt() throws Exception { assertMemoryLeak(() -> { @@ -772,6 +1035,60 @@ public void testTransactionalDefaultTriggersSplitWideRows() throws Exception { }); } + // Captures what QwpWebSocketSender logs, so a test can assert its warnings. + private static ListAppender captureSenderLog() { + ListAppender appender = new ListAppender<>(); + appender.start(); + senderLogger().addAppender(appender); + return appender; + } + + // The appender appends under its own lock, and I/O threads log into it too. + private static void clearLog(ListAppender log) { + synchronized (log) { + log.list.clear(); + } + } + + // The discarded-transaction warnings logged since the last clearLog(). + private static List discardWarnings(ListAppender log) { + List warnings = new ArrayList<>(); + synchronized (log) { + for (ILoggingEvent e : log.list) { + String message = e.getFormattedMessage(); + if (e.getLevel() == Level.WARN && message.contains("discarded an uncommitted transaction")) { + warnings.add(message); + } + } + } + return warnings; + } + + // Every way to configure a WebSocket sender with no auto-flush trigger, applied + // on top of a config string. + private static List noTriggerSpellings() { + List spellings = new ArrayList<>(); + spellings.add(new NoTriggerSpelling("auto_flush=off", c -> Sender.builder(c + "auto_flush=off;"))); + spellings.add(new NoTriggerSpelling("auto_flush_rows=off;auto_flush_interval=off", + c -> Sender.builder(c + "auto_flush_rows=off;auto_flush_interval=off;"))); + spellings.add(new NoTriggerSpelling("auto_flush_interval=off;auto_flush_rows=off", + c -> Sender.builder(c + "auto_flush_interval=off;auto_flush_rows=off;"))); + spellings.add(new NoTriggerSpelling("disableAutoFlush()", + c -> Sender.builder(c).disableAutoFlush())); + spellings.add(new NoTriggerSpelling("autoFlushRows(0).autoFlushIntervalMillis(Integer.MAX_VALUE)", + c -> Sender.builder(c).autoFlushRows(0).autoFlushIntervalMillis(Integer.MAX_VALUE))); + return spellings; + } + + private static void releaseSenderLog(ListAppender log) { + senderLogger().detachAppender(log); + log.stop(); + } + + private static Logger senderLogger() { + return (Logger) LoggerFactory.getLogger(QwpWebSocketSender.class); + } + private static void assertAborted(ThrowingRunnable r) { try { r.run(); @@ -781,6 +1098,16 @@ private static void assertAborted(ThrowingRunnable r) { } } + // Build-time validation runs before the sender connects, so no server is needed. + private static void assertConfigRejected(String config, String expectedMessage) { + try { + Sender.fromConfig("ws::addr=localhost:1;" + config).close(); + Assert.fail(config + " must be rejected"); + } catch (LineSenderException e) { + TestUtils.assertContains(e.getMessage(), expectedMessage); + } + } + private static void assertFramesWithinCap(TxnServer h, int cap) { for (TxnFrame f : h.frames) { Assert.assertTrue("frame of " + f.size + " bytes exceeds " + cap, f.size <= cap); @@ -896,6 +1223,20 @@ private interface ThrowingRunnable { void run(); } + private static final class NoTriggerSpelling { + final String name; + private final Function builder; + + NoTriggerSpelling(String name, Function builder) { + this.name = name; + this.builder = builder; + } + + Sender build(String config) { + return builder.apply(config).build(); + } + } + private static final class TxnFrame { // Index of the connection the frame arrived on, in connection order. final int connection; From a6ed99894fc967e868a1793407c4578449fb82f1 Mon Sep 17 00:00:00 2001 From: Vlad Ilyushchenko Date: Thu, 12 Nov 2026 17:57:59 +0000 Subject: [PATCH 06/20] Keep refused rows out of strict transactions A strict transaction refused a row inconsistently. At the server's qwp.max.uncommitted.rows the row that hit the limit stayed out of the transaction, but at the client's sf_max_total_bytes the row whose auto-flush found no room stayed in it, although at() threw all the same. A caller could not tell whether flush() would commit that row. The auto-flush that finds no room now keeps its rows pending and returns, since the room kept for the commit holds them, and the next row throws. A row whose at() throws TransactionTooLargeException is never part of the transaction, at either limit. flush() still throws when the client buffer cannot hold it, and sends nothing. The errors and the exception's javadoc name the setting to raise instead of suggesting code that commits part of the transaction. A row refused at the client buffer reports the size the transaction would have reached, as a refused flush does, rather than the bytes already sent, which read 0 when nothing had been sent yet. --- .../main/java/io/questdb/client/Sender.java | 6 +- .../qwp/client/QwpWebSocketSender.java | 109 ++++++++------ .../client/TransactionTooLargeException.java | 19 +-- .../qwp/client/QwpLargeTransactionTest.java | 137 ++++++++++++++++-- 4 files changed, 208 insertions(+), 63 deletions(-) diff --git a/core/src/main/java/io/questdb/client/Sender.java b/core/src/main/java/io/questdb/client/Sender.java index c65f15412..b7c511f91 100644 --- a/core/src/main/java/io/questdb/client/Sender.java +++ b/core/src/main/java/io/questdb/client/Sender.java @@ -2824,11 +2824,11 @@ private LineSenderBuilder requestDurableAckTiers(int tiers) { * sends rows to the server without committing them and {@code flush()} * commits, so a transaction can be any size. In addition the transaction * never commits in parts: a row that would take a table past the server's - * {@code qwp.max.uncommitted.rows}, or a transaction that outgrows + * {@code qwp.max.uncommitted.rows}, or the transaction past * {@code sf_max_total_bytes}, throws * {@link io.questdb.client.cutlass.qwp.client.TransactionTooLargeException} - * and leaves the transaction open, and {@code close()} without - * {@code flush()} discards the transaction instead of committing it. + * and is not added, and {@code close()} without {@code flush()} discards the + * transaction instead of committing it. * A sender with no auto-flush trigger (see {@link #disableAutoFlush()}) is * in this mode unless {@link #transactional(boolean)} selects the mode. * WebSocket transport only. diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java index 624d2bc80..a61661f4c 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java @@ -718,7 +718,9 @@ public class QwpWebSocketSender implements Sender { private boolean txnAborted; // Strict mode only: set when the client buffer cannot take another deferred // frame of the open transaction and still commit it. Rejects further rows - // until flush() or rollback() ends the transaction. + // until flush() or rollback() ends the transaction. The rows accepted before + // it stay in the transaction, including the one whose auto-flush found no + // room: the room kept for the commit holds them. private boolean txnBufferFull; // Strict mode only: simulation of how the ring packs the open transaction's // frames, mirroring MmapSegment's append rule. txnSimSegments counts the @@ -732,9 +734,13 @@ public class QwpWebSocketSender implements Sender { // Logs the reset()-cannot-roll-back warning once per sender. private boolean isResetRollbackWarned; // Strict mode only: payload bytes of the open transaction's frames on the - // ring, for the error message. Reset with the transaction. + // ring. Reset with the transaction. private long txnBytes; - // Scratch for ensureStrictTransactionRoom: the frame sizes a flush will + // Strict mode only: the size the open transaction would have reached with the + // flush the client buffer last refused, for the error messages. Reset with the + // transaction. + private long txnRefusedBytes; + // Scratch for hasStrictTransactionRoom: the frame sizes a flush will // publish. Producer thread only. private final IntList strictFrameSizes = new IntList(); @@ -1880,7 +1886,7 @@ private void close0(boolean[] restoreInterrupt) { } } else { try { - flushPendingRows(deferCommit); + flushPendingRows(deferCommit, false); } catch (BatchTooLargeForCapException e) { resetTableBuffersAfterFlush(); terminalError = captureCloseError(terminalError, e); @@ -2375,7 +2381,7 @@ public long flushAndGetSequence() { // is published in its mmap'd segment. PERIODIC stable-storage barriers // run independently in the manager. No processingCount to drain and no // awaitPendingAcks here; just surface any I/O thread error. - flushPendingRows(deferCommit); + flushPendingRows(deferCommit, false); if (!deferCommit && hasDeferredMessages) { sendCommitMessage(); } @@ -3823,11 +3829,12 @@ public void setRecycleDeferredCloseMaxWaitMillisForTesting(long millis) { * Strict transactional mode: auto-flush ships rows as FLAG_DEFER_COMMIT frames * like {@link #setTransactional(boolean) transactional} mode, only an explicit * flush commits, and the open transaction never commits in parts. A row that - * would push a table past the server's {@code qwp.max.uncommitted.rows}, or a - * frame the client buffer could not hold alongside the commit, throws - * {@link TransactionTooLargeException} instead. {@link #close()} discards an - * uncommitted transaction rather than committing it. Enabling it enables - * transactional mode; disabling it leaves transactional mode on. + * would push a table past the server's {@code qwp.max.uncommitted.rows}, or the + * open transaction past what the client buffer can hold alongside the commit, + * throws {@link TransactionTooLargeException} instead and is not added. + * {@link #close()} discards an uncommitted transaction rather than committing + * it. Enabling it enables transactional mode; disabling it leaves transactional + * mode on. */ public void setStrictTransactional(boolean strict) { this.strictTransactional = strict; @@ -5475,8 +5482,12 @@ private void ensureNoInProgressRow() { * @param deferCommit when true, the message carries FLAG_DEFER_COMMIT * so the server appends rows but does not commit. * Used by auto-flush in transactional mode. + * @param isAutoFlush true when a row triggered the flush: when the client + * buffer cannot take it, a strict transaction keeps the + * rows pending instead of throwing, and refuses the next + * row. */ - private void flushPendingRows(boolean deferCommit) { + private void flushPendingRows(boolean deferCommit, boolean isAutoFlush) { if (pendingRowCount <= 0) { return; } @@ -5523,8 +5534,19 @@ private void flushPendingRows(boolean deferCommit) { // A strict transaction must be able to commit as one: refuse, before any // frame of this flush reaches the ring, a flush the client buffer could not // hold together with the commit that has to follow it. - if (strictTransactional && cursorEngine != null) { - ensureStrictTransactionRoom(cap, deltaBaseline, messageSize, deferCommit); + if (strictTransactional && cursorEngine != null + && !hasStrictTransactionRoom(cap, deltaBaseline, messageSize, deferCommit)) { + if (deferCommit) { + txnBufferFull = true; + if (isAutoFlush) { + // The rows stay pending, the one that triggered this flush + // included, and the room kept for the commit holds them. The + // next row is refused, so a refused row is never part of the + // transaction, as at the server's row limit. + return; + } + } + throw transactionTooLargeForClientBuffer("so the flush was not sent"); } // Full-dict over-cap fallback. A full-dictionary frame carries the whole @@ -7471,11 +7493,7 @@ private void checkTransactionAcceptsRow() { return; } if (txnBufferFull) { - throw new TransactionTooLargeException("transaction too large for the client buffer") - .put(" [transactionBytes=").put(txnBytes) - .put("]; the buffer cannot hold another frame of the open transaction and still " - + "commit it, so the row was not added. Commit the transaction with flush() or " - + "discard it with rollback() before adding rows"); + throw transactionTooLargeForClientBuffer("so the row was not added"); } long maxRows = serverMaxUncommittedRows; if (maxRows <= 0) { @@ -7491,8 +7509,7 @@ private void checkTransactionAcceptsRow() { .put(", maxUncommittedRows=").put(maxRows) .put("]; the server commits a table's rows on its own once qwp.max.uncommitted.rows " + "of them are uncommitted, which would split the transaction, so the row was " - + "not added. Commit the transaction with flush() or discard it with rollback(), " - + "then send smaller transactions or raise qwp.max.uncommitted.rows on the server"); + + "not added. Raise qwp.max.uncommitted.rows on the server"); } } @@ -7508,26 +7525,27 @@ private void clearTransactionState() { txnTables.setPos(0); txnBufferFull = false; txnBytes = 0; + txnRefusedBytes = 0; txnSimSegments = 0; txnSimRemaining = 0; } /** - * Strict mode: refuses a flush whose frames, together with the open - * transaction's frames already on the ring and (for a deferred flush) room - * for the commit that must follow, would not fit the ring under - * {@code sf_max_total_bytes}. The server acks none of a transaction's frames - * before its commit, so the ring cannot trim them; a transaction that does - * not fit would block its own commit. + * Strict mode: whether the ring under {@code sf_max_total_bytes} can hold a + * flush's frames together with the open transaction's frames already on it + * and, for a deferred flush, room for the commit that must follow. The server + * acks none of a transaction's frames before its commit, so the ring cannot + * trim them; a transaction that does not fit would block its own commit. *

    * Mirrors how the ring packs frames: frames never span segments, and a frame * that does not fit the current segment opens the next one. The flush's * frame sizes are derived the way flushPendingRows and the split publish * them; dictionary chunks of the full-dictionary fallback count as full * frames. Runs before anything of the flush is published, so a refusal - * leaves the batch pending and the ring untouched. + * leaves the batch pending and the ring untouched. On a refusal it records + * the size the transaction would have reached in {@link #txnRefusedBytes}. */ - private void ensureStrictTransactionRoom(int cap, int deltaBaseline, int messageSize, boolean deferCommit) { + private boolean hasStrictTransactionRoom(int cap, int deltaBaseline, int messageSize, boolean deferCommit) { CursorSendEngine engine = cursorEngine; long segmentPayload = segmentPayloadCapacity(); strictFrameSizes.clear(); @@ -7583,21 +7601,12 @@ && splitFramesFit(cap, currentBatchMaxSymbolId)) { remaining = Math.max(0, remaining - reserve - MmapSegment.FRAME_HEADER_SIZE); } } - long ringCapacity = engine.ringCapacityBytes(); - long maxSegments = Math.max(2, ringCapacity / engine.segmentSizeBytes()); + long maxSegments = Math.max(2, engine.ringCapacityBytes() / engine.segmentSizeBytes()); if (segments > maxSegments) { - if (deferCommit) { - txnBufferFull = true; - } - throw new TransactionTooLargeException("transaction too large for the client buffer") - .put(" [transactionBytes=").put(bytes) - .put(", ringCapacityBytes=").put(ringCapacity) - .put(", segmentBytes=").put(engine.segmentSizeBytes()) - .put("]; the client holds an uncommitted transaction until the server commits it, so " - + "the transaction must fit sf_max_total_bytes. This flush was not sent: commit " - + "the transaction with flush() or discard it with rollback(), then send smaller " - + "transactions, raise sf_max_total_bytes, or set sf_dir to keep it on disk"); + txnRefusedBytes = bytes; + return false; } + return true; } /** @@ -7681,6 +7690,22 @@ private LineSenderException transactionAbortedError() { + "the sender to discard them; the server rolls them back when the connection closes"); } + /** + * The error for a strict transaction the client buffer cannot hold: the size + * the transaction would have reached, the buffer, what was refused, and the + * settings that make room. + */ + private LineSenderException transactionTooLargeForClientBuffer(String outcome) { + CursorSendEngine engine = cursorEngine; + return new TransactionTooLargeException("transaction too large for the client buffer") + .put(" [transactionBytes=").put(txnRefusedBytes) + .put(", ringCapacityBytes=").put(engine.ringCapacityBytes()) + .put(", segmentBytes=").put(engine.segmentSizeBytes()) + .put("]; the client holds a strict transaction until the server commits it, and " + + "sf_max_total_bytes cannot hold this one, ").put(outcome) + .put(". Raise sf_max_total_bytes, or set sf_dir to keep the transaction on disk"); + } + /** * Strict mode commits only on flush(), so closing the sender or returning a * pooled lease discards the open transaction. Logs it when the transaction holds @@ -7752,7 +7777,7 @@ private void sendRow() { currentTableBufferSnapshotBytes = bufferedNow; if (shouldAutoFlush()) { - flushPendingRows(transactional); + flushPendingRows(transactional, true); } } diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java index 2c2b0fc8f..c7cc37f81 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java @@ -28,19 +28,20 @@ /** * A strict transaction ({@code transaction=strict}, or a sender with no auto-flush - * trigger such as {@code auto_flush=off}, on the WebSocket transport) grew past a + * trigger such as {@code auto_flush=off}, on the WebSocket transport) outgrew a * limit that would stop it from committing as one transaction: the server's * per-table {@code qwp.max.uncommitted.rows}, past which the server commits the * rows on its own, or the client's {@code sf_max_total_bytes}, which must hold the - * whole uncommitted transaction until the server commits it. + * whole uncommitted transaction until the server commits it. To send transactions + * of that size, raise the limit the message names: {@code qwp.max.uncommitted.rows} + * on the server, or {@code sf_max_total_bytes} on the client, whose default is + * larger with {@code sf_dir} set. *

    - * Thrown before anything that would cross the limit reaches the server, and the - * transaction stays open: the caller can still commit the rows accepted so far - * with {@code flush()}, or discard them with {@code rollback()}. A row rejected at - * the per-table limit is not part of the transaction. When the client buffer is - * the limit, the row being added when the buffer filled up stays in the - * transaction, and every further row is rejected until {@code flush()} or - * {@code rollback()} ends the transaction. + * {@code at()} and {@code atNow()} throw it for the row that would take the + * transaction past either limit, and that row is not part of the transaction. + * {@code flush()} throws it when the client buffer cannot hold the flush, and + * sends nothing. Either way nothing past the limit reaches the server, and the + * transaction keeps the rows accepted before the error. */ public class TransactionTooLargeException extends LineSenderException { diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index 8393c2f6a..d42307354 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -67,6 +67,9 @@ */ public class QwpLargeTransactionTest { private static final int CAP = 32 * 1024; + // The settings a refusal at the client buffer names. + private static final String CLIENT_BUFFER_REMEDY = "Raise sf_max_total_bytes, or set sf_dir to keep the " + + "transaction on disk"; // What closing a sender or returning a pooled lease logs when it discards an open // strict transaction of 1000 rows, behind the action that discarded it. private static final String DISCARD_WARNING = " discarded an uncommitted transaction of 1000 rows: a strict " @@ -905,8 +908,7 @@ public void testStrictRowLimitFromServer() throws Exception { writeRows(s, "a", 99, 1); Assert.fail("the 100th row of a table must be refused"); } catch (TransactionTooLargeException e) { - TestUtils.assertContains(e.getMessage(), - "transaction too large for the server [table=a, rows=100, maxUncommittedRows=100]"); + Assert.assertEquals(serverRowLimitError("a", 100), e.getMessage()); } // Other tables keep their own count. writeRows(s, "b", 0, 99); @@ -939,7 +941,7 @@ public void testStrictRowLimitDefaultsWhenNotAdvertised() throws Exception { writeRows(s, "a", 9, 1); Assert.fail("the 10th row must be refused"); } catch (TransactionTooLargeException e) { - TestUtils.assertContains(e.getMessage(), "maxUncommittedRows=10"); + Assert.assertEquals(serverRowLimitError("a", 10), e.getMessage()); } ws.applyServerTransactionLimits(0, false); // 0 means "not advertised": the server default applies. @@ -950,10 +952,85 @@ public void testStrictRowLimitDefaultsWhenNotAdvertised() throws Exception { }); } + @Test + public void testStrictCommitTooLargeForClientBufferIsNotSent() throws Exception { + // With auto_flush_bytes=off on top of auto_flush=off, the whole transaction + // waits for flush(), which sends one frame per table. Ten tables of ~28 KB need five 64 KiB + // segments, and sf_max_total_bytes holds four: flush() sends nothing. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "auto_flush=off;auto_flush_bytes=off;" + + "sf_max_segment_bytes=64k;sf_max_total_bytes=256k;")) { + writeTables(s, 0, 10); + long refusedBytes = -1; + try { + s.flush(); + Assert.fail("the client buffer cannot hold the commit"); + } catch (TransactionTooLargeException e) { + refusedBytes = assertClientBufferRefusal(e, 262_144, "so the flush was not sent"); + } + Assert.assertEquals("nothing was sent", 0, h.frames.size()); + s.rollback(); + // The same rows, one table per transaction: the refusal reported + // what these frames add up to. + for (int t = 0; t < 10; t++) { + writeTables(s, t, 1); + s.flush(); + } + Assert.assertTrue(s.drain(5_000)); + Assert.assertEquals(10, h.commitFrames()); + Assert.assertEquals(refusedBytes, frameBytes(h)); + } + } + }); + } + + @Test + public void testStrictDeferredFlushTooLargeForClientBufferIsNotSent() throws Exception { + // setDeferCommit(true) makes flush() send rows without committing them. A + // strict transaction keeps room for its commit next to such a frame. With + // frames as large as a segment that takes four segments, and + // sf_max_total_bytes holds three: flush() sends nothing, and the transaction + // takes no further rows. The commit itself fits. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, 64 * 1024)) { + long refusedBytes = -1; + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(conf(server) + + "transaction=strict;sf_max_segment_bytes=64k;sf_max_total_bytes=192k;")) { + s.setDeferCommit(true); + writeRows(s, "t", 0, 1); + try { + s.flush(); + Assert.fail("the client buffer cannot hold a deferred frame and the commit"); + } catch (TransactionTooLargeException e) { + refusedBytes = assertClientBufferRefusal(e, 196_608, "so the flush was not sent"); + } + Assert.assertEquals("nothing was sent", 0, h.frames.size()); + try { + writeRows(s, "t", 1, 1); + Assert.fail("the transaction must take no further rows"); + } catch (TransactionTooLargeException e) { + Assert.assertEquals(refusedBytes, + assertClientBufferRefusal(e, 196_608, "so the row was not added")); + } + s.setDeferCommit(false); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + // The commit carries the row the refused flush held, and only that row. + Assert.assertEquals(1, h.frames.size()); + Assert.assertTrue(h.frames.get(0).isCommit()); + Assert.assertEquals(refusedBytes, h.frames.get(0).size); + } + }); + } + @Test public void testStrictTransactionTooLargeForClientBufferFailsFast() throws Exception { // 64 KiB segments, 256 KiB budget: four segments. A strict transaction keeps - // room for its commit, so it must refuse the flush that would take that room + // room for its commit, so once its frames fill the rest it must refuse rows // instead of blocking for sf_append_deadline_millis. assertMemoryLeak(() -> { TxnServer h = new TxnServer(); @@ -961,29 +1038,35 @@ public void testStrictTransactionTooLargeForClientBufferFailsFast() throws Excep try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;" + "sf_max_segment_bytes=64k;sf_max_total_bytes=256k;sf_append_deadline_millis=30000;")) { long start = System.nanoTime(); - int row = 0; + long refusedBytes = -1; try { - for (; row < 100_000; row++) { + for (int row = 0; row < 100_000; row++) { s.table("t").longColumn("v", row).stringColumn("s", PAD).atNow(); } Assert.fail("a transaction larger than the client buffer must be refused"); } catch (TransactionTooLargeException e) { - TestUtils.assertContains(e.getMessage(), "transaction too large for the client buffer"); + // As at the server's row limit, the row that hit the limit is not + // in the transaction. + refusedBytes = assertClientBufferRefusal(e, 262_144, "so the row was not added"); } Assert.assertTrue("must fail fast, not wait for the append deadline", System.nanoTime() - start < TimeUnit.SECONDS.toNanos(10)); - // The row being added stays in the transaction; further rows are refused. + // Further rows are refused the same way. try { s.table("t").longColumn("v", -1).stringColumn("s", PAD).atNow(); Assert.fail("a full transaction must refuse rows"); } catch (TransactionTooLargeException e) { - TestUtils.assertContains(e.getMessage(), "the row was not added"); + Assert.assertEquals(refusedBytes, + assertClientBufferRefusal(e, 262_144, "so the row was not added")); } // The reserved room lets the transaction commit. s.flush(); Assert.assertTrue(s.drain(5_000)); Assert.assertTrue(h.frames.get(h.frames.size() - 1).isCommit()); Assert.assertEquals(1, h.commitFrames()); + // The refusal reported the size of the transaction that committed: + // the rows accepted before it, the last of which filled the buffer. + Assert.assertEquals(refusedBytes, frameBytes(h)); // And the next transaction starts with an empty buffer. writeRows(s, "t", 0, 100); s.flush(); @@ -1098,6 +1181,20 @@ private static void assertAborted(ThrowingRunnable r) { } } + // Asserts the error of a strict transaction the client buffer cannot hold, with + // 64 KiB segments, and returns the transaction size it reports. + private static long assertClientBufferRefusal(TransactionTooLargeException e, long ringCapacityBytes, String outcome) { + String message = e.getMessage(); + String prefix = "transaction too large for the client buffer [transactionBytes="; + Assert.assertTrue(message, message.startsWith(prefix)); + long transactionBytes = Long.parseLong(message.substring(prefix.length(), message.indexOf(','))); + Assert.assertTrue(message, transactionBytes > 0); + Assert.assertEquals(prefix + transactionBytes + ", ringCapacityBytes=" + ringCapacityBytes + + ", segmentBytes=65536]; the client holds a strict transaction until the server commits it, " + + "and sf_max_total_bytes cannot hold this one, " + outcome + ". " + CLIENT_BUFFER_REMEDY, message); + return transactionBytes; + } + // Build-time validation runs before the sender connects, so no server is needed. private static void assertConfigRejected(String config, String expectedMessage) { try { @@ -1212,12 +1309,34 @@ private static TestWebSocketServer start(TxnServer h, int cap, int port, boolean return server; } + private static long frameBytes(TxnServer h) { + long bytes = 0; + for (TxnFrame f : h.frames) { + bytes += f.size; + } + return bytes; + } + + private static String serverRowLimitError(String table, long maxUncommittedRows) { + return "transaction too large for the server [table=" + table + ", rows=" + maxUncommittedRows + + ", maxUncommittedRows=" + maxUncommittedRows + "]; the server commits a table's rows on its " + + "own once qwp.max.uncommitted.rows of them are uncommitted, which would split the transaction, " + + "so the row was not added. Raise qwp.max.uncommitted.rows on the server"; + } + private static void writeRows(Sender s, String table, int from, int count) { for (int i = from, n = from + count; i < n; i++) { s.table(table).longColumn("v", i).stringColumn("s", PAD).atNow(); } } + // ~28 KB in each of count tables, from table t: each fits a 32 KiB frame. + private static void writeTables(Sender s, int first, int count) { + for (int t = first, n = first + count; t < n; t++) { + writeRows(s, "t" + t, 0, 280); + } + } + @FunctionalInterface private interface ThrowingRunnable { void run(); From 83eec1e81f66d06b7dac1dba061f6370a86f7d75 Mon Sep 17 00:00:00 2001 From: Vlad Ilyushchenko Date: Thu, 12 Nov 2026 19:13:59 +0000 Subject: [PATCH 07/20] Commit transaction=on in parts at client buffer A transaction=on transaction holds its frames in the store-and-forward buffer until the server commits it, and the server acks none of them before that, so the buffer cannot trim them. The row whose frame no longer fit blocked for sf_append_deadline_millis (30 s by default) and then threw, and close() then committed the frames already sent and dropped the rest, under an error that did not say so. Before a flush that does not fit beside the open transaction's frames, the sender now commits those frames with a bare commit frame and goes on, as the server already does at qwp.max.uncommitted.rows. Every deferred flush leaves room for that commit frame, so it never waits for the buffer to drain. The sender logs a warning on the first part of each transaction it commits this way, and rollback() and reset() warn that the parts already committed stay. Strict mode still refuses such transactions. The client-buffer simulation strict mode uses now tracks transaction=on transactions too. A single flush larger than the whole buffer still blocks, as before; only auto_flush_bytes=off builds one. --- .../main/java/io/questdb/client/Sender.java | 12 +- .../qwp/client/QwpWebSocketSender.java | 200 +++++++++++++----- .../qwp/client/QwpLargeTransactionTest.java | 183 +++++++++++++++- 3 files changed, 340 insertions(+), 55 deletions(-) diff --git a/core/src/main/java/io/questdb/client/Sender.java b/core/src/main/java/io/questdb/client/Sender.java index b7c511f91..fb21442f6 100644 --- a/core/src/main/java/io/questdb/client/Sender.java +++ b/core/src/main/java/io/questdb/client/Sender.java @@ -795,6 +795,10 @@ default void resetSymbolDictionary() { * later rows never commit the discarded ones, even across reconnects. Call * {@link #drain(long)} to wait until the server confirms. *
    + * A {@code transaction=on} transaction that already committed in parts (see + * {@link LineSenderBuilder#transactional(boolean)}) keeps the parts it committed; + * this discards only the rest. + *
    * Discarding rows already sent needs a server that supports QWP rollback. When * the server does not, this method throws and aborts the transaction: every * later flush throws too, and closing the sender discards the rows, because the @@ -2854,8 +2858,12 @@ public LineSenderBuilder strictTransactional(boolean enabled) { * with {@code FLAG_DEFER_COMMIT}; only an explicit {@code flush()} * (or {@code close()}) triggers the server-side WAL commit. This allows * accumulating datasets larger than the server's recv buffer while - * committing atomically per table. The server commits a table on its own - * once {@code qwp.max.uncommitted.rows} of its rows are uncommitted; use + * committing atomically per table. A transaction too large for either side + * commits in parts: the server commits a table on its own once + * {@code qwp.max.uncommitted.rows} of its rows are uncommitted, and the + * sender, which holds the transaction in {@code sf_max_total_bytes} until + * the server commits it, commits the rows it already sent once the + * transaction outgrows that buffer, and logs a warning. Use * {@link #strictTransactional(boolean)} to fail instead. *

    * A sender with no auto-flush trigger (see {@link #disableAutoFlush()}) is diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java index a61661f4c..7e6f01a6f 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java @@ -182,6 +182,12 @@ public class QwpWebSocketSender implements Sender { // Default for symbol_dict_reset_threshold: distinct-symbol count that // triggers a recycle once symbol_dict_reset is on. public static final int DEFAULT_SYMBOL_DICT_RESET_THRESHOLD_SYMBOLS = 100_000; + // Largest bare commit frame: the header and an empty symbol-dictionary delta, + // whose start id takes at most five varint bytes and whose count one. The + // rollback control frame is the header alone. A transaction=on transaction keeps + // room for one such frame in the client buffer, so the frame that ends it never + // waits for the buffer to drain. + private static final int COMMIT_FRAME_MAX_BYTES = QwpConstants.HEADER_SIZE + 6; private static final int DEFAULT_BUFFER_SIZE = 8192; private static final int DEFAULT_MICROBATCH_BUFFER_SIZE = 1024 * 1024; // 1MB // Frames of at most the frame cap that a strict transaction keeps room for in @@ -722,27 +728,31 @@ public class QwpWebSocketSender implements Sender { // it stay in the transaction, including the one whose auto-flush found no // room: the room kept for the commit holds them. private boolean txnBufferFull; - // Strict mode only: simulation of how the ring packs the open transaction's + // Transactional mode: simulation of how the ring packs the open transaction's // frames, mirroring MmapSegment's append rule. txnSimSegments counts the // segments the transaction's frames occupy (0 = no frame yet) and // txnSimRemaining is the raw space left in the last of them. private long txnSimRemaining; private int txnSimSegments; + // transaction=on: rows of the open transaction the sender already committed + // because the transaction outgrew the client buffer, 0 when it did not. Reset + // with the transaction; committing a part keeps it. + private long txnRowsCommittedInParts; // Tables with rows in deferred frames of the open transaction, so a commit // or rollback resets only those tables' counters. Producer thread only. private final ObjList txnTables = new ObjList<>(); // Logs the reset()-cannot-roll-back warning once per sender. private boolean isResetRollbackWarned; - // Strict mode only: payload bytes of the open transaction's frames on the + // Transactional mode: payload bytes of the open transaction's frames on the // ring. Reset with the transaction. private long txnBytes; // Strict mode only: the size the open transaction would have reached with the // flush the client buffer last refused, for the error messages. Reset with the // transaction. private long txnRefusedBytes; - // Scratch for hasStrictTransactionRoom: the frame sizes a flush will - // publish. Producer thread only. - private final IntList strictFrameSizes = new IntList(); + // Scratch for hasTransactionRoom: the frame sizes a flush will publish. + // Producer thread only. + private final IntList transactionFrameSizes = new IntList(); private QwpWebSocketSender( List endpoints, @@ -3112,6 +3122,16 @@ public long getTotalServerErrors() { return counters.serverErrors.get(); } + /** + * Rows of the open transaction the sender already committed because the + * transaction outgrew the client buffer (see {@link #setTransactional}); 0 + * when it did not. + */ + @TestOnly + public long getTxnRowsCommittedInPartsForTesting() { + return txnRowsCommittedInParts; + } + /** * Adds an INT column value to the current row. * @@ -3401,7 +3421,7 @@ public void reset() { discardPendingRows(); if (transactional && hasDeferredMessages && !txnAborted) { if (serverRollbackEnabled) { - rollbackOpenTransaction(); + rollbackOpenTransaction("reset()"); } else if (strictTransactional) { txnAborted = true; } else if (!isResetRollbackWarned) { @@ -3426,6 +3446,10 @@ public void reset() { * later, on every connection and after a restart, so nothing sent later can * commit the discarded rows. Call {@link #drain(long)} to wait for the server * to confirm. + *

    + * A transaction=on transaction that already committed in parts, at the + * client buffer or the server's {@code qwp.max.uncommitted.rows}, keeps the + * parts it committed; this discards only the rest. * * @throws LineSenderException when frames of the open transaction were already * sent and the server does not support QWP rollback @@ -3448,7 +3472,7 @@ public void rollback() { txnAborted = true; throw transactionAbortedError(); } - rollbackOpenTransaction(); + rollbackOpenTransaction("rollback()"); } /** @@ -3479,7 +3503,7 @@ public boolean discardTransactionForReuse() { txnAborted = true; return false; } - rollbackOpenTransaction(); + rollbackOpenTransaction("returning the sender to the pool"); return true; } @@ -3545,8 +3569,12 @@ private void publishRollbackFrame() { * {@code CursorWebSocketSendLoop.retireRollbackFrame}). The same holds for * frames replayed after a restart or by a background drainer, which use the * same loop. + *

    + * The rows a transaction=on transaction committed in parts stay committed; + * {@code action} names the call in the warning that says so. */ - private void rollbackOpenTransaction() { + private void rollbackOpenTransaction(String action) { + long committedRows = txnRowsCommittedInParts; publishRollbackFrame(); hasDeferredMessages = false; // The rollback frame gets an OK ack covering the transaction's frames, or the @@ -3554,6 +3582,11 @@ private void rollbackOpenTransaction() { // close-time drains may wait for it like for a commit. lastCommitBoundaryFsn = cursorEngine.publishedFsn(); clearTransactionState(); + if (committedRows > 0) { + LOG.warn("{} discarded the rows of the open transaction sent since the sender last committed part of " + + "it, but the {} rows it committed when the transaction outgrew the client buffer stay " + + "committed", action, committedRows); + } } /** @@ -3845,8 +3878,11 @@ public void setStrictTransactional(boolean strict) { /** * Transactional mode: auto-flush ships rows as FLAG_DEFER_COMMIT frames and - * only an explicit flush (or close) commits. Disabling it also disables - * {@link #setStrictTransactional(boolean) strict} mode. + * only an explicit flush (or close) commits. A transaction that outgrows the + * client buffer commits in parts: before a flush that does not fit beside the + * frames already sent, the sender commits those frames and logs a warning. + * Disabling it also disables {@link #setStrictTransactional(boolean) strict} + * mode, which refuses rows instead. */ public void setTransactional(boolean transactional) { this.transactional = transactional; @@ -5531,22 +5567,37 @@ private void flushPendingRows(boolean deferCommit, boolean isAutoFlush) { int combinedBodyStart = encodeCombinedFrame(tableCount, deferCommit, deltaBaseline); int messageSize = encoder.finishMessage(); - // A strict transaction must be able to commit as one: refuse, before any - // frame of this flush reaches the ring, a flush the client buffer could not - // hold together with the commit that has to follow it. - if (strictTransactional && cursorEngine != null - && !hasStrictTransactionRoom(cap, deltaBaseline, messageSize, deferCommit)) { - if (deferCommit) { - txnBufferFull = true; - if (isAutoFlush) { - // The rows stay pending, the one that triggered this flush - // included, and the room kept for the commit holds them. The - // next row is refused, so a refused row is never part of the - // transaction, as at the server's row limit. - return; + // The client buffer holds a transaction's frames until the server commits it, + // so it cannot trim them to make room. Before any frame of this flush reaches + // the ring, check that the buffer holds the flush beside them. + if (transactional && cursorEngine != null) { + if (strictTransactional) { + // A strict transaction must be able to commit as one: refuse a flush + // the client buffer could not hold together with the commit that has + // to follow it. + if (!hasTransactionRoom(cap, deltaBaseline, messageSize, deferCommit)) { + if (deferCommit) { + txnBufferFull = true; + if (isAutoFlush) { + // The rows stay pending, the one that triggered this flush + // included, and the room kept for the commit holds them. The + // next row is refused, so a refused row is never part of the + // transaction, as at the server's row limit. + return; + } + } + throw transactionTooLargeForClientBuffer("so the flush was not sent"); } + } else if (txnSimSegments > 0 && !hasTransactionRoom(cap, deltaBaseline, messageSize, deferCommit)) { + // transaction=on commits in parts instead: commit the frames already + // sent, which lets the buffer trim them, and send this flush as the + // start of the next part. A flush that does not fit even alone goes + // out as it is. + commitTransactionPart(); + // The commit frame went through the encoder: encode the batch again. + combinedBodyStart = encodeCombinedFrame(tableCount, deferCommit, deltaBaseline); + messageSize = encoder.finishMessage(); } - throw transactionTooLargeForClientBuffer("so the flush was not sent"); } // Full-dict over-cap fallback. A full-dictionary frame carries the whole @@ -7430,10 +7481,10 @@ private void sealAndSwapBuffer() { // (durable mmap append, returns once published). try { toSend.markSending(); - // Strict mode tracks how the open transaction's frames pack into - // segments; the first frame's placement depends on the active + // Transactional mode tracks how the open transaction's frames pack + // into segments; the first frame's placement depends on the active // segment's room before the append. - boolean isTxnFrame = strictTransactional + boolean isTxnFrame = transactional && isTransactionFrame(toSend.getBufferPtr(), toSend.getBufferPos()); long activeRemaining = isTxnFrame && txnSimSegments == 0 ? cursorEngine.activeSegment().capacityRemaining() : 0; @@ -7526,31 +7577,62 @@ private void clearTransactionState() { txnBufferFull = false; txnBytes = 0; txnRefusedBytes = 0; + txnRowsCommittedInParts = 0; txnSimSegments = 0; txnSimRemaining = 0; } /** - * Strict mode: whether the ring under {@code sf_max_total_bytes} can hold a - * flush's frames together with the open transaction's frames already on it - * and, for a deferred flush, room for the commit that must follow. The server - * acks none of a transaction's frames before its commit, so the ring cannot - * trim them; a transaction that does not fit would block its own commit. + * transaction=on: commits the frames of the open transaction already sent, + * because the next flush does not fit beside them in the client buffer, which + * cannot trim them before the server commits them. The transaction goes on + * with the rows sent from here on, so it commits in parts, as it does when the + * server commits a table at {@code qwp.max.uncommitted.rows}. Logs the first + * part each transaction commits this way. + */ + private void commitTransactionPart() { + long rows = sentTransactionRows(); + long bytes = txnBytes; + long committedRows = txnRowsCommittedInParts; + sendCommitMessage(); + // sendCommitMessage() forgot the transaction, but it goes on. + txnRowsCommittedInParts = committedRows + rows; + if (committedRows == 0) { + LOG.warn("the open transaction outgrew the client buffer, so the sender committed the {} rows it had " + + "already sent, and the rest of the transaction commits separately [transactionBytes={}, " + + "ringCapacityBytes={}]. A transaction=on transaction commits in parts when " + + "sf_max_total_bytes cannot hold it: raise sf_max_total_bytes or set sf_dir to keep such " + + "transactions whole, or use transaction=strict to refuse their rows instead. Logged once " + + "per transaction", + rows, bytes, cursorEngine.ringCapacityBytes()); + } + } + + /** + * Transactional mode: whether the ring under {@code sf_max_total_bytes} can hold + * a flush's frames together with the open transaction's frames already on it + * and, for a deferred flush, room for the frame that ends the transaction. The + * server acks none of a transaction's frames before its commit, so the ring + * cannot trim them; a transaction that does not fit would block its own commit. + * A strict transaction keeps room for a commit that carries the rows still + * pending when it ends, a transaction=on transaction for a bare commit frame: + * it commits its frames with one when the next flush does not fit. *

    * Mirrors how the ring packs frames: frames never span segments, and a frame * that does not fit the current segment opens the next one. The flush's * frame sizes are derived the way flushPendingRows and the split publish * them; dictionary chunks of the full-dictionary fallback count as full * frames. Runs before anything of the flush is published, so a refusal - * leaves the batch pending and the ring untouched. On a refusal it records - * the size the transaction would have reached in {@link #txnRefusedBytes}. + * leaves the batch pending and the ring untouched. On a strict refusal it + * records the size the transaction would have reached in + * {@link #txnRefusedBytes}. */ - private boolean hasStrictTransactionRoom(int cap, int deltaBaseline, int messageSize, boolean deferCommit) { + private boolean hasTransactionRoom(int cap, int deltaBaseline, int messageSize, boolean deferCommit) { CursorSendEngine engine = cursorEngine; long segmentPayload = segmentPayloadCapacity(); - strictFrameSizes.clear(); + transactionFrameSizes.clear(); if (cap <= 0 || messageSize <= cap) { - strictFrameSizes.add(messageSize); + transactionFrameSizes.add(messageSize); } else { int baseline = deltaBaseline; if (!deltaDictEnabled && currentBatchMaxSymbolId > deltaBaseline @@ -7562,23 +7644,28 @@ && splitFramesFit(cap, currentBatchMaxSymbolId)) { - QwpConstants.HEADER_SIZE; long chunkPayload = Math.max(1, cap - QwpConstants.HEADER_SIZE - 16); for (long chunks = dictBytes / chunkPayload + 1; chunks > 0; chunks--) { - strictFrameSizes.add(cap); + transactionFrameSizes.add(cap); } baseline = currentBatchMaxSymbolId; } for (int i = 0, n = splitFrameBodyBytes.size(); i < n; i++) { - strictFrameSizes.add(encoder.getSplitMessageSize( + transactionFrameSizes.add(encoder.getSplitMessageSize( splitFrameBodyBytes.getQuick(i), baseline, currentBatchMaxSymbolId)); if (deltaDictEnabled && currentBatchMaxSymbolId > baseline) { baseline = currentBatchMaxSymbolId; } } } + if (deferCommit && !strictTransactional) { + // Keep room for the bare commit or rollback frame that ends the + // transaction: the next flush that does not fit commits it with one. + transactionFrameSizes.add(COMMIT_FRAME_MAX_BYTES); + } int segments = txnSimSegments; long remaining = segments == 0 ? engine.activeSegment().capacityRemaining() : txnSimRemaining; long bytes = txnBytes; - for (int i = 0, n = strictFrameSizes.size(); i < n; i++) { - long size = strictFrameSizes.getQuick(i); + for (int i = 0, n = transactionFrameSizes.size(); i < n; i++) { + long size = transactionFrameSizes.getQuick(i); bytes += size; if (segments == 0 || size > remaining) { if (segments > 0 || size > remaining) { @@ -7588,7 +7675,7 @@ && splitFramesFit(cap, currentBatchMaxSymbolId)) { } remaining = Math.max(0, remaining - size - MmapSegment.FRAME_HEADER_SIZE); } - if (deferCommit) { + if (deferCommit && strictTransactional) { // Keep room for the commit: the rows pending when this transaction // ends are at most a frame's worth plus one row, which a split // ships as a few frames of at most cap bytes. @@ -7603,7 +7690,9 @@ && splitFramesFit(cap, currentBatchMaxSymbolId)) { } long maxSegments = Math.max(2, engine.ringCapacityBytes() / engine.segmentSizeBytes()); if (segments > maxSegments) { - txnRefusedBytes = bytes; + if (strictTransactional) { + txnRefusedBytes = bytes; + } return false; } return true; @@ -7657,9 +7746,10 @@ private void recomputeFrameBudget() { } /** - * Strict mode: advances the client-buffer simulation by one open-transaction - * frame that just reached the ring. {@code activeRemaining} is the active - * segment's room before the append, needed for the transaction's first frame. + * Transactional mode: advances the client-buffer simulation by one + * open-transaction frame that just reached the ring. {@code activeRemaining} + * is the active segment's room before the append, needed for the + * transaction's first frame. */ private void recordTransactionFrame(int payloadLen, long activeRemaining) { txnBytes += payloadLen; @@ -7684,6 +7774,17 @@ private long segmentPayloadCapacity() { : engine.segmentSizeBytes() - MmapSegment.HEADER_SIZE - MmapSegment.FRAME_HEADER_SIZE; } + /** + * Rows the open transaction's deferred frames already sent, over all its tables. + */ + private long sentTransactionRows() { + long rows = 0; + for (int i = 0, n = txnTables.size(); i < n; i++) { + rows += txnTables.getQuick(i).getTxnSentRows(); + } + return rows; + } + private LineSenderException transactionAbortedError() { return new LineSenderException("transaction aborted: rollback could not undo the frames of the " + "open transaction already sent, because the server does not support QWP rollback. Close " @@ -7715,10 +7816,7 @@ private LineSenderException transactionTooLargeForClientBuffer(String outcome) { * discardPendingRows() clears the latter. */ private void warnDiscardedTransaction(String action) { - long rows = pendingRowCount; - for (int i = 0, n = txnTables.size(); i < n; i++) { - rows += txnTables.getQuick(i).getTxnSentRows(); - } + long rows = pendingRowCount + sentTransactionRows(); if (rows > 0) { LOG.warn("{} discarded an uncommitted transaction of {} rows: a strict transactional sender " + "(transaction=strict, or one with no auto-flush trigger) commits only on flush(). Call " diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index d42307354..95d003c11 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -45,6 +45,7 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; @@ -81,6 +82,12 @@ public class QwpLargeTransactionTest { // ~100 encoded bytes per row: 1000 rows (the default row trigger) are ~100 KB, // three times the 32 KiB cap. private static final String PAD = TestUtils.repeat("x", 90); + // transaction=on in frames of exactly 280 rows (~28 KB): two fill a 64 KiB segment, + // so the 256 KiB client buffer holds eight frames of a transaction. A blocked + // append would wait 30 s. + private static final String TXN_ON_FRAMES_OF_280 = "transaction=on;auto_flush_rows=280;auto_flush_bytes=off;" + + "auto_flush_interval=off;sf_max_segment_bytes=64k;sf_max_total_bytes=256k;" + + "sf_append_deadline_millis=30000;"; @Test public void testAutoFlushBytesAloneCommitsEachBatch() throws Exception { @@ -1100,6 +1107,133 @@ public void testUnacknowledgedRollbackDoesNotStallTheSender() throws Exception { }); } + @Test + public void testTransactionalCommitsInPartsAtClientBuffer() throws Exception { + // The client holds a transaction's frames until the server commits it. The row + // whose frame found no room used to block for sf_append_deadline_millis and then + // throw, and close() then committed the frames already sent and dropped the rest. + // Now the sender commits the frames already sent and carries on, as the server + // does at qwp.max.uncommitted.rows. + assertMemoryLeak(() -> { + ListAppender log = captureSenderLog(); + try { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(conf(server) + TXN_ON_FRAMES_OF_280)) { + long start = System.nanoTime(); + // 17 frames of 280 rows, then 240 rows that flush() commits. + writeRows(s, "t", 0, 5_000); + Assert.assertEquals("two parts of eight frames", 4_480, s.getTxnRowsCommittedInPartsForTesting()); + s.flush(); + Assert.assertEquals(0, s.getTxnRowsCommittedInPartsForTesting()); + Assert.assertTrue("must not wait for sf_append_deadline_millis", + System.nanoTime() - start < TimeUnit.SECONDS.toNanos(10)); + Assert.assertTrue(s.drain(5_000)); + } + // The buffer holds eight frames, so the ninth and the seventeenth each + // start a new part, behind a bare commit frame for the frames before them. + Assert.assertEquals("DDDDDDDDcDDDDDDDDcDC", frameKinds(h)); + Assert.assertEquals("every frame commits", h.frames, h.committedFrames()); + // Logged once for the transaction, with what the first commit covered. + Assert.assertEquals(Collections.singletonList(commitInPartsWarning(2_240, frameBytes(h, 0, 8))), + commitInPartsWarnings(log)); + } + } finally { + releaseSenderLog(log); + } + }); + } + + @Test + public void testTransactionalCommitsInPartsBeforeFlushThatDoesNotFit() throws Exception { + // Eight frames fill the client buffer, and the frame flush() sends with the last + // 279 rows, which commits the transaction, does not fit beside them. flush() used + // to block for sf_append_deadline_millis and throw. Now it commits the eight + // frames first. Each transaction that commits in parts logs once. + assertMemoryLeak(() -> { + ListAppender log = captureSenderLog(); + try { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + TXN_ON_FRAMES_OF_280)) { + writeRows(s, "t", 0, 2_519); + Assert.assertTrue(h.awaitFrames(8)); + long start = System.nanoTime(); + s.flush(); + Assert.assertTrue("must not wait for sf_append_deadline_millis", + System.nanoTime() - start < TimeUnit.SECONDS.toNanos(10)); + Assert.assertTrue(s.drain(5_000)); + Assert.assertEquals("DDDDDDDDcC", frameKinds(h)); + Assert.assertEquals(Collections.singletonList( + commitInPartsWarning(2_240, frameBytes(h, 0, 8))), commitInPartsWarnings(log)); + + // The next transaction's first frame shares a segment with the + // previous commit frame, so seven frames fill the buffer this time. + writeRows(s, "t", 0, 2_519); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + Assert.assertEquals("DDDDDDDDcC" + "DDDDDDDcDC", frameKinds(h)); + Assert.assertEquals("every frame commits", h.frames, h.committedFrames()); + Assert.assertEquals(Arrays.asList( + commitInPartsWarning(2_240, frameBytes(h, 0, 8)), + commitInPartsWarning(1_960, frameBytes(h, 10, 17)) + ), commitInPartsWarnings(log)); + } + } finally { + releaseSenderLog(log); + } + }); + } + + @Test + public void testTransactionalDiscardAfterCommitInPartsWarns() throws Exception { + // The frames committed when the transaction outgrew the client buffer cannot be + // rolled back. rollback() and reset() discard the rest of the transaction, and + // say that the part already committed stays. + assertMemoryLeak(() -> { + ListAppender log = captureSenderLog(); + try { + String[] actions = {"rollback()", "reset()"}; + for (String action : actions) { + clearLog(log); + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(true); + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(conf(server) + TXN_ON_FRAMES_OF_280)) { + // Nine frames, the ninth in a new part, and 100 rows pending. + writeRows(s, "t", 0, 2_620); + Assert.assertEquals(action, 2_240, s.getTxnRowsCommittedInPartsForTesting()); + if ("rollback()".equals(action)) { + s.rollback(); + } else { + s.reset(); + } + Assert.assertEquals(action, 0, s.getTxnRowsCommittedInPartsForTesting()); + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(action, s.drain(5_000)); + } + Assert.assertEquals(action, "DDDDDDDDcDRC", frameKinds(h)); + Assert.assertEquals(action, 1, h.rolledBackGroups); + // The first part and the next transaction commit, the ninth frame does not. + List committed = new ArrayList<>(h.frames.subList(0, 9)); + committed.add(h.frames.get(11)); + Assert.assertEquals(action, committed, h.committedFrames()); + Assert.assertEquals(action, Arrays.asList( + commitInPartsWarning(2_240, frameBytes(h, 0, 8)), + action + " discarded the rows of the open transaction sent since the sender last " + + "committed part of it, but the 2240 rows it committed when the transaction " + + "outgrew the client buffer stay committed" + ), commitInPartsWarnings(log)); + } + } + } finally { + releaseSenderLog(log); + } + }); + } + @Test public void testTransactionalDefaultTriggersSplitWideRows() throws Exception { // Before: transaction=on with the default triggers threw @@ -1133,6 +1267,31 @@ private static void clearLog(ListAppender log) { } } + // What a transaction=on sender logs the first time a transaction outgrows the + // 256 KiB client buffer and it commits the part already sent. + private static String commitInPartsWarning(long rows, long transactionBytes) { + return "the open transaction outgrew the client buffer, so the sender committed the " + rows + + " rows it had already sent, and the rest of the transaction commits separately [transactionBytes=" + + transactionBytes + ", ringCapacityBytes=262144]. A transaction=on transaction commits in parts when " + + "sf_max_total_bytes cannot hold it: raise sf_max_total_bytes or set sf_dir to keep such transactions " + + "whole, or use transaction=strict to refuse their rows instead. Logged once per transaction"; + } + + // The warnings about a transaction the sender committed in parts at the client + // buffer logged since the last clearLog(), in order. + private static List commitInPartsWarnings(ListAppender log) { + List warnings = new ArrayList<>(); + synchronized (log) { + for (ILoggingEvent e : log.list) { + String message = e.getFormattedMessage(); + if (e.getLevel() == Level.WARN && message.contains("outgrew the client buffer")) { + warnings.add(message); + } + } + } + return warnings; + } + // The discarded-transaction warnings logged since the last clearLog(). private static List discardWarnings(ListAppender log) { List warnings = new ArrayList<>(); @@ -1310,13 +1469,28 @@ private static TestWebSocketServer start(TxnServer h, int cap, int port, boolean } private static long frameBytes(TxnServer h) { + return frameBytes(h, 0, h.frames.size()); + } + + // Bytes of the frames [from, to) the server received. + private static long frameBytes(TxnServer h, int from, int to) { long bytes = 0; - for (TxnFrame f : h.frames) { - bytes += f.size; + for (int i = from; i < to; i++) { + bytes += h.frames.get(i).size; } return bytes; } + // One letter per frame the server received: D deferred, c bare commit, C commit + // with rows, R rollback. + private static String frameKinds(TxnServer h) { + StringBuilder kinds = new StringBuilder(); + for (TxnFrame f : h.frames) { + kinds.append(f.isRollback() ? 'R' : f.isDeferred() ? 'D' : f.isBareCommit() ? 'c' : 'C'); + } + return kinds.toString(); + } + private static String serverRowLimitError(String table, long maxUncommittedRows) { return "transaction too large for the server [table=" + table + ", rows=" + maxUncommittedRows + ", maxUncommittedRows=" + maxUncommittedRows + "]; the server commits a table's rows on its " @@ -1368,6 +1542,11 @@ private static final class TxnFrame { this.connection = connection; } + // A commit frame with no table: the header and an empty symbol delta. + boolean isBareCommit() { + return isCommit() && size <= QwpConstants.HEADER_SIZE + 6; + } + boolean isCommit() { return (flags & QwpConstants.FLAG_DEFER_COMMIT) == 0; } From 384bf1636a3b40eb9195ddfde1549c8ad6d8f6e3 Mon Sep 17 00:00:00 2001 From: Vlad Ilyushchenko Date: Tue, 24 Nov 2026 15:41:35 +0000 Subject: [PATCH 08/20] Accept rows after reset() of a refused transaction A strict transaction whose first auto-flush did not fit in the client buffer sends nothing: flushPendingRows() keeps the rows pending and latches txnBufferFull, so the next row is refused. reset() discarded those rows but acted on the transaction only when it had sent frames, so the latch outlived the transaction it refused. Every later row then failed with "transaction too large for the client buffer" and a stale size, flush() had nothing to send, and only rollback() or a new sender recovered. With the server's default frame cap and 4 MiB segments this happens whenever sf_max_total_bytes holds fewer than four segments. reset() now ends a transaction that sent no frames the way rollback() and discardTransactionForReuse() already do: clearTransactionState() forgets it, the latch included. A transaction that sent frames is rolled back or aborted as before. QwpLargeTransactionTest covers reset() and rollback() after a refused first auto-flush, on servers with and without rollback support, a refusal after frames were sent, and a non-transactional sender's deferred frame, which reset() still leaves to the next commit. --- .../qwp/client/QwpWebSocketSender.java | 12 +- .../qwp/client/QwpLargeTransactionTest.java | 146 ++++++++++++++++++ 2 files changed, 156 insertions(+), 2 deletions(-) diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java index 7e6f01a6f..7fca9aecc 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java @@ -3413,13 +3413,21 @@ public void setCloseStartedHook(Runnable hook) { * like {@link #rollback()} it does not wait for the server. Without that * support a strict transaction is aborted -- the next flush throws and only * closing the sender ends it -- while a non-strict one keeps the frames - * already sent, and the next flush commits them, as before. + * already sent, and the next flush commits them, as before. A transaction + * that sent no frames yet ends on any server, so the next row starts a new + * one, also after the client buffer refused a row of a strict transaction. */ @Override public void reset() { checkNotClosed(); discardPendingRows(); - if (transactional && hasDeferredMessages && !txnAborted) { + if (!hasDeferredMessages) { + // No frame of the open transaction was sent, so there is nothing to roll + // back: end the transaction as rollback() does. That also clears the + // refusal a strict auto-flush latches when the client buffer cannot hold + // it, which would otherwise refuse every later row. + clearTransactionState(); + } else if (transactional && !txnAborted) { if (serverRollbackEnabled) { rollbackOpenTransaction("reset()"); } else if (strictTransactional) { diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index 95d003c11..4394c4484 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -599,6 +599,32 @@ public void testResetDuringOutageDoesNotStallTheSender() throws Exception { assertDiscardDuringOutage("transaction=on;", Sender::reset); } + @Test + public void testResetKeepsDeferredFramesOfNonTransactionalSender() throws Exception { + // Outside transactional mode reset() discards only the buffered rows, as before, + // also on a server with rollback support: a frame setDeferCommit(true) already + // sent stays deferred, and the next commit commits it. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(true); + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(conf(server) + "transaction=off;")) { + s.setDeferCommit(true); + writeRows(s, "t", 0, 10); + s.flush(); + writeRows(s, "t", 10, 10); + s.reset(); + Assert.assertTrue(s.hasDeferredMessagesForTesting()); + s.setDeferCommit(false); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + Assert.assertEquals("Dc", frameKinds(h)); + Assert.assertEquals(h.frames, h.committedFrames()); + } + }); + } + @Test public void testResetKeepsLegacyBehaviourWithoutServerRollback() throws Exception { // transaction=on against a server without rollback: reset() cannot reach the @@ -1034,6 +1060,95 @@ public void testStrictDeferredFlushTooLargeForClientBufferIsNotSent() throws Exc }); } + @Test + public void testStrictDiscardAfterRefusedFirstAutoFlushStartsNewTransaction() throws Exception { + // 64 KiB segments, 128 KiB budget: too small for a strict transaction's first + // deferred frame next to the room it keeps for its commit, so the first + // auto-flush is refused and nothing is sent. reset() used to keep the refusal, + // so the sender refused every later row until rollback() or close(). Both + // discards must end the transaction, whether or not the server supports + // rollback: there is nothing to roll back. With the interval trigger off, the + // byte trigger alone decides which row the client buffer refuses. + assertMemoryLeak(() -> { + int expectedFrameSize = commitFrameSize(10); + for (String action : new String[]{"reset()", "rollback()"}) { + for (boolean isRollbackSupported : new boolean[]{true, false}) { + String context = action + ", rollback supported: " + isRollbackSupported; + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(isRollbackSupported); + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;auto_flush_interval=off;" + + "sf_max_segment_bytes=64k;sf_max_total_bytes=128k;")) { + int refused = writeUntilRefused(s, 131_072); + Assert.assertTrue(context, refused > 0); + Assert.assertEquals(context + ": nothing was sent", 0, h.frames.size()); + if ("reset()".equals(action)) { + s.reset(); + // A repeated reset() finds nothing left to discard. + s.reset(); + } else { + s.rollback(); + } + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(context, s.drain(5_000)); + // Only the transaction after the discard reached the server, as one + // commit frame with only its rows; nothing needed a rollback frame. + Assert.assertEquals(context + ": " + h.frames, 1, h.frames.size()); + Assert.assertTrue(context, h.frames.get(0).isCommit()); + Assert.assertEquals(context, expectedFrameSize, h.frames.get(0).size); + // The next transaction has the whole client buffer again: the same + // rows meet the same refusal. + Assert.assertEquals(context, refused, writeUntilRefused(s, 131_072)); + s.rollback(); + } + Assert.assertEquals(context + ": " + h.frames, 1, h.frames.size()); + Assert.assertEquals(context, 0, h.rollbackFrames()); + } + } + } + }); + } + + @Test + public void testStrictResetAfterRefusedLaterAutoFlushDiscardsSentFrames() throws Exception { + // 64 KiB segments, 256 KiB budget: the transaction's first frames go out before + // the client buffer refuses a row. reset() discards them as for any open + // transaction: a server with rollback support rolls them back and the next + // transaction commits alone; without that support the transaction is aborted, + // so nothing can commit them, and a repeated reset() leaves it aborted. + assertMemoryLeak(() -> { + for (boolean isRollbackSupported : new boolean[]{true, false}) { + String context = "rollback supported: " + isRollbackSupported; + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(isRollbackSupported); + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;auto_flush_interval=off;" + + "sf_max_segment_bytes=64k;sf_max_total_bytes=256k;")) { + writeUntilRefused(s, 262_144); + Assert.assertTrue(context + ": frames were sent before the refusal", h.awaitFrames(2)); + s.reset(); + if (isRollbackSupported) { + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(context, s.drain(5_000)); + } else { + assertAborted(() -> s.table("t").longColumn("v", 1).atNow()); + s.reset(); + assertAborted(s::flush); + } + } + if (isRollbackSupported) { + assertRolledBackThenCommitted(h); + } else { + Assert.assertEquals(context + ": " + h.frames, 0, h.commitFrames()); + Assert.assertEquals(context + ": " + h.frames, 0, h.rollbackFrames()); + } + } + } + }); + } + @Test public void testStrictTransactionTooLargeForClientBufferFailsFast() throws Exception { // 64 KiB segments, 256 KiB budget: four segments. A strict transaction keeps @@ -1438,6 +1553,22 @@ private static void assertDiscardDuringOutage(String mode, Consumer disc }); } + // Size of the commit frame a fresh strict sender sends for rows [0, count) of + // table t: what a transaction of only those rows sends. + private static int commitFrameSize(int count) throws Exception { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { + writeRows(s, "t", 0, count); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + Assert.assertEquals(h.frames.toString(), 1, h.frames.size()); + Assert.assertTrue(h.frames.get(0).isCommit()); + return h.frames.get(0).size; + } + } + private static String conf(TestWebSocketServer server) { return "ws::addr=localhost:" + server.getPort() + ";"; } @@ -1511,6 +1642,21 @@ private static void writeTables(Sender s, int first, int count) { } } + // Writes rows 0, 1, ... of table t until the client buffer refuses one, with 64 KiB + // segments, and returns the refused row. + private static int writeUntilRefused(Sender s, long ringCapacityBytes) { + for (int row = 0; row < 100_000; row++) { + try { + s.table("t").longColumn("v", row).stringColumn("s", PAD).atNow(); + } catch (TransactionTooLargeException e) { + assertClientBufferRefusal(e, ringCapacityBytes, "so the row was not added"); + return row; + } + } + Assert.fail("the client buffer must refuse a row"); + return -1; + } + @FunctionalInterface private interface ThrowingRunnable { void run(); From 5c7f3ed4d6990636ebd11abab0a47bb6ffe2e2e7 Mon Sep 17 00:00:00 2001 From: Vlad Ilyushchenko Date: Tue, 24 Nov 2026 15:46:48 +0000 Subject: [PATCH 09/20] Discard transactions without aborting the sender rollback(), reset() of a strict transaction and the return of a strict pooled lease decided on the producer thread, from the last handshake, whether the server could roll back the frames already sent. Before the first handshake the sender cannot know, yet it assumed the server could not. With initial_connect_retry=async or lazy_connect=true and the server down at start: - rollback() threw "the server does not support QWP rollback" and aborted the transaction: every later row, flush() and rollback() threw, even once a server that supports rollback was up. - reset() of a strict transaction aborted it silently, with the same result. A sender with no auto-flush trigger is strict, so this also hit manual-flush senders once their byte trigger had sent a frame. - reset() of a transaction=on transaction warned that the server lacks rollback and kept the rows already sent, so the next flush committed them on a server that supports rollback. - Returning a strict lease retired the pooled sender, and closing it dropped the rows earlier leases had committed into its memory buffer that no server had received yet. Against a server without rollback support the same happened during any outage. Against a server without rollback support the abort also stuck: the sender stayed unusable until closed, and a pooled transaction=on lease threw the abort again from close(). The producer no longer decides. These calls always publish the rollback frame, and CursorWebSocketSendLoop decides per connection, as it already did for a reconnect that reached an older node: it sends the frame to a server that confirmed X-QWP-Rollback, and on any other connection it waits for the acks of earlier commits, then closes the connection, which makes the server roll the frames back, and reconnects. The transaction abort state and its error are gone. reset() of a transaction=on transaction keeps the rows already sent, as before rollback existed, only when the last handshake showed a server without rollback support. On a server that supports rollback nothing changes on the wire. On one that does not, discarding a transaction whose frames went out costs one reconnect, and reset() with nothing sent sends nothing. QwpLargeTransactionTest drives each case through Sender and QuestDB against the server model: discards before the first connection, with servers with and without rollback; strict reset() over every spelling of no auto-flush trigger; rollback() on a server without rollback; pool leases; and the two lost-commit scenarios. Five tests that pinned the abort now pin the discard. --- .../main/java/io/questdb/client/Sender.java | 14 +- .../qwp/client/QwpWebSocketSender.java | 142 ++---- .../sf/cursor/CursorWebSocketSendLoop.java | 16 +- .../io/questdb/client/impl/PooledSender.java | 11 +- .../qwp/client/QwpLargeTransactionTest.java | 475 ++++++++++++++---- 5 files changed, 442 insertions(+), 216 deletions(-) diff --git a/core/src/main/java/io/questdb/client/Sender.java b/core/src/main/java/io/questdb/client/Sender.java index fb21442f6..5b9b9e045 100644 --- a/core/src/main/java/io/questdb/client/Sender.java +++ b/core/src/main/java/io/questdb/client/Sender.java @@ -775,7 +775,9 @@ default void resetSymbolDictionary() { *
    * In WebSocket transactional mode ({@code transaction=on} or {@code strict}) it also * discards the rows of the open transaction that auto-flush already sent, as - * {@link #rollback()} does, when the server supports QWP rollback. + * {@link #rollback()} does. The exception is a {@code transaction=on} sender that last + * connected to a server without QWP rollback support: it keeps those rows, and the next + * flush commits them, as before rollback existed. *
    * Note: the ILP TCP and UDP transports don't support this operation. * @@ -799,15 +801,13 @@ default void resetSymbolDictionary() { * {@link LineSenderBuilder#transactional(boolean)}) keeps the parts it committed; * this discards only the rest. *
    - * Discarding rows already sent needs a server that supports QWP rollback. When - * the server does not, this method throws and aborts the transaction: every - * later flush throws too, and closing the sender discards the rows, because the - * server rolls back uncommitted rows when the connection closes. + * A server without QWP rollback support cannot discard rows already sent on request, + * so the sender closes the connection that holds them instead, which makes the server + * roll them back, and reconnects. *
    * Only the WebSocket transport supports this method. * - * @throws LineSenderException if the transport does not support rollback, or the - * server cannot discard rows already sent + * @throws LineSenderException if the transport does not support rollback */ default void rollback() { throw new LineSenderException("rollback is only supported for WebSocket transport"); diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java index 7fca9aecc..2e8fe9fd7 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java @@ -710,18 +710,21 @@ public class QwpWebSocketSender implements Sender { // commits them on its own (X-QWP-Max-Uncommitted-Rows), 0 when not advertised. // Captured on each FOREGROUND handshake, like serverMaxBatchSize. private volatile long serverMaxUncommittedRows; - // True when the current foreground connection confirmed X-QWP-Rollback, so the - // rollback control frame may go out. Captured on each FOREGROUND handshake. + // True when the server of the last FOREGROUND handshake did not confirm + // X-QWP-Rollback; false before the first handshake, while the sender cannot know. + // Only reset() of a transaction=on transaction reads it: on a server known to lack + // rollback it keeps the rows already sent, as before rollback existed. Captured on + // each FOREGROUND handshake, like serverRollbackEnabled. + private volatile boolean isServerRollbackDeclined; + // True when the server of the last FOREGROUND handshake confirmed X-QWP-Rollback. + // close() reads it to roll a strict transaction back on the server; every other + // discard publishes the rollback frame regardless, and the I/O loop decides per + // connection whether it goes out. Captured on each FOREGROUND handshake. private volatile boolean serverRollbackEnabled; // Strict transactional mode (transaction=strict, or a sender with no auto-flush // trigger): implies transactional, never lets an open transaction commit in // parts, and close() discards instead of committing. See setStrictTransactional. private boolean strictTransactional; - // Set once the open transaction can no longer be rolled back or committed as - // one: rollback()/reset() could not undo frames already sent because the - // server does not support rollback. Every later flush throws, and close() - // discards; only closing the sender ends this state. - private boolean txnAborted; // Strict mode only: set when the client buffer cannot take another deferred // frame of the open transaction and still commit it. Rejects further rows // until flush() or rollback() ends the transaction. The rows accepted before @@ -1871,20 +1874,17 @@ private void close0(boolean[] restoreInterrupt) { // sender to discard the batch, so honour that: // discard it, remember the error, and let the rest of // close() run. rethrowTerminal below still surfaces it. - if (strictTransactional || txnAborted) { + if (strictTransactional) { // A strict transaction commits only on an explicit flush(), so - // closing without one discards it, and an aborted one must never - // commit. The pending rows never left the client. The frames of - // the open transaction already sent stay uncommitted: a server - // with rollback support discards them on the rollback frame, whose - // ack the drain below waits for; any other server rolls them back - // when the connection closes, and a recovered slot retires them - // as an aborted transaction. - if (!txnAborted) { - warnDiscardedTransaction("close()"); - } + // closing without one discards it. The pending rows never left the + // client. The frames of the open transaction already sent stay + // uncommitted: a server with rollback support discards them on the + // rollback frame, whose ack the drain below waits for; any other + // server rolls them back when the connection closes, and a + // recovered slot retires them as an aborted transaction. + warnDiscardedTransaction("close()"); discardPendingRows(); - if (hasDeferredMessages && serverRollbackEnabled && !txnAborted) { + if (hasDeferredMessages && serverRollbackEnabled) { try { publishRollbackFrame(); hasDeferredMessages = false; @@ -1918,7 +1918,7 @@ private void close0(boolean[] restoreInterrupt) { sendCommitMessage(); } } - if (!strictTransactional && !txnAborted && activeBuffer != null && activeBuffer.hasData()) { + if (!strictTransactional && activeBuffer != null && activeBuffer.hasData()) { sealAndSwapBuffer(); if (!deferCommit) { lastCommitBoundaryFsn = cursorEngine.publishedFsn(); @@ -2373,11 +2373,6 @@ public void flush() { public long flushAndGetSequence() { checkNotClosed(); checkRecycleFailure(); - if (txnAborted) { - // Committing now would commit the frames a failed rollback left on - // the server together with whatever came after them. - throw transactionAbortedError(); - } if (cursorEngine != null) { cursorEngine.checkDurability(); } @@ -3409,13 +3404,13 @@ public void setCloseStartedHook(Runnable hook) { /** * Discards the rows buffered since the last flush, like before. In * transactional mode it also discards the open transaction's frames already - * sent, when the server supports QWP rollback (see {@link #rollback()}), and - * like {@link #rollback()} it does not wait for the server. Without that - * support a strict transaction is aborted -- the next flush throws and only - * closing the sender ends it -- while a non-strict one keeps the frames - * already sent, and the next flush commits them, as before. A transaction - * that sent no frames yet ends on any server, so the next row starts a new - * one, also after the client buffer refused a row of a strict transaction. + * sent, as {@link #rollback()} does, without waiting for the server. The + * exception is a transaction=on transaction on a sender whose last handshake + * was with a server without QWP rollback support: it keeps the frames already + * sent, and the next flush commits them, as before rollback existed. A + * transaction that sent no frames yet ends on any server, so the next row + * starts a new one, also after the client buffer refused a row of a strict + * transaction. */ @Override public void reset() { @@ -3427,11 +3422,9 @@ public void reset() { // refusal a strict auto-flush latches when the client buffer cannot hold // it, which would otherwise refuse every later row. clearTransactionState(); - } else if (transactional && !txnAborted) { - if (serverRollbackEnabled) { + } else if (transactional) { + if (strictTransactional || !isServerRollbackDeclined) { rollbackOpenTransaction("reset()"); - } else if (strictTransactional) { - txnAborted = true; } else if (!isResetRollbackWarned) { isResetRollbackWarned = true; LOG.warn("reset() discarded the rows not yet sent, but the server does not support QWP " @@ -3443,76 +3436,51 @@ public void reset() { /** * Discards the open transaction: the rows buffered since the last flush, - * and the transaction's frames already sent, which the server rolls back on - * the rollback control frame. Without an open transaction this only discards - * the buffered rows. + * and the transaction's frames already sent. Without an open transaction this + * only discards the buffered rows. *

    * Like {@link #flush()}, it hands the rollback frame to store-and-forward and * returns without waiting for the server, so a server outage makes it fail * only when the store-and-forward buffer is full, as it would a flush. The * frame goes out behind the transaction's frames and ahead of anything sent * later, on every connection and after a restart, so nothing sent later can - * commit the discarded rows. Call {@link #drain(long)} to wait for the server - * to confirm. + * commit the discarded rows. A server that supports QWP rollback discards them + * on the frame. A server without that support never receives it: the sender + * closes the connection that holds the rows instead, which makes the server + * discard them, and reconnects. Call {@link #drain(long)} to wait until the + * rows are discarded. *

    * A transaction=on transaction that already committed in parts, at the * client buffer or the server's {@code qwp.max.uncommitted.rows}, keeps the * parts it committed; this discards only the rest. - * - * @throws LineSenderException when frames of the open transaction were already - * sent and the server does not support QWP rollback - * (the transaction is then aborted: the next flush - * throws, and only closing the sender ends it) */ @Override public void rollback() { checkNotClosed(); checkRecycleFailure(); discardPendingRows(); - if (txnAborted) { - throw transactionAbortedError(); - } if (!hasDeferredMessages) { clearTransactionState(); return; } - if (!serverRollbackEnabled) { - txnAborted = true; - throw transactionAbortedError(); - } rollbackOpenTransaction("rollback()"); } /** * Pool hook for a strict-mode lease being returned: discards what the - * borrower left uncommitted, so the next borrower starts with no open - * transaction. Returns {@code false} when frames already sent could not be - * rolled back -- the server does not support QWP rollback, or the transaction - * was already aborted -- and the pool must retire the connection instead; the - * server rolls those frames back when the connection closes. + * borrower left uncommitted, like {@link #rollback()}, so the next borrower + * starts with no open transaction. Like rollback() it does not wait for the + * server, and the pool keeps the sender for the next borrower. */ - public boolean discardTransactionForReuse() { + public void discardTransactionForReuse() { checkNotClosed(); - if (!txnAborted) { - warnDiscardedTransaction("returning the sender to the pool"); - } + warnDiscardedTransaction("returning the sender to the pool"); discardPendingRows(); - if (txnAborted) { - return false; - } if (!hasDeferredMessages) { clearTransactionState(); - return true; - } - if (!serverRollbackEnabled) { - // Only closing the connection discards the frames already sent, so the - // transaction is over. Aborting it also keeps the close() that retires - // the connection from warning about the same rows again. - txnAborted = true; - return false; + return; } rollbackOpenTransaction("returning the sender to the pool"); - return true; } private void discardPendingRows() { @@ -3570,13 +3538,15 @@ private void publishRollbackFrame() { * store-and-forward log orders the rollback frame ahead of every frame * published later, and every connection replays the log in that order, so a * server that receives a later commit has rolled the transaction back first. - * Only a server that does not support rollback, reached by a reconnect - * before the frame was acked, could commit them: it would read the frame as - * an empty deferred frame. The I/O loop never sends it there; it discards - * the transaction by closing that connection instead (see - * {@code CursorWebSocketSendLoop.retireRollbackFrame}). The same holds for - * frames replayed after a restart or by a background drainer, which use the - * same loop. + * Only a server that does not support rollback could commit them: it would + * read the frame as an empty deferred frame. The producer cannot tell which + * server the frame reaches -- it may publish it before the first connection, + * during an outage, or while connected to such a server -- so it publishes it + * regardless, and the I/O loop decides per connection. It never sends the + * frame to such a server; it discards the transaction by closing that + * connection instead (see {@code CursorWebSocketSendLoop.retireRollbackFrame}). + * The same holds for frames replayed after a restart or by a background + * drainer, which use the same loop. *

    * The rows a transaction=on transaction committed in parts stay committed; * {@code action} names the call in the warning that says so. @@ -4256,6 +4226,7 @@ public void applyServerBatchSizeLimit(int advertisedMaxBatchSize) { public void applyServerTransactionLimits(long maxUncommittedRows, boolean rollbackEnabled) { serverMaxUncommittedRows = maxUncommittedRows; serverRollbackEnabled = rollbackEnabled; + isServerRollbackDeclined = !rollbackEnabled; } private void atMicros(long timestampMicros) { @@ -7545,9 +7516,6 @@ private void accountTransactionRows(boolean deferred) { } private void checkTransactionAcceptsRow() { - if (txnAborted) { - throw transactionAbortedError(); - } if (!strictTransactional) { return; } @@ -7793,12 +7761,6 @@ private long sentTransactionRows() { return rows; } - private LineSenderException transactionAbortedError() { - return new LineSenderException("transaction aborted: rollback could not undo the frames of the " - + "open transaction already sent, because the server does not support QWP rollback. Close " - + "the sender to discard them; the server rolls them back when the connection closes"); - } - /** * The error for a strict transaction the client buffer cannot hold: the size * the transaction would have reached, the buffer, what was refused, and the diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java index e45e53c8a..ca2715028 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java @@ -4163,14 +4163,14 @@ void positionCursorForStart() { /** * Retires the rollback control frame at the send cursor of a connection whose - * server did not confirm X-QWP-Rollback. The producer sends that frame only after - * a server confirmed rollback, so this connection is a reconnect that reached a - * server without rollback support, such as an older node after a failover, with - * the frame not yet acked. That server would read the frame as an empty deferred - * frame and commit the rolled-back transaction, whose frames it holds uncommitted - * on this connection, with the next commit frame. So the frame never goes out: - * closing the connection discards those frames instead, as every server does with - * the rows a closed connection leaves uncommitted. + * server did not confirm X-QWP-Rollback. The producer publishes that frame without + * knowing which server it reaches: it may do so before the sender's first + * connection, during an outage, while connected to a server without rollback + * support, or ahead of a failover to an older node. Such a server would read the + * frame as an empty deferred frame and commit the rolled-back transaction, whose + * frames it holds uncommitted on this connection, with the next commit frame. So + * the frame never goes out: closing the connection discards those frames instead, + * as every server does with the rows a closed connection leaves uncommitted. *

    * The close waits until the server acks every commit-bearing frame sent on this * connection before the rollback frame: the self-acknowledge below covers those diff --git a/core/src/main/java/io/questdb/client/impl/PooledSender.java b/core/src/main/java/io/questdb/client/impl/PooledSender.java index e25bad14f..45c7524b4 100644 --- a/core/src/main/java/io/questdb/client/impl/PooledSender.java +++ b/core/src/main/java/io/questdb/client/impl/PooledSender.java @@ -173,15 +173,14 @@ public void close() { Sender live = slot.live(generation); if (live instanceof QwpWebSocketSender && ((QwpWebSocketSender) live).isStrictTransactional()) { // A strict transaction commits only on an explicit flush(), so - // returning the lease discards whatever the borrower left open. - // The next borrower must not inherit it, so a transaction the - // server cannot roll back retires the connection instead (the - // server rolls it back when the connection closes). - flushed = ((QwpWebSocketSender) live).discardTransactionForReuse(); + // returning the lease discards whatever the borrower left open, as + // rollback() does, and the next borrower starts with no open + // transaction. + ((QwpWebSocketSender) live).discardTransactionForReuse(); } else { live.flush(); - flushed = true; } + flushed = true; } finally { if (flushed) { slot.pool().giveBack(this); diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index 4394c4484..0cf973282 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -82,6 +82,14 @@ public class QwpLargeTransactionTest { // ~100 encoded bytes per row: 1000 rows (the default row trigger) are ~100 KB, // three times the 32 KiB cap. private static final String PAD = TestUtils.repeat("x", 90); + // What reset() of a transaction=on transaction logs, once per sender, when it keeps the + // rows already sent because the server of the last handshake lacks rollback support. + private static final String RESET_KEEPS_ROWS_WARNING = "reset() discarded the rows not yet sent, but the " + + "server does not support QWP rollback, so the open transaction's rows already sent stay on the " + + "server and the next flush() commits them. Close the sender to discard them instead"; + // Before its first connection the sender sizes frames for the server's default frame + // cap, not for this mock's CAP: 200 rows (~20 KB) keep each such frame within CAP. + private static final String SMALL_FRAMES = "auto_flush_rows=200;"; // transaction=on in frames of exactly 280 rows (~28 KB): two fill a 64 KiB segment, // so the 256 KiB client buffer holds eight frames of a transaction. A blocked // append would wait 30 s. @@ -361,10 +369,12 @@ public void testOneAutoFlushTriggerLeftKeepsEveryBatchCommitting() throws Except } @Test - public void testPooledLeaseWithAbortedTransactionRetiresQuietly() throws Exception { - // reset() could not undo the frames already sent, so the transaction is - // aborted and every flush already said so. Returning the lease retires the - // connection, which discards the frames, without warning about them again. + public void testPooledLeaseResetWithoutServerRollbackKeepsWorking() throws Exception { + // reset() on a lease of a pool with no auto-flush trigger, against a server without + // rollback support, used to abort the transaction: every flush threw until the pool + // retired the connection. The sender now discards the rows already sent by closing + // the connection that holds them, and the lease carries on, without warning about + // rows it discarded on purpose. assertMemoryLeak(() -> { ListAppender log = captureSenderLog(); try { @@ -374,8 +384,10 @@ public void testPooledLeaseWithAbortedTransactionRetiresQuietly() throws Excepti + "auto_flush_rows=off;auto_flush_interval=off;query_pool_min=0;")) { Sender lease = db.borrowSender(); writeRows(lease, "t", 0, 1_000); + Assert.assertTrue(h.awaitFrames(2)); lease.reset(); - assertAborted(lease::flush); + writeRows(lease, "t", 0, 10); + lease.flush(); lease.close(); Sender next = db.borrowSender(); writeRows(next, "t", 0, 10); @@ -383,11 +395,10 @@ public void testPooledLeaseWithAbortedTransactionRetiresQuietly() throws Excepti Assert.assertTrue(next.drain(5_000)); next.close(); } - List committed = h.committedFrames(); - Assert.assertEquals("only the next lease commits", 1, committed.size()); - Assert.assertTrue(committed.get(0).isCommit()); - Assert.assertEquals("the aborted lease's connection was retired", 2, server.upgradeRequestCount()); + Assert.assertEquals("one reconnect discards the transaction", 2, server.upgradeRequestCount()); } + assertDiscardedByClosingConnection("reset() on a lease", h); + Assert.assertEquals("both leases commit: " + h.frames, 2, h.committedFrames().size()); Assert.assertEquals(Collections.emptyList(), discardWarnings(log)); } finally { releaseSenderLog(log); @@ -395,6 +406,33 @@ public void testPooledLeaseWithAbortedTransactionRetiresQuietly() throws Excepti }); } + @Test + public void testPooledLeaseRollbackWithoutServerRollbackClosesQuietly() throws Exception { + // rollback() on a transaction=on lease, against a server without rollback support, + // used to throw and abort the transaction, and returning the lease then threw the + // same error again: the flush that returns a transaction=on lease hit the aborted + // transaction. Now neither throws, and the next lease commits. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (QuestDB db = QuestDB.connect(conf(server) + "transaction=on;query_pool_min=0;")) { + Sender lease = db.borrowSender(); + writeRows(lease, "t", 0, 1_000); + Assert.assertTrue(h.awaitFrames(2)); + lease.rollback(); + lease.close(); + Sender next = db.borrowSender(); + writeRows(next, "t", 0, 10); + next.flush(); + Assert.assertTrue(next.drain(5_000)); + next.close(); + } + Assert.assertEquals("one reconnect discards the transaction", 2, server.upgradeRequestCount()); + } + assertDiscardedByClosingConnection("rollback() on a lease", h); + }); + } + @Test public void testPooledLeaseWithoutAutoFlushTriggerDiscardsOnReturn() throws Exception { // Returning a lease of a pool with no auto-flush trigger used to commit its rows. @@ -481,8 +519,9 @@ public void testPooledStrictLeaseCloseRetiresConnectionWithoutServerRollback() t Sender lease = db.borrowSender(); writeRows(lease, "t", 0, 1_000); Assert.assertTrue(h.awaitFrames(2)); - // The frames already sent cannot be rolled back: the pool retires - // the connection, which makes the server discard them. + // The server cannot roll back the frames already sent: the sender + // closes the connection that holds them, which makes the server + // discard them, and sends the next lease's rows on a new one. lease.close(); Sender next = db.borrowSender(); writeRows(next, "t", 0, 10); @@ -492,7 +531,95 @@ public void testPooledStrictLeaseCloseRetiresConnectionWithoutServerRollback() t } Assert.assertEquals(1, h.commitFrames()); Assert.assertEquals(0, h.rollbackFrames()); + Assert.assertEquals(2, server.upgradeRequestCount()); } + assertDiscardedByClosingConnection("strict lease returned", h); + }); + } + + @Test + public void testPooledStrictLeaseReturnBeforeFirstConnectKeepsEarlierCommits() throws Exception { + // The server is down when the pool starts. Returning a strict lease whose frames + // were already sent used to retire the pooled sender, as if the server could not + // roll them back, and closing it dropped the rows an earlier lease had committed, + // which no server had acknowledged yet. The pool now keeps the sender: once a + // server is reached the transaction is discarded, and both commits land. + for (boolean isRollbackSupported : new boolean[]{true, false}) { + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + TxnServer h = new TxnServer(); + TestWebSocketServer server = null; + try { + try (QuestDB db = QuestDB.connect(outageConf(port) + + "transaction=strict;lazy_connect=true;" + SMALL_FRAMES)) { + Sender lease = db.borrowSender(); + writeRows(lease, "t", 0, 10); + lease.flush(); + lease.close(); + lease = db.borrowSender(); + writeRows(lease, "t", 0, 600); + lease.close(); + server = start(h, CAP, port, isRollbackSupported); + lease = db.borrowSender(); + writeRows(lease, "t", 0, 5); + lease.flush(); + Assert.assertTrue(lease.drain(10_000)); + lease.close(); + } + } finally { + if (server != null) { + server.close(); + } + } + assertCommittedFlushesOnly(h, 2); + Assert.assertEquals(h.frames.toString(), isRollbackSupported ? 1 : 0, h.rollbackFrames()); + Assert.assertEquals(h.frames.toString(), isRollbackSupported ? 1 : 2, h.connectionCount()); + }); + } + } + + @Test + public void testPooledStrictLeaseReturnDuringOutageKeepsEarlierCommits() throws Exception { + // A pool connected to a server without rollback support, which then goes down. + // Returning a strict lease whose frames were already sent used to retire the pooled + // sender, and closing it dropped the rows an earlier lease had committed during the + // outage. The pool now keeps the sender, and both commits land once the server is + // back. + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + TxnServer before = new TxnServer(); + TxnServer after = new TxnServer(); + TestWebSocketServer revived = null; + try (TestWebSocketServer first = start(before, CAP, port, false)) { + try (QuestDB db = QuestDB.connect(outageConf(port) + "transaction=strict;query_pool_min=0;")) { + Sender lease = db.borrowSender(); + writeRows(lease, "t", 0, 10); + lease.flush(); + Assert.assertTrue(lease.drain(5_000)); + lease.close(); + first.close(); + lease = db.borrowSender(); + writeRows(lease, "t", 0, 10); + lease.flush(); + lease.close(); + lease = db.borrowSender(); + writeRows(lease, "t", 0, 600); + lease.close(); + revived = start(after, CAP, port, false); + lease = db.borrowSender(); + writeRows(lease, "t", 0, 5); + lease.flush(); + Assert.assertTrue(lease.drain(10_000)); + lease.close(); + } + } finally { + if (revived != null) { + revived.close(); + } + } + assertCommittedFlushesOnly(before, 1); + assertCommittedFlushesOnly(after, 2); + Assert.assertEquals(after.frames.toString(), 0, after.rollbackFrames()); }); } @@ -575,20 +702,48 @@ public void testStrictMultiTableFlushSplitsWithinTheCap() throws Exception { } @Test - public void testResetAbortsStrictTransactionWithoutServerRollback() throws Exception { - assertMemoryLeak(() -> { - TxnServer h = new TxnServer(); - try (TestWebSocketServer server = start(h, CAP)) { - try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { - writeRows(s, "t", 0, 1_000); - Assert.assertTrue(h.awaitFrames(2)); - s.reset(); - assertAborted(s::flush); - assertAborted(() -> s.table("t").longColumn("v", 1).atNow()); + public void testResetBeforeFirstConnectDiscardsStrictTransaction() throws Exception { + // reset() used to abort a strict transaction silently when no server had been + // reached yet, as if the server could not roll back: every later row and flush + // threw, even once a server that supports rollback came up. + assertDiscardBeforeFirstConnect("transaction=strict;", Sender::reset); + } + + @Test + public void testResetBeforeFirstConnectDiscardsTransaction() throws Exception { + // reset() of a transaction=on transaction used to keep the rows already sent when + // no server had been reached yet, and warned that the server does not support + // rollback: the next flush committed them even on a server that supports it. + assertDiscardBeforeFirstConnect("transaction=on;", Sender::reset); + } + + @Test + public void testResetDiscardsStrictTransactionWithoutServerRollback() throws Exception { + // A server without rollback support cannot discard the rows already sent on + // request. reset() used to abort a strict transaction silently, so every later row + // and flush threw until the sender was closed, which also hit a sender with no + // auto-flush trigger once its byte trigger had sent a frame. The sender now closes + // the connection that holds those rows, which makes the server discard them, and + // carries on. + List spellings = noTriggerSpellings(); + spellings.add(new NoTriggerSpelling("transaction=strict", c -> Sender.builder(c + "transaction=strict;"))); + for (NoTriggerSpelling spelling : spellings) { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = spelling.build(conf(server))) { + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(spelling.name, h.awaitFrames(2)); + s.reset(); + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(spelling.name, s.drain(5_000)); + } + Assert.assertEquals(spelling.name, 2, server.upgradeRequestCount()); } - Assert.assertEquals("the reset transaction must never commit", 0, h.commitFrames()); - } - }); + assertDiscardedByClosingConnection(spelling.name, h); + }); + } } @Test @@ -627,21 +782,30 @@ public void testResetKeepsDeferredFramesOfNonTransactionalSender() throws Except @Test public void testResetKeepsLegacyBehaviourWithoutServerRollback() throws Exception { - // transaction=on against a server without rollback: reset() cannot reach the - // frames already sent, and the next flush() commits them, as before. + // transaction=on against a server that the handshake showed to lack rollback: + // reset() keeps the frames already sent, and the next flush() commits them, as + // before rollback existed. It says so once per sender. assertMemoryLeak(() -> { - TxnServer h = new TxnServer(); - try (TestWebSocketServer server = start(h, CAP)) { - try (Sender s = Sender.fromConfig(conf(server) + "transaction=on;")) { - writeRows(s, "t", 0, 1_000); - Assert.assertTrue(h.awaitFrames(2)); - s.reset(); - s.flush(); - Assert.assertTrue(s.drain(5_000)); + ListAppender log = captureSenderLog(); + try { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "transaction=on;")) { + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(h.awaitFrames(2)); + s.reset(); + s.reset(); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + // The frames sent before reset() are deferred, and the flush after it + // committed them with an empty commit frame. + assertOneTransaction(h); + Assert.assertEquals(1, server.upgradeRequestCount()); } - // The frames sent before reset() are deferred, and the flush after it - // committed them with an empty commit frame. - assertOneTransaction(h); + Assert.assertEquals(Collections.singletonList(RESET_KEEPS_ROWS_WARNING), resetKeepsRowsWarnings(log)); + } finally { + releaseSenderLog(log); } }); } @@ -707,28 +871,23 @@ public void testRollbackFrameNeverReachesServerWithoutRollbackSupport() throws E } } Assert.assertEquals(0, before.committedFrames().size()); - Assert.assertEquals("the rollback frame must not reach a server without rollback support: " - + after.frames, 0, after.rollbackFrames()); - List> connections = after.framesByConnection(); - Assert.assertEquals("one connection for the discarded transaction, one for the next: " - + after.frames, 2, connections.size()); - // The reader threads of the two connections may log their first frames in - // either order: tell them apart by what they carry. - List discarded = connections.get(0); - List next = connections.get(1); - if (next.get(next.size() - 1).isDeferred()) { - discarded = connections.get(1); - next = connections.get(0); - } - Assert.assertTrue("the discarded transaction is replayed: " + after.frames, discarded.size() >= 2); - for (TxnFrame f : discarded) { - Assert.assertTrue("frame must be deferred: " + after.frames, f.isDeferred()); - } - Assert.assertTrue(next.get(next.size() - 1).isCommit()); - Assert.assertEquals("only the next transaction commits", next, after.committedFrames()); + assertDiscardedByClosingConnection("failover to a server without rollback", after); }); } + @Test + public void testRollbackBeforeFirstConnectDiscardsStrictTransaction() throws Exception { + // rollback() used to throw and abort the transaction when no server had been + // reached yet, as if the server could not roll back: every later row and flush + // threw, even once a server that supports rollback came up. + assertDiscardBeforeFirstConnect("transaction=strict;", Sender::rollback); + } + + @Test + public void testRollbackBeforeFirstConnectDiscardsTransaction() throws Exception { + assertDiscardBeforeFirstConnect("transaction=on;", Sender::rollback); + } + @Test public void testRollbackDuringOutageDoesNotStallTheSender() throws Exception { assertDiscardDuringOutage("transaction=strict;", Sender::rollback); @@ -787,24 +946,54 @@ public void testRollbackOnNonWebSocketSenderThrows() throws Exception { } @Test - public void testRollbackUnsupportedAbortsTransaction() throws Exception { - assertMemoryLeak(() -> { - TxnServer h = new TxnServer(); - try (TestWebSocketServer server = start(h, CAP)) { - try (Sender s = Sender.fromConfig(conf(server) + "transaction=on;")) { - Assert.assertFalse(((QwpWebSocketSender) s).isServerRollbackEnabled()); - writeRows(s, "t", 0, 1_000); - Assert.assertTrue(h.awaitFrames(2)); - assertAborted(s::rollback); - assertAborted(s::flush); - assertAborted(() -> s.table("t").longColumn("v", 1).atNow()); - assertAborted(s::rollback); + public void testRollbackWithoutServerRollbackDiscardsTransaction() throws Exception { + // A server without rollback support cannot discard the rows already sent on + // request. rollback() used to throw and abort the transaction, so every later row + // and flush threw until the sender was closed. The sender now closes the + // connection that holds those rows, which makes the server discard them, and + // carries on; a second rollback() finds nothing to discard. + for (String mode : new String[]{"transaction=strict;", "transaction=on;"}) { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + mode)) { + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(mode, h.awaitFrames(2)); + s.rollback(); + s.rollback(); + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(mode, s.drain(5_000)); + } + Assert.assertEquals(mode, 2, server.upgradeRequestCount()); } - // close() of an aborted transaction must not commit it either. - Assert.assertEquals(0, h.commitFrames()); - Assert.assertEquals(0, h.rollbackFrames()); - } - }); + assertDiscardedByClosingConnection(mode, h); + }); + } + } + + @Test + public void testResetWithoutSentFramesSendsNothing() throws Exception { + // reset() discards a transaction's frames already sent without asking whether the + // server supports rollback. With none sent there is nothing to discard on the + // server: no rollback frame, and no reconnect on a server without rollback support. + for (String mode : new String[]{"transaction=strict;", "transaction=on;"}) { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + mode)) { + writeRows(s, "t", 0, 10); + s.reset(); + writeRows(s, "t", 0, 5); + s.flush(); + Assert.assertTrue(mode, s.drain(5_000)); + } + Assert.assertEquals(mode, 1, server.upgradeRequestCount()); + } + Assert.assertEquals(mode + ": " + h.frames, 1, h.frames.size()); + Assert.assertTrue(mode, h.frames.get(0).isCommit()); + }); + } } @Test @@ -874,7 +1063,7 @@ public void testStrictCloseWithoutFlushWarnsOfDiscardedRows() throws Exception { // A sender with no auto-flush trigger used to commit on close(). Now close() // discards its open transaction, and says so once, counting the rows already // sent with those still buffered. A committed transaction leaves nothing to - // discard, and an aborted one already failed every flush. + // discard, and neither does one that reset() already discarded. assertMemoryLeak(() -> { ListAppender log = captureSenderLog(); try { @@ -894,9 +1083,11 @@ public void testStrictCloseWithoutFlushWarnsOfDiscardedRows() throws Exception { } try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { writeRows(s, "t", 0, 1_000); - // Frames went out and the server cannot roll them back. + // Frames went out and the server cannot roll them back: reset() + // discards them by closing the connection, and flush() then has + // nothing to commit. s.reset(); - assertAborted(s::flush); + s.flush(); } Assert.assertEquals(Collections.emptyList(), discardWarnings(log)); Assert.assertEquals(1, h.commitFrames()); @@ -1114,9 +1305,10 @@ public void testStrictDiscardAfterRefusedFirstAutoFlushStartsNewTransaction() th public void testStrictResetAfterRefusedLaterAutoFlushDiscardsSentFrames() throws Exception { // 64 KiB segments, 256 KiB budget: the transaction's first frames go out before // the client buffer refuses a row. reset() discards them as for any open - // transaction: a server with rollback support rolls them back and the next - // transaction commits alone; without that support the transaction is aborted, - // so nothing can commit them, and a repeated reset() leaves it aborted. + // transaction: a server with rollback support rolls them back, and on one without + // that support the sender closes the connection that holds them. Either way the + // refusal ends with the transaction, the next transaction commits alone, and a + // repeated reset() finds nothing left to discard. assertMemoryLeak(() -> { for (boolean isRollbackSupported : new boolean[]{true, false}) { String context = "rollback supported: " + isRollbackSupported; @@ -1128,22 +1320,17 @@ public void testStrictResetAfterRefusedLaterAutoFlushDiscardsSentFrames() throws writeUntilRefused(s, 262_144); Assert.assertTrue(context + ": frames were sent before the refusal", h.awaitFrames(2)); s.reset(); - if (isRollbackSupported) { - writeRows(s, "t", 0, 10); - s.flush(); - Assert.assertTrue(context, s.drain(5_000)); - } else { - assertAborted(() -> s.table("t").longColumn("v", 1).atNow()); - s.reset(); - assertAborted(s::flush); - } - } - if (isRollbackSupported) { - assertRolledBackThenCommitted(h); - } else { - Assert.assertEquals(context + ": " + h.frames, 0, h.commitFrames()); - Assert.assertEquals(context + ": " + h.frames, 0, h.rollbackFrames()); + s.reset(); + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(context, s.drain(5_000)); } + Assert.assertEquals(context, isRollbackSupported ? 1 : 2, server.upgradeRequestCount()); + } + if (isRollbackSupported) { + assertRolledBackThenCommitted(h); + } else { + assertDiscardedByClosingConnection(context, h); } } }); @@ -1437,6 +1624,21 @@ private static List noTriggerSpellings() { return spellings; } + // The warnings reset() logged since the last clearLog() about keeping the rows a + // transaction=on transaction already sent. + private static List resetKeepsRowsWarnings(ListAppender log) { + List warnings = new ArrayList<>(); + synchronized (log) { + for (ILoggingEvent e : log.list) { + String message = e.getFormattedMessage(); + if (e.getLevel() == Level.WARN && message.startsWith("reset() discarded")) { + warnings.add(message); + } + } + } + return warnings; + } + private static void releaseSenderLog(ListAppender log) { senderLogger().detachAppender(log); log.stop(); @@ -1446,15 +1648,83 @@ private static Logger senderLogger() { return (Logger) LoggerFactory.getLogger(QwpWebSocketSender.class); } - private static void assertAborted(ThrowingRunnable r) { - try { - r.run(); - Assert.fail("expected the aborted-transaction error"); - } catch (LineSenderException e) { - TestUtils.assertContains(e.getMessage(), "transaction aborted"); + // Asserts that the server committed only the given number of flushes, each a single + // commit frame, so that no frame of a discarded transaction committed. + private static void assertCommittedFlushesOnly(TxnServer h, int flushes) { + List committed = h.committedFrames(); + Assert.assertEquals("committed " + committed + " of " + h.frames, flushes, committed.size()); + for (TxnFrame f : committed) { + Assert.assertTrue("a deferred frame committed: " + committed, f.isCommit()); + } + } + + // The server is down when the sender starts, so the sender cannot know yet whether it + // supports rollback. A transaction's frames go to store-and-forward, the transaction is + // discarded and the next one committed, and then a server that supports rollback, or + // one that predates it, comes up. The sender must keep working throughout, and only + // the next transaction may commit. + private static void assertDiscardBeforeFirstConnect(String mode, Consumer discard) throws Exception { + for (boolean isRollbackSupported : new boolean[]{true, false}) { + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + TxnServer h = new TxnServer(); + TestWebSocketServer server = null; + ListAppender log = captureSenderLog(); + try { + try (Sender s = Sender.fromConfig(outageConf(port) + mode + + "initial_connect_retry=async;" + SMALL_FRAMES)) { + writeRows(s, "t", 0, 600); + // Must neither fail nor wait: no server has been reached yet. + discard.accept(s); + // Nor may it claim that the server lacks rollback support. + Assert.assertEquals(Collections.emptyList(), resetKeepsRowsWarnings(log)); + writeRows(s, "t", 0, 10); + s.flush(); + server = start(h, CAP, port, isRollbackSupported); + Assert.assertTrue(s.drain(10_000)); + } + } finally { + releaseSenderLog(log); + if (server != null) { + server.close(); + } + } + if (isRollbackSupported) { + assertRolledBackThenCommitted(h); + } else { + assertDiscardedByClosingConnection(mode, h); + } + }); } } + // Asserts what a server without rollback support received when the client discarded a + // transaction whose frames had reached it: those frames, all deferred, on a connection + // the client closed instead of sending the rollback frame, and on a second connection + // what came after the discard, which alone commits. + private static void assertDiscardedByClosingConnection(String name, TxnServer h) { + Assert.assertEquals(name + ": the rollback frame must not reach a server without rollback support: " + + h.frames, 0, h.rollbackFrames()); + List> connections = h.framesByConnection(); + Assert.assertEquals(name + ": one connection for the discarded transaction, one for what came next: " + + h.frames, 2, connections.size()); + // The reader threads of the two connections may log their first frames in + // either order: tell them apart by what they carry. + List discarded = connections.get(0); + List next = connections.get(1); + if (next.get(next.size() - 1).isDeferred()) { + discarded = connections.get(1); + next = connections.get(0); + } + Assert.assertTrue(name + ": the discarded transaction reached the server: " + h.frames, + discarded.size() >= 2); + for (TxnFrame f : discarded) { + Assert.assertTrue(name + ": frame must be deferred: " + h.frames, f.isDeferred()); + } + Assert.assertTrue(name + ": " + h.frames, next.get(next.size() - 1).isCommit()); + Assert.assertEquals(name + ": only what came after the discard commits", next, h.committedFrames()); + } + // Asserts the error of a strict transaction the client buffer cannot hold, with // 64 KiB segments, and returns the transaction size it reports. private static long assertClientBufferRefusal(TransactionTooLargeException e, long ringCapacityBytes, String outcome) { @@ -1657,11 +1927,6 @@ private static int writeUntilRefused(Sender s, long ringCapacityBytes) { return -1; } - @FunctionalInterface - private interface ThrowingRunnable { - void run(); - } - private static final class NoTriggerSpelling { final String name; private final Function builder; From b0d8e459914e64d66a7ec6e741bc6aa8a4bd2fdc Mon Sep 17 00:00:00 2001 From: Vlad Ilyushchenko Date: Tue, 24 Nov 2026 16:44:42 +0000 Subject: [PATCH 10/20] Size pooled strict transactions to their share The senders of a pool share one sf_max_total_bytes budget, and each can hold a strict transaction until the server commits it, yet every sender sized its strict transactions against the whole budget. Two leases whose transactions each fit the budget, but not together, both sent frames until they filled it. Each commit then waited for room that only the other commit could free, threw "cursor SF append failed" after sf_append_deadline_millis, and neither transaction committed. SegmentBudget now records how many senders may charge it at once, and SenderPool declares its maximum size. hasTransactionRoom() holds a strict transaction whose frames span segments to its sender's share, CursorSendEngine.shareSegments(): the capacity divided by the sharers, less in disk mode the segment the manager creates ahead of the next rotation. The shares add up to the budget, so the transactions of all pooled senders fit at once, and a sender refuses the row past its share right away with a TransactionTooLargeException that names the share and the settings that enlarge it. Everything else keeps its sizing: - A transaction whose frames fit one segment is exempt: with its commit it needs at most the two segments the budget grants every sender past its cap, and a share smaller than its room for the commit would refuse batches that fit one frame. - A budget no other sender shares, a sender built on its own or a pool of one, keeps the whole buffer, without the disk-mode deduction. - A transaction the whole buffer cannot hold is refused for that. - transaction=on keeps sizing against the whole buffer, so it does not split transactions that a sender of its own commits whole. The cost: a lone lease gets its share, not the whole buffer. With the defaults, 128 MiB and sender_pool_max=4, a strict transaction that spans segments counts on 32 MiB. QwpLargeTransactionTest covers two leases sequentially and on two threads, at and past their share, the two-segment floor under a share of less than a segment, the one-segment exemption, disk mode, a pool of one in memory and on disk, a refused commit and its growth past the whole buffer, a returned lease, and transaction=on in a pool. SegmentBudgetTest and SenderPoolSharedBudgetTest cover the sharer count and the pool's declaration. --- README.md | 4 + .../main/java/io/questdb/client/Sender.java | 17 +- .../qwp/client/QwpWebSocketSender.java | 54 +- .../client/TransactionTooLargeException.java | 12 +- .../client/sf/cursor/CursorSendEngine.java | 25 + .../qwp/client/sf/cursor/SegmentBudget.java | 32 +- .../io/questdb/client/impl/SenderPool.java | 6 +- .../qwp/client/QwpLargeTransactionTest.java | 473 +++++++++++++++++- .../client/sf/cursor/SegmentBudgetTest.java | 72 +++ .../test/impl/SenderPoolSharedBudgetTest.java | 16 + 10 files changed, 694 insertions(+), 17 deletions(-) create mode 100644 core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/SegmentBudgetTest.java diff --git a/README.md b/README.md index 7aaf10c95..7c43a3400 100644 --- a/README.md +++ b/README.md @@ -676,6 +676,10 @@ The ingest side also accepts store-and-forward and reconnection tuning keys (`au `sf_max_total_bytes` caps the unacknowledged data all pooled senders buffer together — 128 MiB of memory by default, 10 GiB of disk with `sf_dir` — so a larger `sender_pool_max` adds connections, not buffer memory. The only overshoot is the minimum working set every live sender keeps: two segments (`2 × sf_max_segment_bytes`, 8 MiB by default). +A strict transaction (`transaction=strict`, or no auto-flush trigger) stays in that buffer until the server commits +it, and every pooled sender may hold one at once, so a strict transaction that spans more than one segment can use +only its sender's share: `sf_max_total_bytes / sender_pool_max`, one segment less with `sf_dir`. A larger one fails +with `TransactionTooLargeException`. `sf_durability=periodic` checkpoints mmap-published data in the background; `sf_sync_interval_millis` defaults to `5000` in that mode. The interval is a target cadence: JVM scheduling and storage-sync latency add to the actual loss window. Use `request_durable_ack=on` when end-to-end server durability is also required. See the diff --git a/core/src/main/java/io/questdb/client/Sender.java b/core/src/main/java/io/questdb/client/Sender.java index 5b9b9e045..4cef6738f 100644 --- a/core/src/main/java/io/questdb/client/Sender.java +++ b/core/src/main/java/io/questdb/client/Sender.java @@ -2833,6 +2833,10 @@ private LineSenderBuilder requestDurableAckTiers(int tiers) { * {@link io.questdb.client.cutlass.qwp.client.TransactionTooLargeException} * and is not added, and {@code close()} without {@code flush()} discards the * transaction instead of committing it. + * The senders of a pool share {@code sf_max_total_bytes} and may all hold + * strict transactions at once, so there a transaction that spans more than + * one segment counts only on its sender's share: {@code sf_max_total_bytes} + * divided by {@code sender_pool_max}, less one segment with {@code sf_dir}. * A sender with no auto-flush trigger (see {@link #disableAutoFlush()}) is * in this mode unless {@link #transactional(boolean)} selects the mode. * WebSocket transport only. @@ -3133,7 +3137,9 @@ public LineSenderBuilder storeAndForwardMaxSegmentBytes(long maxSegmentBytes) { * {@link #storeAndForwardSharedBudget(SegmentBudget)}. The connection * pool behind {@link QuestDB} does that for every sender it builds, * so in a pool the cap bounds all pooled senders together, not each - * of them. + * of them, and a strict transaction that spans more than one segment + * counts only on its sender's share of the cap (see + * {@link #strictTransactional(boolean)}). */ public LineSenderBuilder storeAndForwardMaxTotalBytes(long maxTotalBytes) { if (protocol != PARAMETER_NOT_SET_EXPLICITLY && protocol != PROTOCOL_WEBSOCKET) { @@ -3154,9 +3160,12 @@ public LineSenderBuilder storeAndForwardMaxTotalBytes(long maxTotalBytes) { * minimum working set: the active segment plus the one it rotates * into. This * sender's own {@code sf_max_total_bytes} then caps only the - * background orphan drainers it starts. The connection pool behind - * {@link QuestDB} builds every sender this way. WebSocket transport - * only. + * background orphan drainers it starts. A strict transaction that + * spans more than one segment counts only on this sender's share of + * the budget: its capacity divided by the senders it was built for + * ({@link SegmentBudget#SegmentBudget(long, int)}). The connection pool + * behind {@link QuestDB} builds every sender this way, on a budget + * built for its maximum size. WebSocket transport only. * * @param budget the shared budget, or {@code null} for a private one * (the default) diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java index 2e8fe9fd7..aa0aa857a 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java @@ -753,6 +753,10 @@ public class QwpWebSocketSender implements Sender { // flush the client buffer last refused, for the error messages. Reset with the // transaction. private long txnRefusedBytes; + // Strict mode only: the flush the client buffer last refused did fit the whole + // buffer but not this sender's share of a buffer other senders share, for the + // error messages. Reset with the transaction. + private boolean isTxnRefusedAtShare; // Scratch for hasTransactionRoom: the frame sizes a flush will publish. // Producer thread only. private final IntList transactionFrameSizes = new IntList(); @@ -7553,6 +7557,7 @@ private void clearTransactionState() { txnBufferFull = false; txnBytes = 0; txnRefusedBytes = 0; + isTxnRefusedAtShare = false; txnRowsCommittedInParts = 0; txnSimSegments = 0; txnSimRemaining = 0; @@ -7594,6 +7599,10 @@ private void commitTransactionPart() { * pending when it ends, a transaction=on transaction for a bare commit frame: * it commits its frames with one when the next flush does not fit. *

    + * When other senders share the budget, as in a pool, they may all hold strict + * transactions at once, so a strict transaction whose frames span segments must + * also fit this sender's share ({@link CursorSendEngine#shareSegments(long)}). + *

    * Mirrors how the ring packs frames: frames never span segments, and a frame * that does not fit the current segment opens the next one. The flush's * frame sizes are derived the way flushPendingRows and the split publish @@ -7601,7 +7610,8 @@ private void commitTransactionPart() { * frames. Runs before anything of the flush is published, so a refusal * leaves the batch pending and the ring untouched. On a strict refusal it * records the size the transaction would have reached in - * {@link #txnRefusedBytes}. + * {@link #txnRefusedBytes}, and in {@link #isTxnRefusedAtShare} whether only + * the share refused it. */ private boolean hasTransactionRoom(int cap, int deltaBaseline, int messageSize, boolean deferCommit) { CursorSendEngine engine = cursorEngine; @@ -7651,6 +7661,9 @@ && splitFramesFit(cap, currentBatchMaxSymbolId)) { } remaining = Math.max(0, remaining - size - MmapSegment.FRAME_HEADER_SIZE); } + // The segments the transaction's frames span with this flush, without the + // room kept for the commit. + int frameSegments = segments; if (deferCommit && strictTransactional) { // Keep room for the commit: the rows pending when this transaction // ends are at most a frame's worth plus one row, which a split @@ -7664,13 +7677,28 @@ && splitFramesFit(cap, currentBatchMaxSymbolId)) { remaining = Math.max(0, remaining - reserve - MmapSegment.FRAME_HEADER_SIZE); } } - long maxSegments = Math.max(2, engine.ringCapacityBytes() / engine.segmentSizeBytes()); - if (segments > maxSegments) { + long capacity = engine.ringCapacityBytes(); + if (segments > Math.max(2, capacity / engine.segmentSizeBytes())) { if (strictTransactional) { txnRefusedBytes = bytes; + isTxnRefusedAtShare = false; } return false; } + // Every sender sharing the budget may hold a strict transaction at the same + // time, and none can trim one before the server commits it. Were each to size + // its transaction against the whole budget, together they could fill it and + // each commit would wait for room only another commit frees, so a transaction + // counts only on its sender's share. One whose frames fit a single segment is + // exempt: with its commit, a frame's worth of rows at most, it needs no more + // than the two segments the budget grants every sender past its cap, and a + // share smaller than its room for that commit would refuse even a batch that + // fits one frame. + if (strictTransactional && frameSegments > 1 && segments > Math.max(2, engine.shareSegments(capacity))) { + txnRefusedBytes = bytes; + isTxnRefusedAtShare = true; + return false; + } return true; } @@ -7762,12 +7790,26 @@ private long sentTransactionRows() { } /** - * The error for a strict transaction the client buffer cannot hold: the size - * the transaction would have reached, the buffer, what was refused, and the - * settings that make room. + * The error for a strict transaction the client buffer, or this sender's share + * of a buffer other senders share, cannot hold: the size the transaction would + * have reached, the buffer, what was refused, and the settings that make room. */ private LineSenderException transactionTooLargeForClientBuffer(String outcome) { CursorSendEngine engine = cursorEngine; + if (isTxnRefusedAtShare) { + int senders = engine.budgetSharers(); + return new TransactionTooLargeException("transaction too large for this sender's share of the client buffer") + .put(" [transactionBytes=").put(txnRefusedBytes) + .put(", ringCapacityBytes=").put(engine.ringCapacityBytes()) + .put(", senders=").put(senders) + .put(", segmentBytes=").put(engine.segmentSizeBytes()) + .put("]; the client holds a strict transaction until the server commits it, and the ").put(senders) + .put(" senders that share sf_max_total_bytes may each hold one at the same time, so a transaction " + + "that spans segments can count only on this sender's share, which cannot hold this one, ") + .put(outcome) + .put(". Raise sf_max_total_bytes, lower sender_pool_max, or set sf_dir to keep the transaction " + + "on disk"); + } return new TransactionTooLargeException("transaction too large for the client buffer") .put(" [transactionBytes=").put(txnRefusedBytes) .put(", ringCapacityBytes=").put(engine.ringCapacityBytes()) diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java index c7cc37f81..9bf6c977c 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java @@ -32,10 +32,14 @@ * limit that would stop it from committing as one transaction: the server's * per-table {@code qwp.max.uncommitted.rows}, past which the server commits the * rows on its own, or the client's {@code sf_max_total_bytes}, which must hold the - * whole uncommitted transaction until the server commits it. To send transactions - * of that size, raise the limit the message names: {@code qwp.max.uncommitted.rows} - * on the server, or {@code sf_max_total_bytes} on the client, whose default is - * larger with {@code sf_dir} set. + * whole uncommitted transaction until the server commits it. In a sender pool, whose + * senders share {@code sf_max_total_bytes} and may all hold such transactions at + * once, a transaction that spans more than one segment gets only its sender's + * share of it. To send transactions of that size, raise the limit the message + * names: {@code qwp.max.uncommitted.rows} on the server, or + * {@code sf_max_total_bytes} on the client, whose default is larger with + * {@code sf_dir} set; in a pool, a lower {@code sender_pool_max} also makes each + * share larger. *

    * {@code at()} and {@code atNow()} throw it for the row that would take the * transaction past either limit, and that row is not part of the transaction. diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorSendEngine.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorSendEngine.java index 16d9296de..3f97bc5cb 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorSendEngine.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorSendEngine.java @@ -1911,6 +1911,31 @@ public long ringCapacityBytes() { return budget.getCapacityBytes() - budget.getSideFileBytes(); } + /** + * The most senders that charge this ring's budget at once: 1 unless the + * budget is shared, as in a sender pool. + */ + public int budgetSharers() { + return manager.getBudget().getMaxSharers(); + } + + /** + * Segments of {@code capacityBytes}, the {@link #ringCapacityBytes()} of this + * ring, that a strict transaction on it can count on while each other sender + * sharing the budget pins as many: an equal share among the budget's sharers, + * or all of them when the budget is not shared. In disk mode the share also + * pays for the segment the manager creates ahead of the ring's next rotation, + * which stays charged to the budget until the ring moves into it. + */ + public long shareSegments(long capacityBytes) { + int sharers = manager.getBudget().getMaxSharers(); + if (sharers == 1) { + return capacityBytes / segmentSizeBytes; + } + long share = capacityBytes / sharers / segmentSizeBytes; + return sfDir == null ? share : share - 1; + } + /** * Configured per-segment size in bytes. */ diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentBudget.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentBudget.java index be7c5a6b8..fb9378d21 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentBudget.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentBudget.java @@ -38,7 +38,9 @@ * hands one budget to every sender it builds, so {@code sf_max_total_bytes} * caps the pool as a whole: growing the pool adds connections, not buffer * memory. Each {@link SegmentManager} keeps its own worker thread and charges - * the budget as it provisions and trims segments. + * the budget as it provisions and trims segments. The pool declares its maximum + * size as the budget's sharers ({@link #getMaxSharers()}), against whose share + * each sender sizes its strict transactions. *

    * The cap is enforced when a ring's {@link SegmentProvisioner} creates the * segment a rotation needs, and a pre-created one only ever takes free room; @@ -57,6 +59,10 @@ public final class SegmentBudget { private final long capacityBytes; + // The most senders that charge this budget at once: 1 for the budget of a + // sender built on its own, the maximum size of a pool for the pool's budget. + // Immutable, so a sender can size what it may pin without consulting the others. + private final int maxSharers; // Live gauges of each charged slot's .symbol-dict side-file bytes. Read on // every cap check rather than folded into segmentBytes: a dictionary // grows out-of-band on producer threads, so an incremental mirror would @@ -69,10 +75,22 @@ public final class SegmentBudget { private long segmentBytes; public SegmentBudget(long capacityBytes) { + this(capacityBytes, 1); + } + + /** + * A budget that at most {@code maxSharers} senders charge at once, as the + * senders of a pool of that maximum size do. See {@link #getMaxSharers()}. + */ + public SegmentBudget(long capacityBytes, int maxSharers) { if (capacityBytes <= 0) { throw new IllegalArgumentException("capacityBytes must be positive: " + capacityBytes); } + if (maxSharers < 1) { + throw new IllegalArgumentException("maxSharers must be positive: " + maxSharers); + } this.capacityBytes = capacityBytes; + this.maxSharers = maxSharers; } /** @@ -86,6 +104,18 @@ public long getCapacityBytes() { return capacityBytes; } + /** + * The most senders that charge this budget at once. A strict transaction pins + * its segments until the server commits it, and trim cannot release them, so + * all sharers may pin segments at the same time: a sender sizes a strict + * transaction that spans segments against its share of the capacity, or the + * transactions of several senders could fill the budget together and leave + * each other's commits no room. + */ + public int getMaxSharers() { + return maxSharers; + } + public synchronized long getSegmentBytes() { return segmentBytes; } diff --git a/core/src/main/java/io/questdb/client/impl/SenderPool.java b/core/src/main/java/io/questdb/client/impl/SenderPool.java index e63bd6ab3..c1040f923 100644 --- a/core/src/main/java/io/questdb/client/impl/SenderPool.java +++ b/core/src/main/java/io/questdb/client/impl/SenderPool.java @@ -79,6 +79,10 @@ * {@code sf_max_total_bytes}. That key therefore caps the pool as a whole: * growing the pool adds connections, not buffer memory. The only overshoot is * the minimum working set (two segments) each live sender is always granted. + * The budget is declared for {@code maxSize} senders: a strict transaction pins + * its segments until the server commits it, so one that spans segments counts + * only on its sender's share of the budget, and the transactions of all pooled + * senders fit at once instead of leaving each other's commits no room. *

    * Store-and-forward slots. When the configuration enables SF * ({@code sf_dir} set), every sender owns an exclusive on-disk slot @@ -557,7 +561,7 @@ private SenderPool( } this.storeAndForward = probe.isStoreAndForwardEnabled(); long budgetBytes = probe.getResolvedSfMaxTotalBytes(); - this.segmentBudget = budgetBytes > 0 ? new SegmentBudget(budgetBytes) : null; + this.segmentBudget = budgetBytes > 0 ? new SegmentBudget(budgetBytes, maxSize) : null; this.slotBaseId = this.storeAndForward ? probe.getConfiguredSenderId() : null; this.sfDir = this.storeAndForward ? probe.getConfiguredSfDir() : null; this.slotInUse = this.storeAndForward ? new boolean[maxSize] : null; diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index 0cf973282..f6ed6c27c 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -34,7 +34,9 @@ import io.questdb.client.cutlass.qwp.client.BatchTooLargeForCapException; import io.questdb.client.cutlass.qwp.client.QwpWebSocketSender; import io.questdb.client.cutlass.qwp.client.TransactionTooLargeException; +import io.questdb.client.cutlass.qwp.client.sf.cursor.SegmentBudget; import io.questdb.client.cutlass.qwp.protocol.QwpConstants; +import io.questdb.client.impl.SenderPool; import io.questdb.client.test.cutlass.qwp.websocket.TestWebSocketServer; import io.questdb.client.test.tools.TestUtils; import org.junit.Assert; @@ -51,6 +53,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CyclicBarrier; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; @@ -87,9 +90,19 @@ public class QwpLargeTransactionTest { private static final String RESET_KEEPS_ROWS_WARNING = "reset() discarded the rows not yet sent, but the " + "server does not support QWP rollback, so the open transaction's rows already sent stay on the " + "server and the next flush() commits them. Close the sender to discard them instead"; + // The settings a refusal at a sender's share of a shared client buffer names. + private static final String SHARE_REMEDY = "Raise sf_max_total_bytes, lower sender_pool_max, or set sf_dir to " + + "keep the transaction on disk"; // Before its first connection the sender sizes frames for the server's default frame // cap, not for this mock's CAP: 200 rows (~20 KB) keep each such frame within CAP. private static final String SMALL_FRAMES = "auto_flush_rows=200;"; + // A strict transaction in frames of exactly 280 rows (~28 KB): two share a 64 KiB + // segment. A deferred frame also keeps room for the commit, three 32 KiB frames: one + // fits next to a single frame of 280 rows, none next to two. So k frames span + // ceil(k/2) segments, and with the room for the commit they need 2 more segments for + // odd k and 3 more for even k. A blocked append would wait 30 s. + private static final String STRICT_FRAMES_OF_280 = "transaction=strict;auto_flush_rows=280;auto_flush_bytes=off;" + + "auto_flush_interval=off;sf_max_segment_bytes=64k;sf_append_deadline_millis=30000;"; // transaction=on in frames of exactly 280 rows (~28 KB): two fill a 64 KiB segment, // so the 256 KiB client buffer holds eight frames of a transaction. A blocked // append would wait 30 s. @@ -675,6 +688,410 @@ public void testPooledStrictLeaseCloseWithOnlyPendingRowsKeepsConnection() throw }); } + @Test + public void testPooledStrictCommitPastTheShareIsNotSent() throws Exception { + // With no auto-flush trigger at all, flush() sends the whole transaction, one + // frame per table, two to a 64 KiB segment. Two senders share 512 KiB, so each + // can count on four segments: nine tables need five, and flush() sends nothing, + // while eight fit and commit as one transaction. The refused transaction stays + // open, and once it outgrows the whole buffer, at seventeen tables in nine + // segments, the refusal says so: only a larger buffer could take it. + assertMemoryLeak(() -> { + String config = "auto_flush=off;auto_flush_bytes=off;sf_max_segment_bytes=64k;sf_max_total_bytes=512k;" + + "sender_pool_max=2;query_pool_min=0;"; + TxnServer h = new TxnServer(); + long refusedBytes = -1; + try (TestWebSocketServer server = start(h, CAP)) { + try (QuestDB db = QuestDB.connect(conf(server) + config)) { + Sender lease = db.borrowSender(); + writeTables(lease, 0, 9); + try { + lease.flush(); + Assert.fail("the sender's share cannot hold the commit"); + } catch (TransactionTooLargeException e) { + refusedBytes = assertShareRefusal(e, 524_288, 2, "so the flush was not sent"); + } + writeTables(lease, 9, 8); + try { + lease.flush(); + Assert.fail("the client buffer cannot hold the commit"); + } catch (TransactionTooLargeException e) { + assertClientBufferRefusal(e, 524_288, "so the flush was not sent"); + } + Assert.assertEquals("nothing was sent", 0, h.frames.size()); + lease.rollback(); + // The same rows, one table per transaction: the refusal reported what + // these frames add up to. + for (int t = 0; t < 9; t++) { + writeTables(lease, t, 1); + lease.flush(); + } + Assert.assertTrue(lease.drain(5_000)); + lease.close(); + } + Assert.assertEquals("CCCCCCCCC", frameKinds(h)); + Assert.assertEquals(refusedBytes, frameBytes(h)); + } + h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (QuestDB db = QuestDB.connect(conf(server) + config)) { + Sender lease = db.borrowSender(); + writeTables(lease, 0, 8); + lease.flush(); + Assert.assertTrue(lease.drain(5_000)); + lease.close(); + } + Assert.assertEquals("DDDDDDDC", frameKinds(h)); + Assert.assertEquals(h.frames.size(), h.committedFrames().size()); + } + }); + } + + @Test + public void testPooledStrictLeaseOfPoolOfOneKeepsTheWholeBuffer() throws Exception { + // A pool of one sender shares its client buffer with no other sender, so its + // lease's strict transaction may fill all of it, like that of a sender built on + // its own, on disk too: no other sender's pre-created segment can take its room. + // 520 KiB holds eight segments: eleven frames of 280 rows and the room for their + // commit, so the twelfth frame is refused. + assertMemoryLeak(() -> { + String dir = TestUtils.createTmpDir("qwp-txn-share-"); + try { + for (boolean isDiskMode : new boolean[]{false, true}) { + String context = isDiskMode ? "sf_dir" : "memory"; + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + String config = conf(server) + STRICT_FRAMES_OF_280 + "sf_max_total_bytes=520k;" + + (isDiskMode ? "sf_dir=" + dir + ";" : ""); + try (SenderPool pool = new SenderPool(config, 1, 1, 5_000, Long.MAX_VALUE, Long.MAX_VALUE)) { + Sender lease = pool.borrow(); + Refusal refusal = writeUntilTooLarge(lease, "t"); + Assert.assertEquals(context, 3_360, refusal.row); + // On disk the budget also charges the symbol dictionary files. + SegmentBudget budget = pool.getSegmentBudgetForTesting(); + assertClientBufferRefusal(refusal.error, + budget.getCapacityBytes() - budget.getSideFileBytes(), "so the row was not added"); + lease.flush(); + Assert.assertTrue(context, lease.drain(5_000)); + lease.close(); + } + if (!isDiskMode) { + // A sender built on its own refuses the same row. + try (Sender s = Sender.fromConfig(config)) { + Assert.assertEquals(3_360, writeUntilRefused(s, 532_480)); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + } + } + Assert.assertEquals(context, isDiskMode ? "DDDDDDDDDDDC" : "DDDDDDDDDDDCDDDDDDDDDDDC", frameKinds(h)); + Assert.assertEquals(context, h.frames.size(), h.committedFrames().size()); + } + } finally { + TestUtils.removeTmpDirRec(dir); + } + }); + } + + @Test + public void testPooledStrictLeaseReturnEndsTheShareRefusal() throws Exception { + // Returning a lease whose transaction its share refused discards the transaction: + // the next borrower of the same sender starts with the whole share again. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(true); + try (QuestDB db = QuestDB.connect(conf(server) + STRICT_FRAMES_OF_280 + + "sf_max_total_bytes=512k;query_pool_min=0;")) { + Sender lease = db.borrowSender(); + Refusal first = writeUntilTooLarge(lease, "t"); + Assert.assertEquals(840, first.row); + assertShareRefusal(first.error, 524_288, 4, "so the row was not added"); + lease.close(); + Sender next = db.borrowSender(); + Refusal second = writeUntilTooLarge(next, "t"); + Assert.assertEquals(840, second.row); + long refusedBytes = assertShareRefusal(second.error, 524_288, 4, "so the row was not added"); + next.flush(); + Assert.assertTrue(next.drain(5_000)); + next.close(); + Assert.assertEquals("DDRDDC", frameKinds(h)); + Assert.assertEquals(refusedBytes, frameBytes(h, 3, 6)); + } + assertRolledBackThenCommitted(h); + } + }); + } + + @Test + public void testPooledStrictLeasesRefuseRowsPastTheirShare() throws Exception { + // The senders of a pool share sf_max_total_bytes, and each may hold a strict + // transaction until the server commits it. Two leases used to size their + // transactions against the whole 512 KiB: both sent frames until together they + // filled it, then each commit waited for room the other held, threw after + // sf_append_deadline_millis, and nothing committed. A transaction that spans + // segments now counts only on its sender's share: two of the eight segments with + // four senders, and two with sixteen, whose share is less than a segment, as the + // budget grants every sender two segments past its cap. The third frame of 280 + // rows spans a second segment and needs four with the room for its commit, so it + // is refused, and row 840 with it. Each lease commits the rows it accepted, as one + // transaction, in the two segments its share holds. + assertMemoryLeak(() -> { + for (int senders : new int[]{4, 16}) { + String context = "senders: " + senders; + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + long[] refusedBytes = new long[2]; + try (QuestDB db = QuestDB.connect(conf(server) + STRICT_FRAMES_OF_280 + + "sf_max_total_bytes=512k;sender_pool_max=" + senders + ";query_pool_min=0;")) { + Sender[] leases = {db.borrowSender(), db.borrowSender()}; + long start = System.nanoTime(); + // Both transactions are open before either commits. + for (int i = 0; i < 2; i++) { + Refusal refusal = writeUntilTooLarge(leases[i], "t" + i); + Assert.assertEquals(context, 840, refusal.row); + refusedBytes[i] = assertShareRefusal(refusal.error, 524_288, senders, "so the row was not added"); + } + for (Sender lease : leases) { + lease.flush(); + } + Assert.assertTrue(context + ": must not wait for sf_append_deadline_millis", + System.nanoTime() - start < TimeUnit.SECONDS.toNanos(10)); + for (Sender lease : leases) { + Assert.assertTrue(context, lease.drain(5_000)); + lease.close(); + } + } + List> byConnection = h.framesByConnection(); + Assert.assertEquals(context + ": " + h.frames, 2, byConnection.size()); + for (int i = 0; i < 2; i++) { + Assert.assertEquals(context, "DDC", frameKinds(byConnection.get(i))); + // The refusal reported the size of the transaction that committed. + Assert.assertEquals(context, refusedBytes[i], frameBytes(byConnection.get(i))); + } + Assert.assertEquals(context, h.frames.size(), h.committedFrames().size()); + } + } + }); + } + + @Test + public void testPooledStrictLeasesRefuseRowsPastTheirShareConcurrently() throws Exception { + // Two leases fill their transactions on two threads at once, so their frames + // compete for the shared client buffer. Each counts only on its own share, so + // neither waits for room the other holds, even with both transactions at their + // share's limit: with two senders and 1 MiB the share is eight segments, which + // hold eleven frames of 280 rows and the room for their commit, so the twelfth + // frame is refused. + assertMemoryLeak(() -> { + String[] configs = {"sf_max_total_bytes=512k;", "sf_max_total_bytes=1m;sender_pool_max=2;"}; + long[] capacities = {524_288, 1_048_576}; + int[] senders = {4, 2}; + int[] refusedRows = {840, 3_360}; + String[] kinds = {"DDC", "DDDDDDDDDDDC"}; + for (int c = 0; c < configs.length; c++) { + String context = configs[c]; + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + Refusal[] refusals = new Refusal[2]; + try (QuestDB db = QuestDB.connect(conf(server) + STRICT_FRAMES_OF_280 + configs[c] + "query_pool_min=0;")) { + Sender[] leases = {db.borrowSender(), db.borrowSender()}; + CyclicBarrier barrier = new CyclicBarrier(2); + Throwable[] errors = new Throwable[2]; + Thread[] threads = new Thread[2]; + long start = System.nanoTime(); + for (int i = 0; i < 2; i++) { + final int lease = i; + threads[i] = new Thread(() -> { + try { + barrier.await(30, TimeUnit.SECONDS); + refusals[lease] = writeUntilTooLarge(leases[lease], "t" + lease); + // Both transactions are open, each at its largest, before + // either commits. + barrier.await(30, TimeUnit.SECONDS); + leases[lease].flush(); + } catch (Throwable t) { + errors[lease] = t; + barrier.reset(); + } + }); + threads[i].start(); + } + for (Thread thread : threads) { + thread.join(); + } + for (Throwable error : errors) { + if (error != null) { + throw new AssertionError(context, error); + } + } + Assert.assertTrue(context + ": must not wait for sf_append_deadline_millis", + System.nanoTime() - start < TimeUnit.SECONDS.toNanos(10)); + for (Sender lease : leases) { + Assert.assertTrue(context, lease.drain(5_000)); + lease.close(); + } + } + List> byConnection = h.framesByConnection(); + Assert.assertEquals(context + ": " + h.frames, 2, byConnection.size()); + // Connections are numbered by their first frame, not by lease: compare + // the sizes each refusal reported with the transactions that committed + // as sets. + long[] refusedBytes = new long[2]; + long[] committedBytes = new long[2]; + for (int i = 0; i < 2; i++) { + Assert.assertEquals(context, refusedRows[c], refusals[i].row); + refusedBytes[i] = assertShareRefusal(refusals[i].error, capacities[c], senders[c], + "so the row was not added"); + Assert.assertEquals(context, kinds[c], frameKinds(byConnection.get(i))); + committedBytes[i] = frameBytes(byConnection.get(i)); + } + Arrays.sort(refusedBytes); + Arrays.sort(committedBytes); + Assert.assertArrayEquals(context, refusedBytes, committedBytes); + Assert.assertEquals(context, h.frames.size(), h.committedFrames().size()); + } + } + }); + } + + @Test + public void testPooledStrictShareLeavesRoomForPrefetchedSegment() throws Exception { + // With sf_dir, the segment manager creates each sender's next segment ahead of + // time, charged to the budget until the sender moves into it, which it may not do + // while it holds a transaction: that segment comes out of the share too. Two + // senders and 648 KiB: in memory the share is five segments, which hold five + // frames of 280 rows and the room for their commit, so the sixth frame is + // refused; on disk it is four, so the fourth frame is. + assertMemoryLeak(() -> { + String dir = TestUtils.createTmpDir("qwp-txn-share-"); + try { + for (boolean isDiskMode : new boolean[]{false, true}) { + String context = isDiskMode ? "sf_dir" : "memory"; + TxnServer h = new TxnServer(); + long refusedBytes; + try (TestWebSocketServer server = start(h, CAP)) { + String config = conf(server) + STRICT_FRAMES_OF_280 + "sf_max_total_bytes=648k;" + + (isDiskMode ? "sf_dir=" + dir + ";" : ""); + try (SenderPool pool = new SenderPool(config, 1, 2, 5_000, Long.MAX_VALUE, Long.MAX_VALUE)) { + Sender lease = pool.borrow(); + Refusal refusal = writeUntilTooLarge(lease, "t"); + Assert.assertEquals(context, isDiskMode ? 1_120 : 1_680, refusal.row); + // On disk the budget also charges the symbol dictionary files. + SegmentBudget budget = pool.getSegmentBudgetForTesting(); + refusedBytes = assertShareRefusal(refusal.error, + budget.getCapacityBytes() - budget.getSideFileBytes(), 2, "so the row was not added"); + lease.flush(); + Assert.assertTrue(context, lease.drain(5_000)); + lease.close(); + } + } + Assert.assertEquals(context, isDiskMode ? "DDDC" : "DDDDDC", frameKinds(h)); + Assert.assertEquals(context, refusedBytes, frameBytes(h)); + } + } finally { + TestUtils.removeTmpDirRec(dir); + } + }); + } + + @Test + public void testPooledStrictTransactionOfOneSegmentKeepsTheWholeBuffer() throws Exception { + // The share bounds only a transaction whose frames span segments. One whose + // frames fit a single segment needs, with its commit, at most the two segments + // the budget grants every sender past its cap, whatever the others hold. Held to + // its share, a lease of a pool of four sharing 256 KiB, whose share is less than a + // segment, would refuse the first frame of every strict transaction: next to the + // room for its commit it needs three segments. A batch that fits one frame, all a + // sender with no auto-flush trigger could send before, would no longer go out. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (QuestDB db = QuestDB.connect(conf(server) + STRICT_FRAMES_OF_280 + + "sf_max_total_bytes=256k;query_pool_min=0;")) { + Sender lease = db.borrowSender(); + // Two frames, one segment. + writeRows(lease, "t", 0, 560); + lease.flush(); + // The third frame spans a second segment: the share refuses it. + Refusal refusal = writeUntilTooLarge(lease, "t"); + Assert.assertEquals(840, refusal.row); + long refusedBytes = assertShareRefusal(refusal.error, 262_144, 4, "so the row was not added"); + lease.flush(); + Assert.assertTrue(lease.drain(5_000)); + lease.close(); + Assert.assertEquals("DDcDDC", frameKinds(h)); + Assert.assertEquals(refusedBytes, frameBytes(h, 3, 6)); + } + Assert.assertEquals(h.frames.size(), h.committedFrames().size()); + } + }); + } + + @Test + public void testPooledStrictTransactionPastTheWholeBufferIsRefusedForIt() throws Exception { + // A transaction the whole client buffer cannot hold is refused for that, share or + // not, as on a sender of its own, since only a larger buffer can take it: with + // 128 KiB, two segments, the first frame of 280 rows needs three next to the room + // for its commit; with 256 KiB, four segments, nine tables sent by one flush() + // need five, more than both the buffer and the share of two segments. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (QuestDB db = QuestDB.connect(conf(server) + STRICT_FRAMES_OF_280 + + "sf_max_total_bytes=128k;sender_pool_max=2;query_pool_min=0;")) { + Sender lease = db.borrowSender(); + Assert.assertEquals(280, writeUntilRefused(lease, 131_072)); + lease.flush(); + Assert.assertTrue(lease.drain(5_000)); + lease.close(); + } + Assert.assertEquals("C", frameKinds(h)); + } + h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (QuestDB db = QuestDB.connect(conf(server) + "auto_flush=off;auto_flush_bytes=off;" + + "sf_max_segment_bytes=64k;sf_max_total_bytes=256k;sender_pool_max=2;query_pool_min=0;")) { + Sender lease = db.borrowSender(); + writeTables(lease, 0, 9); + try { + lease.flush(); + Assert.fail("the client buffer cannot hold the commit"); + } catch (TransactionTooLargeException e) { + assertClientBufferRefusal(e, 262_144, "so the flush was not sent"); + } + lease.rollback(); + lease.close(); + } + Assert.assertEquals("nothing was sent", 0, h.frames.size()); + } + }); + } + + @Test + public void testPooledTransactionalLeaseCommitsInPartsAtTheWholeBuffer() throws Exception { + // transaction=on keeps sizing a transaction against the whole client buffer, and + // commits it in parts when that cannot hold it. Held to its share in a pool of + // four, a quarter of 256 KiB, it would split transactions that a sender of its + // own commits whole. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (QuestDB db = QuestDB.connect(conf(server) + TXN_ON_FRAMES_OF_280 + "query_pool_min=0;")) { + Sender lease = db.borrowSender(); + writeRows(lease, "t", 0, 5_000); + lease.flush(); + Assert.assertTrue(lease.drain(5_000)); + lease.close(); + } + // As on a sender of its own: the buffer holds eight frames, so the ninth + // and the seventeenth each start a new part. + Assert.assertEquals("DDDDDDDDcDDDDDDDDcDC", frameKinds(h)); + Assert.assertEquals("every frame commits", h.frames.size(), h.committedFrames().size()); + } + }); + } + @Test public void testStrictMultiTableFlushSplitsWithinTheCap() throws Exception { // Ten tables in one batch carry ten schemas, so the batch the byte trigger @@ -1739,6 +2156,23 @@ private static long assertClientBufferRefusal(TransactionTooLargeException e, lo return transactionBytes; } + // Asserts the error of a strict transaction that its sender's share of a client + // buffer shared by several senders cannot hold, with 64 KiB segments, and returns + // the transaction size it reports. + private static long assertShareRefusal(TransactionTooLargeException e, long ringCapacityBytes, int senders, String outcome) { + String message = e.getMessage(); + String prefix = "transaction too large for this sender's share of the client buffer [transactionBytes="; + Assert.assertTrue(message, message.startsWith(prefix)); + long transactionBytes = Long.parseLong(message.substring(prefix.length(), message.indexOf(','))); + Assert.assertTrue(message, transactionBytes > 0); + Assert.assertEquals(prefix + transactionBytes + ", ringCapacityBytes=" + ringCapacityBytes + + ", senders=" + senders + ", segmentBytes=65536]; the client holds a strict transaction until the " + + "server commits it, and the " + senders + " senders that share sf_max_total_bytes may each hold " + + "one at the same time, so a transaction that spans segments can count only on this sender's " + + "share, which cannot hold this one, " + outcome + ". " + SHARE_REMEDY, message); + return transactionBytes; + } + // Build-time validation runs before the sender connects, so no server is needed. private static void assertConfigRejected(String config, String expectedMessage) { try { @@ -1873,6 +2307,14 @@ private static long frameBytes(TxnServer h) { return frameBytes(h, 0, h.frames.size()); } + private static long frameBytes(List frames) { + long bytes = 0; + for (int i = 0, n = frames.size(); i < n; i++) { + bytes += frames.get(i).size; + } + return bytes; + } + // Bytes of the frames [from, to) the server received. private static long frameBytes(TxnServer h, int from, int to) { long bytes = 0; @@ -1885,8 +2327,12 @@ private static long frameBytes(TxnServer h, int from, int to) { // One letter per frame the server received: D deferred, c bare commit, C commit // with rows, R rollback. private static String frameKinds(TxnServer h) { + return frameKinds(h.frames); + } + + private static String frameKinds(List frames) { StringBuilder kinds = new StringBuilder(); - for (TxnFrame f : h.frames) { + for (TxnFrame f : frames) { kinds.append(f.isRollback() ? 'R' : f.isDeferred() ? 'D' : f.isBareCommit() ? 'c' : 'C'); } return kinds.toString(); @@ -1912,6 +2358,20 @@ private static void writeTables(Sender s, int first, int count) { } } + // Writes rows 0, 1, ... of the table until the client buffer refuses one, and + // returns the refusal. + private static Refusal writeUntilTooLarge(Sender s, String table) { + for (int row = 0; row < 100_000; row++) { + try { + s.table(table).longColumn("v", row).stringColumn("s", PAD).atNow(); + } catch (TransactionTooLargeException e) { + return new Refusal(row, e); + } + } + Assert.fail("the client buffer must refuse a row"); + return null; + } + // Writes rows 0, 1, ... of table t until the client buffer refuses one, with 64 KiB // segments, and returns the refused row. private static int writeUntilRefused(Sender s, long ringCapacityBytes) { @@ -1927,6 +2387,17 @@ private static int writeUntilRefused(Sender s, long ringCapacityBytes) { return -1; } + // A row the client buffer refused, and why. + private static final class Refusal { + final TransactionTooLargeException error; + final int row; + + Refusal(int row, TransactionTooLargeException error) { + this.row = row; + this.error = error; + } + } + private static final class NoTriggerSpelling { final String name; private final Function builder; diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/SegmentBudgetTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/SegmentBudgetTest.java new file mode 100644 index 000000000..385290a22 --- /dev/null +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/SegmentBudgetTest.java @@ -0,0 +1,72 @@ +/*+***************************************************************************** + * ___ _ ____ ____ + * / _ \ _ _ ___ ___| |_| _ \| __ ) + * | | | | | | |/ _ \/ __| __| | | | _ \ + * | |_| | |_| | __/\__ \ |_| |_| | |_) | + * \__\_\\__,_|\___||___/\__|____/|____/ + * + * 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.sf.cursor; + +import io.questdb.client.cutlass.qwp.client.sf.cursor.SegmentBudget; +import org.junit.Assert; +import org.junit.Test; + +/** + * How many senders a {@link SegmentBudget} is declared for: a sender sizes the + * strict transactions it accepts against its share of the budget. + */ +public class SegmentBudgetTest { + + @Test + public void testCapacityIsValidatedBeforeSharers() { + assertRejected(0, 0, "capacityBytes must be positive: 0"); + assertRejected(-1, 2, "capacityBytes must be positive: -1"); + } + + @Test + public void testMaxSharersDefaultsToOne() { + // A budget built for one sender, as every sender built on its own gets. + Assert.assertEquals(1, new SegmentBudget(1).getMaxSharers()); + Assert.assertEquals(1, new SegmentBudget(Long.MAX_VALUE).getMaxSharers()); + } + + @Test + public void testMaxSharersIsKept() { + Assert.assertEquals(1, new SegmentBudget(1024, 1).getMaxSharers()); + Assert.assertEquals(2, new SegmentBudget(1024, 2).getMaxSharers()); + Assert.assertEquals(Integer.MAX_VALUE, new SegmentBudget(1024, Integer.MAX_VALUE).getMaxSharers()); + } + + @Test + public void testMaxSharersMustBePositive() { + assertRejected(1024, 0, "maxSharers must be positive: 0"); + assertRejected(1024, -1, "maxSharers must be positive: -1"); + assertRejected(1024, Integer.MIN_VALUE, "maxSharers must be positive: " + Integer.MIN_VALUE); + } + + private static void assertRejected(long capacityBytes, int maxSharers, String expectedMessage) { + try { + new SegmentBudget(capacityBytes, maxSharers); + Assert.fail("must reject capacityBytes=" + capacityBytes + ", maxSharers=" + maxSharers); + } catch (IllegalArgumentException e) { + Assert.assertEquals(expectedMessage, e.getMessage()); + } + } +} diff --git a/core/src/test/java/io/questdb/client/test/impl/SenderPoolSharedBudgetTest.java b/core/src/test/java/io/questdb/client/test/impl/SenderPoolSharedBudgetTest.java index deb97f0e3..3ef73521e 100644 --- a/core/src/test/java/io/questdb/client/test/impl/SenderPoolSharedBudgetTest.java +++ b/core/src/test/java/io/questdb/client/test/impl/SenderPoolSharedBudgetTest.java @@ -81,6 +81,22 @@ public void testBudgetIsSizedFromTheResolvedSfMaxTotalBytes() throws Exception { }); } + @Test + public void testBudgetIsDeclaredForThePoolMaximumSize() throws Exception { + // Every sender the pool may build at once can hold a strict transaction + // until the server commits it, so the budget is declared for maxSize senders: + // each sizes its transactions against its share. + TestUtils.assertMemoryLeak(() -> { + for (int maxSize : new int[]{1, POOL_SIZE, 9}) { + // min=0 builds no sender, so nothing connects to this address. + try (SenderPool pool = new SenderPool("ws::addr=127.0.0.1:1;", 0, maxSize, 1_000, + Long.MAX_VALUE, Long.MAX_VALUE)) { + Assert.assertEquals(maxSize, pool.getSegmentBudgetForTesting().getMaxSharers()); + } + } + }); + } + @Test public void testPooledSendersShareOneBudget() throws Exception { TestUtils.assertMemoryLeak(() -> { From 3f711384f52d62c43c8e8807c09a9c4b07284539 Mon Sep 17 00:00:00 2001 From: Vlad Ilyushchenko Date: Tue, 24 Nov 2026 18:40:40 +0000 Subject: [PATCH 11/20] Count every spelling of a table at the row limit The server counts the rows of names that differ only in letter case as one table's. The engine resolves a table name by folding each UTF-16 char with Character.toLowerCase(), and QwpTudCache keys its writers the same way, so "t" and "T" share one writer and one count against qwp.max.uncommitted.rows. A strict transaction counted the rows of each spelling apart, in that spelling's own table buffer, so it accepted 999 rows of "t" and 999 of "T" under a limit of 1000. The server then committed the table on its own at 1000 rows and the transaction landed in parts: flush() committed it as two WAL transactions, and rollback(), reset(), close() without flush() and returning a pooled lease kept the part the server had committed. Each name keeps its own buffer, so rows still go out under the name they were written under, and nothing changes on the wire. What changes is that newTableBuffer() links the buffers of names that differ only in letter case into the spellings of one table, through a map keyed by the name with each char folded by Character.toLowerCase(), the fold Chars.toLowerCase() already implements. That lookup runs once per new name, never per row. checkTransactionAcceptsRow() adds up the rows of every spelling, those sent in deferred frames and those still buffered, from the counts the buffers already keep, so no new counter has to stay in step with them. A table almost always has one spelling, so the check does the same work as before and allocates nothing. The fold is the engine's, char by char: "ti" and its spelling with a dotted capital I are one table, as that letter folds to an ASCII i, while the case of a supplementary letter, a surrogate pair, stays, and a sharp s is no double s. String.toLowerCase() would differ on both counts, and an ASCII-only fold would split names with non-ASCII letters. When the table has several spellings, the refusal says that their rows count together. QwpLargeTransactionTest covers the limit over three spellings of a table, over rows still pending in both spellings, after rollback(), reset() and a pooled lease's return, with the engine's fold of non-ASCII letters, and the row path allocating nothing with two alternating spellings. QwpWebSocketSenderTest covers which buffers become spellings of one table. --- .../main/java/io/questdb/client/Sender.java | 3 +- .../qwp/client/QwpWebSocketSender.java | 51 +++- .../cutlass/qwp/protocol/QwpTableBuffer.java | 46 +++- .../qwp/client/QwpLargeTransactionTest.java | 219 ++++++++++++++++++ .../qwp/client/QwpWebSocketSenderTest.java | 57 +++++ 5 files changed, 364 insertions(+), 12 deletions(-) diff --git a/core/src/main/java/io/questdb/client/Sender.java b/core/src/main/java/io/questdb/client/Sender.java index 4cef6738f..90448c6d8 100644 --- a/core/src/main/java/io/questdb/client/Sender.java +++ b/core/src/main/java/io/questdb/client/Sender.java @@ -2828,7 +2828,8 @@ private LineSenderBuilder requestDurableAckTiers(int tiers) { * sends rows to the server without committing them and {@code flush()} * commits, so a transaction can be any size. In addition the transaction * never commits in parts: a row that would take a table past the server's - * {@code qwp.max.uncommitted.rows}, or the transaction past + * {@code qwp.max.uncommitted.rows}, which counts the rows sent under every name + * that differs from the table's only in letter case, or the transaction past * {@code sf_max_total_bytes}, throws * {@link io.questdb.client.cutlass.qwp.client.TransactionTooLargeException} * and is not added, and {@code close()} without {@code flush()} discards the diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java index aa0aa857a..8eca6c0eb 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java @@ -277,6 +277,12 @@ public class QwpWebSocketSender implements Sender { private final ObjList pendingTables = new ObjList<>(); private final IntList splitFrameBodyBytes = new IntList(); private final CharSequenceObjHashMap tableBuffers; + // The first spelling of every table in tableBuffers, by the table name with every + // char folded by Character.toLowerCase(), as the engine compares table names. The + // server keys its writers the same way (QwpTudCache.tableKey()), so the names that + // fold to one key are spellings of one table (QwpTableBuffer.getFirstSpelling()). + // Producer thread only. + private final CharSequenceObjHashMap firstSpellings = new CharSequenceObjHashMap<>(); // null means plain text (no TLS) private final ClientTlsConfiguration tlsConfig; private MicrobatchBuffer activeBuffer; @@ -2013,6 +2019,7 @@ private void close0(boolean[] restoreInterrupt) { } } tableBuffers.clear(); + firstSpellings.clear(); pendingTables.clear(); } catch (Throwable t) { LOG.error("Error closing encoder or table buffers: {}", String.valueOf(t)); @@ -2857,8 +2864,7 @@ public int getResetFloorSymbolsForTesting() { public QwpTableBuffer getTableBuffer(String tableName) { QwpTableBuffer buffer = tableBuffers.get(tableName); if (buffer == null) { - buffer = new QwpTableBuffer(tableName, this); - tableBuffers.put(tableName, buffer); + buffer = newTableBuffer(tableName); } currentTableBuffer = buffer; currentTableBufferSnapshotBytes = buffer.getBufferedBytes(); @@ -4075,8 +4081,7 @@ public QwpWebSocketSender table(CharSequence tableName) { currentTableName = currentTableBuffer.getTableName(); } else { currentTableName = tableName.toString(); - currentTableBuffer = new QwpTableBuffer(currentTableName, this); - tableBuffers.put(currentTableName, currentTableBuffer); + currentTableBuffer = newTableBuffer(currentTableName); } // Re-snap so sendRow()'s delta math is anchored to this table's // current byte count. The prior current table's bytes already match @@ -5886,6 +5891,25 @@ private void flushPendingRowsSplit( resetTableBuffersAfterFlush(); } + /** + * Creates the buffer of a table name the sender has no buffer for, and makes it + * a spelling of the table whose name differs from it only in letter case, if the + * sender has a buffer of one: the server counts the rows of every spelling as one + * table's, and so must a strict transaction. Runs once per name. + */ + private QwpTableBuffer newTableBuffer(String tableName) { + QwpTableBuffer buffer = new QwpTableBuffer(tableName, this); + tableBuffers.put(tableName, buffer); + String lowerCaseName = Chars.toLowerCase(tableName); + int index = firstSpellings.keyIndex(lowerCaseName); + if (index < 0) { + firstSpellings.valueAtQuick(index).addSpelling(buffer); + } else { + firstSpellings.putAt(index, lowerCaseName, buffer); + } + return buffer; + } + private void onSlotLockReleased() { slotLockReleased = true; Runnable listener = slotLockReleaseListener; @@ -7532,15 +7556,28 @@ private void checkTransactionAcceptsRow() { } // The server commits a table on its own once its uncommitted rows reach // maxRows, so a strict transaction holds at most maxRows - 1 rows per table. - long rows = currentTableBuffer.getTxnSentRows() + currentTableBuffer.getRowCount() + 1; + // The server counts the rows of every spelling of the table, the names that + // differ only in letter case, as one table's: add up the rows of each, those + // shipped in deferred frames and those still buffered. A table almost always + // has one spelling. + QwpTableBuffer firstSpelling = currentTableBuffer.getFirstSpelling(); + long rows = 1; + for (QwpTableBuffer spelling = firstSpelling; spelling != null; spelling = spelling.getNextSpelling()) { + rows += spelling.getTxnSentRows() + spelling.getRowCount(); + } if (rows >= maxRows) { - throw new TransactionTooLargeException("transaction too large for the server") + LineSenderException e = new TransactionTooLargeException("transaction too large for the server") .put(" [table=").put(currentTableName) .put(", rows=").put(rows) .put(", maxUncommittedRows=").put(maxRows) .put("]; the server commits a table's rows on its own once qwp.max.uncommitted.rows " + "of them are uncommitted, which would split the transaction, so the row was " - + "not added. Raise qwp.max.uncommitted.rows on the server"); + + "not added."); + if (firstSpelling.getNextSpelling() != null) { + e.put(" Rows sent under names that differ only in letter case count together: the server " + + "counts them as one table."); + } + throw e.put(" Raise qwp.max.uncommitted.rows on the server"); } } diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpTableBuffer.java b/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpTableBuffer.java index 7e7ce99b6..e999db072 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpTableBuffer.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpTableBuffer.java @@ -73,13 +73,21 @@ public class QwpTableBuffer implements QuietCloseable { private int committedColumnCount; // columns that existed at last nextRow() private byte[] encodedColumnDefs; private ColumnBuffer[] fastColumns; // plain array for O(1) sequential access + // The spellings of this buffer's table: buffers of names that differ only in + // letter case, each char folded by Character.toLowerCase() as the engine compares + // table names, whose rows the server counts as one table's. firstSpelling is the + // one the sender created first, this buffer if no other, and nextSpelling chains + // the rest behind it. Producer thread only. + private QwpTableBuffer firstSpelling = this; private int inProgressColumnCount; // Set while the sender's pending-tables list holds this buffer, so the // buffer is listed once. Producer thread only. private boolean listedPending; + private QwpTableBuffer nextSpelling; private int rowCount; - // Rows of this table the sender already shipped in FLAG_DEFER_COMMIT frames - // of the open transaction. Producer thread only. + // Rows of this buffer the sender already shipped in FLAG_DEFER_COMMIT frames + // of the open transaction, not counting the other spellings of its table. + // Producer thread only. private long txnSentRows; public QwpTableBuffer(String tableName) { @@ -102,6 +110,19 @@ public QwpTableBuffer(String tableName, QwpWebSocketSender sender) { this.columnDefsCacheValid = false; } + /** + * Makes {@code spelling}, a buffer new to the sender, another spelling of this + * buffer's table: its name differs from this one's only in letter case, and this + * buffer is the table's first spelling. + */ + public void addSpelling(QwpTableBuffer spelling) { + assert firstSpelling == this : "spellings join the first spelling"; + assert spelling.firstSpelling == spelling && spelling.nextSpelling == null : "a spelling joins one table once"; + spelling.firstSpelling = this; + spelling.nextSpelling = nextSpelling; + nextSpelling = spelling; + } + /** * Cancels the current in-progress row. *

    @@ -219,6 +240,22 @@ public ColumnBuffer getExistingColumn(CharSequence name, byte type) { return lookupColumn(name, type); } + /** + * Returns the first spelling of this buffer's table, this buffer itself when the + * sender has no buffer of a name that differs from this one's only in letter case. + * Its {@link #getNextSpelling()} chain lists the other spellings. + */ + public QwpTableBuffer getFirstSpelling() { + return firstSpelling; + } + + /** + * Returns the next spelling of this buffer's table, or {@code null} after the last. + */ + public QwpTableBuffer getNextSpelling() { + return nextSpelling; + } + /** * Gets or creates a column with the given name and type. *

    @@ -286,8 +323,9 @@ public String getTableName() { } /** - * Rows of this table already shipped in FLAG_DEFER_COMMIT frames of the - * sender's open transaction; 0 outside a transaction. + * Rows of this buffer already shipped in FLAG_DEFER_COMMIT frames of the + * sender's open transaction, not counting the other spellings of its table + * (see {@link #getFirstSpelling()}); 0 outside a transaction. */ public long getTxnSentRows() { return txnSentRows; diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index f6ed6c27c..406b404c4 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -40,10 +40,12 @@ import io.questdb.client.test.cutlass.qwp.websocket.TestWebSocketServer; import io.questdb.client.test.tools.TestUtils; import org.junit.Assert; +import org.junit.Assume; import org.junit.Test; import org.slf4j.LoggerFactory; import java.io.IOException; +import java.lang.management.ManagementFactory; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; @@ -1593,6 +1595,191 @@ public void testStrictRowLimitDefaultsWhenNotAdvertised() throws Exception { }); } + @Test + public void testStrictRowLimitCountsEverySpellingOfATable() throws Exception { + // The server writes the rows of names that differ only in letter case to one + // table and commits it on its own once the advertised 100 of its rows are + // uncommitted. Each spelling used to keep its own count, so a transaction that + // wrote "tab" and "TAB" took 99 rows of each, and the server committed it in + // parts. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, 4_096)) { + server.setAdvertisedMaxUncommittedRows(100); + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { + // 4 KiB frames: the rows go out over several deferred frames, and + // the last of them are still pending. + writeRows(s, "tab", 0, 40); + writeRows(s, "TAB", 40, 40); + writeRows(s, "Tab", 80, 19); + Assert.assertTrue(h.awaitFrames(2)); + // "tAB" is new to the sender: its first row is the 100th of the table. + for (String spelling : new String[]{"tab", "TAB", "Tab", "tAB"}) { + try { + writeRows(s, spelling, 99, 1); + Assert.fail("the 100th row of the table must be refused as " + spelling); + } catch (TransactionTooLargeException e) { + Assert.assertEquals(spellingsRowLimitError(spelling, 100), e.getMessage()); + } + } + // Other tables keep their own count. + writeRows(s, "other", 0, 99); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + // A new transaction starts from zero again, for every spelling. + writeRows(s, "TAB", 0, 50); + writeRows(s, "tAB", 50, 49); + try { + writeRows(s, "tab", 99, 1); + Assert.fail("the 100th row of the table must be refused"); + } catch (TransactionTooLargeException e) { + Assert.assertEquals(spellingsRowLimitError("tab", 100), e.getMessage()); + } + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + Assert.assertEquals(0, h.rollbackFrames()); + Assert.assertEquals(2, h.commitFrames()); + } + }); + } + + @Test + public void testStrictRowLimitCheckAllocatesNothingPerRow() throws Exception { + // The check runs for every row of a strict transaction and walks every spelling + // of the row's table, here two that alternate row by row. It only reads counts + // the buffers keep. + Assume.assumeTrue(ManagementFactory.getThreadMXBean() instanceof com.sun.management.ThreadMXBean); + com.sun.management.ThreadMXBean mx = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean(); + Assume.assumeTrue(mx.isThreadAllocatedMemorySupported()); + mx.setThreadAllocatedMemoryEnabled(true); + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + // Nothing goes out before flush(), so only the row path runs. + try (Sender s = Sender.fromConfig(conf(server) + "auto_flush=off;auto_flush_bytes=off;")) { + Assert.assertTrue(((QwpWebSocketSender) s).isStrictTransactional()); + long tid = Thread.currentThread().getId(); + // The first pass creates both buffers and grows their columns. + writeAlternatingSpellings(s, 20_000); + s.reset(); + long before = mx.getThreadAllocatedBytes(tid); + writeAlternatingSpellings(s, 20_000); + long allocated = mx.getThreadAllocatedBytes(tid) - before; + // An object per row would take at least 16 bytes each, 320 KB in all. + // The allowance covers one-off costs, such as a coverage agent's probes. + Assert.assertTrue("the row path allocated " + allocated + " bytes", allocated < 8_192); + s.reset(); + } + Assert.assertEquals("nothing was sent", 0, h.frames.size()); + } + }); + } + + @Test + public void testStrictRowLimitCountsPendingRowsOfEverySpelling() throws Exception { + // Nothing goes out before flush(), which then sends the rows of both spellings + // to the same table: their pending rows count together too. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setAdvertisedMaxUncommittedRows(100); + try (Sender s = Sender.fromConfig(conf(server) + "auto_flush=off;")) { + QwpWebSocketSender ws = (QwpWebSocketSender) s; + Assert.assertTrue(ws.isStrictTransactional()); + writeRows(s, "t", 0, 50); + writeRows(s, "T", 50, 49); + try { + writeRows(s, "t", 99, 1); + Assert.fail("the 100th row of the table must be refused"); + } catch (TransactionTooLargeException e) { + Assert.assertEquals(spellingsRowLimitError("t", 100), e.getMessage()); + } + Assert.assertFalse("no frame went out before flush()", ws.hasDeferredMessagesForTesting()); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + Assert.assertEquals("one commit frame", "C", frameKinds(h)); + } + }); + } + + @Test + public void testStrictRowLimitResetsEverySpellingWithTheTransaction() throws Exception { + // rollback(), reset() and returning a pooled lease end the transaction for every + // spelling of a table, whichever of them the transaction wrote last. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, 4_096)) { + server.setAdvertisedMaxUncommittedRows(100); + server.setRollbackSupported(true); + try (QuestDB db = QuestDB.connect(conf(server) + "transaction=strict;query_pool_min=0;")) { + try (Sender lease = db.borrowSender()) { + assertSpellingsRefuseRow100(lease); + lease.rollback(); + assertSpellingsRefuseRow100(lease); + lease.reset(); + assertSpellingsRefuseRow100(lease); + } + // The pool discarded that transaction, so the next lease of the same + // sender starts from zero. + try (Sender lease = db.borrowSender()) { + assertSpellingsRefuseRow100(lease); + lease.flush(); + Assert.assertTrue(lease.drain(5_000)); + } + } + Assert.assertEquals("one connection, so one sender", 1, server.upgradeRequestCount()); + Assert.assertEquals(3, h.rollbackFrames()); + Assert.assertEquals(1, h.commitFrames()); + } + }); + } + + @Test + public void testStrictRowLimitFoldsLetterCaseAsTheEngine() throws Exception { + // The server counts the rows of the names the engine resolves to one table + // together, and the engine folds each char with Character.toLowerCase(): "t\u00e4" + // and "t\u00c4" are one table, and so are "ti" and "t\u0130", whose \u0130 folds to + // an ASCII i. That leaves apart the cases of a letter outside the Basic + // Multilingual Plane, a surrogate pair, and "\u00df" against "SS". + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, 4_096)) { + server.setAdvertisedMaxUncommittedRows(100); + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { + writeRows(s, "t\u00e4", 0, 50); + writeRows(s, "t\u00c4", 50, 49); + writeRows(s, "ti", 0, 50); + writeRows(s, "t\u0130", 50, 49); + writeRows(s, "t\uD801\uDC00", 0, 99); + writeRows(s, "t\uD801\uDC28", 0, 99); + writeRows(s, "stra\u00dfe", 0, 99); + writeRows(s, "STRASSE", 0, 99); + for (String spelling : new String[]{"T\u00c4", "TI", "T\u0130"}) { + try { + writeRows(s, spelling, 99, 1); + Assert.fail("the 100th row of the table must be refused as " + spelling); + } catch (TransactionTooLargeException e) { + Assert.assertEquals(spellingsRowLimitError(spelling, 100), e.getMessage()); + } + } + for (String table : new String[]{"t\uD801\uDC00", "t\uD801\uDC28", "stra\u00dfe", "STRASSE"}) { + try { + writeRows(s, table, 99, 1); + Assert.fail("the 100th row of " + table + " must be refused"); + } catch (TransactionTooLargeException e) { + Assert.assertEquals(serverRowLimitError(table, 100), e.getMessage()); + } + } + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + Assert.assertEquals(1, h.commitFrames()); + } + }); + } + @Test public void testStrictCommitTooLargeForClientBufferIsNotSent() throws Exception { // With auto_flush_bytes=off on top of auto_flush=off, the whole transaction @@ -2345,6 +2532,38 @@ private static String serverRowLimitError(String table, long maxUncommittedRows) + "so the row was not added. Raise qwp.max.uncommitted.rows on the server"; } + // Writes 99 rows of a table under two spellings, which send some of them in deferred + // frames of 4 KiB, and checks that a 100th row is refused under each. + private static void assertSpellingsRefuseRow100(Sender s) { + writeRows(s, "x", 0, 60); + writeRows(s, "X", 60, 39); + for (String spelling : new String[]{"x", "X"}) { + try { + writeRows(s, spelling, 99, 1); + Assert.fail("the 100th row of the table must be refused as " + spelling); + } catch (TransactionTooLargeException e) { + Assert.assertEquals(spellingsRowLimitError(spelling, 100), e.getMessage()); + } + } + } + + // Writes count rows of one table, alternating between two spellings of its name. + private static void writeAlternatingSpellings(Sender s, int count) { + for (int i = 0; i < count; i++) { + s.table(i % 2 == 0 ? "t" : "T").longColumn("v", i).atNow(); + } + } + + // The refusal at the server's row limit of a table the transaction wrote under names + // that differ only in letter case. + private static String spellingsRowLimitError(String table, long maxUncommittedRows) { + return "transaction too large for the server [table=" + table + ", rows=" + maxUncommittedRows + + ", maxUncommittedRows=" + maxUncommittedRows + "]; the server commits a table's rows on its " + + "own once qwp.max.uncommitted.rows of them are uncommitted, which would split the transaction, " + + "so the row was not added. Rows sent under names that differ only in letter case count together: " + + "the server counts them as one table. Raise qwp.max.uncommitted.rows on the server"; + } + private static void writeRows(Sender s, String table, int from, int count) { for (int i = from, n = from + count; i < n; i++) { s.table(table).longColumn("v", i).stringColumn("s", PAD).atNow(); diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpWebSocketSenderTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpWebSocketSenderTest.java index 0df432cc7..12be1f05a 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpWebSocketSenderTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpWebSocketSenderTest.java @@ -668,6 +668,49 @@ public void testLongColumnAfterCloseThrows() throws Exception { }); } + @Test + public void testNamesDifferingOnlyInLetterCaseAreSpellingsOfOneTable() throws Exception { + // The server counts the rows of such names as one table. Each keeps its own + // buffer, so its rows go out under the name they were written under, and the + // buffers form the spellings of that table. Names differ only in letter case + // when each char folds to the same one with Character.toLowerCase(), as the + // engine compares table names. + assertMemoryLeak(() -> { + try (QwpWebSocketSender sender = createUnconnectedSender()) { + QwpTableBuffer first = sender.getTableBuffer("Trades"); + sender.table("TRADES"); + QwpTableBuffer upper = sender.getTableBuffer("TRADES"); + QwpTableBuffer lower = sender.getTableBuffer("trades"); + QwpTableBuffer other = sender.getTableBuffer("trades2"); + QwpTableBuffer umlaut = sender.getTableBuffer("tr\u00c4des"); + QwpTableBuffer umlautUpper = sender.getTableBuffer("TR\u00c4DES"); + QwpTableBuffer umlautLower = sender.getTableBuffer("TR\u00e4DES"); + // The dotted capital I folds to an ASCII i, and the Kelvin sign to an ASCII k. + QwpTableBuffer dotless = sender.getTableBuffer("ti"); + QwpTableBuffer dotted = sender.getTableBuffer("t\u0130"); + QwpTableBuffer kelvinSign = sender.getTableBuffer("\u212Aelvin"); + QwpTableBuffer kelvin = sender.getTableBuffer("KELVIN"); + // Chars fold one by one: the surrogates of a supplementary letter keep its + // case, and a sharp s is no double s. + QwpTableBuffer deseretUpper = sender.getTableBuffer("t\uD801\uDC00"); + QwpTableBuffer deseretLower = sender.getTableBuffer("t\uD801\uDC28"); + QwpTableBuffer sharpS = sender.getTableBuffer("stra\u00dfe"); + QwpTableBuffer doubleS = sender.getTableBuffer("STRASSE"); + + Assert.assertEquals("TRADES", upper.getTableName()); + assertSpellings(first, first, upper, lower); + assertSpellings(other, other); + assertSpellings(umlaut, umlaut, umlautUpper, umlautLower); + assertSpellings(dotless, dotless, dotted); + assertSpellings(kelvinSign, kelvinSign, kelvin); + assertSpellings(deseretUpper, deseretUpper); + assertSpellings(deseretLower, deseretLower); + assertSpellings(sharpS, sharpS); + assertSpellings(doubleS, doubleS); + } + }); + } + @Test public void testNullArgsAfterCloseAllThrowSenderClosed() throws Exception { // Several column setters short-circuit (return this or throw "cannot @@ -1057,6 +1100,20 @@ private QwpWebSocketSender createUnconnectedSender() { return QwpWebSocketSender.createForTesting("localhost", 9000); } + // Checks that the chain from firstSpelling lists exactly the expected buffers, in + // any order, each naming firstSpelling as its table's first spelling. + private static void assertSpellings(QwpTableBuffer firstSpelling, QwpTableBuffer... expected) { + List spellings = new ArrayList<>(); + for (QwpTableBuffer spelling = firstSpelling; spelling != null; spelling = spelling.getNextSpelling()) { + Assert.assertSame(firstSpelling, spelling.getFirstSpelling()); + spellings.add(spelling); + } + Assert.assertEquals(expected.length, spellings.size()); + for (QwpTableBuffer spelling : expected) { + Assert.assertTrue(spelling.getTableName(), spellings.contains(spelling)); + } + } + /** * Records every QWP frame the server receives, in arrival order, and acks each * binary message up to the last frame it carried. From db7d1c565d184d0e1d445008c99a011e989f25b7 Mon Sep 17 00:00:00 2001 From: Vlad Ilyushchenko Date: Thu, 26 Nov 2026 13:54:29 +0000 Subject: [PATCH 12/20] Track a partly sent split frame by frame A flush that splits its batch at the server's frame cap sends one frame per table. When a frame after the first failed to reach the ring -- the store-and-forward buffer full during an outage, or a frame that fits the cap but not a segment -- the tables before it were already on the ring, yet the sender still counted them as unsent and the transaction as having sent nothing, because it updated both after the last frame: - rollback(), reset() and returning a strict pooled lease published no rollback frame, so once the server was back, the next commit committed the rows the caller had discarded. - A retried flush() sent those tables again, so they committed twice. - drain() after the discard waited out its timeout for an ack the server withholds until a commit. sealAndSwapBuffer(), the one place frames reach the ring, now sets hasDeferredMessages from the flags of every frame it appends. That replaces the six assignments its callers made after their own frames, which a run of frames failing partway left behind the ring. The split moves each table out of the batch, and into the open transaction's row counts when its frame is deferred, as soon as the frame is on the ring; after a failure, keepUnsentTables() recounts the batch from the tables left. Every row is then either on the ring, where rollback() discards it and the next commit commits it once, or in the batch, which the next flush sends. In transactional mode a flush that fails after it published dictionary chunks no longer commits them: they join the caller's open transaction, and committing them committed that transaction behind its back, the rows of its earlier frames included. Outside transactional mode they still commit, as before. Outside transactional mode reset() keeps the frames already sent, and the next commit commits them. That now holds for the part of a failed split too, so close() and a flush() with no rows commit it as well. QwpLargeTransactionTest covers rollback(), reset() and a pooled lease's return after a split fails partway, in transaction=on and strict, during an outage and on a frame too large for a segment, a retry in every mode, and a split that fails on its first frame. SelfSufficientFramesTest covers a dictionary chunk or data frame that fails, in strict mode and outside transactional mode. --- .../main/java/io/questdb/client/Sender.java | 8 +- .../qwp/client/QwpWebSocketSender.java | 288 +++++++++------ .../qwp/client/QwpLargeTransactionTest.java | 340 ++++++++++++++++++ .../qwp/client/SelfSufficientFramesTest.java | 160 +++++++++ 4 files changed, 687 insertions(+), 109 deletions(-) diff --git a/core/src/main/java/io/questdb/client/Sender.java b/core/src/main/java/io/questdb/client/Sender.java index 90448c6d8..860cff1c0 100644 --- a/core/src/main/java/io/questdb/client/Sender.java +++ b/core/src/main/java/io/questdb/client/Sender.java @@ -774,8 +774,8 @@ default void resetSymbolDictionary() { * After calling this method, you can start building a new row by calling {@link #table(CharSequence)}. *
    * In WebSocket transactional mode ({@code transaction=on} or {@code strict}) it also - * discards the rows of the open transaction that auto-flush already sent, as - * {@link #rollback()} does. The exception is a {@code transaction=on} sender that last + * discards the rows of the open transaction already sent, by auto-flush or by a + * {@link #flush()} that failed partway, as {@link #rollback()} does. The exception is a {@code transaction=on} sender that last * connected to a server without QWP rollback support: it keeps those rows, and the next * flush commits them, as before rollback existed. *
    @@ -788,8 +788,8 @@ default void resetSymbolDictionary() { /** * Discard the open transaction: the rows buffered since the last flush and, in * WebSocket transactional mode ({@code transaction=on} or {@code strict}), the - * rows of the transaction that auto-flush already sent to the server, which - * the server discards on request. + * rows of the transaction already sent to the server, by auto-flush or by a + * {@link #flush()} that failed partway, which the server discards on request. *
    * Like {@link #flush()}, this returns without waiting for the server, so a * server outage makes it fail only when the store-and-forward buffer is full, diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java index 8eca6c0eb..0d8b9cfc2 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java @@ -433,6 +433,12 @@ public class QwpWebSocketSender implements Sender { // polls through getAckedFsn), so the recycle's engine=null -> base roll -> // engine=fresh write order can never pair the old engine with the new base. private volatile long fsnEpochBase = 0; + // True while the ring holds an open FLAG_DEFER_COMMIT group: the last frame + // published carried the flag, and no commit or rollback frame has closed the group + // since. sealAndSwapBuffer() sets it from the flags of every frame it appends, the + // one place frames reach the ring, so a run of frames that fails partway, such as a + // split flush or dictionary chunks, leaves it exactly as far as the ring got. + // Producer thread only. private boolean hasDeferredMessages; // Latched true the first time ensureConnected() completes. Once set, // every later ensureConnected() -- today only the recycle's step 7 and @@ -1897,7 +1903,6 @@ private void close0(boolean[] restoreInterrupt) { if (hasDeferredMessages && serverRollbackEnabled) { try { publishRollbackFrame(); - hasDeferredMessages = false; lastCommitBoundaryFsn = cursorEngine.publishedFsn(); clearTransactionState(); } catch (Throwable t) { @@ -3564,7 +3569,6 @@ private void publishRollbackFrame() { private void rollbackOpenTransaction(String action) { long committedRows = txnRowsCommittedInParts; publishRollbackFrame(); - hasDeferredMessages = false; // The rollback frame gets an OK ack covering the transaction's frames, or the // I/O loop acknowledges it when it discards the transaction itself, so // close-time drains may wait for it like for a commit. @@ -5078,9 +5082,13 @@ private int collectNonEmptyTables() { * themselves: they carry no rows, and re-registering the same ids with the same * strings is not a redefinition. When the failure came from the SPLIT path the * group may also contain some of the batch's table frames, so the commit can apply - * a partial batch -- accepted deliberately, because the retained batch's retry - * re-sends every table and dedup collapses the overlap, whereas leaving the group - * open kills ingestion outright. + * a partial batch -- accepted deliberately, because the split took those tables + * out of the retained batch, so its retry sends only the others and every row + * still lands once, whereas leaving the group open kills ingestion outright. + *

    + * Never in transactional mode: there the group belongs to the caller's open + * transaction, whose flush() commits it and whose rollback() or reset() discards + * it, so committing it here would commit the transaction behind the caller's back. *

    * Best-effort: the commit publishes through the same seal path that just failed, so * it can fail too. Its failure is attached to the original as a suppressed cause @@ -5618,7 +5626,9 @@ private void flushPendingRows(boolean deferCommit, boolean isAutoFlush) { // backpressure deadline (the ring at sf_max_total_bytes), and neither is // reachable from a size check. Once a chunk is on the ring the flush owns a // commit debt that only its own data frame closes, so track that and close it - // on any failure below. + // on any failure below -- outside transactional mode only: there the group is + // the caller's open transaction, which its flush() commits and its rollback() + // or reset() discards. boolean dictionaryChunksAwaitCommit = false; if (cap > 0 && messageSize > cap && !deltaDictEnabled && currentBatchMaxSymbolId > deltaBaseline @@ -5653,7 +5663,6 @@ && splitFramesFit(cap, currentBatchMaxSymbolId)) { // advance the delta baseline so the next frame ships only newer ids. advanceSentMaxSymbolId(); - hasDeferredMessages = deferCommit; if (!deferCommit) { lastCommitBoundaryFsn = cursorEngine.publishedFsn(); } @@ -5661,7 +5670,7 @@ && splitFramesFit(cap, currentBatchMaxSymbolId)) { resetTableBuffersAfterFlush(); } catch (Throwable t) { - if (dictionaryChunksAwaitCommit) { + if (dictionaryChunksAwaitCommit && !transactional) { commitOrphanedDictionaryChunks(t); } throw t; @@ -5727,21 +5736,25 @@ private boolean splitFramesFit(int cap, int baseline) { * so the server appends rows without committing until the final * message arrives. *

    - * Not atomic across frames. The frames publish one at a time, so a - * publish failure partway through -- {@link #sealAndSwapBuffer()} throwing on - * frame k>1, e.g. a backpressure deadline or the buffer-recycle timeout -- - * leaves frames 1..k-1 already on the ring as deferred (appended, not yet - * committed). The throw propagates past the {@code resetTableBuffersAfterFlush} - * at the end of the loop, so the source rows survive in their table buffers - * and the NEXT flush re-emits the whole batch; the eventual commit then - * commits the already-published prefix alongside the re-sent copies, - * delivering those rows at-least-once (duplicated), not exactly-once. This is - * within store-and-forward's at-least-once contract -- a DEDUP table or a - * durable-ack await absorbs the duplicate, and the symbol-dict state stays - * consistent on the retry (the re-sent frames carry empty deltas and the - * write-ahead persist is a {@code pd.size()} no-op). Making the split atomic - * (rolling back the published prefix, or skipping it on retry) would be a - * larger change. + * The frames reach the ring one at a time, so a publish can fail partway: + * {@link #sealAndSwapBuffer()} can throw on frame k>1, for example at a + * backpressure deadline or for a frame that fits the cap but not a + * store-and-forward segment. So each + * frame that reaches the ring moves its table out of the batch at once and, when + * deferred, into the open transaction, and a failure leaves every row in exactly + * one place: + *

    + * The next flush sends only tables k..n, and its last frame commits the group, + * so every row commits once. rollback() and reset() find the group open and + * publish the rollback frame, which discards tables 1..k-1, and they discard + * tables k..n with the batch. The symbol dictionary stays consistent on either + * path: the first frame carried the batch's new symbols and advanced the + * baseline, so the next flush sends an empty delta and the write-ahead persist + * is a {@code pd.size()} no-op. * * @param deferCommit when true, ALL messages (including the last) * carry FLAG_DEFER_COMMIT. When false, only the @@ -5832,63 +5845,109 @@ private void flushPendingRowsSplit( // pre-registration, which advances the baseline without touching // sentMaxSymbolId (full-dict mode never advances it). int frameBaseline = deltaBaseline; - for (int i = 0; i < nonEmptyCount; i++) { - CharSequence tableName = flushTableNames.getQuick(i); - - boolean isLast = (i == nonEmptyCount - 1); - boolean deferThis = deferCommit || !isLast; - - int tableBodyLength = splitFrameBodyBytes.getQuick(i); - // Persist before touching activeBuffer. If the write-ahead fails, the - // caller can retry with both the source rows and active microbatch - // unchanged. The first frame carries the batch's new symbols; later - // frames are no-ops once the baseline has advanced. - persistNewSymbolsBeforePublish(); - ensureActiveBufferReady(); - // The combined encoder buffer remains immutable for the whole split. - // Assemble this frame directly into the active microbatch: patched - // header + staged delta bytes + the staged table-body slice. No row or - // column is encoded a second time. - int messageSize = encoder.copySplitMessage( - activeBuffer, - tableBodyOffset, - tableBodyLength, - deferThis, - frameBaseline, - currentBatchMaxSymbolId - ); - tableBodyOffset += tableBodyLength; - // The pre-flight pass above already verified every split frame fits the - // cap, so none can be found oversized here -- which is what keeps this - // loop from publishing (and stranding) a deferred prefix before an - // oversized table. Both passes size against the SAME snapshot cap, so a - // mid-flush failover cannot make them disagree; the assert therefore only - // catches a genuine divergence between the pre-flight arithmetic and the - // staged assembler (a future bug), not a cap race. It deliberately does NOT - // reset+throw here, because by this point a prefix may already be on the ring. - assert messageSize <= cap - : "split frame exceeded serverMaxBatchSize after pre-flight [table=" + tableName - + ", messageSize=" + messageSize + ", serverMaxBatchSize=" + cap + ']'; - - activeBuffer.incrementRowCount(); - sealAndSwapBuffer(); - // Frame queued: advance so the next split frame's delta starts above - // the ids this one just registered. - advanceSentMaxSymbolId(); - if (deltaDictEnabled && currentBatchMaxSymbolId > frameBaseline) { - frameBaseline = currentBatchMaxSymbolId; + // Tables whose frames reached the ring. + int sentTables = 0; + try { + for (int i = 0; i < nonEmptyCount; i++) { + CharSequence tableName = flushTableNames.getQuick(i); + + boolean isLast = (i == nonEmptyCount - 1); + boolean deferThis = deferCommit || !isLast; + + int tableBodyLength = splitFrameBodyBytes.getQuick(i); + // Persist before touching activeBuffer. If the write-ahead fails, the + // caller can retry with both the source rows and active microbatch + // unchanged. The first frame carries the batch's new symbols; later + // frames are no-ops once the baseline has advanced. + persistNewSymbolsBeforePublish(); + ensureActiveBufferReady(); + // The combined encoder buffer remains immutable for the whole split. + // Assemble this frame directly into the active microbatch: patched + // header + staged delta bytes + the staged table-body slice. No row or + // column is encoded a second time. + int messageSize = encoder.copySplitMessage( + activeBuffer, + tableBodyOffset, + tableBodyLength, + deferThis, + frameBaseline, + currentBatchMaxSymbolId + ); + tableBodyOffset += tableBodyLength; + // The pre-flight pass above already verified every split frame fits the + // cap, so none can be found oversized here -- which is what keeps this + // loop from publishing (and stranding) a deferred prefix before an + // oversized table. Both passes size against the SAME snapshot cap, so a + // mid-flush failover cannot make them disagree; the assert therefore only + // catches a genuine divergence between the pre-flight arithmetic and the + // staged assembler (a future bug), not a cap race. It deliberately does NOT + // reset+throw here, because by this point a prefix may already be on the ring. + assert messageSize <= cap + : "split frame exceeded serverMaxBatchSize after pre-flight [table=" + tableName + + ", messageSize=" + messageSize + ", serverMaxBatchSize=" + cap + ']'; + + activeBuffer.incrementRowCount(); + sealAndSwapBuffer(); + // The frame is on the ring, and sealAndSwapBuffer() recorded the group it + // opened or closed. Its rows leave the batch now rather than after the + // loop, so if a later frame fails to publish, the next flush does not send + // them again and rollback() still discards them. The frame body was copied + // from the encoder, so the table buffer is free to reset. + QwpTableBuffer table = flushTableBuffers.getQuick(i); + if (deferThis) { + accountTransactionTable(table); + } + table.reset(); + sentTables++; + // Frame queued: advance so the next split frame's delta starts above + // the ids this one just registered. + advanceSentMaxSymbolId(); + if (deltaDictEnabled && currentBatchMaxSymbolId > frameBaseline) { + frameBaseline = currentBatchMaxSymbolId; + } } + } catch (Throwable t) { + if (sentTables > 0) { + keepUnsentTables(sentTables); + } + throw t; } encoder.setDeferCommit(false); - hasDeferredMessages = deferCommit; if (!deferCommit) { // The last message of the split carried no defer flag -- it // committed the whole group. lastCommitBoundaryFsn = cursorEngine.publishedFsn(); + clearTransactionState(); + } + // The loop emptied every table already. + clearFlushedBatch(); + } + + /** + * After a split that failed once the frames of its first {@code sentTables} + * tables reached the ring, which also emptied those tables: makes the batch's + * counters cover only the tables still in it. A split publishes no frame before + * the first table's, so the batch's new symbols left with that frame. The byte + * count, which only the byte trigger reads, is the unsent tables' buffered bytes: + * a few bytes above the running count for a table that keeps empty column state + * from an earlier flush, which can only make the trigger fire marginally early. + */ + private void keepUnsentTables(int sentTables) { + int rows = 0; + long bytes = 0; + for (int i = sentTables, n = flushTableBuffers.size(); i < n; i++) { + QwpTableBuffer table = flushTableBuffers.getQuick(i); + rows += table.getRowCount(); + bytes += table.getBufferedBytes(); } - accountTransactionRows(deferCommit); - resetTableBuffersAfterFlush(); + pendingRowCount = rows; + pendingBytes = bytes; + pendingSymbolDictBytes = 0; + // A row of the batch selected a table, and no row is in progress during a flush: + // the snapshot is the current table's bytes, 0 when the split emptied it. + assert currentTableBuffer != null; + currentTableBufferSnapshotBytes = currentTableBuffer.getBufferedBytes(); } /** @@ -5922,6 +5981,13 @@ private void resetTableBuffersAfterFlush() { for (int i = 0, n = flushTableBuffers.size(); i < n; i++) { flushTableBuffers.getQuick(i).reset(); } + clearFlushedBatch(); + } + + /** + * Ends the batch a flush published, once its tables are empty. + */ + private void clearFlushedBatch() { // The next row lists its table again. clearPendingTables(); // The next flush re-collects. setPos(0) rather than clear(), which fills the @@ -6836,7 +6902,6 @@ private void sendCommitMessage() { activeBuffer.write(buffer.getBufferPtr(), messageSize); activeBuffer.incrementRowCount(); sealAndSwapBuffer(); - hasDeferredMessages = false; lastCommitBoundaryFsn = cursorEngine.publishedFsn(); clearTransactionState(); } @@ -7142,9 +7207,11 @@ private void publishDictionaryChunks(int cap, int from, int batchMaxId) { // Pass two publishes. Every chunk is a DEFERRED frame, so from the first // successful publish onward this method owns a commit debt: if a later chunk // throws (sealAndSwapBuffer's buffer-recycle timeout, or appendBlocking's - // backpressure deadline when the ring is at sf_max_total_bytes), the chunks - // already on the ring have no rollback and nothing downstream will close their - // group. Close it in the catch instead -- see commitOrphanedDictionaryChunks. + // backpressure deadline when the ring is at sf_max_total_bytes), nothing + // downstream closes the group of the chunks already on the ring. Close it in + // the catch instead -- see commitOrphanedDictionaryChunks -- outside + // transactional mode: there the chunks belong to the caller's open + // transaction, which the caller commits or rolls back. for (int id = from; id <= batchMaxId; id++) { int entryBytes = dictionaryEntryWireBytes(id); // Size the frame this entry WOULD produce, with the count varint the @@ -7180,7 +7247,7 @@ private void publishDictionaryChunks(int cap, int from, int batchMaxId) { // watermark as a baseline and never reclaims -- leave it alone. sentMaxSymbolId = Math.min(sentMaxSymbolId, chunkStart - 1); } - if (anyChunkPublished) { + if (anyChunkPublished && !transactional) { commitOrphanedDictionaryChunks(t); } throw t; @@ -7220,17 +7287,12 @@ private void publishDictionaryChunk(int startId, int endId) { activeBuffer.ensureCapacity(messageSize); activeBuffer.write(buffer.getBufferPtr(), messageSize); activeBuffer.incrementRowCount(); - sealAndSwapBuffer(); - // The chunk is on the ring carrying FLAG_DEFER_COMMIT, so the server withholds + // The chunk reaches the ring carrying FLAG_DEFER_COMMIT, so the server withholds // its ack and clamps the connection's cumulative-ack watermark until the group - // commits. Record that debt here rather than leaving it to the caller: when the - // batch meant to close the group throws instead -- an oversized table body - // reaching the split pre-flight -- flushPendingRows never reaches its own - // hasDeferredMessages assignment, close() skips sendCommitMessage, and the group - // never commits. ackedFsn then freezes for the connection's whole life, so trim - // stops for every frame and the ring fills. A later successful flush reassigns - // this from its own deferCommit, which is correct: its data frame closes the group. - hasDeferredMessages = true; + // commits. sealAndSwapBuffer() records the open group, so when the batch meant + // to close it throws instead, close() and the next flush still commit it, and + // ackedFsn does not freeze for the connection's whole life. + sealAndSwapBuffer(); } /** @@ -7488,16 +7550,23 @@ private void sealAndSwapBuffer() { // (durable mmap append, returns once published). try { toSend.markSending(); + long payloadAddr = toSend.getBufferPtr(); + int payloadLen = toSend.getBufferPos(); + boolean isDeferredFrame = isDeferredGroupFrame(payloadAddr, payloadLen); // Transactional mode tracks how the open transaction's frames pack // into segments; the first frame's placement depends on the active // segment's room before the append. - boolean isTxnFrame = transactional - && isTransactionFrame(toSend.getBufferPtr(), toSend.getBufferPos()); + boolean isTxnFrame = transactional && isDeferredFrame; long activeRemaining = isTxnFrame && txnSimSegments == 0 ? cursorEngine.activeSegment().capacityRemaining() : 0; - cursorEngine.appendBlocking(toSend.getBufferPtr(), toSend.getBufferPos()); + cursorEngine.appendBlocking(payloadAddr, payloadLen); + // The frame is on the ring: a deferred frame opens or extends the group, and + // a commit or rollback frame closes it. Every frame passes here, so the group + // follows the ring even when a run of frames fails partway, and rollback(), + // reset() and close() see every deferred frame that went out. + hasDeferredMessages = isDeferredFrame; if (isTxnFrame) { - recordTransactionFrame(toSend.getBufferPos(), activeRemaining); + recordTransactionFrame(payloadLen, activeRemaining); } toSend.markRecycled(); } catch (Throwable t) { @@ -7505,8 +7574,8 @@ private void sealAndSwapBuffer() { // payload never reached the engine, so no I/O thread will // recycle toSend. Recycle it here so a later flush can swap // back to it; flushPendingRows aborts its post-enqueue state - // updates after this throw, so the source rows stay intact and the - // next batch re-emits the same rows along with the full inline + // updates after this throw, so the rows of this frame stay intact + // and the next batch re-emits them along with the full inline // schema and the symbol-dict delta the batch requires. if (toSend.isSending()) { toSend.markRecycled(); @@ -7534,15 +7603,23 @@ private void accountTransactionRows(boolean deferred) { return; } for (int i = 0, n = flushTableBuffers.size(); i < n; i++) { - QwpTableBuffer table = flushTableBuffers.getQuick(i); - long sentRows = table.getTxnSentRows(); - if (sentRows == 0) { - txnTables.add(table); - } - table.setTxnSentRows(sentRows + table.getRowCount()); + accountTransactionTable(flushTableBuffers.getQuick(i)); } } + /** + * Adds the rows of {@code table} that a just-published FLAG_DEFER_COMMIT frame + * shipped to the table's open-transaction count. Call before the table's buffer + * resets. + */ + private void accountTransactionTable(QwpTableBuffer table) { + long sentRows = table.getTxnSentRows(); + if (sentRows == 0) { + txnTables.add(table); + } + table.setTxnSentRows(sentRows + table.getRowCount()); + } + private void checkTransactionAcceptsRow() { if (!strictTransactional) { return; @@ -7740,14 +7817,15 @@ && splitFramesFit(cap, currentBatchMaxSymbolId)) { } /** - * True for a QWP frame that joins the open transaction: FLAG_DEFER_COMMIT - * set, and not the rollback control frame (which also carries the flag). + * True for a frame that joins the open deferred group, and so the open + * transaction: FLAG_DEFER_COMMIT set, and not the rollback control frame (which + * also carries the flag). Every frame the producer publishes comes from the + * encoder, so it starts with a QWP header. */ - private static boolean isTransactionFrame(long payloadAddr, int payloadLen) { - if (payloadLen < QwpConstants.HEADER_SIZE - || Unsafe.getUnsafe().getInt(payloadAddr) != QwpConstants.MAGIC_MESSAGE) { - return false; - } + private static boolean isDeferredGroupFrame(long payloadAddr, int payloadLen) { + assert payloadLen >= QwpConstants.HEADER_SIZE + && Unsafe.getUnsafe().getInt(payloadAddr) == QwpConstants.MAGIC_MESSAGE + : "not a QWP frame [payloadLen=" + payloadLen + ']'; byte flags = Unsafe.getUnsafe().getByte(payloadAddr + QwpConstants.HEADER_OFFSET_FLAGS); return (flags & QwpConstants.FLAG_DEFER_COMMIT) != 0 && (flags & QwpConstants.FLAG_ROLLBACK) == 0; } diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index 406b404c4..61a8c9e14 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -73,6 +73,23 @@ */ public class QwpLargeTransactionTest { private static final int CAP = 32 * 1024; + // Row trigger past the batches here: only flush() sends them. + private static final int NO_ROW_TRIGGER = 100_000; + // OUTAGE_SPLIT_RING's fillers of ~39 KB fit this cap; a split of ~68 KB does not. + private static final int OUTAGE_SPLIT_CAP = 48 * 1024; + // Committed fillers of ~39 KB take a 64 KiB segment each and leave ~26 KB of it free, + // and 256 KiB hold a few of them. A refused append fails after 500 ms. + private static final String OUTAGE_SPLIT_RING = "auto_flush_bytes=off;auto_flush_rows=100000;" + + "auto_flush_interval=off;sf_max_segment_bytes=64k;sf_max_total_bytes=256k;" + + "sf_append_deadline_millis=500;"; + // Twice the 64 KiB segments of SPLIT_PAST_SEGMENT: a split frame can fit the cap but + // not a segment. + private static final int SPLIT_CAP = 128 * 1024; + // No byte trigger, so a batch grows past SPLIT_CAP and flush() splits it per table. + private static final String SPLIT_PAST_SEGMENT = "auto_flush_bytes=off;auto_flush_interval=off;" + + "sf_max_segment_bytes=64k;"; + // Rows sendPartOfSplit writes. + private static final int SPLIT_ROWS = 1_400; // The settings a refusal at the client buffer names. private static final String CLIENT_BUFFER_REMEDY = "Raise sf_max_total_bytes, or set sf_dir to keep the " + "transaction on disk"; @@ -2158,6 +2175,167 @@ public void testTransactionalDefaultTriggersSplitWideRows() throws Exception { }); } + @Test + public void testPartlySentAutoFlushSplitRollbackDiscardsSentTables() throws Exception { + // The row trigger fires on the batch's last row, so auto-flush sends the split, and + // the frame that reached the ring holds rows auto-flush sent. + assertPartlySentSplitDiscarded("transaction=on;", SPLIT_ROWS, Sender::rollback); + } + + @Test + public void testPartlySentSplitDuringOutageResetDiscardsSentTables() throws Exception { + assertPartlySentSplitDuringOutageDiscarded("transaction=on;", Sender::reset); + } + + @Test + public void testPartlySentSplitDuringOutageRollbackDiscardsSentTables() throws Exception { + // The server is down and the client buffer full, so the split sends its first + // table's frame into the room left in the last segment and fails on the second. + // rollback() used to find no open transaction and publish nothing, so once the + // server was back, the next transaction's commit committed the first table. + assertPartlySentSplitDuringOutageDiscarded("transaction=on;", Sender::rollback); + } + + @Test + public void testPartlySentSplitResetDiscardsSentTables() throws Exception { + assertPartlySentSplitDiscarded("transaction=on;", NO_ROW_TRIGGER, Sender::reset); + } + + @Test + public void testPartlySentSplitRetryDuringOutageSendsEachTableOnce() throws Exception { + // flush() of a split that failed partway used to send the whole batch again, so + // the tables that had reached the ring committed twice. + assertRetryOfPartlySentSplitSendsEachTableOnce("transaction=on;"); + } + + @Test + public void testPartlySentSplitRollbackDiscardsSentTables() throws Exception { + assertPartlySentSplitDiscarded("transaction=on;", NO_ROW_TRIGGER, Sender::rollback); + } + + @Test + public void testPooledStrictLeaseReturnDiscardsPartlySentSplit() throws Exception { + // Returning the lease discards the strict transaction: the table the split sent + // must not commit with the next borrower's transaction. The warning counts the + // rows of the table that reached the ring and of the two still in the batch, once. + assertMemoryLeak(() -> { + ListAppender log = captureSenderLog(); + try { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, SPLIT_CAP)) { + server.setRollbackSupported(true); + try (QuestDB db = QuestDB.connect(conf(server) + "transaction=strict;sender_pool_max=1;" + + "query_pool_min=0;" + SPLIT_PAST_SEGMENT + "auto_flush_rows=" + NO_ROW_TRIGGER + ';')) { + Sender lease = db.borrowSender(); + sendPartOfSplit(lease, NO_ROW_TRIGGER); + lease.close(); + Assert.assertEquals(Collections.singletonList("returning the sender to the pool" + + DISCARD_WARNING.replace("of 1000 rows", "of " + SPLIT_ROWS + " rows")), + discardWarnings(log)); + Sender next = db.borrowSender(); + writeRows(next, "t", 0, 10); + next.flush(); + Assert.assertTrue(next.drain(5_000)); + next.close(); + } + assertSentTablesRolledBack(h); + } + } finally { + releaseSenderLog(log); + } + }); + } + + @Test + public void testResetKeepsPartlySentSplitOfNonTransactionalSender() throws Exception { + // Outside transactional mode reset() discards only the rows not yet sent, as it + // does for frames setDeferCommit(true) sent: the frame of the split that reached + // the ring stays in the deferred group, and the next commit commits it. The sender + // used to lose track of that frame, so a flush() with no rows sent no commit, and + // drain() waited for an ack the server withholds until one. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, SPLIT_CAP)) { + server.setRollbackSupported(true); + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(conf(server) + "transaction=off;" + + SPLIT_PAST_SEGMENT + "auto_flush_rows=" + NO_ROW_TRIGGER + ';')) { + sendPartOfSplit(s, NO_ROW_TRIGGER); + s.reset(); + Assert.assertTrue(s.hasDeferredMessagesForTesting()); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + Assert.assertFalse(s.hasDeferredMessagesForTesting()); + } + Assert.assertEquals("Dc", frameKinds(h)); + Assert.assertEquals(h.frames, h.committedFrames()); + } + }); + } + + @Test + public void testSplitThatFailsOnItsFirstFrameKeepsTheWholeBatch() throws Exception { + // Nothing of the split reached the ring, so nothing leaves the batch, and the + // transaction has no frame to roll back. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, SPLIT_CAP)) { + server.setRollbackSupported(true); + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(conf(server) + "transaction=on;" + + SPLIT_PAST_SEGMENT + "auto_flush_rows=" + NO_ROW_TRIGGER + ';')) { + // b, ~80 KB, goes first now: the first frame fits the cap but no segment. + writeRows(s, "b", 0, 800); + writeRows(s, "a", 0, 300); + writeRows(s, "c", 0, 300); + long batchBytes = s.getPendingBytes(); + try { + s.flush(); + Assert.fail("the split's first frame cannot fit a segment"); + } catch (LineSenderException e) { + TestUtils.assertContains(e.getCause().getMessage(), "payload too large for segment"); + } + Assert.assertEquals(-1L, s.getCursorEngineForTesting().publishedFsn()); + Assert.assertFalse(s.hasDeferredMessagesForTesting()); + Assert.assertEquals(batchBytes, s.getPendingBytes()); + Assert.assertEquals(s.totalBufferedBytes(), s.getPendingBytes()); + Assert.assertEquals(800, s.getTableBuffer("b").getRowCount()); + Assert.assertEquals(300, s.getTableBuffer("a").getRowCount()); + Assert.assertEquals(300, s.getTableBuffer("c").getRowCount()); + s.rollback(); + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + Assert.assertEquals("C", frameKinds(h)); + Assert.assertEquals(h.frames, h.committedFrames()); + } + }); + } + + @Test + public void testStrictPartlySentSplitDuringOutageRollbackDiscardsSentTables() throws Exception { + assertPartlySentSplitDuringOutageDiscarded("transaction=strict;", Sender::rollback); + } + + @Test + public void testStrictPartlySentSplitResetDiscardsSentTables() throws Exception { + assertPartlySentSplitDiscarded("transaction=strict;", NO_ROW_TRIGGER, Sender::reset); + } + + @Test + public void testStrictPartlySentSplitRetryDuringOutageSendsEachTableOnce() throws Exception { + assertRetryOfPartlySentSplitSendsEachTableOnce("transaction=strict;"); + } + + @Test + public void testStrictPartlySentSplitRollbackDiscardsSentTables() throws Exception { + assertPartlySentSplitDiscarded("transaction=strict;", NO_ROW_TRIGGER, Sender::rollback); + } + + @Test + public void testTransactionOffPartlySentSplitRetryDuringOutageSendsEachTableOnce() throws Exception { + assertRetryOfPartlySentSplitSendsEachTableOnce("transaction=off;"); + } + // Captures what QwpWebSocketSender logs, so a test can assert its warnings. private static ListAppender captureSenderLog() { ListAppender appender = new ListAppender<>(); @@ -2570,6 +2748,168 @@ private static void writeRows(Sender s, String table, int from, int count) { } } + // A split of three tables past SPLIT_CAP whose first frame reaches the ring and + // whose second, ~80 KB, fits the cap but not a 64 KiB segment. A discard follows, + // then the next transaction commits: only that one may land. + private static void assertPartlySentSplitDiscarded(String mode, int autoFlushRows, Consumer discard) throws Exception { + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, SPLIT_CAP)) { + server.setRollbackSupported(true); + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(conf(server) + mode + + SPLIT_PAST_SEGMENT + "auto_flush_rows=" + autoFlushRows + ';')) { + sendPartOfSplit(s, autoFlushRows); + // a reached the ring and left the batch, which keeps b and c, and the + // batch's byte count, which the byte trigger reads, covers only them. + Assert.assertTrue(s.hasDeferredMessagesForTesting()); + Assert.assertEquals(0, s.getTableBuffer("a").getRowCount()); + Assert.assertEquals(800, s.getTableBuffer("b").getRowCount()); + Assert.assertEquals(300, s.getTableBuffer("c").getRowCount()); + Assert.assertEquals(s.getTableBuffer("b").getBufferedBytes() + s.getTableBuffer("c").getBufferedBytes(), + s.getPendingBytes()); + discard.accept(s); + Assert.assertFalse(s.hasDeferredMessagesForTesting()); + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + assertSentTablesRolledBack(h); + } + }); + } + + // The server goes down, committed fillers fill the client buffer, and a split sends + // its first table's frame into the room left in the last segment and fails on the + // second. A discard follows, then the server comes back and the next transaction + // commits: only the fillers and that transaction may land. + private static void assertPartlySentSplitDuringOutageDiscarded(String mode, Consumer discard) throws Exception { + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + TxnServer before = new TxnServer(); + TxnServer after = new TxnServer(); + TestWebSocketServer revived = null; + int fillers; + try (TestWebSocketServer first = start(before, OUTAGE_SPLIT_CAP, port, true)) { + try (Sender s = Sender.fromConfig(outageConf(port) + mode + OUTAGE_SPLIT_RING)) { + first.close(); + fillers = fillRingDuringOutage(s); + sendPartOfSplitDuringOutage(s); + // Must not wait for the server: the rollback frame fits the room the + // first table's frame left in the last segment. + discard.accept(s); + revived = start(after, OUTAGE_SPLIT_CAP, port, true); + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(s.drain(10_000)); + } + } finally { + if (revived != null) { + revived.close(); + } + } + Assert.assertEquals(0, before.frames.size()); + Assert.assertEquals(after.frames.toString(), TestUtils.repeat("C", fillers) + "DRC", frameKinds(after)); + Assert.assertEquals(1, after.rolledBackGroups); + List committed = new ArrayList<>(after.frames.subList(0, fillers)); + committed.add(after.frames.get(after.frames.size() - 1)); + Assert.assertEquals(committed, after.committedFrames()); + }); + } + + // As assertPartlySentSplitDuringOutageDiscarded, but the caller retries flush() once + // the server is back: the retry sends only the tables that had not reached the ring, + // and every frame commits once. + private static void assertRetryOfPartlySentSplitSendsEachTableOnce(String mode) throws Exception { + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + TxnServer before = new TxnServer(); + TxnServer after = new TxnServer(); + TestWebSocketServer revived = null; + int fillers; + try (TestWebSocketServer first = start(before, OUTAGE_SPLIT_CAP, port, true)) { + try (Sender s = Sender.fromConfig(outageConf(port) + mode + OUTAGE_SPLIT_RING)) { + first.close(); + fillers = fillRingDuringOutage(s); + sendPartOfSplitDuringOutage(s); + revived = start(after, OUTAGE_SPLIT_CAP, port, true); + // The ring replays to the server, whose acks of the fillers make room. + Assert.assertTrue(after.awaitFrames(fillers + 1)); + s.flush(); + Assert.assertTrue(s.drain(10_000)); + } + } finally { + if (revived != null) { + revived.close(); + } + } + Assert.assertEquals(0, before.frames.size()); + // The fillers, the first table's frame replayed, then the other two tables. + Assert.assertEquals(after.frames.toString(), TestUtils.repeat("C", fillers) + "DDC", frameKinds(after)); + Assert.assertEquals(after.frames, after.committedFrames()); + }); + } + + // The server received the first table's frame of the split, the rollback frame that + // discarded it, and the next transaction's commit, which alone committed. + private static void assertSentTablesRolledBack(TxnServer h) { + Assert.assertEquals(h.frames.toString(), "DRC", frameKinds(h)); + Assert.assertEquals(1, h.rolledBackGroups); + Assert.assertEquals(h.frames.subList(2, 3), h.committedFrames()); + } + + // With the server down, commits filler frames, one per segment, until the client + // buffer refuses one, discards that one, and returns how many reached the ring. The + // last segment keeps ~26 KB free. + private static int fillRingDuringOutage(Sender s) { + for (int frames = 0; frames < 100; frames++) { + writeRows(s, "filler", 0, 390); + try { + s.flush(); + } catch (LineSenderException e) { + TestUtils.assertContains(e.getMessage(), "cursor SF append failed"); + s.reset(); + Assert.assertTrue("the ring must take a filler", frames > 0); + return frames; + } + } + Assert.fail("the ring must fill"); + return -1; + } + + // Writes tables a (~30 KB), b (~80 KB) and c (~30 KB), SPLIT_ROWS rows past SPLIT_CAP. + // The split sends a, and b fits the cap but not a 64 KiB segment, so its append fails + // at once. A row trigger of SPLIT_ROWS sends the batch on its last row, as auto-flush; + // flush() sends it otherwise. + private static void sendPartOfSplit(Sender s, int autoFlushRows) { + Assert.assertTrue(autoFlushRows >= SPLIT_ROWS); + try { + writeRows(s, "a", 0, 300); + writeRows(s, "b", 0, 800); + writeRows(s, "c", 0, 300); + s.flush(); + Assert.fail("the split's second frame cannot fit a segment"); + } catch (LineSenderException e) { + TestUtils.assertContains(e.getMessage(), "cursor SF append failed"); + TestUtils.assertContains(e.getCause().getMessage(), "payload too large for segment"); + } + } + + // Writes tables a (~19 KB), b (~39 KB) and c (~10 KB), past OUTAGE_SPLIT_CAP, into a + // ring fillRingDuringOutage filled. The split sends a into the room left in the last + // segment, and b needs a segment the full ring cannot add. + private static void sendPartOfSplitDuringOutage(Sender s) { + writeRows(s, "a", 0, 190); + writeRows(s, "b", 0, 390); + writeRows(s, "c", 0, 100); + try { + s.flush(); + Assert.fail("the split's second frame cannot reach the full ring"); + } catch (LineSenderException e) { + TestUtils.assertContains(e.getMessage(), "cursor SF append failed"); + TestUtils.assertContains(e.getCause().getMessage(), "cursor ring backpressured"); + } + } + // ~28 KB in each of count tables, from table t: each fits a 32 KiB frame. private static void writeTables(Sender s, int first, int count) { for (int t = first, n = first + count; t < n; t++) { diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/SelfSufficientFramesTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/SelfSufficientFramesTest.java index 16f8a3bff..db48d3bdd 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/SelfSufficientFramesTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/SelfSufficientFramesTest.java @@ -1343,6 +1343,93 @@ public void testDictionaryChunksAreCommittedWhenTheDataFrameFailsToPublish() thr }); } + @Test + public void testDictionaryChunkThatFailsToPublishCommitsTheOrphanedChunksOutsideTransactions() throws Exception { + // Outside transactional mode nothing but this flush owns the deferred group, so + // a chunk that fails after an earlier one reached the ring commits that one. + assertDictionaryChunkFailsToPublish(false); + } + + @Test + public void testDictionaryChunkThatFailsToPublishLeavesTheOpenTransactionToTheCaller() throws Exception { + // In strict transactional mode a dictionary chunk that fails after an earlier one + // reached the ring must not commit: the earlier chunk joins the caller's open + // transaction, and only the caller ends it. Committing the orphaned chunk used to + // commit the transaction's earlier frame too, row included. + assertDictionaryChunkFailsToPublish(true); + } + + @Test + public void testDictionaryChunksStayInTheOpenTransactionWhenTheDataFrameFailsToPublish() throws Exception { + // The strict transactional twin of testDictionaryChunksAreCommittedWhenTheData- + // FrameFailsToPublish. There the chunks join the caller's open transaction, next to + // its earlier frames, and only the caller ends it: flush() commits it, rollback() + // or reset() discards it. Committing the orphaned chunks used to commit the whole + // open transaction behind the caller's back, the row of its earlier frame + // included, although a strict transaction never commits in parts. + Path sfDir = temporaryFolder.newFolder("qwp-sf-chunk-open-txn").toPath(); + String slot = sfDir.resolve("default").toString(); + assertMemoryLeak(() -> { + CapturingHandler handler = new CapturingHandler(); + try (TestWebSocketServer server = new TestWebSocketServer(handler)) { + server.setAdvertisedMaxBatchSize(150); + int port = server.getPort(); + server.start(); + Assert.assertTrue(server.awaitStart(5, TimeUnit.SECONDS)); + + UnopenableDictFacade dictFf = new UnopenableDictFacade(); + CursorSendEngine engine = new CursorSendEngine( + slot, 100L, 4L * 1024 * 1024, + CursorSendEngine.DEFAULT_APPEND_DEADLINE_NANOS, dictFf); + QwpWebSocketSender sender = (QwpWebSocketSender) QwpWebSocketSender.connect( + "localhost", port, null, 1_000_000, 0, 0L, null, DurableAckTiers.NONE, engine); + try { + sender.setStrictTransactional(true); + // A deferred frame with a row opens the transaction. + sender.setDeferCommit(true); + sender.table("u").longColumn("v", 1L).atNow(); + sender.flush(); + sender.setDeferCommit(false); + Assert.assertEquals("the transaction's first frame", 0L, engine.publishedFsn()); + + // As in the twin: the chunks publish, and the data frame does not fit + // the 100-byte segment. + String sym = TestUtils.repeat("s", 40); + String rowPad = TestUtils.repeat("x", 96); + sender.table("t").symbol("s", sym).stringColumn("p", rowPad).atNow(); + try { + sender.flush(); + Assert.fail("the data frame must fail to publish"); + } catch (LineSenderException expected) { + Assert.assertTrue(expected.getMessage(), + expected.getMessage().contains("cursor SF append failed")); + } + long published = engine.publishedFsn(); + Assert.assertTrue("the chunker must have published at least one chunk", published >= 1L); + Assert.assertTrue("the transaction stays open", sender.hasDeferredMessagesForTesting()); + + // Everything published reaches the server: the transaction's frame and + // the chunks, and no commit frame. + waitFor(() -> handler.batches.size() == published + 1, 5_000); + for (int i = 0; i < handler.batches.size(); i++) { + Assert.assertEquals("frame " + i + " must not commit the open transaction", + QwpConstants.FLAG_DEFER_COMMIT, + handler.batches.get(i)[QwpConstants.HEADER_OFFSET_FLAGS] + & QwpConstants.FLAG_DEFER_COMMIT); + } + Assert.assertEquals("the transaction's frame carries its row", + 1, QwpWireTestUtils.tableCount(handler.batches.get(0))); + } finally { + try { + sender.close(); + } catch (LineSenderException ignored) { + // Not what this test is about. + } + } + } + }); + } + @Test public void testFullDictCommitFrameCarriesNoDictionaryAfterACancelledRow() throws Exception { // sendCommitMessage bounded its delta with currentBatchMaxSymbolId in full-dict @@ -1505,6 +1592,79 @@ public int openCleanRW(String path) { } } + // A deferred frame with a row, then a batch whose four 40-byte symbols take two + // dictionary chunks of the 150-byte cap in full-dict mode. The second chunk fails + // before it reaches the ring. + private void assertDictionaryChunkFailsToPublish(boolean isTransactional) throws Exception { + Path sfDir = temporaryFolder.newFolder("qwp-sf-chunk-fault-" + isTransactional).toPath(); + String slot = sfDir.resolve("default").toString(); + assertMemoryLeak(() -> { + CapturingHandler handler = new CapturingHandler(); + try (TestWebSocketServer server = new TestWebSocketServer(handler)) { + server.setAdvertisedMaxBatchSize(150); + int port = server.getPort(); + server.start(); + Assert.assertTrue(server.awaitStart(5, TimeUnit.SECONDS)); + + UnopenableDictFacade dictFf = new UnopenableDictFacade(); + CursorSendEngine engine = new CursorSendEngine( + slot, 4096L, 4L * 1024 * 1024, + CursorSendEngine.DEFAULT_APPEND_DEADLINE_NANOS, dictFf); + QwpWebSocketSender sender = (QwpWebSocketSender) QwpWebSocketSender.connect( + "localhost", port, null, 1_000_000, 0, 0L, null, DurableAckTiers.NONE, engine); + try { + sender.setStrictTransactional(isTransactional); + sender.setDeferCommit(true); + sender.table("u").longColumn("v", 1L).atNow(); + sender.flush(); + sender.setDeferCommit(false); + + for (int i = 0; i < 4; i++) { + sender.table("t").symbol("s", TestUtils.repeat(String.valueOf(i), 40)).atNow(); + } + int[] chunkCalls = {0}; + sender.setChunkPublishFaultForTesting(() -> { + if (++chunkCalls[0] == 2) { + throw new LineSenderException("injected chunk publish failure"); + } + }); + try { + sender.flush(); + Assert.fail("the second chunk must fail to publish"); + } catch (LineSenderException expected) { + Assert.assertEquals("injected chunk publish failure", expected.getMessage()); + } finally { + sender.setChunkPublishFaultForTesting(null); + } + Assert.assertEquals(2, chunkCalls[0]); + // The deferred frame and the first chunk, and outside transactional + // mode the commit that closes their group. + long published = engine.publishedFsn(); + Assert.assertEquals(isTransactional ? 1L : 2L, published); + Assert.assertEquals(isTransactional, sender.hasDeferredMessagesForTesting()); + waitFor(() -> handler.batches.size() == published + 1, 5_000); + Assert.assertEquals("the deferred frame carries its row", + 1, QwpWireTestUtils.tableCount(handler.batches.get(0))); + Assert.assertEquals("a chunk carries no table", + 0, QwpWireTestUtils.tableCount(handler.batches.get(1))); + for (int i = 0; i <= published; i++) { + boolean isCommit = !isTransactional && i == published; + Assert.assertEquals("frame " + i, + isCommit ? 0 : QwpConstants.FLAG_DEFER_COMMIT, + handler.batches.get(i)[QwpConstants.HEADER_OFFSET_FLAGS] + & QwpConstants.FLAG_DEFER_COMMIT); + } + } finally { + try { + sender.close(); + } catch (LineSenderException ignored) { + // The retained batch can rethrow here; not what this test is about. + } + } + } + }); + } + private static void waitFor(BoolCondition cond, long timeoutMillis) { long deadline = System.currentTimeMillis() + timeoutMillis; while (System.currentTimeMillis() < deadline) { From 6648cbe7cde236779f7e73898dca28d237ca940d Mon Sep 17 00:00:00 2001 From: Vlad Ilyushchenko Date: Thu, 26 Nov 2026 20:45:23 +0000 Subject: [PATCH 13/20] Test the strict default cap and discard waits Two client behaviours of the large-transaction work had no test that fails when they break: - A strict transaction against a server that does not advertise X-QWP-Max-Uncommitted-Rows assumes the server default of 1,000,000. testStrictRowLimitDefaultsWhenNotAdvertised only showed that the default is above 10, so dropping the fallback cap passed every test. testStrictRowLimitIsServerDefaultWhenNotAdvertised writes 999,999 rows of one table to a mock that advertises nothing and expects the next row to be refused. It runs in about 0.1 s. - rollback(), reset() and returning a strict lease publish the rollback frame and return without waiting for the server. The ...DoesNotStall... tests never timed the call, so a 30 s wait for the rollback ack only made the run slower. assertDiscardDoesNotWait bounds each discard at 2 s against a server that is down, not reached yet, or never acks the frame. --- .../qwp/client/QwpLargeTransactionTest.java | 46 +++++++++++++++++-- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index 61a8c9e14..97fd035ed 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -525,7 +525,7 @@ public void testPooledStrictLeaseCloseDuringOutageKeepsTheConnection() throws Ex writeRows(lease, "t", 0, 1_000); Assert.assertTrue(before.awaitFrames(2)); first.close(); - lease.close(); + assertDiscardDoesNotWait(lease, Sender::close); Sender next = db.borrowSender(); writeRows(next, "t", 0, 10); next.flush(); @@ -1612,6 +1612,34 @@ public void testStrictRowLimitDefaultsWhenNotAdvertised() throws Exception { }); } + @Test + public void testStrictRowLimitIsServerDefaultWhenNotAdvertised() throws Exception { + // A server that does not advertise X-QWP-Max-Uncommitted-Rows commits a table on + // its own once its default qwp.max.uncommitted.rows of 1,000,000 rows are + // uncommitted, so a strict transaction holds at most 999,999 rows of a table. + // Rows of one LONG column keep the transaction small. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(conf(server) + "transaction=strict;")) { + Assert.assertEquals(0, s.getServerMaxUncommittedRows()); + for (int i = 0; i < 999_999; i++) { + s.table("a").longColumn("v", i).atNow(); + } + try { + s.table("a").longColumn("v", 999_999).atNow(); + Assert.fail("the 1,000,000th row of a table must be refused"); + } catch (TransactionTooLargeException e) { + Assert.assertEquals(serverRowLimitError("a", 1_000_000), e.getMessage()); + } + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + assertOneTransaction(h); + } + }); + } + @Test public void testStrictRowLimitCountsEverySpellingOfATable() throws Exception { // The server writes the rows of names that differ only in letter case to one @@ -2020,7 +2048,7 @@ public void testUnacknowledgedRollbackDoesNotStallTheSender() throws Exception { try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { writeRows(s, "t", 0, 1_000); Assert.assertTrue(h.awaitFrames(2)); - s.rollback(); + assertDiscardDoesNotWait(s, Sender::rollback); writeRows(s, "t", 0, 10); s.flush(); Assert.assertTrue(s.drain(5_000)); @@ -2457,7 +2485,7 @@ private static void assertDiscardBeforeFirstConnect(String mode, Consumer discard) { + long start = System.nanoTime(); + discard.accept(s); + long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); + Assert.assertTrue("the discard must not wait for the server [millis=" + millis + ']', millis < 2_000); + } + // Asserts what a server without rollback support received when the client discarded a // transaction whose frames had reached it: those frames, all deferred, on a connection // the client closed instead of sending the rollback frame, and on a second connection @@ -2607,7 +2645,7 @@ private static void assertDiscardDuringOutage(String mode, Consumer disc Assert.assertTrue(before.awaitFrames(2)); first.close(); // Must neither wait for the server nor fail: the server is away. - discard.accept(s); + assertDiscardDoesNotWait(s, discard); writeRows(s, "t", 0, 10); s.flush(); revived = start(after, CAP, port, true); From 54aac154a4874850e6360af089aa1c2f4ae503fd Mon Sep 17 00:00:00 2001 From: Vlad Ilyushchenko Date: Thu, 26 Nov 2026 21:08:18 +0000 Subject: [PATCH 14/20] Never let a late-learned cap split a strict txn A strict transaction checks each row against the server's qwp.max.uncommitted.rows, but the sender can learn that limit only after it accepted rows past it: before its first connection, where it assumes 1,000,000, or on a reconnect to a server that restarted with a lower setting, or to another endpoint. The server then committed the transaction's tables on its own at the limit, so the transaction landed in parts, and a rollback(), close() or pooled-lease return left most of it committed. Strict senders now mark every data frame with the new FLAG_STRICT (0x40). A server that knows it refuses such a frame with STATUS_TRANSACTION_TOO_LARGE (0x0F) instead of committing at the limit, and discards the connection's uncommitted rows; older servers ignore the bit. The I/O loop takes the refused transaction to start right after the last acked frame, sends none of its frames again, and walks them up to the frame that ends it: - a rollback frame: once every frame ahead is acked (durably in durable-ack mode), it acknowledges the transaction's frames itself and recycles the connection, as retireRollbackFrame() does; - a commit frame: the transaction can commit neither as one nor in parts, so the loop halts with a TRANSACTION_TOO_LARGE terminal and keeps the frames, which a sender recovering the slot commits once the limit is raised. The walk adds the skipped frames' symbols to the dictionary mirror, so the next connection's catch-up registers them for later transactions. The producer learns of the refusal through the loop: when the refused transaction is the open one, every row, flush() and drain() throws TransactionTooLargeException until rollback(), reset() or close() discards it. It also catches the case itself once a handshake lowers the limit: a row of a table already at the new limit fails the whole transaction, and flush() rechecks every table when the limit dropped since the rows were checked. SenderErrorTest pins the category count, which this adds one to. --- README.md | 4 +- .../main/java/io/questdb/client/Sender.java | 10 + .../java/io/questdb/client/SenderError.java | 10 + .../qwp/client/QwpWebSocketEncoder.java | 13 + .../qwp/client/QwpWebSocketSender.java | 150 +++- .../client/TransactionTooLargeException.java | 7 + .../cutlass/qwp/client/WebSocketResponse.java | 9 + .../sf/cursor/CursorWebSocketSendLoop.java | 239 +++++- .../cutlass/qwp/protocol/QwpConstants.java | 15 +- .../questdb/client/test/SenderErrorTest.java | 3 +- .../qwp/client/QwpLargeTransactionTest.java | 292 ++++++++ .../qwp/client/QwpWebSocketEncoderTest.java | 49 ++ .../qwp/client/WebSocketResponseTest.java | 23 + ...SocketSendLoopErrorClassificationTest.java | 11 + .../CursorWebSocketSendLoopRollbackTest.java | 708 +++++++++++++++++- 15 files changed, 1515 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 51ef288e1..f0f6547ae 100644 --- a/README.md +++ b/README.md @@ -735,7 +735,9 @@ is the minimum working set every live sender keeps: two segments (`2 × sf_max_s A strict transaction (`transaction=strict`, or no auto-flush trigger) stays in that buffer until the server commits it, and every pooled sender may hold one at once, so a strict transaction that spans more than one segment can use only its sender's share: `sf_max_total_bytes / sender_pool_max`, one segment less with `sf_dir`. A larger one fails -with `TransactionTooLargeException`. +with `TransactionTooLargeException`. So does one that holds more rows of a table than the server's +`qwp.max.uncommitted.rows` when the sender learns that limit only after accepting them, as before its first connection: +the server refuses such a transaction rather than commit it in parts, and `rollback()` discards it. `sf_durability=periodic` checkpoints mmap-published data in the background; `sf_sync_interval_millis` defaults to `5000` in that mode. The interval is a target cadence: JVM scheduling and storage-sync latency add to the actual loss window. Use `request_durable_ack=on` when end-to-end server durability is also required. See the diff --git a/core/src/main/java/io/questdb/client/Sender.java b/core/src/main/java/io/questdb/client/Sender.java index 860cff1c0..539ba8f99 100644 --- a/core/src/main/java/io/questdb/client/Sender.java +++ b/core/src/main/java/io/questdb/client/Sender.java @@ -2834,6 +2834,16 @@ private LineSenderBuilder requestDurableAckTiers(int tiers) { * {@link io.questdb.client.cutlass.qwp.client.TransactionTooLargeException} * and is not added, and {@code close()} without {@code flush()} discards the * transaction instead of committing it. + * The sender may learn the server's {@code qwp.max.uncommitted.rows} only after it + * accepted rows past it: before its first connection, or on a reconnect to a + * server that restarted with a lower setting or to another endpoint. The server + * refuses such a transaction instead of committing it in parts, so every row and + * {@code flush()} of the transaction throws + * {@link io.questdb.client.cutlass.qwp.client.TransactionTooLargeException} until + * {@code rollback()}, {@code reset()} or {@code close()} discards it. If + * {@code flush()} had already committed it, the sender halts with a + * {@link io.questdb.client.SenderError.Category#TRANSACTION_TOO_LARGE} error and + * keeps the transaction in its store-and-forward buffer. * The senders of a pool share {@code sf_max_total_bytes} and may all hold * strict transactions at once, so there a transaction that spans more than * one segment counts only on its sender's share: {@code sf_max_total_bytes} diff --git a/core/src/main/java/io/questdb/client/SenderError.java b/core/src/main/java/io/questdb/client/SenderError.java index 672a6987a..fb5b20ade 100644 --- a/core/src/main/java/io/questdb/client/SenderError.java +++ b/core/src/main/java/io/questdb/client/SenderError.java @@ -278,6 +278,16 @@ public enum Category { * consecutive times with no ack progress — replaying it cannot succeed. */ PROTOCOL_VIOLATION, + /** + * The server cannot commit a strict transaction as one: a table of it would + * reach the server's {@code qwp.max.uncommitted.rows}, where the server commits + * on its own, because the sender accepted the transaction's rows before it + * learned that limit. Wire {@code 0x0F}. The server discarded the rows it had + * received. When the producer rolled the transaction back, the sender discards + * its frames and reports nothing; when the producer committed it, the sender + * halts with this category, and the frames stay in the store-and-forward log. + */ + TRANSACTION_TOO_LARGE, /** * Rows this client had durably buffered will never be sent, and no retry * will change that. The only category with no server involvement: the diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketEncoder.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketEncoder.java index 68c338662..2304f1b47 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketEncoder.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketEncoder.java @@ -249,6 +249,19 @@ public void setDeferCommit(boolean defer) { } } + /** + * Marks every data frame encoded from now on with {@code FLAG_STRICT}: its rows + * belong to a strict transaction, which the server refuses rather than commit in + * parts. The rollback control frame never carries it. + */ + public void setStrict(boolean strict) { + if (strict) { + flags |= FLAG_STRICT; + } else { + flags &= ~FLAG_STRICT; + } + } + public void setVersion(byte version) { this.version = version; } diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java index 0d8b9cfc2..1e09bb5ae 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java @@ -211,6 +211,8 @@ public class QwpWebSocketSender implements Sender { // past any transient disk/NFS stall the deferred-close machinery exists // to survive. private static final long RECYCLE_DEFERRED_CLOSE_MAX_WAIT_MILLIS = 30_000L; + private static final String SPELLINGS_COUNT_TOGETHER = " Rows sent under names that differ only in letter case " + + "count together: the server counts them as one table."; private static final String WRITE_PATH = "/write/v4"; // Yields the Authorization header value presented on each WebSocket upgrade. A constant for a // fixed token or Basic credential; for an httpTokenProvider it pulls a freshly refreshed token, @@ -743,6 +745,19 @@ public class QwpWebSocketSender implements Sender { // it stay in the transaction, including the one whose auto-flush found no // room: the room kept for the commit holds them. private boolean txnBufferFull; + // Strict mode only: why the open transaction can no longer commit as one, null while + // it can. Set when the I/O loop reports that the server refused the transaction, or + // when a table of the transaction already holds a lower qwp.max.uncommitted.rows the + // sender learned after it accepted the rows. Every row and flush() throws it until + // rollback(), reset() or close() ends the transaction. + private String txnRefusal; + // FSN of the open transaction's first frame, -1 while it has sent none: the I/O loop + // names a transaction the server refused by it. sealAndSwapBuffer() keeps it. + private long txnFirstFsn = -1L; + // Strict mode only: the largest qwp.max.uncommitted.rows a row of the open transaction + // was checked against. flush() rechecks the whole transaction only once the server's + // limit has dropped below it. Reset with the transaction. + private long txnMaxCheckedRows; // Transactional mode: simulation of how the ring packs the open transaction's // frames, mirroring MmapSegment's append rule. txnSimSegments counts the // segments the transaction's frames occupy (0 = no frame yet) and @@ -2397,6 +2412,12 @@ public long flushAndGetSequence() { long beforeFsn = cursorEngine != null ? cursorEngine.publishedFsn() : -1L; + if (strictTransactional) { + // Before anything goes out: a commit the server would refuse must not. + checkTransactionNotRefused(); + checkTransactionFitsServerLimit(); + } + // Cursor SF: append happens on the user thread inside // sealAndSwapBuffer, so by the time we reach here every encoded batch // is published in its mmap'd segment. PERIODIC stable-storage barriers @@ -3858,11 +3879,17 @@ public void setRecycleDeferredCloseMaxWaitMillisForTesting(long millis) { * open transaction past what the client buffer can hold alongside the commit, * throws {@link TransactionTooLargeException} instead and is not added. * {@link #close()} discards an uncommitted transaction rather than committing - * it. Enabling it enables transactional mode; disabling it leaves transactional - * mode on. + * it. Its frames carry {@code FLAG_STRICT}, so a server never commits the + * transaction in parts either: when the sender learned the server's limit only + * after it accepted rows past it, the server refuses the transaction, and every + * row and flush of it fails until it is rolled back. Enabling it enables + * transactional mode; disabling it leaves transactional mode on. */ public void setStrictTransactional(boolean strict) { this.strictTransactional = strict; + // The server refuses a strict frame that would reach its limit, rather than + // commit the transaction in parts. + encoder.setStrict(strict); if (strict) { this.transactional = true; } @@ -3880,6 +3907,7 @@ public void setTransactional(boolean transactional) { this.transactional = transactional; if (!transactional) { this.strictTransactional = false; + encoder.setStrict(false); } } @@ -7564,6 +7592,11 @@ private void sealAndSwapBuffer() { // a commit or rollback frame closes it. Every frame passes here, so the group // follows the ring even when a run of frames fails partway, and rollback(), // reset() and close() see every deferred frame that went out. + if (!isDeferredFrame) { + txnFirstFsn = -1L; + } else if (!hasDeferredMessages) { + txnFirstFsn = cursorEngine.publishedFsn(); + } hasDeferredMessages = isDeferredFrame; if (isTxnFrame) { recordTransactionFrame(payloadLen, activeRemaining); @@ -7624,13 +7657,11 @@ private void checkTransactionAcceptsRow() { if (!strictTransactional) { return; } + checkTransactionNotRefused(); if (txnBufferFull) { throw transactionTooLargeForClientBuffer("so the row was not added"); } - long maxRows = serverMaxUncommittedRows; - if (maxRows <= 0) { - maxRows = QwpConstants.DEFAULT_SERVER_MAX_UNCOMMITTED_ROWS; - } + long maxRows = serverMaxUncommittedRowsOrDefault(); // The server commits a table on its own once its uncommitted rows reach // maxRows, so a strict transaction holds at most maxRows - 1 rows per table. // The server counts the rows of every spelling of the table, the names that @@ -7642,7 +7673,12 @@ private void checkTransactionAcceptsRow() { for (QwpTableBuffer spelling = firstSpelling; spelling != null; spelling = spelling.getNextSpelling()) { rows += spelling.getTxnSentRows() + spelling.getRowCount(); } - if (rows >= maxRows) { + if (rows > maxRows) { + // The table already holds the limit without this row: the sender accepted the + // rows under a higher limit, before it learned this one. + throw refuseTransactionOverLimit(currentTableName, rows - 1, maxRows, firstSpelling); + } + if (rows == maxRows) { LineSenderException e = new TransactionTooLargeException("transaction too large for the server") .put(" [table=").put(currentTableName) .put(", rows=").put(rows) @@ -7651,11 +7687,96 @@ private void checkTransactionAcceptsRow() { + "of them are uncommitted, which would split the transaction, so the row was " + "not added."); if (firstSpelling.getNextSpelling() != null) { - e.put(" Rows sent under names that differ only in letter case count together: the server " - + "counts them as one table."); + e.put(SPELLINGS_COUNT_TOGETHER); } throw e.put(" Raise qwp.max.uncommitted.rows on the server"); } + if (maxRows > txnMaxCheckedRows) { + txnMaxCheckedRows = maxRows; + } + } + + /** + * A strict flush() commits the open transaction, which the server commits as one only + * while every table of it stays below qwp.max.uncommitted.rows. Each row was checked + * against the limit the sender knew when the row was added. Once the sender learned a + * lower one, as from a server that restarted with a lower setting, this checks every + * table of the transaction against it, so that no commit goes out that the server + * would refuse. + */ + private void checkTransactionFitsServerLimit() { + long maxRows = serverMaxUncommittedRowsOrDefault(); + if (maxRows >= txnMaxCheckedRows) { + return; + } + ObjList keys = tableBuffers.keys(); + for (int i = 0, n = keys.size(); i < n; i++) { + QwpTableBuffer table = tableBuffers.get(keys.getQuick(i)); + // Count each table once, from its first spelling. + if (table.getFirstSpelling() != table) { + continue; + } + long rows = 0; + for (QwpTableBuffer spelling = table; spelling != null; spelling = spelling.getNextSpelling()) { + rows += spelling.getTxnSentRows() + spelling.getRowCount(); + } + if (rows >= maxRows) { + throw refuseTransactionOverLimit(table.getTableName(), rows, maxRows, table); + } + } + txnMaxCheckedRows = maxRows; + } + + /** + * Records that the open strict transaction can no longer commit as one, because a + * table of it already holds {@code rows} rows, at least the server's limit of + * {@code maxRows} that the sender learned after it accepted them, and returns the + * error to throw. The refusal sticks until the transaction ends. + */ + private TransactionTooLargeException refuseTransactionOverLimit( + CharSequence tableName, + long rows, + long maxRows, + QwpTableBuffer firstSpelling + ) { + StringBuilder message = new StringBuilder(512) + .append("transaction too large for the server [table=").append(tableName) + .append(", rows=").append(rows) + .append(", maxUncommittedRows=").append(maxRows) + .append("]; the sender accepted these rows of the table before it learned the server's " + + "qwp.max.uncommitted.rows, at which the server commits a table's rows on its own, so the " + + "transaction cannot commit as one."); + if (firstSpelling.getNextSpelling() != null) { + message.append(SPELLINGS_COUNT_TOGETHER); + } + txnRefusal = message.append(" Call rollback() to discard it, and raise qwp.max.uncommitted.rows on the server") + .toString(); + return new TransactionTooLargeException(txnRefusal); + } + + /** + * Throws the refusal of the open strict transaction, if it has one. The I/O loop + * reports a transaction the server refused by the FSN of its first frame; when that + * is the open transaction, the refusal sticks until the transaction ends. + */ + private void checkTransactionNotRefused() { + if (txnRefusal == null && hasDeferredMessages) { + // Both callers connect first, and the loop the frames went out on stays while + // they are unacked: a symbol-dictionary recycle waits for a drained ring. + CursorWebSocketSendLoop loop = cursorSendLoop; + assert loop != null : "a sender with frames out has no I/O loop"; + if (loop.getRefusedTransactionFsn() == txnFirstFsn) { + String serverMessage = loop.getRefusedTransactionMessage(); + txnRefusal = "transaction refused by the server" + + (serverMessage != null ? ": " + serverMessage + '.' : ".") + + " The sender accepted the transaction's rows before it learned the server's " + + "qwp.max.uncommitted.rows, and the transaction cannot commit as one. Call rollback() to " + + "discard it"; + } + } + if (txnRefusal != null) { + throw new TransactionTooLargeException(txnRefusal); + } } /** @@ -7669,6 +7790,8 @@ private void clearTransactionState() { } txnTables.setPos(0); txnBufferFull = false; + txnRefusal = null; + txnMaxCheckedRows = 0; txnBytes = 0; txnRefusedBytes = 0; isTxnRefusedAtShare = false; @@ -7904,6 +8027,15 @@ private long sentTransactionRows() { return rows; } + /** + * The server's qwp.max.uncommitted.rows as its last handshake advertised it, or the + * server default when it advertised none. + */ + private long serverMaxUncommittedRowsOrDefault() { + long maxRows = serverMaxUncommittedRows; + return maxRows > 0 ? maxRows : QwpConstants.DEFAULT_SERVER_MAX_UNCOMMITTED_ROWS; + } + /** * The error for a strict transaction the client buffer, or this sender's share * of a buffer other senders share, cannot hold: the size the transaction would diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java index 9bf6c977c..eed6fd7bd 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java @@ -46,6 +46,13 @@ * {@code flush()} throws it when the client buffer cannot hold the flush, and * sends nothing. Either way nothing past the limit reaches the server, and the * transaction keeps the rows accepted before the error. + *

    + * The sender may learn the server's {@code qwp.max.uncommitted.rows} only after it + * accepted rows past it: before its first connection, or on a reconnect to a server + * with a lower setting. Then the transaction as a whole cannot commit as one, and the + * server refuses it rather than commit it in parts: every row, {@code flush()} and + * {@code drain()} of the transaction throws this exception until {@code rollback()}, + * {@code reset()} or {@code close()} discards the transaction. */ public class TransactionTooLargeException extends LineSenderException { diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/WebSocketResponse.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/WebSocketResponse.java index 9b6cb8e24..a955ed133 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/WebSocketResponse.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/WebSocketResponse.java @@ -101,6 +101,13 @@ public class WebSocketResponse { public static final byte STATUS_PARSE_ERROR = 0x05; public static final byte STATUS_SCHEMA_MISMATCH = 0x03; public static final byte STATUS_SECURITY_ERROR = 0x08; + /** + * A frame with {@link io.questdb.client.cutlass.qwp.protocol.QwpConstants#FLAG_STRICT} + * would take a table to the server's {@code qwp.max.uncommitted.rows}, where the server + * commits it on its own. The server refused the frame and discarded the rows the + * connection held uncommitted, so the strict transaction did not commit in parts. + */ + public static final byte STATUS_TRANSACTION_TOO_LARGE = 0x0F; public static final byte STATUS_WRITE_ERROR = 0x09; private final DirectUtf8String lookupKey = new DirectUtf8String(); // Caches decoded table names so the same native-memory byte sequence resolves to @@ -255,6 +262,8 @@ public String getStatusName() { return "NOT_WRITABLE"; case STATUS_DICTIONARY_GAP: return "DICTIONARY_GAP"; + case STATUS_TRANSACTION_TOO_LARGE: + return "TRANSACTION_TOO_LARGE"; default: return "UNKNOWN(" + (status & 0xFF) + ")"; } diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java index ca2715028..ace289bd1 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java @@ -601,6 +601,24 @@ public final class CursorWebSocketSendLoop implements QuietCloseable { // Tracked only while !isRollbackConfirmed, for retireRollbackFrame. Reset with // isRollbackConfirmed; same threading. private long lastSentCommitBearingFsn = -1L; + // A strict transaction the server refused with STATUS_TRANSACTION_TOO_LARGE: the FSN of + // its first frame, -1 when none. The server discarded the transaction's rows and processes + // no later frame of the connection. None of the transaction's frames goes out again: + // trySendBatch walks them instead, see tryResolveRefusedTransaction. I/O thread only; + // survives reconnects until the walk resolves the transaction. + private long refusedTxnStartFsn = -1L; + // The frame the server refused, and the refusal, reported as the terminal error when + // the producer turns out to have committed the transaction. Same threading. + private long refusedTxnFrameFsn = -1L; + private SenderError refusedTxnError; + // FSN of the frame at the cursor while walking the refused transaction, -1 until the + // cursor reaches its first frame; a reconnect resets it. Same threading. + private long refusedTxnScanFsn = -1L; + // The refusal as the producer sees it: the FSN of the refused transaction's first frame, + // -1 when none, and the server's message, which the I/O thread writes first. The producer + // refuses rows and commits of its open transaction when that transaction starts there. + private volatile long refusedTransactionFsn = -1L; + private volatile String refusedTransactionMessage; // Poison-frame detector state (I/O thread only). poisonFsn is the FSN of the // frame implicated by the most recent server-active rejection: the NACK-named // frame, or the OK-level head-of-line frame (highestOkFsn+1) for a @@ -1107,6 +1125,8 @@ public static SenderError.Category classify(byte status) { return SenderError.Category.NOT_WRITABLE; case WebSocketResponse.STATUS_DICTIONARY_GAP: return SenderError.Category.DICTIONARY_GAP; + case WebSocketResponse.STATUS_TRANSACTION_TOO_LARGE: + return SenderError.Category.TRANSACTION_TOO_LARGE; default: return SenderError.Category.UNKNOWN; } @@ -1281,6 +1301,7 @@ public static SenderError.Policy defaultPolicyFor(SenderError.Category category) return SenderError.Policy.ABANDONED; case SCHEMA_MISMATCH: // deterministic: same bytes, same mismatch case PARSE_ERROR: // deterministic: malformed bytes never parse + case TRANSACTION_TOO_LARGE: // deterministic on this server; the loop discards a rolled-back one case SECURITY_ERROR: // ACL denial on a writable node (read-only refusals arrive as role-change closes) case PROTOCOL_VIOLATION: default: @@ -1617,6 +1638,24 @@ public SenderError getLastTerminalServerError() { ? ((LineSenderServerException) e).getServerError() : null; } + /** + * FSN of the first frame of a strict transaction the server refused with + * STATUS_TRANSACTION_TOO_LARGE, or {@code -1}. The producer compares it with the first + * frame of its open transaction: when they match, that transaction can no longer + * commit. The loop clears it once it discarded the transaction. + */ + public long getRefusedTransactionFsn() { + return refusedTransactionFsn; + } + + /** + * The server's message for the transaction {@link #getRefusedTransactionFsn()} names. + * Read it after that FSN: the I/O thread writes it first. + */ + public String getRefusedTransactionMessage() { + return refusedTransactionMessage; + } + /** * Returns the exact latched throwable instance already thrown by * {@link #checkError()}, or {@code null} when no synchronous caller has @@ -3162,6 +3201,10 @@ private void swapClient(WebSocketClient newClient) { long replayStart = engine.ackedFsn() + 1L; this.fsnAtZero = replayStart; this.nextWireSeq = 0L; + // A refused transaction the walk has not resolved yet is never acked, so the + // replay starts at or ahead of it, and the walk starts over when the cursor gets + // there. + refusedTxnScanFsn = -1L; // snapshotReplayTarget froze the completed-send boundary when the // outage began. ACK progress can move replayStart past that boundary; // in that case no frame needs re-sending on this connection. @@ -3933,6 +3976,21 @@ private boolean trySendBatch() { int batchReplayed = 0; long batchBytes = 0; while (true) { + if (refusedTxnStartFsn >= 0 && (refusedTxnScanFsn >= 0 || fsnAtZero + nextWireSeq >= refusedTxnStartFsn)) { + if (batchFrames > 0) { + break; + } + // The cursor reached the strict transaction the server refused: none of its + // frames goes out again. After a reconnect the frames ahead of it went out + // first, and the walk starts at its first frame. + if (refusedTxnScanFsn < 0) { + assert fsnAtZero + nextWireSeq == refusedTxnStartFsn + : "the cursor passed the refused transaction [cursorFsn=" + (fsnAtZero + nextWireSeq) + + ", startFsn=" + refusedTxnStartFsn + ']'; + refusedTxnScanFsn = refusedTxnStartFsn; + } + return tryResolveRefusedTransaction(); + } if (orphanSkipTipFsn >= 0 && fsnAtZero + nextWireSeq >= orphanSkipStartFsn) { if (batchFrames > 0) { break; @@ -4067,10 +4125,7 @@ private boolean trySendBatch() { if (batchFrames > 0) { break; } - recordFatal(new LineSenderException( - "recovered store-and-forward symbol dictionary is incomplete (likely a host crash): " - + "frame delta start " + deltaStart + " exceeds recovered dictionary size " - + sentDictCount + "; cannot replay without corrupting data -- resend required")); + recordFatal(incompleteDictionary(deltaStart)); return false; } try { @@ -4200,6 +4255,178 @@ private void retireRollbackFrame() { "recycling connection to discard a rolled-back transaction the server cannot roll back")); } + // The terminal for a frame whose symbol-dictionary delta starts above the ids the + // mirror holds: those below it are lost, and no frame from here on can go out. + private LineSenderException incompleteDictionary(int deltaStart) { + return new LineSenderException( + "recovered store-and-forward symbol dictionary is incomplete (likely a host crash): " + + "frame delta start " + deltaStart + " exceeds recovered dictionary size " + + sentDictCount + "; cannot replay without corrupting data -- resend required"); + } + + /** + * Ends the walk of a refused strict transaction: clears the I/O thread's state and the + * producer's view of the refusal. + */ + private void clearRefusedTransaction() { + refusedTxnStartFsn = -1L; + refusedTxnFrameFsn = -1L; + refusedTxnError = null; + refusedTxnScanFsn = -1L; + refusedTransactionFsn = -1L; + refusedTransactionMessage = null; + } + + /** + * The producer committed a strict transaction the server refused, so it can commit + * neither as one nor, being strict, in parts. Halts with the refusal over the + * transaction's frames, which stay in the store-and-forward log, as any rejection that + * replaying cannot fix does: on a server with a higher qwp.max.uncommitted.rows, a + * sender recovering the log commits the transaction as one. + */ + private void haltOnRefusedTransaction(long endFsn) { + SenderError refusal = refusedTxnError; + SenderError err = new SenderError( + refusal.getCategory(), + SenderError.Policy.TERMINAL, + refusal.getServerStatusByte(), + refusal.getServerMessage(), + refusal.getMessageSequence(), + externalFsnBase + refusedTxnStartFsn, + externalFsnBase + endFsn, + refusal.getTableName(), + refusal.getDetectedAtNanos() + ); + clearRefusedTransaction(); + recordFatal(new LineSenderServerException(err)); + dispatchError(err); + } + + /** + * The server refused the frame at {@code fsn} with STATUS_TRANSACTION_TOO_LARGE: a + * table of a strict transaction would reach the server's qwp.max.uncommitted.rows, + * where the server commits on its own, because the producer accepted the rows before + * it learned that limit. The server rolled back every row the connection held + * uncommitted, which are the transaction's, and processes no later frame of this + * connection. The transaction's first frame follows the last one the server acked: + * the server acks everything ahead of a refused frame before it refuses it, and + * acks none of a transaction's frames before the transaction commits. + *

    + * None of the transaction's frames goes out again. The producer learns that its open + * transaction can no longer commit, and the cursor goes back to the transaction's + * first frame to walk it, see {@link #tryResolveRefusedTransaction}. + */ + private void refuseTransaction(long fsn, SenderError err) { + long startFsn = Math.max(engine.ackedFsn(), highestOkFsn) + 1L; + if (startFsn > fsn) { + // The server acked the frame it now refuses: no transaction to walk. Halt + // rather than guess which frames the refusal covers. + recordFatal(new LineSenderServerException(err)); + dispatchError(err); + return; + } + LOG.warn("server refused a strict transaction, which cannot commit as one [fsn={}, refusedFsn={}]: {}", + externalFsnBase + startFsn, externalFsnBase + fsn, err.getServerMessage()); + refusedTxnStartFsn = startFsn; + refusedTxnFrameFsn = fsn; + refusedTxnError = err; + refusedTransactionMessage = err.getServerMessage(); + refusedTransactionFsn = startFsn; + positionCursorAt(startFsn); + refusedTxnScanFsn = startFsn; + } + + /** + * The producer rolled back the refused strict transaction, whose rollback frame is at + * {@code rollbackFsn}. Like {@link #retireRollbackFrame}, acknowledges the + * transaction's frames and the rollback frame here, which the cumulative acknowledge + * may do only once the server acked every frame ahead of them, and recycles the + * connection: the walk skipped frames this connection never sent, so the wire + * mapping cannot go on past them, and the server processes no later frame of the + * connection anyway. The next connection starts past the rollback frame. + * + * @return always false: nothing went out + */ + private boolean retireRefusedTransaction(long rollbackFsn) { + if (engine.ackedFsn() < refusedTxnStartFsn - 1L) { + return false; + } + LOG.info("discarding the strict transaction the server refused and the producer rolled back [fsn {}..{}]", + externalFsnBase + refusedTxnStartFsn, externalFsnBase + rollbackFsn); + boolean isAdvanced = engine.acknowledge(rollbackFsn); + assert isAdvanced : "refused transaction already acknowledged [fsn=" + rollbackFsn + ']'; + dispatchProgress(rollbackFsn); + clearRefusedTransaction(); + fail(new LineSenderException("recycling connection after discarding a refused strict transaction")); + return false; + } + + /** + * Walks the refused strict transaction's frames from the cursor, sending none, up to + * the frame that ends it, which the producer publishes once it learned of the refusal: + *

      + *
    • the rollback frame: the producer discarded the transaction, see + * {@link #retireRefusedTransaction};
    • + *
    • a commit-bearing frame: the producer committed it, see + * {@link #haltOnRefusedTransaction}.
    • + *
    + * The deferred frames between carry symbols that frames published later reference, + * so the walk adds them to the dictionary mirror, which the catch-up of the next + * connection registers on the server. + * + * @return always false: nothing goes out + */ + private boolean tryResolveRefusedTransaction() { + while (true) { + // The producer publishes every frame of a segment before it seals the segment + // and makes a new one active. So once the walk sees the segment sealed, the + // published offset it reads after that is final, and no frame can be skipped. + boolean isSealed = sendingSegment != engine.activeSegment(); + long pub = sendingSegment.publishedOffset(); + if (sendOffset >= pub) { + if (!isSealed) { + // The producer has not published the frame that ends the transaction. + return false; + } + MmapSegment next = advanceSegment(); + assert next != sendingSegment : "a sealed segment has a successor"; + sendingSegment = next; + continue; + } + long base = sendingSegment.address(); + int payloadLen = Unsafe.getUnsafe().getInt(base + sendOffset + 4); + long frameEnd = sendOffset + MmapSegment.FRAME_HEADER_SIZE + payloadLen; + assert frameEnd <= pub : "the producer publishes whole frames"; + long frameAddr = base + sendOffset + MmapSegment.FRAME_HEADER_SIZE; + long fsn = refusedTxnScanFsn; + // Both checks bound the payload length first, so a frame they cannot read + // counts as commit-bearing: the safe side, as for retireRollbackFrame. + boolean isRollback = isRollbackFrame(frameAddr, payloadLen); + if (isRollback || !isDeferredFrame(frameAddr, payloadLen)) { + // The frame ends the transaction. An end ahead of the frame the server + // refused would mean the refusal is not about these frames: halt rather + // than discard them. + if (isRollback && fsn >= refusedTxnFrameFsn) { + return retireRefusedTransaction(fsn); + } + haltOnRefusedTransaction(fsn); + return false; + } + int deltaStart = frameDeltaStart(frameAddr, payloadLen); + if (deltaStart > sentDictCount) { + // As trySendBatch's torn-dictionary guard: ids below this frame's delta + // were never registered, so nothing published later can go out either. + recordFatal(incompleteDictionary(deltaStart)); + return false; + } + if (deltaStart >= 0) { + accumulateSentDict(frameAddr, payloadLen, deltaStart); + } + sendOffset = frameEnd; + refusedTxnScanFsn = fsn + 1L; + } + } + /** * Retires the recovered orphaned deferred tail once retirable. *

    @@ -4793,6 +5020,10 @@ private void handleServerRejection(long wireSeq) { ); counters.serverErrors.incrementAndGet(); + if (category == SenderError.Category.TRANSACTION_TOO_LARGE) { + refuseTransaction(fsn, err); + return; + } if (policy == SenderError.Policy.TERMINAL) { // Terminal: stash the typed payload BEFORE dispatching to the // handler. The spec requires signal.terminalError to be latched 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 ba1ee0e5f..c5312c3cc 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 @@ -40,7 +40,9 @@ public final class QwpConstants { * Default of the server's {@code qwp.max.uncommitted.rows}: the per-table * count of rows a deferred-commit group may hold before the server commits * them on its own. A strict transaction assumes this value when the server - * does not advertise {@code X-QWP-Max-Uncommitted-Rows}. + * does not advertise {@code X-QWP-Max-Uncommitted-Rows}, and before its first + * connection. A server whose limit turns out lower refuses a strict transaction + * past it rather than commit it in parts (see {@link #FLAG_STRICT}). */ public static final long DEFAULT_SERVER_MAX_UNCOMMITTED_ROWS = 1_000_000L; /** @@ -63,6 +65,17 @@ public final class QwpConstants { * the client sends only after the server confirmed {@code X-QWP-Rollback}. */ public static final byte FLAG_ROLLBACK = 0x20; + /** + * Flag bit: the frame belongs to a strict transaction, which must commit as one or + * not at all. A strict sender sets it on every data frame. The server then never + * commits the transaction's rows on its own at {@code qwp.max.uncommitted.rows}: it + * answers the frame that would get there with + * {@link io.questdb.client.cutlass.qwp.client.WebSocketResponse#STATUS_TRANSACTION_TOO_LARGE} + * and discards the rows the connection holds uncommitted. A server that predates the + * bit ignores it, like every flag bit it does not know. Mirror of the server-side + * constant. + */ + public static final byte FLAG_STRICT = 0x40; /** * Flag bit: payload region after the prelude is zstd-compressed. Set only * when the handshake negotiated zstd compression. Mirror of the server-side diff --git a/core/src/test/java/io/questdb/client/test/SenderErrorTest.java b/core/src/test/java/io/questdb/client/test/SenderErrorTest.java index 10e91d139..a0be66e4d 100644 --- a/core/src/test/java/io/questdb/client/test/SenderErrorTest.java +++ b/core/src/test/java/io/questdb/client/test/SenderErrorTest.java @@ -41,7 +41,7 @@ public void testAllCategoriesEnumerable() { // Pin the public enum values — adding/removing requires a deliberate spec change // (and an update to wire-classification mapping in the I/O loop). SenderError.Category[] cats = SenderError.Category.values(); - Assert.assertEquals(10, cats.length); + Assert.assertEquals(11, cats.length); Assert.assertEquals(SenderError.Category.SCHEMA_MISMATCH, SenderError.Category.valueOf("SCHEMA_MISMATCH")); Assert.assertEquals(SenderError.Category.PARSE_ERROR, SenderError.Category.valueOf("PARSE_ERROR")); Assert.assertEquals(SenderError.Category.INTERNAL_ERROR, SenderError.Category.valueOf("INTERNAL_ERROR")); @@ -50,6 +50,7 @@ public void testAllCategoriesEnumerable() { Assert.assertEquals(SenderError.Category.NOT_WRITABLE, SenderError.Category.valueOf("NOT_WRITABLE")); Assert.assertEquals(SenderError.Category.DICTIONARY_GAP, SenderError.Category.valueOf("DICTIONARY_GAP")); Assert.assertEquals(SenderError.Category.PROTOCOL_VIOLATION, SenderError.Category.valueOf("PROTOCOL_VIOLATION")); + Assert.assertEquals(SenderError.Category.TRANSACTION_TOO_LARGE, SenderError.Category.valueOf("TRANSACTION_TOO_LARGE")); Assert.assertEquals(SenderError.Category.DATA_LOSS, SenderError.Category.valueOf("DATA_LOSS")); Assert.assertEquals(SenderError.Category.UNKNOWN, SenderError.Category.valueOf("UNKNOWN")); } diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index 97fd035ed..4cf86870d 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -28,12 +28,15 @@ import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; +import io.questdb.client.LineSenderServerException; import io.questdb.client.QuestDB; import io.questdb.client.Sender; +import io.questdb.client.SenderError; import io.questdb.client.cutlass.line.LineSenderException; import io.questdb.client.cutlass.qwp.client.BatchTooLargeForCapException; import io.questdb.client.cutlass.qwp.client.QwpWebSocketSender; import io.questdb.client.cutlass.qwp.client.TransactionTooLargeException; +import io.questdb.client.cutlass.qwp.client.WebSocketResponse; import io.questdb.client.cutlass.qwp.client.sf.cursor.SegmentBudget; import io.questdb.client.cutlass.qwp.protocol.QwpConstants; import io.questdb.client.impl.SenderPool; @@ -48,6 +51,7 @@ import java.lang.management.ManagementFactory; import java.nio.ByteBuffer; import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -1825,6 +1829,207 @@ public void testStrictRowLimitFoldsLetterCaseAsTheEngine() throws Exception { }); } + @Test + public void testClosingARefusedTransactionDiscardsIt() throws Exception { + // close() discards a strict transaction, the one the server refused too: the + // sender discards its frames, so close() returns without an error, and nothing of + // the transaction commits. This server refuses without a message. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + h.refusingStrictDeferredFrame = 2; + h.refusalMessage = null; + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(true); + QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(conf(server) + + "transaction=strict;auto_flush_rows=10;"); + try { + writeRows(s, "t", 0, 35); + awaitRefusalReachesSender(s); + assertRefused(serverRefusalError(null), () -> writeRows(s, "t", 35, 1)); + } finally { + s.close(); + } + Assert.assertTrue(h.committedFrames().isEmpty()); + Assert.assertEquals(1, h.refusals()); + } + }); + } + + @Test + public void testServerRefusalFailsTheOpenTransactionUntilRollback() throws Exception { + // The server refuses the open strict transaction's second frame, as it does one + // that would take a table to qwp.max.uncommitted.rows, where it would commit the + // transaction in parts. From then on every row, flush() and drain() of the + // transaction fails with the refusal, and nothing more of it reaches the server. + // rollback() ends it: the sender discards its frames, reconnects, and the next + // transaction commits. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + h.refusingStrictDeferredFrame = 2; + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(true); + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(conf(server) + + "transaction=strict;auto_flush_rows=10;")) { + writeRows(s, "t", 0, 35); + awaitRefusalReachesSender(s); + String refusal = serverRefusalError(TxnServer.REFUSAL); + assertRefused(refusal, () -> writeRows(s, "t", 35, 1)); + assertRefused(refusal, () -> writeRows(s, "other", 0, 1)); + assertRefused(refusal, s::flush); + assertRefused(refusal, () -> s.drain(1_000)); + s.rollback(); + writeRows(s, "t", 100, 5); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + Assert.assertEquals(1, h.refusals()); + Assert.assertEquals("only the next transaction commits", "C", frameKinds(h.committedFrames())); + Assert.assertEquals(2, h.connectionCount()); + } + }); + } + + @Test + public void testServerRefusalOfACommittedTransactionHaltsTheSender() throws Exception { + // The server refuses the commit frame of a strict transaction that flush() had + // published. The transaction can commit neither as one nor in parts, so the + // sender halts with the refusal over the transaction's frames, which it keeps. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + h.isRefusingStrictCommit = true; + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(true); + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;auto_flush_rows=10;")) { + // Two deferred frames of 10 rows, then the commit frame with 5. + writeRows(s, "t", 0, 25); + s.flush(); + try { + s.drain(5_000); + Assert.fail("the sender must halt"); + } catch (LineSenderServerException e) { + SenderError err = e.getServerError(); + Assert.assertEquals(SenderError.Category.TRANSACTION_TOO_LARGE, err.getCategory()); + Assert.assertEquals(SenderError.Policy.TERMINAL, err.getAppliedPolicy()); + Assert.assertEquals(TxnServer.REFUSAL, err.getServerMessage()); + Assert.assertEquals(0L, err.getFromFsn()); + Assert.assertEquals(2L, err.getToFsn()); + } + } + Assert.assertEquals("DDC", frameKinds(h)); + Assert.assertTrue(h.committedFrames().isEmpty()); + Assert.assertEquals(1, h.connectionCount()); + } + }); + } + + @Test + public void testStrictFlushChecksTheTransactionAgainstALimitLearnedLate() throws Exception { + // A row is checked against the limit when it is added, and flush() commits the + // whole transaction, so once the server's limit drops flush() checks every table. + // Here the 40 rows of "t" and "T", one table to the server, held under the default + // limit, but not under the 30 a handshake then advertised, though the row of a + // added after that fits it. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setRollbackSupported(true); + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(conf(server) + "auto_flush=off;")) { + Assert.assertTrue(s.isStrictTransactional()); + writeRows(s, "t", 0, 20); + writeRows(s, "T", 20, 20); + writeRows(s, "c", 0, 10); + s.applyServerTransactionLimits(30, true); + writeRows(s, "a", 0, 1); + String refusal = overLimitError("t", 40, 30, true); + assertRefused(refusal, s::flush); + assertRefused(refusal, () -> writeRows(s, "a", 1, 1)); + s.rollback(); + // Checked under 30; the limit drops to 20, which the 10 rows still fit. + writeRows(s, "c", 0, 10); + s.applyServerTransactionLimits(20, true); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + Assert.assertEquals("C", frameKinds(h)); + } + }); + } + + @Test + public void testStrictTransactionPastALimitLearnedLateFailsUntilRollback() throws Exception { + // The sender accepted 40 rows of a under the default limit, then a handshake + // advertised 30, as after the server restarted with a lower + // qwp.max.uncommitted.rows. a already holds more than that, so the transaction + // cannot commit as one: the next row of a fails, and so does every later row and + // flush() of the transaction, until rollback() ends it. A row of b, below the new + // limit, still goes in before that. The next transaction starts from zero. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, 4_096)) { + server.setRollbackSupported(true); + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(conf(server) + "transaction=strict;")) { + writeRows(s, "a", 0, 40); + writeRows(s, "b", 0, 5); + s.applyServerTransactionLimits(30, true); + writeRows(s, "b", 5, 1); + String refusal = overLimitError("a", 40, 30, false); + assertRefused(refusal, () -> writeRows(s, "a", 40, 1)); + assertRefused(refusal, () -> writeRows(s, "b", 6, 1)); + assertRefused(refusal, s::flush); + s.rollback(); + writeRows(s, "a", 0, 29); + try { + writeRows(s, "a", 29, 1); + Assert.fail("the 30th row of a must be refused"); + } catch (TransactionTooLargeException e) { + Assert.assertEquals(serverRowLimitError("a", 30), e.getMessage()); + } + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + Assert.assertEquals("only the second transaction commits", 1, h.commitFrames()); + } + }); + } + + @Test + public void testStrictSenderMarksItsDataFramesStrict() throws Exception { + // A strict sender marks its data frames, deferred and commit, with FLAG_STRICT, so + // that the server refuses its transaction rather than commit it in parts; never + // the rollback frame, which the server matches by its exact flags. A + // transaction=on sender marks none. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, 4_096)) { + server.setRollbackSupported(true); + try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { + writeRows(s, "t", 0, 99); + s.flush(); + writeRows(s, "t", 0, 50); + s.rollback(); + Assert.assertTrue(s.drain(5_000)); + } + try (Sender s = Sender.fromConfig(conf(server) + "transaction=on;")) { + writeRows(s, "t", 0, 99); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + List> byConnection = h.framesByConnection(); + Assert.assertEquals(2, byConnection.size()); + String strictKinds = frameKinds(byConnection.get(0)); + Assert.assertTrue(strictKinds, strictKinds.matches("D+[Cc]D+R")); + for (TxnFrame f : byConnection.get(0)) { + Assert.assertEquals(f.toString(), !f.isRollback(), f.isStrict()); + } + String onKinds = frameKinds(byConnection.get(1)); + Assert.assertTrue(onKinds, onKinds.matches("D+[Cc]")); + for (TxnFrame f : byConnection.get(1)) { + Assert.assertFalse(f.toString(), f.isStrict()); + } + } + }); + } + @Test public void testStrictCommitTooLargeForClientBufferIsNotSent() throws Exception { // With auto_flush_bytes=off on top of auto_flush=off, the whole transaction @@ -2741,6 +2946,46 @@ private static String frameKinds(List frames) { return kinds.toString(); } + private static void assertRefused(String expectedMessage, Runnable action) { + try { + action.run(); + Assert.fail("the transaction must be refused"); + } catch (TransactionTooLargeException e) { + Assert.assertEquals(expectedMessage, e.getMessage()); + } + } + + // The I/O thread learns of the server's refusal first; a row added before the sender + // learns of it still goes in. + private static void awaitRefusalReachesSender(QwpWebSocketSender s) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (s.cursorSendLoopForTest().getRefusedTransactionFsn() < 0) { + if (System.nanoTime() > deadline) { + Assert.fail("the sender never learned of the refusal"); + } + Thread.sleep(1); + } + } + + // The refusal of a transaction one table of which holds rows, at or past a limit the + // sender learned after it accepted them. + private static String overLimitError(String table, long rows, long maxUncommittedRows, boolean isSpellings) { + return "transaction too large for the server [table=" + table + ", rows=" + rows + + ", maxUncommittedRows=" + maxUncommittedRows + "]; the sender accepted these rows of the table " + + "before it learned the server's qwp.max.uncommitted.rows, at which the server commits a table's " + + "rows on its own, so the transaction cannot commit as one." + + (isSpellings ? " Rows sent under names that differ only in letter case count together: the " + + "server counts them as one table." : "") + + " Call rollback() to discard it, and raise qwp.max.uncommitted.rows on the server"; + } + + // The refusal of a transaction the server refused, with or without a message. + private static String serverRefusalError(String serverMessage) { + return "transaction refused by the server" + (serverMessage != null ? ": " + serverMessage + '.' : ".") + + " The sender accepted the transaction's rows before it learned the server's " + + "qwp.max.uncommitted.rows, and the transaction cannot commit as one. Call rollback() to discard it"; + } + private static String serverRowLimitError(String table, long maxUncommittedRows) { return "transaction too large for the server [table=" + table + ", rows=" + maxUncommittedRows + ", maxUncommittedRows=" + maxUncommittedRows + "]; the server commits a table's rows on its " @@ -3038,6 +3283,10 @@ boolean isRollback() { return size == QwpConstants.HEADER_SIZE && flags == QwpConstants.ROLLBACK_FRAME_FLAGS; } + boolean isStrict() { + return (flags & QwpConstants.FLAG_STRICT) != 0; + } + @Override public String toString() { return connection + ":" + (isRollback() ? "R" : isDeferred() ? "D" : "C") + size; @@ -3057,10 +3306,20 @@ public String toString() { * frame: the group stays open, and the next commit on the connection commits it. */ private static final class TxnServer implements TestWebSocketServer.WebSocketServerHandler { + // The message the server refuses a strict frame with. + static final String REFUSAL = "strict transaction too large"; // Every frame received, over all connections, in arrival order. final List frames = new CopyOnWriteArrayList<>(); volatile boolean isAckingRollback = true; + // Refuses a strict commit frame, as the QuestDB server does one whose rows take a + // table to qwp.max.uncommitted.rows. + volatile boolean isRefusingStrictCommit; + // Refuses the strict deferred frame at this position in its group, 0 for none. + volatile int refusingStrictDeferredFrame; + // The message of a refusal; null sends none. + volatile String refusalMessage = REFUSAL; volatile int rolledBackGroups; + private int refusals; // Frames a commit frame committed, in commit order. private final List committed = new ArrayList<>(); private final Map connections = new IdentityHashMap<>(); @@ -3077,14 +3336,29 @@ public synchronized void onBinaryMessage(TestWebSocketServer.ClientHandler clien frames.add(frame); notifyAll(); try { + // A refusal discards the group and, as on the QuestDB server, stops the + // processing of everything the connection sends after it. + if (connection.isRefused) { + return; + } + if (frame.isStrict() && (frame.isCommit() ? isRefusingStrictCommit + : ++connection.strictDeferredFrames == refusingStrictDeferredFrame)) { + refusals++; + connection.group.clear(); + connection.isRefused = true; + client.sendBinary(refusal(seq, refusalMessage)); + return; + } if (frame.isCommit()) { committed.addAll(connection.group); committed.add(frame); connection.group.clear(); + connection.strictDeferredFrames = 0; client.sendBinary(ack(seq)); } else if (frame.isRollback() && client.isRollbackConfirmed()) { rolledBackGroups++; connection.group.clear(); + connection.strictDeferredFrames = 0; if (isAckingRollback) { client.sendBinary(ack(seq)); } @@ -3096,6 +3370,22 @@ public synchronized void onBinaryMessage(TestWebSocketServer.ClientHandler clien } } + synchronized int refusals() { + return refusals; + } + + // STATUS_TRANSACTION_TOO_LARGE for the frame at seq. + private static byte[] refusal(long seq, String message) { + byte[] text = message == null ? new byte[0] : message.getBytes(StandardCharsets.UTF_8); + byte[] buf = new byte[1 + 8 + 2 + text.length]; + ByteBuffer bb = ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN); + bb.put(WebSocketResponse.STATUS_TRANSACTION_TOO_LARGE); + bb.putLong(seq); + bb.putShort((short) text.length); + bb.put(text); + return buf; + } + synchronized boolean awaitRollbackFrames(int count) throws InterruptedException { long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); while (rollbackFrames() < count) { @@ -3173,7 +3463,9 @@ private static final class Connection { // Deferred frames the connection holds uncommitted. final List group = new ArrayList<>(); final int index; + boolean isRefused; long nextSeq; + int strictDeferredFrames; Connection(int index) { this.index = index; diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpWebSocketEncoderTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpWebSocketEncoderTest.java index 9767eaf9c..3032656ab 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpWebSocketEncoderTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpWebSocketEncoderTest.java @@ -1423,6 +1423,50 @@ public void testSplitMessageCopiesStagedTableBodies() throws Exception { }); } + @Test + public void testStrictFlagMarksEveryDataFrame() throws Exception { + // A strict sender marks its frames with FLAG_STRICT, so the server refuses rather + // than commits its transaction in parts: frames encode() writes, deferred + // delta-dictionary frames, the split frames copied from them and the bare commit + // frame. Never the rollback frame, which the server matches by its exact flags. + assertMemoryLeak(() -> { + try (QwpWebSocketEncoder encoder = new QwpWebSocketEncoder(); + MicrobatchBuffer target = new MicrobatchBuffer(256); + QwpTableBuffer table = new QwpTableBuffer("t")) { + table.getOrCreateColumn("x", TYPE_LONG, false).addLong(1); + table.nextRow(); + encoder.setStrict(true); + encoder.encode(table); + Assert.assertEquals(FLAG_GORILLA | FLAG_STRICT, headerFlags(encoder.getBuffer().getBufferPtr())); + + GlobalSymbolDictionary dict = new GlobalSymbolDictionary(); + encoder.setDeferCommit(true); + encoder.beginMessage(1, dict, -1, -1); + int tableBodyOffset = encoder.getBuffer().getPosition(); + encoder.addTable(table); + int tableBodyLength = encoder.getBuffer().getPosition() - tableBodyOffset; + encoder.finishMessage(); + Assert.assertEquals(FLAG_GORILLA | FLAG_DELTA_SYMBOL_DICT | FLAG_DEFER_COMMIT | FLAG_STRICT, + headerFlags(encoder.getBuffer().getBufferPtr())); + encoder.copySplitMessage(target, tableBodyOffset, tableBodyLength, false, -1, -1); + Assert.assertEquals(FLAG_GORILLA | FLAG_DELTA_SYMBOL_DICT | FLAG_STRICT, headerFlags(target.getBufferPtr())); + + encoder.setDeferCommit(false); + encoder.beginMessage(0, dict, -1, -1); + encoder.finishMessage(); + Assert.assertEquals(FLAG_GORILLA | FLAG_DELTA_SYMBOL_DICT | FLAG_STRICT, + headerFlags(encoder.getBuffer().getBufferPtr())); + + encoder.encodeRollbackMessage(); + Assert.assertEquals(ROLLBACK_FRAME_FLAGS, headerFlags(encoder.getBuffer().getBufferPtr())); + + encoder.setStrict(false); + encoder.encode(table); + Assert.assertEquals(FLAG_GORILLA, headerFlags(encoder.getBuffer().getBufferPtr())); + } + }); + } + @Test public void testTableHeaderMatchesTheWireLayout() throws Exception { assertMemoryLeak(() -> { @@ -1479,6 +1523,11 @@ public void testVersionByteInHeader() throws Exception { }); } + // The flags byte of the QWP header at ptr, unsigned. + private static int headerFlags(long ptr) { + return Unsafe.getUnsafe().getByte(ptr + HEADER_OFFSET_FLAGS) & 0xFF; + } + private static void assertFailure( Class expectedType, String expectedMessage, diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/WebSocketResponseTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/WebSocketResponseTest.java index b70bdc4f7..052609d9b 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/WebSocketResponseTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/WebSocketResponseTest.java @@ -257,6 +257,29 @@ public void testErrorRoundTrip() throws Exception { }); } + @Test + public void testTransactionTooLargeRoundTrip() throws Exception { + assertMemoryLeak(() -> { + WebSocketResponse original = WebSocketResponse.error( + 5L, WebSocketResponse.STATUS_TRANSACTION_TOO_LARGE, "strict transaction too large"); + int size = original.serializedSize(); + long ptr = Unsafe.malloc(size, MemoryTag.NATIVE_DEFAULT); + try { + original.writeTo(ptr); + + WebSocketResponse parsed = new WebSocketResponse(); + Assert.assertTrue(parsed.readFrom(ptr, size)); + Assert.assertFalse(parsed.isSuccess()); + Assert.assertEquals(0x0F, parsed.getStatus()); + Assert.assertEquals("TRANSACTION_TOO_LARGE", parsed.getStatusName()); + Assert.assertEquals(5L, parsed.getSequence()); + Assert.assertEquals("strict transaction too large", parsed.getErrorMessage()); + } finally { + Unsafe.free(ptr, size, MemoryTag.NATIVE_DEFAULT); + } + }); + } + @Test public void testLargeTableCountWithInsufficientPayload() throws Exception { assertMemoryLeak(() -> { diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoopErrorClassificationTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoopErrorClassificationTest.java index f9b081704..a79edc528 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoopErrorClassificationTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoopErrorClassificationTest.java @@ -82,6 +82,17 @@ public void testClassifyNotWritable() { CursorWebSocketSendLoop.classify(WebSocketResponse.STATUS_NOT_WRITABLE)); } + @Test + public void testClassifyTransactionTooLarge() { + // Wire byte 0x0F: the server refused a strict transaction it cannot commit as + // one. Deterministic on that server, so TERMINAL by default; the loop discards + // the transaction instead when the producer rolled it back. + Assert.assertEquals(SenderError.Category.TRANSACTION_TOO_LARGE, + CursorWebSocketSendLoop.classify(WebSocketResponse.STATUS_TRANSACTION_TOO_LARGE)); + Assert.assertEquals(SenderError.Policy.TERMINAL, + CursorWebSocketSendLoop.defaultPolicyFor(SenderError.Category.TRANSACTION_TOO_LARGE)); + } + @Test public void testClassifyUnknownStatusByte() { // Forward-compat: any byte the client doesn't recognize → UNKNOWN. diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoopRollbackTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoopRollbackTest.java index 7468fde72..aa64415d0 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoopRollbackTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoopRollbackTest.java @@ -25,13 +25,17 @@ package io.questdb.client.test.cutlass.qwp.client.sf.cursor; import io.questdb.client.DefaultHttpClientConfiguration; +import io.questdb.client.LineSenderServerException; +import io.questdb.client.SenderError; import io.questdb.client.cutlass.http.client.WebSocketFrameHandler; +import io.questdb.client.cutlass.line.LineSenderException; import io.questdb.client.cutlass.qwp.client.DurableAckTiers; import io.questdb.client.cutlass.qwp.client.WebSocketResponse; import io.questdb.client.cutlass.qwp.client.sf.cursor.BackgroundDrainer; import io.questdb.client.cutlass.qwp.client.sf.cursor.CursorSendEngine; import io.questdb.client.cutlass.qwp.client.sf.cursor.CursorWebSocketSendLoop; import io.questdb.client.cutlass.qwp.protocol.QwpConstants; +import io.questdb.client.cutlass.qwp.websocket.WebSocketCloseCode; import io.questdb.client.network.PlainSocketFactory; import io.questdb.client.std.MemoryTag; import io.questdb.client.std.Rnd; @@ -47,6 +51,7 @@ import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BooleanSupplier; @@ -75,6 +80,8 @@ public class CursorWebSocketSendLoopRollbackTest { // Random transaction logs per run of the fuzz test; raise it for a local soak. private static final int FUZZ_ITERATIONS = Integer.getInteger("questdb.fuzz.rollback.iterations", 100); + // The message the model server refuses a strict frame with. + private static final String REFUSAL = "strict transaction too large"; private static final long SEGMENT_SIZE_BYTES = 64 * 1024; private static final String TABLE = "t"; @@ -343,6 +350,391 @@ public void testRollbackWaitsForShortFrameAck() throws Exception { assertRollbackWaitsForAckOf(false, engine -> appendForeign(engine, 8), "X8"); } + @Test + public void testCommittedRefusedTransactionHaltsTheLoop() throws Exception { + // The producer committed the transaction before the refusal of its frame 3 + // arrived. Being strict, the transaction cannot commit in parts either, so the + // loop halts with the refusal over its frames, which stay in the log, unacked. + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendStrict(engine, false, 1, 1); + appendStrict(engine, true, 2, 6); + appendStrict(engine, true, 3, 6); + appendStrict(engine, false, 4, 1); + ServerModel server = new ServerModel(); + server.setCap(10); + List clients = new ArrayList<>(); + CursorWebSocketSendLoop loop = newLoop(engine, server, clients, true); + try { + loop.start(); + awaitTrue("the loop halts", () -> loop.getTerminalError() != null); + assertRefusalHalted(loop, 1L, 3L, 2L); + Assert.assertEquals(-1L, loop.getRefusedTransactionFsn()); + } finally { + loop.close(); + } + Assert.assertEquals("the transaction stays in the log", 0L, engine.ackedFsn()); + Assert.assertEquals(Arrays.asList("0:C1", "0:D2", "0:D3", "0:C4"), server.received()); + Assert.assertEquals(Collections.singletonList("0:D3"), server.refused()); + Assert.assertEquals(Collections.singletonList("C1"), server.committed()); + Assert.assertEquals(1, clientCount(clients)); + } + }); + } + + @Test + public void testRefusalOfAFrameTheServerAckedHalts() throws Exception { + // A server that acked a frame cannot refuse it: there is no transaction to walk, + // so the loop halts rather than guess which frames the refusal covers. In + // durable-ack mode the OK moves only the OK watermark, so the refusal does not + // read as one of a dictionary catch-up below the replay start. + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendStrict(engine, true, 1, 1); + appendStrict(engine, false, 2, 1); + RecordingClient client = new RecordingClient(); + CursorWebSocketSendLoop loop = newManualLoop(engine, client, null, DurableAckTiers.REPLICATED); + try { + loop.setRunningForTest(true); + loop.positionCursorForStartForTest(); + Assert.assertTrue(loop.trySendBatchForTest()); + deliverOk(loop, 1L); + deliverRefusal(loop, 1L); + assertRefusalHalted(loop, 1L, 1L, 1L); + Assert.assertEquals(-1L, loop.getRefusedTransactionFsn()); + } finally { + loop.close(); + } + } + }); + } + + @Test + public void testRefusalPastTheEndOfTheTransactionHalts() throws Exception { + // The server refuses frame 2, but the unacked transaction that starts at frame 0 + // ends at the rollback frame 1, ahead of it: the refusal is not about the frames + // the loop would discard, so it halts instead. + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendStrict(engine, true, 1, 1); + appendRollback(engine); + appendStrict(engine, true, 2, 1); + RecordingClient client = new RecordingClient(); + CursorWebSocketSendLoop loop = newManualLoop(engine, client, null, DurableAckTiers.NONE); + try { + loop.setRunningForTest(true); + loop.positionCursorForStartForTest(); + Assert.assertTrue(loop.trySendBatchForTest()); + Assert.assertEquals(Arrays.asList("D1", "R", "D2"), client.log); + deliverRefusal(loop, 2L); + Assert.assertEquals(0L, loop.getRefusedTransactionFsn()); + Assert.assertEquals(REFUSAL, loop.getRefusedTransactionMessage()); + Assert.assertFalse(loop.trySendBatchForTest()); + assertRefusalHalted(loop, 0L, 1L, 2L); + Assert.assertEquals("nothing goes out again", 3, client.log.size()); + } finally { + loop.close(); + } + } + }); + } + + @Test + public void testRefusedOpenTransactionWaitsForItsEnd() throws Exception { + // The refusal arrives while the transaction is open. The loop sends nothing more + // and reports the refusal to the producer, which ends the transaction: here with + // a rollback frame, after which the loop discards the transaction and the next + // connection carries on with the next transaction. + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendStrict(engine, false, 1, 1); + appendStrict(engine, true, 2, 6); + appendStrict(engine, true, 3, 6); + ServerModel server = new ServerModel(); + server.setCap(10); + List clients = new ArrayList<>(); + CursorWebSocketSendLoop loop = newLoop(engine, server, clients, true); + try { + loop.start(); + awaitTrue("the server refuses frame 3", () -> loop.getRefusedTransactionFsn() == 1L); + Assert.assertEquals(REFUSAL, loop.getRefusedTransactionMessage()); + ModelClient first = client(clients, 0); + int polls = first.polls; + awaitTrue("the loop keeps waiting", () -> first.polls >= polls + 50); + Assert.assertEquals(1, clientCount(clients)); + Assert.assertEquals(0L, engine.ackedFsn()); + loop.checkError(); + + appendRollback(engine); + appendStrict(engine, true, 4, 2); + appendStrict(engine, false, 5, 1); + awaitAckedFsn(engine, 5L); + Assert.assertEquals(-1L, loop.getRefusedTransactionFsn()); + Assert.assertNull(loop.getRefusedTransactionMessage()); + } finally { + loop.close(); + } + Assert.assertEquals(Arrays.asList("0:C1", "0:D2", "0:D3", "1:D4", "1:C5"), server.received()); + Assert.assertEquals(Collections.singletonList("0:D3"), server.refused()); + Assert.assertEquals(Arrays.asList("C1", "D4", "C5"), server.committed()); + Assert.assertEquals(2, clientCount(clients)); + } + }); + } + + @Test + public void testRefusedTransactionRolledBackIsDiscarded() throws Exception { + // The server refuses strict frame 3, whose rows take the transaction to its cap of + // 10, and processes nothing after it on that connection. The producer had rolled + // the transaction back already: the loop discards the transaction's frames and + // the rollback frame, and the next connection starts with the next transaction. + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendStrict(engine, false, 1, 1); + appendStrict(engine, true, 2, 6); + appendStrict(engine, true, 3, 6); + appendRollback(engine); + appendStrict(engine, true, 4, 2); + appendStrict(engine, false, 5, 1); + ServerModel server = new ServerModel(); + server.setCap(10); + List clients = new ArrayList<>(); + runToAck(engine, newLoop(engine, server, clients, true), 5L); + Assert.assertEquals(Arrays.asList("0:C1", "0:D2", "0:D3", "0:R", "0:D4", "0:C5", "1:D4", "1:C5"), + server.received()); + Assert.assertEquals(Collections.singletonList("0:D3"), server.refused()); + Assert.assertEquals(Arrays.asList("C1", "D4", "C5"), server.committed()); + Assert.assertEquals(2, clientCount(clients)); + } + }); + } + + @Test + public void testRefusedTransactionStaysUnsentAcrossReconnects() throws Exception { + // The connection drops while the loop waits for the refused transaction to end. + // The next connection replays from the transaction's first frame, which the loop + // walks again instead of sending it. + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendStrict(engine, false, 1, 1); + appendStrict(engine, true, 2, 6); + appendStrict(engine, true, 3, 6); + ServerModel server = new ServerModel(); + server.setCap(10); + List clients = new ArrayList<>(); + CursorWebSocketSendLoop loop = newLoop(engine, server, clients, true); + try { + loop.start(); + awaitTrue("the server refuses frame 3", () -> loop.getRefusedTransactionFsn() == 1L); + client(clients, 0).closeFromServer(); + awaitTrue("the loop reconnects", () -> clientCount(clients) == 2); + ModelClient second = client(clients, 1); + int polls = second.polls; + awaitTrue("the loop keeps waiting on the new connection", () -> second.polls >= polls + 50); + Assert.assertEquals("the refused transaction does not go out again", 0, second.flushedFrames); + Assert.assertEquals(1L, loop.getRefusedTransactionFsn()); + + appendRollback(engine); + appendStrict(engine, true, 4, 2); + appendStrict(engine, false, 5, 1); + awaitAckedFsn(engine, 5L); + } finally { + loop.close(); + } + Assert.assertEquals(Arrays.asList("0:C1", "0:D2", "0:D3", "2:D4", "2:C5"), server.received()); + Assert.assertEquals(Arrays.asList("C1", "D4", "C5"), server.committed()); + Assert.assertEquals(3, clientCount(clients)); + } + }); + } + + @Test + public void testRefusedTransactionWaitsForDurableAckBeforeDiscarding() throws Exception { + // Discarding the refused transaction acknowledges its frames, an acknowledgement + // that also covers commit 1 ahead of them. In durable-ack mode the loop waits for + // commit 1's durable ack first, which the server holds back here. + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendStrict(engine, false, 1, 1); + appendStrict(engine, true, 2, 6); + appendStrict(engine, true, 3, 6); + appendRollback(engine); + appendStrict(engine, true, 4, 2); + appendStrict(engine, false, 5, 1); + ServerModel server = new ServerModel(); + server.setCap(10); + List clients = new ArrayList<>(); + ModelClient first = newClient(server, clients, true, true); + first.isHoldingAcks = true; + AtomicBoolean isFirstConnect = new AtomicBoolean(true); + CursorWebSocketSendLoop loop = new CursorWebSocketSendLoop( + null, engine, 0L, + () -> isFirstConnect.getAndSet(false) ? first : newClient(server, clients, true, true), + 1L, 5L, DurableAckTiers.REPLICATED, 0L); + try { + loop.start(); + awaitTrue("the server refuses frame 3", () -> loop.getRefusedTransactionFsn() == 1L); + int polls = first.polls; + awaitTrue("the loop keeps waiting on its connection", () -> first.polls >= polls + 50); + Assert.assertEquals("no recycle before commit 1 is durable", 1, clientCount(clients)); + Assert.assertEquals(-1L, engine.ackedFsn()); + first.releaseAcks(); + awaitAckedFsn(engine, 5L); + } finally { + loop.close(); + } + Assert.assertEquals(Arrays.asList("0:C1", "0:D2", "0:D3", "0:R", "0:D4", "0:C5", "1:D4", "1:C5"), + server.received()); + Assert.assertEquals(Arrays.asList("C1", "D4", "C5"), server.committed()); + Assert.assertEquals(2, clientCount(clients)); + } + }); + } + + @Test + public void testRefusedTransactionWalkStartsBehindReplayedCommits() throws Exception { + // In durable-ack mode a reconnect replays from the durable watermark, here from + // commit 1, whose durable ack the first connection held back. The loop sends + // commit 1 again, as any replay does, then walks the refused transaction behind it + // without sending it, and discards it once commit 1 is durable. + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendStrict(engine, false, 1, 1); + appendStrict(engine, true, 2, 6); + appendStrict(engine, true, 3, 6); + ServerModel server = new ServerModel(); + server.setCap(10); + List clients = new ArrayList<>(); + ModelClient first = newClient(server, clients, true, true); + first.isHoldingAcks = true; + AtomicBoolean isFirstConnect = new AtomicBoolean(true); + CursorWebSocketSendLoop loop = new CursorWebSocketSendLoop( + null, engine, 0L, + () -> isFirstConnect.getAndSet(false) ? first : newClient(server, clients, true, true), + 1L, 5L, DurableAckTiers.REPLICATED, 0L); + try { + loop.start(); + awaitTrue("the server refuses frame 3", () -> loop.getRefusedTransactionFsn() == 1L); + first.closeFromServer(); + awaitTrue("commit 1 becomes durable on the next connection", () -> engine.ackedFsn() == 0L); + Assert.assertEquals("only commit 1 goes out again", 1, client(clients, 1).flushedFrames); + + appendRollback(engine); + appendStrict(engine, true, 4, 2); + appendStrict(engine, false, 5, 1); + awaitAckedFsn(engine, 5L); + } finally { + loop.close(); + } + Assert.assertEquals(Arrays.asList("0:C1", "0:D2", "0:D3", "1:C1", "2:D4", "2:C5"), server.received()); + Assert.assertEquals(Arrays.asList("C1", "C1", "D4", "C5"), server.committed()); + Assert.assertEquals(3, clientCount(clients)); + } + }); + } + + @Test + public void testRefusedTransactionWalkCrossesSegments() throws Exception { + // The refused transaction's frames fill several store-and-forward segments, which + // the walk follows up to the rollback frame. Frame 6 is the fifth of 2 rows each, + // so it takes the transaction to the cap of 10. + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendStrict(engine, false, 1, 1); + for (int id = 2; id < 8; id++) { + appendStrict(engine, true, id, 2, 20_000); + } + appendRollback(engine); + appendStrict(engine, false, 9, 1); + ServerModel server = new ServerModel(); + server.setCap(10); + List clients = new ArrayList<>(); + runToAck(engine, newLoop(engine, server, clients, true), 8L); + Assert.assertTrue("the transaction spans segments", engine.activeSegment().baseSeq() > 1L); + Assert.assertEquals(Collections.singletonList("0:D6"), server.refused()); + Assert.assertEquals(Arrays.asList("C1", "C9"), server.committed()); + Assert.assertEquals(2, clientCount(clients)); + List secondConnection = new ArrayList<>(); + for (String frame : server.received()) { + if (frame.startsWith("1:")) { + secondConnection.add(frame); + } + } + Assert.assertEquals(Collections.singletonList("1:C9"), secondConnection); + } + }); + } + + @Test + public void testRetiredTransactionSymbolsReachTheNextConnection() throws Exception { + // Frames of the next transaction reference the refused transaction's symbols + // without registering them again. Frame 1 of the refused transaction never went + // out: the walk adds its symbol to the dictionary mirror, so the next + // connection's catch-up registers it with the one frame 0 sent. + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendStrictDelta(engine, true, 0, 'a'); + RecordingClient first = new RecordingClient(); + List next = new ArrayList<>(); + CursorWebSocketSendLoop loop = newManualLoop(engine, first, next, DurableAckTiers.NONE); + try { + loop.setRunningForTest(true); + loop.positionCursorForStartForTest(); + Assert.assertTrue(loop.trySendBatchForTest()); + deliverRefusal(loop, 0L); + appendStrictDelta(engine, true, 1, 'b'); + appendRollback(engine); + appendStrictDelta(engine, false, 2, 'c'); + + Assert.assertFalse("the walk discards the transaction", loop.trySendBatchForTest()); + Assert.assertEquals(2L, engine.ackedFsn()); + Assert.assertEquals(-1L, loop.getRefusedTransactionFsn()); + Assert.assertEquals(Collections.singletonList("D delta 0: a"), first.log); + Assert.assertEquals(1, next.size()); + Assert.assertTrue(loop.trySendBatchForTest()); + Assert.assertEquals(Arrays.asList("catch-up 0: a b", "C delta 2: c"), next.get(0).log); + loop.checkError(); + } finally { + loop.close(); + } + } + }); + } + + @Test + public void testWalkStopsAtATornDictionary() throws Exception { + // The torn-dictionary guard holds in the walk too: a frame whose delta starts + // above every id the mirror holds halts the loop, as it does when sending. + TestUtils.assertMemoryLeak(() -> { + try (CursorSendEngine engine = newEngine()) { + appendStrictDelta(engine, true, 0, 'a'); + RecordingClient client = new RecordingClient(); + CursorWebSocketSendLoop loop = newManualLoop(engine, client, null, DurableAckTiers.NONE); + try { + loop.setRunningForTest(true); + loop.positionCursorForStartForTest(); + Assert.assertTrue(loop.trySendBatchForTest()); + Assert.assertEquals(1, loop.sentDictCount()); + deliverRefusal(loop, 0L); + appendStrictDelta(engine, true, 5, 'f'); + Assert.assertFalse(loop.trySendBatchForTest()); + try { + loop.checkError(); + Assert.fail("the walk must halt at the gap"); + } catch (LineSenderException e) { + Assert.assertEquals("recovered store-and-forward symbol dictionary is incomplete (likely a " + + "host crash): frame delta start 5 exceeds recovered dictionary size 1; " + + "cannot replay without corrupting data -- resend required", + e.getMessage()); + } + Assert.assertEquals(Collections.singletonList("D delta 0: a"), client.log); + } finally { + loop.close(); + } + } + }); + } + private static void appendCommit(CursorSendEngine engine, int id) { appendFrame(engine, (byte) 0, id); } @@ -398,6 +790,136 @@ private static void appendRollback(CursorSendEngine engine) { appendHeader(engine, QwpConstants.MAGIC_MESSAGE, QwpConstants.ROLLBACK_FRAME_FLAGS); } + private static void appendStrict(CursorSendEngine engine, boolean isDeferred, int id, int rows) { + appendStrict(engine, isDeferred, id, rows, 0); + } + + // A frame of a strict sender: its flags carry FLAG_STRICT, and its id and its row + // count, which the model server counts toward its cap, follow the header. + private static void appendStrict(CursorSendEngine engine, boolean isDeferred, int id, int rows, int padding) { + int size = QwpConstants.HEADER_SIZE + 8 + padding; + long buf = Unsafe.malloc(size, MemoryTag.NATIVE_DEFAULT); + try { + Unsafe.getUnsafe().setMemory(buf, size, (byte) 0); + Unsafe.getUnsafe().putInt(buf, QwpConstants.MAGIC_MESSAGE); + Unsafe.getUnsafe().putByte(buf + 4, QwpConstants.VERSION); + Unsafe.getUnsafe().putByte(buf + QwpConstants.HEADER_OFFSET_FLAGS, strictFlags(isDeferred)); + Unsafe.getUnsafe().putInt(buf + QwpConstants.HEADER_SIZE, id); + Unsafe.getUnsafe().putInt(buf + QwpConstants.HEADER_SIZE + 4, rows); + engine.appendBlocking(buf, size); + } finally { + Unsafe.free(buf, size, MemoryTag.NATIVE_DEFAULT); + } + } + + // A strict frame with a symbol-dictionary delta that registers one symbol at + // deltaStart, and no table blocks. + private static void appendStrictDelta(CursorSendEngine engine, boolean isDeferred, int deltaStart, char symbol) { + int size = QwpConstants.HEADER_SIZE + 4; + long buf = Unsafe.malloc(size, MemoryTag.NATIVE_DEFAULT); + try { + Unsafe.getUnsafe().setMemory(buf, size, (byte) 0); + Unsafe.getUnsafe().putInt(buf, QwpConstants.MAGIC_MESSAGE); + Unsafe.getUnsafe().putByte(buf + 4, QwpConstants.VERSION); + Unsafe.getUnsafe().putByte(buf + QwpConstants.HEADER_OFFSET_FLAGS, + (byte) (strictFlags(isDeferred) | QwpConstants.FLAG_DELTA_SYMBOL_DICT)); + long p = buf + QwpConstants.HEADER_SIZE; + Unsafe.getUnsafe().putByte(p, (byte) deltaStart); + Unsafe.getUnsafe().putByte(p + 1, (byte) 1); + Unsafe.getUnsafe().putByte(p + 2, (byte) 1); + Unsafe.getUnsafe().putByte(p + 3, (byte) symbol); + engine.appendBlocking(buf, size); + } finally { + Unsafe.free(buf, size, MemoryTag.NATIVE_DEFAULT); + } + } + + // The loop halted with the server's refusal, reported over the FSNs from..to. + private static void assertRefusalHalted(CursorWebSocketSendLoop loop, long fromFsn, long toFsn, long seq) { + try { + loop.checkError(); + Assert.fail("the loop must halt"); + } catch (LineSenderServerException e) { + SenderError err = e.getServerError(); + Assert.assertSame(err, loop.getLastTerminalServerError()); + Assert.assertEquals(SenderError.Category.TRANSACTION_TOO_LARGE, err.getCategory()); + Assert.assertEquals(SenderError.Policy.TERMINAL, err.getAppliedPolicy()); + Assert.assertEquals(WebSocketResponse.STATUS_TRANSACTION_TOO_LARGE, err.getServerStatusByte()); + Assert.assertEquals(REFUSAL, err.getServerMessage()); + Assert.assertEquals(seq, err.getMessageSequence()); + Assert.assertEquals(fromFsn, err.getFromFsn()); + Assert.assertEquals(toFsn, err.getToFsn()); + } + } + + private static ModelClient client(List clients, int connection) { + synchronized (clients) { + return clients.get(connection); + } + } + + // An OK covering wire sequence seq, for a commit of table TABLE at seqTxn 1. In + // durable-ack mode it waits for a durable ack, which never comes here. + private static void deliverOk(CursorWebSocketSendLoop loop, long seq) { + byte[] name = TABLE.getBytes(StandardCharsets.UTF_8); + int size = 1 + 8 + 2 + 2 + name.length + 8; + long ptr = Unsafe.malloc(size, MemoryTag.NATIVE_DEFAULT); + try { + Unsafe.getUnsafe().putByte(ptr, WebSocketResponse.STATUS_OK); + Unsafe.getUnsafe().putLong(ptr + 1, seq); + Unsafe.getUnsafe().putShort(ptr + 9, (short) 1); + Unsafe.getUnsafe().putShort(ptr + 11, (short) name.length); + for (int i = 0; i < name.length; i++) { + Unsafe.getUnsafe().putByte(ptr + 13 + i, name[i]); + } + Unsafe.getUnsafe().putLong(ptr + 13 + name.length, 1L); + loop.deliverResponseForTest(ptr, size); + } finally { + Unsafe.free(ptr, size, MemoryTag.NATIVE_DEFAULT); + } + } + + private static void deliverRefusal(CursorWebSocketSendLoop loop, long seq) { + byte[] message = REFUSAL.getBytes(StandardCharsets.UTF_8); + int size = 1 + 8 + 2 + message.length; + long ptr = Unsafe.malloc(size, MemoryTag.NATIVE_DEFAULT); + try { + Unsafe.getUnsafe().putByte(ptr, WebSocketResponse.STATUS_TRANSACTION_TOO_LARGE); + Unsafe.getUnsafe().putLong(ptr + 1, seq); + Unsafe.getUnsafe().putShort(ptr + 9, (short) message.length); + for (int i = 0; i < message.length; i++) { + Unsafe.getUnsafe().putByte(ptr + 11 + i, message[i]); + } + loop.deliverResponseForTest(ptr, size); + } finally { + Unsafe.free(ptr, size, MemoryTag.NATIVE_DEFAULT); + } + } + + // A loop the test drives by hand, without starting its I/O thread: it sends to + // client, and the test delivers the server's responses. A reconnect connects a new + // RecordingClient, which it adds to next; with next null, it fails the test. + private static CursorWebSocketSendLoop newManualLoop( + CursorSendEngine engine, + RecordingClient client, + List next, + int durableAckTiers + ) { + return new CursorWebSocketSendLoop( + client, engine, 0L, + () -> { + Assert.assertNotNull("no reconnect expected", next); + RecordingClient reconnected = new RecordingClient(); + next.add(reconnected); + return reconnected; + }, + 0L, 1L, durableAckTiers, 0L); + } + + private static byte strictFlags(boolean isDeferred) { + return (byte) (QwpConstants.FLAG_STRICT | (isDeferred ? QwpConstants.FLAG_DEFER_COMMIT : 0)); + } + // The frame appendAhead writes is the only commit-bearing frame ahead of the rolled-back // transaction, and the server holds it unprocessed, or in durable mode holds back its // durable ack. The loop must not recycle until that ack arrives. @@ -567,9 +1089,11 @@ private static final class ModelClient extends TestWebSocketClient { volatile int flushedFrames; volatile int flushes; volatile boolean isHoldingAcks; + volatile boolean isServerClosing; volatile int polls; private long durableReported; private long nextSeq; + private long pendingErrorSeq = -1L; private long pendingOkSeq = -1L; private long pendingOkSeqTxn; @@ -607,6 +1131,11 @@ public boolean isServerRollbackEnabled() { return isRollbackConfirmed; } + // The server goes away, as on a restart: the next poll delivers its close. + void closeFromServer() { + isServerClosing = true; + } + synchronized void releaseAcks() { isHoldingAcks = false; } @@ -618,22 +1147,37 @@ public void sendPing() { @Override public synchronized boolean tryReceiveFrame(WebSocketFrameHandler handler) { polls++; + if (isServerClosing) { + isServerClosing = false; + handler.onClose(WebSocketCloseCode.GOING_AWAY, "server restarts"); + return true; + } // Durable mode: the server processes and OKs at once and holds back the // durable ack. Otherwise holding back the acks means not processing at all. if (isDurable || !isHoldingAcks) { for (Frame frame; (frame = inFlight.pollFirst()) != null; ) { long seq = nextSeq++; - if (server.process(connection, isRollbackConfirmed, frame)) { + int outcome = server.process(connection, isRollbackConfirmed, frame); + if (outcome == ServerModel.ACK) { pendingOkSeq = seq; pendingOkSeqTxn = frame.kind == 'R' ? 0 : server.seqTxn(); + } else if (outcome == ServerModel.REFUSE) { + pendingErrorSeq = seq; } } } + // As the QuestDB server: the acks of the frames ahead of a refused frame go + // out before the refusal. if (pendingOkSeq >= 0) { sendOk(handler, pendingOkSeq, isDurable && pendingOkSeqTxn > 0 ? pendingOkSeqTxn : 0); pendingOkSeq = -1L; return true; } + if (pendingErrorSeq >= 0) { + sendRefusal(handler, pendingErrorSeq); + pendingErrorSeq = -1L; + return true; + } if (isDurable && !isHoldingAcks && server.seqTxn() > durableReported) { durableReported = server.seqTxn(); sendDurableAck(handler, durableReported); @@ -656,6 +1200,24 @@ private static void sendDurableAck(WebSocketFrameHandler handler, long seqTxn) { } } + // STATUS_TRANSACTION_TOO_LARGE: status, the refused frame's wire sequence, the message. + private static void sendRefusal(WebSocketFrameHandler handler, long seq) { + byte[] message = REFUSAL.getBytes(StandardCharsets.UTF_8); + int size = 1 + 8 + 2 + message.length; + long ptr = Unsafe.malloc(size, MemoryTag.NATIVE_DEFAULT); + try { + Unsafe.getUnsafe().putByte(ptr, WebSocketResponse.STATUS_TRANSACTION_TOO_LARGE); + Unsafe.getUnsafe().putLong(ptr + 1, seq); + Unsafe.getUnsafe().putShort(ptr + 9, (short) message.length); + for (int i = 0; i < message.length; i++) { + Unsafe.getUnsafe().putByte(ptr + 11 + i, message[i]); + } + handler.onBinaryMessage(ptr, size); + } finally { + Unsafe.free(ptr, size, MemoryTag.NATIVE_DEFAULT); + } + } + // STATUS_OK: status, cumulative wire sequence, then the table entries -- one for // a commit in durable mode, so the OK waits for the durable ack covering it. private static void sendOk(WebSocketFrameHandler handler, long seq, long seqTxn) { @@ -694,16 +1256,97 @@ protected void setupIoWait() { } } + /** + * A connection the test drives by hand: it logs what the loop writes to it, and the + * test delivers the server's responses through deliverResponseForTest. It confirms + * rollback, so the loop sends the rollback frame like any other. + */ + private static final class RecordingClient extends TestWebSocketClient { + final List log = new ArrayList<>(); + + RecordingClient() { + super(DefaultHttpClientConfiguration.INSTANCE, PlainSocketFactory.INSTANCE); + } + + @Override + public void batchAppendBinary(long dataPtr, int length) { + byte flags = Unsafe.getUnsafe().getByte(dataPtr + QwpConstants.HEADER_OFFSET_FLAGS); + if (length == QwpConstants.HEADER_SIZE && flags == QwpConstants.ROLLBACK_FRAME_FLAGS) { + log.add("R"); + return; + } + String kind = (flags & QwpConstants.FLAG_DEFER_COMMIT) != 0 ? "D" : "C"; + if ((flags & QwpConstants.FLAG_DELTA_SYMBOL_DICT) != 0) { + long p = dataPtr + QwpConstants.HEADER_SIZE; + log.add(kind + " delta " + Unsafe.getUnsafe().getByte(p) + ":" + symbols(p + 2, Unsafe.getUnsafe().getByte(p + 1))); + } else { + log.add(kind + Unsafe.getUnsafe().getInt(dataPtr + QwpConstants.HEADER_SIZE)); + } + } + + @Override + public void batchFlush() { + } + + @Override + public int getServerMaxBatchSize() { + return 16_384; + } + + @Override + public int getServerQwpVersion() { + return 1; + } + + @Override + public boolean isServerRollbackEnabled() { + return true; + } + + // The dictionary catch-up: a header and the delta's start and count, then the + // symbols, in two parts. + @Override + public void sendBinary(long firstPtr, int firstLength, long secondPtr, int secondLength) { + long p = firstPtr + QwpConstants.HEADER_SIZE; + log.add("catch-up " + Unsafe.getUnsafe().getByte(p) + ":" + symbols(secondPtr, Unsafe.getUnsafe().getByte(p + 1))); + } + + @Override + protected void ioWait(int timeout, int op) { + } + + @Override + protected void setupIoWait() { + } + + // Symbols of one ASCII char each, every one after its length byte. + private static String symbols(long p, int count) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < count; i++, p += 2) { + sb.append(' ').append((char) Unsafe.getUnsafe().getByte(p + 1)); + } + return sb.toString(); + } + } + // A frame as the server sees it: D (deferred), C (commit), R (the rollback frame), or // X, a payload that is not a QWP message, labelled with its size. A frame's id - // follows its header; a bare header has id 0. + // follows its header; a bare header has id 0. A strict frame's rows follow its id. private static final class Frame { + final boolean isStrict; final char kind; final String label; + final int rows; Frame(char kind, String label) { + this(kind, label, false, 0); + } + + Frame(char kind, String label, boolean isStrict, int rows) { this.kind = kind; this.label = label; + this.isStrict = isStrict; + this.rows = rows; } static Frame read(long ptr, int length) { @@ -716,7 +1359,10 @@ static Frame read(long ptr, int length) { } char kind = (flags & QwpConstants.FLAG_DEFER_COMMIT) != 0 ? 'D' : 'C'; int id = length > QwpConstants.HEADER_SIZE ? Unsafe.getUnsafe().getInt(ptr + QwpConstants.HEADER_SIZE) : 0; - return new Frame(kind, kind + Integer.toString(id)); + boolean isStrict = (flags & QwpConstants.FLAG_STRICT) != 0; + int rows = isStrict && length >= QwpConstants.HEADER_SIZE + 8 + ? Unsafe.getUnsafe().getInt(ptr + QwpConstants.HEADER_SIZE + 4) : 0; + return new Frame(kind, kind + Integer.toString(id), isStrict, rows); } @Override @@ -733,49 +1379,86 @@ public String toString() { * frame as an empty deferred frame, so the group stays open and the next commit on * the connection commits it. A closed connection leaves its group uncommitted. A * foreign payload is acked like a commit, so the loop's wait for it ends. + *

    + * With a cap, a strict frame whose rows would take its connection's group to the + * cap is refused with STATUS_TRANSACTION_TOO_LARGE instead: the group is discarded, + * and no later frame of the connection is processed, nor acked. */ private static final class ServerModel { + static final int ACK = 1; + static final int NONE = 0; + static final int REFUSE = 2; + private final List broken = new ArrayList<>(); private final List committed = new ArrayList<>(); + private final List groupRows = new ArrayList<>(); private final List> groups = new ArrayList<>(); private final List received = new ArrayList<>(); + private final List refused = new ArrayList<>(); + private int cap; private int rollbacksReceived; private int rollbacksToServerWithoutRollback; private long seqTxn; synchronized void close(int connection) { - group(connection).clear(); + discardGroup(connection); } synchronized List committed() { return new ArrayList<>(committed); } - // Whether the server acks the frame. - synchronized boolean process(int connection, boolean isRollbackConfirmed, Frame frame) { + // Whether the server acks the frame, refuses it, or neither. + synchronized int process(int connection, boolean isRollbackConfirmed, Frame frame) { received.add(connection + ":" + frame); List group = group(connection); + if (broken.contains(connection)) { + return NONE; + } + if (frame.isStrict && cap > 0) { + int rows = groupRows.get(connection) + frame.rows; + if (rows >= cap) { + refused.add(connection + ":" + frame); + discardGroup(connection); + broken.add(connection); + return REFUSE; + } + groupRows.set(connection, rows); + } switch (frame.kind) { case 'C': case 'X': committed.addAll(group); committed.add(frame.label); - group.clear(); + discardGroup(connection); seqTxn++; - return true; + return ACK; case 'R': rollbacksReceived++; if (isRollbackConfirmed) { - group.clear(); - return true; + discardGroup(connection); + return ACK; } rollbacksToServerWithoutRollback++; - return false; + return NONE; default: group.add(frame.label); - return false; + return NONE; } } + synchronized List refused() { + return new ArrayList<>(refused); + } + + synchronized void setCap(int cap) { + this.cap = cap; + } + + private void discardGroup(int connection) { + group(connection).clear(); + groupRows.set(connection, 0); + } + synchronized List received() { return new ArrayList<>(received); } @@ -795,6 +1478,7 @@ synchronized long seqTxn() { private List group(int connection) { while (groups.size() <= connection) { groups.add(new ArrayList<>()); + groupRows.add(0); } return groups.get(connection); } From a46fcf20a49b9f2e849308d967df3b6d128fb147 Mon Sep 17 00:00:00 2001 From: bluestreak Date: Sun, 29 Nov 2026 21:15:02 +0000 Subject: [PATCH 15/20] Refuse servers without X-QWP-Max-Uncommitted-Rows in strict mode Servers that predate X-QWP-Max-Uncommitted-Rows also predate FLAG_STRICT: they silently ignore bit 0x40 and commit a table's deferred rows on their own once their qwp.max.uncommitted.rows is reached. With a lowered server cap, a strict transaction accepted rows under the 1,000,000 fallback, landed in parts, and rollback()/close() left already-committed rows behind with zero errors. Reuse the existing durable-ack capability-mismatch path: - Extract QwpCapabilityMismatchException (HttpClientException subclass) as the shared base for QwpDurableAckMismatchException and the new QwpStrictTransactionMismatchException. - Pass transactional/strictTransactional into connectWithCredentialSupplier before ensureConnected() and reject servers whose 101 response omits X-QWP-Max-Uncommitted-Rows in buildAndConnect() (plus late calls to setStrictTransactional(true) after connecting to an older server). - Route QwpCapabilityMismatchException through QwpConnectionHealthTracker, CursorWebSocketSendLoop (fail-fast sync connect, startup terminal on async connect before any frame is sent, Invariant B retry on post-connect failover), and BackgroundDrainer (bounded settle budget without firing durable-ack listener callbacks for strict mismatches). - Document the requirement in Sender.strictTransactional, TransactionTooLargeException, and README.md. - Add regression tests covering sync/off rejection, async startup terminal with zero frames sent, mixed-cluster [old, new] skipping, new->old->new failover ride-out, transaction=on compatibility, and BackgroundDrainer. --- README.md | 4 +- .../main/java/io/questdb/client/Sender.java | 20 +- .../cutlass/http/client/WebSocketClient.java | 3 +- .../QwpCapabilityMismatchException.java | 74 ++++++ .../client/QwpConnectionHealthTracker.java | 2 +- .../QwpDurableAckMismatchException.java | 23 +- ...QwpStrictTransactionMismatchException.java | 56 ++++ .../qwp/client/QwpWebSocketSender.java | 89 ++++++- .../client/TransactionTooLargeException.java | 4 +- .../client/sf/cursor/BackgroundDrainer.java | 34 +-- .../sf/cursor/CursorWebSocketSendLoop.java | 38 +-- .../qwp/client/QwpLargeTransactionTest.java | 248 ++++++++++++++++-- .../BackgroundDrainerDurableAckRetryTest.java | 22 ++ ...SendLoopForegroundReconnectPolicyTest.java | 14 + 14 files changed, 547 insertions(+), 84 deletions(-) create mode 100644 core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpCapabilityMismatchException.java create mode 100644 core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpStrictTransactionMismatchException.java diff --git a/README.md b/README.md index f0f6547ae..e8e47080b 100644 --- a/README.md +++ b/README.md @@ -737,7 +737,9 @@ it, and every pooled sender may hold one at once, so a strict transaction that s only its sender's share: `sf_max_total_bytes / sender_pool_max`, one segment less with `sf_dir`. A larger one fails with `TransactionTooLargeException`. So does one that holds more rows of a table than the server's `qwp.max.uncommitted.rows` when the sender learns that limit only after accepting them, as before its first connection: -the server refuses such a transaction rather than commit it in parts, and `rollback()` discards it. +the server refuses such a transaction rather than commit it in parts, and `rollback()` discards it. Strict mode +requires a server that advertises `X-QWP-Max-Uncommitted-Rows`; against older servers the sender fails at connect +with `QwpStrictTransactionMismatchException` rather than commit in parts (use `transaction=on` there). `sf_durability=periodic` checkpoints mmap-published data in the background; `sf_sync_interval_millis` defaults to `5000` in that mode. The interval is a target cadence: JVM scheduling and storage-sync latency add to the actual loss window. Use `request_durable_ack=on` when end-to-end server durability is also required. See the diff --git a/core/src/main/java/io/questdb/client/Sender.java b/core/src/main/java/io/questdb/client/Sender.java index 539ba8f99..9fcf64a05 100644 --- a/core/src/main/java/io/questdb/client/Sender.java +++ b/core/src/main/java/io/questdb/client/Sender.java @@ -2850,6 +2850,12 @@ private LineSenderBuilder requestDurableAckTiers(int tiers) { * divided by {@code sender_pool_max}, less one segment with {@code sf_dir}. * A sender with no auto-flush trigger (see {@link #disableAutoFlush()}) is * in this mode unless {@link #transactional(boolean)} selects the mode. + * Requires a server that advertises {@code X-QWP-Max-Uncommitted-Rows} (and + * honours {@code FLAG_STRICT}); against an older server the sender fails at + * connect with + * {@link io.questdb.client.cutlass.qwp.client.QwpStrictTransactionMismatchException} + * rather than risk a silent partial commit. Use {@link #transactional(boolean) + * transaction=on} against older servers. * WebSocket transport only. * * @param enabled true to enable strict transactional mode; false leaves @@ -3865,6 +3871,10 @@ private QwpWebSocketSender buildWebSocket(HttpTokenProvider tokenProvider) { for (int i = 0, n = hosts.size(); i < n; i++) { wsEndpoints.add(new QwpWebSocketSender.Endpoint(hosts.getQuick(i), ports.getQuick(i))); } + // With no auto-flush trigger only flush() commits: a strict transaction of + // any size, unless transaction= chose the mode. + boolean effectiveStrict = strictTransactional || (!transactionModeSet && !hasAutoFlushTrigger()); + boolean effectiveTransactional = transactional || effectiveStrict; // The recovery seed inside connect() is the authority on whether a recovered // slot can be replayed: it rebuilds the dictionary from its intact prefix and // then from the surviving frames' own delta sections, and throws @@ -3900,7 +3910,9 @@ private QwpWebSocketSender buildWebSocket(HttpTokenProvider tokenProvider) { symbolDictReset, actualSymbolDictResetThreshold, actualSymbolDictResetMaxWaitMillis, - keepaliveIntervalMillis + keepaliveIntervalMillis, + effectiveTransactional, + effectiveStrict ); } catch (UnreplayableSlotException e) { // The one failure build() recovers from. The slot's frames reference ids @@ -3952,12 +3964,6 @@ private QwpWebSocketSender buildWebSocket(HttpTokenProvider tokenProvider) { // closing the engine alone would leak the I/O thread, // dispatcher daemon, drainer pool, microbatch buffers and // WebSocketClient inside the abandoned `connected`. - connected.setTransactional(transactional); - // With no auto-flush trigger only flush() commits: a strict transaction of - // any size, unless transaction= chose the mode. - if (strictTransactional || (!transactionModeSet && !hasAutoFlushTrigger())) { - connected.setStrictTransactional(true); - } try { final String rebuildSfDir = sfDir; final String rebuildSenderId = senderId; diff --git a/core/src/main/java/io/questdb/client/cutlass/http/client/WebSocketClient.java b/core/src/main/java/io/questdb/client/cutlass/http/client/WebSocketClient.java index ab479d602..4eaf9a7a9 100644 --- a/core/src/main/java/io/questdb/client/cutlass/http/client/WebSocketClient.java +++ b/core/src/main/java/io/questdb/client/cutlass/http/client/WebSocketClient.java @@ -1621,7 +1621,8 @@ private void validateUpgradeResponse(int headerEnd) { serverMaxBatchSize = extractMaxBatchSize(response); // Extract X-QWP-Max-Uncommitted-Rows (optional). Older servers omit it; - // a strict transaction then assumes the server's default. + // strict transactional senders reject such servers at connect rather than + // risk silent partial commits, while non-strict senders ignore the cap. serverMaxUncommittedRows = extractMaxUncommittedRows(response); // Extract the X-QWP-Rollback confirmation (optional). Only a client that diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpCapabilityMismatchException.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpCapabilityMismatchException.java new file mode 100644 index 000000000..e7df47f09 --- /dev/null +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpCapabilityMismatchException.java @@ -0,0 +1,74 @@ +/*+***************************************************************************** + * ___ _ ____ ____ + * / _ \ _ _ ___ ___| |_| _ \| __ ) + * | | | | | | |/ _ \/ __| __| | | | _ \ + * | |_| | |_| | __/\__ \ |_| |_| | |_) | + * \__\_\\__,_|\___||___/\__|____/|____/ + * + * 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.cutlass.qwp.client; + +import io.questdb.client.cutlass.http.client.HttpClientException; + +/** + * The server completed the WebSocket upgrade (HTTP 101) but did not confirm a + * required client capability (such as durable ack or strict transactions). + *

    + * Extends {@link HttpClientException} directly (not + * {@link io.questdb.client.cutlass.http.client.WebSocketUpgradeException}) so a + * genuine capability gap stays distinct from a transient 421 role reject across + * mixed-endpoint sweeps. Sync and off initial connects fail fast; an async + * initial connect latches a terminal error before sending any frame; after a + * sender has connected once, foreground reconnects ride out a temporary + * capability gap under store-and-forward Invariant B (for example during a + * rolling upgrade); orphan drainers apply a bounded settle budget before + * quarantining the slot. + */ +public abstract class QwpCapabilityMismatchException extends HttpClientException { + private final String host; + private final int port; + + protected QwpCapabilityMismatchException(String host, int port, String message) { + super(message); + this.host = host; + this.port = port; + } + + /** + * Short human-readable name of the missing server capability (for example + * {@code "durable-ack"} or {@code "strict-transaction"}), used in log and + * sentinel messages. + */ + public abstract String getCapabilityName(); + + /** + * Short error prefix (for example {@code "durable-ack-mismatch"} or + * {@code "strict-transaction-mismatch"}), used in {@code SenderError} + * messages and logs. + */ + public abstract String getErrorPrefix(); + + public String getHost() { + return host; + } + + public int getPort() { + return port; + } +} diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpConnectionHealthTracker.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpConnectionHealthTracker.java index 97b991bd5..b2f27ec8f 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpConnectionHealthTracker.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpConnectionHealthTracker.java @@ -75,7 +75,7 @@ public static ConnectionHealth.Failure classify(Throwable failure, long nowMilli ? failure(ConnectionHealth.FailureClass.ROLE_REJECTED, 0, t, nowMillis) : failure(ConnectionHealth.FailureClass.OTHER, Math.max(0, e.getStatusCode()), t, nowMillis); } - if (t instanceof QwpVersionMismatchException || t instanceof QwpDurableAckMismatchException) { + if (t instanceof QwpVersionMismatchException || t instanceof QwpCapabilityMismatchException) { return failure(ConnectionHealth.FailureClass.OTHER, 0, t, nowMillis); } } diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpDurableAckMismatchException.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpDurableAckMismatchException.java index e8a58e5df..2f1b3f925 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpDurableAckMismatchException.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpDurableAckMismatchException.java @@ -24,7 +24,6 @@ package io.questdb.client.cutlass.qwp.client; -import io.questdb.client.cutlass.http.client.HttpClientException; import org.jetbrains.annotations.Nullable; /** @@ -42,9 +41,7 @@ * requested set and what the server echoed, or that it sent no header. * {@link #getRole()} is {@code null} for this denial. */ -public final class QwpDurableAckMismatchException extends HttpClientException { - private final String host; - private final int port; +public final class QwpDurableAckMismatchException extends QwpCapabilityMismatchException { private final String role; /** @@ -53,7 +50,7 @@ public final class QwpDurableAckMismatchException extends HttpClientException { * value, or {@code null} when the server sent no such header. */ public QwpDurableAckMismatchException(String host, int port, int requestedTiers, @Nullable String serverEcho) { - super("WebSocket upgrade failed: server does not support durable ack [host="); + super(host, port, "WebSocket upgrade failed: server does not support durable ack [host="); put(host).put(", port=").put(port) .put(", requested=").put(DurableAckTiers.configValue(requestedTiers)) .put(", echoed="); @@ -63,29 +60,27 @@ public QwpDurableAckMismatchException(String host, int port, int requestedTiers, put(""); } put(']'); - this.host = host; - this.port = port; this.role = null; } public QwpDurableAckMismatchException(String host, int port, String role) { - super("WebSocket upgrade failed: server does not support durable ack [host="); + super(host, port, "WebSocket upgrade failed: server does not support durable ack [host="); put(host).put(", port=").put(port); if (role != null) { put(", role=").put(role); } put(']'); - this.host = host; - this.port = port; this.role = role; } - public String getHost() { - return host; + @Override + public String getCapabilityName() { + return "durable-ack"; } - public int getPort() { - return port; + @Override + public String getErrorPrefix() { + return "durable-ack-mismatch"; } /** diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpStrictTransactionMismatchException.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpStrictTransactionMismatchException.java new file mode 100644 index 000000000..e4a885bda --- /dev/null +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpStrictTransactionMismatchException.java @@ -0,0 +1,56 @@ +/*+***************************************************************************** + * ___ _ ____ ____ + * / _ \ _ _ ___ ___| |_| _ \| __ ) + * | | | | | | |/ _ \/ __| __| | | | _ \ + * | |_| | |_| | __/\__ \ |_| |_| | |_) | + * \__\_\\__,_|\___||___/\__|____/|____/ + * + * 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.cutlass.qwp.client; + +/** + * The sender requires strict transactional mode ({@code transaction=strict}, or a + * WebSocket sender with no auto-flush trigger) but the server completed the + * WebSocket upgrade without advertising {@code X-QWP-Max-Uncommitted-Rows}. + *

    + * Servers that omit {@code X-QWP-Max-Uncommitted-Rows} also predate + * {@code FLAG_STRICT}: they silently ignore the flag and commit a table's + * deferred rows on their own once their {@code qwp.max.uncommitted.rows} is + * reached, which would split the transaction and leave rolled-back rows + * committed. The sender refuses such a server rather than substitute a weaker + * guarantee; upgrade the server or use {@code transaction=on}. + */ +public final class QwpStrictTransactionMismatchException extends QwpCapabilityMismatchException { + + public QwpStrictTransactionMismatchException(String host, int port) { + super(host, port, "WebSocket upgrade failed: server does not support strict transactions [host="); + put(host).put(", port=").put(port) + .put(", missing=X-QWP-Max-Uncommitted-Rows]; upgrade the server or use transaction=on"); + } + + @Override + public String getCapabilityName() { + return "strict-transaction"; + } + + @Override + public String getErrorPrefix() { + return "strict-transaction-mismatch"; + } +} diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java index 1e09bb5ae..113fde1d8 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java @@ -724,6 +724,11 @@ public class QwpWebSocketSender implements Sender { // commits them on its own (X-QWP-Max-Uncommitted-Rows), 0 when not advertised. // Captured on each FOREGROUND handshake, like serverMaxBatchSize. private volatile long serverMaxUncommittedRows; + // True when the server of the last FOREGROUND handshake did not advertise + // X-QWP-Max-Uncommitted-Rows (and therefore predates FLAG_STRICT); false + // before the first handshake, while the sender cannot know. Guards late + // calls to setStrictTransactional(true) on an already-connected sender. + private volatile boolean isServerStrictUnsupported; // True when the server of the last FOREGROUND handshake did not confirm // X-QWP-Rollback; false before the first handshake, while the sender cannot know. // Only reset() of a transaction=on transaction reads it: on a server known to lack @@ -737,8 +742,10 @@ public class QwpWebSocketSender implements Sender { private volatile boolean serverRollbackEnabled; // Strict transactional mode (transaction=strict, or a sender with no auto-flush // trigger): implies transactional, never lets an open transaction commit in - // parts, and close() discards instead of committing. See setStrictTransactional. - private boolean strictTransactional; + // parts, and close() discards instead of committing. Volatile because + // buildAndConnect reads it on the I/O thread during reconnects. See + // setStrictTransactional. + private volatile boolean strictTransactional; // Strict mode only: set when the client buffer cannot take another deferred // frame of the open transaction and still commit it. Rejects further rows // until flush() or rollback() ends the transaction. The rows accepted before @@ -1353,6 +1360,57 @@ public static QwpWebSocketSender connectWithCredentialSupplier( int symbolDictResetThresholdSymbols, long symbolDictResetMaxWaitMillis, long keepaliveIntervalMillis + ) { + return connectWithCredentialSupplier( + endpoints, tlsConfig, autoFlushRows, autoFlushBytes, autoFlushIntervalNanos, + authorizationHeaderSupplier, durableAckTiers, cursorEngine, closeFlushTimeoutMillis, + reconnectMaxDurationMillis, reconnectInitialBackoffMillis, reconnectMaxBackoffMillis, + initialConnectMode, errorHandler, errorInboxCapacity, durableAckKeepaliveIntervalMillis, + authTimeoutMs, connectTimeoutMs, connectionListener, connectionListenerInboxCapacity, + maxFrameRejections, poisonMinEscalationWindowMillis, catchUpCapGapMinEscalationWindowMillis, + symbolDictResetEnabled, symbolDictResetThresholdSymbols, symbolDictResetMaxWaitMillis, + keepaliveIntervalMillis, false, false + ); + } + + /** + * Master connect entry point — also accepts the transactional mode flags + * ({@code transactional}, {@code strictTransactional}) before the initial + * handshake runs so strict mode can reject servers that do not advertise + * {@code X-QWP-Max-Uncommitted-Rows} at connect time. + * + * @throws LineSenderException if either recycle setting is out of range + */ + public static QwpWebSocketSender connectWithCredentialSupplier( + List endpoints, + ClientTlsConfiguration tlsConfig, + int autoFlushRows, + int autoFlushBytes, + long autoFlushIntervalNanos, + Supplier authorizationHeaderSupplier, + int durableAckTiers, + CursorSendEngine cursorEngine, + long closeFlushTimeoutMillis, + long reconnectMaxDurationMillis, + long reconnectInitialBackoffMillis, + long reconnectMaxBackoffMillis, + Sender.InitialConnectMode initialConnectMode, + SenderErrorHandler errorHandler, + int errorInboxCapacity, + long durableAckKeepaliveIntervalMillis, + long authTimeoutMs, + int connectTimeoutMs, + SenderConnectionListener connectionListener, + int connectionListenerInboxCapacity, + int maxFrameRejections, + long poisonMinEscalationWindowMillis, + long catchUpCapGapMinEscalationWindowMillis, + boolean symbolDictResetEnabled, + int symbolDictResetThresholdSymbols, + long symbolDictResetMaxWaitMillis, + long keepaliveIntervalMillis, + boolean transactional, + boolean strictTransactional ) { if (symbolDictResetThresholdSymbols <= 0 || symbolDictResetThresholdSymbols > QwpConstants.MAX_SYMBOL_DICTIONARY_SIZE / 2) { @@ -1391,6 +1449,10 @@ public static QwpWebSocketSender connectWithCredentialSupplier( sender.initialConnectMode = initialConnectMode == null ? Sender.InitialConnectMode.OFF : initialConnectMode; + sender.setTransactional(transactional); + if (strictTransactional) { + sender.setStrictTransactional(true); + } if (errorHandler != null) { sender.setErrorHandler(errorHandler); } @@ -3886,6 +3948,11 @@ public void setRecycleDeferredCloseMaxWaitMillisForTesting(long millis) { * transactional mode; disabling it leaves transactional mode on. */ public void setStrictTransactional(boolean strict) { + if (strict && isServerStrictUnsupported) { + int idx = currentEndpointIdx; + Endpoint ep = idx >= 0 && idx < endpoints.size() ? endpoints.get(idx) : endpoints.get(0); + throw new QwpStrictTransactionMismatchException(ep.host, ep.port); + } this.strictTransactional = strict; // The server refuses a strict frame that would reach its limit, rather than // commit the transaction in parts. @@ -4266,6 +4333,7 @@ public void applyServerBatchSizeLimit(int advertisedMaxBatchSize) { @TestOnly public void applyServerTransactionLimits(long maxUncommittedRows, boolean rollbackEnabled) { serverMaxUncommittedRows = maxUncommittedRows; + isServerStrictUnsupported = maxUncommittedRows <= 0; serverRollbackEnabled = rollbackEnabled; isServerRollbackDeclined = !rollbackEnabled; } @@ -4761,6 +4829,23 @@ private WebSocketClient connectWalk(ReconnectSupplier ctx, CursorWebSocketSendLo } continue; } + if (strictTransactional && newClient.getServerMaxUncommittedRows() <= 0) { + newClient.close(); + hostTracker.recordRoleReject(idx, false, !background); + QwpStrictTransactionMismatchException strictErr = + new QwpStrictTransactionMismatchException(ep.host, ep.port); + if (terminalUpgradeError == null) { + terminalUpgradeError = strictErr; + } + lastError = strictErr; + if (!background) { + dispatchConnectionEvent( + SenderConnectionEvent.Kind.ENDPOINT_ATTEMPT_FAILED, + ep.host, ep.port, null, SenderConnectionEvent.NO_PORT, + attemptNumber, roundSeq, strictErr); + } + continue; + } hostTracker.recordSuccess(idx, !background); ctx.previousIdx = idx; if (background) { diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java index eed6fd7bd..70ff58916 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java @@ -52,7 +52,9 @@ * with a lower setting. Then the transaction as a whole cannot commit as one, and the * server refuses it rather than commit it in parts: every row, {@code flush()} and * {@code drain()} of the transaction throws this exception until {@code rollback()}, - * {@code reset()} or {@code close()} discards the transaction. + * {@code reset()} or {@code close()} discards the transaction. Servers that predate + * {@code X-QWP-Max-Uncommitted-Rows} and {@code FLAG_STRICT} are refused at connect + * with {@link QwpStrictTransactionMismatchException} instead. */ public class TransactionTooLargeException extends LineSenderException { diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/BackgroundDrainer.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/BackgroundDrainer.java index f1e574c03..c593e6bd6 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/BackgroundDrainer.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/BackgroundDrainer.java @@ -30,6 +30,7 @@ import io.questdb.client.cutlass.http.client.WebSocketUpgradeException; import io.questdb.client.cutlass.qwp.client.DurableAckTiers; import io.questdb.client.cutlass.qwp.client.QwpAuthFailedException; +import io.questdb.client.cutlass.qwp.client.QwpCapabilityMismatchException; import io.questdb.client.cutlass.qwp.client.QwpCredentialUnavailableException; import io.questdb.client.cutlass.qwp.client.QwpDurableAckMismatchException; import io.questdb.client.cutlass.qwp.client.QwpIngressRoleRejectedException; @@ -590,16 +591,17 @@ public WebSocketClient connectWithDurableAckRetry() { slotPath, roleRejectAttempts); lastReplicaWarnNanos = nowWarn; } - } catch (QwpDurableAckMismatchException e) { - // Genuine cluster-wide durable-ack CAPABILITY gap: a server - // upgraded but does not advertise durable ack. Unlike a role - // reject this will not clear by waiting for a promotion, so it - // stays terminal for the drainer -- give the cluster a bounded - // settle budget (rolling upgrade), then quarantine the slot. + } catch (QwpCapabilityMismatchException e) { + // Genuine cluster-wide CAPABILITY gap (durable-ack or strict + // transactions): a server upgraded but does not confirm the + // required capability. Unlike a role reject this will not clear + // by waiting for a promotion, so it stays terminal for the + // drainer -- give the cluster a bounded settle budget (rolling + // upgrade), then quarantine the slot. capabilityGapAttempts++; // Symmetry with the arm above, which restarts the capability-gap episode because an auth // rejection says nothing about a node's batch cap: a capability gap says nothing about the - // credential either. We reached a node and it answered - it simply cannot do durable ack - + // credential either. We reached a node and it answered - it simply lacks the capability - // so this is not time the credential spent REJECTED, and charging it to the rotating-401 // dwell would let a rolling upgrade satisfy that floor for free. The settle budget below can // legitimately run for the whole reconnect budget, which is exactly the span the dwell is @@ -619,9 +621,9 @@ public WebSocketClient connectWithDurableAckRetry() { || capabilityGapElapsedNanos >= reconnectBudgetNanos; BackgroundDrainerListener l = listener; if (exhausted) { - LOG.error("drainer giving up on slot {} after {} durable-ack-mismatch attempts ({}ms): {}", - slotPath, capabilityGapAttempts, elapsedMs, e.getMessage()); - if (l != null) { + LOG.error("drainer giving up on slot {} after {} {} attempts ({}ms): {}", + slotPath, capabilityGapAttempts, e.getErrorPrefix(), elapsedMs, e.getMessage()); + if (l != null && e instanceof QwpDurableAckMismatchException) { try { l.onDurableAckPersistentFailure(slotPath, capabilityGapAttempts, elapsedMs); } catch (Throwable cb) { @@ -630,7 +632,7 @@ public WebSocketClient connectWithDurableAckRetry() { } } lastErrorMessage = e.getMessage(); - String reason = "durable-ack persistently unavailable after " + String reason = e.getCapabilityName() + " persistently unavailable after " + capabilityGapAttempts + " attempts: " + e.getMessage(); OrphanScanner.markFailed(slotPath, reason); dispatchDataLoss(reason); @@ -638,7 +640,7 @@ public WebSocketClient connectWithDurableAckRetry() { return null; } boundedByBudget = true; - if (l != null) { + if (l != null && e instanceof QwpDurableAckMismatchException) { try { l.onDurableAckUnavailable(slotPath, capabilityGapAttempts); } catch (Throwable cb) { @@ -646,8 +648,8 @@ public WebSocketClient connectWithDurableAckRetry() { cb.getMessage()); } } - LOG.warn("drainer slot {} attempt {}: durable-ack unavailable, retrying after backoff", - slotPath, capabilityGapAttempts); + LOG.warn("drainer slot {} attempt {}: {} unavailable, retrying after backoff", + slotPath, capabilityGapAttempts, e.getCapabilityName()); } catch (Throwable t) { if (t instanceof Error) { // java.lang.Error (OOM, LinkageError, StackOverflowError) @@ -1218,9 +1220,9 @@ public void run() { + "re-entering the rotating-401 ride-out", slotPath, t.getMessage()); } else { - LOG.warn("drainer slot {}: durable-ack capability gap " + LOG.warn("drainer slot {}: {} capability gap " + "mid-drain ({}), re-entering settle budget", - slotPath, t.getMessage()); + slotPath, loop.capabilityGapTerminal().getCapabilityName(), t.getMessage()); } try { loop.close(); diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java index ace289bd1..d24fc682a 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java @@ -34,8 +34,8 @@ import io.questdb.client.cutlass.qwp.client.DurableAckTiers; import io.questdb.client.cutlass.qwp.client.NativeBufferWriter; import io.questdb.client.cutlass.qwp.client.QwpAuthFailedException; +import io.questdb.client.cutlass.qwp.client.QwpCapabilityMismatchException; import io.questdb.client.cutlass.qwp.client.QwpCredentialUnavailableException; -import io.questdb.client.cutlass.qwp.client.QwpDurableAckMismatchException; import io.questdb.client.cutlass.qwp.client.QwpIngressRoleRejectedException; import io.questdb.client.cutlass.qwp.client.QwpRoleMismatchException; import io.questdb.client.cutlass.qwp.client.QwpVersionMismatchException; @@ -532,17 +532,17 @@ public final class CursorWebSocketSendLoop implements QuietCloseable { // capability-gap recycle rests on. A CONSTANT credential never sets it (it stays fatal), and // foreground reconnects never set it either. Write-once alongside terminalError. private volatile QwpAuthFailedException authTerminal; - // Typed marker for a durable-ack CAPABILITY-GAP terminal: set (before the + // Typed marker for a server CAPABILITY-GAP terminal: set (before the // terminalError latch, so a checkError() caller that observes the latch is // guaranteed to observe this marker too) when a reconnect sweep threw - // QwpDurableAckMismatchException. The orphan drainer consults it to route - // a mid-drain capability gap into its budgeted settle-retry - // (BackgroundDrainer.connectWithDurableAckRetry) instead of quarantining - // the slot on the first sweep. Foreground reconnects never set this marker; - // they keep retrying after a successful initial connection. Write-once alongside - // terminalError: the only writer runs on the I/O thread under the same - // first-writer-wins latch. - private volatile QwpDurableAckMismatchException capabilityGapTerminal; + // QwpCapabilityMismatchException (durable-ack or strict-transaction). The + // orphan drainer consults it to route a mid-drain capability gap into its + // budgeted settle-retry (BackgroundDrainer.connectWithDurableAckRetry) + // instead of quarantining the slot on the first sweep. Foreground reconnects + // never set this marker; they keep retrying after a successful initial + // connection. Write-once alongside terminalError: the only writer runs on + // the I/O thread under the same first-writer-wins latch. + private volatile QwpCapabilityMismatchException capabilityGapTerminal; // Failed-stop hand-off callback: set when an owner could not stop the I/O // thread and must defer worker-reachable cleanup until the thread exits. // Read strictly after shutdownLatch.countDown(); see delegateClose(). @@ -1181,7 +1181,7 @@ public static WebSocketClient connectWithRetry( } return c; } - } catch (QwpAuthFailedException | QwpDurableAckMismatchException + } catch (QwpAuthFailedException | QwpCapabilityMismatchException | WebSocketUpgradeException e) { // Terminal across all configured endpoints per sf-client.md sections // 8.1 (durable-ack mismatch) and 13.3 (auth). Version mismatch is @@ -1392,7 +1392,7 @@ QwpAuthFailedException authTerminal() { * terminal). Package-private on purpose -- the foreground sender must * not branch on it (spec'd loud-fail, sf-client.md section 8.1). */ - QwpDurableAckMismatchException capabilityGapTerminal() { + QwpCapabilityMismatchException capabilityGapTerminal() { return capabilityGapTerminal; } @@ -2286,12 +2286,12 @@ private void connectWalk(Throwable initial, String phase, long paceFirstAttemptM phase, attempts, e.getMessage()); lastLogNanos = now; } - } catch (QwpDurableAckMismatchException e) { + } catch (QwpCapabilityMismatchException e) { if (endpointPolicyFailureIsTerminal()) { // Orphans hand a capability gap back to BackgroundDrainer's // settle budget. - LOG.error("durable-ack mismatch during {} -- won't retry: {}", - phase, e.getMessage()); + LOG.error("{} during {} -- won't retry: {}", + e.getErrorPrefix(), phase, e.getMessage()); if (terminalError == null) { // Publish the marker before terminalError, which is the // volatile first-writer-wins latch observed by the owner. @@ -2303,7 +2303,7 @@ private void connectWalk(Throwable initial, String phase, long paceFirstAttemptM SenderError.Category.PROTOCOL_VIOLATION, SenderError.Policy.TERMINAL, SenderError.NO_STATUS_BYTE, - "durable-ack-mismatch: " + e.getMessage(), + e.getErrorPrefix() + ": " + e.getMessage(), SenderError.NO_MESSAGE_SEQUENCE, fromFsn, toFsn, @@ -2319,12 +2319,12 @@ private void connectWalk(Throwable initial, String phase, long paceFirstAttemptM lastReconnectError = e; dispatchRetriedEndpointPolicyFailure( SenderError.Category.PROTOCOL_VIOLATION, - "durable-ack-mismatch: " + e.getMessage()); + e.getErrorPrefix() + ": " + e.getMessage()); long now = System.nanoTime(); if (now - lastLogNanos >= RECONNECT_LOG_THROTTLE_NANOS) { - LOG.warn("{} attempt {}: foreground durable-ack capability is temporarily " + LOG.warn("{} attempt {}: foreground {} capability is temporarily " + "unavailable; retrying while store-and-forward owns the buffered data -- {}", - phase, attempts, e.getMessage()); + phase, attempts, e.getCapabilityName(), e.getMessage()); lastLogNanos = now; } } catch (QwpCredentialUnavailableException e) { diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index 4cf86870d..f21511784 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -28,12 +28,15 @@ import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; +import io.questdb.client.ConnectionHealth; import io.questdb.client.LineSenderServerException; import io.questdb.client.QuestDB; import io.questdb.client.Sender; import io.questdb.client.SenderError; import io.questdb.client.cutlass.line.LineSenderException; import io.questdb.client.cutlass.qwp.client.BatchTooLargeForCapException; +import io.questdb.client.cutlass.qwp.client.QwpConnectionHealthTracker; +import io.questdb.client.cutlass.qwp.client.QwpStrictTransactionMismatchException; import io.questdb.client.cutlass.qwp.client.QwpWebSocketSender; import io.questdb.client.cutlass.qwp.client.TransactionTooLargeException; import io.questdb.client.cutlass.qwp.client.WebSocketResponse; @@ -59,8 +62,10 @@ import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Function; @@ -1590,42 +1595,234 @@ public void testStrictRowLimitFromServer() throws Exception { } @Test - public void testStrictRowLimitDefaultsWhenNotAdvertised() throws Exception { + public void testStrictModeRejectsServerWithoutMaxUncommittedRowsHeader() throws Exception { + // Servers that predate X-QWP-Max-Uncommitted-Rows also predate FLAG_STRICT and + // silently commit deferred rows in parts at their qwp.max.uncommitted.rows. A + // strict sender (explicit transaction=strict or no auto-flush triggers) must fail + // at connect rather than risk silent partial commits, while transaction=on keeps + // working against the same older server. assertMemoryLeak(() -> { TxnServer h = new TxnServer(); try (TestWebSocketServer server = start(h, CAP)) { - try (Sender s = Sender.fromConfig(conf(server) + "transaction=strict;")) { - QwpWebSocketSender ws = (QwpWebSocketSender) s; + server.setAdvertisedMaxUncommittedRows(0); + String[] strictModes = { + "transaction=strict;", + "auto_flush=off;", + "auto_flush_rows=off;auto_flush_interval=off;", + "transaction=strict;initial_connect_retry=sync;reconnect_max_duration_millis=60000;" + }; + for (String mode : strictModes) { + long startNanos = System.nanoTime(); + try (Sender ignored = Sender.fromConfig(conf(server) + mode)) { + Assert.fail("strict mode must reject a server advertising no X-QWP-Max-Uncommitted-Rows: " + mode); + } catch (QwpStrictTransactionMismatchException e) { + Assert.assertEquals("localhost", e.getHost()); + Assert.assertEquals(server.getPort(), e.getPort()); + Assert.assertEquals( + "WebSocket upgrade failed: server does not support strict transactions [host=localhost, port=" + + server.getPort() + + ", missing=X-QWP-Max-Uncommitted-Rows]; upgrade the server or use transaction=on", + e.getMessage()); + Assert.assertEquals( + ConnectionHealth.FailureClass.OTHER, + QwpConnectionHealthTracker.classify(e, 1L).getFailureClass()); + } + long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); + Assert.assertTrue("capability mismatch must fail fast, took " + elapsedMs + "ms for " + mode, + elapsedMs < 10_000L); + } + Assert.assertEquals("zero frames must reach an incapable server", 0, h.frames.size()); + + // Enabling strict mode after connecting to an older server is also refused. + try (QwpWebSocketSender ws = (QwpWebSocketSender) Sender.fromConfig(conf(server))) { Assert.assertEquals(0, ws.getServerMaxUncommittedRows()); - // Pretend the server default is small to keep the test fast: the - // assumed default applies only while nothing is advertised. - ws.applyServerTransactionLimits(10, false); - writeRows(s, "a", 0, 9); try { - writeRows(s, "a", 9, 1); - Assert.fail("the 10th row must be refused"); - } catch (TransactionTooLargeException e) { - Assert.assertEquals(serverRowLimitError("a", 10), e.getMessage()); + ws.setStrictTransactional(true); + Assert.fail("late setStrictTransactional(true) must reject an older server"); + } catch (QwpStrictTransactionMismatchException e) { + Assert.assertEquals("localhost", e.getHost()); + Assert.assertEquals(server.getPort(), e.getPort()); + } + Assert.assertFalse(ws.isStrictTransactional()); + } + + // transaction=on and auto_flush=off;transaction=on keep working on older servers. + for (String nonStrict : new String[]{"transaction=on;", "auto_flush=off;transaction=on;"}) { + try (Sender s = Sender.fromConfig(conf(server) + nonStrict)) { + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(s.drain(5_000)); } - ws.applyServerTransactionLimits(0, false); - // 0 means "not advertised": the server default applies. - writeRows(s, "a", 9, 1); - s.flush(); } + Assert.assertEquals(2, h.commitFrames()); } }); } @Test - public void testStrictRowLimitIsServerDefaultWhenNotAdvertised() throws Exception { - // A server that does not advertise X-QWP-Max-Uncommitted-Rows commits a table on - // its own once its default qwp.max.uncommitted.rows of 1,000,000 rows are - // uncommitted, so a strict transaction holds at most 999,999 rows of a table. - // Rows of one LONG column keep the transaction small. + public void testStrictModeAsyncConnectLatchesTerminalAgainstOldServerWithoutSendingFrames() throws Exception { + // An async strict sender may buffer rows and deferred frames before the first + // handshake runs. When that handshake reaches a server without + // X-QWP-Max-Uncommitted-Rows, the loop must latch a startup terminal and never + // send a single frame onto the wire. assertMemoryLeak(() -> { TxnServer h = new TxnServer(); try (TestWebSocketServer server = start(h, CAP)) { - try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(conf(server) + "transaction=strict;")) { + server.setAdvertisedMaxUncommittedRows(0); + CountDownLatch errorLatch = new CountDownLatch(1); + AtomicReference receivedError = new AtomicReference<>(); + try (Sender s = Sender.builder(conf(server) + + "transaction=strict;initial_connect_retry=async;auto_flush_rows=10;") + .errorHandler(err -> { + receivedError.compareAndSet(null, err); + errorLatch.countDown(); + }) + .build()) { + try { + writeRows(s, "t", 0, 25); + } catch (LineSenderServerException ignore) { + // The I/O loop may latch the terminal before the producer finishes writing. + } + Assert.assertTrue("startup terminal must reach errorHandler", + errorLatch.await(10, TimeUnit.SECONDS)); + SenderError err = receivedError.get(); + Assert.assertEquals(SenderError.Category.PROTOCOL_VIOLATION, err.getCategory()); + Assert.assertEquals(SenderError.Policy.TERMINAL, err.getAppliedPolicy()); + TestUtils.assertContains(err.getServerMessage(), "strict-transaction-mismatch"); + TestUtils.assertContains(err.getServerMessage(), "X-QWP-Max-Uncommitted-Rows"); + try { + s.flush(); + Assert.fail("flush() must surface the latched startup terminal"); + } catch (LineSenderServerException e) { + Assert.assertEquals(SenderError.Category.PROTOCOL_VIOLATION, + e.getServerError().getCategory()); + } + } + Assert.assertEquals("old server must never receive a strict frame", 0, h.frames.size()); + } + }); + } + + @Test + public void testStrictModeMixedClusterSkipsOldServerAndConnectsToNewServer() throws Exception { + // In a rolling-upgrade cluster [old, new], a strict sender skips the older node + // that omits X-QWP-Max-Uncommitted-Rows and connects to the capable node. + assertMemoryLeak(() -> { + TxnServer oldHandler = new TxnServer(); + TxnServer newHandler = new TxnServer(); + try (TestWebSocketServer oldServer = start(oldHandler, CAP); + TestWebSocketServer newServer = start(newHandler, CAP)) { + oldServer.setAdvertisedMaxUncommittedRows(0); + newServer.setAdvertisedMaxUncommittedRows(1_000); + newServer.setRollbackSupported(true); + String config = "ws::addr=localhost:" + oldServer.getPort() + + ",localhost:" + newServer.getPort() + + ";transaction=strict;auto_flush_rows=10;"; + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(config)) { + Assert.assertEquals(1_000, s.getServerMaxUncommittedRows()); + writeRows(s, "t", 0, 25); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + Assert.assertEquals("old node must receive no frames", 0, oldHandler.frames.size()); + Assert.assertEquals("DDC", frameKinds(newHandler)); + assertOneTransaction(newHandler); + } + }); + } + + @Test + public void testStrictModeFailoverToOldServerRidesOutWithoutSplitting() throws Exception { + // After a strict sender has connected once, a reconnect that lands on an older + // server (no X-QWP-Max-Uncommitted-Rows) must neither send strict frames to it + // nor kill the sender: store-and-forward holds the transaction under Invariant B + // until a capable server returns, then commits it whole. + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + TxnServer initial = new TxnServer(); + TxnServer oldHandler = new TxnServer(); + TxnServer revived = new TxnServer(); + TestWebSocketServer oldServer = null; + TestWebSocketServer revivedServer = null; + try (TestWebSocketServer first = start(initial, CAP, port, true)) { + try (Sender s = Sender.fromConfig(outageConf(port) + "transaction=strict;auto_flush_rows=10;")) { + writeRows(s, "t", 0, 5); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + + first.close(); + oldServer = new TestWebSocketServer(oldHandler, false, null, port); + oldServer.setAdvertisedMaxBatchSize(CAP); + oldServer.start(); + Assert.assertTrue(oldServer.awaitStart(5, TimeUnit.SECONDS)); + + writeRows(s, "t", 10, 25); + s.flush(); + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (oldServer.upgradeRequestCount() < 2 && System.nanoTime() < deadlineNanos) { + java.util.concurrent.locks.LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(5)); + } + Assert.assertTrue("sender must probe and reject the older server", + oldServer.upgradeRequestCount() >= 2); + Assert.assertEquals("older server must receive zero strict frames", 0, oldHandler.frames.size()); + + oldServer.close(); + oldServer = null; + revivedServer = start(revived, CAP, port, true); + Assert.assertTrue(s.drain(10_000)); + } + } finally { + if (oldServer != null) { + oldServer.close(); + } + if (revivedServer != null) { + revivedServer.close(); + } + } + Assert.assertEquals("old server must never receive a frame", 0, oldHandler.frames.size()); + Assert.assertEquals("DDC", frameKinds(revived)); + assertOneTransaction(revived); + }); + } + + @Test + public void testStrictRowLimitDefaultsBeforeFirstConnect() throws Exception { + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + try (QwpWebSocketSender ws = (QwpWebSocketSender) Sender.fromConfig( + outageConf(port) + "initial_connect_retry=async;transaction=strict;")) { + Assert.assertEquals(0, ws.getServerMaxUncommittedRows()); + // Pretend the server default is small to keep the test fast: the + // assumed default applies while no limit is advertised yet. + ws.applyServerTransactionLimits(10, false); + writeRows(ws, "a", 0, 9); + try { + writeRows(ws, "a", 9, 1); + Assert.fail("the 10th row must be refused"); + } catch (TransactionTooLargeException e) { + Assert.assertEquals(serverRowLimitError("a", 10), e.getMessage()); + } + ws.applyServerTransactionLimits(0, false); + // 0 falls back to the 1,000,000 server default before a handshake learns the real cap. + writeRows(ws, "a", 9, 1); + ws.rollback(); + } + }); + } + + @Test + public void testStrictRowLimitIsServerDefaultBeforeFirstConnect() throws Exception { + // Before its first handshake completes, a strict sender assumes the server's + // default qwp.max.uncommitted.rows of 1,000,000, so a strict transaction holds + // at most 999,999 rows of a table. Rows of one LONG column keep the transaction + // small; once a capable server starts, the buffered transaction commits as one. + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + TxnServer h = new TxnServer(); + TestWebSocketServer server = null; + try { + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig( + outageConf(port) + "initial_connect_retry=async;transaction=strict;")) { Assert.assertEquals(0, s.getServerMaxUncommittedRows()); for (int i = 0; i < 999_999; i++) { s.table("a").longColumn("v", i).atNow(); @@ -1636,10 +1833,15 @@ public void testStrictRowLimitIsServerDefaultWhenNotAdvertised() throws Exceptio } catch (TransactionTooLargeException e) { Assert.assertEquals(serverRowLimitError("a", 1_000_000), e.getMessage()); } + server = start(h, CAP, port, true); s.flush(); - Assert.assertTrue(s.drain(5_000)); + Assert.assertTrue(s.drain(10_000)); } assertOneTransaction(h); + } finally { + if (server != null) { + server.close(); + } } }); } @@ -2895,6 +3097,7 @@ private static String outageConf(int port) { private static TestWebSocketServer start(TxnServer h, int cap) throws Exception { TestWebSocketServer server = new TestWebSocketServer(h); server.setAdvertisedMaxBatchSize(cap); + server.setAdvertisedMaxUncommittedRows(QwpConstants.DEFAULT_SERVER_MAX_UNCOMMITTED_ROWS); server.start(); Assert.assertTrue(server.awaitStart(5, TimeUnit.SECONDS)); return server; @@ -2905,6 +3108,7 @@ private static TestWebSocketServer start(TxnServer h, int cap) throws Exception private static TestWebSocketServer start(TxnServer h, int cap, int port, boolean isRollbackSupported) throws Exception { TestWebSocketServer server = new TestWebSocketServer(h, false, null, port); server.setAdvertisedMaxBatchSize(cap); + server.setAdvertisedMaxUncommittedRows(QwpConstants.DEFAULT_SERVER_MAX_UNCOMMITTED_ROWS); server.setRollbackSupported(isRollbackSupported); server.start(); Assert.assertTrue(server.awaitStart(5, TimeUnit.SECONDS)); diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/BackgroundDrainerDurableAckRetryTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/BackgroundDrainerDurableAckRetryTest.java index edce0a97a..47b2ac1a7 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/BackgroundDrainerDurableAckRetryTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/BackgroundDrainerDurableAckRetryTest.java @@ -36,6 +36,7 @@ import io.questdb.client.std.Os; import io.questdb.client.cutlass.qwp.client.QwpDurableAckMismatchException; import io.questdb.client.cutlass.qwp.client.QwpIngressRoleRejectedException; +import io.questdb.client.cutlass.qwp.client.QwpStrictTransactionMismatchException; import io.questdb.client.cutlass.qwp.client.sf.cursor.BackgroundDrainer; import io.questdb.client.cutlass.qwp.client.sf.cursor.BackgroundDrainerListener; import io.questdb.client.cutlass.qwp.client.sf.cursor.CursorWebSocketSendLoop; @@ -116,6 +117,27 @@ public void tearDown() { closeAllStubs(); } + @Test(timeout = 60_000) + public void testStrictTransactionMismatchUsesSettleBudgetWithoutDurableAckCallbacks() throws Exception { + assertMemoryLeak(() -> { + CountingListener listener = new CountingListener(); + ScriptedFactory factory = ScriptedFactory.alwaysFailing( + () -> new QwpStrictTransactionMismatchException("h", 1234)); + BackgroundDrainer drainer = newDrainer(factory); + drainer.setListener(listener); + WebSocketClient out = drainer.connectWithDurableAckRetry(); + assertNull("escalation must signal failure to caller", out); + assertEquals(BackgroundDrainer.DrainOutcome.FAILED, drainer.outcome()); + assertEquals(BackgroundDrainer.DEFAULT_MAX_DURABLE_ACK_MISMATCH_ATTEMPTS, factory.calls.get()); + assertEquals("strict mismatch must not fire onDurableAckUnavailable", 0, listener.unavailableAttempts.size()); + assertEquals("strict mismatch must not fire onDurableAckPersistentFailure", 0, listener.persistentFailures.get()); + String sentinel = slotPath + "/" + OrphanScanner.FAILED_SENTINEL_NAME; + assertTrue("expected .failed sentinel at " + sentinel, Files.exists(sentinel)); + assertNotNull("lastErrorMessage populated", drainer.getLastErrorMessage()); + TestUtils.assertContains(drainer.getLastErrorMessage(), "server does not support strict transactions"); + }); + } + @Test(timeout = 60_000) public void testCallbackArgumentsCarrySlotPathAndAttemptNumber() throws Exception { assertMemoryLeak(() -> { diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoopForegroundReconnectPolicyTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoopForegroundReconnectPolicyTest.java index be10cbcfb..4df914ebc 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoopForegroundReconnectPolicyTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoopForegroundReconnectPolicyTest.java @@ -31,6 +31,7 @@ import io.questdb.client.cutlass.http.client.WebSocketClientFactory; import io.questdb.client.cutlass.qwp.client.QwpAuthFailedException; import io.questdb.client.cutlass.qwp.client.QwpDurableAckMismatchException; +import io.questdb.client.cutlass.qwp.client.QwpStrictTransactionMismatchException; import io.questdb.client.cutlass.qwp.client.sf.cursor.CursorSendEngine; import io.questdb.client.cutlass.qwp.client.sf.cursor.CursorWebSocketSendLoop; import io.questdb.client.network.PlainSocketFactory; @@ -77,6 +78,13 @@ public void testAsyncInitialDurableAckMismatchSurfacesTerminalToTheCaller() thro "durable-ack-mismatch"); } + @Test + public void testAsyncInitialStrictTransactionMismatchSurfacesTerminalToTheCaller() throws Exception { + assertAsyncInitialForegroundSurfacesTerminal(false, + () -> new QwpStrictTransactionMismatchException("localhost", 1), + "strict-transaction-mismatch"); + } + @Test public void testFirstConnectCatchUpFailureKeepsStartupTerminalArmed() throws Exception { // swapClient must not latch hasEverConnected before the dictionary @@ -136,6 +144,12 @@ public void testPostStartDurableAckMismatchRetriesUntilCapabilityRecovers() thro () -> new QwpDurableAckMismatchException("localhost", 1, "primary")); } + @Test + public void testPostStartStrictTransactionMismatchRetriesUntilCapabilityRecovers() throws Exception { + assertForegroundRecovers(false, + () -> new QwpStrictTransactionMismatchException("localhost", 1)); + } + /** * An endpoint-policy failure before the sender has EVER reached the server is a * startup problem, so it must reach the caller rather than retry silently: an From 34116f5c2df2fcd5433d5452be1307fb394831e0 Mon Sep 17 00:00:00 2001 From: bluestreak Date: Sun, 29 Nov 2026 21:52:16 +0000 Subject: [PATCH 16/20] Size shared strict budgets by live registered rings SegmentBudget(long) declares maxSharers=1, so strict senders sharing a one-argument budget via storeAndForwardSharedBudget (or sharing any SegmentBudget across more senders than its declared maxSharers) each sized their open strict transactions against the whole budget and deadlocked for sf_append_deadline_millis on every call when concurrent transactions filled the buffer together. Track live registered rings on SegmentBudget without adding locks, hot-path overhead, or rejecting transient pool overlaps: - Fold ring registration/deregistration into SegmentBudget.registerRing() and deregisterRing() (replacing the charge/release calls in SegmentManager.register/deregister under SegmentBudget's existing leaf monitor) and publish effectiveSharers = max(maxSharers, registeredRings) as a volatile int (never written after construction when registeredRings <= maxSharers). - Route CursorSendEngine.budgetSharers() and shareSegments() through effectiveSharers(), keeping SegmentBudget.getMaxSharers() immutable. - Snapshot the refusing sharer count in QwpWebSocketSender (txnRefusedSharers, replacing isTxnRefusedAtShare) so a sibling closing between an auto-flush refusal and the next row cannot turn the thrown error's sharer count to 1. - Document SegmentBudget(long) and update Sender.storeAndForwardSharedBudget javadoc. - Add regression tests in SegmentBudgetTest and QwpLargeTransactionTest covering one-argument shared budgets (auto_flush=off, no-trigger, and transaction=strict at 32 KiB and 2 MiB caps), over-shared multi-sharer budgets, sibling close restoring the whole budget, and snapshotted refusal sharer counts. --- .../main/java/io/questdb/client/Sender.java | 5 +- .../qwp/client/QwpWebSocketSender.java | 33 ++-- .../client/sf/cursor/CursorSendEngine.java | 19 +- .../qwp/client/sf/cursor/SegmentBudget.java | 78 ++++++-- .../qwp/client/sf/cursor/SegmentManager.java | 4 +- .../qwp/client/QwpLargeTransactionTest.java | 184 ++++++++++++++++++ .../client/sf/cursor/SegmentBudgetTest.java | 82 ++++++++ 7 files changed, 371 insertions(+), 34 deletions(-) diff --git a/core/src/main/java/io/questdb/client/Sender.java b/core/src/main/java/io/questdb/client/Sender.java index 9fcf64a05..038f8a3eb 100644 --- a/core/src/main/java/io/questdb/client/Sender.java +++ b/core/src/main/java/io/questdb/client/Sender.java @@ -3179,8 +3179,9 @@ public LineSenderBuilder storeAndForwardMaxTotalBytes(long maxTotalBytes) { * sender's own {@code sf_max_total_bytes} then caps only the * background orphan drainers it starts. A strict transaction that * spans more than one segment counts only on this sender's share of - * the budget: its capacity divided by the senders it was built for - * ({@link SegmentBudget#SegmentBudget(long, int)}). The connection pool + * the budget: its capacity divided by the larger of the senders it was + * built for ({@link SegmentBudget#SegmentBudget(long, int)}) and the + * senders currently charging it. The connection pool * behind {@link QuestDB} builds every sender this way, on a budget * built for its maximum size. WebSocket transport only. * diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java index 113fde1d8..fe7e936e6 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java @@ -787,10 +787,12 @@ public class QwpWebSocketSender implements Sender { // flush the client buffer last refused, for the error messages. Reset with the // transaction. private long txnRefusedBytes; - // Strict mode only: the flush the client buffer last refused did fit the whole - // buffer but not this sender's share of a buffer other senders share, for the - // error messages. Reset with the transaction. - private boolean isTxnRefusedAtShare; + // Strict mode only: when > 1, the flush the client buffer last refused did + // fit the whole buffer but not this sender's share among that many sharers + // (snapshotted at the refusal so a sibling closing later cannot turn the + // error's sharer count to 1); 0 when not refused at a share. Reset with the + // transaction. + private int txnRefusedSharers; // Scratch for hasTransactionRoom: the frame sizes a flush will publish. // Producer thread only. private final IntList transactionFrameSizes = new IntList(); @@ -7879,7 +7881,7 @@ private void clearTransactionState() { txnMaxCheckedRows = 0; txnBytes = 0; txnRefusedBytes = 0; - isTxnRefusedAtShare = false; + txnRefusedSharers = 0; txnRowsCommittedInParts = 0; txnSimSegments = 0; txnSimRemaining = 0; @@ -7932,8 +7934,8 @@ private void commitTransactionPart() { * frames. Runs before anything of the flush is published, so a refusal * leaves the batch pending and the ring untouched. On a strict refusal it * records the size the transaction would have reached in - * {@link #txnRefusedBytes}, and in {@link #isTxnRefusedAtShare} whether only - * the share refused it. + * {@link #txnRefusedBytes}, and in {@link #txnRefusedSharers} the sharer + * count (> 1) when only the share refused it (0 otherwise). */ private boolean hasTransactionRoom(int cap, int deltaBaseline, int messageSize, boolean deferCommit) { CursorSendEngine engine = cursorEngine; @@ -8003,7 +8005,7 @@ && splitFramesFit(cap, currentBatchMaxSymbolId)) { if (segments > Math.max(2, capacity / engine.segmentSizeBytes())) { if (strictTransactional) { txnRefusedBytes = bytes; - isTxnRefusedAtShare = false; + txnRefusedSharers = 0; } return false; } @@ -8016,10 +8018,13 @@ && splitFramesFit(cap, currentBatchMaxSymbolId)) { // than the two segments the budget grants every sender past its cap, and a // share smaller than its room for that commit would refuse even a batch that // fits one frame. - if (strictTransactional && frameSegments > 1 && segments > Math.max(2, engine.shareSegments(capacity))) { - txnRefusedBytes = bytes; - isTxnRefusedAtShare = true; - return false; + if (strictTransactional && frameSegments > 1) { + int sharers = engine.budgetSharers(); + if (sharers > 1 && segments > Math.max(2, engine.shareSegments(capacity, sharers))) { + txnRefusedBytes = bytes; + txnRefusedSharers = sharers; + return false; + } } return true; } @@ -8128,8 +8133,8 @@ private long serverMaxUncommittedRowsOrDefault() { */ private LineSenderException transactionTooLargeForClientBuffer(String outcome) { CursorSendEngine engine = cursorEngine; - if (isTxnRefusedAtShare) { - int senders = engine.budgetSharers(); + if (txnRefusedSharers > 1) { + int senders = txnRefusedSharers; return new TransactionTooLargeException("transaction too large for this sender's share of the client buffer") .put(" [transactionBytes=").put(txnRefusedBytes) .put(", ringCapacityBytes=").put(engine.ringCapacityBytes()) diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorSendEngine.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorSendEngine.java index 3f97bc5cb..70c2686ce 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorSendEngine.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorSendEngine.java @@ -1912,11 +1912,13 @@ public long ringCapacityBytes() { } /** - * The most senders that charge this ring's budget at once: 1 unless the - * budget is shared, as in a sender pool. + * Senders that share this ring's budget: the larger of the budget's + * declared {@link SegmentBudget#getMaxSharers()} and the rings currently + * registered on it. 1 unless the budget is shared, as in a sender pool or + * via {@code storeAndForwardSharedBudget}. */ public int budgetSharers() { - return manager.getBudget().getMaxSharers(); + return manager.getBudget().effectiveSharers(); } /** @@ -1928,8 +1930,15 @@ public int budgetSharers() { * which stays charged to the budget until the ring moves into it. */ public long shareSegments(long capacityBytes) { - int sharers = manager.getBudget().getMaxSharers(); - if (sharers == 1) { + return shareSegments(capacityBytes, budgetSharers()); + } + + /** + * Same as {@link #shareSegments(long)} for a snapshotted {@code sharers} + * count from {@link #budgetSharers()}. + */ + public long shareSegments(long capacityBytes, int sharers) { + if (sharers <= 1) { return capacityBytes / segmentSizeBytes; } long share = capacityBytes / sharers / segmentSizeBytes; diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentBudget.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentBudget.java index fb9378d21..dbe7e85da 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentBudget.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentBudget.java @@ -25,6 +25,7 @@ package io.questdb.client.cutlass.qwp.client.sf.cursor; import io.questdb.client.std.ObjList; +import org.jetbrains.annotations.TestOnly; import java.util.function.LongSupplier; @@ -59,9 +60,8 @@ public final class SegmentBudget { private final long capacityBytes; - // The most senders that charge this budget at once: 1 for the budget of a - // sender built on its own, the maximum size of a pool for the pool's budget. - // Immutable, so a sender can size what it may pin without consulting the others. + // The declared upper bound on senders that charge this budget at once: 1 for + // a private budget, the maximum size of a pool for the pool's budget. private final int maxSharers; // Live gauges of each charged slot's .symbol-dict side-file bytes. Read on // every cap check rather than folded into segmentBytes: a dictionary @@ -72,8 +72,21 @@ public final class SegmentBudget { // and a gauge that took that monitor would stall every manager charging // this budget behind one producer's append I/O. private final ObjList sideFileGauges = new ObjList<>(); + // Published for wait-free reads on hasTransactionRoom(): max(maxSharers, registeredRings). + private volatile int effectiveSharers; + private int registeredRings; private long segmentBytes; + /** + * A budget declared for one sender ({@link #getMaxSharers()} is {@code 1}). + *

    + * Callers sharing one budget across several senders via + * {@code storeAndForwardSharedBudget} should prefer + * {@link #SegmentBudget(long, int)} so every sender knows the full sharer + * count before sibling senders are constructed. If more than + * {@code maxSharers} rings register on this budget at once, strict + * transactions automatically size against the live registered count. + */ public SegmentBudget(long capacityBytes) { this(capacityBytes, 1); } @@ -91,6 +104,7 @@ public SegmentBudget(long capacityBytes, int maxSharers) { } this.capacityBytes = capacityBytes; this.maxSharers = maxSharers; + this.effectiveSharers = maxSharers; } /** @@ -104,13 +118,19 @@ public long getCapacityBytes() { return capacityBytes; } + @TestOnly + public int getEffectiveSharersForTesting() { + return effectiveSharers; + } + /** - * The most senders that charge this budget at once. A strict transaction pins - * its segments until the server commits it, and trim cannot release them, so - * all sharers may pin segments at the same time: a sender sizes a strict - * transaction that spans segments against its share of the capacity, or the - * transactions of several senders could fill the budget together and leave - * each other's commits no room. + * The declared upper bound on senders that charge this budget at once. A + * strict transaction pins its segments until the server commits it, and trim + * cannot release them, so all sharers may pin segments at the same time: a + * sender sizes a strict transaction that spans segments against its share of + * the capacity (using the larger of this value and the rings currently + * registered on this budget), or the transactions of several senders could + * fill the budget together and leave each other's commits no room. */ public int getMaxSharers() { return maxSharers; @@ -129,13 +149,49 @@ synchronized void addSideFileGauge(LongSupplier gauge) { } /** - * Charges {@code bytes} unconditionally: segments a ring already owns when - * it registers, and segments created under the liveness floor. + * Charges {@code bytes} unconditionally: segments created under the liveness + * floor. */ synchronized void charge(long bytes) { segmentBytes += bytes; } + /** + * Reverses a ring's registration and its remaining segment bytes. Paired + * with {@link #registerRing(long)} under {@link SegmentManager#deregister}. + */ + synchronized void deregisterRing(long bytes) { + segmentBytes -= bytes; + registeredRings--; + assert registeredRings >= 0 : "deregistered more rings than registered"; + int next = Math.max(maxSharers, registeredRings); + if (effectiveSharers != next) { + effectiveSharers = next; + } + } + + /** + * Larger of {@link #getMaxSharers()} and the rings currently registered on + * this budget. Wait-free: written only under this monitor when the live + * count crosses {@code maxSharers}. + */ + int effectiveSharers() { + return effectiveSharers; + } + + /** + * Registers a ring and charges the segment bytes it already owns (initial + * active or recovered segments). Paired with {@link #deregisterRing(long)} + * under {@link SegmentManager#register}. + */ + synchronized void registerRing(long bytes) { + segmentBytes += bytes; + registeredRings++; + if (registeredRings > maxSharers) { + effectiveSharers = registeredRings; + } + } + synchronized void release(long bytes) { segmentBytes -= bytes; } diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentManager.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentManager.java index ba4000168..f71791b9a 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentManager.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentManager.java @@ -501,7 +501,7 @@ public void deregister(SegmentRing ring) { // totalSegmentBytes() now, including a segment the // provisioner holds after a failed rotation. e.deregister(); - budget.release(ring.totalSegmentBytes()); + budget.deregisterRing(ring.totalSegmentBytes()); if (e.sideFileBytes != null) { budget.removeSideFileGauge(e.sideFileBytes); } @@ -605,7 +605,7 @@ public void register(SegmentRing ring, String dir, AckWatermark watermark, long } throw t; } - budget.charge(ringBytes); + budget.registerRing(ringBytes); if (syncIntervalNanos > 0L) { ring.enablePeriodicSync(); } diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index f21511784..6a5265097 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -983,6 +983,190 @@ public void testPooledStrictLeasesRefuseRowsPastTheirShareConcurrently() throws }); } + @Test + public void testSharedOneArgBudgetSizesStrictSendersToRegisteredCount() throws Exception { + // Two strict senders sharing a one-argument SegmentBudget(512k) via + // storeAndForwardSharedBudget used to both see maxSharers=1, fill the 512 KiB + // buffer together, and deadlock each other for sf_append_deadline_millis on + // every call. Each now counts on its share of the live registered count (2), + // refuses rows past that share immediately with TransactionTooLargeException, + // and commits cleanly; once the sibling closes, the surviving sender recovers + // the whole 512 KiB budget. + assertMemoryLeak(() -> { + String[] modes = { + "auto_flush=off;sf_max_segment_bytes=64k;sf_append_deadline_millis=30000;", + "auto_flush=off;sf_max_segment_bytes=64k;sf_append_deadline_millis=30000;", + "auto_flush_rows=off;auto_flush_interval=off;sf_max_segment_bytes=64k;sf_append_deadline_millis=30000;", + STRICT_FRAMES_OF_280 + }; + int[] serverCaps = {CAP, 2 * 1024 * 1024, CAP, CAP}; + for (int m = 0; m < modes.length; m++) { + String mode = modes[m]; + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, serverCaps[m])) { + SegmentBudget shared = new SegmentBudget(512 * 1024); + Assert.assertEquals(1, shared.getMaxSharers()); + String cfg = conf(server) + mode; + Refusal[] refusals = new Refusal[2]; + try (Sender s1 = Sender.builder(cfg).storeAndForwardSharedBudget(shared).build()) { + Sender s2 = Sender.builder(cfg).storeAndForwardSharedBudget(shared).build(); + try { + Assert.assertEquals(mode, 2, shared.getEffectiveSharersForTesting()); + CyclicBarrier barrier = new CyclicBarrier(2); + Throwable[] errors = new Throwable[2]; + Sender[] senders = {s1, s2}; + Thread[] threads = new Thread[2]; + long start = System.nanoTime(); + for (int i = 0; i < 2; i++) { + final int idx = i; + threads[i] = new Thread(() -> { + try { + barrier.await(10, TimeUnit.SECONDS); + refusals[idx] = writeUntilTooLarge(senders[idx], "t" + idx); + barrier.await(10, TimeUnit.SECONDS); + senders[idx].flush(); + } catch (Throwable t) { + errors[idx] = t; + barrier.reset(); + } + }); + threads[i].start(); + } + for (Thread thread : threads) { + thread.join(); + } + for (Throwable error : errors) { + if (error != null) { + throw new AssertionError(mode, error); + } + } + Assert.assertTrue(mode + ": must not wait for sf_append_deadline_millis", + System.nanoTime() - start < TimeUnit.SECONDS.toNanos(10)); + for (int i = 0; i < 2; i++) { + assertShareRefusal(refusals[i].error, 524_288, 2, "so the row was not added"); + } + Assert.assertTrue(mode, s1.drain(5_000)); + Assert.assertTrue(mode, s2.drain(5_000)); + } finally { + s2.close(); + } + + // Once s2 closes, s1 is the sole sharer again and keeps the whole 512 KiB buffer. + Assert.assertEquals(mode, 1, shared.getEffectiveSharersForTesting()); + Refusal solo = writeUntilTooLarge(s1, "solo"); + Assert.assertTrue(mode + ": solo sender must fit more rows than a 2-sender share", + solo.row > refusals[0].row); + assertClientBufferRefusal(solo.error, 524_288, "so the row was not added"); + s1.flush(); + Assert.assertTrue(mode, s1.drain(5_000)); + } + Assert.assertEquals(mode, 3, h.commitFrames()); + Assert.assertEquals(mode, h.frames.size(), h.committedFrames().size()); + } + } + }); + } + + @Test + public void testSharedBudgetPastDeclaredSharersSizesToRegisteredCount() throws Exception { + // Sharing a 2-sharer budget across 4 strict senders scales the share to 4 + // (1 MiB / 4 = 256 KiB = 4 segments each), so all 4 hold open strict + // transactions concurrently and commit without deadlocking. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + SegmentBudget shared = new SegmentBudget(1_048_576, 2); + String cfg = conf(server) + STRICT_FRAMES_OF_280; + Sender[] senders = new Sender[4]; + Refusal[] refusals = new Refusal[4]; + try { + for (int i = 0; i < senders.length; i++) { + senders[i] = Sender.builder(cfg).storeAndForwardSharedBudget(shared).build(); + } + Assert.assertEquals(2, shared.getMaxSharers()); + Assert.assertEquals(4, shared.getEffectiveSharersForTesting()); + CyclicBarrier barrier = new CyclicBarrier(senders.length); + Throwable[] errors = new Throwable[senders.length]; + Thread[] threads = new Thread[senders.length]; + long start = System.nanoTime(); + for (int i = 0; i < senders.length; i++) { + final int idx = i; + threads[i] = new Thread(() -> { + try { + barrier.await(10, TimeUnit.SECONDS); + refusals[idx] = writeUntilTooLarge(senders[idx], "t" + idx); + barrier.await(10, TimeUnit.SECONDS); + senders[idx].flush(); + } catch (Throwable t) { + errors[idx] = t; + barrier.reset(); + } + }); + threads[i].start(); + } + for (Thread thread : threads) { + thread.join(); + } + for (Throwable error : errors) { + if (error != null) { + throw new AssertionError(error); + } + } + Assert.assertTrue("must not wait for sf_append_deadline_millis", + System.nanoTime() - start < TimeUnit.SECONDS.toNanos(10)); + for (int i = 0; i < senders.length; i++) { + Assert.assertEquals(1_120, refusals[i].row); + assertShareRefusal(refusals[i].error, 1_048_576, 4, "so the row was not added"); + Assert.assertTrue(senders[i].drain(5_000)); + } + } finally { + for (Sender sender : senders) { + if (sender != null) { + sender.close(); + } + } + } + Assert.assertEquals(4, h.commitFrames()); + Assert.assertEquals(h.frames.size(), h.committedFrames().size()); + } + }); + } + + @Test + public void testSharedBudgetRefusalSnapshotsSharerCountAfterSiblingCloses() throws Exception { + // When an auto-flush latches txnBufferFull because of a 2-sender share, closing + // the sibling sender before the next row is written must not turn the thrown + // error's sharer count into 1: the refusal keeps the sharer count that tripped it. + assertMemoryLeak(() -> { + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + SegmentBudget shared = new SegmentBudget(512 * 1024); + String cfg = conf(server) + STRICT_FRAMES_OF_280; + try (Sender s1 = Sender.builder(cfg).storeAndForwardSharedBudget(shared).build()) { + try (Sender ignored = Sender.builder(cfg).storeAndForwardSharedBudget(shared).build()) { + Assert.assertEquals(2, shared.getEffectiveSharersForTesting()); + // 1120 rows trips the 4th 280-row auto-flush, which exceeds the + // 2-sender share of 4 segments and latches txnBufferFull without + // throwing until the next row. + writeRows(s1, "t1", 0, 1_120); + } + // Sibling closed: live sharers dropped back to 1. + Assert.assertEquals(1, shared.getEffectiveSharersForTesting()); + try { + writeRows(s1, "t1", 1_120, 1); + Assert.fail("the next row after txnBufferFull must be refused"); + } catch (TransactionTooLargeException e) { + assertShareRefusal(e, 524_288, 2, "so the row was not added"); + } + s1.flush(); + Assert.assertTrue(s1.drain(5_000)); + } + Assert.assertEquals("DDDC", frameKinds(h)); + Assert.assertEquals(h.frames.size(), h.committedFrames().size()); + } + }); + } + @Test public void testPooledStrictShareLeavesRoomForPrefetchedSegment() throws Exception { // With sf_dir, the segment manager creates each sender's next segment ahead of diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/SegmentBudgetTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/SegmentBudgetTest.java index 385290a22..73f667698 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/SegmentBudgetTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/sf/cursor/SegmentBudgetTest.java @@ -24,7 +24,11 @@ package io.questdb.client.test.cutlass.qwp.client.sf.cursor; +import io.questdb.client.cutlass.qwp.client.sf.cursor.MmapSegment; import io.questdb.client.cutlass.qwp.client.sf.cursor.SegmentBudget; +import io.questdb.client.cutlass.qwp.client.sf.cursor.SegmentManager; +import io.questdb.client.cutlass.qwp.client.sf.cursor.SegmentRing; +import io.questdb.client.test.tools.TestUtils; import org.junit.Assert; import org.junit.Test; @@ -34,12 +38,86 @@ */ public class SegmentBudgetTest { + private static final long SEGMENT_BYTES = 4096; + @Test public void testCapacityIsValidatedBeforeSharers() { assertRejected(0, 0, "capacityBytes must be positive: 0"); assertRejected(-1, 2, "capacityBytes must be positive: -1"); } + @Test + public void testEffectiveSharersTracksRegisteredRingsAboveMaxSharers() throws Exception { + TestUtils.assertMemoryLeak(() -> { + // One-argument budget (maxSharers == 1): effectiveSharers stays 1 for one + // ring, scales up to the live registered count when shared across managers, + // is unaffected by idempotent repeat deregister, and returns to 1 once + // siblings leave. + SegmentBudget oneArg = new SegmentBudget(8 * SEGMENT_BYTES); + Assert.assertEquals(1, oneArg.getMaxSharers()); + Assert.assertEquals(1, oneArg.getEffectiveSharersForTesting()); + try (SegmentRing r1 = newRing(); + SegmentRing r2 = newRing(); + SegmentRing r3 = newRing(); + SegmentManager m1 = new SegmentManager(SEGMENT_BYTES, oneArg); + SegmentManager m2 = new SegmentManager(SEGMENT_BYTES, oneArg); + SegmentManager m3 = new SegmentManager(SEGMENT_BYTES, oneArg)) { + m1.register(r1, null); + Assert.assertEquals(1, oneArg.getMaxSharers()); + Assert.assertEquals(1, oneArg.getEffectiveSharersForTesting()); + + m2.register(r2, null); + Assert.assertEquals(1, oneArg.getMaxSharers()); + Assert.assertEquals(2, oneArg.getEffectiveSharersForTesting()); + + m3.register(r3, null); + Assert.assertEquals(1, oneArg.getMaxSharers()); + Assert.assertEquals(3, oneArg.getEffectiveSharersForTesting()); + + m2.deregister(r2); + Assert.assertEquals(2, oneArg.getEffectiveSharersForTesting()); + // Idempotent: a second deregister must not decrement again. + m2.deregister(r2); + Assert.assertEquals(2, oneArg.getEffectiveSharersForTesting()); + + m3.deregister(r3); + Assert.assertEquals(1, oneArg.getEffectiveSharersForTesting()); + + m1.deregister(r1); + Assert.assertEquals(1, oneArg.getEffectiveSharersForTesting()); + Assert.assertEquals(0, oneArg.getSegmentBytes()); + } + + // Declared maxSharers == 2 acts as a floor while <= 2 rings are registered, + // and yields to the live count once a third ring registers. + SegmentBudget twoArg = new SegmentBudget(8 * SEGMENT_BYTES, 2); + Assert.assertEquals(2, twoArg.getMaxSharers()); + Assert.assertEquals(2, twoArg.getEffectiveSharersForTesting()); + try (SegmentRing r1 = newRing(); + SegmentRing r2 = newRing(); + SegmentRing r3 = newRing(); + SegmentManager m1 = new SegmentManager(SEGMENT_BYTES, twoArg); + SegmentManager m2 = new SegmentManager(SEGMENT_BYTES, twoArg); + SegmentManager m3 = new SegmentManager(SEGMENT_BYTES, twoArg)) { + m1.register(r1, null); + Assert.assertEquals(2, twoArg.getEffectiveSharersForTesting()); + m2.register(r2, null); + Assert.assertEquals(2, twoArg.getEffectiveSharersForTesting()); + m3.register(r3, null); + Assert.assertEquals(2, twoArg.getMaxSharers()); + Assert.assertEquals(3, twoArg.getEffectiveSharersForTesting()); + + m3.deregister(r3); + Assert.assertEquals(2, twoArg.getEffectiveSharersForTesting()); + m2.deregister(r2); + Assert.assertEquals(2, twoArg.getEffectiveSharersForTesting()); + m1.deregister(r1); + Assert.assertEquals(2, twoArg.getEffectiveSharersForTesting()); + Assert.assertEquals(0, twoArg.getSegmentBytes()); + } + }); + } + @Test public void testMaxSharersDefaultsToOne() { // A budget built for one sender, as every sender built on its own gets. @@ -61,6 +139,10 @@ public void testMaxSharersMustBePositive() { assertRejected(1024, Integer.MIN_VALUE, "maxSharers must be positive: " + Integer.MIN_VALUE); } + private static SegmentRing newRing() { + return new SegmentRing(MmapSegment.createInMemory(0, SEGMENT_BYTES), SEGMENT_BYTES); + } + private static void assertRejected(long capacityBytes, int maxSharers, String expectedMessage) { try { new SegmentBudget(capacityBytes, maxSharers); From 949b3b0cab132a6cbe07419e47cf3c03c5991f34 Mon Sep 17 00:00:00 2001 From: bluestreak Date: Sun, 29 Nov 2026 23:58:39 +0000 Subject: [PATCH 17/20] Advertise X-QWP-Max-Uncommitted-Rows in strict SelfSufficientFramesTest servers Commit a46fcf20 made setStrictTransactional(true) reject servers whose 101 handshake omits X-QWP-Max-Uncommitted-Rows. The two strict-mode tests in SelfSufficientFramesTest left advertisedMaxUncommittedRows unset on their TestWebSocketServer and failed with QwpStrictTransactionMismatchException. --- .../test/cutlass/qwp/client/SelfSufficientFramesTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/SelfSufficientFramesTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/SelfSufficientFramesTest.java index db48d3bdd..6bbdd1cbe 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/SelfSufficientFramesTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/SelfSufficientFramesTest.java @@ -1373,6 +1373,7 @@ public void testDictionaryChunksStayInTheOpenTransactionWhenTheDataFrameFailsToP CapturingHandler handler = new CapturingHandler(); try (TestWebSocketServer server = new TestWebSocketServer(handler)) { server.setAdvertisedMaxBatchSize(150); + server.setAdvertisedMaxUncommittedRows(QwpConstants.DEFAULT_SERVER_MAX_UNCOMMITTED_ROWS); int port = server.getPort(); server.start(); Assert.assertTrue(server.awaitStart(5, TimeUnit.SECONDS)); @@ -1602,6 +1603,7 @@ private void assertDictionaryChunkFailsToPublish(boolean isTransactional) throws CapturingHandler handler = new CapturingHandler(); try (TestWebSocketServer server = new TestWebSocketServer(handler)) { server.setAdvertisedMaxBatchSize(150); + server.setAdvertisedMaxUncommittedRows(QwpConstants.DEFAULT_SERVER_MAX_UNCOMMITTED_ROWS); int port = server.getPort(); server.start(); Assert.assertTrue(server.awaitStart(5, TimeUnit.SECONDS)); From ccba9ea51b7b50c14d7f6e2cfb52e9531d1ef897 Mon Sep 17 00:00:00 2001 From: bluestreak Date: Mon, 30 Nov 2026 02:30:09 +0000 Subject: [PATCH 18/20] Fix reset() rollback-unsupported warning to advise rollback() instead of close() In transaction=on mode against a server without QWP rollback support, reset() preserves legacy behaviour by keeping frames already sent with FLAG_DEFER_COMMIT, and close() commits them (QwpWebSocketSender.close0() calls sendCommitMessage(), and PooledSender.close() calls flush()). The warning logged by reset() previously told callers "the next flush() commits them. Close the sender to discard them instead", which caused users following that advice to commit the rows they meant to drop. Update the warning to name both flush() and close() and advise calling rollback() instead ("Call rollback() to discard them; on such a server it closes the connection that holds them"), align the reset() Javadocs on Sender and QwpWebSocketSender, and add regression tests in QwpLargeTransactionTest covering reset() -> close() and reset() -> rollback() on both standalone and pooled senders. --- .../main/java/io/questdb/client/Sender.java | 3 +- .../qwp/client/QwpWebSocketSender.java | 11 +- .../qwp/client/QwpLargeTransactionTest.java | 121 +++++++++++++++++- 3 files changed, 126 insertions(+), 9 deletions(-) diff --git a/core/src/main/java/io/questdb/client/Sender.java b/core/src/main/java/io/questdb/client/Sender.java index 038f8a3eb..5cd5b4575 100644 --- a/core/src/main/java/io/questdb/client/Sender.java +++ b/core/src/main/java/io/questdb/client/Sender.java @@ -777,7 +777,8 @@ default void resetSymbolDictionary() { * discards the rows of the open transaction already sent, by auto-flush or by a * {@link #flush()} that failed partway, as {@link #rollback()} does. The exception is a {@code transaction=on} sender that last * connected to a server without QWP rollback support: it keeps those rows, and the next - * flush commits them, as before rollback existed. + * flush or close commits them, as before rollback existed; call {@link #rollback()} to + * discard them. *
    * Note: the ILP TCP and UDP transports don't support this operation. * diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java index fe7e936e6..6efb33a51 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java @@ -3507,10 +3507,10 @@ public void setCloseStartedHook(Runnable hook) { * sent, as {@link #rollback()} does, without waiting for the server. The * exception is a transaction=on transaction on a sender whose last handshake * was with a server without QWP rollback support: it keeps the frames already - * sent, and the next flush commits them, as before rollback existed. A - * transaction that sent no frames yet ends on any server, so the next row - * starts a new one, also after the client buffer refused a row of a strict - * transaction. + * sent, and the next flush or close commits them, as before rollback existed; + * call {@link #rollback()} to discard them. A transaction that sent no frames + * yet ends on any server, so the next row starts a new one, also after the + * client buffer refused a row of a strict transaction. */ @Override public void reset() { @@ -3529,7 +3529,8 @@ public void reset() { isResetRollbackWarned = true; LOG.warn("reset() discarded the rows not yet sent, but the server does not support QWP " + "rollback, so the open transaction's rows already sent stay on the server and the " - + "next flush() commits them. Close the sender to discard them instead"); + + "next flush() or close() commits them. Call rollback() to discard them; on such a " + + "server it closes the connection that holds them"); } } } diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index 6a5265097..a6171c0d7 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -117,7 +117,8 @@ public class QwpLargeTransactionTest { // rows already sent because the server of the last handshake lacks rollback support. private static final String RESET_KEEPS_ROWS_WARNING = "reset() discarded the rows not yet sent, but the " + "server does not support QWP rollback, so the open transaction's rows already sent stay on the " - + "server and the next flush() commits them. Close the sender to discard them instead"; + + "server and the next flush() or close() commits them. Call rollback() to discard them; on such a " + + "server it closes the connection that holds them"; // The settings a refusal at a sender's share of a shared client buffer names. private static final String SHARE_REMEDY = "Raise sf_max_total_bytes, lower sender_pool_max, or set sf_dir to " + "keep the transaction on disk"; @@ -1412,8 +1413,8 @@ public void testResetKeepsDeferredFramesOfNonTransactionalSender() throws Except @Test public void testResetKeepsLegacyBehaviourWithoutServerRollback() throws Exception { // transaction=on against a server that the handshake showed to lack rollback: - // reset() keeps the frames already sent, and the next flush() commits them, as - // before rollback existed. It says so once per sender. + // reset() keeps the frames already sent, and the next flush() or close() commits + // them, as before rollback existed. It says so once per sender. assertMemoryLeak(() -> { ListAppender log = captureSenderLog(); try { @@ -1439,6 +1440,120 @@ public void testResetKeepsLegacyBehaviourWithoutServerRollback() throws Exceptio }); } + @Test + public void testResetThenCloseCommitsSentFramesWithoutServerRollback() throws Exception { + // In transaction=on against a server without rollback support, close() commits + // the deferred frames reset() kept -- on both a standalone sender and a pooled + // lease (whose close() calls flush()). The warning names flush() or close() and + // advises rollback() instead of close(). + assertMemoryLeak(() -> { + ListAppender log = captureSenderLog(); + try { + TxnServer standalone = new TxnServer(); + try (TestWebSocketServer server = start(standalone, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "transaction=on;")) { + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(standalone.awaitFrames(2)); + s.reset(); + } + assertOneTransaction(standalone); + Assert.assertTrue(standalone.frames.get(standalone.frames.size() - 1).isBareCommit()); + Assert.assertEquals(standalone.frames, standalone.committedFrames()); + Assert.assertEquals(1, server.upgradeRequestCount()); + } + Assert.assertEquals(Collections.singletonList(RESET_KEEPS_ROWS_WARNING), resetKeepsRowsWarnings(log)); + + clearLog(log); + TxnServer pooled = new TxnServer(); + try (TestWebSocketServer server = start(pooled, CAP)) { + try (QuestDB db = QuestDB.connect(conf(server) + "transaction=on;sender_pool_max=1;query_pool_min=0;")) { + Sender lease = db.borrowSender(); + writeRows(lease, "t", 0, 1_000); + Assert.assertTrue(pooled.awaitFrames(2)); + lease.reset(); + lease.close(); + } + assertOneTransaction(pooled); + Assert.assertTrue(pooled.frames.get(pooled.frames.size() - 1).isBareCommit()); + Assert.assertEquals(pooled.frames, pooled.committedFrames()); + Assert.assertEquals(1, server.upgradeRequestCount()); + } + Assert.assertEquals(Collections.singletonList(RESET_KEEPS_ROWS_WARNING), resetKeepsRowsWarnings(log)); + } finally { + releaseSenderLog(log); + } + }); + } + + @Test + public void testResetThenRollbackDiscardsSentFramesWithoutServerRollback() throws Exception { + // Following reset()'s warning advice -- calling rollback() after reset() on a + // server without rollback support -- discards the deferred frames already sent + // by closing the connection that holds them, whether the sender is then closed + // immediately, reused directly, or returned to a pool. + assertMemoryLeak(() -> { + ListAppender log = captureSenderLog(); + try { + // 1) reset() -> rollback() -> immediate close() (no drain()). + TxnServer closed = new TxnServer(); + try (TestWebSocketServer server = start(closed, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "transaction=on;")) { + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(closed.awaitFrames(2)); + s.reset(); + s.rollback(); + } + Assert.assertEquals(Collections.emptyList(), closed.committedFrames()); + Assert.assertEquals(0, closed.commitFrames()); + Assert.assertEquals(0, closed.rollbackFrames()); + } + Assert.assertEquals(Collections.singletonList(RESET_KEEPS_ROWS_WARNING), resetKeepsRowsWarnings(log)); + + // 2) reset() -> rollback() -> next transaction commits on a fresh connection. + clearLog(log); + TxnServer reused = new TxnServer(); + try (TestWebSocketServer server = start(reused, CAP)) { + try (Sender s = Sender.fromConfig(conf(server) + "transaction=on;")) { + writeRows(s, "t", 0, 1_000); + Assert.assertTrue(reused.awaitFrames(2)); + s.reset(); + s.rollback(); + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(s.drain(5_000)); + } + assertDiscardedByClosingConnection("reset() then rollback()", reused); + Assert.assertEquals(2, server.upgradeRequestCount()); + } + Assert.assertEquals(Collections.singletonList(RESET_KEEPS_ROWS_WARNING), resetKeepsRowsWarnings(log)); + + // 3) Pooled lease: reset() -> rollback() -> close() returns a healthy slot. + clearLog(log); + TxnServer pooled = new TxnServer(); + try (TestWebSocketServer server = start(pooled, CAP)) { + try (QuestDB db = QuestDB.connect(conf(server) + "transaction=on;sender_pool_max=1;query_pool_min=0;")) { + Sender lease = db.borrowSender(); + writeRows(lease, "t", 0, 1_000); + Assert.assertTrue(pooled.awaitFrames(2)); + lease.reset(); + lease.rollback(); + lease.close(); + Sender next = db.borrowSender(); + writeRows(next, "t", 0, 10); + next.flush(); + Assert.assertTrue(next.drain(5_000)); + next.close(); + } + assertDiscardedByClosingConnection("pooled reset() then rollback()", pooled); + Assert.assertEquals(2, server.upgradeRequestCount()); + } + Assert.assertEquals(Collections.singletonList(RESET_KEEPS_ROWS_WARNING), resetKeepsRowsWarnings(log)); + } finally { + releaseSenderLog(log); + } + }); + } + @Test public void testResetRollsBackSentFramesWhenServerSupportsIt() throws Exception { assertMemoryLeak(() -> { From e010cd8c4d0bae7d9189eeb8f0ac02c4579580ff Mon Sep 17 00:00:00 2001 From: bluestreak Date: Mon, 30 Nov 2026 02:35:40 +0000 Subject: [PATCH 19/20] Only refuse older servers for explicit transaction=strict Commit 4749d5d5 made WebSocket senders with no auto-flush trigger (such as auto_flush_rows=off;auto_flush_interval=off, which base 58e556ff accepted) strict transactional, and commit a46fcf20 made strict mode refuse every server whose 101 response omits X-QWP-Max-Uncommitted-Rows. Together those broke existing no-trigger senders whenever the client is upgraded before the server. Gate the connect-time X-QWP-Max-Uncommitted-Rows refusal on a separate volatile boolean requireStrictServer that is true only when strict mode was requested explicitly (transaction=strict, strictTransactional(true), or QwpWebSocketSender.setStrictTransactional(true)): - Explicit transaction=strict keeps failing fast with QwpStrictTransactionMismatchException against older servers (and keeps mixed-cluster skipping, failover ride-out, BackgroundDrainer settle budget, and late setStrictTransactional(true) refusal). - Implicit no-trigger senders (auto_flush_rows=off;auto_flush_interval=off, auto_flush=off, and builder equivalents) connect to older servers with a single WARN per sender while keeping client-side strict semantics immutable (close()/lease return discard, client-buffer and 1,000,000 default row limits, zero hot-path overhead, and no I/O-thread mode-flip races). - Align README.md and Javadocs on Sender, QwpStrictTransactionMismatchException, TransactionTooLargeException, and QwpConstants. - Update QwpLargeTransactionTest to cover explicit strict refusal and implicit no-trigger compatibility across all spellings, connect modes, reconnects, close() discard, client buffer refusal, and late explicit setStrictTransactional(true). --- README.md | 8 +- .../main/java/io/questdb/client/Sender.java | 24 ++- ...QwpStrictTransactionMismatchException.java | 7 +- .../qwp/client/QwpWebSocketSender.java | 47 ++++- .../client/TransactionTooLargeException.java | 9 +- .../cutlass/qwp/protocol/QwpConstants.java | 10 +- .../qwp/client/QwpLargeTransactionTest.java | 185 +++++++++++++++++- 7 files changed, 253 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index e8e47080b..335798532 100644 --- a/README.md +++ b/README.md @@ -737,9 +737,11 @@ it, and every pooled sender may hold one at once, so a strict transaction that s only its sender's share: `sf_max_total_bytes / sender_pool_max`, one segment less with `sf_dir`. A larger one fails with `TransactionTooLargeException`. So does one that holds more rows of a table than the server's `qwp.max.uncommitted.rows` when the sender learns that limit only after accepting them, as before its first connection: -the server refuses such a transaction rather than commit it in parts, and `rollback()` discards it. Strict mode -requires a server that advertises `X-QWP-Max-Uncommitted-Rows`; against older servers the sender fails at connect -with `QwpStrictTransactionMismatchException` rather than commit in parts (use `transaction=on` there). +the server refuses such a transaction rather than commit it in parts, and `rollback()` discards it. Explicit +`transaction=strict` requires a server that advertises `X-QWP-Max-Uncommitted-Rows`; against older servers the sender +fails at connect with `QwpStrictTransactionMismatchException` rather than commit in parts (use `transaction=on` there). +A sender that is strict only because it has no auto-flush trigger still connects to older servers with a warning and +client-side limits (assuming 1,000,000 uncommitted rows per table). `sf_durability=periodic` checkpoints mmap-published data in the background; `sf_sync_interval_millis` defaults to `5000` in that mode. The interval is a target cadence: JVM scheduling and storage-sync latency add to the actual loss window. Use `request_durable_ack=on` when end-to-end server durability is also required. See the diff --git a/core/src/main/java/io/questdb/client/Sender.java b/core/src/main/java/io/questdb/client/Sender.java index 5cd5b4575..54e3289c0 100644 --- a/core/src/main/java/io/questdb/client/Sender.java +++ b/core/src/main/java/io/questdb/client/Sender.java @@ -2851,12 +2851,15 @@ private LineSenderBuilder requestDurableAckTiers(int tiers) { * divided by {@code sender_pool_max}, less one segment with {@code sf_dir}. * A sender with no auto-flush trigger (see {@link #disableAutoFlush()}) is * in this mode unless {@link #transactional(boolean)} selects the mode. - * Requires a server that advertises {@code X-QWP-Max-Uncommitted-Rows} (and - * honours {@code FLAG_STRICT}); against an older server the sender fails at - * connect with - * {@link io.questdb.client.cutlass.qwp.client.QwpStrictTransactionMismatchException} - * rather than risk a silent partial commit. Use {@link #transactional(boolean) - * transaction=on} against older servers. + * Explicit {@code transaction=strict} (or calling this method) requires a + * server that advertises {@code X-QWP-Max-Uncommitted-Rows} (and honours + * {@code FLAG_STRICT}); against an older server the sender fails at connect + * with {@link io.questdb.client.cutlass.qwp.client.QwpStrictTransactionMismatchException} + * rather than risk a silent partial commit (use {@link #transactional(boolean) + * transaction=on} against older servers). A sender that is strict only + * because it has no auto-flush trigger connects to older servers with a + * warning and client-side limits (assuming 1,000,000 uncommitted rows per + * table). * WebSocket transport only. * * @param enabled true to enable strict transactional mode; false leaves @@ -3874,9 +3877,13 @@ private QwpWebSocketSender buildWebSocket(HttpTokenProvider tokenProvider) { wsEndpoints.add(new QwpWebSocketSender.Endpoint(hosts.getQuick(i), ports.getQuick(i))); } // With no auto-flush trigger only flush() commits: a strict transaction of - // any size, unless transaction= chose the mode. + // any size, unless transaction= chose the mode. Only an explicit + // transaction=strict (or strictTransactional(true)) refuses servers that + // omit X-QWP-Max-Uncommitted-Rows; an implicit no-trigger sender connects + // to older servers with a warning and client-side limits. boolean effectiveStrict = strictTransactional || (!transactionModeSet && !hasAutoFlushTrigger()); boolean effectiveTransactional = transactional || effectiveStrict; + boolean requireStrictServer = strictTransactional; // The recovery seed inside connect() is the authority on whether a recovered // slot can be replayed: it rebuilds the dictionary from its intact prefix and // then from the surviving frames' own delta sections, and throws @@ -3914,7 +3921,8 @@ private QwpWebSocketSender buildWebSocket(HttpTokenProvider tokenProvider) { actualSymbolDictResetMaxWaitMillis, keepaliveIntervalMillis, effectiveTransactional, - effectiveStrict + effectiveStrict, + requireStrictServer ); } catch (UnreplayableSlotException e) { // The one failure build() recovers from. The slot's frames reference ids diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpStrictTransactionMismatchException.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpStrictTransactionMismatchException.java index e4a885bda..b3cc83520 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpStrictTransactionMismatchException.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpStrictTransactionMismatchException.java @@ -25,9 +25,10 @@ package io.questdb.client.cutlass.qwp.client; /** - * The sender requires strict transactional mode ({@code transaction=strict}, or a - * WebSocket sender with no auto-flush trigger) but the server completed the - * WebSocket upgrade without advertising {@code X-QWP-Max-Uncommitted-Rows}. + * The sender explicitly requires strict transactional mode ({@code transaction=strict}, + * {@link io.questdb.client.Sender.LineSenderBuilder#strictTransactional(boolean)}, or + * {@link QwpWebSocketSender#setStrictTransactional(boolean)}) but the server completed + * the WebSocket upgrade without advertising {@code X-QWP-Max-Uncommitted-Rows}. *

    * Servers that omit {@code X-QWP-Max-Uncommitted-Rows} also predate * {@code FLAG_STRICT}: they silently ignore the flag and commit a table's diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java index 6efb33a51..5e13c1b62 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java @@ -743,9 +743,18 @@ public class QwpWebSocketSender implements Sender { // Strict transactional mode (transaction=strict, or a sender with no auto-flush // trigger): implies transactional, never lets an open transaction commit in // parts, and close() discards instead of committing. Volatile because - // buildAndConnect reads it on the I/O thread during reconnects. See + // connectWalk reads it on the I/O thread during reconnects. See // setStrictTransactional. private volatile boolean strictTransactional; + // True when strict mode was requested explicitly (transaction=strict or + // setStrictTransactional(true)): connectWalk refuses servers that omit + // X-QWP-Max-Uncommitted-Rows with QwpStrictTransactionMismatchException. + // False when strict mode was inferred from having no auto-flush triggers, so + // older servers connect with a one-time warning and client-side limits. + private volatile boolean requireStrictServer; + // Guarded by connectWalkLock (foreground connectWalk only): ensures the + // older-server strict-mode warning is logged at most once per sender. + private boolean isOldServerStrictWarned; // Strict mode only: set when the client buffer cannot take another deferred // frame of the open transaction and still commit it. Rejects further rows // until flush() or rollback() ends the transaction. The rows accepted before @@ -1371,15 +1380,17 @@ public static QwpWebSocketSender connectWithCredentialSupplier( authTimeoutMs, connectTimeoutMs, connectionListener, connectionListenerInboxCapacity, maxFrameRejections, poisonMinEscalationWindowMillis, catchUpCapGapMinEscalationWindowMillis, symbolDictResetEnabled, symbolDictResetThresholdSymbols, symbolDictResetMaxWaitMillis, - keepaliveIntervalMillis, false, false + keepaliveIntervalMillis, false, false, false ); } /** * Master connect entry point — also accepts the transactional mode flags - * ({@code transactional}, {@code strictTransactional}) before the initial - * handshake runs so strict mode can reject servers that do not advertise - * {@code X-QWP-Max-Uncommitted-Rows} at connect time. + * ({@code transactional}, {@code strictTransactional}, {@code requireStrictServer}) + * before the initial handshake runs so explicit strict mode can reject servers + * that do not advertise {@code X-QWP-Max-Uncommitted-Rows} at connect time, + * while an implicit no-trigger sender connects with a warning and client-side + * limits. * * @throws LineSenderException if either recycle setting is out of range */ @@ -1412,7 +1423,8 @@ public static QwpWebSocketSender connectWithCredentialSupplier( long symbolDictResetMaxWaitMillis, long keepaliveIntervalMillis, boolean transactional, - boolean strictTransactional + boolean strictTransactional, + boolean requireStrictServer ) { if (symbolDictResetThresholdSymbols <= 0 || symbolDictResetThresholdSymbols > QwpConstants.MAX_SYMBOL_DICTIONARY_SIZE / 2) { @@ -1453,7 +1465,7 @@ public static QwpWebSocketSender connectWithCredentialSupplier( : initialConnectMode; sender.setTransactional(transactional); if (strictTransactional) { - sender.setStrictTransactional(true); + sender.setStrictTransactional(true, requireStrictServer); } if (errorHandler != null) { sender.setErrorHandler(errorHandler); @@ -3951,12 +3963,17 @@ public void setRecycleDeferredCloseMaxWaitMillisForTesting(long millis) { * transactional mode; disabling it leaves transactional mode on. */ public void setStrictTransactional(boolean strict) { - if (strict && isServerStrictUnsupported) { + setStrictTransactional(strict, strict); + } + + private void setStrictTransactional(boolean strict, boolean requireStrictServer) { + if (strict && requireStrictServer && isServerStrictUnsupported) { int idx = currentEndpointIdx; Endpoint ep = idx >= 0 && idx < endpoints.size() ? endpoints.get(idx) : endpoints.get(0); throw new QwpStrictTransactionMismatchException(ep.host, ep.port); } this.strictTransactional = strict; + this.requireStrictServer = strict && requireStrictServer; // The server refuses a strict frame that would reach its limit, rather than // commit the transaction in parts. encoder.setStrict(strict); @@ -3977,6 +3994,7 @@ public void setTransactional(boolean transactional) { this.transactional = transactional; if (!transactional) { this.strictTransactional = false; + this.requireStrictServer = false; encoder.setStrict(false); } } @@ -4832,7 +4850,7 @@ private WebSocketClient connectWalk(ReconnectSupplier ctx, CursorWebSocketSendLo } continue; } - if (strictTransactional && newClient.getServerMaxUncommittedRows() <= 0) { + if (requireStrictServer && newClient.getServerMaxUncommittedRows() <= 0) { newClient.close(); hostTracker.recordRoleReject(idx, false, !background); QwpStrictTransactionMismatchException strictErr = @@ -4897,6 +4915,17 @@ private WebSocketClient connectWalk(ReconnectSupplier ctx, CursorWebSocketSendLo applyServerBatchSizeLimit(newClient.getServerMaxBatchSize()); applyServerTransactionLimits( newClient.getServerMaxUncommittedRows(), newClient.isServerRollbackEnabled()); + if (strictTransactional && !requireStrictServer + && newClient.getServerMaxUncommittedRows() <= 0 + && !isOldServerStrictWarned) { + isOldServerStrictWarned = true; + LOG.warn("server does not advertise X-QWP-Max-Uncommitted-Rows [host={}, port={}]; " + + "continuing with client-side strict limits (assuming {} uncommitted rows per table), " + + "but older servers ignore FLAG_STRICT and commit a table in parts if their " + + "qwp.max.uncommitted.rows is lower. Upgrade the server, set transaction=strict " + + "to fail fast against older servers, or set transaction=on for non-strict mode", + ep.host, ep.port, QwpConstants.DEFAULT_SERVER_MAX_UNCOMMITTED_ROWS); + } return newClient; } catch (Error e) { closeQuietlyOnError(newClient); diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java index 70ff58916..4ad8aac28 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java @@ -52,9 +52,12 @@ * with a lower setting. Then the transaction as a whole cannot commit as one, and the * server refuses it rather than commit it in parts: every row, {@code flush()} and * {@code drain()} of the transaction throws this exception until {@code rollback()}, - * {@code reset()} or {@code close()} discards the transaction. Servers that predate - * {@code X-QWP-Max-Uncommitted-Rows} and {@code FLAG_STRICT} are refused at connect - * with {@link QwpStrictTransactionMismatchException} instead. + * {@code reset()} or {@code close()} discards the transaction. Under explicit + * {@code transaction=strict}, servers that predate {@code X-QWP-Max-Uncommitted-Rows} + * and {@code FLAG_STRICT} are refused at connect with + * {@link QwpStrictTransactionMismatchException} instead; a sender that is strict + * only because it has no auto-flush trigger connects to such servers with a warning + * and client-side limits. */ public class TransactionTooLargeException extends LineSenderException { 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 c5312c3cc..a6c8fe2f1 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 @@ -39,10 +39,12 @@ public final class QwpConstants { /** * Default of the server's {@code qwp.max.uncommitted.rows}: the per-table * count of rows a deferred-commit group may hold before the server commits - * them on its own. A strict transaction assumes this value when the server - * does not advertise {@code X-QWP-Max-Uncommitted-Rows}, and before its first - * connection. A server whose limit turns out lower refuses a strict transaction - * past it rather than commit it in parts (see {@link #FLAG_STRICT}). + * them on its own. A strict transaction assumes this value before its first + * connection, and when an implicit no-trigger sender connects to a server + * that does not advertise {@code X-QWP-Max-Uncommitted-Rows} (explicit + * {@code transaction=strict} refuses such servers at connect). A server whose + * limit turns out lower refuses a strict transaction past it rather than + * commit it in parts (see {@link #FLAG_STRICT}). */ public static final long DEFAULT_SERVER_MAX_UNCOMMITTED_ROWS = 1_000_000L; /** diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index a6171c0d7..d58b495fa 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -1896,24 +1896,23 @@ public void testStrictRowLimitFromServer() throws Exception { @Test public void testStrictModeRejectsServerWithoutMaxUncommittedRowsHeader() throws Exception { // Servers that predate X-QWP-Max-Uncommitted-Rows also predate FLAG_STRICT and - // silently commit deferred rows in parts at their qwp.max.uncommitted.rows. A - // strict sender (explicit transaction=strict or no auto-flush triggers) must fail - // at connect rather than risk silent partial commits, while transaction=on keeps - // working against the same older server. + // silently commit deferred rows in parts at their qwp.max.uncommitted.rows. An + // explicit transaction=strict sender must fail at connect rather than risk silent + // partial commits, while transaction=on keeps working against the same older server. assertMemoryLeak(() -> { TxnServer h = new TxnServer(); try (TestWebSocketServer server = start(h, CAP)) { server.setAdvertisedMaxUncommittedRows(0); String[] strictModes = { "transaction=strict;", - "auto_flush=off;", - "auto_flush_rows=off;auto_flush_interval=off;", + "auto_flush=off;transaction=strict;", + "auto_flush_rows=off;auto_flush_interval=off;transaction=strict;", "transaction=strict;initial_connect_retry=sync;reconnect_max_duration_millis=60000;" }; for (String mode : strictModes) { long startNanos = System.nanoTime(); try (Sender ignored = Sender.fromConfig(conf(server) + mode)) { - Assert.fail("strict mode must reject a server advertising no X-QWP-Max-Uncommitted-Rows: " + mode); + Assert.fail("explicit strict mode must reject a server advertising no X-QWP-Max-Uncommitted-Rows: " + mode); } catch (QwpStrictTransactionMismatchException e) { Assert.assertEquals("localhost", e.getHost()); Assert.assertEquals(server.getPort(), e.getPort()); @@ -1930,6 +1929,12 @@ public void testStrictModeRejectsServerWithoutMaxUncommittedRowsHeader() throws Assert.assertTrue("capability mismatch must fail fast, took " + elapsedMs + "ms for " + mode, elapsedMs < 10_000L); } + try (QuestDB ignored = QuestDB.connect(conf(server) + "transaction=strict;query_pool_min=0;")) { + Assert.fail("QuestDB.connect with explicit transaction=strict must reject an older server"); + } catch (QwpStrictTransactionMismatchException e) { + Assert.assertEquals("localhost", e.getHost()); + Assert.assertEquals(server.getPort(), e.getPort()); + } Assert.assertEquals("zero frames must reach an incapable server", 0, h.frames.size()); // Enabling strict mode after connecting to an older server is also refused. @@ -1958,6 +1963,159 @@ public void testStrictModeRejectsServerWithoutMaxUncommittedRowsHeader() throws }); } + @Test + public void testNoAutoFlushTriggerConnectsToServerWithoutMaxUncommittedRowsHeaderWithWarning() throws Exception { + // A sender that is strict only because it has no auto-flush trigger (without an + // explicit transaction=strict) still connects to pre-#8343 servers that omit + // X-QWP-Max-Uncommitted-Rows: it logs a single WARN, keeps client-side strict + // semantics (close() discards, client buffer refuses), and commits on flush() in + // every connect mode. + assertMemoryLeak(() -> { + ListAppender log = captureSenderLog(); + try { + // 1. Every no-trigger spelling connects, warns once, commits on flush(), + // discards unflushed rows on close(), and rejects explicit late + // setStrictTransactional(true). + for (NoTriggerSpelling spelling : noTriggerSpellings()) { + clearLog(log); + TxnServer h = new TxnServer(); + List committed; + try (TestWebSocketServer server = start(h, CAP)) { + server.setAdvertisedMaxUncommittedRows(0); + try (Sender s = spelling.build(conf(server))) { + QwpWebSocketSender ws = (QwpWebSocketSender) s; + Assert.assertTrue(spelling.name, ws.isStrictTransactional()); + Assert.assertEquals(spelling.name, 0, ws.getServerMaxUncommittedRows()); + List warns = oldServerStrictWarnings(log); + Assert.assertEquals(spelling.name + ": expected one old-server WARN", 1, warns.size()); + TestUtils.assertContains(warns.get(0), "X-QWP-Max-Uncommitted-Rows"); + TestUtils.assertContains(warns.get(0), "FLAG_STRICT"); + TestUtils.assertContains(warns.get(0), "transaction=strict"); + TestUtils.assertContains(warns.get(0), "transaction=on"); + + // Explicit late setStrictTransactional(true) still refuses an older server + // and keeps the sender usable. + try { + ws.setStrictTransactional(true); + Assert.fail(spelling.name + ": explicit setStrictTransactional(true) must reject older server"); + } catch (QwpStrictTransactionMismatchException e) { + Assert.assertEquals("localhost", e.getHost()); + Assert.assertEquals(server.getPort(), e.getPort()); + } + Assert.assertTrue(spelling.name, ws.isStrictTransactional()); + + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(spelling.name, s.drain(5_000)); + committed = h.committedFrames(); + Assert.assertEquals(spelling.name, 1, committed.size()); + + // Reconnect must not repeat the one-time warning. + server.dropAllConnections(); + writeRows(s, "t", 10, 10); + s.flush(); + Assert.assertTrue(spelling.name, s.drain(5_000)); + committed = h.committedFrames(); + Assert.assertEquals(spelling.name, 2, committed.size()); + Assert.assertEquals(spelling.name + ": warning must be logged once per sender", + 1, oldServerStrictWarnings(log).size()); + + // close() without flush() still discards uncommitted rows. + writeRows(s, "t", 20, 1_000); + Assert.assertTrue(spelling.name, h.awaitFrames(committed.size() + 2)); + } + Assert.assertEquals(spelling.name + ": close() must discard unflushed rows", + committed, h.committedFrames()); + } + } + + // 2. auto_flush_rows=off;auto_flush_interval=off; commits across all connect + // modes (default, off, sync, async, QuestDB.connect default/sync/lazy/async) + // without any SenderError. + String noTriggers = "auto_flush_rows=off;auto_flush_interval=off;"; + String[] senderModes = { + noTriggers, + noTriggers + "initial_connect_retry=off;", + noTriggers + "initial_connect_retry=sync;reconnect_max_duration_millis=5000;", + noTriggers + "initial_connect_retry=async;", + noTriggers + "auto_flush_bytes=off;" + }; + for (String mode : senderModes) { + clearLog(log); + TxnServer h = new TxnServer(); + AtomicReference unexpectedErr = new AtomicReference<>(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setAdvertisedMaxUncommittedRows(0); + try (Sender s = Sender.builder(conf(server) + mode) + .errorHandler(err -> unexpectedErr.compareAndSet(null, err)) + .build()) { + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(mode, s.drain(5_000)); + } + } + Assert.assertNull(mode + ": unexpected async error", unexpectedErr.get()); + Assert.assertEquals(mode, 1, h.commitFrames()); + Assert.assertEquals(mode, 1, oldServerStrictWarnings(log).size()); + } + + String[] questDbModes = { + noTriggers, + noTriggers + "initial_connect_retry=sync;reconnect_max_duration_millis=5000;", + noTriggers + "lazy_connect=true;", + noTriggers + "initial_connect_retry=async;" + }; + for (String mode : questDbModes) { + clearLog(log); + TxnServer h = new TxnServer(); + AtomicReference unexpectedErr = new AtomicReference<>(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setAdvertisedMaxUncommittedRows(0); + server.setSendServerInfo(true); + try (QuestDB db = QuestDB.builder() + .fromConfig(conf(server) + mode) + .errorHandler(err -> unexpectedErr.compareAndSet(null, err)) + .build()) { + try (Sender s = db.borrowSender()) { + writeRows(s, "t", 0, 10); + s.flush(); + Assert.assertTrue(mode, s.drain(5_000)); + } + } + } + Assert.assertNull(mode + ": unexpected async error", unexpectedErr.get()); + Assert.assertEquals(mode, 1, h.commitFrames()); + Assert.assertEquals(mode, 1, oldServerStrictWarnings(log).size()); + } + + // 3. Client-side strict buffer limit still refuses oversize transactions + // instead of committing in parts. + TxnServer h = new TxnServer(); + try (TestWebSocketServer server = start(h, CAP)) { + server.setAdvertisedMaxUncommittedRows(0); + try (Sender s = Sender.fromConfig(conf(server) + + "auto_flush_rows=off;auto_flush_interval=off;" + + "sf_max_segment_bytes=64k;sf_max_total_bytes=128k;sf_append_deadline_millis=5000;")) { + boolean refused = false; + for (int i = 0; i < 5_000; i++) { + try { + writeRows(s, "t", i, 1); + } catch (TransactionTooLargeException e) { + refused = true; + break; + } + } + Assert.assertTrue("client-side strict buffer cap must still refuse oversize transactions", refused); + Assert.assertEquals("nothing may commit in parts", 0, h.commitFrames()); + s.rollback(); + } + } + } finally { + releaseSenderLog(log); + } + }); + } + @Test public void testStrictModeAsyncConnectLatchesTerminalAgainstOldServerWithoutSendingFrames() throws Exception { // An async strict sender may buffer rows and deferred frames before the first @@ -3142,6 +3300,19 @@ private static List noTriggerSpellings() { // The warnings reset() logged since the last clearLog() about keeping the rows a // transaction=on transaction already sent. + private static List oldServerStrictWarnings(ListAppender log) { + List warnings = new ArrayList<>(); + synchronized (log) { + for (ILoggingEvent e : log.list) { + String message = e.getFormattedMessage(); + if (e.getLevel() == Level.WARN && message.startsWith("server does not advertise X-QWP-Max-Uncommitted-Rows")) { + warnings.add(message); + } + } + } + return warnings; + } + private static List resetKeepsRowsWarnings(ListAppender log) { List warnings = new ArrayList<>(); synchronized (log) { From b12177fc79312f164b0ae69f36b29abf04f45f71 Mon Sep 17 00:00:00 2001 From: bluestreak Date: Mon, 30 Nov 2026 02:36:48 +0000 Subject: [PATCH 20/20] Latch pending rollback when rollback() fails to publish rollback(), reset() and discardTransactionForReuse() call discardPendingRows() before publishRollbackFrame(). When an outage fills the store-and-forward ring and the active segment has fewer than 20 raw bytes remaining (8-byte MmapSegment frame header + 12-byte rollback frame), appendBlocking() times out and throws, leaving unsent rows already dropped while the open transaction's sent deferred frames stay on the ring (hasDeferredMessages remains true). Any later flush(), drain(), or transaction=on close() (including PooledSender.close()) then committed the rolled-back rows -- and in strict mode committed only the sent subset of the transaction. Latch pendingRollbackAction before publishing the rollback frame, and clear it only once the frame reaches the ring (or when closing against a server without rollback support, where disconnect and orphan-tail recovery discard the frames): - Complete any pending rollback ahead of rollback(), reset(), discardTransactionForReuse(), table(), flushAndGetSequence() (and drain()), and close0(), so neither later rows nor a non-strict close() can ever commit the discarded frames. - Skip the non-strict flush/commit path in close0() when a rollback is pending, and suppress spurious strict uncommitted-discard warnings on close()/pool return after an explicit rollback(). - Document the pending-rollback behavior on Sender.rollback(), Sender.reset(), and QwpWebSocketSender. - Add regression tests in QwpLargeTransactionTest covering strict and transaction=on rollback()/reset() failures at 19 raw bytes remaining, in-place success at 20 raw bytes, retries, empty flush()/drain(), close() with and without server recovery or rollback support, strict close warning suppression, and pooled lease returns. --- .../main/java/io/questdb/client/Sender.java | 16 +- .../qwp/client/QwpWebSocketSender.java | 122 ++++- .../qwp/client/QwpLargeTransactionTest.java | 463 ++++++++++++++++++ 3 files changed, 575 insertions(+), 26 deletions(-) diff --git a/core/src/main/java/io/questdb/client/Sender.java b/core/src/main/java/io/questdb/client/Sender.java index 54e3289c0..c79147763 100644 --- a/core/src/main/java/io/questdb/client/Sender.java +++ b/core/src/main/java/io/questdb/client/Sender.java @@ -778,7 +778,10 @@ default void resetSymbolDictionary() { * {@link #flush()} that failed partway, as {@link #rollback()} does. The exception is a {@code transaction=on} sender that last * connected to a server without QWP rollback support: it keeps those rows, and the next * flush or close commits them, as before rollback existed; call {@link #rollback()} to - * discard them. + * discard them. If publishing the rollback request fails (for example because the + * store-and-forward buffer is full), buffered rows have already been discarded and the + * rollback remains pending until completed ahead of the next operation, so the + * discarded rows are never committed. *
    * Note: the ILP TCP and UDP transports don't support this operation. * @@ -794,9 +797,14 @@ default void resetSymbolDictionary() { *
    * Like {@link #flush()}, this returns without waiting for the server, so a * server outage makes it fail only when the store-and-forward buffer is full, - * as it would a flush. The request goes out ahead of anything sent later, so - * later rows never commit the discarded ones, even across reconnects. Call - * {@link #drain(long)} to wait until the server confirms. + * as it would a flush. If this call fails, buffered rows have already been + * discarded and the rollback remains pending: retrying {@code rollback()}, or + * the next {@link #table(CharSequence)}, {@link #flush()}, {@link #drain(long)}, + * {@link #reset()}, or {@link #close()} call, publishes the rollback request + * ahead of any later work (or throws again while the buffer stays full). The + * request goes out ahead of anything sent later, so later rows never commit + * the discarded ones, even across reconnects. Call {@link #drain(long)} to wait + * until the server confirms. *
    * A {@code transaction=on} transaction that already committed in parts (see * {@link LineSenderBuilder#transactional(boolean)}) keeps the parts it committed; diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java index 5e13c1b62..40a8213ae 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketSender.java @@ -784,6 +784,13 @@ public class QwpWebSocketSender implements Sender { // because the transaction outgrew the client buffer, 0 when it did not. Reset // with the transaction; committing a part keeps it. private long txnRowsCommittedInParts; + // Action ("rollback()", "reset()", ...) whose rollback frame failed to reach + // the ring after discardPendingRows() ran; null when no rollback is pending. + // While non-null, pendingRowCount == 0, currentTableBuffer == null and + // hasDeferredMessages == true. Completed ahead of any later table(), flush(), + // drain(), rollback(), reset(), discardTransactionForReuse() or close() so the + // discarded deferred frames can never commit. Producer thread only. + private String pendingRollbackAction; // Tables with rows in deferred frames of the open transaction, so a commit // or rollback resets only those tables' counters. Producer thread only. private final ObjList txnTables = new ObjList<>(); @@ -1981,7 +1988,26 @@ private void close0(boolean[] restoreInterrupt) { // sender to discard the batch, so honour that: // discard it, remember the error, and let the rest of // close() run. rethrowTerminal below still surfaces it. - if (strictTransactional) { + if (pendingRollbackAction != null) { + // A prior rollback()/reset() already discarded the pending rows + // and failed to publish the rollback frame. Never fall through to + // the non-strict commit path below: publish the rollback frame if + // the server supports it, or leave the deferred frames uncommitted + // for connection close / orphan-tail recovery to discard. + if (hasDeferredMessages && serverRollbackEnabled) { + try { + completePendingRollback(); + } catch (Throwable t) { + terminalError = captureCloseError(terminalError, t); + } + } else { + long committedRows = txnRowsCommittedInParts; + String action = pendingRollbackAction; + clearTransactionState(); + pendingRollbackAction = null; + warnRollbackCommittedInParts(action, committedRows); + } + } else if (strictTransactional) { // A strict transaction commits only on an explicit flush(), so // closing without one discards it. The pending rows never left the // client. The frames of the open transaction already sent stay @@ -2023,11 +2049,11 @@ private void close0(boolean[] restoreInterrupt) { if (!deferCommit && hasDeferredMessages) { sendCommitMessage(); } - } - if (!strictTransactional && activeBuffer != null && activeBuffer.hasData()) { - sealAndSwapBuffer(); - if (!deferCommit) { - lastCommitBoundaryFsn = cursorEngine.publishedFsn(); + if (activeBuffer != null && activeBuffer.hasData()) { + sealAndSwapBuffer(); + if (!deferCommit) { + lastCommitBoundaryFsn = cursorEngine.publishedFsn(); + } } } // 2) Safety-net rethrow: surface the latched terminal @@ -2485,6 +2511,9 @@ public long flushAndGetSequence() { } ensureNoInProgressRow(); ensureConnected(); + if (pendingRollbackAction != null) { + completePendingRollback(); + } long beforeFsn = cursorEngine != null ? cursorEngine.publishedFsn() : -1L; @@ -2722,6 +2751,11 @@ public boolean hasDeferredMessagesForTesting() { return hasDeferredMessages; } + @TestOnly + public boolean hasPendingRollbackForTesting() { + return pendingRollbackAction != null; + } + /** * Fabricates the state a step-2 close failure leaves behind -- an * abandoned recycle parked at CLOSE_LOOP -- on a loop that is genuinely @@ -3522,11 +3556,18 @@ public void setCloseStartedHook(Runnable hook) { * sent, and the next flush or close commits them, as before rollback existed; * call {@link #rollback()} to discard them. A transaction that sent no frames * yet ends on any server, so the next row starts a new one, also after the - * client buffer refused a row of a strict transaction. + * client buffer refused a row of a strict transaction. If publishing the + * rollback frame fails (for example because the store-and-forward buffer is + * full), buffered rows have already been discarded and the rollback stays + * pending so no later operation can commit the discarded frames. */ @Override public void reset() { checkNotClosed(); + if (pendingRollbackAction != null) { + completePendingRollback(); + return; + } discardPendingRows(); if (!hasDeferredMessages) { // No frame of the open transaction was sent, so there is nothing to roll @@ -3554,14 +3595,19 @@ public void reset() { *

    * Like {@link #flush()}, it hands the rollback frame to store-and-forward and * returns without waiting for the server, so a server outage makes it fail - * only when the store-and-forward buffer is full, as it would a flush. The - * frame goes out behind the transaction's frames and ahead of anything sent - * later, on every connection and after a restart, so nothing sent later can - * commit the discarded rows. A server that supports QWP rollback discards them - * on the frame. A server without that support never receives it: the sender - * closes the connection that holds the rows instead, which makes the server - * discard them, and reconnects. Call {@link #drain(long)} to wait until the - * rows are discarded. + * only when the store-and-forward buffer is full, as it would a flush. If + * publishing the rollback frame fails, the buffered rows have already been + * discarded and the rollback remains pending: retrying {@code rollback()}, or + * the next {@link #table(CharSequence)}, {@link #flush()}, {@link #drain(long)}, + * {@link #reset()}, or {@link #close()} call, publishes the rollback frame + * ahead of any later work (or throws again while the buffer stays full), so + * nothing sent later can commit the discarded rows. The frame goes out behind + * the transaction's frames and ahead of anything sent later, on every + * connection and after a restart. A server that supports QWP rollback discards + * them on the frame. A server without that support never receives it: the + * sender closes the connection that holds the rows instead, which makes the + * server discard them, and reconnects. Call {@link #drain(long)} to wait until + * the rows are discarded. *

    * A transaction=on transaction that already committed in parts, at the * client buffer or the server's {@code qwp.max.uncommitted.rows}, keeps the @@ -3571,6 +3617,10 @@ public void reset() { public void rollback() { checkNotClosed(); checkRecycleFailure(); + if (pendingRollbackAction != null) { + completePendingRollback(); + return; + } discardPendingRows(); if (!hasDeferredMessages) { clearTransactionState(); @@ -3587,6 +3637,10 @@ public void rollback() { */ public void discardTransactionForReuse() { checkNotClosed(); + if (pendingRollbackAction != null) { + completePendingRollback(); + return; + } warnDiscardedTransaction("returning the sender to the pool"); discardPendingRows(); if (!hasDeferredMessages) { @@ -3665,13 +3719,34 @@ private void publishRollbackFrame() { * {@code action} names the call in the warning that says so. */ private void rollbackOpenTransaction(String action) { - long committedRows = txnRowsCommittedInParts; - publishRollbackFrame(); - // The rollback frame gets an OK ack covering the transaction's frames, or the - // I/O loop acknowledges it when it discards the transaction itself, so - // close-time drains may wait for it like for a commit. - lastCommitBoundaryFsn = cursorEngine.publishedFsn(); - clearTransactionState(); + if (pendingRollbackAction == null) { + pendingRollbackAction = action; + } + completePendingRollback(); + } + + private void completePendingRollback() { + if (pendingRollbackAction == null) { + return; + } + String action = pendingRollbackAction; + if (hasDeferredMessages) { + long committedRows = txnRowsCommittedInParts; + publishRollbackFrame(); + // The rollback frame gets an OK ack covering the transaction's frames, or the + // I/O loop acknowledges it when it discards the transaction itself, so + // close-time drains may wait for it like for a commit. + lastCommitBoundaryFsn = cursorEngine.publishedFsn(); + clearTransactionState(); + pendingRollbackAction = null; + warnRollbackCommittedInParts(action, committedRows); + } else { + clearTransactionState(); + pendingRollbackAction = null; + } + } + + private static void warnRollbackCommittedInParts(String action, long committedRows) { if (committedRows > 0) { LOG.warn("{} discarded the rows of the open transaction sent since the sender last committed part of " + "it, but the {} rows it committed when the transaction outgrew the client buffer stay " @@ -4178,6 +4253,9 @@ public QwpWebSocketSender symbol(CharSequence columnName, CharSequence value) { public QwpWebSocketSender table(CharSequence tableName) { checkNotClosed(); checkRecycleFailure(); + if (pendingRollbackAction != null) { + completePendingRollback(); + } if (recycleResume != RecycleResume.NONE) { resumeRecycleIfPending(); } else if (resetArmed) { diff --git a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java index d58b495fa..322f633d3 100644 --- a/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java +++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java @@ -40,8 +40,10 @@ import io.questdb.client.cutlass.qwp.client.QwpWebSocketSender; import io.questdb.client.cutlass.qwp.client.TransactionTooLargeException; import io.questdb.client.cutlass.qwp.client.WebSocketResponse; +import io.questdb.client.cutlass.qwp.client.sf.cursor.MmapSegment; import io.questdb.client.cutlass.qwp.client.sf.cursor.SegmentBudget; import io.questdb.client.cutlass.qwp.protocol.QwpConstants; +import io.questdb.client.impl.PooledSender; import io.questdb.client.impl.SenderPool; import io.questdb.client.test.cutlass.qwp.websocket.TestWebSocketServer; import io.questdb.client.test.tools.TestUtils; @@ -3228,6 +3230,467 @@ public void testTransactionOffPartlySentSplitRetryDuringOutageSendsEachTableOnce assertRetryOfPartlySentSplitSendsEachTableOnce("transaction=off;"); } + @Test + public void testRollbackFailureOnFullRingNeverCommitsOnNextTransaction() throws Exception { + // When a full ring leaves < 20 raw bytes in the active segment (8-byte MmapSegment + // frame header + 12-byte rollback frame), rollback() fails on append backpressure + // after discarding pending rows. The rollback stays latched: while the ring stays + // full, table() and flush() also throw; once the server returns, the next transaction + // publishes the rollback frame first so zero rolled-back rows commit. + assertFailedDiscardNeverCommitsOnNextTransaction("transaction=strict;", Sender::rollback); + assertFailedDiscardNeverCommitsOnNextTransaction("transaction=on;", Sender::rollback); + } + + @Test + public void testResetFailureOnFullRingNeverCommitsOnNextTransaction() throws Exception { + assertFailedDiscardNeverCommitsOnNextTransaction("transaction=strict;", Sender::reset); + assertFailedDiscardNeverCommitsOnNextTransaction("transaction=on;", Sender::reset); + } + + @Test + public void testRollbackFailureOnFullRingRetryDiscardsRows() throws Exception { + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + TxnServer before = new TxnServer(); + TxnServer after = new TxnServer(); + TestWebSocketServer revived = null; + int fillers; + int deferred; + try (TestWebSocketServer first = start(before, OUTAGE_SPLIT_CAP, port, true)) { + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(fullRingRollbackConf(port, "transaction=strict;"))) { + first.close(); + fillers = fillFourSegmentRingDuringOutage(s); + deferred = packDeferredFramesLeavingRawBytes(s, 19); + writeRows(s, "t_rolled_back", 10_000, 5); + + assertBackpressured(() -> s.rollback()); + Assert.assertTrue(s.hasPendingRollbackForTesting()); + Assert.assertTrue(s.hasDeferredMessagesForTesting()); + Assert.assertEquals(0L, s.getPendingBytes()); + + revived = start(after, OUTAGE_SPLIT_CAP, port, true); + Assert.assertTrue(after.awaitFrames(fillers)); + s.rollback(); + Assert.assertFalse(s.hasPendingRollbackForTesting()); + Assert.assertFalse(s.hasDeferredMessagesForTesting()); + + writeRows(s, "t_next", 20_000, 3); + s.flush(); + Assert.assertTrue(s.drain(10_000)); + } + } finally { + if (revived != null) { + revived.close(); + } + } + Assert.assertEquals(0, before.frames.size()); + Assert.assertEquals(TestUtils.repeat("C", fillers) + TestUtils.repeat("D", deferred) + "RC", frameKinds(after)); + Assert.assertEquals(1, after.rolledBackGroups); + Assert.assertEquals(fillers + 1, after.committedFrames().size()); + }); + } + + @Test + public void testRollbackFailureOnFullRingEmptyFlushAndDrainDiscardInsteadOfCommit() throws Exception { + // After a failed rollback(), calling flushAndGetSequence() / drain() with no new rows + // must publish the latched rollback frame rather than sendCommitMessage(). + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + TxnServer before = new TxnServer(); + TxnServer after = new TxnServer(); + TestWebSocketServer revived = null; + int fillers; + int deferred; + try (TestWebSocketServer first = start(before, OUTAGE_SPLIT_CAP, port, true)) { + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(fullRingRollbackConf(port, "transaction=on;"))) { + first.close(); + fillers = fillFourSegmentRingDuringOutage(s); + deferred = packDeferredFramesLeavingRawBytes(s, 19); + writeRows(s, "t_rolled_back", 10_000, 5); + + assertBackpressured(() -> s.rollback()); + Assert.assertTrue(s.hasPendingRollbackForTesting()); + + revived = start(after, OUTAGE_SPLIT_CAP, port, true); + Assert.assertTrue(after.awaitFrames(fillers)); + // Empty flush completes the rollback and returns -1 (no user batch published). + Assert.assertEquals(-1L, s.flushAndGetSequence()); + Assert.assertFalse(s.hasPendingRollbackForTesting()); + Assert.assertFalse(s.hasDeferredMessagesForTesting()); + Assert.assertTrue(s.drain(10_000)); + } + } finally { + if (revived != null) { + revived.close(); + } + } + Assert.assertEquals(0, before.frames.size()); + Assert.assertEquals(TestUtils.repeat("C", fillers) + TestUtils.repeat("D", deferred) + "R", frameKinds(after)); + Assert.assertEquals(1, after.rolledBackGroups); + Assert.assertEquals(fillers, after.committedFrames().size()); + }); + } + + @Test + public void testTransactionOnCloseAfterFailedRollbackNeverCommits() throws Exception { + // After a failed rollback(), close() on a transaction=on sender must complete the + // rollback rather than fall into the non-strict commit path: both when the server + // returned before close() and when the server stays down past the append deadline. + for (boolean serverReturnsBeforeClose : new boolean[]{true, false}) { + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + TxnServer before = new TxnServer(); + TxnServer after = new TxnServer(); + TestWebSocketServer revived = null; + int fillers; + int deferred; + try (TestWebSocketServer first = start(before, OUTAGE_SPLIT_CAP, port, true)) { + String closeTimeout = serverReturnsBeforeClose ? "" : "close_flush_timeout_millis=0;"; + QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig( + fullRingRollbackConf(port, "transaction=on;") + closeTimeout); + try { + first.close(); + fillers = fillFourSegmentRingDuringOutage(s); + deferred = packDeferredFramesLeavingRawBytes(s, 19); + writeRows(s, "t_rolled_back", 10_000, 5); + + assertBackpressured(() -> s.rollback()); + Assert.assertTrue(s.hasPendingRollbackForTesting()); + + if (serverReturnsBeforeClose) { + revived = start(after, OUTAGE_SPLIT_CAP, port, true); + Assert.assertTrue(after.awaitFrames(fillers)); + } + } finally { + if (serverReturnsBeforeClose) { + s.close(); + } else { + // Server stays down: close() fails to publish the rollback frame, + // surfaces the error, and never falls through to sendCommitMessage(). + assertBackpressured(s::close); + Assert.assertTrue(s.hasDeferredMessagesForTesting()); + } + } + } finally { + if (revived != null) { + revived.close(); + } + } + Assert.assertEquals(0, before.frames.size()); + if (serverReturnsBeforeClose) { + Assert.assertEquals(TestUtils.repeat("C", fillers) + TestUtils.repeat("D", deferred) + "R", + frameKinds(after)); + Assert.assertEquals(1, after.rolledBackGroups); + Assert.assertEquals(fillers, after.committedFrames().size()); + } + }); + } + } + + @Test + public void testRollbackFailureWithoutServerRollbackNeverCommitsOnNextTxnOrClose() throws Exception { + // Against a server without X-QWP-Rollback, a latched pending rollback still never + // commits: the next transaction sends the rollback frame through the I/O loop's + // retireRollbackFrame() (which closes and reconnects), and close() drops the + // uncommitted frames on disconnect without sending a commit. + for (boolean closeDirectly : new boolean[]{false, true}) { + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + TxnServer before = new TxnServer(); + TxnServer after = new TxnServer(); + TestWebSocketServer revived = null; + int fillers; + try (TestWebSocketServer first = start(before, OUTAGE_SPLIT_CAP, port, false)) { + QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(fullRingRollbackConf(port, "transaction=on;")); + try { + first.close(); + fillers = fillFourSegmentRingDuringOutage(s); + packDeferredFramesLeavingRawBytes(s, 19); + writeRows(s, "t_rolled_back", 10_000, 5); + + assertBackpressured(() -> s.rollback()); + Assert.assertTrue(s.hasPendingRollbackForTesting()); + + revived = start(after, OUTAGE_SPLIT_CAP, port, false); + Assert.assertTrue(after.awaitFrames(fillers)); + if (!closeDirectly) { + writeRows(s, "t_next", 20_000, 3); + s.flush(); + Assert.assertTrue(s.drain(10_000)); + } + } finally { + s.close(); + } + } finally { + if (revived != null) { + revived.close(); + } + } + Assert.assertEquals(0, before.frames.size()); + Assert.assertEquals(0, after.rollbackFrames()); + int expectedCommits = closeDirectly ? fillers : fillers + 1; + Assert.assertEquals(expectedCommits, after.committedFrames().size()); + for (TxnFrame f : after.committedFrames()) { + Assert.assertTrue("no deferred frame may commit: " + after.committedFrames(), f.isCommit()); + } + }); + } + } + + @Test + public void testStrictCloseAfterFailedRollbackSuppressesUncommittedWarning() throws Exception { + assertMemoryLeak(() -> { + ListAppender log = captureSenderLog(); + try { + int port = TestPorts.findUnusedPort(); + TxnServer before = new TxnServer(); + TxnServer after = new TxnServer(); + TestWebSocketServer revived = null; + int fillers; + int deferred; + try (TestWebSocketServer first = start(before, OUTAGE_SPLIT_CAP, port, true)) { + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(fullRingRollbackConf(port, "transaction=strict;"))) { + first.close(); + fillers = fillFourSegmentRingDuringOutage(s); + deferred = packDeferredFramesLeavingRawBytes(s, 19); + writeRows(s, "t_rolled_back", 10_000, 5); + + assertBackpressured(() -> s.rollback()); + Assert.assertTrue(s.hasPendingRollbackForTesting()); + + revived = start(after, OUTAGE_SPLIT_CAP, port, true); + Assert.assertTrue(after.awaitFrames(fillers)); + } + } finally { + if (revived != null) { + revived.close(); + } + } + Assert.assertEquals(Collections.emptyList(), discardWarnings(log)); + Assert.assertEquals(TestUtils.repeat("C", fillers) + TestUtils.repeat("D", deferred) + "R", frameKinds(after)); + Assert.assertEquals(fillers, after.committedFrames().size()); + } finally { + releaseSenderLog(log); + } + }); + } + + @Test + public void testPooledLeaseReturnAfterFailedRollbackNeverCommits() throws Exception { + // PooledSender.close() calls live.flush() for transaction=on and + // discardTransactionForReuse() for strict. After a failed rollback() on a full + // ring, returning the lease once the server is back must publish the rollback + // frame, commit zero rolled-back rows, and keep the sender reusable. + for (String mode : new String[]{"transaction=on;", "transaction=strict;"}) { + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + TxnServer before = new TxnServer(); + TxnServer after = new TxnServer(); + TestWebSocketServer revived = null; + int fillers; + int deferred; + try (TestWebSocketServer first = start(before, OUTAGE_SPLIT_CAP, port, true)) { + try (QuestDB db = QuestDB.connect(fullRingRollbackConf(port, mode) + + "sender_pool_max=1;query_pool_min=0;")) { + Sender lease = db.borrowSender(); + QwpWebSocketSender ws = (QwpWebSocketSender) ((PooledSender) lease).getDelegateForTesting(); + first.close(); + fillers = fillFourSegmentRingDuringOutage(ws); + deferred = packDeferredFramesLeavingRawBytes(ws, 19); + writeRows(lease, "t_rolled_back", 10_000, 5); + + assertBackpressured(lease::rollback); + Assert.assertTrue(ws.hasPendingRollbackForTesting()); + + revived = start(after, OUTAGE_SPLIT_CAP, port, true); + Assert.assertTrue(after.awaitFrames(fillers)); + // Lease return completes the rollback without committing T1. + lease.close(); + Assert.assertFalse(ws.hasPendingRollbackForTesting()); + + Sender next = db.borrowSender(); + writeRows(next, "t_next", 20_000, 3); + next.flush(); + Assert.assertTrue(next.drain(10_000)); + next.close(); + } + } finally { + if (revived != null) { + revived.close(); + } + } + Assert.assertEquals(0, before.frames.size()); + Assert.assertEquals(mode, TestUtils.repeat("C", fillers) + TestUtils.repeat("D", deferred) + "RC", + frameKinds(after)); + Assert.assertEquals(mode, 1, after.rolledBackGroups); + Assert.assertEquals(mode, fillers + 1, after.committedFrames().size()); + }); + } + } + + @Test + public void testRollbackSucceedsInPlaceAtExactly20RawBytes() throws Exception { + // Exact boundary: 8-byte MmapSegment frame header + 12-byte rollback frame = 20 bytes. + // With 20 raw bytes left in the active segment of a full ring, rollback() succeeds + // immediately in-place without rotating or latching a pending rollback. + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + TxnServer before = new TxnServer(); + TxnServer after = new TxnServer(); + TestWebSocketServer revived = null; + int fillers; + int deferred; + try (TestWebSocketServer first = start(before, OUTAGE_SPLIT_CAP, port, true)) { + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(fullRingRollbackConf(port, "transaction=strict;"))) { + first.close(); + fillers = fillFourSegmentRingDuringOutage(s); + deferred = packDeferredFramesLeavingRawBytes(s, 20); + writeRows(s, "t_rolled_back", 10_000, 5); + + assertDiscardDoesNotWait(s, Sender::rollback); + Assert.assertFalse(s.hasPendingRollbackForTesting()); + Assert.assertFalse(s.hasDeferredMessagesForTesting()); + Assert.assertEquals(0L, rawBytesRemaining(s)); + + revived = start(after, OUTAGE_SPLIT_CAP, port, true); + writeRows(s, "t_next", 20_000, 3); + s.flush(); + Assert.assertTrue(s.drain(10_000)); + } + } finally { + if (revived != null) { + revived.close(); + } + } + Assert.assertEquals(0, before.frames.size()); + Assert.assertEquals(TestUtils.repeat("C", fillers) + TestUtils.repeat("D", deferred) + "RC", frameKinds(after)); + Assert.assertEquals(1, after.rolledBackGroups); + Assert.assertEquals(fillers + 1, after.committedFrames().size()); + }); + } + + private static void assertFailedDiscardNeverCommitsOnNextTransaction(String mode, Consumer discard) throws Exception { + assertMemoryLeak(() -> { + int port = TestPorts.findUnusedPort(); + TxnServer before = new TxnServer(); + TxnServer after = new TxnServer(); + TestWebSocketServer revived = null; + int fillers; + int deferred; + try (TestWebSocketServer first = start(before, OUTAGE_SPLIT_CAP, port, true)) { + try (QwpWebSocketSender s = (QwpWebSocketSender) Sender.fromConfig(fullRingRollbackConf(port, mode))) { + first.close(); + fillers = fillFourSegmentRingDuringOutage(s); + deferred = packDeferredFramesLeavingRawBytes(s, 19); + writeRows(s, "t_rolled_back", 10_000, 5); + Assert.assertEquals(5, s.getTableBuffer("t_rolled_back").getRowCount()); + + assertBackpressured(() -> discard.accept(s)); + Assert.assertTrue(mode, s.hasPendingRollbackForTesting()); + Assert.assertTrue(mode, s.hasDeferredMessagesForTesting()); + Assert.assertEquals(mode, 0, s.getTableBuffer("t_rolled_back").getRowCount()); + Assert.assertEquals(mode, 0L, s.getPendingBytes()); + + // While the ring is still full, starting a new row or flushing must + // retry the pending rollback and fail rather than accept rows or commit. + assertBackpressured(() -> s.table("t_next")); + Assert.assertTrue(mode, s.hasPendingRollbackForTesting()); + assertBackpressured(s::flush); + Assert.assertTrue(mode, s.hasPendingRollbackForTesting()); + + // Server comes back; app does not retry rollback(), just writes T2 and flushes. + revived = start(after, OUTAGE_SPLIT_CAP, port, true); + Assert.assertTrue(after.awaitFrames(fillers)); + writeRows(s, "t_next", 20_000, 3); + Assert.assertFalse(mode, s.hasPendingRollbackForTesting()); + s.flush(); + Assert.assertTrue(s.drain(10_000)); + } + } finally { + if (revived != null) { + revived.close(); + } + } + Assert.assertEquals(0, before.frames.size()); + Assert.assertEquals(mode, TestUtils.repeat("C", fillers) + TestUtils.repeat("D", deferred) + "RC", + frameKinds(after)); + Assert.assertEquals(mode, 1, after.rolledBackGroups); + List expectedCommitted = new ArrayList<>(after.frames.subList(0, fillers)); + expectedCommitted.add(after.frames.get(after.frames.size() - 1)); + Assert.assertEquals(mode, expectedCommitted, after.committedFrames()); + }); + } + + private static void assertBackpressured(Runnable action) { + try { + action.run(); + Assert.fail("expected cursor SF append backpressure"); + } catch (LineSenderException e) { + TestUtils.assertContains(e.getMessage(), "cursor SF append failed"); + TestUtils.assertContains(e.getCause().getMessage(), "cursor ring backpressured"); + } + } + + private static String fullRingRollbackConf(int port, String mode) { + return "ws::addr=localhost:" + port + + ";reconnect_initial_backoff_millis=10;reconnect_max_backoff_millis=50;" + + "close_flush_timeout_millis=5000;" + + mode + + "auto_flush_bytes=off;auto_flush_rows=10;auto_flush_interval=off;" + + "sf_max_segment_bytes=64k;sf_max_total_bytes=256k;" + + "sf_append_deadline_millis=300;"; + } + + private static long rawBytesRemaining(QwpWebSocketSender s) { + MmapSegment seg = s.getCursorEngineForTesting().activeSegment(); + return seg.sizeBytes() - seg.publishedOffset(); + } + + // Commits ~39 KiB filler frames (one per 64 KiB segment) until all 4 segments of the + // 256 KiB ring are live, leaving ~26 KiB free in the 4th (active) segment. + private static int fillFourSegmentRingDuringOutage(QwpWebSocketSender s) { + int fillers = 0; + String bigPad = TestUtils.repeat("f", 7_800); + while (s.getCursorEngineForTesting().getRingForTesting().liveSegmentCount() < 4) { + for (int r = 0; r < 5; r++) { + s.table("filler").longColumn("v", fillers * 10L + r).stringColumn("s", bigPad).atNow(); + } + s.flush(); + fillers++; + Assert.assertTrue("must reach 4 live segments", fillers <= 10); + } + Assert.assertEquals(4, s.getCursorEngineForTesting().getRingForTesting().liveSegmentCount()); + return fillers; + } + + // Sends 10-row auto-flushed deferred frames into the active segment until exactly + // targetRawBytes remain before segment end (e.g. 19 to force rotation, 20 to fit in place). + private static int packDeferredFramesLeavingRawBytes(QwpWebSocketSender s, long targetRawBytes) { + int deferredFrames = 0; + while (rawBytesRemaining(s) > 5_000) { + writeRows(s, "t_rolled_back", deferredFrames * 10, 10); + deferredFrames++; + } + long rawBeforeCalib = rawBytesRemaining(s); + for (int r = 0; r < 9; r++) { + s.table("t_rolled_back").longColumn("v", 50_000L + r).stringColumn("s", "").atNow(); + } + s.table("t_rolled_back").longColumn("v", 50_009L).stringColumn("s", TestUtils.repeat("c", 500)).atNow(); + deferredFrames++; + long baseOverhead = (rawBeforeCalib - rawBytesRemaining(s)) - 500; + + int finalPadLen = (int) (rawBytesRemaining(s) - targetRawBytes - baseOverhead); + Assert.assertTrue("finalPadLen must stay in 2-byte varint range [128, 16383]: " + finalPadLen, + finalPadLen >= 128 && finalPadLen <= 16_383); + for (int r = 0; r < 9; r++) { + s.table("t_rolled_back").longColumn("v", 60_000L + r).stringColumn("s", "").atNow(); + } + s.table("t_rolled_back").longColumn("v", 60_009L).stringColumn("s", TestUtils.repeat("z", finalPadLen)).atNow(); + deferredFrames++; + Assert.assertEquals(targetRawBytes, rawBytesRemaining(s)); + return deferredFrames; + } + // Captures what QwpWebSocketSender logs, so a test can assert its warnings. private static ListAppender captureSenderLog() { ListAppender appender = new ListAppender<>();