Blame view

tests/test_suggestions.py 19.3 KB
f251cf2d   tangwang   suggestion全量索引程序跑通
1
  import json
ff9efda0   tangwang   suggest
2
  from datetime import datetime, timedelta, timezone
f251cf2d   tangwang   suggestion全量索引程序跑通
3
4
5
6
  from typing import Any, Dict, List
  
  import pytest
  
ff9efda0   tangwang   suggest
7
8
9
10
  from suggestion.builder import (
      QueryDelta,
      SuggestionIndexBuilder,
      get_suggestion_alias_name,
9f33fe3c   tangwang   fix suggestion re...
11
      get_suggestion_versioned_index_name,
ff9efda0   tangwang   suggest
12
  )
f251cf2d   tangwang   suggestion全量索引程序跑通
13
14
15
16
  from suggestion.service import SuggestionService
  
  
  class FakeESClient:
ff9efda0   tangwang   suggest
17
      """Lightweight fake ES client for suggestion unit tests."""
f251cf2d   tangwang   suggestion全量索引程序跑通
18
19
20
  
      def __init__(self) -> None:
          self.calls: List[Dict[str, Any]] = []
ff9efda0   tangwang   suggest
21
22
23
          self.indices: set[str] = set()
          self.aliases: Dict[str, List[str]] = {}
          self.client = self  # support service._completion_suggest -> self.es_client.client.search
f251cf2d   tangwang   suggestion全量索引程序跑通
24
  
ff9efda0   tangwang   suggest
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
      def search(
          self,
          index_name: str = None,
          body: Dict[str, Any] = None,
          size: int = 10,
          from_: int = 0,
          routing: str = None,
          index: str = None,
          **kwargs,
      ) -> Dict[str, Any]:
          idx = index_name or index
          body = body or {}
          self.calls.append(
              {
                  "op": "search",
                  "index": idx,
                  "body": body,
                  "size": size,
                  "from": from_,
                  "routing": routing,
              }
          )
  
          # Completion suggest path
          if "suggest" in body:
              return {
                  "suggest": {
                      "s": [
                          {
                              "text": "iph",
                              "offset": 0,
                              "length": 3,
                              "options": [
                                  {
                                      "text": "iphone 15",
                                      "_score": 6.3,
                                      "_source": {
                                          "text": "iphone 15",
                                          "lang": "en",
                                          "rank_score": 5.0,
                                          "sources": ["query_log", "qanchor"],
                                          "lang_source": "log_field",
                                          "lang_confidence": 1.0,
                                          "lang_conflict": False,
                                      },
                                  }
                              ],
                          }
                      ]
                  }
              }
  
          # bool_prefix path
          if idx and "search_suggestions_tenant_" in idx:
f251cf2d   tangwang   suggestion全量索引程序跑通
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
              return {
                  "hits": {
                      "total": {"value": 1},
                      "max_score": 3.2,
                      "hits": [
                          {
                              "_id": "1",
                              "_score": 3.2,
                              "_source": {
                                  "text": "iphone 15",
                                  "lang": "en",
                                  "rank_score": 5.0,
                                  "sources": ["query_log", "qanchor"],
                                  "lang_source": "log_field",
                                  "lang_confidence": 1.0,
                                  "lang_conflict": False,
f251cf2d   tangwang   suggestion全量索引程序跑通
95
96
97
98
99
                              },
                          }
                      ],
                  }
              }
ff9efda0   tangwang   suggest
100
  
f251cf2d   tangwang   suggestion全量索引程序跑通
101
102
          return {"hits": {"total": {"value": 0}, "max_score": 0.0, "hits": []}}
  
f251cf2d   tangwang   suggestion全量索引程序跑通
103
      def bulk_index(self, index_name: str, docs: List[Dict[str, Any]]) -> Dict[str, Any]:
ff9efda0   tangwang   suggest
104
          self.calls.append({"op": "bulk_index", "index": index_name, "docs": docs})
