graphlore 0.7.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- graphlore/__init__.py +7 -0
- graphlore/__main__.py +12 -0
- graphlore/agents_md.py +96 -0
- graphlore/algorithms.py +311 -0
- graphlore/apis.py +617 -0
- graphlore/cli.py +133 -0
- graphlore/clients.py +260 -0
- graphlore/config.py +68 -0
- graphlore/embed.py +233 -0
- graphlore/engine.py +379 -0
- graphlore/graph.py +1643 -0
- graphlore/history.py +198 -0
- graphlore/imports.py +581 -0
- graphlore/oauth.py +169 -0
- graphlore/resolve.py +332 -0
- graphlore/review.py +1121 -0
- graphlore/routes.py +1417 -0
- graphlore/scope.py +362 -0
- graphlore/search.py +1070 -0
- graphlore/server.py +8152 -0
- graphlore/spans.py +1254 -0
- graphlore/viewer.html +1649 -0
- graphlore/viz.py +381 -0
- graphlore-0.7.0.dist-info/METADATA +379 -0
- graphlore-0.7.0.dist-info/RECORD +28 -0
- graphlore-0.7.0.dist-info/WHEEL +4 -0
- graphlore-0.7.0.dist-info/entry_points.txt +2 -0
- graphlore-0.7.0.dist-info/licenses/LICENSE +21 -0
graphlore/search.py
ADDED
|
@@ -0,0 +1,1070 @@
|
|
|
1
|
+
"""graphlore's built-in code search: definition-aligned chunks, BM25F, and an
|
|
2
|
+
optional dense tier.
|
|
3
|
+
|
|
4
|
+
The answer to "where is the code that does X" without the semble extra. Two tiers:
|
|
5
|
+
|
|
6
|
+
- **lexical, always on, stdlib only**: an identifier-aware tokenizer
|
|
7
|
+
(``getUserName``, ``get_user_name`` and ``GetUserName`` share a term; their parts
|
|
8
|
+
are terms too) feeding BM25F over three fields — the definition's name and
|
|
9
|
+
qualified name, the file path, and the body — plus a small overlay built from
|
|
10
|
+
the graph (the docstring a node carries, the names of what it calls and what
|
|
11
|
+
calls it).
|
|
12
|
+
- **dense, optional** (``[embed]`` extra, :mod:`graphlore.embed`): a static
|
|
13
|
+
embedding of each chunk, fused with the lexical ranking by weighted reciprocal
|
|
14
|
+
rank. When the extra or the model is missing the index answers lexically and
|
|
15
|
+
``info()`` says why.
|
|
16
|
+
|
|
17
|
+
What semble does not have: chunks are the span engine's definitions (one per
|
|
18
|
+
function, method or class, a container holding only its own lines), so every hit
|
|
19
|
+
joins to its graph node exactly; module-level code between definitions becomes
|
|
20
|
+
low-weight ``module`` chunks; files the span engine cannot read (another language
|
|
21
|
+
without ``[treesitter]``) are cut into fixed windows and counted.
|
|
22
|
+
|
|
23
|
+
The index is built once per project and refreshed incrementally: each call stats
|
|
24
|
+
the project's files and re-chunks only the ones whose (mtime, size) changed.
|
|
25
|
+
|
|
26
|
+
The hot loop sits behind :class:`_Kernel` (``tokenize`` and ``bm25f``), whose
|
|
27
|
+
reference is :class:`_PyKernel`. An optional accelerator module
|
|
28
|
+
(``graphlore_accel``, not shipped) that exposes ``KERNEL_ABI == 1`` and a
|
|
29
|
+
``Kernel`` class with the same two methods replaces it; every logarithm is
|
|
30
|
+
computed here, so a port does only additions, multiplications and divisions and
|
|
31
|
+
can return bit-identical scores (``tests/fixtures/search_golden.json``).
|
|
32
|
+
|
|
33
|
+
Depends on config, graph, spans, scope, review (the walk's skip lists) and embed.
|
|
34
|
+
"""
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import heapq
|
|
38
|
+
import math
|
|
39
|
+
import os
|
|
40
|
+
import re
|
|
41
|
+
import threading
|
|
42
|
+
from collections import Counter
|
|
43
|
+
from collections.abc import Iterable
|
|
44
|
+
from dataclasses import dataclass
|
|
45
|
+
from pathlib import Path
|
|
46
|
+
from typing import Any, NamedTuple, Protocol
|
|
47
|
+
|
|
48
|
+
from . import config, embed
|
|
49
|
+
from .graph import (
|
|
50
|
+
_CALL_RELATIONS,
|
|
51
|
+
_edge_ends,
|
|
52
|
+
_is_test_path,
|
|
53
|
+
_node_file,
|
|
54
|
+
_node_id,
|
|
55
|
+
_node_label,
|
|
56
|
+
_node_line,
|
|
57
|
+
_rel,
|
|
58
|
+
)
|
|
59
|
+
from .review import _CODE_EXTS, _MENTION_SKIP_DIRS
|
|
60
|
+
from .scope import _minified_by_content, _vendored_by_path
|
|
61
|
+
from .spans import _norm_relpath, _resolve_in_project, _spans_for_file
|
|
62
|
+
|
|
63
|
+
# Source files the index reads: the review layer's code extensions plus a few
|
|
64
|
+
# languages that have no graph nodes of their own but are still code to find.
|
|
65
|
+
_SEARCH_EXTS = _CODE_EXTS | frozenset({
|
|
66
|
+
".vue", ".svelte", ".dart", ".hs", ".ml", ".mli", ".r", ".jl", ".erl", ".hrl",
|
|
67
|
+
".clj", ".cljs", ".pl", ".pm", ".sh", ".bash", ".sql", ".groovy", ".fs", ".nim",
|
|
68
|
+
})
|
|
69
|
+
_SEARCH_MAX_FILE_BYTES = 1_000_000
|
|
70
|
+
_SEARCH_MAX_FILES = 20_000
|
|
71
|
+
_SEARCH_MAX_CHUNKS = 200_000
|
|
72
|
+
# Files without spans, and long runs of module-level code, are cut into windows.
|
|
73
|
+
_WINDOW_LINES = 40
|
|
74
|
+
# Fewer non-blank uncovered lines than this between definitions are not a chunk.
|
|
75
|
+
_GAP_MIN_LINES = 3
|
|
76
|
+
# Module-level code (imports, constants, a script's body) says the file mentions
|
|
77
|
+
# the topic more often than that it answers the question.
|
|
78
|
+
_MODULE_WEIGHT = 0.5
|
|
79
|
+
|
|
80
|
+
# BM25F. Name and path are short fields: barely length-normalised.
|
|
81
|
+
_K1 = 1.2
|
|
82
|
+
_W_NAME, _W_PATH, _W_BODY = 4.0, 1.5, 1.0
|
|
83
|
+
_B_NAME, _B_PATH, _B_BODY = 0.3, 0.3, 0.75
|
|
84
|
+
# The graph overlay (docstring and call-neighbour names) is its own BM25 index,
|
|
85
|
+
# added at this weight.
|
|
86
|
+
_OVERLAY_WEIGHT = 0.6
|
|
87
|
+
_OVERLAY_NEIGHBOURS = 12
|
|
88
|
+
# A symbol query that is a chunk's whole qualified name, or its last component.
|
|
89
|
+
_EXACT_QUALNAME_BOOST = 3.0
|
|
90
|
+
_EXACT_NAME_BOOST = 2.0
|
|
91
|
+
_QUERY_MAX_TERMS = 64
|
|
92
|
+
|
|
93
|
+
# Fusion of the lexical and dense rankings: weighted reciprocal rank.
|
|
94
|
+
_RRF_K = 60
|
|
95
|
+
_FUSION_DEPTH = 50
|
|
96
|
+
# (lexical, dense) weight by query kind: a name is found by its spelling; for a
|
|
97
|
+
# question both rankings count the same. The defaults of this block were chosen on
|
|
98
|
+
# 19 of the 63 repositories of benchmarks/search.py (one per language) and checked
|
|
99
|
+
# on the other 44 (docs/benchmark.md).
|
|
100
|
+
_FUSION_WEIGHTS = {"symbol": (1.0, 0.3), "natural": (1.0, 1.0), "code": (1.0, 1.0)}
|
|
101
|
+
# Rank fusion forgets how far ahead an exact name match was in BM25: on a symbol
|
|
102
|
+
# query a chunk named exactly like the query gains this many first places.
|
|
103
|
+
_EXACT_FUSED_BONUS = 1.0
|
|
104
|
+
|
|
105
|
+
# find_related on the lexical tier: candidates come from the postings of the
|
|
106
|
+
# chunk's heaviest terms, then exact cosine on the best of them.
|
|
107
|
+
_RELATED_TERMS = 32
|
|
108
|
+
_RELATED_CANDIDATES = 200
|
|
109
|
+
|
|
110
|
+
# Where a chunk lives says how likely it is to be the answer: test code, examples
|
|
111
|
+
# and type stubs rank below the implementation unless the query asks for them.
|
|
112
|
+
_TEST_WEIGHT = 0.4
|
|
113
|
+
_EXAMPLE_WEIGHT = 0.5
|
|
114
|
+
_STUB_WEIGHT = 0.7
|
|
115
|
+
_EXAMPLE_DIRS = frozenset({"example", "examples", "_examples", "demo", "demos", "docs_src",
|
|
116
|
+
"samples", "sample", "benchmark", "benchmarks"})
|
|
117
|
+
_TEST_WORDS = frozenset({"test", "tests", "testing", "spec", "specs", "fixture", "fixtures",
|
|
118
|
+
"mock", "mocks"})
|
|
119
|
+
# The n-th chunk of one file in a ranking is worth this much less than the one
|
|
120
|
+
# before it: a question with two homes should show both.
|
|
121
|
+
_FILE_DECAY = 0.4
|
|
122
|
+
# A file several of whose chunks match is more likely the answer: on the BM25-only
|
|
123
|
+
# index its best chunk gains this share of the others' scores, for questions (not
|
|
124
|
+
# names: a symbol query wants the one definition). After fusion it did not help.
|
|
125
|
+
_LEX_COHERENCE = 0.2
|
|
126
|
+
_RERANK_DEPTH = 100
|
|
127
|
+
|
|
128
|
+
_INDEX_CACHE_MAX = 2
|
|
129
|
+
_KERNEL_ABI = 1
|
|
130
|
+
|
|
131
|
+
_STOPWORDS = frozenset("""
|
|
132
|
+
a an and any are as at be been being but by can could do does doing done each
|
|
133
|
+
for from get gets has have how i if in into is it its me my of on or our should
|
|
134
|
+
so some than that the their them then there these they this those to up us was
|
|
135
|
+
we were what when where which who whom why will with would you your code
|
|
136
|
+
function functions method methods class classes implementation implemented
|
|
137
|
+
implement handle handles handled handling logic find finds show shows used use
|
|
138
|
+
uses
|
|
139
|
+
""".split())
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# ---------------------------------------------------------------------------
|
|
143
|
+
# Tokenizer
|
|
144
|
+
# ---------------------------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
_WORD = re.compile(r"[A-Za-z0-9_$\u0080-\U0010ffff]+")
|
|
147
|
+
# Camel humps, acronyms and digit runs; non-ASCII letters count as lower case;
|
|
148
|
+
# `_` and `$` split.
|
|
149
|
+
_PART = re.compile(r"[A-Z]+(?![a-z\u0080-\U0010ffff])|[A-Z]?[a-z\u0080-\U0010ffff]+|[0-9]+")
|
|
150
|
+
_TERM_CACHE: dict[str, tuple[str, ...]] = {}
|
|
151
|
+
_TERM_CACHE_MAX = 500_000
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _stem(w: str) -> str:
|
|
155
|
+
"""A small, fixed suffix stemmer: plurals, -ing, -ed, a trailing -e. Enough to
|
|
156
|
+
join ``retries`` / ``retry`` / ``retrying`` and ``parse`` / ``parsed``."""
|
|
157
|
+
if len(w) > 4 and w.endswith(("ies", "ied")):
|
|
158
|
+
w = w[:-3] + "y"
|
|
159
|
+
elif len(w) > 4 and w.endswith("sses"):
|
|
160
|
+
w = w[:-2]
|
|
161
|
+
elif len(w) > 3 and w.endswith("s") and not w.endswith(("ss", "us", "is")):
|
|
162
|
+
w = w[:-1]
|
|
163
|
+
if len(w) > 5 and w.endswith("ing"):
|
|
164
|
+
w = w[:-3]
|
|
165
|
+
elif len(w) > 4 and w.endswith("ed"):
|
|
166
|
+
w = w[:-2]
|
|
167
|
+
if len(w) > 3 and w.endswith("e"):
|
|
168
|
+
w = w[:-1]
|
|
169
|
+
return w
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _word_terms(word: str) -> tuple[str, ...]:
|
|
173
|
+
"""Terms of one identifier-like word: its whole folded form when it has
|
|
174
|
+
several parts (``getusername``), and each part of two or more characters,
|
|
175
|
+
stemmed. Pure numbers are not terms."""
|
|
176
|
+
cached = _TERM_CACHE.get(word)
|
|
177
|
+
if cached is not None:
|
|
178
|
+
return cached
|
|
179
|
+
parts = [p.lower() for p in _PART.findall(word)]
|
|
180
|
+
terms: list[str] = []
|
|
181
|
+
if len(parts) == 1:
|
|
182
|
+
p = parts[0]
|
|
183
|
+
if len(p) >= 2 and not p.isdigit():
|
|
184
|
+
terms.append(_stem(p))
|
|
185
|
+
elif parts:
|
|
186
|
+
whole = "".join(parts)
|
|
187
|
+
if not whole.isdigit():
|
|
188
|
+
terms.append(whole)
|
|
189
|
+
for p in parts:
|
|
190
|
+
if len(p) >= 2 and not p.isdigit():
|
|
191
|
+
t = _stem(p)
|
|
192
|
+
if t != whole:
|
|
193
|
+
terms.append(t)
|
|
194
|
+
out = tuple(terms)
|
|
195
|
+
if len(_TERM_CACHE) >= _TERM_CACHE_MAX:
|
|
196
|
+
_TERM_CACHE.clear()
|
|
197
|
+
_TERM_CACHE[word] = out
|
|
198
|
+
return out
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class _Kernel(Protocol):
|
|
202
|
+
"""The two hot loops, replaceable by an accelerator with the same results."""
|
|
203
|
+
|
|
204
|
+
name: str
|
|
205
|
+
|
|
206
|
+
def tokenize(self, text: str) -> list[str]: ...
|
|
207
|
+
|
|
208
|
+
def bm25f(
|
|
209
|
+
self,
|
|
210
|
+
terms: list[tuple[float, dict[int, tuple[int, int, int]]]],
|
|
211
|
+
lengths: dict[int, tuple[int, int, int]],
|
|
212
|
+
avg: tuple[float, float, float],
|
|
213
|
+
params: tuple[float, ...],
|
|
214
|
+
) -> dict[int, tuple[float, int]]: ...
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class _PyKernel:
|
|
218
|
+
"""Reference kernel. ``bm25f`` takes each query term's idf (computed by the
|
|
219
|
+
caller) and postings ``{chunk: (tf_name, tf_path, tf_body)}`` and returns
|
|
220
|
+
``{chunk: (score, terms matched)}``; terms are summed in the order given."""
|
|
221
|
+
|
|
222
|
+
name = "python"
|
|
223
|
+
|
|
224
|
+
def tokenize(self, text: str) -> list[str]:
|
|
225
|
+
out: list[str] = []
|
|
226
|
+
for m in _WORD.finditer(text):
|
|
227
|
+
out.extend(_word_terms(m.group()))
|
|
228
|
+
return out
|
|
229
|
+
|
|
230
|
+
def bm25f(
|
|
231
|
+
self,
|
|
232
|
+
terms: list[tuple[float, dict[int, tuple[int, int, int]]]],
|
|
233
|
+
lengths: dict[int, tuple[int, int, int]],
|
|
234
|
+
avg: tuple[float, float, float],
|
|
235
|
+
params: tuple[float, ...],
|
|
236
|
+
) -> dict[int, tuple[float, int]]:
|
|
237
|
+
k1, wn, wp, wb, bn, bp, bb = params
|
|
238
|
+
an, ap, ab = avg
|
|
239
|
+
out: dict[int, tuple[float, int]] = {}
|
|
240
|
+
for idf, plist in terms:
|
|
241
|
+
for cid, (tn, tp, tb) in plist.items():
|
|
242
|
+
ln, lp, lb = lengths[cid]
|
|
243
|
+
tfw = 0.0
|
|
244
|
+
if tn:
|
|
245
|
+
tfw += wn * tn / (1.0 - bn + bn * ln / an)
|
|
246
|
+
if tp:
|
|
247
|
+
tfw += wp * tp / (1.0 - bp + bp * lp / ap)
|
|
248
|
+
if tb:
|
|
249
|
+
tfw += wb * tb / (1.0 - bb + bb * lb / ab)
|
|
250
|
+
s = idf * tfw / (k1 + tfw)
|
|
251
|
+
prev = out.get(cid)
|
|
252
|
+
out[cid] = (s, 1) if prev is None else (prev[0] + s, prev[1] + 1)
|
|
253
|
+
return out
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
_KERNEL: _Kernel | None = None
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _kernel() -> _Kernel:
|
|
260
|
+
"""The accelerator when installed and ABI-compatible, else the Python kernel.
|
|
261
|
+
``GRAPHLORE_SEARCH_KERNEL=python`` forces the reference."""
|
|
262
|
+
global _KERNEL
|
|
263
|
+
if _KERNEL is None:
|
|
264
|
+
kernel: _Kernel = _PyKernel()
|
|
265
|
+
if (config.env("SEARCH_KERNEL", "") or "").strip().lower() != "python":
|
|
266
|
+
try:
|
|
267
|
+
import graphlore_accel # type: ignore[import-not-found]
|
|
268
|
+
|
|
269
|
+
if getattr(graphlore_accel, "KERNEL_ABI", None) == _KERNEL_ABI:
|
|
270
|
+
kernel = graphlore_accel.Kernel()
|
|
271
|
+
except Exception: # noqa: BLE001 - a broken accelerator is no accelerator
|
|
272
|
+
pass
|
|
273
|
+
_KERNEL = kernel
|
|
274
|
+
return _KERNEL
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _tokenize(text: str) -> list[str]:
|
|
278
|
+
return _kernel().tokenize(text)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _query_kind(query: str) -> str:
|
|
282
|
+
"""``symbol`` (a name: one word, or a few with ``_``, ``.``, ``::``, ``()`` or
|
|
283
|
+
camel humps), ``code`` (a pasted snippet) or ``natural`` (a question)."""
|
|
284
|
+
s = query.strip()
|
|
285
|
+
if "\n" in s or len(re.findall(r"[{}();=<>\[\]]", s)) >= 3:
|
|
286
|
+
return "code"
|
|
287
|
+
words = s.split()
|
|
288
|
+
if len(words) <= 1:
|
|
289
|
+
return "symbol"
|
|
290
|
+
if len(words) <= 3 and all(
|
|
291
|
+
"_" in w or "." in w or "::" in w or "(" in w or re.search(r"[a-z][A-Z]", w)
|
|
292
|
+
for w in words
|
|
293
|
+
):
|
|
294
|
+
return "symbol"
|
|
295
|
+
return "natural"
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _query_terms(query: str, kind: str) -> list[str]:
|
|
299
|
+
"""Distinct terms of the query in order; a question loses its stopwords
|
|
300
|
+
(unless nothing else is left)."""
|
|
301
|
+
words = [m.group() for m in _WORD.finditer(query)]
|
|
302
|
+
if kind == "natural":
|
|
303
|
+
kept = [w for w in words if w.lower() not in _STOPWORDS]
|
|
304
|
+
words = kept or words
|
|
305
|
+
seen: dict[str, None] = {}
|
|
306
|
+
for w in words:
|
|
307
|
+
for t in _word_terms(w):
|
|
308
|
+
seen.setdefault(t, None)
|
|
309
|
+
return list(seen)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _path_weight(rel: str, wants_tests: bool) -> float:
|
|
313
|
+
"""The prior of a file: test code, examples, type stubs below the rest."""
|
|
314
|
+
if not wants_tests and _is_test_path(rel):
|
|
315
|
+
return _TEST_WEIGHT
|
|
316
|
+
if any(p.lower() in _EXAMPLE_DIRS for p in rel.split("/")[:-1]):
|
|
317
|
+
return _EXAMPLE_WEIGHT
|
|
318
|
+
if rel.endswith(".d.ts"):
|
|
319
|
+
return _STUB_WEIGHT
|
|
320
|
+
return 1.0
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _symbol_key(query: str) -> str:
|
|
324
|
+
"""The name a symbol query asks for: its last ``.`` / ``::`` component, folded."""
|
|
325
|
+
s = query.strip().rstrip("()").replace("::", ".")
|
|
326
|
+
last = s.rsplit(".", 1)[-1]
|
|
327
|
+
return re.sub(r"[^0-9a-z]", "", last.lower())
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
# ---------------------------------------------------------------------------
|
|
331
|
+
# Chunks
|
|
332
|
+
# ---------------------------------------------------------------------------
|
|
333
|
+
|
|
334
|
+
@dataclass(frozen=True)
|
|
335
|
+
class Chunk:
|
|
336
|
+
"""A searchable piece of one file. ``start_line..end_line`` is the whole
|
|
337
|
+
definition (for a ``definition`` chunk) even though a container indexes only
|
|
338
|
+
the lines its children do not cover."""
|
|
339
|
+
|
|
340
|
+
file_path: str
|
|
341
|
+
start_line: int
|
|
342
|
+
end_line: int
|
|
343
|
+
def_line: int = 0
|
|
344
|
+
qualname: str = ""
|
|
345
|
+
kind: str = "window" # definition | module | window
|
|
346
|
+
|
|
347
|
+
@property
|
|
348
|
+
def name(self) -> str:
|
|
349
|
+
return self.qualname.rsplit(".", 1)[-1] if self.qualname else ""
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
@dataclass(frozen=True)
|
|
353
|
+
class Hit:
|
|
354
|
+
chunk: Chunk
|
|
355
|
+
score: float
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _windows(
|
|
359
|
+
rel: str, lines: list[str], lo: int, hi: int, kind: str
|
|
360
|
+
) -> list[tuple[Chunk, str]]:
|
|
361
|
+
out = []
|
|
362
|
+
start = lo
|
|
363
|
+
while start <= hi:
|
|
364
|
+
end = min(hi, start + _WINDOW_LINES - 1)
|
|
365
|
+
body = lines[start - 1:end]
|
|
366
|
+
if sum(1 for ln in body if ln.strip()) >= (1 if kind == "window" else _GAP_MIN_LINES):
|
|
367
|
+
out.append((Chunk(rel, start, end, 0, "", kind), "\n".join(body)))
|
|
368
|
+
start = end + 1
|
|
369
|
+
return out
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _chunk_file(rel: str, src: bytes) -> tuple[list[tuple[Chunk, str]], bool]:
|
|
373
|
+
"""(chunks with their indexed text, whether the span engine read the file)."""
|
|
374
|
+
text = src.decode("utf-8", "replace")
|
|
375
|
+
lines = text.splitlines()
|
|
376
|
+
n = len(lines)
|
|
377
|
+
if n == 0:
|
|
378
|
+
return [], False
|
|
379
|
+
spans = [
|
|
380
|
+
(rs, min(end, n), dl, q) for rs, end, dl, q in _spans_for_file(rel)
|
|
381
|
+
if 1 <= rs <= n and rs <= end
|
|
382
|
+
]
|
|
383
|
+
if not spans:
|
|
384
|
+
return _windows(rel, lines, 1, n, "window"), False
|
|
385
|
+
order = sorted(set(spans), key=lambda s: (s[0], -s[1], s[2], s[3]))
|
|
386
|
+
children: list[list[tuple[int, int]]] = [[] for _ in order]
|
|
387
|
+
top: list[tuple[int, int]] = []
|
|
388
|
+
stack: list[int] = []
|
|
389
|
+
for i, (rs, end, _dl, _q) in enumerate(order):
|
|
390
|
+
while stack and order[stack[-1]][1] < rs:
|
|
391
|
+
stack.pop()
|
|
392
|
+
if stack and order[stack[-1]][1] >= end:
|
|
393
|
+
children[stack[-1]].append((rs, end))
|
|
394
|
+
else:
|
|
395
|
+
top.append((rs, end))
|
|
396
|
+
stack.append(i)
|
|
397
|
+
out: list[tuple[Chunk, str]] = []
|
|
398
|
+
for i, (rs, end, dl, qual) in enumerate(order):
|
|
399
|
+
own: list[int] = []
|
|
400
|
+
cur = rs
|
|
401
|
+
for crs, cend in sorted(children[i]):
|
|
402
|
+
if crs > cur:
|
|
403
|
+
own.extend(range(cur, crs))
|
|
404
|
+
cur = max(cur, cend + 1)
|
|
405
|
+
own.extend(range(cur, end + 1))
|
|
406
|
+
body = "\n".join(lines[ln - 1] for ln in own)
|
|
407
|
+
out.append((Chunk(rel, rs, end, dl, qual, "definition"), body))
|
|
408
|
+
# Module-level code between the top-level definitions.
|
|
409
|
+
covered = bytearray(n + 2)
|
|
410
|
+
for rs, end in top:
|
|
411
|
+
for ln in range(rs, end + 1):
|
|
412
|
+
covered[ln] = 1
|
|
413
|
+
ln = 1
|
|
414
|
+
while ln <= n:
|
|
415
|
+
if covered[ln]:
|
|
416
|
+
ln += 1
|
|
417
|
+
continue
|
|
418
|
+
run_start = ln
|
|
419
|
+
while ln <= n and not covered[ln]:
|
|
420
|
+
ln += 1
|
|
421
|
+
out.extend(_windows(rel, lines, run_start, ln - 1, "module"))
|
|
422
|
+
return out, True
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
# ---------------------------------------------------------------------------
|
|
426
|
+
# Index
|
|
427
|
+
# ---------------------------------------------------------------------------
|
|
428
|
+
|
|
429
|
+
class _FileEntry(NamedTuple):
|
|
430
|
+
stamp: tuple[int, int]
|
|
431
|
+
cids: tuple[int, ...]
|
|
432
|
+
skipped: str # "" when indexed, else why not (vendored / oversize / binary / capped)
|
|
433
|
+
spans: bool
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
class _Overlay(NamedTuple):
|
|
437
|
+
nodes: list[dict]
|
|
438
|
+
postings: dict[str, dict[tuple[str, int], int]]
|
|
439
|
+
lengths: dict[tuple[str, int], int]
|
|
440
|
+
avg: float
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _tf_fields(
|
|
444
|
+
name: list[str], path: list[str], body: list[str]
|
|
445
|
+
) -> dict[str, tuple[int, int, int]]:
|
|
446
|
+
cn, cp, cb = Counter(name), Counter(path), Counter(body)
|
|
447
|
+
terms = cn.keys() | cp.keys() | cb.keys()
|
|
448
|
+
return {t: (cn.get(t, 0), cp.get(t, 0), cb.get(t, 0)) for t in terms}
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _idf(n: int, df: int) -> float:
|
|
452
|
+
return math.log(1.0 + (n - df + 0.5) / (df + 0.5))
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
class CodeIndex:
|
|
456
|
+
"""The built-in index of one project. Satisfies ``SemanticIndex``
|
|
457
|
+
(``search`` / ``find_related``), plus ``hit_for_span`` and ``info``."""
|
|
458
|
+
|
|
459
|
+
def __init__(self, root: str, spec: str) -> None:
|
|
460
|
+
self.root = root
|
|
461
|
+
self.spec = spec # embedding model spec, or "off"
|
|
462
|
+
self.lock = threading.RLock()
|
|
463
|
+
self.files: dict[str, _FileEntry] = {}
|
|
464
|
+
self.chunks: dict[int, Chunk] = {}
|
|
465
|
+
self.fwd: dict[int, dict[str, tuple[int, int, int]]] = {}
|
|
466
|
+
self.lengths: dict[int, tuple[int, int, int]] = {}
|
|
467
|
+
self.postings: dict[str, dict[int, tuple[int, int, int]]] = {}
|
|
468
|
+
self.totals = [0, 0, 0]
|
|
469
|
+
self.by_def: dict[tuple[str, int], list[int]] = {}
|
|
470
|
+
self.next_id = 0
|
|
471
|
+
self.version = 0
|
|
472
|
+
self.capped = False
|
|
473
|
+
self.overlay: _Overlay | None = None
|
|
474
|
+
self.dense: embed.VectorStore | None = None
|
|
475
|
+
self.dense_reason = (
|
|
476
|
+
"" if spec != "off" else "the dense tier is off (GRAPHLORE_EMBED_MODEL=off)"
|
|
477
|
+
)
|
|
478
|
+
self.ekeys: dict[int, bytes] = {}
|
|
479
|
+
self._matrix: tuple[int, list[int], Any] | None = None
|
|
480
|
+
self.last_embedded = 0
|
|
481
|
+
|
|
482
|
+
# -- building ----------------------------------------------------------
|
|
483
|
+
|
|
484
|
+
def _walk(self, extra: Iterable[str]) -> dict[str, tuple[int, int]]:
|
|
485
|
+
root = Path(self.root)
|
|
486
|
+
found: dict[str, tuple[int, int]] = {}
|
|
487
|
+
self.capped = False
|
|
488
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
489
|
+
dirnames[:] = sorted(
|
|
490
|
+
d for d in dirnames
|
|
491
|
+
if not d.startswith(".") and d not in _MENTION_SKIP_DIRS
|
|
492
|
+
and d != config.OUT_DIR_NAME
|
|
493
|
+
)
|
|
494
|
+
for name in sorted(filenames):
|
|
495
|
+
if os.path.splitext(name)[1].lower() not in _SEARCH_EXTS:
|
|
496
|
+
continue
|
|
497
|
+
full = os.path.join(dirpath, name)
|
|
498
|
+
if os.path.islink(full):
|
|
499
|
+
continue # a link may point outside the project: never follow it
|
|
500
|
+
try:
|
|
501
|
+
st = os.stat(full)
|
|
502
|
+
except OSError:
|
|
503
|
+
continue
|
|
504
|
+
if len(found) >= _SEARCH_MAX_FILES:
|
|
505
|
+
self.capped = True
|
|
506
|
+
break
|
|
507
|
+
rel = os.path.relpath(full, root).replace(os.sep, "/")
|
|
508
|
+
found[rel] = (st.st_mtime_ns, st.st_size)
|
|
509
|
+
# Graph files the walk skipped (a build/ or hidden directory), confined.
|
|
510
|
+
for f in extra:
|
|
511
|
+
rel = _norm_relpath(f)
|
|
512
|
+
if not rel or rel in found or len(found) >= _SEARCH_MAX_FILES:
|
|
513
|
+
continue
|
|
514
|
+
if os.path.splitext(rel)[1].lower() not in _SEARCH_EXTS:
|
|
515
|
+
continue
|
|
516
|
+
full_p = _resolve_in_project(rel)
|
|
517
|
+
if full_p is None:
|
|
518
|
+
continue
|
|
519
|
+
try:
|
|
520
|
+
st = full_p.stat()
|
|
521
|
+
except OSError:
|
|
522
|
+
continue
|
|
523
|
+
if full_p.is_file():
|
|
524
|
+
found[rel] = (st.st_mtime_ns, st.st_size)
|
|
525
|
+
return found
|
|
526
|
+
|
|
527
|
+
def _remove(self, rel: str) -> None:
|
|
528
|
+
entry = self.files.pop(rel, None)
|
|
529
|
+
if entry is None:
|
|
530
|
+
return
|
|
531
|
+
for cid in entry.cids:
|
|
532
|
+
for term in self.fwd.pop(cid, {}):
|
|
533
|
+
plist = self.postings.get(term)
|
|
534
|
+
if plist is not None:
|
|
535
|
+
plist.pop(cid, None)
|
|
536
|
+
if not plist:
|
|
537
|
+
del self.postings[term]
|
|
538
|
+
ln, lp, lb = self.lengths.pop(cid, (0, 0, 0))
|
|
539
|
+
self.totals[0] -= ln
|
|
540
|
+
self.totals[1] -= lp
|
|
541
|
+
self.totals[2] -= lb
|
|
542
|
+
chunk = self.chunks.pop(cid)
|
|
543
|
+
if chunk.def_line:
|
|
544
|
+
ids = self.by_def.get((chunk.file_path, chunk.def_line))
|
|
545
|
+
if ids is not None:
|
|
546
|
+
ids.remove(cid)
|
|
547
|
+
if not ids:
|
|
548
|
+
del self.by_def[(chunk.file_path, chunk.def_line)]
|
|
549
|
+
self.ekeys.pop(cid, None)
|
|
550
|
+
|
|
551
|
+
def _add(self, rel: str, stamp: tuple[int, int], pending: list[tuple[int, bytes, str]]) -> None:
|
|
552
|
+
def skip(why: str) -> None:
|
|
553
|
+
self.files[rel] = _FileEntry(stamp, (), why, False)
|
|
554
|
+
|
|
555
|
+
if stamp[1] > _SEARCH_MAX_FILE_BYTES:
|
|
556
|
+
return skip("oversize")
|
|
557
|
+
if _vendored_by_path(rel) or _minified_by_content(rel):
|
|
558
|
+
return skip("vendored")
|
|
559
|
+
full = _resolve_in_project(rel)
|
|
560
|
+
if full is None:
|
|
561
|
+
return skip("outside")
|
|
562
|
+
try:
|
|
563
|
+
src = full.read_bytes()
|
|
564
|
+
except OSError:
|
|
565
|
+
return skip("unreadable")
|
|
566
|
+
if b"\0" in src[:2048]:
|
|
567
|
+
return skip("binary")
|
|
568
|
+
if len(self.chunks) >= _SEARCH_MAX_CHUNKS:
|
|
569
|
+
self.capped = True
|
|
570
|
+
return skip("capped")
|
|
571
|
+
chunks, spans = _chunk_file(rel, src)
|
|
572
|
+
kernel = _kernel()
|
|
573
|
+
path_terms = kernel.tokenize(rel)
|
|
574
|
+
cids = []
|
|
575
|
+
for chunk, body in chunks:
|
|
576
|
+
cid = self.next_id
|
|
577
|
+
self.next_id += 1
|
|
578
|
+
name_terms = kernel.tokenize(chunk.qualname) if chunk.qualname else []
|
|
579
|
+
body_terms = kernel.tokenize(body)
|
|
580
|
+
fields = _tf_fields(name_terms, path_terms, body_terms)
|
|
581
|
+
self.fwd[cid] = fields
|
|
582
|
+
for term, tfs in fields.items():
|
|
583
|
+
self.postings.setdefault(term, {})[cid] = tfs
|
|
584
|
+
lens = (len(name_terms), len(path_terms), len(body_terms))
|
|
585
|
+
self.lengths[cid] = lens
|
|
586
|
+
self.totals[0] += lens[0]
|
|
587
|
+
self.totals[1] += lens[1]
|
|
588
|
+
self.totals[2] += lens[2]
|
|
589
|
+
self.chunks[cid] = chunk
|
|
590
|
+
if chunk.def_line:
|
|
591
|
+
self.by_def.setdefault((rel, chunk.def_line), []).append(cid)
|
|
592
|
+
if self.spec != "off":
|
|
593
|
+
etext = f"{rel} {chunk.qualname}\n{body}"
|
|
594
|
+
key = embed.text_key(self.spec, etext)
|
|
595
|
+
self.ekeys[cid] = key
|
|
596
|
+
pending.append((cid, key, etext))
|
|
597
|
+
cids.append(cid)
|
|
598
|
+
self.files[rel] = _FileEntry(stamp, tuple(cids), "", spans)
|
|
599
|
+
|
|
600
|
+
def refresh(self, nodes: list[dict] | None = None, edges: list[dict] | None = None) -> None:
|
|
601
|
+
"""Bring the index in line with the files on disk (and the graph overlay
|
|
602
|
+
in line with ``nodes``): only changed files are re-read."""
|
|
603
|
+
with self.lock:
|
|
604
|
+
graph_files = {_node_file(n) for n in nodes} if nodes else set()
|
|
605
|
+
found = self._walk(sorted(f for f in graph_files if f))
|
|
606
|
+
changed = False
|
|
607
|
+
for rel in [r for r in self.files if r not in found]:
|
|
608
|
+
self._remove(rel)
|
|
609
|
+
changed = True
|
|
610
|
+
pending: list[tuple[int, bytes, str]] = []
|
|
611
|
+
for rel in sorted(found):
|
|
612
|
+
stamp = found[rel]
|
|
613
|
+
entry = self.files.get(rel)
|
|
614
|
+
if entry is not None and entry.stamp == stamp and entry.skipped != "capped":
|
|
615
|
+
continue
|
|
616
|
+
self._remove(rel)
|
|
617
|
+
self._add(rel, stamp, pending)
|
|
618
|
+
changed = True
|
|
619
|
+
if changed:
|
|
620
|
+
self.version += 1
|
|
621
|
+
self._refresh_dense(pending)
|
|
622
|
+
if nodes is not None and (self.overlay is None or self.overlay.nodes is not nodes):
|
|
623
|
+
self.overlay = _build_overlay(nodes, edges or [])
|
|
624
|
+
|
|
625
|
+
def _refresh_dense(self, pending: list[tuple[int, bytes, str]]) -> None:
|
|
626
|
+
self.last_embedded = 0
|
|
627
|
+
if self.spec == "off":
|
|
628
|
+
return
|
|
629
|
+
if self.dense is None:
|
|
630
|
+
if self.dense_reason:
|
|
631
|
+
return
|
|
632
|
+
if len(self.chunks) > embed.EMBED_MAX_CHUNKS:
|
|
633
|
+
self.dense_reason = (
|
|
634
|
+
f"the dense tier is off: {len(self.chunks)} chunks is more than "
|
|
635
|
+
f"{embed.EMBED_MAX_CHUNKS}"
|
|
636
|
+
)
|
|
637
|
+
return
|
|
638
|
+
model, why = embed._load_model(self.spec)
|
|
639
|
+
if model is None:
|
|
640
|
+
self.dense_reason = why
|
|
641
|
+
return
|
|
642
|
+
self.dense = embed.VectorStore(model, self.spec, self.root)
|
|
643
|
+
# Texts are not kept: chunks indexed before this call are re-read
|
|
644
|
+
# when the store (perhaps loaded from disk) has no vector for them.
|
|
645
|
+
have = {cid for cid, _k, _t in pending}
|
|
646
|
+
earlier = [(cid, k, "") for cid, k in self.ekeys.items() if cid not in have]
|
|
647
|
+
pending = pending + self._texts_for(earlier)
|
|
648
|
+
if len(self.chunks) > embed.EMBED_MAX_CHUNKS:
|
|
649
|
+
self.dense = None
|
|
650
|
+
self.dense_reason = (
|
|
651
|
+
f"the dense tier is off: {len(self.chunks)} chunks is more than "
|
|
652
|
+
f"{embed.EMBED_MAX_CHUNKS}"
|
|
653
|
+
)
|
|
654
|
+
return
|
|
655
|
+
todo = [(k, t) for _cid, k, t in pending]
|
|
656
|
+
if todo:
|
|
657
|
+
try:
|
|
658
|
+
_m, self.last_embedded = self.dense.vectors_for(
|
|
659
|
+
[k for k, _t in todo], [t for _k, t in todo]
|
|
660
|
+
)
|
|
661
|
+
except Exception as exc: # noqa: BLE001 - a failing model degrades to BM25 only
|
|
662
|
+
self.dense = None
|
|
663
|
+
self.dense_reason = f"embedding failed ({type(exc).__name__}: {str(exc)[:200]})"
|
|
664
|
+
return
|
|
665
|
+
if self.last_embedded or pending:
|
|
666
|
+
self.dense.save(set(self.ekeys.values()))
|
|
667
|
+
|
|
668
|
+
def _texts_for(self, pending: list[tuple[int, bytes, str]]) -> list[tuple[int, bytes, str]]:
|
|
669
|
+
"""The embedded text of chunks whose vectors the store lacks (first dense
|
|
670
|
+
load after a lexical build)."""
|
|
671
|
+
assert self.dense is not None
|
|
672
|
+
missing = {cid for cid, key, _t in pending if key not in self.dense._vecs}
|
|
673
|
+
if not missing:
|
|
674
|
+
return []
|
|
675
|
+
out = []
|
|
676
|
+
by_file: dict[str, list[int]] = {}
|
|
677
|
+
for cid in missing:
|
|
678
|
+
by_file.setdefault(self.chunks[cid].file_path, []).append(cid)
|
|
679
|
+
for rel, cids in by_file.items():
|
|
680
|
+
full = _resolve_in_project(rel)
|
|
681
|
+
if full is None:
|
|
682
|
+
continue
|
|
683
|
+
try:
|
|
684
|
+
chunks, _spans = _chunk_file(rel, full.read_bytes())
|
|
685
|
+
except OSError:
|
|
686
|
+
continue
|
|
687
|
+
bodies = {(c.start_line, c.end_line, c.kind, c.qualname): b for c, b in chunks}
|
|
688
|
+
for cid in cids:
|
|
689
|
+
c = self.chunks[cid]
|
|
690
|
+
body = bodies.get((c.start_line, c.end_line, c.kind, c.qualname))
|
|
691
|
+
if body is not None:
|
|
692
|
+
out.append((cid, self.ekeys[cid], f"{rel} {c.qualname}\n{body}"))
|
|
693
|
+
return out
|
|
694
|
+
|
|
695
|
+
# -- querying ----------------------------------------------------------
|
|
696
|
+
|
|
697
|
+
def _best(self, scores: dict[int, float], k: int) -> list[tuple[int, float]]:
|
|
698
|
+
"""The k best (chunk, score), best first, ties by (file, line) — exactly
|
|
699
|
+
what a full sort gives, without sorting every match."""
|
|
700
|
+
if len(scores) > 4 * k:
|
|
701
|
+
cut = heapq.nlargest(k, scores.values())[-1]
|
|
702
|
+
scores = {c: s for c, s in scores.items() if s >= cut}
|
|
703
|
+
return sorted(scores.items(), key=lambda kv: (-kv[1], self._order(kv[0])))[:k]
|
|
704
|
+
|
|
705
|
+
def _order(self, cid: int) -> tuple[str, int, int]:
|
|
706
|
+
c = self.chunks[cid]
|
|
707
|
+
return (c.file_path, c.start_line, c.end_line)
|
|
708
|
+
|
|
709
|
+
def _avg(self) -> tuple[float, float, float]:
|
|
710
|
+
n = max(1, len(self.chunks))
|
|
711
|
+
return tuple(max(1.0, t / n) for t in self.totals) # type: ignore[return-value]
|
|
712
|
+
|
|
713
|
+
def _lexical(self, query: str, kind: str, overlay_weight: float) -> dict[int, float]:
|
|
714
|
+
terms = _query_terms(query, kind)
|
|
715
|
+
if kind == "code":
|
|
716
|
+
terms = sorted(
|
|
717
|
+
(t for t in terms if t in self.postings),
|
|
718
|
+
key=lambda t: (len(self.postings[t]), t),
|
|
719
|
+
)[:_QUERY_MAX_TERMS]
|
|
720
|
+
n = len(self.chunks)
|
|
721
|
+
plist = [
|
|
722
|
+
(_idf(n, len(self.postings[t])), self.postings[t]) for t in terms if t in self.postings
|
|
723
|
+
]
|
|
724
|
+
raw = _kernel().bm25f(
|
|
725
|
+
plist, self.lengths, self._avg(),
|
|
726
|
+
(_K1, _W_NAME, _W_PATH, _W_BODY, _B_NAME, _B_PATH, _B_BODY),
|
|
727
|
+
)
|
|
728
|
+
nterms = max(1, len(terms))
|
|
729
|
+
scores: dict[int, float] = {}
|
|
730
|
+
for cid, (s, matched) in raw.items():
|
|
731
|
+
chunk = self.chunks[cid]
|
|
732
|
+
if chunk.kind == "module":
|
|
733
|
+
s *= _MODULE_WEIGHT
|
|
734
|
+
if kind == "natural":
|
|
735
|
+
s *= 0.5 + 0.5 * matched / nterms
|
|
736
|
+
scores[cid] = s
|
|
737
|
+
if overlay_weight and self.overlay is not None:
|
|
738
|
+
for key, s in _overlay_scores(self.overlay, terms).items():
|
|
739
|
+
for cid in self.by_def.get(key, ()):
|
|
740
|
+
scores[cid] = scores.get(cid, 0.0) + overlay_weight * s
|
|
741
|
+
if kind == "symbol":
|
|
742
|
+
for cid, boost in self._exact(query, scores).items():
|
|
743
|
+
scores[cid] *= boost
|
|
744
|
+
return scores
|
|
745
|
+
|
|
746
|
+
def _exact(self, query: str, cids: Iterable[int]) -> dict[int, float]:
|
|
747
|
+
"""Chunks named like a symbol query: the boost each gets (whole qualified
|
|
748
|
+
name, or its last component)."""
|
|
749
|
+
want = _symbol_key(query)
|
|
750
|
+
if not want:
|
|
751
|
+
return {}
|
|
752
|
+
whole = re.sub(r"[^0-9a-z.]", "", query.strip().rstrip("()").replace("::", ".").lower())
|
|
753
|
+
out = {}
|
|
754
|
+
for cid in cids:
|
|
755
|
+
chunk = self.chunks[cid]
|
|
756
|
+
if chunk.qualname and chunk.qualname.lower() == whole:
|
|
757
|
+
out[cid] = _EXACT_QUALNAME_BOOST
|
|
758
|
+
elif chunk.name and re.sub(r"[^0-9a-z]", "", chunk.name.lower()) == want:
|
|
759
|
+
out[cid] = _EXACT_NAME_BOOST
|
|
760
|
+
return out
|
|
761
|
+
|
|
762
|
+
def _cohere(self, pool: list[tuple[int, float]], frac: float) -> list[tuple[int, float]]:
|
|
763
|
+
"""Each file's best chunk gains ``frac`` of the scores of the file's other
|
|
764
|
+
chunks in the pool (sorted best first; the result is too)."""
|
|
765
|
+
total: dict[str, float] = {}
|
|
766
|
+
best: dict[str, int] = {}
|
|
767
|
+
for cid, sc in pool:
|
|
768
|
+
f = self.chunks[cid].file_path
|
|
769
|
+
total[f] = total.get(f, 0.0) + sc
|
|
770
|
+
best.setdefault(f, cid)
|
|
771
|
+
out = [
|
|
772
|
+
(cid, sc + frac * (total[self.chunks[cid].file_path] - sc)
|
|
773
|
+
if best[self.chunks[cid].file_path] == cid else sc)
|
|
774
|
+
for cid, sc in pool
|
|
775
|
+
]
|
|
776
|
+
out.sort(key=lambda kv: (-kv[1], self._order(kv[0])))
|
|
777
|
+
return out
|
|
778
|
+
|
|
779
|
+
def _rerank(self, scored: list[tuple[int, float]], query: str) -> list[tuple[int, float]]:
|
|
780
|
+
"""The path prior, then the per-file decay, over the best candidates."""
|
|
781
|
+
wants_tests = any(w.lower() in _TEST_WORDS for w in _WORD.findall(query))
|
|
782
|
+
pool = [
|
|
783
|
+
(cid, s * _path_weight(self.chunks[cid].file_path, wants_tests))
|
|
784
|
+
for cid, s in scored[:_RERANK_DEPTH]
|
|
785
|
+
]
|
|
786
|
+
pool.sort(key=lambda kv: (-kv[1], self._order(kv[0])))
|
|
787
|
+
seen: Counter[str] = Counter()
|
|
788
|
+
out = []
|
|
789
|
+
for cid, s in pool:
|
|
790
|
+
f = self.chunks[cid].file_path
|
|
791
|
+
out.append((cid, s * _FILE_DECAY ** seen[f]))
|
|
792
|
+
seen[f] += 1
|
|
793
|
+
out.sort(key=lambda kv: (-kv[1], self._order(kv[0])))
|
|
794
|
+
return out
|
|
795
|
+
|
|
796
|
+
def _dense_matrix(self) -> tuple[list[int], Any]:
|
|
797
|
+
import numpy as np
|
|
798
|
+
|
|
799
|
+
if self._matrix is not None and self._matrix[0] == self.version:
|
|
800
|
+
return self._matrix[1], self._matrix[2]
|
|
801
|
+
assert self.dense is not None
|
|
802
|
+
vecs = self.dense._vecs
|
|
803
|
+
cids = sorted(c for c in self.chunks if c in self.ekeys and self.ekeys[c] in vecs)
|
|
804
|
+
mat = (
|
|
805
|
+
np.stack([vecs[self.ekeys[c]] for c in cids]).astype(np.float32)
|
|
806
|
+
if cids else None
|
|
807
|
+
)
|
|
808
|
+
self._matrix = (self.version, cids, mat)
|
|
809
|
+
return cids, mat
|
|
810
|
+
|
|
811
|
+
def search(
|
|
812
|
+
self,
|
|
813
|
+
query: str,
|
|
814
|
+
top_k: int = 3,
|
|
815
|
+
*,
|
|
816
|
+
dense: bool | None = None,
|
|
817
|
+
overlay_weight: float = _OVERLAY_WEIGHT,
|
|
818
|
+
) -> list[Hit]:
|
|
819
|
+
"""The ``top_k`` chunks for ``query``, best first. ``dense=False`` ranks
|
|
820
|
+
lexically even when the dense tier is loaded (for comparisons)."""
|
|
821
|
+
with self.lock:
|
|
822
|
+
if top_k < 1 or not self.chunks:
|
|
823
|
+
return []
|
|
824
|
+
kind = _query_kind(query)
|
|
825
|
+
lex = self._lexical(query, kind, overlay_weight)
|
|
826
|
+
ranked = self._best(lex, max(top_k, _RERANK_DEPTH, _FUSION_DEPTH))
|
|
827
|
+
use_dense = self.dense is not None and dense is not False
|
|
828
|
+
if not use_dense:
|
|
829
|
+
if _LEX_COHERENCE and kind != "symbol":
|
|
830
|
+
ranked = self._cohere(ranked[:_RERANK_DEPTH], _LEX_COHERENCE)
|
|
831
|
+
ranked = self._rerank(ranked, query)
|
|
832
|
+
return [Hit(self.chunks[c], round(s, 6)) for c, s in ranked[:top_k]]
|
|
833
|
+
assert self.dense is not None
|
|
834
|
+
cids, mat = self._dense_matrix()
|
|
835
|
+
rows = embed.top_k(mat, self.dense.query(query), _FUSION_DEPTH)
|
|
836
|
+
wl, wd = _FUSION_WEIGHTS[kind]
|
|
837
|
+
fused: dict[int, float] = {}
|
|
838
|
+
for r, (cid, _s) in enumerate(ranked[:_FUSION_DEPTH]):
|
|
839
|
+
fused[cid] = wl / (_RRF_K + r + 1)
|
|
840
|
+
for r, (row, _cos) in enumerate(rows):
|
|
841
|
+
cid = cids[row]
|
|
842
|
+
fused[cid] = fused.get(cid, 0.0) + wd / (_RRF_K + r + 1)
|
|
843
|
+
if kind == "symbol" and _EXACT_FUSED_BONUS:
|
|
844
|
+
for cid, boost in self._exact(query, list(fused)).items():
|
|
845
|
+
fused[cid] += _EXACT_FUSED_BONUS * boost / _EXACT_NAME_BOOST / (_RRF_K + 1)
|
|
846
|
+
out = sorted(fused.items(), key=lambda kv: (-kv[1], self._order(kv[0])))
|
|
847
|
+
out = self._rerank(out, query)
|
|
848
|
+
return [Hit(self.chunks[c], round(s, 6)) for c, s in out[:top_k]]
|
|
849
|
+
|
|
850
|
+
def _cid_of(self, hit: Any) -> int | None:
|
|
851
|
+
c = getattr(hit, "chunk", None)
|
|
852
|
+
if c is None:
|
|
853
|
+
return None
|
|
854
|
+
rel = _norm_relpath(getattr(c, "file_path", ""))
|
|
855
|
+
try:
|
|
856
|
+
sl, el = int(c.start_line), int(c.end_line)
|
|
857
|
+
except (TypeError, ValueError, AttributeError):
|
|
858
|
+
return None
|
|
859
|
+
entry = self.files.get(rel)
|
|
860
|
+
if entry is None:
|
|
861
|
+
return None
|
|
862
|
+
for cid in entry.cids:
|
|
863
|
+
ch = self.chunks[cid]
|
|
864
|
+
if ch.start_line == sl and ch.end_line == el:
|
|
865
|
+
return cid
|
|
866
|
+
return None
|
|
867
|
+
|
|
868
|
+
def hit_for_span(self, file_path: str, start: int, end: int) -> Hit | None:
|
|
869
|
+
"""The chunk of a definition spanning ``start..end`` (exact anchor for the
|
|
870
|
+
duplication scan): the definition chunk with those bounds, else the
|
|
871
|
+
definition chunk that overlaps them most."""
|
|
872
|
+
with self.lock:
|
|
873
|
+
entry = self.files.get(_norm_relpath(file_path))
|
|
874
|
+
if entry is None:
|
|
875
|
+
return None
|
|
876
|
+
best: tuple[int, int] | None = None
|
|
877
|
+
for cid in entry.cids:
|
|
878
|
+
ch = self.chunks[cid]
|
|
879
|
+
if ch.kind != "definition":
|
|
880
|
+
continue
|
|
881
|
+
if ch.start_line == start and ch.end_line == end:
|
|
882
|
+
return Hit(ch, 1.0)
|
|
883
|
+
overlap = min(end, ch.end_line) - max(start, ch.start_line) + 1
|
|
884
|
+
if overlap > 0 and (best is None or overlap > best[0]):
|
|
885
|
+
best = (overlap, cid)
|
|
886
|
+
return Hit(self.chunks[best[1]], 1.0) if best else None
|
|
887
|
+
|
|
888
|
+
def find_related(self, hit: Any, top_k: int = 8) -> list[Hit]:
|
|
889
|
+
"""Chunks most similar to ``hit``'s, best first, never the chunk itself
|
|
890
|
+
or one overlapping it in the same file. Score: cosine in 0..1 (embedding
|
|
891
|
+
vectors on the dense tier, tf-idf vectors on the lexical tier)."""
|
|
892
|
+
with self.lock:
|
|
893
|
+
cid = self._cid_of(hit)
|
|
894
|
+
if cid is None or top_k < 1:
|
|
895
|
+
return []
|
|
896
|
+
me = self.chunks[cid]
|
|
897
|
+
|
|
898
|
+
def far(other: Chunk) -> bool:
|
|
899
|
+
return not (
|
|
900
|
+
other.file_path == me.file_path
|
|
901
|
+
and other.start_line <= me.end_line and other.end_line >= me.start_line
|
|
902
|
+
)
|
|
903
|
+
|
|
904
|
+
if self.dense is not None and cid in self.ekeys and self.ekeys[cid] in self.dense._vecs:
|
|
905
|
+
cids, mat = self._dense_matrix()
|
|
906
|
+
q = self.dense._vecs[self.ekeys[cid]].astype("float32")
|
|
907
|
+
rows = embed.top_k(mat, q, top_k + 16)
|
|
908
|
+
out = []
|
|
909
|
+
for row, cos in rows:
|
|
910
|
+
other = cids[row]
|
|
911
|
+
if other == cid or not far(self.chunks[other]):
|
|
912
|
+
continue
|
|
913
|
+
out.append(Hit(self.chunks[other], round(min(1.0, max(0.0, cos)), 4)))
|
|
914
|
+
if len(out) >= top_k:
|
|
915
|
+
break
|
|
916
|
+
return out
|
|
917
|
+
return self._related_lexical(cid, top_k, far)
|
|
918
|
+
|
|
919
|
+
def _tfidf(self, cid: int) -> dict[str, float]:
|
|
920
|
+
n = len(self.chunks)
|
|
921
|
+
out = {}
|
|
922
|
+
# The body only: a renamed copy is still a copy.
|
|
923
|
+
for t, (_tn, _tp, tb) in self.fwd[cid].items():
|
|
924
|
+
if tb:
|
|
925
|
+
out[t] = (1.0 + math.log(tb)) * _idf(n, len(self.postings[t]))
|
|
926
|
+
return out
|
|
927
|
+
|
|
928
|
+
def _related_lexical(self, cid: int, top_k: int, far: Any) -> list[Hit]:
|
|
929
|
+
vec = self._tfidf(cid)
|
|
930
|
+
if not vec:
|
|
931
|
+
return []
|
|
932
|
+
norm = math.sqrt(sum(w * w for w in vec.values()))
|
|
933
|
+
heavy = sorted(vec, key=lambda t: (-vec[t], t))[:_RELATED_TERMS]
|
|
934
|
+
partial: dict[int, float] = {}
|
|
935
|
+
for t in heavy:
|
|
936
|
+
for other in self.postings[t]:
|
|
937
|
+
if other != cid:
|
|
938
|
+
partial[other] = partial.get(other, 0.0) + vec[t]
|
|
939
|
+
cands = sorted(partial, key=lambda c: (-partial[c], self._order(c)))[:_RELATED_CANDIDATES]
|
|
940
|
+
scored = []
|
|
941
|
+
for other in cands:
|
|
942
|
+
if not far(self.chunks[other]):
|
|
943
|
+
continue
|
|
944
|
+
ov = self._tfidf(other)
|
|
945
|
+
onorm = math.sqrt(sum(w * w for w in ov.values()))
|
|
946
|
+
if not onorm:
|
|
947
|
+
continue
|
|
948
|
+
dot = sum(w * ov[t] for t, w in vec.items() if t in ov)
|
|
949
|
+
scored.append((min(1.0, dot / (norm * onorm)), other))
|
|
950
|
+
scored.sort(key=lambda x: (-x[0], self._order(x[1])))
|
|
951
|
+
return [Hit(self.chunks[o], round(s, 4)) for s, o in scored[:top_k]]
|
|
952
|
+
|
|
953
|
+
# -- reporting ---------------------------------------------------------
|
|
954
|
+
|
|
955
|
+
def mode(self) -> str:
|
|
956
|
+
return "hybrid" if self.dense is not None else "bm25"
|
|
957
|
+
|
|
958
|
+
def info(self) -> dict[str, Any]:
|
|
959
|
+
with self.lock:
|
|
960
|
+
skipped = Counter(e.skipped for e in self.files.values() if e.skipped)
|
|
961
|
+
indexed = [e for e in self.files.values() if not e.skipped]
|
|
962
|
+
out: dict[str, Any] = {
|
|
963
|
+
"files": len(indexed),
|
|
964
|
+
"chunks": len(self.chunks),
|
|
965
|
+
"window_chunked_files": sum(1 for e in indexed if not e.spans and e.cids),
|
|
966
|
+
"tiers": ["bm25", "dense"] if self.dense is not None else ["bm25"],
|
|
967
|
+
"kernel": _kernel().name,
|
|
968
|
+
}
|
|
969
|
+
if self.dense is not None:
|
|
970
|
+
out["model"] = self.spec
|
|
971
|
+
if skipped:
|
|
972
|
+
out["skipped"] = dict(sorted(skipped.items()))
|
|
973
|
+
if self.capped:
|
|
974
|
+
out["truncated"] = True
|
|
975
|
+
out["hint"] = (
|
|
976
|
+
f"The index stops at {_SEARCH_MAX_FILES} files / {_SEARCH_MAX_CHUNKS} "
|
|
977
|
+
"chunks; files past that are not searched."
|
|
978
|
+
)
|
|
979
|
+
return out
|
|
980
|
+
|
|
981
|
+
|
|
982
|
+
def _build_overlay(nodes: list[dict], edges: list[dict]) -> _Overlay:
|
|
983
|
+
"""BM25 documents keyed by (file, line) of each code node: its docstring and
|
|
984
|
+
the names of what it calls and what calls it."""
|
|
985
|
+
labels = {_node_id(n): _node_label(n) for n in nodes}
|
|
986
|
+
callees: dict[str, list[str]] = {}
|
|
987
|
+
callers: dict[str, list[str]] = {}
|
|
988
|
+
for e in edges:
|
|
989
|
+
if _rel(e) not in _CALL_RELATIONS:
|
|
990
|
+
continue
|
|
991
|
+
s, t = _edge_ends(e)
|
|
992
|
+
if s in labels and t in labels:
|
|
993
|
+
callees.setdefault(s, []).append(labels[t])
|
|
994
|
+
callers.setdefault(t, []).append(labels[s])
|
|
995
|
+
kernel = _kernel()
|
|
996
|
+
postings: dict[str, dict[tuple[str, int], int]] = {}
|
|
997
|
+
lengths: dict[tuple[str, int], int] = {}
|
|
998
|
+
for n in nodes:
|
|
999
|
+
rel = _norm_relpath(_node_file(n))
|
|
1000
|
+
try:
|
|
1001
|
+
line = int(_node_line(n))
|
|
1002
|
+
except (TypeError, ValueError):
|
|
1003
|
+
continue
|
|
1004
|
+
if not rel:
|
|
1005
|
+
continue
|
|
1006
|
+
nid = _node_id(n)
|
|
1007
|
+
doc = n.get("doc") or n.get("docstring") or n.get("summary") or n.get("description") or ""
|
|
1008
|
+
words = [str(doc)]
|
|
1009
|
+
words += callees.get(nid, [])[:_OVERLAY_NEIGHBOURS]
|
|
1010
|
+
words += callers.get(nid, [])[:_OVERLAY_NEIGHBOURS]
|
|
1011
|
+
terms = kernel.tokenize(" ".join(words))
|
|
1012
|
+
if not terms:
|
|
1013
|
+
continue
|
|
1014
|
+
key = (rel, line)
|
|
1015
|
+
lengths[key] = lengths.get(key, 0) + len(terms)
|
|
1016
|
+
for t, c in Counter(terms).items():
|
|
1017
|
+
plist = postings.setdefault(t, {})
|
|
1018
|
+
plist[key] = plist.get(key, 0) + c
|
|
1019
|
+
avg = max(1.0, sum(lengths.values()) / max(1, len(lengths)))
|
|
1020
|
+
return _Overlay(nodes, postings, lengths, avg)
|
|
1021
|
+
|
|
1022
|
+
|
|
1023
|
+
def _overlay_scores(ov: _Overlay, terms: list[str]) -> dict[tuple[str, int], float]:
|
|
1024
|
+
n = len(ov.lengths)
|
|
1025
|
+
out: dict[tuple[str, int], float] = {}
|
|
1026
|
+
for t in terms:
|
|
1027
|
+
plist = ov.postings.get(t)
|
|
1028
|
+
if not plist:
|
|
1029
|
+
continue
|
|
1030
|
+
idf = _idf(n, len(plist))
|
|
1031
|
+
for key, tf in plist.items():
|
|
1032
|
+
norm = tf / (1.0 - 0.5 + 0.5 * ov.lengths[key] / ov.avg)
|
|
1033
|
+
out[key] = out.get(key, 0.0) + idf * norm / (_K1 + norm)
|
|
1034
|
+
return out
|
|
1035
|
+
|
|
1036
|
+
|
|
1037
|
+
# ---------------------------------------------------------------------------
|
|
1038
|
+
# The per-project cache
|
|
1039
|
+
# ---------------------------------------------------------------------------
|
|
1040
|
+
|
|
1041
|
+
_INDEX_CACHE: dict[tuple[str, str], CodeIndex] = {}
|
|
1042
|
+
_CACHE_LOCK = threading.Lock()
|
|
1043
|
+
|
|
1044
|
+
|
|
1045
|
+
def index_for_project(
|
|
1046
|
+
nodes: list[dict] | None = None,
|
|
1047
|
+
edges: list[dict] | None = None,
|
|
1048
|
+
dense: bool | None = None,
|
|
1049
|
+
) -> CodeIndex | None:
|
|
1050
|
+
"""The built-in index of ``config.PROJECT_DIR``, refreshed against the disk.
|
|
1051
|
+
|
|
1052
|
+
``dense``: None follows ``GRAPHLORE_EMBED_MODEL`` (on unless ``off``), True
|
|
1053
|
+
asks for the dense tier, False builds a lexical index. None when the project
|
|
1054
|
+
has no searchable source file.
|
|
1055
|
+
"""
|
|
1056
|
+
root = str(config.PROJECT_DIR.resolve())
|
|
1057
|
+
if dense is False or (dense is None and not embed.dense_wanted()):
|
|
1058
|
+
spec = "off"
|
|
1059
|
+
else:
|
|
1060
|
+
spec = embed.model_spec() if embed.dense_wanted() else embed.DEFAULT_MODEL
|
|
1061
|
+
key = (root, spec)
|
|
1062
|
+
with _CACHE_LOCK:
|
|
1063
|
+
idx = _INDEX_CACHE.get(key)
|
|
1064
|
+
if idx is None:
|
|
1065
|
+
if len(_INDEX_CACHE) >= _INDEX_CACHE_MAX:
|
|
1066
|
+
_INDEX_CACHE.pop(next(iter(_INDEX_CACHE)), None) # FIFO
|
|
1067
|
+
idx = CodeIndex(root, spec)
|
|
1068
|
+
_INDEX_CACHE[key] = idx
|
|
1069
|
+
idx.refresh(nodes, edges)
|
|
1070
|
+
return idx if idx.chunks else None
|