lix 0.18.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
//! Differential test harness target for fast and normal sql2 write execution.

#[cfg(test)]
mod tests {
    use crate::session::CreateBranchOptions;
    use crate::sql2::test_support::generators::{
        DifferentialExpectation, DifferentialParam, DifferentialProbe, DifferentialSqlCase,
        ExpectedExecution, deterministic_repro_cases, generated_dml_cases,
    };
    use crate::sql2::{WriteExecutorMode, WriteExecutorPath};
    use crate::storage_adapter::Memory;
    use crate::{ExecuteResult, LixError, Value, engine::Engine};

    #[derive(Debug, Clone)]
    struct DifferentialOutcome {
        execution: ExecutionSignature,
        executor_path: Option<WriteExecutorPath>,
        staged_rows: Vec<ProbeSnapshot>,
        final_rows: Vec<ProbeSnapshot>,
    }

    impl PartialEq for DifferentialOutcome {
        fn eq(&self, other: &Self) -> bool {
            self.execution == other.execution
                && self.staged_rows == other.staged_rows
                && self.final_rows == other.final_rows
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq)]
    enum ExecutionSignature {
        Ok { rows_affected: u64 },
        Err { code: String, message: String },
    }

    #[derive(Debug, Clone, PartialEq)]
    struct ProbeSnapshot {
        name: String,
        rows: Vec<Vec<Value>>,
    }

    struct ProbeQuery {
        name: String,
        sql: String,
        params: Vec<Value>,
    }

    #[tokio::test]
    async fn deterministic_known_repros_match_reference_writer() {
        for case in deterministic_repro_cases() {
            Box::pin(assert_case_matches_reference(&case)).await;
        }
    }

    #[tokio::test]
    async fn generated_dml_cases_match_reference_writer() {
        for case in generated_dml_cases() {
            Box::pin(assert_case_matches_reference(&case)).await;
        }
    }

    async fn assert_case_matches_reference(case: &DifferentialSqlCase) {
        let reference = Box::pin(run_case(case, WriteExecutorMode::ForceDataFusion)).await;
        let candidate_mode = match case.expectation {
            DifferentialExpectation::SemanticParityMayFallback => WriteExecutorMode::Auto,
            DifferentialExpectation::FastRequiredParity => WriteExecutorMode::ForceFast,
        };
        let candidate = Box::pin(run_case(case, candidate_mode)).await;
        assert_expected_execution(case, &reference.execution);
        assert_eq!(
            candidate, reference,
            "differential SQL seed '{}' diverged under {:?}\nSQL: {}",
            case.seed, candidate_mode, case.sql
        );
        if matches!(case.expected_execution, ExpectedExecution::Err { .. }) {
            Box::pin(assert_independent_no_mutation(case, &reference)).await;
        } else if case.expectation == DifferentialExpectation::FastRequiredParity {
            if matches!(
                reference.execution,
                ExecutionSignature::Ok { rows_affected: 0 }
            ) {
                Box::pin(assert_independent_no_mutation(case, &reference)).await;
            }
            assert_eq!(
                candidate.executor_path,
                Some(WriteExecutorPath::Fast),
                "differential SQL seed '{}' did not execute through the fast writer\nSQL: {}",
                case.seed,
                case.sql
            );
        } else if matches!(
            reference.execution,
            ExecutionSignature::Ok { rows_affected: 0 }
        ) {
            Box::pin(assert_independent_no_mutation(case, &reference)).await;
        }
    }

    async fn assert_independent_no_mutation(
        case: &DifferentialSqlCase,
        reference: &DifferentialOutcome,
    ) {
        let baseline = Box::pin(run_baseline(case)).await;
        assert_eq!(
            reference.staged_rows, baseline.staged_rows,
            "differential SQL seed '{}' changed staged rows in the independent no-mutation check\nSQL: {}",
            case.seed, case.sql
        );
        assert_eq!(
            reference.final_rows, baseline.final_rows,
            "differential SQL seed '{}' changed final rows in the independent no-mutation check\nSQL: {}",
            case.seed, case.sql
        );
    }

