Skip to main content

camel_processor/
aggregator.rs

1use std::collections::HashMap;
2use std::future::Future;
3use std::pin::Pin;
4use std::sync::{Arc, Mutex};
5use std::task::{Context, Poll};
6use std::time::{Duration, Instant};
7
8use tokio::sync::mpsc;
9use tokio::task::JoinHandle;
10use tokio_util::sync::CancellationToken;
11use tower::Service;
12
13use async_trait::async_trait;
14use camel_api::{
15    CamelError, MetricsCollector, StepLifecycle, StepShutdownReason,
16    aggregator::{
17        AggregationStrategy, AggregatorConfig, CompletionCondition, CompletionMode,
18        CompletionReason, CorrelationStrategy,
19    },
20    body::Body,
21    exchange::Exchange,
22    message::Message,
23};
24use camel_component_api::InFlightClaim;
25use camel_language_api::{Expression, Language, Predicate};
26
27pub type SharedLanguageRegistry = Arc<std::sync::Mutex<HashMap<String, Arc<dyn Language>>>>;
28
29/// Correlation strategy resolved at construction: the language expression is
30/// compiled once and held as a shareable trait object, so the hot path never
31/// touches the language registry.
32#[derive(Clone)]
33enum CompiledCorrelation {
34    HeaderName(String),
35    Expression(Arc<dyn Expression>),
36    #[allow(clippy::type_complexity)]
37    Fn(Arc<dyn Fn(&Exchange) -> Option<String> + Send + Sync>),
38    /// A strategy this build does not understand. Retained so `try_new` can
39    /// fail closed at construction; the hot-path arm is defensive only.
40    Unsupported,
41}
42
43/// Construction-time view of the aggregator config: everything the hot path
44/// needs, with zero references to the language registry.
45#[derive(Clone)]
46struct CompiledAggregatorConfig {
47    correlation: CompiledCorrelation,
48    /// Every `PredicateExpr` completion condition compiled once, in config
49    /// order. Evaluation OR-combines them; an empty slice means the mode has
50    /// no predicate condition (Size/Predicate/Timeout only). Sync completion
51    /// still reads the original [`AggregatorConfig::completion`].
52    completion_predicates: Arc<[Arc<dyn Predicate>]>,
53}
54
55/// A bucket emission delivered outside the submitting call (timeout
56/// fire, `force_complete_all`): the aggregated exchange plus every
57/// stashed drainclaim it completes. The consumer of the late channel
58/// MUST hold `claims` until the emission's continuation pipeline (or
59/// reply) completes — dropping them IS the release.
60pub struct AggregateEmission {
61    pub exchange: Exchange,
62    pub claims: Vec<Option<InFlightClaim>>,
63}
64
65/// Result of [`AggregatorService::submit_with_claim`].
66///
67/// Claim-propagation contract (drainclaim): on a pending stash the
68/// claim stays inside the bucket; on sync completion the bucket's
69/// claims (the submitter's included) are returned here so the caller
70/// can hold them across the aggregated exchange's continuation; on
71/// error the submitted claim was dropped inside (rejected = released).
72pub struct AggregationReceipt {
73    /// The pending-marked ack or the aggregated exchange — the same
74    /// shapes the tower `Service::call` returns.
75    pub reply: Result<Exchange, CamelError>,
76    /// Claims released with this receipt. Empty for a pending stash
77    /// (claims stay in the bucket) and for errors.
78    pub claims: Vec<Option<InFlightClaim>>,
79}
80
81/// Sampling cadence for the metrics-only sweep (no `bucket_ttl` configured):
82/// matches the 250ms cadence of the other dashboard-observability T3.3
83/// queue-depth samplers.
84const QUEUE_DEPTH_SAMPLE_INTERVAL: Duration = Duration::from_millis(250);
85
86pub const CAMEL_AGGREGATOR_PENDING: &str = "CamelAggregatorPending";
87pub const CAMEL_AGGREGATED_SIZE: &str = "CamelAggregatedSize";
88pub const CAMEL_AGGREGATED_KEY: &str = "CamelAggregatedKey";
89pub const CAMEL_AGGREGATED_COMPLETION_REASON: &str = "CamelAggregatedCompletionReason";
90
91/// Internal bucket structure with timestamp tracking for TTL eviction.
92///
93/// drainclaim: `claims` runs parallel to `exchanges` (same length
94/// invariant, maintained by [`Bucket::push`] and [`Bucket::into_parts`])
95/// — one stashed claim per buffered exchange, moved in by the route
96/// loop via [`AggregatorService::submit_with_claim`]. Whenever a bucket
97/// leaves the map without emitting (TTL eviction, unarmed-bucket
98/// release, discard-on-timeout), the dropped claims release.
99struct Bucket {
100    exchanges: Vec<Exchange>,
101    claims: Vec<Option<InFlightClaim>>,
102    last_updated: Instant,
103}
104
105impl Bucket {
106    fn new() -> Self {
107        Self {
108            exchanges: Vec::new(),
109            claims: Vec::new(),
110            last_updated: Instant::now(),
111        }
112    }
113
114    fn push(&mut self, exchange: Exchange, claim: Option<InFlightClaim>) {
115        self.exchanges.push(exchange);
116        self.claims.push(claim);
117        self.last_updated = Instant::now();
118    }
119
120    /// Split the bucket into its exchanges and their stashed claims
121    /// (same order, same length).
122    fn into_parts(self) -> (Vec<Exchange>, Vec<Option<InFlightClaim>>) {
123        (self.exchanges, self.claims)
124    }
125
126    fn is_expired(&self, ttl: Duration) -> bool {
127        Instant::now().duration_since(self.last_updated) >= ttl
128    }
129}
130
131#[derive(Clone)]
132pub struct AggregatorService {
133    config: AggregatorConfig,
134    buckets: Arc<Mutex<HashMap<String, Bucket>>>,
135    timeout_tasks: Arc<Mutex<HashMap<String, CancellationToken>>>,
136    timeout_handles: Arc<Mutex<HashMap<String, JoinHandle<()>>>>,
137    late_tx: mpsc::Sender<AggregateEmission>,
138    /// Correlation/completion expressions compiled once at construction.
139    /// The language registry is intentionally NOT retained. Shared behind an
140    /// `Arc` so the per-exchange clone is a refcount bump, not a rebuild.
141    compiled: Arc<CompiledAggregatorConfig>,
142    /// Swappable cell holding the cancellation token for the background
143    /// maintenance sweep task. `StepLifecycle::start` replaces this with a fresh token
144    /// so the sweep respawns on the next `poll_ready`; `shutdown` cancels the
145    /// current token to terminate the task. The value is initially seeded from
146    /// the route token — cancelling the route token cancels the sweep (the
147    /// primary shutdown path). This replaces the plain `route_cancel` field.
148    sweep_cancel: Arc<Mutex<CancellationToken>>,
149    /// Handle to the background maintenance sweep task. `None` until the
150    /// first `poll_ready`. The sweep exists when `bucket_ttl` OR
151    /// `queue_metrics` is configured (TTL eviction and/or queue-depth
152    /// sampling); with neither set there is nothing to sweep and no task is
153    /// spawned. The task binds to the current `sweep_cancel` token via
154    /// `select!`; `StepLifecycle::start` clears this to `None` (aborting the
155    /// old task) so `poll_ready` respawns with the fresh token.
156    sweep_handle: Arc<Mutex<Option<JoinHandle<()>>>>,
157    /// Queue-depth reporting (collector + `aggregator:<route>` label). When
158    /// set, the background maintenance sweep publishes the buffered group
159    /// count as `camel_queue_depth{queue}` — with or without a
160    /// `bucket_ttl`. `None` when no collector was injected at compile time.
161    queue_metrics: Option<(Arc<dyn MetricsCollector>, String)>,
162    /// Strong-count cell backing the last-owner check in [`Drop`]: transient
163    /// clones (the pipeline clones the service per `poll_ready`) must not
164    /// abort the shared sweep task; only the final owner's drop may.
165    clone_guard: Arc<()>,
166    /// Memoized correlation-key serialization: the last STRING key value
167    /// paired with its `serde_json::to_string` form. Split-aggregate streams
168    /// re-send the same constant key for every fragment; the memo turns
169    /// per-fragment serialization into one string equality check. Shared via
170    /// `Arc` (cloned into every `call` future) so all clones of the service
171    /// share one memo slot. ONLY string keys are memoizable: their `Value`
172    /// equality exactly tracks their serialization. Every other shape
173    /// serializes per fragment (see `call` — e.g. float `0.0`/`-0.0` compare
174    /// equal but serialize differently, so memoizing numbers could merge
175    /// buckets that serde keeps distinct).
176    cached_key: Arc<Mutex<Option<(serde_json::Value, String)>>>,
177    /// Test-only count of correlation-key serializations actually performed
178    /// (fast-path misses + per-fragment object bypass). Asserted by the memo
179    /// tests; compiles out of non-test builds.
180    #[cfg(test)]
181    key_serializations: Arc<std::sync::atomic::AtomicUsize>,
182}
183
184impl std::fmt::Debug for AggregatorService {
185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186        f.debug_struct("AggregatorService").finish_non_exhaustive()
187    }
188}
189
190impl Drop for AggregatorService {
191    fn drop(&mut self) {
192        // Defense-in-depth: abort the background sweep on drop so it cannot
193        // leak even if the route owner forgets to call `shutdown`. The
194        // primary shutdown path is now `StepLifecycle::shutdown` which
195        // cancels `sweep_cancel` and aborts `sweep_handle`. `abort()` on an
196        // already-finished task is a no-op.
197        //
198        // Last-owner guard: `Clone` shares this cell, so a transient clone
199        // dropping (the pipeline clones the service on every `poll_ready`)
200        // does NOT abort the sweep — only the final owner's drop does.
201        if Arc::strong_count(&self.clone_guard) > 1 {
202            return;
203        }
204        if let Some(handle) = self
205            .sweep_handle
206            .lock()
207            .unwrap_or_else(|e| e.into_inner())
208            .take()
209        {
210            handle.abort();
211        }
212    }
213}
214
215impl AggregatorService {
216    /// Fallible constructor: validates the config and compiles every
217    /// correlation/completion expression ONCE against the language registry.
218    ///
219    /// Construction takes a single registry snapshot and drops it before
220    /// returning, so the service holds zero registry references and the hot
221    /// path cannot fail on a missing/unregistered language. Fails closed
222    /// (ADR-0033): an invalid config, unknown language, malformed expression,
223    /// or unsupported correlation strategy is an error here, never a deferred
224    /// per-exchange failure.
225    ///
226    /// Construction is runtime-free (no `tokio::spawn`); the maintenance sweep
227    /// spawns lazily on the first `poll_ready`.
228    pub fn try_new(
229        config: AggregatorConfig,
230        late_tx: mpsc::Sender<AggregateEmission>,
231        language_registry: SharedLanguageRegistry,
232        route_cancel: CancellationToken,
233    ) -> Result<Self, CamelError> {
234        // R3-M2: at least one memory-release bound is mandatory.
235        config.validate()?;
236
237        // R3-M2 advisory: Size/Predicate-only completion (no Timeout) with no
238        // bucket_ttl means buckets accumulate until max_buckets is hit. Bounded
239        // by max_buckets (validated above) but worth surfacing to operators.
240        let has_timeout = has_timeout_condition(&config.completion);
241        if !has_timeout && config.bucket_ttl.is_none() {
242            tracing::warn!(
243                "Aggregator configured with Size/Predicate completion and no \
244                 bucket_ttl: buckets accumulate until max_buckets is reached"
245            );
246        }
247
248        // Resolve every language handle under ONE lock, then compile. The
249        // snapshot is local and dropped before returning; the service keeps
250        // only the compiled trait objects. Compilation is synchronous, so the
251        // guard never spans an await.
252        let languages = snapshot_languages(&language_registry);
253        let correlation = compile_correlation(&config.correlation, &languages)?;
254        // A future strategy compiles to the inert variant; fail closed here so
255        // the hot path never sees it.
256        if matches!(correlation, CompiledCorrelation::Unsupported) {
257            return Err(CamelError::ProcessorError(
258                "Aggregator: unsupported correlation strategy".to_string(),
259            ));
260        }
261        let compiled = Arc::new(CompiledAggregatorConfig {
262            correlation,
263            completion_predicates: compile_completion_predicates(&config.completion, &languages)?,
264        });
265
266        // Build the shared buckets map up front so the sweep task can
267        // share it via Arc::clone.
268        let buckets: Arc<Mutex<HashMap<String, Bucket>>> = Arc::new(Mutex::new(HashMap::new()));
269
270        // R3-C1 Batch 1: the TTL-sweep is NOT spawned here — construction
271        // must stay runtime-free so callers that build an AggregatorService
272        // outside a tokio runtime (route-spec tests) do not panic on
273        // `tokio::spawn`. The sweep is spawned lazily on the first
274        // `poll_ready`. The inline `guard.retain(...)` per `call` evicts
275        // expired buckets regardless, so the cap + TTL invariants hold
276        // whether or not the sweep has started yet.
277
278        Ok(Self {
279            config,
280            buckets,
281            timeout_tasks: Arc::new(Mutex::new(HashMap::new())),
282            timeout_handles: Arc::new(Mutex::new(HashMap::new())),
283            late_tx,
284            compiled,
285            sweep_cancel: Arc::new(Mutex::new(route_cancel)),
286            sweep_handle: Arc::new(Mutex::new(None)),
287            queue_metrics: None,
288            clone_guard: Arc::new(()),
289            cached_key: Arc::new(Mutex::new(None)),
290            #[cfg(test)]
291            key_serializations: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
292        })
293    }
294
295    /// Infallible constructor preserving the historical signature. Panics when
296    /// [`Self::try_new`] rejects the config (fail-closed startup invariant).
297    ///
298    /// Lifecycle invariant: `sweep_cancel` is initially seeded from the
299    /// route's cancellation token and wrapped in a swappable `Arc<Mutex<...>>`
300    /// cell. `StepLifecycle::start` replaces it with a fresh token so the
301    /// sweep respawns after a restart. Construction is runtime-free (no
302    /// `tokio::spawn` here). The maintenance sweep task (TTL eviction when
303    /// `bucket_ttl` is set, queue-depth sampling when `queue_metrics` is
304    /// set) is spawned LAZILY on the first `poll_ready` and bound to the
305    /// current `sweep_cancel` token via `select!`.
306    /// The route owner MUST call `shutdown` to cancel it;
307    /// `Drop` also aborts it as defense-in-depth.
308    pub fn new(
309        config: AggregatorConfig,
310        late_tx: mpsc::Sender<AggregateEmission>,
311        language_registry: SharedLanguageRegistry,
312        route_cancel: CancellationToken,
313    ) -> Self {
314        Self::try_new(config, late_tx, language_registry, route_cancel).expect(
315            // allow-unwrap
316            // fail-closed startup invariant (ADR-0033); a config without a bound is a programmer/operator error.
317            "AggregatorService::new: config failed validation \
318             (need max_buckets, completionTimeout, or bucket_ttl)",
319        )
320    }
321
322    /// Inject queue-depth reporting: the TTL-sweep maintenance pass publishes
323    /// the buffered group count (open correlation buckets) as
324    /// `camel_queue_depth{queue = label}`. `label` is the route-scoped
325    /// closed-set identifier (`aggregator:<route>`).
326    pub fn with_queue_metrics(
327        mut self,
328        metrics: Arc<dyn MetricsCollector>,
329        label: impl Into<String>,
330    ) -> Self {
331        self.queue_metrics = Some((metrics, label.into()));
332        self
333    }
334
335    pub fn config(&self) -> &AggregatorConfig {
336        &self.config
337    }
338
339    pub fn has_timeout(&self) -> bool {
340        has_timeout_condition(&self.config.completion)
341    }
342
343    pub fn force_complete_all(&self) {
344        let mut buckets_guard = self.buckets.lock().unwrap_or_else(|e| e.into_inner());
345        let keys: Vec<String> = buckets_guard.keys().cloned().collect();
346
347        for key in keys {
348            if let Some(bucket) = buckets_guard.remove(&key) {
349                if self.config.force_completion_on_stop {
350                    cancel_timeout_task_with_handle(
351                        &key,
352                        &self.timeout_tasks,
353                        &self.timeout_handles,
354                    );
355                    let (exchanges, claims) = bucket.into_parts();
356                    match aggregate(exchanges, &self.config.strategy) {
357                        Ok(mut result) => {
358                            result.set_property(
359                                CAMEL_AGGREGATED_COMPLETION_REASON,
360                                serde_json::json!(CompletionReason::Stop.as_str()),
361                            );
362                            if self
363                                .late_tx
364                                .try_send(AggregateEmission {
365                                    exchange: result,
366                                    claims,
367                                })
368                                .is_err()
369                            {
370                                tracing::warn!(
371                                    key = %key,
372                                    "aggregator force-complete emit dropped: late channel full"
373                                );
374                            }
375                        }
376                        Err(e) => {
377                            // log-policy: handler-owned
378                            tracing::warn!(
379                                key = %key,
380                                error = %e,
381                                "aggregation failed in force_complete_all"
382                            );
383                        }
384                    }
385                } else {
386                    cancel_timeout_task_with_handle(
387                        &key,
388                        &self.timeout_tasks,
389                        &self.timeout_handles,
390                    );
391                }
392            }
393        }
394    }
395
396    /// Consumer-exit release (bd rc-iioeq): discard buckets with NO armed
397    /// timeout task, leave armed buckets untouched.
398    ///
399    /// After a natural consumer exit no further exchanges arrive, so a
400    /// bucket without an armed timeout task can never complete on its
401    /// own — its buffered exchanges are released eagerly (the same
402    /// discard semantics `force_complete_all` applies with
403    /// `force_completion_on_stop=false`). A bucket WITH an armed timeout
404    /// task is left alone: that task owns its completion and emits
405    /// through the late channel when the timeout fires.
406    ///
407    /// Arming is decided per bucket in `call`: when the
408    /// `max_timeout_tasks` cap is reached, a timeout-configured bucket
409    /// stays unarmed. Without this release such a bucket would be
410    /// orphaned forever — the `bucket_ttl` sweep only runs inside `call`
411    /// on the next exchange, which never arrives after consumer exit.
412    pub fn release_unarmed_buckets(&self) {
413        let mut buckets_guard = self.buckets.lock().unwrap_or_else(|e| e.into_inner());
414        let timeout_guard = self.timeout_tasks.lock().unwrap_or_else(|e| e.into_inner());
415        let before = buckets_guard.len();
416        buckets_guard.retain(|key, _| timeout_guard.contains_key(key));
417        let released = before - buckets_guard.len();
418        if released > 0 {
419            tracing::debug!(
420                released,
421                armed = buckets_guard.len(),
422                "aggregator released unarmed buckets on consumer exit"
423            );
424        }
425    }
426
427    /// Graceful shutdown: cancel all outstanding timeout tasks and await their
428    /// JoinHandles (with a 5s deadline) so that no tasks are leaked.
429    pub(crate) async fn shutdown_inner(&self) {
430        // Cancel all timeout cancellation tokens.
431        {
432            let mut guard = self.timeout_tasks.lock().unwrap_or_else(|e| e.into_inner());
433            for token in guard.values() {
434                token.cancel();
435            }
436            guard.clear();
437        };
438
439        // Remove and collect all JoinHandles.
440        let handles: Vec<JoinHandle<()>> = {
441            let mut guard = self
442                .timeout_handles
443                .lock()
444                .unwrap_or_else(|e| e.into_inner());
445            guard.drain().map(|(_, handle)| handle).collect()
446        };
447
448        if handles.is_empty() {
449            return;
450        }
451
452        // Await all handles with a deadline.
453        let _ = tokio::time::timeout(Duration::from_secs(5), async {
454            for handle in handles {
455                let _ = handle.await;
456            }
457        })
458        .await;
459    }
460}
461
462#[async_trait]
463impl StepLifecycle for AggregatorService {
464    fn name(&self) -> &'static str {
465        "aggregator"
466    }
467
468    async fn shutdown(&self, reason: StepShutdownReason) -> Result<(), CamelError> {
469        tracing::debug!(reason = ?reason, "Aggregator shutdown via StepLifecycle");
470
471        // Cancel the sweep token so the background task's `select!` cancel
472        // branch fires and the task exits.
473        self.sweep_cancel
474            .lock()
475            .unwrap_or_else(|e| e.into_inner())
476            .cancel();
477
478        // Abort any running sweep handle (defense-in-depth alongside the
479        // token cancel above).
480        if let Some(handle) = self
481            .sweep_handle
482            .lock()
483            .unwrap_or_else(|e| e.into_inner())
484            .take()
485        {
486            handle.abort();
487        }
488
489        self.shutdown_inner().await;
490        Ok(())
491    }
492
493    /// Resets the sweep for a fresh lifecycle: replaces the cancellation token
494    /// with a new one and aborts any existing sweep handle so the next
495    /// `poll_ready` respawns the sweep bound to the new token.
496    async fn start(&self) -> Result<(), CamelError> {
497        *self.sweep_cancel.lock().unwrap_or_else(|e| e.into_inner()) = CancellationToken::new();
498
499        if let Some(handle) = self
500            .sweep_handle
501            .lock()
502            .unwrap_or_else(|e| e.into_inner())
503            .take()
504        {
505            handle.abort();
506        }
507
508        Ok(())
509    }
510}
511
512pub fn has_timeout_condition(mode: &CompletionMode) -> bool {
513    match mode {
514        CompletionMode::Single(CompletionCondition::Timeout(_)) => true,
515        CompletionMode::Any(conditions) => conditions
516            .iter()
517            .any(|c| matches!(c, CompletionCondition::Timeout(_))),
518        _ => false,
519    }
520}
521
522impl Service<Exchange> for AggregatorService {
523    type Response = Exchange;
524    type Error = CamelError;
525    type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
526
527    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), CamelError>> {
528        // R3-C1: lazily spawn the maintenance sweep on the first readiness
529        // poll. A tokio runtime is guaranteed here (the runtime driving the
530        // service), unlike at construction. Single-spawn via the lock +
531        // is_none check. The sweep exists when EITHER release mechanism is
532        // configured: `bucket_ttl` drives eviction, `queue_metrics` drives
533        // queue-depth sampling — a size-only aggregator (bucket_ttl = None)
534        // still samples (T3.3 review F2); eviction itself stays gated on
535        // the TTL.
536        let ttl = self.config.bucket_ttl;
537        if ttl.is_none() && self.queue_metrics.is_none() {
538            return Poll::Ready(Ok(()));
539        }
540        let mut g = self.sweep_handle.lock().unwrap_or_else(|e| e.into_inner());
541        if g.is_none() {
542            let interval = match ttl {
543                Some(ttl) => std::cmp::max(ttl / 2, Duration::from_millis(50)),
544                None => QUEUE_DEPTH_SAMPLE_INTERVAL,
545            };
546            let buckets = Arc::clone(&self.buckets);
547            let cancel = self
548                .sweep_cancel
549                .lock()
550                .unwrap_or_else(|e| e.into_inner())
551                .clone();
552            let queue_metrics = self.queue_metrics.clone();
553            *g = Some(tokio::spawn(async move {
554                loop {
555                    tokio::select! {
556                        _ = cancel.cancelled() => break,
557                        _ = tokio::time::sleep(interval) => {
558                            let mut guard =
559                                buckets.lock().unwrap_or_else(|e| e.into_inner());
560                            if let Some(ttl) = ttl {
561                                guard.retain(|_, b| !b.is_expired(ttl));
562                            }
563                            // Maintenance-pass sampling: publish the
564                            // buffered group count after eviction.
565                            if let Some((metrics, label)) = queue_metrics.as_ref() {
566                                metrics.set_queue_depth(label, guard.len());
567                            }
568                        }
569                    }
570                }
571            }));
572        }
573        Poll::Ready(Ok(()))
574    }
575
576    fn call(&mut self, exchange: Exchange) -> Self::Future {
577        let svc = self.clone();
578        Box::pin(async move {
579            // claimfamily (rc-qbigm): pipeline-embedded submissions carry
580            // their drain-site split sibling ON the exchange — take it as
581            // the stash sidecar so a pending bucket keeps the exchange
582            // counted after the embedding pipeline's ack resolves. A sync
583            // completion re-attaches ONE of the bucket's claims to the
584            // aggregated output (its downstream continuation stays
585            // counted; the drain site takes it back if the output
586            // completes in-band); the remaining claims drop — their
587            // input exchanges were consumed into the aggregate. Every
588            // rejection path drops the submitted claim inside
589            // (rejected = released).
590            let mut exchange = exchange;
591            let claim = exchange.in_flight_claim.take();
592            let AggregationReceipt { reply, claims } = svc.submit_with_claim(exchange, claim).await;
593            match reply {
594                Ok(mut result) => {
595                    result.in_flight_claim = claims.into_iter().flatten().next();
596                    Ok(result)
597                }
598                Err(e) => Err(e),
599            }
600        })
601    }
602}
603
604impl AggregatorService {
605    /// Submit one exchange with its drainclaim sidecar (drainclaim
606    /// claim propagation) — the route loop's aggregate entry point.
607    ///
608    /// Behaviorally identical to the tower `Service::call` this is
609    /// extracted from, except the claim travels with the exchange: a
610    /// pending stash moves it into the bucket, a sync completion
611    /// returns it (with the rest of the bucket's claims) to the caller
612    /// to hold across the aggregated exchange's continuation, and every
613    /// rejection path (bad correlation key, bucket caps) drops it —
614    /// rejected means released.
615    pub async fn submit_with_claim(
616        &self,
617        exchange: Exchange,
618        claim: Option<InFlightClaim>,
619    ) -> AggregationReceipt {
620        let config = self.config.clone();
621        let buckets = Arc::clone(&self.buckets);
622        let timeout_tasks = Arc::clone(&self.timeout_tasks);
623        let timeout_handles = Arc::clone(&self.timeout_handles);
624        let late_tx = self.late_tx.clone();
625        let compiled = self.compiled.clone();
626        let cached_key = Arc::clone(&self.cached_key);
627        #[cfg(test)]
628        let key_serializations = Arc::clone(&self.key_serializations);
629
630        let inner = async move {
631            let key_value = extract_correlation_key(&exchange, &compiled.correlation).await?;
632
633            // Constant-key fast path: STRING keys only are memoized — one
634            // string equality check replaces per-fragment serde, and string
635            // equality exactly tracks its `serde_json::to_string` output.
636            // Every other shape serializes per fragment exactly as before:
637            // `Value` equality can diverge from serialization (float
638            // `0.0` and `-0.0` compare equal but serialize as "0.0" and
639            // "-0.0"; object/array `Value` equality is key-order-insensitive
640            // while output is not), so memoizing them could merge buckets
641            // that serde keeps distinct. Bool/Null serialize to a constant,
642            // so their per-fragment serde cost is trivial.
643            let key_is_memoizable = matches!(key_value, serde_json::Value::String(_));
644            let key_str = if key_is_memoizable {
645                let mut memo = cached_key.lock().unwrap_or_else(|e| e.into_inner());
646                if let Some((v, s)) = memo.as_ref()
647                    && *v == key_value
648                {
649                    s.clone()
650                } else {
651                    #[cfg(test)]
652                    key_serializations.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
653                    let s = serde_json::to_string(&key_value)
654                        .map_err(|e| CamelError::ProcessorError(e.to_string()))?;
655                    *memo = Some((key_value.clone(), s.clone()));
656                    s
657                }
658            } else {
659                #[cfg(test)]
660                key_serializations.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
661                serde_json::to_string(&key_value)
662                    .map_err(|e| CamelError::ProcessorError(e.to_string()))?
663            };
664
665            // Pre-evaluate the compiled completion predicate (if any) BEFORE
666            // taking the buckets lock — predicate evaluation is async and
667            // cannot run under the !Send buckets MutexGuard. The predicate was
668            // compiled at construction, so this no longer touches the language
669            // registry.
670            let predicate_satisfied =
671                evaluate_completion_predicate(&compiled.completion_predicates, &exchange).await?;
672
673            let completed_bucket = {
674                let mut guard = buckets.lock().unwrap_or_else(|e| e.into_inner());
675
676                if let Some(ttl) = config.bucket_ttl {
677                    guard.retain(|_, bucket| !bucket.is_expired(ttl));
678                }
679
680                if let Some(max) = config.max_buckets
681                    && !guard.contains_key(&key_str)
682                    && guard.len() >= max
683                {
684                    tracing::warn!(
685                        max_buckets = max,
686                        correlation_key = %key_str,
687                        "Aggregator reached max buckets limit, rejecting new correlation key"
688                    );
689                    return Err(CamelError::ProcessorError(format!(
690                        "Aggregator reached maximum {} buckets",
691                        max
692                    )));
693                }
694
695                // F6-2 (audit 2026-08-31): per-bucket accumulation bound. A
696                // single hot correlation key must not buffer unboundedly while
697                // waiting for predicate/timeout completion.
698                if let Some(max_size) = config.max_bucket_size
699                    && let Some(existing) = guard.get(&key_str)
700                    && existing.exchanges.len() >= max_size
701                {
702                    tracing::warn!(
703                        max_bucket_size = max_size,
704                        correlation_key = %key_str,
705                        "Aggregator reached per-bucket size limit, rejecting exchange"
706                    );
707                    return Err(CamelError::ProcessorError(format!(
708                        "Aggregator bucket reached maximum {max_size} exchanges"
709                    )));
710                }
711
712                let bucket = match guard.get_mut(&key_str) {
713                    Some(b) => b,
714                    None => guard.entry(key_str.clone()).or_insert_with(Bucket::new),
715                };
716                bucket.push(exchange, claim);
717
718                let (is_complete, reason) = check_sync_completion(
719                    &config.completion,
720                    &bucket.exchanges,
721                    predicate_satisfied,
722                );
723
724                let bucket_parts = if is_complete {
725                    guard.remove(&key_str).map(Bucket::into_parts)
726                } else {
727                    None
728                };
729                (bucket_parts, reason)
730            };
731
732            if completed_bucket.0.is_none() && has_timeout_condition(&config.completion) {
733                let timeout_dur = extract_timeout_duration(&config.completion);
734                if let Some(timeout) = timeout_dur {
735                    // R3-M3: bound the number of concurrently-live per-bucket
736                    // timeout tasks. When the cap is reached, skip the dedicated
737                    // spawn — the bucket relies on bucket_ttl eviction (graceful
738                    // degradation). max_buckets already caps total buckets, so
739                    // memory stays bounded regardless.
740                    let live_count = timeout_handles
741                        .lock()
742                        .unwrap_or_else(|e| e.into_inner())
743                        .len();
744                    if live_count >= config.max_timeout_tasks {
745                        tracing::warn!(
746                            live_timeout_tasks = live_count,
747                            max_timeout_tasks = config.max_timeout_tasks,
748                            correlation_key = %key_str,
749                            "Aggregator timeout-task cap reached; bucket will rely on \
750                             bucket_ttl eviction instead of a dedicated timeout task"
751                        );
752                    } else {
753                        // Cancel old token for this key (if any).
754                        {
755                            let tt_guard = timeout_tasks.lock().unwrap_or_else(|e| e.into_inner());
756                            if let Some(existing) = tt_guard.get(&key_str) {
757                                existing.cancel();
758                            }
759                        }
760                        // Remove old handle if present.
761                        {
762                            let mut hh = timeout_handles.lock().unwrap_or_else(|e| e.into_inner());
763                            if let Some(old) = hh.remove(&key_str) {
764                                old.abort();
765                            }
766                        }
767                        let cancel = CancellationToken::new();
768                        timeout_tasks
769                            .lock()
770                            .unwrap_or_else(|e| e.into_inner())
771                            .insert(key_str.clone(), cancel.clone());
772                        let handle = spawn_timeout_task(
773                            key_str.clone(),
774                            timeout,
775                            cancel,
776                            buckets.clone(),
777                            timeout_tasks.clone(),
778                            timeout_handles.clone(),
779                            late_tx,
780                            config.strategy.clone(),
781                            config.discard_on_timeout,
782                        );
783                        timeout_handles
784                            .lock()
785                            .unwrap_or_else(|e| e.into_inner())
786                            .insert(key_str.clone(), handle);
787                    }
788                }
789            }
790
791            if let Some((exchanges, claims)) = completed_bucket.0 {
792                cancel_timeout_task_with_handle(&key_str, &timeout_tasks, &timeout_handles);
793                let reason = completed_bucket.1;
794                let size = exchanges.len();
795                let mut result = aggregate(exchanges, &config.strategy)?;
796                result.set_property(CAMEL_AGGREGATED_SIZE, serde_json::json!(size as u64));
797                result.set_property(CAMEL_AGGREGATED_KEY, key_value);
798                result.set_property(
799                    CAMEL_AGGREGATED_COMPLETION_REASON,
800                    serde_json::json!(reason.as_str()),
801                );
802                Ok((result, claims))
803            } else {
804                let mut pending = Exchange::new(Message {
805                    headers: Default::default(),
806                    body: Body::Empty,
807                });
808                pending.set_property(CAMEL_AGGREGATOR_PENDING, serde_json::json!(true));
809                // Claims stay stashed in the bucket.
810                Ok((pending, Vec::new()))
811            }
812        }
813        .await;
814
815        match inner {
816            Ok((exchange, claims)) => AggregationReceipt {
817                reply: Ok(exchange),
818                claims,
819            },
820            // The submitted claim was dropped inside the body — rejected
821            // means released, so nothing to hand back.
822            Err(e) => AggregationReceipt {
823                reply: Err(e),
824                claims: Vec::new(),
825            },
826        }
827    }
828}
829
830/// Snapshot the registry once. Construction resolves every language handle
831/// under a single lock and drops the guard immediately; compilation is
832/// synchronous, so no guard ever spans an await.
833fn snapshot_languages(registry: &SharedLanguageRegistry) -> HashMap<String, Arc<dyn Language>> {
834    registry.lock().unwrap_or_else(|e| e.into_inner()).clone()
835}
836
837/// Compile the correlation strategy once at construction.
838fn compile_correlation(
839    strategy: &CorrelationStrategy,
840    languages: &HashMap<String, Arc<dyn Language>>,
841) -> Result<CompiledCorrelation, CamelError> {
842    match strategy {
843        CorrelationStrategy::HeaderName(h) => Ok(CompiledCorrelation::HeaderName(h.clone())),
844        CorrelationStrategy::Expression { expr, language } => {
845            let lang = languages.get(language).ok_or_else(|| {
846                CamelError::ProcessorError(format!(
847                    "Aggregator: language '{}' not found in registry",
848                    language
849                ))
850            })?;
851            let expression = lang
852                .create_expression(expr)
853                .map_err(|e| CamelError::ProcessorError(e.to_string()))?;
854            Ok(CompiledCorrelation::Expression(Arc::from(expression)))
855        }
856        CorrelationStrategy::Fn(f) => Ok(CompiledCorrelation::Fn(Arc::clone(f))),
857        // Future correlation strategies are unsupported: surface the inert
858        // variant so `try_new` can fail closed with one message.
859        _ => Ok(CompiledCorrelation::Unsupported),
860    }
861}
862
863/// Compile every `PredicateExpr` completion condition once, preserving config
864/// order. `Single`/`Any` both yield their predicates in order; Size/Predicate/
865/// Timeout conditions have no compiled predicate and are evaluated by the
866/// synchronous path from the original config.
867fn compile_completion_predicates(
868    mode: &CompletionMode,
869    languages: &HashMap<String, Arc<dyn Language>>,
870) -> Result<Arc<[Arc<dyn Predicate>]>, CamelError> {
871    let conditions: &[CompletionCondition] = match mode {
872        CompletionMode::Single(cond) => std::slice::from_ref(cond),
873        CompletionMode::Any(conditions) => conditions.as_slice(),
874        // Future completion modes have no synchronous/predicate completion.
875        _ => &[],
876    };
877    let mut predicates: Vec<Arc<dyn Predicate>> = Vec::new();
878    for cond in conditions {
879        if let CompletionCondition::PredicateExpr { expr, language } = cond {
880            let lang = languages.get(language).ok_or_else(|| {
881                CamelError::ProcessorError(format!(
882                    "Aggregator: language '{}' not found in registry",
883                    language
884                ))
885            })?;
886            // Predicate grammar, not template mode: completion conditions are
887            // strict booleans. A non-bool result is a `LanguageError`
888            // (type mismatch) surfaced as `ProcessorError` at evaluation time.
889            let predicate = lang
890                .create_predicate(expr)
891                .map_err(|e| CamelError::ProcessorError(e.to_string()))?;
892            predicates.push(Arc::from(predicate));
893        }
894    }
895    Ok(Arc::from(predicates))
896}
897
898async fn extract_correlation_key(
899    exchange: &Exchange,
900    strategy: &CompiledCorrelation,
901) -> Result<serde_json::Value, CamelError> {
902    match strategy {
903        CompiledCorrelation::HeaderName(h) => {
904            exchange.input.headers.get(h).cloned().ok_or_else(|| {
905                CamelError::ProcessorError(format!(
906                    "Aggregator: missing correlation key header '{}'",
907                    h
908                ))
909            })
910        }
911        CompiledCorrelation::Expression(expression) => {
912            let value = expression
913                .evaluate(exchange)
914                .await
915                .map_err(|e| CamelError::ProcessorError(e.to_string()))?;
916            if value.is_null() {
917                return Err(CamelError::ProcessorError(
918                    "Aggregator: correlation expression evaluated to null".to_string(),
919                ));
920            }
921            Ok(value)
922        }
923        CompiledCorrelation::Fn(f) => f(exchange).map(serde_json::Value::String).ok_or_else(|| {
924            CamelError::ProcessorError("Aggregator: correlation function returned None".to_string())
925        }),
926        // `try_new` rejects unsupported strategies; this arm is defensive only.
927        CompiledCorrelation::Unsupported => Err(CamelError::ProcessorError(
928            "Aggregator: unsupported correlation strategy".to_string(),
929        )),
930    }
931}
932
933/// Pre-evaluate the compiled `PredicateExpr` conditions against the incoming
934/// exchange, OR-combining (matches `CompletionMode::Any` semantics). MUST be
935/// called BEFORE the `buckets` lock — predicate evaluation is async and cannot
936/// run under the `!Send` `buckets` MutexGuard. Expressions are compiled at
937/// construction, so no registry lookup happens here.
938async fn evaluate_completion_predicate(
939    predicates: &[Arc<dyn Predicate>],
940    incoming: &Exchange,
941) -> Result<bool, CamelError> {
942    let mut satisfied = false;
943    for predicate in predicates {
944        let matched = predicate
945            .matches(incoming)
946            .await
947            .map_err(|e| CamelError::ProcessorError(e.to_string()))?;
948        if matched {
949            satisfied = true;
950        }
951    }
952    Ok(satisfied)
953}
954
955fn check_sync_completion(
956    mode: &CompletionMode,
957    exchanges: &[Exchange],
958    predicate_satisfied: bool,
959) -> (bool, CompletionReason) {
960    match mode {
961        CompletionMode::Single(cond) => check_single(cond, exchanges, predicate_satisfied),
962        CompletionMode::Any(conditions) => {
963            for cond in conditions {
964                if let CompletionCondition::Timeout(_) = cond {
965                    continue;
966                }
967                let (done, reason) = check_single(cond, exchanges, predicate_satisfied);
968                if done {
969                    return (true, reason);
970                }
971            }
972            (false, CompletionReason::Size)
973        }
974        // Future completion modes are not synchronously complete.
975        _ => (false, CompletionReason::Size),
976    }
977}
978
979fn check_single(
980    cond: &CompletionCondition,
981    exchanges: &[Exchange],
982    predicate_satisfied: bool,
983) -> (bool, CompletionReason) {
984    match cond {
985        CompletionCondition::Size(n) => (exchanges.len() >= *n, CompletionReason::Size),
986        CompletionCondition::Predicate(pred) => (pred(exchanges), CompletionReason::Predicate),
987        CompletionCondition::PredicateExpr { .. } => {
988            (predicate_satisfied, CompletionReason::Predicate)
989        }
990        CompletionCondition::Timeout(_) => (false, CompletionReason::Timeout),
991        // Future condition types cannot be evaluated synchronously.
992        _ => (false, CompletionReason::Size),
993    }
994}
995
996fn extract_timeout_duration(mode: &CompletionMode) -> Option<Duration> {
997    match mode {
998        CompletionMode::Single(CompletionCondition::Timeout(d)) => Some(*d),
999        CompletionMode::Any(conditions) => conditions.iter().find_map(|c| {
1000            if let CompletionCondition::Timeout(d) = c {
1001                Some(*d)
1002            } else {
1003                None
1004            }
1005        }),
1006        _ => None,
1007    }
1008}
1009
1010fn cancel_timeout_task(key: &str, timeout_tasks: &Arc<Mutex<HashMap<String, CancellationToken>>>) {
1011    let mut guard = timeout_tasks.lock().unwrap_or_else(|e| e.into_inner());
1012    if let Some(token) = guard.remove(key) {
1013        token.cancel();
1014    }
1015}
1016
1017/// Also removes the stored JoinHandle for a cancelled/completed timeout task.
1018fn cancel_timeout_task_with_handle(
1019    key: &str,
1020    timeout_tasks: &Arc<Mutex<HashMap<String, CancellationToken>>>,
1021    timeout_handles: &Arc<Mutex<HashMap<String, JoinHandle<()>>>>,
1022) {
1023    cancel_timeout_task(key, timeout_tasks);
1024    let mut guard = timeout_handles.lock().unwrap_or_else(|e| e.into_inner());
1025    guard.remove(key);
1026}
1027
1028#[allow(clippy::too_many_arguments)]
1029fn spawn_timeout_task(
1030    key: String,
1031    timeout: Duration,
1032    cancel: CancellationToken,
1033    buckets: Arc<Mutex<HashMap<String, Bucket>>>,
1034    timeout_tasks: Arc<Mutex<HashMap<String, CancellationToken>>>,
1035    timeout_handles: Arc<Mutex<HashMap<String, JoinHandle<()>>>>,
1036    late_tx: mpsc::Sender<AggregateEmission>,
1037    strategy: AggregationStrategy,
1038    discard: bool,
1039) -> JoinHandle<()> {
1040    let cancel_clone = cancel.clone();
1041    tokio::spawn(async move {
1042        tokio::select! {
1043            _ = tokio::time::sleep(timeout) => {
1044                let should_proceed = {
1045                    let mut tt_guard = timeout_tasks.lock().unwrap_or_else(|e| e.into_inner());
1046                    if cancel_clone.is_cancelled() {
1047                        false
1048                    } else {
1049                        tt_guard.remove(&key);
1050                        true
1051                    }
1052                };
1053                if !should_proceed {
1054                    return;
1055                }
1056                // Clean up our own JoinHandle from the map on natural completion.
1057                // Without this, the handle entry leaks until route shutdown.
1058                {
1059                    let mut hh = timeout_handles.lock().unwrap_or_else(|e| e.into_inner());
1060                    hh.remove(&key);
1061                }
1062                let bucket_parts = {
1063                    let mut guard = buckets.lock().unwrap_or_else(|e| e.into_inner());
1064                    guard.remove(&key).map(Bucket::into_parts)
1065                };
1066                if let Some((exchanges, claims)) = bucket_parts
1067                    && !discard
1068                {
1069                    match aggregate(exchanges, &strategy) {
1070                        Ok(mut result) => {
1071                            result.set_property(
1072                                CAMEL_AGGREGATED_COMPLETION_REASON,
1073                                serde_json::json!(CompletionReason::Timeout.as_str()),
1074                            );
1075                            if late_tx
1076                                .try_send(AggregateEmission {
1077                                    exchange: result,
1078                                    claims,
1079                                })
1080                                .is_err()
1081                            {
1082                                tracing::warn!(
1083                                    key = %key,
1084                                    "aggregator timeout emit dropped: late channel full"
1085                                );
1086                            }
1087                        }
1088                        Err(e) => {
1089                            // log-policy: handler-owned
1090                            tracing::warn!(
1091                                key = %key,
1092                                error = %e,
1093                                "aggregation failed in timeout task"
1094                            );
1095                        }
1096                    }
1097                }
1098            }
1099            _ = cancel_clone.cancelled() => {}
1100        }
1101    })
1102}
1103
1104fn aggregate(
1105    exchanges: Vec<Exchange>,
1106    strategy: &AggregationStrategy,
1107) -> Result<Exchange, CamelError> {
1108    match strategy {
1109        AggregationStrategy::CollectAll => {
1110            let bodies: Vec<serde_json::Value> = exchanges
1111                .into_iter()
1112                .map(|e| match e.input.body {
1113                    Body::Json(v) => v,
1114                    Body::Text(s) => serde_json::Value::String(s),
1115                    Body::Xml(s) => serde_json::Value::String(s),
1116                    Body::Bytes(b) => {
1117                        serde_json::Value::String(String::from_utf8_lossy(&b).into_owned())
1118                    }
1119                    Body::Stream(s) => serde_json::json!({
1120                        "_stream": {
1121                            "origin": s.metadata.origin,
1122                            "placeholder": true,
1123                            "hint": "Materialize exchange body with .into_bytes() before aggregation if content needed"
1124                        }
1125                    }),
1126                    // Empty and future variants contribute no extractable value.
1127                    _ => serde_json::Value::Null,
1128                })
1129                .collect();
1130            Ok(Exchange::new(Message {
1131                headers: Default::default(),
1132                body: Body::Json(serde_json::Value::Array(bodies)),
1133            }))
1134        }
1135        AggregationStrategy::Custom(f) => {
1136            let mut iter = exchanges.into_iter();
1137            let first = iter.next().ok_or_else(|| {
1138                CamelError::ProcessorError("Aggregator: empty bucket".to_string())
1139            })?;
1140            Ok(iter.fold(first, |acc, next| f(acc, next)))
1141        }
1142        // Future aggregation strategies are unsupported here.
1143        _ => Err(CamelError::ProcessorError(
1144            "Aggregator: unsupported aggregation strategy".to_string(),
1145        )),
1146    }
1147}
1148
1149#[cfg(test)]
1150mod tests {
1151    use super::*;
1152    use std::collections::HashMap;
1153
1154    use camel_api::{
1155        StepLifecycle, StepShutdownReason,
1156        aggregator::{AggregationStrategy, AggregatorConfig},
1157        body::Body,
1158        exchange::Exchange,
1159        message::Message,
1160    };
1161    use tokio::sync::mpsc;
1162    use tokio_util::sync::CancellationToken;
1163    use tower::ServiceExt;
1164
1165    fn make_exchange(header: &str, value: &str, body: &str) -> Exchange {
1166        let mut msg = Message {
1167            headers: Default::default(),
1168            body: Body::Text(body.to_string()),
1169        };
1170        msg.headers
1171            .insert(header.to_string(), serde_json::json!(value));
1172        Exchange::new(msg)
1173    }
1174
1175    fn config_size(n: usize) -> AggregatorConfig {
1176        AggregatorConfig::correlate_by("orderId")
1177            .complete_when_size(n)
1178            .build()
1179            .unwrap()
1180    }
1181
1182    fn new_test_svc(config: AggregatorConfig) -> AggregatorService {
1183        let (tx, _rx) = mpsc::channel(256);
1184        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
1185        let cancel = CancellationToken::new();
1186        AggregatorService::new(config, tx, registry, cancel)
1187    }
1188
1189    /// Same as `new_test_svc` but lets the caller install a pre-populated
1190    /// language registry. Used by `CompletionCondition::PredicateExpr` tests
1191    /// where the simple language must be resolvable at construction time.
1192    fn new_test_svc_with_registry(
1193        config: AggregatorConfig,
1194        registry: SharedLanguageRegistry,
1195    ) -> AggregatorService {
1196        let (tx, _rx) = mpsc::channel(256);
1197        let cancel = CancellationToken::new();
1198        AggregatorService::new(config, tx, registry, cancel)
1199    }
1200
1201    fn registry_with_simple() -> SharedLanguageRegistry {
1202        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
1203        registry.lock().unwrap().insert(
1204            "simple".to_string(),
1205            Arc::new(camel_language_simple::SimpleLanguage::new()) as Arc<dyn Language>,
1206        );
1207        registry
1208    }
1209
1210    /// Compile a completion mode via the same internal helper `try_new` uses.
1211    fn compile_test_completion(
1212        mode: &CompletionMode,
1213        registry: &SharedLanguageRegistry,
1214    ) -> Result<Arc<[Arc<dyn Predicate>]>, CamelError> {
1215        compile_completion_predicates(mode, &snapshot_languages(registry))
1216    }
1217
1218    /// Compile a correlation strategy via the same internal helper `try_new`
1219    /// uses.
1220    fn compile_test_correlation(
1221        strategy: &CorrelationStrategy,
1222        registry: &SharedLanguageRegistry,
1223    ) -> Result<CompiledCorrelation, CamelError> {
1224        compile_correlation(strategy, &snapshot_languages(registry))
1225    }
1226
1227    #[test]
1228    fn aggregator_service_and_compiled_handles_are_send_sync() {
1229        fn assert_send_sync<T: Send + Sync>() {}
1230        assert_send_sync::<AggregatorService>();
1231        assert_send_sync::<Arc<dyn Expression>>();
1232        assert_send_sync::<Arc<dyn Predicate>>();
1233    }
1234
1235    #[tokio::test]
1236    async fn test_pending_exchange_not_yet_complete() {
1237        let mut svc = new_test_svc(config_size(3));
1238        let ex = make_exchange("orderId", "A", "first");
1239        let result = svc.ready().await.unwrap().call(ex).await.unwrap();
1240        assert!(matches!(result.input.body, Body::Empty));
1241        assert_eq!(
1242            result.property(CAMEL_AGGREGATOR_PENDING),
1243            Some(&serde_json::json!(true))
1244        );
1245    }
1246
1247    // ── claimfamily (rc-qbigm): embedded (size-only) stash claims ──
1248
1249    #[tokio::test]
1250    async fn embedded_stash_keeps_carried_claim_until_completion() {
1251        let counter = Arc::new(camel_api::InFlightGauge::new());
1252        let svc = new_test_svc(config_size(2));
1253
1254        // First exchange: pending stash — the carried claim moves into
1255        // the bucket and keeps the exchange counted after `call`
1256        // (the embedding pipeline's ack) resolves.
1257        let mut first = make_exchange("orderId", "A", "first");
1258        first.in_flight_claim = Some(InFlightClaim::attach(&counter));
1259        let pending = svc.clone().oneshot(first).await.unwrap();
1260        assert_eq!(
1261            pending.property(CAMEL_AGGREGATOR_PENDING),
1262            Some(&serde_json::json!(true)),
1263            "first exchange must be stashed"
1264        );
1265        assert!(
1266            pending.in_flight_claim.is_none(),
1267            "the pending marker carries no claim (it completes immediately)"
1268        );
1269        assert_eq!(counter.total(), 1, "stashed exchange must stay counted");
1270
1271        // Second exchange completes the bucket: the aggregated output
1272        // carries ONE claim for its downstream continuation; the other
1273        // claim dropped (that input was consumed into the aggregate).
1274        let mut second = make_exchange("orderId", "A", "second");
1275        second.in_flight_claim = Some(InFlightClaim::attach(&counter));
1276        let aggregated = svc.clone().oneshot(second).await.unwrap();
1277        assert!(
1278            aggregated.property(CAMEL_AGGREGATOR_PENDING).is_none(),
1279            "second exchange must complete the bucket"
1280        );
1281        assert!(
1282            aggregated.in_flight_claim.is_some(),
1283            "aggregated output carries one claim downstream"
1284        );
1285        assert_eq!(
1286            counter.total(),
1287            1,
1288            "consumed input's claim released; the output's stays held"
1289        );
1290        drop(aggregated);
1291        assert_eq!(
1292            counter.total(),
1293            0,
1294            "dropping the completed output releases the last claim"
1295        );
1296    }
1297
1298    #[tokio::test]
1299    async fn embedded_rejection_releases_carried_claim() {
1300        let counter = Arc::new(camel_api::InFlightGauge::new());
1301        let svc = new_test_svc(config_size(2));
1302
1303        // Missing correlation header: the submission is rejected and the
1304        // carried claim drops inside — rejected = released.
1305        let mut bad = Exchange::new(Message::new("no-header"));
1306        bad.in_flight_claim = Some(InFlightClaim::attach(&counter));
1307        let result = svc.clone().oneshot(bad).await;
1308        assert!(result.is_err(), "missing correlation key must reject");
1309        assert_eq!(counter.total(), 0, "rejected submission releases its claim");
1310    }
1311
1312    #[tokio::test]
1313    async fn test_completes_on_size() {
1314        let mut svc = new_test_svc(config_size(3));
1315        for _ in 0..2 {
1316            let ex = make_exchange("orderId", "A", "item");
1317            let r = svc.ready().await.unwrap().call(ex).await.unwrap();
1318            assert!(matches!(r.input.body, Body::Empty));
1319        }
1320        let ex = make_exchange("orderId", "A", "last");
1321        let result = svc.ready().await.unwrap().call(ex).await.unwrap();
1322        assert!(result.property(CAMEL_AGGREGATOR_PENDING).is_none());
1323        assert_eq!(
1324            result.property(CAMEL_AGGREGATED_SIZE),
1325            Some(&serde_json::json!(3u64))
1326        );
1327    }
1328
1329    #[tokio::test]
1330    async fn test_collect_all_produces_json_array() {
1331        let mut svc = new_test_svc(config_size(2));
1332        svc.ready()
1333            .await
1334            .unwrap()
1335            .call(make_exchange("orderId", "A", "alpha"))
1336            .await
1337            .unwrap();
1338        let result = svc
1339            .ready()
1340            .await
1341            .unwrap()
1342            .call(make_exchange("orderId", "A", "beta"))
1343            .await
1344            .unwrap();
1345        let Body::Json(v) = &result.input.body else {
1346            panic!("expected Body::Json")
1347        };
1348        let arr = v.as_array().unwrap();
1349        assert_eq!(arr.len(), 2);
1350        assert_eq!(arr[0], serde_json::json!("alpha"));
1351        assert_eq!(arr[1], serde_json::json!("beta"));
1352    }
1353
1354    #[tokio::test]
1355    async fn test_two_keys_independent_buckets() {
1356        // completionSize=3 so we can test that A and B accumulate independently.
1357        let mut svc = new_test_svc(config_size(3));
1358        svc.ready()
1359            .await
1360            .unwrap()
1361            .call(make_exchange("orderId", "A", "a1"))
1362            .await
1363            .unwrap();
1364        svc.ready()
1365            .await
1366            .unwrap()
1367            .call(make_exchange("orderId", "B", "b1"))
1368            .await
1369            .unwrap();
1370        svc.ready()
1371            .await
1372            .unwrap()
1373            .call(make_exchange("orderId", "A", "a2"))
1374            .await
1375            .unwrap();
1376        // A has 2 items, B has 1 item — neither complete yet
1377        let ra = svc
1378            .ready()
1379            .await
1380            .unwrap()
1381            .call(make_exchange("orderId", "A", "a3"))
1382            .await
1383            .unwrap();
1384        // A now has 3 → completes
1385        assert!(matches!(ra.input.body, Body::Json(_)));
1386        // B only has 1 → still pending
1387        let rb = svc
1388            .ready()
1389            .await
1390            .unwrap()
1391            .call(make_exchange("orderId", "B", "b_check"))
1392            .await
1393            .unwrap();
1394        assert!(matches!(rb.input.body, Body::Empty));
1395    }
1396
1397    #[tokio::test]
1398    async fn test_bucket_resets_after_completion() {
1399        let mut svc = new_test_svc(config_size(2));
1400        svc.ready()
1401            .await
1402            .unwrap()
1403            .call(make_exchange("orderId", "A", "x"))
1404            .await
1405            .unwrap();
1406        svc.ready()
1407            .await
1408            .unwrap()
1409            .call(make_exchange("orderId", "A", "x"))
1410            .await
1411            .unwrap(); // completes
1412        // New bucket starts
1413        let r = svc
1414            .ready()
1415            .await
1416            .unwrap()
1417            .call(make_exchange("orderId", "A", "new"))
1418            .await
1419            .unwrap();
1420        assert!(matches!(r.input.body, Body::Empty)); // pending again
1421    }
1422
1423    #[tokio::test]
1424    async fn test_completion_size_1_emits_immediately() {
1425        let mut svc = new_test_svc(config_size(1));
1426        let ex = make_exchange("orderId", "A", "solo");
1427        let result = svc.ready().await.unwrap().call(ex).await.unwrap();
1428        assert!(result.property(CAMEL_AGGREGATOR_PENDING).is_none());
1429    }
1430
1431    #[tokio::test]
1432    async fn test_custom_aggregation_strategy() {
1433        use camel_api::aggregator::AggregationFn;
1434        use std::sync::Arc;
1435
1436        let f: AggregationFn = Arc::new(|mut acc: Exchange, next: Exchange| {
1437            let combined = format!(
1438                "{}+{}",
1439                acc.input.body.as_text().unwrap_or(""),
1440                next.input.body.as_text().unwrap_or("")
1441            );
1442            acc.input.body = Body::Text(combined);
1443            acc
1444        });
1445        let config = AggregatorConfig::correlate_by("key")
1446            .complete_when_size(2)
1447            .strategy(AggregationStrategy::Custom(f))
1448            .build()
1449            .unwrap();
1450        let mut svc = new_test_svc(config);
1451        svc.ready()
1452            .await
1453            .unwrap()
1454            .call(make_exchange("key", "X", "hello"))
1455            .await
1456            .unwrap();
1457        let result = svc
1458            .ready()
1459            .await
1460            .unwrap()
1461            .call(make_exchange("key", "X", "world"))
1462            .await
1463            .unwrap();
1464        assert_eq!(result.input.body.as_text(), Some("hello+world"));
1465    }
1466
1467    #[tokio::test]
1468    async fn test_completion_predicate() {
1469        let config = AggregatorConfig::correlate_by("key")
1470            .complete_when(|bucket| {
1471                bucket
1472                    .iter()
1473                    .any(|e| e.input.body.as_text() == Some("DONE"))
1474            })
1475            .build()
1476            .unwrap();
1477        let mut svc = new_test_svc(config);
1478        svc.ready()
1479            .await
1480            .unwrap()
1481            .call(make_exchange("key", "K", "first"))
1482            .await
1483            .unwrap();
1484        svc.ready()
1485            .await
1486            .unwrap()
1487            .call(make_exchange("key", "K", "second"))
1488            .await
1489            .unwrap();
1490        let result = svc
1491            .ready()
1492            .await
1493            .unwrap()
1494            .call(make_exchange("key", "K", "DONE"))
1495            .await
1496            .unwrap();
1497        assert!(result.property(CAMEL_AGGREGATOR_PENDING).is_none());
1498    }
1499
1500    #[tokio::test]
1501    async fn test_missing_header_returns_error() {
1502        let mut svc = new_test_svc(config_size(2));
1503        let msg = Message {
1504            headers: Default::default(),
1505            body: Body::Text("no key".into()),
1506        };
1507        let ex = Exchange::new(msg);
1508        let result = svc.ready().await.unwrap().call(ex).await;
1509        assert!(result.is_err());
1510        assert!(matches!(
1511            result.unwrap_err(),
1512            camel_api::CamelError::ProcessorError(_)
1513        ));
1514    }
1515
1516    #[tokio::test]
1517    async fn test_cloned_service_shares_state() {
1518        let svc1 = new_test_svc(config_size(2));
1519        let mut svc2 = svc1.clone();
1520        // send first exchange via svc1
1521        svc1.clone()
1522            .ready()
1523            .await
1524            .unwrap()
1525            .call(make_exchange("orderId", "A", "from-svc1"))
1526            .await
1527            .unwrap();
1528        // send second exchange via svc2 — should complete because same Arc<Mutex>
1529        let result = svc2
1530            .ready()
1531            .await
1532            .unwrap()
1533            .call(make_exchange("orderId", "A", "from-svc2"))
1534            .await
1535            .unwrap();
1536        assert!(result.property(CAMEL_AGGREGATOR_PENDING).is_none());
1537    }
1538
1539    #[tokio::test]
1540    async fn test_camel_aggregated_key_property_set() {
1541        let mut svc = new_test_svc(config_size(1));
1542        let ex = make_exchange("orderId", "ORDER-42", "body");
1543        let result = svc.ready().await.unwrap().call(ex).await.unwrap();
1544        assert_eq!(
1545            result.property(CAMEL_AGGREGATED_KEY),
1546            Some(&serde_json::json!("ORDER-42"))
1547        );
1548    }
1549
1550    #[tokio::test]
1551    async fn test_aggregator_enforces_max_buckets() {
1552        let config = AggregatorConfig::correlate_by("orderId")
1553            .complete_when_size(2)
1554            .max_buckets(3)
1555            .build()
1556            .unwrap();
1557
1558        let mut svc = new_test_svc(config);
1559
1560        // Create 3 different correlation keys (fills limit)
1561        for i in 0..3 {
1562            let ex = make_exchange("orderId", &format!("key-{}", i), "body");
1563            let _ = svc.ready().await.unwrap().call(ex).await.unwrap();
1564        }
1565
1566        // 4th key should be rejected
1567        let ex = make_exchange("orderId", "key-4", "body");
1568        let result = svc.ready().await.unwrap().call(ex).await;
1569
1570        assert!(result.is_err(), "Should reject when max buckets reached");
1571        let err = result.unwrap_err().to_string();
1572        assert!(
1573            err.contains("maximum"),
1574            "Error message should contain 'maximum': {}",
1575            err
1576        );
1577    }
1578
1579    #[tokio::test]
1580    async fn test_max_buckets_allows_existing_key() {
1581        let config = AggregatorConfig::correlate_by("orderId")
1582            .complete_when_size(5) // Large size so bucket doesn't complete
1583            .max_buckets(2)
1584            .build()
1585            .unwrap();
1586
1587        let mut svc = new_test_svc(config);
1588
1589        // Create 2 different correlation keys (fills limit)
1590        let ex1 = make_exchange("orderId", "key-A", "body1");
1591        let _ = svc.ready().await.unwrap().call(ex1).await.unwrap();
1592        let ex2 = make_exchange("orderId", "key-B", "body2");
1593        let _ = svc.ready().await.unwrap().call(ex2).await.unwrap();
1594
1595        // Should still allow adding to existing key
1596        let ex3 = make_exchange("orderId", "key-A", "body3");
1597        let result = svc.ready().await.unwrap().call(ex3).await;
1598        assert!(
1599            result.is_ok(),
1600            "Should allow adding to existing bucket even at max limit"
1601        );
1602    }
1603
1604    /// Audit 2026-08-31, F6-2: one hot correlation key must not buffer
1605    /// unboundedly. With a predicate-only completion and a tiny
1606    /// max_bucket_size, the Nth+1 exchange on the same key is rejected.
1607    #[tokio::test]
1608    async fn test_aggregator_enforces_max_bucket_size() {
1609        let config = AggregatorConfig::correlate_by("orderId")
1610            // Predicate that never fires — completion would otherwise end the test.
1611            .complete_when(|_| false)
1612            .max_bucket_size(3)
1613            .build()
1614            .unwrap();
1615
1616        let mut svc = new_test_svc(config);
1617
1618        for _ in 0..3 {
1619            let ex = make_exchange("orderId", "hot-key", "body");
1620            let r = svc.ready().await.unwrap().call(ex).await;
1621            assert!(r.is_ok(), "first 3 exchanges accepted: {r:?}");
1622        }
1623
1624        let ex = make_exchange("orderId", "hot-key", "body");
1625        let result = svc.ready().await.unwrap().call(ex).await;
1626        assert!(result.is_err(), "4th exchange on hot key must be rejected");
1627        let err = result.unwrap_err().to_string();
1628        assert!(
1629            err.contains("maximum"),
1630            "error should mention the per-bucket maximum: {err}"
1631        );
1632
1633        // A DIFFERENT key is unaffected (bounded per bucket, not global).
1634        let ex = make_exchange("orderId", "other-key", "body");
1635        let result = svc.ready().await.unwrap().call(ex).await;
1636        assert!(result.is_ok(), "other keys still accepted: {result:?}");
1637    }
1638
1639    #[tokio::test]
1640    async fn test_bucket_ttl_eviction() {
1641        let config = AggregatorConfig::correlate_by("orderId")
1642            .complete_when_size(10) // Large size so bucket doesn't complete normally
1643            .bucket_ttl(Duration::from_millis(50))
1644            .build()
1645            .unwrap();
1646
1647        let mut svc = new_test_svc(config);
1648
1649        // Create a bucket
1650        let ex1 = make_exchange("orderId", "key-A", "body1");
1651        let _ = svc.ready().await.unwrap().call(ex1).await.unwrap();
1652
1653        // Wait for TTL to expire
1654        tokio::time::sleep(Duration::from_millis(100)).await;
1655
1656        // Create a new bucket - this should trigger eviction of the old one
1657        let ex2 = make_exchange("orderId", "key-B", "body2");
1658        let _ = svc.ready().await.unwrap().call(ex2).await.unwrap();
1659
1660        // The expired bucket should have been evicted, so we should be able to
1661        // add a new key-A bucket again
1662        let ex3 = make_exchange("orderId", "key-A", "body3");
1663        let result = svc.ready().await.unwrap().call(ex3).await;
1664        assert!(result.is_ok(), "Should be able to recreate evicted bucket");
1665    }
1666
1667    #[tokio::test(start_paused = true)]
1668    async fn test_timeout_completes_bucket() {
1669        let config = AggregatorConfig::correlate_by("key")
1670            .complete_on_timeout(Duration::from_millis(100))
1671            .build()
1672            .unwrap();
1673        let mut svc = new_test_svc(config);
1674        let ex = make_exchange("key", "A", "data");
1675        let result = svc.ready().await.unwrap().call(ex).await.unwrap();
1676        assert!(result.property(CAMEL_AGGREGATOR_PENDING).is_some());
1677
1678        tokio::time::sleep(Duration::from_millis(200)).await;
1679
1680        assert_eq!(
1681            svc.buckets.lock().unwrap().len(),
1682            0,
1683            "bucket should be removed after timeout"
1684        );
1685    }
1686
1687    #[tokio::test(start_paused = true)]
1688    async fn test_timeout_resets_on_new_exchange() {
1689        let config = AggregatorConfig::correlate_by("key")
1690            .complete_on_timeout(Duration::from_millis(150))
1691            .build()
1692            .unwrap();
1693        let mut svc = new_test_svc(config);
1694
1695        let ex1 = make_exchange("key", "A", "first");
1696        let _ = svc.ready().await.unwrap().call(ex1).await.unwrap();
1697
1698        tokio::time::sleep(Duration::from_millis(100)).await;
1699
1700        let ex2 = make_exchange("key", "A", "second");
1701        let _ = svc.ready().await.unwrap().call(ex2).await.unwrap();
1702
1703        tokio::time::sleep(Duration::from_millis(100)).await;
1704
1705        assert_eq!(
1706            svc.buckets.lock().unwrap().len(),
1707            1,
1708            "bucket should still exist — timeout was reset"
1709        );
1710
1711        tokio::time::sleep(Duration::from_millis(100)).await;
1712
1713        assert_eq!(
1714            svc.buckets.lock().unwrap().len(),
1715            0,
1716            "bucket should be gone after timeout fires"
1717        );
1718    }
1719
1720    #[tokio::test]
1721    async fn test_composable_size_and_timeout() {
1722        let config = AggregatorConfig::correlate_by("key")
1723            .complete_on_size_or_timeout(2, Duration::from_millis(200))
1724            .build()
1725            .unwrap();
1726        let mut svc = new_test_svc(config);
1727
1728        let ex1 = make_exchange("key", "A", "first");
1729        let _ = svc.ready().await.unwrap().call(ex1).await.unwrap();
1730        assert!(svc.buckets.lock().unwrap().contains_key("\"A\""));
1731
1732        let ex2 = make_exchange("key", "A", "second");
1733        let result = svc.ready().await.unwrap().call(ex2).await.unwrap();
1734        assert!(result.property(CAMEL_AGGREGATOR_PENDING).is_none());
1735        assert_eq!(
1736            result.property(CAMEL_AGGREGATED_COMPLETION_REASON),
1737            Some(&serde_json::json!("size"))
1738        );
1739    }
1740
1741    #[tokio::test(start_paused = true)]
1742    async fn test_discard_on_timeout() {
1743        let config = AggregatorConfig::correlate_by("key")
1744            .complete_on_timeout(Duration::from_millis(50))
1745            .discard_on_timeout(true)
1746            .build()
1747            .unwrap();
1748        let (tx, mut rx) = mpsc::channel(256);
1749        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
1750        let cancel = CancellationToken::new();
1751        let mut svc = AggregatorService::new(config, tx, registry, cancel);
1752
1753        let ex = make_exchange("key", "A", "data");
1754        let _ = svc.ready().await.unwrap().call(ex).await.unwrap();
1755
1756        tokio::time::sleep(Duration::from_millis(100)).await;
1757
1758        assert!(
1759            rx.try_recv().is_err(),
1760            "no emit expected with discard_on_timeout"
1761        );
1762        assert_eq!(svc.buckets.lock().unwrap().len(), 0);
1763        assert!(
1764            svc.timeout_tasks.lock().unwrap().is_empty(),
1765            "timeout task should be cleaned up"
1766        );
1767    }
1768
1769    #[tokio::test]
1770    async fn test_force_completion_on_stop() {
1771        let config = AggregatorConfig::correlate_by("key")
1772            .complete_when_size(10)
1773            .force_completion_on_stop(true)
1774            .build()
1775            .unwrap();
1776        let (tx, mut rx) = mpsc::channel(256);
1777        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
1778        let cancel = CancellationToken::new();
1779        let svc = AggregatorService::new(config, tx, registry, cancel);
1780
1781        let mut call_svc = svc.clone();
1782        let ex = make_exchange("key", "A", "data");
1783        let _ = call_svc.ready().await.unwrap().call(ex).await.unwrap();
1784
1785        svc.force_complete_all();
1786
1787        let result = rx.try_recv().expect("should emit on force-complete");
1788        let result = result.exchange;
1789        assert!(
1790            result.input.body.as_text().is_some() || matches!(result.input.body, Body::Json(_))
1791        );
1792        assert_eq!(
1793            result.property(CAMEL_AGGREGATED_COMPLETION_REASON),
1794            Some(&serde_json::json!("stop"))
1795        );
1796    }
1797
1798    #[tokio::test]
1799    async fn test_completion_reason_property_size() {
1800        let config = AggregatorConfig::correlate_by("key")
1801            .complete_when_size(1)
1802            .build()
1803            .unwrap();
1804        let mut svc = new_test_svc(config);
1805        let ex = make_exchange("key", "X", "body");
1806        let result = svc.ready().await.unwrap().call(ex).await.unwrap();
1807        assert_eq!(
1808            result.property(CAMEL_AGGREGATED_COMPLETION_REASON),
1809            Some(&serde_json::json!("size"))
1810        );
1811    }
1812
1813    #[tokio::test]
1814    async fn test_completion_reason_property_predicate() {
1815        let config = AggregatorConfig::correlate_by("key")
1816            .complete_when(|_| true)
1817            .build()
1818            .unwrap();
1819        let mut svc = new_test_svc(config);
1820        let ex = make_exchange("key", "X", "body");
1821        let result = svc.ready().await.unwrap().call(ex).await.unwrap();
1822        assert_eq!(
1823            result.property(CAMEL_AGGREGATED_COMPLETION_REASON),
1824            Some(&serde_json::json!("predicate"))
1825        );
1826    }
1827
1828    #[tokio::test(start_paused = true)]
1829    async fn test_size_completes_before_timeout() {
1830        let config = AggregatorConfig::correlate_by("key")
1831            .complete_on_size_or_timeout(2, Duration::from_millis(200))
1832            .build()
1833            .unwrap();
1834        let mut svc = new_test_svc(config);
1835
1836        let ex1 = make_exchange("key", "A", "first");
1837        let _ = svc.ready().await.unwrap().call(ex1).await.unwrap();
1838
1839        let ex2 = make_exchange("key", "A", "second");
1840        let result = svc.ready().await.unwrap().call(ex2).await.unwrap();
1841
1842        assert!(result.property(CAMEL_AGGREGATOR_PENDING).is_none());
1843        assert_eq!(
1844            result.property(CAMEL_AGGREGATED_COMPLETION_REASON),
1845            Some(&serde_json::json!("size"))
1846        );
1847        assert_eq!(svc.buckets.lock().unwrap().len(), 0);
1848
1849        tokio::time::sleep(Duration::from_millis(300)).await;
1850        assert_eq!(
1851            svc.buckets.lock().unwrap().len(),
1852            0,
1853            "no re-fire after timeout"
1854        );
1855    }
1856
1857    #[tokio::test(start_paused = true)]
1858    async fn test_concurrent_timeout_fire_and_new_exchange() {
1859        let config = AggregatorConfig::correlate_by("key")
1860            .complete_on_size_or_timeout(2, Duration::from_millis(100))
1861            .build()
1862            .unwrap();
1863        let (tx, mut rx) = mpsc::channel(256);
1864        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
1865        let cancel = CancellationToken::new();
1866        let mut svc = AggregatorService::new(config, tx, registry, cancel);
1867
1868        let ex = make_exchange("key", "A", "data");
1869        let _ = svc.ready().await.unwrap().call(ex).await.unwrap();
1870
1871        // Advance time past timeout — timeout task fires and removes bucket
1872        tokio::time::sleep(Duration::from_millis(150)).await;
1873
1874        // New exchange arrives after timeout — starts a fresh bucket
1875        let ex2 = make_exchange("key", "A", "data2");
1876        let result = svc.ready().await.unwrap().call(ex2).await.unwrap();
1877        assert!(
1878            result.property(CAMEL_AGGREGATOR_PENDING).is_some(),
1879            "should be pending in new bucket"
1880        );
1881
1882        // Drain late emits from timeout
1883        let mut late_count = 0;
1884        while rx.try_recv().is_ok() {
1885            late_count += 1;
1886        }
1887        assert_eq!(
1888            late_count, 1,
1889            "exactly 1 late emit from the timed-out bucket"
1890        );
1891    }
1892
1893    #[tokio::test(start_paused = true)]
1894    async fn test_late_channel_full_drops_with_warning() {
1895        let config = AggregatorConfig::correlate_by("key")
1896            .complete_on_timeout(Duration::from_millis(50))
1897            .build()
1898            .unwrap();
1899        let (tx, mut rx) = mpsc::channel(1);
1900        rx.close();
1901        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
1902        let cancel = CancellationToken::new();
1903        let mut svc = AggregatorService::new(config, tx, registry, cancel);
1904
1905        let ex = make_exchange("key", "A", "data");
1906        let _ = svc.ready().await.unwrap().call(ex).await.unwrap();
1907
1908        tokio::time::sleep(Duration::from_millis(100)).await;
1909        assert_eq!(
1910            svc.buckets.lock().unwrap().len(),
1911            0,
1912            "bucket removed despite channel closed"
1913        );
1914    }
1915
1916    // D-A3 semantic pin: exercises the `force_complete_all()` -> `late_tx.try_send`
1917    // path specifically (not the timeout-task path covered by
1918    // `test_late_channel_full_drops_with_warning` above). Pre-saturates the
1919    // single-slot `late_tx` before constructing the service so every
1920    // force-completed exchange must drop on the `try_send` failure branch.
1921    #[tokio::test]
1922    async fn test_da3_force_complete_all_drops_on_saturated_channel() {
1923        let config = AggregatorConfig::correlate_by("k")
1924            .complete_when_size(10)
1925            .force_completion_on_stop(true)
1926            .build()
1927            .unwrap();
1928        // capacity 1 — deliberately tiny so the pre-fill fully saturates the slot.
1929        let (late_tx, mut late_rx) = mpsc::channel::<AggregateEmission>(1);
1930        // Pre-saturate the 1-slot mpsc BEFORE the Sender is moved into
1931        // AggregatorService::new. The Sender is taken by value into the
1932        // service, so this `try_send` is the only chance to occupy the slot.
1933        late_tx
1934            .try_send(AggregateEmission {
1935                exchange: make_exchange("k", "99", "dummy"),
1936                claims: Vec::new(),
1937            })
1938            .expect("pre-fill succeeds");
1939
1940        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
1941        let cancel = CancellationToken::new();
1942        let mut svc = AggregatorService::new(config, late_tx, registry, cancel);
1943
1944        // Three distinct correlation keys -> three buckets, each holding one
1945        // exchange. size=10 means no bucket auto-completes.
1946        for v in ["1", "2", "3"] {
1947            let ex = make_exchange("k", v, "body");
1948            let _ = svc.ready().await.unwrap().call(ex).await.unwrap();
1949        }
1950        assert_eq!(svc.buckets.lock().unwrap().len(), 3);
1951
1952        // Action: drive the force-complete path.
1953        svc.force_complete_all();
1954
1955        // (a) the manually-sent pre-fill item is still in the channel.
1956        let pre_fill = late_rx
1957            .try_recv()
1958            .expect("pre-fill should still be in channel");
1959        assert_eq!(
1960            pre_fill.exchange.input.headers.get("k"),
1961            Some(&serde_json::json!("99"))
1962        );
1963
1964        // (b) channel drained -- no force-completed exchange got through
1965        // (all three try_send calls hit the full channel and dropped).
1966        assert!(matches!(
1967            late_rx.try_recv(),
1968            Err(mpsc::error::TryRecvError::Empty)
1969        ));
1970
1971        // (c) all three buckets were removed during force_complete_all.
1972        assert!(svc.buckets.lock().unwrap().is_empty());
1973    }
1974
1975    #[tokio::test]
1976    async fn test_aggregate_stream_bodies_creates_valid_json() {
1977        use bytes::Bytes;
1978        use camel_api::{Body, StreamBody, StreamMetadata};
1979        use futures::stream;
1980        use tokio::sync::Mutex;
1981
1982        let chunks = vec![Ok(Bytes::from("test"))];
1983        let stream_body = StreamBody {
1984            stream: Arc::new(Mutex::new(Some(Box::pin(stream::iter(chunks))))),
1985            metadata: StreamMetadata {
1986                origin: Some("file:///test.txt".to_string()),
1987                ..Default::default()
1988            },
1989        };
1990
1991        let ex1 = Exchange::new(Message {
1992            headers: Default::default(),
1993            body: Body::Stream(stream_body),
1994        });
1995
1996        let exchanges = vec![ex1];
1997        let result = aggregate(exchanges, &AggregationStrategy::CollectAll);
1998
1999        let exchange = result.expect("Expected Ok result");
2000        assert!(
2001            matches!(exchange.input.body, Body::Json(_)),
2002            "Expected Json body"
2003        );
2004
2005        if let Body::Json(value) = exchange.input.body {
2006            let json_str = serde_json::to_string(&value).unwrap();
2007            let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
2008
2009            assert!(parsed.is_array(), "Result should be an array");
2010            let arr = parsed.as_array().unwrap();
2011            assert!(arr[0].is_object(), "First element should be an object");
2012            assert!(
2013                arr[0]["_stream"].is_object(),
2014                "Should contain _stream object"
2015            );
2016            assert_eq!(arr[0]["_stream"]["origin"], "file:///test.txt");
2017            assert_eq!(
2018                arr[0]["_stream"]["placeholder"], true,
2019                "placeholder flag should be true"
2020            );
2021        }
2022    }
2023
2024    #[tokio::test]
2025    async fn test_aggregate_stream_bodies_with_none_origin() {
2026        use bytes::Bytes;
2027        use camel_api::{Body, StreamBody, StreamMetadata};
2028        use futures::stream;
2029        use tokio::sync::Mutex;
2030
2031        let chunks = vec![Ok(Bytes::from("test"))];
2032        let stream_body = StreamBody {
2033            stream: Arc::new(Mutex::new(Some(Box::pin(stream::iter(chunks))))),
2034            metadata: StreamMetadata {
2035                origin: None,
2036                ..Default::default()
2037            },
2038        };
2039
2040        let ex1 = Exchange::new(Message {
2041            headers: Default::default(),
2042            body: Body::Stream(stream_body),
2043        });
2044
2045        let exchanges = vec![ex1];
2046        let result = aggregate(exchanges, &AggregationStrategy::CollectAll);
2047
2048        let exchange = result.expect("Expected Ok result");
2049        assert!(
2050            matches!(exchange.input.body, Body::Json(_)),
2051            "Expected Json body"
2052        );
2053
2054        if let Body::Json(value) = exchange.input.body {
2055            let json_str = serde_json::to_string(&value).unwrap();
2056            let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
2057
2058            assert!(parsed.is_array(), "Result should be an array");
2059            let arr = parsed.as_array().unwrap();
2060            assert!(arr[0].is_object(), "First element should be an object");
2061            assert!(
2062                arr[0]["_stream"].is_object(),
2063                "Should contain _stream object"
2064            );
2065            assert_eq!(
2066                arr[0]["_stream"]["origin"],
2067                serde_json::Value::Null,
2068                "origin should be null when None"
2069            );
2070            assert_eq!(
2071                arr[0]["_stream"]["placeholder"], true,
2072                "placeholder flag should be true"
2073            );
2074        }
2075    }
2076
2077    #[tokio::test]
2078    async fn timeout_completion_clears_handle_from_map() {
2079        // Regression: Oracle audit found that natural timeout completion removed
2080        // the bucket but left the JoinHandle in `timeout_handles`, leaking the
2081        // entry until route shutdown. After fix, the timeout task itself cleans
2082        // its handle from the map on natural completion.
2083        let config = AggregatorConfig::correlate_by("key")
2084            .complete_on_timeout(Duration::from_millis(50))
2085            .build()
2086            .unwrap();
2087        let (tx, _rx) = mpsc::channel(256);
2088        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
2089        let cancel = CancellationToken::new();
2090        let svc = AggregatorService::new(config, tx, registry, cancel);
2091
2092        // Send an exchange to create a pending bucket with a timeout task.
2093        let mut call_svc = svc.clone();
2094        let ex = make_exchange("key", "A", "data");
2095        let _ = call_svc.ready().await.unwrap().call(ex).await.unwrap();
2096        assert!(
2097            !svc.timeout_handles.lock().unwrap().is_empty(),
2098            "handle should exist while timeout pending"
2099        );
2100
2101        // Wait real time for the 50ms timeout to fire + spawned task to complete.
2102        tokio::time::sleep(Duration::from_millis(200)).await;
2103
2104        assert!(
2105            svc.timeout_handles.lock().unwrap().is_empty(),
2106            "handle should be cleared from map after natural timeout completion (was leak)"
2107        );
2108    }
2109
2110    #[tokio::test]
2111    async fn aggregator_shutdown_via_trait_dispatch() {
2112        // RED: builds an AggregatorService, dispatches through Arc<dyn StepLifecycle>,
2113        // and asserts idempotent shutdown works.
2114        let config = AggregatorConfig::correlate_by("key")
2115            .complete_when_size(10)
2116            .build()
2117            .unwrap();
2118        let (tx, _rx) = mpsc::channel(256);
2119        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
2120        let cancel = CancellationToken::new();
2121        let svc = AggregatorService::new(config, tx, registry, cancel);
2122
2123        let step: Arc<dyn StepLifecycle> = Arc::new(svc);
2124        step.shutdown(StepShutdownReason::RouteStop)
2125            .await
2126            .expect("first shutdown should succeed");
2127        step.shutdown(StepShutdownReason::RouteStop)
2128            .await
2129            .expect("second shutdown (idempotent) should succeed");
2130    }
2131
2132    #[tokio::test(start_paused = true)]
2133    async fn test_shutdown_awaits_timeout_handles() {
2134        let config = AggregatorConfig::correlate_by("key")
2135            .complete_on_timeout(Duration::from_millis(100))
2136            .build()
2137            .unwrap();
2138        let (tx, _rx) = mpsc::channel(256);
2139        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
2140        let cancel = CancellationToken::new();
2141        let svc = AggregatorService::new(config, tx, registry, cancel);
2142
2143        // Send an exchange to create a pending bucket with a timeout task.
2144        let mut call_svc = svc.clone();
2145        let ex = make_exchange("key", "A", "data");
2146        let _ = call_svc.ready().await.unwrap().call(ex).await.unwrap();
2147
2148        // Verify timeout handle exists.
2149        assert!(
2150            !svc.timeout_handles.lock().unwrap().is_empty(),
2151            "should have a timeout handle"
2152        );
2153
2154        // Shutdown should complete within the 5s deadline (the timeout task
2155        // gets cancelled so it won't wait for the full 100ms sleep).
2156        svc.shutdown_inner().await;
2157
2158        assert!(
2159            svc.timeout_handles.lock().unwrap().is_empty(),
2160            "all handles should be cleaned up after shutdown"
2161        );
2162    }
2163
2164    // ── R3-C1 Batch 1: DoS cap + background sweep ───────────────────
2165
2166    /// R3-C1: a flood of unique correlation keys must stay bounded.
2167    /// Default `max_buckets` is 10_000; the 10_001st unique key is rejected
2168    /// with `Aggregator reached maximum N buckets` (or its updated equivalent
2169    /// after the fix). The unique-key flood does NOT OOM the process.
2170    #[tokio::test]
2171    async fn test_unique_key_flood_stays_bounded_by_default() {
2172        // Builder defaults to max_buckets = 10_000, bucket_ttl = 300s.
2173        let config = AggregatorConfig::correlate_by("orderId")
2174            .complete_when_size(1_000_000) // never completes normally
2175            .build()
2176            .unwrap();
2177        let mut svc = new_test_svc(config);
2178
2179        // Send 10_001 unique keys. The first 10_000 should be accepted
2180        // (pending in their buckets); the 10_001st MUST be rejected.
2181        for i in 0..10_000usize {
2182            let ex = make_exchange("orderId", &format!("key-{i}"), "body");
2183            let result = svc.ready().await.unwrap().call(ex).await;
2184            assert!(result.is_ok(), "key {i} should be accepted under the cap");
2185        }
2186        let ex = make_exchange("orderId", "key-10001", "body");
2187        let result = svc.ready().await.unwrap().call(ex).await;
2188        assert!(
2189            result.is_err(),
2190            "10_001st unique key must be rejected by the max_buckets cap"
2191        );
2192        let err = result.unwrap_err().to_string();
2193        assert!(
2194            err.contains("maximum") || err.contains("max"),
2195            "error should mention cap: {err}"
2196        );
2197    }
2198
2199    /// The `AggregatorService` exposes a `sweep_handle` for the background
2200    /// sweep task. When `config.bucket_ttl` is `Some`, `AggregatorService::new`
2201    /// automatically spawns the sweep task and stores the handle, so the
2202    /// caller never sees `None` for a TTL-configured service. Cancelling the
2203    /// route token (via `shutdown`) aborts the sweep.
2204    #[tokio::test]
2205    async fn test_background_sweep_spawns_on_first_poll_not_construction() {
2206        let config = AggregatorConfig::correlate_by("key")
2207            .complete_when_size(10_000)
2208            .bucket_ttl(Duration::from_millis(50))
2209            .build()
2210            .unwrap();
2211        let cancel = CancellationToken::new();
2212        let (tx, _rx) = mpsc::channel(8);
2213        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
2214        let mut svc = AggregatorService::new(config, tx, registry, cancel.clone());
2215
2216        // Construction is runtime-free: no sweep spawned yet.
2217        assert!(
2218            svc.sweep_handle
2219                .lock()
2220                .unwrap_or_else(|e| e.into_inner())
2221                .is_none(),
2222            "sweep must NOT be spawned at construction (runtime-free new)"
2223        );
2224
2225        // First readiness poll lazily spawns the sweep (a runtime is present
2226        // here). `ready()` drives `poll_ready` until Ready.
2227        let _ = svc.ready().await.unwrap();
2228        let sweep_present = svc
2229            .sweep_handle
2230            .lock()
2231            .unwrap_or_else(|e| e.into_inner())
2232            .is_some();
2233        assert!(
2234            sweep_present,
2235            "sweep handle should be Some after first poll when bucket_ttl is set"
2236        );
2237
2238        // Cancel the route token; the sweep task observes it and exits.
2239        cancel.cancel();
2240        // Give the task a moment to observe the cancel.
2241        tokio::time::sleep(Duration::from_millis(50)).await;
2242    }
2243
2244    /// Shared `MetricsCollector` double that logs every `set_queue_depth`
2245    /// call (queue label, depth). Used by the queue-depth sampling tests.
2246    struct QueueDepthRecorder(Mutex<Vec<(String, usize)>>);
2247    impl MetricsCollector for QueueDepthRecorder {
2248        fn record_exchange_duration(&self, _: &str, _: std::time::Duration) {}
2249        fn increment_errors(&self, _: &str, _: &str) {}
2250        fn increment_exchanges(&self, _: &str) {}
2251        fn set_queue_depth(&self, queue: &str, depth: usize) {
2252            self.0
2253                .lock()
2254                .unwrap_or_else(|e| e.into_inner())
2255                .push((queue.to_string(), depth));
2256        }
2257        fn record_circuit_breaker_change(&self, _: &str, _: &str, _: &str) {}
2258    }
2259
2260    /// Poll the recorder until a sample for `label` matches `pred`, or fail
2261    /// after `deadline`. Keeps the sampling tests scheduling-tolerant.
2262    async fn await_depth_sample(
2263        recorder: &QueueDepthRecorder,
2264        label: &str,
2265        pred: impl Fn(usize) -> bool,
2266    ) {
2267        let deadline = std::time::Instant::now() + Duration::from_secs(2);
2268        loop {
2269            let matched = recorder
2270                .0
2271                .lock()
2272                .unwrap_or_else(|e| e.into_inner())
2273                .iter()
2274                .any(|(q, d)| q == label && pred(*d));
2275            if matched {
2276                return;
2277            }
2278            assert!(
2279                std::time::Instant::now() < deadline,
2280                "no queue-depth sample for '{label}' matched within 2s"
2281            );
2282            tokio::time::sleep(Duration::from_millis(20)).await;
2283        }
2284    }
2285
2286    /// Queue-depth sampling (dashboard-observability T3.3): when
2287    /// `with_queue_metrics` is set, the TTL-sweep maintenance pass publishes
2288    /// the buffered group count, and the count returns to zero once the
2289    /// group completes.
2290    #[tokio::test]
2291    async fn test_sweep_reports_queue_depth() {
2292        let config = AggregatorConfig::correlate_by("orderId")
2293            .complete_when_size(3)
2294            // Short TTL keeps the sweep interval at its 50ms floor so the
2295            // test observes samples quickly; the bucket is completed well
2296            // before eviction.
2297            .bucket_ttl(Duration::from_millis(100))
2298            .build()
2299            .unwrap();
2300        let cancel = CancellationToken::new();
2301        let (tx, _rx) = mpsc::channel(8);
2302        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
2303        let recorder = Arc::new(QueueDepthRecorder(Mutex::new(Vec::new())));
2304        let mut svc = AggregatorService::new(config, tx, registry, cancel).with_queue_metrics(
2305            Arc::clone(&recorder) as Arc<dyn MetricsCollector>,
2306            "aggregator:t",
2307        );
2308
2309        // Spawn the sweep via the first readiness poll.
2310        let _ = svc.ready().await.unwrap();
2311
2312        // Partial group: 1 of 3 messages.
2313        let ex = make_exchange("orderId", "g1", "partial");
2314        let _ = svc.ready().await.unwrap().call(ex).await;
2315
2316        await_depth_sample(&recorder, "aggregator:t", |d| d > 0).await;
2317
2318        // Complete the group; the sweep must report zero again.
2319        let ex = make_exchange("orderId", "g1", "b");
2320        let _ = svc.ready().await.unwrap().call(ex).await;
2321        let ex = make_exchange("orderId", "g1", "c");
2322        let _ = svc.ready().await.unwrap().call(ex).await;
2323
2324        await_depth_sample(&recorder, "aggregator:t", |d| d == 0).await;
2325
2326        svc.shutdown(StepShutdownReason::RouteStop).await.unwrap();
2327    }
2328
2329    /// F2 (T3.3 review): a no-TTL aggregator (size-only completion,
2330    /// `bucket_ttl = None`) with `queue_metrics` set must still sample —
2331    /// the sweep used to live entirely inside the TTL branch and never ran.
2332    /// Eviction stays TTL-gated; only sampling runs.
2333    #[tokio::test]
2334    async fn test_no_ttl_aggregator_reports_queue_depth() {
2335        use camel_api::aggregator::CorrelationStrategy;
2336
2337        let config = AggregatorConfig {
2338            header_name: "orderId".into(),
2339            completion: CompletionMode::Single(CompletionCondition::Size(3)),
2340            correlation: CorrelationStrategy::HeaderName("orderId".into()),
2341            strategy: AggregationStrategy::CollectAll,
2342            max_buckets: Some(100),
2343            max_bucket_size: Some(100),
2344            bucket_ttl: None,
2345            force_completion_on_stop: false,
2346            discard_on_timeout: false,
2347            max_timeout_tasks: 64,
2348        };
2349        let cancel = CancellationToken::new();
2350        let (tx, _rx) = mpsc::channel(8);
2351        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
2352        let recorder = Arc::new(QueueDepthRecorder(Mutex::new(Vec::new())));
2353        let mut svc = AggregatorService::new(config, tx, registry, cancel).with_queue_metrics(
2354            Arc::clone(&recorder) as Arc<dyn MetricsCollector>,
2355            "aggregator:nottl",
2356        );
2357
2358        let _ = svc.ready().await.unwrap();
2359        assert!(
2360            svc.sweep_handle
2361                .lock()
2362                .unwrap_or_else(|e| e.into_inner())
2363                .is_some(),
2364            "metrics-only config (bucket_ttl = None) must still spawn the sweep"
2365        );
2366
2367        // Partial group: 1 of 3 messages — depth must publish > 0.
2368        let ex = make_exchange("orderId", "g1", "partial");
2369        let _ = svc.ready().await.unwrap().call(ex).await;
2370        await_depth_sample(&recorder, "aggregator:nottl", |d| d > 0).await;
2371
2372        // Complete the group; depth must publish 0 again.
2373        let ex = make_exchange("orderId", "g1", "b");
2374        let _ = svc.ready().await.unwrap().call(ex).await;
2375        let ex = make_exchange("orderId", "g1", "c");
2376        let _ = svc.ready().await.unwrap().call(ex).await;
2377        await_depth_sample(&recorder, "aggregator:nottl", |d| d == 0).await;
2378
2379        svc.shutdown(StepShutdownReason::RouteStop).await.unwrap();
2380    }
2381
2382    /// F3 (T3.3 review): the last-owner guard — the pipeline clones the
2383    /// service on every `poll_ready`; a transient clone dropping must NOT
2384    /// abort the shared sweep. The sweep keeps ticking (depth still
2385    /// published) until the final owner drops.
2386    #[tokio::test]
2387    async fn test_transient_clone_drop_keeps_sweep_sampling() {
2388        let config = AggregatorConfig::correlate_by("orderId")
2389            .complete_when_size(3)
2390            .bucket_ttl(Duration::from_millis(100))
2391            .build()
2392            .unwrap();
2393        let cancel = CancellationToken::new();
2394        let (tx, _rx) = mpsc::channel(8);
2395        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
2396        let recorder = Arc::new(QueueDepthRecorder(Mutex::new(Vec::new())));
2397        let mut svc = AggregatorService::new(config, tx, registry, cancel).with_queue_metrics(
2398            Arc::clone(&recorder) as Arc<dyn MetricsCollector>,
2399            "aggregator:clone",
2400        );
2401
2402        let _ = svc.ready().await.unwrap();
2403
2404        // Transient clone drops (as the pipeline does per poll_ready).
2405        drop(svc.clone());
2406        assert!(
2407            svc.sweep_handle
2408                .lock()
2409                .unwrap_or_else(|e| e.into_inner())
2410                .is_some(),
2411            "transient clone drop must not abort the shared sweep"
2412        );
2413
2414        // The sweep still ticks: a partial group produces depth samples.
2415        let ex = make_exchange("orderId", "g1", "partial");
2416        let _ = svc.ready().await.unwrap().call(ex).await;
2417        await_depth_sample(&recorder, "aggregator:clone", |d| d > 0).await;
2418
2419        svc.shutdown(StepShutdownReason::RouteStop).await.unwrap();
2420    }
2421
2422    // ── R3-M3: bounded timeout-task spawn ─────────────────────────────
2423
2424    #[tokio::test]
2425    async fn test_aggregator_timeout_task_cap_no_panic_under_flood() {
2426        // R3-M3: a flood of unique keys with a tiny max_timeout_tasks must not
2427        // spawn unbounded tasks, panic, or deadlock. Each call returns Ok(pending).
2428        use camel_api::aggregator::CorrelationStrategy;
2429
2430        let config = AggregatorConfig {
2431            header_name: "k".into(),
2432            completion: CompletionMode::Any(vec![
2433                CompletionCondition::Size(999),
2434                CompletionCondition::Timeout(Duration::from_secs(30)),
2435            ]),
2436            correlation: CorrelationStrategy::HeaderName("k".into()),
2437            strategy: AggregationStrategy::CollectAll,
2438            max_buckets: Some(50),
2439            max_bucket_size: Some(50),
2440            bucket_ttl: Some(Duration::from_secs(30)),
2441            force_completion_on_stop: false,
2442            discard_on_timeout: false,
2443            max_timeout_tasks: 2,
2444        };
2445        let (late_tx, mut late_rx) = mpsc::channel(64);
2446        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
2447        let cancel = CancellationToken::new();
2448        let svc = AggregatorService::new(config, late_tx, registry, cancel);
2449
2450        // Drive 20 unique-key exchanges — far exceeding max_timeout_tasks=2.
2451        for i in 0..20u64 {
2452            let mut ex = Exchange::new(Message {
2453                headers: HashMap::from([("k".to_string(), serde_json::json!(i))]),
2454                body: Body::Text(i.to_string()),
2455            });
2456            ex.input
2457                .headers
2458                .insert("k".to_string(), serde_json::json!(i));
2459            let outcome = tokio::time::timeout(Duration::from_secs(2), async {
2460                let mut s = svc.clone();
2461                use tower::ServiceExt;
2462                s.ready().await.unwrap().call(ex).await
2463            })
2464            .await;
2465            assert!(outcome.is_ok(), "call {} hung/panicked under task cap", i);
2466            // Each returns Ok(pending) since Size(999) is never reached.
2467            let res = outcome.unwrap().unwrap();
2468            assert_eq!(
2469                res.properties
2470                    .get(CAMEL_AGGREGATOR_PENDING)
2471                    .and_then(|v| v.as_bool()),
2472                Some(true),
2473                "exchange {} should be pending",
2474                i
2475            );
2476        }
2477        // Drain any late emissions to avoid blocking the channel.
2478        let _ = late_rx.try_recv();
2479    }
2480
2481    /// bd rc-iioeq: consumer-exit release is decided PER BUCKET, not from
2482    /// config-global `has_timeout()`. With the timeout-task cap reached, a
2483    /// timeout-configured bucket stays unarmed; after the consumer exits
2484    /// it can never complete on its own (no task owns it, the bucket_ttl
2485    /// sweep only runs inside the next `call`, which never arrives).
2486    /// `release_unarmed_buckets` must discard exactly those buckets while
2487    /// leaving armed ones to their timeout tasks.
2488    #[tokio::test]
2489    async fn test_release_unarmed_buckets_discards_cap_exceeded_keeps_armed() {
2490        let config = AggregatorConfig::correlate_by("k")
2491            .complete_on_timeout(Duration::from_millis(400))
2492            .max_timeout_tasks(1)
2493            .build()
2494            .unwrap();
2495        let (late_tx, mut late_rx) = mpsc::channel(8);
2496        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
2497        let cancel = CancellationToken::new();
2498        let svc = AggregatorService::new(config, late_tx, registry, cancel);
2499
2500        // Key "a" arms the only timeout slot; key "b" hits the cap and
2501        // stays unarmed.
2502        let a = make_exchange("k", "a", "body-a");
2503        let mut sa = svc.clone();
2504        let _ = sa.ready().await.unwrap().call(a).await.unwrap();
2505        let b = make_exchange("k", "b", "body-b");
2506        let mut sb = svc.clone();
2507        let _ = sb.ready().await.unwrap().call(b).await.unwrap();
2508
2509        {
2510            let armed = svc.timeout_tasks.lock().unwrap_or_else(|e| e.into_inner());
2511            assert_eq!(armed.len(), 1, "cap=1 must arm exactly one timeout task");
2512            assert!(
2513                armed.contains_key("\"a\""),
2514                "first key must hold the armed slot, got {armed:?}"
2515            );
2516        }
2517
2518        // Consumer-exit release: unarmed bucket discarded, armed kept.
2519        svc.release_unarmed_buckets();
2520        {
2521            let buckets = svc.buckets.lock().unwrap_or_else(|e| e.into_inner());
2522            assert!(
2523                buckets.contains_key("\"a\""),
2524                "armed bucket must survive the release"
2525            );
2526            assert!(
2527                !buckets.contains_key("\"b\""),
2528                "cap-exceeded (unarmed) bucket must be released, not orphaned"
2529            );
2530        }
2531
2532        // The armed bucket's timeout still owns completion: it emits
2533        // reason=timeout through the late channel.
2534        let emitted = tokio::time::timeout(Duration::from_secs(2), late_rx.recv())
2535            .await
2536            .expect("armed bucket must emit on its timeout")
2537            .expect("late channel must stay open");
2538        assert_eq!(
2539            emitted
2540                .exchange
2541                .properties
2542                .get(CAMEL_AGGREGATED_COMPLETION_REASON),
2543            Some(&serde_json::json!("timeout"))
2544        );
2545
2546        // The released bucket must never emit: both keys were sent within
2547        // milliseconds of each other, so 600 ms after "a"'s emission is
2548        // past "b"'s would-be deadline (400 ms) with margin.
2549        assert!(
2550            tokio::time::timeout(Duration::from_millis(600), late_rx.recv())
2551                .await
2552                .is_err(),
2553            "released unarmed bucket must not emit"
2554        );
2555
2556        svc.shutdown(StepShutdownReason::RouteStop).await.unwrap();
2557    }
2558
2559    #[tokio::test]
2560    async fn evaluate_completion_predicate_or_combines_any() {
2561        use camel_api::aggregator::{CompletionCondition, CompletionMode};
2562
2563        let registry = registry_with_simple();
2564        let incoming = make_exchange("k", "X", "hello");
2565
2566        // Any with two PredicateExpr conditions; second matches body == "hello".
2567        let mode = CompletionMode::Any(vec![
2568            CompletionCondition::PredicateExpr {
2569                expr: "${body} == 'NOPE'".to_string(),
2570                language: "simple".to_string(),
2571            },
2572            CompletionCondition::PredicateExpr {
2573                expr: "${body} == 'hello'".to_string(),
2574                language: "simple".to_string(),
2575            },
2576        ]);
2577
2578        let compiled = compile_test_completion(&mode, &registry).expect("compile must succeed");
2579        let satisfied = evaluate_completion_predicate(&compiled, &incoming)
2580            .await
2581            .expect("eval must succeed");
2582        assert!(satisfied, "second predicate matches → OR true");
2583    }
2584
2585    #[tokio::test]
2586    async fn evaluate_completion_predicate_size_only_returns_false() {
2587        use camel_api::aggregator::{CompletionCondition, CompletionMode};
2588
2589        // Size-only completion has no PredicateExpr, so compilation needs no
2590        // language and evaluation returns false without touching a predicate.
2591        let mode = CompletionMode::Single(CompletionCondition::Size(3));
2592        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
2593        let incoming = make_exchange("k", "X", "hello");
2594        let compiled = compile_test_completion(&mode, &registry).expect("compile must succeed");
2595        let result = evaluate_completion_predicate(&compiled, &incoming).await;
2596        assert!(result.is_ok(), "fast path must not error: {:?}", result);
2597        assert!(!result.unwrap(), "no predicate → not satisfied");
2598    }
2599
2600    #[tokio::test]
2601    async fn compile_completion_unregistered_language_errors() {
2602        use camel_api::aggregator::{CompletionCondition, CompletionMode};
2603
2604        let mode = CompletionMode::Single(CompletionCondition::PredicateExpr {
2605            expr: "${body} == 'DONE'".to_string(),
2606            language: "nonexistent-lang".to_string(),
2607        });
2608        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
2609        let err = compile_test_completion(&mode, &registry)
2610            .err()
2611            .expect("unregistered language must fail at construction");
2612        assert!(
2613            matches!(&err, CamelError::ProcessorError(msg) if msg.contains("not found in registry")),
2614            "error must name the missing language: {err:?}"
2615        );
2616    }
2617
2618    #[tokio::test]
2619    async fn evaluate_completion_predicate_all_miss_returns_false() {
2620        use camel_api::aggregator::{CompletionCondition, CompletionMode};
2621
2622        let registry = registry_with_simple();
2623        let mode = CompletionMode::Single(CompletionCondition::PredicateExpr {
2624            expr: "${body} == 'NOPE'".to_string(),
2625            language: "simple".to_string(),
2626        });
2627        let incoming = make_exchange("k", "X", "hello");
2628        let compiled = compile_test_completion(&mode, &registry).expect("compile must succeed");
2629        let result = evaluate_completion_predicate(&compiled, &incoming).await;
2630        assert!(result.is_ok(), "eval must succeed: {:?}", result);
2631        assert!(!result.unwrap(), "predicate does not match");
2632    }
2633
2634    #[tokio::test]
2635    async fn completion_predicate_non_bool_is_error() {
2636        use camel_api::aggregator::{CompletionCondition, CompletionMode};
2637
2638        let registry = registry_with_simple();
2639
2640        // A bare slot is a value, not a boolean. Completion predicates are
2641        // strict: the Simple predicate reports a type mismatch (expected bool)
2642        // instead of coercing the string to false.
2643        let mode = CompletionMode::Single(CompletionCondition::PredicateExpr {
2644            expr: "${body}".to_string(),
2645            language: "simple".to_string(),
2646        });
2647        let incoming = make_exchange("k", "X", "x");
2648        let compiled = compile_test_completion(&mode, &registry).expect("compile must succeed");
2649        let err = evaluate_completion_predicate(&compiled, &incoming)
2650            .await
2651            .expect_err("non-bool predicate must error, not coerce to false");
2652        // Redacted diagnostic: type names only, asserted via the "bool" text,
2653        // never the runtime body value. The aggregator has no `EvalMeta`, so
2654        // there is no `ExpressionFailed` class to assert.
2655        assert!(
2656            matches!(&err, CamelError::ProcessorError(msg) if msg.contains("bool")),
2657            "error must carry the type-mismatch text naming bool: {err:?}"
2658        );
2659    }
2660
2661    #[tokio::test]
2662    async fn completion_predicate_eval_error_propagates() {
2663        use camel_api::aggregator::{CompletionCondition, CompletionMode};
2664
2665        let registry = registry_with_simple();
2666
2667        // `${body} > 1` over a non-numeric body is an evaluation error. The
2668        // aggregator has no `EvalMeta`, so it surfaces as `ProcessorError`.
2669        // Compilation succeeds; the error still surfaces per exchange.
2670        let mode = CompletionMode::Single(CompletionCondition::PredicateExpr {
2671            expr: "${body} > 1".to_string(),
2672            language: "simple".to_string(),
2673        });
2674        let incoming = make_exchange("k", "X", "hello");
2675        let compiled = compile_test_completion(&mode, &registry).expect("compile must succeed");
2676        let err = evaluate_completion_predicate(&compiled, &incoming)
2677            .await
2678            .expect_err("evaluation error must propagate, not coerce to false");
2679        assert!(
2680            matches!(err, CamelError::ProcessorError(_)),
2681            "eval error must be a ProcessorError: {err:?}"
2682        );
2683    }
2684
2685    #[tokio::test]
2686    async fn compile_correlation_expression_evaluates_after_compile() {
2687        let registry = registry_with_simple();
2688        let strategy = CorrelationStrategy::Expression {
2689            expr: "${header.corr-id}".to_string(),
2690            language: "simple".to_string(),
2691        };
2692        let compiled =
2693            compile_test_correlation(&strategy, &registry).expect("compile must succeed");
2694        let key = extract_correlation_key(&make_exchange("corr-id", "bucket-1", "body"), &compiled)
2695            .await
2696            .expect("evaluate must succeed");
2697        assert_eq!(key, serde_json::json!("bucket-1"));
2698    }
2699
2700    #[tokio::test]
2701    async fn try_new_expression_correlation_with_empty_registry_fails_at_construction() {
2702        use camel_api::aggregator::CorrelationStrategy;
2703
2704        let mut config = AggregatorConfig::correlate_by("key")
2705            .complete_when_size(2)
2706            .build()
2707            .expect("config builds");
2708        config.correlation = CorrelationStrategy::Expression {
2709            expr: "${header.corr-id}".to_string(),
2710            language: "simple".to_string(),
2711        };
2712
2713        let (tx, _rx) = mpsc::channel(8);
2714        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
2715        let err = AggregatorService::try_new(config, tx, registry, CancellationToken::new())
2716            .expect_err("construction must fail without the language");
2717        assert!(
2718            matches!(&err, CamelError::ProcessorError(msg) if msg.contains("not found in registry")),
2719            "expected missing-language error, got {err:?}"
2720        );
2721    }
2722
2723    #[tokio::test]
2724    async fn try_new_malformed_expression_fails_at_construction() {
2725        // Unclosed interpolation: the Simple parser rejects it at
2726        // create_expression time (not per exchange).
2727        let config = AggregatorConfig::correlate_by("key")
2728            .correlate_by_expr("${", "simple")
2729            .complete_when_size(2)
2730            .build()
2731            .expect("config builds");
2732
2733        let (tx, _rx) = mpsc::channel(8);
2734        let err = AggregatorService::try_new(
2735            config,
2736            tx,
2737            registry_with_simple(),
2738            CancellationToken::new(),
2739        )
2740        .expect_err("construction must fail on malformed expression");
2741        assert!(
2742            matches!(&err, CamelError::ProcessorError(msg) if msg.contains("unclosed interpolation")),
2743            "malformed expression must fail in the Simple parser: {err:?}"
2744        );
2745    }
2746
2747    #[tokio::test]
2748    async fn try_new_malformed_predicate_fails_at_construction() {
2749        use camel_api::aggregator::{CompletionCondition, CompletionMode};
2750
2751        // Unclosed interpolation: the Simple predicate parser rejects it at
2752        // create_predicate time (not per exchange).
2753        let mut config = AggregatorConfig::correlate_by("key")
2754            .complete_when_size(2)
2755            .build()
2756            .expect("config builds");
2757        config.completion = CompletionMode::Single(CompletionCondition::PredicateExpr {
2758            expr: "${".to_string(),
2759            language: "simple".to_string(),
2760        });
2761
2762        let (tx, _rx) = mpsc::channel(8);
2763        let err = AggregatorService::try_new(
2764            config,
2765            tx,
2766            registry_with_simple(),
2767            CancellationToken::new(),
2768        )
2769        .expect_err("construction must fail on malformed predicate");
2770        assert!(
2771            matches!(&err, CamelError::ProcessorError(msg) if msg.contains("unclosed interpolation")),
2772            "malformed predicate must fail in the Simple parser: {err:?}"
2773        );
2774    }
2775
2776    #[tokio::test]
2777    async fn predicate_expr_override_with_unknown_language_fails_at_construction() {
2778        use camel_api::aggregator::{CompletionCondition, CompletionMode};
2779
2780        // Override the completion AFTER `build()` (post-validate): the
2781        // constructor still compiles it and must fail closed.
2782        let mut config = AggregatorConfig::correlate_by("key")
2783            .complete_when_size(2)
2784            .build()
2785            .expect("config builds");
2786        config.completion = CompletionMode::Single(CompletionCondition::PredicateExpr {
2787            expr: "${body} == 'DONE'".to_string(),
2788            language: "nonexistent-lang".to_string(),
2789        });
2790
2791        let (tx, _rx) = mpsc::channel(8);
2792        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
2793        let err = AggregatorService::try_new(config, tx, registry, CancellationToken::new())
2794            .expect_err("construction must fail on an unknown language");
2795        assert!(
2796            matches!(&err, CamelError::ProcessorError(msg) if msg.contains("not found in registry")),
2797            "expected missing-language error, got {err:?}"
2798        );
2799    }
2800
2801    #[tokio::test]
2802    async fn compiled_expressions_do_not_touch_registry_after_construction() {
2803        use camel_api::aggregator::{CompletionCondition, CompletionMode};
2804
2805        let registry = registry_with_simple();
2806
2807        let mut config = AggregatorConfig::correlate_by("unused")
2808            .correlate_by_expr("${header.corr-id}", "simple")
2809            .complete_when_size(2)
2810            .build()
2811            .expect("config builds");
2812        config.completion = CompletionMode::Any(vec![
2813            CompletionCondition::Size(2),
2814            CompletionCondition::PredicateExpr {
2815                expr: "${header.corr-id} == 'never-matches'".to_string(),
2816                language: "simple".to_string(),
2817            },
2818        ]);
2819
2820        let (tx, _rx) = mpsc::channel(8);
2821        let mut svc =
2822            AggregatorService::try_new(config, tx, Arc::clone(&registry), CancellationToken::new())
2823                .expect("construction compiles expressions");
2824
2825        // Structural proof: construction consumed its registry snapshot. If
2826        // the service still held the registry, clearing it would break
2827        // correlation and completion on the next exchange.
2828        registry.lock().unwrap().clear();
2829
2830        let first = svc
2831            .ready()
2832            .await
2833            .unwrap()
2834            .call(make_exchange("corr-id", "bucket-1", "a"))
2835            .await
2836            .unwrap();
2837        assert!(first.property(CAMEL_AGGREGATOR_PENDING).is_some());
2838
2839        let second = svc
2840            .ready()
2841            .await
2842            .unwrap()
2843            .call(make_exchange("corr-id", "bucket-1", "b"))
2844            .await
2845            .unwrap();
2846        assert!(second.property(CAMEL_AGGREGATOR_PENDING).is_none());
2847        assert_eq!(
2848            second.property(CAMEL_AGGREGATED_COMPLETION_REASON),
2849            Some(&serde_json::json!("size"))
2850        );
2851    }
2852
2853    #[tokio::test]
2854    async fn completion_predicate_expr_completes_on_match() {
2855        use camel_api::aggregator::{CompletionCondition, CompletionMode};
2856
2857        // Build the config via the builder for correlation + size defaults
2858        // (required by `AggregatorService::new`'s validate()), then OVERRIDE
2859        // the completion field directly — there is no builder setter for
2860        // `PredicateExpr`.
2861        let mut config = AggregatorConfig::correlate_by("key")
2862            .complete_when_size(999) // placeholder; replaced below
2863            .build()
2864            .expect("config builds");
2865        config.completion = CompletionMode::Single(CompletionCondition::PredicateExpr {
2866            expr: "${body} == 'DONE'".to_string(),
2867            language: "simple".to_string(),
2868        });
2869
2870        let mut svc = new_test_svc_with_registry(config, registry_with_simple());
2871
2872        // First exchange — predicate false → still pending.
2873        let r = svc
2874            .ready()
2875            .await
2876            .unwrap()
2877            .call(make_exchange("key", "K", "first"))
2878            .await
2879            .unwrap();
2880        assert!(r.property(CAMEL_AGGREGATOR_PENDING).is_some());
2881
2882        // Matching exchange — predicate true → bucket completes.
2883        let r = svc
2884            .ready()
2885            .await
2886            .unwrap()
2887            .call(make_exchange("key", "K", "DONE"))
2888            .await
2889            .unwrap();
2890        assert!(r.property(CAMEL_AGGREGATOR_PENDING).is_none());
2891        assert_eq!(
2892            r.property(CAMEL_AGGREGATED_COMPLETION_REASON),
2893            Some(&serde_json::json!("predicate"))
2894        );
2895    }
2896
2897    // ── ADR-0046 D-A1: binary-fold strategy contract (no null oldExchange) ──
2898    //
2899    // Apache Camel's AggregationStrategy receives a null `oldExchange` on the
2900    // FIRST message of a bucket so the strategy can initialize. rust-camel's
2901    // AggregationFn has a binary signature `(Exchange, Exchange) -> Exchange`
2902    // and the bucket model holds the first message untouched; the strategy is
2903    // only first invoked on the SECOND message with both exchanges present.
2904    //
2905    // This test pins that contract: a strategy needing initialize-on-first
2906    // logic cannot rely on a null oldExchange — it must branch on a sentinel
2907    // in the accumulated body or on a property.
2908    #[tokio::test]
2909    async fn test_da1_strategy_receives_two_exchanges_first_message_preserved() {
2910        use camel_api::aggregator::{AggregationFn, AggregationStrategy};
2911        use std::sync::Arc;
2912
2913        let recorded: Arc<std::sync::Mutex<Vec<(String, String)>>> =
2914            Arc::new(std::sync::Mutex::new(Vec::new()));
2915        let recorded_for_closure = Arc::clone(&recorded);
2916
2917        let f: AggregationFn = Arc::new(move |old: Exchange, new: Exchange| {
2918            let old_body = old.input.body.as_text().unwrap_or("").to_string();
2919            let new_body = new.input.body.as_text().unwrap_or("").to_string();
2920            recorded_for_closure
2921                .lock()
2922                .expect("recorded mutex poisoned")
2923                .push((old_body, new_body));
2924            new
2925        });
2926
2927        let config = AggregatorConfig::correlate_by("k")
2928            .complete_when_size(2)
2929            .strategy(AggregationStrategy::Custom(f))
2930            .build()
2931            .unwrap();
2932        let mut svc = new_test_svc(config);
2933
2934        // First message: bucket goes 0→1, strategy NOT invoked, return pending.
2935        let first = svc
2936            .ready()
2937            .await
2938            .unwrap()
2939            .call(make_exchange("k", "1", "A"))
2940            .await
2941            .unwrap();
2942        assert!(
2943            first.property(CAMEL_AGGREGATOR_PENDING).is_some(),
2944            "first message must leave the bucket pending (size < 2)"
2945        );
2946        assert!(
2947            recorded.lock().expect("recorded mutex poisoned").is_empty(),
2948            "strategy must NOT be invoked on the first message of a bucket"
2949        );
2950
2951        // Second message: bucket goes 1→2, strategy IS invoked as f(ex1, ex2),
2952        // and the result is emitted.
2953        let _completed = svc
2954            .ready()
2955            .await
2956            .unwrap()
2957            .call(make_exchange("k", "1", "B"))
2958            .await
2959            .unwrap();
2960
2961        let recorded = recorded.lock().expect("recorded mutex poisoned");
2962        assert_eq!(
2963            recorded.len(),
2964            1,
2965            "strategy must be invoked exactly once across the two-message bucket, got {recorded:?}"
2966        );
2967        assert_eq!(
2968            recorded[0],
2969            ("A".to_string(), "B".to_string()),
2970            "strategy must observe the first message as `old` and the second as `new`, \
2971             with both bodies preserved unchanged"
2972        );
2973    }
2974
2975    // ── Sweep lifecycle tests (aggregate-route-cancel-threading) ──────
2976
2977    #[tokio::test]
2978    async fn sweep_shutdown_cancels_task() {
2979        let config = AggregatorConfig::correlate_by("key")
2980            .complete_when_size(10)
2981            .bucket_ttl(Duration::from_millis(100))
2982            .build()
2983            .unwrap();
2984        let (tx, _rx) = mpsc::channel(256);
2985        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
2986        let cancel = CancellationToken::new();
2987        let mut svc = AggregatorService::new(config, tx, registry, cancel);
2988
2989        let _ = svc.ready().await.unwrap();
2990
2991        assert!(
2992            svc.sweep_handle
2993                .lock()
2994                .unwrap_or_else(|e| e.into_inner())
2995                .is_some(),
2996            "sweep handle should be Some after poll_ready"
2997        );
2998
2999        svc.shutdown(StepShutdownReason::RouteStop).await.unwrap();
3000
3001        assert!(
3002            svc.sweep_handle
3003                .lock()
3004                .unwrap_or_else(|e| e.into_inner())
3005                .is_none(),
3006            "sweep handle should be None after shutdown (taken + aborted)"
3007        );
3008        assert!(
3009            svc.sweep_cancel
3010                .lock()
3011                .unwrap_or_else(|e| e.into_inner())
3012                .is_cancelled(),
3013            "sweep_cancel token should be cancelled after shutdown"
3014        );
3015
3016        tokio::time::sleep(Duration::from_millis(50)).await;
3017    }
3018
3019    #[tokio::test]
3020    async fn sweep_start_respawns_after_shutdown() {
3021        let config = AggregatorConfig::correlate_by("key")
3022            .complete_when_size(10)
3023            .bucket_ttl(Duration::from_millis(100))
3024            .build()
3025            .unwrap();
3026        let (tx, _rx) = mpsc::channel(256);
3027        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
3028        let cancel = CancellationToken::new();
3029        let mut svc = AggregatorService::new(config, tx, registry, cancel);
3030
3031        let _ = svc.ready().await.unwrap();
3032        svc.shutdown(StepShutdownReason::RouteStop).await.unwrap();
3033
3034        svc.start().await.unwrap();
3035        let _ = svc.ready().await.unwrap();
3036
3037        assert!(
3038            svc.sweep_handle
3039                .lock()
3040                .unwrap_or_else(|e| e.into_inner())
3041                .is_some(),
3042            "sweep handle should be Some after start + poll_ready"
3043        );
3044        assert!(
3045            !svc.sweep_cancel
3046                .lock()
3047                .unwrap_or_else(|e| e.into_inner())
3048                .is_cancelled(),
3049            "sweep_cancel should be a fresh uncancelled token after start"
3050        );
3051    }
3052
3053    #[tokio::test]
3054    async fn sweep_shutdown_hotswap_cancels_task() {
3055        let config = AggregatorConfig::correlate_by("key")
3056            .complete_when_size(10)
3057            .bucket_ttl(Duration::from_millis(100))
3058            .build()
3059            .unwrap();
3060        let (tx, _rx) = mpsc::channel(256);
3061        let registry: SharedLanguageRegistry = Arc::new(std::sync::Mutex::new(HashMap::new()));
3062        let cancel = CancellationToken::new();
3063        let mut svc = AggregatorService::new(config, tx, registry, cancel);
3064
3065        let _ = svc.ready().await.unwrap();
3066
3067        assert!(
3068            svc.sweep_handle
3069                .lock()
3070                .unwrap_or_else(|e| e.into_inner())
3071                .is_some(),
3072            "sweep handle should be Some after poll_ready"
3073        );
3074
3075        svc.shutdown(StepShutdownReason::HotSwap).await.unwrap();
3076
3077        assert!(
3078            svc.sweep_handle
3079                .lock()
3080                .unwrap_or_else(|e| e.into_inner())
3081                .is_none(),
3082            "sweep handle should be None after HotSwap shutdown"
3083        );
3084        assert!(
3085            svc.sweep_cancel
3086                .lock()
3087                .unwrap_or_else(|e| e.into_inner())
3088                .is_cancelled(),
3089            "sweep_cancel token should be cancelled after HotSwap shutdown"
3090        );
3091
3092        tokio::time::sleep(Duration::from_millis(50)).await;
3093    }
3094
3095    // ── Task 4.1 (direct-inline-dispatch): constant-key memo fast path ──
3096
3097    /// A constant scalar correlation key must serialize exactly ONCE: the
3098    /// first fragment fills the memo, later fragments reuse the memoized
3099    /// string via a scalar equality check. All fragments still land in ONE
3100    /// bucket (the size-3 completion with `CamelAggregatedSize == 3` proves
3101    /// a single bucket held all three).
3102    #[tokio::test]
3103    async fn constant_key_skips_reserialization() {
3104        let mut svc = new_test_svc(config_size(3));
3105        let mut result = None;
3106        for body in ["first", "second", "third"] {
3107            result = Some(
3108                svc.ready()
3109                    .await
3110                    .unwrap()
3111                    .call(make_exchange("orderId", "A", body))
3112                    .await
3113                    .unwrap(),
3114            );
3115        }
3116        let result = result.unwrap();
3117        assert_eq!(
3118            result.property(CAMEL_AGGREGATED_SIZE),
3119            Some(&serde_json::json!(3u64)),
3120            "all 3 fragments must aggregate out of a single bucket"
3121        );
3122        assert!(svc.buckets.lock().unwrap().is_empty());
3123        assert_eq!(
3124            svc.key_serializations
3125                .load(std::sync::atomic::Ordering::Relaxed),
3126            1,
3127            "constant scalar key must serialize exactly once"
3128        );
3129    }
3130
3131    /// Alternating scalar keys keep byte-identical bucket names to direct
3132    /// `serde_json::to_string` calls: k1, k2, k1 → exactly two buckets named
3133    /// `"k1"` and `"k2"` (including the JSON quotes).
3134    #[tokio::test]
3135    async fn divergent_keys_keep_serde_semantics() {
3136        let mut svc = new_test_svc(config_size(10)); // never completes
3137        for key in ["k1", "k2", "k1"] {
3138            svc.ready()
3139                .await
3140                .unwrap()
3141                .call(make_exchange("orderId", key, "body"))
3142                .await
3143                .unwrap();
3144        }
3145        let guard = svc.buckets.lock().unwrap();
3146        assert_eq!(guard.len(), 2, "k1/k2/k1 → exactly two buckets");
3147        for key in ["k1", "k2"] {
3148            let expected = serde_json::to_string(&serde_json::json!(key)).unwrap();
3149            assert!(
3150                guard.contains_key(expected.as_str()),
3151                "bucket name must be byte-identical to serde_json::to_string: \
3152                 expected {expected}, have {:?}",
3153                guard.keys().collect::<Vec<_>>()
3154            );
3155        }
3156    }
3157
3158    /// Object correlation keys bypass the memo entirely — every fragment
3159    /// serializes, and bucketing stays byte-identical to direct
3160    /// `serde_json::to_string` of the objects. The two fixtures share an
3161    /// equal key-set but are built in different insertion orders; the
3162    /// expected bucket-key set is DERIVED from serde_json itself so the pin
3163    /// holds under both order-canonicalizing (BTreeMap) and
3164    /// order-preserving (`preserve_order`) serde_json builds.
3165    #[tokio::test]
3166    async fn object_keys_bypass_cache() {
3167        let mut svc = new_test_svc(config_size(10)); // never completes
3168        let obj_a = serde_json::json!({"a": 1, "b": 2});
3169        let obj_b = serde_json::json!({"b": 2, "a": 1});
3170        for obj in [&obj_a, &obj_b, &obj_a] {
3171            let mut msg = Message {
3172                headers: Default::default(),
3173                body: Body::Text("body".into()),
3174            };
3175            msg.headers.insert("orderId".to_string(), obj.clone());
3176            svc.ready()
3177                .await
3178                .unwrap()
3179                .call(Exchange::new(msg))
3180                .await
3181                .unwrap();
3182        }
3183        let expected_keys: std::collections::HashSet<String> = [&obj_a, &obj_b]
3184            .into_iter()
3185            .map(|o| serde_json::to_string(o).unwrap())
3186            .collect();
3187        let guard = svc.buckets.lock().unwrap();
3188        let actual_keys: std::collections::HashSet<String> = guard.keys().cloned().collect();
3189        assert_eq!(
3190            actual_keys, expected_keys,
3191            "object keys must bucket exactly per serde_json::to_string (cache bypassed)"
3192        );
3193        assert_eq!(
3194            svc.key_serializations
3195                .load(std::sync::atomic::Ordering::Relaxed),
3196            3,
3197            "each object fragment must serialize (memo never consulted for objects)"
3198        );
3199    }
3200
3201    /// Float ±0.0 regression: `json!(0.0) == json!(-0.0)` under `Value`
3202    /// equality, but serde serializes them as "0.0" and "-0.0". Numbers are
3203    /// NOT memoizable — every fragment serializes, and the two zero signs
3204    /// stay in distinct buckets named byte-identically to
3205    /// `serde_json::to_string` of each value.
3206    #[tokio::test]
3207    async fn float_zero_sign_keys_stay_distinct() {
3208        let mut svc = new_test_svc(config_size(10)); // never completes
3209        for key in [0.0_f64, -0.0, 0.0] {
3210            let mut msg = Message {
3211                headers: Default::default(),
3212                body: Body::Text("body".into()),
3213            };
3214            msg.headers
3215                .insert("orderId".to_string(), serde_json::json!(key));
3216            svc.ready()
3217                .await
3218                .unwrap()
3219                .call(Exchange::new(msg))
3220                .await
3221                .unwrap();
3222        }
3223        let guard = svc.buckets.lock().unwrap();
3224        assert_eq!(guard.len(), 2, "±0.0 must stay in distinct buckets");
3225        for key in [0.0_f64, -0.0] {
3226            let expected = serde_json::to_string(&serde_json::json!(key)).unwrap();
3227            assert!(
3228                guard.contains_key(expected.as_str()),
3229                "bucket name must be byte-identical to serde_json::to_string: \
3230                 expected {expected}, have {:?}",
3231                guard.keys().collect::<Vec<_>>()
3232            );
3233        }
3234        assert_eq!(
3235            svc.key_serializations
3236                .load(std::sync::atomic::Ordering::Relaxed),
3237            3,
3238            "number keys serialize per fragment (never memoized)"
3239        );
3240    }
3241}