lix 0.12.3

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
use std::collections::BTreeSet;

use datafusion::error::DataFusionError;
use datafusion::logical_expr::expr::InList;
use datafusion::logical_expr::{BinaryExpr, Expr, Operator};
use datafusion::scalar::ScalarValue;

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

/// Branch scope requested by a SQL surface.
///
/// Active surfaces read through one session branch. By-branch surfaces either
/// read explicitly filtered branches or, without a branch predicate, enumerate
/// every visible branch scope before handing the request to hot_state.
pub(crate) enum SqlBranchScope {
    Active(String),
    Explicit(Vec<String>),
    AllVisible,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum BranchBinding {
    Active { branch_id: String },
    Explicit,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct WriteBranchScope {
    pub(crate) branch_id: String,
    pub(crate) global: bool,
}

impl BranchBinding {
    pub(crate) fn active(branch_id: impl Into<String>) -> Self {
        Self::Active {
            branch_id: branch_id.into(),
        }
    }

    pub(crate) fn explicit() -> Self {
        Self::Explicit
    }

    pub(crate) fn active_branch_id(&self) -> Option<&str> {
        match self {
            Self::Active { branch_id } => Some(branch_id),
            Self::Explicit => None,
        }
    }
}

pub(crate) fn resolve_write_branch_scope(
    explicit_global: Option<bool>,
    explicit_branch_id: Option<String>,
    fallback_branch_id: Option<&str>,
    action: &str,
    surface: &str,
) -> Result<WriteBranchScope, DataFusionError> {
    if explicit_global == Some(true) {
        if explicit_branch_id
            .as_deref()
            .is_some_and(|branch_id| branch_id != GLOBAL_BRANCH_ID)
        {
            return Err(DataFusionError::Execution(format!(
                "{surface} cannot set lixcol_global=true with non-global lixcol_branch_id"
            )));
        }
        return Ok(WriteBranchScope {
            branch_id: GLOBAL_BRANCH_ID.to_string(),
            global: true,
        });
    }

    let branch_id = explicit_branch_id
        .or_else(|| fallback_branch_id.map(ToOwned::to_owned))
        .ok_or_else(|| DataFusionError::Execution(format!("{action} requires lixcol_branch_id")))?;
    if explicit_global == Some(false) && branch_id == GLOBAL_BRANCH_ID {
        return Err(DataFusionError::Execution(format!(
            "{surface} cannot set lixcol_global=false with global lixcol_branch_id"
        )));
    }
    Ok(WriteBranchScope {
        global: explicit_global.unwrap_or(branch_id == GLOBAL_BRANCH_ID),
        branch_id,
    })
}

impl SqlBranchScope {
    pub(crate) fn from_provider(
        binding: &BranchBinding,
        requested_branch_ids: Vec<String>,
    ) -> Self {
        match binding {
            BranchBinding::Active { branch_id } => Self::Active(branch_id.clone()),
            BranchBinding::Explicit if requested_branch_ids.is_empty() => Self::AllVisible,
            BranchBinding::Explicit => Self::Explicit(requested_branch_ids),
        }
    }
}

pub(crate) async fn resolve_sql_branch_scope(
    branch_ref: &dyn BranchRefReader,
    scope: SqlBranchScope,
) -> Result<Vec<String>, LixError> {
    match scope {
        SqlBranchScope::Active(branch_id) => {
            if branch_ref.load_head(&branch_id).await?.is_none() {
                return Err(LixError::branch_not_found(
                    branch_id,
                    "resolve SQL active branch scope",
                    "active branch",
                ));
            }
            Ok(vec![branch_id])
        }
        SqlBranchScope::Explicit(branch_ids) => {
            for branch_id in &branch_ids {
                if branch_id == GLOBAL_BRANCH_ID {
                    continue;
                }
                if branch_ref.load_head(branch_id).await?.is_none() {
                    return Err(LixError::branch_not_found(
                        branch_id.clone(),
                        "resolve SQL explicit branch scope",
                        "requested branch",
                    ));
                }
            }
            Ok(branch_ids)
        }
        SqlBranchScope::AllVisible => visible_branch_ids(branch_ref).await,
    }
}

pub(crate) async fn resolve_provider_branch_ids(
    branch_ref: &dyn BranchRefReader,
    binding: &BranchBinding,
    requested_branch_ids: Vec<String>,
) -> Result<Vec<String>, LixError> {
    resolve_sql_branch_scope(
        branch_ref,
        SqlBranchScope::from_provider(binding, requested_branch_ids),
    )
    .await
}

pub(crate) fn explicit_branch_ids_from_dml_filters(filters: &[Expr]) -> Vec<String> {
    filters
        .iter()
        .flat_map(branch_ids_from_filter)
        .collect::<BTreeSet<_>>()
        .into_iter()
        .collect()
}

fn branch_ids_from_filter(expr: &Expr) -> Vec<String> {
    match expr {
        Expr::BinaryExpr(binary_expr) if binary_expr.op == Operator::And => {
            let mut values = branch_ids_from_filter(&binary_expr.left);
            values.extend(branch_ids_from_filter(&binary_expr.right));
            values
        }
        Expr::BinaryExpr(binary_expr) => branch_id_from_binary_filter(binary_expr)
            .map(|value| vec![value])
            .unwrap_or_default(),
        Expr::InList(in_list) => branch_ids_from_in_list_filter(in_list).unwrap_or_default(),
        _ => Vec::new(),
    }
}

fn branch_id_from_binary_filter(binary_expr: &BinaryExpr) -> Option<String> {
    if binary_expr.op != Operator::Eq {
        return None;
    }

    branch_id_from_column_literal_filter(&binary_expr.left, &binary_expr.right)
        .or_else(|| branch_id_from_column_literal_filter(&binary_expr.right, &binary_expr.left))
}

fn branch_ids_from_in_list_filter(in_list: &InList) -> Option<Vec<String>> {
    if in_list.negated {
        return None;
    }
    let Expr::Column(column) = in_list.expr.as_ref() else {
        return None;
    };
    if column.name != "lixcol_branch_id" {
        return None;
    }

    let values = in_list
        .list
        .iter()
        .map(string_expr_literal)
        .collect::<Option<Vec<_>>>()?;
    if values.is_empty() {
        return None;
    }
    Some(values)
}

fn branch_id_from_column_literal_filter(column_expr: &Expr, literal_expr: &Expr) -> Option<String> {
    let Expr::Column(column) = column_expr else {
        return None;
    };
    if column.name != "lixcol_branch_id" {
        return None;
    }
    string_expr_literal(literal_expr)
}

fn string_expr_literal(expr: &Expr) -> Option<String> {
    let Expr::Literal(literal, _) = expr else {
        return None;
    };
    match literal {
        ScalarValue::Utf8(Some(value))
        | ScalarValue::Utf8View(Some(value))
        | ScalarValue::LargeUtf8(Some(value)) => Some(value.clone()),
        _ => None,
    }
}

async fn visible_branch_ids(branch_ref: &dyn BranchRefReader) -> Result<Vec<String>, LixError> {
    let mut branch_ids = branch_ref
        .scan_heads()
        .await?
        .into_iter()
        .map(|head| head.branch_id)
        .collect::<BTreeSet<_>>();
    branch_ids.insert(GLOBAL_BRANCH_ID.to_string());
    Ok(branch_ids.into_iter().collect())
}

#[cfg(test)]
mod tests {
    use async_trait::async_trait;

    use super::*;
    use crate::branch::BranchHead;
    use crate::changelog::CommitId;

    #[tokio::test]
    async fn active_scope_uses_session_branch() {
        let branch_ref = RowsBranchRefReader::new(vec![BranchHead {
            branch_id: "main".to_string(),
            commit_id: CommitId::for_test_label("commit-main"),
        }]);
        let ids =
            resolve_provider_branch_ids(&branch_ref, &BranchBinding::active("main"), Vec::new())
                .await
                .expect("scope should resolve");

        assert_eq!(ids, vec!["main".to_string()]);
    }

    #[tokio::test]
    async fn active_scope_rejects_missing_branch_ref() {
        let branch_ref = RowsBranchRefReader::new(Vec::new());
        let error =
            resolve_provider_branch_ids(&branch_ref, &BranchBinding::active("main"), Vec::new())
                .await
                .expect_err("missing active branch should be rejected");

        assert_eq!(error.code, LixError::CODE_BRANCH_NOT_FOUND);
        assert!(error.message.contains("branch 'main' was not found"));
    }

    #[tokio::test]
    async fn explicit_scope_keeps_requested_branches() {
        let branch_ref = RowsBranchRefReader::new(vec![BranchHead {
            branch_id: "01920000-0000-7000-8000-0000000000a1".to_string(),
            commit_id: CommitId::for_test_label("commit-01920000-0000-7000-8000-0000000000a1"),
        }]);
        let ids = resolve_provider_branch_ids(
            &branch_ref,
            &BranchBinding::explicit(),
            vec![
                "01920000-0000-7000-8000-0000000000a1".to_string(),
                "ffffffff-ffff-7fff-bfff-ffffffffffff".to_string(),
            ],
        )
        .await
        .expect("scope should resolve");

        assert_eq!(
            ids,
            vec![
                "01920000-0000-7000-8000-0000000000a1".to_string(),
                "ffffffff-ffff-7fff-bfff-ffffffffffff".to_string()
            ]
        );
    }

    #[tokio::test]
    async fn explicit_scope_rejects_missing_branch_ref() {
        let branch_ref = RowsBranchRefReader::new(Vec::new());
        let error = resolve_provider_branch_ids(
            &branch_ref,
            &BranchBinding::explicit(),
            vec!["missing-branch".to_string()],
        )
        .await
        .expect_err("missing explicit branch should be rejected");

        assert_eq!(error.code, LixError::CODE_BRANCH_NOT_FOUND);
        assert!(
            error
                .message
                .contains("branch 'missing-branch' was not found")
        );
    }

    #[tokio::test]
    async fn all_visible_scope_loads_branch_refs_and_global() {
        let branch_ref = RowsBranchRefReader::new(vec![
            BranchHead {
                branch_id: "01920000-0000-7000-8000-0000000000b1".to_string(),
                commit_id: CommitId::for_test_label("commit-01920000-0000-7000-8000-0000000000b1"),
            },
            BranchHead {
                branch_id: "01920000-0000-7000-8000-0000000000a1".to_string(),
                commit_id: CommitId::for_test_label("commit-01920000-0000-7000-8000-0000000000a1"),
            },
        ]);
        let ids = resolve_provider_branch_ids(&branch_ref, &BranchBinding::explicit(), Vec::new())
            .await
            .expect("scope should resolve");

        assert_eq!(
            ids,
            vec![
                "01920000-0000-7000-8000-0000000000a1".to_string(),
                "01920000-0000-7000-8000-0000000000b1".to_string(),
                "ffffffff-ffff-7fff-bfff-ffffffffffff".to_string(),
            ]
        );
    }

    #[test]
    fn write_scope_uses_fallback_branch_when_branch_is_implicit() {
        let scope = resolve_write_branch_scope(
            None,
            None,
            Some("active-branch"),
            "INSERT into surface",
            "surface",
        )
        .expect("scope should resolve");

        assert_eq!(
            scope,
            WriteBranchScope {
                branch_id: "active-branch".to_string(),
                global: false,
            }
        );
    }

    #[test]
    fn write_scope_requires_branch_without_fallback() {
        let error = resolve_write_branch_scope(None, None, None, "INSERT into surface", "surface")
            .expect_err("missing branch should be rejected");

        assert!(
            error
                .to_string()
                .contains("INSERT into surface requires lixcol_branch_id")
        );
    }

    #[test]
    fn write_scope_derives_global_from_global_branch_id() {
        let scope = resolve_write_branch_scope(
            None,
            Some(GLOBAL_BRANCH_ID.to_string()),
            None,
            "INSERT into surface",
            "surface",
        )
        .expect("scope should resolve");

        assert_eq!(
            scope,
            WriteBranchScope {
                branch_id: GLOBAL_BRANCH_ID.to_string(),
                global: true,
            }
        );
    }

    #[test]
    fn write_scope_rejects_non_global_with_global_branch_id() {
        let error = resolve_write_branch_scope(
            Some(false),
            Some(GLOBAL_BRANCH_ID.to_string()),
            None,
            "INSERT into surface",
            "surface",
        )
        .expect_err("conflicting global/branch scope should be rejected");

        assert!(
            error
                .to_string()
                .contains("surface cannot set lixcol_global=false with global lixcol_branch_id")
        );
    }

    #[test]
    fn write_scope_rejects_global_with_non_global_branch_id() {
        let error = resolve_write_branch_scope(
            Some(true),
            Some("01920000-0000-7000-8000-0000000000a1".to_string()),
            None,
            "INSERT into surface",
            "surface",
        )
        .expect_err("conflicting global/branch scope should be rejected");

        assert!(
            error
                .to_string()
                .contains("surface cannot set lixcol_global=true with non-global lixcol_branch_id")
        );
    }

    struct RowsBranchRefReader {
        heads: Vec<BranchHead>,
    }

    impl RowsBranchRefReader {
        fn new(heads: Vec<BranchHead>) -> Self {
            Self { heads }
        }
    }

    #[async_trait]
    impl BranchRefReader for RowsBranchRefReader {
        async fn load_head(&self, branch_id: &str) -> Result<Option<BranchHead>, LixError> {
            Ok(self
                .heads
                .iter()
                .find(|head| head.branch_id == branch_id)
                .cloned())
        }

        async fn scan_heads(&self) -> Result<Vec<BranchHead>, LixError> {
            Ok(self.heads.clone())
        }
    }
}