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