Skip to content

[Fix][Connector-V2] Surface RocketMQ group-offset lookup failures instead of rewinding - #12349

Merged
nzw921rx merged 1 commit into
apache:devfrom
SEPURI-SAI-KRISHNA:fix-rocketmq-group-offset-rewind
Sep 21, 2026
Merged

nzw921rx merged 1 commit into
apache:devfrom
SEPURI-SAI-KRISHNA:fix-rocketmq-group-offset-rewind

Conversation

@SEPURI-SAI-KRISHNA

@SEPURI-SAI-KRISHNA SEPURI-SAI-KRISHNA commented Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator

Purpose of this pull request

Closes #12332.

RocketMqAdminUtil.currentOffsets treated a TOPIC_NOT_EXIST (code 17) failure as proof that a consumer group had committed nothing, returning Collections.emptyMap(). Its only production caller, RocketMqSourceSplitEnumerator.setPartitionStartOffset(), reads an empty map under CONSUME_FROM_GROUP_OFFSETS as a cold start and falls back to CONSUME_FROM_FIRST_OFFSET, so a lost route silently replayed a whole topic while the committed offsets were intact.

The first version of this PR removed that swallow outright. @DanielLeens showed it regresses ordinary cold start, and he was right: DefaultMQAdminExtImpl.examineConsumeStats(group, topic) resolves its route solely from the group's auto-generated %RETRY% topic, never from the requested topic, so code 17 is also what a brand new group returns before its retry topic has been created.

Code 17 therefore has two meanings that have to be separated:

  • the group has never registered, so its retry topic does not exist yet. Legitimately empty, and a cold start is the right answer.
  • a route was lost. Offsets exist but are briefly unreadable, and answering "empty" replays the topic.

This patch separates them by re-resolving the requested topic on the admin client that is already open. The name server removes routes per broker rather than per topic (RouteInfoManager.scanNotActiveBroker closes the channel, then onChannelDestroy sweeps topicQueueTable keyed by brokerName), so an outage takes the requested topic's route along with the retry topic's, while a group that has simply never registered leaves it intact.

  • route still resolves: return an empty map exactly as before, and log a WARN naming the reason
  • route fails too: throw RocketMqConnectorException with GET_CONSUMER_GROUP_OFFSETS_ERROR

What makes the first branch safe rather than a guess is that a group cannot commit an offset without having created its retry topic first. ClientManageProcessor.heartBeat creates %RETRY% plus the group name before it reaches ConsumerManager.registerConsumer, guarded only on the subscription group config that SubscriptionGroupManager auto-creates by default, and a group without that config cannot pull at all (PullMessageProcessor rejects it with subscription group [%s] does not exist).

Two cases this does not cover, both behaving exactly as dev does today: deleting the retry topic from the name server underneath a live group, and a scale-out window where a new broker carries the data topic before the consumer has heartbeated to it.

Also in this change: a package-private currentOffsets overload taking an already-started DefaultMQAdminExt as a test seam, and InterruptedException now re-interrupts the current thread before being wrapped. No new option, no retry policy, no new dependency, and the public signature is unchanged.

Does this PR introduce any user-facing change?

Yes. A job using CONSUME_FROM_GROUP_OFFSETS that previously survived a transient route loss by silently restarting from the first offset will now fail with RocketMqConnectorException carrying GET_CONSUMER_GROUP_OFFSETS_ERROR. That is the intended trade: a visible failure an operator can retry is better than an invisible full topic replay into the sink. Ordinary cold start is unchanged. No config option, default value, or public API changes.

How was this patch tested?

./mvnw -q -DskipTests verify -pl seatunnel-connectors-v2/connector-rocketmq on JDK 11 passes, which covers the enforcer checks, spotless:check, compilation and the shade step. ./mvnw -pl seatunnel-connectors-v2/connector-rocketmq test on JDK 11: 23 tests, 0 failures, 0 errors.

RocketMqAdminUtilTest drives examineConsumeStats and examineTopicRouteInfo through the seam:

  • code 17 with the requested topic still resolving returns an empty map, so the cold start is preserved
  • code 17 with the requested topic also failing throws
  • a response code other than 17 throws even when the route is healthy
  • a successful lookup matching none of the requested queues still returns empty
  • a successful lookup that does match returns the committed offset unchanged

RocketMqSourceSplitEnumeratorTest.testRun_doesNotFallBackToFirstOffsetWhenGroupOffsetLookupFails pins the behaviour at the call site: the failure propagates, flatOffsetTopics is never reached, and no split is assigned.

I also checked that these tests fail for the right reasons rather than passing by luck. Dropping the route guard, which leaves code 17 unconditionally empty, fails only testCurrentOffsets_routeOutageSurfacesAsFailure. Dropping the code 17 branch entirely, which is what the first version of this PR did, fails only testCurrentOffsets_retryTopicMissingWhileRouteHealthyReturnsEmpty. Every other test passes under both mutations.

No new E2E test is included, which I want to flag against the convention that a change in an area with an existing IT should update that IT. The scenario can be injected in principle, since the name server exposes per topic route deletion, but the helper that would be used for it (RocketMqIT.deleteTopicIfExist) does not currently work: it passes broker names where addresses belong and the literal "delete_topic" where the cluster name belongs, and a blanket catch hides the result, so in the CI run on the previous commit it logged connect to null failed 14 times and Deleted topic zero times. Fixing that belongs in its own change. If you would rather this PR wait for that, I am happy to do it in the other order.

