grafeo-engine 0.5.39

Query engine and database management for Grafeo
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
//! MVCC Integration Tests
//!
//! Tests for Multi-Version Concurrency Control (MVCC) functionality.
//! These tests verify snapshot isolation, write-write conflict detection,
//! rollback behavior, and version chain garbage collection.

use std::sync::Arc;

use grafeo_common::types::{EpochId, Value};
use grafeo_core::graph::lpg::LpgStore;
use grafeo_engine::{
    GrafeoDB,
    transaction::{TransactionManager, TransactionState},
};

/// Helper to create a test store with some initial data.
fn create_test_store() -> Arc<LpgStore> {
    let store = Arc::new(LpgStore::new().unwrap());

    // Create some initial nodes
    let alice_id = store.create_node_with_props(
        &["Person"],
        [
            ("name", Value::String("Alix".into())),
            ("age", Value::Int64(30)),
        ],
    );
    let bob_id = store.create_node_with_props(
        &["Person"],
        [
            ("name", Value::String("Gus".into())),
            ("age", Value::Int64(25)),
        ],
    );

    // Create an edge
    store.create_edge(alice_id, bob_id, "KNOWS");

    store
}

// ============================================================================
// Snapshot Isolation Tests
// ============================================================================

#[test]
fn test_snapshot_isolation_reads_see_consistent_data() {
    // A transaction should see a consistent snapshot of data at its start time
    let store = create_test_store();
    let tx_manager = Arc::new(TransactionManager::new());

    // Start T1
    let tx1 = tx_manager.begin();
    let epoch1 = tx_manager.start_epoch(tx1).unwrap();

    // Create a new node (simulating T2 committing)
    let new_epoch = EpochId::new(epoch1.as_u64() + 10);
    let new_tx = tx_manager.begin();
    store.create_node_versioned(&["Person"], new_epoch, new_tx);
    tx_manager.commit(new_tx).unwrap();

    // T1 should not see the new node (created after T1's snapshot)
    let all_nodes = store.node_ids();
    let visible_at_epoch1: Vec<_> = all_nodes
        .iter()
        .filter(|id| store.get_node_versioned(**id, epoch1, tx1).is_some())
        .collect();

    // Should see initial 2 nodes, not the new one
    assert_eq!(
        visible_at_epoch1.len(),
        2,
        "T1 should only see 2 initial nodes"
    );
}

#[test]
fn test_transaction_sees_own_writes() {
    // A transaction should always see its own uncommitted writes
    let store = Arc::new(LpgStore::new().unwrap());
    let tx_manager = Arc::new(TransactionManager::new());

    let tx1 = tx_manager.begin();
    let epoch = tx_manager.current_epoch();

    // Create a node within the transaction
    let node_id = store.create_node_versioned(&["TestNode"], epoch, tx1);

    // Transaction should see its own node
    let visible = store.get_node_versioned(node_id, epoch, tx1);
    assert!(
        visible.is_some(),
        "Transaction should see its own uncommitted writes"
    );
}

#[test]
fn test_committed_writes_visible_to_new_transactions() {
    // After commit, writes should be visible to new transactions
    let store = Arc::new(LpgStore::new().unwrap());
    let tx_manager = Arc::new(TransactionManager::new());

    // T1 creates and commits
    let tx1 = tx_manager.begin();
    let epoch1 = tx_manager.current_epoch();
    let node_id = store.create_node_versioned(&["Committed"], epoch1, tx1);
    let commit_epoch = tx_manager.commit(tx1).unwrap();
    store.finalize_version_epochs(tx1, commit_epoch);

    // T2 starts after commit
    let tx2 = tx_manager.begin();
    let epoch2 = tx_manager.current_epoch();

    // T2 should see T1's committed node
    let visible = store.get_node_versioned(node_id, epoch2, tx2);
    assert!(
        visible.is_some(),
        "New transaction should see committed writes"
    );
}

// ============================================================================
// Write-Write Conflict Detection Tests
// ============================================================================

