session-pane-retention-heap.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. import assert from "node:assert/strict";
  2. import { readFile } from "node:fs/promises";
  3. import { TraceMap, originalPositionFor, type EncodedSourceMap } from "@jridgewell/trace-mapping";
  4. const prefix = "sess_probe_retention_";
  5. interface HeapSnapshot {
  6. snapshot: {
  7. meta: {
  8. location_fields: string[];
  9. node_fields: string[];
  10. node_types: (string | string[])[];
  11. edge_fields: string[];
  12. edge_types: (string | string[])[];
  13. };
  14. };
  15. locations: number[];
  16. nodes: number[];
  17. edges: number[];
  18. strings: string[];
  19. }
  20. // 依据协议对象形状和测试 session 身份计数,不依赖压缩后的类名、变量名或跨快照 object id。
  21. export async function countRetainedHistory(
  22. path: string,
  23. activeSession: string,
  24. sourceMapPath?: string,
  25. ) {
  26. const heap: HeapSnapshot = JSON.parse(await readFile(path, "utf8"));
  27. const meta = heap.snapshot.meta;
  28. const field = (fields: string[], key: string) => {
  29. const index = fields.indexOf(key);
  30. assert(index >= 0, `Heap schema missing ${key}`);
  31. return index;
  32. };
  33. const nf = {
  34. type: field(meta.node_fields, "type"),
  35. name: field(meta.node_fields, "name"),
  36. edge_count: field(meta.node_fields, "edge_count"),
  37. };
  38. const ef = {
  39. type: field(meta.edge_fields, "type"),
  40. name_or_index: field(meta.edge_fields, "name_or_index"),
  41. to_node: field(meta.edge_fields, "to_node"),
  42. };
  43. const nodeTypes = meta.node_types[nf.type] as string[];
  44. const edgeTypes = meta.edge_types[ef.type] as string[];
  45. const nw = meta.node_fields.length;
  46. const ew = meta.edge_fields.length;
  47. const name = (node: number) => heap.strings[heap.nodes[node + nf.name]!]!;
  48. const edgeStarts = new Uint32Array(heap.nodes.length / nw + 1);
  49. let edge = 0;
  50. let snapshots = 0;
  51. let inactiveSnapshots = 0;
  52. let closedStores = 0;
  53. let liveStores = 0;
  54. let inactivePrewarmCoordinators = 0;
  55. const bySession: Record<string, number> = {};
  56. for (let node = 0; node < heap.nodes.length; node += nw) {
  57. edgeStarts[node / nw] = edge;
  58. const end = edge + heap.nodes[node + nf.edge_count]! * ew;
  59. if (nodeTypes[heap.nodes[node + nf.type]!] === "object") {
  60. const props: Record<string, number> = {};
  61. for (let pos = edge; pos < end; pos += ew) {
  62. if (edgeTypes[heap.edges[pos + ef.type]!] !== "property") continue;
  63. props[heap.strings[heap.edges[pos + ef.name_or_index]!]!] = heap.edges[pos + ef.to_node]!;
  64. }
  65. if (
  66. props.protocolVersion !== undefined &&
  67. props.rows !== undefined &&
  68. props.logEpoch !== undefined &&
  69. props.sessionId !== undefined &&
  70. name(props.sessionId).startsWith(prefix)
  71. ) {
  72. const session = name(props.sessionId);
  73. snapshots++;
  74. bySession[session] = (bySession[session] ?? 0) + 1;
  75. if (session !== activeSession) inactiveSnapshots++;
  76. }
  77. if (
  78. props.subscribers !== undefined &&
  79. props.dispatchCommand !== undefined &&
  80. props.blockedInvalidationVersion !== undefined &&
  81. props.current !== undefined &&
  82. props.cleanupTimer !== undefined &&
  83. props.retryTimer !== undefined &&
  84. name(props.current) === "null" &&
  85. name(props.cleanupTimer) === "null" &&
  86. name(props.retryTimer) === "null"
  87. ) {
  88. // 正常在途创建与页面保活都有 current;收口后仍在堆中的空闲 owner 是本次泄漏特征。
  89. inactivePrewarmCoordinators++;
  90. }
  91. if (
  92. props.topic !== undefined &&
  93. props.state !== undefined &&
  94. props.transport !== undefined &&
  95. props.generation !== undefined &&
  96. props.closed !== undefined &&
  97. name(props.topic).includes(`/${prefix}`)
  98. ) {
  99. if (name(props.closed) === "true") closedStores++;
  100. else liveStores++;
  101. }
  102. }
  103. edge = end;
  104. }
  105. edgeStarts[heap.nodes.length / nw] = edge;
  106. const callbacks = sourceMapPath
  107. ? countCallbacks(heap, edgeStarts, JSON.parse(await readFile(sourceMapPath, "utf8")))
  108. : null;
  109. return {
  110. callbacks,
  111. snapshots,
  112. inactiveSnapshots,
  113. closedStores,
  114. liveStores,
  115. inactivePrewarmCoordinators,
  116. bySession,
  117. };
  118. }
  119. // 函数由精确构建 sourcemap + SharedFunctionInfo 识别;不比较跨快照 object id 或压缩变量名。
  120. function countCallbacks(heap: HeapSnapshot, edgeStarts: Uint32Array, sourceMap: EncodedSourceMap) {
  121. const { meta } = heap.snapshot;
  122. const nw = meta.node_fields.length,
  123. ew = meta.edge_fields.length;
  124. const nt = meta.node_fields.indexOf("type"),
  125. nn = meta.node_fields.indexOf("name");
  126. const et = meta.edge_fields.indexOf("type"),
  127. en = meta.edge_fields.indexOf("name_or_index"),
  128. to = meta.edge_fields.indexOf("to_node");
  129. const nodeTypes = meta.node_types[nt] as string[],
  130. edgeTypes = meta.edge_types[et] as string[];
  131. const type = (node: number) => nodeTypes[heap.nodes[node + nt]!];
  132. const name = (node: number) => heap.strings[heap.nodes[node + nn]!]!;
  133. const props = (node: number) => {
  134. const result: Record<string, number> = {};
  135. for (let e = edgeStarts[node / nw]!; e < edgeStarts[node / nw + 1]!; e += ew) {
  136. const key =
  137. edgeTypes[heap.edges[e + et]!] === "element"
  138. ? String(heap.edges[e + en])
  139. : heap.strings[heap.edges[e + en]!]!;
  140. result[key] = heap.edges[e + to]!;
  141. }
  142. return result;
  143. };
  144. const focus = new Set<number>(),
  145. lexicalUpdateListeners: number[] = [];
  146. for (let node = 0; node < heap.nodes.length; node += nw) {
  147. if (type(node) === "native" && name(node).includes('data-testid="v4-composer-input"')) {
  148. const p = props(node),
  149. key = Object.keys(p).find((key) => key.startsWith("__reactProps"));
  150. const callback = key ? props(p[key]!).onFocus : undefined;
  151. if (callback !== undefined) focus.add(callback);
  152. }
  153. if (type(node) !== "object") continue;
  154. const p = props(node);
  155. if (
  156. !["_listeners", "_editorState", "_rootElement", "_commands", "_key"].every(
  157. (key) => p[key] !== undefined,
  158. )
  159. )
  160. continue;
  161. const update = props(p._listeners!).update;
  162. assert(update !== undefined, "Lexical update Set 缺失");
  163. const table = props(update).table;
  164. assert(table !== undefined, "Lexical update Set table 缺失");
  165. lexicalUpdateListeners.push(
  166. new Set(Object.values(props(table)).filter((entry) => type(entry) === "closure")).size,
  167. );
  168. }
  169. assert.equal(focus.size, 1, "必须找到当前真实 Composer onFocus");
  170. assert(lexicalUpdateListeners.length > 0, "必须找到真实 Lexical editor,不能把未识别当成零残留");
  171. const fields = meta.location_fields;
  172. const locations = new Map<number, { line: number; column: number; scriptId: number }>();
  173. for (let pos = 0; pos < heap.locations.length; pos += fields.length)
  174. locations.set(heap.locations[pos + fields.indexOf("object_index")]!, {
  175. line: heap.locations[pos + fields.indexOf("line")]! + 1,
  176. column: heap.locations[pos + fields.indexOf("column")]!,
  177. scriptId: heap.locations[pos + fields.indexOf("script_id")]!,
  178. });
  179. const scriptId = locations.get([...focus][0]!)?.scriptId;
  180. assert(scriptId !== undefined, "onFocus 缺少构建位置");
  181. const map = new TraceMap(sourceMap);
  182. const families: Record<string, Set<number>> = {
  183. onFocus: new Set([...focus].map((node) => props(node).shared!)),
  184. fileLink: new Set(),
  185. prewarmWaiter: new Set(),
  186. };
  187. const lines = (suffix: string) => {
  188. const index = map.sources.findIndex((source) => source?.endsWith(suffix));
  189. const content = map.sourcesContent?.[index];
  190. assert(content, `sourcemap 缺少 ${suffix}`);
  191. return content.split("\n");
  192. };
  193. const fileLinkLine =
  194. lines("/WorkspaceShellLayout.tsx").findIndex((line) =>
  195. line.includes("const handleOpenMarkdownFileLink = useCallback("),
  196. ) + 2;
  197. const prewarmLines = lines("/useDraftSessionPrewarm.ts");
  198. const waiterLine =
  199. prewarmLines.findIndex(
  200. (line) =>
  201. line.includes("return async () => {") ||
  202. line.includes("const waitForSession = useCallback(async () => {"),
  203. ) + 1;
  204. assert(fileLinkLine > 1 && waiterLine > 0, "回调源码定位失败");
  205. for (const [node, location] of locations) {
  206. if (type(node) !== "closure" || location.scriptId !== scriptId) continue;
  207. const original = originalPositionFor(map, location);
  208. if (original.source?.endsWith("/WorkspaceShellLayout.tsx") && original.line === fileLinkLine)
  209. families.fileLink!.add(props(node).shared!);
  210. if (original.source?.endsWith("/useDraftSessionPrewarm.ts") && original.line === waiterLine)
  211. families.prewarmWaiter!.add(props(node).shared!);
  212. }
  213. const counts: Record<string, number> = {};
  214. for (const [key, shared] of Object.entries(families)) {
  215. assert(shared.size > 0, `${key} 未匹配到真实回调`);
  216. counts[key] = 0;
  217. for (let node = 0; node < heap.nodes.length; node += nw)
  218. if (type(node) === "closure" && shared.has(props(node).shared!)) counts[key]++;
  219. }
  220. return {
  221. onFocus: counts.onFocus!,
  222. fileLink: counts.fileLink!,
  223. prewarmWaiter: counts.prewarmWaiter!,
  224. lexicalUpdateListeners,
  225. };
  226. }