allthingssecurity opened a new pull request, #30821:
URL: https://github.com/apache/camel/pull/30821

   # Description
   
   [CAMEL-27527](https://issues.apache.org/jira/browse/CAMEL-27527)
   
   When a consumer of a `disruptor` endpoint starts, stops, is suspended or 
resumed, `DisruptorReference.reconfigure()` replaces the Disruptor: it clears 
the reference (`disruptor.set(null, true)`), calls `Disruptor.shutdown()` on 
the old one (LMAX waits until the event handlers have consumed every claimed 
slot, then halts them), and starts a new one. A producer reads the reference 
and then claims and publishes a slot on that ring buffer, with no lock. Nothing 
makes the reconfiguration wait for a producer that read the reference just 
before it was cleared. So the producer can claim its slot after the drain found 
no backlog, and publish on a ring buffer whose event handlers are halted:
   
   - an InOnly exchange is accepted without exception and never processed;
   - an InOut producer without timeout waits for its reply forever;
   - with `blockWhenFull=true` (the default), once more such producers arrive 
than the old ring buffer has free slots, they wait in `RingBuffer.next()` 
forever.
   
   The window is wide in a common case: producers that wait for a free slot on 
a full ring buffer (`blockWhenFull`) have read the old reference already. They 
take the slots that the drain frees, and the last ones easily come after the 
drain is done.
   
   A queue without consumer has a second loss on the same path. Its ring buffer 
is held by a blocking event handler. When the first consumer starts, the 
handler is unblocked and copies the backlog into `temporaryExchangeBuffer`, an 
`ArrayBlockingQueue` of the queue size, and ignores the result of `offer()`. 
The producers that waited on the full ring buffer then publish into the freed 
slots, and their exchanges are dropped by `offer()` (or stranded on the halted 
ring buffer as above). For example, size 4, 4 messages sent, 4 more producers 
waiting, then a consumer route is added: all 8 sends return normally, the 
consumer gets 4.
   
   `DelayedExecutor` says the ring buffer is swapped "to keep the producers 
operational without the risk of losing messages", and the component page says a 
reconfiguration flushes the pending exchanges.
   
   ## The fix
   
   `DisruptorReference` counts the producers between reading the reference and 
publishing on its ring buffer (`publishesInFlight`, an `AtomicInteger`): a 
producer increments it, then reads the reference; if the reference is cleared, 
it decrements again and waits for the new Disruptor as before. 
`shutdownDisruptor` clears the reference, unblocks the blocking event handler 
as before, then waits until the count is 0, and only then calls 
`Disruptor.shutdown()`. Both sides are volatile accesses in that order, so 
either the reconfiguration sees the producer and waits for it, or the producer 
sees the cleared reference. Every exchange published on the old ring buffer is 
therefore published before the drain starts, and drained.
   
   A producer that waits for a free slot on the full old ring buffer is 
counted, and the reconfiguration waits for it. This cannot hang where main did 
not hang: its event handlers keep running until `shutdown()` (and the blocking 
handler of a queue without consumer was unblocked just before), so they free 
slots. If they cannot (a consumer that never returns), main hangs in 
`Disruptor.shutdown()` the same way, as that waits for the same consumer. A 
consumer that publishes to its own queue while it waits for a free slot keeps 
working as on main: it is counted like any producer and gets its slot from the 
other consumers.
   
   The buffer that carries the backlog of a queue without consumer to the next 
Disruptor is now a `LinkedBlockingQueue` without bound, so `offer()` cannot 
drop. It can hold more exchanges than the ring buffer (the producers that 
waited on the full ring buffer), so `start()` publishes:
   
   - on a Disruptor with consumers: as many as fit, before the reference is set 
(the backlog still goes first, in order; nothing else publishes on the new ring 
buffer yet, so this does not wait). The rest is published, in order, by a 
short-lived thread (`ExecutorServiceManager.newThread`, started only when there 
is such a rest) once the reference is set. Publishing it in `start()` would 
wait for the new consumers while the thread holds the lock of the disruptor, of 
the endpoint and, for a route start, of the CamelContext: a consumer that takes 
one of them while it handles one of its first messages (for example it resolves 
an endpoint of its own queue with other options, as a `toD` does, which takes 
the lock of the disruptor) would block the route start for good. The thread 
publishes like a producer: it is counted, holds no lock, and claims a slot 
before it takes the first buffered exchange. If a reconfiguration starts 
meanwhile, it waits for that thread as for any producer, and the t
 hread goes on with the new Disruptor once it is set; the new `start()` takes 
the next exchanges from the buffer first, and only that thread and `start()` 
take exchanges from the buffer, so each is published once, in buffer order. If 
the new Disruptor has no consumer, or is not started, the thread stops and the 
rest stays buffered for the next start. If the thread cannot be started (any 
`Throwable` from `newThread()` or `Thread.start()`, such as `OutOfMemoryError: 
unable to create native thread`), the flag that marks it as running is reset, a 
WARN line says how many exchanges stay buffered, and the next start publishes 
them; a `VirtualMachineError` is thrown again, as Camel does elsewhere, the 
others are not, as the Disruptor is already in use;
   - on a Disruptor without consumer (an endpoint added again, or the event 
handlers moved to another CamelContext): nothing, the exchanges stay buffered, 
in order, for the first consumer. Main put them back on the new ring buffer, 
whose blocking handler copied them back into the buffer at the next 
reconfiguration. Meanwhile producers can fill the new ring buffer, so such a 
queue can hold more than `size` exchanges until its first consumer starts (on 
main the buffer was bounded by `size`, and what did not fit was dropped). This 
also applies to its capacity as producers see it: after such a restart the 
producers get an empty ring buffer, so `blockWhenFull` producers do not block 
and `getRemainingCapacity()` reports free slots while up to `size` more 
exchanges (more after several restarts) are buffered; 
`getPendingExchangeCount()` counts the buffered ones.
   
   Ordering. The backlog keeps its own order: the part that fits goes first, 
the rest follows in buffer order. The order of one producer is not kept across 
the hand-over, though. A producer that waited on the full ring buffer when the 
first consumer starts returns once its exchange is on the old ring buffer (it 
then goes to the backlog), and its next sends go to the new ring buffer at 
once, where they compete with the thread that publishes the rest: they can 
overtake the exchange it was waiting with. A red-team probe (one producer, size 
4, the first consumer added while it waits) saw that in 20 of 20 runs, nothing 
lost; main lost that exchange in 20 of 20 runs instead. The same happens on 
each suspend and resume of the only consumer of a queue: with 4 producers in a 
loop, the exchanges of one producer arrived out of order 47 times and none was 
lost, where main kept their order but lost 87. Keeping the order of each 
producer would need producers to wait while the rest is published, wh
 ich this PR does not do.
   
   Cost: one atomic increment and one decrement on one counter per publish. 
With the default `producerType=Multi` that is next to the CAS that 
`MultiProducerSequencer.next()` already does on the cursor; with 
`producerType=Single`, `SingleProducerSequencer.next()` has no atomic 
operation, so these two are the only ones of a publish there (uncontended, a 
few nanoseconds, small next to the copy of the exchange). A reconfiguration 
waits for the producers in flight, which publish without blocking, or wait for 
slots that the drain frees anyway.
   
   Not changed here:
   - a reconfiguration that runs on a consumer thread of the same queue (for 
example a route policy that suspends the route from an on completion) still 
waits for its own event in `Disruptor.shutdown()`, as on main;
   - a consumer that starts to publish to its own queue while it is 
reconfigured waits for the reference, which waits for that consumer: as on main;
   - when the new Disruptor fails to start, producers spin forever waiting for 
it: separate PR (CAMEL-27519). Merged with it, `disruptor.set()` is still the 
last statement of the code that its failure handling covers, so a failure can 
never halt a Disruptor that producers already use;
   - a thread that is interrupted while it waits for an event handler to start 
or stop waits again in a loop that logs at every iteration: a separate PR;
   - the order of one producer across the hand-over of a backlog, see 
"Ordering" above.
   
   ## How it was found
   
   A TLA+ model of the producers, the event handlers and the reconfiguration (2 
to 3 producers, up to 4 Disruptors, 0 to 2 consumers, endpoint stop and 
restart). On main it reports the publish on a halted ring buffer, the producer 
that waits forever on it, the InOut producer that never gets its reply, and the 
drop in the backlog buffer. The model's version of this fix (wait for the 
producers in flight, unbounded buffer) passes every property in both scopes. 
The variant that matches this code exactly (a Disruptor without consumer keeps 
the backlog, the rest is published after the reference is set) is in the model 
too, but was not checked yet. A stress run without injected pauses (4 
producers, a reconfiguration in a loop for 20 s) lost 96 of 30,647 accepted 
exchanges on main.
   
   `DisruptorReconfigureWithBlockingProducerTest`, disabled as flaky in 2019 
