god-graph 0.6.0-alpha

A graph-based LLM white-box optimization toolbox: topology validation, Lie group orthogonalization, tensor ring compression
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
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
# VGI 架构实施计划

## Virtual Graph Interface 实现细节

**版本**: v0.6.0-alpha
**日期**: 2026-03-31
**状态**: Phase 1 已完成 ✅

---

## 📁 新增文件结构

```
src/
├── vgi/                          # Virtual Graph Interface 核心
│   ├── mod.rs                    # 模块导出
│   ├── traits.rs                 # 核心 trait 定义
│   ├── metadata.rs               # 图元数据
│   ├── error.rs                  # 统一错误类型
│   └── builder.rs                # 图构建器
│
├── backend/                      # 后端抽象层
│   ├── mod.rs                    # 模块导出
│   ├── traits.rs                 # Backend trait
│   ├── single_machine.rs         # 单机后端(现有 Graph 重构)
│   ├── distributed.rs            # 分布式后端(待实现)
│   └── gpu.rs                    # GPU 后端(待实现)
│
├── plugins/                      # 插件系统
│   ├── mod.rs                    # 模块导出
│   ├── registry.rs               # 插件注册表
│   ├── algorithm.rs              # 算法插件接口
│   ├── serializer.rs             # 序列化插件接口
│   └── loader.rs                 # 插件加载器
│
├── distributed/                  # 分布式图处理
│   ├── mod.rs                    # 模块导出
│   ├── partitioner.rs            # 图分区器
│   ├── executor.rs               # 分布式执行引擎
│   ├── communication.rs          # 节点间通信
│   └── algorithms/               # 分布式算法
│       ├── mod.rs
│       ├── pagerank.rs
│       └── bfs.rs
│
└── ... (现有模块保持不变)
```

---

## 🔧 核心代码实现

### 1. VGI 核心 trait (`src/vgi/traits.rs`)

```rust
//! Virtual Graph Interface - 所有图后端的统一抽象
//!
//! 类比 Linux VFS (Virtual File System),提供统一的图操作接口

use std::collections::HashMap;
use std::hash::Hash;

use crate::vgi::error::GraphResult;
use crate::vgi::metadata::GraphMetadata;

/// 虚拟图接口 - 所有图后端的统一抽象
///
/// # 示例
///
/// ```ignore
/// use god_graph::vgi::VirtualGraph;
///
/// fn process_graph<G: VirtualGraph<NodeData = String, EdgeData = f64>>(
///     graph: &G,
/// ) {
///     println!("Nodes: {}", graph.node_count());
///     println!("Edges: {}", graph.edge_count());
/// }
/// ```
pub trait VirtualGraph: Send + Sync {
    /// 节点数据类型
    type NodeData: Clone + Send + Sync;
    /// 边数据类型
    type EdgeData: Clone + Send + Sync;
    /// 节点索引类型
    type NodeIndex: Copy + Clone + Hash + Eq + Send + Sync;
    /// 边索引类型
    type EdgeIndex: Copy + Clone + Hash + Eq + Send + Sync;

    // === 基础查询操作 ===

    /// 获取节点数量
    fn node_count(&self) -> usize;

    /// 获取边数量
    fn edge_count(&self) -> usize;

    /// 检查是否为空图
    fn is_empty(&self) -> bool {
        self.node_count() == 0
    }

    /// 获取节点数据
    fn get_node(&self, node: Self::NodeIndex) -> GraphResult<&Self::NodeData>;

    /// 获取边数据
    fn get_edge(&self, edge: Self::EdgeIndex) -> GraphResult<&Self::EdgeData>;

    /// 获取边的端点
    fn edge_endpoints(
        &self,
        edge: Self::EdgeIndex,
    ) -> GraphResult<(Self::NodeIndex, Self::NodeIndex)>;

    /// 检查是否存在从 from 到 to 的边
    fn has_edge(&self, from: Self::NodeIndex, to: Self::NodeIndex) -> bool;

    /// 获取节点的邻居迭代器
    fn neighbors(
        &self,
        node: Self::NodeIndex,
    ) -> Box<dyn Iterator<Item = Self::NodeIndex> + '_>;

