Skip to content

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

feat(memory): add import retry and recovery handling

Steven Enamakel6c605d442522
diff --git a/crates/openhuman-core/src/memory/import.rs b/crates/openhuman-core/src/memory/import.rs
index 51578ef1b6..b373180483 100644
--- a/crates/openhuman-core/src/memory/import.rs
+++ b/crates/openhuman-core/src/memory/import.rs
@@ -1,253 +1,99 @@
//! Importing a v1 memory store into the selected engine.
//!
-//! [`scan`] opens `<workspace>/memory/memory.db` read-only through
-//! `tinymemory-import` and counts what it would import. [`start`] refuses to
-//! run without explicit consent (importing uploads local data to the engine),
-//! then runs in the background: a blocking reader walks the legacy store and
-//! hands each item to the async side, which scrubs and stores it and advances
-//! the resumable [`Checkpoint`]. Progress and the checkpoint persist in
-//! `<workspace>/memory/import_state.json`, so a restarted import resumes where
-//! the last one stopped (an item stored but not yet checkpointed is re-sent,
-//! and the engine treats it as a replay). A batch the engine cannot take for
-//! a transient reason (unreachable, overloaded, its indexer behind) is retried
-//! with backoff; if the engine stays unavailable the run stops and, like an
-//! import the app quit in the middle of, resumes on its own
-//! ([`resume_interrupted`]). One stopped by a failure that is not about a
-//! single item and will not pass by itself (credits exhausted, signed out)
-//! waits for the user to start it again.
+//! The driver (batching, checkpoints, backoff, failed-item list, retry) is
+//! `tinymemory_integrations::import::Importer`. This file is the host
+//! adapter around it: the consent gate, the one-run-per-workspace registry,
+//! the atomic state file `<workspace>/memory/import_state.json`, the tokio
+//! clock, the scheduler pause, the credits resume policy, and what follows a
+//! finished import (organizing the tree).
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex};
+use std::time::Duration;
-use serde::{Deserialize, Serialize};
-use tinymemory_api::{WaitFor, WriteOptions};
-use tinymemory_integrations::cortex::is_insufficient_credits;
-use tinymemory_integrations::import::{Checkpoint, ImportedItem};
+use tinymemory_integrations::import::{
+ Begun, CheckpointStore, ImportError, ImportFile, Importer, Pacer,
+};
use crate::config::Config;
use crate::security::secret_storage::file_store::write_atomic;
-use super::engine::{self, BoundEngine};
+use super::engine;
use super::error::{MemoryError, MemoryResult};
use super::types::{ImportCounts, ImportPhase, ImportScanView, ImportState};
-use open::open_legacy;
-
-/// Items stored between two checkpoint writes.
-const CHECKPOINT_EVERY: u64 = 25;
-
-/// Items per bulk store (`MemoryEngine::store_many`).
-const STORE_BATCH: usize = 25;
-
-/// How long to wait before each retry of a batch the engine could not take
-/// for a transient reason (unreachable, overloaded, indexer behind: an
-/// `Unavailable` error). After the last, the run stops and is resumed by the
-/// background job.
-#[cfg(not(test))]
-const RETRY_DELAYS: [std::time::Duration; 3] = [
- std::time::Duration::from_secs(2),
- std::time::Duration::from_secs(10),
- std::time::Duration::from_secs(30),
-];
-#[cfg(test)]
-const RETRY_DELAYS: [std::time::Duration; 3] = [std::time::Duration::from_millis(1); 3];
-
-/// The reason a run stopped on an engine that stayed unavailable through
-/// every retry; it is resumed on its own.
-const UNAVAILABLE_REASON: &str =
- "the memory service is unavailable; the import resumes on its own within a few minutes";
-
-/// What storing one batch of legacy items did.
-#[derive(Debug, Default)]
-struct BatchOutcome {
- /// Items stored (or replayed).
- stored: u64,
- /// The checkpoint after the last item handled, stored or skipped.
- checkpoint: Option<Checkpoint>,
- /// Why the import must stop (credential rejected, credits exhausted,
- /// engine unreachable).
- fatal: Option<String>,
- /// Whether `fatal` is transient: the engine stayed unavailable through
- /// every retry, so the background job resumes the run.
- transient: bool,
- /// Whether `fatal` is the account's credits running out: the run is
- /// paused until automatic runs are allowed again ([`BillingCheck`]).
- credits: bool,
- /// Items the engine refused, skipped so the rest could go on.
- failed: Vec<FailedItem>,
-}
-/// One legacy item the engine refused, kept with the reason so a user can
-/// see it and retry it.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-struct FailedItem {
- /// The item's legacy id (`memory_docs:<id>`, `episodic_log:<session>`, …).
- id: String,
- /// Why the engine refused it.
- reason: String,
-}
+/// Whether background work is paused right now. An automatic resume asks
+/// before it starts and again before every batch it stores.
+pub(crate) type PauseCheck = Arc<dyn Fn() -> bool + Send + Sync>;
-impl FailedItem {
- fn new(item: &tinymemory_api::StoreItem, error: tinymemory_api::Error) -> Self {
- Self {
- id: legacy_id(item),
- reason: MemoryError::from(error).to_string(),
- }
- }
-}
+/// Whether memory work that uploads on its own, with no user action (an
+/// automatic import, or resuming one paused for credits), may run now.
+pub(crate) type BillingCheck = Arc<dyn Fn(&Config) -> bool + Send + Sync>;
+
+/// Imports running now, per workspace.
+static RUNNING: LazyLock<Mutex<HashSet<PathBuf>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
+
+/// Held while an import or a layout migration decides to start: each checks
+/// the other is not going, then registers itself, under this one lock, so
+/// neither can slip in between the other's check and its registration.
+pub(crate) static START_GATE: Mutex<()> = Mutex::new(());
-/// The legacy id the importer gave `item` (its `source.id`).
-fn legacy_id(item: &tinymemory_api::StoreItem) -> String {
- item.meta().source.id.clone().unwrap_or_default()
+fn running(workspace_dir: &Path) -> bool {
+ RUNNING
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .contains(workspace_dir)
}
-/// Runs `call` again after each of [`RETRY_DELAYS`] while it fails with a
-/// transient error, and returns its last result.
-async fn with_retries<T, F, Fut>(mut call: F) -> tinymemory_api::Result<T>
-where
- F: FnMut() -> Fut,
- Fut: std::future::Future<Output = tinymemory_api::Result<T>>,
-{
- let mut result = call().await;
- for delay in RETRY_DELAYS {
- match &result {
- Err(error) if error.is_transient() => {
- tracing::debug!(
- delay_ms = u64::try_from(delay.as_millis()).unwrap_or(u64::MAX),
- %error,
- "[memory:import] engine unavailable; retrying"
- );
- tokio::time::sleep(delay).await;
- result = call().await;
- }
- _ => break,
- }
- }
- result
+fn release(workspace_dir: &Path) {
+ RUNNING
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .remove(workspace_dir);
}
-/// Whether a store failure is about the item (skip it and go on) rather than
-/// the engine or the account (stop, so a resume retries from here).
-///
-/// Only a refusal of the item itself is skippable: malformed or too large
-/// (`InvalidRequest`), not storable here (`Unsupported`, `NotFound`), or a
-/// replay key already bound to a different body (`Conflict`). Everything else
-/// would fail the next item the same way: a rejected credential, an exhausted
-/// credit balance (an `Engine` error), an unreachable or overloaded engine
-/// (`Unavailable`). Skipping those would advance the checkpoint past items
-/// that were never stored and finish `Done` with nothing imported.
-pub(super) fn skips_item(error: &tinymemory_api::Error) -> bool {
- use tinymemory_api::Error as E;
- matches!(
- error,
- E::InvalidRequest(_) | E::Unsupported(_) | E::NotFound(_) | E::Conflict(_)
- )
+/// The state file, written atomically (staged, synced, renamed): a crash
+/// mid-write leaves the previous state, never a torn file that reads back as
+/// a fresh start and re-sends everything.
+pub(crate) struct FileCheckpointStore {
+ path: PathBuf,
}
-/// The message an import stopped by `error` reports.
-fn fatal_message(error: tinymemory_api::Error) -> String {
- if error.is_transient() {
- return UNAVAILABLE_REASON.to_string();
- }
- if is_insufficient_credits(&error) {
- return "not enough credits to import your memory; top up, then resume the import to \
- continue where it stopped"
- .to_string();
+impl FileCheckpointStore {
+ pub(crate) fn new(workspace_dir: &Path) -> Self {
+ Self {
+ path: workspace_dir.join("memory").join("import_state.json"),
+ }
}
- MemoryError::from(error).to_string()
}
-/// Stores `batch` in one bulk call. If the engine refuses the batch because
-/// of an item (see [`skips_item`]), the items are stored one at a time instead
-/// so only the bad ones are skipped. Any other failure stops the import
-/// without advancing the checkpoint past what was stored.
-async fn store_batch(bound: &BoundEngine, batch: Vec<ImportedItem>, wait: WaitFor) -> BatchOutcome {
- let Some(last) = batch.last() else {
- return BatchOutcome::default();
- };
- let last_checkpoint = last.checkpoint.clone();
- let items: Vec<_> = batch.iter().map(|imported| imported.item.clone()).collect();
- let options = WriteOptions { wait };
- match with_retries(|| bound.engine.store_many_with(items.clone(), options)).await {
- Ok(receipts) => {
- tracing::debug!(
- engine = %bound.id,
- count = receipts.len(),
- "[memory:import] batch stored"
- );
- return BatchOutcome {
- stored: receipts.len() as u64,
- checkpoint: Some(last_checkpoint),
- ..BatchOutcome::default()
- };
- }
- Err(error) if !skips_item(&error) => {
- return BatchOutcome {
- transient: error.is_transient(),
- credits: is_insufficient_credits(&error),
- fatal: Some(fatal_message(error)),
- ..BatchOutcome::default()
- };
- }
- Err(error) => {
- tracing::debug!(
- code = MemoryError::from(error).code(),
- "[memory:import] batch refused; storing one by one"
- );
- }
+impl CheckpointStore for FileCheckpointStore {
+ fn load(&self) -> ImportFile {
+ std::fs::read_to_string(&self.path)
+ .ok()
+ .and_then(|text| serde_json::from_str(&text).ok())
+ .unwrap_or_default()
}
- let mut outcome = BatchOutcome::default();
- for imported in batch {
- match with_retries(|| bound.engine.store(imported.item.clone())).await {
- Ok(_) => outcome.stored += 1,
- Err(error) if !skips_item(&error) => {
- outcome.transient = error.is_transient();
- outcome.credits = is_insufficient_credits(&error);
- outcome.fatal = Some(fatal_message(error));
- return outcome;
- }
- Err(error) => {
- tracing::debug!(
- code = MemoryError::from(error.clone()).code(),
- "[memory:import] item skipped"
- );
- outcome.failed.push(FailedItem::new(&imported.item, error));
- }
- }
- outcome.checkpoint = Some(imported.checkpoint);
+
+ fn save(&self, file: &ImportFile) -> Result<(), String> {
+ let json = serde_json::to_vec_pretty(file).map_err(|error| error.to_string())?;
+ write_atomic(&self.path, &json).map_err(|error| error.to_string())
}
- outcome
}
-/// Imports running now, per workspace.
-static RUNNING: LazyLock<Mutex<HashSet<PathBuf>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
+/// Backoff sleeps on the tokio clock.
+struct TokioPacer;
-/// Held while an import or a layout migration decides to start: each checks
-/// the other is not going, then registers itself, under this one lock, so
-/// neither can slip in between the other's check and its registration.
-pub(crate) static START_GATE: Mutex<()> = Mutex::new(());
+#[async_trait::async_trait]
+impl Pacer for TokioPacer {
+ async fn sleep(&self, delay: Duration) {
+ tokio::time::sleep(delay).await;
+ }
+}
-#[derive(Debug, Default, Serialize, Deserialize)]
-struct ImportFile {
- #[serde(default)]
- state: ImportState,
- /// The run stopped because the account ran out of credits; the
- /// background job resumes it once automatic runs are allowed.
- #[serde(default, skip_serializing_if = "std::ops::Not::not")]
- paused_for_credits: bool,
- /// Items the engine refused, for `retry_failed`.
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
- failed: Vec<FailedItem>,
- /// The `Running` run is a retry of `failed`, not the import itself: an
- /// interrupted one resumes as a retry.
- #[serde(default, skip_serializing_if = "std::ops::Not::not")]
- retrying: bool,
- #[serde(default)]
- checkpoint: Checkpoint,
- /// The import ended with its last batch not confirmed listed (the final
- /// wait gave up); see [`listed_unconfirmed`].
- #[serde(default, skip_serializing_if = "std::ops::Not::not")]
- listed_unconfirmed: bool,
+fn read_file(workspace_dir: &Path) -> ImportFile {
+ FileCheckpointStore::new(workspace_dir).load()
}
/// Whether the last import ended with its last batch not confirmed listed:
@@ -257,53 +103,38 @@ pub(crate) fn listed_unconfirmed(workspace_dir: &Path) -> bool {
read_file(workspace_dir).listed_unconfirmed
}
-fn file_path(workspace_dir: &Path) -> PathBuf {
- workspace_dir.join("memory").join("import_state.json")
+fn import_error(error: &ImportError) -> MemoryError {
+ MemoryError::invalid(error.to_string())
}
-fn read_file(workspace_dir: &Path) -> ImportFile {
- std::fs::read_to_string(file_path(workspace_dir))
- .ok()
- .and_then(|text| serde_json::from_str(&text).ok())
- .unwrap_or_default()
-}
-
-/// Persists `file` atomically (staged, synced, renamed): a crash mid-write
-/// leaves the previous state, never a torn file that reads back as a fresh
-/// start and re-sends everything.
-fn write_file(workspace_dir: &Path, file: &ImportFile) {
- let result = serde_json::to_vec_pretty(file)
- .map_err(|error| error.to_string())
- .and_then(|json| {
- write_atomic(&file_path(workspace_dir), &json).map_err(|error| error.to_string())
- });
- if let Err(error) = result {
- tracing::warn!(error = %error, "[memory:import] writing import state failed");
+fn importer(
+ config: &Config,
+ engine: Arc<dyn tinymemory_api::MemoryEngine>,
+ consent: bool,
+ paused: Option<PauseCheck>,
+) -> Arc<Importer> {
+ let mut importer = Importer::new(
+ config.workspace_dir.clone(),
+ engine,
+ Arc::new(FileCheckpointStore::new(&config.workspace_dir)),
+ Arc::new(TokioPacer),
+ Arc::new(move || consent),
+ )
+ .with_describe(Arc::new(|error| MemoryError::from(error.clone()).to_string()));
+ if let Some(paused) = paused {
+ importer = importer.with_pause(paused);
}
+ Arc::new(importer)
}
/// Counts what a legacy store at `workspace_dir` holds, or `None` when there
-/// is no v1 store there (neither `memory/memory.db` nor a usable
-/// `memory_tree/chunks.db`). Sized by the importer's own counts, one query
-/// per section rather than a pass over every item, and exactly what the
-/// import then yields. Blocking (SQLite, and memory-tree chunk files).
+/// is no v1 store there. Blocking (SQLite, and memory-tree chunk files).
pub fn count_legacy(workspace_dir: &Path) -> Option<ImportCounts> {
- let counts = open_legacy(workspace_dir)
- .and_then(|workspace| workspace.counts())
- .map_err(|error| tracing::debug!(error = %error, "[memory:import] no legacy store"))
- .ok()?;
- // Memory-tree chunk sources count as documents: most are, and a chat
- // one is a conversation the import still stores. The three add up to
- // the total either way.
+ let counts = tinymemory_integrations::import::count_legacy(workspace_dir)?;
Some(ImportCounts {
- documents: counts.documents + counts.chunks,
+ documents: counts.documents,
conversations: counts.conversations,
- learnings: counts.learnings
- + counts.profile
- + counts.events
- + counts.lessons
- + counts.relations
- + counts.files,
+ learnings: counts.learnings,
})
}
@@ -326,23 +157,17 @@ pub async fn scan(config: &Config) -> MemoryResult<ImportScanView> {
pub fn in_progress(config: &Config) -> bool {
// A live import counts from its reservation, before its first state
// write (the scan of the old store comes first).
- let live = RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .contains(&config.workspace_dir);
let file = read_file(&config.workspace_dir);
- live || file.state.phase == ImportPhase::Running || file.paused_for_credits
+ running(&config.workspace_dir)
+ || file.state.phase == ImportPhase::Running
+ || file.paused_for_credits
}
/// `memory_import_status`.
#[must_use]
pub fn status(config: &Config) -> ImportState {
let mut state = read_file(&config.workspace_dir).state;
- let running = RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .contains(&config.workspace_dir);
- if state.phase == ImportPhase::Running && !running {
+ if state.phase == ImportPhase::Running && !running(&config.workspace_dir) {
state.phase = ImportPhase::Error;
state.error = Some(state.error.unwrap_or_else(|| {
"the import was interrupted; it resumes on its own within a few minutes, or resume \
@@ -353,14 +178,6 @@ pub fn status(config: &Config) -> ImportState {
state
}
-/// Whether background work is paused right now. An automatic resume asks
-/// before it starts and again before every batch it stores.
-pub(crate) type PauseCheck = Arc<dyn Fn() -> bool + Send + Sync>;
-
-/// Whether memory work that uploads on its own, with no user action (an
-/// automatic import, or resuming one paused for credits), may run now.
-pub(crate) type BillingCheck = Arc<dyn Fn(&Config) -> bool + Send + Sync>;
-
/// The scheduler's pause, which includes being signed out.
pub(crate) fn scheduler_paused() -> bool {
matches!(
@@ -370,13 +187,11 @@ pub(crate) fn scheduler_paused() -> bool {
}
/// Resumes an import the app quit in the middle of, if there is one, under
-/// the scheduler's pause ([`resume_interrupted_with`]). Called from memory's
-/// background job.
+/// the scheduler's pause. Called from memory's background job.
pub async fn resume_interrupted(config: &Config) -> bool {
// A credits pause resumes on its own only while memory work is free
- // (`billing::free_period_active`: always on a self-hosted engine, the
- // backend's free period on the TinyHuman one). The backend is asked only
- // when such a pause is waiting on it.
+ // (`billing::free_period_active`). The backend is asked only when such a
+ // pause is waiting on it.
let file = read_file(&config.workspace_dir);
let free = file.state.phase == ImportPhase::Error
&& file.paused_for_credits
@@ -393,16 +208,10 @@ pub async fn resume_interrupted(config: &Config) -> bool {
/// paused.
///
/// Only a `Running` state with no live run counts: the user consented when
-/// it started, and quitting the app is not a decision to stop. Nothing
-/// resumes while background work is paused (which includes being signed
-/// out), and a resumed run asks `paused` again before every batch, so a pause
-/// that lands after the check stops it at the next batch. Either way the state
-/// stays `Running` with its checkpoint, so a later tick resumes it. An import
-/// that stopped on an error (credits exhausted, engine unreachable) stays
-/// stopped until the user starts it again, and so does one whose automatic
-/// resume could not start: that failure is persisted as `Error`, so a
-/// failure that would recur does not loop. Returns whether a run was
-/// started.
+/// it started. A paused-for-credits run resumes once `billing` allows. A
+/// resumed run asks `paused` again before every batch. An automatic resume
+/// that cannot start is persisted as stopped, so a failure that would recur
+/// does not loop. Returns whether a run was started.
pub(crate) async fn resume_interrupted_with(
config: &Config,
paused: PauseCheck,
@@ -411,30 +220,21 @@ pub(crate) async fn resume_interrupted_with(
let file = read_file(&config.workspace_dir);
let resumable = match file.state.phase {
ImportPhase::Running => true,
- // Out of credits: only once automatic runs are allowed again.
ImportPhase::Error => file.paused_for_credits && billing(config),
_ => false,
};
- if !resumable {
- return false;
- }
- let live = RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .contains(&config.workspace_dir);
- if live {
+ if !resumable || running(&config.workspace_dir) {
return false;
}
if paused() {
tracing::debug!("[memory:import] background paused; interrupted import left for later");
return false;
}
- // An interrupted retry of refused items resumes as a retry, from the
- // items still listed (each stored one was taken off as it went).
- let resumed = if file.state.phase == ImportPhase::Running && file.retrying {
- retry::begin_retry(config, file, Some(paused))
+ let retrying = file.state.phase == ImportPhase::Running && file.retrying;
+ let resumed = if retrying {
+ launch(config, Mode::ResumeRetry, true, Some(paused)).await
} else {
- start_with(config, true, Some(paused)).await
+ launch(config, Mode::Import, true, Some(paused)).await
};
match resumed {
Ok(state) => {
@@ -450,25 +250,20 @@ pub(crate) async fn resume_interrupted_with(
code = error.code(),
"[memory:import] interrupted import could not resume; stopped"
);
- // Re-read so only the phase and reason change: the progress and
- // the checkpoint stay exactly as persisted, and the user's Resume
- // continues from there.
- let mut file = read_file(&config.workspace_dir);
- if file.retrying {
- // The import itself is finished: keep it `Done` with the
- // items still to retry, so Retry stays available.
- file.state.phase = ImportPhase::Done;
- file.state.error = Some(format!(
- "the retry could not resume: {error}; press Retry again"
- ));
- file.retrying = false;
+ let engine = engine::resolve(config).engine().map(|bound| bound.engine);
+ // Without an engine the importer is only used for its store.
+ if let Ok(engine) = engine {
+ importer(config, engine, true, None).record_resume_failure(&error.to_string());
} else {
+ let store = FileCheckpointStore::new(&config.workspace_dir);
+ let mut file = store.load();
file.state.phase = ImportPhase::Error;
file.state.error = Some(format!("the import could not resume: {error}"));
+ file.paused_for_credits = false;
+ if let Err(error) = store.save(&file) {
+ tracing::warn!(%error, "[memory:import] writing import state failed");
+ }
}
- // Not resumed again on its own: the failure would recur.
- file.paused_for_credits = false;
- write_file(&config.workspace_dir, &file);
false
}
}
@@ -476,20 +271,31 @@ pub(crate) async fn resume_interrupted_with(
/// `memory_import_start`: requires `consent`, memory on, and a legacy store.
pub async fn start(config: &Config, consent: bool) -> MemoryResult<ImportState> {
- start_with(config, consent, None).await
+ launch(config, Mode::Import, consent, None).await
+}
+
+/// `memory_import_retry_failed`: stores again the items a finished import
+/// skipped because the engine refused them.
+pub async fn retry_failed(config: &Config) -> MemoryResult<ImportState> {
+ launch(config, Mode::Retry, true, None).await
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Mode {
+ Import,
+ Retry,
+ ResumeRetry,
}
-/// [`start`], with the pause an automatic resume honors (`None` for an import
-/// the user started, which runs to the end).
-async fn start_with(
+/// Claims the workspace, begins the run on the module's driver and spawns it.
+async fn launch(
config: &Config,
+ mode: Mode,
consent: bool,
paused: Option<PauseCheck>,
) -> MemoryResult<ImportState> {
- if !consent {
- return Err(MemoryError::invalid(
- "importing uploads local memory to the selected engine; pass consent: true",
- ));
+ if mode == Mode::Import && !consent {
+ return Err(import_error(&ImportError::ConsentRequired));
}
let bound = engine::resolve(config).engine()?;
let workspace_dir = config.workspace_dir.clone();
@@ -497,12 +303,14 @@ async fn start_with(
let _gate = START_GATE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
- // Imported items written to the legacy tree while it is being moved
- // would be left behind there.
+ // Items written to the legacy tree while it is being moved would be
+ // left behind there.
if super::layout_migration::service::is_running(config) {
- return Err(MemoryError::invalid(
- "memory is being organized; import once that finishes",
- ));
+ return Err(MemoryError::invalid(if mode == Mode::Import {
+ "memory is being organized; import once that finishes"
+ } else {
+ "memory is being organized; retry once that finishes"
+ }));
}
RUNNING
.lock()
@@ -512,58 +320,46 @@ async fn start_with(
if !claimed {
return Ok(status(config));
}
- let mut file = read_file(&workspace_dir);
- if file.state.phase == ImportPhase::Done {
- file = ImportFile::default();
- }
- // A resumed import already knows its total: only check the store is
- // still there, instead of reading all of it again before the run reads
- // it once more.
- let resuming = !file.checkpoint.is_start() && file.state.total > 0;
- let scan_dir = workspace_dir.clone();
- let total = crate::core::runtime::spawn_blocking_scoped(move || {
- if resuming {
- open_legacy(&scan_dir).ok().map(|_| None)
- } else {
- count_legacy(&scan_dir)
- .map(|counts| Some(counts.documents + counts.conversations + counts.learnings))
+ let driver = importer(config, bound.engine, consent, paused);
+ let begin = {
+ let driver = driver.clone();
+ crate::core::runtime::spawn_blocking_scoped(move || match mode {
+ Mode::Import => driver.begin(),
+ Mode::Retry => driver.begin_retry(),
+ Mode::ResumeRetry => Ok(driver.begin_retry_resume()),
+ })
+ .await
+ };
+ let begun: Begun = match begin {
+ Ok(Ok(begun)) => begun,
+ Ok(Err(error)) => {
+ release(&workspace_dir);
+ return Err(import_error(&error));
+ }
+ Err(error) => {
+ release(&workspace_dir);
+ return Err(MemoryError::Engine(format!("import start failed: {error}")));
}
- })
- .await
- .ok()
- .flatten();
- let Some(total) = total else {
- RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .remove(&workspace_dir);
- return Err(MemoryError::invalid("no v1 memory store to import"));
};
- file.state.phase = ImportPhase::Running;
- file.paused_for_credits = false;
- if let Some(total) = total {
- file.state.total = total;
- }
- file.state.error = None;
- write_file(&workspace_dir, &file);
- let state = file.state.clone();
- tracing::info!(total = state.total, "[memory:import] import started");
+ let state = begun.state.clone();
+ tracing::info!(total = state.total, retry = mode != Mode::Import, "[memory:import] run started");
let config = config.clone();
- tokio::spawn(async move {
- run(&workspace_dir, &bound, file, paused).await;
- RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .remove(&workspace_dir);
+ crate::core::runtime::spawn_scoped(async move {
+ if mode == Mode::Import {
+ driver.run(begun).await;
+ } else {
+ driver.run_retry(begun).await;
+ }
+ release(&workspace_dir);
// Import first, then organize: the move starts here, on whatever
// screen the user is, once the import is done.
- if read_file(&workspace_dir).state.phase == ImportPhase::Done {
+ if mode == Mode::Import && read_file(&workspace_dir).state.phase == ImportPhase::Done {
let started = super::layout_migration::start(
config.clone(),
Arc::new(super::layout_migration::AppHost::new(config)),
// Migration is free: organizing follows a finished import
- // straight away, free period or not. A shared self-hosted
- // tree still waits for the takeover consent.
+ // straight away. A shared self-hosted tree still waits for
+ // the takeover consent.
super::layout_migration::Trigger::Manual { takeover: false },
Arc::new(scheduler_paused),
);
@@ -573,178 +369,6 @@ async fn start_with(
Ok(state)
}
-async fn run(
- workspace_dir: &Path,
- bound: &BoundEngine,
- mut file: ImportFile,
- paused: Option<PauseCheck>,
-) {
- let (tx, mut rx) = tokio::sync::mpsc::channel::<Result<ImportedItem, String>>(16);
- let reader_dir = workspace_dir.to_path_buf();
- let checkpoint = file.checkpoint.clone();
- let reader = tokio::task::spawn_blocking(move || {
- let workspace = match open_legacy(&reader_dir) {
- Ok(workspace) => workspace,
- Err(error) => {
- let _ = tx.blocking_send(Err(error.to_string()));
- return;
- }
- };
- for imported in workspace.items_from(&checkpoint) {
- let message = imported.map_err(|error| error.to_string());
- let stop = message.is_err();
- if tx.blocking_send(message).is_err() || stop {
- return;
- }
- }
- });
- let mut since_checkpoint = 0u64;
- let mut failure = None;
- let mut transient = false;
- let mut credits = false;
- let mut pausing = false;
- let mut batch: Vec<ImportedItem> = Vec::with_capacity(STORE_BATCH);
- let mut last: Vec<ImportedItem> = Vec::new();
- let mut reading = true;
- while reading || !batch.is_empty() {
- if reading && batch.len() < STORE_BATCH {
- match rx.recv().await {
- Some(Ok(imported)) => {
- batch.push(imported);
- continue;
- }
- Some(Err(error)) => {
- failure = Some(format!("reading the legacy store failed: {error}"));
- reading = false;
- batch.clear();
- continue;
- }
- None => reading = false,
- }
- }
- if paused.as_ref().is_some_and(|paused| paused()) {
- pausing = true;
- break;
- }
- // Accepted: nothing reads the import back until it ends, so a batch
- // does not wait to be listed; the last one is waited for below.
- last.clone_from(&batch);
- let outcome = store_batch(bound, std::mem::take(&mut batch), WaitFor::Accepted).await;
- file.state.imported += outcome.stored;
- // One entry per legacy id; a later refusal replaces the reason.
- for failed in outcome.failed {
- // Every item the importer yields has a legacy id; one without
- // could never be found again to retry, so it is not listed.
- if failed.id.is_empty() {
- tracing::warn!(
- "[memory:import] a refused item has no legacy id; not kept for retry"
- );
- continue;
- }
- match file.failed.iter_mut().find(|known| known.id == failed.id) {
- Some(known) => *known = failed,
- None => file.failed.push(failed),
- }
- }
- file.state.failed = file.failed.len() as u64;
- if let Some(checkpoint) = outcome.checkpoint {
- file.checkpoint = checkpoint;
- }
- since_checkpoint += outcome.stored;
- if since_checkpoint >= CHECKPOINT_EVERY {
- write_file(workspace_dir, &file);
- since_checkpoint = 0;
- }
- if let Some(error) = outcome.fatal {
- failure = Some(error);
- transient = outcome.transient;
- credits = outcome.credits;
- break;
- }
- }
- drop(rx);
- let _ = reader.await;
- // Every batch was stored accepted. Before the import says it is done
- // (and organizing reads it back), wait once for the last batch to be
- // listed: storing it again visible is a replay that returns when it is,
- // retried like any batch. The wait is best-effort: every item is already
- // accepted, and organizing checks each one it copies, so a listing still
- // behind (or rate limited) finishes the import rather than leaving it to
- // resume into the same wait again.
- if failure.is_none() && !pausing && !last.is_empty() {
- let settled = store_batch(bound, last, WaitFor::Visible).await;
- file.listed_unconfirmed = settled.fatal.is_some();
- if let Some(error) = settled.fatal {
- tracing::warn!(
- %error,
- "[memory:import] the last batch is not listed yet; finishing the import anyway"
- );
- }
- }
- if pausing {
- // Left `Running` with its checkpoint: the next unpaused tick resumes it.
- tracing::info!(
- imported = file.state.imported,
- "[memory:import] background paused; import left to resume"
- );
- write_file(workspace_dir, &file);
- return;
- }
- match failure {
- // Left `Running` with its checkpoint and the reason: the next
- // background tick resumes it, as it does an import the app quit.
- Some(error) if transient => {
- tracing::info!(
- imported = file.state.imported,
- %error,
- "[memory:import] engine unavailable; import left to resume"
- );
- file.state.error = Some(error);
- }
- Some(error) => {
- file.paused_for_credits = credits;
- tracing::warn!(
- imported = file.state.imported,
- "[memory:import] import stopped"
- );
- file.state.phase = ImportPhase::Error;
- file.state.error = Some(error);
- }
- None => {
- tracing::info!(
- imported = file.state.imported,
- "[memory:import] import finished"
- );
- file.state.phase = ImportPhase::Done;
- file.state.error = None;
- }
- }
- write_file(workspace_dir, &file);
-}
-
-#[path = "import_retry.rs"]
-mod retry;
-
-#[path = "import_open.rs"]
-mod open;
-pub use retry::retry_failed;
-
#[cfg(test)]
#[path = "import_tests.rs"]
mod tests;
-
-#[cfg(test)]
-#[path = "import_recovery_tests.rs"]
-mod recovery_tests;
-
-#[cfg(test)]
-#[path = "import_organize_tests.rs"]
-mod organize_tests;
-
-#[cfg(test)]
-#[path = "import_wait_tests.rs"]
-mod wait_tests;
-
-#[cfg(test)]
-#[path = "import_connector_tests.rs"]
-mod connector_tests;
diff --git a/crates/openhuman-core/src/memory/import_connector_tests.rs b/crates/openhuman-core/src/memory/import_connector_tests.rs
deleted file mode 100644
index cbb00dfea2..0000000000
--- a/crates/openhuman-core/src/memory/import_connector_tests.rs
+++ /dev/null
@@ -1,76 +0,0 @@
-//! The import leaves out what v1 synced from Composio and the connectors.
-
-use super::tests::{chunk_only_workspace, legacy_workspace, memory_doc, wait_until_settled};
-use super::*;
-use crate::memory::test_fixtures::{bind_reference, config_in, stored};
-use crate::storage::rusqlite;
-use rusqlite::Connection;
-use tinymemory_api::MetaFilter;
-
-#[tokio::test]
-async fn connector_syncs_are_not_imported() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- // Composio leftovers: a `skill-gmail` doc, a Gmail identity facet, and a
- // chunk store with an email and a Slack source beside a memory-source
- // folder file that must still come across.
- let conn = Connection::open(config.workspace_dir.join("memory").join("memory.db")).unwrap();
- memory_doc(&conn, "d9", "skill-gmail", "Inbox", "Mail from Ann");
- conn.execute(
- "INSERT INTO user_profile (facet_id, facet_type, key, value, confidence, first_seen_at, last_seen_at)
- VALUES ('skill-gmail-c1-name', 'identity', 'skill:gmail:name', 'Ann', 0.9, 1.0, 1.0)",
- [],
- )
- .unwrap();
- drop(conn);
- chunk_only_workspace(&config.workspace_dir);
- let conn =
- Connection::open(config.workspace_dir.join("memory_tree").join("chunks.db")).unwrap();
- conn.execute_batch(
- "INSERT INTO mem_tree_chunks VALUES
- ('k4', 'email', 'thread-1', NULL, NULL, 'me', 4, 4, 4, '[]', 'invoice attached', 3, 0, 4),
- ('k5', 'chat', 'slack:conn1', NULL, NULL, 'me', 5, 5, 5, '[]', 'standup at 10', 3, 0, 5),
- ('k6', 'document', 'mem_src:folder', NULL, NULL, 'me', 6, 6, 6, '[]', 'folder note', 3, 0, 6);",
- )
- .unwrap();
- drop(conn);
-
- // Documents: 2 notes + 2 chunk sources (d1, mem_src); the skill-gmail doc
- // and the email/slack sources are absent. Learnings: doc + 1 facet.
- let counts = scan(&config).await.unwrap().counts.expect("counts");
- assert_eq!(
- (counts.documents, counts.conversations, counts.learnings),
- (5, 1, 2),
- "scan counts exclude connector syncs"
- );
-
- let engine = bind_reference(&config);
- start(&config, true).await.unwrap();
- let done = wait_until_settled(&config).await;
- assert_eq!(
- (done.phase, done.imported, done.total),
- (ImportPhase::Done, 8, 8)
- );
- let items = stored(&engine, MetaFilter::default()).await;
- assert_eq!(items.len(), 8);
- let ids: Vec<String> = items
- .iter()
- .filter_map(|hit| hit.meta.source.id.clone())
- .collect();
- assert_eq!(ids.len(), 8, "every item carries its legacy id");
- for skipped in [
- "memory_docs:d9",
- "user_profile:skill-gmail-c1-name",
- "mem_tree_chunks:email:thread-1",
- "mem_tree_chunks:chat:slack:conn1",
- ] {
- assert!(
- !ids.iter().any(|id| id == skipped),
- "{skipped} imported: {ids:?}"
- );
- }
- assert!(ids
- .iter()
- .any(|id| id == "mem_tree_chunks:document:mem_src:folder"));
-}
diff --git a/crates/openhuman-core/src/memory/import_open.rs b/crates/openhuman-core/src/memory/import_open.rs
deleted file mode 100644
index f3e9a572b8..0000000000
--- a/crates/openhuman-core/src/memory/import_open.rs
+++ /dev/null
@@ -1,12 +0,0 @@
-//! Opening the legacy store for the import.
-
-use std::path::Path;
-
-use tinymemory_integrations::import::{Error, LegacyWorkspace};
-
-/// Opens the legacy store for every scan, count, import and retry, skipping
-/// connector (Composio) syncs so the scan counts match the run.
-pub(super) fn open_legacy(dir: &Path) -> Result<LegacyWorkspace, Error> {
- tracing::debug!(workspace = %dir.display(), "[memory:import] skipping connector syncs");
- LegacyWorkspace::open(dir).map(|workspace| workspace.skip_connector_syncs(true))
-}
diff --git a/crates/openhuman-core/src/memory/import_organize_tests.rs b/crates/openhuman-core/src/memory/import_organize_tests.rs
deleted file mode 100644
index bf18e9f7d3..0000000000
--- a/crates/openhuman-core/src/memory/import_organize_tests.rs
+++ /dev/null
@@ -1,63 +0,0 @@
-//! Tests of the hand-off from the import to organizing memory: an import
-//! counts as unfinished from its reservation, and a finished import starts
-//! the move into the per-user tree.
-
-use std::sync::Arc;
-
-use tinymemory_api::MetaFilter;
-
-use super::tests::{legacy_workspace, wait_until_settled};
-use super::*;
-use crate::memory::test_fixtures::{bind_reference, config_in, stored};
-
-#[test]
-fn an_import_counts_as_in_progress_from_its_reservation() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- assert!(!in_progress(&config));
- // Reserved, still scanning the old store: no state written yet.
- RUNNING.lock().unwrap().insert(config.workspace_dir.clone());
- assert!(in_progress(&config));
- RUNNING.lock().unwrap().remove(&config.workspace_dir);
- assert!(!in_progress(&config));
-}
-
-#[tokio::test]
-async fn a_finished_import_starts_organizing_into_the_per_user_tree() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- let account = "0123456789abcdef01234567";
- // Signed in: the move needs the account's own root, and the switch
- // writes the account's config file.
- config.config_path = tmp.path().join("users").join(account).join("config.toml");
- std::fs::create_dir_all(config.config_path.parent().unwrap()).unwrap();
- config.save().await.unwrap();
- legacy_workspace(&config.workspace_dir);
- let legacy = bind_reference(&config);
- let tree = Arc::new(tinymemory_api::conformance::ReferenceEngine::new());
- crate::memory::engine::install_test_engine_for_root(
- &config.workspace_dir,
- Some(&format!("org:{account}")),
- tree.clone(),
- );
-
- start(&config, true).await.unwrap();
- assert_eq!(wait_until_settled(&config).await.phase, ImportPhase::Done);
-
- // The import's own task starts the move once it is done.
- let mut moved = None;
- for _ in 0..400 {
- let migration = crate::memory::layout_migration::status(&config).unwrap();
- if !migration.running
- && migration.state.phase == crate::memory::layout_migration::Phase::Cleaned
- {
- moved = Some(migration.state);
- break;
- }
- tokio::time::sleep(std::time::Duration::from_millis(25)).await;
- }
- let moved = moved.expect("the move never finished after the import");
- assert_eq!(moved.copied, 5);
- assert_eq!(stored(&tree, MetaFilter::default()).await.len(), 5);
- assert!(stored(&legacy, MetaFilter::default()).await.is_empty());
-}
diff --git a/crates/openhuman-core/src/memory/import_recovery_tests.rs b/crates/openhuman-core/src/memory/import_recovery_tests.rs
deleted file mode 100644
index 1efe471063..0000000000
--- a/crates/openhuman-core/src/memory/import_recovery_tests.rs
+++ /dev/null
@@ -1,488 +0,0 @@
-//! Tests of how the import recovers: an atomic state file, a resume that
-//! keeps its total, transient failures retried and resumed, a credits pause
-//! lifted only when automatic runs are allowed, and refused items kept and
-//! retried.
-
-use super::tests::{
- after_document, always, billing, bind_failing, legacy_workspace, out_of_credits,
- wait_until_no_live_run, wait_until_settled,
-};
-use super::*;
-use crate::memory::error::INVALID_REQUEST;
-use crate::memory::test_fixtures::{bind_reference, config_in, stored};
-use tinymemory_api::MetaFilter;
-
-#[tokio::test]
-async fn a_resumed_import_keeps_its_total_instead_of_rescanning() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- bind_reference(&config);
- // A total no scan of this store would produce: a resume must keep it.
- write_file(
- &config.workspace_dir,
- &ImportFile {
- listed_unconfirmed: false,
- paused_for_credits: false,
- failed: Vec::new(),
- retrying: false,
- state: ImportState {
- phase: ImportPhase::Error,
- imported: 1,
- total: 99,
- error: Some("unavailable".into()),
- failed: 0,
- },
- checkpoint: after_document("d1"),
- },
- );
- let started = start(&config, true).await.unwrap();
- assert_eq!(started.total, 99);
- let done = wait_until_settled(&config).await;
- assert_eq!(
- (done.phase, done.total),
- (ImportPhase::Done, 99),
- "{done:?}"
- );
-}
-
-#[test]
-fn the_import_state_is_written_whole_and_leaves_no_staging_file() {
- let tmp = tempfile::tempdir().unwrap();
- let file = ImportFile {
- listed_unconfirmed: false,
- paused_for_credits: false,
- failed: Vec::new(),
- retrying: false,
- state: ImportState {
- phase: ImportPhase::Running,
- imported: 3,
- total: 7,
- error: None,
- failed: 0,
- },
- checkpoint: after_document("d9"),
- };
- write_file(tmp.path(), &file);
- write_file(tmp.path(), &file);
- let read = read_file(tmp.path());
- assert_eq!((read.state, read.checkpoint), (file.state, file.checkpoint));
- let names: Vec<String> = std::fs::read_dir(tmp.path().join("memory"))
- .unwrap()
- .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
- .collect();
- assert_eq!(names, ["import_state.json"]);
-}
-
-/// Calls a flaky engine has refused so far.
-static FLAKY_CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
-
-#[tokio::test]
-async fn a_transient_failure_is_retried_within_the_run() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- FLAKY_CALLS.store(0, std::sync::atomic::Ordering::SeqCst);
- // Unavailable twice (the indexer behind: HTTP 408), then fine.
- let engine = bind_failing(&config, |_| {
- (FLAKY_CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2)
- .then(|| tinymemory_api::Error::Unavailable("WAIT_TIMEOUT".into()))
- });
-
- start(&config, true).await.unwrap();
- let done = wait_until_settled(&config).await;
- assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
- assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 5);
-}
-
-#[tokio::test]
-async fn an_engine_that_stays_unavailable_is_resumed_by_the_background_job() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- bind_failing(&config, |_| {
- Some(tinymemory_api::Error::Unavailable(
- "connection refused".into(),
- ))
- });
-
- start(&config, true).await.unwrap();
- let stopped = wait_until_settled(&config).await;
- assert_eq!(stopped.phase, ImportPhase::Error, "{stopped:?}");
- assert!(
- stopped
- .error
- .as_deref()
- .unwrap()
- .contains("resumes on its own"),
- "{stopped:?}"
- );
- assert_eq!(
- read_file(&config.workspace_dir).state.phase,
- ImportPhase::Running,
- "left for the background job, not stopped for the user"
- );
-
- let engine = bind_reference(&config);
- assert!(resume_interrupted_with(&config, always(false), billing(false)).await);
- let done = wait_until_settled(&config).await;
- assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
- assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 5);
-}
-
-#[tokio::test]
-async fn an_import_out_of_credits_resumes_only_once_automatic_runs_are_allowed() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- bind_failing(&config, out_of_credits);
- start(&config, true).await.unwrap();
- let stopped = wait_until_settled(&config).await;
- assert_eq!(stopped.phase, ImportPhase::Error, "{stopped:?}");
- assert!(read_file(&config.workspace_dir).paused_for_credits);
-
- // Credits still out (no free period): left paused.
- let engine = bind_reference(&config);
- assert!(!resume_interrupted_with(&config, always(false), billing(false)).await);
- assert_eq!(status(&config).phase, ImportPhase::Error);
-
- // Automatic runs allowed again: the background job resumes it.
- assert!(resume_interrupted_with(&config, always(false), billing(true)).await);
- let done = wait_until_settled(&config).await;
- assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
- assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 5);
- assert!(!read_file(&config.workspace_dir).paused_for_credits);
-}
-
-#[tokio::test]
-async fn a_stop_that_is_not_about_credits_is_not_resumed_by_billing() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- bind_failing(&config, |_| {
- Some(tinymemory_api::Error::Unauthorized("sign in".into()))
- });
- start(&config, true).await.unwrap();
- assert_eq!(wait_until_settled(&config).await.phase, ImportPhase::Error);
- assert!(!read_file(&config.workspace_dir).paused_for_credits);
- assert!(!resume_interrupted_with(&config, always(false), billing(true)).await);
-}
-
-/// An engine refusal of the "Ideas" document while `$flag` is set, one flag
-/// per test so tests running in parallel never toggle each other's.
-macro_rules! ideas_refusal {
- ($flag:ident, $refuse:ident) => {
- static $flag: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
- fn $refuse(item: &tinymemory_api::StoreItem) -> Option<tinymemory_api::Error> {
- let ideas = matches!(item, tinymemory_api::StoreItem::Document { title: Some(title), .. } if title == "Ideas");
- (ideas && $flag.load(std::sync::atomic::Ordering::SeqCst))
- .then(|| tinymemory_api::Error::InvalidRequest("item too large".into()))
- }
- };
-}
-
-ideas_refusal!(REFUSE_IDEAS_KEPT, refuse_ideas_kept);
-ideas_refusal!(REFUSE_IDEAS_STOPPED, refuse_ideas_stopped);
-ideas_refusal!(REFUSE_IDEAS_QUIT, refuse_ideas_quit);
-
-#[tokio::test]
-async fn a_refused_item_is_kept_and_a_retry_stores_it() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- REFUSE_IDEAS_KEPT.store(true, std::sync::atomic::Ordering::SeqCst);
- let engine = bind_failing(&config, refuse_ideas_kept);
-
- start(&config, true).await.unwrap();
- let done = wait_until_settled(&config).await;
- assert_eq!(
- (done.phase, done.imported, done.failed),
- (ImportPhase::Done, 4, 1)
- );
- let file = read_file(&config.workspace_dir);
- assert_eq!(file.failed.len(), 1);
- assert_eq!(file.failed[0].id, "memory_docs:d2");
- assert!(
- file.failed[0].reason.contains("item too large"),
- "{:?}",
- file.failed
- );
-
- // Still refused: kept, with the reason.
- retry_failed(&config).await.unwrap();
- let again = wait_until_settled(&config).await;
- assert_eq!(
- (again.phase, again.failed),
- (ImportPhase::Done, 1),
- "{again:?}"
- );
-
- // The engine takes it now: the list empties and the item is stored.
- REFUSE_IDEAS_KEPT.store(false, std::sync::atomic::Ordering::SeqCst);
- retry_failed(&config).await.unwrap();
- let fixed = wait_until_settled(&config).await;
- assert_eq!(
- (fixed.phase, fixed.imported, fixed.failed),
- (ImportPhase::Done, 5, 0),
- "{fixed:?}"
- );
- assert!(read_file(&config.workspace_dir).failed.is_empty());
- let items = stored(&engine, MetaFilter::default()).await;
- assert!(items.iter().any(|item| item.text.contains("oolong")));
-}
-
-#[tokio::test]
-async fn retrying_needs_a_finished_import_with_failed_items() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- bind_reference(&config);
- let error = retry_failed(&config).await.unwrap_err();
- assert_eq!(error.code(), INVALID_REQUEST);
- start(&config, true).await.unwrap();
- assert_eq!(wait_until_settled(&config).await.failed, 0);
- assert_eq!(
- retry_failed(&config).await.unwrap_err().code(),
- INVALID_REQUEST
- );
-}
-
-#[tokio::test]
-async fn a_retry_stopped_by_the_engine_stays_retryable() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- REFUSE_IDEAS_STOPPED.store(true, std::sync::atomic::Ordering::SeqCst);
- bind_failing(&config, refuse_ideas_stopped);
- start(&config, true).await.unwrap();
- assert_eq!(wait_until_settled(&config).await.failed, 1);
-
- // The engine is down for the retry: it stops, still finished, still listed.
- bind_failing(&config, |_| {
- Some(tinymemory_api::Error::Unauthorized("sign in".into()))
- });
- retry_failed(&config).await.unwrap();
- let stopped = wait_until_settled(&config).await;
- assert_eq!(
- (stopped.phase, stopped.failed),
- (ImportPhase::Done, 1),
- "{stopped:?}"
- );
- // A retry is the user's action: it says to press Retry, not that it
- // resumes on its own.
- let reason = stopped.error.as_deref().unwrap();
- assert!(reason.contains("press Retry again"), "{reason}");
- assert!(!reason.contains("on its own"), "{reason}");
-
- // Back up: the same retry goes through.
- REFUSE_IDEAS_STOPPED.store(false, std::sync::atomic::Ordering::SeqCst);
- let engine = bind_failing(&config, refuse_ideas_stopped);
- retry_failed(&config).await.unwrap();
- let done = wait_until_settled(&config).await;
- assert_eq!(
- (done.phase, done.failed, done.error),
- (ImportPhase::Done, 0, None)
- );
- assert!(stored(&engine, MetaFilter::default())
- .await
- .iter()
- .any(|i| i.text.contains("oolong")));
-}
-
-#[tokio::test]
-async fn a_credits_pause_whose_resume_fails_is_not_retried_every_tick() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- bind_failing(&config, out_of_credits);
- start(&config, true).await.unwrap();
- wait_until_settled(&config).await;
- assert!(read_file(&config.workspace_dir).paused_for_credits);
-
- // The legacy store is gone: the automatic resume cannot start.
- std::fs::remove_file(config.workspace_dir.join("memory").join("memory.db")).unwrap();
- bind_reference(&config);
- assert!(!resume_interrupted_with(&config, always(false), billing(true)).await);
- assert!(!read_file(&config.workspace_dir).paused_for_credits);
- assert!(!resume_interrupted_with(&config, always(false), billing(true)).await);
-}
-
-#[tokio::test]
-async fn a_retry_the_app_quit_during_resumes_as_a_retry() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- REFUSE_IDEAS_QUIT.store(true, std::sync::atomic::Ordering::SeqCst);
- let engine = bind_failing(&config, refuse_ideas_quit);
- start(&config, true).await.unwrap();
- assert_eq!(wait_until_settled(&config).await.failed, 1);
-
- // The app quit mid-retry: the state file says a retry is Running.
- let mut file = read_file(&config.workspace_dir);
- file.state.phase = ImportPhase::Running;
- file.retrying = true;
- write_file(&config.workspace_dir, &file);
-
- // The background resume carries on with the retry, not the import, and
- // the engine takes the item now.
- REFUSE_IDEAS_QUIT.store(false, std::sync::atomic::Ordering::SeqCst);
- assert!(resume_interrupted_with(&config, always(false), billing(false)).await);
- let done = wait_until_settled(&config).await;
- assert_eq!(
- (done.phase, done.failed),
- (ImportPhase::Done, 0),
- "{done:?}"
- );
- assert!(!read_file(&config.workspace_dir).retrying);
- assert!(stored(&engine, MetaFilter::default())
- .await
- .iter()
- .any(|item| item.text.contains("oolong")));
-}
-
-/// A finished import with `d2` ("Ideas") still to retry, and the state of a
-/// retry the app quit during.
-fn quit_mid_retry(config: &Config) {
- let mut file = ImportFile::default();
- file.state = ImportState {
- phase: ImportPhase::Running,
- imported: 4,
- total: 5,
- error: None,
- failed: 1,
- };
- file.failed = vec![FailedItem {
- id: "memory_docs:d2".into(),
- reason: "item too large".into(),
- }];
- file.retrying = true;
- write_file(&config.workspace_dir, &file);
-}
-
-#[tokio::test]
-async fn a_retry_that_cannot_resume_stays_finished_and_retryable() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- quit_mid_retry(&config);
-
- // No engine is bound: the background resume of the retry cannot start.
- assert!(!resume_interrupted_with(&config, always(false), billing(false)).await);
- let file = read_file(&config.workspace_dir);
- assert_eq!(
- (file.state.phase, file.failed.len()),
- (ImportPhase::Done, 1)
- );
- assert!(!file.retrying);
- assert!(file
- .state
- .error
- .as_deref()
- .unwrap()
- .contains("press Retry again"));
-
- // Once an engine is there, Retry goes through.
- let engine = bind_reference(&config);
- retry_failed(&config).await.unwrap();
- let done = wait_until_settled(&config).await;
- assert_eq!(
- (done.phase, done.failed),
- (ImportPhase::Done, 0),
- "{done:?}"
- );
- assert!(stored(&engine, MetaFilter::default())
- .await
- .iter()
- .any(|item| item.text.contains("oolong")));
-}
-
-#[tokio::test]
-async fn a_resumed_retry_stops_when_background_work_is_paused() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- let engine = bind_reference(&config);
- quit_mid_retry(&config);
-
- // Paused after the resume check: the retry stores nothing and is left
- // as a running retry for the next unpaused tick.
- let checks = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
- let seen = checks.clone();
- let paused: PauseCheck =
- std::sync::Arc::new(move || seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst) > 0);
- assert!(resume_interrupted_with(&config, paused, billing(false)).await);
- wait_until_no_live_run(&config).await;
- let file = read_file(&config.workspace_dir);
- assert_eq!(file.state.phase, ImportPhase::Running);
- assert!(file.retrying);
- assert_eq!(file.failed.len(), 1);
- assert!(stored(&engine, MetaFilter::default()).await.is_empty());
-}
-
-#[tokio::test]
-async fn retry_is_accepted_for_a_retry_the_app_quit_during() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- let engine = bind_reference(&config);
- quit_mid_retry(&config);
-
- // The user presses Retry before the background job got to it.
- retry_failed(&config).await.unwrap();
- let done = wait_until_settled(&config).await;
- assert_eq!(
- (done.phase, done.failed),
- (ImportPhase::Done, 0),
- "{done:?}"
- );
- assert!(stored(&engine, MetaFilter::default())
- .await
- .iter()
- .any(|item| item.text.contains("oolong")));
-}
-
-/// An import stopped by exhausted credits, waiting for memory work to be free.
-fn paused_for_credits(config: &Config) {
- let mut file = ImportFile::default();
- file.state = ImportState {
- phase: ImportPhase::Error,
- imported: 1,
- total: 5,
- error: Some("not enough credits".into()),
- failed: 0,
- };
- file.checkpoint = after_document("d1");
- file.paused_for_credits = true;
- write_file(&config.workspace_dir, &file);
-}
-
-#[tokio::test]
-async fn the_background_job_resumes_a_credits_pause_while_memory_work_is_free() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- // Not the hosted engine: `billing::free_period_active` reports free.
- let engine = bind_reference(&config);
- paused_for_credits(&config);
-
- assert!(resume_interrupted(&config).await);
- let done = wait_until_settled(&config).await;
- assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
- assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 4);
-}
-
-#[tokio::test]
-async fn the_background_job_leaves_a_credits_pause_while_memory_work_is_not_free() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- // Memory is off here, which `billing::free_period_active` reads as not
- // free: the pause is left as it is, not tried (a tried resume that
- // fails would clear the pause).
- paused_for_credits(&config);
-
- assert!(!resume_interrupted(&config).await);
- let file = read_file(&config.workspace_dir);
- assert_eq!(file.state.phase, ImportPhase::Error);
- assert!(file.paused_for_credits);
-}
diff --git a/crates/openhuman-core/src/memory/import_retry.rs b/crates/openhuman-core/src/memory/import_retry.rs
deleted file mode 100644
index aebc958581..0000000000
--- a/crates/openhuman-core/src/memory/import_retry.rs
+++ /dev/null
@@ -1,185 +0,0 @@
-//! Retrying the items a finished import skipped because the engine refused
-//! them (`memory_import_retry_failed`), and resuming such a retry after an
-//! interruption. A retry is the user's action: when it stops it says so and
-//! waits for Retry again.
-
-use std::collections::HashSet;
-use std::path::Path;
-
-use tinymemory_integrations::cortex::is_insufficient_credits;
-
-use super::{
- legacy_id, open_legacy, read_file, skips_item, status, with_retries, write_file, FailedItem,
- ImportFile, PauseCheck, RUNNING, START_GATE,
-};
-use crate::config::Config;
-use crate::memory::engine::{self, BoundEngine};
-use crate::memory::error::{MemoryError, MemoryResult};
-use crate::memory::types::{ImportPhase, ImportState};
-
-/// `memory_import_retry_failed`: stores again the items a finished import
-/// skipped because the engine refused them. Items that now store leave the
-/// list; ones refused again stay, with the new reason.
-pub async fn retry_failed(config: &Config) -> MemoryResult<ImportState> {
- let file = read_file(&config.workspace_dir);
- // A retry the app quit during is still a retry the user may press
- // again; a live one is answered with its status by `begin_retry`.
- let interrupted_retry = file.state.phase == ImportPhase::Running && file.retrying;
- if !(file.state.phase == ImportPhase::Done || interrupted_retry) || file.failed.is_empty() {
- return Err(MemoryError::invalid(
- "no failed items to retry: the import has not finished or skipped nothing",
- ));
- }
- begin_retry(config, file, None)
-}
-
-/// Starts (or, after an interruption, resumes) a retry of `file.failed`. A
-/// resume the background job started passes its `paused` check, asked
-/// before every item, as the import asks it before every batch.
-pub(super) fn begin_retry(
- config: &Config,
- mut file: ImportFile,
- paused: Option<PauseCheck>,
-) -> MemoryResult<ImportState> {
- let bound = engine::resolve(config).engine()?;
- let workspace_dir = config.workspace_dir.clone();
- let claimed = {
- // The same start gate as an import: a retry bound to the legacy tree
- // while it is being moved would leave its items behind there.
- let _gate = START_GATE
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- if crate::memory::layout_migration::service::is_running(config) {
- return Err(MemoryError::invalid(
- "memory is being organized; retry once that finishes",
- ));
- }
- RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .insert(workspace_dir.clone())
- };
- if !claimed {
- return Ok(status(config));
- }
- file.state.phase = ImportPhase::Running;
- file.state.error = None;
- file.retrying = true;
- write_file(&workspace_dir, &file);
- let state = file.state.clone();
- tracing::info!(
- failed = file.failed.len(),
- "[memory:import] retrying failed items"
- );
- crate::core::runtime::spawn_scoped(async move {
- retry_run(&workspace_dir, &bound, file, paused).await;
- RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .remove(&workspace_dir);
- });
- Ok(state)
-}
-
-/// Why a retry of failed items stopped, and that pressing Retry again
-/// continues it: a retry is the user's action, so nothing resumes it alone.
-fn retry_stop_message(error: tinymemory_api::Error) -> String {
- if error.is_transient() {
- return "the memory service is unavailable; press Retry again once it is back".to_string();
- }
- if is_insufficient_credits(&error) {
- return "not enough credits to retry these items; top up, then press Retry again"
- .to_string();
- }
- format!(
- "the retry stopped: {}; press Retry again",
- MemoryError::from(error)
- )
-}
-
-async fn retry_run(
- workspace_dir: &Path,
- bound: &BoundEngine,
- mut file: ImportFile,
- paused: Option<PauseCheck>,
-) {
- // An item with no legacy id cannot be found again, so it is never
- // matched (every item the importer yields has one).
- let wanted: HashSet<String> = file
- .failed
- .iter()
- .map(|failed| failed.id.clone())
- .filter(|id| !id.is_empty())
- .collect();
- let reader_dir = workspace_dir.to_path_buf();
- let items = crate::core::runtime::spawn_blocking_scoped(move || {
- let workspace = open_legacy(&reader_dir).map_err(|error| error.to_string())?;
- workspace
- .items()
- .filter_map(|imported| match imported {
- Ok(imported) if wanted.contains(&legacy_id(&imported.item)) => {
- Some(Ok(imported.item))
- }
- Ok(_) => None,
- Err(error) => Some(Err(error.to_string())),
- })
- .collect::<Result<Vec<_>, String>>()
- })
- .await
- .map_err(|error| error.to_string())
- .and_then(|items| items);
- let mut failure = None;
- match items {
- Err(error) => {
- failure = Some(format!(
- "reading the legacy store failed: {error}; press Retry again"
- ));
- }
- Ok(items) => {
- for item in items {
- if paused.as_ref().is_some_and(|paused| paused()) {
- // Left a running retry with what is still listed: the
- // next unpaused tick resumes it.
- tracing::info!("[memory:import] background paused; retry left to resume");
- write_file(workspace_dir, &file);
- return;
- }
- let id = legacy_id(&item);
- match with_retries(|| bound.engine.store(item.clone())).await {
- Ok(_) => {
- file.failed.retain(|failed| failed.id != id);
- file.state.imported += 1;
- file.state.failed = file.failed.len() as u64;
- // Persisted per item, so a quit mid-retry keeps what
- // was stored off the list instead of sending it again.
- write_file(workspace_dir, &file);
- }
- Err(error) if skips_item(&error) => {
- let again = FailedItem::new(&item, error);
- if let Some(failed) = file.failed.iter_mut().find(|f| f.id == id) {
- *failed = again;
- }
- // Persisted as it changes, like a stored item.
- write_file(workspace_dir, &file);
- }
- Err(error) => {
- failure = Some(retry_stop_message(error));
- break;
- }
- }
- }
- }
- }
- file.state.failed = file.failed.len() as u64;
- // The import itself is finished either way, so it stays `Done`: a retry
- // stopped by the engine or the account keeps the items still to retry
- // and says why, and the user retries again once that is resolved.
- file.state.phase = ImportPhase::Done;
- file.state.error = failure;
- file.retrying = false;
- tracing::info!(
- still_failed = file.failed.len(),
- "[memory:import] retry of failed items finished"
- );
- write_file(workspace_dir, &file);
-}
diff --git a/crates/openhuman-core/src/memory/import_tests.rs b/crates/openhuman-core/src/memory/import_tests.rs
deleted file mode 100644
index 33b69d0225..0000000000
--- a/crates/openhuman-core/src/memory/import_tests.rs
+++ /dev/null
@@ -1,716 +0,0 @@
-use super::*;
-use crate::memory::error::{INVALID_REQUEST, MEMORY_OFF};
-use crate::memory::test_fixtures::{bind_reference, config_in, stored};
-use crate::storage::rusqlite;
-use std::sync::Arc;
-
-use rusqlite::{params, Connection};
-use tinymemory_api::MetaFilter;
-
-/// An early v1 `memory.db` (no optional columns), enough for the importer.
-const LEGACY_DDL: &str = "
-CREATE TABLE memory_docs (
- document_id TEXT PRIMARY KEY, namespace TEXT NOT NULL, key TEXT NOT NULL, title TEXT NOT NULL,
- content TEXT NOT NULL, source_type TEXT NOT NULL, priority TEXT NOT NULL, tags_json TEXT NOT NULL,
- metadata_json TEXT NOT NULL, category TEXT NOT NULL, session_id TEXT, created_at REAL NOT NULL,
- updated_at REAL NOT NULL, markdown_rel_path TEXT NOT NULL, UNIQUE(namespace, key));
-CREATE TABLE episodic_log (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, timestamp REAL NOT NULL,
- role TEXT NOT NULL, content TEXT NOT NULL, lesson TEXT);
-CREATE TABLE user_profile (facet_id TEXT PRIMARY KEY, facet_type TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL,
- confidence REAL NOT NULL DEFAULT 0.5, evidence_count INTEGER NOT NULL DEFAULT 1, source_segment_ids TEXT,
- first_seen_at REAL NOT NULL, last_seen_at REAL NOT NULL);
-";
-
-pub(super) fn memory_doc(conn: &Connection, id: &str, namespace: &str, title: &str, content: &str) {
- conn.execute(
- "INSERT INTO memory_docs (document_id, namespace, key, title, content, source_type, priority,
- tags_json, metadata_json, category, created_at, updated_at, markdown_rel_path)
- VALUES (?1, ?2, ?1, ?3, ?4, 'chat', 'normal', '[]', '{}', 'core', 1700000000.0, 1700000000.0, '')",
- params![id, namespace, title, content],
- )
- .unwrap();
-}
-
-/// A v1 workspace: two documents, one learning, one conversation, one facet.
-pub(super) fn legacy_workspace(workspace_dir: &Path) {
- std::fs::create_dir_all(workspace_dir.join("memory")).unwrap();
- let conn = Connection::open(workspace_dir.join("memory").join("memory.db")).unwrap();
- conn.execute_batch(LEGACY_DDL).unwrap();
- memory_doc(&conn, "d1", "notes", "Plan", "Ship memory v2 on Friday");
- memory_doc(&conn, "d2", "notes", "Ideas", "Try oolong tea");
- memory_doc(&conn, "d3", "learning:style", "Style", "Keep answers terse");
- for (n, (role, text)) in [("user", "hi there"), ("assistant", "hello")]
- .iter()
- .enumerate()
- {
- conn.execute(
- "INSERT INTO episodic_log (session_id, timestamp, role, content) VALUES ('s1', ?1, ?2, ?3)",
- params![1_700_000_000.0 + n as f64, role, text],
- )
- .unwrap();
- }
- conn.execute(
- "INSERT INTO user_profile (facet_id, facet_type, key, value, confidence, first_seen_at, last_seen_at)
- VALUES ('f1', 'preference', 'tone', 'terse', 0.9, 1700000000.0, 1700000000.0)",
- [],
- )
- .unwrap();
-}
-
-/// The checkpoint after document `id`. Built from `default()` and an
-/// assignment: tinymemory's `Checkpoint` is non-exhaustive from its next
-/// release, which refuses a struct literal outside the crate.
-pub(super) fn after_document(id: &str) -> Checkpoint {
- let mut checkpoint = Checkpoint::default();
- checkpoint.documents = Some(id.to_string());
- checkpoint
-}
-
-pub(super) async fn wait_until_settled(config: &Config) -> ImportState {
- for _ in 0..400 {
- let state = status(config);
- if state.phase != ImportPhase::Running {
- return state;
- }
- tokio::time::sleep(std::time::Duration::from_millis(25)).await;
- }
- panic!("import never settled");
-}
-
-#[tokio::test]
-async fn scan_reports_no_store_for_a_fresh_workspace() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- let view = scan(&config).await.unwrap();
- assert!(!view.found);
- assert!(view.counts.is_none());
- assert!(count_legacy(&config.workspace_dir).is_none());
-}
-
-#[tokio::test]
-async fn scan_counts_what_a_legacy_store_holds() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- let view = scan(&config).await.unwrap();
- assert!(view.found);
- let counts = view.counts.expect("counts");
- assert_eq!(counts.documents, 2);
- assert_eq!(counts.conversations, 1);
- assert_eq!(counts.learnings, 2, "a learning doc and a profile facet");
-}
-
-/// A store from the later v1 engine: only `memory_tree/chunks.db`, with an
-/// document source of two chunks and a chat source of one (not an email: the
-/// import skips connector syncs, see `connector_syncs_are_not_imported`).
-pub(super) fn chunk_only_workspace(workspace_dir: &Path) {
- std::fs::create_dir_all(workspace_dir.join("memory_tree")).unwrap();
- let conn = Connection::open(workspace_dir.join("memory_tree").join("chunks.db")).unwrap();
- conn.execute_batch(
- "CREATE TABLE mem_tree_chunks (id TEXT PRIMARY KEY, source_kind TEXT NOT NULL,
- source_id TEXT NOT NULL, path_scope TEXT, source_ref TEXT, owner TEXT NOT NULL,
- timestamp_ms INTEGER NOT NULL, time_range_start_ms INTEGER NOT NULL,
- time_range_end_ms INTEGER NOT NULL, tags_json TEXT NOT NULL DEFAULT '[]',
- content TEXT NOT NULL, token_count INTEGER NOT NULL, seq_in_source INTEGER NOT NULL,
- created_at_ms INTEGER NOT NULL);
- INSERT INTO mem_tree_chunks VALUES
- ('k1', 'document', 'd1', NULL, NULL, 'me', 1, 1, 1, '[]', 'launch moved', 3, 0, 1),
- ('k2', 'document', 'd1', NULL, NULL, 'me', 2, 2, 2, '[]', 'to friday', 3, 1, 2),
- ('k3', 'chat', 'c1', NULL, NULL, 'me', 3, 3, 3, '[]', 'hi there', 2, 0, 3);",
- )
- .unwrap();
-}
-
-#[tokio::test]
-async fn a_store_with_only_a_chunk_store_is_found_and_imported() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- chunk_only_workspace(&config.workspace_dir);
-
- let view = scan(&config).await.unwrap();
- assert!(view.found, "the later v1 engine wrote no memory.db");
- let counts = view.counts.expect("counts");
- assert_eq!(
- (counts.documents, counts.conversations, counts.learnings),
- (2, 0, 0),
- "two chunk sources, counted as documents"
- );
-
- let engine = bind_reference(&config);
- start(&config, true).await.unwrap();
- let done = wait_until_settled(&config).await;
- assert_eq!(
- (done.phase, done.imported, done.total),
- (ImportPhase::Done, 2, 2)
- );
- assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 2);
-}
-
-#[tokio::test]
-async fn learnings_count_every_learning_section_the_import_yields() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- // Beside the fixture's learning doc and profile facet: one extracted
- // event, one turn lesson, one graph relation and the goals file.
- let conn = Connection::open(config.workspace_dir.join("memory").join("memory.db")).unwrap();
- conn.execute_batch(
- "CREATE TABLE event_log (event_id TEXT PRIMARY KEY, segment_id TEXT NOT NULL,
- session_id TEXT NOT NULL, event_type TEXT NOT NULL, content TEXT NOT NULL,
- subject TEXT, confidence REAL NOT NULL, created_at REAL NOT NULL);
- INSERT INTO event_log VALUES
- ('e1', 'seg', 's1', 'decision', 'Ship v2 on Friday.', NULL, 0.9, 1700000000.0);
- CREATE TABLE graph_global (subject TEXT NOT NULL, predicate TEXT NOT NULL,
- object TEXT NOT NULL, attrs_json TEXT NOT NULL, updated_at REAL NOT NULL,
- PRIMARY KEY(subject, predicate, object));
- INSERT INTO graph_global VALUES ('Priya', 'works_at', 'Acme', '{}', 1700000000.0);
- UPDATE episodic_log SET lesson = 'Greet back briefly.' WHERE role = 'assistant';",
- )
- .unwrap();
- drop(conn);
- std::fs::write(
- config.workspace_dir.join("MEMORY_GOALS.md"),
- "Run a marathon",
- )
- .unwrap();
-
- let counts = scan(&config).await.unwrap().counts.expect("counts");
- assert_eq!(
- (counts.documents, counts.conversations, counts.learnings),
- (2, 1, 6),
- "learning doc, profile facet, event, lesson, relation, goals file"
- );
-
- let engine = bind_reference(&config);
- start(&config, true).await.unwrap();
- let done = wait_until_settled(&config).await;
- assert_eq!(
- (done.phase, done.imported, done.total),
- (ImportPhase::Done, 9, 9)
- );
- assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 9);
-}
-
-#[test]
-fn status_of_an_untouched_workspace_is_idle() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- assert_eq!(status(&config), ImportState::default());
-}
-
-#[tokio::test]
-async fn start_is_refused_without_consent() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- bind_reference(&config);
- let error = start(&config, false).await.unwrap_err();
- assert_eq!(error.code(), INVALID_REQUEST);
- assert!(error.to_string().contains("consent"));
- assert_eq!(status(&config).phase, ImportPhase::Idle, "nothing started");
-}
-
-#[tokio::test]
-async fn start_needs_memory_on_and_a_legacy_store() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- assert_eq!(start(&config, true).await.unwrap_err().code(), MEMORY_OFF);
-
- let tmp2 = tempfile::tempdir().unwrap();
- let empty = config_in(&tmp2);
- bind_reference(&empty);
- for _ in 0..2 {
- // The claim is released, so asking again gives the same answer rather
- // than a stale "already running" status.
- assert_eq!(
- start(&empty, true).await.unwrap_err().code(),
- INVALID_REQUEST
- );
- }
-}
-
-#[tokio::test]
-async fn a_full_import_stores_every_item_and_finishes_done() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- let engine = bind_reference(&config);
-
- let started = start(&config, true).await.unwrap();
- assert_eq!(started.phase, ImportPhase::Running);
- assert_eq!(started.total, 5);
-
- let done = wait_until_settled(&config).await;
- assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
- assert_eq!(done.imported, 5);
- assert_eq!(done.total, 5);
- assert!(done.error.is_none());
- let items = stored(&engine, MetaFilter::default()).await;
- assert_eq!(items.len(), 5);
- assert!(items
- .iter()
- .all(|item| item.meta.source.kind == tinymemory_api::SourceKind::Import));
- assert!(file_path(&config.workspace_dir).exists());
-}
-
-#[tokio::test]
-async fn an_interrupted_import_resumes_from_its_checkpoint() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- let engine = bind_reference(&config);
-
- // A previous run stored d1 and stopped on an error.
- write_file(
- &config.workspace_dir,
- &ImportFile {
- listed_unconfirmed: false,
- paused_for_credits: false,
- failed: Vec::new(),
- retrying: false,
- state: ImportState {
- phase: ImportPhase::Error,
- imported: 1,
- total: 5,
- error: Some("unauthorized: sign in".into()),
- failed: 0,
- },
- checkpoint: after_document("d1"),
- },
- );
- assert_eq!(status(&config).phase, ImportPhase::Error);
-
- start(&config, true).await.unwrap();
- let done = wait_until_settled(&config).await;
- assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
- assert_eq!(done.imported, 5, "the earlier item counts toward the total");
- let items = stored(&engine, MetaFilter::default()).await;
- assert_eq!(items.len(), 4, "d1 is not sent again");
- assert!(
- !items
- .iter()
- .any(|item| item.text.contains("Ship memory v2")),
- "the checkpointed document was skipped"
- );
-}
-
-#[test]
-fn a_running_state_with_no_live_import_reads_as_interrupted() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- write_file(
- &config.workspace_dir,
- &ImportFile {
- listed_unconfirmed: false,
- paused_for_credits: false,
- failed: Vec::new(),
- retrying: false,
- state: ImportState {
- phase: ImportPhase::Running,
- imported: 3,
- total: 9,
- error: None,
- failed: 0,
- },
- checkpoint: Checkpoint::default(),
- },
- );
- let state = status(&config);
- assert_eq!(state.phase, ImportPhase::Error);
- assert_eq!(state.imported, 3);
- assert!(state
- .error
- .as_deref()
- .unwrap()
- .contains("resumes on its own"));
-}
-
-#[tokio::test]
-async fn a_finished_import_starts_over_when_run_again() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- bind_reference(&config);
- start(&config, true).await.unwrap();
- assert_eq!(wait_until_settled(&config).await.phase, ImportPhase::Done);
-
- let again = start(&config, true).await.unwrap();
- assert_eq!(again.imported, 0, "Done does not resume; it restarts");
- assert_eq!(wait_until_settled(&config).await.imported, 5);
-}
-
-#[tokio::test]
-async fn a_second_start_while_running_returns_the_current_status() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- bind_reference(&config);
- RUNNING.lock().unwrap().insert(config.workspace_dir.clone());
- let state = start(&config, true).await.unwrap();
- assert_eq!(state.phase, ImportPhase::Idle, "no second run was launched");
- RUNNING.lock().unwrap().remove(&config.workspace_dir);
-}
-
-#[test]
-fn a_corrupt_import_file_reads_as_idle() {
- let tmp = tempfile::tempdir().unwrap();
- std::fs::create_dir_all(tmp.path().join("memory")).unwrap();
- std::fs::write(file_path(tmp.path()), "garbage").unwrap();
- assert_eq!(read_file(tmp.path()).state, ImportState::default());
-}
-
-/// A reference engine that refuses a write with whatever `refuse` returns for
-/// its item, and stores it otherwise.
-struct FailingEngine {
- inner: Arc<tinymemory_api::conformance::ReferenceEngine>,
- refuse: fn(&tinymemory_api::StoreItem) -> Option<tinymemory_api::Error>,
-}
-
-#[async_trait::async_trait]
-impl tinymemory_api::MemoryEngine for FailingEngine {
- fn descriptor(&self) -> &tinymemory_api::EngineDescriptor {
- self.inner.descriptor()
- }
- async fn health(&self) -> tinymemory_api::EngineHealth {
- self.inner.health().await
- }
- async fn recall(
- &self,
- req: tinymemory_api::RecallRequest,
- ) -> tinymemory_api::Result<tinymemory_api::RecallAnswer> {
- self.inner.recall(req).await
- }
- async fn fetch(
- &self,
- req: tinymemory_api::FetchRequest,
- ) -> tinymemory_api::Result<tinymemory_api::FetchPage> {
- self.inner.fetch(req).await
- }
- async fn store(
- &self,
- item: tinymemory_api::StoreItem,
- ) -> tinymemory_api::Result<tinymemory_api::StoreReceipt> {
- if let Some(error) = (self.refuse)(&item) {
- return Err(error);
- }
- self.inner.store(item).await
- }
- async fn forget(
- &self,
- target: tinymemory_api::ForgetTarget,
- ) -> tinymemory_api::Result<tinymemory_api::ForgetReport> {
- self.inner.forget(target).await
- }
- async fn list(
- &self,
- req: tinymemory_api::ListRequest,
- ) -> tinymemory_api::Result<tinymemory_api::ListPage> {
- self.inner.list(req).await
- }
-}
-
-/// Binds a [`FailingEngine`] and returns the engine behind it.
-pub(super) fn bind_failing(
- config: &Config,
- refuse: fn(&tinymemory_api::StoreItem) -> Option<tinymemory_api::Error>,
-) -> Arc<tinymemory_api::conformance::ReferenceEngine> {
- let inner = Arc::new(tinymemory_api::conformance::ReferenceEngine::new());
- crate::memory::engine::install_test_engine(
- &config.workspace_dir,
- Arc::new(FailingEngine {
- inner: inner.clone(),
- refuse,
- }),
- );
- inner
-}
-
-pub(super) fn out_of_credits(_: &tinymemory_api::StoreItem) -> Option<tinymemory_api::Error> {
- Some(tinymemory_api::Error::Engine(
- "[USER_INSUFFICIENT_CREDITS] insufficient credits (HTTP 402)".into(),
- ))
-}
-
-#[tokio::test]
-async fn exhausted_credits_stop_the_import_instead_of_skipping_everything() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- let engine = bind_failing(&config, out_of_credits);
-
- start(&config, true).await.unwrap();
- let state = wait_until_settled(&config).await;
- assert_eq!(state.phase, ImportPhase::Error, "{state:?}");
- assert_eq!(state.imported, 0);
- assert!(
- state
- .error
- .as_deref()
- .unwrap()
- .contains("not enough credits"),
- "{state:?}"
- );
- assert!(stored(&engine, MetaFilter::default()).await.is_empty());
- assert_eq!(
- read_file(&config.workspace_dir).checkpoint,
- Checkpoint::default(),
- "the checkpoint does not move past items that were never stored"
- );
-}
-
-#[tokio::test]
-async fn an_unreachable_engine_stops_the_import_and_a_retry_resumes_it() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- bind_failing(&config, |_| {
- Some(tinymemory_api::Error::Unavailable(
- "connection refused".into(),
- ))
- });
-
- start(&config, true).await.unwrap();
- let state = wait_until_settled(&config).await;
- assert_eq!(state.phase, ImportPhase::Error, "{state:?}");
- assert_eq!(state.imported, 0);
-
- // The engine is back: starting again imports everything, nothing skipped.
- let engine = bind_reference(&config);
- start(&config, true).await.unwrap();
- let done = wait_until_settled(&config).await;
- assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
- assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 5);
-}
-
-#[tokio::test]
-async fn an_item_the_engine_refuses_is_skipped_and_the_rest_imported() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- // Refuses the "Ideas" document (d2) as malformed, stores the rest.
- let engine = bind_failing(&config, |item| {
- matches!(item, tinymemory_api::StoreItem::Document { title: Some(title), .. } if title == "Ideas")
- .then(|| tinymemory_api::Error::InvalidRequest("item too large".into()))
- });
-
- start(&config, true).await.unwrap();
- let done = wait_until_settled(&config).await;
- assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
- assert_eq!(done.imported, 4);
- let items = stored(&engine, MetaFilter::default()).await;
- assert_eq!(items.len(), 4);
- assert!(!items.iter().any(|item| item.text.contains("oolong")));
-}
-
-#[tokio::test]
-async fn an_import_the_app_quit_during_resumes_on_its_own() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- let engine = bind_reference(&config);
- // The app quit while the import was running, after d1 was stored.
- write_file(
- &config.workspace_dir,
- &ImportFile {
- listed_unconfirmed: false,
- paused_for_credits: false,
- failed: Vec::new(),
- retrying: false,
- state: ImportState {
- phase: ImportPhase::Running,
- imported: 1,
- total: 5,
- error: None,
- failed: 0,
- },
- checkpoint: after_document("d1"),
- },
- );
-
- assert!(resume_interrupted(&config).await);
- let done = wait_until_settled(&config).await;
- assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
- assert_eq!(done.imported, 5);
- assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 4);
-}
-
-#[tokio::test]
-async fn a_stopped_or_finished_import_is_not_resumed_on_its_own() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- let engine = bind_reference(&config);
- assert!(!resume_interrupted(&config).await, "never started");
-
- for phase in [ImportPhase::Error, ImportPhase::Done] {
- write_file(
- &config.workspace_dir,
- &ImportFile {
- listed_unconfirmed: false,
- paused_for_credits: false,
- failed: Vec::new(),
- retrying: false,
- state: ImportState {
- phase,
- imported: 0,
- total: 5,
- error: None,
- failed: 0,
- },
- checkpoint: Checkpoint::default(),
- },
- );
- assert!(!resume_interrupted(&config).await, "{phase:?}");
- }
- assert!(stored(&engine, MetaFilter::default()).await.is_empty());
-}
-
-/// A persisted `Running` import with no live run: what the app leaves behind
-/// when it quits mid-import after storing d1.
-fn quit_mid_import(config: &Config) {
- write_file(
- &config.workspace_dir,
- &ImportFile {
- listed_unconfirmed: false,
- paused_for_credits: false,
- failed: Vec::new(),
- retrying: false,
- state: ImportState {
- phase: ImportPhase::Running,
- imported: 1,
- total: 5,
- error: None,
- failed: 0,
- },
- checkpoint: after_document("d1"),
- },
- );
-}
-
-#[tokio::test]
-async fn the_background_job_resumes_an_interrupted_import() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- let engine = bind_reference(&config);
- quit_mid_import(&config);
-
- crate::memory::bus::run_system_job(&config, crate::memory::lifecycle::jobs::BACKGROUND_JOB)
- .await;
- let done = wait_until_settled(&config).await;
- assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
- assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 4);
-}
-
-#[tokio::test]
-async fn nothing_resumes_while_background_work_is_paused() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- let engine = bind_reference(&config);
- quit_mid_import(&config);
-
- assert!(!resume_interrupted_with(&config, always(true), billing(false)).await);
- assert!(stored(&engine, MetaFilter::default()).await.is_empty());
- assert_eq!(
- read_file(&config.workspace_dir).state.phase,
- ImportPhase::Running,
- "left resumable for a later, unpaused tick"
- );
-
- assert!(resume_interrupted_with(&config, always(false), billing(false)).await);
- assert_eq!(wait_until_settled(&config).await.phase, ImportPhase::Done);
-}
-
-/// A pause check that always answers `paused`.
-pub(super) fn billing(allowed: bool) -> BillingCheck {
- Arc::new(move |_: &Config| allowed)
-}
-
-pub(super) fn always(paused: bool) -> PauseCheck {
- Arc::new(move || paused)
-}
-
-/// Waits until no import run is live for `config`'s workspace.
-pub(super) async fn wait_until_no_live_run(config: &Config) {
- for _ in 0..400 {
- let live = RUNNING.lock().unwrap().contains(&config.workspace_dir);
- if !live {
- return;
- }
- tokio::time::sleep(std::time::Duration::from_millis(25)).await;
- }
- panic!("the import run never ended");
-}
-
-#[tokio::test]
-async fn a_pause_that_lands_after_the_check_stops_the_run_at_the_next_batch() {
- use std::sync::atomic::{AtomicUsize, Ordering};
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- let engine = bind_reference(&config);
- quit_mid_import(&config);
-
- // Not paused when the resume checks, paused by the time the run asks.
- let asked = Arc::new(AtomicUsize::new(0));
- let counter = asked.clone();
- let paused: PauseCheck = Arc::new(move || counter.fetch_add(1, Ordering::SeqCst) > 0);
-
- assert!(resume_interrupted_with(&config, paused, billing(false)).await);
- wait_until_no_live_run(&config).await;
- assert!(asked.load(Ordering::SeqCst) >= 2, "the run asked again");
- assert!(
- stored(&engine, MetaFilter::default()).await.is_empty(),
- "nothing uploaded once paused"
- );
- let file = read_file(&config.workspace_dir);
- assert_eq!(file.state.phase, ImportPhase::Running, "left resumable");
- assert_eq!(file.checkpoint.documents.as_deref(), Some("d1"));
-
- // Unpaused, the next tick finishes it from the checkpoint.
- assert!(resume_interrupted_with(&config, always(false), billing(false)).await);
- assert_eq!(wait_until_settled(&config).await.phase, ImportPhase::Done);
- assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 4);
-}
-
-#[tokio::test]
-async fn an_automatic_resume_that_cannot_start_is_stopped_not_retried() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- // No engine bound: memory is off, so `start` fails before any run.
- quit_mid_import(&config);
-
- assert!(!resume_interrupted_with(&config, always(false), billing(false)).await);
- let state = read_file(&config.workspace_dir).state;
- assert_eq!(state.phase, ImportPhase::Error);
- assert_eq!(state.imported, 1, "progress is kept");
- assert!(
- state.error.as_deref().unwrap().contains("could not resume"),
- "{state:?}"
- );
- // The next tick does not try again; the user resumes it.
- assert!(!resume_interrupted_with(&config, always(false), billing(false)).await);
- assert_eq!(
- read_file(&config.workspace_dir)
- .checkpoint
- .documents
- .as_deref(),
- Some("d1"),
- "the checkpoint read back from disk survives the failure"
- );
-
- // And the user's Resume continues from that checkpoint, not the start.
- let engine = bind_reference(&config);
- start(&config, true).await.unwrap();
- let done = wait_until_settled(&config).await;
- assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
- assert_eq!(done.imported, 5);
- assert_eq!(
- stored(&engine, MetaFilter::default()).await.len(),
- 4,
- "d1 is not re-sent"
- );
-}
diff --git a/crates/openhuman-core/src/memory/import_wait_tests.rs b/crates/openhuman-core/src/memory/import_wait_tests.rs
deleted file mode 100644
index 6ec5c3a717..0000000000
--- a/crates/openhuman-core/src/memory/import_wait_tests.rs
+++ /dev/null
@@ -1,135 +0,0 @@
-//! Tests of how the import stores its batches: accepted, with one
-//! best-effort wait for the last batch to be listed before it is done.
-
-use std::sync::Arc;
-
-use super::tests::{legacy_workspace, wait_until_settled};
-use super::*;
-use crate::memory::test_fixtures::config_in;
-
-/// A reference engine that records the wait each bulk store asks for.
-#[derive(Default)]
-struct WaitRecordingEngine {
- inner: tinymemory_api::conformance::ReferenceEngine,
- waits: std::sync::Mutex<Vec<tinymemory_api::WaitFor>>,
- /// A visible bulk store times out, as on a listing that lags.
- never_listed: bool,
-}
-
-#[async_trait::async_trait]
-impl tinymemory_api::MemoryEngine for WaitRecordingEngine {
- fn descriptor(&self) -> &tinymemory_api::EngineDescriptor {
- self.inner.descriptor()
- }
- async fn health(&self) -> tinymemory_api::EngineHealth {
- self.inner.health().await
- }
- async fn recall(
- &self,
- req: tinymemory_api::RecallRequest,
- ) -> tinymemory_api::Result<tinymemory_api::RecallAnswer> {
- self.inner.recall(req).await
- }
- async fn fetch(
- &self,
- req: tinymemory_api::FetchRequest,
- ) -> tinymemory_api::Result<tinymemory_api::FetchPage> {
- self.inner.fetch(req).await
- }
- async fn store(
- &self,
- item: tinymemory_api::StoreItem,
- ) -> tinymemory_api::Result<tinymemory_api::StoreReceipt> {
- self.inner.store(item).await
- }
- async fn store_many_with(
- &self,
- items: Vec<tinymemory_api::StoreItem>,
- options: tinymemory_api::WriteOptions,
- ) -> tinymemory_api::Result<Vec<tinymemory_api::StoreReceipt>> {
- self.waits.lock().unwrap().push(options.wait);
- if self.never_listed && options.wait == tinymemory_api::WaitFor::Visible {
- return Err(tinymemory_api::Error::Unavailable(
- "accepted but did not become readable within 30s".into(),
- ));
- }
- self.inner.store_many(items).await
- }
- async fn forget(
- &self,
- target: tinymemory_api::ForgetTarget,
- ) -> tinymemory_api::Result<tinymemory_api::ForgetReport> {
- self.inner.forget(target).await
- }
- async fn list(
- &self,
- req: tinymemory_api::ListRequest,
- ) -> tinymemory_api::Result<tinymemory_api::ListPage> {
- self.inner.list(req).await
- }
-}
-
-/// Batches are stored accepted (nothing reads them back mid-import); the
-/// last is stored again visible, once, before the import says it is done.
-#[tokio::test]
-async fn batches_are_stored_accepted_and_the_last_waited_for_once() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- let engine = Arc::new(WaitRecordingEngine::default());
- crate::memory::engine::install_test_engine(&config.workspace_dir, engine.clone());
-
- start(&config, true).await.unwrap();
- let done = wait_until_settled(&config).await;
- assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
- assert_eq!(
- done.imported, 5,
- "the final wait is a replay, not a recount"
- );
- assert_eq!(
- *engine.waits.lock().unwrap(),
- vec![
- tinymemory_api::WaitFor::Accepted,
- tinymemory_api::WaitFor::Visible
- ],
- "one accepted batch, then the visible wait for it"
- );
- assert!(
- !listed_unconfirmed(&config.workspace_dir),
- "a confirmed wait leaves whole-scope cleanup allowed"
- );
-}
-
-/// The end-of-import wait is best-effort: a listing that never catches up
-/// (every visible store times out) still ends the import `Done`, instead of
-/// leaving it to resume into the same wait for ever.
-#[tokio::test]
-async fn a_last_batch_never_listed_still_finishes_the_import() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- legacy_workspace(&config.workspace_dir);
- let engine = Arc::new(WaitRecordingEngine {
- never_listed: true,
- ..WaitRecordingEngine::default()
- });
- crate::memory::engine::install_test_engine(&config.workspace_dir, engine.clone());
-
- start(&config, true).await.unwrap();
- let done = wait_until_settled(&config).await;
- assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
- assert_eq!(done.imported, 5);
- assert!(done.error.is_none(), "{done:?}");
- let waits = engine.waits.lock().unwrap().clone();
- assert_eq!(waits[0], tinymemory_api::WaitFor::Accepted, "{waits:?}");
- assert!(
- waits[1..]
- .iter()
- .all(|wait| *wait == tinymemory_api::WaitFor::Visible)
- && waits.len() > 2,
- "the final wait was retried, then given up: {waits:?}"
- );
- assert!(
- listed_unconfirmed(&config.workspace_dir),
- "an unconfirmed wait is recorded for the migration's cleanup"
- );
-}
diff --git a/crates/openhuman-core/src/memory/types.rs b/crates/openhuman-core/src/memory/types.rs
index e66b32c991..ca60e80ff8 100644
--- a/crates/openhuman-core/src/memory/types.rs
+++ b/crates/openhuman-core/src/memory/types.rs
@@ -380,38 +380,9 @@ pub struct ImportStartParams {
pub consent: bool,
}
-/// Where an import stands.
-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum ImportPhase {
- /// Never started.
- #[default]
- Idle,
- /// Running.
- Running,
- /// Finished.
- Done,
- /// Stopped on an error; starting again resumes.
- Error,
-}
-
-/// `memory_import_*` state.
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct ImportState {
- /// Phase.
- pub phase: ImportPhase,
- /// Items stored so far.
- pub imported: u64,
- /// Items found by the scan.
- pub total: u64,
- /// Why it stopped.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub error: Option<String>,
- /// Items the engine refused (malformed, too large), kept so they can be
- /// retried (`memory_import_retry_failed`).
- #[serde(default)]
- pub failed: u64,
-}
+/// Where an import stands, and its progress (`memory_import_*` state): the
+/// module's own types, so the persisted file and the wire share one shape.
+pub use tinymemory_integrations::import::{ImportPhase, ImportState};
/// `memory_import_start` / `_status` result.
#[derive(Debug, Clone, Serialize)]