Skip to content

[rust] Add explicit consumer offset commits and restore - #5201

Open
naivedogger wants to merge 18 commits into
apache:mainfrom
naivedogger:codex/consumer-offset-rust-base
Open

naivedogger wants to merge 18 commits into
apache:mainfrom
naivedogger:codex/consumer-offset-rust-base

Conversation

@naivedogger

@naivedogger naivedogger commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Purpose

Closes #5200. This is the explicit-commit foundation for the Rust client in #5198. A consumer processing manually assigned buckets can save its next offsets and resume from them when it restarts.

#5343 builds on this PR with poll-driven automatic commits, missing-offset policies, multi-table scanning, and group management. #5344 exposes these features in C++, Python, and Elixir.

Brief change log

  • Support explicit sync and async commits and restore from committed offsets on both record and Arrow log scanners. Admin can read selected offsets across tables.
  • Keep commits ordered on one scanner. The deadline includes queueing, owner discovery, and retries. Expired unsent writes are rejected; an attempt that may have reached the server can have an unknown outcome.
  • Return bucket failures with the full set of outcomes, so callers can distinguish acknowledged buckets from failed ones.

Tests

Ran the Rust library suite (1,080 tests), workspace Clippy, and seven consumer-offset integration tests locally. Coverage includes an owner change on a three-TabletServer cluster, group authorization, and Java ↔ Rust restore on partitioned buckets. The bidirectional test requires a Java client with scanner commit support and is explicitly enabled with FLUSS_JAVA_CLASSPATH.

API and Format

Single-table scanners accept subscribe_from_committed(bucket_id) or subscribe_partition_from_committed(partition_id, bucket_id). Applications use commit_sync after processing a batch, or commit_async with a callback. Assignment remains manual. The client uses the existing consumer-offset RPCs and storage format.

Documentation

Added scanner examples and the commit, timeout, and handoff contracts to the Rust API reference.

AI assistance: OpenAI Codex (GPT-6).

Co-Authored-By: Codex <[email protected]>
AI-Model: gpt-6
AI-Contributed/Feature: 1305/1305
AI-Contributed/UT: 337/337
@naivedogger

naivedogger commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor Author

@fresh-borzoni @pisceslj PTAL, thanks!

naivedogger and others added 3 commits November 13, 2026 13:43
Co-Authored-By: Codex <[email protected]>
AI-Model: gpt-6
AI-Contributed/Feature: 0/0
AI-Contributed/UT: 5/5
Distinguish unsent RPC failures from uncertain writes so a closed
connection does not permanently block consumer offset commits.
Wait for partition readiness in the consumer offset integration fixture.

Co-Authored-By: Codex <[email protected]>
AI-Model: gpt-6
AI-Contributed/Feature: 308/308
AI-Contributed/UT: 1/1
Co-Authored-By: Codex <[email protected]>
AI-Model: gpt-6.2-astra
AI-Contributed/Feature: 126/126
AI-Contributed/UT: 7/7
@naivedogger

naivedogger commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

cc @gyang94 @loserwang1024 🙏

naivedogger and others added 2 commits November 18, 2026 14:36
Retry the same snapshot after a broken transport. Keep track of potentially
late writes per bucket so a scanner can advance without risking skipped
records when a caller rewinds.

Co-Authored-By: Codex <[email protected]>
AI-Model: gpt-6
AI-Contributed/Feature: 202/202
AI-Contributed/UT: 72/72
Use the completed poll's exclusive offset for both records and Arrow batches.
Reject negative explicit starting offsets without changing subscriptions.
Separate Admin offset queries from scanner commit state and split the
transport failure tests by outcome.

Co-Authored-By: Codex <[email protected]>
AI-Model: gpt-6
AI-Contributed/Feature: 769/769
AI-Contributed/UT: 404/404
naivedogger and others added 6 commits November 24, 2026 17:25
A stale owner can stall during the handshake before a commit is sent.
Clear the cached endpoint on timeout so the next commit can find the
new owner. Return an error before enqueueing outside a Tokio runtime.