    /// 获取节点的关联边迭代器
    fn incident_edges(
        &self,
        node: Self::NodeIndex,
    ) -> Box<dyn Iterator<Item = Self::EdgeIndex> + '_>;

    /// 获取节点的出度
    fn out_degree(&self, node: Self::NodeIndex) -> GraphResult<usize>;

    /// 获取节点的入度(有向图)
    fn in_degree(&self, node: Self::NodeIndex) -> GraphResult<usize> {
        self.out_degree(node)
    }

    /// 获取所有节点迭代器
    fn nodes(&self) -> Box<dyn Iterator<Item = NodeRef<'_, Self::NodeData>> + '_>;

    /// 获取所有边迭代器
    fn edges(&self) -> Box<dyn Iterator<Item = EdgeRef<'_, Self::EdgeData>> + '_>;

    // === 可变操作 ===

    /// 添加节点
    fn add_node(&mut self, data: Self::NodeData) -> GraphResult<Self::NodeIndex>;

    /// 删除节点,返回节点数据
    fn remove_node(&mut self, node: Self::NodeIndex) -> GraphResult<Self::NodeData>;

    /// 添加边
    fn add_edge(
        &mut self,
        from: Self::NodeIndex,
        to: Self::NodeIndex,
        data: Self::EdgeData,
    ) -> GraphResult<Self::EdgeIndex>;

    /// 删除边,返回边数据
    fn remove_edge(&mut self, edge: Self::EdgeIndex) -> GraphResult<Self::EdgeData>;

    /// 更新节点数据,返回旧数据
    fn update_node(
        &mut self,
        node: Self::NodeIndex,
        data: Self::NodeData,
    ) -> GraphResult<Self::NodeData>;

    /// 更新边数据,返回旧数据
    fn update_edge(
        &mut self,
        edge: Self::EdgeIndex,
        data: Self::EdgeData,
    ) -> GraphResult<Self::EdgeData>;

    /// 清空图
    fn clear(&mut self);

    // === 批量操作(提供默认实现,可优化)===

    /// 批量添加节点
    fn bulk_add_nodes(
        &mut self,
        nodes: Vec<Self::NodeData>,
    ) -> GraphResult<Vec<Self::NodeIndex>> {
        nodes.into_iter().map(|n| self.add_node(n)).collect()
    }

    /// 批量添加边
    fn bulk_add_edges(
        &mut self,
        edges: Vec<((Self::NodeIndex, Self::NodeIndex), Self::EdgeData)>,
    ) -> GraphResult<Vec<Self::EdgeIndex>> {
        edges
            .into_iter()
            .map(|((from, to), data)| self.add_edge(from, to, data))
            .collect()
    }

    // === 元数据 ===

    /// 获取图的元数据
    fn metadata(&self) -> GraphMetadata;

    /// 检查是否为有向图
    fn is_directed(&self) -> bool {
        self.metadata().is_directed
    }

    /// 检查是否允许多重边
    fn allows_multiple_edges(&self) -> bool {
        self.metadata().allows_multiple_edges
    }

    /// 检查是否允许自环
    fn allows_self_loops(&self) -> bool {
        self.metadata().allows_self_loops
    }
}

/// 节点引用
#[derive(Debug, Clone)]
pub struct NodeRef<'a, T> {
    index: usize,
    data: &'a T,
}

impl<'a, T> NodeRef<'a, T> {
    pub fn new(index: usize, data: &'a T) -> Self {
        Self { index, data }
    }

    pub fn index(&self) -> usize {
        self.index
    }

    pub fn data(&self) -> &'a T {
        self.data
    }
}

/// 边引用
#[derive(Debug, Clone)]
pub struct EdgeRef<'a, T> {
    index: usize,
    source: usize,
    target: usize,
    data: &'a T,
}

impl<'a, T> EdgeRef<'a, T> {
    pub fn new(index: usize, source: usize, target: usize, data: &'a T) -> Self {
        Self {
            index,
            source,
            target,
            data,
        }
    }