A note on the base

#12323 has now merged (fc1d08d32), so this branch is rebased directly onto dev and the diff is back to the three connector files. The RocketMqIT.java change that previously appeared here belonged to #12323 and has dropped out.

The green rocketmq-connector-it run referenced above was produced on 4e5a44a, which carried #12323's fix as unmerged commits underneath. The rebase changes the base but not the tree, so the code being reviewed is unchanged.

@DanielLeens DanielLeens 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.

What Problem Does This PR Solve?

RocketMqAdminUtil.currentOffsets used to treat any MQClientException whose response code was TOPIC_NOT_EXIST (17) as proof that the consumer group had committed nothing, and silently returned Collections.emptyMap(). The only production caller, RocketMqSourceSplitEnumerator.setPartitionStartOffset() (CONSUME_FROM_GROUP_OFFSETS branch), reads an empty map as "cold start" and falls back to CONSUME_FROM_FIRST_OFFSET, replaying the whole topic. Since code 17 is also what the name server returns for a topic whose route is momentarily missing (not just for a topic that never existed), a transient metadata gap could previously cause a full, silent topic replay even though the committed offsets were intact. This PR removes that swallow: any failure out of examineConsumeStats (including code 17) now throws RocketMqConnectorException instead of being reported as "nothing committed."

1. Code Change Review

1.1 Core Logic Analysis

Before (dev, RocketMqAdminUtil.java:298-317):

} catch (MQClientException | MQBrokerException | RemotingException | InterruptedException e) {
    if (e instanceof MQClientException) {
        if (((MQClientException) e).getResponseCode() == ResponseCode.TOPIC_NOT_EXIST) {
            return Collections.emptyMap();
        } else {
            throw new RocketMqConnectorException(GET_CONSUMER_GROUP_OFFSETS_ERROR, e);
        }
    } else {
        throw new RocketMqConnectorException(GET_CONSUMER_GROUP_OFFSETS_ERROR, e);
    }
}

After (RocketMqAdminUtil.java:326-335):

} catch (MQClientException | MQBrokerException | RemotingException | InterruptedException e) {
    if (e instanceof InterruptedException) {
        Thread.currentThread().interrupt();
    }
    throw new RocketMqConnectorException(GET_CONSUMER_GROUP_OFFSETS_ERROR, e);
}

Runtime flow for the change:

RocketMqSourceSplitEnumerator.run()
  -> fetchPendingPartitionSplit()          [offsetTopics(); no TOPIC_NOT_EXIST branch, fails first for a truly absent topic]
  -> setPartitionStartOffset()
      case CONSUME_FROM_GROUP_OFFSETS:
        -> listConsumerGroupOffsets(queues)
            -> RocketMqAdminUtil.currentOffsets(config, topics, queues)
                -> currentOffsets(adminClient, groupId, topics, queues)   [new package-private overload]
                    -> adminClient.examineConsumeStats(groupId, topic)   <-- CHANGED CATCH BLOCK HERE

I traced this against current dev source, and the ordering claim in the PR description is correct: offsetTopics() (called first, via fetchPendingPartitionSplit()) has no TOPIC_NOT_EXIST special-casing and throws GET_MIN_AND_MAX_OFFSETS_ERROR for a topic with no route at all, so a genuinely nonexistent requested topic never reaches the changed branch. The refactor into a package-private currentOffsets(DefaultMQAdminExt, String, List, Set) overload as a test seam is clean, keeps the public signature and adminClient.shutdown() ownership unchanged, and is a real improvement in its own right: it re-interrupts the thread on InterruptedException before wrapping, which the old code did not do.

However, the PR's central safety argument — "TOPIC_NOT_EXIST on this call path only ever means a momentarily-unavailable route, never a topic that legitimately doesn't exist yet" — is disproved by the PR's own CI run on this exact commit. DefaultMQAdminExt#examineConsumeStats(groupId, topic) does not only resolve the requested topic; RocketMQ auto-subscribes every consumer group to its retry topic (%RETRY%<consumerGroup>), and the broker's consume-stats query also resolves that retry topic's route as part of answering the group's consume stats. The retry topic is only created lazily, the first time a message for that group is nacked/retried — so for essentially every freshly created consumer group (the normal cold-start case this PR is supposed to protect), %RETRY%<group> legitimately does not exist yet, and examineConsumeStats throws MQClientException: CODE: 17 DESC: No topic route info in name server for the topic: %RETRY%<group>.

