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

   # Description
   
   [CAMEL-27336](https://issues.apache.org/jira/browse/CAMEL-27336)
   
   `ServicePool.SinglePool` is the pool of a singleton producer (or polling 
consumer) in every `DefaultProducerCache` (toD, recipientList, routingSlip, 
enrich, ProducerTemplate) and `DefaultConsumerCache`. It kept no record of who 
used its producer, so evictions from the LRU cache of the producer cache went 
wrong in three ways:
   
   1. **An evicted producer was stopped while it was in use.** `onEvict` 
stopped the pool at once when the pool map was larger than the capacity (the 
usual case once the cache is full), or marked it in `singlePoolEvicted` so that 
the next acquire or release of any single pool stopped it. Neither checked for 
use, so a send in flight ran on a stopped producer. For a dynamic endpoint 
(toD) the cleanup then found the endpoint unused (its producer was just 
unregistered), and stopped it and removed it from the registry during the send. 
With the default LRU cache (`SimpleLRUCache`) a hit does not refresh the LRU 
order (`putIfAbsent` of a present key adds no change), so the evicted producer 
is the one created first, often the busiest. `MultiplePool` protects its 
producers in use since CAMEL-25003.
   2. **A stale `singlePoolEvicted` entry hit the next pool of the endpoint.** 
`onEvict` both marked the pool and stopped it, so the mark stayed behind. When 
the next `acquire` of the endpoint had created a new pool before its 
`cleanupEvicts` ran, the old pool's `stop()` removed the new pool from the map 
(`pool.remove(endpoint)`, not `remove(endpoint, this)`), the endpoint was 
stopped, and the orphaned pool handed out a producer of the stopped endpoint. 
The next acquire created a second producer of the singleton endpoint, and a 
later eviction of the first one stopped the current producer instead 
(`SinglePool.evict(s)` ignored `s`) and leaked the evicted one until the 
CamelContext stopped.
   3. **`SinglePool.acquire` could return null.** It read the volatile producer 
field twice (check, then return), and an eviction in between made it return 
null (`IllegalStateException: No producer, this processor has not been started` 
in `DefaultProducerCache`).
   
   `DefaultProducerCache`'s `lastUsedProducer` fast path also handed out a 
producer without going through the pool, so it could return a producer that an 
eviction had stopped.
   
   This builds on CAMEL-25066 (#27523), which stopped `cleanupEvicts` from 
stopping an endpoint that another producer cache uses. That check 
(`isEndpointInUse`, with the evicted producer stopped first so it no longer 
counts) is kept as it is; what changes is when and for which producer it runs.
   
   The change, in `ServicePool.SinglePool`:
   
   - the pool counts the acquires and the releases of its producer in two 
`LongAdder`s (so a send does not write to a location that all the worker 
threads share); the users are the difference. `acquire` and `release` count, 
and so does the fast path of `DefaultProducerCache`, which now reacquires the 
last used producer through the pool (`ServicePool.reacquire`, package-private) 
and falls back to `acquire` when that producer is no longer pooled;
   - an eviction takes the pool out of the pool map at once (`remove(endpoint, 
this)`), so the next acquire of the endpoint creates a new pool and producer. 
The evicted producer is stopped, with the endpoint if nothing else uses it, by 
the eviction when nobody uses it, or by its last release. An acquire that comes 
after the eviction undoes its count and uses the new pool. To decide "nobody 
uses it", the releases are summed before the acquires: an acquire is always 
counted before its release, and a thread that got the producer before the 
eviction was counted in the acquires before the eviction, so the two sums are 
only equal when the producer has no user. A flag (`stopped`, compare-and-set) 
makes sure only one thread stops it;
   - `singlePoolEvicted` now holds the evicted pools whose producer is still in 
use, by producer, so `release` finds the pool of a producer whose endpoint 
already has a new pool. It is filled before the pool leaves the map;
   - an eviction of a producer that is not the pool's producer (an acquire in 
progress puts an evicted producer in the LRU cache again, which then evicts it 
again) is ignored, and so is an eviction of a producer whose pool is already 
gone but still in use;
   - `acquire` returns a local copy of the producer, and when the pool was 
evicted (or stopped) meanwhile `ServicePool.acquire` retries with the new pool 
of the endpoint;
   - the stop of the evicted producer and the in-use check of its endpoint run 
under the lock that creates the producers of this `ServicePool`, so a producer 
that a new pool of the same endpoint creates meanwhile is either seen as using 
the endpoint or created after it was stopped (see "Not changed").
   
   `MultiplePool` is unchanged, except that the "pool map larger than the 
capacity" stop moved from `onEvict` into `MultiplePool.evict` (it only applies 
to multi pools now: a single pool always leaves the map when it is evicted). 
Stopping the `ServicePool` still stops every producer, in use or not, as before.
   
   Behaviour change: an evicted singleton producer that is acquired and never 