    pub fn index(&self) -> usize {
        self.index
    }

    pub fn source(&self) -> usize {
        self.source
    }

    pub fn target(&self) -> usize {
        self.target
    }

    pub fn data(&self) -> &'a T {
        self.data
    }
}
```

---

### 2. 后端抽象层 (`src/backend/traits.rs`)

```rust
//! 后端抽象层 - 类似 Linux 的设备驱动
//!
//! 每个后端(单机、分布式、GPU、持久化)必须实现此 trait

use std::collections::HashMap;

use crate::vgi::VirtualGraph;
use crate::vgi::error::GraphResult;
use crate::vgi::metadata::GraphMetadata;

/// 后端驱动 trait
///
/// # 示例
///
/// ```ignore
/// use god_graph::backend::{GraphBackend, GraphConfig, BackendFeature};
///
/// struct MyBackend;
///
/// impl GraphBackend for MyBackend {
///     fn name(&self) -> &'static str {
///         "my-backend"
///     }
///
///     fn create_graph<N, E>(&self, config: GraphConfig) -> Box<dyn VirtualGraph<NodeData = N, EdgeData = E>> {
///         Box::new(MyGraph::new(config))
///     }
/// }
/// ```
pub trait GraphBackend: Send + Sync {
    /// 后端名称(如 "single-machine", "distributed", "gpu")
    fn name(&self) -> &'static str;

    /// 后端版本
    fn version(&self) -> &'static str {
        env!("CARGO_PKG_VERSION")
    }

    /// 后端描述
    fn description(&self) -> &'static str {
        "Graph backend"
    }

    /// 检查后端是否支持特定功能
    fn supports_feature(&self, feature: BackendFeature) -> bool;

    /// 创建新的图实例
    fn create_graph<N, E>(
        &self,
        config: GraphConfig,
    ) -> Box<dyn VirtualGraph<NodeData = N, EdgeData = E>>
    where
        N: Clone + Send + Sync + 'static,
        E: Clone + Send + Sync + 'static;

    /// 从存储加载图
    fn load_graph<N, E>(
        &self,
        path: &str,
    ) -> GraphResult<Box<dyn VirtualGraph<NodeData = N, EdgeData = E>>>
    where
        N: Clone + Send + Sync + 'static,
        E: Clone + Send + Sync + 'static,
    {
        Err(GraphError::NotImplemented(
            "load_graph not implemented".to_string(),
        ))
    }

    /// 保存图到存储
    fn save_graph<N, E>(
        &self,
        graph: &dyn VirtualGraph<NodeData = N, EdgeData = E>,
        path: &str,
    ) -> GraphResult<()>
    where
        N: Clone + Send + Sync,
        E: Clone + Send + Sync,
    {
        Err(GraphError::NotImplemented(
            "save_graph not implemented".to_string(),
        ))
    }

    /// 获取后端配置
    fn config(&self) -> &BackendConfig {
        &BackendConfig::default()
    }
}

/// 后端功能特性
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BackendFeature {
    /// 支持并行算法
    ParallelAlgorithms,
    /// 支持分布式计算
    DistributedComputing,
    /// 支持 GPU 加速
    GpuAcceleration,
    /// 支持持久化存储
    PersistentStorage,
    /// 支持事务(ACID)
    Transactions,
    /// 支持快照隔离
    SnapshotIsolation,
    /// 支持增量更新
    IncrementalUpdates,
    /// 支持图分区
    GraphPartitioning,
    /// 支持流式处理
    StreamingProcessing,
    /// 支持动态图(频繁更新)
    DynamicGraph,
}

/// 后端配置
#[derive(Debug, Clone, Default)]
pub struct BackendConfig {
    /// 最大并行度
    pub max_parallelism: Option<usize>,
    /// 内存限制(字节)
    pub memory_limit: Option<usize>,
    /// 自定义配置
    pub properties: HashMap<String, String>,
}

