Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,7 @@ The pattern is the same one [`quinn`] _would_ be using if it didn't ship its own
| `arc_swap::ArcSwap` | rare config-rotation slots | Lock-free swap. |
| `slab::Slab` | per-future Waker keyspace | O(1) insertion + removal. |
| `parking_lot::Mutex<BTreeMap<u64, Waker>>` | `magnetar_proto::MemoryLimitController.waiters` (one per client) | Parked `ProducerBlock` sends keyed by never-reused ids; a leaf lock (ADR-0111). |
| `parking_lot::Mutex<Arc<ConnectionShared>>` | `HandleBinding.current` (one per producer / consumer), the client's binding registry | The connection a handle is bound to, retargeted by a re-home; leaf locks (ADR-0157). |

Anything not on this list either has a justification in [GUIDELINES.md](GUIDELINES.md) or is a candidate for removal.

Expand All @@ -450,6 +451,12 @@ It is a **leaf**: nothing is acquired while it is held, and no waker is woken or
Releasing a publish's memory reservation takes it, and that may happen under the global lock — an `OpSend` dropped by the receipt arm — but never under a per-slot lock: the producer state machine hands every removed `OpSend` back to its `Connection` caller, which drops it after the slot guard.
The full order is **global → per-slot → memory-limit waiters**.

Re-homing an established handle to another broker connection ([ADR-0157](specs/adr/0157-reattach-established-handles-until-closed-and-rehome-on-ownership-move.md)) is the one place two connection mutexes are held together.
`relocate_handle` locks the old and the new connection in ascending address order, takes the handle from the old one, adopts it on the new one, and retargets the handle's `HandleBinding` while both locks are held; per-slot mutexes are taken only after both, and wakers run only after both are released.
`HandleBinding` (the handle's current `Arc<ConnectionShared>` plus a generation counter) and the client-wide binding registry are leaf locks: nothing is acquired while either is held.
Per-handle access snapshots the binding, locks that connection, and re-checks the generation, so a future that locks the old connection after a move retries on the new one.
Each engine's `only_relocate_handle_holds_two_connection_guards` unit test scans its own sources and fails if any other function holds two connection guards.

#### Schema — state layout (where each field lives)

```text
Expand Down Expand Up @@ -823,8 +830,13 @@ Retry ownership depends on whether the handle has ever attached:

1. **Provisional setup is client-owned and routing-aware.** Before the first `ProducerSuccess` or subscribe acknowledgement, `Connection::handle_command_error` removes the provisional handle and emits `ProducerOpenFailed` or `SubscribeFailed`.
The runtime client backs off, re-runs lookup and target resolution, and creates a fresh provisional handle on the resolved connection, so a redirect or ownership move can route the retry to a different broker.
2. **Established reattachment is driver-owned and connection-local.** After a handle has attached at least once, a retryable reattachment failure retains its state and emits `ProducerOpenFailedTransient` or `SubscribeFailedTransient`.
The driver sleeps, runs `lookup_then(topic)`, and invokes `retry_producer_open_if_current(handle, failed_request_id)` or `retry_consumer_subscribe_if_current(handle, failed_request_id)` for that established handle; the failed request id makes a delayed retry a no-op when a newer reconnect rebuild or retry generation has already superseded it.
2. **Established reattachment is driver-owned and follows the owning broker** ([ADR-0157](specs/adr/0157-reattach-established-handles-until-closed-and-rehome-on-ownership-move.md)).
After a handle has attached at least once, every reattachment failure — a `CommandError` on the current re-attach, an ADR-0125 open-timeout expiry, or a retry-leg lookup failure — goes through `Connection::note_established_failure`, which retains the handle's state and decides `Retry` or `Terminal`.
Only the Java terminal set ends an established handle (`TopicNotFound`; plus `TopicTerminatedError` and `ProducerFenced` for a producer), or the opt-in `established_reattach_limit`; `max_retries` does not.
On `Retry` the driver sleeps `Connection::reattach_delay` (exponential to `max_backoff`, jittered per handle, zero after a close that named an assigned broker URL), resolves the owner through the client's authoritative lookup with redirect chase, and compares `BrokerIdentity`.
The same broker invokes `retry_producer_open_if_current(handle, failed_request_id)` or `retry_consumer_subscribe_if_current(handle, failed_request_id)` in place; another broker re-homes the handle through `relocate_handle` (see the lock-ordering invariant below).
The failed request id makes a delayed retry a no-op when a newer reconnect rebuild or retry generation has already superseded it.
Scalable `segment://` children keep the bounded ADR-0080 leg on their own connection: `max_retries`, an in-place `lookup_then(topic)`, and a terminal `Redirected`.
Producer and consumer retry lookup legs run only on a connected session and are awakened when their active request generation is replaced, so a blackholed lookup cannot outlive the generation that authorized it.
Producer sends remain staged until `ProducerSuccess`; consumer flow remains gated until the subscribe acknowledgement.
A driver-owned consumer reattachment acknowledgement updates durable attachment state and releases gated flow without emitting an unowned `SubscribeAcked` event.
Expand All @@ -834,7 +846,8 @@ Retry ownership depends on whether the handle has ever attached:
A user-owned subscribe or seek additionally keeps one stable logical waiter token while retry and reconnect replace its active wire `RequestId`; only the current active request can complete that token, so an older same-handle acknowledgement cannot satisfy the waiter or release flow.
Completion remains durable across reset but is consumed only on a connected rebuilt session, and dropping the waiter transfers the active or next rebuilt subscribe to flow ownership.
3. **Retry budgets stay distinct.** Provisional attachment retries consume the caller operation's attachment counter and shared deadline.
Established lifecycle reattachment uses an independent per-handle counter under the same configured policy and does not consume the completed setup operation's count or deadline.
Established lifecycle reattachment uses an independent per-handle counter and does not consume the completed setup operation's count or deadline.
That counter is a backoff input, a diagnostic surfaced as `HandleState::Reattaching { attempts, .. }`, and the input to the opt-in limit; it resets on a successful re-attach and survives a transport reset.

Tokio performs provisional and established retry sleeps on `tokio::time`.
Moonpool routes both through the injected `TimeProvider`, preserving deterministic virtual-time behavior.
Expand Down
40 changes: 40 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,46 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),

