Skip to content

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

fix(learning): read stability's reinforcement from the previous rebuild

Shanu97e1bcb20c63
diff --git a/crates/openhuman-core/src/agent/learning/stability_detector.rs b/crates/openhuman-core/src/agent/learning/stability_detector.rs
index 85d74eb1af..77c1f25ce2 100644
--- a/crates/openhuman-core/src/agent/learning/stability_detector.rs
+++ b/crates/openhuman-core/src/agent/learning/stability_detector.rs
@@ -86,10 +86,17 @@ pub const BUDGET_OVERFLOW: usize = 5;
/// Every rebuild recomputes every facet, and decay alone moves its scores a
/// little each time. Writing each one back cost a write per facet per cycle —
/// several billed requests each on hosted memory — to record a change no
-/// reader would act on. Skipping it loses nothing: decay is exponential in the
-/// time since `last_seen_at`, so the next cycle, computing from the older row,
-/// arrives at the score a write-every-cycle would have reached. The tolerance
-/// only bounds how stale the stored scores may read in between.
+/// reader would act on. Skipping it loses nothing:
+///
+/// - confidence decays exponentially in the time since `last_seen_at`, so the
+/// next cycle, computing from the older row, reaches the confidence a
+/// write-every-cycle would have;
+/// - stability counts time since the last reinforcement, which a skipped
+/// write no longer refreshes, so the rebuild reads it from the previous
+/// rebuild instead (`StabilityDetector::last_rebuild_at`), as the refresh
+/// would have.
+///
+/// The tolerance only bounds how stale the stored scores may read in between.
pub const REWRITE_TOLERANCE: f64 = 0.01;
/// Per-class top-N budget for Active rows.
@@ -164,6 +171,18 @@ pub struct RebuildOutcome {
pub struct StabilityDetector {
pub(crate) cache: FacetCache,
pub(crate) buffer: &'static candidate::Buffer,
+ /// When the previous rebuild in this process finished.
+ ///
+ /// A facet's stability counts time since its last reinforcement, read from
+ /// `last_seen_at`, which every rebuild used to refresh by writing every
+ /// row. A rebuild now skips rows that barely moved (see
+ /// [`REWRITE_TOLERANCE`]), so `last_seen_at` can be older than the last
+ /// rebuild; this is the time the refresh would have carried, so stability
+ /// reads as it did when every row was written.
+ pub(crate) last_rebuild_at: std::sync::Mutex<Option<f64>>,
+ /// 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,
}
impl StabilityDetector {
@@ -174,6 +193,8 @@ impl StabilityDetector {
Self {
cache,
buffer: candidate::global(),
+ last_rebuild_at: std::sync::Mutex::new(None),
+ rewrite_tolerance: REWRITE_TOLERANCE,
}
}
@@ -199,6 +220,13 @@ impl StabilityDetector {
candidates.len()
);
+ // 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(std::sync::PoisonError::into_inner);
+
// Step 2 — load existing facets.
let existing_facets = self.cache.list_all().await?;
let existing_by_key: HashMap<String, ProfileFacet> = existing_facets
@@ -240,7 +268,7 @@ impl StabilityDetector {
let final_stability = stability(
dominant_cue(cands, existing),
total_evidence_count(cands, existing),
- most_recent_reinforcement(cands, existing, now, *class),
+ most_recent_reinforcement(cands, existing, refreshed_at, now, *class),
now,
*class,
has_explicit,
@@ -381,7 +409,7 @@ impl StabilityDetector {
kept += 1;
}
let held = existing_by_key.get(&cf.facet.key);
- if held.is_some_and(|held| !worth_rewriting(held, &cf.facet)) {
+ if held.is_some_and(|held| !worth_rewriting(held, &cf.facet, self.rewrite_tolerance)) {
continue;
}
rewritten += 1;
@@ -409,6 +437,11 @@ 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);
+
// Step 8 — publish CacheRebuilt event.
BUS.publish(DomainEvent::CacheRebuilt {
added,
@@ -473,9 +506,13 @@ fn select_winning_value(
/// Whether a recomputed facet says something its stored row does not: any
/// field other than the two scores, or a score that moved by at least
-/// [`REWRITE_TOLERANCE`]. `last_seen_at` is left out on purpose — see the
-/// constant's docs.
-pub(crate) fn worth_rewriting(held: &ProfileFacet, computed: &ProfileFacet) -> bool {
+/// `tolerance` ([`REWRITE_TOLERANCE`] in production). `last_seen_at` is left
+/// out on purpose — see the constant's docs.
+pub(crate) fn worth_rewriting(
+ held: &ProfileFacet,
+ computed: &ProfileFacet,
+ tolerance: f64,
+) -> bool {
held.value != computed.value
|| held.state != computed.state
|| held.user_state != computed.user_state
@@ -486,8 +523,8 @@ pub(crate) fn worth_rewriting(held: &ProfileFacet, computed: &ProfileFacet) -> b
|| held.class != computed.class
|| held.cue_families != computed.cue_families
|| held.first_seen_at != computed.first_seen_at
- || (held.confidence - computed.confidence).abs() >= REWRITE_TOLERANCE
- || (held.stability - computed.stability).abs() >= REWRITE_TOLERANCE
+ || (held.confidence - computed.confidence).abs() >= tolerance
+ || (held.stability - computed.stability).abs() >= tolerance
}
/// Aggregate stability contribution from all candidates (not per-value).
@@ -606,9 +643,13 @@ fn total_evidence_count(cands: &[LearningCandidate], existing: Option<&ProfileFa
/// `rebuild` is class-scoped, and the half-lives span 7d (Channel) to 90d
/// (Identity), so a hardcoded class would over-retain longer-lived facets and
/// evict shorter-lived ones too early.
+/// An existing row counts as reinforced when it was last written, or at the
+/// previous rebuild (`refreshed_at`), whichever is later: that rebuild would
+/// have rewritten the row before rows that barely moved were skipped.
fn most_recent_reinforcement(
cands: &[LearningCandidate],
existing: Option<&ProfileFacet>,
+ refreshed_at: Option<f64>,
now: f64,
class: FacetClass,
) -> f64 {
@@ -617,7 +658,10 @@ fn most_recent_reinforcement(
.map(|c| c.observed_at)
.fold(f64::NEG_INFINITY, f64::max);
let existing_ts = existing
- .map(|f| f.last_seen_at)
+ .map(|f| {
+ f.last_seen_at
+ .max(refreshed_at.unwrap_or(f64::NEG_INFINITY))
+ })
.unwrap_or(f64::NEG_INFINITY);
newest_cand.max(existing_ts).max(now - half_life(class))
}
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 aad0969cd8..0253fa775e 100644
--- a/crates/openhuman-core/src/agent/learning/stability_detector_tests.rs
+++ b/crates/openhuman-core/src/agent/learning/stability_detector_tests.rs
@@ -5,7 +5,12 @@ fn make_detector() -> StabilityDetector {
let cache = crate::agent::learning::test_profile::in_memory_cache();
// Use a private buffer so tests don't interfere with the global singleton.
let buffer: &'static Buffer = Box::leak(Box::new(Buffer::new(256)));
- StabilityDetector { cache, buffer }
+ StabilityDetector {
+ cache,
+ buffer,
+ last_rebuild_at: std::sync::Mutex::new(None),
+ rewrite_tolerance: REWRITE_TOLERANCE,
+ }
}
fn make_candidate(
@@ -306,7 +311,7 @@ fn reinforcement_floor_scopes_to_facet_class() {
FacetClass::Style,
FacetClass::Channel,
] {
- let floor = most_recent_reinforcement(&[], None, now, class);
+ let floor = most_recent_reinforcement(&[], None, None, now, class);
assert_eq!(
floor,
now - half_life(class),
@@ -316,8 +321,51 @@ fn reinforcement_floor_scopes_to_facet_class() {
// Guard against a regression to a single hardcoded class: a class with a
// different half-life than Style must produce a different floor.
assert_ne!(
- most_recent_reinforcement(&[], None, now, FacetClass::Goal),
- most_recent_reinforcement(&[], None, now, FacetClass::Style),
+ most_recent_reinforcement(&[], None, None, now, FacetClass::Goal),
+ most_recent_reinforcement(&[], None, None, now, FacetClass::Style),
+ );
+}
+
+#[test]
+fn a_row_counts_as_reinforced_at_the_previous_rebuild_at_the_latest() {
+ // A row a rebuild skipped still carries the write time of an earlier
+ // cycle; the previous rebuild would have refreshed it, so that is the
+ // reinforcement stability reads. A later write time wins.
+ let now = 10_000_000.0;
+ let row = ProfileFacet {
+ facet_id: "f".into(),
+ facet_type: FacetType::Preference,
+ key: "style/verbosity".into(),
+ value: "terse".into(),
+ confidence: 0.8,
+ evidence_count: 5,
+ source_segment_ids: None,
+ first_seen_at: 1.0,
+ last_seen_at: now - 7_200.0,
+ state: FacetState::Active,
+ stability: 1.6,
+ user_state: UserState::Auto,
+ evidence_refs: Vec::new(),
+ class: Some("style".into()),
+ cue_families: None,
+ };
+ let class = FacetClass::Style;
+ assert_eq!(
+ most_recent_reinforcement(&[], Some(&row), None, now, class),
+ now - 7_200.0
+ );
+ assert_eq!(
+ most_recent_reinforcement(&[], Some(&row), Some(now - 1_800.0), now, class),
+ now - 1_800.0
+ );
+ assert_eq!(
+ most_recent_reinforcement(&[], Some(&row), Some(now - 9_000.0), now, class),
+ now - 7_200.0
+ );
+ assert_eq!(
+ most_recent_reinforcement(&[], None, Some(now - 1_800.0), now, class),
+ now - half_life(class),
+ "a rebuild time says nothing about a row that did not exist"
);
}
@@ -394,7 +442,14 @@ fn merge_evidence_refs_is_idempotent_across_rebuilds() {
// ── rewrite tolerance ───────────────────────────────────────────────────────
async fn seeded_detector(now: f64) -> StabilityDetector {
- let detector = make_detector();
+ seeded_detector_with(now, REWRITE_TOLERANCE).await
+}
+
+async fn seeded_detector_with(now: f64, rewrite_tolerance: f64) -> StabilityDetector {
+ let detector = StabilityDetector {
+ rewrite_tolerance,
+ ..make_detector()
+ };
for i in 0..5 {
detector.buffer.push(make_candidate(
FacetClass::Style,
@@ -446,29 +501,38 @@ async fn a_rebuild_with_nothing_new_leaves_a_settled_row_alone() {
);
}
-/// Skipping writes does not change where decay lands: rebuilding every half
-/// hour for a week reaches the score one rebuild at the end of the week does,
-/// within the tolerance.
+/// Skipping writes changes nothing a reader acts on. Rebuilding every half
+/// hour for a week, a detector that skips rows that moved less than the
+/// tolerance keeps, at every step, the lifecycle state of one that writes
+/// every row every cycle, with scores within the tolerance — stability
+/// included, which counts time since reinforcement rather than decaying from
+/// the stored row.
#[tokio::test]
-async fn skipped_writes_decay_to_the_same_score() {
+async fn skipped_writes_track_a_detector_that_writes_every_cycle() {
let start = 1_000_000.0;
- let week = 7.0 * 86400.0;
- let stepped = seeded_detector(start).await;
+ let skipping = seeded_detector_with(start, REWRITE_TOLERANCE).await;
+ let writing = seeded_detector_with(start, 0.0).await;
let mut at = start;
- while at < start + week {
+ for _ in 0..(7 * 48) {
at += 30.0 * 60.0;
- stepped.rebuild(at).await.unwrap();
+ skipping.rebuild(at).await.unwrap();
+ writing.rebuild(at).await.unwrap();
+ let (skipped, written) = (verbosity(&skipping).await, verbosity(&writing).await);
+ let since = at - start;
+ assert_eq!(skipped.state, written.state, "state at t+{since}s");
+ assert!(
+ (skipped.confidence - written.confidence).abs() < REWRITE_TOLERANCE,
+ "confidence at t+{since}s: {} vs {}",
+ skipped.confidence,
+ written.confidence
+ );
+ assert!(
+ (skipped.stability - written.stability).abs() < REWRITE_TOLERANCE,
+ "stability at t+{since}s: {} vs {}",
+ skipped.stability,
+ written.stability
+ );
}
- let once = seeded_detector(start).await;
- once.rebuild(at).await.unwrap();
-
- let (stepped, once) = (verbosity(&stepped).await, verbosity(&once).await);
- assert!(
- (stepped.confidence - once.confidence).abs() < REWRITE_TOLERANCE * 2.0,
- "stepped={} once={}",
- stepped.confidence,
- once.confidence
- );
}
#[test]
@@ -496,20 +560,23 @@ fn a_row_is_rewritten_for_what_a_reader_would_see() {
last_seen_at: 99.0,
..held.clone()
};
- assert!(!worth_rewriting(&held, &drifted), "a hair of decay");
+ assert!(
+ !worth_rewriting(&held, &drifted, REWRITE_TOLERANCE),
+ "a hair of decay"
+ );
let decayed = ProfileFacet {
confidence: 0.8 - REWRITE_TOLERANCE,
..held.clone()
};
- assert!(worth_rewriting(&held, &decayed));
+ assert!(worth_rewriting(&held, &decayed, REWRITE_TOLERANCE));
let demoted = ProfileFacet {
state: FacetState::Provisional,
..held.clone()
};
- assert!(worth_rewriting(&held, &demoted));
+ assert!(worth_rewriting(&held, &demoted, REWRITE_TOLERANCE));
let reinforced = ProfileFacet {
evidence_count: 6,
..held
};
- assert!(worth_rewriting(&drifted, &reinforced));
+ assert!(worth_rewriting(&drifted, &reinforced, REWRITE_TOLERANCE));
}
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 9ebcfd863f..43571806a8 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -360,7 +360,7 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an
| 8.2.5 | Coding-session persona ingestion | RU+RI+VU+WD | `vendor/tinymemory/crates/tinymemory-core/src/engine/persona_tests.rs` (vendored `tinymemory`), `crates/openhuman-core/src/memory/sources/rpc_tests.rs`, `tests/json_rpc_e2e.rs`, `app/src/components/intelligence/__tests__/CodingSessionsCard.test.tsx`, `app/src/services/memorySourcesService.test.ts`, `app/test/e2e/specs/coding-session-memory.spec.ts`, `app/test/playwright/specs/coding-session-memory.spec.ts` | ✅ | Discovers Codex and Claude Code histories, excludes machine-authored turns, exposes status/ingest RPCs, and surfaces incremental ingestion on Brain > Sources |
| 8.2.6 | Folder-source path picker | RU+VU | `crates/openhuman-app/src/directory_picker.rs`, `app/src/utils/tauriCommands/directoryPicker.test.ts`, `app/src/components/intelligence/FolderField.test.tsx` | ✅ | Browse resolves an absolute path through the OS-native chooser and refuses to store a non-resolvable value (bare directory name) when none is available (#5831) |
| 8.2.7 | Sync History and live sync activity | RU+RI+VU | `crates/openhuman-core/src/memory/sources/run_history_tests.rs`, `crates/openhuman-core/src/memory/sources/rpc/driver_run_tests.rs`, `crates/openhuman-core/src/memory/sources/rpc_monthly_summary_tests_tests.rs`, `crates/openhuman-core/src/integrations/composio/ops/connector_runs_tests.rs`, `crates/openhuman-core/src/integrations/composio/ops/source_rows_tests.rs`, `crates/openhuman-core/src/memory/sync_activity_tests.rs`, `tests/memory_sources_e2e.rs` (`sources_sync_dispatches_to_the_module_rather_than_refusing_the_capability`), `app/src/components/intelligence/SyncAuditPanel.test.tsx`, `app/src/components/intelligence/SyncActivityCard.test.tsx`, `app/src/components/intelligence/__tests__/memorySyncActivityStore.test.ts`, `app/src/components/intelligence/MemorySourceRow.test.tsx`, `app/src/components/intelligence/MemoryTreeStatusPanel.test.tsx` | ✅ | Every host-driven run (Sync button, Apply all, Composio) leaves one history row merged with the driver's audit log; manual driver runs end in `completed` or `failed`; a late per-document stage cannot reopen a finished row; Brain > Sync shows what is syncing and the job queue, and re-reads the history when a run ends (#6257) |
-| 8.2.8 | Selectable memory engines and migration | RU+RI+VU | `crates/openhuman-core/src/memory/ops/engine_migrate_tests.rs`, `crates/openhuman-core/src/memory/ops/engine_tests.rs`, `tests/memory_engine_e2e.rs`, `tests/memory_engine_migrate_e2e.rs`, `tests/memory_hosted_surface_e2e.rs`, `app/src/components/settings/panels/MemoryEnginePanel.test.tsx`, `app/src/components/settings/panels/MemoryEngineErrorAlert.test.tsx`, `app/src/components/intelligence/MemoryFamilyGate.test.tsx`, `app/src/pages/__tests__/Brain.test.tsx` | ✅ | Engine selection, migration copy/cancel/failure behavior, hosted and external drivers, and capability gating; on the hosted engine a 403 reads `MEMORY_FORBIDDEN:` (never a sign-out), an outage `MEMORY_UNREACHABLE:`, and Brain's sync panels say "Not available" (#6718). The hosted engine serves goals, tool rules, documents, the source sink and maintenance (`memory_hosted_surface_e2e.rs::the_hosted_engine_serves_documents_and_tool_rules`), draws the Brain graph from the server's derived facts (`::the_hosted_engine_draws_the_brain_graph_from_its_understanding`), and takes a local folder synced by the host (`::a_local_folder_syncs_into_hosted_memory`, `memory/sources/hosted_sync_tests.rs`), forgetting a file deleted from the folder (`hosted_sync_tests.rs::a_deleted_file_is_forgotten_by_the_id_the_sink_gave_it`); Brain gates coding sessions on their own family and local-store controls on `chunks`. A copy carries document details, goals, the profile, the conversation history and re-sent content, reporting each step and naming what the new engine cannot take (`engine_migrate_tests.rs`, `MemoryEnginePanel.test.tsx`; the steps themselves are tinymemory's `migrate::copy_all`). On hosted memory the learning rebuild writes only facets that changed (`agent/learning/stability_detector_tests.rs::skipped_writes_decay_to_the_same_score`) and segment recaps fold with the host's model (`agent/harness/archivist/recap_tests.rs::the_host_model_folds_a_segment_the_driver_cannot`) |
+| 8.2.8 | Selectable memory engines and migration | RU+RI+VU | `crates/openhuman-core/src/memory/ops/engine_migrate_tests.rs`, `crates/openhuman-core/src/memory/ops/engine_tests.rs`, `tests/memory_engine_e2e.rs`, `tests/memory_engine_migrate_e2e.rs`, `tests/memory_hosted_surface_e2e.rs`, `app/src/components/settings/panels/MemoryEnginePanel.test.tsx`, `app/src/components/settings/panels/MemoryEngineErrorAlert.test.tsx`, `app/src/components/intelligence/MemoryFamilyGate.test.tsx`, `app/src/pages/__tests__/Brain.test.tsx` | ✅ | Engine selection, migration copy/cancel/failure behavior, hosted and external drivers, and capability gating; on the hosted engine a 403 reads `MEMORY_FORBIDDEN:` (never a sign-out), an outage `MEMORY_UNREACHABLE:`, and Brain's sync panels say "Not available" (#6718). The hosted engine serves goals, tool rules, documents, the source sink and maintenance (`memory_hosted_surface_e2e.rs::the_hosted_engine_serves_documents_and_tool_rules`), draws the Brain graph from the server's derived facts (`::the_hosted_engine_draws_the_brain_graph_from_its_understanding`), and takes a local folder synced by the host (`::a_local_folder_syncs_into_hosted_memory`, `memory/sources/hosted_sync_tests.rs`), forgetting a file deleted from the folder (`hosted_sync_tests.rs::a_deleted_file_is_forgotten_by_the_id_the_sink_gave_it`); Brain gates coding sessions on their own family and local-store controls on `chunks`. A copy carries document details, goals, the profile, the conversation history and re-sent content, reporting each step and naming what the new engine cannot take (`engine_migrate_tests.rs`, `MemoryEnginePanel.test.tsx`; the steps themselves are tinymemory's `migrate::copy_all`). On hosted memory the learning rebuild writes only facets that changed (`agent/learning/stability_detector_tests.rs::skipped_writes_track_a_detector_that_writes_every_cycle`) and segment recaps fold with the host's model (`agent/harness/archivist/recap_tests.rs::the_host_model_folds_a_segment_the_driver_cannot`) |
### 8.3 Memory Retrieval Benchmarks