/// 图配置
#[derive(Debug, Clone)]
pub struct GraphConfig {
    /// 图类型(有向/无向)
    pub is_directed: bool,
    /// 初始容量(节点数)
    pub initial_capacity: usize,
    /// 是否允许多重边
    pub allows_multiple_edges: bool,
    /// 是否允许自环
    pub allows_self_loops: bool,
    /// 是否启用事务
    pub enable_transactions: bool,
    /// 是否启用快照
    pub enable_snapshots: bool,
    /// 自定义配置
    pub properties: HashMap<String, String>,
}

impl Default for GraphConfig {
    fn default() -> Self {
        Self {
            is_directed: true,
            initial_capacity: 1024,
            allows_multiple_edges: false,
            allows_self_loops: false,
            enable_transactions: false,
            enable_snapshots: false,
            properties: HashMap::new(),
        }
    }
}
```

---

### 3. 插件注册表 (`src/plugins/registry.rs`)

```rust
//! 插件注册表 - 管理所有已注册的插件
//!
//! 类似 Linux 内核的模块管理系统

use std::collections::HashMap;
use std::sync::Mutex;

use once_cell::sync::Lazy;

use crate::backend::GraphBackend;
use crate::plugins::algorithm::GraphAlgorithm;
use crate::plugins::serializer::GraphSerializer;

/// 插件注册表
pub struct PluginRegistry {
    /// 已注册的后端
    backends: HashMap<String, Box<dyn GraphBackend>>,
    /// 已注册的算法
    algorithms: HashMap<String, Box<dyn GraphAlgorithm>>,
    /// 已注册的序列化器
    serializers: HashMap<String, Box<dyn GraphSerializer>>,
    /// 已加载的插件文件
    loaded_plugins: Vec<String>,
}

impl PluginRegistry {
    /// 创建新的注册表
    pub fn new() -> Self {
        Self {
            backends: HashMap::new(),
            algorithms: HashMap::new(),
            serializers: HashMap::new(),
            loaded_plugins: Vec::new(),
        }
    }

    /// 注册后端
    pub fn register_backend(&mut self, backend: Box<dyn GraphBackend>) {
        let name = backend.name().to_string();
        log::info!("Registering backend: {}", name);
        self.backends.insert(name, backend);
    }

    /// 注册算法
    pub fn register_algorithm(&mut self, algorithm: Box<dyn GraphAlgorithm>) {
        let name = algorithm.name().to_string();
        log::info!("Registering algorithm: {}", name);
        self.algorithms.insert(name, algorithm);
    }

    /// 注册序列化器
    pub fn register_serializer(&mut self, serializer: Box<dyn GraphSerializer>) {
        let name = serializer.name().to_string();
        log::info!("Registering serializer: {}", name);
        self.serializers.insert(name, serializer);
    }

    /// 获取后端
    pub fn get_backend(&self, name: &str) -> Option<&dyn GraphBackend> {
        self.backends.get(name).map(|b| b.as_ref())
    }

    /// 获取算法
    pub fn get_algorithm(&self, name: &str) -> Option<&dyn GraphAlgorithm> {
        self.algorithms.get(name).map(|a| a.as_ref())
    }

    /// 获取序列化器
    pub fn get_serializer(&self, name: &str) -> Option<&dyn GraphSerializer> {
        self.serializers.get(name).map(|s| s.as_ref())
    }

    /// 列出所有已注册的后端
    pub fn list_backends(&self) -> Vec<&str> {
        self.backends.keys().map(|s| s.as_str()).collect()
    }

    /// 列出所有已注册的算法
    pub fn list_algorithms(&self) -> Vec<&str> {
        self.algorithms.keys().map(|s| s.as_str()).collect()
    }

    /// 列出所有已注册的序列化器
    pub fn list_serializers(&self) -> Vec<&str> {
        self.serializers.keys().map(|s| s.as_str()).collect()
    }

    /// 检查插件是否已加载
    pub fn is_plugin_loaded(&self, name: &str) -> bool {
        self.loaded_plugins.contains(&name.to_string())
    }

    /// 标记插件为已加载
    pub fn mark_plugin_loaded(&mut self, name: String) {
        self.loaded_plugins.push(name);
    }
}

