memory-bench.test.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import assert from "node:assert/strict";
  2. import { EventEmitter } from "node:events";
  3. import { setImmediate as nextTask, setTimeout as delay } from "node:timers/promises";
  4. import test from "node:test";
  5. import type { RunContext } from "@zcode/shared-types";
  6. import { run, type RunDependencies } from "../src/run.js";
  7. import type { CliShutdownProcess } from "../src/shutdown.js";
  8. function harness(argv: string[], enabled = true) {
  9. const calls: string[] = [];
  10. const drainStarted = Promise.withResolvers<void>();
  11. const drainComplete = Promise.withResolvers<void>();
  12. const signalProcess = Object.assign(new EventEmitter(), { platform: "linux" as const });
  13. let stdout = "";
  14. let stderr = "";
  15. const ctx: RunContext = {
  16. argv,
  17. stdin: { isTTY: false } as NodeJS.ReadStream,
  18. stdout: {
  19. write: (chunk: string) => {
  20. stdout += chunk;
  21. return true;
  22. },
  23. } as NodeJS.WriteStream,
  24. stderr: {
  25. write: (chunk: string) => {
  26. stderr += chunk;
  27. return true;
  28. },
  29. } as NodeJS.WriteStream,
  30. };
  31. const deps: RunDependencies = {
  32. skipUserConfig: true,
  33. loadDotenv: () => ({ keys: [], loaded: false }),
  34. startProcessProviderRegistryRuntime: async () =>
  35. ({
  36. runtime: { registryService: {} },
  37. dispose: () => calls.push("dispose"),
  38. }) as never,
  39. shutdownCleanupTimeoutMs: 10,
  40. shutdownProcess: signalProcess as CliShutdownProcess,
  41. exitProcess: (code) => {
  42. calls.push(`exit:${code}`);
  43. },
  44. mapSessionEvent: ((event: unknown) => event) as never,
  45. createZCodeApp: (options) => {
  46. calls.push(`extraction:${options?.runtimeConfig?.memory?.extractionEnabled}`);
  47. assert.equal(options?.runtimeConfig?.memory?.enabled, undefined);
  48. return {
  49. sessionId: "memory-bench-test",
  50. traceId: "memory-bench-trace",
  51. runtime: {
  52. isProjectMemoryEnabled: () => enabled,
  53. drainMemoryExtractions: async (timeoutMs: number | null) => {
  54. assert.equal(timeoutMs, null);
  55. calls.push("drain:start");
  56. drainStarted.resolve();
  57. await drainComplete.promise;
  58. calls.push("drain:end");
  59. },
  60. },
  61. submitPrompt: async (
  62. _prompt: unknown,
  63. options?: { onEvent?: (event: unknown) => void },
  64. ) => {
  65. calls.push("main");
  66. options?.onEvent?.({ type: "turn.completed" });
  67. return {
  68. response: "main answer",
  69. events: [],
  70. projection: { status: "idle", turnCount: 1, totalTokenCount: 0 },
  71. };
  72. },
  73. close: async () => {
  74. calls.push("close");
  75. drainComplete.resolve();
  76. },
  77. } as never;
  78. },
  79. };
  80. return {
  81. calls,
  82. ctx,
  83. deps,
  84. drainStarted,
  85. drainComplete,
  86. signalProcess,
  87. output: () => ({ stdout, stderr }),
  88. };
  89. }
  90. for (const format of ["text", "json", "stream-json"]) {
  91. test(
  92. `memory bench waits before final ${format} output and close, beyond cleanup timeout`,
  93. { timeout: 5000 },
  94. async () => {
  95. const h = harness([
  96. "-p",
  97. "remember this convention",
  98. "--memory-bench",
  99. "--output-format",
  100. format,
  101. ]);
  102. let finished = false;
  103. const running = run(h.ctx, h.deps).then((code) => {
  104. finished = true;
  105. return code;
  106. });
  107. try {
  108. await Promise.race([
  109. h.drainStarted.promise,
  110. running.then(() => assert.fail(h.output().stderr)),
  111. ]);
  112. await delay(25);
  113. assert.equal(finished, false);
  114. assert.deepEqual(h.calls, ["extraction:true", "main", "drain:start"]);
  115. assert.equal(
  116. h.output().stdout,
  117. format === "stream-json" ? '{"type":"turn.completed"}\n' : "",
  118. );
  119. } finally {
  120. h.drainComplete.resolve();
  121. await running;
  122. }
  123. assert.equal(await running, 0);
  124. assert.deepEqual(h.calls, [
  125. "extraction:true",
  126. "main",
  127. "drain:start",
  128. "drain:end",
  129. "close",
  130. "dispose",
  131. ]);
  132. assert.match(h.output().stdout, /main answer/);
  133. },
  134. );
  135. }
  136. test("normal headless prompt keeps Extraction disabled and does not drain", async () => {
  137. const h = harness(["-p", "remember this convention"]);
  138. assert.equal(await run(h.ctx, h.deps), 0);
  139. assert.deepEqual(h.calls, ["extraction:false", "main", "close", "dispose"]);
  140. });
  141. test("memory bench rejects disabled Memory before submitting the main prompt", async () => {
  142. const h = harness(["-p", "remember this convention", "--memory-bench"], false);
  143. assert.equal(await run(h.ctx, h.deps), 1);
  144. assert.match(h.output().stderr, /Memory.*enabled/i);
  145. assert.deepEqual(h.calls, ["extraction:true", "close", "dispose"]);
  146. });
  147. for (const argv of [
  148. [],
  149. ["tui"],
  150. ["app-server"],
  151. ["agent-server"],
  152. ["--target", "remember this convention"],
  153. ]) {
  154. test(`memory bench rejects unsupported invocation ${JSON.stringify(argv)}`, async () => {
  155. const h = harness([...argv, "--memory-bench"]);
  156. assert.equal(await run(h.ctx, h.deps), 1);
  157. assert.match(h.output().stderr, /--memory-bench.*--prompt/);
  158. assert.deepEqual(h.calls, []);
  159. });
  160. }
  161. for (const [signal, code] of [
  162. ["SIGINT", 130],
  163. ["SIGTERM", 143],
  164. ] as const) {
  165. test(
  166. `memory bench keeps ${signal} cancellation active while waiting`,
  167. { timeout: 5000 },
  168. async () => {
  169. const h = harness(["-p", "remember this convention", "--memory-bench"]);
  170. const running = run(h.ctx, h.deps);
  171. await Promise.race([
  172. h.drainStarted.promise,
  173. running.then(() => assert.fail(h.output().stderr)),
  174. ]);
  175. h.signalProcess.emit(signal);
  176. await running;
  177. await nextTask();
  178. assert.equal(h.calls.filter((call) => call === "close").length, 1);
  179. assert.ok(h.calls.includes(`exit:${code}`));
  180. assert.equal(h.output().stdout, "");
  181. },
  182. );
  183. }