case-output-token-continuation.mjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import { mkdir } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { writeJsonFile } from "./artifacts.mjs";
  4. import {
  5. assertCondition,
  6. assertProviderCapture,
  7. buildCaseResult,
  8. buildRuntimeConfig,
  9. createApp,
  10. makeCaseDirs,
  11. writeProviderConfig,
  12. } from "./case-utils.mjs";
  13. import { FAKE_MODEL } from "./constants.mjs";
  14. import {
  15. chatCompletion,
  16. startScriptedProvider,
  17. stopScriptedProvider,
  18. } from "./scripted-provider.mjs";
  19. import { prepareWorkspace } from "./workspace.mjs";
  20. import {
  21. assistantContents,
  22. captureDurableAssistantHistory,
  23. captureDurableContinueCount,
  24. captureRuntimeHistory,
  25. } from "./output-token-continuation-history.mjs";
  26. const CASE_NAME = "output-token-continuation";
  27. const OUTPUT_TOKEN_CONTINUE_PROMPT =
  28. "Output token limit hit. Resume directly — no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces.";
  29. const OUTPUT_TOKEN_LIMIT_ERROR = "The model's response exceeded the output token maximum.";
  30. const SUCCESS_PARTIAL = "OUTPUT_CONTINUE_E2E_PARTIAL";
  31. const SUCCESS_DONE = "OUTPUT_CONTINUE_E2E_DONE";
  32. const COLD_DONE = "OUTPUT_CONTINUE_E2E_COLD_DONE";
  33. const AFTER_ERROR_DONE = "OUTPUT_CONTINUE_E2E_AFTER_ERROR_DONE";
  34. const SCENARIOS = ["success", "exhausted"];
  35. const CONTEXT_WINDOW = 100_000;
  36. const MAX_OUTPUT_TOKENS = 16_000;
  37. export const outputTokenContinuationCase = {
  38. name: CASE_NAME,
  39. requiresApiKey: false,
  40. async run(input) {
  41. const scenarioResults = [];
  42. for (const scenario of SCENARIOS) {
  43. scenarioResults.push(
  44. await runScenario({
  45. ...input,
  46. caseRoot: join(input.caseRoot, scenario),
  47. scenario,
  48. }),
  49. );
  50. }
  51. const artifactsDir = `${input.artifactsRoot}/cases/${CASE_NAME}`;
  52. const capturePath = `${artifactsDir}/capture.json`;
  53. const eventsPath = `${artifactsDir}/events.json`;
  54. const resultPath = `${artifactsDir}/result.json`;
  55. await mkdir(artifactsDir, { recursive: true });
  56. await writeJsonFile(capturePath, {
  57. case: CASE_NAME,
  58. scenarios: scenarioResults.map((result) => ({
  59. name: result.scenario,
  60. records: result.records,
  61. })),
  62. });
  63. await writeJsonFile(eventsPath, {
  64. case: CASE_NAME,
  65. scenarios: scenarioResults.map((result) => ({
  66. events: result.events,
  67. name: result.scenario,
  68. })),
  69. });
  70. const result = buildCaseResult({
  71. capturedProviderRequestCount: scenarioResults.reduce(
  72. (total, scenario) => total + scenario.records.length,
  73. 0,
  74. ),
  75. caseName: CASE_NAME,
  76. capturePath,
  77. events: scenarioResults.flatMap((scenario) => scenario.events),
  78. eventsPath,
  79. response: scenarioResults.map((scenario) => scenario.response).join("\n"),
  80. resultPath,
  81. traceId: scenarioResults.at(-1)?.traceId,
  82. });
  83. await writeJsonFile(resultPath, {
  84. ...result,
  85. scenarios: scenarioResults.map(
  86. ({ events: _events, records: _records, ...scenario }) => scenario,
  87. ),
  88. });
  89. return result;
  90. },
  91. };
  92. async function runScenario(input) {
  93. const scenarioName = `${CASE_NAME}-${input.scenario}`;
  94. const paths = await makeCaseDirs({ ...input, caseName: scenarioName });
  95. const events = [];
  96. let app;
  97. let provider;
  98. try {
  99. await prepareWorkspace({ fixtureDir: input.fixtureDir, workspace: paths.workspace });
  100. provider = await startScriptedProvider({
  101. handler: createScenarioHandler(input.scenario),
  102. name: scenarioName,
  103. });
  104. await writeProviderConfig(paths.configPath, {
  105. apiKeyRequired: false,
  106. baseURL: provider.baseURL,
  107. contextWindow: CONTEXT_WINDOW,
  108. maxOutputTokens: MAX_OUTPUT_TOKENS,
  109. model: FAKE_MODEL,
  110. providerId: "output-continuation-e2e-fake",
  111. providerName: "Output Continuation E2E Provider",
  112. storageDir: paths.storageDir,
  113. });
  114. const runtimeConfig = {
  115. ...buildRuntimeConfig({
  116. compact: { enabled: false, microcompact: { enabled: false } },
  117. maxTurns: 12,
  118. workspace: paths.workspace,
  119. }),
  120. titleGeneration: { enabled: false },
  121. };
  122. // Bug 根因:createApp 已异步化,漏 await 会在第一条 provider 请求前直接失败。
  123. app = await createApp({
  124. configPath: paths.configPath,
  125. modules: input.modules,
  126. runtimeConfig,
  127. storageDir: paths.storageDir,
  128. });
  129. const scenarioResult =
  130. input.scenario === "success"
  131. ? await runSuccessScenario({
  132. app,
  133. events,
  134. input,
  135. paths,
  136. provider,
  137. runtimeConfig,
  138. })
  139. : await runExhaustedScenario({
  140. app,
  141. events,
  142. input,
  143. paths,
  144. provider,
  145. runtimeConfig,
  146. });
  147. assertProviderCapture(provider.records);
  148. await writeJsonFile(paths.capturePath, { records: provider.records, scenario: input.scenario });
  149. await writeJsonFile(paths.eventsPath, events);
  150. return {
  151. ...scenarioResult,
  152. events,
  153. records: provider.records,
  154. scenario: input.scenario,
  155. };
  156. } catch (error) {
  157. await writeJsonFile(paths.capturePath, {
  158. error: error instanceof Error ? error.message : String(error),
  159. records: provider?.records ?? [],
  160. scenario: input.scenario,
  161. });
  162. await writeJsonFile(paths.eventsPath, events);
  163. throw error;
  164. } finally {
  165. await app?.close?.();
  166. await stopScriptedProvider(provider);
  167. }
  168. }
  169. async function runSuccessScenario({ app, events, input, paths, provider, runtimeConfig }) {
  170. const result = await app.submitPrompt("Run successful output continuation.", {
  171. onEvent: async (event) => events.push(event),
  172. });
  173. const firstTurnRecords = [...provider.records];
  174. const runtimeHistory = captureRuntimeHistory(app);
  175. const durableHistory = await captureDurableAssistantHistory(app);
  176. assertCondition(
  177. result.response === SUCCESS_DONE,
  178. "successful chain must return only final text",
  179. {
  180. response: result.response,
  181. },
  182. );
  183. assertContinueRequestSequence(firstTurnRecords);
  184. assertRecordedContinueMatchesRequests(events, input.modules.SessionEventType, firstTurnRecords);
  185. // Continue 按隐藏提醒记录写库:三次续写各一条。
  186. assertCondition(
  187. (await captureDurableContinueCount(app)) === 3,
  188. "each Continue must be persisted as a hidden reminder row",
  189. );
  190. assertCondition(
  191. assistantContents(runtimeHistory).join("|") === `${SUCCESS_PARTIAL}|${SUCCESS_DONE}`,
  192. "only real partial and final assistants may enter runtime history",
  193. { runtimeHistory },
  194. );
  195. assertCondition(
  196. durableHistory.map((message) => message.content).join("|") ===
  197. `${SUCCESS_PARTIAL}|${SUCCESS_DONE}`,
  198. "only real partial and final assistants may enter durable history",
  199. { durableHistory },
  200. );
  201. const sessionId = app.sessionId;
  202. await app.close?.();
  203. let resumedApp;
  204. try {
  205. resumedApp = await createApp({
  206. configPath: paths.configPath,
  207. modules: input.modules,
  208. resume: true,
  209. runtimeConfig,
  210. sessionId,
  211. storageDir: paths.storageDir,
  212. });
  213. await resumedApp.resume?.();
  214. // 恢复成功必须同时证明身份和历史,避免新建空 session 也满足下面的前缀断言。
  215. assertCondition(
  216. resumedApp.sessionId === sessionId,
  217. "cold App must retain the original session",
  218. );
  219. assertCondition(
  220. assistantContents(captureRuntimeHistory(resumedApp)).join("|") ===
  221. `${SUCCESS_PARTIAL}|${SUCCESS_DONE}`,
  222. "cold App must restore the original partial and final assistants before the next prompt",
  223. );
  224. const coldResult = await resumedApp.submitPrompt("Cold follow-up after output continuation.", {
  225. onEvent: async (event) => events.push(event),
  226. });
  227. const coldRequest = parseRecordBody(provider.records.at(-1));
  228. assertCondition(coldResult.response === COLD_DONE, "cold follow-up must complete normally");
  229. // 冷恢复后的第一个请求以重启前最后一个请求为前缀(含三条 Continue),缓存断点不算内容。
  230. const lastLive = parseRecordBody(firstTurnRecords.at(-1));
  231. assertCondition(
  232. JSON.stringify(
  233. withoutCacheControl(coldRequest.messages?.slice(0, lastLive.messages?.length)),
  234. ) === JSON.stringify(withoutCacheControl(lastLive.messages)),
  235. "cold follow-up request must start with the last live request",
  236. { cold: coldRequest.messages, live: lastLive.messages },
  237. );
  238. assertCondition(
  239. countContinuePrompts(coldRequest) === 3,
  240. "cold follow-up request must replay the three persisted Continue messages",
  241. { messages: coldRequest.messages },
  242. );
  243. assertCondition(
  244. JSON.stringify(coldRequest.messages ?? []).includes(
  245. "Cold follow-up after output continuation.",
  246. ),
  247. "cold follow-up request must include the new real user input",
  248. );
  249. return { response: coldResult.response, traceId: coldResult.traceId };
  250. } finally {
  251. await resumedApp?.close?.();
  252. }
  253. }
  254. async function runExhaustedScenario({ app, events, input, paths, provider, runtimeConfig }) {
  255. const { SessionEventType } = input.modules;
  256. let terminalError;
  257. try {
  258. await app.submitPrompt("Exhaust output continuation.", {
  259. onEvent: async (event) => events.push(event),
  260. });
  261. } catch (error) {
  262. terminalError = error;
  263. }
  264. const exhaustedHistory = captureRuntimeHistory(app);
  265. const exhaustedDurableHistory = await captureDurableAssistantHistory(app);
  266. assertCondition(
  267. terminalError instanceof Error && terminalError.message === OUTPUT_TOKEN_LIMIT_ERROR,
  268. "fourth output limit must reject the current Turn with the stable error",
  269. { error: terminalError instanceof Error ? terminalError.message : terminalError },
  270. );
  271. assertCondition(provider.records.length === 4, "exhaustion must not send a fifth request");
  272. assertContinueRequestSequence(provider.records);
  273. const exhaustedRuntimeAssistants = exhaustedHistory.filter((entry) => entry.role === "assistant");
  274. assertCondition(
  275. exhaustedRuntimeAssistants.length === 0 &&
  276. exhaustedDurableHistory.length === 1 &&
  277. exhaustedDurableHistory[0]?.content === "" &&
  278. exhaustedDurableHistory[0]?.error?.data?.message === OUTPUT_TOKEN_LIMIT_ERROR &&
  279. exhaustedDurableHistory[0]?.tokens?.input === 0 &&
  280. exhaustedDurableHistory[0]?.tokens?.output === 0,
  281. "fully empty exhaustion must persist only the durable assistant error",
  282. { exhaustedDurableHistory, exhaustedHistory },
  283. );
  284. assertRecordedContinueMatchesRequests(events, SessionEventType, provider.records);
  285. assertCondition(
  286. events.some((event) => event.type === SessionEventType.TurnError) &&
  287. !events.some((event) => event.type === SessionEventType.TurnComplete),
  288. "exhausted Turn must end in TurnError without TurnComplete(success)",
  289. { eventTypes: events.map((event) => event.type) },
  290. );
  291. const sessionId = app.sessionId;
  292. await app.close?.();
  293. const resumedApp = await createApp({
  294. configPath: paths.configPath,
  295. modules: input.modules,
  296. resume: true,
  297. runtimeConfig,
  298. sessionId,
  299. storageDir: paths.storageDir,
  300. });
  301. try {
  302. await resumedApp.resume?.({ onEvent: async (event) => events.push(event) });
  303. assertCondition(
  304. resumedApp.sessionId === sessionId,
  305. "exhausted App must resume the original session",
  306. );
  307. assertCondition(
  308. captureRuntimeHistory(resumedApp).some(
  309. (entry) => entry.role === "user" && entry.content.includes("Exhaust output continuation."),
  310. ),
  311. "exhausted cold App must restore the original user history",
  312. );
  313. const nextResult = await resumedApp.submitPrompt("Continue after the output-limit error.", {
  314. onEvent: async (event) => events.push(event),
  315. });
  316. const nextRequest = parseRecordBody(provider.records.at(-1));
  317. assertCondition(
  318. nextResult.response === AFTER_ERROR_DONE,
  319. "cold runtime must accept the next Turn",
  320. );
  321. assertCondition(provider.records.length === 5, "next Turn must issue exactly one new request");
  322. assertCondition(
  323. countContinuePrompts(nextRequest) === 3 &&
  324. !nextRequest.messages?.some((message) => message.role === "assistant"),
  325. "cold provider history must replay the persisted Continue and exclude the error-only assistant",
  326. { messages: nextRequest.messages },
  327. );
  328. return { response: nextResult.response, traceId: nextResult.traceId };
  329. } finally {
  330. await resumedApp.close?.();
  331. }
  332. }
  333. function createScenarioHandler(scenario) {
  334. let requestCount = 0;
  335. return async ({ body }) => {
  336. assertCondition(
  337. body?.max_tokens === MAX_OUTPUT_TOKENS,
  338. "every request must retain the case output budget",
  339. {
  340. max_tokens: body?.max_tokens,
  341. },
  342. );
  343. requestCount += 1;
  344. if (scenario === "success") {
  345. const responses = [
  346. { content: "", finishReason: "length" },
  347. { content: SUCCESS_PARTIAL, finishReason: "length" },
  348. { content: "", finishReason: "length" },
  349. { content: SUCCESS_DONE, finishReason: "stop" },
  350. { content: COLD_DONE, finishReason: "stop" },
  351. ];
  352. const response = responses[requestCount - 1];
  353. if (!response) throw new Error(`Unexpected success request ${requestCount}`);
  354. return { body: chatCompletion({ ...response, model: body?.model }) };
  355. }
  356. if (requestCount <= 4) {
  357. return {
  358. body: chatCompletion({
  359. completionTokens: 0,
  360. content: "",
  361. finishReason: "length",
  362. model: body?.model,
  363. }),
  364. };
  365. }
  366. if (requestCount === 5) {
  367. return { body: chatCompletion({ content: AFTER_ERROR_DONE, model: body?.model }) };
  368. }
  369. throw new Error(`Unexpected exhausted request ${requestCount}`);
  370. };
  371. }
  372. function assertContinueRequestSequence(records) {
  373. assertCondition(records.length === 4, "recovery chain must contain exactly four requests", {
  374. requestCount: records.length,
  375. });
  376. const counts = records.map((record) => countContinuePrompts(parseRecordBody(record)));
  377. assertCondition(
  378. JSON.stringify(counts) === JSON.stringify([0, 1, 2, 3]),
  379. "requests 1-4 must contain 0/1/2/3 exact Continue messages",
  380. { counts },
  381. );
  382. }
  383. // ModelRequest 事件与实际请求是同一份消息:每个事件记录的 Continue 条数与对应 HTTP 请求相同。
  384. function assertRecordedContinueMatchesRequests(events, SessionEventType, records) {
  385. const recorded = events
  386. .filter((event) => event.type === SessionEventType.ModelRequest)
  387. .map((event) => countContinuePrompts(event.payload));
  388. const sent = records.map((record) => countContinuePrompts(parseRecordBody(record)));
  389. assertCondition(
  390. JSON.stringify(recorded) === JSON.stringify(sent),
  391. "ModelRequest events must record the same Continue messages as the HTTP requests",
  392. { recorded, sent },
  393. );
  394. }
  395. function withoutCacheControl(value) {
  396. if (Array.isArray(value)) return value.map(withoutCacheControl);
  397. if (!value || typeof value !== "object") return value;
  398. return Object.fromEntries(
  399. Object.entries(value)
  400. .filter(([key]) => key !== "cache_control")
  401. .map(([key, item]) => [key, withoutCacheControl(item)]),
  402. );
  403. }
  404. function countContinuePrompts(body) {
  405. return JSON.stringify(body?.messages ?? []).split(OUTPUT_TOKEN_CONTINUE_PROMPT).length - 1;
  406. }
  407. function parseRecordBody(record) {
  408. try {
  409. return JSON.parse(record?.requestBody ?? "{}");
  410. } catch {
  411. return {};
  412. }
  413. }