Spaces:
Running
Running
Sync from felladrin/MiniSearch@3f9f9de (part 2)
Browse filesFiles changed (6)
351 unmodified lines352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383351 unmodified lines return provider.chatModel.mock.calls.map((call) => call[0]); }
it("sends the configured reasoning effort upstream", async () => { vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT", " low "); vi.mocked(streamText).mockImplementation( () => streamOf([{ type: "finish" }]) as never, );
await callWithFakeTimers();
expect(vi.mocked(streamText).mock.calls[0][0].providerOptions).toEqual({ openai: { reasoningEffort: "low" }, }); });
it("leaves the reasoning effort to the upstream when unset", async () => { vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT", ""); vi.mocked(streamText).mockImplementation( () => streamOf([{ type: "finish" }]) as never, );
await callWithFakeTimers();
expect( vi.mocked(streamText).mock.calls[0][0].providerOptions, ).toBeUndefined(); });
it("tries the configured models in their order", async () => { vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", " model-a , model-b "); vi.mocked(streamText)314 unmodified lines31531631731831932032132232332432532632732832944 unmodified lines374375376377378379380314 unmodified lines return; }
// Passed through unchecked: providers disagree on the accepted values // (`none`, `minimal`, `xhigh`...), and an unknown one comes back from // the upstream as an HTTP error in the log. const reasoningEffort = process.env.INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT?.trim(); const providerOptions = reasoningEffort ? { openai: { reasoningEffort } } : undefined;
const config = getModelConfig(); const maxAttempts = 5; let lastError: unknown = null;44 unmodified lines temperature: clampedTemperature, topP: clampedTopP, maxOutputTokens: clampedMaxTokens, providerOptions, maxRetries: 0, abortSignal: abortController.signal, });185 unmodified lines18618718818918919019119219319419519619719873 unmodified lines27227327426927527627727827928028128228328414 unmodified lines29930030129030230330430530630730830931031116 unmodified lines328329330313331332333334335336337338339340230 unmodified lines571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630185 unmodified lines
expect(unknown.statusCode).toBe(404); expect(fetchSearXNG).toHaveBeenCalledTimes(1); expect(fetchSearXNG).toHaveBeenCalledWith("cats", "images", 30); expect(fetchSearXNG).toHaveBeenCalledWith( "cats", "images", 30, undefined, expect.any(AbortSignal), ); });
it("responds 400 when the query parameter is missing", async () => {73 unmodified lines vi.fn(), );
expect(fetchSearXNG).toHaveBeenCalledWith("cats", "text", 30); expect(fetchSearXNG).toHaveBeenCalledWith( "cats", "text", 30, undefined, expect.any(AbortSignal), ); expect(incrementTextualSearchesSinceLastRestart).toHaveBeenCalled(); expect(response.setHeader).toHaveBeenCalledWith( "Content-Type",14 unmodified lines vi.fn(), );
expect(fetchSearXNG).toHaveBeenCalledWith("cats", "text", 30); expect(fetchSearXNG).toHaveBeenCalledWith( "cats", "text", 30, undefined, expect.any(AbortSignal), ); });
it("reranks results when the reranker is healthy and returns its reordered output", async () => {16 unmodified lines vi.fn(), );
expect(fetchSearXNG).toHaveBeenCalledWith("test", "text", 5); expect(fetchSearXNG).toHaveBeenCalledWith( "test", "text", 5, undefined, expect.any(AbortSignal), ); expect(rankSearchResults).toHaveBeenCalledWith( "test", "text",230 unmodified lines ); }
it("gives up on a stalled SearXNG in time for the fallback to answer", async () => { vi.mocked(isSearchFallbackEnabled).mockReturnValue(true); vi.mocked(fetchFallbackTextResults).mockResolvedValue(fallbackResults); const deadline = new AbortController(); const timeoutSpy = vi .spyOn(AbortSignal, "timeout") .mockReturnValue(deadline.signal); // SearXNG never answers; only the deadline signal ends the request. vi.mocked(fetchSearXNG).mockImplementation( (_query, _searchType, _limit, _breaker, signal) => new Promise((_resolve, reject) => { signal?.addEventListener("abort", () => reject(signal.reason)); }), ); const now = vi.spyOn(performance, "now").mockReturnValue(0);
const handler = getRegisteredHandler(); const response = createResponse(); const handled = handler( createRequest("/search/text?q=cats&token=abc"), response, vi.fn(), );
await vi.waitFor(() => expect(fetchSearXNG).toHaveBeenCalled()); expect(timeoutSpy).toHaveBeenCalledWith(15_000); now.mockReturnValue(15_000); deadline.abort(new DOMException("timed out", "TimeoutError")); await handled;
// The 10 s reserve is left for the fallback, which serves the search. expect(fetchFallbackTextResults).toHaveBeenCalledWith( "cats", 30, 10_000, ); expect(response.statusCode).toBe(200); expect(incrementSearchesServedByFallback).toHaveBeenCalledTimes(1); });
it("gives SearXNG the whole deadline when no fallback can follow", async () => { vi.mocked(fetchSearXNG).mockResolvedValue([]); const timeoutSpy = vi.spyOn(AbortSignal, "timeout");
const handler = getRegisteredHandler(); await handler( createRequest("/search/text?q=cats&token=abc"), createResponse(), vi.fn(), );
expect(timeoutSpy).toHaveBeenCalledWith(25_000); });
it("serves the fallback results through the normal text path", async () => { vi.mocked(isSearchFallbackEnabled).mockReturnValue(true); failSearxng();42 unmodified lines43444546474849505152184 unmodified lines2372382392402412422432442372452462472482492502512522532542 unmodified lines25725825924626026126226342 unmodified lines// A fallback cannot finish in this window, so starting one would only move the// same 502 further out.const MIN_FALLBACK_BUDGET_MS = 2_000;// The part of the deadline SearXNG may not spend when a fallback could answer// instead, so a stalled SearXNG is given up on while the fallback can still// run. SearXNG keeps 15 s, enough for its retries and their backoff.const SEARXNG_FALLBACK_RESERVE_MS = 10_000;
// The official lane is a supplement for a search that already succeeded, so it// never gets the last seconds of the deadline: what it would add is not worth184 unmodified lines let searchResults: TextResult[] | ImageResult[] | null; let servedBySearXNG = false; const searchStartedAt = performance.now(); const fallbackPossible = isTextSearch && isSearchFallbackEnabled(); const searxngTimeoutMs = fallbackPossible ? SEARCH_DEADLINE_MS - SEARXNG_FALLBACK_RESERVE_MS : SEARCH_DEADLINE_MS; try { searchResults = await fetchSearXNG(query, searchType, limit); searchResults = await fetchSearXNG( query, searchType, limit, undefined, AbortSignal.timeout(searxngTimeoutMs), ); servedBySearXNG = true; recordSearchDuration(searchType, performance.now() - searchStartedAt); } catch {2 unmodified lines // and never for images: no fallback provider has image search. searchResults = null;
if (isTextSearch && isSearchFallbackEnabled()) { if (fallbackPossible) { const remainingMs = SEARCH_DEADLINE_MS - (performance.now() - searchStartedAt);
204 unmodified lines205206207208209210209211212213214918 unmodified lines11331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266204 unmodified lines fetchMock.mockResolvedValue(createMockResponse("", false, 500));
const promise = fetchSearXNG("test", "text"); // Exact: the last 500 used to throw the plain status message, so the // retries never showed in the log. const outcome = expect(promise).rejects.toThrow( "SearXNG request failed with status 500", /^SearXNG request failed with status 500 after 3 retries$/, ); await vi.runAllTimersAsync(); await outcome;918 unmodified lines ); });});
/** A failed answer whose body records being cancelled. */function failedResponseWithBody(status: number) { const cancel = vi.fn(() => Promise.resolve()); const response = createMockResponse("", false, status); Object.defineProperty(response, "body", { value: { cancel } }); return { response, cancel };}
describe("search deadline", () => { beforeEach(() => { vi.useFakeTimers(); });
afterEach(() => { vi.useRealTimers(); });
it("passes the signal to every SearXNG fetch", async () => { fetchMock.mockResolvedValue(successResponse()); const { signal } = new AbortController();
await fetchSearXNG("test", "text", 30, new CircuitBreaker(), signal);
expect(fetchMock.mock.calls[0][1]?.signal).toBe(signal); });
it("ends a stalled fetch when the signal fires and counts it against the circuit", async () => { const breaker = new CircuitBreaker({ failureThreshold: 1 }); const deadline = new AbortController(); fetchMock.mockImplementation( (_url, init) => new Promise((_resolve, reject) => { init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), ); }), );
const search = fetchSearXNG("test", "text", 30, breaker, deadline.signal); const outcome = expect(search).rejects.toThrow("timed out"); deadline.abort(new DOMException("timed out", "TimeoutError")); await outcome;
expect(breaker.getState("searxng")).toBe("OPEN"); });
it("stops retrying when the signal fires during the backoff", async () => { fetchMock.mockResolvedValue(createMockResponse("", false, 500)); const deadline = new AbortController();
const search = fetchSearXNG( "test", "text", 30, new CircuitBreaker(), deadline.signal, ); const outcome = expect(search).rejects.toThrow("timed out"); await vi.advanceTimersByTimeAsync(500); deadline.abort(new DOMException("timed out", "TimeoutError")); await vi.runAllTimersAsync(); await outcome;
expect(fetchMock).toHaveBeenCalledTimes(1); });});
describe("failed response bodies", () => { beforeEach(() => { vi.useFakeTimers(); });
afterEach(() => { vi.useRealTimers(); });
it("discards the body of each 500 that is retried", async () => { const first = failedResponseWithBody(500); const second = failedResponseWithBody(500); fetchMock .mockResolvedValueOnce(first.response) .mockResolvedValueOnce(second.response) .mockResolvedValueOnce(successResponse());
const search = fetchSearXNG("test", "text", 30, new CircuitBreaker()); await vi.runAllTimersAsync(); await search;
expect(first.cancel).toHaveBeenCalledTimes(1); expect(second.cancel).toHaveBeenCalledTimes(1); });
it("discards the body of every 500 when the retries run out", async () => { const answers = Array.from({ length: 4 }, () => failedResponseWithBody(500), ); for (const { response } of answers) fetchMock.mockResolvedValueOnce(response);
const search = fetchSearXNG("test", "text", 30, new CircuitBreaker()); const outcome = expect(search).rejects.toThrow(); await vi.runAllTimersAsync(); await outcome;
for (const { cancel } of answers) expect(cancel).toHaveBeenCalledTimes(1); });
it("discards the body of a 503 and keeps its message", async () => { const answer = failedResponseWithBody(503); fetchMock.mockResolvedValueOnce(answer.response);
await expect( fetchSearXNG("test", "text", 30, new CircuitBreaker()), ).rejects.toThrow(/^SearXNG request failed with status 503$/);
expect(answer.cancel).toHaveBeenCalledTimes(1); expect(fetchMock).toHaveBeenCalledTimes(1); });
it("discards the body of a failed supplementary search", async () => { const answer = failedResponseWithBody(503); fetchMock.mockResolvedValueOnce(answer.response);
await expect(fetchSupplementarySearXNG("test", 5)).rejects.toThrow( "SearXNG request failed with status 503", );
expect(answer.cancel).toHaveBeenCalledTimes(1); });});217 unmodified lines2182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572585 unmodified lines26426526623526726826927027127227327427527627727824327928028128251 unmodified lines33433533633733833934034130334234334434539 unmodified lines38538638738838939039139239339439539639739839940035640140240340440540640740840941022 unmodified lines433434435436437438439217 unmodified lines );}
/** * Waits out a retry backoff, or rejects with the signal's reason as soon as it * fires, so a search that has run out of time does not sleep past its deadline. */function waitForRetry(delayMs: number, signal?: AbortSignal): Promise<void> { return new Promise((resolve, reject) => { if (signal?.aborted) { reject(signal.reason); return; } const onAbort = () => { clearTimeout(timer); reject(signal?.reason); }; const timer = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve(); }, delayMs); signal?.addEventListener("abort", onAbort, { once: true }); });}
/** * A response that is not used still holds its connection until its body is * read or cancelled, so a failed answer has its body discarded before the * caller decides to retry or throw. */async function discardBody(response: Response): Promise<void> { await response.body?.cancel().catch(() => {});}
async function performSearch( query: string, searchType: SearchType, signal?: AbortSignal,): Promise<SearxngSearchResult[]> { const searchUrl = buildSearchUrl(query, searchType);
5 unmodified lines printMessage( `SearXNG ${retryReason}, retrying in ${delay}ms (attempt ${attempt}/${MAX_RETRIES})`, ); await new Promise((resolve) => setTimeout(resolve, delay)); await waitForRetry(delay, signal); }
const response = await fetch(searchUrl, { headers: { Accept: "application/json" }, signal, });
if (!response.ok) { await discardBody(response); // Every 500 is retried; the last one leaves the loop for the throw after // it, whose message says the retries happened. if (response.status === 500 && attempt < MAX_RETRIES) { if (response.status === 500) { retryReason = "returned 500"; continue; }51 unmodified lines searchType: SearchType, limit: number, breaker: CircuitBreaker, signal?: AbortSignal,) { // An abort is thrown inside `execute`, so a stalled SearXNG counts as a // failure as soon as the deadline passes. const results = await breaker.execute("searxng", () => performSearch(query, searchType), performSearch(query, searchType, signal), ); const consideredResults = openableUniqueResults(results).slice(0, limit);
39 unmodified lines return filteredResults;}
/** * `signal` bounds the whole search, retries and backoff included: every fetch * gets it, and a backoff ends when it fires. Without one, a stalled SearXNG * holds the request for undici's 300 s default. */export async function fetchSearXNG( query: string, searchType: SearchType, limit = 30, breaker: CircuitBreaker = searxngCircuitBreaker, signal?: AbortSignal,) { try { return await processSearchResults(query, searchType, limit, breaker); return await processSearchResults( query, searchType, limit, breaker, signal, ); } catch (error) { // Upstream failure (bad status, network error, malformed body, open // circuit) propagates so the endpoint can answer non-200; an empty array22 unmodified lines });
if (!response.ok) { await discardBody(response); throw new Error(`SearXNG request failed with status ${response.status}`); }
server/internalApiEndpointServerHook.test.ts+26
server/internalApiEndpointServerHook.ts+10
server/searchEndpointServerHook.test.ts+82-4
server/searchEndpointServerHook.ts+16-2
server/webSearchService.test.ts+134-1
server/webSearchService.ts+56-4