Skip to content

fix(reattach): keep established producers and consumers alive across bundle unloads and re-home them to the owning broker - #937

Merged
alexandrebrg merged 10 commits into
mainfrom
fix/935-established-reattach-unbounded
Dec 2, 2026
Merged

alexandrebrg merged 10 commits into
mainfrom
fix/935-established-reattach-unbounded

Conversation

@alexandrebrg

Copy link
Copy Markdown
Contributor

Fixes #935.

Problem

A long-lived producer hit by code=6 ServiceNotReady during a bundle unload exhausted its transient retry budget (max_retries = Some(8)), was terminalized, and every later send() failed forever with protocol invariant violated: producer rejected send.

The analysis found three causes, not one:

  1. Established handles had a finite count budget, exactly like the initial create (conn.rs CommandError arms, ADR-0125 open-timeout expiry). The Java client has no cap once a producer/consumer has attached: ConnectionHandler reconnects until the user closes it or the broker returns a genuinely final error.
  2. An established handle could never follow its bundle to another broker. Producers and consumers were pinned to one Arc<ConnectionShared>; the retry leg did a non-authoritative lookup on that same connection, ignored the returned owner, re-issued CommandProducer on the old broker and terminalized on a Redirected lookup. When ownership moved to broker B, broker A answers every re-issue with "not served by this instance … redo the lookup", whatever the budget. This is why other (Java) clients re-attached within seconds. Removing the cap alone would have turned the outage into an endless futile loop.
  3. The terminal surface was opaque: ProducerError::Closed was collapsed into InvariantViolation("producer rejected send") and the broker code/message were dropped.

The "9 attempts in ~8 s" in the report is not a bug: the default schedule sleeps 1.9, 3.5, 6.6, 7.0, 7.5, 7.9, 7.8, 7.5 s (≈50 s); the quoted window is only the last leg. A proto unit test pins this schedule.

Options considered

Option Verdict
Remove the count cap only Rejected: endless futile loop against the old owner on a cross-broker move.
Keep the cap, add only a typed error Rejected: not Java parity, and PartitionedProducer never re-creates its children.
Raise max_retries / default it to None Rejected: only delays the outage and also unbounds first creates and lookups.
Unbounded same-broker retry + fast "owner moved" terminal Rejected: the reporter's case (cross-broker move) still ends terminal.
Re-create the handle in the façade Rejected: loses in-flight send futures, sequence-id continuity and consumer queues; does not cover the engine API.
Unbounded established reattach + re-home to the lookup owner + typed terminal failure Chosen (ADR-0157).

Three independent designs were judged on correctness/concurrency, Java parity/semver and testability before synthesis; details in ADR-0157 § Alternatives.

What changes

  • Established reattach is unbounded by default (ADR-0157). One proto policy point, note_established_failure, handles CommandError replies, ADR-0125 open-timeout expiry and retry-leg lookup failures. Terminal sets follow Java: producer TopicNotFound / TopicTerminatedError / ProducerFenced; consumer TopicNotFound. Everything else retries with capped, per-handle-jittered backoff. Pending sends keep queueing and fail only on their own send_timeout. First creates, lookups and partition metadata keep the max_retries bound; scalable segment:// children keep today's bounded policy (their controller re-assigns them).
  • Opt-in bound: ClientBuilder::established_reattach_limit(n) / Client::with_established_reattach_limit(Some(n)).
  • Re-homing: client-wide producer/consumer ids (HandleIdAllocator), BrokerIdentity matching resolve_direct_broker's own predicate, proto take_*_for_rehome / adopt_* / restore_* transfer primitives, and an engine-side HandleBinding so every per-handle future follows the move. The move holds both connection locks in ascending-address order (the single documented exception to ADR-0038, also added to CLAUDE.md invariant Command line version #10 and enforced by a source-scan test in each engine). Ids, queued and in-flight sends, receive queues and waiters move with the handle; adopt refusal restores on the origin.
  • Typed terminal surface: ClientError::Terminated(TerminalFailure) (both engines), PulsarError::Terminated, HandleState (Ready / Reattaching { attempts, last_error } / Terminated / Closed), state() / terminal_failure() / is_terminal() on handles and as provided ProducerApi / ConsumerApi methods. A send on a user-closed clone now returns Closed on both engines.
  • Smaller fixes found along the way: a retry-leg lookup ending in an unexpected outcome no longer strands the handle; CommandCloseConsumer with an assigned broker URL no longer detaches an established consumer forever; a close naming an assigned URL makes the first retry immediate; re-attach WARNs carry attempts / next_delay_ms and escalate on the first failure, powers of two and code changes.

