Skip to content

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

fix(learning): keep the last rebuild time across restarts

Shanu59726fcea9cf
diff --git a/crates/openhuman-core/src/agent/learning/schemas/profile_handlers.rs b/crates/openhuman-core/src/agent/learning/schemas/profile_handlers.rs
index 27b07f8d88..057791c1e7 100644
--- a/crates/openhuman-core/src/agent/learning/schemas/profile_handlers.rs
+++ b/crates/openhuman-core/src/agent/learning/schemas/profile_handlers.rs
@@ -92,7 +92,10 @@ pub(super) fn handle_rebuild_cache(_params: Map<String, Value>) -> ControllerFut
.await
.map_err(|e| format!("memory unavailable: {e}"))?,
);
- let detector = StabilityDetector::new(cache);
+ // The workspace's stored rebuild time, so a one-off rebuild reads
+ // reinforcement as the periodic one does.
+ let config = crate::config::rpc::load_config_with_timeout().await?;
+ let detector = StabilityDetector::new(cache).persisted_in(&config.workspace_dir);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
diff --git a/crates/openhuman-core/src/agent/learning/stability_detector.rs b/crates/openhuman-core/src/agent/learning/stability_detector.rs
index 77c1f25ce2..46c7421463 100644
--- a/crates/openhuman-core/src/agent/learning/stability_detector.rs
+++ b/crates/openhuman-core/src/agent/learning/stability_detector.rs
@@ -32,6 +32,8 @@
//! overflow pool holds up to `BUDGET_OVERFLOW` extra Provisional rows.
use std::collections::{HashMap, HashSet};
+use std::path::{Path, PathBuf};
+use std::sync::PoisonError;
use crate::agent::learning::cache::FacetCache;
use crate::agent::learning::candidate::{self, CueFamily, FacetClass, LearningCandidate};
@@ -183,6 +185,18 @@ pub struct StabilityDetector {
/// How far a score may move before its row is written again. A field so a
/// test can compare against a detector that writes every row every cycle.
pub(crate) rewrite_tolerance: f64,
+ /// Where `last_rebuild_at` is kept between processes, when set (see
+ /// [`Self::persisted_in`]).
+ pub(crate) state_path: Option<PathBuf>,
+}
+
+/// Where a workspace keeps the time of its last rebuild.
+pub const REBUILD_STATE_FILE: &str = "state/learning/rebuild.json";
+
+/// The time of a workspace's last rebuild, as [`REBUILD_STATE_FILE`] holds it.
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+struct RebuildState {
+ last_rebuild_at: f64,
}
impl StabilityDetector {
@@ -195,6 +209,71 @@ impl StabilityDetector {
buffer: candidate::global(),
last_rebuild_at: std::sync::Mutex::new(None),
rewrite_tolerance: REWRITE_TOLERANCE,
+ state_path: None,
+ }
+ }
+
+ /// Keeps the time of the last rebuild in `workspace_dir`
+ /// ([`REBUILD_STATE_FILE`]), and starts from the one stored there.
+ ///
+ /// A row a rebuild skipped can keep an old `last_seen_at` for weeks — a
+ /// low-confidence row moves less than the tolerance per cycle — while the
+ /// rebuild time stands in for its reinforcement. A detector that started
+ /// without that time, after a restart or for a one-off rebuild, would read
+ /// those weeks as decay all at once and could demote or evict a facet an
+ /// uninterrupted detector keeps. Every detector over a workspace's facets
+ /// therefore reads and writes the same stored time.
+ ///
+ /// A missing or unreadable file is a detector with no previous rebuild:
+ /// the first one reads reinforcement from the rows alone, as before.
+ #[must_use]
+ pub fn persisted_in(mut self, workspace_dir: &Path) -> Self {
+ let path = workspace_dir.join(REBUILD_STATE_FILE);
+ let stored = std::fs::read(&path)
+ .ok()
+ .and_then(|bytes| serde_json::from_slice::<RebuildState>(&bytes).ok())
+ .map(|state| state.last_rebuild_at);
+ tracing::debug!(
+ path = %path.display(),
+ stored = ?stored,
+ "[learning::stability] rebuild time restored"
+ );
+ *self
+ .last_rebuild_at
+ .get_mut()
+ .unwrap_or_else(PoisonError::into_inner) = stored;
+ self.state_path = Some(path);
+ self
+ }
+
+ /// Records `at` as the last rebuild, in memory and, when persisted, on
+ /// disk. A write that fails is logged: the next rebuild records again.
+ fn record_rebuild(&self, at: f64) {
+ *self
+ .last_rebuild_at
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner) = Some(at);
+ let Some(path) = &self.state_path else {
+ return;
+ };
+ let write = || -> std::io::Result<()> {
+ if let Some(dir) = path.parent() {
+ std::fs::create_dir_all(dir)?;
+ }
+ let tmp = path.with_extension("json.tmp");
+ std::fs::write(
+ &tmp,
+ serde_json::to_vec(&RebuildState {
+ last_rebuild_at: at,
+ })?,
+ )?;
+ std::fs::rename(&tmp, path)
+ };
+ if let Err(error) = write() {
+ tracing::warn!(
+ path = %path.display(),
+ "[learning::stability] could not record the rebuild time: {error}"
+ );
}
}
@@ -225,7 +304,7 @@ impl StabilityDetector {
let refreshed_at = *self
.last_rebuild_at
.lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
+ .unwrap_or_else(PoisonError::into_inner);
// Step 2 — load existing facets.
let existing_facets = self.cache.list_all().await?;
@@ -437,10 +516,7 @@ impl StabilityDetector {
"[learning::stability] rebuild added={added} evicted={evicted} kept={kept} total={total_size}"
);
- *self
- .last_rebuild_at
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(now);
+ self.record_rebuild(now);
// Step 8 — publish CacheRebuilt event.
BUS.publish(DomainEvent::CacheRebuilt {
diff --git a/crates/openhuman-core/src/agent/learning/stability_detector_tests.rs b/crates/openhuman-core/src/agent/learning/stability_detector_tests.rs
index 0253fa775e..743a36e029 100644
--- a/crates/openhuman-core/src/agent/learning/stability_detector_tests.rs
+++ b/crates/openhuman-core/src/agent/learning/stability_detector_tests.rs
@@ -10,6 +10,7 @@ fn make_detector() -> StabilityDetector {
buffer,
last_rebuild_at: std::sync::Mutex::new(None),
rewrite_tolerance: REWRITE_TOLERANCE,
+ state_path: None,
}
}
@@ -580,3 +581,91 @@ fn a_row_is_rewritten_for_what_a_reader_would_see() {
};
assert!(worth_rewriting(&drifted, &reinforced, REWRITE_TOLERANCE));
}
+
+// ── the rebuild time across restarts ─────────────────────────────────────────
+
+/// A detector over `profile` that keeps its rebuild time in `workspace`.
+fn persisted_detector(
+ profile: &std::sync::Arc<crate::agent::learning::test_profile::InMemoryProfile>,
+ workspace: &std::path::Path,
+) -> StabilityDetector {
+ StabilityDetector {
+ cache: crate::agent::learning::cache::FacetCache::for_tests(profile.clone()),
+ ..make_detector()
+ }
+ .persisted_in(workspace)
+}
+
+async fn channel_facet(detector: &StabilityDetector) -> Option<ProfileFacet> {
+ detector
+ .cache
+ .list_all()
+ .await
+ .unwrap()
+ .into_iter()
+ .find(|f| f.key == "channel/preferred")
+}
+
+/// A detector rebuilt over the same store after a restart keeps the
+/// lifecycle an uninterrupted one gives. The facet's confidence decays below
+/// what the tolerance lets a cycle write, so its row goes weeks without a
+/// write; a restarted detector that lost the rebuild time would read those
+/// weeks as decay at once and drop the facet.
+#[tokio::test]
+async fn a_restarted_detector_keeps_the_lifecycle_of_an_uninterrupted_one() {
+ let start = 1_000_000.0;
+ let step = 6.0 * 3600.0;
+ let restarted_dir = tempfile::tempdir().unwrap();
+ let uninterrupted_dir = tempfile::tempdir().unwrap();
+ let restarted_store =
+ std::sync::Arc::new(crate::agent::learning::test_profile::InMemoryProfile::new());
+ let uninterrupted_store =
+ std::sync::Arc::new(crate::agent::learning::test_profile::InMemoryProfile::new());
+ let mut restarted = persisted_detector(&restarted_store, restarted_dir.path());
+ let uninterrupted = persisted_detector(&uninterrupted_store, uninterrupted_dir.path());
+ for detector in [&restarted, &uninterrupted] {
+ for i in 0..5 {
+ detector.buffer.push(make_candidate(
+ FacetClass::Channel,
+ "preferred",
+ "email",
+ CueFamily::Explicit,
+ start - i as f64 * 10.0,
+ ));
+ }
+ detector.rebuild(start).await.unwrap();
+ }
+
+ let mut at = start;
+ for cycle in 1..=(40 * 4) {
+ at += step;
+ if cycle == 30 * 4 {
+ // The process restarts: a new detector over the same store.
+ restarted = persisted_detector(&restarted_store, restarted_dir.path());
+ }
+ restarted.rebuild(at).await.unwrap();
+ uninterrupted.rebuild(at).await.unwrap();
+ let (r, u) = (
+ channel_facet(&restarted).await,
+ channel_facet(&uninterrupted).await,
+ );
+ let day = (at - start) / 86_400.0;
+ assert_eq!(
+ r.as_ref().map(|f| f.state),
+ u.as_ref().map(|f| f.state),
+ "state on day {day}"
+ );
+ if let (Some(r), Some(u)) = (r, u) {
+ assert!(
+ (r.stability - u.stability).abs() < REWRITE_TOLERANCE,
+ "stability on day {day}: {} vs {}",
+ r.stability,
+ u.stability
+ );
+ }
+ }
+ assert!(
+ restarted_dir.path().join(REBUILD_STATE_FILE).exists(),
+ "the rebuild time is kept in the workspace"
+ );
+}
diff --git a/crates/openhuman-core/src/agent/learning/startup.rs b/crates/openhuman-core/src/agent/learning/startup.rs
index 8b1dc3e328..5be437d03a 100644
--- a/crates/openhuman-core/src/agent/learning/startup.rs
+++ b/crates/openhuman-core/src/agent/learning/startup.rs
@@ -211,7 +211,7 @@ fn register_with_memory(
let Some(cache) = facet_cache_for(workspace_dir) else {
return (None, None);
};
- let detector = Arc::new(StabilityDetector::new(cache));
+ let detector = Arc::new(StabilityDetector::new(cache).persisted_in(workspace_dir));
// Also spawn the periodic rebuild loop (30-minute cadence).
let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);
// Leak the sender so the loop never receives a shutdown signal until the
diff --git a/crates/openhuman-core/src/agent/learning/tools.rs b/crates/openhuman-core/src/agent/learning/tools.rs
index 2766f11804..eb79d99dd2 100644
--- a/crates/openhuman-core/src/agent/learning/tools.rs
+++ b/crates/openhuman-core/src/agent/learning/tools.rs
@@ -465,7 +465,12 @@ impl Tool for LearningRebuildCacheTool {
async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
log::debug!("[tool][learning] rebuild_cache invoked");
let cache = get_cache().await?;
- let detector = StabilityDetector::new(cache);
+ // The workspace's stored rebuild time, so a one-off rebuild reads
+ // reinforcement as the periodic one does.
+ let config = crate::config::rpc::load_config_with_timeout()
+ .await
+ .map_err(|e| anyhow::anyhow!("learning_rebuild_cache: config unavailable: {e}"))?;
+ let detector = StabilityDetector::new(cache).persisted_in(&config.workspace_dir);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs_f64())