Skip to content

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

fix(memory): an automatic resume rechecks the pause before every batch

Ghost Scripter40c8d3660157
diff --git a/crates/openhuman-core/src/memory/import.rs b/crates/openhuman-core/src/memory/import.rs
index c0fdbc6279..8ca67607e3 100644
--- a/crates/openhuman-core/src/memory/import.rs
+++ b/crates/openhuman-core/src/memory/import.rs
@@ -15,7 +15,7 @@
use std::collections::HashSet;
use std::path::{Path, PathBuf};
-use std::sync::{LazyLock, Mutex};
+use std::sync::{Arc, LazyLock, Mutex};
use serde::{Deserialize, Serialize};
use tinymemory_api::ItemKind;
@@ -224,28 +224,40 @@ 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>;
+
+/// The scheduler's pause, which includes being signed out.
+fn scheduler_paused() -> bool {
+ matches!(
+ crate::cron::scheduler_gate::current_policy(),
+ crate::cron::scheduler_gate::Policy::Paused { .. }
+ )
+}
+
/// Resumes an import the app quit in the middle of, if there is one, under
-/// the scheduler's current policy ([`resume_interrupted_with`]). Called from
-/// memory's background job.
+/// the scheduler's pause ([`resume_interrupted_with`]). Called from memory's
+/// background job.
pub async fn resume_interrupted(config: &Config) -> bool {
- resume_interrupted_with(config, crate::cron::scheduler_gate::current_policy()).await
+ resume_interrupted_with(config, Arc::new(scheduler_paused)).await
}
-/// Resumes an interrupted import under `policy`.
+/// Resumes an interrupted import unless `paused` says background work is
+/// 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); the state stays `Running`, so a later tick resumes it. An import
+/// 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.
-pub(crate) async fn resume_interrupted_with(
- config: &Config,
- policy: crate::cron::scheduler_gate::Policy,
-) -> bool {
+pub(crate) async fn resume_interrupted_with(config: &Config, paused: PauseCheck) -> bool {
if read_file(&config.workspace_dir).state.phase != ImportPhase::Running {
return false;
}
@@ -256,14 +268,11 @@ pub(crate) async fn resume_interrupted_with(
if live {
return false;
}
- if let crate::cron::scheduler_gate::Policy::Paused { reason } = policy {
- tracing::debug!(
- ?reason,
- "[memory:import] background paused; interrupted import left for later"
- );
+ if paused() {
+ tracing::debug!("[memory:import] background paused; interrupted import left for later");
return false;
}
- match start(config, true).await {
+ match start_with(config, true, Some(paused)).await {
Ok(state) => {
tracing::info!(
imported = state.imported,
@@ -291,6 +300,16 @@ 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
+}
+
+/// [`start`], with the pause an automatic resume honors (`None` for an import
+/// the user started, which runs to the end).
+async fn start_with(
+ config: &Config,
+ consent: bool,
+ paused: Option<PauseCheck>,
+) -> MemoryResult<ImportState> {
if !consent {
return Err(MemoryError::invalid(
"importing uploads local memory to the selected engine; pass consent: true",
@@ -328,7 +347,7 @@ pub async fn start(config: &Config, consent: bool) -> MemoryResult<ImportState>
let state = file.state.clone();
tracing::info!(total = state.total, "[memory:import] import started");
tokio::spawn(async move {
- run(&workspace_dir, &bound, file).await;
+ run(&workspace_dir, &bound, file, paused).await;
RUNNING
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
@@ -337,7 +356,12 @@ pub async fn start(config: &Config, consent: bool) -> MemoryResult<ImportState>
Ok(state)
}
-async fn run(workspace_dir: &Path, bound: &BoundEngine, mut file: ImportFile) {
+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();
@@ -359,6 +383,7 @@ async fn run(workspace_dir: &Path, bound: &BoundEngine, mut file: ImportFile) {
});
let mut since_checkpoint = 0u64;
let mut failure = None;
+ let mut pausing = false;
let mut batch: Vec<ImportedItem> = Vec::with_capacity(STORE_BATCH);
let mut reading = true;
while reading || !batch.is_empty() {
@@ -377,6 +402,10 @@ async fn run(workspace_dir: &Path, bound: &BoundEngine, mut file: ImportFile) {
None => reading = false,
}
}
+ if paused.as_ref().is_some_and(|paused| paused()) {
+ pausing = true;
+ break;
+ }
let outcome = store_batch(bound, std::mem::take(&mut batch)).await;
file.state.imported += outcome.stored;
if let Some(checkpoint) = outcome.checkpoint {
@@ -394,6 +423,15 @@ async fn run(workspace_dir: &Path, bound: &BoundEngine, mut file: ImportFile) {
}
drop(rx);
let _ = reader.await;
+ 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 {
Some(error) => {
tracing::warn!(
diff --git a/crates/openhuman-core/src/memory/import_tests.rs b/crates/openhuman-core/src/memory/import_tests.rs
index 930e73f08d..a575536708 100644
--- a/crates/openhuman-core/src/memory/import_tests.rs
+++ b/crates/openhuman-core/src/memory/import_tests.rs
@@ -382,8 +382,7 @@ async fn an_item_the_engine_refuses_is_skipped_and_the_rest_imported() {
legacy_workspace(&config.workspace_dir);
// Refuses the "Ideas" document (d2) as malformed, stores the rest.
let engine = bind_failing(&config, |item| {
- format!("{item:?}")
- .contains("oolong")
+ matches!(item, tinymemory_api::StoreItem::Document { title: Some(title), .. } if title == "Ideas")
.then(|| tinymemory_api::Error::InvalidRequest("item too large".into()))
});
@@ -489,17 +488,13 @@ async fn the_background_job_resumes_an_interrupted_import() {
#[tokio::test]
async fn nothing_resumes_while_background_work_is_paused() {
- use crate::cron::scheduler_gate::{PauseReason, Policy};
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
legacy_workspace(&config.workspace_dir);
let engine = bind_reference(&config);
quit_mid_import(&config);
- let paused = Policy::Paused {
- reason: PauseReason::UserDisabled,
- };
- assert!(!resume_interrupted_with(&config, paused).await);
+ assert!(!resume_interrupted_with(&config, always(true)).await);
assert!(stored(&engine, MetaFilter::default()).await.is_empty());
assert_eq!(
read_file(&config.workspace_dir).state.phase,
@@ -507,10 +502,58 @@ async fn nothing_resumes_while_background_work_is_paused() {
"left resumable for a later, unpaused tick"
);
- assert!(resume_interrupted_with(&config, Policy::Normal).await);
+ assert!(resume_interrupted_with(&config, always(false)).await);
assert_eq!(wait_until_settled(&config).await.phase, ImportPhase::Done);
}
+/// A pause check that always answers `paused`.
+fn always(paused: bool) -> PauseCheck {
+ Arc::new(move || paused)
+}
+
+/// Waits until no import run is live for `config`'s workspace.
+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).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)).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();
@@ -519,8 +562,7 @@ async fn an_automatic_resume_that_cannot_start_is_stopped_not_retried() {
// No engine bound: memory is off, so `start` fails before any run.
quit_mid_import(&config);
- let policy = crate::cron::scheduler_gate::Policy::Normal;
- assert!(!resume_interrupted_with(&config, policy).await);
+ assert!(!resume_interrupted_with(&config, always(false)).await);
let state = read_file(&config.workspace_dir).state;
assert_eq!(state.phase, ImportPhase::Error);
assert_eq!(state.imported, 1, "progress is kept");
@@ -529,7 +571,7 @@ async fn an_automatic_resume_that_cannot_start_is_stopped_not_retried() {
"{state:?}"
);
// The next tick does not try again; the user resumes it.
- assert!(!resume_interrupted_with(&config, policy).await);
+ assert!(!resume_interrupted_with(&config, always(false)).await);
assert_eq!(
read_file(&config.workspace_dir)
.checkpoint
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index f9caed7e87..38e5112695 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -365,7 +365,7 @@ Spec: `docs/specs/memory-v2.md` (host) and `vendor/tinymemory/docs/specs/memory-
| 8.2.5 | Document sources: add, sync, list, remove | RU+RI+WD | `crates/openhuman-core/src/memory/sources/sync_tests.rs`, `crates/openhuman-core/src/memory/sources/composio_tests.rs`, `crates/openhuman-core/src/memory/sources/mod_tests.rs`, `tests/memory_v2_e2e.rs` (`sources_add_sync_list_and_remove`), `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | folder, file, link, github, rss, composio |
| 8.2.6 | Folder-source path picker | RU+VU | `crates/openhuman-app/src/directory_picker.rs`, `app/src/utils/tauriCommands/directoryPicker.test.ts` | ✅ | |
| 8.2.7 | Pack preview (Ask tab) and brain views | RU+RI+WD | `crates/openhuman-core/src/memory/lifecycle/views_tests.rs`, `crates/openhuman-core/src/memory/brain_tests.rs`, `tests/memory_v2_e2e.rs`, `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | No `context.md`; pack never persisted in the transcript |
-| 8.2.8 | One-time import of previous (v1) memory | RU+RI+WD | `crates/openhuman-core/src/memory/import_tests.rs`, `tests/memory_v2_e2e.rs`, `app/test/playwright/specs/memory-v2.spec.ts` (`importing previous memory needs explicit consent`, `a stopped import resumes only after consent`), `app/src/components/memory/MemoryImportBanner.test.tsx` | ✅ | Refused without consent; stops (not skips) on exhausted credits or an unreachable engine; resumes on its own after the app quits (unless background work is paused; a resume that cannot start is stopped, not retried); Resume button after an error |
+| 8.2.8 | One-time import of previous (v1) memory | RU+RI+WD | `crates/openhuman-core/src/memory/import_tests.rs`, `tests/memory_v2_e2e.rs`, `app/test/playwright/specs/memory-v2.spec.ts` (`importing previous memory needs explicit consent`, `a stopped import resumes only after consent`), `app/src/components/memory/MemoryImportBanner.test.tsx` | ✅ | Refused without consent; stops (not skips) on exhausted credits or an unreachable engine (`exhausted_credits_stop_the_import_instead_of_skipping_everything`, `an_unreachable_engine_stops_the_import_and_a_retry_resumes_it`); the background job resumes an import the app quit during (`the_background_job_resumes_an_interrupted_import`), never while paused, including a pause mid-run (`nothing_resumes_while_background_work_is_paused`, `a_pause_that_lands_after_the_check_stops_the_run_at_the_next_batch`); a resume that cannot start is stopped, not retried (`an_automatic_resume_that_cannot_start_is_stopped_not_retried`); Resume button after an error, behind consent (`a stopped import resumes only after consent`) |
| 8.2.9 | MCP memory tools | RU | `crates/openhuman-core/src/mcp/server/tools/` | ✅ | `memory.recall`, `memory.fetch`, `memory.list`, `memory.learn`, `memory.forget` |
| 8.2.10 | Memory UI chips and legacy redirects | VU+WD | `app/src/components/memory/*.test.tsx`, `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | Engine, Ask, Explorer, Learnings, Conversations, Brain, Background, Settings; `/brain` and `/settings/memory-engine` redirect |