Blame view

tests/test_search_rerank_window.py 43.1 KB
5f7d7f09   tangwang   性能测试报告.md
1
2
  from __future__ import annotations
  
0ba0e0fc   tangwang   1. rerank漏斗配置优化
3
  from dataclasses import dataclass, field
5f7d7f09   tangwang   性能测试报告.md
4
5
6
7
  from pathlib import Path
  from types import SimpleNamespace
  from typing import Any, Dict, List
  
deccd68a   tangwang   Added the SKU pre...
8
  import numpy as np
5f7d7f09   tangwang   性能测试报告.md
9
10
11
12
  import yaml
  
  from config import (
      ConfigLoader,
9df421ed   tangwang   基于eval框架开始调参
13
      FineRankConfig,
5f7d7f09   tangwang   性能测试报告.md
14
15
16
      FunctionScoreConfig,
      IndexConfig,
      QueryConfig,
5f7d7f09   tangwang   性能测试报告.md
17
18
19
20
21
      RerankConfig,
      SPUConfig,
      SearchConfig,
  )
  from context import create_request_context
cda1cd62   tangwang   意图分析&应用 baseline
22
  from query.style_intent import DetectedStyleIntent, StyleIntentProfile
5f7d7f09   tangwang   性能测试报告.md
23
24
  from search.searcher import Searcher
  
99b72698   tangwang   测试回归钩子梳理
25
26
27
28
  import pytest
  
  pytestmark = [pytest.mark.search, pytest.mark.regression]
  
5f7d7f09   tangwang   性能测试报告.md
29
30
31
32
33
34
35
36
  
  @dataclass
  class _FakeParsedQuery:
      original_query: str
      query_normalized: str
      rewritten_query: str
      detected_language: str = "en"
      translations: Dict[str, str] = None
0ba0e0fc   tangwang   1. rerank漏斗配置优化
37
      keywords_queries: Dict[str, str] = field(default_factory=dict)
5f7d7f09   tangwang   性能测试报告.md
38
      query_vector: Any = None
0ba0e0fc   tangwang   1. rerank漏斗配置优化
39
40
      image_query_vector: Any = None
      query_tokens: List[str] = field(default_factory=list)
cda1cd62   tangwang   意图分析&应用 baseline
41
      style_intent_profile: Any = None
5f7d7f09   tangwang   性能测试报告.md
42
  
74fdf9bd   tangwang   1.
43
44
45
46
47
48
49
50
51
      def text_for_rerank(self) -> str:
          from query.query_parser import rerank_query_text
  
          return rerank_query_text(
              self.original_query,
              detected_language=self.detected_language,
              translations=self.translations,
          )
  
5f7d7f09   tangwang   性能测试报告.md
52
53
54
55
56
57
58
      def to_dict(self) -> Dict[str, Any]:
          return {
              "original_query": self.original_query,
              "query_normalized": self.query_normalized,
              "rewritten_query": self.rewritten_query,
              "detected_language": self.detected_language,
              "translations": self.translations or {},
cda1cd62   tangwang   意图分析&应用 baseline
59
60
61
              "style_intent_profile": (
                  self.style_intent_profile.to_dict() if self.style_intent_profile is not None else None
              ),
5f7d7f09   tangwang   性能测试报告.md
62
63
64
          }
  
  
cda1cd62   tangwang   意图分析&应用 baseline
65
66
67
68
69
70
71
72
73
  def _build_style_intent_profile(intent_type: str, canonical_value: str, *dimension_aliases: str) -> StyleIntentProfile:
      aliases = dimension_aliases or (intent_type,)
      return StyleIntentProfile(
          intents=(
              DetectedStyleIntent(
                  intent_type=intent_type,
                  canonical_value=canonical_value,
                  matched_term=canonical_value,
                  matched_query_text=canonical_value,
b712a831   tangwang   意图识别策略和性能优化
74
                  attribute_terms=(canonical_value,),
cda1cd62   tangwang   意图分析&应用 baseline
75
76
77
78
79
80
                  dimension_aliases=tuple(aliases),
              ),
          )
      )
  
  
5f7d7f09   tangwang   性能测试报告.md
81
  class _FakeQueryParser:
ef5baa86   tangwang   混杂语言处理
82
83
84
85
86
87
88
89
      def parse(
          self,
          query: str,
          tenant_id: str,
          generate_vector: bool,
          context: Any,
          target_languages: Any = None,
      ):
5f7d7f09   tangwang   性能测试报告.md
90
91
92
93
94
95
96
97
98
          return _FakeParsedQuery(
              original_query=query,
              query_normalized=query,
              rewritten_query=query,
              translations={},
          )
  
  
  class _FakeQueryBuilder:
0ba0e0fc   tangwang   1. rerank漏斗配置优化
99
100
101
102
103
104
105
106
107
      knn_text_k = 120
      knn_text_k_long = 160
      knn_text_num_candidates = 400
      knn_text_num_candidates_long = 500
      knn_text_boost = 20.0
      knn_image_k = 120
      knn_image_num_candidates = 400
      knn_image_boost = 20.0
  
5f7d7f09   tangwang   性能测试报告.md
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
      def build_query(self, **kwargs):
          return {
              "query": {"match_all": {}},
              "size": kwargs["size"],
              "from": kwargs["from_"],
          }
  
      def build_facets(self, facets: Any):
          return {}
  
      def add_sorting(self, es_query: Dict[str, Any], sort_by: str, sort_order: str):
          return es_query
  
  
  class _FakeESClient:
      def __init__(self, total_hits: int = 5000):
          self.calls: List[Dict[str, Any]] = []
          self.total_hits = total_hits
  
      @staticmethod
      def _apply_source_filter(src: Dict[str, Any], source_spec: Any) -> Dict[str, Any]:
          if source_spec is None:
              return dict(src)
          if source_spec is False:
              return {}
          if isinstance(source_spec, dict):
              includes = source_spec.get("includes") or []
          elif isinstance(source_spec, list):
              includes = source_spec
          else:
              includes = []
          if not includes:
              return dict(src)
          return {k: v for k, v in src.items() if k in set(includes)}
  
      @staticmethod
      def _full_source(doc_id: str) -> Dict[str, Any]:
          return {
              "spu_id": doc_id,
              "title": {"en": f"product-{doc_id}"},
              "brief": {"en": f"brief-{doc_id}"},
              "vendor": {"en": f"vendor-{doc_id}"},
              "skus": [],
          }
  
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
153
154
155
156
157
158
159
160
      def search(
          self,
          index_name: str,
          body: Dict[str, Any],
          size: int,
          from_: int,
          include_named_queries_score: bool = False,
      ):