Co-Authored-By: Codex <[email protected]>
AI-Model: gpt-6
AI-Contributed/Feature: 21/21
AI-Contributed/UT: 30/30
Co-Authored-By: Codex <[email protected]>
AI-Model: GPT-6
AI-Contributed/Feature: 106/106
AI-Contributed/UT: 0/0
Co-Authored-By: Codex <[email protected]>
AI-Model: GPT-6
AI-Contributed/Feature: 121/121
AI-Contributed/UT: 33/33
Co-Authored-By: Codex <[email protected]>
AI-Model: GPT-6
AI-Contributed/Feature: 58/58
AI-Contributed/UT: 12/12
Co-Authored-By: Codex <[email protected]>
AI-Model: GPT-6
AI-Contributed/Feature: 64/64
AI-Contributed/UT: 0/0
Co-Authored-By: Codex <[email protected]>
AI-Model: gpt-6
AI-Contributed/Feature: 343/343
AI-Contributed/UT: 44/44
.map(|(bucket, saved)| {
(
bucket,
saved.map_or(crate::client::EARLIEST_OFFSET, |v| v.offset),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A missing commit currently sends every group to EARLIEST_OFFSET. Here we only go to the earliest offset. Could we expose the reset policy through ConsumerGroupOptions, keep earliest as the default, and cover latest and none in the restore tests?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR keeps the earliest offset as the default when there’s no commit. I’ll follow up in #5343 with the latest and none policies and their restore tests.

/// Enables persisted offsets for a manually assigned consumer group.
/// Existing subscriptions still use their explicit starting offsets; use
/// `subscribe_from_committed` to restore them. No background commits are made.
pub fn with_consumer_group(mut self, options: ConsumerGroupOptions) -> Result<Self> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the Java client, configuring a group ID enables auto periodic offset commits by default. Do we consider enabling auto commits in Rust client?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. This PR covers explicit commits. In #5343, configuring a consumer group enables auto-commit by default with a five-second interval. Callers can change the interval or turn it off.


fn delivered_offsets(&self) -> Result<HashMap<TableBucket, OffsetAndMetadata>> {
self.check_no_active_reader()?;
Ok(self.group()?.delivered.lock().clone())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suppose the group has committed offset 40 for bucket 0. The application calls subscribe(0, 100) and then commit_sync() before its first poll. Java’s LogScannerStatus.allConsumed() includes the explicitly assigned position, so the group resumes at 100. Here delivered is still empty, so the commit can succeed while the stored offset remains 40.
Could we include explicitly assigned, nonnegative positions in the no-argument commit snapshot and add a test for this sequence? Prefetched records should still have no effect on that snapshot.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed and covered by a regression test. After subscribe(0, 100), commit_sync() now saves 100 even before the first poll. Prefetch alone doesn’t advance that position.

attempt.started = false;
for (bucket, outcome) in &mut results {
match outcome {
OffsetCommitOutcome::Unknown(_) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An owner change can surface as NOT_CONSUMER_GROUP_OWNER on an individual bucket inside a successful RPC response. Java’s synchronous commit path recognizes this routing error, clears the cached owner, and retries. Could we rediscover the owner and retry the affected buckets within the original deadline, while preserving successful bucket results and any uncertainty from an earlier attempt?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. A bucket-level owner error now triggers rediscovery. We retry only the affected buckets within the original deadline, keep acknowledged buckets out of the retry, and preserve uncertainty if an earlier attempt may have written.

&self,
group_id: &str,
buckets: &[TableBucket],
) -> Result<HashMap<TableBucket, Option<crate::client::OffsetAndMetadata>>> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we return an empty map locally when buckets is empty, after validating the group ID? Java’s listConsumerGroupOffsets(groupId, emptySet) completes immediately. Here we still discover the owner and send GetConsumerOffsets, so a query for zero buckets can time out during an owner outage even though its result is already known.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. With an empty bucket list, we validate the group ID and return an empty map locally, without owner discovery or a fetch RPC.

&self,
group_id: &str,
buckets: &[TableBucket],
) -> Result<HashMap<TableBucket, Option<crate::client::OffsetAndMetadata>>> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does rust client support query all buckets in a groupId? e.g. when buckets is null, then we query all buckets offsets in this group.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, in #5343: admin.list_consumer_offsets(group_id).await returns all committed offsets for the group that the caller can see. An empty slice passed to get_consumer_offsets still means zero buckets.


// todo: check fetch result code for per-bucket
let Some(fetch_offset) = log_scanner_status.get_bucket_offset(&table_bucket) else {
// Keep validation and enqueue atomic with a seek that clears the old buffer.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The version check here handles a response that arrives after a seek. I reproduced the reverse ordering: an out-of-range error for offset 8 is already buffered, the caller resubscribes at a valid offset of 20, and the next poll still reports the error for offset 8.

Could we store the bucket’s assignment_version with each buffered fetch and check it before delivering records or surfacing errors? A regression test could enqueue the error first, resubscribe the bucket, and verify that the next poll discards the old error.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. Resubscribing now clears that bucket’s buffered fetches under the assignment lock. The version check still handles late responses. I added a regression test for the offset 8 → 20 case you reproduced.

let start = Instant::now();
let deadline = start + timeout;
let deadline = tokio::time::Instant::now() + timeout;
if !self.restore_committed_offsets(deadline).await? {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we move group.invoke_callbacks(false) before restore_committed_offsets(...) in both poll_records and poll_batches? Suppose a commit for bucket A has already completed when poll starts. If the offset lookup for bucket B times out or fails, poll returns before invoking A’s callback. Repeated lookup failures can leave the caller waiting for a result the scanner already has.

A regression test could start with A’s callback ready and B’s lookup still pending, then call poll(Duration::ZERO). The poll should return no records and invoke A’s callback exactly once.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved callback delivery ahead of offset restoration in both poll paths. The regression test keeps the lookup pending and calls poll(Duration::ZERO): it returns no records but still delivers the ready callback.

@naivedogger

Copy link
Copy Markdown
Contributor Author

@gyang94 Thanks for the detailed review! I’ve addressed the feedback and noted the follow-ups in #5343. Could you take another look when you have a chance?

@loserwang1024 loserwang1024 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed against 0e46ecdbe0ae987bef06fa293989a999e8989fc6.

Please align the single-table committed-offset subscription APIs with the existing subscribe / subscribe_partition APIs before merging, and fix the empty-commit case described inline. The other inline comments cover API contracts, usability, and integration coverage; they are separate from the reproduced empty-commit issue.

Please also expand the PR description using the repository template. In particular, make the scope and dependencies explicit: this PR provides the Rust explicit-commit foundation, #5343 adds automatic commits/reset policies/full management, and #5344 exposes the language bindings. The existing discussions already track those follow-ups.

Validation performed during this review: all 1,077 Rust library unit tests passed on this revision. An additional local regression test showed that an empty commit attempts owner discovery and fails without bootstrap servers; the test passed after adding a local empty-result return inside the ordered commit execution path. No real-cluster or C++ integration tests were run during this review.

impl $scanner {
/// Registers buckets now; poll looks up this group's committed offsets before reading.
/// A missing commit starts at earliest. A lookup error is returned by poll.
pub fn subscribe_from_committed(&self, buckets: &[TableBucket]) -> Result<()> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please align these public entry points with the existing subscription APIs: subscribe_from_committed(bucket_id) and subscribe_partition_from_committed(partition_id, bucket_id), matching subscribe and subscribe_partition.

A single-table scanner already knows its table ID. Switching from an explicit starting offset to a committed offset should not require callers to obtain that ID, construct a fully qualified TableBucket, and wrap it in a collection. This is inconsistent both with Java's single-table API and with Rust's existing subscription methods. Batch entry points can have explicit batch names, while all variants reuse the current restore implementation internally. This request concerns names and parameters; it does not require making deferred registration async.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A single-table scanner no longer requires callers to look up its table ID. Use subscribe_from_committed(bucket_id) or subscribe_partition_from_committed(partition_id, bucket_id), matching subscribe and subscribe_partition. The batch form is now subscribe_buckets_from_committed; all three still resolve the starting offset on poll.

&self,
offsets: HashMap<TableBucket, OffsetAndMetadata>,
) -> std::result::Result<OffsetCommitResult, OffsetCommitError> {
let mut request = self

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Please handle an empty offset map as a successful no-op, consistent with Java. Currently commit_request creates tables: [], but execution still discovers the owner and sends an RPC. An empty commit can therefore fail or time out during an owner outage even though there is nothing to persist. This can occur before any positions are established, after all buckets are unsubscribed, or with an explicitly empty map.

I reproduced this with commit_sync(HashMap::new()) and metadata with no bootstrap servers: it returns Rejected(IllegalArgument("No bootstrap servers configured")) instead of an empty success. Returning an empty result here made that regression test pass. Please keep this handling inside the ordered execution path so preceding commits and callback ordering are preserved.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An empty commit now succeeds without contacting the server. It still goes through the scanner’s queue, so a successful empty commit_sync() delivers earlier async callbacks before returning. I added a regression test for the no-bootstrap case you reproduced.

let group = self.clone();
let (reply, response) = tokio::sync::oneshot::channel();
runtime.spawn(async move {
if let Some(previous) = previous {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

API contract: the operation timeout starts inside commit, only after this wait for preceding commits. Although documented, this means a synchronous commit configured for 30 seconds can wait for several minutes behind queued operations, unlike Java's caller-visible synchronous commit timeout.

Please include queueing time in the operation deadline, starting at admission and using the remaining budget for discovery, connections, and retries. An operation whose deadline expires before dispatch should not subsequently send its request; distinguish that rejection from a timeout after dispatch, where the outcome may be unknown. An outer timeout on the waiting caller alone would not address this because the spawned task survives cancellation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The timeout now starts when the commit enters the queue. Waiting behind an earlier commit, discovering the owner, and waiting for the connection’s write lock all use the same deadline. If it expires before any attempt starts writing, the commit is rejected and won’t be sent later. If a write already started, its outcome may be unknown.

}

/// Per-bucket commit outcomes; contains exactly the requested buckets.
pub type OffsetCommitResult = HashMap<TableBucket, OffsetCommitOutcome>;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

API usability suggestion: scanner.commit_sync().await? can return successfully while individual buckets are Rejected or Unknown. The documentation explains this, but it is easy to miss when migrating from Java, where a bucket failure makes the synchronous scanner commit throw.

Please provide a standard aggregate success check, such as is_success() or an ensure_all_committed() helper that preserves the per-bucket failure details, and use it in the examples. Callers should not need to reimplement the same validation loop after every commit. The C++ binding's aggregate OffsetCommitResult::Ok() is a useful equivalent.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If bucket A succeeds and bucket B fails, commit_sync().await now returns Err(BucketFailures(...)) with both bucket outcomes. commit_async delivers the same error to its callback; its immediate return value only tells the caller whether the commit was queued.

pub(crate) async fn await_pending_commits(&self) {
// Each queued operation releases its permit only after its outcome is known locally.
let drain = self.slots.acquire_many(MAX_PENDING_COMMITS as u32);
if tokio::time::timeout(self.client.options.timeout, drain)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lifecycle contract: please clarify and test what happens to queued commits when close times out. From code inspection, this timeout only stops draining; the tasks spawned by enqueue remain alive and can start sending requests after close returns. invoke_callbacks(true) reports unknown outcomes but does not stop those tasks. This makes replacing a consumer difficult even for operations that had not reached the server when it was closed.

Please stop undispatched queued operations at the close deadline, distinguish them from already-dispatched requests with unknown outcomes, and make an incomplete drain observable to the caller rather than only logging it. A deterministic test should hold the first commit pending, queue another, close the scanner, release the first operation, and verify that the second request is not newly dispatched after close. This observation is based on code inspection; I have not run that lifecycle regression test.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed the case you described. close() now reports a drain timeout, and the regression test verifies that a queued commit rejected during close is never sent afterward.

For applications that need an ordered handoff, I think commit_sync() on the old scanner is the right synchronization point. For example, the old scanner submits 100 asynchronously, then commits 150 synchronously. By the time the second call succeeds, the callback for 100 has already run. If both succeeded, the application can close the old scanner and start the new one at 150. If the callback for 100 reported Unknown, that earlier write could still arrive after 150.

}

#[tokio::test]
async fn restore_skips_a_range_consumed_by_a_zero_row_poll() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add interoperability coverage in both directions: Java commits and Rust restores, then Rust commits and Java restores, including partitioned buckets, missing offsets, next-offset semantics, and metadata. Java normalizes absent metadata to an empty string, whereas Rust preserves None versus an empty string, so the expected round-trip behavior should be explicit.

Please also cover owner failover against a real multi-TabletServer cluster and group/table authorization failures, asserting that authorization errors propagate without falling back to earliest. The scripted RPC tests exercise the client state machine, but they do not establish these server and cross-language contracts. These are coverage requests, not claims that the corresponding paths are currently broken.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a two-partition interop test: Java commits 3 in A and leaves B unset; Rust starts at 3 and 0, then commits 5 in A, and Java resumes at 5. Both directions check metadata strings. The absent-metadata conversion (Rust None → Java "") isn’t covered by this test yet.

I also tested failover with three TabletServers: after the owner stops, the original Rust scanner commits to the new owner, and a fresh scanner resumes at that offset. Denied group access is covered by an integration test; I verified table-permission revocation locally. In both cases poll returns the authorization error instead of reading from earliest.

@naivedogger

Copy link
Copy Markdown
Contributor Author

@loserwang1024 Thanks for the detailed review and for reproducing the empty-commit issue. I’ve updated the scanner APIs and commit lifecycle, added interop and failover tests, and clarified what belongs in #5343 and #5344. Could you take another look when you have a chance?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[rust] Add explicit consumer offset commits and restore

3 participants