lix 0.16.0

Embeddable version control for apps and AI agents.
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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
#![allow(clippy::cloned_ref_to_slice_refs, clippy::match_same_arms)]

use std::collections::BTreeSet;
use std::sync::Arc;

use datafusion::prelude::SessionContext;

use crate::LixError;
use crate::branch::BranchRefReader;

mod branch;
mod change;
mod columns;
mod commit_ancestry;
pub(crate) use commit_ancestry::commit_ancestry_schema;
mod diff;
mod directory;
pub(crate) use diff::relation_diff_schema;
mod diff_command;
mod file;
mod mainline;
pub(crate) use mainline::relation_history_schema;
#[cfg(test)]
pub(crate) use mainline::take_mainline_work;
pub(crate) fn log_schema() -> datafusion::arrow::datatypes::SchemaRef {
    mainline::metadata_schema(false)
}
mod schema;
mod state_at;
#[cfg(test)]
pub(crate) use state_at::{arm_state_at_traversal_probe, take_state_at_traversal_probe};
mod spec;
pub(crate) use spec::{PhysicalScanKey, SpecScanExec, StatementScanKey};
mod upsert;
mod values;

use crate::sql2::catalog::{PublicCatalog, PublicSurfaceContract, PublicSurfaceKind};
use crate::sql2::session::SqlWriteSessionOptions;
use crate::sql2::{SqlExecutionContext, SqlWriteContext};

pub(crate) use directory::execute_exact_lix_directory_root_listing;
pub(crate) use file::{
    ExactLixFileReadColumn, ExactLixFileReadSelector, FastLixFilePathWriteConflict,
    execute_exact_lix_file_batch_read, execute_exact_lix_file_id_manifest_batch_read,
    execute_exact_lix_file_read, execute_exact_lix_file_root_listing,
    execute_fast_lix_file_content_update_by_id,
    execute_fast_lix_file_content_update_by_id_with_metadata, execute_fast_lix_file_id_path_writes,
    execute_fast_lix_file_path_writes, execute_fast_lix_file_prepared_path_write,
};
pub(crate) use schema::{execute_exact_schema_batch_read, execute_exact_schema_point_read};
pub(crate) use spec::{DmlReturning, SpecWriteTarget, WriteTargetRegistry};
pub(crate) use upsert::{UpsertAction, excluded_field_name};

pub(crate) async fn register_read<C>(
    session: &SessionContext,
    ctx: &C,
    branch_ref: Arc<dyn BranchRefReader>,
    active_branch_commit_id: Option<String>,
    selection: &ProviderSelection,
) -> Result<(), LixError>
where
    C: SqlExecutionContext + ?Sized,
{
    let catalog = if selection.requires_visible_schemas() {
        ctx.public_catalog().await?
    } else {
        Arc::clone(PublicCatalog::fixed_system_shared())
    };
    crate::sql2::udfs::register_row_ref_function(session, Arc::clone(&catalog));
    if catalog
        .surface("lix_diff")
        .is_some_and(|surface| selection.includes(surface))
    {
        diff::register_diff_function(session, ctx.changelog_query_source(), Arc::clone(&catalog));
    }
    if catalog
        .surface("lix_as_of")
        .is_some_and(|surface| selection.includes(surface))
    {
        state_at::register_state_at_function(
            session,
            ctx.changelog_query_source(),
            Arc::clone(&catalog),
            ctx.active_branch_id().to_string(),
            ctx.blob_reader(),
        );
    }
    register_read_from_catalog(
        session,
        ctx,
        branch_ref,
        active_branch_commit_id,
        &catalog,
        ReadProviderScope::All,
        selection,
    )
    .await?;
    register_information_schema(session, selection, catalog)
}

/// Installs the `information_schema` views only for statements that can reach
/// them.
///
/// `read_provider_selection` widens to [`ProviderSelection::All`] for every
/// `information_schema`-qualified reference and every `SHOW` form, so a narrowed
/// selection provably never resolves an information-schema table. Registering
/// the schema anyway cost one catalog write lock and one `SchemaProvider`
/// allocation on every ordinary statement.
fn register_information_schema(
    session: &SessionContext,
    selection: &ProviderSelection,
    catalog: Arc<PublicCatalog>,
) -> Result<(), LixError> {
    if !matches!(
        selection,
        ProviderSelection::All | ProviderSelection::AllWithHistory(_)
    ) {
        return Ok(());
    }
    crate::sql2::information_schema::register(session, catalog)
}

