Skip to content

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

fix(tinymemes): address review findings

killbillc9543ee7866f
diff --git a/crates/openhuman-core/src/tinymemes/arm.rs b/crates/openhuman-core/src/tinymemes/arm.rs
index 9c621bf407..0a198c6612 100644
--- a/crates/openhuman-core/src/tinymemes/arm.rs
+++ b/crates/openhuman-core/src/tinymemes/arm.rs
@@ -59,15 +59,15 @@ pub(crate) fn mode_from(value: Option<&str>) -> Mode {
"" | "off" | "0" | "false" | "no" => Mode::Off,
"on" | "1" | "true" | "yes" => Mode::On,
"ab" => Mode::Ab { percent: 50 },
- // Parsed wide, then capped: any numeric percentage above 100 means 100.
- other => match other
- .strip_prefix("ab:")
- .and_then(|p| p.trim().parse::<u64>().ok())
- {
- Some(percent) => Mode::Ab {
- percent: percent.min(100) as u8,
- },
- None => {
+ // Any all-digit percentage above 100 means 100, including one too
+ // large for `u64`.
+ other => match other.strip_prefix("ab:").map(str::trim) {
+ Some(digits) if !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) => {
+ Mode::Ab {
+ percent: digits.parse::<u64>().map_or(100, |n| n.min(100)) as u8,
+ }
+ }
+ _ => {
log::warn!("[tinymemes] unrecognised {FLAG_ENV} value; treating as off");
Mode::Off
}
diff --git a/crates/openhuman-core/src/tinymemes/arm_tests.rs b/crates/openhuman-core/src/tinymemes/arm_tests.rs
index ae630d1d45..a8612684ea 100644
--- a/crates/openhuman-core/src/tinymemes/arm_tests.rs
+++ b/crates/openhuman-core/src/tinymemes/arm_tests.rs
@@ -10,6 +10,11 @@ fn flag_values_parse() {
assert_eq!(mode_from(Some("ab:20")), Mode::Ab { percent: 20 });
assert_eq!(mode_from(Some("ab:300")), Mode::Ab { percent: 100 });
assert_eq!(mode_from(Some("ab:99999")), Mode::Ab { percent: 100 });
+ assert_eq!(
+ mode_from(Some("ab:18446744073709551616")),
+ Mode::Ab { percent: 100 }
+ );
+ assert_eq!(mode_from(Some("ab:")), Mode::Off);
assert_eq!(mode_from(Some("ab:-5")), Mode::Off);
assert_eq!(mode_from(Some("ab:250")), Mode::Ab { percent: 100 });
assert_eq!(mode_from(Some("ab:100")), Mode::Ab { percent: 100 });
@@ -38,7 +43,7 @@ fn assignment_is_stable_and_respects_the_split() {
fn bucket_is_fixed_across_builds() {
// FNV-1a is specified, so this value must never change; a change would
// silently move live threads between arms.
- assert_eq!(bucket("thread-abc"), bucket("thread-abc"));
+ assert_eq!(bucket("thread-abc"), 56);
assert_eq!(bucket(""), (0xcbf2_9ce4_8422_2325_u64 % 100) as u8);
}
diff --git a/crates/openhuman-core/src/tinymemes/host.rs b/crates/openhuman-core/src/tinymemes/host.rs
index 9c59188c06..d891703324 100644
--- a/crates/openhuman-core/src/tinymemes/host.rs
+++ b/crates/openhuman-core/src/tinymemes/host.rs
@@ -40,6 +40,9 @@ pub(crate) struct Host {
pub(crate) engine: MemeEngine,
dir: PathBuf,
remixed: Mutex<VecDeque<String>>,
+ /// Held across each index snapshot and its write, so concurrent saves land
+ /// in order and an older snapshot never replaces a newer one.
+ persist: Mutex<()>,
/// What the engine was built from; a change rebuilds it.
fingerprint: u64,
}
@@ -290,6 +293,7 @@ impl Host {
engine,
dir,
remixed: Mutex::new(remixed),
+ persist: Mutex::new(()),
fingerprint,
}
}
@@ -302,22 +306,23 @@ impl Host {
.any(|id| id == message_id)
}
+ /// Record a delivered remix. The list stays locked through the write, so
+ /// concurrent calls persist in order.
pub(crate) fn mark_remixed(&self, message_id: String) {
- let snapshot = {
- let mut ids = self.remixed.lock().unwrap_or_else(|e| e.into_inner());
- if ids.contains(&message_id) {
- return;
- }
- ids.push_back(message_id);
- cap_remixed(&mut ids);
- serde_json::to_string(&*ids).unwrap_or_default()
- };
+ let mut ids = self.remixed.lock().unwrap_or_else(|e| e.into_inner());
+ if ids.contains(&message_id) {
+ return;
+ }
+ ids.push_back(message_id);
+ cap_remixed(&mut ids);
+ let snapshot = serde_json::to_string(&*ids).unwrap_or_default();
if let Err(e) = write_atomic(&self.dir.join(REMIXED_FILE), &snapshot) {
log::warn!("[tinymemes] cannot save remixed ids: {e}");
}
}
pub(crate) fn save_memes(&self) {
+ let _order = self.persist.lock().unwrap_or_else(|e| e.into_inner());
let json = self.engine.meme_index().to_json();
if let Err(e) = write_atomic(&self.dir.join(MEME_INDEX_FILE), &json) {
log::warn!("[tinymemes] cannot save meme index: {e}");
@@ -325,6 +330,7 @@ impl Host {
}
pub(crate) fn save_index(&self) {
+ let _order = self.persist.lock().unwrap_or_else(|e| e.into_inner());
let json = self.engine.slang_index().to_json();
if let Err(e) = write_atomic(&self.dir.join(INDEX_FILE), &json) {
log::warn!("[tinymemes] cannot save slang index: {e}");
diff --git a/crates/openhuman-core/src/tinymemes/mod.rs b/crates/openhuman-core/src/tinymemes/mod.rs
index 25226bf902..b3757905b3 100644
--- a/crates/openhuman-core/src/tinymemes/mod.rs
+++ b/crates/openhuman-core/src/tinymemes/mod.rs
@@ -227,7 +227,7 @@ async fn remix_with(
}
Err(e) => log::warn!("[tinymemes] slang research failed: {e}"),
}
- host.save_index();
+ persist(&host, |h| h.save_index()).await;
});
}
}
@@ -243,11 +243,12 @@ async fn remix_with(
let moment = user_message.to_owned();
crate::core::runtime::spawn_scoped(async move {
match host.engine.learn_memes(intent, &moment).await {
+ // The query is derived from the user's message, so it stays
+ // out of the log; only counters are recorded.
Ok(Some(r)) => log::info!(
- "[tinymemes] meme research request_id={request_id} query={:?} found={} \
+ "[tinymemes] meme research request_id={request_id} found={} \
added={} rejected_rating={} rejected_topic={} duplicates={} \
failed_jev={}",
- r.query,
r.found,
r.added,
r.rejected_rating,
@@ -260,15 +261,19 @@ async fn remix_with(
}
Err(e) => log::warn!("[tinymemes] meme research failed: {e}"),
}
- host.save_memes();
+ persist(&host, |h| h.save_memes()).await;
});
}
}
let result = if remixed {
- host.mark_remixed(crate::threads::store::run_reply_message_id(request_id));
- host.save_index();
- host.save_memes();
+ let id = crate::threads::store::run_reply_message_id(request_id);
+ persist(host, move |h| {
+ h.mark_remixed(id);
+ h.save_index();
+ h.save_memes();
+ })
+ .await;
"remixed"
} else if outcome.skipped.is_some() && outcome.rating.is_none() {
"error"
@@ -279,6 +284,18 @@ async fn remix_with(
remixed.then_some(outcome.reply)
}
+/// Run state-file writes on the blocking pool: they are synchronous
+/// serialization and file I/O, and must not stall an async worker.
+async fn persist(
+ host: &std::sync::Arc<host::Host>,
+ write: impl FnOnce(&host::Host) + Send + 'static,
+) {
+ let host = host.clone();
+ if let Err(e) = crate::core::runtime::spawn_blocking_scoped(move || write(&host)).await {
+ log::warn!("[tinymemes] state write task failed: {e}");
+ }
+}
+
fn log_outcome(
turn: &TurnInfo<'_>,
started: Instant,
diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rs
index e04fe3978c..915acf7b8c 100644
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@ -255,6 +255,10 @@ pub(crate) async fn run_chat_task(
}
}
};
+ // The agent turn's own duration for the TinyMemes A/B log, taken before
+ // reply speech so synthesis time is not counted as turn time.
+ #[cfg(feature = "tinymemes")]
+ let turn_elapsed = turn_started.elapsed();
if let Ok(ref task_result) = result {
let speak_reply = matches!(metadata.speak_reply, Some(true));
@@ -308,7 +312,7 @@ pub(crate) async fn run_chat_task(
message,
&mut task_result.full_response,
inference_budget_exceeded_user_message(),
- turn_started.elapsed(),
+ turn_elapsed,
)
.await;
}