Evidence from the PR's own fork CI run (35098129976, head SHA a47cd5f1281d7e31c6717f996a2d480c9b1cfd7c, i.e. the exact code under review):

  • rocketmq-connector-it (11, ubuntu-latest): Tests run: 87, Failures: 21, Errors: 29 — https://github.com/SEPURI-SAI-KRISHNA/seatunnel/actions/runs/35098129976/job/104874436406 job 104804402226
  • rocketmq-connector-it (8, ubuntu-latest): same failure pattern, job 104804402155
  • Stack traces point directly at the changed code:
    Caused by: org.apache.seatunnel.connectors.seatunnel.rocketmq.exception.RocketMqConnectorException:
        ErrorCode:[ROCKETMQ-09], ErrorDescription:[Failed to get the offsets of the current consumer group]
        at RocketMqAdminUtil.currentOffsets(RocketMqAdminUtil.java:333)
        at RocketMqAdminUtil.currentOffsets(RocketMqAdminUtil.java:293)
        at RocketMqIT.getRocketMqConsumerData(RocketMqIT.java:516)
    Caused by: org.apache.rocketmq.client.exception.MQClientException:
        CODE: 17  DESC: No topic route info in name server for the topic: %RETRY%SeaTunnel-rocketmq-group
        at RocketMqAdminUtil.currentOffsets(RocketMqAdminUtil.java:316)
    
  • Counting the exact retry-topic route message across the JDK 11 job log: 169 occurrences (%RETRY%SeaTunnel-Consumer-Group: 155, %RETRY%SeaTunnel-rocketmq-group: 14), 162 of which trace through RocketMqAdminUtil.currentOffsets(RocketMqAdminUtil.java:316) — the exact line this PR changed. The JDK 8 job shows the same pattern against several distinct generated group names (36/24/22/22/22/15/14 occurrences respectively).