#[test]
fn test_write_write_conflict_detection() {
    // Two transactions writing to the same entity: first-writer-wins,
    // so the second record_write is rejected immediately.
    let store = create_test_store();
    let tx_manager = Arc::new(TransactionManager::new());

    let node_id = store.node_ids()[0]; // Get first node

    // T1 records a write (succeeds)
    let tx1 = tx_manager.begin();
    tx_manager.record_write(tx1, node_id).unwrap();

    // T2 tries to write the same entity (rejected by first-writer-wins)
    let tx2 = tx_manager.begin();
    let result = tx_manager.record_write(tx2, node_id);
    assert!(
        result.is_err(),
        "Second writer should be rejected immediately"
    );

    let err = result.unwrap_err();
    assert!(
        err.to_string().contains("conflict"),
        "Error should indicate write conflict: {}",
        err
    );
}

#[test]
fn test_committed_transaction_conflict_at_commit() {
    // T2 should fail at commit if T1 wrote to the same entity and committed
    // between T2's start and T2's commit.
    let store = create_test_store();
    let tx_manager = Arc::new(TransactionManager::new());

    let node_id = store.node_ids()[0];

    // Both transactions start (T2 records its start_epoch)
    let tx1 = tx_manager.begin();
    let tx2 = tx_manager.begin();

    // T1 writes and commits (advances epoch past T2's start)
    tx_manager.record_write(tx1, node_id).unwrap();
    tx_manager.commit(tx1).unwrap();

    // T2 writes to same entity (succeeds: T1 is no longer active)
    tx_manager.record_write(tx2, node_id).unwrap();

    // T2 commit fails: T1 committed a conflicting write after T2's start
    let result = tx_manager.commit(tx2);
    assert!(
        result.is_err(),
        "T2 should fail at commit due to write-write conflict with committed T1"
    );
    let err = result.unwrap_err();
    assert!(
        err.to_string().contains("conflict"),
        "Error should indicate write conflict: {err}"
    );
}

#[test]
fn test_post_commit_write_succeeds() {
    // After T1 commits, a new transaction started after the commit should
    // be able to write and commit to the same entity successfully.
    let store = create_test_store();
    let tx_manager = Arc::new(TransactionManager::new());

    let node_id = store.node_ids()[0];

    // T1 writes and commits
    let tx1 = tx_manager.begin();
    tx_manager.record_write(tx1, node_id).unwrap();
    tx_manager.commit(tx1).unwrap();

    // T2 starts after T1 committed, writes to same entity
    let tx2 = tx_manager.begin();
    tx_manager.record_write(tx2, node_id).unwrap();

    // T2 commits successfully (T1's commit is within T2's visible snapshot)
    assert!(
        tx_manager.commit(tx2).is_ok(),
        "T2 should commit after T1 committed (no conflict)"
    );
}

#[test]
fn test_non_overlapping_writes_succeed() {
    // Two transactions writing to different entities should both succeed
    let store = create_test_store();
    let tx_manager = Arc::new(TransactionManager::new());

    let nodes = store.node_ids();
    assert!(nodes.len() >= 2, "Need at least 2 nodes for this test");

    // T1 writes to node 0
    let tx1 = tx_manager.begin();
    tx_manager.record_write(tx1, nodes[0]).unwrap();

    // T2 writes to node 1
    let tx2 = tx_manager.begin();
    tx_manager.record_write(tx2, nodes[1]).unwrap();

    // Both should commit successfully
    assert!(tx_manager.commit(tx1).is_ok(), "T1 should commit");
    assert!(
        tx_manager.commit(tx2).is_ok(),
        "T2 should commit (no conflict)"
    );
}

// ============================================================================
// Rollback Tests
// ============================================================================

#[test]
fn test_rollback_makes_writes_invisible() {
    // After rollback, a transaction's writes should not be visible
    let store = Arc::new(LpgStore::new().unwrap());
    let tx_manager = Arc::new(TransactionManager::new());

    // T1 creates a node
    let tx1 = tx_manager.begin();
    let epoch = tx_manager.current_epoch();
    let node_id = store.create_node_versioned(&["Rollback"], epoch, tx1);
    tx_manager.record_write(tx1, node_id).unwrap();

    // Abort T1
    tx_manager.abort(tx1).unwrap();

    // Discard uncommitted versions for this transaction
    store.discard_uncommitted_versions(tx1);

    // New transaction should not see the aborted node
    let tx2 = tx_manager.begin();
    let epoch2 = tx_manager.current_epoch();
    let visible = store.get_node_versioned(node_id, epoch2, tx2);

    assert!(
        visible.is_none(),
        "Aborted transaction's writes should not be visible"
    );
}