f251cf2d   tangwang   suggestion全量索引程序跑通
105
106
          return {"success": len(docs), "failed": 0, "errors": []}
  
ff9efda0   tangwang   suggest
107
108
109
110
      def bulk_actions(self, actions: List[Dict[str, Any]]) -> Dict[str, Any]:
          self.calls.append({"op": "bulk_actions", "actions": actions})
          return {"success": len(actions), "failed": 0, "errors": []}
  
f251cf2d   tangwang   suggestion全量索引程序跑通
111
      def index_exists(self, index_name: str) -> bool:
ff9efda0   tangwang   suggest
112
          return index_name in self.indices
f251cf2d   tangwang   suggestion全量索引程序跑通
113
114
  
      def delete_index(self, index_name: str) -> bool:
ff9efda0   tangwang   suggest
115
116
117
118
          if index_name in self.indices:
              self.indices.remove(index_name)
              return True
          return False
f251cf2d   tangwang   suggestion全量索引程序跑通
119
120
  
      def create_index(self, index_name: str, body: Dict[str, Any]) -> bool:
ff9efda0   tangwang   suggest
121
122
          self.calls.append({"op": "create_index", "index": index_name, "body": body})
          self.indices.add(index_name)
f251cf2d   tangwang   suggestion全量索引程序跑通
123
124
          return True
  
9f33fe3c   tangwang   fix suggestion re...
125
126
127
128
129
130
131
132
133
134
      def wait_for_index_ready(self, index_name: str, timeout: str = "10s") -> Dict[str, Any]:
          self.calls.append({"op": "wait_for_index_ready", "index": index_name, "timeout": timeout})
          return {"ok": True, "status": "green", "timed_out": False}
  
      def get_allocation_explain(self, index_name: str, shard: int = 0, primary: bool = True) -> Dict[str, Any] | None:
          self.calls.append(
              {"op": "get_allocation_explain", "index": index_name, "shard": shard, "primary": primary}
          )
          return None
  
f251cf2d   tangwang   suggestion全量索引程序跑通
135
      def refresh(self, index_name: str) -> bool:
ff9efda0   tangwang   suggest
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
          self.calls.append({"op": "refresh", "index": index_name})
          return True
  
      def alias_exists(self, alias_name: str) -> bool:
          return alias_name in self.aliases and len(self.aliases[alias_name]) > 0
  
      def get_alias_indices(self, alias_name: str) -> List[str]:
          return list(self.aliases.get(alias_name, []))
  
      def update_aliases(self, actions: List[Dict[str, Any]]) -> bool:
          self.calls.append({"op": "update_aliases", "actions": actions})
          for action in actions:
              if "remove" in action:
                  alias = action["remove"]["alias"]
                  index = action["remove"]["index"]
                  self.aliases[alias] = [x for x in self.aliases.get(alias, []) if x != index]
              if "add" in action:
                  alias = action["add"]["alias"]
                  index = action["add"]["index"]
                  self.aliases[alias] = [index]
f251cf2d   tangwang   suggestion全量索引程序跑通
156
157
          return True
  
ff9efda0   tangwang   suggest
158
159
160
161
      def list_indices(self, pattern: str) -> List[str]:
          prefix = pattern.rstrip("*")
          return sorted([x for x in self.indices if x.startswith(prefix)])
  
f251cf2d   tangwang   suggestion全量索引程序跑通
162
163
  
  @pytest.mark.unit
