Skip to main content

agentic_memory_mcp/session/
transaction.rs

1//! Batched write transactions for high-throughput scenarios.
2
3use super::manager::SessionManager;
4use crate::types::McpResult;
5use agentic_memory::{CognitiveEvent, Edge, WriteEngine};
6
7/// A batched transaction that collects operations and commits them in one save.
8pub struct Transaction<'a> {
9    session: &'a mut SessionManager,
10    events: Vec<CognitiveEvent>,
11    edges: Vec<Edge>,
12}
13
14impl<'a> Transaction<'a> {
15    /// Create a new transaction on the given session manager.
16    pub fn new(session: &'a mut SessionManager) -> Self {
17        Self {
18            session,
19            events: Vec::new(),
20            edges: Vec::new(),
21        }
22    }
23
24    /// Queue a node to be added.
25    pub fn add_node(&mut self, event: CognitiveEvent) -> &mut Self {
26        self.events.push(event);
27        self
28    }
29
30    /// Queue an edge to be added.
31    pub fn add_edge(&mut self, edge: Edge) -> &mut Self {
32        self.edges.push(edge);
33        self
34    }
35
36    /// Commit all queued operations in a single batch, then save.
37    pub fn commit(self) -> McpResult<Vec<u64>> {
38        let dimension = self.session.graph().dimension();
39        let write_engine = WriteEngine::new(dimension);
40
41        let result = write_engine
42            .ingest(self.session.graph_mut(), self.events, self.edges)
43            .map_err(|e| {
44                crate::types::McpError::AgenticMemory(format!("Transaction commit failed: {e}"))
45            })?;
46
47        self.session.mark_dirty();
48        self.session.save()?;
49
50        Ok(result.new_node_ids)
51    }
52}