/// Snapshot-local providers needed to plan already-bound SQL.
///
/// Ordinary reads use DataFusion's resolver, including its CTE scoping and
/// identifier normalization rules. A narrow AST walk additionally extracts the
/// plan-time relation literal from `lix_history(...)`; provider construction
/// cannot depend on a runtime parameter because each relation has a different
/// result schema. Bound target-only writes select their known target directly.
/// Providers and plans remain scoped to the current storage snapshot.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ProviderSelection {
    /// Register every surface when catalog-wide visibility is part of the SQL
    /// semantics (notably `information_schema` and rewritten `SHOW` queries),
    /// or when reference resolution cannot prove a narrower set is sufficient.
    All,
    /// Register every ordinary surface while constructing history providers
    /// only for relation literals that occur in the statement.
    AllWithHistory(BTreeSet<String>),
    /// Register the union of concrete table names referenced by the statements.
    Only {
        names: BTreeSet<String>,
        history_relations: BTreeSet<String>,
    },
}

impl ProviderSelection {
    fn includes(&self, surface: &PublicSurfaceContract) -> bool {
        match self {
            Self::All | Self::AllWithHistory(_) => true,
            Self::Only { names, .. } => names.contains(&surface.name),
        }
    }

    fn requested_history_relations(&self) -> Option<&BTreeSet<String>> {
        match self {
            Self::All => Some(empty_history_relations()),
            Self::AllWithHistory(history_relations) => Some(history_relations),
            Self::Only {
                history_relations, ..
            } => Some(history_relations),
        }
    }

    /// Whether resolving this selection requires the storage-backed catalog.
    ///
    /// Table-free reads and references satisfied by the immutable system catalog
    /// can install providers without scanning `lix_registered_schema` rows.
    /// Runtime registration rejects schema keys whose generated table names
    /// would shadow these fixed providers.
    /// `All` and every unknown name remain conservative: they load the full
    /// visible catalog so information-schema, custom rows, and normal
    /// unknown-table errors keep their current semantics.
    fn requires_visible_schemas(&self) -> bool {
        match self {
            Self::All | Self::AllWithHistory(_) => true,
            Self::Only {
                names,
                history_relations,
            } => {
                names
                    .iter()
                    .any(|name| PublicCatalog::fixed_system().surface(name).is_none())
                    || history_relations.iter().any(|name| {
                        PublicCatalog::fixed_system()
                            .history_relation(name)
                            .is_none()
                    })
            }
        }
    }
}

pub(crate) fn read_provider_selection(
    state: &datafusion::execution::session_state::SessionState,
    statements: &[datafusion::sql::parser::Statement],
) -> ProviderSelection {
    let mut names = BTreeSet::new();
    let mut history_relations = BTreeSet::new();
    let mut requires_all = false;
    // Resolving references only reads the SQL parser configuration, so the
    // statement's pooled session state is used directly instead of cloning the
    // live one.
    for statement in statements {
        collect_history_relation_literals(statement, &mut history_relations);
        collect_dynamic_relation_literals(statement, &mut names);
        if statement_requires_all_providers(statement) {
            requires_all = true;
            continue;
        }
        let Ok(references) = state.resolve_table_references(statement) else {
            requires_all = true;
            continue;
        };
        for reference in references {
            if reference.schema() == Some("information_schema") {
                requires_all = true;
            }
            names.insert(reference.table().to_string());
        }
    }
    if requires_all {
        return all_provider_selection(history_relations);
    }
    ProviderSelection::Only {
        names,
        history_relations,
    }
}

fn all_provider_selection(history_relations: BTreeSet<String>) -> ProviderSelection {
    if history_relations.is_empty() {
        ProviderSelection::All
    } else {
        ProviderSelection::AllWithHistory(history_relations)
    }
}

fn empty_history_relations() -> &'static BTreeSet<String> {
    static EMPTY: std::sync::OnceLock<BTreeSet<String>> = std::sync::OnceLock::new();
    EMPTY.get_or_init(BTreeSet::new)
}

fn collect_history_relation_literals(
    statement: &datafusion::sql::parser::Statement,
    relations: &mut BTreeSet<String>,
) {
    use std::ops::ControlFlow;

    use datafusion::sql::parser::Statement as DataFusionStatement;
    use datafusion::sql::sqlparser::ast::{
        Expr as SqlExpr, FunctionArg, FunctionArgExpr, TableFactor, Value as SqlValue, Visit,
        Visitor,
    };

    struct HistoryRelationVisitor<'a>(&'a mut BTreeSet<String>);

    impl Visitor for HistoryRelationVisitor<'_> {
        type Break = ();

        fn pre_visit_table_factor(
            &mut self,
            table_factor: &TableFactor,
        ) -> ControlFlow<Self::Break> {
            let TableFactor::Table {
                name,
                args: Some(arguments),
                ..
            } = table_factor
            else {
                return ControlFlow::Continue(());
            };
            if !crate::sql2::parse::object_name_is_public_function(name, "lix_history") {
                return ControlFlow::Continue(());
            }
            let Some(FunctionArg::Unnamed(FunctionArgExpr::Expr(SqlExpr::Value(value)))) =
                arguments.args.first()
            else {
                return ControlFlow::Continue(());
            };
            if let SqlValue::SingleQuotedString(relation_name) = &value.value {
                self.0.insert(relation_name.clone());
            }
            ControlFlow::Continue(())
        }
    }

    match statement {
        DataFusionStatement::Statement(statement) => {
            let _ = statement.visit(&mut HistoryRelationVisitor(relations));
        }
        DataFusionStatement::Explain(explain) => {
            collect_history_relation_literals(explain.statement.as_ref(), relations);
        }
        _ => {}
    }
}