9f33fe3c   tangwang   fix suggestion re...
164
165
166
167
168
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
  def test_versioned_index_name_uses_microseconds():
      build_at = datetime(2026, 4, 7, 3, 52, 26, 123456, tzinfo=timezone.utc)
      assert (
          get_suggestion_versioned_index_name("163", build_at)
          == "search_suggestions_tenant_163_v20260407035226123456"
      )
  
  
  @pytest.mark.unit
  def test_rebuild_cleans_up_unallocatable_new_index():
      fake_es = FakeESClient()
  
      def _wait_fail(index_name: str, timeout: str = "10s") -> Dict[str, Any]:
          fake_es.calls.append({"op": "wait_for_index_ready", "index": index_name, "timeout": timeout})
          return {"ok": False, "status": "red", "timed_out": True}
  
      def _allocation_explain(index_name: str, shard: int = 0, primary: bool = True) -> Dict[str, Any]:
          fake_es.calls.append(
              {"op": "get_allocation_explain", "index": index_name, "shard": shard, "primary": primary}
          )
          return {
              "unassigned_info": {"reason": "INDEX_CREATED", "last_allocation_status": "no"},
              "node_allocation_decisions": [
                  {
                      "node_name": "node-1",
                      "deciders": [
                          {
                              "decider": "disk_threshold",
                              "decision": "NO",
                              "explanation": "node is above high watermark",
                          }
                      ],
                  }
              ],
          }
  
      fake_es.wait_for_index_ready = _wait_fail  # type: ignore[method-assign]
      fake_es.get_allocation_explain = _allocation_explain  # type: ignore[method-assign]
  
      builder = SuggestionIndexBuilder(es_client=fake_es, db_engine=None)
  
      from config import tenant_config_loader as tcl
  
      loader = tcl.get_tenant_config_loader()
      loader._config = {
          "default": {"primary_language": "en", "index_languages": ["en", "zh"]},
          "tenants": {
              "163": {"primary_language": "en", "index_languages": ["en", "zh"]},
          },
      }
  
      with pytest.raises(RuntimeError, match="disk_threshold"):
          builder.rebuild_tenant_index(tenant_id="163")
  
      create_calls = [x for x in fake_es.calls if x.get("op") == "create_index"]
      assert len(create_calls) == 1
      created_index = create_calls[0]["index"]
      assert created_index not in fake_es.indices
  
  
  @pytest.mark.unit
ff9efda0   tangwang   suggest
225
  def test_resolve_query_language_prefers_log_field():
f251cf2d   tangwang   suggestion全量索引程序跑通
226
227
      fake_es = FakeESClient()
      builder = SuggestionIndexBuilder(es_client=fake_es, db_engine=None)
f251cf2d   tangwang   suggestion全量索引程序跑通
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
      lang, conf, source, conflict = builder._resolve_query_language(
          query="iphone 15",
          log_language="en",
          request_params=None,
          index_languages=["zh", "en"],
          primary_language="zh",
      )
      assert lang == "en"
      assert conf == 1.0
      assert source == "log_field"
      assert conflict is False
  
  
  @pytest.mark.unit
  def test_resolve_query_language_uses_request_params_when_log_missing():
f251cf2d   tangwang   suggestion全量索引程序跑通
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
      fake_es = FakeESClient()
      builder = SuggestionIndexBuilder(es_client=fake_es, db_engine=None)
      request_params = json.dumps({"language": "zh"})
      lang, conf, source, conflict = builder._resolve_query_language(
          query="芭比娃娃",
          log_language=None,
          request_params=request_params,
          index_languages=["zh", "en"],
          primary_language="en",
      )
      assert lang == "zh"
      assert conf == 1.0
      assert source == "request_params"
      assert conflict is False
  
  
  @pytest.mark.unit
  def test_resolve_query_language_fallback_to_primary():
f251cf2d   tangwang   suggestion全量索引程序跑通
261
262
      fake_es = FakeESClient()
      builder = SuggestionIndexBuilder(es_client=fake_es, db_engine=None)
f251cf2d   tangwang   suggestion全量索引程序跑通
263
      lang, conf, source, conflict = builder._resolve_query_language(
42e3aea6   tangwang   tidy
264
          query="123",
f251cf2d   tangwang   suggestion全量索引程序跑通
265
266
267
268
269
270
271
272
273
274
275
          log_language=None,
          request_params=None,
          index_languages=["zh", "en"],
          primary_language="zh",
      )
      assert lang == "zh"
      assert source == "default"
      assert conflict is False
  
  
  @pytest.mark.unit