    async fn run_case(case: &DifferentialSqlCase, mode: WriteExecutorMode) -> DifferentialOutcome {
        let engine = open_initialized_engine().await;
        let session = engine.open_session().await.expect("session should open");
        create_probe_branches(&session).await;
        let active_branch_id = session
            .active_branch_id()
            .await
            .expect("differential session should have an active branch");

        for setup_sql in case.setup_sql {
            session
                .execute_with_write_executor_mode(
                    setup_sql,
                    &[],
                    WriteExecutorMode::ForceDataFusion,
                )
                .await
                .unwrap_or_else(|error| {
                    panic!(
                        "differential SQL seed '{}' setup failed\nSQL: {}\nerror: {:?}",
                        case.seed, setup_sql, error
                    )
                });
        }

        let params = differential_params(case.params);
        let mut transaction = session
            .begin_transaction()
            .await
            .expect("differential transaction should open");
        for setup_sql in case.transaction_setup_sql {
            Box::pin(transaction.execute_with_write_executor_mode(
                setup_sql,
                &[],
                WriteExecutorMode::ForceDataFusion,
            ))
            .await
            .unwrap_or_else(|error| {
                panic!(
                    "differential SQL seed '{}' transaction setup failed\nSQL: {}\nerror: {:?}",
                    case.seed, setup_sql, error
                )
            });
        }
        let execution_result = Box::pin(transaction.execute_with_write_executor_mode_and_trace(
            case.sql.as_ref(),
            &params,
            mode,
        ))
        .await;
        let execution = execution_signature(&execution_result);
        let executor_path = execution_result
            .as_ref()
            .ok()
            .and_then(|(_result, path)| *path);
        let staged_rows = Box::pin(probe_transaction_state(
            &mut transaction,
            case.probes,
            &active_branch_id,
        ))
        .await;

        match execution_result {
            Ok(_) => transaction
                .commit()
                .await
                .map(|_| ())
                .expect("successful differential case should commit"),
            Err(_) => transaction
                .rollback()
                .await
                .expect("failed differential case should rollback"),
        }

        let final_rows = probe_session_state(&session, case.probes, &active_branch_id).await;
        DifferentialOutcome {
            execution,
            executor_path,
            staged_rows,
            final_rows,
        }
    }

    async fn run_baseline(case: &DifferentialSqlCase) -> DifferentialOutcome {
        let engine = open_initialized_engine().await;
        let session = engine.open_session().await.expect("session should open");
        create_probe_branches(&session).await;
        let active_branch_id = session
            .active_branch_id()
            .await
            .expect("differential session should have an active branch");

        for setup_sql in case.setup_sql {
            session
                .execute_with_write_executor_mode(
                    setup_sql,
                    &[],
                    WriteExecutorMode::ForceDataFusion,
                )
                .await
                .unwrap_or_else(|error| {
                    panic!(
                        "differential SQL seed '{}' baseline setup failed\nSQL: {}\nerror: {:?}",
                        case.seed, setup_sql, error
                    )
                });
        }

        let mut transaction = session
            .begin_transaction()
            .await
            .expect("differential baseline transaction should open");
        for setup_sql in case.transaction_setup_sql {
            Box::pin(
                transaction.execute_with_write_executor_mode(
                    setup_sql,
                    &[],
                    WriteExecutorMode::ForceDataFusion,
                ),
            )
            .await
            .unwrap_or_else(|error| {
                panic!(
                    "differential SQL seed '{}' baseline transaction setup failed\nSQL: {}\nerror: {:?}",
                    case.seed, setup_sql, error
                )
            });
        }

        let staged_rows = Box::pin(probe_transaction_state(
            &mut transaction,
            case.probes,
            &active_branch_id,
        ))
        .await;
        transaction
            .commit()
            .await
            .expect("baseline differential case should commit setup");
        let final_rows = probe_session_state(&session, case.probes, &active_branch_id).await;

        DifferentialOutcome {
            execution: ExecutionSignature::Ok { rows_affected: 0 },
            executor_path: None,
            staged_rows,
            final_rows,
        }
    }

    async fn open_initialized_engine() -> Engine {
        let storage = Memory::new();
        Engine::initialize(storage.clone())
            .await
            .expect("unit storage should initialize");
        Engine::new(storage)
            .await
            .expect("engine should open over initialized unit storage")
    }

    async fn create_probe_branches(session: &crate::session::SessionContext) {
        for id in [
            "01920000-0000-7000-8000-0000000000a1",
            "01920000-0000-7000-8000-0000000000b1",
        ] {
            session
                .create_branch(CreateBranchOptions {
                    id: Some(id.to_string()),
                    name: id.to_string(),
                    from_commit_id: None,
                })
                .await
                .unwrap_or_else(|error| panic!("failed to create probe branch {id}: {error:?}"));
        }
    }

    fn execution_signature(
        result: &Result<(ExecuteResult, Option<WriteExecutorPath>), LixError>,
    ) -> ExecutionSignature {
        match result {
            Ok((result, _path)) => ExecutionSignature::Ok {
                rows_affected: result.rows_affected(),
            },
            Err(error) => ExecutionSignature::Err {
                code: error.code.clone(),
                message: error.message.clone(),
            },
        }
    }

