argo-search 2.11.2 → 2.12.0

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.
Files changed (72) hide show
  1. package/README.en.md +25 -21
  2. package/README.es.md +24 -20
  3. package/README.ja.md +25 -21
  4. package/README.ko.md +24 -20
  5. package/README.md +30 -22
  6. package/SKILL.md +6 -6
  7. package/backends/domain_profiles.json +12 -0
  8. package/backends/engine_registry.yaml +26 -1
  9. package/backends/quota_profiles.json +20 -0
  10. package/bin/argo +7 -0
  11. package/config.yaml +18 -3
  12. package/docs/ENGINE_CATALOG.md +8 -6
  13. package/docs/MCP_SETUP.md +16 -4
  14. package/docs/RELEASE_NOTES_v2.11.2.md +116 -0
  15. package/docs/RELEASE_NOTES_v2.12.0.md +65 -0
  16. package/docs/engines/pixiv.md +27 -0
  17. package/engines/specs/pixiv.yaml +52 -0
  18. package/engines/specs/tracemoe.yaml +33 -0
  19. package/package.json +3 -2
  20. package/packages/dsh-plugin/README.md +20 -11
  21. package/packages/dsh-plugin/dsh/client.js +3 -3
  22. package/packages/dsh-plugin/dsh/index.js +22 -176
  23. package/packages/dsh-plugin/dsh/runner.js +12 -2
  24. package/packages/dsh-plugin/dsh/specs.js +133 -0
  25. package/packages/dsh-plugin/package.json +10 -2
  26. package/packages/dsh-plugin/test/client.test.js +4 -4
  27. package/packages/dsh-plugin/test/diagnostics.test.js +1 -1
  28. package/packages/dsh-plugin/test/index.test.js +28 -2
  29. package/scripts/adaptive.py +101 -27
  30. package/scripts/build_route_labels.py +122 -169
  31. package/scripts/caliber_dedupe.py +4 -4
  32. package/scripts/caliber_isolation.py +17 -17
  33. package/scripts/concept_lookup.py +14 -1
  34. package/scripts/config.py +21 -3
  35. package/scripts/engine_admission.py +35 -17
  36. package/scripts/engine_dispatch.py +16 -16
  37. package/scripts/engine_env.py +4 -0
  38. package/scripts/engine_families.py +6 -4
  39. package/scripts/engines.py +5 -0
  40. package/scripts/engines_base.py +1 -1
  41. package/scripts/engines_builders_data.py +10 -10
  42. package/scripts/engines_builders_pixiv.py +633 -0
  43. package/scripts/engines_builders_reverse_image.py +175 -0
  44. package/scripts/env_store.py +216 -0
  45. package/scripts/extend_route_labels_by_capability.py +4 -4
  46. package/scripts/extend_route_labels_full_coverage.py +329 -0
  47. package/scripts/fetch_v3.py +74 -5
  48. package/scripts/job.py +31 -6
  49. package/scripts/local_image.py +22 -8
  50. package/scripts/mcp_compact.py +9 -1
  51. package/scripts/mcp_launch.sh +1 -1
  52. package/scripts/mcp_setup.py +85 -1
  53. package/scripts/mcp_transport.py +1 -1
  54. package/scripts/plan.py +2 -2
  55. package/scripts/pre-commit +4 -1
  56. package/scripts/query_signals.py +35 -20
  57. package/scripts/quota.py +9 -4
  58. package/scripts/recovery.py +38 -13
  59. package/scripts/redskill/redskill_engine.py +33 -10
  60. package/scripts/route.py +2 -2
  61. package/scripts/route_accuracy_eval.py +2 -2
  62. package/scripts/route_combo.py +22 -3
  63. package/scripts/route_domains.py +182 -50
  64. package/scripts/search.py +0 -2
  65. package/scripts/search_entry.py +38 -42
  66. package/scripts/search_output.py +3 -0
  67. package/scripts/search_pipeline.py +3 -8
  68. package/scripts/search_rank.py +22 -7
  69. package/scripts/serp_guard.py +7 -16
  70. package/scripts/settings_page.py +486 -0
  71. package/scripts/straggler_policy.py +8 -4
  72. package/scripts/tfidf_router.py +82 -24
