delta-funnel 0.3.1

Lightweight, fast Delta Lake to SQL Server loads with DataFusion SQL and native TDS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
//! Explicit runtime boundary for blocking host integrations.
//!
//! The core session API remains async-friendly. This wrapper owns the Tokio
//! runtime needed by synchronous hosts such as a future PyO3 package, while
//! provider, handoff, and sink modules stay async/pull-driven and do not own a
//! hidden process-level runtime.

use tokio::runtime::{Builder, Handle, Runtime};

#[cfg(test)]
use super::session::OrchestratorMssqlOutputWriter;
#[cfg(test)]
use crate::MssqlWorkflowOutputWriter;
use crate::{
    DeltaFunnelError, DeltaFunnelSession, DeltaSourceConfig, ExecutionProfileMode, LazyTable,
    MssqlDryRunOutputReport, MssqlDryRunWorkflowReport, MssqlWriteReport, OutputWritePlan,
    PreviewOptions, TablePreview, WriteAllOptions, WriteAllReport, progress::ProgressReporter,
};

/// Blocking runtime boundary for high-level Delta Funnel session actions.
///
/// This type is intended to be owned by synchronous host bindings. Constructing
/// it only creates a Tokio runtime; it does not register sources, plan SQL,
/// execute DataFusion, contact SQL Server, or write rows.
///
/// The blocking methods are intended for non-async host threads. Rust async
/// callers should use [`DeltaFunnelSession`] async methods directly. Calling
/// these methods from inside an active Tokio runtime returns a configuration
/// error instead of relying on Tokio's nested-runtime panic.
pub struct DeltaFunnelRuntime {
    runtime: Runtime,
}

impl DeltaFunnelRuntime {
    /// Creates a multi-threaded Tokio runtime for blocking host integrations.
    ///
    /// # Errors
    ///
    /// Returns a configuration error if Tokio cannot create the runtime.
    pub fn new() -> Result<Self, DeltaFunnelError> {
        let runtime = Builder::new_multi_thread()
            .enable_all()
            .thread_name("delta-funnel-runtime")
            .build()
            .map_err(|error| DeltaFunnelError::Config {
                message: format!("failed to create DeltaFunnel runtime: {error}"),
            })?;

        Ok(Self { runtime })
    }

    /// Runs async SQL table planning for a synchronous host.
    ///
    /// # Errors
    ///
    /// Returns the same error as [`DeltaFunnelSession::table_from_sql`].
    pub fn table_from_sql(
        &self,
        session: &mut DeltaFunnelSession,
        sql: &str,
    ) -> Result<LazyTable, DeltaFunnelError> {
        reject_nested_runtime()?;
        self.runtime.block_on(session.table_from_sql(sql))
    }

    /// Registers one Delta source and reports its live lifecycle to the caller.
    ///
    /// Registration is synchronous and does not enter this type's Tokio
    /// runtime. The runtime wrapper exists as the public bridge used by
    /// synchronous host bindings.
    #[doc(hidden)]
    pub fn delta_lake_with_progress(
        &self,
        session: &mut DeltaFunnelSession,
        source: DeltaSourceConfig,
        reporter: ProgressReporter,
    ) -> Result<LazyTable, DeltaFunnelError> {
        session.delta_lake_with_progress(source, reporter)
    }

    /// Runs a bounded lazy table preview for a synchronous host.
    ///
    /// # Errors
    ///
    /// Returns the same error as [`DeltaFunnelSession::preview_table`].
    pub fn preview_table(
        &self,
        session: &DeltaFunnelSession,
        table: &LazyTable,
        limit: usize,
    ) -> Result<TablePreview, DeltaFunnelError> {
        self.preview_table_with_options(session, table, PreviewOptions::new(limit))
    }

