pikelet-wasm 0.16.0 → 0.17.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.
- package/CHANGELOG.md +130 -0
- package/FORMAT.md +52 -59
- package/README.md +2 -2
- package/complete/builder.d.ts +8 -7
- package/complete/builder.mjs +18 -36
- package/complete/fusion.mjs +3 -4
- package/complete/grounding.mjs +5 -9
- package/complete/index.d.ts +14 -32
- package/complete/index.mjs +94 -288
- package/complete/inline-transformer.mjs +0 -64
- package/complete/layer-append.mjs +5 -31
- package/complete/layer-chain.mjs +7 -53
- package/complete/layer-compact.mjs +3 -4
- package/complete/layer-encoder.mjs +17 -123
- package/complete/layer-reader.mjs +20 -147
- package/complete/layer-rebase.mjs +1 -1
- package/complete/wordpiece.mjs +0 -22
- package/dist/engine.js +1 -1
- package/dist/engine.scalar.js +1 -1
- package/dist/engine.scalar.wasm +0 -0
- package/dist/engine.wasm +0 -0
- package/package.json +1 -1
- package/src/artifact/pikelet-artifact-sketch.js +48 -124
- package/src/core/pikelet-core.js +6 -3
- package/complete/retrieval-abstention.mjs +0 -232
- package/complete/student-abstention.mjs +0 -102
- package/complete/student-embedder.mjs +0 -231
package/complete/index.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// it. Environment-neutral — the same module runs in Node (file path or
|
|
3
3
|
// range source) and the browser (HTTP range source, via a bundler for the
|
|
4
4
|
// CJS sketch-reader dependency). The query path needs no core HNSW engine:
|
|
5
|
-
// encoder, sketch reference scan, hydration, and
|
|
5
|
+
// encoder, sketch reference scan, hydration, and grounding all run in
|
|
6
6
|
// pure JS; kind-3 artifacts load the reader-owned transformer WASM kernels,
|
|
7
7
|
// and at scale the resident scan optionally accelerates through the
|
|
8
8
|
// engine's SIMD scan kernel (options.sketchScanner — auto-staged in Node,
|
|
@@ -16,14 +16,12 @@
|
|
|
16
16
|
// offset, length, and count is validated — safe integer, within the header's
|
|
17
17
|
// fileBytes and the source's size, under the per-open read budget — before a
|
|
18
18
|
// read is issued or a buffer allocated, and every read must return exactly
|
|
19
|
-
// the bytes asked for.
|
|
20
|
-
//
|
|
21
|
-
// range read
|
|
22
|
-
//
|
|
19
|
+
// the bytes asked for. Files carry per-record corpus digests (format 2,
|
|
20
|
+
// profile pikelet-complete-v2), so each hydrated record is verified on its
|
|
21
|
+
// own range read. Format 1, the Pancake-era profile strings and the
|
|
22
|
+
// student-inline encoder kind were dropped in 0.17: such a file is refused
|
|
23
|
+
// with a message saying it needs recompiling.
|
|
23
24
|
|
|
24
|
-
import { loadStudentModel, embedTextWithStudent } from './student-embedder.mjs';
|
|
25
|
-
import { computeMatchQuality, computePreSearchAbstention } from './student-abstention.mjs';
|
|
26
|
-
import { createAbstentionScorer } from './retrieval-abstention.mjs';
|
|
27
25
|
import { openLexicalIndex, openLexicalIndexLazy } from './lexical.mjs';
|
|
28
26
|
import { groundQuery, GROUNDING_PASSAGES } from './grounding.mjs';
|
|
29
27
|
import { parseRowMapSegment } from './rowmap.mjs';
|
|
@@ -39,10 +37,9 @@ import {
|
|
|
39
37
|
} from './inline-transformer.mjs';
|
|
40
38
|
|
|
41
39
|
export { httpRangeSource } from './sources.mjs';
|
|
42
|
-
// Re-exported for the builder side
|
|
43
|
-
//
|
|
44
|
-
//
|
|
45
|
-
// buildLexicalSegment, before the artifact is written to disk.
|
|
40
|
+
// Re-exported for the builder side and the BEIR benchmarks: an in-memory
|
|
41
|
+
// lexical searcher over the segment bytes buildLexicalSegment assembled,
|
|
42
|
+
// before the artifact is written to disk.
|
|
46
43
|
export { openLexicalIndex } from './lexical.mjs';
|
|
47
44
|
export { fuseCandidates, FUSION_DEFAULTS, ENCODER_FUSION_DEFAULTS, fusionDefaultsFor } from './fusion.mjs';
|
|
48
45
|
import { fuseCandidates, fusionDefaultsFor } from './fusion.mjs';
|
|
@@ -54,11 +51,9 @@ export {
|
|
|
54
51
|
};
|
|
55
52
|
|
|
56
53
|
// Supported container formats: header formatVersion -> manifest profile.
|
|
57
|
-
export const SUPPORTED_PROFILES = Object.freeze({
|
|
58
|
-
//
|
|
59
|
-
|
|
60
|
-
// both spellings indefinitely; builds only write SUPPORTED_PROFILES.
|
|
61
|
-
const LEGACY_PROFILES = Object.freeze({ 1: 'pancake-complete-v1', 2: 'pancake-complete-v2' });
|
|
54
|
+
export const SUPPORTED_PROFILES = Object.freeze({ 2: 'pikelet-complete-v2' });
|
|
55
|
+
// What a file from before 0.17 hears instead of a bare "unsupported".
|
|
56
|
+
const RECOMPILE = 'it was built by a Pikelet release before 0.17; recompile it from its source';
|
|
62
57
|
export const CORPUS_LAYOUT_V2 = 'records-v2';
|
|
63
58
|
|
|
64
59
|
// Read budgets. Open-path reads (manifest, segment table, query-interp,
|
|
@@ -79,16 +74,11 @@ const RECORD_CACHE = 256;
|
|
|
79
74
|
const SKETCH_HEADER_BYTES = 256;
|
|
80
75
|
// Hybrid retrieval: BM25 candidates fetched from the lexical segment per
|
|
81
76
|
// query; the fusion rule and its constants live in fusion.mjs, shared with
|
|
82
|
-
// the
|
|
77
|
+
// the chain reader and the BEIR ladder.
|
|
83
78
|
export const LEXICAL_CANDIDATES = 24;
|
|
84
|
-
// How many fused top records to hydrate in the shared batch so the coverage
|
|
85
|
-
// term hits warm cache (asset.coverage.topK, 5 by default). A batch-sizing
|
|
86
|
-
// choice only: too many costs a little bandwidth, too few a later fetch.
|
|
87
|
-
const COVERAGE_BATCH_COUNT = 5;
|
|
88
79
|
// Only BM25 hits scoring at least top / LEXICAL_CUTOFF join fusion:
|
|
89
80
|
// common terms give every matching document a near-tied score that carries
|
|
90
|
-
// no ranking information.
|
|
91
|
-
// is fit against the same cutoff.
|
|
81
|
+
// no ranking information.
|
|
92
82
|
export const LEXICAL_CUTOFF = 1.5;
|
|
93
83
|
// Query-interpretation segments above this size open lazily (kind 3's
|
|
94
84
|
// inline encoder is ~25 MiB); smaller ones keep the one-read eager path.
|
|
@@ -272,13 +262,6 @@ function toFloat32(vector, dim, what) {
|
|
|
272
262
|
return v;
|
|
273
263
|
}
|
|
274
264
|
|
|
275
|
-
export function base64Bytes(text) {
|
|
276
|
-
if (typeof text !== 'string') return new Uint8Array(0);
|
|
277
|
-
return typeof Buffer !== 'undefined'
|
|
278
|
-
? Buffer.from(text, 'base64')
|
|
279
|
-
: Uint8Array.from(atob(text), (c) => c.charCodeAt(0));
|
|
280
|
-
}
|
|
281
|
-
|
|
282
265
|
// Contract 4.4 mode 2: a host-supplied encoder for a pinned external model
|
|
283
266
|
// is checked against the declaration's verification vectors before the
|
|
284
267
|
// artifact serves a single query. Dimension and every component within the
|
|
@@ -566,7 +549,9 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
566
549
|
}
|
|
567
550
|
const formatVersion = headerView.getUint32(4, true);
|
|
568
551
|
const profile = SUPPORTED_PROFILES[formatVersion];
|
|
569
|
-
if (!profile)
|
|
552
|
+
if (!profile) {
|
|
553
|
+
throw new Error(`unsupported .pikelet format version ${formatVersion}${formatVersion === 1 ? `: ${RECOMPILE}` : ''}`);
|
|
554
|
+
}
|
|
570
555
|
const manifestBytes = headerView.getUint32(8, true);
|
|
571
556
|
const segmentCount = headerView.getUint32(12, true);
|
|
572
557
|
const fileBytes = u64(headerView, 16, 'header fileBytes');
|
|
@@ -610,9 +595,9 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
610
595
|
// passes asChainMember to accept one.
|
|
611
596
|
const isLayerProfile = manifest?.profile === 'pikelet-layer-v1' && formatVersion === 2;
|
|
612
597
|
const acceptLayer = isLayerProfile && options.asChainMember === true;
|
|
613
|
-
if (!manifest || typeof manifest !== 'object'
|
|
614
|
-
|
|
615
|
-
throw new Error(`unsupported profile ${manifest?.profile} for format version ${formatVersion}`);
|
|
598
|
+
if (!manifest || typeof manifest !== 'object' || (manifest.profile !== profile && !acceptLayer)) {
|
|
599
|
+
const legacy = typeof manifest?.profile === 'string' && manifest.profile.startsWith('pancake-');
|
|
600
|
+
throw new Error(`unsupported profile ${manifest?.profile} for format version ${formatVersion}${legacy ? `: ${RECOMPILE}` : ''}`);
|
|
616
601
|
}
|
|
617
602
|
if (!Array.isArray(manifest.segments) || manifest.segments.length !== segmentCount) {
|
|
618
603
|
throw new Error('.pikelet manifest segment list disagrees with the header segment count');
|
|
@@ -718,47 +703,31 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
718
703
|
throw new Error('.pikelet manifest corpus.records is implausible');
|
|
719
704
|
}
|
|
720
705
|
const layout = manifest.corpus.layout;
|
|
721
|
-
|
|
722
|
-
if (perRecord && layout !== CORPUS_LAYOUT_V2) {
|
|
706
|
+
if (layout !== CORPUS_LAYOUT_V2) {
|
|
723
707
|
throw new Error(`.pikelet format ${formatVersion} requires corpus layout ${CORPUS_LAYOUT_V2}, manifest says ${layout}`);
|
|
724
708
|
}
|
|
725
|
-
|
|
726
|
-
|
|
709
|
+
const pageRecords = manifest.corpus.pageRecords;
|
|
710
|
+
if (!Number.isSafeInteger(pageRecords) || pageRecords < 1 || pageRecords > MAX_PAGE_RECORDS) {
|
|
711
|
+
throw new Error('.pikelet manifest corpus.pageRecords is implausible');
|
|
727
712
|
}
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
let recordDigestsAt = 0;
|
|
733
|
-
let recordsAt;
|
|
734
|
-
if (perRecord) {
|
|
735
|
-
pageRecords = manifest.corpus.pageRecords;
|
|
736
|
-
if (!Number.isSafeInteger(pageRecords) || pageRecords < 1 || pageRecords > MAX_PAGE_RECORDS) {
|
|
737
|
-
throw new Error('.pikelet manifest corpus.pageRecords is implausible');
|
|
738
|
-
}
|
|
739
|
-
pages = Math.ceil(declaredRecords / pageRecords);
|
|
740
|
-
if (manifest.corpus.pages !== pages || !isSha256Hex(manifest.corpus.pageTableSha256)
|
|
741
|
-
|| manifest.corpus.recordDigest !== 'sha256') {
|
|
742
|
-
throw new Error('.pikelet manifest corpus integrity block is inconsistent');
|
|
743
|
-
}
|
|
744
|
-
offsetsAt = 8;
|
|
745
|
-
tablesBytes = offsetsAt + 8 * (declaredRecords + 1) + 32 * pages;
|
|
746
|
-
recordDigestsAt = tablesBytes;
|
|
747
|
-
recordsAt = recordDigestsAt + 32 * declaredRecords;
|
|
748
|
-
} else {
|
|
749
|
-
offsetsAt = 4;
|
|
750
|
-
tablesBytes = offsetsAt + 8 * (declaredRecords + 1);
|
|
751
|
-
recordsAt = tablesBytes;
|
|
713
|
+
const pages = Math.ceil(declaredRecords / pageRecords);
|
|
714
|
+
if (manifest.corpus.pages !== pages || !isSha256Hex(manifest.corpus.pageTableSha256)
|
|
715
|
+
|| manifest.corpus.recordDigest !== 'sha256') {
|
|
716
|
+
throw new Error('.pikelet manifest corpus integrity block is inconsistent');
|
|
752
717
|
}
|
|
718
|
+
const offsetsAt = 8;
|
|
719
|
+
const tablesBytes = offsetsAt + 8 * (declaredRecords + 1) + 32 * pages;
|
|
720
|
+
const recordDigestsAt = tablesBytes;
|
|
721
|
+
const recordsAt = recordDigestsAt + 32 * declaredRecords;
|
|
753
722
|
if (!Number.isSafeInteger(recordsAt) || recordsAt > corpus.length) {
|
|
754
723
|
throw new Error('.pikelet manifest corpus.records is implausible for the corpus segment');
|
|
755
724
|
}
|
|
756
|
-
//
|
|
725
|
+
// The manifest commits to the embedded sketch's 256-byte header
|
|
757
726
|
// (metric/dim/count and the sketch's residentSha256/vectorsSha256),
|
|
758
727
|
// anchoring the sketch's own integrity chain to the identity; the
|
|
759
728
|
// sketch's self-checks alone verify against fields an attacker who
|
|
760
729
|
// rewrites the segment also controls.
|
|
761
|
-
if (
|
|
730
|
+
if (!isSha256Hex(manifest.index?.headerSha256) || idx.length < SKETCH_HEADER_BYTES) {
|
|
762
731
|
throw new Error('.pikelet manifest carries no index header commitment (index.headerSha256)');
|
|
763
732
|
}
|
|
764
733
|
|
|
@@ -766,11 +735,10 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
766
735
|
// query-interp segment, the embedded sketch and the corpus tables fetch as
|
|
767
736
|
// one concurrent wave instead of dependent rounds.
|
|
768
737
|
// A large query-interp segment (kind 3's ~25 MiB encoder) is not read at
|
|
769
|
-
// open: its header joins the wave
|
|
770
|
-
//
|
|
771
|
-
//
|
|
772
|
-
//
|
|
773
|
-
// unverified influences a result.
|
|
738
|
+
// open: its header joins the wave and the encoder bytes arrive lazily
|
|
739
|
+
// (prefetched in the background, awaited by the first query). The header
|
|
740
|
+
// is byte-compared against the digest-verified segment before any query
|
|
741
|
+
// can complete, so nothing unverified influences a result.
|
|
774
742
|
const qiDeferrable = qi.length > LAZY_QI_BYTES;
|
|
775
743
|
const [qiFirst, sketch, tables, lexicalBytes, rowMapBytes] = await Promise.all([
|
|
776
744
|
(async () => {
|
|
@@ -783,12 +751,12 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
783
751
|
}
|
|
784
752
|
return bytes;
|
|
785
753
|
})(),
|
|
786
|
-
//
|
|
787
|
-
//
|
|
754
|
+
// The header commitment is checked inside open(), against the
|
|
755
|
+
// same bytes the sketch parses (see expectedHeaderSha256).
|
|
788
756
|
PikeletSketchArtifact.open(windowSource(source, idx.offset, idx.length), {
|
|
789
757
|
maxReadBytes,
|
|
790
758
|
...(options.blobCache ? { blobCache: options.blobCache } : {}),
|
|
791
|
-
|
|
759
|
+
expectedHeaderSha256: manifest.index.headerSha256,
|
|
792
760
|
}),
|
|
793
761
|
readChecked(source, corpus.offset, tablesBytes, 'corpus tables', maxReadBytes, fileBytes),
|
|
794
762
|
// Lexical index (kind 5, OPTIONAL). Small segments: eager
|
|
@@ -864,82 +832,23 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
864
832
|
}
|
|
865
833
|
qiDeferred = false;
|
|
866
834
|
}
|
|
867
|
-
//
|
|
868
|
-
//
|
|
869
|
-
//
|
|
870
|
-
|
|
871
|
-
? await readChecked(source, qi.offset + 16 + encoderLen, calibrationLen, 'calibration region', maxReadBytes, fileBytes)
|
|
872
|
-
: qiBytes.subarray(16 + encoderLen);
|
|
835
|
+
// The calibration region (the second one) is reserved: packs before
|
|
836
|
+
// 0.17 could carry a fitted matchQuality model there, which this
|
|
837
|
+
// reader no longer scores, so it reads nothing from it. Its bytes are
|
|
838
|
+
// still covered by the segment digest like the rest.
|
|
873
839
|
const encoderBytes = qiDeferred ? null : qiBytes.subarray(16, 16 + encoderLen);
|
|
874
|
-
let calibrationJson;
|
|
875
|
-
try { calibrationJson = JSON.parse(decoder.decode(calibrationRegion)); } catch (err) {
|
|
876
|
-
throw new Error('.pikelet calibration is not valid JSON', { cause: err });
|
|
877
|
-
}
|
|
878
|
-
if (!calibrationJson || typeof calibrationJson !== 'object') {
|
|
879
|
-
throw new Error('.pikelet calibration must be a JSON object');
|
|
880
|
-
}
|
|
881
840
|
|
|
882
|
-
// kind
|
|
883
|
-
// abstention. kind 2 (external-transformers-v1): the encoder is a
|
|
841
|
+
// kind 2 (external-transformers-v1): the encoder is a
|
|
884
842
|
// pinned declaration the HOST must satisfy via options.encodeQuery,
|
|
885
|
-
// verified against the declaration's test vectors before serving
|
|
886
|
-
//
|
|
887
|
-
//
|
|
888
|
-
//
|
|
843
|
+
// verified against the declaration's test vectors before serving.
|
|
844
|
+
// kind 3 (inline-transformer-v1): the pinned teacher as data,
|
|
845
|
+
// executed by reader-owned kernels, verified against its own test
|
|
846
|
+
// vectors.
|
|
889
847
|
let embed;
|
|
890
|
-
let preScore = (_context) => null;
|
|
891
|
-
let scoreQuality;
|
|
892
848
|
let encoderInfo;
|
|
893
849
|
let encoderVerified = null;
|
|
894
|
-
const retrievalScorer = () => {
|
|
895
|
-
const scorer = createAbstentionScorer(calibrationJson.asset, base64Bytes(calibrationJson.vocabBloomBase64));
|
|
896
|
-
const VERDICTS = { answer: 'strong', weak: 'weak', abstain: 'none' };
|
|
897
|
-
return async (hits, context, fusedHits, scoreOptions) => {
|
|
898
|
-
if (!scorer) return { match_quality: 'unscored' };
|
|
899
|
-
// The coverage term grounds the verdict in the top passages' text, so they
|
|
900
|
-
// hydrate before scoring, from the fused order when there is one (as
|
|
901
|
-
// calibrate.mjs fits it) and from vector order otherwise. Hydration failures
|
|
902
|
-
// propagate: on format 2 a record that fails its digest must fail the query,
|
|
903
|
-
// not skew its verdict.
|
|
904
|
-
const passageSource = fusedHits?.length ? fusedHits : hits;
|
|
905
|
-
// A record's text starts with its heading (ingest.mjs). Coverage gives a
|
|
906
|
-
// heading match reduced credit, and this split must match
|
|
907
|
-
// retrieval-abstention.mjs's coverageFrac and calibrate.mjs exactly, or the
|
|
908
|
-
// thresholds score a different signal than the one they were fit on.
|
|
909
|
-
const splitHeadingBody = (text) => {
|
|
910
|
-
const nl = String(text || '').indexOf('\n');
|
|
911
|
-
return nl === -1 ? { heading: text, body: '' } : { heading: text.slice(0, nl), body: text.slice(nl + 1) };
|
|
912
|
-
};
|
|
913
|
-
// A chain supplies the passages itself (context.passages): its
|
|
914
|
-
// ids are GLOBAL, and this hydrate only knows this member's
|
|
915
|
-
// local ids, so letting it fetch them would throw on any id a
|
|
916
|
-
// layer owns. Single-file callers pass none and it hydrates.
|
|
917
|
-
const topTexts = Array.isArray(context.passages)
|
|
918
|
-
? context.passages.slice(0, scorer.passagesNeeded || 1).map(splitHeadingBody)
|
|
919
|
-
: scorer.usesPassage && passageSource.length
|
|
920
|
-
? (await Promise.all(passageSource.slice(0, scorer.passagesNeeded || 1)
|
|
921
|
-
.map((hit) => hydrate(hit.id)))).map((record) => splitHeadingBody(record?.text))
|
|
922
|
-
: [];
|
|
923
|
-
// scoreOptions.vocabBloom is the chain's union bloom (4.5).
|
|
924
|
-
// Absent for a single-file pack, where the fit's own bloom is
|
|
925
|
-
// the whole vocabulary.
|
|
926
|
-
const scored = await scorer.score(context.text, hits, topTexts, {
|
|
927
|
-
vocabBloom: scoreOptions?.vocabBloom,
|
|
928
|
-
});
|
|
929
|
-
return { match_quality: VERDICTS[scored.verdict] || scored.verdict, confidence: scored.p, grounding: scored.grounding || null };
|
|
930
|
-
};
|
|
931
|
-
};
|
|
932
850
|
if (qiKind === 1) {
|
|
933
|
-
|
|
934
|
-
encoderInfo = { kind: 'student-inline-v1' };
|
|
935
|
-
embed = (text) => {
|
|
936
|
-
const embedded = embedTextWithStudent(text, student);
|
|
937
|
-
return { vector: toFloat32(embedded.vector, dim, 'inline student encoder'), embedded };
|
|
938
|
-
};
|
|
939
|
-
// Pre-search abstention skips the index entirely when it fires,
|
|
940
|
-
// exactly as the Worker does.
|
|
941
|
-
preScore = (context) => computePreSearchAbstention(context.embedded, calibrationJson);
|
|
942
|
-
scoreQuality = (hits, context) => computeMatchQuality(hits, context.embedded, calibrationJson);
|
|
851
|
+
throw new Error(`.pikelet uses the student-inline-v1 encoder: ${RECOMPILE}`);
|
|
943
852
|
} else if (qiKind === 2) {
|
|
944
853
|
let declaration;
|
|
945
854
|
try { declaration = JSON.parse(decoder.decode(encoderBytes)); } catch (err) {
|
|
@@ -973,10 +882,9 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
973
882
|
}
|
|
974
883
|
return { vector: toFloat32(await encodeQuery(text), dim, 'options.encodeQuery'), text };
|
|
975
884
|
};
|
|
976
|
-
scoreQuality = retrievalScorer();
|
|
977
885
|
} else if (qiKind === 3) {
|
|
978
886
|
// Kernels are reader-owned (spec 3.6) and load dynamically so
|
|
979
|
-
// kind-
|
|
887
|
+
// kind-2 files never touch them; the node-only glue is hidden
|
|
980
888
|
// from bundlers, the web glue stays analyzable so browser builds
|
|
981
889
|
// carry it. options.createEncoder overrides the loader.
|
|
982
890
|
let createEncoder = options.createEncoder;
|
|
@@ -1007,12 +915,10 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1007
915
|
}
|
|
1008
916
|
blobCachePut(options.blobCache, qi.sha256, full);
|
|
1009
917
|
}
|
|
1010
|
-
// The header
|
|
1011
|
-
//
|
|
1012
|
-
//
|
|
1013
|
-
|
|
1014
|
-
if (!bytesEqual(full.subarray(0, 16), openHeader)
|
|
1015
|
-
|| !bytesEqual(full.subarray(16 + encoderLen), calibrationRegion)) {
|
|
918
|
+
// The header used at open was unverified; the
|
|
919
|
+
// digest-verified segment must contain it byte for byte,
|
|
920
|
+
// or the open state is poisoned and every query must fail.
|
|
921
|
+
if (!bytesEqual(full.subarray(0, 16), openHeader)) {
|
|
1016
922
|
throw new Error('.pikelet query-interp segment bytes changed between open and encoder fetch');
|
|
1017
923
|
}
|
|
1018
924
|
encBytes = full.subarray(16, 16 + encoderLen);
|
|
@@ -1050,7 +956,6 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1050
956
|
const { vector } = await embedder.embed(`${declaration.prefixPolicy?.query || ''}${text}`);
|
|
1051
957
|
return { vector: toFloat32(vector, dim, 'inline transformer encoder'), text };
|
|
1052
958
|
};
|
|
1053
|
-
scoreQuality = retrievalScorer();
|
|
1054
959
|
} else if (qiKind === 4 && acceptLayer) {
|
|
1055
960
|
// Kind 4, `inherited-v1` (layered profile 4.5): a layer carries a
|
|
1056
961
|
// COMMITMENT to the base's encoder, never encoder bytes. This open
|
|
@@ -1061,7 +966,6 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1061
966
|
embed = async () => {
|
|
1062
967
|
throw new Error('a layer inherits its encoder from the base: query the chain, not the layer (4.5)');
|
|
1063
968
|
};
|
|
1064
|
-
scoreQuality = null;
|
|
1065
969
|
} else {
|
|
1066
970
|
throw new Error(`unsupported query-interpretation kind ${qiKind}`);
|
|
1067
971
|
}
|
|
@@ -1144,13 +1048,13 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1144
1048
|
|
|
1145
1049
|
// Corpus tables: cross-check the segment's own words, then the
|
|
1146
1050
|
// offsets — monotonic, starting exactly where the tables end, ending
|
|
1147
|
-
// inside the segment — and
|
|
1051
|
+
// inside the segment — and the page table's digest.
|
|
1148
1052
|
const tablesView = viewOf(tables);
|
|
1149
1053
|
const recordCount = tablesView.getUint32(0, true);
|
|
1150
1054
|
if (recordCount !== declaredRecords) {
|
|
1151
1055
|
throw new Error('.pikelet corpus count disagrees with manifest');
|
|
1152
1056
|
}
|
|
1153
|
-
if (
|
|
1057
|
+
if (tablesView.getUint32(4, true) !== pageRecords) {
|
|
1154
1058
|
throw new Error('.pikelet corpus page size disagrees with manifest');
|
|
1155
1059
|
}
|
|
1156
1060
|
const recordOffsets = new Float64Array(recordCount + 1);
|
|
@@ -1161,14 +1065,11 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1161
1065
|
}
|
|
1162
1066
|
recordOffsets[i] = value;
|
|
1163
1067
|
}
|
|
1164
|
-
|
|
1165
|
-
if (
|
|
1166
|
-
|
|
1167
|
-
if (await sha256hex(pageTable) !== manifest.corpus.pageTableSha256) {
|
|
1168
|
-
throw new Error('.pikelet corpus page table failed hash verification');
|
|
1169
|
-
}
|
|
1068
|
+
const pageTable = tables.slice(offsetsAt + 8 * (recordCount + 1), tablesBytes);
|
|
1069
|
+
if (await sha256hex(pageTable) !== manifest.corpus.pageTableSha256) {
|
|
1070
|
+
throw new Error('.pikelet corpus page table failed hash verification');
|
|
1170
1071
|
}
|
|
1171
|
-
const corpusIntegrity =
|
|
1072
|
+
const corpusIntegrity = verifyRecords ? 'per-record-sha256' : 'per-record-sha256 (unverified by option)';
|
|
1172
1073
|
|
|
1173
1074
|
// Per-page record-digest cache: a page is fetched (one read of
|
|
1174
1075
|
// 32 * pageRecords bytes), verified against the page table, and kept
|
|
@@ -1214,7 +1115,7 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1214
1115
|
return record;
|
|
1215
1116
|
};
|
|
1216
1117
|
|
|
1217
|
-
// One record's stored bytes, read and
|
|
1118
|
+
// One record's stored bytes, read and verified against
|
|
1218
1119
|
// its per-record digest. hydrate() parses these; `compact` (6.3)
|
|
1219
1120
|
// copies them verbatim through the chain's __recordBytes seam.
|
|
1220
1121
|
const readRecordBytes = async (id) => {
|
|
@@ -1226,7 +1127,7 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1226
1127
|
// With options.blobCache a verified record is keyed by its own
|
|
1227
1128
|
// digest, so the digest comes first; another process may already
|
|
1228
1129
|
// have fetched the record. Only verified reads use the cache.
|
|
1229
|
-
const cacheable =
|
|
1130
|
+
const cacheable = verifyRecords && options.blobCache;
|
|
1230
1131
|
let digest = null;
|
|
1231
1132
|
if (cacheable) {
|
|
1232
1133
|
const page = Math.floor(id / pageRecords);
|
|
@@ -1236,7 +1137,7 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1236
1137
|
if (cached) return cached;
|
|
1237
1138
|
}
|
|
1238
1139
|
const bytes = await readChecked(source, corpus.offset + start, end - start, `corpus record ${id}`, maxRecordBytes, fileBytes);
|
|
1239
|
-
if (
|
|
1140
|
+
if (verifyRecords) {
|
|
1240
1141
|
if (!digest) {
|
|
1241
1142
|
const page = Math.floor(id / pageRecords);
|
|
1242
1143
|
const at = 32 * (id - page * pageRecords);
|
|
@@ -1293,11 +1194,8 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1293
1194
|
const packFusion = fusionDefaultsFor(encoderInfo?.model);
|
|
1294
1195
|
|
|
1295
1196
|
// The one retrieval path behind query(): resident sketch scan plus BM25
|
|
1296
|
-
// candidates, exact rerank, rank fusion and phrase pinning.
|
|
1297
|
-
|
|
1298
|
-
// from both candidate sources before either is cut to size (calibration
|
|
1299
|
-
// ablations only).
|
|
1300
|
-
const retrieveCandidates = async (trimmed, context, k, queryOptions, excludeIds = null) => {
|
|
1197
|
+
// candidates, exact rerank, rank fusion and phrase pinning.
|
|
1198
|
+
const retrieveCandidates = async (trimmed, context, k, queryOptions) => {
|
|
1301
1199
|
let fusedFull = null;
|
|
1302
1200
|
// retrieval: 'hybrid' (default with a lexical segment) - BM25 top matches
|
|
1303
1201
|
// join the exact rerank as extra candidates (recovering known items the
|
|
@@ -1307,8 +1205,6 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1307
1205
|
// 'augmented' - lexical candidates join the rerank but order stays by pure
|
|
1308
1206
|
// distance, for workloads scored against exact nearest neighbors.
|
|
1309
1207
|
// 'vector' | 'lexical' - for measurement and debugging.
|
|
1310
|
-
// Abstention scores the distance-sorted window identically in every mode;
|
|
1311
|
-
// fusion changes result order only.
|
|
1312
1208
|
const retrieval = queryOptions.retrieval ?? 'hybrid';
|
|
1313
1209
|
if (!['hybrid', 'vector', 'lexical', 'augmented'].includes(retrieval)) {
|
|
1314
1210
|
throw new Error(`query() retrieval must be hybrid, vector, lexical, or augmented, got ${retrieval}`);
|
|
@@ -1317,23 +1213,8 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1317
1213
|
throw new Error('query() fusion must be an object of rrfK, lexicalWeight and guardMargin');
|
|
1318
1214
|
}
|
|
1319
1215
|
const fusion = queryOptions.fusion ? { ...packFusion, ...queryOptions.fusion } : packFusion;
|
|
1320
|
-
// An excluded record must not take a candidate slot on either
|
|
1321
|
-
// side, so both sources skip it before cutting to size — BM25
|
|
1322
|
-
// before its top-n sort (scored with the full corpus's term
|
|
1323
|
-
// statistics, the one way this differs from a corpus without
|
|
1324
|
-
// those records) and the sketch before its top-C cut.
|
|
1325
|
-
const excluded = excludeIds && excludeIds.size ? excludeIds : null;
|
|
1326
|
-
let excludeBits = null;
|
|
1327
|
-
if (excluded) {
|
|
1328
|
-
excludeBits = new Uint8Array(Math.ceil(sketch.count / 8));
|
|
1329
|
-
for (const id of excluded) {
|
|
1330
|
-
// With a row map, excluding a record masks every row it owns.
|
|
1331
|
-
const [from, to] = rowMap ? [rowMap.offsets[id], rowMap.offsets[id + 1]] : [id, id + 1];
|
|
1332
|
-
for (let row = from; row < to; row++) excludeBits[row >> 3] |= 1 << (row & 7);
|
|
1333
|
-
}
|
|
1334
|
-
}
|
|
1335
1216
|
const lexicalRaw = lexicalIndex && retrieval !== 'vector'
|
|
1336
|
-
? await lexicalIndex.search(trimmed, LEXICAL_CANDIDATES
|
|
1217
|
+
? await lexicalIndex.search(trimmed, LEXICAL_CANDIDATES)
|
|
1337
1218
|
: [];
|
|
1338
1219
|
const lexicalHits = lexicalRaw.filter((h) => h.score >= lexicalRaw[0].score / LEXICAL_CUTOFF);
|
|
1339
1220
|
// With a row map (3.9) the sketch searches rows: a record's lexical
|
|
@@ -1354,9 +1235,8 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1354
1235
|
// exceeds the scanner's buffers.
|
|
1355
1236
|
...(scanner ? { scanner } : {}),
|
|
1356
1237
|
...(extraRows.length ? { extraCandidates: extraRows } : {}),
|
|
1357
|
-
|
|
1358
|
-
//
|
|
1359
|
-
// top-10 window independent of the caller's k (retrieval-abstention.mjs).
|
|
1238
|
+
// The full reranked list, not k: fusion ranks the whole window
|
|
1239
|
+
// and grounding reads its top passages whatever the caller's k.
|
|
1360
1240
|
fullRerankOutput: true,
|
|
1361
1241
|
})).results;
|
|
1362
1242
|
// The rerank output is distance-ordered, so a record's first row
|
|
@@ -1372,8 +1252,8 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1372
1252
|
}
|
|
1373
1253
|
}
|
|
1374
1254
|
const hits = searched.slice(0, k);
|
|
1375
|
-
// Full-window fused order
|
|
1376
|
-
//
|
|
1255
|
+
// Full-window fused order: a k-truncated list would drop the fused top
|
|
1256
|
+
// hit grounding grades for callers asking for a small k.
|
|
1377
1257
|
if (retrieval === 'lexical') {
|
|
1378
1258
|
const byId = new Map(searched.map((hit) => [hit.id, hit]));
|
|
1379
1259
|
fusedFull = lexicalHits.map((h) => byId.get(h.id)).filter(Boolean);
|
|
@@ -1381,13 +1261,13 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1381
1261
|
const lexRank = new Map(lexicalHits.map((h, i) => [h.id, i]));
|
|
1382
1262
|
fusedFull = fuseCandidates(searched, lexicalHits.map((h) => h.id), fusion);
|
|
1383
1263
|
// One batched hydration for phrase pinning's candidates (top lexical hits)
|
|
1384
|
-
// and
|
|
1264
|
+
// and grounding's (fusedFull's top few): over a range-read source each
|
|
1385
1265
|
// uncached hydrate() is a round trip, so the two stages share one. A record
|
|
1386
1266
|
// that fails here does not fail the query; it is just missing from the map,
|
|
1387
1267
|
// and a site that actually needs it hydrates (and fails) itself.
|
|
1388
1268
|
const phraseCandidates = lexicalHits.slice(0, 3);
|
|
1389
|
-
const
|
|
1390
|
-
const batchIds = [...new Set([...phraseCandidates, ...
|
|
1269
|
+
const groundingCandidates = fusedFull.slice(0, GROUNDING_PASSAGES);
|
|
1270
|
+
const batchIds = [...new Set([...phraseCandidates, ...groundingCandidates].map((h) => h.id))];
|
|
1391
1271
|
const batch = new Map();
|
|
1392
1272
|
await Promise.all(batchIds.map(async (id) => {
|
|
1393
1273
|
try { batch.set(id, await hydrate(id)); } catch { /* see comment above */ }
|
|
@@ -1455,13 +1335,11 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1455
1335
|
// True only after a full vectors pass (verifyIndexVectors
|
|
1456
1336
|
// at open, or verifyVectors() later).
|
|
1457
1337
|
vectorsVerified: sketch.vectorsVerified === true,
|
|
1458
|
-
//
|
|
1459
|
-
//
|
|
1460
|
-
//
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
indexRowIntegrity: sketch.formatVersion >= 2 && sketch.verifyRows !== false
|
|
1464
|
-
? 'per-row-sha256' : 'segment-sha256',
|
|
1338
|
+
// Every rerank row is verified on its own read against
|
|
1339
|
+
// the identity-anchored page-hash table, unless the
|
|
1340
|
+
// caller opened with verification off.
|
|
1341
|
+
indexRowIntegrity: sketch.verifyRows !== false
|
|
1342
|
+
? 'per-row-sha256' : 'per-row-sha256 (unverified by option)',
|
|
1465
1343
|
// 'engine' once a WASM scan kernel serves the resident
|
|
1466
1344
|
// scan (auto-staged or injected); 'js' before staging
|
|
1467
1345
|
// resolves and forever if it fails or was disabled.
|
|
@@ -1511,63 +1389,24 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1511
1389
|
const trimmed = String(text || '').trim();
|
|
1512
1390
|
if (!trimmed) throw new Error('query text is required');
|
|
1513
1391
|
const context = await embed(trimmed);
|
|
1514
|
-
const
|
|
1515
|
-
let hits = [];
|
|
1516
|
-
let fused = null;
|
|
1517
|
-
let searched = null;
|
|
1518
|
-
let fusedFull = null;
|
|
1519
|
-
if (!pre) ({ hits, fused, searched, fusedFull } = await retrieveCandidates(trimmed, context, k, queryOptions));
|
|
1520
|
-
// Abstention scores the full reranked window (searched), not the
|
|
1521
|
-
// k-truncated hits, because calibration fits at a fixed top-10 (top-5 for
|
|
1522
|
-
// coverage). fusedFull lets coverage grade the passage fusion ranks first,
|
|
1523
|
-
// while d0/margin/mean10 read vector order as calibrated. preScore (kind 1)
|
|
1524
|
-
// runs before search and is unaffected.
|
|
1525
|
-
const quality = pre || await scoreQuality(searched ?? hits, context, fusedFull);
|
|
1526
|
-
// A 'none' verdict withholds results by default — the
|
|
1527
|
-
// calibrated abstention signal is doing its job, and most
|
|
1528
|
-
// callers want that. showAbstained is an explicit opt-out
|
|
1529
|
-
// for a caller that wants the raw retrieval anyway (e.g. to
|
|
1530
|
-
// inspect why the classifier abstained); it never changes
|
|
1531
|
-
// matchQuality or confidence, only whether results ships.
|
|
1532
|
-
const returned = quality.match_quality === 'none' && !queryOptions.showAbstained
|
|
1533
|
-
? [] : (fused || hits);
|
|
1392
|
+
const { hits, fused, searched, fusedFull } = await retrieveCandidates(trimmed, context, k, queryOptions);
|
|
1534
1393
|
// The search's id and distance are authoritative: they are
|
|
1535
1394
|
// written last so a corpus record carrying its own `id` or
|
|
1536
1395
|
// `distance` field cannot overwrite them (reserved names).
|
|
1537
|
-
const results = await Promise.all(
|
|
1396
|
+
const results = await Promise.all((fused || hits).map(async (hit) => {
|
|
1538
1397
|
const record = await hydrate(hit.id);
|
|
1539
1398
|
return { ...record, id: hit.id, distance: hit.distance, ...(hit.fusedRank ? { fusedRank: hit.fusedRank, lexicalRank: hit.lexicalRank, vectorRank: hit.vectorRank } : {}) };
|
|
1540
1399
|
}));
|
|
1541
1400
|
// Grounding: which query words the best of the top passages
|
|
1542
1401
|
// contains and which none does, so a consumer can tell a topical
|
|
1543
|
-
// match ("much money darcy make year") from an answer
|
|
1544
|
-
//
|
|
1545
|
-
//
|
|
1546
|
-
const passageOrder = (fusedFull?.length ? fusedFull :
|
|
1402
|
+
// match ("much money darcy make year") from an answer
|
|
1403
|
+
// (grounding.mjs), from the passages fusion ranks first;
|
|
1404
|
+
// recordId names the graded passage.
|
|
1405
|
+
const passageOrder = (fusedFull?.length ? fusedFull : searched).slice(0, GROUNDING_PASSAGES);
|
|
1547
1406
|
const passageTexts = await Promise.all(passageOrder.map(async (hit) => (await hydrate(hit.id))?.text ?? ''));
|
|
1548
1407
|
const graded = groundQuery(trimmed, passageTexts);
|
|
1549
1408
|
const grounding = graded ? { ...graded, recordId: passageOrder[graded.passageIndex]?.id ?? null } : null;
|
|
1550
|
-
return {
|
|
1551
|
-
},
|
|
1552
|
-
|
|
1553
|
-
/**
|
|
1554
|
-
* The retrieval evidence query() scores, for compile-time
|
|
1555
|
-
* calibration: `vector` is the distance-ordered rerank window
|
|
1556
|
-
* d0/margin/mean10 read, `fused` the order coverage reads its
|
|
1557
|
-
* passages from. Calibration consumes this instead of
|
|
1558
|
-
* reimplementing retrieval, so a verdict is fit on the evidence
|
|
1559
|
-
* it is later scored on. Not part of the documented reader API.
|
|
1560
|
-
*/
|
|
1561
|
-
async __calibrationEvidence(text, { excludeIds = null } = {}) {
|
|
1562
|
-
assertOpen();
|
|
1563
|
-
const trimmed = String(text || '').trim();
|
|
1564
|
-
if (!trimmed) throw new Error('query text is required');
|
|
1565
|
-
// The 10-wide window calibration fits at; any k up to the
|
|
1566
|
-
// pack's rerank depth gives query() the same candidates.
|
|
1567
|
-
const k = Math.min(10, Math.max(recordCount, 1));
|
|
1568
|
-
const { searched, fusedFull } = await retrieveCandidates(trimmed, await embed(trimmed), k, {}, excludeIds);
|
|
1569
|
-
const plain = (list) => list.map((hit) => ({ id: hit.id, distance: hit.distance }));
|
|
1570
|
-
return { vector: plain(searched), fused: plain(fusedFull?.length ? fusedFull : searched) };
|
|
1409
|
+
return { results, ...(grounding ? { grounding } : {}) };
|
|
1571
1410
|
},
|
|
1572
1411
|
|
|
1573
1412
|
/** Hydrate one corpus record by id (verified per record on format 2). */
|
|
@@ -1712,8 +1551,8 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1712
1551
|
// The base's own encoder, for `append` (6.1): a kind-3 base carries the
|
|
1713
1552
|
// teacher, so a pack can compile its own successors with no download.
|
|
1714
1553
|
// Resolving it here, not in the producer, makes substituting a different
|
|
1715
|
-
// encoder impossible. Null for kinds that cannot embed passages: kind
|
|
1716
|
-
// (
|
|
1554
|
+
// encoder impossible. Null for kinds that cannot embed passages: kind 2
|
|
1555
|
+
// (the host's encoder) and kind 4 (a layer, which inherits).
|
|
1717
1556
|
async passageEmbedder() {
|
|
1718
1557
|
assertOpen();
|
|
1719
1558
|
if (qiKind !== 3 || !resolveEmbedder) return null;
|
|
@@ -1729,51 +1568,18 @@ export async function openPikeletFile(input, options = {}) {
|
|
|
1729
1568
|
const { vector } = await embedder.embed(`${prefix}${text}`);
|
|
1730
1569
|
return vector;
|
|
1731
1570
|
},
|
|
1732
|
-
// A
|
|
1733
|
-
//
|
|
1734
|
-
//
|
|
1735
|
-
//
|
|
1736
|
-
//
|
|
1571
|
+
// A chain query is a caller's vector, so a host
|
|
1572
|
+
// that searches a chain (the MCP server, the
|
|
1573
|
+
// journal) embeds its text here. Queries take the
|
|
1574
|
+
// query prefix, not the passage one: the asymmetry
|
|
1575
|
+
// is the encoder's contract.
|
|
1737
1576
|
embedQuery: async (text) => {
|
|
1738
1577
|
const prefix = declaration.prefixPolicy?.query || '';
|
|
1739
1578
|
const { vector } = await embedder.embed(`${prefix}${text}`);
|
|
1740
1579
|
return vector;
|
|
1741
1580
|
},
|
|
1742
|
-
// Word-level vectors for the comparison feature.
|
|
1743
|
-
// Unprefixed by design -- a single word is not a
|
|
1744
|
-
// query needing an instruction prefix. Null when
|
|
1745
|
-
// the kernel cannot do it, which the caller reads
|
|
1746
|
-
// as "fit without that feature".
|
|
1747
|
-
embedWords: typeof embedder.embedWords === 'function'
|
|
1748
|
-
? (text) => embedder.embedWords(text)
|
|
1749
|
-
: null,
|
|
1750
1581
|
};
|
|
1751
1582
|
},
|
|
1752
|
-
// The base's own abstention scorer, for a chain serving
|
|
1753
|
-
// under `inherited` (5.5): "the base's
|
|
1754
|
-
// retrieval-signals-v1 scorer runs unchanged over the
|
|
1755
|
-
// merged searched window and fused passages, with the union
|
|
1756
|
-
// bloom of 4.5". Null when the base carries no fit, which
|
|
1757
|
-
// is what makes a chain report `none` rather than silently
|
|
1758
|
-
// omitting the verdict.
|
|
1759
|
-
scoreQuality: typeof scoreQuality === 'function' ? scoreQuality : null,
|
|
1760
|
-
// The base's fit, for a chain's calibration status (5.5).
|
|
1761
|
-
// It lives in the query-interp segment's calibration
|
|
1762
|
-
// region, not in the manifest — `asset` present means the
|
|
1763
|
-
// base carries a retrieval-signals fit, and
|
|
1764
|
-
// `asset.driftLimit` is the producer's declared validity
|
|
1765
|
-
// envelope when it declared one.
|
|
1766
|
-
calibrationJson,
|
|
1767
|
-
// A deferred kind-3 base read its calibration region at
|
|
1768
|
-
// open without a digest check; the region is verified
|
|
1769
|
-
// only when the full query-interp segment arrives (the
|
|
1770
|
-
// encoder load). A chain query takes a caller's vector
|
|
1771
|
-
// and never embeds, so it awaits this before trusting
|
|
1772
|
-
// calibrationJson. Rejects if the bytes did not verify.
|
|
1773
|
-
async calibrationVerified() {
|
|
1774
|
-
assertOpen();
|
|
1775
|
-
if (qiDeferred && resolveEmbedder) await resolveEmbedder();
|
|
1776
|
-
},
|
|
1777
1583
|
// Raw segment bytes for the chain's structural parsing
|
|
1778
1584
|
// (tombstones, kind-4). Bounded and digest-checked exactly
|
|
1779
1585
|
// as any other segment read: the digest comes from the
|