triviumdb 0.7.0

A high-performance memory-mmap hybrid search engine built for AI, combining dense vector, sparse text, graph relations, and JSON metadata.
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
#![allow(non_snake_case)]
//! TQL 聚合函数、文档过滤操作符与事务系统集成测试
//!
//! 验证范围:
//! - `query/tql_executor.rs`: 聚合函数 (count/sum/avg/min/max/collect)、分组聚合、RETURN AS 别名
//! - `query/tql_parser.rs`: $in/$nin/$exists/$all/$type/$size/$and/$or 操作符、MATCHES 谓词、NOT 谓词
//! - `database/transaction.rs`: begin_tx 全操作组合 (insert/link/unlink/update_payload/update_vector/delete)、
//!   预检失败 (不存在节点、维度不匹配、重复 ID)
//! - `cognitive.rs`: NMF 语义分析 (聚焦/均匀/新颖/零向量)
//! - `database/mod.rs`: WAL 回放幂等性、多次 flush 幂等性

use triviumdb::database::Database;

const DIM: usize = 4;

fn tmp_db(name: &str) -> String {
    let dir = std::env::temp_dir().join("triviumdb_test");
    std::fs::create_dir_all(&dir).ok();
    let path = dir
        .join(format!("cov4_{}", name))
        .to_string_lossy()
        .to_string();
    cleanup(&path);
    path
}

fn cleanup(path: &str) {
    for ext in &["", ".wal", ".vec", ".lock", ".flush_ok", ".tmp", ".vec.tmp"] {
        std::fs::remove_file(format!("{}{}", path, ext)).ok();
    }
}

// ════════════════════════════════════════════════════════════════
//  tql_executor.rs — 聚合函数 (lines 1114-1267)
// ════════════════════════════════════════════════════════════════

fn seed_scored_graph(path: &str) -> Database<f32> {
    let mut db = Database::<f32>::open(path, DIM).unwrap();
    for i in 0..10u32 {
        db.insert(
            &[i as f32, 0.0, 0.0, 0.0],
            serde_json::json!({
                "type": "item",
                "name": format!("item_{}", i),
                "score": i as f64 * 10.0,
                "tags": ["a", "b", "c"],
                "group": if i < 5 { "alpha" } else { "beta" }
            }),
        )
        .unwrap();
    }

    let ids = db.all_node_ids();
    for i in 0..ids.len() - 1 {
        db.link(ids[i], ids[i + 1], "next", 1.0).unwrap();
    }
    db
}

