iceberg icon indicating copy to clipboard operation
iceberg copied to clipboard

Kafka Connect: duplicate coordinator after rebalance because close() re-derives leadership from an unstable consumer group

Open jorgebo10 opened this issue 3 months ago • 5 comments

Apache Iceberg version

1.11.0 (latest release)

Query engine

Kafka Connect

Please describe the bug 🐞

A single rebalance can leave two CoordinatorThreads alive for one connector. Both keep their own commit timer and both broadcast StartCommit on the control topic, which workers cannot distinguish from each other.

Symptom

Observed in production on a sink with 10 tasks: the connector's coordinator consumer group connect-<connector>-coord had two members instead of the expected one, and stayed in COMPLETING_REBALANCING across repeated samples 60s apart. All 10 worker control groups (cg-control-*) were alive and stable at the same time.

When leadership cannot be resolved, the closing task logs:

WARN  o.a.i.connect.channel.CommitterImpl - Committer <connector>-0 found no partitions assigned
      across all members, cannot determine leader

Root cause

CommitterImpl.close() decides whether to stop its coordinator by re-deriving leadership from a live Admin describe of the connect consumer group (line numbers on current main):

// CommitterImpl.java:179
if (hasLeaderPartition(closedPartitions)) {
  LOG.info("Committer {} lost leader partition. Stopping coordinator.", taskId);
  stopCoordinator();
}
// CommitterImpl.java:78
boolean hasLeaderPartition(Collection<TopicPartition> currentAssignedPartitions) {
  ConsumerGroupDescription groupDesc;
  try (Admin admin = clientFactory.createAdmin()) {
    groupDesc = KafkaUtils.consumerGroupDescription(config.connectGroupId(), admin);
  }
  ...
}

But close() runs during the rebalance that is revoking the partitions. At that point the group is not stable, and describeConsumerGroups can return members that carry no assignments at all. findFirstTopicPartition() then returns null, containsFirstPartition() logs the warning above and returns false, and stopCoordinator() is never called.

The next open() on another task sees a settled group, finds it owns the lowest partition, and starts a coordinator of its own — startCoordinator()'s coordinatorThread == null guard is per-instance and cannot see the other task's thread. The previous coordinator is now orphaned: nothing holds a reference that would ever stop it.

The decision is also redundant. A task that owns a coordinator already knows it locally — coordinatorThread != null means "I started one and never stopped it". close() overrides that fact with an inference drawn from data that is specifically unreliable at that instant, and the inference's failure mode ("I cannot tell") resolves to "do nothing".

Reproduction

Deterministic, in-process, no broker required — simulate one rebalance across two committers and count live iceberg-coord threads:

  1. Group is stable; task A owns the lowest partition, open() elects it and starts one coordinator.
  2. Group description switches to members with empty assignments (the mid-rebalance state).
  3. taskA.close([lowest partition]) — returns without stopping the coordinator.
  4. Group description settles again; taskB.open([lowest partition]) elects B and starts a second coordinator.