ff9efda0   tangwang   suggest
276
  def test_suggestion_service_basic_flow_uses_alias_and_routing():
f251cf2d   tangwang   suggestion全量索引程序跑通
277
278
279
      from config import tenant_config_loader as tcl
  
      loader = tcl.get_tenant_config_loader()
f251cf2d   tangwang   suggestion全量索引程序跑通
280
281
282
283
284
285
286
287
      loader._config = {
          "default": {"primary_language": "en", "index_languages": ["en", "zh"]},
          "tenants": {
              "1": {"primary_language": "en", "index_languages": ["en", "zh"]},
          },
      }
  
      fake_es = FakeESClient()
ff9efda0   tangwang   suggest
288
289
290
      alias_name = get_suggestion_alias_name("1")
      fake_es.aliases[alias_name] = ["search_suggestions_tenant_1_v20260310190000"]
  
f251cf2d   tangwang   suggestion全量索引程序跑通
291
292
293
294
295
296
      service = SuggestionService(es_client=fake_es)
      result = service.search(
          tenant_id="1",
          query="iph",
          language="en",
          size=5,
f251cf2d   tangwang   suggestion全量索引程序跑通
297
298
299
300
301
302
303
      )
  
      assert result["resolved_language"] == "en"
      assert result["query"] == "iph"
      assert result["took_ms"] >= 0
      suggestions = result["suggestions"]
      assert len(suggestions) == 1
ff9efda0   tangwang   suggest
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
      assert suggestions[0]["text"] == "iphone 15"
  
      search_calls = [x for x in fake_es.calls if x.get("op") == "search"]
      assert len(search_calls) >= 2
      assert any(x.get("routing") == "1" for x in search_calls)
      assert any(x.get("index") == alias_name for x in search_calls)
  
  
  @pytest.mark.unit
  def test_publish_alias_and_cleanup_old_versions(monkeypatch):
      fake_es = FakeESClient()
      builder = SuggestionIndexBuilder(es_client=fake_es, db_engine=None)
  
      tenant_id = "162"
      alias_name = get_suggestion_alias_name(tenant_id)
      fake_es.indices.update(
          {
              "search_suggestions_tenant_162_v20260310170000",
              "search_suggestions_tenant_162_v20260310180000",
              "search_suggestions_tenant_162_v20260310190000",
          }
      )
      fake_es.aliases[alias_name] = ["search_suggestions_tenant_162_v20260310180000"]
  
      monkeypatch.setattr(builder, "_upsert_meta", lambda tenant_id, patch: None)
  
      result = builder._publish_alias(
          tenant_id=tenant_id,
          index_name="search_suggestions_tenant_162_v20260310190000",
          keep_versions=2,
      )
  
      assert result["current_index"] == "search_suggestions_tenant_162_v20260310190000"
      assert fake_es.aliases[alias_name] == ["search_suggestions_tenant_162_v20260310190000"]
      assert "search_suggestions_tenant_162_v20260310170000" not in fake_es.indices
  
  
  @pytest.mark.unit
  def test_incremental_bootstrap_when_no_active_index(monkeypatch):
      fake_es = FakeESClient()
      builder = SuggestionIndexBuilder(es_client=fake_es, db_engine=None)
  
      from config import tenant_config_loader as tcl
  
      loader = tcl.get_tenant_config_loader()
      loader._config = {
          "default": {"primary_language": "en", "index_languages": ["en", "zh"]},
          "tenants": {"162": {"primary_language": "en", "index_languages": ["en", "zh"]}},
      }
  
      monkeypatch.setattr(
          builder,
          "rebuild_tenant_index",
          lambda **kwargs: {"mode": "full", "tenant_id": kwargs["tenant_id"], "index_name": "v_idx"},
      )
  
      result = builder.incremental_update_tenant_index(tenant_id="162", bootstrap_if_missing=True)
      assert result["mode"] == "incremental"
      assert result["bootstrapped"] is True
      assert result["bootstrap_result"]["mode"] == "full"
  
  
  @pytest.mark.unit
  def test_incremental_updates_existing_index(monkeypatch):
      fake_es = FakeESClient()
      builder = SuggestionIndexBuilder(es_client=fake_es, db_engine=None)
  
      from config import tenant_config_loader as tcl
  
      loader = tcl.get_tenant_config_loader()
      loader._config = {
          "default": {"primary_language": "en", "index_languages": ["en", "zh"]},
          "tenants": {"162": {"primary_language": "en", "index_languages": ["en", "zh"]}},
      }
  
      tenant_id = "162"
      alias_name = get_suggestion_alias_name(tenant_id)
      active_index = "search_suggestions_tenant_162_v20260310190000"
      fake_es.aliases[alias_name] = [active_index]
  
      watermark = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
      monkeypatch.setattr(builder, "_get_meta", lambda _tenant_id: {"last_incremental_watermark": watermark})
      monkeypatch.setattr(builder, "_upsert_meta", lambda tenant_id, patch: None)
  
      monkeypatch.setattr(
          builder,
          "_build_incremental_deltas",
          lambda **kwargs: {
              ("en", "iphone 15"): QueryDelta(
                  tenant_id=tenant_id,
                  lang="en",
                  text="iphone 15",
                  text_norm="iphone 15",
                  delta_7d=2,
                  delta_30d=3,
                  lang_confidence=1.0,
                  lang_source="log_field",
                  lang_conflict=False,
              )
          },
      )
  
      result = builder.incremental_update_tenant_index(
          tenant_id=tenant_id,
          bootstrap_if_missing=False,
          overlap_minutes=10,
      )
  
      assert result["mode"] == "incremental"
      assert result["target_index"] == active_index
      assert result["updated_terms"] == 1
      assert result["bulk_result"]["failed"] == 0