impl Default for PluginRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// 全局插件注册表(懒加载单例)
static GLOBAL_REGISTRY: Lazy<Mutex<PluginRegistry>> =
    Lazy::new(|| Mutex::new(PluginRegistry::new()));

/// 获取全局插件注册表
pub fn global_registry() -> std::sync::MutexGuard<'static, PluginRegistry> {
    GLOBAL_REGISTRY.lock().unwrap()
}

/// 注册后端到全局注册表
pub fn register_backend(backend: Box<dyn GraphBackend>) {
    let mut registry = global_registry();
    registry.register_backend(backend);
}

/// 注册算法到全局注册表
pub fn register_algorithm(algorithm: Box<dyn GraphAlgorithm>) {
    let mut registry = global_registry();
    registry.register_algorithm(algorithm);
}

/// 注册序列化器到全局注册表
pub fn register_serializer(serializer: Box<dyn GraphSerializer>) {
    let mut registry = global_registry();
    registry.register_serializer(serializer);
}
```

---

### 4. 算法插件接口 (`src/plugins/algorithm.rs`)

```rust
//! 算法插件接口 - 第三方算法扩展点
//!
//! 类似 Linux 内核模块(Kernel Modules)

use std::collections::HashMap;

use crate::vgi::VirtualGraph;
use crate::vgi::error::GraphResult;
use crate::backend::BackendFeature;

/// 算法插件 trait
///
/// # 示例
///
/// ```ignore
/// use god_graph::plugins::algorithm::{GraphAlgorithm, AlgorithmConfig, AlgorithmOutput};
///
/// struct PageRankAlgorithm {
///     damping: f64,
/// }
///
/// impl GraphAlgorithm for PageRankAlgorithm {
///     fn name(&self) -> &'static str {
///         "pagerank"
///     }
///
///     fn execute<N, E>(
///         &self,
///         graph: &dyn VirtualGraph<NodeData = N, EdgeData = E>,
///         config: AlgorithmConfig,
///     ) -> GraphResult<AlgorithmOutput> {
///         // 实现 PageRank 算法
///         let ranks = compute_pagerank(graph, self.damping, config.iterations);
///         Ok(AlgorithmOutput::Vector(ranks))
///     }
/// }
/// ```
pub trait GraphAlgorithm: Send + Sync {
    /// 算法名称
    fn name(&self) -> &'static str;

    /// 算法版本
    fn version(&self) -> &'static str {
        env!("CARGO_PKG_VERSION")
    }

    /// 算法描述
    fn description(&self) -> &'static str;

    /// 算法分类(遍历、最短路径、中心性等)
    fn category(&self) -> AlgorithmCategory;

    /// 算法所需的后端功能
    fn required_features(&self) -> Vec<BackendFeature>;

    /// 执行算法
    fn execute<N, E>(
        &self,
        graph: &dyn VirtualGraph<NodeData = N, EdgeData = E>,
        config: AlgorithmConfig,
    ) -> GraphResult<AlgorithmOutput>
    where
        N: Clone + Send + Sync,
        E: Clone + Send + Sync;

    /// 算法作者(可选)
    fn author(&self) -> Option<&'static str> {
        None
    }

    /// 算法引用(可选)
    fn citation(&self) -> Option<&'static str> {
        None
    }
}

/// 算法分类
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AlgorithmCategory {
    /// 图遍历
    Traversal,
    /// 最短路径
    ShortestPath,
    /// 最小生成树
    MinimumSpanningTree,
    /// 中心性算法
    Centrality,
    /// 社区检测
    CommunityDetection,
    /// 流算法
    Flow,
    /// 匹配算法
    Matching,
    /// 图神经网络
    GNN,
    /// 其他
    Other,
}

/// 算法配置
#[derive(Debug, Clone)]
pub struct AlgorithmConfig {
    /// 算法参数
    pub parameters: HashMap<String, String>,
    /// 超时时间(毫秒)
    pub timeout_ms: Option<u64>,
    /// 并行度
    pub parallelism: Option<usize>,
    /// 随机种子
    pub random_seed: Option<u64>,
}

