java-codebase-rag 0.8.0__py3-none-any.whl → 0.9.1__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.
search_lancedb.py CHANGED
@@ -41,6 +41,11 @@ JAVA_ENRICHED_COLUMNS: tuple[str, ...] = (
41
41
  "capabilities",
42
42
  )
43
43
 
44
+ # Over-fetch multiplier for dedup: fetch 4x to absorb per-FQN chunk multiplicity
45
+ # so that after collapsing by primary_type_fqn, a page stays full and the +1
46
+ # truncation sentinel survives. The formula: need = max((limit + offset) * 4, limit + offset + 1)
47
+ DEDUP_OVERFETCH = 4
48
+
44
49
  VECTOR_COLUMN = "embedding"
45
50
  _FTS_READY: set[tuple[str, str]] = set()
46
51
  _FTS_LOCK = threading.Lock()
@@ -201,6 +206,14 @@ _ROLE_SCORE_WEIGHTS: dict[str, float] = {
201
206
  "DTO": -0.08,
202
207
  }
203
208
 
209
+ # Theoretical maximum for hybrid composite score (used for display normalization).
210
+ # Hybrid sort metric: raw_rrf * (import_factor if import_heavy else 1)
211
+ # + role_weight + symbol_bonus
212
+ # where raw_rrf ≤ 2/(k+1) for 2-list RRF, role_weight ≤ max(_ROLE_SCORE_WEIGHTS),
213
+ # and symbol_bonus ≤ _SYMBOL_MATCH_BONUS_CAP + _TYPE_MATCH_BONUS_CAP + _ACTION_VERB_BONUS.
214
+ # The import factor is ≤ 1, so we use the raw max (2/61).
215
+ _HYBRID_SCORE_MAX = (2.0 / 61.0) + max(_ROLE_SCORE_WEIGHTS.values()) + _SYMBOL_MATCH_BONUS_CAP + _TYPE_MATCH_BONUS_CAP + _ACTION_VERB_BONUS
216
+
204
217
 
205
218
  def _query_tokens(query: str) -> set[str]:
