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.
@@ -52,7 +52,7 @@ export function planAppendability({ qiKind, corpusIngest = null, assertIngest =
52
52
  else if (qiKind === 2) encoderSource = 'host'; // the host supplies the named encoder
53
53
  else throw new Error(`unsupported query-interpretation kind ${qiKind} for append`);
54
54
 
55
- if (corpusIngest !== null && corpusIngest !== undefined) {
55
+ if (corpusIngest !== null) {
56
56
  if (assertIngest) {
57
57
  throw new Error('the base declares corpus.ingest; --assert-ingest would override an artifact\'s own declaration (6.1)');
58
58
  }
@@ -117,14 +117,10 @@ export function planLayer({
117
117
  };
118
118
  for (const id of remove) setOne(id, '--remove');
119
119
 
120
- // Each pair is [oldId, target]. `target` is the CALLER's way of naming
121
- // which new record supersedes oldId: a number is a resolved local index
122
- // into this layer's own records, which the producer computed by matching
123
- // the --supersede path against the chunks that path produced. A
124
- // non-numeric target (a raw path the producer could not resolve) falls
125
- // back to positional assignment, which is what this did for every pair —
126
- // so `--supersede 5=a.md --supersede 9=b.md` bound 5 to whichever chunk
127
- // happened to land first, regardless of which file produced it.
120
+ // Each pair is [oldId, target]. A numeric target is a local index into
121
+ // this layer's records, resolved by the producer from the chunks the
122
+ // --supersede path produced. A non-numeric target (a path the producer
123
+ // could not resolve) falls back to positional assignment.
128
124
  const supersessions = [];
129
125
  let nextNewId = rowBase;
130
126
  const claimed = new Set();
@@ -17,8 +17,7 @@ import { testBit, bitsetBytesFor } from './tombstones.mjs';
17
17
  * tiers, and take no part in id resolution.
18
18
  *
19
19
  * Every per-tier construction in section 5 ranges over search tiers, so the
20
- * base is always included — "for every layer" would literally have excluded it,
21
- * which is the bug the term exists to prevent.
20
+ * base is always included ("for every layer" would exclude it).
22
21
  */
23
22
  export function buildIntervalTable(members) {
24
23
  if (!Array.isArray(members) || members.length === 0) {
@@ -31,7 +31,7 @@ export const MAX_HEADS = 17;
31
31
  const isHex64 = (v) => typeof v === 'string' && /^[0-9a-f]{64}$/.test(v);
32
32
  const hexToBytes = (hex) => {
33
33
  const out = new Uint8Array(32);
34
- for (let i = 0; i < 32; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
34
+ for (let i = 0; i < 32; i++) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
35
35
  return out;
36
36
  };
37
37
  const bytesToHex = (bytes) => [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
@@ -64,12 +64,10 @@ export function planCompaction({ rowTotal, headBitset }) {
64
64
  * Build a `lineage-v1` segment (kind 7), REQUIRED for a base compacted from a
65
65
  * chain.
66
66
  *
67
- * The HEAD TABLE is what lets a citation against any head of the compacted
68
- * chain translate — not only the last one. Draft 2's segment named only the old
69
- * head, so once layers were retired a citation made while H3 was published was
70
- * unresolvable, and a chain compacted twice could not recognize the intermediate
71
- * base. The previous compacted base is this table's depth-0 entry, so retaining
72
- * intermediate compacted bases gives multi-hop translation with nothing further.
67
+ * The HEAD TABLE lets a citation against any head of the compacted chain
68
+ * translate, not only the last one. The previous compacted base is its
69
+ * depth-0 entry, so retaining intermediate compacted bases gives multi-hop
70
+ * translation with nothing further.
73
71
  *
74
72
  * @param {{heads: Array<{identity: string, rowTotal: number, depth: number}>,
75
73
  * headBitset: Uint8Array, oldRowTotal: number,
@@ -32,7 +32,8 @@ const isCount = (v, max = MAX_RECORDS) => Number.isSafeInteger(v) && v >= 0 && v
32
32
  export function canonicalJson(value) {
33
33
  if (value === null || typeof value !== 'object') return JSON.stringify(value);
34
34
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
35
- const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort();
35
+ // Code-unit order, not localeCompare: key order is part of the pack identity.
36
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
36
37
  return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`;
37
38
  }
38
39
 
@@ -18,18 +18,15 @@
18
18
  // supplied lineage map (section 7), then each layer's confined
19
19
  // `parent.locator`, then a host resolver. The lineage map is the cheaper path
20
20
  // when available, since every location is known up front and members open in
21
- // one wave; the locator walk is sequential by nature, because each hop's
22
- // location is only known once its child's manifest has been read.
23
- //
24
- // This comment used to claim locator following "is wired". It was not: this
25
- // module did not import layer-locator.mjs at all, so every ancestor had to be
26
- // named by the caller and a published chain could not be mounted from its head.
21
+ // one wave; the locator walk is sequential, because each hop's location is
22
+ // only known once its child's manifest has been read.
27
23
 
28
24
  import { openPikeletFile, readChainMemberShell, readMemberManifest, base64Bytes, LEXICAL_CANDIDATES, LEXICAL_CUTOFF } from './index.mjs';
29
25
  import { resolveParentLocation, assertConfined } from './layer-locator.mjs';
30
26
  import { httpRangeSource } from './sources.mjs';
31
- import { fuseCandidates, FUSION_DEFAULTS } from './fusion.mjs';
27
+ import { fuseCandidates, FUSION_DEFAULTS, fusionDefaultsFor } from './fusion.mjs';
32
28
  import { parseTombstoneSegment, firstSupersetViolation } from './tombstones.mjs';
29
+ import { groundQuery, GROUNDING_PASSAGES } from './grounding.mjs';
33
30
  import { validateAgainstParent, chainIngestDeclaration, validateIngestAgainstChain, LAYER_PROFILE, MAX_DEPTH } from './layer-manifest.mjs';
34
31
  import { parseInheritedQuerySegment, unionBloom } from './layer-encoder.mjs';
35
32
  import {
@@ -43,10 +40,9 @@ import {
43
40
  // can name the budget it hit.
44
41
  export const CHAIN_DEFAULTS = Object.freeze({
45
42
  maxDepth: MAX_DEPTH,
46
- // 5.5: the reader's limit MUST be finite and MUST be declared. 13.1
47
- // measured the inherited fit out to 40% drift with no degradation, so 0.20
48
- // is conservative rather than a guess — but it stays a reader policy, not a
49
- // format constant, so it can be revisited without a format change.
43
+ // 5.5: the reader's limit MUST be finite and declared. 0.20 is
44
+ // conservative (13.1 measured no degradation out to 40% drift), and it is
45
+ // a reader policy, not a format constant.
50
46
  readerDriftLimit: 0.20,
51
47
  });
52
48
 
@@ -80,16 +76,20 @@ async function walkToBase(head, options) {
80
76
  let expectIdentity = null;
81
77
  let childFetch = null;
82
78
  for (let hop = 0; hop <= maxDepth; hop++) {
83
- const peek = await readMemberManifest(cursor, options);
84
- if (expectIdentity !== null && peek.identity !== expectIdentity) {
85
- throw new Error(`chain member at ${describeLocation(cursor)} has identity ${peek.identity.slice(0, 12)}… `
86
- + `but its child named ${expectIdentity.slice(0, 12)}…: the located artifact is not the parent the chain commits to (3.2)`);
79
+ // Above the head, the header's identity is compared with the one the
80
+ // child named before the parent's manifest is fetched.
81
+ let peek;
82
+ try {
83
+ peek = await readMemberManifest(cursor, { ...options, expectedIdentity: expectIdentity ?? undefined });
84
+ } catch (err) {
85
+ if (err?.code !== 'IDENTITY_MISMATCH') throw err;
86
+ throw new Error(`chain member at ${describeLocation(cursor)} has identity ${err.identity.slice(0, 12)}… `
87
+ + `but its child named ${expectIdentity.slice(0, 12)}…: the located artifact is not the parent the chain commits to (3.2)`, { cause: err });
87
88
  }
88
89
  if (!peek.isLayer) return chain; // reached the base
89
90
  if (!peek.parent) throw new Error('a layer manifest carries no layer.parent (3.2)');
90
91
  // A child is a URL whether it arrived as a range source or, one hop
91
- // up, as the URL string a locator resolved to. Classifying every
92
- // string as a file path sent that second hop to fileSource.
92
+ // up, as the URL string a locator resolved to.
93
93
  const childLocation = typeof cursor === 'string' ? cursor : (cursor.url ?? cursor.location ?? null);
94
94
  const childIsFile = typeof cursor === 'string' && !isHttpUrl(cursor);
95
95
  if (typeof cursor === 'object' && typeof cursor?.fetch === 'function') childFetch = cursor.fetch;
@@ -134,7 +134,15 @@ function memberIntegritySummary(opened) {
134
134
  const values = [...new Set(infos.map((i) => i[key]))];
135
135
  return values.length === 1 ? values[0] : 'mixed';
136
136
  };
137
- return { corpusIntegrity: one('corpusIntegrity'), indexRowIntegrity: one('indexRowIntegrity') };
137
+ const lexical = infos.filter((i) => i.lexical);
138
+ const lexicalValues = [...new Set(lexical.map((i) => i.lexical.integrity))];
139
+ return {
140
+ corpusIntegrity: one('corpusIntegrity'),
141
+ indexRowIntegrity: one('indexRowIntegrity'),
142
+ // null when no member carries a lexical segment.
143
+ lexicalIntegrity: lexical.length ? (lexicalValues.length === 1 ? lexicalValues[0] : 'mixed') : null,
144
+ lexicalVerified: lexical.length ? lexical.every((i) => i.lexical.verified === true) : null,
145
+ };
138
146
  }
139
147
 
140
148
  const isHttpUrl = (loc) => /^https?:\/\//i.test(loc);
@@ -204,6 +212,9 @@ export async function openPikeletChain(members, options = {}) {
204
212
  tiersRaw.push(reader.__chainTier);
205
213
  }
206
214
  const base = tiersRaw[0];
215
+ // A chain encodes with its base's encoder (4.5), so its fusion
216
+ // defaults are that encoder's (fusion.mjs ENCODER_FUSION_DEFAULTS).
217
+ const chainFusion = fusionDefaultsFor(base.encoderInfo?.model ?? base.manifest?.encoder?.model);
207
218
  if (base.manifest.profile === LAYER_PROFILE) {
208
219
  throw new Error('the first chain member is a layer, not a base: a layer opened alone would serve a fraction of a corpus (4.1)');
209
220
  }
@@ -228,9 +239,7 @@ export async function openPikeletChain(members, options = {}) {
228
239
  const layerBlooms = [];
229
240
  let everyLayerShipsBloom = true;
230
241
  // 4.5: every layer's bloom MUST use the base asset's geometry, so the
231
- // union is an exact OR. The geometry is right here in the base's fit;
232
- // it used to come only from options.baseBloom, which no caller set, so
233
- // the check never ran and a layer with foreign hashes was OR'd in.
242
+ // union is an exact OR. The geometry comes from the base's fit.
234
243
  const baseVocabBloom = base.calibrationJson?.asset?.vocabBloom;
235
244
  const baseBloomGeometry = options.baseBloom
236
245
  || (baseVocabBloom ? { bits: baseVocabBloom.bits, hashes: baseVocabBloom.hashes } : null);
@@ -269,8 +278,7 @@ export async function openPikeletChain(members, options = {}) {
269
278
  // A missing bloom degrades the chain because it hides a layer's
270
279
  // vocabulary from known_frac (4.5). A tombstone-only layer has no
271
280
  // records and so no vocabulary to hide: its `none` region is the
272
- // empty bloom, not a gap. Counting it took a chain that deleted 3
273
- // of 3,255 records to drift-exceeded, unscoring every query.
281
+ // empty bloom, not a gap.
274
282
  if (inherited.bloomBytes) layerBlooms.push(inherited.bloomBytes);
275
283
  else if (!rel.tombstoneOnly) everyLayerShipsBloom = false;
276
284
 
@@ -295,8 +303,8 @@ export async function openPikeletChain(members, options = {}) {
295
303
  throw new Error(`layer at depth ${rel.depth} clears inherited tombstone for id ${violation}: a child's mask must be a superset of its parent's (3.4)`);
296
304
  }
297
305
  // 4.3: a tombstone-only layer exists only to delete, so its
298
- // cumulative count MUST exceed its parent's. The producer checked
299
- // this; a reader accepted a no-op layer from anyone else.
306
+ // cumulative count MUST exceed its parent's. Checked here too, not
307
+ // only by the producer.
300
308
  if (rel.tombstoneOnly && countBits(tomb.bitset) <= countBits(headBitset)) {
301
309
  throw new Error(`tombstone-only layer at depth ${rel.depth} deletes nothing its parent had not already deleted (4.3)`);
302
310
  }
@@ -333,8 +341,7 @@ export async function openPikeletChain(members, options = {}) {
333
341
  ? calibrationDrift(chainMembers, headTombstoneCount) : 0;
334
342
  // 5.5: "the base carries no fit" is status `none`. The fit lives in the
335
343
  // base's query-interp calibration region (`asset`), never in the
336
- // manifest; an earlier draft of this file read manifest.calibration,
337
- // which does not exist.
344
+ // manifest.
338
345
  const baseCal = base.calibrationJson || null;
339
346
  const baseHasFit = !!(baseCal && baseCal.asset);
340
347
  const calibration = calibrationStatus({
@@ -370,8 +377,7 @@ export async function openPikeletChain(members, options = {}) {
370
377
  identity: chainMembers[chainMembers.length - 1].identity,
371
378
  baseIdentity: base.identity,
372
379
  // The pack's name is the base's: layers add records, not a
373
- // new name. Without it a host fell back to naming the
374
- // chain after its newest layer's file.
380
+ // new name.
375
381
  name: opened[0].info().name ?? null,
376
382
  layers: chainMembers.length,
377
383
  searchTiers: searchTiers.length,
@@ -382,12 +388,10 @@ export async function openPikeletChain(members, options = {}) {
382
388
  dim: base.dim,
383
389
  metric: base.manifest.metric,
384
390
  // 4.5: a chain's encoder IS the base's — a layer carries no
385
- // encoder bytes and inherits by commitment. Omitting it here
386
- // made every consumer that reads info().encoder report null
387
- // on a chain: `list_packs` advertised "encoder": null for a
388
- // pack whose base is MiniLM, so a model asking what embedded
389
- // the corpus got nothing.
391
+ // encoder bytes and inherits by commitment.
390
392
  encoder: base.encoderInfo ?? null,
393
+ // The fusion defaults query() applies (the base encoder's).
394
+ fusion: { ...chainFusion },
391
395
  calibrationDrift: calibration.drift,
392
396
  calibrationStatus: calibration.status,
393
397
  driftLimit: calibration.effectiveLimit,
@@ -405,15 +409,15 @@ export async function openPikeletChain(members, options = {}) {
405
409
  const ri = typeof opened[i]?.info === 'function' ? opened[i].info() : null;
406
410
  return {
407
411
  depth: m.depth, identity: m.identity, records: m.records,
408
- ...(ri ? { corpusIntegrity: ri.corpusIntegrity, indexRowIntegrity: ri.indexRowIntegrity }
409
- : { tombstoneOnly: true }),
412
+ ...(ri ? {
413
+ corpusIntegrity: ri.corpusIntegrity, indexRowIntegrity: ri.indexRowIntegrity,
414
+ ...(ri.lexical ? { lexicalIntegrity: ri.lexical.integrity, lexicalVerified: ri.lexical.verified === true } : {}),
415
+ } : { tombstoneOnly: true }),
410
416
  };
411
417
  }),
412
418
  // The chain encodes with the base's encoder (4.5), so the
413
419
  // base's verification is the chain's. Chain-level integrity
414
- // is the members' when they agree, else 'mixed'. Without
415
- // these, verify_pack on a chain reported no encoder or
416
- // integrity state at all.
420
+ // is the members' when they agree, else 'mixed'.
417
421
  encoderVerified: opened[0].info().encoderVerified,
418
422
  ...memberIntegritySummary(opened),
419
423
  };
@@ -431,15 +435,17 @@ export async function openPikeletChain(members, options = {}) {
431
435
  if (!['hybrid', 'vector', 'lexical', 'augmented'].includes(retrieval)) {
432
436
  throw new Error(`query() retrieval must be hybrid, vector, lexical, or augmented, got ${retrieval}`);
433
437
  }
438
+ // The base's calibration (scorer, union bloom, drift envelope)
439
+ // was read unverified at open when its encoder is deferred.
440
+ if (base.calibrationVerified) await base.calibrationVerified();
434
441
 
435
442
  // --- 2. Lexical candidates (5.3 step 2, 5.4) -------------------
436
- // df is summed across tiers per query term, so a term common in
437
- // the base and rare in a layer scores with one idf everywhere;
438
- // each tier scoring with its own df made layer records outrank
439
- // base records on the same term. With comparable scores every
440
- // tier's own top LEXICAL_CANDIDATES contains its share of the
441
- // merged top LEXICAL_CANDIDATES, so the cutoff and cap below are
442
- // exact over the merged, live-only list.
443
+ // df is summed across tiers per query term, so a term scores
444
+ // with one idf everywhere (per-tier df would let layer records
445
+ // outrank base records on the same term). With comparable
446
+ // scores, each tier's own top LEXICAL_CANDIDATES contains its
447
+ // share of the merged top LEXICAL_CANDIDATES, so the cutoff
448
+ // and cap below are exact over the merged, live-only list.
443
449
  let lexicalHits = [];
444
450
  const lexTiers = searchTiers.map((t, j) => ({ lex: t.reader.lexicalIndex, j }))
445
451
  .filter((x) => x.lex);
@@ -499,8 +505,7 @@ export async function openPikeletChain(members, options = {}) {
499
505
  ...(extra.length ? { extraCandidates: extra } : {}),
500
506
  // Every reranked candidate, not the top k: abstention is
501
507
  // fit at a fixed top-10 window whatever the caller's k,
502
- // and a k-sized window biased mean10 and could flip the
503
- // verdict (the single-file reader's k-mismatch fix).
508
+ // as in the single-file reader.
504
509
  fullRerankOutput: true,
505
510
  });
506
511
  return out.results.map((r) => ({
@@ -521,7 +526,8 @@ export async function openPikeletChain(members, options = {}) {
521
526
  fusedFull = lexicalHits.map((h) => byId.get(h.id)).filter(Boolean);
522
527
  } else if (retrieval === 'hybrid' && lexicalHits.length) {
523
528
  const lexRank = new Map(lexicalHits.map((h, i) => [h.id, i]));
524
- fusedFull = fuseCandidates(searched, lexicalHits.map((h) => h.id), queryOptions.fusion);
529
+ fusedFull = fuseCandidates(searched, lexicalHits.map((h) => h.id),
530
+ queryOptions.fusion ? { ...chainFusion, ...queryOptions.fusion } : chainFusion);
525
531
  const vecRank = new Map(searched.map((h, i) => [h.id, i]));
526
532
  fusedFull = fusedFull.map((hit, i) => ({
527
533
  ...hit,
@@ -546,18 +552,15 @@ export async function openPikeletChain(members, options = {}) {
546
552
  // 5.5: under `inherited` the base's scorer runs unchanged over
547
553
  // the merged window. Under `drift-exceeded` matchQuality is
548
554
  // `unscored`, confidence is omitted, results still ship, and the
549
- // response says which input bound it — so a consumer can tell
550
- // "no fit" from "fit outgrown". A reader MUST NOT apply an
551
- // outgrown fit silently, and MUST NOT omit the verdict either:
552
- // omitting it makes "the fit said no" indistinguishable from
553
- // "nothing scored", which is exactly the confusion 5.5 exists
554
- // to prevent.
555
+ // response says which input bound it, so a consumer can tell
556
+ // "no fit" from "fit outgrown". The verdict is never applied
557
+ // silently or omitted.
555
558
  let matchQuality = 'unscored';
556
559
  let confidence;
557
560
  let grounding = null;
558
561
  if (calibration.status === 'inherited' && base.scoreQuality) {
559
562
  // Coverage reads the fit's passagesNeeded from the FULL
560
- // fused window; top.slice(0, 3) gave it one passage at k=1.
563
+ // fused window, not the k-truncated results.
561
564
  const passagesNeeded = baseCal?.asset?.coverage?.topK || 5;
562
565
  const passageOrder = fusedFull?.length ? fusedFull : searched;
563
566
  const passages = await Promise.all(passageOrder.slice(0, passagesNeeded).map(async (hit) => {
@@ -565,12 +568,9 @@ export async function openPikeletChain(members, options = {}) {
565
568
  const rec = await searchTiers[owner.tier.tier].reader.hydrate(owner.localId);
566
569
  return rec?.text ?? '';
567
570
  }));
568
- // 4.5 is normative: "A reader MUST compute the union
569
- // before scoring." The union was computed at mount and
570
- // then never reached the scorer, so known_frac was
571
- // measured against the base's vocabulary alone and
572
- // under-read every query about a layer's content —
573
- // exactly the records a layer is published to add.
571
+ // 4.5: "A reader MUST compute the union before
572
+ // scoring", so known_frac counts every layer's
573
+ // vocabulary, not only the base's.
574
574
  const scored = await base.scoreQuality(
575
575
  searched,
576
576
  { text: queryOptions.text ?? '', vector, passages },
@@ -580,17 +580,22 @@ export async function openPikeletChain(members, options = {}) {
580
580
  if (scored && scored.match_quality) {
581
581
  matchQuality = scored.match_quality;
582
582
  if (Number.isFinite(scored.confidence)) confidence = scored.confidence;
583
- // Which passage grounded the verdict and which query
584
- // words no passage contains, as the single-file
585
- // reader returns it; recordId is the chain-global id
586
- // of the passage coverage scored.
587
- if (scored.grounding) {
588
- grounding = { ...scored.grounding, recordId: passageOrder[scored.grounding.passageIndex]?.id ?? null };
589
- }
590
583
  }
591
584
  } else if (calibration.status === 'none') {
592
585
  matchQuality = 'unscored';
593
586
  }
587
+ // Grounding for every chain, calibrated or not (grounding.mjs),
588
+ // from the passages fusion ranks first; recordId is the
589
+ // chain-global id of the graded passage.
590
+ {
591
+ const passageOrder = (fusedFull?.length ? fusedFull : searched).slice(0, GROUNDING_PASSAGES);
592
+ const passageTexts = await Promise.all(passageOrder.map(async (hit) => {
593
+ const owner = ownerOf(table, hit.id);
594
+ return (await searchTiers[owner.tier.tier].reader.hydrate(owner.localId))?.text ?? '';
595
+ }));
596
+ const graded = groundQuery(queryOptions.text ?? '', passageTexts);
597
+ if (graded) grounding = { ...graded, recordId: passageOrder[graded.passageIndex]?.id ?? null };
598
+ }
594
599
  // A 'none' verdict withholds results, exactly as the
595
600
  // single-file reader does: the calibrated abstention signal is
596
601
  // doing its job, and a chain must not be a way to get results
@@ -641,10 +646,26 @@ export async function openPikeletChain(members, options = {}) {
641
646
  * base may legitimately fail here, because a layer can tombstone
642
647
  * or supersede the record it expects, so `evaluationScope` says
643
648
  * the material is the base's and not the chain's.
644
- *
645
- * Before this existed `verify_pack` called `search.evaluation()`
646
- * on a chain and got a TypeError.
647
649
  */
650
+ /**
651
+ * verifyLexical() on every member that carries a lexical segment,
652
+ * base first. Resolves false when none does; rejects naming the
653
+ * first member whose segment fails its digest.
654
+ */
655
+ async verifyLexical(verifyOptions = {}) {
656
+ assertOpen();
657
+ let any = false;
658
+ for (let i = 0; i < opened.length; i++) {
659
+ if (typeof opened[i]?.verifyLexical !== 'function') continue;
660
+ try {
661
+ any = (await opened[i].verifyLexical(verifyOptions)) || any;
662
+ } catch (err) {
663
+ throw new Error(`chain member at depth ${chainMembers[i].depth}: ${err?.message ?? err}`, { cause: err });
664
+ }
665
+ }
666
+ return any;
667
+ },
668
+
648
669
  async evaluation() {
649
670
  assertOpen();
650
671
  if (typeof base.evaluation !== 'function') return null;
@@ -674,16 +695,10 @@ export async function openPikeletChain(members, options = {}) {
674
695
  /**
675
696
  * 6.3's verbatim row copy: the quantized bytes and per-row
676
697
  * scale/offset for a set of chain ids, read back from whichever
677
- * tier owns each one. Producer seam, like __head.
678
- *
679
- * `compact` re-embedded every live record with the base's own
680
- * encoder instead, on the stated grounds that the engine exposed
681
- * no row readback. It does: the sketch reader's fetchRows()
682
- * (format 2 verifies each row's digest as it reads) plus the
683
- * resident scales/offsets arrays. Re-embedding costs a forward
684
- * pass per record and only reproduces the same bytes when the
685
- * encoder is bit-identical, which is a stronger assumption than
686
- * the spec's copy makes.
698
+ * tier owns each one, via the sketch reader's fetchRows() (format 2
699
+ * verifies each row's digest) and the resident scales/offsets.
700
+ * Producer seam, like __head. Copying, rather than re-embedding,
701
+ * keeps the bytes without assuming a bit-identical encoder.
687
702
  *
688
703
  * Returns rows in the order ids were given. Throws if an id is
689
704
  * outside every tier, which callers should read as a planning bug
@@ -6,7 +6,7 @@
6
6
  // re-embedded, local ids do not change), and its rowBase, bitset, supersessions
7
7
  // and evaluation material are recomputed.
8
8
  //
9
- // The correctness rule the spec was revised twice to get right:
9
+ // The correctness rule:
10
10
  //
11
11
  // A rebase replays what the layer ITSELF did -- its delta over its old
12
12
  // parent, and the edges physically in its own segment -- and NEVER its
@@ -13,7 +13,8 @@
13
13
  // inflated by node:zlib, never Brotli or zstd.
14
14
  //
15
15
  // Only what the callers use is implemented: GET/HEAD without a request
16
- // body, a headers object (or Headers), an AbortSignal, and the three
16
+ // body, a headers object (or Headers), an AbortSignal, an idle timeout
17
+ // (init.idleTimeoutMs, default 30 s, 0 disables), and the three
17
18
  // redirect modes -- 'follow' for plain reads, 'manual' for the range
18
19
  // source's HEAD walk (which reads Location itself), and 'error' for reads
19
20
  // under a redirectGuard. The result is a real Response, so callers keep
@@ -36,13 +37,27 @@ const agents = {
36
37
  'http:': new http.Agent({ keepAlive: true, maxSockets: MAX_SOCKETS }),
37
38
  'https:': new https.Agent({ keepAlive: true, maxSockets: MAX_SOCKETS }),
38
39
  };
40
+ // A host that accepts a connection and then sends nothing would otherwise
41
+ // hold the request open forever: no error, no response. The clock is the
42
+ // socket's idle time, so a slow but moving body never trips it, and time
43
+ // spent queued for one of the agent's sockets does not count.
44
+ export const DEFAULT_IDLE_TIMEOUT_MS = 30_000;
39
45
 
40
- function requestOnce(url, { method, headers, signal }) {
46
+ function requestOnce(url, { method, headers, signal, idleTimeoutMs }) {
41
47
  const transport = url.protocol === 'https:' ? https : url.protocol === 'http:' ? http : null;
42
48
  if (!transport) return Promise.reject(new TypeError(`unsupported protocol ${url.protocol} in ${url.href}`));
43
49
  return new Promise((resolve, reject) => {
44
50
  const req = transport.request(url, { method, headers, signal, agent: agents[url.protocol] }, resolve);
45
51
  req.on('error', reject);
52
+ if (idleTimeoutMs > 0) {
53
+ // Covers the wait for response headers and every gap in the body: the
54
+ // destroy errors the response stream, which rejects the body read.
55
+ req.setTimeout(idleTimeoutMs, () => {
56
+ const err = Object.assign(new Error(`${url.href} sent nothing for ${idleTimeoutMs / 1000} s; gave up`), { code: 'ETIMEDOUT' });
57
+ req.res?.destroy(err);
58
+ req.destroy(err);
59
+ });
60
+ }
46
61
  req.end();
47
62
  });
48
63
  }
@@ -80,9 +95,13 @@ export async function nodeFetch(input, init = {}) {
80
95
  const headers = Object.fromEntries(new Headers(init.headers || {}));
81
96
  headers['accept-encoding'] = 'identity';
82
97
  headers['user-agent'] ??= 'pikelet';
98
+ const idleTimeoutMs = init.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
99
+ if (!(Number.isFinite(idleTimeoutMs) && idleTimeoutMs >= 0)) {
100
+ throw new TypeError(`idleTimeoutMs must be a non-negative number of milliseconds, got ${init.idleTimeoutMs}`);
101
+ }
83
102
  let url = new URL(String(input));
84
103
  for (let hop = 0; ; hop++) {
85
- const res = await requestOnce(url, { method, headers, signal: init.signal });
104
+ const res = await requestOnce(url, { method, headers, signal: init.signal, idleTimeoutMs });
86
105
  const location = res.headers.location;
87
106
  if (REDIRECT_STATUSES.has(res.statusCode) && location) {
88
107
  res.resume();