5f7d7f09   tangwang   性能测试报告.md
161
          self.calls.append(
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
162
163
164
165
166
167
168
              {
                  "index_name": index_name,
                  "body": body,
                  "size": size,
                  "from_": from_,
                  "include_named_queries_score": include_named_queries_score,
              }
5f7d7f09   tangwang   性能测试报告.md
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
          )
          ids_query = (((body or {}).get("query") or {}).get("ids") or {}).get("values")
          source_spec = (body or {}).get("_source")
  
          if isinstance(ids_query, list):
              # Return reversed order intentionally; caller should restore original ranking order.
              ids = [str(i) for i in ids_query][::-1]
              hits = []
              for doc_id in ids:
                  src = self._apply_source_filter(self._full_source(doc_id), source_spec)
                  hit = {"_id": doc_id, "_score": 1.0}
                  if source_spec is not False:
                      hit["_source"] = src
                  hits.append(hit)
          else:
              end = min(from_ + size, self.total_hits)
              hits = []
              for i in range(from_, end):
                  doc_id = str(i)
                  src = self._apply_source_filter(self._full_source(doc_id), source_spec)
                  hit = {"_id": doc_id, "_score": float(self.total_hits - i)}
                  if source_spec is not False:
                      hit["_source"] = src
                  hits.append(hit)
  
          return {
              "took": 8,
              "hits": {
                  "total": {"value": self.total_hits},
                  "max_score": hits[0]["_score"] if hits else 0.0,
                  "hits": hits,
              },
          }
  
  
317c5d2c   tangwang   feat(search): 引入 ...
204
205
206
207
208
209
210
  def _build_search_config(
      *,
      rerank_enabled: bool = True,
      rerank_window: int = 384,
      exact_knn_rescore_enabled: bool = False,
      exact_knn_rescore_window: int = 0,
  ):
5f7d7f09   tangwang   性能测试报告.md
211
212
213
214
      return SearchConfig(
          field_boosts={"title.en": 3.0},
          indexes=[IndexConfig(name="default", label="default", fields=["title.en"])],
          query_config=QueryConfig(enable_text_embedding=False, enable_query_rewrite=False),
5f7d7f09   tangwang   性能测试报告.md
215
          function_score=FunctionScoreConfig(),
317c5d2c   tangwang   feat(search): 引入 ...
216
217
218
219
220
221
          rerank=RerankConfig(
              enabled=rerank_enabled,
              rerank_window=rerank_window,
              exact_knn_rescore_enabled=exact_knn_rescore_enabled,
              exact_knn_rescore_window=exact_knn_rescore_window,
          ),
5f7d7f09   tangwang   性能测试报告.md
222
223
          spu_config=SPUConfig(enabled=False),
          es_index_name="test_products",
5f7d7f09   tangwang   性能测试报告.md
224
          es_settings={},
5f7d7f09   tangwang   性能测试报告.md
225
226
227
228
229
230
231
232
233
234
235
236
237
      )
  
  
  def _build_searcher(config: SearchConfig, es_client: _FakeESClient) -> Searcher:
      searcher = Searcher(
          es_client=es_client,
          config=config,
          query_parser=_FakeQueryParser(),
      )
      searcher.query_builder = _FakeQueryBuilder()
      return searcher
  
  
5f7d7f09   tangwang   性能测试报告.md
238
239
240
241
242
243
  def test_config_loader_rerank_enabled_defaults_true(tmp_path: Path):
      config_data = {
          "es_index_name": "test_products",
          "field_boosts": {"title.en": 3.0},
          "indexes": [{"name": "default", "label": "default", "fields": ["title.en"]}],
          "query_config": {"supported_languages": ["en"], "default_language": "en"},
ef5baa86   tangwang   混杂语言处理
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
          "services": {
              "translation": {
                  "service_url": "http://localhost:6005",
                  "timeout_sec": 3.0,
                  "default_model": "dummy-model",
                  "default_scene": "general",
                  "cache": {
                      "ttl_seconds": 60,
                      "sliding_expiration": True,
                  },
                  "capabilities": {
                      "dummy-model": {
                          "enabled": True,
                          "backend": "llm",
                          "use_cache": True,
                          "model": "dummy-model",
                          "base_url": "http://localhost:6005/v1",
                          "timeout_sec": 3.0,
                      }
                  },
              },
              "embedding": {
                  "provider": "http",
                  "providers": {
                      "http": {
                          "text_base_url": "http://localhost:6005",
                          "image_base_url": "http://localhost:6008",
                      }
                  },
                  "backend": "tei",
                  "backends": {
                      "tei": {
                          "base_url": "http://localhost:8080",
                          "timeout_sec": 3.0,
                          "model_id": "dummy-embedding-model",
                      }
                  },
              },
              "rerank": {
                  "provider": "http",
                  "providers": {
                      "http": {
                          "base_url": "http://localhost:6007",
                          "service_url": "http://localhost:6007/rerank",
                      }
                  },
                  "backend": "bge",
                  "backends": {
                      "bge": {
                          "model_name": "dummy-rerank-model",
                          "device": "cpu",
                          "use_fp16": False,
                          "batch_size": 8,
                          "max_length": 128,
                          "cache_dir": "./model_cache",
                          "enable_warmup": False,
                      }
                  },
              },
          },
5f7d7f09   tangwang   性能测试报告.md
304
          "spu_config": {"enabled": False},
5f7d7f09   tangwang   性能测试报告.md
305
          "function_score": {"score_mode": "sum", "boost_mode": "multiply", "functions": []},
317c5d2c   tangwang   feat(search): 引入 ...
306
307
308
309
310
          "rerank": {
              "rerank_window": 384,
              "exact_knn_rescore_enabled": True,
              "exact_knn_rescore_window": 160,
          },
5f7d7f09   tangwang   性能测试报告.md
311
312
313
314
315
316
317
318
      }
      config_path = tmp_path / "config.yaml"
      config_path.write_text(yaml.safe_dump(config_data), encoding="utf-8")
  
      loader = ConfigLoader(config_path)
      loaded = loader.load_config(validate=False)
  
      assert loaded.rerank.enabled is True
317c5d2c   tangwang   feat(search): 引入 ...
319
320
      assert loaded.rerank.exact_knn_rescore_enabled is True
      assert loaded.rerank.exact_knn_rescore_window == 160