206
219
  """Lowercased alpha-only tokens from the query, minus stopwords, len >= 3.
@@ -353,7 +366,7 @@ def _hybrid_sort_key(r: dict) -> float:
353
366
  comps["hybrid_rrf"] = s
354
367
  if r.get("_hints", {}).get("import_heavy"):
355
368
  s *= _IMPORT_HYBRID_SCORE_FACTOR
356
- comps["import_penalty"] = _IMPORT_HYBRID_SCORE_FACTOR
369
+ comps["import_penalty"] = 1.0 - _IMPORT_HYBRID_SCORE_FACTOR
357
370
  s += _role_weight(r)
358
371
  s += float(comps.get("symbol_bonus", 0.0))
359
372
  return -s
@@ -376,7 +389,8 @@ def explain_score_components(
376
389
  comps = {}
377
390
  parts: list[str] = []
378
391
  if hybrid:
379
- rrf = comps.get("hybrid_rrf")
392
+ # Prefer rrf_raw (added by PR-SEARCH-1a) for explanation
393
+ rrf = comps.get("rrf_raw") or comps.get("hybrid_rrf")
380
394
  if rrf is not None:
381
395
  parts.append(f"rrf={float(rrf):.3f}")
382
396
  else:
@@ -403,6 +417,46 @@ def l2_distance_to_score(distance: float) -> float:
403
417
  return 1.0 - distance * distance / 2.0
404
418
 
405
419
 
420
+ def _effective_distance(comps: dict[str, float]) -> float:
421
+ """Compute the adjusted distance used for sorting.
422
+
423
+ Matches _vector_sort_key logic: distance + import_penalty - role_weight - symbol_bonus.
424
+ """
425
+ d = comps.get("distance", 0.0)
426
+ d += comps.get("import_penalty", 0.0)
427
+ d -= comps.get("role_weight", 0.0)
428
+ d -= comps.get("symbol_bonus", 0.0)
429
+ return d
430
+
431
+
432
+ def _clamp01(x: float) -> float:
433
+ """Clamp a value to the [0.0, 1.0] range."""
434
+ if x < 0.0:
435
+ return 0.0
436
+ if x > 1.0:
437
+ return 1.0
438
+ return x
439
+
440
+
441
+ def _hybrid_post_sort_normalization(rows: list[dict]) -> None:
442
+ """Set honest displayed scores for hybrid search after sorting.
443
+
444
+ Reconstructs the composite score (raw_rrf * import_factor + role_weight + symbol_bonus)
445
+ and normalizes by _HYBRID_SCORE_MAX to ensure rank-monotonicity.
446
+
447
+ Mutates rows in-place, replacing _score with the normalized value.
448
+ """
449
+ for r in rows:
450
+ comps = r.setdefault("_score_components", {})
451
+ raw = comps.get("hybrid_rrf", 0.0)
452
+ comps["rrf_raw"] = raw # preserve raw RRF for --explain. NOTE: when graph_expand + hybrid combine (Phase 2), _rrf_merge below overwrites this with graph-RRF, so --explain would show graph-RRF not hybrid-RRF.
453
+ s = raw
454
+ if r.get("_hints", {}).get("import_heavy"):
455
+ s *= _IMPORT_HYBRID_SCORE_FACTOR
456
+ s += comps.get("role_weight", 0.0) + comps.get("symbol_bonus", 0.0)
457
+ r["_score"] = _clamp01(s / _HYBRID_SCORE_MAX)
458
+
459
+
406
460
  def _escape_like_fragment(s: str) -> str:
407
461
  return s.replace("'", "''")
408
462
 
@@ -790,9 +844,72 @@ def _rrf_merge(
790
844
  existing["_rrf_score"] = float(existing.get("_rrf_score", 0.0)) + contribution
791
845
  merged = list(pool.values())
792
846
  merged.sort(key=lambda r: -float(r.get("_rrf_score", 0.0)))
847
+ # Normalize displayed _rrf_score to [0,1] by theoretical max
848
+ # RRF max = Σ weight·1/(k+rank+1); theoretical max when all rows are rank 0
849
+ # with weight 1.0 = num_lists / (k + 1)
850
+ num_lists = len(lists)
851
+ max_rrf = num_lists / (k + 1)
852
+ for r in merged:
853
+ raw_score = float(r.get("_rrf_score", 0.0))
854
+ comps = r.setdefault("_score_components", {})
855
+ comps["rrf_raw"] = raw_score
856
+ r["_rrf_score"] = _clamp01(raw_score / max_rrf)
793
857
  return merged
794
858
 
795
859
 
860
+ def _dedup_by_fqn(rows: list[dict], dedup_by_fqn: bool = True) -> list[dict]:
861
+ """Deduplicate rows by primary_type_fqn (java table only).
862
+
863
+ When dedup_by_fqn is True, collapses multiple chunks of the same
864
+ primary_type_fqn into one row (first-seen-wins, since rows are pre-sorted
865
+ so the first is the best chunk). Each survivor gets a _chunks_collapsed
866
+ field (>=1) counting how many rows were collapsed into it.
867
+
868
+ Rows without primary_type_fqn (sql/yaml tables) get a unique __id:<id>
869
+ key so they pass through unchanged (each row is unique).
870
+
871
+ When dedup_by_fqn is False, returns rows unchanged (regression guard).
872
+ """
873
+ if not dedup_by_fqn:
874
+ # Non-dedup path: return unchanged, byte-identical to prior behavior
875
+ return rows
876
+
877
+ deduped: list[dict] = []
878
+ seen_keys: dict[str, dict] = {}
879
+ collapsed_counts: dict[str, int] = {}
880
+
881
+ for row in rows:
882
+ # Build dedup key: primary_type_fqn for java rows, unique __id:<id> for sql/yaml
883
+ fqn = row.get("primary_type_fqn")
884
+ if fqn:
885
+ key = str(fqn)
886
+ else:
887
+ # sql/yaml rows have no primary_type_fqn → unique key per row
888
+ row_id = row.get("id") or id(row)
889
+ key = f"__id:{row_id}"
890
+
891
+ if key not in seen_keys:
892
+ # First occurrence: keep it
893
+ seen_keys[key] = row
894
+ collapsed_counts[key] = 1
895
+ deduped.append(row)
896
+ else:
897
+ # Duplicate: increment collapse count, discard this row
898
+ collapsed_counts[key] += 1
899
+
900
+ # Annotate each survivor with _chunks_collapsed
901
+ for row in deduped:
902
+ fqn = row.get("primary_type_fqn")
903
+ if fqn:
904
+ key = str(fqn)
905
+ else:
906
+ row_id = row.get("id") or id(row)
907
+ key = f"__id:{row_id}"
908
+ row["_chunks_collapsed"] = collapsed_counts[key]
909
+
910
+ return deduped
911
+
912
+
796
913
  def run_search(
797
914
  query: str,
798
915
  *,
@@ -819,6 +936,7 @@ def run_search(
819
936
  exclude_roles: list[str] | None = None,
820
937
  capability: str | None = None,
821
938
  capability_in: list[str] | None = None,
939
+ dedup_by_fqn: bool = False,
822
940
  ) -> list[dict]:
823
941
  effective_hybrid = hybrid
824
942
  effective_fts = fts_text
@@ -852,7 +970,16 @@ def run_search(
852
970
  fts_for_hybrid = effective_fts if effective_fts is not None else query
853
971
 
854
972
  db = lancedb.connect(uri)
855
- need = max(limit + offset, 1)
973
+ if dedup_by_fqn:
974
+ # Over-fetch to absorb per-FQN chunk multiplicity: fetch 4x so that
975
+ # after collapsing, the page stays full and the +1 truncation sentinel survives.
976
+ # The 4× factor assumes typical per-FQN chunk multiplicity; a single type with
977
+ # many high-ranking chunks (e.g. generated/God classes) could starve the page or
978
+ # make the +1 truncation sentinel unreliable; Phase 1 may revisit adaptive over-fetch (plan risk #1).
979
+ need = max((limit + offset) * DEDUP_OVERFETCH, limit + offset + 1)
980
+ else:
981
+ # Non-dedup path: exact fetch as before
982
+ need = max(limit + offset, 1)
856
983
 
857
984
  extra_java = _build_extra_predicates(
858
985
  columns=_table_columns(uri, TABLES["java"], db),
@@ -887,8 +1014,15 @@ def run_search(
887
1014
  _apply_symbol_bonus(rows, query_toks)
888
1015
  if effective_hybrid:
889
1016
  rows.sort(key=_hybrid_sort_key)
1017
+ # Hybrid: set honest displayed score from composite sort metric, clamped to [0,1]
1018
+ _hybrid_post_sort_normalization(rows)
890
1019
  else:
891
1020
  rows.sort(key=_vector_sort_key)
1021
+ # Vector: set honest displayed score from adjusted distance, clamped to [0,1]
1022
+ for r in rows:
1023
+ comps = r.setdefault("_score_components", {})
1024
+ effective_dist = _effective_distance(comps)
1025
+ r["_score"] = _clamp01(l2_distance_to_score(effective_dist))
892
1026
 
893
1027
  if graph_expand and key == "java" and expand_depth > 0:
894
1028
  rows = _graph_expand_merge(
@@ -902,6 +1036,9 @@ def run_search(
902
1036
  ladybug_path=ladybug_path,
903
1037
  )
904
1038
 
1039
+ # Dedup by primary_type_fqn after all sorting/merging, before windowing
1040
+ rows = _dedup_by_fqn(rows, dedup_by_fqn=dedup_by_fqn)
1041
+
905
1042
  window = rows[offset : offset + limit]
906
1043
  if context_neighbors > 0 and key == "java":
907
1044
  _attach_neighbor_context(window, db=db, neighbors=context_neighbors, uri=uri)
@@ -931,6 +1068,15 @@ def run_search(
931
1068
  r["_skip_role_weight"] = True
932
1069
  _apply_symbol_bonus(merged, query_toks)
933
1070
  merged.sort(key=_vector_sort_key)
1071
+ # Vector: set honest displayed score from adjusted distance, clamped to [0,1]
1072
+ for r in merged:
1073
+ comps = r.setdefault("_score_components", {})
1074
+ effective_dist = _effective_distance(comps)
1075
+ r["_score"] = _clamp01(l2_distance_to_score(effective_dist))
1076
+
1077
+ # Dedup by primary_type_fqn after all sorting/merging, before windowing
1078
+ merged = _dedup_by_fqn(merged, dedup_by_fqn=dedup_by_fqn)
1079
+
934
1080
  window = merged[offset : offset + limit]
935
1081
  if context_neighbors > 0:
936
1082
  _attach_neighbor_context(window, db=db, neighbors=context_neighbors, uri=uri)
server.py CHANGED
@@ -349,6 +349,31 @@ async def run_refresh_pipeline(
349
349
  )
350
350
  proc: asyncio.subprocess.Process | None = None
351
351
  out_b, err_b = b"", b""
352
+ # DROP the Lance target tables so the update takes the fast INSERT path
353
+ # instead of cocoindex's in-place bulk-update, which emits ~one deletion-
354
+ # vector + version commit PER matched row — O(rows) of tiny file IO that
355
+ # hangs for many minutes on large repos. Drop+recreate is identical output
356
+ # for a full rebuild (the very thing --full-reprocess means). Same fix on
357
+ # the sync path: pipeline.run_cocoindex_update. Drop failure is non-fatal:
358
+ # the update falls back to the slow in-place path.
359
+ try:
360
+ drop_proc = await asyncio.create_subprocess_exec(
361
+ str(cocoindex_bin),
362
+ "drop",
363
+ _COCOINDEX_TARGET,
364
+ "-f",
365
+ cwd=str(flow_path.parent),
366
+ env=_cocoindex_subprocess_env(root),
367
+ stdout=asyncio.subprocess.PIPE,
368
+ stderr=asyncio.subprocess.PIPE,
369
+ )
370
+ await drop_proc.communicate()
371
+ except Exception as exc:
372
+ print(
373
+ f"java-codebase-rag: drop-before-reprocess failed ({exc!s}); "
374
+ "falling back to in-place update",
375
+ file=sys.stderr,
376
+ )
352
377
  if quiet:
353
378
  try:
354
379
  proc = await asyncio.create_subprocess_exec(
@@ -512,6 +537,7 @@ def create_mcp_server() -> FastMCP:
512
537
  "structured DSL inside `query`; structured predicates belong in `find`. "
513
538
  "For identifier-shaped lookups (FQN, id, route/client identifiers, …), use `resolve` first; "
514
539
  "use `search` for natural-language or ranked fuzzy discovery. "
540
+ "Set `explain=true` to include score breakdown per hit. "
515
541
  "Successful responses echo `limit`/`offset`."
516
542
  ),
517
543
  )
@@ -538,6 +564,14 @@ def create_mcp_server() -> FastMCP:
538
564
  "predicate. Unknown keys or populated fields not applicable to symbols return success=false."
539
565
  ),
540
566
  ),
567
+ explain: bool = Field(
568
+ default=False,
569
+ description="If true, include score_components in each SearchHit (breakdown of distance/rrf, role, symbol, import_penalty).",
570
+ ),
571
+ chunks: bool = Field(
572
+ default=False,
573
+ description="If true, show every chunk (default collapses to one row per symbol/type).",
574
+ ),
541
575
  ) -> mcp_v2.SearchOutput:
542
576
  scoped_filter = _scope_manager.apply_auto_scope(filter) if _scope_manager else filter
543
577
  return await asyncio.to_thread(
@@ -549,7 +583,9 @@ def create_mcp_server() -> FastMCP:
549
583
  offset,
550
584
  path_contains,
551
585
  scoped_filter,
586
+ explain,
552
587
  None,
588
+ not chunks, # dedup=True by default; chunks=True opts out
553
589
  )
554
590
 
555
591
  @mcp.tool(