/// Diff results inherit their relation's Arrow schema, so runtime schema
/// literals must participate in snapshot-local catalog selection even though
/// DataFusion only resolves the table-function name itself.
fn collect_dynamic_relation_literals(
    statement: &datafusion::sql::parser::Statement,
    relations: &mut BTreeSet<String>,
) {
    use std::ops::ControlFlow;

    use datafusion::sql::parser::Statement as DataFusionStatement;
    use datafusion::sql::sqlparser::ast::{
        Expr as SqlExpr, FunctionArg, FunctionArgExpr, TableFactor, Value as SqlValue, Visit,
        Visitor,
    };

    struct DiffRelationVisitor<'a>(&'a mut BTreeSet<String>);

    impl Visitor for DiffRelationVisitor<'_> {
        type Break = ();

        fn pre_visit_expr(&mut self, expression: &SqlExpr) -> ControlFlow<Self::Break> {
            let SqlExpr::Function(function) = expression else {
                return ControlFlow::Continue(());
            };
            if !crate::sql2::parse::object_name_is_public_function(&function.name, "lix_row_ref") {
                return ControlFlow::Continue(());
            }
            let datafusion::sql::sqlparser::ast::FunctionArguments::List(arguments) =
                &function.args
            else {
                return ControlFlow::Continue(());
            };
            let Some(FunctionArg::Unnamed(FunctionArgExpr::Expr(SqlExpr::Value(value)))) =
                arguments.args.first()
            else {
                return ControlFlow::Continue(());
            };
            if let SqlValue::SingleQuotedString(relation_name) = &value.value {
                self.0.insert(relation_name.clone());
            }
            ControlFlow::Continue(())
        }

        fn pre_visit_table_factor(
            &mut self,
            table_factor: &TableFactor,
        ) -> ControlFlow<Self::Break> {
            let TableFactor::Table {
                name,
                args: Some(arguments),
                ..
            } = table_factor
            else {
                return ControlFlow::Continue(());
            };
            if !crate::sql2::parse::object_name_is_public_function(name, "lix_diff")
                && !crate::sql2::parse::object_name_is_public_function(name, "lix_as_of")
            {
                return ControlFlow::Continue(());
            }
            let Some(FunctionArg::Unnamed(FunctionArgExpr::Expr(SqlExpr::Value(value)))) =
                arguments.args.first()
            else {
                return ControlFlow::Continue(());
            };
            if let SqlValue::SingleQuotedString(relation_name) = &value.value {
                self.0.insert(relation_name.clone());
            }
            ControlFlow::Continue(())
        }
    }

    match statement {
        DataFusionStatement::Statement(statement) => {
            let _ = statement.visit(&mut DiffRelationVisitor(relations));
        }
        DataFusionStatement::Explain(explain) => {
            collect_dynamic_relation_literals(explain.statement.as_ref(), relations);
        }
        _ => {}
    }
}

