surreal-sync-runtime 0.6.0

Shared runtime: apply pipeline, init, SurrealDB config, and transform loading for surreal-sync
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
//! Unit tests for Phase 1: InPlaceTransform, CowBatch, Pipeline.

use crate::pipeline::{CowBatch, ExternalTransform, InPlaceTransform, Passthrough, Pipeline};
use anyhow::{bail, Result};
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use surreal_sync_core::{Change, ChangeOp, Row, Value};

fn sample_row(name: &str) -> Row {
    Row::builder("users", 0, Value::Int64(1))
        .field(
            "name",
            Value::VarChar {
                value: name.to_string(),
                length: 64,
            },
        )
        .build()
}

fn sample_change(name: &str) -> Change {
    let mut data = HashMap::new();
    data.insert(
        "name".to_string(),
        Value::VarChar {
            value: name.to_string(),
            length: 64,
        },
    );
    Change::create("users", Value::Int64(1), data)
}

/// Mutating transform used to prove make_mut / stage dispatch.
struct Rename {
    to: String,
}

impl InPlaceTransform for Rename {
    fn transform(
        &self,
        _table: &str,
        _id: &mut Value,
        fields: Option<&mut HashMap<String, Value>>,
    ) -> Result<()> {
        if let Some(fields) = fields {
            fields.insert(
                "name".to_string(),
                Value::VarChar {
                    value: self.to.clone(),
                    length: 64,
                },
            );
        }
        Ok(())
    }
}

/// Counts how many times per-item transforms are invoked.
struct Counting<T> {
    inner: T,
    rows: AtomicUsize,
    changes: AtomicUsize,
}

impl<T: InPlaceTransform> InPlaceTransform for Counting<T> {
    fn transform(
        &self,
        table: &str,
        id: &mut Value,
        fields: Option<&mut HashMap<String, Value>>,
    ) -> Result<()> {
        // Count via the concrete path that will run (row vs change) in slice helpers.
        self.inner.transform(table, id, fields)
    }

    fn transform_row(&self, row: &mut Row) -> Result<()> {
        self.rows.fetch_add(1, Ordering::SeqCst);
        self.inner.transform_row(row)
    }

    fn transform_change(&self, change: &mut Change) -> Result<()> {
        self.changes.fetch_add(1, Ordering::SeqCst);
        self.inner.transform_change(change)
    }
}

/// Always fails; used to assert later stages are not reached.
struct AlwaysFail;

impl InPlaceTransform for AlwaysFail {
    fn transform(
        &self,
        _table: &str,
        _id: &mut Value,
        _fields: Option<&mut HashMap<String, Value>>,
    ) -> Result<()> {
        bail!("stage failed")
    }
}

#[test]
fn empty_pipeline_is_identity() {
    let pipeline = Pipeline::new();
    assert!(pipeline.is_identity());
    assert!(pipeline.is_empty());
    assert_eq!(pipeline.len(), 0);

    let rows = vec![sample_row("alice")];
    let out = pipeline.apply_rows(rows).unwrap();
    assert_eq!(out.len(), 1);
    assert_eq!(
        out[0].get_field("name"),
        Some(&Value::VarChar {
            value: "alice".to_string(),
            length: 64,
        })
    );

    let changes = vec![sample_change("bob")];
    let out = pipeline.apply_changes(changes).unwrap();
    assert_eq!(out[0].operation, ChangeOp::Create);
}

/// Empty pipeline short-circuits before any stage dispatch.
///
/// Phase 1 can only assert emptiness + apply no-op here. Phase 2's apply
/// loop must gate on [`Pipeline::is_identity`] so the sync identity path never
/// enters transform dispatch when there are no stages.
#[test]
fn empty_pipeline_is_identity_short_circuit() {
    let pipeline = Pipeline::new();
    assert!(pipeline.is_identity());
    assert!(pipeline.stages().is_empty());

    let rows = vec![sample_row("x")];
    let out = pipeline.apply_rows(rows).unwrap();
    assert_eq!(
        out[0].get_field("name"),
        Some(&Value::VarChar {
            value: "x".to_string(),
            length: 64,
        })
    );

    let changes = vec![sample_change("y")];
    let out = pipeline.apply_changes(changes).unwrap();
    assert_eq!(
        out[0].fields.as_ref().unwrap().get("name"),
        Some(&Value::VarChar {
            value: "y".to_string(),
            length: 64,
        })
    );

    // Contrast: a non-empty pipeline with a counting stage *does* dispatch.
    let counter = Arc::new(Counting {
        inner: Passthrough,
        rows: AtomicUsize::new(0),
        changes: AtomicUsize::new(0),
    });
    let mut with_stage = Pipeline::new();
    with_stage.push_inplace_arc(counter.clone());
    assert!(!with_stage.is_identity());
    with_stage.apply_rows(vec![sample_row("z")]).unwrap();
    assert_eq!(counter.rows.load(Ordering::SeqCst), 1);
}

