-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathbanking_demo.rs
More file actions
1613 lines (1425 loc) · 76.6 KB
/
Copy pathbanking_demo.rs
File metadata and controls
1613 lines (1425 loc) · 76.6 KB
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Enterprise Banking Demo - Samyama Graph Database
//!
//! This example demonstrates enterprise-level banking data modeling with:
//! - Loading synthetic data from TSV files (customers, accounts, branches, transactions)
//! - Graph-based fraud detection patterns
//! - Money laundering pattern detection (structuring, rapid succession, circular transfers)
//! - OFAC/Sanctions screening simulation
//! - Customer relationship network analysis
//! - Persistence with RocksDB storage
//! - Complex Cypher queries for business intelligence
//!
//! Prerequisites:
//! 1. Generate synthetic data first:
//! cd docs/banking/generators
//! python generate_all.py --size small # or medium/large/enterprise
//!
//! 2. Run the demo:
//! cargo run --example banking_demo
//!
//! Data files expected in docs/banking/data/:
//! - branches.tsv
//! - customers.tsv
//! - accounts.tsv
//! - transactions.tsv
//! - owns_account.tsv
//! - banks_at.tsv
//! - transfer_to.tsv
//! - knows.tsv
//! - referred_by.tsv
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::time::Instant;
use samyama_sdk::{
EmbeddedClient, SamyamaClient,
PersistenceManager, ResourceQuotas,
GraphStore, Label, NodeId,
LLMProvider, NLQConfig,
};
// ============================================================================
// TSV LOADER
// ============================================================================
/// Statistics about loaded data
#[derive(Debug, Default)]
struct LoadStats {
branches: usize,
customers: usize,
accounts: usize,
transactions: usize,
relationships: usize,
}
/// ID mappings for relationship creation
struct IdMappings {
branches: HashMap<String, NodeId>,
customers: HashMap<String, NodeId>,
accounts: HashMap<String, NodeId>,
transactions: HashMap<String, NodeId>,
}
impl IdMappings {
fn new() -> Self {
Self {
branches: HashMap::new(),
customers: HashMap::new(),
accounts: HashMap::new(),
transactions: HashMap::new(),
}
}
fn find(&self, id: &str) -> Option<NodeId> {
self.customers.get(id)
.or_else(|| self.accounts.get(id))
.or_else(|| self.branches.get(id))
.or_else(|| self.transactions.get(id))
.copied()
}
}
/// Load branches from TSV
fn load_branches(
graph: &mut GraphStore,
data_dir: &Path,
mappings: &mut IdMappings,
) -> Result<usize, Box<dyn std::error::Error>> {
let path = data_dir.join("branches.tsv");
if !path.exists() {
return Ok(0);
}
let file = File::open(&path)?;
let reader = BufReader::new(file);
let mut lines = reader.lines();
let header = lines.next().ok_or("Empty file")??;
let headers: Vec<&str> = header.split('\t').collect();
let mut count = 0;
for line_result in lines {
let line = line_result?;
if line.trim().is_empty() { continue; }
let values: Vec<&str> = line.split('\t').collect();
let row: HashMap<&str, &str> = headers.iter().cloned()
.zip(values.iter().cloned())
.collect();
let node_id = graph.create_node("Branch");
// Set properties first (within mutable borrow scope)
if let Some(node) = graph.get_node_mut(node_id) {
for &key in &["branch_id", "name", "code", "branch_type", "address",
"city", "state", "zip_code", "country", "phone", "status"] {
if let Some(v) = row.get(key) { node.set_property(key, *v); }
}
if let Some(v) = row.get("employee_count") {
if let Ok(n) = v.parse::<i64>() { node.set_property("employee_count", n); }
}
if let Some(v) = row.get("latitude") {
if let Ok(n) = v.parse::<f64>() { node.set_property("latitude", n); }
}
if let Some(v) = row.get("longitude") {
if let Ok(n) = v.parse::<f64>() { node.set_property("longitude", n); }
}
}
// Add branch_type as label AFTER releasing mutable borrow
// Using graph.add_label_to_node("default", ) ensures the label_index is updated,
// making the node queryable via get_nodes_by_label() and Cypher MATCH
if let Some(bt) = row.get("branch_type") {
let _ = graph.add_label_to_node("default", node_id, bt.replace(" ", ""));
}
if let Some(id) = row.get("branch_id") {
mappings.branches.insert(id.to_string(), node_id);
}
count += 1;
}
Ok(count)
}
/// Load customers from TSV
fn load_customers(
graph: &mut GraphStore,
data_dir: &Path,
mappings: &mut IdMappings,
) -> Result<usize, Box<dyn std::error::Error>> {
let path = data_dir.join("customers.tsv");
if !path.exists() {
return Ok(0);
}
let file = File::open(&path)?;
let reader = BufReader::new(file);
let mut lines = reader.lines();
let header = lines.next().ok_or("Empty file")??;
let headers: Vec<&str> = header.split('\t').collect();
let mut count = 0;
for line_result in lines {
let line = line_result?;
if line.trim().is_empty() { continue; }
let values: Vec<&str> = line.split('\t').collect();
let row: HashMap<&str, &str> = headers.iter().cloned()
.zip(values.iter().cloned())
.collect();
let node_id = graph.create_node("Customer");
// Collect label info before mutable borrow
let customer_type = row.get("customer_type").map(|s| s.to_string());
let risk_label = row.get("risk_score").and_then(|risk| {
risk.parse::<i64>().ok().map(|score| {
if score >= 80 { "HighRisk" }
else if score >= 50 { "MediumRisk" }
else { "LowRisk" }
})
});
// Set properties (within mutable borrow scope)
if let Some(node) = graph.get_node_mut(node_id) {
// String properties
for &key in &["customer_id", "customer_type", "first_name", "last_name",
"email", "phone", "address", "city", "state", "zip_code",
"country", "date_of_birth", "ssn_last4", "kyc_status",
"account_opened_date", "last_activity_date"] {
if let Some(v) = row.get(key) {
if !v.is_empty() { node.set_property(key, *v); }
}
}
// Optional string properties
for &key in &["company_name", "occupation", "employer", "industry"] {
if let Some(v) = row.get(key) {
if !v.is_empty() { node.set_property(key, *v); }
}
}
// Numeric properties
if let Some(v) = row.get("risk_score") {
if let Ok(n) = v.parse::<i64>() { node.set_property("risk_score", n); }
}
if let Some(v) = row.get("annual_income") {
if let Ok(n) = v.parse::<f64>() { node.set_property("annual_income", n); }
}
if let Some(v) = row.get("credit_score") {
if let Ok(n) = v.parse::<i64>() { node.set_property("credit_score", n); }
}
}
// Add labels AFTER releasing mutable borrow
// Using graph.add_label_to_node("default", ) ensures the label_index is updated,
// making nodes queryable via get_nodes_by_label() and Cypher MATCH (c:Individual)
if let Some(ct) = customer_type {
let _ = graph.add_label_to_node("default", node_id, ct);
}
if let Some(risk) = risk_label {
let _ = graph.add_label_to_node("default", node_id, risk);
}
if let Some(id) = row.get("customer_id") {
mappings.customers.insert(id.to_string(), node_id);
}
count += 1;
}
Ok(count)
}
/// Load accounts from TSV
fn load_accounts(
graph: &mut GraphStore,
data_dir: &Path,
mappings: &mut IdMappings,
) -> Result<usize, Box<dyn std::error::Error>> {
let path = data_dir.join("accounts.tsv");
if !path.exists() {
return Ok(0);
}
let file = File::open(&path)?;
let reader = BufReader::new(file);
let mut lines = reader.lines();
let header = lines.next().ok_or("Empty file")??;
let headers: Vec<&str> = header.split('\t').collect();
let mut count = 0;
for line_result in lines {
let line = line_result?;
if line.trim().is_empty() { continue; }
let values: Vec<&str> = line.split('\t').collect();
let row: HashMap<&str, &str> = headers.iter().cloned()
.zip(values.iter().cloned())
.collect();
let node_id = graph.create_node("Account");
// Collect label info before mutable borrow
let account_type = row.get("account_type").map(|s| s.to_string());
let status_label = row.get("status").and_then(|s| {
if *s != "Active" { Some(s.replace(" ", "")) } else { None }
});
// Set properties (within mutable borrow scope)
if let Some(node) = graph.get_node_mut(node_id) {
// String properties
for &key in &["account_id", "account_number", "account_type", "customer_id",
"branch_id", "currency", "status", "opened_date"] {
if let Some(v) = row.get(key) { node.set_property(key, *v); }
}
if let Some(v) = row.get("last_transaction_date") {
if !v.is_empty() { node.set_property("last_transaction_date", *v); }
}
// Numeric properties
for &key in &["balance", "interest_rate", "credit_limit", "minimum_balance",
"overdraft_limit", "original_amount"] {
if let Some(v) = row.get(key) {
if let Ok(n) = v.parse::<f64>() { node.set_property(key, n); }
}
}
if let Some(v) = row.get("term_months") {
if let Ok(n) = v.parse::<i64>() { node.set_property("term_months", n); }
}
}
// Add labels AFTER releasing mutable borrow
// Using graph.add_label_to_node("default", ) ensures the label_index is updated,
// making nodes queryable via get_nodes_by_label() and Cypher MATCH (a:Checking)
if let Some(at) = account_type {
let _ = graph.add_label_to_node("default", node_id, at);
}
if let Some(status) = status_label {
let _ = graph.add_label_to_node("default", node_id, status);
}
if let Some(id) = row.get("account_id") {
mappings.accounts.insert(id.to_string(), node_id);
}
count += 1;
}
Ok(count)
}
/// Load transactions from TSV
fn load_transactions(
graph: &mut GraphStore,
data_dir: &Path,
mappings: &mut IdMappings,
) -> Result<usize, Box<dyn std::error::Error>> {
let path = data_dir.join("transactions.tsv");
if !path.exists() {
return Ok(0);
}
let file = File::open(&path)?;
let reader = BufReader::new(file);
let mut lines = reader.lines();
let header = lines.next().ok_or("Empty file")??;
let headers: Vec<&str> = header.split('\t').collect();
let mut count = 0;
for line_result in lines {
let line = line_result?;
if line.trim().is_empty() { continue; }
let values: Vec<&str> = line.split('\t').collect();
let row: HashMap<&str, &str> = headers.iter().cloned()
.zip(values.iter().cloned())
.collect();
let node_id = graph.create_node("Transaction");
// Collect label info before mutable borrow
let transaction_type = row.get("transaction_type").map(|s| s.to_string());
let is_fraud = row.get("fraud_flag").map(|ff| *ff == "True").unwrap_or(false);
// Set properties (within mutable borrow scope)
if let Some(node) = graph.get_node_mut(node_id) {
// String properties
for &key in &["transaction_id", "account_id", "transaction_type", "timestamp",
"description", "status", "channel", "reference_number"] {
if let Some(v) = row.get(key) { node.set_property(key, *v); }
}
// Optional string properties
for &key in &["merchant_name", "merchant_category", "counterparty_account",
"location", "ip_address", "device_id"] {
if let Some(v) = row.get(key) {
if !v.is_empty() { node.set_property(key, *v); }
}
}
// Numeric properties
if let Some(v) = row.get("amount") {
if let Ok(n) = v.parse::<f64>() { node.set_property("amount", n); }
}
if let Some(v) = row.get("balance_after") {
if let Ok(n) = v.parse::<f64>() { node.set_property("balance_after", n); }
}
if let Some(v) = row.get("mcc_code") {
if let Ok(n) = v.parse::<i64>() { node.set_property("mcc_code", n); }
}
if let Some(v) = row.get("fraud_score") {
if let Ok(n) = v.parse::<f64>() { node.set_property("fraud_score", n); }
}
if let Some(v) = row.get("fraud_flag") {
node.set_property("fraud_flag", *v == "True");
}
}
// Add labels AFTER releasing mutable borrow
// Using graph.add_label_to_node("default", ) ensures the label_index is updated,
// making nodes queryable via get_nodes_by_label() and Cypher MATCH (t:Transfer)
if let Some(tt) = transaction_type {
let _ = graph.add_label_to_node("default", node_id, tt);
}
if is_fraud {
let _ = graph.add_label_to_node("default", node_id, "Flagged");
let _ = graph.add_label_to_node("default", node_id, "Fraud");
}
if let Some(id) = row.get("transaction_id") {
mappings.transactions.insert(id.to_string(), node_id);
}
count += 1;
}
Ok(count)
}
/// Load a relationship file
fn load_relationship_file(
graph: &mut GraphStore,
data_dir: &Path,
mappings: &IdMappings,
filename: &str,
edge_type: &str,
from_col: &str,
to_col: &str,
) -> Result<usize, Box<dyn std::error::Error>> {
let path = data_dir.join(filename);
if !path.exists() {
return Ok(0);
}
let file = File::open(&path)?;
let reader = BufReader::new(file);
let mut lines = reader.lines();
let header = lines.next().ok_or("Empty file")??;
let headers: Vec<&str> = header.split('\t').collect();
let mut count = 0;
for line_result in lines {
let line = line_result?;
if line.trim().is_empty() { continue; }
let values: Vec<&str> = line.split('\t').collect();
let row: HashMap<&str, &str> = headers.iter().cloned()
.zip(values.iter().cloned())
.collect();
let from_id = row.get(from_col).map(|s| s.to_string());
let to_id = row.get(to_col).map(|s| s.to_string());
if let (Some(from_id), Some(to_id)) = (from_id, to_id) {
if let (Some(from_node), Some(to_node)) = (mappings.find(&from_id), mappings.find(&to_id)) {
if let Ok(edge_id) = graph.create_edge(from_node, to_node, edge_type) {
if let Some(props) = graph.get_edge_properties_mut(edge_id) {
for (key, value) in &row {
if *key != from_col && *key != to_col && !value.is_empty() {
if let Ok(n) = value.parse::<f64>() {
props.insert((*key).into(), n.into());
} else if let Ok(n) = value.parse::<i64>() {
props.insert((*key).into(), n.into());
} else if *value == "True" || *value == "False" {
props.insert((*key).into(), (*value == "True").into());
} else {
props.insert((*key).into(), (*value).into());
}
}
}
}
count += 1;
}
}
}
}
Ok(count)
}
/// Load all relationships
fn load_relationships(
graph: &mut GraphStore,
data_dir: &Path,
mappings: &IdMappings,
) -> Result<usize, Box<dyn std::error::Error>> {
let mut total = 0;
let rel_files = [
("owns_account.tsv", "OWNS", "customer_id", "account_id"),
("banks_at.tsv", "BANKS_AT", "customer_id", "branch_id"),
("account_at_branch.tsv", "LOCATED_AT", "account_id", "branch_id"),
("transfer_to.tsv", "TRANSFER_TO", "from_account_id", "to_account_id"),
("knows.tsv", "KNOWS", "customer1_id", "customer2_id"),
("referred_by.tsv", "REFERRED_BY", "customer_id", "referrer_id"),
("authorized_user.tsv", "AUTHORIZED_USER", "customer_id", "account_id"),
("employed_by.tsv", "EMPLOYED_BY", "customer_id", "employer_id"),
];
for (filename, edge_type, from_col, to_col) in rel_files.iter() {
let loaded = load_relationship_file(graph, data_dir, mappings, filename, edge_type, from_col, to_col)?;
if loaded > 0 {
println!(" {} {} edges", loaded, edge_type);
}
total += loaded;
}
// Create account -> transaction edges
let tx_edges = create_account_transaction_edges(graph, data_dir, mappings)?;
if tx_edges > 0 {
println!(" {} HAS_TRANSACTION edges", tx_edges);
}
total += tx_edges;
Ok(total)
}
/// Create edges from accounts to transactions
fn create_account_transaction_edges(
graph: &mut GraphStore,
data_dir: &Path,
mappings: &IdMappings,
) -> Result<usize, Box<dyn std::error::Error>> {
let path = data_dir.join("transactions.tsv");
if !path.exists() {
return Ok(0);
}
let file = File::open(&path)?;
let reader = BufReader::new(file);
let mut lines = reader.lines();
lines.next(); // Skip header
let mut count = 0;
for line_result in lines {
let line = line_result?;
if line.trim().is_empty() { continue; }
let values: Vec<&str> = line.split('\t').collect();
if values.len() < 2 { continue; }
let tx_id = values[0];
let acc_id = values[1];
if let (Some(&tx_node), Some(&acc_node)) =
(mappings.transactions.get(tx_id), mappings.accounts.get(acc_id))
{
if graph.create_edge(acc_node, tx_node, "HAS_TRANSACTION").is_ok() {
count += 1;
}
}
}
Ok(count)
}
/// Load all data from TSV files
fn load_all_data(
graph: &mut GraphStore,
data_dir: &Path,
) -> Result<LoadStats, Box<dyn std::error::Error>> {
let mut stats = LoadStats::default();
let mut mappings = IdMappings::new();
println!(" Loading branches...");
stats.branches = load_branches(graph, data_dir, &mut mappings)?;
println!(" ✓ {} branches", stats.branches);
println!(" Loading customers...");
stats.customers = load_customers(graph, data_dir, &mut mappings)?;
println!(" ✓ {} customers", stats.customers);
println!(" Loading accounts...");
stats.accounts = load_accounts(graph, data_dir, &mut mappings)?;
println!(" ✓ {} accounts", stats.accounts);
println!(" Loading transactions...");
stats.transactions = load_transactions(graph, data_dir, &mut mappings)?;
println!(" ✓ {} transactions", stats.transactions);
println!(" Loading relationships...");
stats.relationships = load_relationships(graph, data_dir, &mappings)?;
println!(" ✓ {} relationships", stats.relationships);
Ok(stats)
}
// ============================================================================
// MAIN DEMO
// ============================================================================
fn is_claude_available() -> bool {
std::process::Command::new("which")
.arg("claude")
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing_subscriber::fmt::init();
println!("╔══════════════════════════════════════════════════════════════════════╗");
println!("║ SAMYAMA GRAPH DATABASE - Enterprise Banking Demo ║");
println!("╚══════════════════════════════════════════════════════════════════════╝");
println!();
let start_time = Instant::now();
// =========================================================================
// 1. SETUP PERSISTENCE & MULTI-TENANCY
// =========================================================================
println!("┌──────────────────────────────────────────────────────────────────────┐");
println!("│ STEP 1: Setting up Banking Infrastructure │");
println!("└──────────────────────────────────────────────────────────────────────┘");
let persist_mgr = PersistenceManager::new("./banking_data")?;
// Retail Banking Division
let retail_quotas = ResourceQuotas {
max_nodes: Some(10_000_000),
max_edges: Some(50_000_000),
max_memory_bytes: Some(4 * 1024 * 1024 * 1024),
max_storage_bytes: Some(20 * 1024 * 1024 * 1024),
max_connections: Some(500),
max_query_time_ms: Some(60_000),
};
persist_mgr.tenants().create_tenant(
"retail_banking".to_string(),
"Retail Banking Division".to_string(),
Some(retail_quotas),
)?;
println!(" ✓ Created 'retail_banking' tenant (quota: 10M nodes, 50M edges)");
// Corporate Banking Division
let corporate_quotas = ResourceQuotas {
max_nodes: Some(1_000_000),
max_edges: Some(10_000_000),
max_memory_bytes: Some(8 * 1024 * 1024 * 1024),
max_storage_bytes: Some(50 * 1024 * 1024 * 1024),
max_connections: Some(100),
max_query_time_ms: Some(120_000),
};
persist_mgr.tenants().create_tenant(
"corporate_banking".to_string(),
"Corporate Banking Division".to_string(),
Some(corporate_quotas),
)?;
println!(" ✓ Created 'corporate_banking' tenant (quota: 1M nodes, 10M edges)");
// Wealth Management Division
let wealth_quotas = ResourceQuotas {
max_nodes: Some(500_000),
max_edges: Some(5_000_000),
max_memory_bytes: Some(2 * 1024 * 1024 * 1024),
max_storage_bytes: Some(10 * 1024 * 1024 * 1024),
max_connections: Some(50),
max_query_time_ms: Some(180_000),
};
persist_mgr.tenants().create_tenant(
"wealth_management".to_string(),
"Wealth Management Division".to_string(),
Some(wealth_quotas),
)?;
println!(" ✓ Created 'wealth_management' tenant (quota: 500K nodes, 5M edges)");
println!();
// =========================================================================
// 2. INITIALIZE GRAPH & LOAD DATA
// =========================================================================
println!("┌──────────────────────────────────────────────────────────────────────┐");
println!("│ STEP 2: Loading Enterprise Banking Data │");
println!("└──────────────────────────────────────────────────────────────────────┘");
let client = EmbeddedClient::new();
let data_dir = Path::new("docs/banking/data");
let stats = {
let mut graph = client.store_write().await;
if data_dir.exists() {
load_all_data(&mut graph, data_dir)?
} else {
println!(" ⚠ Data directory not found: {}", data_dir.display());
println!(" Run the data generator first:");
println!(" cd docs/banking/generators && python generate_all.py --size small");
println!();
println!(" Creating sample data inline...");
create_sample_data(&mut graph)?
}
};
let load_time = start_time.elapsed();
println!();
println!(" Data loaded in {:.2}s", load_time.as_secs_f64());
println!();
// =========================================================================
// 3. PERSIST DATA TO STORAGE
// =========================================================================
println!("┌──────────────────────────────────────────────────────────────────────┐");
println!("│ STEP 3: Persisting Data to Storage │");
println!("└──────────────────────────────────────────────────────────────────────┘");
let persist_start = Instant::now();
// Persist customers by type to appropriate tenants
{
let graph = client.store_read().await;
let individual_customers: Vec<_> = graph.get_nodes_by_label(&Label::new("Individual"))
.into_iter()
.filter(|n| n.labels.iter().any(|l| l.as_str() == "Customer"))
.collect();
for node in &individual_customers {
persist_mgr.persist_create_node("retail_banking", node)?;
}
println!(" ✓ Persisted {} individual customers to retail_banking", individual_customers.len());
let corporate_customers: Vec<_> = graph.get_nodes_by_label(&Label::new("Corporate"))
.into_iter()
.filter(|n| n.labels.iter().any(|l| l.as_str() == "Customer"))
.collect();
for node in &corporate_customers {
persist_mgr.persist_create_node("corporate_banking", node)?;
}
println!(" ✓ Persisted {} corporate customers to corporate_banking", corporate_customers.len());
let hnw_customers: Vec<_> = graph.get_nodes_by_label(&Label::new("HighNetWorth"))
.into_iter()
.filter(|n| n.labels.iter().any(|l| l.as_str() == "Customer"))
.collect();
for node in &hnw_customers {
persist_mgr.persist_create_node("wealth_management", node)?;
}
println!(" ✓ Persisted {} HNW customers to wealth_management", hnw_customers.len());
let mut retail_edges = 0;
let mut corporate_edges = 0;
let mut wealth_edges = 0;
for node in &individual_customers {
for edge in graph.get_outgoing_edges(node.id) {
if edge.edge_type.as_str() == "OWNS" {
persist_mgr.persist_create_edge("retail_banking", &edge)?;
retail_edges += 1;
}
}
}
println!(" ✓ Persisted {} edges to retail_banking", retail_edges);
for node in &corporate_customers {
for edge in graph.get_outgoing_edges(node.id) {
if edge.edge_type.as_str() == "OWNS" {
persist_mgr.persist_create_edge("corporate_banking", &edge)?;
corporate_edges += 1;
}
}
}
println!(" ✓ Persisted {} edges to corporate_banking", corporate_edges);
for node in &hnw_customers {
for edge in graph.get_outgoing_edges(node.id) {
if edge.edge_type.as_str() == "OWNS" {
persist_mgr.persist_create_edge("wealth_management", &edge)?;
wealth_edges += 1;
}
}
}
println!(" ✓ Persisted {} edges to wealth_management", wealth_edges);
}
persist_mgr.checkpoint()?;
println!(" ✓ Checkpoint created ({:.2}s)", persist_start.elapsed().as_secs_f64());
println!();
// =========================================================================
// 4. RUN CYPHER QUERIES
// =========================================================================
println!("┌──────────────────────────────────────────────────────────────────────┐");
println!("│ STEP 4: Running Cypher Queries │");
println!("└──────────────────────────────────────────────────────────────────────┘");
// Query 1: All customers
println!("\n Query: MATCH (c:Customer) RETURN c LIMIT 5");
let q_start = Instant::now();
let result = client.query_readonly("default", "MATCH (c:Customer) RETURN c LIMIT 5").await?;
println!(" Found {} results ({:.3}ms)", result.len(), q_start.elapsed().as_secs_f64() * 1000.0);
for row in &result.records {
println!(" {:?}", row);
}
// Query 2: High-risk customers
println!("\n Query: MATCH (c:HighRisk) RETURN c LIMIT 10");
let q_start = Instant::now();
let result = client.query_readonly("default", "MATCH (c:HighRisk) RETURN c LIMIT 10").await?;
println!(" Found {} high-risk customers ({:.3}ms)", result.len(), q_start.elapsed().as_secs_f64() * 1000.0);
// Query 3: Corporate customers
println!("\n Query: MATCH (c:Corporate) RETURN c LIMIT 5");
let q_start = Instant::now();
let result = client.query_readonly("default", "MATCH (c:Corporate) RETURN c LIMIT 5").await?;
println!(" Found {} corporate customers ({:.3}ms)", result.len(), q_start.elapsed().as_secs_f64() * 1000.0);
// Query 4: Flagged transactions
println!("\n Query: MATCH (t:Flagged) RETURN t LIMIT 10");
let q_start = Instant::now();
let result = client.query_readonly("default", "MATCH (t:Flagged) RETURN t LIMIT 10").await?;
println!(" Found {} flagged transactions ({:.3}ms)", result.len(), q_start.elapsed().as_secs_f64() * 1000.0);
// Query 5: Branches
println!("\n Query: MATCH (b:Branch) RETURN b LIMIT 5");
let q_start = Instant::now();
let result = client.query_readonly("default", "MATCH (b:Branch) RETURN b LIMIT 5").await?;
println!(" Found {} branches ({:.3}ms)", result.len(), q_start.elapsed().as_secs_f64() * 1000.0);
// Query 6: Checking accounts
println!("\n Query: MATCH (a:Checking) RETURN a LIMIT 5");
let q_start = Instant::now();
let result = client.query_readonly("default", "MATCH (a:Checking) RETURN a LIMIT 5").await?;
println!(" Found {} checking accounts ({:.3}ms)", result.len(), q_start.elapsed().as_secs_f64() * 1000.0);
println!();
// =========================================================================
// 5. FRAUD DETECTION ANALYSIS
// =========================================================================
println!("┌──────────────────────────────────────────────────────────────────────┐");
println!("│ STEP 5A: Fraud Detection Analysis │");
println!("└──────────────────────────────────────────────────────────────────────┘");
// High-risk customer connections (KNOWS relationships from high-risk customers)
println!("\n Analyzing high-risk customer network...");
let graph = client.store_read().await;
let high_risk = graph.get_nodes_by_label(&Label::new("HighRisk"));
println!(" High-risk customers (risk_score >= 80): {}", high_risk.len());
let mut risk_connections = 0;
for hr_node in &high_risk {
let edges = graph.get_outgoing_edges(hr_node.id);
for edge in edges {
if edge.edge_type.as_str() == "KNOWS" {
risk_connections += 1;
}
}
}
println!(" KNOWS connections from high-risk customers: {}", risk_connections);
// Flagged transactions analysis (transactions with fraud_flag = true)
println!("\n Analyzing flagged transactions...");
let flagged = graph.get_nodes_by_label(&Label::new("Flagged"));
println!(" Flagged transactions (fraud_flag = true): {}", flagged.len());
let mut total_flagged_amount = 0.0;
for tx_node in &flagged {
if let Some(amount) = tx_node.get_property("amount") {
if let Some(amt) = amount.as_float() {
total_flagged_amount += amt;
}
}
}
println!(" Total flagged transaction amount: ${:.2}", total_flagged_amount);
// Frozen accounts (accounts with status = "Frozen", ~2% of accounts)
// Note: Frozen accounts are separate from flagged transactions
// - Frozen = account status set during account creation
// - Flagged = individual transactions marked suspicious
println!("\n Analyzing account status...");
let under_review = graph.get_nodes_by_label(&Label::new("Frozen"));
let total_accounts = graph.get_nodes_by_label(&Label::new("Account")).len();
let frozen_pct = if total_accounts > 0 {
(under_review.len() as f64 / total_accounts as f64) * 100.0
} else {
0.0
};
println!(" Accounts with Frozen status: {} ({:.1}% of {} accounts)",
under_review.len(), frozen_pct, total_accounts);
println!();
// =========================================================================
// STEP 5B: Money Laundering Pattern Detection
// =========================================================================
println!("┌──────────────────────────────────────────────────────────────────────┐");
println!("│ STEP 5B: Money Laundering Pattern Detection │");
println!("└──────────────────────────────────────────────────────────────────────┘");
// --- Structuring detection: transactions just under $10,000 (BSA threshold) ---
println!("\n [1] Structuring Detection (BSA $10,000 Threshold)");
println!(" Searching for transactions between $9,000 and $10,000...");
let all_transactions = graph.get_nodes_by_label(&Label::new("Transaction"));
let mut structuring_suspects: Vec<(String, f64)> = Vec::new();
for tx_node in &all_transactions {
if let Some(amount) = tx_node.get_property("amount").and_then(|v| v.as_float()) {
if amount >= 9000.0 && amount < 10000.0 {
let tx_id = tx_node.get_property("transaction_id")
.and_then(|v| v.as_string())
.unwrap_or("unknown")
.to_string();
structuring_suspects.push((tx_id, amount));
}
}
}
if structuring_suspects.is_empty() {
println!(" No structuring patterns detected.");
} else {
println!(" ALERT: {} transactions just under BSA reporting threshold:",
structuring_suspects.len());
for (tx_id, amount) in &structuring_suspects {
println!(" - {} : ${:.2}", tx_id, amount);
}
}
// --- Rapid succession: accounts with multiple large transactions ---
println!("\n [2] Rapid Succession Detection (Multiple Large Transactions)");
println!(" Searching for accounts with 2+ transactions over $5,000...");
let all_accounts = graph.get_nodes_by_label(&Label::new("Account"));
let mut rapid_succession_accounts: Vec<(String, usize, f64)> = Vec::new();
for acc_node in &all_accounts {
let acc_edges = graph.get_outgoing_edges(acc_node.id);
let mut large_tx_count = 0usize;
let mut large_tx_total = 0.0f64;
for edge in &acc_edges {
if edge.edge_type.as_str() == "HAS_TRANSACTION" {
if let Some(tx_node) = graph.get_node(edge.target) {
if let Some(amount) = tx_node.get_property("amount").and_then(|v| v.as_float()) {
if amount > 5000.0 {
large_tx_count += 1;
large_tx_total += amount;
}
}
}
}
}
if large_tx_count >= 2 {
let acc_id = acc_node.get_property("account_id")
.and_then(|v| v.as_string())
.unwrap_or("unknown")
.to_string();
rapid_succession_accounts.push((acc_id, large_tx_count, large_tx_total));
}
}
if rapid_succession_accounts.is_empty() {
println!(" No rapid succession patterns detected.");
} else {
println!(" ALERT: {} accounts with multiple large transactions:",
rapid_succession_accounts.len());
for (acc_id, count, total) in &rapid_succession_accounts {
println!(" - {} : {} large txns totaling ${:.2}", acc_id, count, total);
}
}
// --- Circular transfer detection: A -> B -> C -> A ---
println!("\n [3] Circular Transfer Detection (A -> B -> C -> A)");
println!(" Scanning TRANSFER_TO edges for circular patterns...");
let mut circular_patterns: Vec<(NodeId, NodeId, NodeId)> = Vec::new();
// Build an adjacency list of TRANSFER_TO edges for efficient lookup
let mut transfer_adj: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
for acc_node in &all_accounts {
let edges = graph.get_outgoing_edges(acc_node.id);
for edge in &edges {
if edge.edge_type.as_str() == "TRANSFER_TO" {
transfer_adj.entry(acc_node.id).or_default().push(edge.target);
}
}
}
// For each node A with outgoing TRANSFER_TO, check A->B->C->A
for (&node_a, targets_b) in &transfer_adj {
for &node_b in targets_b {
if let Some(targets_c) = transfer_adj.get(&node_b) {
for &node_c in targets_c {
if node_c == node_a { continue; } // skip A->B->A (length 2)
if let Some(targets_from_c) = transfer_adj.get(&node_c) {
if targets_from_c.contains(&node_a) {
// Found cycle A -> B -> C -> A
// Normalize to avoid duplicates: smallest ID first
let cycle = [node_a, node_b, node_c];
let min_idx = cycle.iter().enumerate()
.min_by_key(|&(_, id)| *id)
.map(|(i, _)| i).unwrap();
let normalized = (
cycle[min_idx],
cycle[(min_idx + 1) % 3],
cycle[(min_idx + 2) % 3],
);
if !circular_patterns.contains(&normalized) {
circular_patterns.push(normalized);
}
}
}
}
}
}
}
if circular_patterns.is_empty() {
println!(" No circular transfer patterns detected.");
} else {
println!(" ALERT: {} circular transfer patterns detected:", circular_patterns.len());
for (a, b, c) in &circular_patterns {
let name_a = graph.get_node(*a)
.and_then(|n| n.get_property("account_id"))
.and_then(|v| v.as_string())
.map(|s| s.to_string())
.unwrap_or_else(|| format!("{:?}", a));
let name_b = graph.get_node(*b)
.and_then(|n| n.get_property("account_id"))
.and_then(|v| v.as_string())
.map(|s| s.to_string())
.unwrap_or_else(|| format!("{:?}", b));
let name_c = graph.get_node(*c)
.and_then(|n| n.get_property("account_id"))