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