Skip to content

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

feat(memory): expose the connector-tree backfill over RPC

Shanu2939aa7134fb
diff --git a/src/openhuman/memory/guard/families_part_01.rs b/src/openhuman/memory/guard/families_part_01.rs
index aa5f6baefd..cd050afb7b 100644
--- a/src/openhuman/memory/guard/families_part_01.rs
+++ b/src/openhuman/memory/guard/families_part_01.rs
@@ -36,9 +36,9 @@ use crate::openhuman::memory::api::provider::sync::{
SyncRunOutcome,
};
use crate::openhuman::memory::api::provider::types::{
- ChunkEntityOccurrence, DiffReport, EntityHit, EntityOccurrence, ForgetOutcome, ForgetSelector,
- IngestItem, IngestOutcome, MaintenanceReport, PurgeOutcome, SnapshotRef, SourceItem,
- SourceScope,
+ BackfillTreesOutcome, BackfillTreesRequest, ChunkEntityOccurrence, DiffReport, EntityHit,
+ EntityOccurrence, ForgetOutcome, ForgetSelector, IngestItem, IngestOutcome,
+ MaintenanceReport, PurgeOutcome, SnapshotRef, SourceItem, SourceScope,
};
use crate::openhuman::memory::api::provider::{
EpisodicEvent, MemoryCodingSessions, MemoryDiff, MemoryDocuments, MemoryEntities, MemoryGoals,
diff --git a/src/openhuman/memory/guard/families_part_02.rs b/src/openhuman/memory/guard/families_part_02.rs
index 865f3ee66f..d153d1ce7a 100644
--- a/src/openhuman/memory/guard/families_part_02.rs
+++ b/src/openhuman/memory/guard/families_part_02.rs
@@ -391,6 +391,23 @@ impl MemoryMaintenance for GuardedMaintenance {
self.family()?.consolidate().await
}
+ /// Writes memory-tree rows for documents already stored, so it takes the
+ /// **write** tier like every other mutating maintenance member. A
+ /// `readonly` operator may inspect a store; re-filing thousands of its
+ /// documents is not inspection.
+ async fn backfill_connector_trees(
+ &self,
+ request: BackfillTreesRequest,
+ ) -> Result<BackfillTreesOutcome, MemoryError> {
+ self.policy.admit_write(
+ Capability::Maintenance,
+ "maintenance.backfill_connector_trees",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?.backfill_connector_trees(request).await
+ }
+
/// Read-only by contract, so this takes the **read** tier check: a
/// `readonly` operator must still be able to run `doctor`, which is exactly
/// the tier where diagnosing without mutating matters most.
diff --git a/src/openhuman/memory/read_rpc/admin.rs b/src/openhuman/memory/read_rpc/admin.rs
index 504dfae394..3e9a844698 100644
--- a/src/openhuman/memory/read_rpc/admin.rs
+++ b/src/openhuman/memory/read_rpc/admin.rs
@@ -15,10 +15,11 @@ use crate::rpc::RpcOutcome;
// and it is the same constant the driver writing those rows reads.
use tinymemory_api::chunks::SourceKind;
use tinymemory_api::composio::KV_NAMESPACE;
+use tinymemory_api::provider::types::BackfillTreesRequest;
use super::types::{
- DeleteSourceResponse, FlushNowResponse, FlushSourceTreeResponse, ResetTreeResponse,
- WipeAllResponse,
+ BackfillConnectorTreesResponse, DeleteSourceResponse, FlushNowResponse,
+ FlushSourceTreeResponse, ResetTreeResponse, WipeAllResponse,
};
// ── wipe_all ─────────────────────────────────────────────────────────────
@@ -418,6 +419,67 @@ pub async fn flush_now_rpc(config: &Config) -> Result<RpcOutcome<FlushNowRespons
Ok(RpcOutcome::single_log(resp, log))
}
+// ── backfill_connector_trees ───────────────────────────────────────────────
+
+/// Re-file connector documents stored before the routing fix into the memory
+/// tree (#6012).
+///
+/// #6007 fixed the routing for items synced from then on. It could not fix the
+/// records already stored: the per-item sync gate treats an ingested document as
+/// done, so re-syncing fetches nothing and creates no tree rows. Those memories
+/// sit fully embedded in the document store and invisible to every tree-backed
+/// surface until something re-files them.
+///
+/// Asked of the driver rather than walked here. The namespaces, the
+/// `{toolkit}:{connection_id}` identity and the ingest funnel all live in the
+/// engine beside the sync path that writes the same rows — a host-side walk
+/// would be a second implementation of an identity that must not drift, which
+/// is the mistake that caused #6007 in the first place.
+///
+/// Expensive by nature: a pass is one read and one set of chunk embeddings per
+/// document. Nothing calls this on its own initiative, and `dry_run` defaults to
+/// true at the RPC boundary so a caller has to ask for the write.
+pub async fn backfill_connector_trees_rpc(
+ config: &Config,
+ limit: Option<u64>,
+ dry_run: bool,
+) -> Result<RpcOutcome<BackfillConnectorTreesResponse>, String> {
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let Some(maintenance) = binding.provider().as_maintenance() else {
+ return Err(format!(
+ "backfill_connector_trees: driver '{}' does not serve Maintenance",
+ binding.driver_id()
+ ));
+ };
+
+ let outcome = maintenance
+ .backfill_connector_trees(BackfillTreesRequest { limit, dry_run })
+ .await
+ .map_err(|error| format!("backfill_connector_trees: {error}"))?;
+
+ let resp = BackfillConnectorTreesResponse {
+ executed: !dry_run,
+ scanned: outcome.scanned,
+ ingested: outcome.ingested,
+ already_present: outcome.already_present,
+ skipped: outcome.skipped,
+ more_pending: outcome.more_pending,
+ notes: outcome.notes,
+ };
+
+ let log = format!(
+ "memory_tree::read: backfill_connector_trees executed={} scanned={} ingested={} \
+ already_present={} skipped={} more_pending={}",
+ resp.executed,
+ resp.scanned,
+ resp.ingested,
+ resp.already_present,
+ resp.skipped,
+ resp.more_pending
+ );
+ Ok(RpcOutcome::single_log(resp, log))
+}
+
// ── delete_source ──────────────────────────────────────────────────────────
/// Fully delete one document source by its **exact** `source_id`.
diff --git a/src/openhuman/memory/read_rpc/mod.rs b/src/openhuman/memory/read_rpc/mod.rs
index 7787461dfc..ebc2362c3c 100644
--- a/src/openhuman/memory/read_rpc/mod.rs
+++ b/src/openhuman/memory/read_rpc/mod.rs
@@ -18,7 +18,8 @@ pub mod vault;
// Re-export everything so consumers and the test file keep working with `use super::*;`
pub use admin::{
- delete_source_rpc, flush_now_rpc, flush_source_tree_rpc, reset_tree_rpc, wipe_all_rpc,
+ backfill_connector_trees_rpc, delete_source_rpc, flush_now_rpc, flush_source_tree_rpc,
+ reset_tree_rpc, wipe_all_rpc,
};
pub use chunks::{
display_name_for_source, list_chunks_rpc, list_sources_rpc, read_chunk_row, recall_rpc,
@@ -32,10 +33,10 @@ pub use graph::{
graph_export_rpc, sanitize_basename, GraphEdge, GraphExportResponse, GraphMode, GraphNode,
};
pub use types::{
- ChunkFilter, ChunkRow, DeleteChunkResponse, DeleteSourceResponse, EntityRef, FlushNowResponse,
- FlushSourceTreeResponse, ListChunksResponse, ObsidianVaultStatusResponse, RecallResponse,
- ResetTreeResponse, ScoreBreakdown, ScoreSignal, Source, VaultHealthCheckResponse,
- WipeAllResponse,
+ BackfillConnectorTreesResponse, ChunkFilter, ChunkRow, DeleteChunkResponse,
+ DeleteSourceResponse, EntityRef, FlushNowResponse, FlushSourceTreeResponse, ListChunksResponse,
+ ObsidianVaultStatusResponse, RecallResponse, ResetTreeResponse, ScoreBreakdown, ScoreSignal,
+ Source, VaultHealthCheckResponse, WipeAllResponse,
};
pub use vault::{obsidian_vault_status_rpc, vault_health_check_rpc};
diff --git a/src/openhuman/memory/read_rpc/types.rs b/src/openhuman/memory/read_rpc/types.rs
index 5dec650fb9..8abdef4453 100644
--- a/src/openhuman/memory/read_rpc/types.rs
+++ b/src/openhuman/memory/read_rpc/types.rs
@@ -155,6 +155,32 @@ pub struct FlushNowResponse {
pub stale_buffers: u32,
}
+/// Response shape for [`backfill_connector_trees_rpc`].
+///
+/// Four counters rather than one, because "did nothing" has three different
+/// causes an operator has to tell apart: the tree already held everything
+/// (`already_present`), nothing could be addressed (`skipped`), or there was
+/// nothing to look at (`scanned == 0`).
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct BackfillConnectorTreesResponse {
+ /// Whether this actually wrote. `false` is the dry-run preview.
+ pub executed: bool,
+ /// Documents examined.
+ pub scanned: u64,
+ /// Documents that produced new memory-tree rows.
+ pub ingested: u64,
+ /// Documents the tree already held — what makes a repeated run readable as
+ /// "nothing left to do" rather than as a failure.
+ pub already_present: u64,
+ /// Documents left alone, never filed under a guess. See `notes`.
+ pub skipped: u64,
+ /// Whether the pass stopped on its limit with documents still unexamined.
+ /// Resume by calling again; the work is idempotent, so there is no cursor.
+ pub more_pending: bool,
+ /// Bounded, human-readable reasons behind `skipped`.
+ pub notes: Vec<String>,
+}
+
/// Response shape for [`obsidian_vault_status_rpc`].
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ObsidianVaultStatusResponse {
diff --git a/src/openhuman/memory/schema/handlers.rs b/src/openhuman/memory/schema/handlers.rs
index a99109e439..de49982600 100644
--- a/src/openhuman/memory/schema/handlers.rs
+++ b/src/openhuman/memory/schema/handlers.rs
@@ -212,6 +212,30 @@ pub(super) fn handle_flush_source(params: Map<String, Value>) -> ControllerFutur
})
}
+pub(super) fn handle_backfill_connector_trees(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ /// `dry_run` defaults to **true**, and the default is the point.
+ ///
+ /// A pass costs one read and one set of chunk embeddings per document,
+ /// against a user's embedding budget. A caller that omits the field gets
+ /// the preview; writing is something you ask for.
+ #[derive(serde::Deserialize)]
+ struct Req {
+ #[serde(default = "dry_run_default")]
+ dry_run: bool,
+ #[serde(default)]
+ limit: Option<u64>,
+ }
+ fn dry_run_default() -> bool {
+ true
+ }
+
+ let config = config_rpc::load_config_with_timeout().await?;
+ let req = parse_value::<Req>(Value::Object(params))?;
+ to_json(read_rpc::backfill_connector_trees_rpc(&config, req.limit, req.dry_run).await?)
+ })
+}
+
pub(super) fn handle_flush_now(_params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let config = config_rpc::load_config_with_timeout().await?;
diff --git a/src/openhuman/memory/schema/registry.rs b/src/openhuman/memory/schema/registry.rs
index e96201ce8e..97a850674f 100644
--- a/src/openhuman/memory/schema/registry.rs
+++ b/src/openhuman/memory/schema/registry.rs
@@ -39,6 +39,7 @@ pub fn all_controller_schemas() -> Vec<ControllerSchema> {
schemas("graph_export"),
schemas("obsidian_vault_status"),
schemas("vault_health_check"),
+ schemas("backfill_connector_trees"),
schemas("flush_now"),
schemas("flush_source"),
schemas("wipe_all"),
@@ -119,6 +120,10 @@ pub fn all_registered_controllers() -> Vec<RegisteredController> {
schema: schemas("vault_health_check"),
handler: handle_vault_health_check,
},
+ RegisteredController {
+ schema: schemas("backfill_connector_trees"),
+ handler: handle_backfill_connector_trees,
+ },
RegisteredController {
schema: schemas("flush_now"),
handler: handle_flush_now,
diff --git a/src/openhuman/memory/schema/schema_schema_part_01.rs b/src/openhuman/memory/schema/schema_schema_part_01.rs
index f85721b994..c6840d3ee1 100644
--- a/src/openhuman/memory/schema/schema_schema_part_01.rs
+++ b/src/openhuman/memory/schema/schema_schema_part_01.rs
@@ -481,6 +481,81 @@ pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {
},
],
}),
+"backfill_connector_trees" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "backfill_connector_trees",
+ description: "Re-file connector documents stored before the memory-tree \
+ routing fix (#6007) into the tree. Those records are already \
+ embedded in the document store but invisible to tree recall, \
+ the memory graph and the source row's ingest status, and a \
+ re-sync will not recover them: the per-item sync gate treats \
+ them as done. Idempotent — the ingest gate recognises what it \
+ already treed, so a repeated pass writes nothing. EXPENSIVE: \
+ one read and one set of chunk embeddings per document, so \
+ `dry_run` defaults to true and a caller must ask for the write.",
+ inputs: vec![
+ FieldSchema {
+ name: "dry_run",
+ ty: TypeSchema::Bool,
+ comment: "Report what a pass would examine and write nothing. \
+ Defaults to TRUE — the write is the opt-in.",
+ required: false,
+ },
+ FieldSchema {
+ name: "limit",
+ ty: TypeSchema::U64,
+ comment: "Documents to examine at most. Omit to leave the bound to \
+ the driver. Resume by calling again; the work is \
+ idempotent, so there is no cursor to carry.",
+ required: false,
+ },
+ ],
+ outputs: vec![
+ FieldSchema {
+ name: "executed",
+ ty: TypeSchema::Bool,
+ comment: "False for a dry-run preview.",
+ required: true,
+ },
+ FieldSchema {
+ name: "scanned",
+ ty: TypeSchema::U64,
+ comment: "Documents examined.",
+ required: true,
+ },
+ FieldSchema {
+ name: "ingested",
+ ty: TypeSchema::U64,
+ comment: "Documents that produced new memory-tree rows.",
+ required: true,
+ },
+ FieldSchema {
+ name: "already_present",
+ ty: TypeSchema::U64,
+ comment: "Documents the tree already held — what makes a repeated \
+ run readable as \"nothing left to do\".",
+ required: true,
+ },
+ FieldSchema {
+ name: "skipped",
+ ty: TypeSchema::U64,
+ comment: "Documents left alone rather than filed under a guess.",
+ required: true,
+ },
+ FieldSchema {
+ name: "more_pending",
+ ty: TypeSchema::Bool,
+ comment: "The pass stopped on its limit with documents unexamined.",
+ required: true,
+ },
+ FieldSchema {
+ name: "notes",
+ ty: TypeSchema::Json,
+ comment: "Bounded, human-readable reasons behind `skipped`.",
+ required: true,
+ },
+ ],
+ }),
"flush_now" => Some( ControllerSchema {
namespace: NAMESPACE,
function: "flush_now",
diff --git a/src/openhuman/modules/memory_part_01.rs b/src/openhuman/modules/memory_part_01.rs
index fa6f5f344e..33d14fc09f 100644
--- a/src/openhuman/modules/memory_part_01.rs
+++ b/src/openhuman/modules/memory_part_01.rs
@@ -151,8 +151,9 @@ use tinymemory_api::provider::sync::{
SyncRunOutcome,
};
use tinymemory_api::provider::types::{
- ChunkEntityOccurrence, DiffReport, EntityHit, EntityOccurrence, ExportPage, ExportRecord,
- FlushOutcome, ForgetOutcome, ForgetSelector, ImportOutcome, IngestItem, IngestOutcome,
+ BackfillTreesOutcome, BackfillTreesRequest, ChunkEntityOccurrence, DiffReport, EntityHit,
+ EntityOccurrence, ExportPage, ExportRecord, FlushOutcome, ForgetOutcome, ForgetSelector,
+ ImportOutcome, IngestItem, IngestOutcome,
MaintenanceReport, PurgeOutcome, QueueFailure, QueueStats, ResetOutcome, SnapshotRef,
SourceItem, SourceScope, StoreStats,
};
diff --git a/src/openhuman/modules/memory_part_02.rs b/src/openhuman/modules/memory_part_02.rs
index 982812f8fc..0def4ae784 100644
--- a/src/openhuman/modules/memory_part_02.rs
+++ b/src/openhuman/modules/memory_part_02.rs
@@ -551,6 +551,22 @@ impl MemoryMaintenance for ModuleMemoryProvider {
async fn flush_pending(&self) -> Result<FlushOutcome, MemoryError> {
module_call!(self, "flush_pending", methods::FLUSH_PENDING, ())
}
+ /// Long-running by nature — a pass reads and re-embeds up to its whole
+ /// limit of documents — so this takes the bulk deadline rather than the
+ /// default 30s one. `AcceptSourceItems` is here for the same reason: a call
+ /// that outruns the deadline while the module goes on working is the
+ /// pathology that made the connector sync retry a finished handoff forever.
+ async fn backfill_connector_trees(
+ &self,
+ request: BackfillTreesRequest,
+ ) -> Result<BackfillTreesOutcome, MemoryError> {
+ module_call_slow!(
+ self,
+ "backfill_connector_trees",
+ methods::BACKFILL_CONNECTOR_TREES,
+ (request,)
+ )
+ }
async fn reset_derived_index(&self) -> Result<ResetOutcome, MemoryError> {
module_call!(
self,