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 — [fix][metadata]Solve the problem of broker log looping and request failure stagnation after network packet loss recovery by Radiancebobo · Pull Request #26254 · apache/pulsar

Conversation

@Radiancebobo

@Radiancebobo Radiancebobo commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Motivation

During ZooKeeper session-expired recovery, the broker can close the old ZooKeeper handle and create a new
ZooKeeper client. The old handle may emit KeeperState.Closed as part of this local close sequence.

Before this change, ZKSessionWatcher treated every ZooKeeper KeeperState other than Expired and
Disconnected as a successful reconnection. This means KeeperState.Closed could be translated into
Reconnected and SessionReestablished, even though Closed only means the old ZooKeeper handle was closed. It
does not prove that a new session has connected to the ZooKeeper quorum.

This matters because Reconnected and SessionReestablished are not passive notifications in Pulsar. They trigger
metadata recovery work, including persistent watch recreation, resource lock revalidation, and leader election
revalidation. If these events are published before the new ZooKeeper session is actually healthy, the broker can start
recovery work against an unstable or expired session.

In a severe network-loss scenario, this can become a recovery storm:

  1. ZooKeeper session expires.
  2. The broker starts the reconnect flow and closes the old ZooKeeper handle.
  3. The old handle emits KeeperState.Closed.
  4. Closed is incorrectly treated as a successful reconnection.
  5. Pulsar publishes Reconnected / SessionReestablished.
  6. Watch recreation, lock revalidation, and leader election recovery start too early.
  7. These recovery operations fail against the unstable session and can trigger more reconnect/recovery work.

The logs will output in a loop as follows:

PulsarZooKeeperClient - ZooKeeper session 0 is created to pulsar-zookeeper.pulsar:2181.
ZKSessionWatcher - Got ZK session watch event: WatchedEvent state:Closed type:None path:null
PulsarService - Received metadata service session event: Reconnected
ZKMetadataStore - Failed to recreate persistent watch on ZooKeeper: SESSIONEXPIRED
ResourceLockImpl - Failed to revalidate the lock at /namespace/... SessionExpiredException - Retrying ...

The fix is to make the state machine explicit: only KeeperState.SyncConnected should be treated as a successful
reconnection.

Modifications

  • Tightened ZKSessionWatcher state handling so only KeeperState.SyncConnected publishes Reconnected and
    SessionReestablished.
  • Handled non-recovery states explicitly:
    • Disconnected continues to wait for reconnection.
    • ConnectedReadOnly waits for a writable quorum connection instead of treating the read-only connection as fully
      recovered.
    • AuthFailed marks the metadata session as lost.
    • SaslAuthenticated is logged without publishing recovery events.
    • Closed is logged without changing the metadata session state.
  • Added ZKSessionWatcherTest to verify that Closed and other non-SyncConnected states do not publish
    Reconnected or SessionReestablished after SessionLost.
  • Kept the existing stale session-id protection in ZKSessionWatcher.

Verifying this change

  • Make sure that the change passes the CI checks.

This change added tests and can be verified as follows:

  • Added unit tests for ZKSessionWatcher state transitions.
  • Verified existing ZooKeeper session recovery behavior with ZKSessionTest.

Commands run locally:

./gradlew :pulsar-metadata:test --tests org.apache.pulsar.metadata.impl.ZKSessionWatcherTest --tests org.apache.pulsar.metadata.ZKSessionTest
./gradlew :pulsar-metadata:checkstyleMain :pulsar-metadata:checkstyleTest

Does this pull request potentially affect one of the following parts:

  • Dependencies (add or upgrade a dependency)
  • The public API
  • The schema
  • The default values of configurations
  • The threading model
  • The binary protocol
  • The REST endpoints
  • The admin CLI options
  • The metrics
  • Anything that affects deployment

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@Radiancebobo Radiancebobo closed this Jul 28, 2026
@Radiancebobo Radiancebobo reopened this Jul 28, 2026
@Radiancebobo Radiancebobo closed this Jul 30, 2026
@Radiancebobo

Radiancebobo commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

Our team used mirrored images of the old and new code to inject 90% packet loss into each broker pod for half an hour. Without the fix, even after the broker network recovered, the logs would keep looping and the broker would experience prolonged connection interruptions. With the fix applied, the broker traffic recovered quickly after the network was restored. Therefore, I believe this PR is still valuable.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@Radiancebobo Radiancebobo reopened this Jul 30, 2026
@Radiancebobo Radiancebobo changed the title [fix][metadata]ZKSessionWatcher to only trigger reconnection on SyncConnected state [fix][metadata]Solve the problem of broker log looping and request failure stagnation after network packet loss recovery Jul 30, 2026
@void-ptr974

