search-run.test.ts (24379B)
1 import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; 2 import { readFileSync } from 'node:fs'; 3 import { finalizeEvent } from 'applesauce-core/helpers'; 4 import type { PublicPoolMessage } from '../../src/lib/nostr/exports.ts'; 5 import type { RequestClock } from '../../src/lib/nostr/request-scope.ts'; 6 let search: typeof import('../../src/lib/catalog/search-run.ts'); 7 let runtime: typeof import('../../src/lib/runtime/public-runtime.ts'); 8 let requests: typeof import('../../src/lib/nostr/request-scope.ts'); 9 let context: ReturnType<typeof runtime.createPublicRuntimeContext>; 10 const keys: Uint8Array[] = []; 11 beforeEach(async () => { 12 vi.resetModules(); 13 vi.stubGlobal('window', {}); 14 search = await import('../../src/lib/catalog/search-run.ts'); 15 runtime = await import('../../src/lib/runtime/public-runtime.ts'); 16 requests = await import('../../src/lib/nostr/request-scope.ts'); 17 }); 18 afterEach(() => { 19 if (context) runtime.closePublicRuntime(context); 20 for (const key of keys.splice(0)) key.fill(0); 21 vi.restoreAllMocks(); 22 vi.unstubAllGlobals(); 23 }); 24 const corpus = JSON.parse( 25 readFileSync( 26 new URL( 27 '../../../contracts/interop/food_availability/corpus.v1.json', 28 import.meta.url 29 ), 30 'utf8' 31 ) 32 ) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; 33 const base = JSON.parse( 34 corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous 35 ) as { tags: string[][]; content: string; created_at: number }; 36 async function fixture(nip50 = false, sourceCount = 1) { 37 const { RelayPool } = await import('applesauce-relay/pool'); 38 const { validateRelayPolicy } = 39 await import('../../src/lib/config/relays.ts'); 40 const { verifyEnvelope } = 41 await import('../../src/lib/nostr/verified-envelope.ts'); 42 const { createPublicHeadCandidate } = 43 await import('../../src/lib/catalog/heads.ts'); 44 const channels: { 45 emit: (value: PublicPoolMessage) => void; 46 stopped: () => boolean; 47 }[] = []; 48 const provider = vi.spyOn(RelayPool.prototype, 'req').mockImplementation( 49 () => 50 ({ 51 subscribe(subscriber: { next?: (value: PublicPoolMessage) => void }) { 52 let stopped = false; 53 channels.push({ 54 emit: (value: PublicPoolMessage) => { 55 if (!stopped) subscriber.next?.(value); 56 }, 57 stopped: () => stopped 58 }); 59 return { 60 get closed() { 61 return stopped; 62 }, 63 unsubscribe() { 64 stopped = true; 65 } 66 }; 67 } 68 }) as unknown as ReturnType<InstanceType<typeof RelayPool>['req']> 69 ); 70 const origin = 'wss://one.example.org'; 71 const policy = validateRelayPolicy( 72 JSON.stringify({ 73 schemaVersion: 1, 74 public: Array.from({ length: sourceCount }, (_, n) => ({ 75 origin: n === 0 ? origin : `wss://source${n}.example.org`, 76 read: true, 77 write: false, 78 nip50 79 })), 80 inbox: [], 81 postingEnabled: false, 82 messagingEnabled: false, 83 operatorDenylist: [] 84 }) 85 )!; 86 const key = crypto.getRandomValues(new Uint8Array(32)); 87 keys.push(key); 88 const wire = ( 89 title = 'Carrots', 90 d?: string, 91 time = base.created_at, 92 content = base.content 93 ) => 94 finalizeEvent( 95 { 96 kind: 30402, 97 created_at: time, 98 content, 99 tags: base.tags.map((tag) => 100 tag[0] === 'title' 101 ? ['title', title] 102 : tag[0] === 'd' && d !== undefined 103 ? ['d', d] 104 : [...tag] 105 ) 106 }, 107 key 108 ); 109 const head = (event = wire()) => { 110 const p = verifyEnvelope(JSON.stringify(event)); 111 if (!p.ok) throw Error('fixture proof'); 112 const h = createPublicHeadCandidate(p.value); 113 if (!h) throw Error('fixture head'); 114 return h; 115 }; 116 let now = 0, 117 reads = 0; 118 let onNow = () => {}; 119 const timers = new Map<() => void, { at: number; callback: () => void }>(); 120 const clock: RequestClock = { 121 now: () => { 122 reads++; 123 onNow(); 124 return now; 125 }, 126 schedule: (callback, delay) => { 127 const cancel = () => { 128 timers.delete(cancel); 129 }; 130 timers.set(cancel, { at: now + delay, callback }); 131 return cancel; 132 } 133 }; 134 context = runtime.createPublicRuntimeContext(); 135 const owner = runtime.mountPublicRuntime(context, policy, clock)!; 136 const view = runtime.createPublicView(owner); 137 const wallClock = { 138 nowSeconds: () => base.created_at + 10 139 }; 140 const coordinator = search.createFoodSearchCoordinator(view, wallClock); 141 const begin = (query = '', heads: readonly ReturnType<typeof head>[] = []) => 142 search.beginFoodSearch(coordinator, query, heads); 143 const snapshot = () => search.foodSearchSnapshot(coordinator)!; 144 const emit = (i: number, event: ReturnType<typeof wire>) => 145 channels[i].emit({ type: 'EVENT', id: 'fixture', from: origin, event }); 146 return { 147 eose: (i: number) => { 148 const selected = provider.mock.calls[i][0]; 149 if (!Array.isArray(selected)) throw new Error('fixture source array'); 150 for (const source of selected) 151 channels[i].emit({ type: 'EOSE', id: 'fixture', from: String(source) }); 152 }, 153 coordinator, 154 view, 155 wallClock, 156 begin, 157 snapshot, 158 head, 159 wire, 160 emit, 161 channels, 162 provider, 163 origin, 164 timers, 165 reads: () => reads, 166 reenter: (callback: () => void) => { 167 onNow = callback; 168 }, 169 advance: (value: number) => { 170 now = value; 171 for (const timer of [...timers.values()]) 172 if (timer.at <= now) timer.callback(); 173 } 174 }; 175 } 176 describe('finite food search coordination (isolated SDK provider, not qualification)', () => { 177 it('enforces twenty publisher admissions per page across row reordering', async () => { 178 const f = await fixture(); 179 const values = Array.from({ length: 21 }, (_, n) => { 180 const key = crypto.getRandomValues(new Uint8Array(32)); 181 keys.push(key); 182 return finalizeEvent( 183 { 184 kind: 30402, 185 created_at: base.created_at + (n === 20 ? 1 : 0), 186 content: base.content, 187 tags: base.tags.map((t) => 188 t[0] === 'd' ? ['d', `page_${n}`] : [...t] 189 ) 190 }, 191 key 192 ); 193 }); 194 const token = f.begin( 195 '', 196 values.slice(0, 20).map((v) => f.head(v)) 197 ); 198 f.eose(0); 199 f.eose(1); 200 search.resolveFoodSearchPublishers(token); 201 f.eose(2); 202 search.chronologicalFoodSearch(token); 203 f.emit(3, values[20]); 204 f.snapshot(); 205 f.eose(4); 206 f.eose(5); 207 f.eose(3); 208 expect(f.snapshot().rows[0].state.head.id).toBe(values[20].id); 209 expect(search.resolveFoodSearchPublishers(token)).toEqual([]); 210 const profiles = f.provider.mock.calls.flatMap(([, input]) => 211 Array.isArray(input) && input[0].kinds?.[0] === 0 ? [input[0]] : [] 212 ); 213 expect(profiles).toHaveLength(1); 214 expect(profiles[0].authors).toHaveLength(20); 215 expect(f.snapshot().listings[0].publisher).toEqual({ 216 pubkey: values[20].pubkey, 217 label: values[20].pubkey, 218 assertedName: false 219 }); 220 }); 221 it('orders final verified revisions before selecting the first twenty rows', async () => { 222 const f = await fixture(); 223 const values = Array.from({ length: 26 }, (_, n) => 224 f.wire('Carrots', `ordered_${n}`, base.created_at - 26 + n) 225 ); 226 f.begin( 227 'carrots', 228 values.map((value) => f.head(value)) 229 ); 230 expect(f.snapshot().rows.map((row) => row.state.head.id)).toEqual( 231 values 232 .toReversed() 233 .slice(0, 20) 234 .map((value) => value.id) 235 ); 236 }); 237 it('reserves at most two chronological windows even after clean EOSE', async () => { 238 const f = await fixture(), 239 token = f.begin(''); 240 for (let n = 0; n < 2; n++) { 241 search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }]); 242 f.channels[n].emit({ type: 'EOSE', id: 'fixture', from: f.origin }); 243 } 244 expect(() => 245 search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }]) 246 ).toThrow('food_search_chronological_window_limit'); 247 expect(f.provider).toHaveBeenCalledTimes(2); 248 expect(f.snapshot().definitiveAbsence).toBe(false); 249 }); 250 251 it('keeps a saturated source boundary even when another readable source returns an older head', async () => { 252 const f = await fixture(false, 2), 253 token = f.begin('carrots'); 254 search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }]); 255 const item = f.wire('Carrots', 'saturated', base.created_at), 256 older = f.wire('Carrots', 'other', base.created_at - 1); 257 for (let n = 0; n < 200; n++) f.emit(0, item); 258 f.channels[0].emit({ 259 type: 'EVENT', 260 id: 'fixture', 261 from: 'wss://source1.example.org', 262 event: older 263 }); 264 f.eose(0); 265 expect(f.snapshot().continuation.until).toBe(base.created_at); 266 search.chronologicalFoodSearch(token); 267 expect(f.provider.mock.calls.at(-1)![1]).toEqual([ 268 { kinds: [30402], limit: 200, until: base.created_at } 269 ]); 270 }); 271 it('uses only chronological verified times for the inclusive cursor despite earlier relevance samples', async () => { 272 const f = await fixture(true), 273 token = f.begin('carrots'); 274 search.sampleFoodSearch(token); 275 f.emit(0, f.wire('Carrots', 'sample', base.created_at - 100)); 276 f.channels[0].emit({ type: 'EOSE', id: 'sample', from: f.origin }); 277 const request = search.chronologicalFoodSearch(token); 278 f.emit(1, f.wire('Carrots', 'chronological', base.created_at)); 279 f.channels[1].emit({ type: 'EOSE', id: 'chronological', from: f.origin }); 280 expect(requests.publicRequestScopeSnapshot(request).state).toBe('eose'); 281 expect(f.snapshot().continuation.until).toBe(base.created_at); 282 search.chronologicalFoodSearch(token); 283 expect(f.provider.mock.calls.at(-1)![1]).toEqual([ 284 { kinds: [30402], limit: 200, until: base.created_at } 285 ]); 286 expect(() => 287 search.subscribeFoodSearch(token, [ 288 { kinds: [30402], limit: 200, until: base.created_at - 1 } 289 ]) 290 ).toThrow('food_search_chronological_filter'); 291 }); 292 it('shows another local20row page without opening a source and keeps the current generation', async () => { 293 const f = await fixture(), 294 heads = Array.from({ length: 26 }, (_, n) => 295 f.head(f.wire('Carrots', String(n))) 296 ); 297 const token = f.begin('carrots', heads), 298 first = f.snapshot(); 299 expect(first.rows).toHaveLength(20); 300 expect(first.hasMore).toBe(true); 301 const count = f.provider.mock.calls.length; 302 search.showMoreFoodSearch(token); 303 expect(f.provider).toHaveBeenCalledTimes(count); 304 const next = f.snapshot(); 305 expect(next.generation).toBe(token); 306 expect(next.rows).toHaveLength(26); 307 expect(next.hasMore).toBe(false); 308 }); 309 it('starts an explicit older successor run at the same inclusive boundary and preserves known results', async () => { 310 const f = await fixture(), 311 token = f.begin('carrots'); 312 search.chronologicalFoodSearch(token); 313 f.emit(0, f.wire()); 314 f.channels[0].emit({ type: 'EOSE', id: 'chronological', from: f.origin }); 315 const first = f.snapshot(); 316 expect(first.continuation.until).toBe(base.created_at); 317 const older = search.searchOlderFoodSearch(f.coordinator); 318 expect(older).not.toBe(token); 319 expect(() => search.showMoreFoodSearch(token)).toThrow( 320 'food_search_superseded' 321 ); 322 expect(f.provider.mock.calls.at(-1)![1]).toEqual([ 323 { kinds: [30402], limit: 200, until: base.created_at } 324 ]); 325 expect(f.snapshot()).toMatchObject({ 326 query: 'carrots', 327 generation: older, 328 definitiveAbsence: false 329 }); 330 expect(f.snapshot().rows).toHaveLength(1); 331 }); 332 it('requires the one-round sampler for relevance filters even after a completed sample', async () => { 333 const f = await fixture(true), 334 token = f.begin('carrots'); 335 search.sampleFoodSearch(token); 336 f.channels[0].emit({ type: 'EOSE', id: 'sample', from: f.origin }); 337 // A JavaScript caller can supply extra arguments despite the public type. 338 const unsafeSubscribe = search.subscribeFoodSearch as unknown as ( 339 run: typeof token, 340 filters: Parameters<typeof search.subscribeFoodSearch>[1], 341 source: string 342 ) => unknown; 343 expect(() => 344 unsafeSubscribe( 345 token, 346 [{ kinds: [30402], search: 'carrots', limit: 100 }], 347 f.origin 348 ) 349 ).toThrow('food_search_sample_required'); 350 expect(f.provider).toHaveBeenCalledTimes(1); 351 }); 352 it('locally rejects irrelevant or ignored relevance matches and accepts matching fallback evidence', async () => { 353 const f = await fixture(true), 354 token = f.begin('carrots'); 355 search.sampleFoodSearch(token); 356 f.emit( 357 0, 358 f.wire('Celery', 'irrelevant', base.created_at, 'Celery available') 359 ); 360 f.channels[0].emit({ type: 'EOSE', id: 'sample', from: f.origin }); 361 expect(f.snapshot().rows).toHaveLength(0); 362 const fallback = search.subscribeFoodSearch(token, [ 363 { kinds: [30402], limit: 200 } 364 ]); 365 expect(requests.publicRequestScopeSnapshot(fallback).state).toBe('active'); 366 f.emit(f.channels.length - 1, f.wire('Carrots', 'wanted')); 367 const snapshot = f.snapshot(); 368 expect(snapshot.rows).toHaveLength(1); 369 expect(snapshot.rows[0].state.food?.title).toBe('Carrots'); 370 expect(snapshot.rows[0].lastKnown).toBe(true); 371 expect(snapshot.definitiveAbsence).toBe(false); 372 expect('olderCursor' in snapshot).toBe(false); 373 }); 374 375 it('samples a qualified source once and leaves ordinary fallback available', async () => { 376 const f = await fixture(true), 377 token = f.begin(' CARROTS '); 378 const samples = search.sampleFoodSearch(token); 379 expect(samples).toHaveLength(1); 380 expect(f.provider.mock.calls[0][0]).toEqual([f.origin]); 381 expect(f.provider.mock.calls[0][1]).toEqual([ 382 { kinds: [30402], search: 'carrots', limit: 100 } 383 ]); 384 f.channels[0].emit({ type: 'EOSE', id: 'sample', from: f.origin }); 385 expect(f.snapshot()).toMatchObject({ 386 refresh: 'bounded-eose', 387 definitiveAbsence: false, 388 rows: [] 389 }); 390 expect(() => search.sampleFoodSearch(token)).toThrow( 391 'food_search_sample_round_limit' 392 ); 393 search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }]); 394 expect(f.provider.mock.calls[1][1]).toEqual([ 395 { kinds: [30402], limit: 200 } 396 ]); 397 expect(f.snapshot().run?.activeRequests).toBe(1); 398 }); 399 it('skips sampling for empty queries and unqualified sources without preventing fallback', async () => { 400 const f = await fixture(false), 401 token = f.begin('carrots'); 402 expect(search.sampleFoodSearch(token)).toEqual([]); 403 expect(f.provider).not.toHaveBeenCalled(); 404 const browse = f.begin(''); 405 expect(search.sampleFoodSearch(browse)).toEqual([]); 406 search.subscribeFoodSearch(browse, [{ kinds: [30402], limit: 200 }]); 407 expect(f.provider).toHaveBeenCalledTimes(1); 408 }); 409 it('records sample provider failure and still permits ordinary chronological discovery', async () => { 410 const f = await fixture(true), 411 token = f.begin('carrots'); 412 f.provider.mockImplementationOnce(() => { 413 throw new Error('isolated sample refused'); 414 }); 415 expect(search.sampleFoodSearch(token)).toEqual([]); 416 expect(f.snapshot()).toMatchObject({ 417 refresh: 'error', 418 definitiveAbsence: false 419 }); 420 search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }]); 421 expect(f.channels).toHaveLength(1); 422 expect(f.snapshot().run?.activeRequests).toBe(1); 423 }); 424 425 it('uses one coordinator per genuine view and refuses a changed clock owner', async () => { 426 const f = await fixture(); 427 expect(search.createFoodSearchCoordinator(f.view, f.wallClock)).toBe( 428 f.coordinator 429 ); 430 expect(() => 431 search.createFoodSearchCoordinator(f.view, { 432 nowSeconds: () => base.created_at + 10 433 }) 434 ).toThrow('food_search_clock_changed'); 435 }); 436 it('bounds primary scope history to one three-source sample round plus two chronological windows', async () => { 437 const f = await fixture(true, 3), 438 token = f.begin('carrots'); 439 search.sampleFoodSearch(token); 440 for (let i = 0; i < 3; i++) f.eose(i); 441 for (let i = 0; i < 2; i++) { 442 search.chronologicalFoodSearch(token); 443 f.eose(i + 3); 444 } 445 expect(() => search.chronologicalFoodSearch(token)).toThrow( 446 'food_search_chronological_window_limit' 447 ); 448 expect(f.channels).toHaveLength(5); 449 expect(f.snapshot().scopes).toHaveLength(5); 450 expect(f.snapshot().refresh).toBe('limit'); 451 }); 452 it('charges failed sample and chronological attempts before provider effects without unlimited retries', async () => { 453 const f = await fixture(true, 3), 454 token = f.begin('carrots'); 455 f.provider.mockImplementation(() => { 456 throw new Error('isolated provider failure'); 457 }); 458 expect(search.sampleFoodSearch(token)).toEqual([]); 459 for (let i = 0; i < 2; i++) 460 expect(() => search.chronologicalFoodSearch(token)).toThrow( 461 'food_search_request_failed' 462 ); 463 expect(f.provider).toHaveBeenCalledTimes(5); 464 expect(() => search.chronologicalFoodSearch(token)).toThrow( 465 'food_search_chronological_window_limit' 466 ); 467 expect(f.provider).toHaveBeenCalledTimes(5); 468 expect(f.channels).toHaveLength(0); 469 expect(f.snapshot().scopes).toHaveLength(0); 470 expect(f.snapshot().refresh).toBe('limit'); 471 }); 472 it('rejects invalid query before effects and preserves the current generation', async () => { 473 const f = await fixture(), 474 token = f.begin(' carrots '), 475 reads = f.reads(); 476 expect(() => f.begin('x'.repeat(513))).toThrow('query_too_long'); 477 expect(f.reads()).toBe(reads); 478 expect(f.snapshot()).toMatchObject({ 479 generation: token, 480 query: 'carrots', 481 definitiveAbsence: false 482 }); 483 }); 484 it('browses retained active heads and keeps source uncertainty explicit', async () => { 485 const f = await fixture(); 486 f.begin('', [f.head(), f.head()]); 487 expect(f.snapshot()).toMatchObject({ 488 query: '', 489 available: true, 490 refresh: 'refreshing', 491 definitiveAbsence: false 492 }); 493 expect(f.snapshot().rows).toHaveLength(1); 494 expect(f.snapshot().rows[0].lastKnown).toBe(true); 495 expect(f.channels).toHaveLength(2); 496 }); 497 it('bounds and validates the entire cached seed before changing the generation', async () => { 498 const f = await fixture(), 499 token = f.begin('carrots'), 500 h = f.head(), 501 reads = f.reads(); 502 expect(() => f.begin('', Array(2001).fill(h))).toThrow( 503 'head_query_input_limit' 504 ); 505 expect(() => f.begin('', [{} as typeof h])).toThrow('public_head_invalid'); 506 expect(f.reads()).toBe(reads); 507 expect(f.snapshot().generation).toBe(token); 508 }); 509 it('cancels superseded scopes and refuses an old handle while retaining known evidence', async () => { 510 const f = await fixture(), 511 first = f.begin('carrots', [f.head()]); 512 const second = f.begin('celery'); 513 expect(f.channels.slice(0, 2).every((c) => c.stopped())).toBe(true); 514 expect(() => search.foodSearchRequestOwner(first)).toThrow( 515 'food_search_superseded' 516 ); 517 f.emit(0, f.wire('Carrots', undefined, base.created_at + 2)); 518 f.emit(2, f.wire('Celery', undefined, base.created_at + 1)); 519 expect(f.snapshot().generation).toBe(second); 520 expect(f.snapshot().rows[0].state.food?.title).toBe('Celery'); 521 }); 522 it('cannot publish a generation superseded during an injected clock read', async () => { 523 const f = await fixture(); 524 f.begin('carrots', [f.head()]); 525 let armed = true; 526 f.reenter(() => { 527 if (armed) { 528 armed = false; 529 f.begin('celery'); 530 } 531 }); 532 expect(search.foodSearchSnapshot(f.coordinator)).toBeUndefined(); 533 expect(f.snapshot().query).toBe('celery'); 534 }); 535 it('shares all six scope slots with cached latest and deletion lookups', async () => { 536 const f = await fixture(true, 3), 537 token = f.begin('carrots', [f.head()]); 538 search.sampleFoodSearch(token); 539 search.chronologicalFoodSearch(token); 540 expect(f.snapshot().run?.activeRequests).toBe(6); 541 expect(() => 542 search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }]) 543 ).toThrow('food_search_chronological_pending'); 544 expect(f.snapshot().run?.activeRequests).toBe(6); 545 search.cancelFoodSearch(token); 546 expect(f.channels.every((c) => c.stopped())).toBe(true); 547 expect(f.timers.size).toBe(0); 548 expect(f.snapshot().rows).toHaveLength(1); 549 }); 550 it('truncates later requests at the original fifteen-second run deadline', async () => { 551 const f = await fixture(), 552 token = f.begin('', [f.head()]); 553 f.advance(8000); 554 const request = search.subscribeFoodSearch(token, [ 555 { kinds: [30402], limit: 200 } 556 ]); 557 expect(requests.publicRequestScopeSnapshot(request).deadline).toBe(15000); 558 f.advance(15000); 559 expect(f.snapshot()).toMatchObject({ 560 refresh: 'deadline', 561 run: { deadline: 15000, active: false }, 562 definitiveAbsence: false 563 }); 564 expect(f.snapshot().rows).toHaveLength(1); 565 expect(f.channels.every((c) => c.stopped())).toBe(true); 566 }); 567 it('charges duplicates and rejects across primary and auxiliary work to one two-thousand delivery cap', async () => { 568 const f = await fixture(), 569 token = f.begin('', [f.head()]); 570 search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }]); 571 const valid = f.wire(), 572 invalid = { ...valid, id: '0'.repeat(64) }; 573 for (let i = 0; i < 2000; i++) 574 f.emit(i % 2 === 0 ? 2 : 0, i < 1000 ? valid : invalid); 575 expect(f.snapshot().run?.ingress).toMatchObject({ 576 deliveries: 2000, 577 stopped: true 578 }); 579 expect(f.snapshot().refresh).toBe('limit'); 580 expect(f.channels.every((c) => c.stopped())).toBe(true); 581 expect(f.snapshot().rows).toHaveLength(1); 582 }); 583 it('charges rejected bytes across primary and auxiliary work to the same eight-MiB ceiling', async () => { 584 const f = await fixture(), 585 token = f.begin('', [f.head()]); 586 search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }]); 587 const invalid = { ...f.wire(), content: 'x'.repeat(128000) }; 588 for (let i = 0; i < 100 && !f.snapshot().run?.ingress.stopped; i++) 589 f.emit(i % 2 === 0 ? 2 : 0, invalid); 590 expect(f.snapshot().run?.ingress).toMatchObject({ 591 chargedBytes: 8388608, 592 stopped: true 593 }); 594 expect(f.snapshot().run!.ingress.deliveries).toBeLessThan(2000); 595 expect(f.snapshot().refresh).toBe('limit'); 596 expect(f.snapshot().rows).toHaveLength(1); 597 }); 598 it('materializes a newly discovered cached coordinate after deadline without starting new requests', async () => { 599 const f = await fixture(), 600 token = f.begin(''); 601 search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }]); 602 f.emit(0, f.wire('New carrots', 'fresh-coordinate')); 603 f.advance(15000); 604 const count = f.channels.length, 605 row = f.snapshot().rows[0]; 606 expect(row.state.food?.title).toBe('New carrots'); 607 expect(row).toMatchObject({ 608 coverage: 'partial', 609 lastKnown: true, 610 definitiveAbsence: false 611 }); 612 expect(f.channels).toHaveLength(count); 613 }); 614 it('retains bounded results despite relay closure and never exposes global completeness', async () => { 615 const f = await fixture(), 616 token = f.begin('', [f.head()]); 617 search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }]); 618 for (const channel of f.channels) 619 channel.emit({ 620 type: 'CLOSED', 621 id: 'fixture', 622 from: f.origin, 623 reason: 'unavailable' 624 }); 625 const snapshot = f.snapshot(); 626 expect(snapshot.rows).toHaveLength(1); 627 expect(snapshot.refresh).toBe('partial'); 628 expect(snapshot.definitiveAbsence).toBe(false); 629 expect(Object.hasOwn(snapshot, 'complete')).toBe(false); 630 }); 631 it('disposes the owned view and denies further query effects', async () => { 632 const f = await fixture(); 633 f.begin('', [f.head()]); 634 search.closeFoodSearchCoordinator(f.coordinator); 635 expect(search.foodSearchSnapshot(f.coordinator)).toBeUndefined(); 636 expect(() => f.begin('')).toThrow('food_search_closed'); 637 expect(f.channels.every((c) => c.stopped())).toBe(true); 638 }); 639 });