@@ -107,6 +107,11 @@ def allows_result_path(self, path: str, *, corpus: str) -> bool:
107107 def path_weight (self , path : str ) -> float :
108108 return self .retrieval .path_weight (path )
109109
110+ def needs_prefilter_expansion (self , * , corpus : str ) -> bool :
111+ if corpus == "sessions" :
112+ return False
113+ return bool (self .retrieval .allow or self .retrieval .deny or not self .retrieval .include_durable_context )
114+
110115
111116class _WakeBuilder (Protocol ):
112117 def build (self , req : WakeReq ) -> WakeResp : ...
@@ -511,13 +516,14 @@ def _search_candidates(
511516 source_policy : SourcePolicy | None = None ,
512517) -> list [object ]:
513518 scored_results : dict [str , tuple [float , object ]] = {}
519+ request_k = _expanded_candidate_limit (k , source_policy = source_policy , corpus = corpus )
514520 for query_index , query in enumerate (query for query in queries if query .strip ()):
515521 if deadline is not None and deadline .expired :
516522 break
517523 response = search_engine .search (
518524 SearchReq (
519525 query = query ,
520- k = k ,
526+ k = request_k ,
521527 mode = mode ,
522528 corpus = corpus ,
523529 include_content = include_content ,
@@ -529,6 +535,10 @@ def _search_candidates(
529535 path = _result_path (result )
530536 if not path :
531537 continue
538+ if not _is_active_memory_candidate (result , corpus = corpus ):
539+ continue
540+ if source_policy is not None and not source_policy .allows_result_path (path , corpus = corpus ):
541+ continue
532542 raw_score = float (getattr (result , "score" , 0.0 ) or 0.0 )
533543 rank_score = getattr (result , "rank_score" , None )
534544 normalized_score = getattr (result , "score_normalized" , None )
@@ -549,6 +559,12 @@ def _search_candidates(
549559 return [result for _score , result in ordered [:k ]]
550560
551561
562+ def _expanded_candidate_limit (k : int , * , source_policy : SourcePolicy | None , corpus : str ) -> int :
563+ if source_policy is None or not source_policy .needs_prefilter_expansion (corpus = corpus ):
564+ return k
565+ return min (50 , max (k , k * 4 ))
566+
567+
552568def _preferred_active_memory_results (results : list [object ]) -> list [object ]:
553569 fresh_results = [result for result in results if not str (getattr (result , "stale_warning" , "" ) or "" ).strip ()]
554570 return fresh_results or results
0 commit comments