Skip to content

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

feat(metric): export ragfs metrics to python observability system (#5041)

baojun-zhange04f4360df55
diff --git a/crates/ragfs-python/src/lib.rs b/crates/ragfs-python/src/lib.rs
index 5f0cef2fa..e2e4ecf38 100644
--- a/crates/ragfs-python/src/lib.rs
+++ b/crates/ragfs-python/src/lib.rs
@@ -212,6 +212,7 @@ use ragfs::lock::{
BorrowedPathLockLease, OwnedPathLockLease, PathLockConfig, PathLockHandoffRef, PathLockKind,
PathLockManager, PathLockRequest,
};
+use ragfs::metrics::{RagfsMetric, RagfsMetricValue};
/// Parse an optional listing sort field and return the matching RagFS value.
fn parse_list_sort_by(value: Option<&str>) -> PyResult<Option<ListSortBy>> {
@@ -489,12 +490,9 @@ fn pathlock_config_from_value(value: &serde_json::Value) -> Result<PathLockConfi
}
}
- let lock_timeout_secs =
- f64_field(pathlock, "lock_timeout_secs", 0.0)?;
+ let lock_timeout_secs = f64_field(pathlock, "lock_timeout_secs", 0.0)?;
if !lock_timeout_secs.is_finite() || lock_timeout_secs < 0.0 {
- return Err(
- "pathlock.lock_timeout_secs must be a finite non-negative number".to_string(),
- );
+ return Err("pathlock.lock_timeout_secs must be a finite non-negative number".to_string());
}
let lock_expire_secs = f64_field(pathlock, "lock_expire_secs", 30.0)?;
if !lock_expire_secs.is_finite() || lock_expire_secs < 1.0 {
@@ -532,8 +530,7 @@ fn cache_config_from_ov_conf_with_runtime(
fn cache_config_from_canonical_ov_conf(
json: &serde_json::Value,
) -> Result<RagfsCacheConfig, String> {
- let pathlock_uses_cache =
- pathlock_config_from_canonical_ov_conf(json)?.provider == "cache";
+ let pathlock_uses_cache = pathlock_config_from_canonical_ov_conf(json)?.provider == "cache";
cache_config_from_canonical_ov_conf_with_runtime(json, pathlock_uses_cache)
}
@@ -1078,14 +1075,54 @@ fn grep_result_to_py_dict(py: Python<'_>, result: &GrepResult) -> PyResult<Py<Py
Ok(dict.into())
}
-/// Convert OperationStats to a Python dict.
+/// Convert the supplied native statistics into the legacy microsecond Python dict.
fn operation_stats_to_py_dict(py: Python<'_>, stats: &OperationStats) -> PyResult<Py<PyDict>> {
let dict = PyDict::new(py);
dict.set_item("count", stats.count)?;
- dict.set_item("total_time_us", stats.total_time_us)?;
- dict.set_item("min_time_us", stats.min_time_us)?;
- dict.set_item("max_time_us", stats.max_time_us)?;
- dict.set_item("avg_time_us", stats.avg_time_us())?;
+ dict.set_item("total_time_us", stats.total_time_ns / 1_000)?;
+ dict.set_item(
+ "min_time_us",
+ if stats.count == 0 {
+ u64::MAX
+ } else {
+ stats.min_time_ns / 1_000
+ },
+ )?;
+ dict.set_item("max_time_us", stats.max_time_ns / 1_000)?;
+ dict.set_item("avg_time_us", stats.avg_time_ns() / 1_000.0)?;
+ Ok(dict.into())
+}
+
+/// Convert the supplied native metric into a flat Python dict, preserving integer values.
+fn metric_to_py_dict(py: Python<'_>, metric: &RagfsMetric) -> PyResult<Py<PyDict>> {
+ let dict = PyDict::new(py);
+ dict.set_item("name", &metric.name)?;
+ dict.set_item("labels", &metric.labels)?;
+ match &metric.value {
+ RagfsMetricValue::Counter { value, scale } => {
+ dict.set_item("type", "counter")?;
+ dict.set_item("value", value)?;
+ dict.set_item("scale", scale)?;
+ }
+ RagfsMetricValue::Gauge(value) => {
+ dict.set_item("type", "gauge")?;
+ dict.set_item("value", value)?;
+ }
+ RagfsMetricValue::Histogram {
+ bucket_bounds,
+ bucket_counts,
+ count,
+ sum,
+ scale,
+ } => {
+ dict.set_item("type", "histogram")?;
+ dict.set_item("bucket_bounds", bucket_bounds)?;
+ dict.set_item("bucket_counts", bucket_counts)?;
+ dict.set_item("count", count)?;
+ dict.set_item("sum", sum)?;
+ dict.set_item("scale", scale)?;
+ }
+ }
Ok(dict.into())
}
@@ -1523,8 +1560,8 @@ impl RAGFSBindingClient {
}
if let Some(pl_obj) = cfg.get("pathlock") {
let pl_value = py_to_json_value(pl_obj.bind(py))?;
- ragfs_cfg.pathlock = pathlock_config_from_value(&pl_value)
- .map_err(PyValueError::new_err)?;
+ ragfs_cfg.pathlock =
+ pathlock_config_from_value(&pl_value).map_err(PyValueError::new_err)?;
}
}
@@ -2905,6 +2942,20 @@ impl RAGFSBindingClient {
})
}
+ /// Read all native metrics with no arguments and return a list of flat Python dicts.
+ fn metrics(&self, py: Python<'_>) -> PyResult<Py<PyList>> {
+ let fs = self.mountable.clone();
+ let metrics = py_detach_blocking(py, move || {
+ self.rt.block_on(async move { fs.metrics().await })
+ })
+ .map_err(to_py_err)?;
+ let result = PyList::empty(py);
+ for metric in &metrics {
+ result.append(metric_to_py_dict(py, metric)?)?;
+ }
+ Ok(result.into())
+ }
+
/// Get filesystem statistics.
///
/// Args:
diff --git a/crates/ragfs/src/core/mountable.rs b/crates/ragfs/src/core/mountable.rs
index a6c1bda4a..0a9df8537 100644
--- a/crates/ragfs/src/core/mountable.rs
+++ b/crates/ragfs/src/core/mountable.rs
@@ -14,6 +14,9 @@ use tokio::sync::RwLock;
use tracing::warn;
use crate::lock::{AutoPathLockAction, PathLockKind, PathLockManager, PathLockRequest};
+use crate::metrics::{
+ lock_metrics, merge_metrics, operation_metrics, RagfsMetric, RagfsMetricValue,
+};
use crate::multibackend::factory::build_multi_write_fs;
use crate::multibackend::types::MultiBackendBuildContext;
use crate::plugins::QueueFileSystem;
@@ -595,6 +598,55 @@ impl MountableFS {
result
}
+ /// Read current mount and lock collectors; return merged, sorted native metrics or an error.
+ pub async fn metrics(&self) -> Result<Vec<RagfsMetric>> {
+ let mut mounts: Vec<_> = {
+ let mounts = self.mounts.read().await;
+ mounts.iter().map(|(_, info)| info.clone()).collect()
+ };
+ mounts.sort_by(|a, b| a.path.cmp(&b.path));
+
+ let mut metrics = Vec::new();
+ for mount in mounts {
+ metrics.extend(operation_metrics(
+ &mount.plugin_name,
+ &mount.stats.snapshot().await,
+ ));
+ #[cfg(feature = "cache")]
+ if let Some(cache) = Self::as_cached(&mount.fs) {
+ metrics.extend(crate::metrics::cache_metrics(cache.metrics().snapshot()));
+ }
+ if let Some(multiwrite) = Self::as_multiwrite(&mount.fs) {
+ metrics.push(RagfsMetric {
+ name: "ragfs_multiwrite_background_tasks".into(),
+ labels: Default::default(),
+ value: RagfsMetricValue::Gauge(multiwrite.background_task_count() as f64),
+ });
+ let routes = multiwrite.inner.read_route_metrics();
+ for (route, key) in [
+ ("primary", "primary_hits"),
+ ("backup", "backup_hits"),
+ ("redirect", "redirect_hits"),
+ ("miss", "misses"),
+ ] {
+ let count = routes[key].as_u64().ok_or_else(|| {
+ Error::internal(format!("invalid read-route counter '{key}'"))
+ })?;
+ metrics.push(RagfsMetric::counter(
+ "ragfs_multiwrite_read_routes_total",
+ &[("route", route)],
+ count,
+ 1.0,
+ ));
+ }
+ }
+ }
+ if let Some(manager) = self.pathlock_manager.get() {
+ metrics.extend(lock_metrics(manager.metrics_snapshot().await));
+ }
+ merge_metrics(metrics)
+ }
+
/// Read raw bytes from the underlying plugin backend, bypassing the encryption layer.
///
/// Used by tests to verify ciphertext on disk and by cp/persist for verbatim blob copies.
diff --git a/crates/ragfs/src/core/multibackend_wrapper.rs b/crates/ragfs/src/core/multibackend_wrapper.rs
index b0b89777d..a72f84de1 100644
--- a/crates/ragfs/src/core/multibackend_wrapper.rs
+++ b/crates/ragfs/src/core/multibackend_wrapper.rs
@@ -573,6 +573,11 @@ impl MultiWriteWrappedFSBuilder {
}
impl MultiWriteWrappedFS {
+ /// Return this wrapper's current background task count without scanning metadata.
+ pub(crate) fn background_task_count(&self) -> usize {
+ self.inner.background_tasks.load(Ordering::SeqCst)
+ }
+
/// Start building a multi-write wrapper from a primary backend.
pub fn builder(primary_backend: Arc<dyn FileSystem>) -> MultiWriteWrappedFSBuilder {
MultiWriteWrappedFSBuilder {
diff --git a/crates/ragfs/src/core/stats.rs b/crates/ragfs/src/core/stats.rs
index 0a626c7c5..6907babee 100644
--- a/crates/ragfs/src/core/stats.rs
+++ b/crates/ragfs/src/core/stats.rs
@@ -92,50 +92,67 @@ impl FsOperation {
}
}
+/// Inclusive upper bounds for operation duration buckets, in nanoseconds.
+pub const DURATION_BUCKET_BOUNDS_NS: [u64; 11] = [
+ 100_000, 500_000, 1_000_000, 5_000_000, 10_000_000, 50_000_000,
+ 100_000_000, 500_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000,
+];
+
/// Statistics for a single operation type
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OperationStats {
/// Number of times the operation was called
pub count: u64,
- /// Total time spent on this operation (microseconds)
- pub total_time_us: u64,
- /// Minimum time spent (microseconds)
- pub min_time_us: u64,
- /// Maximum time spent (microseconds)
- pub max_time_us: u64,
+ /// Number of successful operations.
+ pub success_count: u64,
+ /// Number of failed operations.
+ pub error_count: u64,
+ /// Total time spent on this operation (nanoseconds).
+ pub total_time_ns: u64,
+ /// Minimum time spent (nanoseconds); u64::MAX when count is zero.
+ pub min_time_ns: u64,
+ /// Maximum time spent (nanoseconds).
+ pub max_time_ns: u64,
+ /// Noncumulative duration counts; the last bucket holds overflow samples.
+ pub duration_bucket_counts: [u64; 12],
}
impl Default for OperationStats {
+ /// Return empty statistics with no inputs and an unset minimum duration.
fn default() -> Self {
Self {
count: 0,
- total_time_us: 0,
- min_time_us: u64::MAX,
- max_time_us: 0,
+ success_count: 0,
+ error_count: 0,
+ total_time_ns: 0,
+ min_time_ns: u64::MAX,
+ max_time_ns: 0,
+ duration_bucket_counts: [0; 12],
}
}
}
impl OperationStats {
- /// Record an operation duration
- pub fn record(&mut self, duration: Duration) {
- let us = duration.as_micros() as u64;
- self.count += 1;
- self.total_time_us += us;
- if us < self.min_time_us {
- self.min_time_us = us;
- }
- if us > self.max_time_us {
- self.max_time_us = us;
- }
- }
-
- /// Get average time per operation (microseconds)
- pub fn avg_time_us(&self) -> f64 {
+ /// Record the supplied duration and success flag, updating totals in place.
+ pub fn record(&mut self, duration: Duration, success: bool) {
+ let ns = u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX);
+ self.count = self.count.saturating_add(1);
+ let outcome = if success { &mut self.success_count } else { &mut self.error_count };
+ *outcome = outcome.saturating_add(1);
+ self.total_time_ns = self.total_time_ns.saturating_add(ns);
+ self.min_time_ns = self.min_time_ns.min(ns);
+ self.max_time_ns = self.max_time_ns.max(ns);
+ let bucket = DURATION_BUCKET_BOUNDS_NS.partition_point(|bound| *bound < ns);
+ self.duration_bucket_counts[bucket] =
+ self.duration_bucket_counts[bucket].saturating_add(1);
+ }
+
+ /// Return this operation's average nanoseconds, or zero when no samples exist.
+ pub fn avg_time_ns(&self) -> f64 {
if self.count == 0 {
0.0
} else {
- self.total_time_us as f64 / self.count as f64
+ self.total_time_ns as f64 / self.count as f64
}
}
}
@@ -193,10 +210,10 @@ impl StatsCollector {
}
}
- /// Record an operation
- pub async fn record(&self, op: FsOperation, duration: Duration) {
+ /// Record the supplied operation, duration, and success flag; return unit.
+ pub async fn record(&self, op: FsOperation, duration: Duration, success: bool) {
let mut stats = self.stats.write().await;
- stats.operations.entry(op).or_default().record(duration);
+ stats.operations.entry(op).or_default().record(duration, success);
}
/// Get a snapshot of current statistics
@@ -228,9 +245,9 @@ impl OperationTimer {
}
}
- /// Finish the timer and record the duration
- pub async fn finish(self) {
+ /// Consume this timer and record elapsed time with the supplied outcome; return unit.
+ pub async fn finish(self, success: bool) {
let duration = self.start.elapsed();
- self.collector.record(self.op, duration).await;
+ self.collector.record(self.op, duration, success).await;
}
}
diff --git a/crates/ragfs/src/core/stats_wrapper.rs b/crates/ragfs/src/core/stats_wrapper.rs
index d731698f3..c40a54b2c 100644
--- a/crates/ragfs/src/core/stats_wrapper.rs
+++ b/crates/ragfs/src/core/stats_wrapper.rs
@@ -67,42 +67,42 @@ impl FileSystem for StatsWrappedFS {
async fn create(&self, path: &str) -> Result<()> {
let timer = OperationTimer::start(FsOperation::Create, Arc::clone(&self.stats));
let result = self.inner.create(path).await;
- timer.finish().await;
+ timer.finish(result.is_ok()).await;
result
}
async fn mkdir(&self, path: &str, mode: u32) -> Result<()> {
let timer = OperationTimer::start(FsOperation::Mkdir, Arc::clone(&self.stats));
let result = self.inner.mkdir(path, mode).await;
- timer.finish().await;
+ timer.finish(result.is_ok()).await;
result
}
async fn remove(&self, path: &str) -> Result<()> {
let timer = OperationTimer::start(FsOperation::Remove, Arc::clone(&self.stats));
let result = self.inner.remove(path).await;
- timer.finish().await;
+ timer.finish(result.is_ok()).await;
result
}
async fn remove_all(&self, path: &str) -> Result<()> {
let timer = OperationTimer::start(FsOperation::RemoveAll, Arc::clone(&self.stats));
let result = self.inner.remove_all(path).await;
- timer.finish().await;
+ timer.finish(result.is_ok()).await;
result
}
async fn read(&self, path: &str, offset: u64, size: u64) -> Result<Vec<u8>> {
let timer = OperationTimer::start(FsOperation::Read, Arc::clone(&self.stats));
let result = self.inner.read(path, offset, size).await;
- timer.finish().await;
+ timer.finish(result.is_ok()).await;
result
}
async fn write(&self, path: &str, data: &[u8], offset: u64, flags: WriteFlag) -> Result<u64> {
let timer = OperationTimer::start(FsOperation::Write, Arc::clone(&self.stats));
let result = self.inner.write(path, data, offset, flags).await;
- timer.finish().await;
+ timer.finish(result.is_ok()).await;
result
}
@@ -119,56 +119,56 @@ impl FileSystem for StatsWrappedFS {
.inner
.read_dir(path, offset, limit, sort_by, sort_order)
.await;
- timer.finish().await;
+ timer.finish(result.is_ok()).await;
result
}
async fn stat(&self, path: &str) -> Result<FileInfo> {
let timer = OperationTimer::start(FsOperation::Stat, Arc::clone(&self.stats));
let result = self.inner.stat(path).await;
- timer.finish().await;
+ timer.finish(result.is_ok()).await;
result
}
async fn rename(&self, old_path: &str, new_path: &str) -> Result<()> {
let timer = OperationTimer::start(FsOperation::Rename, Arc::clone(&self.stats));
let result = self.inner.rename(old_path, new_path).await;
- timer.finish().await;
+ timer.finish(result.is_ok()).await;
result
}
async fn replace(&self, src_path: &str, dst_path: &str) -> Result<()> {
let timer = OperationTimer::start(FsOperation::Rename, Arc::clone(&self.stats));
let result = self.inner.replace(src_path, dst_path).await;
- timer.finish().await;
+ timer.finish(result.is_ok()).await;
result
}
async fn chmod(&self, path: &str, mode: u32) -> Result<()> {
let timer = OperationTimer::start(FsOperation::Chmod, Arc::clone(&self.stats));
let result = self.inner.chmod(path, mode).await;
- timer.finish().await;
+ timer.finish(result.is_ok()).await;
result
}
async fn truncate(&self, path: &str, size: u64) -> Result<()> {
let timer = OperationTimer::start(FsOperation::Truncate, Arc::clone(&self.stats));
let result = self.inner.truncate(path, size).await;
- timer.finish().await;
+ timer.finish(result.is_ok()).await;
result
}
async fn ensure_parent_dirs(&self, path: &str, mode: u32) -> Result<()> {
let timer = OperationTimer::start(FsOperation::EnsureParentDirs, Arc::clone(&self.stats));
let result = self.inner.ensure_parent_dirs(path, mode).await;
- timer.finish().await;
+ timer.finish(result.is_ok()).await;
result
}
async fn exists(&self, path: &str) -> bool {
let timer = OperationTimer::start(FsOperation::Exists, Arc::clone(&self.stats));
let result = self.inner.exists(path).await;
- timer.finish().await;
+ timer.finish(true).await;
result
}
@@ -195,7 +195,7 @@ impl FileSystem for StatsWrappedFS {
level_limit,
)
.await;
- timer.finish().await;
+ timer.finish(result.is_ok()).await;
result
}
@@ -222,7 +222,7 @@ impl FileSystem for StatsWrappedFS {
sort_order,
)
.await;
- timer.finish().await;
+ timer.finish(result.is_ok()).await;
result
}
@@ -247,7 +247,7 @@ impl FileSystem for StatsWrappedFS {
continuation_token,
)
.await;
- timer.finish().await;
+ timer.finish(result.is_ok()).await;
result
}
}
diff --git a/crates/ragfs/src/lib.rs b/crates/ragfs/src/lib.rs
index 3fa37e735..0b81357be 100644
--- a/crates/ragfs/src/lib.rs
+++ b/crates/ragfs/src/lib.rs
@@ -36,6 +36,7 @@ pub mod cache_runtime;
pub mod core;
pub mod crypto;
pub mod lock;
+pub mod metrics;
pub mod multibackend;
pub mod git;
pub mod plugins;
diff --git a/crates/ragfs/src/lock/manager.rs b/crates/ragfs/src/lock/manager.rs
index dab28f1d2..58bc145e7 100644
--- a/crates/ragfs/src/lock/manager.rs
+++ b/crates/ragfs/src/lock/manager.rs
@@ -486,7 +486,7 @@ pub struct PathLockManager {
config: PathLockConfig,
metrics: Arc<RwLock<LockMetrics>>,
waiting_lock_count: AtomicUsize,
- wait_duration_ms: AtomicU64,
+ wait_duration_ns: AtomicU64,
}
impl PathLockManager {
@@ -588,7 +588,7 @@ impl PathLockManager {
config,
metrics,
waiting_lock_count: AtomicUsize::new(0),
- wait_duration_ms: AtomicU64::new(0),
+ wait_duration_ns: AtomicU64::new(0),
}
}
@@ -984,8 +984,12 @@ impl PathLockManager {
match result {
Ok(owned) => {
- self.wait_duration_ms
- .fetch_add(start.elapsed().as_millis() as u64, AtomicOrdering::Relaxed);
+ let elapsed_ns = u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX);
+ let _ = self.wait_duration_ns.fetch_update(
+ AtomicOrdering::Relaxed,
+ AtomicOrdering::Relaxed,
+ |total| Some(total.saturating_add(elapsed_ns)),
+ );
if waiting.0.is_some() {
info!(lease_ref = %owned.lease.lease_ref, owner_id = %owned.lease.owner_id, lock_paths = ?owned.lease.lock_paths, covered_paths = ?owned.lease.covered_paths, wait_ms = start.elapsed().as_millis() as u64, "pathlock acquire batch succeeded after waiting");
}
@@ -1282,7 +1286,9 @@ impl PathLockManager {
let mut metrics = self.metrics.write().await;
metrics.descendant_scan_count += 1;
- metrics.descendant_scan_duration_ms += scan_start.elapsed().as_millis() as u64;
+ metrics.descendant_scan_duration_ns = metrics
+ .descendant_scan_duration_ns
+ .saturating_add(u64::try_from(scan_start.elapsed().as_nanos()).unwrap_or(u64::MAX));
drop(metrics);
debug!(path = %path, descendant_count = descendants.len(), scan_ms = scan_start.elapsed().as_millis() as u64, "scanned descendant pathlock tokens");
@@ -2109,7 +2115,7 @@ impl PathLockManager {
let mut metrics = self.metrics.read().await.clone();
metrics.active_lock_count = self.lease_registry.active_count();
metrics.waiting_lock_count = self.waiting_lock_count.load(AtomicOrdering::Relaxed);
- metrics.wait_duration_ms = self.wait_duration_ms.load(AtomicOrdering::Relaxed);
+ metrics.wait_duration_ns = self.wait_duration_ns.load(AtomicOrdering::Relaxed);
metrics
}
}
diff --git a/crates/ragfs/src/lock/metrics.rs b/crates/ragfs/src/lock/metrics.rs
index 9a60bff9c..ca01d4ec3 100644
--- a/crates/ragfs/src/lock/metrics.rs
+++ b/crates/ragfs/src/lock/metrics.rs
@@ -20,10 +20,10 @@ pub struct LockMetrics {
pub stale_cleanup_failures: usize,
/// Cumulative count of descendant scan operations.
pub descendant_scan_count: usize,
- /// Total milliseconds spent in descendant scans.
- pub descendant_scan_duration_ms: u64,
- /// Total milliseconds spent waiting for locks.
- pub wait_duration_ms: u64,
+ /// Total nanoseconds spent in descendant scans.
+ pub descendant_scan_duration_ns: u64,
+ /// Total nanoseconds spent waiting for successfully acquired locks.
+ pub wait_duration_ns: u64,
/// Count of conflicts by type (exact/exact, tree/exact, etc.).
pub conflict_count: usize,
/// Recent conflicts for observability (ring buffer).
diff --git a/crates/ragfs/src/metrics/mod.rs b/crates/ragfs/src/metrics/mod.rs
new file mode 100644
index 000000000..7f6f1ec47
--- /dev/null
+++ b/crates/ragfs/src/metrics/mod.rs
@@ -0,0 +1,193 @@
+//! Native metric records converted from existing filesystem collectors.
+
+use std::collections::BTreeMap;
+
+use crate::core::stats::DURATION_BUCKET_BOUNDS_NS;
+use crate::core::{Error, FilesystemStats, FsOperation, Result};
+use crate::lock::metrics::LockMetrics;
+
+/// One metric series, identified by its name and bounded labels.
+#[derive(Debug, Clone, PartialEq)]
+pub struct RagfsMetric {
+ /// Metric family name without an application prefix.
+ pub name: String,
+ /// Stable labels; never include paths, mounts, accounts, or owners.
+ pub labels: BTreeMap<String, String>,
+ /// Raw measurement and its conversion scale.
+ pub value: RagfsMetricValue,
+}
+
+/// Raw metric values; durations remain integer nanoseconds until export.
+#[derive(Debug, Clone, PartialEq)]
+pub enum RagfsMetricValue {
+ /// Monotonic total with an export-unit multiplier.
+ Counter {
+ /// Raw count, bytes, or nanoseconds.
+ value: u64,
+ /// Multiply the raw value by this factor for export.
+ scale: f64,
+ },
+ /// Current value, already in export units.
+ Gauge(f64),
+ /// Noncumulative duration buckets, including a final overflow bucket.
+ Histogram {
+ /// Inclusive finite upper bounds in raw units.
+ bucket_bounds: Vec<u64>,
+ /// Per-bucket counts; one more element than finite bounds.
+ bucket_counts: Vec<u64>,
+ /// Total number of samples across all outcomes.
+ count: u64,
+ /// Sum of samples in raw units.
+ sum: u64,
+ /// Multiply bounds and sum by this factor for export.
+ scale: f64,
+ },
+}
+
+impl RagfsMetric {
+ /// Return a counter from its family name, label pairs, raw value, and scale.
+ pub(crate) fn counter(name: &str, labels: &[(&str, &str)], value: u64, scale: f64) -> Self {
+ Self {
+ name: name.to_string(),
+ labels: labels.iter().map(|(key, value)| (key.to_string(), value.to_string())).collect(),
+ value: RagfsMetricValue::Counter { value, scale },
+ }
+ }
+}
+
+/// Convert one plugin's operation statistics into result counters and histograms.
+pub(crate) fn operation_metrics(plugin: &str, stats: &FilesystemStats) -> Vec<RagfsMetric> {
+ let mut metrics = Vec::new();
+ for operation in FsOperation::all() {
+ let stats = stats.get(*operation);
+ for (status, count) in [("success", stats.success_count), ("error", stats.error_count)] {
+ metrics.push(RagfsMetric::counter(
+ "ragfs_operation_results_total",
+ &[("plugin", plugin), ("operation", operation.as_str()), ("status", status)],
+ count,
+ 1.0,
+ ));
+ }
+ metrics.push(RagfsMetric {
+ name: "ragfs_operation_duration_seconds".into(),
+ labels: [
+ ("plugin".into(), plugin.into()),
+ ("operation".into(), operation.as_str().into()),
+ ].into(),
+ value: RagfsMetricValue::Histogram {
+ bucket_bounds: DURATION_BUCKET_BOUNDS_NS.to_vec(),
+ bucket_counts: stats.duration_bucket_counts.to_vec(),
+ count: stats.count,
+ sum: stats.total_time_ns,
+ scale: 1e-9,
+ },
+ });
+ }
+ metrics
+}
+
+/// Convert a cache snapshot into counters without changing its collector state.
+#[cfg(feature = "cache")]
+pub(crate) fn cache_metrics(stats: crate::cache::CacheMetricsSnapshot) -> Vec<RagfsMetric> {
+ let mut metrics = Vec::new();
+ for (kind, result, count) in [
+ ("file", "hit", stats.file_hits),
+ ("file", "miss", stats.file_misses),
+ ("directory", "hit", stats.read_dir_hits),
+ ("directory", "miss", stats.read_dir_misses),
+ ] {
+ metrics.push(RagfsMetric::counter(
+ "ragfs_cache_requests_total", &[("kind", kind), ("result", result)], count, 1.0,
+ ));
+ }
+ for (name, count) in [
+ ("ragfs_cache_backend_fallbacks_total", stats.backend_fallbacks),
+ ("ragfs_cache_invalidations_total", stats.invalidations),
+ ("ragfs_cache_errors_total", stats.errors),
+ ("ragfs_cache_policy_bypasses_total", stats.policy_bypasses),
+ ] {
+ metrics.push(RagfsMetric::counter(name, &[], count, 1.0));
+ }
+ for (name, label, value, count, scale) in [
+ ("ragfs_cache_operations_total", "operation", "put", stats.puts, 1.0),
+ ("ragfs_cache_operations_total", "operation", "delete", stats.deletes, 1.0),
+ ("ragfs_cache_bytes_total", "source", "backend", stats.backend_bytes, 1.0),
+ ("ragfs_cache_bytes_total", "source", "cache", stats.cache_bytes, 1.0),
+ ("ragfs_cache_operation_duration_seconds_total", "operation", "get", stats.get_latency_ns, 1e-9),
+ ("ragfs_cache_operation_duration_seconds_total", "operation", "put", stats.put_latency_ns, 1e-9),
+ ("ragfs_cache_operation_duration_seconds_total", "operation", "delete", stats.delete_latency_ns, 1e-9),
+ ("ragfs_cache_inflight_events_total", "event", "leader", stats.inflight_leaders, 1.0),
+ ("ragfs_cache_inflight_events_total", "event", "follower", stats.inflight_followers, 1.0),
+ ("ragfs_cache_inflight_events_total", "event", "backend_saved", stats.inflight_backend_saved, 1.0),
+ ] {
+ metrics.push(RagfsMetric::counter(name, &[(label, value)], count, scale));
+ }
+ metrics
+}
+
+/// Convert the single lock manager's snapshot into unlabeled metric records.
+pub(crate) fn lock_metrics(stats: LockMetrics) -> Vec<RagfsMetric> {
+ let mut metrics = Vec::new();
+ for (name, value) in [
+ ("lock_active", stats.active_lock_count),
+ ("lock_waiting", stats.waiting_lock_count),
+ ("lock_stale", stats.stale_tokens_removed),
+ ] {
+ metrics.push(RagfsMetric {
+ name: name.into(),
+ labels: BTreeMap::new(),
+ value: RagfsMetricValue::Gauge(value as f64),
+ });
+ }
+ for (name, value) in [
+ ("lock_conflicts_total", stats.conflict_count),
+ ("lock_stale_leases_released_total", stats.stale_leases_released),
+ ("lock_descendant_scans_total", stats.descendant_scan_count),
+ ] {
+ metrics.push(RagfsMetric::counter(name, &[], value as u64, 1.0));
+ }
+ metrics.push(RagfsMetric::counter(
+ "lock_descendant_scan_duration_seconds_total", &[], stats.descendant_scan_duration_ns, 1e-9,
+ ));
+ metrics
+}
+
+/// Merge supplied series by name and labels; return sorted records or an incompatibility error.
+pub(crate) fn merge_metrics(mut metrics: Vec<RagfsMetric>) -> Result<Vec<RagfsMetric>> {
+ metrics.sort_by(|a, b| (&a.name, &a.labels).cmp(&(&b.name, &b.labels)));
+ let mut merged: Vec<RagfsMetric> = Vec::new();
+ for metric in metrics {
+ let Some(previous) = merged.last_mut()
+ .filter(|last| last.name == metric.name && last.labels == metric.labels)
+ else {
+ merged.push(metric);
+ continue;
+ };
+ match (&mut previous.value, metric.value) {
+ (
+ RagfsMetricValue::Counter { value, scale },
+ RagfsMetricValue::Counter { value: other, scale: other_scale },
+ ) if *scale == other_scale => *value = value.saturating_add(other),
+ (RagfsMetricValue::Gauge(value), RagfsMetricValue::Gauge(other)) => *value += other,
+ (
+ RagfsMetricValue::Histogram { bucket_bounds, bucket_counts, count, sum, scale },
+ RagfsMetricValue::Histogram {
+ bucket_bounds: other_bounds, bucket_counts: other_counts,
+ count: other_count, sum: other_sum, scale: other_scale,
+ },
+ ) if *bucket_bounds == other_bounds
+ && bucket_counts.len() == other_counts.len()
+ && bucket_counts.len() == bucket_bounds.len() + 1
+ && *scale == other_scale =>
+ {
+ for (value, other) in bucket_counts.iter_mut().zip(other_counts) {
+ *value = value.saturating_add(other);
+ }
+ *count = count.saturating_add(other_count);
+ *sum = sum.saturating_add(other_sum);
+ }
+ _ => return Err(Error::internal(format!("incompatible metric series '{}'", metric.name))),
+ }
+ }
+ Ok(merged)
+}
diff --git a/docs/design/metric-design.md b/docs/design/metric-design.md
index ea8d212e3..605381b58 100644
--- a/docs/design/metric-design.md
+++ b/docs/design/metric-design.md
@@ -348,7 +348,7 @@ graph LR
I["CacheCollector"]
J["EncryptionCollector"]
K["QueueCollector"]
- L["LockCollector"]
+ L["RagfsMetricCollector"]
M["VikingDBCollector"]
N["ObserverHealthCollector"]
O["TaskTrackerCollector"]
@@ -372,7 +372,7 @@ graph LR
B --> I
B --> J
C --> K
- C --> L
+ D --> L
C --> M
C --> N
C --> O
@@ -416,7 +416,7 @@ Collector 与 DataSource 的主映射关系如下:
| `CacheCollector` | `EventMetricCollector` | cache 命中或未命中事件 | hit / miss |
| `EncryptionCollector` | `EventMetricCollector` | encrypt / decrypt / verify / kdf / key_load 事件 | 加密次数、认证失败、耗时、字节量、密钥处理统计 |
| `QueueCollector` | `StateMetricCollector` | QueueManager / DAG 当前状态 | pending、in_progress、processed、errors |
-| `LockCollector` | `StateMetricCollector` | LockManager 当前状态 | active、waiting、stale |
+| `RagfsMetricCollector` | `DomainStatsMetricCollector` | `RagfsMetricDataSource`,一次 RAGFS `metrics()` 调用 | 文件操作、Cache、multi-backend、Lock |
| `VikingDBCollector` | `StateMetricCollector` | VikingDB collection 当前状态 | health、vectors、collections |
| `ObserverHealthCollector` | `StateMetricCollector` | ObserverService 结果 | component health、component errors |
| `TaskTrackerCollector` | `StateMetricCollector` | TaskTracker 当前状态 | pending、running、completed、failed |
@@ -465,11 +465,31 @@ Registry 只解决“如何统一保存指标”,不解决:
- EventCollector 决定何时调用 `inc_counter` 或 `observe_histogram`;
- StateCollector 决定何时调用 `set_gauge`;
-- DomainStatsCollector 决定如何把已有累计统计映射到统一写接口;
+- DomainStatsCollector 决定如何把已有累计统计映射到统一写接口;RAGFS 使用绝对值覆盖;
- ProbeCollector 决定如何把 probe 结果翻译成 readiness / health gauge。
也就是说,Registry 不感知“当前写入的是事件、状态、统计还是探针”,它只感知“要写入哪种指标类型、哪个指标名、哪些标签和值”。
+RAGFS 使用单一 `metrics()` 接口,返回扁平指标记录,不暴露内部对象层级。
+`RagfsMetricDataSource` 校验整批记录,`RagfsMetricCollector` 只按类型分发:
+
+```text
+Counter -> value * scale -> set_counter()
+Gauge -> value -> set_gauge()
+Histogram -> bounds/sum * scale -> set_histogram()
+```
+
+耗时在 Rust 内部以整数纳秒累计,通过 `scale=1e-9` 转为小数秒。
+Registry 的绝对值 setter 支持零值和计数重置,原有增量接口保持不变。
+Collector 不保存前值、不计算差分;只保存序列标识,用于删除消失的序列。
+读取或校验失败时保留旧数据;写入失败后由下一轮全量覆盖恢复。
+采集锁覆盖整轮读取和写入,避免超时线程与后续刷新并行更新。
+
+RAGFS 首期导出 20 个指标族,不带 `mount` 或 `account_id` 标签。
+`openviking_lock_active` 保留原名和 Gauge 类型,表示当前已发布的锁租约数。
+`openviking_lock_stale` 保留原名和 Gauge 类型,表示累计已清理的过期锁 token 数。
+`get_stats()` 在 Binding 输出层转换回微秒,Python Observer 不变。
+
由此,registry 可以作为整个指标系统的稳定核心,而不随 exporter 或 collector 的演化频繁变动。
### 2.4 `BaseMetricExporter` 设计
@@ -620,7 +640,8 @@ sequenceDiagram
| 模型链路监控 | `ModelUsageDataSource`、模型调用事件 | `VLMCollector`、`EmbeddingCollector`、`ModelUsageCollector` | Counter、Histogram | model calls、tokens、duration |
| 资源导入监控 | `ResourceIngestionEventDataSource` | `ResourceIngestionCollector` | Counter、Histogram | parse / finalize / summarize / wait duration |
| Session 与异步任务监控 | `SessionLifecycleDataSource`、`TaskStateDataSource`、`QueuePipelineStateDataSource` | `TaskTrackerCollector`、`QueueCollector` | Gauge、Counter | task pending、queue backlog、session lifecycle count |
-| 诊断与状态监控 | `ObserverStateDataSource`、`QueuePipelineStateDataSource` | `ObserverHealthCollector`、`LockCollector`、`VikingDBCollector` | Gauge | component health、lock active、collection health |
+| 诊断与状态监控 | `ObserverStateDataSource`、`VikingDBStateDataSource` | `ObserverHealthCollector`、`VikingDBCollector` | Gauge | component health、collection health |
+| RAGFS 监控 | `RagfsMetricDataSource` | `RagfsMetricCollector` | Counter、Histogram、Gauge | 文件操作、Cache、multi-backend、Lock |
| 加密监控 | `EncryptionEventDataSource`、`EncryptionProbeDataSource` | `EncryptionCollector`、`EncryptionProbeCollector` | Counter、Histogram、Gauge | encrypt count、decrypt duration、root key readiness |
| 系统探针监控 | 各类 `*ProbeDataSource` | 各类 `*ProbeCollector` | Gauge、Health | service readiness、storage readiness、kms availability |
| 操作级 Telemetry 指标化 | telemetry adapter / bridge | `TelemetryBridgeCollector` | Counter、Histogram、Gauge | operation requests、vector scanned、memory extracted |
diff --git a/docs/en/concepts/12-metrics.md b/docs/en/concepts/12-metrics.md
index a7068c455..b79f172ef 100644
--- a/docs/en/concepts/12-metrics.md
+++ b/docs/en/concepts/12-metrics.md
@@ -228,15 +228,48 @@ Notes:
| `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 |
-| `openviking_lock_waiting` | Gauge | none | locks currently waiting |
-| `openviking_lock_stale` | Gauge | none | potentially stale locks |
+| `openviking_lock_active` | Gauge | none | current published lock leases |
+| `openviking_lock_waiting` | Gauge | none | requests currently waiting for locks |
+| `openviking_lock_stale` | Gauge | none | cumulative count of stale lock tokens removed |
+| `openviking_lock_conflicts_total` | Counter | none | observed lock conflicts |
+| `openviking_lock_stale_leases_released_total` | Counter | none | stale leases released |
+| `openviking_lock_descendant_scans_total` | Counter | none | completed descendant scans |
+| `openviking_lock_descendant_scan_duration_seconds_total` | Counter | none | cumulative descendant scan duration |
These help answer:
- Is there queue backlog?
- Is there lock contention or stale locking?
+### RAGFS
+
+RAGFS exports filesystem, cache, multi-backend and lock metrics through one native
+`metrics()` call. The collector replaces Registry values directly without computing
+deltas. Durations are sampled in integer nanoseconds and exported as fractional
+seconds, for example `123 ns = 0.000000123 seconds`.
+
+| Metric Family | Type | Common Labels | Meaning |
+|---------------|------|---------------|---------|
+| `openviking_ragfs_operation_results_total` | Counter | `plugin, operation, status` | successful and failed operations |
+| `openviking_ragfs_operation_duration_seconds` | Histogram | `plugin, operation` | operation duration distribution |
+| `openviking_ragfs_cache_requests_total` | Counter | `kind, result` | file/directory cache hits and misses |
+| `openviking_ragfs_cache_backend_fallbacks_total` | Counter | none | backend loads after cache misses |
+| `openviking_ragfs_cache_operations_total` | Counter | `operation` | cache put/delete attempts |
+| `openviking_ragfs_cache_invalidations_total` | Counter | none | completed invalidations |
+| `openviking_ragfs_cache_errors_total` | Counter | none | cache errors hidden by bypass mode |
+| `openviking_ragfs_cache_policy_bypasses_total` | Counter | none | reads bypassing cache |
+| `openviking_ragfs_cache_bytes_total` | Counter | `source` | bytes from backend/cache |
+| `openviking_ragfs_cache_operation_duration_seconds_total` | Counter | `operation` | cumulative get/put/delete duration |
+| `openviking_ragfs_cache_inflight_events_total` | Counter | `event` | leader/follower/backend_saved counts |
+| `openviking_ragfs_multiwrite_background_tasks` | Gauge | none | background tasks, including the retry loop |
+| `openviking_ragfs_multiwrite_read_routes_total` | Counter | `route` | primary/backup/redirect/miss selections |
+
+These metrics have no `mount` or `account_id` label. Cache and multi-backend
+families are absent when those capabilities are not enabled. `status` is
+`success` or `error`; `exists=false` is successful and `replace` uses `rename`.
+Histogram buckets cover all outcomes, with finite bounds from 0.0001 to 10 seconds.
+Python `get_stats()` retains its microsecond fields.
+
### Tasks and Task Tracker
| Metric Family | Type | Common Labels | Meaning |
diff --git a/docs/zh/concepts/12-metrics.md b/docs/zh/concepts/12-metrics.md
index 42569d09a..90dcec4f2 100644
--- a/docs/zh/concepts/12-metrics.md
+++ b/docs/zh/concepts/12-metrics.md
@@ -231,15 +231,48 @@ scrape_configs:
| `openviking_queue_errors_total` | Counter | `queue` | 队列累计错误量 |
| `openviking_queue_pending` | Gauge | `queue` | 队列待处理数 |
| `openviking_queue_in_progress` | Gauge | `queue` | 队列执行中数量 |
-| `openviking_lock_active` | Gauge | 无 | 当前活跃锁数量 |
-| `openviking_lock_waiting` | Gauge | 无 | 当前等待中的锁数量 |
-| `openviking_lock_stale` | Gauge | 无 | 可能 stale 的锁数量 |
+| `openviking_lock_active` | Gauge | 无 | 当前已发布的锁租约数 |
+| `openviking_lock_waiting` | Gauge | 无 | 当前等待锁的请求数 |
+| `openviking_lock_stale` | Gauge | 无 | 累计已清理的过期锁 token 数 |
+| `openviking_lock_conflicts_total` | Counter | 无 | 累计锁冲突次数 |
+| `openviking_lock_stale_leases_released_total` | Counter | 无 | 已释放的过期租约数 |
+| `openviking_lock_descendant_scans_total` | Counter | 无 | 已完成的后代锁扫描次数 |
+| `openviking_lock_descendant_scan_duration_seconds_total` | Counter | 无 | 后代锁扫描累计耗时 |
这些指标适合回答:
- 是否有队列堆积?
- 是否有锁竞争或 stale lock?
+
+### RAGFS
+
+RAGFS 通过一次原生 `metrics()` 调用读取文件系统、Cache、multi-backend
+和 Lock 指标。Collector 直接覆盖 Registry 当前值,不计算差分。
+内部以整数纳秒采样,导出为小数秒,例如 `123 ns = 0.000000123 seconds`。
+
+| 指标族 | 类型 | 常见标签 | 含义 |
+|--------|------|----------|------|
+| `openviking_ragfs_operation_results_total` | Counter | `plugin, operation, status` | 操作成功和失败次数 |
+| `openviking_ragfs_operation_duration_seconds` | Histogram | `plugin, operation` | 操作耗时分布 |
+| `openviking_ragfs_cache_requests_total` | Counter | `kind, result` | 文件和目录缓存命中、未命中次数 |
+| `openviking_ragfs_cache_backend_fallbacks_total` | Counter | 无 | 缓存未命中后的后端读取次数 |
+| `openviking_ragfs_cache_operations_total` | Counter | `operation` | 缓存 put/delete 尝试次数 |
+| `openviking_ragfs_cache_invalidations_total` | Counter | 无 | 已完成的缓存失效次数 |
+| `openviking_ragfs_cache_errors_total` | Counter | 无 | 旁路模式下忽略的缓存错误数 |
+| `openviking_ragfs_cache_policy_bypasses_total` | Counter | 无 | 绕过缓存的读取次数 |
+| `openviking_ragfs_cache_bytes_total` | Counter | `source` | 来自后端和缓存的字节数 |
+| `openviking_ragfs_cache_operation_duration_seconds_total` | Counter | `operation` | get/put/delete 累计耗时 |
+| `openviking_ragfs_cache_inflight_events_total` | Counter | `event` | leader/follower/backend_saved 次数 |
+| `openviking_ragfs_multiwrite_background_tasks` | Gauge | 无 | 后台任务数,包含重试循环 |
+| `openviking_ragfs_multiwrite_read_routes_total` | Counter | `route` | primary/backup/redirect/miss 路由选择次数 |
+
+这些指标不带 `mount` 和 `account_id` 标签。未启用 Cache 或 multi-backend
+时,不生成对应指标族。`status` 为 `success` 或 `error`。
+`exists=false` 计为成功;`replace` 使用 `rename` 操作标签。
+Histogram 包含全部操作结果,有限桶边界范围为 0.0001 至 10 秒。
+Python `get_stats()` 保留原有微秒字段。
+
### 任务与 Task Tracker
| 指标族 | 类型 | 常见标签 | 含义 |
diff --git a/openviking/metrics/bootstrap.py b/openviking/metrics/bootstrap.py
index 9a67ef433..19e9955f8 100644
--- a/openviking/metrics/bootstrap.py
+++ b/openviking/metrics/bootstrap.py
@@ -8,7 +8,7 @@ This module wires DataSources and Collectors into a CollectorManager that is inv
before each Prometheus scrape (`/metrics`).
The registered collectors are intentionally split into two categories:
-- Per-scrape refresh (no TTL): cheap, purely in-process reads (e.g., queue/lock counters).
+- Per-scrape refresh (no TTL): cheap, purely in-process reads (e.g., queue counters).
- TTL/SWR protected: collectors that may touch slower or less reliable subsystems
(e.g., service/model probes, vikingdb state, aggregated model usage).
@@ -33,12 +33,12 @@ from openviking.metrics.collectors import (
CollectorManager,
EncryptionProbeCollector,
FeedbackCollector,
- LockCollector,
ModelProviderProbeCollector,
ModelUsageCollector,
ObserverHealthCollector,
ObserverStateCollector,
QueueCollector,
+ RagfsMetricCollector,
RetrievalBackendProbeCollector,
ServiceProbeCollector,
StorageProbeCollector,
@@ -48,7 +48,6 @@ from openviking.metrics.collectors import (
from openviking.metrics.datasources.encryption import EncryptionProbeDataSource
from openviking.metrics.datasources.model_usage import ModelUsageDataSource
from openviking.metrics.datasources.observer_state import (
- LockStateDataSource,
ObserverStateDataSource,
VikingDBStateDataSource,
)
@@ -60,6 +59,7 @@ from openviking.metrics.datasources.probes import (
StorageProbeDataSource,
)
from openviking.metrics.datasources.queue import QueuePipelineStateDataSource
+from openviking.metrics.datasources.ragfs import RagfsMetricDataSource
from openviking.metrics.datasources.task import TaskStateDataSource
from openviking_cli.utils.config.open_viking_config import get_openviking_config
@@ -88,7 +88,7 @@ def create_default_collector_manager(*, app=None, service=None, config=None) ->
manager.register(FeedbackCollector(bot_data_path=feedback_bot_data_path))
manager.register(ObserverHealthCollector(data_source=ObserverStateDataSource(service=service)))
manager.register(ObserverStateCollector(data_source=ObserverStateDataSource(service=service)))
- manager.register(LockCollector(data_source=LockStateDataSource()))
+ manager.register(RagfsMetricCollector(data_source=RagfsMetricDataSource(service=service)))
manager.register(VikingDBCollector(data_source=VikingDBStateDataSource(service=service)))
manager.register(
ModelUsageCollector(
diff --git a/openviking/metrics/collectors/__init__.py b/openviking/metrics/collectors/__init__.py
index 985a64648..716fde7a9 100644
--- a/openviking/metrics/collectors/__init__.py
+++ b/openviking/metrics/collectors/__init__.py
@@ -17,13 +17,13 @@ from .embedding import EmbeddingCollector
from .encryption import EncryptionCollector
from .encryption_probe import EncryptionProbeCollector
from .feedback import FeedbackCollector
-from .lock import LockCollector
from .manager import CollectorManager, RefreshResult
from .model_provider_probe import ModelProviderProbeCollector
from .model_usage import ModelUsageCollector
from .observer_health import ObserverHealthCollector
from .observer_state import ObserverStateCollector
from .queue import QueueCollector
+from .ragfs import RagfsMetricCollector
from .rerank import RerankCollector
from .retrieval import RetrievalCollector
from .retrieval_backend_probe import RetrievalBackendProbeCollector
@@ -48,7 +48,7 @@ __all__ = [
"FeedbackCollector",
"QueueCollector",
"RerankCollector",
- "LockCollector",
+ "RagfsMetricCollector",
"VikingDBCollector",
"ObserverHealthCollector",
"TaskTrackerCollector",
diff --git a/openviking/metrics/collectors/base.py b/openviking/metrics/collectors/base.py
index 939dc57eb..936a1ed98 100644
--- a/openviking/metrics/collectors/base.py
+++ b/openviking/metrics/collectors/base.py
@@ -369,13 +369,14 @@ class DomainStatsMetricCollector(MetricCollector, Refreshable, ABC):
"""Return the collector category identifier."""
return cls.KIND
- def collect(self, registry) -> None:
+ def collect(self, registry) -> bool | None:
"""
Read domain-statistics input and delegate metric emission through subclass hooks.
Concrete domain collectors define how aggregate input is read and how it becomes
registry output. Read failures are delegated to `collect_error_hook(...)` so collectors
can emit stale/invalid gauges when that matches their contract.
+ Return None after completion; overrides may return False to report a skipped refresh.
"""
writer = CollectorMetricWriter(registry)
try:
diff --git a/openviking/metrics/collectors/lock.py b/openviking/metrics/collectors/lock.py
deleted file mode 100644
index 06af3e149..000000000
--- a/openviking/metrics/collectors/lock.py
+++ /dev/null
@@ -1,48 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-from typing import ClassVar
-
-from openviking.metrics.core.base import MetricCollector
-from openviking.metrics.datasources.observer_state import LockStateDataSource
-
-from .base import CollectorConfig, StateMetricCollector
-
-
-@dataclass
-class LockCollector(StateMetricCollector):
- """
- Translate lock-manager snapshots into lock-related gauge families.
-
- The datasource returns a point-in-time view of active, waiting, and stale locks. This
- collector mirrors that snapshot directly as gauges because the values represent current state
- rather than cumulative activity.
- """
-
- DOMAIN: ClassVar[str] = "lock"
- # rule: <METRICS_NAMESPACE>_<DOMAIN>_active
- # e.g.: openviking_lock_active
- ACTIVE: ClassVar[str] = MetricCollector.metric_name(DOMAIN, "active")
- # rule: <METRICS_NAMESPACE>_<DOMAIN>_waiting
- # e.g.: openviking_lock_waiting
- WAITING: ClassVar[str] = MetricCollector.metric_name(DOMAIN, "waiting")
- # rule: <METRICS_NAMESPACE>_<DOMAIN>_stale
- # e.g.: openviking_lock_stale
- STALE: ClassVar[str] = MetricCollector.metric_name(DOMAIN, "stale")
-
- data_source: LockStateDataSource
- config: CollectorConfig = CollectorConfig(timeout_seconds=0.5)
-
- def read_metric_input(self):
- """Read the latest lock-manager state counters from the datasource."""
- return self.data_source.read_lock_state()
-
- def collect_hook(self, registry, metric_input) -> None:
- """Publish the current lock snapshot as active, waiting, and stale gauges."""
- active, waiting, stale = metric_input
- registry.set_gauge(self.ACTIVE, float(active))
- registry.set_gauge(self.WAITING, float(waiting))
- registry.set_gauge(self.STALE, float(stale))
diff --git a/openviking/metrics/collectors/manager.py b/openviking/metrics/collectors/manager.py
index 5a1f3ed60..82214bb13 100644
--- a/openviking/metrics/collectors/manager.py
+++ b/openviking/metrics/collectors/manager.py
@@ -215,15 +215,17 @@ class CollectorManager:
Returns:
A `RefreshResult` describing the collector outcome without propagating exceptions to
- the caller.
+ the caller. An explicit False return means collection was skipped.
"""
try:
- await asyncio.wait_for(asyncio.to_thread(collector.collect, registry), timeout=timeout)
+ collected = await asyncio.wait_for(
+ asyncio.to_thread(collector.collect, registry), timeout=timeout
+ )
return RefreshResult(
collector=self._collector_name(collector),
- attempted=True,
- success=True,
- reason="ok",
+ attempted=collected is not False,
+ success=collected is not False,
+ reason="skipped" if collected is False else "ok",
)
except asyncio.TimeoutError:
return RefreshResult(
diff --git a/openviking/metrics/collectors/ragfs.py b/openviking/metrics/collectors/ragfs.py
new file mode 100644
index 000000000..b0bf3d6b3
--- /dev/null
+++ b/openviking/metrics/collectors/ragfs.py
@@ -0,0 +1,81 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+"""Publish authoritative native metrics through the shared Registry."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from threading import Lock
+
+from openviking.metrics.core.base import ReadEnvelope
+from openviking.metrics.datasources.ragfs import RagfsMetricDataSource
+
+from .base import CollectorConfig, DomainStatsMetricCollector
+
+
+@dataclass
+class RagfsMetricCollector(DomainStatsMetricCollector):
+ """Replace native metric values without computing increments or retaining previous values."""
+
+ data_source: RagfsMetricDataSource
+ config: CollectorConfig = CollectorConfig(ttl_seconds=None, timeout_seconds=1.0)
+ _collect_lock: Lock = field(default_factory=Lock, init=False, repr=False)
+ _tracked_series: set[tuple[str, str, tuple[tuple[str, str], ...]]] = field(
+ default_factory=set, init=False, repr=False
+ )
+
+ def collect(self, registry) -> bool | None:
+ """Collect into registry; return False on overlap, or None after completion."""
+ if not self._collect_lock.acquire(blocking=False):
+ return False
+ try:
+ super().collect(registry)
+ finally:
+ self._collect_lock.release()
+
+ def read_metric_input(self) -> ReadEnvelope[list[dict[str, object]]]:
+ """Return the datasource's validated current native records."""
+ return self.data_source.read_metrics()
+
+ def collect_hook(self, registry, metric_input: list[dict[str, object]]) -> None:
+ """Replace validated records in registry, then delete absent series; return None."""
+ current_series = set()
+ for record in metric_input:
+ name = f"{self.METRICS_NAMESPACE}_{record['name']}"
+ kind = record["type"]
+ labels = record["labels"]
+ label_names = tuple(sorted(labels))
+ if kind == "counter":
+ registry.set_counter(
+ name,
+ float(record["value"]) * record["scale"],
+ labels=labels,
+ label_names=label_names,
+ )
+ elif kind == "gauge":
+ registry.set_gauge(
+ name,
+ record["value"],
+ labels=labels,
+ label_names=label_names,
+ )
+ else:
+ registry.set_histogram(
+ name,
+ bucket_bounds=[
+ float(bound) * record["scale"] for bound in record["bucket_bounds"]
+ ],
+ bucket_counts=record["bucket_counts"],
+ count=record["count"],
+ value_sum=float(record["sum"]) * record["scale"],
+ labels=labels,
+ label_names=label_names,
+ )
+ identity = (kind, name, tuple(sorted(labels.items())))
+ current_series.add(identity)
+ self._tracked_series.add(identity)
+ for identity in sorted(self._tracked_series - current_series):
+ kind, name, labels = identity
+ getattr(registry, f"{kind}_delete_matching")(name, match_labels=dict(labels))
+ self._tracked_series.remove(identity)
diff --git a/openviking/metrics/core/base.py b/openviking/metrics/core/base.py
index 70836585f..cf7973290 100644
--- a/openviking/metrics/core/base.py
+++ b/openviking/metrics/core/base.py
@@ -172,13 +172,16 @@ class MetricCollector(ABC):
"""
return self.__class__.__name__
- def collect(self, registry) -> None:
+ def collect(self, registry) -> bool | None:
"""
Perform pull-style collection and write samples into the registry.
Args:
registry: The in-process metric registry that receives the collector output.
+ Returns:
+ None or True after completion; False when skipped without refreshing data.
+
This method is intentionally a no-op by default. Event-driven collectors do not need
to implement pull behavior, while refresh-managed collectors override this method with
their actual state-reading logic.
diff --git a/openviking/metrics/core/registry.py b/openviking/metrics/core/registry.py
index 2bd969d64..8512d2b0c 100644
--- a/openviking/metrics/core/registry.py
+++ b/openviking/metrics/core/registry.py
@@ -20,7 +20,9 @@ Important behaviors:
from __future__ import annotations
+import math
import threading
+import time
from bisect import bisect_left
from typing import Mapping, Sequence
@@ -40,6 +42,48 @@ def _canonicalize_label_names(label_names: Sequence[str]) -> tuple[str, ...]:
return tuple(sorted(str(name) for name in label_names))
+def _validate_label_keys(
+ name: str,
+ label_names: tuple[str, ...],
+ normalized: tuple[tuple[str, str], ...],
+) -> None:
+ """Check normalized labels against the named metric's declared keys; return None."""
+ if not label_names and normalized:
+ raise ValueError(f"metric {name} does not accept labels")
+ if label_names and tuple(k for k, _ in normalized) != label_names:
+ raise ValueError(f"metric {name} label keys mismatch: expected {label_names}")
+
+
+def _validate_counter_value(value: float) -> float:
+ """Return value as a finite, nonnegative float or raise ValueError."""
+ value = float(value)
+ if not math.isfinite(value) or value < 0:
+ raise ValueError("counter value must be finite and nonnegative")
+ return value
+
+
+def _validate_histogram_values(
+ bounds: tuple[float, ...],
+ bucket_counts: Sequence[int],
+ count: int,
+ value_sum: float,
+) -> tuple[tuple[int, ...], float]:
+ """Validate bounds and totals; return bucket_counts as a tuple and value_sum as a float."""
+ bucket_counts = tuple(bucket_counts)
+ value_sum = float(value_sum)
+ if any(not math.isfinite(bound) or bound < 0 for bound in bounds) or any(
+ left >= right for left, right in zip(bounds, bounds[1:], strict=False)
+ ):
+ raise ValueError("histogram bounds must be finite, nonnegative and increasing")
+ if len(bucket_counts) != len(bounds) + 1 or any(
+ type(value) is not int or value < 0 for value in (*bucket_counts, count)
+ ):
+ raise ValueError("histogram counts must be nonnegative integers matching bounds")
+ if sum(bucket_counts) != count or not math.isfinite(value_sum) or value_sum < 0:
+ raise ValueError("histogram count or sum is invalid")
+ return bucket_counts, value_sum
+
+
def _labels_contains(
labels: tuple[tuple[str, str], ...],
match: tuple[tuple[str, str], ...],
@@ -106,6 +150,44 @@ class MetricRegistry:
"""
self.counter(name, label_names=label_names).inc(labels=labels, amount=float(amount))
+ def set_counter(
+ self,
+ name: str,
+ value: float,
+ *,
+ labels: Mapping[str, str] | None = None,
+ label_names: Sequence[str] = (),
+ ) -> None:
+ """Replace the named counter's labelled value, including zero or reset; return None."""
+ value = _validate_counter_value(value)
+ ln = _canonicalize_label_names(label_names)
+ normalized = normalize_labels(labels)
+ _validate_label_keys(name, ln, normalized)
+ self.counter(name, label_names=ln).set(value, labels=dict(normalized))
+
+ def set_histogram(
+ self,
+ name: str,
+ *,
+ bucket_bounds: Sequence[float],
+ bucket_counts: Sequence[int],
+ count: int,
+ value_sum: float,
+ labels: Mapping[str, str] | None = None,
+ label_names: Sequence[str] = (),
+ ) -> None:
+ """Replace a named histogram from disjoint bucket counts and totals; return None."""
+ bounds = tuple(float(bound) for bound in bucket_bounds)
+ bucket_counts, value_sum = _validate_histogram_values(
+ bounds, bucket_counts, count, value_sum
+ )
+ ln = _canonicalize_label_names(label_names)
+ normalized = normalize_labels(labels)
+ _validate_label_keys(name, ln, normalized)
+ self.histogram(name, label_names=ln, buckets=bounds).set(
+ bucket_counts, count, value_sum, labels=dict(normalized)
+ )
+
def set_gauge(
self,
name: str,
@@ -242,17 +324,26 @@ class MetricRegistry:
family._validate_buckets(b)
return _Histogram(family)
- def iter_counters(self):
+ def iter_counters(self, *, include_start_time: bool = False):
"""
Iterate over all counter families and their current series values.
The returned family payload is a detached snapshot so exporters can iterate without
- holding the registry lock during rendering.
+ holding the registry lock during rendering. When include_start_time is True,
+ each series also includes its cumulative start time in Unix nanoseconds.
"""
with self._lock:
families = dict(self._counters)
for name, family in families.items():
- yield name, list(family.copy_values().items())
+ values = family.copy_values()
+ if values is not None:
+ yield (
+ name,
+ [
+ (labels, *value) if include_start_time else (labels, value[0])
+ for labels, value in values.items()
+ ],
+ )
def counter_label_names(self, name: str) -> tuple[str, ...]:
"""Return the registered label key tuple for a counter family, if present."""
@@ -270,7 +361,9 @@ class MetricRegistry:
with self._lock:
families = dict(self._gauges)
for name, family in families.items():
- yield name, list(family.copy_values().items())
+ values = family.copy_values()
+ if values is not None:
+ yield name, list(values.items())
def gauge_label_names(self, name: str) -> tuple[str, ...]:
"""Return the registered label key tuple for a gauge family, if present."""
@@ -309,18 +402,40 @@ class MetricRegistry:
return
family.delete_matching(match_labels=match_labels)
- def iter_histograms(self):
+ def counter_delete_matching(self, name: str, *, match_labels: Mapping[str, str]) -> None:
+ """Delete counter series matching the supplied label subset; return None."""
+ with self._lock:
+ family = self._counters.get(name)
+ if family is not None:
+ family.delete_matching(match_labels=match_labels)
+
+ def histogram_delete_matching(self, name: str, *, match_labels: Mapping[str, str]) -> None:
+ """Delete histogram series matching the supplied label subset; return None."""
+ with self._lock:
+ family = self._histograms.get(name)
+ if family is not None:
+ family.delete_matching(match_labels=match_labels)
+
+ def iter_histograms(self, *, include_start_time: bool = False):
"""
Iterate over all histogram families and their materialized series snapshots.
Each yielded item contains family metadata and a detached list of per-series bucket
- counts, sample counts, and sums ready for exporter rendering.
+ counts, sample counts, and sums ready for exporter rendering. When include_start_time
+ is True, each series also includes its cumulative start time in Unix nanoseconds.
"""
with self._lock:
families = dict(self._histograms)
for name, family in families.items():
- label_names, bucket_bounds, series = family.copy_series()
- yield name, label_names, bucket_bounds, series
+ snapshot = family.copy_series()
+ if snapshot is not None:
+ label_names, bucket_bounds, series = snapshot
+ yield (
+ name,
+ label_names,
+ bucket_bounds,
+ (series if include_start_time else [values[:-1] for values in series]),
+ )
def iter_dropped_series(self):
"""
@@ -358,7 +473,8 @@ class _CounterFamily:
self._max_series = max_series
self._on_drop = on_drop
self._lock = threading.Lock()
- self._values: dict[tuple[tuple[str, str], ...], float] = {}
+ self._values: dict[tuple[tuple[str, str], ...], tuple[float, int]] = {}
+ self._had_deletions = False
def inc(self, *, labels: Mapping[str, str] | None, amount: float) -> None:
"""
@@ -374,13 +490,39 @@ class _CounterFamily:
if key not in self._values and len(self._values) >= self._max_series:
self._on_drop(self.name)
return
- self._values[key] = self._values.get(key, 0.0) + float(amount)
+ value, start_time_ns = self._values.get(key, (0.0, 0))
+ self._values[key] = (value + float(amount), start_time_ns or time.time_ns())
- def copy_values(self) -> dict[tuple[tuple[str, str], ...], float]:
- """Return a detached copy of all series values in this family."""
+ def copy_values(self) -> dict[tuple[tuple[str, str], ...], tuple[float, int]] | None:
+ """Return totals with their start times, or None if deletion emptied this family."""
with self._lock:
+ if self._had_deletions and not self._values:
+ return None
return dict(self._values)
+ def set(self, *, labels: Mapping[str, str] | None, value: float) -> None:
+ """Replace labels with value, starting a new cumulative period on decrease; return None."""
+ value = _validate_counter_value(value)
+ key = self._normalize_and_validate(labels)
+ with self._lock:
+ if key not in self._values and len(self._values) >= self._max_series:
+ self._on_drop(self.name)
+ return
+ previous = self._values.get(key)
+ start_time_ns = (
+ previous[1] if previous is not None and value >= previous[0] else time.time_ns()
+ )
+ self._values[key] = (value, start_time_ns)
+
+ def delete_matching(self, *, match_labels: Mapping[str, str]) -> None:
+ """Remove counter entries containing the supplied labels; return None."""
+ normalized = normalize_labels(match_labels)
+ with self._lock:
+ for key in list(self._values):
+ if _labels_contains(key, normalized):
+ del self._values[key]
+ self._had_deletions = True
+
def _normalize_and_validate(
self, labels: Mapping[str, str] | None
) -> tuple[tuple[str, str], ...]:
@@ -398,10 +540,7 @@ class _CounterFamily:
def _validate_label_names_against(self, normalized: tuple[tuple[str, str], ...]) -> None:
"""Ensure a concrete series write uses exactly the configured label keys."""
- if not self.label_names and normalized:
- raise ValueError(f"metric {self.name} does not accept labels")
- if self.label_names and tuple(k for k, _ in normalized) != self.label_names:
- raise ValueError(f"metric {self.name} label keys mismatch: expected {self.label_names}")
+ _validate_label_keys(self.name, self.label_names, normalized)
class _GaugeFamily:
@@ -422,6 +561,7 @@ class _GaugeFamily:
self._on_drop = on_drop
self._lock = threading.Lock()
self._values: dict[tuple[tuple[str, str], ...], float] = {}
+ self._had_deletions = False
def set(self, *, labels: Mapping[str, str] | None, value: float) -> None:
"""
@@ -451,9 +591,11 @@ class _GaugeFamily:
return
self._values[key] = self._values.get(key, 0.0) + float(delta)
- def copy_values(self) -> dict[tuple[tuple[str, str], ...], float]:
- """Return a detached copy of all gauge series values."""
+ def copy_values(self) -> dict[tuple[tuple[str, str], ...], float] | None:
+ """Return a gauge value snapshot, or None if deletion emptied this family."""
with self._lock:
+ if self._had_deletions and not self._values:
+ return None
return dict(self._values)
def get_value(self, *, labels: Mapping[str, str] | None) -> float | None:
@@ -470,6 +612,7 @@ class _GaugeFamily:
for k in keys:
if _labels_contains(k, normalized):
self._values.pop(k, None)
+ self._had_deletions = True
def _normalize_and_validate(
self, labels: Mapping[str, str] | None
@@ -514,6 +657,7 @@ class _HistogramFamily:
self._on_drop = on_drop
self._lock = threading.Lock()
self._series: dict[tuple[tuple[str, str], ...], _HistogramSeries] = {}
+ self._had_deletions = False
def observe(self, *, labels: Mapping[str, str] | None, value: float) -> None:
"""
@@ -533,23 +677,56 @@ class _HistogramFamily:
self._series[key] = series
series.observe(float(value))
+ def set(
+ self,
+ *,
+ labels: Mapping[str, str] | None,
+ bucket_counts: Sequence[int],
+ count: int,
+ value_sum: float,
+ ) -> None:
+ """Validate bucket_counts, count and value_sum before replacing labels; return None."""
+ bucket_counts, value_sum = _validate_histogram_values(
+ self.bucket_bounds, bucket_counts, count, value_sum
+ )
+ key = self._normalize_and_validate(labels)
+ with self._lock:
+ series = self._series.get(key)
+ if series is None:
+ if len(self._series) >= self._max_series:
+ self._on_drop(self.name)
+ return
+ series = _HistogramSeries(bucket_bounds=self.bucket_bounds)
+ self._series[key] = series
+ series.set_values(bucket_counts, count, value_sum)
+
+ def delete_matching(self, *, match_labels: Mapping[str, str]) -> None:
+ """Remove histogram entries containing the supplied labels; return None."""
+ normalized = normalize_labels(match_labels)
+ with self._lock:
+ for key in list(self._series):
+ if _labels_contains(key, normalized):
+ del self._series[key]
+ self._had_deletions = True
+
def copy_series(
self,
- ) -> tuple[
- tuple[str, ...],
- tuple[float, ...],
- list[tuple[tuple[tuple[str, str], ...], tuple[int, ...], int, float]],
- ]:
- """Return a detached snapshot of the histogram family and all of its series."""
+ ) -> (
+ tuple[
+ tuple[str, ...],
+ tuple[float, ...],
+ list[tuple[tuple[tuple[str, str], ...], tuple[int, ...], int, float, int]],
+ ]
+ | None
+ ):
+ """Return histogram values and start times, or None if deletion emptied this family."""
with self._lock:
- series_copy: dict[tuple[tuple[str, str], ...], _HistogramSeries] = dict(self._series)
- label_names = self.label_names
- bucket_bounds = self.bucket_bounds
- series: list[tuple[tuple[tuple[str, str], ...], tuple[int, ...], int, float]] = []
- for labels, s in series_copy.items():
- bucket_counts, count, value_sum = s.copy_values()
- series.append((labels, bucket_counts, count, value_sum))
- return label_names, bucket_bounds, series
+ if self._had_deletions and not self._series:
+ return None
+ series: list[tuple[tuple[tuple[str, str], ...], tuple[int, ...], int, float, int]] = []
+ for labels, s in self._series.items():
+ series.append((labels, *s.copy_values()))
+ return self.label_names, self.bucket_bounds, series
def _normalize_and_validate(
self, labels: Mapping[str, str] | None
@@ -568,10 +745,7 @@ class _HistogramFamily:
def _validate_label_names_against(self, normalized: tuple[tuple[str, str], ...]) -> None:
"""Ensure a concrete series write uses exactly the configured label keys."""
- if not self.label_names and normalized:
- raise ValueError(f"metric {self.name} does not accept labels")
- if self.label_names and tuple(k for k, _ in normalized) != self.label_names:
- raise ValueError(f"metric {self.name} label keys mismatch: expected {self.label_names}")
+ _validate_label_keys(self.name, self.label_names, normalized)
def _validate_buckets(self, bucket_bounds: tuple[float, ...]) -> None:
"""Ensure a histogram family is never reopened with a different bucket layout."""
@@ -589,6 +763,7 @@ class _HistogramSeries:
self._bucket_counts: list[int] = [0] * (len(bucket_bounds) + 1)
self._count: int = 0
self._sum: float = 0.0
+ self._start_time_ns = time.time_ns()
def observe(self, value: float) -> None:
"""
@@ -603,10 +778,26 @@ class _HistogramSeries:
self._count += 1
self._sum += value
- def copy_values(self) -> tuple[tuple[int, ...], int, float]:
- """Return immutable copies of bucket counts, sample count, and sum."""
+ def copy_values(self) -> tuple[tuple[int, ...], int, float, int]:
+ """Return bucket counts, sample count, sum and cumulative start time under one lock."""
with self._lock:
- return tuple(self._bucket_counts), self._count, self._sum
+ return tuple(self._bucket_counts), self._count, self._sum, self._start_time_ns
+
+ def set_values(self, bucket_counts: tuple[int, ...], count: int, value_sum: float) -> None:
+ """Replace validated totals, starting a new period if any total decreases; return None."""
+ with self._lock:
+ if (
+ count < self._count
+ or value_sum < self._sum
+ or any(
+ current < previous
+ for current, previous in zip(bucket_counts, self._bucket_counts, strict=True)
+ )
+ ):
+ self._start_time_ns = time.time_ns()
+ self._bucket_counts = list(bucket_counts)
+ self._count = count
+ self._sum = value_sum
class _Counter:
@@ -620,6 +811,10 @@ class _Counter:
"""Increment one series in the bound counter family using the public wrapper API."""
self._family.inc(labels=labels, amount=amount)
+ def set(self, value: float, *, labels: Mapping[str, str] | None = None) -> None:
+ """Replace the labelled series with a validated absolute value; return None."""
+ self._family.set(labels=labels, value=value)
+
class _Gauge:
"""Public lightweight handle used by callers to mutate one gauge family."""
@@ -636,6 +831,7 @@ class _Gauge:
"""Increase one series in the bound gauge family by a positive delta."""
self._family.add(labels=labels, delta=amount)
+
class _Histogram:
"""Public lightweight handle used by callers to mutate one histogram family."""
@@ -646,3 +842,16 @@ class _Histogram:
def observe(self, value: float, *, labels: Mapping[str, str] | None = None) -> None:
"""Record one observation for a series in the bound histogram family wrapper."""
self._family.observe(labels=labels, value=value)
+
+ def set(
+ self,
+ bucket_counts: Sequence[int],
+ count: int,
+ value_sum: float,
+ *,
+ labels: Mapping[str, str] | None = None,
+ ) -> None:
+ """Replace the labelled series using validated disjoint counts and totals; return None."""
+ self._family.set(
+ labels=labels, bucket_counts=bucket_counts, count=count, value_sum=value_sum
+ )
diff --git a/openviking/metrics/datasources/observer_state.py b/openviking/metrics/datasources/observer_state.py
index 68613729e..c428c88a9 100644
--- a/openviking/metrics/datasources/observer_state.py
+++ b/openviking/metrics/datasources/observer_state.py
@@ -6,7 +6,6 @@ from __future__ import annotations
from typing import Any
from openviking.metrics.core.base import ReadEnvelope
-from openviking.storage.viking_fs import get_viking_fs
from openviking_cli.utils import run_async
from .base import DomainStatsMetricDataSource, StateMetricDataSource
@@ -59,33 +58,6 @@ class ObserverStateDataSource(DomainStatsMetricDataSource):
return self.safe_read(_read, default={})
-class LockStateDataSource(StateMetricDataSource):
- """
- Read lock-manager counters from the pathlock observe snapshot.
-
- The datasource reads the ``pathlock_observe()`` snapshot to derive active,
- waiting, and stale lock counts.
- """
-
- def read_lock_state(self) -> ReadEnvelope[tuple[int, int, int]]:
- """
- Read active, waiting, and stale lock counts from the pathlock observe snapshot.
-
- Returns:
- A tuple of ``(active_locks, waiting_locks, stale_locks_removed)``.
- """
-
- def _read() -> tuple[int, int, int]:
- viking_fs = get_viking_fs()
- snapshot = run_async(viking_fs._async_agfs.pathlock_observe())
- active = int(snapshot.get("active_locks", 0))
- waiting = int(snapshot.get("waiting_locks", 0))
- stale = int(snapshot.get("stale_locks_removed", 0))
- return active, waiting, stale
-
- return self.safe_read(_read, default=(0, 0, 0))
-
-
class VikingDBStateDataSource(StateMetricDataSource):
"""
Read health and size signals from the active VikingDB manager, when available.
diff --git a/openviking/metrics/datasources/ragfs.py b/openviking/metrics/datasources/ragfs.py
new file mode 100644
index 000000000..1501b18e6
--- /dev/null
+++ b/openviking/metrics/datasources/ragfs.py
@@ -0,0 +1,143 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+"""Read and validate native metrics without retaining a second metrics state."""
+
+from __future__ import annotations
+
+import math
+import re
+from typing import Any
+
+from openviking.metrics.core.base import ReadEnvelope
+
+from .base import DomainStatsMetricDataSource
+
+_NAME = re.compile(r"[a-zA-Z_:][a-zA-Z0-9_:]*")
+_LABEL = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*")
+_FORBIDDEN_LABELS = frozenset(
+ {
+ "mount",
+ "account_id",
+ "path",
+ "resource_uri",
+ "user_id",
+ "session_id",
+ "owner",
+ "owner_id",
+ "lock_owner",
+ "lock_path",
+ "backend_error",
+ "error",
+ "error_message",
+ "error_text",
+ }
+)
+_FIELDS = {
+ "counter": {"name", "labels", "type", "value", "scale"},
+ "gauge": {"name", "labels", "type", "value"},
+ "histogram": {
+ "name",
+ "labels",
+ "type",
+ "bucket_bounds",
+ "bucket_counts",
+ "count",
+ "sum",
+ "scale",
+ },
+}
+
+
+def _u64(value: object) -> int:
+ """Return an unsigned 64-bit integer input, rejecting booleans and out-of-range values."""
+ if type(value) is not int or not 0 <= value <= 2**64 - 1:
+ raise ValueError("native metric integer must fit u64")
+ return value
+
+
+def _finite(value: object) -> float:
+ """Return a finite numeric input as float, rejecting booleans and nonnumeric values."""
+ if type(value) not in (int, float) or not math.isfinite(value):
+ raise ValueError("native metric value must be finite")
+ return float(value)
+
+
+class RagfsMetricDataSource(DomainStatsMetricDataSource):
+ """Read one flat native metrics batch and validate it before Registry mutation."""
+
+ def __init__(self, *, service: Any = None) -> None:
+ """Keep the service reference for late client resolution; return None."""
+ self._service = service
+
+ def read_metrics(self) -> ReadEnvelope[list[dict[str, object]]]:
+ """Return one validated native batch, or a failed envelope with an empty list."""
+ return self.safe_read(self._read, default=[])
+
+ def _read(self) -> list[dict[str, object]]:
+ """Read the current service client's metrics once and return validated raw records."""
+ client = getattr(self._service, "_agfs_client", None)
+ if client is None:
+ raise RuntimeError("RAGFS client is not available")
+ records = client.metrics()
+ if not isinstance(records, list):
+ raise ValueError("native metrics must be a list")
+ seen = set()
+ families = {}
+ for record in records:
+ if not isinstance(record, dict):
+ raise ValueError("native metric must be a dict")
+ name, labels, kind = record.get("name"), record.get("labels"), record.get("type")
+ if (
+ not isinstance(name, str)
+ or not _NAME.fullmatch(name)
+ or name.startswith("openviking_")
+ ):
+ raise ValueError("native metric name must be valid and unprefixed")
+ if not isinstance(kind, str) or kind not in _FIELDS or set(record) != _FIELDS[kind]:
+ raise ValueError("native metric fields do not match its type")
+ if not isinstance(labels, dict) or any(
+ not isinstance(key, str)
+ or not isinstance(value, str)
+ or not _LABEL.fullmatch(key)
+ or key.startswith("__")
+ or key in _FORBIDDEN_LABELS
+ or (kind == "histogram" and key == "le")
+ for key, value in labels.items()
+ ):
+ raise ValueError("native metric labels are invalid or forbidden")
+ identity = (name, tuple(sorted(labels.items())))
+ if identity in seen:
+ raise ValueError("duplicate native metric series")
+ seen.add(identity)
+ scale, bounds = None, ()
+ if kind == "gauge":
+ _finite(record["value"])
+ else:
+ scale = _finite(record["scale"])
+ if scale <= 0:
+ raise ValueError("native metric scale must be positive")
+ if kind == "counter":
+ _finite(_u64(record["value"]) * scale)
+ else:
+ raw_bounds, counts = record["bucket_bounds"], record["bucket_counts"]
+ if not isinstance(raw_bounds, list) or not isinstance(counts, list):
+ raise ValueError("native histogram bounds and counts must be lists")
+ bounds = tuple(_u64(bound) for bound in raw_bounds)
+ scaled_bounds = tuple(_finite(bound * scale) for bound in bounds)
+ if any(
+ left >= right for left, right in zip(bounds, bounds[1:], strict=False)
+ ) or any(
+ left >= right
+ for left, right in zip(scaled_bounds, scaled_bounds[1:], strict=False)
+ ):
+ raise ValueError("native histogram bounds must remain increasing")
+ count = _u64(record["count"])
+ if len(counts) != len(bounds) + 1 or sum(_u64(n) for n in counts) != count:
+ raise ValueError("native histogram counts do not match bounds or count")
+ _finite(_u64(record["sum"]) * scale)
+ shape = (kind, tuple(sorted(labels)), scale, bounds)
+ if name in families and families[name] != shape:
+ raise ValueError("inconsistent native metric family")
+ families[name] = shape
+ return records
diff --git a/openviking/metrics/exporters/otel.py b/openviking/metrics/exporters/otel.py
index d48793a74..936e2e023 100644
--- a/openviking/metrics/exporters/otel.py
+++ b/openviking/metrics/exporters/otel.py
@@ -355,7 +355,7 @@ class OTelMetricExporter(MetricExporter):
Empty unlabeled counters emit a single zero data point to match PrometheusExporter.
"""
- for name, counter_series in self._registry.iter_counters():
+ for name, counter_series in self._registry.iter_counters(include_start_time=True):
metric = metrics.add()
metric.name = name
metric.description = "OpenViking metric."
@@ -379,7 +379,9 @@ class OTelMetricExporter(MetricExporter):
Bucket counts and explicit bounds are copied directly from the registry snapshot.
"""
- for name, label_names, bucket_bounds, series_iter in self._registry.iter_histograms():
+ for name, label_names, bucket_bounds, series_iter in self._registry.iter_histograms(
+ include_start_time=True
+ ):
series_list = list(series_iter)
metric = metrics.add()
metric.name = name
@@ -400,9 +402,9 @@ class OTelMetricExporter(MetricExporter):
This mirrors the `openviking_metrics_dropped_series_total` metric emitted by
PrometheusExporter.
"""
- dropped_points: list[tuple[tuple[tuple[str, str], ...], float]] = []
+ dropped_points: list[tuple[tuple[tuple[str, str], ...], float, int]] = []
for metric_name, dropped in self._registry.iter_dropped_series():
- dropped_points.append(((("metric", metric_name),), float(dropped)))
+ dropped_points.append(((("metric", metric_name),), float(dropped), self._start_time_ns))
if not dropped_points:
return
@@ -417,7 +419,7 @@ class OTelMetricExporter(MetricExporter):
Build an OTLP Sum message from a counter-like registry family.
Args:
- series: List of `(labels, value)` tuples from MetricRegistry.
+ series: List of `(labels, value, start_time_ns)` tuples from MetricRegistry.
now_ns: Export timestamp in nanoseconds.
name: Metric family name for zero-series handling.
"""
@@ -435,13 +437,13 @@ class OTelMetricExporter(MetricExporter):
sum_metric.data_points.append(point)
return sum_metric
- for labels, value in series:
+ for labels, value, start_time_ns in series:
point = NumberDataPoint(
- start_time_unix_nano=self._start_time_ns,
- time_unix_nano=now_ns,
+ start_time_unix_nano=start_time_ns,
+ time_unix_nano=max(now_ns, start_time_ns),
)
point.attributes.extend(self._build_attributes(labels))
- if float(value).is_integer():
+ if float(value).is_integer() and -(2**63) <= value < 2**63:
point.as_int = int(value)
else:
point.as_double = float(value)
@@ -467,7 +469,7 @@ class OTelMetricExporter(MetricExporter):
for labels, value in series:
point = NumberDataPoint(time_unix_nano=now_ns)
point.attributes.extend(self._build_attributes(labels))
- if float(value).is_integer():
+ if float(value).is_integer() and -(2**63) <= value < 2**63:
point.as_int = int(value)
else:
point.as_double = float(value)
@@ -486,10 +488,9 @@ class OTelMetricExporter(MetricExporter):
Build an OTLP Histogram message from a registry histogram family.
Args:
- name: Histogram family name.
label_names: Registered label keys for the family.
bucket_bounds: Explicit bucket upper bounds from the registry.
- series_list: Histogram series snapshot from the registry.
+ series_list: Registry series with bucket counts, totals and start_time_ns.
now_ns: Export timestamp in nanoseconds.
"""
histogram_metric = Histogram(
@@ -508,10 +509,10 @@ class OTelMetricExporter(MetricExporter):
histogram_metric.data_points.append(point)
return histogram_metric
- for labels, bucket_counts, count, value_sum in series_list:
+ for labels, bucket_counts, count, value_sum, start_time_ns in series_list:
point = HistogramDataPoint(
- start_time_unix_nano=self._start_time_ns,
- time_unix_nano=now_ns,
+ start_time_unix_nano=start_time_ns,
+ time_unix_nano=max(now_ns, start_time_ns),
count=int(count),
sum=float(value_sum),
)
diff --git a/tests/agfs/test_fs_binding.py b/tests/agfs/test_fs_binding.py
index 9525be1ec..1599b5c00 100644
--- a/tests/agfs/test_fs_binding.py
+++ b/tests/agfs/test_fs_binding.py
@@ -44,6 +44,55 @@ async def viking_fs_binding_instance():
class TestVikingFSBindingLocal:
"""Test VikingFS operations with binding mode (local backend)."""
+ async def test_native_metrics_and_legacy_stats(self, viking_fs_binding_instance):
+ """Use the binding fixture to check flat metrics and legacy stats; return None."""
+ client = viking_fs_binding_instance._async_agfs
+ metrics = await client.run("metrics")
+ shapes = {
+ "counter": {"value", "scale"},
+ "gauge": {"value"},
+ "histogram": {"bucket_bounds", "bucket_counts", "count", "sum", "scale"},
+ }
+ assert {m["type"] for m in metrics} == set(shapes)
+ for metric in metrics:
+ assert set(metric) == {"name", "labels", "type"} | shapes[metric["type"]]
+ assert not metric["name"].startswith("openviking_")
+ assert set(metric["labels"]) <= {
+ "plugin",
+ "operation",
+ "status",
+ "kind",
+ "result",
+ "source",
+ "event",
+ "route",
+ }
+ if metric["type"] == "histogram":
+ assert len(metric["bucket_counts"]) == len(metric["bucket_bounds"]) + 1 == 12
+ assert sum(metric["bucket_counts"]) == metric["count"]
+ assert metric["scale"] == 1e-9 and type(metric["sum"]) is int
+ else:
+ assert type(metric["value"]) is (int if metric["type"] == "counter" else float)
+ all_stats = await client.run("get_stats")
+ assert set(all_stats) == {"mounts"} and all_stats["mounts"]
+ scoped = await client.run("get_stats", path=all_stats["mounts"][0]["path"])
+ for mount in [*all_stats["mounts"], scoped]:
+ assert set(mount) == {"path", "plugin", "stats"}
+ for stats in mount["stats"]["operations"].values():
+ assert set(stats) == {
+ "count",
+ "total_time_us",
+ "min_time_us",
+ "max_time_us",
+ "avg_time_us",
+ }
+ assert all(
+ type(value) is (float if key == "avg_time_us" else int)
+ for key, value in stats.items()
+ )
+ if stats["count"] == 0:
+ assert stats["min_time_us"] == 2**64 - 1 and stats["avg_time_us"] == 0.0
+
async def test_file_operations(self, viking_fs_binding_instance):
"""Test VikingFS file operations: read, write, ls, stat."""
vfs = viking_fs_binding_instance
diff --git a/tests/metrics/collectors/test_collector_contracts.py b/tests/metrics/collectors/test_collector_contracts.py
index f0794c3b3..dc9e425ef 100644
--- a/tests/metrics/collectors/test_collector_contracts.py
+++ b/tests/metrics/collectors/test_collector_contracts.py
@@ -347,12 +347,13 @@ def test_prometheus_exporter_inherits_base_metric_exporter():
def test_concrete_datasources_and_collectors_follow_doc_inheritance():
from openviking.metrics.collectors.base import (
+ DomainStatsMetricCollector,
ProbeMetricCollector,
Refreshable,
StateMetricCollector,
)
- from openviking.metrics.collectors.lock import LockCollector
from openviking.metrics.collectors.queue import QueueCollector
+ from openviking.metrics.collectors.ragfs import RagfsMetricCollector
from openviking.metrics.collectors.service_probe import ServiceProbeCollector
from openviking.metrics.collectors.vikingdb import VikingDBCollector
from openviking.metrics.datasources.base import (
@@ -361,25 +362,25 @@ def test_concrete_datasources_and_collectors_follow_doc_inheritance():
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
+ from openviking.metrics.datasources.ragfs import RagfsMetricDataSource
assert issubclass(QueuePipelineStateDataSource, StateMetricDataSource)
assert issubclass(ObserverStateDataSource, DomainStatsMetricDataSource)
- assert issubclass(LockStateDataSource, StateMetricDataSource)
+ assert issubclass(RagfsMetricDataSource, DomainStatsMetricDataSource)
assert issubclass(VikingDBStateDataSource, StateMetricDataSource)
assert issubclass(ServiceProbeDataSource, ProbeMetricDataSource)
assert issubclass(QueueCollector, StateMetricCollector)
- assert issubclass(LockCollector, StateMetricCollector)
+ assert issubclass(RagfsMetricCollector, DomainStatsMetricCollector)
assert issubclass(VikingDBCollector, StateMetricCollector)
assert issubclass(ServiceProbeCollector, ProbeMetricCollector)
assert issubclass(QueueCollector, Refreshable)
- assert issubclass(LockCollector, Refreshable)
+ assert issubclass(RagfsMetricCollector, Refreshable)
assert issubclass(VikingDBCollector, Refreshable)
assert issubclass(ServiceProbeCollector, Refreshable)
diff --git a/tests/metrics/collectors/test_state_collectors.py b/tests/metrics/collectors/test_state_collectors.py
index 9f8491245..67ef5b2c1 100644
--- a/tests/metrics/collectors/test_state_collectors.py
+++ b/tests/metrics/collectors/test_state_collectors.py
@@ -3,6 +3,12 @@
from __future__ import annotations
+from concurrent.futures import ThreadPoolExecutor
+from threading import Event
+from types import SimpleNamespace
+
+import pytest
+
from openviking.metrics.collectors.observer_health import ObserverHealthCollector
from openviking.metrics.collectors.queue import QueueCollector
from openviking.metrics.collectors.task_tracker import TaskTrackerCollector
@@ -249,3 +255,111 @@ def test_vikingdb_collector_exports_health_and_count(monkeypatch):
assert (
'openviking_vikingdb_collection_vectors{collection="my_collection",valid="1"} 123.0' in text
)
+
+
+def test_ragfs_collector_replaces_recovers_and_deletes(monkeypatch):
+ """Drive real registry writes through controlled native batches and faults; return None."""
+ from openviking.metrics.collectors.ragfs import RagfsMetricCollector
+ from openviking.metrics.datasources.ragfs import RagfsMetricDataSource
+
+ records = []
+ service = SimpleNamespace(_agfs_client=SimpleNamespace(metrics=lambda: records))
+ collector = RagfsMetricCollector(data_source=RagfsMetricDataSource(service=service))
+ registry = MetricRegistry()
+ for count in (4, 2, 0):
+ records[:] = [
+ {
+ "name": "ragfs_calls_total",
+ "labels": {},
+ "type": "counter",
+ "value": count,
+ "scale": 1.0,
+ },
+ {"name": "ragfs_tasks", "labels": {}, "type": "gauge", "value": float(count)},
+ {
+ "name": "ragfs_latency_seconds",
+ "labels": {},
+ "type": "histogram",
+ "bucket_bounds": [1000],
+ "bucket_counts": [count, 0],
+ "count": count,
+ "sum": 123 * count,
+ "scale": 1e-9,
+ },
+ ]
+ collector.collect(registry)
+ assert dict(registry.iter_counters())["openviking_ragfs_calls_total"] == [((), count)]
+ assert registry.gauge_get("openviking_ragfs_tasks") == count
+ hist = list(registry.iter_histograms())[0]
+ assert hist[2] == pytest.approx((1e-6,))
+ assert hist[3][0][1:3] == ((count, 0), count)
+ assert hist[3][0][3] == pytest.approx(123e-9 * count)
+ assert "account_id" not in PrometheusExporter(registry=registry).render()
+ previous = PrometheusExporter(registry=registry).render()
+ records.append({"broken": True})
+ with pytest.raises(RuntimeError):
+ collector.collect(registry)
+ assert PrometheusExporter(registry=registry).render() == previous
+
+ def fail(*args, **kwargs):
+ """Raise an injected storage error for supplied write or delete arguments."""
+ raise RuntimeError("injected")
+
+ records[:] = [
+ {
+ "name": "ragfs_partial_total",
+ "labels": {},
+ "type": "counter",
+ "value": 9,
+ "scale": 1.0,
+ },
+ {"name": "ragfs_tasks", "labels": {}, "type": "gauge", "value": 1.0},
+ ]
+ with monkeypatch.context() as patch:
+ patch.setattr(registry, "set_gauge", fail)
+ with pytest.raises(RuntimeError, match="injected"):
+ collector.collect(registry)
+ assert dict(registry.iter_counters())["openviking_ragfs_partial_total"] == [((), 9)]
+ records.clear()
+ with monkeypatch.context() as patch:
+ patch.setattr(registry, "counter_delete_matching", fail)
+ with pytest.raises(RuntimeError, match="injected"):
+ collector.collect(registry)
+ collector.collect(registry)
+ assert list(registry.iter_counters()) == []
+ assert list(registry.iter_gauges()) == []
+ assert list(registry.iter_histograms()) == []
+ assert "openviking_ragfs_" not in PrometheusExporter(registry=registry).render()
+
+
+def test_ragfs_collector_serializes_whole_refresh():
+ """Hold a native read with Events and verify concurrent refresh cannot overwrite it."""
+ from openviking.metrics.collectors.ragfs import RagfsMetricCollector
+ from openviking.metrics.datasources.ragfs import RagfsMetricDataSource
+
+ entered, release = Event(), Event()
+ calls = []
+
+ def metrics():
+ """Block one native read until released and return a gauge record."""
+ calls.append(1)
+ entered.set()
+ assert release.wait(5)
+ return [{"name": "ragfs_tasks", "labels": {}, "type": "gauge", "value": 3.0}]
+
+ collector = RagfsMetricCollector(
+ data_source=RagfsMetricDataSource(
+ service=SimpleNamespace(_agfs_client=SimpleNamespace(metrics=metrics))
+ )
+ )
+ registry = MetricRegistry()
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ first = pool.submit(collector.collect, registry)
+ try:
+ assert entered.wait(5)
+ pool.submit(collector.collect, registry).result(timeout=2)
+ assert len(calls) == 1
+ finally:
+ release.set()
+ first.result(timeout=5)
+ assert registry.gauge_get("openviking_ragfs_tasks") == 3
diff --git a/tests/metrics/core/test_registry.py b/tests/metrics/core/test_registry.py
index d17e238d7..3ba9304e1 100644
--- a/tests/metrics/core/test_registry.py
+++ b/tests/metrics/core/test_registry.py
@@ -7,6 +7,7 @@ import pytest
from openviking.metrics.core.base import MetricCollector
from openviking.metrics.core.registry import MetricRegistry
+from openviking.metrics.exporters.otel import OTelMetricExporter
def test_metric_collector_metric_name_includes_namespace_and_optional_unit():
@@ -81,3 +82,217 @@ def test_collectors_do_not_embed_openviking_metric_name_literals():
if '"openviking_' in text or "'openviking_" in text:
offenders.append(path.name)
assert offenders == []
+
+
+def test_registry_absolute_values_and_deletion():
+ """Use real families with fixed inputs to verify replacement and deletion; return None."""
+ registry = MetricRegistry(max_series_per_metric=1)
+ labels = {"plugin": "memfs"}
+ for value in (10, 12, 3, 0):
+ registry.set_counter("calls_total", value, labels=labels, label_names=("plugin",))
+ registry.set_histogram(
+ "latency_seconds",
+ bucket_bounds=(0.001,),
+ bucket_counts=(value, 0),
+ count=value,
+ value_sum=value * 0.001,
+ labels=labels,
+ label_names=("plugin",),
+ )
+ assert dict(registry.iter_counters())["calls_total"] == [(tuple(labels.items()), value)]
+ assert list(registry.iter_histograms())[0][3] == [
+ (tuple(labels.items()), (value, 0), value, value * 0.001)
+ ]
+ registry.inc_counter("calls_total", labels=labels, label_names=("plugin",))
+ registry.observe_histogram(
+ "latency_seconds",
+ 0.002,
+ labels=labels,
+ label_names=("plugin",),
+ buckets=(0.001,),
+ )
+ assert list(registry.iter_histograms())[0][3][0][1:] == ((0, 1), 1, 0.002)
+ registry.set_counter("calls_total", 5, labels={"plugin": "other"}, label_names=("plugin",))
+ assert dict(registry.iter_counters())["calls_total"][0][1] == 1
+ assert dict(registry.iter_dropped_series()) == {"calls_total": 1}
+ for name, method in (
+ ("calls_total", registry.counter_delete_matching),
+ ("latency_seconds", registry.histogram_delete_matching),
+ ):
+ method(name, match_labels={"plugin": "other"})
+ method(name, match_labels=labels)
+ method(name, match_labels=labels)
+ assert list(registry.iter_counters()) == []
+ assert list(registry.iter_histograms()) == []
+
+
[email protected]("value", [-1, float("inf"), float("nan")])
+def test_registry_rejects_invalid_absolute_counter(value):
+ """Reject invalid counter input without replacing the previous value; return None."""
+ registry = MetricRegistry()
+ registry.set_counter("calls_total", 4)
+ with pytest.raises(ValueError):
+ registry.set_counter("calls_total", value)
+ assert dict(registry.iter_counters())["calls_total"] == [((), 4)]
+ empty = MetricRegistry()
+ with pytest.raises(ValueError):
+ empty.set_counter("calls_total", value)
+ assert list(empty.iter_counters()) == []
+
+
+ "changes",
+ [
+ {"bucket_bounds": (1.0, 0.0)},
+ {"bucket_bounds": (float("inf"),)},
+ {"bucket_counts": (1,)},
+ {"bucket_counts": (-1, 2)},
+ {"count": 2},
+ {"count": True},
+ {"bucket_counts": (True, 0)},
+ {"value_sum": float("nan")},
+ ],
+)
+def test_registry_rejects_invalid_absolute_histogram(changes):
+ """Reject malformed histogram input without corrupting an existing series; return None."""
+ registry = MetricRegistry()
+ values = {
+ "bucket_bounds": (0.001,),
+ "bucket_counts": (1, 0),
+ "count": 1,
+ "value_sum": 0.001,
+ }
+ registry.set_histogram("latency_seconds", **values)
+ before = list(registry.iter_histograms())
+ with pytest.raises(ValueError):
+ registry.set_histogram("latency_seconds", **(values | changes))
+ assert list(registry.iter_histograms()) == before
+ empty = MetricRegistry()
+ with pytest.raises(ValueError):
+ empty.set_histogram("latency_seconds", **(values | changes))
+ assert list(empty.iter_histograms()) == []
+ empty.set_histogram("latency_seconds", **values)
+ assert list(empty.iter_histograms()) == before
+
+
+def test_registry_deletion_hides_empty_families_but_keeps_contract(render_prometheus):
+ """Delete all series for each type and verify export absence and schema retention."""
+ registry = MetricRegistry()
+ registry.counter("untouched_total")
+ registry.gauge("untouched_gauge")
+ registry.histogram("untouched_histogram")
+ registry.counter_delete_matching("untouched_total", match_labels={})
+ registry.gauge_delete_matching("untouched_gauge", match_labels={})
+ registry.histogram_delete_matching("untouched_histogram", match_labels={})
+ assert "untouched_total 0" in render_prometheus(registry)
+ registry.set_counter("removed_total", 1)
+ registry.set_gauge("removed_gauge", 1)
+ registry.set_histogram(
+ "removed_histogram",
+ bucket_bounds=[1],
+ bucket_counts=[1, 0],
+ count=1,
+ value_sum=1,
+ )
+ for kind, name in (
+ ("counter", "removed_total"),
+ ("gauge", "removed_gauge"),
+ ("histogram", "removed_histogram"),
+ ):
+ getattr(registry, f"{kind}_delete_matching")(name, match_labels={})
+ text = render_prometheus(registry)
+ assert "removed_" not in text
+ assert "untouched_total 0" in text and "untouched_gauge 0" in text
+ assert "untouched_histogram_count 0" in text
+ exporter = OTelMetricExporter(registry=registry, enabled=False)
+ request = exporter._build_export_request()
+ metrics = {m.name: m for m in request.resource_metrics[0].scope_metrics[0].metrics}
+ assert set(metrics) == {"untouched_total", "untouched_gauge", "untouched_histogram"}
+ assert metrics["untouched_total"].sum.data_points[0].as_int == 0
+ assert metrics["untouched_gauge"].gauge.data_points[0].as_int == 0
+ assert metrics["untouched_histogram"].histogram.data_points[0].count == 0
+ with pytest.raises(ValueError):
+ registry.gauge("removed_total")
+ with pytest.raises(ValueError):
+ registry.histogram("removed_histogram", buckets=[2])
+ with pytest.raises(ValueError):
+ registry.counter("removed_total").set(-1)
+ with pytest.raises(ValueError):
+ registry.histogram("removed_histogram", buckets=[1]).set((1,), 1, 1)
+ assert "removed_" not in render_prometheus(registry)
+ registry.set_counter("removed_total", 2)
+ registry.gauge("removed_gauge").inc(2)
+ registry.histogram("removed_histogram", buckets=[1]).observe(0.5)
+ text = render_prometheus(registry)
+ assert "removed_total 2" in text
+ assert "removed_gauge 2.0" in text
+ assert "removed_histogram_count 1" in text
+ request = exporter._build_export_request()
+ metrics = {m.name: m for m in request.resource_metrics[0].scope_metrics[0].metrics}
+ assert metrics["removed_total"].sum.data_points[0].as_int == 2
+ assert metrics["removed_gauge"].gauge.data_points[0].as_int == 2
+ assert metrics["removed_histogram"].histogram.data_points[0].count == 1
+
+
[email protected]("kind", ("counter", "gauge", "histogram"))
+def test_registry_partial_deletion_keeps_active_series(kind, render_prometheus):
+ """Delete selected labels for kind; retain active values and the label contract."""
+ registry = MetricRegistry()
+ options = {"buckets": [1]} if kind == "histogram" else {}
+ handle = getattr(registry, kind)("active", label_names=("plugin",), **options)
+ for plugin in ("removed", "kept"):
+ if kind == "histogram":
+ handle.observe(0.5, labels={"plugin": plugin})
+ else:
+ handle.inc(labels={"plugin": plugin})
+ delete = getattr(registry, f"{kind}_delete_matching")
+ delete("active", match_labels={"plugin": "removed"})
+ text = render_prometheus(registry)
+ assert 'plugin="removed"' not in text
+ sample = "active_count" if kind == "histogram" else "active"
+ assert f'{sample}{{plugin="kept"}} 1' in text
+ delete("active", match_labels={"plugin": "kept"})
+ assert "active" not in render_prometheus(registry)
+ with pytest.raises(ValueError):
+ getattr(registry, kind)("active", label_names=("other",), **options)
+ if kind == "histogram":
+ handle.set((0, 0), 0, 0, labels={"plugin": "kept"})
+ else:
+ handle.set(0, labels={"plugin": "kept"})
+ assert f'{sample}{{plugin="kept"}} 0' in render_prometheus(registry)
+
+
+def test_registry_handles_validate_absolute_values(render_prometheus):
+ """Call public handles with integer and invalid inputs and verify validated storage."""
+ registry = MetricRegistry()
+ counter = registry.counter("calls_total")
+ counter.set(1)
+ assert "calls_total 1" in render_prometheus(registry)
+ for value in (-1, float("inf"), float("-inf"), float("nan")):
+ with pytest.raises(ValueError):
+ counter.set(value)
+ assert dict(registry.iter_counters())["calls_total"] == [((), 1)]
+ histogram = registry.histogram("latency", buckets=[1])
+ histogram.set([1, 0], 1, 1)
+ assert "latency_sum 1.0" in render_prometheus(registry)
+ before = list(registry.iter_histograms())
+ for counts, count, value_sum in (
+ ((1,), 1, 1),
+ ((-1, 2), 1, 1),
+ ((True, 0), 1, 1),
+ ((1.0, 0), 1, 1),
+ ((1, 0), True, 1),
+ ((1, 0), 2, 1),
+ ((1, 0), 1, -1),
+ ((1, 0), 1, float("inf")),
+ ((1, 0), 1, float("nan")),
+ ):
+ with pytest.raises(ValueError):
+ histogram.set(counts, count, value_sum)
+ assert list(registry.iter_histograms()) == before
+ for bounds in ((-1,), (float("inf"),), (float("nan"),), (1, 1), (2, 1)):
+ invalid = MetricRegistry()
+ handle = invalid.histogram("invalid", buckets=bounds)
+ with pytest.raises(ValueError):
+ handle.set((0,) * (len(bounds) + 1), 0, 0)
+ assert list(invalid.iter_histograms())[0][3] == []
diff --git a/tests/metrics/datasources/test_state_datasources.py b/tests/metrics/datasources/test_state_datasources.py
index 650ec92e6..76f133bdf 100644
--- a/tests/metrics/datasources/test_state_datasources.py
+++ b/tests/metrics/datasources/test_state_datasources.py
@@ -6,6 +6,8 @@ from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
+import pytest
+
import openviking.metrics.datasources.probes as probes
from openviking.metrics.collectors.base import (
CollectorConfig,
@@ -233,3 +235,99 @@ def test_async_system_probe_datasource_returns_default_on_exception(monkeypatch)
assert env.ok is False
assert env.value == {"queue": False}
assert env.error_type == "RuntimeError"
+
+
+ "changes",
+ [
+ {},
+ {"name": "openviking_calls"},
+ {"name": "bad name"},
+ {"value": True},
+ {"value": -1},
+ {"value": 2**64},
+ {"scale": 0.0},
+ {"scale": float("inf")},
+ {"scale": 1e308},
+ {"labels": {"mount": "/local"}},
+ {"labels": {"account_id": "x"}},
+ {"labels": {"path": "/a"}},
+ {"labels": {"__name__": "x"}},
+ {"type": "unknown"},
+ ],
+)
+def test_ragfs_datasource_validates_records(changes):
+ """Use native-shaped counter input to check validation and one read; return None."""
+ from openviking.metrics.datasources.ragfs import RagfsMetricDataSource
+
+ calls = []
+ records = [
+ {
+ "name": "ragfs_calls_total",
+ "labels": {},
+ "type": "counter",
+ "value": 123,
+ "scale": 1.0,
+ }
+ | changes
+ ]
+
+ def metrics():
+ """Record one native read and return the controlled batch."""
+ calls.append(1)
+ return records
+
+ service = SimpleNamespace(_agfs_client=SimpleNamespace(metrics=metrics))
+ source = RagfsMetricDataSource(service=service)
+ result = source.read_metrics()
+ assert result.ok is (not changes)
+ assert result.value == (records if not changes else [])
+ assert len(calls) == 1
+ service._agfs_client = None
+ assert source.read_metrics().ok is False
+
+
+ "changes",
+ [
+ {},
+ {"bucket_counts": [1]},
+ {"bucket_counts": [True, 0]},
+ {"count": 3},
+ {"bucket_bounds": [2, 1]},
+ {"sum": -1},
+ {"bucket_bounds": [2**53, 2**53 + 1], "bucket_counts": [1, 0, 0]},
+ ],
+)
+def test_ragfs_datasource_validates_histogram_and_family(changes):
+ """Check histogram shape, duplicates and same-name contracts from batches; return None."""
+ from openviking.metrics.datasources.ragfs import RagfsMetricDataSource
+
+ record = {
+ "name": "ragfs_duration_seconds",
+ "labels": {"plugin": "localfs"},
+ "type": "histogram",
+ "bucket_bounds": [1000],
+ "bucket_counts": [1, 0],
+ "count": 1,
+ "sum": 123,
+ "scale": 1e-9,
+ } | changes
+ records = [record]
+ source = RagfsMetricDataSource(
+ service=SimpleNamespace(_agfs_client=SimpleNamespace(metrics=lambda: records))
+ )
+ assert source.read_metrics().ok is (not changes)
+ if not changes:
+ for other in (
+ record,
+ record | {"labels": {}},
+ record | {"scale": 1.0},
+ record | {"bucket_bounds": [2000]},
+ ):
+ records[:] = [record, other]
+ assert source.read_metrics().ok is False
+ records[:] = [{"name": "ragfs_tasks", "labels": {}, "type": "gauge", "value": -2.0}]
+ assert source.read_metrics().ok
+ records[0]["value"] = float("nan")
+ assert not source.read_metrics().ok
diff --git a/tests/metrics/integration/test_bootstrap.py b/tests/metrics/integration/test_bootstrap.py
index b26e961be..5c0f93432 100644
--- a/tests/metrics/integration/test_bootstrap.py
+++ b/tests/metrics/integration/test_bootstrap.py
@@ -28,7 +28,7 @@ def test_create_default_collector_manager_registers_expected_collectors_in_order
"TaskTrackerCollector",
"ObserverHealthCollector",
"ObserverStateCollector",
- "LockCollector",
+ "RagfsMetricCollector",
"VikingDBCollector",
"ModelUsageCollector",
"ServiceProbeCollector",
@@ -59,7 +59,7 @@ def test_create_default_collector_manager_registers_feedback_collector_when_bot_
"FeedbackCollector",
"ObserverHealthCollector",
"ObserverStateCollector",
- "LockCollector",
+ "RagfsMetricCollector",
"VikingDBCollector",
"ModelUsageCollector",
"ServiceProbeCollector",
diff --git a/tests/server/test_prometheus_metrics.py b/tests/server/test_prometheus_metrics.py
index 977750b0f..77ed66598 100644
--- a/tests/server/test_prometheus_metrics.py
+++ b/tests/server/test_prometheus_metrics.py
@@ -4,6 +4,7 @@
"""Tests for the Prometheus metrics endpoint and exposition output."""
import json
+from types import SimpleNamespace
import httpx
import pytest
@@ -120,6 +121,33 @@ class TestRetrievalStatsMetricsIntegration:
class TestMetricsEndpoint:
"""Tests for the /metrics HTTP endpoint."""
+ async def test_ragfs_authoritative_metrics_endpoint(self):
+ """Export fixed native records through bootstrap and HTTP; return None."""
+ records = [
+ {"name": "lock_active", "labels": {}, "type": "gauge", "value": 2.0},
+ {"name": "lock_stale", "labels": {}, "type": "gauge", "value": 7.0},
+ ]
+ service = SimpleNamespace(_agfs_client=SimpleNamespace(metrics=lambda: records))
+ config = ServerConfig(
+ observability=ObservabilityConfig(metrics=MetricsConfig(enabled=True))
+ )
+ app = create_app(config=config, service=None)
+ init_metrics_from_server_config(config, app=app, service=service)
+ try:
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ response = await client.get("/metrics")
+ assert response.status_code == 200
+ assert "# TYPE openviking_lock_active gauge" in response.text
+ assert "openviking_lock_active 2.0" in response.text
+ assert "# TYPE openviking_lock_stale gauge" in response.text
+ assert "openviking_lock_stale 7.0" in response.text
+ assert "openviking_lock_active_leases" not in response.text
+ assert "openviking_lock_stale_tokens_removed_total" not in response.text
+ finally:
+ shutdown_metrics(app=app)
+
async def test_metrics_disabled_returns_404(self):
config = ServerConfig()
app = create_app(config=config, service=None)