bash-resource-telemetry.test.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import { zcodeToolExecResourceSchema } from "@zcode/shared";
  3. import { createBashResourceTelemetry } from "../src/exec/bash-resource-telemetry.js";
  4. import { createProcessProbe } from "../src/device/process-probe.js";
  5. afterEach(() => vi.useRealTimers());
  6. describe("Bash 慢命令采样", () => {
  7. it("相同指标的不同命令各有完成标识,同一命令重复 finish 只发一次", async () => {
  8. vi.useFakeTimers();
  9. const onComplete = vi.fn();
  10. const options = {
  11. platform: "win32" as const,
  12. onComplete,
  13. readContext: () => ({ cliRssKb: 1024, systemFreeMemoryKb: 2048 }),
  14. };
  15. const first = createBashResourceTelemetry(options);
  16. const second = createBashResourceTelemetry(options);
  17. await vi.advanceTimersByTimeAsync(40_000);
  18. first.finish("completed");
  19. first.finish("killed");
  20. second.finish("completed");
  21. expect(onComplete).toHaveBeenCalledTimes(2);
  22. const firstSample = onComplete.mock.calls[0]?.[0];
  23. const secondSample = onComplete.mock.calls[1]?.[0];
  24. expect(firstSample).toMatchObject({ completionToken: expect.any(String) });
  25. expect(secondSample).toMatchObject({ completionToken: expect.any(String) });
  26. expect(zcodeToolExecResourceSchema.parse(firstSample)).toEqual(firstSample);
  27. expect(zcodeToolExecResourceSchema.parse(secondSample)).toEqual(secondSample);
  28. expect(firstSample.completionToken).not.toBe(secondSample.completionToken);
  29. expect({ ...firstSample, completionToken: undefined }).toEqual({
  30. ...secondSample,
  31. completionToken: undefined,
  32. });
  33. });
  34. it("错相位命令不提前采样,共享 tick 不补采积压", async () => {
  35. vi.useFakeTimers();
  36. const probe = { sampleProcessGroup: vi.fn().mockResolvedValue([{ pid: 10, rssKb: 100 }]) };
  37. const first = createBashResourceTelemetry({
  38. platform: "linux",
  39. processGroupId: 10,
  40. probe,
  41. onComplete: vi.fn(),
  42. });
  43. await vi.advanceTimersByTimeAsync(500);
  44. const second = createBashResourceTelemetry({
  45. platform: "linux",
  46. processGroupId: 20,
  47. probe,
  48. onComplete: vi.fn(),
  49. });
  50. expect(vi.getTimerCount()).toBe(1);
  51. await vi.advanceTimersByTimeAsync(14500);
  52. expect(probe.sampleProcessGroup.mock.calls).toEqual([[10]]);
  53. await vi.advanceTimersByTimeAsync(1000);
  54. expect(probe.sampleProcessGroup.mock.calls).toEqual([[10], [20]]);
  55. await vi.advanceTimersByTimeAsync(14000);
  56. expect(probe.sampleProcessGroup.mock.calls).toEqual([[10], [20], [10]]);
  57. await vi.advanceTimersByTimeAsync(1000);
  58. expect(probe.sampleProcessGroup.mock.calls).toEqual([[10], [20], [10], [20]]);
  59. first.finish("completed");
  60. second.finish("completed");
  61. expect(vi.getTimerCount()).toBe(0);
  62. });
  63. it("多条 Bash 共用既有轮询器,短命令退出不会重置其他命令的采样节拍", async () => {
  64. vi.useFakeTimers();
  65. const sampleProcessGroup = vi.fn().mockResolvedValue([{ pid: 10, rssKb: 100 }]);
  66. const options = {
  67. platform: "linux" as const,
  68. processGroupId: 10,
  69. probe: { sampleProcessGroup },
  70. onComplete: vi.fn(),
  71. };
  72. const first = createBashResourceTelemetry(options);
  73. const second = createBashResourceTelemetry(options);
  74. expect(vi.getTimerCount()).toBe(1);
  75. await vi.advanceTimersByTimeAsync(5000);
  76. first.finish("completed");
  77. await vi.advanceTimersByTimeAsync(25000);
  78. expect(sampleProcessGroup).toHaveBeenCalledTimes(2);
  79. second.finish("completed");
  80. expect(vi.getTimerCount()).toBe(0);
  81. });
  82. it("PRT-012: Windows 无定时探针,40 秒结束只带零成本属性", async () => {
  83. vi.useFakeTimers();
  84. const execFile = vi.fn();
  85. const onComplete = vi.fn();
  86. const sampler = createBashResourceTelemetry({
  87. platform: "win32",
  88. processGroupId: 123,
  89. probe: createProcessProbe({ platform: "win32", execFile }),
  90. onComplete,
  91. });
  92. expect(vi.getTimerCount()).toBe(0);
  93. await vi.advanceTimersByTimeAsync(40000);
  94. sampler.finish("completed");
  95. expect(execFile).not.toHaveBeenCalled();
  96. expect(onComplete).toHaveBeenCalledExactlyOnceWith({
  97. completionToken: expect.any(String),
  98. platform: "win32",
  99. toolName: "bash",
  100. durationMs: 40000,
  101. exitKind: "completed",
  102. sampleCount: 0,
  103. cliRssKb: expect.any(Number),
  104. systemFreeMemoryKb: expect.any(Number),
  105. });
  106. });
  107. it("最多尝试 20 次,长命令仍在结束时报告且计时器释放", async () => {
  108. vi.useFakeTimers();
  109. const sampleProcessGroup = vi.fn().mockResolvedValue([{ pid: 10, rssKb: 100, cpuTimeMs: 200 }]);
  110. const onComplete = vi.fn();
  111. const sampler = createBashResourceTelemetry({
  112. platform: "linux",
  113. processGroupId: 10,
  114. probe: { sampleProcessGroup },
  115. onComplete,
  116. });
  117. await vi.advanceTimersByTimeAsync(600000);
  118. expect(sampleProcessGroup).toHaveBeenCalledTimes(20);
  119. expect(vi.getTimerCount()).toBe(0);
  120. expect(onComplete).not.toHaveBeenCalled();
  121. sampler.finish("timeout");
  122. expect(onComplete).toHaveBeenCalledWith(
  123. expect.objectContaining({
  124. sampleCount: 20,
  125. exitKind: "timeout",
  126. durationMs: 600000,
  127. treeCpuTimeMs: 200,
  128. }),
  129. );
  130. });
  131. it("探针抛错、空样本与超时只丢样本,完成回调抛错不外溢", async () => {
  132. vi.useFakeTimers();
  133. const sampleProcessGroup = vi
  134. .fn()
  135. .mockRejectedValueOnce(new Error("probe failed"))
  136. .mockResolvedValueOnce([])
  137. .mockResolvedValueOnce(undefined);
  138. const onComplete = vi.fn(() => {
  139. throw new Error("closed");
  140. });
  141. const sampler = createBashResourceTelemetry({
  142. platform: "linux",
  143. processGroupId: 10,
  144. probe: { sampleProcessGroup },
  145. onComplete,
  146. });
  147. await vi.advanceTimersByTimeAsync(45000);
  148. expect(() => sampler.finish("error")).not.toThrow();
  149. expect(onComplete).toHaveBeenCalledWith(
  150. expect.objectContaining({
  151. sampleCount: 0,
  152. treeRssKbPeak: 0,
  153. treeCpuTimeMs: 0,
  154. exitKind: "error",
  155. }),
  156. );
  157. });
  158. it("采样不重叠,结束不等待在途探针,迟到结果丢弃", async () => {
  159. vi.useFakeTimers();
  160. let resolve!: (rows: { pid: number; rssKb: number; cpuTimeMs: number }[]) => void;
  161. const sampleProcessGroup = vi.fn(
  162. () =>
  163. new Promise<{ pid: number; rssKb: number; cpuTimeMs: number }[]>((done) => {
  164. resolve = done;
  165. }),
  166. );
  167. const onComplete = vi.fn();
  168. const sampler = createBashResourceTelemetry({
  169. platform: "linux",
  170. processGroupId: 10,
  171. probe: { sampleProcessGroup },
  172. onComplete,
  173. });
  174. await vi.advanceTimersByTimeAsync(40000);
  175. expect(sampleProcessGroup).toHaveBeenCalledTimes(1);
  176. sampler.finish("killed");
  177. expect(onComplete).toHaveBeenCalledWith(
  178. expect.objectContaining({ sampleCount: 0, exitKind: "killed" }),
  179. );
  180. resolve([{ pid: 10, rssKb: 1000, cpuTimeMs: 2000 }]);
  181. await vi.advanceTimersByTimeAsync(15000);
  182. expect(onComplete).toHaveBeenCalledTimes(1);
  183. expect(onComplete.mock.calls[0]?.[0].sampleCount).toBe(0);
  184. });
  185. it("PRT-011: 40 秒命令在 15/30 秒采样,退出只发一次;5 秒命令不发", async () => {
  186. vi.useFakeTimers();
  187. const sampleProcessGroup = vi
  188. .fn()
  189. .mockResolvedValueOnce([
  190. { pid: 10, rssKb: 100, cpuTimeMs: 1000 },
  191. { pid: 11, rssKb: 200, cpuTimeMs: 2000 },
  192. ])
  193. .mockResolvedValueOnce([{ pid: 10, rssKb: 200, cpuTimeMs: 4000 }]);
  194. const onComplete = vi.fn();
  195. const options = {
  196. processGroupId: 10,
  197. platform: "linux" as const,
  198. probe: { sampleProcessGroup },
  199. onComplete,
  200. readContext: () => ({ cliRssKb: 1024, systemFreeMemoryKb: 2048 }),
  201. };
  202. const short = createBashResourceTelemetry(options);
  203. await vi.advanceTimersByTimeAsync(5000);
  204. short.finish("completed");
  205. expect(onComplete).not.toHaveBeenCalled();
  206. const slow = createBashResourceTelemetry(options);
  207. await vi.advanceTimersByTimeAsync(14999);
  208. expect(sampleProcessGroup).not.toHaveBeenCalled();
  209. await vi.advanceTimersByTimeAsync(1);
  210. expect(sampleProcessGroup).toHaveBeenCalledExactlyOnceWith(10);
  211. await vi.advanceTimersByTimeAsync(15000);
  212. expect(sampleProcessGroup).toHaveBeenCalledTimes(2);
  213. await vi.advanceTimersByTimeAsync(10000);
  214. slow.finish("completed");
  215. slow.finish("killed");
  216. await vi.advanceTimersByTimeAsync(15000);
  217. expect(onComplete).toHaveBeenCalledExactlyOnceWith({
  218. completionToken: expect.any(String),
  219. platform: "linux",
  220. toolName: "bash",
  221. durationMs: 40000,
  222. exitKind: "completed",
  223. treeRssKbPeak: 300,
  224. treeCpuTimeMs: 6000,
  225. sampleCount: 2,
  226. cliRssKb: 1024,
  227. systemFreeMemoryKb: 2048,
  228. });
  229. expect(sampleProcessGroup).toHaveBeenCalledTimes(2);
  230. });
  231. });