#[test]
fn test_abort_releases_write_locks() {
    // After abort, another transaction should be able to write to the same entity
    let store = create_test_store();
    let tx_manager = Arc::new(TransactionManager::new());

    let node_id = store.node_ids()[0];

    // T1 records a write
    let tx1 = tx_manager.begin();
    tx_manager.record_write(tx1, node_id).unwrap();

    // Abort T1
    tx_manager.abort(tx1).unwrap();

    // GC the aborted transaction
    tx_manager.gc();

    // T2 should be able to write to the same entity
    let tx2 = tx_manager.begin();
    tx_manager.record_write(tx2, node_id).unwrap();

    // T2 should commit successfully
    assert!(
        tx_manager.commit(tx2).is_ok(),
        "T2 should commit after T1 aborted"
    );
}

// ============================================================================
// Version Chain GC Tests
// ============================================================================

#[test]
fn test_gc_cleans_up_completed_transactions() {
    // GC should clean up completed (committed/aborted) transactions
    let tx_manager = Arc::new(TransactionManager::new());

    // Create and complete several transactions
    for _ in 0..5 {
        let tx = tx_manager.begin();
        tx_manager.commit(tx).unwrap();
    }

    for _ in 0..3 {
        let tx = tx_manager.begin();
        tx_manager.abort(tx).unwrap();
    }

    // All transactions are completed
    assert_eq!(tx_manager.active_count(), 0, "No active transactions");

    // GC should clean them up
    let cleaned = tx_manager.gc();
    assert_eq!(
        cleaned, 8,
        "GC should clean up all 8 completed transactions"
    );
}

// ============================================================================
// Session Integration Tests (using GrafeoDB)
// ============================================================================

#[test]
fn test_session_transaction_isolation() {
    // Verify session-level transaction isolation
    let db = GrafeoDB::new_in_memory();
    let mut session = db.session();

    // Begin transaction
    session.begin_transaction().unwrap();

    // Create a node within transaction (using GQL INSERT syntax)
    session
        .execute("INSERT (:TestIsolation {value: 42})")
        .unwrap();

    // Commit
    session.commit().unwrap();

    // Query should find the node
    let result = session
        .execute("MATCH (n:TestIsolation) RETURN n.value")
        .unwrap();
    assert!(
        result.row_count() >= 1,
        "Node should be visible after commit"
    );
}

#[test]
fn test_session_rollback_state() {
    // Verify session rollback properly releases transaction state
    // NOTE: Full SQL rollback (discarding INSERT/UPDATE/DELETE) requires
    // the query executor to use versioned storage, which is a separate enhancement.
    let db = GrafeoDB::new_in_memory();
    let mut session = db.session();

    // Begin transaction
    session.begin_transaction().unwrap();
    assert!(
        session.in_transaction(),
        "Should be in transaction after begin"
    );

    // Rollback
    session.rollback().unwrap();
    assert!(
        !session.in_transaction(),
        "Should not be in transaction after rollback"
    );

    // Should be able to begin a new transaction
    session.begin_transaction().unwrap();
    assert!(
        session.in_transaction(),
        "Should be able to begin new transaction"
    );
    session.commit().unwrap();
}

// ============================================================================
// Edge Cases
// ============================================================================

#[test]
fn test_empty_transaction_commits_successfully() {
    // A transaction that does nothing should commit without issues
    let tx_manager = Arc::new(TransactionManager::new());

    let tx = tx_manager.begin();
    let result = tx_manager.commit(tx);

    assert!(
        result.is_ok(),
        "Empty transaction should commit successfully"
    );
}

#[test]
fn test_transaction_state_transitions() {
    // Verify proper state transitions
    let tx_manager = Arc::new(TransactionManager::new());

    let tx = tx_manager.begin();
    assert_eq!(tx_manager.state(tx), Some(TransactionState::Active));

    tx_manager.commit(tx).unwrap();
    assert_eq!(tx_manager.state(tx), Some(TransactionState::Committed));

    let tx2 = tx_manager.begin();
    tx_manager.abort(tx2).unwrap();
    assert_eq!(tx_manager.state(tx2), Some(TransactionState::Aborted));
}

