arc-graph-core 0.2.0

Framework-free knowledge-graph model for arc-graph: nodes, typed kinds, weighted edges, adjacency index, filter/search and JSON/CSV import.
Documentation
//! 知识图谱数据模型:节点 / 关系 / 类型 / 权重 + 变更 API。
//!
//! 设计要点(方案 `docs/graph/knowledge-graph-plan.md` §2):
//! - 纯数据,不依赖 gpui;颜色等外观一律留在视图层(arc-tokens),核心层只存类型名。
//! - 权重在输入边界净化(NaN / 负数归默认值),布局引擎(G2)可以直接信任。
//! - 邻接索引增量维护(见 [`AdjacencyIndex`]),读路径 O(1),写路径摊还 O(degree)。

use crate::adjacency::AdjacencyIndex;
use crate::ids::{EdgeId, KindId, NodeId};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;

/// 节点默认质量(力导向里的质量 / 惯性)。
pub const DEFAULT_NODE_WEIGHT: f32 = 1.0;
/// 边默认引力强度。
pub const DEFAULT_EDGE_WEIGHT: f32 = 1.0;

/// 顶层错误。`Display` 与 arc-flow-core 的 `GraphError` 风格一致。
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GraphError {
    MissingNode(NodeId),
    MissingEdge(EdgeId),
    MissingKind(KindId),
    DuplicateId(u64),
    /// 导入文档结构不合法(坏 JSON / 表头缺失等)。解析层保证不 panic。
    Format(String),
}

impl fmt::Display for GraphError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingNode(id) => write!(f, "missing node {id}"),
            Self::MissingEdge(id) => write!(f, "missing edge {id}"),
            Self::MissingKind(id) => write!(f, "missing kind {id}"),
            Self::DuplicateId(id) => write!(f, "duplicate id {id}"),
            Self::Format(m) => write!(f, "invalid document: {m}"),
        }
    }
}

impl std::error::Error for GraphError {}

/// 节点类型(如「人物」「机构」「概念」)。只存名称;颜色映射在视图层按类型序号取 arc-tokens 调色板。
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NodeKind {
    pub id: KindId,
    pub name: String,
}

/// 图节点。`weight` 是力导向质量,`pinned` 表示布局中固定不动。
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Node {
    pub id: NodeId,
    /// 类型;`None` 表示未分类。
    pub kind: Option<KindId>,
    pub label: String,
    /// 布局质量,恒 ≥ 0 且非 NaN(输入边界已净化)。
    pub weight: f32,
    /// 固定节点:布局迭代中位置不动,可被拖动 / 搜索定位。
    pub pinned: bool,
}

/// 关系边。知识图谱常为有向(A → B),也支持无向整体开关。
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Edge {
    pub id: EdgeId,
    pub source: NodeId,
    pub target: NodeId,
    /// 引力强度,恒 ≥ 0 且非 NaN。
    pub weight: f32,
    pub label: Option<String>,
}

/// 权重净化:NaN / 负数 / 非有限值归默认,防止布局发散(方案 §7「大图不溢出」)。
pub(crate) fn sanitize_weight(w: f32, default: f32) -> f32 {
    if w.is_finite() && w >= 0.0 {
        w
    } else {
        default
    }
}

/// 持久化文档格式(JSON)。
#[derive(Serialize, Deserialize)]
struct GraphDoc {
    version: u32,
    directed: bool,
    kinds: Vec<NodeKind>,
    nodes: Vec<Node>,
    edges: Vec<Edge>,
}

/// 知识图谱。有向 / 无向在图级别声明(布局与邻接口径一致)。
#[derive(Clone, Debug, Default)]
pub struct KnowledgeGraph {
    /// 是否有向;无向图的邻接查询双向对称。
    pub directed: bool,
    kinds: BTreeMap<KindId, NodeKind>,
    nodes: BTreeMap<NodeId, Node>,
    edges: BTreeMap<EdgeId, Edge>,
    adjacency: AdjacencyIndex,
    next_node: u64,
    next_edge: u64,
    next_kind: u64,
}

