Skip to content

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

fix(learning): rebuilds over one workspace take turns and share the stored time

Shanua486b4482bf0
diff --git a/crates/openhuman-core/src/agent/learning/stability_detector.rs b/crates/openhuman-core/src/agent/learning/stability_detector.rs
index 46c7421463..f3c7c6bd6b 100644
--- a/crates/openhuman-core/src/agent/learning/stability_detector.rs
+++ b/crates/openhuman-core/src/agent/learning/stability_detector.rs
@@ -33,7 +33,9 @@
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
-use std::sync::PoisonError;
+use std::sync::{Arc, OnceLock, PoisonError};
+
+use fs2::FileExt;
use crate::agent::learning::cache::FacetCache;
use crate::agent::learning::candidate::{self, CueFamily, FacetClass, LearningCandidate};
@@ -173,7 +175,8 @@ pub struct RebuildOutcome {
pub struct StabilityDetector {
pub(crate) cache: FacetCache,
pub(crate) buffer: &'static candidate::Buffer,
- /// When the previous rebuild in this process finished.
+ /// When the previous rebuild finished: this detector's, or, when
+ /// persisted, a later one by another detector over the same workspace.
///
/// A facet's stability counts time since its last reinforcement, read from
/// `last_seen_at`, which every rebuild used to refresh by writing every
@@ -188,6 +191,12 @@ pub struct StabilityDetector {
/// Where `last_rebuild_at` is kept between processes, when set (see
/// [`Self::persisted_in`]).
pub(crate) state_path: Option<PathBuf>,
+ /// Held for the length of a rebuild, so rebuilds over the same facets run
+ /// one at a time: this detector's periodic and event-driven ones, and,
+ /// once [`Self::persisted_in`], those of every detector over the workspace
+ /// in this process. Each then starts from the facets and the rebuild time
+ /// the one before it left, rather than racing it and overwriting its rows.
+ pub(crate) rebuild_turn: Arc<tokio::sync::Mutex<()>>,
}
/// Where a workspace keeps the time of its last rebuild.
@@ -210,11 +219,13 @@ impl StabilityDetector {
last_rebuild_at: std::sync::Mutex::new(None),
rewrite_tolerance: REWRITE_TOLERANCE,
state_path: None,
+ rebuild_turn: Arc::default(),
}
}
/// Keeps the time of the last rebuild in `workspace_dir`
- /// ([`REBUILD_STATE_FILE`]), and starts from the one stored there.
+ /// ([`REBUILD_STATE_FILE`]), and starts each rebuild 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
@@ -222,54 +233,56 @@ impl StabilityDetector {
/// 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.
+ /// therefore reads and writes the same stored time, and reads it again at
+ /// each rebuild: the scheduled detector lives on beside the one-off ones
+ /// the tool and the RPC build, and must count from their rebuilds too.
+ /// Rebuilds over the workspace in this process also take turns (see
+ /// `rebuild_turn`).
///
/// 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);
+ let workspace =
+ std::fs::canonicalize(workspace_dir).unwrap_or_else(|_| workspace_dir.to_path_buf());
+ self.rebuild_turn = workspace_turn(&workspace);
+ self.state_path = Some(workspace_dir.join(REBUILD_STATE_FILE));
+ self
+ }
+
+ /// When the facets were last rebuilt: by this detector, or, when
+ /// persisted, later by another one over the workspace.
+ fn previous_rebuild(&self) -> Option<f64> {
+ let stored = self.state_path.as_deref().and_then(read_rebuild_time);
+ let mut held = self
+ .last_rebuild_at
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner);
tracing::debug!(
- path = %path.display(),
+ held = ?*held,
stored = ?stored,
- "[learning::stability] rebuild time restored"
+ "[learning::stability] previous rebuild"
);
- *self
- .last_rebuild_at
- .get_mut()
- .unwrap_or_else(PoisonError::into_inner) = stored;
- self.state_path = Some(path);
- self
+ *held = later(*held, stored);
+ *held
}
/// Records `at` as the last rebuild, in memory and, when persisted, on
- /// disk. A write that fails is logged: the next rebuild records again.
+ /// disk; neither moves back to an earlier time. 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 at = {
+ let mut held = self
+ .last_rebuild_at
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner);
+ *held = later(*held, Some(at));
+ held.unwrap_or(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() {
+ if let Err(error) = store_rebuild_time(path, at) {
tracing::warn!(
path = %path.display(),
"[learning::stability] could not record the rebuild time: {error}"
@@ -290,6 +303,7 @@ impl StabilityDetector {
///
/// Async since the facet store moved behind the memory driver.
pub async fn rebuild(&self, now: f64) -> anyhow::Result<RebuildOutcome> {
+ let turn = self.rebuild_turn.lock().await;
tracing::debug!("[learning::stability] rebuild starting at t={now:.0}");
// Step 1 — drain buffer.
@@ -301,10 +315,7 @@ impl StabilityDetector {
// The previous rebuild's time stands in for the refresh a skipped
// write did not make (see `last_rebuild_at`).
- let refreshed_at = *self
- .last_rebuild_at
- .lock()
- .unwrap_or_else(PoisonError::into_inner);
+ let refreshed_at = self.previous_rebuild();
// Step 2 — load existing facets.
let existing_facets = self.cache.list_all().await?;
@@ -517,6 +528,7 @@ impl StabilityDetector {
);
self.record_rebuild(now);
+ drop(turn);
// Step 8 — publish CacheRebuilt event.
BUS.publish(DomainEvent::CacheRebuilt {
@@ -536,6 +548,68 @@ impl StabilityDetector {
}
}
+// ── The rebuild time ──────────────────────────────────────────────────────────
+
+/// The turn rebuilds over `workspace` take, shared by every detector persisted
+/// there in this process.
+fn workspace_turn(workspace: &Path) -> Arc<tokio::sync::Mutex<()>> {
+ static TURNS: OnceLock<std::sync::Mutex<HashMap<PathBuf, Arc<tokio::sync::Mutex<()>>>>> =
+ OnceLock::new();
+ TURNS
+ .get_or_init(Default::default)
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .entry(workspace.to_path_buf())
+ .or_default()
+ .clone()
+}
+
+/// The rebuild time stored at `path`, if there is a readable one.
+fn read_rebuild_time(path: &Path) -> Option<f64> {
+ std::fs::read(path)
+ .ok()
+ .and_then(|bytes| serde_json::from_slice::<RebuildState>(&bytes).ok())
+ .map(|state| state.last_rebuild_at)
+}
+
+/// Stores `at` at `path` as the last rebuild, unless a later one is there.
+///
+/// Writers in every process take turns on a lock file beside it, held from
+/// the read through the rename: two rebuilds that finish together then
+/// neither interleave their writes nor leave the earlier time standing. The
+/// lock sits on its own file because the rename replaces the state file. A
+/// reader takes no lock, and sees the whole previous file or the whole new
+/// one.
+fn store_rebuild_time(path: &Path, at: f64) -> std::io::Result<()> {
+ if let Some(dir) = path.parent() {
+ std::fs::create_dir_all(dir)?;
+ }
+ let lock = std::fs::OpenOptions::new()
+ .create(true)
+ .read(true)
+ .write(true)
+ .truncate(false)
+ .open(path.with_extension("json.lock"))?;
+ lock.lock_exclusive()?;
+ let at = read_rebuild_time(path).map_or(at, |stored| stored.max(at));
+ 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)
+}
+
+/// The later of two times, either of which may be unknown.
+fn later(a: Option<f64>, b: Option<f64>) -> Option<f64> {
+ match (a, b) {
+ (Some(a), Some(b)) => Some(a.max(b)),
+ (a, b) => a.or(b),
+ }
+}
+
// ── Rebuild internals ─────────────────────────────────────────────────────────
struct ComputedFacet {
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 743a36e029..aeaf2143cc 100644
--- a/crates/openhuman-core/src/agent/learning/stability_detector_tests.rs
+++ b/crates/openhuman-core/src/agent/learning/stability_detector_tests.rs
@@ -11,6 +11,7 @@ fn make_detector() -> StabilityDetector {
last_rebuild_at: std::sync::Mutex::new(None),
rewrite_tolerance: REWRITE_TOLERANCE,
state_path: None,
+ rebuild_turn: std::sync::Arc::default(),
}
}
@@ -596,6 +597,24 @@ fn persisted_detector(
.persisted_in(workspace)
}
+fn profile_store() -> std::sync::Arc<crate::agent::learning::test_profile::InMemoryProfile> {
+ std::sync::Arc::new(crate::agent::learning::test_profile::InMemoryProfile::new())
+}
+
+/// Rebuilds `detector` at `start` over explicit evidence for one channel.
+async fn seed_channel(detector: &StabilityDetector, start: f64) {
+ 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();
+}
+
async fn channel_facet(detector: &StabilityDetector) -> Option<ProfileFacet> {
detector
.cache
@@ -606,6 +625,24 @@ async fn channel_facet(detector: &StabilityDetector) -> Option<ProfileFacet> {
.find(|f| f.key == "channel/preferred")
}
+/// Asserts the channel facet reads alike in both stores on `day`.
+async fn assert_same_channel(a: &StabilityDetector, b: &StabilityDetector, day: f64) {
+ let (a, b) = (channel_facet(a).await, channel_facet(b).await);
+ assert_eq!(
+ a.as_ref().map(|f| f.state),
+ b.as_ref().map(|f| f.state),
+ "state on day {day}"
+ );
+ if let (Some(a), Some(b)) = (a, b) {
+ assert!(
+ (a.stability - b.stability).abs() < REWRITE_TOLERANCE,
+ "stability on day {day}: {} vs {}",
+ a.stability,
+ b.stability
+ );
+ }
+}
+
/// 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
@@ -617,24 +654,12 @@ async fn a_restarted_detector_keeps_the_lifecycle_of_an_uninterrupted_one() {
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 restarted_store = profile_store();
+ let uninterrupted_store = profile_store();
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();
- }
+ seed_channel(&restarted, start).await;
+ seed_channel(&uninterrupted, start).await;
let mut at = start;
for cycle in 1..=(40 * 4) {
@@ -645,27 +670,86 @@ async fn a_restarted_detector_keeps_the_lifecycle_of_an_uninterrupted_one() {
}
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_same_channel(&restarted, &uninterrupted, (at - start) / 86_400.0).await;
}
assert!(
restarted_dir.path().join(REBUILD_STATE_FILE).exists(),
"the rebuild time is kept in the workspace"
);
}
+
+/// The scheduled detector lives on beside the one-off detectors the tool and
+/// the RPC build over the same workspace, and counts from their rebuilds as
+/// from its own. Taking turns with them, it keeps the lifecycle of a detector
+/// that ran every rebuild itself; one that read only its own rebuild time
+/// would count the days since as decay and drop the facet.
+#[tokio::test]
+async fn a_long_lived_detector_counts_from_the_one_off_rebuilds_beside_it() {
+ let start = 1_000_000.0;
+ let step = 6.0 * 3600.0;
+ let shared_dir = tempfile::tempdir().unwrap();
+ let alone_dir = tempfile::tempdir().unwrap();
+ let shared_store = profile_store();
+ let alone_store = profile_store();
+ let long_lived = persisted_detector(&shared_store, shared_dir.path());
+ let alone = persisted_detector(&alone_store, alone_dir.path());
+ seed_channel(&long_lived, start).await;
+ seed_channel(&alone, start).await;
+
+ let mut at = start;
+ for cycle in 1..=(40 * 4) {
+ at += step;
+ if cycle % 8 == 0 {
+ long_lived.rebuild(at).await.unwrap();
+ } else {
+ let one_off = persisted_detector(&shared_store, shared_dir.path());
+ one_off.rebuild(at).await.unwrap();
+ }
+ alone.rebuild(at).await.unwrap();
+ assert_same_channel(&long_lived, &alone, (at - start) / 86_400.0).await;
+ }
+}
+
+/// Rebuilds over one workspace take turns, whichever detector runs them: a
+/// one-off rebuild started while the scheduled one runs waits for it, and
+/// then starts from the facets and the time it left.
+#[tokio::test]
+async fn rebuilds_over_one_workspace_take_turns() {
+ let workspace = tempfile::tempdir().unwrap();
+ let store = profile_store();
+ let scheduled = persisted_detector(&store, workspace.path());
+ let one_off = persisted_detector(&store, workspace.path());
+
+ let running = scheduled.rebuild_turn.lock().await;
+ let waiting = tokio::spawn(async move { one_off.rebuild(1_000_000.0).await.map(drop) });
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ assert!(
+ !waiting.is_finished(),
+ "the one-off rebuild ran beside the scheduled one"
+ );
+ drop(running);
+ waiting.await.unwrap().unwrap();
+}
+
+/// Rebuilds that finish together leave the latest time stored, whatever
+/// order their writes land in, and an earlier rebuild finishing late does
+/// not move it back.
+#[test]
+fn the_stored_rebuild_time_only_moves_forward() {
+ let workspace = tempfile::tempdir().unwrap();
+ let path = workspace.path().join(REBUILD_STATE_FILE);
+ store_rebuild_time(&path, 2_000.0).unwrap();
+ store_rebuild_time(&path, 1_000.0).unwrap();
+ assert_eq!(read_rebuild_time(&path), Some(2_000.0));
+
+ let writers: Vec<_> = (0..16)
+ .map(|i| {
+ let path = path.clone();
+ std::thread::spawn(move || store_rebuild_time(&path, 3_000.0 + f64::from(i)))
+ })
+ .collect();
+ for writer in writers {
+ writer.join().unwrap().unwrap();
+ }
+ assert_eq!(read_rebuild_time(&path), Some(3_015.0));
+}