5f7d7f09   tangwang   性能测试报告.md
321
322
  
  
daa2690b   tangwang   漏斗参数调优&呈现优化
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
  def test_config_loader_parses_named_rerank_instances(tmp_path: Path):
      from config.loader import AppConfigLoader
  
      config_data = {
          "es_index_name": "test_products",
          "field_boosts": {"title.en": 3.0},
          "indexes": [{"name": "default", "label": "default", "fields": ["title.en"]}],
          "query_config": {"supported_languages": ["en"], "default_language": "en"},
          "services": {
              "translation": {
                  "service_url": "http://localhost:6005",
                  "timeout_sec": 3.0,
                  "default_model": "dummy-model",
                  "default_scene": "general",
                  "cache": {"ttl_seconds": 60, "sliding_expiration": True},
                  "capabilities": {
                      "dummy-model": {
                          "enabled": True,
                          "backend": "llm",
                          "model": "dummy-model",
                          "base_url": "http://localhost:6005/v1",
                          "timeout_sec": 3.0,
                          "use_cache": True,
                      }
                  },
              },
              "embedding": {
                  "provider": "http",
                  "providers": {"http": {"text_base_url": "http://localhost:6005", "image_base_url": "http://localhost:6008"}},
                  "backend": "tei",
                  "backends": {"tei": {"base_url": "http://localhost:8080", "model_id": "dummy-embedding-model"}},
              },
              "rerank": {
                  "provider": "http",
                  "providers": {
                      "http": {
                          "instances": {
                              "default": {"service_url": "http://localhost:6007/rerank"},
                              "fine": {"service_url": "http://localhost:6009/rerank"},
                          }
                      }
                  },
                  "default_instance": "default",
                  "instances": {
                      "default": {"port": 6007, "backend": "qwen3_vllm_score"},
                      "fine": {"port": 6009, "backend": "bge"},
                  },
                  "backends": {
                      "bge": {"model_name": "BAAI/bge-reranker-v2-m3"},
                      "qwen3_vllm_score": {"model_name": "Qwen/Qwen3-Reranker-0.6B"},
                  },
              },
          },
          "spu_config": {"enabled": False},
          "function_score": {"score_mode": "sum", "boost_mode": "multiply", "functions": []},
      }
      config_path = tmp_path / "config.yaml"
      config_path.write_text(yaml.safe_dump(config_data), encoding="utf-8")
  
      loader = AppConfigLoader(config_file=config_path)
      loaded = loader.load(validate=False)
  
      assert loaded.services.rerank.default_instance == "default"
      assert loaded.services.rerank.get_instance("fine").port == 6009
      assert loaded.services.rerank.get_instance("fine").backend == "bge"
  
  
5f7d7f09   tangwang   性能测试报告.md
390
391
392
393
394
395
396
397
398
399
400
401
  def test_searcher_reranks_top_window_by_default(monkeypatch):
      es_client = _FakeESClient()
      searcher = _build_searcher(_build_search_config(rerank_enabled=True), es_client)
      context = create_request_context(reqid="t1", uid="u1")
  
      monkeypatch.setattr(
          "search.searcher.get_tenant_config_loader",
          lambda: SimpleNamespace(get_tenant_config=lambda tenant_id: {"index_languages": ["en"]}),
      )
  
      called: Dict[str, Any] = {"count": 0, "docs": 0}
  
8c8b9d84   tangwang   ES 拉取 coarse_rank...
402
403
404
405
406
407
      def _fake_run_lightweight_rerank(**kwargs):
          hits = kwargs["es_hits"]
          for idx, hit in enumerate(hits):
              hit["_fine_score"] = float(len(hits) - idx)
          return [hit["_fine_score"] for hit in hits], {"stage": "fine"}, []
  
5f7d7f09   tangwang   性能测试报告.md
408
409
410
411
412
      def _fake_run_rerank(**kwargs):
          called["count"] += 1
          called["docs"] = len(kwargs["es_response"]["hits"]["hits"])
          return kwargs["es_response"], None, []
  
8c8b9d84   tangwang   ES 拉取 coarse_rank...
413
      monkeypatch.setattr("search.rerank_client.run_lightweight_rerank", _fake_run_lightweight_rerank)
5f7d7f09   tangwang   性能测试报告.md
414
415
416
417
418
419
420
421
422
423
424
425
      monkeypatch.setattr("search.rerank_client.run_rerank", _fake_run_rerank)
  
      result = searcher.search(
          query="toy",
          tenant_id="162",
          from_=20,
          size=10,
          context=context,
          enable_rerank=None,
      )
  
      assert called["count"] == 1
8c8b9d84   tangwang   ES 拉取 coarse_rank...
426
      assert called["docs"] == searcher.config.rerank.rerank_window
5f7d7f09   tangwang   性能测试报告.md
427
      assert es_client.calls[0]["from_"] == 0
8c8b9d84   tangwang   ES 拉取 coarse_rank...
428
      assert es_client.calls[0]["size"] == searcher.config.coarse_rank.input_window
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
429
      assert es_client.calls[0]["include_named_queries_score"] is True
8c8b9d84   tangwang   ES 拉取 coarse_rank...
430
431
432
433
434
435
      assert es_client.calls[0]["body"]["_source"] is False
      assert len(es_client.calls) == 3
      assert es_client.calls[1]["size"] == max(
          searcher.config.coarse_rank.output_window,
          searcher.config.rerank.rerank_window,
      )
5f7d7f09   tangwang   性能测试报告.md
436
      assert es_client.calls[1]["from_"] == 0
8c8b9d84   tangwang   ES 拉取 coarse_rank...
437
438
439
      assert es_client.calls[2]["size"] == 10
      assert es_client.calls[2]["from_"] == 0
      assert es_client.calls[2]["body"]["query"]["ids"]["values"] == [str(i) for i in range(20, 30)]
5f7d7f09   tangwang   性能测试报告.md
440
441
442
443
444
      assert len(result.results) == 10
      assert result.results[0].spu_id == "20"
      assert result.results[0].brief == "brief-20"
  
  
