Skip to content

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

fix(memory): carry a host sync past what the sink already accepted

Shanu501597ffb563
diff --git a/crates/openhuman-core/src/memory/read_rpc/admin.rs b/crates/openhuman-core/src/memory/read_rpc/admin.rs
index b31a133895..c996f5ab14 100644
--- a/crates/openhuman-core/src/memory/read_rpc/admin.rs
+++ b/crates/openhuman-core/src/memory/read_rpc/admin.rs
@@ -540,6 +540,9 @@ pub async fn delete_source_rpc(
})
.await
.map_err(|e| format!("delete_source: {e}"))?;
+ // A host-synced source's record of what it sent would otherwise skip the
+ // items just forgotten on its next sync.
+ crate::memory::sources::hosted_sync::forget_state(config, &source_id);
let resp = DeleteSourceResponse {
// `deleted` is true if we removed chunks OR cleaned a stale orphaned
diff --git a/crates/openhuman-core/src/memory/sources/hosted_sync.rs b/crates/openhuman-core/src/memory/sources/hosted_sync.rs
index b8a6b902e6..4d9b1427a0 100644
--- a/crates/openhuman-core/src/memory/sources/hosted_sync.rs
+++ b/crates/openhuman-core/src/memory/sources/hosted_sync.rs
@@ -10,20 +10,37 @@
//!
//! # What a run does
//!
-//! It lists the source's items with the source's reader, keeps the newest
-//! `max_items` and none older than `sync_depth_days`, reads each one, and hands
-//! them to `accept_source_items` in batches. The sink skips an item it already
-//! holds unchanged, so a run over an unchanged folder writes nothing, and a
-//! changed item replaces its old version. `max_tokens_per_sync` stops the run
-//! once the text read would pass it, at about four characters a token, and the
-//! run reports more pending.
+//! It lists the source's items with the source's reader, newest first and none
+//! older than `sync_depth_days`, and works only on what is new or changed since
+//! the sink last accepted it: an item whose modified time matches what was
+//! recorded is not read at all, and one read whose text is unchanged is not
+//! sent. New and changed items go to `accept_source_items` in batches, and what
+//! each accepted batch held is recorded once the sink has taken it.
+//!
+//! `max_items` caps the new or changed items a run sends, and
+//! `max_tokens_per_sync` caps their text, at about four characters a token.
+//! Either cap stops the run with more pending, and because what was sent is
+//! recorded, the next run carries on past it rather than re-sending the same
+//! newest items.
+//!
+//! The record is the host's, one small file per source, and it only ever saves
+//! work: a missing or unreadable one is a full pass, which the sink makes
+//! cheap by skipping what it already holds unchanged.
//!
//! # What it does not do
//!
//! An item removed from the source stays in memory: the sink forgets a whole
-//! source, never one item by its id. Removing the source forgets everything it
-//! synced.
+//! source, never one item by its id. Removing a source from the registry stops
+//! its syncs and keeps what it synced, as on the local engine; deleting the
+//! source's memory (`memory_tree.delete_source`) forgets all of it and clears
+//! this record, so a later sync starts over.
+
+use std::collections::{HashMap, HashSet};
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex, OnceLock, PoisonError};
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
use tinymemory_sources::types::ContentType;
use crate::config::Config;
@@ -33,7 +50,8 @@ use crate::memory::api::provider::types::SourceItem as SinkItem;
use crate::memory::api::provider::{MemoryProvider, MemorySourceSink};
use crate::memory::api::types::MemoryTaint;
use crate::memory::sources::readers::{folder, github, rss, web_page, SourceReader};
-use crate::memory::sources::types::{MemorySourceEntry, SourceItem, SourceKind};
+use crate::memory::sources::rpc::driver_run::PartialFailure;
+use crate::memory::sources::types::{MemorySourceEntry, SourceContent, SourceItem, SourceKind};
/// Items handed to the sink in one call.
const BATCH: usize = 25;
@@ -41,6 +59,9 @@ const BATCH: usize = 25;
/// Characters a token is counted as, for `max_tokens_per_sync`.
const CHARS_PER_TOKEN: u64 = 4;
+/// Where the per-source records live, under the workspace's state directory.
+const STATE_DIR: &str = "state/hosted_sync";
+
/// Whether the host syncs local sources for `provider`: it keeps what it is
/// sent, and runs no source pipeline of its own.
pub(crate) fn host_synced(provider: &dyn MemoryProvider) -> bool {
@@ -88,61 +109,224 @@ fn mime_of(content_type: &ContentType) -> &'static str {
}
}
-/// The items a run reads: none older than `sync_depth_days`, newest first, at
-/// most `max_items`.
+/// The items a run considers: none older than `sync_depth_days`, newest first.
fn chosen(entry: &MemorySourceEntry, mut items: Vec<SourceItem>, now_ms: i64) -> Vec<SourceItem> {
if let Some(days) = entry.sync_depth_days.filter(|days| *days > 0) {
let floor = now_ms - i64::from(days) * 86_400_000;
items.retain(|item| item.updated_at_ms.is_none_or(|at| at >= floor));
}
items.sort_by_key(|item| std::cmp::Reverse(item.updated_at_ms));
- if let Some(cap) = entry.max_items {
- items.truncate(cap as usize);
- }
items
}
+/// One item as the sink last took it.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+struct Seen {
+ /// The item's modified time then, when its reader gives one.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ at: Option<i64>,
+ /// A digest of what was sent: its title, text and URL.
+ digest: String,
+}
+
+/// What a source's earlier runs handed the sink, by item id.
+#[derive(Debug, Default, Serialize, Deserialize)]
+struct SyncState {
+ #[serde(default)]
+ items: HashMap<String, Seen>,
+}
+
+/// The file holding `source_id`'s record. The name is a digest, so any source
+/// id makes a safe file name.
+fn state_path(config: &Config, source_id: &str) -> PathBuf {
+ let digest = Sha256::digest(source_id.as_bytes());
+ let name: String = digest[..8].iter().map(|b| format!("{b:02x}")).collect();
+ config
+ .workspace_dir
+ .join(STATE_DIR)
+ .join(format!("{name}.json"))
+}
+
+/// The record at `path`, or an empty one when there is none or it cannot be
+/// read: a full pass costs lookups, never wrong data.
+fn load_state(path: &Path) -> SyncState {
+ match std::fs::read(path) {
+ Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|error| {
+ tracing::warn!(
+ path = %path.display(),
+ "[memory_sources:hosted_sync] sync record unreadable; doing a full pass: {error}"
+ );
+ SyncState::default()
+ }),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => SyncState::default(),
+ Err(error) => {
+ tracing::warn!(
+ path = %path.display(),
+ "[memory_sources:hosted_sync] sync record unreadable; doing a full pass: {error}"
+ );
+ SyncState::default()
+ }
+ }
+}
+
+/// Saves the record, replacing the old one whole. A failure is logged and not
+/// fatal: the next run re-sends what this one could not record, and the sink
+/// skips it.
+fn save_state(path: &Path, state: &SyncState) {
+ let write = || -> std::io::Result<()> {
+ if let Some(dir) = path.parent() {
+ std::fs::create_dir_all(dir)?;
+ }
+ let tmp = path.with_extension("json.tmp");
+ std::fs::write(&tmp, serde_json::to_vec(state)?)?;
+ std::fs::rename(&tmp, path)
+ };
+ if let Err(error) = write() {
+ tracing::warn!(
+ path = %path.display(),
+ "[memory_sources:hosted_sync] could not save the sync record: {error}"
+ );
+ }
+}
+
+/// Forgets what was recorded for `source_id`, so its next sync is a full pass.
+/// Called when the source's memory is deleted or the source is removed.
+pub(crate) fn forget_state(config: &Config, source_id: &str) {
+ let path = state_path(config, source_id);
+ match std::fs::remove_file(&path) {
+ Ok(()) => tracing::debug!(
+ path = %path.display(),
+ "[memory_sources:hosted_sync] sync record cleared"
+ ),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
+ Err(error) => tracing::warn!(
+ path = %path.display(),
+ "[memory_sources:hosted_sync] could not clear the sync record: {error}"
+ ),
+ }
+}
+
+/// The lock one source's runs take, so a manual sync and a scheduled one do
+/// not read and send the same items at once.
+fn source_lock(source_id: &str) -> Arc<tokio::sync::Mutex<()>> {
+ static LOCKS: OnceLock<Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>> = OnceLock::new();
+ LOCKS
+ .get_or_init(Default::default)
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .entry(source_id.to_string())
+ .or_default()
+ .clone()
+}
+
+fn digest_of(title: &str, content: &SourceContent, url: Option<&str>) -> String {
+ let mut hasher = Sha256::new();
+ for part in [title, &content.body, url.unwrap_or_default()] {
+ hasher.update((part.len() as u64).to_le_bytes());
+ hasher.update(part.as_bytes());
+ }
+ hasher.finalize()[..16]
+ .iter()
+ .map(|b| format!("{b:02x}"))
+ .collect()
+}
+
+/// A run's batch in flight, and what it has done so far.
+struct Progress {
+ path: PathBuf,
+ state: SyncState,
+ batch: Vec<SinkItem>,
+ seen: Vec<(String, Seen)>,
+ outcome: SyncRunOutcome,
+}
+
+impl Progress {
+ /// Sends the batch and, once the sink has taken it, records what it held.
+ async fn flush(
+ &mut self,
+ entry: &MemorySourceEntry,
+ sink: &dyn MemorySourceSink,
+ ) -> Result<(), MemoryError> {
+ if self.batch.is_empty() {
+ return Ok(());
+ }
+ let written = send(entry, sink, std::mem::take(&mut self.batch)).await?;
+ self.outcome.records_ingested += written;
+ for (id, seen) in self.seen.drain(..) {
+ self.state.items.insert(id, seen);
+ }
+ save_state(&self.path, &self.state);
+ Ok(())
+ }
+}
+
/// Syncs `entry` into `sink` once.
///
/// # Errors
///
/// [`MemoryError::Unsupported`] for a kind the host does not sync;
/// [`MemoryError::Backend`] when the source cannot be listed; the sink's own
-/// error when a batch is refused. An item that cannot be read is skipped and
-/// counted in the outcome's note.
-pub(crate) async fn run(
+/// error when a batch is refused, with what earlier batches wrote. An item
+/// that cannot be read is skipped and counted in the outcome's note.
+pub(in crate::memory::sources) async fn run(
config: &Config,
entry: &MemorySourceEntry,
sink: &dyn MemorySourceSink,
-) -> Result<SyncRunOutcome, MemoryError> {
+) -> Result<SyncRunOutcome, PartialFailure> {
let Some(reader) = reader(&entry.kind) else {
return Err(MemoryError::unsupported_raw(format!(
"host sync of {} sources",
entry.kind.as_str()
- )));
+ ))
+ .into());
};
+ let lock = source_lock(&entry.id);
+ let _running = lock.lock().await;
let listed = reader
.list_items(entry, &config.workspace_dir)
.await
.map_err(|error| MemoryError::Backend(format!("listing source '{}': {error}", entry.id)))?;
+ let listed_ids: HashSet<String> = listed.iter().map(|item| item.id.clone()).collect();
let total = listed.len();
let items = chosen(entry, listed, chrono::Utc::now().timestamp_millis());
+ let path = state_path(config, &entry.id);
+ let mut state = load_state(&path);
+ // An item the source no longer lists has nothing left to compare.
+ state.items.retain(|id, _| listed_ids.contains(id));
tracing::debug!(
source_id = %entry.id,
kind = entry.kind.as_str(),
listed = total,
- chosen = items.len(),
+ considered = items.len(),
+ recorded = state.items.len(),
"[memory_sources:hosted_sync] run starting"
);
let budget = entry
.max_tokens_per_sync
.map(|tokens| tokens.saturating_mul(CHARS_PER_TOKEN));
+ let cap = entry.max_items.map(|cap| cap as usize);
let mut spent: u64 = 0;
+ let mut queued = 0usize;
let mut unreadable = 0usize;
+ let mut unchanged = 0usize;
let mut more_pending = false;
- let mut batch: Vec<SinkItem> = Vec::with_capacity(BATCH);
- let mut outcome = SyncRunOutcome::default();
+ let mut progress = Progress {
+ path,
+ state,
+ batch: Vec::with_capacity(BATCH),
+ seen: Vec::with_capacity(BATCH),
+ outcome: SyncRunOutcome::default(),
+ };
for item in items {
+ let held = progress.state.items.get(&item.id);
+ if item.updated_at_ms.is_some() && held.is_some_and(|held| held.at == item.updated_at_ms) {
+ unchanged += 1;
+ continue;
+ }
+ if cap.is_some_and(|cap| queued >= cap) {
+ more_pending = true;
+ break;
+ }
let content = match reader
.read_item(entry, &item.id, &config.workspace_dir)
.await
@@ -158,7 +342,30 @@ pub(crate) async fn run(
continue;
}
};
- if content.body.trim().is_empty() {
+ let title = if content.title.is_empty() {
+ item.title.clone()
+ } else {
+ content.title.clone()
+ };
+ let url = content
+ .metadata
+ .get("url")
+ .and_then(serde_json::Value::as_str)
+ .map(str::to_string);
+ let seen = Seen {
+ at: item.updated_at_ms,
+ digest: digest_of(&title, &content, url.as_deref()),
+ };
+ let same_text = progress
+ .state
+ .items
+ .get(&item.id)
+ .is_some_and(|held| held.digest == seen.digest);
+ if same_text || content.body.trim().is_empty() {
+ // Nothing to send. Recording it now lets the next run skip it
+ // without reading it, by its modified time.
+ unchanged += 1;
+ progress.state.items.insert(item.id, seen);
continue;
}
let size = content.body.len() as u64;
@@ -167,30 +374,29 @@ pub(crate) async fn run(
break;
}
spent += size;
- batch.push(SinkItem {
- item_id: item.id,
- title: if content.title.is_empty() {
- item.title
- } else {
- content.title
- },
+ queued += 1;
+ progress.batch.push(SinkItem {
+ item_id: item.id.clone(),
+ title,
content: content.body,
mime: Some(mime_of(&content.content_type).to_string()),
- url: content
- .metadata
- .get("url")
- .and_then(serde_json::Value::as_str)
- .map(str::to_string),
+ url,
updated_at_ms: item.updated_at_ms,
tags: Vec::new(),
});
- if batch.len() == BATCH {
- outcome.records_ingested += send(entry, sink, std::mem::take(&mut batch)).await?;
+ progress.seen.push((item.id, seen));
+ if progress.batch.len() == BATCH {
+ if let Err(error) = progress.flush(entry, sink).await {
+ return Err(failed(progress, error, more_pending));
+ }
}
}
- if !batch.is_empty() {
- outcome.records_ingested += send(entry, sink, batch).await?;
+ if let Err(error) = progress.flush(entry, sink).await {
+ return Err(failed(progress, error, more_pending));
}
+ // What was read and found unchanged is recorded even when nothing was sent.
+ save_state(&progress.path, &progress.state);
+ let mut outcome = progress.outcome;
outcome.more_pending = more_pending;
if unreadable > 0 {
outcome.note = Some(format!("{unreadable} item(s) could not be read"));
@@ -198,6 +404,7 @@ pub(crate) async fn run(
tracing::debug!(
source_id = %entry.id,
written = outcome.records_ingested,
+ unchanged,
unreadable,
more_pending,
"[memory_sources:hosted_sync] run finished"
@@ -205,6 +412,15 @@ pub(crate) async fn run(
Ok(outcome)
}
+/// A refused batch, with what the run had done before it. The batch that was
+/// refused is not recorded, so the next run sends it again.
+fn failed(progress: Progress, error: MemoryError, more_pending: bool) -> PartialFailure {
+ save_state(&progress.path, &progress.state);
+ let mut done = progress.outcome;
+ done.more_pending = more_pending;
+ PartialFailure { error, done }
+}
+
/// One batch into the sink; answers how many items it wrote.
async fn send(
entry: &MemorySourceEntry,
diff --git a/crates/openhuman-core/src/memory/sources/hosted_sync_tests.rs b/crates/openhuman-core/src/memory/sources/hosted_sync_tests.rs
index 365673c2ec..6061b57128 100644
--- a/crates/openhuman-core/src/memory/sources/hosted_sync_tests.rs
+++ b/crates/openhuman-core/src/memory/sources/hosted_sync_tests.rs
@@ -1,7 +1,10 @@
//! The host's sync of local sources into a driver's sink: which items a run
-//! reads, what it sends, and the budgets it keeps.
+//! reads, what it sends, the budgets it keeps, and how the next run carries on
+//! from what the sink accepted.
+use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
+use std::time::{Duration, SystemTime};
use async_trait::async_trait;
@@ -11,13 +14,23 @@ use crate::memory::api::provider::types::IngestOutcome;
/// One `accept_source_items` call: source id, source kind, items, taint.
type Batch = (String, String, Vec<SinkItem>, MemoryTaint);
-/// A sink that records every batch and writes each item it is handed.
+/// A sink that records every batch and writes each item it is handed, or
+/// refuses the call numbered `refuse_call` (1-based).
#[derive(Default)]
struct RecordingSink {
batches: Mutex<Vec<Batch>>,
+ calls: AtomicUsize,
+ refuse_call: Option<usize>,
}
impl RecordingSink {
+ fn refusing(call: usize) -> Self {
+ Self {
+ refuse_call: Some(call),
+ ..Self::default()
+ }
+ }
+
fn items(&self) -> Vec<SinkItem> {
self.batches
.lock()
@@ -26,6 +39,12 @@ impl RecordingSink {
.flat_map(|(_, _, items, _)| items.clone())
.collect()
}
+
+ fn item_ids(&self) -> Vec<String> {
+ let mut ids: Vec<String> = self.items().into_iter().map(|item| item.item_id).collect();
+ ids.sort();
+ ids
+ }
}
#[async_trait]
@@ -37,6 +56,10 @@ impl MemorySourceSink for RecordingSink {
items: Vec<SinkItem>,
taint: MemoryTaint,
) -> Result<IngestOutcome, MemoryError> {
+ let call = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
+ if self.refuse_call == Some(call) {
+ return Err(MemoryError::Unavailable("memory API unavailable".into()));
+ }
let written = items.len() as u32;
self.batches.lock().expect("batches").push((
source_id.to_string(),
@@ -81,6 +104,33 @@ fn config(dir: &std::path::Path) -> Config {
}
}
+/// A folder of `names`, each file `size` characters long, with distinct
+/// modified times so the newest-first order is fixed: the first name is the
+/// oldest.
+fn folder_of(dir: &std::path::Path, names: &[&str], size: usize) -> std::path::PathBuf {
+ let folder = dir.join("notes");
+ std::fs::create_dir_all(&folder).expect("folder");
+ let base = SystemTime::now() - Duration::from_secs(3_600);
+ for (i, name) in names.iter().enumerate() {
+ write_at(
+ &folder.join(format!("{name}.md")),
+ &format!("{name}{}", "x".repeat(size.saturating_sub(name.len()))),
+ base + Duration::from_secs(i as u64 * 60),
+ );
+ }
+ folder
+}
+
+fn write_at(path: &std::path::Path, text: &str, modified: SystemTime) {
+ std::fs::write(path, text).expect("write");
+ std::fs::File::options()
+ .write(true)
+ .open(path)
+ .expect("open")
+ .set_modified(modified)
+ .expect("set the modified time");
+}
+
#[test]
fn the_host_syncs_local_kinds_only() {
for kind in [
@@ -103,7 +153,7 @@ fn the_host_syncs_local_kinds_only() {
}
#[test]
-fn a_run_reads_the_newest_items_within_its_depth_and_cap() {
+fn a_run_considers_the_newest_items_within_its_depth() {
let day = 86_400_000;
let now = 100 * day;
let mut entry = folder_entry(std::path::Path::new("."));
@@ -126,8 +176,6 @@ fn a_run_reads_the_newest_items_within_its_depth_and_cap() {
["new", "mid", "undated"],
"an item with no date is kept"
);
- entry.max_items = Some(1);
- assert_eq!(ids(chosen(&entry, items(), now)), ["new"]);
}
#[tokio::test]
@@ -154,24 +202,135 @@ async fn a_folder_is_read_and_sent_to_the_sink() {
assert_eq!(items[0].mime.as_deref(), Some("text/markdown"));
}
+/// What the sink accepted is not sent again; a changed file is.
#[tokio::test]
-async fn a_token_budget_stops_the_run_with_more_pending() {
+async fn only_new_or_changed_items_are_sent_again() {
let dir = tempfile::tempdir().expect("tempdir");
- let folder = dir.path().join("notes");
- std::fs::create_dir_all(&folder).expect("folder");
- for name in ["a", "b", "c"] {
- std::fs::write(folder.join(format!("{name}.md")), "x".repeat(400)).expect("file");
- }
- let mut entry = folder_entry(&folder);
- entry.max_tokens_per_sync = Some(150);
+ let folder = folder_of(dir.path(), &["a", "b"], 40);
+ let entry = folder_entry(&folder);
+ let config = config(dir.path());
let sink = RecordingSink::default();
- let outcome = run(&config(dir.path()), &entry, &sink).await.expect("run");
- assert_eq!(
- sink.items().len(),
- 1,
- "600 characters fit one 400-character file"
+ run(&config, &entry, &sink).await.expect("first");
+ assert_eq!(sink.item_ids(), ["a.md", "b.md"]);
+
+ let again = RecordingSink::default();
+ let outcome = run(&config, &entry, &again).await.expect("unchanged");
+ assert!(
+ again.items().is_empty(),
+ "an unchanged folder sends nothing"
);
+ assert_eq!(outcome.records_ingested, 0);
+
+ write_at(&folder.join("b.md"), "b, rewritten", SystemTime::now());
+ let changed = RecordingSink::default();
+ run(&config, &entry, &changed).await.expect("changed");
+ assert_eq!(changed.item_ids(), ["b.md"]);
+}
+
+/// A run stopped by its budget is picked up where it stopped, not restarted
+/// from the newest items, so a source larger than its budget still syncs.
+#[tokio::test]
+async fn a_budget_limited_sync_carries_on_across_runs() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let folder = folder_of(dir.path(), &["a", "b", "c"], 400);
+ let mut entry = folder_entry(&folder);
+ // 600 characters: one 400-character file a run.
+ entry.max_tokens_per_sync = Some(150);
+ let config = config(dir.path());
+ let mut sent = Vec::new();
+ for _ in 0..3 {
+ let sink = RecordingSink::default();
+ let outcome = run(&config, &entry, &sink).await.expect("run");
+ assert_eq!(sink.items().len(), 1);
+ sent.extend(sink.item_ids());
+ if sent.len() < 3 {
+ assert!(outcome.more_pending);
+ }
+ }
+ assert_eq!(sent, ["c.md", "b.md", "a.md"], "newest first, each once");
+ let last = RecordingSink::default();
+ let outcome = run(&config, &entry, &last).await.expect("done");
+ assert!(last.items().is_empty());
+ assert!(!outcome.more_pending);
+}
+
+/// `max_items` caps what one run sends, and the next run continues.
+#[tokio::test]
+async fn max_items_caps_each_run_and_the_next_one_continues() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let folder = folder_of(dir.path(), &["a", "b", "c"], 20);
+ let mut entry = folder_entry(&folder);
+ entry.max_items = Some(2);
+ let config = config(dir.path());
+ let first = RecordingSink::default();
+ let outcome = run(&config, &entry, &first).await.expect("first");
+ assert_eq!(first.item_ids(), ["b.md", "c.md"]);
assert!(outcome.more_pending);
+ let second = RecordingSink::default();
+ run(&config, &entry, &second).await.expect("second");
+ assert_eq!(second.item_ids(), ["a.md"]);
+}
+
+/// A refused batch fails the run, keeps what earlier batches wrote, and is
+/// sent again next time; the earlier batches are not.
+#[tokio::test]
+async fn a_refused_batch_keeps_earlier_progress_and_is_retried() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let names: Vec<String> = (0..30).map(|i| format!("n{i:02}")).collect();
+ let names: Vec<&str> = names.iter().map(String::as_str).collect();
+ let folder = folder_of(dir.path(), &names, 20);
+ let entry = folder_entry(&folder);
+ let config = config(dir.path());
+
+ let refusing = RecordingSink::refusing(2);
+ let failure = run(&config, &entry, &refusing)
+ .await
+ .expect_err("the second batch is refused");
+ assert!(
+ matches!(failure.error, MemoryError::Unavailable(_)),
+ "{failure:?}"
+ );
+ assert_eq!(failure.done.records_ingested, BATCH as u32);
+ assert_eq!(refusing.items().len(), BATCH);
+
+ let retry = RecordingSink::default();
+ let outcome = run(&config, &entry, &retry).await.expect("retry");
+ assert_eq!(retry.items().len(), 30 - BATCH, "only the refused batch");
+ assert_eq!(outcome.records_ingested, (30 - BATCH) as u32);
+}
+
+/// Deleting a source's memory clears the record, so the next sync sends
+/// everything again rather than trusting what was forgotten.
+#[tokio::test]
+async fn a_cleared_record_means_a_full_pass() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let folder = folder_of(dir.path(), &["a", "b"], 20);
+ let entry = folder_entry(&folder);
+ let config = config(dir.path());
+ run(&config, &entry, &RecordingSink::default())
+ .await
+ .expect("first");
+ forget_state(&config, &entry.id);
+ let again = RecordingSink::default();
+ run(&config, &entry, &again).await.expect("after clearing");
+ assert_eq!(again.item_ids(), ["a.md", "b.md"]);
+ // Clearing a record that is not there is a no-op.
+ forget_state(&config, "never-synced");
+}
+
+/// A record that cannot be read is a full pass, never a failure.
+#[tokio::test]
+async fn an_unreadable_record_is_a_full_pass() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let folder = folder_of(dir.path(), &["a"], 20);
+ let entry = folder_entry(&folder);
+ let config = config(dir.path());
+ let path = state_path(&config, &entry.id);
+ std::fs::create_dir_all(path.parent().expect("parent")).expect("dir");
+ std::fs::write(&path, b"not json").expect("garbage");
+ let sink = RecordingSink::default();
+ run(&config, &entry, &sink).await.expect("run");
+ assert_eq!(sink.item_ids(), ["a.md"]);
}
#[tokio::test]
@@ -183,16 +342,20 @@ async fn a_missing_folder_or_unserved_kind_fails_the_run() {
&folder_entry(&dir.path().join("absent")),
&sink,
)
- .await;
+ .await
+ .expect_err("a missing folder");
assert!(
- matches!(missing, Err(MemoryError::Backend(_))),
+ matches!(missing.error, MemoryError::Backend(_)),
"{missing:?}"
);
+ assert_eq!(missing.done, SyncRunOutcome::default());
let mut chats = folder_entry(dir.path());
chats.kind = SourceKind::Conversation;
- let refused = run(&config(dir.path()), &chats, &sink).await;
+ let refused = run(&config(dir.path()), &chats, &sink)
+ .await
+ .expect_err("an unserved kind");
assert!(
- matches!(refused, Err(MemoryError::Unsupported { .. })),
+ matches!(refused.error, MemoryError::Unsupported { .. }),
"{refused:?}"
);
assert!(sink.items().is_empty());
diff --git a/crates/openhuman-core/src/memory/sources/rpc/registry_crud.rs b/crates/openhuman-core/src/memory/sources/rpc/registry_crud.rs
index b831c8702a..dddb657eb7 100644
--- a/crates/openhuman-core/src/memory/sources/rpc/registry_crud.rs
+++ b/crates/openhuman-core/src/memory/sources/rpc/registry_crud.rs
@@ -231,6 +231,12 @@ pub struct RemoveResponse {
pub async fn remove_rpc(req: RemoveRequest) -> Result<Outcome<RemoveResponse>, String> {
tracing::info!(id = %req.id, "[memory_sources] remove_rpc: entry");
let removed = registry::remove_source(&req.id).await?;
+ if removed {
+ // A removed source is never synced again, so the host's record of
+ // what it sent goes with it. Its memory stays, as on the local engine.
+ let config = config_rpc::load_config_with_timeout().await?;
+ crate::memory::sources::hosted_sync::forget_state(&config, &req.id);
+ }
Ok(Outcome::new(RemoveResponse { removed }, vec![]))
}
diff --git a/gitbooks/developing/engines.md b/gitbooks/developing/engines.md
index 7cf3fc3dcf..747bf4ef6e 100644
--- a/gitbooks/developing/engines.md
+++ b/gitbooks/developing/engines.md
@@ -143,8 +143,11 @@ chunk store (reset, rebuild, vault, pipeline status) need `chunks`. Each shows
runs no source pipeline of its own, so the host syncs local folder, GitHub, RSS
and web-page sources itself: it reads them and sends the items through the
engine's sink, from the Sync button, Apply all, and a daily schedule
-(`memory/sources/hosted_sync.rs`, `hosted_periodic.rs`). A file removed from a
-synced folder stays in memory until the source is removed.
+(`memory/sources/hosted_sync.rs`, `hosted_periodic.rs`). The host records what
+the sink accepted, so a run sends only new or changed items and one stopped by
+its budget carries on where it stopped. A file removed from a synced folder
+stays in memory, and removing the source keeps what it synced, as on the local
+engine; deleting the source's memory forgets all of it.
Hosted CortexDB ranks its recall without scoring it: a hit carries its rank and
no signal (no similarity, keyword, graph, episodic or freshness), with or