Skip to main content

camel_component_sql/
consumer.rs

1use std::sync::Arc;
2use std::time::Duration;
3
4use async_trait::async_trait;
5use bytes::Bytes;
6use camel_api::datasource::DatasourceCatalog;
7use futures::TryStreamExt;
8use serde_json::Value as JsonValue;
9use sqlx::AnyPool;
10use sqlx::any::AnyPoolOptions;
11use sqlx::any::AnyRow;
12use tokio::sync::OnceCell;
13use tracing::{debug, error, info, warn};
14
15use camel_component_api::retry_async;
16use camel_component_api::{
17    Body, CamelError, Exchange, Message, RuntimeObservability, StreamBody, StreamMetadata,
18};
19use camel_component_api::{ConcurrencyModel, Consumer, ConsumerContext};
20
21use crate::bind_kinds::{BindMode, BindPlan, bind_single_item, plan_binds};
22use crate::config::{
23    PollStrategy, ProcessingStrategy, SqlEndpointConfig, SqlOutputType, TransactionMode,
24    enrich_db_url_with_ssl, redact_db_url,
25};
26use crate::headers;
27use crate::producer::release_after_error;
28use crate::query::{QueryTemplate, parse_query_template, resolve_params};
29use crate::utils::{fetch_error, is_retryable_sqlx_error, row_to_json};
30
31/// Record a post-process (b′) failure for ADR-0012 outside-contract sites in this
32/// consumer. Increments the per-label error metric AND emits an `error!` log
33/// per ADR-0012 L57 + L70-72 (the metric is the operator signal; `error!`
34/// provides loud log visibility — b′ errors are NOT absorbed by route handlers).
35///
36/// Both the metric call and the `error!` live INSIDE this helper so that
37/// `lint-log-levels`'s `has_replacement_signal` (scripts/xtask/src/main.rs)
38/// sees both literals in the helper's function body. Call sites have NO
39/// `error!` of their own.
40///
41/// Regression-tested by:
42/// - `record_post_process_failure_increments_errors_and_emits_error_log` (helper unit)
43/// - `unbridged_send_and_wait_failure_emits_error_loud` (StreamList integration path)
44fn record_post_process_failure(
45    runtime: &dyn RuntimeObservability,
46    route_id: &str,
47    label: &str,
48    error: &CamelError,
49    message: &str,
50) {
51    // allow-open-label rc-otxh (label: caller-bounded b-prime literals at all four call sites; helper co-locates metric + error! for lint-log-levels)
52    runtime.metrics().increment_errors(route_id, label);
53    // log-policy: outside-contract
54    error!(error = %error, "{message}");
55}
56
57/// Outcome of a single poll cycle. Carries whether the poll returned zero rows,
58/// threaded up to the poll loop for `break_on_empty` (without propagating errors,
59/// which are swallowed/bridged by `handle_poll_result`).
60#[derive(Debug, Clone, Copy, Default)]
61struct PollOutcome {
62    was_empty: bool,
63}
64
65pub struct SqlConsumer {
66    pub(crate) config: SqlEndpointConfig,
67    pub(crate) pool: Arc<OnceCell<Arc<AnyPool>>>,
68    pub(crate) catalog: Option<Arc<dyn DatasourceCatalog>>,
69    stopped: bool,
70    /// Runtime observability for metrics and health — used by the
71    /// `record_post_process_failure` helper for ADR-0012 (b′) metric calls.
72    runtime: Arc<dyn RuntimeObservability>,
73}
74
75impl SqlConsumer {
76    pub fn new(
77        config: SqlEndpointConfig,
78        pool: Arc<OnceCell<Arc<AnyPool>>>,
79        catalog: Option<Arc<dyn DatasourceCatalog>>,
80        runtime: Arc<dyn RuntimeObservability>,
81    ) -> Self {
82        Self {
83            config,
84            pool,
85            catalog,
86            stopped: false,
87            runtime,
88        }
89    }
90
91    /// Poll the database for new rows and process them.
92    async fn poll_database(
93        &self,
94        pool: &AnyPool,
95        context: &ConsumerContext,
96        template: &QueryTemplate,
97    ) -> Result<PollOutcome, CamelError> {
98        // Capture route_id from ConsumerContext for ADR-0012 metrics
99        let route_id = context.route_id();
100
101        // Create an empty exchange for parameter resolution (consumer has no input)
102        let empty_exchange = Exchange::new(Message::default());
103
104        // Resolve parameters
105        let prepared = resolve_params(template, &empty_exchange, &self.config.in_separator)?;
106
107        debug!(query = %prepared.sql, "executing SQL consumer poll");
108
109        if self.config.output_type == SqlOutputType::StreamList {
110            return self.poll_database_stream(pool, context, &prepared).await;
111        }
112
113        let mut conn = pool
114            .acquire()
115            .await
116            .map_err(|e| fetch_error("Failed to acquire database connection", e))?;
117
118        let fetched = async {
119            // Plan and execute against the SAME pooled connection so the
120            // normalization targets name the OIDs of the statement that
121            // actually runs (bd rc-7e681).
122            let plan = plan_binds(
123                &mut conn,
124                &prepared.sql,
125                &[prepared.bindings.as_slice()],
126                BindMode::Consumer,
127            )
128            .await?;
129            let query =
130                sqlx::query(sqlx::AssertSqlSafe(plan.sql.as_str())).persistent(plan.persistent);
131            let query = bind_single_item(query, &prepared.bindings, &plan.targets)?;
132            query
133                .fetch_all(&mut *conn)
134                .await
135                .map_err(|e| fetch_error("SQL consumer poll query failed", e))
136        }
137        .await;
138
139        let rows: Vec<AnyRow> = match fetched {
140            Ok(rows) => {
141                // `fetch_all` drained the statement: release the connection
142                // before post-processing, because every onConsume /
143                // onConsumeFailed query acquires its own pooled connection
144                // and a single-connection pool would deadlock on the nested
145                // acquire.
146                drop(conn);
147                rows
148            }
149            Err(original) => return Err(release_after_error(conn, original).await),
150        };
151
152        debug!(rows = rows.len(), "SQL consumer poll completed");
153
154        let was_empty = rows.is_empty();
155        if was_empty && !self.config.route_empty_result_set {
156            return Ok(PollOutcome { was_empty });
157        }
158
159        let rows_to_process: Vec<AnyRow> = if let Some(max) = self.config.max_messages_per_poll {
160            if max > 0 {
161                rows.into_iter().take(max as usize).collect()
162            } else {
163                rows
164            }
165        } else {
166            rows
167        };
168
169        if self.config.use_iterator {
170            // Process each row individually
171            for row in rows_to_process {
172                let row_json = row_to_json(&row)?;
173
174                // Create exchange with the row as JSON body
175                let mut msg = Message::new(Body::Json(row_json.clone()));
176
177                // Set individual column headers with CamelSql. prefix per Apache Camel convention
178                if let Some(obj) = row_json.as_object() {
179                    for (key, value) in obj {
180                        msg.set_header(format!("CamelSql.{}", key), value.clone());
181                    }
182                }
183
184                let exchange = Exchange::new(msg);
185
186                // Send and wait for processing
187                let result = context.send_and_wait(exchange).await;
188
189                // Handle post-processing (onConsume/onConsumeFailed)
190                if let Err(e) = self.handle_post_processing(pool, &result, &row_json).await {
191                    record_post_process_failure(
192                        self.runtime.as_ref(),
193                        route_id,
194                        "b-prime:sql:on-consume",
195                        &e,
196                        "Post-processing failed",
197                    );
198                    if self.config.break_batch_on_consume_fail {
199                        return Err(e);
200                    }
201                }
202
203                // If downstream processing itself failed, honour break_batch_on_consume_fail
204                if let Err(ref consume_err) = result
205                    && self.config.break_batch_on_consume_fail
206                {
207                    return Err(consume_err.clone());
208                }
209            }
210        } else {
211            // Process all rows as a single batch
212            let rows_json: Vec<JsonValue> = rows_to_process
213                .iter()
214                .map(row_to_json)
215                .collect::<Result<Vec<_>, CamelError>>()?;
216
217            let row_count = rows_json.len();
218
219            // Create exchange with array of rows
220            let mut msg = Message::new(Body::Json(JsonValue::Array(rows_json.clone())));
221            msg.set_header(headers::ROW_COUNT, JsonValue::Number(row_count.into()));
222
223            let exchange = Exchange::new(msg);
224
225            // Send and wait for result
226            let result = context.send_and_wait(exchange).await;
227
228            // SQL-021: Run per-row post-processing even in batch mode so that
229            // onConsume/onConsumeFailed queries can reference row-specific parameters
230            // (e.g. `:#id`). Each row gets its own post-processing query execution.
231            for row_json in rows_json.iter() {
232                if let Err(e) = self.handle_post_processing(pool, &result, row_json).await {
233                    record_post_process_failure(
234                        self.runtime.as_ref(),
235                        route_id,
236                        "b-prime:sql:on-consume-batch",
237                        &e,
238                        "Post-processing failed for batch row",
239                    );
240                    if self.config.break_batch_on_consume_fail {
241                        return Err(e);
242                    }
243                }
244            }
245
246            // If downstream processing itself failed, honour break_batch_on_consume_fail
247            if let Err(ref consume_err) = result
248                && self.config.break_batch_on_consume_fail
249            {
250                return Err(consume_err.clone());
251            }
252        }
253
254        // Execute on_consume_batch_complete if configured
255        if let Some(ref batch_query) = self.config.on_consume_batch_complete {
256            let _ = self
257                .execute_post_query(pool, batch_query, &JsonValue::Null)
258                .await;
259        }
260
261        Ok(PollOutcome { was_empty })
262    }
263
264    async fn poll_database_stream(
265        &self,
266        pool: &AnyPool,
267        context: &ConsumerContext,
268        prepared: &crate::query::PreparedQuery,
269    ) -> Result<PollOutcome, CamelError> {
270        let pool_clone = pool.clone();
271        let sql_str = prepared.sql.clone();
272        let bindings = prepared.bindings.clone();
273
274        let byte_stream = async_stream::try_stream! {
275            let mut conn = pool_clone
276                .acquire()
277                .await
278                .map_err(|e| fetch_error("Failed to acquire database connection", e))?;
279
280            // Plan and execute against the SAME pooled connection: the
281            // stream's rows come from the statement that was described
282            // (bd rc-7e681).
283            let plan = match plan_binds(
284                &mut conn,
285                &sql_str,
286                &[bindings.as_slice()],
287                BindMode::Consumer,
288            )
289            .await
290            {
291                Ok(plan) => plan,
292                Err(original) => {
293                    // `try_stream!` turns `?` into "yield the error and
294                    // return", but the compiler still sees the `Ok` arm
295                    // as reachable; that arm must diverge for the
296                    // connection move to be accepted.
297                    Err::<BindPlan, CamelError>(release_after_error(conn, original).await)?;
298                    unreachable!("`release_after_error` always propagates the error")
299                }
300            };
301            let q = sqlx::query(sqlx::AssertSqlSafe(plan.sql.as_str()))
302                .persistent(plan.persistent);
303            let q = match bind_single_item(q, &bindings, &plan.targets) {
304                Ok(q) => q,
305                Err(original) => {
306                    Err::<_, CamelError>(release_after_error(conn, original).await)?;
307                    unreachable!("`release_after_error` always propagates the error")
308                }
309            };
310            let mut rows = q.fetch(&mut *conn);
311            let mut failure: Option<CamelError> = None;
312            loop {
313                let row = match rows.try_next().await {
314                    Ok(Some(row)) => row,
315                    Ok(None) => break,
316                    Err(e) => {
317                        failure = Some(fetch_error("Query execution failed", e));
318                        break;
319                    }
320                };
321                let json_val = match row_to_json(&row) {
322                    Ok(json_val) => json_val,
323                    Err(original) => {
324                        failure = Some(original);
325                        break;
326                    }
327                };
328                let mut bytes = match serde_json::to_vec(&json_val) {
329                    Ok(bytes) => bytes,
330                    Err(e) => {
331                        failure = Some(CamelError::ProcessorError(format!(
332                            "JSON serialization failed: {}",
333                            e
334                        )));
335                        break;
336                    }
337                };
338                bytes.push(b'\n');
339                yield Bytes::from(bytes);
340            }
341            // `rows` borrows the connection: end the borrow before handing
342            // the connection to the rollback.
343            drop(rows);
344            if let Some(original) = failure {
345                Err::<(), CamelError>(release_after_error(conn, original).await)?;
346            }
347        };
348
349        let msg = Message::new(Body::Stream(StreamBody {
350            stream: Arc::new(tokio::sync::Mutex::new(Some(Box::pin(byte_stream)))),
351            metadata: StreamMetadata {
352                content_type: Some("application/x-ndjson".to_string()),
353                size_hint: None,
354                origin: None,
355            },
356        }));
357
358        let exchange = Exchange::new(msg);
359        let result = context.send_and_wait(exchange).await;
360        if let Err(e) = result {
361            record_post_process_failure(
362                self.runtime.as_ref(),
363                context.route_id(),
364                "b-prime:sql:stream-list",
365                &e,
366                "StreamList consumer downstream processing failed",
367            );
368            return Err(e);
369        }
370
371        debug!("StreamList: consumer poll completed (lazy stream emitted)");
372        // StreamList ignores break_on_empty, so it always returns was_empty=false
373        Ok(PollOutcome::default())
374    }
375
376    /// Handle post-processing after a row is processed (onConsume/onConsumeFailed).
377    async fn handle_post_processing(
378        &self,
379        pool: &AnyPool,
380        result: &Result<Exchange, CamelError>,
381        row_json: &JsonValue,
382    ) -> Result<(), CamelError> {
383        match result {
384            Ok(_) => {
385                // Success - execute onConsume if configured
386                if let Some(ref on_consume) = self.config.on_consume {
387                    self.execute_post_query(pool, on_consume, row_json).await?;
388                }
389            }
390            Err(_) => {
391                // Failure - execute onConsumeFailed if configured
392                if let Some(ref on_consume_failed) = self.config.on_consume_failed {
393                    self.execute_post_query(pool, on_consume_failed, row_json)
394                        .await?;
395                }
396            }
397        }
398        Ok(())
399    }
400
401    /// Execute a post-processing query with the row data as parameters.
402    async fn execute_post_query(
403        &self,
404        pool: &AnyPool,
405        query_str: &str,
406        row_json: &JsonValue,
407    ) -> Result<(), CamelError> {
408        // Parse the query template
409        let template = parse_query_template(query_str, self.config.placeholder)?;
410
411        // Create a temporary exchange with the row as body for parameter resolution
412        // Populate CamelSql.* headers so named params can reference them
413        let mut temp_msg = Message::new(Body::Json(row_json.clone()));
414        if let Some(obj) = row_json.as_object() {
415            for (key, value) in obj {
416                temp_msg.set_header(format!("CamelSql.{}", key), value.clone());
417            }
418        }
419        let temp_exchange = Exchange::new(temp_msg);
420
421        // Resolve parameters
422        let prepared = resolve_params(&template, &temp_exchange, &self.config.in_separator)?;
423
424        // Plan and execute the post-query on ONE pooled connection so the
425        // binds target the statement that actually runs (bd rc-7e681).
426        let mut conn = pool
427            .acquire()
428            .await
429            .map_err(|e| fetch_error("Failed to acquire database connection", e))?;
430
431        let executed = async {
432            let plan = plan_binds(
433                &mut conn,
434                &prepared.sql,
435                &[prepared.bindings.as_slice()],
436                BindMode::Consumer,
437            )
438            .await?;
439            let query =
440                sqlx::query(sqlx::AssertSqlSafe(plan.sql.as_str())).persistent(plan.persistent);
441            let query = bind_single_item(query, &prepared.bindings, &plan.targets)?;
442            query.execute(&mut *conn).await.map_err(|e| {
443                CamelError::ProcessorError(format!("Post-query execution failed: {}", e))
444            })
445        }
446        .await;
447
448        let result = match executed {
449            Ok(result) => result,
450            Err(original) => return Err(release_after_error(conn, original).await),
451        };
452
453        // Warn if 0 rows affected (the row may not have been marked correctly)
454        if result.rows_affected() == 0 {
455            warn!(
456                query = query_str,
457                "Post-processing query affected 0 rows — the row may not have been marked correctly"
458            );
459        }
460
461        Ok(())
462    }
463
464    /// Handle the result of a single poll cycle, including bridging if configured.
465    /// Extracted from `run()` so tests can exercise the error-handling branch directly.
466    /// Returns `PollOutcome` so the poll loop can decide whether to break on empty.
467    async fn handle_poll_result(
468        &self,
469        pool: &AnyPool,
470        context: &ConsumerContext,
471        template: &QueryTemplate,
472    ) -> PollOutcome {
473        match self.poll_database(pool, context, template).await {
474            Ok(outcome) => outcome,
475            Err(e) => {
476                // Swallow the poll error (do NOT propagate via ? — the loop continues).
477                if self.config.bridge_error_handler {
478                    // log-policy: handler-owned
479                    // (category b-bridged: error will be wrapped as Exchange
480                    // and flow into the route's error handler)
481                    warn!(error = %e, "SQL consumer poll failed (bridged)");
482                    if let Err(route_err) = self.bridge_poll_error(context, e).await {
483                        // (the bridge channel itself broke — route will CrashNotification per ADR-0007)
484                        // log-policy: system-broken
485                        error!(error = %route_err, "Failed to bridge SQL consumer error to route");
486                    }
487                } else {
488                    record_post_process_failure(
489                        self.runtime.as_ref(),
490                        context.route_id(),
491                        "b-prime:sql:poll-failed",
492                        &e,
493                        "SQL consumer poll failed",
494                    );
495                }
496                // An error is NOT an empty poll — the loop must continue.
497                PollOutcome::default()
498            }
499        }
500    }
501
502    async fn bridge_poll_error(
503        &self,
504        context: &ConsumerContext,
505        error: CamelError,
506    ) -> Result<(), CamelError> {
507        if !self.config.bridge_error_handler {
508            return Ok(());
509        }
510        let mut exchange = Exchange::new(Message::default());
511        exchange.set_error(error);
512        context.send_and_wait(exchange).await.map(|_| ())
513    }
514}
515
516#[async_trait]
517impl Consumer for SqlConsumer {
518    async fn start(&mut self, context: ConsumerContext) -> Result<(), CamelError> {
519        // Reject double-start
520        if self.stopped {
521            return Err(CamelError::Config(
522                "SQL consumer cannot be restarted after stop".into(),
523            ));
524        }
525
526        // Step 1: Initialize the connection pool
527        let route_id = context.route_id().to_string();
528        let catalog = self.catalog.clone();
529        let ds_name = self.config.datasource_name.clone();
530
531        // SQL-014: resolve file-based query before pool init, regardless of pool source
532        self.config.resolve_defaults();
533        self.config.resolve_file_query().await?;
534
535        let pool = self
536            .pool
537            .get_or_try_init(|| async {
538                // Catalog path: resolve shared pool from the datasource catalog
539                if let (Some(ref cat), Some(ref name)) = (catalog, ds_name) {
540                    let handle = cat.get_pool(name).await?;
541                    return handle.downcast::<AnyPool>();
542                }
543
544                // Install all compiled-in sqlx drivers so AnyPool can resolve them.
545                // This is idempotent; safe to call multiple times.
546                sqlx::any::install_default_drivers();
547                let db_url = enrich_db_url_with_ssl(&self.config.db_url, &self.config)?;
548
549                let max_conn = self.config.max_connections.ok_or_else(|| {
550                    CamelError::Config("max_connections not resolved for SQL consumer pool".into())
551                })?;
552                let min_conn = self.config.min_connections.ok_or_else(|| {
553                    CamelError::Config("min_connections not resolved for SQL consumer pool".into())
554                })?;
555                let idle_timeout = self.config.idle_timeout_secs.ok_or_else(|| {
556                    CamelError::Config(
557                        "idle_timeout_secs not resolved for SQL consumer pool".into(),
558                    )
559                })?;
560                let max_lifetime = self.config.max_lifetime_secs.ok_or_else(|| {
561                    CamelError::Config(
562                        "max_lifetime_secs not resolved for SQL consumer pool".into(),
563                    )
564                })?;
565
566                info!(
567                    db_url = %redact_db_url(&self.config.db_url),
568                    "SQL consumer pool initializing"
569                );
570                let retry_policy = &self.config.retry;
571                let pool = retry_async::<_, _, _, _, sqlx::Error>(
572                    retry_policy,
573                    "sql",
574                    "consumer-pool-init",
575                    || {
576                        async {
577                            AnyPoolOptions::new()
578                                .max_connections(max_conn)
579                                .min_connections(min_conn)
580                                .idle_timeout(Duration::from_secs(idle_timeout))
581                                .max_lifetime(Duration::from_secs(max_lifetime))
582                                .connect(&db_url)
583                                .await
584                        }
585                    },
586                    is_retryable_sqlx_error,
587                    Some(self.runtime.metrics().as_ref()),
588                )
589                .await
590                .map_err(|e| {
591                    self.runtime.health().force_unhealthy_for_route(
592                        &route_id,
593                        "g:sql:consumer-pool-init",
594                        &e.to_string(),
595                    );
596                    // log-policy: outside-contract
597                    error!(error = %e, db_url = %redact_db_url(&self.config.db_url), "SQL connect failed, giving up");
598                    CamelError::EndpointCreationFailed(format!(
599                        "Failed to connect to database: {}",
600                        e
601                    ))
602                })?;
603                Ok(Arc::new(pool))
604            })
605            .await?;
606
607        // SQL-002: unreachable through the URI surface — `create_endpoint` rejects
608        // `transactionMode=Managed` first (`validate_transaction_mode`). Kept as a
609        // safety net for programmatic construction via `SqlEndpoint::new*`, which
610        // bypasses validation.
611        if self.config.transaction_mode == TransactionMode::Managed {
612            warn!("transactionManager not yet implemented; using Auto mode");
613        }
614
615        // SQL-017/SQL-018: log processing and poll strategies
616        if self.config.processing_strategy == ProcessingStrategy::Scheduled {
617            debug!(
618                "Processing strategy: Scheduled (rows dispatched individually via send_and_wait)"
619            );
620        }
621        if self.config.poll_strategy == PollStrategy::Burst {
622            debug!("Poll strategy: Burst (rapid successive polls)");
623        }
624
625        if self.config.output_type == SqlOutputType::StreamList
626            && (self.config.on_consume.is_some()
627                || self.config.on_consume_failed.is_some()
628                || self.config.on_consume_batch_complete.is_some()
629                || self.config.break_on_empty)
630        {
631            warn!(
632                "onConsume/onConsumeFailed/onConsumeBatchComplete/breakOnEmpty are not executed in \
633                 StreamList mode (rows are consumed lazily downstream)"
634            );
635        }
636
637        // Warn if no onConsume configured
638        if self.config.on_consume.is_none() {
639            warn!(
640                "SQL consumer started without onConsume configured — consumed rows will not be marked/deleted"
641            );
642        }
643
644        info!(
645            db_url = %redact_db_url(&self.config.db_url),
646            query_len = self.config.query.len(),
647            "SQL consumer started"
648        );
649
650        // Step 2: Parse query template once (avoid re-parsing every poll)
651        let template = parse_query_template(&self.config.query, self.config.placeholder)
652            .map_err(|e| CamelError::Config(format!("Invalid query template: {}", e)))?;
653
654        // Step 3: Initial delay before starting polling
655        if self.config.initial_delay_ms > 0 {
656            tokio::select! {
657                _ = context.cancelled() => {
658                    info!("SQL consumer stopped during initial delay");
659                    return Ok(());
660                }
661                _ = tokio::time::sleep(Duration::from_millis(self.config.initial_delay_ms)) => {}
662            }
663        }
664
665        // Step 4: Polling loop
666        //
667        // This is a POLLING LOOP with fixed cadence (delay_ms), NOT a
668        // retry loop. It polls the database until cancelled or repeat_count
669        // is reached — there is no "transient error → retry with backoff"
670        // contract at this level. retry_async / retry_async_cancelable do
671        // not apply because they are designed for bounded retry, not
672        // repeated polling with uniform delay.
673        //
674        // The pool-connect retry at startup (Step 1) was migrated to
675        // retry_async in rc-d2r. The per-poll error handling (poll_database
676        // failures) is an error-bridge pattern, not a retry loop.
677        //
678        // See camel-redis/src/consumer.rs:325 for a similar polling-loop
679        // justification.
680        let mut poll_count: u32 = 0;
681        loop {
682            // SQL-015: check repeat_count limit
683            if let Some(max_repeats) = self.config.repeat_count
684                && poll_count >= max_repeats
685            {
686                info!(
687                    repeat_count = max_repeats,
688                    "SQL consumer reached repeat_count limit, stopping"
689                );
690                break;
691            }
692
693            tokio::select! {
694                _ = context.cancelled() => {
695                    info!("SQL consumer stopped");
696                    break;
697                }
698                _ = tokio::time::sleep(Duration::from_millis(self.config.delay_ms)) => {
699                    poll_count += 1;
700                    let outcome = self.handle_poll_result(pool.as_ref(), &context, &template).await;
701                    if self.config.break_on_empty && outcome.was_empty {
702                        info!("SQL consumer stopping: break_on_empty triggered (poll returned 0 rows)");
703                        break;
704                    }
705                }
706            }
707        }
708
709        Ok(())
710    }
711
712    async fn stop(&mut self) -> Result<(), CamelError> {
713        // Double-stop is safe — no-op after first stop
714        if self.stopped {
715            debug!("SQL consumer stop called on already-stopped consumer");
716            return Ok(());
717        }
718
719        // Close the connection pool if it was initialized
720        if let Some(pool) = self.pool.get() {
721            debug!("SQL consumer closing connection pool");
722            pool.close().await;
723            debug!("SQL consumer pool closed");
724        }
725
726        self.stopped = true;
727        info!("SQL consumer stopped");
728        Ok(())
729    }
730
731    fn concurrency_model(&self) -> ConcurrencyModel {
732        // Sequential is correct for SQL consumers: concurrent polls would fetch
733        // duplicate rows. The design doc mentioned SharedState (which doesn't exist
734        // in this runtime) — Sequential is the correct equivalent.
735        ConcurrencyModel::Sequential
736    }
737}
738
739#[cfg(test)]
740mod tests {
741    use super::*;
742    use camel_api::MetricsCollector;
743    use camel_component_api::HealthCheckRegistry;
744    use camel_component_api::test_support::PanicRuntimeObservability;
745    fn test_rt() -> std::sync::Arc<dyn camel_component_api::RuntimeObservability> {
746        std::sync::Arc::new(PanicRuntimeObservability)
747    }
748    use crate::config::SqlEndpointConfig;
749    use camel_component_api::ExchangeEnvelope;
750    use camel_component_api::UriConfig;
751    use sqlx::any::AnyPoolOptions;
752    use std::sync::Arc;
753    use std::sync::Mutex;
754    use std::time::Duration;
755    use tokio::sync::mpsc;
756    use tokio::time::timeout;
757    use tokio_util::sync::CancellationToken;
758
759    // -----------------------------------------------------------------------
760    // Recording metrics collector for testing increment_errors calls
761    // -----------------------------------------------------------------------
762
763    struct RecordingMetrics {
764        errors: Arc<Mutex<Vec<(String, String)>>>,
765    }
766
767    impl MetricsCollector for RecordingMetrics {
768        fn record_exchange_duration(&self, _: &str, _: Duration) {}
769        fn increment_errors(&self, route_id: &str, error_type: &str) {
770            self.errors
771                .lock()
772                .unwrap()
773                .push((route_id.to_string(), error_type.to_string()));
774        }
775        fn increment_exchanges(&self, _: &str) {}
776        fn set_queue_depth(&self, _: &str, _: usize) {}
777        fn record_circuit_breaker_change(&self, _: &str, _: &str, _: &str) {}
778    }
779
780    struct RecordingRuntime {
781        metrics_collector: Arc<RecordingMetrics>,
782    }
783
784    impl RecordingRuntime {
785        fn new(errors: Arc<Mutex<Vec<(String, String)>>>) -> Self {
786            Self {
787                metrics_collector: Arc::new(RecordingMetrics { errors }),
788            }
789        }
790    }
791
792    impl RuntimeObservability for RecordingRuntime {
793        fn metrics(&self) -> Arc<dyn MetricsCollector> {
794            self.metrics_collector.clone() as Arc<dyn MetricsCollector>
795        }
796        fn health(&self) -> Arc<dyn HealthCheckRegistry> {
797            panic!("RecordingRuntime::health not used in this test")
798        }
799    }
800
801    /// Regression test for ADR-0012: the record_post_process_failure helper
802    /// must increment the error metric with the correct route_id and label,
803    /// AND emit error! via tracing.
804    #[tracing_test::traced_test]
805    #[test]
806    fn record_post_process_failure_increments_errors_and_emits_error_log() {
807        let errors: Arc<Mutex<Vec<(String, String)>>> = Arc::new(Mutex::new(Vec::new()));
808        let runtime = Arc::new(RecordingRuntime::new(Arc::clone(&errors)));
809        let error = CamelError::ProcessorError("test failure".to_string());
810
811        // Directly invoke the helper
812        record_post_process_failure(
813            runtime.as_ref(),
814            "test-route",
815            "b-prime:sql:on-consume",
816            &error,
817            "Post-processing failed",
818        );
819
820        // Verify MetricsCollector::increment_errors was called
821        let recorded = errors.lock().unwrap();
822        assert_eq!(recorded.len(), 1, "expected 1 increment_errors call");
823        assert_eq!(recorded[0].0, "test-route");
824        assert_eq!(recorded[0].1, "b-prime:sql:on-consume");
825        drop(recorded);
826
827        // Verify error! was emitted
828        assert!(logs_contain("ERROR"), "helper must emit error! log");
829        assert!(
830            logs_contain("Post-processing failed"),
831            "helper must include the message in the log"
832        );
833    }
834
835    async fn sqlite_pool() -> AnyPool {
836        sqlx::any::install_default_drivers();
837        // Per-attempt deadline (lintwiden D4.3): a wedged pool connect
838        // must fail the helper instead of parking it.
839        tokio::time::timeout(
840            std::time::Duration::from_secs(10),
841            AnyPoolOptions::new()
842                .max_connections(1)
843                .connect("sqlite::memory:"),
844        )
845        .await
846        .expect("sqlite pool connect timed out after 10s")
847        .expect("sqlite pool")
848    }
849
850    async fn seed_consumer_table(pool: &AnyPool) {
851        sqlx::query("CREATE TABLE jobs (id INTEGER PRIMARY KEY, processed INTEGER DEFAULT 0, failed INTEGER DEFAULT 0)")
852            .execute(pool)
853            .await
854            .expect("create table");
855        sqlx::query("INSERT INTO jobs (id, processed, failed) VALUES (1, 0, 0), (2, 0, 0)")
856            .execute(pool)
857            .await
858            .expect("seed rows");
859    }
860
861    fn config() -> SqlEndpointConfig {
862        let mut c =
863            SqlEndpointConfig::from_uri("sql:select * from t?db_url=postgres://localhost/test")
864                .unwrap();
865        c.resolve_defaults();
866        c
867    }
868
869    #[test]
870    fn consumer_concurrency_model() {
871        let c = SqlConsumer::new(config(), Arc::new(OnceCell::new()), None, test_rt());
872        assert_eq!(c.concurrency_model(), ConcurrencyModel::Sequential);
873    }
874
875    #[test]
876    fn consumer_stores_config() {
877        let mut config = SqlEndpointConfig::from_uri(
878            "sql:select * from t?db_url=postgres://localhost/test&delay=2000&onConsume=update t set done=true"
879        ).unwrap();
880        config.resolve_defaults();
881        let c = SqlConsumer::new(config.clone(), Arc::new(OnceCell::new()), None, test_rt());
882        assert_eq!(c.config.delay_ms, 2000);
883        assert!(c.config.on_consume.is_some());
884    }
885
886    #[tokio::test]
887    async fn poll_database_runs_on_consume_for_successful_rows() {
888        let pool = sqlite_pool().await;
889        seed_consumer_table(&pool).await;
890
891        let mut config = SqlEndpointConfig::from_uri(
892            "sql:select id, processed, failed from jobs where processed = 0 order by id?db_url=sqlite::memory:&onConsume=update jobs set processed=1 where id=:#id&initialDelay=0&delay=1",
893        )
894        .unwrap();
895        config.resolve_defaults();
896
897        let consumer = SqlConsumer::new(config.clone(), Arc::new(OnceCell::new()), None, test_rt());
898        let template = parse_query_template(&config.query, config.placeholder).unwrap();
899
900        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(8);
901        tokio::spawn(async move {
902            loop {
903                match timeout(Duration::from_secs(2), rx.recv()).await {
904                    Ok(Some(env)) => {
905                        if let Some(reply_tx) = env.reply_tx {
906                            let _ = reply_tx.send(Ok(env.exchange));
907                        }
908                    }
909                    Ok(None) => break, // closed: drain complete
910                    Err(_) => break,   // stalled: drainer ends
911                }
912            }
913        });
914        let ctx = ConsumerContext::new(tx, CancellationToken::new(), "sql-test-route".to_string());
915
916        consumer
917            .poll_database(&pool, &ctx, &template)
918            .await
919            .expect("poll must succeed");
920
921        let row = sqlx::query("select processed from jobs where id = 1")
922            .fetch_one(&pool)
923            .await
924            .expect("row 1");
925        let processed_1: i64 = sqlx::Row::try_get(&row, 0).expect("processed");
926
927        let row = sqlx::query("select processed from jobs where id = 2")
928            .fetch_one(&pool)
929            .await
930            .expect("row 2");
931        let processed_2: i64 = sqlx::Row::try_get(&row, 0).expect("processed");
932
933        assert_eq!(processed_1, 1);
934        assert_eq!(processed_2, 1);
935    }
936
937    #[tokio::test]
938    async fn poll_database_runs_on_consume_failed_when_downstream_fails() {
939        let pool = sqlite_pool().await;
940        seed_consumer_table(&pool).await;
941
942        let mut config = SqlEndpointConfig::from_uri(
943            "sql:select id, processed, failed from jobs where processed = 0 order by id?db_url=sqlite::memory:&onConsumeFailed=update jobs set failed=1 where id=:#id&initialDelay=0&delay=1",
944        )
945        .unwrap();
946        config.resolve_defaults();
947
948        let consumer = SqlConsumer::new(config.clone(), Arc::new(OnceCell::new()), None, test_rt());
949        let template = parse_query_template(&config.query, config.placeholder).unwrap();
950
951        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(8);
952        tokio::spawn(async move {
953            loop {
954                match timeout(Duration::from_secs(2), rx.recv()).await {
955                    Ok(Some(env)) => {
956                        if let Some(reply_tx) = env.reply_tx {
957                            let _ = reply_tx
958                                .send(Err(CamelError::ProcessorError("downstream boom".into())));
959                        }
960                    }
961                    Ok(None) => break, // closed: drain complete
962                    Err(_) => break,   // stalled: drainer ends
963                }
964            }
965        });
966        let ctx = ConsumerContext::new(tx, CancellationToken::new(), "sql-test-route".to_string());
967
968        consumer
969            .poll_database(&pool, &ctx, &template)
970            .await
971            .expect("consumer should swallow downstream errors when breakBatchOnConsumeFail=false");
972
973        let row = sqlx::query("select failed from jobs where id = 1")
974            .fetch_one(&pool)
975            .await
976            .expect("row 1");
977        let failed_1: i64 = sqlx::Row::try_get(&row, 0).expect("failed");
978
979        let row = sqlx::query("select failed from jobs where id = 2")
980            .fetch_one(&pool)
981            .await
982            .expect("row 2");
983        let failed_2: i64 = sqlx::Row::try_get(&row, 0).expect("failed");
984
985        assert_eq!(failed_1, 1);
986        assert_eq!(failed_2, 1);
987    }
988
989    #[tokio::test]
990    async fn poll_database_breaks_batch_on_consume_fail() {
991        let pool = sqlite_pool().await;
992        seed_consumer_table(&pool).await;
993
994        let mut config = SqlEndpointConfig::from_uri(
995            "sql:select id, processed, failed from jobs where processed = 0 order by id?db_url=sqlite::memory:&onConsumeFailed=update jobs set failed=1 where id=:#id&breakBatchOnConsumeFail=true&initialDelay=0&delay=1",
996        )
997        .unwrap();
998        config.resolve_defaults();
999
1000        let consumer = SqlConsumer::new(config.clone(), Arc::new(OnceCell::new()), None, test_rt());
1001        let template = parse_query_template(&config.query, config.placeholder).unwrap();
1002
1003        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(8);
1004        tokio::spawn(async move {
1005            loop {
1006                match timeout(Duration::from_secs(2), rx.recv()).await {
1007                    Ok(Some(env)) => {
1008                        if let Some(reply_tx) = env.reply_tx {
1009                            let _ = reply_tx
1010                                .send(Err(CamelError::ProcessorError("downstream boom".into())));
1011                        }
1012                    }
1013                    Ok(None) => break, // closed: drain complete
1014                    Err(_) => break,   // stalled: drainer ends
1015                }
1016            }
1017        });
1018        let ctx = ConsumerContext::new(tx, CancellationToken::new(), "sql-test-route".to_string());
1019
1020        let err = consumer
1021            .poll_database(&pool, &ctx, &template)
1022            .await
1023            .expect_err("must stop on first downstream failure");
1024        assert!(err.to_string().contains("downstream boom"));
1025
1026        let row = sqlx::query("select failed from jobs where id = 1")
1027            .fetch_one(&pool)
1028            .await
1029            .expect("row 1");
1030        let failed_1: i64 = sqlx::Row::try_get(&row, 0).expect("failed");
1031
1032        let row = sqlx::query("select failed from jobs where id = 2")
1033            .fetch_one(&pool)
1034            .await
1035            .expect("row 2");
1036        let failed_2: i64 = sqlx::Row::try_get(&row, 0).expect("failed");
1037
1038        assert_eq!(failed_1, 1);
1039        assert_eq!(failed_2, 0, "second row must not be processed");
1040    }
1041
1042    // --- Phase B hardening tests ---
1043
1044    // SQL-001: Direct consumer construction without resolve_defaults does not panic.
1045    // The consumer defensively calls resolve_defaults() during pool init, so the pool
1046    // fields get resolved. This test verifies no panic occurs.
1047    #[tokio::test]
1048    async fn consumer_no_panic_without_prior_resolve_defaults() {
1049        let config = SqlEndpointConfig::from_uri(
1050            "sql:select 1?db_url=sqlite::memory:&initialDelay=0&delay=1",
1051        )
1052        .unwrap();
1053        // Deliberately NOT calling resolve_defaults() — pool fields remain None
1054        assert!(config.max_connections.is_none());
1055
1056        let mut consumer = SqlConsumer::new(
1057            config,
1058            Arc::new(OnceCell::new()),
1059            None,
1060            // Noop runtime: pool-init retries now record per-attempt
1061            // telemetry by design, which the panic runtime would reject.
1062            std::sync::Arc::new(camel_component_api::test_support::NoopRuntimeObservability),
1063        );
1064        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(8);
1065        tokio::spawn(async move {
1066            loop {
1067                match timeout(Duration::from_secs(2), rx.recv()).await {
1068                    Ok(Some(env)) => {
1069                        if let Some(reply_tx) = env.reply_tx {
1070                            let _ = reply_tx.send(Ok(env.exchange));
1071                        }
1072                    }
1073                    Ok(None) => break, // closed: drain complete
1074                    Err(_) => break,   // stalled: drainer ends
1075                }
1076            }
1077        });
1078        let token = CancellationToken::new();
1079        let ctx = ConsumerContext::new(tx, token.clone(), "sql-test-route".to_string());
1080
1081        // Spawn the consumer and cancel it quickly — it should not panic
1082        let consumer_handle = tokio::spawn(async move { consumer.start(ctx).await });
1083
1084        // Cancel after a short delay
1085        tokio::time::sleep(Duration::from_millis(50)).await;
1086        token.cancel();
1087
1088        let result = consumer_handle.await.expect("task should not panic"); // allow-test-wait: cancel token triggered before join
1089        // Should complete without panic (may be Ok or Err depending on timing)
1090        let _ = result;
1091    }
1092
1093    // SQL-008: stop() closes the pool
1094    #[tokio::test]
1095    async fn stop_closes_pool() {
1096        let pool = sqlite_pool().await;
1097        seed_consumer_table(&pool).await;
1098
1099        let mut config = SqlEndpointConfig::from_uri(
1100            "sql:select id from jobs?db_url=sqlite::memory:&onConsume=update jobs set processed=1 where id=:#id&initialDelay=0&delay=1",
1101        )
1102        .unwrap();
1103        config.resolve_defaults();
1104
1105        let pool_cell = Arc::new(OnceCell::new());
1106        pool_cell.set(Arc::new(pool.clone())).unwrap();
1107
1108        let mut consumer = SqlConsumer::new(config, pool_cell, None, test_rt());
1109        consumer.stop().await.expect("stop should succeed");
1110
1111        // After stop, the pool should be closed
1112        assert!(
1113            pool.is_closed(),
1114            "Pool should be closed after consumer.stop()"
1115        );
1116    }
1117
1118    // SQL-008: double-stop is safe
1119    #[tokio::test]
1120    async fn double_stop_is_safe() {
1121        let pool = sqlite_pool().await;
1122        let mut config = SqlEndpointConfig::from_uri(
1123            "sql:select 1?db_url=sqlite::memory:&initialDelay=0&delay=1",
1124        )
1125        .unwrap();
1126        config.resolve_defaults();
1127
1128        let pool_cell = Arc::new(OnceCell::new());
1129        pool_cell.set(Arc::new(pool.clone())).unwrap();
1130
1131        let mut consumer = SqlConsumer::new(config, pool_cell, None, test_rt());
1132        consumer.stop().await.expect("first stop should succeed");
1133        consumer
1134            .stop()
1135            .await
1136            .expect("second stop should also succeed");
1137    }
1138
1139    // SQL-008: start after stop is rejected
1140    #[tokio::test]
1141    async fn start_after_stop_rejected() {
1142        let pool = sqlite_pool().await;
1143        let mut config = SqlEndpointConfig::from_uri(
1144            "sql:select 1?db_url=sqlite::memory:&initialDelay=0&delay=1",
1145        )
1146        .unwrap();
1147        config.resolve_defaults();
1148
1149        let pool_cell = Arc::new(OnceCell::new());
1150        pool_cell.set(Arc::new(pool.clone())).unwrap();
1151
1152        let mut consumer = SqlConsumer::new(config, pool_cell, None, test_rt());
1153        consumer.stop().await.expect("stop should succeed");
1154
1155        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(8);
1156        tokio::spawn(async move {
1157            loop {
1158                match timeout(Duration::from_secs(2), rx.recv()).await {
1159                    Ok(Some(env)) => {
1160                        if let Some(reply_tx) = env.reply_tx {
1161                            let _ = reply_tx.send(Ok(env.exchange));
1162                        }
1163                    }
1164                    Ok(None) => break, // closed: drain complete
1165                    Err(_) => break,   // stalled: drainer ends
1166                }
1167            }
1168        });
1169        let ctx = ConsumerContext::new(tx, CancellationToken::new(), "sql-test-route".to_string());
1170
1171        let result = consumer.start(ctx).await;
1172        assert!(result.is_err());
1173        let err_msg = result.unwrap_err().to_string();
1174        assert!(
1175            err_msg.contains("cannot be restarted") || err_msg.contains("after stop"),
1176            "Expected restart error, got: {}",
1177            err_msg
1178        );
1179    }
1180
1181    // SQL-021: batch mode per-row post-processing
1182    #[tokio::test]
1183    async fn batch_mode_per_row_post_processing() {
1184        let pool = sqlite_pool().await;
1185        seed_consumer_table(&pool).await;
1186
1187        let mut config = SqlEndpointConfig::from_uri(
1188            "sql:select id, processed, failed from jobs where processed = 0 order by id?db_url=sqlite::memory:&onConsume=update jobs set processed=1 where id=:#id&useIterator=false&initialDelay=0&delay=1",
1189        )
1190        .unwrap();
1191        config.resolve_defaults();
1192
1193        let consumer = SqlConsumer::new(config.clone(), Arc::new(OnceCell::new()), None, test_rt());
1194        let template = parse_query_template(&config.query, config.placeholder).unwrap();
1195
1196        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(8);
1197        tokio::spawn(async move {
1198            loop {
1199                match timeout(Duration::from_secs(2), rx.recv()).await {
1200                    Ok(Some(env)) => {
1201                        if let Some(reply_tx) = env.reply_tx {
1202                            let _ = reply_tx.send(Ok(env.exchange));
1203                        }
1204                    }
1205                    Ok(None) => break, // closed: drain complete
1206                    Err(_) => break,   // stalled: drainer ends
1207                }
1208            }
1209        });
1210        let ctx = ConsumerContext::new(tx, CancellationToken::new(), "sql-test-route".to_string());
1211
1212        consumer
1213            .poll_database(&pool, &ctx, &template)
1214            .await
1215            .expect("poll must succeed");
1216
1217        // SQL-021: Each row should have been processed individually via onConsume
1218        let row = sqlx::query("select processed from jobs where id = 1")
1219            .fetch_one(&pool)
1220            .await
1221            .expect("row 1");
1222        let processed_1: i64 = sqlx::Row::try_get(&row, 0).expect("processed");
1223
1224        let row = sqlx::query("select processed from jobs where id = 2")
1225            .fetch_one(&pool)
1226            .await
1227            .expect("row 2");
1228        let processed_2: i64 = sqlx::Row::try_get(&row, 0).expect("processed");
1229
1230        assert_eq!(
1231            processed_1, 1,
1232            "row 1 should be marked processed via per-row onConsume"
1233        );
1234        assert_eq!(
1235            processed_2, 1,
1236            "row 2 should be marked processed via per-row onConsume"
1237        );
1238    }
1239
1240    // SQL-021: batch mode per-row onConsumeFailed when downstream fails
1241    #[tokio::test]
1242    async fn batch_mode_per_row_post_processing_on_failure() {
1243        let pool = sqlite_pool().await;
1244        seed_consumer_table(&pool).await;
1245
1246        let mut config = SqlEndpointConfig::from_uri(
1247            "sql:select id, processed, failed from jobs where processed = 0 order by id?db_url=sqlite::memory:&onConsumeFailed=update jobs set failed=1 where id=:#id&useIterator=false&initialDelay=0&delay=1",
1248        )
1249        .unwrap();
1250        config.resolve_defaults();
1251
1252        let consumer = SqlConsumer::new(config.clone(), Arc::new(OnceCell::new()), None, test_rt());
1253        let template = parse_query_template(&config.query, config.placeholder).unwrap();
1254
1255        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(8);
1256        tokio::spawn(async move {
1257            loop {
1258                match timeout(Duration::from_secs(2), rx.recv()).await {
1259                    Ok(Some(env)) => {
1260                        if let Some(reply_tx) = env.reply_tx {
1261                            let _ = reply_tx
1262                                .send(Err(CamelError::ProcessorError("downstream boom".into())));
1263                        }
1264                    }
1265                    Ok(None) => break, // closed: drain complete
1266                    Err(_) => break,   // stalled: drainer ends
1267                }
1268            }
1269        });
1270        let ctx = ConsumerContext::new(tx, CancellationToken::new(), "sql-test-route".to_string());
1271
1272        consumer
1273            .poll_database(&pool, &ctx, &template)
1274            .await
1275            .expect("consumer should swallow downstream errors when breakBatchOnConsumeFail=false");
1276
1277        // SQL-021: Each row should have onConsumeFailed executed individually
1278        let row = sqlx::query("select failed from jobs where id = 1")
1279            .fetch_one(&pool)
1280            .await
1281            .expect("row 1");
1282        let failed_1: i64 = sqlx::Row::try_get(&row, 0).expect("failed");
1283
1284        let row = sqlx::query("select failed from jobs where id = 2")
1285            .fetch_one(&pool)
1286            .await
1287            .expect("row 2");
1288        let failed_2: i64 = sqlx::Row::try_get(&row, 0).expect("failed");
1289
1290        assert_eq!(
1291            failed_1, 1,
1292            "row 1 should be marked failed via per-row onConsumeFailed"
1293        );
1294        assert_eq!(
1295            failed_2, 1,
1296            "row 2 should be marked failed via per-row onConsumeFailed"
1297        );
1298    }
1299
1300    #[tokio::test]
1301    async fn bridge_error_handler_routes_poll_errors_to_exchange_error() {
1302        let mut config = config();
1303        config.bridge_error_handler = true;
1304        let consumer = SqlConsumer::new(config, Arc::new(OnceCell::new()), None, test_rt());
1305
1306        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(4);
1307        tokio::spawn(async move {
1308            #[allow(clippy::never_loop)]
1309            loop {
1310                match timeout(Duration::from_secs(2), rx.recv()).await {
1311                    Ok(Some(env)) => {
1312                        assert!(env.exchange.error.is_some(), "exchange must carry error");
1313                        if let Some(reply_tx) = env.reply_tx {
1314                            let _ = reply_tx.send(Ok(env.exchange));
1315                        }
1316                        break;
1317                    }
1318                    Ok(None) => break, // closed: drain complete
1319                    Err(_) => break,   // stalled: drainer ends
1320                }
1321            }
1322        });
1323
1324        let ctx = ConsumerContext::new(tx, CancellationToken::new(), "sql-test-route".to_string());
1325        consumer
1326            .bridge_poll_error(&ctx, CamelError::ProcessorError("poll failed".into()))
1327            .await
1328            .expect("bridging should succeed");
1329    }
1330
1331    /// Regression for ADR-0012: when bridge_error_handler=true, the poll
1332    /// failure must NOT emit error! (the route's error handler owns ERROR
1333    /// for bridged failures). Was previously duplicated at line 429 + 431.
1334    #[tracing_test::traced_test]
1335    #[tokio::test]
1336    async fn bridged_poll_failure_emits_warn_not_error() {
1337        let pool = sqlite_pool().await;
1338        // Do NOT create any table — the query against a non-existent
1339        // table will fail at fetch_all, returning Err BEFORE any
1340        // downstream send (so lines 103/205 are never reached).
1341
1342        let mut config = config();
1343        config.bridge_error_handler = true;
1344        // Query a non-existent table to trigger a query-failure poll error.
1345        config.query = "select * from nonexistent_table".to_string();
1346        config.resolve_defaults();
1347        let consumer = SqlConsumer::new(config.clone(), Arc::new(OnceCell::new()), None, test_rt());
1348        let template = parse_query_template(&config.query, config.placeholder).unwrap();
1349
1350        // Healthy downstream — replies Ok so bridge_poll_error succeeds
1351        // and does NOT emit its own error!.
1352        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(4);
1353        tokio::spawn(async move {
1354            loop {
1355                match timeout(Duration::from_secs(2), rx.recv()).await {
1356                    Ok(Some(env)) => {
1357                        if let Some(reply_tx) = env.reply_tx {
1358                            let _ = reply_tx.send(Ok(env.exchange));
1359                        }
1360                    }
1361                    Ok(None) => break, // closed: drain complete
1362                    Err(_) => break,   // stalled: drainer ends
1363                }
1364            }
1365        });
1366        let ctx = ConsumerContext::new(tx, CancellationToken::new(), "sql-test-route".to_string());
1367
1368        // Drive poll — fetch_all will fail because the table is missing.
1369        consumer.handle_poll_result(&pool, &ctx, &template).await;
1370
1371        // The bridged path must NOT emit ERROR (handler owns it).
1372        assert!(
1373            !logs_contain("ERROR"),
1374            "bridged poll failure must not emit ERROR (handler owns it); check captured logs for stray ERROR lines"
1375        );
1376        // Sanity: warn! was emitted so the failure is still visible.
1377        assert!(
1378            logs_contain("WARN"),
1379            "bridged poll failure should emit warn! for operator visibility"
1380        );
1381    }
1382
1383    /// Regression for ADR-0012 "b-bridged discriminator": when
1384    /// send_and_wait returns Err on a NORMAL-DATA send (i.e., not a
1385    /// deliberate bridge_poll_error handoff), the route handler did NOT
1386    /// absorb the failure (consumer.rs:77-91 contract; error_handler.rs
1387    /// returns Ok in every branch). The consumer's error! is the only
1388    /// ERROR signal for the unhandled failure and MUST stay at error!.
1389    ///
1390    /// Protects consumer.rs:205 (StreamList downstream send) and any
1391    /// future site that uses send_and_wait on a non-bridge path.
1392    #[tracing_test::traced_test]
1393    #[tokio::test]
1394    async fn unbridged_send_and_wait_failure_emits_error_loud() {
1395        let pool = sqlite_pool().await;
1396        sqlx::query("CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT)")
1397            .execute(&pool)
1398            .await
1399            .expect("create table");
1400        sqlx::query("INSERT INTO items (id, name) VALUES (1, 'alpha')")
1401            .execute(&pool)
1402            .await
1403            .expect("seed rows");
1404
1405        let mut config = SqlEndpointConfig::from_uri(
1406            "sql:select id, name from items order by id?db_url=sqlite::memory:&outputType=StreamList&initialDelay=0&delay=1",
1407        )
1408        .unwrap();
1409        config.resolve_defaults();
1410        // Explicitly non-bridged: normal-data send path.
1411        config.bridge_error_handler = false;
1412        let consumer = SqlConsumer::new(
1413            config.clone(),
1414            Arc::new(OnceCell::new()),
1415            None,
1416            Arc::new(RecordingRuntime::new(Arc::new(Mutex::new(Vec::new())))),
1417        );
1418        let template = parse_query_template(&config.query, config.placeholder).unwrap();
1419
1420        // Downstream that returns Err — simulates unhandled route failure.
1421        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(8);
1422        tokio::spawn(async move {
1423            loop {
1424                match timeout(Duration::from_secs(2), rx.recv()).await {
1425                    Ok(Some(env)) => {
1426                        if let Some(reply_tx) = env.reply_tx {
1427                            let _ = reply_tx.send(Err(CamelError::ProcessorError("boom".into())));
1428                        }
1429                    }
1430                    Ok(None) => break, // closed: drain complete
1431                    Err(_) => break,   // stalled: drainer ends
1432                }
1433            }
1434        });
1435        let ctx = ConsumerContext::new(tx, CancellationToken::new(), "sql-test-route".to_string());
1436
1437        let _ = consumer.poll_database(&pool, &ctx, &template).await;
1438
1439        // The unbridged path MUST emit ERROR — consumer owns the signal.
1440        assert!(
1441            logs_contain("ERROR"),
1442            "unbridged send_and_wait failure MUST emit ERROR (consumer owns the signal)"
1443        );
1444    }
1445
1446    /// The lazy StreamList body propagates `row_to_json` failures verbatim:
1447    /// the consumer must surface the typed conversion error (column, driver
1448    /// type, CAST hint), never wrap it in an opaque serialization error.
1449    ///
1450    /// A non-UTF-8 BLOB fetches fine; it fails the UTF-8 branch inside
1451    /// `row_to_json`, which is exactly the wrapped site in
1452    /// `poll_database_stream`.
1453    #[tokio::test]
1454    async fn consumer_stream_body_error_is_typed_not_wrapped() {
1455        let pool = sqlite_pool().await;
1456
1457        let mut config = SqlEndpointConfig::from_uri(
1458            "sql:select 1?db_url=sqlite::memory:&outputType=StreamList&initialDelay=0&delay=1",
1459        )
1460        .unwrap();
1461        config.resolve_defaults();
1462        config.query = "SELECT x'00FF00' AS payload".to_string();
1463        let consumer = SqlConsumer::new(config.clone(), Arc::new(OnceCell::new()), None, test_rt());
1464        let template = parse_query_template(&config.query, config.placeholder).unwrap();
1465        let prepared = resolve_params(
1466            &template,
1467            &Exchange::new(Message::default()),
1468            &config.in_separator,
1469        )
1470        .expect("resolve stream query params");
1471
1472        // Downstream forwards the received stream body through a side channel
1473        // BEFORE replying Ok: the exchange itself is consumed by the producer's
1474        // send_and_wait, only the shared `Arc<Mutex<...>>` reaches the test.
1475        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(8);
1476        let (stream_tx, mut stream_rx) = mpsc::channel::<StreamBody>(1);
1477        tokio::spawn(async move {
1478            match timeout(Duration::from_secs(2), rx.recv()).await {
1479                Ok(Some(env)) => {
1480                    if let Body::Stream(stream_body) = &env.exchange.input.body {
1481                        let _ = stream_tx.send(stream_body.clone()).await;
1482                    }
1483                    if let Some(reply_tx) = env.reply_tx {
1484                        let _ = reply_tx.send(Ok(env.exchange));
1485                    }
1486                }
1487                Ok(None) => {}
1488                Err(_) => {}
1489            }
1490        });
1491        let ctx = ConsumerContext::new(tx, CancellationToken::new(), "sql-test-route".to_string());
1492
1493        consumer
1494            .poll_database_stream(&pool, &ctx, &prepared)
1495            .await
1496            .expect("StreamList poll must succeed eagerly (lazy stream emitted)");
1497
1498        let stream_body = timeout(Duration::from_secs(2), stream_rx.recv())
1499            .await
1500            .expect("downstream must forward the stream body within 2s")
1501            .expect("downstream must receive the stream body");
1502        let mut guard = stream_body.stream.lock().await; // allow-test-wait: stream slot after delivery; no holder
1503        let mut stream = guard.take().expect("stream slot must hold the stream");
1504        drop(guard);
1505
1506        use futures::StreamExt;
1507        let mut items = Vec::new();
1508        while let Some(item) = stream.next().await {
1509            items.push(item);
1510        }
1511
1512        assert_eq!(
1513            items.len(),
1514            1,
1515            "undecodable row must yield exactly one item, got {}",
1516            items.len()
1517        );
1518        let err = match items.remove(0) {
1519            Ok(chunk) => panic!("undecodable column must not yield bytes, got: {chunk:?}"),
1520            Err(e) => e,
1521        };
1522        match err {
1523            CamelError::TypeConversionFailed(msg) => {
1524                assert!(msg.contains("payload"), "column named: {msg}");
1525                assert!(
1526                    !msg.contains("JSON serialization failed"),
1527                    "stream error must not be wrapped: {msg}"
1528                );
1529            }
1530            other => panic!("stream error must be the typed conversion failure, got {other:?}"),
1531        }
1532    }
1533
1534    /// Regression for ADR-0012: when bridge_error_handler=false, the unbridged
1535    /// branch of handle_poll_result MUST emit ERROR for unhandled poll failure.
1536    #[tracing_test::traced_test]
1537    #[tokio::test]
1538    async fn unbridged_handle_poll_result_emits_error_loud() {
1539        let pool = sqlite_pool().await;
1540        // Do NOT create any table — fetch_all will fail in poll_database.
1541
1542        let mut config = config();
1543        config.bridge_error_handler = false;
1544        config.query = "select * from nonexistent_table".to_string();
1545        config.resolve_defaults();
1546        let consumer = SqlConsumer::new(
1547            config.clone(),
1548            Arc::new(OnceCell::new()),
1549            None,
1550            Arc::new(RecordingRuntime::new(Arc::new(Mutex::new(Vec::new())))),
1551        );
1552        let template = parse_query_template(&config.query, config.placeholder).unwrap();
1553
1554        // Healthy downstream task; should not be reached for this poll-failure path.
1555        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(4);
1556        tokio::spawn(async move {
1557            loop {
1558                match timeout(Duration::from_secs(2), rx.recv()).await {
1559                    Ok(Some(env)) => {
1560                        if let Some(reply_tx) = env.reply_tx {
1561                            let _ = reply_tx.send(Ok(env.exchange));
1562                        }
1563                    }
1564                    Ok(None) => break, // closed: drain complete
1565                    Err(_) => break,   // stalled: drainer ends
1566                }
1567            }
1568        });
1569        let ctx = ConsumerContext::new(tx, CancellationToken::new(), "sql-test-route".to_string());
1570
1571        consumer.handle_poll_result(&pool, &ctx, &template).await;
1572
1573        assert!(
1574            logs_contain("ERROR"),
1575            "unbridged handle_poll_result failure MUST emit ERROR (consumer owns signal)"
1576        );
1577    }
1578
1579    #[tokio::test]
1580    async fn stream_list_consumer_emits_ndjson_body() {
1581        let pool = sqlite_pool().await;
1582        sqlx::query("CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT)")
1583            .execute(&pool)
1584            .await
1585            .expect("create table");
1586        sqlx::query("INSERT INTO items (id, name) VALUES (1, 'alpha'), (2, 'beta'), (3, 'gamma')")
1587            .execute(&pool)
1588            .await
1589            .expect("seed rows");
1590
1591        let mut config = SqlEndpointConfig::from_uri(
1592            "sql:select id, name from items order by id?db_url=sqlite::memory:&outputType=StreamList&initialDelay=0&delay=1",
1593        )
1594        .unwrap();
1595        config.resolve_defaults();
1596
1597        let consumer = SqlConsumer::new(config.clone(), Arc::new(OnceCell::new()), None, test_rt());
1598        let template = parse_query_template(&config.query, config.placeholder).unwrap();
1599
1600        let (tx, rx) = mpsc::channel::<ExchangeEnvelope>(8);
1601        let (result_tx, result_rx) = tokio::sync::oneshot::channel::<Exchange>();
1602        tokio::spawn(async move {
1603            let mut rx = rx;
1604            match timeout(Duration::from_secs(2), rx.recv()).await {
1605                Ok(Some(env)) => {
1606                    if let Some(reply_tx) = env.reply_tx {
1607                        let _ = reply_tx.send(Ok(env.exchange.clone()));
1608                    }
1609                    let _ = result_tx.send(env.exchange);
1610                }
1611                Ok(None) => {}
1612                Err(_) => {}
1613            }
1614        });
1615        let ctx = ConsumerContext::new(tx, CancellationToken::new(), "sql-test-route".to_string());
1616
1617        consumer
1618            .poll_database(&pool, &ctx, &template)
1619            .await
1620            .expect("poll must succeed");
1621
1622        let exchange = result_rx.await.expect("should have received one exchange");
1623
1624        match exchange.input.body {
1625            Body::Stream(ref stream_body) => {
1626                let stream = stream_body.stream.clone();
1627                let mut guard = stream.lock().await; // allow-test-wait: stream slot after delivery; no holder
1628                let stream_opt = guard.take();
1629                assert!(stream_opt.is_some(), "stream should be present");
1630
1631                use futures::StreamExt;
1632                let mut collected = Vec::new();
1633                let mut stream = stream_opt.unwrap();
1634                while let Some(chunk) = stream.next().await {
1635                    let chunk = chunk.expect("stream chunk should not error");
1636                    collected.extend_from_slice(&chunk);
1637                }
1638
1639                let ndjson = String::from_utf8(collected).expect("valid utf8");
1640                let lines: Vec<&str> = ndjson.trim().lines().collect();
1641                assert_eq!(lines.len(), 3, "should have 3 NDJSON lines");
1642
1643                let row0: serde_json::Value =
1644                    serde_json::from_str(lines[0]).expect("valid json line 0");
1645                assert_eq!(row0["id"], 1);
1646                assert_eq!(row0["name"], "alpha");
1647
1648                let row1: serde_json::Value =
1649                    serde_json::from_str(lines[1]).expect("valid json line 1");
1650                assert_eq!(row1["id"], 2);
1651                assert_eq!(row1["name"], "beta");
1652
1653                let row2: serde_json::Value =
1654                    serde_json::from_str(lines[2]).expect("valid json line 2");
1655                assert_eq!(row2["id"], 3);
1656                assert_eq!(row2["name"], "gamma");
1657            }
1658            ref other => panic!("expected Body::Stream, got {:?}", other),
1659        }
1660    }
1661
1662    #[tokio::test]
1663    async fn stream_list_consumer_empty_result_set_emits_empty_stream() {
1664        let pool = sqlite_pool().await;
1665        sqlx::query("CREATE TABLE empty_items (id INTEGER PRIMARY KEY, name TEXT)")
1666            .execute(&pool)
1667            .await
1668            .expect("create table");
1669
1670        let mut config = SqlEndpointConfig::from_uri(
1671            "sql:select id, name from empty_items?db_url=sqlite::memory:&outputType=StreamList&initialDelay=0&delay=1",
1672        )
1673        .unwrap();
1674        config.resolve_defaults();
1675
1676        let consumer = SqlConsumer::new(config.clone(), Arc::new(OnceCell::new()), None, test_rt());
1677        let template = parse_query_template(&config.query, config.placeholder).unwrap();
1678
1679        let (tx, rx) = tokio::sync::oneshot::channel();
1680        let (mpsc_tx, mut mpsc_rx) = mpsc::channel::<ExchangeEnvelope>(8);
1681        tokio::spawn(async move {
1682            #[allow(clippy::never_loop)]
1683            loop {
1684                match timeout(Duration::from_secs(2), mpsc_rx.recv()).await {
1685                    Ok(Some(env)) => {
1686                        if let Some(reply_tx) = env.reply_tx {
1687                            let _ = reply_tx.send(Ok(env.exchange.clone()));
1688                        }
1689                        let _ = tx.send(env.exchange);
1690                        break;
1691                    }
1692                    Ok(None) => break, // closed: drain complete
1693                    Err(_) => break,   // stalled: drainer ends
1694                }
1695            }
1696        });
1697        let ctx = ConsumerContext::new(
1698            mpsc_tx,
1699            CancellationToken::new(),
1700            "sql-test-route".to_string(),
1701        );
1702
1703        consumer
1704            .poll_database(&pool, &ctx, &template)
1705            .await
1706            .expect("poll must succeed");
1707
1708        let exchange = rx
1709            .await
1710            .expect("StreamList should emit exchange even for empty results");
1711
1712        match exchange.input.body {
1713            Body::Stream(ref stream_body) => {
1714                let stream = stream_body.stream.clone();
1715                let mut guard = stream.lock().await; // allow-test-wait: stream slot after delivery; no holder
1716                let stream_opt = guard.take();
1717
1718                use futures::StreamExt;
1719                let mut count = 0;
1720                if let Some(mut stream) = stream_opt {
1721                    while let Some(chunk) = stream.next().await {
1722                        let chunk = chunk.expect("stream chunk should not error");
1723                        count += chunk.len();
1724                    }
1725                }
1726                assert_eq!(count, 0, "empty table should produce zero stream bytes");
1727            }
1728            ref other => panic!("expected Body::Stream, got {:?}", other),
1729        }
1730    }
1731
1732    #[tokio::test]
1733    async fn break_on_empty_stops_after_drained_table() {
1734        let pool = sqlite_pool().await;
1735        seed_consumer_table(&pool).await;
1736
1737        // onConsume marks rows processed=1; query selects only processed=0 → drains in one poll.
1738        let mut config = SqlEndpointConfig::from_uri(
1739            "sql:select id from jobs where processed = 0 order by id?db_url=sqlite::memory:&onConsume=update jobs set processed=1 where id=:#id&initialDelay=0&delay=50&breakOnEmpty=true&repeatCount=100",
1740        )
1741        .unwrap();
1742        config.resolve_defaults();
1743
1744        // Inject the seeded pool — start() otherwise self-initializes a disjoint
1745        // sqlite::memory: DB (per-connection private).
1746        let pool_cell = Arc::new(OnceCell::new());
1747        pool_cell
1748            .set(Arc::new(pool.clone()))
1749            .expect("pool cell set");
1750        let mut consumer = SqlConsumer::new(config, pool_cell, None, test_rt());
1751
1752        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(8);
1753        let route_cancel = CancellationToken::new();
1754        // Count envelopes so we can pin the productive poll's row processing.
1755        // With use_iterator=true (default) and 2 seeded rows, the productive poll
1756        // must emit exactly 2 envelopes before the empty poll triggers the break.
1757        let received = Arc::new(std::sync::atomic::AtomicU32::new(0));
1758        let echo_cancel = route_cancel.clone();
1759        let counter = Arc::clone(&received);
1760        // Echo replies so the poll completes.
1761        tokio::spawn(async move {
1762            loop {
1763                tokio::select! {
1764                    _ = echo_cancel.cancelled() => break,
1765                    Some(env) = rx.recv() => {
1766                        counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1767                        if let Some(reply_tx) = env.reply_tx {
1768                            let _ = reply_tx.send(Ok(env.exchange));
1769                        }
1770                    }
1771                }
1772            }
1773        });
1774
1775        let ctx = ConsumerContext::new(tx, route_cancel.clone(), "sql-test-route".to_string());
1776
1777        // start() runs the poll loop to completion (returns when the loop breaks).
1778        let start = tokio::time::Instant::now();
1779        consumer.start(ctx).await.expect("start must succeed");
1780        let elapsed = start.elapsed();
1781
1782        // Productive poll must have emitted exactly 2 envelopes (one per row in
1783        // the seeded table). Locks "no rows skipped, no rows lost".
1784        let n = received.load(std::sync::atomic::Ordering::Relaxed);
1785        assert_eq!(
1786            n, 2,
1787            "productive poll should emit 2 envelopes (2 seeded rows), got {}",
1788            n
1789        );
1790
1791        // Both rows drained (processed=1) by the productive poll.
1792        let count_unprocessed: i64 =
1793            sqlx::query_scalar("select count(*) from jobs where processed = 0")
1794                .fetch_one(&pool)
1795                .await
1796                .expect("count");
1797        assert_eq!(count_unprocessed, 0);
1798
1799        // Upper bound: with delay=10ms and breakOnEmpty, the consumer should stop
1800        // well under the repeatCount=100 ceiling (which would take ~1s).
1801        assert!(
1802            elapsed < std::time::Duration::from_millis(500),
1803            "consumer should have stopped on empty poll, took {:?}",
1804            elapsed
1805        );
1806
1807        // Lower bound — LOCKS the [productive_poll, empty_poll] ordering.
1808        // With delay=50ms:
1809        //   - Correct: at least 2 full delays elapse (1st sleep + 2nd sleep) ≈ 100ms+,
1810        //     because the loop MUST run a second (empty) poll before breaking.
1811        //   - Buggy (break after the productive poll): only the 1st delay elapses
1812        //     ≈ 50ms+processing. 100ms threshold sits safely between the two and
1813        //     would FAIL if the consumer incorrectly set was_empty=true on the
1814        //     productive poll and broke early. Wide margin survives slow CI boxes.
1815        assert!(
1816            elapsed >= std::time::Duration::from_millis(100),
1817            "consumer must run a second (empty) poll before breaking on break_on_empty, \
1818             took {:?} — likely broke after the productive poll without seeing the empty one",
1819            elapsed
1820        );
1821    }
1822
1823    /// Regression: `handle_poll_result` with `break_on_empty=true` must NOT
1824    /// signal `was_empty: true` when `poll_database` returns an error — the
1825    /// loop should continue past the error.
1826    #[tokio::test]
1827    async fn handle_poll_result_error_does_not_signal_empty() {
1828        let pool = sqlite_pool().await;
1829
1830        let mut config = SqlEndpointConfig::from_uri(
1831            "sql:select * from this_table_does_not_exist?db_url=sqlite::memory:&breakOnEmpty=true&initialDelay=0&delay=1",
1832        )
1833        .unwrap();
1834        config.resolve_defaults();
1835
1836        let pool_cell = Arc::new(OnceCell::new());
1837        pool_cell.set(Arc::new(pool.clone())).unwrap();
1838        // Use RecordingRuntime (not test_rt/PanicRuntime) because
1839        // handle_poll_result calls record_post_process_failure → metrics().
1840        let consumer = SqlConsumer::new(
1841            config.clone(),
1842            pool_cell,
1843            None,
1844            Arc::new(RecordingRuntime::new(Arc::new(Mutex::new(Vec::new())))),
1845        );
1846
1847        let template = parse_query_template(&config.query, config.placeholder).unwrap();
1848
1849        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(8);
1850        tokio::spawn(async move {
1851            loop {
1852                match timeout(Duration::from_secs(2), rx.recv()).await {
1853                    Ok(Some(env)) => {
1854                        if let Some(reply_tx) = env.reply_tx {
1855                            let _ = reply_tx.send(Ok(env.exchange));
1856                        }
1857                    }
1858                    Ok(None) => break, // closed: drain complete
1859                    Err(_) => break,   // stalled: drainer ends
1860                }
1861            }
1862        });
1863        let ctx = ConsumerContext::new(tx, CancellationToken::new(), "sql-test-route".to_string());
1864
1865        let outcome = consumer.handle_poll_result(&pool, &ctx, &template).await;
1866        assert!(
1867            !outcome.was_empty,
1868            "poll error must NOT signal empty (was_empty should be false)"
1869        );
1870    }
1871
1872    // ── ADR-0012 (g) regression tests ──────────────────────────────────
1873
1874    /// Fixture: captures `force_unhealthy_for_route` calls.
1875    #[derive(Debug, Default)]
1876    struct RecordingHealth {
1877        forced: Arc<Mutex<Vec<(String, String, String)>>>,
1878    }
1879
1880    impl HealthCheckRegistry for RecordingHealth {
1881        fn force_unhealthy_for_route(&self, route_id: &str, name: &str, reason: &str) {
1882            self.forced.lock().unwrap().push((
1883                route_id.to_string(),
1884                name.to_string(),
1885                reason.to_string(),
1886            ));
1887        }
1888    }
1889
1890    struct NoopMetricsForConsumer;
1891
1892    impl MetricsCollector for NoopMetricsForConsumer {
1893        fn record_exchange_duration(&self, _: &str, _: Duration) {}
1894        fn increment_errors(&self, _: &str, _: &str) {}
1895        fn increment_exchanges(&self, _: &str) {}
1896        fn set_queue_depth(&self, _: &str, _: usize) {}
1897        fn record_circuit_breaker_change(&self, _: &str, _: &str, _: &str) {}
1898    }
1899
1900    struct RecordingRuntimeWithHealth {
1901        health: Arc<RecordingHealth>,
1902    }
1903
1904    impl RuntimeObservability for RecordingRuntimeWithHealth {
1905        fn metrics(&self) -> Arc<dyn MetricsCollector> {
1906            Arc::new(NoopMetricsForConsumer)
1907        }
1908        fn health(&self) -> Arc<dyn HealthCheckRegistry> {
1909            self.health.clone()
1910        }
1911    }
1912
1913    /// Regression: consumer pool init failure calls force_unhealthy_for_route
1914    /// with correct route_id + name "g:sql:consumer-pool-init" + non-empty reason.
1915    #[tokio::test]
1916    async fn consumer_pool_init_failure_calls_force_unhealthy_for_route() {
1917        let health = Arc::new(RecordingHealth::default());
1918        let recorded_health = health.clone();
1919        let rt: Arc<dyn RuntimeObservability> = Arc::new(RecordingRuntimeWithHealth { health });
1920
1921        let mut config = SqlEndpointConfig::from_uri(
1922            "sql:select 1?db_url=postgres://nonexistent-host:5432/nonexistent_db&retryEnabled=false&initialDelay=0&delay=1",
1923        )
1924        .unwrap();
1925        config.max_connections = Some(1);
1926        config.min_connections = Some(0);
1927        config.idle_timeout_secs = Some(300);
1928        config.max_lifetime_secs = Some(1800);
1929
1930        let mut consumer = SqlConsumer::new(config, Arc::new(OnceCell::new()), None, rt);
1931
1932        let (tx, _rx) = mpsc::channel(8);
1933        let ctx = ConsumerContext::new(
1934            tx,
1935            CancellationToken::new(),
1936            "sql-consumer-test-route".to_string(),
1937        );
1938
1939        let result = consumer.start(ctx).await;
1940        assert!(result.is_err(), "pool init should fail with bad db_url");
1941
1942        let forced = recorded_health.forced.lock().unwrap();
1943        assert_eq!(
1944            forced.len(),
1945            1,
1946            "expected one force_unhealthy_for_route call"
1947        );
1948        assert_eq!(forced[0].0, "sql-consumer-test-route");
1949        assert_eq!(forced[0].1, "g:sql:consumer-pool-init");
1950        assert!(!forced[0].2.is_empty(), "reason should be non-empty");
1951    }
1952
1953    /// Regression: max_attempts=N → exactly N invocations (caught OpenSearch off-by-one 1f5c4c2a).
1954    /// Replicates the exact retry loop from SqlConsumer::start() (consumer.rs:343-367):
1955    ///   attempt starts at 0, incremented at top, should_retry(attempt), delay_for(attempt-1)
1956    #[tokio::test]
1957    async fn retry_loop_invokes_operation_exactly_max_attempts_times() {
1958        use camel_component_api::NetworkRetryPolicy;
1959        use std::sync::Arc;
1960        use std::sync::atomic::{AtomicU32, Ordering};
1961
1962        let policy = NetworkRetryPolicy {
1963            max_attempts: 3,
1964            initial_delay: Duration::from_millis(1),
1965            max_delay: Duration::from_millis(1),
1966            multiplier: 1.0,
1967            ..NetworkRetryPolicy::default()
1968        };
1969
1970        let calls = Arc::new(AtomicU32::new(0));
1971        let calls_clone = Arc::clone(&calls);
1972
1973        let mut attempt: u32 = 0;
1974        let _result: Result<(), ()> = tokio::time::timeout(Duration::from_secs(30), async {
1975            loop {
1976                attempt += 1;
1977                calls_clone.fetch_add(1, Ordering::SeqCst);
1978                let op_result: Result<(), ()> = Err(());
1979                match op_result {
1980                    Ok(v) => break Ok(v),
1981                    Err(_) if policy.should_retry(attempt) => {
1982                        let delay = policy.delay_for(attempt - 1);
1983                        tokio::time::sleep(delay).await;
1984                        continue;
1985                    }
1986                    Err(_) => break Err(()),
1987                }
1988            }
1989        })
1990        .await
1991        .expect("retry loop must finish within 30s");
1992
1993        assert_eq!(
1994            calls.load(Ordering::SeqCst),
1995            3,
1996            "max_attempts=3 must yield exactly 3 invocations"
1997        );
1998    }
1999
2000    // ── break_on_empty edge-case tests ──────────────────────────────────
2001
2002    #[tokio::test]
2003    #[tracing_test::traced_test]
2004    async fn break_on_empty_ignored_in_streamlist() {
2005        let pool = sqlite_pool().await;
2006        seed_consumer_table(&pool).await;
2007
2008        // StreamList + breakOnEmpty=true: warn must fire, breakOnEmpty ignored
2009        // (no break on empty — rows flow lazily). repeatCount=3 to distinguish
2010        // "ran 3 polls" from "broke on poll 1".
2011        let mut config = SqlEndpointConfig::from_uri(
2012            "sql:select id from jobs?db_url=sqlite::memory:&outputType=StreamList&initialDelay=0&delay=1&breakOnEmpty=true&repeatCount=3",
2013        )
2014        .unwrap();
2015        config.resolve_defaults();
2016        assert_eq!(config.output_type, SqlOutputType::StreamList);
2017        assert!(config.break_on_empty);
2018
2019        let pool_cell = Arc::new(OnceCell::new());
2020        pool_cell
2021            .set(Arc::new(pool.clone()))
2022            .expect("pool cell set");
2023        let mut consumer = SqlConsumer::new(config, pool_cell, None, test_rt());
2024
2025        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(8);
2026        let route_cancel = CancellationToken::new();
2027        let received = Arc::new(std::sync::atomic::AtomicU32::new(0));
2028        let echo_cancel = route_cancel.clone();
2029        let counter = Arc::clone(&received);
2030        tokio::spawn(async move {
2031            loop {
2032                tokio::select! {
2033                    _ = echo_cancel.cancelled() => break,
2034                    Some(env) = rx.recv() => {
2035                        counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2036                        if let Some(reply_tx) = env.reply_tx {
2037                            let _ = reply_tx.send(Ok(env.exchange));
2038                        }
2039                    }
2040                }
2041            }
2042        });
2043
2044        let ctx = ConsumerContext::new(tx, route_cancel, "sql-test-route".to_string());
2045        consumer.start(ctx).await.expect("start must succeed");
2046
2047        // The startup warn must name breakOnEmpty (FAILS before Step 2 — current
2048        // warn message omits it).
2049        assert!(
2050            logs_contain("breakOnEmpty"),
2051            "expected StreamList warn naming breakOnEmpty"
2052        );
2053
2054        // Counter must prove the stream ran multiple polls (no early break).
2055        // repeatCount=3 with delay=1ms means 3 polls; even accounting for race
2056        // the counter must be >=2 if no early break.
2057        assert!(
2058            received.load(std::sync::atomic::Ordering::Relaxed) >= 2,
2059            "StreamList must not break early with breakOnEmpty, got {} exchanges",
2060            received.load(std::sync::atomic::Ordering::Relaxed)
2061        );
2062    }
2063
2064    #[tokio::test]
2065    async fn break_on_empty_false_default_loops_on_empty() {
2066        let pool = sqlite_pool().await;
2067        // Empty table (seed then drain) — every poll returns 0 rows.
2068        seed_consumer_table(&pool).await;
2069        sqlx::query("delete from jobs")
2070            .execute(&pool)
2071            .await
2072            .expect("drain");
2073
2074        // breakOnEmpty NOT set (default false); repeatCount=3 so the loop must run
2075        // all 3 polls (NOT break on the first empty poll). delay=20ms each.
2076        let mut config = SqlEndpointConfig::from_uri(
2077            "sql:select id from jobs where processed = 0?db_url=sqlite::memory:&initialDelay=0&delay=20&repeatCount=3",
2078        )
2079        .unwrap();
2080        config.resolve_defaults();
2081        assert!(!config.break_on_empty);
2082
2083        let pool_cell = Arc::new(OnceCell::new());
2084        pool_cell
2085            .set(Arc::new(pool.clone()))
2086            .expect("pool cell set");
2087        let mut consumer = SqlConsumer::new(config, pool_cell, None, test_rt());
2088
2089        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(8);
2090        let route_cancel = CancellationToken::new();
2091        let echo_cancel = route_cancel.clone();
2092        tokio::spawn(async move {
2093            loop {
2094                tokio::select! {
2095                    _ = echo_cancel.cancelled() => break,
2096                    Some(env) = rx.recv() => {
2097                        if let Some(reply_tx) = env.reply_tx {
2098                            let _ = reply_tx.send(Ok(env.exchange));
2099                        }
2100                    }
2101                }
2102            }
2103        });
2104
2105        let ctx = ConsumerContext::new(tx, route_cancel, "sql-test-route".to_string());
2106        let start = tokio::time::Instant::now();
2107        consumer.start(ctx).await.expect("start must succeed");
2108        let elapsed = start.elapsed();
2109
2110        // Regression guard: with breakOnEmpty=false + repeatCount=3 + delay=20ms,
2111        // the loop runs all 3 polls (~60ms). If breakOnEmpty were mis-defaulted to
2112        // true, it would break on poll 1 (~20ms). Assert the full window ran.
2113        assert!(
2114            elapsed >= std::time::Duration::from_millis(55),
2115            "consumer should run all 3 polls (breakOnEmpty=false), took {:?}",
2116            elapsed
2117        );
2118    }
2119
2120    #[tokio::test]
2121    async fn break_on_empty_with_route_empty_result_set() {
2122        let pool = sqlite_pool().await;
2123        seed_consumer_table(&pool).await;
2124        sqlx::query("delete from jobs")
2125            .execute(&pool)
2126            .await
2127            .expect("drain");
2128        // Side-effect table for onConsumeBatchComplete: each fire of the
2129        // batch-complete callback increments `n` exactly once. With
2130        // breakOnEmpty=true on an empty table, the spec pins that the
2131        // empty-poll fall-through fires the callback exactly once before
2132        // termination.
2133        sqlx::query("CREATE TABLE batch_marks (n INTEGER NOT NULL DEFAULT 0)")
2134            .execute(&pool)
2135            .await
2136            .expect("create batch_marks");
2137        sqlx::query("INSERT INTO batch_marks (n) VALUES (0)")
2138            .execute(&pool)
2139            .await
2140            .expect("seed batch_marks");
2141
2142        // Empty table + routeEmptyResultSet=true: empty polls fall through to the
2143        // batch path (emit empty result) instead of early-returning. breakOnEmpty=true
2144        // must break AFTER that batch processing → exactly one downstream exchange.
2145        // onConsumeBatchComplete is wired so we can observe the empty-poll fall-through.
2146        let mut config = SqlEndpointConfig::from_uri(
2147            "sql:select id from jobs where processed = 0?db_url=sqlite::memory:&routeEmptyResultSet=true&breakOnEmpty=true&useIterator=false&onConsumeBatchComplete=update batch_marks set n = n + 1&initialDelay=0&delay=10&repeatCount=100",
2148        )
2149        .unwrap();
2150        config.resolve_defaults();
2151
2152        let pool_cell = Arc::new(OnceCell::new());
2153        pool_cell
2154            .set(Arc::new(pool.clone()))
2155            .expect("pool cell set");
2156        let mut consumer = SqlConsumer::new(config, pool_cell, None, test_rt());
2157
2158        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(8);
2159        let route_cancel = CancellationToken::new();
2160        let received = Arc::new(std::sync::atomic::AtomicU32::new(0));
2161        let echo_cancel = route_cancel.clone();
2162        let counter = Arc::clone(&received);
2163        tokio::spawn(async move {
2164            loop {
2165                tokio::select! {
2166                    _ = echo_cancel.cancelled() => break,
2167                    Some(env) = rx.recv() => {
2168                        counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2169                        if let Some(reply_tx) = env.reply_tx {
2170                            let _ = reply_tx.send(Ok(env.exchange));
2171                        }
2172                    }
2173                }
2174            }
2175        });
2176
2177        let ctx = ConsumerContext::new(tx, route_cancel, "sql-test-route".to_string());
2178        let start = tokio::time::Instant::now();
2179        consumer.start(ctx).await.expect("start must succeed");
2180
2181        // Exactly one downstream exchange emitted (the first empty poll's empty result),
2182        // then breakOnEmpty stopped the loop. Must NOT be 0 (route_empty honored) and
2183        // must NOT be repeatCount=100 (break_on_empty honored).
2184        let n = received.load(std::sync::atomic::Ordering::Relaxed);
2185        assert_eq!(n, 1, "expected exactly 1 empty-result exchange, got {}", n);
2186        assert!(
2187            start.elapsed() < std::time::Duration::from_millis(500),
2188            "consumer should have stopped after the first empty poll, took {:?}",
2189            start.elapsed()
2190        );
2191
2192        // onConsumeBatchComplete must fire exactly once on the empty-poll
2193        // fall-through before the loop breaks. A buggy version that broke
2194        // before invoking the batch callback would leave n=0; a version
2195        // that looped through repeatCount=100 would leave n=100.
2196        let batch_fires: i64 = sqlx::query_scalar("select n from batch_marks")
2197            .fetch_one(&pool)
2198            .await
2199            .expect("batch_marks n");
2200        assert_eq!(
2201            batch_fires, 1,
2202            "onConsumeBatchComplete must fire exactly once on the empty-poll \
2203             fall-through before break_on_empty, got {}",
2204            batch_fires
2205        );
2206    }
2207
2208    #[tokio::test]
2209    async fn repeat_count_zero_polls_never() {
2210        let pool = sqlite_pool().await;
2211        seed_consumer_table(&pool).await;
2212
2213        // repeatCount=0 → consumer exits before the first poll (guard at loop top).
2214        let mut config = SqlEndpointConfig::from_uri(
2215            "sql:select id from jobs?db_url=sqlite::memory:&initialDelay=0&delay=1&repeatCount=0&onConsume=update jobs set processed=1 where id=:#id",
2216        )
2217        .unwrap();
2218        config.resolve_defaults();
2219
2220        // Inject the seeded pool — start() otherwise self-initializes a disjoint
2221        // sqlite::memory: DB (per-connection private). Pattern: consumer.rs:967-970.
2222        let pool_cell = Arc::new(OnceCell::new());
2223        pool_cell
2224            .set(Arc::new(pool.clone()))
2225            .expect("pool cell set");
2226        let mut consumer = SqlConsumer::new(config, pool_cell, None, test_rt());
2227
2228        let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(8);
2229        let route_cancel = CancellationToken::new();
2230        let echo_cancel = route_cancel.clone();
2231        tokio::spawn(async move {
2232            loop {
2233                tokio::select! {
2234                    _ = echo_cancel.cancelled() => break,
2235                    Some(env) = rx.recv() => {
2236                        if let Some(reply_tx) = env.reply_tx {
2237                            let _ = reply_tx.send(Ok(env.exchange));
2238                        }
2239                    }
2240                }
2241            }
2242        });
2243
2244        let ctx = ConsumerContext::new(tx, route_cancel, "sql-test-route".to_string());
2245        consumer.start(ctx).await.expect("start must succeed");
2246
2247        // No poll ran → rows are untouched (processed=0).
2248        let count_processed: i64 =
2249            sqlx::query_scalar("select count(*) from jobs where processed = 1")
2250                .fetch_one(&pool)
2251                .await
2252                .expect("count");
2253        assert_eq!(count_processed, 0, "repeatCount=0 must not poll");
2254    }
2255}