pikelet-wasm 0.13.0 → 0.15.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.
@@ -20,10 +20,8 @@ export const sha256 = (bytes) => crypto.createHash('sha256').update(bytes).diges
20
20
  export const align16 = (n) => Math.ceil(n / 16) * 16;
21
21
 
22
22
  // Canonical form = JSON.stringify semantics with sorted object keys:
23
- // undefined / functions / symbols are omitted as object properties and
24
- // become null as array elements, exactly as JSON.stringify treats them —
25
- // previously they leaked through as the literal text `undefined`, producing
26
- // output JSON.parse rejects.
23
+ // undefined / functions / symbols are omitted as properties and become null
24
+ // as array elements.
27
25
  export function canonicalJson(value) {
28
26
  if (Array.isArray(value)) {
29
27
  return `[${value.map((v) => canonicalJson(v) ?? 'null').join(',')}]`;
@@ -51,16 +49,11 @@ export function buildQueryInterpSegment(kind, encoderBytes, calibrationBytes) {
51
49
  }
52
50
 
53
51
  // Lexical index segment (kind 5, OPTIONAL), layout bm25-v1: a static
54
- // inverted index over the corpus records for hybrid retrieval. Terms are
55
- // addressed by a 64-bit hash (two fnv1a-32 passes, seeds 0 and 0x9e3779b9)
56
- // in a fixed-width table sorted by (hashHi, hashLo), so a reader can binary
57
- // search without materializing term strings — lazy-friendly by
58
- // construction, even though the phase-1 reader loads the segment eagerly.
59
- // Postings are (docIdDelta, tf) varint pairs. Document length (indexed
60
- // tokens per record) and the corpus token total ship for BM25
61
- // normalization. Hash collisions merge two terms' postings; at 64 bits over
62
- // realistic vocabularies the probability is negligible and the failure mode
63
- // is one slightly-wrong lexical score, not corruption.
52
+ // inverted index for hybrid retrieval. Terms are addressed by a 64-bit hash
53
+ // (two fnv1a-32 passes, seeds 0 and 0x9e3779b9) in a table sorted by
54
+ // (hashHi, hashLo), so a reader can binary search, or read lazily, without
55
+ // term strings. A hash collision merges two terms' postings: at 64 bits the
56
+ // odds are negligible and the cost is one slightly wrong score.
64
57
  //
65
58
  // [0,4) u32 version = 1
66
59
  // [4,8) u32 docCount
@@ -79,25 +72,14 @@ export function buildQueryInterpSegment(kind, encoderBytes, calibrationBytes) {
79
72
  // varint tf, repeated df times
80
73
  //
81
74
  // Indexing tokenizes on [a-z0-9']+ lowercased, keeps tokens of 2..32 chars,
82
- // and skips a small function-word stopword list — readers need no
83
- // coordination with the list, because an unindexed query token simply finds
84
- // no postings.
75
+ // and skips a small stopword list; readers need no copy of it, since an
76
+ // unindexed query token just finds no postings.
85
77
  //
86
- // Interrogative words (how/does/what/who/why/where/when/which/do/did) are
87
- // deliberately in this list, not just the base one: without them, a
88
- // natural-language question's own scaffolding becomes real, indexable BM25
89
- // content — a passage containing literal dialogue like "How does Georgiana
90
- // get on, Darcy?" then wins a high lexical score against the query "How
91
- // does Elizabeth initially react to Mr. Darcy?" purely from "how does" and
92
- // "darcy" co-occurring, with zero topical relevance. Confirmed live: this
93
- // pushed a genuinely correct chunk (ranked #2 by the vector search alone)
94
- // completely out of the fused top-10, replaced by RRF-boosted noise. Not
95
- // borrowed wholesale from calibrate.mjs's COVERAGE_STOPWORDS, which also
96
- // excludes domain words ("tell", "explain", "overview", "history",
97
- // "definition") that are legitimate lexical CONTENT on many real corpora
98
- // (a docs site literally titled "History") — this list only adds the
99
- // unambiguous interrogative set, since the lexical index (unlike coverage)
100
- // also indexes passage text, not just the query.
78
+ // Interrogatives (how/does/what/...) are stopped here too: otherwise a
79
+ // question's scaffolding scores BM25 matches against literal dialogue ("How
80
+ // does Georgiana get on, Darcy?") and pushes correct chunks out of the fused
81
+ // top-10. calibrate.mjs's COVERAGE_STOPWORDS is not reused: it also stops
82
+ // words ("history", "overview") that are real content in passage text.
101
83
  const LEXICAL_LAYOUT = 'bm25-v1';
102
84
  const LEXICAL_STOPWORDS = new Set(['the', 'a', 'an', 'and', 'or', 'but', 'of', 'to', 'in', 'on', 'at', 'by', 'for', 'with', 'from', 'into', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'it', 'its', 'this', 'that', 'these', 'those', 'as', 'their', 'they', 'them', 'his', 'her', 'has', 'have', 'had', 'not', 'can', 'will', 'if', 'we', 'you', 'your', 'i',
103
85
  'how', 'does', 'did', 'do', 'what', 'who', 'why', 'where', 'when', 'which']);
@@ -125,14 +107,11 @@ function varintBytes(n) {
125
107
  return out;
126
108
  }
127
109
 
128
- // Counting-sort construction over typed arrays: the obvious
129
- // Map-of-Maps build dies around tens of millions of posting entries
130
- // (a 456k-chunk wiki corpus has ~30M), so terms are interned to dense
131
- // indexes on a first tokenize pass (df counted per term), entry arrays
132
- // are preallocated exactly, and a second tokenize pass scatters
133
- // (docId, tf) pairs into per-term slots. Entries land doc-ascending per
134
- // term by construction, which is what the delta varints need. Output
135
- // bytes are identical to the original builder's.
110
+ // Counting-sort construction over typed arrays: a Map-of-Maps build dies
111
+ // around tens of millions of postings (the 456k-chunk wiki corpus has ~30M).
112
+ // Terms are interned and df counted on a first pass, entry arrays are
113
+ // preallocated, and a second pass scatters (docId, tf) pairs into per-term
114
+ // slots, doc-ascending as the delta varints need.
136
115
  export function buildLexicalSegment(texts) {
137
116
  const docCount = texts.length;
138
117
  const doclens = new Uint32Array(docCount);
@@ -345,19 +324,14 @@ export function buildInlineTransformerEncoderSegment({ declaration, vocabBytes,
345
324
  return out;
346
325
  }
347
326
 
348
- // The spec's measured operating point (SKETCH_PROFILE.md section 5, mandatory
349
- // in the complete profile's evaluation segment): open the just-built sketch
350
- // bytes in memory, replay a query set at increasing rerank C against the
351
- // exact full-rerank top-k, and return the smallest C whose recall reaches
352
- // targetRecall — plus the whole curve for the evaluation segment. Queries
353
- // are the corpus's own float embeddings when the caller has them, else rows
354
- // dequantized out of the snapshot.
355
- //
356
- // The sweep stops at the reader's default ceiling (MAX_RECOMMENDED_RERANK):
357
- // it used to fall back to the full row count, a depth readers no longer
358
- // honor by default, so a pack could record a recall it would not be served
359
- // at. The last rung is the ceiling, measured like any other, and
360
- // targetReached says whether the target was met below it.
327
+ // The measured operating point (SKETCH_PROFILE.md section 5, mandatory in
328
+ // the evaluation segment): replay a query set against the just-built sketch
329
+ // at increasing rerank C and return the smallest C whose recall against the
330
+ // exact full-rerank top-k reaches targetRecall, plus the curve. Queries are
331
+ // the corpus's float embeddings when given, else rows dequantized from the
332
+ // snapshot. The sweep stops at the reader's default ceiling
333
+ // (MAX_RECOMMENDED_RERANK), so a pack never records a recall it would not be
334
+ // served at; targetReached says whether the target was met below it.
361
335
  export async function measureRecommendedRerank({
362
336
  artifactModule,
363
337
  sketchBytes,
@@ -552,17 +526,28 @@ export function assemblePikeletFile(manifestFields, segments, outPath) {
552
526
  header.writeBigUInt64LE(BigInt(fileBytes), 16);
553
527
  identity.copy(header, 24);
554
528
 
555
- const fd = fs.openSync(outPath, 'w');
529
+ // Write beside the target and rename over it: a crash mid-write, or an
530
+ // output that is also an input still being read, never leaves a truncated
531
+ // pack where a valid one was.
532
+ const tmpPath = `${outPath}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`;
533
+ const fd = fs.openSync(tmpPath, 'wx');
556
534
  try {
557
- fs.writeSync(fd, header, 0, header.length, 0);
558
- fs.writeSync(fd, manifestBytes, 0, manifestBytes.length, HEADER_BYTES);
559
- fs.writeSync(fd, table, 0, table.length, tableOffset);
560
- for (const { offset, bytes } of placed) {
561
- fs.writeSync(fd, bytes, 0, bytes.length, offset);
535
+ try {
536
+ fs.writeSync(fd, header, 0, header.length, 0);
537
+ fs.writeSync(fd, manifestBytes, 0, manifestBytes.length, HEADER_BYTES);
538
+ fs.writeSync(fd, table, 0, table.length, tableOffset);
539
+ for (const { offset, bytes } of placed) {
540
+ fs.writeSync(fd, bytes, 0, bytes.length, offset);
541
+ }
542
+ fs.ftruncateSync(fd, fileBytes);
543
+ fs.fsyncSync(fd);
544
+ } finally {
545
+ fs.closeSync(fd);
562
546
  }
563
- fs.ftruncateSync(fd, fileBytes);
564
- } finally {
565
- fs.closeSync(fd);
547
+ fs.renameSync(tmpPath, outPath);
548
+ } catch (error) {
549
+ fs.rmSync(tmpPath, { force: true });
550
+ throw error;
566
551
  }
567
552
  return { outPath, fileBytes, formatVersion, identity: identity.toString('hex'), manifest };
568
553
  }
@@ -0,0 +1,92 @@
1
+ // Grounding: which of the query's content words the best of the top
2
+ // passages contains (covered) and which none of them does (uncovered). It
3
+ // needs nothing from the pack but the passages' text, so every pack gets
4
+ // it, calibrated or not; an agent reads `uncovered` to tell "the passage is
5
+ // about this" from "the passage states this".
6
+ //
7
+ // The word rules follow the calibrated coverage term
8
+ // (retrieval-abstention.mjs) — possessives stripped, light suffix stemming,
9
+ // plural forms, heading-only matches at half credit — with two
10
+ // differences: a token holding a digit counts whatever its length ("v8",
11
+ // "3d", "4"), and every word weighs the same (the calibrated term discounts
12
+ // corpus-common words through a bloom only a calibration asset carries).
13
+ // The calibrated verdict keeps its own coverage term unchanged.
14
+
15
+ // How many passages grounding reads, in fused order.
16
+ export const GROUNDING_PASSAGES = 5;
17
+
18
+ const MIN_WORD_LEN = 3;
19
+ const STOPWORDS = new Set([
20
+ 'the', 'a', 'an', 'and', 'or', 'but', 'of', 'to', 'in', 'on', 'at', 'by', 'for', 'with', 'from', 'into',
21
+ 'through', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'it', 'its', 'this', 'that', 'these', 'those',
22
+ 'as', 'their', 'they', 'them', 'also', 'can', 'will', 'which', 'when', 'where', 'while', 'his', 'her', 'has',
23
+ 'have', 'had', 'not', 'often', 'usually', 'without',
24
+ // Question scaffolding, so "how does X work" is grounded by X.
25
+ 'what', 'how', 'who', 'why', 'do', 'does', 'did', 'me', 'tell', 'about', 'explain', 'explained', 'facts',
26
+ 'information', 'overview', 'history', 'definition', 'important', 'work', 'works', 'known', 'anything', 'said',
27
+ 'much', 'many', 'each', 'would', 'could', 'some', 'such', 'very', 'more', 'after', 'before',
28
+ ]);
29
+ const HEADING_WEIGHT = 0.5;
30
+ const STEM_MIN_LEN = 4;
31
+ const STEM_SUFFIXES = ['ization', 'isation', 'ication', 'ation', 'ition', 'tion', 'ing', 'ed', 'ate', 'ize', 'ise'];
32
+
33
+ const tokenize = (text) => String(text || '').toLowerCase().match(/[a-z0-9']+/g) || [];
34
+ function stem(w) {
35
+ for (const suf of STEM_SUFFIXES) {
36
+ if (w.length - suf.length >= STEM_MIN_LEN && w.endsWith(suf)) return w.slice(0, -suf.length);
37
+ }
38
+ if (w.length - 1 >= STEM_MIN_LEN && w.endsWith('e')) return w.slice(0, -1);
39
+ return w;
40
+ }
41
+ function stripPossessive(w) {
42
+ if (w.endsWith("'s")) return w.slice(0, -2);
43
+ if (w.endsWith("s'")) return w.slice(0, -1);
44
+ if (w.endsWith("'")) return w.slice(0, -1);
45
+ return w;
46
+ }
47
+
48
+ // The query words grounding grades, in query order, without repeats.
49
+ export function groundingWords(query) {
50
+ const words = tokenize(query).map(stripPossessive)
51
+ .filter((w) => w && (w.length >= MIN_WORD_LEN || /\d/.test(w)) && !STOPWORDS.has(w));
52
+ return [...new Set(words)];
53
+ }
54
+
55
+ /**
56
+ * Grade the query's content words against passage texts (a record's first
57
+ * line is its heading, as ingest writes it). Returns the best passage's
58
+ * { passageIndex, coverage, covered, uncovered }, or null when the query has
59
+ * no gradable word or there are no passages.
60
+ */
61
+ export function groundQuery(query, passageTexts) {
62
+ const content = groundingWords(query);
63
+ if (!content.length || !passageTexts?.length) return null;
64
+ let best = null;
65
+ let bestRaw = -1;
66
+ passageTexts.forEach((text, passageIndex) => {
67
+ const s = String(text || '');
68
+ const nl = s.indexOf('\n');
69
+ const heading = nl === -1 ? s : s.slice(0, nl);
70
+ const body = nl === -1 ? '' : s.slice(nl + 1);
71
+ const bodyWords = tokenize(body).map(stripPossessive);
72
+ const bodySet = new Set(bodyWords);
73
+ const bodyStems = new Set(bodyWords.map(stem));
74
+ const headingSet = new Set(tokenize(heading).map(stripPossessive));
75
+ const presentIn = (set, stems, w) => set.has(w) || set.has(`${w}s`) || set.has(`${w}es`)
76
+ || (w.endsWith('s') && set.has(w.slice(0, -1)))
77
+ || (stems !== null && stems.has(stem(w)));
78
+ const credit = (w) => (presentIn(bodySet, bodyStems, w) ? 1 : presentIn(headingSet, null, w) ? HEADING_WEIGHT : 0);
79
+ const credits = content.map(credit);
80
+ const coverage = credits.reduce((a, c) => a + c, 0) / content.length;
81
+ if (coverage > bestRaw) {
82
+ bestRaw = coverage;
83
+ best = {
84
+ passageIndex,
85
+ coverage: +coverage.toFixed(3),
86
+ covered: content.filter((_, i) => credits[i] > 0),
87
+ uncovered: content.filter((_, i) => credits[i] === 0),
88
+ };
89
+ }
90
+ });
91
+ return best;
92
+ }
@@ -62,6 +62,13 @@ export declare function httpRangeSource(url: string, options?: {
62
62
  * disables. CDNs rate-limit the parallel range bursts a query issues.
63
63
  */
64
64
  maxRetries?: number;
65
+ /**
66
+ * How long, in milliseconds, each wait on the host (response headers, then
67
+ * each body chunk) may go without progress before the read fails with code
68
+ * ETIMEDOUT and the request is aborted. Default 30000; 0 disables. Retry
69
+ * sleeps do not count.
70
+ */
71
+ idleTimeoutMs?: number;
65
72
  /**
66
73
  * Called with each redirect target before it is followed; throw to refuse
67
74
  * the hop. When set, range reads never auto-follow redirects. A chain walk
@@ -79,6 +86,8 @@ export declare function httpRangeSource(url: string, options?: {
79
86
  method?: string;
80
87
  headers?: Record<string, string>;
81
88
  redirect?: 'follow' | 'manual' | 'error';
89
+ /** Aborted when a request makes no progress for idleTimeoutMs. */
90
+ signal?: unknown;
82
91
  }) => Promise<any>;
83
92
  }): HttpRangeSource;
84
93
 
@@ -94,9 +103,15 @@ export declare function nodeFetch(input: string, init?: {
94
103
  signal?: unknown;
95
104
  /** Inflate a gzip/deflate body a server sent despite identity (crawled HTML); Brotli/zstd still refused. */
96
105
  inflateGzip?: boolean;
106
+ /**
107
+ * Milliseconds the connection may sit idle (no response headers, or a gap
108
+ * in the body) before the request fails with code ETIMEDOUT. Default
109
+ * 30000; 0 disables. Time queued for a socket does not count.
110
+ */
111
+ idleTimeoutMs?: number;
97
112
  }): Promise<any>;
98
113
 
99
- /** openPikeletFile's options.blobCache: bytes keyed by their sha256 (lowercase hex). */
114
+ /** openPikeletFile's options.blobCache: bytes keyed by their sha256 (lowercase hex, 32-64 digits). */
100
115
  export interface BlobCache {
101
116
  get(key: string): Promise<Uint8Array | null> | Uint8Array | null;
102
117
  put(key: string, bytes: Uint8Array): Promise<void> | void;
@@ -104,17 +119,23 @@ export interface BlobCache {
104
119
  }
105
120
 
106
121
  /**
107
- * Node only (the 'node' export condition): a BlobCache on disk, one file per
108
- * key under `dir` (default defaultBlobCacheDir()), evicting least recently
109
- * used entries past maxBytes (default 2 GiB). flush() settles pending writes.
122
+ * Node only (the 'node' export condition): a BlobCache on disk under `dir`
123
+ * (default defaultBlobCacheDir()). Entries of 64 KiB or more get a file each,
124
+ * evicting least recently used past maxBytes (default 2 GiB). Smaller ones
125
+ * (per-query rows, records, digest pages) go to append-only log generations
126
+ * capped at smallMaxBytes in total (default 64 MiB; 0 disables them), the
127
+ * oldest generation dropped whole. flush() settles pending writes; close()
128
+ * releases the log's file handles.
110
129
  */
111
- export declare function diskBlobCache(dir?: string, options?: { maxBytes?: number }): BlobCache & {
130
+ export declare function diskBlobCache(dir?: string, options?: { maxBytes?: number; smallMaxBytes?: number }): BlobCache & {
112
131
  dir: string;
113
132
  flush(): Promise<void>;
133
+ close(): Promise<void>;
114
134
  };
115
135
  /** $PIKELET_CACHE_DIR/blobs, else $XDG_CACHE_HOME/pikelet/blobs, else ~/.cache/pikelet/blobs. */
116
136
  export declare function defaultBlobCacheDir(env?: Record<string, string | undefined>): string;
117
137
  export declare const DEFAULT_BLOB_CACHE_BYTES: number;
138
+ export declare const DEFAULT_SMALL_CACHE_BYTES: number;
118
139
 
119
140
  export interface CompleteQueryResult {
120
141
  /**
@@ -123,7 +144,7 @@ export interface CompleteQueryResult {
123
144
  * it measures retrieval relevance: 'none' means the pack does not appear
124
145
  * to cover the query's topic, 'strong' that it does — not that a
125
146
  * returned passage states the specific fact asked for. 'unscored': the
126
- * pack ships no fitted calibrator.
147
+ * pack ships no fitted calibrator, as every pack compiled after 0.14.0.
127
148
  */
128
149
  matchQuality: 'strong' | 'weak' | 'none' | 'unscored';
129
150
  confidence?: number;
@@ -135,17 +156,18 @@ export interface CompleteQueryResult {
135
156
  */
136
157
  results: Array<{ id: number; distance: number } & Record<string, unknown>>;
137
158
  /**
138
- * Which passage grounded the verdict and which of the query's content
139
- * words it contains. Present when a fitted calibrator scored the query
140
- * (absent on 'unscored'). An asked-for value in `uncovered` is one no top
141
- * passage states, whatever matchQuality says.
159
+ * Which of the query's content words the best of the top five passages
160
+ * (the one containing the most of them) contains (covered) and lacks
161
+ * (uncovered). Computed for every pack, calibrated or not; absent only
162
+ * when the query has no gradable word. An asked-for value in `uncovered`
163
+ * is one the best passage does not state, whatever matchQuality says.
142
164
  */
143
165
  grounding?: {
144
- /** Id of the passage the coverage score was taken from. */
166
+ /** Id of the passage that covered the most query words. */
145
167
  recordId: number | null;
146
168
  /** Index of that passage in the fused (or distance-ordered) window. */
147
169
  passageIndex: number;
148
- /** Weighted share of the query's content words the passage contains, 0-1. */
170
+ /** Share of the query's content words the passage contains, 0-1 (a heading-only match counts half). */
149
171
  coverage: number;
150
172
  covered: string[];
151
173
  uncovered: string[];
@@ -217,6 +239,8 @@ export interface CompleteSearch {
217
239
  docCount: number;
218
240
  /** 'segment-sha256' when read eagerly and verified whole; 'unverified-lazy-reads' for lazily opened segments. */
219
241
  integrity: 'segment-sha256' | 'unverified-lazy-reads';
242
+ /** True once the whole segment matched its digest: at open when eager, after verifyLexical() when lazy. */
243
+ verified: boolean;
220
244
  lazy?: true;
221
245
  } | null;
222
246
  /**
@@ -240,6 +264,12 @@ export interface CompleteSearch {
240
264
  * on match; throws on mismatch.
241
265
  */
242
266
  verifyVectors(options?: { chunkBytes?: number }): Promise<true>;
267
+ /**
268
+ * Stream a lazily opened lexical segment against its identity-anchored
269
+ * digest (an eager one was verified at open). Resolves false when the
270
+ * pack has no lexical segment; rejects if the bytes do not match.
271
+ */
272
+ verifyLexical(options?: { chunkBytes?: number }): Promise<boolean>;
243
273
  query(text: string, options?: {
244
274
  k?: number;
245
275
  /**
@@ -308,14 +338,18 @@ export declare function openPikeletFile(
308
338
  */
309
339
  prefetchEncoder?: boolean;
310
340
  /**
311
- * A store for the regions a pack commits to by sha256 that dominate a
312
- * cold URL mount: the sketch's resident prefix and the query-interp
313
- * segment holding the inline encoder. Keys are those digests (lowercase
314
- * hex), so entries never go stale. Every hit is hashed against its key
315
- * before use and a mismatch is treated as a miss (and deleted), so the
316
- * store need not be trusted; get/put/delete faults never fail an open.
317
- * diskBlobCache() (Node) is a ready implementation. Ignored by an open
318
- * whose resident verification is off.
341
+ * A store for bytes a pack commits to by sha256. At mount: the sketch's
342
+ * resident prefix and the query-interp segment holding the inline
343
+ * encoder, which dominate a cold URL mount. Per query: rerank vector
344
+ * rows (format 2), corpus records, and the digest pages that verify
345
+ * both. Keys are those digests in lowercase hex (a row's digest may be
346
+ * truncated to 16-31 bytes), so entries never go stale. Every hit is
347
+ * hashed and must match its key (a prefix, for a truncated key); a
348
+ * mismatch is treated as a miss and deleted, so the store need not be
349
+ * trusted, and get/put/delete faults never fail a read. Only reads that
350
+ * are verified on their own use it: nothing when verification is off,
351
+ * and never the lazy lexical index. diskBlobCache() (Node) is a ready
352
+ * implementation.
319
353
  */
320
354
  blobCache?: BlobCache;
321
355
  /**
@@ -334,6 +368,14 @@ export declare function openPikeletFile(
334
368
  maxReadBytes?: number;
335
369
  /** Budget for a single corpus record read. Default 16 MiB. */
336
370
  maxRecordBytes?: number;
371
+ /**
372
+ * Lexical segments larger than this open lazily: term table and
373
+ * postings are read on demand and not verified per read until
374
+ * verifyLexical() runs. Smaller ones are read and verified whole at
375
+ * open. Default 8 MiB; Infinity reads every segment whole (up to
376
+ * maxReadBytes).
377
+ */
378
+ lazyLexicalBytes?: number;
337
379
  /** Override the kind-3 wasm kernel loader. */
338
380
  createEncoder?: () => Promise<unknown> | unknown;
339
381
  /**