Semver

New variants on the exhaustive ClientError (both engines) and PulsarError, plus behaviour changes listed in the CHANGELOG "Upgrading from 2.1" section. Following the 1.1.0 / 1.4.0 / 2.1.0 precedents this is written up for 2.2.0; maintainers may prefer 3.0.0 with identical code.

Tests

  • Proto unit: unbounded producer/consumer reattach past max_retries, the Java terminal-set table, the opt-in limit, the segment carve-out, ADR-0125 expiry by default and under the limit, CloseConsumer with URL, log escalation, schedule pinning, id allocator, take/adopt/restore (including the refusal and post-seek waiter hand-off cases).
  • Tokio + moonpool (1:1, 710 = 710): tests/established_reattach.rs (long unloads under paused/virtual time, typed terminal errors, send timeout while reattaching, leg cancellation on user close) and tests/handle_rehome.rs (re-home with replay, redirect chase, fan-out does not churn, close during re-home, socket clients), plus inline driver twins for the relocation/binding protocol.
  • Differential: established_reattach_unbounded_equivalence, handle_rehome_equivalence, handle_rehome_engine_equivalence, typed_terminal_failure_equivalence.
  • E2E (shared fixture): e2e_established_reattach_beyond_budget (real topics unload + forged ServiceNotReady rejections beyond the budget, producer and consumer recover; limit restores the bounded give-up) and e2e_typed_terminal_failure (real terminated topic → PulsarError::Terminated { kind: TopicTerminated }). Cross-broker re-home cannot run on the single-broker fixture; it is covered by scripted two-broker runtime tests, simulation and differential layers (recorded in docs/testing.md).

Validation (local)

Full CLAUDE.md chain: fmt, workspace build, clippy on every axis, cargo test --workspace --all-features with the Docker e2e suite (one unrelated e2e_replicated_subscriptions flake passed on rerun), 32-seed moonpool sweep, cargo deny, docs with -D warnings, every xtask gate (check-no-channels, check-no-io-deps, check-no-internal-clock, check-log-fields, check-e2e-fixture, codegen --check, check-runtime-test-parity, check-known-failing-seeds, check-crypto-matrix, check-sim-coverage), prettier on all Markdown.

Out of scope (recorded in ADR-0157 / docs/follow-ups.md)