released (or released more often than acquired) is no longer stopped by the 
eviction; it is stopped when the producer cache stops. The `ProducerCache` and 
`ConsumerCache` contracts already require one release per acquire, and the 
Camel processors do so.
   
   Cost: the fast path of `DefaultProducerCache` now does a `ConcurrentHashMap` 
lookup and a `LongAdder` increment per send, and a release one more increment. 
Measured with a plain loop (no JMH) on one singleton producer with a no-op 
`process`: an acquire and release through `DefaultProducerCache` takes about 12 
ns instead of 4.5 ns, the same with 1 and 8 threads; a whole `send` takes about 
115 ns instead of 104 ns with 1 thread, and about 530 to 560 ns instead of 470 
to 500 ns with 8 threads. A first version with one `AtomicInteger` per pool 
took 1.5 to 3 us per acquire and release with 8 threads (all threads write the 
same counter), which is why the counts are `LongAdder`s. Measured again 
independently on the same machine (single thread, `seda` endpoint, acquire and 
release through `DefaultProducerCache`): 4.3 ns on main, 11.7 ns with the 
change. About 4 ns of the difference are the two atomic increments and about 
1.5 ns the map lookup of the fast path; any count of the users of a 
 shared producer needs an atomic write on acquire and on release, so the 
increments are the floor of this approach. The multi-threaded numbers above 
come from macOS, where `System.nanoTime()` does not scale across threads (as 
noted in CAMEL-25132), so take them as indicative only. Under contention a 
`LongAdder` grows padded cells (up to one per CPU), so a pool whose producer 
many threads share at once uses a few KB more memory. The `ServicePool` work on 
eviction is the same as before, plus the two sums for an evicted producer.
   
   Found with a TLA+ model of `ServicePool` (worker threads that acquire, use 
and release producers, the LRU cache and its eviction callback, 
`cleanupEvicts`, `MultiplePool`, endpoint stop and registry removal), which I 
extended with the fix (the acquire and release counts as one monotonic cell per 
thread, summed cell by cell, the evicted and stopped flags, `singlePoolEvicted` 
by producer, the lock around the stop, the `lastUsedProducer` fast path). On 
main it finds a producer stopped in use (NotStoppedInUse, 1,806 distinct 
states), a null acquire (AcquireNotNull, 23,635), an endpoint stopped while one 
of its producers is in use (9,747) and a leaked producer (NoLeak, 2,409,905). 
With the fix all of these hold, plus "acquires minus releases of a pool equals 
the threads that acquired its producer and did not release it" and "no evicted 
pool is left once all threads are idle": 2 threads, 2 singleton endpoints, 
cache size 1: 2,540,831 distinct states (3,380,919 with the fast path; 1,959,
 922 with one singleton and one non-singleton endpoint), same counts with TLC 
and everystate; with 3 threads (one send each) no violation in 59,204,345 
distinct states, where I stopped it after 25 minutes (not exhaustive, 
everystate only). Two variants show why the code is as it is: without the lock 
around the stop the model finds an endpoint stopped under a producer that a new 
pool created after the in-use check (690,237 distinct states), and summing the 
acquires before the releases stops a producer in use (3 threads, 1,585,953 
distinct states).
   
   Tests: new `ProducerCacheSingletonEvictionTest` (camel-core, deterministic, 
latches only):
   
   - `testEvictedProducerNotStoppedWhileProcessing`: cache size 1, a send to 
