The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
perf(learning): write back only the facets a rebuild changed
Shanueae996ea2221
diff --git a/crates/openhuman-core/src/agent/learning/stability_detector.rs b/crates/openhuman-core/src/agent/learning/stability_detector.rsindex 24d3614523..85d74eb1af 100644--- a/crates/openhuman-core/src/agent/learning/stability_detector.rs+++ b/crates/openhuman-core/src/agent/learning/stability_detector.rs@@ -80,6 +80,18 @@ pub const BUDGET_CHANNEL: usize = 1;/// Cross-class overflow pool for Provisional rows that didn't make a class budget.pub const BUDGET_OVERFLOW: usize = 5;+/// How far a facet's confidence or stability may drift before a rebuild+/// writes the row again.+///+/// 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.+pub const REWRITE_TOLERANCE: f64 = 0.01;+/// Per-class top-N budget for Active rows.pub fn class_budget(class: FacetClass) -> usize {match class {@@ -359,6 +371,7 @@ impl StabilityDetector {let mut kept = 0usize;let mut evicted = 0usize;+ let mut rewritten = 0usize;for cf in &all_final {if cf.facet.state == FacetState::Dropped {evicted += 1;@@ -367,8 +380,17 @@ impl StabilityDetector {} else {kept += 1;}+ let held = existing_by_key.get(&cf.facet.key);+ if held.is_some_and(|held| !worth_rewriting(held, &cf.facet)) {+ continue;+ }+ rewritten += 1;self.cache.upsert(&cf.facet).await?;}+ tracing::debug!(+ "[learning::stability] wrote {rewritten} of {} facets; the rest moved less than the rewrite tolerance",+ all_final.len()+ );// (Existing keys not in the rebuild output are legacy/non-class rows — skip.)@@ -449,6 +471,25 @@ fn select_winning_value(.map(|(v, _)| v.to_string())}+/// 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 {+ held.value != computed.value+ || held.state != computed.state+ || held.user_state != computed.user_state+ || held.facet_type != computed.facet_type+ || held.evidence_count != computed.evidence_count+ || held.evidence_refs != computed.evidence_refs+ || held.source_segment_ids != computed.source_segment_ids+ || 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+}+/// Aggregate stability contribution from all candidates (not per-value)./// Returns (aggregate_score, has_explicit_evidence).fn aggregate_stability(diff --git a/crates/openhuman-core/src/agent/learning/stability_detector_tests.rs b/crates/openhuman-core/src/agent/learning/stability_detector_tests.rsindex 6993e86cbc..aad0969cd8 100644--- a/crates/openhuman-core/src/agent/learning/stability_detector_tests.rs+++ b/crates/openhuman-core/src/agent/learning/stability_detector_tests.rs@@ -390,3 +390,126 @@ fn merge_evidence_refs_is_idempotent_across_rebuilds() {assert_eq!(first, second);assert_eq!(first.len(), 2);}++// ── rewrite tolerance ───────────────────────────────────────────────────────++async fn seeded_detector(now: f64) -> StabilityDetector {+ let detector = make_detector();+ for i in 0..5 {+ detector.buffer.push(make_candidate(+ FacetClass::Style,+ "verbosity",+ "terse",+ CueFamily::Explicit,+ now - i as f64 * 10.0,+ ));+ }+ detector.rebuild(now).await.unwrap();+ detector+}++async fn verbosity(detector: &StabilityDetector) -> ProfileFacet {+ detector+ .cache+ .list_all()+ .await+ .unwrap()+ .into_iter()+ .find(|f| f.key == "style/verbosity")+ .expect("the facet exists")+}++/// Once a facet has settled, a cycle that brings no evidence moves its scores+/// by a hair, and the row is not written again for it.+///+/// The first cycle after the evidence does change it — that cycle's explicit+/// cues are gone, so its stability and state move — and is written.+#[tokio::test]+async fn a_rebuild_with_nothing_new_leaves_a_settled_row_alone() {+ let now = 1_000_000.0;+ let half_hour = 30.0 * 60.0;+ let detector = seeded_detector(now).await;+ detector.rebuild(now + half_hour).await.unwrap();+ let settled = verbosity(&detector).await;+ assert_eq!(+ settled.last_seen_at,+ now + half_hour,+ "the first cycle writes"+ );++ let outcome = detector.rebuild(now + 2.0 * half_hour).await.unwrap();+ assert_eq!(outcome.kept, 1, "the facet is still kept");+ assert_eq!(+ verbosity(&detector).await,+ settled,+ "nothing moved enough to be written"+ );+}++/// 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.+#[tokio::test]+async fn skipped_writes_decay_to_the_same_score() {+ let start = 1_000_000.0;+ let week = 7.0 * 86400.0;+ let stepped = seeded_detector(start).await;+ let mut at = start;+ while at < start + week {+ at += 30.0 * 60.0;+ stepped.rebuild(at).await.unwrap();+ }+ 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]+fn a_row_is_rewritten_for_what_a_reader_would_see() {+ let held = 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: 2.0,+ state: FacetState::Active,+ stability: 1.6,+ user_state: UserState::Auto,+ evidence_refs: Vec::new(),+ class: Some("style".into()),+ cue_families: None,+ };+ let drifted = ProfileFacet {+ confidence: 0.8 - REWRITE_TOLERANCE / 2.0,+ stability: 1.6 - REWRITE_TOLERANCE / 2.0,+ last_seen_at: 99.0,+ ..held.clone()+ };+ assert!(!worth_rewriting(&held, &drifted), "a hair of decay");+ let decayed = ProfileFacet {+ confidence: 0.8 - REWRITE_TOLERANCE,+ ..held.clone()+ };+ assert!(worth_rewriting(&held, &decayed));+ let demoted = ProfileFacet {+ state: FacetState::Provisional,+ ..held.clone()+ };+ assert!(worth_rewriting(&held, &demoted));+ let reinforced = ProfileFacet {+ evidence_count: 6,+ ..held+ };+ assert!(worth_rewriting(&drifted, &reinforced));+}