#[test]
fn test_double_commit_fails() {
    // Committing an already committed transaction should fail
    let tx_manager = Arc::new(TransactionManager::new());

    let tx = tx_manager.begin();
    tx_manager.commit(tx).unwrap();

    let result = tx_manager.commit(tx);
    assert!(result.is_err(), "Double commit should fail");
}

#[test]
fn test_commit_after_abort_fails() {
    // Committing an aborted transaction should fail
    let tx_manager = Arc::new(TransactionManager::new());

    let tx = tx_manager.begin();
    tx_manager.abort(tx).unwrap();

    let result = tx_manager.commit(tx);
    assert!(result.is_err(), "Commit after abort should fail");
}

// ============================================================================
// Stress Tests
// ============================================================================

#[test]
fn test_many_concurrent_transactions() {
    // Verify system handles many concurrent transactions
    let store = Arc::new(LpgStore::new().unwrap());
    let tx_manager = Arc::new(TransactionManager::new());

    let mut transactions = Vec::new();

    // Start 100 transactions
    for _ in 0..100 {
        let tx = tx_manager.begin();
        let epoch = tx_manager.current_epoch();

        // Create a node in each transaction
        let node_id = store.create_node_versioned(&["Stress"], epoch, tx);
        tx_manager.record_write(tx, node_id).unwrap();

        transactions.push((tx, node_id));
    }

    assert_eq!(
        tx_manager.active_count(),
        100,
        "Should have 100 active transactions"
    );

    // Commit half, abort half
    for (i, (tx, _)) in transactions.iter().enumerate() {
        if i % 2 == 0 {
            tx_manager.commit(*tx).unwrap();
        } else {
            tx_manager.abort(*tx).unwrap();
        }
    }

    assert_eq!(
        tx_manager.active_count(),
        0,
        "No active transactions after completion"
    );

    // GC
    let cleaned = tx_manager.gc();
    assert_eq!(cleaned, 100, "GC should clean up all 100 transactions");
}

// ============================================================================
// Multi-Session Tests
// ============================================================================

#[test]
fn test_multiple_sessions_independent() {
    // Multiple sessions should operate independently
    let db = GrafeoDB::new_in_memory();

    let session1 = db.session();
    let session2 = db.session();

    // Session 1 creates data
    session1.execute("INSERT (:Session1Node)").unwrap();

    // Session 2 creates different data
    session2.execute("INSERT (:Session2Node)").unwrap();

    // Both should see their own data
    let r1 = session1.execute("MATCH (n:Session1Node) RETURN n").unwrap();
    let r2 = session2.execute("MATCH (n:Session2Node) RETURN n").unwrap();

    assert!(r1.row_count() >= 1, "Session 1 should see its data");
    assert!(r2.row_count() >= 1, "Session 2 should see its data");
}

#[test]
fn test_session_auto_commit_mode() {
    // Verify auto-commit mode works correctly
    let db = GrafeoDB::new_in_memory();
    let session = db.session();

    // Auto-commit should be on by default
    assert!(session.auto_commit());

    // Execute without explicit transaction
    session.execute("INSERT (:AutoCommit)").unwrap();

    // Data should be visible immediately in new session
    let session2 = db.session();
    let result = session2.execute("MATCH (n:AutoCommit) RETURN n").unwrap();
    assert!(
        result.row_count() >= 1,
        "Auto-committed data should be visible"
    );
}

// ==================== Edge type visibility after transaction commit ====================

/// Regression test: edges created on transaction-committed nodes must
/// retain their type label. Previously, the LpgStore epoch counter was not
/// synced with the TxManager epoch on commit, so `edge_type()` used a stale
/// epoch and couldn't see the edge record.
#[test]
fn edge_type_visible_after_tx_commit_autocommit_edge() {
    let db = GrafeoDB::new_in_memory();
    let mut session = db.session();

    // Create nodes inside a transaction
    session.begin_transaction().unwrap();
    session.execute("INSERT (:Person {id: 'tx_a'})").unwrap();
    session.execute("INSERT (:Person {id: 'tx_b'})").unwrap();
    session.commit().unwrap();

    // Create a typed edge in auto-commit (no transaction)
    session
        .execute("MATCH (a {id: 'tx_a'}), (b {id: 'tx_b'}) CREATE (a)-[:KNOWS]->(b)")
        .unwrap();

    // type(r) must return the edge type, not NULL
    let result = session
        .execute("MATCH ({id: 'tx_a'})-[r]->() RETURN type(r) AS t")
        .unwrap();
    assert_eq!(result.row_count(), 1, "Edge should exist");

    assert_eq!(
        result.rows()[0][0],
        Value::String("KNOWS".into()),
        "Edge type must not be NULL after tx-committed nodes"
    );
}

