Skip to content

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

feat(embedding_host): add factory tests for embedding host

Steven Enamakele80c143a2615
diff --git a/crates/openhuman-core/src/inference/embedding_host/factory_tests.rs b/crates/openhuman-core/src/inference/embedding_host/factory_tests.rs
index a9cad508ff..3c8a8cc0ce 100644
--- a/crates/openhuman-core/src/inference/embedding_host/factory_tests.rs
+++ b/crates/openhuman-core/src/inference/embedding_host/factory_tests.rs
@@ -288,214 +288,3 @@ async fn default_embedder_honors_configured_local_provider() {
assert_eq!(vectors.first().map(|v| v.len()), Some(3));
assert_eq!(*hit.count.lock().unwrap(), 1);
}
-
-/// End-to-end binding proof (#5356): a provider built **through
-/// `create_embedding_provider_with_config`** must authenticate with the
-/// `app-session` token stored under the *config* credential scope. A local
-/// mock stands in for the cloud backend (no external network) and captures
-/// the bearer it receives. A regression to `OpenHumanCloudEmbedding::new(None,
-/// None, true, …)` would resolve the token from `default_state_dir()` — a
-/// different directory with no token — and fail with "No backend session"
-/// before any request, so this test fails if the factory ignores `config`.
-#[tokio::test]
-async fn factory_managed_provider_authenticates_with_config_scoped_token() {
- use std::sync::{Arc, Mutex};
-
- use axum::{extract::State, http::HeaderMap, routing::post, Json, Router};
-
- // Mock cloud embeddings backend at {BACKEND_URL}/openai/v1/embeddings.
- #[derive(Clone, Default)]
- struct Captured {
- auth: Arc<Mutex<Option<String>>>,
- }
- let captured = Captured::default();
- let app = Router::new()
- .route(
- "/openai/v1/embeddings",
- post(
- |State(cap): State<Captured>,
- headers: HeaderMap,
- Json(_body): Json<serde_json::Value>| async move {
- *cap.auth.lock().unwrap() = headers
- .get("authorization")
- .and_then(|v| v.to_str().ok())
- .map(str::to_owned);
- Json(serde_json::json!({
- "object": "list",
- "data": [{ "object": "embedding", "index": 0, "embedding": [0.1_f32, 0.2, 0.3] }],
- "model": "voyage-3-large",
- }))
- },
- ),
- )
- .with_state(captured.clone());
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let base = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
- tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
-
- // The app-session token lives ONLY under the config credential scope.
- let tmp = TempDir::new().unwrap();
- let config = test_config(&tmp);
- AuthService::from_config(&config)
- .store_provider_token(
- APP_SESSION_PROVIDER,
- "default",
- "sess-scoped-5356",
- HashMap::new(),
- true,
- )
- .unwrap();
-
- // The managed base URL comes from the backend transport, which (the
- // `cfg(test)` plain one here) honours `config.api_url`: point it at the mock.
- let config = Config {
- api_url: Some(base.clone()),
- ..config
- };
- let provider =
- create_embedding_provider_with_config(&config, "managed", "voyage-3-large", 3, "", None)
- .expect("managed provider builds via config-aware factory");
-
- // Embed: the lazy bearer resolver reads the config scope, finds the
- // token, and authenticates to the mock.
- let vectors = provider
- .embed(&["binding probe".to_string()])
- .await
- .expect("factory-built managed provider must resolve the config-scoped token and embed");
- assert_eq!(vectors.first().map(|v| v.len()).unwrap_or(0), 3);
- assert_eq!(
- captured.auth.lock().unwrap().as_deref(),
- Some("Bearer sess-scoped-5356"),
- "managed provider must authenticate with the token from the config scope"
- );
-}
-
-/// #5501 regression: the memory client's inline embedder is built through
-/// [`default_embedding_provider_with_config`], which MUST authenticate with
-/// the `app-session` token under the *config* credential scope — the same
-/// scope "Test connection" uses. The removed pre-fix keyless constructor
-/// resolved `default_state_dir()` with
-/// encryption forced on, so a signed-in user's ingested documents embedded
-/// with "No backend session" and persisted vector-less while the connection
-/// test still passed. A local mock stands in for the cloud backend (no
-/// network) and captures the bearer it receives; a regression back to the
-/// keyless constructor resolves a scope with no token and never reaches it.
-#[tokio::test]
-async fn default_provider_with_config_authenticates_with_config_scoped_token() {
- use std::sync::{Arc, Mutex};
-
- use axum::{extract::State, http::HeaderMap, routing::post, Json, Router};
-
- #[derive(Clone, Default)]
- struct Captured {
- auth: Arc<Mutex<Option<String>>>,
- }
- let captured = Captured::default();
- let app = Router::new()
- .route(
- "/openai/v1/embeddings",
- post(
- |State(cap): State<Captured>,
- headers: HeaderMap,
- Json(_body): Json<serde_json::Value>| async move {
- *cap.auth.lock().unwrap() = headers
- .get("authorization")
- .and_then(|v| v.to_str().ok())
- .map(str::to_owned);
- // The embedder validates returned dims against the
- // requested default, so the mock must echo that width.
- let embedding = vec![0.1_f32; DEFAULT_CLOUD_EMBEDDING_DIMENSIONS];
- Json(serde_json::json!({
- "object": "list",
- "data": [{ "object": "embedding", "index": 0, "embedding": embedding }],
- "model": DEFAULT_CLOUD_EMBEDDING_MODEL,
- }))
- },
- ),
- )
- .with_state(captured.clone());
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let base = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
- tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
-
- // The app-session token lives ONLY under the config credential scope.
- let tmp = TempDir::new().unwrap();
- let config = test_config(&tmp);
- AuthService::from_config(&config)
- .store_provider_token(
- APP_SESSION_PROVIDER,
- "default",
- "sess-default-5501",
- HashMap::new(),
- true,
- )
- .unwrap();
-
- let config = Config {
- api_url: Some(base.clone()),
- ..config
- };
- let provider = default_embedding_provider_with_config(&config);
-
- let vectors = provider
- .embed(&["binding probe".to_string()])
- .await
- .expect("config-scoped default embedder must resolve the app-session token and embed");
- assert_eq!(
- vectors.first().map(|v| v.len()).unwrap_or(0),
- DEFAULT_CLOUD_EMBEDDING_DIMENSIONS
- );
- assert_eq!(
- captured.auth.lock().unwrap().as_deref(),
- Some("Bearer sess-default-5501"),
- "the memory client's default embedder must authenticate with the config-scoped token"
- );
-}
-
-/// The factory path a chat turn takes: the managed model it builds for a chat
-/// discloses its cloud egress to that chat, and the same factory without a chat
-/// discloses unrouted.
-#[tokio::test]
-async fn a_managed_provider_built_for_a_chat_turn_discloses_to_that_chat() {
- crate::core::bus::init().await.expect("bus init");
- let mut rx = crate::core::bus::BUS.get().unwrap().receiver();
- let tmp = TempDir::new().unwrap();
- let mut config = test_config(&tmp);
- config.api_url = Some("http://127.0.0.1:0".into());
- let marker = "factory-embed-for-a-chat";
- let chat = crate::security::approval::ApprovalChatContext {
- thread_id: "thread-factory".into(),
- client_id: "client-factory".into(),
- request_id: Some("req-factory".into()),
- };
-
- let routed = create_embedding_provider_for_chat(
- &config,
- "managed",
- marker,
- DEFAULT_CLOUD_EMBEDDING_DIMENSIONS,
- "",
- None,
- Some(chat),
- )
- .unwrap();
- let _ = routed.embed(&["hello".to_string()]).await;
-
- loop {
- match rx.recv().await {
- Some(crate::core::events::DomainEvent::ExternalTransferPending {
- descriptor,
- thread_id,
- client_id,
- request_id,
- }) if descriptor.service == marker => {
- assert_eq!(thread_id.as_deref(), Some("thread-factory"));
- assert_eq!(client_id.as_deref(), Some("client-factory"));
- assert_eq!(request_id.as_deref(), Some("req-factory"));
- break;
- }
- Some(_) => continue,
- None => panic!("the bus closed before the disclosure arrived"),
- }
- }
-}
diff --git a/crates/openhuman-core/src/inference/embedding_host/removed_factory_tests.tmp b/crates/openhuman-core/src/inference/embedding_host/removed_factory_tests.tmp
new file mode 100644
index 0000000000..2e0f851080
--- /dev/null
+++ b/crates/openhuman-core/src/inference/embedding_host/removed_factory_tests.tmp
@@ -0,0 +1,210 @@
+/// End-to-end binding proof (#5356): a provider built **through
+/// `create_embedding_provider_with_config`** must authenticate with the
+/// `app-session` token stored under the *config* credential scope. A local
+/// mock stands in for the cloud backend (no external network) and captures
+/// the bearer it receives. A regression to `OpenHumanCloudEmbedding::new(None,
+/// None, true, …)` would resolve the token from `default_state_dir()` — a
+/// different directory with no token — and fail with "No backend session"
+/// before any request, so this test fails if the factory ignores `config`.
+#[tokio::test]
+async fn factory_managed_provider_authenticates_with_config_scoped_token() {
+ use std::sync::{Arc, Mutex};
+
+ use axum::{extract::State, http::HeaderMap, routing::post, Json, Router};
+
+ // Mock cloud embeddings backend at {BACKEND_URL}/openai/v1/embeddings.
+ #[derive(Clone, Default)]
+ struct Captured {
+ auth: Arc<Mutex<Option<String>>>,
+ }
+ let captured = Captured::default();
+ let app = Router::new()
+ .route(
+ "/openai/v1/embeddings",
+ post(
+ |State(cap): State<Captured>,
+ headers: HeaderMap,
+ Json(_body): Json<serde_json::Value>| async move {
+ *cap.auth.lock().unwrap() = headers
+ .get("authorization")
+ .and_then(|v| v.to_str().ok())
+ .map(str::to_owned);
+ Json(serde_json::json!({
+ "object": "list",
+ "data": [{ "object": "embedding", "index": 0, "embedding": [0.1_f32, 0.2, 0.3] }],
+ "model": "voyage-3-large",
+ }))
+ },
+ ),
+ )
+ .with_state(captured.clone());
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+
+ // The app-session token lives ONLY under the config credential scope.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ AuthService::from_config(&config)
+ .store_provider_token(
+ APP_SESSION_PROVIDER,
+ "default",
+ "sess-scoped-5356",
+ HashMap::new(),
+ true,
+ )
+ .unwrap();
+
+ // The managed base URL comes from the backend transport, which (the
+ // `cfg(test)` plain one here) honours `config.api_url`: point it at the mock.
+ let config = Config {
+ api_url: Some(base.clone()),
+ ..config
+ };
+ let provider =
+ create_embedding_provider_with_config(&config, "managed", "voyage-3-large", 3, "", None)
+ .expect("managed provider builds via config-aware factory");
+
+ // Embed: the lazy bearer resolver reads the config scope, finds the
+ // token, and authenticates to the mock.
+ let vectors = provider
+ .embed(&["binding probe".to_string()])
+ .await
+ .expect("factory-built managed provider must resolve the config-scoped token and embed");
+ assert_eq!(vectors.first().map(|v| v.len()).unwrap_or(0), 3);
+ assert_eq!(
+ captured.auth.lock().unwrap().as_deref(),
+ Some("Bearer sess-scoped-5356"),
+ "managed provider must authenticate with the token from the config scope"
+ );
+}
+
+/// #5501 regression: the memory client's inline embedder is built through
+/// [`default_embedding_provider_with_config`], which MUST authenticate with
+/// the `app-session` token under the *config* credential scope — the same
+/// scope "Test connection" uses. The removed pre-fix keyless constructor
+/// resolved `default_state_dir()` with
+/// encryption forced on, so a signed-in user's ingested documents embedded
+/// with "No backend session" and persisted vector-less while the connection
+/// test still passed. A local mock stands in for the cloud backend (no
+/// network) and captures the bearer it receives; a regression back to the
+/// keyless constructor resolves a scope with no token and never reaches it.
+#[tokio::test]
+async fn default_provider_with_config_authenticates_with_config_scoped_token() {
+ use std::sync::{Arc, Mutex};
+
+ use axum::{extract::State, http::HeaderMap, routing::post, Json, Router};
+
+ #[derive(Clone, Default)]
+ struct Captured {
+ auth: Arc<Mutex<Option<String>>>,
+ }
+ let captured = Captured::default();
+ let app = Router::new()
+ .route(
+ "/openai/v1/embeddings",
+ post(
+ |State(cap): State<Captured>,
+ headers: HeaderMap,
+ Json(_body): Json<serde_json::Value>| async move {
+ *cap.auth.lock().unwrap() = headers
+ .get("authorization")
+ .and_then(|v| v.to_str().ok())
+ .map(str::to_owned);
+ // The embedder validates returned dims against the
+ // requested default, so the mock must echo that width.
+ let embedding = vec![0.1_f32; DEFAULT_CLOUD_EMBEDDING_DIMENSIONS];
+ Json(serde_json::json!({
+ "object": "list",
+ "data": [{ "object": "embedding", "index": 0, "embedding": embedding }],
+ "model": DEFAULT_CLOUD_EMBEDDING_MODEL,
+ }))
+ },
+ ),
+ )
+ .with_state(captured.clone());
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+
+ // The app-session token lives ONLY under the config credential scope.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ AuthService::from_config(&config)
+ .store_provider_token(
+ APP_SESSION_PROVIDER,
+ "default",
+ "sess-default-5501",
+ HashMap::new(),
+ true,
+ )
+ .unwrap();
+
+ let config = Config {
+ api_url: Some(base.clone()),
+ ..config
+ };
+ let provider = default_embedding_provider_with_config(&config);
+
+ let vectors = provider
+ .embed(&["binding probe".to_string()])
+ .await
+ .expect("config-scoped default embedder must resolve the app-session token and embed");
+ assert_eq!(
+ vectors.first().map(|v| v.len()).unwrap_or(0),
+ DEFAULT_CLOUD_EMBEDDING_DIMENSIONS
+ );
+ assert_eq!(
+ captured.auth.lock().unwrap().as_deref(),
+ Some("Bearer sess-default-5501"),
+ "the memory client's default embedder must authenticate with the config-scoped token"
+ );
+}
+
+/// The factory path a chat turn takes: the managed model it builds for a chat
+/// discloses its cloud egress to that chat, and the same factory without a chat
+/// discloses unrouted.
+#[tokio::test]
+async fn a_managed_provider_built_for_a_chat_turn_discloses_to_that_chat() {
+ crate::core::bus::init().await.expect("bus init");
+ let mut rx = crate::core::bus::BUS.get().unwrap().receiver();
+ let tmp = TempDir::new().unwrap();
+ let mut config = test_config(&tmp);
+ config.api_url = Some("http://127.0.0.1:0".into());
+ let marker = "factory-embed-for-a-chat";
+ let chat = crate::security::approval::ApprovalChatContext {
+ thread_id: "thread-factory".into(),
+ client_id: "client-factory".into(),
+ request_id: Some("req-factory".into()),
+ };
+
+ let routed = create_embedding_provider_for_chat(
+ &config,
+ "managed",
+ marker,
+ DEFAULT_CLOUD_EMBEDDING_DIMENSIONS,
+ "",
+ None,
+ Some(chat),
+ )
+ .unwrap();
+ let _ = routed.embed(&["hello".to_string()]).await;
+
+ loop {
+ match rx.recv().await {
+ Some(crate::core::events::DomainEvent::ExternalTransferPending {
+ descriptor,
+ thread_id,
+ client_id,
+ request_id,
+ }) if descriptor.service == marker => {
+ assert_eq!(thread_id.as_deref(), Some("thread-factory"));
+ assert_eq!(client_id.as_deref(), Some("client-factory"));
+ assert_eq!(request_id.as_deref(), Some("req-factory"));
+ break;
+ }
+ Some(_) => continue,
+ None => panic!("the bus closed before the disclosure arrived"),
+ }
+ }
+}