    /// Runs a bounded preview with explicit profiling options.
    ///
    /// # Errors
    ///
    /// Returns the same error as [`DeltaFunnelSession::preview_table_with_options`].
    pub fn preview_table_with_options(
        &self,
        session: &DeltaFunnelSession,
        table: &LazyTable,
        options: PreviewOptions,
    ) -> Result<TablePreview, DeltaFunnelError> {
        reject_nested_runtime()?;
        self.runtime
            .block_on(session.preview_table_with_options(table, options))
    }

    /// Runs a bounded preview and reports its live lifecycle to the caller.
    #[doc(hidden)]
    pub fn preview_table_with_progress(
        &self,
        session: &DeltaFunnelSession,
        table: &LazyTable,
        limit: usize,
        reporter: ProgressReporter,
    ) -> Result<TablePreview, DeltaFunnelError> {
        reject_nested_runtime()?;
        self.runtime
            .block_on(session.preview_table_with_progress(table, limit, reporter))
    }

    /// Runs an option-bearing bounded preview with live progress reporting.
    #[doc(hidden)]
    pub fn preview_table_with_options_and_progress(
        &self,
        session: &DeltaFunnelSession,
        table: &LazyTable,
        options: PreviewOptions,
        reporter: ProgressReporter,
    ) -> Result<TablePreview, DeltaFunnelError> {
        reject_nested_runtime()?;
        self.runtime
            .block_on(session.preview_table_with_options_and_progress(table, options, reporter))
    }

    /// Runs a single-output dry run through the high-level session API.
    ///
    /// # Errors
    ///
    /// Returns the same error as [`DeltaFunnelSession::dry_run_to_mssql`].
    pub fn dry_run_to_mssql(
        &self,
        session: &DeltaFunnelSession,
        request: &OutputWritePlan,
    ) -> Result<MssqlDryRunOutputReport, DeltaFunnelError> {
        reject_nested_runtime()?;
        session.dry_run_to_mssql(request)
    }

    /// Runs a single-output dry run with a workspace host progress reporter.
    #[doc(hidden)]
    pub fn dry_run_to_mssql_with_progress(
        &self,
        session: &DeltaFunnelSession,
        request: &OutputWritePlan,
        reporter: ProgressReporter,
    ) -> Result<MssqlDryRunOutputReport, DeltaFunnelError> {
        reject_nested_runtime()?;
        session.dry_run_to_mssql_with_reporter(request, reporter)
    }

    /// Runs a multi-output dry run through the high-level session API.
    ///
    /// # Errors
    ///
    /// Returns the same error as [`DeltaFunnelSession::dry_run_all_to_mssql`].
    pub fn dry_run_all_to_mssql(
        &self,
        session: &DeltaFunnelSession,
        requests: &[OutputWritePlan],
    ) -> Result<MssqlDryRunWorkflowReport, DeltaFunnelError> {
        reject_nested_runtime()?;
        session.dry_run_all_to_mssql_with_tracing(requests)
    }

    /// Runs a multi-output dry run and reports its live progress to the caller.
    ///
    /// Progress describes work while it is happening. The returned report
    /// describes the completed dry-run result. Reporting progress does not
    /// change that result.
    #[doc(hidden)]
    pub fn dry_run_all_to_mssql_with_progress(
        &self,
        session: &DeltaFunnelSession,
        requests: &[OutputWritePlan],
        reporter: ProgressReporter,
    ) -> Result<MssqlDryRunWorkflowReport, DeltaFunnelError> {
        reject_nested_runtime()?;
        session.dry_run_all_to_mssql_with_observability(requests, Some(reporter))
    }

    /// Runs a multi-output dry run with source scan-summary options.
    ///
    /// # Errors
    ///
    /// Returns the same error as
    /// [`DeltaFunnelSession::dry_run_all_to_mssql_with_scan_summary`].
    pub fn dry_run_all_to_mssql_with_scan_summary(
        &self,
        session: &DeltaFunnelSession,
        requests: &[OutputWritePlan],
    ) -> Result<MssqlDryRunWorkflowReport, DeltaFunnelError> {
        reject_nested_runtime()?;
        self.runtime
            .block_on(session.dry_run_all_to_mssql_with_scan_summary_with_tracing(requests))
    }