f251cf2d   tangwang   suggestion全量索引程序跑通
416
  
ff9efda0   tangwang   suggest
417
418
419
      bulk_calls = [x for x in fake_es.calls if x.get("op") == "bulk_actions"]
      assert len(bulk_calls) == 1
      assert len(bulk_calls[0]["actions"]) == 1
daf66a51   tangwang   已完成接口级压测脚本,覆盖搜索、s...
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
  
  
  @pytest.mark.unit
  def test_build_full_candidates_fallback_to_id_when_spu_id_missing(monkeypatch):
      fake_es = FakeESClient()
      builder = SuggestionIndexBuilder(es_client=fake_es, db_engine=None)
  
      monkeypatch.setattr(
          builder,
          "_iter_products",
          lambda tenant_id, batch_size=500: iter(
              [
                  {
                      "_id": "521",
                      "_source": {
                          "id": "521",
                          "title": {"en": "Furby Toy"},
                          "qanchors": {"en": "furby"},
                      },
                  }
              ]
          ),
      )
      monkeypatch.setattr(builder, "_iter_query_log_rows", lambda **kwargs: iter([]))
  
      key_to_candidate = builder._build_full_candidates(
          tenant_id="162",
          index_languages=["en"],
          primary_language="en",
          days=365,
          batch_size=100,
          min_query_len=1,
      )
  
      title_key = ("en", "furby toy")
      qanchor_key = ("en", "furby")
      assert title_key in key_to_candidate
      assert qanchor_key in key_to_candidate
      assert key_to_candidate[title_key].title_spu_ids == {"521"}
      assert key_to_candidate[qanchor_key].qanchor_spu_ids == {"521"}
  
  
  @pytest.mark.unit