`my:a` waits in `process()`, a send to `my:b` evicts its producer: the producer 
and the endpoint must stay started during the send, the send must not fail, and 
both are stopped once it is done;
   - `testEvictedProducerInUseIsStoppedWhenReleased`: the evicted producer in 
use is not handed out again, a second eviction of it (stale entry) does not 
touch the current producer, and its release stops it but not the current 
producer or the endpoint;
   - `testEvictionDoesNotAffectTheNewPoolOfTheEndpoint`: the sequence of item 2 
(`acquire(a)`, `release(a)`, `acquire(b)` held, `acquire(a)` twice): one 
started producer of a started endpoint;
   - `testFastPathDoesNotHandOutEvictedProducer`: the `lastUsedProducer` fast 
path does not hand out an evicted producer, and counts the producer it hands 
out;
   - `testAcquireDoesNotReturnNullWhenEvictedMeanwhile`: an acquire paused 
between reading and returning the producer (through the trace log of 
`SinglePool.acquire`, which calls the producer's `toString()`) while another 
acquire evicts it.
   
   On main all five fail (`The evicted producer should not be stopped while it 
is processing`, `... while it is in use`, `The endpoint of the acquired 
producer should be started`, `The evicted producer should not be handed out 
again`, `Acquire should not return null while the pool is started`). With the 
change all five pass. The new class 20 times in one JVM: 100 run, 0 failures.
   
   Module tests: `camel-support`: 181 run, 0 failures, 5 skipped (and 181, 0 
failures, in its virtual threads execution); `camel-core`: 9712 run, 0 
failures, 1 error, 54 skipped. The error is `ValidatorExternalResourceTest`, 
which loads an XSD from raw.githubusercontent.com and cannot connect from this 
machine, as in #27523. In an earlier run of the module 
`FileConsumerDoneFileNameAsyncLastFileTest` timed out once while the machine 
was busy; it passed 3 of 3 on its own with the change. `camel-management` (the 
whole module, including `ManagedConsumerCacheTest`, 
`ManagedSendDynamicProcessorTest` and the recipient list and endpoint registry 
tests): 491 run, 0 failures.
   
   Not changed (as on main, and as described in CAMEL-25066):
   
   - A producer cache that resolved an endpoint instance just before it was 
stopped and removed (by the eviction of its last producer, in this or another 
producer cache) creates its first producer of the stopped endpoint. Closing 
that needs the endpoint to be resolved and acquired under one lock shared by 
all producer caches.
   - `DefaultConsumerCache` uses the same `SinglePool` for singleton polling 
consumers, so it gets the same fix; I did not add a separate test of it, as the 
pool code is the same for producers and polling consumers and 
`DefaultConsumerCache` releases in a `finally`. For polling consumers the 
behaviour change above means: a `pollEnrich` that is still waiting in 
`receive()` (for example with no timeout) keeps an evicted polling consumer 
started until the receive returns (main could stop it during the receive).
   
   # Target
   
   - [x] I checked that the commit is targeting the correct branch (Camel 4 
uses the `main` branch)
   
   # Tracking
   - [x] If this is a large change, bug fix, or code improvement, I checked 
there is a [JIRA issue](https://issues.apache.org/jira/browse/CAMEL) filed for 
the change (usually before you start working on it): 
[CAMEL-27336](https://issues.apache.org/jira/browse/CAMEL-27336).
   
   # Apache Camel coding standards and style
   
   - [x] I checked that each commit in the pull request has a meaningful 
subject line and body.
   - [ ] I have run `mvn clean install -DskipTests` locally from root folder 
and I have committed all auto-generated changes.
     (I built and tested `core/camel-support` and `core/camel-core`, including 
the formatter and import-sort plugins. No generated files change. I did not run 
the full root build.)
   
   # AI-assisted contributions
   
   - [x] If this PR includes AI-generated code, commits have proper 
co-authorship attribution (e.g., `Co-authored-by` trailers) and the PR 
description identifies the AI tool used.
     This PR was prepared with Claude Code (Claude Opus 5.5). The commit 
carries a `Co-Authored-By` trailer.
   
   _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