void-ptr974 commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Thanks for the detailed investigation and the clear explanation of the recovery loop. Preventing Closed from the old ZooKeeper handle from being treated as a successful reconnection is a valuable and well-motivated fix.

However, I think the expanded state handling should be completed before merging. The scheduled checkConnectionStatus() probe can currently bypass the new KeeperState switch because every result except CONNECTIONLOSS and SESSIONEXPIRED is converted to SyncConnected.

For example:

  1. AuthFailed

    AuthFailed
      → SessionLost
      → the next exists("/") returns AUTHFAILED
      → default maps it to SyncConnected
      → Reconnected + SessionReestablished
    

    This incorrectly reverses the AuthFailed handling on the next scheduled probe.

  2. ConnectedReadOnly

    ConnectedReadOnly
      → ConnectionLost
      → exists("/") succeeds because it is a read operation
      → OK is mapped to SyncConnected
      → full recovery is triggered before reaching a writable quorum
    

    Additionally, routing ConnectedReadOnly through handleDisconnected() can publish SessionLost after the timeout even though no Expired event was received. A read-only connection is not fully writable, but it also does not necessarily mean that the session has expired.

I suggest updating the probe so that it preserves the actual ZooKeeper state:

  • Map AUTHFAILED explicitly to KeeperState.AuthFailed.
  • For successful probes, distinguish CONNECTED from CONNECTEDREADONLY using zk.getState().
  • Handle ConnectedReadOnly separately instead of promoting it to SessionLost through the disconnection timeout.
  • Only publish SessionReestablished after an actual session loss followed by a writable SyncConnected state.

Please also add deterministic tests for the scheduled probe path, for example:

  • AuthFailed followed by an AUTHFAILED probe must not publish Reconnected or SessionReestablished.
  • ConnectedReadOnly followed by a successful read probe must remain read-only and must not publish full recovery events.
  • ConnectedReadOnly must not become SessionLost without an actual Expired event.
  • Closed from the old handle must remain ignored until the replacement client reports a real writable connection.

The current tests only invoke process() directly and close the watcher before the scheduled probe runs, so they do not cover these transitions.