@@ -75,55 +75,129 @@ _ZH_LANG_GATED_DOMAINS = frozenset({
75
75
  _compiled_domains: list[dict[str, Any]] | None = None
76
76
  _compiled_domains_id: tuple | None = None # (name, patterns/exclude_if 内容指纹)
77
77
  _compiled_domains_ref: int | None = None
78
- _anchor_matcher: re.Pattern | None = None
78
+ _anchor_matcher: Any = None
79
79
  _anchor_to_domains: dict[str, list[int]] = {}
80
+ _anchor_first_char_lens: dict[str, list[int]] = {}
80
81
  _unconstrained_domains: set[int] = set()
81
82
 
83
+ _ANCHOR_LOOKAROUND_RE = re.compile(r"\(\?[=!<][^()]*\)")
84
+ _ANCHOR_OPT_GROUP_RE = re.compile(r"\((?:\?:)?[^()]+\)(?:\?|\*|\{0,[^}]*\})")
85
+ _ANCHOR_CHARSET_RE = re.compile(r"\[(?:\\.|[^\]\\])*\]\??\*?\+?(?:\{\d+,?\d*\})?")
86
+ _ANCHOR_ESCAPE_RE = re.compile(r"\\[wWdDsSbB]|\\.")
87
+ _ANCHOR_OPT_CHAR_RE = re.compile(r"[^()|\\]\?|\.\*|\.\+|\.\?")
88
+ _ANCHOR_QUANT_RE = re.compile(r"\{\d+,?\d*\}")
89
+ _ANCHOR_INNER_GROUP_RE = re.compile(r"\((?:\?:)?([^()]+)\)")
90
+ _ANCHOR_RUN_RE = re.compile(
91
+ r"[\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]{1,}"
92
+ r"|[a-zA-Z0-9_\-\.\u00c0-\u024f\u0400-\u04ff\u0600-\u06ff\u0590-\u05ff\u0e00-\u0e7f]{2,}"
93
+ )
82
94
 
83
- def _extract_anchors(src: Any) -> set[str] | None:
84
- """从正则源码中提取一组必须包含其一的字面锚点词集合(全小写)。
85
95
 
86
- 若无法提取安全锚点(如含有纯通配、字符集类 []、通用转义字符类),返回 None。
87
- """
88
- if not isinstance(src, str) or not src:
89
- return None
90
- s = re.sub(r"^\(\?[a-zA-Z]+\)", "", src)
91
- s = re.sub(r"\\b", "", s)
92
- if s.startswith("(") and s.endswith(")"):
93
- s = s[1:-1]
96
+ def _split_top_level_pipe(s: str) -> list[str]:
94
97
  parts: list[str] = []
95
98
  depth = 0
99
+ in_br = False
100
+ escape = False
96
101
  cur: list[str] = []
97
102
  for ch in s:
98
- if ch in ("(", "["):
99
- depth += 1
100
- elif ch in (")", "]"):
101
- depth -= 1
102
- if ch == "|" and depth == 0:
103
- parts.append("".join(cur))
104
- cur = []
105
- else:
103
+ if escape:
106
104
  cur.append(ch)
105
+ escape = False
106
+ continue
107
+ if ch == "\\":
108
+ cur.append(ch)
109
+ escape = True
110
+ continue
111
+ if ch == "[" and not in_br:
112
+ in_br = True
113
+ elif ch == "]" and in_br:
114
+ in_br = False
115
+ elif not in_br:
116
+ if ch == "(":
117
+ depth += 1
118
+ elif ch == ")":
119
+ depth -= 1
120
+ elif ch == "|" and depth == 0:
121
+ parts.append("".join(cur))
122
+ cur = []
123
+ continue
124
+ cur.append(ch)
107
125
  if cur:
108
126
  parts.append("".join(cur))
127
+ return parts
128
+
129
+
130
+ def _extract_anchors(src: Any, _depth: int = 0) -> set[str] | None:
131
+ """从正则源码中提取一组必须包含其一的字面锚点词集合(全小写)。
109
132
 
133
+ 对每个顶层 | 分支提取必现字面量(剥离环视断言、字符集、转义类与可选量词),
134
+ 若某分支无顶层字面量但含必现括号组,则递归提取该组的锚点并求并集。
135
+ 若任一分支无法提取安全锚点,返回 None(该域归入 _unconstrained_domains)。
136
+ """
137
+ if not isinstance(src, str) or not src or _depth > 3:
138
+ return None
139
+ s = re.sub(r"^\(\?[a-zA-Z]+\)", "", src.strip())
140
+ while s.startswith("(") and s.endswith(")"):
141
+ inner = s[1:-1]
142
+ if len(_split_top_level_pipe(inner)) >= 1 and inner.count("(") == inner.count(")"):
143
+ d = 0
144
+ ok = True
145
+ for ch in inner:
146
+ if ch == "(":
147
+ d += 1
148
+ elif ch == ")":
149
+ d -= 1
150
+ if d < 0:
151
+ ok = False
152
+ break
153
+ if ok and d == 0:
154
+ s = inner
155
+ continue
156
+ break
157
+ if s.startswith("?:"):
158
+ s = s[2:]
159
+
160
+ parts = _split_top_level_pipe(s)
161
+ if not parts:
162
+ return None
110
163
  anchors: set[str] = set()
111
164
  for part in parts:
112
- # 正则字符类与元字符无法保证字面子串存在
113
- if re.search(r"\[.*?\]", part) or re.search(r"\\[wWdDsS]", part):
114
- return None
115
- runs = re.findall(r"[\u4e00-\u9fff]{1,}|[a-zA-Z0-9_\-\.]{2,}", part)
116
- if not runs:
165
+ p_no_la = _ANCHOR_LOOKAROUND_RE.sub(" ", part)
166
+ p_no_opt_grp = _ANCHOR_OPT_GROUP_RE.sub(" ", p_no_la)
167
+ p_outside = re.sub(r"\([^()]*\)", " ", p_no_opt_grp)
168
+ while "(" in p_outside and ")" in p_outside:
169
+ p_outside_next = re.sub(r"\([^()]*\)", " ", p_outside)
170
+ if p_outside_next == p_outside:
171
+ break
172
+ p_outside = p_outside_next
173
+ p_clean = _ANCHOR_CHARSET_RE.sub(" ", p_outside)
174
+ p_clean = _ANCHOR_ESCAPE_RE.sub(" ", p_clean)
175
+ p_clean = _ANCHOR_OPT_CHAR_RE.sub(" ", p_clean)
176
+ p_clean = _ANCHOR_QUANT_RE.sub(" ", p_clean)
177
+ runs = _ANCHOR_RUN_RE.findall(p_clean)
178
+ # 单字锚点(含 CJK 单字)过滤力接近零、还会把带通配的模式误判成有锚点,
179
+ # 一律不收:宁可落进 _unconstrained_domains 多算几路,也不造假锚点。
180
+ valid = [v for v in (r.strip(".-_").lower() for r in runs) if len(v) >= 2]
181
+ if valid:
182
+ anchors.add(max(valid, key=len))
183
+ continue
184
+ found_grp = False
185
+ for m_grp in _ANCHOR_INNER_GROUP_RE.finditer(p_no_opt_grp):
186
+ grp_anc = _extract_anchors(m_grp.group(1), _depth + 1)
187
+ if grp_anc:
188
+ anchors.update(grp_anc)
189
+ found_grp = True
190
+ break
191
+ if not found_grp:
117
192
  return None
118
- for r in runs:
119
- anchors.add(r.lower())
120
193
  return anchors if anchors else None
121
194
 
122
195
 
123
196
  def _init_anchor_index(compiled: list[dict[str, Any]]) -> None:
124
- """初始化全局锚点自动机索引(方案一:Aho-Corasick 前置快速分桶)。"""
125
- global _anchor_matcher, _anchor_to_domains, _unconstrained_domains
197
+ """初始化全局锚点字典索引(子串闭包 + 首字符长度表贪心扫描)。"""
198
+ global _anchor_matcher, _anchor_to_domains, _anchor_first_char_lens, _unconstrained_domains
126
199
  _anchor_to_domains = {}
200
+ _anchor_first_char_lens = {}
127
201
  _unconstrained_domains = set()
128
202
  all_anchors: set[str] = set()
129
203
 
@@ -149,23 +223,46 @@ def _init_anchor_index(compiled: list[dict[str, Any]]) -> None:
149
223
  all_anchors.add(term)
150
224
 
151
225
  if all_anchors:
152
- sorted_terms = sorted(all_anchors, key=len, reverse=True)
153
- escaped = [re.escape(t) for t in sorted_terms]
154
- _anchor_matcher = re.compile("|".join(escaped), re.IGNORECASE)
226
+ by_fc: dict[str, set[int]] = {}
227
+ for t in all_anchors:
228
+ by_fc.setdefault(t[0], set()).add(len(t))
229
+ _anchor_first_char_lens = {
230
+ k: sorted(v, reverse=True) for k, v in by_fc.items()
231
+ }
232
+ _anchor_matcher = True
155
233
  else:
156
234
  _anchor_matcher = None
157
235
 
158
236
 
159
237
  def _get_candidate_domain_indices(query: str) -> set[int] | None:
160
- """通过锚点词快速扫描返回候选域索引集合;无索引时返回 None。"""
161
- if _anchor_matcher is None:
238
+ """通过锚点字典快速扫描返回候选域索引集合;无索引时返回 None。
239
+
240
+ 为与旧 `_anchor_matcher.finditer` 的非重叠贪心最长匹配语义逐位一致,
241
+ 命中长为 ln 的锚点词后游标推进 ln(不回看其内部被长词覆盖的短子串)。
242
+ """
243
+ if not _anchor_matcher:
162
244
  return None
163
245
  candidates = set(_unconstrained_domains)
164
- for m in _anchor_matcher.finditer(query):
165
- term = m.group(0).lower()
166
- doms = _anchor_to_domains.get(term)
167
- if doms:
168
- candidates.update(doms)
246
+ q_low = query.lower()
247
+ qn = len(q_low)
248
+ fc_map = _anchor_first_char_lens
249
+ a2d = _anchor_to_domains
250
+ i = 0
251
+ while i < qn:
252
+ lens = fc_map.get(q_low[i])
253
+ if not lens:
254
+ i += 1
255
+ continue
256
+ rem = qn - i
257
+ matched_ln = 0
258
+ for ln in lens:
259
+ if ln <= rem:
260
+ doms = a2d.get(q_low[i:i + ln])
261
+ if doms:
262
+ candidates.update(doms)
263
+ matched_ln = ln
264
+ break
265
+ i += matched_ln if matched_ln > 0 else 1
169
266
  return candidates
170
267
 
171
268
 
@@ -292,25 +389,51 @@ class _LiteralMatcher:
292
389
  alternation(如 `(?i)(金十|jin10)`、`(?i)(技术社区|程序员社区)`),它们每次
293
390
  冷进程都要付一次 `re.compile`(326 条全量实测 23.8 ms),而子串查找零编译、
294
391
  更快。判定由 `_literal_alternatives` 保守把关,判不准的一律走原正则路径。
392
+ AC-IGTR 增补首字符分桶索引与预小写复用,消除宽分支字面表的无关扫描。
295
393
  """
296
394
 
297
- __slots__ = ("_words", "_ignore_case")
395
+ __slots__ = ("_words", "_ignore_case", "_by_fc")
298
396
 
299
397
  def __init__(self, words: list[str], ignore_case: bool):
300
398
  self._words = words
301
399
  self._ignore_case = ignore_case
400
+ if len(words) >= 6:
401
+ by_fc: dict[str, list[tuple[int, str]]] = {}
402
+ for idx, w in enumerate(words):
403
+ by_fc.setdefault(w[0], []).append((idx, w))
404
+ self._by_fc: dict[str, list[tuple[int, str]]] | None = by_fc
405
+ else:
406
+ self._by_fc = None
302
407
 
303
- def search(self, query: str) -> _LiteralMatch | None:
304
- hay = query.lower() if self._ignore_case else query
305
- best: tuple[int, int] | None = None
306
- for w in self._words:
408
+ def search(self, query: str, q_lower: str | None = None) -> _LiteralMatch | None:
409
+ hay = (q_lower if q_lower is not None else query.lower()) if self._ignore_case else query
410
+ if not hay:
411
+ return None
412
+ best: tuple[int, int, int] | None = None
413
+ if self._by_fc is not None:
414
+ seen_fc: set[str] = set()
415
+ for ch in hay:
416
+ if ch in seen_fc:
417
+ continue
418
+ seen_fc.add(ch)
419
+ bucket = self._by_fc.get(ch)
420
+ if not bucket:
421
+ continue
422
+ for idx, w in bucket:
423
+ pos = hay.find(w)
424
+ if pos < 0:
425
+ continue
426
+ if best is None or pos < best[0] or (pos == best[0] and idx < best[1]):
427
+ best = (pos, idx, pos + len(w))
428
+ return _LiteralMatch((best[0], best[2])) if best is not None else None
429
+ for idx, w in enumerate(self._words):
307
430
  pos = hay.find(w)
308
431
  if pos < 0:
309
432
  continue
310
433
  # 与 re 的 leftmost 语义一致:取最早出现;同位置取分支顺序在前者
311
434
  if best is None or pos < best[0]:
312
- best = (pos, pos + len(w))
313
- return _LiteralMatch(best) if best is not None else None
435
+ best = (pos, idx, pos + len(w))
436
+ return _LiteralMatch((best[0], best[2])) if best is not None else None
314
437
 
315
438
 
316
439
  def _try_compile(src: Any) -> Any:
@@ -424,12 +547,20 @@ def _split_pattern_entry(entry: Any) -> tuple[Any, Any]:
424
547
  return entry, None
425
548
 
426
549
 
427
- def _domain_fires_with_span(domain: dict[str, Any], query: str) -> tuple[bool, int, int]:
550
+ def _domain_fires_with_span(
551
+ domain: dict[str, Any], query: str, q_lower: str | None = None
552
+ ) -> tuple[bool, int, int]:
428
553
  """一个域是否成立,并返回命中的 (是否成立, match_span_start, match_span_len)。"""
429
554
  for match_re, unless_re in _ensure_domain_compiled(domain):
430
- if unless_re is not None and unless_re.search(query):
431
- continue
432
- m = match_re.search(query)
555
+ if unless_re is not None:
556
+ u_hit = (unless_re.search(query, q_lower)
557
+ if isinstance(unless_re, _LiteralMatcher)
558
+ else unless_re.search(query))
559
+ if u_hit:
560
+ continue
561
+ m = (match_re.search(query, q_lower)
562
+ if isinstance(match_re, _LiteralMatcher)
563
+ else match_re.search(query))
433
564
  if m is not None:
434
565
  start, end = m.span()
435
566
  return True, start, end - start
@@ -676,6 +807,7 @@ def match_domains(query: str, domains: list[dict[str, Any]] | None = None,
676
807
  non_zh = bool(primary_lang and primary_lang not in ("zh", "mixed", "other"))
677
808
  candidates = _get_candidate_domain_indices(query)
678
809
  q_len = max(len(query), 1)
810
+ q_lower = query.lower()
679
811
 
680
812
  for idx, domain in enumerate(compiled):
681
813
  if not domain.get("patterns", []):
@@ -685,7 +817,7 @@ def match_domains(query: str, domains: list[dict[str, Any]] | None = None,
685
817
  continue
686
818
  if candidates is not None and idx not in candidates:
687
819
  continue
688
- fires, span_start, span_len = _domain_fires_with_span(domain, query)
820
+ fires, span_start, span_len = _domain_fires_with_span(domain, query, q_lower)
689
821
  if fires:
690
822
  if not hits:
691
823
  hits.append(domain)
package/scripts/search.py CHANGED
@@ -235,8 +235,6 @@ def _local_seek_grace_s() -> float:
235
235
  return 0.25
236
236
 
237
237
 
238
- _LOCAL_SEEK_GRACE_S = _local_seek_grace_s()
239
-
240
238
  # include-local 的本地搜索 worker:单例下沉到 local_seek 模块,避免 search.py
241
239
  # 在 daemon.py 的 runpy.run_module("search", run_name="__main__") 下重跑顶层时
242
240
  # 把 _LOCAL_SEEK_EXECUTOR 覆写为 None、导致每次调用泄漏一个 ThreadPoolExecutor。
@@ -120,51 +120,9 @@ def prepare(query: str, decision: dict[str, Any], max_results: int,
120
120
  engines = [e for e in engines_combo if e] or ["anysearch"]
121
121
  parallel = decision.get("parallel", False) and len(engines) > 1
122
122
 
123
- # P0-001:查询理解 — clean_query 用于检索,exclude_terms 用于融合后过滤
124
- exclude_terms: list[str] = []
125
- retrieval_query = query
126
- qu = None
127
- try:
128
- from query_understanding import _understand_cached as understand
129
- qu = understand(query)
130
- exclude_terms = qu.exclude_terms
131
- # 查询操作符 -词/-"短语" 的排除项汇合(2026-10-17 query_operators):
132
- # 与否定理解共用同一「融合后过滤」通道,去重保序。
133
- _op_excl = ((decision or {}).get("operators") or {}).get("exclude_terms") or []
134
- for t in _op_excl:
135
- if t and t not in exclude_terms:
136
- exclude_terms.append(t)
137
- # 仅当去否定片段后仍有实义内容时才替换检索词,避免空检索
138
- if qu.clean_query and qu.clean_query.strip():
139
- retrieval_query = qu.clean_query
140
- except ImportError:
141
- pass # query_understanding 不可用
142
- except Exception as e:
143
- _log(f"查询理解跳过: {type(e).__name__}")
144
-
145
- # 词形规范化:全角→半角、拆斜杠、压多余空格(提升精确源命中,治型号/日期分隔符)
146
- try:
147
- from query_enhance import normalize_query
148
- retrieval_query = normalize_query(retrieval_query)
149
- except ImportError:
150
- pass
151
-
152
123
  if on_progress:
153
124
  on_progress(Stage.START, {"query": query})
154
125
 
155
- # 网络环境感知:慢网放大超时预算(避免误杀),快网收紧(更快响应)
156
- _eff_timeout = timeout
157
- try:
158
- from network_aware import adjusted_timeout, network_profile
159
- _eff_timeout = adjusted_timeout(timeout, engines)
160
- if _eff_timeout != timeout:
161
- _log(
162
- f"网络感知超时: {timeout}s → {_eff_timeout}s "
163
- f"({network_profile(engines).get('network')})",
164
- )
165
- except ImportError:
166
- pass
167
-
168
126
  # 时间窗归一化:下推/缓存键用归一化 ISO(相对值转绝对日期),
169
127
  # 后过滤用 epoch 秒;非法输入保持原样下推、不参与后过滤。
170
128
  since_iso, until_iso, since_ts, until_ts = _normalize_time_window(since, until)
@@ -281,6 +239,44 @@ def prepare(query: str, decision: dict[str, Any], max_results: int,
281
239
  if timing is not None:
282
240
  _hit["timing"] = timing.summary()
283
241
  return _Prepared(cached=_hit)
242
+
243
+ # 缓存未命中才拉起查询理解、词形规范化与网络感知超时(缓存命中热路径零开销)
244
+ exclude_terms: list[str] = []
245
+ retrieval_query = query
246
+ qu = None
247
+ try:
248
+ from query_understanding import _understand_cached as understand
249
+ qu = understand(query)
250
+ exclude_terms = qu.exclude_terms
251
+ _op_excl = ((decision or {}).get("operators") or {}).get("exclude_terms") or []
252
+ for t in _op_excl:
253
+ if t and t not in exclude_terms:
254
+ exclude_terms.append(t)
255
+ if qu.clean_query and qu.clean_query.strip():
256
+ retrieval_query = qu.clean_query
257
+ except ImportError:
258
+ pass
259
+ except Exception as e:
260
+ _log(f"查询理解跳过: {type(e).__name__}")
261
+
262
+ try:
263
+ from query_enhance import normalize_query
264
+ retrieval_query = normalize_query(retrieval_query)
265
+ except ImportError:
266
+ pass
267
+
268
+ _eff_timeout = timeout
269
+ try:
270
+ from network_aware import adjusted_timeout, network_profile
271
+ _eff_timeout = adjusted_timeout(timeout, engines)
272
+ if _eff_timeout != timeout:
273
+ _log(
274
+ f"网络感知超时: {timeout}s → {_eff_timeout}s "
275
+ f"({network_profile(engines).get('network')})",
276
+ )
277
+ except ImportError:
278
+ pass
279
+
284
280
  try:
285
281
  from circuit_breaker import get_breaker
286
282
  breaker = get_breaker()
@@ -70,6 +70,9 @@ _AGENT_RESULT_FIELDS = (
70
70
  # 出现(backfill_results 回填),未核验结果不造假摘要。
71
71
  "summary",
72
72
  "image_url", "image_license",
73
+ # 双通道引擎(同一引擎名背后有匿名与认证两条取数通路)标出本条实际走的
74
+ # 通道:内容范围差异正是两条通路的区别,剥掉它就只能靠猜。
75
+ "channel",
73
76
  "episode_count", "duration_minutes",
74
77
  # 本地已有正文:是可操作提示而非观测数据——告诉 Agent 这条不必重新联网,
75
78
  # 以及全文在哪(被截断时还给出 full_text_path)。剥掉它等于把「随时
@@ -810,11 +810,12 @@ def finalize(req: _SearchRequest, run: _SearchRun, hooks: Any) -> dict[str, Any]
810
810
  # 自适应学习(单事务批量写入 + cache_guard 统一状态态过滤)
811
811
  try:
812
812
  import contextlib
813
- from adaptive import get_learner, scenario_of
813
+ from adaptive import get_learner, marginal_contribution, scenario_of
814
814
  learner = get_learner()
815
815
  _outcome_of = {o.get("engine"): o
816
816
  for o in engine_outcomes if isinstance(o, dict)}
817
817
  _batch_ctx = learner.batch() if hasattr(learner, "batch") else contextlib.nullcontext()
818
+ _shares = marginal_contribution(merged, max_results, [e for e, r in raw_results.items() if r]) # 终榜边际贡献,见 adaptive
818
819
  with _batch_ctx:
819
820
  for eng, res in raw_results.items():
820
821
  outcome = _outcome_of.get(eng)
@@ -826,13 +827,7 @@ def finalize(req: _SearchRequest, run: _SearchRun, hooks: Any) -> dict[str, Any]
826
827
  empty = (not success) and st in ("no-results", "no-results-cached")
827
828
  latency = engine_latency.get(eng, elapsed / max(len(raw_results), 1))
828
829
  cost = get_cost_factor(eng)
829
- quality = None
830
- if success:
831
- try:
832
- from query_signals import result_relevance
833
- quality = result_relevance(query, res)
834
- except Exception:
835
- quality = None
830
+ quality = _shares.get(eng) if success else None
836
831
  learner.record(eng, success=success, latency_ms=latency,
837
832
  cost=0.0 if cost >= 0.85 else 0.001, empty=empty,
838
833
  quality=quality, **scenario_of(decision))
@@ -500,7 +500,7 @@ def rerank_results(query: str, results: list[dict[str, Any]],
500
500
  """使用博查语义排序模型对搜索结果二次精排。
501
501
 
502
502
  返回 (results, status):status ∈ ok | skipped_no_key | skipped_short |
503
- skipped_fast | skipped_circuit_open | fallback
503
+ skipped_fast | skipped_circuit_open | skipped_quota | fallback
504
504
  """
505
505
  if not results or len(results) <= 1:
506
506
  return results, "skipped_short"
@@ -509,6 +509,20 @@ def rerank_results(query: str, results: list[dict[str, Any]],
509
509
  if not api_key:
510
510
  return results, "skipped_no_key"
511
511
 
512
+ # 配额联动(在熔断器之前):bocha 搜索侧已归因 quota_exhausted(同源同
513
+ # key)时,精排端点连「半开探测」都不必打。此前 rerank 的 403 归 auth 走
514
+ # 熔断器,冷却结束就放一次真实探测(实测 opens=18、间隔 ~100s,折合
515
+ # ~866 次无效 403/天);联动后行为与搜索端点对称——冷却期由
516
+ # quota._quota_cooldown_seconds 单点决定(余额类 1h,免费额度类按 period),
517
+ # 充值/换 Key 后随搜索端点一起自愈。fail-open:quota 层读不到就照旧走
518
+ # 熔断器,联动检查不成为新的单点故障。
519
+ try:
520
+ from quota import get_quota_manager
521
+ if get_quota_manager().is_remote_exhausted("bocha"):
522
+ return results, "skipped_quota"
523
+ except Exception:
524
+ pass
525
+
512
526
  # 端点熔断:先问「还该不该打这一枪」。
513
527
  #
514
528
  # 为什么必须记住失败:这是一次**同步阻塞**的网络调用,压在 CPU 后处理链上。
@@ -611,7 +625,6 @@ def _jaccard(a: set[str], b: set[str]) -> float:
611
625
 
612
626
 
613
627
 
614
-
615
628
  def _consensus_prior(results: list[dict[str, Any]]) -> list[float]:
616
629
  """融合先验:把 RRF 分与跨引擎共识数归一化成 [0,1](逐条保持一致 results)。
617
630
 
@@ -635,18 +648,19 @@ def _consensus_prior(results: list[dict[str, Any]]) -> list[float]:
635
648
  priors: list[float] = []
636
649
  raw = [float(r.get("_rrf_score", 0.0) or 0.0) for r in results]
637
650
  peak = max(raw) if raw else 0.0
651
+ from caliber_isolation import caliber_of
638
652
  for r, rrf in zip(results, raw):
639
653
  rrf_norm = (rrf / peak) if peak > 0 else 0.0
640
- cons = len(r.get("consensus_engines") or [])
654
+ cons_engs = r.get("consensus_engines") or []
655
+ cons = len(cons_engs)
641
656
  cons_norm = min(max(cons - 1, 0), 3) / 3.0
642
- # 两个子信号取均值:单纯多引擎重复 != 更可信,RRF 分还含引擎权重
657
+ if cons >= 2 and len({caliber_of(e) for e in cons_engs if e}) >= 2:
658
+ cons_norm = min(1.0, cons_norm + 0.15)
659
+ # 两个子信号取均值:跨口径独立共识额外获 0.15 异质印证增益
643
660
  priors.append(0.5 * rrf_norm + 0.5 * cons_norm)
644
661
  return priors
645
662
 
646
663
 
647
-
648
-
649
-
650
664
  def local_five_dim_rerank(query: str, results: list[dict[str, Any]],
651
665
  domain: str = "general", top_n: int = 10
652
666
  ) -> list[dict[str, Any]]:
@@ -996,5 +1010,6 @@ _RERANK_DEGRADED_STATUSES = frozenset({
996
1010
  "skipped_short", # 结果太少,不值得精排
997
1011
  "skipped_fast", # fast 档不付远程精排
998
1012
  "skipped_circuit_open", # 端点熔断中(见 _RERANK_BREAKER_KEY)
1013
+ "skipped_quota", # 搜索端点已归因配额耗尽,联动跳过(同源同 key)
999
1014
  "fallback", # 端点报错或返回不可用数据
1000
1015
  })
@@ -348,23 +348,14 @@ def filter_content_farms(results: list) -> list:
348
348
 
349
349
  # ── 自适应放宽建议(2026-10-23 方案四)───────────────────────────────────
350
350
 
351
- _RELAX_TAIL_RE = re.compile(
352
- r"(?:\b\d{4}年?(?:度)?|\b\d{1,2}月|"
353
- r"最新|最全|详细|完整|全面|2020|2021|2022|2023|2024|2025|2026|"
354
- r"知乎|贴吧|论坛|大全|汇总|排行榜|一览|数据|报告|统计|分析|趋势)"
355
- )
356
-
357
-
358
351
  def suggest_relaxed_query(query: str) -> str:
359
- """针对 SERP 守卫击杀场景的自适应放宽查询(剥离过度约束的修饰与年份词)。"""
352
+ """针对 SERP 守卫击杀场景的自适应放宽查询(剥离过度约束的修饰与年份词)。
353
+
354
+ 与恢复链 L1 放宽同一口径,直接复用 `recovery.relax_query`:此前这里抄了一份
355
+ 同样的尾修饰正则,两份一起把「GB/T 15834」切成「GB T 4」。
356
+ """
360
357
  if not query or not isinstance(query, str):
361
358
  return ""
362
- q = _RELAX_TAIL_RE.sub(" ", query)
363
- q = re.sub(r"(?<=\s)[年月](?=\s|$)|^([年月]\s+)", " ", q)
364
- tokens = re.findall(r"[\u4e00-\u9fffA-Za-z0-9]+", q)
365
- stopwords = {"的", "了", "呢", "吧", "请问", "怎么", "如何", "一下", "关于", "有关", "求", "谁知道",
366
- "the", "a", "an", "of", "for", "to", "how", "what"}
367
- kept = [t for t in tokens if t.lower() not in stopwords]
368
- relaxed = " ".join(kept).strip()
369
- return relaxed or re.sub(r"\s+", " ", q).strip() or query
359
+ from recovery import relax_query
360
+ return relax_query(query)
370
361