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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. // Concurrency isolation for the output-safety host loop.
  2. //
  3. // The blocked flag / abort / review buffers live on per-attempt writer instances
  4. // (locals inside runTurn), never on the shared host. This test runs two turns
  5. // concurrently through ONE host — one whose output is rejected, one clean — and
  6. // asserts the rejection cannot leak into the clean turn.
  7. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
  8. import { LocalRuntimeHost, type LocalTurnRunner } from '../../src/runtime/host.js';
  9. import { RespDataType } from '@mavis/agent-core/protocol/agent-message';
  10. import { RuntimeEventType, type IRuntimeEvent } from '@mavis/protocol';
  11. function finalMessage(content: string): IRuntimeEvent {
  12. return {
  13. schema: 'runtime.event/v1',
  14. event_id: `evt_${Math.random().toString(36).slice(2)}`,
  15. session_id: 'ses',
  16. turn_id: 'turn',
  17. type: RuntimeEventType.STREAM_RESP,
  18. payload: {
  19. stream_resp: JSON.stringify({
  20. type: RespDataType.AgentMessage,
  21. agent_message: { msg_id: `msg_${Math.random().toString(36).slice(2)}`, msg_content: content },
  22. }),
  23. },
  24. } as IRuntimeEvent;
  25. }
  26. /** Reject any review whose content contains the marker 'BLOCK', else pass. */
  27. function installContentAwareFetch() {
  28. const reviewedTurns = new Set<boolean>();
  29. let releaseFirstReviews!: () => void;
  30. const firstReviews = new Promise<void>((resolve) => {
  31. releaseFirstReviews = resolve;
  32. });
  33. return vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
  34. const body = JSON.parse(String(init?.body ?? '{}')) as { content_text: string };
  35. const blocked = body.content_text.includes('BLOCK');
  36. // Hold both initial reviews until both turns have reached the shared gateway.
  37. reviewedTurns.add(blocked);
  38. if (reviewedTurns.size === 2) releaseFirstReviews();
  39. await firstReviews;
  40. return Response.json(
  41. blocked
  42. ? { action: 4, errorCode: 50201 }
  43. : { action: 1 },
  44. );
  45. });
  46. }
  47. describe('LocalRuntimeHost output safety — concurrency isolation', () => {
  48. beforeEach(() => {
  49. delete process.env.IDC;
  50. });
  51. afterEach(() => {
  52. vi.restoreAllMocks();
  53. delete process.env.IDC;
  54. });
  55. it('a rejected turn never contaminates a concurrent clean turn', async () => {
  56. const fetchMock = installContentAwareFetch();
  57. // One shared runner + one shared host drive both turns. Each turn emits
  58. // content keyed off its own sessionId.
  59. const runner: LocalTurnRunner = {
  60. async runTurn(input) {
  61. const content =
  62. input.sessionId === 'ses_block' ? 'BLOCK this unsafe output' : 'a perfectly safe answer';
  63. await input.eventWriter.pushRuntime(finalMessage(content));
  64. },
  65. };
  66. const host = new LocalRuntimeHost({ safetyApiVersion: 'v2', piRunner: runner });
  67. const blockRecall = vi.fn();
  68. const okRecall = vi.fn();
  69. const base = {
  70. workspaceDir: '/tmp/ws',
  71. systemPrompt: '',
  72. userMessage: { text: 'hi' },
  73. llm: { model: {} as never },
  74. rewindPiHistory: async () => {},
  75. };
  76. const [blockOut, okOut] = await Promise.all([
  77. host.runTurn({
  78. ...base,
  79. sessionId: 'ses_block',
  80. turnId: 't_block',
  81. onOutputRecall: blockRecall,
  82. }),
  83. host.runTurn({ ...base, sessionId: 'ses_ok', turnId: 't_ok', onOutputRecall: okRecall }),
  84. ]);
  85. // The rejected turn retracts; the clean turn is entirely unaffected.
  86. expect(blockOut.retracted).toBe(true);
  87. expect(okOut.retracted).toBe(false);
  88. // Clean turn forwarded its content; blocked turn forwarded no assistant text.
  89. const okText = okOut.events
  90. .filter((e) => e.type === RuntimeEventType.STREAM_RESP)
  91. .map((e) => String(e.payload?.stream_resp ?? ''))
  92. .join('');
  93. expect(okText).toContain('perfectly safe answer');
  94. expect(okText).not.toContain('BLOCK');
  95. expect(
  96. blockOut.events.filter((e) => e.type === RuntimeEventType.STREAM_RESP),
  97. ).toHaveLength(0);
  98. // Recall fired only for the blocked turn's regenerations.
  99. expect(okRecall).not.toHaveBeenCalled();
  100. expect(blockRecall).toHaveBeenCalledTimes(3);
  101. expect(fetchMock).toHaveBeenCalledTimes(5);
  102. const requests = fetchMock.mock.calls.map(([url, init]) => {
  103. expect(String(url)).toContain('/mavis/api/v2/content?require_auth=true');
  104. return JSON.parse(String(init?.body)) as { content_text: string; scene: number };
  105. });
  106. expect(requests.filter((body) => body.content_text.includes('BLOCK'))).toHaveLength(4);
  107. expect(requests.filter((body) => !body.content_text.includes('BLOCK'))).toHaveLength(1);
  108. expect(requests.every((body) => body.scene === 11)).toBe(true);
  109. });
  110. });