okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-split-int (a3024ed10) into f-split-qa1: qa2's s3237-s3238 kept, my 21 strings renumbered s3260-s32808667a3dbf

main
10.3 KiB178 linesraw
1// The agent's keyless web search against a MOCKED, rate-limited DuckDuckGo: spaced requests, a session cache, a cooldown that doubles,
2// Bing as the second source, and one plain sentence (with the place to add a key) when every source refuses.
3import test from 'node:test';
4import assert from 'node:assert/strict';
5import { readFileSync } from 'node:fs';
6import { createDuckDuckGoSearch, BLOCKED_MESSAGE, LIMITED_SENTENCE, UNREACHABLE_MESSAGE } from '../server/web-search-ddg.mjs';
7import { bingTarget, parseBingResults, bingLooksBlocked } from '../server/web-search-bing.mjs';
8
9const BING = readFileSync(new URL('./fixtures/bing-results.html', import.meta.url), 'utf8');
10const DDG = `<div class="result"><h2 class="result__title"><a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fddg.example%2Fa">DDG one</a></h2>
11<a class="result__snippet" href="x">First snippet</a></div>
12<div class="result"><h2 class="result__title"><a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fddg.example%2Fb">DDG two</a></h2></div>`;
13const ANOMALY = '<html><body><div class="anomaly-modal">Unfortunately, bots use DuckDuckGo too.</div></body></html>';
14
15/** A fake clock whose sleep moves time, and a fake web: `script(url, n)` decides each answer. */
16function world(script, { random = () => 0.5 } = {}) {
17  let t = 5_000_000;
18  const calls = [];
19  const fetch = async (url, init) => {
20    const at = t;
21    const call = { url: String(url), method: init?.method ?? 'GET', at, headers: init?.headers ?? {} };
22    calls.push(call);
23    const out = await script(call, calls.length);
24    if (out instanceof Error) throw out;
25    return out;
26  };
27  const search = createDuckDuckGoSearch({ fetch, now: () => t, sleep: async ms => { t += ms; }, random });
28  return { search, calls, advance: ms => { t += ms; }, clock: () => t, hostCalls: host => calls.filter(c => c.url.includes(host)) };
29}
30const page = (body, status = 200, headers = {}) => new Response(body, { status, headers });
31const duck = url => /duckduckgo\.com/.test(url);
32
33test('requests to one source are spaced 2.5 s or more apart, never in a burst', async () => {
34  const w = world(() => page(DDG));
35  for (const q of ['one', 'two', 'three', 'four']) await w.search.search({ query: q });
36  const at = w.calls.map(c => c.at);
37  assert.equal(at.length, 4);
38  for (let i = 1; i < at.length; i++) assert.ok(at[i] - at[i - 1] >= 2500, `gap ${i}: ${at[i] - at[i - 1]} ms`);
39});
40
41test('the request looks like the page\'s own form post: browser headers, Referer, Origin, no hidden tricks', async () => {
42  const w = world(() => page(DDG));
43  await w.search.search({ query: 'strata' });
44  const [c] = w.calls;
45  assert.equal(c.method, 'POST');
46  assert.match(c.headers['user-agent'], /Mozilla\/5\.0 .*Chrome\/\d+/);
47  assert.equal(c.headers.referer, 'https://html.duckduckgo.com/');
48  assert.equal(c.headers.origin, 'https://html.duckduckgo.com');
49  assert.equal(c.headers['sec-fetch-mode'], 'navigate');
50  assert.match(c.headers['accept-language'], /en/);
51});
52
53test('the same question is answered from the session cache, even while DuckDuckGo is refusing', async () => {
54  let refuse = false;
55  const w = world(call => (duck(call.url) ? (refuse ? page(ANOMALY, 202) : page(DDG)) : page(BING)));
56  const a = await w.search.search({ query: 'Strata  Engine' });
57  assert.equal(a.sources.length, 2);
58  refuse = true;
59  const b = await w.search.search({ query: 'strata engine' });
60  assert.deepEqual(b.sources, a.sources);
61  assert.equal(w.calls.length, 1, 'no second request');
62  w.advance(20 * 60_000);
63  assert.equal((await w.search.search({ query: 'STRATA ENGINE' })).sources.length, 2, 'still cached after 20 minutes');
64  assert.equal(w.calls.length, 1);
65  w.advance(11 * 60_000);
66  await w.search.search({ query: 'strata engine' });
67  assert.ok(w.calls.length > 1, 'asked again after the cache is 30 minutes old');
68});
69
70test('DuckDuckGo refuses (HTTP 202): Bing answers, DuckDuckGo is left alone for a minute, and its lite page is not tried', async () => {
71  const w = world(call => (duck(call.url) ? page(ANOMALY, 202) : page(BING)));
72  const first = await w.search.search({ query: 'node release notes', maxResults: 3 });
73  assert.equal(first.sources.length, 3);
74  assert.equal(first.sources[0].url, 'https://github.com/Niko1221/Strata');
75  assert.equal(w.hostCalls('html.duckduckgo.com').length, 1);
76  assert.equal(w.hostCalls('lite.duckduckgo.com').length, 0, 'a refusal is not followed by the lite page');
77  assert.equal(w.hostCalls('bing.com').length, 1);
78  // The next question goes straight to Bing: DuckDuckGo is cooling down.
79  await w.search.search({ query: 'another question' });
80  assert.equal(w.hostCalls('duckduckgo.com').length, 1, 'no request to DuckDuckGo during the cooldown');
81  assert.equal(w.hostCalls('bing.com').length, 2);
82  assert.ok(w.search.status().duckduckgo.blockedForMs > 0);
83  // After the cooldown one probe goes out again.
84  w.advance(61_000);
85  await w.search.search({ query: 'a third question' });
86  assert.equal(w.hostCalls('html.duckduckgo.com').length, 2);
87});
88
89test('every source refuses: one plain sentence with the place to add a key; later searches make no request at all', async () => {
90  const w = world(call => page(duck(call.url) ? ANOMALY : '<html>captcha</html>', duck(call.url) ? 202 : 429));
91  const error = await w.search.search({ query: 'hello world' }).catch(e => e);
92  assert.equal(error.code, 'WEB_RATE_LIMITED');
93  assert.equal(error.message, BLOCKED_MESSAGE);
94  assert.ok(error.message.startsWith(LIMITED_SENTENCE));
95  assert.match(LIMITED_SENTENCE, /^Web search is limited right now\. Try again in a minute, or add a search key \(Exa, Perplexity or DeepSeek\) in Settings → Tools → Web search\.$/);
96  assert.match(error.message, /Do not retry this search/, 'the model is told to stop');
97  const used = w.calls.length;
98  assert.equal(used, 2, 'one request per source, nothing more');
99  for (const q of ['again', 'and again', 'once more']) {
100    const e = await w.search.search({ query: q }).catch(x => x);
101    assert.equal(e.code, 'WEB_RATE_LIMITED', q);
102  }
103  assert.equal(w.calls.length, used, 'a model that keeps asking does not extend the block');
104});
105
106test('the cooldown doubles each time a source refuses again, and a Retry-After header is honoured', async () => {
107  const w = world(call => (duck(call.url) ? page(ANOMALY, 202) : page('<html>captcha</html>', 429)));
108  await w.search.search({ query: 'q1' }).catch(() => {});
109  const first = w.search.status().duckduckgo.blockedForMs;
110  assert.ok(first > 55_000 && first <= 60_000, `first cooldown ${first}`);
111  w.advance(61_000);
112  await w.search.search({ query: 'q2' }).catch(() => {});
113  const second = w.search.status().duckduckgo.blockedForMs;
114  assert.ok(second > 115_000 && second <= 120_000, `second cooldown ${second}`);
115  w.advance(121_000);
116  await w.search.search({ query: 'q3' }).catch(() => {});
117  assert.ok(w.search.status().duckduckgo.blockedForMs > 235_000);
118  const r = world(call => (duck(call.url) ? page(ANOMALY, 429, { 'retry-after': '300' }) : page('<html>captcha</html>', 429)));
119  await r.search.search({ query: 'x' }).catch(() => {});
120  assert.ok(r.search.status().duckduckgo.blockedForMs > 295_000, 'Retry-After: 300');
121});
122
123test('a recovered source resets the cooldown', async () => {
124  let refuse = true;
125  const w = world(call => (duck(call.url) ? (refuse ? page(ANOMALY, 202) : page(DDG)) : page('<html>captcha</html>', 429)));
126  await w.search.search({ query: 'a' }).catch(() => {});
127  w.advance(61_000);
128  refuse = false;
129  assert.equal((await w.search.search({ query: 'b' })).sources[0].url, 'https://ddg.example/a');
130  assert.equal(w.search.status().duckduckgo.strikes, 0);
131  assert.equal(w.search.status().duckduckgo.blockedForMs, 0);
132});
133
134test('a timeout or a server error gets one retry; two in a row moves on to the next source; nothing reachable says so', async () => {
135  let n = 0;
136  const flaky = world(call => (duck(call.url) ? (++n === 1 ? page('oops', 503) : page(DDG)) : page(BING)));
137  assert.equal((await flaky.search.search({ query: 'q' })).sources[0].url, 'https://ddg.example/a');
138  assert.equal(flaky.hostCalls('duckduckgo.com').length, 2);
139  const down = world(call => (duck(call.url) ? new TypeError('fetch failed') : page(BING)));
140  const viaBing = await down.search.search({ query: 'q' });
141  assert.equal(viaBing.sources.length, 5, 'DuckDuckGo unreachable twice: Bing answers');
142  const none = world(() => new TypeError('fetch failed'));
143  const e = await none.search.search({ query: 'q' }).catch(x => x);
144  assert.equal(e.message, UNREACHABLE_MESSAGE);
145  assert.notEqual(e.code, 'WEB_RATE_LIMITED');
146});
147
148test('a search with no hits is an answer; a cancelled search is cancelled', async () => {
149  const w = world(() => page('<html><body>No results found.</body></html>'));
150  assert.deepEqual(await w.search.search({ query: 'zzzz qqqq' }), { sources: [], truncated: false });
151  const ctrl = new AbortController(); ctrl.abort();
152  const e = await w.search.search({ query: 'later' }, ctrl.signal).catch(x => x);
153  assert.equal(e.code, 'WEB_ABORTED');
154});
155
156test('too many searches in a minute are held back by the app, not sent to the sources', async () => {
157  const w = world(() => page(DDG));
158  let held = null;
159  for (let i = 0; i < 12 && !held; i++) held = await w.search.search({ query: `question ${i}` }).then(() => null, e => e);
160  assert.ok(held, 'the ninth search in a minute is held back');
161  assert.equal(held.code, 'WEB_RATE_LIMITED');
162  assert.ok(w.hostCalls('duckduckgo.com').length <= 8);
163});
164
165test('Bing: the real result page is read (redirect links decoded, snippets kept); a challenge page is a refusal; ordinary pages are not', () => {
166  const rows = parseBingResults(BING);
167  assert.equal(rows.length, 5);
168  assert.ok(rows.every(r => /^https:\/\//.test(r.url) && !r.url.includes('bing.com')), 'real addresses, not Bing redirects');
169  assert.equal(rows[1].url, 'https://github.com/Niko1221/Strata/releases');
170  assert.ok(rows[0].snippet.length > 20);
171  assert.equal(bingTarget('https://www.bing.com/ck/a?!&&p=1&u=a1aHR0cHM6Ly9leGFtcGxlLmNvbS9hP3g9MQ&ntb=1'), 'https://example.com/a?x=1');
172  assert.equal(bingTarget('https://www.bing.com/images/search?q=x'), null);
173  assert.equal(bingTarget('https://example.org/direct'), 'https://example.org/direct');
174  assert.equal(bingLooksBlocked(429, ''), true);
175  assert.equal(bingLooksBlocked(200, '<html><form>captcha</form></html>'), true);
176  assert.equal(bingLooksBlocked(200, BING), false);
177  assert.deepEqual(parseBingResults('<html>nothing here</html>'), []);
178});