fix(query): match a label's name after its schema/namespace qualifier

`query sweep_widget_state` missed `public.sweep_widget_state()` even though
`explain` on the same name found it. The full-query tier only fires when the
joined query tokens equal or prefix the label, so a leading `public` defeated
it, and the per-token tiers handed the seed slots to unrelated nodes whose
whole label is one of the query's tokens (`SWEEP`, `WIDGET`, `State`).

Add a tier between exact and prefix for labels of the shape
`<qualifier><sep><rest>` where the query names exactly `<rest>`: dotted,
`::`, `/`, `:` and `@` segments, plus a CamelCase qualifier on the last
segment. It is scaled down by the qualifier's token count and capped at four
tokens, so `public.f()` is trusted more than `a.b.c.d.f()`. Trailing
file-extension and numeric segments are skipped, so `lib/foo/bar.py` is the
name `bar` rather than `py`.

Nothing changes for a query that already equals or prefixes a label, or for
plain snake_case identifiers: those never reach the new branch.

Fixes #5080

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 8d2e1caed8)
This commit is contained in:
Houyun Sun authored and safishamsi committed 2026-11-09 14:09:46 +00:00
1 parent 913b8e3a56
commit 3192fdf1f4
2 files changed
+173

No files matched your search

+89
View File
@@ -351,6 +351,84 @@ _SOURCE_MATCH_BONUS = 0.5
_RATIONALE_MATCH_BONUS = 0.75
_ATTRIBUTE_MATCH_BONUS = 0.75
# A label may carry a leading qualifier that the query never repeats: a SQL
# function is `public.sweep_widget_state()`, a namespaced symbol is
# `fmt.Println`. The full-query tier below only fires on equal/prefix, so the
# qualifier alone defeats it and the per-token tiers take over — where an
# unrelated node whose *whole* label is one of the query's tokens outranks the
# intended one (#5080). Keep the bonus below the exact tier (the query is not
# the label) but well above the per-token exact tier it has to beat, and scale
# it by how small the qualifier is so `public.f()` (one token) is trusted more
# than `a.b.c.d.f()`.
_QUALIFIED_MATCH_BONUS = 500.0
_QUALIFIED_MAX_TOKENS = 4
# Separators that start a new segment of a qualified name.
_QUALIFIER_SEPARATORS = r"\.{1,}|::|/|\\|:|@"
# `sweep_widget_state()` and `sweep widget state` are the same name; strip these
# before comparing. `_search_tokens` already drops them from the inside.
_NAME_EDGES = "()[]{}"
_CAMEL_WORD_RE = re.compile(r"[A-Z]+(?![a-z])|[A-Z][a-z0-9]*|[a-z0-9]+")
# Only a separator or a lower->upper transition below the first character can
# leave a qualifier behind; plain `snake_case_name` cannot, so reject it early.
_QUALIFIER_MAYBE_RE = re.compile(r"[.::/\\:@]|[a-z0-9][A-Z]")
# File-extension segments (`.py`, `.md`) are not qualifiers: the tail of
# `lib/foo/bar.py` is `bar`, not `py`. Numbers are not names either (`3.14`).
_FILE_SUFFIX_RE = re.compile(r"^(?:py|pyi|js|jsx|ts|tsx|mjs|cjs|go|rs|java|kt|kts|c|h|cc|cpp|hpp|cs|rb|php|swift|scala|lua|sh|bash|sql|md|rst|txt|ya?ml|toml|json|ini|cfg|html?|css|scss|vue|svelte|ex|exs|erl|hs|ml|clj|dart|proto|graphql)$")
def _is_name_segment(segment: str) -> bool:
"""True if `segment` names something rather than being an extension or a number."""
return bool(segment) and not segment.isdigit() and not _FILE_SUFFIX_RE.match(segment)
def _qualified_tail(norm_label: str) -> tuple[int, str] | None:
"""Split a label into `(qualifier_token_count, tail_key)`, or `None` if unqualified.
`public.sweep_widget_state()` -> `(1, "sweep widget state")`: the tail is the
part a query would actually name. Segments are split on punctuation; a
qualifier can also be CamelCase, so `Index.ClientLive` -> `(1, "client live")`.
"""
label = (norm_label or "").strip()
# Cheap reject first: without a separator and without an inner capital there
# is nothing to split. This is the common case on a whole-graph pass, and it
# keeps the regex work off every plain identifier.
if not _QUALIFIER_MAYBE_RE.search(label):
return None
parts = [p for p in re.split(_QUALIFIER_SEPARATORS, label) if p]
# Drop trailing non-name segments (`lib/foo/bar.py` -> `lib`, `foo`, `bar`).
while parts and not _is_name_segment(parts[-1]):
parts.pop()
if not parts:
return None
tail = parts[-1]
if len(parts) > 1:
head_tokens = len(_search_tokens(" ".join(parts[:-1])))
if head_tokens:
return head_tokens, _name_key(tail)
# No separator: only a CamelCase qualifier can still leave one. Require at
# least two words and an inner capital, so all-lower snake_case names are
# left alone (they are already matched as one token run).
words = _CAMEL_WORD_RE.findall(tail)
if len(words) < 2 or not any(w[:1].isupper() for w in words[1:]):
return None
head_tokens = len(_search_tokens(" ".join(words[:-1])))
if not head_tokens:
return None
return head_tokens, _name_key(words[-1])
def _name_key(text: str) -> str:
"""Token-joined form of an already-normalized name, for comparing two names.
`norm_label` has been lowercased and had its diacritics stripped already, so
splitting on non-alphanumerics is all `_search_tokens` would add here — and
skipping the per-call Unicode normalization matters, this runs on the whole
graph.
"""
stripped = str(text or "").strip(_NAME_EDGES + " ").lower()
return " ".join(re.findall(r"[^\W_]+", stripped))
def _flatten_attr_text(val, parts: list[str]) -> None:
if isinstance(val, dict):
@@ -712,6 +790,17 @@ def _score_query(
or label_tokens.startswith(joined)
):
score += _PREFIX_MATCH_BONUS * 10 * joined_w
else:
# Qualified name: the label is `<qualifier>.<rest>` (or a
# CamelCase variant) and the query names the rest. Ranking
# below the exact tier — the label is not what was typed — but
# above what the per-token tiers can add up to for a node whose
# whole label is one query token (#5080).
qualified = _qualified_tail(norm_label)
if qualified is not None and qualified[0] <= _QUALIFIED_MAX_TOKENS:
qualifier_tokens, tail_key = qualified
if tail_key and tail_key == joined:
score += _QUALIFIED_MATCH_BONUS * joined_w / qualifier_tokens
# Term coverage (#1602): scale the per-term exact/prefix tiers by the
# squared fraction of query terms the node's LABEL matches, so a lone
# generic word that happens to equal a short label (query term "home"
+84
View File
@@ -2166,3 +2166,87 @@ def test_an_exact_spelling_does_not_break_a_tie_between_two_files():
nid, err = _resolve_single_node(G, "CheckHealth")
assert nid is None
assert err.startswith("Ambiguous:"), err
# --- schema/namespace-qualified labels (#5080) ---
def _qualified_graph() -> nx.Graph:
"""A SQL function behind a schema prefix, plus nodes whose whole label is one query token."""
G = nx.Graph()
for i in range(4):
G.add_node(f"migrations/04{i}_widget_sweep.sql::public.sweep_widget_state()",
label="public.sweep_widget_state()", norm_label="public.sweep_widget_state()",
source_file=f"migrations/04{i}_widget_sweep.sql", community=0)
G.add_node("consts_sweep", label="SWEEP", norm_label="sweep", source_file="src/consts.py", community=0)
G.add_node("consts_widget", label="WIDGET", norm_label="widget", source_file="src/consts.py", community=0)
G.add_node("types_state", label="State", norm_label="state", source_file="src/types.py", community=0)
for i in range(6):
G.add_node(f"noise_{i}", label=f"unrelated_{i}", source_file=f"src/noise{i}.py", community=1)
return G
def test_qualified_label_beats_a_whole_label_token_collision():
"""`query sweep_widget_state` must seed on `public.sweep_widget_state()` (#5080).
Every one of `SWEEP`, `WIDGET` and `State` exactly equals a query token while
the function only prefix/substring-matches them, so without the qualified
tier the three collisions take the seed slots and the function never gets
traversed — whereas `explain sweep_widget_state` lists it. The user does not
type the schema, so the qualifier cannot be part of the match.
"""
G = _qualified_graph()
scored = _score_nodes(G, ["sweep_widget_state"])
target = "migrations/040_widget_sweep.sql::public.sweep_widget_state()"
assert scored[0][1] == target
# All four migrations define the same function, so they tie; what matters is
# that the collisions come after them rather than taking the seed slots.
assert all(nid.startswith("migrations/") for _s, nid in scored[:4])
assert scored[4][0] < scored[0][0], "the qualified match must strictly outrank the token collisions"
text = _query_graph_text(G, "sweep_widget_state", token_budget=4000)
assert "public.sweep_widget_state()" in text
@pytest.mark.parametrize("question", ["public.sweep_widget_state", "public.sweep_widget_state()"])
def test_typing_the_qualifier_still_works(question):
"""Pinning the qualifier keeps resolving — and lands on the exact tier, not the qualified one."""
G = _qualified_graph()
scored = _score_nodes(G, [question])
assert scored[0][1].startswith("migrations/040_widget_sweep.sql::public.sweep_widget_state()")
assert _find_node(G, question)
def test_qualified_tier_stays_below_an_exact_label():
"""A label equal to the query always wins over a qualified label ending in it."""
G = nx.Graph()
G.add_node("qualified", label="public.sweep()", norm_label="public.sweep()", source_file="m.sql", community=0)
G.add_node("plain", label="sweep", norm_label="sweep", source_file="s.py", community=0)
scored = _score_nodes(G, ["sweep"])
assert scored[0][1] == "plain"
def test_qualified_tier_ignores_a_partial_tail():
"""Only a tail equal to the whole query counts; a longer tail must not."""
G = nx.Graph()
G.add_node("long", label="public.sweep_state_machine()", norm_label="public.sweep_state_machine()",
source_file="m.sql", community=0)
G.add_node("other", label="sweep", norm_label="sweep", source_file="s.py", community=0)
by_id = {nid: s for s, nid in _score_nodes(G, ["sweep"])}
assert by_id["other"] > 0
assert by_id["long"] < by_id["other"]
def test_qualified_tail_split():
from graphify.serve import _qualified_tail
assert _qualified_tail("public.sweep_widget_state()") == (1, "sweep widget state")
assert _qualified_tail("Index.ClientLive") == (1, "clientlive")
assert _qualified_tail("fmt.Println") == (1, "println")
assert _qualified_tail("Widget::sweep") == (1, "sweep")
# Not names: file extensions, numbers, plain snake_case.
assert _qualified_tail("lib/foo/bar.py") == (2, "bar")
assert _qualified_tail("3.14") is None
assert _qualified_tail("HTTPClient") is None
assert _qualified_tail("sweep_widget_state") is None
assert _qualified_tail("") is None