diff --git a/README.md b/README.md index 232e64fb..33579853 100644 --- a/README.md +++ b/README.md @@ -732,6 +732,16 @@ 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`. 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. 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/QuestDB.java b/core/src/main/java/io/questdb/client/QuestDB.java index 8cfc437b..02a0cb6d 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 d16e9780..c7914776 100644
--- a/core/src/main/java/io/questdb/client/Sender.java
+++ b/core/src/main/java/io/questdb/client/Sender.java
@@ -773,13 +773,55 @@ 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 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 or close commits them, as before rollback existed; call {@link #rollback()} to
+ * 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.
*
* @see #flush()
*/
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 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,
+ * 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;
+ * this discards only the rest.
+ *
+ * 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
+ */
+ 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 +1117,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
@@ -1118,10 +1163,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;
@@ -1234,7 +1281,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
@@ -1385,7 +1437,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
@@ -1397,6 +1455,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")
@@ -1455,7 +1515,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()}. * @@ -1868,9 +1930,17 @@ 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. 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) @@ -1885,10 +1955,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; } @@ -2757,12 +2831,78 @@ 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}, 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 + * 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} + * 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. + * 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 + * {@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. 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
+ * 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
@@ -2772,6 +2912,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;
}
@@ -3022,7 +3166,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) {
@@ -3043,9 +3189,13 @@ 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 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.
*
* @param budget the shared budget, or {@code null} for a private one
* (the default)
@@ -3734,6 +3884,14 @@ 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. 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
@@ -3769,7 +3927,10 @@ private QwpWebSocketSender buildWebSocket(HttpTokenProvider tokenProvider) {
symbolDictReset,
actualSymbolDictResetThreshold,
actualSymbolDictResetMaxWaitMillis,
- keepaliveIntervalMillis
+ keepaliveIntervalMillis,
+ effectiveTransactional,
+ effectiveStrict,
+ requireStrictServer
);
} catch (UnreplayableSlotException e) {
// The one failure build() recovers from. The slot's frames reference ids
@@ -3821,7 +3982,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);
try {
final String rebuildSfDir = sfDir;
final String rebuildSenderId = senderId;
@@ -4230,8 +4390,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 +4844,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 +4985,7 @@ public java.util.Map
+ * 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 97b991bd..b2f27ec8 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 e8a58e5d..2f1b3f92 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("
+ * 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/QwpWebSocketEncoder.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpWebSocketEncoder.java
index f38d9e93..2304f1b4 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);
@@ -229,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 1fc43484..40a8213a 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,13 @@
*/
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.
+ */
+ 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
@@ -174,8 +182,23 @@ 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
+ // 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
@@ -188,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,
@@ -254,6 +279,12 @@ public class QwpWebSocketSender implements Sender {
private final ObjList
+ * 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. 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
+ * parts it committed; this discards only the rest.
+ */
+ @Override
+ public void rollback() {
+ checkNotClosed();
+ checkRecycleFailure();
+ if (pendingRollbackAction != null) {
+ completePendingRollback();
+ return;
+ }
+ discardPendingRows();
+ if (!hasDeferredMessages) {
+ clearTransactionState();
+ return;
+ }
+ rollbackOpenTransaction("rollback()");
+ }
+
+ /**
+ * Pool hook for a strict-mode lease being returned: discards what the
+ * 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 void discardTransactionForReuse() {
+ checkNotClosed();
+ if (pendingRollbackAction != null) {
+ completePendingRollback();
+ return;
+ }
+ warnDiscardedTransaction("returning the sender to the pool");
+ discardPendingRows();
+ if (!hasDeferredMessages) {
+ clearTransactionState();
+ return;
+ }
+ rollbackOpenTransaction("returning the sender to the pool");
+ }
+
+ private void discardPendingRows() {
// Reset ALL table buffers, not just the current one
ObjList
+ * 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 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.
+ */
+ private void rollbackOpenTransaction(String action) {
+ 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 "
+ + "committed", action, committedRows);
+ }
+ }
+
/**
* Advisory request to start a fresh symbol-dictionary epoch. Sets
* {@link #manualResetRequested}; if no flush is in flight
@@ -3400,6 +3872,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 +4023,55 @@ public void setRecycleDeferredCloseMaxWaitMillisForTesting(long millis) {
this.recycleDeferredCloseMaxWaitMillis = 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 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. 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) {
+ 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);
+ if (strict) {
+ this.transactional = true;
+ }
+ }
+
+ /**
+ * Transactional mode: auto-flush ships rows as FLAG_DEFER_COMMIT frames and
+ * 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;
+ if (!transactional) {
+ this.strictTransactional = false;
+ this.requireStrictServer = false;
+ encoder.setStrict(false);
+ }
}
/**
@@ -3732,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) {
@@ -3755,8 +4279,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
@@ -3886,44 +4409,32 @@ private static List
- * 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;
+ isServerStrictUnsupported = maxUncommittedRows <= 0;
+ serverRollbackEnabled = rollbackEnabled;
+ isServerRollbackDeclined = !rollbackEnabled;
}
private void atMicros(long timestampMicros) {
@@ -4256,6 +4767,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
@@ -4414,6 +4928,23 @@ private WebSocketClient connectWalk(ReconnectSupplier ctx, CursorWebSocketSendLo
}
continue;
}
+ if (requireStrictServer && 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) {
@@ -4460,6 +4991,19 @@ 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());
+ 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);
@@ -4761,9 +5305,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
@@ -5189,8 +5737,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;
}
@@ -5202,6 +5754,7 @@ private void flushPendingRows(boolean deferCommit) {
if (tableCount == 0) {
clearPendingTables();
pendingBytes = 0;
+ pendingSymbolDictBytes = 0;
currentTableBufferSnapshotBytes = currentTableBuffer == null
? 0 : currentTableBuffer.getBufferedBytes();
pendingRowCount = 0;
@@ -5233,6 +5786,39 @@ private void flushPendingRows(boolean deferCommit) {
int combinedBodyStart = encodeCombinedFrame(tableCount, deferCommit, deltaBaseline);
int messageSize = encoder.finishMessage();
+ // 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();
+ }
+ }
+
// 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
@@ -5263,7 +5849,9 @@ private void flushPendingRows(boolean deferCommit) {
// 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
@@ -5298,14 +5886,14 @@ && splitFramesFit(cap, currentBatchMaxSymbolId)) {
// advance the delta baseline so the next frame ships only newer ids.
advanceSentMaxSymbolId();
- hasDeferredMessages = deferCommit;
if (!deferCommit) {
lastCommitBoundaryFsn = cursorEngine.publishedFsn();
}
+ accountTransactionRows(deferCommit);
resetTableBuffersAfterFlush();
} catch (Throwable t) {
- if (dictionaryChunksAwaitCommit) {
+ if (dictionaryChunksAwaitCommit && !transactional) {
commitOrphanedDictionaryChunks(t);
}
throw t;
@@ -5371,21 +5959,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:
+ *
+ * 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
+ * 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 strict refusal it
+ * records the size the transaction would have reached in
+ * {@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;
+ long segmentPayload = segmentPayloadCapacity();
+ transactionFrameSizes.clear();
+ if (cap <= 0 || messageSize <= cap) {
+ transactionFrameSizes.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--) {
+ transactionFrameSizes.add(cap);
+ }
+ baseline = currentBatchMaxSymbolId;
+ }
+ for (int i = 0, n = splitFrameBodyBytes.size(); i < n; i++) {
+ 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 = transactionFrameSizes.size(); i < n; i++) {
+ long size = transactionFrameSizes.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);
+ }
+ // 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
+ // 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 capacity = engine.ringCapacityBytes();
+ if (segments > Math.max(2, capacity / engine.segmentSizeBytes())) {
+ if (strictTransactional) {
+ txnRefusedBytes = bytes;
+ txnRefusedSharers = 0;
+ }
+ 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) {
+ int sharers = engine.budgetSharers();
+ if (sharers > 1 && segments > Math.max(2, engine.shareSegments(capacity, sharers))) {
+ txnRefusedBytes = bytes;
+ txnRefusedSharers = sharers;
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * 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 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;
+ }
+
+ /**
+ * 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.
+ *
+ * {@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.
+ *
+ * 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. 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 {
+
+ public TransactionTooLargeException(CharSequence message) {
+ super(message);
+ }
+}
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 9b6cb8e2..a955ed13 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/BackgroundDrainer.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/BackgroundDrainer.java
index f1e574c0..c593e6bd 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/CursorSendEngine.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorSendEngine.java
index ba46365a..70c2686c 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,51 @@ 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();
+ }
+
+ /**
+ * 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().effectiveSharers();
+ }
+
+ /**
+ * 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) {
+ 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;
+ 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/CursorWebSocketSendLoop.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/CursorWebSocketSendLoop.java
index 8a76edcc..d24fc682 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().
@@ -591,6 +591,34 @@ 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;
+ // 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
@@ -1097,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;
}
@@ -1151,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
@@ -1271,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:
@@ -1361,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;
}
@@ -1607,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
@@ -2237,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.
@@ -2254,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,
@@ -2270,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) {
@@ -3152,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.
@@ -3198,6 +3251,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 +3287,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
@@ -3899,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;
@@ -4001,6 +4093,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
@@ -4023,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 {
@@ -4063,6 +4162,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 +4216,217 @@ 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 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
+ * 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"));
+ }
+
+ // 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:
+ *
@@ -4707,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/client/sf/cursor/SegmentBudget.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/sf/cursor/SegmentBudget.java
index be7c5a6b..dbe7e85d 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;
@@ -38,7 +39,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 +60,9 @@
public final class SegmentBudget {
private final long capacityBytes;
+ // 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
// grows out-of-band on producer threads, so an incremental mirror would
@@ -66,13 +72,39 @@ 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
+ * 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);
+ }
+
+ /**
+ * 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;
+ this.effectiveSharers = maxSharers;
}
/**
@@ -86,6 +118,24 @@ public long getCapacityBytes() {
return capacityBytes;
}
+ @TestOnly
+ public int getEffectiveSharersForTesting() {
+ return effectiveSharers;
+ }
+
+ /**
+ * 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;
+ }
+
public synchronized long getSegmentBytes() {
return segmentBytes;
}
@@ -99,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 7d3f5f56..f71791b9 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.
*
@@ -493,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);
}
@@ -597,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/main/java/io/questdb/client/cutlass/qwp/protocol/QwpConstants.java b/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpConstants.java
index 0fa7a645..a6c8fe2f 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,17 @@ 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 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;
/**
* 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 +61,23 @@ 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: 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
@@ -108,6 +136,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 02f95b91..e999db07 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,11 +73,22 @@ 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 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) {
this(tableName, null);
@@ -99,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.
*
@@ -216,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.
*
@@ -282,6 +322,15 @@ public String getTableName() {
return tableName;
}
+ /**
+ * 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;
+ }
+
/**
* Returns true if a row is partially built (columns written but not yet committed
* via {@link #nextRow()}).
@@ -426,6 +475,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 a9ef418a..45c7524b 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;
@@ -47,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
@@ -167,7 +170,16 @@ 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();
+ 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, as
+ // rollback() does, and the next borrower starts with no open
+ // transaction.
+ ((QwpWebSocketSender) live).discardTransactionForReuse();
+ } else {
+ live.flush();
+ }
flushed = true;
} finally {
if (flushed) {
@@ -341,6 +353,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/main/java/io/questdb/client/impl/SenderPool.java b/core/src/main/java/io/questdb/client/impl/SenderPool.java
index e63bd6ab..c1040f92 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/QuestDBBuilderTest.java b/core/src/test/java/io/questdb/client/test/QuestDBBuilderTest.java
index e304df95..d1571390 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,18 +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 disables
- // auto-flush (unsupported on WebSocket), also when auto_flush_bytes is set, 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;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;",
+ "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");
+ "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/SenderErrorTest.java b/core/src/test/java/io/questdb/client/test/SenderErrorTest.java
index 10e91d13..a0be66e4 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/http/client/WebSocketClientTest.java b/core/src/test/java/io/questdb/client/test/cutlass/http/client/WebSocketClientTest.java
index cc8c78aa..fdde0e56 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 fbc833d8..390168fd 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 1d83dff2..f69a5851 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,28 @@ public void testDefaultIsAsync() {
}
@Test
- public void testDisableAutoFlush_notSupportedForWebSocket() {
- 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(),
- "not supported for WebSocket");
+ .disableAutoFlush()
+ .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
@@ -790,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
new file mode 100644
index 00000000..322f633d
--- /dev/null
+++ b/core/src/test/java/io/questdb/client/test/cutlass/qwp/client/QwpLargeTransactionTest.java
@@ -0,0 +1,4612 @@
+/*+*****************************************************************************
+ * ___ _ ____ ____
+ * / _ \ _ _ ___ ___| |_| _ \| __ )
+ * | | | | | | |/ _ \/ __| __| | | | _ \
+ * | |_| | |_| | __/\__ \ |_| |_| | |_) |
+ * \__\_\\__,_|\___||___/\__|____/|____/
+ *
+ * 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 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.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;
+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;
+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.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+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.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;
+
+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;
+ // 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";
+ // 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);
+ // 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() 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";
+ // 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.
+ 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 {
+ // 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(() -> {
+ 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());
+ }
+ }
+ });
+ }
+
+ @Test
+ 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(() -> {
+ 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]");
+ });
+ }
+
+ @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 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 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
+ * 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 {
+ // 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
+ * 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);
+ // 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";
+
+ @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
+ * 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
@@ -5068,8 +5242,13 @@ 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 (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/SenderError.java b/core/src/main/java/io/questdb/client/SenderError.java
index 672a6987..fb5b20ad 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/http/client/WebSocketClient.java b/core/src/main/java/io/questdb/client/cutlass/http/client/WebSocketClient.java
index 938d5175..4eaf9a7a 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
+ *
+ * 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
@@ -5476,62 +6068,128 @@ 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();
+ }
+ 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();
+ }
+
+ /**
+ * 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);
}
- resetTableBuffersAfterFlush();
+ return buffer;
}
private void onSlotLockReleased() {
@@ -5546,6 +6204,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
@@ -5554,6 +6219,7 @@ private void resetTableBuffersAfterFlush() {
flushTableBuffers.setPos(0);
currentBatchMaxSymbolId = -1;
pendingBytes = 0;
+ pendingSymbolDictBytes = 0;
currentTableBufferSnapshotBytes = 0;
pendingRowCount = 0;
firstPendingRowTimeNanos = 0;
@@ -6459,8 +7125,8 @@ private void sendCommitMessage() {
activeBuffer.write(buffer.getBufferPtr(), messageSize);
activeBuffer.incrementRowCount();
sealAndSwapBuffer();
- hasDeferredMessages = false;
lastCommitBoundaryFsn = cursorEngine.publishedFsn();
+ clearTransactionState();
}
private SenderErrorHandler userErrorHandler() {
@@ -6764,9 +7430,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
@@ -6802,7 +7470,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;
@@ -6842,17 +7510,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();
}
/**
@@ -7110,15 +7773,37 @@ private void sealAndSwapBuffer() {
// (durable mmap append, returns once published).
try {
toSend.markSending();
- cursorEngine.appendBlocking(toSend.getBufferPtr(), toSend.getBufferPos());
+ 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 && isDeferredFrame;
+ long activeRemaining = isTxnFrame && txnSimSegments == 0
+ ? cursorEngine.activeSegment().capacityRemaining() : 0;
+ 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.
+ if (!isDeferredFrame) {
+ txnFirstFsn = -1L;
+ } else if (!hasDeferredMessages) {
+ txnFirstFsn = cursorEngine.publishedFsn();
+ }
+ hasDeferredMessages = isDeferredFrame;
+ if (isTxnFrame) {
+ recordTransactionFrame(payloadLen, activeRemaining);
+ }
toSend.markRecycled();
} catch (Throwable t) {
// appendBlocking failed synchronously on the user thread — the
// 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();
@@ -7135,6 +7820,468 @@ 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++) {
+ 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;
+ }
+ checkTransactionNotRefused();
+ if (txnBufferFull) {
+ throw transactionTooLargeForClientBuffer("so the row was not added");
+ }
+ 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
+ // 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) {
+ // 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)
+ .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.");
+ if (firstSpelling.getNextSpelling() != null) {
+ 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
+ *
+ */
+ 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) {
+ effectiveAutoFlushBytes = (int) budget;
+ } else {
+ effectiveAutoFlushBytes = 0;
+ }
+ }
+
+ /**
+ * 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;
+ 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;
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * 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
+ * have reached, the buffer, what was refused, and the settings that make room.
+ */
+ private LineSenderException transactionTooLargeForClientBuffer(String outcome) {
+ CursorSendEngine engine = cursorEngine;
+ 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())
+ .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())
+ .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
+ * 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 + 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 "
+ + "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).
@@ -7142,6 +8289,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
@@ -7179,7 +8332,7 @@ private void sendRow() {
currentTableBufferSnapshotBytes = bufferedNow;
if (shouldAutoFlush()) {
- flushPendingRows(transactional);
+ flushPendingRows(transactional, true);
}
}
@@ -7193,7 +8346,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 00000000..4ad8aac2
--- /dev/null
+++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/TransactionTooLargeException.java
@@ -0,0 +1,67 @@
+/*+*****************************************************************************
+ * ___ _ ____ ____
+ * / _ \ _ _ ___ ___| |_| _ \| __ )
+ * | | | | | | |/ _ \/ __| __| | | | _ \
+ * | |_| | |_| | __/\__ \ |_| |_| | |_) |
+ * \__\_\\__,_|\___||___/\__|____/|____/
+ *
+ * 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 a sender with no auto-flush
+ * 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. 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.
+ *
+ *
+ * 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.
* > 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 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
+ // 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
+ // 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 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
> 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
+ // 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 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 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;
+ 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();
+ 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);
+ }
+ }
+ });
+ }
+
+ @Test
+ public void testStrictTransactionTooLargeForClientBufferFailsFast() throws Exception {
+ // 64 KiB segments, 256 KiB budget: four segments. A strict transaction keeps
+ // 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();
+ 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();
+ long refusedBytes = -1;
+ try {
+ 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) {
+ // 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));
+ // 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) {
+ 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();
+ Assert.assertTrue(s.drain(5_000));
+ }
+ }
+ });
+ }
+
+ @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));
+ assertDiscardDoesNotWait(s, Sender::rollback);
+ writeRows(s, "t", 0, 10);
+ s.flush();
+ Assert.assertTrue(s.drain(5_000));
+ }
+ assertRolledBackThenCommitted(h);
+ }
+ });
+ }
+
+ @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
> 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
> 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) {
+ 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;
+ }
+
+ private static final class Connection {
+ // Deferred frames the connection holds uncommitted.
+ final List
> groups = new ArrayList<>();
+ private final List