daa2690b   tangwang   漏斗参数调优&呈现优化
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
  def test_searcher_debug_info_exposes_ranking_funnel(monkeypatch):
      es_client = _FakeESClient(total_hits=120)
      searcher = _build_searcher(_build_search_config(rerank_enabled=True, rerank_window=20), es_client)
      context = create_request_context(reqid="t-debug", uid="u-debug")
  
      monkeypatch.setattr(
          "search.searcher.get_tenant_config_loader",
          lambda: SimpleNamespace(get_tenant_config=lambda tenant_id: {"index_languages": ["en"]}),
      )
  
      def _fake_run_lightweight_rerank(**kwargs):
          hits = kwargs["es_hits"]
          scores = []
          debug_rows = []
          for idx, hit in enumerate(hits):
              score = float(len(hits) - idx)
              hit["_fine_score"] = score
              scores.append(score)
              debug_rows.append(
                  {
                      "doc_id": hit["_id"],
                      "fine_score": score,
                      "rerank_input": {"doc_preview": f"product-{hit['_id']}"},
                  }
              )
          hits.sort(key=lambda item: item["_fine_score"], reverse=True)
          return scores, {"model": "fine-bge"}, debug_rows
  
      def _fake_run_rerank(**kwargs):
          hits = kwargs["es_response"]["hits"]["hits"]
          fused_debug = []
          for idx, hit in enumerate(hits):
              hit["_rerank_score"] = 10.0 - idx
              hit["_fused_score"] = 100.0 - idx
              hit["_text_score"] = hit.get("_score", 0.0)
              hit["_knn_score"] = 0.0
              fused_debug.append(
                  {
                      "doc_id": hit["_id"],
                      "rerank_score": hit["_rerank_score"],
                      "fine_score": hit.get("_fine_score"),
                      "text_score": hit["_text_score"],
                      "knn_score": 0.0,
                      "rerank_factor": 1.0,
                      "fine_factor": 1.0,
                      "text_factor": 1.0,
                      "knn_factor": 1.0,
                      "fused_score": hit["_fused_score"],
                      "matched_queries": {},
                      "rerank_input": {"doc_preview": f"product-{hit['_id']}"},
                  }
              )
          return kwargs["es_response"], {"model": "final-reranker"}, fused_debug
  
      monkeypatch.setattr("search.rerank_client.run_lightweight_rerank", _fake_run_lightweight_rerank)
      monkeypatch.setattr("search.rerank_client.run_rerank", _fake_run_rerank)
  
      result = searcher.search(
          query="toy",
          tenant_id="162",
          from_=0,
          size=5,
          context=context,
          enable_rerank=True,
          debug=True,
      )
  
      assert result.debug_info["ranking_funnel"]["fine_rank"]["docs_out"] == 80
      assert result.debug_info["ranking_funnel"]["rerank"]["docs_out"] == 20
dbe04e9e   tangwang   统一排序漏斗协议,精简冗余字段与前...
514
515
      assert result.debug_info["ranking_funnel"]["coarse_rank"]["applied"] is True
      assert result.debug_info["ranking_funnel"]["coarse_rank"]["backend"] == "local_coarse_fusion"
daa2690b   tangwang   漏斗参数调优&呈现优化
516
517
518
      first = result.debug_info["per_result"][0]["ranking_funnel"]
      assert first["es_recall"]["rank"] is not None
      assert first["coarse_rank"]["score"] is not None
dbe04e9e   tangwang   统一排序漏斗协议,精简冗余字段与前...
519
      assert first["coarse_rank"]["fusion_summary"] is not None
daa2690b   tangwang   漏斗参数调优&呈现优化
520
521
522
523
      assert first["fine_rank"]["score"] is not None
      assert first["rerank"]["rerank_score"] is not None
  
  
5f7d7f09   tangwang   性能测试报告.md
524
525
526
527
528
529
530
531
532
  def test_searcher_rerank_prefetch_source_follows_doc_template(monkeypatch):
      es_client = _FakeESClient()
      searcher = _build_searcher(_build_search_config(rerank_enabled=True), es_client)
      context = create_request_context(reqid="t1b", uid="u1b")
  
      monkeypatch.setattr(
          "search.searcher.get_tenant_config_loader",
          lambda: SimpleNamespace(get_tenant_config=lambda tenant_id: {"index_languages": ["en"]}),
      )
8c8b9d84   tangwang   ES 拉取 coarse_rank...
533
534
535
536
      monkeypatch.setattr(
          "search.rerank_client.run_lightweight_rerank",
          lambda **kwargs: ([1.0] * len(kwargs["es_hits"]), {"stage": "fine"}, []),
      )
5f7d7f09   tangwang   性能测试报告.md
537
538
539
540
541
542
543
544
545
546
547
548
      monkeypatch.setattr("search.rerank_client.run_rerank", lambda **kwargs: (kwargs["es_response"], None, []))
  
      searcher.search(
          query="toy",
          tenant_id="162",
          from_=0,
          size=5,
          context=context,
          enable_rerank=None,
          rerank_doc_template="{title} {vendor} {brief}",
      )
  
8c8b9d84   tangwang   ES 拉取 coarse_rank...
549
550
      assert es_client.calls[0]["body"]["_source"] is False
      assert es_client.calls[1]["body"]["_source"] == {"includes": ["brief", "title", "vendor"]}
5f7d7f09   tangwang   性能测试报告.md
551
552
  
  
cda1cd62   tangwang   意图分析&应用 baseline
553
554
555
556
557
558
559
560
561
562
  def test_searcher_rerank_prefetch_source_includes_sku_fields_when_style_intent_active(monkeypatch):
      es_client = _FakeESClient()
      searcher = _build_searcher(_build_search_config(rerank_enabled=True), es_client)
      context = create_request_context(reqid="t1c", uid="u1c")
  
      monkeypatch.setattr(
          "search.searcher.get_tenant_config_loader",
          lambda: SimpleNamespace(get_tenant_config=lambda tenant_id: {"index_languages": ["en"]}),
      )
      monkeypatch.setattr(
8c8b9d84   tangwang   ES 拉取 coarse_rank...
563
564
565
566
          "search.rerank_client.run_lightweight_rerank",
          lambda **kwargs: ([1.0] * len(kwargs["es_hits"]), {"stage": "fine"}, []),
      )
      monkeypatch.setattr(
cda1cd62   tangwang   意图分析&应用 baseline
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
          "search.rerank_client.run_rerank",
          lambda **kwargs: (kwargs["es_response"], None, []),
      )
  
      class _IntentQueryParser:
          text_encoder = None
  
          def parse(
              self,
              query: str,
              tenant_id: str,
              generate_vector: bool,
              context: Any,
              target_languages: Any = None,
          ):
              return _FakeParsedQuery(
                  original_query=query,
                  query_normalized=query,
                  rewritten_query=query,
                  translations={},
                  style_intent_profile=_build_style_intent_profile(
                      "color", "black", "color", "colors", "颜色"
                  ),
              )
  
      searcher.query_parser = _IntentQueryParser()
  
      searcher.search(
          query="black dress",
          tenant_id="162",
          from_=0,
          size=5,
          context=context,
          enable_rerank=None,
      )
  
8c8b9d84   tangwang   ES 拉取 coarse_rank...
603
604
      assert es_client.calls[0]["body"]["_source"] is False
      assert es_client.calls[1]["body"]["_source"] == {
5c9baf91   tangwang   feat(search): 款式意...
605
606
607
608
609
610
611
612
          "includes": [
              "enriched_taxonomy_attributes",
              "option1_name",
              "option2_name",
              "option3_name",
              "skus",
              "title",
          ]
cda1cd62   tangwang   意图分析&应用 baseline
613
614
615
      }
  
  
