Repository navigation
refactor(phase-5): core domain logic for retrieval, chunking, prompts #352
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 6 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
3eab2f0
core/prompts: add pure builders + disk template loader (5C)
EnjoyBacon7 6a3b508
core/chunking: add markdown utils + RecursiveSplitter (5B)
EnjoyBacon7 49f5fdc
core/retrieval: add retriever strategies, pipeline, RRF, searcher por…
EnjoyBacon7 246d763
phase-5: add bookkeeping (decision log + FORWARD_PORT_LOG) + ruff format
EnjoyBacon7 3a75727
test(core/prompts): cover contextualization, query rewriter, template…
EnjoyBacon7 f36aa02
fix(core): post-review hardening for phase-5 modules
EnjoyBacon7 4a8f767
refactor(phase-5.15): convert legacy chunker/retriever/prompts to shi…
EnjoyBacon7 be72516
fix(core): address ultrareview findings on phase-5
EnjoyBacon7 f7f0602
fix(core/chunk): coerce Milvus int _id to string in from_langchain
EnjoyBacon7 88c749a
fix(services/milvus-shim): use openrag-rooted ray_utils import
EnjoyBacon7 1a06f69
fix(core/chunk): drop misleading 'Logged via repr' comment in fallback
EnjoyBacon7 97570f7
docs(decision-log): record phase-5 deviations on text-splitter dep an…
EnjoyBacon7 998e166
refactor(core/retrieval): split retriever_registry into its own module
EnjoyBacon7 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| # Forward Port Log | ||
|
|
||
| Tracks `dev` changes during MODE 2 isolation (Phases 5-9). | ||
| Each entry: what changed on `dev`, whether it was forward-ported or deferred | ||
| to the cutover re-implementation queue. | ||
|
|
||
| > Created retroactively at the start of Phase 5 (2026-04-29). The Phase 0-4 | ||
| > Mode 1 work merged from `dev` cleanly so this log starts empty. | ||
|
|
||
| --- | ||
|
|
||
| ## Forward-ported (critical) | ||
|
|
||
| _Security fixes, data-loss bugs, production outages re-implemented against | ||
| the new architecture. Each entry pairs the dev commit with the refactor | ||
| commit so a reviewer can audit equivalence._ | ||
|
|
||
| (none yet) | ||
|
|
||
| ## Deferred to cutover (features) | ||
|
|
||
| _Non-critical changes that landed on `dev` during MODE 2. These will be | ||
| re-implemented directly in the new architecture during MODE 3 (Phases | ||
| 10-12) or post-cutover. List the dev PR number / commit and the target | ||
| location in the new layout._ | ||
|
|
||
| (none yet) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,24 @@ | ||
| """ChunkingStrategy ABC + registry.""" | ||
| """ChunkingStrategy ABC + registry + concrete strategies.""" | ||
|
|
||
| from .chunking_strategy import ChunkingStrategy | ||
| from .markdown_utils import ( | ||
| MDElement, | ||
| chunk_table, | ||
| get_chunk_page_number, | ||
| parse_markdown_table, | ||
| split_md_elements, | ||
| ) | ||
| from .recursive import BaseChunker, RecursiveSplitter | ||
| from .registry import chunking_registry | ||
|
|
||
| __all__ = ["ChunkingStrategy", "chunking_registry"] | ||
| __all__ = [ | ||
| "ChunkingStrategy", | ||
| "chunking_registry", | ||
| "BaseChunker", | ||
| "RecursiveSplitter", | ||
| "MDElement", | ||
| "chunk_table", | ||
| "get_chunk_page_number", | ||
| "parse_markdown_table", | ||
| "split_md_elements", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,224 @@ | ||
| """Markdown parsing primitives used by chunking strategies. | ||
|
|
||
| Pure functions extracted from ``components/indexer/chunker/utils.py``. They | ||
| recognize page markers, image-description blocks, and tables; split a | ||
| markdown document into typed elements; and split oversize tables along | ||
| their semantic groups. | ||
|
|
||
| This module has no IO and no config dependency. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import re | ||
| from collections.abc import Callable | ||
| from dataclasses import dataclass | ||
| from typing import Literal | ||
|
|
||
| from openrag.core.utils.text import clean_markdown_table_spacing | ||
|
|
||
| # Header + delimiter + at least one row. | ||
| TABLE_RE = re.compile( | ||
| r"((?:^|\n)\|.*?\|\r?\n\|\s*[:-]+(?:\s*\|[:-]+)*\|\r?\n(?:\|.*?\|\r?\n)+)", | ||
| re.DOTALL | re.MULTILINE, | ||
| ) | ||
|
|
||
| # `<image_description>...</image_description>` block injected by the VLM step. | ||
| IMAGE_RE = re.compile(r"(<image_description>(.*?)</image_description>)", re.DOTALL) | ||
|
|
||
| # `[PAGE_N]` page-boundary markers — content BEFORE [PAGE_N] is on page N. | ||
| PAGE_RE = re.compile(r"\[PAGE_(\d+)\]") | ||
|
|
||
|
|
||
| ElementType = Literal["text", "table", "image"] | ||
|
|
||
|
|
||
| @dataclass | ||
| class MDElement: | ||
| """A typed segment of markdown content with optional source page number.""" | ||
|
|
||
| type: ElementType | ||
| content: str | ||
| page_number: int | None = None | ||
|
|
||
| def __repr__(self) -> str: | ||
| return f"MDElement(type={self.type}, page_number={self.page_number}, content={self.content[:100]}...)" | ||
|
|
||
|
|
||
| def span_inside(span: tuple[int, int], container: tuple[int, int]) -> bool: | ||
| """Return True if ``span`` is fully contained within ``container``.""" | ||
| return container[0] <= span[0] and span[1] <= container[1] | ||
|
|
||
|
|
||
| def get_page_number(position: int, page_markers: list[tuple[int, int]]) -> int: | ||
| """Look up the page number for a position in the source markdown. | ||
|
|
||
| ``page_markers`` is a sorted list of ``(offset, page_n)`` tuples taken | ||
| from ``[PAGE_N]`` matches. Content AFTER ``[PAGE_N]`` belongs to page | ||
| ``N + 1``; content before any marker is page 1. | ||
| """ | ||
| current_page = 1 | ||
| for marker_pos, page_num in page_markers: | ||
| if position >= marker_pos: | ||
| current_page = page_num + 1 | ||
| else: | ||
| break | ||
| return current_page | ||
|
|
||
|
|
||
| def split_md_elements(md_text: str) -> list[MDElement]: | ||
| """Split markdown into ``MDElement`` segments of text, table, and image. | ||
|
|
||
| Tables nested inside an ``<image_description>`` block are NOT extracted | ||
| as separate elements — they belong to the image. | ||
| """ | ||
| page_markers: list[tuple[int, int]] = [] | ||
| for match in PAGE_RE.finditer(md_text): | ||
| page_markers.append((match.start(), int(match.group(1)))) | ||
| page_markers.sort() | ||
|
|
||
| all_matches: list[tuple[tuple[int, int], ElementType, str, int | None]] = [] | ||
| image_spans: list[tuple[int, int]] = [] | ||
|
|
||
| for match in IMAGE_RE.finditer(md_text): | ||
| span = match.span() | ||
| page_num = get_page_number(span[0], page_markers) | ||
| all_matches.append((span, "image", match.group(1).strip(), page_num)) | ||
| image_spans.append(span) | ||
|
|
||
| for match in TABLE_RE.finditer(md_text): | ||
| span = match.span() | ||
| if not any(span_inside(span, image_span) for image_span in image_spans): | ||
| page_num = get_page_number(span[0], page_markers) | ||
| all_matches.append((span, "table", match.group(1).strip(), page_num)) | ||
|
|
||
| all_matches.sort(key=lambda x: x[0][0]) | ||
|
|
||
| parts: list[MDElement] = [] | ||
| last = 0 | ||
|
|
||
| for (start, end), match_type, content, page_num in all_matches: | ||
| if start > last: | ||
| text_segment = md_text[last:start] | ||
| if text_segment.strip(): | ||
| parts.append(MDElement(type="text", content=text_segment.strip())) | ||
| parts.append(MDElement(type=match_type, content=content, page_number=page_num)) | ||
| last = end | ||
|
|
||
| if last < len(md_text): | ||
| remaining = md_text[last:] | ||
| if remaining.strip(): | ||
| parts.append(MDElement(type="text", content=remaining.strip())) | ||
|
|
||
| return parts | ||
|
|
||
|
|
||
| def get_chunk_page_number(chunk_str: str, previous_chunk_ending_page: int = 1) -> dict[str, int]: | ||
| """Resolve start and end pages for a text chunk containing ``[PAGE_N]`` markers. | ||
|
|
||
| Returns ``{"start_page": int, "end_page": int}``. | ||
| """ | ||
| matches = list(PAGE_RE.finditer(chunk_str)) | ||
|
|
||
| if not matches: | ||
| return { | ||
| "start_page": previous_chunk_ending_page, | ||
| "end_page": previous_chunk_ending_page, | ||
| } | ||
|
|
||
| first_match = matches[0] | ||
| last_match = matches[-1] | ||
| last_char_idx = len(chunk_str) - 1 | ||
|
|
||
| if first_match.start() == 0: | ||
| start_page = int(first_match.group(1)) + 1 | ||
| else: | ||
| start_page = previous_chunk_ending_page | ||
|
|
||
| if last_match.end() - 1 == last_char_idx: | ||
| end_page = int(last_match.group(1)) | ||
| else: | ||
| end_page = int(last_match.group(1)) + 1 | ||
|
|
||
| return {"start_page": start_page, "end_page": end_page} | ||
|
|
||
|
|
||
| def parse_markdown_table(markdown_table: str) -> tuple[list[str], list[list[str]]]: | ||
| """Parse a markdown table into header lines + groups of rows. | ||
|
|
||
| Rows are grouped by the first column ("Domain"): a non-empty Domain | ||
| starts a new group, an empty Domain continues the current group. This | ||
| preserves the document's logical structure when chunking large tables. | ||
| """ | ||
| lines = markdown_table.strip().split("\n") | ||
| header_lines = lines[:2] | ||
| data_rows = lines[2:] | ||
|
|
||
| groups: list[list[str]] = [] | ||
| current_group: list[str] = [] | ||
|
|
||
| for row in data_rows: | ||
| cells = [cell.strip() for cell in row.split("|")[1:-1]] | ||
| if not cells: | ||
| continue | ||
| domain = cells[0] | ||
| if domain: | ||
| if current_group: | ||
| groups.append(current_group) | ||
| current_group = [row] | ||
| else: | ||
| current_group.append(row) | ||
|
|
||
| if current_group: | ||
| groups.append(current_group) | ||
|
|
||
| return header_lines, groups | ||
|
|
||
|
|
||
| def chunk_table( | ||
| table_element: MDElement, | ||
| chunk_size: int, | ||
| length_function: Callable[[str], int], | ||
| ) -> list[MDElement]: | ||
| """Split an oversize markdown table into multiple ``MDElement`` chunks. | ||
|
|
||
| Each chunk repeats the table header. When a new chunk starts, the LAST | ||
| row of the previous chunk is replayed as overlap so context is preserved | ||
| across the boundary. | ||
| """ | ||
| txt = clean_markdown_table_spacing(table_element.content) | ||
| header_lines, groups = parse_markdown_table(txt) | ||
|
|
||
| header_text = "\n".join(header_lines) | ||
| group_texts = ["\n".join(g) for g in groups] | ||
|
|
||
| header_ntoks = length_function(header_text) | ||
| groups_ntoks = [length_function(g) for g in group_texts] | ||
|
|
||
| subtables: list[str] = [] | ||
| body_rows: list[str] = [] # rows under the current chunk, header excluded | ||
| body_size = 0 | ||
| prev_last_row: str | None = None | ||
|
|
||
| for group_txt, g_ntoks in zip(group_texts, groups_ntoks, strict=True): | ||
| # Only flush when we actually have body content to flush — otherwise an | ||
| # oversized first group would emit a header-only chunk. | ||
| if body_rows and header_ntoks + body_size + g_ntoks > chunk_size: | ||
| subtables.append("\n".join([header_text, *body_rows])) | ||
| body_rows = [] | ||
| body_size = 0 | ||
| # Replay only the last row of the previous chunk as overlap | ||
| # (matches the docstring contract; prev_last_row is the trailing | ||
| # line of the last admitted group). | ||
| if prev_last_row: | ||
| body_rows.append(prev_last_row) | ||
| body_size += length_function(prev_last_row) | ||
| body_rows.append(group_txt) | ||
| body_size += g_ntoks | ||
| # The "last row" is the trailing line of this group, not the whole group. | ||
| prev_last_row = group_txt.rsplit("\n", 1)[-1] | ||
|
|
||
| if body_rows: | ||
| subtables.append("\n".join([header_text, *body_rows])) | ||
|
|
||
| return [MDElement(type="table", content=subtable, page_number=table_element.page_number) for subtable in subtables] | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.