fn statement_requires_all_providers(statement: &datafusion::sql::parser::Statement) -> bool {
    use datafusion::sql::parser::Statement as DataFusionStatement;
    use datafusion::sql::sqlparser::ast::Statement as SqlStatement;

    fn sql_statement_requires_all_providers(statement: &SqlStatement) -> bool {
        match statement {
            SqlStatement::ShowFunctions { .. }
            | SqlStatement::ShowVariable { .. }
            | SqlStatement::ShowStatus { .. }
            | SqlStatement::ShowVariables { .. }
            | SqlStatement::ShowCreate { .. }
            | SqlStatement::ShowColumns { .. }
            | SqlStatement::ShowTables { .. }
            | SqlStatement::ShowCollation { .. } => true,
            SqlStatement::Explain { statement, .. } => {
                sql_statement_requires_all_providers(statement)
            }
            _ => false,
        }
    }

    match statement {
        DataFusionStatement::Statement(statement) => {
            sql_statement_requires_all_providers(statement)
        }
        DataFusionStatement::Explain(explain) => {
            statement_requires_all_providers(explain.statement.as_ref())
        }
        _ => false,
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ReadProviderScope {
    All,
    ReadOnly,
}

impl ReadProviderScope {
    fn includes(self, surface: &PublicSurfaceContract) -> bool {
        self == Self::All || !is_write_surface(surface)
    }
}

fn is_write_surface(surface: &PublicSurfaceContract) -> bool {
    surface.capabilities.insert || surface.capabilities.update || surface.capabilities.delete
}

async fn register_read_from_catalog<C>(
    session: &SessionContext,
    ctx: &C,
    branch_ref: Arc<dyn BranchRefReader>,
    active_branch_commit_id: Option<String>,
    catalog: &Arc<PublicCatalog>,
    scope: ReadProviderScope,
    selection: &ProviderSelection,
) -> Result<(), LixError>
where
    C: SqlExecutionContext + ?Sized,
{
    if let Some(requested) = selection.requested_history_relations() {
        for relation_name in requested {
            if catalog.history_relation(relation_name).is_none() {
                return Err(LixError::new(
                    LixError::CODE_UNSUPPORTED_SQL,
                    format!("lix_history does not support relation '{relation_name}'"),
                ));
            }
        }
    }
    for surface in catalog.surfaces() {
        if !scope.includes(surface) || !selection.includes(surface) {
            continue;
        }
        match &surface.kind {
            PublicSurfaceKind::Branch => {
                branch::register_lix_branch_read_provider(
                    session,
                    &surface.name,
                    ctx.hot_state(),
                    Arc::clone(&branch_ref),
                )
                .await?;
            }
            PublicSurfaceKind::Change => {
                change::register_lix_change_read_provider(
                    session,
                    &surface.name,
                    ctx.changelog_query_source(),
                )
                .await?;
            }
            PublicSurfaceKind::CommitAncestryFunction => {
                let active_branch_commit_id = active_branch_commit_id.clone().ok_or_else(|| {
                    LixError::branch_not_found(
                        ctx.active_branch_id(),
                        "register lix_commit_ancestry",
                        "active branch",
                    )
                })?;
                commit_ancestry::register_commit_ancestry_function(
                    session,
                    &surface.name,
                    active_branch_commit_id,
                    ctx.commit_graph(),
                );
            }
            PublicSurfaceKind::File => {
                file::register_lix_file_active_provider(
                    session,
                    &surface.name,
                    ctx.active_branch_id(),
                    ctx.hot_state(),
                    ctx.filesystem_path_index(),
                    Arc::clone(&branch_ref),
                    ctx.blob_reader(),
                    ctx.plugin_host(),
                    ctx.functions(),
                    ctx.session_file_views(),
                )
                .await?;
            }
            PublicSurfaceKind::Directory => {
                directory::register_lix_directory_active_provider(
                    session,
                    &surface.name,
                    ctx.active_branch_id(),
                    ctx.hot_state(),
                    ctx.filesystem_path_index(),
                    Arc::clone(&branch_ref),
                    ctx.functions(),
                )
                .await?;
            }
            PublicSurfaceKind::SchemaBase { .. }
            | PublicSurfaceKind::LogFunction
            | PublicSurfaceKind::HistoryFunction
            | PublicSurfaceKind::DiffFunction
            | PublicSurfaceKind::CheckpointFunction
            | PublicSurfaceKind::StateAtFunction
            | PublicSurfaceKind::Revert
            | PublicSurfaceKind::Apply
            | PublicSurfaceKind::Restore => {}
        }
    }
    schema::register_row_providers(
        session,
        ctx.active_branch_id(),
        ctx.hot_state(),
        ctx.row_snapshot_reader(),
        Arc::clone(&branch_ref),
        catalog,
        scope == ReadProviderScope::All,
        selection,
    )
    .await?;

    if ["lix_log", "lix_history"].iter().any(|name| {
        catalog
            .surface(name)
            .is_some_and(|surface| scope.includes(surface) && selection.includes(surface))
    }) {
        mainline::register_functions(session, ctx.changelog_query_source(), Arc::clone(catalog));
    }

    Ok(())
}

pub(crate) async fn register_write(
    session: &SessionContext,
    write_ctx: SqlWriteContext,
    branch_ref: Arc<dyn BranchRefReader>,
    options: SqlWriteSessionOptions,
    selection: &ProviderSelection,
) -> Result<(), LixError> {
    let catalog = write_ctx.public_catalog()?;
    crate::sql2::udfs::register_row_ref_function(session, Arc::clone(&catalog));
    register_write_from_catalog(session, write_ctx, branch_ref, options, &catalog, selection)
        .await?;
    register_information_schema(session, selection, catalog)
}

pub(crate) async fn register_transaction<C>(
    session: &SessionContext,
    read_ctx: &C,
    read_branch_ref: Arc<dyn BranchRefReader>,
    active_branch_commit_id: Option<String>,
    write_ctx: SqlWriteContext,
    write_branch_ref: Arc<dyn BranchRefReader>,
    options: SqlWriteSessionOptions,
    selection: &ProviderSelection,
) -> Result<(), LixError>
where
    C: SqlExecutionContext + ?Sized,
{
    // Both capabilities project the same transaction-scoped schema snapshot.
    // Reuse that immutable metadata, then install read-only providers from the
    // committed read capability and writable providers from the overlay.
    let catalog = write_ctx.public_catalog()?;
    crate::sql2::udfs::register_row_ref_function(session, Arc::clone(&catalog));
    if catalog
        .surface("lix_diff")
        .is_some_and(|surface| selection.includes(surface))
    {
        diff::register_diff_function(
            session,
            read_ctx.changelog_query_source(),
            Arc::clone(&catalog),
        );
    }
    if catalog
        .surface("lix_as_of")
        .is_some_and(|surface| selection.includes(surface))
    {
        state_at::register_state_at_function(
            session,
            read_ctx.changelog_query_source(),
            Arc::clone(&catalog),
            read_ctx.active_branch_id().to_string(),
            read_ctx.blob_reader(),
        );
    }
    register_read_from_catalog(
        session,
        read_ctx,
        read_branch_ref,
        active_branch_commit_id,
        &catalog,
        ReadProviderScope::ReadOnly,
        selection,
    )
    .await?;
    register_write_from_catalog(
        session,
        write_ctx,
        write_branch_ref,
        options,
        &catalog,
        selection,
    )
    .await?;
    register_information_schema(session, selection, catalog)
}

async fn register_write_from_catalog(
    session: &SessionContext,
    write_ctx: SqlWriteContext,
    branch_ref: Arc<dyn BranchRefReader>,
    options: SqlWriteSessionOptions,
    catalog: &PublicCatalog,
    selection: &ProviderSelection,
) -> Result<(), LixError> {
    for surface in catalog.surfaces() {
        if !selection.includes(surface) {
            continue;
        }
        match &surface.kind {
            PublicSurfaceKind::Branch => {
                branch::register_write_provider(
                    session,
                    &surface.name,
                    write_ctx.clone(),
                    Arc::clone(&branch_ref),
                )
                .await?;
            }
            PublicSurfaceKind::File => {
                file::register_active_write_provider(
                    session,
                    &surface.name,
                    write_ctx.clone(),
                    Arc::clone(&branch_ref),
                    options.clone(),
                )
                .await?;
            }
            PublicSurfaceKind::Directory => {
                directory::register_active_write_provider(
                    session,
                    &surface.name,
                    write_ctx.clone(),
                    Arc::clone(&branch_ref),
                )
                .await?;
            }
            PublicSurfaceKind::Revert => {
                diff_command::register_diff_command_provider(
                    session,
                    &surface.name,
                    crate::sql2::DiffCommand::Revert,
                    write_ctx.clone(),
                )
                .await?;
            }
            PublicSurfaceKind::Apply => {
                diff_command::register_diff_command_provider(
                    session,
                    &surface.name,
                    crate::sql2::DiffCommand::Apply,
                    write_ctx.clone(),
                )
                .await?;
            }
            PublicSurfaceKind::Change
            | PublicSurfaceKind::LogFunction
            | PublicSurfaceKind::HistoryFunction
            | PublicSurfaceKind::DiffFunction
            | PublicSurfaceKind::CheckpointFunction
            | PublicSurfaceKind::StateAtFunction
            | PublicSurfaceKind::CommitAncestryFunction
            | PublicSurfaceKind::Restore => {}
            PublicSurfaceKind::SchemaBase { .. } => {}
        }
    }
    schema::register_row_write_providers(session, write_ctx, branch_ref, catalog, selection)
        .await?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;
    use std::sync::Arc;

    use async_trait::async_trait;
    use serde_json::json;

    use datafusion::arrow::datatypes::{DataType, SchemaRef};
    use datafusion::prelude::SessionContext;

    use crate::LixError;
    use crate::branch::{BranchHead, BranchRefReader};
    use crate::changelog::CommitId;
    use crate::hot_state::{HotStateReader, HotStateScanRequest};
    use crate::sql2::catalog::{PublicCatalog, derive_schema_surface_spec_from_schema};

    use super::{
        ProviderSelection, ReadProviderScope, branch, change, directory, file, is_write_surface,
        read_provider_selection, relation_history_schema, schema,
    };

    fn selection_for_sql(sql: &[&str]) -> ProviderSelection {
        let statements = sql
            .iter()
            .map(|sql| crate::sql2::parse_statement(sql).expect("SQL should parse"))
            .collect::<Vec<_>>();
        read_provider_selection(&SessionContext::new().state(), &statements)
    }

    fn selected_names(names: &[&str]) -> ProviderSelection {
        ProviderSelection::Only {
            names: names.iter().map(|name| (*name).to_string()).collect(),
            history_relations: BTreeSet::new(),
        }
    }

    #[test]
    fn referenced_provider_selection_uses_datafusion_cte_and_set_operation_resolution() {
        let selection = selection_for_sql(&["WITH shadowed AS (\
                 SELECT id FROM lix_key_value \
                 WHERE EXISTS (SELECT 1 FROM lix_file)\
             ) \
             SELECT left_side.id \
             FROM shadowed AS left_side \
             JOIN (\
                 SELECT row_pk FROM lix_change \
                 UNION ALL \
                 SELECT row_pk FROM lix_change\
               ) AS right_side \
               ON false \
             JOIN public.\"lix_directory\" AS directory_a ON true \
             JOIN public.\"lix_directory\" AS directory_b ON true"]);

        assert_eq!(
            selection,
            selected_names(&["lix_change", "lix_directory", "lix_file", "lix_key_value"])
        );
    }

    #[test]
    fn referenced_provider_selection_excludes_shadowed_and_recursive_cte_names() {
        assert_eq!(
            selection_for_sql(&["WITH lix_file AS (SELECT id FROM lix_key_value) \
                 SELECT * FROM lix_file",]),
            selected_names(&["lix_key_value"])
        );
        assert_eq!(
            selection_for_sql(&["WITH RECURSIVE walk(id) AS (\
                     SELECT id FROM lix_branch \
                     UNION ALL \
                     SELECT branch.id FROM lix_branch AS branch \
                     JOIN walk ON branch.id = walk.id\
                 ) \
                 SELECT * FROM walk",]),
            selected_names(&["lix_branch"])
        );
    }

    #[test]
    fn referenced_provider_selection_unions_batches_and_preserves_unknown_names() {
        assert_eq!(
            selection_for_sql(&[
                "SELECT * FROM lix_file",
                "SELECT * FROM public.lix_key_value JOIN \"UnknownTable\" ON true",
            ]),
            selected_names(&["UnknownTable", "lix_file", "lix_key_value"])
        );
    }

    #[test]
    fn referenced_provider_selection_registers_none_for_table_free_queries() {
        assert_eq!(
            selection_for_sql(&["SELECT 1, uuidv7()"]),
            ProviderSelection::Only {
                names: BTreeSet::new(),
                history_relations: BTreeSet::new(),
            }
        );
    }

    #[test]
    fn history_provider_selection_keeps_the_literal_relation_separate_from_the_function() {
        assert_eq!(
            selection_for_sql(&["SELECT id FROM lix_history('lix_file', $1)"]),
            ProviderSelection::Only {
                names: BTreeSet::from(["lix_history".to_string()]),
                history_relations: BTreeSet::from(["lix_file".to_string()]),
            }
        );
        assert!(
            selection_for_sql(&["SELECT * FROM lix_history('runtime_note')"])
                .requires_visible_schemas()
        );
        assert_eq!(
            selection_for_sql(&[
                "SELECT * FROM information_schema.tables",
                "SELECT * FROM lix_history('lix_file')",
            ]),
            ProviderSelection::AllWithHistory(BTreeSet::from(["lix_file".to_string()]))
        );

        for sql in [
            "SELECT * FROM LIX_HISTORY('lix_file')",
            "SELECT * FROM public.lix_history('lix_file')",
            "SELECT * FROM datafusion.public.lix_history('lix_file')",
            "SELECT * FROM \"lix_history\"('lix_file')",
        ] {
            let selection = selection_for_sql(&[sql]);
            assert!(
                selection
                    .requested_history_relations()
                    .is_some_and(|relations| relations.contains("lix_file")),
                "{sql} should select the literal history provider: {selection:?}",
            );
        }

        assert!(
            !selection_for_sql(&["SELECT * FROM \"LIX_HISTORY\"('lix_file')"])
                .requested_history_relations()
                .is_some_and(|relations| relations.contains("lix_file")),
            "quoted identifiers retain their case",
        );
        assert!(
            !selection_for_sql(&["SELECT * FROM \"PUBLIC\".lix_history('lix_file')"])
                .requested_history_relations()
                .is_some_and(|relations| relations.contains("lix_file")),
            "quoted schema identifiers retain their case",
        );
    }

    #[test]
    fn diff_provider_selection_loads_runtime_relation_schema_for_dynamic_side_columns() {
        assert_eq!(
            selection_for_sql(&["SELECT to_value FROM lix_diff('lix_key_value', $1, $2)"]),
            selected_names(&["lix_diff", "lix_key_value"]),
        );
        assert!(
            selection_for_sql(&["SELECT * FROM lix_diff('runtime_note', $1, $2)"])
                .requires_visible_schemas()
        );
    }

    #[test]
    fn referenced_provider_selection_keeps_catalog_wide_information_schema_semantics() {
        assert_eq!(
            selection_for_sql(&["SELECT * FROM information_schema.tables"]),
            ProviderSelection::All
        );
        assert_eq!(selection_for_sql(&["SHOW TABLES"]), ProviderSelection::All);
    }

    #[test]
    fn visible_schema_loading_boundary_is_conservative() {
        assert!(!selection_for_sql(&["SELECT 1"]).requires_visible_schemas());
        assert!(!selection_for_sql(&["SELECT * FROM lix_key_value"]).requires_visible_schemas());
        assert!(
            !selection_for_sql(&["SELECT * FROM lix_history('lix_key_value')"])
                .requires_visible_schemas()
        );
        assert!(
            !selection_for_sql(&["SELECT * FROM lix_key_value JOIN lix_file ON false"])
                .requires_visible_schemas()
        );
        assert!(selection_for_sql(&["SELECT * FROM custom_row"]).requires_visible_schemas());
        assert!(
            selection_for_sql(&["SELECT * FROM lix_key_value JOIN custom_row ON false",])
                .requires_visible_schemas()
        );
        assert!(
            selection_for_sql(&["SELECT * FROM information_schema.tables"])
                .requires_visible_schemas()
        );
    }

    #[test]
    fn referenced_provider_selection_filters_transaction_capabilities_symmetrically() {
        let catalog = PublicCatalog::from_visible_schemas(&[]).expect("catalog should build");
        let selection = selection_for_sql(&[
            "SELECT * FROM lix_file JOIN lix_history('lix_file') AS history ON false",
        ]);

        let committed_read_names = catalog
            .surfaces()
            .filter(|surface| {
                ReadProviderScope::ReadOnly.includes(surface) && selection.includes(surface)
            })
            .map(|surface| surface.name.as_str())
            .collect::<Vec<_>>();
        let overlay_write_names = catalog
            .surfaces()
            .filter(|surface| is_write_surface(surface) && selection.includes(surface))
            .map(|surface| surface.name.as_str())
            .collect::<Vec<_>>();

        assert_eq!(committed_read_names, vec!["lix_history"]);
        assert_eq!(overlay_write_names, vec!["lix_file"]);
    }

    #[test]
    fn transaction_registration_partitions_provider_construction_once() {
        let schema = json!({
            "$schema": "https://lix.dev/schema-v1.json",
            "key": "phase8_row",
            "columns": [
                { "name": "id", "type": "text", "nullable": false },
            ],
            "primary_key": ["id"],
        });
        let catalog = PublicCatalog::from_visible_schemas(&[schema]).expect("catalog should build");

        let read_only = catalog
            .surfaces()
            .filter(|surface| ReadProviderScope::ReadOnly.includes(surface))
            .map(|surface| surface.name.as_str())
            .collect::<Vec<_>>();
        let writable = catalog
            .surfaces()
            .filter(|surface| is_write_surface(surface))
            .map(|surface| surface.name.as_str())
            .collect::<Vec<_>>();
        let all_read = catalog
            .surfaces()
            .filter(|surface| ReadProviderScope::All.includes(surface))
            .count();

        assert_eq!(
            read_only,
            vec![
                "lix_as_of",
                "lix_change",
                "lix_commit_ancestry",
                "lix_create_checkpoint",
                "lix_diff",
                "lix_history",
                "lix_log",
            ]
        );
        assert_eq!(
            writable,
            vec![
                "lix_apply",
                "lix_branch",
                "lix_directory",
                "lix_file",
                "lix_restore",
                "lix_revert",
                "phase8_row",
            ]
        );
        assert_eq!(read_only.len() + writable.len(), catalog.surfaces().count());
        assert_eq!(all_read + writable.len(), 21, "construction count");
        assert_eq!(read_only.len() + writable.len(), 14, "surface count");
    }

    #[test]
    fn target_write_selection_reduces_provider_construction_count_to_one() {
        let catalog = PublicCatalog::from_visible_schemas(&[]).expect("catalog should build");
        let all_writable = catalog
            .surfaces()
            .filter(|surface| is_write_surface(surface))
            .count();
        let selection = selected_names(&["lix_file"]);
        let selected_writable = catalog
            .surfaces()
            .filter(|surface| is_write_surface(surface) && selection.includes(surface))
            .map(|surface| surface.name.as_str())
            .collect::<Vec<_>>();

        assert_eq!(all_writable, 6, "standalone write count");
        assert_eq!(selected_writable, vec!["lix_file"]);
    }

    #[test]
    fn provider_history_schemas_match_catalog_contract_order() {
        let catalog = PublicCatalog::from_visible_schemas(&[]).expect("catalog should build");

        assert_surface_schema_matches_provider_schema(
            &catalog,
            "lix_file",
            file::lix_file_schema(),
        );
        assert_surface_schema_matches_provider_schema(
            &catalog,
            "lix_directory",
            directory::lix_directory_schema(),
        );
        assert_surface_schema_matches_provider_schema(
            &catalog,
            "lix_branch",
            branch::lix_branch_schema(),
        );
        assert_surface_schema_matches_provider_schema(
            &catalog,
            "lix_change",
            change::lix_change_schema(),
        );
        assert_history_schema_matches_provider_schema(
            &catalog,
            "lix_file",
            relation_history_schema(&catalog, "lix_file").expect("file history schema"),
        );
        assert_history_schema_matches_provider_schema(
            &catalog,
            "lix_directory",
            relation_history_schema(&catalog, "lix_directory").expect("directory history schema"),
        );
    }

    #[test]
    fn file_content_surfaces_use_large_binary() {
        let catalog = PublicCatalog::from_visible_schemas(&[]).expect("catalog should build");

        for (surface_name, column, schema) in [
            ("lix_file", "content", catalog.surface_schema("lix_file")),
            (
                "lix_history('lix_file')",
                "to_content",
                catalog.history_relation_schema("lix_file"),
            ),
        ] {
            let schema = schema.unwrap_or_else(|| panic!("{surface_name} should be in catalog"));
            let content_field = schema
                .field_with_name(column)
                .unwrap_or_else(|_| panic!("{surface_name}.content should exist"));

            assert_eq!(
                content_field.data_type(),
                &DataType::LargeBinary,
                "{surface_name}.content should avoid Arrow Binary's 32-bit offset limit",
            );
        }
    }

    #[tokio::test]
    async fn provider_row_schemas_match_catalog_contract_order() {
        let schema = json!({
            "$schema": "https://lix.dev/schema-v1.json",
            "key": "phase8_row",
            "columns": [
                { "name": "id", "type": "text", "nullable": false },
                { "name": "count", "type": "int8", "nullable": true },
                { "name": "body", "type": "jsonb", "nullable": true },
            ],
            "primary_key": ["id"],
        });
        let catalog =
            PublicCatalog::from_visible_schemas(&[schema.clone()]).expect("catalog should build");
        let _spec = derive_schema_surface_spec_from_schema(&schema).expect("schema should derive");
        let session = SessionContext::new();
        schema::register_row_providers(
            &session,
            "01920000-0000-7000-8000-0000000000a1",
            Arc::new(EmptyHotStateReader),
            None,
            Arc::new(EmptyBranchRefReader),
            &catalog,
            true,
            &ProviderSelection::All,
        )
        .await
        .expect("row providers should register");

        assert_registered_table_schema_matches_catalog(&session, &catalog, "phase8_row").await;
    }

    async fn assert_registered_table_schema_matches_catalog(
        session: &SessionContext,
        catalog: &PublicCatalog,
        surface_name: &str,
    ) {
        let provider = session
            .table_provider(surface_name)
            .await
            .unwrap_or_else(|error| panic!("{surface_name} provider should load: {error}"));
        assert_surface_schema_matches_provider_schema(catalog, surface_name, provider.schema());
    }

    fn assert_surface_schema_matches_provider_schema(
        catalog: &PublicCatalog,
        surface_name: &str,
        provider_schema: SchemaRef,
    ) {
        let surface = catalog
            .surface(surface_name)
            .unwrap_or_else(|| panic!("{surface_name} should be in catalog"));
        let catalog_column_names = surface
            .columns
            .iter()
            .map(|column| column.name.as_str())
            .collect::<Vec<_>>();
        let provider_field_names = provider_schema
            .fields()
            .iter()
            .map(|field| field.name().as_str())
            .collect::<Vec<_>>();
        assert_eq!(
            catalog_column_names, provider_field_names,
            "{surface_name} column order"
        );

        let catalog_schema = catalog
            .surface_schema(surface_name)
            .unwrap_or_else(|| panic!("{surface_name} should be in catalog"));
        assert_eq!(
            catalog_schema.fields(),
            provider_schema.fields(),
            "{surface_name}"
        );
    }

    fn assert_history_schema_matches_provider_schema(
        catalog: &PublicCatalog,
        relation_name: &str,
        provider_schema: SchemaRef,
    ) {
        let contract = catalog
            .history_relation(relation_name)
            .unwrap_or_else(|| panic!("{relation_name} history should be in catalog"));
        let catalog_columns = contract
            .columns
            .iter()
            .filter(|column| column.is_public())
            .map(|column| column.name.as_str())
            .collect::<Vec<_>>();
        let provider_columns = provider_schema
            .fields()
            .iter()
            .map(|field| field.name().as_str())
            .collect::<Vec<_>>();
        assert_eq!(
            catalog_columns, provider_columns,
            "{relation_name} history columns"
        );
    }

    struct EmptyHotStateReader;

    #[async_trait]
    impl HotStateReader for EmptyHotStateReader {
        async fn load_exact_batch(
            &self,
            request: &crate::hot_state::HotStateExactBatchRequest,
        ) -> Result<crate::hot_state::MaterializedHotStateExactBatch, LixError> {
            crate::hot_state::load_exact_batch_via_scan_for_test(self, request).await
        }

        async fn scan_batch(
            &self,
            _request: &HotStateScanRequest,
        ) -> Result<crate::hot_state::MaterializedHotStateBatch, LixError> {
            Ok(Vec::new().into())
        }
    }

    struct EmptyBranchRefReader;

    #[async_trait]
    impl BranchRefReader for EmptyBranchRefReader {
        async fn load_head(&self, branch_id: &str) -> Result<Option<BranchHead>, LixError> {
            Ok(Some(BranchHead {
                working_base_commit_id: None,
                branch_id: branch_id.to_string(),
                commit_id: CommitId::for_test_label(&format!("commit-{branch_id}")),
            }))
        }

        async fn scan_heads(&self) -> Result<Vec<BranchHead>, LixError> {
            Ok(Vec::new().into())
        }
    }
}