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..40326177a --- /dev/null +++ b/core/autocomplete/generation/utils.test.ts @@ -0,0 +1,138 @@ +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.only("should stop processing after max time is reached", async () => { + // Mock implementation of Date.now + let currentTime = 0; + const originalDateNow = Date.now; + Date.now = jest.fn(() => currentTime); + + // Create a generator that we can control + async function* controlledGenerator(): AsyncGenerator { + for (let i = 0; i < 100; i++) { + // After yielding 10 chunks, simulate time passing beyond our limit + if (i === 10) { + currentTime = 1000; // This exceeds our 500ms limit + } + yield `chunk-${i}`; + } + } + + const fullStop = jest.fn(); + const maxTimeMs = 500; + + const transformedGenerator = stopAfterMaxProcessingTime( + controlledGenerator(), + maxTimeMs, + fullStop, + ); + + // Consume the generator and collect outputs + const outputs: string[] = []; + for await (const chunk of transformedGenerator) { + outputs.push(chunk); + } + + // We expect: + // 1. Not all chunks were processed (less than 100) + // 2. fullStop was called + // 3. We processed at least the chunks before time was exceeded + expect(outputs.length).toBeLessThan(100); + expect(outputs.length).toBeGreaterThanOrEqual(10); // We should get at least the first 10 chunks + expect(fullStop).toHaveBeenCalled(); + + // Restore Date.now + Date.now = originalDateNow; + }); + + 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; + } + } + } +}