Repository navigation
[rust] Add explicit consumer offset commits and restore - #5201
naivedogger wants to merge 18 commits into
Conversation
Co-Authored-By: Codex <[email protected]> AI-Model: gpt-6 AI-Contributed/Feature: 1305/1305 AI-Contributed/UT: 337/337
|
@fresh-borzoni @pisceslj PTAL, thanks! |
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
|
cc @gyang94 @loserwang1024 🙏 |
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
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), |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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> { |
There was a problem hiding this comment.
In the Java client, configuring a group ID enables auto periodic offset commits by default. Do we consider enabling auto commits in Rust client?
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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(_) => { |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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>>> { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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>>> { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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? { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
loserwang1024
left a comment
There was a problem hiding this comment.
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<()> { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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>; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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() { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
@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? |
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
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)orsubscribe_partition_from_committed(partition_id, bucket_id). Applications usecommit_syncafter processing a batch, orcommit_asyncwith 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).