@opennodes/registry 0.1.58 → 0.1.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,9 +3,9 @@
3
3
  The OpenNodes Protocol (ONP) reference registry — an open, federatable discovery service for AI inference nodes.
4
4
 
5
5
  ```bash
6
- npx @opennodes/registry@0.1.58 # web app + API on http://127.0.0.1:4300
7
- ONP_DB=./registry.db npx @opennodes/registry@0.1.58 # persistent SQLite + persistent signing key
8
- ONP_DB=postgres://user:pass@host/db npx @opennodes/registry@0.1.58
6
+ npx @opennodes/registry@0.1.60 # web app + API on http://127.0.0.1:4300
7
+ ONP_DB=./registry.db npx @opennodes/registry@0.1.60 # persistent SQLite + persistent signing key
8
+ ONP_DB=postgres://user:pass@host/db npx @opennodes/registry@0.1.60
9
9
  ```
10
10
 
11
11
  What it does:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opennodes/registry",
3
- "version": "0.1.58",
3
+ "version": "0.1.60",
4
4
  "description": "OpenNodes (ONP) reference registry: node registration with proof-of-resource qualification (Stage A/B/C), transparent ranking, enforceable estimates, catalog importers (OpenRouter, Hugging Face, models.dev, Ollama, AI Horde), MCP surface, and the web app (catalog, chat, advisor, Node Builder)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
package/src/schedule.js CHANGED
@@ -34,6 +34,9 @@ export const SCHEDULE_DEFAULTS = Object.freeze({
34
34
  // The card revision really moved during Stage B (an excused 409, stageb.js): run again at a random
35
35
  // time within the hour (tick slack included). At most MAX_EXCUSED_409 in a row; the next run is judged.
36
36
  staleRetryMs: [0, 50 * 60_000],
37
+ // Identity prompts got no reply even after retries (5xx, 429, timeouts: stageb.js), or the run could
38
+ // not finish: not judged, and run again at a random time in this window.
39
+ stageBFailedMs: [HOUR, DAY],
37
40
  });
38
41
 
39
42
  /** States whose nodes get Stage A on schedule, and the subset that gets Stage B. */
@@ -45,6 +48,19 @@ export const STAGE_B_STATES = ['community', 'verified', 'attested'];
45
48
  * a light-check mismatch never redraw it.
46
49
  */
47
50
  export const TIMER = 'B:timer';
51
+ /**
52
+ * The private row that holds automatic Stage B after a run ended "identity inconclusive" (ONP-3
53
+ * §4a.4): `digest` lists the artefacts (JSON). With the same references a second run would give the
54
+ * same mismatch and dispute without anyone having looked, so no change, retry or blind check sets
55
+ * Stage B off until the artefact is captured again (reopenAfterCapture) or an admin runs Stage B.
56
+ */
57
+ export const HOLD = 'B:hold';
58
+
59
+ /** Artefacts a node's Stage B hold waits on ([] when there is no hold). */
60
+ export async function heldArtifacts(store, nodeId) {
61
+ const row = await store.getSchedule(nodeId, HOLD);
62
+ try { return row?.digest ? JSON.parse(row.digest) : []; } catch { return []; }
63
+ }
48
64
 
49
65
  const iso = (ms) => new Date(ms).toISOString();
50
66
  const sha256 = (s) => createHash('sha256').update(s).digest('hex');