/// count(a) 聚合
#[test]
fn COV4_01_tql_agg_count() {
    let path = tmp_db("agg_count");
    let db = seed_scored_graph(&path);

    let results = db.tql(r#"MATCH (a)-[:next]->(b) RETURN count(a)"#).unwrap();
    assert!(!results.is_empty(), "count 聚合应返回结果");

    cleanup(&path);
}

/// sum(a.score) 聚合
#[test]
fn COV4_02_tql_agg_sum() {
    let path = tmp_db("agg_sum");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"MATCH (a)-[:next]->(b) RETURN sum(a.score)"#)
        .unwrap();
    assert!(!results.is_empty());

    cleanup(&path);
}

/// avg(a.score) 聚合
#[test]
fn COV4_03_tql_agg_avg() {
    let path = tmp_db("agg_avg");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"MATCH (a)-[:next]->(b) RETURN avg(a.score)"#)
        .unwrap();
    assert!(!results.is_empty());

    cleanup(&path);
}

/// min(a.score) 聚合
#[test]
fn COV4_04_tql_agg_min() {
    let path = tmp_db("agg_min");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"MATCH (a)-[:next]->(b) RETURN min(a.score)"#)
        .unwrap();
    assert!(!results.is_empty());

    cleanup(&path);
}

/// max(a.score) 聚合
#[test]
fn COV4_05_tql_agg_max() {
    let path = tmp_db("agg_max");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"MATCH (a)-[:next]->(b) RETURN max(a.score)"#)
        .unwrap();
    assert!(!results.is_empty());

    cleanup(&path);
}

/// collect(a) 聚合
#[test]
fn COV4_06_tql_agg_collect() {
    let path = tmp_db("agg_collect");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"MATCH (a)-[:next]->(b) RETURN collect(a)"#)
        .unwrap();
    assert!(!results.is_empty());

    cleanup(&path);
}

/// 混合聚合: 分组列 + 聚合列
#[test]
fn COV4_07_tql_agg_with_group() {
    let path = tmp_db("agg_group");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"FIND {type: "item"} RETURN _.group, count(_)"#)
        .unwrap();
    assert!(!results.is_empty());

    cleanup(&path);
}

/// RETURN 带 alias (AS)
#[test]
fn COV4_08_tql_return_alias() {
    let path = tmp_db("agg_alias");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"MATCH (a)-[:next]->(b) RETURN count(a) AS total, max(a.score) AS top_score"#)
        .unwrap();
    assert!(!results.is_empty());

    cleanup(&path);
}

// ════════════════════════════════════════════════════════════════
//  tql_parser.rs — 更多 Filter 操作符
// ════════════════════════════════════════════════════════════════

/// $in 操作符
#[test]
fn COV4_09_filter_in() {
    let path = tmp_db("filter_in");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"FIND {name: {$in: ["item_1", "item_3", "item_5"]}} RETURN *"#)
        .unwrap();
    assert_eq!(results.len(), 3, "$in 应匹配 3 个");

    cleanup(&path);
}

/// $nin 操作符
#[test]
fn COV4_10_filter_nin() {
    let path = tmp_db("filter_nin");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"FIND {name: {$nin: ["item_1", "item_3"]}} RETURN *"#)
        .unwrap();
    assert_eq!(results.len(), 8, "$nin 应排除 2 个");

    cleanup(&path);
}

/// $exists 操作符
#[test]
fn COV4_11_filter_exists() {
    let path = tmp_db("filter_exists");
    let db = seed_scored_graph(&path);

    let results = db.tql(r#"FIND {score: {$exists: true}} RETURN *"#).unwrap();
    assert_eq!(results.len(), 10);

    let results = db
        .tql(r#"FIND {nonexistent: {$exists: false}} RETURN *"#)
        .unwrap();
    assert_eq!(results.len(), 10);

    cleanup(&path);
}

/// $type 操作符
#[test]
fn COV4_12_filter_type() {
    let path = tmp_db("filter_type");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"FIND {name: {$type: "string"}} RETURN *"#)
        .unwrap();
    assert_eq!(results.len(), 10);

    cleanup(&path);
}

/// $all 操作符
#[test]
fn COV4_13_filter_all() {
    let path = tmp_db("filter_all");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"FIND {tags: {$all: ["a", "b"]}} RETURN *"#)
        .unwrap();
    assert_eq!(results.len(), 10);

    cleanup(&path);
}

/// $size 操作符
#[test]
fn COV4_14_filter_size() {
    let path = tmp_db("filter_size");
    let db = seed_scored_graph(&path);

    let results = db.tql(r#"FIND {tags: {$size: 3}} RETURN *"#).unwrap();
    assert_eq!(results.len(), 10);

    cleanup(&path);
}

/// $and / $or 组合过滤
#[test]
fn COV4_15_filter_and_or() {
    let path = tmp_db("filter_andor");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"FIND {$and: [{group: "alpha"}, {score: {$gte: 20}}]} RETURN *"#)
        .unwrap();
    assert_eq!(results.len(), 3);

    let results = db
        .tql(r#"FIND {$or: [{group: "alpha"}, {score: {$gte: 80}}]} RETURN *"#)
        .unwrap();
    assert_eq!(results.len(), 7);

    cleanup(&path);
}

// ════════════════════════════════════════════════════════════════
//  transaction.rs — 事务内多操作覆盖 (begin_tx API)
// ════════════════════════════════════════════════════════════════

/// 事务: 全操作组合 Link + UpdatePayload + UpdateVector + Unlink + Delete
#[test]
fn COV4_16_tx_full_ops() {
    let path = tmp_db("tx_full");
    let mut db = Database::<f32>::open(&path, DIM).unwrap();

    // 基础节点
    let ids = {
        let mut tx = db.begin_tx();
        tx.insert(&[1.0, 0.0, 0.0, 0.0], serde_json::json!({"name": "A"}));
        tx.insert(&[0.0, 1.0, 0.0, 0.0], serde_json::json!({"name": "B"}));
        tx.insert(&[0.0, 0.0, 1.0, 0.0], serde_json::json!({"name": "C"}));
        tx.commit().unwrap()
    };

    // 事务内: Link + UpdatePayload + UpdateVector
    {
        let mut tx = db.begin_tx();
        tx.link(ids[0], ids[1], "knows", 0.8);
        tx.link(ids[1], ids[2], "knows", 0.7);
        tx.update_payload(
            ids[0],
            serde_json::json!({"name": "A_updated", "flag": true}),
        );
        tx.update_vector(ids[2], &[0.0, 0.0, 0.0, 1.0]);
        tx.commit().unwrap();
    }

    assert_eq!(db.get_payload(ids[0]).unwrap()["name"], "A_updated");
    assert_eq!(db.get_edges(ids[0]).len(), 1);

    // 事务内: Unlink + Delete
    {
        let mut tx = db.begin_tx();
        tx.unlink(ids[0], ids[1]);
        tx.delete(ids[2]);
        tx.commit().unwrap();
    }

    assert!(db.get_edges(ids[0]).is_empty());
    assert!(!db.contains(ids[2]));

    cleanup(&path);
}

/// 事务: Link 不存在的节点 - 预检失败
#[test]
fn COV4_17_tx_link_nonexistent() {
    let path = tmp_db("tx_link_err");
    let mut db = Database::<f32>::open(&path, DIM).unwrap();

    let result = {
        let mut tx = db.begin_tx();
        tx.link(999, 998, "x", 1.0);
        tx.commit()
    };
    assert!(result.is_err(), "Link 不存在节点应失败");

    cleanup(&path);
}

/// 事务: UpdatePayload/UpdateVector/Delete/Unlink 不存在节点
#[test]
fn COV4_18_tx_ops_nonexistent() {
    let path = tmp_db("tx_ops_err");
    let mut db = Database::<f32>::open(&path, DIM).unwrap();

    // UpdatePayload 不存在
    let r = {
        let mut tx = db.begin_tx();
        tx.update_payload(999, serde_json::json!({"x": 1}));
        tx.commit()
    };
    assert!(r.is_err());

    // UpdateVector 不存在
    let r = {
        let mut tx = db.begin_tx();
        tx.update_vector(999, &[1.0, 0.0, 0.0, 0.0]);
        tx.commit()
    };
    assert!(r.is_err());

    // Delete 不存在
    let r = {
        let mut tx = db.begin_tx();
        tx.delete(999);
        tx.commit()
    };
    assert!(r.is_err());

    // Unlink 不存在
    let r = {
        let mut tx = db.begin_tx();
        tx.unlink(999, 998);
        tx.commit()
    };
    assert!(r.is_err());

    cleanup(&path);
}

/// 事务: UpdateVector 维度不匹配
#[test]
fn COV4_19_tx_dim_mismatch() {
    let path = tmp_db("tx_dim");
    let mut db = Database::<f32>::open(&path, DIM).unwrap();
    let ids = {
        let mut tx = db.begin_tx();
        tx.insert(&[1.0, 0.0, 0.0, 0.0], serde_json::json!({}));
        tx.commit().unwrap()
    };

    let result = {
        let mut tx = db.begin_tx();
        tx.update_vector(ids[0], &[1.0, 0.0]); // 维度不匹配
        tx.commit()
    };
    assert!(result.is_err(), "维度不匹配应失败");

    cleanup(&path);
}

/// 事务: InsertWithId 重复 ID
#[test]
fn COV4_20_tx_duplicate_id() {
    let path = tmp_db("tx_dup_id");
    let mut db = Database::<f32>::open(&path, DIM).unwrap();
    let ids = {
        let mut tx = db.begin_tx();
        tx.insert(&[1.0, 0.0, 0.0, 0.0], serde_json::json!({}));
        tx.commit().unwrap()
    };

    let result = {
        let mut tx = db.begin_tx();
        tx.insert_with_id(ids[0], &[0.0, 1.0, 0.0, 0.0], serde_json::json!({}));
        tx.commit()
    };
    assert!(result.is_err(), "重复 ID 应失败");

    cleanup(&path);
}

// ════════════════════════════════════════════════════════════════
//  WAL 回放 + cognitive NMF
// ════════════════════════════════════════════════════════════════

/// WAL 回放幂等性: 含 link/update/unlink/delete 的完整回放
#[test]
fn COV4_21_wal_replay_full() {
    let path = tmp_db("wal_full");
    let id1;
    {
        let mut db = Database::<f32>::open(&path, DIM).unwrap();
        id1 = db
            .insert(&[1.0, 0.0, 0.0, 0.0], serde_json::json!({"v": 1}))
            .unwrap();
        let id2 = db
            .insert(&[0.0, 1.0, 0.0, 0.0], serde_json::json!({"v": 2}))
            .unwrap();
        db.link(id1, id2, "rel", 0.5).unwrap();
        db.update_payload(id1, serde_json::json!({"v": 10}))
            .unwrap();
        db.update_vector(id2, &[0.0, 0.0, 1.0, 0.0]).unwrap();
        db.unlink(id1, id2).unwrap();
        db.delete(id2).unwrap();
        // 不 flush — WAL 仍在
    }

    // 重新打开触发 WAL 回放
    let db = Database::<f32>::open(&path, DIM).unwrap();
    assert_eq!(db.node_count(), 1);
    assert_eq!(db.get_payload(id1).unwrap()["v"], 10);

    cleanup(&path);
}

/// NMF analyze_query 覆盖
#[test]
fn COV4_22_nmf_analyze_query() {
    use triviumdb::cognitive::nmf_analyze_query;

    let k = 3;
    let d = 4;
    let h_flat = vec![1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0];

    // 聚焦查询
    let (depth, coverage, novelty, topics) =
        nmf_analyze_query(&[1.0, 0.0, 0.0, 0.0], &h_flat, k, d);
    assert!(depth > 0.0, "聚焦应有正深度: {}", depth);
    assert!(coverage >= 1);
    eprintln!(
        "  focused: d={:.2}, c={}, n={:.2}, t={:?}",
        depth, coverage, novelty, topics
    );

    // 均匀查询
    let (d2, c2, _, _) = nmf_analyze_query(&[1.0, 1.0, 1.0, 0.0], &h_flat, k, d);
    assert!(d2 < depth);
    assert!(c2 >= coverage);

    // 新颖查询
    let (_, _, n3, _) = nmf_analyze_query(&[0.0, 0.0, 0.0, 1.0], &h_flat, k, d);
    assert!(n3 > 0.0, "新颖查询应有正新颖度: {}", n3);

    // 零向量
    let _ = nmf_analyze_query(&[0.0, 0.0, 0.0, 0.0], &h_flat, k, d);
}

// ════════════════════════════════════════════════════════════════
//  tql_parser.rs — 更多语法分支
// ════════════════════════════════════════════════════════════════

/// 解析错误路径
#[test]
fn COV4_23_parser_errors() {
    let path = tmp_db("parse_err");
    let db = Database::<f32>::open(&path, DIM).unwrap();

    assert!(db.tql("FIND").is_err());
    assert!(db.tql("MATCH").is_err());
    assert!(db.tql(r#"FIND {type: "x"} RETURN"#).is_err());

    cleanup(&path);
}

/// TQL MATCHES 谓词
#[test]
fn COV4_24_tql_matches_predicate() {
    let path = tmp_db("tql_matches");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"MATCH (a)-[:next]->(b) WHERE a MATCHES {group: "alpha"} RETURN a, b"#)
        .unwrap();
    eprintln!("  MATCHES: {}", results.len());

    cleanup(&path);
}

/// NOT 谓词
#[test]
fn COV4_25_tql_not_predicate() {
    let path = tmp_db("tql_not");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"MATCH (a) WHERE NOT a.score > 50 RETURN a"#)
        .unwrap();
    eprintln!("  NOT: {}", results.len());

    cleanup(&path);
}

/// 多列 ORDER BY
#[test]
fn COV4_26_tql_multi_order() {
    let path = tmp_db("tql_multi_ord");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"FIND {type: "item"} RETURN * ORDER BY _.group ASC, _.score DESC"#)
        .unwrap();
    assert!(!results.is_empty());

    cleanup(&path);
}

/// RETURN a.field (属性投影)
#[test]
fn COV4_27_tql_return_property() {
    let path = tmp_db("tql_ret_prop");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"MATCH (a)-[:next]->(b) RETURN a.name, b.score"#)
        .unwrap();
    assert!(!results.is_empty());

    cleanup(&path);
}

/// EXPLAIN MATCH / SEARCH
#[test]
fn COV4_28_tql_explain_variants() {
    let path = tmp_db("explain_var");
    let db = seed_scored_graph(&path);

    let r1 = db
        .tql(r#"EXPLAIN MATCH (a)-[:next]->(b) RETURN a, b"#)
        .unwrap();
    assert!(!r1.is_empty());

    let r2 = db
        .tql("EXPLAIN SEARCH VECTOR [1.0, 0.0, 0.0, 0.0] TOP 3 RETURN *")
        .unwrap();
    assert!(!r2.is_empty());

    cleanup(&path);
}

/// SEARCH + EXPAND + WHERE 组合
#[test]
fn COV4_29_search_expand_where() {
    let path = tmp_db("search_combo");
    let db = seed_scored_graph(&path);

    let results = db
        .tql(r#"SEARCH VECTOR [5.0, 0.0, 0.0, 0.0] TOP 3 EXPAND [:next*1..2] WHERE {score: {$gte: 30}} RETURN *"#)
        .unwrap();
    eprintln!("  SEARCH+EXPAND+WHERE: {}", results.len());

    cleanup(&path);
}

/// flush 后 flush(幂等性)
#[test]
fn COV4_30_double_flush() {
    let path = tmp_db("dbl_flush");
    let mut db = Database::<f32>::open(&path, DIM).unwrap();
    db.insert(&[1.0, 0.0, 0.0, 0.0], serde_json::json!({}))
        .unwrap();
    db.flush().unwrap();
    db.flush().unwrap();
    assert_eq!(db.node_count(), 1);

    cleanup(&path);
}