RAGFS Cache
RAGFS cache is an optional read-cache layer for OpenViking query results. It speeds up stat, read_dir, tree_directory, glob_directory, and grep. It is only an acceleration layer, not the source of truth; backend filesystem data remains authoritative.
CachedFileSystem assumptions:
- Only one OpenViking / RAGFS process writes to the same cache namespace.
- File and directory changes go through RAGFS.
- The backend is not modified externally by bypassing RAGFS.
- After a cache Provider successfully writes or deletes one key, later reads of that key do not return the old value.
These assumptions apply to the read-cache layer. QueueFS and PathLock also use CacheRuntime, but define their own consistency rules.
Quick Start
For first-time setup, complete the base configuration first:
openviking-server init
openviking-server doctorConfigure the global top-level cache Provider, then select backend=cache under storage.agfs.cachefs:
{
"service_name": "openviking-server",
"cache": {
"provider": "redis",
"params": {
"mode": "standalone",
"endpoints": ["redis://127.0.0.1:6379"],
"pool_size": 32,
"connect_timeout_ms": 1000,
"command_timeout_ms": 1000,
"default_ttl_seconds": 300
}
},
"storage": {
"workspace": "./data",
"agfs": {
"backend": "local",
"cachefs": {
"backend": "cache"
},
"pathlock": {
"provider": "cache",
"lock_expire_secs": 30.0
}
}
}
}Start Redis and OpenViking:
redis-serverIn a second terminal, start OpenViking:
openviking-server --config ~/.openviking/ov.confIf the configuration file is at the default path ~/.openviking/ov.conf, you can also run:
openviking-serverAvailable Providers:
| Provider | Best for | Notes |
|---|---|---|
redis | Default delivery on standard networks | Built into RAGFS; supports standalone, Cluster, and Sentinel |
dynamic | YuanRong, Mooncake, or closed-source cache systems | Loaded from an external shared library through the versioned C ABI |
MemoryMockProvider is only used by unit and smoke tests; it is not a production configuration option.
Cache-backed PathLock
Set storage.agfs.pathlock.provider to cache to coordinate path locks between OpenViking processes through the shared Redis CacheRuntime. OpenViking derives the PathLock Redis namespace from top-level service_name. Use distinct service names for independent deployments. Distributed path locking does not remove the single-writer requirement of CachedFileSystem. Cache-backed PathLock only supports the built-in Redis Provider.
Redis HASH keys are partitioned by logical path scope:
{service_name}:ov:pathlock:global:tokens
{service_name}:ov:pathlock:scope:_system:tokens
{service_name}:ov:pathlock:scope:account:{account}:tokens{service_name} is used as the Redis Cluster hash tag, so all PathLock keys for one deployment remain in one slot. Tree conflict checks scan only the HASH for the request scope. / and /local use the global HASH but do not scan account or _system HASHes. A batch containing paths from different scopes is rejected.
Do not run versions that use the legacy single HASH key together with versions that use scoped keys. Stop old writers, wait at least 2 * lock_expire_secs for legacy keys to expire, and then start the new version.
Breaking Configuration Change
Legacy cache configuration is no longer accepted. Migrate before upgrading:
| Removed configuration | Canonical replacement |
|---|---|
storage.agfs.cache | top-level cache.provider + cache.params, plus storage.agfs.cachefs.backend="cache" |
storage.agfs.queuefs.backend="redis" and queuefs.redis | storage.agfs.queuefs.backend="cache", plus the shared top-level cache section |
Redis mode="singleton" | mode="standalone" |
tls_enabled=true | use rediss:// endpoints |
read_from_replica | removed; all reads use the primary |
DynamicProvider
OpenViking ships the DynamicProvider loader and a versioned C ABI. The default wheel does not bundle third-party SDKs or Provider libraries. Deploy the Provider shared library separately and configure provider=dynamic when an external cache system is required.
A dynamic library must export this versioned entry point:
openviking_cache_provider_v1The C contract is defined by crates/ragfs/include/openviking_cache_provider_v1.h. The Provider must use the Host allocator for returned data, obey the documented ownership and close semantics, catch exceptions before they cross the C ABI, and make its handle safe for concurrent calls.
Provider artifacts should declare the ABI version, target OS and CPU, minimum runtime version, external SDK version, dynamic dependencies, and SHA256. When a Provider depends on native libraries, its publisher must make them discoverable through RPATH, LD_LIBRARY_PATH, or deployment instructions.
External Providers can be upgraded independently without rebuilding the default OpenViking wheel. OpenViking only needs a coordinated upgrade when the DynamicProvider ABI becomes incompatible.
Configuration
Top-level service_name defaults to "openviking-server" and supplies the Redis namespace for CacheFS, QueueFS cache backend, cache-backed PathLock, and cache-backed multi-write metadata.
The top-level cache section is a sibling of storage:
| Option | Type | Default | Description |
|---|---|---|---|
provider | str | none | Provider name; supports redis and dynamic |
params | object | {} | Provider-owned parameters |
storage.agfs.cachefs controls CacheFS behavior:
| Option | Type | Default | Description |
|---|---|---|---|
backend | str | "local" | local preserves existing behavior; cache enables CachedFileSystem |
shared_redis_ttl_seconds | int | 0 | TTL override for every query bucket when CacheFS shares a Redis service with QueueFS, cache-backed PathLock, or the expiry scheduler; 0 keeps the provider default |
shared_redis_ttl_seconds applies uniformly to stat, read_dir, tree_directory, glob_directory, and grep buckets. It does not encode a per-file priority: after the query-driven CacheFS refactor, cached objects are query results rather than file bodies or directory entries. Set it lower than the provider's default_ttl_seconds to bound cache retention when stateful modules share the service. OpenViking ignores the option when CacheFS uses an isolated Redis service.
storage.agfs.pathlock controls PathLock storage:
| Option | Type | Default | Description |
|---|---|---|---|
provider | str | "filesystem" | filesystem, memory, sqlite, or cache; see SQLite setup |
lock_expire_secs | float | 30.0 | Lock stale timeout; must be at least 1.0 |
Redis configuration:
| Option | Default | Description |
|---|---|---|
mode | "standalone" | Redis deployment mode |
endpoints | ["redis://127.0.0.1:6379"] | Redis connection URLs; use redis:// for plaintext or rediss:// for TLS |
username | "" | Redis ACL username |
password_env | "" | Environment variable that stores the Redis password |
pool_size | 32 | Command concurrency |
connect_timeout_ms | 10000 | Connection timeout in milliseconds |
command_timeout_ms | 0 | Command timeout in milliseconds; 0 disables command timeouts |
default_ttl_seconds | 300 | Runtime default TTL used by CacheFS query buckets; 0 means no TTL |
tls_insecure_skip_verify | false | Skip certificate verification for rediss://; intended only for controlled test environments |
All Redis reads are sent to the primary node so QueueFS does not observe stale queue state. CacheRuntime relies on Redis transport security when required and does not add a separate application-layer value encryption format.
With command_timeout_ms=0, CacheRuntime does not time out slow Redis commands. It also does not automatically fall back after a fixed interval.
DynamicProvider configuration:
OpenViking uses cache.params.library to load the dynamic library. All remaining fields are Provider-owned and passed to create as JSON. Use the schema documented by the Provider publisher.
{
"cache": {
"provider": "dynamic",
"params": {
"library": "/opt/openviking/providers/libopenviking_cache_provider.so",
"endpoint": "127.0.0.1:31501",
"request_timeout_ms": 5000
}
}
}Architecture
RAGFS separates Provider access from its consumers:
CachedFileSystem: implements filesystem semantics, including cache hit/miss handling, backend fallback, cache fill, invalidation, request checks, and metrics.CacheRuntime: exposes common primitive operations and binds either the built-in RedisProvider or an external DynamicProvider during startup.QueueFSandRedisPathLockProvider: reuse the shared CacheRuntime for queue and distributed-lock storage. RedisPathLockProvider requires the built-in RedisProvider.
Call flow:
OpenViking
-> RAGFS / MountableFS
|-> CachedFileSystem ------\
|-> QueueFS cache backend --+-> shared CacheRuntime -> RedisProvider
`-> RedisPathLockProvider --/ `-> DynamicProvider
`-> Backend FileSystemCachedFileSystem and QueueFS can use RedisProvider or DynamicProvider. RedisPathLockProvider depends on Redis Lua execution and therefore only uses RedisProvider. Filesystem semantics remain in CachedFileSystem; an external Provider only supplies primitive key-value operations through the stable C ABI.
Cache Objects
RAGFS caches read-only query results. It no longer stores legacy path-object cache entries.
Query Bucket
Each path and operation has one HASH bucket:
{<service_name>}:ov:cache:v1:<path_key>:<op>Each bucket reserves __epoch for a random generation token. Query fields use xxh3_128(canonical_request_json) and store a QueryCacheEnvelope containing:
requestpayload
RAGFS compares the stored request with the current request before returning the cached payload. This protects against hash collisions and request encoding changes.
Supported operations:
statread_dirtree_directoryglob_directorygrep
Query Index
All active buckets are registered in one ZSET:
{<service_name>}:ov:cacheidx:v1The ZSET member is the bucket key. The score is expire_at_ms. The Redis hash tag keeps buckets and the index in the same cluster slot so CacheFS can update them in one Lua script. This index lets writes delete affected buckets without scanning all Redis keys.
Consistency and Invalidation
In the single-writer scenario, RAGFS does not need a distributed write lock. It physically deletes query buckets affected by each write.
For a normal path change, RAGFS builds the affected bucket list in memory:
- exact path buckets:
stat,read_dir,tree_directory,glob_directory,grep - parent bucket:
read_dir(parent) - ancestor recursive buckets:
tree_directory,glob_directory,grep
It then runs one script per bucket to UNLINK the bucket and ZREM its index member atomically.
For recursive path operations such as remove_all, rename, and replace, RAGFS also scans the query index:
ZSCAN {<service_name>}:ov:cacheidx:v1 MATCH '{<service_name>}:ov:cache:v1:<path_key>/*:*' COUNT 1000Matched descendant buckets are deleted by the same bucket/index script. After a miss, an atomic script captures __epoch and registers the bucket before backend fallback. Another script fills the query field and refreshes the index only when that epoch is still current. A successful UNLINK removes the epoch, so an older query cannot restore stale data. Pending no-TTL epochs expire after 300 seconds; successful fills remain persistent.
Typical write order:
Apply backend change
-> Schedule asynchronous invalidation
-> Return result
Background task -> ZSCAN descendant buckets
Background task -> Build exact-path and ancestor buckets
Background task -> Run bucket/index delete script for each bucketIf a Provider fails, RAGFS treats the backend as authoritative for the current request. It records the cache error and does not cache that result.
Request Coalescing
When multiple requests read the same uncached query at the same time, CachedFileSystem uses an in-process inflight table to coalesce them:
The first miss becomes the leader and performs backend fallback and cache fill.
Later requests for the same key become followers and wait for the leader result.
The inflight entry is removed after the request completes.This only reduces duplicate backend access within one OpenViking process. It does not change the Provider consistency boundary.
Cache Scope
CacheFS only stores query results for stat, read_dir, tree_directory, glob_directory, and grep. Cache keys are derived from the path, operation name, and query parameters. Successful writes actively remove affected query buckets. Runtime-internal PathLock files such as .path.ovlock and .exact.ovlock.* are excluded from query cache payloads, and direct queries against those files bypass CacheFS.
Failure and Observability
The cache layer must not affect filesystem correctness:
getfailure: fall back to backend.putfailure: record the error and keep the backend result.deletefailure: record the error; TTL remains the fallback.- Provider unavailable: do not return old cache; use backend results as authoritative.
Recommended signals to watch:
- query hit / miss
- provider get / put / delete latency
- cache set / delete failures
- backend fallbacks
Shared Redis Deployments
CacheFS query buckets can share one Redis service with QueueFS, a cache-backed PathLock, and the expiry scheduler. Redis applies maxmemory and eviction policy to the whole service, so shared_redis_ttl_seconds is a retention bound rather than a capacity reservation or a survival guarantee for stateful keys.
- Set
shared_redis_ttl_secondsbelowcache.redis.default_ttl_secondswhen cache retention should yield to stateful workloads. - Keep
shared_redis_ttl_secondsat0to retain the provider default. - For a hard capacity boundary, use a dedicated Redis service. A logical database index does not isolate
maxmemoryor eviction policy. - When sharing a service, monitor
used_memory,evicted_keys, and cache hit/miss metrics together.
Recommended Rollout
- Disable caching to validate baseline backend behavior.
- Use the built-in
redisProvider to validate remote-cache benefits. - Use an independently released DynamicProvider
.sofor high-performance or closed-source cache systems. - Cache
stat,read_dir,tree_directory,glob_directory, andgrepquery results.
RAGFS cache handles invalidation according to filesystem semantics; the Provider decides where cache objects live. The backend remains the source of truth, and every cache hit must pass request validation before it is returned.
After enabling the cache, compare repeated reads and invalidation after a file update against the baseline. A higher hit rate is useful only if the returned contents remain current.