#[test]
fn lone_passthrough_is_not_identity() {
    let mut pipeline = Pipeline::new();
    pipeline.push_inplace(Passthrough);
    assert!(!pipeline.is_identity());
    assert_eq!(pipeline.len(), 1);
    // Still a no-op on data, but stages are dispatched (not the zero-dispatch path).
    let out = pipeline.apply_rows(vec![sample_row("alice")]).unwrap();
    assert_eq!(
        out[0].get_field("name"),
        Some(&Value::VarChar {
            value: "alice".to_string(),
            length: 64,
        })
    );
}

#[test]
fn passthrough_on_owned_vec_mutates_in_place_without_realloc() {
    let mut pipeline = Pipeline::new();
    pipeline.push_inplace(Passthrough);

    let mut rows = vec![sample_row("alice"), sample_row("bob")];
    let ptr_before = rows.as_ptr();
    pipeline.transform_rows_inplace(&mut rows).unwrap();
    assert_eq!(rows.as_ptr(), ptr_before);
    assert_eq!(
        rows[0].get_field("name"),
        Some(&Value::VarChar {
            value: "alice".to_string(),
            length: 64,
        })
    );
}

#[test]
fn cowbatch_passthrough_unique_arc_no_clone() {
    let row = sample_row("alice");
    let arc = Arc::new(row);
    let ptr_before = Arc::as_ptr(&arc);

    let mut batch = CowBatch::new(vec![arc]);
    batch.apply_inplace(&Passthrough).unwrap();

    let ptr_after = Arc::as_ptr(&batch.items[0]);
    assert_eq!(
        ptr_before, ptr_after,
        "unique Arc must not be cloned by make_mut on passthrough"
    );
    assert_eq!(Arc::strong_count(&batch.items[0]), 1);
}

/// Regression: shared Arc + Passthrough still clones — `make_mut` runs before
/// the no-op transform body.
#[test]
fn cowbatch_shared_passthrough_still_clones() {
    let row = sample_row("alice");
    let shared = Arc::new(row);
    let held = Arc::clone(&shared);
    assert_eq!(Arc::strong_count(&shared), 2);

    let ptr_before = Arc::as_ptr(&shared);
    let mut batch = CowBatch::new(vec![shared]);
    batch.apply_inplace(&Passthrough).unwrap();

    let ptr_after = Arc::as_ptr(&batch.items[0]);
    assert_ne!(
        ptr_before, ptr_after,
        "shared Arc must be cloned by make_mut even for Passthrough"
    );
    assert_eq!(Arc::strong_count(&batch.items[0]), 1);
    assert_eq!(Arc::strong_count(&held), 1);
    // Original holder unchanged; batch item is a distinct clone of the same data.
    assert_eq!(
        held.get_field("name"),
        Some(&Value::VarChar {
            value: "alice".to_string(),
            length: 64,
        })
    );
    assert_eq!(
        batch.items[0].get_field("name"),
        Some(&Value::VarChar {
            value: "alice".to_string(),
            length: 64,
        })
    );
}

#[test]
fn cowbatch_make_mut_clones_only_when_shared() {
    let change = sample_change("alice");
    let shared = Arc::new(change);
    let held = Arc::clone(&shared);
    assert_eq!(Arc::strong_count(&shared), 2);

    let ptr_before = Arc::as_ptr(&shared);
    let mut batch = CowBatch::new(vec![shared]);

    // Mutating transform: make_mut must clone because Arc is shared.
    batch
        .apply_inplace(&Rename {
            to: "carol".to_string(),
        })
        .unwrap();

    let ptr_after = Arc::as_ptr(&batch.items[0]);
    assert_ne!(
        ptr_before, ptr_after,
        "shared Arc must be cloned by make_mut before mutation"
    );
    // Original holder still sees the old value (COW).
    assert_eq!(
        held.fields.as_ref().unwrap().get("name"),
        Some(&Value::VarChar {
            value: "alice".to_string(),
            length: 64,
        })
    );
    assert_eq!(
        batch.items[0].fields.as_ref().unwrap().get("name"),
        Some(&Value::VarChar {
            value: "carol".to_string(),
            length: 64,
        })
    );
    assert_eq!(Arc::strong_count(&batch.items[0]), 1);
    assert_eq!(Arc::strong_count(&held), 1);
}

