pikelet-wasm 0.14.0 → 0.16.0

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.
@@ -1,50 +1,50 @@
1
- // Client-side abstention scorer for the wiki pack. Mirrors the math in
2
- // ../../calibrate_abstention.mjs exactly: retrieval signals (d0, margin,
3
- // mean10) plus the corpus-vocabulary known-token fraction from the shipped
4
- // bloom filter, standardized and passed through the fitted logistic model.
5
- // Verdict semantics: 'answer' (strong match), 'weak' (closest match is
6
- // distant — shown with a caveat), 'abstain' (nothing useful in the pack).
7
- // What "match" means is the asset's: pikelet's self-templates-v6 assets
8
- // (calibration.target 'relevance') are fit against off-topic queries, so
9
- // 'abstain' means the pack does not cover the query's topic and 'answer'
10
- // means it does — not that a passage states the asked-for fact. Earlier
11
- // assets were fit against in-domain-unanswerable queries instead. The
12
- // scoring math here is the same for both.
1
+ // Reader-side matchQuality scorer. Mirrors the fit in pikelet/src/calibrate.mjs
2
+ // (and examples/static-wiki-pack/calibrate_abstention.mjs): retrieval signals
3
+ // (d0, margin, mean10) plus the known-token fraction from the shipped bloom,
4
+ // standardized and passed through the fitted logistic model.
13
5
  //
14
- // Assets calibrated by pikelet's self-templates-v2+ may carry an additional
15
- // grounding term (asset.coverage): the fraction of the query's content
16
- // words that appear in the top retrieved passage's text (coverage1,
17
- // exact/stemmed match). Every base feature measures topic similarity, so
18
- // "the corpus discusses this area" and "this passage answers this
19
- // question" are indistinguishable without a grounding term. The term is
20
- // serialized outside features[]/weights[] deliberately: a reader that
21
- // predates it scores the topic-only model against the same thresholds (a
22
- // conservative degradation) instead of hitting an unknown feature name and
23
- // computing NaN. Word rules (min length, stopwords) ship in the asset so
24
- // builder and reader cannot drift.
6
+ // Verdicts: 'answer' (strong), 'weak' (shown with a caveat), 'abstain'.
7
+ // For self-templates-v6 assets (calibration.target 'relevance'), 'abstain'
8
+ // means the pack does not cover the query's topic, not that no passage
9
+ // states the fact. Older assets used a different target; the math is the same.
25
10
  //
26
- // A semantic word-cosine grounding term (maxSim1, folded into grounding1
27
- // via Math.max with coverage1, gated by asset.coverage.useMaxSim) was
28
- // tried twice and reverted twice — see pikelet/src/calibrate.mjs's
29
- // GROUNDING_FEAT design note for the two failure modes (an unrescaled
30
- // version inflated the fitted threshold and caused widespread false
31
- // abstention; a rescaled/damped version fixed that but still made
32
- // real-query behavior worse than plain coverage1 alone). The mechanism
33
- // itself was also measured to cost 200-400 individual per-word encoder
34
- // calls per query once whatever built the calibration asset turned the
35
- // flag on — a 30-80ms search became 1.5-4.6 seconds, with nothing in the
36
- // response indicating why. Removed entirely (not just disabled) rather
37
- // than left as a dormant code path: dead code an external asset can
38
- // silently reactivate isn't actually dead, and both attempts already
39
- // failed for a structural reason (see the design note), not a tuning
40
- // one — there is no scenario where re-adding this via a config flag was
41
- // going to end differently a third time.
11
+ // asset.coverage, when present, adds coverage1: the share of the query's
12
+ // content words found in the top passages. It lives outside
13
+ // features[]/weights[] so a reader that predates it scores the topic-only
14
+ // model instead of NaN. Word rules ship in the asset so builder and reader
15
+ // cannot drift. There is no semantic (maxSim) grounding path; see
16
+ // docs/calibration.md for why it was removed.
17
+ //
18
+ // asset.gate, when present, is a second, distance-only model that alone
19
+ // decides 'abstain': results are hidden only when the retrieval itself is
20
+ // far, never because the query's words are missing from the passages (a
21
+ // paraphrase). The model above then only splits shown results into
22
+ // 'answer' and 'weak'. A reader that predates the gate ignores it and
23
+ // scores as before. See docs/calibration.md, "Two decisions".
42
24
 
43
25
  // Upper bound on asset.coverage.topK. calibrate.mjs ships 5; every passage
