From e7d2ac7b246e36baabb17f10b3b2ca3251d5cb57 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 19 May 2025 16:25:49 -0700 Subject: [PATCH 1/2] improv: cancel autocomplete requests after timeout is reached --- .../generation/CompletionStreamer.ts | 29 +++- core/autocomplete/generation/utils.test.ts | 127 ++++++++++++++++++ core/autocomplete/generation/utils.ts | 27 ++++ 3 files changed, 176 insertions(+), 7 deletions(-) create mode 100644 core/autocomplete/generation/utils.test.ts create mode 100644 core/autocomplete/generation/utils.ts 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; + } + } + } +} From 88ccb74f7e69cf816d27f15a318a42c11f6d2aa5 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 19 May 2025 17:21:07 -0700 Subject: [PATCH 2/2] fix: failing tests --- core/autocomplete/generation/utils.test.ts | 59 +++++++++++++--------- 1 file changed, 35 insertions(+), 24 deletions(-) diff --git a/core/autocomplete/generation/utils.test.ts b/core/autocomplete/generation/utils.test.ts index 66732b749..40326177a 100644 --- a/core/autocomplete/generation/utils.test.ts +++ b/core/autocomplete/generation/utils.test.ts @@ -37,37 +37,48 @@ describe("stopAfterMaxProcessingTime", () => { 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 + it.only("should stop processing after max time is reached", async () => { + // Mock implementation of Date.now let currentTime = 0; - jest.spyOn(Date, "now").mockImplementation(() => { - currentTime += 100; // Each call advances time by 100ms - return currentTime; - }); + const originalDateNow = Date.now; + Date.now = jest.fn(() => currentTime); - const result = stopAfterMaxProcessingTime(mockStream, 500, fullStop); - - // Consume the stream - const output = []; - try { - for await (const chunk of result) { - output.push(chunk); + // 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}`; } - } catch (e) { - // Ignore any errors from early termination } - // Should have been terminated before processing all chunks - expect(output.length).toBeLessThan(chunks.length); + 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 original Date.now - jest.spyOn(Date, "now").mockRestore(); + // Restore Date.now + Date.now = originalDateNow; }); it("should check time only periodically based on checkInterval", async () => {