diff --git a/docs/features/code-index/operations.md b/docs/features/code-index/operations.md index dd095733a8..7d5372b413 100644 --- a/docs/features/code-index/operations.md +++ b/docs/features/code-index/operations.md @@ -119,6 +119,11 @@ 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. +In matches mode, a literal can end with `\n` or `\r\n` to match that physical +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 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..fca06faedd 100644 --- a/server/code/app/grep.py +++ b/server/code/app/grep.py @@ -281,6 +281,12 @@ class _GrepLineScan: batch_partial_reason: str = "" +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( patterns: list[str], chunks: list[dict[str, Any]], @@ -290,7 +296,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 +311,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[: _terminated_lines(chunk)])) 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 +1114,26 @@ 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") + *, + 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 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 and offset < terminated_lines 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) - ) - if hit: - yield offset, line, hay + 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 def _matching_lines( @@ -1139,7 +1161,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 +1192,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, terminated_lines=_terminated_lines(c) + ): 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 +1202,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/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 5856df755a..4d2b81fc42 100644 --- a/server/code/domain/index/grep_sql.py +++ b/server/code/domain/index/grep_sql.py @@ -54,7 +54,31 @@ 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' + AND NOT endsWith(lower(path), '.ipynb') + {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, + 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.""" inner = newest_live( @@ -62,10 +86,16 @@ 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" + 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 + 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} @@ -73,7 +103,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,19 +118,41 @@ 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( + (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)), " + "arraySlice(physical_lines_with_endings, 1, " + "greatest(0, toInt64(ifNull(source_loc, 0)) - toInt64(start_line))), 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 ( @@ -101,12 +160,14 @@ 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' + {kind_guard} kind != 'class_skeleton' AND span > 0 AND length(source_parts) >= span + trailing_lf AND NOT arrayExists( suffix -> endsWith(content, suffix), @@ -121,7 +182,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..c02bc55e95 100644 --- a/server/code/store/index/grep.py +++ b/server/code/store/index/grep.py @@ -215,9 +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) + cond, + prefix_clause, + path_sql, + code_deadline.break_settings(max_execution_s), + with_endings=bool(endings), + endings_only=bool(endings) and len(endings) == len(literals), ), { "org": org, @@ -263,6 +270,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..89771c6432 100644 --- a/tests/integration/test_code_grep_source_coordinates.py +++ b/tests/integration/test_code_grep_source_coordinates.py @@ -240,10 +240,41 @@ 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"]) 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 @@ -286,7 +317,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, @@ -298,6 +329,15 @@ 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"), + ("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=[ @@ -316,6 +356,21 @@ 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", "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], + [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"], + ) args = { "org": org, "namespace": ns, @@ -324,7 +379,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 +405,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 +424,59 @@ 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()"), + ] + 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"] + 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, + ns, + endings, + case_sensitive=True, + path_prefix="projected/", + 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