#[test]
fn cowbatch_unique_arc_mutating_transform_no_clone() {
    let change = sample_change("alice");
    let arc = Arc::new(change);
    let ptr_before = Arc::as_ptr(&arc);

    let mut batch = CowBatch::new(vec![arc]);
    batch
        .apply_inplace(&Rename {
            to: "dave".to_string(),
        })
        .unwrap();

    assert_eq!(
        Arc::as_ptr(&batch.items[0]),
        ptr_before,
        "unique Arc should mutate in place without clone"
    );
    assert_eq!(
        batch.items[0].fields.as_ref().unwrap().get("name"),
        Some(&Value::VarChar {
            value: "dave".to_string(),
            length: 64,
        })
    );
}

#[test]
fn pipeline_applies_inplace_stages_in_order() {
    let counter = Arc::new(Counting {
        inner: Rename {
            to: "step1".to_string(),
        },
        rows: AtomicUsize::new(0),
        changes: AtomicUsize::new(0),
    });

    let mut pipeline = Pipeline::new();
    pipeline.push_inplace_arc(counter.clone());
    pipeline.push_inplace(Rename {
        to: "step2".to_string(),
    });

    let out = pipeline.apply_rows(vec![sample_row("alice")]).unwrap();
    assert_eq!(counter.rows.load(Ordering::SeqCst), 1);
    assert_eq!(
        out[0].get_field("name"),
        Some(&Value::VarChar {
            value: "step2".to_string(),
            length: 64,
        })
    );
}

#[test]
fn pipeline_applies_changes_stages_in_order() {
    let step1 = Arc::new(Counting {
        inner: Rename {
            to: "step1".to_string(),
        },
        rows: AtomicUsize::new(0),
        changes: AtomicUsize::new(0),
    });
    let step2 = Arc::new(Counting {
        inner: Rename {
            to: "step2".to_string(),
        },
        rows: AtomicUsize::new(0),
        changes: AtomicUsize::new(0),
    });

    let mut pipeline = Pipeline::new();
    pipeline.push_inplace_arc(step1.clone());
    pipeline.push_inplace_arc(step2.clone());

    let out = pipeline
        .apply_changes(vec![sample_change("alice")])
        .unwrap();
    assert_eq!(step1.changes.load(Ordering::SeqCst), 1);
    assert_eq!(step2.changes.load(Ordering::SeqCst), 1);
    assert_eq!(
        out[0].fields.as_ref().unwrap().get("name"),
        Some(&Value::VarChar {
            value: "step2".to_string(),
            length: 64,
        })
    );

    // Same ordering via transform_changes_inplace.
    let mut changes = vec![sample_change("bob")];
    pipeline.transform_changes_inplace(&mut changes).unwrap();
    assert_eq!(step1.changes.load(Ordering::SeqCst), 2);
    assert_eq!(step2.changes.load(Ordering::SeqCst), 2);
    assert_eq!(
        changes[0].fields.as_ref().unwrap().get("name"),
        Some(&Value::VarChar {
            value: "step2".to_string(),
            length: 64,
        })
    );
}

#[test]
fn failing_stage_stops_later_stages_rows() {
    let later = Arc::new(Counting {
        inner: Rename {
            to: "should-not-run".to_string(),
        },
        rows: AtomicUsize::new(0),
        changes: AtomicUsize::new(0),
    });

    let mut pipeline = Pipeline::new();
    pipeline.push_inplace(AlwaysFail);
    pipeline.push_inplace_arc(later.clone());

    let err = pipeline.apply_rows(vec![sample_row("alice")]).unwrap_err();
    assert!(
        err.to_string().contains("stage failed"),
        "unexpected error: {err}"
    );
    assert_eq!(
        later.rows.load(Ordering::SeqCst),
        0,
        "later stage must not run after earlier failure"
    );
}

#[test]
fn failing_stage_stops_later_stages_changes() {
    let later = Arc::new(Counting {
        inner: Rename {
            to: "should-not-run".to_string(),
        },
        rows: AtomicUsize::new(0),
        changes: AtomicUsize::new(0),
    });

    let mut pipeline = Pipeline::new();
    pipeline.push_inplace(AlwaysFail);
    pipeline.push_inplace_arc(later.clone());

    let err = pipeline
        .apply_changes(vec![sample_change("alice")])
        .unwrap_err();
    assert!(
        err.to_string().contains("stage failed"),
        "unexpected error: {err}"
    );
    assert_eq!(
        later.changes.load(Ordering::SeqCst),
        0,
        "later stage must not run after earlier failure"
    );
}