    fn assert_expected_execution(case: &DifferentialSqlCase, execution: &ExecutionSignature) {
        match (case.expected_execution, execution) {
            (ExpectedExecution::Ok, ExecutionSignature::Ok { .. })
            | (ExpectedExecution::Err { .. }, ExecutionSignature::Err { .. }) => {}
            (ExpectedExecution::Ok, ExecutionSignature::Err { code, message }) => {
                panic!(
                    "differential SQL seed '{}' should succeed but failed with {code}: {message}\nSQL: {}",
                    case.seed, case.sql
                );
            }
            (ExpectedExecution::Err { code }, ExecutionSignature::Ok { rows_affected }) => {
                panic!(
                    "differential SQL seed '{}' should fail with {code} but succeeded with {rows_affected} rows affected\nSQL: {}",
                    case.seed, case.sql
                );
            }
        }
        if let (
            ExpectedExecution::Err {
                code: expected_code,
            },
            ExecutionSignature::Err { code, message },
        ) = (case.expected_execution, execution)
        {
            assert_eq!(
                code, expected_code,
                "differential SQL seed '{}' failed with the wrong error code: {code}: {message}\nSQL: {}",
                case.seed, case.sql
            );
        }
    }

    fn differential_params(params: &[DifferentialParam]) -> Vec<Value> {
        params
            .iter()
            .map(|param| match param {
                DifferentialParam::Jsonb(value) => {
                    let value =
                        serde_json::from_str(value).expect("differential JSON param should parse");
                    Value::Jsonb(value)
                }
                DifferentialParam::Text(value) => Value::Text((*value).to_string()),
                DifferentialParam::Blob(value) => Value::Blob((*value).to_vec().into()),
            })
            .collect()
    }

    async fn probe_session_state(
        session: &crate::session::SessionContext,
        probes: &[DifferentialProbe],
        _active_branch_id: &str,
    ) -> Vec<ProbeSnapshot> {
        let mut snapshots = Vec::with_capacity(probes.len());
        for probe in probes {
            let query = probe_query(probe);
            snapshots.push(ProbeSnapshot {
                name: query.name,
                rows: session
                    .execute(&query.sql, &query.params)
                    .await
                    .unwrap_or_else(|error| {
                        panic!(
                            "final differential probe failed\nSQL: {}\nerror: {error:?}",
                            query.sql
                        )
                    })
                    .rows()
                    .iter()
                    .map(|row| row.values().to_vec())
                    .collect(),
            });
        }
        snapshots
    }

    async fn probe_transaction_state(
        transaction: &mut crate::session::SessionTransaction,
        probes: &[DifferentialProbe],
        _active_branch_id: &str,
    ) -> Vec<ProbeSnapshot> {
        let mut snapshots = Vec::with_capacity(probes.len());
        for probe in probes {
            let query = probe_query(probe);
            snapshots.push(ProbeSnapshot {
                name: query.name,
                rows: transaction
                    .execute(&query.sql, &query.params)
                    .await
                    .unwrap_or_else(|error| {
                        panic!(
                            "staged differential probe failed\nSQL: {}\nerror: {error:?}",
                            query.sql
                        )
                    })
                    .rows()
                    .iter()
                    .map(|row| row.values().to_vec())
                    .collect(),
            });
        }
        snapshots
    }

    fn probe_query(probe: &DifferentialProbe) -> ProbeQuery {
        match probe {
            DifferentialProbe::RegisteredSchemaActive => ProbeQuery {
                name: "lix_registered_schema".to_string(),
                sql: "SELECT schema_key, value, lixcol_metadata, lixcol_global, lixcol_untracked \
                 FROM lix_registered_schema \
                 ORDER BY schema_key"
                    .to_string(),
                params: Vec::new(),
            },
            DifferentialProbe::LixFileActive { paths } => {
                let mut params = Vec::with_capacity(paths.len());
                let placeholders = paths
                    .iter()
                    .enumerate()
                    .map(|(index, path)| {
                        params.push(Value::Text((*path).to_string()));
                        format!("${}", index + 1)
                    })
                    .collect::<Vec<_>>()
                    .join(", ");
                ProbeQuery {
                    name: format!("lix_file:{paths:?}"),
                    sql: format!(
                        "SELECT path, content \
                         FROM lix_file \
                         WHERE path IN ({placeholders}) \
                         ORDER BY path"
                    ),
                    params,
                }
            }
        }
    }
}