processResourceCliSource.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. import { beforeEach, afterEach, describe, expect, it, vi } from "vitest";
  2. import {
  3. cliProcessResourceSampleSource,
  4. ingestCliResourceSample,
  5. } from "@desktop/main/processResourceCliSource";
  6. import { PROCESS_RESOURCE_SAMPLE_SOURCES } from "@desktop/main/processResourceSampleSourceRegistry";
  7. import {
  8. collectExternalAppResourceTotals,
  9. recordExternalAppResourceSample,
  10. resetExternalAppResourceSamples,
  11. } from "@desktop/main/processResourceExternalAppSamples";
  12. import type { ProcessRoleSample } from "@desktop/main/processResourceWindowAggregator";
  13. import { ZCODE_CLI_RESOURCE_SAMPLE_INTERVAL_MS } from "@zcode/shared";
  14. const CLI_PERIOD_MS = ZCODE_CLI_RESOURCE_SAMPLE_INTERVAL_MS;
  15. function cliSample(overrides: Record<string, unknown> = {}): Record<string, unknown> {
  16. return {
  17. platform: "darwin",
  18. arch: "arm64",
  19. logicalCpuCount: 10,
  20. intervalMs: CLI_PERIOD_MS,
  21. cpuCores: 0.5,
  22. cpuPercent: 5,
  23. rssKb: 200_000,
  24. heapUsedKb: 40_000,
  25. uptimeMinutes: 8,
  26. totalMemoryGb: 32,
  27. instanceToken: "chat-instance-0001",
  28. lane: "chat",
  29. ...overrides,
  30. };
  31. }
  32. /**
  33. * ingest 用 `Date.now()` 记到达时刻、tick 用 `context.now`,生产里两者是同一墙钟,
  34. * 因此测试必须让假时钟同时驱动两边,否则「有没有新读数」的判定会被时钟错位掩盖。
  35. */
  36. function ingestAt(
  37. now: number,
  38. sample: unknown,
  39. runtimeSurface: "local" | "remote" = "local",
  40. ): void {
  41. vi.setSystemTime(now);
  42. ingestCliResourceSample(sample, runtimeSurface);
  43. }
  44. function collect(
  45. run: (context: Parameters<NonNullable<typeof cliProcessResourceSampleSource.sample>>[0]) => void,
  46. now: number,
  47. ): ProcessRoleSample[] {
  48. vi.setSystemTime(now);
  49. const samples: ProcessRoleSample[] = [];
  50. run({
  51. now,
  52. addRoleSample: (sample) => samples.push(sample),
  53. addRoleHeapSample: () => {},
  54. addAppProcessTotals: () => {},
  55. });
  56. return samples;
  57. }
  58. /** main 的 10 秒 tick。 */
  59. function tickAt(now = 0): ProcessRoleSample[] {
  60. return collect((context) => cliProcessResourceSampleSource.sample?.(context), now);
  61. }
  62. /** 正常退出时的残窗补交。 */
  63. function flushAt(now = 0): ProcessRoleSample[] {
  64. return collect((context) => cliProcessResourceSampleSource.flushPending?.(context), now);
  65. }
  66. describe("processResourceCliSource", () => {
  67. beforeEach(() => {
  68. vi.useFakeTimers();
  69. vi.setSystemTime(0);
  70. cliProcessResourceSampleSource.reset?.();
  71. resetExternalAppResourceSamples();
  72. });
  73. afterEach(() => {
  74. vi.useRealTimers();
  75. });
  76. it("PRT-007 chat lane 的两个进程聚合为 cli_chat,plugin lane 归 cli_aux", () => {
  77. ingestAt(0, cliSample({ instanceToken: "chat-instance-0001", cpuPercent: 5, rssKb: 200_000 }));
  78. ingestAt(
  79. 0,
  80. cliSample({
  81. instanceToken: "chat-instance-0002",
  82. cpuPercent: 7,
  83. rssKb: 300_000,
  84. heapUsedKb: 90_000,
  85. uptimeMinutes: 12,
  86. }),
  87. );
  88. ingestAt(
  89. 0,
  90. cliSample({
  91. lane: "plugin",
  92. instanceToken: "aux-instance-0001",
  93. cpuPercent: 1,
  94. rssKb: 90_000,
  95. }),
  96. );
  97. expect(tickAt()).toEqual([
  98. {
  99. role: "cli_chat",
  100. runtimeSurface: "local",
  101. cpuPercent: 12,
  102. rssKbTotal: 500_000,
  103. rssKbMaxProcess: 300_000,
  104. processCount: 2,
  105. uptimeMinutes: 12,
  106. // 多进程角色的 heap 取每次采样的最大单进程。
  107. heapUsedKb: 90_000,
  108. hardware: { platform: "darwin", arch: "arm64", logicalCpuCount: 10, totalMemoryGb: 32 },
  109. },
  110. {
  111. role: "cli_aux",
  112. runtimeSurface: "local",
  113. cpuPercent: 1,
  114. rssKbTotal: 90_000,
  115. rssKbMaxProcess: 90_000,
  116. processCount: 1,
  117. uptimeMinutes: 8,
  118. heapUsedKb: 40_000,
  119. hardware: { platform: "darwin", arch: "arm64", logicalCpuCount: 10, totalMemoryGb: 32 },
  120. },
  121. ]);
  122. });
  123. it("mcp-status lane 与 plugin 合并进同一条 cli_aux", () => {
  124. ingestAt(
  125. 0,
  126. cliSample({ lane: "mcp-status", instanceToken: "aux-mcp-status-01", rssKb: 100_000 }),
  127. );
  128. ingestAt(0, cliSample({ lane: "plugin", instanceToken: "aux-plugin-01", rssKb: 150_000 }));
  129. const samples = tickAt();
  130. expect(samples).toHaveLength(1);
  131. expect(samples[0]).toMatchObject({
  132. role: "cli_aux",
  133. processCount: 2,
  134. rssKbTotal: 250_000,
  135. rssKbMaxProcess: 150_000,
  136. });
  137. });
  138. it("PRT-008 远端样本自带运行机信息,且不进入设备级应用总量", () => {
  139. ingestAt(
  140. 0,
  141. cliSample({
  142. platform: "linux",
  143. arch: "x64",
  144. logicalCpuCount: 4,
  145. totalMemoryGb: 8,
  146. instanceToken: "remote-instance-01",
  147. }),
  148. "remote",
  149. );
  150. expect(tickAt()).toEqual([
  151. expect.objectContaining({
  152. role: "cli_chat",
  153. runtimeSurface: "remote",
  154. hardware: { platform: "linux", arch: "x64", logicalCpuCount: 4, totalMemoryGb: 8 },
  155. }),
  156. ]);
  157. // 设备级总量只统计本机进程。
  158. expect(collectExternalAppResourceTotals(0)).toEqual({
  159. cpuPercent: 0,
  160. rssKbTotal: 0,
  161. processCount: 0,
  162. });
  163. });
  164. it("跑在两台不同远端机器上的同角色进程分成两条样本,RSS 不相加", () => {
  165. ingestAt(
  166. 0,
  167. cliSample({
  168. platform: "linux",
  169. arch: "x64",
  170. logicalCpuCount: 4,
  171. totalMemoryGb: 8,
  172. instanceToken: "remote-host-a",
  173. rssKb: 100_000,
  174. }),
  175. "remote",
  176. );
  177. ingestAt(
  178. 0,
  179. cliSample({
  180. platform: "linux",
  181. arch: "arm64",
  182. logicalCpuCount: 16,
  183. totalMemoryGb: 64,
  184. instanceToken: "remote-host-b",
  185. rssKb: 900_000,
  186. }),
  187. "remote",
  188. );
  189. // 一条事件的 platform / arch / 核数 / 内存只能描述一台机器,因此按运行机分组。
  190. const samples = tickAt();
  191. expect(samples).toHaveLength(2);
  192. expect(samples.map((sample) => sample.rssKbTotal)).toEqual([100_000, 900_000]);
  193. expect(samples.map((sample) => sample.hardware?.logicalCpuCount)).toEqual([4, 16]);
  194. expect(samples.every((sample) => sample.processCount === 1)).toBe(true);
  195. });
  196. it("本机样本按角色喂进设备级应用总量的外部样本入口", () => {
  197. ingestAt(0, cliSample({ instanceToken: "chat-instance-0001" }));
  198. ingestAt(
  199. 0,
  200. cliSample({
  201. lane: "plugin",
  202. instanceToken: "aux-instance-0001",
  203. cpuPercent: 1,
  204. rssKb: 90_000,
  205. }),
  206. );
  207. tickAt();
  208. expect(collectExternalAppResourceTotals(0)).toEqual({
  209. cpuPercent: 6,
  210. rssKbTotal: 290_000,
  211. processCount: 2,
  212. });
  213. });
  214. it("每 60 秒最多交一次,且只在有新读数时交,同一份读数不会被计入两次", () => {
  215. ingestAt(0, cliSample());
  216. expect(tickAt(0)).toHaveLength(1);
  217. expect(tickAt(10_000)).toHaveLength(0);
  218. // 60 秒到了,但 CLI 没有新读数(进程卡住或即将退出):不能把同一份事实再计一次。
  219. expect(tickAt(CLI_PERIOD_MS)).toHaveLength(0);
  220. ingestAt(CLI_PERIOD_MS, cliSample({ rssKb: 260_000 }));
  221. expect(tickAt(CLI_PERIOD_MS + 10_000)[0]).toMatchObject({ rssKbTotal: 260_000 });
  222. });
  223. it("正常退出时把还没赶上 60 秒交付点的读数补交给窗口", () => {
  224. ingestAt(0, cliSample());
  225. expect(tickAt(0)).toHaveLength(1);
  226. // 退出发生在下一个交付点之前:这条读数只有 flushPending 能救回来。
  227. ingestAt(30_000, cliSample({ rssKb: 280_000 }));
  228. expect(tickAt(40_000)).toHaveLength(0);
  229. expect(flushAt(40_000)[0]).toMatchObject({ role: "cli_chat", rssKbTotal: 280_000 });
  230. // 已经交过的读数不会被重复排空。
  231. expect(flushAt(41_000)).toEqual([]);
  232. });
  233. it("同一进程的新读数覆盖旧读数,超过两个采样周期未更新的进程不再计入", () => {
  234. ingestAt(0, cliSample({ rssKb: 200_000 }));
  235. expect(tickAt(0)[0]).toMatchObject({ rssKbTotal: 200_000, processCount: 1 });
  236. ingestAt(CLI_PERIOD_MS, cliSample({ rssKb: 260_000 }));
  237. expect(tickAt(CLI_PERIOD_MS)[0]).toMatchObject({ rssKbTotal: 260_000, processCount: 1 });
  238. // 进程退出后不再有新读数:刚过两个采样周期条目就被丢弃,不拿旧值充当当前事实。
  239. expect(tickAt(CLI_PERIOD_MS * 3 + 1)).toEqual([]);
  240. expect(flushAt(CLI_PERIOD_MS * 3 + 1)).toEqual([]);
  241. });
  242. it("非法样本在 main 入口被丢弃且不抛错", () => {
  243. for (const invalid of [
  244. undefined,
  245. null,
  246. "sample",
  247. {},
  248. cliSample({ lane: "unknown-lane" }),
  249. cliSample({ instanceToken: "/Users/somebody/repo" }),
  250. cliSample({ cpuPercent: Number.NaN }),
  251. { ...cliSample(), pid: 4_321 },
  252. { ...cliSample(), workspacePath: "/Users/somebody/repo" },
  253. ]) {
  254. expect(() => ingestCliResourceSample(invalid, "local")).not.toThrow();
  255. }
  256. expect(tickAt()).toEqual([]);
  257. });
  258. it("旧 CLI 的样本没有新字段也能聚合,heap 与运行时长缺省不进事件", () => {
  259. ingestAt(0, {
  260. platform: "darwin",
  261. arch: "arm64",
  262. logicalCpuCount: 10,
  263. intervalMs: CLI_PERIOD_MS,
  264. cpuCores: 0.5,
  265. cpuPercent: 5,
  266. rssKb: 200_000,
  267. });
  268. expect(tickAt()).toEqual([
  269. {
  270. // 无 lane 的样本按 chat 归属:唯一来源是版本落后、还没打标的远端 server。
  271. role: "cli_chat",
  272. runtimeSurface: "local",
  273. cpuPercent: 5,
  274. rssKbTotal: 200_000,
  275. rssKbMaxProcess: 200_000,
  276. // 无 instanceToken 时无法区分进程,只能按一个进程计。
  277. processCount: 1,
  278. uptimeMinutes: 0,
  279. hardware: { platform: "darwin", arch: "arm64", logicalCpuCount: 10 },
  280. },
  281. ]);
  282. });
  283. it("reset 丢弃尚未交出的样本", () => {
  284. ingestAt(0, cliSample());
  285. cliProcessResourceSampleSource.reset?.();
  286. expect(tickAt()).toEqual([]);
  287. });
  288. it("PRT-033 本机 aux 停更后不被 chat 新读数重复交付或续期", () => {
  289. ingestAt(0, cliSample({ lane: "plugin", instanceToken: "aux-stopped-01", rssKb: 250_000 }));
  290. expect(tickAt(0)).toHaveLength(1);
  291. for (const now of [60_000, 120_000]) {
  292. ingestAt(now, cliSample({ instanceToken: "chat-active-01", rssKb: 400_000 }));
  293. expect(tickAt(now).map((sample) => sample.role)).toEqual(["cli_chat"]);
  294. }
  295. expect(tickAt(120_001)).toEqual([]);
  296. expect(collectExternalAppResourceTotals(120_001)).toMatchObject({
  297. rssKbTotal: 400_000,
  298. processCount: 1,
  299. });
  300. ingestAt(130_000, cliSample({ instanceToken: "chat-active-01", rssKb: 420_000 }));
  301. expect(flushAt(130_000).map((sample) => sample.role)).toEqual(["cli_chat"]);
  302. expect(flushAt(130_001)).toEqual([]);
  303. });
  304. it("PRT-033 错相位两组在五个周期中各交付五次", () => {
  305. const delivered: ProcessRoleSample[] = [];
  306. for (let now = 0; now <= 300_000; now += 10_000) {
  307. if (now < 300_000 && now % 60_000 === 0)
  308. ingestAt(now, cliSample({ instanceToken: "chat-active-01" }));
  309. if (now % 60_000 === 30_000)
  310. ingestAt(now, cliSample({ instanceToken: "aux-active-01", lane: "plugin" }));
  311. delivered.push(...tickAt(now));
  312. }
  313. expect(delivered.filter((sample) => sample.role === "cli_chat")).toHaveLength(5);
  314. expect(delivered.filter((sample) => sample.role === "cli_aux")).toHaveLength(5);
  315. });
  316. it("PRT-033 同组某实例到期后立即退出设备总量,不等另一个实例下次交付", () => {
  317. ingestAt(0, cliSample({ instanceToken: "chat-stopped-01", rssKb: 250_000 }));
  318. ingestAt(0, cliSample({ instanceToken: "chat-active-01", rssKb: 400_000 }));
  319. tickAt(0);
  320. for (const now of [60_000, 120_000]) {
  321. ingestAt(now, cliSample({ instanceToken: "chat-active-01", rssKb: 400_000 }));
  322. tickAt(now);
  323. }
  324. expect(collectExternalAppResourceTotals(120_000).processCount).toBe(2);
  325. tickAt(120_001);
  326. expect(collectExternalAppResourceTotals(120_001)).toMatchObject({
  327. rssKbTotal: 400_000,
  328. processCount: 1,
  329. });
  330. });
  331. it("PRT-033 按实例保存 CLI 后仍保留 MCP 来源的预算", () => {
  332. for (let index = 0; index < 64; index++) {
  333. ingestAt(0, cliSample({ instanceToken: `chat-instance-${index}` }));
  334. }
  335. for (let index = 0; index < 32; index++) {
  336. recordExternalAppResourceSample({
  337. sourceKey: `mcp:${index}`,
  338. runtimeSurface: "local",
  339. cpuPercent: 0,
  340. rssKbTotal: 1000,
  341. processCount: 1,
  342. receivedAt: 0,
  343. intervalMs: 300_000,
  344. });
  345. }
  346. expect(collectExternalAppResourceTotals(0).processCount).toBe(96);
  347. });
  348. it("PRT-034 同硬件不同环境与相同实例标识仍隔离,同环境重复转发只计一次", () => {
  349. const raw = cliSample({ cpuPercent: 80, rssKb: 500_000 });
  350. const environmentA = "a".repeat(64);
  351. const environmentB = "b".repeat(64);
  352. ingestCliResourceSample(raw, "remote", environmentA);
  353. ingestCliResourceSample(raw, "remote", environmentB);
  354. ingestCliResourceSample(raw, "remote", environmentA);
  355. const samples = tickAt();
  356. expect(samples).toHaveLength(2);
  357. expect(samples.map((sample) => sample.environmentKey)).toEqual([environmentA, environmentB]);
  358. expect(
  359. samples.every(
  360. (sample) =>
  361. sample.cpuPercent === 80 && sample.rssKbTotal === 500_000 && sample.processCount === 1,
  362. ),
  363. ).toBe(true);
  364. expect(collectExternalAppResourceTotals(0).processCount).toBe(0);
  365. });
  366. it("已注册进来源注册表", () => {
  367. expect(PROCESS_RESOURCE_SAMPLE_SOURCES.map((source) => source.id)).toContain(
  368. cliProcessResourceSampleSource.id,
  369. );
  370. });
  371. });