commit 4727549eea1c61d928ded372b5d3e5163f81656a
parent 4eb1cf0b7598ea32be41c795d771a089e09a0da2
Author: triesap <tyson@radroots.org>
Date: Tue, 6 Oct 2026 15:42:19 +0000
availability: Implement the finite search-run coordinator (HCP-039)
- Bind immutable query generations to genuine public view and run owners.
- Share bounded primary and auxiliary admission while retaining known matches.
- Reject stale clock reentry and allow inactive projection of cached proof.
- Verify cancellation, work limits, finite attempts, and actual SDK discovery.
Diffstat:
9 files changed, 1168 insertions(+), 10 deletions(-)
diff --git a/web/src/lib/catalog/resolve-head.ts b/web/src/lib/catalog/resolve-head.ts
@@ -75,7 +75,7 @@ export interface KnownHeadSource {
}
interface Owner {
readonly available: () => boolean;
- readonly resolve: (heads: readonly PublicHead[]) => void;
+ readonly resolve: (heads: readonly PublicHead[], lookup: boolean) => void;
readonly snapshot: () => readonly HeadResolution[];
readonly close: () => void;
}
@@ -243,8 +243,11 @@ export function createHeadResolver(
}
owners.set(token, {
available: retained,
- resolve(heads) {
- if (!active()) throw new Error('head_resolver_inactive');
+ resolve(heads, lookup) {
+ if (closed || (lookup && !active()))
+ throw new Error('head_resolver_inactive');
+ if (!lookup && active()) throw new Error('head_resolver_still_active');
+ if (!lookup && !known) throw new Error('head_resolver_known_required');
// Validate the complete batch and total coordinate admission before any
// external clock/request callback. Repeated coordinates never reset work.
headResolutionQueries(heads);
@@ -281,7 +284,7 @@ export function createHeadResolver(
publicHeadEnvelope(mergeKnown(head))
);
}
- if (group && active()) group.open();
+ if (lookup && group && active()) group.open();
},
snapshot() {
if (!retained()) {
@@ -379,7 +382,15 @@ export function resolveHeads(
resolver: HeadResolver,
heads: readonly PublicHead[]
): void {
- ownerOf(resolver).resolve(heads);
+ ownerOf(resolver).resolve(heads, true);
+}
+// Only previously retained proof may seed an ended run's partial projection.
+// The known-source admission owner validates the complete batch before changes.
+export function resolveKnownHeads(
+ resolver: HeadResolver,
+ heads: readonly PublicHead[]
+): void {
+ ownerOf(resolver).resolve(heads, false);
}
export function headResolutionSnapshot(
resolver: HeadResolver
diff --git a/web/src/lib/catalog/search-run.ts b/web/src/lib/catalog/search-run.ts
@@ -0,0 +1,382 @@
+import {
+ PUBLIC_QUERY_BUDGETS,
+ PUBLIC_SEARCH_RUN_BUDGETS
+} from '../config/budgets.ts';
+import type { PublicFilter } from '../nostr/exports.ts';
+import { headResolutionQueries } from '../nostr/product-queries.ts';
+import {
+ publicRunSnapshot,
+ publicRequestScopeSnapshot,
+ closePublicRequest,
+ cancelPublicRun,
+ type PublicRun,
+ type PublicRequest
+} from '../nostr/request-scope.ts';
+import {
+ beginPublicViewRun,
+ publicViewRunCurrent,
+ publicViewProjectionAvailable,
+ subscribePublicView,
+ disposePublicView,
+ type PublicView
+} from '../runtime/public-runtime.ts';
+import {
+ createPublicHeadCandidate,
+ publicHeadKey,
+ publicHeadSnapshot,
+ selectPublicHead,
+ type PublicHead
+} from './heads.ts';
+import { normalizePublicQuery } from './query-input.ts';
+import {
+ createPublicViewHeadResolver,
+ resolveHeads,
+ resolveKnownHeads,
+ headResolutionSnapshot,
+ type HeadResolver
+} from './resolve-head.ts';
+import { searchResolvedFood } from './search-match.ts';
+import {
+ searchRefreshState,
+ type SearchScope,
+ type SearchSnapshot
+} from './search-state.ts';
+import type { WallClock } from './clock-policy.ts';
+declare const coordinatorBrand: unique symbol;
+declare const generationBrand: unique symbol;
+export type FoodSearchCoordinator = Readonly<{
+ readonly [coordinatorBrand]: true;
+}>;
+export type FoodSearchRun = Readonly<{ readonly [generationBrand]: true }>;
+interface Coordinator {
+ readonly view: PublicView;
+ readonly clock: WallClock;
+ readonly current: () => FoodSearchRun | undefined;
+ readonly reserve: (token: FoodSearchRun) => void;
+ readonly closed: () => boolean;
+ readonly close: () => void;
+}
+interface Session {
+ readonly coordinator: Coordinator;
+ readonly token: FoodSearchRun;
+ readonly query: string;
+ readonly heads: () => readonly PublicHead[];
+ readonly pending: () => readonly PublicHead[];
+ readonly resolved: (heads: readonly PublicHead[]) => void;
+ readonly remember: (head: PublicHead) => boolean;
+ readonly requests: () => readonly PublicRequest[];
+ readonly track: (request: PublicRequest) => void;
+ readonly reserveSource: () => void;
+ readonly run: () => PublicRun | undefined;
+ readonly bindRun: (run: PublicRun) => void;
+ readonly model: () => HeadResolver | undefined;
+ readonly bindModel: (model: HeadResolver) => void;
+ readonly flags: () => Readonly<{
+ cancelled: boolean;
+ failed: boolean;
+ capped: boolean;
+ }>;
+ readonly fail: () => void;
+ readonly cancel: () => void;
+}
+const coordinators = new WeakMap<FoodSearchCoordinator, Coordinator>();
+const viewCoordinators = new WeakMap<
+ PublicView,
+ Readonly<{ clock: WallClock; token: FoodSearchCoordinator }>
+>();
+const sessions = new WeakMap<FoodSearchRun, Session>();
+function coordinatorOf(token: FoodSearchCoordinator): Coordinator {
+ const owner = coordinators.get(token);
+ if (!owner) throw new Error('food_search_coordinator_invalid');
+ return owner;
+}
+function sessionOf(token: FoodSearchRun): Session {
+ const session = sessions.get(token);
+ if (!session) throw new Error('food_search_invalid');
+ return session;
+}
+function current(session: Session): boolean {
+ return (
+ !session.coordinator.closed() &&
+ session.coordinator.current() === session.token
+ );
+}
+function requireCurrent(session: Session): void {
+ if (!current(session)) throw new Error('food_search_superseded');
+}
+// All mutation stays in lexical plain-model owners; callers get opaque handles
+// and detached snapshots, never map-returned mutable records or SDK objects.
+function createSession(
+ coordinator: Coordinator,
+ token: FoodSearchRun,
+ query: string,
+ seed: readonly PublicHead[],
+ fallback: HeadResolver | undefined
+): Session {
+ const heads = new Map(seed.map((head) => [publicHeadKey(head), head]));
+ const resolved = new Map<string, true>();
+ const requests = new Map<PublicRequest, true>();
+ let run: PublicRun | undefined,
+ model = fallback;
+ let cancelled = false,
+ failed = false,
+ capped = false;
+ let attempts = 0;
+ return {
+ coordinator,
+ token,
+ query,
+ heads: () => Array.from(heads.values()),
+ pending: () =>
+ Array.from(heads.values()).filter(
+ (head) => !resolved.has(publicHeadKey(head))
+ ),
+ resolved: (values) => {
+ for (const head of values) resolved.set(publicHeadKey(head), true);
+ },
+ remember(head) {
+ const key = publicHeadKey(head);
+ if (
+ !heads.has(key) &&
+ heads.size >= PUBLIC_QUERY_BUDGETS.coordinatesPerRun
+ ) {
+ capped = true;
+ return false;
+ }
+ heads.set(key, selectPublicHead(heads.get(key), head).head);
+ return true;
+ },
+ requests: () => Array.from(requests.keys()),
+ track: (request) => {
+ requests.set(request, true);
+ },
+ reserveSource() {
+ if (attempts >= PUBLIC_SEARCH_RUN_BUDGETS.primaryScopes) {
+ capped = true;
+ throw new Error('food_search_primary_limit');
+ }
+ attempts++;
+ },
+ run: () => run,
+ bindRun: (value) => {
+ run = value;
+ },
+ model: () => model,
+ bindModel: (value) => {
+ model = value;
+ },
+ flags: () => ({ cancelled, failed, capped }),
+ fail: () => {
+ failed = true;
+ },
+ cancel() {
+ cancelled = true;
+ if (run) cancelPublicRun(run);
+ }
+ };
+}
+export function createFoodSearchCoordinator(
+ view: PublicView,
+ clock: WallClock
+): FoodSearchCoordinator {
+ publicViewProjectionAvailable(view);
+ if (typeof clock.nowSeconds !== 'function')
+ throw new Error('food_search_clock_invalid');
+ const existing = viewCoordinators.get(view);
+ if (existing) {
+ if (existing.clock !== clock) throw new Error('food_search_clock_changed');
+ return existing.token;
+ }
+ const token = Object.freeze({}) as FoodSearchCoordinator;
+ let generation: FoodSearchRun | undefined,
+ closed = false;
+ coordinators.set(token, {
+ view,
+ clock,
+ current: () => generation,
+ reserve: (value) => {
+ generation = value;
+ },
+ closed: () => closed,
+ close() {
+ closed = true;
+ // Preserve failed cleanup controls; repeated disposal retries the view.
+ disposePublicView(view);
+ generation = undefined;
+ }
+ });
+ viewCoordinators.set(view, { clock, token });
+ return token;
+}
+export function beginFoodSearch(
+ coordinator: FoodSearchCoordinator,
+ input: unknown,
+ known: readonly PublicHead[] = []
+): FoodSearchRun {
+ const owner = coordinatorOf(coordinator);
+ if (owner.closed()) throw new Error('food_search_closed');
+ const query = normalizePublicQuery(input);
+ if (!query.ok) throw new Error(query.error);
+ // Complete seed validation precedes clocks, cache and run effects.
+ headResolutionQueries(known);
+ const previousToken = owner.current();
+ const previous =
+ previousToken === undefined ? undefined : sessionOf(previousToken);
+ const heads = new Map(
+ previous?.heads().map((head) => [publicHeadKey(head), head])
+ );
+ for (const head of known) {
+ const key = publicHeadKey(head);
+ heads.set(key, selectPublicHead(heads.get(key), head).head);
+ }
+ if (heads.size > PUBLIC_QUERY_BUDGETS.coordinatesPerRun)
+ throw new Error('head_resolver_coordinate_limit');
+ const token = Object.freeze({}) as FoodSearchRun;
+ const seed = Array.from(heads.values());
+ const session = createSession(
+ owner,
+ token,
+ query.text,
+ seed,
+ previous?.model()
+ );
+ sessions.set(token, session);
+ owner.reserve(token); // Reserve before previous settlement or injected clocks.
+ try {
+ const run = beginPublicViewRun(owner.view);
+ session.bindRun(run);
+ requireCurrent(session);
+ const model = createPublicViewHeadResolver(owner.view, run, owner.clock);
+ session.bindModel(model);
+ requireCurrent(session);
+ session.resolved(seed);
+ if (seed.length) resolveHeads(model, seed);
+ requireCurrent(session);
+ return token;
+ } catch {
+ if (!current(session)) throw new Error('food_search_superseded');
+ session.fail();
+ const run = session.run();
+ if (run) {
+ try {
+ cancelPublicRun(run);
+ } catch {
+ /* Still owned, retryable. */
+ }
+ }
+ throw new Error('food_search_start_failed');
+ }
+}
+export function foodSearchRequestOwner(token: FoodSearchRun): PublicRun {
+ const session = sessionOf(token);
+ requireCurrent(session);
+ const run = session.run();
+ if (!run || !publicViewRunCurrent(session.coordinator.view, run))
+ throw new Error('food_search_inactive');
+ requireCurrent(session);
+ return run;
+}
+// Filter strategies remain separate; primary sources and all auxiliaries share
+// one genuine anonymous run rather than creating transport or budget owners.
+export function subscribeFoodSearch(
+ token: FoodSearchRun,
+ filters: readonly PublicFilter[]
+): PublicRequest {
+ const session = sessionOf(token),
+ run = foodSearchRequestOwner(token);
+ session.reserveSource(); // Reservation precedes SDK effects and never refunds.
+ let request: PublicRequest;
+ try {
+ request = subscribePublicView(
+ session.coordinator.view,
+ run,
+ 'search',
+ filters,
+ (proof) => {
+ // Admission already includes a valid inclusive tail that stopped ingress.
+ if (!current(session)) return;
+ const head = createPublicHeadCandidate(proof);
+ if (!head || publicHeadSnapshot(head).kind !== 30402) return;
+ if (!session.remember(head)) cancelPublicRun(run);
+ }
+ );
+ } catch {
+ if (current(session)) session.fail();
+ throw new Error('food_search_request_failed');
+ }
+ session.track(request);
+ if (!current(session)) {
+ closePublicRequest(request);
+ throw new Error('food_search_superseded');
+ }
+ return request;
+}
+export function foodSearchSnapshot(
+ coordinator: FoodSearchCoordinator
+): SearchSnapshot<FoodSearchRun> | undefined {
+ const owner = coordinatorOf(coordinator),
+ token = owner.current();
+ if (owner.closed() || token === undefined) return undefined;
+ const session = sessionOf(token),
+ model = session.model(),
+ ownedRun = session.run();
+ if (ownedRun && model) {
+ const active = publicViewRunCurrent(owner.view, ownedRun);
+ if (!current(session)) return undefined;
+ const pending = session.pending();
+ if (pending.length) {
+ try {
+ if (active) resolveHeads(model, pending);
+ else resolveKnownHeads(model, pending);
+ session.resolved(pending);
+ } catch {
+ session.fail();
+ }
+ }
+ }
+ const raw = model ? headResolutionSnapshot(model) : [];
+ const matched = model ? searchResolvedFood(model, session.query) : undefined;
+ const scopes = new Map<object, SearchScope>();
+ for (const request of session.requests()) {
+ const scope = publicRequestScopeSnapshot(request);
+ scopes.set(scope.result.context, scope);
+ }
+ for (const row of raw)
+ for (const scope of [row.headSources, row.deletionSources])
+ if (scope) scopes.set(scope.result.context, scope);
+ const available =
+ publicViewProjectionAvailable(owner.view) &&
+ (matched?.ok ? matched.available : true);
+ const run = ownedRun ? publicRunSnapshot(ownedRun) : undefined;
+ // Model/run clocks may synchronously supersede or dispose this generation.
+ if (!current(session)) return undefined;
+ const sources = Array.from(scopes.values()),
+ flags = session.flags();
+ return {
+ generation: token,
+ query: session.query,
+ refresh: searchRefreshState(
+ available,
+ run,
+ sources,
+ flags.cancelled,
+ flags.failed,
+ flags.capped
+ ),
+ available,
+ rows: available && matched?.ok ? matched.rows : [],
+ scopes: sources,
+ run,
+ definitiveAbsence: false
+ };
+}
+export function cancelFoodSearch(token: FoodSearchRun): void {
+ const session = sessionOf(token);
+ requireCurrent(session);
+ session.cancel();
+}
+export function closeFoodSearchCoordinator(
+ coordinator: FoodSearchCoordinator
+): void {
+ coordinatorOf(coordinator).close();
+}
diff --git a/web/src/lib/catalog/search-state.ts b/web/src/lib/catalog/search-state.ts
@@ -0,0 +1,45 @@
+import type {
+ publicRunSnapshot,
+ publicRequestScopeSnapshot
+} from '../nostr/request-scope.ts';
+import type { HeadResolution } from './resolve-head.ts';
+export type SearchScope = ReturnType<typeof publicRequestScopeSnapshot>;
+export type SearchRefresh =
+ | 'idle'
+ | 'refreshing'
+ | 'bounded-eose'
+ | 'partial'
+ | 'cancelled'
+ | 'deadline'
+ | 'limit'
+ | 'error'
+ | 'unavailable';
+export type SearchSnapshot<Generation> = Readonly<{
+ generation: Generation;
+ query: string;
+ refresh: SearchRefresh;
+ available: boolean;
+ rows: readonly HeadResolution[];
+ scopes: readonly SearchScope[];
+ run: ReturnType<typeof publicRunSnapshot> | undefined;
+ definitiveAbsence: false;
+}>;
+// A completed bounded set never proves global completeness or absence.
+export function searchRefreshState(
+ available: boolean,
+ run: SearchSnapshot<unknown>['run'],
+ scopes: readonly SearchScope[],
+ cancelled: boolean,
+ failed: boolean,
+ capped: boolean
+): SearchRefresh {
+ if (!available) return 'unavailable';
+ if (capped || run?.ingress.stopped) return 'limit';
+ if (cancelled) return 'cancelled';
+ if (failed) return 'error';
+ if (run?.activeRequests) return 'refreshing';
+ if (scopes.some((scope) => scope.state === 'deadline')) return 'deadline';
+ if (scopes.some((scope) => scope.state !== 'eose')) return 'partial';
+ if (scopes.length > 0) return 'bounded-eose';
+ return run?.active ? 'idle' : 'partial';
+}
diff --git a/web/src/lib/config/budgets.ts b/web/src/lib/config/budgets.ts
@@ -1,6 +1,10 @@
// Browser relay scopes are independent; these are application admission caps,
// not a DNS policy, native transport limit or browser memory guarantee.
-export const RELAY_BUDGETS = Object.freeze({ public: 3, inbox: 3 });
+const publicRelayLimit = 3;
+export const RELAY_BUDGETS = Object.freeze({
+ public: publicRelayLimit,
+ inbox: 3
+});
// Approved public-run admission limits shared by all primary/auxiliary sources.
// Logical post-parse work accounting; no WebSocket preallocation guarantee.
@@ -36,3 +40,12 @@ export const PUBLIC_SEARCH_BUDGETS = Object.freeze({
queryBytes: 512,
terms: 12
});
+
+// One NIP-50 round may select each of the three qualified sources separately;
+// chronological discovery has two group windows. Count failed attempts too.
+const publicChronologicalWindows = 2;
+export const PUBLIC_SEARCH_RUN_BUDGETS = Object.freeze({
+ nip50Rounds: 1,
+ chronologicalWindows: publicChronologicalWindows,
+ primaryScopes: publicRelayLimit + publicChronologicalWindows
+});
diff --git a/web/src/lib/runtime/public-runtime.ts b/web/src/lib/runtime/public-runtime.ts
@@ -12,6 +12,7 @@ import {
closePublicStore,
publicStoreRetention,
publicStoreKnownEvidence,
+ publicStoreEnvelope,
type PublicStore
} from '../nostr/public-store.ts';
import {
@@ -28,7 +29,11 @@ import {
type RequestClock
} from '../nostr/request-scope.ts';
import type { PublicFilter } from '../nostr/exports.ts';
-import { publicHeadEnvelope, type PublicHead } from '../catalog/heads.ts';
+import {
+ publicHeadEnvelope,
+ publicHeadSnapshot,
+ type PublicHead
+} from '../catalog/heads.ts';
import type { KnownPublicEvidence } from '../catalog/retention.ts';
import type { VerifiedEnvelope } from '../nostr/verified-envelope.ts';
declare const contextBrand: unique symbol;
@@ -260,7 +265,19 @@ export function createPublicView(runtime: PublicRuntime): PublicView {
!shared.projectionValid()
)
throw new Error('public_view_run_superseded');
- run = createPublicRun(shared.scheduler, shared.policy);
+ const candidate = createPublicRun(shared.scheduler, shared.policy);
+ // Run creation samples the injected clock. It may synchronously start a
+ // newer view generation before returning; never overwrite that owner.
+ if (
+ operation !== generation ||
+ disposed ||
+ shared.closed() ||
+ !shared.projectionValid()
+ ) {
+ disposePublicRun(candidate);
+ throw new Error('public_view_run_superseded');
+ }
+ run = candidate;
return run;
},
settling: () => settling,
@@ -357,8 +374,20 @@ export function retainPublicViewHeads(
heads: readonly PublicHead[]
): boolean {
const owner = viewOf(view);
- if (!publicViewRunCurrent(view, run) || !owner.runtime.projectionValid())
- return false;
+ if (!owner.current(run) || !owner.runtime.projectionValid()) return false;
+ const active = publicRunSnapshot(run).active;
+ if (!owner.current(run) || !owner.runtime.projectionValid()) return false;
+ if (!active) {
+ // Inactive materialization cannot install or charge another event. Require
+ // every genuine head to have already passed the shared retained cache.
+ for (const head of heads) {
+ if (
+ !publicStoreEnvelope(owner.runtime.store, publicHeadSnapshot(head).id)
+ )
+ throw new Error('public_view_uncached_head');
+ }
+ return owner.current(run) && owner.runtime.projectionValid();
+ }
for (const head of heads) {
const result = insertPublicEnvelope(
owner.runtime.store,
diff --git a/web/tests/integration/search-run.test.ts b/web/tests/integration/search-run.test.ts
@@ -0,0 +1,186 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { once } from 'node:events';
+import { readFile } from 'node:fs/promises';
+import { finalizeEvent } from 'applesauce-core/helpers';
+import WebSocket, { WebSocketServer } from 'ws';
+import { validateRelayPolicy } from '../../src/lib/config/relays.ts';
+import {
+ createPublicRuntimeContext,
+ mountPublicRuntime,
+ createPublicView,
+ closePublicRuntime
+} from '../../src/lib/runtime/public-runtime.ts';
+import {
+ createFoodSearchCoordinator,
+ beginFoodSearch,
+ subscribeFoodSearch,
+ foodSearchSnapshot,
+ cancelFoodSearch
+} from '../../src/lib/catalog/search-run.ts';
+
+await test('actual SDK finite discovery shares latest/deletion budgets and replaces an old local match with suppressed newest evidence', async () => {
+ const corpus = JSON.parse(
+ await readFile(
+ new URL(
+ '../../../contracts/interop/food_availability/corpus.v1.json',
+ import.meta.url
+ ),
+ 'utf8'
+ )
+ ) as { vectors: { id: string; signed_wires: Record<string, string> }[] };
+ const base = JSON.parse(
+ corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous
+ ) as { tags: string[][]; content: string; created_at: number };
+ const key = crypto.getRandomValues(new Uint8Array(32));
+ const previous = finalizeEvent(
+ {
+ kind: 30402,
+ created_at: base.created_at,
+ tags: base.tags,
+ content: base.content
+ },
+ key
+ );
+ const current = finalizeEvent(
+ {
+ kind: 30402,
+ created_at: base.created_at + 1,
+ tags: base.tags.map((t) =>
+ t[0] === 'status'
+ ? ['status', 'sold']
+ : t[0] === 'title'
+ ? ['title', 'Renamed celery']
+ : [...t]
+ ),
+ content: base.content
+ },
+ key
+ );
+ const deletion = finalizeEvent(
+ {
+ kind: 5,
+ created_at: base.created_at - 1,
+ tags: [['e', current.id]],
+ content: ''
+ },
+ key
+ );
+ key.fill(0);
+ const origin = 'wss://one.example.org',
+ server = new WebSocketServer({
+ host: '127.0.0.1',
+ port: 0,
+ maxPayload: 4096
+ });
+ const sockets: WebSocket[] = [];
+ const filters: Record<string, unknown>[] = [];
+ let sent = () => {};
+ const sentBoth = new Promise<void>((resolve) => {
+ sent = resolve;
+ });
+ server.on('connection', (socket) => {
+ sockets.push(socket);
+ socket.on('message', (bytes) => {
+ const buffer = Array.isArray(bytes)
+ ? Buffer.concat(bytes)
+ : Buffer.isBuffer(bytes)
+ ? bytes
+ : Buffer.from(bytes);
+ const frame = JSON.parse(buffer.toString('utf8')) as unknown[];
+ if (frame[0] !== 'REQ') return;
+ const id = String(frame[1]),
+ query = frame[2] as Record<string, unknown>;
+ filters.push(query);
+ const values =
+ (query.kinds as number[])[0] === 30402
+ ? query.authors === undefined
+ ? [previous]
+ : [current]
+ : [deletion];
+ for (const value of values)
+ socket.send(JSON.stringify(['EVENT', id, value]));
+ socket.send(JSON.stringify(['EOSE', id]));
+ if (filters.length === 1) sent();
+ });
+ });
+ await once(server, 'listening');
+ const address = server.address();
+ assert.ok(address && typeof address !== 'string');
+ const port = address.port;
+ const oldWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'),
+ oldSocket = globalThis.WebSocket;
+ class FixtureSocket extends WebSocket {
+ constructor(url: string | URL) {
+ assert.equal(String(url).replace(/\/$/, ''), origin);
+ super(`ws://127.0.0.1:${port}`);
+ }
+ }
+ Object.defineProperty(globalThis, 'window', {
+ configurable: true,
+ value: {}
+ });
+ globalThis.WebSocket =
+ FixtureSocket as unknown as typeof globalThis.WebSocket;
+ const context = createPublicRuntimeContext();
+ try {
+ const policy = validateRelayPolicy(
+ JSON.stringify({
+ schemaVersion: 1,
+ public: [{ origin, read: true, write: false, nip50: false }],
+ inbox: [],
+ postingEnabled: false,
+ messagingEnabled: false,
+ operatorDenylist: []
+ })
+ )!;
+ const runtime = mountPublicRuntime(context, policy)!;
+ const view = createPublicView(runtime);
+ const coordinator = createFoodSearchCoordinator(view, {
+ nowSeconds: () => base.created_at + 10
+ });
+ const generation = beginFoodSearch(coordinator, '');
+ subscribeFoodSearch(generation, [{ kinds: [30402], limit: 200 }]);
+ await sentBoth;
+ for (
+ let n = 0;
+ n < 100 && foodSearchSnapshot(coordinator)?.refresh !== 'bounded-eose';
+ n++
+ )
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ assert.equal(filters.length, 3);
+ const head = filters.find(
+ (q) => (q.kinds as number[])[0] === 30402 && q.authors !== undefined
+ )!;
+ const requests = filters.find((q) => (q.kinds as number[])[0] === 5)!;
+ assert.deepEqual(head.authors, [previous.pubkey]);
+ assert.deepEqual(head['#d'], [base.tags.find((t) => t[0] === 'd')![1]]);
+ assert.deepEqual(requests.authors, [previous.pubkey]);
+ for (const q of filters) {
+ assert.equal(q.limit, 200);
+ assert.equal('q' in q, false);
+ assert.equal('search' in q, false);
+ assert.equal('since' in q, false);
+ assert.equal('#k' in q, false);
+ }
+ const snapshot = foodSearchSnapshot(coordinator)!;
+ assert.equal(snapshot.query, '');
+ assert.equal(snapshot.refresh, 'bounded-eose');
+ assert.equal(snapshot.rows.length, 0);
+ assert.equal(snapshot.definitiveAbsence, false);
+ assert.equal(snapshot.run?.ingress.deliveries, 3);
+ assert.equal(snapshot.run?.activeRequests, 0);
+ assert.equal(snapshot.scopes.length, 3);
+ cancelFoodSearch(generation);
+ } finally {
+ closePublicRuntime(context);
+ key.fill(0);
+ globalThis.WebSocket = oldSocket;
+ if (oldWindow) Object.defineProperty(globalThis, 'window', oldWindow);
+ else delete (globalThis as { window?: unknown }).window;
+ for (const socket of sockets) socket.terminate();
+ await new Promise<void>((resolve, reject) =>
+ server.close((error) => (error ? reject(error) : resolve()))
+ );
+ }
+});
diff --git a/web/tests/unit/public-runtime.test.ts b/web/tests/unit/public-runtime.test.ts
@@ -10,6 +10,33 @@ afterEach(() => {
vi.unstubAllGlobals();
});
describe('root public runtime context', () => {
+ it('reserves the view generation across synchronous run-creation clock reentry', () => {
+ vi.stubGlobal('window', {});
+ const context = runtime.createPublicRuntimeContext();
+ let armed = false;
+ let inner: ReturnType<typeof runtime.beginPublicViewRun> | undefined;
+ const owner = runtime.mountPublicRuntime(context, undefined, {
+ now: () => {
+ if (armed) {
+ armed = false;
+ inner = runtime.beginPublicViewRun(view);
+ }
+ return 0;
+ },
+ schedule: () => () => {}
+ })!;
+ const view = runtime.createPublicView(owner);
+ armed = true;
+ try {
+ expect(() => runtime.beginPublicViewRun(view)).toThrow(
+ 'public_view_run_superseded'
+ );
+ expect(inner).toBeDefined();
+ expect(runtime.publicViewRunCurrent(view, inner!)).toBe(true);
+ } finally {
+ runtime.closePublicRuntime(context);
+ }
+ });
it('creates an inert SSR context without acquiring browser capabilities', () => {
vi.stubGlobal('window', undefined);
const context = runtime.createPublicRuntimeContext();
diff --git a/web/tests/unit/resolve-head.test.ts b/web/tests/unit/resolve-head.test.ts
@@ -15,16 +15,25 @@ import {
} from '../../src/lib/nostr/request-scope.ts';
import {
createPublicHeadCandidate,
+ publicHeadEnvelope,
+ publicHeadSnapshot,
publicHeadKey
} from '../../src/lib/catalog/heads.ts';
import { headResolutionQueries } from '../../src/lib/nostr/product-queries.ts';
import {
createHeadResolver,
resolveHeads,
+ resolveKnownHeads,
headResolutionSnapshot,
closeHeadResolver,
type HeadSubscriber
} from '../../src/lib/catalog/resolve-head.ts';
+import {
+ createPublicRetention,
+ retainPublicEnvelope,
+ publicRetentionEnvelope,
+ publicRetentionKnown
+} from '../../src/lib/catalog/retention.ts';
const corpus = JSON.parse(
readFileSync(
@@ -140,6 +149,89 @@ function fixture() {
};
}
describe('bounded exact-coordinate head resolution', () => {
+ it('materializes already retained heads after the run ends without opening a new request', () => {
+ const f = fixture(),
+ retention = createPublicRetention();
+ retainPublicEnvelope(retention, publicHeadEnvelope(f.initial));
+ let opened = 0;
+ const known = createHeadResolver(
+ f.run,
+ () => {
+ opened++;
+ throw Error('inactive request');
+ },
+ { nowSeconds: () => base.created_at + 10 },
+ {
+ retain: (heads) => {
+ if (
+ heads.some(
+ (h) =>
+ !publicRetentionEnvelope(retention, publicHeadSnapshot(h).id)
+ )
+ )
+ throw Error('cache_missing');
+ return true;
+ },
+ read: (h) => publicRetentionKnown(retention, h),
+ available: () => true
+ }
+ );
+ f.advance(15000);
+ resolveKnownHeads(known, [f.initial]);
+ expect(headResolutionSnapshot(known)[0]).toMatchObject({
+ lastKnown: true,
+ coverage: 'partial',
+ definitiveAbsence: false
+ });
+ expect(headResolutionSnapshot(known)[0].state.food).toBeDefined();
+ const target = publicHeadSnapshot(f.initial).id;
+ const deletion = f.proof(f.event(base.created_at, [['e', target]], '', 5));
+ retainPublicEnvelope(retention, deletion);
+ expect(headResolutionSnapshot(known)[0].deletion.outcome).toBe(
+ 'suppressed'
+ );
+ expect(headResolutionSnapshot(known)[0].state.food).toBeUndefined();
+ expect(opened).toBe(0);
+ });
+ it('denies unretained proof in an inactive projection before changing its known rows', () => {
+ const f = fixture(),
+ retention = createPublicRetention();
+ retainPublicEnvelope(retention, publicHeadEnvelope(f.initial));
+ const known = createHeadResolver(
+ f.run,
+ () => {
+ throw Error('inactive request');
+ },
+ { nowSeconds: () => base.created_at + 10 },
+ {
+ retain: (heads) => {
+ if (
+ heads.some(
+ (h) =>
+ !publicRetentionEnvelope(retention, publicHeadSnapshot(h).id)
+ )
+ )
+ throw Error('cache_missing');
+ return true;
+ },
+ read: (h) => publicRetentionKnown(retention, h),
+ available: () => true
+ }
+ );
+ expect(() => resolveKnownHeads(known, [f.initial])).toThrow(
+ 'head_resolver_still_active'
+ );
+ f.advance(15000);
+ resolveKnownHeads(known, [f.initial]);
+ const other = f.head(
+ f.event(
+ base.created_at,
+ base.tags.map((t) => (t[0] === 'd' ? ['d', 'uncached'] : [...t]))
+ )
+ );
+ expect(() => resolveKnownHeads(known, [other])).toThrow('cache_missing');
+ expect(headResolutionSnapshot(known)).toHaveLength(1);
+ });
it('batches unique exact coordinates and author deletion lookups without keyword constraints', () => {
const f = fixture(),
other = f.head(
diff --git a/web/tests/unit/search-run.test.ts b/web/tests/unit/search-run.test.ts
@@ -0,0 +1,373 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { finalizeEvent } from 'applesauce-core/helpers';
+import type { PublicPoolMessage } from '../../src/lib/nostr/exports.ts';
+import type { RequestClock } from '../../src/lib/nostr/request-scope.ts';
+let search: typeof import('../../src/lib/catalog/search-run.ts');
+let runtime: typeof import('../../src/lib/runtime/public-runtime.ts');
+let requests: typeof import('../../src/lib/nostr/request-scope.ts');
+let context: ReturnType<typeof runtime.createPublicRuntimeContext>;
+const keys: Uint8Array[] = [];
+beforeEach(async () => {
+ vi.resetModules();
+ vi.stubGlobal('window', {});
+ search = await import('../../src/lib/catalog/search-run.ts');
+ runtime = await import('../../src/lib/runtime/public-runtime.ts');
+ requests = await import('../../src/lib/nostr/request-scope.ts');
+});
+afterEach(() => {
+ if (context) runtime.closePublicRuntime(context);
+ for (const key of keys.splice(0)) key.fill(0);
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+const corpus = JSON.parse(
+ readFileSync(
+ new URL(
+ '../../../contracts/interop/food_availability/corpus.v1.json',
+ import.meta.url
+ ),
+ 'utf8'
+ )
+) as { vectors: { id: string; signed_wires: Record<string, string> }[] };
+const base = JSON.parse(
+ corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous
+) as { tags: string[][]; content: string; created_at: number };
+async function fixture() {
+ const { RelayPool } = await import('applesauce-relay/pool');
+ const { validateRelayPolicy } =
+ await import('../../src/lib/config/relays.ts');
+ const { verifyEnvelope } =
+ await import('../../src/lib/nostr/verified-envelope.ts');
+ const { createPublicHeadCandidate } =
+ await import('../../src/lib/catalog/heads.ts');
+ const channels: {
+ emit: (value: PublicPoolMessage) => void;
+ stopped: () => boolean;
+ }[] = [];
+ const provider = vi.spyOn(RelayPool.prototype, 'req').mockImplementation(
+ () =>
+ ({
+ subscribe(subscriber: { next?: (value: PublicPoolMessage) => void }) {
+ let stopped = false;
+ channels.push({
+ emit: (value: PublicPoolMessage) => {
+ if (!stopped) subscriber.next?.(value);
+ },
+ stopped: () => stopped
+ });
+ return {
+ get closed() {
+ return stopped;
+ },
+ unsubscribe() {
+ stopped = true;
+ }
+ };
+ }
+ }) as unknown as ReturnType<InstanceType<typeof RelayPool>['req']>
+ );
+ const origin = 'wss://one.example.org';
+ const policy = validateRelayPolicy(
+ JSON.stringify({
+ schemaVersion: 1,
+ public: [{ origin, read: true, write: false, nip50: false }],
+ inbox: [],
+ postingEnabled: false,
+ messagingEnabled: false,
+ operatorDenylist: []
+ })
+ )!;
+ const key = crypto.getRandomValues(new Uint8Array(32));
+ keys.push(key);
+ const wire = (title = 'Carrots', d?: string, time = base.created_at) =>
+ finalizeEvent(
+ {
+ kind: 30402,
+ created_at: time,
+ content: base.content,
+ tags: base.tags.map((tag) =>
+ tag[0] === 'title'
+ ? ['title', title]
+ : tag[0] === 'd' && d !== undefined
+ ? ['d', d]
+ : [...tag]
+ )
+ },
+ key
+ );
+ const head = (event = wire()) => {
+ const p = verifyEnvelope(JSON.stringify(event));
+ if (!p.ok) throw Error('fixture proof');
+ const h = createPublicHeadCandidate(p.value);
+ if (!h) throw Error('fixture head');
+ return h;
+ };
+ let now = 0,
+ reads = 0;
+ let onNow = () => {};
+ const timers = new Map<() => void, { at: number; callback: () => void }>();
+ const clock: RequestClock = {
+ now: () => {
+ reads++;
+ onNow();
+ return now;
+ },
+ schedule: (callback, delay) => {
+ const cancel = () => {
+ timers.delete(cancel);
+ };
+ timers.set(cancel, { at: now + delay, callback });
+ return cancel;
+ }
+ };
+ context = runtime.createPublicRuntimeContext();
+ const owner = runtime.mountPublicRuntime(context, policy, clock)!;
+ const view = runtime.createPublicView(owner);
+ const wallClock = {
+ nowSeconds: () => base.created_at + 10
+ };
+ const coordinator = search.createFoodSearchCoordinator(view, wallClock);
+ const begin = (query = '', heads: readonly ReturnType<typeof head>[] = []) =>
+ search.beginFoodSearch(coordinator, query, heads);
+ const snapshot = () => search.foodSearchSnapshot(coordinator)!;
+ const emit = (i: number, event: ReturnType<typeof wire>) =>
+ channels[i].emit({ type: 'EVENT', id: 'fixture', from: origin, event });
+ return {
+ coordinator,
+ view,
+ wallClock,
+ begin,
+ snapshot,
+ head,
+ wire,
+ emit,
+ channels,
+ provider,
+ origin,
+ timers,
+ reads: () => reads,
+ reenter: (callback: () => void) => {
+ onNow = callback;
+ },
+ advance: (value: number) => {
+ now = value;
+ for (const timer of [...timers.values()])
+ if (timer.at <= now) timer.callback();
+ }
+ };
+}
+describe('finite food search coordination (isolated SDK provider, not qualification)', () => {
+ it('uses one coordinator per genuine view and refuses a changed clock owner', async () => {
+ const f = await fixture();
+ expect(search.createFoodSearchCoordinator(f.view, f.wallClock)).toBe(
+ f.coordinator
+ );
+ expect(() =>
+ search.createFoodSearchCoordinator(f.view, {
+ nowSeconds: () => base.created_at + 10
+ })
+ ).toThrow('food_search_clock_changed');
+ });
+ it('bounds primary scope history to the approved source-round and chronological-window maximum', async () => {
+ const f = await fixture(),
+ token = f.begin('');
+ for (let i = 0; i < 5; i++) {
+ search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }]);
+ f.channels[i].emit({ type: 'EOSE', id: 'fixture', from: f.origin });
+ }
+ expect(() =>
+ search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }])
+ ).toThrow('food_search_primary_limit');
+ expect(f.channels).toHaveLength(5);
+ expect(f.snapshot().scopes).toHaveLength(5);
+ expect(f.snapshot().refresh).toBe('limit');
+ });
+ it('charges failed primary attempts before provider effects without unlimited retries', async () => {
+ const f = await fixture(),
+ token = f.begin('');
+ f.provider.mockImplementation(() => {
+ throw new Error('isolated provider failure');
+ });
+ for (let i = 0; i < 5; i++) {
+ expect(() =>
+ search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }])
+ ).toThrow('food_search_request_failed');
+ }
+ expect(f.provider).toHaveBeenCalledTimes(5);
+ expect(() =>
+ search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }])
+ ).toThrow('food_search_primary_limit');
+ expect(f.provider).toHaveBeenCalledTimes(5);
+ expect(f.channels).toHaveLength(0);
+ expect(f.snapshot().scopes).toHaveLength(0);
+ expect(f.snapshot().refresh).toBe('limit');
+ });
+ it('rejects invalid query before effects and preserves the current generation', async () => {
+ const f = await fixture(),
+ token = f.begin(' carrots '),
+ reads = f.reads();
+ expect(() => f.begin('x'.repeat(513))).toThrow('query_too_long');
+ expect(f.reads()).toBe(reads);
+ expect(f.snapshot()).toMatchObject({
+ generation: token,
+ query: 'carrots',
+ definitiveAbsence: false
+ });
+ });
+ it('browses retained active heads and keeps source uncertainty explicit', async () => {
+ const f = await fixture();
+ f.begin('', [f.head(), f.head()]);
+ expect(f.snapshot()).toMatchObject({
+ query: '',
+ available: true,
+ refresh: 'refreshing',
+ definitiveAbsence: false
+ });
+ expect(f.snapshot().rows).toHaveLength(1);
+ expect(f.snapshot().rows[0].lastKnown).toBe(true);
+ expect(f.channels).toHaveLength(2);
+ });
+ it('bounds and validates the entire cached seed before changing the generation', async () => {
+ const f = await fixture(),
+ token = f.begin('carrots'),
+ h = f.head(),
+ reads = f.reads();
+ expect(() => f.begin('', Array(2001).fill(h))).toThrow(
+ 'head_query_input_limit'
+ );
+ expect(() => f.begin('', [{} as typeof h])).toThrow('public_head_invalid');
+ expect(f.reads()).toBe(reads);
+ expect(f.snapshot().generation).toBe(token);
+ });
+ it('cancels superseded scopes and refuses an old handle while retaining known evidence', async () => {
+ const f = await fixture(),
+ first = f.begin('carrots', [f.head()]);
+ const second = f.begin('celery');
+ expect(f.channels.slice(0, 2).every((c) => c.stopped())).toBe(true);
+ expect(() => search.foodSearchRequestOwner(first)).toThrow(
+ 'food_search_superseded'
+ );
+ f.emit(0, f.wire('Carrots', undefined, base.created_at + 2));
+ f.emit(2, f.wire('Celery', undefined, base.created_at + 1));
+ expect(f.snapshot().generation).toBe(second);
+ expect(f.snapshot().rows[0].state.food?.title).toBe('Celery');
+ });
+ it('cannot publish a generation superseded during an injected clock read', async () => {
+ const f = await fixture();
+ f.begin('carrots', [f.head()]);
+ let armed = true;
+ f.reenter(() => {
+ if (armed) {
+ armed = false;
+ f.begin('celery');
+ }
+ });
+ expect(search.foodSearchSnapshot(f.coordinator)).toBeUndefined();
+ expect(f.snapshot().query).toBe('celery');
+ });
+ it('shares all six scope slots with cached latest and deletion lookups', async () => {
+ const f = await fixture(),
+ token = f.begin('', [f.head()]);
+ for (let i = 0; i < 4; i++)
+ search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }]);
+ expect(f.snapshot().run?.activeRequests).toBe(6);
+ expect(() =>
+ search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }])
+ ).toThrow('food_search_request_failed');
+ expect(f.snapshot().run?.activeRequests).toBe(6);
+ search.cancelFoodSearch(token);
+ expect(f.channels.every((c) => c.stopped())).toBe(true);
+ expect(f.timers.size).toBe(0);
+ expect(f.snapshot().rows).toHaveLength(1);
+ });
+ it('truncates later requests at the original fifteen-second run deadline', async () => {
+ const f = await fixture(),
+ token = f.begin('', [f.head()]);
+ f.advance(8000);
+ const request = search.subscribeFoodSearch(token, [
+ { kinds: [30402], limit: 200 }
+ ]);
+ expect(requests.publicRequestScopeSnapshot(request).deadline).toBe(15000);
+ f.advance(15000);
+ expect(f.snapshot()).toMatchObject({
+ refresh: 'deadline',
+ run: { deadline: 15000, active: false },
+ definitiveAbsence: false
+ });
+ expect(f.snapshot().rows).toHaveLength(1);
+ expect(f.channels.every((c) => c.stopped())).toBe(true);
+ });
+ it('charges duplicates and rejects across primary and auxiliary work to one two-thousand delivery cap', async () => {
+ const f = await fixture(),
+ token = f.begin('', [f.head()]);
+ search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }]);
+ const valid = f.wire(),
+ invalid = { ...valid, id: '0'.repeat(64) };
+ for (let i = 0; i < 2000; i++)
+ f.emit(i % 2 === 0 ? 2 : 0, i < 1000 ? valid : invalid);
+ expect(f.snapshot().run?.ingress).toMatchObject({
+ deliveries: 2000,
+ stopped: true
+ });
+ expect(f.snapshot().refresh).toBe('limit');
+ expect(f.channels.every((c) => c.stopped())).toBe(true);
+ expect(f.snapshot().rows).toHaveLength(1);
+ });
+ it('charges rejected bytes across primary and auxiliary work to the same eight-MiB ceiling', async () => {
+ const f = await fixture(),
+ token = f.begin('', [f.head()]);
+ search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }]);
+ const invalid = { ...f.wire(), content: 'x'.repeat(128000) };
+ for (let i = 0; i < 100 && !f.snapshot().run?.ingress.stopped; i++)
+ f.emit(i % 2 === 0 ? 2 : 0, invalid);
+ expect(f.snapshot().run?.ingress).toMatchObject({
+ chargedBytes: 8388608,
+ stopped: true
+ });
+ expect(f.snapshot().run!.ingress.deliveries).toBeLessThan(2000);
+ expect(f.snapshot().refresh).toBe('limit');
+ expect(f.snapshot().rows).toHaveLength(1);
+ });
+ it('materializes a newly discovered cached coordinate after deadline without starting new requests', async () => {
+ const f = await fixture(),
+ token = f.begin('');
+ search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }]);
+ f.emit(0, f.wire('New carrots', 'fresh-coordinate'));
+ f.advance(15000);
+ const count = f.channels.length,
+ row = f.snapshot().rows[0];
+ expect(row.state.food?.title).toBe('New carrots');
+ expect(row).toMatchObject({
+ coverage: 'partial',
+ lastKnown: true,
+ definitiveAbsence: false
+ });
+ expect(f.channels).toHaveLength(count);
+ });
+ it('retains bounded results despite relay closure and never exposes global completeness', async () => {
+ const f = await fixture(),
+ token = f.begin('', [f.head()]);
+ search.subscribeFoodSearch(token, [{ kinds: [30402], limit: 200 }]);
+ for (const channel of f.channels)
+ channel.emit({
+ type: 'CLOSED',
+ id: 'fixture',
+ from: f.origin,
+ reason: 'unavailable'
+ });
+ const snapshot = f.snapshot();
+ expect(snapshot.rows).toHaveLength(1);
+ expect(snapshot.refresh).toBe('partial');
+ expect(snapshot.definitiveAbsence).toBe(false);
+ expect(Object.hasOwn(snapshot, 'complete')).toBe(false);
+ });
+ it('disposes the owned view and denies further query effects', async () => {
+ const f = await fixture();
+ f.begin('', [f.head()]);
+ search.closeFoodSearchCoordinator(f.coordinator);
+ expect(search.foodSearchSnapshot(f.coordinator)).toBeUndefined();
+ expect(() => f.begin('')).toThrow('food_search_closed');
+ expect(f.channels.every((c) => c.stopped())).toBe(true);
+ });
+});