0ba0e0fc   tangwang   1. rerank漏斗配置优化
616
  def test_searcher_keeps_previous_stage_order_when_request_explicitly_disables_rerank(monkeypatch):
5f7d7f09   tangwang   性能测试报告.md
617
618
619
620
621
622
623
624
625
      es_client = _FakeESClient()
      searcher = _build_searcher(_build_search_config(rerank_enabled=True), es_client)
      context = create_request_context(reqid="t2", uid="u2")
  
      monkeypatch.setattr(
          "search.searcher.get_tenant_config_loader",
          lambda: SimpleNamespace(get_tenant_config=lambda tenant_id: {"index_languages": ["en"]}),
      )
  
0ba0e0fc   tangwang   1. rerank漏斗配置优化
626
627
628
629
630
631
632
633
634
      called: Dict[str, int] = {"count": 0, "fine": 0}
  
      def _fake_run_lightweight_rerank(**kwargs):
          called["fine"] += 1
          hits = kwargs["es_hits"]
          for idx, hit in enumerate(hits):
              hit["_fine_score"] = float(idx + 1)
          hits.reverse()
          return [hit["_fine_score"] for hit in hits], {"stage": "fine"}, []
5f7d7f09   tangwang   性能测试报告.md
635
636
637
638
639
  
      def _fake_run_rerank(**kwargs):
          called["count"] += 1
          return kwargs["es_response"], None, []
  
0ba0e0fc   tangwang   1. rerank漏斗配置优化
640
      monkeypatch.setattr("search.rerank_client.run_lightweight_rerank", _fake_run_lightweight_rerank)
5f7d7f09   tangwang   性能测试报告.md
641
642
      monkeypatch.setattr("search.rerank_client.run_rerank", _fake_run_rerank)
  
0ba0e0fc   tangwang   1. rerank漏斗配置优化
643
      result = searcher.search(
5f7d7f09   tangwang   性能测试报告.md
644
645
646
647
648
649
          query="toy",
          tenant_id="162",
          from_=20,
          size=10,
          context=context,
          enable_rerank=False,
0ba0e0fc   tangwang   1. rerank漏斗配置优化
650
          debug=True,
5f7d7f09   tangwang   性能测试报告.md
651
652
653
      )
  
      assert called["count"] == 0
0ba0e0fc   tangwang   1. rerank漏斗配置优化
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
      assert called["fine"] == 1
      assert es_client.calls[0]["from_"] == 0
      assert es_client.calls[0]["size"] == searcher.config.coarse_rank.input_window
      assert es_client.calls[0]["include_named_queries_score"] is True
      assert len(es_client.calls) == 3
      assert es_client.calls[2]["body"]["query"]["ids"]["values"] == [str(i) for i in range(363, 353, -1)]
      assert len(result.results) == 10
      assert [item.spu_id for item in result.results[:3]] == ["363", "362", "361"]
      assert result.debug_info["rerank"]["enabled"] is False
      assert result.debug_info["rerank"]["applied"] is False
      assert result.debug_info["rerank"]["skipped_reason"] == "disabled"
      assert result.debug_info["per_result"][0]["ranking_funnel"]["rerank"]["rank"] == 21
  
  
  def test_searcher_keeps_previous_stage_order_when_config_disables_rerank(monkeypatch):
      es_client = _FakeESClient()
      searcher = _build_searcher(_build_search_config(rerank_enabled=False), es_client)
      context = create_request_context(reqid="t2b", uid="u2b")
  
      monkeypatch.setattr(
          "search.searcher.get_tenant_config_loader",
          lambda: SimpleNamespace(get_tenant_config=lambda tenant_id: {"index_languages": ["en"]}),
      )
  
      called: Dict[str, int] = {"count": 0, "fine": 0}
  
      def _fake_run_lightweight_rerank(**kwargs):
          called["fine"] += 1
          hits = kwargs["es_hits"]
          hits.reverse()
          for idx, hit in enumerate(hits):
              hit["_fine_score"] = float(len(hits) - idx)
          return [hit["_fine_score"] for hit in hits], {"stage": "fine"}, []
  
      def _fake_run_rerank(**kwargs):
          called["count"] += 1
          return kwargs["es_response"], None, []
  
      monkeypatch.setattr("search.rerank_client.run_lightweight_rerank", _fake_run_lightweight_rerank)
      monkeypatch.setattr("search.rerank_client.run_rerank", _fake_run_rerank)
  
      result = searcher.search(
          query="toy",
          tenant_id="162",
          from_=0,
          size=5,
          context=context,
          enable_rerank=None,
          debug=True,
      )
  
      assert called["count"] == 0
      assert called["fine"] == 1
      assert es_client.calls[0]["from_"] == 0
      assert es_client.calls[0]["size"] == searcher.config.coarse_rank.input_window
      assert es_client.calls[0]["include_named_queries_score"] is True
      assert len(result.results) == 5
      assert [item.spu_id for item in result.results] == ["383", "382", "381", "380", "379"]
      assert result.debug_info["rerank"]["enabled"] is False
      assert result.debug_info["rerank"]["applied"] is False
      assert result.debug_info["rerank"]["skipped_reason"] == "disabled"
5f7d7f09   tangwang   性能测试报告.md
715
716
717
718
  
  
  def test_searcher_skips_rerank_when_page_exceeds_window(monkeypatch):
      es_client = _FakeESClient()
c51d254f   tangwang   性能测试
719
      searcher = _build_searcher(_build_search_config(rerank_enabled=True, rerank_window=384), es_client)
5f7d7f09   tangwang   性能测试报告.md
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
      context = create_request_context(reqid="t3", uid="u3")
  
      monkeypatch.setattr(
          "search.searcher.get_tenant_config_loader",
          lambda: SimpleNamespace(get_tenant_config=lambda tenant_id: {"index_languages": ["en"]}),
      )
  
      called: Dict[str, int] = {"count": 0}
  
      def _fake_run_rerank(**kwargs):
          called["count"] += 1
          return kwargs["es_response"], None, []
  
      monkeypatch.setattr("search.rerank_client.run_rerank", _fake_run_rerank)
  
      searcher.search(
          query="toy",
          tenant_id="162",
          from_=995,
          size=10,
          context=context,
          enable_rerank=None,
      )
  
      assert called["count"] == 0
      assert es_client.calls[0]["from_"] == 995
      assert es_client.calls[0]["size"] == 10
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
747
      assert es_client.calls[0]["include_named_queries_score"] is False
