Spaces:
Running
Running
Sync from felladrin/MiniSearch@a3854eb (part 2)
Browse filesFiles changed (8)
3 unmodified lines456789105 unmodified lines1617181920212223242526273 unmodified lines# file only declares what MiniSearch overrides:# - a placeholder secret_key# - JSON output format (consumed by server/webSearchService.ts)# - Mojeek switched on for text search## Docs: https://docs.searxng.org/admin/settings/settings_use_default_settings.htmluse_default_settings: true5 unmodified linessearch: formats: - json
engines: # Upstream ships Mojeek `inactive: true`, which only `inactive: false` undoes # (`disabled: false` leaves it unloaded). It runs its own index, so its # results are mostly ones the other engines do not return, and it keeps # answering where DuckDuckGo shows a CAPTCHA. See docs/configuration.md, # "Tuning the Search Engines". - name: mojeek inactive: false879 unmodified lines880881882883884885886887888889890891892893894895896897898899900901902903904905906879 unmodified lines expect(LONG_EXCERPT[kept.length]).toBe(" "); });
// The page read for this result would go looking for the text the snippet // cut, so the whole of it is kept for `/page-content`, under the query. it("keeps the whole cleaned excerpt text for the page read", async () => { const results = await run([ { url: "https://example.com/long", title: "Long", excerpts: ["Skip to main content", `## ${LONG_EXCERPT}`, EXCERPT], }, ]); const { recallSearchExcerpts } = await import("./searchExcerptStore");
expect(results[0][1].length).toBeLessThanOrEqual(400); expect(recallSearchExcerpts(QUERY, "https://example.com/long")).toBe( `${LONG_EXCERPT}\n\n${EXCERPT}`, ); expect( recallSearchExcerpts("another query", "https://example.com/long"), ).toBeUndefined(); });
it("leaves a snippet that fits untouched", async () => { expect(EXCERPT.length).toBeLessThanOrEqual(400);
123456761 unmodified lines6970717273747576233 unmodified lines3103113123103133143153163 unmodified lines32032132232332432532632732891 unmodified lines42042142241742342442542678 unmodified lines505506507502508509504510511506512513514515108 unmodified lines62462562662162262362462562662762862963063163263363463563663763863967 unmodified lines707708709710711712713714715716717718719702720721722723724707708709725726727711728729730731732import { randomUUID } from "node:crypto";import { basename } from "node:path";import debug from "debug";import { rememberSearchExcerpts } from "./searchExcerptStore.ts";import { isOpenableUrl } from "./utils/openableUrl.ts";
const fileName = basename(import.meta.url);61 unmodified linesinterface MappedResults { results: TextualResult[]; received: number; /** The provider's longer text per result URL, kept for `/page-content`. */ pageTexts?: Map<string, string>;}
interface FallbackProvider {233 unmodified lines const attemptMs = Math.ceil(remainingMs / eligibleCount);
try { const results = await searchWithProvider( const { results, pageTexts } = await searchWithProvider( provider, query, limit,3 unmodified lines if (results.length > 0) { countFor(provider.name).served++; printMessage(`Fallback search served by ${provider.name}.`); for (const [url, text] of pageTexts ?? []) { rememberSearchExcerpts(query, url, text); } return results; } countFor(provider.name).empty++;91 unmodified lines query: string, limit: number, signal: AbortSignal,): Promise<TextualResult[]> {): Promise<MappedResults> { const apiKey = (process.env[provider.apiKeyVariable] ?? "").trim(); const endpointUrl = provider.endpointUrl(apiKey);
78 unmodified lines }
const document = await readSearchDocument<object>(callResponse, 2); const { results, received } = provider.mapResults(document, limit); const mapped = provider.mapResults(document, limit); printMessage( `Fallback search usable text results from ${provider.name}: ${results.length} of ${received}.`, `Fallback search usable text results from ${provider.name}: ${mapped.results.length} of ${mapped.received}.`, ); return results; return mapped;}
/**108 unmodified lines ); }
return { results: mapEntries(document.results, limit, (result) => buildSnippet(result.excerpts), ), received: document.results.length, }; // The snippet keeps 400 characters of the excerpts; the rest is what the // page read would have gone looking for, so it is kept for `/page-content`. const pageTexts = new Map<string, string>(); const results = mapEntries(document.results, limit, (result) => { const text = cleanExcerpts(result.excerpts); if (text && typeof result.url === "string") pageTexts.set(result.url, text); return toSnippet(text); });
return { results, received: document.results.length, pageTexts };}
function mapYoucomResults(67 unmodified lines}
function buildSnippet(excerpts: string[] | undefined): string { return toSnippet(cleanExcerpts(excerpts));}
/** * One kept line per paragraph, separated by blank lines, which is where * `splitIntoPassages` cuts when the text is read as page content. */function cleanExcerpts(excerpts: string[] | undefined): string { if (!Array.isArray(excerpts) || excerpts.length === 0) return "";
const snippet = excerpts return excerpts .join("\n") .split("\n") .map(stripMarkdown) .filter((line) => line.length >= MIN_SNIPPET_LINE_LENGTH) .join(" ") .replace(/\s+/g, " ") .trim(); .join("\n\n");}
return truncateSnippet(snippet);function toSnippet(text: string): string { return truncateSnippet(text.replace(/\s+/g, " ").trim());}
/**31 unmodified lines323334353637381055 unmodified lines109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114831 unmodified lines PageReadHostBreaker,} from "./pageReadHostBreaker";import { getPageReadStats } from "./pageReadsSinceLastRestart";import { rememberSearchExcerpts } from "./searchExcerptStore";
const fetchMock = vi.fn();vi.stubGlobal("fetch", fetchMock);1055 unmodified lines });});
describe("pages the fallback search already sent", () => { // The store outlives each test, so each one uses its own URL. let url: string; let nextPage = 0; beforeEach(() => { url = `https://example.com/heat-pumps-${nextPage++}`; }); const excerpts = [ "A heat pump moves heat from the outside air into the house instead of generating it, which is why it uses less electricity than a resistive heater for the same warmth.", "In cooling mode the same refrigerant cycle runs in reverse and carries the heat from the house back to the outside unit, the way an air conditioner does.", ].join("\n\n");
it("grounds on the excerpts without reading the page", async () => { rememberSearchExcerpts("how does a heat pump work", url, excerpts); const before = getPageReadStats();
const contents = await fetchPageContents("how does a heat pump work", [ url, ]);
expect(fetchMock).not.toHaveBeenCalled(); expect(contents).toHaveLength(1); expect(contents[0].content).toContain("refrigerant cycle"); const after = getPageReadStats(); expect(after.servedFromSearchExcerpts).toBe( before.servedFromSearchExcerpts + 1, ); expect(after.requested).toBe(before.requested); });
it("reads the page when the excerpts were sent for another query", async () => { rememberSearchExcerpts("heat pump prices", url, excerpts); respondWithHtml(articlePage);
await fetchPageContents("how does a heat pump work", [url]);
expect(fetchMock).toHaveBeenCalledTimes(1); });
it("reads the page when the excerpts are too short to ground on", async () => { rememberSearchExcerpts("short excerpts", url, "Too short to ground on."); respondWithHtml(articlePage);
await fetchPageContents("short excerpts", [url]);
expect(fetchMock).toHaveBeenCalledTimes(1); });});
describe("fetchPageContents", () => { it("identifies itself with the name, version and repository in package.json", async () => { respondWithHtml(articlePage);8 unmodified lines91011121314151617405 unmodified lines423424425426427428429430766 unmodified lines1197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512264 unmodified lines12311232123312061234123512361237123812399 unmodified lines1249125012511222125212531254125512561257125817 unmodified lines12761277127812791280128112821283128412858 unmodified linesimport { type PageReadOutcome, recordPageRead, recordPageServedFromSearchExcerpts,} from "./pageReadsSinceLastRestart.ts";import { recallSearchExcerpts } from "./searchExcerptStore.ts";import { resolvePublicUrl } from "./utils/publicUrl.ts";import { readCappedBytes } from "./utils/streamUtils.ts";
405 unmodified lines contextTerms: string[]; durationMs: number; bodyTruncated: boolean; /** Text the search provider already sent, so no request was made. */ fromSearchExcerpts?: boolean;}
function isRedirect(status: number): boolean {766 unmodified lines }}
/** * The excerpts the fallback search received for this query and URL, as a page, * when they hold enough text to ground on. Otherwise the page is read. */function pageFromSearchExcerpts( query: string, url: string,): FetchedPage | null { const text = recallSearchExcerpts(query, url); if (text === undefined) return null;
const passages = splitIntoPassages(text); if (passages.join("\n").length < MIN_USEFUL_CHARS) return null;
return { url, passages, contextTerms: [], durationMs: 0, bodyTruncated: false, fromSearchExcerpts: true, };}
/** * Reads the given pages and returns the passages most relevant to the query. * Pages that fail, time out, or carry no readable text are left out instead of4 unmodified lines * appear on several pages reach the prompt once. * * A host that refused enough recent reads is skipped without a request, under * `breaker`, and that skip is counted like any other outcome. * `breaker`, and that skip is counted like any other outcome. A page the * fallback search already sent excerpts of for this query is not requested * either: those excerpts stand in for its text. * * Nothing here is logged. Every read is counted instead, by outcome, in * `pageReadsSinceLastRestart`, since a line naming the query or the URL would9 unmodified lines breaker: PageReadHostBreaker = pageReadHostBreaker,): Promise<PageContent[]> { const results = await Promise.all( urls.map((url) => fetchPageContent(url, breaker)), urls.map( (url) => pageFromSearchExcerpts(query, url) ?? fetchPageContent(url, breaker), ), );
const pages = results.filter((r): r is FetchedPage => r !== null);17 unmodified lines );
for (const page of pages) { if (page.fromSearchExcerpts) { recordPageServedFromSearchExcerpts(); continue; } const selected = selectedByUrl.get(page.url) ?? []; recordPageRead({ outcome: "read",49 unmodified lines5051525354555657585923 unmodified lines8384858687888990919215 unmodified lines10810911011111211311449 unmodified lineslet groundingRequests = 0;let groundingRequestsWithContent = 0;
// Pages whose text came with the search results, so no read was made. Kept out// of `requested`, so `readRate` keeps measuring the reads that went out.let servedFromSearchExcerpts = 0;
let totalReadMs = 0;let bodiesTruncated = 0;let totalPassagesKept = 0;23 unmodified lines totalPassagesAvailable += passagesAvailable;}
export function recordPageServedFromSearchExcerpts(): void { servedFromSearchExcerpts++;}
/** One `/page-content` request, and whether any of its pages yielded text. */export function recordGroundingOutcome(hadContent: boolean): void { groundingRequests++;15 unmodified lines requested, read, readRate: Number(((read / requested) * 100 || 0).toFixed(1)), servedFromSearchExcerpts, averageReadMs: Math.round(totalReadMs / requested || 0), bodiesTruncated, // A ratio rather than a count of pages that overflowed: an article almost123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
type StoreModule = typeof import("./searchExcerptStore");let rememberSearchExcerpts: StoreModule["rememberSearchExcerpts"];let recallSearchExcerpts: StoreModule["recallSearchExcerpts"];
beforeEach(async () => { // A fresh store per test, since the entries are module state. vi.resetModules(); ({ rememberSearchExcerpts, recallSearchExcerpts } = await import( "./searchExcerptStore" ));});
afterEach(() => { vi.useRealTimers();});
describe("searchExcerptStore", () => { it("returns the text only for the query and URL it was stored under", () => { rememberSearchExcerpts("heat pumps", "https://example.com/a", "Text A");
expect(recallSearchExcerpts("heat pumps", "https://example.com/a")).toBe( "Text A", ); expect(recallSearchExcerpts(" heat pumps ", "https://example.com/a")).toBe( "Text A", ); expect( recallSearchExcerpts("heat pump", "https://example.com/a"), ).toBeUndefined(); expect( recallSearchExcerpts("heat pumps", "https://example.com/b"), ).toBeUndefined(); });
it("forgets an entry after five minutes", () => { vi.useFakeTimers(); rememberSearchExcerpts("q", "https://example.com/a", "Text");
vi.advanceTimersByTime(5 * 60_000 - 1); expect(recallSearchExcerpts("q", "https://example.com/a")).toBe("Text");
vi.advanceTimersByTime(1); expect(recallSearchExcerpts("q", "https://example.com/a")).toBeUndefined(); });
it("drops the oldest entries beyond 500", () => { for (let index = 0; index <= 500; index++) { rememberSearchExcerpts("q", `https://example.com/${index}`, `${index}`); }
expect(recallSearchExcerpts("q", "https://example.com/0")).toBeUndefined(); expect(recallSearchExcerpts("q", "https://example.com/1")).toBe("1"); expect(recallSearchExcerpts("q", "https://example.com/500")).toBe("500"); });});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455import { createHash } from "node:crypto";
/** * Page text a search provider already sent with its results, held so that * `/page-content` can ground the answer on it instead of downloading the page. * Only the fallback search fills it: Parallel answers each result with excerpts * picked for the query, a median of about 2,500 characters, of which the * result's snippet keeps 400. * * Keyed on a hash of the query and the URL. Excerpts picked for one query are * no grounding for another, an entry only reaches a caller that already sent * the same query, and the store holds no query in clear text. */const TTL_MS = 5 * 60_000;const MAX_ENTRIES = 500;
const entries = new Map<string, { text: string; expiresAt: number }>();
function keyOf(query: string, url: string): string { return createHash("sha256") .update(JSON.stringify([query.trim(), url])) .digest("hex");}
export function rememberSearchExcerpts( query: string, url: string, text: string,): void { const now = Date.now(); const key = keyOf(query, url); entries.delete(key); entries.set(key, { text, expiresAt: now + TTL_MS });
// Insertion order is expiry order, since every entry lives for the same // time, so the oldest entries are both the expired and the evictable ones. for (const [oldestKey, oldest] of entries) { if (entries.size <= MAX_ENTRIES && oldest.expiresAt > now) break; entries.delete(oldestKey); }}
export function recallSearchExcerpts( query: string, url: string,): string | undefined { const key = keyOf(query, url); const entry = entries.get(key); if (!entry) return undefined; if (entry.expiresAt <= Date.now()) { entries.delete(key); return undefined; } return entry.text;}searxng-settings.yml+10
server/fallbackSearchService.test.ts+21
server/fallbackSearchService.ts+34-16
server/pageContentService.test.ts+50
server/pageContentService.ts+39-2
server/pageReadsSinceLastRestart.ts+9
server/searchExcerptStore.test.tsAdded+57
server/searchExcerptStore.tsAdded+55