    /// Blocks on one selected output write.
    ///
    /// # Errors
    ///
    /// Returns the same error as [`DeltaFunnelSession::write_to_mssql`].
    pub fn write_to_mssql(
        &self,
        session: &DeltaFunnelSession,
        request: &OutputWritePlan,
    ) -> Result<MssqlWriteReport, DeltaFunnelError> {
        self.write_to_mssql_with_profile_mode(session, request, ExecutionProfileMode::Disabled)
    }

    /// Blocks on one selected output write with optional detailed query profiling.
    ///
    /// # Errors
    ///
    /// Returns the same error as
    /// [`DeltaFunnelSession::write_to_mssql_with_profile_mode`].
    pub fn write_to_mssql_with_profile_mode(
        &self,
        session: &DeltaFunnelSession,
        request: &OutputWritePlan,
        profile_mode: ExecutionProfileMode,
    ) -> Result<MssqlWriteReport, DeltaFunnelError> {
        reject_nested_runtime()?;
        self.runtime
            .block_on(session.write_to_mssql_with_profile_mode(request, profile_mode))
    }

    /// Blocks on one selected output write with a workspace host progress reporter.
    #[doc(hidden)]
    pub fn write_to_mssql_with_progress(
        &self,
        session: &DeltaFunnelSession,
        request: &OutputWritePlan,
        reporter: ProgressReporter,
    ) -> Result<MssqlWriteReport, DeltaFunnelError> {
        reject_nested_runtime()?;
        self.runtime
            .block_on(session.write_to_mssql_with_reporter(request, reporter))
    }

    /// Blocks on one profiled output write with a workspace host progress reporter.
    #[doc(hidden)]
    pub fn write_to_mssql_with_profile_mode_and_progress(
        &self,
        session: &DeltaFunnelSession,
        request: &OutputWritePlan,
        profile_mode: ExecutionProfileMode,
        reporter: ProgressReporter,
    ) -> Result<MssqlWriteReport, DeltaFunnelError> {
        reject_nested_runtime()?;
        self.runtime
            .block_on(session.write_to_mssql_with_profile_mode_and_reporter(
                request,
                profile_mode,
                reporter,
            ))
    }

    #[cfg(test)]
    pub(crate) fn write_to_mssql_with_writer<W>(
        &self,
        session: &DeltaFunnelSession,
        request: &OutputWritePlan,
        writer: &mut W,
    ) -> Result<MssqlWriteReport, DeltaFunnelError>
    where
        W: OrchestratorMssqlOutputWriter,
    {
        reject_nested_runtime()?;
        self.runtime
            .block_on(session.write_to_mssql_with_writer(request, writer))
    }

    /// Blocks on the default multi-output write workflow.
    ///
    /// # Errors
    ///
    /// Returns the same error as [`DeltaFunnelSession::write_all`].
    pub fn write_all(
        &self,
        session: &DeltaFunnelSession,
        requests: &[OutputWritePlan],
    ) -> Result<WriteAllReport, DeltaFunnelError> {
        reject_nested_runtime()?;
        self.runtime.block_on(session.write_all(requests))
    }

    /// Blocks on the multi-output write workflow with explicit options.
    ///
    /// # Errors
    ///
    /// Returns the same error as [`DeltaFunnelSession::write_all_with_options`].
    pub fn write_all_with_options(
        &self,
        session: &DeltaFunnelSession,
        requests: &[OutputWritePlan],
        options: WriteAllOptions,
    ) -> Result<WriteAllReport, DeltaFunnelError> {
        reject_nested_runtime()?;
        self.runtime
            .block_on(session.write_all_with_options(requests, options))
    }

