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.
- package/CHANGELOG.md +420 -0
- package/FORMAT.md +500 -0
- package/NOTICE +25 -0
- package/README.md +47 -19
- package/complete/blob-cache.node.mjs +245 -19
- package/complete/builder.mjs +47 -62
- package/complete/grounding.mjs +92 -0
- package/complete/index.d.ts +62 -20
- package/complete/index.mjs +215 -240
- package/complete/index.node.mjs +1 -1
- package/complete/layer-append.mjs +4 -8
- package/complete/layer-chain.mjs +1 -2
- package/complete/layer-compact.mjs +4 -6
- package/complete/layer-reader.mjs +89 -80
- package/complete/layer-rebase.mjs +1 -1
- package/complete/node-fetch.mjs +22 -3
- package/complete/retrieval-abstention.mjs +68 -91
- package/complete/sources.mjs +171 -68
- package/package.json +2 -1
- package/src/artifact/pikelet-artifact-common.js +15 -9
- package/src/artifact/pikelet-artifact-sketch.js +35 -1
- package/src/core/pikelet-core.js +9 -0
package/README.md
CHANGED
|
@@ -2,9 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
**Knowledge that ships as a file.**
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
A `.pikelet` file is a searchable corpus in a single file. It holds the source text, a vector index and a keyword (BM25) index, the neural encoder that turns a question into a vector, and the tests the pack was built to pass. Its identity is a SHA-256 digest that commits to all of it, so the file fixes not just what the corpus says but how it is queried: the model that encodes a question, the indexes that find candidates, and the order they rank passages in. **The format makes retrieval semantics part of the versioned knowledge artifact.**
|
|
6
6
|
|
|
7
|
-
The
|
|
7
|
+
The layout is built for byte-range reads. A reader opens the file from a small prefix and then fetches only the index rows and records a query needs, verifying each against the identity, so a pack can sit on disk, S3, R2, a CDN or any static HTTP host, with no vector database, embedding API or retrieval server behind it. [FORMAT.md](FORMAT.md) describes the binary structure, the embedded encoder, the indexes, the integrity commitments, versioning, compatibility and the format's limits.
|
|
8
|
+
|
|
9
|
+
**Pikelet** is the open-source toolchain for the format: a compiler (`pikelet compile`) that builds packs from folders, websites, git history or exported chats; a reader library (`pikelet-wasm`) for browsers, Node and edge workers; and an MCP server (`pikelet mcp`) that mounts packs for LLM agents.
|
|
8
10
|
|
|
9
11
|
It is built for corpora that are static or change on a release cycle: documentation, API references, manuals, standards, legal and policy texts, research corpora, and reference packs for agents.
|
|
10
12
|
|
|
@@ -13,19 +15,41 @@ It is built for corpora that are static or change on a release cycle: documentat
|
|
|
13
15
|
The `pikelet` CLI requires Node 22.23.4+, 24.22.1+ or 26.12.1+ (earlier releases' fetch decompresses whatever a server labels as encoded; 18.x and 20.x are end-of-life and cannot be fixed); the `pikelet-wasm` library runs on Node 18+, browsers, and Cloudflare Workers.
|
|
14
16
|
|
|
15
17
|
```bash
|
|
16
|
-
npx pikelet compile
|
|
18
|
+
npx pikelet compile ./docs --out docs.pikelet
|
|
17
19
|
```
|
|
18
20
|
|
|
19
21
|
```text
|
|
20
|
-
Ingested 3 docs ->
|
|
21
|
-
Embedded
|
|
22
|
-
|
|
22
|
+
Ingested 3 docs -> 16 chunks
|
|
23
|
+
Embedded 16/16 chunks with inline transformer
|
|
24
|
+
2/16 chunks exceeded the 512-token encoder window and were mean-pooled across windows
|
|
25
|
+
Validated self-recall@1 on 16 sampled chunks
|
|
26
|
+
Embedded 24 golden queries, each verified to retrieve its source
|
|
27
|
+
Built complete .pikelet artifact with 24.59 MiB
|
|
23
28
|
Compiled docs.pikelet
|
|
24
|
-
24.
|
|
29
|
+
24.59 MiB, 16 records, identity 5fcdaeac75d4...
|
|
30
|
+
Next:
|
|
31
|
+
pikelet query docs.pikelet "a question" search it here
|
|
32
|
+
pikelet mcp install --pack docs.pikelet give it to Claude Code
|
|
25
33
|
```
|
|
26
34
|
|
|
27
35
|
Every `.pikelet` is at least ~25 MiB, because the query encoder ships inside it: a 5-file folder and a 500-file folder both start around that size. The first run downloads the encoder from a GitHub release and caches it.
|
|
28
36
|
|
|
37
|
+
Compiling is mostly embedding, at about one chunk a second per CPU core: 828 chunks took 110 seconds on 8 cores, so a few thousand chunks take several minutes, and longer on a 2-core machine.
|
|
38
|
+
|
|
39
|
+
Search it from the terminal:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
npx pikelet query docs.pikelet "why is a pack one file"
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
```text
|
|
46
|
+
docs: 5 results
|
|
47
|
+
|
|
48
|
+
1. Why make knowledge a file
|
|
49
|
+
why-a-file.md#why-make-knowledge-a-file · distance 0.617
|
|
50
|
+
The reasoning behind the single-artifact design. ...
|
|
51
|
+
```
|
|
52
|
+
|
|
29
53
|
Give it to an LLM — Claude Code, Claude Desktop, or any MCP client:
|
|
30
54
|
|
|
31
55
|
```bash
|
|
@@ -39,9 +63,9 @@ Or query it from code:
|
|
|
39
63
|
```js
|
|
40
64
|
import { openPikeletFile } from 'pikelet-wasm/complete';
|
|
41
65
|
const pack = await openPikeletFile('docs.pikelet');
|
|
42
|
-
const out = await pack.query('how
|
|
43
|
-
console.log(out.
|
|
44
|
-
// '
|
|
66
|
+
const out = await pack.query('how is a remote pack verified', { k: 5 });
|
|
67
|
+
console.log(out.results[0]?.title, out.grounding?.uncovered);
|
|
68
|
+
// 'How a .pikelet query runs' []
|
|
45
69
|
```
|
|
46
70
|
|
|
47
71
|
`compile` also takes a live URL (`--source https://docs.example.com`), a repository's commit history (`--git ./repo`), or exported chats (`--conversations <file|folder>`). To install instead of using `npx`, run `npm install -g pikelet`. `create` builds a deployed search app (a Worker and UI) rather than a file. [QUICKSTART.md](QUICKSTART.md) walks the whole lifecycle; [`packages/pikelet/README.md`](packages/pikelet/README.md) is the full CLI reference.
|
|
@@ -63,11 +87,11 @@ The complete artifact is never downloaded. The transcript and per-query table ar
|
|
|
63
87
|
|
|
64
88
|
## Packs for agents
|
|
65
89
|
|
|
66
|
-
`pikelet mcp` serves one or more packs over the Model Context Protocol, with four tools: `search`, `get_record`, `list_packs`, and `verify_pack`, which replays the tests stored inside the pack. If one pack fails to mount (an unreachable host, a refused pin), the others still serve and `list_packs` names the missing one and why.
|
|
90
|
+
`pikelet mcp` serves one or more packs over the Model Context Protocol, with four tools: `search`, `get_record`, `list_packs`, and `verify_pack`, which replays the tests stored inside the pack. If one pack fails to mount (an unreachable host, a refused pin), the others still serve and `list_packs` names the missing one and why; one on a slow host does not hold the others up past a 2 s grace.
|
|
67
91
|
|
|
68
92
|
A pack mounted with a content hash — `https://example.com/docs.pikelet#<sha256>` — has a stable identity, so "what body of knowledge did this agent query?" has a reproducible answer. A citation is `(pack identity, record id)`, and it survives updates: a chain of layers resolves citations made against its earlier versions, and a compacted pack translates them forward or reports that the record was deleted. Citation translation is a library call today (`citation(identity, id)`); the MCP tools do not expose it yet.
|
|
69
93
|
|
|
70
|
-
**A mounted pack's content reaches the model as tool output.** `verify_pack`
|
|
94
|
+
**A mounted pack's content reaches the model as tool output.** `verify_pack` reports which of the pack's bytes have been checked against its identity (with `full: true` it also checks a large pack's lexical index whole) and replays the pack's own tests; it does not prove the corpus is trustworthy. Mounting a pack from a source you don't control is the same trust decision as giving an agent any other untrusted-content tool — treat pack text like search results or fetched web pages, not as instructions.
|
|
71
95
|
|
|
72
96
|
**A journal the agent can write (experimental).** Packs are read-only to the model, with one opt-in exception: `--journal <name>` mounts a private pack the agent appends notes to — handoffs, decisions, dead ends, measurements — through `write_note` and `latest`, so a later session, from any vendor, can pick up where the work stands. Notes come back labelled agent-written and unverified. See [the CLI README](packages/pikelet/README.md#a-journal-the-agent-can-write-experimental) and [`docs/agent-journal.md`](docs/agent-journal.md).
|
|
73
97
|
|
|
@@ -88,25 +112,27 @@ npx pikelet append --parent docs.0001.pikelet --remove 412 --out docs.0002.pikel
|
|
|
88
112
|
npx pikelet mcp --pack docs.0002.pikelet
|
|
89
113
|
```
|
|
90
114
|
|
|
91
|
-
On a 20-record test pack with a 24.6 MiB base, deleting a record took a 1.2 KiB layer and replacing one took
|
|
115
|
+
On a 20-record test pack with a 24.6 MiB base, deleting a record took a 1.2 KiB layer and replacing one took 4.3 KiB. Deleting hides a record from search but does not erase it: the older files still hold its bytes, and `get_record` still serves it by id, marked `tombstoned`, so old citations resolve. `compact` writes a new base without it. Mounting the newest layer finds and verifies the rest of the chain, locally or over HTTP, and `#<sha256>` on it pins the whole history. Each layer adds a file to fetch and an index to search, so fold a long chain into a fresh base with `compact`. The format is specified in [`LAYERED_PROFILE.md`](LAYERED_PROFILE.md).
|
|
116
|
+
|
|
117
|
+
## Does the pack answer the question?
|
|
92
118
|
|
|
93
|
-
|
|
119
|
+
A nearest neighbour is not evidence that a corpus answers a question: every query returns *something*. Pikelet does not try to decide for you. Each result carries its `distance`, and each response lists the question's words missing from whichever of the top five passages contains the most of them (`grounding.uncovered`). "How do I keep snapshots forever" against a pack whose snapshot page never mentions keeping them forever comes back with `keep` and `forever` uncovered; the MCP server tells the model to cite only a passage that states the answer.
|
|
94
120
|
|
|
95
|
-
|
|
121
|
+
Earlier releases also shipped a relevance verdict (`matchQuality: strong | weak | none`) fitted at build time. On a 1,377-article Wikipedia pack it called 278 of 512 questions whose answer article was not in the pack `strong`, and agents given the verdict declined unanswerable questions no more often than agents without it: they read the passages either way. So `compile` no longer fits one; packs calibrated by earlier releases keep theirs in the library. [docs/calibration.md](docs/calibration.md#why-the-verdict-was-dropped-2026-11) has the measurements.
|
|
96
122
|
|
|
97
|
-
|
|
123
|
+
None of this is a guarantee that an LLM will never hallucinate.
|
|
98
124
|
|
|
99
125
|
## When it fits, and when it doesn't
|
|
100
126
|
|
|
101
127
|
Pikelet targets `build → publish → query many times → replace on release`, with small layered updates in between. Use it when you want search without operating search infrastructure, search inside a browser, edge worker, or offline tool, a corpus you can hand to someone else, or an agent working against a frozen, versioned body of knowledge.
|
|
102
128
|
|
|
103
|
-
Use a database instead if your corpus has heavy online writes, needs transactional mutation, serves many tenants, or already lives comfortably in one. The remote scan is linear in row count, so the design targets corpora through the low millions of records, not web scale.
|
|
129
|
+
Use a database instead if your corpus has heavy online writes, needs transactional mutation, serves many tenants, or already lives comfortably in one. The remote scan is linear in row count, so the design targets corpora through the low millions of records, not web scale. Text handling is English-first: keyword search keeps only ASCII letters and digits, so accented words are split into fragments and non-Latin words are dropped (see [Limitations](packages/pikelet/README.md#limitations)).
|
|
104
130
|
|
|
105
131
|
It is also not new retrieval research. HNSW is HNSW, BM25 is BM25, HTTP Range is HTTP Range, and the bundled MiniLM-L6 encoder was chosen for being small enough to live inside the file — ArguAna shows a real quality cost from that. The project is about arranging those pieces around one constraint: **the knowledge base itself must be distributable as a file and stay useful without retrieval infrastructure.**
|
|
106
132
|
|
|
107
133
|
## Deeper dives
|
|
108
134
|
|
|
109
|
-
- [How a `.pikelet` query runs](docs/how-a-query-runs.md) — what is inside the file, what a query costs on the wire, integrity checks on the read path, and
|
|
135
|
+
- [How a `.pikelet` query runs](docs/how-a-query-runs.md) — what is inside the file, what a query costs on the wire, integrity checks on the read path, and grounding.
|
|
110
136
|
- [The Wikipedia demonstration](docs/wikipedia-demonstration.md) — the agent transcript, the network table, and what cold processes cost.
|
|
111
137
|
- [The Veyra ablation](docs/veyra-ablation.md) — what happens to answers when the supporting record is edited or removed.
|
|
112
138
|
- [Why make knowledge a file](docs/why-a-file.md) — the reasoning behind the single-artifact design.
|
|
@@ -134,10 +160,12 @@ The **range proof** uses a server that does not understand Pikelet and reports m
|
|
|
134
160
|
|
|
135
161
|
## Status
|
|
136
162
|
|
|
137
|
-
Pikelet is early: the implementation is real, the format is not frozen
|
|
163
|
+
Pikelet is early: the implementation is real, the format is not frozen, and there is one primary author. Prebuilt WASM, local and HTTP readers, the embedded encoder, BM25 hybrid retrieval, content identity with lazy-read verification, query-word grounding, MCP mounting, layered updates, and the experimental journal all ship today. `npm test` runs the engine, artifact-profile, MCP, ingestion, and format-hardening conformance suites.
|
|
138
164
|
|
|
139
165
|
Previously known as **Pancake** (renamed September 2026); files from before the rename remain readable — see [`docs/history.md`](docs/history.md). Pikelet is unrelated to the Pikelet programming language.
|
|
140
166
|
|
|
141
167
|
## License
|
|
142
168
|
|
|
143
169
|
Apache-2.0. See [LICENSE](LICENSE).
|
|
170
|
+
|
|
171
|
+
Every `.pikelet` carries its query encoder, so a pack redistributes the all-MiniLM-L6-v2 weights (quantized) and the BERT WordPiece vocabulary, both Apache-2.0. [NOTICE](NOTICE) credits them; keep it with packs you publish.
|
|
@@ -1,23 +1,46 @@
|
|
|
1
|
-
// A disk store for openPikeletFile's options.blobCache:
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
1
|
+
// A disk store for openPikeletFile's options.blobCache: bytes a pack commits
|
|
2
|
+
// to by sha256, filed under that digest. Two kinds of entry reach it:
|
|
3
|
+
//
|
|
4
|
+
// - whole regions read at mount (the sketch's resident prefix, the
|
|
5
|
+
// query-interp segment holding the encoder): most of what a URL mount
|
|
6
|
+
// downloads, about 71 of 77 MiB on the 649 MiB Simple English Wikipedia
|
|
7
|
+
// pack. One file each.
|
|
8
|
+
// - pieces read per query (rerank vector rows, corpus records, and the
|
|
9
|
+
// digest pages that verify them): a few hundred bytes to a few KiB, and
|
|
10
|
+
// hundreds per query. One file each would be a poor fit, so entries under
|
|
11
|
+
// SMALL_ENTRY_BYTES go into append-only log files (generations) with an
|
|
12
|
+
// in-memory index, and whole generations rotate out under their own
|
|
13
|
+
// budget.
|
|
7
14
|
//
|
|
8
15
|
// The store is untrusted by design: the reader hashes every hit against the
|
|
9
16
|
// digest it asked for and treats a mismatch as a miss (blobCacheGet in
|
|
10
|
-
// pikelet-artifact-common.js), so a torn write
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
// entries (by mtime, touched on every hit) after each write.
|
|
17
|
+
// pikelet-artifact-common.js), so a torn write, a corrupted file, or two
|
|
18
|
+
// processes appending to one log at once costs a refetch, never a wrong byte.
|
|
19
|
+
// Entries are immutable and never go stale; the only policy is size.
|
|
14
20
|
|
|
15
21
|
import fs from 'node:fs/promises';
|
|
16
22
|
import os from 'node:os';
|
|
17
23
|
import path from 'node:path';
|
|
18
24
|
|
|
19
|
-
|
|
25
|
+
// A full sha256, or a truncated one of at least 128 bits (sketch row digests
|
|
26
|
+
// may be 16-32 bytes).
|
|
27
|
+
const KEY = /^(?:[0-9a-f]{2}){16,32}$/;
|
|
20
28
|
export const DEFAULT_BLOB_CACHE_BYTES = 2 * 1024 * 1024 * 1024;
|
|
29
|
+
export const DEFAULT_SMALL_CACHE_BYTES = 64 * 1024 * 1024;
|
|
30
|
+
// Entries below this go to the log; at or above it, a file of their own.
|
|
31
|
+
export const SMALL_ENTRY_BYTES = 64 * 1024;
|
|
32
|
+
// The log keeps this many generations; the oldest is deleted whole when the
|
|
33
|
+
// newest fills (smallMaxBytes / GENERATIONS each).
|
|
34
|
+
const GENERATIONS = 4;
|
|
35
|
+
// Log record: magic 'PKB1' (u32 LE), key length (u8), key bytes, data length
|
|
36
|
+
// (u32 LE), data. A scan stops at the first record that does not parse.
|
|
37
|
+
const RECORD_MAGIC = 0x3142_4b50;
|
|
38
|
+
const GEN_FILE = /^gen-(\d{8})\.log$/;
|
|
39
|
+
// Entries are pack content, record text included, and a pack can be a
|
|
40
|
+
// private repository or a conversation history: the store is private to its
|
|
41
|
+
// owner whatever the umask.
|
|
42
|
+
const DIR_MODE = 0o700;
|
|
43
|
+
const FILE_MODE = 0o600;
|
|
21
44
|
|
|
22
45
|
// $PIKELET_CACHE_DIR, else $XDG_CACHE_HOME/pikelet/blobs, else
|
|
23
46
|
// ~/.cache/pikelet/blobs: the same root the CLI already caches encoder
|
|
@@ -28,15 +51,28 @@ export function defaultBlobCacheDir(env = process.env) {
|
|
|
28
51
|
return path.join(base, 'pikelet', 'blobs');
|
|
29
52
|
}
|
|
30
53
|
|
|
31
|
-
export function diskBlobCache(dir = defaultBlobCacheDir(), { maxBytes = DEFAULT_BLOB_CACHE_BYTES } = {}) {
|
|
32
|
-
|
|
33
|
-
|
|
54
|
+
export function diskBlobCache(dir = defaultBlobCacheDir(), { maxBytes = DEFAULT_BLOB_CACHE_BYTES, smallMaxBytes = DEFAULT_SMALL_CACHE_BYTES } = {}) {
|
|
55
|
+
for (const [label, value] of [['maxBytes', maxBytes], ['smallMaxBytes', smallMaxBytes]]) {
|
|
56
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
57
|
+
throw new Error(`diskBlobCache ${label} must be a non-negative integer`);
|
|
58
|
+
}
|
|
34
59
|
}
|
|
35
60
|
const root = path.resolve(dir);
|
|
36
|
-
const
|
|
37
|
-
if (
|
|
38
|
-
|
|
61
|
+
const checkKey = (key) => {
|
|
62
|
+
if (typeof key !== 'string' || !KEY.test(key)) {
|
|
63
|
+
throw new Error(`blob cache key must be a lowercase sha256 hex digest (32-64 hex digits), got ${JSON.stringify(key)}`);
|
|
64
|
+
}
|
|
65
|
+
return key;
|
|
39
66
|
};
|
|
67
|
+
const fileOf = (key) => path.join(root, key.slice(0, 2), checkKey(key));
|
|
68
|
+
// Once per instance, before the first write: a root made by an older
|
|
69
|
+
// store (or by mkdir -p under umask 022) is tightened, which also closes
|
|
70
|
+
// off whatever it already holds. Best effort; on Windows modes are moot.
|
|
71
|
+
let privateRoot = null;
|
|
72
|
+
const makeRootPrivate = () => (privateRoot ??= (async () => {
|
|
73
|
+
await fs.mkdir(root, { recursive: true, mode: DIR_MODE });
|
|
74
|
+
await fs.chmod(root, DIR_MODE).catch(() => {});
|
|
75
|
+
})());
|
|
40
76
|
const pending = new Set();
|
|
41
77
|
const track = (promise) => {
|
|
42
78
|
pending.add(promise);
|
|
@@ -48,6 +84,7 @@ export function diskBlobCache(dir = defaultBlobCacheDir(), { maxBytes = DEFAULT_
|
|
|
48
84
|
const entries = [];
|
|
49
85
|
let total = 0;
|
|
50
86
|
for (const shard of await fs.readdir(root).catch(() => [])) {
|
|
87
|
+
if (shard === 'small') continue;
|
|
51
88
|
const shardDir = path.join(root, shard);
|
|
52
89
|
for (const name of await fs.readdir(shardDir).catch(() => [])) {
|
|
53
90
|
if (!KEY.test(name)) continue;
|
|
@@ -67,9 +104,178 @@ export function diskBlobCache(dir = defaultBlobCacheDir(), { maxBytes = DEFAULT_
|
|
|
67
104
|
}
|
|
68
105
|
};
|
|
69
106
|
|
|
107
|
+
// --- the small-entry log -------------------------------------------------
|
|
108
|
+
const smallDir = path.join(root, 'small');
|
|
109
|
+
const genBytes = Math.max(1, Math.floor(smallMaxBytes / GENERATIONS));
|
|
110
|
+
const genPath = (gen) => path.join(smallDir, `gen-${String(gen).padStart(8, '0')}.log`);
|
|
111
|
+
const index = new Map(); // key -> { gen, offset, length }
|
|
112
|
+
const handles = new Map(); // gen -> Promise<FileHandle> (read)
|
|
113
|
+
let current = 0;
|
|
114
|
+
// Set when the newest generation ends in bytes that do not parse (a torn
|
|
115
|
+
// write): a scan stops there, so anything appended after it would never
|
|
116
|
+
// be indexed again. Writing resumes in a fresh generation instead.
|
|
117
|
+
let sealed = false;
|
|
118
|
+
let queue = [];
|
|
119
|
+
let flushing = null;
|
|
120
|
+
|
|
121
|
+
const listGens = async () => (await fs.readdir(smallDir).catch(() => []))
|
|
122
|
+
.map((name) => GEN_FILE.exec(name)).filter(Boolean).map((m) => Number(m[1])).sort((a, b) => a - b);
|
|
123
|
+
|
|
124
|
+
const forgetGen = async (gen) => {
|
|
125
|
+
for (const [key, at] of index) if (at.gen === gen) index.delete(key);
|
|
126
|
+
const handle = handles.get(gen);
|
|
127
|
+
handles.delete(gen);
|
|
128
|
+
if (handle) await handle.then((h) => h.close(), () => {});
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const scan = (gen, bytes) => {
|
|
132
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
133
|
+
let at = 0;
|
|
134
|
+
while (at + 9 <= bytes.length && view.getUint32(at, true) === RECORD_MAGIC) {
|
|
135
|
+
const keyLen = bytes[at + 4];
|
|
136
|
+
if (keyLen < 16 || keyLen > 32 || at + 5 + keyLen + 4 > bytes.length) break;
|
|
137
|
+
const key = Buffer.from(bytes.subarray(at + 5, at + 5 + keyLen)).toString('hex');
|
|
138
|
+
const length = view.getUint32(at + 5 + keyLen, true);
|
|
139
|
+
const offset = at + 9 + keyLen;
|
|
140
|
+
if (offset + length > bytes.length) break;
|
|
141
|
+
index.set(key, { gen, offset, length });
|
|
142
|
+
at = offset + length;
|
|
143
|
+
}
|
|
144
|
+
return at === bytes.length;
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
// Built once, on first use: every generation still on disk is read and
|
|
148
|
+
// indexed (at most smallMaxBytes), later generations overriding earlier.
|
|
149
|
+
let ready = null;
|
|
150
|
+
const smallReady = () => (ready ??= (async () => {
|
|
151
|
+
if (smallMaxBytes === 0) return;
|
|
152
|
+
const gens = await listGens();
|
|
153
|
+
for (const gen of gens.slice(0, Math.max(0, gens.length - GENERATIONS))) {
|
|
154
|
+
await fs.rm(genPath(gen), { force: true });
|
|
155
|
+
}
|
|
156
|
+
for (const gen of gens.slice(-GENERATIONS)) {
|
|
157
|
+
const bytes = await fs.readFile(genPath(gen)).catch(() => null);
|
|
158
|
+
const whole = bytes ? scan(gen, bytes) : true;
|
|
159
|
+
if (gen === gens[gens.length - 1]) sealed = !whole;
|
|
160
|
+
}
|
|
161
|
+
current = gens.length ? gens[gens.length - 1] : 0;
|
|
162
|
+
})());
|
|
163
|
+
|
|
164
|
+
const readSmall = async (key) => {
|
|
165
|
+
const at = index.get(key);
|
|
166
|
+
if (!at) return null;
|
|
167
|
+
let handle = handles.get(at.gen);
|
|
168
|
+
if (!handle) {
|
|
169
|
+
handle = fs.open(genPath(at.gen), 'r');
|
|
170
|
+
handles.set(at.gen, handle);
|
|
171
|
+
handle.catch(() => { if (handles.get(at.gen) === handle) handles.delete(at.gen); });
|
|
172
|
+
}
|
|
173
|
+
let fh;
|
|
174
|
+
try { fh = await handle; } catch (err) {
|
|
175
|
+
// Another process rotated this generation away.
|
|
176
|
+
if (err?.code === 'ENOENT') { await forgetGen(at.gen); return null; }
|
|
177
|
+
throw err;
|
|
178
|
+
}
|
|
179
|
+
const out = new Uint8Array(at.length);
|
|
180
|
+
const { bytesRead } = await fh.read(out, 0, at.length, at.offset);
|
|
181
|
+
if (bytesRead !== at.length) { index.delete(key); return null; }
|
|
182
|
+
// A hit from an older generation is written again to the newest, so
|
|
183
|
+
// rotation drops what has not been read lately: LRU by generation.
|
|
184
|
+
if (at.gen !== current) enqueue(key, out);
|
|
185
|
+
return out;
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
const rotate = async () => {
|
|
189
|
+
await makeRootPrivate();
|
|
190
|
+
await fs.mkdir(smallDir, { recursive: true, mode: DIR_MODE });
|
|
191
|
+
const gens = await listGens();
|
|
192
|
+
current = Math.max(current, gens.length ? gens[gens.length - 1] : 0) + 1;
|
|
193
|
+
// Exclusive create; another process that rotated first owns the
|
|
194
|
+
// name, and appending after its records is fine.
|
|
195
|
+
await fs.writeFile(genPath(current), new Uint8Array(0), { flag: 'wx', mode: FILE_MODE }).catch((err) => {
|
|
196
|
+
if (err?.code !== 'EEXIST') throw err;
|
|
197
|
+
});
|
|
198
|
+
for (const gen of (await listGens()).filter((g) => g <= current - GENERATIONS)) {
|
|
199
|
+
await forgetGen(gen);
|
|
200
|
+
await fs.rm(genPath(gen), { force: true });
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
const flushSmall = async () => {
|
|
205
|
+
while (queue.length) {
|
|
206
|
+
const batch = queue;
|
|
207
|
+
queue = [];
|
|
208
|
+
const total = batch.reduce((n, r) => n + r.record.length, 0);
|
|
209
|
+
if (!current || sealed) {
|
|
210
|
+
await rotate();
|
|
211
|
+
sealed = false;
|
|
212
|
+
} else {
|
|
213
|
+
const st = await fs.stat(genPath(current)).catch(() => null);
|
|
214
|
+
if (!st || st.size + total > genBytes) await rotate();
|
|
215
|
+
}
|
|
216
|
+
const buf = Buffer.concat(batch.map((r) => r.record));
|
|
217
|
+
const fh = await fs.open(genPath(current), 'a+', FILE_MODE);
|
|
218
|
+
let base;
|
|
219
|
+
try {
|
|
220
|
+
await fh.write(buf);
|
|
221
|
+
// O_APPEND puts the batch at the end; its offset is the size
|
|
222
|
+
// now minus its length, unless another process appended
|
|
223
|
+
// between the write and the stat. So the batch is read back
|
|
224
|
+
// there before it is indexed: records are content-addressed,
|
|
225
|
+
// so wherever these exact bytes sit is a right offset.
|
|
226
|
+
base = (await fh.stat()).size - buf.length;
|
|
227
|
+
if (base >= 0) {
|
|
228
|
+
const back = Buffer.alloc(buf.length);
|
|
229
|
+
const { bytesRead } = await fh.read(back, 0, buf.length, base);
|
|
230
|
+
if (bytesRead !== buf.length || !back.equals(buf)) base = -1;
|
|
231
|
+
}
|
|
232
|
+
} finally {
|
|
233
|
+
await fh.close();
|
|
234
|
+
}
|
|
235
|
+
if (base < 0) {
|
|
236
|
+
// The end moved: find where the batch landed by scanning the
|
|
237
|
+
// generation, which indexes the other writer's records too.
|
|
238
|
+
// A record still being written stops the scan; whatever lies
|
|
239
|
+
// past it is a miss, not a wrong offset.
|
|
240
|
+
const bytes = await fs.readFile(genPath(current)).catch(() => null);
|
|
241
|
+
if (bytes) scan(current, bytes);
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
let at = base;
|
|
245
|
+
for (const r of batch) {
|
|
246
|
+
index.set(r.key, { gen: current, offset: at + r.headerBytes, length: r.length });
|
|
247
|
+
at += r.record.length;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
const enqueue = (key, bytes) => {
|
|
253
|
+
if (index.has(key) && index.get(key).gen === current) return;
|
|
254
|
+
const raw = Buffer.from(key, 'hex');
|
|
255
|
+
const headerBytes = 9 + raw.length;
|
|
256
|
+
const record = Buffer.alloc(headerBytes + bytes.byteLength);
|
|
257
|
+
record.writeUInt32LE(RECORD_MAGIC, 0);
|
|
258
|
+
record[4] = raw.length;
|
|
259
|
+
raw.copy(record, 5);
|
|
260
|
+
record.writeUInt32LE(bytes.byteLength, 5 + raw.length);
|
|
261
|
+
record.set(bytes, headerBytes);
|
|
262
|
+
queue.push({ key, record, headerBytes, length: bytes.byteLength });
|
|
263
|
+
// One append per burst: a query stores hundreds of rows at once.
|
|
264
|
+
flushing ??= track(new Promise((resolve) => setImmediate(resolve))
|
|
265
|
+
.then(() => flushSmall())
|
|
266
|
+
.finally(() => { flushing = null; }));
|
|
267
|
+
return flushing;
|
|
268
|
+
};
|
|
269
|
+
|
|
70
270
|
return {
|
|
71
271
|
dir: root,
|
|
72
272
|
async get(key) {
|
|
273
|
+
checkKey(key);
|
|
274
|
+
if (smallMaxBytes > 0) {
|
|
275
|
+
await smallReady();
|
|
276
|
+
const small = await readSmall(key);
|
|
277
|
+
if (small) return small;
|
|
278
|
+
}
|
|
73
279
|
const file = fileOf(key);
|
|
74
280
|
let bytes;
|
|
75
281
|
try { bytes = await fs.readFile(file); } catch (err) {
|
|
@@ -82,15 +288,21 @@ export function diskBlobCache(dir = defaultBlobCacheDir(), { maxBytes = DEFAULT_
|
|
|
82
288
|
return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
83
289
|
},
|
|
84
290
|
put(key, bytes) {
|
|
291
|
+
checkKey(key);
|
|
292
|
+
if (bytes.byteLength < SMALL_ENTRY_BYTES) {
|
|
293
|
+
if (smallMaxBytes === 0 || bytes.byteLength > genBytes) return Promise.resolve();
|
|
294
|
+
return track(smallReady().then(() => enqueue(key, bytes)));
|
|
295
|
+
}
|
|
85
296
|
const file = fileOf(key);
|
|
86
297
|
return track((async () => {
|
|
87
298
|
if (bytes.byteLength > maxBytes) return;
|
|
88
|
-
await
|
|
299
|
+
await makeRootPrivate();
|
|
300
|
+
await fs.mkdir(path.dirname(file), { recursive: true, mode: DIR_MODE });
|
|
89
301
|
// Write-then-rename, so a reader in another process sees
|
|
90
302
|
// either no entry or a whole one.
|
|
91
303
|
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
92
304
|
try {
|
|
93
|
-
await fs.writeFile(tmp, bytes);
|
|
305
|
+
await fs.writeFile(tmp, bytes, { mode: FILE_MODE });
|
|
94
306
|
await fs.rename(tmp, file);
|
|
95
307
|
} catch (err) {
|
|
96
308
|
await fs.rm(tmp, { force: true });
|
|
@@ -100,6 +312,10 @@ export function diskBlobCache(dir = defaultBlobCacheDir(), { maxBytes = DEFAULT_
|
|
|
100
312
|
})());
|
|
101
313
|
},
|
|
102
314
|
async delete(key) {
|
|
315
|
+
checkKey(key);
|
|
316
|
+
// A log entry cannot be removed in place; forgetting it is enough,
|
|
317
|
+
// and rotation reclaims the bytes.
|
|
318
|
+
index.delete(key);
|
|
103
319
|
await fs.rm(fileOf(key), { force: true });
|
|
104
320
|
},
|
|
105
321
|
// Settles every write started so far: for tests, and for a process
|
|
@@ -107,5 +323,15 @@ export function diskBlobCache(dir = defaultBlobCacheDir(), { maxBytes = DEFAULT_
|
|
|
107
323
|
async flush() {
|
|
108
324
|
while (pending.size) await Promise.allSettled([...pending]);
|
|
109
325
|
},
|
|
326
|
+
// Closes the log's read handles (they otherwise live as long as the
|
|
327
|
+
// process). The store stays usable; handles reopen on demand.
|
|
328
|
+
async close() {
|
|
329
|
+
await this.flush();
|
|
330
|
+
for (const gen of [...handles.keys()]) {
|
|
331
|
+
const handle = handles.get(gen);
|
|
332
|
+
handles.delete(gen);
|
|
333
|
+
await handle.then((h) => h.close(), () => {});
|
|
334
|
+
}
|
|
335
|
+
},
|
|
110
336
|
};
|
|
111
337
|
}
|