@@ -100,6 +116,7 @@ export function makePlanner(store, options = {}) {
100
116
  */
101
117
  async stageBSoon(nodeId, card) {
102
118
  const prev = await store.getSchedule(nodeId, 'B');
119
+ if ((await heldArtifacts(store, nodeId)).length) return prev?.next_at ?? null; // held: see HOLD
103
120
  const at = Date.now() + between(o.stageBIdentityMs, random);
104
121
  const next = iso(Math.min(prev?.next_at ? Date.parse(prev.next_at) : Infinity, at));
105
122
  await store.setSchedule(nodeId, 'B', prev ? { ...prev, next_at: next } : {
@@ -111,6 +128,23 @@ export function makePlanner(store, options = {}) {
111
128
  async afterStageB(nodeId, card, result) {
112
129
  const prev = await store.getSchedule(nodeId, 'B') ?? {};
113
130
  const now = Date.now();
131
+ if (result.inconclusive) {
132
+ // Not passed, not disputed: nothing runs until a recapture or an admin's run (HOLD).
133
+ const artifacts = [...new Set([...await heldArtifacts(store, nodeId), ...result.inconclusive.map((i) => i.artifact)])];
134
+ await store.setSchedule(nodeId, HOLD, { last_at: iso(now), next_at: null, digest: JSON.stringify(artifacts) });
135
+ await store.setSchedule(nodeId, 'B', {
136
+ last_at: iso(now), next_at: null, ok: false, revision: card?.revision ?? null,
137
+ digest: servingDigest(card), pending_digest: null, failures: (prev.failures ?? 0) + 1,
138
+ });
139
+ return;
140
+ }
141
+ if (result.endpointFailed || result.error) {
142
+ // Not judged: identity prompts got no reply even after retries, or the run could not finish
143
+ // (stageb.js endpointFailedOf). last_at stays, so the bound counts every such run since the
144
+ // last judged one; the next run comes within a day; the timer and any hold stay as they were.
145
+ await store.setSchedule(nodeId, 'B', { ...prev, next_at: iso(now + between(o.stageBFailedMs, random)), ok: false, failures: (prev.failures ?? 0) + 1 });
146
+ return;
147
+ }
114
148
  if (result.stale) {
115
149
  // Unjudged: last_at stays, so the excused 409s since the last judged run keep counting.
116
150
  await store.setSchedule(nodeId, 'B', { ...prev, next_at: iso(now + between(o.staleRetryMs, random)), failures: (prev.failures ?? 0) + 1 });
@@ -131,6 +165,29 @@ export function makePlanner(store, options = {}) {
131
165
  last_at: iso(now), next_at: next, ok: result.ok, revision: card?.revision ?? null,
132
166
  digest: servingDigest(card), pending_digest: null, failures: result.ok ? 0 : (prev.failures ?? 0) + 1,
133
167
  });
168
+ // A judged run (an admin's, while held) ends the hold.
169
+ if (await store.getSchedule(nodeId, HOLD)) await store.deleteSchedule(nodeId, HOLD);
170
+ },
171
+ /**
172
+ * The artefact's references were captured again: nodes held on it (HOLD) get Stage B at a random
173
+ * time in the first-run window once nothing else holds them. Returns the node ids reopened.
174
+ */
175
+ async reopenAfterCapture(artifact) {
176
+ const reopened = [];
177
+ for (const node of await store.allNodes()) {
178
+ const held = await heldArtifacts(store, node.id);
179
+ if (!held.includes(artifact)) continue;
180
+ const rest = held.filter((a) => a !== artifact);
181
+ if (rest.length) {
182
+ const row = await store.getSchedule(node.id, HOLD);
183
+ await store.setSchedule(node.id, HOLD, { ...row, digest: JSON.stringify(rest) });
184
+ continue;
185
+ }
186
+ await store.deleteSchedule(node.id, HOLD);
187
+ if (STAGE_B_STATES.includes(node.state)) await this.firstStageB(node.id, await store.latestCard(node.id), 'first');
188
+ reopened.push(node.id);
189
+ }
190
+ return reopened;
134
191
  },
135
192
  };
136
193
  }
@@ -158,6 +215,7 @@ export function startScheduler(store, planner, { stageA, stageB, random = Math.r
158
215
 
159
216
  const current = await store.getNode(node.id);
160
217
  if (!STAGE_B_STATES.includes(current?.state)) continue;
218
+ if ((await heldArtifacts(store, node.id)).length) continue; // identity inconclusive: see HOLD
161
219
  const fresh = await store.latestCard(node.id);
162
220
  let b = await store.getSchedule(node.id, 'B');
163
221
  if (!b) {
package/src/server.js CHANGED
@@ -11,7 +11,7 @@ import { fileURLToPath } from 'node:url';
11
11
  import { generateKeypair, keypairFromPem } from '@opennodes/core';
12
12
  import { createStore } from './store.js';
13
13
  import { runStageA, verificationOf } from './probes.js';
14
- import { runStageB, captureFingerprints, UNSIGNED_CARD, IDENTITY_CAPTURE, CUSTOMER_ACCESS_NEEDED } from './stageb.js';
14
+ import { runStageB, captureFingerprints, judgeMismatch, STAGE_B_INCONCLUSIVE, UNSIGNED_CARD, IDENTITY_CAPTURE, CUSTOMER_ACCESS_NEEDED } from './stageb.js';
15
15
  import { startStageC } from './stagec.js';
16
16
  import { loadCorpus } from './corpus.js';
17
17
  import { vendorTable, proprietaryVendor, VENDOR_SLUG, NAMESPACE, ARTIFACT } from './vendors.js';
@@ -32,7 +32,10 @@ import {
32
32
  HORDE_STATUS_URL, HORDE_TEXT_REFERENCE_URL, HORDE_CLIENT_AGENT,
33
33
  } from './importers.js';
34
34
  import { locationRoutes, loadLocationSeeds, seedPlacements, seedNodeSites, nodeServes } from './locations.js';
35
- import { makeRequestCounter, nodeIdsIn } from './counts.js';
35
+ import { makeRequestCounter, nodeIdsIn, isoWeek, recentWeeks, weekStart } from './counts.js';
36
+
37
+ /** Why POST /v0/nodes refused a registration before storing anything (GET /v0/stats/registrations). */
38
+ const REGISTRATION_FAILURES = ['card-unfetchable', 'card-invalid', 'namespace-mismatch'];
36
39
 
37
40
  /** Default basemap. OSM's tile policy asks for attribution and light use; busy registries set their own. */
38
41
  export const OSM_TILES = {
@@ -46,6 +49,7 @@ export async function startRegistry({
46
49
  allowPrivateTargets = false, // SSRF guard off only for dev/e2e
47
50
  dnsResolveTxt = resolveTxt, // injectable for tests
48
51
  stageBCapacity = {}, // e.g. { durationMs, steps } — shortened in tests
52
+ stageBIdentityRetry = null, // {pausesMs, rateLimitPausesMs, retryAfterCapMs} for identity prompts after an endpoint failure (default stageb.js IDENTITY_RETRY)
49
53
  stageC = null, // { livenessIntervalMs, blindIntervalMs, failThreshold } to enable
50
54
  reimport = null, // { intervalMs, sources } to keep imported catalogs fresh
51
55
  adminToken = null, // bearer for admin routes; without it, loopback-only
@@ -155,6 +159,11 @@ export async function startRegistry({
155
159
  * operator's probe key (card-only listings of keyed APIs), and only toward the card's own
156
160
  * endpoint origins — never to anything else.
157
161
  */
162
+ /** A registration refused before anything was stored (GET /v0/stats/registrations). Never fails the reply. */
163
+ async function failedRegistration(reason) {
164
+ try { await store.addRegistrationFailure(isoWeek(), reason); } catch { /* counting is best-effort */ }
165
+ }
166
+
158
167
  async function authFetch(nodeId, card) {
159
168
  const key = (await store.getCustomerKey(nodeId)) ?? (await store.getProbeKey(nodeId));
160
169
  if (!key || !card?.endpoints) return safeFetch;
@@ -309,13 +318,37 @@ export async function startRegistry({
309
318
  const now = await store.latestRevision(nodeId);
310
319
  return now && now.revision !== card.revision ? now.revision : null;
311
320
  };
312
- const stageB = await runStageB(store, nodeId, card, {
313
- safeFetch: await authFetch(nodeId, card), capacity: stageBCapacity, corpus, vendors: await vendors(), signed: Boolean(revision?.sig_ok), revisionMoved,
314
- });
321
+ let stageB;
322
+ try {
323
+ stageB = await runStageB(store, nodeId, card, {
324
+ safeFetch: await authFetch(nodeId, card), capacity: stageBCapacity, corpus, vendors: await vendors(), signed: Boolean(revision?.sig_ok), revisionMoved,
325
+ ...(stageBIdentityRetry ? { identityRetry: stageBIdentityRetry } : {}),
326
+ });
327
+ } catch (err) {
328
+ // The run could not finish: recorded, not judged (the tier stays), and run again within a day.
329
+ const reason = `Stage B could not finish: ${String(err?.message ?? err).slice(0, 200)}`;
330
+ await store.recordProbe(nodeId, null, 'B', 'error', false, reason);
331
+ const result = { ok: false, identityFailed: false, error: true, reason, verdicts: [], untested: [] };
332
+ await planner.afterStageB(nodeId, card, result);
333
+ return result;
334
+ }
315
335
  const node = await store.getNode(nodeId);
336
+ let result = stageB;
316
337
  if (!stageB.stale && LISTED.includes(node.state)) {
317
- if (stageB.identityFailed) {
318
- await store.setState(nodeId, 'disputed', 'Stage B identity fingerprint mismatch');
338
+ // A confirmed mismatch disputes, except a node's first one for an artefact since its
339
+ // references were captured: "identity inconclusive" (ONP-3 §4a.4), held until a recapture.
340
+ const judged = stageB.identityFailed ? await judgeMismatch(store, nodeId, stageB) : null;
341
+ if (judged?.dispute) {
342
+ await store.setState(nodeId, 'disputed', judged.why);
343
+ } else if (judged) {
344
+ const what = judged.inconclusive.map((i) => `${i.offering_id} (${i.artifact}): ${i.matches}/${i.total} reference matches`).join('; ');
345
+ for (const i of judged.inconclusive) {
346
+ await store.recordInconclusive(nodeId, i.artifact);
347
+ await store.recordProbe(nodeId, i.offering_id, 'B', STAGE_B_INCONCLUSIVE, false,
348
+ `${i.matches}/${i.total} reference matches: identity inconclusive, the node's first mismatch for ${i.artifact} since its references were captured; not passed and not disputed; Stage B runs again after the references are captured again or an admin's review, and another mismatch then disputes`);
349
+ }
350
+ result = { ...stageB, ok: false, identityFailed: false, inconclusive: judged.inconclusive, reason: `identity inconclusive: ${what}` };
351
+ if (node.state !== 'community') await store.setState(nodeId, 'community', `Stage B identity inconclusive: ${what}`);
319
352
  } else if (stageB.ok && held) {
320
353
  // Passed, but on probes the operator could tell apart: it stays at (or returns to) community.
321
354
  stageB.held = CUSTOMER_ACCESS_NEEDED;
@@ -329,8 +362,8 @@ export async function startRegistry({
329
362
  await store.setState(nodeId, 'community', `Stage B failed: ${stageB.reason}`);
330
363
  }
331
364
  }
332
- await planner.afterStageB(nodeId, card, stageB);
333
- return stageB;
365
+ await planner.afterStageB(nodeId, card, result);
366
+ return result;
334
367
  } finally {
335
368
  stageBRunning.delete(nodeId);
336
369
  }
@@ -343,15 +376,16 @@ export async function startRegistry({
343
376
  if (probe_key != null && (typeof probe_key !== 'string' || probe_key.length > 4096)) return problem(res, 400, 'bad-probe-key', 'probe_key must be a string');
344
377
  if (!card_url) return problem(res, 400, 'missing-card-url', 'body must be {"card_url": "..."}');
345
378
  let card;
346
- try { card = await fetchCard(card_url); } catch (err) { return problem(res, 422, 'card-unfetchable', String(err.message)); }
379
+ try { card = await fetchCard(card_url); } catch (err) { await failedRegistration('card-unfetchable'); return problem(res, 422, 'card-unfetchable', String(err.message)); }
347
380
  const errors = validateCard(card);
348
- if (errors.length) return problem(res, 422, 'card-invalid', errors.slice(0, 10).join('; '));
381
+ if (errors.length) { await failedRegistration('card-invalid'); return problem(res, 422, 'card-invalid', errors.slice(0, 10).join('; ')); }
349
382
 
350
383
  const nodeId = card.node.id;
351
384
  const origin = new URL(card_url).origin;
352
385
  // The card must be served by a host that controls the claimed id (reverse-DNS). Otherwise anyone
353
386
  // could host a card naming someone else's node and pass the HTTP challenge on their own server.
354
387
  if (!namespaceOk(origin, nodeId)) {
388
+ await failedRegistration('namespace-mismatch');
355
389
  return problem(res, 403, 'namespace-mismatch',
356
390
  `node id ${nodeId} maps to ${domainForNodeId(nodeId)}; its card must be served from that host or a parent domain, not ${new URL(origin).hostname}`);
357
391
  }
@@ -471,7 +505,42 @@ export async function startRegistry({
471
505
  catch (err) { return problem(res, 502, 'capture-failed', String(err.message)); }
472
506
  if (replace) await store.clearFingerprints(target);
473
507
  await store.addFingerprints(target, refs);
474
- sendJson(res, 200, { artifact: target, references: refs.length, corpus: corpus.private ? 'private' : 'built-in' });
508
+ await store.recordCapture(target, { how: 'node', node_id, offering_id, host: new URL(card.endpoints.openai).host });
509
+ const reopened = await planner.reopenAfterCapture(target);
510
+ sendJson(res, 200, { artifact: target, references: refs.length, corpus: corpus.private ? 'private' : 'built-in', ...(reopened.length ? { reopened } : {}) });
511
+ }],
512
+
513
+ // Reference capture from an endpoint that is not a registered node (admin): a separate machine
514
+ // serving the public weights, which must not be listed, scheduled or probed. Body {endpoint (its
515
+ // OpenAI base URL, e.g. http://host:11434/v1), model_id, artifact}, optional {key} (sent as a
516
+ // Bearer token to that origin only; never stored, logged or returned), {runtime} (e.g. "ollama
517
+ // 0.12.3, CPU", kept privately with the capture) and {"replace": false}. Same SSRF guard, same
518
+ // private corpus and the same request body as Stage B. Lists nothing.
519
+ ['POST', '/v0/fingerprints/capture-endpoint', async (req, res) => {
520
+ if (!adminOk(req, res)) return;
521
+ const { endpoint, model_id, artifact, key, runtime, replace = true } = await readJson(req);
522
+ let url;
523
+ try { url = new URL(endpoint); } catch { return problem(res, 400, 'bad-endpoint', 'endpoint must be an http(s) URL: the OpenAI base URL, e.g. http://host:11434/v1'); }
524
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash || endpoint.length > 500) {
525
+ return problem(res, 400, 'bad-endpoint', 'endpoint must be an http(s) base URL without credentials, query or fragment');
526
+ }
527
+ if (typeof model_id !== 'string' || !model_id || model_id.length > 200) return problem(res, 400, 'bad-model-id', 'model_id must be the model name the endpoint serves');
528
+ if (typeof artifact !== 'string' || !ARTIFACT.test(artifact)) return problem(res, 400, 'bad-artifact', 'artifact must be hf:{org}/{repo}, ollama:{name}[:{tag}] or urn:proprietary:{vendor}:{model}');
529
+ if (key != null && (typeof key !== 'string' || key.length > 4096)) return problem(res, 400, 'bad-key', 'key must be a string');
530
+ if (runtime != null && (typeof runtime !== 'string' || runtime.length > 200)) return problem(res, 400, 'bad-runtime', 'runtime must be a short string');
531
+ const base = url.href.replace(/\/+$/, '');
532
+ const fetcher = key
533
+ ? (u, opts = {}, timeoutMs) => safeFetch(u, new URL(u).origin === url.origin ? { ...opts, headers: { ...(opts.headers ?? {}), authorization: `Bearer ${key}` } } : opts, timeoutMs)
534
+ : safeFetch;
535
+ const offering = { offering_id: 'capture', model: { artifact }, binding: { model_id } };
536
+ let refs;
537
+ try { refs = await captureFingerprints(fetcher, { endpoints: { openai: base } }, offering, corpus.identityPrompts(IDENTITY_CAPTURE)); }
538
+ catch (err) { const why = String(err.message); return problem(res, 502, 'capture-failed', key ? why.split(key).join('…') : why); }
539
+ if (replace) await store.clearFingerprints(artifact);
540
+ await store.addFingerprints(artifact, refs);
541
+ await store.recordCapture(artifact, { how: 'endpoint', host: url.host, model_id, ...(runtime ? { runtime } : {}) });
542
+ const reopened = await planner.reopenAfterCapture(artifact);
543
+ sendJson(res, 200, { artifact, references: refs.length, corpus: corpus.private ? 'private' : 'built-in', source: { host: url.host, ...(runtime ? { runtime } : {}) }, ...(reopened.length ? { reopened } : {}) });
475
544
  }],
476
545
 
477
546
  // Dispute resolution (admin): the only way out of `disputed`. Body {"resolution": "..."}: what
@@ -615,6 +684,25 @@ export async function startRegistry({
615
684
  });
616
685
  }],
617
686
 
687
+ // Failed registrations: per ISO week, how many POST /v0/nodes were refused before anything was
688
+ // stored, by reason. Counts only. ?weeks=1..52 (default 12).
689
+ ['GET', '/v0/stats/registrations', async (req, res, { query }) => {
690
+ const weeks = Math.min(52, Math.max(1, Math.floor(Number(query.get('weeks') ?? 12)) || 12));
691
+ const range = recentWeeks(weeks);
692
+ const rows = await store.registrationFailures(range.at(-1));
693
+ const out = new Map(range.map((w) => [w, { week: w, starts: weekStart(w), failed: Object.fromEntries(REGISTRATION_FAILURES.map((r) => [r, 0])), total: 0 }]));
694
+ for (const r of rows) {
695
+ const w = out.get(r.week);
696
+ if (!w || !REGISTRATION_FAILURES.includes(r.reason)) continue;
697
+ w.failed[r.reason] += Number(r.n);
698
+ w.total += Number(r.n);
699
+ }
700
+ sendJson(res, 200, {
701
+ counted: 'registrations (POST /v0/nodes) refused before anything was stored, per ISO week (Monday 00:00 UTC) and reason: card-unfetchable, card-invalid, namespace-mismatch. Counts only: never the card URL, the node id or the client.',
702
+ weeks: [...out.values()],
703
+ });
704
+ }],
705
+
618
706
  ['GET', '/v0/offerings', async (req, res, { query }) => {
619
707
  let page;
620
708
  try { page = await searchOfferingsPaged(store, query); }
package/src/stageb.js CHANGED
@@ -35,13 +35,14 @@ export const IDENTITY_MAX_TOKENS = 64;
35
35
  */
36
36
  export async function chatOnce(safeFetch, card, offering, content, maxTokens = IDENTITY_MAX_TOKENS, timeoutMs = 60_000) {
37
37
  const t0 = performance.now();
38
- const { status, body } = await fetchJsonCapped(safeFetch, `${card.endpoints.openai}/chat/completions`, {
38
+ const { status, body, headers } = await fetchJsonCapped(safeFetch, `${card.endpoints.openai}/chat/completions`, {
39
39
  method: 'POST',
40
- headers: {
40
+ // A reference capture from an endpoint that is not a node (no card) sends no ONP headers.
41
+ headers: card.node ? {
41
42
  'content-type': 'application/json',
42
43
  'onp-offering': `${card.node.id}/${offering.offering_id}`,
43
44
  'onp-card-revision': card.revision,
44
- },
45
+ } : { 'content-type': 'application/json' },
45
46
  body: JSON.stringify({
46
47
  model: offering.binding.model_id,
47
48
  messages: [{ role: 'user', content }],
@@ -54,6 +55,8 @@ export async function chatOnce(safeFetch, card, offering, content, maxTokens = I
54
55
  text: body?.choices?.[0]?.message?.content ?? null,
55
56
  usage: body?.usage ?? null,
56
57
  latencyMs: performance.now() - t0,
58
+ // A 429's or 503's Retry-After (seconds, or an HTTP date), for the identity retries.
59
+ retryAfter: headers?.get?.('retry-after') ?? null,
57
60
  };
58
61
  }
59
62
 
@@ -71,9 +74,78 @@ export async function captureFingerprints(safeFetch, card, offering, prompts = D
71
74
  return refs;
72
75
  }
73
76
 
77
+ /**
78
+ * A confirmed identity mismatch in Stage B, judged (ONP-3 §4a.4, first mismatch): `dispute`, or
79
+ * `inconclusive` for the node's first mismatch on an artefact since that artefact's references
80
+ * were last captured, whether or not any reference matched. Only hashes are stored, so a different
81
+ * model cannot be told from the same weights on other hardware, engine version or kernels, and a
82
+ * long-enough reply on other hardware can diverge on every prompt. A model swap gains one
83
+ * inconclusive run per artefact and capture at most, and gets no `verified` from it. Disputes at
84
+ * once: any non-matching prompt that went unanswered on either ask (a refusal or failed reply, so
85
+ * M4's rule that a refusal counts as a non-match keeps its force). Card revisions do not reset the
86
+ * count; only a new capture does. A prompt that got no reply even after the retries (an endpoint
87
+ * failure) is neither: a run with only such prompts failing is not judged (endpointFailedOf), and
88
+ * with a confirmed mismatch beside them the mismatch is judged as usual.
89
+ * Returns {dispute: true, why} or {dispute: false, inconclusive: [{offering_id, artifact, matches, total}]}.
90
+ */
91
+ /** Whether a verdict's identity check failed on evidence: not unverified (nothing to compare) and not endpoint-failed. */
92
+ const identityMismatch = (v) => Boolean(v.identity) && !v.identity.ok && !v.identity.unverified && !v.identity.endpointFailed;
93
+
94
+ export async function judgeMismatch(store, nodeId, stageB) {
95
+ const failed = (stageB.verdicts ?? []).filter(identityMismatch);
96
+ const inconclusive = [];
97
+ for (const v of failed) {
98
+ const id = v.identity;
99
+ const artifact = v.artifact;
100
+ if (id.failedAgain) return { dispute: true, why: IDENTITY_FAILED_AGAIN };
101
+ if (!artifact) return { dispute: true, why: IDENTITY_MISMATCH };
102
+ if (id.unanswered || id.moved) return { dispute: true, why: IDENTITY_MISMATCH };
103
+ const since = await store.lastCaptureAt(artifact);
104
+ if (await store.countInconclusive(nodeId, artifact, since) > 0) {
105
+ return { dispute: true, why: IDENTITY_MISMATCH };
106
+ }
107
+ inconclusive.push({ offering_id: v.offering_id, artifact, matches: id.matches, total: id.total });
108
+ }
109
+ return inconclusive.length ? { dispute: false, inconclusive } : { dispute: true, why: IDENTITY_MISMATCH };
110
+ }
111
+
112
+ /** The transition reason of a Stage B dispute (the identity probe record says how many references matched). */
113
+ export const IDENTITY_MISMATCH = 'Stage B identity fingerprint mismatch';
114
+ /** Probe record of a Stage B run that ended identity inconclusive. */
115
+ export const STAGE_B_INCONCLUSIVE = 'identity-inconclusive';
116
+
74
117
  /** Whether a reply's text is the reference's: the exact-output comparison of ONP-3 §4a.4. */
75
118
  export const matchesReference = (text, ref) => typeof text === 'string' && sha256(text) === ref.expected_hash;
76
119
 
120
+ /**
121
+ * Asking an identity prompt again after an endpoint failure (a 5xx, a 429, a 401, 403 or 408, a 200
122
+ * without a reply text, a timeout, a connection error): the pauses before each retry; for a 429 the
123
+ * pauses are `rateLimitPausesMs` (a per-minute quota needs the last one to reach the next minute),
124
+ * and a Retry-After header, up to `retryAfterCapMs`, sets the pause when it is longer.
125
+ */
126
+ export const IDENTITY_RETRY = Object.freeze({ pausesMs: [2_000, 8_000], rateLimitPausesMs: [5_000, 60_000], retryAfterCapMs: 120_000 });
127
+ /** Statuses that are endpoint failures, not refusals (with every 5xx). 401/403: a lapsed or revoked probe key looks the same as a refusal. */
128
+ const ENDPOINT_FAILURE_STATUSES = new Set([401, 403, 408, 429]);
129
+ /** A Retry-After header in ms (seconds or an HTTP date), or null. */
130
+ export function retryAfterMs(value, now = Date.now()) {
131
+ if (value == null || value === '') return null;
132
+ if (/^\d+$/.test(String(value).trim())) return Number(value) * 1000;
133
+ const at = Date.parse(value);
134
+ return Number.isFinite(at) ? Math.max(0, at - now) : null;
135
+ }
136
+ /**
137
+ * Probe record of a Stage B run that ended "endpoint failed" while the node answered other requests
138
+ * in it (selective). One is excused since the node's last judged run; with one already recorded, the
139
+ * next one's failed prompts count as unanswered, and the node is disputed (ONP-3 §4a.4).
140
+ */
141
+ export const STAGE_B_FAILED = 'identity-failed';
142
+ /** Probe record of a run that ended "endpoint failed" with nothing answered in it: the node was down. Never counts. */
143
+ export const STAGE_B_UNREACHABLE = 'identity-unreachable';
144
+ /** Selective endpoint-failed runs excused since the node's last judged Stage B. */
145
+ export const MAX_FAILED_RUNS = 1;
146
+ /** The transition reason of a dispute for identity prompts that failed again while other requests were answered. */
147
+ export const IDENTITY_FAILED_AGAIN = 'Stage B identity prompts failed in a second run while the node answered other requests';
148
+
77
149
  /** 409s to identity prompts excused (the run stops unjudged and is retried) since the node's last judged Stage B. */
78
150
  export const MAX_EXCUSED_409 = 3;
79
151
  /** The probe record of an excused one. */
@@ -129,36 +201,80 @@ const sameModelClaim = (a, b) => a.model?.artifact === b.model?.artifact
129
201
  * parallel slots can change a temperature-0 reply now and then). A 409 counts as a reply that does
130
202
  * not match unless `on409` excuses it (makeOn409).
131
203
  */
132
- async function probeIdentity(safeFetch, pin, offering, refs, on409) {
204
+ async function probeIdentity(safeFetch, pin, offering, refs, on409, retry = IDENTITY_RETRY, endpoint = { down: false }) {
133
205
  let matches = 0, retried = 0, refused = 0, refusedRepinned = 0, repinned = null, stop = null;
206
+ let answered = 0, failure = null;
134
207
  let current = offering;
208
+ // One request. An endpoint failure (a 5xx, a 401, 403, 408 or 429, a 200 without a reply text, a
209
+ // timeout, a connection error) is {failure}; any other status is {status}, for the refusal rule below.
210
+ const once = async (prompt) => {
211
+ try {
212
+ const { status, text, retryAfter } = await chatOnce(safeFetch, pin.card, current, prompt);
213
+ if (status === 200 && typeof text === 'string') return { text };
214
+ if (status === 200 || status >= 500 || ENDPOINT_FAILURE_STATUSES.has(status)) {
215
+ return { failure: status === 200 ? '200 without a reply text' : `status ${status}`, status429: status === 429, retryAfter: retryAfterMs(retryAfter) };
216
+ }
217
+ return { status };
218
+ } catch (err) {
219
+ return { failure: /abort|timeout/i.test(String(err?.name) + String(err?.message)) ? 'timeout' : 'connection error', thrown: true };
220
+ }
221
+ };
222
+ const pause = (ms) => (ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : null);
223
+ // {hash} | {refused: true} | {failed: true} | {} (the run stops: `stop`).
135
224
  const ask = async (prompt, again = true) => {
136
- const { status, text } = await chatOnce(safeFetch, pin.card, current, prompt);
137
- if (status !== 200) {
138
- // A 409, or another failure (a 404 for a model dropped since the card was fetched): only a
225
+ let r = await once(prompt);
226
+ // An endpoint failure is asked again, once per pause; once the run has found the endpoint
227
+ // unreachable (`endpoint.down`, shared by the run's offerings), not again until something answers.
228
+ for (let i = 0; r.failure && !endpoint.down && i < retry.pausesMs.length; i++) {
229
+ const base = (r.status429 ? retry.rateLimitPausesMs : retry.pausesMs)[i] ?? 0;
230
+ await pause(Math.max(base, Math.min(r.retryAfter ?? 0, retry.retryAfterCapMs)));
231
+ r = await once(prompt);
232
+ }
233
+ if (r.failure) { failure = r.failure; if (r.thrown) endpoint.down = true; return { failed: true }; }
234
+ endpoint.down = false;
235
+ if (r.status) {
236
+ // A 409, or another refusal (a 404 for a model dropped since the card was fetched): only a
139
237
  // revision that really moved excuses it; with the current revision pinned it does not match.
140
- const what = await on409(current, status);
238
+ const what = await on409(current, r.status);
141
239
  if (what.kind === 'repin') {
142
240
  // Beyond the bound: ask again with the revision just fetched pinned; a refusal then counts.
143
241
  current = what.offering;
144
242
  repinned = what.beyond;
145
243
  if (again) return ask(prompt, false);
146
244
  refusedRepinned++;
147
- return null;
245
+ return { refused: true };
148
246
  }
149
- if (what.kind !== 'refused') stop = what;
150
- else if (status === 409) refused++;
151
- return null;
247
+ if (what.kind !== 'refused') { stop = what; return {}; }
248
+ if (r.status === 409) refused++;
249
+ return { refused: true };
152
250
  }
153
- return text !== null ? sha256(text) : null;
251
+ answered++;
252
+ return { hash: sha256(r.text) };
154
253
  };
254
+ // Per prompt that did not match: `unanswered` when an ask was refused (such a mismatch is never
255
+ // "inconclusive": judgeMismatch disputes at once, so M4's rule keeps its force); else `failed` when
256
+ // an ask got no reply even after the retries (not judged: endpointFailedOf); else `mismatched`, a
257
+ // reply on both asks that is not the reference's.
258
+ let unanswered = 0, failed = 0, mismatched = 0;
155
259
  for (const ref of refs) {
156
- let hash = await ask(ref.prompt);
157
- if (hash !== ref.expected_hash && !stop) { retried++; hash = await ask(ref.prompt); }
158
- if (hash === ref.expected_hash) matches++;
260
+ let r = await ask(ref.prompt);
261
+ let refusedAny = Boolean(r.refused);
262
+ // A reply that does not match (or a refusal) is asked once more; a failed ask has had its retries.
263
+ if (!r.failed && r.hash !== ref.expected_hash && !stop) {
264
+ retried++;
265
+ r = await ask(ref.prompt);
266
+ refusedAny ||= Boolean(r.refused);
267
+ }
159
268
  if (stop) break;
269
+ if (r.hash === ref.expected_hash) matches++;
270
+ else if (refusedAny) unanswered++;
271
+ else if (r.failed) failed++;
272
+ else mismatched++;
160
273
  }
161
- const extra = { ...(retried ? { retried } : {}), ...(refused ? { refused } : {}),
274
+ const extra = { ...(retried ? { retried } : {}), ...(refused ? { refused } : {}), ...(unanswered ? { unanswered } : {}),
275
+ ...(failed ? { failed, failure } : {}), ...(mismatched ? { mismatched } : {}), answered,
276
+ // Nothing answered and the endpoint unreachable: the run sends this offering nothing more.
277
+ ...(failed && !answered && endpoint.down ? { unreachable: true } : {}),
162
278
  ...(repinned ? { repinned, refused_repinned: refusedRepinned } : {}) };
163
279
  if (stop?.kind === 'stale') return { ok: false, matches, total: refs.length, ...extra, stale: true };
164
280
  if (stop?.kind === 'moved') return { ok: false, matches, total: refs.length, ...extra, moved: true, reason: stop.reason };
@@ -207,17 +323,18 @@ async function probeContext(safeFetch, card, offering, corpus) {
207
323
  const body = Math.floor(tokens * charsPerToken) - fact.length - question.length - 40; // 40: chat template slack
208
324
  const before = Math.floor(body * 0.1);
209
325
  const prompt = corpus.haystack(before) + fact + corpus.haystack(body - before) + question;
210
- let found = false, why = null, promptTokens = null;
326
+ let found = false, why = null, promptTokens = null, answered = false;
211
327
  try {
212
328
  // Prefill on modest hardware is slow: allow ~30 ms per claimed token on top of the base timeout.
213
329
  const { status, text, usage } = await chatOnce(safeFetch, card, offering, prompt, 64, 60_000 + tokens * 30);
330
+ answered = status === 200 && typeof text === 'string'; // a reply, for the endpoint-failure bound
214
331
  promptTokens = usage?.prompt_tokens ?? null;
215
332
  if (status !== 200) why = `status ${status}`;
216
333
  else if (measured && promptTokens != null && promptTokens < tokens * 0.85) why = `prompt cut to ${promptTokens} tokens`;
217
334
  else if (!needleFound(text, digits)) why = 'number not in reply';
218
335
  else found = true;
219
336
  } catch (err) { why = /abort|timeout/i.test(String(err?.message)) ? 'timeout' : String(err?.message ?? err).slice(0, 80); }
220
- results.push({ fraction, tokens, found, ...(promptTokens != null ? { prompt_tokens: promptTokens } : {}), ...(why ? { why } : {}) });
337
+ results.push({ fraction, tokens, found, ...(answered ? { answered } : {}), ...(promptTokens != null ? { prompt_tokens: promptTokens } : {}), ...(why ? { why } : {}) });
221
338
  if (found && unbroken) cap = tokens; else unbroken = false;
222
339
  }
223
340
  const allPassed = results.every((r) => r.found);
@@ -227,7 +344,7 @@ async function probeContext(safeFetch, card, offering, corpus) {
227
344
  /** DS-ADM-04: stepped-concurrency ramp; measures TTFT p50/p95 and rough TPS. */
228
345
  async function probeCapacity(safeFetch, card, offering, corpus, { steps = CAPACITY_RAMP.steps, durationMs = CAPACITY_RAMP.durationMs } = {}) {
229
346
  const latencies = [];
230
- let completed = 0, failed = 0, outputTokens = 0;
347
+ let completed = 0, failed = 0, outputTokens = 0, answered = 0;
231
348
  const deadline = Date.now() + durationMs;
232
349
  for (const concurrency of steps) {
233
350
  while (Date.now() < deadline) {
@@ -240,6 +357,7 @@ async function probeCapacity(safeFetch, card, offering, corpus, { steps = CAPACI
240
357
  for (const r of batch) {
241
358
  if (!r) { failed++; continue; }
242
359
  completed++;
360
+ if (typeof r.text === 'string') answered++; // a reply with text, for the endpoint-failure bound
243
361
  latencies.push(r.latencyMs);
244
362
  outputTokens += r.usage?.completion_tokens ?? 0;
245
363
  }
@@ -251,7 +369,7 @@ async function probeCapacity(safeFetch, card, offering, corpus, { steps = CAPACI
251
369
  const totalSeconds = Math.max(0.001, durationMs / 1000);
252
370
  return {
253
371
  ok: completed > 0 && failed / Math.max(1, completed + failed) < 0.1,
254
- completed, failed,
372
+ completed, failed, answered,
255
373
  ttft_ms: { p50: pct(0.5), p95: pct(0.95) },
256
374
  tps: Math.round(outputTokens / totalSeconds),
257
375
  };
@@ -265,14 +383,57 @@ async function probeCapacity(safeFetch, card, offering, corpus, { steps = CAPACI
265
383
  * offering cannot be verified: no usable reference for the artefact, or a proprietary artefact
266
384
  * claimed outside the vendor's namespace.
267
385
  */
268
- async function identityOf(store, nodeId, safeFetch, pin, offering, { corpus, vendors, identitySample, on409 }) {
386
+ async function identityOf(store, nodeId, safeFetch, pin, offering, { corpus, vendors, identitySample, on409, identityRetry, endpoint }) {
269
387
  const artifact = offering.model?.artifact;
270
388
  const claim = vendorClaim(artifact, nodeId, vendors);
271
389
  if (!claim.ok) return { ok: false, unverified: true, reason: `${artifact} is not this node's to claim (vendor namespace)` };
272
390
  // References captured with public prompts prove nothing: a node could have recognised them.
273
391
  const refs = (await store.getFingerprints(artifact)).filter((r) => corpus.usableReference(r.prompt));
274
392
  if (!refs.length) return { ok: false, unverified: true, reason: NO_REFERENCE };
275
- return probeIdentity(safeFetch, pin, offering, sample(refs, identitySample), on409);
393
+ const asked = sample(refs, identitySample);
394
+ if (endpoint.down) {
395
+ // An earlier offering found the endpoint unreachable and nothing has answered since: not asked.
396
+ return { ok: false, matches: 0, total: asked.length, failed: asked.length, answered: 0, unreachable: true,
397
+ failure: 'not asked: the endpoint was unreachable for an earlier offering in this run' };
398
+ }
399
+ return probeIdentity(safeFetch, pin, offering, asked, on409, identityRetry, endpoint);
400
+ }
401
+
402
+ /**
403
+ * Whether the node answered any non-identity request of this offering's run: a 200 with a reply text
404
+ * (a context probe or a capacity request). A 200 without one, such as a proxy's error page, is no answer.
405
+ */
406
+ const answeredOtherwise = (verdict) => (verdict.capacity?.answered ?? 0) > 0
407
+ || (verdict.context?.results ?? []).some((r) => r.answered);
408
+
409
+ /**
410
+ * An identity check whose only non-matching prompts got no reply even after the retries (no refusal,
411
+ * no confirmed mismatch) is not judged: the run ends "not passed: endpoint failed", is recorded, and
412
+ * Stage B runs again soon. The bound: when the node answered other requests in the run (selective),
413
+ * one such run is excused since its last judged run; the next one's failed prompts count as
414
+ * unanswered, and the node is disputed. A node that answered nothing was down, and that never counts.
415
+ * Sets `endpointFailed` (with `reason`) or `failedAgain` on the identity verdict. `before`: selective
416
+ * endpoint-failed runs recorded since the last judged run, counted once at the start of this run, so
417
+ * that two offerings failing in one run are one run.
418
+ */
419
+ async function endpointFailedOf(store, nodeId, verdict, before) {
420
+ const id = verdict.identity;
421
+ if (id.ok || !id.failed || id.unanswered || id.mismatched || id.unverified || id.moved) return;
422
+ const selective = id.answered > 0 || answeredOtherwise(verdict);
423
+ const what = `${id.failed} of ${id.total} identity prompts got no reply, even after retries (last: ${id.failure})`;
424
+ if (selective && before >= MAX_FAILED_RUNS) {
425
+ id.failedAgain = true;
426
+ id.unanswered = id.failed;
427
+ await store.recordProbe(nodeId, verdict.offering_id, 'B', STAGE_B_FAILED, false,
428
+ `${what}, while the node answered other requests, again since its last judged run (${before} such run excused): counted as unanswered`);
429
+ return;
430
+ }
431
+ id.endpointFailed = true;
432
+ id.reason = `endpoint failed: ${what}`;
433
+ await store.recordProbe(nodeId, verdict.offering_id, 'B', selective ? STAGE_B_FAILED : STAGE_B_UNREACHABLE, false,
434
+ selective
435
+ ? `${what}, while the node answered other requests: not passed and not judged; Stage B runs again soon, and the next such run before a judged one counts them as unanswered`
436
+ : `${what}, and the node answered nothing in the run: not passed and not judged; Stage B runs again soon`);
276
437
  }
277
438
 
278
439
  /**
@@ -286,7 +447,7 @@ async function identityOf(store, nodeId, safeFetch, pin, offering, { corpus, ven
286
447
  */
287
448
  export async function runStageB(store, nodeId, card, {
288
449
  safeFetch, capacity = {}, corpus = DEV_CORPUS, vendors = vendorTable(), signed = true, identitySample = IDENTITY_SAMPLE,
289
- revisionMoved = null, maxExcused409 = MAX_EXCUSED_409,
450
+ revisionMoved = null, maxExcused409 = MAX_EXCUSED_409, identityRetry = IDENTITY_RETRY,
290
451
  } = {}) {
291
452
  // The card the run pins: the one held, until a refusal beyond the bound re-pins the fetched one.
292
453
  const pin = { card };
@@ -300,29 +461,48 @@ export async function runStageB(store, nodeId, card, {
300
461
  return { ok: false, identityFailed: false, reason: NO_TESTED_OFFERINGS, verdicts: [], untested };
301
462
  }
302
463
  const verdicts = [];
464
+ // Selective endpoint-failed runs since the last judged one, counted before this run records any.
465
+ const failedRunsBefore = await store.countProbes(nodeId, STAGE_B_FAILED, (await store.getSchedule(nodeId, 'B'))?.last_at ?? '');
303
466
  // The offering as the pinned card lists it now (a re-pin replaces the card mid-run).
304
467
  const pinned = (o) => pin.card.offerings.find((p) => p.offering_id === o.offering_id) ?? o;
468
+ // Shared by the run's offerings (one endpoint): set when an ask found it unreachable, cleared by any answer.
469
+ const endpoint = { down: false };
470
+
471
+ // First every offering's identity prompts, then the heavier probes: the run's own load (context
472
+ // probes, capacity ramps) must not rate-limit a later offering's identity asks.
305
473
  for (const listed of card.offerings) {
306
474
  if (!testable(listed)) continue;
307
- let offering = pinned(listed);
308
- const verdict = { offering_id: offering.offering_id, identity: null, context: null, capacity: null };
475
+ const offering = pinned(listed);
476
+ const verdict = { offering_id: offering.offering_id, artifact: offering.model?.artifact ?? null, identity: null, context: null, capacity: null };
309
477
 
310
- verdict.identity = await identityOf(store, nodeId, safeFetch, pin, offering, { corpus, vendors, identitySample, on409 });
478
+ verdict.identity = await identityOf(store, nodeId, safeFetch, pin, offering, { corpus, vendors, identitySample, on409, identityRetry, endpoint });
311
479
  if (verdict.identity.stale) {
312
480
  // The card's revision really moved (an excused 409, recorded). Abort without judging: the caller retries.
313
481
  return { ok: false, identityFailed: false, stale: true, verdicts: [...verdicts, verdict], untested };
314
482
  }
315
- const { matches, total, refused, repinned, refused_repinned: refusedRepinned } = verdict.identity;
483
+ const { matches, total, refused, repinned, refused_repinned: refusedRepinned, failed, failure } = verdict.identity;
316
484
  await store.recordProbe(nodeId, offering.offering_id, 'B', 'identity', verdict.identity.ok,
317
485
  verdict.identity.unverified ? `identity unverified: ${verdict.identity.reason}`
318
486
  : verdict.identity.moved ? `not judged: ${verdict.identity.reason}`
319
487
  : `${matches}/${total} reference matches${refused ? `; ${refused} replies refused with 409, the current card revision pinned` : ''}`
488
+ + (failed ? `; ${failed} prompts got no reply, even after retries (last: ${failure})` : '')
320
489
  + (repinned ? `; ${repinned}${refusedRepinned ? `, then ${refusedRepinned} refusals with it pinned, counted as replies that do not match` : ''}` : ''));
321
490
  if (verdict.identity.moved) {
322
491
  // Beyond the bound, and the claimed model changed: not passed, and nothing more is sent.
323
492
  return { ok: false, identityFailed: false, reason: `${offering.offering_id}: ${verdict.identity.reason}`, verdicts: [...verdicts, verdict], untested };
324
493
  }
325
- offering = pinned(offering);
494
+ verdicts.push(verdict);
495
+ }
496
+
497
+ for (const verdict of verdicts) {
498
+ let offering = pinned({ offering_id: verdict.offering_id });
499
+ if (endpoint.down) {
500
+ // The endpoint was unreachable when last asked: nothing more is sent (a context probe can wait
501
+ // up to an hour on a large window), and the run ends with what it has.
502
+ verdict.skipped = 'endpoint unreachable';
503
+ await endpointFailedOf(store, nodeId, verdict, failedRunsBefore);
504
+ continue;
505
+ }
326
506
 
327
507
  verdict.context = await probeContext(safeFetch, pin.card, offering, corpus);
328
508
  await store.recordProbe(nodeId, offering.offering_id, 'B', 'context', verdict.context.ok,
@@ -337,8 +517,8 @@ export async function runStageB(store, nodeId, card, {
337
517
  // A failed ramp on a card that has since moved (the model dropped or changed during the run)
338
518
  // is not judged, by the same rule and bound as a 409.
339
519
  const what = await on409(offering, 'capacity failure');
340
- if (what.kind === 'stale') return { ok: false, identityFailed: false, stale: true, verdicts: [...verdicts, verdict], untested };
341
- if (what.kind === 'moved') return { ok: false, identityFailed: false, reason: `${offering.offering_id}: ${what.reason}`, verdicts: [...verdicts, verdict], untested };
520
+ if (what.kind === 'stale') return { ok: false, identityFailed: false, stale: true, verdicts, untested };
521
+ if (what.kind === 'moved') return { ok: false, identityFailed: false, reason: `${offering.offering_id}: ${what.reason}`, verdicts, untested };
342
522
  // Beyond the bound, same model: the ramp once more with the fetched card pinned, and that one counts.
343
523
  if (what.kind === 'repin') { offering = what.offering; verdict.capacity = await probeCapacity(safeFetch, pin.card, offering, corpus, capacity); }
344
524
  }
@@ -347,17 +527,21 @@ export async function runStageB(store, nodeId, card, {
347
527
  await store.setObservation(nodeId, offering.offering_id, 'ttft_ms', verdict.capacity.ttft_ms);
348
528
  await store.setObservation(nodeId, offering.offering_id, 'tps', verdict.capacity.tps);
349
529
  }
350
-
351
- verdicts.push(verdict);
530
+ // Only now: whether the node answered the run's other requests decides the endpoint-failure bound.
531
+ await endpointFailedOf(store, nodeId, verdict, failedRunsBefore);
352
532
  }
353
533
 
354
- const identityFailed = verdicts.some((v) => !v.identity.ok && !v.identity.unverified);
534
+ const identityFailed = verdicts.some(identityMismatch);
355
535
  const unverified = verdicts.filter((v) => v.identity.unverified);
356
- const capacityFailed = verdicts.filter((v) => !v.capacity?.ok);
536
+ const endpointFailed = verdicts.filter((v) => v.identity.endpointFailed);
537
+ const capacityFailed = verdicts.filter((v) => !v.skipped && !v.capacity?.ok);
357
538
  const reasons = [
358
539
  ...unverified.map((v) => `${v.offering_id}: identity unverified (${v.identity.reason})`),
540
+ ...endpointFailed.map((v) => `${v.offering_id}: identity not judged (${v.identity.reason})`),
359
541
  ...capacityFailed.map((v) => `${v.offering_id}: capacity ramp failed`),
360
542
  ];
361
543
  const ok = !identityFailed && reasons.length === 0;
362
- return { ok, identityFailed, ...(ok || identityFailed ? {} : { reason: reasons.join('; ') }), verdicts, untested };
544
+ // `endpointFailed`: not judged (the scheduler retries soon and keeps the last judged run's time).
545
+ return { ok, identityFailed, ...(!identityFailed && endpointFailed.length ? { endpointFailed: true } : {}),
546
+ ...(ok || identityFailed ? {} : { reason: reasons.join('; ') }), verdicts, untested };
363
547
  }
package/src/store-pg.js CHANGED
@@ -54,6 +54,16 @@ const SCHEMA = `
54
54
  CREATE TABLE IF NOT EXISTS vendor_namespaces (
55
55
  vendor TEXT PRIMARY KEY, namespaces TEXT NOT NULL, updated_at TEXT NOT NULL
56
56
  );
57
+ CREATE TABLE IF NOT EXISTS fingerprint_captures (
58
+ id SERIAL PRIMARY KEY, artifact TEXT NOT NULL, source TEXT NOT NULL, captured_at TEXT NOT NULL
59
+ );
60
+ CREATE TABLE IF NOT EXISTS identity_inconclusive (
61
+ id SERIAL PRIMARY KEY, node_id TEXT NOT NULL, artifact TEXT NOT NULL, at TEXT NOT NULL
62
+ );
63
+ CREATE TABLE IF NOT EXISTS registration_failures (
64
+ week TEXT NOT NULL, reason TEXT NOT NULL, n INTEGER NOT NULL,
65
+ PRIMARY KEY (week, reason)
66
+ );
57
67
  `;
58
68
 
59
69
  const NODE_FLAGS = ['institutional', 'founding']; // same list as store.js
@@ -215,6 +225,33 @@ export async function createPgStore({ connectionString, pool } = {}) {
215
225
  ? q('SELECT * FROM request_counts WHERE node_id = $1 AND week >= $2 ORDER BY week DESC', [nodeId, sinceWeek])
216
226
  : q('SELECT * FROM request_counts WHERE week >= $1 ORDER BY week DESC', [sinceWeek]);
217
227
  },
228
+ async deleteSchedule(nodeId, stage) {
229
+ await q('DELETE FROM schedule WHERE node_id = $1 AND stage = $2', [nodeId, stage]);
230
+ },
231
+ async recordCapture(artifact, source) {
232
+ await q('INSERT INTO fingerprint_captures (artifact, source, captured_at) VALUES ($1, $2, $3)', [artifact, JSON.stringify(source), now()]);
233
+ },
234
+ async lastCaptureAt(artifact) {
235
+ return (await q('SELECT MAX(captured_at) AS at FROM fingerprint_captures WHERE artifact = $1', [artifact]))[0]?.at ?? null;
236
+ },
237
+ async captures(artifact) {
238
+ return (await q('SELECT artifact, source, captured_at FROM fingerprint_captures WHERE artifact = $1 ORDER BY id DESC', [artifact]))
239
+ .map((r) => ({ ...r, source: JSON.parse(r.source) }));
240
+ },
241
+ async recordInconclusive(nodeId, artifact) {
242
+ await q('INSERT INTO identity_inconclusive (node_id, artifact, at) VALUES ($1, $2, $3)', [nodeId, artifact, now()]);
243
+ },
244
+ async countInconclusive(nodeId, artifact, since = null) {
245
+ return Number((await q('SELECT COUNT(*) AS n FROM identity_inconclusive WHERE node_id = $1 AND artifact = $2 AND at > $3',
246
+ [nodeId, artifact, since ?? '']))[0].n);
247
+ },
248
+ async addRegistrationFailure(week, reason) {
249
+ await q(`INSERT INTO registration_failures (week, reason, n) VALUES ($1, $2, 1)
250
+ ON CONFLICT (week, reason) DO UPDATE SET n = registration_failures.n + 1`, [week, reason]);
251
+ },
252
+ async registrationFailures(sinceWeek = '0000-W00') {
253
+ return q('SELECT * FROM registration_failures WHERE week >= $1 ORDER BY week DESC', [sinceWeek]);
254
+ },
218
255
  async close() { await p.end(); },
219
256
  };
220
257
  }
package/src/store.js CHANGED
@@ -79,6 +79,22 @@ export async function createSqliteStore(path = ':memory:') {
79
79
  CREATE TABLE IF NOT EXISTS vendor_namespaces (
80
80
  vendor TEXT PRIMARY KEY, namespaces TEXT NOT NULL, updated_at TEXT NOT NULL
81
81
  );
82
+ -- Each reference capture of an artefact: when, and from where (host, runtime, how), so a later
83
+ -- mismatch can be traced to a hardware or runtime difference. Private: no API or export reads it.
84
+ CREATE TABLE IF NOT EXISTS fingerprint_captures (
85
+ id INTEGER PRIMARY KEY AUTOINCREMENT, artifact TEXT NOT NULL, source TEXT NOT NULL, captured_at TEXT NOT NULL
86
+ );
87
+ -- Stage B runs that ended "identity inconclusive" (ONP-3 §4a.4): a node's first confirmed partial
88
+ -- mismatch for an artefact since that artefact's last capture. The next one disputes.
89
+ CREATE TABLE IF NOT EXISTS identity_inconclusive (
90
+ id INTEGER PRIMARY KEY AUTOINCREMENT, node_id TEXT NOT NULL, artifact TEXT NOT NULL, at TEXT NOT NULL
91
+ );
92
+ -- Registrations refused before anything was stored, per ISO week and reason. Counts only: never
93
+ -- the card URL, the node id or the client.
94
+ CREATE TABLE IF NOT EXISTS registration_failures (
95
+ week TEXT NOT NULL, reason TEXT NOT NULL, n INTEGER NOT NULL,
96
+ PRIMARY KEY (week, reason)
97
+ );
82
98
  `);
83
99
  // Databases created before the founding mark existed: add the column in place.
84
100
  if (!db.prepare('PRAGMA table_info(nodes)').all().some((c) => c.name === 'founding')) {
@@ -228,6 +244,36 @@ export async function createSqliteStore(path = ':memory:') {
228
244
  ? db.prepare('SELECT * FROM request_counts WHERE node_id = ? AND week >= ? ORDER BY week DESC').all(nodeId, sinceWeek)
229
245
  : db.prepare('SELECT * FROM request_counts WHERE week >= ? ORDER BY week DESC').all(sinceWeek);
230
246
  },
247
+ async deleteSchedule(nodeId, stage) {
248
+ db.prepare('DELETE FROM schedule WHERE node_id = ? AND stage = ?').run(nodeId, stage);
249
+ },
250
+ /** source: {how, host, runtime?, model_id?, node_id?, offering_id?} — kept private. */
251
+ async recordCapture(artifact, source) {
252
+ db.prepare('INSERT INTO fingerprint_captures (artifact, source, captured_at) VALUES (?, ?, ?)').run(artifact, JSON.stringify(source), now());
253
+ },
254
+ /** ISO time of an artefact's last reference capture, or null. */
255
+ async lastCaptureAt(artifact) {
256
+ return db.prepare('SELECT MAX(captured_at) AS at FROM fingerprint_captures WHERE artifact = ?').get(artifact)?.at ?? null;
257
+ },
258
+ async captures(artifact) {
259
+ return db.prepare('SELECT artifact, source, captured_at FROM fingerprint_captures WHERE artifact = ? ORDER BY id DESC').all(artifact)
260
+ .map((r) => ({ ...r, source: JSON.parse(r.source) }));
261
+ },
262
+ async recordInconclusive(nodeId, artifact) {
263
+ db.prepare('INSERT INTO identity_inconclusive (node_id, artifact, at) VALUES (?, ?, ?)').run(nodeId, artifact, now());
264
+ },
265
+ /** Inconclusive runs for a node and artefact after an ISO time (null: ever). */
266
+ async countInconclusive(nodeId, artifact, since = null) {
267
+ return db.prepare('SELECT COUNT(*) AS n FROM identity_inconclusive WHERE node_id = ? AND artifact = ? AND at > ?')
268
+ .get(nodeId, artifact, since ?? '').n;
269
+ },
270
+ async addRegistrationFailure(week, reason) {
271
+ db.prepare(`INSERT INTO registration_failures (week, reason, n) VALUES (?, ?, 1)
272
+ ON CONFLICT(week, reason) DO UPDATE SET n = registration_failures.n + 1`).run(week, reason);
273
+ },
274
+ async registrationFailures(sinceWeek = '0000-W00') {
275
+ return db.prepare('SELECT * FROM registration_failures WHERE week >= ? ORDER BY week DESC').all(sinceWeek);
276
+ },
231
277
  async close() { db.close(); },
232
278
  };
233
279
  }
@@ -655,7 +655,7 @@
655
655
  <p class="sub">Listing is open; tiers are earned. The registry runs an automated admission battery against your live endpoints — no paperwork, no gatekeepers, no exceptions. Every verdict is recorded and visible in your node's listing history.</p>
656
656
  <div class="panel pad" style="max-width:56rem">
657
657
  <div class="stage"><span class="k">STAGE A</span><span><b>Conformance</b> — gate to <span class="chip t-community">COMMUNITY</span>, minutes. Health endpoint live; card valid; models list agrees with the card; one blind invocation returns proper usage accounting; a proprietary artefact (<code>urn:proprietary:{vendor}:…</code>) only from that vendor's own namespace, so name open-weight models by their public record (<code>hf:</code>, <code>ollama:</code>). Runs when you verify your registration, on every new card revision, and again at least every 6 hours on the registry's own timer.</span></div>
658
- <div class="stage"><span class="k">STAGE B</span><span><b>Substance</b> — gate to <span class="chip t-verified">VERIFIED</span>, hours. The registry chooses when it runs; nobody can ask for it. <b>Identity fingerprinting:</b> prompts from a private set, at temperature 0, compared with reference answers the registry captured from a deployment of the same weights it trusts. With no reference for your model's artefact, identity is unverified and the node stays at community. A mismatch marks the node <i>disputed</i> and delists it; registering again does not end a dispute, only a resolution the registry records after review. A 409 to a fingerprint prompt stops the run only when your card's revision really changed (then it runs again within the hour, at most 3 times before a run is judged); with the current revision pinned, or beyond those 3, a 409 counts as a reply that does not match. <b>Signed card:</b> the verified tier needs a card whose signature verifies against your JWKS. <b>Card-only listings:</b> if you gave a probe key at registration, probes carrying it are easy to pick out, so the node stays at community until the registry has bought access to your API as an ordinary customer; from then on probes use that access, and the next Stage B can verify the node. <b>Context verification:</b> needle-in-haystack probes at 25/50/90% of the claimed window; overclaims are capped to the verified size, visibly. <b>Capacity ramp:</b> stepped concurrent load; measured TTFT/throughput overrides claims in search results.</span></div>
658
+ <div class="stage"><span class="k">STAGE B</span><span><b>Substance</b> — gate to <span class="chip t-verified">VERIFIED</span>, hours. The registry chooses when it runs; nobody can ask for it. <b>Identity fingerprinting:</b> prompts from a private set, at temperature 0, compared with reference answers the registry captured from a deployment of the same weights it trusts. With no reference for your model's artefact, identity is unverified and the node stays at community. A confirmed mismatch marks the node <i>disputed</i> and delists it; registering again does not end a dispute, only a resolution the registry records after review. The exception is a first mismatch: when every prompt got a reply, the run ends <i>identity inconclusive</i> (not passed, not disputed, and a verified node returns to community), even if no reply matched, because exact replies can differ between processors and engine versions. Stage B then waits until the registry has captured the references again or reviewed the case, and a second mismatch disputes. A 409 to a fingerprint prompt stops the run only when your card's revision really changed (then it runs again within the hour, at most 3 times before a run is judged); with the current revision pinned, or beyond those 3, a 409 counts as a reply that does not match. A 5xx, a 429 (after its Retry-After, or a minute), a 401, 403 or 408, a reply without text, a timeout or a dropped connection is asked again twice; a prompt that still gets nothing is not judged: the run is not passed (a verified node returns to community), nothing is disputed, and Stage B runs again within a day. If your endpoint answers other requests but fails the fingerprint prompts again in the next such run, they count as unanswered and the node is disputed. <b>Signed card:</b> the verified tier needs a card whose signature verifies against your JWKS. <b>Card-only listings:</b> if you gave a probe key at registration, probes carrying it are easy to pick out, so the node stays at community until the registry has bought access to your API as an ordinary customer; from then on probes use that access, and the next Stage B can verify the node. <b>Context verification:</b> needle-in-haystack probes at 25/50/90% of the claimed window; overclaims are capped to the verified size, visibly. <b>Capacity ramp:</b> stepped concurrent load; measured TTFT/throughput overrides claims in search results.</span></div>
659
659
  <div class="stage"><span class="k">STAGE C</span><span><b>Continuous</b> — keeps the tier honest. Liveness sweeps feed a rolling availability score; random blind invocations at unpredictable times, worded like ordinary requests, defeat "benchmark mode". On verified nodes some of them ask an identity prompt, and a reply that is not the reference's brings Stage B within the hour. Sustained liveness failures suspend the listing; blind invocations that keep failing while the node answers its health checks cost it a tier.</span></div>
660
660
  <div class="stage"><span class="k">COVERAGE</span><span><b>What is tested.</b> This registry has tests only for chat offerings (<code>onp.openai.chat/v1</code>). A tier covers only the offerings it could test: speech, embeddings, image or any other offering is listed as <span class="chip untested">UNTESTED</span>, and its tier is capped to <span class="chip t-unverified">UNVERIFIED</span> whatever the node's tier. A node with no chat offering stays unverified, because Stage A has nothing to call.</span></div>
661
661
  </div>
@@ -663,7 +663,7 @@
663
663
  <p class="sub">Everything this registry sends to your endpoints, as the code runs today: how much, how often and what starts it, so you can size your probe allowance. A <i>chat offering</i> is one bound to <code>onp.openai.chat/v1</code>; other offerings get only the health and models checks. Probe calls carry your probe key if you gave one at registration, or, once the registry has bought access to your API as a customer, that access instead; the registry does not pay for calls made with your probe key. Their wording comes from a private set of ordinary requests, the same kind your customers send; it is not published.</p>
664
664
  <div class="panel pad" style="max-width:56rem" id="probe-load-table">
665
665
  <div class="stage"><span class="k">STAGE A</span><span><b>When:</b> when you verify your registration, on each <code>PUT /v0/nodes/{id}/ping</code>, on every new card revision, and at least every 6&nbsp;hours (each gap is random, 4.5 to 6&nbsp;hours); a scheduled run uses the card the registry already holds.<br><b>Sends:</b> 1 GET to your health endpoint, 1 GET to <code>/models</code>, and 1 blind chat completion per chat offering (a short request, at most 32 output tokens): about 4 of each a day.</span></div>
666
- <div class="stage"><span class="k">STAGE B</span><span><b>When:</b> on the registry's schedule, never on request: between 1 and 24&nbsp;hours after your node reaches community; at a random time within 72&nbsp;hours of a change to a chat offering's model, serving, hardware or binding block, a new chat offering, or a change to your API endpoint; within 1&nbsp;hour of a confirmed identity mismatch in a blind call (below), at most once a day; within 1&nbsp;hour after a run stopped because your card's revision changed; again after 7&nbsp;days when a run did not pass; and after a pass at a random time from 1&nbsp;day on, and at most every 91&nbsp;days. That random run is set apart: a run that a change brings does not move it. The registry admin can also run it.<br><b>Sends, per chat offering</b> (up to 20 chat completions, plus one repeat for each identity reply that does not match):
666
+ <div class="stage"><span class="k">STAGE B</span><span><b>When:</b> on the registry's schedule, never on request: between 1 and 24&nbsp;hours after your node reaches community; at a random time within 72&nbsp;hours of a change to a chat offering's model, serving, hardware or binding block, a new chat offering, or a change to your API endpoint; within 1&nbsp;hour of a confirmed identity mismatch in a blind call (below), at most once a day; within 1&nbsp;hour after a run stopped because your card's revision changed; again after 7&nbsp;days when a run did not pass; and after a pass at a random time from 1&nbsp;day on, and at most every 91&nbsp;days. That random run is set apart: a run that a change brings does not move it. The registry admin can also run it.<br><b>Sends, per chat offering</b> (up to 20 chat completions, plus one repeat for each identity reply that does not match, and up to two more asks for each identity prompt that gets a 5xx, a 429, a 401, 403 or 408, no reply text, a timeout or a dropped connection; every offering's identity prompts come first, and an endpoint found unreachable gets nothing more in that run):
667
667
  <br>· <b>Fingerprint battery:</b> 3 prompts drawn at random from the 8 reference prompts the registry holds for your model's artefact, at temperature 0, at most 64 output tokens each. With no reference for the artefact nothing is asked, and the offering cannot be verified.
668
668
  <br>· <b>Calibration:</b> 1 call with about 4,000 characters of text, at most 4 output tokens, to measure your tokenizer.
669
669
  <br>· <b>Context:</b> 3 probes sized at 25, 50 and 90% of the claimed context window, at most 64 output tokens each: about 1.65 times the window in prompt tokens altogether (about 210k tokens for a 128k window).