Skip to content

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

feat(metric): add token-full-cycle metric (#1488)

baojun-zhang629fc241e46a
diff --git a/docs/design/metric-design.md b/docs/design/metric-design.md
index 8cacfeaec..618a2b260 100644
--- a/docs/design/metric-design.md
+++ b/docs/design/metric-design.md
@@ -775,7 +775,7 @@ sequenceDiagram
| --- | --- |
| `summary.operation` + `summary.status` | `openviking_operation_requests_total` |
| `summary.duration_ms` | `openviking_operation_duration_seconds` |
-| `summary.tokens.total` | `openviking_operation_tokens_total{token_type="all"}` |
+| `summary.tokens.total` | 不直接落单独指标;通过对 `openviking_operation_tokens_total` 的原子分量在查询层聚合得到 |
| `summary.tokens.llm.input` | `openviking_operation_tokens_total{token_type="llm_input"}` |
| `summary.tokens.llm.output` | `openviking_operation_tokens_total{token_type="llm_output"}` |
| `summary.tokens.embedding.total` | `openviking_operation_tokens_total{token_type="embedding"}` |
@@ -809,7 +809,7 @@ Openviking 指标体系采用如下兼容性策略:
- 保持现有 retrieval / embedding / vlm / cache 指标名尽量不变;
- `/metrics` 路由地址保持不变;
-- `telemetry.prometheus.enabled` 配置保持不变;
+- `server.observability.metrics.enabled` 配置保持不变;
- `/api/v1/observer/*` 与 `/api/v1/stats/*` 行为保持不变。
## 6. 风险与缓解
diff --git a/docs/en/concepts/12-metrics.md b/docs/en/concepts/12-metrics.md
index e01fd21fd..e4bf34275 100644
--- a/docs/en/concepts/12-metrics.md
+++ b/docs/en/concepts/12-metrics.md
@@ -124,13 +124,16 @@ scrape_configs:
| `context_type` | retrieval context type | `resource` |
| `provider` | model or external service provider | `volcengine` |
| `model_name` | model name | `doubao-seed-1-8-251228` |
-| `stage` | resource processing stage | `parse`, `persist`, `process` |
+| `stage` | stage label (defined by each metric family) | resource stage: `parse`; token attribution stage: `embed_query` |
| `valid` | whether the current sample is fresh and valid | `1` / `0` |
Notes:
- `account_id` is only enabled on controlled allowlisted metric families to prevent high-cardinality growth
- `valid=0` means the current state/probe sample is a fallback or stale value, not that the label itself is malformed
+- `stage` semantics depend on the metric family:
+ - `openviking_resource_stage_*`: resource ingestion pipeline stages (for example `parse/persist/process`)
+ - `openviking_operation_tokens_total`: token attribution stages (for example `embed_query/rerank/vlm`)
## Key Metric Families
@@ -158,8 +161,12 @@ Typical usage:
| `openviking_retrieval_requests_total` | Counter | `account_id, context_type` | retrieval request count |
| `openviking_retrieval_results_total` | Counter | `account_id, context_type` | total retrieved results |
| `openviking_retrieval_latency_seconds` | Histogram | `account_id, context_type` | retrieval latency distribution |
+| `openviking_retrieval_zero_result_total` | Counter | `account_id, context_type` | retrieval zero-result count |
+| `openviking_retrieval_rerank_used_total` | Counter | `account_id` | number of retrievals that used rerank |
+| `openviking_retrieval_rerank_fallback_total` | Counter | `account_id` | retrieval rerank fallback count |
| `openviking_resource_stage_total` | Counter | `account_id, stage, status` | count of resource ingestion stages |
| `openviking_resource_stage_duration_seconds` | Histogram | `account_id, stage, status` | duration distribution of ingestion stages |
+| `openviking_resource_wait_duration_seconds` | Histogram | `account_id, operation` | resource ingestion wait duration distribution (for example queue waiting) |
Typical `stage` values include:
@@ -170,6 +177,18 @@ Typical `stage` values include:
- `finalize`
- `process`
+### Vector, Memory, and Semantic Metrics
+
+| Metric Family | Type | Common Labels | Meaning |
+|---------------|------|---------------|---------|
+| `openviking_vector_searches_total` | Counter | `operation` | vector search count |
+| `openviking_vector_scored_total` | Counter | `operation` | total scored candidates |
+| `openviking_vector_passed_total` | Counter | `operation` | total passed candidates |
+| `openviking_vector_returned_total` | Counter | `operation` | total returned candidates |
+| `openviking_vector_scanned_total` | Counter | `operation` | total scanned candidates |
+| `openviking_memory_extracted_total` | Counter | `operation` | total extracted memory items |
+| `openviking_semantic_nodes_total` | Counter | `status` | total semantic nodes |
+
### Model Calls and Tokens
| Metric Family | Type | Common Labels | Meaning |
@@ -183,6 +202,18 @@ Typical `stage` values include:
| `openviking_vlm_call_duration_seconds` | Histogram | `account_id, provider, model_name` | VLM call duration distribution |
| `openviking_embedding_requests_total` | Counter | `account_id, status` | embedding request count |
| `openviking_embedding_latency_seconds` | Histogram | `account_id, status` | embedding latency distribution |
+| `openviking_embedding_errors_total` | Counter | `account_id, error_code` | embedding error count |
+| `openviking_embedding_calls_total` | Counter | `account_id, provider, model_name` | embedding provider call count (per-call) |
+| `openviking_embedding_call_duration_seconds` | Histogram | `account_id, provider, model_name` | embedding provider call duration distribution (per-call) |
+| `openviking_embedding_tokens_input_total` | Counter | `account_id, provider, model_name` | embedding input tokens (per-call aggregate) |
+| `openviking_embedding_tokens_output_total` | Counter | `account_id, provider, model_name` | embedding output tokens (per-call aggregate; may not appear if always 0) |
+| `openviking_embedding_tokens_total` | Counter | `account_id, provider, model_name` | embedding total tokens (per-call aggregate) |
+| `openviking_rerank_calls_total` | Counter | `account_id, provider, model_name` | rerank provider call count (per-call) |
+| `openviking_rerank_call_duration_seconds` | Histogram | `account_id, provider, model_name` | rerank provider call duration distribution (per-call) |
+| `openviking_rerank_tokens_input_total` | Counter | `account_id, provider, model_name` | rerank input tokens (per-call aggregate) |
+| `openviking_rerank_tokens_output_total` | Counter | `account_id, provider, model_name` | rerank output tokens (per-call aggregate; may not appear if always 0) |
+| `openviking_rerank_tokens_total` | Counter | `account_id, provider, model_name` | rerank total tokens (per-call aggregate) |
+| `openviking_operation_tokens_total` | Counter | `account_id, operation, stage, token_type` | operation token aggregation (token attribution stages) |
Notes:
@@ -194,6 +225,7 @@ Notes:
| Metric Family | Type | Common Labels | Meaning |
|---------------|------|---------------|---------|
| `openviking_queue_processed_total` | Counter | `queue` | total processed items per queue |
+| `openviking_queue_errors_total` | Counter | `queue` | total error count per queue |
| `openviking_queue_pending` | Gauge | `queue` | pending queue items |
| `openviking_queue_in_progress` | Gauge | `queue` | in-progress queue items |
| `openviking_lock_active` | Gauge | none | current active locks |
@@ -205,6 +237,30 @@ These help answer:
- Is there queue backlog?
- Is there lock contention or stale locking?
+### Tasks and Task Tracker
+
+| Metric Family | Type | Common Labels | Meaning |
+|---------------|------|---------------|---------|
+| `openviking_task_pending` | Gauge | `task_type` | pending tasks tracked by task tracker |
+| `openviking_task_running` | Gauge | `task_type` | running tasks tracked by task tracker |
+| `openviking_task_completed` | Gauge | `task_type` | completed tasks tracked by task tracker |
+| `openviking_task_failed` | Gauge | `task_type` | failed tasks tracked by task tracker |
+
+### Cache
+
+| Metric Family | Type | Common Labels | Meaning |
+|---------------|------|---------------|---------|
+| `openviking_cache_hits_total` | Counter | `level` | cache hit count |
+| `openviking_cache_misses_total` | Counter | `level` | cache miss count |
+
+### Session
+
+| Metric Family | Type | Common Labels | Meaning |
+|---------------|------|---------------|---------|
+| `openviking_session_lifecycle_total` | Counter | `account_id, action, status` | session lifecycle event count |
+| `openviking_session_contexts_used_total` | Counter | `account_id, action` | session contexts used total |
+| `openviking_session_archive_total` | Counter | `account_id, status` | session archive count |
+
### Probes and Health State
| Metric Family | Type | Common Labels | Meaning |
@@ -224,6 +280,22 @@ Meaning of `valid`:
- `valid="1"`: the sample was produced by a successful refresh
- `valid="0"`: the sample is a fallback or stale value and should be treated with caution
+### Encryption (Operational Metrics)
+
+| Metric Family | Type | Common Labels | Meaning |
+|---------------|------|---------------|---------|
+| `openviking_encryption_operations_total` | Counter | `account_id, operation, status` | encrypt/decrypt operation count |
+| `openviking_encryption_duration_seconds` | Histogram | `account_id, operation, status` | encrypt/decrypt duration distribution |
+| `openviking_encryption_bytes_total` | Counter | `account_id, operation` | encrypt/decrypt processed bytes total |
+| `openviking_encryption_payload_size_bytes` | Histogram | `account_id, operation` | encrypt/decrypt payload size distribution |
+| `openviking_encryption_auth_failed_total` | Counter | `account_id, status` | auth-failed count |
+| `openviking_encryption_key_derivation_total` | Counter | `account_id, status` | key derivation count |
+| `openviking_encryption_key_derivation_duration_seconds` | Histogram | `account_id, status` | key derivation duration distribution |
+| `openviking_encryption_key_load_duration_seconds` | Histogram | `account_id, status, provider` | key load duration distribution |
+| `openviking_encryption_key_cache_hits_total` | Counter | `account_id, provider` | key cache hit count |
+| `openviking_encryption_key_cache_misses_total` | Counter | `account_id, provider` | key cache miss count |
+| `openviking_encryption_key_version_usage_total` | Counter | `account_id, key_version` | key version usage count |
+
### Component and Observer Aggregate Metrics
| Metric Family | Type | Common Labels | Meaning |
@@ -260,30 +332,28 @@ Possible `model_type` values include:
### Enabling Metrics
-In `ov.conf`, the new metrics subsystem can be explicitly enabled through `server.metrics`:
+In `ov.conf`, the metrics subsystem can be explicitly enabled through `server.observability.metrics`:
```json
{
"server": {
- "telemetry": {
- "prometheus": {
- "enabled": true
- }
- },
- "metrics": {
- "enabled": true,
- "account_dimension": {
+ "observability": {
+ "metrics": {
"enabled": true,
- "max_active_accounts": 100,
- "metric_allowlist": [
- "openviking_http_requests_total",
- "openviking_http_request_duration_seconds",
- "openviking_http_inflight_requests",
- "openviking_operation_requests_total",
- "openviking_operation_duration_seconds",
- "openviking_vlm_calls_total",
- "openviking_vlm_call_duration_seconds"
- ]
+ "account_dimension": {
+ "enabled": true,
+ "max_active_accounts": 100,
+ "metric_allowlist": [
+ "openviking_http_requests_total",
+ "openviking_http_request_duration_seconds",
+ "openviking_http_inflight_requests",
+ "openviking_operation_requests_total",
+ "openviking_operation_duration_seconds",
+ "openviking_vlm_calls_total",
+ "openviking_vlm_call_duration_seconds",
+ "openviking_rerank_*"
+ ]
+ }
}
}
}
@@ -292,16 +362,15 @@ In `ov.conf`, the new metrics subsystem can be explicitly enabled through `serve
Recommended mental model:
-- `server.metrics.enabled`: master switch for the new metrics subsystem
-- `server.metrics.account_dimension`: controls whether `account_id` labels are enabled and where they are allowed
-- `server.telemetry.prometheus.enabled`: compatibility path for the older configuration entry; the current implementation still reads it
+- `server.observability.metrics.enabled`: master switch for the metrics subsystem
+- `server.observability.metrics.account_dimension`: controls whether `account_id` labels are enabled and where they are allowed
### Recommended `account_id` Usage
- enabled by default, but only allowlisted metric families will receive tenant ids (empty allowlist still yields `__unknown__`)
- do not turn `user_id`, `session_id`, or `resource_uri` into labels
- only enable tenant dimensions on a small set of critical dashboard and alert metrics
-- `metric_allowlist` supports a limited wildcard syntax: only trailing `*` prefix matches (e.g. `openviking_rerank_*`)
+- `metric_allowlist` supports a limited wildcard syntax: only trailing `*` prefix matches (e.g. `openviking_rerank_*`, `openviking_embedding_*`)
- a standalone `*` is not supported, nor full glob/regex patterns
## Related Documentation
diff --git a/docs/en/guides/05-observability.md b/docs/en/guides/05-observability.md
index 581c8b919..e9f68587e 100644
--- a/docs/en/guides/05-observability.md
+++ b/docs/en/guides/05-observability.md
@@ -246,6 +246,34 @@ Compared with `observer/*`, `/metrics` is better for **trends, aggregation, and
Compared with `telemetry`, `/metrics` focuses on **aggregated time series**, while `telemetry` focuses on **what happened inside one specific request**.
+### Enable metrics quickly
+
+`/metrics` may be disabled by default. When the metrics subsystem is not enabled, the endpoint returns `404` with the message `Prometheus metrics are disabled.`.
+
+You do not need the full configuration to get started. Enabling the master switch under the `server` section is enough.
+
+**Minimal config (recommended)**
+
+Add the following to `~/.openviking/ov.conf` (or the path passed via `--config`):
+
+```json
+{
+ "server": {
+ "observability": {
+ "metrics": {
+ "enabled": true
+ }
+ }
+ }
+}
+```
+
+Restart OpenViking Server after editing the config.
+
+For full fields, supported ranges, and more examples, see:
+
+- [Metrics](../concepts/12-metrics.md)
+
### Access `/metrics` directly
In the current implementation, `/metrics` is not wired to `get_request_context` or other auth dependencies, so from the code-path perspective it currently behaves as a public scrape endpoint:
@@ -284,9 +312,10 @@ If there is no data yet, go back to the Prometheus scrape configuration above an
**Step 2: Import the official demo dashboard into Grafana**
-The OpenViking repository already includes a ready-to-import dashboard JSON:
+The OpenViking repository already includes ready-to-import dashboard JSON:
- [openviking_demo_dashboard.json](../../../examples/grafana/openviking_demo_dashboard.json)
+- [openviking_token_demo_dashboard.json](../../../examples/grafana/openviking_token_demo_dashboard.json) (Note: this dashboard depends on the `tim012432-calendarheatmap-panel` Grafana plugin. Install it before importing to ensure panels render correctly.)
You can import it with the following steps:
diff --git a/docs/zh/concepts/12-metrics.md b/docs/zh/concepts/12-metrics.md
index b34308105..a4f1668f8 100644
--- a/docs/zh/concepts/12-metrics.md
+++ b/docs/zh/concepts/12-metrics.md
@@ -124,13 +124,16 @@ scrape_configs:
| `context_type` | 检索上下文类型 | `resource` |
| `provider` | 模型或外部服务提供方 | `volcengine` |
| `model_name` | 模型名称 | `doubao-seed-1-8-251228` |
-| `stage` | 资源处理阶段 | `parse`、`persist`、`process` |
+| `stage` | 阶段标签(按指标族定义) | 资源阶段:`parse`;Token 归因阶段:`embed_query` |
| `valid` | 当前样本是否为有效新鲜值 | `1` / `0` |
其中:
- `account_id` 只在受控白名单指标上启用,避免高基数失控
- `valid=0` 表示该状态/探针的当前样本是失败回退值或 stale fallback,不代表标签本身错误
+- `stage` 的语义依赖指标族:
+ - `openviking_resource_stage_*`:资源导入流水线阶段(如 `parse/persist/process`)
+ - `openviking_operation_tokens_total`:Token Attribution 的归因阶段(如 `embed_query/rerank/vlm`)
## 关键指标说明
@@ -158,8 +161,12 @@ scrape_configs:
| `openviking_retrieval_requests_total` | Counter | `account_id, context_type` | 检索请求次数 |
| `openviking_retrieval_results_total` | Counter | `account_id, context_type` | 检索返回结果数量累计 |
| `openviking_retrieval_latency_seconds` | Histogram | `account_id, context_type` | 检索耗时分布 |
+| `openviking_retrieval_zero_result_total` | Counter | `account_id, context_type` | 检索零结果次数 |
+| `openviking_retrieval_rerank_used_total` | Counter | `account_id` | 检索中使用 rerank 的次数 |
+| `openviking_retrieval_rerank_fallback_total` | Counter | `account_id` | 检索 rerank 回退次数 |
| `openviking_resource_stage_total` | Counter | `account_id, stage, status` | 资源导入各阶段执行次数 |
| `openviking_resource_stage_duration_seconds` | Histogram | `account_id, stage, status` | 资源导入阶段耗时分布 |
+| `openviking_resource_wait_duration_seconds` | Histogram | `account_id, operation` | 资源导入等待耗时分布(例如队列等待) |
典型 `stage` 包括:
@@ -170,6 +177,18 @@ scrape_configs:
- `finalize`
- `process`
+### 向量检索、记忆与语义节点
+
+| 指标族 | 类型 | 常见标签 | 含义 |
+|--------|------|----------|------|
+| `openviking_vector_searches_total` | Counter | `operation` | 向量检索次数 |
+| `openviking_vector_scored_total` | Counter | `operation` | 向量候选打分数量累计 |
+| `openviking_vector_passed_total` | Counter | `operation` | 向量候选通过数量累计 |
+| `openviking_vector_returned_total` | Counter | `operation` | 向量候选返回数量累计 |
+| `openviking_vector_scanned_total` | Counter | `operation` | 向量候选扫描数量累计 |
+| `openviking_memory_extracted_total` | Counter | `operation` | memory extracted 数量累计 |
+| `openviking_semantic_nodes_total` | Counter | `status` | semantic nodes 数量累计 |
+
### 模型调用与 Token
| 指标族 | 类型 | 常见标签 | 含义 |
@@ -183,17 +202,33 @@ scrape_configs:
| `openviking_vlm_call_duration_seconds` | Histogram | `account_id, provider, model_name` | VLM 调用耗时分布 |
| `openviking_embedding_requests_total` | Counter | `account_id, status` | embedding 请求数 |
| `openviking_embedding_latency_seconds` | Histogram | `account_id, status` | embedding 耗时分布 |
+| `openviking_embedding_errors_total` | Counter | `account_id, error_code` | embedding 错误次数 |
+| `openviking_embedding_calls_total` | Counter | `account_id, provider, model_name` | embedding provider 调用次数(per-call) |
+| `openviking_embedding_call_duration_seconds` | Histogram | `account_id, provider, model_name` | embedding provider 调用耗时分布(per-call) |
+| `openviking_embedding_tokens_input_total` | Counter | `account_id, provider, model_name` | embedding 输入 token(per-call 聚合) |
+| `openviking_embedding_tokens_output_total` | Counter | `account_id, provider, model_name` | embedding 输出 token(per-call 聚合;若长期为 0 可能不出现) |
+| `openviking_embedding_tokens_total` | Counter | `account_id, provider, model_name` | embedding 总 token(per-call 聚合) |
+| `openviking_rerank_calls_total` | Counter | `account_id, provider, model_name` | rerank provider 调用次数(per-call) |
+| `openviking_rerank_call_duration_seconds` | Histogram | `account_id, provider, model_name` | rerank provider 调用耗时分布(per-call) |
+| `openviking_rerank_tokens_input_total` | Counter | `account_id, provider, model_name` | rerank 输入 token(per-call 聚合) |
+| `openviking_rerank_tokens_output_total` | Counter | `account_id, provider, model_name` | rerank 输出 token(per-call 聚合;若长期为 0 可能不出现) |
+| `openviking_rerank_tokens_total` | Counter | `account_id, provider, model_name` | rerank 总 token(per-call 聚合) |
+| `openviking_operation_tokens_total` | Counter | `account_id, operation, stage, token_type` | Operation Token 汇总(含 token attribution 归因阶段) |
说明:
- `openviking_model_*` 是统一模型视角,便于同时看 embedding / vlm
- `openviking_vlm_*` 和 `openviking_embedding_*` 更适合业务侧针对性看板
+ - `*_requests_*` 更偏“业务请求视角”
+ - `*_calls_* / *_call_duration_* / *_tokens_*` 更偏“模型调用视角”(按 `provider/model_name` 聚合)
+ - `openviking_operation_tokens_total` 不存 `token_type="all/total"` 这类预聚合标签,总账建议在 TSDB 查询侧用 `sum(...)` 聚合得到
### 队列、锁与系统运行态
| 指标族 | 类型 | 常见标签 | 含义 |
|--------|------|----------|------|
| `openviking_queue_processed_total` | Counter | `queue` | 队列累计处理量 |
+| `openviking_queue_errors_total` | Counter | `queue` | 队列累计错误量 |
| `openviking_queue_pending` | Gauge | `queue` | 队列待处理数 |
| `openviking_queue_in_progress` | Gauge | `queue` | 队列执行中数量 |
| `openviking_lock_active` | Gauge | 无 | 当前活跃锁数量 |
@@ -205,6 +240,30 @@ scrape_configs:
- 是否有队列堆积?
- 是否有锁竞争或 stale lock?
+### 任务与 Task Tracker
+
+| 指标族 | 类型 | 常见标签 | 含义 |
+|--------|------|----------|------|
+| `openviking_task_pending` | Gauge | `task_type` | task tracker 待执行任务数 |
+| `openviking_task_running` | Gauge | `task_type` | task tracker 执行中任务数 |
+| `openviking_task_completed` | Gauge | `task_type` | task tracker 已完成任务数 |
+| `openviking_task_failed` | Gauge | `task_type` | task tracker 失败任务数 |
+
+### Cache
+
+| 指标族 | 类型 | 常见标签 | 含义 |
+|--------|------|----------|------|
+| `openviking_cache_hits_total` | Counter | `level` | Cache 命中次数 |
+| `openviking_cache_misses_total` | Counter | `level` | Cache 未命中次数 |
+
+### Session
+
+| 指标族 | 类型 | 常见标签 | 含义 |
+|--------|------|----------|------|
+| `openviking_session_lifecycle_total` | Counter | `account_id, action, status` | session 生命周期事件次数 |
+| `openviking_session_contexts_used_total` | Counter | `account_id, action` | session contexts used 累计量 |
+| `openviking_session_archive_total` | Counter | `account_id, status` | session archive 次数 |
+
### 探针与健康状态
| 指标族 | 类型 | 常见标签 | 含义 |
@@ -224,6 +283,22 @@ scrape_configs:
- `valid="1"`:当前样本是本次成功刷新得到的结果
- `valid="0"`:当前样本是失败回退值或 stale fallback,说明该探针/状态当前不可完全信任
+### 加密(运行指标)
+
+| 指标族 | 类型 | 常见标签 | 含义 |
+|--------|------|----------|------|
+| `openviking_encryption_operations_total` | Counter | `account_id, operation, status` | encrypt/decrypt 操作次数 |
+| `openviking_encryption_duration_seconds` | Histogram | `account_id, operation, status` | encrypt/decrypt 耗时分布 |
+| `openviking_encryption_bytes_total` | Counter | `account_id, operation` | encrypt/decrypt 处理字节数累计 |
+| `openviking_encryption_payload_size_bytes` | Histogram | `account_id, operation` | encrypt/decrypt payload size 分布 |
+| `openviking_encryption_auth_failed_total` | Counter | `account_id, status` | auth failed 次数 |
+| `openviking_encryption_key_derivation_total` | Counter | `account_id, status` | key derivation 次数 |
+| `openviking_encryption_key_derivation_duration_seconds` | Histogram | `account_id, status` | key derivation 耗时分布 |
+| `openviking_encryption_key_load_duration_seconds` | Histogram | `account_id, status, provider` | key load 耗时分布 |
+| `openviking_encryption_key_cache_hits_total` | Counter | `account_id, provider` | key cache hits 次数 |
+| `openviking_encryption_key_cache_misses_total` | Counter | `account_id, provider` | key cache misses 次数 |
+| `openviking_encryption_key_version_usage_total` | Counter | `account_id, key_version` | key version 使用次数 |
+
### 组件与 Observer 聚合指标
| 指标族 | 类型 | 常见标签 | 含义 |
@@ -260,30 +335,28 @@ scrape_configs:
### 启用 Metrics
-在 `ov.conf` 中,可以通过 `server.metrics` 显式启用新的 metrics 子系统:
+在 `ov.conf` 中,可以通过 `server.observability.metrics` 显式启用 metrics 子系统:
```json
{
"server": {
- "telemetry": {
- "prometheus": {
- "enabled": true
- }
- },
- "metrics": {
- "enabled": true,
- "account_dimension": {
+ "observability": {
+ "metrics": {
"enabled": true,
- "max_active_accounts": 100,
- "metric_allowlist": [
- "openviking_http_requests_total",
- "openviking_http_request_duration_seconds",
- "openviking_http_inflight_requests",
- "openviking_operation_requests_total",
- "openviking_operation_duration_seconds",
- "openviking_vlm_calls_total",
- "openviking_vlm_call_duration_seconds"
- ]
+ "account_dimension": {
+ "enabled": true,
+ "max_active_accounts": 100,
+ "metric_allowlist": [
+ "openviking_http_requests_total",
+ "openviking_http_request_duration_seconds",
+ "openviking_http_inflight_requests",
+ "openviking_operation_requests_total",
+ "openviking_operation_duration_seconds",
+ "openviking_vlm_calls_total",
+ "openviking_vlm_call_duration_seconds",
+ "openviking_rerank_*"
+ ]
+ }
}
}
}
@@ -292,9 +365,8 @@ scrape_configs:
推荐理解方式:
-- `server.metrics.enabled`:新指标体系总开关
-- `server.metrics.account_dimension`:控制 `account_id` 标签是否启用以及启用范围
-- `server.telemetry.prometheus.enabled`:兼容旧配置入口,当前实现仍兼容读取
+- `server.observability.metrics.enabled`:指标体系总开关
+- `server.observability.metrics.account_dimension`:控制 `account_id` 标签是否启用以及启用范围
### `account_id` 标签的使用建议
diff --git a/docs/zh/guides/05-observability.md b/docs/zh/guides/05-observability.md
index 266d790af..3ec1b1796 100644
--- a/docs/zh/guides/05-observability.md
+++ b/docs/zh/guides/05-observability.md
@@ -246,6 +246,33 @@ curl -X POST http://localhost:1933/api/v1/search/find \
和前面的 `telemetry` 相比,`/metrics` 关注的是**聚合后的时间序列**;`telemetry` 关注的是**某一次请求内部到底发生了什么**。
+### 快速开启 metrics
+
+`/metrics` 默认是关闭的:当指标体系未启用时,访问会返回 `404`,并提示 `Prometheus metrics are disabled.`。
+
+开启方式不需要完整配置,只需要在 `ov.conf` 的 `server` 段打开总开关即可。
+
+**最小配置(推荐)**
+
+在 `~/.openviking/ov.conf`(或你启动时通过 `--config` 指定的路径)里加入:
+
+```json
+{
+ "server": {
+ "observability": {
+ "metrics": {
+ "enabled": true
+ }
+ }
+ }
+}
+```
+改完配置后需要**重启 OpenViking Server** 才会生效。
+
+完整字段、支持范围和更多示例见:
+
+- [指标](../concepts/12-metrics.md)
+
### 直接访问 `/metrics`
当前实现中,`/metrics` 未接入 `get_request_context` 等鉴权依赖,因此从代码行为上看,它当前等价于公开抓取端点:
@@ -284,9 +311,10 @@ scrape_configs:
**第 2 步:在 Grafana 导入官方 demo dashboard**
-OpenViking 仓库里已经提供了一个可直接导入的 dashboard JSON:
+OpenViking 仓库里已经提供了可直接导入的 dashboard JSON:
- [openviking_demo_dashboard.json](../../../examples/grafana/openviking_demo_dashboard.json)
+- [openviking_token_demo_dashboard.json](../../../examples/grafana/openviking_token_demo_dashboard.json) (注意,该 dashboard 依赖 `tim012432-calendarheatmap-panel` grafana 插件,需要先安装才能正常工作)
导入步骤可以按下面做:
diff --git a/examples/grafana/openviking_token_demo_dashboard.json b/examples/grafana/openviking_token_demo_dashboard.json
new file mode 100644
index 000000000..30c2cff1f
--- /dev/null
+++ b/examples/grafana/openviking_token_demo_dashboard.json
@@ -0,0 +1,1732 @@
+{
+ "annotations": {
+ "list": [
+ {
+ "builtIn": 1,
+ "datasource": {
+ "type": "grafana",
+ "uid": "-- Grafana --"
+ },
+ "enable": true,
+ "hide": true,
+ "iconColor": "#00FFE5",
+ "name": "Annotations & Alerts",
+ "type": "dashboard"
+ }
+ ]
+ },
+ "editable": true,
+ "fiscalYearStartMonth": 0,
+ "graphTooltip": 2,
+ "links": [],
+ "panels": [
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 0
+ },
+ "id": 1,
+ "panels": [],
+ "title": "Token Cockpit",
+ "type": "row"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "thresholds"
+ },
+ "mappings": [],
+ "min": 0,
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "#9FB0E2",
+ "value": null
+ },
+ {
+ "color": "#00FFE5",
+ "value": 1
+ }
+ ]
+ },
+ "unit": "tps"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 5,
+ "w": 4,
+ "x": 0,
+ "y": 1
+ },
+ "id": 2,
+ "options": {
+ "colorMode": "value",
+ "graphMode": "area",
+ "justifyMode": "center",
+ "orientation": "auto",
+ "percentChangeColorMode": "standard",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ },
+ "showPercentChange": false,
+ "text": {
+ "titleSize": 12,
+ "valueSize": 26
+ },
+ "textMode": "value_and_name",
+ "wideLayout": false
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "sum(rate(openviking_operation_tokens_total{account_id=~\"$account_id\",operation=~\"$operation\"}[5m]))",
+ "legendFormat": "All tokens/sec",
+ "range": true,
+ "refId": "A"
+ }
+ ],
+ "title": "All Tokens/s",
+ "type": "stat"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "thresholds"
+ },
+ "mappings": [],
+ "min": 0,
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "#9FB0E2",
+ "value": null
+ },
+ {
+ "color": "#6EE7FF",
+ "value": 1
+ }
+ ]
+ },
+ "unit": "tps"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 5,
+ "w": 4,
+ "x": 4,
+ "y": 1
+ },
+ "id": 3,
+ "options": {
+ "colorMode": "value",
+ "graphMode": "area",
+ "justifyMode": "center",
+ "orientation": "auto",
+ "percentChangeColorMode": "standard",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ },
+ "showPercentChange": false,
+ "text": {
+ "titleSize": 12,
+ "valueSize": 26
+ },
+ "textMode": "value_and_name",
+ "wideLayout": false
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "sum(rate(openviking_vlm_tokens_input_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[5m]))",
+ "legendFormat": "VLM input/s",
+ "range": true,
+ "refId": "A"
+ }
+ ],
+ "title": "VLM Input Tokens/s",
+ "type": "stat"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "thresholds"
+ },
+ "mappings": [],
+ "min": 0,
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "#9FB0E2",
+ "value": null
+ },
+ {
+ "color": "#FFD60A",
+ "value": 1
+ }
+ ]
+ },
+ "unit": "tps"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 5,
+ "w": 4,
+ "x": 8,
+ "y": 1
+ },
+ "id": 4,
+ "options": {
+ "colorMode": "value",
+ "graphMode": "area",
+ "justifyMode": "center",
+ "orientation": "auto",
+ "percentChangeColorMode": "standard",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ },
+ "showPercentChange": false,
+ "text": {
+ "titleSize": 12,
+ "valueSize": 26
+ },
+ "textMode": "value_and_name",
+ "wideLayout": false
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "sum(rate(openviking_vlm_tokens_output_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[5m]))",
+ "legendFormat": "VLM output/s",
+ "range": true,
+ "refId": "A"
+ }
+ ],
+ "title": "VLM Output Tokens/s",
+ "type": "stat"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "thresholds"
+ },
+ "mappings": [],
+ "min": 0,
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "#9FB0E2",
+ "value": null
+ },
+ {
+ "color": "#2CE26A",
+ "value": 1
+ }
+ ]
+ },
+ "unit": "tps"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 5,
+ "w": 4,
+ "x": 12,
+ "y": 1
+ },
+ "id": 5,
+ "options": {
+ "colorMode": "value",
+ "graphMode": "area",
+ "justifyMode": "center",
+ "orientation": "auto",
+ "percentChangeColorMode": "standard",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ },
+ "showPercentChange": false,
+ "text": {
+ "titleSize": 12,
+ "valueSize": 26
+ },
+ "textMode": "value_and_name",
+ "wideLayout": false
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "sum(rate(openviking_embedding_tokens_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[5m]))",
+ "legendFormat": "Embedding tokens/s",
+ "range": true,
+ "refId": "A"
+ }
+ ],
+ "title": "Embedding Tokens/s",
+ "type": "stat"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "thresholds"
+ },
+ "mappings": [],
+ "min": 0,
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "#9FB0E2",
+ "value": null
+ },
+ {
+ "color": "#A78BFA",
+ "value": 1
+ }
+ ]
+ },
+ "unit": "tps"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 5,
+ "w": 4,
+ "x": 16,
+ "y": 1
+ },
+ "id": 6,
+ "options": {
+ "colorMode": "value",
+ "graphMode": "area",
+ "justifyMode": "center",
+ "orientation": "auto",
+ "percentChangeColorMode": "standard",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ },
+ "showPercentChange": false,
+ "text": {
+ "titleSize": 12,
+ "valueSize": 26
+ },
+ "textMode": "value_and_name",
+ "wideLayout": false
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "sum(rate(openviking_rerank_tokens_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[5m]))",
+ "legendFormat": "Rerank tokens/s",
+ "range": true,
+ "refId": "A"
+ }
+ ],
+ "title": "Rerank Tokens/s",
+ "type": "stat"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "thresholds"
+ },
+ "mappings": [],
+ "min": 0,
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "#9FB0E2",
+ "value": null
+ },
+ {
+ "color": "#00FFE5",
+ "value": 1
+ }
+ ]
+ },
+ "unit": "short"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 5,
+ "w": 4,
+ "x": 20,
+ "y": 1
+ },
+ "id": 7,
+ "options": {
+ "colorMode": "value",
+ "graphMode": "area",
+ "justifyMode": "center",
+ "orientation": "auto",
+ "percentChangeColorMode": "standard",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ },
+ "showPercentChange": false,
+ "text": {
+ "titleSize": 12,
+ "valueSize": 26
+ },
+ "textMode": "value_and_name",
+ "wideLayout": false
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "sum(rate(openviking_operation_tokens_total{account_id=~\"$account_id\",operation=~\"$operation\"}[5m])) / clamp_min(sum(rate(openviking_operation_requests_total{account_id=~\"$account_id\",operation=~\"$operation\"}[5m])), 1e-9)",
+ "legendFormat": "tokens/request",
+ "range": true,
+ "refId": "A"
+ }
+ ],
+ "title": "Tokens / Operation Req",
+ "type": "stat"
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 6
+ },
+ "id": 8,
+ "panels": [],
+ "title": "Token Totals (Selected Time Range)",
+ "type": "row"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "thresholds"
+ },
+ "mappings": [],
+ "min": 0,
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "#9FB0E2",
+ "value": null
+ },
+ {
+ "color": "#00FFE5",
+ "value": 1
+ }
+ ]
+ },
+ "unit": "short"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 5,
+ "w": 4,
+ "x": 0,
+ "y": 7
+ },
+ "id": 12,
+ "options": {
+ "colorMode": "value",
+ "graphMode": "area",
+ "justifyMode": "center",
+ "orientation": "auto",
+ "percentChangeColorMode": "standard",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ },
+ "showPercentChange": false,
+ "text": {
+ "titleSize": 12,
+ "valueSize": 26
+ },
+ "textMode": "value_and_name",
+ "wideLayout": false
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "((sum(increase(openviking_vlm_tokens_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[$__range])) or vector(0)) + (sum(increase(openviking_embedding_tokens_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[$__range])) or vector(0)) + (sum(increase(openviking_rerank_tokens_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[$__range])) or vector(0)))",
+ "legendFormat": "total tokens",
+ "range": true,
+ "refId": "A"
+ }
+ ],
+ "title": "Total Tokens (range)",
+ "type": "stat"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "thresholds"
+ },
+ "mappings": [],
+ "min": 0,
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "#9FB0E2",
+ "value": null
+ },
+ {
+ "color": "#6EE7FF",
+ "value": 1
+ }
+ ]
+ },
+ "unit": "short"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 5,
+ "w": 4,
+ "x": 4,
+ "y": 7
+ },
+ "id": 13,
+ "options": {
+ "colorMode": "value",
+ "graphMode": "area",
+ "justifyMode": "center",
+ "orientation": "auto",
+ "percentChangeColorMode": "standard",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ },
+ "showPercentChange": false,
+ "text": {
+ "titleSize": 12,
+ "valueSize": 26
+ },
+ "textMode": "value_and_name",
+ "wideLayout": false
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "(sum(increase(openviking_vlm_tokens_input_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[$__range])) or vector(0))",
+ "legendFormat": "vlm input",
+ "range": true,
+ "refId": "A"
+ }
+ ],
+ "title": "VLM Input (range)",
+ "type": "stat"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "thresholds"
+ },
+ "mappings": [],
+ "min": 0,
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "#9FB0E2",
+ "value": null
+ },
+ {
+ "color": "#FFD60A",
+ "value": 1
+ }
+ ]
+ },
+ "unit": "short"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 5,
+ "w": 4,
+ "x": 8,
+ "y": 7
+ },
+ "id": 14,
+ "options": {
+ "colorMode": "value",
+ "graphMode": "area",
+ "justifyMode": "center",
+ "orientation": "auto",
+ "percentChangeColorMode": "standard",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ },
+ "showPercentChange": false,
+ "text": {
+ "titleSize": 12,
+ "valueSize": 26
+ },
+ "textMode": "value_and_name",
+ "wideLayout": false
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "(sum(increase(openviking_vlm_tokens_output_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[$__range])) or vector(0))",
+ "legendFormat": "vlm output",
+ "range": true,
+ "refId": "A"
+ }
+ ],
+ "title": "VLM Output (range)",
+ "type": "stat"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "thresholds"
+ },
+ "mappings": [],
+ "min": 0,
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "#9FB0E2",
+ "value": null
+ },
+ {
+ "color": "#2CE26A",
+ "value": 1
+ }
+ ]
+ },
+ "unit": "short"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 5,
+ "w": 4,
+ "x": 12,
+ "y": 7
+ },
+ "id": 15,
+ "options": {
+ "colorMode": "value",
+ "graphMode": "area",
+ "justifyMode": "center",
+ "orientation": "auto",
+ "percentChangeColorMode": "standard",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ },
+ "showPercentChange": false,
+ "text": {
+ "titleSize": 12,
+ "valueSize": 26
+ },
+ "textMode": "value_and_name",
+ "wideLayout": false
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "(sum(increase(openviking_embedding_tokens_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[$__range])) or vector(0))",
+ "legendFormat": "embedding",
+ "range": true,
+ "refId": "A"
+ }
+ ],
+ "title": "Embedding (range)",
+ "type": "stat"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "thresholds"
+ },
+ "mappings": [],
+ "min": 0,
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "#9FB0E2",
+ "value": null
+ },
+ {
+ "color": "#A78BFA",
+ "value": 1
+ }
+ ]
+ },
+ "unit": "short"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 5,
+ "w": 4,
+ "x": 16,
+ "y": 7
+ },
+ "id": 16,
+ "options": {
+ "colorMode": "value",
+ "graphMode": "area",
+ "justifyMode": "center",
+ "orientation": "auto",
+ "percentChangeColorMode": "standard",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ },
+ "showPercentChange": false,
+ "text": {
+ "titleSize": 12,
+ "valueSize": 26
+ },
+ "textMode": "value_and_name",
+ "wideLayout": false
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "(sum(increase(openviking_rerank_tokens_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[$__range])) or vector(0))",
+ "legendFormat": "rerank",
+ "range": true,
+ "refId": "A"
+ }
+ ],
+ "title": "Rerank (range)",
+ "type": "stat"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "thresholds"
+ },
+ "mappings": [],
+ "min": 0,
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "#9FB0E2",
+ "value": null
+ },
+ {
+ "color": "#00FFE5",
+ "value": 1
+ }
+ ]
+ },
+ "unit": "short"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 5,
+ "w": 4,
+ "x": 20,
+ "y": 7
+ },
+ "id": 17,
+ "options": {
+ "colorMode": "value",
+ "graphMode": "area",
+ "justifyMode": "center",
+ "orientation": "auto",
+ "percentChangeColorMode": "standard",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ },
+ "showPercentChange": false,
+ "text": {
+ "titleSize": 12,
+ "valueSize": 26
+ },
+ "textMode": "value_and_name",
+ "wideLayout": false
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "(((sum(increase(openviking_vlm_tokens_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[$__range])) or vector(0)) + (sum(increase(openviking_embedding_tokens_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[$__range])) or vector(0)) + (sum(increase(openviking_rerank_tokens_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[$__range])) or vector(0))) * 86400) / $__range_s",
+ "legendFormat": "tokens/day",
+ "range": true,
+ "refId": "A"
+ }
+ ],
+ "title": "Avg Tokens / Day (range)",
+ "type": "stat"
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 12
+ },
+ "id": 10,
+ "panels": [],
+ "title": "Token Calendar (GitHub-style)",
+ "type": "row"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "description": "Annual GitHub-style token calendar rendered by tim012432-calendarheatmap-panel. Uses a log2-transformed daily token value so low-traffic days remain visible.",
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "thresholds"
+ },
+ "custom": {},
+ "mappings": [],
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "#2A2F3A",
+ "value": null
+ }
+ ]
+ },
+ "unit": "short"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 11,
+ "w": 24,
+ "x": 0,
+ "y": 13
+ },
+ "id": 1100,
+ "options": {
+ "aggregation": "last",
+ "autoRectSize": true,
+ "colorScheme": "green",
+ "customColor": "#22c55e",
+ "emptyColor": "#2A2F3A",
+ "monthLabelCustom": "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec",
+ "monthLabelMode": "default",
+ "radius": 2,
+ "rectSize": 11,
+ "showLegend": true,
+ "showMonthLabels": true,
+ "showTooltip": true,
+ "showWeekLabels": true,
+ "space": 3,
+ "weekLabelCustom": "Sun,Mon,Tue,Wed,Thu,Fri,Sat",
+ "weekLabelMode": "default",
+ "weekStart": "monday"
+ },
+ "pluginVersion": "1.1.0",
+ "targets": [
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "editorMode": "code",
+ "expr": "clamp_min(log2(sum by () (increase(openviking_operation_tokens_total{account_id=~\"$account_id\",operation=~\"$operation\"}[1d])) + 1), 0)",
+ "interval": "1d",
+ "legendFormat": "daily_log2_tokens",
+ "range": true,
+ "refId": "A"
+ }
+ ],
+ "title": "Annual Token Contribution Calendar",
+ "transparent": false,
+ "type": "tim012432-calendarheatmap-panel"
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 24
+ },
+ "id": 20,
+ "panels": [],
+ "title": "Full Cycle: per-call -> attribution -> ledger",
+ "type": "row"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "palette-classic"
+ },
+ "custom": {
+ "axisBorderShow": false,
+ "axisCenteredZero": false,
+ "axisColorMode": "text",
+ "axisLabel": "",
+ "axisPlacement": "auto",
+ "barAlignment": 0,
+ "drawStyle": "line",
+ "fillOpacity": 12,
+ "gradientMode": "none",
+ "hideFrom": {
+ "legend": false,
+ "tooltip": false,
+ "viz": false
+ },
+ "insertNulls": false,
+ "lineInterpolation": "linear",
+ "lineWidth": 2,
+ "pointSize": 4,
+ "scaleDistribution": {
+ "type": "linear"
+ },
+ "showPoints": "never",
+ "spanNulls": true,
+ "stacking": {
+ "group": "A",
+ "mode": "normal"
+ },
+ "thresholdsStyle": {
+ "mode": "off"
+ }
+ },
+ "mappings": [],
+ "unit": "tps"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 10,
+ "w": 24,
+ "x": 0,
+ "y": 25
+ },
+ "id": 21,
+ "options": {
+ "legend": {
+ "calcs": [],
+ "displayMode": "table",
+ "placement": "right",
+ "showLegend": true
+ },
+ "tooltip": {
+ "mode": "multi",
+ "sort": "desc"
+ }
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "sum by (provider, model_name) (rate(openviking_vlm_tokens_input_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[5m]))",
+ "legendFormat": "vlm input {{provider}}/{{model_name}}",
+ "range": true,
+ "refId": "A"
+ },
+ {
+ "editorMode": "code",
+ "expr": "sum by (provider, model_name) (rate(openviking_vlm_tokens_output_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[5m]))",
+ "legendFormat": "vlm output {{provider}}/{{model_name}}",
+ "range": true,
+ "refId": "B"
+ },
+ {
+ "editorMode": "code",
+ "expr": "sum by (provider, model_name) (rate(openviking_embedding_tokens_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[5m]))",
+ "legendFormat": "embedding {{provider}}/{{model_name}}",
+ "range": true,
+ "refId": "C"
+ },
+ {
+ "editorMode": "code",
+ "expr": "sum by (provider, model_name) (rate(openviking_rerank_tokens_total{account_id=~\"$account_id\",provider=~\"$provider\",model_name=~\"$model_name\"}[5m]))",
+ "legendFormat": "rerank {{provider}}/{{model_name}}",
+ "range": true,
+ "refId": "D"
+ }
+ ],
+ "title": "A) per-call Tokens/s (VLM / Embedding / Rerank)",
+ "type": "timeseries"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "palette-classic"
+ },
+ "custom": {
+ "axisBorderShow": false,
+ "axisCenteredZero": false,
+ "axisColorMode": "text",
+ "axisLabel": "",
+ "axisPlacement": "auto",
+ "barAlignment": 0,
+ "drawStyle": "bars",
+ "fillOpacity": 70,
+ "gradientMode": "none",
+ "hideFrom": {
+ "legend": false,
+ "tooltip": false,
+ "viz": false
+ },
+ "lineWidth": 0,
+ "pointSize": 2,
+ "scaleDistribution": {
+ "type": "linear"
+ },
+ "showPoints": "never",
+ "stacking": {
+ "group": "B",
+ "mode": "normal"
+ },
+ "thresholdsStyle": {
+ "mode": "off"
+ }
+ },
+ "mappings": [],
+ "unit": "tps"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 10,
+ "w": 12,
+ "x": 0,
+ "y": 35
+ },
+ "id": 22,
+ "options": {
+ "legend": {
+ "calcs": [],
+ "displayMode": "table",
+ "placement": "right",
+ "showLegend": true
+ },
+ "tooltip": {
+ "mode": "multi",
+ "sort": "desc"
+ }
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "sum by (stage) (rate(openviking_operation_tokens_total{account_id=~\"$account_id\",operation=~\"$operation\"}[5m]))",
+ "legendFormat": "{{stage}}",
+ "range": true,
+ "refId": "A"
+ }
+ ],
+ "title": "B) Operation Token Attribution by Stage (stacked)",
+ "type": "timeseries"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "palette-classic"
+ },
+ "custom": {
+ "axisBorderShow": false,
+ "axisCenteredZero": false,
+ "axisColorMode": "text",
+ "axisLabel": "",
+ "axisPlacement": "auto",
+ "barAlignment": 0,
+ "drawStyle": "bars",
+ "fillOpacity": 70,
+ "gradientMode": "none",
+ "hideFrom": {
+ "legend": false,
+ "tooltip": false,
+ "viz": false
+ },
+ "lineWidth": 0,
+ "pointSize": 2,
+ "scaleDistribution": {
+ "type": "linear"
+ },
+ "showPoints": "never",
+ "stacking": {
+ "group": "C",
+ "mode": "normal"
+ },
+ "thresholdsStyle": {
+ "mode": "off"
+ }
+ },
+ "mappings": [],
+ "unit": "tps"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 10,
+ "w": 12,
+ "x": 12,
+ "y": 35
+ },
+ "id": 23,
+ "options": {
+ "legend": {
+ "calcs": [],
+ "displayMode": "table",
+ "placement": "right",
+ "showLegend": true
+ },
+ "tooltip": {
+ "mode": "multi",
+ "sort": "desc"
+ }
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "sum by (stage, token_type) (rate(openviking_operation_tokens_total{account_id=~\"$account_id\",operation=~\"$operation\"}[5m]))",
+ "legendFormat": "{{stage}} / {{token_type}}",
+ "range": true,
+ "refId": "A"
+ }
+ ],
+ "title": "B2) Operation Token Attribution by Stage + Token Type",
+ "type": "timeseries"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "palette-classic"
+ },
+ "custom": {
+ "axisBorderShow": false,
+ "axisCenteredZero": false,
+ "axisColorMode": "text",
+ "axisLabel": "",
+ "axisPlacement": "auto",
+ "barAlignment": 0,
+ "drawStyle": "bars",
+ "fillOpacity": 70,
+ "gradientMode": "none",
+ "hideFrom": {
+ "legend": false,
+ "tooltip": false,
+ "viz": false
+ },
+ "lineWidth": 0,
+ "pointSize": 2,
+ "scaleDistribution": {
+ "type": "linear"
+ },
+ "showPoints": "never",
+ "stacking": {
+ "group": "D",
+ "mode": "normal"
+ },
+ "thresholdsStyle": {
+ "mode": "off"
+ }
+ },
+ "mappings": [],
+ "unit": "tps"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 10,
+ "w": 24,
+ "x": 0,
+ "y": 45
+ },
+ "id": 24,
+ "options": {
+ "legend": {
+ "calcs": [],
+ "displayMode": "table",
+ "placement": "right",
+ "showLegend": true
+ },
+ "tooltip": {
+ "mode": "multi",
+ "sort": "desc"
+ }
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "sum by (model_type, token_type) (rate(openviking_model_tokens_total[5m]))",
+ "legendFormat": "{{model_type}} / {{token_type}}",
+ "range": true,
+ "refId": "A"
+ }
+ ],
+ "title": "C) Unified Ledger: openviking_model_tokens_total (rate)",
+ "type": "timeseries"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "palette-classic"
+ },
+ "mappings": [],
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "#9FB0E2",
+ "value": null
+ },
+ {
+ "color": "#00FFE5",
+ "value": 1
+ }
+ ]
+ },
+ "unit": "tps"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 10,
+ "w": 10,
+ "x": 0,
+ "y": 55
+ },
+ "id": 25,
+ "options": {
+ "displayLabels": [
+ "name",
+ "percent"
+ ],
+ "legend": {
+ "displayMode": "table",
+ "placement": "right",
+ "showLegend": true,
+ "values": [
+ "percent",
+ "value"
+ ]
+ },
+ "pieType": "pie",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ },
+ "tooltip": {
+ "mode": "single"
+ }
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "topk(10, sum by (operation) (rate(openviking_operation_tokens_total{account_id=~\"$account_id\"}[5m])))",
+ "instant": true,
+ "legendFormat": "{{operation}}",
+ "range": false,
+ "refId": "A"
+ }
+ ],
+ "title": "Top Operations by Token Share (topk 10)",
+ "type": "piechart"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "palette-classic"
+ },
+ "custom": {
+ "axisBorderShow": false,
+ "axisCenteredZero": false,
+ "axisColorMode": "text",
+ "axisLabel": "tokens/s",
+ "axisPlacement": "bottom",
+ "barAlignment": 0,
+ "fillOpacity": 85,
+ "gradientMode": "none",
+ "lineWidth": 1,
+ "scaleDistribution": {
+ "type": "linear"
+ },
+ "showValue": "auto"
+ },
+ "mappings": [],
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "#9FB0E2",
+ "value": null
+ },
+ {
+ "color": "#00FFE5",
+ "value": 1
+ }
+ ]
+ },
+ "unit": "tps"
+ },
+ "overrides": [
+ {
+ "matcher": {
+ "id": "byFrameRefID",
+ "options": "A"
+ },
+ "properties": [
+ {
+ "id": "color",
+ "value": {
+ "fixedColor": "#FFD60A",
+ "mode": "fixed"
+ }
+ }
+ ]
+ },
+ {
+ "matcher": {
+ "id": "byFrameRefID",
+ "options": "B"
+ },
+ "properties": [
+ {
+ "id": "color",
+ "value": {
+ "fixedColor": "#00FFE5",
+ "mode": "fixed"
+ }
+ }
+ ]
+ },
+ {
+ "matcher": {
+ "id": "byFrameRefID",
+ "options": "C"
+ },
+ "properties": [
+ {
+ "id": "color",
+ "value": {
+ "fixedColor": "#A78BFA",
+ "mode": "fixed"
+ }
+ }
+ ]
+ },
+ {
+ "matcher": {
+ "id": "byFrameRefID",
+ "options": "D"
+ },
+ "properties": [
+ {
+ "id": "color",
+ "value": {
+ "fixedColor": "#64748B",
+ "mode": "fixed"
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "gridPos": {
+ "h": 10,
+ "w": 14,
+ "x": 10,
+ "y": 55
+ },
+ "id": 26,
+ "options": {
+ "barRadius": 0,
+ "barWidth": 0.88,
+ "fullHighlight": false,
+ "groupWidth": 0.9,
+ "legend": {
+ "displayMode": "list",
+ "placement": "bottom",
+ "showLegend": false
+ },
+ "orientation": "horizontal",
+ "showValue": "always",
+ "stacking": "none",
+ "tooltip": {
+ "mode": "single"
+ },
+ "xTickLabelRotation": 0,
+ "xTickLabelSpacing": 0
+ },
+ "pluginVersion": "12.4.1",
+ "targets": [
+ {
+ "editorMode": "code",
+ "expr": "topk(1, sum by (operation) (rate(openviking_operation_tokens_total{account_id=~\"$account_id\"}[5m])))",
+ "instant": true,
+ "legendFormat": "{{operation}}",
+ "range": false,
+ "refId": "A"
+ },
+ {
+ "editorMode": "code",
+ "expr": "topk(2, sum by (operation) (rate(openviking_operation_tokens_total{account_id=~\"$account_id\"}[5m]))) unless topk(1, sum by (operation) (rate(openviking_operation_tokens_total{account_id=~\"$account_id\"}[5m])))",
+ "instant": true,
+ "legendFormat": "{{operation}}",
+ "range": false,
+ "refId": "B"
+ },
+ {
+ "editorMode": "code",
+ "expr": "topk(3, sum by (operation) (rate(openviking_operation_tokens_total{account_id=~\"$account_id\"}[5m]))) unless topk(2, sum by (operation) (rate(openviking_operation_tokens_total{account_id=~\"$account_id\"}[5m])))",
+ "instant": true,
+ "legendFormat": "{{operation}}",
+ "range": false,
+ "refId": "C"
+ },
+ {
+ "editorMode": "code",
+ "expr": "topk(10, sum by (operation) (rate(openviking_operation_tokens_total{account_id=~\"$account_id\"}[5m]))) unless topk(3, sum by (operation) (rate(openviking_operation_tokens_total{account_id=~\"$account_id\"}[5m])))",
+ "instant": true,
+ "legendFormat": "{{operation}}",
+ "range": false,
+ "refId": "D"
+ }
+ ],
+ "title": "Top Operations by Token Rate (top10, top3 highlighted)",
+ "type": "barchart"
+ }
+ ],
+ "preload": false,
+ "refresh": "30s",
+ "schemaVersion": 42,
+ "tags": [
+ "openviking",
+ "metrics",
+ "prometheus",
+ "token",
+ "developer",
+ "cockpit"
+ ],
+ "templating": {
+ "list": [
+ {
+ "current": {
+ "text": "Prometheus",
+ "value": "prometheus"
+ },
+ "includeAll": false,
+ "label": "datasource",
+ "name": "DS_PROMETHEUS",
+ "options": [],
+ "query": "prometheus",
+ "refresh": 1,
+ "regex": "",
+ "type": "datasource"
+ },
+ {
+ "current": {
+ "text": "All",
+ "value": [
+ "$__all"
+ ]
+ },
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "definition": "label_values(openviking_operation_tokens_total, account_id)",
+ "includeAll": true,
+ "label": "account_id",
+ "multi": true,
+ "name": "account_id",
+ "options": [],
+ "query": {
+ "query": "label_values(openviking_operation_tokens_total, account_id)",
+ "refId": "account_id-var"
+ },
+ "refresh": 2,
+ "regex": "",
+ "regexApplyTo": "value",
+ "sort": 1,
+ "type": "query"
+ },
+ {
+ "current": {
+ "text": "All",
+ "value": [
+ "$__all"
+ ]
+ },
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "definition": "label_values(openviking_operation_tokens_total{account_id=~\"$account_id\"}, operation)",
+ "includeAll": true,
+ "label": "operation",
+ "multi": true,
+ "name": "operation",
+ "options": [],
+ "query": {
+ "query": "label_values(openviking_operation_tokens_total{account_id=~\"$account_id\"}, operation)",
+ "refId": "operation-var"
+ },
+ "refresh": 2,
+ "regex": "",
+ "regexApplyTo": "value",
+ "sort": 1,
+ "type": "query"
+ },
+ {
+ "current": {
+ "text": "All",
+ "value": [
+ "$__all"
+ ]
+ },
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "definition": "label_values(openviking_model_calls_total, provider)",
+ "includeAll": true,
+ "label": "provider",
+ "multi": true,
+ "name": "provider",
+ "options": [],
+ "query": {
+ "query": "label_values(openviking_model_calls_total, provider)",
+ "refId": "provider-var"
+ },
+ "refresh": 2,
+ "regex": "",
+ "regexApplyTo": "value",
+ "sort": 1,
+ "type": "query"
+ },
+ {
+ "current": {
+ "text": "All",
+ "value": [
+ "$__all"
+ ]
+ },
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "definition": "label_values(openviking_model_calls_total{provider=~\"$provider\"}, model_name)",
+ "includeAll": true,
+ "label": "model_name",
+ "multi": true,
+ "name": "model_name",
+ "options": [],
+ "query": {
+ "query": "label_values(openviking_model_calls_total{provider=~\"$provider\"}, model_name)",
+ "refId": "model_name-var"
+ },
+ "refresh": 2,
+ "regex": "",
+ "regexApplyTo": "value",
+ "sort": 1,
+ "type": "query"
+ },
+ {
+ "current": {
+ "text": "All",
+ "value": [
+ "$__all"
+ ]
+ },
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "definition": "label_values(openviking_operation_tokens_total, stage)",
+ "includeAll": true,
+ "label": "stage",
+ "multi": true,
+ "name": "stage",
+ "options": [],
+ "query": {
+ "query": "label_values(openviking_operation_tokens_total, stage)",
+ "refId": "stage-var"
+ },
+ "refresh": 2,
+ "regex": "",
+ "regexApplyTo": "value",
+ "sort": 1,
+ "type": "query"
+ }
+ ]
+ },
+ "time": {
+ "from": "now-365d",
+ "to": "now"
+ },
+ "timepicker": {},
+ "timezone": "browser",
+ "title": "OpenViking - Token Cockpit",
+ "uid": "openviking-token-cockpit",
+ "version": 1,
+ "weekStart": ""
+}
\ No newline at end of file
diff --git a/examples/ov.conf.example b/examples/ov.conf.example
index 890dd428d..3e19929bf 100644
--- a/examples/ov.conf.example
+++ b/examples/ov.conf.example
@@ -4,19 +4,16 @@
"port": 1933,
"root_api_key": null,
"cors_origins": ["*"],
- "telemetry": {
- "prometheus": {
- "enabled": false
- }
- },
- "metrics": {
- "enabled": true,
- "account_dimension": {
+ "observability": {
+ "metrics": {
"enabled": true,
- "max_active_accounts": 100,
- "metric_allowlist": [
- "openviking_*"
- ]
+ "account_dimension": {
+ "enabled": true,
+ "max_active_accounts": 100,
+ "metric_allowlist": [
+ "openviking_*"
+ ]
+ }
}
}
},
diff --git a/openviking/metrics/account_dimension.py b/openviking/metrics/account_dimension.py
index 3bae0fb84..96bb05166 100644
--- a/openviking/metrics/account_dimension.py
+++ b/openviking/metrics/account_dimension.py
@@ -22,6 +22,11 @@ ACCOUNT_DIMENSION_SUPPORTED_METRICS = frozenset(
"openviking_embedding_requests_total",
"openviking_embedding_latency_seconds",
"openviking_embedding_errors_total",
+ "openviking_embedding_calls_total",
+ "openviking_embedding_call_duration_seconds",
+ "openviking_embedding_tokens_input_total",
+ "openviking_embedding_tokens_output_total",
+ "openviking_embedding_tokens_total",
"openviking_http_requests_total",
"openviking_http_request_duration_seconds",
"openviking_http_inflight_requests",
@@ -45,6 +50,11 @@ ACCOUNT_DIMENSION_SUPPORTED_METRICS = frozenset(
"openviking_vlm_tokens_input_total",
"openviking_vlm_tokens_output_total",
"openviking_vlm_tokens_total",
+ "openviking_rerank_calls_total",
+ "openviking_rerank_call_duration_seconds",
+ "openviking_rerank_tokens_input_total",
+ "openviking_rerank_tokens_output_total",
+ "openviking_rerank_tokens_total",
}
)
@@ -58,9 +68,8 @@ class MetricAccountDimensionConfig:
account cap that protects Prometheus from unbounded tenant cardinality.
"""
- # Enabled by default, but still allowlist-gated at write time.
- enabled: bool = True
- max_active_accounts: int = 100
+ enabled: bool = False
+ max_active_accounts: int = 0
metric_allowlist: frozenset[str] = frozenset()
@@ -126,21 +135,20 @@ class MetricAccountDimensionPolicy:
if not normalized:
continue
if normalized.endswith("*"):
- # Limited wildcard syntax: trailing '*' means prefix match.
- # '*' alone (empty prefix) is ignored to reduce accidental broad exposure.
+ # Support a limited wildcard syntax: trailing '*' means prefix match.
prefix = normalized[:-1].strip()
if prefix:
prefixes.add(prefix)
continue
exact.add(normalized)
self._metric_allowlist_exact = frozenset(exact)
- # Tuple keeps iteration deterministic and slightly faster than set in hot path.
self._metric_allowlist_prefixes = tuple(sorted(prefixes))
self._max_active_accounts = max(0, int(max_active_accounts))
self._lock = threading.Lock()
self._active_accounts: set[str] = set()
def _is_metric_allowlisted(self, metric_name: str) -> bool:
+ """Return whether the metric name passes the allowlist gate (exact or prefix '*')."""
name = str(metric_name)
if name in self._metric_allowlist_exact:
return True
diff --git a/openviking/metrics/collectors/__init__.py b/openviking/metrics/collectors/__init__.py
index 042d06b07..7f63d51ca 100644
--- a/openviking/metrics/collectors/__init__.py
+++ b/openviking/metrics/collectors/__init__.py
@@ -23,6 +23,7 @@ from .model_usage import ModelUsageCollector
from .observer_health import ObserverHealthCollector
from .observer_state import ObserverStateCollector
from .queue import QueueCollector
+from .rerank import RerankCollector
from .retrieval import RetrievalCollector
from .retrieval_backend_probe import RetrievalBackendProbeCollector
from .service_probe import ServiceProbeCollector
@@ -44,6 +45,7 @@ __all__ = [
"CacheCollector",
"EncryptionCollector",
"QueueCollector",
+ "RerankCollector",
"LockCollector",
"VikingDBCollector",
"ObserverHealthCollector",
diff --git a/openviking/metrics/collectors/embedding.py b/openviking/metrics/collectors/embedding.py
index bd5869cb0..003eb8bf9 100644
--- a/openviking/metrics/collectors/embedding.py
+++ b/openviking/metrics/collectors/embedding.py
@@ -8,6 +8,7 @@ Tracks embedding request outcomes and latency:
- Requests counter by status
- Latency histogram by status
- Error counter by normalized error code
+- Per-call provider/model counters, latency, and token usage
It is fed by EmbeddingEventDataSource events emitted from embedding call sites.
"""
@@ -32,6 +33,27 @@ class EmbeddingCollector(EventMetricCollector):
"""
DOMAIN: ClassVar[str] = "embedding"
+ # rule: <METRICS_NAMESPACE>_<DOMAIN>_calls_total
+ # e.g.: openviking_embedding_calls_total
+ CALLS_TOTAL: ClassVar[str] = MetricCollector.metric_name(DOMAIN, "calls", unit="total")
+ # rule: <METRICS_NAMESPACE>_<DOMAIN>_call_duration_seconds
+ # e.g.: openviking_embedding_call_duration_seconds
+ CALL_DURATION_SECONDS: ClassVar[str] = MetricCollector.metric_name(
+ DOMAIN, "call_duration", unit="seconds"
+ )
+ # rule: <METRICS_NAMESPACE>_<DOMAIN>_tokens_input_total
+ # e.g.: openviking_embedding_tokens_input_total
+ TOKENS_INPUT_TOTAL: ClassVar[str] = MetricCollector.metric_name(
+ DOMAIN, "tokens_input", unit="total"
+ )
+ # rule: <METRICS_NAMESPACE>_<DOMAIN>_tokens_output_total
+ # e.g.: openviking_embedding_tokens_output_total
+ TOKENS_OUTPUT_TOTAL: ClassVar[str] = MetricCollector.metric_name(
+ DOMAIN, "tokens_output", unit="total"
+ )
+ # rule: <METRICS_NAMESPACE>_<DOMAIN>_tokens_total
+ # e.g.: openviking_embedding_tokens_total
+ TOKENS_TOTAL: ClassVar[str] = MetricCollector.metric_name(DOMAIN, "tokens", unit="total")
# rule: <METRICS_NAMESPACE>_<DOMAIN>_requests_total
# e.g.: openviking_embedding_requests_total
REQUESTS_TOTAL: ClassVar[str] = MetricCollector.metric_name(DOMAIN, "requests", unit="total")
@@ -42,7 +64,13 @@ class EmbeddingCollector(EventMetricCollector):
# e.g.: openviking_embedding_errors_total
ERRORS_TOTAL: ClassVar[str] = MetricCollector.metric_name(DOMAIN, "errors", unit="total")
- SUPPORTED_EVENTS: ClassVar[frozenset[str]] = frozenset({"embedding.success", "embedding.error"})
+ SUPPORTED_EVENTS: ClassVar[frozenset[str]] = frozenset(
+ {
+ "embedding.call",
+ "embedding.success",
+ "embedding.error",
+ }
+ )
def collect(self, registry=None) -> None:
"""Implement the unified collector interface as a no-op for this event-driven collector."""
@@ -55,6 +83,19 @@ class EmbeddingCollector(EventMetricCollector):
Success and error events intentionally diverge into separate write paths so the collector
can emit different label sets without overloading one payload shape.
"""
+ if event_name == "embedding.call":
+ self.record_call(
+ registry,
+ provider=str(payload["provider"]),
+ model_name=str(payload["model_name"]),
+ duration_seconds=float(payload["duration_seconds"]),
+ prompt_tokens=int(payload["prompt_tokens"]),
+ completion_tokens=int(payload["completion_tokens"]),
+ account_id=(
+ None if payload.get("account_id") is None else str(payload.get("account_id"))
+ ),
+ )
+ return
if event_name == "embedding.success":
self.record_success(
registry,
@@ -73,6 +114,58 @@ class EmbeddingCollector(EventMetricCollector):
),
)
+ def record_call(
+ self,
+ registry,
+ *,
+ provider: str,
+ model_name: str,
+ duration_seconds: float,
+ prompt_tokens: int,
+ completion_tokens: int,
+ account_id: str | None = None,
+ ) -> None:
+ """Record one embedding provider call as calls/tokens counters and a latency sample."""
+ labels = {"provider": str(provider), "model_name": str(model_name)}
+ registry.inc_counter(
+ self.CALLS_TOTAL,
+ labels=labels,
+ label_names=("provider", "model_name"),
+ account_id=account_id,
+ )
+ registry.observe_histogram(
+ self.CALL_DURATION_SECONDS,
+ float(duration_seconds),
+ labels=labels,
+ label_names=("provider", "model_name"),
+ account_id=account_id,
+ )
+ if int(prompt_tokens) > 0:
+ registry.inc_counter(
+ self.TOKENS_INPUT_TOTAL,
+ labels=labels,
+ label_names=("provider", "model_name"),
+ amount=int(prompt_tokens),
+ account_id=account_id,
+ )
+ if int(completion_tokens) > 0:
+ registry.inc_counter(
+ self.TOKENS_OUTPUT_TOTAL,
+ labels=labels,
+ label_names=("provider", "model_name"),
+ amount=int(completion_tokens),
+ account_id=account_id,
+ )
+ total_tokens = int(prompt_tokens) + int(completion_tokens)
+ if total_tokens > 0:
+ registry.inc_counter(
+ self.TOKENS_TOTAL,
+ labels=labels,
+ label_names=("provider", "model_name"),
+ amount=total_tokens,
+ account_id=account_id,
+ )
+
def record_success(
self, registry, *, latency_seconds: float, account_id: str | None = None
) -> None:
diff --git a/openviking/metrics/collectors/http.py b/openviking/metrics/collectors/http.py
index 1479ff580..44e08c74f 100644
--- a/openviking/metrics/collectors/http.py
+++ b/openviking/metrics/collectors/http.py
@@ -25,10 +25,10 @@ from .base import EventMetricCollector
@dataclass
class HTTPCollector(EventMetricCollector):
"""
- Translate HTTP lifecycle events into request counters, latency histograms, and inflight gauges.
+ Translate HTTP lifecycle events into request volume, latency, and inflight gauges.
- The collector expects already-normalized route templates and status codes from the middleware
- datasource, then applies account-dimension policy before writing registry series.
+ Events are emitted by `HttpRequestLifecycleDataSource` (and middleware call sites) and are
+ normalized to avoid framework-specific request objects leaking into the metrics layer.
"""
DOMAIN: ClassVar[str] = "http"
@@ -47,37 +47,53 @@ class HTTPCollector(EventMetricCollector):
SUPPORTED_EVENTS: ClassVar[frozenset[str]] = frozenset({"http.request", "http.inflight"})
def collect(self, registry=None) -> None:
- """Implement the unified collector interface as a no-op for this event-driven collector."""
+ """Implement the collector interface as a no-op because HTTP metrics are event-driven."""
return None
def receive_hook(self, event_name: str, payload: dict, registry) -> None:
"""
- Translate one supported HTTP lifecycle event into the corresponding metric writes.
+ Dispatch one normalized HTTP event payload to the matching metric writers.
- The hook assumes payload validation has already happened in the shared event-collector
- entrypoint and only branches on the normalized event name.
+ Supported payloads:
+ - http.request: method, route, status, duration_seconds, optional account_id
+ - http.inflight: route, value, optional account_id
"""
if event_name == "http.request":
+ # Be defensive: router/middleware bugs should never crash metrics.
+ required_keys = ("method", "route", "status", "duration_seconds")
+ if not all(key in payload for key in required_keys):
+ return
+ try:
+ duration_seconds = float(payload["duration_seconds"])
+ except (TypeError, ValueError):
+ return
self.record_request(
registry,
method=str(payload["method"]),
route=str(payload["route"]),
status=str(payload["status"]),
- duration_seconds=float(payload["duration_seconds"]),
- account_id=(
- None if payload.get("account_id") is None else str(payload.get("account_id"))
- ),
+ duration_seconds=duration_seconds,
+ account_id=payload.get("account_id"),
)
return
if event_name == "http.inflight":
+ if "route" not in payload or "value" not in payload:
+ return
+ try:
+ value = float(payload["value"])
+ except (TypeError, ValueError):
+ return
self.record_inflight(
registry,
route=str(payload["route"]),
- value=float(payload["value"]),
- account_id=(
- None if payload.get("account_id") is None else str(payload.get("account_id"))
- ),
+ value=value,
+ account_id=payload.get("account_id"),
)
+ return
+
+ # Unknown events are ignored; `EventMetricCollector.receive()` already gates supported
+ # events, but keep this explicit to avoid future regressions.
+ return
def record_request(
self,
@@ -89,40 +105,32 @@ class HTTPCollector(EventMetricCollector):
duration_seconds: float,
account_id: str | None = None,
) -> None:
- """
- Record a completed HTTP request as both a counter increment and a latency sample.
-
- Counter and histogram labels intentionally share the same route/method/status tuple so
- downstream PromQL can aggregate them consistently.
- """
+ """Record a completed HTTP request counter increment and one latency sample."""
labels = {"method": str(method), "route": str(route), "status": str(status)}
registry.inc_counter(
self.REQUESTS_TOTAL,
labels=labels,
label_names=("method", "route", "status"),
- account_id=account_id,
+ account_id=None if account_id is None else str(account_id),
)
+ if duration_seconds < 0:
+ return
registry.observe_histogram(
self.REQUEST_DURATION_SECONDS,
float(duration_seconds),
labels=labels,
label_names=("method", "route", "status"),
- account_id=account_id,
+ account_id=None if account_id is None else str(account_id),
)
def record_inflight(
self, registry, *, route: str, value: float, account_id: str | None = None
) -> None:
- """
- Set the current inflight request gauge value for one normalized route template.
-
- The caller provides the absolute inflight value, allowing middleware to keep the stateful
- accounting logic outside the collector itself.
- """
+ """Set the inflight request gauge value for one route template."""
registry.set_gauge(
self.INFLIGHT_REQUESTS,
float(value),
labels={"route": str(route)},
label_names=("route",),
- account_id=account_id,
+ account_id=None if account_id is None else str(account_id),
)
diff --git a/openviking/metrics/collectors/rerank.py b/openviking/metrics/collectors/rerank.py
new file mode 100644
index 000000000..195943343
--- /dev/null
+++ b/openviking/metrics/collectors/rerank.py
@@ -0,0 +1,128 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+"""
+Event collector: RerankCollector.
+
+Tracks rerank call count, duration, and token usage:
+- Calls counter by provider/model
+- Duration histogram by provider/model
+- Token counters by provider/model
+
+This collector is fed by `RerankEventDataSource.record_call(...)` events emitted from rerank code
+paths.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import ClassVar
+
+from openviking.metrics.core.base import MetricCollector
+
+from .base import EventMetricCollector
+
+
+@dataclass
+class RerankCollector(EventMetricCollector):
+ """
+ Translate rerank call events into per-provider/model counters and latency/token metrics.
+
+ The collector mirrors the VLM per-call metric family so rerank can participate in the same
+ dashboard patterns without introducing provider-specific series names.
+ """
+
+ DOMAIN: ClassVar[str] = "rerank"
+ # rule: <METRICS_NAMESPACE>_<DOMAIN>_calls_total
+ # e.g.: openviking_rerank_calls_total
+ CALLS_TOTAL: ClassVar[str] = MetricCollector.metric_name(DOMAIN, "calls", unit="total")
+ # rule: <METRICS_NAMESPACE>_<DOMAIN>_call_duration_seconds
+ # e.g.: openviking_rerank_call_duration_seconds
+ CALL_DURATION_SECONDS: ClassVar[str] = MetricCollector.metric_name(
+ DOMAIN, "call_duration", unit="seconds"
+ )
+ # rule: <METRICS_NAMESPACE>_<DOMAIN>_tokens_input_total
+ # e.g.: openviking_rerank_tokens_input_total
+ TOKENS_INPUT_TOTAL: ClassVar[str] = MetricCollector.metric_name(
+ DOMAIN, "tokens_input", unit="total"
+ )
+ # rule: <METRICS_NAMESPACE>_<DOMAIN>_tokens_output_total
+ # e.g.: openviking_rerank_tokens_output_total
+ TOKENS_OUTPUT_TOTAL: ClassVar[str] = MetricCollector.metric_name(
+ DOMAIN, "tokens_output", unit="total"
+ )
+ # rule: <METRICS_NAMESPACE>_<DOMAIN>_tokens_total
+ # e.g.: openviking_rerank_tokens_total
+ TOKENS_TOTAL: ClassVar[str] = MetricCollector.metric_name(DOMAIN, "tokens", unit="total")
+
+ SUPPORTED_EVENTS: ClassVar[frozenset[str]] = frozenset({"rerank.call"})
+
+ def collect(self, registry=None) -> None:
+ """Implement the unified collector interface as a no-op for this event-driven collector."""
+ return None
+
+ def receive_hook(self, event_name: str, payload: dict, registry) -> None:
+ """Translate one rerank-call payload into counters and histogram samples."""
+ self.record_call(
+ registry,
+ provider=str(payload["provider"]),
+ model_name=str(payload["model_name"]),
+ duration_seconds=float(payload["duration_seconds"]),
+ prompt_tokens=int(payload["prompt_tokens"]),
+ completion_tokens=int(payload["completion_tokens"]),
+ account_id=(
+ None if payload.get("account_id") is None else str(payload.get("account_id"))
+ ),
+ )
+
+ def record_call(
+ self,
+ registry,
+ *,
+ provider: str,
+ model_name: str,
+ duration_seconds: float,
+ prompt_tokens: int,
+ completion_tokens: int,
+ account_id: str | None = None,
+ ) -> None:
+ """Record one rerank call as calls/tokens counters plus a latency histogram sample."""
+ labels = {"provider": str(provider), "model_name": str(model_name)}
+ registry.inc_counter(
+ self.CALLS_TOTAL,
+ labels=labels,
+ label_names=("provider", "model_name"),
+ account_id=account_id,
+ )
+ registry.observe_histogram(
+ self.CALL_DURATION_SECONDS,
+ float(duration_seconds),
+ labels=labels,
+ label_names=("provider", "model_name"),
+ account_id=account_id,
+ )
+ if int(prompt_tokens) > 0:
+ registry.inc_counter(
+ self.TOKENS_INPUT_TOTAL,
+ labels=labels,
+ label_names=("provider", "model_name"),
+ amount=int(prompt_tokens),
+ account_id=account_id,
+ )
+ if int(completion_tokens) > 0:
+ registry.inc_counter(
+ self.TOKENS_OUTPUT_TOTAL,
+ labels=labels,
+ label_names=("provider", "model_name"),
+ amount=int(completion_tokens),
+ account_id=account_id,
+ )
+ total_tokens = int(prompt_tokens) + int(completion_tokens)
+ if total_tokens > 0:
+ registry.inc_counter(
+ self.TOKENS_TOTAL,
+ labels=labels,
+ label_names=("provider", "model_name"),
+ amount=total_tokens,
+ account_id=account_id,
+ )
diff --git a/openviking/metrics/collectors/telemetry_bridge.py b/openviking/metrics/collectors/telemetry_bridge.py
index 5e05df572..01340a8ef 100644
--- a/openviking/metrics/collectors/telemetry_bridge.py
+++ b/openviking/metrics/collectors/telemetry_bridge.py
@@ -114,6 +114,56 @@ class TelemetryBridgeCollector(EventMetricCollector):
SUPPORTED_EVENTS: ClassVar[frozenset[str]] = frozenset({"telemetry.summary"})
+ @staticmethod
+ def _extract_total_tokens(payload: Any) -> int:
+ """Extract a total token count from either an int payload or a `{total: ...}` mapping."""
+ if isinstance(payload, Mapping):
+ return int(payload.get("total", 0) or 0)
+ return int(payload or 0)
+
+ def _iter_stage_token_metrics(self, tokens: Mapping[str, Any]) -> list[tuple[str, str, int]]:
+ """Expand telemetry token payloads into `(stage, token_type, value)` tuples."""
+ stages = tokens.get("stages") or {}
+ if isinstance(stages, Mapping) and stages:
+ metrics: list[tuple[str, str, int]] = []
+ for stage, stage_payload in stages.items():
+ if not isinstance(stage_payload, Mapping):
+ continue
+ llm_payload = stage_payload.get("llm") or {}
+ if isinstance(llm_payload, Mapping):
+ llm_input = int(llm_payload.get("input", 0) or 0)
+ llm_output = int(llm_payload.get("output", 0) or 0)
+ if llm_input > 0:
+ metrics.append((str(stage), "llm_input", llm_input))
+ if llm_output > 0:
+ metrics.append((str(stage), "llm_output", llm_output))
+ for source_name, token_type in (
+ ("embedding", "embedding"),
+ ("rerank", "rerank"),
+ ):
+ total = self._extract_total_tokens(stage_payload.get(source_name, 0) or 0)
+ if total > 0:
+ metrics.append((str(stage), token_type, total))
+ return metrics
+
+ llm = tokens.get("llm") or {}
+ metrics = []
+ llm_input = int(llm.get("input", 0) or 0)
+ llm_output = int(llm.get("output", 0) or 0)
+ if llm_input > 0:
+ metrics.append(("vlm", "llm_input", llm_input))
+ if llm_output > 0:
+ metrics.append(("vlm", "llm_output", llm_output))
+
+ embedding_total = self._extract_total_tokens(tokens.get("embedding", 0) or 0)
+ if embedding_total > 0:
+ metrics.append(("embed_resource", "embedding", embedding_total))
+
+ rerank_total = self._extract_total_tokens(tokens.get("rerank", 0) or 0)
+ if rerank_total > 0:
+ metrics.append(("rerank", "rerank", rerank_total))
+ return metrics
+
def collect(self, registry=None) -> None:
"""
Implement the unified collector interface as a no-op for this event-driven collector.
@@ -160,24 +210,13 @@ class TelemetryBridgeCollector(EventMetricCollector):
)
tokens = summary.get("tokens") or {}
- total_tokens = int(tokens.get("total", 0) or 0)
- llm = tokens.get("llm") or {}
- llm_input = int(llm.get("input", 0) or 0)
- llm_output = int(llm.get("output", 0) or 0)
- embedding_tokens = int(tokens.get("embedding", 0) or 0)
-
- for token_type, value in (
- ("all", total_tokens),
- ("llm_input", llm_input),
- ("llm_output", llm_output),
- ("embedding", embedding_tokens),
- ):
+ for stage, token_type, value in self._iter_stage_token_metrics(tokens):
if value <= 0:
continue
registry.inc_counter(
self.OPERATION_TOKENS_TOTAL,
- labels={"operation": operation, "token_type": token_type},
- label_names=("operation", "token_type"),
+ labels={"operation": operation, "stage": stage, "token_type": token_type},
+ label_names=("operation", "stage", "token_type"),
amount=value,
)
diff --git a/openviking/metrics/datasources/__init__.py b/openviking/metrics/datasources/__init__.py
index 26f2d73af..c7b02c1c2 100644
--- a/openviking/metrics/datasources/__init__.py
+++ b/openviking/metrics/datasources/__init__.py
@@ -12,7 +12,7 @@ from .base import (
from .cache import CacheEventDataSource
from .encryption import EncryptionEventDataSource
from .http import HttpRequestLifecycleDataSource
-from .model_usage import EmbeddingEventDataSource, VLMEventDataSource
+from .model_usage import EmbeddingEventDataSource, RerankEventDataSource, VLMEventDataSource
from .resource import ResourceIngestionEventDataSource
from .retrieval import RetrievalStatsDataSource
from .session import SessionLifecycleDataSource
@@ -25,6 +25,7 @@ __all__ = [
"ProbeMetricDataSource",
"RetrievalStatsDataSource",
"EmbeddingEventDataSource",
+ "RerankEventDataSource",
"VLMEventDataSource",
"SessionLifecycleDataSource",
"HttpRequestLifecycleDataSource",
diff --git a/openviking/metrics/datasources/model_usage.py b/openviking/metrics/datasources/model_usage.py
index cdddf9c7e..39292fec5 100644
--- a/openviking/metrics/datasources/model_usage.py
+++ b/openviking/metrics/datasources/model_usage.py
@@ -8,7 +8,8 @@ This file provides two categories of DataSource APIs:
1) DomainStats (pull): `ModelUsageDataSource.read_model_usage()` reads aggregated cumulative
usage from in-process model instances / shared token trackers. This is used by
`ModelUsageCollector` which converts cumulative stats into Prometheus Counters via deltas.
-2) Event (push): `VLMEventDataSource` and `EmbeddingEventDataSource` emit per-call events.
+2) Event (push): `VLMEventDataSource`, `EmbeddingEventDataSource`, and
+ `RerankEventDataSource` emit per-call events.
These events are routed to Event collectors via `try_dispatch_event`.
Note: DataSources are not allowed to write into MetricRegistry directly in this architecture.
@@ -158,6 +159,29 @@ class EmbeddingEventDataSource(EventMetricDataSource):
appropriate request, latency, and error-code series without inspecting exception objects.
"""
+ @staticmethod
+ def record_call(
+ *,
+ provider: str,
+ model_name: str,
+ duration_seconds: float,
+ prompt_tokens: int,
+ completion_tokens: int,
+ account_id: str | None = None,
+ ) -> None:
+ """Emit one embedding provider call with tokens, latency, and optional account context."""
+ EventMetricDataSource._emit(
+ "embedding.call",
+ {
+ "provider": str(provider),
+ "model_name": str(model_name),
+ "duration_seconds": float(duration_seconds),
+ "prompt_tokens": int(prompt_tokens),
+ "completion_tokens": int(completion_tokens),
+ "account_id": None if account_id is None else str(account_id),
+ },
+ )
+
@staticmethod
def record_success(*, latency_seconds: float, account_id: str | None = None) -> None:
"""
@@ -191,6 +215,33 @@ class EmbeddingEventDataSource(EventMetricDataSource):
)
+class RerankEventDataSource(EventMetricDataSource):
+ """Event datasource for per-call rerank usage events."""
+
+ @staticmethod
+ def record_call(
+ *,
+ provider: str,
+ model_name: str,
+ duration_seconds: float,
+ prompt_tokens: int,
+ completion_tokens: int,
+ account_id: str | None = None,
+ ) -> None:
+ """Emit one rerank provider call with tokens, latency, and optional account context."""
+ EventMetricDataSource._emit(
+ "rerank.call",
+ {
+ "provider": str(provider),
+ "model_name": str(model_name),
+ "duration_seconds": float(duration_seconds),
+ "prompt_tokens": int(prompt_tokens),
+ "completion_tokens": int(completion_tokens),
+ "account_id": None if account_id is None else str(account_id),
+ },
+ )
+
+
def _extract_usage_by_model(token_usage: dict, datasource: DomainStatsMetricDataSource) -> dict:
"""
Extract and normalize a `usage_by_model` mapping from TokenUsageTracker-like payloads.
diff --git a/openviking/metrics/global_api.py b/openviking/metrics/global_api.py
index 8269e2575..d65ff03ff 100644
--- a/openviking/metrics/global_api.py
+++ b/openviking/metrics/global_api.py
@@ -20,6 +20,8 @@ from __future__ import annotations
import threading
from typing import Optional
+from openviking.server.config import ServerConfig
+
from .account_dimension import (
configure_metric_account_dimension as _configure_metric_account_dimension_runtime,
)
@@ -31,6 +33,7 @@ from .collectors.cache import CacheCollector
from .collectors.embedding import EmbeddingCollector
from .collectors.encryption import EncryptionCollector
from .collectors.http import HTTPCollector
+from .collectors.rerank import RerankCollector
from .collectors.resource import ResourceIngestionCollector
from .collectors.retrieval import RetrievalCollector
from .collectors.session import SessionCollector
@@ -46,20 +49,6 @@ _exporter: Optional[PrometheusExporter] = None
_event_router: EventCollectorRouter | None = None
-def is_metrics_enabled_from_server_config(config) -> bool:
- """
- Return whether metrics are enabled through either the new or legacy server config path.
-
- This compatibility helper keeps older `telemetry.prometheus.enabled` deployments working
- while newer code migrates toward `server.metrics.enabled`.
- """
- legacy_enabled = bool(
- getattr(getattr(getattr(config, "telemetry", None), "prometheus", None), "enabled", False)
- )
- metrics_enabled = bool(getattr(getattr(config, "metrics", None), "enabled", False))
- return legacy_enabled or metrics_enabled
-
-
def configure_metric_account_dimension(
*,
enabled: bool | None = None,
@@ -84,7 +73,7 @@ def configure_metric_account_dimension(
def init_metrics_from_server_config(
- config, *, app=None, service=None, registry: MetricRegistry | None = None
+ config: ServerConfig, *, app=None, service=None, registry: MetricRegistry | None = None
) -> None:
"""
Initialize the process-global metrics registry, router, and exporter from server config.
@@ -99,7 +88,7 @@ def init_metrics_from_server_config(
- Resets account-dimension runtime to its disabled defaults
- Detaches any exporter reference previously stored on `app.state`
"""
- enabled = is_metrics_enabled_from_server_config(config)
+ enabled = config.observability.metrics.enabled
global _registry, _exporter, _event_router
with _lock:
if not enabled:
@@ -110,12 +99,11 @@ def init_metrics_from_server_config(
if app is not None:
app.state.metrics_exporter = None
return
- metrics_config = getattr(config, "metrics", None)
- account_dimension = getattr(metrics_config, "account_dimension", None)
+ account_dimension = config.observability.metrics.account_dimension
configure_metric_account_dimension(
- enabled=bool(getattr(account_dimension, "enabled", False)),
- metric_allowlist=list(getattr(account_dimension, "metric_allowlist", []) or []),
- max_active_accounts=int(getattr(account_dimension, "max_active_accounts", 0) or 0),
+ enabled=account_dimension.enabled,
+ metric_allowlist=list(account_dimension.metric_allowlist or []),
+ max_active_accounts=int(account_dimension.max_active_accounts),
)
_registry = registry or MetricRegistry()
collector_manager = create_default_collector_manager(app=app, service=service)
@@ -189,6 +177,7 @@ def _build_event_router(registry: MetricRegistry) -> EventCollectorRouter:
http_collector = HTTPCollector()
cache_collector = CacheCollector()
embedding_collector = EmbeddingCollector()
+ rerank_collector = RerankCollector()
vlm_collector = VLMCollector()
session_collector = SessionCollector()
resource_collector = ResourceIngestionCollector()
@@ -216,8 +205,10 @@ def _build_event_router(registry: MetricRegistry) -> EventCollectorRouter:
("http.inflight", http_collector),
("cache.hit", cache_collector),
("cache.miss", cache_collector),
+ ("embedding.call", embedding_collector),
("embedding.success", embedding_collector),
("embedding.error", embedding_collector),
+ ("rerank.call", rerank_collector),
("vlm.call", vlm_collector),
("session.lifecycle", session_collector),
("session.contexts_used", session_collector),
diff --git a/openviking/models/embedder/base.py b/openviking/models/embedder/base.py
index 765559f4c..91352cd65 100644
--- a/openviking/models/embedder/base.py
+++ b/openviking/models/embedder/base.py
@@ -1,6 +1,7 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
import asyncio
+import logging
import random
import time
import weakref
@@ -13,6 +14,7 @@ from openviking.telemetry import get_current_telemetry
from openviking.utils.model_retry import retry_async, retry_sync
T = TypeVar("T")
+logger = logging.getLogger(__name__)
_token_tracker_instance = None
@@ -44,20 +46,28 @@ def _get_token_tracker():
async def embed_compat(embedder: Any, text: str, *, is_query: bool = False) -> "EmbedResult":
"""Call async embedding when available, otherwise fall back to sync embed()."""
+ from openviking.telemetry import bind_telemetry_stage
+
+ stage = "embed_query" if is_query else "embed_resource"
embed_async = getattr(embedder, "embed_async", None)
- if callable(embed_async):
- return await embed_async(text, is_query=is_query)
- return embedder.embed(text, is_query=is_query)
+ with bind_telemetry_stage(stage):
+ if callable(embed_async):
+ return await embed_async(text, is_query=is_query)
+ return embedder.embed(text, is_query=is_query)
async def embed_batch_compat(
embedder: Any, texts: List[str], *, is_query: bool = False
) -> List["EmbedResult"]:
"""Call async batch embedding when available, otherwise fall back to sync embed_batch()."""
+ from openviking.telemetry import bind_telemetry_stage
+
+ stage = "embed_query" if is_query else "embed_resource"
embed_batch_async = getattr(embedder, "embed_batch_async", None)
- if callable(embed_batch_async):
- return await embed_batch_async(texts, is_query=is_query)
- return embedder.embed_batch(texts, is_query=is_query)
+ with bind_telemetry_stage(stage):
+ if callable(embed_batch_async):
+ return await embed_batch_async(texts, is_query=is_query)
+ return embedder.embed_batch(texts, is_query=is_query)
def truncate_and_normalize(embedding: List[float], dimension: Optional[int]) -> List[float]:
@@ -131,6 +141,7 @@ class EmbedderBase(ABC):
# Token usage tracking
self._token_tracker = _get_token_tracker()
+ self._active_call_started_at: float | None = None
@abstractmethod
def embed(self, text: str, is_query: bool = False) -> EmbedResult:
@@ -208,8 +219,16 @@ class EmbedderBase(ABC):
pass
def _run_with_retry(self, func: Callable[[], T], *, logger=None, operation_name: str) -> T:
+ def _wrapped() -> T:
+ previous_started_at = self._active_call_started_at
+ self._active_call_started_at = time.monotonic()
+ try:
+ return func()
+ finally:
+ self._active_call_started_at = previous_started_at
+
return retry_sync(
- func,
+ _wrapped,
max_retries=self.max_retries,
logger=logger,
operation_name=operation_name,
@@ -232,6 +251,8 @@ class EmbedderBase(ABC):
telemetry.set("embedding.async.wait_ms", round(wait_elapsed * 1000, 3))
started = time.monotonic()
+ previous_started_at = self._active_call_started_at
+ self._active_call_started_at = started
try:
return await func()
finally:
@@ -246,6 +267,7 @@ class EmbedderBase(ABC):
wait_elapsed * 1000,
elapsed * 1000,
)
+ self._active_call_started_at = previous_started_at
semaphore.release()
return await retry_async(
@@ -270,12 +292,25 @@ class EmbedderBase(ABC):
"""Check if result is hybrid (contains both dense and sparse vectors)"""
return False
+ def _resolve_metrics_duration_seconds(self, duration_seconds: float = 0.0) -> float:
+ """Resolve per-call metrics duration from an explicit value or the active call timer."""
+ try:
+ normalized_duration = max(float(duration_seconds), 0.0)
+ except (TypeError, ValueError):
+ normalized_duration = 0.0
+ if normalized_duration > 0:
+ return normalized_duration
+ if self._active_call_started_at is None:
+ return 0.0
+ return max(time.monotonic() - self._active_call_started_at, 0.0)
+
def update_token_usage(
self,
model_name: str,
provider: str,
prompt_tokens: int,
completion_tokens: int,
+ duration_seconds: float = 0.0,
) -> None:
"""Update token usage
@@ -284,6 +319,7 @@ class EmbedderBase(ABC):
provider: Provider name (openai, volcengine, etc.)
prompt_tokens: Number of input tokens
completion_tokens: Number of output tokens
+ duration_seconds: Wall-clock duration of the embedding provider call in seconds
"""
self._token_tracker.update(
model_name=model_name,
@@ -291,6 +327,28 @@ class EmbedderBase(ABC):
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
)
+ try:
+ from openviking.metrics.account_context import get_metric_account_context
+ from openviking.metrics.datasources import EmbeddingEventDataSource
+
+ EmbeddingEventDataSource.record_call(
+ provider=str(provider),
+ model_name=str(model_name),
+ duration_seconds=self._resolve_metrics_duration_seconds(duration_seconds),
+ prompt_tokens=int(prompt_tokens),
+ completion_tokens=int(completion_tokens),
+ account_id=get_metric_account_context().http_account_id,
+ )
+ except Exception as e:
+ # Metrics must never break embedding execution.
+ if logger.isEnabledFor(logging.DEBUG):
+ logger.debug(
+ "embedding.update_token_usage metrics emit failed provider=%s model_name=%s err=%s: %s",
+ provider,
+ model_name,
+ type(e).__name__,
+ e,
+ )
def get_token_usage(self) -> Dict[str, Any]:
"""Get token usage
diff --git a/openviking/models/rerank/base.py b/openviking/models/rerank/base.py
index 358a78eef..61942746c 100644
--- a/openviking/models/rerank/base.py
+++ b/openviking/models/rerank/base.py
@@ -6,9 +6,11 @@ RerankBase: Base class for all rerank clients.
Provides common token usage tracking functionality.
"""
+import logging
from typing import Any, Dict
_token_tracker_instance = None
+logger = logging.getLogger(__name__)
def _get_token_tracker():
@@ -53,6 +55,7 @@ class RerankBase:
provider: str,
prompt_tokens: int,
completion_tokens: int,
+ duration_seconds: float = 0.0,
) -> None:
"""Update token usage
@@ -61,6 +64,7 @@ class RerankBase:
provider: Provider name (vikingdb, openai, cohere, litellm, etc.)
prompt_tokens: Number of input tokens
completion_tokens: Number of output tokens
+ duration_seconds: Wall-clock duration of the rerank provider call in seconds
"""
self._token_tracker.update(
model_name=model_name,
@@ -68,12 +72,54 @@ class RerankBase:
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
)
+ try:
+ from openviking.telemetry import get_current_telemetry
+
+ get_current_telemetry().record_token_usage(
+ "rerank",
+ int(prompt_tokens),
+ int(completion_tokens),
+ stage="rerank",
+ )
+ except Exception as e:
+ # Telemetry must never break rerank execution.
+ if logger.isEnabledFor(logging.DEBUG):
+ logger.debug(
+ "rerank.update_token_usage telemetry emit failed provider=%s model_name=%s err=%s: %s",
+ provider,
+ model_name,
+ type(e).__name__,
+ e,
+ )
+ try:
+ from openviking.metrics.account_context import get_metric_account_context
+ from openviking.metrics.datasources import RerankEventDataSource
+
+ RerankEventDataSource.record_call(
+ provider=str(provider),
+ model_name=str(model_name),
+ duration_seconds=max(float(duration_seconds), 0.0),
+ prompt_tokens=int(prompt_tokens),
+ completion_tokens=int(completion_tokens),
+ account_id=get_metric_account_context().http_account_id,
+ )
+ except Exception as e:
+ # Metrics must never break rerank execution.
+ if logger.isEnabledFor(logging.DEBUG):
+ logger.debug(
+ "rerank.update_token_usage metrics emit failed provider=%s model_name=%s err=%s: %s",
+ provider,
+ model_name,
+ type(e).__name__,
+ e,
+ )
def _extract_and_update_token_usage(
self,
response_data: dict,
query: str,
documents: list,
+ duration_seconds: float = 0.0,
) -> None:
"""Extract and update token usage from API response.
@@ -81,6 +127,7 @@ class RerankBase:
response_data: Raw API response dict
query: Query text (for estimation if needed)
documents: List of documents (for estimation if needed)
+ duration_seconds: Wall-clock duration of the rerank provider call in seconds
"""
prompt_tokens = 0
completion_tokens = 0
@@ -109,6 +156,7 @@ class RerankBase:
provider=self.provider,
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
+ duration_seconds=duration_seconds,
)
def get_token_usage(self) -> Dict[str, Any]:
diff --git a/openviking/models/rerank/cohere_rerank.py b/openviking/models/rerank/cohere_rerank.py
index 473bb982a..79a3e22a8 100644
--- a/openviking/models/rerank/cohere_rerank.py
+++ b/openviking/models/rerank/cohere_rerank.py
@@ -9,6 +9,7 @@ Same interface: rerank_batch(query, documents) -> List[float]
# For logging, use Python's built-in logging
import logging
+import time
from typing import List, Optional
import httpx
@@ -57,6 +58,7 @@ class CohereRerankClient(RerankBase):
return []
try:
+ started = time.monotonic()
resp = self._client.post(
"/v2/rerank",
json={
@@ -71,7 +73,12 @@ class CohereRerankClient(RerankBase):
data = resp.json()
# Update token usage tracking
- self._extract_and_update_token_usage(data, query, documents)
+ self._extract_and_update_token_usage(
+ data,
+ query,
+ documents,
+ duration_seconds=time.monotonic() - started,
+ )
# Cohere returns results sorted by score desc with index field
# We need to map back to original order
diff --git a/openviking/models/rerank/litellm_rerank.py b/openviking/models/rerank/litellm_rerank.py
index c41bbe473..8bc2e9159 100644
--- a/openviking/models/rerank/litellm_rerank.py
+++ b/openviking/models/rerank/litellm_rerank.py
@@ -6,6 +6,7 @@ LiteLLM Rerank API Client.
# For logging, use Python's built-in logging
import logging
+import time
from typing import List, Optional
from openviking.models.rerank.base import RerankBase
@@ -51,6 +52,7 @@ class LiteLLMRerankClient(RerankBase):
try:
import litellm
+ started = time.monotonic()
response = litellm.rerank(
model=self.model_name,
query=query,
@@ -63,7 +65,12 @@ class LiteLLMRerankClient(RerankBase):
response_dict = (
response.model_dump() if hasattr(response, "model_dump") else response.__dict__
)
- self._extract_and_update_token_usage(response_dict, query, documents)
+ self._extract_and_update_token_usage(
+ response_dict,
+ query,
+ documents,
+ duration_seconds=time.monotonic() - started,
+ )
results = response.results
if not results:
diff --git a/openviking/models/rerank/volcengine_rerank.py b/openviking/models/rerank/volcengine_rerank.py
index 88d61cbce..cbb8a709c 100644
--- a/openviking/models/rerank/volcengine_rerank.py
+++ b/openviking/models/rerank/volcengine_rerank.py
@@ -10,6 +10,7 @@ import json
# For logging, use Python's built-in logging
import logging
+import time
from typing import List, Optional
import requests
@@ -109,6 +110,7 @@ class RerankClient(RerankBase):
}
try:
+ started = time.monotonic()
req = self._prepare_request(
method="POST",
path="/api/vikingdb/rerank",
@@ -130,7 +132,12 @@ class RerankClient(RerankBase):
return None
# Update token usage tracking (estimate, VikingDB doesn't provide token info)
- self._extract_and_update_token_usage(result, query, documents)
+ self._extract_and_update_token_usage(
+ result,
+ query,
+ documents,
+ duration_seconds=time.monotonic() - started,
+ )
# Each document is a separate group, data array returns scores for each group sequentially
data = result["result"]["data"]
diff --git a/openviking/models/vlm/base.py b/openviking/models/vlm/base.py
index 20b7aaa61..5845f8656 100644
--- a/openviking/models/vlm/base.py
+++ b/openviking/models/vlm/base.py
@@ -2,6 +2,7 @@
# SPDX-License-Identifier: AGPL-3.0
"""VLM base interface and abstract classes"""
+import logging
import re
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
@@ -13,6 +14,7 @@ from openviking.utils.time_utils import format_iso8601
from .token_usage import TokenUsageTracker
_THINK_TAG_RE = re.compile(r"<think>[\s\S]*?</think>")
+logger = logging.getLogger(__name__)
@dataclass
@@ -196,12 +198,23 @@ class VLMBase(ABC):
)
# Operation-level telemetry aggregation (no-op when telemetry is disabled).
try:
- from openviking.telemetry import get_current_telemetry
+ from openviking.telemetry import get_current_telemetry, get_current_telemetry_stage
- get_current_telemetry().add_token_usage(prompt_tokens, completion_tokens)
- except Exception:
+ get_current_telemetry().add_token_usage(
+ prompt_tokens,
+ completion_tokens,
+ stage=get_current_telemetry_stage() or "vlm",
+ )
+ except Exception as e:
# Telemetry must never break model inference.
- pass
+ if logger.isEnabledFor(logging.DEBUG):
+ logger.debug(
+ "vlm.update_token_usage telemetry emit failed provider=%s model_name=%s err=%s: %s",
+ provider,
+ model_name,
+ type(e).__name__,
+ e,
+ )
# Record the VLM call in Prometheus metrics (if enabled).
try:
@@ -216,8 +229,16 @@ class VLMBase(ABC):
completion_tokens=int(completion_tokens),
account_id=get_metric_account_context().http_account_id,
)
- except Exception:
- pass
+ except Exception as e:
+ # Metrics must never break model inference.
+ if logger.isEnabledFor(logging.DEBUG):
+ logger.debug(
+ "vlm.update_token_usage metrics emit failed provider=%s model_name=%s err=%s: %s",
+ provider,
+ model_name,
+ type(e).__name__,
+ e,
+ )
def get_token_usage(self) -> Dict[str, Any]:
"""Get token usage
diff --git a/openviking/server/app.py b/openviking/server/app.py
index 2f67d8cb9..d173b474c 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -113,11 +113,10 @@ def create_app(
from openviking.metrics.global_api import (
init_metrics_from_server_config,
- is_metrics_enabled_from_server_config,
)
init_metrics_from_server_config(config, app=app, service=service)
- if is_metrics_enabled_from_server_config(config):
+ if config.observability.metrics.enabled:
logger.info("Prometheus metrics enabled at /metrics")
# Start TaskTracker cleanup loop
diff --git a/openviking/server/config.py b/openviking/server/config.py
index 3f95d0502..9808ba816 100644
--- a/openviking/server/config.py
+++ b/openviking/server/config.py
@@ -23,22 +23,6 @@ from openviking_cli.utils.config.consts import (
logger = get_logger(__name__)
-class PrometheusConfig(BaseModel):
- """Prometheus exporter configuration."""
-
- enabled: bool = False
-
- model_config = {"extra": "forbid"}
-
-
-class TelemetryConfig(BaseModel):
- """Telemetry configuration."""
-
- prometheus: PrometheusConfig = Field(default_factory=PrometheusConfig)
-
- model_config = {"extra": "forbid"}
-
-
class MetricsAccountDimensionConfig(BaseModel):
"""Account-dimension configuration for metrics label injection."""
@@ -61,6 +45,14 @@ class MetricsConfig(BaseModel):
model_config = {"extra": "forbid"}
+class ObservabilityConfig(BaseModel):
+ """Server-side observability configuration."""
+
+ metrics: MetricsConfig = Field(default_factory=MetricsConfig)
+
+ model_config = {"extra": "forbid"}
+
+
class ServerConfig(BaseModel):
host: str = "127.0.0.1"
port: int = 1933
@@ -71,8 +63,7 @@ class ServerConfig(BaseModel):
with_bot: bool = False # Enable Bot API proxy to Vikingbot
bot_api_url: str = "http://localhost:18790" # Vikingbot OpenAPIChannel URL (default port)
encryption_enabled: bool = False # Whether API key hashing is enabled
- telemetry: TelemetryConfig = Field(default_factory=TelemetryConfig)
- metrics: MetricsConfig = Field(default_factory=MetricsConfig)
+ observability: ObservabilityConfig = Field(default_factory=ObservabilityConfig)
model_config = {"extra": "forbid"}
diff --git a/openviking/session/memory/extract_loop.py b/openviking/session/memory/extract_loop.py
index b764c7745..191a19340 100644
--- a/openviking/session/memory/extract_loop.py
+++ b/openviking/session/memory/extract_loop.py
@@ -28,7 +28,7 @@ from openviking.session.memory.utils import (
validate_operations_uris,
)
from openviking.storage.viking_fs import VikingFS, get_viking_fs
-from openviking.telemetry import tracer
+from openviking.telemetry import bind_telemetry_stage, tracer
from openviking_cli.utils import get_logger
logger = get_logger(__name__)
@@ -361,11 +361,12 @@ The final output of the model must strictly follow the JSON Schema format shown
if not self._disable_tools_for_iteration:
tools = self._tool_schemas
tool_choice = "auto"
- response = await self.vlm.get_completion_async(
- messages=messages,
- tools=tools,
- tool_choice=tool_choice,
- )
+ with bind_telemetry_stage("memory_extract"):
+ response = await self.vlm.get_completion_async(
+ messages=messages,
+ tools=tools,
+ tool_choice=tool_choice,
+ )
tracer.info(f"response={response}")
# print(f'response={response}')
# Log cache hit info
diff --git a/openviking/session/memory_deduplicator.py b/openviking/session/memory_deduplicator.py
index 393873149..c57ae8216 100644
--- a/openviking/session/memory_deduplicator.py
+++ b/openviking/session/memory_deduplicator.py
@@ -19,7 +19,7 @@ from openviking.models.embedder.base import EmbedResult, embed_compat
from openviking.prompts import render_prompt
from openviking.server.identity import RequestContext
from openviking.storage import VikingDBManager
-from openviking.telemetry import get_current_telemetry
+from openviking.telemetry import bind_telemetry_stage, get_current_telemetry
from openviking_cli.utils import get_logger
from openviking_cli.utils.config import get_openviking_config
@@ -293,7 +293,8 @@ class MemoryDeduplicator:
],
}
logger.debug("Dedup LLM request summary: %s", request_summary)
- response = await vlm.get_completion_async(prompt)
+ with bind_telemetry_stage("memory_extract"):
+ response = await vlm.get_completion_async(prompt)
logger.debug("Dedup LLM raw response: %s", response)
data = parse_json_from_response(response) or {}
logger.debug("Dedup LLM parsed payload: %s", data)
diff --git a/openviking/session/memory_extractor.py b/openviking/session/memory_extractor.py
index 3c84813ed..fefef0ba7 100644
--- a/openviking/session/memory_extractor.py
+++ b/openviking/session/memory_extractor.py
@@ -18,7 +18,7 @@ from openviking.core.context import Context, ContextType, Vectorize
from openviking.prompts import render_prompt
from openviking.server.identity import RequestContext
from openviking.storage.viking_fs import get_viking_fs
-from openviking.telemetry import get_current_telemetry
+from openviking.telemetry import bind_telemetry_stage, get_current_telemetry
from openviking_cli.exceptions import NotFoundError
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils import get_logger
@@ -312,7 +312,8 @@ class MemoryExtractor:
}
logger.debug("Memory extraction LLM request summary: %s", request_summary)
with telemetry.measure("memory.extract.stage.llm_extract"):
- response = await vlm.get_completion_async(prompt)
+ with bind_telemetry_stage("memory_extract"):
+ response = await vlm.get_completion_async(prompt)
logger.debug("Memory extraction LLM raw response: %s", response)
with telemetry.measure("memory.extract.stage.normalize_candidates"):
data = parse_json_from_response(response) or {}
@@ -590,7 +591,8 @@ class MemoryExtractor:
try:
from openviking_cli.utils.llm import parse_json_from_response
- response = await vlm.get_completion_async(prompt)
+ with bind_telemetry_stage("memory_extract"):
+ response = await vlm.get_completion_async(prompt)
data = parse_json_from_response(response) or {}
if not isinstance(data, dict):
logger.error("Memory merge bundle parse failed: non-dict payload")
@@ -1002,7 +1004,8 @@ class MemoryExtractor:
)
try:
- response = await vlm.get_completion_async(prompt)
+ with bind_telemetry_stage("memory_extract"):
+ response = await vlm.get_completion_async(prompt)
compressed = response.strip()
if len(compressed) <= max_length:
logger.info(
diff --git a/openviking/storage/queuefs/semantic_processor.py b/openviking/storage/queuefs/semantic_processor.py
index 32031b536..dc1437800 100644
--- a/openviking/storage/queuefs/semantic_processor.py
+++ b/openviking/storage/queuefs/semantic_processor.py
@@ -31,7 +31,7 @@ from openviking.storage.queuefs.named_queue import DequeueHandlerBase
from openviking.storage.queuefs.semantic_dag import DagStats, SemanticDagExecutor
from openviking.storage.queuefs.semantic_msg import SemanticMsg
from openviking.storage.viking_fs import get_viking_fs
-from openviking.telemetry import bind_telemetry, resolve_telemetry
+from openviking.telemetry import bind_telemetry, bind_telemetry_stage, resolve_telemetry
from openviking.telemetry.request_wait_tracker import get_request_wait_tracker
from openviking.utils.circuit_breaker import (
CircuitBreaker,
@@ -903,7 +903,8 @@ class SemanticProcessor(DequeueHandlerBase):
},
)
async with llm_sem:
- summary = await vlm.get_completion_async(prompt)
+ with bind_telemetry_stage("resource_summarize"):
+ summary = await vlm.get_completion_async(prompt)
return {"name": file_name, "summary": summary.strip()}
if skeleton_text is None:
logger.info("AST unsupported language, fallback to LLM: %s", file_path)
@@ -916,7 +917,8 @@ class SemanticProcessor(DequeueHandlerBase):
{"file_name": file_name, "content": content, "output_language": output_language},
)
async with llm_sem:
- summary = await vlm.get_completion_async(prompt)
+ with bind_telemetry_stage("resource_summarize"):
+ summary = await vlm.get_completion_async(prompt)
return {"name": file_name, "summary": summary.strip()}
elif file_type == FILE_TYPE_DOCUMENTATION:
@@ -930,7 +932,8 @@ class SemanticProcessor(DequeueHandlerBase):
)
async with llm_sem:
- summary = await vlm.get_completion_async(prompt)
+ with bind_telemetry_stage("resource_summarize"):
+ summary = await vlm.get_completion_async(prompt)
return {"name": file_name, "summary": summary.strip()}
async def _generate_single_file_summary(
@@ -1173,7 +1176,8 @@ class SemanticProcessor(DequeueHandlerBase):
},
)
- overview = await vlm.get_completion_async(prompt)
+ with bind_telemetry_stage("resource_summarize"):
+ overview = await vlm.get_completion_async(prompt)
# Post-process: replace [number] with actual file name
def replace_index(match):
@@ -1267,7 +1271,8 @@ class SemanticProcessor(DequeueHandlerBase):
async def _run_batch(batch_idx: int, prompt: str, batch_index_map: Dict[int, str]) -> None:
try:
async with llm_sem:
- partial = await vlm.get_completion_async(prompt)
+ with bind_telemetry_stage("resource_summarize"):
+ partial = await vlm.get_completion_async(prompt)
partial = re.sub(r"\[(\d+)\]", make_replacer(batch_index_map), partial)
partial_overviews[batch_idx] = partial.strip()
except Exception as e:
@@ -1298,7 +1303,8 @@ class SemanticProcessor(DequeueHandlerBase):
"output_language": output_language,
},
)
- overview = await vlm.get_completion_async(prompt)
+ with bind_telemetry_stage("resource_summarize"):
+ overview = await vlm.get_completion_async(prompt)
return overview.strip()
except Exception as e:
logger.error(
diff --git a/openviking/telemetry/__init__.py b/openviking/telemetry/__init__.py
index c83e1138b..80a9ff2dd 100644
--- a/openviking/telemetry/__init__.py
+++ b/openviking/telemetry/__init__.py
@@ -2,12 +2,17 @@
# SPDX-License-Identifier: AGPL-3.0
"""OpenViking telemetry runtime and operation telemetry helpers."""
-from .context import bind_telemetry, get_current_telemetry
+from . import tracer as tracer_module
+from .context import (
+ bind_telemetry,
+ bind_telemetry_stage,
+ get_current_telemetry,
+ get_current_telemetry_stage,
+)
from .operation import OperationTelemetry, TelemetrySnapshot
from .registry import register_telemetry, resolve_telemetry, unregister_telemetry
from .request import TelemetryRequest, TelemetrySelection, normalize_telemetry_request
from .runtime import get_telemetry_runtime, set_telemetry_runtime
-from . import tracer as tracer_module
from .tracer import tracer
__all__ = [
@@ -16,7 +21,9 @@ __all__ = [
"TelemetrySelection",
"TelemetrySnapshot",
"bind_telemetry",
+ "bind_telemetry_stage",
"get_current_telemetry",
+ "get_current_telemetry_stage",
"get_telemetry_runtime",
"normalize_telemetry_request",
"register_telemetry",
diff --git a/openviking/telemetry/context.py b/openviking/telemetry/context.py
index 35528ee90..291a457fc 100644
--- a/openviking/telemetry/context.py
+++ b/openviking/telemetry/context.py
@@ -14,6 +14,10 @@ _CURRENT_TELEMETRY: contextvars.ContextVar[OperationTelemetry | None] = contextv
"openviking_operation_telemetry",
default=None,
)
+_CURRENT_TELEMETRY_STAGE: contextvars.ContextVar[str | None] = contextvars.ContextVar(
+ "openviking_operation_telemetry_stage",
+ default=None,
+)
def get_current_telemetry() -> OperationTelemetry:
@@ -35,4 +39,29 @@ def bind_telemetry(handle: OperationTelemetry) -> Iterator[OperationTelemetry]:
_CURRENT_TELEMETRY.reset(token)
-__all__ = ["bind_telemetry", "get_current_telemetry"]
+def get_current_telemetry_stage() -> str | None:
+ """Return the currently bound low-cardinality telemetry stage, if any."""
+ stage = _CURRENT_TELEMETRY_STAGE.get()
+ if stage is None:
+ return None
+ normalized = str(stage).strip()
+ return normalized or None
+
+
+@contextmanager
+def bind_telemetry_stage(stage: str | None) -> Iterator[str | None]:
+ """Bind a fixed stage label to the current context for downstream token attribution."""
+ normalized = None if stage is None else str(stage).strip() or None
+ token = _CURRENT_TELEMETRY_STAGE.set(normalized)
+ try:
+ yield normalized
+ finally:
+ _CURRENT_TELEMETRY_STAGE.reset(token)
+
+
+__all__ = [
+ "bind_telemetry",
+ "bind_telemetry_stage",
+ "get_current_telemetry",
+ "get_current_telemetry_stage",
+]
diff --git a/openviking/telemetry/operation.py b/openviking/telemetry/operation.py
index 713aa0ba5..d5fb4d268 100644
--- a/openviking/telemetry/operation.py
+++ b/openviking/telemetry/operation.py
@@ -125,6 +125,27 @@ class TelemetrySummaryBuilder:
key.startswith(needle) for key in gauges
)
+ @classmethod
+ def _build_stage_token_summary(cls, counters: Dict[str, float]) -> Dict[str, Dict[str, Any]]:
+ """Build a low-cardinality stage -> source -> token breakdown from counter keys."""
+ summary: Dict[str, Dict[str, Any]] = {}
+ prefix = "tokens.stages."
+ for key, value in counters.items():
+ if not key.startswith(prefix):
+ continue
+ parts = key.split(".")
+ if len(parts) != 5:
+ continue
+ _, _, stage, source, token_field = parts
+ normalized_value = cls._i(value, 0)
+ if normalized_value <= 0:
+ continue
+ source_payload = summary.setdefault(stage, {}).setdefault(source, {})
+ if source != "llm" and token_field != "total":
+ continue
+ source_payload[token_field] = normalized_value
+ return summary
+
@classmethod
def build(
cls,
@@ -142,6 +163,8 @@ class TelemetrySummaryBuilder:
llm_output_tokens = cls._i(counters.get("tokens.llm.output"), 0)
llm_total_tokens = cls._i(counters.get("tokens.llm.total"), 0)
embedding_total_tokens = cls._i(counters.get("tokens.embedding.total"), 0)
+ rerank_total_tokens = cls._i(counters.get("tokens.rerank.total"), 0)
+ stage_token_summary = cls._build_stage_token_summary(counters)
vector_candidates_scored = cls._i(counters.get("vector.scored"), 0)
vectors_scanned = gauges.get("vector.scanned")
if vectors_scanned is None:
@@ -162,8 +185,11 @@ class TelemetrySummaryBuilder:
"total": llm_total_tokens,
},
"embedding": {"total": embedding_total_tokens},
+ "rerank": {"total": rerank_total_tokens},
},
}
+ if stage_token_summary:
+ summary["tokens"]["stages"] = stage_token_summary
if cls._has_metric_prefix("queue", counters, gauges):
summary["queue"] = {
@@ -338,15 +364,32 @@ class OperationTelemetry:
finally:
self.add_duration(key, (time.perf_counter() - start) * 1000)
- def add_token_usage(self, input_tokens: int, output_tokens: int) -> None:
- self.add_token_usage_by_source("llm", input_tokens, output_tokens)
+ def add_token_usage(
+ self, input_tokens: int, output_tokens: int, *, stage: str | None = None
+ ) -> None:
+ """Record LLM token usage into aggregate and optional stage-specific counters."""
+ self.add_token_usage_by_source("llm", input_tokens, output_tokens, stage=stage)
- def record_token_usage(self, source: str, input_tokens: int, output_tokens: int = 0) -> None:
- self.add_token_usage_by_source(source, input_tokens, output_tokens)
+ def record_token_usage(
+ self,
+ source: str,
+ input_tokens: int,
+ output_tokens: int = 0,
+ *,
+ stage: str | None = None,
+ ) -> None:
+ """Record source-scoped token usage into aggregate and optional stage-specific counters."""
+ self.add_token_usage_by_source(source, input_tokens, output_tokens, stage=stage)
def add_token_usage_by_source(
- self, source: str, input_tokens: int, output_tokens: int = 0
+ self,
+ source: str,
+ input_tokens: int,
+ output_tokens: int = 0,
+ *,
+ stage: str | None = None,
) -> None:
+ """Record token usage for one source and optionally mirror it into a fixed stage bucket."""
if not self.enabled:
return
@@ -360,6 +403,19 @@ class OperationTelemetry:
self.count(f"tokens.{source}.input", normalized_input)
self.count(f"tokens.{source}.output", normalized_output)
self.count(f"tokens.{source}.total", normalized_total)
+ if stage is None:
+ try:
+ from .context import get_current_telemetry_stage
+
+ stage = get_current_telemetry_stage()
+ except Exception:
+ stage = None
+ if stage:
+ normalized_stage = str(stage).strip()
+ if normalized_stage:
+ self.count(f"tokens.stages.{normalized_stage}.{source}.input", normalized_input)
+ self.count(f"tokens.stages.{normalized_stage}.{source}.output", normalized_output)
+ self.count(f"tokens.stages.{normalized_stage}.{source}.total", normalized_total)
def set_error(self, stage: str, code: str, message: str) -> None:
if not self.enabled:
diff --git a/tests/metrics/account/test_context.py b/tests/metrics/account/test_context.py
deleted file mode 100644
index 6dbaf39e1..000000000
--- a/tests/metrics/account/test_context.py
+++ /dev/null
@@ -1,20 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-"""Tests for metrics request-scoped account context propagation."""
-
-from openviking.metrics.account_context import (
- bind_metric_account_context,
- get_metric_account_context,
- reset_metric_account_context,
-)
-
-
-def test_http_account_context_round_trip():
- token = bind_metric_account_context(account_id="acct-1")
- try:
- assert get_metric_account_context().http_account_id == "acct-1"
- finally:
- reset_metric_account_context(token)
-
- assert get_metric_account_context().http_account_id is None
diff --git a/tests/metrics/account/test_policy.py b/tests/metrics/account/test_policy.py
deleted file mode 100644
index 6154ca8c7..000000000
--- a/tests/metrics/account/test_policy.py
+++ /dev/null
@@ -1,73 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-"""Tests for account-dimension whitelist and overflow policy behavior."""
-
-from openviking.metrics.account_dimension import (
- OVERFLOW_ACCOUNT_ID,
- UNKNOWN_ACCOUNT_ID,
- MetricAccountDimensionPolicy,
-)
-
-
-def test_account_dimension_disabled_still_emits_unknown():
- policy = MetricAccountDimensionPolicy(
- enabled=False,
- metric_allowlist={"openviking_http_requests_total"},
- max_active_accounts=2,
- )
-
- assert (
- policy.resolve(metric_name="openviking_http_requests_total", account_id="acct-1")
- == UNKNOWN_ACCOUNT_ID
- )
-
-
-def test_account_dimension_non_allowlisted_metric_emits_unknown():
- policy = MetricAccountDimensionPolicy(
- enabled=True,
- metric_allowlist={"openviking_http_requests_total"},
- max_active_accounts=2,
- )
-
- assert (
- policy.resolve(metric_name="openviking_task_pending", account_id="acct-1")
- == UNKNOWN_ACCOUNT_ID
- )
-
-
-def test_account_dimension_overflow_after_limit():
- policy = MetricAccountDimensionPolicy(
- enabled=True,
- metric_allowlist={"openviking_http_requests_total"},
- max_active_accounts=1,
- )
-
- assert (
- policy.resolve(metric_name="openviking_http_requests_total", account_id="acct-1")
- == "acct-1"
- )
- assert (
- policy.resolve(metric_name="openviking_http_requests_total", account_id="acct-2")
- == OVERFLOW_ACCOUNT_ID
- )
-
-
-def test_account_dimension_allowlist_supports_prefix_wildcard():
- policy = MetricAccountDimensionPolicy(
- enabled=True,
- metric_allowlist={"openviking_rerank_*"},
- max_active_accounts=10,
- )
-
- assert (
- policy.resolve(metric_name="openviking_rerank_calls_total", account_id="acct-1") == "acct-1"
- )
- assert (
- policy.resolve(metric_name="openviking_rerank_tokens_total", account_id="acct-1")
- == "acct-1"
- )
- assert (
- policy.resolve(metric_name="openviking_vlm_calls_total", account_id="acct-1")
- == UNKNOWN_ACCOUNT_ID
- )
diff --git a/tests/metrics/collectors/test_category_strategies.py b/tests/metrics/collectors/test_category_strategies.py
deleted file mode 100644
index 7b73f30ef..000000000
--- a/tests/metrics/collectors/test_category_strategies.py
+++ /dev/null
@@ -1,119 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-import pytest
-
-from openviking.metrics.collectors.base import (
- CollectorConfig,
- DomainStatsMetricCollector,
- ProbeMetricCollector,
- StateMetricCollector,
-)
-from openviking.metrics.core.registry import MetricRegistry
-
-
-class _FailingProbeCollector(ProbeMetricCollector):
- config = CollectorConfig()
-
- def __init__(self) -> None:
- self.stale_called = False
-
- def read_metric_input(self):
- raise RuntimeError("probe read failed")
-
- def collect_hook(self, registry, metric_input) -> None:
- raise AssertionError("collect_hook must not be called on read failure")
-
- def collect_stale_hook(self, registry, error: Exception) -> None:
- self.stale_called = True
-
-
-class _FailingStateCollector(StateMetricCollector):
- config = CollectorConfig()
-
- def read_metric_input(self):
- raise RuntimeError("state read failed")
-
- def collect_hook(self, registry, metric_input) -> None:
- raise AssertionError("collect_hook must not be called on read failure")
-
-
-class _StaleOnErrorStateCollector(StateMetricCollector):
- config = CollectorConfig()
- STALE_ON_ERROR = True
-
- def __init__(self) -> None:
- self.stale_called = False
-
- def read_metric_input(self):
- raise RuntimeError("state read failed")
-
- def collect_hook(self, registry, metric_input) -> None:
- raise AssertionError("collect_hook must not be called on read failure")
-
- def collect_stale_hook(self, registry, error: Exception) -> None:
- self.stale_called = True
-
-
-class _DeltaDomainStatsCollector(DomainStatsMetricCollector):
- config = CollectorConfig()
-
- def read_metric_input(self):
- return None
-
- def collect_hook(self, registry, metric_input) -> None:
- self.inc_counter_from_cumulative(
- registry=registry,
- metric_name="openviking_test_cumulative_total",
- key=("k",),
- current_value=10,
- )
- self.inc_counter_from_cumulative(
- registry=registry,
- metric_name="openviking_test_cumulative_total",
- key=("k",),
- current_value=15,
- )
- self.inc_counter_from_cumulative(
- registry=registry,
- metric_name="openviking_test_cumulative_total",
- key=("k",),
- current_value=3,
- )
-
-
-def test_probe_default_error_strategy_does_not_raise_and_calls_stale_hook():
- registry = MetricRegistry()
- collector = _FailingProbeCollector()
-
- collector.collect(registry)
-
- assert collector.stale_called is True
-
-
-def test_state_default_error_strategy_raises():
- registry = MetricRegistry()
- collector = _FailingStateCollector()
-
- with pytest.raises(RuntimeError, match="state read failed"):
- collector.collect(registry)
-
-
-def test_state_stale_on_error_strategy_calls_stale_hook_and_does_not_raise():
- registry = MetricRegistry()
- collector = _StaleOnErrorStateCollector()
-
- collector.collect(registry)
-
- assert collector.stale_called is True
-
-
-def test_domain_stats_delta_helper_applies_non_negative_deltas_and_handles_resets():
- registry = MetricRegistry()
- collector = _DeltaDomainStatsCollector()
-
- collector.collect(registry)
-
- counters = dict(registry.iter_counters())
- series = dict(counters["openviking_test_cumulative_total"])
- assert series[()] == 10 + 5 + 3
diff --git a/tests/metrics/collectors/test_collector_contracts.py b/tests/metrics/collectors/test_collector_contracts.py
new file mode 100644
index 000000000..f0794c3b3
--- /dev/null
+++ b/tests/metrics/collectors/test_collector_contracts.py
@@ -0,0 +1,455 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+
+import pytest
+
+from openviking.metrics.collectors.async_system_probe import AsyncSystemProbeCollector
+from openviking.metrics.collectors.base import (
+ CollectorConfig,
+ DomainStatsMetricCollector,
+ ProbeMetricCollector,
+ StateMetricCollector,
+)
+from openviking.metrics.collectors.encryption_probe import EncryptionProbeCollector
+from openviking.metrics.collectors.model_provider_probe import ModelProviderProbeCollector
+from openviking.metrics.collectors.retrieval_backend_probe import RetrievalBackendProbeCollector
+from openviking.metrics.collectors.service_probe import ServiceProbeCollector
+from openviking.metrics.collectors.storage_probe import StorageProbeCollector
+from openviking.metrics.core.base import ReadEnvelope
+from openviking.metrics.core.registry import MetricRegistry
+
+
+class _FailingProbeCollector(ProbeMetricCollector):
+ config = CollectorConfig()
+
+ def __init__(self) -> None:
+ self.stale_called = False
+
+ def read_metric_input(self):
+ raise RuntimeError("probe read failed")
+
+ def collect_hook(self, registry, metric_input) -> None:
+ raise AssertionError("collect_hook must not be called on read failure")
+
+ def collect_stale_hook(self, registry, error: Exception) -> None:
+ self.stale_called = True
+
+
+class _FailingStateCollector(StateMetricCollector):
+ config = CollectorConfig()
+
+ def read_metric_input(self):
+ raise RuntimeError("state read failed")
+
+ def collect_hook(self, registry, metric_input) -> None:
+ raise AssertionError("collect_hook must not be called on read failure")
+
+
+class _StaleOnErrorStateCollector(StateMetricCollector):
+ config = CollectorConfig()
+ STALE_ON_ERROR = True
+
+ def __init__(self) -> None:
+ self.stale_called = False
+
+ def read_metric_input(self):
+ raise RuntimeError("state read failed")
+
+ def collect_hook(self, registry, metric_input) -> None:
+ raise AssertionError("collect_hook must not be called on read failure")
+
+ def collect_stale_hook(self, registry, error: Exception) -> None:
+ self.stale_called = True
+
+
+class _DeltaDomainStatsCollector(DomainStatsMetricCollector):
+ config = CollectorConfig()
+
+ def read_metric_input(self):
+ return None
+
+ def collect_hook(self, registry, metric_input) -> None:
+ self.inc_counter_from_cumulative(
+ registry=registry,
+ metric_name="openviking_test_cumulative_total",
+ key=("k",),
+ current_value=10,
+ )
+ self.inc_counter_from_cumulative(
+ registry=registry,
+ metric_name="openviking_test_cumulative_total",
+ key=("k",),
+ current_value=15,
+ )
+ self.inc_counter_from_cumulative(
+ registry=registry,
+ metric_name="openviking_test_cumulative_total",
+ key=("k",),
+ current_value=3,
+ )
+
+
+@dataclass
+class _ProbeDataSource:
+ value: object | None = None
+ ok: bool = True
+ raises: bool = False
+
+ def read_probe_state(self):
+ if self.raises:
+ raise RuntimeError("probe read failed")
+ return ReadEnvelope(ok=self.ok, value=self.value, error_type="probe", error_message="fail")
+
+
+class _DummyStateCollector(StateMetricCollector):
+ config = CollectorConfig()
+
+ def __init__(self) -> None:
+ self.seen = []
+
+ def read_metric_input(self):
+ return {"value": 3}
+
+ def collect_hook(self, registry, metric_input) -> None:
+ self.seen.append(("state", metric_input["value"]))
+
+
+class _DummyProbeCollector(ProbeMetricCollector):
+ config = CollectorConfig()
+
+ def __init__(self) -> None:
+ self.seen = []
+
+ def read_metric_input(self):
+ return {"ok": True}
+
+ def collect_hook(self, registry, metric_input) -> None:
+ self.seen.append(("probe", metric_input["ok"]))
+
+
+class _DummyDomainCollector(DomainStatsMetricCollector):
+ config = CollectorConfig()
+
+ def __init__(self) -> None:
+ self.seen = []
+
+ def read_metric_input(self):
+ return {"total": 7}
+
+ def collect_hook(self, registry, metric_input) -> None:
+ self.seen.append(("domain", metric_input["total"]))
+
+
+class _DummyFailingStateCollector(StateMetricCollector):
+ config = CollectorConfig()
+
+ def __init__(self) -> None:
+ self.error_seen = None
+
+ def read_metric_input(self):
+ raise RuntimeError("boom")
+
+ def collect_hook(self, registry, metric_input) -> None:
+ raise AssertionError("should not be called")
+
+ def collect_error_hook(self, registry, error: Exception) -> None:
+ self.error_seen = str(error)
+
+
+def test_probe_default_error_strategy_does_not_raise_and_calls_stale_hook():
+ registry = MetricRegistry()
+ collector = _FailingProbeCollector()
+
+ collector.collect(registry)
+
+ assert collector.stale_called is True
+
+
+def test_state_default_error_strategy_raises():
+ registry = MetricRegistry()
+ collector = _FailingStateCollector()
+
+ with pytest.raises(RuntimeError, match="state read failed"):
+ collector.collect(registry)
+
+
+def test_state_stale_on_error_strategy_calls_stale_hook_and_does_not_raise():
+ registry = MetricRegistry()
+ collector = _StaleOnErrorStateCollector()
+
+ collector.collect(registry)
+
+ assert collector.stale_called is True
+
+
+def test_domain_stats_delta_helper_applies_non_negative_deltas_and_handles_resets():
+ registry = MetricRegistry()
+ collector = _DeltaDomainStatsCollector()
+
+ collector.collect(registry)
+
+ counters = dict(registry.iter_counters())
+ series = dict(counters["openviking_test_cumulative_total"])
+ assert series[()] == 18
+
+
+def test_service_probe_collector_emits_valid_on_success_and_invalid_on_failure(
+ registry, render_prometheus
+):
+ ds = _ProbeDataSource(
+ value={"service_readiness": True, "api_key_manager_readiness": False}, ok=True
+ )
+ c = ServiceProbeCollector(data_source=ds)
+ c.collect(registry)
+ text = render_prometheus(registry)
+ assert 'openviking_service_readiness{valid="1"} 1.0' in text
+ assert 'openviking_api_key_manager_readiness{valid="1"} 0.0' in text
+
+ ds.ok = False
+ c.collect(registry)
+ text2 = render_prometheus(registry)
+ assert 'openviking_service_readiness{valid="0"} 0.0' in text2
+ assert 'openviking_api_key_manager_readiness{valid="0"} 0.0' in text2
+
+
+def test_storage_probe_collector_preserves_last_probe_set_and_marks_invalid(
+ registry, render_prometheus
+):
+ ds = _ProbeDataSource(value={"agfs": True, "other": False}, ok=True)
+ c = StorageProbeCollector(data_source=ds)
+ c.collect(registry)
+ text = render_prometheus(registry)
+ assert 'openviking_storage_readiness{probe="agfs",valid="1"} 1.0' in text
+ assert 'openviking_storage_readiness{probe="other",valid="1"} 0.0' in text
+
+ ds.raises = True
+ c.collect(registry)
+ text2 = render_prometheus(registry)
+ assert 'openviking_storage_readiness{probe="agfs",valid="0"} 0.0' in text2
+ assert 'openviking_storage_readiness{probe="other",valid="0"} 0.0' in text2
+
+
+def test_retrieval_backend_probe_collector_preserves_last_probe_set_and_marks_invalid(
+ registry, render_prometheus
+):
+ ds = _ProbeDataSource(value={"vikingdb": True}, ok=True)
+ c = RetrievalBackendProbeCollector(data_source=ds)
+ c.collect(registry)
+ text = render_prometheus(registry)
+ assert 'openviking_retrieval_backend_readiness{probe="vikingdb",valid="1"} 1.0' in text
+
+ ds.ok = False
+ c.collect(registry)
+ text2 = render_prometheus(registry)
+ assert 'openviking_retrieval_backend_readiness{probe="vikingdb",valid="0"} 0.0' in text2
+
+
+def test_encryption_probe_collector_uses_last_provider_on_failure(registry, render_prometheus):
+ ds = _ProbeDataSource(value=(True, "volcengine"), ok=True)
+ c = EncryptionProbeCollector(data_source=ds)
+ c.collect(registry)
+ text = render_prometheus(registry)
+ assert 'openviking_encryption_component_health{valid="1"} 1.0' in text
+ assert 'openviking_encryption_root_key_ready{valid="1"} 1.0' in text
+ assert 'openviking_encryption_kms_provider_ready{provider="volcengine",valid="1"} 1.0' in text
+
+ ds.raises = True
+ c.collect(registry)
+ text2 = render_prometheus(registry)
+ assert 'openviking_encryption_component_health{valid="0"} 0.0' in text2
+ assert 'openviking_encryption_root_key_ready{valid="0"} 0.0' in text2
+ assert 'openviking_encryption_kms_provider_ready{provider="volcengine",valid="0"} 0.0' in text2
+
+
+def test_model_provider_probe_collector_uses_last_provider_on_failure(registry, render_prometheus):
+ ds = _ProbeDataSource(value={"provider": ("volcengine", True)}, ok=True)
+ c = ModelProviderProbeCollector(data_source=ds)
+ c.collect(registry)
+ text = render_prometheus(registry)
+ assert 'openviking_model_provider_readiness{provider="volcengine",valid="1"} 1.0' in text
+
+ ds.ok = False
+ c.collect(registry)
+ text2 = render_prometheus(registry)
+ assert 'openviking_model_provider_readiness{provider="volcengine",valid="0"} 0.0' in text2
+
+
+def test_async_system_probe_collector_marks_invalid_on_failure(registry, render_prometheus):
+ ds = _ProbeDataSource(value={"queue": True}, ok=True)
+ c = AsyncSystemProbeCollector(data_source=ds)
+ c.collect(registry)
+ text = render_prometheus(registry)
+ assert 'openviking_async_system_readiness{probe="queue",valid="1"} 1.0' in text
+
+ ds.raises = True
+ c.collect(registry)
+ text2 = render_prometheus(registry)
+ assert 'openviking_async_system_readiness{probe="queue",valid="0"} 0.0' in text2
+
+
+def test_required_core_modules_exist():
+ import openviking.metrics.core.base as core_base
+ import openviking.metrics.core.refresh as core_refresh
+ import openviking.metrics.core.registry as core_registry
+ import openviking.metrics.core.runtime as core_runtime
+ import openviking.metrics.core.types as core_types
+
+ assert hasattr(core_base, "MetricDataSource")
+ assert hasattr(core_base, "MetricCollector")
+ assert hasattr(core_base, "MetricExporter")
+ assert hasattr(core_refresh, "RefreshGate")
+ assert hasattr(core_registry, "MetricRegistry")
+ assert hasattr(core_runtime, "EventCollectorRouter")
+ assert core_types is not None
+
+
+def test_required_architecture_types_exist():
+ import openviking.metrics.core.base as base_module
+
+ assert hasattr(base_module, "MetricDataSource")
+ assert hasattr(base_module, "MetricCollector")
+ assert hasattr(base_module, "MetricExporter")
+
+
+def test_required_intermediate_types_exist():
+ import openviking.metrics.collectors.base as collector_base_module
+ import openviking.metrics.datasources as ds_module
+ import openviking.metrics.datasources.base as ds_base_module
+
+ assert hasattr(ds_base_module, "EventMetricDataSource")
+ assert hasattr(ds_base_module, "StateMetricDataSource")
+ assert hasattr(ds_base_module, "DomainStatsMetricDataSource")
+ assert hasattr(ds_base_module, "ProbeMetricDataSource")
+ assert hasattr(ds_module, "CacheEventDataSource")
+ assert hasattr(ds_module, "TelemetryBridgeEventDataSource")
+
+ assert hasattr(collector_base_module, "EventMetricCollector")
+ assert hasattr(collector_base_module, "StateMetricCollector")
+ assert hasattr(collector_base_module, "DomainStatsMetricCollector")
+ assert hasattr(collector_base_module, "ProbeMetricCollector")
+ assert hasattr(collector_base_module, "Refreshable")
+ assert not hasattr(collector_base_module, "AbstractMetricCollector")
+
+
+def test_prometheus_exporter_inherits_base_metric_exporter():
+ import openviking.metrics.exporters as exporters_module
+ from openviking.metrics.core.base import MetricExporter
+ from openviking.metrics.exporters.prometheus import PrometheusExporter
+
+ assert issubclass(PrometheusExporter, MetricExporter)
+ assert not hasattr(exporters_module, "AbstractMetricExporter")
+
+
+def test_concrete_datasources_and_collectors_follow_doc_inheritance():
+ from openviking.metrics.collectors.base import (
+ ProbeMetricCollector,
+ Refreshable,
+ StateMetricCollector,
+ )
+ from openviking.metrics.collectors.lock import LockCollector
+ from openviking.metrics.collectors.queue import QueueCollector
+ from openviking.metrics.collectors.service_probe import ServiceProbeCollector
+ from openviking.metrics.collectors.vikingdb import VikingDBCollector
+ from openviking.metrics.datasources.base import (
+ DomainStatsMetricDataSource,
+ ProbeMetricDataSource,
+ StateMetricDataSource,
+ )
+ from openviking.metrics.datasources.observer_state import (
+ LockStateDataSource,
+ ObserverStateDataSource,
+ VikingDBStateDataSource,
+ )
+ from openviking.metrics.datasources.probes import ServiceProbeDataSource
+ from openviking.metrics.datasources.queue import QueuePipelineStateDataSource
+
+ assert issubclass(QueuePipelineStateDataSource, StateMetricDataSource)
+ assert issubclass(ObserverStateDataSource, DomainStatsMetricDataSource)
+ assert issubclass(LockStateDataSource, StateMetricDataSource)
+ assert issubclass(VikingDBStateDataSource, StateMetricDataSource)
+ assert issubclass(ServiceProbeDataSource, ProbeMetricDataSource)
+
+ assert issubclass(QueueCollector, StateMetricCollector)
+ assert issubclass(LockCollector, StateMetricCollector)
+ assert issubclass(VikingDBCollector, StateMetricCollector)
+ assert issubclass(ServiceProbeCollector, ProbeMetricCollector)
+ assert issubclass(QueueCollector, Refreshable)
+ assert issubclass(LockCollector, Refreshable)
+ assert issubclass(VikingDBCollector, Refreshable)
+ assert issubclass(ServiceProbeCollector, Refreshable)
+
+
+def test_metrics_code_has_no_snapshot_api():
+ root = Path(__file__).resolve().parents[3] / "openviking" / "metrics"
+ for path in root.rglob("*.py"):
+ text = path.read_text(encoding="utf-8")
+ assert ".snapshot(" not in text, f"snapshot api still found in {path}"
+
+
+def test_metric_collector_supports_collect_and_receive():
+ from openviking.metrics.core.base import MetricCollector
+
+ class _DummyCollector(MetricCollector):
+ @classmethod
+ def kind(cls) -> str:
+ return "dummy"
+
+ collector = _DummyCollector()
+ assert collector.collector_name() == "_DummyCollector"
+ assert collector.collect(None) is None
+ assert collector.receive("event", {}, None) is None
+
+
+def test_runtime_code_has_no_prometheus_observer_references():
+ root = Path(__file__).resolve().parents[3] / "openviking"
+ banned = (
+ "PrometheusObserver",
+ "get_prometheus_observer",
+ "set_prometheus_observer",
+ "prometheus_observer.py",
+ )
+ for path in root.rglob("*.py"):
+ text = path.read_text(encoding="utf-8")
+ for needle in banned:
+ assert needle not in text, f"{needle} still found in {path}"
+
+
+def test_state_metric_collector_collect_uses_template_hooks():
+ registry = MetricRegistry()
+ collector = _DummyStateCollector()
+
+ collector.collect(registry)
+
+ assert collector.seen == [("state", 3)]
+
+
+def test_probe_metric_collector_collect_uses_template_hooks():
+ registry = MetricRegistry()
+ collector = _DummyProbeCollector()
+
+ collector.collect(registry)
+
+ assert collector.seen == [("probe", True)]
+
+
+def test_domain_stats_metric_collector_collect_uses_template_hooks():
+ registry = MetricRegistry()
+ collector = _DummyDomainCollector()
+
+ collector.collect(registry)
+
+ assert collector.seen == [("domain", 7)]
+
+
+def test_state_metric_collector_collect_error_hook_can_handle_read_failures():
+ registry = MetricRegistry()
+ collector = _DummyFailingStateCollector()
+
+ collector.collect(registry)
+
+ assert collector.error_seen == "boom"
diff --git a/tests/metrics/collectors/test_domain_stats.py b/tests/metrics/collectors/test_domain_stats.py
deleted file mode 100644
index 960feb539..000000000
--- a/tests/metrics/collectors/test_domain_stats.py
+++ /dev/null
@@ -1,127 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-
-def test_observer_state_collector_valid_and_failure_keeps_last_values(registry, render_prometheus):
- from openviking.metrics.collectors.observer_state import ObserverStateCollector
-
- class S:
- def __init__(self, ok: bool, err: bool):
- self.is_healthy = ok
- self.has_errors = err
-
- class DS:
- def __init__(self):
- self.fail = False
-
- def read_component_states(self):
- if self.fail:
- raise RuntimeError("boom")
- return {"a": S(True, False), "b": S(False, True), "c": S(True, True)}
-
- ds = DS()
- c = ObserverStateCollector(data_source=ds)
- c.collect(registry)
- text = render_prometheus(registry)
- assert 'openviking_observer_components_total{valid="1"} 3.0' in text
- assert 'openviking_observer_components_unhealthy{valid="1"} 1.0' in text
- assert 'openviking_observer_components_with_errors{valid="1"} 2.0' in text
-
- ds.fail = True
- c.collect(registry)
- text2 = render_prometheus(registry)
- assert 'openviking_observer_components_total{valid="0"} 3.0' in text2
- assert 'openviking_observer_components_unhealthy{valid="0"} 1.0' in text2
- assert 'openviking_observer_components_with_errors{valid="0"} 2.0' in text2
-
-
-def test_model_usage_collector_delta_and_available_gauge(registry, render_prometheus):
- from openviking.metrics.collectors.model_usage import ModelUsageCollector
-
- class DS:
- def __init__(self):
- self.data = {
- "vlm": {
- "available": True,
- "usage_by_model": {
- "m1": {
- "usage_by_provider": {
- "p1": {
- "prompt_tokens": 2,
- "completion_tokens": 3,
- "total_tokens": 5,
- "call_count": 1,
- }
- }
- }
- },
- },
- "embedding": {
- "available": False,
- "usage_by_model": {},
- },
- "rerank": {
- "available": False,
- "usage_by_model": {},
- },
- }
-
- def read_model_usage(self):
- return self.data
-
- ds = DS()
- c = ModelUsageCollector(data_source=ds)
- c.collect(registry)
- text = render_prometheus(registry)
- assert 'openviking_model_usage_available{model_type="vlm",valid="1"} 1.0' in text
- assert 'openviking_model_usage_available{model_type="embedding",valid="1"} 0.0' in text
- assert 'openviking_model_usage_available{model_type="rerank",valid="1"} 0.0' in text
- assert "openviking_model_usage_valid" not in text
- assert 'openviking_model_calls_total{model_name="m1",model_type="vlm",provider="p1"} 1' in text
- assert (
- 'openviking_model_tokens_total{model_name="m1",model_type="vlm",provider="p1",token_type="total"} 5'
- in text
- )
-
- ds.data["vlm"]["usage_by_model"]["m1"]["usage_by_provider"]["p1"]["call_count"] = 2
- ds.data["vlm"]["usage_by_model"]["m1"]["usage_by_provider"]["p1"]["total_tokens"] = 7
- ds.data["vlm"]["usage_by_model"]["m1"]["usage_by_provider"]["p1"]["prompt_tokens"] = 3
- ds.data["vlm"]["usage_by_model"]["m1"]["usage_by_provider"]["p1"]["completion_tokens"] = 4
- c.collect(registry)
- text2 = render_prometheus(registry)
- assert 'openviking_model_calls_total{model_name="m1",model_type="vlm",provider="p1"} 2' in text2
- assert (
- 'openviking_model_tokens_total{model_name="m1",model_type="vlm",provider="p1",token_type="total"} 7'
- in text2
- )
-
-
-def test_model_usage_collector_failure_reuses_last_available_state_with_valid_zero(
- registry, render_prometheus
-):
- from openviking.metrics.collectors.model_usage import ModelUsageCollector
-
- class DS:
- def __init__(self):
- self.fail = False
-
- def read_model_usage(self):
- if self.fail:
- raise RuntimeError("boom")
- return {
- "vlm": {"available": True, "usage_by_model": {}},
- "embedding": {"available": False, "usage_by_model": {}},
- "rerank": {"available": False, "usage_by_model": {}},
- }
-
- ds = DS()
- collector = ModelUsageCollector(data_source=ds)
-
- collector.collect(registry)
- ds.fail = True
- collector.collect(registry)
-
- text = render_prometheus(registry)
- assert 'openviking_model_usage_available{model_type="vlm",valid="0"} 1.0' in text
- assert 'openviking_model_usage_available{model_type="embedding",valid="0"} 0.0' in text
- assert 'openviking_model_usage_available{model_type="rerank",valid="0"} 0.0' in text
diff --git a/tests/metrics/collectors/test_event_collectors.py b/tests/metrics/collectors/test_event_collectors.py
new file mode 100644
index 000000000..0a7789c2e
--- /dev/null
+++ b/tests/metrics/collectors/test_event_collectors.py
@@ -0,0 +1,273 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+from __future__ import annotations
+
+import re
+
+import openviking.metrics.global_api as global_api
+from openviking.metrics.collectors.base import EventMetricCollector
+from openviking.metrics.collectors.cache import CacheCollector
+from openviking.metrics.collectors.embedding import EmbeddingCollector
+from openviking.metrics.collectors.rerank import RerankCollector
+from openviking.metrics.collectors.session import SessionCollector
+from openviking.metrics.collectors.telemetry_bridge import TelemetryBridgeCollector
+
+
+class _DummyEventCollector(EventMetricCollector):
+ SUPPORTED_EVENTS = frozenset({"demo.hit"})
+
+ def __init__(self) -> None:
+ self.seen: list[tuple[str, str]] = []
+
+ def receive_hook(self, event_name: str, payload: dict, registry) -> None:
+ self.seen.append(
+ (
+ str(event_name),
+ str(payload["value"]),
+ registry.collector_name() if hasattr(registry, "collector_name") else "registry",
+ )
+ )
+
+
+def test_event_metric_collector_uses_supported_events_and_receive_hook(registry):
+ collector = _DummyEventCollector()
+
+ collector.receive("demo.hit", {"value": "ok"}, registry)
+ collector.receive("demo.unknown", {"value": "skip"}, registry)
+
+ assert collector.SUPPORTED_EVENTS == frozenset({"demo.hit"})
+ assert collector.seen == [("demo.hit", "ok", "registry")]
+
+
+def test_cache_collector_uses_supported_events_and_receive_hook_routing(
+ registry, render_prometheus
+):
+ collector = CacheCollector()
+
+ collector.receive("cache.hit", {"level": "L0"}, registry)
+ collector.receive("cache.miss", {"level": "L1"}, registry)
+
+ text = render_prometheus(registry)
+
+ assert collector.SUPPORTED_EVENTS == frozenset({"cache.hit", "cache.miss"})
+ assert 'openviking_cache_hits_total{level="L0"} 1' in text
+ assert 'openviking_cache_misses_total{level="L1"} 1' in text
+
+
+def test_session_collector_records_lifecycle_and_contexts_and_archive(registry, render_prometheus):
+ c = SessionCollector()
+ c.receive("session.lifecycle", {"action": "create", "status": "ok"}, registry)
+ c.receive("session.contexts_used", {"action": "create", "delta": 2}, registry)
+ c.receive("session.archive", {"status": "ok"}, registry)
+
+ text = render_prometheus(registry)
+ assert (
+ 'openviking_session_lifecycle_total{account_id="__unknown__",action="create",status="ok"} 1'
+ in text
+ )
+ assert (
+ 'openviking_session_contexts_used_total{account_id="__unknown__",action="create"} 2' in text
+ )
+ assert 'openviking_session_archive_total{account_id="__unknown__",status="ok"} 1' in text
+
+
+def test_session_collector_ignores_malformed_payloads_instead_of_raising(
+ registry, render_prometheus
+):
+ c = SessionCollector()
+
+ c.receive("session.lifecycle", "not-a-dict", registry)
+ c.receive("session.lifecycle", {"action": "create"}, registry)
+ c.receive("session.contexts_used", {"action": "create"}, registry)
+ c.receive("session.archive", {}, registry)
+
+ text = render_prometheus(registry)
+ assert "openviking_session_lifecycle_total" not in text
+ assert "openviking_session_contexts_used_total" not in text
+ assert "openviking_session_archive_total" not in text
+
+
+def test_rerank_collector_maps_calls_duration_and_tokens():
+ from openviking.metrics.core.registry import MetricRegistry
+ from openviking.metrics.exporters.prometheus import PrometheusExporter
+
+ registry = MetricRegistry()
+ RerankCollector().receive(
+ "rerank.call",
+ {
+ "provider": "cohere",
+ "model_name": "rerank-v3.5",
+ "duration_seconds": 0.3,
+ "prompt_tokens": 9,
+ "completion_tokens": 0,
+ },
+ registry,
+ )
+ text = PrometheusExporter(registry=registry).render()
+
+ assert re.search(
+ r'openviking_rerank_calls_total\{(?=[^}]*model_name="rerank-v3.5")(?=[^}]*provider="cohere")[^}]*\} 1(?:\.0)?',
+ text,
+ )
+ assert re.search(
+ r'openviking_rerank_call_duration_seconds_count\{(?=[^}]*model_name="rerank-v3.5")(?=[^}]*provider="cohere")[^}]*\} 1(?:\.0)?',
+ text,
+ )
+ assert re.search(
+ r'openviking_rerank_tokens_input_total\{(?=[^}]*model_name="rerank-v3.5")(?=[^}]*provider="cohere")[^}]*\} 9(?:\.0)?',
+ text,
+ )
+ assert re.search(
+ r'openviking_rerank_tokens_total\{(?=[^}]*model_name="rerank-v3.5")(?=[^}]*provider="cohere")[^}]*\} 9(?:\.0)?',
+ text,
+ )
+
+
+def test_telemetry_bridge_collector_records_basic_operation_metrics(registry, render_prometheus):
+ c = TelemetryBridgeCollector()
+ c.receive(
+ "telemetry.summary",
+ {
+ "summary": {
+ "operation": "resource.process",
+ "status": "ok",
+ "duration_ms": 250.0,
+ "tokens": {
+ "total": 10,
+ "llm": {"input": 3, "output": 2},
+ "embedding": {"total": 5},
+ "rerank": {"total": 4},
+ "stages": {
+ "embed_query": {"embedding": {"total": 5}},
+ "rerank": {"rerank": {"total": 4}},
+ "vlm": {"llm": {"input": 3, "output": 2, "total": 5}},
+ },
+ },
+ }
+ },
+ registry,
+ )
+
+ text = render_prometheus(registry)
+ assert (
+ 'openviking_operation_requests_total{account_id="__unknown__",operation="resource.process",status="ok"} 1'
+ in text
+ )
+ assert (
+ 'openviking_operation_tokens_total{account_id="__unknown__",operation="resource.process",stage="vlm",token_type="llm_input"} 3'
+ in text
+ )
+ assert (
+ 'openviking_operation_tokens_total{account_id="__unknown__",operation="resource.process",stage="vlm",token_type="llm_output"} 2'
+ in text
+ )
+ assert (
+ 'openviking_operation_tokens_total{account_id="__unknown__",operation="resource.process",stage="embed_query",token_type="embedding"} 5'
+ in text
+ )
+ assert (
+ 'openviking_operation_tokens_total{account_id="__unknown__",operation="resource.process",stage="rerank",token_type="rerank"} 4'
+ in text
+ )
+
+
+def test_telemetry_bridge_collector_ignores_malformed_payloads_instead_of_raising(
+ registry, render_prometheus
+):
+ c = TelemetryBridgeCollector()
+
+ c.receive("telemetry.summary", {}, registry)
+ c.receive("telemetry.summary", {"summary": "not-a-mapping"}, registry)
+
+ text = render_prometheus(registry)
+ assert "openviking_operation_requests_total" not in text
+
+
+def test_http_collector_importable() -> None:
+ from openviking.metrics.collectors.http import HTTPCollector
+
+ assert HTTPCollector is not None
+
+
+def test_global_api_no_longer_exports_metrics_enabled_helper() -> None:
+ """Avoid redundant exports: metrics enablement is read via direct config access."""
+ assert not hasattr(global_api, "is_metrics_enabled_from_server_config")
+
+
+def test_embedding_collector_maps_call_metrics_and_tokens(registry, render_prometheus):
+ """`embedding.call` must produce calls/duration/tokens metrics keyed by provider+model."""
+ EmbeddingCollector().receive(
+ "embedding.call",
+ {
+ "provider": "openai",
+ "model_name": "text-embedding-3-large",
+ "duration_seconds": 0.12,
+ "prompt_tokens": 3,
+ "completion_tokens": 2,
+ },
+ registry,
+ )
+ text = render_prometheus(registry)
+
+ # Account dimension is supported for embedding families; default runtime resolves to __unknown__.
+ assert re.search(
+ r'openviking_embedding_calls_total\{(?=[^}]*account_id="__unknown__")(?=[^}]*model_name="text-embedding-3-large")(?=[^}]*provider="openai")[^}]*\} 1(?:\.0)?',
+ text,
+ )
+ assert re.search(
+ r'openviking_embedding_call_duration_seconds_count\{(?=[^}]*account_id="__unknown__")(?=[^}]*model_name="text-embedding-3-large")(?=[^}]*provider="openai")[^}]*\} 1(?:\.0)?',
+ text,
+ )
+ assert re.search(
+ r'openviking_embedding_tokens_input_total\{(?=[^}]*account_id="__unknown__")(?=[^}]*model_name="text-embedding-3-large")(?=[^}]*provider="openai")[^}]*\} 3(?:\.0)?',
+ text,
+ )
+ assert re.search(
+ r'openviking_embedding_tokens_output_total\{(?=[^}]*account_id="__unknown__")(?=[^}]*model_name="text-embedding-3-large")(?=[^}]*provider="openai")[^}]*\} 2(?:\.0)?',
+ text,
+ )
+ assert re.search(
+ r'openviking_embedding_tokens_total\{(?=[^}]*account_id="__unknown__")(?=[^}]*model_name="text-embedding-3-large")(?=[^}]*provider="openai")[^}]*\} 5(?:\.0)?',
+ text,
+ )
+
+
+def test_embedding_collector_records_success_volume_and_latency(registry, render_prometheus):
+ """`embedding.success` must increment request volume and observe latency."""
+ EmbeddingCollector().receive(
+ "embedding.success",
+ {"latency_seconds": 0.2},
+ registry,
+ )
+ text = render_prometheus(registry)
+ assert (
+ 'openviking_embedding_requests_total{account_id="__unknown__",status="ok"} 1' in text
+ or 'openviking_embedding_requests_total{account_id="__unknown__",status="ok"} 1.0' in text
+ )
+ assert (
+ 'openviking_embedding_latency_seconds_count{account_id="__unknown__",status="ok"} 1' in text
+ )
+
+
+def test_embedding_collector_records_error_volume_and_error_code_counter(
+ registry, render_prometheus
+):
+ """`embedding.error` must track request errors and normalize error_code labels."""
+ EmbeddingCollector().receive(
+ "embedding.error",
+ {"error_code": "rate_limit"},
+ registry,
+ )
+ text = render_prometheus(registry)
+ assert (
+ 'openviking_embedding_requests_total{account_id="__unknown__",status="error"} 1' in text
+ or 'openviking_embedding_requests_total{account_id="__unknown__",status="error"} 1.0'
+ in text
+ )
+ assert (
+ 'openviking_embedding_errors_total{account_id="__unknown__",error_code="rate_limit"} 1'
+ in text
+ or 'openviking_embedding_errors_total{account_id="__unknown__",error_code="rate_limit"} 1.0'
+ in text
+ )
diff --git a/tests/metrics/collectors/test_event_routing.py b/tests/metrics/collectors/test_event_routing.py
deleted file mode 100644
index 7efe399cf..000000000
--- a/tests/metrics/collectors/test_event_routing.py
+++ /dev/null
@@ -1,46 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-from openviking.metrics.collectors.base import EventMetricCollector
-from openviking.metrics.collectors.cache import CacheCollector
-
-
-class _DummyEventCollector(EventMetricCollector):
- SUPPORTED_EVENTS = frozenset({"demo.hit"})
-
- def __init__(self) -> None:
- self.seen: list[tuple[str, str]] = []
-
- def receive_hook(self, event_name: str, payload: dict, registry) -> None:
- self.seen.append(
- (
- str(event_name),
- str(payload["value"]),
- registry.collector_name() if hasattr(registry, "collector_name") else "registry",
- )
- )
-
-
-def test_event_metric_collector_uses_supported_events_and_receive_hook(registry):
- collector = _DummyEventCollector()
-
- collector.receive("demo.hit", {"value": "ok"}, registry)
- collector.receive("demo.unknown", {"value": "skip"}, registry)
-
- assert collector.SUPPORTED_EVENTS == frozenset({"demo.hit"})
- assert collector.seen == [("demo.hit", "ok", "registry")]
-
-
-def test_cache_collector_uses_supported_events_and_receive_hook_routing(
- registry, render_prometheus
-):
- collector = CacheCollector()
-
- collector.receive("cache.hit", {"level": "L0"}, registry)
- collector.receive("cache.miss", {"level": "L1"}, registry)
-
- text = render_prometheus(registry)
-
- assert collector.SUPPORTED_EVENTS == frozenset({"cache.hit", "cache.miss"})
- assert 'openviking_cache_hits_total{level="L0"} 1' in text
- assert 'openviking_cache_misses_total{level="L1"} 1' in text
diff --git a/tests/metrics/collectors/test_probe_valid_stale_contracts.py b/tests/metrics/collectors/test_probe_valid_stale_contracts.py
deleted file mode 100644
index 404aad3f0..000000000
--- a/tests/metrics/collectors/test_probe_valid_stale_contracts.py
+++ /dev/null
@@ -1,138 +0,0 @@
-"""Contract tests for probe collectors (valid/stale semantics)."""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-
-import pytest
-
-from openviking.metrics.collectors.async_system_probe import AsyncSystemProbeCollector
-from openviking.metrics.collectors.encryption_probe import EncryptionProbeCollector
-from openviking.metrics.collectors.model_provider_probe import ModelProviderProbeCollector
-from openviking.metrics.collectors.retrieval_backend_probe import RetrievalBackendProbeCollector
-from openviking.metrics.collectors.service_probe import ServiceProbeCollector
-from openviking.metrics.collectors.storage_probe import StorageProbeCollector
-from openviking.metrics.core.base import ReadEnvelope
-
-
-@dataclass
-class _ProbeDataSource:
- """
- Minimal stub datasource for probe collectors.
-
- The stub can return a `ReadEnvelope` (ok or failure) or raise an exception to exercise
- probe collector error paths.
- """
-
- value: object | None = None
- ok: bool = True
- raises: bool = False
-
- def read_probe_state(self):
- """Return a probe envelope or raise an exception depending on the configured flags."""
- if self.raises:
- raise RuntimeError("probe read failed")
- return ReadEnvelope(ok=self.ok, value=self.value, error_type="probe", error_message="fail")
-
-
-def test_service_probe_collector_emits_valid_on_success_and_invalid_on_failure(
- registry, render_prometheus
-):
- """ServiceProbeCollector must export readiness as `valid=1` on success and `valid=0` on failure."""
- ds = _ProbeDataSource(
- value={"service_readiness": True, "api_key_manager_readiness": False}, ok=True
- )
- c = ServiceProbeCollector(data_source=ds)
- c.collect(registry)
- text = render_prometheus(registry)
- assert 'openviking_service_readiness{valid="1"} 1.0' in text
- assert 'openviking_api_key_manager_readiness{valid="1"} 0.0' in text
-
- # Failure via envelope must flip to `valid=0` replacement series.
- ds.ok = False
- c.collect(registry)
- text2 = render_prometheus(registry)
- assert 'openviking_service_readiness{valid="0"} 0.0' in text2
- assert 'openviking_api_key_manager_readiness{valid="0"} 0.0' in text2
-
-
-def test_storage_probe_collector_preserves_last_probe_set_and_marks_invalid(
- registry, render_prometheus
-):
- """StorageProbeCollector must re-publish last-known probe set under `valid=0` on failure."""
- ds = _ProbeDataSource(value={"agfs": True, "other": False}, ok=True)
- c = StorageProbeCollector(data_source=ds)
- c.collect(registry)
- text = render_prometheus(registry)
- assert 'openviking_storage_readiness{probe="agfs",valid="1"} 1.0' in text
- assert 'openviking_storage_readiness{probe="other",valid="1"} 0.0' in text
-
- ds.raises = True
- with pytest.raises(RuntimeError):
- ds.read_probe_state() # sanity: ensure exception path is exercised
- c.collect(registry)
- text2 = render_prometheus(registry)
- assert 'openviking_storage_readiness{probe="agfs",valid="0"} 0.0' in text2
- assert 'openviking_storage_readiness{probe="other",valid="0"} 0.0' in text2
-
-
-def test_retrieval_backend_probe_collector_preserves_last_probe_set_and_marks_invalid(
- registry, render_prometheus
-):
- """RetrievalBackendProbeCollector must re-publish last-known probes under `valid=0` on failure."""
- ds = _ProbeDataSource(value={"vikingdb": True}, ok=True)
- c = RetrievalBackendProbeCollector(data_source=ds)
- c.collect(registry)
- text = render_prometheus(registry)
- assert 'openviking_retrieval_backend_readiness{probe="vikingdb",valid="1"} 1.0' in text
-
- ds.ok = False
- c.collect(registry)
- text2 = render_prometheus(registry)
- assert 'openviking_retrieval_backend_readiness{probe="vikingdb",valid="0"} 0.0' in text2
-
-
-def test_encryption_probe_collector_uses_last_provider_on_failure(registry, render_prometheus):
- """EncryptionProbeCollector must preserve last provider label when emitting `valid=0` series."""
- ds = _ProbeDataSource(value=(True, "volcengine"), ok=True)
- c = EncryptionProbeCollector(data_source=ds)
- c.collect(registry)
- text = render_prometheus(registry)
- assert 'openviking_encryption_component_health{valid="1"} 1.0' in text
- assert 'openviking_encryption_root_key_ready{valid="1"} 1.0' in text
- assert 'openviking_encryption_kms_provider_ready{provider="volcengine",valid="1"} 1.0' in text
-
- ds.raises = True
- c.collect(registry)
- text2 = render_prometheus(registry)
- assert 'openviking_encryption_component_health{valid="0"} 0.0' in text2
- assert 'openviking_encryption_root_key_ready{valid="0"} 0.0' in text2
- assert 'openviking_encryption_kms_provider_ready{provider="volcengine",valid="0"} 0.0' in text2
-
-
-def test_model_provider_probe_collector_uses_last_provider_on_failure(registry, render_prometheus):
- """ModelProviderProbeCollector must preserve last provider label when emitting `valid=0` series."""
- ds = _ProbeDataSource(value={"provider": ("volcengine", True)}, ok=True)
- c = ModelProviderProbeCollector(data_source=ds)
- c.collect(registry)
- text = render_prometheus(registry)
- assert 'openviking_model_provider_readiness{provider="volcengine",valid="1"} 1.0' in text
-
- ds.ok = False
- c.collect(registry)
- text2 = render_prometheus(registry)
- assert 'openviking_model_provider_readiness{provider="volcengine",valid="0"} 0.0' in text2
-
-
-def test_async_system_probe_collector_marks_invalid_on_failure(registry, render_prometheus):
- """AsyncSystemProbeCollector must publish `valid` and emit invalid series on failure."""
- ds = _ProbeDataSource(value={"queue": True}, ok=True)
- c = AsyncSystemProbeCollector(data_source=ds)
- c.collect(registry)
- text = render_prometheus(registry)
- assert 'openviking_async_system_readiness{probe="queue",valid="1"} 1.0' in text
-
- ds.raises = True
- c.collect(registry)
- text2 = render_prometheus(registry)
- assert 'openviking_async_system_readiness{probe="queue",valid="0"} 0.0' in text2
diff --git a/tests/metrics/collectors/test_session_collector.py b/tests/metrics/collectors/test_session_collector.py
deleted file mode 100644
index 4d79a18d2..000000000
--- a/tests/metrics/collectors/test_session_collector.py
+++ /dev/null
@@ -1,43 +0,0 @@
-"""Module-level tests for `openviking.metrics.collectors.session`."""
-
-from __future__ import annotations
-
-from openviking.metrics.collectors.session import SessionCollector
-
-
-def test_session_collector_records_lifecycle_and_contexts_and_archive(registry, render_prometheus):
- """SessionCollector must translate supported events into bounded counters."""
- c = SessionCollector()
- c.receive("session.lifecycle", {"action": "create", "status": "ok"}, registry)
- c.receive("session.contexts_used", {"action": "create", "delta": 2}, registry)
- c.receive("session.archive", {"status": "ok"}, registry)
-
- text = render_prometheus(registry)
- assert (
- 'openviking_session_lifecycle_total{account_id="__unknown__",action="create",status="ok"} 1'
- in text
- )
- assert (
- 'openviking_session_contexts_used_total{account_id="__unknown__",action="create"} 2' in text
- )
- assert 'openviking_session_archive_total{account_id="__unknown__",status="ok"} 1' in text
-
-
-def test_session_collector_ignores_malformed_payloads_instead_of_raising(
- registry, render_prometheus
-):
- """Missing keys must not raise; the collector should best-effort ignore malformed payloads."""
- c = SessionCollector()
-
- # Guard: base collector should ignore non-dict payloads.
- c.receive("session.lifecycle", "not-a-dict", registry)
-
- # Malformed dicts: should not raise and should not modify counters.
- c.receive("session.lifecycle", {"action": "create"}, registry)
- c.receive("session.contexts_used", {"action": "create"}, registry)
- c.receive("session.archive", {}, registry)
-
- text = render_prometheus(registry)
- assert "openviking_session_lifecycle_total" not in text
- assert "openviking_session_contexts_used_total" not in text
- assert "openviking_session_archive_total" not in text
diff --git a/tests/metrics/collectors/test_default_collectors.py b/tests/metrics/collectors/test_state_collectors.py
similarity index 51%
rename from tests/metrics/collectors/test_default_collectors.py
rename to tests/metrics/collectors/test_state_collectors.py
index 886a23ba4..539a97499 100644
--- a/tests/metrics/collectors/test_default_collectors.py
+++ b/tests/metrics/collectors/test_state_collectors.py
@@ -1,6 +1,8 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
+from __future__ import annotations
+
import time
from openviking.metrics.collectors.lock import LockCollector
@@ -68,6 +70,19 @@ def test_task_tracker_collector_maps_counts(monkeypatch):
assert 'openviking_task_failed{task_type="session_commit"} 4.0' in text
+def test_task_tracker_collector_clears_disappeared_task_types():
+ registry = MetricRegistry()
+ collector = TaskTrackerCollector(data_source=TaskStateDataSource())
+
+ collector.collect_hook(registry, {"session_commit": {"pending": 2}})
+ text = PrometheusExporter(registry=registry).render()
+ assert 'openviking_task_pending{task_type="session_commit"} 2.0' in text
+
+ collector.collect_hook(registry, {})
+ text2 = PrometheusExporter(registry=registry).render()
+ assert 'task_type="session_commit"' not in text2
+
+
def test_observer_health_collector_maps_component_status():
class Status:
def __init__(self, ok: bool, err: bool) -> None:
@@ -99,6 +114,125 @@ def test_observer_health_collector_maps_component_status():
assert 'openviking_component_health{component="vikingdb",valid="1"} 1.0' in text
+def test_observer_state_collector_valid_and_failure_keeps_last_values(registry, render_prometheus):
+ from openviking.metrics.collectors.observer_state import ObserverStateCollector
+
+ class S:
+ def __init__(self, ok: bool, err: bool):
+ self.is_healthy = ok
+ self.has_errors = err
+
+ class DS:
+ def __init__(self):
+ self.fail = False
+
+ def read_component_states(self):
+ if self.fail:
+ raise RuntimeError("boom")
+ return {"a": S(True, False), "b": S(False, True), "c": S(True, True)}
+
+ ds = DS()
+ c = ObserverStateCollector(data_source=ds)
+ c.collect(registry)
+ text = render_prometheus(registry)
+ assert 'openviking_observer_components_total{valid="1"} 3.0' in text
+ assert 'openviking_observer_components_unhealthy{valid="1"} 1.0' in text
+ assert 'openviking_observer_components_with_errors{valid="1"} 2.0' in text
+
+ ds.fail = True
+ c.collect(registry)
+ text2 = render_prometheus(registry)
+ assert 'openviking_observer_components_total{valid="0"} 3.0' in text2
+ assert 'openviking_observer_components_unhealthy{valid="0"} 1.0' in text2
+ assert 'openviking_observer_components_with_errors{valid="0"} 2.0' in text2
+
+
+def test_model_usage_collector_delta_and_available_gauge(registry, render_prometheus):
+ from openviking.metrics.collectors.model_usage import ModelUsageCollector
+
+ class DS:
+ def __init__(self):
+ self.data = {
+ "vlm": {
+ "available": True,
+ "usage_by_model": {
+ "m1": {
+ "usage_by_provider": {
+ "p1": {
+ "prompt_tokens": 2,
+ "completion_tokens": 3,
+ "total_tokens": 5,
+ "call_count": 1,
+ }
+ }
+ }
+ },
+ },
+ "embedding": {"available": False, "usage_by_model": {}},
+ "rerank": {"available": False, "usage_by_model": {}},
+ }
+
+ def read_model_usage(self):
+ return self.data
+
+ ds = DS()
+ c = ModelUsageCollector(data_source=ds)
+ c.collect(registry)
+ text = render_prometheus(registry)
+ assert 'openviking_model_usage_available{model_type="vlm",valid="1"} 1.0' in text
+ assert 'openviking_model_usage_available{model_type="embedding",valid="1"} 0.0' in text
+ assert 'openviking_model_usage_available{model_type="rerank",valid="1"} 0.0' in text
+ assert "openviking_model_usage_valid" not in text
+ assert 'openviking_model_calls_total{model_name="m1",model_type="vlm",provider="p1"} 1' in text
+ assert (
+ 'openviking_model_tokens_total{model_name="m1",model_type="vlm",provider="p1",token_type="total"} 5'
+ in text
+ )
+
+ ds.data["vlm"]["usage_by_model"]["m1"]["usage_by_provider"]["p1"]["call_count"] = 2
+ ds.data["vlm"]["usage_by_model"]["m1"]["usage_by_provider"]["p1"]["total_tokens"] = 7
+ ds.data["vlm"]["usage_by_model"]["m1"]["usage_by_provider"]["p1"]["prompt_tokens"] = 3
+ ds.data["vlm"]["usage_by_model"]["m1"]["usage_by_provider"]["p1"]["completion_tokens"] = 4
+ c.collect(registry)
+ text2 = render_prometheus(registry)
+ assert 'openviking_model_calls_total{model_name="m1",model_type="vlm",provider="p1"} 2' in text2
+ assert (
+ 'openviking_model_tokens_total{model_name="m1",model_type="vlm",provider="p1",token_type="total"} 7'
+ in text2
+ )
+
+
+def test_model_usage_collector_failure_reuses_last_available_state_with_valid_zero(
+ registry, render_prometheus
+):
+ from openviking.metrics.collectors.model_usage import ModelUsageCollector
+
+ class DS:
+ def __init__(self):
+ self.fail = False
+
+ def read_model_usage(self):
+ if self.fail:
+ raise RuntimeError("boom")
+ return {
+ "vlm": {"available": True, "usage_by_model": {}},
+ "embedding": {"available": False, "usage_by_model": {}},
+ "rerank": {"available": False, "usage_by_model": {}},
+ }
+
+ ds = DS()
+ collector = ModelUsageCollector(data_source=ds)
+
+ collector.collect(registry)
+ ds.fail = True
+ collector.collect(registry)
+
+ text = render_prometheus(registry)
+ assert 'openviking_model_usage_available{model_type="vlm",valid="0"} 1.0' in text
+ assert 'openviking_model_usage_available{model_type="embedding",valid="0"} 0.0' in text
+ assert 'openviking_model_usage_available{model_type="rerank",valid="0"} 0.0' in text
+
+
def test_lock_collector_counts_active_and_stale(monkeypatch):
class Handle:
def __init__(self, locks: int, last_active_at: float) -> None:
diff --git a/tests/metrics/collectors/test_task_tracker_collector.py b/tests/metrics/collectors/test_task_tracker_collector.py
deleted file mode 100644
index c547c73de..000000000
--- a/tests/metrics/collectors/test_task_tracker_collector.py
+++ /dev/null
@@ -1,22 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-from openviking.metrics.collectors.task_tracker import TaskTrackerCollector
-from openviking.metrics.core.registry import MetricRegistry
-from openviking.metrics.datasources.task import TaskStateDataSource
-from openviking.metrics.exporters.prometheus import PrometheusExporter
-
-
-def test_task_tracker_collector_clears_disappeared_task_types():
- registry = MetricRegistry()
- collector = TaskTrackerCollector(data_source=TaskStateDataSource())
-
- collector.collect_hook(registry, {"session_commit": {"pending": 2}})
- text = PrometheusExporter(registry=registry).render()
- assert 'openviking_task_pending{task_type="session_commit"} 2.0' in text
-
- # When the snapshot no longer includes the task type, previously-exported series must not
- # remain stale forever.
- collector.collect_hook(registry, {})
- text2 = PrometheusExporter(registry=registry).render()
- assert 'task_type="session_commit"' not in text2
diff --git a/tests/metrics/collectors/test_telemetry_bridge_collector.py b/tests/metrics/collectors/test_telemetry_bridge_collector.py
deleted file mode 100644
index 502a7b13c..000000000
--- a/tests/metrics/collectors/test_telemetry_bridge_collector.py
+++ /dev/null
@@ -1,45 +0,0 @@
-"""Module-level tests for `openviking.metrics.collectors.telemetry_bridge`."""
-
-from __future__ import annotations
-
-from openviking.metrics.collectors.telemetry_bridge import TelemetryBridgeCollector
-
-
-def test_telemetry_bridge_collector_records_basic_operation_metrics(registry, render_prometheus):
- """TelemetryBridgeCollector must expand one telemetry summary into core operation metrics."""
- c = TelemetryBridgeCollector()
- c.receive(
- "telemetry.summary",
- {
- "summary": {
- "operation": "resource.process",
- "status": "ok",
- "duration_ms": 250.0,
- "tokens": {"total": 3},
- }
- },
- registry,
- )
-
- text = render_prometheus(registry)
- assert (
- 'openviking_operation_requests_total{account_id="__unknown__",operation="resource.process",status="ok"} 1'
- in text
- )
- assert (
- 'openviking_operation_tokens_total{account_id="__unknown__",operation="resource.process",token_type="all"} 3'
- in text
- )
-
-
-def test_telemetry_bridge_collector_ignores_malformed_payloads_instead_of_raising(
- registry, render_prometheus
-):
- """Missing/invalid `summary` payload must not raise; collector should ignore it best-effort."""
- c = TelemetryBridgeCollector()
-
- c.receive("telemetry.summary", {}, registry)
- c.receive("telemetry.summary", {"summary": "not-a-mapping"}, registry)
-
- text = render_prometheus(registry)
- assert "openviking_operation_requests_total" not in text
diff --git a/tests/metrics/config/test_server_config.py b/tests/metrics/config/test_server_config.py
new file mode 100644
index 000000000..47f1cc81b
--- /dev/null
+++ b/tests/metrics/config/test_server_config.py
@@ -0,0 +1,59 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+import json
+
+import pytest
+
+from openviking.server.config import load_server_config
+
+
+def test_load_server_config_rejects_legacy_server_metrics_field(tmp_path):
+ config_path = tmp_path / "ov.conf"
+ config_path.write_text(json.dumps({"server": {"metrics": {"enabled": True}}}))
+
+ with pytest.raises(ValueError, match=r"server\.metrics"):
+ load_server_config(str(config_path))
+
+
+def test_load_server_config_rejects_legacy_server_telemetry_field(tmp_path):
+ config_path = tmp_path / "ov.conf"
+ config_path.write_text(json.dumps({"server": {"telemetry": {"prometheus": {"enabled": True}}}}))
+
+ with pytest.raises(ValueError, match=r"server\.telemetry"):
+ load_server_config(str(config_path))
+
+
+def test_load_server_config_preserves_metrics_fields_under_server_observability(tmp_path):
+ config_path = tmp_path / "ov.conf"
+ config_path.write_text(
+ json.dumps(
+ {
+ "server": {
+ "observability": {
+ "metrics": {
+ "enabled": True,
+ "account_dimension": {
+ "enabled": True,
+ "max_active_accounts": 5,
+ "metric_allowlist": [
+ "openviking_http_requests_total",
+ "openviking_task_pending",
+ ],
+ },
+ }
+ }
+ }
+ }
+ )
+ )
+
+ config = load_server_config(str(config_path))
+
+ assert config.observability.metrics.enabled is True
+ assert config.observability.metrics.account_dimension.enabled is True
+ assert config.observability.metrics.account_dimension.max_active_accounts == 5
+ assert config.observability.metrics.account_dimension.metric_allowlist == [
+ "openviking_http_requests_total",
+ "openviking_task_pending",
+ ]
diff --git a/tests/metrics/contracts/test_architecture_contracts.py b/tests/metrics/contracts/test_architecture_contracts.py
deleted file mode 100644
index c2dbe5228..000000000
--- a/tests/metrics/contracts/test_architecture_contracts.py
+++ /dev/null
@@ -1,117 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-from pathlib import Path
-
-
-def test_required_core_modules_exist():
- import openviking.metrics.core.base as core_base
- import openviking.metrics.core.refresh as core_refresh
- import openviking.metrics.core.registry as core_registry
- import openviking.metrics.core.runtime as core_runtime
- import openviking.metrics.core.types as core_types
-
- assert hasattr(core_base, "MetricDataSource")
- assert hasattr(core_base, "MetricCollector")
- assert hasattr(core_base, "MetricExporter")
- assert hasattr(core_refresh, "RefreshGate")
- assert hasattr(core_registry, "MetricRegistry")
- assert hasattr(core_runtime, "EventCollectorRouter")
- assert core_types is not None
-
-
-def test_required_architecture_types_exist():
- import openviking.metrics.core.base as base_module
-
- assert hasattr(base_module, "MetricDataSource")
- assert hasattr(base_module, "MetricCollector")
- assert hasattr(base_module, "MetricExporter")
-
-
-def test_required_intermediate_types_exist():
- import openviking.metrics.collectors.base as collector_base_module
- import openviking.metrics.datasources as ds_module
- import openviking.metrics.datasources.base as ds_base_module
-
- assert hasattr(ds_base_module, "EventMetricDataSource")
- assert hasattr(ds_base_module, "StateMetricDataSource")
- assert hasattr(ds_base_module, "DomainStatsMetricDataSource")
- assert hasattr(ds_base_module, "ProbeMetricDataSource")
- assert hasattr(ds_module, "CacheEventDataSource")
- assert hasattr(ds_module, "TelemetryBridgeEventDataSource")
-
- assert hasattr(collector_base_module, "EventMetricCollector")
- assert hasattr(collector_base_module, "StateMetricCollector")
- assert hasattr(collector_base_module, "DomainStatsMetricCollector")
- assert hasattr(collector_base_module, "ProbeMetricCollector")
- assert hasattr(collector_base_module, "Refreshable")
- assert not hasattr(collector_base_module, "AbstractMetricCollector")
-
-
-def test_prometheus_exporter_inherits_base_metric_exporter():
- import openviking.metrics.exporters as exporters_module
- from openviking.metrics.core.base import MetricExporter
- from openviking.metrics.exporters.prometheus import PrometheusExporter
-
- assert issubclass(PrometheusExporter, MetricExporter)
- assert not hasattr(exporters_module, "AbstractMetricExporter")
-
-
-def test_concrete_datasources_and_collectors_follow_doc_inheritance():
- from openviking.metrics.collectors.base import (
- ProbeMetricCollector,
- Refreshable,
- StateMetricCollector,
- )
- from openviking.metrics.collectors.lock import LockCollector
- from openviking.metrics.collectors.queue import QueueCollector
- from openviking.metrics.collectors.service_probe import ServiceProbeCollector
- from openviking.metrics.collectors.vikingdb import VikingDBCollector
- from openviking.metrics.datasources.base import (
- DomainStatsMetricDataSource,
- ProbeMetricDataSource,
- StateMetricDataSource,
- )
- from openviking.metrics.datasources.observer_state import (
- LockStateDataSource,
- ObserverStateDataSource,
- VikingDBStateDataSource,
- )
- from openviking.metrics.datasources.probes import ServiceProbeDataSource
- from openviking.metrics.datasources.queue import QueuePipelineStateDataSource
-
- assert issubclass(QueuePipelineStateDataSource, StateMetricDataSource)
- assert issubclass(ObserverStateDataSource, DomainStatsMetricDataSource)
- assert issubclass(LockStateDataSource, StateMetricDataSource)
- assert issubclass(VikingDBStateDataSource, StateMetricDataSource)
- assert issubclass(ServiceProbeDataSource, ProbeMetricDataSource)
-
- assert issubclass(QueueCollector, StateMetricCollector)
- assert issubclass(LockCollector, StateMetricCollector)
- assert issubclass(VikingDBCollector, StateMetricCollector)
- assert issubclass(ServiceProbeCollector, ProbeMetricCollector)
- assert issubclass(QueueCollector, Refreshable)
- assert issubclass(LockCollector, Refreshable)
- assert issubclass(VikingDBCollector, Refreshable)
- assert issubclass(ServiceProbeCollector, Refreshable)
-
-
-def test_metrics_code_has_no_snapshot_api():
- root = Path(__file__).resolve().parents[2] / "openviking" / "metrics"
- for path in root.rglob("*.py"):
- text = path.read_text(encoding="utf-8")
- assert ".snapshot(" not in text, f"snapshot api still found in {path}"
-
-
-def test_metric_collector_supports_collect_and_receive():
- from openviking.metrics.core.base import MetricCollector
-
- class _DummyCollector(MetricCollector):
- @classmethod
- def kind(cls) -> str:
- return "dummy"
-
- collector = _DummyCollector()
- assert collector.collector_name() == "_DummyCollector"
- assert collector.collect(None) is None
- assert collector.receive("event", {}, None) is None
diff --git a/tests/metrics/contracts/test_prometheus_observer_removed.py b/tests/metrics/contracts/test_prometheus_observer_removed.py
deleted file mode 100644
index eaf33d390..000000000
--- a/tests/metrics/contracts/test_prometheus_observer_removed.py
+++ /dev/null
@@ -1,19 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-from pathlib import Path
-
-
-def test_runtime_code_has_no_prometheus_observer_references():
- # tests/metrics/contracts -> repo_root/openviking
- root = Path(__file__).resolve().parents[3] / "openviking"
- banned = (
- "PrometheusObserver",
- "get_prometheus_observer",
- "set_prometheus_observer",
- "prometheus_observer.py",
- )
- for path in root.rglob("*.py"):
- text = path.read_text(encoding="utf-8")
- for needle in banned:
- assert needle not in text, f"{needle} still found in {path}"
diff --git a/tests/metrics/contracts/test_pull_collector_templates.py b/tests/metrics/contracts/test_pull_collector_templates.py
deleted file mode 100644
index f7029927e..000000000
--- a/tests/metrics/contracts/test_pull_collector_templates.py
+++ /dev/null
@@ -1,101 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-from openviking.metrics.collectors.base import (
- CollectorConfig,
- DomainStatsMetricCollector,
- ProbeMetricCollector,
- StateMetricCollector,
-)
-from openviking.metrics.core.registry import MetricRegistry
-
-
-class _DummyStateCollector(StateMetricCollector):
- config = CollectorConfig()
-
- def __init__(self) -> None:
- self.seen = []
-
- def read_metric_input(self):
- return {"value": 3}
-
- def collect_hook(self, registry, metric_input) -> None:
- self.seen.append(("state", metric_input["value"]))
-
-
-class _DummyProbeCollector(ProbeMetricCollector):
- config = CollectorConfig()
-
- def __init__(self) -> None:
- self.seen = []
-
- def read_metric_input(self):
- return {"ok": True}
-
- def collect_hook(self, registry, metric_input) -> None:
- self.seen.append(("probe", metric_input["ok"]))
-
-
-class _DummyDomainCollector(DomainStatsMetricCollector):
- config = CollectorConfig()
-
- def __init__(self) -> None:
- self.seen = []
-
- def read_metric_input(self):
- return {"total": 7}
-
- def collect_hook(self, registry, metric_input) -> None:
- self.seen.append(("domain", metric_input["total"]))
-
-
-class _DummyFailingStateCollector(StateMetricCollector):
- config = CollectorConfig()
-
- def __init__(self) -> None:
- self.error_seen = None
-
- def read_metric_input(self):
- raise RuntimeError("boom")
-
- def collect_hook(self, registry, metric_input) -> None:
- raise AssertionError("should not be called")
-
- def collect_error_hook(self, registry, error: Exception) -> None:
- self.error_seen = str(error)
-
-
-def test_state_metric_collector_collect_uses_template_hooks():
- registry = MetricRegistry()
- collector = _DummyStateCollector()
-
- collector.collect(registry)
-
- assert collector.seen == [("state", 3)]
-
-
-def test_probe_metric_collector_collect_uses_template_hooks():
- registry = MetricRegistry()
- collector = _DummyProbeCollector()
-
- collector.collect(registry)
-
- assert collector.seen == [("probe", True)]
-
-
-def test_domain_stats_metric_collector_collect_uses_template_hooks():
- registry = MetricRegistry()
- collector = _DummyDomainCollector()
-
- collector.collect(registry)
-
- assert collector.seen == [("domain", 7)]
-
-
-def test_state_metric_collector_collect_error_hook_can_handle_read_failures():
- registry = MetricRegistry()
- collector = _DummyFailingStateCollector()
-
- collector.collect(registry)
-
- assert collector.error_seen == "boom"
diff --git a/tests/metrics/core/test_exporter.py b/tests/metrics/core/test_exporter.py
new file mode 100644
index 000000000..1782f0ce8
--- /dev/null
+++ b/tests/metrics/core/test_exporter.py
@@ -0,0 +1,14 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+
+def test_exporter_outputs_help_type_and_empty_metrics(registry, render_prometheus):
+ registry.counter("openviking_empty_counter_total")
+ registry.gauge("openviking_empty_gauge")
+ registry.histogram("openviking_empty_histogram_seconds")
+ text = render_prometheus(registry)
+ assert "# TYPE openviking_empty_counter_total counter" in text
+ assert "openviking_empty_counter_total 0" in text
+ assert "# TYPE openviking_empty_histogram_seconds histogram" in text
+ assert "openviking_empty_histogram_seconds_count 0" in text
+ assert 'openviking_empty_histogram_seconds_bucket{le="+Inf"} 0' in text
diff --git a/tests/metrics/core/test_metric_name_builder.py b/tests/metrics/core/test_metric_name_builder.py
deleted file mode 100644
index e43113c6f..000000000
--- a/tests/metrics/core/test_metric_name_builder.py
+++ /dev/null
@@ -1,27 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-from pathlib import Path
-
-from openviking.metrics.core.base import MetricCollector
-
-
-def test_metric_collector_metric_name_includes_namespace_and_optional_unit():
- assert (
- MetricCollector.metric_name("cache", "hits", unit="total") == "openviking_cache_hits_total"
- )
- assert (
- MetricCollector.metric_name("resource", "stage_duration", unit="seconds")
- == "openviking_resource_stage_duration_seconds"
- )
- assert MetricCollector.metric_name("lock", "active") == "openviking_lock_active"
-
-
-def test_collectors_do_not_embed_openviking_metric_name_literals():
- root = Path(__file__).resolve().parents[2] / "openviking" / "metrics" / "collectors"
- offenders = []
- for path in root.glob("*.py"):
- text = path.read_text(encoding="utf-8")
- if '"openviking_' in text or "'openviking_" in text:
- offenders.append(path.name)
- assert offenders == []
diff --git a/tests/metrics/core/test_refresh_control.py b/tests/metrics/core/test_refresh.py
similarity index 96%
rename from tests/metrics/core/test_refresh_control.py
rename to tests/metrics/core/test_refresh.py
index 160259af2..077f0a456 100644
--- a/tests/metrics/core/test_refresh_control.py
+++ b/tests/metrics/core/test_refresh.py
@@ -145,13 +145,11 @@ async def test_collector_manager_deadline_exceeded_does_not_stick_inflight(monke
assert r1
assert any(item.collector == "dummy" and item.reason == "deadline_exceeded" for item in r1)
- # While the long refresh is still running, we should see inflight but it must not be permanent.
r2 = await mgr.refresh_all(registry, deadline_seconds=1.0)
assert r2 and r2[0].collector == "dummy"
assert r2[0].attempted is False
assert r2[0].reason == "inflight"
- # Let the background refresh finish and confirm the next scrape recovers to ttl_valid.
release.set()
await asyncio.wait_for(asyncio.sleep(0), timeout=0.5)
r3 = await mgr.refresh_all(registry, deadline_seconds=1.0)
diff --git a/tests/metrics/core/test_registry_and_exporter.py b/tests/metrics/core/test_registry.py
similarity index 70%
rename from tests/metrics/core/test_registry_and_exporter.py
rename to tests/metrics/core/test_registry.py
index 68284ee8f..ecd89240b 100644
--- a/tests/metrics/core/test_registry_and_exporter.py
+++ b/tests/metrics/core/test_registry.py
@@ -1,11 +1,25 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
+from pathlib import Path
+
import pytest
+from openviking.metrics.core.base import MetricCollector
from openviking.metrics.core.registry import MetricRegistry
+def test_metric_collector_metric_name_includes_namespace_and_optional_unit():
+ assert (
+ MetricCollector.metric_name("cache", "hits", unit="total") == "openviking_cache_hits_total"
+ )
+ assert (
+ MetricCollector.metric_name("resource", "stage_duration", unit="seconds")
+ == "openviking_resource_stage_duration_seconds"
+ )
+ assert MetricCollector.metric_name("lock", "active") == "openviking_lock_active"
+
+
def test_registry_rejects_type_conflict():
registry = MetricRegistry()
registry.counter("openviking_conflict_total")
@@ -68,13 +82,11 @@ def test_histogram_boundary_bucket(registry, render_prometheus):
assert 'openviking_latency_seconds_bucket{le="+Inf"} 1' in text
-def test_exporter_outputs_help_type_and_empty_metrics(registry, render_prometheus):
- registry.counter("openviking_empty_counter_total")
- registry.gauge("openviking_empty_gauge")
- registry.histogram("openviking_empty_histogram_seconds")
- text = render_prometheus(registry)
- assert "# TYPE openviking_empty_counter_total counter" in text
- assert "openviking_empty_counter_total 0" in text
- assert "# TYPE openviking_empty_histogram_seconds histogram" in text
- assert "openviking_empty_histogram_seconds_count 0" in text
- assert 'openviking_empty_histogram_seconds_bucket{le="+Inf"} 0' in text
+def test_collectors_do_not_embed_openviking_metric_name_literals():
+ root = Path(__file__).resolve().parents[3] / "openviking" / "metrics" / "collectors"
+ offenders = []
+ for path in root.glob("*.py"):
+ text = path.read_text(encoding="utf-8")
+ if '"openviking_' in text or "'openviking_" in text:
+ offenders.append(path.name)
+ assert offenders == []
diff --git a/tests/metrics/datasources/test_abstraction_reuse.py b/tests/metrics/datasources/test_abstraction_reuse.py
deleted file mode 100644
index 8adb9bd59..000000000
--- a/tests/metrics/datasources/test_abstraction_reuse.py
+++ /dev/null
@@ -1,43 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-from pathlib import Path
-
-
-def test_metric_datasource_owns_safe_read_helpers_and_datasource_subclasses_reuse_them():
- # This test reads source files by absolute path; keep it stable across test subdirectories.
- project_root = Path(__file__).resolve().parents[3]
-
- core_base = (project_root / "openviking" / "metrics" / "core" / "base.py").read_text(
- encoding="utf-8"
- )
- datasource_base = (
- project_root / "openviking" / "metrics" / "datasources" / "base.py"
- ).read_text(encoding="utf-8")
- probes = (project_root / "openviking" / "metrics" / "datasources" / "probes.py").read_text(
- encoding="utf-8"
- )
- encryption = (
- project_root / "openviking" / "metrics" / "datasources" / "encryption.py"
- ).read_text(encoding="utf-8")
- model_usage = (
- project_root / "openviking" / "metrics" / "datasources" / "model_usage.py"
- ).read_text(encoding="utf-8")
- observer_state = (
- project_root / "openviking" / "metrics" / "datasources" / "observer_state.py"
- ).read_text(encoding="utf-8")
-
- assert "def safe_read(" in core_base
- assert "def safe_read_async(" in core_base
- assert "def best_effort(" not in datasource_base
- assert "def best_effort_async(" not in datasource_base
-
- assert "safe_value_probe(" in datasource_base
- assert probes.count("safe_value_probe(") >= 1
- assert encryption.count("safe_value_probe(") >= 1
-
- assert '"available"' in model_usage
- assert '"usage_by_model"' in model_usage
- assert ".as_dict(" in model_usage
- assert ".normalize_str(" in model_usage
- assert ".as_dict(" in observer_state or ".normalize_str(" in observer_state
diff --git a/tests/metrics/datasources/test_encryption.py b/tests/metrics/datasources/test_encryption.py
deleted file mode 100644
index 439078d2c..000000000
--- a/tests/metrics/datasources/test_encryption.py
+++ /dev/null
@@ -1,70 +0,0 @@
-"""Module-level tests for `openviking.metrics.datasources.encryption`."""
-
-from __future__ import annotations
-
-from types import SimpleNamespace
-
-import openviking.metrics.datasources.encryption as enc
-
-
-def test_encryption_event_datasource_emits_operation_event(patch_event_emit):
- """EncryptionEventDataSource must emit a normalized `encryption.operation` event."""
-
- enc.EncryptionEventDataSource.record_operation(
- operation="encrypt",
- status="ok",
- duration_seconds=0.25,
- )
-
- assert (
- "encryption.operation",
- {"operation": "encrypt", "status": "ok", "duration_seconds": 0.25},
- ) in patch_event_emit
-
-
-def test_encryption_event_datasource_ignores_non_positive_bytes(monkeypatch):
- """EncryptionEventDataSource must not emit `encryption.bytes` when size is non-positive."""
-
- calls: list[tuple[str, dict]] = []
-
- def _emit(event_name: str, payload: dict) -> None:
- calls.append((str(event_name), dict(payload)))
- raise RuntimeError("should not be called for non-positive bytes")
-
- monkeypatch.setattr(enc.EventMetricDataSource, "_emit", staticmethod(_emit))
- enc.EncryptionEventDataSource.record_bytes(operation="encrypt", size_bytes=0)
- enc.EncryptionEventDataSource.record_bytes(operation="encrypt", size_bytes=-1)
- assert calls == []
-
-
-def test_encryption_probe_datasource_ok_and_provider(monkeypatch):
- """EncryptionProbeDataSource returns `(True, provider)` on successful bootstrap."""
-
- class _Cfg:
- encryption = SimpleNamespace(provider="volcengine")
-
- def _bootstrap():
- return None
-
- monkeypatch.setattr("openviking.crypto.config.bootstrap_encryption", _bootstrap)
- ds = enc.EncryptionProbeDataSource(config_provider=lambda: _Cfg())
- env = ds.read_probe_state()
- assert env.ok is True
- assert env.value == (True, "volcengine")
-
-
-def test_encryption_probe_datasource_returns_default_on_exception(monkeypatch):
- """EncryptionProbeDataSource must return `(False, provider)` with `ok=False` on failures."""
-
- class _Cfg:
- encryption = SimpleNamespace(provider="volcengine")
-
- def _boom():
- raise RuntimeError("bootstrap failed")
-
- monkeypatch.setattr("openviking.crypto.config.bootstrap_encryption", _boom)
- ds = enc.EncryptionProbeDataSource(config_provider=lambda: _Cfg())
- env = ds.read_probe_state()
- assert env.ok is False
- assert env.value == (False, "volcengine")
- assert env.error_type == "RuntimeError"
diff --git a/tests/metrics/datasources/test_envelope.py b/tests/metrics/datasources/test_envelope.py
deleted file mode 100644
index 7df4ef703..000000000
--- a/tests/metrics/datasources/test_envelope.py
+++ /dev/null
@@ -1,65 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-from openviking.metrics.collectors.base import (
- CollectorConfig,
- ProbeMetricCollector,
- StateMetricCollector,
-)
-from openviking.metrics.core.base import ReadEnvelope
-from openviking.metrics.core.registry import MetricRegistry
-
-
-class _EnvelopeStateCollector(StateMetricCollector):
- config = CollectorConfig()
- STALE_ON_ERROR = True
-
- def __init__(self) -> None:
- self.error_seen = False
- self.value_seen = None
-
- def read_metric_input(self):
- return ReadEnvelope(ok=False, value=("fallback",))
-
- def collect_hook(self, registry, metric_input) -> None:
- self.value_seen = metric_input
-
- def collect_stale_hook(self, registry, error: Exception) -> None:
- self.error_seen = True
-
-
-class _EnvelopeProbeCollector(ProbeMetricCollector):
- config = CollectorConfig()
-
- def __init__(self) -> None:
- self.error_seen = False
- self.value_seen = None
-
- def read_metric_input(self):
- return ReadEnvelope(ok=False, value={"probe": True})
-
- def collect_hook(self, registry, metric_input) -> None:
- self.value_seen = metric_input
-
- def collect_stale_hook(self, registry, error: Exception) -> None:
- self.error_seen = True
-
-
-def test_state_collector_unwraps_envelope_and_routes_ok_false_to_stale_hook():
- registry = MetricRegistry()
- collector = _EnvelopeStateCollector()
-
- collector.collect(registry)
-
- assert collector.error_seen is True
- assert collector.value_seen is None
-
-
-def test_probe_collector_unwraps_envelope_and_routes_ok_false_to_stale_hook():
- registry = MetricRegistry()
- collector = _EnvelopeProbeCollector()
-
- collector.collect(registry)
-
- assert collector.error_seen is True
- assert collector.value_seen is None
diff --git a/tests/metrics/datasources/test_event_datasources.py b/tests/metrics/datasources/test_event_datasources.py
new file mode 100644
index 000000000..ea54d8775
--- /dev/null
+++ b/tests/metrics/datasources/test_event_datasources.py
@@ -0,0 +1,162 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import openviking.metrics.datasources.encryption as enc
+import openviking.metrics.datasources.retrieval as retrieval
+import openviking.metrics.datasources.session as session
+from openviking.metrics.datasources.base import EventMetricDataSource
+from openviking.metrics.datasources.cache import CacheEventDataSource
+from openviking.metrics.datasources.http import HttpRequestLifecycleDataSource
+
+
+def test_event_datasources_use_shared_event_metric_datasource_emit(monkeypatch):
+ calls: list[tuple[str, dict]] = []
+
+ def _fake_emit(event_name: str, payload: dict) -> None:
+ calls.append((str(event_name), dict(payload)))
+
+ monkeypatch.setattr(EventMetricDataSource, "_emit", staticmethod(_fake_emit), raising=False)
+
+ CacheEventDataSource.record_hit("L0")
+ CacheEventDataSource.record_miss("L1")
+ HttpRequestLifecycleDataSource.record_request(
+ method="GET", route="/demo", status="200", duration_seconds=0.01
+ )
+
+ assert calls[0][0] == "cache.hit"
+ assert calls[1][0] == "cache.miss"
+ assert calls[2][0] == "http.request"
+
+
+def test_encryption_event_datasource_emits_operation_event(patch_event_emit):
+ """EncryptionEventDataSource must emit a normalized `encryption.operation` event."""
+
+ enc.EncryptionEventDataSource.record_operation(
+ operation="encrypt",
+ status="ok",
+ duration_seconds=0.25,
+ )
+
+ assert (
+ "encryption.operation",
+ {"operation": "encrypt", "status": "ok", "duration_seconds": 0.25},
+ ) in patch_event_emit
+
+
+def test_encryption_event_datasource_ignores_non_positive_bytes(monkeypatch):
+ """EncryptionEventDataSource must not emit `encryption.bytes` when size is non-positive."""
+
+ calls: list[tuple[str, dict]] = []
+
+ def _emit(event_name: str, payload: dict) -> None:
+ calls.append((str(event_name), dict(payload)))
+ raise RuntimeError("should not be called for non-positive bytes")
+
+ monkeypatch.setattr(enc.EventMetricDataSource, "_emit", staticmethod(_emit))
+ enc.EncryptionEventDataSource.record_bytes(operation="encrypt", size_bytes=0)
+ enc.EncryptionEventDataSource.record_bytes(operation="encrypt", size_bytes=-1)
+ assert calls == []
+
+
+def test_encryption_probe_datasource_ok_and_provider(monkeypatch):
+ """EncryptionProbeDataSource returns `(True, provider)` on successful bootstrap."""
+
+ class _Cfg:
+ encryption = SimpleNamespace(provider="volcengine")
+
+ def _bootstrap():
+ return None
+
+ monkeypatch.setattr("openviking.crypto.config.bootstrap_encryption", _bootstrap)
+ ds = enc.EncryptionProbeDataSource(config_provider=lambda: _Cfg())
+ env = ds.read_probe_state()
+ assert env.ok is True
+ assert env.value == (True, "volcengine")
+
+
+def test_encryption_probe_datasource_returns_default_on_exception(monkeypatch):
+ """EncryptionProbeDataSource must return `(False, provider)` with `ok=False` on failures."""
+
+ class _Cfg:
+ encryption = SimpleNamespace(provider="volcengine")
+
+ def _boom():
+ raise RuntimeError("bootstrap failed")
+
+ monkeypatch.setattr("openviking.crypto.config.bootstrap_encryption", _boom)
+ ds = enc.EncryptionProbeDataSource(config_provider=lambda: _Cfg())
+ env = ds.read_probe_state()
+ assert env.ok is False
+ assert env.value == (False, "volcengine")
+ assert env.error_type == "RuntimeError"
+
+
+def test_retrieval_stats_datasource_emits_completed_event(patch_event_emit):
+ """RetrievalStatsDataSource must emit a normalized `retrieval.completed` event payload."""
+
+ retrieval.RetrievalStatsDataSource.record_retrieval(
+ context_type="context_1",
+ result_count=3,
+ latency_seconds=0.12,
+ rerank_used=True,
+ rerank_fallback=False,
+ )
+
+ assert (
+ "retrieval.completed",
+ {
+ "context_type": "context_1",
+ "result_count": 3,
+ "latency_seconds": 0.12,
+ "rerank_used": True,
+ "rerank_fallback": False,
+ },
+ ) in patch_event_emit
+
+
+def test_retrieval_stats_datasource_normalizes_unknown_context_type(patch_event_emit):
+ """Empty/falsey context types are normalized to `unknown`."""
+
+ retrieval.RetrievalStatsDataSource.record_retrieval(
+ context_type="",
+ result_count=0,
+ latency_seconds=0.0,
+ )
+
+ assert any(
+ event_name == "retrieval.completed" and payload.get("context_type") == "unknown"
+ for event_name, payload in patch_event_emit
+ )
+
+
+def test_session_lifecycle_datasource_emits_lifecycle_event(patch_event_emit):
+ """SessionLifecycleDataSource must emit `session.lifecycle` with bounded labels."""
+
+ session.SessionLifecycleDataSource.record_lifecycle(action="create", status="ok")
+ assert ("session.lifecycle", {"action": "create", "status": "ok"}) in patch_event_emit
+
+
+def test_session_lifecycle_datasource_ignores_non_positive_context_deltas(monkeypatch):
+ """SessionLifecycleDataSource must not emit when delta is non-positive."""
+
+ calls: list[tuple[str, dict]] = []
+
+ def _emit(event_name: str, payload: dict) -> None:
+ calls.append((str(event_name), dict(payload)))
+ raise RuntimeError("should not be called for non-positive deltas")
+
+ monkeypatch.setattr(session.EventMetricDataSource, "_emit", staticmethod(_emit))
+ session.SessionLifecycleDataSource.record_contexts_used(action="create", delta=0)
+ session.SessionLifecycleDataSource.record_contexts_used(action="create", delta=-1)
+ assert calls == []
+
+
+def test_session_lifecycle_datasource_emits_archive_event(patch_event_emit):
+ """SessionLifecycleDataSource must emit `session.archive` events."""
+
+ session.SessionLifecycleDataSource.record_archive(status="ok")
+ assert ("session.archive", {"status": "ok"}) in patch_event_emit
diff --git a/tests/metrics/datasources/test_event_emit.py b/tests/metrics/datasources/test_event_emit.py
deleted file mode 100644
index 4a63308ee..000000000
--- a/tests/metrics/datasources/test_event_emit.py
+++ /dev/null
@@ -1,25 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-from openviking.metrics.datasources.base import EventMetricDataSource
-from openviking.metrics.datasources.cache import CacheEventDataSource
-from openviking.metrics.datasources.http import HttpRequestLifecycleDataSource
-
-
-def test_event_datasources_use_shared_event_metric_datasource_emit(monkeypatch):
- calls: list[tuple[str, dict]] = []
-
- def _fake_emit(event_name: str, payload: dict) -> None:
- calls.append((str(event_name), dict(payload)))
-
- monkeypatch.setattr(EventMetricDataSource, "_emit", staticmethod(_fake_emit), raising=False)
-
- CacheEventDataSource.record_hit("L0")
- CacheEventDataSource.record_miss("L1")
- HttpRequestLifecycleDataSource.record_request(
- method="GET", route="/demo", status="200", duration_seconds=0.01
- )
-
- assert calls[0][0] == "cache.hit"
- assert calls[1][0] == "cache.miss"
- assert calls[2][0] == "http.request"
diff --git a/tests/metrics/datasources/test_retrieval.py b/tests/metrics/datasources/test_retrieval.py
deleted file mode 100644
index a74b97c9e..000000000
--- a/tests/metrics/datasources/test_retrieval.py
+++ /dev/null
@@ -1,43 +0,0 @@
-"""Module-level tests for `openviking.metrics.datasources.retrieval`."""
-
-from __future__ import annotations
-
-import openviking.metrics.datasources.retrieval as retrieval
-
-
-def test_retrieval_stats_datasource_emits_completed_event(patch_event_emit):
- """RetrievalStatsDataSource must emit a normalized `retrieval.completed` event payload."""
-
- retrieval.RetrievalStatsDataSource.record_retrieval(
- context_type="context_1",
- result_count=3,
- latency_seconds=0.12,
- rerank_used=True,
- rerank_fallback=False,
- )
-
- assert (
- "retrieval.completed",
- {
- "context_type": "context_1",
- "result_count": 3,
- "latency_seconds": 0.12,
- "rerank_used": True,
- "rerank_fallback": False,
- },
- ) in patch_event_emit
-
-
-def test_retrieval_stats_datasource_normalizes_unknown_context_type(patch_event_emit):
- """Empty/falsey context types are normalized to `unknown`."""
-
- retrieval.RetrievalStatsDataSource.record_retrieval(
- context_type="",
- result_count=0,
- latency_seconds=0.0,
- )
-
- assert any(
- event_name == "retrieval.completed" and payload.get("context_type") == "unknown"
- for event_name, payload in patch_event_emit
- )
diff --git a/tests/metrics/datasources/test_session.py b/tests/metrics/datasources/test_session.py
deleted file mode 100644
index ac7830981..000000000
--- a/tests/metrics/datasources/test_session.py
+++ /dev/null
@@ -1,34 +0,0 @@
-"""Module-level tests for `openviking.metrics.datasources.session`."""
-
-from __future__ import annotations
-
-import openviking.metrics.datasources.session as session
-
-
-def test_session_lifecycle_datasource_emits_lifecycle_event(patch_event_emit):
- """SessionLifecycleDataSource must emit `session.lifecycle` with bounded labels."""
-
- session.SessionLifecycleDataSource.record_lifecycle(action="create", status="ok")
- assert ("session.lifecycle", {"action": "create", "status": "ok"}) in patch_event_emit
-
-
-def test_session_lifecycle_datasource_ignores_non_positive_context_deltas(monkeypatch):
- """SessionLifecycleDataSource must not emit when delta is non-positive."""
-
- calls: list[tuple[str, dict]] = []
-
- def _emit(event_name: str, payload: dict) -> None:
- calls.append((str(event_name), dict(payload)))
- raise RuntimeError("should not be called for non-positive deltas")
-
- monkeypatch.setattr(session.EventMetricDataSource, "_emit", staticmethod(_emit))
- session.SessionLifecycleDataSource.record_contexts_used(action="create", delta=0)
- session.SessionLifecycleDataSource.record_contexts_used(action="create", delta=-1)
- assert calls == []
-
-
-def test_session_lifecycle_datasource_emits_archive_event(patch_event_emit):
- """SessionLifecycleDataSource must emit `session.archive` events."""
-
- session.SessionLifecycleDataSource.record_archive(status="ok")
- assert ("session.archive", {"status": "ok"}) in patch_event_emit
diff --git a/tests/metrics/datasources/test_probes.py b/tests/metrics/datasources/test_state_datasources.py
similarity index 54%
rename from tests/metrics/datasources/test_probes.py
rename to tests/metrics/datasources/test_state_datasources.py
index 0127e5a34..650ec92e6 100644
--- a/tests/metrics/datasources/test_probes.py
+++ b/tests/metrics/datasources/test_state_datasources.py
@@ -1,15 +1,115 @@
-"""Module-level tests for `openviking.metrics.datasources.probes`."""
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
from __future__ import annotations
+from pathlib import Path
from types import SimpleNamespace
import openviking.metrics.datasources.probes as probes
+from openviking.metrics.collectors.base import (
+ CollectorConfig,
+ ProbeMetricCollector,
+ StateMetricCollector,
+)
+from openviking.metrics.core.base import ReadEnvelope
+from openviking.metrics.core.registry import MetricRegistry
-def test_service_probe_datasource_reads_service_and_app_state_success():
- """ServiceProbeDataSource returns readiness booleans derived from service/app state."""
+class _EnvelopeStateCollector(StateMetricCollector):
+ config = CollectorConfig()
+ STALE_ON_ERROR = True
+
+ def __init__(self) -> None:
+ self.error_seen = False
+ self.value_seen = None
+
+ def read_metric_input(self):
+ return ReadEnvelope(ok=False, value=("fallback",))
+
+ def collect_hook(self, registry, metric_input) -> None:
+ self.value_seen = metric_input
+
+ def collect_stale_hook(self, registry, error: Exception) -> None:
+ self.error_seen = True
+
+
+class _EnvelopeProbeCollector(ProbeMetricCollector):
+ config = CollectorConfig()
+
+ def __init__(self) -> None:
+ self.error_seen = False
+ self.value_seen = None
+
+ def read_metric_input(self):
+ return ReadEnvelope(ok=False, value={"probe": True})
+
+ def collect_hook(self, registry, metric_input) -> None:
+ self.value_seen = metric_input
+
+ def collect_stale_hook(self, registry, error: Exception) -> None:
+ self.error_seen = True
+
+
+def test_metric_datasource_owns_safe_read_helpers_and_datasource_subclasses_reuse_them():
+ project_root = Path(__file__).resolve().parents[3]
+
+ core_base = (project_root / "openviking" / "metrics" / "core" / "base.py").read_text(
+ encoding="utf-8"
+ )
+ datasource_base = (
+ project_root / "openviking" / "metrics" / "datasources" / "base.py"
+ ).read_text(encoding="utf-8")
+ probes_text = (project_root / "openviking" / "metrics" / "datasources" / "probes.py").read_text(
+ encoding="utf-8"
+ )
+ encryption = (
+ project_root / "openviking" / "metrics" / "datasources" / "encryption.py"
+ ).read_text(encoding="utf-8")
+ model_usage = (
+ project_root / "openviking" / "metrics" / "datasources" / "model_usage.py"
+ ).read_text(encoding="utf-8")
+ observer_state = (
+ project_root / "openviking" / "metrics" / "datasources" / "observer_state.py"
+ ).read_text(encoding="utf-8")
+
+ assert "def safe_read(" in core_base
+ assert "def safe_read_async(" in core_base
+ assert "def best_effort(" not in datasource_base
+ assert "def best_effort_async(" not in datasource_base
+
+ assert "safe_value_probe(" in datasource_base
+ assert probes_text.count("safe_value_probe(") >= 1
+ assert encryption.count("safe_value_probe(") >= 1
+
+ assert '"available"' in model_usage
+ assert '"usage_by_model"' in model_usage
+ assert ".as_dict(" in model_usage
+ assert ".normalize_str(" in model_usage
+ assert ".as_dict(" in observer_state or ".normalize_str(" in observer_state
+
+def test_state_collector_unwraps_envelope_and_routes_ok_false_to_stale_hook():
+ registry = MetricRegistry()
+ collector = _EnvelopeStateCollector()
+
+ collector.collect(registry)
+
+ assert collector.error_seen is True
+ assert collector.value_seen is None
+
+
+def test_probe_collector_unwraps_envelope_and_routes_ok_false_to_stale_hook():
+ registry = MetricRegistry()
+ collector = _EnvelopeProbeCollector()
+
+ collector.collect(registry)
+
+ assert collector.error_seen is True
+ assert collector.value_seen is None
+
+
+def test_service_probe_datasource_reads_service_and_app_state_success():
app = SimpleNamespace(state=SimpleNamespace(api_key_manager=object()))
service = SimpleNamespace(initialized=True)
ds = probes.ServiceProbeDataSource(app=app, service=service)
@@ -21,8 +121,6 @@ def test_service_probe_datasource_reads_service_and_app_state_success():
def test_service_probe_datasource_returns_default_on_exception():
- """ServiceProbeDataSource must wrap exceptions into `ok=False` with deterministic default."""
-
class _BadApp:
@property
def state(self):
@@ -38,8 +136,6 @@ def test_service_probe_datasource_returns_default_on_exception():
def test_storage_probe_datasource_returns_agfs_probe_success(monkeypatch):
- """StorageProbeDataSource exposes a single `agfs` boolean probe on success."""
-
monkeypatch.setattr(probes, "get_viking_fs", lambda: SimpleNamespace(agfs=object()))
ds = probes.StorageProbeDataSource()
@@ -49,8 +145,6 @@ def test_storage_probe_datasource_returns_agfs_probe_success(monkeypatch):
def test_storage_probe_datasource_returns_default_on_exception(monkeypatch):
- """StorageProbeDataSource must return `ok=False` with `{agfs: False}` on read failure."""
-
def _boom():
raise RuntimeError("no fs")
@@ -64,8 +158,6 @@ def test_storage_probe_datasource_returns_default_on_exception(monkeypatch):
def test_retrieval_backend_probe_datasource_returns_false_when_no_service():
- """RetrievalBackendProbeDataSource treats missing wiring as a negative readiness (ok=True)."""
-
ds = probes.RetrievalBackendProbeDataSource(service=None)
env = ds.read_probe_state()
assert env.ok is True
@@ -73,8 +165,6 @@ def test_retrieval_backend_probe_datasource_returns_false_when_no_service():
def test_retrieval_backend_probe_datasource_returns_default_on_exception(monkeypatch):
- """RetrievalBackendProbeDataSource must return `ok=False` on health-check runner failures."""
-
class _VikingDB:
def health_check(self):
return object()
@@ -93,8 +183,6 @@ def test_retrieval_backend_probe_datasource_returns_default_on_exception(monkeyp
def test_model_provider_probe_datasource_returns_provider_tuple_success():
- """ModelProviderProbeDataSource must return provider name and a boolean ok flag."""
-
class _VlmCfg:
provider = "volcengine"
@@ -110,8 +198,6 @@ def test_model_provider_probe_datasource_returns_provider_tuple_success():
def test_model_provider_probe_datasource_returns_default_on_exception():
- """ModelProviderProbeDataSource must fall back to `unknown/False` on config failures."""
-
class _BadVlmCfg:
provider = "volcengine"
@@ -128,8 +214,6 @@ def test_model_provider_probe_datasource_returns_default_on_exception():
def test_async_system_probe_datasource_returns_queue_probe_success(monkeypatch):
- """AsyncSystemProbeDataSource returns a boolean `queue` probe based on queue manager wiring."""
-
monkeypatch.setattr(probes, "get_queue_manager", lambda: object())
ds = probes.AsyncSystemProbeDataSource()
@@ -139,8 +223,6 @@ def test_async_system_probe_datasource_returns_queue_probe_success(monkeypatch):
def test_async_system_probe_datasource_returns_default_on_exception(monkeypatch):
- """AsyncSystemProbeDataSource must return `ok=False` with `{queue: False}` on failures."""
-
def _boom():
raise RuntimeError("no queue")
diff --git a/tests/metrics/integration/test_account_dimension.py b/tests/metrics/integration/test_account_dimension.py
new file mode 100644
index 000000000..2cfc52640
--- /dev/null
+++ b/tests/metrics/integration/test_account_dimension.py
@@ -0,0 +1,262 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from openviking.metrics.account_context import (
+ bind_metric_account_context,
+ get_metric_account_context,
+ reset_metric_account_context,
+)
+from openviking.metrics.account_dimension import (
+ configure_metric_account_dimension,
+ reset_metric_account_dimension,
+)
+from openviking.metrics.collectors.base import EventMetricCollector
+from openviking.metrics.collectors.embedding import EmbeddingCollector
+from openviking.metrics.collectors.http import HTTPCollector
+from openviking.metrics.core.registry import MetricRegistry
+from openviking.metrics.datasources.base import EventMetricDataSource
+from openviking.metrics.exporters.prometheus import PrometheusExporter
+from openviking.metrics.http_middleware import create_http_metrics_middleware
+
+
+def test_metric_account_context_binds_and_resets_account_id():
+ """Binding a context must be observable via `get_metric_account_context()` and resettable."""
+ token = bind_metric_account_context(account_id="acct_123")
+ try:
+ assert get_metric_account_context().http_account_id == "acct_123"
+ finally:
+ reset_metric_account_context(token)
+
+ assert get_metric_account_context().http_account_id is None
+
+
+async def test_metric_account_context_is_isolated_per_task():
+ """Two concurrent tasks must not leak metric account context into each other."""
+
+ async def _worker(account_id: str, seen: list[str | None]):
+ token = bind_metric_account_context(account_id=account_id)
+ try:
+ await asyncio.sleep(0)
+ seen.append(get_metric_account_context().http_account_id)
+ finally:
+ reset_metric_account_context(token)
+
+ seen: list[str | None] = []
+ await asyncio.gather(_worker("acct_a", seen), _worker("acct_b", seen))
+ assert sorted(seen) == ["acct_a", "acct_b"]
+
+
+def test_http_collector_uses_unknown_account_when_unbound():
+ """When no context is bound, supported allowlisted metrics still resolve to `__unknown__`."""
+ registry = MetricRegistry()
+ configure_metric_account_dimension(
+ enabled=True,
+ metric_allowlist={
+ HTTPCollector.REQUESTS_TOTAL,
+ HTTPCollector.REQUEST_DURATION_SECONDS,
+ HTTPCollector.INFLIGHT_REQUESTS,
+ },
+ max_active_accounts=10,
+ )
+ collector = HTTPCollector()
+ collector.receive(
+ "http.request",
+ {
+ "method": "GET",
+ "route": "/items",
+ "status": "200",
+ "duration_seconds": 0.1,
+ },
+ registry,
+ )
+ reset_metric_account_dimension()
+
+ text = PrometheusExporter(registry=registry).render()
+ assert (
+ 'openviking_http_requests_total{account_id="__unknown__",method="GET",route="/items",status="200"} 1'
+ in text
+ )
+
+
+async def test_http_metrics_middleware_propagates_state_account_to_collector(monkeypatch):
+ """HTTP middleware must attach the authenticated account id to emitted http events."""
+ captured: list[tuple[str, dict]] = []
+ middleware = create_http_metrics_middleware()
+
+ def _fake_emit(event_name: str, payload: dict) -> None:
+ captured.append((event_name, dict(payload)))
+
+ monkeypatch.setattr(EventMetricDataSource, "_emit", staticmethod(_fake_emit), raising=False)
+
+ async def _call_next(request):
+ request.state.metric_account_id = "acct-mdw"
+ return SimpleNamespace(status_code=200)
+
+ from starlette.requests import Request
+
+ request = Request(
+ {
+ "type": "http",
+ "method": "GET",
+ "path": "/api/v1/resources",
+ "route": SimpleNamespace(path="/api/v1/resources"),
+ "headers": [],
+ "state": {},
+ }
+ )
+ await middleware(request, _call_next)
+
+ assert any(
+ event_name == "http.request" and payload.get("account_id") == "acct-mdw"
+ for event_name, payload in captured
+ )
+
+
+def test_account_dimension_injects_account_id_when_metric_allowlisted_exact():
+ """Allowlist exact match must inject the bound account id for supported metrics."""
+ registry = MetricRegistry()
+ configure_metric_account_dimension(
+ enabled=True,
+ metric_allowlist={EmbeddingCollector.CALLS_TOTAL},
+ max_active_accounts=10,
+ )
+ token = bind_metric_account_context(account_id="acct-embed-1")
+ try:
+ EmbeddingCollector().receive(
+ "embedding.call",
+ {
+ "provider": "openai",
+ "model_name": "text-embedding-3-large",
+ "duration_seconds": 0.1,
+ "prompt_tokens": 1,
+ "completion_tokens": 1,
+ },
+ registry,
+ )
+ finally:
+ reset_metric_account_context(token)
+ reset_metric_account_dimension()
+
+ text = PrometheusExporter(registry=registry).render()
+ assert 'openviking_embedding_calls_total{account_id="acct-embed-1",' in text
+
+
+def test_account_dimension_injects_account_id_when_metric_allowlisted_by_prefix():
+ """Allowlist prefix match (trailing '*') must inject the bound account id."""
+ registry = MetricRegistry()
+ configure_metric_account_dimension(
+ enabled=True,
+ metric_allowlist={"openviking_embedding_*"},
+ max_active_accounts=10,
+ )
+ token = bind_metric_account_context(account_id="acct-embed-2")
+ try:
+ EmbeddingCollector().receive(
+ "embedding.success",
+ {"latency_seconds": 0.2},
+ registry,
+ )
+ finally:
+ reset_metric_account_context(token)
+ reset_metric_account_dimension()
+
+ text = PrometheusExporter(registry=registry).render()
+ assert (
+ 'openviking_embedding_requests_total{account_id="acct-embed-2",status="ok"} 1' in text
+ or 'openviking_embedding_requests_total{account_id="acct-embed-2",status="ok"} 1.0' in text
+ )
+
+
+def test_account_dimension_returns_overflow_when_max_active_accounts_exceeded():
+ """When active accounts exceed the cap, new accounts resolve to `__overflow__`."""
+ registry = MetricRegistry()
+ configure_metric_account_dimension(
+ enabled=True,
+ metric_allowlist={EmbeddingCollector.CALLS_TOTAL},
+ max_active_accounts=2,
+ )
+ try:
+ for account_id in ("acct-a", "acct-b", "acct-c"):
+ token = bind_metric_account_context(account_id=account_id)
+ try:
+ EmbeddingCollector().receive(
+ "embedding.call",
+ {
+ "provider": "openai",
+ "model_name": "text-embedding-3-large",
+ "duration_seconds": 0.01,
+ "prompt_tokens": 1,
+ "completion_tokens": 0,
+ },
+ registry,
+ )
+ finally:
+ reset_metric_account_context(token)
+ finally:
+ reset_metric_account_dimension()
+
+ text = PrometheusExporter(registry=registry).render()
+ assert 'openviking_embedding_calls_total{account_id="__overflow__",' in text
+ assert 'account_id="acct-c"' not in text
+
+
+def test_account_dimension_returns_unknown_for_not_allowlisted_metric_even_with_context():
+ """Enabled account-dimension still resolves to `__unknown__` when metric is not allowlisted."""
+ registry = MetricRegistry()
+ configure_metric_account_dimension(
+ enabled=True,
+ metric_allowlist={HTTPCollector.REQUESTS_TOTAL},
+ max_active_accounts=10,
+ )
+ token = bind_metric_account_context(account_id="acct-x")
+ try:
+ EmbeddingCollector().receive(
+ "embedding.success",
+ {"latency_seconds": 0.01},
+ registry,
+ )
+ finally:
+ reset_metric_account_context(token)
+ reset_metric_account_dimension()
+
+ text = PrometheusExporter(registry=registry).render()
+ assert (
+ 'openviking_embedding_requests_total{account_id="__unknown__",status="ok"} 1' in text
+ or 'openviking_embedding_requests_total{account_id="__unknown__",status="ok"} 1.0' in text
+ )
+
+
+def test_account_dimension_does_not_inject_account_id_for_unsupported_metric_names():
+ """Metrics outside the supported set must never receive `account_id` label injection."""
+
+ class DummyCollector(EventMetricCollector):
+ SUPPORTED_EVENTS = frozenset({"demo"})
+
+ def receive_hook(self, event_name: str, payload: dict, registry) -> None:
+ registry.inc_counter("openviking_unsupported_total")
+
+ registry = MetricRegistry()
+ configure_metric_account_dimension(
+ enabled=True,
+ metric_allowlist={"openviking_unsupported_total"},
+ max_active_accounts=10,
+ )
+ token = bind_metric_account_context(account_id="acct-z")
+ try:
+ DummyCollector().receive("demo", {}, registry)
+ finally:
+ reset_metric_account_context(token)
+ reset_metric_account_dimension()
+
+ text = PrometheusExporter(registry=registry).render()
+ assert "openviking_unsupported_total{" not in text
+ assert "openviking_unsupported_total 1" in text
diff --git a/tests/metrics/wiring/test_resource_ingestion_datasource_wiring.py b/tests/metrics/integration/test_bootstrap.py
similarity index 60%
rename from tests/metrics/wiring/test_resource_ingestion_datasource_wiring.py
rename to tests/metrics/integration/test_bootstrap.py
index 86a1d5727..1226db7ee 100644
--- a/tests/metrics/wiring/test_resource_ingestion_datasource_wiring.py
+++ b/tests/metrics/integration/test_bootstrap.py
@@ -1,6 +1,13 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+import openviking.metrics.bootstrap as bootstrap
from openviking.metrics.account_dimension import (
configure_metric_account_dimension,
reset_metric_account_dimension,
@@ -12,6 +19,51 @@ from openviking.metrics.datasources.resource import ResourceIngestionEventDataSo
from openviking.metrics.exporters.prometheus import PrometheusExporter
+def test_create_default_collector_manager_registers_expected_collectors_in_order():
+ manager = bootstrap.create_default_collector_manager(app=None, service=None)
+
+ names = [type(c).__name__ for c in manager._collectors]
+ assert names == [
+ "QueueCollector",
+ "TaskTrackerCollector",
+ "ObserverHealthCollector",
+ "ObserverStateCollector",
+ "LockCollector",
+ "VikingDBCollector",
+ "ModelUsageCollector",
+ "ServiceProbeCollector",
+ "StorageProbeCollector",
+ "RetrievalBackendProbeCollector",
+ "ModelProviderProbeCollector",
+ "AsyncSystemProbeCollector",
+ "EncryptionProbeCollector",
+ ]
+
+
+def test_create_default_collector_manager_propagates_construction_failures(monkeypatch):
+ def _boom():
+ raise RuntimeError("cannot init datasource")
+
+ monkeypatch.setattr(bootstrap, "QueuePipelineStateDataSource", _boom)
+ with pytest.raises(RuntimeError, match="cannot init datasource"):
+ bootstrap.create_default_collector_manager(app=None, service=None)
+
+
+def test_optional_cache_datasource_instrumentation_is_wired_into_key_call_sites():
+ project_root = Path(__file__).resolve().parents[3]
+ targets = [
+ project_root / "openviking" / "storage" / "queuefs" / "semantic_dag.py",
+ project_root / "openviking" / "storage" / "queuefs" / "semantic_processor.py",
+ project_root / "openviking" / "session" / "memory" / "extract_loop.py",
+ ]
+ missing = []
+ for path in targets:
+ text = path.read_text(encoding="utf-8")
+ if "CacheEventDataSource.record_" not in text:
+ missing.append(path.name)
+ assert missing == []
+
+
def test_resource_ingestion_event_datasource_can_drive_resource_ingestion_collector(monkeypatch):
registry = MetricRegistry()
collector = ResourceIngestionCollector()
diff --git a/tests/metrics/account/test_integration.py b/tests/metrics/integration/test_http_metrics.py
similarity index 73%
rename from tests/metrics/account/test_integration.py
rename to tests/metrics/integration/test_http_metrics.py
index 6b8834bd7..1af2b5334 100644
--- a/tests/metrics/account/test_integration.py
+++ b/tests/metrics/integration/test_http_metrics.py
@@ -1,7 +1,7 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
-"""Integration-oriented tests for account-aware metric writes."""
+from __future__ import annotations
from types import SimpleNamespace
@@ -13,17 +13,11 @@ from openviking.metrics.account_context import (
bind_metric_account_context,
reset_metric_account_context,
)
-from openviking.metrics.account_dimension import MetricAccountDimensionPolicy
-from openviking.metrics.collectors.embedding import EmbeddingCollector
from openviking.metrics.collectors.http import HTTPCollector
-from openviking.metrics.collectors.task_tracker import TaskTrackerCollector
-from openviking.metrics.collectors.vlm import VLMCollector
from openviking.metrics.core.registry import MetricRegistry
from openviking.metrics.datasources.base import EventMetricDataSource
from openviking.metrics.datasources.http import HttpRequestLifecycleDataSource
-from openviking.metrics.datasources.model_usage import (
- VLMEventDataSource,
-)
+from openviking.metrics.datasources.model_usage import VLMEventDataSource
from openviking.metrics.exporters.prometheus import PrometheusExporter
from openviking.metrics.global_api import configure_metric_account_dimension, shutdown_metrics
from openviking.metrics.http_middleware import (
@@ -39,15 +33,13 @@ from openviking.models.vlm.base import VLMBase
def test_http_collector_emits_account_label():
registry = MetricRegistry()
configure_metric_account_dimension(
- policy=MetricAccountDimensionPolicy(
- enabled=True,
- metric_allowlist={
- HTTPCollector.REQUESTS_TOTAL,
- HTTPCollector.REQUEST_DURATION_SECONDS,
- HTTPCollector.INFLIGHT_REQUESTS,
- },
- max_active_accounts=10,
- )
+ enabled=True,
+ metric_allowlist={
+ HTTPCollector.REQUESTS_TOTAL,
+ HTTPCollector.REQUEST_DURATION_SECONDS,
+ HTTPCollector.INFLIGHT_REQUESTS,
+ },
+ max_active_accounts=10,
)
collector = HTTPCollector()
@@ -74,38 +66,6 @@ def test_http_collector_emits_account_label():
)
-def test_state_collector_emits_unknown_when_metric_not_allowlisted(monkeypatch):
- class DummyTracker:
- def snapshot_counts_by_type(self):
- return {
- "session_commit": {"pending": 1, "running": 0, "completed": 0, "failed": 0},
- }
-
- import openviking.metrics.datasources.task as task_datasource_module
- from openviking.metrics.datasources.task import TaskStateDataSource
-
- monkeypatch.setattr(task_datasource_module, "get_task_tracker", lambda: DummyTracker())
- configure_metric_account_dimension(
- policy=MetricAccountDimensionPolicy(
- enabled=True,
- metric_allowlist={HTTPCollector.REQUESTS_TOTAL},
- max_active_accounts=10,
- )
- )
- registry = MetricRegistry()
- collector = TaskTrackerCollector(data_source=TaskStateDataSource())
-
- token = bind_metric_account_context(account_id="acct-9")
- try:
- collector.collect(registry)
- finally:
- reset_metric_account_context(token)
- shutdown_metrics(app=None)
-
- text = PrometheusExporter(registry=registry).render()
- assert 'openviking_task_pending{task_type="session_commit"} 1.0' in text
-
-
def test_http_request_datasource_propagates_explicit_account_id(monkeypatch):
captured: list[tuple[str, dict]] = []
@@ -149,77 +109,6 @@ def test_http_request_datasource_propagates_explicit_account_id(monkeypatch):
]
-def test_vlm_collector_uses_explicit_account_id_from_payload():
- registry = MetricRegistry()
- configure_metric_account_dimension(
- policy=MetricAccountDimensionPolicy(
- enabled=True,
- metric_allowlist={
- VLMCollector.CALLS_TOTAL,
- VLMCollector.CALL_DURATION_SECONDS,
- VLMCollector.TOKENS_INPUT_TOTAL,
- VLMCollector.TOKENS_OUTPUT_TOTAL,
- VLMCollector.TOKENS_TOTAL,
- },
- max_active_accounts=10,
- )
- )
-
- VLMCollector().receive(
- "vlm.call",
- {
- "provider": "volcengine",
- "model_name": "m1",
- "duration_seconds": 1.2,
- "prompt_tokens": 10,
- "completion_tokens": 5,
- "account_id": "acct-vlm",
- },
- registry,
- )
- text = PrometheusExporter(registry=registry).render()
- shutdown_metrics(app=None)
-
- assert (
- 'openviking_vlm_calls_total{account_id="acct-vlm",model_name="m1",provider="volcengine"} 1'
- in text
- )
-
-
-def test_embedding_collector_uses_explicit_account_id_from_payload():
- registry = MetricRegistry()
- configure_metric_account_dimension(
- policy=MetricAccountDimensionPolicy(
- enabled=True,
- metric_allowlist={
- EmbeddingCollector.REQUESTS_TOTAL,
- EmbeddingCollector.LATENCY_SECONDS,
- EmbeddingCollector.ERRORS_TOTAL,
- },
- max_active_accounts=10,
- )
- )
-
- collector = EmbeddingCollector()
- collector.receive(
- "embedding.success",
- {"latency_seconds": 0.6, "account_id": "acct-embed"},
- registry,
- )
- collector.receive(
- "embedding.error",
- {"error_code": "timeout", "account_id": "acct-embed"},
- registry,
- )
- text = PrometheusExporter(registry=registry).render()
- shutdown_metrics(app=None)
-
- assert 'openviking_embedding_requests_total{account_id="acct-embed",status="ok"} 1' in text
- assert (
- 'openviking_embedding_errors_total{account_id="acct-embed",error_code="timeout"} 1' in text
- )
-
-
def test_extract_request_account_id_prefers_authenticated_request_state():
request = Request(
{
diff --git a/tests/metrics/wiring/test_telemetry_bridge.py b/tests/metrics/integration/test_telemetry_bridge.py
similarity index 80%
rename from tests/metrics/wiring/test_telemetry_bridge.py
rename to tests/metrics/integration/test_telemetry_bridge.py
index c27a7ce09..fc736441c 100644
--- a/tests/metrics/wiring/test_telemetry_bridge.py
+++ b/tests/metrics/integration/test_telemetry_bridge.py
@@ -3,12 +3,12 @@
from openviking.metrics.datasources.telemetry_bridge import TelemetryBridgeEventDataSource
from openviking.metrics.global_api import init_metrics_from_server_config, shutdown_metrics
-from openviking.server.config import PrometheusConfig, ServerConfig, TelemetryConfig
+from openviking.server.config import MetricsConfig, ObservabilityConfig, ServerConfig
def test_telemetry_bridge_records_operation_and_resource_metrics(registry, render_prometheus):
init_metrics_from_server_config(
- ServerConfig(telemetry=TelemetryConfig(prometheus=PrometheusConfig(enabled=True))),
+ ServerConfig(observability=ObservabilityConfig(metrics=MetricsConfig(enabled=True))),
app=None,
registry=registry,
)
@@ -18,7 +18,15 @@ def test_telemetry_bridge_records_operation_and_resource_metrics(registry, rende
"operation": "resource.process",
"status": "ok",
"duration_ms": 1200,
- "tokens": {"total": 10, "llm": {"input": 3, "output": 7}},
+ "tokens": {
+ "total": 14,
+ "llm": {"input": 3, "output": 7},
+ "rerank": {"total": 4},
+ "stages": {
+ "vlm": {"llm": {"input": 3, "output": 7, "total": 10}},
+ "rerank": {"rerank": {"total": 4}},
+ },
+ },
"vector": {"searches": 1, "scored": 2, "passed": 2, "returned": 1, "scanned": 9},
"memory": {"extracted": 4},
"semantic_nodes": {"OK": 12},
@@ -43,6 +51,10 @@ def test_telemetry_bridge_records_operation_and_resource_metrics(registry, rende
'openviking_operation_duration_seconds_count{account_id="__unknown__",operation="resource.process",status="ok"} 1'
in text
)
+ assert (
+ 'openviking_operation_tokens_total{account_id="__unknown__",operation="resource.process",stage="rerank",token_type="rerank"} 4'
+ in text
+ )
assert 'openviking_vector_searches_total{operation="resource.process"} 1' in text
assert 'openviking_memory_extracted_total{operation="resource.process"} 4' in text
assert (
@@ -63,7 +75,7 @@ def test_telemetry_bridge_records_operation_and_resource_metrics(registry, rende
def test_telemetry_bridge_semantic_nodes_total_is_cumulative(registry, render_prometheus):
init_metrics_from_server_config(
- ServerConfig(telemetry=TelemetryConfig(prometheus=PrometheusConfig(enabled=True))),
+ ServerConfig(observability=ObservabilityConfig(metrics=MetricsConfig(enabled=True))),
app=None,
registry=registry,
)
diff --git a/tests/metrics/wiring/test_bootstrap.py b/tests/metrics/wiring/test_bootstrap.py
deleted file mode 100644
index 63793c82b..000000000
--- a/tests/metrics/wiring/test_bootstrap.py
+++ /dev/null
@@ -1,44 +0,0 @@
-"""Module-level tests for `openviking.metrics.bootstrap`."""
-
-from __future__ import annotations
-
-import pytest
-
-import openviking.metrics.bootstrap as bootstrap
-
-
-def test_create_default_collector_manager_registers_expected_collectors_in_order():
- """Default bootstrap must register a stable collector sequence for `/metrics` refresh."""
- manager = bootstrap.create_default_collector_manager(app=None, service=None)
-
- names = [type(c).__name__ for c in manager._collectors] # noqa: SLF001 (intentional white-box)
- assert names == [
- "QueueCollector",
- "TaskTrackerCollector",
- "ObserverHealthCollector",
- "ObserverStateCollector",
- "LockCollector",
- "VikingDBCollector",
- "ModelUsageCollector",
- "ServiceProbeCollector",
- "StorageProbeCollector",
- "RetrievalBackendProbeCollector",
- "ModelProviderProbeCollector",
- "AsyncSystemProbeCollector",
- "EncryptionProbeCollector",
- ]
-
-
-def test_create_default_collector_manager_propagates_construction_failures(monkeypatch):
- """
- If a required datasource fails to construct, bootstrap should fail fast.
-
- This protects the server from silently starting with a partially wired metrics stack.
- """
-
- def _boom():
- raise RuntimeError("cannot init datasource")
-
- monkeypatch.setattr(bootstrap, "QueuePipelineStateDataSource", _boom)
- with pytest.raises(RuntimeError, match="cannot init datasource"):
- bootstrap.create_default_collector_manager(app=None, service=None)
diff --git a/tests/metrics/wiring/test_optional_instrumentation_call_sites.py b/tests/metrics/wiring/test_optional_instrumentation_call_sites.py
deleted file mode 100644
index fd3eb74e6..000000000
--- a/tests/metrics/wiring/test_optional_instrumentation_call_sites.py
+++ /dev/null
@@ -1,20 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-from pathlib import Path
-
-
-def test_optional_cache_datasource_instrumentation_is_wired_into_key_call_sites():
- # This test reads source files by absolute path; keep it stable across test subdirectories.
- project_root = Path(__file__).resolve().parents[3]
- targets = [
- project_root / "openviking" / "storage" / "queuefs" / "semantic_dag.py",
- project_root / "openviking" / "storage" / "queuefs" / "semantic_processor.py",
- project_root / "openviking" / "session" / "memory" / "extract_loop.py",
- ]
- missing = []
- for path in targets:
- text = path.read_text(encoding="utf-8")
- if "CacheEventDataSource.record_" not in text:
- missing.append(path.name)
- assert missing == []
diff --git a/tests/test_telemetry_runtime.py b/tests/test_telemetry_runtime.py
index 27ba89fab..aa1ae9219 100644
--- a/tests/test_telemetry_runtime.py
+++ b/tests/test_telemetry_runtime.py
@@ -3,13 +3,15 @@
from __future__ import annotations
+import asyncio
import json
from types import SimpleNamespace
import pytest
from openviking.metrics.account_context import get_metric_account_context
-from openviking.models.embedder.base import EmbedResult
+from openviking.models.embedder.base import EmbedResult, embed_compat
+from openviking.models.vlm.base import VLMBase
from openviking.server.identity import RequestContext, Role
from openviking.service.resource_service import ResourceService
from openviking.storage.collection_schemas import TextEmbeddingHandler
@@ -23,7 +25,7 @@ from openviking.telemetry import (
unregister_telemetry,
)
from openviking.telemetry.backends.memory import MemoryOperationTelemetry
-from openviking.telemetry.context import bind_telemetry
+from openviking.telemetry.context import bind_telemetry, bind_telemetry_stage
from openviking.telemetry.snapshot import TelemetrySnapshot
from openviking_cli.session.user_id import UserIdentifier
@@ -76,6 +78,94 @@ def test_telemetry_summary_breaks_down_llm_and_embedding_token_usage():
assert "errors" not in summary
+def test_telemetry_summary_breaks_down_stage_token_usage():
+ telemetry = MemoryOperationTelemetry(operation="search.find", enabled=True)
+ telemetry.record_token_usage("embedding", 11, 0, stage="embed_query")
+ telemetry.record_token_usage("rerank", 7, 0, stage="rerank")
+ telemetry.record_token_usage("llm", 5, 3, stage="vlm")
+
+ summary = telemetry.finish().summary
+
+ assert summary["tokens"]["total"] == 26
+ assert summary["tokens"]["rerank"] == {"total": 7}
+ assert summary["tokens"]["stages"]["embed_query"]["embedding"] == {"total": 11}
+ assert summary["tokens"]["stages"]["rerank"]["rerank"] == {"total": 7}
+ assert summary["tokens"]["stages"]["vlm"]["llm"] == {
+ "input": 5,
+ "output": 3,
+ "total": 8,
+ }
+
+
+async def test_bind_telemetry_stage_propagates_across_async_tasks():
+ telemetry = MemoryOperationTelemetry(operation="resource.process", enabled=True)
+
+ async def _worker() -> None:
+ await asyncio.sleep(0)
+ get_current_telemetry().add_token_usage(6, 4)
+
+ with bind_telemetry(telemetry):
+ with bind_telemetry_stage("resource_summarize"):
+ await asyncio.create_task(_worker())
+
+ summary = telemetry.finish().summary
+ assert summary["tokens"]["stages"]["resource_summarize"]["llm"] == {
+ "input": 6,
+ "output": 4,
+ "total": 10,
+ }
+
+
+async def test_embed_compat_binds_query_stage_for_embedding_tokens():
+ telemetry = MemoryOperationTelemetry(operation="search.find", enabled=True)
+
+ class _TelemetryAwareAsyncEmbedder:
+ async def embed_async(self, text: str, is_query: bool = False) -> EmbedResult:
+ assert text == "hello"
+ assert is_query is True
+ get_current_telemetry().record_token_usage("embedding", 9, 0)
+ return EmbedResult(dense_vector=[0.1, 0.2])
+
+ with bind_telemetry(telemetry):
+ await embed_compat(_TelemetryAwareAsyncEmbedder(), "hello", is_query=True)
+
+ summary = telemetry.finish().summary
+ assert summary["tokens"]["stages"]["embed_query"]["embedding"] == {"total": 9}
+
+
+def test_vlm_base_defaults_operation_tokens_to_vlm_stage():
+ class _DummyVLM(VLMBase):
+ def get_completion(self, *args, **kwargs):
+ raise NotImplementedError()
+
+ async def get_completion_async(self, *args, **kwargs):
+ raise NotImplementedError()
+
+ def get_vision_completion(self, *args, **kwargs):
+ raise NotImplementedError()
+
+ async def get_vision_completion_async(self, *args, **kwargs):
+ raise NotImplementedError()
+
+ telemetry = MemoryOperationTelemetry(operation="session.commit", enabled=True)
+ with bind_telemetry(telemetry):
+ _DummyVLM({"provider": "openai", "model": "gpt-4o-mini"}).update_token_usage(
+ model_name="gpt-4o-mini",
+ provider="openai",
+ prompt_tokens=7,
+ completion_tokens=5,
+ )
+
+ summary = telemetry.finish().summary
+ assert summary["tokens"]["stages"]["vlm"]["llm"] == {
+ "input": 7,
+ "output": 5,
+ "total": 12,
+ }
+
+
def test_disabled_telemetry_still_has_request_id():
telemetry = MemoryOperationTelemetry(operation="resources.add_resource", enabled=False)
@@ -227,8 +317,9 @@ async def test_embedding_handler_binds_registered_operation_telemetry(monkeypatc
register_telemetry(telemetry)
class _TelemetryAwareEmbedder:
- def embed(self, text: str) -> EmbedResult:
+ def embed(self, text: str, is_query: bool = False) -> EmbedResult:
assert text == "hello"
+ assert is_query is False
get_current_telemetry().record_token_usage("embedding", 9, 0)
return EmbedResult(dense_vector=[0.1, 0.2])