fix(query): order the per-term guaranteed seeds by match strength (#4357)
_pick_seeds appended the per-term guaranteed seeds (#1445) in sorted(best_seed_by_term), alphabetical term order,
and the renderer prints seeds first, so a weak match on an early-alphabet term led a specific term's exact match.
_score_query now returns term_order: the per-term winners by their existing key (-singleton score, which carries
the term's IDF weight, then -degree, label length, node id), the term breaking ties. _query_graph_text passes it to
_pick_seeds. The same seeds are picked and the order is deterministic; without term_order the sorted order is kept.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 7bcbc60ac1)
This commit is contained in:
1 parent
c8d769f95c
commit
d3f8687c00
2 files changed
+89
-3
No files matched your search
+16
-3
@@ -543,6 +543,8 @@ class _QueryScores(NamedTuple):
|
||||
"""
|
||||
ranked: list[tuple[float, str]]
|
||||
best_seed_by_term: dict[str, str]
|
||||
# Terms of `best_seed_by_term`, strongest per-term match first (see `_pick_seeds`).
|
||||
term_order: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
|
||||
@@ -734,9 +736,14 @@ def _score_query(
|
||||
# match beats a longer superset that happens to share the same score.
|
||||
scored.sort(key=lambda s: (-s[0], len(G.nodes[s[1]].get("label") or s[1]), s[1]))
|
||||
best_seed_by_term: dict[str, str] = {}
|
||||
term_order: tuple[str, ...] = ()
|
||||
if collect_per_term_seeds and best_by_term:
|
||||
best_seed_by_term = {t: nid for t, (_key, nid) in best_by_term.items()}
|
||||
return _QueryScores(ranked=scored, best_seed_by_term=best_seed_by_term)
|
||||
# Strongest per-term winner first: the key is (-singleton score, -degree, label length, node id), and the
|
||||
# singleton score already carries the term's IDF weight, so a specific term's exact match leads and a
|
||||
# common term's substring hit trails. The term itself breaks remaining ties, so the order is deterministic.
|
||||
term_order = tuple(t for t, _ in sorted(best_by_term.items(), key=lambda kv: (kv[1][0], kv[0])))
|
||||
return _QueryScores(ranked=scored, best_seed_by_term=best_seed_by_term, term_order=term_order)
|
||||
|
||||
|
||||
def _pick_scored_endpoint(G: nx.Graph, scored: list[tuple[float, str]], query: str) -> str:
|
||||
@@ -770,6 +777,7 @@ def _pick_seeds(
|
||||
*,
|
||||
G: "nx.Graph | None" = None,
|
||||
best_seed_by_term: dict[str, str] | None = None,
|
||||
term_order: "tuple[str, ...] | list[str] | None" = None,
|
||||
) -> list[str]:
|
||||
"""Select BFS seed nodes, stopping when score drops too far below the top.
|
||||
|
||||
@@ -844,7 +852,12 @@ def _pick_seeds(
|
||||
# The per-label dedup cap also gates these additions, so the guarantee
|
||||
# cannot reintroduce a second copy of an already-seeded generic label
|
||||
# (#1766).
|
||||
for term in sorted(best_seed_by_term):
|
||||
# With `term_order` (from `_score_query`), the guaranteed seeds follow the strength of each term's best
|
||||
# match, strongest first, so the seeds the renderer prints first are the strongest; without it, the
|
||||
# legacy sorted-term order.
|
||||
ordered_terms = [t for t in (term_order or ()) if t in best_seed_by_term]
|
||||
ordered_terms += sorted(t for t in best_seed_by_term if t not in set(ordered_terms))
|
||||
for term in ordered_terms:
|
||||
best_nid = best_seed_by_term[term]
|
||||
# Honor the same per-label cap so the per-term guarantee can't
|
||||
# reintroduce a second copy of an already-seeded generic label.
|
||||
@@ -1410,7 +1423,7 @@ def _query_graph_text(
|
||||
best_seed_by_term = {
|
||||
t: nid for t, nid in best_seed_by_term.items() if t not in intent
|
||||
}
|
||||
start_nodes = _pick_seeds(qs.ranked, G=G, best_seed_by_term=best_seed_by_term)
|
||||
start_nodes = _pick_seeds(qs.ranked, G=G, best_seed_by_term=best_seed_by_term, term_order=qs.term_order)
|
||||
if not start_nodes:
|
||||
return _QUERY_NO_MATCH
|
||||
resolved_filters, filter_source = _resolve_context_filters(question, context_filters)
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""The per-term guaranteed seeds follow the strength of each term's best match, strongest first.
|
||||
|
||||
`_pick_seeds` guarantees one seed per query term (#1445). Those seeds used to be appended in alphabetical term
|
||||
order, and the renderer prints seeds first, so on a long query a weak match on an early-alphabet term was printed
|
||||
ahead of a specific term's exact match. `_score_query` now returns `term_order` (strongest per-term winner first,
|
||||
the term breaking ties) and `_query_graph_text` passes it on. Which seeds are picked does not change, only their
|
||||
order, and the order stays deterministic."""
|
||||
from __future__ import annotations
|
||||
|
||||
import networkx as nx
|
||||
|
||||
from graphify.serve import _pick_seeds, _query_graph_text, _score_query
|
||||
|
||||
|
||||
def _graph():
|
||||
G = nx.Graph()
|
||||
G.add_node("top", label="TopLevelRouter", source_file="router.py", source_location="L1")
|
||||
G.add_node("apple_weak", label="apple_pie_formatting_helper", source_file="fmt.py", source_location="L3")
|
||||
G.add_node("zebra_exact", label="zebra", source_file="zebra.py", source_location="L1")
|
||||
for i in range(6): # make "apple" common, so its match weighs less
|
||||
G.add_node(f"apple{i}", label=f"apple_util_{i}", source_file=f"apples{i}.py", source_location="L1")
|
||||
G.add_edge("top", "apple_weak")
|
||||
G.add_edge("top", "zebra_exact")
|
||||
return G
|
||||
|
||||
|
||||
def test_pick_seeds_follows_term_order_when_given():
|
||||
G = _graph()
|
||||
scored = [(1000.0, "top"), (1.0, "apple_weak"), (1.0, "zebra_exact")]
|
||||
best = {"apple": "apple_weak", "zebra": "zebra_exact"}
|
||||
assert _pick_seeds(scored, G=G, best_seed_by_term=best, term_order=("zebra", "apple")) == ["top", "zebra_exact", "apple_weak"]
|
||||
|
||||
|
||||
def test_pick_seeds_keeps_sorted_term_order_without_it():
|
||||
G = _graph()
|
||||
scored = [(1000.0, "top"), (1.0, "apple_weak"), (1.0, "zebra_exact")]
|
||||
best = {"apple": "apple_weak", "zebra": "zebra_exact"}
|
||||
assert _pick_seeds(scored, G=G, best_seed_by_term=best) == ["top", "apple_weak", "zebra_exact"]
|
||||
|
||||
|
||||
def test_pick_seeds_appends_terms_missing_from_term_order_in_sorted_order():
|
||||
G = _graph()
|
||||
scored = [(1000.0, "top")]
|
||||
best = {"apple": "apple_weak", "zebra": "zebra_exact"}
|
||||
assert _pick_seeds(scored, G=G, best_seed_by_term=best, term_order=("zebra",)) == ["top", "zebra_exact", "apple_weak"]
|
||||
|
||||
|
||||
def test_score_query_orders_terms_by_their_best_match_strength():
|
||||
qs = _score_query(_graph(), ["apple", "zebra"], collect_per_term_seeds=True)
|
||||
assert set(qs.term_order) == set(qs.best_seed_by_term)
|
||||
assert qs.term_order[0] == "zebra" # an exact label match on a rare term leads
|
||||
assert qs.best_seed_by_term["zebra"] == "zebra_exact"
|
||||
|
||||
|
||||
def _five_term_graph():
|
||||
"""Five terms with exact label matches; "apple" is common (eight more labels contain it), so its exact match
|
||||
carries less IDF weight than the rare "charlie". Three seeds fill the gap window; "apple" and "charlie" arrive
|
||||
through the per-term guarantee."""
|
||||
G = nx.Graph()
|
||||
for name in ("alpha", "bravo", "charlie", "zebra", "apple"):
|
||||
G.add_node(name, label=name, source_file=f"{name}.py", source_location="L1")
|
||||
for i in range(8):
|
||||
G.add_node(f"apple{i}", label=f"apple_util_{i}", source_file=f"apples{i}.py", source_location="L1")
|
||||
return G
|
||||
|
||||
|
||||
def test_query_prints_the_stronger_guaranteed_seed_first_and_is_deterministic():
|
||||
G = _five_term_graph()
|
||||
text = _query_graph_text(G, "alpha bravo charlie apple zebra", mode="bfs", depth=1)
|
||||
assert text == _query_graph_text(G, "alpha bravo charlie apple zebra", mode="bfs", depth=1)
|
||||
start = text.split("Start: ", 1)[1].split("]", 1)[0]
|
||||
# Alphabetical term order printed the common term's seed ("apple") ahead of the rare exact match ("charlie").
|
||||
assert start.index("'charlie'") < start.index("'apple'"), start
|
||||
Reference in new issue
Block a user