5f7d7f09   tangwang   性能测试报告.md
748
      assert len(es_client.calls) == 1
deccd68a   tangwang   Added the SKU pre...
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
  
  
  def test_searcher_promotes_sku_when_option1_matches_translated_query(monkeypatch):
      es_client = _FakeESClient(total_hits=1)
      searcher = _build_searcher(_build_search_config(rerank_enabled=False), es_client)
      context = create_request_context(reqid="sku-text", uid="u-sku-text")
  
      monkeypatch.setattr(
          "search.searcher.get_tenant_config_loader",
          lambda: SimpleNamespace(get_tenant_config=lambda tenant_id: {"index_languages": ["en", "zh"]}),
      )
  
      class _TranslatedQueryParser:
          text_encoder = None
  
ef5baa86   tangwang   混杂语言处理
764
765
766
767
768
769
770
771
          def parse(
              self,
              query: str,
              tenant_id: str,
              generate_vector: bool,
              context: Any,
              target_languages: Any = None,
          ):
deccd68a   tangwang   Added the SKU pre...
772
773
774
775
776
              return _FakeParsedQuery(
                  original_query=query,
                  query_normalized=query,
                  rewritten_query=query,
                  translations={"en": "black dress"},
cda1cd62   tangwang   意图分析&应用 baseline
777
778
779
                  style_intent_profile=_build_style_intent_profile(
                      "color", "black", "color", "colors", "颜色"
                  ),
deccd68a   tangwang   Added the SKU pre...
780
781
782
783
784
785
786
787
788
789
              )
  
      searcher.query_parser = _TranslatedQueryParser()
  
      def _full_source_with_skus(doc_id: str) -> Dict[str, Any]:
          return {
              "spu_id": doc_id,
              "title": {"en": f"product-{doc_id}"},
              "brief": {"en": f"brief-{doc_id}"},
              "vendor": {"en": f"vendor-{doc_id}"},
a7cc9078   tangwang   sku排序
790
              "option1_name": "Color",
deccd68a   tangwang   Added the SKU pre...
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
              "image_url": "https://img/default.jpg",
              "skus": [
                  {"sku_id": "sku-red", "option1_value": "Red", "image_src": "https://img/red.jpg"},
                  {"sku_id": "sku-black", "option1_value": "Black", "image_src": "https://img/black.jpg"},
              ],
          }
  
      monkeypatch.setattr(_FakeESClient, "_full_source", staticmethod(_full_source_with_skus))
  
      result = searcher.search(
          query="黑色 连衣裙",
          tenant_id="162",
          from_=0,
          size=1,
          context=context,
          enable_rerank=False,
      )
  
      assert len(result.results) == 1
      assert result.results[0].skus[0].sku_id == "sku-black"
      assert result.results[0].image_url == "https://img/black.jpg"
  
  
2efad04b   tangwang   意图匹配的性能优化:
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
  def test_searcher_uses_first_text_match_without_comparing_all_matches(monkeypatch):
      es_client = _FakeESClient(total_hits=1)
      searcher = _build_searcher(_build_search_config(rerank_enabled=False), es_client)
      context = create_request_context(reqid="sku-first-text", uid="u-sku-first-text")
  
      monkeypatch.setattr(
          "search.searcher.get_tenant_config_loader",
          lambda: SimpleNamespace(get_tenant_config=lambda tenant_id: {"index_languages": ["en"]}),
      )
  
      class _TextMatchQueryParser:
          text_encoder = None
  
          def parse(
              self,
              query: str,
              tenant_id: str,
              generate_vector: bool,
              context: Any,
              target_languages: Any = None,
          ):
              return _FakeParsedQuery(
                  original_query=query,
                  query_normalized=query,
                  rewritten_query=query,
                  translations={},
                  style_intent_profile=_build_style_intent_profile(
                      "color", "black", "color", "colors", "颜色"
                  ),
              )
  
      searcher.query_parser = _TextMatchQueryParser()
  
      def _full_source_with_multiple_text_matches(doc_id: str) -> Dict[str, Any]:
          return {
              "spu_id": doc_id,
              "title": {"en": f"product-{doc_id}"},
              "brief": {"en": f"brief-{doc_id}"},
              "vendor": {"en": f"vendor-{doc_id}"},
              "option1_name": "Color",
              "image_url": "https://img/default.jpg",
              "skus": [
                  {"sku_id": "sku-red", "option1_value": "Red", "image_src": "https://img/red.jpg"},
                  {
                      "sku_id": "sku-gloss-black",
                      "option1_value": "Gloss Black",
                      "image_src": "https://img/gloss-black.jpg",
                  },
                  {"sku_id": "sku-black", "option1_value": "Black", "image_src": "https://img/black.jpg"},
              ],
          }
  
      monkeypatch.setattr(_FakeESClient, "_full_source", staticmethod(_full_source_with_multiple_text_matches))
  
      result = searcher.search(
          query="black dress",
          tenant_id="162",
          from_=0,
          size=1,
          context=context,
          enable_rerank=False,
      )
  
      assert len(result.results) == 1
      assert result.results[0].skus[0].sku_id == "sku-gloss-black"
      assert result.results[0].image_url == "https://img/gloss-black.jpg"
  
  
  def test_searcher_skips_sku_selection_when_option_name_does_not_match_dimension_alias(monkeypatch):
      es_client = _FakeESClient(total_hits=1)
      searcher = _build_searcher(_build_search_config(rerank_enabled=False), es_client)
      context = create_request_context(reqid="sku-unresolved-dimension", uid="u-sku-unresolved-dimension")
  
      monkeypatch.setattr(
          "search.searcher.get_tenant_config_loader",
          lambda: SimpleNamespace(get_tenant_config=lambda tenant_id: {"index_languages": ["en", "zh"]}),
      )
  
      class _UnresolvedDimensionQueryParser:
          text_encoder = None
  
          def parse(
              self,
              query: str,
              tenant_id: str,
              generate_vector: bool,
              context: Any,
              target_languages: Any = None,
          ):
              return _FakeParsedQuery(
                  original_query=query,
                  query_normalized=query,
                  rewritten_query=query,
                  translations={"en": "black dress"},
                  style_intent_profile=_build_style_intent_profile(
                      "color", "black", "color", "colors", "颜色"
                  ),
              )
  
      searcher.query_parser = _UnresolvedDimensionQueryParser()
  
      def _full_source_with_unmatched_option_name(doc_id: str) -> Dict[str, Any]:
          return {
              "spu_id": doc_id,
              "title": {"en": f"product-{doc_id}"},
              "brief": {"en": f"brief-{doc_id}"},
              "vendor": {"en": f"vendor-{doc_id}"},
              "option1_name": "Tone",
              "image_url": "https://img/default.jpg",
              "skus": [
                  {"sku_id": "sku-red", "option1_value": "Red", "image_src": "https://img/red.jpg"},
                  {"sku_id": "sku-black", "option1_value": "Black", "image_src": "https://img/black.jpg"},
              ],
          }
  
      monkeypatch.setattr(_FakeESClient, "_full_source", staticmethod(_full_source_with_unmatched_option_name))
  
      result = searcher.search(
          query="黑色 连衣裙",
          tenant_id="162",
          from_=0,
          size=1,
          context=context,
          enable_rerank=False,
      )
  
      assert len(result.results) == 1
      assert result.results[0].skus[0].sku_id == "sku-red"
      assert result.results[0].image_url == "https://img/default.jpg"
  
  