## [Unreleased]

### Upgrading from 2.1

- `ClientError` of `magnetar-runtime-tokio` and of `magnetar-runtime-moonpool`, and the façade's `PulsarError`, gain a `Terminated(TerminalFailure)` variant.
An exhaustive `match` on any of them needs a new arm.
- `OperationRetryConfig::max_retries` no longer bounds a producer or consumer that has attached once; it keeps bounding first creates and subscribes, lookups and partition metadata.
To keep a bound on re-attaching handles, set `ClientBuilder::established_reattach_limit(n)` (or `Client::with_established_reattach_limit(Some(n))` on a runtime client).
- A send or receive on a handle the broker terminally failed now returns `ClientError::Terminated` / `PulsarError::Terminated` instead of `ClientError::Protocol`, `ClientError::Other`, `ClientError::PeerClosed`, `ClientError::Closed` or a stringified `PulsarError::Other`.
Match the typed `TerminalFailure` (`kind`, `code`, `message`) instead of the error text.
A connection-level failure (a driver exit or a supervisor give-up) still returns `PeerClosed` on send and `Closed` on receive.
- A send on a clone of a producer the user closed now returns `ClientError::Closed` on both engines, instead of `ClientError::Protocol(InvariantViolation)` on tokio and `ClientError::Other` on moonpool.
- Producer and consumer ids on the wire come from one client-wide sequence, so ids on pool connections are no longer per-connection.

### Added

