evaluate.mjs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. // Run from the repository root: pnpm exec tsx apps/zcode-cli/packages/bootstrap/tests/data/plugin-discovery-search/evaluate.mjs [--performance]
  2. import assert from "node:assert/strict";
  3. import { readFile } from "node:fs/promises";
  4. import { rankVisiblePlugins, searchPluginCatalog } from "../../../src/plugin-discovery/search.ts";
  5. const read = (name) => readFile(new URL(name, import.meta.url), "utf8");
  6. const { listings, sourceSha256 } = JSON.parse(await read("catalog.json"));
  7. const catalog = listings.map((entry) => ({
  8. ...entry,
  9. pluginId: entry.name + "@zcode-plugins-official",
  10. installed: false,
  11. enabled: false,
  12. action: "install",
  13. scope: "user",
  14. }));
  15. const normalize = (v) => v.normalize("NFKC").toLocaleLowerCase("en-US");
  16. const labels = (await read("queries.tsv"))
  17. .trimEnd()
  18. .split("\n")
  19. .filter((line) => !line.startsWith("#"))
  20. .map((line) => {
  21. const [split, query, ids, weak] = line.split("\t");
  22. const gold = ids.split(",");
  23. for (const name of gold)
  24. assert.ok(
  25. catalog.some((p) => p.name === name),
  26. name,
  27. );
  28. return { split, query, gold, weak };
  29. });
  30. assert.equal(new Set(labels.map((r) => r.query)).size, labels.length);
  31. assert.equal(labels.length >= 60, true);
  32. const tune = labels.filter((r) => r.split === "tune");
  33. const holdout = labels.filter((r) => r.split === "holdout");
  34. assert.equal(tune.length + holdout.length, labels.length);
  35. // !2855 原 4:1 子串规则;对同一批可见条目排序。
  36. function baseline(query) {
  37. const words = normalize(query)
  38. .split(/[\s,,;;]+/u)
  39. .filter(Boolean);
  40. return catalog
  41. .map((p) => {
  42. const names = normalize(
  43. [p.pluginId, p.name, p.displayName, ...Object.values(p.displayNameI18n ?? {})].join(" "),
  44. );
  45. const detail = normalize(
  46. [
  47. p.description,
  48. p.category,
  49. ...Object.values(p.descriptionI18n ?? {}),
  50. ...(p.examplePrompts ?? []),
  51. ].join(" "),
  52. );
  53. const score = words.reduce(
  54. (sum, w) => sum + (names.includes(w) ? 4 : 0) + (detail.includes(w) ? 1 : 0),
  55. 0,
  56. );
  57. return { p, score };
  58. })
  59. .filter((x) => x.score > 0)
  60. .sort((a, b) => b.score - a.score || a.p.pluginId.localeCompare(b.p.pluginId))
  61. .slice(0, 10)
  62. .map((x) => x.p.name);
  63. }
  64. const production = (query) =>
  65. searchPluginCatalog(catalog, { query }, false).plugins.map((p) => p.name);
  66. function measure(rows, search) {
  67. let recall = 0,
  68. ndcg = 0;
  69. for (const { query, gold } of rows) {
  70. const top = search(query);
  71. const relevant = top.map((name) => gold.includes(name));
  72. const gain = (rank) => 1 / Math.log2(rank + 2);
  73. recall += relevant.filter(Boolean).length / gold.length;
  74. ndcg +=
  75. relevant.reduce((s, hit, rank) => s + (hit ? gain(rank) : 0), 0) /
  76. gold.slice(0, 10).reduce((s, _id, rank) => s + gain(rank), 0);
  77. }
  78. return { recall: recall / rows.length, ndcg: ndcg / rows.length };
  79. }
  80. const report = {
  81. sourceSha256,
  82. count: catalog.length,
  83. tuneCount: tune.length,
  84. holdoutCount: holdout.length,
  85. };
  86. if (process.argv.includes("--performance")) {
  87. const durations = {};
  88. for (const [n, samples] of [
  89. [catalog.length, 100],
  90. [1_000, 40],
  91. [10_000, 20],
  92. ]) {
  93. // 按真实条目的长度与语言分布扩容;ID 保持唯一。
  94. const synthetic =
  95. n === catalog.length
  96. ? catalog
  97. : Array.from({ length: n }, (_, i) => ({
  98. ...catalog[i % catalog.length],
  99. pluginId: `sample-${i}@zcode-plugins-official`,
  100. }));
  101. const queries = [
  102. "CLI",
  103. "cloud resource profile",
  104. "企业信息查询",
  105. "收件箱",
  106. "编辑 PDF",
  107. "Jupyter Notebook",
  108. "浏览器操作",
  109. "创建工具",
  110. ];
  111. for (let i = -8; i < samples; i++) {
  112. const query = queries[(i + 8) % queries.length];
  113. const start = performance.now();
  114. searchPluginCatalog(synthetic, { query }, false);
  115. const ms = performance.now() - start;
  116. if (i >= 0) (durations[n] ??= []).push(ms);
  117. }
  118. }
  119. report.timings = Object.fromEntries(
  120. Object.entries(durations).map(([n, d]) => {
  121. d.sort((a, b) => a - b);
  122. return [
  123. n,
  124. {
  125. samples: d.length,
  126. p50: d[Math.ceil(0.5 * d.length) - 1],
  127. p95: d[Math.ceil(0.95 * d.length) - 1],
  128. },
  129. ];
  130. }),
  131. );
  132. console.log(JSON.stringify(report, null, 2));
  133. assert.ok(report.timings[catalog.length].p95 <= 50, "real catalog p95 > 50 ms");
  134. } else {
  135. // 只在调参集比较敏感性;产品参数由规格冻结,留出集只评一次,不回调参数。
  136. report.tuneGrid = [
  137. { nameWeight: 4, k1: 1.2, detailB: 0.75 },
  138. { nameWeight: 2, k1: 1.2, detailB: 0.75 },
  139. { nameWeight: 6, k1: 1.2, detailB: 0.75 },
  140. { nameWeight: 4, k1: 0.8, detailB: 0.5 },
  141. { nameWeight: 4, k1: 1.6, detailB: 0.9 },
  142. ].map((params) => ({
  143. ...params,
  144. ...measure(tune, (query) =>
  145. rankVisiblePlugins(catalog, normalize(query).trim(), params)
  146. .slice(0, 10)
  147. .map((p) => p.name),
  148. ),
  149. }));
  150. report.quality = {};
  151. for (const [split, rows] of [
  152. ["tune", tune],
  153. ["holdout", holdout],
  154. ["weak", holdout.filter((x) => x.weak)],
  155. ]) {
  156. report.quality[split] = { baseline: measure(rows, baseline), bm25: measure(rows, production) };
  157. }
  158. report.weak = holdout
  159. .filter((row) => row.weak)
  160. .map(({ query, gold }) => ({
  161. query,
  162. gold,
  163. before: baseline(query).findIndex((name) => gold.includes(name)) + 1 || null,
  164. after: production(query).findIndex((name) => gold.includes(name)) + 1 || null,
  165. }));
  166. console.log(JSON.stringify(report, null, 2));
  167. const h = report.quality.holdout,
  168. w = report.quality.weak;
  169. assert.ok(h.bm25.recall >= h.baseline.recall && h.bm25.ndcg >= h.baseline.ndcg);
  170. assert.ok(w.bm25.ndcg > w.baseline.ndcg);
  171. }