00c8ddb9   tangwang   suggest rank opti...
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
  def test_build_full_candidates_tags_and_qanchor_phrases(monkeypatch):
      fake_es = FakeESClient()
      builder = SuggestionIndexBuilder(es_client=fake_es, db_engine=None)
  
      monkeypatch.setattr(
          builder,
          "_iter_products",
          lambda tenant_id, batch_size=500: iter(
              [
                  {
                      "_id": "900",
                      "_source": {
                          "spu_id": "900",
                          "title": {"en": "Tee", "zh": "T恤"},
                          "qanchors": {
d350861f   tangwang   索引结构修改
478
479
480
                              "en": ["slim fit", "sporty casual"],
                              "zh": ["修身", "显瘦"],
                          },
e50924ed   tangwang   1. tags -> enrich...
481
                          "enriched_tags": {
d350861f   tangwang   索引结构修改
482
483
                              "en": ["Classic", "ribbed neckline"],
                              "zh": ["辣妹风"],
00c8ddb9   tangwang   suggest rank opti...
484
                          },
00c8ddb9   tangwang   suggest rank opti...
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
                      },
                  }
              ]
          ),
      )
      monkeypatch.setattr(builder, "_iter_query_log_rows", lambda **kwargs: iter([]))
  
      key_to_candidate = builder._build_full_candidates(
          tenant_id="162",
          index_languages=["en", "zh"],
          primary_language="en",
          days=365,
          batch_size=100,
          min_query_len=1,
      )
  
      assert ("en", "slim fit") in key_to_candidate
      assert ("en", "sporty casual") in key_to_candidate
      assert ("zh", "修身") in key_to_candidate
      assert ("zh", "显瘦") in key_to_candidate
      assert ("en", "classic") in key_to_candidate
      assert key_to_candidate[("en", "classic")].tag_spu_ids == {"900"}
      assert ("zh", "辣妹风") in key_to_candidate
      assert key_to_candidate[("zh", "辣妹风")].tag_spu_ids == {"900"}
      assert ("en", "ribbed neckline") in key_to_candidate
  
  
  @pytest.mark.unit
daf66a51   tangwang   已完成接口级压测脚本,覆盖搜索、s...
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
  def test_build_full_candidates_splits_long_title_for_suggest(monkeypatch):
      fake_es = FakeESClient()
      builder = SuggestionIndexBuilder(es_client=fake_es, db_engine=None)
  
      long_title = (
          "Furby Furblets 2-Pack, Mini Friends Ray-Vee & Hip-Bop, 45+ Sounds Each, "
          "Music & Furbish Phrases, Electronic Plush Toys, Rainbow & Pink/Purple, "
          "Ages 6+ (Amazon Exclusive)"
      )
      monkeypatch.setattr(
          builder,
          "_iter_products",
          lambda tenant_id, batch_size=500: iter(
              [{"_id": "521", "_source": {"id": "521", "title": {"en": long_title}, "qanchors": {}}}]
          ),
      )
      monkeypatch.setattr(builder, "_iter_query_log_rows", lambda **kwargs: iter([]))
  
      key_to_candidate = builder._build_full_candidates(
          tenant_id="162",
          index_languages=["en"],
          primary_language="en",
          days=365,
          batch_size=100,
          min_query_len=1,
      )
  
      key = ("en", "furby furblets 2-pack")
      assert key in key_to_candidate
      assert key_to_candidate[key].text == "Furby Furblets 2-Pack"
  
  
  @pytest.mark.unit
  def test_iter_products_requests_dual_sort_and_fields():
      fake_es = FakeESClient()
      builder = SuggestionIndexBuilder(es_client=fake_es, db_engine=None)
  
      list(builder._iter_products(tenant_id="162", batch_size=10))
  
      search_calls = [x for x in fake_es.calls if x.get("op") == "search"]
      assert len(search_calls) >= 1
      body = search_calls[0]["body"]
      sort = body.get("sort", [])
      assert {"spu_id": {"order": "asc", "missing": "_last"}} in sort
      assert {"id.keyword": {"order": "asc", "missing": "_last"}} in sort
      assert "id" in body.get("_source", [])
      assert "spu_id" in body.get("_source", [])