Skip to content

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

fix(resource): 拒绝导入只有换行或空白的文件 (#5125)

Qin Haojie5c5101636555
diff --git a/openviking/parse/directory_scan.py b/openviking/parse/directory_scan.py
index 8e4d02755..61c33de92 100644
--- a/openviking/parse/directory_scan.py
+++ b/openviking/parse/directory_scan.py
@@ -16,7 +16,7 @@ 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.parsers.upload_utils import is_empty_file, is_text_file
from openviking.parse.registry import ParserRegistry, get_registry
from openviking_cli.exceptions import InvalidArgumentError, UnsupportedDirectoryFilesError
from openviking_cli.utils.logger import get_logger
@@ -56,14 +56,14 @@ def _should_skip_file(file_path: Path) -> tuple[bool, str]:
"""
Return (True, reason) if the file should be skipped (not counted as supported/unsupported).
- Skip: dot files, symlinks, empty files (per RFC phase-one).
+ Skip: dot files, symlinks, empty or whitespace-only files.
"""
if file_path.name.startswith("."):
return True, "dot file"
if file_path.is_symlink():
return True, "symlink"
try:
- if file_path.stat().st_size == 0:
+ if is_empty_file(file_path):
return True, "empty file"
except OSError:
return True, "os error"
diff --git a/openviking/parse/parsers/upload_utils.py b/openviking/parse/parsers/upload_utils.py
index 2f3f7080f..fc9071664 100644
--- a/openviking/parse/parsers/upload_utils.py
+++ b/openviking/parse/parsers/upload_utils.py
@@ -70,6 +70,15 @@ def detect_and_convert_encoding(content: bytes, file_path: Union[str, Path] = ""
return normalize_text_bytes(content, file_path)
+def is_empty_file(file_path: Path) -> bool:
+ """Return whether a file is empty or contains only ASCII whitespace."""
+ with file_path.open("rb") as source:
+ while chunk := source.read(8192):
+ if chunk.strip():
+ return False
+ return True
+
+
def should_skip_file(
file_path: Path,
max_file_size: int = 10 * 1024 * 1024,
@@ -94,7 +103,7 @@ def should_skip_file(
file_size = file_path.stat().st_size
if file_size > max_file_size:
return True, f"file too large: {file_size} bytes"
- if file_size == 0:
+ if is_empty_file(file_path):
return True, "empty file"
except OSError as exc:
return True, f"os error: {exc}"
diff --git a/openviking/utils/media_processor.py b/openviking/utils/media_processor.py
index 509620bad..434804d4d 100644
--- a/openviking/utils/media_processor.py
+++ b/openviking/utils/media_processor.py
@@ -19,6 +19,7 @@ from openviking.parse.parsers.constants import (
TYPESCRIPT_MPEG_TS_EXTENSION,
)
from openviking.parse.parsers.media.utils import is_mpeg_ts, read_mpeg_ts_probe
+from openviking.parse.parsers.upload_utils import is_empty_file
from openviking.parse.registry import parse
from openviking.server.local_input_guard import (
is_remote_resource_source,
@@ -242,12 +243,12 @@ class UnifiedResourceProcessor:
than being parsed and indexed as an empty resource.
Directories are skipped: their size is not meaningful, and
- directory_scan already drops zero-byte members. content/write is a
+ directory_scan already drops empty or whitespace-only members. content/write is a
different path and still allows an empty file, because creating one
there is an explicit user action.
"""
try:
- if not resource.path.is_file() or resource.path.stat().st_size:
+ if not resource.path.is_file() or not is_empty_file(resource.path):
return
except OSError:
# An unreadable source is not this check's business; let the normal
@@ -262,7 +263,7 @@ class UnifiedResourceProcessor:
or resource.path.name
)
raise InvalidArgumentError(
- f"'{name}' is empty (0 bytes), so there is nothing to extract or index. "
+ f"'{name}' is empty or contains only whitespace, so there is nothing to extract or index. "
"Add a resource with content, or use content/write if an empty file is "
"what you want."
)
diff --git a/tests/parse/test_directory_scan.py b/tests/parse/test_directory_scan.py
index acde78f91..c93e432cb 100644
--- a/tests/parse/test_directory_scan.py
+++ b/tests/parse/test_directory_scan.py
@@ -107,10 +107,14 @@ class TestScanDirectoryTraversal:
assert not any("node_modules" in p for p in rel_paths)
def test_skips_dot_files_and_empty(self, tmp_tree: Path, registry: ParserRegistry) -> None:
+ (tmp_tree / "application.properties").write_bytes(b"\n")
+ (tmp_tree / "blank.txt").write_bytes(b" \t\r\n")
result: DirectoryScanResult = scan_directory(tmp_tree, registry=registry, strict=False)
all_rel = [f.rel_path for f in result.processable + result.unsupported]
assert ".hidden" not in all_rel
assert "empty.txt" not in all_rel
+ assert "application.properties" not in all_rel
+ assert "blank.txt" not in all_rel
assert any("empty" in s or "dot" in s for s in result.skipped)
diff --git a/tests/parse/test_empty_source_rejection.py b/tests/parse/test_empty_source_rejection.py
index 3a7d64bcf..631f22321 100644
--- a/tests/parse/test_empty_source_rejection.py
+++ b/tests/parse/test_empty_source_rejection.py
@@ -24,9 +24,20 @@ def _processor(monkeypatch, resource: LocalResource) -> UnifiedResourceProcessor
@pytest.mark.asyncio
-async def test_prepare_rejects_and_cleans_up_a_temporary_empty_file(monkeypatch, tmp_path):
+ ("content", "reject"),
+ [
+ (b"", True),
+ (b"\n", True),
+ (b" \t\r\n" * 4096, True),
+ (b" \t\r\n" * 4096 + b"key=value\n", False),
+ ],
+)
+async def test_prepare_rejects_and_cleans_up_a_temporary_empty_file(
+ monkeypatch, tmp_path, content, reject
+):
downloaded = tmp_path / "tmp9f3a21"
- downloaded.write_bytes(b"")
+ downloaded.write_bytes(content)
resource = LocalResource(
path=downloaded,
source_type=SourceType.HTTP,
@@ -36,6 +47,11 @@ async def test_prepare_rejects_and_cleans_up_a_temporary_empty_file(monkeypatch,
)
processor = _processor(monkeypatch, resource)
+ if not reject:
+ assert await processor.prepare(resource.original_source) is resource
+ assert downloaded.read_bytes() == content
+ return
+
with pytest.raises(InvalidArgumentError) as excinfo:
await processor.prepare("https://example.com/quarterly-report.pdf")
diff --git a/tests/test_upload_utils.py b/tests/test_upload_utils.py
index 732fdb2ba..25b088fb5 100644
--- a/tests/test_upload_utils.py
+++ b/tests/test_upload_utils.py
@@ -308,8 +308,12 @@ class TestUploadDirectory:
@pytest.mark.asyncio
async def test_skips_empty_files(self, tmp_dir: Path, viking_fs: FakeVikingFS) -> None:
+ (tmp_dir / "application.properties").write_bytes(b"\n")
+ (tmp_dir / "blank.txt").write_bytes(b" \t\r\n")
await upload_directory(tmp_dir, "viking://temp/test", viking_fs)
assert all("empty.txt" not in uri for uri in viking_fs.files)
+ assert "viking://temp/test/application.properties" not in viking_fs.files
+ assert "viking://temp/test/blank.txt" not in viking_fs.files
@pytest.mark.asyncio
async def test_creates_root_dir(self, tmp_dir: Path, viking_fs: FakeVikingFS) -> None: