HKUDS/Vibe-Trading · error · ValueError

inverted page range: {part!r}

Error message

inverted page range: {part!r}

What it means

Raised when parsing a page-range token like 'start-end' where start > end, e.g. '5-2'. The parser mirrors alpha_bench_tool._parse_period and refuses inverted ranges rather than silently returning an empty page set.

Source

Thrown at agent/src/tools/doc_reader_tool.py:124

    """Parse '1-10' / '5' / '1,3,5-8' into zero-based indices."""
    # Word/LLM paste often uses en/em/minus dashes; treat as ASCII hyphen.
    pages_str = (
        pages_str.replace("\u2013", "-")
        .replace("\u2014", "-")
        .replace("\u2212", "-")
    )
    out: list[int] = []
    for part in pages_str.split(","):
        part = part.strip()
        if not part:
            continue
        if "-" in part:
            start, end = part.split("-", 1)
            start_1 = int(start.strip())
            end_1 = int(end.strip())
            # Mirror alpha_bench_tool._parse_period: reject inverted ranges.
            if start_1 > end_1:
                raise ValueError(f"inverted page range: {part!r}")
            s = max(start_1 - 1, 0)
            e = min(end_1, total)
            out.extend(range(s, e))
        elif part.isdigit():
            out.append(int(part) - 1)
    return sorted(set(out))


def _read_pdf(path: Path, pages: str, min_text_per_page: int = _MIN_TEXT_PER_PAGE) -> str:
    """Extract PDF text; OCR pages with too little text."""
    try:
        import pypdfium2 as pdfium  # type: ignore
    except ImportError:
        return _err("pypdfium2 not installed; cannot read PDF")

    doc = pdfium.PdfDocument(str(path))
    try:
        total_pages = len(doc)

View on GitHub (pinned to 80ffdda44c)

Solutions

  1. Swap the endpoints so the smaller page comes first (e.g. '2-5')
  2. If generating ranges in code, assert start <= end before formatting the string

Example fix

# before
read(path, pages="5-2")
# after
read(path, pages="2-5")
Defensive patterns

Strategy: validation

Validate before calling

import re

def valid_pages(spec: str) -> bool:
    for part in spec.split(","):
        part = part.strip().replace("\u2013", "-").replace("\u2014", "-")
        if "-" in part:
            a, b = part.split("-", 1)
            if not (a.strip().isdigit() and b.strip().isdigit()):
                return False
            if int(a) > int(b):
                return False
    return True

Try / catch

try:
    text = read(path, pages=spec)
except ValueError as exc:
    if "inverted page range" in str(exc):
        text = read(path)  # fall back to full document
    else:
        raise

Prevention

When it happens

Trigger: Calling the doc reader with pages='5-2', pages='10-3'; also triggers with dash forms including em/en dashes that resolve to inverted numbers, e.g. '5–2'.

Common situations: User typos in a pages= argument; LLM agents transposing numbers; swapped start/end variables when building the range programmatically.

Related errors


AI-assisted analysis of HKUDS/Vibe-Trading@80ffdda44c (2026-08-28). Data as JSON: /api/errors/1765125e8e2ec62e. Report an issue: GitHub.