Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(server): add request-scoped http profiling (#2125)

Jiahui Zhoue9e6ce5e9ad7
diff --git a/crates/ov_cli/src/base_client.rs b/crates/ov_cli/src/base_client.rs
index 15d6d9e1b..5a0a63a84 100644
--- a/crates/ov_cli/src/base_client.rs
+++ b/crates/ov_cli/src/base_client.rs
@@ -1,6 +1,7 @@
use reqwest::{Client as ReqwestClient, StatusCode};
use serde::de::DeserializeOwned;
use serde_json::Value;
+use std::any::TypeId;
use std::fs::File;
use std::path::Path;
use std::str::FromStr;
@@ -74,6 +75,31 @@ pub fn api_error_from_envelope(json: &Value, status: StatusCode) -> String {
}
}
+pub fn unwrap_success_envelope(json: Value, preserve_profile: bool) -> Value {
+ let Some(result) = json.get("result") else {
+ return json;
+ };
+
+ if !preserve_profile {
+ return result.clone();
+ }
+
+ let Some(profile) = json.get("profile") else {
+ return result.clone();
+ };
+
+ if let Some(result_obj) = result.as_object() {
+ let mut merged = result_obj.clone();
+ merged.insert("profile".to_string(), profile.clone());
+ return Value::Object(merged);
+ }
+
+ let mut wrapped = serde_json::Map::new();
+ wrapped.insert("result".to_string(), result.clone());
+ wrapped.insert("profile".to_string(), profile.clone());
+ Value::Object(wrapped)
+}
+
// ============ TimeoutConfig ============
/// Dynamic timeout calculator based on file size
@@ -120,6 +146,7 @@ pub struct BaseClient {
pub(crate) account: Option<String>,
pub(crate) user: Option<String>,
pub(crate) agent_id: Option<String>,
+ pub(crate) profile_enabled: bool,
pub(crate) extra_headers: Option<std::collections::HashMap<String, String>>,
}
@@ -138,6 +165,7 @@ impl BaseClient {
account: None,
user: None,
agent_id: None,
+ profile_enabled: false,
extra_headers: None,
}
}
@@ -149,6 +177,7 @@ impl BaseClient {
account: Option<String>,
user: Option<String>,
timeout_secs: f64,
+ profile_enabled: bool,
extra_headers: Option<std::collections::HashMap<String, String>>,
) -> Self {
let http = ReqwestClient::builder()
@@ -163,10 +192,19 @@ impl BaseClient {
account,
user,
agent_id,
+ profile_enabled,
extra_headers,
}
}
+ fn append_profile_query<'a>(&self, params: &'a [(String, String)]) -> Vec<(String, String)> {
+ let mut merged = params.to_vec();
+ if self.profile_enabled && !merged.iter().any(|(k, _)| k == "profile") {
+ merged.push(("profile".to_string(), "1".to_string()));
+ }
+ merged
+ }
+
pub fn base_url(&self) -> &str {
&self.base_url
}
@@ -221,7 +259,10 @@ impl BaseClient {
headers
}
- pub(crate) async fn handle_response<T: DeserializeOwned>(&self, response: reqwest::Response) -> Result<T> {
+ pub(crate) async fn handle_response<T: DeserializeOwned + 'static>(
+ &self,
+ response: reqwest::Response,
+ ) -> Result<T> {
let status = response.status();
if status == StatusCode::NO_CONTENT || status == StatusCode::ACCEPTED {
@@ -263,11 +304,8 @@ impl BaseClient {
}
}
- let result = if let Some(result) = json.get("result") {
- result.clone()
- } else {
- json.clone()
- };
+ let preserve_profile = TypeId::of::<T>() == TypeId::of::<Value>();
+ let result = unwrap_success_envelope(json.clone(), preserve_profile);
serde_json::from_value(result).map_err(|e| {
Error::Parse(format!(
@@ -296,17 +334,18 @@ impl BaseClient {
.map_err(|e| Error::Network(format!("Failed to build HTTP client: {}", e)))
}
- pub async fn get<T: DeserializeOwned>(
+ pub async fn get<T: DeserializeOwned + 'static>(
&self,
path: &str,
params: &[(String, String)],
) -> Result<T> {
let url = format!("{}{}", self.base_url, path);
+ let params = self.append_profile_query(params);
let response = self
.http
.get(&url)
.headers(self.build_headers())
- .query(params)
+ .query(&params)
.send()
.await
.map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
@@ -314,17 +353,23 @@ impl BaseClient {
self.handle_response(response).await
}
- pub async fn post<B: serde::Serialize, T: DeserializeOwned>(
+ pub async fn post<B: serde::Serialize, T: DeserializeOwned + 'static>(
&self,
path: &str,
body: &B,
) -> Result<T> {
let url = format!("{}{}", self.base_url, path);
- let response = self
+ let request = self
.http
.post(&url)
.headers(self.build_headers())
- .json(body)
+ .json(body);
+ let request = if self.profile_enabled {
+ request.query(&[("profile", "1")])
+ } else {
+ request
+ };
+ let response = request
.send()
.await
.map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
@@ -332,7 +377,7 @@ impl BaseClient {
self.handle_response(response).await
}
- pub async fn post_with_timeout<B: serde::Serialize, T: DeserializeOwned>(
+ pub async fn post_with_timeout<B: serde::Serialize, T: DeserializeOwned + 'static>(
&self,
path: &str,
body: &B,
@@ -341,10 +386,16 @@ impl BaseClient {
let url = format!("{}{}", self.base_url, path);
let client = self.create_client_with_timeout(timeout)?;
- let response = client
+ let request = client
.post(&url)
.headers(self.build_headers())
- .json(body)
+ .json(body);
+ let request = if self.profile_enabled {
+ request.query(&[("profile", "1")])
+ } else {
+ request
+ };
+ let response = request
.send()
.await
.map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
@@ -352,17 +403,23 @@ impl BaseClient {
self.handle_response(response).await
}
- pub async fn put<B: serde::Serialize, T: DeserializeOwned>(
+ pub async fn put<B: serde::Serialize, T: DeserializeOwned + 'static>(
&self,
path: &str,
body: &B,
) -> Result<T> {
let url = format!("{}{}", self.base_url, path);
- let response = self
+ let request = self
.http
.put(&url)
.headers(self.build_headers())
- .json(body)
+ .json(body);
+ let request = if self.profile_enabled {
+ request.query(&[("profile", "1")])
+ } else {
+ request
+ };
+ let response = request
.send()
.await
.map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
@@ -370,17 +427,18 @@ impl BaseClient {
self.handle_response(response).await
}
- pub async fn delete<T: DeserializeOwned>(
+ pub async fn delete<T: DeserializeOwned + 'static>(
&self,
path: &str,
params: &[(String, String)],
) -> Result<T> {
let url = format!("{}{}", self.base_url, path);
+ let params = self.append_profile_query(params);
let response = self
.http
.delete(&url)
.headers(self.build_headers())
- .query(params)
+ .query(&params)
.send()
.await
.map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
@@ -388,17 +446,23 @@ impl BaseClient {
self.handle_response(response).await
}
- pub async fn delete_with_body<B: serde::Serialize, T: DeserializeOwned>(
+ pub async fn delete_with_body<B: serde::Serialize, T: DeserializeOwned + 'static>(
&self,
path: &str,
body: &B,
) -> Result<T> {
let url = format!("{}{}", self.base_url, path);
- let response = self
+ let request = self
.http
.delete(&url)
.headers(self.build_headers())
- .json(body)
+ .json(body);
+ let request = if self.profile_enabled {
+ request.query(&[("profile", "1")])
+ } else {
+ request
+ };
+ let response = request
.send()
.await
.map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
@@ -406,18 +470,19 @@ impl BaseClient {
self.handle_response(response).await
}
- pub async fn patch<B: serde::Serialize, T: DeserializeOwned>(
+ pub async fn patch<B: serde::Serialize, T: DeserializeOwned + 'static>(
&self,
path: &str,
body: &B,
params: &[(String, String)],
) -> Result<T> {
let url = format!("{}{}", self.base_url, path);
+ let params = self.append_profile_query(params);
let response = self
.http
.patch(&url)
.headers(self.build_headers())
- .query(params)
+ .query(&params)
.json(body)
.send()
.await
@@ -426,18 +491,19 @@ impl BaseClient {
self.handle_response(response).await
}
- pub async fn post_with_query<B: serde::Serialize, T: DeserializeOwned>(
+ pub async fn post_with_query<B: serde::Serialize, T: DeserializeOwned + 'static>(
&self,
path: &str,
body: &B,
params: &[(String, String)],
) -> Result<T> {
let url = format!("{}{}", self.base_url, path);
+ let params = self.append_profile_query(params);
let response = self
.http
.post(&url)
.headers(self.build_headers())
- .query(params)
+ .query(&params)
.json(body)
.send()
.await
@@ -447,6 +513,121 @@ impl BaseClient {
}
}
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn unwrap_success_envelope_preserves_profile_for_value_results() {
+ let body = json!({
+ "status": "ok",
+ "result": [
+ {"id": "1"}
+ ],
+ "profile": [
+ "line one",
+ "line two"
+ ]
+ });
+
+ let result = unwrap_success_envelope(body, true);
+
+ assert_eq!(
+ result,
+ json!({
+ "result": [
+ {"id": "1"}
+ ],
+ "profile": [
+ "line one",
+ "line two"
+ ]
+ })
+ );
+ }
+
+ #[test]
+ fn unwrap_success_envelope_wraps_scalar_results_when_profile_is_preserved() {
+ let body = json!({
+ "status": "ok",
+ "result": "content",
+ "profile": [
+ "line one"
+ ]
+ });
+
+ let result = unwrap_success_envelope(body, true);
+
+ assert_eq!(
+ result,
+ json!({
+ "result": "content",
+ "profile": [
+ "line one"
+ ]
+ })
+ );
+ }
+
+ #[test]
+ fn unwrap_success_envelope_drops_profile_for_scalar_results() {
+ let body = json!({
+ "status": "ok",
+ "result": "content",
+ "profile": [
+ "line one"
+ ]
+ });
+
+ let result = unwrap_success_envelope(body, false);
+
+ assert_eq!(result, json!("content"));
+ }
+
+ #[test]
+ fn append_profile_query_adds_flag_when_enabled() {
+ let client = BaseClient::new(
+ "http://localhost:1933",
+ None,
+ None,
+ None,
+ None,
+ 5.0,
+ true,
+ None,
+ );
+
+ let params = client.append_profile_query(&[("to_uri".to_string(), "viking://x".to_string())]);
+
+ assert_eq!(
+ params,
+ vec![
+ ("to_uri".to_string(), "viking://x".to_string()),
+ ("profile".to_string(), "1".to_string()),
+ ]
+ );
+ }
+
+ #[test]
+ fn append_profile_query_keeps_existing_profile_flag() {
+ let client = BaseClient::new(
+ "http://localhost:1933",
+ None,
+ None,
+ None,
+ None,
+ 5.0,
+ true,
+ None,
+ );
+
+ let params = client.append_profile_query(&[("profile".to_string(), "1".to_string())]);
+
+ assert_eq!(params, vec![("profile".to_string(), "1".to_string())]);
+ }
+}
+
// ============ FileUploader ============
/// Handles file compression and upload logic
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index e0aef9ca2..c792d15d3 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -23,6 +23,7 @@ impl HttpClient {
account: Option<String>,
user: Option<String>,
timeout_secs: f64,
+ profile_enabled: bool,
extra_headers: Option<std::collections::HashMap<String, String>>,
) -> Self {
Self {
@@ -33,6 +34,7 @@ impl HttpClient {
account,
user,
timeout_secs,
+ profile_enabled,
extra_headers,
),
}
@@ -66,7 +68,7 @@ impl HttpClient {
// ============ HTTP Methods ============
- pub async fn get<T: DeserializeOwned>(
+ pub async fn get<T: DeserializeOwned + 'static>(
&self,
path: &str,
params: &[(String, String)],
@@ -74,7 +76,7 @@ impl HttpClient {
self.base.get(path, params).await
}
- pub async fn post<B: serde::Serialize, T: DeserializeOwned>(
+ pub async fn post<B: serde::Serialize, T: DeserializeOwned + 'static>(
&self,
path: &str,
body: &B,
@@ -82,7 +84,7 @@ impl HttpClient {
self.base.post(path, body).await
}
- pub async fn put<B: serde::Serialize, T: DeserializeOwned>(
+ pub async fn put<B: serde::Serialize, T: DeserializeOwned + 'static>(
&self,
path: &str,
body: &B,
@@ -90,7 +92,7 @@ impl HttpClient {
self.base.put(path, body).await
}
- pub async fn delete<T: DeserializeOwned>(
+ pub async fn delete<T: DeserializeOwned + 'static>(
&self,
path: &str,
params: &[(String, String)],
@@ -98,7 +100,7 @@ impl HttpClient {
self.base.delete(path, params).await
}
- pub async fn delete_with_body<B: serde::Serialize, T: DeserializeOwned>(
+ pub async fn delete_with_body<B: serde::Serialize, T: DeserializeOwned + 'static>(
&self,
path: &str,
body: &B,
@@ -106,7 +108,7 @@ impl HttpClient {
self.base.delete_with_body(path, body).await
}
- pub async fn patch<B: serde::Serialize, T: DeserializeOwned>(
+ pub async fn patch<B: serde::Serialize, T: DeserializeOwned + 'static>(
&self,
path: &str,
body: &B,
@@ -115,7 +117,7 @@ impl HttpClient {
self.base.patch(path, body, params).await
}
- pub async fn post_with_query<B: serde::Serialize, T: DeserializeOwned>(
+ pub async fn post_with_query<B: serde::Serialize, T: DeserializeOwned + 'static>(
&self,
path: &str,
body: &B,
@@ -168,16 +170,31 @@ impl HttpClient {
self.get("/api/v1/content/read", &params).await
}
+ pub async fn read_profiled(&self, uri: &str) -> Result<Value> {
+ let params = vec![("uri".to_string(), uri.to_string())];
+ self.get("/api/v1/content/read", &params).await
+ }
+
pub async fn abstract_content(&self, uri: &str) -> Result<String> {
let params = vec![("uri".to_string(), uri.to_string())];
self.get("/api/v1/content/abstract", &params).await
}
+ pub async fn abstract_content_profiled(&self, uri: &str) -> Result<Value> {
+ let params = vec![("uri".to_string(), uri.to_string())];
+ self.get("/api/v1/content/abstract", &params).await
+ }
+
pub async fn overview(&self, uri: &str) -> Result<String> {
let params = vec![("uri".to_string(), uri.to_string())];
self.get("/api/v1/content/overview", &params).await
}
+ pub async fn overview_profiled(&self, uri: &str) -> Result<Value> {
+ let params = vec![("uri".to_string(), uri.to_string())];
+ self.get("/api/v1/content/overview", &params).await
+ }
+
pub async fn write(
&self,
uri: &str,
@@ -225,7 +242,10 @@ impl HttpClient {
/// Download file as raw bytes
pub async fn get_bytes(&self, uri: &str) -> Result<Vec<u8>> {
let url = format!("{}/api/v1/content/download", self.base.base_url);
- let params = vec![("uri".to_string(), uri.to_string())];
+ let params = vec![
+ ("uri".to_string(), uri.to_string()),
+ ("profile".to_string(), "0".to_string()),
+ ];
let response = self
.base
@@ -316,13 +336,12 @@ impl HttpClient {
self.get("/api/v1/fs/tree", &params).await
}
- pub async fn mkdir(&self, uri: &str, description: Option<&str>) -> Result<()> {
+ pub async fn mkdir(&self, uri: &str, description: Option<&str>) -> Result<serde_json::Value> {
let body = match description {
Some(description) => serde_json::json!({ "uri": uri, "description": description }),
None => serde_json::json!({ "uri": uri }),
};
- let _: serde_json::Value = self.post("/api/v1/fs/mkdir", &body).await?;
- Ok(())
+ self.post("/api/v1/fs/mkdir", &body).await
}
pub async fn rm(&self, uri: &str, recursive: bool) -> Result<serde_json::Value> {
@@ -333,13 +352,12 @@ impl HttpClient {
self.delete("/api/v1/fs", &params).await
}
- pub async fn mv(&self, from_uri: &str, to_uri: &str) -> Result<()> {
+ pub async fn mv(&self, from_uri: &str, to_uri: &str) -> Result<serde_json::Value> {
let body = serde_json::json!({
"from_uri": from_uri,
"to_uri": to_uri,
});
- let _: serde_json::Value = self.post("/api/v1/fs/mv", &body).await?;
- Ok(())
+ self.post("/api/v1/fs/mv", &body).await
}
pub async fn stat(&self, uri: &str) -> Result<serde_json::Value> {
@@ -728,6 +746,7 @@ impl HttpClient {
.post(&url)
.headers(self.base.build_headers())
.json(&body)
+ .query(&[("profile", "0")])
.send()
.await
.map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
@@ -1175,6 +1194,7 @@ mod tests {
Some("acme".to_string()),
Some("alice".to_string()),
5.0,
+ true,
Some(extra_headers),
);
@@ -1233,4 +1253,48 @@ mod tests {
"[PROCESSING_ERROR] Parse error: boom"
);
}
+
+ #[test]
+ fn unwrap_result_preserves_profile_for_non_object_results() {
+ let body = json!({
+ "status": "ok",
+ "result": [
+ {"id": "1"}
+ ],
+ "profile": [
+ "line one",
+ "line two"
+ ]
+ });
+
+ let result = crate::base_client::unwrap_success_envelope(body, true);
+
+ assert_eq!(
+ result,
+ json!({
+ "result": [
+ {"id": "1"}
+ ],
+ "profile": [
+ "line one",
+ "line two"
+ ]
+ })
+ );
+ }
+
+ #[test]
+ fn unwrap_result_drops_profile_for_scalar_typed_results() {
+ let body = json!({
+ "status": "ok",
+ "result": "content",
+ "profile": [
+ "line one"
+ ]
+ });
+
+ let result = crate::base_client::unwrap_success_envelope(body, false);
+
+ assert_eq!(result, json!("content"));
+ }
}
diff --git a/crates/ov_cli/src/commands/content.rs b/crates/ov_cli/src/commands/content.rs
index 3e062a3dc..371b653d8 100644
--- a/crates/ov_cli/src/commands/content.rs
+++ b/crates/ov_cli/src/commands/content.rs
@@ -1,6 +1,7 @@
use crate::client::HttpClient;
use crate::error::Result;
use crate::output::OutputFormat;
+use serde_json::Value;
use std::fs::File;
use std::io::Write;
use std::path::Path;
@@ -8,34 +9,31 @@ use std::path::Path;
pub async fn read(
client: &HttpClient,
uri: &str,
- _output_format: OutputFormat,
- _compact: bool,
+ output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
- let content = client.read(uri).await?;
- println!("{}", content);
- Ok(())
+ let content = client.read_profiled(uri).await?;
+ output_content_result(content, output_format, compact)
}
pub async fn abstract_content(
client: &HttpClient,
uri: &str,
- _output_format: OutputFormat,
- _compact: bool,
+ output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
- let content = client.abstract_content(uri).await?;
- println!("{}", content);
- Ok(())
+ let content = client.abstract_content_profiled(uri).await?;
+ output_content_result(content, output_format, compact)
}
pub async fn overview(
client: &HttpClient,
uri: &str,
- _output_format: OutputFormat,
- _compact: bool,
+ output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
- let content = client.overview(uri).await?;
- println!("{}", content);
- Ok(())
+ let content = client.overview_profiled(uri).await?;
+ output_content_result(content, output_format, compact)
}
pub async fn write(
@@ -100,3 +98,52 @@ pub async fn get(client: &HttpClient, uri: &str, local_path: &str) -> Result<()>
println!("Downloaded {} bytes to {}", bytes.len(), local_path);
Ok(())
}
+
+fn output_content_result(result: Value, output_format: OutputFormat, compact: bool) -> Result<()> {
+ match output_format {
+ OutputFormat::Json => crate::output::output_success(result, output_format, compact),
+ OutputFormat::Table => {
+ if let Some(rendered) = crate::output::render_profiled_scalar_result(&result) {
+ println!("{}", rendered);
+ } else if let Some(content) = result.as_str() {
+ println!("{}", content);
+ } else {
+ crate::output::output_success(result, output_format, compact);
+ }
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ #[test]
+ fn table_output_renders_profiled_scalar_content() {
+ let result = json!({
+ "result": "content",
+ "profile": [
+ "line one",
+ "line two"
+ ]
+ });
+
+ let rendered = crate::output::render_profiled_scalar_result(&result);
+
+ assert_eq!(
+ rendered,
+ Some(
+ [
+ "content",
+ "",
+ "profile",
+ "line one",
+ "line two",
+ "",
+ ]
+ .join("\n")
+ )
+ );
+ }
+}
diff --git a/crates/ov_cli/src/commands/filesystem.rs b/crates/ov_cli/src/commands/filesystem.rs
index daa0c8f03..06216bc9a 100644
--- a/crates/ov_cli/src/commands/filesystem.rs
+++ b/crates/ov_cli/src/commands/filesystem.rs
@@ -58,11 +58,16 @@ pub async fn mkdir(
client: &HttpClient,
uri: &str,
description: Option<&str>,
- _output_format: OutputFormat,
- _compact: bool,
+ output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
- client.mkdir(uri, description).await?;
- println!("Directory created: {}", uri);
+ let result = client.mkdir(uri, description).await?;
+ output_message_result(
+ result,
+ format!("Directory created: {}", uri),
+ output_format,
+ compact,
+ );
Ok(())
}
@@ -70,17 +75,18 @@ pub async fn rm(
client: &HttpClient,
uri: &str,
recursive: bool,
- _output_format: OutputFormat,
- _compact: bool,
+ output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let result = client.rm(uri, recursive).await?;
- // Try to extract estimated_deleted_count if available
- if let Some(count) = result.get("estimated_deleted_count").and_then(|v| v.as_u64()) {
- println!("Removed: {} ({} items)", uri, count);
+ let message = if let Some(count) = result.get("estimated_deleted_count").and_then(|v| v.as_u64()) {
+ format!("Removed: {} ({} items)", uri, count)
} else {
- println!("Removed: {}", uri);
- }
+ format!("Removed: {}", uri)
+ };
+
+ output_message_result(result, message, output_format, compact);
Ok(())
}
@@ -89,11 +95,16 @@ pub async fn mv(
client: &HttpClient,
from_uri: &str,
to_uri: &str,
- _output_format: OutputFormat,
- _compact: bool,
+ output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
- client.mv(from_uri, to_uri).await?;
- println!("Moved: {} -> {}", from_uri, to_uri);
+ let result = client.mv(from_uri, to_uri).await?;
+ output_message_result(
+ result,
+ format!("Moved: {} -> {}", from_uri, to_uri),
+ output_format,
+ compact,
+ );
Ok(())
}
@@ -107,3 +118,49 @@ pub async fn stat(
output_success(&result, output_format, compact);
Ok(())
}
+
+fn output_message_result(
+ result: serde_json::Value,
+ message: String,
+ output_format: OutputFormat,
+ compact: bool,
+) {
+ match output_format {
+ OutputFormat::Json => output_success(result, output_format, compact),
+ OutputFormat::Table => {
+ println!("{}", crate::output::append_profile_to_rendered(message, &result));
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::output::render_profiled_scalar_result;
+ use serde_json::json;
+
+ #[test]
+ fn profiled_filesystem_message_includes_profile_section() {
+ let result = json!({
+ "result": "Directory created: viking://dir",
+ "profile": [
+ "mkdir took 1ms"
+ ]
+ });
+
+ let rendered = render_profiled_scalar_result(&result);
+
+ assert_eq!(
+ rendered,
+ Some(
+ [
+ "Directory created: viking://dir",
+ "",
+ "profile",
+ "mkdir took 1ms",
+ "",
+ ]
+ .join("\n")
+ )
+ );
+ }
+}
diff --git a/crates/ov_cli/src/commands/privacy.rs b/crates/ov_cli/src/commands/privacy.rs
index 0224d8a46..fa40b7c0d 100644
--- a/crates/ov_cli/src/commands/privacy.rs
+++ b/crates/ov_cli/src/commands/privacy.rs
@@ -160,18 +160,19 @@ fn render_kv_ascii_table(rows: &[Value]) -> String {
out
}
-fn output_section_table(title: &str, rows: Vec<Value>, _compact: bool) {
- println!("[{}]", title);
- println!("{}", render_kv_ascii_table(&rows));
+fn render_section_table(title: &str, rows: Vec<Value>) -> String {
+ format!("[{}]\n{}", title, render_kv_ascii_table(&rows))
}
-fn output_meta_current_tables(meta: &Map<String, Value>, values: &Map<String, Value>, compact: bool) {
- output_section_table("meta", to_kv_rows(meta), compact);
- println!();
- output_section_table("current", to_kv_rows(values), compact);
+fn render_meta_current_tables(meta: &Map<String, Value>, values: &Map<String, Value>) -> String {
+ format!(
+ "{}\n\n{}",
+ render_section_table("meta", to_kv_rows(meta)),
+ render_section_table("current", to_kv_rows(values))
+ )
}
-fn output_version_like_tables(result: &Value, compact: bool) -> Result<()> {
+fn output_version_like_tables(result: &Value, _compact: bool) -> Result<()> {
let mut meta = result
.as_object()
.ok_or_else(|| Error::Parse("Expected object response".to_string()))?
@@ -181,7 +182,8 @@ fn output_version_like_tables(result: &Value, compact: bool) -> Result<()> {
.and_then(|v| v.as_object().cloned())
.ok_or_else(|| Error::Parse("Expected values object in response".to_string()))?;
- output_meta_current_tables(&meta, &values, compact);
+ let rendered = render_meta_current_tables(&meta, &values);
+ println!("{}", crate::output::append_profile_to_rendered(rendered, result));
Ok(())
}
@@ -222,7 +224,8 @@ pub async fn get_current(
.and_then(Value::as_object)
.ok_or_else(|| Error::Parse("Expected current.values object in response".to_string()))?
.clone();
- output_meta_current_tables(&meta, &values, compact);
+ let rendered = render_meta_current_tables(&meta, &values);
+ println!("{}", crate::output::append_profile_to_rendered(rendered, &result));
return Ok(());
}
@@ -354,12 +357,55 @@ pub async fn upsert(
.ok_or_else(|| Error::Parse("Expected values object in upsert response".to_string()))?
.clone();
let (updated_rows, unchanged_rows) = split_kv_rows_by_keys(&values, &requested_keys);
- output_section_table("updated", updated_rows, compact);
- println!();
- output_section_table("unchanged", unchanged_rows, compact);
+ let rendered = format!(
+ "{}\n\n{}",
+ render_section_table("updated", updated_rows),
+ render_section_table("unchanged", unchanged_rows)
+ );
+ println!("{}", crate::output::append_profile_to_rendered(rendered, &result));
return Ok(());
}
output_success(&result, output_format, compact);
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn version_like_table_output_keeps_profile_section() {
+ let result = json!({
+ "version": 3,
+ "change_reason": "rotate",
+ "values": {
+ "k": "v"
+ },
+ "profile": [
+ "privacy took 3ms"
+ ]
+ });
+
+ let mut meta = result
+ .as_object()
+ .expect("object")
+ .clone();
+ let values = meta
+ .remove("values")
+ .and_then(|v| v.as_object().cloned())
+ .expect("values");
+ let rendered = format!(
+ "[meta]\n{}\n\n[current]\n{}",
+ render_kv_ascii_table(&to_kv_rows(&meta)),
+ render_kv_ascii_table(&to_kv_rows(&values))
+ );
+ let final_rendered = crate::output::append_profile_to_rendered(
+ rendered,
+ &result,
+ );
+
+ assert!(final_rendered.contains("profile\nprivacy took 3ms\n"));
+ }
+}
diff --git a/crates/ov_cli/src/commands/session.rs b/crates/ov_cli/src/commands/session.rs
index c373e3f2e..a43ceb793 100644
--- a/crates/ov_cli/src/commands/session.rs
+++ b/crates/ov_cli/src/commands/session.rs
@@ -162,6 +162,7 @@ pub async fn add_memory(
// 1. Create a new session
let session_response: serde_json::Value = client.post("/api/v1/sessions", &json!({})).await?;
+ let mut profile_lines: Vec<serde_json::Value> = extract_profile_lines(&session_response);
let session_id = session_response["session_id"].as_str().ok_or_else(|| {
crate::error::Error::Api("Failed to get session_id from new session response".to_string())
})?;
@@ -173,20 +174,71 @@ pub async fn add_memory(
"role": role,
"content": content
});
- let _: serde_json::Value = client.post(&path, &body).await?;
+ let response: serde_json::Value = client.post(&path, &body).await?;
+ profile_lines.extend(extract_profile_lines(&response));
}
// 3. Commit (async — don't read response)
let commit_path = format!("/api/v1/sessions/{}/commit", url_encode(session_id));
- let _: serde_json::Value = client.post(&commit_path, &json!({})).await?;
-
- output_success(&json!("OK"), output_format, compact);
+ let commit_response: serde_json::Value = client.post(&commit_path, &json!({})).await?;
+ profile_lines.extend(extract_profile_lines(&commit_response));
+
+ let result = if profile_lines.is_empty() {
+ json!("OK")
+ } else {
+ json!({
+ "result": "OK",
+ "profile": profile_lines,
+ })
+ };
+ output_success(&result, output_format, compact);
Ok(())
}
+fn extract_profile_lines(value: &serde_json::Value) -> Vec<serde_json::Value> {
+ value
+ .get("profile")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default()
+}
+
fn url_encode(s: &str) -> String {
// Simple URL encoding for session IDs
s.replace('/', "%2F")
.replace(':', "%3A")
.replace(' ', "%20")
}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ #[test]
+ fn add_memory_ok_output_can_include_profile_section() {
+ let result = json!({
+ "result": "OK",
+ "profile": [
+ "create session 1ms",
+ "commit 2ms"
+ ]
+ });
+
+ let rendered = crate::output::render_profiled_scalar_result(&result);
+
+ assert_eq!(
+ rendered,
+ Some(
+ [
+ "OK",
+ "",
+ "profile",
+ "create session 1ms",
+ "commit 2ms",
+ "",
+ ]
+ .join("\n")
+ )
+ );
+ }
+}
diff --git a/crates/ov_cli/src/commands/system.rs b/crates/ov_cli/src/commands/system.rs
index 8cebadea3..f8efabf10 100644
--- a/crates/ov_cli/src/commands/system.rs
+++ b/crates/ov_cli/src/commands/system.rs
@@ -54,18 +54,42 @@ fn output_consistency_table(response: &serde_json::Value, compact: bool) {
.and_then(|v| v.as_bool())
.unwrap_or(false),
});
- output_success(&summary, OutputFormat::Table, compact);
+ let mut sections = vec![
+ crate::output::render_table_with_optional_profile(&summary, compact)
+ .unwrap_or_default()
+ .trim_end()
+ .to_string(),
+ ];
let Some(missing_records) = response.get("missing_records").and_then(|v| v.as_array()) else {
+ println!(
+ "{}",
+ crate::output::append_profile_to_rendered(sections.join("\n"), response)
+ );
return;
};
if missing_records.is_empty() {
+ println!(
+ "{}",
+ crate::output::append_profile_to_rendered(sections.join("\n"), response)
+ );
return;
}
- println!();
- println!("missing_records");
- output_success(missing_records, OutputFormat::Table, compact);
+ sections.push("missing_records".to_string());
+ sections.push(
+ crate::output::render_table_with_optional_profile(
+ &serde_json::Value::Array(missing_records.clone()),
+ compact,
+ )
+ .unwrap_or_default()
+ .trim_end()
+ .to_string(),
+ );
+ println!(
+ "{}",
+ crate::output::append_profile_to_rendered(sections.join("\n\n"), response)
+ );
}
pub async fn health(
@@ -98,3 +122,31 @@ pub async fn health(
Ok(healthy)
}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ #[test]
+ fn consistency_table_output_keeps_profile_section() {
+ let response = json!({
+ "ok": true,
+ "expected_count": 3,
+ "missing_record_count": 1,
+ "missing_records_truncated": false,
+ "missing_records": [
+ {"key": "viking://a", "value": "missing"}
+ ],
+ "profile": [
+ "consistency took 2ms"
+ ]
+ });
+
+ let full = crate::output::append_profile_to_rendered(
+ "ok true\n\nmissing_records\nkey value\nviking://a missing".to_string(),
+ &response,
+ );
+
+ assert!(full.contains("profile\nconsistency took 2ms\n"));
+ }
+}
diff --git a/crates/ov_cli/src/config.rs b/crates/ov_cli/src/config.rs
index 6efc6818b..2fff9d881 100644
--- a/crates/ov_cli/src/config.rs
+++ b/crates/ov_cli/src/config.rs
@@ -44,6 +44,8 @@ pub struct Config {
#[serde(default = "default_verbose")]
pub verbose: bool,
#[serde(default)]
+ pub profile: bool,
+ #[serde(default)]
pub upload: UploadConfig,
#[serde(default, alias = "extra_header")]
pub extra_headers: Option<std::collections::HashMap<String, String>>,
@@ -87,6 +89,7 @@ impl Default for Config {
echo_command: true,
show_progress: false,
verbose: false,
+ profile: false,
upload: UploadConfig::default(),
extra_headers: None,
}
@@ -332,6 +335,19 @@ mod tests {
assert!(config.extra_headers.is_none());
}
+ #[test]
+ fn config_deserializes_profile_flag() {
+ let config: Config = serde_json::from_str(
+ r#"{
+ "url": "http://localhost:1933",
+ "profile": true
+ }"#,
+ )
+ .expect("config should deserialize with profile");
+
+ assert!(config.profile);
+ }
+
#[test]
fn config_deserializes_extra_header_alias() {
let config: Config = serde_json::from_str(
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index af05c919e..37ef730b7 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -96,6 +96,7 @@ pub async fn handle_add_resource(
ctx.config.account.clone(),
ctx.config.user.clone(),
effective_timeout,
+ ctx.profile.unwrap_or(ctx.config.profile),
ctx.config.extra_headers.clone(),
);
commands::resources::add_resource(
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 362a7522a..d0773b3e6 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -25,6 +25,7 @@ pub struct CliContext {
pub show_progress: Option<bool>,
/// Whether to enable verbose output (override config)
pub verbose: Option<bool>,
+ pub profile: Option<bool>,
}
impl CliContext {
@@ -37,6 +38,7 @@ impl CliContext {
sudo: bool,
show_progress: Option<bool>,
verbose: Option<bool>,
+ profile: Option<bool>,
) -> Result<Self> {
let config = Config::load()?;
Ok(Self::from_config(
@@ -49,6 +51,7 @@ impl CliContext {
sudo,
show_progress,
verbose,
+ profile,
))
}
@@ -62,6 +65,7 @@ impl CliContext {
sudo: bool,
show_progress: Option<bool>,
verbose: Option<bool>,
+ profile: Option<bool>,
) -> Self {
if account.is_some() {
config.account = account;
@@ -79,6 +83,7 @@ impl CliContext {
sudo,
show_progress,
verbose,
+ profile,
}
}
@@ -109,6 +114,7 @@ impl CliContext {
self.config.account.clone(),
self.config.user.clone(),
timeout_secs.unwrap_or(self.config.timeout),
+ self.profile.unwrap_or(self.config.profile),
self.config.extra_headers.clone(),
)
}
@@ -144,6 +150,10 @@ struct Cli {
#[arg(long)]
sudo: bool,
+ /// Enable HTTP request profiling for this command
+ #[arg(long, global = true)]
+ profile: bool,
+
/// Show upload progress (legacy pre-command placement; prefer command-local --progress)
#[arg(long, hide = true)]
progress: bool,
@@ -1154,6 +1164,7 @@ async fn main() {
cli.sudo,
None,
None,
+ if cli.profile { Some(true) } else { None },
) {
Ok(ctx) => ctx,
Err(e) => {
@@ -1653,6 +1664,7 @@ mod tests {
verbose: false,
upload: Default::default(),
extra_headers: None,
+ profile: false,
};
let ctx = CliContext::from_config(
@@ -1665,6 +1677,7 @@ mod tests {
false,
None,
None,
+ None,
);
assert_eq!(ctx.config.account.as_deref(), Some("from-cli-account"));
@@ -1686,6 +1699,7 @@ mod tests {
echo_command: true,
show_progress: false,
verbose: false,
+ profile: false,
upload: Default::default(),
extra_headers: None,
};
@@ -1701,6 +1715,7 @@ mod tests {
false,
None,
None,
+ None,
);
let client = ctx.get_client();
assert_eq!(client.api_key(), Some("user-key"));
@@ -1716,6 +1731,7 @@ mod tests {
true,
None,
None,
+ None,
);
let client = ctx.get_client();
assert_eq!(client.api_key(), Some("root-key"));
diff --git a/crates/ov_cli/src/output.rs b/crates/ov_cli/src/output.rs
index da7921b39..6348af1fd 100644
--- a/crates/ov_cli/src/output.rs
+++ b/crates/ov_cli/src/output.rs
@@ -92,11 +92,16 @@ fn print_table<T: Serialize>(result: T, compact: bool) {
if let Some(obj) = value.as_object() {
if !obj.is_empty() {
if let Some(rendered) = render_session_context(obj, compact) {
- println!("{}", rendered);
+ println!("{}", append_profile_section(rendered, obj));
return;
}
if let Some(rendered) = render_session_archive(obj, compact) {
+ println!("{}", append_profile_section(rendered, obj));
+ return;
+ }
+
+ if let Some(rendered) = value_to_table_with_profile(&value, compact) {
println!("{}", rendered);
return;
}
@@ -145,7 +150,7 @@ fn print_table<T: Serialize>(result: T, compact: bool) {
}
}
}
- println!("{}", lines.join("\n"));
+ println!("{}", append_profile_section(lines.join("\n"), obj));
return;
}
@@ -154,6 +159,9 @@ fn print_table<T: Serialize>(result: T, compact: bool) {
let mut prim_lists: Vec<(String, &Vec<serde_json::Value>)> = Vec::new();
for (key, val) in obj {
+ if key == "profile" {
+ continue;
+ }
if let Some(arr) = val.as_array() {
if !arr.is_empty() {
if arr.iter().all(|item| item.is_object()) {
@@ -185,7 +193,7 @@ fn print_table<T: Serialize>(result: T, compact: bool) {
rows.push(serde_json::Value::Object(row));
}
if let Some(table) = format_array_to_table(&rows, compact) {
- println!("{}", table);
+ println!("{}", append_profile_section(table, obj));
return;
}
}
@@ -194,7 +202,7 @@ fn print_table<T: Serialize>(result: T, compact: bool) {
if dict_lists.len() == 1 && prim_lists.is_empty() {
let (_key, items) = &dict_lists[0];
if let Some(table) = format_array_to_table(items, compact) {
- println!("{}", table);
+ println!("{}", append_profile_section(table, obj));
return;
}
}
@@ -222,7 +230,7 @@ fn print_table<T: Serialize>(result: T, compact: bool) {
}
if !merged.is_empty() {
if let Some(table) = format_array_to_table(&merged, compact) {
- println!("{}", table);
+ println!("{}", append_profile_section(table, obj));
return;
}
}
@@ -240,13 +248,16 @@ fn print_table<T: Serialize>(result: T, compact: bool) {
let mut output = String::new();
for (k, v) in obj {
+ if k == "profile" {
+ continue;
+ }
let is_uri = k == "uri";
let formatted_value = format_value(v);
let (content, _) = truncate_string(&formatted_value, is_uri, MAX_COL_WIDTH);
let padded_key = pad_cell(k, max_key_width, false);
output.push_str(&format!("{} {}\n", padded_key, content));
}
- println!("{}", output);
+ println!("{}", append_profile_section(output, obj));
return;
}
}
@@ -263,6 +274,87 @@ fn print_table<T: Serialize>(result: T, compact: bool) {
}
}
+fn value_to_table_with_profile(value: &serde_json::Value, compact: bool) -> Option<String> {
+ let obj = value.as_object()?;
+ let rendered = if let Some(rendered) = value_to_table(value, compact) {
+ rendered
+ } else {
+ let max_key_width = obj
+ .keys()
+ .filter(|k| k.as_str() != "profile")
+ .map(|k| k.width())
+ .max()
+ .unwrap_or(0)
+ .min(MAX_COL_WIDTH);
+
+ let mut output = String::new();
+ for (k, v) in obj {
+ if k == "profile" {
+ continue;
+ }
+ let is_uri = k == "uri";
+ let formatted_value = format_value(v);
+ let (content, _) = truncate_string(&formatted_value, is_uri, MAX_COL_WIDTH);
+ let padded_key = pad_cell(k, max_key_width, false);
+ output.push_str(&format!("{} {}\n", padded_key, content));
+ }
+ output
+ };
+ Some(append_profile_section(rendered, obj))
+}
+
+fn append_profile_section(
+ rendered: String,
+ obj: &serde_json::Map<String, serde_json::Value>,
+) -> String {
+ let Some(profile) = obj.get("profile").and_then(|v| v.as_array()) else {
+ return rendered;
+ };
+ if profile.is_empty() {
+ return rendered;
+ }
+
+ let lines: Vec<String> = profile
+ .iter()
+ .map(|line| match line {
+ serde_json::Value::String(s) => s.clone(),
+ other => format_value(other),
+ })
+ .collect();
+ if lines.is_empty() {
+ return rendered;
+ }
+
+ let mut out = rendered.trim_end_matches('\n').to_string();
+ out.push_str("\n\nprofile\n");
+ out.push_str(&lines.join("\n"));
+ out.push('\n');
+ out
+}
+
+pub fn render_profiled_scalar_result(value: &serde_json::Value) -> Option<String> {
+ let obj = value.as_object()?;
+ let result = obj.get("result")?.as_str()?;
+ Some(append_profile_section(result.to_string(), obj))
+}
+
+pub fn append_profile_to_rendered(
+ rendered: String,
+ value: &serde_json::Value,
+) -> String {
+ let Some(obj) = value.as_object() else {
+ return rendered;
+ };
+ append_profile_section(rendered, obj)
+}
+
+pub fn render_table_with_optional_profile(
+ value: &serde_json::Value,
+ compact: bool,
+) -> Option<String> {
+ value_to_table_with_profile(value, compact)
+}
+
fn value_to_table(value: &serde_json::Value, compact: bool) -> Option<String> {
// Rule 1: list[dict] -> multi-row table
if let Some(items) = value.as_array() {
@@ -290,6 +382,9 @@ fn value_to_table(value: &serde_json::Value, compact: bool) -> Option<String> {
let mut prim_lists: Vec<(String, &Vec<serde_json::Value>)> = Vec::new();
for (key, val) in obj {
+ if key == "profile" {
+ continue;
+ }
if let Some(arr) = val.as_array() {
if !arr.is_empty() {
if arr.iter().all(|item| item.is_object()) {
@@ -846,4 +941,95 @@ mod tests {
assert_eq!(rendered, long_abstract);
assert!(skip_padding);
}
+
+ #[test]
+ fn test_profile_section_is_preserved_for_table_objects_with_list_payloads() {
+ let value = json!({
+ "items": [
+ {"id": "1", "name": "alpha"},
+ {"id": "2", "name": "beta"}
+ ],
+ "profile": [
+ "line one",
+ "line two"
+ ]
+ });
+
+ let rendered = value_to_table_with_profile(&value, true);
+
+ assert_eq!(
+ rendered,
+ Some(
+ [
+ "id name ",
+ " 1 alpha",
+ " 2 beta ",
+ "",
+ "profile",
+ "line one",
+ "line two",
+ "",
+ ]
+ .join("\n")
+ )
+ );
+ }
+
+ #[test]
+ fn test_profile_section_is_not_duplicated_for_plain_object_output() {
+ let value = json!({
+ "healthy": true,
+ "version": "0.1.x",
+ "profile": [
+ "line one",
+ "line two"
+ ]
+ });
+
+ let rendered = value_to_table_with_profile(&value, true);
+
+ assert_eq!(
+ rendered,
+ Some(
+ [
+ "healthy true",
+ "version 0.1.x",
+ "",
+ "profile",
+ "line one",
+ "line two",
+ "",
+ ]
+ .join("\n")
+ )
+ );
+ }
+
+ #[test]
+ fn test_render_profiled_scalar_result_appends_profile_section() {
+ let value = json!({
+ "result": "content",
+ "profile": [
+ "line one",
+ "line two"
+ ]
+ });
+
+ let rendered = render_profiled_scalar_result(&value);
+
+ assert_eq!(
+ rendered,
+ Some(
+ [
+ "content",
+ "",
+ "profile",
+ "line one",
+ "line two",
+ "",
+ ]
+ .join("\n")
+ )
+ );
+ }
}
diff --git a/docs/en/api/07-system.md b/docs/en/api/07-system.md
index 7d8072975..10d1ddd67 100644
--- a/docs/en/api/07-system.md
+++ b/docs/en/api/07-system.md
@@ -17,7 +17,25 @@ Basic health check endpoint. No authentication required. Returns service version
#### 2. Interface and Parameters
-No parameters.
+| Parameter | Type | Required | Default | Description |
+|-----------|------|----------|---------|-------------|
+| profile | string | No | - | When set to `1`, `true`, `yes`, or `on`, enables request-scoped `cProfile` and appends a `profile` field to JSON responses |
+
+**`profile` behavior**:
+- `profile` is implemented at the HTTP middleware layer and works for any OpenViking endpoint that returns JSON, not just `/health`.
+- The request flag only takes effect when the server enables `server.profile_enabled = true` in `ov.conf`; otherwise the server ignores `profile=1`.
+- `profile` only applies to the current request and is automatically disabled when the request completes, so later requests do not inherit it.
+- The middleware only injects a `profile` field into JSON responses; plain text, file, and streaming responses are left unchanged.
+- The returned value is `list[string]`, where each element is one formatted `pstats` line. This makes browser JSON viewers and line-by-line UI rendering easier.
+- The `ov` CLI displays the returned `profile`. The Python HTTP client can trigger server-side profiling via `ovcli.conf.profile = true`, but most SDK methods still return only the business `result` and do not expose the top-level `profile` field directly.
+
+**`profile` column meanings**:
+- `ncalls`: Number of calls. When shown as `total/primitive`, the first value is total calls and the second is primitive calls.
+- `tottime`: Total time spent in the function body itself, excluding time in subcalls.
+- `percall` (first): `tottime / ncalls`, the average self time per call.
+- `cumtime`: Cumulative time including the current function and all of its subcalls.
+- `percall` (second): `cumtime / primitive calls`, the average cumulative time per primitive call.
+- `filename:lineno(function)`: Function location. Regular Python code shows the trimmed module path; entries like `~:0(...)` usually represent builtin or native-extension calls.
#### 3. Usage Examples
@@ -31,6 +49,11 @@ GET /health
curl -X GET http://localhost:1933/health
```
+```bash
+curl -G http://localhost:1933/health \
+ --data-urlencode "profile=1"
+```
+
**Python SDK**
```python
@@ -49,6 +72,10 @@ print(f"Healthy: {healthy}")
ov system health
```
+```bash
+ov --profile health
+```
+
**Response Example**
```json
@@ -60,6 +87,27 @@ ov system health
}
```
+**Response Example With `profile`**
+
+```json
+{
+ "status": "ok",
+ "healthy": true,
+ "version": "0.1.x",
+ "profile": [
+ " 325 function calls (310 primitive calls) in 0.004 seconds",
+ "",
+ " Ordered by: cumulative time",
+ " List reduced from 87 to 87 due to restriction <100>",
+ "",
+ " ncalls tottime percall cumtime percall filename:lineno(function)",
+ " 1 0.000 0.000 0.003 0.003 starlette/middleware/base.py:112(call_next)",
+ " 1 0.000 0.000 0.001 0.001 openviking/server/routers/system.py:39(health_check)",
+ " 3 0.000 0.000 0.000 0.000 ~:0(<method 'read' of 'builtins.RAGFSBindingClient' objects>)"
+ ]
+}
+```
+
---
### ready
diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.md
index 595e0f20c..42ef8cbac 100644
--- a/docs/en/guides/01-configuration.md
+++ b/docs/en/guides/01-configuration.md
@@ -1117,6 +1117,7 @@ Config file for the HTTP client (`SyncHTTPClient` / `AsyncHTTPClient`) and CLI t
"account": "acme",
"user": "alice",
"agent_id": "my-agent",
+ "profile": false,
"upload": {
"mode": "local",
"ignore_dirs": "node_modules,.cache,.nx",
@@ -1133,6 +1134,7 @@ Config file for the HTTP client (`SyncHTTPClient` / `AsyncHTTPClient`) and CLI t
| `account` | Default account sent as `X-OpenViking-Account` | `null` |
| `user` | Default user sent as `X-OpenViking-User` | `null` |
| `agent_id` | Agent identifier for agent space isolation | `null` |
+| `profile` | Whether to append `profile=1` to HTTP requests by default. Applies to both the Python HTTP client and the `ov` CLI; `ov --profile` can enable it per invocation. Actual effect still depends on the server enabling `server.profile_enabled`. | `false` |
| `upload.ignore_dirs` | Default directory ignore list for `add-resource` (CSV) | `null` |
| `upload.include` | Default include patterns for `add-resource` (CSV) | `null` |
| `upload.exclude` | Default exclude patterns for `add-resource` (CSV) | `null` |
@@ -1167,6 +1169,7 @@ When running OpenViking as an HTTP service, add a `server` section to `ov.conf`:
"port": 1933,
"auth_mode": "api_key",
"root_api_key": "your-secret-root-key",
+ "profile_enabled": false,
"cors_origins": ["*"],
"public_base_url": "https://ov.example.com",
"upload_signed_ttl_seconds": 600,
@@ -1185,6 +1188,7 @@ When running OpenViking as an HTTP service, add a `server` section to `ov.conf`:
| `port` | int | Bind port | `1933` |
| `auth_mode` | str | Authentication mode: `"api_key"` or `"trusted"`. Default is `"api_key"` | `"api_key"` |
| `root_api_key` | str | Root API key for multi-tenant auth in `api_key` mode. In `trusted` mode it is optional on localhost, but required for any non-localhost deployment; it does not become the source of user identity | `null` |
+| `profile_enabled` | bool | Whether to allow request-scoped cProfile via `profile=1` on HTTP requests. When disabled, the server ignores that query parameter. When enabled, the CLI can display the returned `profile`, while the Python HTTP client currently triggers profiling but does not automatically attach the top-level `profile` field to most SDK return values. | `false` |
| `cors_origins` | list | Allowed CORS origins | `["*"]` |
| `public_base_url` | str | Public-facing base URL emitted in MCP-issued upload instructions. Resolution order: env var `OPENVIKING_PUBLIC_BASE_URL` → this field → `X-Forwarded-Host`/`X-Forwarded-Proto` request headers → `Host` request header → listen-address fallback. Set this (or the env var) when the server runs behind a reverse proxy that does not forward `X-Forwarded-*` headers. | `null` |
| `upload_signed_ttl_seconds` | int | TTL in seconds for one-shot tokens minted by the MCP `add_resource` tool for local-file uploads via the signed `POST /api/v1/resources/temp_upload_signed` endpoint. | `600` (10 minutes) |
diff --git a/docs/zh/api/07-system.md b/docs/zh/api/07-system.md
index c3860ad85..fd50e39dd 100644
--- a/docs/zh/api/07-system.md
+++ b/docs/zh/api/07-system.md
@@ -17,7 +17,25 @@ OpenViking 提供系统健康检查、可观测性和调试 API,用于监控
#### 2. 接口和参数说明
-无参数。
+| 参数 | 类型 | 必填 | 默认值 | 说明 |
+|------|------|------|--------|------|
+| profile | string | 否 | - | 传 `1`、`true`、`yes` 或 `on` 时,为本次请求开启 `cProfile`,并在 JSON 响应里追加 `profile` 字段 |
+
+**profile 行为说明**:
+- `profile` 是 HTTP middleware 级能力,对任意返回 JSON 的 OpenViking 接口都生效,不限于 `/health`。
+- 仅当服务端在 `ov.conf` 中开启 `server.profile_enabled = true` 时,请求里的 `profile=1` 才会生效;否则服务端会忽略该参数。
+- `profile` 仅对当前请求生效,请求结束后自动关闭;后续请求默认不会继承这次 profile 状态。
+- 仅 JSON 响应会追加 `profile` 字段;纯文本、文件、流式响应不会被改写。
+- `profile` 的返回值是 `list[string]`,每个元素对应一行格式化后的 `pstats` 输出,便于浏览器直接查看和前端按行渲染。
+- `ov` CLI 会显示返回的 `profile`;Python HTTP client 可以通过 `ovcli.conf.profile = true` 触发服务端 profile,但大多数 SDK 方法默认只返回业务 `result`,不会把顶层 `profile` 一并暴露给调用方。
+
+**profile 表头字段说明**:
+- `ncalls`: 调用次数。若显示为 `总调用次数/原始调用次数`,前者是总调用数,后者是 primitive calls。
+- `tottime`: 函数自身耗时,总时间,不包含其调用的子函数耗时。
+- `percall`(第一列): `tottime / ncalls`,即函数自身平均每次调用耗时。
+- `cumtime`: 累计耗时,包含当前函数及其所有子调用耗时。
+- `percall`(第二列): `cumtime / primitive calls`,即按原始调用计算的平均累计耗时。
+- `filename:lineno(function)`: 函数定义位置。普通 Python 代码会显示为裁剪后的模块路径;`~:0(...)` 这类条目通常表示 builtin 或 C 扩展调用。
#### 3. 使用示例
@@ -31,6 +49,11 @@ GET /health
curl -X GET http://localhost:1933/health
```
+```bash
+curl -G http://localhost:1933/health \
+ --data-urlencode "profile=1"
+```
+
**Python SDK**
```python
@@ -49,6 +72,10 @@ print(f"Healthy: {healthy}")
ov system health
```
+```bash
+ov --profile health
+```
+
**响应示例**
```json
@@ -60,6 +87,27 @@ ov system health
}
```
+**带 profile 的响应示例**
+
+```json
+{
+ "status": "ok",
+ "healthy": true,
+ "version": "0.1.x",
+ "profile": [
+ " 325 function calls (310 primitive calls) in 0.004 seconds",
+ "",
+ " Ordered by: cumulative time",
+ " List reduced from 87 to 87 due to restriction <100>",
+ "",
+ " ncalls tottime percall cumtime percall filename:lineno(function)",
+ " 1 0.000 0.000 0.003 0.003 starlette/middleware/base.py:112(call_next)",
+ " 1 0.000 0.000 0.001 0.001 openviking/server/routers/system.py:39(health_check)",
+ " 3 0.000 0.000 0.000 0.000 ~:0(<method 'read' of 'builtins.RAGFSBindingClient' objects>)"
+ ]
+}
+```
+
---
### ready
diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.md
index d9bd3776c..aa36ce5a4 100644
--- a/docs/zh/guides/01-configuration.md
+++ b/docs/zh/guides/01-configuration.md
@@ -1089,6 +1089,7 @@ HTTP 客户端(`SyncHTTPClient` / `AsyncHTTPClient`)和 CLI 工具连接远
"account": "acme",
"user": "alice",
"agent_id": "my-agent",
+ "profile": false,
"upload": {
"mode": "local",
"ignore_dirs": "node_modules,.cache,.nx",
@@ -1105,6 +1106,7 @@ HTTP 客户端(`SyncHTTPClient` / `AsyncHTTPClient`)和 CLI 工具连接远
| `account` | 默认发送为 `X-OpenViking-Account` 的租户标识 | `null` |
| `user` | 默认发送为 `X-OpenViking-User` 的用户标识 | `null` |
| `agent_id` | Agent 标识,用于 agent space 隔离 | `null` |
+| `profile` | 是否默认给 HTTP 请求追加 `profile=1`。对 Python HTTP client 和 `ov` CLI 都生效;也可通过 CLI 的 `--profile` 单次开启。是否真正生效还取决于服务端是否开启 `server.profile_enabled`。 | `false` |
| `upload.ignore_dirs` | `add-resource` 默认忽略目录列表(CSV) | `null` |
| `upload.include` | `add-resource` 默认包含模式(CSV) | `null` |
| `upload.exclude` | `add-resource` 默认排除模式(CSV) | `null` |
@@ -1139,6 +1141,7 @@ openviking add-resource ./docs --exclude "*.tmp"
"port": 1933,
"auth_mode": "api_key",
"root_api_key": "your-secret-root-key",
+ "profile_enabled": false,
"cors_origins": ["*"],
"public_base_url": "https://ov.example.com",
"upload_signed_ttl_seconds": 600,
@@ -1157,6 +1160,7 @@ openviking add-resource ./docs --exclude "*.tmp"
| `port` | int | 绑定端口 | `1933` |
| `auth_mode` | str | 认证模式:`"api_key"` 或 `"trusted"`。默认值为 `"api_key"` | `"api_key"` |
| `root_api_key` | str | Root API Key。在 `api_key` 模式下启用多租户认证;在 `trusted` 模式下它只是可选附加保护,不负责解析普通用户身份 | `null` |
+| `profile_enabled` | bool | 是否允许 HTTP 请求通过 `profile=1` 开启请求级 cProfile。关闭时服务端会忽略该请求参数;开启后,CLI 可以显示返回的 `profile`,而 Python HTTP client 默认只触发服务端 profile,不会把顶层 `profile` 字段自动附着到大多数 SDK 返回值上。 | `false` |
| `cors_origins` | list | CORS 允许的来源 | `["*"]` |
| `public_base_url` | str | MCP `add_resource` 工具向客户端返回的上传指令里使用的对外可见 base URL。解析顺序:环境变量 `OPENVIKING_PUBLIC_BASE_URL` → 本字段 → 请求头 `X-Forwarded-Host` / `X-Forwarded-Proto` → 请求头 `Host` → 监听地址兜底。当 server 部署在反向代理后且代理不转发 `X-Forwarded-*` 时,请显式设置本字段(或环境变量)。 | `null` |
| `upload_signed_ttl_seconds` | int | MCP `add_resource` 为本地文件上传 mint 的一次性 token 在签名端点 `POST /api/v1/resources/temp_upload_signed` 上的过期时间(秒)。 | `600`(10 分钟) |
diff --git a/openviking/server/app.py b/openviking/server/app.py
index d0548259b..06a972747 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -27,6 +27,7 @@ from openviking.server.dependencies import set_server_config, set_service
from openviking.server.error_mapping import map_exception
from openviking.server.identity import AuthMode, Role
from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Response
+from openviking.server.profile_middleware import create_profile_http_middleware
from openviking.server.routers import (
admin_router,
bot_router,
@@ -363,11 +364,16 @@ def create_app(
)
http_observability_middleware = create_http_observability_middleware()
+ profile_http_middleware = create_profile_http_middleware()
@app.middleware("http")
async def add_http_observability(request: Request, call_next: Callable):
return await http_observability_middleware(request, call_next)
+ @app.middleware("http")
+ async def add_profile_output(request: Request, call_next: Callable):
+ return await profile_http_middleware(request, call_next)
+
# Add request timing middleware last (so it executes first as the outermost layer)
# This ensures X-Process-Time includes the full request duration including
# observability middleware overhead.
diff --git a/openviking/server/config.py b/openviking/server/config.py
index 48edcdf58..13b530a68 100644
--- a/openviking/server/config.py
+++ b/openviking/server/config.py
@@ -162,6 +162,7 @@ class ServerConfig(BaseModel):
workers: int = 1
auth_mode: Optional[AuthMode] = None # If None, auto-detect based on root_api_key
root_api_key: Optional[str] = None
+ profile_enabled: bool = False
cors_origins: List[str] = Field(default_factory=lambda: ["*"])
with_bot: bool = False # Enable Bot API proxy to Vikingbot
bot_api_url: str = "http://localhost:18790" # Vikingbot OpenAPIChannel URL (default port)
diff --git a/openviking/server/models.py b/openviking/server/models.py
index afe315fcb..e998239d3 100644
--- a/openviking/server/models.py
+++ b/openviking/server/models.py
@@ -22,6 +22,7 @@ class Response(BaseModel):
result: Optional[Any] = None
error: Optional[ErrorInfo] = None
telemetry: Optional[Dict[str, Any]] = None
+ profile: Optional[list[str]] = None
# Error code to HTTP status code mapping
diff --git a/openviking/server/profile_middleware.py b/openviking/server/profile_middleware.py
new file mode 100644
index 000000000..ebbd390ef
--- /dev/null
+++ b/openviking/server/profile_middleware.py
@@ -0,0 +1,226 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""HTTP request profiling middleware helpers."""
+
+from __future__ import annotations
+
+import cProfile
+import json
+import site
+import sysconfig
+from pathlib import Path
+from typing import Awaitable, Callable
+
+from fastapi import Request
+from fastapi.responses import FileResponse, JSONResponse
+from starlette.responses import Response as StarletteResponse
+from starlette.responses import StreamingResponse
+
+PROFILE_TRUE_VALUES = {"1", "true", "yes", "on"}
+PROFILE_SORT_BY = "cumulative"
+PROFILE_TOP_N = 100
+PROFILE_MAX_CHARS = 16 * 1024
+_PROJECT_ROOT = Path(__file__).resolve().parents[2]
+
+
+def _build_profile_roots() -> tuple[Path, ...]:
+ roots: list[Path] = [_PROJECT_ROOT]
+
+ try:
+ roots.extend(Path(path) for path in site.getsitepackages())
+ except Exception:
+ pass
+
+ try:
+ user_site = site.getusersitepackages()
+ if user_site:
+ roots.append(Path(user_site))
+ except Exception:
+ pass
+
+ for key in ("stdlib", "platstdlib"):
+ try:
+ stdlib_path = sysconfig.get_paths().get(key)
+ if stdlib_path:
+ roots.append(Path(stdlib_path))
+ except Exception:
+ pass
+
+ deduped: list[Path] = []
+ seen: set[str] = set()
+ for root in roots:
+ raw = root.as_posix()
+ resolved = root.resolve().as_posix()
+ for candidate in (raw, resolved):
+ if candidate and candidate not in seen:
+ deduped.append(Path(candidate))
+ seen.add(candidate)
+ return tuple(deduped)
+
+
+PROFILE_ROOTS = _build_profile_roots()
+
+
+def profile_enabled(request: Request) -> bool:
+ server_config = getattr(request.app.state, "config", None)
+ if server_config is not None and not getattr(server_config, "profile_enabled", False):
+ return False
+ value = request.query_params.get("profile")
+ if value is None:
+ return False
+ return value.strip().lower() in PROFILE_TRUE_VALUES
+
+
+def _infer_module_suffix(path: Path) -> str:
+ parts = list(path.parts)
+ if not parts:
+ return path.name
+
+ suffix = [path.name]
+ for part in reversed(parts[:-1]):
+ if part.isidentifier():
+ suffix.insert(0, part)
+ continue
+ break
+
+ if len(suffix) >= 2:
+ return "/".join(suffix)
+ if len(parts) >= 2:
+ return "/".join(parts[-2:])
+ return path.name
+
+
+def _sanitize_profile_path(path: str) -> str:
+ raw_path = Path(path)
+ candidates = [raw_path]
+ try:
+ resolved = raw_path.resolve()
+ except Exception:
+ resolved = None
+ if resolved is not None and resolved != raw_path:
+ candidates.append(resolved)
+
+ for candidate in candidates:
+ parts = candidate.parts
+
+ for marker in ("site-packages", "dist-packages"):
+ if marker in parts:
+ idx = parts.index(marker)
+ if idx + 1 < len(parts):
+ return "/".join(parts[idx + 1 :])
+
+ for idx, part in enumerate(parts):
+ if part.startswith("python") and idx + 1 < len(parts):
+ suffix = parts[idx + 1 :]
+ if suffix:
+ return "/".join(suffix)
+
+ for root in PROFILE_ROOTS:
+ try:
+ return candidate.relative_to(root).as_posix()
+ except ValueError:
+ continue
+
+ return _infer_module_suffix(raw_path)
+
+
+def format_profile_output(profiler: cProfile.Profile) -> list[str]:
+ import pstats
+
+ stats = pstats.Stats(profiler)
+ stats.sort_stats(PROFILE_SORT_BY)
+
+ rows = list(stats.stats.items())
+ if PROFILE_SORT_BY == "cumulative":
+ rows.sort(key=lambda item: (item[1][3], item[1][2]), reverse=True)
+ else:
+ rows.sort(key=lambda item: item[1][2], reverse=True)
+
+ total_calls = getattr(stats, "total_calls", 0)
+ prim_calls = getattr(stats, "prim_calls", 0)
+ total_tt = getattr(stats, "total_tt", 0.0)
+
+ lines = [
+ f" {total_calls} function calls ({prim_calls} primitive calls) in {total_tt:.3f} seconds",
+ "",
+ f" Ordered by: {PROFILE_SORT_BY} time",
+ f" List reduced from {len(rows)} to {min(len(rows), PROFILE_TOP_N)} due to restriction <{PROFILE_TOP_N}>",
+ "",
+ " ncalls tottime percall cumtime percall filename:lineno(function)",
+ ]
+
+ for (filename, lineno, funcname), stat in rows[:PROFILE_TOP_N]:
+ cc, nc, tt, ct, _callers = stat
+ ncalls = f"{cc}/{nc}" if cc != nc else str(nc)
+ percall_tt = tt / nc if nc else 0.0
+ percall_ct = ct / cc if cc else 0.0
+ location = f"{_sanitize_profile_path(filename)}:{lineno}({funcname})"
+ lines.append(
+ f"{ncalls:>9} {tt:>8.3f} {percall_tt:>8.3f} {ct:>8.3f} {percall_ct:>8.3f} {location}"
+ )
+
+ profile_text = "\n".join(lines)
+ if len(profile_text) <= PROFILE_MAX_CHARS:
+ return lines
+
+ truncated = profile_text[: PROFILE_MAX_CHARS - len("\n... [truncated]")] + "\n... [truncated]"
+ return truncated.splitlines()
+
+
+async def inject_profile_into_response(response, profile_lines: list[str]):
+ if isinstance(response, (FileResponse, StreamingResponse)):
+ return response
+
+ content_type = response.headers.get("content-type", "").lower()
+ if "application/json" not in content_type and "+json" not in content_type:
+ return response
+
+ if hasattr(response, "body") and response.body is not None:
+ body = response.body
+ else:
+ body = b""
+ async for chunk in response.body_iterator:
+ body += chunk
+
+ try:
+ payload = json.loads(body)
+ except (TypeError, ValueError):
+ return StarletteResponse(
+ content=body,
+ status_code=response.status_code,
+ headers=dict(response.headers),
+ media_type=response.media_type,
+ )
+
+ if not isinstance(payload, dict):
+ return StarletteResponse(
+ content=body,
+ status_code=response.status_code,
+ headers=dict(response.headers),
+ media_type=response.media_type,
+ )
+
+ payload["profile"] = profile_lines
+ rebuilt = JSONResponse(status_code=response.status_code, content=payload)
+ for key, value in response.headers.items():
+ if key.lower() not in {"content-length", "content-type"}:
+ rebuilt.headers[key] = value
+ return rebuilt
+
+
+def create_profile_http_middleware() -> Callable[[Request, Callable[..., Awaitable]], Awaitable]:
+ async def add_profile_output(request: Request, call_next: Callable[..., Awaitable]):
+ if not profile_enabled(request):
+ return await call_next(request)
+
+ profiler = cProfile.Profile()
+ profiler.enable()
+ try:
+ response = await call_next(request)
+ finally:
+ profiler.disable()
+
+ profile_lines = format_profile_output(profiler)
+ return await inject_profile_into_response(response, profile_lines)
+
+ return add_profile_output
diff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.py
index 0a9446e50..81e747b62 100644
--- a/openviking_cli/client/http.py
+++ b/openviking_cli/client/http.py
@@ -144,6 +144,7 @@ class AsyncHTTPClient(BaseClient):
user: Optional[str] = None,
timeout: float = 60.0,
extra_headers: Optional[Dict[str, str]] = None,
+ profile_enabled: Optional[bool] = None,
):
"""Initialize AsyncHTTPClient.
@@ -160,6 +161,7 @@ class AsyncHTTPClient(BaseClient):
extra_headers: Additional HTTP headers to send with requests. If not provided, reads from ovcli.conf.
"""
effective_user = user if user is not None else user_id
+ profile_load_requested = profile_enabled is None
should_load_cli_config = (
url is None
or api_key is None
@@ -169,6 +171,7 @@ class AsyncHTTPClient(BaseClient):
or timeout == 60.0
or extra_headers is None
)
+ cli_config = None
if should_load_cli_config:
cli_config = load_ovcli_config()
if cli_config is not None:
@@ -181,6 +184,11 @@ class AsyncHTTPClient(BaseClient):
timeout = cli_config.timeout
if extra_headers is None:
extra_headers = cli_config.extra_headers
+ if profile_load_requested:
+ if cli_config is None:
+ cli_config = load_ovcli_config()
+ if cli_config is not None:
+ profile_enabled = cli_config.profile
if not url:
raise ValueError(
"url is required. Pass it explicitly or configure in "
@@ -194,6 +202,7 @@ class AsyncHTTPClient(BaseClient):
self._user = UserIdentifier.the_default_user()
self._timeout = timeout
self._extra_headers = extra_headers
+ self._profile_enabled = bool(profile_enabled)
self._upload_mode = None
if should_load_cli_config and cli_config is not None and cli_config.upload is not None:
self._upload_mode = cli_config.upload.mode
@@ -219,6 +228,7 @@ class AsyncHTTPClient(BaseClient):
base_url=self._url,
headers=headers,
timeout=self._timeout,
+ params={"profile": "1"} if self._profile_enabled else None,
)
self._observer = _HTTPObserver(self)
diff --git a/openviking_cli/client/sync_http.py b/openviking_cli/client/sync_http.py
index 9819f26db..d2c8bf2f8 100644
--- a/openviking_cli/client/sync_http.py
+++ b/openviking_cli/client/sync_http.py
@@ -38,6 +38,7 @@ class SyncHTTPClient:
user: Optional[str] = None,
timeout: float = 60.0,
extra_headers: Optional[Dict[str, str]] = None,
+ profile_enabled: Optional[bool] = None,
):
self._async_client = AsyncHTTPClient(
url=url,
@@ -48,6 +49,7 @@ class SyncHTTPClient:
user=user,
timeout=timeout,
extra_headers=extra_headers,
+ profile_enabled=profile_enabled,
)
self._initialized = False
diff --git a/openviking_cli/utils/config/ovcli_config.py b/openviking_cli/utils/config/ovcli_config.py
index d7689955c..a89487421 100644
--- a/openviking_cli/utils/config/ovcli_config.py
+++ b/openviking_cli/utils/config/ovcli_config.py
@@ -32,6 +32,7 @@ class OVCLIConfig(BaseModel):
account: Optional[str] = None
user: Optional[str] = None
timeout: float = 60.0
+ profile: bool = False
upload: Optional[OVCLIUploadConfig] = None
extra_headers: Optional[Dict[str, str]] = None
diff --git a/tests/client/test_http_client_config.py b/tests/client/test_http_client_config.py
index a4abda6b3..88195238f 100644
--- a/tests/client/test_http_client_config.py
+++ b/tests/client/test_http_client_config.py
@@ -20,6 +20,7 @@ def test_async_http_client_loads_missing_fields_from_ovcli_config(tmp_path, monk
"account": "config-account",
"user": "config-user",
"timeout": 12.5,
+ "profile": True,
}
)
)
@@ -33,6 +34,7 @@ def test_async_http_client_loads_missing_fields_from_ovcli_config(tmp_path, monk
assert client._account == "config-account"
assert client._user_id == "config-user"
assert client._timeout == 12.5
+ assert client._profile_enabled is True
def test_async_http_client_explicit_values_override_ovcli_config(tmp_path, monkeypatch):
@@ -44,6 +46,7 @@ def test_async_http_client_explicit_values_override_ovcli_config(tmp_path, monke
"api_key": "config-key",
"account": "config-account",
"timeout": 12.5,
+ "profile": True,
}
)
)
@@ -54,17 +57,22 @@ def test_async_http_client_explicit_values_override_ovcli_config(tmp_path, monke
api_key="explicit-key",
account="explicit-account",
timeout=33.0,
+ profile_enabled=False,
)
assert client._url == "http://explicit-host:1933"
assert client._api_key == "explicit-key"
assert client._account == "explicit-account"
assert client._timeout == 33.0
+ assert client._profile_enabled is False
@pytest.mark.asyncio
-async def test_async_http_client_user_id_sets_openviking_user_header(monkeypatch):
+async def test_async_http_client_user_id_sets_openviking_user_header(tmp_path, monkeypatch):
captured: dict[str, object] = {}
+ config_path = tmp_path / "ovcli.conf"
+ config_path.write_text("{}")
+ monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))
class FakeAsyncClient:
def __init__(self, **kwargs):
diff --git a/tests/server/test_profile_middleware.py b/tests/server/test_profile_middleware.py
new file mode 100644
index 000000000..4dc87b930
--- /dev/null
+++ b/tests/server/test_profile_middleware.py
@@ -0,0 +1,145 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+import httpx
+import pytest
+from fastapi import APIRouter
+from fastapi.responses import PlainTextResponse, StreamingResponse
+
+from openviking.server.app import create_app
+from openviking.server.config import ServerConfig
+from openviking.server.profile_middleware import PROFILE_TOP_N, _sanitize_profile_path
+
+
+def _make_test_app():
+ class _Service:
+ _initialized = True
+
+ async def initialize(self):
+ pass
+
+ async def close(self):
+ pass
+
+ return create_app(config=ServerConfig(profile_enabled=True), service=_Service())
+
+
+def _make_test_app_with_config(config: ServerConfig):
+ class _Service:
+ _initialized = True
+
+ async def initialize(self):
+ pass
+
+ async def close(self):
+ pass
+
+ return create_app(config=config, service=_Service())
+
+
+async def test_profile_query_adds_profile_field_to_json_response():
+ app = _make_test_app()
+ transport = httpx.ASGITransport(app=app)
+
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ resp = await client.get("/health", params={"profile": "1"})
+
+ assert resp.status_code == 200
+ body = resp.json()
+ assert "profile" in body
+ assert isinstance(body["profile"], list)
+ assert any("ncalls" in line for line in body["profile"])
+ assert any("cumtime" in line for line in body["profile"])
+ assert not any(
+ "/Users/bytedance/github_openviking/OpenViking/" in line for line in body["profile"]
+ )
+ assert not any("/site-packages/" in line for line in body["profile"])
+ assert not any("/lib/python" in line for line in body["profile"])
+ assert any("openviking/" in line or "tests/" in line for line in body["profile"])
+ assert any(
+ "starlette/" in line or "fastapi/" in line or "asyncio/" in line for line in body["profile"]
+ )
+
+
+async def test_profile_query_does_not_affect_following_request():
+ app = _make_test_app()
+ transport = httpx.ASGITransport(app=app)
+
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ profiled = await client.get("/health", params={"profile": "1"})
+ plain = await client.get("/health")
+
+ assert profiled.status_code == 200
+ assert isinstance(profiled.json()["profile"], list)
+ assert plain.status_code == 200
+ assert "profile" not in plain.json()
+
+
+async def test_profile_query_is_ignored_when_server_profile_disabled():
+ app = _make_test_app_with_config(ServerConfig(profile_enabled=False))
+ transport = httpx.ASGITransport(app=app)
+
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ resp = await client.get("/health", params={"profile": "1"})
+
+ assert resp.status_code == 200
+ assert "profile" not in resp.json()
+
+
+async def test_profile_query_does_not_rewrite_plain_text_response():
+ app = _make_test_app()
+ router = APIRouter()
+
+ @router.get("/plain")
+ async def plain():
+ return PlainTextResponse("ok")
+
+ app.include_router(router)
+ transport = httpx.ASGITransport(app=app)
+
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ resp = await client.get("/plain", params={"profile": "1"})
+
+ assert resp.status_code == 200
+ assert resp.text == "ok"
+ assert resp.headers["content-type"].startswith("text/plain")
+
+
+async def test_profile_query_does_not_rewrite_streaming_response():
+ app = _make_test_app()
+ router = APIRouter()
+
+ async def _iterator():
+ yield b"streamed"
+
+ @router.get("/stream")
+ async def stream():
+ return StreamingResponse(_iterator(), media_type="text/plain")
+
+ app.include_router(router)
+ transport = httpx.ASGITransport(app=app)
+
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ resp = await client.get("/stream", params={"profile": "1"})
+
+ assert resp.status_code == 200
+ assert resp.text == "streamed"
+ assert resp.headers["content-type"].startswith("text/plain")
+
+
+def test_sanitize_profile_path_prefers_package_root_over_project_root_for_venv_packages():
+ path = (
+ "/Users/bytedance/github_openviking/OpenViking/"
+ ".venv/lib/python3.11/site-packages/starlette/middleware/base.py"
+ )
+
+ assert _sanitize_profile_path(path) == "starlette/middleware/base.py"
+
+
+def test_profile_default_top_n_is_100():
+ assert PROFILE_TOP_N == 100