impl KnowledgeGraph {
    pub fn new() -> Self {
        Self {
            directed: false,
            next_node: 1,
            next_edge: 1,
            next_kind: 1,
            ..Default::default()
        }
    }

    /// 有向图构造器(导入与测试用)。
    pub fn directed(mut self) -> Self {
        self.directed = true;
        self
    }

    // ---------- ID ----------

    /// 分配并占用一个新节点 ID(导入预扫用,避免逐条 add 的开销)。
    pub fn alloc_node_id(&mut self) -> NodeId {
        let id = NodeId(self.next_node);
        self.next_node += 1;
        id
    }

    pub fn alloc_edge_id(&mut self) -> EdgeId {
        let id = EdgeId(self.next_edge);
        self.next_edge += 1;
        id
    }

    pub fn alloc_kind_id(&mut self) -> KindId {
        let id = KindId(self.next_kind);
        self.next_kind += 1;
        id
    }

    // ---------- 类型 ----------

    pub fn add_kind(&mut self, name: impl Into<String>) -> KindId {
        let id = self.alloc_kind_id();
        self.kinds.insert(
            id,
            NodeKind {
                id,
                name: name.into(),
            },
        );
        id
    }

    /// 插入指定 ID 的类型;已存在时只更新名称(CSV 按名引用的场景)。
    pub fn upsert_kind(&mut self, id: KindId, name: impl Into<String>) {
        self.kinds
            .entry(id)
            .or_insert_with(|| NodeKind {
                id,
                name: String::new(),
            })
            .name = name.into();
        self.next_kind = self.next_kind.max(id.0 + 1);
    }

    pub fn kind(&self, id: KindId) -> Option<&NodeKind> {
        self.kinds.get(&id)
    }

    /// 类型列表,按 ID 有序(保证遍历与序列化可复现)。
    pub fn kinds(&self) -> impl Iterator<Item = &NodeKind> {
        self.kinds.values()
    }

    // ---------- 节点 ----------

    pub fn add_node(&mut self, label: impl Into<String>, kind: Option<KindId>) -> NodeId {
        let id = self.alloc_node_id();
        // 新分配的 ID 不可能与现有节点冲突,插入必成功。
        self.insert_node(Node {
            id,
            kind,
            label: label.into(),
            weight: DEFAULT_NODE_WEIGHT,
            pinned: false,
        })
        .expect("freshly allocated node id must not collide");
        id
    }

    /// 插入完整节点(导入路径)。ID 已存在返回错误且不产生半写入。
    pub fn insert_node(&mut self, node: Node) -> Result<(), GraphError> {
        if self.nodes.contains_key(&node.id) {
            return Err(GraphError::DuplicateId(node.id.0));
        }
        if let Some(k) = node.kind
            && !self.kinds.contains_key(&k)
        {
            return Err(GraphError::MissingKind(k));
        }
        let n = Node {
            weight: sanitize_weight(node.weight, DEFAULT_NODE_WEIGHT),
            ..node
        };
        // 外部指定的 ID 也要推进计数器,避免后续 add_node 分配出重复 ID。
        self.next_node = self.next_node.max(n.id.0 + 1);
        self.adjacency.add_vertex(n.id);
        self.nodes.insert(n.id, n);
        Ok(())
    }

    /// 直接更新节点(保留原位置语义在布局层,这里只是存储替换)。
    pub fn update_node(&mut self, node: Node) -> Result<(), GraphError> {
        if !self.nodes.contains_key(&node.id) {
            return Err(GraphError::MissingNode(node.id));
        }
        let n = Node {
            weight: sanitize_weight(node.weight, DEFAULT_NODE_WEIGHT),
            ..node
        };
        self.nodes.insert(n.id, n);
        Ok(())
    }

    pub fn node(&self, id: NodeId) -> Option<&Node> {
        self.nodes.get(&id)
    }