/// Same scenario but the edge is also created inside a new transaction.
#[test]
fn edge_type_visible_after_tx_commit_transaction_edge() {
    let db = GrafeoDB::new_in_memory();
    let mut session = db.session();

    // Create nodes in first transaction
    session.begin_transaction().unwrap();
    session.execute("INSERT (:Person {id: 'tx2_a'})").unwrap();
    session.execute("INSERT (:Person {id: 'tx2_b'})").unwrap();
    session.commit().unwrap();

    // Create edge in a second transaction
    session.begin_transaction().unwrap();
    session
        .execute("MATCH (a {id: 'tx2_a'}), (b {id: 'tx2_b'}) CREATE (a)-[:FRIENDS]->(b)")
        .unwrap();
    session.commit().unwrap();

    let result = session
        .execute("MATCH ({id: 'tx2_a'})-[r]->() RETURN type(r) AS t")
        .unwrap();
    assert_eq!(result.row_count(), 1);
    assert_eq!(
        result.rows()[0][0],
        Value::String("FRIENDS".into()),
        "Edge type must be visible after two sequential transactions"
    );
}

/// Nodes and edges created in the same transaction should work.
#[test]
fn edge_type_visible_same_tx() {
    let db = GrafeoDB::new_in_memory();
    let mut session = db.session();

    session.begin_transaction().unwrap();
    session.execute("INSERT (:Person {id: 'same_a'})").unwrap();
    session.execute("INSERT (:Person {id: 'same_b'})").unwrap();

    session
        .execute("MATCH (a {id: 'same_a'}), (b {id: 'same_b'}) CREATE (a)-[:WORKS_WITH]->(b)")
        .unwrap();

    session.commit().unwrap();

    let result = session
        .execute("MATCH ({id: 'same_a'})-[r]->() RETURN type(r) AS t")
        .unwrap();
    assert_eq!(result.row_count(), 1);
    assert_eq!(result.rows()[0][0], Value::String("WORKS_WITH".into()));
}

/// Bulk: many nodes in tx, many typed edges after commit.
#[test]
fn edge_types_preserved_bulk_after_tx() {
    let db = GrafeoDB::new_in_memory();
    let mut session = db.session();

    // Bulk-create nodes in a transaction
    session.begin_transaction().unwrap();
    for i in 0..20 {
        session
            .execute(&format!("INSERT (:Node {{idx: {i}}})"))
            .unwrap();
    }
    session.commit().unwrap();

    // Create typed edges in auto-commit
    for i in 0..19 {
        session
            .execute(&format!(
                "MATCH (a {{idx: {i}}}), (b {{idx: {next}}}) CREATE (a)-[:NEXT]->(b)",
                next = i + 1
            ))
            .unwrap();
    }

    // All 19 edges should have type NEXT
    let result = session
        .execute("MATCH ()-[r:NEXT]->() RETURN type(r) AS t")
        .unwrap();
    assert_eq!(
        result.row_count(),
        19,
        "All 19 typed edges should be found by type filter"
    );
}

/// Interleave auto-commit and transaction node creation.
#[test]
fn edge_types_interleaved_autocommit_and_tx() {
    let db = GrafeoDB::new_in_memory();
    let mut session = db.session();

    // Auto-commit node
    session.execute("INSERT (:Person {id: 'auto_x'})").unwrap();

    // Transaction node
    session.begin_transaction().unwrap();
    session.execute("INSERT (:Person {id: 'tx_y'})").unwrap();
    session.commit().unwrap();

    // Edge between auto-commit and tx nodes
    session
        .execute("MATCH (a {id: 'auto_x'}), (b {id: 'tx_y'}) CREATE (a)-[:LINKED]->(b)")
        .unwrap();

    let result = session
        .execute("MATCH ({id: 'auto_x'})-[r]->() RETURN type(r) AS t")
        .unwrap();
    assert_eq!(result.row_count(), 1);
    assert_eq!(result.rows()[0][0], Value::String("LINKED".into()),);
}