Skip to content

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

perf(storage): skip unnecessary directory counts in internal stat calls (#4703)

Jiahui Zhou2251aa136a0d
diff --git a/openviking/parse/parsers/media/utils.py b/openviking/parse/parsers/media/utils.py
index 7ce8e5306..3f85f9075 100644
--- a/openviking/parse/parsers/media/utils.py
+++ b/openviking/parse/parsers/media/utils.py
@@ -419,7 +419,7 @@ async def _generate_media_summary(
result = {"name": original_filename, "summary": ""}
viking_fs = get_viking_fs()
- stat = await viking_fs.stat(media_uri, ctx=ctx)
+ stat = await viking_fs.stat(media_uri, ctx=ctx, skip_count=True)
size_bytes = int((stat or {}).get("size", 0))
if not vlm.supports_media(
media_type=media_type,
diff --git a/openviking/parse/tree_builder.py b/openviking/parse/tree_builder.py
index b7e7f3abf..deae20b76 100644
--- a/openviking/parse/tree_builder.py
+++ b/openviking/parse/tree_builder.py
@@ -126,7 +126,7 @@ class TreeBuilder:
f"Parent URI does not exist: {effective_parent_uri}. "
f"Use --parent-auto-create/-p to automatically create it."
)
- stat_result = await viking_fs.stat(effective_parent_uri, ctx=ctx)
+ stat_result = await viking_fs.stat(effective_parent_uri, ctx=ctx, skip_count=True)
if not stat_result.get("isDir"):
raise ValueError(f"Parent URI is not a directory: {effective_parent_uri}")
base_uri = effective_parent_uri
diff --git a/openviking/privacy/service.py b/openviking/privacy/service.py
index dc66b5e48..b2bc08c7b 100644
--- a/openviking/privacy/service.py
+++ b/openviking/privacy/service.py
@@ -40,7 +40,11 @@ class UserPrivacyConfigService:
async def exists(self, ctx: RequestContext, category: str, target_key: str) -> bool:
try:
- await self._viking_fs.stat(self.get_config_root(ctx, category, target_key), ctx=ctx)
+ await self._viking_fs.stat(
+ self.get_config_root(ctx, category, target_key),
+ ctx=ctx,
+ skip_count=True,
+ )
return True
except (NotFoundError, FileNotFoundError):
return False
diff --git a/openviking/resource/watch_scheduler.py b/openviking/resource/watch_scheduler.py
index b07ade999..a47de00e4 100644
--- a/openviking/resource/watch_scheduler.py
+++ b/openviking/resource/watch_scheduler.py
@@ -583,7 +583,7 @@ class WatchScheduler:
if self._viking_fs is None:
return True
try:
- await self._viking_fs.stat(uri, ctx=ctx)
+ await self._viking_fs.stat(uri, ctx=ctx, skip_count=True)
return True
except NotFoundError:
return False
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index c732a8b3f..145425957 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -518,7 +518,7 @@ async def read(uris: str | list[str]) -> str | list[ContentBlock]:
return resolved_uri, None, None
async with semaphore:
- stat = await service.fs.stat(resolved_uri, ctx=ctx)
+ stat = await service.fs.stat(resolved_uri, ctx=ctx, skip_count=True)
if stat.get("isDir"):
return (
resolved_uri,
diff --git a/openviking/server/routers/content.py b/openviking/server/routers/content.py
index 2a098eb5d..ca123bfbb 100644
--- a/openviking/server/routers/content.py
+++ b/openviking/server/routers/content.py
@@ -215,7 +215,7 @@ async def download(
# Try to get filename from stat
filename = "download"
try:
- stat = await service.fs.stat(uri, ctx=_ctx)
+ stat = await service.fs.stat(uri, ctx=_ctx, skip_count=True)
if stat and "name" in stat:
filename = stat["name"]
except Exception:
diff --git a/openviking/server/routers/filesystem.py b/openviking/server/routers/filesystem.py
index 74be67423..3db41d2c4 100644
--- a/openviking/server/routers/filesystem.py
+++ b/openviking/server/routers/filesystem.py
@@ -204,7 +204,7 @@ async def attrs(
service = get_service()
uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)
try:
- stat_result = await service.fs.stat(uri, ctx=_ctx)
+ stat_result = await service.fs.stat(uri, ctx=_ctx, skip_count=True)
result = {
"uri": uri,
"context_type": context_type_for_uri(uri),
diff --git a/openviking/server/routers/skills.py b/openviking/server/routers/skills.py
index 1daff2283..27eefb9b6 100644
--- a/openviking/server/routers/skills.py
+++ b/openviking/server/routers/skills.py
@@ -159,7 +159,7 @@ async def _entry_looks_like_skill(service, ctx: RequestContext, entry: Dict[str,
# directory actually contains a SKILL.md file before listing it. Any
# error (including NotFound) means we cannot confirm it is a skill.
try:
- skill_md_stat = await service.fs.stat(_skill_md_uri(entry_uri), ctx=ctx)
+ skill_md_stat = await service.fs.stat(_skill_md_uri(entry_uri), ctx=ctx, skip_count=True)
except Exception:
return False
if not skill_md_stat or skill_md_stat.get("isDir", False):
@@ -266,7 +266,7 @@ async def _require_skill(
if target_uri:
root_uri = _skill_root_uri(ctx, skill_name, target_uri)
try:
- stat = await service.fs.stat(root_uri, ctx=ctx)
+ stat = await service.fs.stat(root_uri, ctx=ctx, skip_count=True)
if stat and stat.get("isDir", False):
return root_uri
except NotFoundError:
@@ -276,7 +276,7 @@ async def _require_skill(
user_root_uri = _skill_root_uri(ctx, skill_name)
try:
- stat = await service.fs.stat(user_root_uri, ctx=ctx)
+ stat = await service.fs.stat(user_root_uri, ctx=ctx, skip_count=True)
if stat and stat.get("isDir", False):
return user_root_uri
except NotFoundError:
@@ -286,7 +286,7 @@ async def _require_skill(
agent_root_uri = _skill_root_uri(ctx, skill_name, "viking://agent/skills")
try:
- stat = await service.fs.stat(agent_root_uri, ctx=ctx)
+ stat = await service.fs.stat(agent_root_uri, ctx=ctx, skip_count=True)
if stat and stat.get("isDir", False):
return agent_root_uri
except NotFoundError:
diff --git a/openviking/server/routers/webdav.py b/openviking/server/routers/webdav.py
index 88311e8b4..bd8da9d10 100644
--- a/openviking/server/routers/webdav.py
+++ b/openviking/server/routers/webdav.py
@@ -179,7 +179,7 @@ async def _write_text_resource(service, uri: str, content: str, ctx: RequestCont
async def _safe_stat(service, uri: str, ctx: RequestContext) -> Optional[dict[str, Any]]:
try:
- return await service.fs.stat(uri, ctx=ctx)
+ return await service.fs.stat(uri, ctx=ctx, skip_count=True)
except (FileNotFoundError, NotFoundError):
return None
diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.py
index 97a5f9c78..5e2b16f18 100644
--- a/openviking/service/fs_service.py
+++ b/openviking/service/fs_service.py
@@ -854,10 +854,10 @@ class FSService:
result = result[:node_limit]
return result
- async def stat(self, uri: str, ctx: RequestContext) -> Dict[str, Any]:
+ async def stat(self, uri: str, ctx: RequestContext, skip_count: bool = False) -> Dict[str, Any]:
"""Get resource status."""
viking_fs = self._ensure_initialized()
- return await viking_fs.stat(uri, ctx=ctx)
+ return await viking_fs.stat(uri, ctx=ctx, skip_count=skip_count)
async def system_sync_status(self, uri: str, ctx: RequestContext) -> Dict[str, Any]:
"""Return multi-write sync status for one Viking URI subtree."""
diff --git a/openviking/service/reindex_executor.py b/openviking/service/reindex_executor.py
index 857ac8f02..542889063 100644
--- a/openviking/service/reindex_executor.py
+++ b/openviking/service/reindex_executor.py
@@ -509,7 +509,7 @@ class ReindexExecutor:
acquire_lock = service.viking_fs._async_agfs.pathlock_acquire_tree
if mode != "prune_orphans" or await service.viking_fs.exists(uri, ctx=ctx):
- stat = await service.viking_fs.stat(uri, ctx=ctx)
+ stat = await service.viking_fs.stat(uri, ctx=ctx, skip_count=True)
if not stat.get("isDir", stat.get("is_dir")):
acquire_lock = service.viking_fs._async_agfs.pathlock_acquire_exact
lease = await acquire_lock(path)
@@ -1009,7 +1009,7 @@ class ReindexExecutor:
counters = run.counters
ctx = run.ctx
if mode == "semantic_and_vectors":
- stat = await get_viking_fs().stat(uri, ctx=ctx)
+ stat = await get_viking_fs().stat(uri, ctx=ctx, skip_count=True)
if stat.get("isDir", stat.get("is_dir")):
semantic_kwargs = {
"uri": uri,
@@ -1078,7 +1078,7 @@ class ReindexExecutor:
try:
if not await viking_fs.exists(uri, ctx=ctx):
raise NotFoundError(uri, "resource")
- stat = await viking_fs.stat(uri, ctx=ctx)
+ stat = await viking_fs.stat(uri, ctx=ctx, skip_count=True)
is_dir = stat.get("isDir", stat.get("is_dir")) if isinstance(stat, dict) else False
if is_dir and recursive:
entries = await self._tree_all(viking_fs, uri, show_all_hidden=True, ctx=ctx)
@@ -1582,7 +1582,7 @@ class ReindexExecutor:
) -> None:
viking_fs = get_viking_fs()
if await viking_fs.exists(uri, ctx=ctx):
- stat = await viking_fs.stat(uri, ctx=ctx)
+ stat = await viking_fs.stat(uri, ctx=ctx, skip_count=True)
if stat.get("isDir", stat.get("is_dir")):
entries = (
await self._tree_all(viking_fs, uri, show_all_hidden=False, ctx=ctx)
diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.py
index 0cf0fe32c..486d7becb 100644
--- a/openviking/service/resource_service.py
+++ b/openviking/service/resource_service.py
@@ -596,7 +596,7 @@ class ResourceService:
try:
if not await self._viking_fs.exists(root_uri, ctx=ctx):
return True
- stat = await self._viking_fs.stat(root_uri, ctx=ctx)
+ stat = await self._viking_fs.stat(root_uri, ctx=ctx, skip_count=True)
if not isinstance(stat, dict) or not stat.get("isDir"):
return False
entries = await self._viking_fs.ls(
diff --git a/openviking/session/session.py b/openviking/session/session.py
index 9707f1aa3..972f3e89a 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -806,7 +806,7 @@ class Session:
async def exists(self) -> bool:
"""Check whether this session already exists in storage."""
try:
- await self._viking_fs.stat(self._session_uri, ctx=self.ctx)
+ await self._viking_fs.stat(self._session_uri, ctx=self.ctx, skip_count=True)
return True
except Exception as exc:
if not _is_storage_not_found(exc):
diff --git a/openviking/storage/content_write.py b/openviking/storage/content_write.py
index 406760135..90b0e2cbf 100644
--- a/openviking/storage/content_write.py
+++ b/openviking/storage/content_write.py
@@ -168,9 +168,7 @@ class ContentWriteCoordinator:
)
context_type = context_type_for_uri(normalized_uri)
- root_uri = await self._resolve_root_uri(
- normalized_uri, ctx=ctx, anchor_to_parent=True
- )
+ root_uri = await self._resolve_root_uri(normalized_uri, ctx=ctx, anchor_to_parent=True)
written_bytes = len(content.encode("utf-8"))
telemetry_id = get_current_telemetry().telemetry_id
@@ -870,9 +868,7 @@ class ContentWriteCoordinator:
elif refresh_action is FreshnessAction.MARK_PENDING:
# Changed-file semantic/vector work may still be queued, while
# the directory aggregation itself is intentionally deferred.
- _, vector_status = self._refresh_statuses(
- wait=wait, queue_status=queue_status
- )
+ _, vector_status = self._refresh_statuses(wait=wait, queue_status=queue_status)
result_kwargs = {
"semantic_status": "deferred",
"vector_status": vector_status,
@@ -1033,7 +1029,7 @@ class ContentWriteCoordinator:
self, uri: str, *, ctx: RequestContext, allow_not_found: bool = False
) -> Dict[str, Any]:
try:
- return await self._viking_fs.stat(uri, ctx=ctx)
+ return await self._viking_fs.stat(uri, ctx=ctx, skip_count=True)
except Exception as exc:
if self._is_not_found(exc):
if allow_not_found:
diff --git a/openviking/storage/ovpack/operations.py b/openviking/storage/ovpack/operations.py
index 3d818e52c..47ff28ebf 100644
--- a/openviking/storage/ovpack/operations.py
+++ b/openviking/storage/ovpack/operations.py
@@ -118,7 +118,7 @@ async def _root_exists(viking_fs, root_uri: str, ctx: RequestContext) -> bool:
async def _ensure_parent_exists(viking_fs, parent: str, ctx: RequestContext) -> None:
try:
- await viking_fs.stat(parent, ctx=ctx)
+ await viking_fs.stat(parent, ctx=ctx, skip_count=True)
except Exception:
await viking_fs.mkdir(parent, ctx=ctx)
@@ -699,7 +699,7 @@ async def restore_ovpack(
continue
try:
- target_stat = await viking_fs.stat(target_uri, ctx=ctx)
+ target_stat = await viking_fs.stat(target_uri, ctx=ctx, skip_count=True)
except (NotFoundError, FileNotFoundError):
target_stat = None
diff --git a/openviking/storage/queuefs/semantic_dag.py b/openviking/storage/queuefs/semantic_dag.py
index ba7b97270..c30f47286 100644
--- a/openviking/storage/queuefs/semantic_dag.py
+++ b/openviking/storage/queuefs/semantic_dag.py
@@ -635,8 +635,8 @@ class SemanticDagExecutor:
if not target_path:
return True
try:
- current_stat = await self._viking_fs.stat(file_path, ctx=self._ctx)
- target_stat = await self._viking_fs.stat(target_path, ctx=self._ctx)
+ current_stat = await self._viking_fs.stat(file_path, ctx=self._ctx, skip_count=True)
+ target_stat = await self._viking_fs.stat(target_path, ctx=self._ctx, skip_count=True)
current_size = current_stat.get("size") if isinstance(current_stat, dict) else None
target_size = target_stat.get("size") if isinstance(target_stat, dict) else None
if current_size is not None and target_size is not None and current_size != target_size:
diff --git a/openviking/storage/queuefs/semantic_processor.py b/openviking/storage/queuefs/semantic_processor.py
index 16d984b98..e30f426c6 100644
--- a/openviking/storage/queuefs/semantic_processor.py
+++ b/openviking/storage/queuefs/semantic_processor.py
@@ -931,7 +931,7 @@ class SemanticProcessor(DequeueHandlerBase):
else f"{target_prefix}/{mapping_name}"
)
try:
- await viking_fs.stat(target_mapping, ctx=ctx)
+ await viking_fs.stat(target_mapping, ctx=ctx, skip_count=True)
continue # already carried over
except Exception:
pass
diff --git a/openviking/storage/viking_fs/_grep.py b/openviking/storage/viking_fs/_grep.py
index f0e048e65..207dba787 100644
--- a/openviking/storage/viking_fs/_grep.py
+++ b/openviking/storage/viking_fs/_grep.py
@@ -659,7 +659,7 @@ class _GrepMixin:
logger.debug(f"Skipping excluded uri during grep: {normalized_uri}")
return file_uris
try:
- root_stat = await self.stat(normalized_uri, ctx=ctx)
+ root_stat = await self.stat(normalized_uri, ctx=ctx, skip_count=True)
except Exception:
return file_uris
if not root_stat.get("isDir", False):
diff --git a/openviking/storage/viking_fs/_sync.py b/openviking/storage/viking_fs/_sync.py
index a4eb7a935..8ec7cc271 100644
--- a/openviking/storage/viking_fs/_sync.py
+++ b/openviking/storage/viking_fs/_sync.py
@@ -94,9 +94,7 @@ class _SyncMixin:
async def list_children(dir_uri: str) -> Tuple[Dict[str, str], Dict[str, str]]:
files: Dict[str, str] = {}
dirs: Dict[str, str] = {}
- entries = await self.ls(
- dir_uri, show_all_hidden=True, node_limit=LS_ALL_NODES, ctx=ctx
- )
+ entries = await self.ls(dir_uri, show_all_hidden=True, node_limit=LS_ALL_NODES, ctx=ctx)
for entry in entries:
name = entry.get("name", "")
if not name or name in [".", ".."]:
@@ -112,11 +110,15 @@ class _SyncMixin:
async def default_is_changed(root_file: str, target_file: str) -> bool:
try:
- current_stat = await self.stat(root_file, ctx=ctx)
- target_stat = await self.stat(target_file, ctx=ctx)
+ current_stat = await self.stat(root_file, ctx=ctx, skip_count=True)
+ target_stat = await self.stat(target_file, ctx=ctx, skip_count=True)
current_size = current_stat.get("size") if isinstance(current_stat, dict) else None
target_size = target_stat.get("size") if isinstance(target_stat, dict) else None
- if current_size is not None and target_size is not None and current_size != target_size:
+ if (
+ current_size is not None
+ and target_size is not None
+ and current_size != target_size
+ ):
return True
current_content = await self.read_file(root_file, ctx=ctx)
target_content = await self.read_file(target_file, ctx=ctx)
diff --git a/openviking/utils/embedding_utils.py b/openviking/utils/embedding_utils.py
index 227e04040..57f20638b 100644
--- a/openviking/utils/embedding_utils.py
+++ b/openviking/utils/embedding_utils.py
@@ -165,7 +165,7 @@ async def _resolve_context_timestamps(
) -> tuple[datetime, datetime]:
updated_at = datetime.now(timezone.utc)
try:
- stat_result = await get_viking_fs().stat(uri, ctx=ctx)
+ stat_result = await get_viking_fs().stat(uri, ctx=ctx, skip_count=True)
stat_mod_time = _coerce_datetime((stat_result or {}).get("modTime"))
if stat_mod_time is not None:
updated_at = stat_mod_time
diff --git a/openviking/utils/resource_processor.py b/openviking/utils/resource_processor.py
index 34657d2da..e87cecd7e 100644
--- a/openviking/utils/resource_processor.py
+++ b/openviking/utils/resource_processor.py
@@ -439,7 +439,7 @@ class ResourceProcessor:
target_preexisting = await viking_fs.exists(root_uri, ctx=ctx)
if target_preexisting:
try:
- stat = await viking_fs.stat(root_uri, ctx=ctx)
+ stat = await viking_fs.stat(root_uri, ctx=ctx, skip_count=True)
if isinstance(stat, dict) and stat.get("isDir"):
entries = await viking_fs.ls(
root_uri,
diff --git a/tests/misc/test_ovpack_import_policy.py b/tests/misc/test_ovpack_import_policy.py
index 2b6ebcbca..29ef18b4f 100644
--- a/tests/misc/test_ovpack_import_policy.py
+++ b/tests/misc/test_ovpack_import_policy.py
@@ -36,7 +36,8 @@ class FakeVikingFS:
self.existing_roots = existing_roots or set()
self.removed_roots: list[str] = []
- async def stat(self, uri: str, ctx=None):
+ async def stat(self, uri: str, ctx=None, skip_count=False):
+ assert skip_count is True
return {"uri": uri, "isDir": True}
async def mkdir(self, uri: str, exist_ok: bool = False, ctx=None):
diff --git a/tests/parse/test_media_understanding_summary.py b/tests/parse/test_media_understanding_summary.py
index 7d5fdbce6..248d6e5ae 100644
--- a/tests/parse/test_media_understanding_summary.py
+++ b/tests/parse/test_media_understanding_summary.py
@@ -258,6 +258,29 @@ async def test_unknown_size_media_stops_at_hard_staging_limit(
assert client.path_calls == 0
+async def test_media_summary_stat_skips_directory_vector_count(monkeypatch):
+ fs = _FS()
+ client = _CapturingPathClient()
+ model_config = SimpleNamespace(get_client_instance=lambda: client)
+ monkeypatch.setattr(media_utils, "get_viking_fs", lambda: fs)
+ monkeypatch.setattr(
+ media_utils,
+ "get_openviking_config",
+ lambda: _config(model_config),
+ )
+
+ await media_utils.generate_video_summary(
+ "viking://resources/video/clip.mp4",
+ "clip.mp4",
+ )
+
+ fs.stat.assert_awaited_once_with(
+ "viking://resources/video/clip.mp4",
+ ctx=None,
+ skip_count=True,
+ )
+
+
async def test_success_normalizes_markdown_and_filename_heading(
monkeypatch,
):
diff --git a/tests/resource/test_watch_scheduler.py b/tests/resource/test_watch_scheduler.py
index a742786d4..fdad269e4 100644
--- a/tests/resource/test_watch_scheduler.py
+++ b/tests/resource/test_watch_scheduler.py
@@ -136,7 +136,8 @@ class TestWatchSchedulerResourceExistence:
from openviking_cli.exceptions import NotFoundError
class FakeVikingFS:
- async def stat(self, uri, ctx=None):
+ async def stat(self, uri, ctx=None, skip_count=False):
+ assert skip_count is True
raise NotFoundError(uri, "resource")
class FakeResourceService(ResourceService):
@@ -177,7 +178,8 @@ class TestWatchSchedulerResourceExistence:
@pytest.mark.asyncio
async def test_target_uri_check_error_does_not_deactivate_task(self, tmp_path):
class FakeVikingFS:
- async def stat(self, uri, ctx=None):
+ async def stat(self, uri, ctx=None, skip_count=False):
+ assert skip_count is True
raise RuntimeError("temporary stat failure")
class FakeResourceService(ResourceService):
diff --git a/tests/server/test_content_batch_write.py b/tests/server/test_content_batch_write.py
index 649e5078e..085f39214 100644
--- a/tests/server/test_content_batch_write.py
+++ b/tests/server/test_content_batch_write.py
@@ -49,8 +49,9 @@ class _VFS:
del ctx
return "/virtual/" + uri.removeprefix("viking://")
- async def stat(self, uri, ctx=None):
+ async def stat(self, uri, ctx=None, skip_count=False):
del ctx
+ assert skip_count is True
if uri == self.root:
return {"uri": uri, "isDir": True}
if uri in self.files:
diff --git a/tests/server/test_content_write_service.py b/tests/server/test_content_write_service.py
index 4c4e7c551..e5921bf1f 100644
--- a/tests/server/test_content_write_service.py
+++ b/tests/server/test_content_write_service.py
@@ -342,7 +342,9 @@ async def test_memory_write_linkifies_resource_uri_marker_with_readable_anchor(s
refs = mf.extra_fields["resource_refs"]
assert refs[0]["resource_uri"] == resource_uri
assert refs[0]["source"] == "content.write"
- assert refs[0]["match_text"] == "2026-06-12,用户保存了粉丝创作的越前龙马动漫插画资源,资源URI为"
+ assert (
+ refs[0]["match_text"] == "2026-06-12,用户保存了粉丝创作的越前龙马动漫插画资源,资源URI为"
+ )
assert mf.links == []
@@ -462,8 +464,9 @@ class _FakeVikingFS:
self.tree_entries = []
self._async_agfs = _FakePathLock()
- async def stat(self, uri: str, ctx=None):
+ async def stat(self, uri: str, ctx=None, skip_count=False):
del ctx
+ assert skip_count is True
if uri == self._file_uri or uri in self.content:
return {"isDir": False}
if uri == self._root_uri:
@@ -873,8 +876,9 @@ class _FakeVikingFSForCreate:
self.existing_dirs = set({root_uri} if existing_dirs is None else existing_dirs)
self._async_agfs = _FakePathLock()
- async def stat(self, uri: str, ctx=None):
+ async def stat(self, uri: str, ctx=None, skip_count=False):
del ctx
+ assert skip_count is True
if uri == self._file_uri:
if self._file_exists:
return {"isDir": False}
@@ -1216,8 +1220,9 @@ class _AnyDirVikingFS:
def __init__(self, file_uri: str):
self._file_uri = file_uri
- async def stat(self, uri: str, ctx=None):
+ async def stat(self, uri: str, ctx=None, skip_count=False):
del ctx
+ assert skip_count is True
return {"isDir": uri != self._file_uri}
diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.py
index 5ee1e9d77..1dd8e7087 100644
--- a/tests/server/test_mcp_endpoint.py
+++ b/tests/server/test_mcp_endpoint.py
@@ -746,7 +746,11 @@ async def test_read_video_returns_unsupported_hint(monkeypatch):
assert "no standard VideoContent" in result
assert 'ov get "viking://resources/demo.mp4" "./demo.mp4"' in result
- stat.assert_awaited_once_with("viking://resources/demo.mp4", ctx=DEFAULT_CTX)
+ stat.assert_awaited_once_with(
+ "viking://resources/demo.mp4",
+ ctx=DEFAULT_CTX,
+ skip_count=True,
+ )
read_visible.assert_not_awaited()
@@ -769,7 +773,11 @@ async def test_read_video_nonexistent_uri_preserves_not_found(monkeypatch):
assert "not found" in result.lower()
assert "VideoContent" not in result
- stat.assert_awaited_once_with("viking://resources/missing.mp4", ctx=DEFAULT_CTX)
+ stat.assert_awaited_once_with(
+ "viking://resources/missing.mp4",
+ ctx=DEFAULT_CTX,
+ skip_count=True,
+ )
read_visible.assert_not_awaited()
@@ -792,7 +800,11 @@ async def test_read_video_directory_uri_preserves_directory_hint(monkeypatch):
assert "URI points to a directory" in result
assert "VideoContent" not in result
- stat.assert_awaited_once_with("viking://resources/archive.mp4", ctx=DEFAULT_CTX)
+ stat.assert_awaited_once_with(
+ "viking://resources/archive.mp4",
+ ctx=DEFAULT_CTX,
+ skip_count=True,
+ )
read_visible.assert_not_awaited()
diff --git a/tests/service/test_fs_service.py b/tests/service/test_fs_service.py
index f57341128..5cd13a9c6 100644
--- a/tests/service/test_fs_service.py
+++ b/tests/service/test_fs_service.py
@@ -53,6 +53,24 @@ class _FakeVikingFS:
}
+async def test_stat_forwards_skip_count_without_changing_default(request_context):
+ viking_fs = SimpleNamespace(stat=AsyncMock(return_value={"isDir": True}))
+ service = FSService(viking_fs=viking_fs)
+
+ await service.stat("viking://resources", request_context, skip_count=True)
+ await service.stat("viking://resources", request_context)
+
+ assert viking_fs.stat.await_args_list[0].kwargs == {
+ "ctx": request_context,
+ "skip_count": True,
+ }
+ assert viking_fs.stat.await_args_list[1].kwargs == {
+ "ctx": request_context,
+ "skip_count": False,
+ }
+
+
class _FakeMutationCoordinator:
def __init__(self, events=None):
self.calls = []
diff --git a/tests/service/test_reindex_file_lock.py b/tests/service/test_reindex_file_lock.py
index bd568f7bf..1e8f54dce 100644
--- a/tests/service/test_reindex_file_lock.py
+++ b/tests/service/test_reindex_file_lock.py
@@ -23,8 +23,9 @@ class _FakeVikingFS:
async def exists(self, uri: str, ctx=None):
return uri == self._uri
- async def stat(self, uri: str, ctx=None):
+ async def stat(self, uri: str, ctx=None, skip_count=False):
assert uri == self._uri
+ assert skip_count is True
return {"isDir": False}
async def read_file(self, uri: str, ctx=None):
diff --git a/tests/service/test_resource_service_reserved_target_cleanup.py b/tests/service/test_resource_service_reserved_target_cleanup.py
index 239906c1d..754b2a83c 100644
--- a/tests/service/test_resource_service_reserved_target_cleanup.py
+++ b/tests/service/test_resource_service_reserved_target_cleanup.py
@@ -50,10 +50,16 @@ async def test_cleanup_reserved_target_removes_only_empty_directory():
ctx=ctx,
lease_ref=lock,
)
+ viking_fs.stat.assert_awaited_once_with(
+ "viking://resources/empty",
+ ctx=ctx,
+ skip_count=True,
+ )
@pytest.mark.asyncio
async def test_cleanup_reserved_target_preserves_nonempty_directory():
+ ctx = _ctx()
viking_fs = SimpleNamespace(
exists=AsyncMock(return_value=True),
stat=AsyncMock(return_value={"isDir": True}),
@@ -64,12 +70,17 @@ async def test_cleanup_reserved_target_preserves_nonempty_directory():
removed = await service._cleanup_reserved_target_if_empty(
root_uri="viking://resources/nonempty",
- ctx=_ctx(),
+ ctx=ctx,
resource_lock={"lease_ref": "lock-1"},
)
assert removed is False
viking_fs.rm.assert_not_awaited()
+ viking_fs.stat.assert_awaited_once_with(
+ "viking://resources/nonempty",
+ ctx=ctx,
+ skip_count=True,
+ )
@pytest.mark.asyncio
diff --git a/tests/session/test_session_lifecycle.py b/tests/session/test_session_lifecycle.py
index f03274a7b..cf46d4741 100644
--- a/tests/session/test_session_lifecycle.py
+++ b/tests/session/test_session_lifecycle.py
@@ -5,6 +5,8 @@
import re
from functools import partial
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
from openviking.server.identity import RequestContext
from openviking.service.core import OpenVikingService
@@ -154,6 +156,19 @@ class TestSessionServiceGet:
class TestSessionExists:
"""Test persisted session existence."""
+ async def test_session_exists_skips_directory_vector_count(self):
+ session = Session.__new__(Session)
+ session._viking_fs = SimpleNamespace(stat=AsyncMock(return_value={"isDir": True}))
+ session._session_uri = "viking://user/alice/sessions/session-1"
+ session.ctx = SimpleNamespace()
+
+ assert await session.exists() is True
+ session._viking_fs.stat.assert_awaited_once_with(
+ session._session_uri,
+ ctx=session.ctx,
+ skip_count=True,
+ )
+
async def test_session_exists_true_after_create(
self,
service: OpenVikingService,
diff --git a/tests/storage/test_content_write_processing_mode.py b/tests/storage/test_content_write_processing_mode.py
index 66a541ea4..e36f03c47 100644
--- a/tests/storage/test_content_write_processing_mode.py
+++ b/tests/storage/test_content_write_processing_mode.py
@@ -47,6 +47,20 @@ class _FakeVikingFS:
del uri, ctx, action
+async def test_content_write_stat_skips_directory_vector_count(ctx):
+ fake_fs = _FakeVikingFS()
+ fake_fs.stat = AsyncMock(return_value={"isDir": True})
+ coordinator = ContentWriteCoordinator(viking_fs=fake_fs)
+
+ assert await coordinator._safe_stat("viking://resources/demo", ctx=ctx) == {"isDir": True}
+ fake_fs.stat.assert_awaited_once_with(
+ "viking://resources/demo",
+ ctx=ctx,
+ skip_count=True,
+ )
+
+
def _sidecar(level=ContextLevel.ABSTRACT, body="Original body."):
return render_abstract_overview(
level,
@@ -151,7 +165,9 @@ async def test_write_builds_ingest_options_before_scheduling_resource_refresh(ct
coordinator = ContentWriteCoordinator(viking_fs=_FakeVikingFS())
coordinator._safe_stat = AsyncMock(return_value={"isDir": False})
coordinator._resolve_root_uri = AsyncMock(return_value="viking://resources")
- coordinator._write_direct_with_refresh = AsyncMock(return_value={"uri": "viking://resources/demo.md"})
+ coordinator._write_direct_with_refresh = AsyncMock(
+ return_value={"uri": "viking://resources/demo.md"}
+ )
await coordinator.write(
uri="viking://resources/demo.md",
@@ -229,9 +245,7 @@ async def test_vectors_only_write_wait_reports_skipped_when_nothing_enqueued(mon
async def test_automatic_wide_directory_delay_reports_deferred(monkeypatch, ctx):
fake_fs = _FakeVikingFS()
coordinator = ContentWriteCoordinator(viking_fs=fake_fs)
- coordinator._enqueue_semantic_refresh = AsyncMock(
- return_value=FreshnessAction.MARK_PENDING
- )
+ coordinator._enqueue_semantic_refresh = AsyncMock(return_value=FreshnessAction.MARK_PENDING)
result = await coordinator._write_direct_with_refresh(
uri="viking://resources/wide/demo.md",
diff --git a/tests/storage/test_viking_fs_grep.py b/tests/storage/test_viking_fs_grep.py
index b56e8c831..b537660f1 100644
--- a/tests/storage/test_viking_fs_grep.py
+++ b/tests/storage/test_viking_fs_grep.py
@@ -64,6 +64,21 @@ async def _fake_stat(uri, ctx=None, skip_count=False):
return {"name": uri.rsplit("/", 1)[-1], "isDir": True}
+async def test_collect_grep_files_skips_directory_vector_count(monkeypatch):
+ viking_fs = VikingFS(agfs=_DummyAgfs())
+ stat = AsyncMock(return_value={"isDir": True})
+ monkeypatch.setattr(viking_fs, "stat", stat)
+ monkeypatch.setattr(viking_fs, "ls", AsyncMock(return_value=[]))
+
+ assert await viking_fs._collect_grep_files(
+ "viking://resources",
+ excluded_prefix=None,
+ level_limit=1,
+ ) == []
+ stat.assert_awaited_once_with("viking://resources", ctx=None, skip_count=True)
+
+
def test_grep_config_default_switch_to_remote_threshold_is_10000():
assert GrepConfig().switch_to_remote_threshold == 10000