This is not flaky/environmental noise (contrast with the author's own, separately-tracked test_topic_source / GET_MIN_AND_MAX_OFFSETS_ERROR failures from offsetTopics(), an unrelated, pre-existing code path this PR does not touch). It is a deterministic consequence of this diff: on dev, the exact same %RETRY%<group>-route-missing exception was silently absorbed as Collections.emptyMap() and the caller correctly fell back to a cold start — which is precisely why this condition never showed up as a test failure before. This PR removes that absorption without adding any handling for the retry-topic case, so it now turns a near-universal, expected condition (fresh consumer group, no retries yet) into a hard RocketMqConnectorException that fails the split enumerator's run() and, per SourceSplitEnumeratorTask.stateProcess() (STARTING state, enumerator.run() called unguarded), fails the job.

Issue 1: The fix breaks the ordinary CONSUME_FROM_GROUP_OFFSETS cold-start path for (almost) every fresh consumer group — proven by this PR's own CI run

  • Location: seatunnel-connectors-v2/connector-rocketmq/src/main/java/org/apache/seatunnel/connectors/seatunnel/rocketmq/common/RocketMqAdminUtil.java:326-335
  • Problem description: examineConsumeStats(groupId, topic) also resolves the group's auto-generated retry topic (%RETRY%<groupId>), which does not exist until the group's first retried message. That is the default state for a brand-new consumer group, not a transient failure. Because the new catch block no longer distinguishes "this specific requested topic has a route problem" from "the group's own never-yet-created retry topic has no route," it converts this completely normal case into a hard failure.
  • Potential risk: A job with start.mode = CONSUME_FROM_GROUP_OFFSETS against a brand-new consumer group (the common case for a first run, or any group that has never had a message go to retry) now fails at startup with RocketMqConnectorException/GET_CONSUMER_GROUP_OFFSETS_ERROR instead of correctly cold-starting. This is a regression from "always starts" to "usually fails," which is a materially worse outcome for ordinary users than the transient-route-gap bug being fixed. It is already demonstrated end-to-end by this PR's own CI (21 failures / 29 errors out of 87 tests in the connector's own E2E suite).
  • Best improvement:
    • Option A (minimal, targeted): when the caught MQClientException is TOPIC_NOT_EXIST and the topic named in the failure is the group's own derived retry topic ("%RETRY%" + groupId), treat that specific failure as "no retry backlog yet" (contribute nothing for it) rather than failing the whole lookup; any other TOPIC_NOT_EXIST/failure (i.e., for a topic the caller actually asked about) still surfaces as RocketMqConnectorException as this PR intends.
    • Option B (matches the fix the author already proposed in the linked issue #12332): before concluding "nothing committed" vs. "failure," consult the existing RocketMqAdminUtil.topicExist(config, topic) helper (already in this class) for the requested topic specifically, rather than trusting the response code from examineConsumeStats, which conflates the requested topic and the retry topic.
    • Either option needs its own regression test reproducing "fresh consumer group, retry topic not yet created" alongside the existing TOPIC_NOT_EXIST-surfaces-as-failure test, so the fix for #12332 can't silently regress this path again.
  • Severity: High (blocking — main cold-start path failure, proven by CI on this exact commit)
  • Raised by another reviewer: No

1.2 Compatibility Impact

Partially incompatible, and more broadly than the PR description states. The PR description correctly discloses that a job relying on the old "rewind on transient failure" behavior will now fail loudly instead — that trade-off is reasonable and is the intended fix for #12332. What is not disclosed, and what the evidence above shows, is that the same code path now also fails loudly for a class of jobs that were never relying on any bug: an ordinary first-time CONSUME_FROM_GROUP_OFFSETS job against a consumer group that has never had a retried message. That is an ordinary/majority-case cold start, not an edge case, and it did not fail on dev. No config option, default, or public API is changed, so this doesn't rise to "Incompatible" in the API/protocol/serialization sense, but the observable behavior break on the normal path is severe enough to block on its own (see Issue 1).

The checkpoint-restore path is unaffected: setPartitionStartOffset() (RocketMqSourceSplitEnumerator.java:333-344) explicitly skips any MessageQueue present in restoredSplits, which is populated only via addSplitsBack() when isRestored && !initialized (i.e., only for splits carrying checkpoint-restored offsets). Restored splits never call listConsumerGroupOffsets()/currentOffsets(), so this diff cannot affect the checkpoint/restore path — this matches the PR description's claim, verified directly in the current dev source, not just asserted from the description.

1.3 Performance / Side-Effect Analysis

No new allocations, threads, locks, retries, or network calls are introduced. The admin client lifecycle (startMQAdminTool / adminClient.shutdown() in the outer method's finally) is unchanged. The InterruptedException handling is strictly better than before (re-interrupts the thread before wrapping, where the old code silently dropped the interrupt flag). No resource-leak or concurrency concerns.

1.4 Error Handling and Logging

The thrown RocketMqConnectorException carries the original MQClientException/MQBrokerException/RemotingException as cause, so the context (including the offending topic name, visible in the CI logs above) is preserved for operators. No sensitive data is logged. No new log statements were added; none were needed for this change in isolation, but see Issue 1 — once the retry-topic case is handled, it would be worth a WARN-level log noting "retry topic not yet created, treated as no backlog" so operators can distinguish that from a real route problem when debugging.

2. Code Quality Assessment

2.1 Coding Standards

Good. The new package-private currentOffsets(DefaultMQAdminExt, String, List, Set) has a clear Javadoc explaining why it exists (test seam) and its scope. The updated Javadoc on the public currentOffsets(...) overload correctly documents the new contract. The new test class RocketMqAdminUtilTest has class-level Javadoc explaining the contract under test, and each test method has a one-line Javadoc explaining the scenario, consistent with this repo's "no @DisplayName, use Javadoc" convention. No style issues found.

2.2 Test Coverage and Test Stability

The new/changed tests are all deterministic, mock-based (Mockito mock/mockStatic), with no Thread.sleep, no shared static state across tests, and no order dependence — Stability rating: Stable for the tests this PR adds.

That said, test coverage has a real gap directly related to Issue 1: none of the new tests (RocketMqAdminUtilTest, or the new RocketMqSourceSplitEnumeratorTest.testRun_doesNotFallBackToFirstOffsetWhenGroupOffsetLookupFails) exercise the retry-topic-not-yet-created scenario, which is exactly the scenario that fails in the connector's own E2E suite (RocketMqIT) against this commit. The unit tests prove the intended new contract in isolation; they do not prove the change is safe against the connector's actual RocketMQ admin API surface, which the E2E run does — and the E2E run fails. The PR text explains at length why no new E2E test was added for the original transient-route-gap scenario (avoiding a race with broker heartbeat re-registration); that reasoning doesn't apply here, since the existing, unmodified E2E suite already reproduces the regression deterministically without any new test being written.

2.3 Documentation Updates

No docs/en/docs/zh changes. None are needed: no config option, default, or documented behavior contract changes (the RocketMQ connector docs don't describe this failure-handling nuance today).

3. Architectural Soundness

3.1 Elegance of the Solution

The refactor itself (extracting the package-private overload as a test seam, tightening the InterruptedException handling) is a precise, well-scoped change and a genuine improvement. The core semantic fix, however, is currently a temporary workaround at best — it swaps one incorrect blanket assumption ("TOPIC_NOT_EXIST always means nothing committed") for another incorrect blanket assumption ("TOPIC_NOT_EXIST never means nothing committed"), when the real fix needs to distinguish the two cases (see Issue 1, Option A/B), as the author themselves originally scoped it in the linked issue's "Possible fix" section before narrowing to this PR.

3.2 Maintainability

Good. The package-private test seam is a reasonable, minimal pattern that avoids introducing mocking frameworks for static broker interactions beyond what's already used elsewhere in this test class (Mockito.mockStatic).

3.3 Extensibility

Neutral — this is a narrowly scoped bugfix, not a new extension point.

3.4 Historical-Version Compatibility

Not applicable in the checkpoint/serialization sense (no state format, protocol, or serialization changes). See 1.2 for the observable-behavior compatibility concern, which is the operative compatibility issue for this PR.

4. Issue Summary

Number Issue Location Severity
1 Fix breaks the ordinary CONSUME_FROM_GROUP_OFFSETS cold-start path for fresh consumer groups (CI-proven on this commit) RocketMqAdminUtil.java:326-335 High

5. Merge Recommendation

Conclusion: Not recommended for merge

  1. Blockers — must be fixed:

    • Issue 1: handle the auto-generated %RETRY%<groupId> topic's "not yet created" case as legitimate emptiness rather than a hard failure, distinguishing it from a genuine transient-route problem on the caller's actually-requested topic (Option A or B above), and add a regression test for it (unit and/or a targeted assertion in RocketMqAdminUtilTest) so this can't silently regress again. The PR's own fork CI run (rocketmq-connector-it, both JDK 8 and 11) is currently red because of exactly this gap — 21 failures / 29 errors out of 87 tests on the JDK 11 job alone, all traceable to RocketMqAdminUtil.currentOffsets(RocketMqAdminUtil.java:316).
  2. Recommended fixes — non-blocking: once Issue 1 is addressed, consider a WARN-level log line for the "retry topic not yet created" case so operators can tell it apart from a genuine route outage when reading logs.

Overall: the diagnosis in #12332 and the direction of this fix (stop silently rewinding on a failed lookup) are correct and worth pursuing — the problem is specifically that examineConsumeStats(groupId, topic)'s implicit dependency on the group's retry-topic route wasn't accounted for, and that's exactly the class of case the old swallow was (accidentally) also protecting against. I'd like to see this land once the retry-topic case is handled explicitly and the connector's own E2E suite is green on the PR's own fork CI. Thank you for the very thorough issue writeup and the CI-timing investigation in #12323/#12332 — that rigor made this easy to verify quickly; the retry-topic interaction is a genuinely easy thing to miss since it's internal to RocketMQ's client/broker protocol rather than anything visible in this connector's own code.

🤖 Generated with Claude Code

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

You're right, and I reproduced it. The retry-topic interaction is a real defect in my change and I missed it entirely.

One correction on attribution first. I counted the 50 failure markers in the JDK 11 job:

cause tests
broker[broker-a] not exist at generateTestData:467 22
ROCKETMQ-11 from offsetTopics 14
ROCKETMQ-09 via the %RETRY% route 14

36 of those are the pre-existing #12322 flakiness that #12323 fixes, which this branch doesn't carry. One test settles it anyway: testSourceRocketMqTextToConsole fails 7 of 7, inside the submitted job, at run:180 -> setPartitionStartOffset:380 -> listConsumerGroupOffsets:457 on CODE: 17 %RETRY%SeaTunnel-Consumer-Group, and it never failed once in the 12 daily Schedule Backend runs I sampled for #12322.

Code 17 can be told apart from a route gap

I went through the 4.9.4 bytecode, which is both what the connector pins and what the E2E image runs.

DefaultMQAdminExtImpl.examineConsumeStats resolves its route only from %RETRY%<group>: offsets 0-7 are getRetryTopic then examineTopicRouteInfo, with no try/catch and no fallback. The requested topic is only a parameter to the later getConsumeStats broker call, which throws MQBrokerException rather than MQClientException, and getTopicRouteInfoFromNameServer always throws on code 17 instead of returning null. So any MQClientException carrying code 17 out of examineConsumeStats is the retry topic and nothing else, without having to parse the topic name out of the message.

RouteInfoManager decides the other half. BROKER_CHANNEL_EXPIRED_TIME is 120000L, and scanNotActiveBroker closes the channel then calls onChannelDestroy, which sweeps topicQueueTable keyed by brokerName. Route loss is broker scoped rather than topic scoped, so a genuine gap takes %RETRY%<group> and the data topic together. The only thing that removes one topic's route on its own is RouteInfoManager.deleteTopic, which is deliberate admin action.

That is why Option A unguarded would put the bug back. It reads a real gap as a cold start and rewinds exactly as dev does, leaving #12332 open underneath a PR that claims to close it.

Option B is out for the reason you gave me on #12332: topicExist swallows code 17 and returns false (RocketMqAdminUtil.java:196-198), so it carries the same ambiguity.

What I'll implement

Option A with one guard. On code 17, probe the requested topic's route using the admin client already open:

  • resolves, so the name server is healthy and the retry topic is genuinely absent: contribute nothing for that topic and carry on, preserving today's cold start
  • also fails, so the gap is broker wide: throw, as this PR intends

Plus the WARN line you asked for on the first branch.

Two things make that first branch safe rather than a guess. ClientManageProcessor.heartBeat creates %RETRY%<group> at offsets 132-163, before registerConsumer at 200, guarded only on the subscription group config that SubscriptionGroupManager auto-creates by default; a group without one can't pull at all, since PullMessageProcessor rejects it with subscription group [%s] does not exist. So committed offsets imply the retry topic was created. Separately, setPartitionStartOffset has a single call site at run():180, immediately after fetchPendingPartitionSplit():179 under the same lock, and discoverySplits():280 never calls it; since offsetTopics resolves the requested topic through examineTopicStats -> examineTopicRouteInfo, that route was live microseconds before the probe runs.

Two cases it still won't cover, both behaving exactly as dev does today: someone deleting %RETRY%<group> out from under a live group, and a scale-out window where a new broker carries the data topic before the consumer has heartbeated to it.

E2E and CI

I said in the description that this couldn't be injected deterministically, which was too strong, since per-topic deletion does exist and dropping only the retry topic would do it. But deleteTopicIfExist (RocketMqIT.java:903-925) doesn't currently work: it passes broker names where addresses belong and the literal "delete_topic" where the cluster name belongs, and the blanket catch hides the result. In this job it logs connect to null failed 14 times and Deleted topic zero times. I'll raise that on its own rather than widen this PR, and cover both branches here with unit tests on the existing seam, which has no timing window.

On wanting the connector E2E green here before merge: that can't happen while #12323 is unmerged, since the 36 failures above are the ones it fixes. The two PRs touch disjoint files, so I'll rebase onto that branch and note it in the description.

If you'd still rather have Option A unguarded, say so and I'll cut the probe. Thanks for catching this.

@DanielLeens DanielLeens 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.

Thanks for the very thorough follow-up on the retry-topic issue, and for reproducing it and walking through the RocketMQ 4.9.4 client/broker internals in such detail. I re-reviewed the current head (4e5a44a) from scratch rather than just the incremental diff, and the guarded fix you landed does resolve the blocking issue from my last review: the connector's own rocketmq-connector-it suite, which was failing 21/29 (JDK 11) and similarly on JDK 8 against the previous commit, is now green on both JDK 8 and JDK 11 against this head. Nice work tracking down the actual invariant (retry-topic creation gated on subscription-group registration) instead of just papering over the symptom.

What Problem Does This PR Solve?

RocketMqAdminUtil.currentOffsets previously treated any MQClientException with response code TOPIC_NOT_EXIST (17) as proof the consumer group had committed nothing, returning Collections.emptyMap(). The only caller, RocketMqSourceSplitEnumerator.setPartitionStartOffset() (CONSUME_FROM_GROUP_OFFSETS branch), reads an empty map as "cold start" and rewinds to CONSUME_FROM_FIRST_OFFSET. Since examineConsumeStats(groupId, topic) resolves its route from the group's auto-generated retry topic (%RETRY%<groupId>), not from the requested topic, a transient route outage on that retry topic could previously cause a full silent topic replay even with intact committed offsets. This PR removes the blind swallow and instead disambiguates: on TOPIC_NOT_EXIST, it probes the requested topic's own route via examineTopicRouteInfo. If that route still resolves, the group has simply never registered (no retry topic yet, a genuine and common cold start) and the lookup returns empty. If the requested topic's route is also gone, the outage is broker-wide and the failure now surfaces as RocketMqConnectorException instead of a silent rewind.

1. Code Change Review

1.1 Core Logic Analysis

Current head, RocketMqAdminUtil.java:326-386 (package-private overload used as the real implementation, and as a test seam):

static Map<MessageQueue, Long> currentOffsets(
        DefaultMQAdminExt adminClient, String groupId, List<String> topics, Set<MessageQueue> messageQueues) {
    Map<MessageQueue, OffsetWrapper> consumerOffsets = Maps.newConcurrentMap();
    for (String topic : topics) {
        try {
            ConsumeStats consumeStats = adminClient.examineConsumeStats(groupId, topic);
            consumerOffsets.putAll(consumeStats.getOffsetTable());
        } catch (MQClientException e) {
            if (e.getResponseCode() == ResponseCode.TOPIC_NOT_EXIST
                    && topicRouteAvailable(adminClient, topic)) {
                log.warn("Consumer group {} has no retry topic yet ... Topic {} still resolves ...", groupId, topic);
                return Collections.emptyMap();
            }
            throw new RocketMqConnectorException(GET_CONSUMER_GROUP_OFFSETS_ERROR, e);
        } catch (MQBrokerException | RemotingException e) {
            throw new RocketMqConnectorException(GET_CONSUMER_GROUP_OFFSETS_ERROR, e);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RocketMqConnectorException(GET_CONSUMER_GROUP_OFFSETS_ERROR, e);
        }
    }
    return consumerOffsets.keySet().stream()
            .filter(messageQueues::contains)
            .collect(Collectors.toMap(mq -> mq, mq -> consumerOffsets.get(mq).getConsumerOffset()));
}

private static boolean topicRouteAvailable(DefaultMQAdminExt adminClient, String topic) {
    try {
        return adminClient.examineTopicRouteInfo(topic) != null;
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return false;
    } catch (MQClientException | RemotingException e) {
        return false;
    }
}

Runtime flow is unchanged from before: RocketMqSourceSplitEnumerator.run() -> setPartitionStartOffset() (CONSUME_FROM_GROUP_OFFSETS) -> listConsumerGroupOffsets() -> RocketMqAdminUtil.currentOffsets(config, topics, queues) -> the package-private overload above. Only the catch block's disambiguation logic changed. I traced the fail-safe direction of topicRouteAvailable: any failure while probing (including a probe that itself hits TOPIC_NOT_EXIST for the requested topic) returns false, which routes back into the outer throw, not into the empty-map branch. That's the correct direction — if the probe itself is inconclusive, the code surfaces a failure rather than risking a silent rewind, which is exactly the property this whole PR exists to guarantee.

Key finding (non-blocking, not a regression from dev): the empty-map return inside the loop exits the whole method, discarding any offsets already accumulated for topics processed earlier in a multi-topic topics list (multi-topic RocketMQ sources are an explicitly documented, supported configuration — RocketMqSourceOptions.java:39, "If there are multiple topics, use , to split"). In principle, if topic A's lookup already returned real committed offsets and topic B then hits the cold-start branch, topic A's data is discarded and the caller rewinds everything. In practice this can't actually happen under the invariant you described (the retry topic is scoped to the group, not the topic, and committing an offset for any topic implies the group already registered and therefore the retry topic already exists), so this isn't reachable in the normal case, and — importantly — it is not a new problem this PR introduces: dev's old code has the exact same "any exception mid-loop discards earlier accumulated topics" structure (single try wrapping the whole loop). Flagging only for completeness since it touches the same failure mode this PR is fixing; no action required.

1.2 Compatibility Impact

Same conclusion as before, now proven, not just argued: a job relying on the old "silently rewind on any TOPIC_NOT_EXIST" behavior will now fail loudly on a genuine route outage — that's the intended, disclosed trade-off from the linked issue. The ordinary cold-start case for a fresh consumer group, which regressed in the previous commit, is fixed and verified against the connector's own E2E suite. No config option, default, public API, or checkpoint/restore path is touched (setPartitionStartOffset() still skips any MessageQueue in restoredSplits, so restored splits never reach this code at all). Not incompatible in the API/protocol/serialization sense.

1.3 Performance / Side-Effect Analysis

One additional RPC call (examineTopicRouteInfo) only in the TOPIC_NOT_EXIST branch, i.e. only on the first ever run for a fresh consumer group. No loops, no Thread.sleep, no new threads or locks. adminClient.shutdown() ownership is unchanged (still in the outer method's finally). This is materially better than the alternative approach in sibling PR #12340 — see the comparison below.

1.4 Error Handling and Logging

@Slf4j + log.warn(...) added for the disambiguated cold-start case, with groupId and topic as structured arguments, no sensitive data. RocketMqConnectorException still carries the original cause. InterruptedException correctly re-interrupts the thread before wrapping, in both currentOffsets and the new topicRouteAvailable probe.

2. Code Quality Assessment

2.1 Coding Standards

Good. Both currentOffsets overloads and topicRouteAvailable carry clear Javadoc explaining the retry-topic-vs-route-outage distinction and why the disambiguation is safe. No style issues.

2.2 Test Coverage and Test Stability

RocketMqAdminUtilTest now has five deterministic, Mockito-based tests directly pinning the two branches this fix depends on: retry-topic-missing-while-route-healthy -> empty map, and route-outage-on-both -> exception, plus a non-TOPIC_NOT_EXIST failure case and two successful-lookup cases. This is exactly the regression coverage I asked for last round. RocketMqSourceSplitEnumeratorTest retains the propagation test confirming a lookup failure doesn't fall back to CONSUME_FROM_FIRST_OFFSET. All new/changed unit tests: no Thread.sleep, no shared static state, no order dependence. The RocketMqIT.java E2E changes only add/relocate calls to the pre-existing waitForTopicRoute() helper (RocketMqIT.java:483-498), which is itself Awaitility-based (pollInterval 1s, atMost 1 minute, ignoreExceptions, untilAsserted) — no hard waits introduced.

Stability rating: Stable.

Coverage gap from last round is closed: this PR's own fork CI now shows rocketmq-connector-it (11, ubuntu-latest) and rocketmq-connector-it (8, ubuntu-latest) both green against 4e5a44a, where they were red (21 failures / 29 errors on JDK 11 alone) against the previously-reviewed commit.

2.3 Documentation Updates

None needed, consistent with before — no documented config or behavior contract changes.

3. Architectural Soundness

3.1 Precision of the Fix

This is now a precise, targeted fix rather than the blanket-assumption swap from the previous commit: it distinguishes "this group has never registered" from "the name server briefly lost this topic's route" using the requested topic's own route as the disambiguator, matching the RocketMQ client/broker invariants you documented (retry topic is created during heartBeat/registerConsumer, before any offset can be committed; route loss is broker-scoped so it takes the requested topic and the retry topic together).

3.2 Maintainability

Good. The package-private test seam remains a clean, minimal pattern; the new topicRouteAvailable helper is small and single-purpose.

3.3 Extensibility

Neutral — narrowly scoped bugfix, no new extension points.

3.4 Historical-Version Compatibility

Not applicable — no state, serialization, or protocol changes.

Comparison with PR #12340

PR #12340 ("[Fix][Connector-V2] Fix RocketMQ silent rewind on transient consumer group metadata lookup failures") targets the exact same bug and the exact same method, but takes a fundamentally different approach: on TOPIC_NOT_EXIST it retries examineConsumeStats up to 3 times with Thread.sleep(1000L * retryCount) (1s, 2s, 3s — up to 6s of blocking sleep per topic) before giving up and throwing.

This does not fix the regression this PR was written to close. The retry-topic-missing condition for a fresh consumer group is not transient — %RETRY%<groupId> is only created lazily on the group's first heartbeat/registration, so retrying with a delay does not make it appear. #12340's own unit test (RocketMqAdminUtilTest.testCurrentOffsetsThrowsWhenRouteInfoNotFound) proves this directly: it mocks examineConsumeStats to always throw TOPIC_NOT_EXIST, and asserts the method retries 4 times total and then throws RocketMqConnectorException — i.e. by its own test, #12340 turns the ordinary cold-start path into a hard failure as well, just after burning up to 6 seconds of blocking Thread.sleep on the split enumerator's startup path first. That sleep-based delay is itself a new side effect this PR's approach doesn't have. #12340's fork CI is currently ACTION_REQUIRED (not yet run), so this hasn't been demonstrated against the connector's own E2E suite, but I'd expect the same rocketmq-connector-it failures that hit the previous commit of this PR, just after added latency.

Recommendation for maintainers: #12349 (this PR) is the more correct fix — it distinguishes the two failure causes instead of guessing via retry, adds no blocking delay, and is now proven green on the connector's own E2E suite. #12340 should not be merged as-is; if the two authors want to reconcile, #12340's PR could be closed in favor of this one, or repurposed if there's any complementary hardening worth carrying over (I didn't find any — the approaches are alternatives for the same fix, not complementary).

4. Issue Summary

Number Issue Location Severity
1 (carryover, resolved) Original fix broke the ordinary CONSUME_FROM_GROUP_OFFSETS cold-start path for fresh consumer groups RocketMqAdminUtil.java (previous commit) High -> Resolved in 4e5a44a
2 Early return on the cold-start branch discards offsets already accumulated for earlier topics in a multi-topic lookup; not reachable under the stated RocketMQ invariants and not a regression from dev's existing behavior, but worth a comment if the loop is ever touched again RocketMqAdminUtil.java:333-339 Low (non-blocking, informational)

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers — must be fixed: none. The High-severity blocker from my previous review is resolved and verified against the connector's own E2E suite (both JDK 8 and JDK 11 rocketmq-connector-it jobs green on this head).

  2. Recommended fixes — non-blocking:

    • Issue 2 above, purely for future-proofing the loop structure; not required for this PR.
    • Once this merges, it would be worth flagging PR #12340 as superseded/duplicate given the comparison above, so reviewer time isn't spent twice on the same bug.

Overall: this is now a well-reasoned, well-tested, minimally-scoped fix that correctly separates a genuine broker-wide route outage from an ordinary fresh-consumer-group cold start, with the disambiguation logic backed by a real understanding of the RocketMQ client/broker protocol rather than guesswork. Thanks again for chasing down the retry-topic interaction so thoroughly — that's a subtle thing to get right.

🤖 Generated with Claude Code

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Thanks for re-reviewing the head from scratch rather than just the incremental diff, and for catching the retry-topic interaction in the first place. That was the whole fix.

One piece of housekeeping: this came through as a comment rather than an approval, so the CHANGES_REQUESTED from 09-16 is still the active review state on the PR. Anyone scanning the queue sees changes requested rather than your conclusion. If you are happy with 4e5a44a, would you mind re-submitting it as an approval so the two agree?

On Issue 2, the early return discarding offsets already accumulated for earlier topics in a multi-topic lookup: agreed on all of it, including that it is unreachable under the retry-topic invariant and not a regression from dev. I would rather not touch it here. A push restarts the full suite, and the green rocketmq-connector-it result on both JDKs is the evidence this PR took two rounds to earn, in a connector with enough ambient flakiness that I would not want to re-roll it for a comment. I would rather fold it into the follow-up that fixes RocketMqIT.deleteTopicIfExist, since that touches the same area. If you would rather have it in this PR, say so and I will add it.

On the #12340 overlap: that is a call for the committers rather than for either author, and I am fine with whatever they decide. I have not commented on that PR and do not intend to.

@DanielLeens DanielLeens 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.

Good catch, and fair ask — thanks for flagging that the review-state on the PR didn't match my actual conclusion.

Formalizing this as an approval now: my prior comment already confirmed the blocking issue from the previous round is resolved on this exact head (4e5a44a), verified against the connector's own rocketmq-connector-it suite (green on both JDK 8 and JDK 11). This approval supersedes my earlier CHANGES_REQUESTED from 09-16.

On Issue 2 (early return discarding earlier-topic offsets in a multi-topic lookup): agreed with your reasoning — it's unreachable under the retry-topic invariant, it's not a regression from dev, and re-rolling a connector test suite with real ambient flakiness just to add a defensive comment isn't a good trade. Folding it into the follow-up that also touches RocketMqIT.deleteTopicIfExist makes sense to me; no need to add it here.

On the #12340 overlap: agreed that's a call for the committers, not the two of us. I've noted the comparison in my prior review for whoever picks that up, but I won't be commenting on #12340 myself.

Thanks again for tracking down the actual retry-topic invariant here instead of just retrying past the symptom — that was the right fix.

…tead of rewinding

RocketMqAdminUtil.currentOffsets treated TOPIC_NOT_EXIST (code 17) as proof
that a consumer group had committed nothing and returned an empty map. The
only production caller reads an empty map under CONSUME_FROM_GROUP_OFFSETS as
a cold start and falls back to CONSUME_FROM_FIRST_OFFSET, so a lost route
silently replayed a whole topic while the committed offsets were intact.

Code 17 has two meanings here, because examineConsumeStats resolves its route
solely from the group's auto-generated %RETRY% topic rather than from the
requested topic: a group that has never registered has no retry topic yet, and
a route that has been lost looks identical. The two are separated by
re-resolving the requested topic, since the name server removes routes per
broker rather than per topic. If it still resolves the lookup is legitimately
empty and the cold start is preserved, with a WARN naming the reason. If it
does not, the failure surfaces as RocketMqConnectorException.

Also adds a package-private currentOffsets overload taking an already-started
DefaultMQAdminExt as a test seam, and re-interrupts the current thread on
InterruptedException before wrapping it.

@nzw921rx nzw921rx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

+1 LGTM

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

Projects

None yet

3 participants