#[test]
fn pipeline_external_sync_inplace_errors() {
    let transport = crate::pipeline::test_support::ScriptedExternalTransport::new();
    let mut pipeline = Pipeline::new();
    pipeline.push_external(ExternalTransform::with_transport(std::sync::Arc::new(
        transport,
    )));
    let err = pipeline.apply_rows(vec![sample_row("alice")]).unwrap_err();
    assert!(
        err.to_string().contains("BatchTransformer") || err.to_string().contains("async"),
        "unexpected error: {err}"
    );
}

#[test]
fn pipeline_external_sync_relation_inplace_errors() {
    use surreal_sync_core::{Relation, RelationChange, ThingRef};

    let transport = crate::pipeline::test_support::ScriptedExternalTransport::new();
    let mut pipeline = Pipeline::new();
    pipeline.push_external(ExternalTransform::with_transport(std::sync::Arc::new(
        transport,
    )));

    let rel = Relation::new(
        "follows",
        Value::Int64(1),
        ThingRef::new("users", Value::Int64(1)),
        ThingRef::new("users", Value::Int64(2)),
        HashMap::new(),
    );

    let err_changes = pipeline
        .apply_relation_changes(vec![RelationChange::create(rel.clone())])
        .unwrap_err();
    assert!(
        err_changes.to_string().contains("BatchTransformer")
            || err_changes.to_string().contains("async")
            || err_changes.to_string().contains("transform_relation"),
        "sync apply_relation_changes with External must bail: {err_changes}"
    );

    let err_rels = pipeline.apply_relations(vec![rel]).unwrap_err();
    assert!(
        err_rels.to_string().contains("BatchTransformer")
            || err_rels.to_string().contains("async")
            || err_rels.to_string().contains("transform_relation"),
        "sync apply_relations with External must bail: {err_rels}"
    );
}

/// Custom BatchTransformer that only overrides row/change paths must not
/// silently no-op relation batches (fail closed by default).
#[tokio::test]
async fn batch_transformer_default_relation_methods_fail_closed() {
    use crate::pipeline::BatchTransformer;
    use async_trait::async_trait;
    use surreal_sync_core::{Relation, RelationChange, ThingRef};

    struct ChangesOnly;

    #[async_trait]
    impl BatchTransformer for ChangesOnly {
        fn is_identity(&self) -> bool {
            false
        }

        async fn transform_changes(
            &self,
            _batch_id: u64,
            changes: Vec<Change>,
        ) -> Result<Vec<Change>> {
            Ok(changes)
        }

        async fn transform_rows(&self, _batch_id: u64, rows: Vec<Row>) -> Result<Vec<Row>> {
            Ok(rows)
        }
    }

    let t = ChangesOnly;
    let rel = Relation::new(
        "follows",
        Value::Int64(1),
        ThingRef::new("users", Value::Int64(1)),
        ThingRef::new("users", Value::Int64(2)),
        HashMap::new(),
    );

    let err = t
        .transform_relation_changes(1, vec![RelationChange::create(rel.clone())])
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("transform_relation_changes")
            && err.to_string().contains("not implemented"),
        "unexpected: {err}"
    );

    let err = t.transform_relations(1, vec![rel]).await.unwrap_err();
    assert!(
        err.to_string().contains("transform_relations")
            && err.to_string().contains("not implemented"),
        "unexpected: {err}"
    );

    // Mixed events also fail closed via the default transform_events path.
    let err = t
        .transform_events(
            1,
            vec![
                crate::pipeline::ApplyEvent::Change(sample_change("a")),
                crate::pipeline::ApplyEvent::relation_change(RelationChange::create(
                    Relation::new(
                        "follows",
                        Value::Int64(2),
                        ThingRef::new("users", Value::Int64(3)),
                        ThingRef::new("users", Value::Int64(4)),
                        HashMap::new(),
                    ),
                )),
            ],
        )
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("transform_relation_changes"),
        "mixed events must not silently drop relations: {err}"
    );
}

#[test]
fn cowbatch_from_owned_and_row_apply() {
    let mut batch = CowBatch::from_owned(vec![sample_row("alice")]);
    assert_eq!(batch.len(), 1);
    assert!(!batch.is_empty());
    batch
        .apply_inplace(&Rename {
            to: "zoe".to_string(),
        })
        .unwrap();
    let items = batch.into_items();
    assert_eq!(
        items[0].get_field("name"),
        Some(&Value::VarChar {
            value: "zoe".to_string(),
            length: 64,
        })
    );
}