Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/features/code-index/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
54 changes: 41 additions & 13 deletions server/code/app/grep.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]],
Expand All @@ -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:
Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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 {}
)
Expand Down Expand Up @@ -1170,15 +1192,21 @@ 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")
if match_commits.setdefault(key, commit) != commit:
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
Expand Down
8 changes: 8 additions & 0 deletions server/code/app/grep_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
79 changes: 70 additions & 9 deletions server/code/domain/index/grep_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,59 +54,120 @@ 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(
"path, scope, symbol_ids, kind, start_line, end_line, content, chunk_id, embedding_model, "
"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}
"""


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(
"path, scope, symbol_ids, kind, start_line, end_line, content, chunk_id, embedding_model, "
"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 (
SELECT *,
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),
Expand All @@ -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
Expand Down
10 changes: 9 additions & 1 deletion server/code/store/index/grep.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading