You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by pi...@apache.org on 2026/09/07 09:26:39 UTC
(iggy) branch master updated: fix(partitions): bound consumer offset state per partition (#4063)
This is an automated email from the ASF dual-hosted git repository.
spetz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iggy.git
The following commit(s) were added to refs/heads/master by this push:
new 0bdd8c6ca fix(partitions): bound consumer offset state per partition (#4063)
0bdd8c6ca is described below
commit 0bdd8c6ca83e4b80f46e2c3793491c0ad4aa9e56
Author: Piotr Gankiewicz <pi...@gmail.com>
AuthorDate: Mon Sep 7 11:26:35 2026 +0200
fix(partitions): bound consumer offset state per partition (#4063)
Every distinct consumer id stored one offset file and one map
entry per partition with no upper bound, so a partition could
accumulate durable state until the filesystem or memory gave out
and the replica fenced itself. Offset deletes acknowledged
locally could also free a primary slot while backups kept every
older generation, and follower-served auto-commit cursors could
be promoted into committed state across leadership changes.
Add a per-partition, per-kind admission limit enforced on the
primary before a new key enters consensus or touches disk.
Admission counts durable keys plus in-flight reservations, so
existing consumers keep updating at the limit while new keys
get a typed TooManyConsumerOffsets reply. Replicated partitions
now commit every offset store and delete through VSR regardless
of the acknowledgement byte, and consumer-group cleanup uses
replicated deletes, which keeps file counts identical on all
replicas. State transfer exports committed values only, and
recovery preserves state above a lowered limit with a warning.
Auto-commit hands its reservation to the partition pump through
an internal frame instead of a per-poll waiter, phantom cursors
are reclaimed on promotion, and the reconciler no longer runs a
full pass on every group offset advance. Missing consumer groups
return the existing not-found codes. The limit ships as
[partition] consumer_offsets_max with a default of 4096, and the
new error code is mirrored in the Go, Java, and Node SDKs.
---
Cargo.lock | 22 +-
Cargo.toml | 10 +-
bdd/go/tests/tcp_test/offset_feature_delete.go | 21 +-
bdd/python/uv.lock | 2 +-
core/ai/mcp/Cargo.toml | 2 +-
core/bench/Cargo.toml | 2 +-
core/bench/dashboard/frontend/Cargo.toml | 2 +-
core/bench/dashboard/server/Cargo.toml | 2 +-
core/bench/report/Cargo.toml | 2 +-
core/bench/src/benchmarks/common.rs | 10 +-
core/binary_protocol/Cargo.toml | 2 +-
core/binary_protocol/src/primitives/ack_level.rs | 9 +-
.../consumer_offsets/delete_consumer_offset.rs | 4 +-
.../consumer_offsets/store_consumer_offset.rs | 4 +-
core/cli/Cargo.toml | 2 +-
core/common/Cargo.toml | 2 +-
core/common/src/error/iggy_error.rs | 10 +
core/common/src/traits/consumer_offset_client.rs | 7 +
core/common/src/traits/message_client.rs | 10 +
core/configs/src/server_config/defaults.rs | 2 +
core/configs/src/server_config/displays.rs | 6 +-
core/configs/src/server_config/partition.rs | 72 +
core/connectors/sdk/Cargo.toml | 2 +-
core/integration/src/harness/disk.rs | 33 +-
.../tests/cluster/consumer_offset_quota.rs | 357 +++
core/integration/tests/cluster/mod.rs | 1 +
.../tests/server/consumer_offset_quota_vsr.rs | 514 ++++
core/integration/tests/server/mod.rs | 1 +
core/integration/tests/server/raw_tcp.rs | 5 +
core/message_bus/src/lib.rs | 2 +-
core/metadata/src/impls/metadata.rs | 6 +-
core/metadata/src/stm/user.rs | 4 +-
core/partitions/src/consumer_offset_capacity.rs | 717 +++++
core/partitions/src/iggy_partition.rs | 2771 +++++++++++++++++---
core/partitions/src/iggy_partitions.rs | 51 +-
core/partitions/src/lib.rs | 19 +-
core/partitions/src/offset_storage.rs | 197 +-
core/partitions/src/poll_plan.rs | 352 ++-
core/partitions/src/state_transfer.rs | 727 +++--
core/partitions/src/types.rs | 5 +
core/sdk/Cargo.toml | 2 +-
core/sdk/src/clients/consumer.rs | 32 +-
core/sdk/src/leader_aware.rs | 25 +
core/sdk/src/quic/quic_client.rs | 14 +-
core/sdk/src/tcp/tcp_client.rs | 27 +-
core/sdk/src/websocket/websocket_client.rs | 14 +-
core/server/Cargo.toml | 2 +-
core/server/config.toml | 30 +
core/server/src/boot/recovery.rs | 11 +
core/server/src/consumer_group.rs | 46 +-
core/server/src/dispatch/mod.rs | 1 +
core/server/src/dispatch/partition.rs | 399 ++-
core/server/src/dispatch/session_ops.rs | 1 +
core/server/src/dispatch/test_support.rs | 1 +
core/server/src/http/handlers.rs | 18 +-
core/server/src/offset_recovery.rs | 354 ++-
core/server/src/partition_helpers.rs | 119 +-
core/server/src/partition_reconciler.rs | 380 ++-
core/server/src/responses.rs | 51 +-
core/shard/src/lib.rs | 194 +-
core/shard/src/metrics.rs | 124 +-
core/shard/src/router.rs | 9 +
core/simulator/src/client.rs | 4 +-
core/simulator/src/lib.rs | 239 +-
core/simulator/src/replica.rs | 1 +
core/simulator/src/workload/effect.rs | 2 +-
core/simulator/src/workload/shadow.rs | 2 +-
examples/node/package-lock.json | 2 +-
examples/python/uv.lock | 2 +-
foreign/go/contracts/version.go | 2 +-
foreign/go/errors/errors.yaml | 4 +
foreign/go/errors/errors_gen.go | 17 +
foreign/go/errors/errors_test.go | 19 +
.../org/apache/iggy/exception/IggyErrorCode.java | 3 +
.../apache/iggy/exception/IggyErrorCodeTest.java | 1 +
foreign/node/package-lock.json | 4 +-
foreign/node/package.json | 2 +-
foreign/node/src/wire/error.code.test.ts | 4 +
foreign/node/src/wire/error.code.ts | 1 +
foreign/python/Cargo.toml | 4 +-
foreign/python/pyproject.toml | 2 +-
foreign/python/uv.lock | 2 +-
82 files changed, 7052 insertions(+), 1088 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 56ecb71dd..7856dd413 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1862,7 +1862,7 @@ checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1"
[[package]]
name = "bench-dashboard-frontend"
-version = "0.8.0-edge.3"
+version = "0.8.0-edge.4"
dependencies = [
"bench-dashboard-shared",
"bench-report",
@@ -1892,7 +1892,7 @@ dependencies = [
[[package]]
name = "bench-report"
-version = "0.4.0-edge.3"
+version = "0.4.0-edge.4"
dependencies = [
"charming",
"colored",
@@ -6594,7 +6594,7 @@ checksum = "cd62e6b5e86ea8eeeb8db1de02880a6abc01a397b2ebb64b5d74ac255318f5cb"
[[package]]
name = "iggy"
-version = "0.11.0-edge.6"
+version = "0.11.0-edge.7"
dependencies = [
"async-broadcast",
"async-dropper",
@@ -6628,7 +6628,7 @@ dependencies = [
[[package]]
name = "iggy-bench"
-version = "0.6.0-edge.6"
+version = "0.6.0-edge.7"
dependencies = [
"async-trait",
"bench-report",
@@ -6657,7 +6657,7 @@ dependencies = [
[[package]]
name = "iggy-bench-dashboard-server"
-version = "0.8.0-edge.3"
+version = "0.8.0-edge.4"
dependencies = [
"actix-cors",
"actix-files",
@@ -6685,7 +6685,7 @@ dependencies = [
[[package]]
name = "iggy-cli"
-version = "0.14.0-edge.6"
+version = "0.14.0-edge.7"
dependencies = [
"anyhow",
"apple-native-keyring-store",
@@ -6791,7 +6791,7 @@ dependencies = [
[[package]]
name = "iggy-mcp"
-version = "0.5.0-edge.5"
+version = "0.5.0-edge.6"
dependencies = [
"axum",
"axum-server",
@@ -6825,7 +6825,7 @@ dependencies = [
[[package]]
name = "iggy_binary_protocol"
-version = "0.11.0-edge.6"
+version = "0.11.0-edge.7"
dependencies = [
"aligned-vec",
"bytemuck",
@@ -6838,7 +6838,7 @@ dependencies = [
[[package]]
name = "iggy_common"
-version = "0.11.0-edge.6"
+version = "0.11.0-edge.7"
dependencies = [
"aes-gcm 0.11.1",
"async-broadcast",
@@ -7203,7 +7203,7 @@ dependencies = [
[[package]]
name = "iggy_connector_sdk"
-version = "0.4.0-edge.3"
+version = "0.4.0-edge.4"
dependencies = [
"anyhow",
"apache-avro 0.22.0",
@@ -12160,7 +12160,7 @@ dependencies = [
[[package]]
name = "server"
-version = "0.9.0-edge.6"
+version = "0.9.0-edge.7"
dependencies = [
"ahash 0.8.12",
"argon2",
diff --git a/Cargo.toml b/Cargo.toml
index af7a697ca..beb92e80f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -198,13 +198,13 @@ hyper-util = { version = "0.1.20", features = ["server-auto", "service"] }
iceberg = "0.10.1"
iceberg-catalog-rest = "0.10.1"
iceberg-storage-opendal = "0.10.1"
-iggy = { path = "core/sdk", version = "0.11.0-edge.6" }
-iggy-cli = { path = "core/cli", version = "0.14.0-edge.6" }
+iggy = { path = "core/sdk", version = "0.11.0-edge.7" }
+iggy-cli = { path = "core/cli", version = "0.14.0-edge.7" }
iggy-gateway-kafka = { path = "gateways/kafka" }
-iggy_binary_protocol = { path = "core/binary_protocol", version = "0.11.0-edge.6" }
-iggy_common = { path = "core/common", version = "0.11.0-edge.6" }
+iggy_binary_protocol = { path = "core/binary_protocol", version = "0.11.0-edge.7" }
+iggy_common = { path = "core/common", version = "0.11.0-edge.7" }
iggy_connector_doris_sink = { path = "core/connectors/sinks/doris_sink" }
-iggy_connector_sdk = { path = "core/connectors/sdk", version = "0.4.0-edge.3" }
+iggy_connector_sdk = { path = "core/connectors/sdk", version = "0.4.0-edge.4" }
indexmap = "2.14.1"
integration = { path = "core/integration" }
ipnet = "2.12.1"
diff --git a/bdd/go/tests/tcp_test/offset_feature_delete.go b/bdd/go/tests/tcp_test/offset_feature_delete.go
index 0d8d93d92..f51537560 100644
--- a/bdd/go/tests/tcp_test/offset_feature_delete.go
+++ b/bdd/go/tests/tcp_test/offset_feature_delete.go
@@ -129,12 +129,25 @@ var _ = ginkgo.Describe("DELETE CONSUMER OFFSET:", func() {
&partitionId,
)
- // A consumer-offset request is routed by its packed namespace, so
- // the shard that answers reports a missing resource rather than
- // naming the group.
- itShouldReturnSpecificError(err, ierror.ErrResourceNotFound)
+ // The stream and topic resolve, so the server names the group.
+ itShouldReturnSpecificError(err, ierror.ErrConsumerGroupIdNotFound)
})
+ ginkgo.Context("and attempts to delete an offset from a non-existing named consumer group", func() {
+ client := createAuthorizedConnection()
+ streamId, _ := successfullyCreateStream(prefix, client)
+ defer deleteStreamAfterTests(streamId, client)
+ topicId, _ := successfullyCreateTopic(streamId, client)
+ streamIdentifier, _ := iggcon.NewIdentifier(streamId)
+ topicIdentifier, _ := iggcon.NewIdentifier(topicId)
+ groupIdentifier, _ := iggcon.NewIdentifier("missing-offset-group")
+ partitionId := uint32(1)
+ err := client.DeleteConsumerOffset(
+ context.Background(), iggcon.NewGroupConsumer(groupIdentifier),
+ streamIdentifier, topicIdentifier, &partitionId,
+ )
+ itShouldReturnSpecificError(err, ierror.ErrConsumerGroupNameNotFound)
+ })
ginkgo.Context("and attempts to delete an offset from a non-existing stream", func() {
client := createAuthorizedConnection()
consumer := iggcon.NewGroupConsumer(randomU32Identifier())
diff --git a/bdd/python/uv.lock b/bdd/python/uv.lock
index 44c64ab55..b10e81b84 100644
--- a/bdd/python/uv.lock
+++ b/bdd/python/uv.lock
@@ -8,7 +8,7 @@ exclude-newer-span = "P7D"
[[package]]
name = "apache-iggy"
-version = "0.9.0.dev6"
+version = "0.9.0.dev7"
source = { directory = "../../foreign/python" }
[package.metadata]
diff --git a/core/ai/mcp/Cargo.toml b/core/ai/mcp/Cargo.toml
index 5386c5c4a..1d1953f9f 100644
--- a/core/ai/mcp/Cargo.toml
+++ b/core/ai/mcp/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "iggy-mcp"
-version = "0.5.0-edge.5"
+version = "0.5.0-edge.6"
description = "MCP Server for Iggy message streaming platform"
edition = "2024"
license = "Apache-2.0"
diff --git a/core/bench/Cargo.toml b/core/bench/Cargo.toml
index e2a3c8d8d..7a3f1ce42 100644
--- a/core/bench/Cargo.toml
+++ b/core/bench/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "iggy-bench"
-version = "0.6.0-edge.6"
+version = "0.6.0-edge.7"
edition = "2024"
license = "Apache-2.0"
repository = "https://github.com/apache/iggy"
diff --git a/core/bench/dashboard/frontend/Cargo.toml b/core/bench/dashboard/frontend/Cargo.toml
index 595cec1d0..6b023d631 100644
--- a/core/bench/dashboard/frontend/Cargo.toml
+++ b/core/bench/dashboard/frontend/Cargo.toml
@@ -18,7 +18,7 @@
[package]
name = "bench-dashboard-frontend"
license = "Apache-2.0"
-version = "0.8.0-edge.3"
+version = "0.8.0-edge.4"
edition = "2024"
publish = false
diff --git a/core/bench/dashboard/server/Cargo.toml b/core/bench/dashboard/server/Cargo.toml
index 726df33be..68570b112 100644
--- a/core/bench/dashboard/server/Cargo.toml
+++ b/core/bench/dashboard/server/Cargo.toml
@@ -18,7 +18,7 @@
[package]
name = "iggy-bench-dashboard-server"
license = "Apache-2.0"
-version = "0.8.0-edge.3"
+version = "0.8.0-edge.4"
edition = "2024"
publish = false
diff --git a/core/bench/report/Cargo.toml b/core/bench/report/Cargo.toml
index a418cdd25..bc5649a57 100644
--- a/core/bench/report/Cargo.toml
+++ b/core/bench/report/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "bench-report"
-version = "0.4.0-edge.3"
+version = "0.4.0-edge.4"
edition = "2024"
description = "Benchmark report and chart generation library for iggy-bench binary and iggy-benchmarks-dashboard web app"
license = "Apache-2.0"
diff --git a/core/bench/src/benchmarks/common.rs b/core/bench/src/benchmarks/common.rs
index bd5a38247..ed166bd10 100644
--- a/core/bench/src/benchmarks/common.rs
+++ b/core/bench/src/benchmarks/common.rs
@@ -44,7 +44,11 @@ pub async fn create_consumer(
"Consumer #{} → joining consumer group #{}",
consumer_id, consumer_group_id
);
- let cg_identifier = Identifier::try_from(*consumer_group_id).unwrap();
+ // By name: the group was created by name and the server assigns its
+ // own numeric id, which need not equal the bench's counter.
+ let cg_identifier =
+ Identifier::named(&format!("{CONSUMER_GROUP_NAME_PREFIX}-{consumer_group_id}"))
+ .unwrap();
client
.join_consumer_group(stream_id, topic_id, &cg_identifier)
.await
@@ -209,8 +213,10 @@ pub fn build_consumer_futures(
consumer_id
};
let stream_id = format!("bench-stream-{stream_idx}");
+ // Groups are created as `BASE + 1..=cg_count`, one per stream, so the
+ // consumer must land on the group of the stream it polls.
let consumer_group_id = if cg_count > 0 {
- Some(CONSUMER_GROUP_BASE_ID + (consumer_id % cg_count))
+ Some(CONSUMER_GROUP_BASE_ID + stream_idx)
} else {
None
};
diff --git a/core/binary_protocol/Cargo.toml b/core/binary_protocol/Cargo.toml
index 0a83a4c01..be97141e3 100644
--- a/core/binary_protocol/Cargo.toml
+++ b/core/binary_protocol/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "iggy_binary_protocol"
-version = "0.11.0-edge.6"
+version = "0.11.0-edge.7"
description = "Wire protocol types and codec for the Iggy binary protocol. Shared between server and SDK."
edition = "2024"
rust-version.workspace = true
diff --git a/core/binary_protocol/src/primitives/ack_level.rs b/core/binary_protocol/src/primitives/ack_level.rs
index a2ddb2389..d1fc8064b 100644
--- a/core/binary_protocol/src/primitives/ack_level.rs
+++ b/core/binary_protocol/src/primitives/ack_level.rs
@@ -20,9 +20,12 @@ use crate::WireError;
/// Acknowledgement policy for consumer-offset write commands.
///
/// Wire format: single `u8` discriminant.
-/// - `NoAck(0)`: leader-local write only; respond as soon as the in-memory
-/// and on-disk state have been updated. Matches the fast path used by
-/// `PollMessages` auto-commit.
+/// - `NoAck(0)`: local fast path for a single-replica partition. Replicated
+/// partitions commit offset writes through VSR before replying, including
+/// when this acknowledgement value is selected.
+/// On a single replica, a directory-sync failure can be reported after the
+/// mutation became visible. Its crash durability is then unknown. Retrying
+/// a deletion that already took effect can return `ConsumerOffsetNotFound`.
/// - `Quorum(1)`: submit through the partition VSR consensus pipeline and
/// respond only after the write has been committed by a quorum of replicas.
/// This is the default for explicit client writes.
diff --git a/core/binary_protocol/src/requests/consumer_offsets/delete_consumer_offset.rs b/core/binary_protocol/src/requests/consumer_offsets/delete_consumer_offset.rs
index 014081794..e5ca29d1a 100644
--- a/core/binary_protocol/src/requests/consumer_offsets/delete_consumer_offset.rs
+++ b/core/binary_protocol/src/requests/consumer_offsets/delete_consumer_offset.rs
@@ -24,8 +24,8 @@ use bytes::{BufMut, BytesMut};
/// `DeleteConsumerOffset` request.
///
-/// Adds an `ack` byte: `NoAck` = leader-local fast path, `Quorum` = VSR
-/// pipeline.
+/// The `ack` byte selects the local fast path only for `NoAck` on a
+/// single-replica partition. Replicated partitions use VSR for both values.
///
/// Wire format:
/// ```text
diff --git a/core/binary_protocol/src/requests/consumer_offsets/store_consumer_offset.rs b/core/binary_protocol/src/requests/consumer_offsets/store_consumer_offset.rs
index 5261d5c53..228360798 100644
--- a/core/binary_protocol/src/requests/consumer_offsets/store_consumer_offset.rs
+++ b/core/binary_protocol/src/requests/consumer_offsets/store_consumer_offset.rs
@@ -24,8 +24,8 @@ use bytes::{BufMut, BytesMut};
/// `StoreConsumerOffset` request.
///
-/// Adds an `ack` byte: `NoAck` = leader-local fast path, `Quorum` = VSR
-/// pipeline.
+/// The `ack` byte selects the local fast path only for `NoAck` on a
+/// single-replica partition. Replicated partitions use VSR for both values.
///
/// Wire format:
/// ```text
diff --git a/core/cli/Cargo.toml b/core/cli/Cargo.toml
index a2f8756bb..f8a2b89f1 100644
--- a/core/cli/Cargo.toml
+++ b/core/cli/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "iggy-cli"
-version = "0.14.0-edge.6"
+version = "0.14.0-edge.7"
edition = "2024"
rust-version.workspace = true
authors = ["bartosz.ciesla@gmail.com"]
diff --git a/core/common/Cargo.toml b/core/common/Cargo.toml
index 16aaa621c..2e059fc3e 100644
--- a/core/common/Cargo.toml
+++ b/core/common/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "iggy_common"
-version = "0.11.0-edge.6"
+version = "0.11.0-edge.7"
description = "Iggy is the persistent message streaming platform written in Rust, supporting QUIC, TCP and HTTP transport protocols, capable of processing millions of messages per second."
edition = "2024"
rust-version.workspace = true
diff --git a/core/common/src/error/iggy_error.rs b/core/common/src/error/iggy_error.rs
index e79d96b89..6a31bcb48 100644
--- a/core/common/src/error/iggy_error.rs
+++ b/core/common/src/error/iggy_error.rs
@@ -333,6 +333,8 @@ pub enum IggyError {
NotResolvedConsumer(Identifier) = 3022,
#[error("Cannot open consumer offsets file for path: {0}")]
CannotOpenConsumerOffsetsFile(String) = 3023,
+ #[error("Consumer offset limit reached for partition, raise [partition] consumer_offsets_max")]
+ TooManyConsumerOffsets = 3024,
#[error("Segment not found")]
SegmentNotFound = 4000,
#[error("Segment with start offset: {0} and partition with ID: {1} is closed")]
@@ -627,4 +629,12 @@ mod tests {
IggyError::from_code_as_string(GROUP_NAME_ERROR_CODE)
)
}
+
+ #[test]
+ fn too_many_consumer_offsets_round_trips_by_code() {
+ let error = IggyError::TooManyConsumerOffsets;
+ assert_eq!(error.as_code(), 3024);
+ assert_eq!(IggyError::from_code(3024), error);
+ assert_eq!(IggyError::from_code_as_string(3024), error.as_string());
+ }
}
diff --git a/core/common/src/traits/consumer_offset_client.rs b/core/common/src/traits/consumer_offset_client.rs
index ffdddb7e6..6409ff81d 100644
--- a/core/common/src/traits/consumer_offset_client.rs
+++ b/core/common/src/traits/consumer_offset_client.rs
@@ -24,6 +24,7 @@ pub trait ConsumerOffsetClient {
/// Store the consumer offset for a specific consumer or consumer group for the given stream and topic by unique IDs or names.
///
/// Authentication is required, and the permission to poll the messages.
+ /// A new key at the per-partition limit returns [`IggyError::TooManyConsumerOffsets`] (3024).
async fn store_consumer_offset(
&self,
consumer: &Consumer,
@@ -35,6 +36,8 @@ pub trait ConsumerOffsetClient {
/// Get the consumer offset for a specific consumer or consumer group for the given stream and topic by unique IDs or names.
///
/// Authentication is required, and the permission to poll the messages.
+ /// An absent offset key returns `Ok(None)` when its stream, topic, and consumer group resolve.
+ /// A local auto-commit cursor can be visible before its durable store commits.
async fn get_consumer_offset(
&self,
consumer: &Consumer,
@@ -45,6 +48,10 @@ pub trait ConsumerOffsetClient {
/// Delete the consumer offset for a specific consumer or consumer group for the given stream and topic by unique IDs or names.
///
/// Authentication is required, and the permission to poll the messages.
+ /// A missing durable key returns [`IggyError::ConsumerOffsetNotFound`] (3021).
+ /// Missing numeric and named groups return codes 5000 and 5003 respectively.
+ /// A replica unable to admit the request returns [`IggyError::TransientNotAccepted`].
+ /// Deletion does not allocate a new key and is allowed at the offset limit.
async fn delete_consumer_offset(
&self,
consumer: &Consumer,
diff --git a/core/common/src/traits/message_client.rs b/core/common/src/traits/message_client.rs
index 18c6d2294..b71017647 100644
--- a/core/common/src/traits/message_client.rs
+++ b/core/common/src/traits/message_client.rs
@@ -30,6 +30,16 @@ pub trait MessageClient {
///
/// Polling a consumer group the client is not (or no longer) a member of fails with `ConsumerGroupMemberNotFound` rather than returning an empty batch, so the caller can rejoin.
/// A member that holds no partitions gets an empty batch whose `partition_id` is [`NO_ASSIGNED_PARTITION`](crate::NO_ASSIGNED_PARTITION).
+ ///
+ /// With server-side auto-commit enabled, a new consumer offset key can be
+ /// rejected with `TooManyConsumerOffsets` at the partition's configured
+ /// limit. That poll returns no messages. Existing keys remain writable,
+ /// and polling without auto-commit does not allocate a stored offset.
+ /// A refused auto-commit submission returns `TransientNotAccepted` with no
+ /// messages and may be retried. A capacity error requires capacity to be freed.
+ /// Local cursors without a committed offset can be evicted at the limit.
+ /// Their next `Next` poll resumes from the earliest retained messages,
+ /// which can redeliver messages from earlier polls.
#[allow(clippy::too_many_arguments)]
async fn poll_messages(
&self,
diff --git a/core/configs/src/server_config/defaults.rs b/core/configs/src/server_config/defaults.rs
index 330f39877..a08913968 100644
--- a/core/configs/src/server_config/defaults.rs
+++ b/core/configs/src/server_config/defaults.rs
@@ -183,6 +183,8 @@ impl Default for PartitionConfig {
PartitionConfig {
prepare_queue_depth: partition.prepare_queue_depth as usize,
dedup_clients_max: partition.dedup_clients_max as usize,
+ consumer_offsets_max: partition.consumer_offsets_max as usize,
+ consumer_offset_enforce_fsync: partition.consumer_offset_enforce_fsync,
offset_reservation_lease: NonZeroU32::new(partition.offset_reservation_lease as u32)
.expect("the embedded config.toml carries a nonzero offset_reservation_lease"),
evicted_ring_capacity: partition.evicted_ring_capacity as usize,
diff --git a/core/configs/src/server_config/displays.rs b/core/configs/src/server_config/displays.rs
index 5c46c7b82..d0284e588 100644
--- a/core/configs/src/server_config/displays.rs
+++ b/core/configs/src/server_config/displays.rs
@@ -56,10 +56,14 @@ impl Display for PartitionConfig {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
- "{{ prepare_queue_depth: {}, offset_reservation_lease: {}, \
+ "{{ prepare_queue_depth: {}, dedup_clients_max: {}, consumer_offsets_max: {}, \
+ consumer_offset_enforce_fsync: {}, offset_reservation_lease: {}, \
evicted_ring_capacity: {}, evicted_ring_bytes_max: {}, \
transfer_served_cache_bytes_max: {}, transfer_artifact_bytes_max: {} }}",
self.prepare_queue_depth,
+ self.dedup_clients_max,
+ self.consumer_offsets_max,
+ self.consumer_offset_enforce_fsync,
self.offset_reservation_lease,
self.evicted_ring_capacity,
self.evicted_ring_bytes_max,
diff --git a/core/configs/src/server_config/partition.rs b/core/configs/src/server_config/partition.rs
index 86ee3a7c4..56257936c 100644
--- a/core/configs/src/server_config/partition.rs
+++ b/core/configs/src/server_config/partition.rs
@@ -139,6 +139,23 @@ pub const PARTITION_DEDUP_CLIENTS_DEFAULT: usize = 4096;
/// bytes`: a 112-byte slot entry plus its index-map slot.
pub const PARTITION_DEDUP_CLIENTS_CEILING: usize = 1 << 16;
+/// Shipped per-kind consumer-offset cardinality limit for one partition.
+///
+/// Mirrors `partitions::DEFAULT_CONSUMER_OFFSETS_MAX`. The server crate pins
+/// the duplicated literals because configs must not depend on partitions.
+pub const PARTITION_CONSUMER_OFFSETS_DEFAULT: usize = 4096;
+
+/// Configuration typo guard for the per-kind consumer-offset limit.
+///
+/// The runtime state-transfer decoder accepts `1 << 20` entries per section.
+/// Keeping the configurable ceiling at one quarter leaves room for recovered
+/// over-limit state while the shipped default remains much smaller.
+pub const PARTITION_CONSUMER_OFFSETS_CEILING: usize = 1 << 18;
+
+fn default_consumer_offsets_max() -> usize {
+ PARTITION_CONSUMER_OFFSETS_DEFAULT
+}
+
/// Capacity tunables for the per-partition consensus plane.
#[derive(Debug, Deserialize, Serialize, Clone, ConfigEnv)]
pub struct PartitionConfig {
@@ -161,6 +178,19 @@ pub struct PartitionConfig {
/// single partition actually sees, not the node's client total.
pub dedup_clients_max: usize,
+ /// Distinct durable consumer-offset keys admitted per kind by one
+ /// partition primary. Existing keys remain writable at the limit.
+ #[serde(default = "default_consumer_offsets_max")]
+ pub consumer_offsets_max: usize,
+
+ /// Whether consumer-offset files are written crash-safe: data-synced, then
+ /// renamed over the prior cursor, with the directory synced once per commit
+ /// walk. Independent of the topic's `enforce_fsync`, which governs message
+ /// and index files. Off, an offset file is rewritten in place with no sync.
+ /// A lost or torn cursor can cause replay from the earliest retained data.
+ #[serde(default)]
+ pub consumer_offset_enforce_fsync: bool,
+
/// Offsets claimed in the superblock ahead of the mint counter before an
/// append, so a crash-restarted replica resumes above what it confirmed.
/// One superblock write per block: lowering it raises the fsync rate,
@@ -244,6 +274,16 @@ impl Validatable<ConfigurationError> for PartitionConfig {
);
return Err(ConfigurationError::InvalidConfigurationValue);
}
+ if self.consumer_offsets_max == 0
+ || self.consumer_offsets_max > PARTITION_CONSUMER_OFFSETS_CEILING
+ {
+ eprintln!(
+ "{COMPONENT} partition.consumer_offsets_max ({}) must be > 0 and <= \
+ {PARTITION_CONSUMER_OFFSETS_CEILING}",
+ self.consumer_offsets_max
+ );
+ return Err(ConfigurationError::InvalidConfigurationValue);
+ }
if self.offset_reservation_lease.get() > MAX_OFFSET_RESERVATION_LEASE {
eprintln!(
"{COMPONENT} partition.offset_reservation_lease ({}) exceeds the maximum \
@@ -337,6 +377,34 @@ mod tests {
);
}
+ #[test]
+ fn shipped_consumer_offsets_default_matches_constant() {
+ assert_eq!(
+ PartitionConfig::default().consumer_offsets_max,
+ PARTITION_CONSUMER_OFFSETS_DEFAULT
+ );
+ }
+
+ #[test]
+ fn rejects_out_of_range_consumer_offsets_max() {
+ for value in [0, PARTITION_CONSUMER_OFFSETS_CEILING + 1] {
+ let config = PartitionConfig {
+ consumer_offsets_max: value,
+ ..PartitionConfig::default()
+ };
+ assert!(config.validate().is_err());
+ }
+ }
+
+ #[test]
+ fn accepts_consumer_offsets_max_at_ceiling() {
+ let config = PartitionConfig {
+ consumer_offsets_max: PARTITION_CONSUMER_OFFSETS_CEILING,
+ ..PartitionConfig::default()
+ };
+ assert!(config.validate().is_ok());
+ }
+
#[test]
fn rejects_out_of_range_dedup_clients_max() {
for value in [0, PARTITION_DEDUP_CLIENTS_CEILING + 1] {
@@ -420,6 +488,10 @@ mod tests {
config.offset_reservation_lease.get(),
DEFAULT_OFFSET_RESERVATION_LEASE
);
+ assert_eq!(
+ config.consumer_offsets_max,
+ PARTITION_CONSUMER_OFFSETS_DEFAULT
+ );
assert!(config.validate().is_ok());
}
diff --git a/core/connectors/sdk/Cargo.toml b/core/connectors/sdk/Cargo.toml
index fae1b4a0a..5d6b98daa 100644
--- a/core/connectors/sdk/Cargo.toml
+++ b/core/connectors/sdk/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "iggy_connector_sdk"
-version = "0.4.0-edge.3"
+version = "0.4.0-edge.4"
description = "Iggy is the persistent message streaming platform written in Rust, supporting QUIC, TCP and HTTP transport protocols, capable of processing millions of messages per second."
edition = "2024"
license = "Apache-2.0"
diff --git a/core/integration/src/harness/disk.rs b/core/integration/src/harness/disk.rs
index 97d42b16c..4b72890f7 100644
--- a/core/integration/src/harness/disk.rs
+++ b/core/integration/src/harness/disk.rs
@@ -26,7 +26,7 @@ use std::path::{Path, PathBuf};
use std::time::Duration;
use consensus::VsrState;
-use iggy::prelude::{ClusterClient, ClusterNodeRole};
+use iggy::prelude::{ClusterClient, ClusterNodeRole, ConsumerKind};
use journal::superblock::{SLOT_FILE_NAMES, SuperblockContents, decode_slots};
use tokio::time::sleep;
@@ -39,6 +39,37 @@ const CONVERGENCE_POLL_INTERVAL: Duration = Duration::from_millis(200);
const CONVERGENCE_DEADLINE: Duration = Duration::from_secs(20);
const CONVERGENCE_STABLE_POLLS: u32 = 3;
+/// Numeric regular offset files in one partition's selected kind directory.
+pub fn consumer_offset_file_ids(
+ data_path: &Path,
+ stream_id: u32,
+ topic_id: u32,
+ partition_id: u32,
+ kind: ConsumerKind,
+) -> std::io::Result<BTreeSet<u32>> {
+ let kind_dir = match kind {
+ ConsumerKind::Consumer => "consumers",
+ ConsumerKind::ConsumerGroup => "groups",
+ };
+ let dir = data_path.join(format!(
+ "streams/{stream_id}/topics/{topic_id}/partitions/{partition_id}/offsets/{kind_dir}"
+ ));
+ let entries = fs::read_dir(dir)?;
+ let mut ids = BTreeSet::new();
+ for entry in entries {
+ let entry = entry?;
+ if entry.file_type()?.is_file()
+ && let Some(id) = entry
+ .file_name()
+ .to_str()
+ .and_then(|name| name.parse().ok())
+ {
+ ids.insert(id);
+ }
+ }
+ Ok(ids)
+}
+
/// A partition segment `.log`, named for its 20-digit zero-padded base offset
/// (see `partitions::state_transfer`'s path builders).
///
diff --git a/core/integration/tests/cluster/consumer_offset_quota.rs b/core/integration/tests/cluster/consumer_offset_quota.rs
new file mode 100644
index 000000000..3aa9a7d9d
--- /dev/null
+++ b/core/integration/tests/cluster/consumer_offset_quota.rs
@@ -0,0 +1,357 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.
+
+use crate::server::raw_tcp;
+use iggy::prelude::*;
+use iggy_binary_protocol::codec::WireEncode;
+use iggy_binary_protocol::consensus::Operation;
+use iggy_binary_protocol::requests::consumer_offsets::{
+ DeleteConsumerOffsetRequest, StoreConsumerOffsetRequest,
+};
+use iggy_binary_protocol::{AckLevel, WireConsumer, WireIdentifier};
+use integration::harness::{TestHarness, disk};
+use integration::iggy_harness;
+use std::path::PathBuf;
+use std::time::Duration;
+use tokio::time::{Instant, sleep};
+
+const STREAM_NAME: &str = "cluster-offset-quota-stream";
+const TOPIC_NAME: &str = "cluster-offset-quota-topic";
+const PARTITION_ID: u32 = 0;
+const RAW_CLIENT_ID: u128 = 0xC0FF_EE02;
+const WAIT: Duration = Duration::from_secs(20);
+
+#[iggy_harness(
+ cluster_nodes = 3,
+ server(partition.consumer_offsets_max = "4")
+)]
+async fn given_replicated_partition_when_no_ack_offsets_mutate_should_converge_and_stay_bounded(
+ harness: &mut TestHarness,
+) {
+ let leader = disk::leader_node_index(harness).await;
+ let client = harness
+ .root_client_for_node(leader)
+ .await
+ .expect("root client");
+ let stream = Identifier::named(STREAM_NAME).expect("stream identifier");
+ let topic = Identifier::named(TOPIC_NAME).expect("topic identifier");
+ let stream_details = client
+ .create_stream(STREAM_NAME)
+ .await
+ .expect("create stream");
+ let topic_details = client
+ .create_topic(
+ &stream,
+ TOPIC_NAME,
+ &TopicCreateOptions {
+ partitions_count: Some(1),
+ message_expiry: Some(IggyExpiry::NeverExpire),
+ ..TopicCreateOptions::default()
+ },
+ )
+ .await
+ .expect("create topic");
+ let mut messages = vec![
+ IggyMessage::builder()
+ .payload("cluster-offset-quota".into())
+ .build()
+ .expect("build message"),
+ ];
+ client
+ .send_messages(
+ &stream,
+ &topic,
+ &Partitioning::partition_id(PARTITION_ID),
+ &mut messages,
+ )
+ .await
+ .expect("seed non-empty partition");
+
+ let address = harness.node(leader).tcp_addr().expect("leader TCP address");
+ let mut raw = raw_tcp::connect_to(address).await;
+ let session = raw_tcp::register_root(&mut raw, RAW_CLIENT_ID).await;
+ let wire_stream = WireIdentifier::Numeric(stream_details.id);
+ let wire_topic = WireIdentifier::Numeric(topic_details.id);
+ let raw_consumer_id = 41;
+
+ let store = StoreConsumerOffsetRequest {
+ consumer: WireConsumer::consumer(WireIdentifier::Numeric(raw_consumer_id)),
+ stream_id: wire_stream.clone(),
+ topic_id: wire_topic.clone(),
+ partition_id: Some(PARTITION_ID),
+ offset: 0,
+ ack: AckLevel::NoAck,
+ }
+ .to_bytes();
+ let store_header = raw_tcp::request_header(
+ Operation::StoreConsumerOffset,
+ RAW_CLIENT_ID,
+ session,
+ 1,
+ store.len(),
+ );
+ let (reply, _) = raw_tcp::exchange(&mut raw, &store_header, &store).await;
+ assert_eq!(raw_tcp::reply_status(&reply), 0);
+ wait_for_file_state(
+ harness,
+ stream_details.id,
+ topic_details.id,
+ raw_consumer_id,
+ true,
+ )
+ .await;
+
+ let delete = DeleteConsumerOffsetRequest {
+ consumer: WireConsumer::consumer(WireIdentifier::Numeric(raw_consumer_id)),
+ stream_id: wire_stream,
+ topic_id: wire_topic,
+ partition_id: Some(PARTITION_ID),
+ ack: AckLevel::NoAck,
+ }
+ .to_bytes();
+ let delete_header = raw_tcp::request_header(
+ Operation::DeleteConsumerOffset,
+ RAW_CLIENT_ID,
+ session,
+ 2,
+ delete.len(),
+ );
+ let (reply, _) = raw_tcp::exchange(&mut raw, &delete_header, &delete).await;
+ assert_eq!(raw_tcp::reply_status(&reply), 0);
+ wait_for_file_state(
+ harness,
+ stream_details.id,
+ topic_details.id,
+ raw_consumer_id,
+ false,
+ )
+ .await;
+
+ let auto_commit_consumer = Consumer::new(Identifier::numeric(1).expect("consumer identifier"));
+ let polled = client
+ .poll_messages(
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ &auto_commit_consumer,
+ &PollingStrategy::first(),
+ 1,
+ true,
+ )
+ .await
+ .expect("auto-commit poll within limit");
+ assert_eq!(polled.messages.len(), 1);
+ wait_for_file_state(harness, stream_details.id, topic_details.id, 1, true).await;
+
+ for consumer_id in 1..=4 {
+ client
+ .store_consumer_offset(
+ &Consumer::new(Identifier::numeric(consumer_id).expect("consumer identifier")),
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ 0,
+ )
+ .await
+ .expect("store offset within limit");
+ }
+ let rejected = client
+ .store_consumer_offset(
+ &Consumer::new(Identifier::numeric(5).expect("consumer identifier")),
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ 0,
+ )
+ .await;
+ assert!(matches!(rejected, Err(IggyError::TooManyConsumerOffsets)));
+ wait_for_max_file_count(harness, stream_details.id, topic_details.id, 4).await;
+
+ let backup = (0..harness.cluster_size())
+ .find(|node| *node != leader)
+ .expect("backup replica");
+ harness
+ .kill_node(backup)
+ .expect("pause one replica during group churn");
+ for generation in 0..6 {
+ let name = format!("quota-group-{generation}");
+ client
+ .create_consumer_group(&stream, &topic, &name)
+ .await
+ .expect("create group");
+ let group = Identifier::named(&name).expect("group identifier");
+ client
+ .join_consumer_group(&stream, &topic, &group)
+ .await
+ .expect("join group");
+ client
+ .store_consumer_offset(
+ &Consumer::group(group.clone()),
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ 0,
+ )
+ .await
+ .expect("store valid group offset");
+ client
+ .delete_consumer_group(&stream, &topic, &group)
+ .await
+ .expect("delete group metadata");
+ let deadline = Instant::now() + WAIT;
+ loop {
+ let ids = disk::consumer_offset_file_ids(
+ &harness.node(leader).data_path(),
+ stream_details.id,
+ topic_details.id,
+ PARTITION_ID,
+ ConsumerKind::ConsumerGroup,
+ )
+ .expect("group offset directory");
+ if ids.is_empty() {
+ break;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "replicated cleanup did not delete {ids:?}"
+ );
+ sleep(Duration::from_millis(50)).await;
+ }
+ }
+ harness
+ .restart_node(backup)
+ .expect("restart lagging replica");
+ client
+ .send_messages(
+ &stream,
+ &topic,
+ &Partitioning::partition_id(PARTITION_ID),
+ &mut messages,
+ )
+ .await
+ .expect("produce after rejoin");
+ client
+ .store_consumer_offset(
+ &Consumer::new(Identifier::numeric(1).unwrap()),
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ 1,
+ )
+ .await
+ .expect("store convergence marker");
+ let deadline = Instant::now() + WAIT;
+ loop {
+ let caught_up = (0..harness.cluster_size()).all(|node| {
+ std::fs::read(offset_file(
+ harness,
+ node,
+ stream_details.id,
+ topic_details.id,
+ 1,
+ ))
+ .ok()
+ .and_then(|bytes| bytes.first_chunk::<8>().copied())
+ .map(u64::from_le_bytes)
+ == Some(1)
+ });
+ if caught_up {
+ break;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "replica never applied the post-cleanup marker"
+ );
+ sleep(Duration::from_millis(50)).await;
+ }
+ for node in 0..harness.cluster_size() {
+ assert!(
+ disk::consumer_offset_file_ids(
+ &harness.node(node).data_path(),
+ stream_details.id,
+ topic_details.id,
+ PARTITION_ID,
+ ConsumerKind::ConsumerGroup
+ )
+ .expect("rejoined group directory")
+ .is_empty(),
+ "node {node} retained deleted group generations"
+ );
+ }
+}
+
+async fn wait_for_file_state(
+ harness: &TestHarness,
+ stream_id: u32,
+ topic_id: u32,
+ consumer_id: u32,
+ expected: bool,
+) {
+ let deadline = Instant::now() + WAIT;
+ loop {
+ let states: Vec<bool> = (0..harness.cluster_size())
+ .map(|node| offset_file(harness, node, stream_id, topic_id, consumer_id).exists())
+ .collect();
+ if states.iter().all(|state| *state == expected) {
+ return;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "consumer offset file state did not converge to {expected}: {states:?}"
+ );
+ sleep(Duration::from_millis(100)).await;
+ }
+}
+
+async fn wait_for_max_file_count(harness: &TestHarness, stream_id: u32, topic_id: u32, max: usize) {
+ let deadline = Instant::now() + WAIT;
+ loop {
+ let counts: Vec<usize> = (0..harness.cluster_size())
+ .map(|node| {
+ disk::consumer_offset_file_ids(
+ &harness.node(node).data_path(),
+ stream_id,
+ topic_id,
+ PARTITION_ID,
+ ConsumerKind::Consumer,
+ )
+ .expect("consumer offset directory")
+ .len()
+ })
+ .collect();
+ if counts.iter().all(|count| *count == max) {
+ return;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "consumer offset files did not converge at {max}: {counts:?}"
+ );
+ sleep(Duration::from_millis(100)).await;
+ }
+}
+
+fn offset_file(
+ harness: &TestHarness,
+ node: usize,
+ stream_id: u32,
+ topic_id: u32,
+ consumer_id: u32,
+) -> PathBuf {
+ harness.node(node).data_path().join(format!(
+ "streams/{stream_id}/topics/{topic_id}/partitions/{PARTITION_ID}/offsets/consumers/{consumer_id}"
+ ))
+}
diff --git a/core/integration/tests/cluster/mod.rs b/core/integration/tests/cluster/mod.rs
index 57359759f..e9f81fb93 100644
--- a/core/integration/tests/cluster/mod.rs
+++ b/core/integration/tests/cluster/mod.rs
@@ -17,6 +17,7 @@
mod client_table_adversarial;
mod client_table_restart;
+mod consumer_offset_quota;
mod crash_durability;
mod crash_offset_reuse;
mod crash_recovery_corruption;
diff --git a/core/integration/tests/server/consumer_offset_quota_vsr.rs b/core/integration/tests/server/consumer_offset_quota_vsr.rs
new file mode 100644
index 000000000..ef454b81e
--- /dev/null
+++ b/core/integration/tests/server/consumer_offset_quota_vsr.rs
@@ -0,0 +1,514 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.
+
+use iggy::prelude::*;
+use iggy_binary_protocol::codec::WireEncode;
+use iggy_binary_protocol::consensus::Operation;
+use iggy_binary_protocol::requests::consumer_offsets::StoreConsumerOffsetRequest;
+use iggy_binary_protocol::{AckLevel, WireConsumer, WireIdentifier};
+use iggy_common::store_consumer_offset::StoreConsumerOffset;
+use integration::harness::TestBinary;
+use integration::iggy_harness;
+use reqwest::StatusCode;
+use std::collections::BTreeMap;
+use std::fs;
+
+use super::http_client::HttpClient;
+use super::raw_tcp;
+
+const STREAM_NAME: &str = "consumer-offset-quota-stream";
+const TOPIC_NAME: &str = "consumer-offset-quota-topic";
+const PARTITION_ID: u32 = 0;
+const LIMIT: u32 = 4;
+
+#[iggy_harness(
+ cluster_nodes = 1,
+ server(partition.consumer_offsets_max = "4")
+)]
+async fn given_full_consumer_offset_table_when_creating_another_should_reject_without_new_file(
+ harness: &TestHarness,
+) {
+ let client = harness.tcp_root_client().await.expect("TCP root client");
+ let stream = Identifier::named(STREAM_NAME).expect("stream identifier");
+ let topic = Identifier::named(TOPIC_NAME).expect("topic identifier");
+ let stream_details = client
+ .create_stream(STREAM_NAME)
+ .await
+ .expect("create stream");
+ let topic_details = client
+ .create_topic(
+ &stream,
+ TOPIC_NAME,
+ &TopicCreateOptions {
+ partitions_count: Some(1),
+ message_expiry: Some(IggyExpiry::NeverExpire),
+ ..TopicCreateOptions::default()
+ },
+ )
+ .await
+ .expect("create topic");
+ let mut messages = vec![
+ IggyMessage::builder()
+ .payload("offset-quota".into())
+ .build()
+ .expect("build message"),
+ ];
+ client
+ .send_messages(
+ &stream,
+ &topic,
+ &Partitioning::partition_id(PARTITION_ID),
+ &mut messages,
+ )
+ .await
+ .expect("seed non-empty partition");
+
+ client
+ .create_user(
+ "offset-poll-only",
+ "password123",
+ UserStatus::Active,
+ Some(Permissions {
+ global: GlobalPermissions::default(),
+ streams: Some(BTreeMap::from([(
+ stream_details.id as usize,
+ StreamPermissions {
+ topics: Some(BTreeMap::from([(
+ topic_details.id as usize,
+ TopicPermissions {
+ poll_messages: true,
+ ..Default::default()
+ },
+ )])),
+ ..Default::default()
+ },
+ )])),
+ }),
+ )
+ .await
+ .expect("create a topic-scoped consumer");
+ let client = harness.tcp_new_client().await.expect("consumer TCP client");
+ client
+ .login_user("offset-poll-only", "password123")
+ .await
+ .expect("consumer login");
+
+ let first_consumer = Consumer::new(Identifier::numeric(1).unwrap());
+ let polled = client
+ .poll_messages(
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ &first_consumer,
+ &PollingStrategy::first(),
+ 1,
+ true,
+ )
+ .await
+ .expect("new auto-commit consumer fits");
+ assert_eq!(polled.messages.len(), 1);
+ let first_file = harness.server().data_path().join(format!(
+ "streams/{}/topics/{}/partitions/{PARTITION_ID}/offsets/consumers/1",
+ stream_details.id, topic_details.id
+ ));
+ let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10);
+ while !first_file.is_file() {
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "auto-commit never reached its file"
+ );
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ assert!(
+ client
+ .poll_messages(
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ &first_consumer,
+ &PollingStrategy::next(),
+ 1,
+ true
+ )
+ .await
+ .expect("next poll")
+ .messages
+ .is_empty()
+ );
+
+ for consumer_id in 1..=LIMIT {
+ client
+ .store_consumer_offset(
+ &Consumer::new(Identifier::numeric(consumer_id).expect("consumer identifier")),
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ 0,
+ )
+ .await
+ .expect("store offset within limit");
+ }
+
+ let rejected_consumer =
+ Consumer::new(Identifier::numeric(LIMIT + 1).expect("consumer identifier"));
+ let rejected = client
+ .store_consumer_offset(&rejected_consumer, &stream, &topic, Some(PARTITION_ID), 0)
+ .await;
+ assert!(
+ matches!(rejected, Err(IggyError::TooManyConsumerOffsets)),
+ "the first key above the limit must receive the typed capacity error"
+ );
+
+ client
+ .store_consumer_offset(
+ &Consumer::new(Identifier::numeric(1).expect("consumer identifier")),
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ 0,
+ )
+ .await
+ .expect("existing key remains writable at the limit");
+
+ let poll_rejected = client
+ .poll_messages(
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ &rejected_consumer,
+ &PollingStrategy::first(),
+ 1,
+ true,
+ )
+ .await;
+ assert!(
+ matches!(poll_rejected, Err(IggyError::TooManyConsumerOffsets)),
+ "auto-commit must not return data when its new key cannot be admitted"
+ );
+ client
+ .poll_messages(
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ &rejected_consumer,
+ &PollingStrategy::first(),
+ 1,
+ false,
+ )
+ .await
+ .expect("the same poll succeeds when auto-commit is disabled");
+
+ client
+ .delete_consumer_offset(
+ &Consumer::new(Identifier::numeric(1).expect("consumer identifier")),
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ )
+ .await
+ .expect("delete one accepted offset");
+ client
+ .store_consumer_offset(&rejected_consumer, &stream, &topic, Some(PARTITION_ID), 0)
+ .await
+ .expect("delete releases one durable slot");
+
+ let mut raw = raw_tcp::connect(harness).await;
+ let raw_client_id = 0xC0FF_EE03;
+ let session = raw_tcp::register_root(&mut raw, raw_client_id).await;
+ let unresolved_group = StoreConsumerOffsetRequest {
+ consumer: WireConsumer::consumer_group(WireIdentifier::Numeric(999)),
+ stream_id: WireIdentifier::Numeric(stream_details.id),
+ topic_id: WireIdentifier::Numeric(topic_details.id),
+ partition_id: Some(PARTITION_ID),
+ offset: 0,
+ ack: AckLevel::Quorum,
+ }
+ .to_bytes();
+ let header = raw_tcp::request_header(
+ Operation::StoreConsumerOffset,
+ raw_client_id,
+ session,
+ 1,
+ unresolved_group.len(),
+ );
+ let (reply, _) = raw_tcp::exchange(&mut raw, &header, &unresolved_group).await;
+ assert_eq!(
+ raw_tcp::reply_status(&reply),
+ IggyError::ConsumerGroupIdNotFound(Identifier::numeric(999).unwrap(), topic.clone())
+ .as_code()
+ );
+
+ let file_count = integration::harness::disk::consumer_offset_file_ids(
+ &harness.server().data_path(),
+ stream_details.id,
+ topic_details.id,
+ PARTITION_ID,
+ ConsumerKind::Consumer,
+ )
+ .expect("consumer offsets directory")
+ .len();
+ assert_eq!(file_count, LIMIT as usize);
+ let group_file_count = integration::harness::disk::consumer_offset_file_ids(
+ &harness.server().data_path(),
+ stream_details.id,
+ topic_details.id,
+ PARTITION_ID,
+ ConsumerKind::ConsumerGroup,
+ )
+ .map_or(0, |ids| ids.len());
+ assert_eq!(group_file_count, 0);
+
+ let named_group = StoreConsumerOffsetRequest {
+ consumer: WireConsumer::consumer_group(WireIdentifier::named("unknown-group").unwrap()),
+ stream_id: WireIdentifier::Numeric(stream_details.id),
+ topic_id: WireIdentifier::Numeric(topic_details.id),
+ partition_id: Some(PARTITION_ID),
+ offset: 0,
+ ack: AckLevel::Quorum,
+ }
+ .to_bytes();
+ let header = raw_tcp::request_header(
+ Operation::StoreConsumerOffset,
+ raw_client_id,
+ session,
+ 2,
+ named_group.len(),
+ );
+ let (reply, _) = raw_tcp::exchange(&mut raw, &header, &named_group).await;
+ assert_eq!(
+ raw_tcp::reply_status(&reply),
+ IggyError::ConsumerGroupNameNotFound("unknown-group".to_owned(), topic.clone()).as_code()
+ );
+
+ let unknown_stream = StoreConsumerOffsetRequest {
+ consumer: WireConsumer::consumer_group(WireIdentifier::Numeric(999)),
+ stream_id: WireIdentifier::Numeric(999_999),
+ topic_id: WireIdentifier::Numeric(topic_details.id),
+ partition_id: Some(PARTITION_ID),
+ offset: 0,
+ ack: AckLevel::Quorum,
+ }
+ .to_bytes();
+ let header = raw_tcp::request_header(
+ Operation::StoreConsumerOffset,
+ raw_client_id,
+ session,
+ 3,
+ unknown_stream.len(),
+ );
+ let (reply, _) = raw_tcp::exchange(&mut raw, &header, &unknown_stream).await;
+ assert_eq!(
+ raw_tcp::reply_status(&reply),
+ IggyError::ResourceNotFound(String::new()).as_code(),
+ "a missing stream is not reported as a missing group"
+ );
+
+ let http = HttpClient::login_root(harness).await;
+ let response = http
+ .client
+ .put(http.url(&format!(
+ "/streams/{STREAM_NAME}/topics/{TOPIC_NAME}/consumer-offsets"
+ )))
+ .bearer_auth(&http.token)
+ .json(&StoreConsumerOffset {
+ consumer: Consumer::new(Identifier::numeric(6).expect("consumer identifier")),
+ partition_id: Some(PARTITION_ID),
+ offset: 0,
+ })
+ .send()
+ .await
+ .expect("HTTP capacity request");
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ let body: serde_json::Value = response.json().await.expect("HTTP error body");
+ assert_eq!(body["id"], 3024);
+ assert_eq!(body["code"], "too_many_consumer_offsets");
+
+ let metrics = http
+ .client
+ .get(http.url("/metrics"))
+ .bearer_auth(&http.token)
+ .send()
+ .await
+ .expect("metrics response")
+ .text()
+ .await
+ .expect("metrics text");
+ let denied_for = |kind: &str| -> u64 {
+ let kind_label = format!("kind=\"{kind}\"");
+ let mut samples = 0;
+ let total = metrics
+ .lines()
+ .filter_map(|line| {
+ line.strip_prefix("partition_consumer_offsets_denied_total{")?
+ .split_once('}')
+ })
+ .filter(|(labels, _)| labels.split(',').any(|label| label == kind_label))
+ .map(|(_, value)| {
+ samples += 1;
+ value
+ .split_whitespace()
+ .last()
+ .expect("counter value")
+ .parse::<u64>()
+ .expect("numeric counter")
+ })
+ .sum();
+ assert!(
+ samples > 0,
+ "missing {kind} denial metric in response: {metrics}"
+ );
+ total
+ };
+ assert_eq!(
+ denied_for("consumer"),
+ 3,
+ "one explicit TCP, one poll, and one HTTP denial, all on the consumer kind"
+ );
+ assert_eq!(
+ denied_for("consumer_group"),
+ 0,
+ "no consumer group offset was denied in this test"
+ );
+}
+
+#[iggy_harness(
+ cluster_nodes = 1,
+ server(partition.consumer_offsets_max = "2")
+)]
+async fn given_full_consumer_offset_table_when_server_restarts_should_preserve_admission_state(
+ harness: &mut TestHarness,
+) {
+ let client = harness.tcp_root_client().await.expect("TCP root client");
+ let stream = Identifier::named("consumer-offset-restart-stream").expect("stream identifier");
+ let topic = Identifier::named("consumer-offset-restart-topic").expect("topic identifier");
+ let stream_details = client
+ .create_stream("consumer-offset-restart-stream")
+ .await
+ .expect("create stream");
+ let topic_details = client
+ .create_topic(
+ &stream,
+ "consumer-offset-restart-topic",
+ &TopicCreateOptions {
+ partitions_count: Some(1),
+ message_expiry: Some(IggyExpiry::NeverExpire),
+ ..TopicCreateOptions::default()
+ },
+ )
+ .await
+ .expect("create topic");
+ let mut messages = vec![
+ IggyMessage::builder()
+ .payload("offset-restart".into())
+ .build()
+ .expect("build message"),
+ ];
+ client
+ .send_messages(
+ &stream,
+ &topic,
+ &Partitioning::partition_id(PARTITION_ID),
+ &mut messages,
+ )
+ .await
+ .expect("seed non-empty partition");
+ for consumer_id in 1..=2 {
+ client
+ .store_consumer_offset(
+ &Consumer::new(Identifier::numeric(consumer_id).expect("consumer identifier")),
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ 0,
+ )
+ .await
+ .expect("store offset before restart");
+ }
+ drop(client);
+ harness.server_mut().stop().expect("stop server");
+ let offsets_dir = harness.server().data_path().join(format!(
+ "streams/{}/topics/{}/partitions/{PARTITION_ID}/offsets/consumers",
+ stream_details.id, topic_details.id
+ ));
+ fs::copy(offsets_dir.join("1"), offsets_dir.join("3"))
+ .expect("create first historical over-limit offset");
+ fs::copy(offsets_dir.join("1"), offsets_dir.join("4"))
+ .expect("create second historical over-limit offset");
+ harness.server_mut().start().expect("restart server");
+ let client = harness
+ .root_client()
+ .await
+ .expect("post-restart root client");
+
+ let rejected = client
+ .store_consumer_offset(
+ &Consumer::new(Identifier::numeric(5).expect("consumer identifier")),
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ 0,
+ )
+ .await;
+ assert!(matches!(rejected, Err(IggyError::TooManyConsumerOffsets)));
+ client
+ .store_consumer_offset(
+ &Consumer::new(Identifier::numeric(4).expect("consumer identifier")),
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ 0,
+ )
+ .await
+ .expect("recovered existing key remains writable");
+ client
+ .delete_consumer_offset(
+ &Consumer::new(Identifier::numeric(4).expect("consumer identifier")),
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ )
+ .await
+ .expect("delete recovered key");
+ client
+ .delete_consumer_offset(
+ &Consumer::new(Identifier::numeric(3).expect("consumer identifier")),
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ )
+ .await
+ .expect("delete second historical key");
+ client
+ .delete_consumer_offset(
+ &Consumer::new(Identifier::numeric(2).expect("consumer identifier")),
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ )
+ .await
+ .expect("delete below configured limit");
+ client
+ .store_consumer_offset(
+ &Consumer::new(Identifier::numeric(5).expect("consumer identifier")),
+ &stream,
+ &topic,
+ Some(PARTITION_ID),
+ 0,
+ )
+ .await
+ .expect("deleting below the limit releases a slot");
+}
diff --git a/core/integration/tests/server/mod.rs b/core/integration/tests/server/mod.rs
index e32f2c5ab..85a690696 100644
--- a/core/integration/tests/server/mod.rs
+++ b/core/integration/tests/server/mod.rs
@@ -78,6 +78,7 @@ mod partition_view_durability_vsr;
// 80-case race matrix with hardcoded HTTP variants (test_matrix bypasses
// the harness transport filter).
mod concurrent_addition;
+mod consumer_offset_quota_vsr;
mod general;
// The per-shard segment cleaner deletes expired / oversize segments from disk.
mod message_cleanup;
diff --git a/core/integration/tests/server/raw_tcp.rs b/core/integration/tests/server/raw_tcp.rs
index cfe5d8c69..8711a6059 100644
--- a/core/integration/tests/server/raw_tcp.rs
+++ b/core/integration/tests/server/raw_tcp.rs
@@ -21,6 +21,7 @@
//! can ride a bound session.
use std::mem::offset_of;
+use std::net::SocketAddr;
use std::time::Duration;
use iggy::prelude::*;
@@ -55,6 +56,10 @@ pub(crate) async fn connect(harness: &TestHarness) -> TcpStream {
.server()
.tcp_addr()
.expect("server must expose a TCP address");
+ connect_to(addr).await
+}
+
+pub(crate) async fn connect_to(addr: SocketAddr) -> TcpStream {
TcpStream::connect(addr).await.unwrap()
}
diff --git a/core/message_bus/src/lib.rs b/core/message_bus/src/lib.rs
index 74836bb8e..d8038b612 100644
--- a/core/message_bus/src/lib.rs
+++ b/core/message_bus/src/lib.rs
@@ -797,7 +797,7 @@ impl IggyMessageBus {
}
/// Construct a bus with explicit runtime tunables and a pre-allocated
- /// owner table. Server-ng bootstrap uses this so every shard's bus
+ /// owner table. Server bootstrap uses this so every shard's bus
/// shares the same atomic slots; tests use [`Self::with_tunables`]
/// which allocates a fresh table per bus.
///
diff --git a/core/metadata/src/impls/metadata.rs b/core/metadata/src/impls/metadata.rs
index 9fbd167cf..3c4d19f47 100644
--- a/core/metadata/src/impls/metadata.rs
+++ b/core/metadata/src/impls/metadata.rs
@@ -693,7 +693,7 @@ pub fn apply_committed_prepare<M>(
pub type CommitNotifier = std::rc::Rc<dyn Fn(Operation)>;
pub struct IggyMetadata<C, J, S, M, SB = PingPongSuperblock> {
- /// `Some` on shard 0, `None` on other shards. Server-ng bootstrap
+ /// `Some` on shard 0, `None` on other shards. Server bootstrap
/// holds the invariant: only shard 0 owns the metadata consensus
/// replica; every other shard reconstructs `mux_stm` from the
/// `MetadataHandoff::Waiter` factory bundle broadcast by shard 0
@@ -928,7 +928,7 @@ impl<C, J, S, M, SB> IggyMetadata<C, J, S, M, SB> {
}
/// Install (or replace) the post-commit notifier. Passing `None`
- /// removes any previous one. Server-ng bootstrap calls this on shard 0
+ /// removes any previous one. Server bootstrap calls this on shard 0
/// only; peer shards never commit metadata locally.
pub fn set_commit_notifier(&self, notifier: Option<CommitNotifier>) {
*self.commit_notifier.borrow_mut() = notifier;
@@ -937,7 +937,7 @@ impl<C, J, S, M, SB> IggyMetadata<C, J, S, M, SB> {
/// Seed the coordinator's last-checkpoint pairing at boot from the recovered
/// snapshot, so the first post-boot view-change superblock write records the real
/// `(checkpoint_op, checksum)` instead of `(0, 0)`. No-op without a coordinator
- /// (peer shards, the simulator). Server-ng bootstrap calls this on shard 0 after
+ /// (peer shards, the simulator). Server bootstrap calls this on shard 0 after
/// cross-checking the pairing.
pub fn seed_checkpoint_ref(&self, checkpoint_op: u64, checkpoint_checksum: u128) {
if let Some(coordinator) = &self.coordinator {
diff --git a/core/metadata/src/stm/user.rs b/core/metadata/src/stm/user.rs
index 1e79d7853..c78ea7507 100644
--- a/core/metadata/src/stm/user.rs
+++ b/core/metadata/src/stm/user.rs
@@ -642,14 +642,14 @@ impl StateHandler for UpdatePermissionsRequest {
/// The success reply here is deliberately empty: the raw token the caller needs
/// is the one thing this apply must never see.
///
-/// The primary mints the raw token and its hash at ingress (server-ng
+/// The primary mints the raw token and its hash at ingress (server
/// `pat::rewrite_pat_request_for_user`) and replicates only the hash. Minting
/// inside this apply would call `ring::rand` on every replica and diverge the
/// token index, and replicating the raw token would persist a live credential in
/// every WAL and snapshot. So the raw token leaves the primary by a side channel
/// (`maybe_rewrite_pat_request` returns it alongside the rewritten request) and
/// the home shard splices it into this op's reply as a typed
-/// `RawPersonalAccessTokenResponse` (server-ng `responses::build_raw_pat_reply`).
+/// `RawPersonalAccessTokenResponse` (server `responses::build_raw_pat_reply`).
///
/// One consequence rides on that: the secret exists only on the wire of the
/// original reply, so a replayed request cannot be served from the client-table
diff --git a/core/partitions/src/consumer_offset_capacity.rs b/core/partitions/src/consumer_offset_capacity.rs
new file mode 100644
index 000000000..aaaa93208
--- /dev/null
+++ b/core/partitions/src/consumer_offset_capacity.rs
@@ -0,0 +1,717 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.
+
+use iggy_common::ConsumerKind;
+use std::cell::{Cell, RefCell};
+use std::collections::hash_map::Entry;
+use std::collections::{HashMap, HashSet};
+use std::rc::Rc;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct DurableOffsetState {
+ pub(crate) committed_offset: u64,
+ pub(crate) persisted_high_water: u64,
+}
+
+#[derive(Debug, Default)]
+pub struct DurableConsumerOffsets {
+ consumers: RefCell<HashMap<u32, DurableOffsetState>>,
+ groups: RefCell<HashMap<u32, DurableOffsetState>>,
+ membership_epoch: Cell<u64>,
+}
+
+impl DurableConsumerOffsets {
+ pub(crate) fn get(&self, kind: ConsumerKind, id: u32) -> Option<DurableOffsetState> {
+ self.entries(kind).borrow().get(&id).copied()
+ }
+
+ pub(crate) fn contains(&self, kind: ConsumerKind, id: u32) -> bool {
+ self.entries(kind).borrow().contains_key(&id)
+ }
+
+ pub(crate) fn count(&self, kind: ConsumerKind) -> usize {
+ self.entries(kind).borrow().len()
+ }
+
+ pub(crate) fn covers(&self, kind: ConsumerKind, id: u32, offset: u64) -> bool {
+ self.get(kind, id).is_some_and(|state| {
+ state.committed_offset >= offset && state.persisted_high_water >= offset
+ })
+ }
+
+ pub(crate) fn record_explicit(
+ &self,
+ kind: ConsumerKind,
+ id: u32,
+ committed_offset: u64,
+ persisted_high_water: u64,
+ ) -> bool {
+ let created = self
+ .entries(kind)
+ .borrow_mut()
+ .insert(
+ id,
+ DurableOffsetState {
+ committed_offset,
+ persisted_high_water,
+ },
+ )
+ .is_none();
+ if created {
+ self.bump_membership_epoch();
+ }
+ created
+ }
+
+ pub(crate) fn record_auto_commit(
+ &self,
+ kind: ConsumerKind,
+ id: u32,
+ committed_offset: u64,
+ persisted_high_water: u64,
+ ) {
+ let mut entries = self.entries(kind).borrow_mut();
+ match entries.entry(id) {
+ Entry::Occupied(mut entry) => {
+ let state = entry.get_mut();
+ state.committed_offset = state.committed_offset.max(committed_offset);
+ state.persisted_high_water = state.persisted_high_water.max(persisted_high_water);
+ }
+ Entry::Vacant(entry) => {
+ entry.insert(DurableOffsetState {
+ committed_offset,
+ persisted_high_water,
+ });
+ drop(entries);
+ self.bump_membership_epoch();
+ }
+ }
+ }
+
+ pub(crate) fn remove(&self, kind: ConsumerKind, id: u32) -> bool {
+ let removed = self.entries(kind).borrow_mut().remove(&id).is_some();
+ if removed {
+ self.bump_membership_epoch();
+ }
+ removed
+ }
+
+ pub(crate) fn clear(&self) {
+ self.consumers.borrow_mut().clear();
+ self.groups.borrow_mut().clear();
+ self.bump_membership_epoch();
+ }
+
+ #[cfg(any(test, feature = "simulator"))]
+ pub(crate) fn committed_entries(&self, kind: ConsumerKind) -> Vec<(u32, u64)> {
+ self.entries(kind)
+ .borrow()
+ .iter()
+ .map(|(id, state)| (*id, state.committed_offset))
+ .collect()
+ }
+
+ pub(crate) fn with_entries<T>(
+ &self,
+ kind: ConsumerKind,
+ read: impl FnOnce(&HashMap<u32, DurableOffsetState>) -> T,
+ ) -> T {
+ read(&self.entries(kind).borrow())
+ }
+
+ const fn entries(&self, kind: ConsumerKind) -> &RefCell<HashMap<u32, DurableOffsetState>> {
+ match kind {
+ ConsumerKind::Consumer => &self.consumers,
+ ConsumerKind::ConsumerGroup => &self.groups,
+ }
+ }
+
+ fn bump_membership_epoch(&self) {
+ self.membership_epoch
+ .set(self.membership_epoch.get().wrapping_add(1));
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct ConsumerOffsetCapacityError {
+ pub kind: ConsumerKind,
+ pub occupied: usize,
+ pub limit: usize,
+ pub first_in_episode: bool,
+ pub uncertain: bool,
+}
+
+impl From<ConsumerOffsetCapacityError> for iggy_common::IggyError {
+ fn from(error: ConsumerOffsetCapacityError) -> Self {
+ if error.uncertain {
+ Self::TransientNotAccepted
+ } else {
+ Self::TooManyConsumerOffsets
+ }
+ }
+}
+
+#[derive(Debug)]
+pub struct ConsumerOffsetCapacity {
+ kind: ConsumerKind,
+ limit: Cell<usize>,
+ pending: RefCell<HashMap<u32, usize>>,
+ provisional: RefCell<HashMap<u32, Arc<ProvisionalToken>>>,
+ active_provisional_keys: Arc<AtomicUsize>,
+ stranded: RefCell<HashSet<u32>>,
+ uncertain: Cell<bool>,
+ durable_warned: Cell<bool>,
+ map_warned: Cell<bool>,
+ reclaim_epoch: Arc<AtomicU64>,
+ last_reclaim: Cell<Option<(u64, u64)>>,
+}
+
+impl ConsumerOffsetCapacity {
+ pub(crate) fn new(kind: ConsumerKind, limit: usize) -> Self {
+ Self {
+ kind,
+ limit: Cell::new(limit),
+ pending: RefCell::new(HashMap::new()),
+ provisional: RefCell::new(HashMap::new()),
+ active_provisional_keys: Arc::new(AtomicUsize::new(0)),
+ stranded: RefCell::new(HashSet::new()),
+ uncertain: Cell::new(false),
+ durable_warned: Cell::new(false),
+ map_warned: Cell::new(false),
+ reclaim_epoch: Arc::new(AtomicU64::new(0)),
+ last_reclaim: Cell::new(None),
+ }
+ }
+
+ pub(crate) fn set_limit(&self, limit: usize) {
+ self.limit.set(limit);
+ }
+
+ pub(crate) const fn limit(&self) -> usize {
+ self.limit.get()
+ }
+
+ pub(crate) fn try_reserve(
+ &self,
+ id: u32,
+ durable: &DurableConsumerOffsets,
+ ) -> Result<(), ConsumerOffsetCapacityError> {
+ self.check(id, durable)?;
+ *self.pending.borrow_mut().entry(id).or_default() += 1;
+ Ok(())
+ }
+
+ pub(crate) fn check(
+ &self,
+ id: u32,
+ durable: &DurableConsumerOffsets,
+ ) -> Result<(), ConsumerOffsetCapacityError> {
+ if self.holds(id, durable) || self.stranded.borrow().contains(&id) {
+ return Ok(());
+ }
+ let limit = self.limit.get();
+ let durable_count = durable.count(self.kind);
+ let fixed = durable_count
+ .saturating_add(self.pending.borrow().len())
+ .saturating_add(self.stranded.borrow().len());
+ let provisional_len = self.active_provisional_keys.load(Ordering::Relaxed);
+ let upper_bound = fixed.saturating_add(provisional_len);
+ if !self.uncertain.get() && upper_bound < limit {
+ self.durable_warned.set(false);
+ return Ok(());
+ }
+ // A full durable table cannot gain room by pruning provisional keys.
+ let occupied = if durable_count >= limit {
+ durable_count
+ } else {
+ self.occupied(durable)
+ };
+ if self.uncertain.get() || occupied >= limit {
+ return Err(ConsumerOffsetCapacityError {
+ kind: self.kind,
+ occupied,
+ limit,
+ first_in_episode: !self.durable_warned.replace(true),
+ uncertain: self.uncertain.get(),
+ });
+ }
+ self.durable_warned.set(false);
+ Ok(())
+ }
+
+ pub(crate) fn reserve_provisional(
+ self: &Rc<Self>,
+ id: u32,
+ durable: &Rc<DurableConsumerOffsets>,
+ ) -> Result<AutoCommitReservation, ConsumerOffsetCapacityError> {
+ self.check(id, durable)?;
+ let mut provisional = self.provisional.borrow_mut();
+ if provisional.len() >= self.limit.get() && !provisional.contains_key(&id) {
+ provisional.retain(|_, token| token.active.load(Ordering::Relaxed) > 0);
+ }
+ let token = Arc::clone(provisional.entry(id).or_insert_with(|| {
+ Arc::new(ProvisionalToken {
+ reclaim_epoch: Arc::clone(&self.reclaim_epoch),
+ active_keys: Arc::clone(&self.active_provisional_keys),
+ active: AtomicUsize::new(0),
+ })
+ }));
+ if token.active.fetch_add(1, Ordering::Relaxed) == 0 {
+ token.active_keys.fetch_add(1, Ordering::Relaxed);
+ }
+ Ok(AutoCommitReservation {
+ token,
+ kind: self.kind,
+ consumer_id: id,
+ })
+ }
+
+ pub(crate) fn owns(&self, reservation: &AutoCommitReservation) -> bool {
+ reservation.kind == self.kind
+ && self
+ .provisional
+ .borrow()
+ .get(&reservation.consumer_id)
+ .is_some_and(|token| Arc::ptr_eq(token, &reservation.token))
+ }
+
+ pub(crate) fn holds(&self, id: u32, durable: &DurableConsumerOffsets) -> bool {
+ durable.contains(self.kind, id)
+ || self.pending.borrow().contains_key(&id)
+ || self
+ .provisional
+ .borrow()
+ .get(&id)
+ .is_some_and(|token| token.active.load(Ordering::Relaxed) > 0)
+ }
+
+ /// Assigns the pending count outright while [`Self::release_reservation`]
+ /// decrements it. Both take `&self` and neither locks: they are serialized
+ /// by their call sites, which all run under the partition's `&mut self` on
+ /// its own shard thread.
+ pub(crate) fn set_pending_count(&self, id: u32, count: usize) {
+ if count == 0 {
+ if self.pending.borrow_mut().remove(&id).is_some() {
+ self.note_local_key_change();
+ }
+ } else {
+ self.pending.borrow_mut().insert(id, count);
+ }
+ }
+
+ /// See [`Self::set_pending_count`] for the serialization contract.
+ pub(crate) fn release_reservation(&self, id: u32) {
+ let mut pending = self.pending.borrow_mut();
+ let Some(count) = pending.get_mut(&id) else {
+ return;
+ };
+ if *count == 1 {
+ pending.remove(&id);
+ self.note_local_key_change();
+ } else {
+ *count -= 1;
+ }
+ }
+
+ pub(crate) const fn is_uncertain(&self) -> bool {
+ self.uncertain.get()
+ }
+
+ pub(crate) fn rebuild(
+ &self,
+ durable: &DurableConsumerOffsets,
+ pending_ids: impl IntoIterator<Item = u32>,
+ ) {
+ let mut pending = self.pending.borrow_mut();
+ pending.clear();
+ for id in pending_ids {
+ *pending.entry(id).or_default() += 1;
+ }
+ drop(pending);
+ self.note_local_key_change();
+ self.uncertain.set(false);
+ self.rearm_if_below_limit(durable);
+ }
+
+ pub(crate) fn mark_uncertain(&self) {
+ self.pending.borrow_mut().clear();
+ self.uncertain.set(true);
+ self.note_local_key_change();
+ }
+
+ pub(crate) fn record_stranded(&self, id: u32) {
+ self.stranded.borrow_mut().insert(id);
+ }
+
+ pub(crate) fn clear_stranded(&self, id: u32) {
+ self.stranded.borrow_mut().remove(&id);
+ }
+
+ pub(crate) fn is_stranded(&self, id: u32) -> bool {
+ self.stranded.borrow().contains(&id)
+ }
+
+ /// Keys whose file could not be loaded or unlinked. Cleared only by a
+ /// later store or delete of the same key, never by `rebuild` or
+ /// `mark_uncertain`, so a permanently unwritable file keeps this above
+ /// zero. Exported as a gauge so that refusal has a signal.
+ pub(crate) fn stranded_count(&self) -> usize {
+ self.stranded.borrow().len()
+ }
+
+ pub(crate) fn rearm_if_below_limit(&self, durable: &DurableConsumerOffsets) {
+ if !self.durable_warned.get()
+ || self.uncertain.get()
+ || durable.count(self.kind) >= self.limit.get()
+ {
+ return;
+ }
+ if self.occupied(durable) < self.limit.get() {
+ self.durable_warned.set(false);
+ }
+ }
+
+ pub(crate) fn admit_local_map_key(
+ &self,
+ map_len: usize,
+ durable_full: bool,
+ ) -> Result<(), ConsumerOffsetCapacityError> {
+ let limit = self.limit.get();
+ if map_len < limit {
+ self.map_warned.set(false);
+ return Ok(());
+ }
+ Err(ConsumerOffsetCapacityError {
+ kind: self.kind,
+ occupied: map_len,
+ limit,
+ first_in_episode: !self.map_warned.replace(true),
+ uncertain: !durable_full,
+ })
+ }
+
+ pub(crate) fn note_local_key_change(&self) {
+ self.reclaim_epoch.fetch_add(1, Ordering::Relaxed);
+ }
+
+ pub(crate) fn forget_inactive_provisional(&self, id: u32) {
+ let mut provisional = self.provisional.borrow_mut();
+ if provisional
+ .get(&id)
+ .is_some_and(|token| token.active.load(Ordering::Relaxed) == 0)
+ {
+ provisional.remove(&id);
+ }
+ }
+
+ pub(crate) fn should_reclaim(&self, durable: &DurableConsumerOffsets) -> bool {
+ if self.uncertain.get() {
+ return false;
+ }
+ let epoch = (
+ self.reclaim_epoch.load(Ordering::Relaxed),
+ durable.membership_epoch.get(),
+ );
+ self.last_reclaim.replace(Some(epoch)) != Some(epoch)
+ }
+
+ /// Keys this kind holds: the durable set plus every pending, active
+ /// provisional or stranded key the durable set does not already count.
+ pub(crate) fn occupied(&self, durable: &DurableConsumerOffsets) -> usize {
+ let pending = self.pending.borrow();
+ let provisional = self.provisional.borrow();
+ let stranded = self.stranded.borrow();
+ let mut local: HashSet<u32> = pending.keys().copied().collect();
+ local.extend(
+ provisional
+ .iter()
+ .filter(|(_, token)| token.active.load(Ordering::Relaxed) > 0)
+ .map(|(id, _)| *id),
+ );
+ local.extend(stranded.iter().copied());
+ durable.count(self.kind)
+ + local
+ .into_iter()
+ .filter(|id| !durable.contains(self.kind, *id))
+ .count()
+ }
+}
+
+/// Keeps a provisional key occupied until the pump admits or drops its request.
+#[derive(Debug)]
+pub struct AutoCommitReservation {
+ token: Arc<ProvisionalToken>,
+ pub(crate) kind: ConsumerKind,
+ pub(crate) consumer_id: u32,
+}
+
+#[derive(Debug)]
+struct ProvisionalToken {
+ reclaim_epoch: Arc<AtomicU64>,
+ active_keys: Arc<AtomicUsize>,
+ active: AtomicUsize,
+}
+
+impl Drop for AutoCommitReservation {
+ fn drop(&mut self) {
+ if self.token.active.fetch_sub(1, Ordering::Relaxed) == 1 {
+ self.token.active_keys.fetch_sub(1, Ordering::Relaxed);
+ self.token.reclaim_epoch.fetch_add(1, Ordering::Relaxed);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn given_cached_inactive_tokens_when_admitting_should_count_only_active_keys() {
+ let durable = Rc::new(DurableConsumerOffsets::default());
+ let capacity = Rc::new(ConsumerOffsetCapacity::new(ConsumerKind::Consumer, 2));
+ let first = capacity.reserve_provisional(1, &durable).unwrap();
+ let repeated = capacity.reserve_provisional(1, &durable).unwrap();
+ assert_eq!(capacity.active_provisional_keys.load(Ordering::Relaxed), 1);
+ drop(first);
+ assert_eq!(capacity.active_provisional_keys.load(Ordering::Relaxed), 1);
+ drop(repeated);
+ assert_eq!(capacity.active_provisional_keys.load(Ordering::Relaxed), 0);
+ assert_eq!(capacity.provisional.borrow().len(), 1);
+ capacity.check(2, &durable).unwrap();
+ let second = capacity.reserve_provisional(2, &durable).unwrap();
+ assert_eq!(capacity.active_provisional_keys.load(Ordering::Relaxed), 1);
+ drop(second);
+ capacity.check(3, &durable).unwrap();
+ assert_eq!(capacity.active_provisional_keys.load(Ordering::Relaxed), 0);
+ }
+
+ #[test]
+ fn given_low_occupancy_when_accounting_is_uncertain_should_reject_new_keys() {
+ let durable = DurableConsumerOffsets::default();
+ let capacity = ConsumerOffsetCapacity::new(ConsumerKind::Consumer, 100);
+ capacity.try_reserve(1, &durable).unwrap();
+ capacity.mark_uncertain();
+ assert!(capacity.check(2, &durable).unwrap_err().uncertain);
+ capacity.rebuild(&durable, [1]);
+ capacity.check(2, &durable).unwrap();
+ }
+
+ #[test]
+ fn given_overlapping_accounting_sets_when_sum_exceeds_limit_should_use_exact_occupancy() {
+ let durable = DurableConsumerOffsets::default();
+ durable.record_explicit(ConsumerKind::Consumer, 1, 0, 0);
+ let capacity = ConsumerOffsetCapacity::new(ConsumerKind::Consumer, 2);
+ capacity.try_reserve(1, &durable).unwrap();
+ capacity.record_stranded(1);
+ capacity.check(2, &durable).unwrap();
+ }
+
+ #[test]
+ fn given_unchanged_protection_when_reclaim_repeats_should_skip_until_guard_drops() {
+ let durable = Rc::new(DurableConsumerOffsets::default());
+ let capacity = Rc::new(ConsumerOffsetCapacity::new(ConsumerKind::Consumer, 2));
+ let held = capacity.reserve_provisional(7, &durable).unwrap();
+ assert!(capacity.should_reclaim(&durable));
+ for _ in 0..100 {
+ assert!(!capacity.should_reclaim(&durable));
+ }
+ drop(held);
+ assert!(capacity.should_reclaim(&durable));
+ assert!(!capacity.should_reclaim(&durable));
+ capacity.note_local_key_change();
+ assert!(capacity.should_reclaim(&durable));
+ }
+
+ #[test]
+ fn given_repeated_reservation_for_same_key_should_reuse_token_allocation() {
+ let durable = Rc::new(DurableConsumerOffsets::default());
+ let capacity = Rc::new(ConsumerOffsetCapacity::new(ConsumerKind::Consumer, 2));
+ let first = capacity.reserve_provisional(7, &durable).unwrap();
+ let token = Arc::clone(&first.token);
+ drop(first);
+ drop(capacity.reserve_provisional(8, &durable).unwrap());
+ assert_eq!(capacity.provisional.borrow().len(), 2);
+ let second = capacity.reserve_provisional(7, &durable).unwrap();
+ assert!(Arc::ptr_eq(&token, &second.token));
+ }
+
+ #[test]
+ fn given_inactive_token_cache_at_limit_when_new_key_arrives_should_prune_it() {
+ let durable = Rc::new(DurableConsumerOffsets::default());
+ let capacity = Rc::new(ConsumerOffsetCapacity::new(ConsumerKind::Consumer, 2));
+ drop(capacity.reserve_provisional(7, &durable).unwrap());
+ drop(capacity.reserve_provisional(8, &durable).unwrap());
+ assert_eq!(capacity.provisional.borrow().len(), 2);
+ let _third = capacity.reserve_provisional(9, &durable).unwrap();
+ assert_eq!(capacity.provisional.borrow().len(), 1);
+ assert!(capacity.provisional.borrow().contains_key(&9));
+ }
+
+ #[test]
+ fn given_local_map_pressure_when_durable_has_room_should_return_transient_error() {
+ let capacity = ConsumerOffsetCapacity::new(ConsumerKind::Consumer, 1);
+ assert!(matches!(
+ iggy_common::IggyError::from(capacity.admit_local_map_key(1, false).unwrap_err()),
+ iggy_common::IggyError::TransientNotAccepted
+ ));
+ assert!(matches!(
+ iggy_common::IggyError::from(capacity.admit_local_map_key(1, true).unwrap_err()),
+ iggy_common::IggyError::TooManyConsumerOffsets
+ ));
+ }
+
+ #[test]
+ fn given_provisional_and_journal_reservations_when_rebuilt_and_canceled_should_preserve_journal_slot()
+ {
+ let durable = Rc::new(DurableConsumerOffsets::default());
+ let capacity = Rc::new(ConsumerOffsetCapacity::new(ConsumerKind::Consumer, 1));
+ let provisional = capacity
+ .reserve_provisional(7, &durable)
+ .expect("reserve poll");
+ capacity.rebuild(&durable, [7]);
+ drop(provisional);
+ assert!(capacity.check(8, &durable).is_err());
+ capacity.set_pending_count(7, 0);
+ assert!(capacity.check(8, &durable).is_ok());
+ }
+
+ #[test]
+ fn given_dropped_submit_when_guard_leaves_scope_should_release_only_its_key() {
+ let durable = Rc::new(DurableConsumerOffsets::default());
+ let capacity = Rc::new(ConsumerOffsetCapacity::new(ConsumerKind::Consumer, 2));
+ let first = capacity
+ .reserve_provisional(7, &durable)
+ .expect("reserve first poll");
+ let second = capacity
+ .reserve_provisional(8, &durable)
+ .expect("reserve second poll");
+ assert!(capacity.check(9, &durable).is_err());
+ drop(first);
+ assert!(capacity.check(9, &durable).is_ok());
+ assert_eq!(capacity.occupied(&durable), 1);
+ drop(second);
+ assert_eq!(capacity.occupied(&durable), 0);
+ }
+
+ #[test]
+ fn given_full_durable_set_when_reserving_new_key_should_reject() {
+ let durable = DurableConsumerOffsets::default();
+ durable.record_explicit(ConsumerKind::Consumer, 1, 0, 0);
+ let capacity = ConsumerOffsetCapacity::new(ConsumerKind::Consumer, 1);
+ let error = capacity
+ .try_reserve(2, &durable)
+ .expect_err("new key must be rejected");
+ assert_eq!(error.occupied, 1);
+ assert_eq!(error.limit, 1);
+ assert!(error.first_in_episode);
+ }
+
+ #[test]
+ fn given_same_pending_key_when_reserved_twice_should_consume_one_slot() {
+ let durable = DurableConsumerOffsets::default();
+ let capacity = ConsumerOffsetCapacity::new(ConsumerKind::Consumer, 1);
+ assert_eq!(capacity.try_reserve(7, &durable), Ok(()));
+ assert_eq!(capacity.try_reserve(7, &durable), Ok(()));
+ assert!(capacity.try_reserve(8, &durable).is_err());
+ capacity.release_reservation(7);
+ assert!(
+ capacity.try_reserve(8, &durable).is_err(),
+ "one of two reservations still owns the slot"
+ );
+ capacity.release_reservation(7);
+ assert!(
+ capacity.try_reserve(8, &durable).is_ok(),
+ "the slot is released after the last reservation"
+ );
+ }
+
+ #[test]
+ fn given_stranded_file_when_reserving_same_and_different_ids_should_only_reuse_exact_path() {
+ let durable = DurableConsumerOffsets::default();
+ let capacity = ConsumerOffsetCapacity::new(ConsumerKind::Consumer, 1);
+ capacity.record_stranded(7);
+ assert!(capacity.try_reserve(8, &durable).is_err());
+ assert!(
+ capacity.try_reserve(7, &durable).is_ok(),
+ "rewriting the same path does not allocate another file"
+ );
+ }
+
+ #[test]
+ fn given_uncertain_rebuild_when_reserving_new_key_should_fail_closed() {
+ let durable = DurableConsumerOffsets::default();
+ let capacity = ConsumerOffsetCapacity::new(ConsumerKind::Consumer, 4);
+ capacity.mark_uncertain();
+ let error = capacity
+ .try_reserve(7, &durable)
+ .expect_err("unknown pending state must block new keys");
+ assert_eq!(error.occupied, 0);
+ assert!(error.uncertain);
+ assert!(error.first_in_episode);
+ assert!(
+ !capacity
+ .try_reserve(8, &durable)
+ .expect_err("the same uncertain episode stays closed")
+ .first_in_episode
+ );
+ }
+
+ #[test]
+ fn given_capacity_episode_when_occupancy_drops_should_rearm_first_warning() {
+ let durable = DurableConsumerOffsets::default();
+ durable.record_explicit(ConsumerKind::Consumer, 1, 0, 0);
+ let capacity = ConsumerOffsetCapacity::new(ConsumerKind::Consumer, 1);
+ assert!(
+ capacity
+ .try_reserve(2, &durable)
+ .expect_err("full table")
+ .first_in_episode
+ );
+ assert!(
+ !capacity
+ .try_reserve(2, &durable)
+ .expect_err("same full table")
+ .first_in_episode
+ );
+ durable.remove(ConsumerKind::Consumer, 1);
+ capacity.rearm_if_below_limit(&durable);
+ durable.record_explicit(ConsumerKind::Consumer, 3, 0, 0);
+ assert!(
+ capacity
+ .try_reserve(4, &durable)
+ .expect_err("new full episode")
+ .first_in_episode
+ );
+ }
+
+ #[test]
+ fn given_persisted_state_when_checking_coverage_should_preserve_membership() {
+ let durable = DurableConsumerOffsets::default();
+ durable.record_explicit(ConsumerKind::Consumer, 3, 11, 11);
+ assert!(durable.contains(ConsumerKind::Consumer, 3));
+ assert_eq!(durable.count(ConsumerKind::Consumer), 1);
+ assert_eq!(
+ durable.get(ConsumerKind::Consumer, 3),
+ Some(DurableOffsetState {
+ committed_offset: 11,
+ persisted_high_water: 11,
+ })
+ );
+ }
+}
diff --git a/core/partitions/src/iggy_partition.rs b/core/partitions/src/iggy_partition.rs
index 356a10a7e..f25616ad3 100644
--- a/core/partitions/src/iggy_partition.rs
+++ b/core/partitions/src/iggy_partition.rs
@@ -15,6 +15,9 @@
// specific language governing permissions and limitations
// under the License.
+use crate::consumer_offset_capacity::{
+ ConsumerOffsetCapacity, ConsumerOffsetCapacityError, DurableConsumerOffsets,
+};
use crate::iggy_index_writer::IggyIndexWriter;
use crate::journal::{MessageLookup, PartitionJournal, PartitionJournalMemStorage};
use crate::log::JournalInfo;
@@ -51,7 +54,7 @@ use iggy_binary_protocol::responses::messages::{
SendMessagesConfirmationResponse, SendMessagesResponse,
};
use iggy_binary_protocol::{
- AckLevel, GenericHeader, Operation, PrepareHeader, WireDecode, WireEncode, WireIdentifier,
+ AckLevel, Operation, PrepareHeader, WireDecode, WireEncode, WireIdentifier,
};
use iggy_binary_protocol::{PrepareOkHeader, ReplyHeader, RoutedRequestHeader};
use iggy_common::{
@@ -67,8 +70,8 @@ use journal::superblock::{
};
use message_bus::{IggyMessageBus, MessageBus, is_auto_commit_client};
use server_common::{
- MESSAGE_ALIGN, Message, SegmentStorage,
- iobuf::{Frozen, Owned},
+ Message, SegmentStorage,
+ iobuf::Frozen,
send_messages::{
BatchHeader, ChecksumMode, convert_request_message, decode_prepare_slice,
decode_prepare_slice_trusted, stamp_prepare_for_persistence,
@@ -205,20 +208,27 @@ where
/// server down without the partition moving again in the meantime.
fatal: Option<FatalCommit>,
pub(crate) pending_consumer_offset_commits: HashMap<u64, PendingConsumerOffsetCommit>,
- /// Committed-only mirror of each consumer's persisted offset file: the
- /// last value this replica durably wrote per (kind, consumer id). Fed
- /// exclusively by the file-writing paths (replicated commit-apply, the
- /// primary-local `NoAck` store, purge/delete/reclaim) and never by the
- /// eager poll-path in-memory apply, so both readers see committed state
- /// only: the auto-commit persist gate (skip or blind-write, no per-commit
- /// file read) and the submit-side coalesce gate
- /// ([`Self::is_auto_commit_offset_covered`]). A cold key (first touch
- /// after boot) folds against the file once via `persist_offset_max`, so
- /// the tracker rebuilds from disk lazily and deterministically.
- /// `RefCell`: mutated from `&self` paths on the single shard thread;
- /// borrows never cross an await.
- pub(crate) persisted_offsets: RefCell<HashMap<(ConsumerKind, u32), u64>>,
+ pub(crate) queued_auto_commit_reservations:
+ RefCell<HashMap<(ConsumerKind, u32), Vec<crate::AutoCommitReservation>>>,
+ /// Committed consumer-offset membership and values. This is deliberately
+ /// separate from the eager poll maps because follower-local and uncommitted
+ /// auto-commit progress must never consume a durable slot or enter a state
+ /// transfer artifact.
+ pub(crate) durable_consumer_offsets: Rc<DurableConsumerOffsets>,
+ pub(crate) consumer_offset_capacity: Rc<ConsumerOffsetCapacity>,
+ pub(crate) consumer_group_offset_capacity: Rc<ConsumerOffsetCapacity>,
pub(crate) observed_view: u32,
+ offset_reservations_need_resync: Cell<bool>,
+ offset_reservations_scan_state: Option<(u64, u64, u64, Option<u64>)>,
+ consumer_group_offsets_reconcile_epoch: Rc<Cell<u64>>,
+ consumer_offset_dirs_dirty: [Cell<bool>; 2],
+ /// Latest operation of each kind in the current commit walk. Even a covered
+ /// store depends on an earlier unsynced directory entry of its kind.
+ consumer_offset_dirs_touched: [Cell<Option<(u64, Operation)>>; 2],
+ #[cfg(test)]
+ consumer_offset_dir_sync_fault: Cell<Option<usize>>,
+ #[cfg(test)]
+ offset_dir_sync_count: Cell<usize>,
/// Highest `PurgeTopic` generation this replica has locally applied (reset
/// the partition to empty). The reconciler compares the committed metadata
/// generation against this and resets only when it advances, so a redundant
@@ -556,8 +566,26 @@ where
installed_frontier: None,
fatal: None,
pending_consumer_offset_commits: HashMap::new(),
- persisted_offsets: RefCell::new(HashMap::new()),
+ queued_auto_commit_reservations: RefCell::new(HashMap::new()),
+ durable_consumer_offsets: Rc::new(DurableConsumerOffsets::default()),
+ consumer_offset_capacity: Rc::new(ConsumerOffsetCapacity::new(
+ ConsumerKind::Consumer,
+ crate::DEFAULT_CONSUMER_OFFSETS_MAX,
+ )),
+ consumer_group_offset_capacity: Rc::new(ConsumerOffsetCapacity::new(
+ ConsumerKind::ConsumerGroup,
+ crate::DEFAULT_CONSUMER_OFFSETS_MAX,
+ )),
observed_view,
+ offset_reservations_need_resync: Cell::new(false),
+ offset_reservations_scan_state: None,
+ consumer_group_offsets_reconcile_epoch: Rc::new(Cell::new(0)),
+ consumer_offset_dirs_dirty: [Cell::new(false), Cell::new(false)],
+ consumer_offset_dirs_touched: [Cell::new(None), Cell::new(None)],
+ #[cfg(test)]
+ consumer_offset_dir_sync_fault: Cell::new(None),
+ #[cfg(test)]
+ offset_dir_sync_count: Cell::new(0),
applied_purge_generation: 0,
created_revision: 0,
purge_floor_op: 0,
@@ -653,6 +681,12 @@ where
self.dedup.set_capacity(clients_max);
}
+ /// Set the per-kind durable consumer-offset limit for this partition.
+ pub fn set_consumer_offsets_max(&mut self, offsets_max: usize) {
+ self.consumer_offset_capacity.set_limit(offsets_max);
+ self.consumer_group_offset_capacity.set_limit(offsets_max);
+ }
+
#[must_use]
pub fn with_in_memory_storage(
stats: Arc<PartitionStats>,
@@ -1090,8 +1124,34 @@ where
durable_offset,
write_offset,
offset_space_used,
+ consumer_offsets,
+ consumer_group_offsets,
} = state;
self.log = log;
+ for (consumer_id, offset) in consumer_offsets {
+ self.consumer_offsets.pin().insert(
+ consumer_id as usize,
+ ConsumerOffset::new(ConsumerKind::Consumer, consumer_id, offset, String::new()),
+ );
+ self.durable_consumer_offsets.record_explicit(
+ ConsumerKind::Consumer,
+ consumer_id,
+ offset,
+ offset,
+ );
+ }
+ for (group_id, offset) in consumer_group_offsets {
+ self.consumer_group_offsets.pin().insert(
+ ConsumerGroupId(group_id as usize),
+ ConsumerOffset::new(ConsumerKind::ConsumerGroup, group_id, offset, String::new()),
+ );
+ self.durable_consumer_offsets.record_explicit(
+ ConsumerKind::ConsumerGroup,
+ group_id,
+ offset,
+ offset,
+ );
+ }
// Empty carry-over: the previous incarnation never took a write, so there
// is no offset space to restore and claiming one would make the next
// prepare mint from a base no peer agrees on.
@@ -1119,6 +1179,12 @@ where
self.recovered_durable_offset = Some(durable);
}
+ #[cfg(any(test, feature = "simulator"))]
+ #[must_use]
+ pub fn retained_consumer_offsets(&self, kind: ConsumerKind) -> Vec<(u32, u64)> {
+ self.durable_consumer_offsets.committed_entries(kind)
+ }
+
/// The in-memory half of [`Self::reanchor_to_offset_frontier`], for a
/// simulator partition rebuilt over a restored offset counter.
///
@@ -1943,6 +2009,52 @@ where
self.consumer_offset_enforce_fsync = consumer_offset_enforce_fsync;
}
+ /// Seed committed membership from one recovered offset file. The logical
+ /// value may be clamped to the recovered message frontier while the file
+ /// high-water retains the value read from disk.
+ pub fn seed_recovered_consumer_offset(
+ &self,
+ kind: ConsumerKind,
+ consumer_id: u32,
+ committed_offset: u64,
+ persisted_high_water: u64,
+ ) {
+ self.durable_consumer_offsets.record_explicit(
+ kind,
+ consumer_id,
+ committed_offset,
+ persisted_high_water,
+ );
+ }
+
+ pub fn seed_stranded_consumer_offset(&self, kind: ConsumerKind, consumer_id: u32) -> bool {
+ if !self.durable_consumer_offsets.contains(kind, consumer_id) {
+ self.consumer_offset_capacity_for(kind)
+ .record_stranded(consumer_id);
+ return true;
+ }
+ false
+ }
+
+ #[must_use]
+ pub fn durable_consumer_offset_count(&self, kind: ConsumerKind) -> usize {
+ self.durable_consumer_offsets.count(kind)
+ }
+
+ #[must_use]
+ pub fn occupied_consumer_offset_count(&self, kind: ConsumerKind) -> usize {
+ self.consumer_offset_capacity_for(kind)
+ .occupied(&self.durable_consumer_offsets)
+ }
+
+ #[must_use]
+ pub fn consumer_offset_map_count(&self, kind: ConsumerKind) -> usize {
+ match kind {
+ ConsumerKind::Consumer => self.consumer_offsets.len(),
+ ConsumerKind::ConsumerGroup => self.consumer_group_offsets.len(),
+ }
+ }
+
/// Stage a consumer offset upsert for the replicated op. The prepare
/// must already have been appended to `self.log.journal` by the caller
/// so `VsrAction::RetransmitPrepares` can recover it during a view
@@ -1963,7 +2075,11 @@ where
} else {
PendingConsumerOffsetCommit::upsert(kind, consumer_id, offset)
};
- self.pending_consumer_offset_commits.insert(op, pending);
+ let replaced = self.pending_consumer_offset_commits.insert(op, pending);
+ if let Some(replaced) = replaced {
+ self.refresh_consumer_offset_reservation(replaced.kind, replaced.consumer_id);
+ }
+ self.refresh_consumer_offset_reservation(kind, consumer_id);
}
/// Stage a consumer offset delete for the replicated op. See
@@ -1982,7 +2098,9 @@ where
consumer_id: u32,
) {
let pending = PendingConsumerOffsetCommit::delete(kind, consumer_id);
- self.pending_consumer_offset_commits.insert(op, pending);
+ if let Some(replaced) = self.pending_consumer_offset_commits.insert(op, pending) {
+ self.refresh_consumer_offset_reservation(replaced.kind, replaced.consumer_id);
+ }
}
pub(crate) async fn apply_staged_consumer_offset_commit(
@@ -2008,8 +2126,16 @@ where
// durably stored; the in-memory update is idempotent on replay
// because we look up by (kind, id).
self.persist_consumer_offset_commit(pending).await?;
- self.apply_consumer_offset_commit(pending)?;
+ let operation = match pending.mutation {
+ PendingConsumerOffsetMutation::Upsert(_) => Operation::StoreConsumerOffset,
+ PendingConsumerOffsetMutation::Delete => Operation::DeleteConsumerOffset,
+ };
+ // A covered store also depends on an earlier dirty directory entry.
+ self.consumer_offset_dirs_touched[crate::state_transfer::consumer_kind_index(pending.kind)]
+ .set(Some((op, operation)));
+ self.apply_consumer_offset_commit(pending);
self.pending_consumer_offset_commits.remove(&op);
+ self.refresh_consumer_offset_reservation(pending.kind, pending.consumer_id);
Ok(())
}
@@ -2017,15 +2143,13 @@ where
&self,
pending: PendingConsumerOffsetCommit,
) -> Result<(), IggyError> {
- let Some(path) = self.persisted_offset_path(pending.kind, pending.consumer_id) else {
- return Ok(());
- };
- let key = (pending.kind, pending.consumer_id);
+ let path = self.persisted_offset_path(pending.kind, pending.consumer_id);
+ let capacity = self.consumer_offset_capacity_for(pending.kind);
match pending.mutation {
// A server auto-commit persists monotonically: its op offset can
// trail the durably-recorded value (disk-tier polls replicate in
// IO-completion order), so a plain overwrite would rewind the file
- // and re-deliver on restart. The `persisted_offsets` tracker keeps
+ // and re-deliver on restart. The durable offset tracker keeps
// the fold off the file: a covered offset skips the write, an
// advancing one blind-writes, and only a cold key (first commit
// after boot) reads the file once. Explicit client stores
@@ -2033,58 +2157,123 @@ where
// in-memory `upsert_offset_max` vs `upsert_offset` split in the
// commit-apply.
PendingConsumerOffsetMutation::Upsert(offset) if pending.auto_commit => {
- let tracked = self.persisted_offsets.borrow().get(&key).copied();
- let persisted = match tracked {
- Some(high_water) if offset <= high_water => return Ok(()),
- Some(_) => {
- persist_offset(&path, offset, self.consumer_offset_enforce_fsync).await?;
- offset
+ let tracked = self
+ .durable_consumer_offsets
+ .get(pending.kind, pending.consumer_id);
+ let (persisted_high_water, written) = match (path.as_deref(), tracked) {
+ (None, _) => (offset, false),
+ (Some(_), Some(state)) if offset <= state.persisted_high_water => {
+ (state.persisted_high_water, false)
+ }
+ (Some(path), Some(state)) => {
+ let value = state.committed_offset.max(offset);
+ persist_offset(path, value, self.consumer_offset_enforce_fsync).await?;
+ (value, true)
}
- None => {
- persist_offset_max(&path, offset, self.consumer_offset_enforce_fsync)
- .await?
+ (Some(path), None) => {
+ let persisted =
+ persist_offset_max(path, offset, self.consumer_offset_enforce_fsync)
+ .await?;
+ (persisted.offset, persisted.written)
}
};
- self.persisted_offsets.borrow_mut().insert(key, persisted);
+ self.durable_consumer_offsets.record_auto_commit(
+ pending.kind,
+ pending.consumer_id,
+ if tracked.is_none() {
+ persisted_high_water
+ } else {
+ offset
+ },
+ persisted_high_water,
+ );
+ if written && self.consumer_offset_enforce_fsync {
+ self.mark_consumer_offset_dir_dirty(pending.kind);
+ }
+ capacity.clear_stranded(pending.consumer_id);
+ if pending.kind == ConsumerKind::ConsumerGroup && tracked.is_none() {
+ self.mark_consumer_group_offsets_need_reconcile();
+ }
Ok(())
}
PendingConsumerOffsetMutation::Upsert(offset) => {
- persist_offset(&path, offset, self.consumer_offset_enforce_fsync).await?;
- self.persisted_offsets.borrow_mut().insert(key, offset);
+ if let Some(path) = path.as_deref() {
+ persist_offset(path, offset, self.consumer_offset_enforce_fsync).await?;
+ }
+ let created = self.durable_consumer_offsets.record_explicit(
+ pending.kind,
+ pending.consumer_id,
+ offset,
+ offset,
+ );
+ if path.is_some() && self.consumer_offset_enforce_fsync {
+ self.mark_consumer_offset_dir_dirty(pending.kind);
+ }
+ capacity.clear_stranded(pending.consumer_id);
+ if pending.kind == ConsumerKind::ConsumerGroup && created {
+ self.mark_consumer_group_offsets_need_reconcile();
+ }
Ok(())
}
PendingConsumerOffsetMutation::Delete => {
- delete_persisted_offset(&path).await?;
- self.persisted_offsets.borrow_mut().remove(&key);
+ if let Some(path) = path.as_deref() {
+ // Keep the logical state until the file is removed. The
+ // partition journal is memory-only, so acknowledging an
+ // unsuccessful unlink would let boot resurrect the key.
+ match delete_persisted_offset(path).await {
+ Ok(removed) => {
+ if removed && self.consumer_offset_enforce_fsync {
+ self.mark_consumer_offset_dir_dirty(pending.kind);
+ }
+ capacity.clear_stranded(pending.consumer_id);
+ }
+ Err(error) => {
+ capacity.record_stranded(pending.consumer_id);
+ warn!(
+ target: "iggy.partitions.diag",
+ plane = "partitions",
+ replica_id = self.consensus.replica(),
+ namespace_raw = self.namespace().inner(),
+ kind = ?pending.kind,
+ consumer_id = pending.consumer_id,
+ path,
+ %error,
+ "committed consumer offset delete could not remove its file"
+ );
+ return Err(error);
+ }
+ }
+ }
+ self.durable_consumer_offsets
+ .remove(pending.kind, pending.consumer_id);
+ capacity.forget_inactive_provisional(pending.consumer_id);
+ capacity.rearm_if_below_limit(&self.durable_consumer_offsets);
Ok(())
}
}
}
- /// Whether the committed high-water for this consumer already covers
- /// `offset`, so a poll's auto-commit submit cannot advance it and may be
- /// skipped instead of burning a consensus op. Reads committed state only
- /// (the tracker is fed at commit-apply, never by the eager poll-path
- /// apply): an offset covered in memory but not yet committed keeps
- /// resubmitting until the covering op actually lands, so a dropped
- /// in-flight op self-heals on the next poll.
+ /// Reject completion from a removed partition or a view whose retained
+ /// prepares have not yet been accounted for by the pump.
#[must_use]
- pub fn is_auto_commit_offset_covered(
- &self,
- kind: ConsumerKind,
- consumer_id: u32,
- offset: u64,
- ) -> bool {
- self.persisted_offsets
- .borrow()
- .get(&(kind, consumer_id))
- .is_some_and(|&high_water| offset <= high_water)
- }
-
- fn apply_consumer_offset_commit(
- &self,
- pending: PendingConsumerOffsetCommit,
- ) -> Result<(), IggyError> {
+ pub fn auto_commit_admission_ready(&self, applied: &crate::AutoCommitApplied) -> bool {
+ applied.belongs_to(&self.durable_consumer_offsets)
+ && self.observed_view == self.consensus.view()
+ && !self.offset_reservations_need_resync.get()
+ && (!self
+ .consumer_offset_capacity_for(applied.kind)
+ .is_uncertain()
+ || self
+ .durable_consumer_offsets
+ .contains(applied.kind, applied.consumer_id))
+ }
+
+ fn apply_consumer_offset_commit(&self, pending: PendingConsumerOffsetCommit) {
+ if pending.kind == ConsumerKind::ConsumerGroup
+ && matches!(pending.mutation, PendingConsumerOffsetMutation::Delete)
+ {
+ self.mark_consumer_group_offsets_need_reconcile();
+ }
match pending.mutation {
PendingConsumerOffsetMutation::Upsert(offset)
if pending.kind == ConsumerKind::Consumer =>
@@ -2104,7 +2293,6 @@ where
pending.auto_commit,
create,
);
- Ok(())
}
PendingConsumerOffsetMutation::Upsert(offset)
if pending.kind == ConsumerKind::ConsumerGroup =>
@@ -2133,28 +2321,15 @@ where
pending.auto_commit,
create,
);
- Ok(())
}
- // Commit-time apply keeps its invariant check on the PRIMARY:
- // admission verified the offset exists there, so a miss on the
- // primary is real divergence (log corruption / out-of-order apply)
- // and must surface rather than silently mask a split state. A
- // FOLLOWER may legitimately miss the offset: `AckLevel::NoAck`
- // stores apply on the primary only and are never replicated,
- // so a later quorum delete finds nothing on the backups -- erroring
- // there would fail the committed apply, panic the replica as
- // divergent, and crash-loop on every journal replay. The
- // prepare-time race is handled by not re-checking existence at
- // staging (see `stage_consumer_offset_delete`).
+ // Two independently admitted deletes can commit after both saw
+ // the key present. Deletion is idempotent on every replica, while
+ // admission still rejects a request for an already absent key.
PendingConsumerOffsetMutation::Delete if pending.kind == ConsumerKind::Consumer => {
let id = pending.consumer_id;
let guard = self.consumer_offsets.pin();
let key = usize::try_from(id).expect("u32 consumer id must fit usize");
- let removed = guard.remove(&key).is_some();
- if !removed && !self.consensus.is_follower() {
- return Err(IggyError::ConsumerOffsetNotFound(key));
- }
- Ok(())
+ guard.remove(&key);
}
PendingConsumerOffsetMutation::Delete
if pending.kind == ConsumerKind::ConsumerGroup =>
@@ -2164,13 +2339,9 @@ where
let key = ConsumerGroupId(
usize::try_from(group_id).expect("u32 group id must fit usize"),
);
- let removed = guard.remove(&key).is_some();
- if !removed && !self.consensus.is_follower() {
- return Err(IggyError::ConsumerOffsetNotFound(key.0));
- }
- Ok(())
+ guard.remove(&key);
}
- _ => Ok(()),
+ _ => (),
}
}
@@ -2186,38 +2357,52 @@ where
.collect()
}
- /// Reclaim every stored consumer-group offset whose group id is no longer
- /// `is_live`, returning the owned persisted-file paths the caller must unlink.
- ///
- /// Fully synchronous (no `.await`): the in-memory papaya remove happens here,
- /// the disk unlink is deferred to the caller on owned `String` data so no
- /// borrow of `self` survives across the await. This is the only safe shape
- /// for the reconciler, which runs on a sibling task to the pump that may
- /// realloc the partitions vec during that await. The remove-then-unlink
- /// ordering matches the crash-safe GC invariant (monotonic, never-reused
- /// group ids mean a recreated group never reads a dead group's offset).
+ /// Snapshot dead group keys for deletion through the partition's VSR log.
+ /// A local unlink could free the primary's quota while backups retained
+ /// every older generation, so reclamation uses the same ordered delete as
+ /// an explicit consumer-offset request.
#[must_use]
- #[allow(clippy::cast_possible_truncation)]
- pub fn reclaim_dead_group_offsets(&self, is_live: impl Fn(u64) -> bool) -> Vec<String> {
- let pinned = self.consumer_group_offsets.pin();
- let dead: Vec<u64> = pinned
- .keys()
- .map(|key| key.0 as u64)
- .filter(|group_id| !is_live(*group_id))
- .collect();
- let mut paths = Vec::with_capacity(dead.len());
- for group_id in dead {
- pinned.remove(&ConsumerGroupId(group_id as usize));
- self.persisted_offsets
- .borrow_mut()
- .remove(&(ConsumerKind::ConsumerGroup, group_id as u32));
- if let Some(path) =
- self.persisted_offset_path(ConsumerKind::ConsumerGroup, group_id as u32)
+ pub fn dead_consumer_group_offset_ids(&self, is_live: impl Fn(u64) -> bool) -> Vec<u32> {
+ if !self.consensus.is_primary() || !self.consensus.is_normal() {
+ return Vec::new();
+ }
+ // A stranded file already failed normal loading or unlink. Reissuing
+ // replicated deletes every reconciliation pass cannot make its
+ // filesystem writable and would create a permanent commit loop.
+ // A single-replica explicit deletion can retry after repair. On a
+ // replicated partition the file must be repaired or removed locally,
+ // because older peers do not recognize a delete for a map-missing key.
+ let capacity = self.consumer_offset_capacity_for(ConsumerKind::ConsumerGroup);
+ let mut dead = Vec::new();
+ for key in self.consumer_group_offsets.pin().keys() {
+ let Ok(id) = u32::try_from(key.0) else {
+ continue;
+ };
+ if !is_live(u64::from(id))
+ && !capacity.is_stranded(id)
+ && self
+ .durable_consumer_offsets
+ .contains(ConsumerKind::ConsumerGroup, id)
{
- paths.push(path);
+ dead.push(id);
}
}
- paths
+ dead.sort_unstable();
+ dead.dedup();
+ dead
+ }
+
+ pub(crate) fn set_consumer_group_offsets_reconcile_epoch(&mut self, epoch: Rc<Cell<u64>>) {
+ self.consumer_group_offsets_reconcile_epoch = epoch;
+ self.mark_consumer_group_offsets_need_reconcile();
+ }
+
+ fn mark_consumer_group_offsets_need_reconcile(&self) {
+ self.consumer_group_offsets_reconcile_epoch.set(
+ self.consumer_group_offsets_reconcile_epoch
+ .get()
+ .wrapping_add(1),
+ );
}
/// Cooperative-rebalance classification: a group's `(last_polled, committed)`
@@ -2261,21 +2446,59 @@ where
);
if let Err(error) = self.persist_consumer_offset_commit(pending).await {
+ if offset.is_some() {
+ self.release_consumer_offset_reservation(kind, consumer_id);
+ }
emit_partition_diag(
tracing::Level::WARN,
&PartitionDiagEvent::new(self.diag_ctx(), "no_ack offset persist failed")
.with_operation(request_header.operation)
.with_error(error.to_string()),
);
+ Self::send_partition_deny_or_log(
+ &self.consensus,
+ &request_header,
+ error.as_code(),
+ "no_ack offset failure reply send failed",
+ waiter,
+ )
+ .await;
return;
}
- if let Err(error) = self.apply_consumer_offset_commit(pending) {
+ self.apply_consumer_offset_commit(pending);
+ // Only this request's kind: dirt on the other directory belongs to
+ // whichever path left it, and its failure is not this client's answer.
+ // Visibility does not prove crash durability. A failed required barrier
+ // must remain an error even after the mutation becomes visible.
+ let mut kinds = [false; 2];
+ kinds[crate::state_transfer::consumer_kind_index(kind)] = true;
+ let failed = self.flush_consumer_offset_directories_for(kinds).await;
+ if failed.iter().any(|failed| *failed) {
+ if offset.is_some() {
+ self.release_consumer_offset_reservation(kind, consumer_id);
+ } else {
+ // Retain retry admission after the visible deletion so a new
+ // delete can retry its directory barrier instead of returning
+ // ConsumerOffsetNotFound.
+ self.consumer_offset_capacity_for(kind)
+ .record_stranded(consumer_id);
+ }
emit_partition_diag(
tracing::Level::WARN,
- &PartitionDiagEvent::new(self.diag_ctx(), "no_ack offset apply failed")
- .with_operation(request_header.operation)
- .with_error(error.to_string()),
+ &PartitionDiagEvent::new(
+ self.diag_ctx(),
+ "no_ack offset directory sync failed after a visible local mutation",
+ )
+ .with_operation(request_header.operation),
);
+ Self::send_partition_deny_or_log(
+ &self.consensus,
+ &request_header,
+ IggyError::CannotSyncFile.as_code(),
+ "no_ack offset directory sync failure reply send failed",
+ waiter,
+ )
+ .await;
return;
}
@@ -2284,6 +2507,9 @@ where
&request_header,
committed_reply_body(request_header.operation),
);
+ if offset.is_some() {
+ self.release_consumer_offset_reservation(kind, consumer_id);
+ }
// Same rule as the committed path: a submit's waiter takes the reply,
// because `header.client` is then the VSR consensus id.
if let Some(waiter) = waiter {
@@ -2323,11 +2549,105 @@ where
}
}
+ pub(crate) fn consumer_offset_capacity_for(
+ &self,
+ kind: ConsumerKind,
+ ) -> &ConsumerOffsetCapacity {
+ match kind {
+ ConsumerKind::Consumer => &self.consumer_offset_capacity,
+ ConsumerKind::ConsumerGroup => &self.consumer_group_offset_capacity,
+ }
+ }
+
+ fn reserve_consumer_offset(
+ &self,
+ kind: ConsumerKind,
+ consumer_id: u32,
+ ) -> Result<(), ConsumerOffsetCapacityError> {
+ self.consumer_offset_capacity_for(kind)
+ .try_reserve(consumer_id, &self.durable_consumer_offsets)
+ }
+
+ fn release_consumer_offset_reservation(&self, kind: ConsumerKind, consumer_id: u32) {
+ self.consumer_offset_capacity_for(kind)
+ .release_reservation(consumer_id);
+ }
+
+ fn refresh_consumer_offset_reservation(&self, kind: ConsumerKind, consumer_id: u32) {
+ let count = self
+ .pending_consumer_offset_commits
+ .values()
+ .filter(|pending| {
+ pending.kind == kind
+ && pending.consumer_id == consumer_id
+ && matches!(pending.mutation, PendingConsumerOffsetMutation::Upsert(_))
+ })
+ .count();
+ let capacity = self.consumer_offset_capacity_for(kind);
+ capacity.set_pending_count(consumer_id, count);
+ capacity.rearm_if_below_limit(&self.durable_consumer_offsets);
+ }
+
+ async fn admit_consumer_offset_key(
+ &self,
+ header: &RoutedRequestHeader,
+ kind: ConsumerKind,
+ consumer_id: u32,
+ waiter: &mut Option<consensus::Sender<Message<ReplyHeader>>>,
+ ) -> bool {
+ if self.consumer_offset_capacity_for(kind).is_uncertain()
+ && !self.durable_consumer_offsets.contains(kind, consumer_id)
+ {
+ Self::send_partition_deny_or_log(
+ &self.consensus,
+ header,
+ IggyError::TransientNotAccepted.as_code(),
+ "consumer offset accounting unavailable reply send failed",
+ waiter.take(),
+ )
+ .await;
+ return false;
+ }
+ let Err(capacity_error) = self.reserve_consumer_offset(kind, consumer_id) else {
+ return true;
+ };
+ if capacity_error.first_in_episode {
+ warn!(
+ target: "iggy.partitions.diag",
+ plane = "partitions",
+ replica_id = self.consensus.replica(),
+ namespace_raw = self.namespace().inner(),
+ ?kind,
+ occupied = capacity_error.occupied,
+ limit = capacity_error.limit,
+ config = "[partition] consumer_offsets_max",
+ "consumer offset admission limit reached"
+ );
+ }
+ Self::send_partition_deny_or_log(
+ &self.consensus,
+ header,
+ IggyError::TooManyConsumerOffsets.as_code(),
+ "consumer offset capacity deny reply send failed",
+ waiter.take(),
+ )
+ .await;
+ false
+ }
+
fn ensure_consumer_offset_exists(
&self,
kind: ConsumerKind,
consumer_id: u32,
) -> Result<(), IggyError> {
+ if self.durable_consumer_offsets.contains(kind, consumer_id) {
+ return Ok(());
+ }
+ // A local-only cursor is not a replicated key. Older replicas reject
+ // missing-key deletes when replaying as primary during a rolling upgrade.
+ if self.consensus.replica_count() > 1 {
+ return Err(IggyError::ConsumerOffsetNotFound(consumer_id as usize));
+ }
let found = match kind {
ConsumerKind::Consumer => {
let key = usize::try_from(consumer_id).expect("u32 consumer id must fit usize");
@@ -2341,7 +2661,10 @@ where
}
};
- if found {
+ let local_stranded = self
+ .consumer_offset_capacity_for(kind)
+ .is_stranded(consumer_id);
+ if found || local_stranded {
Ok(())
} else {
Err(IggyError::ConsumerOffsetNotFound(
@@ -2355,14 +2678,201 @@ where
ReplicaLogContext::from_consensus(self.consensus(), PlaneKind::Partitions)
}
- fn clear_pending_consumer_offset_commits_if_view_changed(&mut self) {
+ fn store_offset_range_error(&self, offset: u64) -> Option<IggyError> {
+ let current = self.stats.current_offset();
+ (offset > current || (current == 0 && self.stats.messages_count_inconsistent() == 0))
+ .then_some(IggyError::InvalidOffset(offset))
+ }
+
+ fn resynchronize_consumer_offset_reservations(&mut self) {
+ self.resynchronize_consumer_offset_reservations_inner(false);
+ }
+
+ /// Retry incomplete accounting at most once per shard tick, after progress.
+ pub fn retry_consumer_offset_reservations(&mut self) {
+ if self.consumer_offset_capacity.is_uncertain()
+ || self.consumer_group_offset_capacity.is_uncertain()
+ {
+ self.resynchronize_consumer_offset_reservations_inner(true);
+ }
+ }
+
+ #[allow(clippy::too_many_lines)]
+ fn resynchronize_consumer_offset_reservations_inner(&mut self, from_tick: bool) {
let current_view = self.consensus.view();
+ let scan_state = (
+ self.consensus.commit_min(),
+ self.consensus.commit_max(),
+ self.consensus.sequencer().current_sequence(),
+ self.log.journal().inner.last_op(),
+ );
+ let uncertain = self.consumer_offset_capacity.is_uncertain()
+ || self.consumer_group_offset_capacity.is_uncertain();
if current_view == self.observed_view {
- return;
+ if uncertain && !from_tick {
+ return;
+ }
+ let retry_requested = self.offset_reservations_need_resync.get()
+ || (uncertain && self.offset_reservations_scan_state != Some(scan_state));
+ if !retry_requested {
+ return;
+ }
}
- self.pending_consumer_offset_commits.clear();
+ if current_view != self.observed_view {
+ self.queued_auto_commit_reservations.borrow_mut().clear();
+ self.mark_consumer_group_offsets_need_reconcile();
+ }
+
+ let from_op = self
+ .consensus
+ .commit_min()
+ .max(self.purge_floor_op)
+ .saturating_add(1);
+ let commit_max = self.consensus.commit_max();
+ let to_op = self
+ .consensus
+ .sequencer()
+ .current_sequence()
+ .min(self.log.journal().inner.last_op().unwrap_or(commit_max));
+ // Committed offset prepares still need local apply, even if a message
+ // flush already evicted their journal bytes. Never drop their staging.
+ // Within one view an op is assigned once, so uncommitted staging is
+ // kept too; only a view change can replace what sits at those ops, and
+ // only then is the tail decoded again.
+ let same_view = current_view == self.observed_view;
+ let mut rebuilt: HashMap<_, _> = self
+ .pending_consumer_offset_commits
+ .iter()
+ .filter(|(op, _)| {
+ **op >= from_op && (**op <= commit_max || (same_view && **op <= to_op))
+ })
+ .map(|(op, pending)| (*op, *pending))
+ .collect();
+ let headers = self.log.journal().inner.repair_headers_in(from_op..=to_op);
+ let uncommitted_from = from_op.max(commit_max.saturating_add(1));
+ let expected = to_op
+ .checked_sub(uncommitted_from)
+ .map_or(0, |span| span.saturating_add(1));
+ let mut decode_failed =
+ headers.keys().filter(|op| **op >= uncommitted_from).count() as u64 != expected;
+ for (op, header) in headers {
+ if !matches!(
+ header.operation,
+ Operation::StoreConsumerOffset | Operation::DeleteConsumerOffset
+ ) {
+ continue;
+ }
+ if rebuilt.contains_key(&op) {
+ continue;
+ }
+ match self.restage_consumer_offset_from_journal(op) {
+ Ok(pending) => {
+ rebuilt.insert(op, pending);
+ }
+ Err(error) => {
+ error!(
+ target: "iggy.partitions.diag",
+ plane = "partitions",
+ replica_id = self.consensus.replica(),
+ namespace_raw = self.namespace().inner(),
+ op,
+ %error,
+ "failed to rebuild consumer offset reservations after view change"
+ );
+ decode_failed = true;
+ break;
+ }
+ }
+ }
+ self.pending_consumer_offset_commits = rebuilt;
+ if decode_failed {
+ self.consumer_offset_capacity.mark_uncertain();
+ self.consumer_group_offset_capacity.mark_uncertain();
+ } else {
+ let consumer_ids = self
+ .pending_consumer_offset_commits
+ .values()
+ .filter(|pending| {
+ pending.kind == ConsumerKind::Consumer
+ && matches!(pending.mutation, PendingConsumerOffsetMutation::Upsert(_))
+ })
+ .map(|pending| pending.consumer_id);
+ self.consumer_offset_capacity
+ .rebuild(&self.durable_consumer_offsets, consumer_ids);
+ let group_ids = self
+ .pending_consumer_offset_commits
+ .values()
+ .filter(|pending| {
+ pending.kind == ConsumerKind::ConsumerGroup
+ && matches!(pending.mutation, PendingConsumerOffsetMutation::Upsert(_))
+ })
+ .map(|pending| pending.consumer_id);
+ self.consumer_group_offset_capacity
+ .rebuild(&self.durable_consumer_offsets, group_ids);
+ }
self.observed_view = current_view;
+ self.offset_reservations_scan_state = Some(scan_state);
+ // The shard tick retries uncertainty after journal or frontier progress.
+ self.offset_reservations_need_resync.set(false);
+ }
+
+ fn reclaim_phantom_offsets(&self, kind: ConsumerKind, map_count: usize) {
+ let capacity = self.consumer_offset_capacity_for(kind);
+ if self.durable_consumer_offsets.count(kind) >= capacity.limit()
+ || !capacity.should_reclaim(&self.durable_consumer_offsets)
+ {
+ return;
+ }
+ let needed = map_count.saturating_sub(capacity.limit()).saturating_add(1);
+ match kind {
+ ConsumerKind::Consumer => {
+ self.reclaim_phantom_offset_keys(&self.consumer_offsets, kind, needed, |key| {
+ u32::try_from(*key).ok()
+ });
+ }
+ ConsumerKind::ConsumerGroup => self.reclaim_phantom_offset_keys(
+ &self.consumer_group_offsets,
+ kind,
+ needed,
+ |key| u32::try_from(key.0).ok(),
+ ),
+ }
+ }
+
+ fn reclaim_phantom_offset_keys<K: Hash + Eq>(
+ &self,
+ offsets: &papaya::HashMap<K, ConsumerOffset>,
+ kind: ConsumerKind,
+ mut remaining: usize,
+ consumer_id: impl Fn(&K) -> Option<u32>,
+ ) {
+ let capacity = self.consumer_offset_capacity_for(kind);
+ let map = offsets.pin();
+ for (key, _) in &map {
+ if let Some(id) = consumer_id(key)
+ && !capacity.holds(id, &self.durable_consumer_offsets)
+ && map.remove(key).is_some()
+ {
+ capacity.forget_inactive_provisional(id);
+ // This cursor was never durable, so the consumer's next `Next`
+ // poll restarts from offset 0 and redelivers. At-least-once
+ // permits it; an operator should still see it happen.
+ warn!(
+ target: "iggy.partitions.diag",
+ plane = "partitions",
+ namespace_raw = self.namespace().inner(),
+ ?kind,
+ consumer_id = id,
+ "reclaimed a local consumer offset cursor with no durable backing; its next \
+ poll restarts from offset 0"
+ );
+ remaining -= 1;
+ if remaining == 0 {
+ break;
+ }
+ }
+ }
}
/// Build an owned [`PollPlan`] synchronously (no `.await`), so the caller
@@ -2421,6 +2931,30 @@ where
}
};
+ if args.auto_commit
+ && let Ok(pending) = PendingConsumerOffsetCommit::try_from_polling_consumer(consumer, 0)
+ {
+ let capacity = self.consumer_offset_capacity_for(pending.kind);
+ if !capacity.is_uncertain() {
+ let exists = match pending.kind {
+ ConsumerKind::Consumer => self
+ .consumer_offsets
+ .pin()
+ .contains_key(&(pending.consumer_id as usize)),
+ ConsumerKind::ConsumerGroup => self
+ .consumer_group_offsets
+ .pin()
+ .contains_key(&ConsumerGroupId(pending.consumer_id as usize)),
+ };
+ if !exists {
+ let map_count = self.consumer_offset_map_count(pending.kind);
+ if map_count >= capacity.limit() {
+ self.reclaim_phantom_offsets(pending.kind, map_count);
+ }
+ }
+ }
+ }
+
// Past the empty-return guards: only now build the auto-commit context,
// whose offset-path `format!()` is wasted on the early returns above.
let auto_commit = self.auto_commit_ctx(consumer, args.auto_commit);
@@ -2533,7 +3067,15 @@ where
create_path: self.consumer_group_offsets_path.clone(),
},
};
- Some(AutoCommitCtx { target })
+ let capacity = match pending.kind {
+ ConsumerKind::Consumer => Rc::clone(&self.consumer_offset_capacity),
+ ConsumerKind::ConsumerGroup => Rc::clone(&self.consumer_group_offset_capacity),
+ };
+ Some(AutoCommitCtx {
+ target,
+ capacity,
+ durable: Rc::clone(&self.durable_consumer_offsets),
+ })
}
/// Synchronous in-memory journal poll, for the resident tier. Never awaits
@@ -2580,17 +3122,6 @@ where
.map(|journaled| journaled.result)
}
- #[allow(clippy::cast_possible_truncation)]
- fn store_consumer_offset(
- &self,
- consumer: PollingConsumer,
- offset: u64,
- ) -> Result<(), IggyError> {
- let pending = PendingConsumerOffsetCommit::try_from_polling_consumer(consumer, offset)?;
- self.apply_consumer_offset_commit(pending)?;
- Ok(())
- }
-
fn get_consumer_offset(&self, consumer: PollingConsumer) -> Option<u64> {
match consumer {
PollingConsumer::Consumer(id, _) => self
@@ -2798,13 +3329,36 @@ where
message: Message<RoutedRequestHeader>,
reply: Option<consensus::Sender<Message<ReplyHeader>>>,
) {
- // Taken by whichever arm answers: the deny paths, the NoAck fast path,
- // or the pipeline entry that fires it at commit. Exactly one runs.
- let mut reply = reply;
- self.clear_pending_consumer_offset_commits_if_view_changed();
- let namespace = IggyNamespace::from_raw(message.header().group);
- let client_id = message.header().client;
- let request = message.header().request;
+ self.on_request_with_reservation(message, reply, None).await;
+ }
+
+ #[allow(clippy::too_many_lines)]
+ pub(crate) async fn on_request_with_reservation(
+ &mut self,
+ message: Message<RoutedRequestHeader>,
+ reply: Option<consensus::Sender<Message<ReplyHeader>>>,
+ mut reservation: Option<crate::AutoCommitReservation>,
+ ) {
+ if reservation.as_ref().is_some_and(|reservation| {
+ !self
+ .consumer_offset_capacity_for(reservation.kind)
+ .owns(reservation)
+ }) {
+ debug!(
+ namespace_raw = self.namespace().inner(),
+ kind = ?reservation.as_ref().map(|reservation| reservation.kind),
+ consumer_id = ?reservation.as_ref().map(|reservation| reservation.consumer_id),
+ "dropping auto-commit reservation owned by another partition incarnation"
+ );
+ return;
+ }
+ // Taken by whichever arm answers: the deny paths, the NoAck fast path,
+ // or the pipeline entry that fires it at commit. Exactly one runs.
+ let mut reply = reply;
+ self.resynchronize_consumer_offset_reservations();
+ let namespace = IggyNamespace::from_raw(message.header().group);
+ let client_id = message.header().client;
+ let request = message.header().request;
let disposition = {
let consensus = self.consensus();
@@ -2992,39 +3546,45 @@ where
// code on this committed-shaped frame (op=commit_max) as success.
if matches!(message.header().operation, Operation::StoreConsumerOffset)
&& let Some((_, _, Some(requested_offset), _)) = consumer_offset
+ && let Some(error) = self.store_offset_range_error(requested_offset)
{
- let current_offset = self.stats.current_offset();
- let partition_empty =
- self.stats.messages_count_inconsistent() == 0 && current_offset == 0;
- if partition_empty || requested_offset > current_offset {
- emit_partition_diag(
- tracing::Level::WARN,
- &PartitionDiagEvent::new(
- ReplicaLogContext::from_consensus(consensus, PlaneKind::Partitions),
- "rejecting store_consumer_offset for out-of-range offset",
- )
- .with_operation(message.header().operation)
- .with_error(IggyError::InvalidOffset(requested_offset).to_string()),
- );
- Self::send_partition_deny_or_log(
- consensus,
- message.header(),
- IggyError::InvalidOffset(requested_offset).as_code(),
- "store_consumer_offset deny reply send failed",
- reply.take(),
+ emit_partition_diag(
+ tracing::Level::WARN,
+ &PartitionDiagEvent::new(
+ ReplicaLogContext::from_consensus(consensus, PlaneKind::Partitions),
+ "rejecting store_consumer_offset for out-of-range offset",
)
- .await;
- return;
- }
+ .with_operation(message.header().operation)
+ .with_error(error.to_string()),
+ );
+ Self::send_partition_deny_or_log(
+ consensus,
+ message.header(),
+ error.as_code(),
+ "store_consumer_offset deny reply send failed",
+ reply.take(),
+ )
+ .await;
+ return;
}
- // NoAck -> fast path. Quorum -> VSR pipeline.
+ // The node-local fast path is safe only for a single-replica
+ // partition. Every mutation in a replicated partition enters VSR
+ // regardless of the acknowledgement byte.
if let Some((kind, consumer_id, offset, AckLevel::NoAck)) = consumer_offset
+ && consensus.replica_count() == 1
&& matches!(
message.header().operation,
Operation::StoreConsumerOffset | Operation::DeleteConsumerOffset,
)
{
+ if offset.is_some()
+ && !self
+ .admit_consumer_offset_key(message.header(), kind, consumer_id, &mut reply)
+ .await
+ {
+ return;
+ }
Disposition::NoAck {
request_header: Box::new(*message.header()),
kind,
@@ -3071,10 +3631,24 @@ where
waiter,
)
.await;
+ } else if let Some(reservation) = reservation.take() {
+ self.queued_auto_commit_reservations
+ .borrow_mut()
+ .entry((reservation.kind, reservation.consumer_id))
+ .or_default()
+ .push(reservation);
}
return;
}
+ if let Some((kind, consumer_id, Some(_), _)) = consumer_offset
+ && !self
+ .admit_consumer_offset_key(message.header(), kind, consumer_id, &mut reply)
+ .await
+ {
+ return;
+ }
+
let prepare = message.project(consensus);
consensus.verify_pipeline();
match reply.take() {
@@ -3135,11 +3709,40 @@ where
/// # Panics
/// On mid-iteration status flip. Reachable only if `clear_request_queue`
/// is bypassed at view-change reset.
- #[allow(clippy::future_not_send)]
+ #[allow(clippy::future_not_send, clippy::too_many_lines)]
pub async fn drain_request_queue_into_prepares(&mut self, slots_freed: usize) {
- for _ in 0..slots_freed {
+ self.resynchronize_consumer_offset_reservations();
+ let mut promoted = 0;
+ // Denials do not consume a slot, so without a budget one drain could
+ // answer the whole queue, each with an awaited reply send, inside one
+ // commit turn. Consecutive denials end the drain. The shard tick
+ // resumes parked work even if no further operation commits.
+ let mut consecutive_denials = 0usize;
+ while promoted < slots_freed {
let req = self.consensus().pop_queued_request();
let Some(mut req) = req else { break };
+ let parsed_store = (req.message.header().operation == Operation::StoreConsumerOffset)
+ .then(|| {
+ Self::parse_consumer_offset_request(
+ Operation::StoreConsumerOffset,
+ &req.message,
+ )
+ });
+ let _reservation = parsed_store
+ .as_ref()
+ .and_then(|parsed| parsed.as_ref().ok())
+ .and_then(|(kind, id, _, _)| {
+ if !is_auto_commit_client(req.message.header().client) {
+ return None;
+ }
+ let mut queued = self.queued_auto_commit_reservations.borrow_mut();
+ let reservations = queued.get_mut(&(*kind, *id))?;
+ let reservation = reservations.pop();
+ if reservations.is_empty() {
+ queued.remove(&(*kind, *id));
+ }
+ reservation
+ });
// Taken before the preflight so a refusal answers the parked waiter
// instead of waking it with `Canceled`.
@@ -3151,6 +3754,55 @@ where
break;
}
+ if let Some(parsed) = parsed_store {
+ let Ok((kind, consumer_id, Some(offset), _)) = parsed else {
+ Self::send_partition_deny_or_log(
+ self.consensus(),
+ req.message.header(),
+ IggyError::InvalidCommand.as_code(),
+ "queued consumer offset parse deny reply send failed",
+ reply_sender.take(),
+ )
+ .await;
+ consecutive_denials += 1;
+ if consecutive_denials >= PROMOTION_DENIALS_MAX {
+ break;
+ }
+ continue;
+ };
+ if let Some(error) = self.store_offset_range_error(offset) {
+ Self::send_partition_deny_or_log(
+ self.consensus(),
+ req.message.header(),
+ error.as_code(),
+ "queued offset range deny reply send failed",
+ reply_sender.take(),
+ )
+ .await;
+ consecutive_denials += 1;
+ if consecutive_denials >= PROMOTION_DENIALS_MAX {
+ break;
+ }
+ continue;
+ }
+ if !self
+ .admit_consumer_offset_key(
+ req.message.header(),
+ kind,
+ consumer_id,
+ &mut reply_sender,
+ )
+ .await
+ {
+ consecutive_denials += 1;
+ if consecutive_denials >= PROMOTION_DENIALS_MAX {
+ break;
+ }
+ continue;
+ }
+ }
+ consecutive_denials = 0;
+
let prepare = {
let consensus = self.consensus();
assert!(
@@ -3179,17 +3831,35 @@ where
}
prepare
};
+ promoted += 1;
self.on_replicate(prepare).await;
}
}
+ #[must_use]
+ pub fn queued_requests_ready(&self) -> bool {
+ self.fatal.is_none()
+ && self.consensus.is_primary()
+ && self.consensus.is_normal()
+ && !self.consensus.is_transferring()
+ && !self.consensus.pipeline_is_full()
+ && self.consensus.request_queue_len() > 0
+ }
+
+ /// Resume a bounded promotion turn without waiting for another commit.
+ pub async fn resume_queued_requests(&mut self) {
+ if self.queued_requests_ready() {
+ self.drain_request_queue_into_prepares(1).await;
+ }
+ }
+
/// # Panics
/// Panics on a primary when a prepare's op is ahead of the local
/// sequencer: journaling it would make the next op assignment collide,
/// which is unrecoverable in place.
#[allow(clippy::future_not_send, clippy::too_many_lines)]
pub async fn on_replicate(&mut self, message: Message<PrepareHeader>) {
- self.clear_pending_consumer_offset_commits_if_view_changed();
+ self.resynchronize_consumer_offset_reservations();
let header = *message.header();
// Same reason as the metadata plane: `checksum` is compared as an opaque token
// downstream, so a corrupted frame passes whenever its flipped value satisfies
@@ -3525,7 +4195,7 @@ where
if self.fatal.is_some() {
return;
}
- self.clear_pending_consumer_offset_commits_if_view_changed();
+ self.resynchronize_consumer_offset_reservations();
let header = *message.header();
{
let consensus = self.consensus();
@@ -3600,7 +4270,7 @@ where
if self.fatal.is_some() {
return;
}
- self.clear_pending_consumer_offset_commits_if_view_changed();
+ self.resynchronize_consumer_offset_reservations();
// The primary commits inline via `on_ack` (it drains its own pipeline).
// Backups never populate the pipeline - they journal replicated prepares
@@ -3673,7 +4343,8 @@ where
Ok(frozen)
}
Operation::StoreConsumerOffset | Operation::DeleteConsumerOffset => {
- // Replicated path is Quorum-only by construction; ack ignored.
+ // Replication semantics do not depend on the acknowledgement
+ // byte. Multi-replica `NoAck` requests enter this same path.
let (kind, consumer_id, offset, _ack) =
Self::parse_staged_consumer_offset_commit(header.operation, &message)?;
let write_lock = self.write_lock.clone();
@@ -3948,6 +4619,10 @@ where
}
}
self.consensus.invalidate_local_dvc_suffix();
+ let commit_max = self.consensus.commit_max();
+ self.pending_consumer_offset_commits
+ .retain(|op, _| *op < from_op || *op <= commit_max);
+ self.offset_reservations_need_resync.set(true);
Ok(removed)
}
@@ -4075,6 +4750,12 @@ where
let (frozen_batches, index_bytes, flush_index, batch_count, committed_info, chunk_len) = {
let segment = self.log.active_segment();
let mut file_position = segment.size.as_bytes_u64();
+ let persisted_end = if file_position == 0 {
+ segment.start_offset.checked_sub(1)
+ } else {
+ Some(segment.end_offset)
+ }
+ .max(self.recovered_durable_offset);
let mut flush_index = None;
let mut frozen = Vec::with_capacity(entries.len());
let mut batch_count = 0u32;
@@ -4123,13 +4804,13 @@ where
if message_count == 0 {
continue;
}
- // A repaired batch at or below the boot-time recovered
- // durable offset is already IN the segments this replica
- // recovered; persisting it again would append duplicate
- // bytes past the segment end. Evict it without writing.
- // Live traffic always sits above the (immutable) line.
+ // Flush can run ahead of the bounded commit walk. Repair
+ // may re-journal an evicted batch above commit_min even
+ // after this process persisted it. Include the current
+ // segment frontier, not just the boot recovery frontier,
+ // so that replay cannot append a second copy.
let batch_end = batch.header.base_offset + u64::from(message_count) - 1;
- if let Some(durable) = self.recovered_durable_offset
+ if let Some(durable) = persisted_end
&& batch_end <= durable
{
continue;
@@ -4320,13 +5001,22 @@ where
let committed_batch_stats = self.resolve_committed_visible_offsets(&drained);
let mut messages_committed = false;
- for (mut entry, batch_stats) in drained.into_iter().zip(committed_batch_stats) {
+ // Apply the drained batch before advancing any op because directory
+ // durability is shared by every delete in the batch. Until the sync
+ // below succeeds, earlier applied entries intentionally remain above
+ // commit_min and their replies and dedup folds stay owned by `drained`.
+ // A failure at entry K fences the replica. Recovery replays the whole
+ // unadvanced prefix idempotently, including entries applied before K.
+ for cell in &self.consumer_offset_dirs_touched {
+ cell.set(None);
+ }
+ for (entry, batch_stats) in drained.iter().zip(&committed_batch_stats) {
let prepare_header = entry.header;
if !self
.commit_partition_entry(
prepare_header,
&mut messages_committed,
- batch_stats,
+ *batch_stats,
&mut failed_commit,
config,
)
@@ -4367,7 +5057,49 @@ where
});
return;
}
+ }
+
+ // Commit replies and the applied frontier must follow directory
+ // durability. One sync per dirty kind covers the whole walk. A sync
+ // failure is attributed to an operation of that kind in this walk.
+ // Covered stores depend on previously dirty directory entries too.
+ // Only a kind THIS walk uses can fence it: dirt left by a NoAck
+ // request belongs to that request's kind, and fencing a walk that wrote
+ // consumer offsets over the groups directory would take the node down
+ // for a failure none of its ops caused.
+ let touched = [
+ self.consumer_offset_dirs_touched[0].replace(None),
+ self.consumer_offset_dirs_touched[1].replace(None),
+ ];
+ let failed = self
+ .flush_consumer_offset_directories_for(touched.map(|entry| entry.is_some()))
+ .await;
+ if failed.iter().any(|failed| *failed) {
+ let failed_entry = failed
+ .iter()
+ .zip(touched)
+ .find_map(|(failed, entry)| if *failed { entry } else { None });
+ error!(
+ namespace_raw,
+ failed_consumer = failed[0],
+ failed_consumer_group = failed[1],
+ touched_consumer = touched[0].is_some(),
+ touched_consumer_group = touched[1].is_some(),
+ fences = failed_entry.is_some(),
+ "consumer offset directory sync failed after committed operations"
+ );
+ if let Some((op, operation)) = failed_entry {
+ self.fatal = Some(FatalCommit {
+ namespace_raw,
+ op,
+ operation,
+ });
+ return;
+ }
+ }
+ for (mut entry, batch_stats) in drained.into_iter().zip(committed_batch_stats) {
+ let prepare_header = entry.header;
self.consensus.advance_commit_min(prepare_header.op);
// Fold the committed request into this group's dedup slice. Runs on
@@ -4412,7 +5144,14 @@ where
// `AUTO_COMMIT_CLIENT_ID`: no client ever waits on it, so skip the
// reply. Emitting it would push an unrequested frame onto a real
// client's lockstep reply stream if the sentinel ever routed there.
- if send_client_replies && !is_auto_commit_client(prepare_header.client) {
+ if is_auto_commit_client(prepare_header.client) {
+ if let Some(sender) = entry.take_reply_sender() {
+ let _ = sender.send(build_reply_message(
+ &prepare_header,
+ &committed_reply_body(prepare_header.operation),
+ ));
+ }
+ } else if send_client_replies {
let body = match prepare_header.operation {
Operation::SendMessages => {
send_messages_reply_body(prepare_header.group, batch_stats)
@@ -4470,6 +5209,69 @@ where
self.drain_request_queue_into_prepares(drained_count).await;
}
+ /// Sync the dirty offset directories selected by `kinds`, indexed by
+ /// `consumer_kind_index`. Returns which of them failed. A failed directory
+ /// stays dirty for the next attempt.
+ async fn flush_consumer_offset_directories_for(&self, kinds: [bool; 2]) -> [bool; 2] {
+ let mut failed = [false; 2];
+ for (index, dir) in [
+ self.consumer_offsets_path.as_deref(),
+ self.consumer_group_offsets_path.as_deref(),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ if !kinds[index] || !self.consumer_offset_dirs_dirty[index].get() {
+ continue;
+ }
+ #[cfg(test)]
+ if self.consumer_offset_dir_sync_fault.get() == Some(index) {
+ failed[index] = true;
+ continue;
+ }
+ if let Some(dir) = dir {
+ match crate::state_transfer::fsync_dir(dir).await {
+ Ok(()) => {}
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
+ // The directory disappeared after the final unlink.
+ // There is no remaining dirent whose durability needs
+ // proving.
+ }
+ Err(error) => {
+ warn!(
+ target: "iggy.partitions.diag",
+ plane = "partitions",
+ replica_id = self.consensus.replica(),
+ namespace_raw = self.namespace().inner(),
+ path = dir,
+ error_kind = ?error.kind(),
+ %error,
+ "consumer offset directory sync failed"
+ );
+ failed[index] = true;
+ continue;
+ }
+ }
+ #[cfg(test)]
+ self.offset_dir_sync_count
+ .set(self.offset_dir_sync_count.get() + 1);
+ }
+ self.consumer_offset_dirs_dirty[index].set(false);
+ }
+ failed
+ }
+
+ fn mark_consumer_offset_dir_dirty(&self, kind: ConsumerKind) {
+ let index = crate::state_transfer::consumer_kind_index(kind);
+ self.consumer_offset_dirs_dirty[index].set(true);
+ }
+
+ /// Keys of `kind` whose offset file could not be loaded or unlinked.
+ #[must_use]
+ pub fn stranded_consumer_offset_count(&self, kind: ConsumerKind) -> usize {
+ self.consumer_offset_capacity_for(kind).stranded_count()
+ }
+
/// Batch stats for each drained entry, positionally parallel to `drained`.
/// Every entry contributes exactly one slot (`None` for the operations that
/// carry no batch), which is what makes the pairing correct by
@@ -4672,6 +5474,9 @@ where
send_fail_label: &'static str,
waiter: Option<consensus::Sender<Message<ReplyHeader>>>,
) {
+ if waiter.is_none() && is_auto_commit_client(header.client) {
+ return;
+ }
let reply = build_deny_reply_from_request(consensus, header, status);
Self::deliver_reply_or_log(consensus, header, reply, waiter, send_fail_label).await;
}
@@ -4718,17 +5523,17 @@ where
.inner
.repair_entry(op)
.ok_or(IggyError::InvalidCommand)?;
- // Deep copy: the journal buffer is shared and `Message::try_from`
- // wants an `Owned`; this path only runs on the post-view-change
- // fallback, never per-commit.
- let owned = Owned::<MESSAGE_ALIGN>::copy_from_slice(entry.as_slice());
- let message = Message::<GenericHeader>::try_from(owned)
- .map_err(|_| IggyError::InvalidCommand)?
- .try_into_typed::<PrepareHeader>()
+ let bytes = entry.as_slice();
+ let header_bytes = bytes
+ .get(..size_of::<PrepareHeader>())
+ .ok_or(IggyError::InvalidCommand)?;
+ let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(header_bytes)
.map_err(|_| IggyError::InvalidCommand)?;
- let header = *message.header();
+ let body = bytes
+ .get(size_of::<PrepareHeader>()..header.size as usize)
+ .ok_or(IggyError::InvalidCommand)?;
let (kind, consumer_id, offset, _ack) =
- Self::parse_staged_consumer_offset_commit(header.operation, &message)?;
+ Self::parse_consumer_offset_payload(header.operation, body)?;
match header.operation {
Operation::StoreConsumerOffset => {
let offset = offset.ok_or(IggyError::InvalidCommand)?;
@@ -4806,8 +5611,13 @@ where
// from the kept journal entries, so a cleared table alone would be
// repopulated from the entry this guard is fencing.
if prepare_header.op <= self.purge_floor_op {
- self.pending_consumer_offset_commits
- .remove(&prepare_header.op);
+ if let Some(pending) = self
+ .pending_consumer_offset_commits
+ .remove(&prepare_header.op)
+ && matches!(pending.mutation, PendingConsumerOffsetMutation::Upsert(_))
+ {
+ self.release_consumer_offset_reservation(pending.kind, pending.consumer_id);
+ }
return true;
}
@@ -5680,27 +6490,29 @@ where
// Clear consumer + consumer-group offsets (memory + disk). Collect the
// file paths before deleting so the map guard is not held across an
// await.
- let consumer_paths: Vec<String> = {
+ let consumer_paths: Vec<(ConsumerKind, u32, String)> = {
let guard = self.consumer_offsets.pin();
let paths = guard
.iter()
.filter_map(|(key, _)| {
- u32::try_from(*key)
- .ok()
- .and_then(|id| self.persisted_offset_path(ConsumerKind::Consumer, id))
+ u32::try_from(*key).ok().and_then(|id| {
+ self.persisted_offset_path(ConsumerKind::Consumer, id)
+ .map(|path| (ConsumerKind::Consumer, id, path))
+ })
})
.collect();
guard.clear();
paths
};
- let group_paths: Vec<String> = {
+ let group_paths: Vec<(ConsumerKind, u32, String)> = {
let guard = self.consumer_group_offsets.pin();
let paths = guard
.iter()
.filter_map(|(key, _)| {
- u32::try_from(key.0)
- .ok()
- .and_then(|id| self.persisted_offset_path(ConsumerKind::ConsumerGroup, id))
+ u32::try_from(key.0).ok().and_then(|id| {
+ self.persisted_offset_path(ConsumerKind::ConsumerGroup, id)
+ .map(|path| (ConsumerKind::ConsumerGroup, id, path))
+ })
})
.collect();
guard.clear();
@@ -5710,15 +6522,43 @@ where
// full reset, and an offset file the live map never held -- a pre-purge
// op re-persisted by journal repair on a restarted replica -- would
// otherwise survive for boot to hydrate back.
- let strayed =
- crate::state_transfer::strayed_offset_files(self.consumer_offsets_path.as_deref(), &[])
+ let strayed_consumers =
+ crate::state_transfer::strayed_offset_files(self.consumer_offsets_path.as_deref())
.into_iter()
- .chain(crate::state_transfer::strayed_offset_files(
- self.consumer_group_offsets_path.as_deref(),
- &[],
- ));
- for path in consumer_paths.into_iter().chain(group_paths).chain(strayed) {
- let _ = delete_persisted_offset(&path).await;
+ .filter_map(|path| {
+ crate::state_transfer::numeric_offset_id(&path)
+ .map(|id| (ConsumerKind::Consumer, id, path))
+ });
+ let strayed_groups = crate::state_transfer::strayed_offset_files(
+ self.consumer_group_offsets_path.as_deref(),
+ )
+ .into_iter()
+ .filter_map(|path| {
+ crate::state_transfer::numeric_offset_id(&path)
+ .map(|id| (ConsumerKind::ConsumerGroup, id, path))
+ });
+ for (kind, consumer_id, path) in consumer_paths
+ .into_iter()
+ .chain(group_paths)
+ .chain(strayed_consumers)
+ .chain(strayed_groups)
+ {
+ if let Err(error) = delete_persisted_offset(&path).await {
+ self.consumer_offset_capacity_for(kind)
+ .record_stranded(consumer_id);
+ warn!(
+ target: "iggy.partitions.diag",
+ plane = "partitions",
+ namespace_raw = namespace.inner(),
+ generation,
+ path,
+ %error,
+ "purge could not remove a consumer offset file"
+ );
+ } else {
+ self.consumer_offset_capacity_for(kind)
+ .clear_stranded(consumer_id);
+ }
}
// Directory fsync so those unlinks stick, mirroring the install path: a
// crash right after the purge otherwise resurrects the offset files at
@@ -5747,10 +6587,13 @@ where
);
}
}
- // The persisted-offset tracker mirrors the files unlinked above; a
- // stale entry would make a post-purge auto-commit skip its write and
- // lose the offset on restart.
- self.persisted_offsets.borrow_mut().clear();
+ self.durable_consumer_offsets.clear();
+ self.pending_consumer_offset_commits.clear();
+ self.queued_auto_commit_reservations.borrow_mut().clear();
+ self.consumer_offset_capacity
+ .rebuild(&self.durable_consumer_offsets, std::iter::empty());
+ self.consumer_group_offset_capacity
+ .rebuild(&self.durable_consumer_offsets, std::iter::empty());
// Clear the ephemeral cooperative-rebalance tracking too: after the
// reset to offset 0 a stale `last_polled` (a high pre-purge offset)
@@ -5944,6 +6787,7 @@ where
consensus.sequencer().set_sequence(frontier);
consensus.set_last_prepare_checksum(frontier_checksum);
}
+ self.offset_reservations_need_resync.set(true);
}
/// Conclude a repair stream: settle the commit floor at the serving
@@ -6399,6 +7243,11 @@ fn accumulate_committed_info(
/// it -- only a backlog does, and that one drains over several passes.
const SEGMENT_REMOVAL_BUDGET_PER_PASS: usize = 16;
+/// Consecutive denials that end one promotion drain. Denials free no slot, so
+/// without this bound a single commit turn could answer every queued request,
+/// each with an awaited reply send.
+const PROMOTION_DENIALS_MAX: usize = 4;
+
/// What one call to [`IggyPartition::remove_sealed_segments_up_to`] reclaimed.
///
/// `budget_spent` reports that the pass stopped on
@@ -6493,6 +7342,7 @@ mod tests {
use iggy_binary_protocol::{Command, ReplyHeader, WireConsumer, WireEncode};
use message_bus::{BusMessage, SendError};
use server_common::MESSAGE_ALIGN;
+ use server_common::iobuf::Owned;
use server_common::send_messages::{
COMMAND_HEADER_SIZE, IggyMessage, IggyMessageHeader, IggyMessages, SendMessagesOwned,
decode_batch_slice,
@@ -7748,69 +8598,983 @@ mod tests {
})
}
- /// Deleting a consumer offset that was never stored must answer with a
- /// typed deny reply (empty body, `status` = `ConsumerOffsetNotFound`,
- /// `op` 0) before consensus: nothing may enter the pipeline, and an
- /// awaited client write must fail fast instead of waiting out its reply
- /// timeout. Once the offset exists, the same request must pass the gate
- /// into the pipeline without a deny.
- #[compio::test]
- async fn on_request_delete_of_missing_offset_replies_typed_deny() {
- let (mut partition, sent_to_clients) = recording_partition();
- let client_id: u128 = 42;
- let consumer_id: u32 = 5;
+ fn store_offset_request(
+ client_id: u128,
+ request_id: u64,
+ kind: ConsumerKind,
+ consumer_id: u32,
+ offset: u64,
+ ack: AckLevel,
+ ) -> Message<RoutedRequestHeader> {
+ let body = StoreConsumerOffsetRequest {
+ consumer: WireConsumer {
+ kind: kind.as_code(),
+ id: WireIdentifier::Numeric(consumer_id),
+ },
+ stream_id: WireIdentifier::Numeric(1),
+ topic_id: WireIdentifier::Numeric(1),
+ partition_id: Some(0),
+ offset,
+ ack,
+ }
+ .to_bytes();
+ let header_size = std::mem::size_of::<RoutedRequestHeader>();
+ let total = header_size + body.len();
+ let mut message = Message::<RoutedRequestHeader>::new(total);
+ message.as_mut_slice()[header_size..].copy_from_slice(&body);
+ message.transmute_header(|_, header: &mut RoutedRequestHeader| {
+ header.command = Command::Request;
+ header.operation = Operation::StoreConsumerOffset;
+ header.client = client_id;
+ header.session = 1;
+ header.request = request_id;
+ header.group = IggyNamespace::new(1, 1, 0).inner();
+ header.size = u32::try_from(total).expect("request size fits u32");
+ })
+ }
+ #[compio::test]
+ async fn given_transfer_above_cap_when_file_write_fails_should_refuse_until_retry_succeeds() {
+ let dir = tempfile::tempdir().expect("transfer directory");
+ let consumers = dir.path().join("consumers");
+ let groups = dir.path().join("groups");
+ std::fs::File::create(&groups).expect("block group-file creation");
+ let mut partition = test_partition();
+ partition.set_partition_dir(dir.path().to_string_lossy().into_owned());
+ partition.set_consumer_offsets_max(1);
+ partition.consumer_offsets_path = Some(consumers.to_string_lossy().into_owned());
+ partition.consumer_group_offsets_path = Some(groups.to_string_lossy().into_owned());
+ let wire = crate::state_transfer::ConsumerOffsetsWire {
+ purge_generation: 0,
+ next_offset: 10,
+ consumers: vec![(7, 1), (8, 2)],
+ groups: vec![(9, 3)],
+ dedup: Vec::new(),
+ };
partition
- .on_request(delete_offset_request(client_id, 7, consumer_id), None)
- .await;
-
- {
- let sent = sent_to_clients.borrow();
- assert_eq!(sent.len(), 1, "exactly one deny reply");
- let (reply_client, frame) = &sent[0];
- assert_eq!(*reply_client, client_id);
- let header = bytemuck::checked::try_from_bytes::<ReplyHeader>(
- &frame.as_slice()[..std::mem::size_of::<ReplyHeader>()],
- )
- .expect("deny frame starts with a valid reply header");
- assert_eq!(header.command, Command::Reply);
- assert_eq!(
- header.status,
- IggyError::ConsumerOffsetNotFound(0).as_code()
- );
- assert_eq!(header.op, 0, "a deny commits nothing");
- assert_eq!(header.request, 7);
- assert_eq!(
- header.size as usize,
- std::mem::size_of::<ReplyHeader>(),
- "deny reply body must be empty"
- );
- }
+ .install_state_transfer(&repair_config(), 12, Vec::new(), &wire.encode(), 0)
+ .await
+ .expect_err("incomplete offset state must not advance the commit floor");
+ assert_eq!(partition.consensus.commit_min(), 0);
assert_eq!(
- partition.consensus().pipeline_len(),
- 0,
- "denied delete must not replicate"
+ partition.log.segments().len(),
+ 1,
+ "offset staging failure must preserve the existing segment chain"
);
- assert!(partition.pending_consumer_offset_commits.is_empty());
-
- // Existing offset: the gate passes and the delete enters the pipeline.
- partition.consumer_offsets.pin().insert(
- consumer_id as usize,
- ConsumerOffset::new(ConsumerKind::Consumer, consumer_id, 3, String::new()),
+ assert_eq!(
+ partition.durable_consumer_offset_count(ConsumerKind::Consumer),
+ 0
);
- partition
- .on_request(delete_offset_request(client_id, 8, consumer_id), None)
- .await;
assert_eq!(
- partition.consensus().pipeline_len(),
- 1,
- "existing offset delete must replicate"
+ partition.durable_consumer_offset_count(ConsumerKind::ConsumerGroup),
+ 0
);
- }
-
- #[compio::test]
- async fn on_request_delete_on_stale_backup_replies_transient_before_not_found() {
- let (mut partition, sent_to_clients) = recording_partition_at(1, 3);
+ std::fs::remove_file(&groups).expect("remove file-write fault");
+ let outcome = partition
+ .install_state_transfer(&repair_config(), 12, Vec::new(), &wire.encode(), 0)
+ .await
+ .expect("retry must install accepted state above the local cap");
+ assert!(outcome.purge_generation_recorded);
+ assert_eq!(partition.consensus.commit_min(), 12);
+ assert_eq!(
+ partition.durable_consumer_offset_count(ConsumerKind::Consumer),
+ 2
+ );
+ assert_eq!(
+ partition.durable_consumer_offset_count(ConsumerKind::ConsumerGroup),
+ 1
+ );
+ assert!(
+ partition
+ .reserve_consumer_offset(ConsumerKind::Consumer, 10)
+ .is_err()
+ );
+ assert!(
+ partition
+ .durable_consumer_offsets
+ .covers(ConsumerKind::ConsumerGroup, 9, 3)
+ );
+ assert_eq!(
+ partition
+ .offsets_wire_snapshot_for_test()
+ .expect("durable snapshot"),
+ vec![(7, 1), (8, 2)]
+ );
+ }
+
+ #[compio::test]
+ async fn given_committed_deletes_when_drained_together_should_sync_directory_once_before_replies()
+ {
+ let dir = tempfile::tempdir().unwrap();
+ let (mut partition, sent) = recording_partition_at(0, 3);
+ partition.consumer_offsets_path = Some(dir.path().to_string_lossy().into_owned());
+ partition.consumer_offset_enforce_fsync = true;
+ let mut drained = Vec::new();
+ for id in 1..=2 {
+ partition
+ .persist_consumer_offset_commit(PendingConsumerOffsetCommit::upsert(
+ ConsumerKind::Consumer,
+ id,
+ 0,
+ ))
+ .await
+ .unwrap();
+ partition.stage_consumer_offset_delete(u64::from(id), ConsumerKind::Consumer, id);
+ let header = PrepareHeader {
+ op: u64::from(id),
+ operation: Operation::DeleteConsumerOffset,
+ client: 42,
+ request: u64::from(id),
+ ..Default::default()
+ };
+ drained.push(PipelineEntry::new(header));
+ }
+ partition.consensus.restore_commit_state(0, 2);
+ partition
+ .handle_committed_entries(drained, &repair_config(), true)
+ .await;
+ assert_eq!(partition.offset_dir_sync_count.get(), 1);
+ assert_eq!(partition.consensus.commit_min(), 2);
+ assert_eq!(sent.borrow().len(), 2);
+ assert!(!dir.path().join("1").exists());
+ assert!(!dir.path().join("2").exists());
+ }
+
+ #[compio::test]
+ async fn given_absent_offset_file_when_delete_commits_should_skip_directory_sync() {
+ let dir = tempfile::tempdir().unwrap();
+ let (mut partition, sent) = recording_partition_at(0, 3);
+ partition.consumer_offsets_path =
+ Some(dir.path().join("missing").to_string_lossy().into_owned());
+ partition.stage_consumer_offset_delete(1, ConsumerKind::Consumer, 7);
+ partition.consensus.restore_commit_state(0, 1);
+ let header = PrepareHeader {
+ op: 1,
+ operation: Operation::DeleteConsumerOffset,
+ client: 42,
+ request: 1,
+ ..Default::default()
+ };
+ partition
+ .handle_committed_entries(vec![PipelineEntry::new(header)], &repair_config(), true)
+ .await;
+ assert!(partition.fatal.is_none());
+ assert_eq!(partition.consensus.commit_min(), 1);
+ assert_eq!(partition.offset_dir_sync_count.get(), 0);
+ assert_eq!(sent.borrow().len(), 1);
+ }
+
+ #[compio::test]
+ async fn given_one_offset_directory_sync_failure_when_flushing_should_sync_the_other_directory()
+ {
+ let dir = tempfile::tempdir().unwrap();
+ let invalid = dir.path().join("file");
+ std::fs::write(&invalid, b"not a directory").unwrap();
+ let (mut partition, _) = recording_partition();
+ partition.consumer_offsets_path =
+ Some(invalid.join("child").to_string_lossy().into_owned());
+ partition.consumer_group_offsets_path = Some(dir.path().to_string_lossy().into_owned());
+ partition.mark_consumer_offset_dir_dirty(ConsumerKind::Consumer);
+ partition.mark_consumer_offset_dir_dirty(ConsumerKind::ConsumerGroup);
+ assert_eq!(
+ partition
+ .flush_consumer_offset_directories_for([true, true])
+ .await,
+ [true, false]
+ );
+ assert!(partition.consumer_offset_dirs_dirty[0].get());
+ assert!(!partition.consumer_offset_dirs_dirty[1].get());
+ assert_eq!(partition.offset_dir_sync_count.get(), 1);
+ }
+
+ #[compio::test]
+ async fn given_covered_auto_commit_when_persisting_should_not_sync_directory() {
+ let dir = tempfile::tempdir().unwrap();
+ let (mut partition, _) = recording_partition();
+ partition.consumer_offsets_path = Some(dir.path().to_string_lossy().into_owned());
+ partition.consumer_offset_enforce_fsync = true;
+ let path = dir.path().join("7");
+ persist_offset(path.to_str().unwrap(), 10, true)
+ .await
+ .unwrap();
+ for offset in [5, 7] {
+ partition
+ .persist_consumer_offset_commit(PendingConsumerOffsetCommit::upsert_auto_commit(
+ ConsumerKind::Consumer,
+ 7,
+ offset,
+ ))
+ .await
+ .unwrap();
+ assert!(!partition.consumer_offset_dirs_dirty[0].get());
+ }
+ partition
+ .persist_consumer_offset_commit(PendingConsumerOffsetCommit::upsert_auto_commit(
+ ConsumerKind::Consumer,
+ 7,
+ 11,
+ ))
+ .await
+ .unwrap();
+ assert!(partition.consumer_offset_dirs_dirty[0].get());
+ }
+
+ #[compio::test]
+ async fn given_empty_transfer_frontier_when_incoming_offsets_are_clamped_out_should_remove_old_files()
+ {
+ let dir = tempfile::tempdir().unwrap();
+ let mut partition = test_partition();
+ partition.set_partition_dir(dir.path().to_string_lossy().into_owned());
+ let consumers = dir.path().join("offsets/consumers");
+ let groups = dir.path().join("offsets/groups");
+ partition.consumer_offsets_path = Some(consumers.to_string_lossy().into_owned());
+ partition.consumer_group_offsets_path = Some(groups.to_string_lossy().into_owned());
+ for path in [consumers.join("7"), groups.join("8")] {
+ persist_offset(path.to_str().unwrap(), 5, true)
+ .await
+ .unwrap();
+ }
+ let wire = crate::state_transfer::ConsumerOffsetsWire {
+ purge_generation: 1,
+ next_offset: 0,
+ consumers: vec![(7, 5)],
+ groups: vec![(8, 5)],
+ dedup: Vec::new(),
+ };
+ partition
+ .install_state_transfer(&repair_config(), 1, Vec::new(), &wire.encode(), 0)
+ .await
+ .unwrap();
+ assert!(!consumers.join("7").exists());
+ assert!(!groups.join("8").exists());
+ assert_eq!(
+ partition.durable_consumer_offset_count(ConsumerKind::Consumer),
+ 0
+ );
+ assert_eq!(
+ partition.durable_consumer_offset_count(ConsumerKind::ConsumerGroup),
+ 0
+ );
+ }
+
+ #[compio::test]
+ async fn given_committed_store_when_offset_persist_fails_should_set_fatal_commit() {
+ let dir = tempfile::tempdir().expect("temporary offset parent");
+ let parent = dir.path().join("not-a-directory");
+ std::fs::File::create(&parent).expect("create invalid directory fixture");
+ let (mut partition, _) = recording_partition_at(0, 3);
+ partition.consumer_offsets_path = Some(parent.to_string_lossy().into_owned());
+ partition.stats.increment_messages_count(1);
+ partition
+ .on_request(
+ store_offset_request(42, 1, ConsumerKind::Consumer, 7, 0, AckLevel::Quorum),
+ None,
+ )
+ .await;
+ let header = partition
+ .log
+ .journal()
+ .inner
+ .header_by_op(1)
+ .expect("prepared offset op");
+ partition.consensus.restore_commit_state(0, 1);
+ partition
+ .handle_committed_entries(vec![PipelineEntry::new(header)], &repair_config(), true)
+ .await;
+ let fatal = partition
+ .fatal
+ .as_ref()
+ .expect("committed persistence failure fences partition");
+ assert_eq!(fatal.operation, Operation::StoreConsumerOffset);
+ assert_eq!(fatal.op, 1);
+ assert_eq!(
+ partition.durable_consumer_offset_count(ConsumerKind::Consumer),
+ 0
+ );
+ }
+
+ #[compio::test]
+ async fn given_queued_capacity_denial_when_promoting_should_use_the_slot_for_next_existing_key()
+ {
+ let (mut partition, _) = recording_partition_at(0, 3);
+ partition.set_consumer_offsets_max(1);
+ partition.seed_recovered_consumer_offset(ConsumerKind::Consumer, 7, 0, 0);
+ partition.consumer_offsets.pin().insert(
+ 7,
+ ConsumerOffset::new(ConsumerKind::Consumer, 7, 0, String::new()),
+ );
+ partition.stats.increment_messages_count(1);
+ for (request_id, consumer_id) in [(1, 8), (2, 7)] {
+ assert!(
+ partition
+ .consensus
+ .push_queued_request(consensus::RequestEntry::with_sender(
+ store_offset_request(
+ 42,
+ request_id,
+ ConsumerKind::Consumer,
+ consumer_id,
+ 0,
+ AckLevel::Quorum
+ ),
+ None,
+ ))
+ .is_ok()
+ );
+ }
+ partition.drain_request_queue_into_prepares(1).await;
+ assert_eq!(partition.consensus.pipeline_len(), 1);
+ assert_eq!(
+ partition
+ .pending_consumer_offset_commits
+ .get(&1)
+ .expect("existing update projected")
+ .consumer_id,
+ 7
+ );
+ assert!(partition.consensus.pop_queued_request().is_none());
+ }
+
+ #[compio::test]
+ async fn given_same_view_truncation_when_resynchronizing_should_release_discarded_reservations()
+ {
+ let mut partition = test_partition();
+ journal_prepare(&partition, 1, Operation::StoreConsumerOffset).await;
+ journal_prepare(&partition, 2, Operation::StoreConsumerOffset).await;
+ partition.consensus.sequencer().set_sequence(2);
+ partition.stage_consumer_offset_upsert(1, ConsumerKind::Consumer, 7, 0, false);
+ partition.stage_consumer_offset_upsert(2, ConsumerKind::Consumer, 8, 0, false);
+ partition.truncate_uncommitted_from(2).await.unwrap();
+ partition.resynchronize_consumer_offset_reservations();
+ assert!(partition.pending_consumer_offset_commits.contains_key(&1));
+ assert!(!partition.pending_consumer_offset_commits.contains_key(&2));
+ assert_eq!(
+ partition.occupied_consumer_offset_count(ConsumerKind::Consumer),
+ 1
+ );
+ assert!(!partition.consumer_offset_capacity.is_uncertain());
+ }
+
+ #[compio::test]
+ async fn given_promotion_denial_budget_when_no_more_commits_arrive_should_resume_queued_work() {
+ let (mut partition, sent) = recording_partition_at(0, 3);
+ partition.set_consumer_offsets_max(1);
+ partition.seed_recovered_consumer_offset(ConsumerKind::Consumer, 7, 0, 0);
+ partition.consumer_offsets.pin().insert(
+ 7,
+ ConsumerOffset::new(ConsumerKind::Consumer, 7, 0, String::new()),
+ );
+ partition.stats.increment_messages_count(1);
+ for (request, id) in [8, 9, 10, 11, 12, 7].into_iter().enumerate() {
+ partition
+ .consensus
+ .push_queued_request(consensus::RequestEntry::with_sender(
+ store_offset_request(
+ 42,
+ request as u64 + 1,
+ ConsumerKind::Consumer,
+ id,
+ 0,
+ AckLevel::Quorum,
+ ),
+ None,
+ ))
+ .unwrap();
+ }
+ partition.drain_request_queue_into_prepares(1).await;
+ assert_eq!(sent.borrow().len(), PROMOTION_DENIALS_MAX);
+ assert_eq!(partition.consensus.request_queue_len(), 2);
+ assert_eq!(partition.consensus.pipeline_len(), 0);
+ assert!(partition.queued_requests_ready());
+ partition.resume_queued_requests().await;
+ assert_eq!(partition.consensus.request_queue_len(), 0);
+ assert_eq!(partition.consensus.pipeline_len(), 1);
+ assert!(!partition.queued_requests_ready());
+ }
+
+ #[compio::test]
+ async fn given_covered_store_with_dirty_directory_when_sync_fails_should_fence_its_own_operation()
+ {
+ let dir = tempfile::tempdir().unwrap();
+ let (mut partition, sent) = recording_partition_at(0, 3);
+ partition.consumer_offsets_path = Some(dir.path().to_string_lossy().into_owned());
+ partition.consumer_offset_enforce_fsync = true;
+ let pending =
+ PendingConsumerOffsetCommit::upsert_auto_commit(ConsumerKind::Consumer, 7, 10);
+ partition
+ .persist_consumer_offset_commit(pending)
+ .await
+ .unwrap();
+ partition.apply_consumer_offset_commit(pending);
+ partition.consumer_offset_dir_sync_fault.set(Some(0));
+ partition.stage_consumer_offset_upsert(1, ConsumerKind::Consumer, 7, 5, true);
+ partition.consensus.restore_commit_state(0, 1);
+ let header = PrepareHeader {
+ op: 1,
+ operation: Operation::StoreConsumerOffset,
+ client: 42,
+ request: 1,
+ ..Default::default()
+ };
+ partition
+ .handle_committed_entries(vec![PipelineEntry::new(header)], &repair_config(), true)
+ .await;
+ assert_eq!(partition.fatal.as_ref().unwrap().op, 1);
+ assert_eq!(
+ partition.fatal.as_ref().unwrap().operation,
+ Operation::StoreConsumerOffset
+ );
+ assert_eq!(partition.consensus.commit_min(), 0);
+ assert!(sent.borrow().is_empty());
+ assert!(partition.consumer_offset_dirs_dirty[0].get());
+ }
+
+ #[compio::test]
+ async fn given_repeated_admitted_deletes_when_committed_should_be_idempotent() {
+ let (mut partition, _) = recording_partition();
+ partition.consumer_offsets.pin().insert(
+ 7,
+ ConsumerOffset::new(ConsumerKind::Consumer, 7, 0, String::new()),
+ );
+ partition.seed_recovered_consumer_offset(ConsumerKind::Consumer, 7, 0, 0);
+ for op in 1..=2 {
+ partition.stage_consumer_offset_delete(op, ConsumerKind::Consumer, 7);
+ }
+ for op in 1..=2 {
+ partition
+ .apply_staged_consumer_offset_commit(op)
+ .await
+ .expect("admitted delete converges");
+ }
+ assert_eq!(
+ partition.occupied_consumer_offset_count(ConsumerKind::Consumer),
+ 0
+ );
+ }
+
+ #[compio::test]
+ async fn given_queued_auto_commit_when_view_changes_should_release_its_provisional_slot() {
+ let namespace = IggyNamespace::new(1, 1, 0);
+ let consensus = VsrConsensus::new(
+ TEST_CLUSTER,
+ 0,
+ 3,
+ namespace.inner(),
+ RecordingBus::default(),
+ LocalPipeline::with_capacities(1, 2),
+ );
+ consensus.init();
+ let mut partition: IggyPartition<RecordingBus> = IggyPartition::with_in_memory_storage(
+ Arc::new(PartitionStats::default()),
+ consensus,
+ IggyByteSize::from(1024 * 1024),
+ false,
+ );
+ partition.stats.increment_messages_count(1);
+ partition.set_consumer_offsets_max(2);
+ partition
+ .on_request(
+ store_offset_request(42, 1, ConsumerKind::Consumer, 7, 0, AckLevel::Quorum),
+ None,
+ )
+ .await;
+ let reservation = partition
+ .consumer_offset_capacity
+ .reserve_provisional(8, &partition.durable_consumer_offsets)
+ .unwrap();
+ partition
+ .on_request_with_reservation(
+ store_offset_request(
+ message_bus::AUTO_COMMIT_CLIENT_ID,
+ 1,
+ ConsumerKind::Consumer,
+ 8,
+ 0,
+ AckLevel::Quorum,
+ ),
+ None,
+ Some(reservation),
+ )
+ .await;
+ assert_eq!(
+ partition.occupied_consumer_offset_count(ConsumerKind::Consumer),
+ 2
+ );
+ assert_eq!(partition.queued_auto_commit_reservations.borrow().len(), 1);
+ partition.consensus.set_view(3);
+ partition.resynchronize_consumer_offset_reservations();
+ assert!(
+ partition
+ .queued_auto_commit_reservations
+ .borrow()
+ .is_empty()
+ );
+ assert_eq!(
+ partition.occupied_consumer_offset_count(ConsumerKind::Consumer),
+ 1
+ );
+ }
+
+ #[compio::test]
+ async fn given_auto_commit_guard_when_pump_admits_should_transfer_to_journal_without_reply() {
+ let (mut partition, sent) = recording_partition_at(0, 3);
+ partition.stats.increment_messages_count(1);
+ partition.set_consumer_offsets_max(1);
+ let reservation = partition
+ .consumer_offset_capacity
+ .reserve_provisional(7, &partition.durable_consumer_offsets)
+ .unwrap();
+ partition
+ .on_request_with_reservation(
+ store_offset_request(
+ message_bus::AUTO_COMMIT_CLIENT_ID,
+ 1,
+ ConsumerKind::Consumer,
+ 7,
+ 0,
+ AckLevel::Quorum,
+ ),
+ None,
+ Some(reservation),
+ )
+ .await;
+ assert_eq!(partition.pending_consumer_offset_commits.len(), 1);
+ assert_eq!(
+ partition.occupied_consumer_offset_count(ConsumerKind::Consumer),
+ 1
+ );
+ assert!(sent.borrow().is_empty());
+ partition
+ .apply_staged_consumer_offset_commit(1)
+ .await
+ .unwrap();
+ assert_eq!(
+ partition.durable_consumer_offset_count(ConsumerKind::Consumer),
+ 1
+ );
+ assert!(sent.borrow().is_empty());
+ }
+
+ #[compio::test]
+ async fn given_group_offset_updates_when_key_already_exists_should_keep_reconciliation_idle() {
+ let (mut partition, _) = recording_partition();
+ let epoch = partition.consumer_group_offsets_reconcile_epoch.clone();
+ let initial = epoch.get();
+ partition.stage_consumer_offset_upsert(1, ConsumerKind::ConsumerGroup, 7, 1, true);
+ partition
+ .apply_staged_consumer_offset_commit(1)
+ .await
+ .unwrap();
+ assert!(epoch.get() > initial);
+ let after_create = epoch.get();
+ assert!(
+ partition
+ .dead_consumer_group_offset_ids(|_| true)
+ .is_empty()
+ );
+ assert_eq!(epoch.get(), after_create);
+ partition.stage_consumer_offset_upsert(2, ConsumerKind::ConsumerGroup, 7, 2, true);
+ partition
+ .apply_staged_consumer_offset_commit(2)
+ .await
+ .unwrap();
+ assert_eq!(epoch.get(), after_create);
+ partition.consumer_group_offsets.pin().insert(
+ ConsumerGroupId(8),
+ ConsumerOffset::new(ConsumerKind::ConsumerGroup, 8, 3, String::new()),
+ );
+ partition.stage_consumer_offset_upsert(3, ConsumerKind::ConsumerGroup, 8, 3, true);
+ partition
+ .apply_staged_consumer_offset_commit(3)
+ .await
+ .unwrap();
+ assert!(
+ epoch.get() > after_create,
+ "first durable commit must discover an eager map key"
+ );
+ }
+
+ #[compio::test]
+ async fn given_primary_view_change_when_map_pressure_arrives_should_reclaim_only_unprotected_key()
+ {
+ let (mut partition, _) = recording_partition_at(0, 3);
+ partition.set_consumer_offsets_max(4);
+ partition.stats.increment_messages_count(1);
+ partition.seed_recovered_consumer_offset(ConsumerKind::Consumer, 7, 0, 0);
+ partition
+ .on_request(
+ store_offset_request(42, 1, ConsumerKind::Consumer, 8, 0, AckLevel::Quorum),
+ None,
+ )
+ .await;
+ let held = partition
+ .consumer_offset_capacity
+ .reserve_provisional(9, &partition.durable_consumer_offsets)
+ .unwrap();
+ for id in 7..=10 {
+ partition.consumer_offsets.pin().insert(
+ id as usize,
+ ConsumerOffset::new(ConsumerKind::Consumer, id, 0, String::new()),
+ );
+ }
+ partition.consensus.set_view(3);
+ partition.resynchronize_consumer_offset_reservations();
+ assert_eq!(partition.consumer_offsets.len(), 4);
+ partition.reclaim_phantom_offsets(ConsumerKind::Consumer, 4);
+ assert_eq!(partition.consumer_offsets.len(), 3);
+ assert!(!partition.consumer_offsets.pin().contains_key(&10));
+ for id in 7..=9 {
+ assert!(partition.consumer_offsets.pin().contains_key(&id));
+ }
+ drop(held);
+ }
+
+ #[test]
+ fn given_full_live_map_when_polling_existing_key_should_reclaim_only_for_new_keys() {
+ let (mut partition, _) = recording_partition();
+ partition.set_consumer_offsets_max(2);
+ partition.offset_space.committed_seeded = true;
+ partition.seed_recovered_consumer_offset(ConsumerKind::Consumer, 7, 0, 0);
+ for id in 7..=8 {
+ partition.consumer_offsets.pin().insert(
+ id as usize,
+ ConsumerOffset::new(ConsumerKind::Consumer, id, 0, String::new()),
+ );
+ }
+ let args = PollingArgs::new(iggy_common::PollingStrategy::first(), 1, true);
+ let _ = partition.build_poll_plan(PollingConsumer::Consumer(7, 0), &args, false);
+ assert_eq!(partition.consumer_offsets.len(), 2);
+ let _ = partition.build_poll_plan(PollingConsumer::Consumer(9, 0), &args, false);
+ assert_eq!(partition.consumer_offsets.len(), 1);
+ assert!(partition.consumer_offsets.pin().contains_key(&7));
+ }
+
+ #[compio::test]
+ async fn given_missing_retained_header_when_journal_progresses_should_retry_without_view_change()
+ {
+ let mut partition = test_partition();
+ journal_prepare(&partition, 2, Operation::SendMessages).await;
+ partition.consensus.sequencer().set_sequence(2);
+ partition.consensus.set_view(1);
+ partition.resynchronize_consumer_offset_reservations();
+ assert!(partition.consumer_offset_capacity.is_uncertain());
+ assert!(!partition.offset_reservations_need_resync.get());
+ let failed_scan = partition.offset_reservations_scan_state;
+ for op in 3..=20 {
+ journal_prepare(&partition, op, Operation::SendMessages).await;
+ partition.consensus.sequencer().set_sequence(op);
+ partition.offset_reservations_need_resync.set(true);
+ partition.resynchronize_consumer_offset_reservations();
+ assert_eq!(partition.offset_reservations_scan_state, failed_scan);
+ }
+ partition.retry_consumer_offset_reservations();
+ assert_ne!(partition.offset_reservations_scan_state, failed_scan);
+ assert!(partition.consumer_offset_capacity.is_uncertain());
+ partition.seed_recovered_consumer_offset(ConsumerKind::Consumer, 7, 0, 0);
+ let existing = partition
+ .auto_commit_ctx(PollingConsumer::Consumer(7, 0), true)
+ .unwrap()
+ .apply(0)
+ .unwrap();
+ assert!(partition.auto_commit_admission_ready(&existing));
+ let new = partition
+ .auto_commit_ctx(PollingConsumer::Consumer(8, 0), true)
+ .unwrap()
+ .apply(0)
+ .unwrap();
+ assert!(!partition.auto_commit_admission_ready(&new));
+ partition.log.journal().inner.clear_all();
+ for op in 1..=3 {
+ journal_prepare(&partition, op, Operation::SendMessages).await;
+ }
+ partition.consensus.sequencer().set_sequence(3);
+ partition.resynchronize_consumer_offset_reservations();
+ assert!(partition.consumer_offset_capacity.is_uncertain());
+ partition.retry_consumer_offset_reservations();
+ assert!(!partition.consumer_offset_capacity.is_uncertain());
+ }
+
+ #[compio::test]
+ async fn given_evicted_committed_prefix_when_promoted_should_preserve_staging_without_latching()
+ {
+ let mut partition = test_partition();
+ partition.consensus.restore_commit_state(0, 5000);
+ partition.consensus.sequencer().set_sequence(5001);
+ partition.stage_consumer_offset_upsert(4999, ConsumerKind::Consumer, 7, 0, false);
+ journal_prepare(&partition, 5001, Operation::SendMessages).await;
+ partition.consensus.set_view(1);
+ partition.resynchronize_consumer_offset_reservations();
+ assert!(!partition.consumer_offset_capacity.is_uncertain());
+ assert!(
+ partition
+ .pending_consumer_offset_commits
+ .contains_key(&4999)
+ );
+ assert_eq!(
+ partition.occupied_consumer_offset_count(ConsumerKind::Consumer),
+ 1
+ );
+ }
+
+ #[test]
+ fn given_truncated_journal_when_sequencer_is_ahead_should_not_latch_capacity() {
+ let (mut partition, _) = recording_partition();
+ partition.consensus.sequencer().set_sequence(100);
+ partition.offset_reservations_need_resync.set(true);
+ partition.resynchronize_consumer_offset_reservations();
+ assert!(!partition.consumer_offset_capacity.is_uncertain());
+ assert!(
+ partition
+ .reserve_consumer_offset(ConsumerKind::Consumer, 7)
+ .is_ok()
+ );
+ }
+
+ #[test]
+ fn given_full_backup_phantom_map_when_new_consumer_polls_should_reclaim_without_promotion() {
+ let (mut partition, _) = recording_partition_at(1, 3);
+ partition.set_consumer_offsets_max(2);
+ partition.offset_space.committed_seeded = true;
+ for id in 1..=2 {
+ partition
+ .auto_commit_ctx(PollingConsumer::Consumer(id, 0), true)
+ .unwrap()
+ .apply(0)
+ .unwrap();
+ }
+ let args = PollingArgs::new(iggy_common::PollingStrategy::first(), 1, true);
+ let _ = partition.build_poll_plan(PollingConsumer::Consumer(3, 0), &args, false);
+ assert_eq!(partition.consumer_offsets.len(), 1);
+ let retained_id = *partition.consumer_offsets.pin().keys().next().unwrap();
+ assert!(retained_id == 1 || retained_id == 2);
+ assert!(
+ partition
+ .auto_commit_ctx(PollingConsumer::Consumer(3, 0), true)
+ .unwrap()
+ .apply(0)
+ .is_ok()
+ );
+ assert!(partition.consumer_offsets.pin().contains_key(&retained_id));
+ assert_eq!(partition.consumer_offsets.len(), 2);
+ assert!(!partition.consensus.is_primary());
+ }
+
+ #[compio::test]
+ async fn given_full_offset_table_when_storing_new_id_should_reject_before_replication() {
+ let (mut partition, sent_to_clients) = recording_partition();
+ partition.set_consumer_offsets_max(1);
+ partition.stats.increment_messages_count(1);
+
+ partition
+ .on_request(
+ store_offset_request(42, 1, ConsumerKind::Consumer, 7, 0, AckLevel::NoAck),
+ None,
+ )
+ .await;
+ assert_eq!(
+ partition.durable_consumer_offset_count(ConsumerKind::Consumer),
+ 1
+ );
+
+ partition
+ .on_request(
+ store_offset_request(42, 2, ConsumerKind::Consumer, 8, 0, AckLevel::NoAck),
+ None,
+ )
+ .await;
+ let sent = sent_to_clients.borrow();
+ let denied = sent
+ .iter()
+ .find_map(|(_, frame)| {
+ let header = bytemuck::checked::try_from_bytes::<ReplyHeader>(
+ &frame.as_slice()[..std::mem::size_of::<ReplyHeader>()],
+ )
+ .ok()?;
+ (header.request == 2).then_some(*header)
+ })
+ .expect("capacity denial reply");
+ assert_eq!(denied.status, IggyError::TooManyConsumerOffsets.as_code());
+ assert_eq!(denied.op, 0);
+ assert!(partition.consumer_offsets.pin().get(&8).is_none());
+ assert_eq!(partition.consensus().pipeline_len(), 0);
+ }
+
+ #[compio::test]
+ async fn given_full_offset_table_when_updating_existing_id_should_succeed() {
+ let (mut partition, _) = recording_partition();
+ partition.set_consumer_offsets_max(1);
+ partition.stats.increment_messages_count(1);
+ for request_id in 1..=2 {
+ partition
+ .on_request(
+ store_offset_request(
+ 42,
+ request_id,
+ ConsumerKind::Consumer,
+ 7,
+ 0,
+ AckLevel::NoAck,
+ ),
+ None,
+ )
+ .await;
+ }
+ assert_eq!(
+ partition.durable_consumer_offset_count(ConsumerKind::Consumer),
+ 1
+ );
+ assert_eq!(partition.consumer_offsets.pin().len(), 1);
+ }
+
+ #[compio::test]
+ async fn given_replicated_partition_when_no_ack_offset_is_stored_should_enter_vsr() {
+ let (mut partition, sent_to_clients) = recording_partition_at(0, 3);
+ partition.stats.increment_messages_count(1);
+ partition
+ .on_request(
+ store_offset_request(42, 1, ConsumerKind::Consumer, 7, 0, AckLevel::NoAck),
+ None,
+ )
+ .await;
+
+ assert_eq!(partition.consensus().pipeline_len(), 1);
+ assert_eq!(partition.pending_consumer_offset_commits.len(), 1);
+ assert_eq!(
+ partition.durable_consumer_offset_count(ConsumerKind::Consumer),
+ 0,
+ "durable membership begins at commit"
+ );
+ assert!(sent_to_clients.borrow().is_empty());
+ }
+
+ #[compio::test]
+ async fn given_pending_offset_prepare_when_view_changes_should_rebuild_capacity_from_journal() {
+ let (mut partition, _) = recording_partition_at(0, 3);
+ partition.set_consumer_offsets_max(1);
+ partition.stats.increment_messages_count(1);
+ partition
+ .on_request(
+ store_offset_request(42, 1, ConsumerKind::Consumer, 7, 0, AckLevel::Quorum),
+ None,
+ )
+ .await;
+ assert_eq!(partition.pending_consumer_offset_commits.len(), 1);
+
+ partition.pending_consumer_offset_commits.clear();
+ partition.consumer_offset_capacity.release_reservation(7);
+ partition.consensus.set_view(1);
+ partition.resynchronize_consumer_offset_reservations();
+
+ assert_eq!(partition.pending_consumer_offset_commits.len(), 1);
+ assert!(
+ partition
+ .reserve_consumer_offset(ConsumerKind::Consumer, 8)
+ .is_err(),
+ "the retained prepare must keep the only slot reserved"
+ );
+ }
+
+ #[test]
+ fn given_phantom_and_eager_offsets_when_snapshotting_should_export_committed_durable_value_only()
+ {
+ let (partition, _) = recording_partition();
+ partition.consumer_offsets.pin().insert(
+ 7,
+ ConsumerOffset::new(ConsumerKind::Consumer, 7, 9, String::new()),
+ );
+ partition.consumer_offsets.pin().insert(
+ 8,
+ ConsumerOffset::new(ConsumerKind::Consumer, 8, 11, String::new()),
+ );
+ partition.seed_recovered_consumer_offset(ConsumerKind::Consumer, 7, 5, 5);
+
+ assert_eq!(
+ partition
+ .offsets_wire_snapshot_for_test()
+ .expect("durable key exists in live map"),
+ vec![(7, 5)],
+ "the eager value and the follower-local phantom must not enter the artifact"
+ );
+ }
+
+ #[test]
+ fn given_durable_offset_missing_from_live_map_when_snapshotting_should_refuse() {
+ let (partition, _) = recording_partition();
+ partition.seed_recovered_consumer_offset(ConsumerKind::Consumer, 7, 5, 5);
+ assert!(matches!(
+ partition.offsets_wire_snapshot_for_test(),
+ Err(
+ crate::state_transfer::PartitionTransferUnavailable::ConsumerOffsetStateInconsistent {
+ kind: ConsumerKind::Consumer,
+ consumer_id: 7,
+ }
+ )
+ ));
+ }
+
+ /// Deleting a consumer offset that was never stored must answer with a
+ /// typed deny reply (empty body, `status` = `ConsumerOffsetNotFound`,
+ /// `op` 0) before consensus: nothing may enter the pipeline, and an
+ /// awaited client write must fail fast instead of waiting out its reply
+ /// timeout. Once the offset exists, the same request must pass the gate
+ /// into the pipeline without a deny.
+ #[compio::test]
+ async fn on_request_delete_of_missing_offset_replies_typed_deny() {
+ let (mut partition, sent_to_clients) = recording_partition();
+ let client_id: u128 = 42;
+ let consumer_id: u32 = 5;
+
+ partition
+ .on_request(delete_offset_request(client_id, 7, consumer_id), None)
+ .await;
+
+ {
+ let sent = sent_to_clients.borrow();
+ assert_eq!(sent.len(), 1, "exactly one deny reply");
+ let (reply_client, frame) = &sent[0];
+ assert_eq!(*reply_client, client_id);
+ let header = bytemuck::checked::try_from_bytes::<ReplyHeader>(
+ &frame.as_slice()[..std::mem::size_of::<ReplyHeader>()],
+ )
+ .expect("deny frame starts with a valid reply header");
+ assert_eq!(header.command, Command::Reply);
+ assert_eq!(
+ header.status,
+ IggyError::ConsumerOffsetNotFound(0).as_code()
+ );
+ assert_eq!(header.op, 0, "a deny commits nothing");
+ assert_eq!(header.request, 7);
+ assert_eq!(
+ header.size as usize,
+ std::mem::size_of::<ReplyHeader>(),
+ "deny reply body must be empty"
+ );
+ }
+ assert_eq!(
+ partition.consensus().pipeline_len(),
+ 0,
+ "denied delete must not replicate"
+ );
+ assert!(partition.pending_consumer_offset_commits.is_empty());
+
+ // Existing offset: the gate passes and the delete enters the pipeline.
+ partition.consumer_offsets.pin().insert(
+ consumer_id as usize,
+ ConsumerOffset::new(ConsumerKind::Consumer, consumer_id, 3, String::new()),
+ );
+ partition
+ .on_request(delete_offset_request(client_id, 8, consumer_id), None)
+ .await;
+ assert_eq!(
+ partition.consensus().pipeline_len(),
+ 1,
+ "existing offset delete must replicate"
+ );
+ }
+
+ #[compio::test]
+ async fn on_request_delete_on_stale_backup_replies_transient_before_not_found() {
+ let (mut partition, sent_to_clients) = recording_partition_at(1, 3);
let client_id = 42;
partition
@@ -7891,11 +9655,15 @@ mod tests {
);
assert!(
- partition.is_auto_commit_offset_covered(ConsumerKind::Consumer, consumer_id, 114),
+ partition
+ .durable_consumer_offsets
+ .covers(ConsumerKind::Consumer, consumer_id, 114),
"committed high-water covers the persisted offset"
);
assert!(
- !partition.is_auto_commit_offset_covered(ConsumerKind::Consumer, consumer_id, 115),
+ !partition
+ .durable_consumer_offsets
+ .covers(ConsumerKind::Consumer, consumer_id, 115),
"an advancing offset is not covered and must submit"
);
@@ -7910,7 +9678,9 @@ mod tests {
.expect("explicit store persist 109");
assert_eq!(read_disk(&path), 109, "explicit store may rewind the file");
assert!(
- !partition.is_auto_commit_offset_covered(ConsumerKind::Consumer, consumer_id, 114),
+ !partition
+ .durable_consumer_offsets
+ .covers(ConsumerKind::Consumer, consumer_id, 114),
"explicit rewind lowers the high-water so a later auto-commit may re-advance"
);
@@ -7958,7 +9728,9 @@ mod tests {
.await
.expect("seed offset file");
assert!(
- !partition.is_auto_commit_offset_covered(ConsumerKind::Consumer, consumer_id, 1),
+ !partition
+ .durable_consumer_offsets
+ .covers(ConsumerKind::Consumer, consumer_id, 1),
"a cold key is never covered; the first submit must go through"
);
@@ -7976,7 +9748,9 @@ mod tests {
"cold-key fold must not rewind the pre-existing on-disk value"
);
assert!(
- partition.is_auto_commit_offset_covered(ConsumerKind::Consumer, consumer_id, 114),
+ partition
+ .durable_consumer_offsets
+ .covers(ConsumerKind::Consumer, consumer_id, 114),
"tracker warms with the on-disk value, not the trailing op offset"
);
@@ -7989,7 +9763,9 @@ mod tests {
.expect("delete persisted offset");
assert!(!std::path::Path::new(&path).exists(), "file unlinked");
assert!(
- !partition.is_auto_commit_offset_covered(ConsumerKind::Consumer, consumer_id, 1),
+ !partition
+ .durable_consumer_offsets
+ .covers(ConsumerKind::Consumer, consumer_id, 1),
"delete drops the tracker entry with the file"
);
@@ -8006,49 +9782,369 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
- /// `reclaim_dead_group_offsets` must drop exactly the not-`is_live` groups
- /// from the in-memory map and hand back their owned persisted-file paths,
- /// leaving live groups untouched. The returned `Vec<String>` is what the
- /// reconciler unlinks off-borrow, so it carries no partition reference.
- ///
- /// Scope: the synchronous removal contract the off-borrow split relies on.
- /// The cross-task interleave it enables -- a pump mutating the partitions vec
- /// while a sibling task is parked mid-await -- is covered on the simulator's
- /// deterministic executor, against the debug borrow tripwire, by
- /// `simulator::tests::shell_detects_partition_borrow_held_across_await`
- /// (`swap_remove`) and
- /// `shell_detects_partition_borrow_held_across_a_pump_realloc` (a growing
- /// `push`, which relocates every element).
#[compio::test]
- async fn reclaim_dead_group_offsets_drops_dead_keeps_live() {
- let mut partition = test_partition();
- let group_offsets_path = "/iggy-test-cg-offsets".to_owned();
- partition.consumer_group_offsets_path = Some(group_offsets_path.clone());
+ async fn given_dead_group_when_reclaimed_should_keep_capacity_until_replicated_delete() {
+ let (mut partition, _) = recording_partition();
+ partition.consumer_group_offsets.pin().insert(
+ ConsumerGroupId(7),
+ ConsumerOffset::new(ConsumerKind::ConsumerGroup, 7, 11, String::new()),
+ );
+ partition.seed_recovered_consumer_offset(ConsumerKind::ConsumerGroup, 7, 11, 11);
+ assert_eq!(partition.dead_consumer_group_offset_ids(|_| false), vec![7]);
+ assert_eq!(partition.consumer_group_offset_ids(), vec![7]);
+ assert_eq!(
+ partition.occupied_consumer_offset_count(ConsumerKind::ConsumerGroup),
+ 1
+ );
+ partition.stage_consumer_offset_delete(1, ConsumerKind::ConsumerGroup, 7);
+ partition
+ .apply_staged_consumer_offset_commit(1)
+ .await
+ .expect("delete commits");
+ assert_eq!(
+ partition.occupied_consumer_offset_count(ConsumerKind::ConsumerGroup),
+ 0
+ );
+ assert!(partition.consumer_group_offset_ids().is_empty());
+ }
- let dead: u32 = 1;
- let live: u32 = 2;
+ #[compio::test]
+ async fn given_known_stranded_group_file_when_reconciling_should_not_submit_delete_loop() {
+ let dir = tempfile::tempdir().unwrap();
+ let group_dir = dir.path().join("groups");
+ std::fs::create_dir_all(group_dir.join("7")).unwrap();
+ let (mut partition, _) = recording_partition();
+ partition.consumer_group_offsets_path = Some(group_dir.to_string_lossy().into_owned());
+ // In the live map, so the reclaim walk actually meets the key and the
+ // stranded filter is what keeps it out of the delete log.
+ partition.seed_recovered_consumer_offset(ConsumerKind::ConsumerGroup, 7, 11, 11);
partition.consumer_group_offsets.pin().insert(
- ConsumerGroupId(dead as usize),
- ConsumerOffset::new(ConsumerKind::ConsumerGroup, dead, 7, String::new()),
+ ConsumerGroupId(7),
+ ConsumerOffset::new(ConsumerKind::ConsumerGroup, 7, 11, String::new()),
+ );
+ partition.consumer_group_offset_capacity.record_stranded(7);
+ assert!(partition.consumer_group_offset_capacity.is_stranded(7));
+ assert_eq!(
+ partition.dead_consumer_group_offset_ids(|_| true),
+ Vec::<u32>::new()
+ );
+ assert!(
+ partition
+ .dead_consumer_group_offset_ids(|_| false)
+ .is_empty(),
+ "automatic cleanup must not resubmit a known failed unlink"
+ );
+ partition.consumer_group_offset_capacity.clear_stranded(7);
+ assert_eq!(
+ partition.dead_consumer_group_offset_ids(|_| false),
+ vec![7],
+ "the same dead key is reclaimed once it is no longer stranded"
+ );
+ assert!(
+ partition
+ .offsets_wire_snapshot_for_test()
+ .unwrap()
+ .is_empty()
+ );
+ }
+
+ #[test]
+ fn given_local_only_key_when_replicated_should_require_durable_membership_to_delete() {
+ let (partition, _) = recording_partition_at(0, 3);
+ partition.seed_stranded_consumer_offset(ConsumerKind::ConsumerGroup, 7);
+ assert!(
+ partition
+ .ensure_consumer_offset_exists(ConsumerKind::ConsumerGroup, 7)
+ .is_err(),
+ "a stranded file is not a replicated key"
);
partition.consumer_group_offsets.pin().insert(
- ConsumerGroupId(live as usize),
- ConsumerOffset::new(ConsumerKind::ConsumerGroup, live, 9, String::new()),
+ ConsumerGroupId(8),
+ ConsumerOffset::new(ConsumerKind::ConsumerGroup, 8, 0, String::new()),
+ );
+ assert!(
+ partition
+ .ensure_consumer_offset_exists(ConsumerKind::ConsumerGroup, 8)
+ .is_err(),
+ "a local poll cursor must not produce a missing-key delete on an older peer"
+ );
+ partition
+ .durable_consumer_offsets
+ .record_explicit(ConsumerKind::ConsumerGroup, 9, 0, 0);
+ assert!(
+ partition
+ .ensure_consumer_offset_exists(ConsumerKind::ConsumerGroup, 9)
+ .is_ok()
);
+ assert!(
+ partition
+ .ensure_consumer_offset_exists(ConsumerKind::ConsumerGroup, 10)
+ .is_err(),
+ "an unknown key still answers not found"
+ );
+
+ let (single, _) = recording_partition();
+ single.seed_stranded_consumer_offset(ConsumerKind::ConsumerGroup, 7);
+ assert!(
+ single
+ .ensure_consumer_offset_exists(ConsumerKind::ConsumerGroup, 7)
+ .is_ok()
+ );
+ }
- let paths = partition.reclaim_dead_group_offsets(|group_id| group_id == u64::from(live));
+ #[compio::test]
+ async fn given_committed_delete_when_unlink_fails_should_preserve_state_and_report_failure() {
+ let dir = tempfile::tempdir().unwrap();
+ let group_dir = dir.path().join("groups");
+ std::fs::create_dir_all(group_dir.join("7")).unwrap();
+ let (mut partition, _) = recording_partition();
+ partition.consumer_group_offsets_path = Some(group_dir.to_string_lossy().into_owned());
+ partition.consumer_group_offsets.pin().insert(
+ ConsumerGroupId(7),
+ ConsumerOffset::new(ConsumerKind::ConsumerGroup, 7, 11, String::new()),
+ );
+ partition.seed_recovered_consumer_offset(ConsumerKind::ConsumerGroup, 7, 11, 11);
+ partition.stage_consumer_offset_delete(1, ConsumerKind::ConsumerGroup, 7);
+ // A failed file mutation cannot become a successful logical delete.
+ assert!(
+ partition
+ .apply_staged_consumer_offset_commit(1)
+ .await
+ .is_err()
+ );
+ assert_eq!(partition.consumer_group_offset_ids(), vec![7]);
assert_eq!(
- paths,
- vec![format!("{group_offsets_path}/{dead}")],
- "only the dead group's persisted path is returned for unlink"
+ partition.durable_consumer_offset_count(ConsumerKind::ConsumerGroup),
+ 1
+ );
+ assert!(partition.pending_consumer_offset_commits.contains_key(&1));
+ assert!(partition.consumer_group_offset_capacity.is_stranded(7));
+ assert!(partition.fatal.is_none());
+ }
+
+ #[compio::test]
+ async fn given_no_ack_store_when_unrelated_dirty_directory_is_gone_should_succeed() {
+ let dir = tempfile::tempdir().unwrap();
+ let (mut partition, sent) = recording_partition();
+ partition.consumer_offsets_path =
+ Some(dir.path().join("consumers").to_string_lossy().into_owned());
+ partition.consumer_group_offsets_path = Some(
+ dir.path()
+ .join("missing-groups")
+ .to_string_lossy()
+ .into_owned(),
+ );
+ partition.consumer_offset_dirs_dirty[1].set(true);
+ partition.stats.increment_messages_count(1);
+
+ partition
+ .on_request(
+ store_offset_request(42, 1, ConsumerKind::Consumer, 7, 0, AckLevel::NoAck),
+ None,
+ )
+ .await;
+
+ assert!(partition.consumer_offsets.pin().contains_key(&7));
+ assert!(
+ partition
+ .durable_consumer_offsets
+ .covers(ConsumerKind::Consumer, 7, 0)
+ );
+ let reply = sent.borrow();
+ let header = reply
+ .first()
+ .and_then(|(_, message)| {
+ bytemuck::checked::try_from_bytes::<ReplyHeader>(
+ &message.as_slice()[..size_of::<ReplyHeader>()],
+ )
+ .ok()
+ })
+ .expect("success reply");
+ assert_eq!(header.status, 0);
+ }
+
+ #[compio::test]
+ async fn given_no_ack_store_when_its_directory_sync_fails_should_report_failure_and_stay_dirty()
+ {
+ let dir = tempfile::tempdir().unwrap();
+ let (mut partition, sent) = recording_partition();
+ partition.consumer_offsets_path =
+ Some(dir.path().join("consumers").to_string_lossy().into_owned());
+ partition.consumer_group_offsets_path =
+ Some(dir.path().join("groups").to_string_lossy().into_owned());
+ partition.consumer_offset_enforce_fsync = true;
+ // Visibility alone cannot satisfy the explicitly requested barrier.
+ partition.consumer_offset_dir_sync_fault.set(Some(0));
+ partition.stats.increment_messages_count(1);
+
+ partition
+ .on_request(
+ store_offset_request(42, 1, ConsumerKind::Consumer, 7, 0, AckLevel::NoAck),
+ None,
+ )
+ .await;
+
+ assert!(partition.consumer_offsets.pin().contains_key(&7));
+ assert!(
+ partition
+ .durable_consumer_offsets
+ .covers(ConsumerKind::Consumer, 7, 0)
+ );
+ let reply = sent.borrow();
+ let header = reply
+ .first()
+ .and_then(|(_, message)| {
+ bytemuck::checked::try_from_bytes::<ReplyHeader>(
+ &message.as_slice()[..size_of::<ReplyHeader>()],
+ )
+ .ok()
+ })
+ .expect("failure reply");
+ assert_eq!(header.status, IggyError::CannotSyncFile.as_code());
+ assert!(
+ partition.consumer_offset_dirs_dirty[0].get(),
+ "the failed directory keeps its dirt for the next walk"
+ );
+ }
+
+ #[compio::test]
+ async fn given_stale_dirt_on_the_other_kind_when_its_sync_fails_should_not_fence_the_walk() {
+ let dir = tempfile::tempdir().unwrap();
+ let (mut partition, sent) = recording_partition_at(0, 3);
+ partition.consumer_offsets_path =
+ Some(dir.path().join("consumers").to_string_lossy().into_owned());
+ partition.consumer_group_offsets_path =
+ Some(dir.path().join("groups").to_string_lossy().into_owned());
+ partition.consumer_offset_enforce_fsync = true;
+ // Dirt a NoAck request left on the groups directory, whose sync now
+ // fails. This walk writes consumer offsets only.
+ partition.consumer_offset_dirs_dirty[1].set(true);
+ partition.consumer_offset_dir_sync_fault.set(Some(1));
+ partition
+ .persist_consumer_offset_commit(PendingConsumerOffsetCommit::upsert(
+ ConsumerKind::Consumer,
+ 1,
+ 0,
+ ))
+ .await
+ .unwrap();
+ partition.stage_consumer_offset_delete(1, ConsumerKind::Consumer, 1);
+ let header = PrepareHeader {
+ op: 1,
+ operation: Operation::DeleteConsumerOffset,
+ client: 42,
+ request: 1,
+ ..Default::default()
+ };
+ partition.consensus.restore_commit_state(0, 1);
+ partition
+ .handle_committed_entries(vec![PipelineEntry::new(header)], &repair_config(), true)
+ .await;
+ assert!(
+ partition.fatal.is_none(),
+ "a failure on a kind this walk did not write must not fence it"
+ );
+ assert_eq!(partition.consensus.commit_min(), 1);
+ assert_eq!(sent.borrow().len(), 1);
+ assert!(!partition.consumer_offset_dirs_dirty[0].get());
+ assert!(partition.consumer_offset_dirs_dirty[1].get());
+
+ // The same failure on the kind the walk wrote fences it.
+ partition.consumer_offset_dir_sync_fault.set(Some(0));
+ partition
+ .persist_consumer_offset_commit(PendingConsumerOffsetCommit::upsert(
+ ConsumerKind::Consumer,
+ 2,
+ 0,
+ ))
+ .await
+ .unwrap();
+ partition.stage_consumer_offset_delete(2, ConsumerKind::Consumer, 2);
+ let header = PrepareHeader {
+ op: 2,
+ operation: Operation::DeleteConsumerOffset,
+ client: 42,
+ request: 2,
+ ..Default::default()
+ };
+ partition.consensus.advance_commit_max(2);
+ partition
+ .handle_committed_entries(vec![PipelineEntry::new(header)], &repair_config(), true)
+ .await;
+ assert!(
+ partition.fatal.is_some(),
+ "a sync failure on a written kind fences the walk"
+ );
+ assert_eq!(partition.consensus.commit_min(), 1);
+ }
+
+ #[compio::test]
+ async fn given_no_ack_delete_sync_failure_when_retried_should_retry_barrier_and_succeed() {
+ let dir = tempfile::tempdir().unwrap();
+ let (mut partition, sent) = recording_partition();
+ partition.consumer_offsets_path = Some(dir.path().to_string_lossy().into_owned());
+ partition.consumer_offset_enforce_fsync = true;
+ let stored = PendingConsumerOffsetCommit::upsert(ConsumerKind::Consumer, 7, 0);
+ partition
+ .persist_consumer_offset_commit(stored)
+ .await
+ .unwrap();
+ partition.apply_consumer_offset_commit(stored);
+ partition.consumer_offset_dir_sync_fault.set(Some(0));
+ partition
+ .apply_consumer_offset_no_ack(
+ Box::new(*delete_offset_request(42, 1, 7).header()),
+ ConsumerKind::Consumer,
+ 7,
+ None,
+ None,
+ )
+ .await;
+ let status = |index: usize| {
+ let frames = sent.borrow();
+ let bytes = frames[index].1.as_slice();
+ let start = std::mem::offset_of!(ReplyHeader, status);
+ u32::from_le_bytes(bytes[start..start + 4].try_into().unwrap())
+ };
+ assert_eq!(status(0), IggyError::CannotSyncFile.as_code());
+ assert!(!dir.path().join("7").exists());
+ assert!(
+ partition
+ .ensure_consumer_offset_exists(ConsumerKind::Consumer, 7)
+ .is_ok()
+ );
+ partition.consumer_offset_dir_sync_fault.set(None);
+ partition
+ .apply_consumer_offset_no_ack(
+ Box::new(*delete_offset_request(42, 2, 7).header()),
+ ConsumerKind::Consumer,
+ 7,
+ None,
+ None,
+ )
+ .await;
+ assert_eq!(status(1), 0);
+ assert!(!partition.consumer_offset_dirs_dirty[0].get());
+ assert!(!partition.consumer_offset_capacity.is_stranded(7));
+ }
+
+ #[test]
+ fn given_follower_when_group_is_deleted_should_wait_for_ordered_reclamation() {
+ let (partition, _) = recording_partition_at(1, 3);
+ partition.consumer_group_offsets.pin().insert(
+ ConsumerGroupId(7),
+ ConsumerOffset::new(ConsumerKind::ConsumerGroup, 7, 11, String::new()),
+ );
+ partition.seed_recovered_consumer_offset(ConsumerKind::ConsumerGroup, 7, 11, 11);
+ assert!(
+ partition
+ .dead_consumer_group_offset_ids(|_| false)
+ .is_empty()
);
- let mut remaining = partition.consumer_group_offset_ids();
- remaining.sort_unstable();
assert_eq!(
- remaining,
- vec![u64::from(live)],
- "dead group removed in-memory; live group retained"
+ partition.durable_consumer_offset_count(ConsumerKind::ConsumerGroup),
+ 1
);
}
@@ -8853,6 +10949,7 @@ mod tests {
messages_required_to_save: 1,
size_of_messages_required_to_save: IggyByteSize::from(1024 * 1024),
enforce_fsync: false,
+ consumer_offset_enforce_fsync: false,
validate_checksum: true,
segment_size: IggyByteSize::from(1024 * 1024),
preallocate_segments: false,
@@ -9820,6 +11917,72 @@ mod tests {
);
}
+ #[compio::test]
+ async fn given_flushed_repair_ahead_of_commit_min_when_replayed_should_persist_only_new_batches()
+ {
+ let dir = tempfile::tempdir().expect("temp dir");
+ let log_path = dir.path().join("segment.log");
+ let index_path = dir.path().join("segment.index");
+ let mut fixture = PersistFixture::new(
+ log_path.to_str().expect("utf-8 path"),
+ index_path.to_str().expect("utf-8 path"),
+ )
+ .await;
+ let partition = &mut fixture.partition;
+ partition.log.journal().inner.set_repair_retention(true);
+ partition.repair = Some(armed_session(4, 0, None));
+ let prepares: Vec<_> = (1..=4)
+ .map(|op| repaired_send_prepare(op, 0, u128::from(op)).into_frozen())
+ .collect();
+ let replay = |op: usize| {
+ let bytes = prepares[op - 1].as_slice();
+ let mut message = Message::<PrepareHeader>::new(bytes.len());
+ message.as_mut_slice().copy_from_slice(bytes);
+ message
+ };
+ for op in 1..=3 {
+ partition.apply_repaired_prepare(replay(op)).await;
+ }
+ partition.consensus().advance_commit_max(3);
+ partition
+ .flush_committed_messages(&repair_config())
+ .await
+ .expect("flush before the commit walk catches up");
+ assert_eq!(partition.consensus().commit_min(), 0);
+ assert_eq!(partition.recovered_durable_offset, None);
+ let original = std::fs::read(&log_path).expect("read initial segment");
+ let original_index = std::fs::read(&index_path).expect("read initial index");
+
+ for op in 2..=3 {
+ partition.apply_repaired_prepare(replay(op)).await;
+ }
+ partition
+ .flush_committed_messages(&repair_config())
+ .await
+ .expect("flush replayed batches");
+ assert_eq!(std::fs::read(&log_path).unwrap(), original);
+ assert_eq!(std::fs::read(&index_path).unwrap(), original_index);
+
+ let next = replay(4);
+ let mut expected = original;
+ expected.extend_from_slice(&next.as_slice()[size_of::<PrepareHeader>()..]);
+ partition.apply_repaired_prepare(next).await;
+ partition.consensus().advance_commit_max(4);
+ partition
+ .flush_committed_messages(&repair_config())
+ .await
+ .expect("flush the new batch");
+ assert_eq!(std::fs::read(&log_path).unwrap(), expected);
+ // The commit walk needs resident headers after the earlier flush.
+ for op in 1..=4 {
+ partition.apply_repaired_prepare(replay(op)).await;
+ }
+ partition.commit_journal(&repair_config()).await;
+ assert_eq!(partition.consensus().commit_min(), 4);
+ assert!(partition.fatal.is_none());
+ assert_eq!(std::fs::read(&log_path).unwrap(), expected);
+ }
+
#[cfg(target_os = "linux")]
#[compio::test]
async fn given_a_persist_failure_on_a_committed_op_should_fence_the_partition_not_panic() {
diff --git a/core/partitions/src/iggy_partitions.rs b/core/partitions/src/iggy_partitions.rs
index 2a2ee6e1e..d71819efd 100644
--- a/core/partitions/src/iggy_partitions.rs
+++ b/core/partitions/src/iggy_partitions.rs
@@ -34,10 +34,10 @@ use message_bus::MessageBus;
use server_common::Message;
use server_common::send_messages::{ChecksumMode, convert_request_message, encrypt_batch_request};
use server_common::sharding::{IggyNamespace, LocalIdx, ShardId};
-#[cfg(debug_assertions)]
use std::cell::Cell;
use std::cell::{RefCell, UnsafeCell};
use std::collections::BTreeMap;
+use std::rc::Rc;
use tracing::warn;
/// RAII counter for live [`IggyPartitions::with_partition`] borrows. The
@@ -108,6 +108,7 @@ where
/// per-shard runtime is single-threaded, so runtime borrow checks
/// suffice; callers must not hold a borrow across `.await`.
tombstoned: RefCell<AHashSet<IggyNamespace>>,
+ consumer_group_offsets_reconcile_epoch: Rc<Cell<u64>>,
/// Debug-only tripwire: counts live [`Self::with_partition`] borrows so
/// `insert` / `remove` can assert the partitions vec is never mutated
/// while a sanctioned non-pump read borrow is outstanding. Cannot fire for
@@ -131,6 +132,7 @@ where
partitions: UnsafeCell::new(Vec::new()),
namespace_to_local: UnsafeCell::new(BTreeMap::new()),
tombstoned: RefCell::new(AHashSet::new()),
+ consumer_group_offsets_reconcile_epoch: Rc::new(Cell::new(0)),
#[cfg(debug_assertions)]
borrow_active: Cell::new(0),
}
@@ -145,6 +147,7 @@ where
// BTreeMap has no capacity hint; the Vec above absorbs the sizing.
namespace_to_local: UnsafeCell::new(BTreeMap::new()),
tombstoned: RefCell::new(AHashSet::new()),
+ consumer_group_offsets_reconcile_epoch: Rc::new(Cell::new(0)),
#[cfg(debug_assertions)]
borrow_active: Cell::new(0),
}
@@ -224,7 +227,11 @@ where
/// [`Self::with_partition`]; the `&mut` path above is uncounted (it is
/// pump-only, so it cannot alias this same-task mutation).
#[doc(hidden)]
- pub fn insert(&self, namespace: IggyNamespace, partition: IggyPartition<B, SB>) -> LocalIdx {
+ pub fn insert(
+ &self,
+ namespace: IggyNamespace,
+ mut partition: IggyPartition<B, SB>,
+ ) -> LocalIdx {
#[cfg(debug_assertions)]
debug_assert_eq!(
self.borrow_active.get(),
@@ -232,6 +239,9 @@ where
"IggyPartitions::insert while a with_partition borrow is live"
);
partition.publish_current_offset();
+ partition.set_consumer_group_offsets_reconcile_epoch(Rc::clone(
+ &self.consumer_group_offsets_reconcile_epoch,
+ ));
// Safety: pump-only invariant, caller responsibility.
let partitions = unsafe { &mut *self.partitions.get() };
let local_idx = LocalIdx::new(partitions.len());
@@ -240,6 +250,18 @@ where
local_idx
}
+ pub fn consumer_group_offsets_reconcile_epoch(&self) -> u64 {
+ self.consumer_group_offsets_reconcile_epoch.get()
+ }
+
+ pub fn note_consumer_group_offsets_reconcile_needed(&self) {
+ self.consumer_group_offsets_reconcile_epoch.set(
+ self.consumer_group_offsets_reconcile_epoch
+ .get()
+ .wrapping_add(1),
+ );
+ }
+
/// Check if a namespace exists.
pub fn contains(&self, namespace: &IggyNamespace) -> bool {
self.namespace_map().contains_key(namespace)
@@ -628,6 +650,31 @@ where
let _ = waiter.send(build_deny_reply_from_request_header(header, status));
}
}
+
+ pub async fn on_auto_commit_request(
+ &self,
+ request: Message<RoutedRequestHeader>,
+ reservation: crate::AutoCommitReservation,
+ ) {
+ let namespace = IggyNamespace::from_raw(request.header().group);
+ if self.is_tombstoned(&namespace) {
+ tracing::debug!(
+ namespace_raw = namespace.inner(),
+ "dropping auto-commit for tombstoned partition"
+ );
+ return;
+ }
+ if let Some(partition) = self.get_mut_by_ns(&namespace) {
+ partition
+ .on_request_with_reservation(request, None, Some(reservation))
+ .await;
+ } else {
+ tracing::debug!(
+ namespace_raw = namespace.inner(),
+ "dropping auto-commit for missing partition"
+ );
+ }
+ }
}
impl<B, SB> Plane<VsrConsensus<B>> for IggyPartitions<B, SB>
diff --git a/core/partitions/src/lib.rs b/core/partitions/src/lib.rs
index 059c795a0..36be8081b 100644
--- a/core/partitions/src/lib.rs
+++ b/core/partitions/src/lib.rs
@@ -17,6 +17,7 @@
#![allow(clippy::future_not_send)]
+mod consumer_offset_capacity;
mod iggy_index;
mod iggy_index_reader;
mod iggy_index_writer;
@@ -32,6 +33,7 @@ pub mod segment_anchor;
pub mod state_transfer;
mod types;
+pub use consumer_offset_capacity::{AutoCommitReservation, ConsumerOffsetCapacityError};
use iggy_binary_protocol::PrepareHeader;
use iggy_common::IggyError;
pub use iggy_index::IggyIndex;
@@ -54,12 +56,16 @@ pub use journal::{EVICTED_RING_BYTES_MAX, EVICTED_RING_CAPACITY};
/// Both consumers -- the fallback in [`IggyPartition`] and the `[partition]`
/// config default boot installs -- already depend on this crate.
pub const DEFAULT_OFFSET_RESERVATION_LEASE: u32 = 64 * 1024;
+
+/// Shipped per-kind durable consumer-offset limit for one partition.
+pub const DEFAULT_CONSUMER_OFFSETS_MAX: usize = 4096;
pub use messages_writer::MessagesWriter;
pub use offset_storage::delete_persisted_offset;
pub use poll_plan::{AutoCommitApplied, PollPlan};
pub use segment::Segment;
use server_common::Message;
pub use server_common::send_messages::{IggyMessage, IggyMessageHeader, IggyMessages};
+pub use state_transfer::CONSUMER_OFFSETS_ENTRIES_MAX;
pub use types::{
AppendResult, COMMIT_WALK_OPS_MAX, FatalCommit, Fragment, PartitionOffsets,
PartitionPathLayout, PartitionsConfig, PollFragments, PollQueryResult, PollingArgs,
@@ -89,6 +95,8 @@ pub struct RetainedPartitionState {
/// Whether that incarnation ever stamped an offset, i.e. whether the two
/// numbers above describe an offset space at all.
pub offset_space_used: bool,
+ pub consumer_offsets: Vec<(u32, u64)>,
+ pub consumer_group_offsets: Vec<(u32, u64)>,
}
/// Partition-level data plane operations.
@@ -101,17 +109,6 @@ pub trait Partition {
message: Message<PrepareHeader>,
) -> impl Future<Output = Result<AppendResult, IggyError>>;
- /// # Errors
- /// Returns `IggyError::FeatureUnavailable` by default.
- fn store_consumer_offset(
- &self,
- consumer: PollingConsumer,
- offset: u64,
- ) -> Result<(), IggyError> {
- let _ = (consumer, offset);
- Err(IggyError::FeatureUnavailable)
- }
-
fn get_consumer_offset(&self, consumer: PollingConsumer) -> Option<u64> {
let _ = consumer;
None
diff --git a/core/partitions/src/offset_storage.rs b/core/partitions/src/offset_storage.rs
index 618f987eb..f750b1345 100644
--- a/core/partitions/src/offset_storage.rs
+++ b/core/partitions/src/offset_storage.rs
@@ -16,7 +16,7 @@
// under the License.
use compio::{
- fs::{OpenOptions, create_dir_all, remove_file},
+ fs::{OpenOptions, create_dir_all, remove_file, rename},
io::{AsyncReadAt, AsyncReadAtExt, AsyncWriteAtExt},
};
use iggy_common::{IggyError, calculate_checksum};
@@ -39,6 +39,9 @@ pub const OFFSET_RECORD_SIZE: usize = OFFSET_SIZE + CHECKSUM_SIZE;
/// partition incarnation it was applied for.
pub const PURGE_GENERATION_FILE: &str = "purge.gen";
+/// Sibling name an atomic offset replacement writes before its rename lands.
+const OFFSET_REPLACEMENT_SUFFIX: &str = ".tmp";
+
/// `[generation][created_revision]`, both LE u64.
const PURGE_GENERATION_RECORD_SIZE: usize = 2 * OFFSET_SIZE;
@@ -48,7 +51,9 @@ pub enum OffsetRecord {
/// A usable offset. `checksummed` is false for a bare offset predating the
/// checksum, read as-is and upgraded by the next write.
Value { offset: u64, checksummed: bool },
- /// Shorter than the value: a crash between `persist_offset`'s truncate and write.
+ /// Shorter than the value: a crash between the truncate and the write of an
+ /// in-place update, the default path while `consumer_offset_enforce_fsync`
+ /// is off.
Torn,
/// The checksum does not describe the value stored beside it.
Corrupt {
@@ -106,9 +111,41 @@ pub fn decode_offset_record(bytes: &[u8]) -> OffsetRecord {
/// Overwrite a consumer-offset file with `offset` and a checksum over it.
///
+/// Without `enforce_fsync` the file is rewritten in place and no directory is
+/// synced. With it, the record goes to a sibling inode, is data-synced and
+/// renamed over the prior file, so a failed write leaves the prior cursor
+/// intact, and the caller marks the parent directory for a sync on the next
+/// commit walk. The replacement is tied to the same knob as the sync: without
+/// the sync neither the write nor the rename is ordered against a crash, so
+/// the extra inode and rename buy nothing.
+///
/// # Errors
/// [`IggyError`] when the directory, file, or write cannot be created or completed.
pub async fn persist_offset(path: &str, offset: u64, enforce_fsync: bool) -> Result<(), IggyError> {
+ let record = encode_offset_record(offset);
+ if enforce_fsync {
+ replace_file(path, record, true, false).await
+ } else {
+ write_in_place(path, record).await
+ }
+}
+
+async fn write_in_place<const N: usize>(path: &str, record: [u8; N]) -> Result<(), IggyError> {
+ create_parent_dir(path).await?;
+ let mut file = OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .open(path)
+ .await
+ .map_err(|_| IggyError::CannotOpenConsumerOffsetsFile(path.to_owned()))?;
+ file.write_all_at(record, 0)
+ .await
+ .0
+ .map_err(|_| IggyError::CannotWriteToFile)
+}
+
+async fn create_parent_dir(path: &str) -> Result<(), IggyError> {
// No `exists()` probe first: that is a BLOCKING `std::path` stat on the pump
// in front of every write, which serialises a batched fan-out on stats
// before it can submit any I/O. `create_dir_all` is already a no-op on an
@@ -118,26 +155,96 @@ pub async fn persist_offset(path: &str, offset: u64, enforce_fsync: bool) -> Res
IggyError::CannotCreateConsumerOffsetsDirectory(parent.display().to_string())
})?;
}
+ Ok(())
+}
+
+pub(crate) async fn stage_offset_replacement(path: &str, offset: u64) -> Result<(), IggyError> {
+ // Install can remove old files before publishing replacements. Staging
+ // must survive a crash regardless of the normal consumer-offset fsync knob.
+ write_replacement(path, encode_offset_record(offset), true)
+ .await
+ .map(|_| ())
+}
+
+pub(crate) async fn commit_offset_replacement(path: &str) -> Result<(), IggyError> {
+ rename(replacement_path(path), path)
+ .await
+ .map_err(|_| IggyError::CannotWriteToFile)
+}
+
+pub(crate) async fn discard_offset_replacement(path: &str) {
+ let _ = remove_file(replacement_path(path)).await;
+}
+
+async fn replace_file<const N: usize>(
+ path: &str,
+ record: [u8; N],
+ enforce_fsync: bool,
+ sync_parent: bool,
+) -> Result<(), IggyError> {
+ let temporary = write_replacement(path, record, enforce_fsync).await?;
+ if rename(&temporary, path).await.is_err() {
+ let _ = remove_file(&temporary).await;
+ return Err(IggyError::CannotWriteToFile);
+ }
+ if sync_parent && let Some(parent) = Path::new(path).parent() {
+ let parent = compio::fs::File::open(parent)
+ .await
+ .map_err(|_| IggyError::CannotSyncFile)?;
+ parent
+ .sync_all()
+ .await
+ .map_err(|_| IggyError::CannotSyncFile)?;
+ }
+ Ok(())
+}
+
+async fn write_replacement<const N: usize>(
+ path: &str,
+ record: [u8; N],
+ enforce_fsync: bool,
+) -> Result<String, IggyError> {
+ create_parent_dir(path).await?;
+
+ // Keep the previous cursor intact until the complete replacement exists.
+ // A failed truncate-and-write otherwise turns a valid cursor into a torn
+ // file that boot discards. The fixed sibling is safe because writes to one
+ // consumer key are serialized by the partition pump.
+ let temporary = replacement_path(path);
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
- .open(path)
+ .open(&temporary)
.await
.map_err(|_| IggyError::CannotOpenConsumerOffsetsFile(path.to_owned()))?;
- file.write_all_at(encode_offset_record(offset), 0)
- .await
- .0
- .map_err(|_| IggyError::CannotWriteToFile)?;
+ if file.write_all_at(record, 0).await.0.is_err() {
+ let _ = remove_file(&temporary).await;
+ return Err(IggyError::CannotWriteToFile);
+ }
- if enforce_fsync {
- file.sync_data()
- .await
- .map_err(|_| IggyError::CannotWriteToFile)?;
+ if enforce_fsync && file.sync_data().await.is_err() {
+ let _ = remove_file(&temporary).await;
+ return Err(IggyError::CannotWriteToFile);
}
+ drop(file);
+ Ok(temporary)
+}
- Ok(())
+fn replacement_path(path: &str) -> String {
+ format!("{path}{OFFSET_REPLACEMENT_SUFFIX}")
+}
+
+#[must_use]
+pub fn offset_replacement_id(name: &str) -> Option<u32> {
+ name.strip_suffix(OFFSET_REPLACEMENT_SUFFIX)?.parse().ok()
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct PersistedOffset {
+ pub offset: u64,
+ pub written: bool,
}
/// Monotone counterpart of [`persist_offset`] for a server auto-commit op.
@@ -165,7 +272,7 @@ pub async fn persist_offset_max(
path: &str,
offset: u64,
enforce_fsync: bool,
-) -> Result<u64, IggyError> {
+) -> Result<PersistedOffset, IggyError> {
let on_disk = match read_offset_record(path).await? {
Some(OffsetRecord::Value { offset, .. }) => Some(offset),
Some(OffsetRecord::Corrupt {
@@ -187,16 +294,20 @@ pub async fn persist_offset_max(
Some(OffsetRecord::Torn) | None => None,
};
let effective = on_disk.map_or(offset, |current| current.max(offset));
- if on_disk != Some(effective) {
+ let written = on_disk != Some(effective);
+ if written {
persist_offset(path, effective, enforce_fsync).await?;
}
- Ok(effective)
+ Ok(PersistedOffset {
+ offset: effective,
+ written,
+ })
}
/// Durably record the purge generation a partition has locally applied, keyed
/// to the incarnation (`created_revision`) it was applied for.
///
-/// Truncate+write like [`persist_offset`] but ALWAYS data-synced, regardless of
+/// Atomic replacement like [`persist_offset`] but ALWAYS data-synced, regardless of
/// the consumer-offset fsync knob: purges are rare, the record is 16 bytes, and
/// a generation lost from the page cache in a crash makes the reconciler
/// re-purge on restart, wiping messages appended after the purge. A failure
@@ -210,30 +321,10 @@ pub async fn persist_purge_generation(
generation: u64,
created_revision: u64,
) -> Result<(), IggyError> {
- if let Some(parent) = Path::new(path).parent() {
- create_dir_all(parent).await.map_err(|_| {
- IggyError::CannotCreateConsumerOffsetsDirectory(parent.display().to_string())
- })?;
- }
-
- let mut file = OpenOptions::new()
- .write(true)
- .create(true)
- .truncate(true)
- .open(path)
- .await
- .map_err(|_| IggyError::CannotOpenConsumerOffsetsFile(path.to_owned()))?;
let mut record = [0u8; PURGE_GENERATION_RECORD_SIZE];
record[..OFFSET_SIZE].copy_from_slice(&generation.to_le_bytes());
record[OFFSET_SIZE..].copy_from_slice(&created_revision.to_le_bytes());
- file.write_all_at(record, 0)
- .await
- .0
- .map_err(|_| IggyError::CannotWriteToFile)?;
- file.sync_data()
- .await
- .map_err(|_| IggyError::CannotWriteToFile)?;
- Ok(())
+ replace_file(path, record, true, true).await
}
/// Read the purge generation this replica applied for the `created_revision`
@@ -323,16 +414,17 @@ async fn read_offset_record(path: &str) -> Result<Option<OffsetRecord>, IggyErro
}
/// Unlink a persisted consumer-offset file. A no-op if the file is absent.
+/// Returns whether a file was removed. An absent file is `Ok(false)`.
///
/// # Errors
/// Returns [`IggyError::CannotDeleteConsumerOffsetFile`] if the unlink fails.
-pub async fn delete_persisted_offset(path: &str) -> Result<(), IggyError> {
+pub async fn delete_persisted_offset(path: &str) -> Result<bool, IggyError> {
// NotFound is tolerated on the result instead of probed for: the probe was
// a blocking stat on the pump before every unlink, and "already gone" is
// exactly the outcome this wants anyway.
match remove_file(path).await {
- Ok(()) => Ok(()),
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Ok(()) => Ok(true),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(_) => Err(IggyError::CannotDeleteConsumerOffsetFile(path.to_owned())),
}
}
@@ -479,6 +571,29 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
+ #[compio::test]
+ async fn failed_replacement_keeps_the_previous_offset_file_intact() {
+ let dir = unique_temp_dir();
+ let path = dir.join("42").to_string_lossy().into_owned();
+ persist_offset(&path, 114, true)
+ .await
+ .expect("initial persist");
+ std::fs::create_dir(format!("{path}{OFFSET_REPLACEMENT_SUFFIX}"))
+ .expect("block temporary file creation");
+
+ assert!(persist_offset(&path, 115, true).await.is_err());
+ let bytes = std::fs::read(&path).expect("previous offset survives");
+ assert_eq!(
+ decode_offset_record(&bytes),
+ OffsetRecord::Value {
+ offset: 114,
+ checksummed: true,
+ }
+ );
+
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
#[compio::test]
async fn read_offset_record_torn_file_is_torn_not_error() {
let dir = unique_temp_dir();
@@ -635,7 +750,7 @@ mod tests {
.await
.expect("a corrupt file must not fail the commit");
assert_eq!(
- folded, 7,
+ folded.offset, 7,
"the untrusted stored value must not win the fold"
);
diff --git a/core/partitions/src/poll_plan.rs b/core/partitions/src/poll_plan.rs
index 7d3fae869..6b8a01e00 100644
--- a/core/partitions/src/poll_plan.rs
+++ b/core/partitions/src/poll_plan.rs
@@ -31,6 +31,10 @@
//! sound on a detached task concurrently with the pump's own writes.
use crate::PollFragments;
+use crate::consumer_offset_capacity::{
+ AutoCommitReservation, ConsumerOffsetCapacity, ConsumerOffsetCapacityError,
+ DurableConsumerOffsets,
+};
use crate::iggy_index::{IGGY_INDEX_SIZE, IggyIndexCache};
use crate::iggy_index_reader::IggyIndexReader;
use crate::journal::{
@@ -174,6 +178,8 @@ pub struct DiskSegment {
/// node-local only and diverge on failover.
pub struct AutoCommitCtx {
pub(crate) target: AutoCommitTarget,
+ pub(crate) capacity: Rc<ConsumerOffsetCapacity>,
+ pub(crate) durable: Rc<DurableConsumerOffsets>,
}
/// The offset an `auto_commit` poll applied in memory, surfaced for replication.
@@ -185,6 +191,11 @@ pub struct AutoCommitApplied {
pub kind: ConsumerKind,
pub consumer_id: u32,
pub offset: u64,
+ previous_offset: Option<u64>,
+ target: AutoCommitTarget,
+ capacity: Rc<ConsumerOffsetCapacity>,
+ durable: Rc<DurableConsumerOffsets>,
+ last_polled: Option<LastPolledCtx>,
}
/// The lock-free offset map this auto-commit updates, captured as an owned
@@ -296,7 +307,17 @@ impl PollPlan {
/// docs), so it is safe on a detached task. Returns the served fragments,
/// the poll's high-water offset, and the auto-committed offset (if any) for
/// the serving shard to replicate through consensus.
- pub async fn execute(self) -> (PollFragments<4096>, u64, Option<AutoCommitApplied>) {
+ ///
+ /// # Errors
+ /// Returns a capacity error when auto-commit would create a new live-map
+ /// entry after the configured per-kind bound has been reached.
+ /// The serving shard also rejects completion with `TransientNotAccepted`
+ /// if the partition disappeared or changed incarnation during disk I/O.
+ /// No fragments are returned for that rejected completion.
+ pub async fn execute(
+ self,
+ ) -> Result<(PollFragments<4096>, u64, Option<AutoCommitApplied>), ConsumerOffsetCapacityError>
+ {
let commit_offset = self.commit_offset;
let (fragments, last_matching_offset) = match self.tier {
PollTier::Empty => (PollFragments::new(), None),
@@ -362,7 +383,7 @@ impl PollPlan {
};
finish(
- self.last_polled.as_ref(),
+ self.last_polled,
self.auto_commit,
commit_offset,
fragments,
@@ -374,8 +395,14 @@ impl PollPlan {
/// ([`Self::needs_off_pump_io`] is `false`): no disk read, so the pump
/// applies the auto-commit in memory and replies inline without spawning.
/// The auto-committed offset is returned for the serving shard to replicate.
- #[must_use]
- pub fn execute_resident(self) -> (PollFragments<4096>, u64, Option<AutoCommitApplied>) {
+ ///
+ /// # Errors
+ /// Returns a capacity error when auto-commit would create a new live-map
+ /// entry after the configured per-kind bound has been reached.
+ pub fn execute_resident(
+ self,
+ ) -> Result<(PollFragments<4096>, u64, Option<AutoCommitApplied>), ConsumerOffsetCapacityError>
+ {
let commit_offset = self.commit_offset;
let (fragments, last_matching_offset) = match self.tier {
PollTier::Empty => (PollFragments::new(), None),
@@ -390,7 +417,7 @@ impl PollPlan {
}
};
finish(
- self.last_polled.as_ref(),
+ self.last_polled,
self.auto_commit,
commit_offset,
fragments,
@@ -403,17 +430,19 @@ impl PollPlan {
/// factored out so the high-water record, auto-commit, and returned triple
/// stay identical across both.
fn finish(
- last_polled: Option<&LastPolledCtx>,
+ last_polled: Option<LastPolledCtx>,
auto_commit: Option<AutoCommitCtx>,
commit_offset: u64,
fragments: PollFragments<4096>,
last_matching_offset: Option<u64>,
-) -> (PollFragments<4096>, u64, Option<AutoCommitApplied>) {
- if let (Some(last_polled), Some(last_offset)) = (last_polled, last_matching_offset) {
+) -> Result<(PollFragments<4096>, u64, Option<AutoCommitApplied>), ConsumerOffsetCapacityError> {
+ let mut auto_commit_applied = apply_auto_commit(auto_commit, &fragments, last_matching_offset)?;
+ if let Some(applied) = &mut auto_commit_applied {
+ applied.last_polled = last_polled;
+ } else if let (Some(last_polled), Some(last_offset)) = (last_polled, last_matching_offset) {
last_polled.record(last_offset);
}
- let auto_commit_applied = apply_auto_commit(auto_commit, &fragments, last_matching_offset);
- (fragments, commit_offset, auto_commit_applied)
+ Ok((fragments, commit_offset, auto_commit_applied))
}
/// Apply an `auto_commit` to the in-memory offset map (monotone) and surface
@@ -429,19 +458,17 @@ fn apply_auto_commit(
auto_commit: Option<AutoCommitCtx>,
fragments: &PollFragments<4096>,
last_matching_offset: Option<u64>,
-) -> Option<AutoCommitApplied> {
- let auto_commit = auto_commit?;
+) -> Result<Option<AutoCommitApplied>, ConsumerOffsetCapacityError> {
+ let Some(auto_commit) = auto_commit else {
+ return Ok(None);
+ };
if fragments.is_empty() {
- return None;
+ return Ok(None);
}
- let last_offset = last_matching_offset?;
- auto_commit.apply(last_offset);
- let (kind, consumer_id) = auto_commit.kind_and_id();
- Some(AutoCommitApplied {
- kind,
- consumer_id,
- offset: last_offset,
- })
+ let Some(last_offset) = last_matching_offset else {
+ return Ok(None);
+ };
+ auto_commit.apply(last_offset).map(Some)
}
pub enum PollTier {
@@ -861,53 +888,168 @@ impl AutoCommitCtx {
/// newer explicit store; the maps are lock-free (`papaya`), so this is
/// sound off the pump task.
#[allow(clippy::cast_possible_truncation)]
- pub(crate) fn apply(&self, offset: u64) {
- match &self.target {
+ pub(crate) fn apply(
+ self,
+ offset: u64,
+ ) -> Result<AutoCommitApplied, ConsumerOffsetCapacityError> {
+ let (kind, consumer_id) = self.kind_and_id();
+ let create = |path: Option<&str>| {
+ ConsumerOffset::new(
+ kind,
+ consumer_id,
+ offset,
+ path.map_or_else(String::new, |path| format!("{path}/{consumer_id}")),
+ )
+ };
+ let previous_offset = match &self.target {
AutoCommitTarget::Consumer {
offsets,
consumer_id,
create_path,
- } => {
- let consumer_id = *consumer_id;
- let map: &ConsumerOffsets = offsets;
- upsert_offset_max(map, consumer_id as usize, offset, || {
- create_path.as_deref().map_or_else(
- || {
- ConsumerOffset::new(
- ConsumerKind::Consumer,
- consumer_id,
- 0,
- String::new(),
- )
- },
- |path| ConsumerOffset::default_for_consumer(consumer_id, path),
- )
- });
- }
+ } => apply_local_offset(
+ offsets,
+ *consumer_id as usize,
+ offset,
+ &self.capacity,
+ self.durable.count(kind) >= self.capacity.limit(),
+ || create(create_path.as_deref()),
+ )?,
AutoCommitTarget::ConsumerGroup {
offsets,
group_id,
create_path,
- } => {
- let group_id = *group_id;
- let key = ConsumerGroupId(group_id as usize);
- let map: &ConsumerGroupOffsets = offsets;
- upsert_offset_max(map, key, offset, || {
- create_path.as_deref().map_or_else(
- || {
- ConsumerOffset::new(
- ConsumerKind::ConsumerGroup,
- group_id,
- 0,
- String::new(),
- )
- },
- |path| ConsumerOffset::default_for_consumer_group(key, path),
- )
- });
+ } => apply_local_offset(
+ offsets,
+ ConsumerGroupId(*group_id as usize),
+ offset,
+ &self.capacity,
+ self.durable.count(kind) >= self.capacity.limit(),
+ || create(create_path.as_deref()),
+ )?,
+ };
+ Ok(AutoCommitApplied {
+ kind,
+ consumer_id,
+ offset,
+ previous_offset,
+ target: self.target,
+ capacity: self.capacity,
+ durable: self.durable,
+ last_polled: None,
+ })
+ }
+}
+
+impl AutoCommitApplied {
+ /// Record the group handoff frontier only after poll admission succeeds.
+ fn mark_served(&self) {
+ if let Some(last_polled) = &self.last_polled {
+ last_polled.record(self.offset);
+ }
+ }
+ /// Reserve a durable key before the synthetic store is submitted.
+ /// Returns `None` when committed state already covers this offset.
+ ///
+ /// # Errors
+ /// Returns a capacity error when this is a new durable key and the
+ /// partition's per-kind limit has been reached.
+ pub fn reserve_durable(
+ &self,
+ ) -> Result<Option<AutoCommitReservation>, ConsumerOffsetCapacityError> {
+ if self
+ .durable
+ .covers(self.kind, self.consumer_id, self.offset)
+ {
+ return Ok(None);
+ }
+ self.capacity
+ .reserve_provisional(self.consumer_id, &self.durable)
+ .map(Some)
+ }
+
+ pub(crate) fn belongs_to(&self, durable: &Rc<DurableConsumerOffsets>) -> bool {
+ Rc::ptr_eq(&self.durable, durable)
+ }
+
+ /// Run the serving shard's synchronous admission and settle this apply in
+ /// the same call: `Ok` marks the cursor served, `Err` rolls the eager
+ /// local update back and returns the error. The rollback is a bare store of
+ /// the previous offset, so nothing may yield between the decision and it.
+ /// Keeping both inside one synchronous method is what makes that hold for
+ /// every caller.
+ ///
+ /// # Errors
+ /// Whatever `decide` returned, after the rollback.
+ pub fn admit<E>(self, decide: impl FnOnce(&Self) -> Result<(), E>) -> Result<(), E> {
+ match decide(&self) {
+ Ok(()) => {
+ self.mark_served();
+ Ok(())
}
+ Err(error) => {
+ self.rollback_created();
+ Err(error)
+ }
+ }
+ }
+
+ /// Undo this poll's eager update after synchronous admission fails.
+ fn rollback_created(&self) {
+ match &self.target {
+ AutoCommitTarget::Consumer {
+ offsets,
+ consumer_id,
+ ..
+ } => rollback_local_offset(offsets, *consumer_id as usize, self.previous_offset),
+ AutoCommitTarget::ConsumerGroup {
+ offsets, group_id, ..
+ } => rollback_local_offset(
+ offsets,
+ ConsumerGroupId(*group_id as usize),
+ self.previous_offset,
+ ),
+ }
+ if self.previous_offset.is_none() {
+ self.capacity.note_local_key_change();
+ self.capacity.forget_inactive_provisional(self.consumer_id);
+ }
+ }
+}
+
+fn rollback_local_offset<K: Hash + Eq + Send + Sync + Copy>(
+ map: &papaya::HashMap<K, ConsumerOffset>,
+ key: K,
+ previous: Option<u64>,
+) {
+ let guard = map.pin();
+ if let Some(previous) = previous {
+ if let Some(entry) = guard.get(&key) {
+ entry.offset.store(previous, Ordering::Relaxed);
}
+ } else {
+ guard.remove(&key);
+ }
+}
+
+fn apply_local_offset<K: Hash + Eq + Clone + Send + Sync>(
+ map: &papaya::HashMap<K, ConsumerOffset>,
+ key: K,
+ offset: u64,
+ capacity: &ConsumerOffsetCapacity,
+ durable_full: bool,
+ create: impl FnOnce() -> ConsumerOffset,
+) -> Result<Option<u64>, ConsumerOffsetCapacityError> {
+ let guard = map.pin();
+ if let Some(existing) = guard.get(&key) {
+ return Ok(Some(existing.offset.fetch_max(offset, Ordering::Relaxed)));
}
+ // The `len()` read and the insert are not atomic on this lock-free map.
+ // The bound holds because every poll of one partition runs on that
+ // partition's own shard thread, so no second inserter exists.
+ capacity.admit_local_map_key(guard.len(), durable_full)?;
+ guard.insert(key, create());
+ capacity.note_local_key_change();
+ Ok(None)
}
/// Upsert a committed offset into a lock-free `papaya` offset map: bump an
@@ -1141,15 +1283,95 @@ mod tests {
}
fn consumer_auto_commit(offsets: Arc<ConsumerOffsets>, consumer_id: u32) -> AutoCommitCtx {
+ consumer_auto_commit_with_limit(offsets, consumer_id, crate::DEFAULT_CONSUMER_OFFSETS_MAX)
+ }
+
+ fn consumer_auto_commit_with_limit(
+ offsets: Arc<ConsumerOffsets>,
+ consumer_id: u32,
+ limit: usize,
+ ) -> AutoCommitCtx {
AutoCommitCtx {
target: AutoCommitTarget::Consumer {
offsets,
consumer_id,
create_path: None,
},
+ capacity: Rc::new(ConsumerOffsetCapacity::new(ConsumerKind::Consumer, limit)),
+ durable: Rc::new(DurableConsumerOffsets::default()),
}
}
+ #[test]
+ fn given_existing_phantom_when_primary_reservation_is_denied_should_restore_previous_offset() {
+ let offsets = Arc::new(ConsumerOffsets::with_capacity(2));
+ offsets.pin().insert(
+ 7,
+ ConsumerOffset::new(ConsumerKind::Consumer, 7, 4, String::new()),
+ );
+ let context = consumer_auto_commit_with_limit(Arc::clone(&offsets), 7, 1);
+ context
+ .durable
+ .record_explicit(ConsumerKind::Consumer, 8, 0, 0);
+ let applied = context
+ .apply(9)
+ .expect("existing phantom is locally writable");
+ assert!(applied.reserve_durable().is_err());
+ applied.rollback_created();
+ assert_eq!(
+ offsets
+ .pin()
+ .get(&7)
+ .expect("phantom retained")
+ .offset
+ .load(Ordering::Relaxed),
+ 4
+ );
+ }
+
+ #[test]
+ fn given_new_auto_commit_when_provisional_guard_is_dropped_should_reopen_capacity() {
+ let offsets = Arc::new(ConsumerOffsets::with_capacity(1));
+ let context = consumer_auto_commit_with_limit(Arc::clone(&offsets), 7, 1);
+ let capacity = Rc::clone(&context.capacity);
+ let durable = Rc::clone(&context.durable);
+ let applied = context.apply(9).expect("new poll fits");
+ let reservation = applied
+ .reserve_durable()
+ .expect("primary admits")
+ .expect("new slot");
+ assert!(capacity.check(8, &durable).is_err());
+ drop(reservation);
+ applied.rollback_created();
+ assert!(capacity.check(8, &durable).is_ok());
+ assert!(offsets.pin().is_empty());
+ }
+
+ #[test]
+ fn given_full_auto_commit_map_when_creating_key_should_reject_without_insertion() {
+ let offsets = Arc::new(ConsumerOffsets::with_capacity(1));
+ offsets.pin().insert(
+ 1,
+ ConsumerOffset::new(ConsumerKind::Consumer, 1, 0, String::new()),
+ );
+ let plan = PollPlan {
+ commit_offset: 42,
+ auto_commit: Some(consumer_auto_commit_with_limit(offsets.clone(), 2, 1)),
+ last_polled: None,
+ tier: PollTier::Resident {
+ fragments: non_empty_fragments(),
+ last_matching_offset: Some(5),
+ },
+ };
+
+ let Err(error) = plan.execute_resident() else {
+ panic!("a missing key at the map limit must be rejected");
+ };
+ assert_eq!(error.kind, ConsumerKind::Consumer);
+ assert_eq!(error.occupied, 1);
+ assert!(offsets.pin().get(&2).is_none());
+ }
+
#[test]
fn resident_auto_commit_applies_in_memory_and_surfaces_offset() {
// A resident auto_commit poll stays on the inline fast path (no detached
@@ -1172,7 +1394,8 @@ mod tests {
"a resident auto_commit no longer persists on the poll path; the pump must not spawn",
);
- let (fragments, commit_offset, applied) = plan.execute_resident();
+ let (fragments, commit_offset, applied) =
+ plan.execute_resident().expect("auto-commit is admitted");
assert!(!fragments.is_empty(), "resident fragments must be returned");
assert_eq!(commit_offset, 42, "commit offset is forwarded verbatim");
@@ -1203,7 +1426,8 @@ mod tests {
last_polled: None,
tier: PollTier::Empty,
};
- let (fragments, _commit_offset, applied) = plan.execute_resident();
+ let (fragments, _commit_offset, applied) =
+ plan.execute_resident().expect("empty poll needs no slot");
assert!(fragments.is_empty());
assert!(
applied.is_none(),
@@ -1220,9 +1444,9 @@ mod tests {
// Auto-commit must never rewind a newer offset (anti-rewind via
// fetch_max); an explicit StoreConsumerOffset may legitimately rewind.
let offsets = Arc::new(ConsumerOffsets::with_capacity(1));
- let auto_commit = consumer_auto_commit(offsets.clone(), 7);
-
- auto_commit.apply(10);
+ consumer_auto_commit(offsets.clone(), 7)
+ .apply(10)
+ .expect("first auto-commit is admitted");
let after_high = offsets
.pin()
.get(&7usize)
@@ -1230,7 +1454,9 @@ mod tests {
assert_eq!(after_high, Some(10));
// A stale auto-commit with a smaller offset must not rewind.
- auto_commit.apply(4);
+ consumer_auto_commit(offsets.clone(), 7)
+ .apply(4)
+ .expect("existing key remains admitted");
let after_stale = offsets
.pin()
.get(&7usize)
diff --git a/core/partitions/src/state_transfer.rs b/core/partitions/src/state_transfer.rs
index 1872d5216..94a62b60e 100644
--- a/core/partitions/src/state_transfer.rs
+++ b/core/partitions/src/state_transfer.rs
@@ -29,7 +29,9 @@
use crate::messages_writer::MessagesWriter;
use crate::offset_storage::{
- PURGE_GENERATION_FILE, delete_persisted_offset, persist_offset, persist_purge_generation,
+ PURGE_GENERATION_FILE, commit_offset_replacement, delete_persisted_offset,
+ discard_offset_replacement, offset_replacement_id, persist_purge_generation,
+ stage_offset_replacement,
};
use crate::segment::Segment;
use crate::segment_anchor::ANCHOR_SUFFIX;
@@ -46,8 +48,9 @@ use journal::superblock::SuperblockStore;
use message_bus::MessageBus;
use server_common::send_messages::decode_batch_slice;
use server_common::{SegmentStorage, yield_to_reactor};
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use std::fmt;
+use std::future::Future;
use std::mem::size_of;
use std::path::{Path, PathBuf};
use std::rc::Rc;
@@ -79,7 +82,7 @@ const CONSUMER_OFFSETS_VERSION_V1: u8 = 1;
/// A corruption guard, not a target: it bounds the allocation `decode`
/// makes from a length field a peer sent, exactly like the manifest's own
/// entry ceiling.
-pub(crate) const CONSUMER_OFFSETS_ENTRIES_MAX: u32 = 1 << 20;
+pub const CONSUMER_OFFSETS_ENTRIES_MAX: u32 = 1 << 20;
/// Wire stride of one dedup entry: client u128 + watermark u64 + commit u64 +
/// user u32 + committed window u128.
@@ -612,10 +615,46 @@ impl fmt::Display for ConsumerOffsetsWireError {
impl std::error::Error for ConsumerOffsetsWireError {}
+const fn validate_consumer_offset_transfer_count(
+ kind: ConsumerKind,
+ count: usize,
+ max: usize,
+) -> Result<(), PartitionTransferUnavailable> {
+ if count <= max {
+ return Ok(());
+ }
+ Err(PartitionTransferUnavailable::ConsumerOffsetsTooLarge { kind, count, max })
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ #[compio::test]
+ async fn given_transient_offset_io_failure_when_retried_should_succeed_without_exhausting_budget()
+ {
+ let attempts = std::cell::Cell::new(0);
+ let result = retry_offset_mutation(|| {
+ attempts.set(attempts.get() + 1);
+ std::future::ready(if attempts.get() == 1 { Err(()) } else { Ok(7) })
+ })
+ .await;
+ assert_eq!(result, Ok(7));
+ assert_eq!(attempts.get(), 2);
+ }
+
+ #[compio::test]
+ async fn given_persistent_offset_io_failure_when_retried_should_stop_at_attempt_limit() {
+ let attempts = std::cell::Cell::new(0);
+ let result = retry_offset_mutation(|| {
+ attempts.set(attempts.get() + 1);
+ std::future::ready(Err::<(), _>(7))
+ })
+ .await;
+ assert_eq!(result, Err(7));
+ assert_eq!(attempts.get(), OFFSET_IO_ATTEMPTS);
+ }
+
fn table() -> ConsumerOffsetsWire {
ConsumerOffsetsWire {
purge_generation: 3,
@@ -903,6 +942,25 @@ mod tests {
"bytes past the last section must fail closed"
);
}
+
+ #[test]
+ fn given_offset_count_above_transfer_ceiling_when_validated_should_reject() {
+ assert!(validate_consumer_offset_transfer_count(ConsumerKind::Consumer, 4, 4).is_ok());
+ assert!(matches!(
+ validate_consumer_offset_transfer_count(ConsumerKind::ConsumerGroup, 5, 4),
+ Err(PartitionTransferUnavailable::ConsumerOffsetsTooLarge {
+ kind: ConsumerKind::ConsumerGroup,
+ count: 5,
+ max: 4,
+ })
+ ));
+ let error = validate_consumer_offset_transfer_count(ConsumerKind::Consumer, 5, 4)
+ .expect_err("count above ceiling");
+ assert!(
+ !error.transient(),
+ "an artifact that cannot fit the decoder will not heal by retrying"
+ );
+ }
}
/// What a full validation walk over one segment payload derived.
@@ -1171,6 +1229,15 @@ pub enum PartitionTransferUnavailable {
/// In-memory / simulated partition: nothing on disk to serve.
NoPartitionDir,
RepairInProgress,
+ ConsumerOffsetsTooLarge {
+ kind: ConsumerKind,
+ count: usize,
+ max: usize,
+ },
+ ConsumerOffsetStateInconsistent {
+ kind: ConsumerKind,
+ consumer_id: u32,
+ },
/// Primary-by-index of a group that has committed nothing: an empty group
/// is trivially "caught up", so this is the only thing separating a real
/// primary from a view-0 phantom whose directory vanished.
@@ -1220,6 +1287,8 @@ impl PartitionTransferUnavailable {
| Self::SegmentSetChanged
| Self::OfferBuildInProgress { .. } => true,
Self::NoPartitionDir
+ | Self::ConsumerOffsetsTooLarge { .. }
+ | Self::ConsumerOffsetStateInconsistent { .. }
| Self::ManifestTooLarge { .. }
| Self::FlushFailed(_)
| Self::SegmentUnreadable { .. } => false,
@@ -1233,6 +1302,14 @@ impl fmt::Display for PartitionTransferUnavailable {
Self::NotCaughtUpPrimary => write!(f, "not the caught-up primary of this group"),
Self::NoPartitionDir => write!(f, "partition has no on-disk directory"),
Self::RepairInProgress => write!(f, "partition is itself mid-repair"),
+ Self::ConsumerOffsetsTooLarge { kind, count, max } => write!(
+ f,
+ "partition has {count} {kind:?} offset entries, past the {max} transfer ceiling"
+ ),
+ Self::ConsumerOffsetStateInconsistent { kind, consumer_id } => write!(
+ f,
+ "durable {kind:?} offset {consumer_id} is missing from the live map"
+ ),
Self::NothingCommitted => write!(
f,
"primary by index at view 0 with nothing committed; refusing to serve an empty offer"
@@ -1262,9 +1339,8 @@ impl fmt::Display for PartitionTransferUnavailable {
impl std::error::Error for PartitionTransferUnavailable {}
-/// Outcome of a completed install. A degraded install is a SUCCESS: the
-/// segments and floor landed; only some consumer-offset file writes failed,
-/// and the next offset commit blind-writes those files.
+/// Outcome of a completed install. Offset files must land before the installed
+/// commit floor advances. A failed purge-generation record remains retryable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PartitionInstallOutcome {
/// The consensus op the install applied. Named for what it holds: every
@@ -1273,19 +1349,22 @@ pub struct PartitionInstallOutcome {
/// `installed_frontier`), and op-vs-offset confusion is what produced this
/// PR's durability defects.
pub applied_commit_op: u64,
- /// Every transferred offset file was WRITTEN (and the offset
- /// directories fsynced, so the old files' unlinks stick). Not a
- /// durability claim for the file contents: `persist_offset` fsyncs only
- /// under `consumer_offset_enforce_fsync`, matching the normal
- /// offset-commit path -- shipped default off.
- pub offsets_written: bool,
+ /// The offered purge generation was already recorded or persisted during
+ /// this install. False means a restart may repeat the purge and transfer.
+ pub purge_generation_recorded: bool,
}
-/// Failure installing a transferred partition state. Every `check`-phase
-/// variant means NOTHING was mutated.
+/// Failure installing a transferred partition state.
+///
+/// Validation failures mutate nothing. Pre-swap offset failures can leave
+/// ignored replacement siblings when best-effort cleanup also fails, but never
+/// alter live files.
#[derive(Debug)]
pub enum PartitionInstallError {
NoPartitionDir,
+ NoOffsetDir {
+ kind: ConsumerKind,
+ },
/// `commit_op` fell below this replica's commit frontier; installing
/// would rewind `commit_min` (the anti-rewind assert, as a refusal).
StaleTransfer {
@@ -1307,6 +1386,12 @@ pub enum PartitionInstallError {
offer_next_offset: u64,
local_next_offset: u64,
},
+ /// Consumer-offset staging failed before the segment swap, or finalizing a
+ /// staged offset failed during it.
+ OffsetPersistence {
+ path: String,
+ source: iggy_common::IggyError,
+ },
Offsets(ConsumerOffsetsWireError),
/// Duplicate base offset in the staged set.
DuplicateSegment {
@@ -1353,6 +1438,9 @@ impl fmt::Display for PartitionInstallError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NoPartitionDir => write!(f, "partition has no on-disk directory"),
+ Self::NoOffsetDir { kind } => {
+ write!(f, "partition has no {kind:?} offset directory configured")
+ }
Self::StaleTransfer {
commit_op,
commit_min,
@@ -1372,6 +1460,9 @@ impl fmt::Display for PartitionInstallError {
"offer frontier {offer_next_offset} is below this replica's own next offset \
{local_next_offset}; installing it would rewind the offset space"
),
+ Self::OffsetPersistence { path, source } => {
+ write!(f, "consumer offset persistence failed at {path}: {source}")
+ }
Self::Offsets(source) => write!(f, "consumer-offsets artifact rejected: {source}"),
Self::DuplicateSegment { start_offset } => {
write!(f, "duplicate staged segment at base offset {start_offset}")
@@ -1551,6 +1642,34 @@ fn final_paths(partition_dir: &str, start_offset: u64) -> (String, String) {
/// depth against how long one partition monopolises it; matches the tick's
/// superblock pre-pass.
const OFFSET_PERSIST_CONCURRENCY: usize = 16;
+const OFFSET_IO_ATTEMPTS: usize = 3;
+/// First retry delay of [`retry_offset_mutation`]; each further retry doubles it.
+const OFFSET_IO_BACKOFF_BASE: std::time::Duration = std::time::Duration::from_millis(10);
+
+async fn retry_offset_mutation<T, E: fmt::Debug, F: Future<Output = Result<T, E>>>(
+ mut operation: impl FnMut() -> F,
+) -> Result<T, E> {
+ for attempt in 1..OFFSET_IO_ATTEMPTS {
+ match operation().await {
+ Ok(value) => return Ok(value),
+ Err(error) => {
+ tracing::debug!(
+ attempt,
+ ?error,
+ "offset mutation failed, retrying after backoff"
+ );
+ compio::time::sleep(OFFSET_IO_BACKOFF_BASE * (1 << (attempt - 1))).await;
+ }
+ }
+ }
+ operation().await.inspect_err(|error| {
+ tracing::debug!(
+ attempt = OFFSET_IO_ATTEMPTS,
+ ?error,
+ "offset mutation failed on the last attempt"
+ );
+ })
+}
/// One consumer-offset file the install is about to write. Collected before any
/// write is issued so the offset maps and the persisted-offset tracker are never
@@ -1562,6 +1681,40 @@ struct PlannedOffsetWrite {
value: u64,
}
+pub(crate) const fn consumer_kind_index(kind: ConsumerKind) -> usize {
+ match kind {
+ ConsumerKind::Consumer => 0,
+ ConsumerKind::ConsumerGroup => 1,
+ }
+}
+
+async fn stage_offset_writes(planned: &[PlannedOffsetWrite]) -> Result<(), PartitionInstallError> {
+ for batch in planned.chunks(OFFSET_PERSIST_CONCURRENCY) {
+ let writes = batch.iter().map(|write| async move {
+ (
+ &write.path,
+ retry_offset_mutation(|| stage_offset_replacement(&write.path, write.value)).await,
+ )
+ });
+ for (path, result) in futures::future::join_all(writes).await {
+ if let Err(source) = result {
+ discard_offset_writes(planned).await;
+ return Err(PartitionInstallError::OffsetPersistence {
+ path: path.clone(),
+ source,
+ });
+ }
+ }
+ }
+ Ok(())
+}
+
+async fn discard_offset_writes(planned: &[PlannedOffsetWrite]) {
+ for write in planned {
+ discard_offset_replacement(&write.path).await;
+ }
+}
+
/// fsync the partition directory so a rename made durable stays durable.
/// Async so the wait parks the task instead of the whole shard reactor;
/// every other future on the pump keeps running through it.
@@ -1577,6 +1730,45 @@ where
B: MessageBus,
SB: SuperblockStore,
{
+ fn plan_transfer_offset_writes(
+ &self,
+ offsets_wire: &ConsumerOffsetsWire,
+ next_offset: u64,
+ ) -> Result<Vec<PlannedOffsetWrite>, PartitionInstallError> {
+ let consumer_dir =
+ self.consumer_offsets_path
+ .as_deref()
+ .ok_or(PartitionInstallError::NoOffsetDir {
+ kind: ConsumerKind::Consumer,
+ })?;
+ let group_dir = self.consumer_group_offsets_path.as_deref().ok_or(
+ PartitionInstallError::NoOffsetDir {
+ kind: ConsumerKind::ConsumerGroup,
+ },
+ )?;
+ let clamp = |offset: u64| next_offset.checked_sub(1).map(|last| offset.min(last));
+ let mut planned =
+ Vec::with_capacity(offsets_wire.consumers.len() + offsets_wire.groups.len());
+ for (kind, dir, offsets) in [
+ (
+ ConsumerKind::Consumer,
+ consumer_dir,
+ &offsets_wire.consumers,
+ ),
+ (ConsumerKind::ConsumerGroup, group_dir, &offsets_wire.groups),
+ ] {
+ planned.extend(offsets.iter().filter_map(|(id, offset)| {
+ clamp(*offset).map(|value| PlannedOffsetWrite {
+ kind,
+ id: *id,
+ path: format!("{dir}/{id}"),
+ value,
+ })
+ }));
+ }
+ Ok(planned)
+ }
+
/// Build (or serve from cache) this group's state-transfer offer.
///
/// Force-flushes the committed prefix first so the segments cover every
@@ -1770,7 +1962,7 @@ where
// serve it only when a recorded purge says the emptiness is the truth.
// `install_state_transfer`'s `purge_advances` check re-decides that
// against the metadata plane and refuses the rest.
- let offsets_wire = self.offsets_wire_snapshot();
+ let offsets_wire = self.offsets_wire_snapshot()?;
if segments.is_empty()
&& offsets_wire.next_offset == 0
&& offsets_wire.purge_generation == 0
@@ -1919,53 +2111,84 @@ where
self.transfer_offer_cache.borrow_mut().take();
}
- /// Snapshot the live offset maps + purge generation into the wire shape.
- /// Eagerly auto-committed offsets can run slightly ahead of committed
- /// state; that is safe because their covering ops sit in
- /// `(commit_op, commit_max]`, which the receiver's tail repair replays,
- /// and offset applies converge (monotone auto-commit, verbatim stores).
- fn offsets_wire_snapshot(&self) -> ConsumerOffsetsWire {
- // Every key is minted from a u32 wire id, so the narrowing filter is
- // an invariant, not a policy: say so out loud instead of silently
- // shrinking the snapshot when it ever breaks.
- let mut consumers: Vec<(u32, u64)> = self
- .consumer_offsets
- .pin()
- .iter()
- .filter_map(|(id, offset)| {
- let narrowed = u32::try_from(*id).ok();
- debug_assert!(narrowed.is_some(), "consumer offset key {id} exceeds u32");
- narrowed.map(|id| (id, offset.offset.load(Ordering::Acquire)))
- })
- .collect();
- consumers.sort_unstable_by_key(|(id, _)| *id);
- let mut groups: Vec<(u32, u64)> = self
- .consumer_group_offsets
- .pin()
- .iter()
- .filter_map(|(id, offset)| {
- let narrowed = u32::try_from(id.0).ok();
- debug_assert!(
- narrowed.is_some(),
- "consumer group offset key {} exceeds u32",
- id.0
+ fn validate_consumer_offset_transfer_counts(&self) -> Result<(), PartitionTransferUnavailable> {
+ for kind in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup] {
+ let count = self.durable_consumer_offsets.count(kind);
+ if let Err(error) = validate_consumer_offset_transfer_count(
+ kind,
+ count,
+ CONSUMER_OFFSETS_ENTRIES_MAX as usize,
+ ) {
+ tracing::error!(
+ target: "iggy.partitions.diag",
+ plane = "partitions",
+ namespace_raw = self.consensus().group(),
+ ?kind,
+ count,
+ max = CONSUMER_OFFSETS_ENTRIES_MAX,
+ "consumer offset state exceeds the transfer ceiling"
);
- narrowed.map(|id| (id, offset.offset.load(Ordering::Acquire)))
- })
- .collect();
- groups.sort_unstable_by_key(|(id, _)| *id);
+ return Err(error);
+ }
+ }
+ Ok(())
+ }
+
+ /// Snapshot committed durable offsets only. Eager auto-commit progress and
+ /// follower-local cursor entries stay in the live maps until a replicated
+ /// store commits them, so neither can be promoted by state transfer.
+ fn offsets_wire_snapshot(&self) -> Result<ConsumerOffsetsWire, PartitionTransferUnavailable> {
+ self.validate_consumer_offset_transfer_counts()?;
+ let consumer_map = self.consumer_offsets.pin();
+ let consumers = self.snapshot_offset_kind(ConsumerKind::Consumer, |id| {
+ consumer_map.contains_key(&(id as usize))
+ })?;
+ let group_map = self.consumer_group_offsets.pin();
+ let groups = self.snapshot_offset_kind(ConsumerKind::ConsumerGroup, |id| {
+ group_map.contains_key(&ConsumerGroupId(id as usize))
+ })?;
// The append counter, not the segment end: retention can GC every
// sealed segment while the counter stands at N, and the receiver
// must resume minting at N either way.
let next_offset = self.offset_frontier();
let dedup = self.dedup().watermarks_sorted();
- ConsumerOffsetsWire {
+ Ok(ConsumerOffsetsWire {
purge_generation: self.applied_purge_generation,
next_offset,
consumers,
groups,
dedup,
- }
+ })
+ }
+
+ fn snapshot_offset_kind(
+ &self,
+ kind: ConsumerKind,
+ map_contains: impl Fn(u32) -> bool,
+ ) -> Result<Vec<(u32, u64)>, PartitionTransferUnavailable> {
+ self.durable_consumer_offsets.with_entries(kind, |entries| {
+ let mut snapshot = Vec::with_capacity(entries.len());
+ for (&consumer_id, state) in entries {
+ if !map_contains(consumer_id) {
+ return Err(
+ PartitionTransferUnavailable::ConsumerOffsetStateInconsistent {
+ kind,
+ consumer_id,
+ },
+ );
+ }
+ snapshot.push((consumer_id, state.committed_offset));
+ }
+ snapshot.sort_unstable_by_key(|(id, _)| *id);
+ Ok(snapshot)
+ })
+ }
+
+ #[cfg(test)]
+ pub(crate) fn offsets_wire_snapshot_for_test(
+ &self,
+ ) -> Result<Vec<(u32, u64)>, PartitionTransferUnavailable> {
+ self.offsets_wire_snapshot().map(|wire| wire.consumers)
}
/// Validate one completed `SEGMENT_LOG` artifact and spill it to staging
@@ -2169,10 +2392,10 @@ where
/// `commit_op`. The live tail `(commit_op, commit_max]` is left to
/// ordinary journal repair.
///
- /// Two-phase: every validation runs before any mutation. The mutate
- /// phase's crash windows all recover as an honestly-shorter partition
- /// (see the swap ordering comments); no durable completeness claim
- /// exists anywhere, so boot re-derives from whatever files survive.
+ /// Validation runs before live-state mutation. Offset replacement siblings
+ /// are then written and synced while the old partition remains intact. The
+ /// segment swap's crash windows recover as an honestly-shorter partition
+ /// (see the swap ordering comments); boot re-derives from surviving files.
///
/// # Errors
/// [`PartitionInstallError`]; check-phase variants mutate nothing.
@@ -2185,7 +2408,8 @@ where
offsets_bytes: &[u8],
committed_purge_generation: u64,
) -> Result<PartitionInstallOutcome, PartitionInstallError> {
- // ---- check phase: nothing below may mutate ----
+ // ---- check phase: nothing below may mutate live state. Staging
+ // writes only sibling files the install can abandon. ----
let Some(partition_dir) = self.partition_dir.clone() else {
return Err(PartitionInstallError::NoPartitionDir);
};
@@ -2280,6 +2504,16 @@ where
}
}
+ let installed_end = staged.last().map(|meta| meta.end_offset);
+ let next_offset = offsets_wire
+ .next_offset
+ .max(installed_end.map_or(0, |end| end + 1));
+ let planned_offsets = self.plan_transfer_offset_writes(&offsets_wire, next_offset)?;
+ // Write and data-sync every small offset record before the destructive
+ // segment swap. Only ignored, nonnumeric replacement siblings exist at
+ // this point, so a write fault leaves the old partition serviceable.
+ stage_offset_writes(&planned_offsets).await?;
+
// ---- mutate phase ----
// Record the INCOMING frontier before anything destructive: the swap
// below unlinks the old chain and makes that durable before the first
@@ -2316,6 +2550,7 @@ where
.await
};
if !frontier_durable {
+ discard_offset_writes(&planned_offsets).await;
return Err(PartitionInstallError::FrontierNotDurable {
frontier: offsets_wire.next_offset,
});
@@ -2331,9 +2566,18 @@ where
// below it.
let staged_was_empty = staged.is_empty();
let outcome = self
- .apply_checked_install(config, commit_op, staged, &offsets_wire, &partition_dir)
+ .apply_checked_install(
+ config,
+ commit_op,
+ staged,
+ &offsets_wire,
+ &planned_offsets,
+ &partition_dir,
+ next_offset,
+ )
.await;
if outcome.is_err() {
+ discard_offset_writes(&planned_offsets).await;
// A mutate-phase failure can leave the log drained or half
// rebuilt while the disk already holds any prefix of the new
// chain. Converge BOTH the live state and the disk to an empty,
@@ -2382,14 +2626,16 @@ where
/// caller converges from. Split out so the convergence handling cannot
/// be forgotten on a new error path. Runs under the caller's write-lock
/// guard.
- #[allow(clippy::too_many_lines)]
+ #[allow(clippy::too_many_lines, clippy::too_many_arguments)]
async fn apply_checked_install(
&mut self,
config: &PartitionsConfig,
commit_op: u64,
staged: Vec<StagedSegmentMeta>,
offsets_wire: &ConsumerOffsetsWire,
+ planned_offsets: &[PlannedOffsetWrite],
partition_dir: &str,
+ next_offset: u64,
) -> Result<PartitionInstallOutcome, PartitionInstallError> {
// Sweep staging strays a dead earlier attempt left behind, keeping
// only what THIS install is about to rename. Bounded disk hygiene;
@@ -2646,21 +2892,20 @@ where
// must not rewind every transferred offset to 0 -- a durable,
// client-visible rewind the replicas would then disagree on.
let installed_end = staged.last().map(|meta| meta.end_offset);
- let next_offset = offsets_wire
- .next_offset
- .max(installed_end.map_or(0, |end| end + 1));
- let mut offsets_written = true;
// A key that fails the u32 narrowing would strand its old offset
// file's delete, which boot can then resurrect: unreachable while
// keys are minted from u32 wire ids, so assert it.
- let old_consumer_paths: Vec<String> = {
+ let old_consumer_paths: Vec<(ConsumerKind, u32, String)> = {
let guard = self.consumer_offsets.pin();
- let mut paths: Vec<String> = guard
+ let mut paths: Vec<(ConsumerKind, u32, String)> = guard
.iter()
.filter_map(|(key, _)| {
let narrowed = u32::try_from(*key).ok();
debug_assert!(narrowed.is_some(), "consumer offset key {key} exceeds u32");
- narrowed.and_then(|id| self.persisted_offset_path(ConsumerKind::Consumer, id))
+ narrowed.and_then(|id| {
+ self.persisted_offset_path(ConsumerKind::Consumer, id)
+ .map(|path| (ConsumerKind::Consumer, id, path))
+ })
})
.collect();
guard.clear();
@@ -2669,15 +2914,18 @@ where
// and a purged origin offering `next_offset = 0` drops every
// incoming entry, so a map-only sweep leaves the old table for boot
// to resurrect.
- paths.extend(strayed_offset_files(
- self.consumer_offsets_path.as_deref(),
- &offsets_wire.consumers,
- ));
+ paths.extend(
+ strayed_offset_files(self.consumer_offsets_path.as_deref())
+ .into_iter()
+ .filter_map(|path| {
+ numeric_offset_id(&path).map(|id| (ConsumerKind::Consumer, id, path))
+ }),
+ );
paths
};
- let old_group_paths: Vec<String> = {
+ let old_group_paths: Vec<(ConsumerKind, u32, String)> = {
let guard = self.consumer_group_offsets.pin();
- let mut paths: Vec<String> = guard
+ let mut paths: Vec<(ConsumerKind, u32, String)> = guard
.iter()
.filter_map(|(key, _)| {
let narrowed = u32::try_from(key.0).ok();
@@ -2686,130 +2934,125 @@ where
"consumer group offset key {} exceeds u32",
key.0
);
- narrowed
- .and_then(|id| self.persisted_offset_path(ConsumerKind::ConsumerGroup, id))
+ narrowed.and_then(|id| {
+ self.persisted_offset_path(ConsumerKind::ConsumerGroup, id)
+ .map(|path| (ConsumerKind::ConsumerGroup, id, path))
+ })
})
.collect();
guard.clear();
- paths.extend(strayed_offset_files(
- self.consumer_group_offsets_path.as_deref(),
- &offsets_wire.groups,
- ));
+ paths.extend(
+ strayed_offset_files(self.consumer_group_offsets_path.as_deref())
+ .into_iter()
+ .filter_map(|path| {
+ numeric_offset_id(&path).map(|id| (ConsumerKind::ConsumerGroup, id, path))
+ }),
+ );
paths
};
- for path in old_consumer_paths.into_iter().chain(old_group_paths) {
- if let Err(error) = delete_persisted_offset(&path).await {
- // Not fatal, but not silent either: a stranded file is an id
- // absent from the NEW table (matching ids get overwritten at
- // the same path), and boot resurrects it. Sharpest after a
- // purged origin ships `next_offset = 0`, where the clamp drops
- // every incoming entry and the whole old table survives while
- // the install still reports success.
- tracing::warn!(
- target: "iggy.partitions.diag",
- plane = "partitions",
- namespace_raw = self.consensus().group(),
- path = %path,
- %error,
- "failed to unlink a superseded consumer-offset file during install"
- );
+ let mut offset_dirs_changed = [false; 2];
+ let planned_ids: HashSet<_> = planned_offsets
+ .iter()
+ .map(|write| (write.kind, write.id))
+ .collect();
+ // Replacements atomically overwrite their old files. Only keys absent
+ // from the clamped plan require unlinking, including every key when
+ // the incoming message frontier is empty.
+ let old_paths: HashMap<_, _> = old_consumer_paths
+ .into_iter()
+ .chain(old_group_paths)
+ .filter(|(kind, id, _)| !planned_ids.contains(&(*kind, *id)))
+ .map(|(kind, id, path)| ((kind, id), path))
+ .collect();
+ for ((kind, consumer_id), path) in old_paths {
+ // An obsolete authoritative file must not survive a successful
+ // install because boot would reload it outside the incoming table.
+ match delete_persisted_offset(&path).await {
+ Ok(removed) => {
+ if removed {
+ offset_dirs_changed[consumer_kind_index(kind)] = true;
+ }
+ self.consumer_offset_capacity_for(kind)
+ .clear_stranded(consumer_id);
+ }
+ Err(error) => {
+ self.consumer_offset_capacity_for(kind)
+ .record_stranded(consumer_id);
+ tracing::warn!(
+ target: "iggy.partitions.diag",
+ plane = "partitions",
+ namespace_raw = self.consensus().group(),
+ path,
+ consumer_id,
+ %error,
+ "install could not remove a superseded consumer offset file"
+ );
+ return Err(PartitionInstallError::OffsetPersistence {
+ path,
+ source: error,
+ });
+ }
}
}
- self.persisted_offsets.borrow_mut().clear();
+ self.durable_consumer_offsets.clear();
self.pending_consumer_offset_commits.clear();
+ self.queued_auto_commit_reservations.borrow_mut().clear();
+ self.consumer_offset_capacity
+ .rebuild(&self.durable_consumer_offsets, std::iter::empty());
+ self.consumer_group_offset_capacity
+ .rebuild(&self.durable_consumer_offsets, std::iter::empty());
self.last_polled_offsets.pin().clear();
- // `None` when the group's offset space is empty (`next_offset == 0`,
- // a purged origin): clamping every transferred offset to 0 would tell
- // each consumer it consumed offset 0 on a partition that never minted
- // one, so a `Next` poll skips the first message. Dropping the entries
- // is what "no offsets yet" means.
- let clamp = |offset: u64| next_offset.checked_sub(1).map(|last| offset.min(last));
- if self.consumer_offsets_path.is_none() || self.consumer_group_offsets_path.is_none() {
- // Nothing to write the transferred table into: unreachable via
- // the server boot paths (they always configure storage), but if
- // it ever fires the table was dropped and the flag must say so.
- offsets_written = false;
- }
- // Both maps are populated first (no await, so nothing borrows across
- // one), then the files are written in capped batches. One await per
- // file put a rejoin carrying thousands of consumers on the pump for
- // thousands of sequential open + write + optional fsync round trips;
- // the tick's superblock pre-pass sets the precedent for the width.
- // The dedup slice is memory-only, so it installs here with the maps
- // rather than being written anywhere. No frontier fence is needed: the
- // install lifts `commit_min` to the offer's `commit_op`, so the commit
- // walk that follows starts strictly above everything this artifact
- // covers, and `record_commit` is idempotent besides.
+ // The replacement siblings were written and data-synced before any
+ // segment mutation. Finalize only their directory entries here, then
+ // publish the matching maps and durable membership.
self.dedup_mut()
.install_watermarks(offsets_wire.dedup.iter().copied());
- let mut planned: Vec<PlannedOffsetWrite> =
- Vec::with_capacity(offsets_wire.consumers.len() + offsets_wire.groups.len());
- if let Some(dir) = self.consumer_offsets_path.clone() {
- for (id, offset) in &offsets_wire.consumers {
- let Some(value) = clamp(*offset) else {
- continue;
- };
- let entry = ConsumerOffset::default_for_consumer(*id, &dir);
- entry.offset.store(value, Ordering::Release);
- let path = entry.path.clone();
- self.consumer_offsets.pin().insert(*id as usize, entry);
- planned.push(PlannedOffsetWrite {
- kind: ConsumerKind::Consumer,
- id: *id,
- path,
- value,
- });
- }
- }
- if let Some(dir) = self.consumer_group_offsets_path.clone() {
- for (id, offset) in &offsets_wire.groups {
- let Some(value) = clamp(*offset) else {
- continue;
- };
- let group_id = ConsumerGroupId(*id as usize);
- let entry = ConsumerOffset::default_for_consumer_group(group_id, &dir);
- entry.offset.store(value, Ordering::Release);
- let path = entry.path.clone();
- self.consumer_group_offsets.pin().insert(group_id, entry);
- planned.push(PlannedOffsetWrite {
- kind: ConsumerKind::ConsumerGroup,
- id: *id,
- path,
- value,
- });
- }
- }
- let enforce_fsync = self.consumer_offset_enforce_fsync;
- for batch in planned.chunks(OFFSET_PERSIST_CONCURRENCY) {
- let writes = batch.iter().map(|write| async move {
- let written = persist_offset(&write.path, write.value, enforce_fsync)
- .await
- .is_ok();
- (written, write.kind, write.id, write.value)
- });
- for (written, kind, id, value) in futures::future::join_all(writes).await {
- if written {
- self.persisted_offsets
- .borrow_mut()
- .insert((kind, id), value);
- } else {
- offsets_written = false;
+ for write in planned_offsets {
+ // A rename failure after the segment swap leaves an incomplete
+ // install. Propagate it to convergence rather than acknowledge
+ // mixed state or retry a standalone directory barrier.
+ commit_offset_replacement(&write.path)
+ .await
+ .map_err(|source| PartitionInstallError::OffsetPersistence {
+ path: write.path.clone(),
+ source,
+ })?;
+ offset_dirs_changed[consumer_kind_index(write.kind)] = true;
+ let entry = ConsumerOffset::new(write.kind, write.id, write.value, write.path.clone());
+ match write.kind {
+ ConsumerKind::Consumer => {
+ self.consumer_offsets.pin().insert(write.id as usize, entry);
+ }
+ ConsumerKind::ConsumerGroup => {
+ self.consumer_group_offsets
+ .pin()
+ .insert(ConsumerGroupId(write.id as usize), entry);
}
}
- }
- // Directory fsync so the OLD files' unlinks stick: without it a
- // crash right after install resurrects the pre-transfer offset
- // files at boot. The per-file content durability stays governed by
- // `consumer_offset_enforce_fsync` like every other offset commit.
- for dir in self
- .consumer_offsets_path
- .clone()
- .into_iter()
- .chain(self.consumer_group_offsets_path.clone())
- {
- if fsync_dir(&dir).await.is_err() {
- offsets_written = false;
+ self.durable_consumer_offsets.record_explicit(
+ write.kind,
+ write.id,
+ write.value,
+ write.value,
+ );
+ self.consumer_offset_capacity_for(write.kind)
+ .clear_stranded(write.id);
+ }
+ // One observation per changed directory. Retrying with a newly opened
+ // handle can mask the writeback error that the first fsync consumed.
+ for (changed, dir) in offset_dirs_changed.into_iter().zip([
+ self.consumer_offsets_path.as_deref(),
+ self.consumer_group_offsets_path.as_deref(),
+ ]) {
+ if changed {
+ let dir = dir.expect("planned offset directory was validated before mutation");
+ fsync_dir(dir)
+ .await
+ .map_err(|source| PartitionInstallError::SwapIo {
+ path: dir.to_owned(),
+ source,
+ })?;
}
}
@@ -2862,8 +3105,8 @@ where
// would make a restart re-purge the just-installed data and pull it
// all over again. A write failure only re-opens that restart window
// (the wipe-then-retransfer is self-healing, peers keep the data),
- // so it degrades like the offset writes above instead of failing the
- // install.
+ // so it is reported separately from the mandatory offset writes.
+ let mut purge_generation_recorded = true;
if offsets_wire.purge_generation > self.applied_purge_generation
&& let Some(dir) = self.partition_dir.clone()
{
@@ -2885,7 +3128,7 @@ where
generation; a restart before the next purge records it will \
re-purge and re-transfer this partition"
);
- offsets_written = false;
+ purge_generation_recorded = false;
}
}
self.applied_purge_generation = self
@@ -2926,7 +3169,7 @@ where
Ok(PartitionInstallOutcome {
applied_commit_op: commit_op,
- offsets_written,
+ purge_generation_recorded,
})
}
@@ -2944,6 +3187,7 @@ where
/// [`iggy_common::IggyError`] when the sweep or the empty plant fails;
/// the partition then has no serviceable chain and the caller must
/// fence it (see [`PartitionInstallError::ConvergeFailed`]).
+ #[allow(clippy::too_many_lines)]
async fn converge_to_empty_after_failed_install(
&mut self,
config: &PartitionsConfig,
@@ -2959,6 +3203,62 @@ where
}
self.log.journal().inner.clear_all();
self.log.journal_mut().info = crate::log::JournalInfo::default();
+ self.consumer_offsets.pin().clear();
+ self.consumer_group_offsets.pin().clear();
+ self.last_polled_offsets.pin().clear();
+ self.durable_consumer_offsets.clear();
+ self.pending_consumer_offset_commits.clear();
+ self.queued_auto_commit_reservations.borrow_mut().clear();
+ for kind in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup] {
+ self.consumer_offset_capacity_for(kind)
+ .rebuild(&self.durable_consumer_offsets, std::iter::empty());
+ }
+ for (kind, dir) in [
+ (ConsumerKind::Consumer, self.consumer_offsets_path.as_ref()),
+ (
+ ConsumerKind::ConsumerGroup,
+ self.consumer_group_offsets_path.as_ref(),
+ ),
+ ] {
+ let Some(dir) = dir else { continue };
+ for entry in offset_dir_entries(dir) {
+ match entry {
+ OffsetDirEntry::Replacement(path) => {
+ if let Err(error) = compio::fs::remove_file(&path).await {
+ tracing::warn!(
+ path,
+ %error,
+ "could not remove an abandoned offset replacement"
+ );
+ }
+ }
+ OffsetDirEntry::Offset { id, path } => {
+ // A remaining authoritative file prevents convergence.
+ match retry_offset_mutation(|| delete_persisted_offset(&path)).await {
+ Ok(_) => self.consumer_offset_capacity_for(kind).clear_stranded(id),
+ Err(error) => {
+ self.consumer_offset_capacity_for(kind).record_stranded(id);
+ tracing::warn!(
+ path,
+ consumer_id = id,
+ %error,
+ "converge could not remove a consumer offset file"
+ );
+ return Err(error);
+ }
+ }
+ }
+ }
+ }
+ // No `exists()` probe: that is a blocking stat on the pump. A
+ // directory the unlinks emptied and removed has nothing left to
+ // make durable.
+ match fsync_dir(dir).await {
+ Ok(()) => {}
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
+ Err(_) => return Err(iggy_common::IggyError::CannotSyncFile),
+ }
+ }
// Every segment and staging file this partition had is about to be
// unlinked, so neither memo can describe anything real afterwards. The
// checksum map's own doc promises the clear happens here; without it the
@@ -3295,35 +3595,60 @@ pub fn offered_purge_generation(offsets_bytes: &[u8]) -> u64 {
.unwrap_or_default()
}
-/// Offset files under `dir` whose id is absent from `incoming`.
-///
-/// The install's own map cannot name these: a pre-purge offset op replayed by
-/// journal repair persists a file this incarnation never held, and a purged
-/// origin offers `next_offset = 0`, which drops every incoming entry. Left
-/// behind, boot hydrates them back.
+/// One regular file of a consumer-offset directory, classified by name.
+enum OffsetDirEntry {
+ /// A sibling an atomic replacement left behind.
+ Replacement(String),
+ /// A bare-u32 offset file and its id.
+ Offset { id: u32, path: String },
+}
+
+/// The offset files and abandoned replacements under `dir`, in one pass.
///
-/// A file whose name is not a bare u32 is left alone rather than guessed at:
-/// every offset file is named by its id, so anything else is not ours.
-pub(crate) fn strayed_offset_files(dir: Option<&str>, incoming: &[(u32, u64)]) -> Vec<String> {
- let Some(dir) = dir else {
- return Vec::new();
- };
+/// A file whose name is neither a bare u32 nor a replacement sibling is left
+/// alone rather than guessed at: every offset file is named by its id, so
+/// anything else is not ours.
+fn offset_dir_entries(dir: &str) -> Vec<OffsetDirEntry> {
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
};
entries
.filter_map(Result::ok)
.filter_map(|entry| {
+ if !entry.file_type().ok()?.is_file() {
+ return None;
+ }
let name = entry.file_name().into_string().ok()?;
+ let path = format!("{dir}/{name}");
+ if offset_replacement_id(&name).is_some() {
+ return Some(OffsetDirEntry::Replacement(path));
+ }
let id: u32 = name.parse().ok()?;
- incoming
- .iter()
- .all(|(incoming_id, _)| *incoming_id != id)
- .then(|| format!("{dir}/{name}"))
+ Some(OffsetDirEntry::Offset { id, path })
+ })
+ .collect()
+}
+
+/// Every offset file under `dir`.
+///
+/// The live map cannot name these: a pre-purge offset op replayed by journal
+/// repair persists a file this incarnation never held. Left behind, boot
+/// hydrates them back.
+pub(crate) fn strayed_offset_files(dir: Option<&str>) -> Vec<String> {
+ dir.map(offset_dir_entries)
+ .unwrap_or_default()
+ .into_iter()
+ .filter_map(|entry| match entry {
+ OffsetDirEntry::Offset { path, .. } => Some(path),
+ OffsetDirEntry::Replacement(_) => None,
})
.collect()
}
+pub(crate) fn numeric_offset_id(path: &str) -> Option<u32> {
+ Path::new(path).file_name()?.to_str()?.parse().ok()
+}
+
/// Stamp over every `SEGMENT_LOG` entry of a manifest, keying
/// [`ReuseScanMemo`]. Equal digests mean the two offers expect byte-identical
/// staged files, so a scan already done for one answers the other; the offsets
diff --git a/core/partitions/src/types.rs b/core/partitions/src/types.rs
index f2a3bd791..0c720dd71 100644
--- a/core/partitions/src/types.rs
+++ b/core/partitions/src/types.rs
@@ -366,6 +366,7 @@ impl Default for PartitionPathLayout {
/// Mirrors the relevant fields from the server's `PartitionConfig` and
/// `SegmentConfig` (`core/server/src/configs/system.rs`).
#[derive(Debug, Clone)]
+#[allow(clippy::struct_excessive_bools)]
pub struct PartitionsConfig {
/// Flush journal to disk when it accumulates this many messages.
pub messages_required_to_save: u32,
@@ -373,6 +374,10 @@ pub struct PartitionsConfig {
pub size_of_messages_required_to_save: IggyByteSize,
/// Whether to enforce fsync after writes.
pub enforce_fsync: bool,
+ /// Whether consumer-offset files are written crash-safe (data-synced,
+ /// renamed, directory synced). Independent of `enforce_fsync`, which
+ /// governs message and index files.
+ pub consumer_offset_enforce_fsync: bool,
/// Whether a disk poll verifies each batch's `batch_checksum` against the bytes
/// it just read.
///
diff --git a/core/sdk/Cargo.toml b/core/sdk/Cargo.toml
index 09ef84d03..93993589c 100644
--- a/core/sdk/Cargo.toml
+++ b/core/sdk/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "iggy"
-version = "0.11.0-edge.6"
+version = "0.11.0-edge.7"
description = "Iggy is the persistent message streaming platform written in Rust, supporting QUIC, TCP and HTTP transport protocols, capable of processing millions of messages per second."
edition = "2024"
rust-version.workspace = true
diff --git a/core/sdk/src/clients/consumer.rs b/core/sdk/src/clients/consumer.rs
index 1f38f2c76..e6f66ba49 100644
--- a/core/sdk/src/clients/consumer.rs
+++ b/core/sdk/src/clients/consumer.rs
@@ -466,10 +466,12 @@ unsafe impl Sync for IggyConsumer {}
/// comes back empty is not an error and not the end of the stream, it just means nothing new has
/// arrived yet.
///
-/// A failed request is yielded as `Some(Err(..))` and leaves the consumer usable, while the next call
-/// retries. Connection and authentication failures pause polling until the client has reconnected
-/// and signed in again, which the consumer handles automatically. Hence, deciding when to give up on
-/// repeated errors is up to you.
+/// A failed poll request waits [`polling_retry_interval()`] before yielding `Some(Err(..))` and leaves
+/// the consumer usable for the next call. This delay also applies to terminal server errors and when
+/// the ordinary poll interval is disabled. Connection and authentication failures are yielded at once
+/// and pause polling until the client has reconnected and signed in again, which the consumer handles
+/// automatically; the next call parks for [`polling_retry_interval()`] while polling is paused. Hence,
+/// deciding when to give up on repeated errors is up to you.
///
/// For a boilerplate implementation of such a loop Iggy provides [`IggyConsumerMessageExt::consume_messages`].
///
@@ -548,7 +550,7 @@ unsafe impl Sync for IggyConsumer {}
/// | [`allow_replay()`] | off | whether a message can be handed over again |
/// | [`auto_join_consumer_group()`] | on | joining the group during [`init()`](Self::init) and again whenever the membership is lost. With [`do_not_auto_join_consumer_group()`] joining is up to the caller, and a poll without a membership fails with [`IggyError::ConsumerGroupMemberNotFound`] |
/// | [`create_consumer_group_if_not_exists()`] | on | creating the group when it is missing |
-/// | [`polling_retry_interval()`] | one second | wait between attempts while polling is blocked or the member holds no partitions |
+/// | [`polling_retry_interval()`] | one second | delay before yielding poll errors other than connection and authentication failures, and between attempts while polling is blocked or the member holds no partitions |
/// | [`init_retries()`] | none, one second apart | retries when the stream or topic is missing at [`init()`](Self::init) |
/// | [`offset_drain_timeout()`] | five seconds | how long [`shutdown()`](Self::shutdown) waits for pending commits |
/// | [`encryptor()`] | inherited from the client | decrypting payloads and user headers, see [Encryption](#encryption) |
@@ -618,6 +620,14 @@ unsafe impl Sync for IggyConsumer {}
/// [`topic()`]: crate::prelude::IggyConsumerBuilder::topic
/// [`without_encryptor()`]: crate::prelude::IggyConsumerBuilder::without_encryptor
/// [`without_poll_interval()`]: crate::prelude::IggyConsumerBuilder::without_poll_interval
+///
+/// A server-side auto-commit poll can fail with `TooManyConsumerOffsets` when
+/// its consumer needs a new offset key at the partition's configured limit.
+/// The rejected poll returns no messages. Other auto-commit modes store the
+/// same key through a client request. Background and shutdown stores log a
+/// capacity failure but do not yield it through this stream. Only
+/// [`AutoCommit::Disabled`] avoids automatic key allocation. Existing keys
+/// remain usable.
pub struct IggyConsumer {
initialized: bool,
shutdown: Arc<AtomicBool>,
@@ -1351,8 +1361,11 @@ impl IggyConsumer {
return Ok(PolledMessages::empty());
}
- // Handle connection/auth errors - disable polling until event task re-enables
- // it after reconnection and rejoin complete
+ // Connection and auth errors: disable polling until the event task
+ // re-enables it after reconnection and rejoin complete. Yielded at
+ // once: the next poll already parks on `can_poll`, so a retry sleep
+ // here would only delay the caller's view of an error it does not
+ // act on.
if matches!(
error,
IggyError::Disconnected | IggyError::Unauthenticated | IggyError::StaleClient
@@ -1361,9 +1374,10 @@ impl IggyConsumer {
if is_consumer_group {
joined_consumer_group.store(false, ORDERING);
}
- trace!("Retrying to poll messages in {retry_interval}...");
- sleep(retry_interval.get_duration()).await;
+ return Err(error);
}
+ trace!("Retrying to poll messages in {retry_interval}...");
+ sleep(retry_interval.get_duration()).await;
Err(error)
}
}
diff --git a/core/sdk/src/leader_aware.rs b/core/sdk/src/leader_aware.rs
index 2d1c61be8..0319451e2 100644
--- a/core/sdk/src/leader_aware.rs
+++ b/core/sdk/src/leader_aware.rs
@@ -355,6 +355,8 @@ fn normalize_address(addr: &str) -> String {
/// failed dial cannot cycle the request back through nodes it already tried.
#[derive(Debug)]
pub(crate) struct RosterWalk {
+ /// Whether the roster named at least one node when the walk was built.
+ roster_known: bool,
remaining: VecDeque<String>,
attempted: Vec<String>,
}
@@ -382,6 +384,7 @@ impl RosterWalk {
Self {
remaining: ordered,
attempted: vec![current.to_owned()],
+ roster_known: !roster.is_empty(),
}
}
@@ -406,6 +409,13 @@ impl RosterWalk {
self.attempted.push(endpoint.clone());
Some(endpoint)
}
+
+ /// True only when the roster itself names one node. An empty roster (its
+ /// discovery failed) also leaves nothing to walk, but replaying that one
+ /// address would be a guess, not a decision.
+ pub(crate) fn is_single_endpoint(&self) -> bool {
+ self.roster_known && self.remaining.is_empty() && self.attempted.len() == 1
+ }
}
/// Coordinates callers of one client's complete connect and authentication
@@ -777,6 +787,10 @@ mod tests {
assert_eq!(walk.next().as_deref(), Some("10.0.0.2:8090"));
assert_eq!(walk.next().as_deref(), Some("10.0.0.3:8090"));
assert_eq!(walk.next(), None);
+ assert!(
+ !walk.is_single_endpoint(),
+ "exhausting a cluster does not make it a single node"
+ );
let mut from_last = RosterWalk::new("10.0.0.3:8090", &roster);
assert_eq!(from_last.next().as_deref(), Some("10.0.0.1:8090"));
@@ -784,6 +798,17 @@ mod tests {
assert_eq!(from_last.next(), None);
}
+ #[test]
+ fn given_single_endpoint_roster_when_exhausted_should_allow_local_retry() {
+ assert!(!RosterWalk::new("127.0.0.1:8090", &[]).is_single_endpoint());
+ let mut walk = RosterWalk::new("127.0.0.1:8090", &["localhost:8090".to_owned()]);
+ assert!(walk.is_single_endpoint());
+ assert_eq!(walk.next(), None);
+ assert!(walk.is_single_endpoint());
+ walk.record_attempt("127.0.0.2:8090");
+ assert!(!walk.is_single_endpoint());
+ }
+
#[test]
fn a_roster_walk_never_revisits_redirects_or_duplicate_spellings() {
let mut walk = RosterWalk::new(
diff --git a/core/sdk/src/quic/quic_client.rs b/core/sdk/src/quic/quic_client.rs
index 5dcadc1d6..e0493c946 100644
--- a/core/sdk/src/quic/quic_client.rs
+++ b/core/sdk/src/quic/quic_client.rs
@@ -162,11 +162,12 @@ impl BinaryTransport for QuicClient {
&& self.config.reconnection.enabled
&& !matches!(self.config.auto_login, AutoLogin::Disabled)
{
- let _routing_guard =
+ let routing_guard =
match tokio::time::timeout_at(roster_deadline, self.routing_lock.lock()).await {
Ok(guard) => guard,
Err(_) => return Err(IggyError::TransientNotAccepted),
};
+ let mut routing_guard = Some(routing_guard);
let overall_deadline = roster_deadline;
// A concurrent refused request may have completed the movement
// while this request waited for the gate.
@@ -217,8 +218,17 @@ impl BinaryTransport for QuicClient {
(target, false)
} else if let Some(next) = roster_walk.as_mut().and_then(RosterWalk::next) {
(next, true)
+ } else if roster_walk
+ .as_ref()
+ .is_some_and(RosterWalk::is_single_endpoint)
+ {
+ // A single-node roster can still be converging a newly
+ // committed partition. Retry this explicitly unadmitted
+ // request on the current endpoint within the same budget.
+ drop(routing_guard.take());
+ (current, false)
} else {
- break;
+ return Err(IggyError::TransientNotAccepted);
};
loop {
diff --git a/core/sdk/src/tcp/tcp_client.rs b/core/sdk/src/tcp/tcp_client.rs
index 154670833..b559f81ba 100644
--- a/core/sdk/src/tcp/tcp_client.rs
+++ b/core/sdk/src/tcp/tcp_client.rs
@@ -1280,8 +1280,23 @@ impl TcpClient {
return Err(IggyError::TransientNotAccepted);
}
+ if roster_walk
+ .as_ref()
+ .is_some_and(RosterWalk::is_single_endpoint)
+ {
+ // Discovery already proved there is no routing choice.
+ // Retry without reacquiring the lock so reconnects and
+ // unrelated requests do not wait out this deadline.
+ drop(routing_guard.take());
+ continue;
+ }
+
if routing_guard.is_none() {
- routing_guard = Some(self.routing_lock.lock().await);
+ routing_guard = Some(
+ tokio::time::timeout_at(overall_deadline, self.routing_lock.lock())
+ .await
+ .map_err(|_| IggyError::TransientNotAccepted)?,
+ );
// A concurrent refused request may have moved the
// shared client while this request waited.
continue;
@@ -1323,6 +1338,16 @@ impl TcpClient {
// hops would bounce the request between two nodes and
// never reach the rest of the roster.
(next, true)
+ } else if roster_walk
+ .as_ref()
+ .is_some_and(RosterWalk::is_single_endpoint)
+ {
+ // Partition materialisation can outlast the short retry
+ // window on a single node. No routing change is needed.
+ // Subsequent refusals take the lock-free local retry
+ // branch above rather than reacquiring this guard.
+ drop(routing_guard.take());
+ continue;
} else {
return Err(IggyError::TransientNotAccepted);
};
diff --git a/core/sdk/src/websocket/websocket_client.rs b/core/sdk/src/websocket/websocket_client.rs
index 2a22683e0..1ecc2997b 100644
--- a/core/sdk/src/websocket/websocket_client.rs
+++ b/core/sdk/src/websocket/websocket_client.rs
@@ -155,11 +155,12 @@ impl BinaryTransport for WebSocketClient {
&& self.config.reconnection.enabled
&& !matches!(self.config.auto_login, AutoLogin::Disabled)
{
- let _routing_guard =
+ let routing_guard =
match tokio::time::timeout_at(roster_deadline, self.routing_lock.lock()).await {
Ok(guard) => guard,
Err(_) => return Err(IggyError::TransientNotAccepted),
};
+ let mut routing_guard = Some(routing_guard);
let overall_deadline = roster_deadline;
// A concurrent refused request may have completed the movement
// while this request waited for the gate.
@@ -210,8 +211,17 @@ impl BinaryTransport for WebSocketClient {
(target, false)
} else if let Some(next) = roster_walk.as_mut().and_then(RosterWalk::next) {
(next, true)
+ } else if roster_walk
+ .as_ref()
+ .is_some_and(RosterWalk::is_single_endpoint)
+ {
+ // A single-node roster can still be converging a newly
+ // committed partition. Retry this explicitly unadmitted
+ // request on the current endpoint within the same budget.
+ drop(routing_guard.take());
+ (current, false)
} else {
- break;
+ return Err(IggyError::TransientNotAccepted);
};
loop {
diff --git a/core/server/Cargo.toml b/core/server/Cargo.toml
index 1d5911488..553d8d9ff 100644
--- a/core/server/Cargo.toml
+++ b/core/server/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "server"
-version = "0.9.0-edge.6"
+version = "0.9.0-edge.7"
edition = "2024"
license = "Apache-2.0"
publish = false
diff --git a/core/server/config.toml b/core/server/config.toml
index e36912513..55a3ad506 100644
--- a/core/server/config.toml
+++ b/core/server/config.toml
@@ -1025,6 +1025,36 @@ prepare_queue_depth = 32
# actually sees, not the node's client total.
dedup_clients_max = 4096
+# Distinct durable consumer-offset keys a partition primary admits per kind.
+# Standalone consumers and consumer groups are counted separately. Existing
+# keys remain writable at the limit. A new key is rejected before consensus.
+# A non-empty auto_commit poll that needs a new offset key is also rejected
+# with TooManyConsumerOffsets and returns no messages. A poll whose auto_commit
+# cannot be submitted (the owning shard's inbox is full, or the partition
+# changed primary during the read) is rejected with TransientNotAccepted, also
+# without messages; both are retriable. Polls with auto_commit disabled do not
+# allocate offset keys and remain available.
+# UPGRADE: existing files are loaded even above this limit, but new keys then
+# remain blocked until offsets are explicitly deleted or this limit is raised.
+# Standalone offsets have no automatic expiry. Reuse stable consumer ids and
+# count existing numeric offset files per partition and kind before upgrading.
+# The environment override is IGGY_PARTITION_CONSUMER_OFFSETS_MAX.
+# UPGRADE: on replicated partitions, offset stores and deletes carrying NoAck
+# wait for VSR commit. First-party SDK offset methods request Quorum.
+# Must be > 0 and <= 262144.
+consumer_offsets_max = 4096
+
+# Whether consumer-offset files are written crash-safe. On, every committed
+# offset store writes a sibling file, fdatasyncs it and renames it over the
+# prior cursor, and the offsets directory is fsynced once per commit walk before
+# any reply in that walk is sent. Independent of the topic's enforce_fsync,
+# which governs message and index files. Off, the file is rewritten in place
+# with no sync. A lost or torn cursor can cause replay from the earliest retained
+# data. On, the filesystem must support both file and directory sync. A failed
+# required barrier is reported as a failure, even if the mutation is visible.
+# The environment override is IGGY_PARTITION_CONSUMER_OFFSET_ENFORCE_FSYNC.
+consumer_offset_enforce_fsync = false
+
# How many offsets a partition claims in its superblock ahead of the mint
# counter before it will append, so a crash-restarted replica resumes above
# every offset it confirmed to a client instead of re-minting it for a different
diff --git a/core/server/src/boot/recovery.rs b/core/server/src/boot/recovery.rs
index 46558ffc7..812e4ee93 100644
--- a/core/server/src/boot/recovery.rs
+++ b/core/server/src/boot/recovery.rs
@@ -122,6 +122,7 @@ pub(in crate::boot) async fn build_shard_for_thread(
iggy_common::DEFAULT_SIZE_OF_MESSAGES_REQUIRED_TO_SAVE,
),
enforce_fsync: iggy_common::DEFAULT_ENFORCE_FSYNC,
+ consumer_offset_enforce_fsync: config.partition.consumer_offset_enforce_fsync,
validate_checksum: config.system.partition.validate_checksum,
segment_size: IggyByteSize::from(iggy_common::DEFAULT_SEGMENT_SIZE),
preallocate_segments: iggy_common::DEFAULT_PREALLOCATE_SEGMENTS,
@@ -331,6 +332,16 @@ const _: () = assert!(
const _: () = assert!(
configs::partition::PARTITION_DEDUP_CLIENTS_DEFAULT == consensus::PARTITION_DEDUP_CLIENTS_MAX
);
+const _: () = assert!(
+ configs::partition::PARTITION_CONSUMER_OFFSETS_DEFAULT
+ == partitions::DEFAULT_CONSUMER_OFFSETS_MAX
+);
+const _: () = assert!(
+ 4 * configs::partition::PARTITION_CONSUMER_OFFSETS_CEILING
+ <= partitions::CONSUMER_OFFSETS_ENTRIES_MAX as usize,
+ "four ceilings fill the transfer decoder's entry budget exactly, with no headroom left; raise \
+ CONSUMER_OFFSETS_ENTRIES_MAX before raising PARTITION_CONSUMER_OFFSETS_CEILING"
+);
const _: () =
assert!(configs::metadata::DEFAULT_METADATA_CLIENTS_TABLE_MAX == consensus::CLIENTS_TABLE_MAX);
const _: () =
diff --git a/core/server/src/consumer_group.rs b/core/server/src/consumer_group.rs
index d4b77eb95..abeca570f 100644
--- a/core/server/src/consumer_group.rs
+++ b/core/server/src/consumer_group.rs
@@ -25,13 +25,12 @@
//! primary enriches the op here before replication, mirroring the PAT mint
//! in [`crate::pat`] and the password hash in [`crate::users`].
-use crate::responses::resolve_partition_namespace;
+use crate::responses::{resolve_offset_group_id, resolve_partition_namespace};
use crate::shell::{ShellBus, ShellShard};
use crate::wire::{request_body, rewrite_request_body};
use consensus::MetadataHandle;
use iggy_binary_protocol::PrepareHeader;
use iggy_binary_protocol::codec::{WireDecode, WireEncode};
-use iggy_binary_protocol::primitives::consumer::WireConsumer;
use iggy_binary_protocol::requests::consumer_groups::{
JoinConsumerGroupRequest as WireJoinConsumerGroupRequest,
LeaveConsumerGroupRequest as WireLeaveConsumerGroupRequest,
@@ -226,16 +225,21 @@ where
let body = request_body(&request);
// The store/delete ops differ only in the decode type; this collapses
// their identical decode -> resolve group id -> rewrite consumer id ->
- // re-encode bodies. A non-group consumer or unresolved group returns the
- // request untouched (the apply/read path handles the miss).
+ // re-encode bodies. Individual consumers pass through. A group identifier
+ // that metadata cannot resolve is rejected before it can create a raw file
+ // in the group-offset directory.
macro_rules! rewrite_group_offset {
($ty:ty) => {{
let mut wire = <$ty>::decode_from(body).map_err(|_| IggyError::InvalidCommand)?;
- let Some(group_id) =
- resolve_group_offset_id(shard, &wire.consumer, (&wire.stream_id, &wire.topic_id))
- else {
+ if wire.consumer.kind != KIND_CONSUMER_GROUP {
return Ok(request);
- };
+ }
+ let group_id = resolve_offset_group_id(
+ shard.plane.metadata().mux_stm.streams(),
+ &wire.stream_id,
+ &wire.topic_id,
+ &wire.consumer.id,
+ )?;
// The partition-plane group-offset key is u32 (see the documented
// ceiling on `Topic::next_consumer_group_id`). Clamp on the
// ~4-billion-creates overflow rather than panic this live
@@ -254,29 +258,3 @@ where
rewrite_request_body(&request, &rewritten)
}
-
-/// Resolve the monotonic group id for a group consumer-offset op, or `None` for
-/// an individual consumer (kind != 2) / unresolved group (leave the body as-is;
-/// the apply / read path handle the miss).
-fn resolve_group_offset_id<B, MJ, S, SB>(
- shard: &Rc<ShellShard<B, MJ, S, SB>>,
- consumer: &WireConsumer,
- namespace: (&WireIdentifier, &WireIdentifier),
-) -> Option<u64>
-where
- B: ShellBus,
- MJ: JournalHandle + 'static,
- MJ::Target: Journal<Entry = Message<PrepareHeader>, Header = PrepareHeader>,
- S: 'static,
- SB: SuperblockStore + 'static,
-{
- if consumer.kind != KIND_CONSUMER_GROUP {
- return None;
- }
- shard
- .plane
- .metadata()
- .mux_stm
- .streams()
- .resolve_consumer_group_id(namespace.0, namespace.1, &consumer.id)
-}
diff --git a/core/server/src/dispatch/mod.rs b/core/server/src/dispatch/mod.rs
index 50b40dcd2..662c25038 100644
--- a/core/server/src/dispatch/mod.rs
+++ b/core/server/src/dispatch/mod.rs
@@ -909,6 +909,7 @@ mod tests {
messages_required_to_save: 1,
size_of_messages_required_to_save: iggy_common::IggyByteSize::from(1024_u64),
enforce_fsync: false,
+ consumer_offset_enforce_fsync: false,
validate_checksum: true,
segment_size: iggy_common::IggyByteSize::from(1_048_576_u64),
preallocate_segments: false,
diff --git a/core/server/src/dispatch/partition.rs b/core/server/src/dispatch/partition.rs
index ac20090ab..76fcd985c 100644
--- a/core/server/src/dispatch/partition.rs
+++ b/core/server/src/dispatch/partition.rs
@@ -59,7 +59,7 @@ use iggy_binary_protocol::{
AckLevel, Command, KIND_CONSUMER_GROUP, Operation, RoutedRequestHeader, WireDecode, WireEncode,
WireIdentifier,
};
-use iggy_common::{IggyError, PollingStrategy, RESYNC_REQUIRED_PARTITION_SENTINEL};
+use iggy_common::{ConsumerKind, IggyError, PollingStrategy, RESYNC_REQUIRED_PARTITION_SENTINEL};
use journal::superblock::SuperblockStore;
use journal::{Journal, JournalHandle};
use message_bus::{AUTO_COMMIT_CLIENT_ID, BusMessage};
@@ -67,7 +67,10 @@ use metadata::impls::metadata::{
StreamsFrontend, build_truncate_partition_client_message,
build_truncate_partition_client_message_with_identifiers,
};
-use partitions::{AutoCommitApplied, PollPlan, PollingArgs, PollingConsumer};
+use partitions::{
+ AutoCommitApplied, ConsumerOffsetCapacityError, PollFragments, PollPlan, PollingArgs,
+ PollingConsumer,
+};
use server_common::Message;
use server_common::sharding::IggyNamespace;
use shard::shards_table::ShardsTable;
@@ -111,14 +114,8 @@ where
spawn_poll_io(Rc::clone(&shard), namespace, plan, reply);
}
Some(plan) => {
- let (fragments, current_offset, auto_commit) = plan.execute_resident();
- if let Some(applied) = auto_commit {
- submit_auto_commit(&shard, namespace, &applied);
- }
- let _ = reply.try_send(PartitionReadReply::Poll {
- fragments,
- current_offset,
- });
+ let result = poll_reply(&shard, namespace, plan.execute_resident());
+ let _ = reply.try_send(result);
}
}
}
@@ -190,7 +187,7 @@ fn spawn_poll_io<B, MJ, S, SB>(
// measures near-zero real time and never fires). Do not derive any
// replicated or reply value from it, or replay determinism breaks.
let poll_started = std::time::Instant::now();
- let (fragments, current_offset, auto_commit) = plan.execute().await;
+ let result = plan.execute().await;
let elapsed = poll_started.elapsed();
if elapsed > std::time::Duration::from_secs(1) {
warn!(
@@ -199,28 +196,67 @@ fn spawn_poll_io<B, MJ, S, SB>(
"slow partition poll; gather side may have timed out"
);
}
- // Fire-and-forget: the poll reply is not gated on the offset commit.
- if let Some(applied) = auto_commit {
- submit_auto_commit(&shard, namespace, &applied);
- }
- let _ = reply.try_send(PartitionReadReply::Poll {
- fragments,
- current_offset,
- });
+ let result = poll_reply(&shard, namespace, result);
+ let _ = reply.try_send(result);
});
}
+fn poll_reply<B, MJ, S, SB>(
+ shard: &Rc<ShellShard<B, MJ, S, SB>>,
+ namespace: IggyNamespace,
+ result: Result<(PollFragments, u64, Option<AutoCommitApplied>), ConsumerOffsetCapacityError>,
+) -> PartitionReadReply
+where
+ B: ShellBus,
+ MJ: JournalHandle + 'static,
+ MJ::Target: Journal<Entry = Message<PrepareHeader>, Header = PrepareHeader>,
+ S: 'static,
+ SB: SuperblockStore + 'static,
+{
+ match result {
+ Ok((fragments, current_offset, auto_commit)) => {
+ if let Some(applied) = auto_commit
+ && let Err(error) = submit_auto_commit(shard, namespace, applied)
+ {
+ PartitionReadReply::Rejected(error)
+ } else {
+ PartitionReadReply::Poll {
+ fragments,
+ current_offset,
+ }
+ }
+ }
+ Err(error) => {
+ if !error.uncertain {
+ shard.metrics().record_consumer_offset_denied(error.kind);
+ }
+ warn_auto_commit_capacity(namespace, error);
+ PartitionReadReply::Rejected(error.into())
+ }
+ }
+}
+
/// Replicate a poll's auto-committed offset through the partition consensus so
/// it survives failover, mirroring the explicit `StoreConsumerOffset` path: the
-/// same op code, submitted onto the owning shard's own pipeline. Best-effort and
-/// fire-and-forget -- the poll reply never waits on it, and a full inbox drops
-/// the op at WARN rather than backpressuring the reply.
+/// same op code, submitted onto the owning shard's own pipeline. The poll reply
+/// does not wait for commit, but a primary reserves cardinality before this
+/// submission and rejects the poll if the local inbox cannot accept it.
///
/// The partition plane admits writes on the primary only (it asserts so), and a
/// poll is served on whichever node owns the namespace locally, which may be a
-/// backup. So gate on primary status here and drop at WARN otherwise; auto-commit
+/// backup. So gate on primary status here. Auto-commit
/// is server-managed best-effort (at-least-once delivery), so a follower-served
-/// poll simply does not advance the durable offset.
+/// poll simply does not advance the durable offset. The same contract covers a
+/// local cursor that never became durable: when the per-kind live map is over
+/// its limit the partition evicts such a cursor, and that consumer's next
+/// `Next` poll restarts from offset 0.
+///
+/// A poll whose auto-commit cannot be submitted is answered
+/// `TransientNotAccepted` and returns no messages, even though the fragments
+/// were already read: the owning shard's inbox refused the frame, or the
+/// partition changed primary or incarnation during the read. Like the
+/// `TooManyConsumerOffsets` refusal at the key limit, it returns no batch.
+/// Transient refusals permit retry. Capacity refusals need available capacity.
///
/// Coalescing: an offset the partition's committed high-water already covers is
/// dropped without a consensus op (the steady state for a re-poll of committed
@@ -230,61 +266,86 @@ fn spawn_poll_io<B, MJ, S, SB>(
fn submit_auto_commit<B, MJ, S, SB>(
shard: &Rc<ShellShard<B, MJ, S, SB>>,
namespace: IggyNamespace,
- applied: &AutoCommitApplied,
-) where
+ applied: AutoCommitApplied,
+) -> Result<(), IggyError>
+where
B: ShellBus,
MJ: JournalHandle + 'static,
MJ::Target: Journal<Entry = Message<PrepareHeader>, Header = PrepareHeader>,
S: 'static,
SB: SuperblockStore + 'static,
{
- enum AutoCommitGate {
- Submit,
- Covered,
- NotPrimary,
- }
- let gate = shard
- .plane
- .partitions()
- .with_partition(&namespace, |partition| {
- let consensus = partition.consensus();
- if !(consensus.is_primary() && consensus.is_normal() && !consensus.is_transferring()) {
- AutoCommitGate::NotPrimary
- } else if partition.is_auto_commit_offset_covered(
- applied.kind,
- applied.consumer_id,
- applied.offset,
- ) {
- AutoCommitGate::Covered
- } else {
- AutoCommitGate::Submit
- }
- });
- match gate {
- Some(AutoCommitGate::Submit) => {}
- Some(AutoCommitGate::Covered) => return,
- Some(AutoCommitGate::NotPrimary) | None => {
- warn!(
+ // Everything inside is synchronous: `admit` rolls the eager cursor update
+ // back on `Err` in the same call, and no await may sit between the update
+ // and that rollback.
+ applied.admit(|applied| {
+ let primary = shard
+ .plane
+ .partitions()
+ .with_partition(&namespace, |partition| {
+ let consensus = partition.consensus();
+ if !partition.auto_commit_admission_ready(applied) {
+ return Err(IggyError::TransientNotAccepted);
+ }
+ Ok(consensus.is_primary() && consensus.is_normal() && !consensus.is_transferring())
+ });
+ if matches!(primary, None | Some(Err(_))) {
+ return Err(IggyError::TransientNotAccepted);
+ }
+ if primary == Some(Ok(false)) {
+ debug!(
namespace_raw = namespace.inner(),
"auto-commit offset not replicated: partition not primary on this node (best-effort)"
);
- return;
+ return Ok(());
}
- }
- let message = match build_auto_commit_request(namespace, applied) {
- Ok(message) => message,
- Err(error) => {
+ let reservation = match applied.reserve_durable() {
+ Ok(Some(reservation)) => reservation,
+ Ok(None) => return Ok(()),
+ Err(error) => {
+ if !error.uncertain {
+ shard.metrics().record_consumer_offset_denied(applied.kind);
+ }
+ warn_auto_commit_capacity(namespace, error);
+ return Err(error.into());
+ }
+ };
+ let message = build_auto_commit_request(namespace, applied).inspect_err(|error| {
warn!(
namespace_raw = namespace.inner(),
error = %error,
"failed to build auto-commit store-offset request"
);
- return;
- }
- };
- // Routes by namespace to this same (owning, primary) shard's inbox; the pump
- // admits it next turn exactly like a client store. `dispatch` never blocks.
- shard.dispatch(message.into_generic());
+ })?;
+ // Routes by namespace to this same owning primary shard's inbox. The
+ // pump admits it next turn exactly like a client store. `dispatch`
+ // never blocks.
+ shard
+ .submit_auto_commit_offset(message, reservation)
+ .map_err(|_| IggyError::TransientNotAccepted)
+ })
+}
+
+fn warn_auto_commit_capacity(
+ namespace: IggyNamespace,
+ error: partitions::ConsumerOffsetCapacityError,
+) {
+ if error.first_in_episode && error.uncertain {
+ warn!(
+ namespace_raw = namespace.inner(),
+ kind = ?error.kind,
+ "consumer offset accounting unavailable during auto-commit"
+ );
+ } else if error.first_in_episode {
+ warn!(
+ namespace_raw = namespace.inner(),
+ kind = ?error.kind,
+ occupied = error.occupied,
+ limit = error.limit,
+ config = "[partition] consumer_offsets_max",
+ "consumer offset map limit reached during auto-commit"
+ );
+ }
}
/// Build the synthetic `StoreConsumerOffset` request for an auto-commit, keyed
@@ -395,13 +456,15 @@ pub async fn dispatch_partition_request<B, MJ, S, SB>(
operation = ?header.operation,
"partition request with unresolved namespace; replying denied"
);
- send_deny_reply(
- shard,
- transport_client_id,
- &header,
- IggyError::ResourceNotFound(String::new()).as_code(),
- )
- .await;
+ let status = if matches!(
+ header.operation,
+ Operation::StoreConsumerOffset | Operation::DeleteConsumerOffset
+ ) {
+ error.as_code()
+ } else {
+ IggyError::ResourceNotFound(String::new()).as_code()
+ };
+ send_deny_reply(shard, transport_client_id, &header, status).await;
return;
}
};
@@ -471,11 +534,8 @@ pub async fn dispatch_partition_request<B, MJ, S, SB>(
// metadata access to resolve it.
let request = match maybe_rewrite_consumer_offset_request(shard, request) {
Ok(rewritten) => rewritten,
- // Not reachable through the wire path: the same body already decoded in
- // `resolve_partition_request_namespace` above, and re-encoding it can
- // only fail past `u32::MAX` bytes against a 64 MiB request cap. Denying
- // typed keeps a future re-encode failure from acking work the partition
- // plane never saw.
+ // Metadata can change during the routing wait, so a previously valid
+ // group may be missing now. Preserve the typed failure before submit.
Err(error) => {
warn!(
transport_client_id,
@@ -544,6 +604,7 @@ async fn relay_partition_reply<B, MJ, S, SB>(
S: 'static,
SB: SuperblockStore + 'static,
{
+ let consumer_kind = consumer_offset_kind(&request);
let Ok(ticket) = shard.partition_submit(namespace, request) else {
// `PartitionSubmitRefused`: the frame never reached the owning shard,
// so this is a known outcome and the client can be told now rather
@@ -569,6 +630,18 @@ async fn relay_partition_reply<B, MJ, S, SB>(
// commits moments later. The client's read-timeout is the recovery.
return;
};
+ if let Some(kind) = consumer_kind
+ && reply
+ .as_slice()
+ .get(..size_of::<iggy_binary_protocol::ReplyHeader>())
+ .and_then(|bytes| {
+ bytemuck::checked::try_from_bytes::<iggy_binary_protocol::ReplyHeader>(bytes)
+ .ok()
+ })
+ .is_some_and(|header| header.status == IggyError::TooManyConsumerOffsets.as_code())
+ {
+ shard.metrics().record_consumer_offset_denied(kind);
+ }
if let Err(error) = shard
.bus
.send_to_client(transport_client_id, reply.into_frozen())
@@ -584,6 +657,15 @@ async fn relay_partition_reply<B, MJ, S, SB>(
});
}
+fn consumer_offset_kind(request: &Message<RoutedRequestHeader>) -> Option<ConsumerKind> {
+ if request.header().operation != Operation::StoreConsumerOffset {
+ return None;
+ }
+ // WireConsumer starts with its kind byte. The dispatch path has already
+ // decoded and validated the complete request.
+ ConsumerKind::from_code(*request_body(request).first()?).ok()
+}
+
/// Serve `poll_messages`: resolve the partition namespace, run the read on
/// the owning shard ([`shard::IggyShard::partition_read`]), and re-encode
/// the stored batches into the legacy wire `PolledMessages` body.
@@ -651,7 +733,12 @@ pub(in crate::dispatch) async fn handle_poll_messages<B, MJ, S, SB>(
.await;
return;
}
- Err(fallback) => fallback,
+ Err(ReadPolledMessagesError::Fallback(fallback)) => fallback,
+ Err(ReadPolledMessagesError::Rejected(error)) => {
+ send_non_replicated_deny(shard, request, transport_client_id, error.as_code())
+ .await;
+ return;
+ }
}
}
// A generation fence: the client's cached assignment went stale after a
@@ -701,7 +788,7 @@ async fn read_polled_messages<B, MJ, S, SB>(
transport_client_id: u128,
request: &Message<RoutedRequestHeader>,
(namespace, partition_id, consumer, args): DecodedPollRequest,
-) -> Result<BusMessage, (Bytes, FrameChannel)>
+) -> Result<BusMessage, ReadPolledMessagesError>
where
B: ShellBus,
MJ: JournalHandle + 'static,
@@ -730,8 +817,9 @@ where
error = %error,
"failed to re-encode polled batches; replying empty poll"
);
- empty_poll_fallback(partition_id)
+ ReadPolledMessagesError::Fallback(empty_poll_fallback(partition_id))
}),
+ Some(PartitionReadReply::Rejected(error)) => Err(ReadPolledMessagesError::Rejected(error)),
other => {
warn!(
transport_client_id,
@@ -739,11 +827,18 @@ where
reply_was_none = other.is_none(),
"partition read failed; replying empty poll"
);
- Err(empty_poll_fallback(partition_id))
+ Err(ReadPolledMessagesError::Fallback(empty_poll_fallback(
+ partition_id,
+ )))
}
}
}
+enum ReadPolledMessagesError {
+ Fallback((Bytes, FrameChannel)),
+ Rejected(IggyError),
+}
+
/// The fail-fast poll reply for a partition that could not answer: the
/// 16-byte empty poll for `partition_id`, riding the re-sync sentinel
/// channel when the id is the sentinel and the empty-frame channel
@@ -1300,6 +1395,7 @@ mod tests {
};
use iggy_binary_protocol::ReplyHeader;
use iggy_binary_protocol::primitives::partition_assignment::CreatedPartitionAssignment;
+ use iggy_binary_protocol::requests::consumer_offsets::DeleteConsumerOffsetRequest;
use iggy_binary_protocol::requests::messages::SendMessagesHeader;
use iggy_binary_protocol::requests::streams::CreateStreamRequest;
use iggy_binary_protocol::requests::topics::{
@@ -1320,6 +1416,146 @@ mod tests {
ShardIdentity, shard_channel,
};
+ #[compio::test]
+ async fn given_invalid_partition_writes_when_resolving_should_preserve_offset_error_codes() {
+ const VSR_CLIENT: u128 = 1;
+ let bus = SpyBus::default();
+ let shard = Rc::new(test_shard(&bus, 0, 1, 1));
+ // Stream 0 / topic 0 / partition 0 committed straight into the STM, so a
+ // group op resolves its namespace and reaches the group fence, which
+ // runs before the routable wait.
+ let md = shard.plane.metadata();
+ md.mux_stm.users().ensure_root_user("iggy", "hash");
+ let create_stream = CreateStreamRequest {
+ name: WireName::new("stream").unwrap(),
+ options: WireOptions::empty(),
+ };
+ md.mux_stm
+ .update(prepare_message(
+ Operation::CreateStream,
+ VSR_CLIENT,
+ 1,
+ &create_stream.to_bytes(),
+ ))
+ .unwrap();
+ let create_topic = CreateTopicWithAssignmentsRequest {
+ request: CreateTopicRequest {
+ stream_id: WireIdentifier::numeric(0),
+ partitions_count: 1,
+ name: WireName::new("topic").unwrap(),
+ options: WireOptions::empty(),
+ },
+ derived_options: WireOptions::empty(),
+ partitions: vec![CreatedPartitionAssignment {
+ partition_id: 0,
+ consensus_group_id: 1,
+ }],
+ created_view: 0,
+ };
+ md.mux_stm
+ .update(prepare_message(
+ Operation::CreateTopicWithAssignments,
+ VSR_CLIENT,
+ 2,
+ &create_topic.to_bytes(),
+ ))
+ .unwrap();
+
+ let offset_body = |operation: Operation,
+ consumer: WireConsumer,
+ stream_id: WireIdentifier,
+ topic_id: WireIdentifier| {
+ if operation == Operation::StoreConsumerOffset {
+ StoreConsumerOffsetRequest {
+ consumer,
+ stream_id,
+ topic_id,
+ partition_id: Some(0),
+ offset: 0,
+ ack: iggy_binary_protocol::AckLevel::Quorum,
+ }
+ .to_bytes()
+ } else {
+ DeleteConsumerOffsetRequest {
+ consumer,
+ stream_id,
+ topic_id,
+ partition_id: Some(0),
+ ack: iggy_binary_protocol::AckLevel::Quorum,
+ }
+ .to_bytes()
+ }
+ };
+ let mut cases = Vec::new();
+ for operation in [
+ Operation::StoreConsumerOffset,
+ Operation::DeleteConsumerOffset,
+ ] {
+ cases.push((operation, vec![1], IggyError::InvalidCommand));
+ cases.push((
+ operation,
+ offset_body(
+ operation,
+ WireConsumer::consumer(WireIdentifier::Numeric(1)),
+ WireIdentifier::Numeric(404),
+ WireIdentifier::Numeric(1),
+ )
+ .to_vec(),
+ IggyError::StreamIdNotFound(Identifier::numeric(404).unwrap()),
+ ));
+ // The group fence: an unknown group on a known topic answers the
+ // group's own not-found code, numeric and named, not a bare
+ // ResourceNotFound.
+ cases.push((
+ operation,
+ offset_body(
+ operation,
+ WireConsumer::consumer_group(WireIdentifier::Numeric(999)),
+ WireIdentifier::Numeric(0),
+ WireIdentifier::Numeric(0),
+ )
+ .to_vec(),
+ IggyError::ConsumerGroupIdNotFound(
+ Identifier::numeric(999).unwrap(),
+ Identifier::numeric(0).unwrap(),
+ ),
+ ));
+ cases.push((
+ operation,
+ offset_body(
+ operation,
+ WireConsumer::consumer_group(WireIdentifier::named("ghost").unwrap()),
+ WireIdentifier::Numeric(0),
+ WireIdentifier::Numeric(0),
+ )
+ .to_vec(),
+ IggyError::ConsumerGroupNameNotFound(
+ "ghost".to_owned(),
+ Identifier::numeric(0).unwrap(),
+ ),
+ ));
+ }
+ cases.push((
+ Operation::SendMessages,
+ vec![1],
+ IggyError::ResourceNotFound(String::new()),
+ ));
+ for (index, (operation, body, expected)) in cases.into_iter().enumerate() {
+ let request = request_message(operation, 1, 1, index as u64 + 1, &body);
+ dispatch_partition_request(&shard, request, 1, 1, 91, Some(DEFAULT_ROOT_USER_ID)).await;
+ let replies = bus.client_replies.borrow();
+ assert_eq!(
+ replies.len(),
+ index + 1,
+ "{operation:?} must reply exactly once"
+ );
+ let (_, frame) = replies.last().unwrap();
+ let start = std::mem::offset_of!(ReplyHeader, status);
+ let status = u32::from_le_bytes(frame[start..start + 4].try_into().unwrap());
+ assert_eq!(status, expected.as_code(), "{operation:?}");
+ }
+ }
+
/// An undecodable request body is a PERMANENT client error, so every read
/// on this path must answer a nonzero status. The fail-fast shapes these
/// used to borrow all decode as success: the 16-byte empty poll reads as a
@@ -1480,6 +1716,7 @@ mod tests {
messages_required_to_save: 1,
size_of_messages_required_to_save: iggy_common::IggyByteSize::from(1024_u64),
enforce_fsync: false,
+ consumer_offset_enforce_fsync: false,
validate_checksum: true,
segment_size: iggy_common::IggyByteSize::from(1_048_576_u64),
preallocate_segments: false,
@@ -1606,6 +1843,7 @@ mod tests {
messages_required_to_save: 1,
size_of_messages_required_to_save: iggy_common::IggyByteSize::from(1024_u64),
enforce_fsync: false,
+ consumer_offset_enforce_fsync: false,
validate_checksum: true,
segment_size: iggy_common::IggyByteSize::from(1_048_576_u64),
preallocate_segments: false,
@@ -1671,6 +1909,7 @@ mod tests {
messages_required_to_save: 1,
size_of_messages_required_to_save: iggy_common::IggyByteSize::from(1024_u64),
enforce_fsync: false,
+ consumer_offset_enforce_fsync: false,
validate_checksum: true,
segment_size: iggy_common::IggyByteSize::from(1_048_576_u64),
preallocate_segments: false,
diff --git a/core/server/src/dispatch/session_ops.rs b/core/server/src/dispatch/session_ops.rs
index a8d2e62db..0dde38649 100644
--- a/core/server/src/dispatch/session_ops.rs
+++ b/core/server/src/dispatch/session_ops.rs
@@ -1472,6 +1472,7 @@ mod tests {
messages_required_to_save: 1,
size_of_messages_required_to_save: iggy_common::IggyByteSize::from(1024_u64),
enforce_fsync: false,
+ consumer_offset_enforce_fsync: false,
validate_checksum: true,
segment_size: iggy_common::IggyByteSize::from(1_048_576_u64),
preallocate_segments: false,
diff --git a/core/server/src/dispatch/test_support.rs b/core/server/src/dispatch/test_support.rs
index c0a005734..bbfded15b 100644
--- a/core/server/src/dispatch/test_support.rs
+++ b/core/server/src/dispatch/test_support.rs
@@ -184,6 +184,7 @@ pub fn test_shard(bus: &SpyBus, replica: u8, replica_count: u8, incarnation: u12
messages_required_to_save: 1,
size_of_messages_required_to_save: iggy_common::IggyByteSize::from(1024_u64),
enforce_fsync: false,
+ consumer_offset_enforce_fsync: false,
validate_checksum: true,
segment_size: iggy_common::IggyByteSize::from(1_048_576_u64),
preallocate_segments: false,
diff --git a/core/server/src/http/handlers.rs b/core/server/src/http/handlers.rs
index fc877054b..cdd8f638c 100644
--- a/core/server/src/http/handlers.rs
+++ b/core/server/src/http/handlers.rs
@@ -1296,6 +1296,7 @@ pub(in crate::http) async fn poll_messages(
))
}
Some(PartitionReadReply::NotFound) => Err(ReadError::NotFound),
+ Some(PartitionReadReply::Rejected(error)) => Err(ReadError::Rejected(error)),
Some(_) => Err(ReadError::Rejected(IggyError::InvalidCommand)),
None => Err(ReadError::Timeout),
}
@@ -1466,13 +1467,26 @@ pub(in crate::http) async fn store_consumer_offset(
let request = store_offset_wire_request(&stream_id, &topic_id, &command)
.map_err(PartitionWriteError::Rejected)?;
let body = request.to_bytes();
- SendWrapper::new(partition_write_replicated(
+ let consumer_kind = command.consumer.kind;
+ let result = SendWrapper::new(partition_write_replicated(
&state,
&identity.session,
Operation::StoreConsumerOffset,
&body,
))
- .await?;
+ .await;
+ if matches!(
+ &result,
+ Err(PartitionWriteError::Rejected(
+ IggyError::TooManyConsumerOffsets
+ ))
+ ) {
+ state
+ .shard
+ .metrics()
+ .record_consumer_offset_denied(consumer_kind);
+ }
+ result?;
Ok(StatusCode::NO_CONTENT)
}
diff --git a/core/server/src/offset_recovery.rs b/core/server/src/offset_recovery.rs
index afb60c820..40dca3ff8 100644
--- a/core/server/src/offset_recovery.rs
+++ b/core/server/src/offset_recovery.rs
@@ -27,168 +27,200 @@
//! here as unchecksummed.
use iggy_common::{ConsumerGroupId, ConsumerKind, ConsumerOffset, IggyError};
-use partitions::offset_storage::{OffsetRecord, decode_offset_record};
+use partitions::offset_storage::{OffsetRecord, decode_offset_record, offset_replacement_id};
+use std::path::PathBuf;
use std::sync::atomic::AtomicU64;
+use tokio::sync::{Semaphore, mpsc};
use tracing::{error, trace, warn};
const COMPONENT: &str = "STREAMING_PARTITIONS";
+const OFFSET_DIRECTORY_BUFFER: usize = 64;
+static OFFSET_DIRECTORY_READERS: Semaphore = Semaphore::const_new(4);
+type OffsetDirectoryEntries = mpsc::Receiver<std::io::Result<Option<PathBuf>>>;
-pub fn load_consumer_offsets(path: &str) -> Result<Vec<ConsumerOffset>, IggyError> {
- trace!("Loading consumer offsets from path: {path}...");
- let Ok(dir_entries) = std::fs::read_dir(path) else {
- return Err(IggyError::CannotReadConsumerOffsets(path.to_owned()));
- };
-
- let mut consumer_offsets = Vec::new();
- for dir_entry in dir_entries {
- let dir_entry = match dir_entry {
- Ok(entry) => entry,
- Err(e) => {
- warn!(
- "Failed to read directory entry in consumer offsets path: {path}, \
- error: {e}, skipping."
- );
- continue;
- }
- };
+pub struct RecoveredOffsets<T> {
+ pub entries: Vec<T>,
+ pub stranded_ids: Vec<u32>,
+}
- let metadata = match dir_entry.metadata() {
- Ok(m) => m,
- Err(e) => {
- warn!(
- "Failed to read metadata for entry in consumer offsets path: {path}, \
- error: {e}, skipping."
- );
- continue;
- }
- };
+enum OffsetFileLoad {
+ Loaded(AtomicU64),
+ Removed,
+ Stranded,
+}
- if metadata.is_dir() {
- continue;
+impl<T> Default for RecoveredOffsets<T> {
+ fn default() -> Self {
+ Self {
+ entries: Vec::new(),
+ stranded_ids: Vec::new(),
}
-
- let name = dir_entry.file_name().to_string_lossy().to_string();
- let Ok(consumer_id) = name.parse::<u32>() else {
- warn!(
- "Unexpected non-numeric consumer offset file: '{}', skipping.",
- name
- );
- continue;
- };
-
- let path = dir_entry.path();
- let Some(path) = path.to_str().map(str::to_owned) else {
- error!("Invalid consumer ID path for file with name: '{}'.", name);
- continue;
- };
-
- let Some(offset) = read_offset_file(&path, "consumer offset") else {
- continue;
- };
-
- consumer_offsets.push(ConsumerOffset {
- kind: ConsumerKind::Consumer,
- consumer_id,
- offset,
- path,
- });
}
-
- consumer_offsets.sort_by_key(|consumer_offset| consumer_offset.consumer_id);
- Ok(consumer_offsets)
}
-pub fn load_consumer_group_offsets(
+pub async fn load_consumer_offsets(
path: &str,
-) -> Result<Vec<(ConsumerGroupId, ConsumerOffset)>, IggyError> {
- trace!("Loading consumer group offsets from path: {path}...");
- let Ok(dir_entries) = std::fs::read_dir(path) else {
- return Err(IggyError::CannotReadConsumerOffsets(path.to_owned()));
- };
+) -> Result<RecoveredOffsets<ConsumerOffset>, IggyError> {
+ let mut recovered = load_offsets(path, ConsumerKind::Consumer, |offset| offset).await?;
+ recovered.entries.sort_by_key(|offset| offset.consumer_id);
+ Ok(recovered)
+}
- let mut consumer_group_offsets = Vec::new();
- for dir_entry in dir_entries {
- let dir_entry = match dir_entry {
- Ok(entry) => entry,
- Err(e) => {
- warn!(
- "Failed to read directory entry in consumer group offsets path: {path}, \
- error: {e}, skipping."
- );
- continue;
- }
- };
+pub async fn load_consumer_group_offsets(
+ path: &str,
+) -> Result<RecoveredOffsets<(ConsumerGroupId, ConsumerOffset)>, IggyError> {
+ load_offsets(path, ConsumerKind::ConsumerGroup, |offset| {
+ (ConsumerGroupId(offset.consumer_id as usize), offset)
+ })
+ .await
+}
- let metadata = match dir_entry.metadata() {
- Ok(m) => m,
- Err(e) => {
- warn!(
- "Failed to read metadata for entry in consumer group offsets path: {path}, \
- error: {e}, skipping."
- );
- continue;
+async fn load_offsets<T>(
+ path: &str,
+ kind: ConsumerKind,
+ construct: impl Fn(ConsumerOffset) -> T,
+) -> Result<RecoveredOffsets<T>, IggyError> {
+ trace!(?kind, path, "loading consumer offsets");
+ let mut dir_entries = offset_directory_entries(path).await?;
+ let mut recovered = RecoveredOffsets::default();
+ loop {
+ let entry_path = match dir_entries.recv().await {
+ Some(Ok(Some(path))) => path,
+ Some(Ok(None)) => break,
+ Some(Err(error)) => {
+ warn!(?kind, path, %error, "failed to enumerate offset directory");
+ return Err(IggyError::CannotReadConsumerOffsets(path.to_owned()));
}
+ None => return Err(IggyError::CannotReadConsumerOffsets(path.to_owned())),
};
-
- if metadata.is_dir() {
+ let name = entry_path
+ .file_name()
+ .unwrap_or_default()
+ .to_string_lossy()
+ .into_owned();
+ if offset_replacement_id(&name).is_some() {
+ remove_stale_replacement(&entry_path, &name).await;
continue;
}
-
- let name = dir_entry.file_name().to_string_lossy().to_string();
- let Ok(raw_consumer_group_id) = name.parse::<u32>() else {
+ let Ok(consumer_id) = name.parse::<u32>() else {
warn!(
- "Unexpected non-numeric consumer group offset file: '{}', skipping.",
- name
+ ?kind,
+ name, "unexpected non-numeric consumer offset file, skipping"
);
continue;
};
- let consumer_group_id = ConsumerGroupId(raw_consumer_group_id as usize);
-
- let path = dir_entry.path();
- let Some(path) = path.to_str().map(str::to_owned) else {
- error!(
- "Invalid consumer group offset path for file with name: '{}'.",
- name
- );
+ let Some(path) = entry_path.to_str().map(str::to_owned) else {
+ error!(?kind, name, "invalid consumer offset path");
continue;
};
-
- let Some(offset) = read_offset_file(&path, "consumer group offset") else {
- continue;
+ let offset = match read_offset_file(&path, offset_kind_label(kind)).await {
+ OffsetFileLoad::Loaded(offset) => offset,
+ OffsetFileLoad::Removed => continue,
+ OffsetFileLoad::Stranded => {
+ recovered.stranded_ids.push(consumer_id);
+ continue;
+ }
};
-
- let consumer_offset = ConsumerOffset {
- kind: ConsumerKind::ConsumerGroup,
- consumer_id: raw_consumer_group_id,
+ recovered.entries.push(construct(ConsumerOffset {
+ kind,
+ consumer_id,
offset,
path,
- };
+ }));
+ }
+ Ok(recovered)
+}
+
+async fn offset_directory_entries(path: &str) -> Result<OffsetDirectoryEntries, IggyError> {
+ // Compio has no asynchronous directory iterator and the shard's blocking
+ // pool is disabled. Bound both OS threads and buffered paths. The worker
+ // owns the permit so cancellation cannot exceed the concurrency bound.
+ let permit = OFFSET_DIRECTORY_READERS
+ .acquire()
+ .await
+ .map_err(|_| IggyError::CannotReadConsumerOffsets(path.to_owned()))?;
+ let (sender, receiver) = mpsc::channel(OFFSET_DIRECTORY_BUFFER);
+ let directory = path.to_owned();
+ std::thread::Builder::new()
+ .name("iggy-offset-recovery".to_owned())
+ .spawn(move || {
+ let _permit = permit;
+ let result = (|| {
+ // Only the directory read itself is fatal. One unreadable
+ // entry is skipped with a warning, as the on-reactor loader
+ // did, so a single bad dirent cannot keep a partition from
+ // booting.
+ for entry in std::fs::read_dir(&directory)? {
+ let entry = match entry {
+ Ok(entry) => entry,
+ Err(error) => {
+ warn!(path = directory, %error, "failed to read offset directory entry");
+ continue;
+ }
+ };
+ let is_file = match entry.file_type() {
+ Ok(file_type) => file_type.is_file(),
+ Err(error) => {
+ warn!(path = directory, %error, "failed to read offset entry type");
+ continue;
+ }
+ };
+ if is_file && sender.blocking_send(Ok(Some(entry.path()))).is_err() {
+ return Ok(());
+ }
+ }
+ Ok(())
+ })();
+ // Explicit completion distinguishes an empty directory from an
+ // interrupted worker. Closed receivers simply abandon enumeration.
+ let _ = sender.blocking_send(result.map(|()| None));
+ })
+ .map_err(|error| {
+ error!(path, %error, "failed to start offset directory reader");
+ IggyError::CannotReadConsumerOffsets(path.to_owned())
+ })?;
+ Ok(receiver)
+}
- consumer_group_offsets.push((consumer_group_id, consumer_offset));
+/// A crashed atomic replacement leaves its sibling behind. The rename never
+/// landed, so the sibling is never authoritative. Removal needs no directory
+/// sync because a resurrected sibling is still ignored on the next load.
+async fn remove_stale_replacement(path: &std::path::Path, name: &str) {
+ match compio::fs::remove_file(path).await {
+ Ok(()) => trace!("Removed stale offset replacement file: '{name}'."),
+ Err(e) => warn!(
+ "{COMPONENT} (error: {e}) - could not remove stale offset replacement \
+ file: '{name}', skipping."
+ ),
}
+}
- Ok(consumer_group_offsets)
+const fn offset_kind_label(kind: ConsumerKind) -> &'static str {
+ match kind {
+ ConsumerKind::Consumer => "consumer offset",
+ ConsumerKind::ConsumerGroup => "consumer group offset",
+ }
}
-fn read_offset_file(path: &str, offset_kind: &'static str) -> Option<AtomicU64> {
- let bytes = match std::fs::read(path) {
+async fn read_offset_file(path: &str, offset_kind: &'static str) -> OffsetFileLoad {
+ let bytes = match compio::fs::read(path).await {
Ok(bytes) => bytes,
Err(e) => {
warn!(
"{COMPONENT} (error: {e}) - failed to read offset file, \
path: {path}, skipping."
);
- return None;
+ return OffsetFileLoad::Stranded;
}
};
match decode_offset_record(&bytes) {
- OffsetRecord::Value { offset, .. } => Some(AtomicU64::new(offset)),
+ OffsetRecord::Value { offset, .. } => OffsetFileLoad::Loaded(AtomicU64::new(offset)),
OffsetRecord::Torn => {
warn!(
"{COMPONENT} - failed to read {offset_kind} from file (truncated), \
- path: {path}, skipping."
+ path: {path}, removing invalid file."
);
- None
+ remove_invalid_offset_file(path, offset_kind).await
}
// Skipped rather than loaded: resuming from a cursor provably not the one
// written reads as ordinary redelivery or a gap, never as corruption.
@@ -206,13 +238,87 @@ fn read_offset_file(path: &str, offset_kind: &'static str) -> Option<AtomicU64>
(offset: {offset}, expected: {expected}, found: {found}), \
path: {path}, removing it and resuming this consumer from the start."
);
- if let Err(e) = std::fs::remove_file(path) {
- error!(
- "{COMPONENT} (error: {e}) - could not remove the corrupt \
- {offset_kind} file, path: {path}; remove it manually."
- );
- }
- None
+ remove_invalid_offset_file(path, offset_kind).await
}
}
}
+
+async fn remove_invalid_offset_file(path: &str, offset_kind: &'static str) -> OffsetFileLoad {
+ if let Err(error) = compio::fs::remove_file(path).await {
+ error!(
+ "{COMPONENT} (error: {error}) - could not remove the invalid \
+ {offset_kind} file, path: {path}; remove it manually."
+ );
+ return OffsetFileLoad::Stranded;
+ }
+ let Some(parent) = std::path::Path::new(path).parent() else {
+ return OffsetFileLoad::Removed;
+ };
+ match async {
+ let directory = compio::fs::File::open(parent).await?;
+ directory.sync_all().await
+ }
+ .await
+ {
+ Ok(()) => OffsetFileLoad::Removed,
+ Err(error) => {
+ error!(
+ "{COMPONENT} (error: {error}) - removed invalid {offset_kind} file but \
+ could not sync its directory, path: {path}; retaining its capacity slot."
+ );
+ OffsetFileLoad::Stranded
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[compio::test]
+ async fn given_missing_directory_when_loading_should_report_error_instead_of_empty_state() {
+ let dir = tempfile::tempdir().unwrap();
+ let missing = dir.path().join("missing");
+ assert!(matches!(
+ load_consumer_offsets(missing.to_str().unwrap()).await,
+ Err(IggyError::CannotReadConsumerOffsets(_))
+ ));
+ }
+
+ #[compio::test]
+ async fn given_full_directory_buffer_when_loader_is_cancelled_should_release_worker_capacity() {
+ let dir = tempfile::tempdir().unwrap();
+ for id in 0..OFFSET_DIRECTORY_BUFFER * 2 {
+ std::fs::write(dir.path().join(id.to_string()), 0_u64.to_le_bytes()).unwrap();
+ }
+ let path = dir.path().to_str().unwrap();
+ for _ in 0..8 {
+ let entries = offset_directory_entries(path).await.unwrap();
+ drop(entries);
+ }
+ let loaded = load_consumer_offsets(path).await.unwrap();
+ assert_eq!(loaded.entries.len(), OFFSET_DIRECTORY_BUFFER * 2);
+ }
+
+ #[compio::test]
+ async fn given_numeric_directory_and_torn_file_when_loading_should_remove_only_invalid_file() {
+ let dir = tempfile::tempdir().unwrap();
+ std::fs::create_dir(dir.path().join("7")).unwrap();
+ std::fs::write(dir.path().join("8"), [1, 2]).unwrap();
+ std::fs::write(dir.path().join("9"), 12_u64.to_le_bytes()).unwrap();
+ std::fs::write(dir.path().join("9.tmp"), [0_u8; 4]).unwrap();
+ std::fs::write(dir.path().join("notes.tmp"), b"unrelated").unwrap();
+ let path = dir.path().to_str().unwrap();
+ let consumers = load_consumer_offsets(path).await.unwrap();
+ assert!(!dir.path().join("9.tmp").exists());
+ assert!(dir.path().join("notes.tmp").exists());
+ assert_eq!(consumers.entries.len(), 1);
+ assert_eq!(consumers.entries[0].consumer_id, 9);
+ assert!(consumers.stranded_ids.is_empty());
+ assert!(!dir.path().join("8").exists());
+ let groups = load_consumer_group_offsets(path).await.unwrap();
+ assert_eq!(groups.entries.len(), 1);
+ assert_eq!(groups.entries[0].0, ConsumerGroupId(9));
+ assert!(groups.stranded_ids.is_empty());
+ }
+}
diff --git a/core/server/src/partition_helpers.rs b/core/server/src/partition_helpers.rs
index 15a519a22..af6e19028 100644
--- a/core/server/src/partition_helpers.rs
+++ b/core/server/src/partition_helpers.rs
@@ -29,7 +29,9 @@
//! `CreateTopic` / `CreatePartitions` event has no matching local
//! partition yet.
-use crate::offset_recovery::{load_consumer_group_offsets, load_consumer_offsets};
+use crate::offset_recovery::{
+ RecoveredOffsets, load_consumer_group_offsets, load_consumer_offsets,
+};
use crate::segment_recovery::{RecoveredSegment, load_persisted_segments};
use crate::server_error::{PartitionRecoveryRefusal, ServerError};
use crate::shell::consensus_timers;
@@ -39,8 +41,8 @@ use consensus::{
FreshGroupStart, JoinMode, LocalPipeline, VsrConsensus, VsrRestore, VsrState, fresh_group_start,
};
use iggy_common::{
- ConsumerGroupOffsets, ConsumerOffsets, IggyByteSize, IggyError, IggyTimestamp, PartitionStats,
- TopicRuntimeOptions,
+ ConsumerGroupOffsets, ConsumerKind, ConsumerOffsets, IggyByteSize, IggyError, IggyTimestamp,
+ PartitionStats, TopicRuntimeOptions,
};
use journal::superblock::{PingPongSuperblock, SuperblockContents};
use message_bus::IggyMessageBus;
@@ -155,7 +157,8 @@ pub async fn create_partition_file_hierarchy(
/// Returns [`ServerError::ConsumerOffsetsLoad`] when the on-disk files
/// exist but fail to decode. A stored offset past the offset space is clamped
/// to `current_offset` (with a warning), not an error.
-pub fn configure_consumer_offsets(
+#[allow(clippy::too_many_lines)]
+pub async fn configure_consumer_offsets(
partition: &mut IggyPartition<Rc<IggyMessageBus>>,
config: &ServerConfig,
namespace: IggyNamespace,
@@ -184,17 +187,18 @@ pub fn configure_consumer_offsets(
// path, where the max leaves `current_offset` in charge as before.
let offset_space_ceiling = current_offset.max(partition.mint_frontier().saturating_sub(1));
- let loaded_consumer_offsets = load_partition_consumer_offsets(
+ let recovered_consumers = load_partition_consumer_offsets(
&consumer_offsets_path,
"consumer",
stream_id,
topic_id,
partition_id,
- )?;
- let consumer_offsets = ConsumerOffsets::with_capacity(loaded_consumer_offsets.len());
+ )
+ .await?;
+ let consumer_offsets = ConsumerOffsets::with_capacity(recovered_consumers.entries.len());
{
let guard = consumer_offsets.pin();
- for offset in loaded_consumer_offsets {
+ for offset in recovered_consumers.entries {
let recovered_offset = offset.offset.load(Ordering::Relaxed);
if recovered_offset > offset_space_ceiling {
// A crash can persist an offset ahead of the flushed data
@@ -213,20 +217,30 @@ pub fn configure_consumer_offsets(
);
offset.offset.store(current_offset, Ordering::Relaxed);
}
- guard.insert(offset.consumer_id as usize, offset);
+ let consumer_id = offset.consumer_id;
+ let committed_offset = offset.offset.load(Ordering::Relaxed);
+ partition.seed_recovered_consumer_offset(
+ ConsumerKind::Consumer,
+ consumer_id,
+ committed_offset,
+ recovered_offset,
+ );
+ guard.insert(consumer_id as usize, offset);
}
}
- let loaded_group_offsets = load_partition_consumer_group_offsets(
+ let recovered_groups = load_partition_consumer_group_offsets(
&consumer_group_offsets_path,
stream_id,
topic_id,
partition_id,
- )?;
- let consumer_group_offsets = ConsumerGroupOffsets::with_capacity(loaded_group_offsets.len());
+ )
+ .await?;
+ let consumer_group_offsets =
+ ConsumerGroupOffsets::with_capacity(recovered_groups.entries.len());
{
let guard = consumer_group_offsets.pin();
- for (group_id, offset) in loaded_group_offsets {
+ for (group_id, offset) in recovered_groups.entries {
let recovered_offset = offset.offset.load(Ordering::Relaxed);
if recovered_offset > offset_space_ceiling {
warn!(
@@ -241,42 +255,71 @@ pub fn configure_consumer_offsets(
);
offset.offset.store(current_offset, Ordering::Relaxed);
}
+ let committed_offset = offset.offset.load(Ordering::Relaxed);
+ partition.seed_recovered_consumer_offset(
+ ConsumerKind::ConsumerGroup,
+ u32::try_from(group_id.0).expect("recovered group id originated as u32"),
+ committed_offset,
+ recovered_offset,
+ );
guard.insert(group_id, offset);
}
}
- // Offset files follow the topic's own `enforce_fsync`: they are part of the
- // same partition's durability story, and the global knob they used to read
- // is gone.
- let enforce_fsync = partition
- .runtime_options()
- .enforce_fsync
- .unwrap_or(iggy_common::DEFAULT_ENFORCE_FSYNC);
+ // Offset files have their own knob, not the topic's `enforce_fsync`: that
+ // one gates message and index writes, and syncing a 16-byte cursor on every
+ // commit costs milliseconds per commit for a file whose loss is a redelivery.
partition.configure_consumer_offset_storage(
- consumer_offsets_path,
- consumer_group_offsets_path,
+ consumer_offsets_path.clone(),
+ consumer_group_offsets_path.clone(),
consumer_offsets,
consumer_group_offsets,
- enforce_fsync,
+ config.partition.consumer_offset_enforce_fsync,
);
+ for consumer_id in recovered_consumers.stranded_ids {
+ if partition.seed_stranded_consumer_offset(ConsumerKind::Consumer, consumer_id) {
+ warn!(stream_id, topic_id, partition_id, consumer_id, path = %consumer_offsets_path,
+ "unloaded consumer offset file retains its capacity slot until updated or deleted");
+ }
+ }
+ for group_id in recovered_groups.stranded_ids {
+ if partition.seed_stranded_consumer_offset(ConsumerKind::ConsumerGroup, group_id) {
+ warn!(stream_id, topic_id, partition_id, group_id, path = %consumer_group_offsets_path,
+ "unloaded group offset file retains its capacity slot until repaired or reclaimed");
+ }
+ }
+ for kind in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup] {
+ let count = partition.occupied_consumer_offset_count(kind);
+ if count > config.partition.consumer_offsets_max {
+ warn!(
+ stream_id,
+ topic_id,
+ partition_id,
+ ?kind,
+ count,
+ limit = config.partition.consumer_offsets_max,
+ "recovered consumer offsets exceed the configured admission limit"
+ );
+ }
+ }
Ok(())
}
-fn load_partition_consumer_offsets(
+async fn load_partition_consumer_offsets(
path: &str,
consumer_kind: &'static str,
stream_id: usize,
topic_id: usize,
partition_id: usize,
-) -> Result<Vec<iggy_common::ConsumerOffset>, ServerError> {
+) -> Result<RecoveredOffsets<iggy_common::ConsumerOffset>, ServerError> {
if !Path::new(path).exists() {
- return Ok(Vec::new());
+ return Ok(RecoveredOffsets::default());
}
- load_consumer_offsets(path).or_else(|source| {
+ load_consumer_offsets(path).await.or_else(|source| {
if matches!(&source, IggyError::CannotReadConsumerOffsets(missing_path) if !Path::new(missing_path).exists())
{
- return Ok(Vec::new());
+ return Ok(RecoveredOffsets::default());
}
Err(ServerError::ConsumerOffsetsLoad {
@@ -290,20 +333,23 @@ fn load_partition_consumer_offsets(
})
}
-fn load_partition_consumer_group_offsets(
+async fn load_partition_consumer_group_offsets(
path: &str,
stream_id: usize,
topic_id: usize,
partition_id: usize,
-) -> Result<Vec<(iggy_common::ConsumerGroupId, iggy_common::ConsumerOffset)>, ServerError> {
+) -> Result<
+ RecoveredOffsets<(iggy_common::ConsumerGroupId, iggy_common::ConsumerOffset)>,
+ ServerError,
+> {
if !Path::new(path).exists() {
- return Ok(Vec::new());
+ return Ok(RecoveredOffsets::default());
}
- load_consumer_group_offsets(path).or_else(|source| {
+ load_consumer_group_offsets(path).await.or_else(|source| {
if matches!(&source, IggyError::CannotReadConsumerOffsets(missing_path) if !Path::new(missing_path).exists())
{
- return Ok(Vec::new());
+ return Ok(RecoveredOffsets::default());
}
Err(ServerError::ConsumerOffsetsLoad {
@@ -816,6 +862,7 @@ async fn load_partition(
config.partition.evicted_ring_bytes_max.as_bytes_u64(),
);
partition.set_dedup_clients_max(config.partition.dedup_clients_max);
+ partition.set_consumer_offsets_max(config.partition.consumer_offsets_max);
partition.set_offset_reservation_lease(config.partition.offset_reservation_lease);
partition.set_partition_dir(partition_dir.clone());
// Before the hydrate: the durable record is keyed by incarnation, so a
@@ -836,7 +883,7 @@ async fn load_partition(
restore_partition_offsets(&mut partition, partitions_config, recovered_state.as_ref()).await?;
let current_offset = partition.offset.load(Ordering::Acquire);
- configure_consumer_offsets(&mut partition, config, namespace, current_offset)?;
+ configure_consumer_offsets(&mut partition, config, namespace, current_offset).await?;
ensure_initial_segment(&mut partition, config, stream_id, topic_id, partition_id).await?;
Ok(partition)
@@ -1264,6 +1311,7 @@ pub async fn build_partition_fresh(
config.partition.evicted_ring_bytes_max.as_bytes_u64(),
);
partition.set_dedup_clients_max(config.partition.dedup_clients_max);
+ partition.set_consumer_offsets_max(config.partition.consumer_offsets_max);
partition.set_offset_reservation_lease(config.partition.offset_reservation_lease);
partition.set_partition_dir(partition_dir);
// Fresh dirs read generation 0; a dir surviving from a crashed process
@@ -1301,7 +1349,7 @@ pub async fn build_partition_fresh(
let current_offset = partition.offset.load(Ordering::Acquire);
- configure_consumer_offsets(&mut partition, config, namespace, current_offset)?;
+ configure_consumer_offsets(&mut partition, config, namespace, current_offset).await?;
ensure_initial_segment(&mut partition, config, stream_id, topic_id, partition_id).await?;
// Claim the first offset-reservation block HERE so no send ever pays the
@@ -1508,6 +1556,7 @@ mod tests {
messages_required_to_save: 1,
size_of_messages_required_to_save: IggyByteSize::from(1024_u64),
enforce_fsync: false,
+ consumer_offset_enforce_fsync: false,
validate_checksum: true,
segment_size: IggyByteSize::from(1_048_576_u64),
preallocate_segments: false,
diff --git a/core/server/src/partition_reconciler.rs b/core/server/src/partition_reconciler.rs
index e35f62378..6ce661ee7 100644
--- a/core/server/src/partition_reconciler.rs
+++ b/core/server/src/partition_reconciler.rs
@@ -170,11 +170,17 @@ use ahash::{AHashMap, AHashSet};
use configs::server::ServerConfig;
use consensus::{MetadataHandle, PartitionsHandle};
use futures::FutureExt;
+use iggy_binary_protocol::requests::consumer_offsets::DeleteConsumerOffsetRequest;
+use iggy_binary_protocol::{
+ AckLevel, Command, Operation, ReplyHeader, RoutedRequestHeader, WireConsumer, WireEncode,
+ WireIdentifier,
+};
use iggy_common::{ConsumerGroupId, IggyTimestamp};
+use message_bus::AUTO_COMMIT_CLIENT_ID;
use message_bus::MessageBus;
use metadata::impls::metadata::StreamsFrontend;
use metadata::stm::stream::Partition;
-use partitions::delete_persisted_offset;
+use server_common::Message;
use server_common::sharding::{IggyNamespace, ShardId};
use shard::MetadataSubmit;
use shard::ReconcileOp;
@@ -184,10 +190,11 @@ use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};
-use tracing::{debug, error, trace, warn};
+use tracing::{debug, error, trace};
const BACKOFF_BASE: Duration = Duration::from_secs(1);
const BACKOFF_MAX: Duration = Duration::from_mins(1);
+const GROUP_OFFSET_DELETES_PER_PASS: usize = 32;
/// Consecutive same-cause failures before [`ReconcilerCtx::record_failure`]
/// escalates to an operator-visible error (the backoff is capped, so
@@ -229,6 +236,9 @@ pub struct ReconcilerCtx {
/// `true` when the previous pass made no changes. Only then is a
/// same-`revision` pass safe to skip.
last_pass_noop: Cell<bool>,
+ group_offset_cleanup_inflight: Rc<RefCell<AHashSet<IggyNamespace>>>,
+ group_offset_cleanup_completed: Rc<Cell<usize>>,
+ last_group_offset_reconcile_epoch: Cell<u64>,
}
impl ReconcilerCtx {
@@ -251,6 +261,9 @@ impl ReconcilerCtx {
failure_state: RefCell::new(AHashMap::new()),
last_revision: Cell::new(None),
last_pass_noop: Cell::new(false),
+ group_offset_cleanup_inflight: Rc::new(RefCell::new(AHashSet::new())),
+ group_offset_cleanup_completed: Rc::new(Cell::new(0)),
+ last_group_offset_reconcile_epoch: Cell::new(0),
}
}
@@ -383,9 +396,12 @@ struct PassCounters {
backoff_skipped: usize,
/// Stale incarnations (slab-key reuse) torn down for rebuild.
stale: usize,
- /// Consumer-group offsets reclaimed for groups deleted while their topic
- /// survived (a bare `DeleteConsumerGroup`, not a topic/stream delete).
- cg_offsets_purged: usize,
+ /// Group-offset deletes successfully handed to the pump this pass.
+ cg_offsets_submitted: usize,
+ /// Successful replicated deletes reported by detached completion tasks.
+ cg_offsets_completed: usize,
+ /// Group-offset deletes refused by the inbox and needing another pass.
+ cg_offsets_pending: usize,
/// Committed delete watermarks not yet fully enforced on local segments.
/// Counted so the pass does not arm the fast-skip: the pump can be
/// blocked by a consumer barrier or by a rejoin whose offsets land via
@@ -423,7 +439,9 @@ impl PassCounters {
+ self.removed_routed
+ self.backoff_skipped
+ self.stale
- + self.cg_offsets_purged
+ + self.cg_offsets_submitted
+ + self.cg_offsets_completed
+ + self.cg_offsets_pending
+ self.trims_pending
+ self.purges_staged
+ self.deferred
@@ -439,6 +457,14 @@ impl PassCounters {
async fn reconcile_once(ctx: &ReconcilerCtx) -> bool {
let shard_id = ctx.shard.id;
let revision = current_revision(ctx);
+ // Snapshotted with `revision` before the pass, so a partition that arms
+ // itself during one of the awaits below bumps past this value and forces
+ // the next pass instead of being absorbed by an end-of-pass read.
+ let group_offset_epoch = ctx
+ .shard
+ .plane
+ .partitions()
+ .consumer_group_offsets_reconcile_epoch();
// Cooperative-revocation completion runs every tick, before the fast-skip:
// a timeout fires on wall-clock and a drain on partition-offset state, and
@@ -464,7 +490,9 @@ async fn reconcile_once(ctx: &ReconcilerCtx) -> bool {
if ctx.last_revision.get() == Some(revision)
&& ctx.last_pass_noop.get()
&& ctx.failure_state.borrow().is_empty()
+ && ctx.group_offset_cleanup_completed.get() == 0
&& !ctx.shard.has_parked_partition_frames()
+ && ctx.last_group_offset_reconcile_epoch.get() == group_offset_epoch
{
trace!(
shard = shard_id,
@@ -475,12 +503,15 @@ async fn reconcile_once(ctx: &ReconcilerCtx) -> bool {
let target = snapshot_target_namespaces(ctx);
let target_set: AHashSet<IggyNamespace> = target.iter().map(|partition| partition.ns).collect();
- let mut counters = PassCounters::default();
+ let mut counters = PassCounters {
+ cg_offsets_completed: ctx.group_offset_cleanup_completed.replace(0),
+ ..PassCounters::default()
+ };
reconcile_additions(ctx, target, &mut counters).await;
reconcile_removals(ctx, &target_set, &mut counters).await;
reconcile_parked_frames(ctx, &mut counters);
- reconcile_consumer_group_offsets(ctx, &mut counters).await;
+ reconcile_consumer_group_offsets(ctx, &mut counters);
reconcile_segment_truncations(ctx, &mut counters);
reconcile_partition_purges(ctx, &mut counters);
@@ -494,6 +525,8 @@ async fn reconcile_once(ctx: &ReconcilerCtx) -> bool {
// still runs even though `revision` did not change.
let did_work = counters.total() > 0;
ctx.last_revision.set(Some(revision));
+ ctx.last_group_offset_reconcile_epoch
+ .set(group_offset_epoch);
ctx.last_pass_noop.set(!did_work);
if did_work {
@@ -511,6 +544,7 @@ async fn reconcile_once(ctx: &ReconcilerCtx) -> bool {
parked_reclaimed = counters.parked_reclaimed,
purges_staged = counters.purges_staged,
trims_pending = counters.trims_pending,
+ cg_offsets_pending = counters.cg_offsets_pending,
"partition reconciler pass complete"
);
} else {
@@ -960,47 +994,118 @@ async fn tear_down_owned_partition(
counters.removed_local += 1;
}
-/// Reclaim consumer-group offsets left behind by a `DeleteConsumerGroup` whose
-/// topic still exists (a topic/stream delete already drops the whole partition
-/// directory, offsets included). For each owned partition, any stored
-/// consumer-group offset whose group id is no longer present in the topic's
-/// committed metadata is removed (in-memory entry + persisted file). Monotonic,
-/// never-reused group ids make this purely reclamation -- a recreated group
-/// gets a fresh id and never reads a dead group's offset -- so it is safe to do
-/// lazily on the reconcile pass rather than synchronously on delete.
-async fn reconcile_consumer_group_offsets(ctx: &ReconcilerCtx, counters: &mut PassCounters) {
+/// Reclaim deleted groups through ordered offset deletes. Replicas must see
+/// each delete before a replacement store can reuse its durable slot.
+fn reconcile_consumer_group_offsets(ctx: &ReconcilerCtx, counters: &mut PassCounters) {
let live_groups = snapshot_topic_live_groups(ctx);
let partitions = ctx.shard.plane.partitions();
let owned: Vec<IggyNamespace> = partitions.namespaces().copied().collect();
- for ns in owned {
- let live = live_groups.get(&(ns.stream_id(), ns.topic_id()));
- // Take the in-memory removes + owned unlink paths under a closure-scoped
- // borrow that cannot escape into the await below. Holding a raw
- // `&IggyPartition` across `delete_persisted_offset().await` would let the
- // pump task realloc the partitions vec underneath us (a UAF).
- let paths = partitions.with_partition(&ns, |partition| {
- partition.reclaim_dead_group_offsets(|group_id| {
- live.is_some_and(|set| set.contains(&group_id))
- })
- });
- let Some(paths) = paths else {
+ for namespace in owned {
+ if ctx
+ .group_offset_cleanup_inflight
+ .borrow()
+ .contains(&namespace)
+ {
+ continue;
+ }
+ let Some((next_group_id, live)) =
+ live_groups.get(&(namespace.stream_id(), namespace.topic_id()))
+ else {
continue;
};
- for path in paths {
- if let Err(err) = delete_persisted_offset(&path).await {
- warn!(
- shard = ctx.shard.id,
- ns_raw = ns.inner(),
- error = %err,
- "reconciler failed to reclaim deleted consumer-group offset"
- );
- continue;
+ let dead = partitions
+ .with_partition(&namespace, |partition| {
+ partition.dead_consumer_group_offset_ids(|group_id| {
+ // A lagging metadata replica cannot prove a group deleted
+ // until it has applied the allocation of that group's id.
+ group_id >= *next_group_id || live.contains(&group_id)
+ })
+ })
+ .unwrap_or_default();
+ // Bound work per pass so a historical directory cannot monopolize the
+ // reconciler. Unprocessed keys keep the partition's dirty flag armed.
+ let mut tickets = Vec::with_capacity(dead.len().min(GROUP_OFFSET_DELETES_PER_PASS));
+ for consumer_id in dead.into_iter().take(GROUP_OFFSET_DELETES_PER_PASS) {
+ let request = group_offset_delete_request(namespace, consumer_id);
+ if let Ok(ticket) = ctx.shard.partition_submit(namespace, request) {
+ counters.cg_offsets_submitted += 1;
+ tickets.push(ticket);
+ } else {
+ counters.cg_offsets_pending += 1;
}
- counters.cg_offsets_purged += 1;
}
+ if tickets.is_empty() {
+ continue;
+ }
+ ctx.group_offset_cleanup_inflight
+ .borrow_mut()
+ .insert(namespace);
+ let inflight = Rc::clone(&ctx.group_offset_cleanup_inflight);
+ let completed = Rc::clone(&ctx.group_offset_cleanup_completed);
+ let shard = Rc::clone(&ctx.shard);
+ shard.bus.clone().spawn(async move {
+ let replies = futures::future::join_all(
+ tickets
+ .into_iter()
+ .map(|ticket| shard.await_partition_submit(ticket)),
+ )
+ .await;
+ let count = replies
+ .into_iter()
+ .flatten()
+ .filter(|reply| {
+ reply
+ .as_slice()
+ .get(..size_of::<ReplyHeader>())
+ .and_then(|bytes| {
+ bytemuck::checked::try_from_bytes::<ReplyHeader>(bytes).ok()
+ })
+ .is_some_and(|header| header.status == 0)
+ })
+ .count();
+ completed.set(completed.get() + count);
+ inflight.borrow_mut().remove(&namespace);
+ shard
+ .plane
+ .partitions()
+ .note_consumer_group_offsets_reconcile_needed();
+ });
}
}
+fn group_offset_delete_request(
+ namespace: IggyNamespace,
+ consumer_id: u32,
+) -> Message<RoutedRequestHeader> {
+ let body = DeleteConsumerOffsetRequest {
+ consumer: WireConsumer::consumer_group(WireIdentifier::Numeric(consumer_id)),
+ stream_id: WireIdentifier::Numeric(
+ u32::try_from(namespace.stream_id()).expect("stream id fits u32"),
+ ),
+ topic_id: WireIdentifier::Numeric(
+ u32::try_from(namespace.topic_id()).expect("topic id fits u32"),
+ ),
+ partition_id: Some(u32::try_from(namespace.partition_id()).expect("partition id fits u32")),
+ ack: AckLevel::Quorum,
+ }
+ .to_bytes();
+ let size = size_of::<RoutedRequestHeader>() + body.len();
+ let mut request = Message::<RoutedRequestHeader>::new(size);
+ request.as_mut_slice()[size_of::<RoutedRequestHeader>()..].copy_from_slice(&body);
+ request.transmute_header(|_, header: &mut RoutedRequestHeader| {
+ *header = RoutedRequestHeader {
+ command: Command::Request,
+ operation: Operation::DeleteConsumerOffset,
+ size: u32::try_from(size).expect("offset request fits u32"),
+ client: AUTO_COMMIT_CLIENT_ID,
+ session: 1,
+ request: 1,
+ group: namespace.inner(),
+ ..Default::default()
+ };
+ })
+}
+
/// Complete cooperative consumer-group revocations whose source member has
/// drained the partition (`committed >= last_polled`), was never polled, or
/// timed out. Reads pending revocations from metadata + local partition offset
@@ -1068,21 +1173,23 @@ fn reconcile_pending_revocations(ctx: &ReconcilerCtx) {
/// id (the store path is rewritten to it; the read path resolves it), so the
/// live-set carries those ids too -- otherwise the reconciler would treat every
/// live offset as orphaned and purge it.
-fn snapshot_topic_live_groups(ctx: &ReconcilerCtx) -> AHashMap<(usize, usize), AHashSet<u64>> {
+fn snapshot_topic_live_groups(
+ ctx: &ReconcilerCtx,
+) -> AHashMap<(usize, usize), (u64, AHashSet<u64>)> {
ctx.shard.plane.metadata().mux_stm.streams().read(|inner| {
- let mut map: AHashMap<(usize, usize), AHashSet<u64>> = AHashMap::new();
+ let mut map = AHashMap::new();
for (_, stream) in &inner.items {
for (topic_id, topic) in &stream.topics {
- if topic.consumer_groups.is_empty() {
- continue;
- }
map.insert(
(stream.id, topic_id),
- topic
- .consumer_groups
- .values()
- .map(|group| group.id)
- .collect(),
+ (
+ topic.next_consumer_group_id,
+ topic
+ .consumer_groups
+ .values()
+ .map(|group| group.id)
+ .collect(),
+ ),
);
}
}
@@ -1273,8 +1380,9 @@ pub fn install_tick_handler(shard: &Rc<ServerShard>, wake_tx: WakeTx) {
#[cfg(test)]
mod tests {
use super::{
- FailureCause, FailureRecord, ReconcilerCtx, build_partition_fresh,
- delete_partitions_from_disk, fetch_partition_stats, reconcile_once,
+ FailureCause, FailureRecord, PassCounters, ReconcilerCtx, build_partition_fresh,
+ current_revision, delete_partitions_from_disk, fetch_partition_stats,
+ reconcile_consumer_group_offsets, reconcile_once,
};
use configs::server::{ServerConfig, ServerSystemConfig};
use consensus::{MetadataHandle, PartitionsHandle};
@@ -1621,6 +1729,7 @@ mod tests {
messages_required_to_save: 1,
size_of_messages_required_to_save: iggy_common::IggyByteSize::from(1024_u64),
enforce_fsync: false,
+ consumer_offset_enforce_fsync: false,
validate_checksum: true,
segment_size: iggy_common::IggyByteSize::from(iggy_common::DEFAULT_SEGMENT_SIZE),
preallocate_segments: false,
@@ -2410,6 +2519,21 @@ mod tests {
"unchanged revision after convergence must fast-skip the diff"
);
+ let revision = current_revision(&ctx);
+ shard
+ .plane
+ .partitions()
+ .note_consumer_group_offsets_reconcile_needed();
+ assert_eq!(
+ current_revision(&ctx),
+ revision,
+ "partition-local offset work does not change metadata revision"
+ );
+ assert!(
+ reconcile_once(&ctx).await,
+ "the shard offset epoch must defeat the O(1) fast-skip"
+ );
+
// A new partition-shaping commit bumps the revision → next pass runs.
seed_topic(
&shard.plane.metadata().mux_stm,
@@ -3181,11 +3305,146 @@ mod tests {
);
}
- /// A bare `DeleteConsumerGroup` (topic survives) leaves the group's offsets
- /// on the partition. The reconciler must reclaim a deleted group's offset
- /// while leaving a still-live group's offset untouched.
+ /// Failed delivery must leave the offset and its quota slot intact for a
+ /// later replicated delete. This fixture deliberately has no running pump.
#[compio::test]
- async fn reconcile_reclaims_offsets_of_deleted_consumer_group() {
+ async fn given_pending_group_cleanup_when_another_topic_arrives_should_reconcile_without_waiting()
+ {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let mux = TestMux::default();
+ seed_stream(&mux, 1, "cleanup-stream");
+ seed_topic(&mux, 2, 0, "cleanup-topic", vec![assignment(0, 1)]);
+ seed_create_consumer_group(&mux, 3, 0, 0, "deleted");
+ seed_delete_consumer_group(&mux, 4, 0, 0, 0);
+ let (shard, _inbox) = build_test_shard_with_inbox(0, &config, mux, 32);
+ let ctx = make_ctx(Rc::clone(&shard), 1, Rc::new(config));
+ reconcile_pass(&ctx).await;
+ let namespace = IggyNamespace::new(0, 0, 0);
+ shard
+ .plane
+ .partitions()
+ .with_partition(&namespace, |partition| {
+ partition.seed_recovered_consumer_offset(
+ iggy_common::ConsumerKind::ConsumerGroup,
+ 0,
+ 0,
+ 0,
+ );
+ partition.consumer_group_offsets.pin().insert(
+ iggy_common::ConsumerGroupId(0),
+ iggy_common::ConsumerOffset::new(
+ iggy_common::ConsumerKind::ConsumerGroup,
+ 0,
+ 0,
+ String::new(),
+ ),
+ );
+ });
+ reconcile_consumer_group_offsets(&ctx, &mut PassCounters::default());
+ assert!(
+ ctx.group_offset_cleanup_inflight
+ .borrow()
+ .contains(&namespace)
+ );
+ seed_topic(
+ &shard.plane.metadata().mux_stm,
... 1465 lines suppressed ...