Skip to content

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

fix(learning): validate facet class against the taxonomy across learning_*\n\nlearning.list_facets accepted any class string (class="nonsense" returned an\nempty page with no error) and its filter had a redundant key-prefix arm. The\nclass column is always derived from the key prefix, so the reported cross-class\nleak was not reachable, but the family validated class PRESENCE and never its\nVALUE — inconsistent and silent on typos.\n\nAdd parse_facet_class_name (delegating to the existing class_from_key taxonomy)\nand validate the caller-supplied class in every learning_* handler and its\nagent-tool mirror (list/get/update/pin/unpin/forget), rejecting an unknown class\nwith a structured error. Drop the redundant || key.starts_with filter arm so\nlist_facets filters on the class column alone.\n\nFixes #6077\n

shanubaa1f8110a48
diff --git a/src/openhuman/agent/learning/cache.rs b/src/openhuman/agent/learning/cache.rs
index 429963d205..b6d4b589fe 100644
--- a/src/openhuman/agent/learning/cache.rs
+++ b/src/openhuman/agent/learning/cache.rs
@@ -147,6 +147,21 @@ pub fn class_from_key(key: &str) -> Option<FacetClass> {
}
}
+/// Validate a caller-supplied class **name** against the facet taxonomy.
+///
+/// The learning RPC handlers and agent tools take `class` as a bare taxonomy
+/// name (`"style"`, `"goal"`, …), not a full key. Reuse [`class_from_key`],
+/// which matches on the first `/`-segment, so a bare name is validated as its
+/// own prefix and an unknown name is rejected with a caller-facing error rather
+/// than silently composing a key no facet can ever carry.
+pub(crate) fn parse_facet_class_name(class: &str) -> Result<FacetClass, String> {
+ class_from_key(class).ok_or_else(|| {
+ format!(
+ "invalid class `{class}` (expected one of style, identity, tooling, veto, goal, channel)"
+ )
+ })
+}
+
/// Delete every non-`Pinned` facet, returning `(deleted, pinned_preserved)`.
///
/// Shared by the `learning.reset_cache` RPC and the `learning_reset_cache`
diff --git a/src/openhuman/agent/learning/cache_tests.rs b/src/openhuman/agent/learning/cache_tests.rs
index a583a6d3df..c951b42135 100644
--- a/src/openhuman/agent/learning/cache_tests.rs
+++ b/src/openhuman/agent/learning/cache_tests.rs
@@ -81,6 +81,71 @@ fn class_from_key_parses_known_classes() {
assert_eq!(class_from_key("no_slash"), None);
}
+// ── parse_facet_class_name ────────────────────────────────────────────────────
+
+#[test]
+fn parse_facet_class_name_accepts_every_taxonomy_name() {
+ assert_eq!(parse_facet_class_name("style"), Ok(FacetClass::Style));
+ assert_eq!(parse_facet_class_name("identity"), Ok(FacetClass::Identity));
+ assert_eq!(parse_facet_class_name("tooling"), Ok(FacetClass::Tooling));
+ assert_eq!(parse_facet_class_name("veto"), Ok(FacetClass::Veto));
+ assert_eq!(parse_facet_class_name("goal"), Ok(FacetClass::Goal));
+ assert_eq!(parse_facet_class_name("channel"), Ok(FacetClass::Channel));
+}
+
+#[test]
+fn parse_facet_class_name_rejects_unknown_class() {
+ let err = parse_facet_class_name("nonsense").expect_err("unknown class must be rejected");
+ assert!(err.contains("invalid class `nonsense`"), "got: {err}");
+ // Lists the accepted taxonomy so the caller can recover.
+ assert!(
+ err.contains("style, identity, tooling, veto, goal, channel"),
+ "got: {err}"
+ );
+}
+
+// ── class filter is column-only (#6077) ───────────────────────────────────────
+//
+// `list_facets` filters on the `class` column alone; the redundant
+// `|| key.starts_with("{class}/")` arm was dropped. This proves the two are not
+// equivalent when they disagree: a valid class returns exactly the rows whose
+// `class` column matches, and a key-prefix that does not match the column is
+// excluded.
+#[tokio::test]
+async fn class_filter_matches_column_not_key_prefix() {
+ let cache = make_cache();
+
+ // Two facets whose class column is genuinely `style`.
+ let mut a = stub_facet("f1", "style/verbosity", "terse", FacetState::Active, 1.8);
+ a.class = Some("style".into());
+ let mut b = stub_facet("f2", "style/tone", "formal", FacetState::Active, 0.9);
+ b.class = Some("style".into());
+ // A facet whose key prefix reads "style/" but whose class column is `goal` —
+ // the old `starts_with` arm would have wrongly matched this under a `style`
+ // filter; the column-only rule must not.
+ let mut c = stub_facet("f3", "style/mislabelled", "x", FacetState::Active, 0.5);
+ c.class = Some("goal".into());
+
+ cache.upsert(&a).await.unwrap();
+ cache.upsert(&b).await.unwrap();
+ cache.upsert(&c).await.unwrap();
+
+ // The same predicate list_facets now applies: class column only.
+ let all = cache.list_all().await.unwrap();
+ let matched: Vec<&str> = all
+ .iter()
+ .filter(|f| f.state == FacetState::Active)
+ .filter(|f| f.class.as_deref() == Some("style"))
+ .map(|f| f.key.as_str())
+ .collect();
+
+ assert_eq!(matched, vec!["style/verbosity", "style/tone"]);
+ assert!(
+ !matched.contains(&"style/mislabelled"),
+ "column-only filter must exclude a key-prefix match with a different class column"
+ );
+}
+
// ── set_user_state_pinned_persists ────────────────────────────────────────────
#[tokio::test]
diff --git a/src/openhuman/agent/learning/schemas_part_02.rs b/src/openhuman/agent/learning/schemas_part_02.rs
index 5825d14160..0a10ee9898 100644
--- a/src/openhuman/agent/learning/schemas_part_02.rs
+++ b/src/openhuman/agent/learning/schemas_part_02.rs
@@ -12,6 +12,13 @@ fn handle_list_facets(params: Map<String, Value>) -> ControllerFuture {
.and_then(Value::as_str)
.map(str::to_string);
+ // Reject an unknown class before touching the store, so a filter that
+ // could never match a facet is surfaced as an error instead of an
+ // empty result the caller cannot distinguish from "nothing learned".
+ if let Some(cls) = &class_filter {
+ crate::openhuman::agent::learning::cache::parse_facet_class_name(cls)?;
+ }
+
let cache = get_cache().await?;
// list_all returns all states (active + provisional + candidate + dropped).
@@ -27,11 +34,12 @@ fn handle_list_facets(params: Map<String, Value>) -> ControllerFuture {
f.state == FacetState::Active || f.state == FacetState::Provisional
})
.filter(|f| {
- if let Some(cls) = &class_filter {
- f.class.as_deref() == Some(cls.as_str())
- || f.key.starts_with(&format!("{cls}/"))
- } else {
- true
+ // Filter on the class column only — it is always derived from
+ // the key prefix, so the old `|| key.starts_with(...)` arm was
+ // redundant.
+ match &class_filter {
+ Some(cls) => f.class.as_deref() == Some(cls.as_str()),
+ None => true,
}
})
.map(facet_to_json)
@@ -63,6 +71,8 @@ fn handle_get_facet(params: Map<String, Value>) -> ControllerFuture {
.ok_or_else(|| "missing required `key`".to_string())?
.to_string();
+ crate::openhuman::agent::learning::cache::parse_facet_class_name(&class_str)?;
+
let fk = full_key(&class_str, &key_suffix);
tracing::debug!("[learning.get_facet] key={fk}");
@@ -105,6 +115,8 @@ fn handle_update_facet(params: Map<String, Value>) -> ControllerFuture {
.ok_or_else(|| "missing required `value`".to_string())?
.to_string();
+ crate::openhuman::agent::learning::cache::parse_facet_class_name(&class_str)?;
+
let fk = full_key(&class_str, &key_suffix);
tracing::debug!("[learning.update_facet] key={fk} value={new_value}");
@@ -156,6 +168,8 @@ fn handle_pin_facet(params: Map<String, Value>) -> ControllerFuture {
.ok_or_else(|| "missing required `key`".to_string())?
.to_string();
+ crate::openhuman::agent::learning::cache::parse_facet_class_name(&class_str)?;
+
let fk = full_key(&class_str, &key_suffix);
tracing::debug!("[learning.pin_facet] key={fk}");
@@ -198,6 +212,8 @@ fn handle_unpin_facet(params: Map<String, Value>) -> ControllerFuture {
.ok_or_else(|| "missing required `key`".to_string())?
.to_string();
+ crate::openhuman::agent::learning::cache::parse_facet_class_name(&class_str)?;
+
let fk = full_key(&class_str, &key_suffix);
tracing::debug!("[learning.unpin_facet] key={fk}");
@@ -240,6 +256,8 @@ fn handle_forget_facet(params: Map<String, Value>) -> ControllerFuture {
.ok_or_else(|| "missing required `key`".to_string())?
.to_string();
+ crate::openhuman::agent::learning::cache::parse_facet_class_name(&class_str)?;
+
let fk = full_key(&class_str, &key_suffix);
tracing::debug!("[learning.forget_facet] key={fk}");
diff --git a/src/openhuman/agent/learning/schemas_tests.rs b/src/openhuman/agent/learning/schemas_tests.rs
index 59f15a1a50..0989af68d1 100644
--- a/src/openhuman/agent/learning/schemas_tests.rs
+++ b/src/openhuman/agent/learning/schemas_tests.rs
@@ -141,3 +141,54 @@ fn reset_cache_schema_shape() {
assert!(s.outputs.iter().any(|f| f.name == "deleted"));
assert!(s.outputs.iter().any(|f| f.name == "pinned_preserved"));
}
+
+// ── strict class validation (#6077) ───────────────────────────────────────────
+//
+// The class filter/argument is validated before the handler touches the store,
+// so an unknown class is rejected without a bound memory guard — which is what
+// lets these run as plain unit tests. On the old code `list_facets` with an
+// unknown class returned `{facets:[],count:0}`; it must now be an error.
+
+fn params_with_class(class: &str) -> Map<String, Value> {
+ let mut m = Map::new();
+ m.insert("class".to_string(), Value::String(class.to_string()));
+ m
+}
+
+#[tokio::test]
+async fn list_facets_rejects_unknown_class() {
+ let err = handle_list_facets(params_with_class("nonsense"))
+ .await
+ .expect_err("unknown class must be an error, not an empty result");
+ assert!(err.contains("invalid class `nonsense`"), "got: {err}");
+}
+
+#[tokio::test]
+async fn get_facet_rejects_unknown_class() {
+ let mut params = params_with_class("nonsense");
+ params.insert("key".to_string(), Value::String("verbosity".to_string()));
+ let err = handle_get_facet(params)
+ .await
+ .expect_err("unknown class must be rejected before store access");
+ assert!(err.contains("invalid class `nonsense`"), "got: {err}");
+}
+
+#[tokio::test]
+async fn forget_facet_rejects_unknown_class() {
+ let mut params = params_with_class("nonsense");
+ params.insert("key".to_string(), Value::String("verbosity".to_string()));
+ let err = handle_forget_facet(params)
+ .await
+ .expect_err("unknown class must be rejected before store access");
+ assert!(err.contains("invalid class `nonsense`"), "got: {err}");
+}
+
+#[tokio::test]
+async fn class_taking_handlers_keep_presence_check_before_value_check() {
+ // A missing class is still the presence error, not the invalid-class error —
+ // the new validation does not weaken the existing "missing required" contract.
+ let err = handle_get_facet(Map::new())
+ .await
+ .expect_err("missing class must error");
+ assert!(err.contains("missing required `class`"), "got: {err}");
+}
diff --git a/src/openhuman/agent/learning/tools.rs b/src/openhuman/agent/learning/tools.rs
index 825048aa2a..7792109b5e 100644
--- a/src/openhuman/agent/learning/tools.rs
+++ b/src/openhuman/agent/learning/tools.rs
@@ -42,6 +42,17 @@ fn full_key(class_str: &str, key_suffix: &str) -> String {
format!("{class_str}/{key_suffix}")
}
+/// Validate a caller-supplied class name against the facet taxonomy.
+///
+/// Mirrors the RPC handlers' strict check so the agent-tool surface rejects an
+/// unknown class instead of composing a key no facet can carry. Delegates to
+/// the shared taxonomy validator and lifts its string error into `anyhow`.
+fn validate_class(class_str: &str) -> anyhow::Result<()> {
+ crate::openhuman::agent::learning::cache::parse_facet_class_name(class_str)
+ .map(|_| ())
+ .map_err(|e| anyhow::anyhow!(e))
+}
+
fn facet_to_json(f: &ProfileFacet) -> serde_json::Value {
serde_json::to_value(f).unwrap_or(serde_json::Value::Null)
}
@@ -86,6 +97,11 @@ impl Tool for LearningListFacetsTool {
.get("class")
.and_then(serde_json::Value::as_str)
.map(str::to_string);
+ // Reject an unknown class before touching the store, so a filter that
+ // could never match a facet is an error rather than a silent empty list.
+ if let Some(cls) = &class_filter {
+ validate_class(cls)?;
+ }
let cache = get_cache().await?;
let all = cache
.list_all()
@@ -94,11 +110,10 @@ impl Tool for LearningListFacetsTool {
let facets: Vec<serde_json::Value> = all
.iter()
.filter(|f| f.state == FacetState::Active || f.state == FacetState::Provisional)
+ // Filter on the class column only — it is always derived from the key
+ // prefix, so the old `|| key.starts_with(...)` arm was redundant.
.filter(|f| match &class_filter {
- Some(cls) => {
- f.class.as_deref() == Some(cls.as_str())
- || f.key.starts_with(&format!("{cls}/"))
- }
+ Some(cls) => f.class.as_deref() == Some(cls.as_str()),
None => true,
})
.map(facet_to_json)
@@ -143,6 +158,7 @@ impl Tool for LearningGetFacetTool {
log::debug!("[tool][learning] get_facet invoked");
let class_str = read_required_str(&args, "class")?;
let key_suffix = read_required_str(&args, "key")?;
+ validate_class(&class_str)?;
let fk = full_key(&class_str, &key_suffix);
let cache = get_cache().await?;
let facet = cache
@@ -248,6 +264,7 @@ impl Tool for LearningUpdateFacetTool {
let class_str = read_required_str(&args, "class")?;
let key_suffix = read_required_str(&args, "key")?;
let value = read_required_str(&args, "value")?;
+ validate_class(&class_str)?;
let fk = full_key(&class_str, &key_suffix);
let cache = get_cache().await?;
let mut facet = cache
@@ -275,6 +292,7 @@ async fn set_pin(
) -> anyhow::Result<ToolResult> {
let class_str = read_required_str(&args, "class")?;
let key_suffix = read_required_str(&args, "key")?;
+ validate_class(&class_str)?;
let fk = full_key(&class_str, &key_suffix);
let cache = get_cache().await?;
let updated = cache
@@ -388,6 +406,7 @@ impl Tool for LearningForgetFacetTool {
log::debug!("[tool][learning] forget_facet invoked");
let class_str = read_required_str(&args, "class")?;
let key_suffix = read_required_str(&args, "key")?;
+ validate_class(&class_str)?;
let fk = full_key(&class_str, &key_suffix);
let cache = get_cache().await?;
let facet_json = match cache
diff --git a/src/openhuman/agent/learning/tools_tests.rs b/src/openhuman/agent/learning/tools_tests.rs
index aaabab295f..1d09eecef0 100644
--- a/src/openhuman/agent/learning/tools_tests.rs
+++ b/src/openhuman/agent/learning/tools_tests.rs
@@ -46,3 +46,43 @@ async fn update_facet_requires_value() {
.expect_err("missing value");
assert!(err.to_string().contains("value"));
}
+
+// ── strict class validation (#6077) ───────────────────────────────────────────
+//
+// `validate_class` runs before `get_cache`, so an unknown class is rejected
+// without a bound memory guard — which is what lets these run as unit tests.
+
+#[test]
+fn validate_class_accepts_taxonomy_and_rejects_unknown() {
+ assert!(validate_class("style").is_ok());
+ assert!(validate_class("channel").is_ok());
+ let err = validate_class("nonsense").expect_err("unknown class must be rejected");
+ assert!(err.to_string().contains("invalid class `nonsense`"));
+}
+
+#[tokio::test]
+async fn list_facets_tool_rejects_unknown_class() {
+ let err = LearningListFacetsTool
+ .execute(json!({ "class": "nonsense" }))
+ .await
+ .expect_err("unknown class must be an error, not an empty list");
+ assert!(err.to_string().contains("invalid class `nonsense`"));
+}
+
+#[tokio::test]
+async fn get_facet_tool_rejects_unknown_class() {
+ let err = LearningGetFacetTool
+ .execute(json!({ "class": "nonsense", "key": "verbosity" }))
+ .await
+ .expect_err("unknown class must be rejected before store access");
+ assert!(err.to_string().contains("invalid class `nonsense`"));
+}
+
+#[tokio::test]
+async fn forget_facet_tool_rejects_unknown_class() {
+ let err = LearningForgetFacetTool
+ .execute(json!({ "class": "nonsense", "key": "verbosity" }))
+ .await
+ .expect_err("unknown class must be rejected before store access");
+ assert!(err.to_string().contains("invalid class `nonsense`"));
+}