GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [improve][broker] PIP-473: address TC discovery review findings · apache/pulsar@6acca7f

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • pulsar-broker-common/src/main/java/org/apache/pulsar/broker
    • ServiceConfiguration.java
  • pulsar-broker/src
    • main/java/org/apache/pulsar/broker
      • service
        • ServerCnx.java
      • transaction
        • coordinator/v5
          • TransactionCoordinatorV5.java
        • metadata
          • TxnPaths.java
    • test/java/org/apache/pulsar/broker/transaction/coordinator/v5
      • TransactionCoordinatorV5Test.java
  • pulsar-client/src/main/java/org/apache/pulsar/client/impl
    • HandlerState.java
    • transaction
      • AssignTopicTcDiscovery.java
      • TransactionCoordinatorClientImpl.java
      • WatchTcAssignmentsDiscovery.java
  • tests/integration/src/test/java/org/apache/pulsar/tests/integration/transaction
    • TcMetadataDiscoveryTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎pulsar-broker-common/src/main/java/org/apache/pulsar/broker/ServiceConfiguration.java‎

Copy file name to clipboardExpand all lines: pulsar-broker-common/src/main/java/org/apache/pulsar/broker/ServiceConfiguration.java
+7-2Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3836,12 +3836,17 @@ public double getLoadBalancerBandwidthOutResourceWeight() {
38363836

38373837
@FieldContext(
38383838
category = CATEGORY_TRANSACTION,
3839+
minValue = 1,
38393840
doc = "Degree of parallelism for the scalable-topics transaction coordinator: how many"
38403841
+ " independent coordinator instances run across the cluster. Each is"
38413842
+ " leader-elected independently in the metadata store and coordinates the"
38423843
+ " transactions whose id maps to it. Fixed at cluster bring-up — changing it"
3843-
+ " later would strand the coordinator id encoded in existing transaction ids."
3844-
+ " Only relevant when transactionCoordinatorScalableTopicsEnabled = true."
3844+
+ " later would strand the coordinator id encoded in existing transaction ids"
3845+
+ " (and, because an aborted transaction's records are retained as long as its"
3846+
+ " messages are, the value can only be reduced once all transactions created"
3847+
+ " under the previous value have been fully cleaned up). All brokers must agree"
3848+
+ " on this value; a mismatch is rejected at startup. Only relevant when"
3849+
+ " transactionCoordinatorScalableTopicsEnabled = true."
38453850
)
38463851
private int transactionCoordinatorScalableTopicsParallelism = 16;
38473852

Collapse file

‎pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java‎

Copy file name to clipboardExpand all lines: pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java
+26-6Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -873,6 +873,9 @@ protected void handleCommandScalableTopicLookup(
873873
// --- Transaction-coordinator assignment watchers ---
874874
// watchId -> deregistration handle for the listener registered on TransactionCoordinatorV5.
875875
private final ConcurrentHashMap<Long, AutoCloseable> tcAssignmentWatchers = new ConcurrentHashMap<>();
876+
// Delay before re-pushing a TC-assignment snapshot that was incomplete (a partition mid-election)
877+
// or that failed to build, so the client converges without waiting for an external trigger.
878+
private static final long TC_ASSIGNMENTS_REPUSH_DELAY_MS = 1000L;
876879

877880
@Override
878881
protected void handleCommandWatchScalableTopics(
@@ -1008,12 +1011,29 @@ private void sendTcAssignmentsSnapshot(long watchId, TransactionCoordinatorV5 tc
10081011
if (!tcAssignmentWatchers.containsKey(watchId)) {
10091012
return;
10101013
}
1011-
var snapshot = tc.buildAssignmentsSnapshot();
1012-
java.util.Map<Integer, String[]> leaders = new java.util.HashMap<>();
1013-
snapshot.assignments().forEach((partition, leader) ->
1014-
leaders.put(partition, new String[] {leader.brokerServiceUrl(), leader.brokerServiceUrlTls()}));
1015-
ctx.writeAndFlush(Commands.newWatchTcAssignmentsSnapshot(
1016-
watchId, snapshot.partitionCount(), leaders));
1014+
tc.buildAssignmentsSnapshot().thenAccept(snapshot -> ctx.executor().execute(() -> {
1015+
if (!tcAssignmentWatchers.containsKey(watchId)) {
1016+
return;
1017+
}
1018+
java.util.Map<Integer, String[]> leaders = new java.util.HashMap<>();
1019+
snapshot.assignments().forEach((partition, leader) -> leaders.put(partition,
1020+
new String[] {leader.brokerServiceUrl(), leader.brokerServiceUrlTls()}));
1021+
ctx.writeAndFlush(Commands.newWatchTcAssignmentsSnapshot(
1022+
watchId, snapshot.partitionCount(), leaders));
1023+
// If some partition is still mid-election, the snapshot is incomplete. Schedule a single
1024+
// delayed re-push so the client doesn't stay parked on a missing partition waiting for a
1025+
// leadership change that may never come (the cache repopulating fires no TC listener).
1026+
if (!snapshot.isComplete()) {
1027+
ctx.executor().schedule(() -> sendTcAssignmentsSnapshot(watchId, tc),
1028+
TC_ASSIGNMENTS_REPUSH_DELAY_MS, TimeUnit.MILLISECONDS);
1029+
}
1030+
})).exceptionally(ex -> {
1031+
log.warn().attr("watchId", watchId).exception(ex)
1032+
.log("Failed to build TC-assignments snapshot; retrying shortly");
1033+
ctx.executor().schedule(() -> sendTcAssignmentsSnapshot(watchId, tc),
1034+
TC_ASSIGNMENTS_REPUSH_DELAY_MS, TimeUnit.MILLISECONDS);
1035+
return null;
1036+
});
10171037
}
10181038

10191039
@Override
Collapse file

‎pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/coordinator/v5/TransactionCoordinatorV5.java‎

Copy file name to clipboardExpand all lines: pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/coordinator/v5/TransactionCoordinatorV5.java
+78-9Lines changed: 78 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import java.util.TreeMap;
3030
import java.util.concurrent.CompletableFuture;
3131
import java.util.concurrent.ConcurrentHashMap;
32+
import java.util.concurrent.ConcurrentSkipListMap;
3233
import java.util.concurrent.CopyOnWriteArrayList;
3334
import java.util.concurrent.Executors;
3435
import java.util.concurrent.ScheduledExecutorService;
@@ -150,6 +151,7 @@ public synchronized void start() {
150151
if (closed || sweepExecutor != null) {
151152
return;
152153
}
154+
verifyParallelismConsistency();
153155
this.localLeader = new TcLeader(pulsar.getBrokerId(), pulsar.getBrokerServiceUrl(),
154156
pulsar.getBrokerServiceUrlTls(), pulsar.getSafeWebServiceAddress());
155157
for (int partition = 0; partition < partitionCount; partition++) {
@@ -176,6 +178,52 @@ public synchronized void start() {
176178
gcSweepIntervalMs, gcSweepIntervalMs, TimeUnit.MILLISECONDS);
177179
}
178180

181+
/**
182+
* Persist this broker's configured parallelism cluster-wide on first start, and verify every
183+
* subsequent broker agrees. A mismatch means brokers would run different election sets and the
184+
* coordinator-count encoded in transaction ids would be ambiguous — fatal misconfiguration, so
185+
* we fail fast rather than start in an inconsistent state.
186+
*/
187+
private void verifyParallelismConsistency() {
188+
var store = pulsar.getLocalMetadataStore();
189+
try {
190+
byte[] value = Integer.toString(partitionCount).getBytes(java.nio.charset.StandardCharsets.UTF_8);
191+
var existing = store.get(TxnPaths.TXN_TC_PARALLELISM_PATH).get();
192+
if (existing.isEmpty()) {
193+
// First broker to start writes the value (CAS create; lose harmlessly to a racing peer).
194+
store.put(TxnPaths.TXN_TC_PARALLELISM_PATH, value, java.util.Optional.of(-1L))
195+
.get();
196+
var after = store.get(TxnPaths.TXN_TC_PARALLELISM_PATH).get();
197+
if (after.isPresent()) {
198+
checkParallelismMatches(after.get().getValue());
199+
}
200+
} else {
201+
checkParallelismMatches(existing.get().getValue());
202+
}
203+
} catch (IllegalStateException e) {
204+
throw e;
205+
} catch (Exception e) {
206+
// A racing create (BadVersion) or read-after-write resolves by re-reading and comparing.
207+
try {
208+
var after = store.get(TxnPaths.TXN_TC_PARALLELISM_PATH).get();
209+
after.ifPresent(r -> checkParallelismMatches(r.getValue()));
210+
} catch (Exception ignore) {
211+
log.warn().exception(e).log("Could not verify TC parallelism consistency; proceeding");
212+
}
213+
}
214+
}
215+
216+
private void checkParallelismMatches(byte[] storedValue) {
217+
int stored = Integer.parseInt(new String(storedValue, java.nio.charset.StandardCharsets.UTF_8).trim());
218+
if (stored != partitionCount) {
219+
throw new IllegalStateException(
220+
"transactionCoordinatorScalableTopicsParallelism mismatch: this broker is configured"
221+
+ " with " + partitionCount + " but the cluster was initialized with " + stored
222+
+ ". The value is fixed at cluster bring-up and must be identical on every"
223+
+ " broker.");
224+
}
225+
}
226+
179227
/** Stop the sweeps and release every leader-election lease. Idempotent. */
180228
public synchronized void close() {
181229
closed = true;
@@ -265,18 +313,35 @@ public CompletableFuture<Void> handleClientConnect(TransactionCoordinatorID tcId
265313
// ---- Assignment discovery (client watch) ------------------------------
266314

267315
/**
268-
* Build the current full {@code partition → leader} snapshot from the election state. A
269-
* partition with no currently-known leader (mid-election) is omitted; the client parks any
270-
* transaction routed there until a later snapshot fills it in. Always the complete map — the
271-
* watch protocol sends full snapshots, never diffs.
316+
* Build the current full {@code partition → leader} snapshot from the election state. Uses the
317+
* async {@link LeaderElection#getLeaderValue()} (which loads from the metadata store on a cache
318+
* miss) rather than the cache-only {@code getLeaderValueIfPresent()}: when this broker just
319+
* transitioned to {@code Following} for a partition, its local cache for the new leader's node
320+
* may not be repopulated yet, and a cache-only read would silently omit that partition. Loading
321+
* from the store closes that window so a follower's snapshot is still complete.
322+
*
323+
* <p>A partition still genuinely without a leader (no broker elected yet) is omitted; the caller
324+
* ({@code ServerCnx}) re-pushes shortly after so the client isn't stranded. Always the complete
325+
* map — the watch protocol sends full snapshots, never diffs.
326+
*
327+
* @return a future of the snapshot plus whether it is complete (every partition has a leader)
272328
*/
273-
public TcAssignmentsSnapshot buildAssignmentsSnapshot() {
274-
Map<Integer, TcLeader> assignments = new TreeMap<>();
329+
public CompletableFuture<TcAssignmentsSnapshot> buildAssignmentsSnapshot() {
330+
Map<Integer, TcLeader> assignments = new ConcurrentSkipListMap<>();
331+
List<CompletableFuture<Void>> loads = new ArrayList<>(elections.size());
275332
for (Map.Entry<Integer, LeaderElection<TcLeader>> e : elections.entrySet()) {
276-
e.getValue().getLeaderValueIfPresent()
277-
.ifPresent(leader -> assignments.put(e.getKey(), leader));
333+
int partition = e.getKey();
334+
loads.add(e.getValue().getLeaderValue()
335+
.thenAccept(opt -> opt.ifPresent(leader -> assignments.put(partition, leader)))
336+
.exceptionally(ex -> {
337+
// Treat a load error as "leader unknown for now"; the re-push will retry.
338+
log.debug().attr("partition", partition).exception(ex)
339+
.log("v5 TC leader-value load failed while building snapshot");
340+
return null;
341+
}));
278342
}
279-
return new TcAssignmentsSnapshot(partitionCount, assignments);
343+
return FutureUtil.waitForAll(loads)
344+
.thenApply(__ -> new TcAssignmentsSnapshot(partitionCount, new TreeMap<>(assignments)));
280345
}
281346

282347
/**
@@ -291,6 +356,10 @@ public AutoCloseable registerAssignmentChangeListener(Runnable listener) {
291356

292357
/** Immutable full assignment snapshot: partition count + the currently-known leaders. */
293358
public record TcAssignmentsSnapshot(int partitionCount, Map<Integer, TcLeader> assignments) {
359+
/** @return true if every partition has a known leader (no mid-election gaps). */
360+
public boolean isComplete() {
361+
return assignments.size() == partitionCount;
362+
}
294363
}
295364

296365
// ---- newTransaction ---------------------------------------------------
Collapse file

‎pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/metadata/TxnPaths.java‎

Copy file name to clipboardExpand all lines: pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/metadata/TxnPaths.java
+8Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,14 @@ public static String tcLeaderPath(int partition) {
121121
return TXN_TC_LEADER_PREFIX + "/" + partition;
122122
}
123123

124+
/**
125+
* Cluster-wide record of the scalable-topics TC parallelism, written once by the first broker to
126+
* start. Every broker verifies its configured value against this and refuses to start on a
127+
* mismatch, so the coordinator-count encoded in transaction ids stays stable for the cluster's
128+
* lifetime.
129+
*/
130+
public static final String TXN_TC_PARALLELISM_PATH = "/txn/tc/parallelism";
131+
124132
/** Width used when formatting long values into lexicographically-orderable index keys. */
125133
public static final int LONG_KEY_WIDTH = 20;
126134

Collapse file

‎pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/coordinator/v5/TransactionCoordinatorV5Test.java‎

Copy file name to clipboardExpand all lines: pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/coordinator/v5/TransactionCoordinatorV5Test.java
+31-3Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -371,11 +371,11 @@ public void election_singleBrokerLeadsAllPartitions() {
371371

372372
@Test
373373
public void buildAssignmentsSnapshot_reportsAllLedPartitions() {
374-
var snapshot = tc.buildAssignmentsSnapshot();
375-
assertThat(snapshot.partitionCount()).isEqualTo(4);
374+
assertThat(tc.buildAssignmentsSnapshot().join().partitionCount()).isEqualTo(4);
376375
Awaitility.await().untilAsserted(() -> {
377-
var snap = tc.buildAssignmentsSnapshot();
376+
var snap = tc.buildAssignmentsSnapshot().join();
378377
assertThat(snap.assignments()).hasSize(4);
378+
assertThat(snap.isComplete()).isTrue();
379379
assertThat(snap.assignments().get(0).brokerServiceUrl())
380380
.isEqualTo("pulsar://broker-test:6650");
381381
assertThat(snap.assignments().get(0).brokerId()).isEqualTo("broker-test:8080");
@@ -396,4 +396,32 @@ public void handleClientConnect_acceptsWhenLeader() throws Exception {
396396
// We lead partition 0, so connect is accepted without consulting assign-topic ownership.
397397
tc.handleClientConnect(TC_ID).get();
398398
}
399+
400+
@Test
401+
public void start_failsOnParallelismMismatch() throws Exception {
402+
// The running tc (from setUp) persisted parallelism=4. A second coordinator configured with a
403+
// different value against the same metadata store must refuse to start.
404+
ServiceConfiguration mismatchCfg = new ServiceConfiguration();
405+
mismatchCfg.setTransactionCoordinatorScalableTopicsGcRetentionSeconds(0);
406+
mismatchCfg.setTransactionCoordinatorScalableTopicsParallelism(8);
407+
PulsarService other = mock(PulsarService.class);
408+
when(other.getLocalMetadataStore()).thenReturn(store);
409+
when(other.getCoordinationService()).thenReturn(coordinationService);
410+
when(other.getConfiguration()).thenReturn(mismatchCfg);
411+
when(other.getBrokerId()).thenReturn("broker-other:8080");
412+
when(other.getBrokerServiceUrl()).thenReturn("pulsar://broker-other:6650");
413+
when(other.getSafeWebServiceAddress()).thenReturn("http://broker-other:8080");
414+
when(other.getBrokerService()).thenReturn(brokerService);
415+
416+
TransactionCoordinatorV5 mismatched = new TransactionCoordinatorV5(other);
417+
try {
418+
assertThatThrownBy(mismatched::start)
419+
.isInstanceOf(IllegalStateException.class)
420+
.hasMessageContaining("mismatch")
421+
.hasMessageContaining("8")
422+
.hasMessageContaining("4");
423+
} finally {
424+
mismatched.close();
425+
}
426+
}
399427
}
Collapse file

‎pulsar-client/src/main/java/org/apache/pulsar/client/impl/HandlerState.java‎

Copy file name to clipboardExpand all lines: pulsar-client/src/main/java/org/apache/pulsar/client/impl/HandlerState.java
+7Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,13 @@ public HandlerState(PulsarClientImpl client, String topic) {
5555

5656
protected void setRedirectedClusterURI(String serviceUrl, String serviceUrlTls) throws URISyntaxException {
5757
String url = client.conf.isUseTls() && StringUtils.isNotBlank(serviceUrlTls) ? serviceUrlTls : serviceUrl;
58+
if (StringUtils.isBlank(url)) {
59+
// e.g. a non-TLS client given a TLS-only endpoint (or vice versa). Surface a clear,
60+
// catchable error rather than letting new URI(null) throw an NPE.
61+
throw new URISyntaxException(String.valueOf(url),
62+
"No usable service URL (useTls=" + client.conf.isUseTls()
63+
+ ", serviceUrl=" + serviceUrl + ", serviceUrlTls=" + serviceUrlTls + ")");
64+
}
5865
this.redirectedClusterURI = new URI(url);
5966
}
6067

Collapse file

‎pulsar-client/src/main/java/org/apache/pulsar/client/impl/transaction/AssignTopicTcDiscovery.java‎

Copy file name to clipboardExpand all lines: pulsar-client/src/main/java/org/apache/pulsar/client/impl/transaction/AssignTopicTcDiscovery.java
+2-1Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,8 @@ public TransactionMetaStoreHandler nextHandler() {
104104

105105
@Override
106106
public java.util.Collection<TransactionMetaStoreHandler> handlers() {
107-
return handlers == null ? java.util.List.of() : java.util.List.of(handlers);
107+
TransactionMetaStoreHandler[] snapshot = handlers;
108+
return snapshot == null ? java.util.List.of() : java.util.List.of(snapshot);
108109
}
109110

110111
@Override
Collapse file

‎pulsar-client/src/main/java/org/apache/pulsar/client/impl/transaction/TransactionCoordinatorClientImpl.java‎

Copy file name to clipboardExpand all lines: pulsar-client/src/main/java/org/apache/pulsar/client/impl/transaction/TransactionCoordinatorClientImpl.java
+10Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,4 +271,14 @@ public State getState() {
271271
public Collection<TransactionMetaStoreHandler> getHandlers() {
272272
return discovery == null ? List.of() : discovery.handlers();
273273
}
274+
275+
/**
276+
* @return {@code true} if coordinator discovery uses the metadata-store assignment watch (rather
277+
* than the assign-topic fallback). Visible for testing so integration tests can assert the
278+
* watch path was actually exercised.
279+
*/
280+
@VisibleForTesting
281+
public boolean isUsingMetadataDiscovery() {
282+
return discovery instanceof WatchTcAssignmentsDiscovery;
283+
}
274284
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.