java.lang.AssertionError: after one rebalance there must still be exactly one live iceberg-coord thread
Expected size: 1 but was: 2 in:
[Thread[#36,iceberg-coord,5,main], Thread[#35,iceberg-coord,5,main]]

Suggested fix

Stop asking the broker on the revocation path. Record the partition leadership was won with at open() time, and have close() compare it against the revoked partitions locally:

private TopicPartition leaderPartition;   // set in hasLeaderPartition() when the check passes

// close()
if (coordinatorThread != null
    && (leaderPartition == null || closedPartitions.contains(leaderPartition))) {
  stopCoordinator();
}

Checking the specific elected partition rather than "did I lose anything" keeps this correct under cooperative rebalancing, where a task can be closed for a subset of its partitions and legitimately keep leadership. Falling back to stopping when the elected partition is unknown is the safe direction, since an orphaned coordinator corrupts data while a missing one is re-elected on the next open().

I have a branch with the fix and the test above, and will open a PR referencing this issue.

Related but distinct

  • #16016 — same symptom class (a coordinator thread that outlives the task) but a different trigger and mechanism: a write failure kills the task, and CoordinatorThread.terminate() does not join the thread, so the coordinator keeps running against a catalog that IcebergSinkTask.close() has already closed. Not addressed by this fix.
  • #17340 — duplicate data files, but attributed there to Channel.consumeAvailable regressing the control-topic watermark on re-read, which is independent of coordinator count.

Willingness to contribute

  • [x] I can contribute a fix for this bug independently
  • [ ] I would be willing to contribute a fix for this bug with guidance from the Iceberg community
  • [ ] I cannot contribute a fix for this bug at this time

jorgebo10 avatar Aug 13 '26 17:08 jorgebo10

The duplicate-coordinator behavior itself clearly belongs in Iceberg. The recovery question afterward is what caught our attention: how do you establish the affected Kafka offsets/range, validate what should be replayed, and recover it without broadly reprocessing unrelated traffic?

That's the operator-side recovery workflow we're building around with ReplayGuard.

How did you determine the affected source scope in this incident?

https://replayguard.in/

ravithejatech714-create avatar Aug 29 '26 14:08 ravithejatech714-create

Confirmed this on current main — the diagnosis in the report holds exactly as written.

close() gates coordinator shutdown on hasLeaderPartition(closedPartitions), which opens a fresh Admin and does a live describeConsumerGroups. When that runs during the rebalance that is revoking the partitions, the described members can carry no assignments, findFirstTopicPartition(members) returns null, containsFirstPartition logs "found no partitions assigned across all members" and returns false, and stopCoordinator() is never reached. The coordinatorThread == null guard in startCoordinator() is per-instance, so the next task to open() on a settled group starts a second coordinator without being able to see the first.

Before writing a patch I would like to agree on the shape, since there is a design call here.

The ambiguous case currently fails toward leaving a coordinator running. That is the wrong default: an undetectable leader means we cannot prove we are not the leader, and the cost of stopping a coordinator we should have kept is a re-election on the next open(), while the cost of keeping one we should have stopped is two coordinators both broadcasting StartCommit. I would invert it — if this committer owns a coordinatorThread and leadership cannot be determined, stop it.

The live Admin describe in close() looks avoidable entirely. The class already captures membersWhenWorkerIsCoordinator at the moment leadership was established, when the group was stable, and passes it to the Coordinator constructor. close() could derive the leader partition from that snapshot and check whether closedPartitions contains it, which keeps the existing intent — only stop when actually losing the leader partition, so a partial cooperative revocation that leaves the leader partition in place does not churn the coordinator — without querying a group that is by definition mid-rebalance at that moment. It also takes an Admin round-trip out of the close path, where a throwing describe is its own failure mode.

So, concretely:

  1. close() derives leadership from the stored member snapshot rather than a fresh describe.
  2. If leadership cannot be determined and coordinatorThread != null, stop the coordinator.

Two questions for whoever knows the original intent here:

  • Was the live describe in close() deliberate — is there a case where the snapshot from open() is known to be stale in a way that matters?
  • Would you rather close() stop the coordinator unconditionally whenever this instance owns one? That is simpler and strictly safe against duplicates, at the cost of a coordinator restart on every partial revocation. I lean toward the snapshot approach to avoid that churn, but I do not have a feel for how often partial revocations happen on a real sink.

Happy to put up a PR with a test that drives CommitterImpl against an Admin returning members with empty assignments and asserts the coordinator is stopped — that reproduces the report at unit level. Wanted the approach settled first rather than guess.

vbhanuchander-lang avatar Sep 10 '26 01:09 vbhanuchander-lang

We hit this in production on 1.11.0 (12-task sink connector). Same fingerprint as the report: restarting one failed task (POST /connectors/<name>/restart?includeTasks=true&onlyFailed=true) triggered a rebalance. All 11 running tasks logged found no partitions assigned across all members, cannot determine leader within ~1 s, none logged lost leader partition, and 0.6 s later the restarted task logged received leader partition. The previous coordinator kept running for ~34 h, until we restarted all tasks of the connector.

We also see this after node preemptions and node-pool upgrades, at times on several connectors at once. CommitterImpl is unchanged in 1.12.0, so the bug is still present there.

+1 for the proposed shape (record the elected partition at open(), compare locally in close()). Our workaround meanwhile: restart all tasks of the connector instead of only the failed ones, because only the explicit-stop path (close(List.of())) reliably stops the coordinator.

Setsushin avatar Oct 28 '26 05:10 Setsushin

+1 for this fix, we have been experiencing the same issue

ujasur avatar Oct 29 '26 03:10 ujasur

@jorgebo10 @vbhanuchander-lang since no PR has come up for this yet, I opened one (linked above) with the shape suggested here: close() compares the revoked partitions with the leader partition from the description seen at election, and no longer describes the group mid-rebalance. Besides the empty-assignment case, this also covers cooperative rebalancing, where the description no longer shows the revoked leader partition, so another partition looks like the first one. Happy to fold in anything from your branches.

binarybrain-009 avatar Oct 29 '26 09:10 binarybrain-009