44
26
  // counted here is a record hydrated on every query, so a pack must not be
45
27
  // able to turn one query into a hydration of its whole rerank window.
46
28
  export const MAX_COVERAGE_TOP_K = 10;
47
29
 
30
+ // The signals a gate may name: the retrieval-side ones score() computes.
31
+ const GATE_SIGNALS = new Set(['d0', 'margin', 'mean10', 'known_frac']);
32
+
33
+ // A gate that is present but malformed returns undefined, which the caller
34
+ // turns into an unscored scorer: falling back to the coverage model would
35
+ // silently restore the behaviour the gate exists to replace.
36
+ function parseGate(gate) {
37
+ if (gate === undefined) return null;
38
+ if (!gate || typeof gate !== 'object') return undefined;
39
+ const { features, weights, bias, standardize, hard } = gate;
40
+ if (!Array.isArray(features) || features.length === 0 || !Array.isArray(weights) || weights.length !== features.length) return undefined;
41
+ if (!features.every((f) => GATE_SIGNALS.has(f)) || !weights.every(Number.isFinite) || !Number.isFinite(bias)) return undefined;
42
+ const mean = standardize?.mean, std = standardize?.std;
43
+ if (!features.every((f) => Number.isFinite(mean?.[f]) && Number.isFinite(std?.[f]) && std[f] > 0)) return undefined;
44
+ if (!Number.isFinite(hard) || hard < 0 || hard > 1) return undefined;
45
+ return { features, weights, bias, mean, std, hard };
46
+ }
47
+
48
48
  export function createAbstentionScorer(asset, bloomBytes) {
49
49
  if (!asset || !Array.isArray(asset.weights) || !asset.thresholds) return null;
50
50
  // Thresholds that are missing, non-numeric or out of order compare false
@@ -52,6 +52,8 @@ export function createAbstentionScorer(asset, bloomBytes) {
52
52
  // degrade to unscored instead (callers map a null scorer to it).
53
53
  const { hard, weak } = asset.thresholds;
54
54
  if (!Number.isFinite(hard) || !Number.isFinite(weak) || hard < 0 || hard > weak || weak > 1) return null;
55
+ const gate = parseGate(asset.gate);
56
+ if (gate === undefined) return null;
55
57
  const coverageCfg = asset.coverage && typeof asset.coverage.weight === 'number'
56
58
  && Number.isFinite(asset.coverage.mean) && Number.isFinite(asset.coverage.std)
57
59
  ? asset.coverage : null;
@@ -80,13 +82,8 @@ export function createAbstentionScorer(asset, bloomBytes) {
80
82
  // reduced weight — mirrors pikelet/src/calibrate.mjs
81
83
  // coverageFrac exactly (the weight ships in the asset).
82
84
  const commonWordWeight = coverageCfg?.commonWordWeight ?? 1 / 3;
83
- // Light suffix stripping so "quantize" grounds against "quantization"
84
- // and "configure" against "configuration" — kept byte-identical to
85
- // pikelet/src/calibrate.mjs's stem() (same suffix list and order):
86
- // present() otherwise only forgave plurals, so any word-form mismatch
87
- // at all scored zero coverage for a passage that plainly answers the
88
- // query. Deliberately conservative (STEM_MIN_LEN guards short words
89
- // like "king" from over-stripping); not a general stemmer.
85
+ // Light suffix stripping ("configure" grounds "configuration"). Must stay
86
+ // byte-identical to calibrate.mjs's stem() (same suffix list and order).
90
87
  const STEM_MIN_LEN = 4;
91
88
  const STEM_SUFFIXES = ['ization', 'isation', 'ication', 'ation', 'ition', 'tion', 'ing', 'ed', 'ate', 'ize', 'ise'];
92
89
  function stem(w) {
@@ -96,37 +93,23 @@ export function createAbstentionScorer(asset, bloomBytes) {
96
93
  if (w.length - 1 >= STEM_MIN_LEN && w.endsWith('e')) return w.slice(0, -1);
97
94
  return w;
98
95
  }
99
- // Kept byte-identical to pikelet/src/calibrate.mjs's stripPossessive:
100
- // the tokenizer regex keeps the apostrophe, so a possessive ("darcy's")
101
- // is one token that never matches a plain mention ("darcy") without
102
- // this, in either direction.
96
+ // Byte-identical to calibrate.mjs's stripPossessive: the tokenizer keeps
97
+ // apostrophes, so "darcy's" would never match "darcy".
103
98
  function stripPossessive(w) {
104
99
  if (w.endsWith("'s")) return w.slice(0, -2);
105
100
  if (w.endsWith("s'")) return w.slice(0, -1);
106
101
  if (w.endsWith("'")) return w.slice(0, -1);
107
102
  return w;
108
103
  }
109
- // Kept byte-identical to pikelet/src/calibrate.mjs's isNumeral: a
110
- // numeral is exempted from the coverageMinLen floor because it is
111
- // often the only token distinguishing two otherwise-identical
112
- // passages ("Chamber 4" vs "Chamber 5"), unlike an ordinary short
113
- // word the floor exists to drop.
104
+ // Byte-identical to calibrate.mjs's isNumeral: numerals skip the
105
+ // coverageMinLen floor ("Chamber 4" vs "Chamber 5").
114
106
  const isNumeral = (w) => /^\d+$/.test(w);
115
- // A word present only in a passage's heading, not its body, still
116
- // grounds the query, at reduced credit — kept byte-identical to
117
- // pikelet/src/calibrate.mjs's HEADING_COVERAGE_WEIGHT. Full credit
118
- // there is the free-coverage bug body/heading splitting exists to fix
119
- // (a title-templated positive's own words ARE the heading); zero
120
- // credit is the opposite failure (a real rank-1 hit whose match is in
121
- // the heading scoring no coverage at all).
107
+ // A heading-only match grounds at reduced credit, byte-identical to
108
+ // calibrate.mjs's HEADING_COVERAGE_WEIGHT.
122
109
  const HEADING_COVERAGE_WEIGHT = 0.5;
123
- // Returns { value, grounding } rather than writing grounding detail to
124
- // a shared variable: score() is async, so a module- or closure-level
125
- // "last grounding" write would race between two concurrent queries
126
- // against the same open pack if anything ever awaited between this
127
- // call and reading it back — the second call's write could land, and
128
- // get read back, before the first call's own return. Threading the
129
- // value through the return keeps it local to this call regardless.
110
+ // Returns { value, grounding } instead of writing to shared state, so two
111
+ // concurrent queries on the same open pack cannot read each other's
112
+ // grounding.
130
113
  function coverageFrac(text, passages) {
131
114
  const content = (String(text).toLowerCase().match(/[a-z0-9']+/g) || [])
132
115
  .map(stripPossessive)
@@ -197,21 +180,14 @@ export function createAbstentionScorer(asset, bloomBytes) {
197
180
  }
198
181
 
199
182
  return {
200
- // The caller must hydrate the top passagesNeeded results' text
201
- // before scoring when usesPassage is true; the coverage/maxSim
202
- // terms read them (older assets scored one passage; topK now
203
- // defaults to it). maxSim never ships without coverage (calibrate.mjs
204
- // fits them together), so coverageCfg.topK already covers both.
183
+ // When usesPassage is true the caller must hydrate the top passagesNeeded
184
+ // results' text before scoring; coverage reads them.
205
185
  usesPassage: !!coverageCfg,
206
186
  passagesNeeded: coverageCfg ? (coverageCfg.topK || 1) : 0,
207
187
  async score(queryText, results, passageTexts, options = {}) {
208
- // Fit at build time (pikelet/src/calibrate.mjs) always scores a
209
- // fixed top-10 window (K = min(10, candidates)), independent of
210
- // whatever k a caller later passes to query(). Slicing to the
211
- // caller's k here before windowing would shrink margin/mean10/
212
- // coverage's inputs at small k and change the verdict for an
213
- // identical retrieval — the window, not the caller's k, is what
214
- // must match the fit.
188
+ // The fit always scores a fixed top-10 window (K = min(10, candidates)),
189
+ // whatever k the caller passes. Slicing to k first would change the
190
+ // verdict for an identical retrieval.
215
191
  const top = results.slice(0, Math.min(10, results.length));
216
192
  const d0 = top.length ? top[0].distance : 1;
217
193
  const margin = top.length > 1
@@ -223,23 +199,16 @@ export function createAbstentionScorer(asset, bloomBytes) {
223
199
  asset.features.forEach((f, j) => {
224
200
  z += ((signals[f] - asset.standardize.mean[f]) / asset.standardize.std[f]) * asset.weights[j];
225
201
  });
226
- // Local to this call (not module/closure state — see
227
- // coverageFrac's comment) so concurrent queries against the
228
- // same open pack can never see each other's grounding detail.
202
+ // Local to this call so concurrent queries never share grounding detail.
229
203
  let grounding = null;
230
204
  if (coverageCfg) {
231
- // passageTexts is hydrated by the caller for the fixed
232
- // top-COVERAGE_TOP_PASSAGES window (see passagesNeeded
233
- // below), independent of the caller's k, matching
205
+ // passageTexts covers the fixed top-COVERAGE_TOP_PASSAGES window, matching
234
206
  // calibrate.mjs's top.slice(0, COVERAGE_TOP_PASSAGES).
235
207
  const passages = Array.isArray(passageTexts) ? passageTexts : [passageTexts];
236
208
  const coverage = coverageFrac(queryText, passages);
237
209
  signals.coverage1 = coverage.value;
238
210
  grounding = coverage.grounding;
239
- // grounding1 is coverage1 alone — see this file's header
240
- // comment and calibrate.mjs's GROUNDING_FEAT design note
241
- // for why a semantic (maxSim1) blend was tried twice and
242
- // removed both times.
211
+ // grounding1 is coverage1 alone (see docs/calibration.md).
243
212
  z += ((signals.coverage1 - coverageCfg.mean) / (coverageCfg.std || 1)) * coverageCfg.weight;
244
213
  }
245
214
  // A malformed asset (unknown feature name, non-numeric term) must
@@ -247,6 +216,14 @@ export function createAbstentionScorer(asset, bloomBytes) {
247
216
  // both thresholds and answers everything.
248
217
  if (!Number.isFinite(z)) return { p: null, verdict: 'unscored', signals };
249
218
  const p = 1 / (1 + Math.exp(-z));
219
+ if (gate) {
220
+ let zGate = gate.bias;
221
+ gate.features.forEach((f, j) => { zGate += ((signals[f] - gate.mean[f]) / gate.std[f]) * gate.weights[j]; });
222
+ if (!Number.isFinite(zGate)) return { p: null, verdict: 'unscored', signals };
223
+ const pGate = 1 / (1 + Math.exp(-zGate));
224
+ const verdict = pGate < gate.hard ? 'abstain' : p < asset.thresholds.weak ? 'weak' : 'answer';
225
+ return { p, pGate, verdict, signals, grounding };
226
+ }
250
227
  const verdict = p < asset.thresholds.hard ? 'abstain'
251
228
  : p < asset.thresholds.weak ? 'weak' : 'answer';
252
229
  return { p, verdict, signals, grounding };
@@ -14,7 +14,8 @@ export function httpRangeSource(url, options = {}) {
14
14
  // GitHub's release CDN answers rate-limited range bursts with 429
15
15
  // and a Retry-After of up to a minute; honoring it (capped) beats
16
16
  // guessing. Without one, exponential backoff capped at 15 s.
17
- const after = Number(response.headers.get('retry-after'));
17
+ const raw = response.headers.get('retry-after');
18
+ const after = raw?.trim() ? Number(raw) : Number.NaN;
18
19
  if (Number.isFinite(after) && after >= 0 && after <= 90) return after * 1000;
19
20
  return Math.min(15000, 250 * 2 ** attempt);
20
21
  };
@@ -27,13 +28,43 @@ export function httpRangeSource(url, options = {}) {
27
28
  : (options.cacheKeyParam === null || options.cacheKeyParam === false) ? null
28
29
  : String(options.cacheKeyParam);
29
30
  let full = null;
31
+ // One full download, shared: every read in flight when the host first
32
+ // answers 200 would otherwise start its own (rerank runs 32 at once).
33
+ let fullPending = null;
34
+ // A body this reader will not consume is cancelled, so the connection
35
+ // goes back to the pool instead of waiting on an unread stream.
36
+ const discard = (response) => response?.body?.cancel?.().catch(() => {});
37
+ // Weak comparison (RFC 9110 8.8.3.2): W/"x" and "x" name the same entity.
38
+ const sameEtag = (a, b) => a.replace(/^W\//, '') === b.replace(/^W\//, '');
30
39
  // A parent reached through a publisher-supplied locator is confined to the
31
40
  // child's origin and directory, and 5.1.1 applies that rule to EVERY
32
41
  // redirect hop before it is followed. The guard throws to refuse a hop.
33
42
  // With a guard set, reads never auto-follow: only the HEAD walk below,
34
43
  // which checks each hop, may move the target.
35
44
  const redirectGuard = typeof options.redirectGuard === 'function' ? options.redirectGuard : null;
36
- const readInit = (headers) => (redirectGuard ? { headers, redirect: 'error' } : { headers });
45
+ const readInit = (headers, signal) => (redirectGuard ? { headers, redirect: 'error', signal } : { headers, signal });
46
+
47
+ // A host that accepts a request and then sends nothing would leave the
48
+ // read, and the query waiting on it, pending forever. Every await on the
49
+ // host (headers, and each body chunk) gets this long to make progress;
50
+ // the transport is aborted when it does not, for transports that honor
51
+ // a signal. Retry sleeps are not on this clock. 0 disables it.
52
+ const idleTimeoutMs = options.idleTimeoutMs ?? 30_000;
53
+ if (!(Number.isFinite(idleTimeoutMs) && idleTimeoutMs >= 0)) {
54
+ throw new TypeError(`idleTimeoutMs must be a non-negative number of milliseconds, got ${options.idleTimeoutMs}`);
55
+ }
56
+ const idle = (promise, controller, what) => {
57
+ if (idleTimeoutMs === 0) return promise;
58
+ let timer;
59
+ const stalled = new Promise((_, reject) => {
60
+ timer = setTimeout(() => {
61
+ const err = Object.assign(new Error(`${what}: the host sent nothing for ${idleTimeoutMs / 1000} s; gave up`), { code: 'ETIMEDOUT' });
62
+ controller?.abort(err);
63
+ reject(err);
64
+ }, idleTimeoutMs);
65
+ });
66
+ return Promise.race([promise, stalled]).finally(() => clearTimeout(timer));
67
+ };
37
68
 
38
69
  // Redirect memoization. A host that answers with a redirect (GitHub
39
70
  // release assets: github.com 302s every hit to a signed CDN URL) would
@@ -56,7 +87,9 @@ export function httpRangeSource(url, options = {}) {
56
87
  let viaRedirect = false;
57
88
  try {
58
89
  for (let hop = 0; hop < 5; hop++) {
59
- const probe = await fetch(target, { method: 'HEAD', redirect: 'manual' });
90
+ const controller = new AbortController();
91
+ const probe = await idle(fetch(target, { method: 'HEAD', redirect: 'manual', signal: controller.signal }),
92
+ controller, `HEAD ${target}`);
60
93
  const location = probe.headers.get('location');
61
94
  if (probe.status >= 300 && probe.status < 400 && location) {
62
95
  const next = new URL(location, target).href;
@@ -75,7 +108,7 @@ export function httpRangeSource(url, options = {}) {
75
108
  }
76
109
  if (probe.type === 'opaqueredirect' || probe.status === 0) {
77
110
  // Browser CORS: the chain is invisible; let fetch
78
- // auto-follow per read as before.
111
+ // auto-follow per read.
79
112
  target = url;
80
113
  viaRedirect = false;
81
114
  } else if (probe.ok) {
@@ -106,8 +139,9 @@ export function httpRangeSource(url, options = {}) {
106
139
  } catch (err) {
107
140
  // A refused hop is a verdict, not a probe failure: falling back
108
141
  // to the original URL would retry the same redirect. So is a
109
- // replaced artifact.
110
- if (err?.redirectRefused || err?.artifactChanged) {
142
+ // replaced artifact, and so is a host that never answered
143
+ // (the read that followed would wait out the same silence).
144
+ if (err?.redirectRefused || err?.artifactChanged || err?.code === 'ETIMEDOUT') {
111
145
  resolving = null;
112
146
  throw err;
113
147
  }
@@ -149,6 +183,7 @@ export function httpRangeSource(url, options = {}) {
149
183
  // After a one-time full download (host ignored Range) every read
150
184
  // is served from memory; no further requests go out.
151
185
  if (full) return full.subarray(offset, offset + length);
186
+ if (fullPending) return (await fullPending).subarray(offset, offset + length);
152
187
  stats.requests += 1;
153
188
  stats.bytes += length;
154
189
  const end = offset + length - 1;
@@ -168,18 +203,28 @@ export function httpRangeSource(url, options = {}) {
168
203
  const targetFor = ({ target, viaRedirect }) => (cacheKeyParam && !viaRedirect
169
204
  ? `${target}${target.includes('?') ? '&' : '?'}${cacheKeyParam}=${offset}-${end}`
170
205
  : target);
171
- let response = await fetch(targetFor(pinned), readInit(headers));
206
+ const what = `range read of bytes ${offset}-${end} from ${url}`;
207
+ let controller = null;
208
+ const send = (target) => {
209
+ controller = new AbortController();
210
+ return idle(fetch(target, readInit(headers, controller.signal)), controller, what);
211
+ };
212
+ const bodyStep = (promise) => idle(promise, controller, what);
213
+ let response = await send(targetFor(pinned));
172
214
  if ((response.status === 401 || response.status === 403) && pinned.viaRedirect) {
173
215
  // The pinned signed URL expired; resolve a fresh one once
174
216
  // and retry. Concurrent reads share the re-resolution.
175
217
  if (resolvedTarget === pinned) resolvedTarget = null;
176
218
  stats.retries += 1;
177
- response = await fetch(targetFor(await resolveTarget()), readInit(headers));
219
+ discard(response);
220
+ response = await send(targetFor(await resolveTarget()));
178
221
  }
179
222
  for (let attempt = 0; RETRYABLE.has(response.status) && attempt < maxRetries; attempt++) {
180
223
  stats.retries += 1;
181
- await new Promise((resolve) => setTimeout(resolve, retryDelayMs(attempt, response)));
182
- response = await fetch(targetFor(resolvedTarget || pinned), readInit(headers));
224
+ const delay = retryDelayMs(attempt, response);
225
+ discard(response);
226
+ await new Promise((resolve) => setTimeout(resolve, delay));
227
+ response = await send(targetFor(resolvedTarget || pinned));
183
228
  }
184
229
 
185
230
  // A pack is content-addressed bytes: a body the host encoded is
@@ -193,84 +238,142 @@ export function httpRangeSource(url, options = {}) {
193
238
  throw new Error(`range read returned Content-Encoding: ${encoding}; a .pikelet must be served unencoded`);
194
239
  }
195
240
  if (response.status === 206) {
196
- // A 206 must be the range we asked for, and must say so: a
197
- // host (or cache) answering with a different slice would
198
- // otherwise be caught only downstream, by the digest on
199
- // whatever that slice happens to be part of — and the lazy
200
- // sketch rows have no per-row digest yet. RFC 9110 requires
201
- // Content-Range on a 206, so its absence fails closed too.
202
- const contentRange = response.headers.get('content-range');
203
- const m = contentRange && /^bytes (\d+)-(\d+)\//.exec(contentRange);
204
- if (!m || Number(m[1]) !== offset || Number(m[2]) > end) {
205
- throw new Error(`range read returned Content-Range ${contentRange || '(missing)'}, requested bytes ${offset}-${end}`);
206
- }
207
- const body = new Uint8Array(await response.arrayBuffer());
208
- if (body.length !== Number(m[2]) - Number(m[1]) + 1) {
209
- throw new Error(`range read body is ${body.length} bytes for Content-Range ${contentRange}`);
210
- }
211
- return body;
212
- }
213
- if (response.status === 200) {
214
- // If-Range has a defined meaning: a 200 instead of the
215
- // requested 206 means either the host ignores Range, or the
216
- // pinned ETag no longer matches (the artifact was replaced).
217
- // Those need different handling — slices of a replaced file
218
- // don't match what the manifest describes, and format-2's
219
- // lexical segment above 8 MiB carries only a whole-segment
220
- // digest, so postings read from it would go unverified.
221
- // Only fall back when the ETag still matches (or neither
222
- // side has one to compare).
223
- if (stats.etag) {
224
- const responseEtag = response.headers.get('etag');
225
- if (responseEtag !== stats.etag) {
241
+ // A slice of a replaced file must not mix with the pinned one:
242
+ // If-Range guards this only for a strong pinned ETag on a host
243
+ // that honors it, and lexical windows and format-1 sketch rows
244
+ // have no per-read digest. Compare whenever both sides have an
245
+ // ETag; with none pinned (HEAD failed), the first one seen pins.
246
+ const responseEtag = response.headers.get('etag');
247
+ if (responseEtag) {
248
+ if (!stats.etag) stats.etag = responseEtag;
249
+ else if (!sameEtag(responseEtag, stats.etag)) {
250
+ discard(response);
226
251
  throw pikeletError(
227
252
  PIKELET_ERROR_CODES.ARTIFACT_CHANGED,
228
- `artifact changed on the host: expected ETag ${stats.etag}, got ${responseEtag || '(missing)'}`,
253
+ `artifact changed on the host: expected ETag ${stats.etag}, got ${responseEtag} on a range read`,
229
254
  { expectedEtag: stats.etag, actualEtag: responseEtag },
230
255
  );
231
256
  }
232
257
  }
233
- // An unknown size must refuse, not pass the gate: with no
234
- // Content-Length (chunked body) and init() never called,
235
- // size would be 0 and the cap check silently vacuous.
236
- const size = Number(response.headers.get('content-length')) || this.size || 0;
237
- if (size <= 0) {
238
- throw new Error('host ignores Range and reports no size; refusing unbounded full download (call init() first or fix the host)');
239
- }
240
- if (size > maxFullFallbackBytes) {
241
- throw new Error(`host ignores Range and the file is ${size} bytes; refusing full download`);
258
+ // A 206 must be the range we asked for and say so (RFC 9110 requires
259
+ // Content-Range): a wrong slice would otherwise be caught only by a
260
+ // downstream digest, and format-1 sketch rows have no per-row digest.
261
+ const contentRange = response.headers.get('content-range');
262
+ const m = contentRange && /^bytes (\d+)-(\d+)\//.exec(contentRange);
263
+ if (!m || Number(m[1]) !== offset || Number(m[2]) < offset || Number(m[2]) > end) {
264
+ discard(response);
265
+ throw new Error(`range read returned Content-Range ${contentRange || '(missing)'}, requested bytes ${offset}-${end}`);
242
266
  }
243
- // Declared sizes are advisory (a chunked body can stream more
244
- // than any header claimed), so the cap is enforced on the
245
- // bytes actually received, aborting as soon as it is crossed.
267
+ const expected = Number(m[2]) - Number(m[1]) + 1;
246
268
  const reader = response.body?.getReader?.();
269
+ // Real fetch responses stream: stop at the range boundary,
270
+ // before an untrusted host can buffer an unbounded body.
271
+ // Array-buffer-only custom transports retain their old API.
247
272
  if (!reader) {
248
- const bytes = new Uint8Array(await response.arrayBuffer());
249
- if (bytes.length > maxFullFallbackBytes) {
250
- throw new Error(`host ignores Range and streamed ${bytes.length} bytes; refusing full download over ${maxFullFallbackBytes}`);
273
+ const body = new Uint8Array(await bodyStep(response.arrayBuffer()));
274
+ if (body.length !== expected) {
275
+ throw new Error(`range read body is ${body.length} bytes for Content-Range ${contentRange}`);
251
276
  }
252
- full = bytes;
253
- } else {
254
- const chunks = [];
255
- let received = 0;
277
+ return body;
278
+ }
279
+ const chunks = [];
280
+ let received = 0;
281
+ try {
256
282
  for (;;) {
257
- const { done, value } = await reader.read();
283
+ const { done, value } = await bodyStep(reader.read());
258
284
  if (done) break;
259
285
  received += value.byteLength;
260
- if (received > maxFullFallbackBytes) {
286
+ if (received > expected) {
261
287
  await reader.cancel().catch(() => {});
262
- throw new Error(`host ignores Range and streamed over ${maxFullFallbackBytes} bytes; aborting full download`);
288
+ throw new Error(`range read body exceeds ${expected} bytes for Content-Range ${contentRange}`);
263
289
  }
264
290
  chunks.push(value);
265
291
  }
266
- full = new Uint8Array(received);
292
+ if (received !== expected) {
293
+ throw new Error(`range read body is ${received} bytes for Content-Range ${contentRange}`);
294
+ }
295
+ const body = new Uint8Array(received);
267
296
  let at = 0;
268
- for (const chunk of chunks) { full.set(chunk, at); at += chunk.byteLength; }
297
+ for (const chunk of chunks) { body.set(chunk, at); at += chunk.byteLength; }
298
+ return body;
299
+ } finally {
300
+ reader.releaseLock();
301
+ }
302
+ }
303
+ if (response.status === 200) {
304
+ // Another read already started the full download: this body
305
+ // is the same file again, so drop it and share that one.
306
+ if (fullPending) {
307
+ discard(response);
308
+ return (await fullPending).subarray(offset, offset + length);
309
+ }
310
+ fullPending = (async () => {
311
+ // Under If-Range, a 200 instead of 206 means the host ignores Range or the
312
+ // pinned ETag no longer matches (the artifact was replaced). Only the first
313
+ // may fall back to a full download: slices of a replaced file don't match
314
+ // the manifest, and a large lexical segment has only a whole-segment digest.
315
+ // So fall back only when the ETag still matches (or neither side has one).
316
+ if (stats.etag) {
317
+ const responseEtag = response.headers.get('etag');
318
+ if (!responseEtag || !sameEtag(responseEtag, stats.etag)) {
319
+ discard(response);
320
+ throw pikeletError(
321
+ PIKELET_ERROR_CODES.ARTIFACT_CHANGED,
322
+ `artifact changed on the host: expected ETag ${stats.etag}, got ${responseEtag || '(missing)'}`,
323
+ { expectedEtag: stats.etag, actualEtag: responseEtag },
324
+ );
325
+ }
326
+ }
327
+ // An unknown size must refuse, not pass the gate: with no
328
+ // Content-Length (chunked body) and init() never called,
329
+ // size would be 0 and the cap check silently vacuous.
330
+ const size = Number(response.headers.get('content-length')) || this.size || 0;
331
+ if (size <= 0) {
332
+ throw new Error('host ignores Range and reports no size; refusing unbounded full download (call init() first or fix the host)');
333
+ }
334
+ if (size > maxFullFallbackBytes) {
335
+ throw new Error(`host ignores Range and the file is ${size} bytes; refusing full download`);
336
+ }
337
+ // Declared sizes are advisory (a chunked body can stream more
338
+ // than any header claimed), so the cap is enforced on the
339
+ // bytes actually received, aborting as soon as it is crossed.
340
+ const reader = response.body?.getReader?.();
341
+ if (!reader) {
342
+ const bytes = new Uint8Array(await bodyStep(response.arrayBuffer()));
343
+ if (bytes.length > maxFullFallbackBytes) {
344
+ throw new Error(`host ignores Range and streamed ${bytes.length} bytes; refusing full download over ${maxFullFallbackBytes}`);
345
+ }
346
+ full = bytes;
347
+ } else {
348
+ const chunks = [];
349
+ let received = 0;
350
+ for (;;) {
351
+ const { done, value } = await bodyStep(reader.read());
352
+ if (done) break;
353
+ received += value.byteLength;
354
+ if (received > maxFullFallbackBytes) {
355
+ await reader.cancel().catch(() => {});
356
+ throw new Error(`host ignores Range and streamed over ${maxFullFallbackBytes} bytes; aborting full download`);
357
+ }
358
+ chunks.push(value);
359
+ }
360
+ full = new Uint8Array(received);
361
+ let at = 0;
362
+ for (const chunk of chunks) { full.set(chunk, at); at += chunk.byteLength; }
363
+ }
364
+ stats.fullFallback = true;
365
+ console.warn('.pikelet host does not honor Range; fell back to a one-time full download');
366
+ return full;
367
+ })();
368
+ try {
369
+ return (await fullPending).subarray(offset, offset + length);
370
+ } catch (err) {
371
+ discard(response);
372
+ fullPending = null; // a later read may try again
373
+ throw err;
269
374
  }
270
- stats.fullFallback = true;
271
- console.warn('.pikelet host does not honor Range; fell back to a one-time full download');
272
- return full.subarray(offset, offset + length);
273
375
  }
376
+ discard(response);
274
377
  throw new Error(`range read failed: HTTP ${response.status}`);
275
378
  },
276
379
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pikelet-wasm",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "Vector search engine and .pikelet artifact readers/builders, in WebAssembly. Compile a corpus into one self-contained, hash-verified search file, or use the underlying HNSW engine directly. Runs in Node.js, browsers, and Cloudflare Workers with no native dependencies.",
5
5
  "main": "src/pikelet.js",
6
6
  "types": "src/pikelet.d.ts",
@@ -59,10 +59,6 @@
59
59
  "default": "./src/pikelet.js"
60
60
  }
61
61
  },
62
- "./artifact": {
63
- "types": "./src/artifact/pikelet-artifact.d.ts",
64
- "default": "./src/artifact/pikelet-artifact.js"
65
- },
66
62
  "./complete": {
67
63
  "types": "./complete/index.d.ts",
68
64
  "workerd": "./complete/index.mjs",
@@ -120,6 +116,7 @@
120
116
  "LICENSE",
121
117
  "README.md",
122
118
  "CHANGELOG.md",
119
+ "FORMAT.md",
123
120
  "NOTICE"
124
121
  ],
125
122
  "scripts": {