Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(parser): enforce hard character limit per section in MarkdownParser (#826)
ChenXiaofei3064725bd63f
diff --git a/examples/ov.conf.example b/examples/ov.conf.exampleindex 18e69ded6..c4211385c 100644--- a/examples/ov.conf.example+++ b/examples/ov.conf.example@@ -100,6 +100,7 @@"max_content_length": 100000,"max_section_size": 4000,"section_size_flexibility": 0.3,+ "max_section_chars": 6000,"mineru_endpoint": "https://mineru.example.com/api/v1","mineru_api_key": "{your-mineru-api-key}","mineru_timeout": 300.0diff --git a/openviking/parse/parsers/markdown.py b/openviking/parse/parsers/markdown.pyindex fb570e30b..abeb54242 100644--- a/openviking/parse/parsers/markdown.py+++ b/openviking/parse/parsers/markdown.py@@ -296,6 +296,9 @@ class MarkdownParser(BaseParser):"""Split oversized content by paragraphs, force split single oversized paragraphs.+ Enforces both a token estimate limit (max_size) and a hard character limit+ (self.config.max_section_chars) to guard against token estimation errors.+Args:content: Content to splitmax_size: Maximum size per part (in tokens)@@ -303,6 +306,10 @@ class MarkdownParser(BaseParser):Returns:List of content parts"""+ max_chars = self.config.max_section_chars+ if max_chars <= 0:+ # Char limit disabled (misconfigured); fall back to token-only splitting+ max_chars = len(content) + 1paragraphs = content.split("\n\n")parts = []current = ""@@ -310,18 +317,19 @@ class MarkdownParser(BaseParser):for para in paragraphs:para_tokens = self._estimate_token_count(para)+ para_len = len(para)- # Single paragraph too long, force split by characters- if para_tokens > max_size:+ # Single paragraph too long (by tokens or chars): force split by characters+ if para_tokens > max_size or para_len > max_chars:if current:parts.append(current.strip())current = ""current_tokens = 0- # Split by character count (rough approximation: 1 token ~ 3 chars)- char_split_size = int(max_size * 3)- for i in range(0, len(para), char_split_size):- parts.append(para[i : i + char_split_size].strip())- elif current_tokens + para_tokens > max_size and current:+ for i in range(0, len(para), max_chars):+ parts.append(para[i : i + max_chars].strip())+ elif (+ current_tokens + para_tokens > max_size or len(current) + len(para) + 2 > max_chars+ ) and current:parts.append(current.strip())current = paracurrent_tokens = para_tokens@@ -376,6 +384,7 @@ class MarkdownParser(BaseParser):"""viking_fs = self._get_viking_fs()max_size = self.config.max_section_size or self.DEFAULT_MAX_SECTION_SIZE+ max_chars = self.config.max_section_charsmin_size = self.DEFAULT_MIN_SECTION_TOKENS# Estimate document size@@ -388,8 +397,8 @@ class MarkdownParser(BaseParser):# Get document namedoc_name = self._sanitize_for_path(Path(source_path).stem if source_path else "content")- # Small document: save as single file- if estimated_tokens <= max_size:+ # Small document: save as single file (check both token and char limits)+ if estimated_tokens <= max_size and len(content) <= max_chars:file_path = f"{root_dir}/{doc_name}.md"await viking_fs.write_file(file_path, content)logger.debug(f"[MarkdownParser] Small document saved as: {file_path}")@@ -520,8 +529,8 @@ class MarkdownParser(BaseParser):name, tokens, content_text = section["name"], section["tokens"], section["content"]has_children = section["has_children"]- # Fits in one file- if tokens <= max_size:+ # Fits in one file (check both token and char limits)+ if tokens <= max_size and len(content_text) <= self.config.max_section_chars:await viking_fs.write_file(f"{parent_dir}/{name}.md", content_text)logger.debug(f"[MarkdownParser] Saved: {name}.md")return@@ -611,11 +620,26 @@ class MarkdownParser(BaseParser):async def _save_merged(self, viking_fs, parent_dir: str, sections: List[Tuple[str, str, int]]) -> None:- """Save merged sections as single file with smart naming."""+ """Save merged sections as single file with smart naming.++ If the joined content exceeds max_section_chars it is split further+ by _smart_split_content before writing, so no single file ever exceeds+ the hard character limit.+ """name = self._generate_merged_filename(sections)content = "\n\n".join(c for _, c, _ in sections)- await viking_fs.write_file(f"{parent_dir}/{name}.md", content)- logger.debug(f"[MarkdownParser] Merged: {name}.md ({len(sections)} sections)")+ max_chars = self.config.max_section_chars+ if len(content) > max_chars:+ max_size = self.config.max_section_size or self.DEFAULT_MAX_SECTION_SIZE+ parts = self._smart_split_content(content, max_size)+ for i, part in enumerate(parts, 1):+ await viking_fs.write_file(f"{parent_dir}/{name}_{i}.md", part)+ logger.debug(+ f"[MarkdownParser] Merged then split: {name} ({len(sections)} sections → {len(parts)} parts)"+ )+ else:+ await viking_fs.write_file(f"{parent_dir}/{name}.md", content)+ logger.debug(f"[MarkdownParser] Merged: {name}.md ({len(sections)} sections)")def _get_section_info(self,diff --git a/openviking_cli/utils/config/parser_config.py b/openviking_cli/utils/config/parser_config.pyindex 717375646..6265626cb 100644--- a/openviking_cli/utils/config/parser_config.py+++ b/openviking_cli/utils/config/parser_config.py@@ -25,8 +25,9 @@ class ParserConfig:enabled: Whether the parser is enabledmax_content_length: Maximum content length to process (characters)encoding: Default file encoding- max_section_size: Maximum characters per section before splitting+ max_section_size: Maximum tokens per section before splittingsection_size_flexibility: Allow overflow to maintain coherence (0.0-1.0)+ max_section_chars: Hard character limit per section (guards against token estimation errors)"""enabled: bool = True@@ -36,6 +37,9 @@ class ParserConfig:# Smart splitting configurationmax_section_size: int = 1000 # Maximum tokens per section before splittingsection_size_flexibility: float = 0.3 # Allow 30% overflow to maintain coherence+ max_section_chars: int = (+ 6000 # Hard character limit per section (guards against token estimation errors)+ )@classmethoddef from_dict(cls, data: Dict[str, Any]) -> "ParserConfig":@@ -104,6 +108,9 @@ class ParserConfig:if not 0.0 <= self.section_size_flexibility <= 1.0:raise ValueError("section_size_flexibility must be between 0.0 and 1.0")+ if self.max_section_chars <= 0:+ raise ValueError("max_section_chars must be positive")+def to_dict(self) -> Dict[str, Any]:"""Export configuration as dictionary.diff --git a/tests/parse/test_markdown_char_limit.py b/tests/parse/test_markdown_char_limit.pynew file mode 100644index 000000000..c41f0357f--- /dev/null+++ b/tests/parse/test_markdown_char_limit.py@@ -0,0 +1,327 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0+"""Tests for MarkdownParser hard character limit enforcement (max_section_chars)."""++from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from openviking.parse.parsers.markdown import MarkdownParser+from openviking_cli.utils.config.parser_config import ParserConfig++# ---------------------------------------------------------------------------+# ParserConfig+# ---------------------------------------------------------------------------+++class TestParserConfigMaxSectionChars:+ def test_default_value(self):+ config = ParserConfig()+ assert config.max_section_chars == 6000++ def test_custom_value(self):+ config = ParserConfig(max_section_chars=3000)+ assert config.max_section_chars == 3000++ def test_from_dict(self):+ config = ParserConfig.from_dict({"max_section_chars": 2000})+ assert config.max_section_chars == 2000++ def test_from_dict_missing_key_uses_default(self):+ config = ParserConfig.from_dict({})+ assert config.max_section_chars == 6000++ def test_validate_rejects_zero(self):+ config = ParserConfig(max_section_chars=0)+ with pytest.raises(ValueError, match="max_section_chars"):+ config.validate()++ def test_validate_rejects_negative(self):+ config = ParserConfig(max_section_chars=-1)+ with pytest.raises(ValueError, match="max_section_chars"):+ config.validate()++ def test_validate_accepts_positive(self):+ config = ParserConfig(max_section_chars=1)+ config.validate() # must not raise+++# ---------------------------------------------------------------------------+# _smart_split_content — unit tests (no VikingFS needed)+# ---------------------------------------------------------------------------+++class TestSmartSplitContentCharLimit:+ def _make_parser(self, max_section_chars: int = 100) -> MarkdownParser:+ """Parser with a tight char limit for easy testing."""+ config = ParserConfig(max_section_size=1000, max_section_chars=max_section_chars)+ return MarkdownParser(config=config)++ def test_short_content_returned_as_single_part(self):+ parser = self._make_parser(max_section_chars=500)+ content = "Hello world. " * 10 # 130 chars, well within limit+ parts = parser._smart_split_content(content, max_size=1000)+ assert len(parts) == 1++ def test_paragraph_exceeding_char_limit_is_force_split(self):+ """A single paragraph longer than max_section_chars must be split."""+ parser = self._make_parser(max_section_chars=50)+ # One paragraph of 200 chars — no \n\n so it stays as one para+ long_para = "x" * 200+ parts = parser._smart_split_content(long_para, max_size=1000)+ # Each part must be <= max_section_chars+ for part in parts:+ assert len(part) <= 50+ # All content is preserved+ assert "".join(p.strip() for p in parts) == long_para++ def test_accumulated_chunks_respect_char_limit(self):+ """Multiple small paragraphs that together exceed max_chars are split."""+ parser = self._make_parser(max_section_chars=80)+ # Each paragraph is 40 chars; two together (40+2+40=82) exceed the limit+ para = "y" * 40+ content = f"{para}\n\n{para}\n\n{para}"+ parts = parser._smart_split_content(content, max_size=1000)+ for part in parts:+ assert len(part) <= 80++ def test_char_limit_splits_even_when_token_estimate_is_small(self):+ """Content within token limit but exceeding char limit must still be split."""+ # Use a very large max_section_chars to NOT trigger char splitting+ parser_no_limit = self._make_parser(max_section_chars=10000)+ # Use a tight max_section_chars to force splitting+ parser_with_limit = self._make_parser(max_section_chars=50)++ content = "a" * 120 # single paragraph, ~36 estimated tokens (well under 1000)++ parts_no_limit = parser_no_limit._smart_split_content(content, max_size=1000)+ parts_with_limit = parser_with_limit._smart_split_content(content, max_size=1000)++ # Without char limit: one part (token estimate is fine)+ assert len(parts_no_limit) == 1+ # With char limit: must be split into multiple parts+ assert len(parts_with_limit) > 1+ for part in parts_with_limit:+ assert len(part) <= 50++ def test_empty_paragraphs_handled(self):+ parser = self._make_parser(max_section_chars=200)+ content = "line1\n\n\n\nline2"+ parts = parser._smart_split_content(content, max_size=1000)+ assert all(p.strip() for p in parts) # no blank-only parts++ def test_content_entirely_preserved_after_split(self):+ """No characters should be lost during splitting."""+ parser = self._make_parser(max_section_chars=60)+ # Build content where each paragraph is 50 chars+ para = "p" * 50+ content = "\n\n".join([para] * 5)+ parts = parser._smart_split_content(content, max_size=1000)+ # Reconstruct: strip whitespace added by joining+ total_chars = sum(len(p.replace(" ", "").replace("\n", "")) for p in parts)+ original_chars = len(content.replace(" ", "").replace("\n", ""))+ assert total_chars == original_chars+++# ---------------------------------------------------------------------------+# _save_section — char limit gates (async, VikingFS mocked)+# ---------------------------------------------------------------------------+++class TestSaveSectionCharLimit:+ def _make_parser(self, max_section_chars: int = 100) -> MarkdownParser:+ config = ParserConfig(max_section_size=1000, max_section_chars=max_section_chars)+ return MarkdownParser(config=config)++ def _mock_viking_fs(self):+ vfs = MagicMock()+ vfs.write_file = AsyncMock()+ vfs.mkdir = AsyncMock()+ return vfs++ @pytest.mark.asyncio+ async def test_section_within_both_limits_saved_as_file(self):+ """Section under token AND char limit → single .md file."""+ parser = self._make_parser(max_section_chars=500)+ mock_vfs = self._mock_viking_fs()++ section = {+ "name": "intro",+ "tokens": 50,+ "content": "Short content",+ "has_children": False,+ }++ with patch.object(parser, "_get_viking_fs", return_value=mock_vfs):+ await parser._save_section("", [], "viking://tmp/root", section, 1000, 512)++ mock_vfs.write_file.assert_called_once()+ call_path = mock_vfs.write_file.call_args[0][0]+ assert call_path.endswith("intro.md")++ @pytest.mark.asyncio+ async def test_section_exceeding_char_limit_is_split_even_if_tokens_ok(self):+ """Section within token limit but over char limit must NOT be written as single file."""+ parser = self._make_parser(max_section_chars=50)+ mock_vfs = self._mock_viking_fs()++ long_content = "word " * 30 # 150 chars, ~14 estimated tokens (under 1000)+ section = {+ "name": "big_section",+ "tokens": 14,+ "content": long_content,+ "has_children": False,+ }++ with patch.object(parser, "_get_viking_fs", return_value=mock_vfs):+ await parser._save_section("", [], "viking://tmp/root", section, 1000, 512)++ # Must have written at least one file+ mock_vfs.write_file.assert_called()+ # Every written chunk must respect the char limit+ for call in mock_vfs.write_file.call_args_list:+ written_content = call[0][1]+ assert len(written_content) <= 50, (+ f"Written content exceeds char limit: {len(written_content)} chars"+ )+ # A directory should have been created for the split+ mock_vfs.mkdir.assert_called()+++# ---------------------------------------------------------------------------+# _save_merged — char limit enforcement (async, VikingFS mocked)+# ---------------------------------------------------------------------------+++class TestSaveMergedCharLimit:+ def _make_parser(self, max_section_chars: int) -> MarkdownParser:+ config = ParserConfig(max_section_size=1000, max_section_chars=max_section_chars)+ return MarkdownParser(config=config)++ def _mock_viking_fs(self):+ vfs = MagicMock()+ vfs.write_file = AsyncMock()+ return vfs++ @pytest.mark.asyncio+ async def test_merged_within_char_limit_saved_as_single_file(self):+ parser = self._make_parser(max_section_chars=500)+ mock_vfs = self._mock_viking_fs()++ sections = [("s1", "hello", 5), ("s2", "world", 5)]+ with patch.object(parser, "_get_viking_fs", return_value=mock_vfs):+ await parser._save_merged(mock_vfs, "viking://tmp/root", sections)++ mock_vfs.write_file.assert_called_once()+ path, content = mock_vfs.write_file.call_args[0]+ assert path.endswith(".md")+ assert "hello" in content and "world" in content++ @pytest.mark.asyncio+ async def test_merged_exceeding_char_limit_is_split_into_multiple_files(self):+ """When joined content exceeds max_section_chars, _save_merged must split it."""+ parser = self._make_parser(max_section_chars=60)+ mock_vfs = self._mock_viking_fs()++ # Each section is 40 chars; joined = 40 + "\n\n" + 40 = 82 chars > 60+ sections = [("a", "A" * 40, 12), ("b", "B" * 40, 12)]+ with patch.object(parser, "_get_viking_fs", return_value=mock_vfs):+ await parser._save_merged(mock_vfs, "viking://tmp/root", sections)++ # Should have written multiple files+ assert mock_vfs.write_file.call_count > 1+ for call in mock_vfs.write_file.call_args_list:+ written_content = call[0][1]+ assert len(written_content) <= 60, (+ f"Merged split part exceeds char limit: {len(written_content)} chars"+ )++ @pytest.mark.asyncio+ async def test_many_small_sections_merged_correctly_split(self):+ """Many token-small but char-large sections that accumulate past the limit."""+ parser = self._make_parser(max_section_chars=100)+ mock_vfs = self._mock_viking_fs()++ # 10 sections × 30 chars = 300 chars + separators >> 100 chars+ sections = [(f"s{i}", "z" * 30, 9) for i in range(10)]+ with patch.object(parser, "_get_viking_fs", return_value=mock_vfs):+ await parser._save_merged(mock_vfs, "viking://tmp/root", sections)++ # Every written part must respect the char limit+ mock_vfs.write_file.assert_called()+ for call in mock_vfs.write_file.call_args_list:+ written_content = call[0][1]+ assert len(written_content) <= 100, (+ f"Part exceeds char limit: {len(written_content)} chars"+ )+++# ---------------------------------------------------------------------------+# _parse_and_create_structure — small-document char limit (async, VikingFS mocked)+# ---------------------------------------------------------------------------+++class TestParseAndCreateStructureCharLimit:+ def _make_parser(self, max_section_size: int = 1000, max_section_chars: int = 100):+ config = ParserConfig(+ max_section_size=max_section_size, max_section_chars=max_section_chars+ )+ return MarkdownParser(config=config)++ def _mock_viking_fs(self):+ vfs = MagicMock()+ vfs.write_file = AsyncMock()+ vfs.mkdir = AsyncMock()+ return vfs++ @pytest.mark.asyncio+ async def test_small_doc_within_both_limits_saved_as_single_file(self):+ parser = self._make_parser(max_section_size=1000, max_section_chars=500)+ mock_vfs = self._mock_viking_fs()+ content = "# Title\n\nShort body." # well under both limits++ with patch.object(parser, "_get_viking_fs", return_value=mock_vfs):+ await parser._parse_and_create_structure(content, [], "viking://tmp/root")++ mock_vfs.write_file.assert_called_once()+ written_content = mock_vfs.write_file.call_args[0][1]+ assert written_content == content++ @pytest.mark.asyncio+ async def test_small_doc_exceeding_char_limit_is_not_saved_as_single_file(self):+ """Even if token estimate is tiny, a doc over max_section_chars must be split."""+ parser = self._make_parser(max_section_size=1000, max_section_chars=30)+ mock_vfs = self._mock_viking_fs()++ # 200 chars but NO headings → no sections, falls back to paragraph split+ content = "a" * 200++ with patch.object(parser, "_get_viking_fs", return_value=mock_vfs):+ await parser._parse_and_create_structure(content, [], "viking://tmp/root")++ # Must have been split: each written chunk ≤ max_section_chars+ assert mock_vfs.write_file.call_count > 1+ for call in mock_vfs.write_file.call_args_list:+ written = call[0][1]+ assert len(written) <= 30++ @pytest.mark.asyncio+ async def test_doc_with_headings_exceeding_char_limit_is_not_saved_as_single_file(self):+ """Small-document fast-path with headings: char limit must still be enforced."""+ parser = self._make_parser(max_section_size=1000, max_section_chars=50)+ mock_vfs = self._mock_viking_fs()++ # 200 chars WITH a heading — exercises the char-check at the+ # "estimated_tokens <= max_size AND len(content) <= max_chars" guard+ content = "# Heading\n\n" + "b" * 189 # total > 50 chars, token estimate << 1000++ with patch.object(parser, "_get_viking_fs", return_value=mock_vfs):+ headings = parser._find_headings(content)+ await parser._parse_and_create_structure(content, headings, "viking://tmp/root")++ # Must not have been saved as a single file equal to the full content+ for call in mock_vfs.write_file.call_args_list:+ written = call[0][1]+ assert len(written) <= 50, (+ f"Single file written with {len(written)} chars, exceeds limit of 50"+ )