local-runtime-host-output-safety-concurrency.test.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import { LocalAgentTurnRunner } from '../../../local-runtime-v2/src/service/turn-system/agent-host/runner/local-agent-turn-runner.js';
  2. import { logger } from '../../src/common/logger.js';
  3. // Concurrency isolation for the output-safety host loop.
  4. //
  5. // The blocked flag / abort / review buffers live on per-attempt writer instances
  6. // (locals inside runTurn), never on the shared host. This test runs two turns
  7. // concurrently through ONE host — one whose output is rejected, one clean — and
  8. // asserts the rejection cannot leak into the clean turn.
  9. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
  10. import { LocalRuntimeHost, type LocalTurnRunner } from '../../src/runtime/host.js';
  11. import { RespDataType } from '@mavis/agent-core/protocol/agent-message';
  12. import { RuntimeEventStatus, RuntimeEventType, type IRuntimeEvent } from '@mavis/protocol';
  13. function finalMessage(content: string): IRuntimeEvent {
  14. return {
  15. schema: 'runtime.event/v1',
  16. event_id: `evt_${Math.random().toString(36).slice(2)}`,
  17. session_id: 'ses',
  18. turn_id: 'turn',
  19. type: RuntimeEventType.STREAM_RESP,
  20. payload: {
  21. stream_resp: JSON.stringify({
  22. type: RespDataType.AgentMessage,
  23. agent_message: { msg_id: `msg_${Math.random().toString(36).slice(2)}`, msg_content: content },
  24. }),
  25. },
  26. } as IRuntimeEvent;
  27. }
  28. /** Reject any review whose content contains the marker 'BLOCK', else pass. */
  29. function installContentAwareFetch() {
  30. const reviewedTurns = new Set<boolean>();
  31. let releaseFirstReviews!: () => void;
  32. const firstReviews = new Promise<void>((resolve) => {
  33. releaseFirstReviews = resolve;
  34. });
  35. return vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
  36. const body = JSON.parse(String(init?.body ?? '{}')) as { content_text: string };
  37. const blocked = body.content_text.includes('BLOCK');
  38. // Hold both initial reviews until both turns have reached the shared gateway.
  39. reviewedTurns.add(blocked);
  40. if (reviewedTurns.size === 2) releaseFirstReviews();
  41. await firstReviews;
  42. return Response.json(
  43. blocked
  44. ? { action: 4, errorCode: 50201 }
  45. : { action: 1 },
  46. );
  47. });
  48. }
  49. describe('LocalRuntimeHost output safety — concurrency isolation', () => {
  50. beforeEach(() => {
  51. delete process.env.IDC;
  52. });
  53. afterEach(() => {
  54. vi.restoreAllMocks();
  55. delete process.env.IDC;
  56. });
  57. it('records a review stop while retaining completed terminal semantics', async () => {
  58. const log = vi.spyOn(logger, 'warn').mockImplementation(() => {});
  59. const fetchMock = vi
  60. .spyOn(globalThis, 'fetch')
  61. .mockRejectedValue(new DOMException('timeout', 'TimeoutError'));
  62. const host = new LocalRuntimeHost({
  63. safetyApiVersion: 'v2',
  64. outputSafetyRetryDelay: async () => {},
  65. piRunner: {
  66. async runTurn(input) {
  67. await input.eventWriter.pushRuntime(finalMessage('unreviewed-output'));
  68. },
  69. },
  70. });
  71. const output = await host.runTurn({
  72. workspaceDir: '/tmp/ws',
  73. systemPrompt: '',
  74. userMessage: { text: 'hi' },
  75. llm: { model: {} as never },
  76. sessionId: 'ses',
  77. turnId: 'turn',
  78. });
  79. expect(fetchMock).toHaveBeenCalledTimes(4);
  80. expect(output).toMatchObject({ networkStopped: true, retracted: false });
  81. expect(output.events.filter((event) => event.type === RuntimeEventType.STREAM_RESP)).toEqual(
  82. [],
  83. );
  84. expect(output.events).toContainEqual(
  85. expect.objectContaining({
  86. type: RuntimeEventType.SESSION_STATUS,
  87. payload: expect.objectContaining({ status: RuntimeEventStatus.COMPLETED }),
  88. }),
  89. );
  90. expect(log).toHaveBeenCalledWith(
  91. {
  92. sessionId: 'ses',
  93. turnId: 'turn',
  94. reviewOutcome: 'unavailable',
  95. outputSuppressed: true,
  96. terminalStatus: 'completed',
  97. },
  98. '[content-safety] output review stopped turn',
  99. );
  100. expect(JSON.stringify(log.mock.calls)).not.toContain('unreviewed-output');
  101. });
  102. it.each([false, true])('diagnoses the V2 review stop without overriding runner failure: %s', async (runnerFailed) => {
  103. const log = vi.spyOn(logger, 'warn').mockImplementation(() => {});
  104. const events: IRuntimeEvent[] = [];
  105. const eventWriter = {
  106. events,
  107. async pushRuntime(event: IRuntimeEvent) { events.push(event); },
  108. async appendEvents(next: IRuntimeEvent[]) { events.push(...next); },
  109. };
  110. const reviewContent = vi.fn(async () => ({ pass: false, errorKind: 'local_error' as const }));
  111. const runner = new LocalAgentTurnRunner({
  112. reviewContent,
  113. outputSafetyRetryDelay: async () => {},
  114. piRunner: { async runTurn(input) {
  115. await input.eventWriter.pushRuntime(finalMessage('unreviewed-output'));
  116. if (runnerFailed) await input.eventWriter.pushRuntime({
  117. ...finalMessage(''), type: RuntimeEventType.SESSION_STATUS,
  118. payload: { status: RuntimeEventStatus.FAILED },
  119. });
  120. } },
  121. });
  122. const output = await runner.runTurn({
  123. workspaceDir: '/tmp/ws', systemPrompt: '', userMessage: { text: 'hi' },
  124. llm: { model: {} as never }, sessionId: 'ses', turnId: 'turn', eventWriter,
  125. toolContext: { agentName: 'test', parentAgentConfig: {}, trustedExactWritePaths: [], eventWriter } as never,
  126. });
  127. expect(reviewContent).toHaveBeenCalledTimes(4);
  128. expect(events.filter(event => event.type === RuntimeEventType.STREAM_RESP)).toEqual([]);
  129. expect(output.outcome.status).toBe(runnerFailed ? 'failed' : 'completed');
  130. if (runnerFailed) {
  131. expect(log).not.toHaveBeenCalled();
  132. } else {
  133. expect(output).toMatchObject({ networkStopped: true, retracted: false, reconcile: { kind: 'network-reconcile' } });
  134. expect(log).toHaveBeenCalledWith({
  135. sessionId: 'ses', turnId: 'turn', reviewOutcome: 'unavailable',
  136. outputSuppressed: true, terminalStatus: 'completed',
  137. }, '[content-safety] output review stopped turn');
  138. }
  139. });
  140. it('a rejected turn never contaminates a concurrent clean turn', async () => {
  141. const fetchMock = installContentAwareFetch();
  142. // One shared runner + one shared host drive both turns. Each turn emits
  143. // content keyed off its own sessionId.
  144. const runner: LocalTurnRunner = {
  145. async runTurn(input) {
  146. const content =
  147. input.sessionId === 'ses_block' ? 'BLOCK this unsafe output' : 'a perfectly safe answer';
  148. await input.eventWriter.pushRuntime(finalMessage(content));
  149. },
  150. };
  151. const host = new LocalRuntimeHost({ safetyApiVersion: 'v2', piRunner: runner });
  152. const blockRecall = vi.fn();
  153. const okRecall = vi.fn();
  154. const base = {
  155. workspaceDir: '/tmp/ws',
  156. systemPrompt: '',
  157. userMessage: { text: 'hi' },
  158. llm: { model: {} as never },
  159. rewindPiHistory: async () => {},
  160. };
  161. const [blockOut, okOut] = await Promise.all([
  162. host.runTurn({
  163. ...base,
  164. sessionId: 'ses_block',
  165. turnId: 't_block',
  166. onOutputRecall: blockRecall,
  167. }),
  168. host.runTurn({ ...base, sessionId: 'ses_ok', turnId: 't_ok', onOutputRecall: okRecall }),
  169. ]);
  170. // The rejected turn retracts; the clean turn is entirely unaffected.
  171. expect(blockOut.retracted).toBe(true);
  172. expect(okOut.retracted).toBe(false);
  173. // Clean turn forwarded its content; blocked turn forwarded no assistant text.
  174. const okText = okOut.events
  175. .filter((e) => e.type === RuntimeEventType.STREAM_RESP)
  176. .map((e) => String(e.payload?.stream_resp ?? ''))
  177. .join('');
  178. expect(okText).toContain('perfectly safe answer');
  179. expect(okText).not.toContain('BLOCK');
  180. expect(
  181. blockOut.events.filter((e) => e.type === RuntimeEventType.STREAM_RESP),
  182. ).toHaveLength(0);
  183. // Recall fired only for the blocked turn's regenerations.
  184. expect(okRecall).not.toHaveBeenCalled();
  185. expect(blockRecall).toHaveBeenCalledTimes(3);
  186. expect(fetchMock).toHaveBeenCalledTimes(5);
  187. const requests = fetchMock.mock.calls.map(([url, init]) => {
  188. expect(String(url)).toContain('/mavis/api/v2/content?require_auth=true');
  189. return JSON.parse(String(init?.body)) as { content_text: string; scene: number };
  190. });
  191. expect(requests.filter((body) => body.content_text.includes('BLOCK'))).toHaveLength(4);
  192. expect(requests.filter((body) => !body.content_text.includes('BLOCK'))).toHaveLength(1);
  193. expect(requests.every((body) => body.scene === 11)).toBe(true);
  194. });
  195. });