diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts index d44957d15..fdaa09eb5 100644 --- a/core/autocomplete/generation/CompletionStreamer.ts +++ b/core/autocomplete/generation/CompletionStreamer.ts @@ -3,6 +3,7 @@ import { StreamTransformPipeline } from "../filtering/streamTransforms/StreamTra import { HelperVars } from "../util/HelperVars"; import { GeneratorReuseManager } from "./GeneratorReuseManager"; +import { stopAfterMaxProcessingTime } from "./utils"; export class CompletionStreamer { private streamTransformPipeline = new StreamTransformPipeline(); @@ -22,23 +23,37 @@ export class CompletionStreamer { completionOptions: Partial | undefined, helper: HelperVars, ) { + // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion + const fullStop = () => + this.generatorReuseManager.currentGenerator?.cancel(); + // Try to reuse pending requests if what the user typed matches start of completion const generator = this.generatorReuseManager.getGenerator( prefix, - (abortSignal: AbortSignal) => - llm.supportsFim() + (abortSignal: AbortSignal) => { + const generator = llm.supportsFim() ? llm.streamFim(prefix, suffix, abortSignal, completionOptions) : llm.streamComplete(prompt, abortSignal, { ...completionOptions, raw: true, - }), + }); + + /** + * This transformer applies even on reused generator. We are deliberately + * not using streamTransformPipeline because we want to capture and stop + * the request even if the generator is being reused. + */ + return helper.options.transform + ? stopAfterMaxProcessingTime( + generator, + helper.options.modelTimeout * 2.5, + fullStop, + ) + : generator; + }, multiline, ); - // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion - const fullStop = () => - this.generatorReuseManager.currentGenerator?.cancel(); - // LLM const generatorWithCancellation = async function* () { for await (const update of generator) { diff --git a/core/autocomplete/generation/utils.test.ts b/core/autocomplete/generation/utils.test.ts new file mode 100644 index 000000000..66732b749 --- /dev/null +++ b/core/autocomplete/generation/utils.test.ts @@ -0,0 +1,127 @@ +import { jest } from "@jest/globals"; +import { stopAfterMaxProcessingTime } from "./utils"; + +describe("stopAfterMaxProcessingTime", () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + async function* createMockStream(chunks: string[]): AsyncGenerator { + for (const chunk of chunks) { + yield chunk; + } + } + + async function streamToString( + stream: AsyncGenerator, + ): Promise { + let result = ""; + for await (const chunk of stream) { + result += chunk; + } + return result; + } + + it("should yield all chunks when maxTimeMs is not reached", async () => { + const mockStream = createMockStream(["Hello", " world", "!"]); + const fullStop = jest.fn(); + const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop); + + const output = await streamToString(result); + + expect(output).toBe("Hello world!"); + expect(fullStop).not.toHaveBeenCalled(); + }); + + it("should stop processing after max time is reached", async () => { + // Create a stream that will take some time to process + const chunks = Array(50).fill("chunk"); + const mockStream = createMockStream(chunks); + const fullStop = jest.fn(); + + // Set up Date.now to simulate time passing + let currentTime = 0; + jest.spyOn(Date, "now").mockImplementation(() => { + currentTime += 100; // Each call advances time by 100ms + return currentTime; + }); + + const result = stopAfterMaxProcessingTime(mockStream, 500, fullStop); + + // Consume the stream + const output = []; + try { + for await (const chunk of result) { + output.push(chunk); + } + } catch (e) { + // Ignore any errors from early termination + } + + // Should have been terminated before processing all chunks + expect(output.length).toBeLessThan(chunks.length); + expect(fullStop).toHaveBeenCalled(); + + // Restore original Date.now + jest.spyOn(Date, "now").mockRestore(); + }); + + it("should check time only periodically based on checkInterval", async () => { + const chunks = Array(100).fill("x"); + const mockStream = createMockStream(chunks); + const fullStop = jest.fn(); + + // Spy on Date.now to count how many times it's called + const dateSpy = jest.spyOn(Date, "now"); + + // Stream should complete normally (not hitting the timeout) + await streamToString( + stopAfterMaxProcessingTime(mockStream, 10000, fullStop), + ); + + // The first call is to set startTime, then once every checkInterval (10) chunks + // So for 100 chunks, we expect startTime + ~10 checks = ~11 calls + // We use a range because implementation details might vary slightly + expect(dateSpy.mock.calls.length).toBeGreaterThanOrEqual(1); + expect(dateSpy.mock.calls.length).toBeLessThanOrEqual(15); + + dateSpy.mockRestore(); + }); + + it("should handle empty stream gracefully", async () => { + const mockStream = createMockStream([]); + const fullStop = jest.fn(); + const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop); + + const output = await streamToString(result); + + expect(output).toBe(""); + expect(fullStop).not.toHaveBeenCalled(); + }); + + it("should pass through all chunks if there's no timeout", async () => { + const chunks = Array(100).fill("test chunk"); + const mockStream = createMockStream(chunks); + const fullStop = jest.fn(); + + // Use undefined as timeout to simulate no timeout + const result = stopAfterMaxProcessingTime( + mockStream, + undefined as any, + fullStop, + ); + + // Process the stream + const processedChunks = []; + for await (const chunk of result) { + processedChunks.push(chunk); + } + + expect(processedChunks.length).toBe(chunks.length); + expect(fullStop).not.toHaveBeenCalled(); + }); +}); diff --git a/core/autocomplete/generation/utils.ts b/core/autocomplete/generation/utils.ts new file mode 100644 index 000000000..b5c94d9a9 --- /dev/null +++ b/core/autocomplete/generation/utils.ts @@ -0,0 +1,27 @@ +export async function* stopAfterMaxProcessingTime( + stream: AsyncGenerator, + maxTimeMs: number, + fullStop: () => void, +): AsyncGenerator { + const startTime = Date.now(); + /** + * Check every 10 chunks to avoid performance overhead. + */ + const checkInterval = 10; + let chunkCount = 0; + let totalCharCount = 0; + + for await (const chunk of stream) { + yield chunk; + + chunkCount++; + totalCharCount += chunk.length; + + if (chunkCount % checkInterval === 0) { + if (Date.now() - startTime > maxTimeMs) { + fullStop(); + return; + } + } + } +}