and repaired in CAMEL-23437, also sends while a consumer route is added, so I 
checked whether its flakiness was this bug. It does not look like it: I ran its 
original scenario (20 messages sent while a second consumer route with `size=8` 
is added, the first route with an asynchronous `delay`) 10 times on main and 10 
times with this fix, counting what each route got after waiting for them: in 
all 20 runs the first route got all 20 messages and the added route none, 
because the producer was done before the route was added (the `delay` is 
asynchronous, so the ring buffer drains at once, as CAMEL-23437 says). Its 
flakiness came from its expectation that the added route gets at least 10 
messages and from its wall-clock check, not from this race, which that scenario 
does not reach. That test is not changed here.
   
   ## Tests
   
   New `DisruptorReconfigureWithWaitingProducersTest` (package-private, JUnit 
assertions as in the module, Awaitility, no sleeps; a producer counts as 
waiting once its thread is in the sequencer's `next()`):
   
   - `producersWaitingOnTheFullRingBufferWhileAConsumerIsAddedAreNotLost`: a 
queue of size 1 whose consumer holds the first message, 8 producers waiting for 
the slot, then a second consumer route is added on another thread. Once the 
held consumer goes on, the reconfiguration ends, every producer returns, the 
first consumer gets all 10 messages (the 9 sent before plus one sent 
afterwards) and the new one only the message sent afterwards. Size 1 makes 
every message the consumer finishes empty the ring buffer while producers still 
wait, which is where main lets the drain end: on main some producers publish on 
the halted ring buffer and the next ones wait forever;
   - 
`requestReplyProducersWaitingOnTheFullRingBufferWhileAConsumerIsAddedGetTheirReply`:
 the same with InOut producers without timeout: each gets its reply (on main 
some never return);
   - 
`producersWaitingOnTheFullRingBufferOfAQueueWithoutConsumerAreNotLostWhenTheFirstConsumerStarts`:
 a queue of size 4 without consumer, 4 sent, 4 more waiting, then the first 
consumer starts: the reconfiguration does not wait for the waiting producers 
forever, and the consumer gets all 8, the backlog first and in order (on main 
it gets 4);
   - 
`consumerThatTakesTheLockOfItsQueueWhileTheRestOfTheBacklogIsPublishedDoesNotBlockItsStart`:
 a queue of size 2 without consumer, 2 sent, 2 more waiting, then the first 
consumer route is added; on its first message the consumer resolves an endpoint 
of its own queue with another option (as a `toD` does), which takes the lock of 
the disruptor. The route start ends and the consumer gets all 4, the backlog 
first. Publishing the rest in `start()`, with the lock held, blocks both for 
good (the thread that adds the route waits in `RingBuffer.next()` for the 
consumer, which waits for the lock in `addEndpoint`);
   - `consumerAddedWhileTheRestOfTheBacklogIsPublishedGetsTheRestOnce`: the 
same queue with 4 waiting, the first consumer holds the first message, so the 
thread that publishes the rest waits for a slot; a second consumer route is 
added meanwhile. The first consumer gets all 6 once, in buffer order, and the 
second exactly the last 3 (one more was published on the old ring buffer before 
the reconfiguration went on, the others on the new one).
   - `restOfTheBacklogStaysBufferedWhenItsThreadCannotBeStarted`: the same 
queue with 4 waiting; the CamelContext gets an `ExecutorServiceManager` (a 
`DefaultExecutorServiceManager` subclass, as other Camel tests do) whose 
`newThread()` throws an `Error` once for the thread that publishes the rest. 
The route of the first consumer starts, the consumer gets the 2 that fit the 
ring buffer, and the 4 others stay buffered; a second consumer route is added, 
and the first consumer gets all 6, the backlog first. Before this change the 
`Error` went out of the route start; with a variant that catches it but does 
not reset the flag, the last 2 are never published.
   
   On main the six tests fail (6/6): the first two wait 20 s for the producers, 
the others get part of the messages. With a variant that publishes the rest in 
`start()` instead (after the reference is set, with the lock held), the lock 
test hangs (killed after 120 s; the thread dump shows the two threads described 
above) and the fifth test fails. With the previous version of this PR (thread 
start failures caught as `RuntimeException` only), the new sixth test fails 
with the `Error`; with the variant that does not reset the flag, it gets 4 of 
6. With the fix: the class 20 times in one JVM, 120/120; camel-disruptor 142 
tests, 0 failures. A stress run without injected pauses (4 producers for 15 s: 
a reconfiguration loop, and a loop that suspends and resumes the only consumer 
of a queue of size 4, which leaves a rest each time) lost 0 of 5,876 and 0 of 
51,532 accepted exchanges, with no duplicate and no stuck producer (run on the 
previous version, whose publish path is the same). Merged 
 with CAMEL-27519 and with the separate PR for the interrupted wait (no 
conflict, also none with current main): camel-disruptor 145 tests, 0 failures; 
the three new or changed test classes 5 times in one JVM, 45/45.
   
   Backport: the same code is on camel-4.22.x, camel-4.18.x and camel-4.14.x; 
this is silent message loss, so a backport candidate.
   
   _Claude Code on behalf of allthingssecurity_
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to