814e352b   tangwang   乘法公式配置化
945
  def test_searcher_debug_info_uses_initial_es_max_score_for_normalization(monkeypatch):
581dafae   tangwang   debug工具,每条结果的打分中间...
946
      es_client = _FakeESClient(total_hits=3)
0ba0e0fc   tangwang   1. rerank漏斗配置优化
947
948
      cfg = _build_search_config(rerank_enabled=False)
      searcher = _build_searcher(cfg, es_client)
581dafae   tangwang   debug工具,每条结果的打分中间...
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
      context = create_request_context(reqid="dbg", uid="u-dbg")
  
      monkeypatch.setattr(
          "search.searcher.get_tenant_config_loader",
          lambda: SimpleNamespace(get_tenant_config=lambda tenant_id: {"index_languages": ["en", "zh"]}),
      )
  
      result = searcher.search(
          query="toy",
          tenant_id="162",
          from_=0,
          size=2,
          context=context,
          enable_rerank=False,
          debug=True,
      )
  
      assert result.debug_info["query_analysis"]["index_languages"] == ["en", "zh"]
814e352b   tangwang   乘法公式配置化
967
      assert result.debug_info["query_analysis"]["query_tokens"] == []
0ba0e0fc   tangwang   1. rerank漏斗配置优化
968
969
      expected_es_fetch = max(cfg.rerank.rerank_window, cfg.coarse_rank.input_window)
      assert result.debug_info["es_query_context"]["es_fetch_size"] == expected_es_fetch
814e352b   tangwang   乘法公式配置化
970
      assert result.debug_info["es_response"]["es_score_normalization_factor"] == 3.0
581dafae   tangwang   debug工具,每条结果的打分中间...
971
972
973
      assert result.debug_info["per_result"][0]["initial_rank"] == 1
      assert result.debug_info["per_result"][0]["final_rank"] == 1
      assert result.debug_info["per_result"][0]["es_score_normalized"] == 1.0
814e352b   tangwang   乘法公式配置化
974
      assert result.debug_info["per_result"][1]["es_score_normalized"] == 2.0 / 3.0
9df421ed   tangwang   基于eval框架开始调参
975
976
  
  
317c5d2c   tangwang   feat(search): 引入 ...
977
978
979
980
981
982
983
984
985
986
  def test_searcher_attaches_exact_knn_rescore_for_rank_window(monkeypatch):
      class _VectorQueryParser:
          def parse(self, query: str, tenant_id: str, generate_vector: bool, context: Any, target_languages: Any = None):
              return _FakeParsedQuery(
                  original_query=query,
                  query_normalized=query,
                  rewritten_query=query,
                  translations={},
                  query_vector=np.array([0.1, 0.2, 0.3], dtype=np.float32),
                  image_query_vector=np.array([0.4, 0.5, 0.6], dtype=np.float32),
47452e1d   tangwang   feat(search): 支持可...
987
                  query_tokens=["dress", "formal", "spring", "summer", "floral"],
317c5d2c   tangwang   feat(search): 引入 ...
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
              )
  
      es_client = _FakeESClient(total_hits=5)
      base = _build_search_config(
          rerank_enabled=True,
          rerank_window=5,
          exact_knn_rescore_enabled=True,
          exact_knn_rescore_window=3,
      )
      config = SearchConfig(
          field_boosts=base.field_boosts,
          indexes=base.indexes,
          query_config=QueryConfig(
              enable_text_embedding=True,
              enable_query_rewrite=False,
              text_embedding_field="title_embedding",
              image_embedding_field="image_embedding.vector",
          ),
          function_score=base.function_score,
          coarse_rank=base.coarse_rank,
          fine_rank=FineRankConfig(enabled=False, input_window=5, output_window=5),
          rerank=base.rerank,
          spu_config=base.spu_config,
          es_index_name=base.es_index_name,
          es_settings=base.es_settings,
      )
47452e1d   tangwang   feat(search): 支持可...
1014
1015
1016
1017
1018
1019
      searcher = Searcher(
          es_client=es_client,
          config=config,
          query_parser=_VectorQueryParser(),
          image_encoder=SimpleNamespace(),
      )
317c5d2c   tangwang   feat(search): 引入 ...
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
      context = create_request_context(reqid="exact-rescore", uid="u-exact")
  
      monkeypatch.setattr(
          "search.searcher.get_tenant_config_loader",
          lambda: SimpleNamespace(get_tenant_config=lambda tenant_id: {"index_languages": ["en"]}),
      )
  
      searcher.search(
          query="dress",
          tenant_id="162",
          from_=0,
          size=2,
          context=context,
          enable_rerank=False,
          debug=True,
      )
  
      body = es_client.calls[0]["body"]
      assert body["rescore"]["window_size"] == 3
      assert body["rescore"]["query"]["score_mode"] == "total"
      assert body["rescore"]["query"]["rescore_query_weight"] == 0.0
      should = body["rescore"]["query"]["rescore_query"]["bool"]["should"]
      names = []
      for clause in should:
          if "script_score" in clause:
              names.append(clause["script_score"]["_name"])
          elif "nested" in clause:
              names.append(clause["nested"]["_name"])
      assert names == ["exact_text_knn_query", "exact_image_knn_query"]