impl Default for AlgorithmConfig {
    fn default() -> Self {
        Self {
            parameters: HashMap::new(),
            timeout_ms: Some(60000), // 默认 60 秒超时
            parallelism: None,
            random_seed: None,
        }
    }
}

impl AlgorithmConfig {
    /// 创建新的算法配置
    pub fn new() -> Self {
        Self::default()
    }

    /// 设置参数
    pub fn with_param(mut self, key: &str, value: &str) -> Self {
        self.parameters.insert(key.to_string(), value.to_string());
        self
    }

    /// 获取参数
    pub fn get_param(&self, key: &str, default: Option<&str>) -> Option<String> {
        self.parameters
            .get(key)
            .cloned()
            .or_else(|| default.map(|s| s.to_string()))
    }

    /// 获取整数参数
    pub fn get_int_param(&self, key: &str, default: i64) -> i64 {
        self.get_param(key, None)
            .and_then(|s| s.parse().ok())
            .unwrap_or(default)
    }

    /// 获取浮点参数
    pub fn get_float_param(&self, key: &str, default: f64) -> f64 {
        self.get_param(key, None)
            .and_then(|s| s.parse().ok())
            .unwrap_or(default)
    }
}

/// 算法输出
#[derive(Debug, Clone)]
pub enum AlgorithmOutput {
    /// 无输出(仅副作用)
    None,
    /// 节点标签(如社区检测、最短路径距离)
    NodeLabels(HashMap<usize, String>),
    /// 边标签(如最小生成树)
    EdgeLabels(HashMap<usize, String>),
    /// 标量值(如图密度、直径)
    Scalar(f64),
    /// 向量值(如 PageRank 排名)
    Vector(Vec<f64>),
    /// 图结构(如子图提取)
    Subgraph(Box<dyn VirtualGraph>),
    /// 复合结果
    Composite(HashMap<String, AlgorithmOutput>),
}

impl AlgorithmOutput {
    /// 创建空输出
    pub fn none() -> Self {
        Self::None
    }

    /// 创建标量输出
    pub fn scalar(value: f64) -> Self {
        Self::Scalar(value)
    }

    /// 创建向量输出
    pub fn vector(values: Vec<f64>) -> Self {
        Self::Vector(values)
    }
}
```

---

## 📝 迁移指南

### 从现有 Graph<T, E> 迁移到 VGI

#### 步骤 1: 保持向后兼容

```rust
// 现有代码
use god_graph::graph::Graph;

let mut graph = Graph::<String, f64>::directed();
let a = graph.add_node("A".to_string()).unwrap();
let b = graph.add_node("B".to_string()).unwrap();
graph.add_edge(a, b, 1.0).unwrap();

// 新代码(VGI)
use god_graph::vgi::VirtualGraph;
use god_graph::backend::single_machine::SingleMachineGraph;

let mut graph = SingleMachineGraph::<String, f64>::directed();
let a = graph.add_node("A".to_string()).unwrap();
let b = graph.add_node("B".to_string()).unwrap();
graph.add_edge(a, b, 1.0).unwrap();
```

#### 步骤 2: 实现 VGI trait

```rust
use god_graph::vgi::{VirtualGraph, NodeRef, EdgeRef, GraphMetadata};
use god_graph::vgi::error::GraphResult;

