Skip to content

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

Understanding directory (#4439)

ShaoZegangByte4845ae39e3a7
diff --git a/docs/design/resource-ingestion-routing.md b/docs/design/resource-ingestion-routing.md
index d0ce5b3f6..93237a989 100644
--- a/docs/design/resource-ingestion-routing.md
+++ b/docs/design/resource-ingestion-routing.md
@@ -207,7 +207,27 @@ HTTPAccessor 按以下顺序收集和修正类型:
ParserRegistry 只注册项目内置 Parser,不再提供自定义 Parser 类、回调注册或可选模块注册入口。新增数据源优先实现 Accessor;新增文件格式则直接增加内置 Parser 和对应测试。
-目录、网站和压缩包的“子文件遍历”属于当前内置 Parser 的内部实现,不回到顶层 `ResourceService`,也不会给每个子文件重新选择 Understanding。顶层压缩文件本身是否进入 Understanding,仍由其冻结扩展名和 `parser_api.extensions` 决定。
+目录、网站和由内置 ZipParser 展开的压缩包,其“子文件遍历”仍属于当前内置
+Parser 的内部实现,不回到顶层 `ResourceService`。`DirectoryParser` 会递归扫描
+每个叶子文件,并通过 `ParserRouter` 重新检查 `parser_api.extensions`:命中的文件
+交给 Understanding,未命中的文件继续使用内置 Parser 或直接写入。该过程在当前
+目录任务内执行,不会把每个子文件拆成独立的 `ExternalParse` 队列任务。顶层压缩
+文件本身是否直接进入 Understanding,仍由其冻结扩展名和
+`parser_api.extensions` 决定。
+
+启用 Understanding 目录路由后,每次 `DirectoryParser` 扫描在发起该层远程请求前执行
+预检,默认限制为 1000 个入选文件和 10 层目录深度;关闭 Understanding 时,
+OpenViking 原生目录解析不应用这两个限制。内置 `ZipParser` 递归展开压缩包时会创建新的
+目录扫描,嵌套 ZIP 不与外层共享文件数量和深度预算。
+客户端导入本地目录时,会先将整个目录压缩为 ZIP,再由
+`/resources/temp_upload` 对整个 ZIP 执行上传大小限制。ZIP 解压后的叶子文件不再由
+`DirectoryParser` 设置统一大小限制,而是交给对应内置 Parser 或 Understanding,遵循
+各自的格式和上传限制。这些文件使用固定 worker 池,默认并发为 4;远程解析可以并发,
+但向目录临时树的合并始终按扫描顺序串行执行。目录限制可通过
+`parsers.directory` 配置调整。目录内部分文件失败时仍提交成功文件并通过
+`meta.failed_files` 返回失败详情;嵌套 ZIP 的叶子失败使用 `bundle.zip/path/to/file`
+形式的路径并保留远端任务 ID。如果没有任何文件成功,则在 TreeBuilder 持久化前
+终止任务,并清理本次请求新预占的空目标目录。
## Understanding 链路
diff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.md
index 1029ba132..c7a67920c 100644
--- a/docs/en/api/02-resources.md
+++ b/docs/en/api/02-resources.md
@@ -206,9 +206,10 @@ This endpoint is the core entry point for resource management, supporting adding
- If the request omits the app pair, user-token watches use `FEISHU_APP_ID` and `FEISHU_APP_SECRET`, or `feishu.app_id` and `feishu.app_secret` in `ov.conf`. Feishu refresh tokens are bound to their issuing app, so whichever app credentials are used must match the supplied user token.
- Watch task token state and request-supplied app credentials are stored in the internal `viking://resources/.watch_tasks.json` control file and hidden from watch API/MCP/CLI responses. If VikingFS file encryption is enabled, this control file is encrypted at rest; otherwise the server-side control file contains this private state in plaintext.
- For local directory inputs, scanning respects `.gitignore` files (root and nested) with standard Git semantics; `ignore_dirs`, `include`, and `exclude` further refine what is ingested.
-- `args.parse_mode=no_split` still invokes the normal format Parser. PDF, Word, PowerPoint, HTML, and other supported documents are converted to Markdown, but heading-, paragraph-, and size-based splitting is skipped. A directory import applies this independently to each supported document and continues to honor `.gitignore`, filters, and `preserve_structure`.
+- Directory ingestion is best-effort only when at least one selected file succeeds: failed files are reported in `meta.failed_files` while successful files are committed. Leaf failures from nested ZIP files are reported with archive-qualified paths such as `bundle.zip/path/to/file` and retain their remote task IDs. If no file succeeds, or the filters select no processable files, the task fails and no empty resource directory is retained.
+- `args.parse_mode=no_split` still invokes the normal format Parser. PDF, Word, PowerPoint, HTML, and other supported documents are converted to Markdown, but heading-, paragraph-, and size-based splitting is skipped. A directory import applies this independently to each supported document and continues to honor `.gitignore`, filters, and `preserve_structure`. Directory files configured for Understanding fall back to their native Parser in this mode; a file type without native parsing support is recorded in `meta.failed_files` without preventing other selected files from succeeding.
- For a single-file input in `no_split` mode, when parsing produces exactly one visible file and `to` is omitted, that file is stored directly under the resolved parent (for example, `guide.md` becomes `viking://resources/guide.md`). No wrapper directory or directory-level `.abstract.md` / `.overview.md` is created. If parsing also produces images or other visible files, the wrapper directory is retained. An explicit `to` is always preserved as the exact final URI.
-- `no_split` changes only the stored Markdown layout. Semantic processing, file vectorization, and any internal embedding chunking remain unchanged. Relative Markdown links are resolved against the same no-split output layout, so links do not point to split-only paths. A configured Understanding parser that cannot guarantee a single Markdown body returns an explicit unsupported-mode error.
+- `no_split` changes only the stored Markdown layout. Semantic processing, file vectorization, and any internal embedding chunking remain unchanged. Relative Markdown links are resolved against the same no-split output layout, so links do not point to split-only paths. Understanding is not called for directory files in this mode.
- To create or update plain text directly, use [content/write](03-filesystem.md#write) instead of `add_resource`. Semantic processing and embeddings are refreshed automatically after resource ingestion and content writes.
#### 3. Usage Examples
diff --git a/docs/en/configuration/01-server.md b/docs/en/configuration/01-server.md
index 88f4fdbe0..24c9fd973 100644
--- a/docs/en/configuration/01-server.md
+++ b/docs/en/configuration/01-server.md
@@ -352,7 +352,12 @@ Parsers live under `parsers`:
},
"html": {},
"text": {},
- "directory": {},
+ "directory": {
+ "preserve_structure": true,
+ "max_files": 1000,
+ "max_depth": 10,
+ "max_concurrent": 4
+ },
"feishu": {
"domain": "https://open.feishu.cn",
"max_rows_per_sheet": 1000,
@@ -364,6 +369,24 @@ Parsers live under `parsers`:
}
```
+`parsers.directory.max_concurrent` is shared by all directory imports in the
+server event loop. With the default value `4`, one directory can run four
+Understanding jobs concurrently, while multiple concurrent directories still
+run at most four in total.
+
+`max_files` and `max_depth` apply when Understanding directory routing is enabled.
+Each `DirectoryParser` scan applies these limits independently before submitting its
+own Understanding requests. A nested ZIP starts a new directory scan and does not
+share the outer scan's file-count or depth budget.
+When Understanding is disabled, native OpenViking directory parsing does not apply
+these two limits.
+
+When a local directory is added through the client, the complete directory ZIP is
+subject to the `/resources/temp_upload` size limit. After extraction,
+`DirectoryParser` does not impose a common per-file byte limit. Each selected file
+follows the limits and upload behavior of its assigned built-in parser or
+Understanding API backend.
+
| Setting | Purpose |
|---|---|
| `pdf` | PDF text, image, and layout parsing |
diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.md
index 83b1204f9..2a3561e73 100644
--- a/docs/zh/api/02-resources.md
+++ b/docs/zh/api/02-resources.md
@@ -201,9 +201,10 @@ URL/文件 Parser TreeBuilder AGFS Summarizer/Vector
- 请求未传应用凭证时,用户 token watch 回退使用 `FEISHU_APP_ID` 和 `FEISHU_APP_SECRET`,或 `ov.conf` 中的 `feishu.app_id` 和 `feishu.app_secret`。飞书 refresh token 绑定签发它的应用,因此实际使用的应用凭证必须与传入的用户 token 匹配。
- Watch task 的 token 状态和请求传入的应用凭证保存在内部控制文件 `viking://resources/.watch_tasks.json` 中,不会出现在 watch API/MCP/CLI 返回里。若启用了 VikingFS 文件加密,该控制文件会静态加密;否则服务端控制文件中会包含这些明文私有状态。
- 本地目录输入会遵循 `.gitignore`(根目录和子目录,标准 Git 语义);`ignore_dirs`、`include`、`exclude` 会在此基础上进一步过滤。
-- `args.parse_mode=no_split` 仍调用正常的格式 Parser。PDF、Word、PowerPoint、HTML 等受支持文档会转换为 Markdown,但跳过按标题、段落和长度拆分。目录导入会对每个受支持文档分别应用该规则,并继续遵循 `.gitignore`、筛选参数和 `preserve_structure`。
+- 目录导入仅在至少一个入选文件成功时采用 best-effort:失败文件写入 `meta.failed_files`,成功文件正常提交。嵌套 ZIP 的叶子失败使用 `bundle.zip/path/to/file` 形式的归档限定路径,并保留远端任务 ID。如果没有任何文件成功,或筛选后没有可处理文件,任务会失败且不会保留空资源目录。
+- `args.parse_mode=no_split` 仍调用正常的格式 Parser。PDF、Word、PowerPoint、HTML 等受支持文档会转换为 Markdown,但跳过按标题、段落和长度拆分。目录导入会对每个受支持文档分别应用该规则,并继续遵循 `.gitignore`、筛选参数和 `preserve_structure`。该模式下,配置为走 Understanding 的目录文件会回退到对应的原生 Parser;没有原生解析能力的文件会写入 `meta.failed_files`,但不会阻止其他入选文件成功导入。
- 对单文件输入使用 `no_split` 时,如果解析结果恰好只有一个可见文件且未指定 `to`,该文件会直接放到解析出的父目录下(例如 `guide.md` 写入 `viking://resources/guide.md`),不会创建同名上层目录,也不会生成目录级 `.abstract.md` / `.overview.md`。如果解析结果还包含图片等其他可见文件,则保留上层目录。显式指定的 `to` 始终作为最终 URI 原样保留。
-- `no_split` 只改变 Markdown 正文的存储布局,不改变语义处理、文件向量化和内部 embedding 分块。Markdown 相对链接会按同一个 no-split 输出布局解析,不会再指向仅拆分模式存在的路径。如果配置的 Understanding 解析器无法保证单一 Markdown 正文,接口会明确返回不支持该模式的错误。
+- `no_split` 只改变 Markdown 正文的存储布局,不改变语义处理、文件向量化和内部 embedding 分块。Markdown 相对链接会按同一个 no-split 输出布局解析,不会再指向仅拆分模式存在的路径。该模式下不会为目录文件调用 Understanding。
- 如果要直接创建或更新纯文本内容,请使用 [content/write](03-filesystem.md#write),不要使用 `add_resource`。资源导入和内容写入后都会自动刷新语义与 embedding。
#### 3. 使用示例
diff --git a/docs/zh/configuration/01-server.md b/docs/zh/configuration/01-server.md
index f8325eb2f..ee79666cf 100644
--- a/docs/zh/configuration/01-server.md
+++ b/docs/zh/configuration/01-server.md
@@ -352,7 +352,12 @@ Provider 和密钥管理配置见[加密指南](../guides/08-encryption.md)。
},
"html": {},
"text": {},
- "directory": {},
+ "directory": {
+ "preserve_structure": true,
+ "max_files": 1000,
+ "max_depth": 10,
+ "max_concurrent": 4
+ },
"feishu": {
"domain": "https://open.feishu.cn",
"max_rows_per_sheet": 1000,
@@ -364,6 +369,19 @@ Provider 和密钥管理配置见[加密指南](../guides/08-encryption.md)。
}
```
+`parsers.directory.max_concurrent` 由服务事件循环中的所有目录导入共享。默认值为
+`4` 时,单个目录可以并发执行 4 个 Understanding 任务;多个目录同时导入时,合计仍最多
+执行 4 个。
+
+启用 Understanding 目录路由时,`max_files` 和 `max_depth` 才约束目录导入。每次
+`DirectoryParser` 扫描会在提交该层 Understanding 请求前独立应用限制;嵌套 ZIP 会启动
+新的目录扫描,不与外层共享文件数量和深度预算。关闭 Understanding 时,OpenViking
+原生目录解析不应用这两个限制。
+
+客户端导入本地目录时,完整目录 ZIP 受 `/resources/temp_upload` 上传大小限制。ZIP
+解压后,`DirectoryParser` 不再设置统一的单文件字节限制;每个入选文件遵循对应内置
+Parser 或 Understanding API 后端自身的限制和上传行为。
+
| 配置项 | 作用 |
|---|---|
| `pdf` | PDF 文本、图片和版面解析 |
diff --git a/openviking/parse/directory_scan.py b/openviking/parse/directory_scan.py
index 797a04219..8e4d02755 100644
--- a/openviking/parse/directory_scan.py
+++ b/openviking/parse/directory_scan.py
@@ -12,13 +12,13 @@ import fnmatch
import os
from dataclasses import dataclass, field
from pathlib import Path
-from typing import List, Optional, Set, Union
+from typing import Callable, List, Optional, Set, Union
from openviking.parse.gitignore import GitignoreMatcher
from openviking.parse.parsers.constants import IGNORE_DIRS
from openviking.parse.parsers.upload_utils import is_text_file
from openviking.parse.registry import ParserRegistry, get_registry
-from openviking_cli.exceptions import UnsupportedDirectoryFilesError
+from openviking_cli.exceptions import InvalidArgumentError, UnsupportedDirectoryFilesError
from openviking_cli.utils.logger import get_logger
logger = get_logger(__name__)
@@ -159,15 +159,19 @@ def _matches_exclude(rel_path_norm: str, path_name: str, patterns: List[str]) ->
def _classify_file(
file_path: Path,
registry: ParserRegistry,
+ additional_can_process: Optional[Callable[[Path], bool]] = None,
) -> str:
"""
Classify a single file as CLASS_PROCESSABLE or CLASS_UNSUPPORTED.
- Processable: ParserRegistry has a parser, or is_text_file (code/config/docs).
+ Processable: ParserRegistry has a parser, an additional parser backend can
+ handle the file, or is_text_file (code/config/docs).
"""
# Normal classification logic
if registry.get_parser_for_file(file_path) is not None:
return CLASS_PROCESSABLE
+ if additional_can_process and additional_can_process(file_path):
+ return CLASS_PROCESSABLE
if is_text_file(file_path):
return CLASS_PROCESSABLE
return CLASS_UNSUPPORTED
@@ -180,6 +184,9 @@ def scan_directory(
ignore_dirs: Optional[Set[str]] = None,
include: Optional[str] = None,
exclude: Optional[str] = None,
+ additional_can_process: Optional[Callable[[Path], bool]] = None,
+ max_files: Optional[int] = None,
+ max_depth: Optional[int] = None,
) -> DirectoryScanResult:
"""
Traverse directory tree and classify every file (phase-one validation).
@@ -190,7 +197,8 @@ def scan_directory(
(e.g. include="*.pdf,*.md"). If exclude is set, files matching any exclude pattern are
skipped (e.g. exclude="drafts/" for path prefix, or "*.tmp" for name glob).
- Classifies remaining files:
- - processable: ParserRegistry has a parser, or is_text_file (code/docs/config)
+ - processable: ParserRegistry has a parser, an additional parser backend
+ accepts it, or is_text_file (code/docs/config)
- unsupported: everything else
Args:
@@ -203,11 +211,16 @@ def scan_directory(
(e.g. "*.pdf,*.md"). If not set, all files (subject to exclude) are considered.
exclude: Comma-separated patterns: trailing '/' = path prefix (e.g. "drafts/"),
else glob on file name (e.g. "*.tmp").
+ additional_can_process: Optional capability check for parser backends
+ outside ParserRegistry.
+ max_files: Optional maximum number of selected files admitted by the scan.
+ max_depth: Optional maximum nested directory depth below the root.
Returns:
DirectoryScanResult with processable, unsupported, warnings.
Raises:
+ InvalidArgumentError: When a configured directory safety limit is exceeded.
UnsupportedDirectoryFilesError: When strict=True and there is at least one unsupported file.
FileNotFoundError: When root does not exist.
NotADirectoryError: When root is not a directory.
@@ -218,6 +231,15 @@ def scan_directory(
if not root.is_dir():
raise NotADirectoryError(f"Not a directory: {root}")
+ limits = {
+ "max_files": max_files,
+ "max_depth": max_depth,
+ }
+ for name, value in limits.items():
+ if value is None:
+ continue
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
+ raise InvalidArgumentError(f"directory.{name} must be a positive integer")
effective_registry = registry if registry is not None else get_registry()
include_patterns = _parse_patterns(include)
exclude_patterns = _parse_patterns(exclude)
@@ -235,8 +257,21 @@ def scan_directory(
ignore_dirs_set = ignore_dirs
result = DirectoryScanResult(root=root)
+ selected_file_count = 0
for dir_path_str, dir_names, file_names in os.walk(root, topdown=True):
dir_path = Path(dir_path_str)
+ try:
+ relative_dir_path = dir_path.relative_to(root)
+ directory_depth = len(relative_dir_path.parts)
+ except ValueError:
+ relative_dir_path = Path("<outside-root>")
+ directory_depth = max_depth + 1 if max_depth is not None else 0
+ if max_depth is not None and directory_depth > max_depth:
+ display_path = _normalize_rel_path(str(relative_dir_path))
+ raise InvalidArgumentError(
+ f"Directory depth exceeds limit: depth={directory_depth}, "
+ f"max_depth={max_depth}, path={display_path}"
+ )
dir_spec = gitignore_matcher.spec_for_dir(dir_path)
# Prune subdirectories in-place so os.walk won't descend into them
@@ -283,7 +318,21 @@ def scan_directory(
result.skipped.append(f"{rel_path} (excluded by exclude filter)")
continue
- classification = _classify_file(file_path, effective_registry)
+ accepted_by_additional_parser = bool(
+ additional_can_process and additional_can_process(file_path)
+ )
+ if max_files is not None:
+ selected_file_count += 1
+ if max_files is not None and selected_file_count > max_files:
+ raise InvalidArgumentError(
+ f"Directory file count exceeds limit: count={selected_file_count}, "
+ f"max_files={max_files}, path={rel_path_norm}"
+ )
+ classification = (
+ CLASS_PROCESSABLE
+ if accepted_by_additional_parser
+ else _classify_file(file_path, effective_registry)
+ )
classified = ClassifiedFile(
path=file_path, rel_path=rel_path_norm, classification=classification
)
diff --git a/openviking/parse/parsers/directory.py b/openviking/parse/parsers/directory.py
index 2c526d5df..2c7f5d4e2 100644
--- a/openviking/parse/parsers/directory.py
+++ b/openviking/parse/parsers/directory.py
@@ -9,16 +9,19 @@ CodeRepositoryParser:
1. Scan → classify files with ``scan_directory()``
2. For each file:
- - Files WITH a dedicated parser → ``parser.parse()`` handles conversion
- and VikingFS temp creation; results are merged into the main temp.
+ - Files routed to UnderstandingAPI or a dedicated internal parser →
+ ``parser.parse()`` handles conversion and VikingFS temp creation; results
+ are merged into the main temp.
- Files WITHOUT a parser (code, config, …) → written directly to VikingFS.
3. Return ``ParseResult`` so that ``TreeBuilder.finalize_from_temp``
can move the content to AGFS and enqueue semantic processing.
"""
+import asyncio
import time
from pathlib import Path, PurePosixPath
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
+from weakref import WeakKeyDictionary
from openviking.parse.base import (
NodeType,
@@ -29,11 +32,14 @@ from openviking.parse.base import (
from openviking.parse.image_rewrite import IMAGE_MAPPINGS_FILENAME
from openviking.parse.parsers.base_parser import BaseParser
from openviking.parse.parsers.media.constants import MEDIA_EXTENSIONS
+from openviking.parse.parsers.upload_utils import is_text_file
from openviking.storage.viking_fs import LS_ALL_NODES
+from openviking_cli.exceptions import InvalidArgumentError
from openviking_cli.utils.logger import get_logger
if TYPE_CHECKING:
from openviking.parse.directory_scan import ClassifiedFile
+ from openviking.parse.parser_router import ParserRouter
from openviking.parse.registry import ParserRegistry
logger = get_logger(__name__)
@@ -42,14 +48,38 @@ logger = get_logger(__name__)
# Everything else hidden stays filtered, like a default ls.
_MERGE_SIDECAR_ALLOWLIST = frozenset({IMAGE_MAPPINGS_FILENAME})
+# DirectoryParser instances share one limiter in the server event loop so
+# concurrent directory imports cannot multiply UnderstandingAPI concurrency.
+_UNDERSTANDING_LIMITERS: WeakKeyDictionary[
+ asyncio.AbstractEventLoop, tuple[int, asyncio.Semaphore]
+] = WeakKeyDictionary()
+
+
+def _get_understanding_limiter(max_concurrent: int) -> asyncio.Semaphore:
+ """Return the shared directory Understanding limiter for this event loop."""
+ loop = asyncio.get_running_loop()
+ configured = _UNDERSTANDING_LIMITERS.get(loop)
+ if configured is None:
+ limiter = asyncio.Semaphore(max_concurrent)
+ _UNDERSTANDING_LIMITERS[loop] = (max_concurrent, limiter)
+ return limiter
+
+ configured_limit, limiter = configured
+ if configured_limit != max_concurrent:
+ raise InvalidArgumentError(
+ "parsers.directory.max_concurrent changed while the service is running; "
+ "restart the service to apply the new global directory limit"
+ )
+ return limiter
+
class DirectoryParser(BaseParser):
"""
Parser for local directories.
- Scans the directory, delegates each file to its registered parser via
- ``parser.parse()``, and merges all results into a single VikingFS temp.
- Files without a dedicated parser are written directly.
+ Scans the directory, routes each file through ParserRouter when configured
+ for UnderstandingAPI, and otherwise delegates to its registered parser.
+ Files without any parser are written directly.
The resulting ``ParseResult.temp_dir_path`` is consumed by
``TreeBuilder.finalize_from_temp`` exactly like any other parser.
@@ -116,9 +146,23 @@ class DirectoryParser(BaseParser):
try:
# ── Phase 1: scan directory ───────────────────────────────
from openviking.parse.directory_scan import scan_directory
+ from openviking.parse.parser_router import ParserRouter
from openviking.parse.registry import get_registry
+ from openviking_cli.utils.config.open_viking_config import get_openviking_config
+ from openviking_cli.utils.config.parser_config import DirectoryConfig
registry = get_registry()
+ parser_router = ParserRouter(registry)
+ ov_config = get_openviking_config()
+ directory_config = getattr(ov_config, "directory", None) or DirectoryConfig()
+
+ split_content = kwargs.get("split_content", True)
+ parser_api_config = getattr(ov_config, "parser_api", None)
+ understanding_limits_enabled = bool(
+ split_content
+ and parser_router.understanding_api_enabled()
+ and getattr(parser_api_config, "extensions", None)
+ )
scan_result = scan_directory(
root=str(source_path),
@@ -127,19 +171,14 @@ class DirectoryParser(BaseParser):
ignore_dirs=kwargs.get("ignore_dirs"),
include=kwargs.get("include"),
exclude=kwargs.get("exclude"),
+ additional_can_process=parser_router.should_use_understanding_api,
+ max_files=directory_config.max_files if understanding_limits_enabled else None,
+ max_depth=directory_config.max_depth if understanding_limits_enabled else None,
)
directly_upload_media = kwargs.get("directly_upload_media", True)
preserve_structure = kwargs.get("preserve_structure")
if preserve_structure is None:
- # Fall back to config default
- try:
- from openviking_cli.utils.config.open_viking_config import (
- get_openviking_config,
- )
-
- preserve_structure = get_openviking_config().directory.preserve_structure
- except Exception:
- preserve_structure = True
+ preserve_structure = directory_config.preserve_structure
processable_files = scan_result.all_processable_files()
warnings.extend(scan_result.warnings)
source_skipped_items = self._source_skipped_items(
@@ -151,6 +190,53 @@ class DirectoryParser(BaseParser):
for item in source_skipped_items
)
+ file_jobs: List[Dict[str, Any]] = []
+ understanding_jobs: List[Dict[str, Any]] = []
+ for index, cf in enumerate(processable_files):
+ configured_for_understanding = parser_router.should_use_understanding_api(cf.path)
+ use_understanding = bool(split_content and configured_for_understanding)
+ native_parser = None if use_understanding else self._assign_parser(cf, registry)
+ file_parser = parser_router if use_understanding else native_parser
+ native_parser_unavailable = bool(
+ not split_content
+ and configured_for_understanding
+ and native_parser is None
+ and not is_text_file(cf.path)
+ )
+ parser_name = (
+ "UnderstandingAPI"
+ if use_understanding
+ else "native"
+ if native_parser_unavailable
+ else type(file_parser).__name__
+ if file_parser
+ else "direct"
+ )
+
+ is_media_parser = file_parser and parser_name in {
+ "ImageParser",
+ "AudioParser",
+ "VideoParser",
+ }
+ is_media_file = Path(cf.path).suffix.lower() in MEDIA_EXTENSIONS
+ job = {
+ "index": index,
+ "classified_file": cf,
+ "file_parser": file_parser,
+ "parser_name": parser_name,
+ "use_understanding": use_understanding,
+ "native_parser_unavailable": native_parser_unavailable,
+ "direct_upload": bool(
+ directly_upload_media
+ and not use_understanding
+ and is_media_parser
+ and is_media_file
+ ),
+ }
+ file_jobs.append(job)
+ if use_understanding:
+ understanding_jobs.append(job)
+
viking_fs = self._get_viking_fs()
temp_uri = self._create_temp_uri()
target_uri = f"{temp_uri}/{dir_name}"
@@ -178,30 +264,83 @@ class DirectoryParser(BaseParser):
result.meta["processed_files"] = []
result.meta["failed_files"] = source_skipped_items
result.meta["unsupported_files"] = []
- result.meta["skipped_files"] = []
+ result.meta["skipped_files"] = self._parse_skipped(scan_result.skipped)
return result
# ── Phase 2: process each file ────────────────────────────
file_count = 0
- processed_files: List[Dict[str, str]] = []
- failed_files: List[Dict[str, str]] = []
-
- for cf in processable_files:
- file_parser = self._assign_parser(cf, registry)
- parser_name = type(file_parser).__name__ if file_parser else "direct"
-
- # Check if this is a media parser and we should directly upload
- is_media_parser = file_parser and parser_name in [
- "ImageParser",
- "AudioParser",
- "VideoParser",
- ]
- ext = Path(cf.path).suffix.lower()
- is_media_file = ext in MEDIA_EXTENSIONS
+ processed_files: List[Dict[str, Any]] = []
+ failed_files: List[Dict[str, Any]] = []
+ understanding_results: Dict[int, Dict[str, Any]] = {}
+
+ if understanding_jobs:
+ parser_api = getattr(ov_config, "parser_api", None)
+ job_timeout = self._get_parser_api_job_timeout(parser_api)
+ logger.info(
+ "[DirectoryParser] Processing %d Understanding file(s) with "
+ "shared_max_concurrent=%d, job_timeout=%.1fs",
+ len(understanding_jobs),
+ directory_config.max_concurrent,
+ job_timeout,
+ )
+ understanding_results = await self._parse_understanding_jobs(
+ understanding_jobs,
+ preserve_structure=preserve_structure,
+ import_root=str(source_path),
+ split_content=split_content,
+ max_concurrent=directory_config.max_concurrent,
+ job_timeout=job_timeout,
+ )
- if directly_upload_media and is_media_parser and is_media_file:
- # Directly upload media file without using media parser
- ok = await self._upload_file_directly(
+ for job in file_jobs:
+ cf = job["classified_file"]
+ file_parser = job["file_parser"]
+ parser_name = job["parser_name"]
+ detail: Dict[str, Any]
+
+ if job["use_understanding"]:
+ parsed = understanding_results[job["index"]]
+ error = parsed.get("error")
+ sub_result = parsed.get("result")
+ if error is not None:
+ warnings.append(f"Failed to parse {cf.rel_path}: {error}")
+ error_meta = getattr(error, "meta", {})
+ detail = {
+ "ok": False,
+ "meta": error_meta if isinstance(error_meta, dict) else {},
+ "error": str(error),
+ }
+ else:
+ try:
+ await self._merge_parser_result(
+ cf,
+ sub_result,
+ target_uri,
+ viking_fs,
+ preserve_structure=preserve_structure,
+ split_content=split_content,
+ )
+ detail = {
+ "ok": True,
+ "meta": getattr(sub_result, "meta", {}) or {},
+ "error": None,
+ }
+ except Exception as exc:
+ warnings.append(f"Failed to parse {cf.rel_path}: {exc}")
+ detail = {
+ "ok": False,
+ "meta": getattr(sub_result, "meta", {}) or {},
+ "error": str(exc),
+ }
+ elif job["native_parser_unavailable"]:
+ error = (
+ "parse_mode='no_split' requires a native parser, but none is "
+ "available for this file type"
+ )
+ warnings.append(f"Failed to parse {cf.rel_path}: {error}")
+ detail = {"ok": False, "meta": {}, "error": error}
+ elif job["direct_upload"]:
+ detail = await self._upload_file_directly(
cf,
target_uri,
viking_fs,
@@ -210,8 +349,7 @@ class DirectoryParser(BaseParser):
)
parser_name = "direct_upload"
else:
- # Normal processing with parser
- ok = await self._process_single_file(
+ detail = await self._process_single_file(
cf,
file_parser,
target_uri,
@@ -219,24 +357,16 @@ class DirectoryParser(BaseParser):
warnings,
preserve_structure=preserve_structure,
import_root=str(source_path),
- split_content=kwargs.get("split_content", True),
+ split_content=split_content,
)
- if ok:
+ file_entry = self._file_status_entry(cf, parser_name, detail)
+ if detail["ok"]:
file_count += 1
- processed_files.append(
- {
- "path": cf.rel_path,
- "parser": parser_name,
- }
- )
+ processed_files.append(file_entry)
else:
- failed_files.append(
- {
- "path": cf.rel_path,
- "parser": parser_name,
- }
- )
+ failed_files.append(file_entry)
+ failed_files.extend(self._nested_failed_files(cf, parser_name, detail))
# Collect unsupported files from scan result
unsupported_files = [
@@ -280,6 +410,8 @@ class DirectoryParser(BaseParser):
return result
+ except InvalidArgumentError:
+ raise
except Exception as exc:
logger.error(
f"[DirectoryParser] Failed to parse directory {source_path}: {exc}",
@@ -328,7 +460,7 @@ class DirectoryParser(BaseParser):
"""Parse skipped entry strings into structured dicts.
Each entry has the format ``"rel_path (reason)"``.
- Returns a list of ``{"path": ..., "status": ...}``.
+ Returns a list of ``{"path": ..., "status": ..., "reason": ...}``.
"""
result: List[Dict[str, str]] = []
for entry in skipped:
@@ -341,7 +473,7 @@ class DirectoryParser(BaseParser):
path = entry
reason = "skip"
status = DirectoryParser._REASON_TO_STATUS.get(reason, "skip")
- result.append({"path": path, "status": status})
+ result.append({"path": path, "status": status, "reason": reason})
return result
@staticmethod
@@ -379,6 +511,71 @@ class DirectoryParser(BaseParser):
)
return normalized
+ @staticmethod
+ def _nested_failed_files(
+ classified_file: "ClassifiedFile",
+ parser_name: str,
+ detail: Dict[str, Any],
+ ) -> List[Dict[str, Any]]:
+ """Promote leaf failures from a parsed ZIP into the outer directory result."""
+ if parser_name != "ZipParser":
+ return []
+ meta = detail.get("meta")
+ if not isinstance(meta, dict) or not isinstance(meta.get("failed_files"), list):
+ return []
+
+ prefix = classified_file.rel_path.replace("\\", "/").rstrip("/")
+ promoted: List[Dict[str, Any]] = []
+ for item in meta["failed_files"]:
+ if not isinstance(item, dict):
+ continue
+ child = dict(item)
+ child_path = str(child.get("path") or "<unknown>").replace("\\", "/").lstrip("/")
+ child["path"] = f"{prefix}/{child_path}"
+ promoted.append(child)
+ return promoted
+
+ @staticmethod
+ def _file_status_entry(
+ classified_file: "ClassifiedFile",
+ parser_name: str,
+ detail: Dict[str, Any],
+ ) -> Dict[str, Any]:
+ """Build deterministic per-file status metadata."""
+ entry: Dict[str, Any] = {
+ "path": classified_file.rel_path,
+ "parser": parser_name,
+ }
+ meta = detail.get("meta")
+ if isinstance(meta, dict):
+ for key in (
+ "doc_name",
+ "doc_type",
+ "source_name",
+ "file_name",
+ "file_id",
+ "response_id",
+ ):
+ if meta.get(key):
+ entry[key] = meta[key]
+ if detail.get("error"):
+ entry["error"] = str(detail["error"])
+ return entry
+
+ @staticmethod
+ def _get_parser_api_job_timeout(parser_api: Any, default: float = 1800.0) -> float:
+ """Return a bounded end-to-end timeout for one Understanding file."""
+ try:
+ response_timeout = float(getattr(parser_api, "response_timeout_seconds", default))
+ http_timeout = float(getattr(parser_api, "http_timeout_seconds", 10.0))
+ except (TypeError, ValueError) as exc:
+ raise InvalidArgumentError(
+ "parser_api response/http timeouts must be positive numbers"
+ ) from exc
+ if response_timeout <= 0 or http_timeout <= 0:
+ raise InvalidArgumentError("parser_api response/http timeouts must be positive numbers")
+ return response_timeout + max(60.0, http_timeout * 2.0)
+
# ------------------------------------------------------------------
# Parser assignment
# ------------------------------------------------------------------
@@ -400,17 +597,127 @@ class DirectoryParser(BaseParser):
# Per-file processing
# ------------------------------------------------------------------
+ @staticmethod
+ async def _parse_understanding_jobs(
+ jobs: List[Dict[str, Any]],
+ *,
+ preserve_structure: bool,
+ import_root: Optional[str],
+ split_content: bool,
+ max_concurrent: int,
+ job_timeout: float,
+ ) -> Dict[int, Dict[str, Any]]:
+ """Parse jobs with a fixed local pool and a shared service-loop limit."""
+ limiter = _get_understanding_limiter(max_concurrent)
+ queue: asyncio.Queue[Dict[str, Any]] = asyncio.Queue()
+ for job in jobs:
+ queue.put_nowait(job)
+
+ results: Dict[int, Dict[str, Any]] = {}
+
+ async def _worker() -> None:
+ while True:
+ try:
+ job = queue.get_nowait()
+ except asyncio.QueueEmpty:
+ return
+
+ try:
+ async with limiter:
+ parse_coro = DirectoryParser._parse_file_with_parser(
+ job["classified_file"],
+ job["file_parser"],
+ preserve_structure=preserve_structure,
+ import_root=import_root,
+ split_content=split_content,
+ )
+ sub_result = await asyncio.wait_for(parse_coro, timeout=job_timeout)
+ results[job["index"]] = {"result": sub_result, "error": None}
+ except asyncio.TimeoutError:
+ results[job["index"]] = {
+ "result": None,
+ "error": TimeoutError(
+ f"Understanding job timed out after {job_timeout:.1f}s"
+ ),
+ }
+ except Exception as exc:
+ results[job["index"]] = {"result": None, "error": exc}
+ finally:
+ queue.task_done()
+
+ worker_count = min(max_concurrent, len(jobs))
+ workers = [asyncio.create_task(_worker()) for _ in range(worker_count)]
+ try:
+ await asyncio.gather(*workers)
+ finally:
+ for worker in workers:
+ if not worker.done():
+ worker.cancel()
+ await asyncio.gather(*workers, return_exceptions=True)
+
+ return results
+
+ @staticmethod
+ async def _parse_file_with_parser(
+ classified_file: "ClassifiedFile",
+ parser: Union[BaseParser, "ParserRouter"],
+ *,
+ preserve_structure: bool,
+ import_root: Optional[str],
+ split_content: bool,
+ ) -> ParseResult:
+ """Run one parser without mutating the directory destination tree."""
+ return await parser.parse(
+ str(classified_file.path),
+ enable_link_rewrite=preserve_structure,
+ link_rewrite_root=import_root,
+ allowed_media_dirs=[Path(import_root)] if import_root else None,
+ split_content=split_content,
+ flatten_single_output=bool(not split_content and preserve_structure),
+ )
+
+ @staticmethod
+ async def _merge_parser_result(
+ classified_file: "ClassifiedFile",
+ sub_result: ParseResult,
+ target_uri: str,
+ viking_fs: Any,
+ *,
+ preserve_structure: bool,
+ split_content: bool,
+ ) -> None:
+ """Merge one completed parser result in source-file order."""
+ no_content_error = "Parse failed: no content generated"
+ if sub_result.warnings:
+ no_content_error += "; " + "; ".join(sub_result.warnings)
+ if not sub_result.temp_dir_path:
+ raise ValueError(no_content_error)
+
+ if preserve_structure:
+ parent = str(PurePosixPath(classified_file.rel_path).parent)
+ dest = f"{target_uri}/{parent}" if parent != "." else target_uri
+ else:
+ dest = target_uri
+ merged = await DirectoryParser._merge_temp(
+ viking_fs,
+ sub_result.temp_dir_path,
+ dest,
+ flatten_single_output=bool(not split_content and preserve_structure),
+ )
+ if not merged:
+ raise ValueError(no_content_error)
+
@staticmethod
async def _process_single_file(
classified_file: "ClassifiedFile",
- parser: Optional[BaseParser],
+ parser: Optional[Union[BaseParser, "ParserRouter"]],
target_uri: str,
viking_fs: Any,
warnings: List[str],
preserve_structure: bool = True,
import_root: Optional[str] = None,
split_content: bool = True,
- ) -> bool:
+ ) -> Dict[str, Any]:
"""Process one file into the VikingFS directory temp.
- Files WITH a parser → ``parser.parse()`` → merge output into
@@ -423,42 +730,42 @@ class DirectoryParser(BaseParser):
*target_uri* (flat).
Returns:
- *True* on success, *False* on failure.
+ Per-file status detail including the parser error when processing fails.
"""
rel_path = classified_file.rel_path
src_file = classified_file.path
if parser:
+ sub_result: Optional[ParseResult] = None
try:
- sub_result = await parser.parse(
- str(src_file),
- # Rewrite only makes sense when relative structure is preserved;
- # in flat mode link targets don't exist at their original paths.
- enable_link_rewrite=preserve_structure,
- link_rewrite_root=import_root,
- # The whole ingested tree is fair game for image ingestion:
- # an md may reference shared images outside its own directory
- # (e.g. ../images/x.gif) that still live inside the import.
- allowed_media_dirs=[Path(import_root)] if import_root else None,
+ sub_result = await DirectoryParser._parse_file_with_parser(
+ classified_file,
+ parser,
+ preserve_structure=preserve_structure,
+ import_root=import_root,
split_content=split_content,
- flatten_single_output=bool(not split_content and preserve_structure),
)
- if sub_result.temp_dir_path:
- if preserve_structure:
- parent = str(PurePosixPath(rel_path).parent)
- dest = f"{target_uri}/{parent}" if parent != "." else target_uri
- else:
- dest = target_uri
- await DirectoryParser._merge_temp(
- viking_fs,
- sub_result.temp_dir_path,
- dest,
- flatten_single_output=bool(not split_content and preserve_structure),
- )
- return True
+ await DirectoryParser._merge_parser_result(
+ classified_file,
+ sub_result,
+ target_uri,
+ viking_fs,
+ preserve_structure=preserve_structure,
+ split_content=split_content,
+ )
+ return {
+ "ok": True,
+ "meta": getattr(sub_result, "meta", {}) or {},
+ "error": None,
+ }
except Exception as exc:
warnings.append(f"Failed to parse {rel_path}: {exc}")
- return False
+ meta = getattr(sub_result, "meta", {}) if sub_result is not None else {}
+ return {
+ "ok": False,
+ "meta": meta if isinstance(meta, dict) else {},
+ "error": str(exc),
+ }
else:
try:
content = src_file.read_bytes()
@@ -467,10 +774,10 @@ class DirectoryParser(BaseParser):
else:
dst_uri = f"{target_uri}/{PurePosixPath(rel_path).name}"
await viking_fs.write_file(dst_uri, content)
- return True
+ return {"ok": True, "meta": {}, "error": None}
except Exception as exc:
warnings.append(f"Failed to upload {rel_path}: {exc}")
- return False
+ return {"ok": False, "meta": {}, "error": str(exc)}
@staticmethod
async def _upload_file_directly(
@@ -479,7 +786,7 @@ class DirectoryParser(BaseParser):
viking_fs: Any,
warnings: List[str],
preserve_structure: bool = True,
- ) -> bool:
+ ) -> Dict[str, Any]:
"""Directly upload a file without using its parser.
Used for media files when directly_upload_media=True.
@@ -490,7 +797,7 @@ class DirectoryParser(BaseParser):
*target_uri* (flat).
Returns:
- *True* on success, *False* on failure.
+ Per-file status detail including the upload error when processing fails.
"""
rel_path = classified_file.rel_path
src_file = classified_file.path
@@ -502,10 +809,10 @@ class DirectoryParser(BaseParser):
else:
dst_uri = f"{target_uri}/{PurePosixPath(rel_path).name}"
await viking_fs.write_file(dst_uri, content)
- return True
+ return {"ok": True, "meta": {}, "error": None}
except Exception as exc:
warnings.append(f"Failed to upload {rel_path}: {exc}")
- return False
+ return {"ok": False, "meta": {}, "error": str(exc)}
# ------------------------------------------------------------------
# VikingFS merge helpers
@@ -523,7 +830,7 @@ class DirectoryParser(BaseParser):
dest_uri: str,
*,
flatten_single_output: bool = False,
- ) -> None:
+ ) -> bool:
"""Move all content from a parser's temp directory into *dest_uri*.
After the move the source temp is deleted. Hidden files stay filtered,
@@ -532,8 +839,34 @@ class DirectoryParser(BaseParser):
image rewrite). In no-split directory imports, a wrapper containing one
standalone file is promoted into ``dest_uri``; wrappers with additional
files, directories, sidecars, or destination-name conflicts are retained.
+ Returns False for a tree with no visible files, without creating any
+ destination directories. Sidecars alone do not count as content.
"""
entries = await viking_fs.ls(src_temp_uri, show_all_hidden=True, node_limit=LS_ALL_NODES)
+
+ async def has_content(parent_uri: str, children: List[Dict[str, Any]]) -> bool:
+ for entry in children:
+ name = entry.get("name", "")
+ if not name or name in {".", ".."}:
+ continue
+ if DirectoryParser._is_dir_entry(entry):
+ child_uri = entry.get("uri", f"{parent_uri.rstrip('/')}/{name}")
+ child_entries = await viking_fs.ls(
+ child_uri, show_all_hidden=True, node_limit=LS_ALL_NODES
+ )
+ if await has_content(child_uri, child_entries):
+ return True
+ elif not name.startswith("."):
+ return True
+ return False
+
+ if not await has_content(src_temp_uri, entries):
+ try:
+ await viking_fs.delete_temp(src_temp_uri)
+ except Exception:
+ pass
+ return False
+
merge_entries = [
entry
for entry in entries
@@ -591,7 +924,7 @@ class DirectoryParser(BaseParser):
await viking_fs.delete_temp(src_temp_uri)
except Exception:
pass
- return
+ return True
for entry in entries:
name = entry.get("name", "")
if not name or name in (".", ".."):
@@ -612,6 +945,7 @@ class DirectoryParser(BaseParser):
await viking_fs.delete_temp(src_temp_uri)
except Exception:
pass
+ return True
@staticmethod
async def _is_git_repository(source_path: Path) -> bool:
diff --git a/openviking/parse/understanding_api.py b/openviking/parse/understanding_api.py
index bf656c6f8..26c11cab4 100644
--- a/openviking/parse/understanding_api.py
+++ b/openviking/parse/understanding_api.py
@@ -46,6 +46,14 @@ PREPARED_RESPONSE_ID_ARG = "understanding_response_id"
PREPARED_FILE_ID_ARG = "understanding_file_id"
+class UnderstandingAPIError(RuntimeError):
+ """Parser API failure carrying the remote identifiers already observed."""
+
+ def __init__(self, message: str, meta: Optional[Dict[str, Any]] = None):
+ self.meta = dict(meta or {})
+ super().__init__(message)
+
+
class UnderstandingAPI(BaseParser):
"""
UnderstandingAPI: Third-party parse client.
@@ -158,62 +166,76 @@ class UnderstandingAPI(BaseParser):
doc_name = Path(effective_name).stem or "resource"
doc_type = doc_type or "unknown"
- task_meta: Dict[str, Any] = {}
+ task_meta: Dict[str, Any] = {"doc_name": doc_name, "doc_type": doc_type}
+ source_name = kwargs.get("source_name")
+ if isinstance(source_name, str) and source_name:
+ task_meta["source_name"] = source_name
+ if local_path is not None:
+ task_meta["file_name"] = local_path.name
- if prepared_response_id:
- response_id = prepared_response_id
- elif prepared_file_id:
- task_meta["file_id"] = prepared_file_id
- response_obj = await self._create_response_for_file(file_id=prepared_file_id)
- elif url is None and local_path is not None:
- file_obj = await self._create_file(local_path=local_path)
- file_id = file_obj.get("id")
- if not file_id:
- raise RuntimeError(
- f"files api missing file_id: {self._safe_error_summary(file_obj)}"
+ try:
+ if prepared_response_id:
+ response_id = prepared_response_id
+ elif prepared_file_id:
+ task_meta["file_id"] = prepared_file_id
+ response_obj = await self._create_response_for_file(file_id=prepared_file_id)
+ elif url is None and local_path is not None:
+ file_obj = await self._create_file(local_path=local_path)
+ file_id_value = file_obj.get("id")
+ if not file_id_value:
+ raise RuntimeError(
+ f"files api missing file_id: {self._safe_error_summary(file_obj)}"
+ )
+ file_id = str(file_id_value)
+ task_meta["file_id"] = file_id
+ response_obj = await self._create_response_for_file(file_id=file_id)
+ else:
+ if url is None:
+ raise RuntimeError("missing url for url mode")
+ response_obj = await self._create_response_for_url(
+ url=url,
+ doc_type=doc_type,
+ lark_file=lark_file,
)
- task_meta["file_id"] = file_id
- response_obj = await self._create_response_for_file(file_id=file_id)
- else:
- if url is None:
- raise RuntimeError("missing url for url mode")
- response_obj = await self._create_response_for_url(
- url=url,
- doc_type=doc_type,
- lark_file=lark_file if is_feishu_url else None,
- )
- if not prepared_response_id:
- response_id_value = response_obj.get("id")
- if not response_id_value:
+ if not prepared_response_id:
+ response_id_value = response_obj.get("id")
+ if not response_id_value:
+ raise RuntimeError(
+ f"responses api missing id: {self._safe_error_summary(response_obj)}"
+ )
+ response_id = str(response_id_value)
+ task_meta["response_id"] = response_id
+
+ response_obj = await self._poll_response(response_id=response_id)
+ zip_url = self._extract_zip_url(response_obj)
+ if not zip_url:
raise RuntimeError(
- f"responses api missing id: {self._safe_error_summary(response_obj)}"
+ "understanding result missing zip_url: "
+ f"{self._safe_error_summary(response_obj)}"
)
- response_id = str(response_id_value)
- task_meta["response_id"] = response_id
- response_obj = await self._poll_response(response_id=response_id)
- zip_url = self._extract_zip_url(response_obj)
- if not zip_url:
- raise RuntimeError(
- f"understanding result missing zip_url: {self._safe_error_summary(response_obj)}"
- )
-
- zip_path = await self._download_zip(zip_url)
- try:
- if is_feishu_url and not display_name:
- archive_root = self._single_zip_root_name(zip_path)
- if archive_root:
- doc_name = archive_root
- temp_dir_path = await self._unpack_zip_to_temp_dir(
- zip_path=zip_path,
- resource_name=doc_name,
- )
- finally:
+ zip_path = await self._download_zip(zip_url)
try:
- zip_path.unlink()
- except Exception:
- pass
+ if is_feishu_url and not display_name:
+ archive_root = self._single_zip_root_name(zip_path)
+ if archive_root:
+ doc_name = archive_root
+ task_meta["doc_name"] = doc_name
+ temp_dir_path = await self._unpack_zip_to_temp_dir(
+ zip_path=zip_path,
+ resource_name=doc_name,
+ )
+ finally:
+ try:
+ zip_path.unlink()
+ except Exception:
+ pass
+ except UnderstandingAPIError:
+ raise
+ except Exception as exc:
+ logger.warning("[UnderstandingAPI] Parse failed: %s; meta=%s", exc, task_meta)
+ raise UnderstandingAPIError(str(exc), task_meta) from exc
content_type = (
"video"
@@ -248,7 +270,7 @@ class UnderstandingAPI(BaseParser):
),
temp_dir_path=temp_dir_path,
parser_name="UnderstandingAPI",
- meta=task_meta,
+ meta={key: task_meta[key] for key in ("file_id", "response_id") if task_meta.get(key)},
)
logger.info("[UnderstandingAPI] done")
@@ -329,7 +351,10 @@ class UnderstandingAPI(BaseParser):
return json.dumps(obj, ensure_ascii=False).encode("utf-8")
def _auth_headers(self, extra: Optional[Dict[str, str]] = None) -> Dict[str, str]:
- headers = {"Authorization": f"Bearer {self._api_key}"}
+ headers = {
+ "Authorization": f"Bearer {self._api_key}",
+ "x-kb-env": "snake",
+ }
if extra:
headers.update(extra)
return headers
@@ -343,15 +368,66 @@ class UnderstandingAPI(BaseParser):
summary[key] = obj.get(key)
err = obj.get("error")
if isinstance(err, dict):
- summary["error"] = {k: err.get(k) for k in ("type", "code", "message") if k in err}
+ summary["error"] = {
+ k: err.get(k) for k in ("type", "code", "message", "param") if k in err
+ }
+ # Failed Responses tasks carry the reason in output_text, not error.
+ output = obj.get("output")
+ if obj.get("status") == "failed" and isinstance(output, list):
+ texts = []
+ for item in output:
+ if not isinstance(item, dict):
+ continue
+ content = item.get("content")
+ if not isinstance(content, list):
+ continue
+ for part in content:
+ if not isinstance(part, dict) or part.get("type") != "output_text":
+ continue
+ text = part.get("text")
+ if isinstance(text, str) and text.strip():
+ texts.append(text)
+ if texts:
+ summary["output_text"] = texts
return summary
+ def _error_message(self, obj: Any) -> str:
+ """Extract the failure reason without adding remote identifiers."""
+ summary = self._safe_error_summary(obj)
+ error = summary.get("error") or {}
+ for message in (error.get("message"), summary.get("message")):
+ if isinstance(message, str) and message.strip():
+ return message.strip()
+ if summary.get("output_text"):
+ return "; ".join(summary["output_text"])
+ return str(error.get("code") or "request failed")
+
def _raise_if_error(self, obj: Any, *, context: str) -> None:
if not isinstance(obj, dict):
return
err = obj.get("error")
if isinstance(err, dict) and err.get("code"):
- raise RuntimeError(f"{context}: {self._safe_error_summary(obj)}")
+ raise RuntimeError(f"{context}: {self._error_message(obj)}")
+
+ def _read_api_response(self, rsp: httpx.Response, *, context: str) -> Dict[str, Any]:
+ """Preserve business error details and the HTTP exception's status metadata."""
+ try:
+ rsp.raise_for_status()
+ except httpx.HTTPStatusError as exc:
+ try:
+ summary = self._safe_error_summary(rsp.json())
+ except ValueError:
+ summary = None
+ if summary is not None:
+ raise httpx.HTTPStatusError(
+ f"{context}: HTTP {rsp.status_code}: {summary}",
+ request=exc.request,
+ response=exc.response,
+ ) from exc
+ raise
+ body = rsp.json()
+ self._raise_if_error(body, context=context)
+ return body
async def _create_file(self, *, local_path: Path) -> Dict[str, Any]:
file_size = local_path.stat().st_size
@@ -360,7 +436,9 @@ class UnderstandingAPI(BaseParser):
if file_size > self._upload_simple_max_bytes:
if not self._enable_resumable_upload:
raise ValueError(
- f"file too large ({file_size} bytes), enable parser_api.enable_resumable_upload to continue"
+ f"file too large: size={file_size}, "
+ f"upload_simple_max_bytes={self._upload_simple_max_bytes}; "
+ "enable parser_api.enable_resumable_upload to continue"
)
return await self._multipart_create_file(local_path)
@@ -376,10 +454,7 @@ class UnderstandingAPI(BaseParser):
data=data,
files=files,
)
- rsp.raise_for_status()
- body = rsp.json()
- self._raise_if_error(body, context="files api error")
- return body
+ return self._read_api_response(rsp, context="files api error")
async def _create_response_for_file(self, *, file_id: str) -> Dict[str, Any]:
content: Dict[str, Any] = {"type": "file", "file": {"file_id": file_id}}
@@ -396,10 +471,7 @@ class UnderstandingAPI(BaseParser):
content=self._json_bytes(payload),
headers=self._auth_headers({"Content-Type": "application/json;charset=UTF-8"}),
)
- rsp.raise_for_status()
- body = rsp.json()
- self._raise_if_error(body, context="responses api error")
- return body
+ return self._read_api_response(rsp, context="responses api error")
async def _create_response_for_url(
self,
@@ -431,10 +503,7 @@ class UnderstandingAPI(BaseParser):
content=self._json_bytes(payload),
headers=self._auth_headers({"Content-Type": "application/json;charset=UTF-8"}),
)
- rsp.raise_for_status()
- body = rsp.json()
- self._raise_if_error(body, context="responses api error")
- return body
+ return self._read_api_response(rsp, context="responses api error")
@staticmethod
def _is_feishu_url(source: str) -> bool:
@@ -508,11 +577,7 @@ class UnderstandingAPI(BaseParser):
f"{self._api_base}/responses/{response_id}",
headers=self._auth_headers(),
)
- rsp.raise_for_status()
- body = rsp.json()
- self._raise_if_error(
- body, context=f"responses api error: response_id={response_id}"
- )
+ body = self._read_api_response(rsp, context="responses api error")
status = body.get("status")
if status != last_status:
logger.info(f"[UnderstandingAPI] response_id={response_id} status={status}")
@@ -520,13 +585,9 @@ class UnderstandingAPI(BaseParser):
if status == "completed":
return body
if status == "failed":
- raise RuntimeError(
- f"understanding failed: response_id={response_id} body={self._safe_error_summary(body)}"
- )
+ raise RuntimeError(f"understanding failed: {self._error_message(body)}")
if asyncio.get_running_loop().time() > deadline:
- raise TimeoutError(
- f"understanding timeout: response_id={response_id} last_status={last_status}"
- )
+ raise TimeoutError(f"understanding timeout: last_status={last_status}")
await asyncio.sleep(max(self._default_poll_interval_ms, 200) / 1000.0)
def _extract_zip_url(self, response_obj: Dict[str, Any]) -> Optional[str]:
@@ -559,10 +620,7 @@ class UnderstandingAPI(BaseParser):
content=self._json_bytes(payload),
headers=self._auth_headers({"Content-Type": "application/json;charset=UTF-8"}),
)
- rsp.raise_for_status()
- body = rsp.json()
- self._raise_if_error(body, context="uploads init error")
- return body
+ return self._read_api_response(rsp, context="uploads init error")
async def _uploads_status(self, *, upload_id: str, object_key: str) -> Dict[str, Any]:
async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as client:
@@ -570,10 +628,7 @@ class UnderstandingAPI(BaseParser):
f"{self._api_base}/files?upload_id={upload_id}&object_key={object_key}",
headers=self._auth_headers(),
)
- rsp.raise_for_status()
- body = rsp.json()
- self._raise_if_error(body, context="uploads status error")
- return body
+ return self._read_api_response(rsp, context="uploads status error")
async def _uploads_put_part(
self, *, upload_id: str, object_key: str, part_number: int, data: bytes
@@ -585,10 +640,7 @@ class UnderstandingAPI(BaseParser):
headers=headers,
content=data,
)
- rsp.raise_for_status()
- body = rsp.json()
- self._raise_if_error(body, context="uploads part error")
- return body
+ return self._read_api_response(rsp, context="uploads part error")
async def _uploads_complete(
self, *, upload_id: str, object_key: str, parts: List[Dict[str, Any]]
@@ -600,10 +652,7 @@ class UnderstandingAPI(BaseParser):
content=self._json_bytes(payload),
headers=self._auth_headers({"Content-Type": "application/json;charset=UTF-8"}),
)
- rsp.raise_for_status()
- body = rsp.json()
- self._raise_if_error(body, context="uploads complete error")
- return body
+ return self._read_api_response(rsp, context="uploads complete error")
async def _multipart_create_file(self, file_path: Path) -> Dict[str, Any]:
init_obj = await self._uploads_init(file_path=file_path)
diff --git a/openviking/server/resource_ingest.py b/openviking/server/resource_ingest.py
index 25937f817..9f3aacf3e 100644
--- a/openviking/server/resource_ingest.py
+++ b/openviking/server/resource_ingest.py
@@ -47,7 +47,10 @@ async def ingest_temp_upload(
try:
ingest_args = dict(args or {})
if parse_mode != ParseMode.DEFAULT and parse_mode != ParseMode.DEFAULT.value:
- ingest_args.setdefault("parse_mode", str(parse_mode.value if isinstance(parse_mode, ParseMode) else parse_mode))
+ ingest_args.setdefault(
+ "parse_mode",
+ str(parse_mode.value if isinstance(parse_mode, ParseMode) else parse_mode),
+ )
result = await get_service().resources.add_resource(
path=resolved.local_path,
ctx=ctx,
diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.py
index 6775049ae..0d455a28e 100644
--- a/openviking/service/resource_service.py
+++ b/openviking/service/resource_service.py
@@ -57,7 +57,7 @@ from openviking.server.user_config import (
from openviking.storage.acl import AclAction
from openviking.storage.queuefs import QueueManager, get_queue_manager
from openviking.storage.queuefs.add_resource_msg import AddResourcePhase
-from openviking.storage.viking_fs import VikingFS
+from openviking.storage.viking_fs import LS_ALL_NODES, VikingFS
from openviking.storage.vikingdb_manager import VikingDBManager
from openviking.telemetry import get_current_telemetry, register_telemetry, unregister_telemetry
from openviking.telemetry.request_wait_tracker import get_request_wait_tracker
@@ -378,9 +378,7 @@ class ResourceService:
try:
await self._handle_watch_task_cancellation(to_uri=to, ctx=ctx)
except Exception as e:
- logger.warning(
- f"[ResourceService] Failed to cancel watch task for {to}: {e}"
- )
+ logger.warning(f"[ResourceService] Failed to cancel watch task for {to}: {e}")
def _normalize_add_resource_args(
self,
@@ -396,9 +394,7 @@ class ResourceService:
if not args:
return _NormalizedAddResourceArgs({})
- reserved_fields = _ADD_RESOURCE_ARGS_RESERVED_FIELDS - (
- allowed_reserved_fields or set()
- )
+ reserved_fields = _ADD_RESOURCE_ARGS_RESERVED_FIELDS - (allowed_reserved_fields or set())
reserved = sorted(set(args).intersection(reserved_fields))
if reserved:
raise InvalidArgumentError(
@@ -534,6 +530,43 @@ class ResourceService:
if inspect.isawaitable(result):
await result
+ async def _cleanup_reserved_target_if_empty(
+ self,
+ *,
+ root_uri: str,
+ ctx: RequestContext,
+ resource_lock: Dict[str, Any],
+ ) -> bool:
+ """Remove a newly reserved target only while it is still empty."""
+ try:
+ if not await self._viking_fs.exists(root_uri, ctx=ctx):
+ return True
+ stat = await self._viking_fs.stat(root_uri, ctx=ctx)
+ if not isinstance(stat, dict) or not stat.get("isDir"):
+ return False
+ entries = await self._viking_fs.ls(
+ root_uri,
+ show_all_hidden=True,
+ node_limit=LS_ALL_NODES,
+ ctx=ctx,
+ )
+ if any(entry.get("name") not in {None, "", ".", ".."} for entry in entries):
+ return False
+ await self._viking_fs.rm(
+ root_uri,
+ recursive=True,
+ ctx=ctx,
+ lease_ref=resource_lock,
+ )
+ return True
+ except Exception as exc:
+ logger.warning(
+ "[ResourceService] Failed to clean empty reserved target %s: %s",
+ root_uri,
+ exc,
+ )
+ return False
+
async def close_background_tasks(self) -> None:
"""Cancel in-flight connector monitoring tasks during service shutdown."""
if not self._background_tasks:
@@ -552,6 +585,7 @@ class ResourceService:
resource_lock: Optional[Dict[str, Any]] = None,
task_auth: Optional[Dict[str, Any]] = None,
on_enqueued: Optional[Callable[[], None]] = None,
+ on_failed_with_lock: Optional[Callable[[Dict[str, Any]], Awaitable[None]]] = None,
) -> Any:
"""Persist a job and fully own the passed lock until handoff or release completes."""
from openviking.service.task_tracker import get_task_tracker
@@ -588,6 +622,8 @@ class ResourceService:
)
except BaseException:
if resource_lock is not None:
+ if on_failed_with_lock is not None:
+ await on_failed_with_lock(resource_lock)
await self._release_lock_ref(resource_lock)
if task is not None and not enqueued:
await tracker.fail(
@@ -619,7 +655,8 @@ class ResourceService:
legacy_backend = normalize_parser_backend(queued_args.pop("parser_backend", None))
parser_backend = legacy_backend or (
ParserBackend.UNDERSTANDING
- if msg.understanding_response_id is not None or msg.understanding_file_id is not None
+ if msg.understanding_response_id is not None
+ or msg.understanding_file_id is not None
else ParserBackend.INTERNAL
)
internal_kwargs: Dict[str, Any] = {"parser_backend": parser_backend}
@@ -671,33 +708,52 @@ class ResourceService:
from openviking.parse.understanding_api import PREPARED_FILE_ID_ARG
internal_kwargs[PREPARED_FILE_ID_ARG] = msg.understanding_file_id
- result = await self._execute_resource_ingestion(
- path=msg.path,
- ctx=ctx,
- to=target_uri,
- parent=parent_uri,
- to_is_directory=msg.to_is_directory,
- reason=msg.reason,
- instruction=msg.instruction,
- defer_post_processing=False,
- timeout=msg.timeout,
- build_index=msg.build_index,
- summarize=msg.summarize,
- processing_mode=msg.processing_mode,
- parse_mode=msg.parse_mode,
- watch_interval=msg.watch_interval,
- manage_watch=not msg.skip_watch_management,
- tags=msg.tags,
- tag_mode=msg.tag_mode,
- allow_local_path_resolution=msg.allow_local_path_resolution,
- enforce_public_remote_targets=msg.enforce_public_remote_targets,
- resource_lock=resource_lock,
- stage_callback=stage_callback,
- watch_auth_state=watch_auth_state,
- prepared_resource=prepared_resource,
- internal_task=msg.internal_task,
- **internal_kwargs,
- )
+ try:
+ result = await self._execute_resource_ingestion(
+ path=msg.path,
+ ctx=ctx,
+ to=target_uri,
+ parent=parent_uri,
+ to_is_directory=msg.to_is_directory,
+ reason=msg.reason,
+ instruction=msg.instruction,
+ defer_post_processing=False,
+ timeout=msg.timeout,
+ build_index=msg.build_index,
+ summarize=msg.summarize,
+ processing_mode=msg.processing_mode,
+ parse_mode=msg.parse_mode,
+ watch_interval=msg.watch_interval,
+ manage_watch=not msg.skip_watch_management,
+ tags=msg.tags,
+ tag_mode=msg.tag_mode,
+ allow_local_path_resolution=msg.allow_local_path_resolution,
+ enforce_public_remote_targets=msg.enforce_public_remote_targets,
+ resource_lock=resource_lock,
+ stage_callback=stage_callback,
+ watch_auth_state=watch_auth_state,
+ prepared_resource=prepared_resource,
+ internal_task=msg.internal_task,
+ **internal_kwargs,
+ )
+ except BaseException:
+ if msg.cleanup_empty_target_on_failure and resource_lock is not None:
+ await self._cleanup_reserved_target_if_empty(
+ root_uri=msg.root_uri,
+ ctx=ctx,
+ resource_lock=resource_lock,
+ )
+ raise
+ if (
+ result.get("status") == "error"
+ and msg.cleanup_empty_target_on_failure
+ and resource_lock is not None
+ ):
+ await self._cleanup_reserved_target_if_empty(
+ root_uri=msg.root_uri,
+ ctx=ctx,
+ resource_lock=resource_lock,
+ )
if msg.staged_source is not None:
result["source_path"] = msg.source_path
stage_result = stage_callback("processing_queue")
@@ -859,7 +915,9 @@ class ResourceService:
path,
ctx,
snapshot_required=local_source
- or bool(processor_kwargs.get("tos_signature") or processor_kwargs.get("tos_access")),
+ or bool(
+ processor_kwargs.get("tos_signature") or processor_kwargs.get("tos_access")
+ ),
parse_mode=mode,
allow_local_path_resolution=allow_local_path_resolution,
**processor_kwargs,
@@ -979,16 +1037,10 @@ class ResourceService:
) -> Dict[str, Any]:
from openviking.storage.queuefs.add_resource_msg import AddResourceMsg
- planned_to_is_directory = (
- to_is_directory if to_is_directory is not None else bool(to)
- )
+ planned_to_is_directory = to_is_directory if to_is_directory is not None else bool(to)
target_to_is_exact = bool(to and not is_content_root_uri(to, kind="resource"))
defer_candidate_resolution = bool(
- (
- plan.defer_unnamed_target
- and plan.source_identity.source_name is None
- and not to
- )
+ (plan.defer_unnamed_target and plan.source_identity.source_name is None and not to)
or (mode is ParseMode.NO_SPLIT and not target_to_is_exact)
)
root_uri = ""
@@ -996,7 +1048,12 @@ class ResourceService:
defer_target_resolution = False
staged_enqueued = False
try:
- root_uri, resource_lock, defer_target_resolution = await self._plan_source_job_target(
+ (
+ root_uri,
+ resource_lock,
+ defer_target_resolution,
+ cleanup_empty_target_on_failure,
+ ) = await self._plan_source_job_target(
path=plan.path,
ctx=ctx,
to=to,
@@ -1060,6 +1117,7 @@ class ResourceService:
to_is_directory=planned_to_is_directory,
args=plan.processor_args,
defer_target_resolution=defer_target_resolution,
+ cleanup_empty_target_on_failure=cleanup_empty_target_on_failure,
understanding_response_id=plan.understanding_response_id,
understanding_file_id=plan.understanding_file_id,
internal_task=internal_task,
@@ -1077,12 +1135,22 @@ class ResourceService:
)
enqueue_lock = resource_lock
resource_lock = None
+
+ async def cleanup_enqueue_failure(lock: Dict[str, Any]) -> None:
+ if cleanup_empty_target_on_failure:
+ await self._cleanup_reserved_target_if_empty(
+ root_uri=root_uri,
+ ctx=ctx,
+ resource_lock=lock,
+ )
+
task = await self._enqueue_add_resource_job(
msg,
queue_name=queue_name,
resource_lock=enqueue_lock,
task_auth=plan.task_auth,
on_enqueued=(transfer_staged_source if plan.staged_source is not None else None),
+ on_failed_with_lock=cleanup_enqueue_failure,
)
except BaseException:
if resource_lock is not None:
@@ -1106,7 +1174,8 @@ class ResourceService:
create_parent: bool,
source_info: _ResourceSourceInfo,
defer_candidate_resolution: bool,
- ) -> tuple[str, Optional[Dict[str, Any]], bool]:
+ ) -> tuple[str, Optional[Dict[str, Any]], bool, bool]:
+ """Resolve the target and track ownership of a newly reserved empty path."""
if not self._resource_processor or not self._viking_fs:
raise NotInitializedError("ResourceProcessor")
@@ -1127,15 +1196,20 @@ class ResourceService:
candidate_uri=candidate_uri,
ctx=ctx,
)
- return root_uri, None, True
+ return root_uri, None, True, False
if candidate_uri:
root_uri, resource_lock = await self._resource_processor.reserve_unique_candidate(
candidate_uri=candidate_uri,
ctx=ctx,
)
- return root_uri, resource_lock, False
+ return root_uri, resource_lock, False, True
await self._viking_fs._ensure_access(root_uri, ctx, action=AclAction.WRITE)
+ # A tree lock may materialize an empty directory marker, so ownership
+ # must be recorded immediately before acquiring it. The zero-timeout
+ # lock still rejects compliant concurrent writers, and cleanup rechecks
+ # that the target is empty before deleting it.
+ target_preexisting = await self._viking_fs.exists(root_uri, ctx=ctx)
dst_path = self._viking_fs._uri_to_path(root_uri, ctx=ctx)
resource_lock = await self._viking_fs._async_agfs.pathlock_acquire_tree(
dst_path,
@@ -1146,7 +1220,7 @@ class ResourceService:
except BaseException:
await self._release_lock_ref(resource_lock)
raise
- return root_uri, resource_lock, False
+ return root_uri, resource_lock, False, not target_preexisting
@staticmethod
def _target_doc_name(
@@ -1189,15 +1263,15 @@ class ResourceService:
else:
proc.kill()
with contextlib.suppress(Exception):
- await asyncio.wait_for(
- asyncio.shield(proc.communicate()), timeout=1.0
- )
+ await asyncio.wait_for(asyncio.shield(proc.communicate()), timeout=1.0)
if isinstance(exc, asyncio.TimeoutError):
raise InvalidArgumentError(
"Cannot access Git repository; the preflight timed out after 10s."
) from exc
if isinstance(exc, Exception):
- raise InvalidArgumentError("Cannot access Git repository during preflight.") from exc
+ raise InvalidArgumentError(
+ "Cannot access Git repository during preflight."
+ ) from exc
raise
if proc.returncode != 0:
diff --git a/openviking/storage/queuefs/add_resource_msg.py b/openviking/storage/queuefs/add_resource_msg.py
index 189bfc3b1..d493e7929 100644
--- a/openviking/storage/queuefs/add_resource_msg.py
+++ b/openviking/storage/queuefs/add_resource_msg.py
@@ -52,6 +52,7 @@ class AddResourceMsg:
watch_interval: float = 0
skip_watch_management: bool = True
defer_target_resolution: bool = False
+ cleanup_empty_target_on_failure: bool = False
understanding_response_id: Optional[str] = None
understanding_file_id: Optional[str] = None
processing_mode: ProcessingMode = DEFAULT_PROCESSING_MODE
@@ -185,6 +186,9 @@ class AddResourceMsg:
watch_interval=float(data.get("watch_interval", 0) or 0),
skip_watch_management=bool(data.get("skip_watch_management", True)),
defer_target_resolution=bool(data.get("defer_target_resolution", False)),
+ cleanup_empty_target_on_failure=bool(
+ data.get("cleanup_empty_target_on_failure", False)
+ ),
understanding_response_id=(
data.get("understanding_response_id")
if isinstance(data.get("understanding_response_id"), str)
diff --git a/openviking/storage/queuefs/add_resource_processor.py b/openviking/storage/queuefs/add_resource_processor.py
index c2a2ea4aa..0312cb9b4 100644
--- a/openviking/storage/queuefs/add_resource_processor.py
+++ b/openviking/storage/queuefs/add_resource_processor.py
@@ -76,6 +76,12 @@ class AddResourceProcessor(DequeueHandlerBase):
if msg.lock_handoff is not None:
try:
lock = await self._viking_fs._async_agfs.pathlock_adopt(msg.lock_handoff)
+ if msg.cleanup_empty_target_on_failure:
+ await self._resource_service._cleanup_reserved_target_if_empty(
+ root_uri=msg.root_uri,
+ ctx=ctx,
+ resource_lock=lock,
+ )
await self._viking_fs._async_agfs.pathlock_release(lock)
except Exception as exc:
logger.warning("[AddResource] Failed to release cancelled lock handoff: %s", exc)
@@ -296,6 +302,7 @@ class AddResourceProcessor(DequeueHandlerBase):
RequestContext(
user=UserIdentifier(msg.account_id, msg.user_id),
role=Role(msg.role),
+ group_ids=tuple(msg.group_ids),
actor_peer_id=msg.actor_peer_id,
bypass_acl=msg.bypass_acl,
),
diff --git a/openviking/utils/resource_processor.py b/openviking/utils/resource_processor.py
index b031020d0..34657d2da 100644
--- a/openviking/utils/resource_processor.py
+++ b/openviking/utils/resource_processor.py
@@ -104,6 +104,42 @@ class ResourceProcessor:
)
return self._media_processor
+ @staticmethod
+ def _empty_directory_error(meta: Dict[str, Any]) -> str:
+ """Build a bounded error message for a directory with no successful files."""
+ failed_files = meta.get("failed_files")
+ failures = failed_files if isinstance(failed_files, list) else []
+ try:
+ total_processable = int(meta.get("total_processable", 0) or 0)
+ except (TypeError, ValueError):
+ total_processable = 0
+
+ if total_processable > 0:
+ message = (
+ "Directory import produced no content: "
+ f"all {total_processable} processable file(s) failed"
+ )
+ else:
+ message = "Directory import produced no content: no processable files were selected"
+
+ details: List[str] = []
+ for item in failures[:5]:
+ if not isinstance(item, dict):
+ continue
+ path = str(item.get("path") or "<unknown>")
+ reason = str(item.get("error") or item.get("reason") or "failed")
+ remote_ids = [
+ f"{key}={item[key]}" for key in ("file_id", "response_id") if item.get(key)
+ ]
+ if remote_ids:
+ path = f"{path} ({', '.join(remote_ids)})"
+ details.append(f"{path}: {reason[:120]}")
+ if details:
+ message += "; failed files: " + "; ".join(details)
+ if len(failures) > len(details):
+ message += f"; ... {len(failures) - len(details)} more"
+ return message
+
async def prepare_durable_source(
self,
path: str,
@@ -115,9 +151,8 @@ class ResourceProcessor:
) -> Optional["LocalResource"]:
"""Freeze a source when durable routing cannot safely defer access."""
media_processor = self._get_media_processor()
- if (
- not snapshot_required
- and not media_processor.durable_route_requires_preparation(path, **kwargs)
+ if not snapshot_required and not media_processor.durable_route_requires_preparation(
+ path, **kwargs
):
return None
with get_viking_fs().bind_request_context(ctx):
@@ -249,6 +284,30 @@ class ResourceProcessor:
stage_status = "error"
return result
+ parse_meta = parse_result.meta if isinstance(parse_result.meta, dict) else {}
+ is_directory_aggregate = all(
+ key in parse_meta
+ for key in (
+ "file_count",
+ "total_processable",
+ "processed_files",
+ "failed_files",
+ )
+ )
+ if is_directory_aggregate and parse_meta.get("file_count") == 0:
+ result["status"] = "error"
+ result["errors"].append(self._empty_directory_error(parse_meta))
+ try:
+ await viking_fs.delete_temp(parse_result.temp_dir_path, ctx=ctx)
+ except Exception as exc:
+ logger.warning(
+ "[ResourceProcessor] Failed to clean empty directory temp %s: %s",
+ parse_result.temp_dir_path,
+ exc,
+ )
+ stage_status = "error"
+ return result
+
if parse_result.warnings and kwargs.get("strict", False):
result.setdefault("warnings", []).extend(parse_result.warnings)
@@ -263,7 +322,11 @@ class ResourceProcessor:
raise
except Exception as e:
result["status"] = "error"
- result["errors"].append(f"Parse error: {e}")
+ error_message = f"Parse error: {e}"
+ error_meta = getattr(e, "meta", {})
+ if isinstance(error_meta, dict) and error_meta.get("response_id"):
+ error_message += f" (response_id={error_meta['response_id']})"
+ result["errors"].append(error_message)
logger.error(f"[ResourceProcessor] Parse error: {e}")
telemetry.set_error("resource_processor.parse", "PROCESSING_ERROR", str(e))
import traceback
@@ -596,7 +659,9 @@ class ResourceProcessor:
elif build_index:
if root_is_file:
await self._vectorize_resource_file(
- root_uri, ctx=ctx, ingest_options=ingest_options,
+ root_uri,
+ ctx=ctx,
+ ingest_options=ingest_options,
creator_acl_grant=(
CreatorAclGrant.DIRECT if not target_preexisting else None
),
@@ -620,10 +685,10 @@ class ResourceProcessor:
return result
if root_is_file:
await self._vectorize_resource_file(
- root_uri, ctx=ctx, ingest_options=ingest_options,
- creator_acl_grant=(
- CreatorAclGrant.DIRECT if not target_preexisting else None
- ),
+ root_uri,
+ ctx=ctx,
+ ingest_options=ingest_options,
+ creator_acl_grant=(CreatorAclGrant.DIRECT if not target_preexisting else None),
)
else:
await self._vectorize_resource_files(
diff --git a/openviking/utils/zip_safe.py b/openviking/utils/zip_safe.py
index 451bd3aee..60ca28615 100644
--- a/openviking/utils/zip_safe.py
+++ b/openviking/utils/zip_safe.py
@@ -24,14 +24,19 @@ def _contains_cjk(text: str) -> bool:
def _contains_common_mojibake(text: str) -> bool:
return any(
- "\u0370" <= ch <= "\u03ff" or "\u2200" <= ch <= "\u22ff" or "\u2500" <= ch <= "\u257f"
+ # CP437 decodes UTF-8 lead byte 0xE6 as U+00B5. That byte covers
+ # a large part of the basic CJK block whose mojibake otherwise has
+ # no Greek, mathematical, or box-drawing characters.
+ ch == "\u00b5"
+ or "\u0370" <= ch <= "\u03ff"
+ or "\u2200" <= ch <= "\u22ff"
+ or "\u2500" <= ch <= "\u257f"
for ch in text
)
def normalize_zip_filenames(zipf: zipfile.ZipFile) -> None:
"""Repair UTF-8 member names when archives forgot to set the UTF-8 flag."""
- repaired_any = False
for member in zipf.infolist():
if member.flag_bits & _UTF8_FLAG:
continue
@@ -51,12 +56,10 @@ def normalize_zip_filenames(zipf: zipfile.ZipFile) -> None:
if not _contains_common_mojibake(member.filename):
continue
+ # Keep orig_filename unchanged. ZipFile.open() compares the local-header
+ # name decoded as CP437 with this value; changing it would make repaired
+ # entries unreadable even though their output path is now correct.
member.filename = repaired_name
- member.orig_filename = repaired_name
- repaired_any = True
-
- if repaired_any:
- zipf.metadata_encoding = "utf-8"
def _safe_zip_member_path(filename: str) -> Path:
diff --git a/openviking_cli/utils/config/parser_config.py b/openviking_cli/utils/config/parser_config.py
index 31520326f..2423637dc 100644
--- a/openviking_cli/utils/config/parser_config.py
+++ b/openviking_cli/utils/config/parser_config.py
@@ -601,9 +601,34 @@ class DirectoryConfig(ParserConfig):
adding directory resources. When True (default), files maintain their
relative path hierarchy. When False, all files are flattened to a
single level under the resource root.
+ max_files: Maximum number of selected files admitted by one Understanding
+ directory import.
+ max_depth: Maximum nested directory depth below an Understanding directory
+ import root.
+ max_concurrent: Maximum concurrent Understanding jobs shared by all
+ directory imports in one service event loop.
"""
preserve_structure: bool = True
+ max_files: int = 1000
+ max_depth: int = 10
+ max_concurrent: int = 4
+
+ def validate(self) -> None:
+ """Validate directory resource and concurrency limits."""
+ super().validate()
+
+ for name in (
+ "max_files",
+ "max_depth",
+ "max_concurrent",
+ ):
+ value = getattr(self, name)
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
+ raise ValueError(f"{name} must be a positive integer")
+
+ def __post_init__(self) -> None:
+ self.validate()
@dataclass
diff --git a/tests/misc/test_resource_processor_mv.py b/tests/misc/test_resource_processor_mv.py
index 0cfc0cceb..ea710786d 100644
--- a/tests/misc/test_resource_processor_mv.py
+++ b/tests/misc/test_resource_processor_mv.py
@@ -1,3 +1,4 @@
+import json
import os
import sys
from types import SimpleNamespace
@@ -114,6 +115,139 @@ def _patch_viking_fs(monkeypatch, fake_fs):
monkeypatch.setattr("openviking.parse.image_rewrite.get_viking_fs", lambda: fake_fs)
+async def test_resource_processor_rejects_directory_when_every_file_failed(monkeypatch):
+ from openviking.server.responses import response_from_result
+ from openviking.utils.resource_processor import ResourceProcessor
+
+ fake_fs = _FakeVikingFS()
+ monkeypatch.setattr(
+ "openviking.utils.resource_processor.get_current_telemetry",
+ lambda: _DummyTelemetry(),
+ )
+ _patch_viking_fs(monkeypatch, fake_fs)
+
+ failed_files = [
+ {
+ "path": "native.pdf",
+ "parser": "PDFParser",
+ "error": "native parser rejected file",
+ },
+ {
+ "path": "remote.pdf",
+ "parser": "UnderstandingAPI",
+ "file_id": "file-1",
+ "response_id": "response-1",
+ "error": "remote parser rejected file",
+ },
+ ]
+ rp = ResourceProcessor(vikingdb=_DummyVikingDB(), media_storage=None)
+ rp._get_media_processor = MagicMock()
+ rp._get_media_processor.return_value.process = AsyncMock(
+ return_value=SimpleNamespace(
+ temp_dir_path="viking://temp/empty-directory",
+ source_path="directory.zip",
+ # Local directories arrive through temp-upload as ZIP files. ZipParser
+ # preserves DirectoryParser's aggregate metadata while changing this
+ # outer format marker to "zip".
+ source_format="zip",
+ meta={
+ "file_count": 0,
+ "total_processable": 2,
+ "processed_files": [],
+ "failed_files": failed_files,
+ },
+ warnings=[],
+ )
+ )
+ rp.tree_builder.finalize_from_temp = AsyncMock()
+
+ result = await rp.process_resource(path="directory.zip", ctx=object(), build_index=True)
+
+ assert result["status"] == "error"
+ assert result["meta"]["failed_files"] == failed_files
+ assert "all 2 processable file(s) failed" in result["errors"][0]
+ assert "native.pdf: native parser rejected file" in result["errors"][0]
+ assert (
+ "remote.pdf (file_id=file-1, response_id=response-1): remote parser rejected file"
+ in result["errors"][0]
+ )
+ response = response_from_result(result)
+ assert response.status_code == 500
+ assert json.loads(response.body)["error"]["code"] == "PROCESSING_ERROR"
+ assert fake_fs.delete_temp_calls == [("viking://temp/empty-directory", None)]
+ assert fake_fs.persist_calls == []
+ rp.tree_builder.finalize_from_temp.assert_not_awaited()
+
+
[email protected]("length", [119, 120, 121, 240])
+def test_empty_directory_error_keeps_120_character_limit(length):
+ from openviking.utils.resource_processor import ResourceProcessor
+
+ reason = "错误原因" * (length // 4) + "错" * (length % 4)
+ meta = {
+ "total_processable": 1,
+ "failed_files": [
+ {
+ "path": "空白.md",
+ "error": reason,
+ "file_id": "file-1",
+ "response_id": "response-1",
+ }
+ ],
+ }
+ message = ResourceProcessor._empty_directory_error(meta)
+ assert message.endswith(
+ f"failed files: 空白.md (file_id=file-1, response_id=response-1): {reason[:120]}"
+ )
+ assert message.count("response_id=response-1") == 1
+
+
+ "meta",
+ [None, {}, {"file_id": "file-1"}, {"response_id": "response-1"}],
+ ids=["native", "no_ids", "file_id_only", "response_id"],
+)
+ "reason", ["文件解析任务失败:empty parse result", "错误原因" * 50], ids=["short", "long"]
+)
+async def test_resource_processor_preserves_single_file_reason_and_response_id(
+ monkeypatch, meta, reason
+):
+ from openviking.parse.understanding_api import UnderstandingAPIError
+ from openviking.server.responses import response_from_result
+ from openviking.utils.resource_processor import ResourceProcessor
+
+ fake_fs = _FakeVikingFS()
+ monkeypatch.setattr(
+ "openviking.utils.resource_processor.get_current_telemetry",
+ lambda: _DummyTelemetry(),
+ )
+ _patch_viking_fs(monkeypatch, fake_fs)
+ error = RuntimeError(reason) if meta is None else UnderstandingAPIError(reason, meta)
+ rp = ResourceProcessor(vikingdb=_DummyVikingDB(), media_storage=None)
+ rp._get_media_processor = MagicMock()
+ rp._get_media_processor.return_value.process = AsyncMock(side_effect=error)
+ rp.tree_builder.finalize_from_temp = AsyncMock()
+
+ result = await rp.process_resource(path="report.pdf", ctx=object(), build_index=False)
+
+ expected = f"Parse error: {reason}"
+ if meta and meta.get("response_id"):
+ expected += " (response_id=response-1)"
+ assert result["status"] == "error"
+ assert result["errors"] == [expected]
+ response = response_from_result(result)
+ assert response.status_code == 500
+ assert json.loads(response.body)["error"] == {
+ "code": "PROCESSING_ERROR",
+ "message": expected,
+ }
+ assert fake_fs.persist_calls == []
+ rp.tree_builder.finalize_from_temp.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_resource_processor_first_add_summarizes_from_committed_uri(monkeypatch):
from openviking.utils.resource_processor import ResourceProcessor
@@ -217,13 +351,9 @@ async def test_resource_processor_allows_flat_root_only_for_single_no_split_sour
assert result["status"] == "success"
assert result["root_uri"] == root_uri
- assert fake_fs._async_agfs.exact_attempts == [
- ("/mock/resources/神雕_副本.md", 0.0)
- ]
+ assert fake_fs._async_agfs.exact_attempts == [("/mock/resources/神雕_副本.md", 0.0)]
assert fake_fs._async_agfs.tree_attempts == []
- assert rp.tree_builder.finalize_from_temp.await_args.kwargs[
- "flatten_single_file"
- ] is True
+ assert rp.tree_builder.finalize_from_temp.await_args.kwargs["flatten_single_file"] is True
@pytest.mark.asyncio
@@ -257,9 +387,7 @@ async def test_resource_processor_keeps_wrapper_for_directory_to_no_split(monkey
_root_is_file=False,
)
)
- rp._summarizer = SimpleNamespace(
- summarize=AsyncMock(return_value={"status": "success"})
- )
+ rp._summarizer = SimpleNamespace(summarize=AsyncMock(return_value={"status": "success"}))
result = await rp.process_resource(
path="神雕.md",
@@ -271,9 +399,7 @@ async def test_resource_processor_keeps_wrapper_for_directory_to_no_split(monkey
)
assert result["root_uri"] == "viking://resources/0803_shendiao_01"
- assert rp.tree_builder.finalize_from_temp.await_args.kwargs[
- "flatten_single_file"
- ] is False
+ assert rp.tree_builder.finalize_from_temp.await_args.kwargs["flatten_single_file"] is False
@pytest.mark.asyncio
diff --git a/tests/misc/test_zip_safe.py b/tests/misc/test_zip_safe.py
index f126ec879..cd273196a 100644
--- a/tests/misc/test_zip_safe.py
+++ b/tests/misc/test_zip_safe.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import io
import stat
+import struct
import zipfile
from pathlib import Path
@@ -39,6 +40,28 @@ def _make_zip_with_raw_info(entries: list[tuple[zipfile.ZipInfo, str]]) -> bytes
return buf.getvalue()
+def _clear_utf8_filename_flags(data: bytes) -> bytes:
+ """Clear bit 11 in every local and central-directory file header."""
+ patched = bytearray(data)
+ header_specs = (
+ (b"PK\x03\x04", 6),
+ (b"PK\x01\x02", 8),
+ )
+ for signature, flag_offset in header_specs:
+ cursor = 0
+ matched = 0
+ while True:
+ header_offset = data.find(signature, cursor)
+ if header_offset < 0:
+ break
+ flags = struct.unpack_from("<H", patched, header_offset + flag_offset)[0]
+ struct.pack_into("<H", patched, header_offset + flag_offset, flags & ~0x800)
+ matched += 1
+ cursor = header_offset + len(signature)
+ assert matched > 0, f"ZIP header not found: {signature!r}"
+ return bytes(patched)
+
+
def _assert_no_escape(tmp_path: Path, dest_dir: Path) -> None:
"""Assert no extracted files escaped dest_dir."""
for f in tmp_path.rglob("*"):
@@ -85,7 +108,13 @@ class TestContainsCommonMojibake:
"""Verify mojibake pattern detection."""
def test_detects_greek_chars(self) -> None:
- assert _contains_common_mojibake("αβ") is True # Greek alpha, beta
+ mojibake = "αβ".encode("utf-8").decode("cp437")
+ assert _contains_common_mojibake(mojibake) is True
+
+ def test_detects_cp437_micro_sign_from_cjk_utf8(self) -> None:
+ mojibake = "怀".encode("utf-8").decode("cp437")
+ assert mojibake == "怀"
+ assert _contains_common_mojibake(mojibake) is True
def test_detects_math_operators(self) -> None:
assert _contains_common_mojibake("\u2200x") is True # for-all
@@ -127,48 +156,41 @@ class TestNormalizeZipFilenames:
normalize_zip_filenames(zf)
assert zf.infolist()[0].filename == "readme.txt"
- def test_repairs_cjk_filename_from_cp437_mojibake(self) -> None:
+ @pytest.mark.parametrize("cjk_name", ["测试文件.txt", "怀.txt"])
+ def test_repairs_cjk_filename_from_cp437_mojibake(
+ self,
+ cjk_name: str,
+ tmp_path: Path,
+ ) -> None:
"""Simulate a CJK filename stored without UTF-8 flag.
The zip module reads it via cp437 producing mojibake.
normalize_zip_filenames should re-decode from cp437 -> UTF-8.
"""
- # Create a zip with raw bytes: write CJK UTF-8 bytes as the filename
- # but do NOT set the UTF-8 flag, so Python's zipfile reads it as cp437.
- cjk_name = "测试文件.txt"
- utf8_bytes = cjk_name.encode("utf-8")
-
+ # Python correctly sets bit 11 for non-ASCII names. Patch both copies
+ # of the flag to reproduce an archive that stored UTF-8 bytes but
+ # forgot to declare their encoding.
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
- info = zipfile.ZipInfo(cjk_name)
- info.flag_bits = 0 # no UTF-8 flag
- zf.writestr(info, "content")
- # Manually patch the raw zip to remove UTF-8 flag
- # (Python's ZipFile may set it automatically for non-ASCII)
- # The flag_bits field is at offset 6 in the local file header
- # This is complex; instead test the logic paths individually
- # by directly calling with a pre-mangled ZipInfo
- buf2 = io.BytesIO()
- with zipfile.ZipFile(buf2, "w") as zf:
- # Encode filename as cp437 representation of the UTF-8 bytes
- try:
- cp437_name = utf8_bytes.decode("cp437")
- except UnicodeDecodeError:
- pytest.skip("Cannot represent CJK UTF-8 bytes in cp437")
- info = zipfile.ZipInfo(cp437_name)
- info.flag_bits = 0
- zf.writestr(info, "content")
- buf2.seek(0)
- with zipfile.ZipFile(buf2, "r") as zf:
+ zf.writestr(cjk_name, "content")
+ malformed_zip = _clear_utf8_filename_flags(buf.getvalue())
+ cp437_name = cjk_name.encode("utf-8").decode("cp437")
+
+ with zipfile.ZipFile(io.BytesIO(malformed_zip), "r") as zf:
member = zf.infolist()[0]
- # Before normalization, filename should be the mojibake
+ assert member.flag_bits & 0x800 == 0
assert member.filename == cp437_name
normalize_zip_filenames(zf)
- # After normalization, the name should be repaired to CJK
repaired = zf.infolist()[0]
assert repaired.filename == cjk_name, (
f"Expected filename to be repaired to {cjk_name!r}, got {repaired.filename!r}"
)
+ assert zf.read(repaired) == b"content"
+
+ extract_dir = tmp_path / "repaired"
+ with zipfile.ZipFile(io.BytesIO(malformed_zip), "r") as zf:
+ safe_extract_zip(zf, extract_dir)
+ assert (extract_dir / cjk_name).read_bytes() == b"content"
# ── safe_extract_zip ─────────────────────────────────────────────────────────
diff --git a/tests/parse/test_directory_scan.py b/tests/parse/test_directory_scan.py
index 039b6a2eb..acde78f91 100644
--- a/tests/parse/test_directory_scan.py
+++ b/tests/parse/test_directory_scan.py
@@ -13,7 +13,7 @@ from openviking.parse.directory_scan import (
scan_directory,
)
from openviking.parse.registry import ParserRegistry
-from openviking_cli.exceptions import UnsupportedDirectoryFilesError
+from openviking_cli.exceptions import InvalidArgumentError, UnsupportedDirectoryFilesError
# ---------------------------------------------------------------------------
# Fixtures
@@ -295,6 +295,58 @@ class TestScanDirectoryEdgeCases:
assert cf.classification == CLASS_PROCESSABLE
+class TestDirectorySafetyLimits:
+ """Directory scans must fail before processing unbounded input trees."""
+
+ def test_rejects_too_many_files(self, tmp_path: Path, registry: ParserRegistry) -> None:
+ for index in range(3):
+ (tmp_path / f"{index}.txt").write_text("x", encoding="utf-8")
+
+ with pytest.raises(InvalidArgumentError, match="file count exceeds"):
+ scan_directory(tmp_path, registry=registry, max_files=2)
+
+ def test_additional_parser_marks_file_processable(
+ self, tmp_path: Path, registry: ParserRegistry
+ ) -> None:
+ (tmp_path / "large.external").write_bytes(b"12345")
+
+ result = scan_directory(
+ tmp_path,
+ registry=registry,
+ strict=True,
+ additional_can_process=lambda path: path.suffix == ".external",
+ )
+
+ assert [item.rel_path for item in result.processable] == ["large.external"]
+
+ def test_rejects_excessive_depth(self, tmp_path: Path, registry: ParserRegistry) -> None:
+ nested = tmp_path / "level-1" / "level-2"
+ nested.mkdir(parents=True)
+ (nested / "deep.txt").write_text("deep", encoding="utf-8")
+
+ with pytest.raises(InvalidArgumentError, match="depth exceeds") as exc_info:
+ scan_directory(tmp_path, registry=registry, max_depth=1)
+
+ assert "path=level-1/level-2" in str(exc_info.value)
+ assert str(tmp_path) not in str(exc_info.value)
+
+ @pytest.mark.parametrize(
+ "limit_name",
+ [
+ "max_files",
+ "max_depth",
+ ],
+ )
+ def test_rejects_non_positive_limit(
+ self,
+ tmp_path: Path,
+ registry: ParserRegistry,
+ limit_name: str,
+ ) -> None:
+ with pytest.raises(InvalidArgumentError, match=limit_name):
+ scan_directory(tmp_path, registry=registry, **{limit_name: 0})
+
+
# ---------------------------------------------------------------------------
# Include / exclude filters
# ---------------------------------------------------------------------------
diff --git a/tests/parse/test_directory_understanding_routing.py b/tests/parse/test_directory_understanding_routing.py
new file mode 100644
index 000000000..50e59ba8e
--- /dev/null
+++ b/tests/parse/test_directory_understanding_routing.py
@@ -0,0 +1,916 @@
+import asyncio
+import zipfile
+from contextlib import nullcontext
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import httpx
+import pytest
+
+from openviking.parse.accessors.base import LocalResource, SourceType
+from openviking.parse.accessors.web_crawler.models import CrawledPage, CrawlResult
+from openviking.parse.base import NodeType, ResourceNode, create_parse_result
+from openviking.parse.parser_router import ParserRouter
+from openviking.parse.parsers.base_parser import BaseParser
+from openviking.parse.parsers.directory import DirectoryParser
+from openviking.parse.parsers.html import HTMLParser
+from openviking.parse.parsers.pdf import PDFParser
+from openviking.parse.understanding_api import UnderstandingAPI, UnderstandingAPIError
+from openviking.utils.media_processor import UnifiedResourceProcessor
+from openviking.utils.resource_processor import ResourceProcessor
+from openviking_cli.exceptions import InvalidArgumentError
+
+
+class _FakeVikingFS:
+ def __init__(self) -> None:
+ self._temp_counter = 0
+ self.files: dict[str, bytes] = {}
+
+ def create_temp_uri(self) -> str:
+ self._temp_counter += 1
+ return f"viking://temp/directory_route_{self._temp_counter}"
+
+ async def mkdir(self, _uri: str, exist_ok: bool = False) -> None:
+ _ = exist_ok
+
+ async def write(self, uri: str, data) -> str:
+ self.files[uri] = data.encode("utf-8") if isinstance(data, str) else data
+ return uri
+
+ async def write_file(self, uri: str, content) -> None:
+ self.files[uri] = content.encode("utf-8") if isinstance(content, str) else content
+
+ async def write_file_bytes(self, uri: str, content: bytes) -> None:
+ self.files[uri] = content
+
+
+def _configure_understanding(
+ monkeypatch,
+ extensions: list[str],
+ *,
+ enabled: bool = True,
+ max_concurrent: int = 4,
+ max_files: int = 1000,
+ max_depth: int = 10,
+ upload_simple_max_bytes: int = 512 * 1024 * 1024,
+ enable_resumable_upload: bool = False,
+) -> None:
+ config = SimpleNamespace(
+ parser_api=SimpleNamespace(
+ enable=enabled,
+ host="https://parser.example.com",
+ api_key="test-key",
+ enable_feishu_url=False,
+ extensions=extensions,
+ response_timeout_seconds=1800,
+ http_timeout_seconds=10.0,
+ upload_simple_max_bytes=upload_simple_max_bytes,
+ upload_part_size_bytes=8 * 1024 * 1024,
+ enable_resumable_upload=enable_resumable_upload,
+ ),
+ directory=SimpleNamespace(
+ preserve_structure=True,
+ max_files=max_files,
+ max_depth=max_depth,
+ max_concurrent=max_concurrent,
+ ),
+ )
+ monkeypatch.setattr(
+ "openviking_cli.utils.config.open_viking_config.get_openviking_config",
+ lambda: config,
+ )
+
+
+def _fake_understanding_parse(calls: list[Path]):
+ async def parse(_self, source, **_kwargs):
+ source_path = Path(source)
+ calls.append(source_path)
+ result = create_parse_result(
+ root=ResourceNode(type=NodeType.ROOT, title=source_path.stem),
+ source_path=str(source_path),
+ source_format=source_path.suffix.lstrip("."),
+ parser_name="UnderstandingAPI",
+ )
+ result.temp_dir_path = f"viking://temp/understanding_{len(calls)}"
+ return result
+
+ return parse
+
+
+async def test_materialized_html_webpage_routes_to_understanding(monkeypatch, tmp_path: Path):
+ _configure_understanding(monkeypatch, ["html"])
+ site_dir = tmp_path / "example.com"
+ nested_dir = site_dir / "articles"
+ nested_dir.mkdir(parents=True)
+ (site_dir / "index.html").write_text("<html><h1>Home</h1></html>", encoding="utf-8")
+ (nested_dir / "detail.html").write_text(
+ "<html><h1>Detail</h1></html>",
+ encoding="utf-8",
+ )
+ resource = LocalResource(
+ path=site_dir,
+ source_type=SourceType.HTTP,
+ original_source="https://example.com/",
+ meta={"web_import": True, "original_filename": "example.com"},
+ is_temporary=False,
+ )
+ calls: list[Path] = []
+ fake_fs = _FakeVikingFS()
+
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=fake_fs),
+ patch.object(UnderstandingAPI, "parse", new=_fake_understanding_parse(calls)),
+ patch.object(DirectoryParser, "_merge_temp", new=AsyncMock(return_value=True)),
+ ):
+ result = await UnifiedResourceProcessor(vlm_processor=object()).process(
+ "https://example.com/",
+ prepared_resource=resource,
+ strict=True,
+ )
+
+ assert {path.relative_to(site_dir).as_posix() for path in calls} == {
+ "articles/detail.html",
+ "index.html",
+ }
+ assert result.meta["file_count"] == 2
+ assert {item["parser"] for item in result.meta["processed_files"]} == {"UnderstandingAPI"}
+
+
+ "url,depth,enabled,extensions,expected_parser",
+ [
+ pytest.param(
+ "https://example.com/article", 0, True, ["html"], "UnderstandingAPI", id="extensionless"
+ ),
+ pytest.param(
+ "https://example.com/page.html", 0, True, ["html"], "UnderstandingAPI", id="html"
+ ),
+ pytest.param(
+ "https://example.com/page.htm?view=full#top",
+ 0,
+ True,
+ ["html"],
+ "UnderstandingAPI",
+ id="htm-query",
+ ),
+ pytest.param(
+ "https://example.com/", 1, True, ["html"], "UnderstandingAPI", id="multiple-pages"
+ ),
+ pytest.param(
+ "https://example.com/page.html", 0, False, ["html"], "HTMLParser", id="disabled"
+ ),
+ pytest.param(
+ "https://example.com/article",
+ 0,
+ True,
+ ["pdf"],
+ "HTMLParser",
+ id="extension-not-enabled",
+ ),
+ ],
+)
+async def test_html_url_routes_materialized_pages(
+ monkeypatch, tmp_path: Path, url, depth, enabled, extensions, expected_parser
+):
+ _configure_understanding(monkeypatch, extensions, enabled=enabled)
+ pages = [CrawledPage(url=url, html="<html><h1>Home</h1><p>Home content</p></html>")]
+ if depth:
+ pages.append(
+ CrawledPage(
+ url="https://example.com/articles/detail",
+ depth=1,
+ html="<html><h1>Detail</h1><p>Detail content</p></html>",
+ )
+ )
+ crawler = MagicMock()
+ crawler.return_value.crawl = AsyncMock(
+ return_value=CrawlResult(pages=pages, total_crawled=len(pages))
+ )
+ monkeypatch.setattr("openviking.parse.accessors.web_importer.ScrapyWebCrawler", crawler)
+ monkeypatch.setattr(
+ "openviking.parse.accessors.web_importer.tempfile.mkdtemp",
+ lambda **_kwargs: str(tmp_path / "web"),
+ )
+ transport = httpx.MockTransport(
+ lambda _request: httpx.Response(
+ 200, headers={"content-type": "text/html; charset=utf-8"}, text=pages[0].html
+ )
+ )
+ client_type = httpx.AsyncClient
+ monkeypatch.setattr(
+ httpx, "AsyncClient", lambda **kwargs: client_type(transport=transport, **kwargs)
+ )
+ parsed_files = {}
+
+ async def parse_html(parser, source, **_kwargs):
+ path = Path(source)
+ parsed_files[path.name] = (type(parser).__name__, path.read_text(encoding="utf-8"))
+ result = create_parse_result(
+ root=ResourceNode(type=NodeType.ROOT, title=path.stem),
+ parser_name=type(parser).__name__,
+ )
+ result.temp_dir_path = f"viking://temp/{path.stem}"
+ return result
+
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=_FakeVikingFS()),
+ patch.object(UnderstandingAPI, "parse", new=parse_html),
+ patch.object(HTMLParser, "parse", new=parse_html),
+ patch.object(DirectoryParser, "_merge_temp", new=AsyncMock(return_value=True)),
+ ):
+ result = await UnifiedResourceProcessor(vlm_processor=object()).process(
+ url, depth=depth, strict=True
+ )
+
+ expected = {"Home.html": (expected_parser, pages[0].html)}
+ if depth:
+ expected["Detail.html"] = (expected_parser, pages[1].html)
+ assert parsed_files == expected
+ assert result.meta["failed_files"] == []
+ assert result.meta["file_count"] == len(pages)
+ assert {item["parser"] for item in result.meta["processed_files"]} == {expected_parser}
+ crawler.return_value.crawl.assert_awaited_once_with(url)
+ assert crawler.call_args.args[0].depth == depth
+
+
+async def test_disabled_understanding_uses_native_directory_parser(monkeypatch, tmp_path: Path):
+ _configure_understanding(monkeypatch, ["pdf"], enabled=False)
+ pdf_path = tmp_path / "native.pdf"
+ pdf_path.write_bytes(b"%PDF-1.7")
+ native_parse = AsyncMock(return_value={"ok": True, "meta": {}, "error": None})
+ understanding_parse = AsyncMock()
+
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=_FakeVikingFS()),
+ patch.object(DirectoryParser, "_process_single_file", new=native_parse),
+ patch.object(ParserRouter, "parse", new=understanding_parse),
+ ):
+ result = await DirectoryParser().parse(str(tmp_path), strict=True)
+
+ understanding_parse.assert_not_awaited()
+ native_parse.assert_awaited_once()
+ assert type(native_parse.await_args.args[1]).__name__ == "PDFParser"
+ assert result.meta["processed_files"][0]["parser"] == "PDFParser"
+
+
+ ("enabled", "extensions"),
+ [(False, ["pdf"]), (True, [])],
+)
+async def test_directory_limits_require_understanding_routing(
+ monkeypatch,
+ tmp_path: Path,
+ enabled: bool,
+ extensions: list[str],
+):
+ _configure_understanding(
+ monkeypatch,
+ extensions,
+ enabled=enabled,
+ max_files=1,
+ max_depth=1,
+ )
+ nested = tmp_path / "level-1" / "level-2"
+ nested.mkdir(parents=True)
+ (tmp_path / "first.pdf").write_bytes(b"%PDF-1.7")
+ (nested / "second.pdf").write_bytes(b"%PDF-1.7")
+ native_parse = AsyncMock(return_value={"ok": True, "meta": {}, "error": None})
+
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=_FakeVikingFS()),
+ patch.object(DirectoryParser, "_process_single_file", new=native_parse),
+ ):
+ result = await DirectoryParser().parse(str(tmp_path), strict=True)
+
+ assert native_parse.await_count == 2
+ assert result.meta["file_count"] == 2
+ assert result.meta["failed_files"] == []
+
+
+async def test_directory_recursively_routes_understanding_files(
+ monkeypatch,
+ tmp_path: Path,
+):
+ _configure_understanding(
+ monkeypatch,
+ ["pdf", "external", "png"],
+ upload_simple_max_bytes=16,
+ )
+ nested_dir = tmp_path / "level-1" / "level-2"
+ nested_dir.mkdir(parents=True)
+ (nested_dir / "paper.pdf").write_bytes(b"%PDF-1.7")
+ (nested_dir / "custom.external").write_bytes(b"external-only")
+ (nested_dir / "image.png").write_bytes(b"\x89PNG\r\n\x1a\n")
+ calls: list[Path] = []
+ fake_fs = _FakeVikingFS()
+ direct_upload = AsyncMock(return_value=True)
+
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=fake_fs),
+ patch.object(ParserRouter, "parse", new=_fake_understanding_parse(calls)),
+ patch.object(DirectoryParser, "_merge_temp", new=AsyncMock(return_value=True)),
+ patch.object(DirectoryParser, "_upload_file_directly", new=direct_upload),
+ ):
+ result = await DirectoryParser().parse(str(tmp_path), strict=True)
+
+ assert {path.relative_to(tmp_path).as_posix() for path in calls} == {
+ "level-1/level-2/custom.external",
+ "level-1/level-2/image.png",
+ "level-1/level-2/paper.pdf",
+ }
+ direct_upload.assert_not_awaited()
+ assert result.meta["file_count"] == 3
+ assert result.meta["unsupported_files"] == []
+ assert {item["parser"] for item in result.meta["processed_files"]} == {"UnderstandingAPI"}
+
+
+async def test_directory_does_not_preflight_understanding_file_size(
+ monkeypatch,
+ tmp_path: Path,
+):
+ _configure_understanding(
+ monkeypatch,
+ ["pdf"],
+ upload_simple_max_bytes=8,
+ enable_resumable_upload=False,
+ )
+ large_pdf = tmp_path / "large.pdf"
+ small_pdf = tmp_path / "small.pdf"
+ large_pdf.write_bytes(b"%PDF-1.7+")
+ small_pdf.write_bytes(b"%PDF-1.7")
+ calls: list[Path] = []
+
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=_FakeVikingFS()),
+ patch.object(ParserRouter, "parse", new=_fake_understanding_parse(calls)),
+ patch.object(DirectoryParser, "_merge_temp", new=AsyncMock(return_value=True)),
+ ):
+ result = await DirectoryParser().parse(str(tmp_path), strict=True)
+
+ assert calls == [large_pdf, small_pdf]
+ assert result.meta["file_count"] == 2
+ assert result.meta["skipped_files"] == []
+
+
+async def test_native_parser_failures_include_each_file_error(
+ monkeypatch,
+ tmp_path: Path,
+):
+ _configure_understanding(monkeypatch, [], enabled=False)
+ for name in ("first.pdf", "second.pdf"):
+ (tmp_path / name).write_bytes(b"%PDF-1.7")
+
+ class _RejectingParser:
+ async def parse(self, source, **_kwargs):
+ raise ValueError(f"parser rejected {Path(source).name}")
+
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=_FakeVikingFS()),
+ patch.object(DirectoryParser, "_assign_parser", return_value=_RejectingParser()),
+ ):
+ result = await DirectoryParser().parse(str(tmp_path), strict=True)
+
+ assert result.meta["file_count"] == 0
+ assert result.meta["failed_files"] == [
+ {
+ "path": "first.pdf",
+ "parser": "_RejectingParser",
+ "error": "parser rejected first.pdf",
+ },
+ {
+ "path": "second.pdf",
+ "parser": "_RejectingParser",
+ "error": "parser rejected second.pdf",
+ },
+ ]
+
+
[email protected]("use_understanding", [False, True])
[email protected]("keep_good_file", [False, True])
+ "output", ["missing", "empty-root", "empty", "hidden", "sidecar", "content", "media"]
+)
+async def test_directory_counts_only_parser_results_with_content(
+ monkeypatch, tmp_path: Path, use_understanding: bool, keep_good_file: bool, output: str
+):
+ _configure_understanding(monkeypatch, ["pdf"], enabled=use_understanding)
+ (tmp_path / "paper.pdf").write_bytes(b"%PDF-1.7")
+ if keep_good_file:
+ (tmp_path / "keep.py").write_text("print('keep')", encoding="utf-8")
+
+ sub_result = create_parse_result(
+ root=ResourceNode(type=NodeType.ROOT),
+ warnings=["parser warning"],
+ meta={"file_id": "file-1", "response_id": "response-1"},
+ )
+ temp_uri = "viking://temp/parsed-file"
+ wrapper_uri = f"{temp_uri}/paper"
+ if output != "missing":
+ sub_result.temp_dir_path = temp_uri
+ payload_name = {
+ "hidden": ".ignored",
+ "sidecar": ".image_mappings.json",
+ "content": "paper.md",
+ "media": "image.png",
+ }.get(output)
+ listings = {
+ temp_uri: [] if output == "empty-root" else [{"name": "paper", "isDir": True}],
+ wrapper_uri: [{"name": payload_name, "isDir": False}] if payload_name else [],
+ }
+ fake_fs = _FakeVikingFS()
+ fake_fs.ls = AsyncMock(side_effect=lambda uri, **_kwargs: listings[uri])
+ fake_fs.mkdir = AsyncMock()
+ fake_fs.move_file = AsyncMock()
+ fake_fs.delete_temp = AsyncMock()
+ native_parser = SimpleNamespace(parse=AsyncMock(return_value=sub_result))
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=fake_fs),
+ patch.object(ParserRouter, "parse", new=AsyncMock(return_value=sub_result)),
+ patch.object(
+ DirectoryParser,
+ "_assign_parser",
+ side_effect=lambda cf, _registry: native_parser if cf.path.suffix == ".pdf" else None,
+ ),
+ ):
+ result = await DirectoryParser().parse(str(tmp_path))
+
+ has_content = output in {"content", "media"}
+ assert result.meta["file_count"] == int(keep_good_file) + int(has_content)
+ assert {item["path"] for item in result.meta["processed_files"]} == (
+ ({"keep.py"} if keep_good_file else set()) | ({"paper.pdf"} if has_content else set())
+ )
+ if has_content:
+ assert result.meta["failed_files"] == []
+ fake_fs.move_file.assert_awaited_once()
+ else:
+ failure = result.meta["failed_files"][0]
+ assert failure["path"] == "paper.pdf"
+ assert "no content generated" in failure["error"]
+ assert "parser warning" in failure["error"]
+ if use_understanding:
+ assert failure["file_id"] == "file-1"
+ assert failure["response_id"] == "response-1"
+ fake_fs.move_file.assert_not_awaited()
+ assert not any(call.args[0].endswith("/paper") for call in fake_fs.mkdir.await_args_list)
+ if output != "missing":
+ fake_fs.delete_temp.assert_awaited_once_with(temp_uri)
+ else:
+ fake_fs.delete_temp.assert_not_awaited()
+
+
+async def test_directory_reports_empty_parser_result_without_warnings(monkeypatch, tmp_path: Path):
+ _configure_understanding(monkeypatch, ["pdf"], enabled=False)
+ (tmp_path / "paper.pdf").write_bytes(b"%PDF-1.7")
+ parser = SimpleNamespace(
+ parse=AsyncMock(return_value=create_parse_result(root=ResourceNode(type=NodeType.ROOT)))
+ )
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=_FakeVikingFS()),
+ patch.object(DirectoryParser, "_assign_parser", return_value=parser),
+ ):
+ result = await DirectoryParser().parse(str(tmp_path))
+
+ assert result.meta["file_count"] == 0
+ assert result.meta["failed_files"][0]["error"] == "Parse failed: no content generated"
+
+
+async def test_directory_preserves_native_pdf_soft_failure(monkeypatch, tmp_path: Path):
+ _configure_understanding(monkeypatch, ["pdf"], enabled=False)
+ (tmp_path / "broken.pdf").write_bytes(b"%PDF-1.7")
+ fake_fs = _FakeVikingFS()
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=fake_fs),
+ patch.object(
+ PDFParser, "_convert_to_markdown", new=AsyncMock(side_effect=ValueError("invalid PDF"))
+ ),
+ ):
+ result = await DirectoryParser().parse(str(tmp_path))
+
+ assert result.meta["file_count"] == 0
+ assert result.meta["processed_files"] == []
+ assert result.meta["failed_files"] == [
+ {
+ "path": "broken.pdf",
+ "parser": "PDFParser",
+ "error": "Parse failed: no content generated; Failed to parse PDF: invalid PDF",
+ }
+ ]
+
+ fake_fs.bind_request_context = lambda _ctx: nullcontext()
+ fake_fs.delete_temp = AsyncMock()
+ fake_fs.persist_temp_tree = AsyncMock()
+ processor = ResourceProcessor(
+ vikingdb=SimpleNamespace(get_embedder=lambda: None), media_storage=None
+ )
+ processor._get_media_processor = lambda: SimpleNamespace(process=AsyncMock(return_value=result))
+ processor.tree_builder.finalize_from_temp = AsyncMock()
+ ctx = object()
+ with (
+ patch("openviking.utils.resource_processor.get_viking_fs", return_value=fake_fs),
+ patch(
+ "openviking.utils.resource_processor.get_current_telemetry", return_value=MagicMock()
+ ),
+ ):
+ processed = await processor.process_resource(path=str(tmp_path), ctx=ctx)
+
+ assert processed["status"] == "error"
+ assert "all 1 processable file(s) failed" in processed["errors"][0]
+ assert "broken.pdf" in processed["errors"][0]
+ assert "invalid PDF" in processed["errors"][0]
+ fake_fs.delete_temp.assert_awaited_once_with(result.temp_dir_path, ctx=ctx)
+ fake_fs.persist_temp_tree.assert_not_awaited()
+ processor.tree_builder.finalize_from_temp.assert_not_awaited()
+
+
+async def test_direct_upload_failure_includes_file_error(
+ monkeypatch,
+ tmp_path: Path,
+):
+ _configure_understanding(monkeypatch, [], enabled=False)
+ video = tmp_path / "video.mp4"
+ video.write_bytes(b"01234567")
+ fake_fs = _FakeVikingFS()
+ fake_fs.write_file = AsyncMock(side_effect=OSError("storage rejected video.mp4"))
+
+ with patch.object(BaseParser, "_get_viking_fs", return_value=fake_fs):
+ result = await DirectoryParser().parse(str(tmp_path), strict=True)
+
+ assert result.meta["file_count"] == 0
+ assert result.meta["failed_files"] == [
+ {
+ "path": "video.mp4",
+ "parser": "direct_upload",
+ "error": "storage rejected video.mp4",
+ }
+ ]
+
+
+async def test_understanding_directory_jobs_use_bounded_concurrency(monkeypatch, tmp_path: Path):
+ _configure_understanding(monkeypatch, ["pdf"], max_concurrent=2)
+ for name in ("a.pdf", "b.pdf", "c.pdf"):
+ (tmp_path / name).write_bytes(b"%PDF-1.7")
+
+ inflight = 0
+ max_seen = 0
+
+ async def parse(_self, source, **_kwargs):
+ nonlocal inflight, max_seen
+ inflight += 1
+ max_seen = max(max_seen, inflight)
+ await asyncio.sleep(0.01)
+ inflight -= 1
+ source_path = Path(source)
+ result = create_parse_result(
+ root=ResourceNode(type=NodeType.ROOT, title=source_path.stem),
+ source_path=str(source_path),
+ source_format="pdf",
+ parser_name="UnderstandingAPI",
+ )
+ result.temp_dir_path = f"viking://temp/{source_path.stem}"
+ return result
+
+ fake_fs = _FakeVikingFS()
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=fake_fs),
+ patch.object(ParserRouter, "parse", new=parse),
+ patch.object(DirectoryParser, "_merge_temp", new=AsyncMock(return_value=True)),
+ ):
+ result = await DirectoryParser().parse(str(tmp_path), strict=True)
+
+ assert max_seen == 2
+ assert [item["path"] for item in result.meta["processed_files"]] == [
+ "a.pdf",
+ "b.pdf",
+ "c.pdf",
+ ]
+
+
+async def test_understanding_directory_jobs_share_limit_across_directories(
+ monkeypatch,
+ tmp_path: Path,
+):
+ _configure_understanding(monkeypatch, ["pdf"], max_concurrent=4)
+ directories = [tmp_path / "first", tmp_path / "second"]
+ for directory in directories:
+ directory.mkdir()
+ for index in range(4):
+ (directory / f"{index}.pdf").write_bytes(b"%PDF-1.7")
+
+ inflight = 0
+ max_seen = 0
+ limit_reached = asyncio.Event()
+ release = asyncio.Event()
+
+ async def parse(_self, source, **_kwargs):
+ nonlocal inflight, max_seen
+ inflight += 1
+ max_seen = max(max_seen, inflight)
+ if inflight == 4:
+ limit_reached.set()
+ try:
+ await release.wait()
+ finally:
+ inflight -= 1
+
+ source_path = Path(source)
+ result = create_parse_result(
+ root=ResourceNode(type=NodeType.ROOT, title=source_path.stem),
+ source_path=str(source_path),
+ source_format="pdf",
+ parser_name="UnderstandingAPI",
+ )
+ result.temp_dir_path = f"viking://temp/{source_path.parent.name}_{source_path.stem}"
+ return result
+
+ fake_fs = _FakeVikingFS()
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=fake_fs),
+ patch.object(ParserRouter, "parse", new=parse),
+ patch.object(DirectoryParser, "_merge_temp", new=AsyncMock(return_value=True)),
+ ):
+ tasks = [
+ asyncio.create_task(DirectoryParser().parse(str(directory), strict=True))
+ for directory in directories
+ ]
+ try:
+ await asyncio.wait_for(limit_reached.wait(), timeout=1)
+ await asyncio.sleep(0.01)
+ assert max_seen == 4
+ finally:
+ release.set()
+ results = await asyncio.gather(*tasks)
+
+ assert sum(result.meta["file_count"] for result in results) == 8
+
+
+async def test_understanding_results_merge_in_source_order(monkeypatch, tmp_path: Path):
+ _configure_understanding(monkeypatch, ["pdf"], max_concurrent=3)
+ for name in ("a.pdf", "b.pdf", "c.pdf"):
+ (tmp_path / name).write_bytes(b"%PDF-1.7")
+
+ delays = {"a.pdf": 0.03, "b.pdf": 0.02, "c.pdf": 0.01}
+
+ async def parse(_self, source, **_kwargs):
+ source_path = Path(source)
+ await asyncio.sleep(delays[source_path.name])
+ result = create_parse_result(
+ root=ResourceNode(type=NodeType.ROOT, title=source_path.stem),
+ source_path=str(source_path),
+ source_format="pdf",
+ parser_name="UnderstandingAPI",
+ )
+ result.temp_dir_path = f"viking://temp/{source_path.stem}"
+ return result
+
+ merge_order: list[str] = []
+
+ async def merge(classified_file, *_args, **_kwargs):
+ merge_order.append(classified_file.rel_path)
+
+ fake_fs = _FakeVikingFS()
+ merge_mock = AsyncMock(side_effect=merge)
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=fake_fs),
+ patch.object(ParserRouter, "parse", new=parse),
+ patch.object(DirectoryParser, "_merge_parser_result", new=merge_mock),
+ ):
+ await DirectoryParser().parse(str(tmp_path), strict=True)
+
+ assert merge_order == ["a.pdf", "b.pdf", "c.pdf"]
+
+
+ ("parser_type", "extension", "content"),
+ [
+ (PDFParser, "pdf", b"%PDF-1.7"),
+ (HTMLParser, "html", b"<h1>Page</h1>"),
+ ],
+)
+async def test_no_split_directory_falls_back_to_native_parser(
+ monkeypatch,
+ tmp_path: Path,
+ parser_type,
+ extension,
+ content,
+):
+ _configure_understanding(monkeypatch, [extension])
+ source_path = tmp_path / f"paper.{extension}"
+ source_path.write_bytes(content)
+ understanding_parse = AsyncMock(
+ side_effect=AssertionError("Understanding must not be submitted")
+ )
+ native_calls = []
+
+ async def native_parse(_self, source, **kwargs):
+ native_calls.append((Path(source), kwargs))
+ result = create_parse_result(
+ root=ResourceNode(type=NodeType.ROOT, title="paper"),
+ source_path=str(source),
+ source_format=extension,
+ parser_name=parser_type.__name__,
+ )
+ result.temp_dir_path = f"viking://temp/native_{extension}"
+ return result
+
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=_FakeVikingFS()),
+ patch.object(ParserRouter, "parse", new=understanding_parse),
+ patch.object(parser_type, "parse", new=native_parse),
+ patch.object(DirectoryParser, "_merge_parser_result", new=AsyncMock()),
+ ):
+ result = await DirectoryParser().parse(str(tmp_path), split_content=False, strict=True)
+
+ understanding_parse.assert_not_awaited()
+ assert len(native_calls) == 1
+ assert native_calls[0][0] == source_path
+ assert native_calls[0][1]["split_content"] is False
+ assert result.meta["processed_files"] == [
+ {"path": source_path.name, "parser": parser_type.__name__}
+ ]
+ assert result.meta["failed_files"] == []
+
+
+async def test_no_split_directory_records_missing_native_parser_per_file(
+ monkeypatch,
+ tmp_path: Path,
+):
+ _configure_understanding(monkeypatch, ["bin"])
+ (tmp_path / "README").write_text("plain text", encoding="utf-8")
+ (tmp_path / "payload.bin").write_bytes(b"\x00\x01")
+ understanding_parse = AsyncMock(
+ side_effect=AssertionError("Understanding must not be submitted")
+ )
+
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=_FakeVikingFS()),
+ patch.object(ParserRouter, "parse", new=understanding_parse),
+ ):
+ result = await DirectoryParser().parse(str(tmp_path), split_content=False, strict=True)
+
+ understanding_parse.assert_not_awaited()
+ assert result.meta["file_count"] == 1
+ assert result.meta["processed_files"] == [{"path": "README", "parser": "direct"}]
+ assert result.meta["failed_files"] == [
+ {
+ "path": "payload.bin",
+ "parser": "native",
+ "error": (
+ "parse_mode='no_split' requires a native parser, but none is "
+ "available for this file type"
+ ),
+ }
+ ]
+
+
+async def test_directory_limits_fail_before_understanding_submit(monkeypatch, tmp_path: Path):
+ _configure_understanding(monkeypatch, ["pdf"], max_files=1)
+ (tmp_path / "a.pdf").write_bytes(b"%PDF-1.7")
+ (tmp_path / "b.pdf").write_bytes(b"%PDF-1.7")
+ parse = AsyncMock(side_effect=AssertionError("Understanding must not be submitted"))
+
+ with patch.object(ParserRouter, "parse", new=parse):
+ with pytest.raises(InvalidArgumentError, match="file count exceeds"):
+ await DirectoryParser().parse(str(tmp_path), strict=True)
+
+ parse.assert_not_awaited()
+
+
+async def test_nested_zip_leaf_failures_are_promoted_with_remote_ids(
+ monkeypatch,
+ tmp_path: Path,
+):
+ _configure_understanding(monkeypatch, ["pdf"])
+ archive_path = tmp_path / "bundle.zip"
+ with zipfile.ZipFile(archive_path, "w") as archive:
+ archive.writestr("good.md", "# good\n")
+ archive.writestr("bad.pdf", b"%PDF-1.7")
+
+ async def parse(_self, source, **_kwargs):
+ assert Path(source).name == "bad.pdf"
+ raise UnderstandingAPIError(
+ "remote parse failed",
+ {"file_id": "file-bad", "response_id": "response-bad"},
+ )
+
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=_FakeVikingFS()),
+ patch.object(ParserRouter, "parse", new=parse),
+ patch.object(DirectoryParser, "_merge_parser_result", new=AsyncMock()),
+ ):
+ result = await DirectoryParser().parse(str(tmp_path), strict=True)
+
+ assert result.meta["processed_files"] == [{"path": "bundle.zip", "parser": "ZipParser"}]
+ assert result.meta["failed_files"] == [
+ {
+ "path": "bundle.zip/bad.pdf",
+ "parser": "UnderstandingAPI",
+ "file_id": "file-bad",
+ "response_id": "response-bad",
+ "error": "remote parse failed",
+ }
+ ]
+
+
+async def test_understanding_directory_job_timeout_is_recorded(monkeypatch, tmp_path: Path):
+ _configure_understanding(monkeypatch, ["pdf"])
+ (tmp_path / "slow.pdf").write_bytes(b"%PDF-1.7")
+
+ async def parse(_self, _source, **_kwargs):
+ await asyncio.sleep(1)
+
+ fake_fs = _FakeVikingFS()
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=fake_fs),
+ patch.object(ParserRouter, "parse", new=parse),
+ patch.object(DirectoryParser, "_get_parser_api_job_timeout", return_value=0.01),
+ ):
+ result = await DirectoryParser().parse(str(tmp_path), strict=True)
+
+ assert result.meta["file_count"] == 0
+ assert result.meta["failed_files"][0]["path"] == "slow.pdf"
+ assert "timed out" in result.meta["failed_files"][0]["error"]
+
+
[email protected]("extension,content", [("pdf", b"%PDF-1.7"), ("html", b"<h1>Page</h1>")])
+async def test_understanding_directory_failure_preserves_remote_ids(
+ monkeypatch, tmp_path: Path, extension, content
+):
+ _configure_understanding(monkeypatch, [extension])
+ (tmp_path / f"failed.{extension}").write_bytes(content)
+
+ async def parse(_self, _source, **_kwargs):
+ raise UnderstandingAPIError(
+ "remote parse failed",
+ {"file_id": "file-1", "response_id": "response-1"},
+ )
+
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=_FakeVikingFS()),
+ patch.object(ParserRouter, "parse", new=parse),
+ ):
+ result = await DirectoryParser().parse(str(tmp_path), strict=True)
+
+ assert result.meta["failed_files"] == [
+ {
+ "path": f"failed.{extension}",
+ "parser": "UnderstandingAPI",
+ "file_id": "file-1",
+ "response_id": "response-1",
+ "error": "remote parse failed",
+ }
+ ]
+
+
+async def test_cancelling_directory_parse_cancels_understanding_workers(
+ monkeypatch,
+ tmp_path: Path,
+):
+ _configure_understanding(monkeypatch, ["pdf"], max_concurrent=2)
+ (tmp_path / "a.pdf").write_bytes(b"%PDF-1.7")
+ (tmp_path / "b.pdf").write_bytes(b"%PDF-1.7")
+ started = asyncio.Event()
+ cancelled = 0
+
+ async def parse(_self, _source, **_kwargs):
+ nonlocal cancelled
+ started.set()
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ cancelled += 1
+ raise
+
+ fake_fs = _FakeVikingFS()
+ with (
+ patch.object(BaseParser, "_get_viking_fs", return_value=fake_fs),
+ patch.object(ParserRouter, "parse", new=parse),
+ ):
+ task = asyncio.create_task(DirectoryParser().parse(str(tmp_path), strict=True))
+ await asyncio.wait_for(started.wait(), timeout=1)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert cancelled >= 1
diff --git a/tests/parse/test_feishu_parser_api.py b/tests/parse/test_feishu_parser_api.py
index 2751d64e2..096288295 100644
--- a/tests/parse/test_feishu_parser_api.py
+++ b/tests/parse/test_feishu_parser_api.py
@@ -1,4 +1,5 @@
import asyncio
+import concurrent.futures
import json
import zipfile
from pathlib import Path
@@ -27,6 +28,66 @@ from openviking_cli.exceptions import InvalidArgumentError
from openviking_cli.session.user_id import UserIdentifier
+async def test_add_resource_processor_cancelled_context_preserves_group_ids(monkeypatch):
+ lock = {"lease_ref": "lock-1"}
+ cleanup = AsyncMock(return_value=True)
+ service = SimpleNamespace(_cleanup_reserved_target_if_empty=cleanup)
+ viking_fs = SimpleNamespace(
+ _async_agfs=SimpleNamespace(
+ pathlock_adopt=AsyncMock(return_value=lock),
+ pathlock_release=AsyncMock(),
+ ),
+ delete_temp=AsyncMock(),
+ )
+ processor = AddResourceProcessor(
+ service,
+ asyncio.get_running_loop(),
+ QueueManager.ADD_RESOURCE,
+ viking_fs,
+ )
+ msg = AddResourceMsg(
+ task_id="task-cancelled",
+ path="report.zip",
+ root_uri="viking://resources/report",
+ account_id="account-1",
+ user_id="user-1",
+ group_ids=["writers", "reviewers"],
+ role="user",
+ lock_handoff={"handle_id": "lock-1"},
+ cleanup_empty_target_on_failure=True,
+ )
+
+ def run_on_current_loop(coro, _loop):
+ task = asyncio.create_task(coro)
+ future: concurrent.futures.Future[None] = concurrent.futures.Future()
+
+ def complete(completed: asyncio.Task) -> None:
+ if completed.cancelled():
+ future.cancel()
+ return
+ error = completed.exception()
+ if error is not None:
+ future.set_exception(error)
+ else:
+ future.set_result(completed.result())
+
+ task.add_done_callback(complete)
+ return future
+
+ monkeypatch.setattr(
+ "openviking.storage.queuefs.add_resource_processor.asyncio.run_coroutine_threadsafe",
+ run_on_current_loop,
+ )
+
+ await processor.on_cancelled({"data": json.dumps(msg.to_dict())})
+
+ cleanup.assert_awaited_once()
+ cleanup_ctx = cleanup.await_args.kwargs["ctx"]
+ assert cleanup_ctx.group_ids == ("writers", "reviewers")
+ viking_fs._async_agfs.pathlock_release.assert_awaited_once_with(lock)
+
+
@pytest.mark.asyncio
async def test_feishu_parser_api_bypasses_accessor():
result = object()
@@ -387,6 +448,7 @@ def test_add_resource_message_round_trips_internal_fields():
role="user",
bypass_acl=True,
defer_target_resolution=True,
+ cleanup_empty_target_on_failure=True,
understanding_response_id="response-1",
internal_task=True,
)
@@ -397,6 +459,7 @@ def test_add_resource_message_round_trips_internal_fields():
assert "feishu_access_token" not in json.dumps(restored.to_dict())
assert restored.bypass_acl is True
assert restored.defer_target_resolution is True
+ assert restored.cleanup_empty_target_on_failure is True
assert restored.understanding_response_id == "response-1"
assert restored.job_phase is AddResourcePhase.SOURCE
assert restored.internal_task is True
@@ -482,7 +545,7 @@ async def test_uat_producer_payload_reaches_worker_without_persisting_token(
return SimpleNamespace(source_name=preflight_name, source_format="file")
async def plan_source_job_target(*, source_info, **_kwargs):
- return root_uri, None, source_info.source_name is None
+ return root_uri, None, source_info.source_name is None, False
monkeypatch.setattr(
"openviking.parse.accessors.feishu_accessor.FeishuAccessor.preflight_source",
@@ -570,7 +633,7 @@ async def test_local_source_job_stages_snapshot_before_enqueue(monkeypatch, tmp_
skill_processor=SimpleNamespace(),
)
service._enqueue_add_resource_job = AsyncMock(return_value=SimpleNamespace(task_id="task-1"))
- service._plan_source_job_target = AsyncMock(return_value=(root_uri, None, False))
+ service._plan_source_job_target = AsyncMock(return_value=(root_uri, None, False, False))
monkeypatch.setattr(
service,
"_connector_delegate",
@@ -688,9 +751,12 @@ async def test_uat_producer_cancellation_respects_queue_ownership(
service = ResourceService(
viking_fs=SimpleNamespace(
+ exists=AsyncMock(return_value=False),
+ stat=AsyncMock(return_value={"isDir": True}),
+ ls=AsyncMock(return_value=[]),
+ rm=AsyncMock(),
_uri_to_path=lambda _uri, ctx: "/resources/fixed",
_async_agfs=agfs,
- exists=AsyncMock(return_value=False),
_ensure_access=AsyncMock(),
),
resource_processor=resource_processor,
diff --git a/tests/parse/test_understanding_api.py b/tests/parse/test_understanding_api.py
index ef8a9389e..858ea6461 100644
--- a/tests/parse/test_understanding_api.py
+++ b/tests/parse/test_understanding_api.py
@@ -1,16 +1,31 @@
from pathlib import Path
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, Mock
+import httpx
import pytest
-from openviking.parse.understanding_api import PREPARED_FILE_ID_ARG, UnderstandingAPI
+from openviking.parse.understanding_api import (
+ PREPARED_FILE_ID_ARG,
+ UnderstandingAPI,
+ UnderstandingAPIError,
+)
from openviking_cli.exceptions import InvalidArgumentError
@pytest.mark.asyncio
-async def test_parse_uses_downloaded_file_and_resolved_extension(monkeypatch, tmp_path):
- downloaded = tmp_path / "download"
- downloaded.write_bytes(b"%PDF-1.7")
+ "filename,content,original_source,resolved_extension,source_format",
+ [
+ ("download", b"%PDF-1.7", "https://example.com/download?id=123", ".pdf", "pdf"),
+ ("page.html", b"<h1>Page</h1>", "https://example.com/page.html?view=full", "", "html"),
+ ("page.html", b"<h1>Page</h1>", "https://example.com/article?id=123", ".html", "html"),
+ ],
+)
+async def test_parse_uses_downloaded_file_and_resolved_extension(
+ monkeypatch, tmp_path, filename, content, original_source, resolved_extension, source_format
+):
+ downloaded = tmp_path / filename
+ downloaded.write_bytes(content)
zip_path = tmp_path / "result.zip"
zip_path.write_bytes(b"zip")
uploaded: list[Path] = []
@@ -45,14 +60,14 @@ async def test_parse_uses_downloaded_file_and_resolved_extension(monkeypatch, tm
result = await api.parse(
downloaded,
- original_source="https://example.com/download?id=123",
+ original_source=original_source,
resource_name="report",
- resolved_extension=".pdf",
+ resolved_extension=resolved_extension,
)
assert uploaded == [downloaded]
- assert result.source_path == "https://example.com/download?id=123"
- assert result.source_format == "pdf"
+ assert result.source_path == original_source
+ assert result.source_format == source_format
assert result.root.title == "report"
@@ -118,5 +133,416 @@ async def test_parse_prepared_file_id_creates_response_and_polls(monkeypatch, tm
api._create_file.assert_not_awaited()
+async def test_file_above_simple_limit_requires_resumable_upload(tmp_path):
+ source = tmp_path / "large.pdf"
+ source.write_bytes(b"123456789")
+ api = UnderstandingAPI.__new__(UnderstandingAPI)
+ api._upload_simple_max_bytes = 8
+ api._enable_resumable_upload = False
+
+ with pytest.raises(ValueError, match="size=9, upload_simple_max_bytes=8"):
+ await api._create_file(local_path=source)
+
+
+async def test_file_above_simple_limit_uses_multipart_when_enabled(tmp_path):
+ source = tmp_path / "large.pdf"
+ source.write_bytes(b"123456789")
+ api = UnderstandingAPI.__new__(UnderstandingAPI)
+ api._upload_simple_max_bytes = 8
+ api._enable_resumable_upload = True
+ api._multipart_create_file = AsyncMock(return_value={"id": "file-1"})
+
+ result = await api._create_file(local_path=source)
+
+ assert result == {"id": "file-1"}
+ api._multipart_create_file.assert_awaited_once_with(source)
+
+
+async def test_parse_failure_preserves_observed_remote_ids(monkeypatch, tmp_path):
+ source = tmp_path / "report.pdf"
+ source.write_bytes(b"%PDF-1.7")
+ api = UnderstandingAPI.__new__(UnderstandingAPI)
+ api._video_exts = {"mp4"}
+ api._audio_exts = {"mp3"}
+ api._image_exts = {"png"}
+ warning = Mock()
+ monkeypatch.setattr("openviking.parse.understanding_api.logger.warning", warning)
+
+ monkeypatch.setattr(api, "_create_file", AsyncMock(return_value={"id": "file-1"}))
+ monkeypatch.setattr(
+ api,
+ "_create_response_for_file",
+ AsyncMock(return_value={"id": "response-1"}),
+ )
+ monkeypatch.setattr(
+ api,
+ "_poll_response",
+ AsyncMock(side_effect=RuntimeError("remote parse failed")),
+ )
+
+ with pytest.raises(UnderstandingAPIError, match="remote parse failed") as exc_info:
+ await api.parse(source, source_name="original.pdf")
+
+ assert exc_info.value.meta == {
+ "doc_name": "original",
+ "doc_type": "pdf",
+ "source_name": "original.pdf",
+ "file_name": "report.pdf",
+ "file_id": "file-1",
+ "response_id": "response-1",
+ }
+ assert str(exc_info.value) == "remote parse failed"
+ assert isinstance(exc_info.value, RuntimeError)
+ warning.assert_called_once_with(
+ "[UnderstandingAPI] Parse failed: %s; meta=%s",
+ exc_info.value.__cause__,
+ exc_info.value.meta,
+ )
+
+
async def _return(value):
return value
+
+
+def _api_with_transport(monkeypatch, handler):
+ api = UnderstandingAPI.__new__(UnderstandingAPI)
+ api._api_base = "https://parser.example.test/api/v3"
+ api._api_key = "test-key"
+ api._http_timeout_sec = 1.0
+ api._timeout_sec = 2.0
+ api._default_poll_interval_ms = 0
+ api._upload_simple_max_bytes = 1024
+ api._upload_part_size_bytes = 512
+ api._video_exts = {"mp4"}
+ api._audio_exts = {"mp3"}
+ api._image_exts = {"png"}
+ client_class = httpx.AsyncClient
+ monkeypatch.setattr(
+ "openviking.parse.understanding_api.httpx.AsyncClient",
+ lambda **kwargs: client_class(transport=httpx.MockTransport(handler), **kwargs),
+ )
+ return api
+
+
[email protected]("failure_stage", ["create_response", "poll_response"])
+async def test_prepared_file_failure_preserves_reason_and_remote_ids(
+ monkeypatch, tmp_path, failure_stage
+):
+ message = "文件解析任务失败:未生成可解析内容"
+ requests = []
+
+ def handler(request):
+ requests.append(request)
+ if request.method == "POST":
+ assert request.url.path == "/api/v3/responses"
+ if failure_stage == "create_response":
+ return httpx.Response(
+ 400, json={"error": {"code": "InvalidParameter", "message": message}}
+ )
+ return httpx.Response(200, json={"id": "response-1"})
+ assert request.url.path == "/api/v3/responses/response-1"
+ return httpx.Response(
+ 200,
+ json={
+ "id": "response-1",
+ "status": "failed",
+ "output": [{"content": [{"type": "output_text", "text": message}]}],
+ },
+ )
+
+ api = _api_with_transport(monkeypatch, handler)
+ api._create_file = AsyncMock(side_effect=AssertionError("prepared file must not reupload"))
+ source = tmp_path / "upload_already_cleaned.pdf"
+
+ with pytest.raises(UnderstandingAPIError, match=message) as exc_info:
+ await api.parse(
+ source,
+ source_name="report.pdf",
+ resolved_extension=".pdf",
+ **{PREPARED_FILE_ID_ARG: "file-1"},
+ )
+
+ error = exc_info.value
+ assert error.meta["file_id"] == "file-1"
+ assert error.meta["source_name"] == "report.pdf"
+ if failure_stage == "create_response":
+ assert "response_id" not in error.meta
+ assert isinstance(error.__cause__, httpx.HTTPStatusError)
+ assert error.__cause__.response.status_code == 400
+ assert len(requests) == 1
+ else:
+ assert error.meta["response_id"] == "response-1"
+ assert str(error) == f"understanding failed: {message}"
+ assert len(requests) == 2
+ api._create_file.assert_not_awaited()
+
+
+ "method",
+ [
+ "_create_file",
+ "_create_response_for_file",
+ "_create_response_for_url",
+ "_poll_response",
+ "_uploads_init",
+ "_uploads_status",
+ "_uploads_put_part",
+ "_uploads_complete",
+ ],
+)
[email protected]("nested_error", [False, True])
+async def test_http_errors_preserve_business_message(monkeypatch, tmp_path, method, nested_error):
+ message = (
+ "One or more parameters specified in the request are not valid. "
+ "file too large (536870913 > 536870912), please use multipart upload"
+ )
+ body = {"message": message, "input": "private-input"}
+ if nested_error:
+ body = {
+ "error": {
+ "code": "InvalidParameter",
+ "message": message,
+ "internal": "private-internal",
+ },
+ "input": "private-input",
+ }
+ requests = []
+
+ def handler(request):
+ requests.append(request)
+ return httpx.Response(400, json=body)
+
+ api = _api_with_transport(monkeypatch, handler)
+ source = tmp_path / "report.pdf"
+ source.write_bytes(b"%PDF-fixture")
+ arguments = {
+ "_create_file": {"local_path": source},
+ "_create_response_for_file": {"file_id": "file-1"},
+ "_create_response_for_url": {"url": "https://example.test/a.pdf", "doc_type": "pdf"},
+ "_poll_response": {"response_id": "response-1"},
+ "_uploads_init": {"file_path": source},
+ "_uploads_status": {"upload_id": "upload-1", "object_key": "object-1"},
+ "_uploads_put_part": {
+ "upload_id": "upload-1",
+ "object_key": "object-1",
+ "part_number": 1,
+ "data": b"part",
+ },
+ "_uploads_complete": {"upload_id": "upload-1", "object_key": "object-1", "parts": []},
+ }
+
+ with pytest.raises(httpx.HTTPStatusError) as exc_info:
+ await getattr(api, method)(**arguments[method])
+
+ assert len(requests) == 1
+ assert exc_info.value.response.status_code == 400
+ assert exc_info.value.request is requests[0]
+ assert message in str(exc_info.value)
+ assert "private-input" not in str(exc_info.value)
+ assert "private-internal" not in str(exc_info.value)
+ if nested_error:
+ assert "InvalidParameter" in str(exc_info.value)
+
+
+async def test_response_http_error_preserves_param_and_type(monkeypatch):
+ message = "One or more parameters specified in the request are not valid. request body is empty"
+ body = {"error": {"code": "InvalidParameter", "message": message, "param": "", "type": ""}}
+ api = _api_with_transport(monkeypatch, lambda _: httpx.Response(400, json=body))
+
+ with pytest.raises(httpx.HTTPStatusError) as exc_info:
+ await api._create_response_for_file(file_id="file-1")
+
+ assert api._safe_error_summary(body) == body
+ assert "InvalidParameter" in str(exc_info.value)
+ assert message in str(exc_info.value)
+ assert "'param': ''" in str(exc_info.value)
+ assert "'type': ''" in str(exc_info.value)
+
+
+async def test_non_json_http_error_preserves_http_exception(monkeypatch):
+ api = _api_with_transport(
+ monkeypatch, lambda _: httpx.Response(502, text="<html>gateway</html>")
+ )
+
+ with pytest.raises(httpx.HTTPStatusError) as exc_info:
+ await api._create_response_for_file(file_id="file-1")
+
+ assert exc_info.value.response.status_code == 502
+
+
[email protected]("method", ["_create_response_for_file", "_poll_response"])
+async def test_api_calls_do_not_retry_transient_http_error(monkeypatch, method):
+ calls = []
+
+ def handler(request):
+ calls.append(request)
+ return httpx.Response(503, json={"error": {"code": "unavailable", "message": "try later"}})
+
+ api = _api_with_transport(monkeypatch, handler)
+ arguments = (
+ {"file_id": "file-1"}
+ if method == "_create_response_for_file"
+ else {"response_id": "response-1"}
+ )
+ with pytest.raises(httpx.HTTPStatusError, match="try later"):
+ await getattr(api, method)(**arguments)
+ assert len(calls) == 1
+
+
+async def test_parse_http_failure_preserves_message_and_remote_ids(monkeypatch, tmp_path):
+ api = _api_with_transport(
+ monkeypatch,
+ lambda _: httpx.Response(400, json={"error": {"code": "invalid", "message": "bad file"}}),
+ )
+ api._create_file = AsyncMock(return_value={"id": "file-1"})
+ api._create_response_for_file = AsyncMock(return_value={"id": "response-1"})
+ source = tmp_path / "report.pdf"
+ source.write_bytes(b"%PDF-fixture")
+
+ with pytest.raises(UnderstandingAPIError, match="bad file") as exc_info:
+ await api.parse(source)
+
+ assert exc_info.value.meta["file_id"] == "file-1"
+ assert exc_info.value.meta["response_id"] == "response-1"
+ assert isinstance(exc_info.value.__cause__, httpx.HTTPStatusError)
+
+
+ "message",
+ [
+ "文件解析任务失败。",
+ "文件解析任务失败:未生成可解析内容",
+ "文件解析任务失败:empty parse result",
+ ],
+)
+async def test_parse_failed_response_preserves_output_text(monkeypatch, tmp_path, message):
+ body = {
+ "id": "response-1",
+ "status": "failed",
+ "output": [
+ {
+ "type": "message",
+ "role": "assistant",
+ "status": "failed",
+ "content": [{"type": "output_text", "text": message}],
+ }
+ ],
+ }
+ requests = []
+
+ def handler(request):
+ requests.append(request)
+ return httpx.Response(200, json=body)
+
+ api = _api_with_transport(monkeypatch, handler)
+ api._create_file = AsyncMock(return_value={"id": "file-1"})
+ api._create_response_for_file = AsyncMock(return_value={"id": "response-1"})
+ api._download_zip = AsyncMock()
+ source = tmp_path / "report.pdf"
+ source.write_bytes(b"%PDF-fixture")
+
+ with pytest.raises(UnderstandingAPIError, match=message) as exc_info:
+ await api.parse(source)
+
+ assert len(requests) == 1
+ assert str(exc_info.value) == f"understanding failed: {message}"
+ assert exc_info.value.meta["file_id"] == "file-1"
+ assert exc_info.value.meta["response_id"] == "response-1"
+ assert api._safe_error_summary(body) == {
+ "id": "response-1",
+ "status": "failed",
+ "output_text": [message],
+ }
+ api._download_zip.assert_not_awaited()
+
+
+ ("error", "message", "expected"),
+ [
+ ({"message": "upstream reason"}, "top-level reason", "upstream reason"),
+ ({"message": " "}, "top-level reason", "top-level reason"),
+ ({}, None, "first reason; second reason"),
+ ],
+)
+def test_error_message_prefers_business_reason(error, message, expected):
+ api = UnderstandingAPI.__new__(UnderstandingAPI)
+ body = {
+ "id": "response-1",
+ "status": "failed",
+ "error": error,
+ "message": message,
+ "output": [
+ {
+ "content": [
+ {"type": "output_text", "text": "first reason"},
+ {"type": "output_text", "text": "second reason"},
+ ]
+ }
+ ],
+ }
+ assert api._error_message(body) == expected
+
+
+ ("body", "expected"),
+ [
+ (None, "request failed"),
+ ({"id": "response-1", "status": "failed"}, "request failed"),
+ ({"error": {"code": "InvalidParameter"}}, "InvalidParameter"),
+ ],
+)
+def test_error_message_fallback_does_not_include_remote_ids(body, expected):
+ assert UnderstandingAPI.__new__(UnderstandingAPI)._error_message(body) == expected
+
+
+def test_failed_response_summary_keeps_only_output_text():
+ api = UnderstandingAPI.__new__(UnderstandingAPI)
+ body = {
+ "id": "response-1",
+ "status": "failed",
+ "input": "private-input",
+ "output": [
+ None,
+ {"content": None},
+ {"content": {"text": "private-content"}},
+ {
+ "content": [
+ None,
+ {"type": "output_text", "text": None},
+ {"type": "output_text", "text": " "},
+ {"type": "input_text", "text": "private-input"},
+ {"type": "zip_url", "zip_url": {"url": "https://private.test/?token=secret"}},
+ {"type": "output_text", "text": "first reason", "internal": "private"},
+ ]
+ },
+ {"content": [{"type": "output_text", "text": "second reason"}]},
+ ],
+ }
+
+ assert api._safe_error_summary(body) == {
+ "id": "response-1",
+ "status": "failed",
+ "output_text": ["first reason", "second reason"],
+ }
+
+
[email protected]("status", ["in_progress", "completed"])
+def test_non_failed_response_summary_does_not_include_output_text(status):
+ api = UnderstandingAPI.__new__(UnderstandingAPI)
+ body = {
+ "id": "response-1",
+ "status": status,
+ "output": [{"content": [{"type": "output_text", "text": "private document content"}]}],
+ }
+
+ assert api._safe_error_summary(body) == {"id": "response-1", "status": status}
diff --git a/tests/parse/test_url_filename_preservation.py b/tests/parse/test_url_filename_preservation.py
index 20a8693f6..eea0ce6a1 100644
--- a/tests/parse/test_url_filename_preservation.py
+++ b/tests/parse/test_url_filename_preservation.py
@@ -58,6 +58,20 @@ class TestURLTypeDetectorCodeExtensions:
def setup_method(self):
self.detector = URLTypeDetector()
+ @pytest.mark.asyncio
+ async def test_extensionless_html_detected_from_head(self, monkeypatch):
+ _patch_httpx_client(
+ monkeypatch,
+ headers={"content-type": "text/html; charset=utf-8"},
+ content=b"<html><h1>Page</h1></html>",
+ fail_head=False,
+ )
+
+ url_type, meta = await self.detector.detect("https://example.com/article?id=123")
+
+ assert url_type == URLType.WEBPAGE
+ assert meta["detected_by"] == "media_type"
+
@pytest.mark.asyncio
async def test_py_extension_detected(self):
url = "https://example.com/path/schemas.py"
@@ -426,7 +440,7 @@ def _patch_httpx_client(
async def __aexit__(self, *_args):
return False
- async def head(self, _url):
+ async def head(self, _url, headers=None):
if fail_head:
raise RuntimeError("SignatureDoesNotMatch")
return FakeResponse(response_head_headers, b"", head_status_code)
diff --git a/tests/service/test_resource_service_connector.py b/tests/service/test_resource_service_connector.py
index 3867109ba..901433627 100644
--- a/tests/service/test_resource_service_connector.py
+++ b/tests/service/test_resource_service_connector.py
@@ -1413,7 +1413,7 @@ async def test_native_git_nested_auth_is_owned_by_durable_task(
)
)
service._plan_source_job_target = AsyncMock(
- return_value=("viking://resources/private", None, False)
+ return_value=("viking://resources/private", None, False, False)
)
service._execute_resource_ingestion = AsyncMock(
side_effect=AssertionError("Git source work must run in the queue worker")
@@ -1462,7 +1462,7 @@ async def test_native_git_nested_auth_watch_is_copied_from_task_state_by_worker(
)
)
service._plan_source_job_target = AsyncMock(
- return_value=("viking://resources/private", None, False)
+ return_value=("viking://resources/private", None, False, False)
)
service._enqueue_add_resource_job = AsyncMock(
return_value=SimpleNamespace(task_id="task-private")
@@ -1505,7 +1505,7 @@ async def test_native_git_watch_refresh_queues_with_restored_task_auth(
)
)
service._plan_source_job_target = AsyncMock(
- return_value=("viking://resources/private", None, False)
+ return_value=("viking://resources/private", None, False, False)
)
service._enqueue_add_resource_job = AsyncMock(
return_value=SimpleNamespace(task_id="task-refresh")
@@ -1663,7 +1663,7 @@ async def test_add_resource_falls_back_for_shared_source_with_parent(
)
)
service._plan_source_job_target = AsyncMock(
- return_value=("viking://resources/repo/repo", None, False)
+ return_value=("viking://resources/repo/repo", None, False, False)
)
service._enqueue_add_resource_job = AsyncMock(
return_value=SimpleNamespace(task_id="task-standard")
diff --git a/tests/service/test_resource_service_parse_mode.py b/tests/service/test_resource_service_parse_mode.py
index b9e1f08a7..e3ff5194c 100644
--- a/tests/service/test_resource_service_parse_mode.py
+++ b/tests/service/test_resource_service_parse_mode.py
@@ -84,7 +84,7 @@ def service(monkeypatch: pytest.MonkeyPatch) -> ResourceService:
monkeypatch.setattr(
instance,
"_plan_source_job_target",
- AsyncMock(return_value=("viking://resources/test", None, False)),
+ AsyncMock(return_value=("viking://resources/test", None, False, False)),
)
return instance
@@ -95,7 +95,7 @@ async def test_no_split_is_forwarded_and_persisted_for_watch_replay(
ctx: RequestContext,
):
watch_manager = SimpleNamespace(
- get_task_by_uri=AsyncMock(return_value=None),
+ get_upsertable_task_by_uri=AsyncMock(return_value=None),
create_task=AsyncMock(return_value=SimpleNamespace(task_id="watch-1")),
)
scheduler = SimpleNamespace(watch_manager=watch_manager)
@@ -131,6 +131,7 @@ async def test_no_split_watch_replay_preserves_auto_bound_file_target(
"viking://resources/test",
None,
kwargs["defer_candidate_resolution"],
+ False,
)
)
@@ -179,6 +180,7 @@ async def test_no_split_defers_initial_root_when_parent_targeted(
"viking://resources/test",
None,
kwargs["defer_candidate_resolution"],
+ False,
)
)
@@ -265,7 +267,9 @@ async def test_tos_auth_args_require_http_resource_url(
service: ResourceService,
ctx: RequestContext,
):
- with pytest.raises(InvalidArgumentError, match=r"tos_signature and tos_access are only supported"):
+ with pytest.raises(
+ InvalidArgumentError, match=r"tos_signature and tos_access are only supported"
+ ):
await service.add_resource(
path="/test/path",
ctx=ctx,
@@ -402,7 +406,7 @@ async def test_native_git_enqueue_persists_internal_no_split_mode(
)
)
service._plan_source_job_target = AsyncMock(
- return_value=("viking://resources/repo", None, False)
+ return_value=("viking://resources/repo", None, False, False)
)
service._enqueue_add_resource_job = AsyncMock(return_value=SimpleNamespace(task_id="task-git"))
diff --git a/tests/service/test_resource_service_reserved_target_cleanup.py b/tests/service/test_resource_service_reserved_target_cleanup.py
new file mode 100644
index 000000000..239906c1d
--- /dev/null
+++ b/tests/service/test_resource_service_reserved_target_cleanup.py
@@ -0,0 +1,221 @@
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from openviking.server.identity import RequestContext, Role
+from openviking.service.resource_service import ResourceService
+from openviking.storage.queuefs.add_resource_msg import AddResourceMsg
+from openviking_cli.session.user_id import UserIdentifier
+
+
+def _ctx() -> RequestContext:
+ return RequestContext(
+ user=UserIdentifier("account-1", "user-1"),
+ role=Role.USER,
+ )
+
+
+def _service(viking_fs, resource_processor=None) -> ResourceService:
+ return ResourceService(
+ vikingdb=object(),
+ viking_fs=viking_fs,
+ resource_processor=resource_processor or SimpleNamespace(),
+ skill_processor=object(),
+ )
+
+
+async def test_cleanup_reserved_target_removes_only_empty_directory():
+ lock = {"lease_ref": "lock-1"}
+ ctx = _ctx()
+ viking_fs = SimpleNamespace(
+ exists=AsyncMock(return_value=True),
+ stat=AsyncMock(return_value={"isDir": True}),
+ ls=AsyncMock(return_value=[]),
+ rm=AsyncMock(),
+ )
+ service = _service(viking_fs)
+
+ removed = await service._cleanup_reserved_target_if_empty(
+ root_uri="viking://resources/empty",
+ ctx=ctx,
+ resource_lock=lock,
+ )
+
+ assert removed is True
+ viking_fs.rm.assert_awaited_once_with(
+ "viking://resources/empty",
+ recursive=True,
+ ctx=ctx,
+ lease_ref=lock,
+ )
+
+
+async def test_cleanup_reserved_target_preserves_nonempty_directory():
+ viking_fs = SimpleNamespace(
+ exists=AsyncMock(return_value=True),
+ stat=AsyncMock(return_value={"isDir": True}),
+ ls=AsyncMock(return_value=[{"name": "document.md", "isDir": False}]),
+ rm=AsyncMock(),
+ )
+ service = _service(viking_fs)
+
+ removed = await service._cleanup_reserved_target_if_empty(
+ root_uri="viking://resources/nonempty",
+ ctx=_ctx(),
+ resource_lock={"lease_ref": "lock-1"},
+ )
+
+ assert removed is False
+ viking_fs.rm.assert_not_awaited()
+
+
+ ("target_preexisting", "cleanup_empty_target_on_failure"),
+ [(False, True), (True, False)],
+)
+async def test_explicit_target_plan_tracks_reservation_ownership(
+ target_preexisting: bool,
+ cleanup_empty_target_on_failure: bool,
+):
+ lock = {"lease_ref": "lock-1"}
+ calls = []
+
+ async def acquire_lock(*args, **kwargs):
+ calls.append("lock")
+ return lock
+
+ async def target_exists(*args, **kwargs):
+ calls.append("exists")
+ return target_preexisting
+
+ async def ensure_access(*args, **kwargs):
+ calls.append("acl")
+
+ viking_fs = SimpleNamespace(
+ exists=AsyncMock(side_effect=target_exists),
+ _ensure_access=AsyncMock(side_effect=ensure_access),
+ _uri_to_path=lambda uri, ctx: f"/agfs/{uri}",
+ _async_agfs=SimpleNamespace(pathlock_acquire_tree=AsyncMock(side_effect=acquire_lock)),
+ )
+ processor = SimpleNamespace(
+ tree_builder=SimpleNamespace(
+ resolve_target_uri=AsyncMock(return_value=("viking://resources/report", None))
+ )
+ )
+ service = _service(viking_fs, processor)
+
+ planned = await service._plan_source_job_target(
+ path="report.zip",
+ ctx=_ctx(),
+ to="viking://resources/report",
+ parent="",
+ create_parent=False,
+ source_info=SimpleNamespace(
+ source_path="report.zip",
+ source_name="report.zip",
+ source_format="zip",
+ ),
+ defer_candidate_resolution=False,
+ )
+
+ assert planned == (
+ "viking://resources/report",
+ lock,
+ False,
+ cleanup_empty_target_on_failure,
+ )
+ assert calls == ["acl", "exists", "lock", "acl"]
+
+
+async def test_source_job_error_cleans_new_empty_reservation():
+ viking_fs = SimpleNamespace()
+ service = _service(viking_fs)
+ service._execute_resource_ingestion = AsyncMock(
+ return_value={"status": "error", "errors": ["directory produced no content"]}
+ )
+ service._cleanup_reserved_target_if_empty = AsyncMock(return_value=True)
+ lock = {"lease_ref": "lock-1"}
+ ctx = _ctx()
+ msg = AddResourceMsg(
+ task_id="task-1",
+ path="report.zip",
+ root_uri="viking://resources/report",
+ account_id="account-1",
+ user_id="user-1",
+ role="user",
+ cleanup_empty_target_on_failure=True,
+ )
+
+ result = await service.execute_add_resource_job(
+ msg,
+ ctx=ctx,
+ resource_lock=lock,
+ stage_callback=AsyncMock(),
+ )
+
+ assert result["status"] == "error"
+ service._cleanup_reserved_target_if_empty.assert_awaited_once_with(
+ root_uri="viking://resources/report",
+ ctx=ctx,
+ resource_lock=lock,
+ )
+
+
[email protected]("cleanup_on_failure", [False, True])
[email protected]("raises_error", [False, True])
+async def test_prepared_file_failure_preserves_cleanup_policy(cleanup_on_failure, raises_error):
+ service = _service(SimpleNamespace())
+ error_message = "remote parser rejected file"
+ error_result = {"status": "error", "errors": [error_message]}
+ service._execute_resource_ingestion = AsyncMock(
+ side_effect=RuntimeError(error_message) if raises_error else None,
+ return_value=error_result,
+ )
+ service._cleanup_reserved_target_if_empty = AsyncMock(return_value=True)
+ lock = {"lease_ref": "lock-1"}
+ ctx = _ctx()
+ msg = AddResourceMsg.from_dict(
+ AddResourceMsg(
+ task_id="task-1",
+ path="report.pdf",
+ root_uri="viking://resources/report",
+ account_id="account-1",
+ user_id="user-1",
+ role="user",
+ understanding_file_id="file-1",
+ cleanup_empty_target_on_failure=cleanup_on_failure,
+ internal_task=True,
+ ).to_dict()
+ )
+
+ job = service.execute_add_resource_job(
+ msg,
+ ctx=ctx,
+ resource_lock=lock,
+ stage_callback=AsyncMock(),
+ )
+ if raises_error:
+ with pytest.raises(RuntimeError, match=error_message):
+ await job
+ else:
+ assert await job == error_result
+
+ service._execute_resource_ingestion.assert_awaited_once()
+ kwargs = service._execute_resource_ingestion.await_args.kwargs
+ assert kwargs["understanding_file_id"] == "file-1"
+ assert kwargs["parser_backend"] == "understanding"
+ assert kwargs["internal_task"] is True
+ if cleanup_on_failure:
+ service._cleanup_reserved_target_if_empty.assert_awaited_once_with(
+ root_uri=msg.root_uri,
+ ctx=ctx,
+ resource_lock=lock,
+ )
+ else:
+ service._cleanup_reserved_target_if_empty.assert_not_awaited()
diff --git a/tests/service/test_resource_service_watch.py b/tests/service/test_resource_service_watch.py
index d8f51ac02..54dbcda01 100644
--- a/tests/service/test_resource_service_watch.py
+++ b/tests/service/test_resource_service_watch.py
@@ -468,7 +468,9 @@ class TestAddResourceArgs:
)
disable_task_tracker(monkeypatch)
to_uri = "viking://resources/feishu_user_watch"
- resource_service._plan_source_job_target = AsyncMock(return_value=(to_uri, None, False))
+ resource_service._plan_source_job_target = AsyncMock(
+ return_value=(to_uri, None, False, False)
+ )
async def preflight(_self, _source, *, feishu_access_token=None):
assert feishu_access_token == "u-test"
@@ -569,7 +571,9 @@ class TestAddResourceArgs:
source_format="repository",
)
)
- resource_service._plan_source_job_target = AsyncMock(return_value=(to_uri, None, False))
+ resource_service._plan_source_job_target = AsyncMock(
+ return_value=(to_uri, None, False, False)
+ )
await resource_service.add_resource(
path=repo_url,
diff --git a/tests/test_config_loader.py b/tests/test_config_loader.py
index 7977b9fcf..2fb2e8c33 100644
--- a/tests/test_config_loader.py
+++ b/tests/test_config_loader.py
@@ -19,7 +19,7 @@ from openviking_cli.utils.config.config_loader import (
resolve_config_path,
)
from openviking_cli.utils.config.open_viking_config import OpenVikingConfig, ParserApiConfig
-from openviking_cli.utils.config.parser_config import CodeHostingConfig
+from openviking_cli.utils.config.parser_config import CodeHostingConfig, DirectoryConfig
from openviking_cli.utils.config.queue_worker_config import QueueWorkersConfig
@@ -168,6 +168,53 @@ def test_parser_api_rejects_worker_max_concurrent():
assert exc_info.value.errors()[0]["type"] == "extra_forbidden"
+def test_parser_api_upload_defaults():
+ config = ParserApiConfig()
+
+ assert config.enable_resumable_upload is False
+ assert config.upload_simple_max_bytes == 512 * 1024 * 1024
+ assert config.upload_part_size_bytes == 8 * 1024 * 1024
+
+
+def test_directory_safety_limits_have_bounded_defaults():
+ config = DirectoryConfig()
+
+ assert config.max_files == 1000
+ assert config.max_depth == 10
+ assert config.max_concurrent == 4
+
+
+def test_directory_safety_limits_load_from_parser_config():
+ config = OpenVikingConfig.from_dict(
+ {
+ "parsers": {
+ "directory": {
+ "max_files": 20,
+ "max_depth": 5,
+ "max_concurrent": 2,
+ }
+ }
+ }
+ )
+
+ assert config.directory.max_files == 20
+ assert config.directory.max_depth == 5
+ assert config.directory.max_concurrent == 2
+
+
+ "field",
+ [
+ "max_files",
+ "max_depth",
+ "max_concurrent",
+ ],
+)
+def test_directory_safety_limits_reject_non_positive_values(field):
+ with pytest.raises(ValueError, match=field):
+ DirectoryConfig.from_dict({field: 0})
+
+
def test_generic_code_hosting_domains_include_supported_platforms():
config = CodeHostingConfig()