47452e1d   tangwang   feat(search): 支持可...
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
      recall_query = body["query"]
      if "bool" in recall_query and recall_query["bool"].get("must"):
          recall_query = recall_query["bool"]["must"][0]
      if "function_score" in recall_query:
          recall_query = recall_query["function_score"]["query"]
      recall_should = recall_query["bool"]["should"]
      text_knn_clause = next(
          clause["knn"]
          for clause in recall_should
          if clause.get("knn", {}).get("_name") == "knn_query"
      )
      image_knn_clause = next(
          clause["nested"]["query"]["knn"]
          for clause in recall_should
          if clause.get("nested", {}).get("_name") == "image_knn_query"
      )
      exact_text_clause = next(
          clause["script_score"]
          for clause in should
          if clause.get("script_score", {}).get("_name") == "exact_text_knn_query"
      )
      exact_image_clause = next(
          clause["nested"]["query"]["script_score"]
          for clause in should
          if clause.get("nested", {}).get("_name") == "exact_image_knn_query"
      )
      assert text_knn_clause["boost"] == 28.0
      assert exact_text_clause["script"]["params"]["boost"] == text_knn_clause["boost"]
      assert image_knn_clause["boost"] == 20.0
      assert exact_image_clause["script"]["params"]["boost"] == image_knn_clause["boost"]
317c5d2c   tangwang   feat(search): 引入 ...
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
  
  
  def test_searcher_skips_exact_knn_rescore_outside_rank_window(monkeypatch):
      class _VectorQueryParser:
          def parse(self, query: str, tenant_id: str, generate_vector: bool, context: Any, target_languages: Any = None):
              return _FakeParsedQuery(
                  original_query=query,
                  query_normalized=query,
                  rewritten_query=query,
                  translations={},
                  query_vector=np.array([0.1, 0.2, 0.3], dtype=np.float32),
              )
  
      es_client = _FakeESClient(total_hits=20)
      base = _build_search_config(
          rerank_enabled=True,
          rerank_window=5,
          exact_knn_rescore_enabled=True,
          exact_knn_rescore_window=4,
      )
      config = SearchConfig(
          field_boosts=base.field_boosts,
          indexes=base.indexes,
          query_config=QueryConfig(
              enable_text_embedding=True,
              enable_query_rewrite=False,
              text_embedding_field="title_embedding",
          ),
          function_score=base.function_score,
          coarse_rank=base.coarse_rank,
          fine_rank=FineRankConfig(enabled=False, input_window=5, output_window=5),
          rerank=base.rerank,
          spu_config=base.spu_config,
          es_index_name=base.es_index_name,
          es_settings=base.es_settings,
      )
      searcher = _build_searcher(config, es_client)
      searcher.query_parser = _VectorQueryParser()
      context = create_request_context(reqid="exact-rescore-off", uid="u-exact-off")
  
      monkeypatch.setattr(
          "search.searcher.get_tenant_config_loader",
          lambda: SimpleNamespace(get_tenant_config=lambda tenant_id: {"index_languages": ["en"]}),
      )
  
      searcher.search(
          query="dress",
          tenant_id="162",
          from_=5,
          size=2,
          context=context,
          enable_rerank=False,
      )
  
      body = es_client.calls[0]["body"]
      assert "rescore" not in body
  
  
9df421ed   tangwang   基于eval框架开始调参
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
  def test_searcher_rerank_rank_change_falls_back_to_coarse_rank_when_fine_disabled(monkeypatch):
      es_client = _FakeESClient(total_hits=5)
      config = _build_search_config(rerank_enabled=True, rerank_window=5)
      config = SearchConfig(
          field_boosts=config.field_boosts,
          indexes=config.indexes,
          query_config=config.query_config,
          function_score=config.function_score,
          coarse_rank=config.coarse_rank,
          fine_rank=FineRankConfig(enabled=False, input_window=5, output_window=5),
          rerank=config.rerank,
          spu_config=config.spu_config,
          es_index_name=config.es_index_name,
          es_settings=config.es_settings,
      )
      searcher = _build_searcher(config, es_client)
      context = create_request_context(reqid="rank-fallback", uid="u-rank-fallback")
  
      monkeypatch.setattr(
          "search.searcher.get_tenant_config_loader",
          lambda: SimpleNamespace(get_tenant_config=lambda tenant_id: {"index_languages": ["en"]}),
      )
  
0ba0e0fc   tangwang   1. rerank漏斗配置优化
1160
1161
1162
1163
1164
1165
      fine_called: Dict[str, int] = {"count": 0}
  
      def _fake_run_lightweight_rerank(**kwargs):
          fine_called["count"] += 1
          return [], {"stage": "fine"}, []
  
9df421ed   tangwang   基于eval框架开始调参
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
      def _fake_run_rerank(**kwargs):
          hits = kwargs["es_response"]["hits"]["hits"]
          hits.reverse()
          fused_debug = []
          for idx, hit in enumerate(hits):
              hit["_fused_score"] = 100.0 - idx
              hit["_rerank_score"] = 1.0 - 0.1 * idx
              fused_debug.append(
                  {
                      "doc_id": hit["_id"],
                      "score": hit["_fused_score"],
                      "es_score": hit.get("_raw_es_score", hit.get("_score")),
                      "rerank_score": hit["_rerank_score"],
                      "text_score": hit.get("_text_score", hit.get("_score")),
                      "knn_score": hit.get("_knn_score", 0.0),
                      "es_factor": 1.0,
                      "rerank_factor": 1.0,
                      "text_factor": 1.0,
                      "knn_factor": 1.0,
                      "fused_score": hit["_fused_score"],
                  }
              )
          return kwargs["es_response"], {"model": "final-reranker"}, fused_debug
  
0ba0e0fc   tangwang   1. rerank漏斗配置优化
1190
      monkeypatch.setattr("search.rerank_client.run_lightweight_rerank", _fake_run_lightweight_rerank)
9df421ed   tangwang   基于eval框架开始调参
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
      monkeypatch.setattr("search.rerank_client.run_rerank", _fake_run_rerank)
  
      result = searcher.search(
          query="toy",
          tenant_id="162",
          from_=0,
          size=5,
          context=context,
          enable_rerank=True,
          debug=True,
      )
  
      per_result = {row["spu_id"]: row for row in result.debug_info["per_result"]}
      moved = per_result["4"]["ranking_funnel"]
0ba0e0fc   tangwang   1. rerank漏斗配置优化
1205
1206
1207
1208
1209
1210
      assert fine_called["count"] == 0
      assert result.debug_info["fine_rank"]["enabled"] is False
      assert result.debug_info["fine_rank"]["applied"] is False
      assert result.debug_info["fine_rank"]["skipped_reason"] == "disabled"
      assert moved["fine_rank"]["rank"] == 5
      assert moved["fine_rank"]["rank_change"] == 0
9df421ed   tangwang   基于eval框架开始调参
1211
1212
1213
      assert moved["rerank"]["rank"] == 1
      assert moved["rerank"]["rank_change"] == 4
      assert moved["final_page"]["rank_change"] == 0