impl<N, E> VirtualGraph for Graph<N, E>
where
    N: Clone + Send + Sync,
    E: Clone + Send + Sync,
{
    type NodeData = N;
    type EdgeData = E;
    type NodeIndex = usize;
    type EdgeIndex = usize;

    fn node_count(&self) -> usize {
        self.node_count()
    }

    fn edge_count(&self) -> usize {
        self.edge_count()
    }

    fn get_node(&self, node: Self::NodeIndex) -> GraphResult<&Self::NodeData> {
        self.get_node(node).map_err(|e| e.into())
    }

    // ... 其他方法实现
}
```

---

## ✅ 验收标准

### Phase 1 完成标准

- [x] `VirtualGraph` trait 定义完成 ✅
- [x] `GraphBackend` trait 定义完成 ✅
- [x] `SingleMachineBackend` 实现完成(现有 Graph 重构)✅
- [x] 插件注册表实现完成 ✅
- [x] 至少 3 个示例算法插件 ✅ (PageRank, BFS, DFS, Connected Components)
- [x] 文档:`VGI_GUIDE.md` 完成 ✅
- [x] 所有现有测试通过 ✅ (196 个测试全部通过)
- [x] 性能基准测试无回归 ✅

### Phase 2 完成标准

- [x] 算法插件接口完善 ✅
- [x] 插件开发模板发布 ✅
- [x] 至少 10 个示例插件 ✅ (PageRank, BFS, DFS, Connected Components, Dijkstra, Bellman-Ford, Topological Sort, Betweenness Centrality, Closeness Centrality, Louvain)
- [x] 文档:`PLUGIN_DEVELOPMENT.md` 完成 ✅
- [ ] 插件热加载机制(可选)

### Phase 3 完成标准

- [x] 图分区器实现(Hash, Range)✅
- [x] 分布式执行引擎实现 ✅
- [x] 分布式 PageRank 和 BFS ✅
- [x] 性能基准测试报告 ✅
- [x] 文档:`DISTRIBUTED_GUIDE.md` 完成 ✅

---

## 🔗 参考资源

- [Linux VFS 设计]https://www.kernel.org/doc/html/latest/filesystems/vfs.html
- [OSGi 插件架构]https://www.osgi.org/developer/
- [Apache Spark GraphX]https://spark.apache.org/graphx/
- [Neo4j Graph Database]https://neo4j.com/

---

## 📊 当前进度

### 已完成的工作 (Phase 1, Phase 2 & Phase 3 ✅)

✅ **核心架构**
- `VirtualGraph` trait 定义和实现
- `Backend` trait 定义和实现
- `SingleMachineBackend` 完整实现
- `Graph<T, E>` 无缝集成到 VGI 体系

✅ **插件系统**
- `PluginRegistry` 插件注册表
- `GraphAlgorithm` 算法插件接口
- 内置算法:PageRank, BFS, DFS, Connected Components, Dijkstra, Bellman-Ford, Topological Sort, Betweenness Centrality, Closeness Centrality, Louvain (共 10 个)
- 插件标签系统和查找功能
- 插件开发文档:`PLUGIN_DEVELOPMENT.md`

✅ **分布式处理**
- `HashPartitioner``RangePartitioner`
- `DistributedExecutor` 执行引擎
- `Communication` 通信层
- 分布式 PageRank 和 BFS 算法
- 性能基准测试报告:`distributed-benchmarks.md`

✅ **文档**
- `VGI_GUIDE.md` 用户指南
- `VGI_IMPLEMENTATION_PLAN.md` 实施计划(本文档)
- `PLUGIN_DEVELOPMENT.md` 插件开发指南
- `DISTRIBUTED_GUIDE.md` 分布式处理指南
- `PHASE2_PLUGIN_ECOSYSTEM_PLAN.md` Phase 2 实施计划
- `distributed-benchmarks.md` 性能基准测试报告

### Phase 3 总结

🎉 **Phase 3 已完成!**

**关键成果**:
1. ✅ 完整的分布式图处理框架
2. ✅ 两种分区策略(Hash、Range)
3. ✅ 分布式执行引擎和通信层
4. ✅ 分布式 PageRank 和 BFS 算法
5. ✅ 性能基准测试(13 个基准测试)
6. ✅ 完整的分布式处理指南

**性能亮点**:
- Range 分区器比 Hash 快 1.2-6.8x
- 分布式 PageRank: 10K 节点 5.24ms
- 分布式 BFS: 10K 节点 238µs
- 分区开销:PageRank 3.5-5x, BFS 2.4-2.8x

**下一步行动**:

1. ✅ Phase 1 实施完成
2. ✅ Phase 2 插件生态建设完成
3. ✅ Phase 3 分布式处理完成
4. 🔲 Phase 4: 生产就绪 (v1.0.0-stable)
   - API 稳定性审查
   - 更多分布式算法(DFS、Connected Components、最短路径)
   - 容错机制
   - 生产环境测试