Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

Assert the graph export's shaping without needing a loaded module

Shanuf41e7a47044b
diff --git a/src/openhuman/memory/read_rpc/graph.rs b/src/openhuman/memory/read_rpc/graph.rs
index 07ba2f6e54..6acbdb163b 100644
--- a/src/openhuman/memory/read_rpc/graph.rs
+++ b/src/openhuman/memory/read_rpc/graph.rs
@@ -115,12 +115,6 @@ pub async fn graph_export_rpc(
async fn collect_tree_graph(cfg: &Config) -> Result<(Vec<GraphNode>, Vec<GraphEdge>), String> {
const MAX_TREE_NODES: usize = 10_000;
- struct SummaryRow {
- node: GraphNode,
- tree_scope: String,
- child_ids: Vec<String>,
- }
-
let binding = crate::openhuman::memory::binding::for_config(cfg)?;
// Resolved once and held across both calls: the forest skeleton and its
// bottom edge are two members of the same family, and re-resolving between
@@ -161,11 +155,86 @@ async fn collect_tree_graph(cfg: &Config) -> Result<(Vec<GraphNode>, Vec<GraphEd
forest.truncated
);
+ let mut nodes = shape_summary_nodes(forest.summaries, MAX_TREE_NODES);
+
+ let chunk_budget = MAX_TREE_NODES.saturating_sub(nodes.len());
+ // The guard is load-bearing, not cosmetic: the driver clamps a listing
+ // limit into `1..=cap`, so asking for zero leaves would return one.
+ if chunk_budget > 0 {
+ let leaves = match tree {
+ Some(tree) => tree
+ .recent_leaves(chunk_budget, None)
+ .await
+ .map_err(|e| format!("recent_leaves: {e}"))?,
+ None => Vec::new(),
+ };
+ log::debug!(
+ "[memory_tree::read::graph_tree] leaves={} budget={chunk_budget}",
+ leaves.len()
+ );
+ for leaf in leaves {
+ let TreeLeaf {
+ chunk_id,
+ parent_summary_id,
+ // Selected by the read this replaced and discarded there too:
+ // a leaf node draws its edge from its summary, not its source.
+ source_id: _,
+ preview,
+ time_range_start,
+ time_range_end,
+ } = leaf;
+ let label = preview.chars().take(CHUNK_LABEL_CHARS).collect::<String>();
+ nodes.push(GraphNode {
+ kind: "chunk".into(),
+ id: chunk_id,
+ label,
+ tree_kind: None,
+ tree_scope: None,
+ tree_id: None,
+ level: None,
+ // The contract's driver already drops the empty string; kept
+ // here so a driver that does not cannot draw an edge to a node
+ // named "".
+ parent_id: parent_summary_id.filter(|s| !s.is_empty()),
+ child_count: None,
+ time_range_start_ms: Some(time_range_start.timestamp_millis()),
+ time_range_end_ms: Some(time_range_end.timestamp_millis()),
+ file_basename: None,
+ entity_kind: None,
+ });
+ }
+ }
+
+ Ok((nodes, Vec::new()))
+}
+
+/// Shape the forest's summary nodes into graph nodes: a synthetic source root
+/// per scope, every summary re-parented onto its root when its real parent is
+/// not itself in the forest, and a document leaf per child id of an L1 summary
+/// that sealed over raw items rather than other summaries.
+///
+/// Split out of [`collect_tree_graph`] because it is the whole of what this
+/// export decides. The driver supplies the forest and nothing else: which
+/// nodes exist, how they are labelled, what is a root, what is an orphan and
+/// what becomes a document leaf are all decided here. Keeping it a pure
+/// function of the forest is what lets those rules be asserted directly —
+/// `summary_forest` is served by the memory module now, so a test that reached
+/// them through `graph_export_rpc` would need a loaded module to say anything
+/// about node shape (see graph_tests.rs).
+///
+/// `max_nodes` bounds the whole result, document leaves included; the summary
+/// nodes are emitted first and the document tail is what gets cut.
+fn shape_summary_nodes(summaries: Vec<TreeSummary>, max_nodes: usize) -> Vec<GraphNode> {
+ struct SummaryRow {
+ node: GraphNode,
+ tree_scope: String,
+ child_ids: Vec<String>,
+ }
+
// Destructured exhaustively rather than field-picked: a field added to
// `TreeSummary` upstream then fails to compile here instead of silently
// going unrendered.
- let summary_rows: Vec<SummaryRow> = forest
- .summaries
+ let summary_rows: Vec<SummaryRow> = summaries
.into_iter()
.map(|summary| {
let TreeSummary {
@@ -254,7 +323,7 @@ async fn collect_tree_graph(cfg: &Config) -> Result<(Vec<GraphNode>, Vec<GraphEd
nodes.push(node);
}
- let doc_budget = MAX_TREE_NODES.saturating_sub(nodes.len());
+ let doc_budget = max_nodes.saturating_sub(nodes.len());
let mut doc_count = 0usize;
for sr in &summary_rows {
if doc_count >= doc_budget {
@@ -295,55 +364,7 @@ async fn collect_tree_graph(cfg: &Config) -> Result<(Vec<GraphNode>, Vec<GraphEd
}
}
- let chunk_budget = MAX_TREE_NODES.saturating_sub(nodes.len());
- // The guard is load-bearing, not cosmetic: the driver clamps a listing
- // limit into `1..=cap`, so asking for zero leaves would return one.
- if chunk_budget > 0 {
- let leaves = match tree {
- Some(tree) => tree
- .recent_leaves(chunk_budget, None)
- .await
- .map_err(|e| format!("recent_leaves: {e}"))?,
- None => Vec::new(),
- };
- log::debug!(
- "[memory_tree::read::graph_tree] leaves={} budget={chunk_budget}",
- leaves.len()
- );
- for leaf in leaves {
- let TreeLeaf {
- chunk_id,
- parent_summary_id,
- // Selected by the read this replaced and discarded there too:
- // a leaf node draws its edge from its summary, not its source.
- source_id: _,
- preview,
- time_range_start,
- time_range_end,
- } = leaf;
- let label = preview.chars().take(CHUNK_LABEL_CHARS).collect::<String>();
- nodes.push(GraphNode {
- kind: "chunk".into(),
- id: chunk_id,
- label,
- tree_kind: None,
- tree_scope: None,
- tree_id: None,
- level: None,
- // The contract's driver already drops the empty string; kept
- // here so a driver that does not cannot draw an edge to a node
- // named "".
- parent_id: parent_summary_id.filter(|s| !s.is_empty()),
- child_count: None,
- time_range_start_ms: Some(time_range_start.timestamp_millis()),
- time_range_end_ms: Some(time_range_end.timestamp_millis()),
- file_basename: None,
- entity_kind: None,
- });
- }
- }
-
- Ok((nodes, Vec::new()))
+ nodes
}
fn scope_display_label(scope: &str) -> String {
@@ -558,3 +579,7 @@ pub fn sanitize_basename(id: &str) -> String {
})
.collect()
}
+
+#[cfg(test)]
+#[path = "graph_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/read_rpc/graph_tests.rs b/src/openhuman/memory/read_rpc/graph_tests.rs
new file mode 100644
index 0000000000..99658d2d20
--- /dev/null
+++ b/src/openhuman/memory/read_rpc/graph_tests.rs
@@ -0,0 +1,245 @@
+//! Sibling tests for the tree-mode graph export, covering the shaping that
+//! stayed host-side when `summary_forest` moved onto the memory module (#5560).
+//!
+//! These assertions used to live in `tests/memory_sync_pipeline_e2e.rs`, driven
+//! through `graph_export_rpc` against an in-process engine. That route is gone:
+//! the forest is served by the module now, so the same test would need a loaded
+//! module to say anything at all about node shape — and it would then be
+//! asserting the driver's storage as much as the host's rendering. What is
+//! actually worth pinning here is the second half, and none of it needs a store:
+//!
+//! 1. **A synthetic source root per scope, parented to nothing.** The forest has
+//! no such node; the export invents one so the UI has something to hang a
+//! tree off. Its id is derived (`source:<scope>`), so a scope that collides
+//! with a real summary id would silently merge two trees.
+//! 2. **An orphan summary is re-parented onto its source root, and only an
+//! orphan.** "Orphan" means the parent it names is not itself in the forest —
+//! which is the normal state of an L1 seal, not an error. A summary whose
+//! parent *is* present must keep it, or a truncated forest would quietly
+//! reshape into a flat one.
+//! 3. **Document leaves come from an L1 summary's child ids, but only when
+//! those children are raw items.** A summary that sealed over other
+//! summaries already has its children in the forest as real nodes; emitting
+//! document leaves for them too would double every interior node.
+//! 4. **The node budget cuts the document tail, never the summaries.** The
+//! summaries are the skeleton — a budget that dropped them would leave
+//! document leaves parented to nodes that are not in the response.
+
+use chrono::{TimeZone, Utc};
+
+use super::shape_summary_nodes;
+use crate::openhuman::memory::api::tree::TreeSummary;
+
+const BUDGET: usize = 10_000;
+
+fn summary(
+ id: &str,
+ scope: &str,
+ level: u32,
+ parent: Option<&str>,
+ children: &[&str],
+) -> TreeSummary {
+ TreeSummary {
+ id: id.to_string(),
+ tree_id: format!("tree-{scope}"),
+ tree_kind: "source".to_string(),
+ tree_scope: scope.to_string(),
+ level,
+ parent_id: parent.map(str::to_string),
+ child_ids: children.iter().map(|c| (*c).to_string()).collect(),
+ time_range_start: Utc.timestamp_opt(1_700_000_000, 0).unwrap(),
+ time_range_end: Utc.timestamp_opt(1_700_000_900, 0).unwrap(),
+ }
+}
+
+#[test]
+fn each_scope_gets_one_synthetic_source_root_with_no_parent() {
+ let nodes = shape_summary_nodes(
+ vec![
+ summary("summary:a", "github:acme/widgets", 1, None, &["commit:aaa"]),
+ summary("summary:b", "github:acme/gadgets", 1, None, &["commit:bbb"]),
+ // A second summary in an already-seen scope must not add a root.
+ summary("summary:c", "github:acme/widgets", 1, None, &["commit:ccc"]),
+ ],
+ BUDGET,
+ );
+
+ let roots: Vec<_> = nodes.iter().filter(|n| n.kind == "source").collect();
+ assert_eq!(roots.len(), 2, "one root per distinct scope, got {roots:?}");
+ for root in &roots {
+ assert_eq!(root.parent_id, None, "a source root has no parent");
+ }
+ assert!(roots.iter().any(|n| n.id == "source:github:acme/widgets"));
+ assert!(roots.iter().any(|n| n.id == "source:github:acme/gadgets"));
+}
+
+#[test]
+fn an_orphan_summary_is_reparented_onto_its_source_root() {
+ // `parent_id` names a summary that is not in the forest — the ordinary
+ // shape of an L1 seal that has not been rolled up yet.
+ let nodes = shape_summary_nodes(
+ vec![summary(
+ "summary:l1",
+ "github:acme/widgets",
+ 1,
+ Some("summary:absent"),
+ &["commit:aaa"],
+ )],
+ BUDGET,
+ );
+
+ let l1 = nodes
+ .iter()
+ .find(|n| n.id == "summary:l1")
+ .expect("the summary is in the graph");
+ assert_eq!(
+ l1.parent_id.as_deref(),
+ Some("source:github:acme/widgets"),
+ "an unresolvable parent means orphan, so it hangs off the source root"
+ );
+}
+
+#[test]
+fn a_summary_whose_parent_is_present_keeps_it() {
+ let nodes = shape_summary_nodes(
+ vec![
+ summary(
+ "summary:l2",
+ "github:acme/widgets",
+ 2,
+ None,
+ &["summary:l1"],
+ ),
+ summary(
+ "summary:l1",
+ "github:acme/widgets",
+ 1,
+ Some("summary:l2"),
+ &["commit:aaa"],
+ ),
+ ],
+ BUDGET,
+ );
+
+ let l1 = nodes
+ .iter()
+ .find(|n| n.id == "summary:l1")
+ .expect("the L1 summary is in the graph");
+ assert_eq!(
+ l1.parent_id.as_deref(),
+ Some("summary:l2"),
+ "a real parent in the forest must survive the re-parenting pass"
+ );
+}
+
+#[test]
+fn document_leaves_are_emitted_for_an_l1_summary_over_raw_items() {
+ let nodes = shape_summary_nodes(
+ vec![summary(
+ "summary:l1",
+ "github:acme/widgets",
+ 1,
+ None,
+ &["commit:aaa111", "issue:42", "pr:7"],
+ )],
+ BUDGET,
+ );
+
+ let docs: Vec<_> = nodes
+ .iter()
+ .filter(|n| n.kind == "chunk" && n.parent_id.as_deref() == Some("summary:l1"))
+ .collect();
+ assert_eq!(
+ docs.len(),
+ 3,
+ "one document leaf per raw child id, got {docs:?}"
+ );
+ assert!(
+ docs.iter().any(|n| n.id.contains("commit:aaa111")),
+ "the child id is carried into the leaf's own id"
+ );
+}
+
+#[test]
+fn a_summary_that_sealed_over_summaries_emits_no_document_leaves() {
+ // Its children are already in the forest as real summary nodes; emitting
+ // document leaves for them as well would render every interior node twice.
+ let nodes = shape_summary_nodes(
+ vec![
+ summary(
+ "summary:l1",
+ "github:acme/widgets",
+ 1,
+ None,
+ &["summary:child-a", "summary:child-b"],
+ ),
+ summary("summary:child-a", "github:acme/widgets", 1, None, &[]),
+ ],
+ BUDGET,
+ );
+
+ let docs: Vec<_> = nodes
+ .iter()
+ .filter(|n| n.kind == "chunk" && n.parent_id.as_deref() == Some("summary:l1"))
+ .collect();
+ assert!(docs.is_empty(), "expected no document leaves, got {docs:?}");
+}
+
+#[test]
+fn a_non_l1_summary_emits_no_document_leaves() {
+ let nodes = shape_summary_nodes(
+ vec![summary(
+ "summary:l2",
+ "github:acme/widgets",
+ 2,
+ None,
+ &["commit:aaa"],
+ )],
+ BUDGET,
+ );
+
+ assert!(
+ !nodes.iter().any(|n| n.kind == "chunk"),
+ "document leaves hang off L1 only, got {nodes:?}"
+ );
+}
+
+#[test]
+fn the_budget_cuts_the_document_tail_and_keeps_every_summary() {
+ // One scope (1 root) + one summary = 2 nodes before any document leaf, so
+ // a budget of 3 leaves room for exactly one of the three children.
+ let nodes = shape_summary_nodes(
+ vec![summary(
+ "summary:l1",
+ "github:acme/widgets",
+ 1,
+ None,
+ &["commit:aaa", "commit:bbb", "commit:ccc"],
+ )],
+ 3,
+ );
+
+ assert_eq!(
+ nodes.iter().filter(|n| n.kind == "source").count(),
+ 1,
+ "the source root survives the budget"
+ );
+ assert_eq!(
+ nodes.iter().filter(|n| n.kind == "summary").count(),
+ 1,
+ "the summary skeleton survives the budget"
+ );
+ assert_eq!(
+ nodes.iter().filter(|n| n.kind == "chunk").count(),
+ 1,
+ "only the document tail is cut, got {nodes:?}"
+ );
+}
+
+#[test]
+fn an_empty_forest_shapes_to_no_nodes_at_all() {
+ // Not even a source root: roots are derived from the scopes present, so a
+ // store that has sealed nothing renders as empty rather than as one bare
+ // root per scope it has never seen.
+ assert!(shape_summary_nodes(Vec::new(), BUDGET).is_empty());
+}
diff --git a/tests/memory_sync_pipeline_e2e.rs b/tests/memory_sync_pipeline_e2e.rs
index 8cc3738c42..07060b6179 100644
--- a/tests/memory_sync_pipeline_e2e.rs
+++ b/tests/memory_sync_pipeline_e2e.rs
@@ -43,7 +43,6 @@ use chrono::Utc;
use tempfile::TempDir;
use openhuman_core::openhuman::config::Config;
-use openhuman_core::openhuman::memory::read_rpc::{graph_export_rpc, GraphMode};
use openhuman_core::openhuman::memory::sources::sync::sync_source;
use openhuman_core::openhuman::memory::sources::types::{MemorySourceEntry, SourceKind};
use openhuman_core::openhuman::memory::tree::ingest::{ingest_summary, SummaryIngestInput};
@@ -111,6 +110,10 @@ fn summary_input(content: &str, tokens: u32) -> SummaryIngestInput {
fn run_git(args: &[&str], cwd: &Path) {
let status = Command::new("git")
+ // A contributor with `commit.gpgsign = true` set globally otherwise
+ // gets a `git commit` here that blocks forever on a pinentry prompt
+ // with no tty behind it — the whole file hangs rather than failing.
+ .args(["-c", "commit.gpgsign=false"])
.args(args)
.current_dir(cwd)
.env("GIT_AUTHOR_NAME", "Test")
@@ -503,87 +506,10 @@ async fn check_and_rebuild_auto_detects_raw_without_summaries() {
// ── Test 6: graph export — source roots, doc leaves, orphan linking ────────
-#[tokio::test]
-async fn graph_export_builds_source_roots_doc_leaves_and_orphan_links() {
- let tmp = TempDir::new().unwrap();
- let cfg = test_config(&tmp);
-
- // Ingest an L1 summary whose children are raw item ids (commits) — this
- // is the shape that produces document/chunk leaf nodes in the export.
- let scope = "github:acme/widgets";
- let tree = get_or_create_source_tree(&cfg, scope).unwrap();
- let mut input = summary_input("Summary of recent commits to widgets.", 40);
- input.child_labels = vec![
- "commit:aaa111".to_string(),
- "issue:42".to_string(),
- "pr:7".to_string(),
- ];
- let ingested = ingest_summary(&cfg, &tree, input).await.unwrap();
-
- // Export the tree-mode graph.
- let resp = graph_export_rpc(&cfg, GraphMode::Tree)
- .await
- .expect("graph_export_rpc should succeed");
- let nodes = resp.value.nodes;
-
- // (a) Synthetic source root for the scope.
- let source_root_id = format!("source:{scope}");
- let root = nodes
- .iter()
- .find(|n| n.id == source_root_id)
- .expect("a synthetic source-root node must exist for the scope");
- assert_eq!(root.kind, "source");
- assert_eq!(root.parent_id, None, "source root has no parent");
-
- // (b) The L1 summary is an orphan (no real summary parent) and so links
- // to its source root.
- let summary = nodes
- .iter()
- .find(|n| n.id == ingested.summary_id)
- .expect("the ingested L1 summary must appear in the graph");
- assert_eq!(summary.kind, "summary");
- assert_eq!(
- summary.parent_id.as_deref(),
- Some(source_root_id.as_str()),
- "orphan summary should be re-parented onto its synthetic source root"
- );
-
- // (c) Document leaf nodes are emitted from the L1 summary's child_ids,
- // each parented to the summary.
- let doc_nodes: Vec<_> = nodes
- .iter()
- .filter(|n| {
- n.kind == "chunk" && n.parent_id.as_deref() == Some(ingested.summary_id.as_str())
- })
- .collect();
- assert_eq!(
- doc_nodes.len(),
- 3,
- "expected 3 document leaf nodes from the summary's child_ids, got {}",
- doc_nodes.len()
- );
- assert!(
- doc_nodes.iter().any(|n| n.id.contains("commit:aaa111")),
- "a document leaf for commit:aaa111 should exist"
- );
-
- // (d) content_root_abs is populated so the UI can build the vault link.
- assert!(
- !resp.value.content_root_abs.is_empty(),
- "graph export should carry the absolute content root"
- );
-
- // Sanity: the export is non-trivial.
- assert!(
- nodes.len() >= 5,
- "graph should have source root + summary + 3 docs, got {} nodes: {:?}",
- nodes.len(),
- nodes.iter().map(|n| (&n.kind, &n.id)).collect::<Vec<_>>()
- );
-
- // Tree mode encodes edges via parent_id, so the explicit edges array is empty.
- assert!(
- resp.value.edges.is_empty(),
- "tree-mode export encodes edges via parent_id, not the edges array"
- );
-}
+// `graph_export_builds_source_roots_doc_leaves_and_orphan_links` used to sit
+// here. `graph_export_rpc` reads the forest through `summary_forest`, which the
+// memory module serves now (#5560), so the case could only run against a loaded
+// module — and what it actually asserted was the host's own shaping of that
+// forest, not the store underneath it. Those assertions moved to
+// `src/openhuman/memory/read_rpc/graph_tests.rs`, where they are a pure
+// function of a hand-built forest and cover more cases than this one could.