Merge pull request #5739 from continuedev/tomasz/fix-autocomplete-abort

improv: cancel autocomplete requests after timeout is reached
This commit is contained in:
Tomasz Stefaniak 2025-05-19 17:48:38 -07:00 • committed by GitHub
commit 028a558663
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 187 additions and 7 deletions

View file

@ -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<CompletionOptions> | 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) {

View file

@ -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<string> {
for (const chunk of chunks) {
yield chunk;
}
}
async function streamToString(
stream: AsyncGenerator<string>,
): Promise<string> {
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<string> {
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();
});
});

View file

@ -0,0 +1,27 @@
export async function* stopAfterMaxProcessingTime(
stream: AsyncGenerator<string>,
maxTimeMs: number,
fullStop: () => void,
): AsyncGenerator<string> {
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;
}
}
}
}