PIP-188 TopicMigrated re-home, an established subscribe deadline (#20), holding grouped acks / flow while a consumer is detached, and a possible zombie registration on the old broker after an ADR-0125 expiry followed by a re-home.

…past the retry budget

Issue #935: an established producer or consumer shared the provisional
create's `OperationRetryConfig::max_retries` budget (default 8), so a
bundle unload longer than ~50 s of backoff terminalized it and every later
send failed with an opaque `InvariantViolation("producer rejected send")`.

Every established re-attach failure (CommandError on the re-attach, the
ADR-0125 open timeout, and a retry-leg lookup failure) now goes through one
proto policy point, `Connection::note_established_failure`. It retries
everything except the Java terminal set (TopicNotFound; for a producer also
TopicTerminatedError and ProducerFenced) and the opt-in
`established_reattach_limit` (proto setter, engine
`Client::with_established_reattach_limit`, facade
`ClientBuilder::established_reattach_limit` and the moonpool facade's
`PulsarClient::with_established_reattach_limit`). `segment://` children keep
the bounded ADR-0080 policy.

- leg delay: `reattach_delay` / `delay_for_reattach` (per-handle jitter,
  capped at max_backoff, 64-step clamp also applied to
  `delay_after_failure`); one-shot immediate leg after a close carrying an
  assigned broker URL
- the retry leg no longer strands the handle on an unexpected lookup
  outcome; lookup failures feed the policy point and loop
- CommandCloseConsumer with an assigned URL re-subscribes an established
  consumer in place instead of leaving it detached
- DriverRetry and ReattachDecision::Retry carry attempts and log_escalate;
  open and leg-lookup failures log at WARN on the first failure, powers of
  two and code changes, DEBUG otherwise
- typed surface: TerminalFailure / TerminalFailureKind / HandleState in
  proto, ClientError::Terminated in both engines (drained in-flight sends,
  consumer receive, and one send-rejection mapping shared by the fast path
  and the memory-reserving path, which now both queue through the per-slot
  `try_queue_send_reserved`), Closed for a send on a user-closed clone,
  PulsarError::Terminated in the facade (every `?` on a tokio engine error,
  the typed message builder, `receive_with_interceptors` and the
  multi-topics / pattern consumer receive), and state() /
  terminal_failure() / is_terminal() / child_states() accessors plus
  provided ProducerApi / ConsumerApi methods

The retry leg still re-issues on the handle's own connection; re-homing to
the new bundle owner follows in a later commit.

Refs #935

Signed-off-by: Alexandre Burgoni <alexandre.burgoni@clever.cloud>
…1.97

Clippy 1.97 (stable) adds `duration_suboptimal_units`, which fails the
workspace `cargo clippy --all-features --all-targets -D warnings` gate on
pre-existing test, example and e2e literals such as
`Duration::from_secs(60)`. Mechanical `cargo clippy --fix` rewrite to
`from_mins` / `from_hours` (stable since 1.91, MSRV is 1.95); every value
is unchanged, so there is no behavioural change and no new test.

Refs #935

Signed-off-by: Alexandre Burgoni <alexandre.burgoni@clever.cloud>
…imitives

Second step of issue #935 (ADR-0157): the building blocks that let an
established producer or consumer follow its bundle to the broker that now
owns it. Nothing moves a handle yet; the engine relocation legs follow.

- HandleIdAllocator: one producer and one consumer id counter per client.
  Connection::set_handle_id_allocator makes create_producer / subscribe
  number from it, raising it past any id the connection already used. Both
  engines install one allocator on the bootstrap connection and on every
  pooled connection (supervised constructors and pool entry build), so wire
  producer/consumer ids are now unique across a pooled client, like Java's
  newProducerId / newConsumerId. A connection without an allocator keeps its
  per-connection counters, so direct proto users are unchanged.
- lookup: BrokerIdentity (Bootstrap / Direct / Proxy, no fan-out index),
  RouteTarget, target_identity and same_host_port. Both engines'
  resolve_direct_broker now take their bootstrap-equality decision through
  same_host_port, so an identity names exactly the connection routing picks.
- Connection::take_producer_for_rehome / adopt_producer / restore_producer
  and the consumer twins, with opaque ProducerTransfer / ConsumerTransfer.
  Take is gated on the retry-leg currency predicate plus established, open
  and non-terminal; it moves the slot, create request, reset-time snapshots,
  send outcomes and slab wakers (producer) or the slot with its queue and
  trackers (consumer), discards a queued driver retry for the handle,
  settles the consumer's in-flight acks (#346), awaited seek and
  last-message-id (ServiceNotReady) and forgotten seek on the old
  connection, rolls back a seek in flight, and stages no close; queued
  events are not moved. Adopt refuses a duplicate id, an exited driver, a
  user-closed connection, or one still on its first handshake (no rebuild
  would ever open the handle there), so the caller restores it instead of
  stranding it. It emits the re-attach at epoch + 1 through the in-place emitters on a
  handshaked connection (ADR-0125 deadline measured from the injected now) and
  otherwise defers to rebuild_producers / rebuild_consumers. It also
  defers on a connection whose handshake completed after a reset but whose
  rebuild has not run yet (reset sets a per-kind rebuild-owed flag that the
  rebuild clears), so an adoption racing the supervisor's rebuild cannot
  open the same producer or consumer twice. Restore puts a refused
  transfer back so the in-place retry still applies.

Tests: proto unit tests for the allocator, the identity truth table and
every transfer path; handle_rehome_equivalence.rs drives two connections
per engine over one shared allocator; tokio and moonpool
handle_ids_are_unique_across_pool_connections pin the wire ids across a
bootstrap and its sibling. The id audit found no test asserting
per-connection ids on a secondary connection: the scripted brokers echo
the wire ids.

Refs #935

Signed-off-by: Alexandre Burgoni <alexandre.burgoni@clever.cloud>
…ing broker

Third step of issue #935 (ADR-0157): an established producer or consumer
whose namespace bundle moved to another broker now follows it, like the
Java client, instead of re-attaching on the old broker until it gives up.
Both engines, 1:1.

- Routing: the client's lookup and connection routing (authoritative
  lookup with redirect chase, connections_per_broker fan-out, pool) is
  split out of Client by impl-block boundaries into a Routing shared with
  every connection of the client through a Weak stamped on
  ConnectionShared (moonpool: the provider-free OwnerRouting object, since
  ConnectionShared is not generic). Routing also keeps a leaf-locked
  registry of the handles' bindings, registered on open and pruned on the
  last clone's drop.
