From a6178050fb8660265e43c522b961bbbc5b7e968d Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Wed, 25 Nov 2026 14:11:11 +0530 Subject: [PATCH 1/4] Grep matches literal line endings in indexed source Keep retained terminators for exact alternatives that request them, including the fallback scan for an uncovered literal. Signed-off-by: Lareb Zafar --- docs/features/code-index/operations.md | 3 ++ server/code/app/grep.py | 42 +++++++++++++------ server/code/domain/index/grep_sql.py | 32 ++++++++++++-- server/code/store/index/grep.py | 1 + .../test_code_grep_source_coordinates.py | 29 +++++++++++-- 5 files changed, 88 insertions(+), 19 deletions(-) diff --git a/docs/features/code-index/operations.md b/docs/features/code-index/operations.md index dd095733a8..d63e019c31 100644 --- a/docs/features/code-index/operations.md +++ b/docs/features/code-index/operations.md @@ -119,6 +119,9 @@ A literal batch can recover one missing call alongside other exact literals, such as an existing test name. The exact matches and related source stay in their respective result fields. +A literal can end with `\n` or `\r\n` to match that physical line ending. +The returned match text excludes the terminator. + Use a list for literal alternatives. When a string of call fragments separated by pipes fails to compile as a regex, `related_on_miss` can find qualified uses of one shared member spelling in the same search scope. The `related` block diff --git a/server/code/app/grep.py b/server/code/app/grep.py index 0bc430dc66..0721bcb83e 100644 --- a/server/code/app/grep.py +++ b/server/code/app/grep.py @@ -290,7 +290,10 @@ def _missing_chunk_patterns( deadline: float | None, ) -> list[str]: fold = str if case_sensitive else ascii_lower - remaining = list(dict.fromkeys(fold(pattern) for pattern in patterns if "\n" not in pattern)) + remaining = list( + dict.fromkeys(fold(pattern) for pattern in patterns if "\n" not in pattern[:-1]) + ) + needs_endings = any(literal.endswith("\n") for literal in remaining) scanned = 0 for chunk in chunks: if deadline is not None and time.monotonic() >= deadline: @@ -302,7 +305,12 @@ def _missing_chunk_patterns( break if lines := retained_source_lines(chunk): source = fold("\n".join(line.removesuffix("\n").removesuffix("\r") for line in lines)) - remaining = [literal for literal in remaining if literal not in source] + raw = fold("".join(lines)) if needs_endings else "" + remaining = [ + literal + for literal in remaining + if literal not in (raw if literal.endswith("\n") else source) + ] if not remaining: break return remaining @@ -1100,18 +1108,22 @@ def _matching_source_lines( pattern: str | list[str], line_re: Any, fold_case: Callable[[str], str], -) -> Iterator[tuple[int, str, str]]: - for offset, line in enumerate(lines): - line = line.removesuffix("\n").removesuffix("\r") +) -> Iterator[tuple[int, str, str, str]]: + literals = [pattern] if isinstance(pattern, str) else pattern + plain = [literal for literal in literals if "\n" not in literal] + endings = [ + literal for literal in literals if literal.endswith("\n") and "\n" not in literal[:-1] + ] + for offset, raw in enumerate(lines): + line = raw.removesuffix("\n").removesuffix("\r") hay = fold_case(line) + with_ending = fold_case(raw) if endings else "" if line_re is not None: hit = line_re.search(line) else: - hit = ( - pattern in hay if isinstance(pattern, str) else any(text in hay for text in pattern) - ) + hit = any(text in hay for text in plain) or any(text in with_ending for text in endings) if hit: - yield offset, line, hay + yield offset, line, hay, with_ending def _matching_lines( @@ -1139,7 +1151,7 @@ def _matching_lines( else [fold_case(text) for text in pattern] ) first_hits = ( - dict.fromkeys((literal for literal in pattern if "\n" not in literal), -1) + dict.fromkeys((literal for literal in pattern if "\n" not in literal[:-1]), -1) if priority_limit and line_re is None and isinstance(pattern, list) and len(pattern) > 1 else {} ) @@ -1170,7 +1182,9 @@ def _matching_lines( pending_here = {literal for literal in pending if literal in source} if len(matches) > keep and not pending_here: continue - for off, line, hay in _matching_source_lines(lines, pattern, line_re, fold_case): + for off, line, hay, with_ending in _matching_source_lines( + lines, pattern, line_re, fold_case + ): key = (str(c["path"]), int(c["start_line"] or 1) + off) if match_commits is not None: commit = str(c.get("indexed_commit") or "").rstrip("\0") @@ -1178,7 +1192,11 @@ def _matching_lines( match_commits[key] = "" if key in seen: continue # the same span indexed twice (re-parse race) - new_patterns = {literal for literal in pending_here if literal in hay} + new_patterns = { + literal + for literal in pending_here + if literal in (with_ending if literal.endswith("\n") else hay) + } if len(matches) > keep and not new_patterns: if not pending: return _promote_pattern_hits(matches, first_hits, priority_limit), False diff --git a/server/code/domain/index/grep_sql.py b/server/code/domain/index/grep_sql.py index 5856df755a..64e5b6ba15 100644 --- a/server/code/domain/index/grep_sql.py +++ b/server/code/domain/index/grep_sql.py @@ -73,7 +73,14 @@ def grep_chunks_sql(cond: str, prefix_clause: str, path_sql: str, extra_settings def grep_pattern_chunks_sql( - cond: str, prefix_clause: str, path_sql: str, patterns: str, position: str, extra_settings: str + cond: str, + prefix_clause: str, + path_sql: str, + patterns: str, + position: str, + extra_settings: str, + *, + with_endings: bool = False, ) -> str: """First live chunk with a physical match per uncovered literal.""" inner = newest_live( @@ -81,6 +88,21 @@ def grep_pattern_chunks_sql( "indexed_commit", _where(cond, prefix_clause, path_sql), ) + raw_lines = ( + """ + , arrayMap( + (line, i) -> concat(line, if(i < span OR trailing_lf, char(10), '')), + physical_parts, arrayEnumerate(physical_parts) + ) AS physical_lines_with_endings + """ + if with_endings + else "" + ) + match_lines = ( + "if(endsWith(literals[i], char(10)), physical_lines_with_endings, physical_lines)" + if with_endings + else "physical_lines" + ) return f""" WITH {patterns} AS literals, concat('[', char(9), '-', char(13), char(28), '-', char(32), @@ -101,10 +123,12 @@ def grep_pattern_chunks_sql( splitByChar(char(10), content) AS source_parts, toInt64(end_line) - toInt64(start_line) + 1 AS span, toInt64(endsWith(content, char(10))) AS trailing_lf, + arraySlice(source_parts, -span - trailing_lf, greatest(0, span)) + AS physical_parts, arrayMap( line -> left(line, length(line) - endsWith(line, char(13))), - arraySlice(source_parts, -span - trailing_lf, greatest(0, span)) - ) AS physical_lines + physical_parts + ) AS physical_lines {raw_lines} FROM {inner} AND kind != 'class_skeleton' AND span > 0 AND length(source_parts) >= span + trailing_lf @@ -121,7 +145,7 @@ def grep_pattern_chunks_sql( ) ) ARRAY JOIN arrayFilter( - i -> arrayExists(line -> {position}(line, literals[i]) > 0, physical_lines), + i -> arrayExists(line -> {position}(line, literals[i]) > 0, {match_lines}), arrayEnumerate(literals) ) AS pattern_index GROUP BY pattern_index diff --git a/server/code/store/index/grep.py b/server/code/store/index/grep.py index 0a02a1c8d9..60efc5d6c1 100644 --- a/server/code/store/index/grep.py +++ b/server/code/store/index/grep.py @@ -263,6 +263,7 @@ async def grep_pattern_chunks( pattern_expr, position, code_deadline.break_settings(max_execution_s), + with_endings=any(pattern.endswith("\n") for pattern in patterns), ), { "org": org, diff --git a/tests/integration/test_code_grep_source_coordinates.py b/tests/integration/test_code_grep_source_coordinates.py index d20bb6deb3..a9b4098e4a 100644 --- a/tests/integration/test_code_grep_source_coordinates.py +++ b/tests/integration/test_code_grep_source_coordinates.py @@ -242,8 +242,9 @@ def use(client: Client): @pytest.mark.asyncio @pytest.mark.parametrize("early_hits", [4, 20]) +@pytest.mark.parametrize("tail_pattern", ["def tail_requested", "def tail_requested():\n"]) async def test_coding_grep_keeps_distinct_batch_patterns_on_first_page( - ch_client: Any, monkeypatch: pytest.MonkeyPatch, early_hits: int + ch_client: Any, monkeypatch: pytest.MonkeyPatch, early_hits: int, tail_pattern: str ) -> None: from server.transport.mcp_defaults import mcp_default_arguments @@ -298,6 +299,9 @@ async def test_coding_grep_keeps_distinct_batch_patterns_on_first_page( ("edges/b.py", "real_needle", "real needle source\n"), ("edges/c.py", "trailing_cr", "target\r\n"), ("edges/d.py", "interior_cr", "real target\r rest\n"), + ("endings/a.py", "unterminated", "check_ending()"), + ("endings/b.py", "line_feed", "check_ending()\n"), + ("endings/c.py", "carriage_return", "check_ending()\r\n"), ) ], column_names=[ @@ -324,7 +328,7 @@ async def test_coding_grep_keeps_distinct_batch_patterns_on_first_page( "def REQUESTED", "match_alpha", "match_beta", - "def tail_requested", + tail_pattern, "def forbidden", ], "path_globs": ["src/**"], @@ -350,7 +354,7 @@ async def test_coding_grep_keeps_distinct_batch_patterns_on_first_page( witnesses = await repo.grep_pattern_chunks( org, ns, - ["def REQUESTED", "match_alpha", "match_beta", "def tail_requested", "def forbidden"], + ["def REQUESTED", "match_alpha", "match_beta", tail_pattern, "def forbidden"], case_sensitive=False, path_prefix="", scope=build_scope(path_globs=["src/**"]), @@ -369,6 +373,25 @@ async def test_coding_grep_keeps_distinct_batch_patterns_on_first_page( limit=2, ) assert [row["path"] for row in exact_lines] == ["edges/b.py", "edges/d.py"] + endings = ["check_ending()\n", "check_ending()\r\n"] + ending_witnesses = await repo.grep_pattern_chunks( + org, + ns, + endings, + case_sensitive=True, + path_prefix="endings/", + scope=build_scope(), + exclude_paths=[], + limit=3, + ) + ending_hits = await handle_code_grep( + CodeGrepInput(org=org, namespace=ns, pattern=endings, path_prefix="endings/") + ) + assert [row["path"] for row in ending_witnesses] == ["endings/b.py", "endings/c.py"] + assert [(row["path"], row["line"], row["text"]) for row in ending_hits.matches] == [ + ("endings/b.py", 1, "check_ending()"), + ("endings/c.py", 1, "check_ending()"), + ] async def missing_pool(*args: Any, **kwargs: Any) -> None: return None From 57ccca739d48f29325b67134fa99e5d49d60f126 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Wed, 25 Nov 2026 14:18:26 +0530 Subject: [PATCH 2/4] Grep verifies terminators on split source lines Use the indexed file line count at the same revision to distinguish a real line feed from a synthetic one. Keep ordinary literals on the direct substring path. Signed-off-by: Lareb Zafar --- docs/features/code-index/operations.md | 5 ++- server/code/app/grep.py | 27 ++++++++---- server/code/domain/index/grep_sql.py | 44 ++++++++++++++++--- server/code/store/index/grep.py | 10 ++++- .../test_code_grep_source_coordinates.py | 17 +++++++ 5 files changed, 86 insertions(+), 17 deletions(-) diff --git a/docs/features/code-index/operations.md b/docs/features/code-index/operations.md index d63e019c31..63b91aa070 100644 --- a/docs/features/code-index/operations.md +++ b/docs/features/code-index/operations.md @@ -119,8 +119,9 @@ A literal batch can recover one missing call alongside other exact literals, such as an existing test name. The exact matches and related source stay in their respective result fields. -A literal can end with `\n` or `\r\n` to match that physical line ending. -The returned match text excludes the terminator. +In matches mode, a literal can end with `\n` or `\r\n` to match that physical +line ending. Single-line windows need file metadata from the same indexed +revision to verify the terminator. The returned match text excludes it. Use a list for literal alternatives. When a string of call fragments separated by pipes fails to compile as a regex, `related_on_miss` can find qualified uses diff --git a/server/code/app/grep.py b/server/code/app/grep.py index 0721bcb83e..2b8d7dfe22 100644 --- a/server/code/app/grep.py +++ b/server/code/app/grep.py @@ -281,6 +281,13 @@ class _GrepLineScan: batch_partial_reason: str = "" +def _ends_in_source(row: dict[str, Any]) -> bool: + # A mid-line slice can carry a synthetic LF. The file row counts its + # LF bytes plus one, so a lower coordinate has a physical terminator. + start = int(row["start_line"]) + return start < max(int(row["end_line"]), int(row.get("source_loc") or 0)) + + def _missing_chunk_patterns( patterns: list[str], chunks: list[dict[str, Any]], @@ -305,7 +312,7 @@ def _missing_chunk_patterns( break if lines := retained_source_lines(chunk): source = fold("\n".join(line.removesuffix("\n").removesuffix("\r") for line in lines)) - raw = fold("".join(lines)) if needs_endings else "" + raw = fold("".join(lines)) if needs_endings and _ends_in_source(chunk) else "" remaining = [ literal for literal in remaining @@ -1108,12 +1115,16 @@ def _matching_source_lines( pattern: str | list[str], line_re: Any, fold_case: Callable[[str], str], + *, + endings_proved: bool, ) -> Iterator[tuple[int, str, str, str]]: literals = [pattern] if isinstance(pattern, str) else pattern - plain = [literal for literal in literals if "\n" not in literal] - endings = [ - literal for literal in literals if literal.endswith("\n") and "\n" not in literal[:-1] - ] + endings = ( + [literal for literal in literals if literal.endswith("\n") and "\n" not in literal[:-1]] + if endings_proved and line_re is None + else [] + ) + plain = [literal for literal in literals if "\n" not in literal] if endings else pattern for offset, raw in enumerate(lines): line = raw.removesuffix("\n").removesuffix("\r") hay = fold_case(line) @@ -1121,8 +1132,8 @@ def _matching_source_lines( if line_re is not None: hit = line_re.search(line) else: - hit = any(text in hay for text in plain) or any(text in with_ending for text in endings) - if hit: + hit = plain in hay if isinstance(plain, str) else any(text in hay for text in plain) + if hit or (endings and any(text in with_ending for text in endings)): yield offset, line, hay, with_ending @@ -1183,7 +1194,7 @@ def _matching_lines( if len(matches) > keep and not pending_here: continue for off, line, hay, with_ending in _matching_source_lines( - lines, pattern, line_re, fold_case + lines, pattern, line_re, fold_case, endings_proved=_ends_in_source(c) ): key = (str(c["path"]), int(c["start_line"] or 1) + off) if match_commits is not None: diff --git a/server/code/domain/index/grep_sql.py b/server/code/domain/index/grep_sql.py index 64e5b6ba15..7aa27b0ef6 100644 --- a/server/code/domain/index/grep_sql.py +++ b/server/code/domain/index/grep_sql.py @@ -54,7 +54,29 @@ def _where(cond: str, prefix_clause: str, path_sql: str) -> str: ) -def grep_chunks_sql(cond: str, prefix_clause: str, path_sql: str, extra_settings: str = "") -> str: +def _with_source_loc(inner: str, prefix_clause: str, path_sql: str) -> str: + """Attach the indexed LF count plus one, from the same file revision.""" + return f"""( + SELECT chunks.*, files.loc AS source_loc + FROM (SELECT * FROM {inner}) AS chunks + LEFT ANY JOIN ( + SELECT path, indexed_commit, loc + FROM loom.code_files FINAL + WHERE org = {{org:String}} AND namespace = {{ns:String}} + AND tombstoned_at IS NULL AND lang != 'reference' + {prefix_clause} {path_sql} + ) AS files ON chunks.path = files.path AND chunks.indexed_commit = files.indexed_commit + )""" + + +def grep_chunks_sql( + cond: str, + prefix_clause: str, + path_sql: str, + extra_settings: str = "", + *, + with_endings: bool = False, +) -> str: """mode=matches: whole chunk rows in (path, start_line) order, chunk_id breaking ties so the page edge is deterministic.""" inner = newest_live( @@ -62,9 +84,13 @@ def grep_chunks_sql(cond: str, prefix_clause: str, path_sql: str, extra_settings "indexed_commit", _where(cond, prefix_clause, path_sql), ) + loc_col = "" + if with_endings: + inner = _with_source_loc(inner, prefix_clause, path_sql) + loc_col = ", source_loc" return f""" SELECT path, scope, symbol_ids, kind, start_line, end_line, content, - embedding_model, toString(indexed_commit) AS indexed_commit + embedding_model, toString(indexed_commit) AS indexed_commit{loc_col} FROM {inner} ORDER BY path, start_line, chunk_id LIMIT {{limit:UInt32}} @@ -88,6 +114,10 @@ def grep_pattern_chunks_sql( "indexed_commit", _where(cond, prefix_clause, path_sql), ) + loc = "0" + if with_endings: + inner = _with_source_loc(inner, prefix_clause, path_sql) + loc = "source_loc" raw_lines = ( """ , arrayMap( @@ -99,23 +129,25 @@ def grep_pattern_chunks_sql( else "" ) match_lines = ( - "if(endsWith(literals[i], char(10)), physical_lines_with_endings, physical_lines)" + "if(endsWith(literals[i], char(10)), " + "if(span > 1 OR start_line < source_loc, physical_lines_with_endings, []), physical_lines)" if with_endings else "physical_lines" ) + kind_guard = "WHERE" if with_endings else "AND" return f""" WITH {patterns} AS literals, concat('[', char(9), '-', char(13), char(28), '-', char(32), char(194, 133), char(92), 'p{{Z}}]') AS source_space SELECT hit.1 AS path, hit.2 AS scope, hit.3 AS symbol_ids, hit.4 AS kind, hit.5 AS start_line, hit.6 AS end_line, hit.7 AS content, - hit.8 AS embedding_model, hit.9 AS indexed_commit + hit.8 AS embedding_model, hit.9 AS indexed_commit, hit.10 AS source_loc FROM ( SELECT hit, min(pattern_index) AS first_pattern FROM ( SELECT pattern_index, argMin( tuple(path, scope, symbol_ids, kind, start_line, end_line, content, - embedding_model, toString(indexed_commit)), + embedding_model, toString(indexed_commit), {loc}), tuple(path, start_line, chunk_id, embedding_model) ) AS hit FROM ( @@ -130,7 +162,7 @@ def grep_pattern_chunks_sql( physical_parts ) AS physical_lines {raw_lines} FROM {inner} - AND kind != 'class_skeleton' + {kind_guard} kind != 'class_skeleton' AND span > 0 AND length(source_parts) >= span + trailing_lf AND NOT arrayExists( suffix -> endsWith(content, suffix), diff --git a/server/code/store/index/grep.py b/server/code/store/index/grep.py index 60efc5d6c1..0311ece9ac 100644 --- a/server/code/store/index/grep.py +++ b/server/code/store/index/grep.py @@ -217,7 +217,15 @@ async def grep_chunks( path_sql, path_params = _scope_path_sql(scope) return await self._ch.query_all( grep_sql.grep_chunks_sql( - cond, prefix_clause, path_sql, code_deadline.break_settings(max_execution_s) + cond, + prefix_clause, + path_sql, + code_deadline.break_settings(max_execution_s), + with_endings=not regex + and any( + literal.endswith("\n") + for literal in ([pattern] if isinstance(pattern, str) else pattern) + ), ), { "org": org, diff --git a/tests/integration/test_code_grep_source_coordinates.py b/tests/integration/test_code_grep_source_coordinates.py index a9b4098e4a..374d3acc7d 100644 --- a/tests/integration/test_code_grep_source_coordinates.py +++ b/tests/integration/test_code_grep_source_coordinates.py @@ -299,9 +299,11 @@ async def test_coding_grep_keeps_distinct_batch_patterns_on_first_page( ("edges/b.py", "real_needle", "real needle source\n"), ("edges/c.py", "trailing_cr", "target\r\n"), ("edges/d.py", "interior_cr", "real target\r rest\n"), + ("endings/0.py", "synthetic_end", "check_ending()\n"), ("endings/a.py", "unterminated", "check_ending()"), ("endings/b.py", "line_feed", "check_ending()\n"), ("endings/c.py", "carriage_return", "check_ending()\r\n"), + ("endings/d.py", "older_chunk", "check_ending()\n"), ) ], column_names=[ @@ -320,6 +322,17 @@ async def test_coding_grep_keeps_distinct_batch_patterns_on_first_page( "indexed_commit", ], ) + ch_client.insert( + "loom.code_files", + [ + [org, ns, "endings/0.py", 1, "b" * 40], + [org, ns, "endings/a.py", 1, "b" * 40], + [org, ns, "endings/b.py", 2, "b" * 40], + [org, ns, "endings/c.py", 2, "b" * 40], + [org, ns, "endings/d.py", 2, "c" * 40], + ], + column_names=["org", "namespace", "path", "loc", "indexed_commit"], + ) args = { "org": org, "namespace": ns, @@ -392,6 +405,10 @@ async def test_coding_grep_keeps_distinct_batch_patterns_on_first_page( ("endings/b.py", 1, "check_ending()"), ("endings/c.py", 1, "check_ending()"), ] + scalar_ending = await handle_code_grep( + CodeGrepInput(org=org, namespace=ns, pattern=endings[0], path_prefix="endings/") + ) + assert [row["path"] for row in scalar_ending.matches] == ["endings/b.py"] async def missing_pool(*args: Any, **kwargs: Any) -> None: return None From f4a15beec6e5f142b0f216704ba5d17e6d90e6e9 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Wed, 25 Nov 2026 14:23:45 +0530 Subject: [PATCH 3/4] Exact line endings require physical source coordinates Use live file metadata from the same revision for each line and keep projected excerpts on ordinary literal matching. Signed-off-by: Lareb Zafar --- docs/features/code-index/operations.md | 5 +-- server/code/app/grep.py | 19 +++++----- server/code/domain/index/grep_sql.py | 4 ++- .../test_code_grep_source_coordinates.py | 35 +++++++++++++++---- 4 files changed, 43 insertions(+), 20 deletions(-) diff --git a/docs/features/code-index/operations.md b/docs/features/code-index/operations.md index 63b91aa070..7d5372b413 100644 --- a/docs/features/code-index/operations.md +++ b/docs/features/code-index/operations.md @@ -120,8 +120,9 @@ such as an existing test name. The exact matches and related source stay in their respective result fields. In matches mode, a literal can end with `\n` or `\r\n` to match that physical -line ending. Single-line windows need file metadata from the same indexed -revision to verify the terminator. The returned match text excludes it. +line ending. The check uses file metadata from the same indexed revision. +Notebook projections and reference excerpts support literal text matches. +The returned match text excludes the terminator. Use a list for literal alternatives. When a string of call fragments separated by pipes fails to compile as a regex, `related_on_miss` can find qualified uses diff --git a/server/code/app/grep.py b/server/code/app/grep.py index 2b8d7dfe22..fca06faedd 100644 --- a/server/code/app/grep.py +++ b/server/code/app/grep.py @@ -281,11 +281,10 @@ class _GrepLineScan: batch_partial_reason: str = "" -def _ends_in_source(row: dict[str, Any]) -> bool: - # A mid-line slice can carry a synthetic LF. The file row counts its - # LF bytes plus one, so a lower coordinate has a physical terminator. - start = int(row["start_line"]) - return start < max(int(row["end_line"]), int(row.get("source_loc") or 0)) +def _terminated_lines(row: dict[str, Any]) -> int: + # The file row counts its LF bytes plus one. Each lower coordinate has + # a physical terminator, including when the chunker split a long line. + return max(0, int(row.get("source_loc") or 0) - int(row["start_line"])) def _missing_chunk_patterns( @@ -312,7 +311,7 @@ def _missing_chunk_patterns( break if lines := retained_source_lines(chunk): source = fold("\n".join(line.removesuffix("\n").removesuffix("\r") for line in lines)) - raw = fold("".join(lines)) if needs_endings and _ends_in_source(chunk) else "" + raw = fold("".join(lines[: _terminated_lines(chunk)])) if needs_endings else "" remaining = [ literal for literal in remaining @@ -1116,19 +1115,19 @@ def _matching_source_lines( line_re: Any, fold_case: Callable[[str], str], *, - endings_proved: bool, + terminated_lines: int, ) -> Iterator[tuple[int, str, str, str]]: literals = [pattern] if isinstance(pattern, str) else pattern endings = ( [literal for literal in literals if literal.endswith("\n") and "\n" not in literal[:-1]] - if endings_proved and line_re is None + if terminated_lines and line_re is None else [] ) plain = [literal for literal in literals if "\n" not in literal] if endings else pattern for offset, raw in enumerate(lines): line = raw.removesuffix("\n").removesuffix("\r") hay = fold_case(line) - with_ending = fold_case(raw) if endings else "" + with_ending = fold_case(raw) if endings and offset < terminated_lines else "" if line_re is not None: hit = line_re.search(line) else: @@ -1194,7 +1193,7 @@ def _matching_lines( if len(matches) > keep and not pending_here: continue for off, line, hay, with_ending in _matching_source_lines( - lines, pattern, line_re, fold_case, endings_proved=_ends_in_source(c) + lines, pattern, line_re, fold_case, terminated_lines=_terminated_lines(c) ): key = (str(c["path"]), int(c["start_line"] or 1) + off) if match_commits is not None: diff --git a/server/code/domain/index/grep_sql.py b/server/code/domain/index/grep_sql.py index 7aa27b0ef6..1bb9a51829 100644 --- a/server/code/domain/index/grep_sql.py +++ b/server/code/domain/index/grep_sql.py @@ -64,6 +64,7 @@ def _with_source_loc(inner: str, prefix_clause: str, path_sql: str) -> str: FROM loom.code_files FINAL WHERE org = {{org:String}} AND namespace = {{ns:String}} AND tombstoned_at IS NULL AND lang != 'reference' + AND NOT endsWith(lower(path), '.ipynb') {prefix_clause} {path_sql} ) AS files ON chunks.path = files.path AND chunks.indexed_commit = files.indexed_commit )""" @@ -130,7 +131,8 @@ def grep_pattern_chunks_sql( ) match_lines = ( "if(endsWith(literals[i], char(10)), " - "if(span > 1 OR start_line < source_loc, physical_lines_with_endings, []), physical_lines)" + "arraySlice(physical_lines_with_endings, 1, " + "greatest(0, toInt64(ifNull(source_loc, 0)) - toInt64(start_line))), physical_lines)" if with_endings else "physical_lines" ) diff --git a/tests/integration/test_code_grep_source_coordinates.py b/tests/integration/test_code_grep_source_coordinates.py index 374d3acc7d..b6ea9219d4 100644 --- a/tests/integration/test_code_grep_source_coordinates.py +++ b/tests/integration/test_code_grep_source_coordinates.py @@ -287,7 +287,7 @@ async def test_coding_grep_keeps_distinct_batch_patterns_on_first_page( "function", scope, 1, - 1, + 2 if path.startswith("projected/") else 1, content, [0.0] * settings.embedding_dim, 1, @@ -304,6 +304,8 @@ async def test_coding_grep_keeps_distinct_batch_patterns_on_first_page( ("endings/b.py", "line_feed", "check_ending()\n"), ("endings/c.py", "carriage_return", "check_ending()\r\n"), ("endings/d.py", "older_chunk", "check_ending()\n"), + ("projected/a.reference", "", "check_ending()\n… clipped reference\n"), + ("projected/b.ipynb", "cell", "def cell():\n check_ending()\n"), ) ], column_names=[ @@ -325,13 +327,15 @@ async def test_coding_grep_keeps_distinct_batch_patterns_on_first_page( ch_client.insert( "loom.code_files", [ - [org, ns, "endings/0.py", 1, "b" * 40], - [org, ns, "endings/a.py", 1, "b" * 40], - [org, ns, "endings/b.py", 2, "b" * 40], - [org, ns, "endings/c.py", 2, "b" * 40], - [org, ns, "endings/d.py", 2, "c" * 40], + [org, ns, "endings/0.py", "python", 1, "b" * 40], + [org, ns, "endings/a.py", "python", 1, "b" * 40], + [org, ns, "endings/b.py", "python", 2, "b" * 40], + [org, ns, "endings/c.py", "python", 2, "b" * 40], + [org, ns, "endings/d.py", "python", 2, "c" * 40], + [org, ns, "projected/a.reference", "reference", 3, "b" * 40], + [org, ns, "projected/b.ipynb", "python", 5, "b" * 40], ], - column_names=["org", "namespace", "path", "loc", "indexed_commit"], + column_names=["org", "namespace", "path", "lang", "loc", "indexed_commit"], ) args = { "org": org, @@ -409,6 +413,23 @@ async def test_coding_grep_keeps_distinct_batch_patterns_on_first_page( CodeGrepInput(org=org, namespace=ns, pattern=endings[0], path_prefix="endings/") ) assert [row["path"] for row in scalar_ending.matches] == ["endings/b.py"] + projected = CodeGrepInput(org=org, namespace=ns, pattern=endings, path_prefix="projected/") + assert not (await handle_code_grep(projected)).matches + plain = await handle_code_grep(projected.model_copy(update={"pattern": "check_ending()"})) + assert [row["path"] for row in plain.matches] == [ + "projected/a.reference", + "projected/b.ipynb", + ] + assert not await repo.grep_pattern_chunks( + org, + ns, + endings, + case_sensitive=True, + path_prefix="projected/", + scope=build_scope(), + exclude_paths=[], + limit=3, + ) async def missing_pool(*args: Any, **kwargs: Any) -> None: return None From c5e4c8f9add520ea0953893c9192597017e9d4ad Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Wed, 25 Nov 2026 14:39:49 +0530 Subject: [PATCH 4/4] Verified grep endings keep their scan slots and source proof Filter projected chunks out of ending-only pools and carry the same file revision proof through skeleton recovery. Signed-off-by: Lareb Zafar --- server/code/app/grep_source.py | 8 +++ server/code/domain/index/grep_sql.py | 3 ++ server/code/store/index/grep.py | 9 ++-- .../test_code_grep_source_coordinates.py | 51 ++++++++++++++++++- 4 files changed, 64 insertions(+), 7 deletions(-) diff --git a/server/code/app/grep_source.py b/server/code/app/grep_source.py index 1e6047fc68..b13788617a 100644 --- a/server/code/app/grep_source.py +++ b/server/code/app/grep_source.py @@ -194,6 +194,11 @@ async def recover_source_chunks( recovered[key] = [dict(row, path=path, embedding_model=model) for row in rows] if not recovered: return chunks + source_locs = { + (row["path"], row.get("indexed_commit")): loc + for row in chunks + if (loc := row.get("source_loc")) + } output = [ row for row in chunks @@ -202,6 +207,9 @@ async def recover_source_chunks( not in recovered ] for rows in recovered.values(): + for row in rows: + if loc := source_locs.get((row["path"], row.get("indexed_commit"))): + row["source_loc"] = loc output.extend(rows) output.sort(key=lambda row: (str(row["path"]), int(row["start_line"]), int(row["end_line"]))) return output diff --git a/server/code/domain/index/grep_sql.py b/server/code/domain/index/grep_sql.py index 1bb9a51829..4d2b81fc42 100644 --- a/server/code/domain/index/grep_sql.py +++ b/server/code/domain/index/grep_sql.py @@ -77,6 +77,7 @@ def grep_chunks_sql( extra_settings: str = "", *, with_endings: bool = False, + endings_only: bool = False, ) -> str: """mode=matches: whole chunk rows in (path, start_line) order, chunk_id breaking ties so the page edge is deterministic.""" @@ -89,10 +90,12 @@ def grep_chunks_sql( if with_endings: inner = _with_source_loc(inner, prefix_clause, path_sql) loc_col = ", source_loc" + valid_positions = "WHERE start_line < ifNull(source_loc, 0)" if endings_only else "" return f""" SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, toString(indexed_commit) AS indexed_commit{loc_col} FROM {inner} + {valid_positions} ORDER BY path, start_line, chunk_id LIMIT {{limit:UInt32}} {GREP_SCAN_SETTINGS}{extra_settings} diff --git a/server/code/store/index/grep.py b/server/code/store/index/grep.py index 0311ece9ac..c02bc55e95 100644 --- a/server/code/store/index/grep.py +++ b/server/code/store/index/grep.py @@ -215,17 +215,16 @@ async def grep_chunks( cond, cond_params = _scan_predicate(pattern, regex=regex, case_sensitive=case_sensitive) prefix_clause = "AND startsWith(path, {prefix:String})" if path_prefix else "" path_sql, path_params = _scope_path_sql(scope) + literals = [pattern] if isinstance(pattern, str) else pattern + endings = [literal for literal in literals if not regex and literal.endswith("\n")] return await self._ch.query_all( grep_sql.grep_chunks_sql( cond, prefix_clause, path_sql, code_deadline.break_settings(max_execution_s), - with_endings=not regex - and any( - literal.endswith("\n") - for literal in ([pattern] if isinstance(pattern, str) else pattern) - ), + with_endings=bool(endings), + endings_only=bool(endings) and len(endings) == len(literals), ), { "org": org, diff --git a/tests/integration/test_code_grep_source_coordinates.py b/tests/integration/test_code_grep_source_coordinates.py index b6ea9219d4..89771c6432 100644 --- a/tests/integration/test_code_grep_source_coordinates.py +++ b/tests/integration/test_code_grep_source_coordinates.py @@ -240,6 +240,36 @@ def use(client: Client): assert next_focused.matches == next_exact.matches and next_focused.related is None +@pytest.mark.asyncio +async def test_ending_proof_survives_recovery_of_nested_class_source( + ch_client, monkeypatch +) -> None: + org, ns = unique_org("grep-recovered-ending"), "source" + monkeypatch.setattr(settings, "code_intel_enabled", True) + embedder = FakeNGramEmbedder(dim=settings.embedding_dim) + monkeypatch.setattr(settings, "embedding_model", embedder.model_name) + await get_client().connect() + repo = CodeRepo() + path = "nested.py" + pattern = "def exact():\n" + await ingest_file( + repo, + org, + ns, + path=path, + source=b"class Outer:\n class Middle:\n class Inner:\n def exact():\n return 1\n", + commit_sha="b" * 40, + embedding_model=embedder.model_name, + embedder=embedder, + ) + pool = await repo.grep_chunks(org, ns, pattern, limit=3) + assert [row["kind"] for row in pool] == ["class_skeleton"] * 3 + result = await handle_code_grep(CodeGrepInput(org=org, namespace=ns, pattern=pattern, limit=1)) + assert [(row["path"], row["line"], row["text"]) for row in result.matches] == [ + (path, 4, "def exact():"), + ] + + @pytest.mark.asyncio @pytest.mark.parametrize("early_hits", [4, 20]) @pytest.mark.parametrize("tail_pattern", ["def tail_requested", "def tail_requested():\n"]) @@ -306,6 +336,8 @@ async def test_coding_grep_keeps_distinct_batch_patterns_on_first_page( ("endings/d.py", "older_chunk", "check_ending()\n"), ("projected/a.reference", "", "check_ending()\n… clipped reference\n"), ("projected/b.ipynb", "cell", "def cell():\n check_ending()\n"), + ("projected/c.ipynb", "cell", "def cell():\n check_ending()\n"), + ("projected/z.py", "physical", "def physical():\n check_ending()\n"), ) ], column_names=[ @@ -334,6 +366,8 @@ async def test_coding_grep_keeps_distinct_batch_patterns_on_first_page( [org, ns, "endings/d.py", "python", 2, "c" * 40], [org, ns, "projected/a.reference", "reference", 3, "b" * 40], [org, ns, "projected/b.ipynb", "python", 5, "b" * 40], + [org, ns, "projected/c.ipynb", "python", 5, "b" * 40], + [org, ns, "projected/z.py", "python", 3, "b" * 40], ], column_names=["org", "namespace", "path", "lang", "loc", "indexed_commit"], ) @@ -413,12 +447,19 @@ async def test_coding_grep_keeps_distinct_batch_patterns_on_first_page( CodeGrepInput(org=org, namespace=ns, pattern=endings[0], path_prefix="endings/") ) assert [row["path"] for row in scalar_ending.matches] == ["endings/b.py"] - projected = CodeGrepInput(org=org, namespace=ns, pattern=endings, path_prefix="projected/") + projected = CodeGrepInput( + org=org, + namespace=ns, + pattern=endings, + path_prefix="projected/", + exclude_globs=["projected/z.py"], + ) assert not (await handle_code_grep(projected)).matches plain = await handle_code_grep(projected.model_copy(update={"pattern": "check_ending()"})) assert [row["path"] for row in plain.matches] == [ "projected/a.reference", "projected/b.ipynb", + "projected/c.ipynb", ] assert not await repo.grep_pattern_chunks( org, @@ -426,10 +467,16 @@ async def test_coding_grep_keeps_distinct_batch_patterns_on_first_page( endings, case_sensitive=True, path_prefix="projected/", - scope=build_scope(), + scope=build_scope(exclude_globs=["projected/z.py"]), exclude_paths=[], limit=3, ) + physical = await handle_code_grep( + CodeGrepInput( + org=org, namespace=ns, pattern=endings[0], path_prefix="projected/", limit=1 + ) + ) + assert [row["path"] for row in physical.matches] == ["projected/z.py"] async def missing_pool(*args: Any, **kwargs: Any) -> None: return None