PageIndex/tests/test_pipeline.py
mountain 2d46d68052 fix(index): bound LLM concurrency at the leaf, not per gather call
The previous approach (bounded_gather building a fresh semaphore per call)
did NOT compose: the indexing call graph nests gathers
(tree_parser -> process_large_node_recursively -> recurse, plus each node's
check_title gather), and each level got its own independent cap. Peak
in-flight LLM calls grew ~N^depth, so a deep/wide document still exhausted
file descriptors (Errno 24) — the exact failure the cap was meant to
prevent — while the flat summary phase was over-serialized. Naively sharing
one semaphore across gather levels would instead deadlock (a parent holds a
slot while awaiting children that need slots).

Move the throttle to the single chokepoint every LLM call funnels through,
llm_acompletion: one shared semaphore per event loop, acquired only around
the litellm.acompletion network call. This gives a true global cap that
composes across any nesting and can't deadlock (a parent awaiting children
holds no slot). bounded_gather is gone; the call sites revert to plain
asyncio.gather.

Also:
- Reject bool in max_concurrency validation (bool is an int subclass, so
  set_max_concurrency(True) / IndexConfig(max_concurrency=True) previously
  became Semaphore(1) and silently serialized). Shared _validate_max_concurrency
  + a pydantic field_validator.
- Guard check_title_appearance_in_start_concurrent against an out-of-range
  or 0 physical_index (LLM can emit one): it was dereferenced during task
  construction, outside the gather's return_exceptions protection, aborting
  the whole build; 0 silently wrapped to the last page. Now marked 'no'.
- Propagate contextvars into agent.py's worker-thread run (mirrors
  pipeline._run_async) so ContextVar settings stay consistent.
- Tests rewritten to cover the nested case the old flat tests missed, the
  leaf-level throttle in llm_acompletion, bool rejection, and the
  out-of-range physical_index guard.

Claude-Session: https://claude.ai/code/session_01Kx5DgKbhK1N8autqXH8SmS
2026-07-08 11:26:36 +08:00

114 lines
4.4 KiB
Python

# tests/sdk/test_pipeline.py
import asyncio
from unittest.mock import patch, AsyncMock
from pageindex.parser.protocol import ContentNode, ParsedDocument
from pageindex.index.pipeline import (
detect_strategy, build_tree_from_levels, build_index,
_content_based_pipeline, _NullLogger,
)
def test_detect_strategy_with_level():
nodes = [
ContentNode(content="# Intro", tokens=10, title="Intro", index=1, level=1),
ContentNode(content="## Details", tokens=10, title="Details", index=5, level=2),
]
assert detect_strategy(nodes) == "level_based"
def test_detect_strategy_without_level():
nodes = [
ContentNode(content="Page 1 text", tokens=100, index=1),
ContentNode(content="Page 2 text", tokens=100, index=2),
]
assert detect_strategy(nodes) == "content_based"
def test_build_tree_from_levels():
nodes = [
ContentNode(content="ch1 text", tokens=10, title="Chapter 1", index=1, level=1),
ContentNode(content="s1.1 text", tokens=10, title="Section 1.1", index=5, level=2),
ContentNode(content="s1.2 text", tokens=10, title="Section 1.2", index=10, level=2),
ContentNode(content="ch2 text", tokens=10, title="Chapter 2", index=20, level=1),
]
tree = build_tree_from_levels(nodes)
assert len(tree) == 2 # 2 root nodes (chapters)
assert tree[0]["title"] == "Chapter 1"
assert len(tree[0]["nodes"]) == 2 # 2 sections under chapter 1
assert tree[0]["nodes"][0]["title"] == "Section 1.1"
assert tree[0]["nodes"][1]["title"] == "Section 1.2"
assert tree[1]["title"] == "Chapter 2"
assert len(tree[1]["nodes"]) == 0
def test_build_tree_from_levels_single_level():
nodes = [
ContentNode(content="a", tokens=5, title="A", index=1, level=1),
ContentNode(content="b", tokens=5, title="B", index=2, level=1),
]
tree = build_tree_from_levels(nodes)
assert len(tree) == 2
assert tree[0]["title"] == "A"
assert tree[1]["title"] == "B"
def test_build_tree_from_levels_deep_nesting():
nodes = [
ContentNode(content="h1", tokens=5, title="H1", index=1, level=1),
ContentNode(content="h2", tokens=5, title="H2", index=2, level=2),
ContentNode(content="h3", tokens=5, title="H3", index=3, level=3),
]
tree = build_tree_from_levels(nodes)
assert len(tree) == 1
assert tree[0]["title"] == "H1"
assert len(tree[0]["nodes"]) == 1
assert tree[0]["nodes"][0]["title"] == "H2"
assert len(tree[0]["nodes"][0]["nodes"]) == 1
assert tree[0]["nodes"][0]["nodes"][0]["title"] == "H3"
def test_content_based_pipeline_does_not_raise():
"""_content_based_pipeline should delegate to tree_parser, not raise NotImplementedError."""
fake_tree = [{"title": "Intro", "start_index": 1, "end_index": 2, "nodes": []}]
async def fake_tree_parser(page_list, opt, doc=None, logger=None):
return fake_tree
page_list = [("Page 1 text", 50), ("Page 2 text", 60)]
from types import SimpleNamespace
opt = SimpleNamespace(model="test-model")
with patch("pageindex.index.page_index.tree_parser", new=fake_tree_parser):
result = asyncio.run(_content_based_pipeline(page_list, opt))
assert result == fake_tree
def test_null_logger_methods():
"""NullLogger should have info/error/debug and not raise."""
logger = _NullLogger()
logger.info("test message")
logger.error("test error")
logger.debug("test debug")
logger.info({"key": "value"})
def test_check_title_appearance_tolerates_out_of_range_physical_index():
"""An LLM-emitted physical_index outside page_list must be marked 'no', not
raise IndexError (which happens during task construction, outside the
gather's return_exceptions protection, and would abort the whole build)."""
from pageindex.index.page_index import check_title_appearance_in_start_concurrent
page_list = [("only page text", 3)] # length 1
structure = [
{"title": "A", "physical_index": 5}, # out of range -> would IndexError
{"title": "B", "physical_index": 0}, # 0 -> would wrap to page_list[-1]
{"title": "C", "physical_index": None}, # missing
{"title": "D"}, # no physical_index key at all
]
result = asyncio.run(
check_title_appearance_in_start_concurrent(structure, page_list)
)
assert all(item["appear_start"] == "no" for item in result)