- Broker identity: the bootstrap, its siblings, and every pool entry are
  stamped with the BrokerIdentity of the route that opened them (a proxy
  entry is its backend broker even when it is configured as the
  bootstrap's own proxy_to_broker_url), through the proto target_identity
  rule owner resolution applies too, so connections_per_broker siblings
  never look like an ownership move.
- HandleBinding: Producer, Consumer and every per-handle future and guard
  hold a binding to the connection they currently ride instead of a fixed
  ConnectionShared. Per-handle work snapshots the binding, locks that
  connection and re-checks the generation, retrying on the new connection
  when a move slipped in. Request-bound futures (close, ack receipt, seek,
  last-message-id, schema) keep the connection they were issued on.
  Producer::flush takes its Notified on the snapshotted connection before
  re-checking the generation, so a move landing before it parks cannot
  strand it.
- Retry leg: a non-segment established handle on a routed connection
  resolves the topic's owner with the client's authoritative lookup (a
  Redirected answer is chased, never terminal) under one operation_timeout
  on the engine clock. The same broker identity re-issues in place; a
  different one re-homes the handle in relocate_handle: both connection
  mutexes taken in ascending address order (the only dual-lock site,
  checked by a source-scan test in each engine that also flags a
  connection guard live across a binding-routed lock or inside a binding
  closure, and nested binding closures), take on the old
  connection, adopt on the new one (re-attach at epoch + 1, or deferred
  to its rebuild), binding retargeted inside that critical section, then
  wakers and old-connection waiters pulsed after both are released. A
  refused adoption restores the handle and re-issues in place; a self
  relocation or a handle whose binding is not registered yet re-issues in
  place. A lookup failure feeds the proto policy point (only
  TopicNotFound is terminal). Unrouted connections (tokio from_socket,
  moonpool connect_plain / from_parts, hand-built) keep the in-place leg.
  The moonpool move arms the adoption's open deadline from the injected
  clock. One INFO per move names from/to.

Tests (identically named on both engines, parity 709 = 709):
tests/handle_rehome.rs (10 scripted two-broker scenarios: lookup owner,
assigned-URL immediate leg, redirect chase, proxied brokers, configured
proxy backend in place, consumer queue kept, in-flight receipt ack fails
fast, fan-out sibling stays, close during the move, unrouted client in
place) and inline driver.rs / consumer.rs twins (relocation, adopt
refusal, generation retry, self relocation, flush lost wakeup, the
dual-guard scan, receive after a racing move, per-handle calls and the
deferred receive on the bound connection). The three established_reattach
leg-lookup tests now run each scenario on a routed and on an unrouted
client, so both leg shapes keep their failure paths exercised. Differential
handle_rehome_engine_equivalence.rs drives both engines through the same
two-broker re-home and asserts identical broker-side and client-side
observations.

Refs #935

Signed-off-by: Alexandre Burgoni <alexandre.burgoni@clever.cloud>
Reader::read_next and the tokio read_next_with_timeout now map a
broker-terminated child through the same consumer_receive_error /
PulsarError::from_client path as the consumer wrappers, so a reader on a
terminated topic surfaces PulsarError::Terminated instead of an untyped
Other string.

Document that ProducerApi::is_terminal and PartitionedProducer::is_terminal
also report a connection gone for good (no driver), in which case
terminal_failure() is None and sends fail with PeerClosed, and that
TerminalFailureKind::ReattachLimitExceeded also covers a scalable segment
child exhausting its bounded max_retries budget.

Refs #935

Signed-off-by: Alexandre Burgoni <alexandre.burgoni@clever.cloud>
…d terminal failures

Extract the frame-forging gate of e2e_driver_mid_session_reject.rs into the
shared tests/common/open_reject_gate.rs. It forges a CommandError reply to the
CommandProducer and CommandSubscribe frames a predicate selects; the #302
give-up and #343 first-open tests keep their behaviour through it.

e2e_established_reattach_beyond_budget.rs refuses six re-attaches (three times
max_retries) after a real topics unload: a PartitionedProducer and a consumer
report Reattaching meanwhile and recover once the gate releases, and
established_reattach_limit(2) restores a bounded give-up as
PulsarError::Terminated of kind ReattachLimitExceeded.

e2e_typed_terminal_failure.rs terminates and unloads a topic under an
established TypedProducer and PartitionedProducer: the real broker refuses the
re-attach with TopicTerminatedError, and both send paths return
PulsarError::Terminated of kind TopicTerminated.

All suites boot the default broker through the shared fixture.

Refs #935

Signed-off-by: Alexandre Burgoni <alexandre.burgoni@clever.cloud>
Record the issue #935 decision: an established producer or consumer
re-attaches until it is closed, ended only by the Java terminal set or the
opt-in established_reattach_limit, and re-homes to the owning broker through
an address-ordered two-connection move and a leaf HandleBinding. Terminal
handles surface a typed TerminalFailure.

Amend ADR-0038 (relocation lock rule), ADR-0069, ADR-0080, ADR-0106, ADR-0125
and ADR-0130 with status-line and amendment notes, and update the index,
ARCHITECTURE.md, the README parity rows, docs/follow-ups.md (§19 narrowed to
TopicMigrated, §20 cross-referenced, new §33 and §34), docs/testing.md and the
CHANGELOG [Unreleased] section with an "Upgrading from 2.1" part.

Refs #935

Signed-off-by: Alexandre Burgoni <alexandre.burgoni@clever.cloud>
A tracing field expression only runs when a subscriber enables the level, so
the post-seek 'redeliver_unacked_all = resubscribed && !rehomed' line was
never executed by the subscriber-less coverage domains. Compute it before the
macro in both engines, as the other lifecycle records already do.

Refs #935

Signed-off-by: Alexandre Burgoni <alexandre.burgoni@clever.cloud>
CI's stable toolchain (rustc 1.100.1) adds assert_is_empty and deprecates
AtomicUsize::fetch_update. Assert emptiness with assert_eq! against an empty
Vec so a failure prints the value, and replace fetch_update in the
handle_rehome scripted broker of both engines with a compare_exchange loop
(try_update is not available at the 1.95 MSRV).

Refs #935

Signed-off-by: Alexandre Burgoni <alexandre.burgoni@clever.cloud>
check-sim-coverage failed in CI on 35 added lines that passed locally.
The failure was not a race: the gate reproduces the exact CI set on a
16-core host once it runs the CI toolchain, stable 1.100.1 with its own
llvm-tools-preview (LLVM 23). The earlier local pass paired an LLVM 22
toolchain with the system llvm-cov 22. LLVM 23 rejects those older raw
profiles, and its line attribution gives three shapes a count of their own:

- the closing brace of an `if`/`if let` without `else` carries the
  not-taken edge (conn.rs consumer close, both pools' identity/routing
  stamping, both engines' reissue_in_place, tokio
  with_established_reattach_limit);
- a line holding only a closure carries the closure's count
  (ProducerSlot::queue_send_reserved's map_err);
- each field and message line of a tracing event carries the event
  body, which runs only when a subscriber enables the level (the
  terminal-failure warn, the consumer in-place resubscribe debug, the
  re-home info/warn and the segment lookup retry debug in both engines,
  and tokio's re-attach failure warn/debug).

Evidence, per line group:

- the established_reattach and handle_rehome binaries of both engines
  install the once-per-binary TRACE sink subscriber (`log_every_event`,
  as lookup_reset_race and the differential log contracts already do)
  before every scripted broker binds;
- relocate_restores_on_adopt_refusal, the one test that drives the
  refused re-home, runs its refusals under a scoped TRACE sink subscriber
  in both engines;
- established_reattach_limit_surfaces_typed_terminal_send_error runs on
  a pool-less client as well as a routed one in both engines, so the
  limit is shown to hold without a pool;
- both driver test modules gain
  stale_reissue_in_place_emits_nothing_and_leaves_the_driver_idle (1:1);
- typed_slot_send_errors_and_states_identically asserts the untyped
  queue_send_reserved still folds a rejection into InvariantViolation.

The None arm of the consumer-slot lookup after an in-place resubscribe and
of a pool entry's identity/routing cannot occur, so those are one
expression (`inspect` / `map`) instead of an `if let`; behaviour is
unchanged. docs/testing.md records the toolchain requirement and the
three shapes.

Refs #935

Signed-off-by: Alexandre Burgoni <alexandre.burgoni@clever.cloud>
@alexandrebrg
alexandrebrg merged commit 7aa039a into main Dec 2, 2026
31 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Producer terminally fails after code=6 ServiceNotReady during a bundle unload; every send then returns "producer rejected send"

1 participant