If the intention is to keep this PR narrowly focused, another reasonable option is to handle only the original Closed regression here and address AuthFailed, ConnectedReadOnly, and the probe-state mapping in a separate PR.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Technoboy- and others added 23 commits October 8, 2026 23:53
@Technoboy- hechengbo
[fix][ml] Track all pending read callbacks for timeouts (apache#26081)
23663d9
@hiSandog hechengbo
[fix][misc] Resolve void by name in Reflections.loadClass (apache#26478)
fd586d9
@lhotari hechengbo
[improve][cli] Add v4-client subcommands to pulsar-perf and pulsar-cl…
fc2fe05
…ient (apache#26480)

### Motivation

`pulsar-perf` was migrated to the V5 client API in apache#25887 and `pulsar-client` in apache#25917, so every
subcommand of both tools now drives the V5 SDK. Pulsar 5.0 does not deprecate ordinary
(non-scalable) topics and the v4 client remains fully supported, so it is still useful to drive the
CLI tools with the v4 client: for benchmark results comparable across broker versions (the v4
commands can also target pre-5.0 brokers, which the V5 SDK cannot talk to at all), and for testing
the v4 client and ordinary topics without the V5 SDK in the path.

The migration also left a set of options that are still accepted but no longer do what they say,
with no way to get the behaviour back — round-robin partition routing and the outstanding-message
limits on `produce`, the real subscription types and the receiver-queue knobs on `consume`, the v4
`Reader` and its `<ledgerId>:<entryId>` start position on `read`, the v4 transaction coordinator on
`transaction`, KeyValue schemas and non-durable subscriptions on `pulsar-client`, and `loadConf`
for `client.conf` keys without a dedicated CLI flag.

### Modifications

Each command is split into an abstract base holding everything that is not client-specific, plus two
thin sibling subclasses that bind the client types — the existing V5 command and a new v4 one:

```
PerformanceProducerBase    -> PerformanceProducer    / PerformanceProducerV4    (produce-v4)
PerformanceConsumerBase    -> PerformanceConsumer    / PerformanceConsumerV4    (consume-v4)
PerformanceReaderBase      -> PerformanceReader      / PerformanceReaderV4      (read-v4)
PerformanceTransactionBase -> PerformanceTransaction / PerformanceTransactionV4 (transaction-v4)

AbstractCmdProduce         -> CmdProduce             / CmdProduceV4             (produce-v4)
AbstractCmdConsumeCommand  -> CmdConsume             / CmdConsumeV4             (consume-v4)
AbstractCmdReadCommand     -> CmdRead                / CmdReadV4                (read-v4)
```

`PulsarClientTool` builds a second, lazily-supplied v4 `ClientBuilder` for the `*-v4` commands; it
keeps `loadConf` and accepts `http://` service URLs. `pulsar-shell` picks the new `pulsar-client`
commands up for free, and both tools' `gen-doc` / `generate_documentation` render them.

New subcommands only. The V5 commands keep their behaviour apart from a few deliberate fixes that
the split surfaced (the `ProducerSocket` send/ack ordering and its `close()` null guard, the
transaction receive-failure path), plus some added "use the `-v4` command" pointers on existing
warnings — all listed in the PR description.

### Verifying this change

Covered by `PulsarPerfTestToolTest`, `PerformanceV4CommandsTest`, `PerformanceTransactionV4Test`,
`CmdV4CommandsTest`, `PulsarClientToolTest` (including the three KeyValue cases disabled by apache#25917,
now re-enabled against `produce-v4`), and new `produce-v4` / `consume-v4` / `read-v4` cases in the
`PerfToolTest` integration test.
@merlimat hechengbo
[improve][ml] Parse message metadata at entry cache insert time inste…
7c065fe
…ad of under the wrapper write lock (apache#26463)
@lhotari hechengbo
[improve][ml] Back LongBitmap with the on-heap RoaringBitmap to fix a…
26abcc6
…ck allocation hotspot (apache#26500)
@lhotari hechengbo
[fix][broker] Fix NPE in ManagedLedgerInterceptorImpl when AppendInde…
438c114
…xMetadataInterceptor isn't configured (apache#26497)
@lhotari hechengbo
[improve][test] Split PulsarProfilingTest into v5 and v4 variants (ap…
da1a121
…ache#26503)
@lhotari hechengbo
[fix][broker] Prevent automatic TTL expiry from skipping reader messa…
fd06ec4
…ges (apache#26505)
@SongOf @song-of-bot hechengbo
[fix][admin] Reject empty cluster migration URL: fix inverted Cluster…
cac94ef
…Url.isEmpty() (apache#26473)

Co-authored-by: maxlisongsong <[email protected]>
@SongOf @song-of-bot hechengbo
[fix][client] Release the reserved memory only once when failing a se…
b503e19
…nd in a terminal state (apache#26476)

Co-authored-by: maxlisongsong <[email protected]>
@lhotari hechengbo
[fix][ml] Parse the cached entry's message metadata from the buffer t…
87a9558
…he cache keeps (apache#26495)
@AlvaroStream hechengbo
[improve][cli] Default the pulsar-perf client memory limit to half of…
3f316e1
… the JVM max direct memory (apache#26491)
@SongOf @song-of-bot hechengbo
[fix][client] Remove the dead letter candidate entry using the entry-…
fdce592
…level message id (apache#26477)

Co-authored-by: maxlisongsong <[email protected]>
@Demogorgon314 hechengbo
[fix][broker] Cancel queued transaction snapshot recovery on topic cl…
d767632
…ose (apache#26335)
@nodece hechengbo
[fix][test] Fix flaky V5DagWatchAutoReconnectTest producer test (apac…
75642be
…he#26510)
@lhotari hechengbo
[fix][ml] Fix active cursor retention and deferred-update synchroniza…
bc295bf
…tion (apache#26511)
@dao-jun hechengbo
[fix][ml] Preserve ledger properties when recovering the last ledger …
3f48947
…on open (apache#26509)
@void-ptr974 hechengbo
[fix][ml] Fix batch ACK index loss when recovering cursor from Metada…
5857e15
…taStore (apache#26474)
@lhotari hechengbo
[fix][sec] Upgrade Netty to 4.2.18 to address several CVEs and bugs (a…
c500175
…pache#26514)
@nodece hechengbo
[fix][client] Release the command header when send serialization fails (
e8c2daf
apache#26492)
@void-ptr974 hechengbo
[fix][broker] Fix persistent throughput degradation caused by permit …
1f6b6f5
…loss during frequent reconnects on Shared subscriptions (apache#26289)
@SEPURI-SAI-KRISHNA hechengbo
[fix][broker] Resolve replicator remote cluster by prefix so cluster …
2dd56c7
…names containing a dot work (apache#26451)
@nodece @lhotari hechengbo
[improve][doc] Require imports over fully qualified class names (apac…
4eecaeb
…he#26516)

Co-authored-by: Lari Hotari <[email protected]>
lhotari and others added 27 commits October 8, 2026 23:53
@lhotari hechengbo
[fix][broker] Align partitioned topic truncate checks with non-partit…
f68b04b
…ioned topics (apache#26776)
@lhotari hechengbo
[fix][txn] Improve transaction admin checks (apache#26773)
d794a8f
@lhotari hechengbo
[improve][test] Add host and per-container CPU and perf counter sampl…
94b2d48
…ing, default bookie cache sizes and bottleneck analysis guidance to the performance tests (apache#26749)
@lhotari hechengbo
[fix][ws] Check dead letter topic permission for WebSocket consumers (a…
c526608
…pache#26772)
@lhotari hechengbo
[fix][fn] Check produce permission on the input topic when triggering…
81504b3
… functions (apache#26777)
@lhotari hechengbo
[fix][ml][broker] Keep source ledger data on every shadow managed led…
a0e6dc6
…ger trim, delete and offload path (apache#26746)
@poorbarcode hechengbo
[improve][broker] Allow dynamically updating topic load timeout (apac…
8f44fe2
…he#26781)
@lhotari hechengbo
[fix][admin] Restore Pulsar 4.x compatible serialVersionUID for Packa…
290f3a9
…geMetadata (apache#26784)
@lhotari hechengbo
[improve][misc] Disable Netty leak detection by default in bin/pulsar…
52d225c
…, pulsar-perf and the CLI tools (apache#26783)
@KannarFr @claude hechengbo
[improve][ml] Reduce tiered storage reads of the search by timestamp …
741a31e
…in offloaded ledgers (apache#26778)

Co-authored-by: Claude Opus 5.5 <[email protected]>
@lhotari hechengbo
[fix][test] Fix flaky V5CumulativeAckTest.testRetryingAnAckThatFailed…
7945669
…WhileDisconnectedAdvancesTheCursor (apache#26789)
@lhotari hechengbo
[fix][fn] Check packages permission for function, source and sink pac…
833baf3
…kage URLs (apache#26771)
@lhotari hechengbo
[improve][test] Record Netty's allocator events and other JFR setting…
9f0b6a5
…s per profiled component, and profile on Alpine (apache#26787)
@KannarFr @claude hechengbo
[improve][offload] Resume offloaded reads from offsets learned in the…
d7055a3
… same data block (apache#26782)

Co-authored-by: Claude Opus 5.5 <[email protected]>
@lhotari hechengbo
[fix][broker] Apply managedLedgerContinueCachingAddedEntriesAfterLast…
0de0838
…ActiveCursorLeavesMillis to managed ledgers (apache#26785)
@lhotari hechengbo
[fix][broker] Preserve standalone bookie identities across upgrades (a…
9edf83c
…pache#26790)
@lhotari hechengbo
[feat][fn] PIP-496: Support the V5 client and topic:// topics in Puls…
5fbecfb
…ar Functions and IO (apache#26697)
@lhotari hechengbo
[improve] Preload mimalloc in the Alpine-based Pulsar image (apache#2…
1823e79
…6791)
@Denovo1998 hechengbo
[fix][broker] Preserve replicated subscription activity on activation (…
3d9cc78
…apache#26780)
@void-ptr974 hechengbo
[fix][broker] Fix lookup permit leak when namespace policy reads fail (…
5eda793
…apache#26606)
@codelipenghui hechengbo
[improve][pip] PIP-441: Add Broker-Level Metrics for Skipped Non-Reco…
2469f7d
…verable Data (apache#24716)
@lhotari hechengbo
[fix][test] Fix flaky V5ProducerBackpressureTest.retriesAcrossASegmen…
129c335
…tSplitKeepTheAccountingBalanced (apache#26792)
@Denovo1998 hechengbo
[improve][test] Strengthen auto-split selector concurrency test (apac…
57668f4
…he#26779)
@Denovo1998 hechengbo
[fix][broker] Avoid misleading ownership lock expiry logs during shut…
2348213
…down (apache#26633)
@programmerahul Rahul Prasad hechengbo
[fix][Client] permit leak in chunked message discard path (apache#26661)
39ae8da
Co-authored-by: Rahul Prasad <[email protected]>
@codelipenghui hechengbo
[feat][broker] PIP-441:Add broker-level metrics for non-recoverable d…
7b81b96
…ata skips (apache#24726)
hechengbo
fix][metadata]ZKSessionWatcher to only trigger reconnection on SyncCo…
66599eb
…nnected state
@Radiancebobo Radiancebobo closed this Oct 8, 2026
@Radiancebobo Radiancebobo mentioned this pull request Oct 8, 2026
[fix][meta] Fix repeated metadata recovery failures after a ZooKeeper session expires #26845
Merged
11 tasks
@github-actions github-actions Bot added the PIP label Oct 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

No reviews

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

PIP

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

20 participants

@Radiancebobo @void-ptr974 @Technoboy- @hiSandog @lhotari @merlimat @SongOf @AlvaroStream @Demogorgon314 @nodece @dao-jun @SEPURI-SAI-KRISHNA @FlorentinDUBOIS @alexandrebrg @Shawyeok @zgzyq @Dream95 @geniusjoe @hangc0276 @ChimdumebiNebolisa
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — 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.