- **`HandleState` and typed terminal failures** ([ADR-0157](specs/adr/0157-reattach-established-handles-until-closed-and-rehome-on-ownership-move.md)).
`Producer::state()`, `Consumer::state()`, `TypedProducer::state()`, `PartitionedProducer::partition_states()` and `MultiTopicsConsumer::child_states()` / `PatternConsumer::child_states()` report `Ready`, `Reattaching { attempts, last_error }`, `Terminated(TerminalFailure)` or `Closed`.
`terminal_failure()` and `is_terminal()` on the producers, and `terminal_failure()` on the consumers, return the broker's refusal as a `TerminalFailure` of kind `TopicNotFound`, `TopicTerminated`, `ProducerFenced`, `ReattachLimitExceeded` or `Rejected`.
A producer's `is_terminal()` is also `true` when its connection is gone for good with no driver left to reconnect it; `terminal_failure()` is then `None` and sends return `PeerClosed`.
`ProducerApi` and `ConsumerApi` gain these as provided methods, so external implementors need no change.
`TerminalFailure`, `TerminalFailureKind` and `HandleState` are re-exported from `magnetar`.
- **`ClientBuilder::established_reattach_limit(u32)`** and `Client::with_established_reattach_limit(Option<u32>)` on both runtime clients bound how many failed re-attaches an established handle survives; the default is unbounded.

### Changed

- **An established producer or consumer re-attaches until it is closed, as in the Java client** ([ADR-0157](specs/adr/0157-reattach-established-handles-until-closed-and-rehome-on-ownership-move.md), [#935](https://github.com/CleverCloud/magnetar/issues/935)).
Only `TopicNotFound` (and, for a producer, `TopicTerminatedError` or `ProducerFenced`) or the opt-in limit ends it; every other refusal, including `ServiceNotReady`, authorization errors and `IncompatibleSchema`, is retried.
Pending sends keep queueing and fail only on their own `send_timeout`.
Scalable `segment://` children keep the bounded `max_retries` policy, because their controller re-assigns them.
- **An established handle follows its topic to the owning broker.** Each retry resolves the owner through an authoritative lookup with redirect chase, and a handle whose owner is another broker is re-homed to that broker's connection with its id, its queued and in-flight sends, its receive queue and its waiters.
A close that names an assigned broker URL makes the first retry immediate.
`is_connected()` keeps describing the shared connection; use `is_ready()` or `state()` for one handle.
- Re-attach failures log at WARN on the first failure, every power of two and every change of error code (DEBUG otherwise), with `attempts` and `next_delay_ms`; a re-home logs one INFO naming the old and new broker.

### Fixed

- **Established producers and consumers no longer die after a bundle unload** ([#935](https://github.com/CleverCloud/magnetar/issues/935)).
An unloaded bundle terminalized every established handle after `max_retries` refused re-attaches (about 50 s with the default policy), after which every send failed with `send: producer rejected send` and the application had to rebuild the producer; a bundle moved to another broker was retried against the old owner until then.
- A retry-leg lookup that ended in an unexpected outcome (such as a connection reset mid-lookup) no longer strands the handle without any further retry.
- A `CommandCloseConsumer` naming an assigned broker URL no longer leaves an established consumer detached for good: it resubscribes in place, as a close without a URL already did.

## [2.1.0] - 2026-11-24

### Upgrading from 2.0
Expand Down
4 changes: 3 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,9 @@ These are the **workspace-wide rules**. The protocol-correctness subset (CRC32C,
The hot path (`Producer::send` → `ProducerSlot::queue_send`) takes only the per-slot mutex; the driver merges per-slot staged frames into the connection buffer under the global lock via `poll_transmit`.
The reverse acquisition order deadlocks under contention.
The client-wide `MemoryLimitController`'s waiter mutex sits below both as a leaf lock: nothing is acquired while it is held, no waker runs under it, and a memory reservation is never dropped under a per-slot mutex.
([ADR-0038](specs/adr/0038-split-connection-mutex.md), [ADR-0111](specs/adr/0111-share-one-memory-limit-controller-per-client.md))
The one place two connection mutexes are held together is `relocate_handle`, which re-homes an established handle to another broker connection: it locks both in ascending address order, takes per-slot mutexes only after both, and wakes wakers only after releasing them.
The engine-side `HandleBinding` and the client-wide binding registry are leaf locks; nothing else may hold two connection guards, which each engine's `only_relocate_handle_holds_two_connection_guards` test enforces.
([ADR-0038](specs/adr/0038-split-connection-mutex.md), [ADR-0111](specs/adr/0111-share-one-memory-limit-controller-per-client.md), [ADR-0157](specs/adr/0157-reattach-established-handles-until-closed-and-rehome-on-ownership-move.md))

## Workflow

Expand Down
Loading
Loading