    /// Runs a multi-output write and reports its live progress to the caller.
    ///
    /// Progress describes work while it is happening. The returned report
    /// describes the completed per-output results. Reporting progress does not
    /// change those results.
    #[doc(hidden)]
    pub fn write_all_with_progress(
        &self,
        session: &DeltaFunnelSession,
        requests: &[OutputWritePlan],
        options: WriteAllOptions,
        reporter: ProgressReporter,
    ) -> Result<WriteAllReport, DeltaFunnelError> {
        reject_nested_runtime()?;
        self.runtime
            .block_on(session.write_all_with_progress(requests, options, reporter))
    }

    #[cfg(test)]
    pub(crate) fn write_all_with_writer<W>(
        &self,
        session: &DeltaFunnelSession,
        requests: &[OutputWritePlan],
        writer: W,
    ) -> Result<WriteAllReport, DeltaFunnelError>
    where
        W: MssqlWorkflowOutputWriter,
    {
        reject_nested_runtime()?;
        self.runtime
            .block_on(session.write_all_with_writer(requests, writer))
    }
}

fn reject_nested_runtime() -> Result<(), DeltaFunnelError> {
    if Handle::try_current().is_ok() {
        return Err(DeltaFunnelError::Config {
            message: "DeltaFunnelRuntime blocking methods cannot be called from inside an active Tokio runtime; use DeltaFunnelSession async APIs directly".to_owned(),
        });
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use std::sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    };

    use super::*;
    use async_trait::async_trait;
    use datafusion::arrow::datatypes::SchemaRef;
    use futures_util::StreamExt;

    use crate::{
        DeltaSourceConfig, DryRunScanSummaryMode, LoadMode, MssqlConnectionConfig,
        MssqlConnectionSource, MssqlOutputBatchStream, MssqlOutputTarget, MssqlTargetCleanupStatus,
        MssqlTargetConfig, MssqlTargetOutputPlan, MssqlTargetTable, MssqlWriteBackend,
        MssqlWriteFailureContext, MssqlWritePhase, ResolvedMssqlTarget, RunMode, SessionOptions,
        ValidationOptions, table_formats::RealParquetDeltaTable,
    };

    fn secret_connection() -> Result<MssqlConnectionConfig, DeltaFunnelError> {
        Ok(MssqlConnectionConfig::new(
            "server=tcp:sql.example.com;database=warehouse;user=admin;password=secret-token",
        )?
        .with_display_label("warehouse-primary"))
    }

    fn output_request(
        table: LazyTable,
        output_name: &str,
        target_table: &str,
    ) -> Result<OutputWritePlan, DeltaFunnelError> {
        let target = MssqlTargetConfig::new(MssqlTargetTable::new("dbo", target_table)?)
            .with_load_mode(LoadMode::AppendExisting);

        Ok(OutputWritePlan::new(
            table,
            MssqlOutputTarget::new(output_name, target, RunMode::DryRun),
        ))
    }

    fn execute_output_request(
        table: LazyTable,
        output_name: &str,
        target_table: &str,
        load_mode: LoadMode,
    ) -> Result<OutputWritePlan, DeltaFunnelError> {
        let target = MssqlTargetConfig::new(MssqlTargetTable::new("dbo", target_table)?)
            .with_load_mode(load_mode);

        Ok(OutputWritePlan::new(
            table,
            MssqlOutputTarget::new(output_name, target, RunMode::Execute),
        ))
    }

    #[test]
    fn runtime_preview_table_returns_limited_formatted_rows() -> Result<(), DeltaFunnelError> {
        let runtime = DeltaFunnelRuntime::new()?;
        let mut session = DeltaFunnelSession::new(SessionOptions::default())?;
        let table = runtime.table_from_sql(
            &mut session,
            "select 'open' as status union all select 'closed' as status order by status desc",
        )?;

        let preview = runtime.preview_table(&session, &table, 1)?;

        assert!(preview.text().contains("| status |"));
        assert!(
            preview
                .text()
                .lines()
                .any(|line| line.contains("| open   |"))
        );
        assert!(
            !preview
                .text()
                .lines()
                .any(|line| line.contains("| closed |"))
        );
        Ok(())
    }

    #[derive(Debug, Clone, PartialEq, Eq)]
    struct FakeRuntimeWriteCall {
        output_name: String,
        target_table: MssqlTargetTable,
        connection_source: MssqlConnectionSource,
        rows: u64,
        batches: u64,
        schema_fields: usize,
    }

    #[derive(Default)]
    struct FakeRuntimeWriter {
        calls: Vec<FakeRuntimeWriteCall>,
    }

    #[async_trait]
    impl OrchestratorMssqlOutputWriter for FakeRuntimeWriter {
        async fn write_output(
            &mut self,
            output_plan: MssqlTargetOutputPlan,
            resolved_target: ResolvedMssqlTarget,
            mut batches: MssqlOutputBatchStream,
            _write_backend: MssqlWriteBackend,
            _validation_options: ValidationOptions,
            _reporter: Option<&ProgressReporter>,
        ) -> Result<MssqlWriteReport, DeltaFunnelError> {
            let mut rows = 0_u64;
            let mut batch_count = 0_u64;

            while let Some(batch) = batches.next().await {
                let cleanup = match output_plan.load_mode() {
                    LoadMode::AppendExisting => MssqlTargetCleanupStatus::NotApplicable,
                    LoadMode::CreateAndLoad | LoadMode::Replace => {
                        MssqlTargetCleanupStatus::NotAttempted
                    }
                };
                let batch = batch.map_err(|error| DeltaFunnelError::MssqlWritePhase {
                    context: Box::new(MssqlWriteFailureContext::from_output_plan(
                        &output_plan,
                        MssqlWritePhase::PollBatchStream,
                        rows,
                        batch_count,
                        0,
                        rows != 0,
                        cleanup,
                    )),
                    message: error.to_string(),
                })?;
                rows = rows.saturating_add(crate::usize_to_u64_saturating(batch.num_rows()));
                batch_count = batch_count.saturating_add(1);
            }

            self.calls.push(FakeRuntimeWriteCall {
                output_name: resolved_target.output_name().to_owned(),
                target_table: resolved_target.table().clone(),
                connection_source: resolved_target.connection_source(),
                rows,
                batches: batch_count,
                schema_fields: output_plan.schema_mappings().len(),
            });

            Ok(MssqlWriteReport::from_output_plan(
                &output_plan,
                rows,
                batch_count,
                0,
                false,
                MssqlTargetCleanupStatus::NotApplicable,
            ))
        }
    }

    #[async_trait]
    impl MssqlWorkflowOutputWriter for FakeRuntimeWriter {
        async fn write_output(
            &mut self,
            output_schema: SchemaRef,
            resolved_target: ResolvedMssqlTarget,
            schema_options: crate::MssqlSchemaPlanOptions,
            batches: MssqlOutputBatchStream,
            write_backend: MssqlWriteBackend,
            validation_options: ValidationOptions,
            reporter: Option<&ProgressReporter>,
        ) -> Result<MssqlWriteReport, DeltaFunnelError> {
            let output_plan = crate::plan_mssql_target_for_resolved_output(
                output_schema.as_ref(),
                &resolved_target,
                schema_options,
            )?;

            OrchestratorMssqlOutputWriter::write_output(
                self,
                output_plan,
                resolved_target,
                batches,
                write_backend,
                validation_options,
                reporter,
            )
            .await
        }
    }

    #[test]
    fn runtime_constructs_without_starting_session_work() -> Result<(), DeltaFunnelError> {
        let _runtime = DeltaFunnelRuntime::new()?;

        Ok(())
    }

    #[test]
    fn runtime_drives_table_sql_and_single_output_dry_run() -> Result<(), DeltaFunnelError> {
        let runtime = DeltaFunnelRuntime::new()?;
        let mut session = DeltaFunnelSession::new(
            SessionOptions::new().with_default_mssql_connection(secret_connection()?),
        )?;
        let output = runtime.table_from_sql(&mut session, "select 1 as id")?;
        let request = output_request(output, "orders_output", "orders_sink")?;
        let deliveries = Arc::new(AtomicUsize::new(0));
        let callback_deliveries = Arc::clone(&deliveries);
        let reporter = ProgressReporter::new(move |_| {
            callback_deliveries.fetch_add(1, Ordering::Relaxed);
        });

        let report = runtime.dry_run_to_mssql_with_progress(&session, &request, reporter)?;

        assert_eq!(report.output_name(), "orders_output");
        assert_eq!(report.run_mode(), RunMode::DryRun);
        assert!(!report.sql_server_contacted());
        assert!(!report.row_production_started());
        assert_eq!(deliveries.load(Ordering::Relaxed), 3);
        Ok(())
    }

    #[test]
    fn runtime_drives_multi_output_dry_run() -> Result<(), DeltaFunnelError> {
        let runtime = DeltaFunnelRuntime::new()?;
        let mut session = DeltaFunnelSession::new(
            SessionOptions::new().with_default_mssql_connection(secret_connection()?),
        )?;
        let west = runtime.table_from_sql(&mut session, "select 1 as id")?;
        let east = runtime.table_from_sql(&mut session, "select 2 as id")?;
        let west = output_request(west, "west_output", "west_orders")?;
        let east = output_request(east, "east_output", "east_orders")?;

        let report = runtime.dry_run_all_to_mssql(&session, &[west, east])?;

        assert_eq!(report.len(), 2);
        assert_eq!(report.outputs()[0].output_name(), "west_output");
        assert_eq!(report.outputs()[1].output_name(), "east_output");
        assert!(!report.sql_server_contacted());
        assert!(!report.row_production_started());
        Ok(())
    }

    #[test]
    fn runtime_drives_dry_run_scan_summary() -> Result<(), Box<dyn std::error::Error>> {
        let runtime = DeltaFunnelRuntime::new()?;
        let table = RealParquetDeltaTable::new_default("orders")?;
        let mut session = DeltaFunnelSession::new(
            SessionOptions::new()
                .with_default_mssql_connection(secret_connection()?)
                .with_validation_options(
                    ValidationOptions::new()
                        .with_dry_run_scan_summary_mode(DryRunScanSummaryMode::ExhaustScanMetadata),
                ),
        )?;
        let source = session.delta_lake(DeltaSourceConfig::new(
            "orders",
            table.path().to_string_lossy().to_string(),
        ))?;
        let request = output_request(source, "orders_output", "orders_sink")?;

        let report = runtime.dry_run_all_to_mssql_with_scan_summary(&session, &[request])?;

        assert_eq!(report.sources().len(), 1);
        assert!(report.sources()[0].provider_read_stats().is_some());
        assert!(!report.row_production_started());
        Ok(())
    }

    #[test]
    fn runtime_preserves_sanitized_session_errors() -> Result<(), DeltaFunnelError> {
        let runtime = DeltaFunnelRuntime::new()?;
        let mut session = DeltaFunnelSession::new(SessionOptions::default())?;
        let output = runtime.table_from_sql(&mut session, "select 1 as id")?;
        let request = output_request(output, "orders_output", "orders_sink")?;

        let error = runtime.dry_run_to_mssql(&session, &request);

        assert!(matches!(
            error,
            Err(DeltaFunnelError::MissingMssqlConnection { output_name })
                if output_name == "orders_output"
        ));
        Ok(())
    }

    #[test]
    fn runtime_drives_single_output_write_with_injected_writer()
    -> Result<(), Box<dyn std::error::Error>> {
        let runtime = DeltaFunnelRuntime::new()?;
        let mut session = DeltaFunnelSession::new(
            SessionOptions::new().with_default_mssql_connection(secret_connection()?),
        )?;
        let output =
            runtime.table_from_sql(&mut session, "select 1 as id union all select 2 as id")?;
        let request = execute_output_request(
            output,
            "orders_output",
            "orders_sink",
            LoadMode::CreateAndLoad,
        )?;
        let mut writer = FakeRuntimeWriter::default();

        let report = runtime.write_to_mssql_with_writer(&session, &request, &mut writer)?;

        assert_eq!(writer.calls.len(), 1);
        let call = writer
            .calls
            .first()
            .ok_or("expected fake runtime writer call")?;
        assert_eq!(call.output_name, "orders_output");
        assert_eq!(call.target_table.table(), "orders_sink");
        assert_eq!(
            call.connection_source,
            MssqlConnectionSource::ContextDefault
        );
        assert_eq!(call.rows, 2);
        assert!(call.batches >= 1);
        assert_eq!(call.schema_fields, 1);
        assert_eq!(report.output_name(), "orders_output");
        assert_eq!(report.stats().rows_written(), 2);
        assert_eq!(report.stats().batches_written(), call.batches);
        Ok(())
    }

    #[test]
    fn runtime_drives_multi_output_write_with_injected_writer()
    -> Result<(), Box<dyn std::error::Error>> {
        let runtime = DeltaFunnelRuntime::new()?;
        let mut session = DeltaFunnelSession::new(
            SessionOptions::new().with_default_mssql_connection(secret_connection()?),
        )?;
        let west =
            runtime.table_from_sql(&mut session, "select 1 as id union all select 2 as id")?;
        let east = runtime.table_from_sql(&mut session, "select 3 as id")?;
        let west =
            execute_output_request(west, "west_output", "west_orders", LoadMode::AppendExisting)?;
        let east =
            execute_output_request(east, "east_output", "east_orders", LoadMode::CreateAndLoad)?;
        let writer = FakeRuntimeWriter::default();

        let report = runtime.write_all_with_writer(&session, &[west, east], writer)?;

        assert_eq!(report.len(), 2);
        assert!(report.all_succeeded());
        assert_eq!(report.outputs()[0].output_name(), "west_output");
        assert_eq!(report.outputs()[1].output_name(), "east_output");
        let crate::MssqlOutputWriteStatus::Succeeded(west_report) = &report.outputs()[0] else {
            return Err(format!("expected succeeded status, got {:?}", report.outputs()[0]).into());
        };
        let crate::MssqlOutputWriteStatus::Succeeded(east_report) = &report.outputs()[1] else {
            return Err(format!("expected succeeded status, got {:?}", report.outputs()[1]).into());
        };
        assert_eq!(west_report.stats().rows_written(), 2);
        assert_eq!(east_report.stats().rows_written(), 1);
        Ok(())
    }

    #[test]
    fn runtime_rejects_blocking_calls_inside_active_tokio_runtime()
    -> Result<(), Box<dyn std::error::Error>> {
        let runtime = DeltaFunnelRuntime::new()?;
        let mut session = DeltaFunnelSession::new(
            SessionOptions::new().with_default_mssql_connection(secret_connection()?),
        )?;
        let output = runtime.table_from_sql(&mut session, "select 1 as id")?;
        let request = output_request(output, "orders_output", "orders_sink")?;
        let host_runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()?;

        let error = host_runtime.block_on(async { runtime.dry_run_to_mssql(&session, &request) });

        assert!(matches!(
            error,
            Err(DeltaFunnelError::Config { message })
                if message.contains("cannot be called from inside an active Tokio runtime")
                    && message.contains("DeltaFunnelSession async APIs")
        ));
        Ok(())
    }

    #[test]
    fn lower_level_modules_do_not_create_hidden_tokio_runtimes() {
        let low_level_sources = [
            include_str!("../pipeline/batch_handoff.rs"),
            include_str!("../query_engine/datafusion/execution.rs"),
            include_str!("../query_engine/datafusion/execution/planning_exec.rs"),
            include_str!("../sql_server/execution/connection.rs"),
            include_str!("../sql_server/execution/sink.rs"),
            include_str!("../sql_server/execution/workflow.rs"),
            include_str!("../sql_server/execution/write.rs"),
        ];

        for source in low_level_sources {
            assert!(!source.contains("tokio::runtime"));
            assert!(!source.contains("Runtime::new"));
            assert!(!source.contains("block_on"));
        }
    }
}