You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by gk...@apache.org on 2026/06/30 15:59:55 UTC
(iggy) branch fix_integration_tests_rest created (now 8653e5d93)
This is an automated email from the ASF dual-hosted git repository.
numinnex pushed a change to branch fix_integration_tests_rest
in repository https://gitbox.apache.org/repos/asf/iggy.git
at 8653e5d93 fixes
This branch includes the following new commits:
new 8653e5d93 fixes
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(iggy) 01/01: fixes
Posted by gk...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
numinnex pushed a commit to branch fix_integration_tests_rest
in repository https://gitbox.apache.org/repos/asf/iggy.git
commit 8653e5d9346fb40268f8f803365d73a9342db37f
Author: Grzegorz Koszyk <g....@gmail.com>
AuthorDate: Tue Jun 30 16:59:58 2026 +0200
fixes
---
Cargo.lock | 1 +
core/common/src/error/iggy_error.rs | 2 +
core/configs/src/server_config/sharding.rs | 2 +-
core/consensus/src/impls.rs | 23 ++-
core/consensus/src/metadata_helpers.rs | 24 ++-
core/consensus/src/plane_helpers.rs | 59 +++++++
core/integration/tests/sdk/raw.rs | 2 +-
core/integration/tests/server/cg_vsr.rs | 14 +-
.../tests/server/concurrent_addition.rs | 12 +-
core/integration/tests/server/mod.rs | 3 +-
...onsumer_group_duplicate_name_create_scenario.rs | 11 +-
core/integration/tests/server/scenarios/mod.rs | 1 -
core/message_bus/Cargo.toml | 1 +
core/message_bus/src/transports/quic.rs | 176 ++++++++++++++-----
core/metadata/src/impls/metadata.rs | 190 ++++++++++++++++++---
core/sdk/src/quic/quic_client.rs | 179 +++++++++++++++----
core/sdk/src/tcp/tcp_client.rs | 189 +++++++++++---------
core/sdk/src/vsr.rs | 10 +-
core/sdk/src/websocket/websocket_client.rs | 173 +++++++++++--------
core/server-ng/src/auth.rs | 40 ++++-
core/server-ng/src/responses.rs | 33 +++-
core/shard/src/lib.rs | 12 ++
22 files changed, 867 insertions(+), 290 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 1f867651e..a0f83de2f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -8287,6 +8287,7 @@ dependencies = [
"ahash 0.8.12",
"async-channel",
"blake3",
+ "bytemuck",
"bytes",
"compio",
"compio-quic",
diff --git a/core/common/src/error/iggy_error.rs b/core/common/src/error/iggy_error.rs
index 22f1308c8..4bae28138 100644
--- a/core/common/src/error/iggy_error.rs
+++ b/core/common/src/error/iggy_error.rs
@@ -120,6 +120,8 @@ pub enum IggyError {
UsersLimitReached = 55,
#[error("Invalid personal access token expiry")]
InvalidPersonalAccessTokenExpiry = 56,
+ #[error("Request transiently not committed; retry")]
+ TransientNotCommitted = 57,
#[error("Not connected")]
NotConnected = 61,
#[error("Client shutdown")]
diff --git a/core/configs/src/server_config/sharding.rs b/core/configs/src/server_config/sharding.rs
index 7434f9167..ec332462b 100644
--- a/core/configs/src/server_config/sharding.rs
+++ b/core/configs/src/server_config/sharding.rs
@@ -25,7 +25,7 @@ use configs::ConfigEnv;
/// Default capacity of the per-shard inter-shard inbox channel. Sized
/// comfortably above the consensus working set, which is roughly
-/// `PIPELINE_PREPARE_QUEUE_MAX (= 8) * replica_count * directions`
+/// `PIPELINE_PREPARE_QUEUE_MAX (= 32) * replica_count * directions`
/// frames in flight per shard, without allowing a runaway producer to
/// eat unbounded memory. Tunable via `[system.sharding] inbox_capacity`
/// in TOML.
diff --git a/core/consensus/src/impls.rs b/core/consensus/src/impls.rs
index 0edcb2fee..53bb8aaac 100644
--- a/core/consensus/src/impls.rs
+++ b/core/consensus/src/impls.rs
@@ -85,7 +85,14 @@ impl Sequencer for LocalSequencer {
/// TODO The below numbers need to be added a consensus config
/// TODO understand how to configure these numbers.
/// Maximum number of prepares that can be in-flight in the pipeline.
-pub const PIPELINE_PREPARE_QUEUE_MAX: usize = 8;
+///
+/// Sized to absorb a synchronized client burst (e.g. the 20-way
+/// concurrent-creation race tests across TCP/QUIC/WebSocket) without
+/// `PipelineFull`-rejecting and disconnecting clients that cannot replay in
+/// time. At depth 8 the QUIC burst wedges the metadata consensus even in
+/// release. Stays well under the journal's `SLOT_COUNT` (1024) and the inbox
+/// capacity headroom.
+pub const PIPELINE_PREPARE_QUEUE_MAX: usize = 32;
/// Max accepted-but-not-yet-prepared requests buffered behind a full
/// prepare queue. Beyond this, requests drop and the client retries.
@@ -777,6 +784,20 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
pub fn advance_commit_max(&self, commit: u64) {
if commit > self.commit_max.get() {
self.commit_max.set(commit);
+ // A prepare just committed. Re-arm the prepare-retransmit timer for
+ // the next-oldest pending prepare rather than letting it inherit the
+ // previous op's grown backoff: the push-site `start` is a no-op
+ // while ticking and nothing else clears `attempts`, so under
+ // sustained load the backoff ratchets up to 16x base and the tail
+ // op's retransmit fires too rarely to recover a lost backup ack,
+ // stalling commit. `start` (not `reset`) forces the timer ticking
+ // at the base interval - `reset` alone leaves `ticking` untouched,
+ // so a timer stopped earlier would be armed-but-dead and never
+ // fire. When nothing is pending the timer self-stops via the
+ // empty-pipeline branch in `handle_prepare_timeout`.
+ if self.sequencer.current_sequence() > commit {
+ self.timeouts.borrow_mut().start(TimeoutKind::Prepare);
+ }
}
assert!(self.commit_max.get() >= self.commit_min.get());
}
diff --git a/core/consensus/src/metadata_helpers.rs b/core/consensus/src/metadata_helpers.rs
index 2622d4bf3..b2a4ecfdc 100644
--- a/core/consensus/src/metadata_helpers.rs
+++ b/core/consensus/src/metadata_helpers.rs
@@ -46,8 +46,13 @@ pub enum PreflightOutcome {
/// Session gone (`NoSession`) or rotated past the retry (`SessionTooLow`):
/// the client must be told with an eviction frame.
Evict(EvictionReason),
- /// Absorbed with nothing to send: in-flight prepare, not-caught-up
- /// primary, stale/gap retry, or a client-bug newer session.
+ /// Transient: the request could not be committed *right now* but a replay of
+ /// the same `request_id` is expected to succeed (in-flight prepare,
+ /// not-caught-up primary). The caller sends a `TransientNotCommitted` reply
+ /// so the client replays immediately instead of waiting out its read-timeout.
+ NotReady,
+ /// Absorbed with nothing to send: stale/gap retry or a client-bug newer
+ /// session. Replaying the same `request_id` cannot help, so stay silent.
Drop,
}
@@ -77,9 +82,9 @@ where
tracing::debug!(
client_id,
request,
- "request_preflight: in-flight prepare, drop"
+ "request_preflight: in-flight prepare, not ready"
);
- return PreflightOutcome::Drop;
+ return PreflightOutcome::NotReady;
}
// Catch-up gate: stale ClientTable on a new primary could return `New`
@@ -95,9 +100,9 @@ where
is_syncing = consensus.is_syncing(),
commit_min = consensus.commit_min(),
commit_max = consensus.commit_max(),
- "request_preflight: not caught up, drop"
+ "request_preflight: not caught up, not ready"
);
- return PreflightOutcome::Drop;
+ return PreflightOutcome::NotReady;
}
let status = client_table
@@ -172,7 +177,12 @@ where
send_eviction_to_client(consensus, client_id, reason).await;
false
}
- PreflightOutcome::Drop => false,
+ // The wire-ingress plane has no per-request transport context to build a
+ // correlated `TransientNotCommitted` reply (that lives on the in-process
+ // home-shard path); stay silent here as before. NotReady and Drop both
+ // mean "do not dispatch"; the difference (explicit retry frame) only
+ // applies where the request header is in scope.
+ PreflightOutcome::NotReady | PreflightOutcome::Drop => false,
}
}
diff --git a/core/consensus/src/plane_helpers.rs b/core/consensus/src/plane_helpers.rs
index f40562cb3..1d921edf0 100644
--- a/core/consensus/src/plane_helpers.rs
+++ b/core/consensus/src/plane_helpers.rs
@@ -334,6 +334,65 @@ where
.expect("reply buffer must contain a valid reply message")
}
+/// Builds a `Reply` carrying only a metadata result section, no payload.
+///
+/// For a request that could not be committed *right now* (not-caught-up /
+/// in-flight / pipeline-full / view-change cancel): the body is
+/// `[count=1][index=0][result=code]`. The SDK decodes the nonzero `result` to a
+/// typed retryable error (`IggyError::TransientNotCommitted`) and replays the
+/// same `request_id` immediately, instead of waiting out its response
+/// read-timeout.
+///
+/// Stamped from the request header (no prepare exists for an uncommitted op).
+/// `commit` is the primary's current commit position and is informational here:
+/// a transient reply is sent, never cached in the `ClientTable`, so it is not
+/// subject to the `commit_reply` regression order.
+///
+/// # Panics
+/// If the constructed message buffer is not a valid reply.
+#[must_use]
+#[allow(clippy::cast_possible_truncation)]
+pub fn build_transient_reply(
+ request_header: &RequestHeader,
+ commit: u64,
+ code: u32,
+) -> Message<ReplyHeader> {
+ // `[count: u32][index: u32][result: u32]`, the single-entry rejection shape
+ // of `ApplyReply::write_reply_body` (mirrored here to avoid a metadata dep).
+ const RESULT_BODY_LEN: usize = 12;
+ let header_size = std::mem::size_of::<ReplyHeader>();
+ let total_size = header_size + RESULT_BODY_LEN;
+ let mut buffer = bytes::BytesMut::zeroed(total_size);
+
+ let header = bytemuck::checked::try_from_bytes_mut::<ReplyHeader>(&mut buffer[..header_size])
+ .expect("zeroed bytes are valid");
+ *header = ReplyHeader {
+ cluster: request_header.cluster,
+ size: total_size as u32,
+ view: request_header.view,
+ release: request_header.release,
+ command: Command2::Reply,
+ replica: request_header.replica,
+ request_checksum: request_header.request_checksum,
+ client: request_header.client,
+ op: request_header.session,
+ commit,
+ timestamp: request_header.timestamp,
+ request: request_header.request,
+ operation: request_header.operation,
+ namespace: request_header.namespace,
+ ..Default::default()
+ };
+
+ let body = &mut buffer[header_size..];
+ body[0..4].copy_from_slice(&1u32.to_le_bytes());
+ body[4..8].copy_from_slice(&0u32.to_le_bytes());
+ body[8..12].copy_from_slice(&code.to_le_bytes());
+
+ Message::try_from(Owned::<4096>::copy_from_slice(buffer.as_ref()))
+ .expect("transient reply buffer must contain a valid reply message")
+}
+
/// Reply for fast paths that skip the VSR pipeline (e.g. `AckLevel::NoAck`).
///
/// Stamps `op` and `commit` with `commit_max` — monotonic, so
diff --git a/core/integration/tests/sdk/raw.rs b/core/integration/tests/sdk/raw.rs
index f507603ac..cffeec954 100644
--- a/core/integration/tests/sdk/raw.rs
+++ b/core/integration/tests/sdk/raw.rs
@@ -32,7 +32,7 @@ async fn given_authenticated_client_when_sending_raw_request_should_round_trip(
}
#[cfg(feature = "vsr")]
-#[iggy_harness(test_client_transport = [Tcp, WebSocket])]
+#[iggy_harness(test_client_transport = [Tcp, WebSocket, Quic])]
async fn given_authenticated_client_when_sending_raw_request_should_round_trip(
harness: &TestHarness,
) {
diff --git a/core/integration/tests/server/cg_vsr.rs b/core/integration/tests/server/cg_vsr.rs
index 2448b41e1..ecf595a89 100644
--- a/core/integration/tests/server/cg_vsr.rs
+++ b/core/integration/tests/server/cg_vsr.rs
@@ -29,7 +29,7 @@ use crate::server::scenarios::{
use integration::iggy_harness;
#[iggy_harness(
- test_client_transport = [Tcp],
+ test_client_transport = [Tcp, WebSocket, Quic],
server(tcp.socket.override_defaults = true, tcp.socket.nodelay = true)
)]
async fn duplicate_name_create_preserves_live_group(harness: &TestHarness) {
@@ -37,7 +37,7 @@ async fn duplicate_name_create_preserves_live_group(harness: &TestHarness) {
}
#[iggy_harness(
- test_client_transport = [Tcp],
+ test_client_transport = [Tcp, WebSocket, Quic],
server(tcp.socket.override_defaults = true, tcp.socket.nodelay = true)
)]
async fn join(harness: &TestHarness) {
@@ -45,7 +45,7 @@ async fn join(harness: &TestHarness) {
}
#[iggy_harness(
- test_client_transport = [Tcp],
+ test_client_transport = [Tcp, WebSocket, Quic],
server(tcp.socket.override_defaults = true, tcp.socket.nodelay = true)
)]
async fn single_client(harness: &TestHarness) {
@@ -53,7 +53,7 @@ async fn single_client(harness: &TestHarness) {
}
#[iggy_harness(
- test_client_transport = [Tcp],
+ test_client_transport = [Tcp, WebSocket, Quic],
server(tcp.socket.override_defaults = true, tcp.socket.nodelay = true)
)]
async fn multiple_clients(harness: &TestHarness) {
@@ -61,7 +61,7 @@ async fn multiple_clients(harness: &TestHarness) {
}
#[iggy_harness(
- test_client_transport = [Tcp],
+ test_client_transport = [Tcp, WebSocket, Quic],
server(tcp.socket.override_defaults = true, tcp.socket.nodelay = true)
)]
async fn offset_cleanup(harness: &TestHarness) {
@@ -69,7 +69,7 @@ async fn offset_cleanup(harness: &TestHarness) {
}
#[iggy_harness(
- test_client_transport = [Tcp],
+ test_client_transport = [Tcp, WebSocket, Quic],
server(tcp.socket.override_defaults = true, tcp.socket.nodelay = true)
)]
async fn auto_commit_reconnection(harness: &TestHarness) {
@@ -77,7 +77,7 @@ async fn auto_commit_reconnection(harness: &TestHarness) {
}
#[iggy_harness(
- test_client_transport = [Tcp],
+ test_client_transport = [Tcp, WebSocket, Quic],
server(tcp.socket.override_defaults = true, tcp.socket.nodelay = true)
)]
async fn new_messages_after_restart(harness: &TestHarness) {
diff --git a/core/integration/tests/server/concurrent_addition.rs b/core/integration/tests/server/concurrent_addition.rs
index ff1a4347e..e590078f1 100644
--- a/core/integration/tests/server/concurrent_addition.rs
+++ b/core/integration/tests/server/concurrent_addition.rs
@@ -37,12 +37,19 @@ use test_case::test_matrix;
quic.max_idle_timeout = "500s",
quic.keep_alive_interval = "15s"
))]
-#[test_matrix(
+// vsr excludes HTTP only (server-ng exposes no HTTP listener).
+#[cfg_attr(not(feature = "vsr"), test_matrix(
[tcp(), http(), quic(), websocket()],
[user(), stream(), topic(), partition(), consumer_group()],
[hot(), cold()],
[barrier_on(), barrier_off()]
-)]
+))]
+#[cfg_attr(feature = "vsr", test_matrix(
+ [tcp(), quic(), websocket()],
+ [user(), stream(), topic(), partition(), consumer_group()],
+ [hot(), cold()],
+ [barrier_on(), barrier_off()]
+))]
async fn matrix(
harness: &TestHarness,
transport: TransportProtocol,
@@ -57,6 +64,7 @@ fn tcp() -> TransportProtocol {
TransportProtocol::Tcp
}
+#[cfg(not(feature = "vsr"))]
fn http() -> TransportProtocol {
TransportProtocol::Http
}
diff --git a/core/integration/tests/server/mod.rs b/core/integration/tests/server/mod.rs
index 53e8c70a4..eaed6e591 100644
--- a/core/integration/tests/server/mod.rs
+++ b/core/integration/tests/server/mod.rs
@@ -25,8 +25,7 @@ mod cg;
#[cfg(feature = "vsr")]
mod cg_vsr;
// 80-case race matrix with hardcoded HTTP variants (test_matrix bypasses
-// the harness transport filter); revisit under vsr once basics are green.
-#[cfg(not(feature = "vsr"))]
+// the harness transport filter).
mod concurrent_addition;
mod general;
// The per-shard segment cleaner deletes expired / oversize segments from disk
diff --git a/core/integration/tests/server/scenarios/consumer_group_duplicate_name_create_scenario.rs b/core/integration/tests/server/scenarios/consumer_group_duplicate_name_create_scenario.rs
index fa1b928cb..71c310d5b 100644
--- a/core/integration/tests/server/scenarios/consumer_group_duplicate_name_create_scenario.rs
+++ b/core/integration/tests/server/scenarios/consumer_group_duplicate_name_create_scenario.rs
@@ -30,7 +30,9 @@ use iggy::prelude::Identifier;
use iggy::prelude::IggyExpiry;
use iggy::prelude::MaxTopicSize;
use iggy::prelude::{ConsumerGroupClient, StreamClient, TopicClient};
-use integration::harness::{TestHarness, assert_clean_system, create_user, login_user};
+use integration::harness::{
+ TestHarness, assert_clean_system, create_user, delete_user, login_user,
+};
pub async fn run(harness: &TestHarness) {
let system_client = harness
@@ -99,7 +101,12 @@ pub async fn run(harness: &TestHarness) {
"the surviving member must keep its partition assignment"
);
- cleanup(&system_client, true).await;
+ // This scenario creates only USERNAME_1, so delete just that user (the
+ // shared `cleanup(_, true)` deletes USERNAME_1/2/3 and would fail with
+ // UserNotFound on the two it never created); `cleanup(_, false)` drops the
+ // stream.
+ delete_user(&system_client, USERNAME_1).await;
+ cleanup(&system_client, false).await;
assert_clean_system(&system_client).await;
}
diff --git a/core/integration/tests/server/scenarios/mod.rs b/core/integration/tests/server/scenarios/mod.rs
index 7b02e107d..8ccb98b21 100644
--- a/core/integration/tests/server/scenarios/mod.rs
+++ b/core/integration/tests/server/scenarios/mod.rs
@@ -23,7 +23,6 @@ pub mod bench_scenario;
// panic on the primary); skip until the metadata races are fixed.
#[cfg(not(feature = "vsr"))]
pub mod concurrent_produce_consume_scenario;
-#[cfg(not(feature = "vsr"))]
pub mod concurrent_scenario;
pub mod consumer_group_auto_commit_reconnection_scenario;
// Only consumed by `cg_vsr` (server-ng); legacy `cg.rs` has no equivalent.
diff --git a/core/message_bus/Cargo.toml b/core/message_bus/Cargo.toml
index 4b63f2c93..a5017d127 100644
--- a/core/message_bus/Cargo.toml
+++ b/core/message_bus/Cargo.toml
@@ -32,6 +32,7 @@ publish = false
ahash = { workspace = true }
async-channel = { workspace = true }
blake3 = { workspace = true }
+bytemuck = { workspace = true }
bytes = { workspace = true }
compio = { workspace = true }
compio-quic = { workspace = true }
diff --git a/core/message_bus/src/transports/quic.rs b/core/message_bus/src/transports/quic.rs
index 02cb7dc7e..e7b1730e8 100644
--- a/core/message_bus/src/transports/quic.rs
+++ b/core/message_bus/src/transports/quic.rs
@@ -30,22 +30,27 @@
//! at a time:
//!
//! 1. accept the next bidi (or break on shutdown / connection close);
-//! 2. read exactly one inbound frame from the `RecvStream` and forward it
-//! to [`ActorContext::in_tx`];
-//! 3. await one outbound frame on [`ActorContext::rx`] (the reply), drain
-//! any additional immediate replies via `try_recv` (defensive — 1:1 in
-//! steady state), write each to the `SendStream`, then `finish()` to
-//! deliver pending data + FIN to the peer;
+//! 2. read exactly one inbound frame from the `RecvStream`, note its
+//! `request` id, and forward it to [`ActorContext::in_tx`];
+//! 3. wait on [`ActorContext::rx`] for the reply whose `request` id matches,
+//! discarding any stale/duplicate reply left by an abandoned bidi; on
+//! [`REPLY_WAIT_TIMEOUT`] abandon this bidi (the dispatch stayed silent on
+//! a transient submit, expecting a replay) and accept the next; write the
+//! matched reply, then `finish()` to deliver pending data + FIN;
//! 4. drop the bidi pair and loop to the next `accept_bi`.
//!
-//! The `accept_bi` loop is serial by design: the single
-//! [`ActorContext::rx`] channel per connection is unkeyed, so two
-//! concurrent in-flight bidis would race the reply queue with no way to
-//! tell which reply belongs to which bidi. The iggy SDK on a single
-//! connection already serialises via an internal `RwLock`, so this is a
-//! semantic match, not a regression. A future pipelining upgrade would
-//! introduce `request_id`-keyed reply routing and run per-bidi handlers
-//! concurrently.
+//! The `accept_bi` loop is still serial (the iggy SDK serialises per
+//! connection via an internal `RwLock`, so one bidi at a time is a semantic
+//! match), but the reply wait is now `request_id`-KEYED rather than "next
+//! frame on `rx`". This matters because the server stays deliberately silent
+//! on a transient submit (it expects the SDK to replay): an unkeyed,
+//! untimed wait would block this bidi - and, serial, the whole connection -
+//! forever, so the replay's fresh bidi could never be accepted (acute at
+//! `max_concurrent_bidi_streams=1`). Keying + the timeout let a transient
+//! bidi be abandoned safely: the SDK replays with the SAME request id, so a
+//! late reply for the abandoned request matches the replay's bidi and is
+//! consumed there, never mis-delivered to a later request. A future
+//! pipelining upgrade would additionally run per-bidi handlers concurrently.
//!
//! The handshake itself is driven by [`accept_handshake`] (no bidi
//! captured). To avoid a single slow / hostile peer wedging the entire
@@ -73,6 +78,7 @@
use super::{ActorContext, TransportConn, TransportListener};
use crate::config::QuicTuning;
use crate::framing;
+use crate::lifecycle::connection_registry::BusMessage;
use compio::BufResult;
use compio::io::AsyncWriteExt;
use compio_quic::{
@@ -80,6 +86,7 @@ use compio_quic::{
crypto::rustls::QuicServerConfig,
};
use futures::FutureExt;
+use iggy_binary_protocol::{Command2, HEADER_SIZE, ReplyHeader, RequestHeader};
use std::io;
use std::net::SocketAddr;
use std::sync::Arc;
@@ -276,6 +283,51 @@ async fn accept_handshake_inner(incoming: Incoming) -> Option<(QuicTransportConn
/// using `MessageBusConfig::close_grace`.
pub(crate) const DEFAULT_CLOSE_GRACE: Duration = Duration::from_secs(2);
+/// How long a bidi waits for its keyed reply before abandoning the stream.
+/// A replicated submit the server cannot yet commit is answered with silence
+/// (the server expects the SDK to replay), so without a bound the per-bidi
+/// wait - and, since `accept_bi` is serial, the whole connection - would wedge:
+/// the SDK's replay opens a fresh bidi that, at `max_concurrent_bidi_streams=1`,
+/// can only be accepted once this one is released. Kept below the SDK's
+/// per-attempt retry interval so the slot frees before the client replays; a
+/// late reply for the abandoned request carries the same request id and is
+/// matched (and consumed) by the replay's bidi, so abandoning early is safe.
+const REPLY_WAIT_TIMEOUT: Duration = Duration::from_secs(2);
+
+/// `Command2` byte offset shared by every consensus header (after the
+/// fixed checksum/cluster/size/view/release prefix).
+const COMMAND_OFFSET: usize = 60;
+
+/// How an outbound frame routes to a waiting bidi.
+enum ReplyRoute {
+ /// A request-keyed `Reply`: deliver only to the bidi whose request id
+ /// matches; a non-matching one is a stale/duplicate from an abandoned bidi.
+ Keyed(u64),
+ /// A terminal/control frame (`Eviction`, etc.) with no `request` field, or
+ /// an undecodable header: deliver to the in-flight bidi unconditionally.
+ /// Filtering these out would silently swallow session-terminal signals
+ /// (e.g. `NoSession` -> `Unauthenticated`), leaving the client to time out.
+ Unkeyed,
+}
+
+/// Decide how to route an outbound frame. Only `Command2::Reply` carries a
+/// `request` id; everything else must pass through unfiltered.
+fn reply_route(frame: &BusMessage) -> ReplyRoute {
+ let bytes = frame.as_slice();
+ let is_reply = bytes
+ .get(COMMAND_OFFSET)
+ .is_some_and(|&command| command == Command2::Reply as u8);
+ if !is_reply {
+ return ReplyRoute::Unkeyed;
+ }
+ bytes
+ .get(..HEADER_SIZE)
+ .and_then(|header| bytemuck::checked::try_from_bytes::<ReplyHeader>(header).ok())
+ .map_or(ReplyRoute::Unkeyed, |header| {
+ ReplyRoute::Keyed(header.request)
+ })
+}
+
/// A single accepted QUIC connection.
///
/// Per-request bidirectional streams are accepted on demand inside
@@ -317,7 +369,7 @@ impl QuicTransportConn {
}
impl TransportConn for QuicTransportConn {
- #[allow(clippy::future_not_send)]
+ #[allow(clippy::future_not_send, clippy::too_many_lines)]
async fn run(self, ctx: ActorContext) {
let connection = self.connection;
let ActorContext {
@@ -369,46 +421,86 @@ impl TransportConn for QuicTransportConn {
continue;
}
};
+ // Request id this bidi is waiting on. Used to match its reply and
+ // to discard stale/duplicate replies left by an abandoned bidi.
+ // `None` (unparseable) degrades to accepting the first reply.
+ let request_id = req
+ .as_slice()
+ .get(..HEADER_SIZE)
+ .and_then(|bytes| bytemuck::checked::try_from_bytes::<RequestHeader>(bytes).ok())
+ .map(|header| header.request);
+
if in_tx.send(req).await.is_err() {
debug!(%label, %peer, "quic: inbound queue dropped");
break;
}
- // Wait for the matching reply. The single bus rx channel is
- // unkeyed; serialising one bidi at a time guarantees the
- // next frame on `rx` is the reply for THIS bidi.
- // `async_channel::Receiver::recv` and `FusedShutdown` are
- // both cancel-safe and compio-buffer-free, so select-drop
- // here cannot poison anything.
- let first = futures::select! {
- () = shutdown_fut.as_mut() => {
- debug!(%label, %peer, "quic: shutdown during reply wait");
- break;
+ // Wait for THIS bidi's reply, keyed by request id. The bus `rx` is
+ // a single unkeyed per-connection channel, so filter by id and
+ // discard replies belonging to an abandoned earlier bidi (the SDK
+ // replays with the SAME request id, so a late reply matches and is
+ // consumed by the replay's bidi - never mis-delivered to a later
+ // request). On timeout the dispatch produced no reply (a transient
+ // submit: the server stays silent expecting a replay); abandon this
+ // bidi and accept the next so the replay's fresh stream is not
+ // blocked behind us (acute at `max_concurrent_bidi_streams=1`).
+ let mut matched: Option<BusMessage> = None;
+ let mut connection_gone = false;
+ {
+ let mut reply_deadline =
+ std::pin::pin!(compio::time::sleep(REPLY_WAIT_TIMEOUT).fuse());
+ loop {
+ futures::select! {
+ () = shutdown_fut.as_mut() => {
+ debug!(%label, %peer, "quic: shutdown during reply wait");
+ connection_gone = true;
+ break;
+ }
+ () = reply_deadline.as_mut() => {
+ debug!(%label, %peer, ?request_id, "quic: no reply within timeout; abandoning bidi for client replay");
+ break;
+ }
+ res = rx.recv().fuse() => if let Ok(m) = res {
+ let deliver = match reply_route(&m) {
+ // Eviction / control frame: always deliver.
+ ReplyRoute::Unkeyed => true,
+ // Keyed reply: only this bidi's; else it's a
+ // stale/duplicate from an abandoned bidi -> drop.
+ ReplyRoute::Keyed(id) => {
+ request_id.is_none() || Some(id) == request_id
+ }
+ };
+ if deliver {
+ matched = Some(m);
+ break;
+ }
+ } else {
+ debug!(%label, %peer, "quic: mailbox closed");
+ connection_gone = true;
+ break;
+ },
+ }
}
- res = rx.recv().fuse() => if let Ok(m) = res {
- m
- } else {
- debug!(%label, %peer, "quic: mailbox closed");
- break;
- },
+ }
+ if connection_gone {
+ break;
+ }
+ let Some(first) = matched else {
+ // Timeout: close our send half so the SDK's read ends, then
+ // accept the next bidi (the client's replay).
+ if let Err(e) = send.finish() {
+ debug!(%label, %peer, error = ?e, "quic: send.finish() failed after reply timeout");
+ }
+ continue;
};
- // Write the reply, drain any additional immediate replies
- // (defensive 1:N), then `finish()` so quinn-proto flushes
- // pending data + a FIN, signalling the SDK that the reply
- // is complete.
+ // Write the reply, then `finish()` so quinn-proto flushes pending
+ // data + a FIN, signalling the SDK that the reply is complete.
let BufResult(result, _frozen) = send.write_all(first).await;
if let Err(e) = result {
debug!(%label, %peer, error = ?e, "quic: write failed");
continue;
}
- while let Ok(more) = rx.try_recv() {
- let BufResult(result, _frozen) = send.write_all(more).await;
- if let Err(e) = result {
- debug!(%label, %peer, error = ?e, "quic: write failed during burst drain");
- break;
- }
- }
if let Err(e) = send.finish() {
debug!(%label, %peer, error = ?e, "quic: send.finish() failed");
}
diff --git a/core/metadata/src/impls/metadata.rs b/core/metadata/src/impls/metadata.rs
index 73511c701..e329ef550 100644
--- a/core/metadata/src/impls/metadata.rs
+++ b/core/metadata/src/impls/metadata.rs
@@ -26,7 +26,7 @@ use consensus::{
PipelineEntry, Plane, PlaneIdentity, PlaneKind, PreflightOutcome, Project, ReplicaLogContext,
RequestLogEvent, Sequencer, SimEventKind, VsrConsensus, ack_preflight, ack_quorum_reached,
apply_preflight_consensus_plane, build_eviction_message, build_reply_message,
- build_reply_message_with, drain_committable_prefix, emit_sim_event,
+ build_reply_message_with, build_transient_reply, drain_committable_prefix, emit_sim_event,
fence_old_prepare_by_commit, is_caught_up_primary,
panic_if_hash_chain_would_break_in_same_view, pipeline_prepare_common, register_preflight,
replicate_preflight, replicate_to_next_in_chain, request_preflight, send_eviction_to_client,
@@ -530,6 +530,7 @@ where
.await;
}
+ #[allow(clippy::too_many_lines)]
async fn on_replicate(&self, message: <VsrConsensus<B> as Consensus>::Message<PrepareHeader>) {
let Some(consensus) =
require_shard_zero(self.consensus.as_ref(), "on_replicate", "consensus")
@@ -560,11 +561,37 @@ where
}
};
- // TODO: Handle idx calculation, for now using header.op, but since the journal may get compacted, this may not be correct.
+ // Fenced by commit: the whole chain has already committed this op, so
+ // nobody needs it again. Drop entirely. (Mirror of the partition
+ // plane's split in `IggyPartition::on_replicate`.)
+ #[allow(clippy::cast_possible_truncation)]
+ if fence_old_prepare_by_commit(consensus, &header) {
+ warn!(
+ target: "iggy.metadata.diag",
+ plane = "metadata",
+ replica_id = consensus.replica(),
+ view = consensus.view(),
+ op = header.op,
+ commit = consensus.commit_max(),
+ operation = ?header.operation,
+ "received old prepare (<= commit), skipping replication"
+ );
+ return;
+ }
+
+ // Durable here but not yet committed, and the primary is retransmitting
+ // it: our original PrepareOk was lost (e.g. the primary's inbox
+ // overflowed under a client burst). Re-forward the tail down the chain
+ // so a downstream replica that missed it recovers, then re-ack every
+ // op in our uncommitted prepared suffix - not just this one. Acks are
+ // tracked per-op (see `ack_quorum_reached`), and the primary's commit
+ // frontier only advances over a contiguous quorum-acked prefix, so a
+ // lost ack for a lower op keeps that prefix pinned even after we re-ack
+ // the tail. Re-acking the whole suffix the backup holds restores
+ // quorum on the gap. Bounded by the pipeline depth; both downstream
+ // and primary are idempotent on a duplicate (replica, op).
#[allow(clippy::cast_possible_truncation)]
- let is_old_prepare = fence_old_prepare_by_commit(consensus, &header)
- || journal.handle().header(header.op as usize).is_some();
- if is_old_prepare {
+ if journal.handle().header(header.op as usize).is_some() {
warn!(
target: "iggy.metadata.diag",
plane = "metadata",
@@ -573,10 +600,16 @@ where
op = header.op,
commit = consensus.commit_max(),
operation = ?header.operation,
- "received old prepare, skipping replication"
+ "journal already holds prepare, re-forwarding + re-acking suffix"
);
- // Old prepare: downstream already has it or learns via newer
- // forward; no chain-replicate; WAL unaffected.
+ self.replicate(&message).await;
+ for op in (consensus.commit_max() + 1)..=header.op {
+ if let Some(suffix_header) =
+ journal.handle().header(op as usize).map(|header| *header)
+ {
+ self.send_prepare_ok(&suffix_header).await;
+ }
+ }
return;
}
@@ -1303,22 +1336,27 @@ where
.as_ref()
.expect("submit_request_in_process: consensus only exists on shard 0");
+ // Not-primary / not-caught-up is transient: the same request replayed
+ // once a primary is caught up commits fine. Reply with the explicit
+ // `TransientNotCommitted` frame (relayed to the socket by the home shard)
+ // so the client replays immediately rather than waiting out its
+ // read-timeout. The frame keeps the lockstep TCP/WS stream in framing
+ // sync, so the client resends on the same connection (session intact).
if !is_caught_up_primary(consensus) {
- return Err(
- if consensus.is_primary() && consensus.is_normal() && !consensus.is_syncing() {
- MetadataSubmitError::NotCaughtUp
- } else {
- MetadataSubmitError::NotPrimary
- },
- );
+ return Ok(build_transient_reply(
+ &request_header,
+ consensus.commit_max(),
+ IggyError::TransientNotCommitted.as_code(),
+ )
+ .into_generic());
}
// Dedup / session / eviction. shard 0 cannot route by the VSR
// consensus `client_id` (its top bits are random, not home-shard
- // routing), so a Replay/Evict is returned to the home shard as the
- // reply -- `handle_client_request` writes it to the originating socket
- // by transport id, exactly like a fresh commit. Drop surfaces as
- // Canceled so the home shard stays silent and the SDK replays.
+ // routing), so a Replay/Evict/NotReady is returned to the home shard as
+ // the reply -- `handle_client_request` writes it to the originating
+ // socket by transport id, exactly like a fresh commit. Drop (client-bug
+ // stale/gap) surfaces as Canceled so the home shard stays silent.
match request_preflight(consensus, &self.client_table, client_id, session, request) {
PreflightOutcome::Dispatch => {}
PreflightOutcome::Replay(reply) => {
@@ -1333,11 +1371,27 @@ where
let ctx = EvictionContext::from_consensus(consensus);
return Ok(build_eviction_message(ctx, client_id, reason).into_generic());
}
+ // In-flight prepare from this client: replaying the same request_id
+ // is absorbed until the original commits, then served from cache.
+ PreflightOutcome::NotReady => {
+ return Ok(build_transient_reply(
+ &request_header,
+ consensus.commit_max(),
+ IggyError::TransientNotCommitted.as_code(),
+ )
+ .into_generic());
+ }
PreflightOutcome::Drop => return Err(MetadataSubmitError::Canceled),
}
+ // Pipeline full: backpressure, not failure. Tell the client to replay.
if consensus.pipeline().borrow().is_full() {
- return Err(MetadataSubmitError::PipelineFull);
+ return Ok(build_transient_reply(
+ &request_header,
+ consensus.commit_max(),
+ IggyError::TransientNotCommitted.as_code(),
+ )
+ .into_generic());
}
let Ok(prepare) = self.prepare_request(message) else {
@@ -1349,10 +1403,19 @@ where
return Ok(build_eviction_message(ctx, client_id, reason).into_generic());
};
- self.dispatch_prepare_and_await(consensus, prepare)
- .await
- .map(server_common::Message::into_generic)
- .map_err(|Canceled| MetadataSubmitError::Canceled)
+ // A view change canceled the pending prepare before commit. The op may
+ // or may not have committed; replaying the same request_id is idempotent
+ // (the new primary serves it from cache if committed, else re-dispatches),
+ // so reply with the transient frame rather than staying silent.
+ match self.dispatch_prepare_and_await(consensus, prepare).await {
+ Ok(reply) => Ok(reply.into_generic()),
+ Err(Canceled) => Ok(build_transient_reply(
+ &request_header,
+ consensus.commit_max(),
+ IggyError::TransientNotCommitted.as_code(),
+ )
+ .into_generic()),
+ }
}
/// Subscribe to a prepared metadata write, dispatch it into the pipeline,
@@ -1410,6 +1473,85 @@ where
receiver.await
}
+ /// Repair the primary's own missing self-acks.
+ ///
+ /// The primary's `PrepareOk` for its own prepare is produced exactly once,
+ /// as a loopback right after the WAL append (see `on_replicate`). If that
+ /// one-shot is lost or suppressed (e.g. the `send_prepare_ok` persistence
+ /// gate races the sequencer pre-advance under a client burst), no
+ /// retransmit path regenerates it: `retransmit_targets` lists the primary
+ /// itself among the missing replicas, but `RetransmitPrepares` to self is a
+ /// no-op. The op then sits one vote short of quorum forever and pins the
+ /// contiguous commit prefix, so `commit_min` never catches up to
+ /// `commit_max` and the cluster wedges.
+ ///
+ /// This is a re-ack-only repair: for each pending op the primary holds
+ /// DURABLY but has not self-acked, re-emit the self `PrepareOk` and drain
+ /// it through `on_ack`. A pending op the primary does NOT yet hold durably
+ /// is skipped - filling that hole needs full message repair, which is out
+ /// of scope here. Driven each consensus tick;
+ /// `on_ack` dedups a redundant self-ack via `has_ack`, so re-running is
+ /// idempotent and stops once the op commits and leaves the pending range.
+ #[allow(clippy::future_not_send, clippy::cast_possible_truncation)]
+ pub async fn repair_primary_self_acks(&self) {
+ let Some(consensus) = self.consensus.as_ref() else {
+ return;
+ };
+ if !consensus.is_primary() || !consensus.is_normal() || consensus.is_syncing() {
+ return;
+ }
+ let Some(journal) = self.journal.as_ref() else {
+ return;
+ };
+ let self_replica = consensus.replica();
+
+ // Snapshot durable, self-unacked pending ops, dropping the pipeline and
+ // journal borrows before the `send_prepare_ok` awaits below.
+ let mut headers: Vec<PrepareHeader> = Vec::new();
+ {
+ let pipeline = consensus.pipeline().borrow();
+ let from = consensus.commit_max() + 1;
+ let to = consensus.sequencer().current_sequence();
+ for op in from..=to {
+ let Some(entry) = pipeline.entry_by_op(op) else {
+ continue;
+ };
+ if entry.has_ack(self_replica) {
+ continue;
+ }
+ // Durable only: re-acking implies "I hold this op". A gap (op not
+ // in the journal) must not be self-acked - that path needs repair.
+ if let Some(header) = journal.handle().header(op as usize).map(|header| *header) {
+ headers.push(header);
+ }
+ }
+ }
+ if headers.is_empty() {
+ return;
+ }
+
+ for header in &headers {
+ self.send_prepare_ok(header).await;
+ }
+ let mut loopback = Vec::new();
+ consensus.drain_loopback_into(&mut loopback);
+ for message in loopback {
+ match message.header().command {
+ Command2::PrepareOk => match message.try_into_typed::<PrepareOkHeader>() {
+ Ok(prepare_ok) => self.on_ack(prepare_ok).await,
+ Err(error) => warn!(
+ error = %error,
+ "dropping malformed PrepareOk from self-ack repair loopback"
+ ),
+ },
+ command => warn!(
+ ?command,
+ "dropping unexpected message from self-ack repair loopback"
+ ),
+ }
+ }
+ }
+
/// Promote up to `slots_freed` buffered requests into prepares after
/// `on_ack` commits a prefix.
///
diff --git a/core/sdk/src/quic/quic_client.rs b/core/sdk/src/quic/quic_client.rs
index a1e1360fc..c0a01c773 100644
--- a/core/sdk/src/quic/quic_client.rs
+++ b/core/sdk/src/quic/quic_client.rs
@@ -54,6 +54,31 @@ const REQUEST_INITIAL_BYTES_LENGTH: usize = 4;
const RESPONSE_INITIAL_BYTES_LENGTH: usize = 8;
const NAME: &str = "Iggy";
+/// Bound on how long a single QUIC request waits for its response, mirroring the
+/// TCP client's `RESPONSE_READ_TIMEOUT`. A replicated request that the server
+/// cannot commit transiently is answered with silence - the server expects the
+/// SDK read-timeout to drive a replay. `RecvStream::read_to_end` on an
+/// unanswered bidi stream otherwise blocks until the QUIC idle timeout (which
+/// can be minutes), parking that request and, because the connection is held
+/// under lock per send, every later request on the client.
+const RESPONSE_READ_TIMEOUT: Duration = Duration::from_secs(30);
+
+/// Per-attempt response read timeout for the same-connection transient resend
+/// loop (see `send_raw`). A replicated submit the server can't yet commit is
+/// answered with silence; rather than wait the full `RESPONSE_READ_TIMEOUT`
+/// once, abandon the unanswered bidi after this shorter interval and resend the
+/// same request on a fresh stream. Bounded overall by `RESPONSE_READ_TIMEOUT`.
+#[cfg(feature = "vsr")]
+const TRANSIENT_RETRY_INTERVAL: Duration = Duration::from_secs(3);
+
+/// Backoff before replaying a request the server answered with an explicit
+/// `TransientNotCommitted` frame (not-caught-up / in-flight / pipeline-full /
+/// view-change cancel). Unlike a silent timeout, this reply arrives promptly, so
+/// a short pause keeps the replay from spinning while the primary catches up.
+/// Bounded overall by `RESPONSE_READ_TIMEOUT`.
+#[cfg(feature = "vsr")]
+const NOT_READY_RETRY_INTERVAL: Duration = Duration::from_millis(50);
+
/// QUIC client for interacting with the Iggy API.
#[derive(Debug)]
pub struct QuicClient {
@@ -144,7 +169,13 @@ impl BinaryTransport for QuicClient {
}
#[cfg(feature = "vsr")]
- if matches!(self.config.auto_login, AutoLogin::Disabled) {
+ if matches!(self.config.auto_login, AutoLogin::Disabled) && !is_login_register_code(code) {
+ // Without auto-login a reconnect cannot re-establish the session, so
+ // non-login requests are not recovered here - their transient replay
+ // happens on the live connection inside `send_raw`. Login/register
+ // is the exception: the server stays deliberately silent on a
+ // transient register failure and relies on the client replaying via
+ // a reconnect with a fresh session.
return Err(error);
}
@@ -154,6 +185,13 @@ impl BinaryTransport for QuicClient {
#[cfg(feature = "vsr")]
if skip_auto_login {
*self.skip_auto_login_once.lock().await = true;
+ // The replayed login/register must mint a fresh Register: the failed
+ // attempt already consumed the one-shot register request id and may
+ // have half-bound the session.
+ *self
+ .consensus_session
+ .lock()
+ .expect("consensus session mutex poisoned") = ConsensusSession::new();
}
let server_address = self.current_server_address.lock().await.to_string();
info!(
@@ -302,10 +340,14 @@ impl QuicClient {
async fn handle_response(
recv: &mut RecvStream,
response_buffer_size: usize,
+ read_timeout: Duration,
) -> Result<Bytes, IggyError> {
- let buffer = recv
- .read_to_end(response_buffer_size)
+ let buffer = tokio::time::timeout(read_timeout, recv.read_to_end(response_buffer_size))
.await
+ .map_err(|_| {
+ error!("Timed out after {read_timeout:?} waiting for QUIC response");
+ IggyError::Disconnected
+ })?
.map_err(|error| {
error!("Failed to read response data: {error}");
IggyError::QuicError
@@ -660,73 +702,138 @@ impl QuicClient {
// SAFETY: we run code holding the `connection` lock in a task so we can't be cancelled while holding the lock.
tokio::spawn(async move {
let connection = connection.lock().await;
- if let Some(connection) = connection.as_ref() {
- #[cfg(feature = "vsr")]
+ let Some(connection) = connection.as_ref() else {
+ error!("Cannot send data. Client is not connected.");
+ return Err(IggyError::NotConnected);
+ };
+
+ #[cfg(feature = "vsr")]
+ {
let (request_header, request_size) = {
let mut consensus_session = consensus_session
.lock()
.expect("consensus session mutex poisoned");
crate::vsr::encode_request_header(&mut consensus_session, code, &payload)?
};
- #[cfg(not(feature = "vsr"))]
- let payload_length = payload.len() + REQUEST_INITIAL_BYTES_LENGTH;
- let (mut send, mut recv) = connection.open_bi().await.map_err(|error| {
- error!("Failed to open a bidirectional stream: {error}");
- IggyError::QuicError
- })?;
- trace!("Sending a QUIC request with code: {code}");
- #[cfg(feature = "vsr")]
- trace!(
- "Sending a QUIC VSR request of size {} with code: {code}",
- request_size
- );
- #[cfg(feature = "vsr")]
- send.write_all(bytemuck::bytes_of(&request_header))
- .await
- .map_err(|error| {
+ trace!("Sending a QUIC VSR request of size {request_size} with code: {code}");
+ // Same-connection transient resend. A replicated submit the
+ // server cannot yet commit is answered with silence - it expects
+ // the client to replay. The connection and login session are
+ // intact; only this bidi went unanswered. So abandon it after a
+ // short read timeout and resend the SAME request header (same
+ // request id, so the server dedups/commits it idempotently) on a
+ // fresh bidi, bounded overall by `RESPONSE_READ_TIMEOUT`. This
+ // needs no reconnect or relogin, so it recovers transients even
+ // with auto-login disabled. Login/register is one-shot (a replay
+ // must mint a fresh session), so it is left to the reconnect path
+ // in `send_raw_with_response` and not resent here.
+ let allow_resend = !is_login_register_code(code);
+ let header_bytes = bytemuck::bytes_of(&request_header);
+ let deadline = tokio::time::Instant::now() + RESPONSE_READ_TIMEOUT;
+ loop {
+ let (mut send, mut recv) = connection.open_bi().await.map_err(|error| {
+ error!("Failed to open a bidirectional stream: {error}");
+ IggyError::QuicError
+ })?;
+ send.write_all(header_bytes).await.map_err(|error| {
error!("Failed to write VSR request header: {error}");
IggyError::QuicError
})?;
- #[cfg(feature = "vsr")]
- if !payload.is_empty() {
- send.write_all(&payload).await.map_err(|error| {
- error!("Failed to write VSR request payload: {error}");
+ if !payload.is_empty() {
+ send.write_all(&payload).await.map_err(|error| {
+ error!("Failed to write VSR request payload: {error}");
+ IggyError::QuicError
+ })?;
+ }
+ send.finish().map_err(|error| {
+ error!("Failed to finish VSR request stream: {error}");
IggyError::QuicError
})?;
+ let remaining =
+ deadline.saturating_duration_since(tokio::time::Instant::now());
+ if remaining.is_zero() {
+ return Err(IggyError::Disconnected);
+ }
+ let attempt_timeout = remaining.min(TRANSIENT_RETRY_INTERVAL);
+ match QuicClient::handle_response(
+ &mut recv,
+ response_buffer_size as usize,
+ attempt_timeout,
+ )
+ .await
+ {
+ Ok(reply) => return Ok(reply),
+ // `Disconnected` = our read timed out (server never
+ // answered). `EmptyResponse` = the server abandoned the
+ // bidi (finished it with no body). `TransientNotCommitted`
+ // = the server replied with an explicit retry frame
+ // because it could not commit yet (not-caught-up /
+ // in-flight / pipeline-full / view-change cancel). All
+ // three mean "resend the same request on a fresh bidi";
+ // the session stays intact so no reconnect/relogin needed.
+ // Login/register resends on `TransientNotCommitted` too
+ // (nothing committed -> the same Register replays
+ // idempotently, no fresh session needed); for the silent
+ // paths login still falls through to the reconnect+relogin
+ // path in `send_raw_with_response`.
+ Err(
+ error @ (IggyError::Disconnected
+ | IggyError::EmptyResponse
+ | IggyError::TransientNotCommitted),
+ ) if (allow_resend || error == IggyError::TransientNotCommitted)
+ && tokio::time::Instant::now() < deadline =>
+ {
+ // The explicit frame returns promptly (no read
+ // timeout elapsed), so pace the replay; the silent
+ // paths already waited out `attempt_timeout`.
+ if error == IggyError::TransientNotCommitted {
+ let remaining = deadline
+ .saturating_duration_since(tokio::time::Instant::now());
+ tokio::time::sleep(NOT_READY_RETRY_INTERVAL.min(remaining)).await;
+ }
+ warn!(
+ "QUIC request code {code} not committed (transient); resending on a new stream"
+ );
+ }
+ Err(error) => return Err(error),
+ }
}
- #[cfg(feature = "vsr")]
- send.finish().map_err(|error| {
- error!("Failed to finish VSR request stream: {error}");
+ }
+
+ #[cfg(not(feature = "vsr"))]
+ {
+ let payload_length = payload.len() + REQUEST_INITIAL_BYTES_LENGTH;
+ let (mut send, mut recv) = connection.open_bi().await.map_err(|error| {
+ error!("Failed to open a bidirectional stream: {error}");
IggyError::QuicError
})?;
- #[cfg(not(feature = "vsr"))]
+ trace!("Sending a QUIC request with code: {code}");
send.write_all(&(payload_length as u32).to_le_bytes())
.await
.map_err(|error| {
error!("Failed to write payload length: {error}");
IggyError::QuicError
})?;
- #[cfg(not(feature = "vsr"))]
send.write_all(&code.to_le_bytes()).await.map_err(|error| {
error!("Failed to write payload code: {error}");
IggyError::QuicError
})?;
- #[cfg(not(feature = "vsr"))]
send.write_all(&payload).await.map_err(|error| {
error!("Failed to write payload: {error}");
IggyError::QuicError
})?;
- #[cfg(not(feature = "vsr"))]
send.finish().map_err(|error| {
error!("Failed to finish sending data: {error}");
IggyError::QuicError
})?;
trace!("Sent a QUIC request with code: {code}, waiting for a response...");
- return QuicClient::handle_response(&mut recv, response_buffer_size as usize).await;
+ QuicClient::handle_response(
+ &mut recv,
+ response_buffer_size as usize,
+ RESPONSE_READ_TIMEOUT,
+ )
+ .await
}
-
- error!("Cannot send data. Client is not connected.");
- Err(IggyError::NotConnected)
})
.await
.map_err(|e| {
diff --git a/core/sdk/src/tcp/tcp_client.rs b/core/sdk/src/tcp/tcp_client.rs
index 127a2f58f..d69ffd2ae 100644
--- a/core/sdk/src/tcp/tcp_client.rs
+++ b/core/sdk/src/tcp/tcp_client.rs
@@ -64,6 +64,14 @@ const NAME: &str = "Iggy";
#[cfg(feature = "vsr")]
const RESPONSE_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
+/// Backoff before replaying a request the server answered with an explicit
+/// `TransientNotCommitted` frame (not-caught-up / in-flight / pipeline-full /
+/// view-change cancel). The reply arrives promptly, so a short pause keeps the
+/// replay from spinning while the primary catches up. Bounded by
+/// `RESPONSE_READ_TIMEOUT`.
+#[cfg(feature = "vsr")]
+const NOT_READY_RETRY_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50);
+
/// TCP client for interacting with the Iggy API.
/// It requires a valid server address.
#[derive(Debug)]
@@ -700,107 +708,122 @@ impl TcpClient {
let result = tokio::spawn(async move {
let mut stream = stream.lock().await;
if let Some(stream) = stream.as_mut() {
- #[cfg(feature = "vsr")]
- let (request_header, request_size) = {
- let mut consensus_session = consensus_session
- .lock()
- .expect("consensus session mutex poisoned");
- crate::vsr::encode_request_header(&mut consensus_session, code, &payload)?
- };
- #[cfg(not(feature = "vsr"))]
- let payload_length = payload.len() + REQUEST_INITIAL_BYTES_LENGTH;
- #[cfg(feature = "vsr")]
- trace!(
- "Sending a TCP VSR request of size {} with code: {code}",
- request_size
- );
- #[cfg(not(feature = "vsr"))]
- trace!("Sending a TCP request of size {payload_length} with code: {code}");
- #[cfg(feature = "vsr")]
- stream.write(bytemuck::bytes_of(&request_header)).await?;
- #[cfg(feature = "vsr")]
- if !payload.is_empty() {
- stream.write(&payload).await?;
- }
- #[cfg(not(feature = "vsr"))]
- stream.write(&(payload_length as u32).to_le_bytes()).await?;
- #[cfg(not(feature = "vsr"))]
- stream.write(&code.to_le_bytes()).await?;
- #[cfg(not(feature = "vsr"))]
- stream.write(&payload).await?;
- stream.flush().await?;
- trace!("Sent a TCP request with code: {code}, waiting for a response...");
#[cfg(feature = "vsr")]
{
- let mut response_header = [0u8; iggy_binary_protocol::HEADER_SIZE];
- // `stream.read` delegates to `read_exact`; on success it
- // always returns the requested length, so no short-read
- // guard is needed here.
- //
- // Deadline guards against server-side reply loss (e.g. a
- // stalled replication quorum that never commits the op):
- // the connection is lockstep, so an unanswered read would
- // hold the stream lock forever and wedge every later
- // request on this client. On expiry drop the stream --
- // a late reply would desync framing for the next request.
- //
- // One deadline spans BOTH the header and body reads: a
- // reply that delivers a header then stalls must not get a
- // fresh full timeout for the body (which would allow up to
- // 2x `RESPONSE_READ_TIMEOUT` total).
- let response_deadline = tokio::time::Instant::now() + RESPONSE_READ_TIMEOUT;
- let header_read =
- tokio::time::timeout_at(response_deadline, stream.read(&mut response_header))
- .await;
- let Ok(header_read) = header_read else {
- error!(
- "Timed out after {RESPONSE_READ_TIMEOUT:?} waiting for VSR response header for TCP request with code: {code}",
- );
- return Err(IggyError::Disconnected);
+ // Encode the request header ONCE: `next_request_id` advances
+ // here, so a transient replay must reuse the same id for the
+ // server's dedup. The connection is lockstep (one request in
+ // flight per client), so a complete reply leaves the stream at
+ // a clean frame boundary -- a `TransientNotCommitted` answer
+ // (the server could not commit yet: not-caught-up / in-flight
+ // / pipeline-full / view-change cancel) lets us resend the
+ // SAME request on the SAME connection with no reconnect and
+ // the session intact. Bounded overall by RESPONSE_READ_TIMEOUT.
+ let (request_header, request_size) = {
+ let mut consensus_session = consensus_session
+ .lock()
+ .expect("consensus session mutex poisoned");
+ crate::vsr::encode_request_header(&mut consensus_session, code, &payload)?
};
- header_read.map_err(|error| {
- error!(
- "Failed to read VSR response header for TCP request with code: {code}: {error}",
- code = code,
- error = error
- );
- IggyError::Disconnected
- })?;
-
- let response_size = crate::vsr::response_size(&response_header)?;
-
- let body_size = response_size - iggy_binary_protocol::HEADER_SIZE;
- let body = if body_size > 0 {
- let mut body = BytesMut::with_capacity(body_size);
- let body_read = tokio::time::timeout_at(
- response_deadline,
- stream.read_buf(&mut body, body_size),
+ trace!("Sending a TCP VSR request of size {request_size} with code: {code}");
+ let header_bytes = bytemuck::bytes_of(&request_header);
+ // One deadline bounds the whole request including transient
+ // replays, so a slow primary cannot stretch a single call
+ // beyond RESPONSE_READ_TIMEOUT.
+ let retry_deadline = tokio::time::Instant::now() + RESPONSE_READ_TIMEOUT;
+ loop {
+ stream.write(header_bytes).await?;
+ if !payload.is_empty() {
+ stream.write(&payload).await?;
+ }
+ stream.flush().await?;
+ trace!("Sent a TCP request with code: {code}, waiting for a response...");
+
+ let mut response_header = [0u8; iggy_binary_protocol::HEADER_SIZE];
+ // `stream.read` delegates to `read_exact`; on success it
+ // always returns the requested length, so no short-read
+ // guard is needed here.
+ //
+ // Deadline guards against server-side reply loss (e.g. a
+ // stalled replication quorum that never commits the op):
+ // the connection is lockstep, so an unanswered read would
+ // hold the stream lock forever and wedge every later
+ // request on this client. On expiry drop the stream --
+ // a late reply would desync framing for the next request.
+ //
+ // One deadline spans BOTH the header and body reads: a
+ // reply that delivers a header then stalls must not get a
+ // fresh full timeout for the body.
+ let header_read = tokio::time::timeout_at(
+ retry_deadline,
+ stream.read(&mut response_header),
)
.await;
- let Ok(body_read) = body_read else {
+ let Ok(header_read) = header_read else {
error!(
- "Timed out after {RESPONSE_READ_TIMEOUT:?} waiting for VSR response body for TCP request with code: {code}",
+ "Timed out after {RESPONSE_READ_TIMEOUT:?} waiting for VSR response header for TCP request with code: {code}",
);
return Err(IggyError::Disconnected);
};
- body_read.map_err(|error| {
+ header_read.map_err(|error| {
error!(
- "Failed to read VSR response body for TCP request with code: {code}: {error}",
- code = code,
- error = error
+ "Failed to read VSR response header for TCP request with code: {code}: {error}",
);
IggyError::Disconnected
})?;
- body.freeze()
- } else {
- Bytes::new()
- };
- return crate::vsr::decode_response_split(&response_header, body);
+ let response_size = crate::vsr::response_size(&response_header)?;
+ let body_size = response_size - iggy_binary_protocol::HEADER_SIZE;
+ let body = if body_size > 0 {
+ let mut body = BytesMut::with_capacity(body_size);
+ let body_read = tokio::time::timeout_at(
+ retry_deadline,
+ stream.read_buf(&mut body, body_size),
+ )
+ .await;
+ let Ok(body_read) = body_read else {
+ error!(
+ "Timed out after {RESPONSE_READ_TIMEOUT:?} waiting for VSR response body for TCP request with code: {code}",
+ );
+ return Err(IggyError::Disconnected);
+ };
+ body_read.map_err(|error| {
+ error!(
+ "Failed to read VSR response body for TCP request with code: {code}: {error}",
+ );
+ IggyError::Disconnected
+ })?;
+ body.freeze()
+ } else {
+ Bytes::new()
+ };
+
+ match crate::vsr::decode_response_split(&response_header, body) {
+ // Server could not commit yet but answered with a
+ // complete frame; the lockstep stream is in sync, so
+ // replay the same request id on this connection after
+ // a short pause (no reconnect, session intact).
+ Err(IggyError::TransientNotCommitted)
+ if tokio::time::Instant::now() < retry_deadline =>
+ {
+ let remaining = retry_deadline
+ .saturating_duration_since(tokio::time::Instant::now());
+ tokio::time::sleep(NOT_READY_RETRY_INTERVAL.min(remaining)).await;
+ }
+ other => return other,
+ }
+ }
}
#[cfg(not(feature = "vsr"))]
{
+ let payload_length = payload.len() + REQUEST_INITIAL_BYTES_LENGTH;
+ trace!("Sending a TCP request of size {payload_length} with code: {code}");
+ stream.write(&(payload_length as u32).to_le_bytes()).await?;
+ stream.write(&code.to_le_bytes()).await?;
+ stream.write(&payload).await?;
+ stream.flush().await?;
+ trace!("Sent a TCP request with code: {code}, waiting for a response...");
let mut response_buffer = [0u8; RESPONSE_INITIAL_BYTES_LENGTH];
let read_bytes = stream.read(&mut response_buffer).await.map_err(|error| {
error!(
diff --git a/core/sdk/src/vsr.rs b/core/sdk/src/vsr.rs
index 8f7f45624..f82be63a8 100644
--- a/core/sdk/src/vsr.rs
+++ b/core/sdk/src/vsr.rs
@@ -243,7 +243,15 @@ fn read_operation(header_bytes: &[u8; HEADER_SIZE]) -> Result<Operation, IggyErr
/// section is corruption, never a silent success, so it maps to `InvalidCommand`
/// rather than risk a rejection decoding as `Ok`.
fn split_metadata_result(operation: Operation, body: Bytes) -> Result<Bytes, IggyError> {
- if !operation.is_metadata() {
+ // Register (login/register) replies are result-framed too, so a transient
+ // login decodes to `TransientNotCommitted` and the SDK replays it. The one
+ // exception is a terminal failure, which ships an empty body (no result
+ // section) and is passed through to fail the typed `LoginRegisterResponse`
+ // decode. Reads, the partition data plane, and Logout carry no result
+ // section and pass through untouched.
+ let result_framed =
+ operation.is_metadata() || (operation == Operation::Register && !body.is_empty());
+ if !result_framed {
return Ok(body);
}
match result_code(&body) {
diff --git a/core/sdk/src/websocket/websocket_client.rs b/core/sdk/src/websocket/websocket_client.rs
index bbeee44e9..ab3786e11 100644
--- a/core/sdk/src/websocket/websocket_client.rs
+++ b/core/sdk/src/websocket/websocket_client.rs
@@ -66,6 +66,14 @@ const NAME: &str = "WebSocket";
#[cfg(feature = "vsr")]
const RESPONSE_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
+/// Backoff before replaying a request the server answered with an explicit
+/// `TransientNotCommitted` frame (not-caught-up / in-flight / pipeline-full /
+/// view-change cancel). The reply arrives promptly, so a short pause keeps the
+/// replay from spinning while the primary catches up. Bounded by
+/// `RESPONSE_READ_TIMEOUT`.
+#[cfg(feature = "vsr")]
+const NOT_READY_RETRY_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50);
+
#[derive(Debug)]
pub struct WebSocketClient {
stream: Arc<Mutex<Option<WebSocketStreamKind>>>,
@@ -671,96 +679,111 @@ impl WebSocketClient {
}
let mut stream_guard = self.stream.lock().await;
- let stream = stream_guard.as_mut().ok_or_else(|| {
+ if stream_guard.is_none() {
trace!("Cannot send data. Client is not connected.");
- IggyError::NotConnected
- })?;
-
- #[cfg(feature = "vsr")]
- let request = {
- let mut consensus_session = self
- .consensus_session
- .lock()
- .expect("consensus session mutex poisoned");
- crate::vsr::encode_contiguous_request(&mut consensus_session, code, &payload)?
- };
- #[cfg(not(feature = "vsr"))]
- let payload_length = payload.len() + REQUEST_INITIAL_BYTES_LENGTH;
- #[cfg(not(feature = "vsr"))]
- let mut request = BytesMut::with_capacity(4 + REQUEST_INITIAL_BYTES_LENGTH + payload.len());
- #[cfg(not(feature = "vsr"))]
- request.put_u32_le(payload_length as u32);
- #[cfg(not(feature = "vsr"))]
- request.put_u32_le(code);
- #[cfg(not(feature = "vsr"))]
- request.put_slice(&payload);
-
- trace!(
- "Sending {NAME} message with code: {}, payload size: {} bytes",
- code,
- payload.len()
- );
- #[cfg(feature = "vsr")]
- trace!(
- "Sending {NAME} VSR request of size {} with code: {code}",
- request.len()
- );
-
- stream.write(&request).await?;
- stream.flush().await?;
+ return Err(IggyError::NotConnected);
+ }
#[cfg(feature = "vsr")]
{
- // Mirror the TCP path: header onto stack, body into its own
- // buffer, `decode_response_split` slices without concatenation.
- // Old path did `vec![0; HEADER_SIZE]` + `vec![0; body_size]`
- // (two zero-fills) + `BytesMut::with_capacity(response_size)` +
- // two `put_slice` memcopies per reply.
- // One deadline spans both the header and body reads so a reply
- // that delivers a header then stalls cannot wait up to 2x the
- // timeout. On expiry drop the stream: the read runs inline here
- // (no spawned task to cancel), so without an explicit drop a late
- // reply would desync framing for the next request.
- let response_deadline = tokio::time::Instant::now() + RESPONSE_READ_TIMEOUT;
- let mut response_header = [0u8; iggy_binary_protocol::HEADER_SIZE];
- let header_read =
- tokio::time::timeout_at(response_deadline, stream.read(&mut response_header)).await;
- let Ok(header_read) = header_read else {
- error!(
- "Timed out after {RESPONSE_READ_TIMEOUT:?} waiting for {NAME} VSR response header for request with code: {code}"
- );
- *stream_guard = None;
- return Err(IggyError::Disconnected);
+ // Encode the request ONCE: `next_request_id` advances here, so a
+ // transient replay must reuse the same id for the server's dedup.
+ // The connection is lockstep (one request in flight per client), so a
+ // complete reply leaves the stream at a clean frame boundary -- a
+ // `TransientNotCommitted` answer (the server could not commit yet)
+ // lets us resend the SAME request on the SAME connection with no
+ // reconnect and the session intact. Bounded by RESPONSE_READ_TIMEOUT.
+ let request = {
+ let mut consensus_session = self
+ .consensus_session
+ .lock()
+ .expect("consensus session mutex poisoned");
+ crate::vsr::encode_contiguous_request(&mut consensus_session, code, &payload)?
};
- header_read?;
-
- let response_size = crate::vsr::response_size(&response_header)?;
- let body_size = response_size - iggy_binary_protocol::HEADER_SIZE;
- let body = if body_size > 0 {
- // `WebSocketStreamKind::read` reads into a slice without a
- // zero-fill prerequisite; we still allocate `body_size` but
- // skip the header concatenation.
- let mut body = vec![0u8; body_size];
- let body_read =
- tokio::time::timeout_at(response_deadline, stream.read(&mut body)).await;
- let Ok(body_read) = body_read else {
+ trace!(
+ "Sending {NAME} VSR request of size {} with code: {code}",
+ request.len()
+ );
+ // One deadline bounds the whole request including transient replays.
+ let retry_deadline = tokio::time::Instant::now() + RESPONSE_READ_TIMEOUT;
+ loop {
+ let stream = stream_guard.as_mut().ok_or(IggyError::NotConnected)?;
+ stream.write(&request).await?;
+ stream.flush().await?;
+
+ // One deadline spans both the header and body reads so a reply
+ // that delivers a header then stalls cannot wait up to 2x the
+ // timeout. On expiry drop the stream: the read runs inline here
+ // (no spawned task to cancel), so without an explicit drop a late
+ // reply would desync framing for the next request.
+ let mut response_header = [0u8; iggy_binary_protocol::HEADER_SIZE];
+ let header_read =
+ tokio::time::timeout_at(retry_deadline, stream.read(&mut response_header))
+ .await;
+ let Ok(header_read) = header_read else {
error!(
- "Timed out after {RESPONSE_READ_TIMEOUT:?} waiting for {NAME} VSR response body for request with code: {code}"
+ "Timed out after {RESPONSE_READ_TIMEOUT:?} waiting for {NAME} VSR response header for request with code: {code}"
);
*stream_guard = None;
return Err(IggyError::Disconnected);
};
- body_read?;
- Bytes::from(body)
- } else {
- Bytes::new()
- };
+ header_read?;
+
+ let response_size = crate::vsr::response_size(&response_header)?;
+ let body_size = response_size - iggy_binary_protocol::HEADER_SIZE;
+ let body = if body_size > 0 {
+ let mut body = vec![0u8; body_size];
+ let body_read =
+ tokio::time::timeout_at(retry_deadline, stream.read(&mut body)).await;
+ let Ok(body_read) = body_read else {
+ error!(
+ "Timed out after {RESPONSE_READ_TIMEOUT:?} waiting for {NAME} VSR response body for request with code: {code}"
+ );
+ *stream_guard = None;
+ return Err(IggyError::Disconnected);
+ };
+ body_read?;
+ Bytes::from(body)
+ } else {
+ Bytes::new()
+ };
- crate::vsr::decode_response_split(&response_header, body)
+ match crate::vsr::decode_response_split(&response_header, body) {
+ // Server could not commit yet but answered with a complete
+ // frame; the lockstep stream is in sync, so replay the same
+ // request id on this connection after a short pause.
+ Err(IggyError::TransientNotCommitted)
+ if tokio::time::Instant::now() < retry_deadline =>
+ {
+ let remaining =
+ retry_deadline.saturating_duration_since(tokio::time::Instant::now());
+ tokio::time::sleep(NOT_READY_RETRY_INTERVAL.min(remaining)).await;
+ }
+ other => return other,
+ }
+ }
}
#[cfg(not(feature = "vsr"))]
{
+ let stream = stream_guard.as_mut().ok_or_else(|| {
+ trace!("Cannot send data. Client is not connected.");
+ IggyError::NotConnected
+ })?;
+ let payload_length = payload.len() + REQUEST_INITIAL_BYTES_LENGTH;
+ let mut request =
+ BytesMut::with_capacity(4 + REQUEST_INITIAL_BYTES_LENGTH + payload.len());
+ request.put_u32_le(payload_length as u32);
+ request.put_u32_le(code);
+ request.put_slice(&payload);
+ trace!(
+ "Sending {NAME} message with code: {}, payload size: {} bytes",
+ code,
+ payload.len()
+ );
+ stream.write(&request).await?;
+ stream.flush().await?;
+
let mut response_initial_buffer = vec![0u8; RESPONSE_INITIAL_BYTES_LENGTH];
stream.read(&mut response_initial_buffer).await?;
diff --git a/core/server-ng/src/auth.rs b/core/server-ng/src/auth.rs
index b8aa393f6..8b8699755 100644
--- a/core/server-ng/src/auth.rs
+++ b/core/server-ng/src/auth.rs
@@ -26,12 +26,12 @@ use crate::dispatch::submit_register_on_owner;
use crate::login_register::LoginRegisterError;
use crate::responses::{build_empty_reply, build_login_register_reply, current_metadata_commit};
use crate::session_manager::{ClientSdkInfo, SessionManager};
-use consensus::MetadataHandle;
+use consensus::{MetadataHandle, build_transient_reply};
use iggy_binary_protocol::{ClientVersionInfo, RequestHeader};
use iggy_common::defaults::{
MAX_PASSWORD_LENGTH, MAX_USERNAME_LENGTH, MIN_PASSWORD_LENGTH, MIN_USERNAME_LENGTH,
};
-use iggy_common::{IggyTimestamp, PersonalAccessToken, UserStatus};
+use iggy_common::{IggyError, IggyTimestamp, PersonalAccessToken, UserStatus};
use message_bus::MessageBus;
use metadata::impls::metadata::StreamsFrontend;
use server::streaming::utils::crypto;
@@ -210,6 +210,42 @@ pub(crate) async fn surface_login_failure(
) {
if error.is_terminal() {
send_login_failure_reply(shard, transport_client_id, request_header).await;
+ } else {
+ // Transient consensus failure (not-caught-up / not-primary / pipeline
+ // full): send the explicit `TransientNotCommitted` frame instead of
+ // staying silent, so the SDK replays the login immediately rather than
+ // waiting out its read-timeout. Same contract as a transient metadata
+ // request -- nothing committed, so the replayed Register is idempotent.
+ send_login_transient_reply(shard, transport_client_id, request_header).await;
+ }
+}
+
+/// Result-framed `TransientNotCommitted` Reply on a transient (non-terminal)
+/// failed Register. The SDK decodes the nonzero result code and replays the
+/// same login on the same connection. Only call for transient errors -- see
+/// [`surface_login_failure`].
+#[allow(clippy::future_not_send)]
+async fn send_login_transient_reply(
+ shard: &Rc<ServerNgShard>,
+ transport_client_id: u128,
+ request_header: &RequestHeader,
+) {
+ let commit = current_metadata_commit(shard);
+ let reply = build_transient_reply(
+ request_header,
+ commit,
+ IggyError::TransientNotCommitted.as_code(),
+ );
+ if let Err(error) = shard
+ .bus
+ .send_to_client(transport_client_id, reply.into_generic().into_frozen())
+ .await
+ {
+ warn!(
+ transport_client_id,
+ error = %error,
+ "failed to send login transient reply"
+ );
}
}
diff --git a/core/server-ng/src/responses.rs b/core/server-ng/src/responses.rs
index bd11b9915..4d1d7e8a6 100644
--- a/core/server-ng/src/responses.rs
+++ b/core/server-ng/src/responses.rs
@@ -33,6 +33,7 @@ use iggy_binary_protocol::codes::{
GET_STREAM_CODE, GET_STREAMS_CODE, GET_TOPIC_CODE, GET_TOPICS_CODE, GET_USER_CODE,
GET_USERS_CODE,
};
+use iggy_binary_protocol::consensus::{RESULT_COUNT_LEN, result_code};
use iggy_binary_protocol::primitives::consumer::WireConsumer;
use iggy_binary_protocol::requests::consumer_groups::{
GetConsumerGroupRequest, GetConsumerGroupsRequest,
@@ -788,14 +789,22 @@ pub(crate) fn build_login_register_reply(
commit: u64,
user_id: u32,
) -> Message<ReplyHeader> {
- let body = LoginRegisterResponse {
+ // Result-framed like every metadata reply: a zero result-count (success)
+ // followed by the `LoginRegisterResponse` payload. A transient Register
+ // instead ships a `[count=1][index=0][TransientNotCommitted]` frame
+ // (`build_transient_reply`), which the SDK decodes and replays. The matching
+ // strip is in the SDK `split_metadata_result` (Register is result-framed).
+ let payload = LoginRegisterResponse {
user_id,
session,
server_protocol_version: IGGY_PROTOCOL_VERSION,
server_version: WireName::new(SERVER_VERSION).expect("SERVER_VERSION is 1-255 bytes"),
}
.to_bytes();
- build_reply_from_bytes(request_header, client_id, session, commit, &body)
+ let mut body = Vec::with_capacity(RESULT_COUNT_LEN + payload.len());
+ body.extend_from_slice(&[0u8; RESULT_COUNT_LEN]);
+ body.extend_from_slice(&payload);
+ build_reply_from_bytes(request_header, client_id, session, commit, &Bytes::from(body))
}
pub(crate) fn build_reply_from_bytes(
@@ -839,12 +848,30 @@ pub(crate) fn build_raw_pat_reply(
return Ok(committed);
}
let header_len = std::mem::size_of::<ReplyHeader>();
+ // A `Reply` whose result section is nonzero is not a successful commit but a
+ // committed business rejection or a `TransientNotCommitted` retry frame, both
+ // with no payload and no token to ship. Pass it through so the client decodes
+ // the typed result (and, for a transient, replays) instead of having a raw
+ // token grafted onto a rejection body.
+ if result_code(&committed.as_slice()[header_len..]) != Some(0) {
+ return Ok(committed);
+ }
let committed_header =
bytemuck::checked::try_from_bytes::<ReplyHeader>(&committed.as_slice()[..header_len])
.map_err(|_| IggyError::InvalidFormat)?;
let commit = committed_header.commit;
let token = WireName::new(raw.as_str()).map_err(|_| IggyError::InvalidFormat)?;
- let body = RawPersonalAccessTokenResponse { token }.to_bytes();
+ let token_payload = RawPersonalAccessTokenResponse { token }.to_bytes();
+ // Metadata reply bodies are framed `[result_count:u32][payload]`; a success
+ // is `count == 0` followed by the payload (see `ApplyReply::write_reply_body`
+ // / `result_code`). The committed reply carried an empty payload with this
+ // same framing, so reproduce it here - prepend the zero result-count rather
+ // than shipping a bare `RawPersonalAccessTokenResponse`, which the client
+ // would misread as the result-count and reject as a bogus error.
+ let mut framed = Vec::with_capacity(RESULT_COUNT_LEN + token_payload.len());
+ framed.extend_from_slice(&[0u8; RESULT_COUNT_LEN]);
+ framed.extend_from_slice(&token_payload);
+ let body = Bytes::from(framed);
let reply = build_reply_from_bytes(
request_header,
request_header.client,
diff --git a/core/shard/src/lib.rs b/core/shard/src/lib.rs
index 424c71ac3..8bc00a2ae 100644
--- a/core/shard/src/lib.rs
+++ b/core/shard/src/lib.rs
@@ -1830,6 +1830,11 @@ where
Entry = Message<PrepareHeader>,
Header = PrepareHeader,
>,
+ M: StateMachine<
+ Input = Message<PrepareHeader>,
+ Output = metadata::stm::result::ApplyReply,
+ Error = iggy_common::IggyError,
+ > + StreamsFrontend,
{
let metadata = self.plane.metadata();
let Some(ref consensus) = metadata.consensus else {
@@ -1839,6 +1844,13 @@ where
let actions = consensus.tick(PlaneKind::Metadata);
dispatch_vsr_actions(consensus, metadata.journal.as_ref(), &actions).await;
+
+ // Repair a lost primary self-ack: `RetransmitPrepares` to self is a
+ // no-op, so the timer-driven retransmit above cannot recover the
+ // primary's own missing vote. Without this the commit prefix can pin
+ // forever (commit_min stuck below commit_max). See
+ // `IggyMetadata::repair_primary_self_acks`.
+ metadata.repair_primary_self_acks().await;
}
}