Skip to content

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

feat(studio): show error details in request logs (#4172)

Hao Zhea809a0aaef80
diff --git a/openviking/metrics/datasources/http.py b/openviking/metrics/datasources/http.py
index 160dbc0e2..8b3fcccbc 100644
--- a/openviking/metrics/datasources/http.py
+++ b/openviking/metrics/datasources/http.py
@@ -13,6 +13,8 @@ The actual MetricRegistry writes are performed by HTTPCollector.
from __future__ import annotations
+from typing import Any
+
from .base import EventMetricDataSource
@@ -35,6 +37,9 @@ class HttpRequestLifecycleDataSource(EventMetricDataSource):
request_id: str | None = None,
user_id: str | None = None,
url_path: str | None = None,
+ error_code: str | None = None,
+ error_message: str | None = None,
+ error_details: dict[str, Any] | None = None,
) -> None:
"""
Emit a completed-request event with normalized method, route, status, and duration data.
@@ -55,6 +60,12 @@ class HttpRequestLifecycleDataSource(EventMetricDataSource):
payload["user_id"] = str(user_id)
if url_path is not None:
payload["url_path"] = str(url_path)
+ if error_code is not None:
+ payload["error_code"] = str(error_code)
+ if error_message is not None:
+ payload["error_message"] = str(error_message)
+ if error_details is not None:
+ payload["error_details"] = dict(error_details)
EventMetricDataSource._emit("http.request", payload)
@staticmethod
diff --git a/openviking/observability/http_error_context.py b/openviking/observability/http_error_context.py
new file mode 100644
index 000000000..4f02f8ada
--- /dev/null
+++ b/openviking/observability/http_error_context.py
@@ -0,0 +1,208 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Request-local capture of bounded public HTTP error information."""
+
+from __future__ import annotations
+
+import contextvars
+import json
+import re
+from dataclasses import dataclass
+from typing import Any
+
+MAX_ERROR_CODE_CHARS = 64
+MAX_ERROR_MESSAGE_CHARS = 500
+MAX_ERROR_DETAILS_BYTES = 4096
+
+_MAX_DETAIL_STRING_CHARS = 2048
+_MAX_DETAIL_KEY_CHARS = 256
+_MAX_CONTAINER_ITEMS = 100
+_MAX_DETAILS_DEPTH = 8
+_TRUNCATED_DETAILS = {"truncated": True}
+_REDACTED = "[REDACTED]"
+
+_SENSITIVE_KEYS = frozenset(
+ {
+ "access_token",
+ "api_key",
+ "authorization",
+ "client_secret",
+ "cookie",
+ "credential",
+ "password",
+ "refresh_token",
+ "root_api_key",
+ "secret",
+ "secret_access_key",
+ "secret_key",
+ "set_cookie",
+ "token",
+ "user_key",
+ }
+)
+_SENSITIVE_ASSIGNMENT_RE = re.compile(
+ r"(?i)\b(access[_-]?token|api[_-]?key|authorization|client[_-]?secret|cookie|"
+ r"credential|password|refresh[_-]?token|root[_-]?api[_-]?key|secret|"
+ r"secret[_-]?access[_-]?key|secret[_-]?key|set[_-]?cookie|token|user[_-]?key)"
+ r"(\s*[:=]\s*)(?:\"[^\"\r\n]*\"|'[^'\r\n]*'|[^\r\n,}\]]+)"
+)
+_TOKEN_RE = re.compile(
+ r"(?i)\b(?P<scheme>Bearer|Basic)\s+[a-zA-Z0-9._~+/=-]+|"
+ r"\b(?:sk-|cr_|ghp_|ntn_|xox[baprs]-)[a-zA-Z0-9._-]+"
+)
+
+
+@dataclass(frozen=True, slots=True)
+class CapturedHTTPError:
+ """Sanitized public error fields attached to one completed HTTP request."""
+
+ code: str
+ message: str
+ details: dict[str, Any] | None = None
+
+
+@dataclass(slots=True)
+class _HTTPErrorContext:
+ error: CapturedHTTPError | None = None
+
+
+_HTTP_ERROR_CONTEXT: contextvars.ContextVar[_HTTPErrorContext | None] = contextvars.ContextVar(
+ "openviking_http_error_context",
+ default=None,
+)
+
+
+def bind_http_error_context() -> contextvars.Token:
+ """Install a mutable request-local holder and return its reset token."""
+ return _HTTP_ERROR_CONTEXT.set(_HTTPErrorContext())
+
+
+def reset_http_error_context(token: contextvars.Token) -> None:
+ """Restore the previous request-local error holder."""
+ _HTTP_ERROR_CONTEXT.reset(token)
+
+
+def get_captured_http_error() -> CapturedHTTPError | None:
+ """Return the public error captured for the current request, if any."""
+ state = _HTTP_ERROR_CONTEXT.get()
+ return state.error if state is not None else None
+
+
+def capture_public_http_error(
+ *,
+ code: Any,
+ message: Any,
+ details: Any = None,
+) -> None:
+ """Capture the standard error envelope without changing the HTTP response."""
+ state = _HTTP_ERROR_CONTEXT.get()
+ if state is None:
+ return
+ try:
+ state.error = sanitize_public_http_error(code=code, message=message, details=details)
+ except Exception:
+ # Audit capture is a side channel and must never change the API response.
+ return
+
+
+def sanitize_public_http_error(
+ *,
+ code: Any,
+ message: Any,
+ details: Any = None,
+) -> CapturedHTTPError:
+ """Return bounded, credential-redacted fields safe for durable audit storage."""
+ return CapturedHTTPError(
+ code=_bounded_text(code, MAX_ERROR_CODE_CHARS),
+ message=_bounded_text(message, MAX_ERROR_MESSAGE_CHARS),
+ details=sanitize_public_error_details(details),
+ )
+
+
+def sanitize_public_error_details(details: Any) -> dict[str, Any] | None:
+ """Return a bounded JSON object, or ``None`` when no object was supplied."""
+ if not isinstance(details, dict):
+ return None
+ sanitized = _sanitize_detail_value(details, depth=0)
+ if not isinstance(sanitized, dict):
+ return None
+ try:
+ encoded = json.dumps(
+ sanitized,
+ ensure_ascii=False,
+ separators=(",", ":"),
+ allow_nan=False,
+ ).encode("utf-8")
+ except (TypeError, ValueError):
+ return dict(_TRUNCATED_DETAILS)
+ if len(encoded) > MAX_ERROR_DETAILS_BYTES:
+ return dict(_TRUNCATED_DETAILS)
+ return sanitized
+
+
+def serialize_public_error_details(details: Any) -> str | None:
+ """Serialize bounded public details for the SQLite TEXT column."""
+ sanitized = sanitize_public_error_details(details)
+ if sanitized is None:
+ return None
+ return json.dumps(sanitized, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
+
+
+def _bounded_text(value: Any, max_chars: int) -> str:
+ text = _redact_sensitive_text(str(value or ""))
+ if len(text) <= max_chars:
+ return text
+ suffix = "...[truncated]"
+ return text[: max(max_chars - len(suffix), 0)] + suffix[:max_chars]
+
+
+def _redact_sensitive_text(value: str) -> str:
+ def _redact_token(match: re.Match[str]) -> str:
+ scheme = match.groupdict().get("scheme")
+ return f"{scheme} {_REDACTED}" if scheme else _REDACTED
+
+ value = _TOKEN_RE.sub(_redact_token, value)
+
+ def _redact_assignment(match: re.Match[str]) -> str:
+ return f"{match.group(1)}{match.group(2)}{_REDACTED}"
+
+ return _SENSITIVE_ASSIGNMENT_RE.sub(_redact_assignment, value)
+
+
+def _is_sensitive_key(key: str) -> bool:
+ normalized = key.strip().lower().replace("-", "_")
+ return normalized in _SENSITIVE_KEYS or normalized.endswith(
+ ("_api_key", "_access_token", "_refresh_token", "_client_secret", "_password")
+ )
+
+
+def _sanitize_detail_value(value: Any, *, depth: int) -> Any:
+ if depth >= _MAX_DETAILS_DEPTH:
+ return "[truncated]"
+ if isinstance(value, dict):
+ result: dict[str, Any] = {}
+ for index, (key, item) in enumerate(value.items()):
+ if index >= _MAX_CONTAINER_ITEMS:
+ break
+ raw_key = str(key)
+ key_text = _bounded_text(raw_key, _MAX_DETAIL_KEY_CHARS)
+ result[key_text] = (
+ _REDACTED
+ if _is_sensitive_key(raw_key)
+ else _sanitize_detail_value(item, depth=depth + 1)
+ )
+ if len(value) > _MAX_CONTAINER_ITEMS:
+ result["truncated"] = True
+ return result
+ if isinstance(value, (list, tuple)):
+ items = [
+ _sanitize_detail_value(item, depth=depth + 1) for item in value[:_MAX_CONTAINER_ITEMS]
+ ]
+ if len(value) > _MAX_CONTAINER_ITEMS:
+ items.append("[truncated]")
+ return items
+ if isinstance(value, str):
+ return _bounded_text(value, _MAX_DETAIL_STRING_CHARS)
+ if value is None or isinstance(value, (bool, int, float)):
+ return value
+ return _bounded_text(value, _MAX_DETAIL_STRING_CHARS)
diff --git a/openviking/observability/http_observability_middleware.py b/openviking/observability/http_observability_middleware.py
index 48536cbc6..5df654a3c 100644
--- a/openviking/observability/http_observability_middleware.py
+++ b/openviking/observability/http_observability_middleware.py
@@ -26,6 +26,12 @@ from openviking.observability.context import (
bind_root_observability_context,
reset_root_observability_context,
)
+from openviking.observability.http_error_context import (
+ bind_http_error_context,
+ capture_public_http_error,
+ get_captured_http_error,
+ reset_http_error_context,
+)
from openviking.telemetry.span_models import RootSpanAttributes, create_root_span_attributes
from openviking_cli.utils import get_logger
@@ -676,6 +682,8 @@ def apply_http_metrics_finalize(
# Record request duration and status code
try:
+ captured_error = get_captured_http_error()
+ include_error = int(root_attrs.http_status_code or 500) >= 400
HttpRequestLifecycleDataSource.record_request(
method=root_attrs.http_method,
route=final_route,
@@ -685,6 +693,9 @@ def apply_http_metrics_finalize(
request_id=root_attrs.request_id,
user_id=root_attrs.user_id,
url_path=root_attrs.url_path,
+ error_code=captured_error.code if include_error and captured_error else None,
+ error_message=captured_error.message if include_error and captured_error else None,
+ error_details=captured_error.details if include_error and captured_error else None,
)
except (TypeError, ValueError, AttributeError) as e:
@@ -788,6 +799,30 @@ async def _execute_request_with_span(
return response
except Exception as exc:
+ # The catch-all JSON renderer is outside this middleware, so mirror
+ # its public mapping before the audit event is emitted. This keeps
+ # the stored status and envelope aligned with the client response;
+ # unexpected exception text remains confined to logs and traces.
+ try:
+ from openviking.server.error_mapping import map_exception
+ from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS
+
+ mapped = map_exception(exc)
+ except Exception:
+ mapped = None
+ if mapped is not None:
+ root_attrs.http_status_code = ERROR_CODE_TO_HTTP_STATUS.get(mapped.code, 500)
+ capture_public_http_error(
+ code=mapped.code,
+ message=mapped.message,
+ details=mapped.details,
+ )
+ else:
+ root_attrs.http_status_code = 500
+ capture_public_http_error(
+ code="INTERNAL",
+ message="Internal server error",
+ )
# Update route and span name if we have a real span
if span is not None:
_maybe_update_route_and_span_name(
@@ -844,6 +879,7 @@ def create_http_observability_middleware() -> Callable[[Request, Callable], Resp
request.state.request_id = request_id
# Bind root context and start metrics
+ error_token = bind_http_error_context()
root_token = bind_root_observability_context(root_attrs)
apply_http_metrics_start(request=request, root_attrs=root_attrs)
@@ -874,5 +910,6 @@ def create_http_observability_middleware() -> Callable[[Request, Callable], Resp
# Reset root context
reset_root_observability_context(root_token)
+ reset_http_error_context(error_token)
return middleware
diff --git a/openviking/observability/usage_audit/README.md b/openviking/observability/usage_audit/README.md
index 371e67478..68294dca8 100644
--- a/openviking/observability/usage_audit/README.md
+++ b/openviking/observability/usage_audit/README.md
@@ -159,8 +159,15 @@ vector filter,也不从历史写入事件累计当前库存。
- `api_type`
- `status_code`
- `duration_ms`
+- `error_code`(仅标准错误响应)
+- `error_message`(仅标准错误响应)
+- `error_details`(仅标准错误响应,可空)
- `created_at`
+错误字段来自 OpenViking 已返回给调用方的标准错误结构,不读取或缓存 HTTP response
+body。`error_details` 经过凭据脱敏和大小限制;它可能包含被拒绝的参数值,但不会额外保存
+原始 request body、header、query string、stack trace 或 exception text。
+
以下 route 不进入审计:
- `/metrics`
diff --git a/openviking/observability/usage_audit/projection.py b/openviking/observability/usage_audit/projection.py
index 53bda6abb..c0c719fba 100644
--- a/openviking/observability/usage_audit/projection.py
+++ b/openviking/observability/usage_audit/projection.py
@@ -10,6 +10,10 @@ from datetime import datetime, timezone
from typing import Any, Sequence
from openviking.observability.events import ObservabilityEvent
+from openviking.observability.http_error_context import (
+ sanitize_public_http_error,
+ serialize_public_error_details,
+)
UNKNOWN_IDENTITY = "__unknown__"
AUDIT_EXCLUDED_ROUTES = frozenset(
@@ -230,10 +234,24 @@ def _project_http_request(
audit_user = normalize_identity(payload.get("user_id") or event.user_id) or None
row_user = audit_user or ""
status = "success" if 200 <= status_code < 400 else "error"
+ error_code: str | None = None
+ error_message: str | None = None
+ error_details: str | None = None
+ if status_code >= 400 and any(
+ payload.get(key) is not None for key in ("error_code", "error_message", "error_details")
+ ):
+ captured_error = sanitize_public_http_error(
+ code=payload.get("error_code"),
+ message=payload.get("error_message"),
+ details=payload.get("error_details"),
+ )
+ error_code = captured_error.code or None
+ error_message = captured_error.message or None
+ error_details = serialize_public_error_details(captured_error.details)
retrieval_operation = retrieval_operation_for_http(method, route)
if retrieval_operation:
- key = (
+ retrieval_key = (
audit_account,
row_user,
event_date,
@@ -241,13 +259,13 @@ def _project_http_request(
retrieval_operation,
status,
)
- prev_count, prev_results = retrieval_rows[key]
- retrieval_rows[key] = (prev_count + 1, prev_results)
+ prev_count, prev_results = retrieval_rows[retrieval_key]
+ retrieval_rows[retrieval_key] = (prev_count + 1, prev_results)
context_operation = context_write_operation_for_http(method, route, status_code)
if context_operation:
- key = (audit_account, row_user, event_date, hour, context_operation)
- context_rows[key] += 1
+ context_key = (audit_account, row_user, event_date, hour, context_operation)
+ context_rows[context_key] += 1
audit_rows.append(
(
@@ -259,6 +277,9 @@ def _project_http_request(
str(payload.get("api_type") or derive_api_type(route)),
status_code,
duration_ms,
+ error_code,
+ error_message,
+ error_details,
created_at,
)
)
diff --git a/openviking/observability/usage_audit/schema.py b/openviking/observability/usage_audit/schema.py
index 1a5bafefe..c90199984 100644
--- a/openviking/observability/usage_audit/schema.py
+++ b/openviking/observability/usage_audit/schema.py
@@ -8,10 +8,10 @@ serve any region. Token and retrieval rollups are hour-grained so cross-tz
"today" queries can slice at user-local day boundaries.
"""
-# Bump when the table layout changes incompatibly. Stored on the `_schema_meta`
-# row so `SQLiteUsageAuditStore.initialize` can reset the local SQLite store
-# when an older snapshot is detected.
-SCHEMA_VERSION = 4
+# Stored on the `_schema_meta` row. Version 4 has an explicit additive migration;
+# unhandled newer transitions fail closed, while older incompatible snapshots
+# continue to use the reset path.
+SCHEMA_VERSION = 5
SQLITE_SCHEMA = """
CREATE TABLE IF NOT EXISTS _schema_meta (
@@ -80,6 +80,9 @@ CREATE TABLE IF NOT EXISTS request_audit (
api_type TEXT NOT NULL,
status_code INTEGER NOT NULL,
duration_ms REAL NOT NULL,
+ error_code TEXT,
+ error_message TEXT,
+ error_details TEXT,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_request_audit_account_created
diff --git a/openviking/observability/usage_audit/sqlite_store.py b/openviking/observability/usage_audit/sqlite_store.py
index 0814fde19..c3859fe47 100644
--- a/openviking/observability/usage_audit/sqlite_store.py
+++ b/openviking/observability/usage_audit/sqlite_store.py
@@ -10,6 +10,7 @@ underlying hourly rows into user-local days / hours.
from __future__ import annotations
import asyncio
+import json
import sqlite3
from datetime import date, datetime, time, timedelta, timezone, tzinfo
from pathlib import Path
@@ -71,10 +72,9 @@ class SQLiteUsageAuditStore:
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA foreign_keys=ON")
- # Reset incompatible pre-v3 local tables before creating the new
- # UTC/hourly layout. The SQLite backend has short retention and may live
- # inside one workspace, so dropping stale rollups is safer than mixing
- # old daily/local columns with the new UTC columns.
+ # Preserve the compatible v4 layout through its additive migration.
+ # Unknown newer transitions fail closed; older daily/local layouts
+ # remain incompatible and use the reset path.
self._migrate_legacy_sync(conn)
conn.executescript(SQLITE_SCHEMA)
conn.execute(
@@ -90,11 +90,42 @@ class SQLiteUsageAuditStore:
except sqlite3.OperationalError:
row = None
current = int(row["value"]) if row and row["value"] else 0
- if current >= SCHEMA_VERSION:
+ if current > SCHEMA_VERSION:
+ raise RuntimeError(
+ "Usage/audit database schema "
+ f"version {current} is newer than supported version {SCHEMA_VERSION}"
+ )
+ if current == SCHEMA_VERSION:
+ return
+ if current == 4 and SCHEMA_VERSION == 5:
+ SQLiteUsageAuditStore._migrate_v4_to_v5_sync(conn)
return
+ if current >= 4:
+ raise RuntimeError(
+ f"No usage/audit schema migration path from version {current} to {SCHEMA_VERSION}"
+ )
for table in RESET_ON_SCHEMA_UPGRADE_TABLES:
conn.execute(f"DROP TABLE IF EXISTS {table}")
+ @staticmethod
+ def _migrate_v4_to_v5_sync(conn: sqlite3.Connection) -> None:
+ """Add nullable audit error fields without deleting v4 usage data."""
+ table = conn.execute(
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_audit'"
+ ).fetchone()
+ if table is None:
+ return
+ columns = {str(row["name"]) for row in conn.execute("PRAGMA table_info(request_audit)")}
+ conn.execute("BEGIN")
+ try:
+ for name in ("error_code", "error_message", "error_details"):
+ if name not in columns:
+ conn.execute(f"ALTER TABLE request_audit ADD COLUMN {name} TEXT")
+ conn.execute("COMMIT")
+ except Exception:
+ conn.execute("ROLLBACK")
+ raise
+
async def close(self) -> None:
await asyncio.to_thread(self._close_sync)
@@ -224,9 +255,10 @@ class SQLiteUsageAuditStore:
"""
INSERT INTO request_audit (
request_id, account_id, user_id, method, route,
- api_type, status_code, duration_ms, created_at
+ api_type, status_code, duration_ms,
+ error_code, error_message, error_details, created_at
)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
rows,
)
@@ -710,7 +742,8 @@ class SQLiteUsageAuditStore:
rows = self._conn.execute(
f"""
SELECT request_id, account_id, user_id, method, route, api_type,
- status_code, duration_ms, created_at
+ status_code, duration_ms, error_code, error_message,
+ error_details, created_at
FROM request_audit
WHERE {where_sql}
ORDER BY created_at DESC, id DESC
@@ -723,9 +756,23 @@ class SQLiteUsageAuditStore:
"success_rate": (success / total) if total else 0.0,
"page": page,
"page_size": page_size,
- "items": [dict(row) for row in rows],
+ "items": [self._audit_item(row) for row in rows],
}
+ @staticmethod
+ def _audit_item(row: sqlite3.Row) -> dict[str, Any]:
+ item = dict(row)
+ raw_details = item.get("error_details")
+ if raw_details:
+ try:
+ decoded = json.loads(raw_details)
+ except (TypeError, ValueError):
+ decoded = None
+ item["error_details"] = decoded if isinstance(decoded, dict) else None
+ else:
+ item["error_details"] = None
+ return item
+
@staticmethod
def _status_filter_sql(statuses: list[str]) -> tuple[str, list[Any]]:
if not statuses:
diff --git a/openviking/server/app.py b/openviking/server/app.py
index 9335f479b..33355abcb 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -17,6 +17,7 @@ from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.middleware.exceptions import ExceptionMiddleware
+from openviking.observability.http_error_context import capture_public_http_error
from openviking.server.config import (
ServerConfig,
load_bot_gateway_token,
@@ -487,6 +488,7 @@ def create_app(
@app.exception_handler(OpenVikingError)
async def openviking_error_handler(request: Request, exc: OpenVikingError):
http_status = ERROR_CODE_TO_HTTP_STATUS.get(exc.code, 500)
+ capture_public_http_error(code=exc.code, message=exc.message, details=exc.details)
return JSONResponse(
status_code=http_status,
content=Response(
@@ -503,14 +505,21 @@ def create_app(
async def request_validation_error_handler(request: Request, exc: RequestValidationError):
errors = [_normalize_validation_error(error) for error in exc.errors()]
code = "INVALID_ARGUMENT"
+ message = _validation_error_message(errors)
+ details = {"validation_errors": errors}
+ capture_public_http_error(
+ code=code,
+ message=message,
+ details=details,
+ )
return JSONResponse(
status_code=ERROR_CODE_TO_HTTP_STATUS[code],
content=Response(
status="error",
error=ErrorInfo(
code=code,
- message=_validation_error_message(errors),
- details={"validation_errors": errors},
+ message=message,
+ details=details,
),
).model_dump(exclude_none=True),
)
@@ -524,6 +533,8 @@ def create_app(
details = None
if exc.status_code != response_status:
details = {"original_http_status_code": exc.status_code}
+ message = _message_from_http_detail(exc.detail)
+ capture_public_http_error(code=code, message=message, details=details)
return JSONResponse(
status_code=response_status,
headers=exc.headers,
@@ -531,7 +542,7 @@ def create_app(
status="error",
error=ErrorInfo(
code=code,
- message=_message_from_http_detail(exc.detail),
+ message=message,
details=details,
),
).model_dump(exclude_none=True),
diff --git a/openviking/server/responses.py b/openviking/server/responses.py
index 65a90866c..f0e7b383b 100644
--- a/openviking/server/responses.py
+++ b/openviking/server/responses.py
@@ -6,6 +6,7 @@ from typing import Any, Dict, Optional
from fastapi.responses import JSONResponse
+from openviking.observability.http_error_context import capture_public_http_error
from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Response
@@ -50,6 +51,11 @@ def response_from_result(
message=_message_from_business_error(result),
details=details if isinstance(details, dict) else None,
)
+ capture_public_http_error(
+ code=error.code,
+ message=error.message,
+ details=error.details,
+ )
content = Response(
status="error",
error=error,
@@ -75,6 +81,7 @@ def error_response(
telemetry: Optional[Dict[str, Any]] = None,
):
"""Build a standard API error response with the mapped HTTP status."""
+ capture_public_http_error(code=code, message=message, details=details)
content = Response(
status="error",
error=ErrorInfo(code=code, message=message, details=details),
diff --git a/tests/observability/test_http_error_context.py b/tests/observability/test_http_error_context.py
new file mode 100644
index 000000000..4b7256de9
--- /dev/null
+++ b/tests/observability/test_http_error_context.py
@@ -0,0 +1,68 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+from openviking.observability.http_error_context import (
+ MAX_ERROR_CODE_CHARS,
+ MAX_ERROR_DETAILS_BYTES,
+ MAX_ERROR_MESSAGE_CHARS,
+ bind_http_error_context,
+ capture_public_http_error,
+ get_captured_http_error,
+ reset_http_error_context,
+ sanitize_public_http_error,
+ serialize_public_error_details,
+)
+
+
+def test_public_http_error_is_bounded_and_redacts_credentials() -> None:
+ error = sanitize_public_http_error(
+ code="X" * 100,
+ message=(
+ "authorization=Basic dXNlcjpwYXNz, "
+ "api_key='top secret', Bearer bearer-secret rejected " + "m" * 600
+ ),
+ details={
+ "api_key": "sk-secret",
+ "rejected_value": "Bearer another-secret",
+ "nested": {
+ "client-secret": "very-secret",
+ "message": "password='secret phrase'",
+ },
+ },
+ )
+
+ assert len(error.code) == MAX_ERROR_CODE_CHARS
+ assert len(error.message) == MAX_ERROR_MESSAGE_CHARS
+ assert "dXNlcjpwYXNz" not in error.message
+ assert "top secret" not in error.message
+ assert "bearer-secret" not in error.message
+ assert error.details == {
+ "api_key": "[REDACTED]",
+ "rejected_value": "Bearer [REDACTED]",
+ "nested": {
+ "client-secret": "[REDACTED]",
+ "message": "password=[REDACTED]",
+ },
+ }
+
+
+def test_oversized_public_error_details_use_bounded_marker() -> None:
+ serialized = serialize_public_error_details(
+ {f"value-{index}": "x" * 100 for index in range(MAX_ERROR_DETAILS_BYTES // 50)}
+ )
+
+ assert serialized == '{"truncated":true}'
+ assert len(serialized.encode("utf-8")) <= MAX_ERROR_DETAILS_BYTES
+
+
+def test_public_error_capture_never_changes_response_control_flow() -> None:
+ class BrokenString:
+ def __str__(self) -> str:
+ raise RuntimeError("cannot serialize")
+
+ token = bind_http_error_context()
+ try:
+ capture_public_http_error(code=BrokenString(), message="safe")
+ assert get_captured_http_error() is None
+ finally:
+ reset_http_error_context(token)
diff --git a/tests/observability/test_usage_audit_runtime.py b/tests/observability/test_usage_audit_runtime.py
index 3e1a5d718..451473d26 100644
--- a/tests/observability/test_usage_audit_runtime.py
+++ b/tests/observability/test_usage_audit_runtime.py
@@ -41,6 +41,8 @@ async def test_usage_audit_runtime_subscribes_to_shared_event_bus(tmp_path):
"route": "/api/v1/search/find",
"status": "200",
"duration_seconds": 0.01,
+ "error_code": "SHOULD_NOT_PERSIST",
+ "error_message": "success response",
},
)
await runtime.worker.close(timeout_seconds=1.0)
@@ -60,3 +62,6 @@ async def test_usage_audit_runtime_subscribes_to_shared_event_bus(tmp_path):
assert retrievals["find"] == 1
assert audit["total"] == 1
assert audit["items"][0]["request_id"] == "req-runtime"
+ assert audit["items"][0]["error_code"] is None
+ assert audit["items"][0]["error_message"] is None
+ assert audit["items"][0]["error_details"] is None
diff --git a/tests/observability/test_usage_audit_store.py b/tests/observability/test_usage_audit_store.py
index ae59ad40e..655d494f4 100644
--- a/tests/observability/test_usage_audit_store.py
+++ b/tests/observability/test_usage_audit_store.py
@@ -10,6 +10,7 @@ from zoneinfo import ZoneInfo
import pytest
from openviking.observability.events import ObservabilityEvent
+from openviking.observability.usage_audit import sqlite_store as sqlite_store_module
from openviking.observability.usage_audit.sqlite_store import SQLiteUsageAuditStore
UTC = ZoneInfo("UTC")
@@ -37,6 +38,11 @@ def _create_legacy_usage_audit_db(db_path) -> None:
try:
conn.executescript(
"""
+ CREATE TABLE _schema_meta (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL
+ );
+ INSERT INTO _schema_meta (key, value) VALUES ('version', '3');
CREATE TABLE usage_token_daily (
account_id TEXT NOT NULL,
user_id TEXT NOT NULL,
@@ -100,6 +106,98 @@ def _create_legacy_usage_audit_db(db_path) -> None:
conn.close()
+def _create_v4_usage_audit_db(db_path) -> None:
+ """Create and populate the exact compatible layout shipped by schema v4."""
+ conn = sqlite3.connect(db_path)
+ try:
+ conn.executescript(
+ """
+ CREATE TABLE _schema_meta (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL
+ );
+ INSERT INTO _schema_meta (key, value) VALUES ('version', '4');
+
+ CREATE TABLE usage_token_hourly (
+ account_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ date_utc TEXT NOT NULL,
+ hour_utc INTEGER NOT NULL,
+ source TEXT NOT NULL,
+ token_type TEXT NOT NULL,
+ provider TEXT NOT NULL,
+ model_name TEXT NOT NULL,
+ token_count INTEGER NOT NULL DEFAULT 0,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (
+ account_id, user_id, date_utc, hour_utc,
+ source, token_type, provider, model_name
+ )
+ );
+ CREATE TABLE usage_retrieval_hourly (
+ account_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ date_utc TEXT NOT NULL,
+ hour_utc INTEGER NOT NULL,
+ operation TEXT NOT NULL,
+ status TEXT NOT NULL,
+ request_count INTEGER NOT NULL DEFAULT 0,
+ result_count INTEGER NOT NULL DEFAULT 0,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (
+ account_id, user_id, date_utc, hour_utc, operation, status
+ )
+ );
+ CREATE TABLE usage_context_write_bucket (
+ account_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ date_utc TEXT NOT NULL,
+ hour_utc INTEGER NOT NULL,
+ operation TEXT NOT NULL,
+ count INTEGER NOT NULL DEFAULT 0,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (account_id, user_id, date_utc, hour_utc, operation)
+ );
+ CREATE TABLE request_audit (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ request_id TEXT,
+ account_id TEXT NOT NULL,
+ user_id TEXT,
+ method TEXT NOT NULL,
+ route TEXT NOT NULL,
+ api_type TEXT NOT NULL,
+ status_code INTEGER NOT NULL,
+ duration_ms REAL NOT NULL,
+ created_at TEXT NOT NULL
+ );
+
+ INSERT INTO usage_token_hourly VALUES (
+ 'acct-1', 'user-1', '2026-05-12', 1,
+ 'vlm', 'input', 'p', 'm', 11, '2026-05-12T01:02:03+00:00'
+ );
+ INSERT INTO usage_retrieval_hourly VALUES (
+ 'acct-1', 'user-1', '2026-05-12', 1,
+ 'find', 'success', 2, 0, '2026-05-12T01:02:03+00:00'
+ );
+ INSERT INTO usage_context_write_bucket VALUES (
+ 'acct-1', 'user-1', '2026-05-12', 1,
+ 'session.commit', 3, '2026-05-12T01:02:03+00:00'
+ );
+ INSERT INTO request_audit (
+ request_id, account_id, user_id, method, route,
+ api_type, status_code, duration_ms, created_at
+ ) VALUES (
+ 'v4-request', 'acct-1', 'user-1', 'GET',
+ '/api/v1/system/status', 'system', 200, 1.0,
+ '2026-05-12T01:02:03+00:00'
+ );
+ """
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+
@pytest.mark.asyncio
async def test_sqlite_usage_audit_store_aggregates_dashboard_data(tmp_path):
store = SQLiteUsageAuditStore(tmp_path / "usage.sqlite3")
@@ -346,11 +444,154 @@ async def test_sqlite_usage_audit_store_resets_incompatible_legacy_schema(tmp_pa
assert "hour_utc" in context_columns
assert "hour_bucket" not in context_columns
version = conn.execute("SELECT value FROM _schema_meta WHERE key = 'version'").fetchone()
- assert version == ("4",)
+ assert version == ("5",)
+ finally:
+ conn.close()
+
+
+async def test_sqlite_usage_audit_store_migrates_v4_without_losing_rows(tmp_path):
+ db_path = tmp_path / "usage.sqlite3"
+ _create_v4_usage_audit_db(db_path)
+
+ store = SQLiteUsageAuditStore(db_path)
+ await store.initialize()
+ try:
+ tokens = await store.get_today_tokens(
+ account_id="acct-1",
+ user_id="user-1",
+ user_date="2026-05-12",
+ tz=UTC,
+ )
+ retrievals = await store.get_today_retrievals(
+ account_id="acct-1",
+ user_id="user-1",
+ user_date="2026-05-12",
+ tz=UTC,
+ )
+ commits = await store.get_context_commit_heatmap(
+ account_id="acct-1",
+ user_id="user-1",
+ start_user_date="2026-05-12",
+ end_user_date="2026-05-12",
+ bucket="hour",
+ tz=UTC,
+ )
+ before = await store.query_audit_logs(account_id="acct-1", page_size=10)
+
+ assert tokens["vlm_input"] == 11
+ assert retrievals["find"] == 2
+ assert any(row["session_commit"] == 3 for row in commits)
+ assert before["items"][0]["request_id"] == "v4-request"
+ assert before["items"][0]["error_code"] is None
+ assert before["items"][0]["error_message"] is None
+ assert before["items"][0]["error_details"] is None
+
+ await store.record_batch(
+ [
+ _event(
+ "http.request",
+ {
+ "request_id": "new-error",
+ "method": "GET",
+ "route": "/api/v1/tasks/{task_id}",
+ "status": "404",
+ "duration_seconds": 0.01,
+ "error_code": "NOT_FOUND",
+ "error_message": "Task was not found",
+ "error_details": {"task_id": "missing"},
+ },
+ )
+ ]
+ )
+ after = await store.query_audit_logs(account_id="acct-1", page_size=10)
+ inserted = next(item for item in after["items"] if item["request_id"] == "new-error")
+ assert inserted["error_code"] == "NOT_FOUND"
+ assert inserted["error_message"] == "Task was not found"
+ assert inserted["error_details"] == {"task_id": "missing"}
+ assert {item["request_id"] for item in after["items"]} == {
+ "v4-request",
+ "new-error",
+ }
+ finally:
+ await store.close()
+
+ conn = sqlite3.connect(db_path)
+ try:
+ columns = {row[1] for row in conn.execute("PRAGMA table_info(request_audit)")}
+ assert {"error_code", "error_message", "error_details"} <= columns
+ version = conn.execute("SELECT value FROM _schema_meta WHERE key = 'version'").fetchone()
+ assert version == ("5",)
+ finally:
+ conn.close()
+
+
+async def test_sqlite_usage_audit_store_rejects_unhandled_future_migration_without_data_loss(
+ tmp_path, monkeypatch
+):
+ db_path = tmp_path / "usage.sqlite3"
+ _create_v4_usage_audit_db(db_path)
+
+ store = SQLiteUsageAuditStore(db_path)
+ await store.initialize()
+ await store.close()
+
+ monkeypatch.setattr(sqlite_store_module, "SCHEMA_VERSION", 6)
+ conn = sqlite3.connect(db_path)
+ conn.row_factory = sqlite3.Row
+ try:
+ with pytest.raises(
+ RuntimeError,
+ match="No usage/audit schema migration path from version 5 to 6",
+ ):
+ SQLiteUsageAuditStore._migrate_legacy_sync(conn)
+
+ assert conn.execute("SELECT COUNT(*) FROM request_audit").fetchone()[0] == 1
+ assert conn.execute("SELECT COUNT(*) FROM usage_token_hourly").fetchone()[0] == 1
+ version = conn.execute("SELECT value FROM _schema_meta WHERE key = 'version'").fetchone()
+ assert version[0] == "5"
finally:
conn.close()
+async def test_sqlite_usage_audit_store_handles_malformed_error_details(tmp_path):
+ db_path = tmp_path / "usage.sqlite3"
+ store = SQLiteUsageAuditStore(db_path)
+ await store.initialize()
+ try:
+ assert store._conn is not None
+ store._conn.execute(
+ """
+ INSERT INTO request_audit (
+ request_id, account_id, user_id, method, route, api_type,
+ status_code, duration_ms, error_code, error_message,
+ error_details, created_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """,
+ (
+ "malformed",
+ "acct-1",
+ "user-1",
+ "GET",
+ "/api/v1/tasks/{task_id}",
+ "tasks",
+ 404,
+ 1.0,
+ "NOT_FOUND",
+ "Task was not found",
+ "not-json",
+ "2026-05-12T01:02:03+00:00",
+ ),
+ )
+
+ audit = await store.query_audit_logs(account_id="acct-1")
+ assert audit["items"][0]["error_details"] is None
+ finally:
+ await store.close()
+
+
@pytest.mark.asyncio
async def test_sqlite_usage_audit_store_trims_audit_per_account(tmp_path):
store = SQLiteUsageAuditStore(
diff --git a/tests/server/test_request_id.py b/tests/server/test_request_id.py
index 9cc9503e2..c8204b413 100644
--- a/tests/server/test_request_id.py
+++ b/tests/server/test_request_id.py
@@ -14,6 +14,7 @@ import httpx
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
+from openviking.metrics.datasources import HttpRequestLifecycleDataSource
from openviking.observability.context import get_root_observability_context
from openviking.observability.http_observability_middleware import (
create_http_observability_middleware,
@@ -128,9 +129,15 @@ async def test_invalid_request_ids_are_rejected_without_logging_raw_values() ->
assert all(raw not in rendered for raw in ("contains spaces", "x" * 129, "first", "second"))
-async def test_unhandled_500_keeps_request_id_for_log_and_response() -> None:
+async def test_unhandled_500_keeps_request_id_for_log_and_response(monkeypatch) -> None:
app = create_app(config=ServerConfig(), service=SimpleNamespace())
records: list[logging.LogRecord] = []
+ completed_requests: list[dict] = []
+ monkeypatch.setattr(
+ HttpRequestLifecycleDataSource,
+ "record_request",
+ lambda **kwargs: completed_requests.append(kwargs),
+ )
server_logger = logging.getLogger("openviking")
handler = _CaptureHandler(records)
@@ -159,6 +166,35 @@ async def test_unhandled_500_keeps_request_id_for_log_and_response() -> None:
assert len(error_records) == 1
assert error_records[0].request_id == "failed-request-001"
assert error_records[0].getMessage().startswith("[request_id=failed-request-001] ")
+ assert len(completed_requests) == 1
+ assert completed_requests[0]["error_code"] == "INTERNAL"
+ assert completed_requests[0]["error_message"] == "Internal server error"
+ assert completed_requests[0]["error_details"] is None
+ assert "synthetic failure" not in str(completed_requests[0])
+
+
+async def test_mapped_exception_audit_matches_public_response(monkeypatch) -> None:
+ app = create_app(config=ServerConfig(), service=SimpleNamespace())
+ completed_requests: list[dict] = []
+ monkeypatch.setattr(
+ HttpRequestLifecycleDataSource,
+ "record_request",
+ lambda **kwargs: completed_requests.append(kwargs),
+ )
+
+ @app.get("/_request-id-test/invalid")
+ async def invalid():
+ raise ValueError("invalid page size")
+
+ response = await _request(app, "/_request-id-test/invalid")
+
+ assert response.status_code == 400
+ assert response.json()["error"]["code"] == "INVALID_ARGUMENT"
+ assert len(completed_requests) == 1
+ assert completed_requests[0]["status"] == "400"
+ assert completed_requests[0]["error_code"] == "INVALID_ARGUMENT"
+ assert completed_requests[0]["error_message"] == "invalid page size"
+ assert completed_requests[0]["error_details"] == response.json()["error"]["details"]
async def test_concurrent_requests_do_not_mix_or_leak_request_ids() -> None:
diff --git a/tests/telemetry/test_http_observability_middleware.py b/tests/telemetry/test_http_observability_middleware.py
index c3a9568e5..9a1863cb9 100644
--- a/tests/telemetry/test_http_observability_middleware.py
+++ b/tests/telemetry/test_http_observability_middleware.py
@@ -1,6 +1,10 @@
from fastapi import FastAPI
from fastapi.testclient import TestClient
+from openviking.metrics.datasources import HttpRequestLifecycleDataSource
+from openviking.server.request_id import RequestIdMiddleware
+from openviking.server.responses import error_response, response_from_result
+
class _DummySpan:
def __init__(self) -> None:
@@ -76,3 +80,74 @@ def test_http_observability_middleware_updates_route_template_after_routing(monk
assert root_attrs.url_query is None
assert "url.query" not in root_attrs.to_otel_attributes()
assert "GET /hello" in dummy_span.updated_names
+
+
+def test_http_observability_captures_public_error_without_reading_response_body(
+ monkeypatch,
+) -> None:
+ from openviking.observability import http_observability_middleware as mw_mod
+
+ completed: list[dict] = []
+ monkeypatch.setattr(HttpRequestLifecycleDataSource, "set_inflight", lambda **_: None)
+ monkeypatch.setattr(
+ HttpRequestLifecycleDataSource,
+ "record_request",
+ lambda **kwargs: completed.append(kwargs),
+ )
+ monkeypatch.setattr(mw_mod, "maybe_start_root_span", lambda *_: None)
+
+ app = FastAPI()
+ http_mw = mw_mod.create_http_observability_middleware()
+
+ @app.middleware("http")
+ async def _mw(request, call_next):
+ return await http_mw(request, call_next)
+
+ app.add_middleware(RequestIdMiddleware)
+
+ @app.get("/invalid")
+ async def invalid():
+ return error_response(
+ "INVALID_ARGUMENT",
+ "limit must be at most 200",
+ details={"limit": 300, "api_key": "sk-not-persisted"},
+ )
+
+ @app.get("/unavailable")
+ async def unavailable():
+ return error_response(
+ "UNAVAILABLE",
+ "Parser service is unavailable",
+ details={"retryable": True},
+ )
+
+ @app.get("/business-error")
+ async def business_error():
+ return response_from_result(
+ {
+ "status": "error",
+ "code": "PROCESSING_ERROR",
+ "message": "Resource processing failed",
+ "details": {"stage": "parse"},
+ }
+ )
+
+ with TestClient(app) as client:
+ invalid_response = client.get("/invalid")
+ unavailable_response = client.get("/unavailable")
+ business_response = client.get("/business-error")
+
+ assert invalid_response.status_code == 400
+ assert invalid_response.json()["error"]["details"]["api_key"] == "sk-not-persisted"
+ assert unavailable_response.status_code == 503
+ assert business_response.status_code == 500
+ assert len(completed) == 3
+ assert completed[0]["error_code"] == "INVALID_ARGUMENT"
+ assert completed[0]["error_message"] == "limit must be at most 200"
+ assert completed[0]["error_details"] == {"limit": 300, "api_key": "[REDACTED]"}
+ assert completed[1]["error_code"] == "UNAVAILABLE"
+ assert completed[1]["error_message"] == "Parser service is unavailable"
+ assert completed[1]["error_details"] == {"retryable": True}
+ assert completed[2]["error_code"] == "PROCESSING_ERROR"
+ assert completed[2]["error_message"] == "Resource processing failed"
+ assert completed[2]["error_details"] == {"stage": "parse"}
diff --git a/web-studio/src/i18n/locales/en/resources.ts b/web-studio/src/i18n/locales/en/resources.ts
index c3a011603..a845737cf 100644
--- a/web-studio/src/i18n/locales/en/resources.ts
+++ b/web-studio/src/i18n/locales/en/resources.ts
@@ -18,6 +18,13 @@ const resources = {
'Usage/Audit is not initialized, so server-side request logs are unavailable.',
title: 'Audit logs unavailable',
},
+ details: {
+ code: 'Error code',
+ data: 'Error details',
+ hide: 'Hide error details',
+ message: 'Error message',
+ show: 'Show error details',
+ },
empty: {
description: 'Start your first audited API call!',
filteredDescription:
diff --git a/web-studio/src/i18n/locales/zh-CN/resources.ts b/web-studio/src/i18n/locales/zh-CN/resources.ts
index 71058dfad..fef182bf4 100644
--- a/web-studio/src/i18n/locales/zh-CN/resources.ts
+++ b/web-studio/src/i18n/locales/zh-CN/resources.ts
@@ -17,6 +17,13 @@ const resources = {
description: 'Usage/Audit 未初始化,暂无服务端请求日志。',
title: '审计日志不可用',
},
+ details: {
+ code: '错误代码',
+ data: '错误详情',
+ hide: '收起错误详情',
+ message: '错误信息',
+ show: '展开错误详情',
+ },
empty: {
description: '先开始您的第一次可审计调用吧!',
filteredDescription: '调整搜索内容或状态筛选,扩大可见日志范围。',
diff --git a/web-studio/src/routes/request-logs/-components/row.test.tsx b/web-studio/src/routes/request-logs/-components/row.test.tsx
new file mode 100644
index 000000000..74f370e94
--- /dev/null
+++ b/web-studio/src/routes/request-logs/-components/row.test.tsx
@@ -0,0 +1,88 @@
+// @vitest-environment jsdom
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { RequestLogRow } from './row'
+import type { ConsoleAuditLogItem } from '@ov-server/api/v1/console'
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+
+afterEach(cleanup)
+
+function renderRow(log: ConsoleAuditLogItem) {
+ return render(
+ <table>
+ <tbody>
+ <RequestLogRow log={log} />
+ </tbody>
+ </table>,
+ )
+}
+
+describe('RequestLogRow', () => {
+ it('expands structured error information from the existing audit row', () => {
+ renderRow({
+ api_type: 'tasks',
+ error_code: 'INVALID_ARGUMENT',
+ error_details: { limit: 300 },
+ error_message: 'limit must be at most 200',
+ method: 'GET',
+ route: '/api/v1/tasks',
+ status_code: 400,
+ })
+
+ expect(screen.queryByText('INVALID_ARGUMENT')).toBeNull()
+ fireEvent.click(screen.getByRole('button', { name: 'details.show' }))
+
+ expect(screen.getByText('INVALID_ARGUMENT')).toBeTruthy()
+ expect(screen.getByText('limit must be at most 200')).toBeTruthy()
+ expect(screen.getByText(/"limit": 300/)).toBeTruthy()
+ expect(
+ screen
+ .getByRole('button', { name: 'details.hide' })
+ .getAttribute('aria-expanded'),
+ ).toBe('true')
+ })
+
+ it('also expands when the user clicks the error row', () => {
+ renderRow({
+ error_code: 'NOT_FOUND',
+ error_message: 'Task was not found',
+ method: 'GET',
+ route: '/api/v1/tasks/{task_id}',
+ status_code: 404,
+ })
+
+ const route = screen.getByText('/api/v1/tasks/{task_id}')
+ fireEvent.click(route.closest('tr')!)
+
+ expect(screen.getByText('NOT_FOUND')).toBeTruthy()
+ expect(screen.getByText('Task was not found')).toBeTruthy()
+ })
+
+ it('omits the structured details section for an empty object', () => {
+ renderRow({
+ error_code: 'PERMISSION_DENIED',
+ error_details: {},
+ error_message: 'Permission denied',
+ method: 'GET',
+ route: '/api/v1/resources',
+ status_code: 403,
+ })
+
+ fireEvent.click(screen.getByRole('button', { name: 'details.show' }))
+
+ expect(screen.getByText('PERMISSION_DENIED')).toBeTruthy()
+ expect(screen.getByText('Permission denied')).toBeTruthy()
+ expect(screen.queryByText('details.data')).toBeNull()
+ })
+
+ it('does not add an expansion control to rows without captured errors', () => {
+ renderRow({ method: 'GET', route: '/api/v1/tasks', status_code: 200 })
+
+ expect(screen.queryByRole('button')).toBeNull()
+ })
+})
diff --git a/web-studio/src/routes/request-logs/-components/row.tsx b/web-studio/src/routes/request-logs/-components/row.tsx
index 76df50eb5..72d254614 100644
--- a/web-studio/src/routes/request-logs/-components/row.tsx
+++ b/web-studio/src/routes/request-logs/-components/row.tsx
@@ -1,6 +1,9 @@
+import { useId, useState } from 'react'
+import { ChevronRightIcon } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { Badge } from '#/components/ui/badge'
+import { Button } from '#/components/ui/button'
import { TableCell, TableRow } from '#/components/ui/table'
import { cn } from '#/lib/utils'
import type { ConsoleAuditLogItem } from '@ov-server/api/v1/console'
@@ -19,58 +22,140 @@ type RequestLogRowProps = {
export function RequestLogRow({ log }: RequestLogRowProps) {
const { t } = useTranslation('requestLogs')
+ const [expanded, setExpanded] = useState(false)
+ const detailsId = useId()
const status = normalizeStatus(log.status_code)
const method = log.method ?? '-'
const isSlow = (log.duration_ms ?? 0) > 1000
+ const hasErrorDetails = Boolean(
+ log.error_code || log.error_message || log.error_details,
+ )
+ const hasStructuredDetails = Boolean(
+ log.error_details && Object.keys(log.error_details).length > 0,
+ )
+ const serializedDetails = hasStructuredDetails
+ ? JSON.stringify(log.error_details, null, 2)
+ : null
+
+ const toggleExpanded = () => {
+ if (hasErrorDetails) {
+ setExpanded((value) => !value)
+ }
+ }
return (
- <TableRow>
- <TableCell className="text-muted-foreground tabular-nums">
- {formatTime(log.created_at)}
- </TableCell>
- <TableCell className="max-w-40 truncate font-mono text-xs text-muted-foreground">
- {log.api_type || '-'}
- </TableCell>
- <TableCell>
- <span
- className={cn('font-mono text-xs font-semibold', methodTone(method))}
- >
- {method}
- </span>
- </TableCell>
- <TableCell className="max-w-[34rem]">
- <div className="truncate font-mono text-xs text-foreground">
- {log.route || '/'}
- </div>
- </TableCell>
- <TableCell>
- <Badge
- variant="outline"
+ <>
+ <TableRow
+ className={cn(hasErrorDetails && 'cursor-pointer')}
+ onClick={hasErrorDetails ? toggleExpanded : undefined}
+ >
+ <TableCell className="text-muted-foreground tabular-nums">
+ {formatTime(log.created_at)}
+ </TableCell>
+ <TableCell className="max-w-40 truncate font-mono text-xs text-muted-foreground">
+ {log.api_type || '-'}
+ </TableCell>
+ <TableCell>
+ <span
+ className={cn(
+ 'font-mono text-xs font-semibold',
+ methodTone(method),
+ )}
+ >
+ {method}
+ </span>
+ </TableCell>
+ <TableCell className="max-w-[34rem]">
+ <div className="truncate font-mono text-xs text-foreground">
+ {log.route || '/'}
+ </div>
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-1">
+ <Badge
+ variant="outline"
+ className={cn(
+ 'font-mono text-xs',
+ getStatusTone(status, log.status_code),
+ )}
+ >
+ {log.status_code ?? t(`status.${status}`)}
+ </Badge>
+ {hasErrorDetails ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ aria-controls={detailsId}
+ aria-expanded={expanded}
+ aria-label={t(expanded ? 'details.hide' : 'details.show')}
+ onClick={(event) => {
+ event.stopPropagation()
+ toggleExpanded()
+ }}
+ >
+ <ChevronRightIcon
+ className={cn(
+ 'transition-transform',
+ expanded && 'rotate-90',
+ )}
+ />
+ </Button>
+ ) : null}
+ </div>
+ </TableCell>
+ <TableCell
className={cn(
- 'font-mono text-xs',
- getStatusTone(status, log.status_code),
+ 'text-right font-mono text-xs tabular-nums text-muted-foreground',
+ isSlow && 'font-semibold text-amber-600 dark:text-amber-300',
)}
>
- {log.status_code ?? t(`status.${status}`)}
- </Badge>
- </TableCell>
- <TableCell
- className={cn(
- 'text-right font-mono text-xs tabular-nums text-muted-foreground',
- isSlow && 'font-semibold text-amber-600 dark:text-amber-300',
- )}
- >
- {formatDuration(log.duration_ms)}
- </TableCell>
- <TableCell className="max-w-44 truncate font-mono text-xs text-muted-foreground">
- {log.request_id || '-'}
- </TableCell>
- <TableCell className="max-w-36 truncate font-mono text-xs text-muted-foreground">
- {log.account_id || '-'}
- </TableCell>
- <TableCell className="max-w-36 truncate font-mono text-xs text-muted-foreground">
- {log.user_id || '-'}
- </TableCell>
- </TableRow>
+ {formatDuration(log.duration_ms)}
+ </TableCell>
+ <TableCell className="max-w-44 truncate font-mono text-xs text-muted-foreground">
+ {log.request_id || '-'}
+ </TableCell>
+ <TableCell className="max-w-36 truncate font-mono text-xs text-muted-foreground">
+ {log.account_id || '-'}
+ </TableCell>
+ <TableCell className="max-w-36 truncate font-mono text-xs text-muted-foreground">
+ {log.user_id || '-'}
+ </TableCell>
+ </TableRow>
+ {hasErrorDetails && expanded ? (
+ <TableRow id={detailsId} className="bg-muted/20 hover:bg-muted/20">
+ <TableCell colSpan={9} className="whitespace-normal px-4 py-3">
+ <div className="grid gap-3 text-sm md:grid-cols-[12rem_minmax(0,1fr)]">
+ <div>
+ <div className="text-xs font-medium text-muted-foreground">
+ {t('details.code')}
+ </div>
+ <div className="mt-1 font-mono text-xs text-foreground">
+ {log.error_code || '-'}
+ </div>
+ </div>
+ <div>
+ <div className="text-xs font-medium text-muted-foreground">
+ {t('details.message')}
+ </div>
+ <div className="mt-1 break-words text-foreground">
+ {log.error_message || '-'}
+ </div>
+ </div>
+ {serializedDetails ? (
+ <div className="md:col-span-2">
+ <div className="text-xs font-medium text-muted-foreground">
+ {t('details.data')}
+ </div>
+ <pre className="mt-1 overflow-x-auto rounded-md border bg-background p-3 font-mono text-xs whitespace-pre-wrap text-foreground">
+ {serializedDetails}
+ </pre>
+ </div>
+ ) : null}
+ </div>
+ </TableCell>
+ </TableRow>
+ ) : null}
+ </>
)
}
diff --git a/web-studio/types/ov-server/api/v1/console.ts b/web-studio/types/ov-server/api/v1/console.ts
index f22418eb2..6d627be4a 100644
--- a/web-studio/types/ov-server/api/v1/console.ts
+++ b/web-studio/types/ov-server/api/v1/console.ts
@@ -77,6 +77,9 @@ export type ConsoleAuditLogItem = {
api_type?: string
created_at?: string
duration_ms?: number
+ error_code?: string | null
+ error_details?: Record<string, unknown> | null
+ error_message?: string | null
method?: string
request_id?: string | null
route?: string