    /// 删除节点,级联删除全部关联边。
    pub fn remove_node(&mut self, id: NodeId) -> Result<(), GraphError> {
        let Some(_node) = self.nodes.remove(&id) else {
            return Err(GraphError::MissingNode(id));
        };
        let incident = self.adjacency.incident_edges(id);
        for e in incident {
            if let Some(edge) = self.edges.remove(&e) {
                self.adjacency
                    .remove_edge(edge.source, edge.target, e, self.directed);
            }
        }
        self.adjacency.remove_vertex(id);
        Ok(())
    }

    // ---------- 边 ----------

    pub fn add_edge(
        &mut self,
        source: NodeId,
        target: NodeId,
        weight: f32,
        label: Option<String>,
    ) -> Result<EdgeId, GraphError> {
        if !self.nodes.contains_key(&source) {
            return Err(GraphError::MissingNode(source));
        }
        if !self.nodes.contains_key(&target) {
            return Err(GraphError::MissingNode(target));
        }
        let id = self.alloc_edge_id();
        self.edges.insert(
            id,
            Edge {
                id,
                source,
                target,
                weight: sanitize_weight(weight, DEFAULT_EDGE_WEIGHT),
                label,
            },
        );
        self.adjacency.add_edge(source, target, id, self.directed);
        Ok(id)
    }

    pub fn edge(&self, id: EdgeId) -> Option<&Edge> {
        self.edges.get(&id)
    }

    pub fn remove_edge(&mut self, id: EdgeId) -> Result<(), GraphError> {
        let Some(edge) = self.edges.remove(&id) else {
            return Err(GraphError::MissingEdge(id));
        };
        self.adjacency
            .remove_edge(edge.source, edge.target, id, self.directed);
        Ok(())
    }

    // ---------- 查询 ----------

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

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

    pub fn nodes(&self) -> impl Iterator<Item = &Node> {
        self.nodes.values()
    }

    pub fn edges(&self) -> impl Iterator<Item = &Edge> {
        self.edges.values()
    }

    /// 邻接索引(一度邻居 / 入射边 / 度数)。
    pub fn adjacency(&self) -> &AdjacencyIndex {
        &self.adjacency
    }

    // ---------- 序列化 ----------

    /// 导出为 JSON 文档字符串。
    pub fn to_json(&self) -> String {
        let doc = GraphDoc {
            version: crate::FORMAT_VERSION,
            directed: self.directed,
            kinds: self.kinds.values().cloned().collect(),
            nodes: self.nodes.values().cloned().collect(),
            edges: self.edges.values().cloned().collect(),
        };
        serde_json::to_string(&doc).unwrap_or_else(|_| "{}".into())
    }

    /// 从 JSON 文档导入。坏 JSON 返回 `GraphError::Format`,不 panic。
    pub fn from_json(json: &str) -> Result<Self, GraphError> {
        let doc: GraphDoc =
            serde_json::from_str(json).map_err(|e| GraphError::Format(e.to_string()))?;
        if doc.version != crate::FORMAT_VERSION {
            return Err(GraphError::Format(format!(
                "unsupported version {}",
                doc.version
            )));
        }
        let mut g = Self::new();
        g.directed = doc.directed;
        for k in doc.kinds {
            g.upsert_kind(k.id, k.name);
        }
        for n in doc.nodes {
            g.insert_node(n)?;
        }
        for e in doc.edges {
            if g.edges.contains_key(&e.id) {
                return Err(GraphError::DuplicateId(e.id.0));
            }
            let edge = Edge {
                weight: sanitize_weight(e.weight, DEFAULT_EDGE_WEIGHT),
                ..e
            };
            if !g.nodes.contains_key(&edge.source) {
                return Err(GraphError::MissingNode(edge.source));
            }
            if !g.nodes.contains_key(&edge.target) {
                return Err(GraphError::MissingNode(edge.target));
            }
            let id = edge.id;
            let (source, target) = (edge.source, edge.target);
            g.edges.insert(id, edge);
            g.adjacency.add_edge(source, target, id, g.directed);
            g.next_edge = g.next_edge.max(id.0 + 1);
        }
        Ok(g)
    }
}