@factoidal/core 0.5.1 → 0.6.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 +132 -0
- package/README.md +180 -16
- package/bin/ext.mjs +198 -0
- package/bin/factoidal.mjs +62 -4
- package/bin/pack-host.mjs +19 -1
- package/bin/store-worker-host.mjs +397 -0
- package/bin/store-worker.mjs +100 -0
- package/bin/store.mjs +29 -9
- package/l4-assets/l4factoidal.js +1 -1
- package/l4-assets/l4factoidal.mjs +1 -1
- package/l4-assets/l4factoidal.wasm +0 -0
- package/l4-assets/version.json +4 -4
- package/package.json +4 -1
- package/version.json +1 -1
package/bin/pack-host.mjs
CHANGED
|
@@ -46,7 +46,7 @@ import { StoreHostError, listGeneration, readWhole } from '../store-host/index.m
|
|
|
46
46
|
import { fileUrlToPath, joinPath } from '../store-host/paths.mjs'
|
|
47
47
|
import { loadEngine } from './engine.mjs'
|
|
48
48
|
import { PackError, packFile, packSupported, verifyGeneration } from './pack.mjs'
|
|
49
|
-
import { openStore } from './store.mjs'
|
|
49
|
+
import { StoreOperationError, openStore } from './store.mjs'
|
|
50
50
|
|
|
51
51
|
const isDeno = typeof globalThis.Deno !== 'undefined'
|
|
52
52
|
|
|
@@ -144,6 +144,16 @@ export function describeError (error) {
|
|
|
144
144
|
path: error.path === undefined ? null : error.path
|
|
145
145
|
}
|
|
146
146
|
}
|
|
147
|
+
if (error instanceof StoreOperationError) {
|
|
148
|
+
return {
|
|
149
|
+
type: 'StoreOperationError',
|
|
150
|
+
message: error.message,
|
|
151
|
+
capValue: error.capValue,
|
|
152
|
+
capLimit: error.capLimit,
|
|
153
|
+
digestKey: error.digestKey,
|
|
154
|
+
stackLimit: error.stackLimit
|
|
155
|
+
}
|
|
156
|
+
}
|
|
147
157
|
return {
|
|
148
158
|
type: 'Error',
|
|
149
159
|
message: error && error.message ? String(error.message) : String(error)
|
|
@@ -160,6 +170,14 @@ export function reviveError (description) {
|
|
|
160
170
|
const detail = description.path === null ? {} : { path: description.path }
|
|
161
171
|
return new StoreHostError(description.code, description.message, detail)
|
|
162
172
|
}
|
|
173
|
+
if (description.type === 'StoreOperationError') {
|
|
174
|
+
return new StoreOperationError(description.message, {
|
|
175
|
+
capValue: description.capValue === null ? undefined : description.capValue,
|
|
176
|
+
capLimit: description.capLimit === null ? undefined : description.capLimit,
|
|
177
|
+
digestKey: description.digestKey === null ? undefined : description.digestKey,
|
|
178
|
+
stackLimit: description.stackLimit
|
|
179
|
+
})
|
|
180
|
+
}
|
|
163
181
|
return new Error(description.message)
|
|
164
182
|
}
|
|
165
183
|
|
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
// Giving the store operations a call stack big enough to finish, without
|
|
2
|
+
// asking the reader for a runtime flag.
|
|
3
|
+
// https://github.com/danbri/factoidal/issues/653
|
|
4
|
+
//
|
|
5
|
+
// THE DEFECT THIS FILE EXISTS FOR
|
|
6
|
+
// Several engine paths recurse once per manifest entry or once per row.
|
|
7
|
+
// On a large generation that exceeds the default call stack of Node and
|
|
8
|
+
// of Deno, and the failure is `Maximum call stack size exceeded` rather
|
|
9
|
+
// than an engine refusal. MEASURED 2026-09-05 against the committed
|
|
10
|
+
// module, on a 7,315,251-quad collection of 3,286 blocks in 204 graphs
|
|
11
|
+
// (`/Users/danbri/working/factoidal-skosfull`): `storeQueryPlan` alone
|
|
12
|
+
// overflows on plain `node`, before a single artifact byte is read, and
|
|
13
|
+
// `node --stack-size=60000` clears the plan, the open and every query.
|
|
14
|
+
// Earlier the same limit was narrowed to any query that materialises
|
|
15
|
+
// about 14,576 rows or more, whatever it returns.
|
|
16
|
+
//
|
|
17
|
+
// `factoidal pack` had the same defect and it was solved host-side, on a
|
|
18
|
+
// worker thread with a raised stack (`bin/pack-host.mjs`,
|
|
19
|
+
// https://github.com/danbri/factoidal/issues/649). This file carries that
|
|
20
|
+
// route to the store operations.
|
|
21
|
+
//
|
|
22
|
+
// WHY THE HANDLE ITSELF LIVES IN THE WORKER
|
|
23
|
+
// A handle is STATE INSIDE THE WASM INSTANCE -- the verified, decoded,
|
|
24
|
+
// indexed blocks that `storeOpen` retained. A WebAssembly instance does
|
|
25
|
+
// not cross a thread boundary, so a handle opened on the main thread
|
|
26
|
+
// cannot be queried from a worker, and the reverse. Only two designs are
|
|
27
|
+
// available:
|
|
28
|
+
//
|
|
29
|
+
// (a) the handle lives in the worker, and `query()` and `close()` are
|
|
30
|
+
// messages to it;
|
|
31
|
+
// (b) each query spawns a worker, which re-reads and re-decodes every
|
|
32
|
+
// artifact.
|
|
33
|
+
//
|
|
34
|
+
// (b) destroys the reason a handle exists: `storeOpen` is the expensive
|
|
35
|
+
// call (5.4 s against the collection above, where a query is 0.6 s), and
|
|
36
|
+
// paying it per query is worse than the stateless `queryStore` path. So
|
|
37
|
+
// (a) is what this file implements.
|
|
38
|
+
//
|
|
39
|
+
// THE COST OF (a), STATED
|
|
40
|
+
// - One worker thread per SESSION, not per handle. A session holds one
|
|
41
|
+
// engine and as many handles as the engine's own handle cap allows,
|
|
42
|
+
// so a caller that opens several stores pays for one thread and one
|
|
43
|
+
// copy of the module. `openStoreHandleOnWorker` uses a shared session
|
|
44
|
+
// by default; `{ownWorker: true}` gives a handle its own thread, and
|
|
45
|
+
// its own copy of the 5.6 MB module, when a caller wants failure
|
|
46
|
+
// isolation between stores.
|
|
47
|
+
// - Every call is ASYNCHRONOUS, where the in-process handle is
|
|
48
|
+
// synchronous. A message round trip is the price of the bigger stack.
|
|
49
|
+
// - An extension function registered on the MAIN thread's engine
|
|
50
|
+
// (`bin/ext.mjs`) is not visible to the worker's engine. Register it
|
|
51
|
+
// inside the worker, or use the in-process handle.
|
|
52
|
+
// - The worker keeps the process alive until `close()` or
|
|
53
|
+
// `terminate()`. `unref()` is not used: a server that dropped its
|
|
54
|
+
// last reference would otherwise lose its store silently.
|
|
55
|
+
//
|
|
56
|
+
// WHAT A ONE-SHOT QUERY DOES INSTEAD
|
|
57
|
+
// A single `factoidal query` builds no handle and drops whatever it
|
|
58
|
+
// loads, so a worker is measured overhead it cannot amortise. It runs
|
|
59
|
+
// IN PROCESS, and only when the runtime runs out of frames does it retry
|
|
60
|
+
// once on a worker (`queryStoreOnWorker`). The normal case pays nothing.
|
|
61
|
+
|
|
62
|
+
import { loadEngine } from './engine.mjs'
|
|
63
|
+
import {
|
|
64
|
+
WORKER_STACK_MB, isStackOverflow, reviveError, workerRefused, workerStackMb
|
|
65
|
+
} from './pack-host.mjs'
|
|
66
|
+
import {
|
|
67
|
+
StoreOperationError, openStore, openStoreHandle, planQuery, queryStore
|
|
68
|
+
} from './store.mjs'
|
|
69
|
+
|
|
70
|
+
const isDeno = typeof globalThis.Deno !== 'undefined'
|
|
71
|
+
|
|
72
|
+
export { WORKER_STACK_MB, isStackOverflow, workerRefused, workerStackMb }
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Whether this runtime has the `worker_threads` route at all.
|
|
76
|
+
*
|
|
77
|
+
* Deno has a `node:worker_threads` shim, and it accepts
|
|
78
|
+
* `resourceLimits.stackSizeMb` and does almost nothing with it. MEASURED
|
|
79
|
+
* 2026-09-05, deno 2.9.4 / V8 15.0.245.2 against Node 22.22.2, by
|
|
80
|
+
* counting frames to the overflow inside the worker:
|
|
81
|
+
*
|
|
82
|
+
* runtime default stackSizeMb 64
|
|
83
|
+
* node 41,195 696,555
|
|
84
|
+
* deno 10,835 13,837
|
|
85
|
+
*
|
|
86
|
+
* A 1.28-times raise does not carry a store open that needs sixteen
|
|
87
|
+
* times the default, so Deno takes the re-exec route in
|
|
88
|
+
* `bin/pack-host.mjs` instead: the command runs itself again once with
|
|
89
|
+
* `--v8-flags=--stack-size=...`, which needs --allow-run and --allow-env.
|
|
90
|
+
* A Deno LIBRARY caller cannot re-execute its own host, so
|
|
91
|
+
* `openStoreHandleOnWorker` gives it an in-process handle behind the same
|
|
92
|
+
* asynchronous interface, and the process must be started with
|
|
93
|
+
* deno run --allow-read --v8-flags=--stack-size=65536
|
|
94
|
+
*/
|
|
95
|
+
export function workerRouteAvailable () {
|
|
96
|
+
return !isDeno
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ------------------------------------------------------------- a session
|
|
100
|
+
//
|
|
101
|
+
// One worker thread, one engine, many handles.
|
|
102
|
+
|
|
103
|
+
let nextRequestId = 1
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* A worker thread holding one engine and the handles opened through it.
|
|
107
|
+
*
|
|
108
|
+
* Hold one of these for as long as a process answers questions about a
|
|
109
|
+
* store. `terminate()` drops the thread and everything in it.
|
|
110
|
+
*/
|
|
111
|
+
export class StoreWorkerSession {
|
|
112
|
+
constructor (worker) {
|
|
113
|
+
this.worker = worker
|
|
114
|
+
this.pending = new Map()
|
|
115
|
+
this.dead = null
|
|
116
|
+
this.handles = new Set()
|
|
117
|
+
worker.on('message', (message) => {
|
|
118
|
+
const waiting = this.pending.get(message.id)
|
|
119
|
+
if (waiting === undefined) return
|
|
120
|
+
this.pending.delete(message.id)
|
|
121
|
+
if (message.kind === 'error') waiting.reject(reviveError(message.error))
|
|
122
|
+
else waiting.resolve(message.answer)
|
|
123
|
+
})
|
|
124
|
+
worker.on('error', (error) => { this.fail(error) })
|
|
125
|
+
worker.on('exit', (code) => {
|
|
126
|
+
this.fail(new StoreOperationError(
|
|
127
|
+
`the store worker exited with code ${code}`))
|
|
128
|
+
})
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Fail every outstanding request and refuse every later one. */
|
|
132
|
+
fail (error) {
|
|
133
|
+
if (this.dead === null) this.dead = error
|
|
134
|
+
for (const waiting of this.pending.values()) waiting.reject(error)
|
|
135
|
+
this.pending.clear()
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Send one request and await its answer. */
|
|
139
|
+
send (request) {
|
|
140
|
+
if (this.dead !== null) return Promise.reject(this.dead)
|
|
141
|
+
const id = nextRequestId
|
|
142
|
+
nextRequestId += 1
|
|
143
|
+
return new Promise((resolve, reject) => {
|
|
144
|
+
this.pending.set(id, { resolve, reject })
|
|
145
|
+
this.worker.postMessage({ ...request, id })
|
|
146
|
+
})
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Open one store handle inside this session's worker.
|
|
151
|
+
*
|
|
152
|
+
* @param {string} root the collection root that holds CURRENT
|
|
153
|
+
* @param {{generation?: string, keys?: string[], sparql?: string}} options
|
|
154
|
+
* the same options `openStoreHandle` takes, plus `generation` to open
|
|
155
|
+
* a generation that has not been activated
|
|
156
|
+
* @returns {Promise<WorkerStoreHandle>}
|
|
157
|
+
*/
|
|
158
|
+
async open (root, options = {}) {
|
|
159
|
+
const envelope = await this.send({
|
|
160
|
+
kind: 'open',
|
|
161
|
+
root,
|
|
162
|
+
generation: typeof options.generation === 'string' ? options.generation : null,
|
|
163
|
+
keys: Array.isArray(options.keys) ? options.keys : null,
|
|
164
|
+
sparql: typeof options.sparql === 'string' ? options.sparql : null
|
|
165
|
+
})
|
|
166
|
+
const handle = new WorkerStoreHandle(this, envelope)
|
|
167
|
+
this.handles.add(handle)
|
|
168
|
+
return handle
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** `storeHandleList` from inside the worker: what this session holds. */
|
|
172
|
+
async list () {
|
|
173
|
+
return (await this.send({ kind: 'list' })).list
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Stop the thread. Every handle it held is gone with it. */
|
|
177
|
+
async terminate () {
|
|
178
|
+
if (this.dead === null) this.dead = new StoreOperationError(
|
|
179
|
+
'this store worker session is terminated')
|
|
180
|
+
for (const handle of this.handles) handle.closed = true
|
|
181
|
+
this.handles.clear()
|
|
182
|
+
await this.worker.terminate()
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* A store handle held inside a worker thread.
|
|
188
|
+
*
|
|
189
|
+
* The same envelope fields as the in-process `StoreHandle`, and the same
|
|
190
|
+
* two methods, except that both are asynchronous. The wasm module is
|
|
191
|
+
* single-threaded, so two `query()` calls on one session are served in
|
|
192
|
+
* the order they were sent.
|
|
193
|
+
*/
|
|
194
|
+
export class WorkerStoreHandle {
|
|
195
|
+
constructor (session, envelope) {
|
|
196
|
+
this.session = session
|
|
197
|
+
this.handle = envelope.handle
|
|
198
|
+
this.identity = envelope.identity
|
|
199
|
+
this.layout = envelope.layout
|
|
200
|
+
this.wireVersion = envelope.wireVersion
|
|
201
|
+
this.artifacts = envelope.artifacts
|
|
202
|
+
this.bytes = envelope.bytes
|
|
203
|
+
this.rows = envelope.rows
|
|
204
|
+
this.closed = false
|
|
205
|
+
// Set when this handle owns its session, so `close()` stops the thread.
|
|
206
|
+
this.ownSession = false
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** One SPARQL query against the retained blocks. The envelope is the
|
|
210
|
+
* one the in-process handle answers with. */
|
|
211
|
+
async query (sparql) {
|
|
212
|
+
if (this.closed) {
|
|
213
|
+
throw new StoreOperationError(`store handle ${this.handle} is closed`)
|
|
214
|
+
}
|
|
215
|
+
return (await this.session.send({
|
|
216
|
+
kind: 'query', handle: this.handle, sparql
|
|
217
|
+
})).result
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Drop the handle and everything it retained. Idempotent. */
|
|
221
|
+
async close () {
|
|
222
|
+
if (this.closed) return
|
|
223
|
+
this.closed = true
|
|
224
|
+
this.session.handles.delete(this)
|
|
225
|
+
if (this.ownSession) {
|
|
226
|
+
await this.session.terminate()
|
|
227
|
+
return
|
|
228
|
+
}
|
|
229
|
+
if (this.session.dead !== null) return
|
|
230
|
+
await this.session.send({ kind: 'close', handle: this.handle })
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// ------------------------------------------------------- starting one
|
|
235
|
+
|
|
236
|
+
/** Start a worker thread with a stack big enough for the store paths. */
|
|
237
|
+
async function startWorker () {
|
|
238
|
+
if (!workerRouteAvailable()) {
|
|
239
|
+
throw new StoreOperationError(
|
|
240
|
+
'this runtime has no worker_threads route for the store operations; ' +
|
|
241
|
+
'raise the call stack itself instead')
|
|
242
|
+
}
|
|
243
|
+
const { Worker } = await import('node:worker_threads')
|
|
244
|
+
const entry = new URL('./store-worker.mjs', import.meta.url)
|
|
245
|
+
const worker = new Worker(entry, {
|
|
246
|
+
resourceLimits: { stackSizeMb: workerStackMb() }
|
|
247
|
+
})
|
|
248
|
+
const session = new StoreWorkerSession(worker)
|
|
249
|
+
// Load the engine now, so the first query measures the query.
|
|
250
|
+
await session.send({ kind: 'warm' })
|
|
251
|
+
return session
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Start a session of this session's own. */
|
|
255
|
+
export async function openStoreWorkerSession () {
|
|
256
|
+
return await startWorker()
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
let sharedSession = null
|
|
260
|
+
|
|
261
|
+
/** The session `openStoreHandleOnWorker` uses when the caller names none:
|
|
262
|
+
* one thread, one engine, shared by every handle in the process. */
|
|
263
|
+
export async function sharedStoreWorkerSession () {
|
|
264
|
+
if (sharedSession === null) sharedSession = startWorker()
|
|
265
|
+
try {
|
|
266
|
+
return await sharedSession
|
|
267
|
+
} catch (error) {
|
|
268
|
+
sharedSession = null
|
|
269
|
+
throw error
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Stop the shared session, if one was started. */
|
|
274
|
+
export async function closeSharedStoreWorkerSession () {
|
|
275
|
+
if (sharedSession === null) return
|
|
276
|
+
const session = sharedSession
|
|
277
|
+
sharedSession = null
|
|
278
|
+
await (await session).terminate()
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Open one store handle on a worker thread with a raised call stack.
|
|
283
|
+
*
|
|
284
|
+
* This is the handle a long-lived process wants against a large store: an
|
|
285
|
+
* MCP server, a chat tool loop, a SPARQL endpoint. It is asynchronous
|
|
286
|
+
* where `openStoreHandle` is synchronous, and it needs no runtime flag.
|
|
287
|
+
*
|
|
288
|
+
* @param {string} root the collection root that holds CURRENT
|
|
289
|
+
* @param {{generation?: string, keys?: string[], sparql?: string,
|
|
290
|
+
* session?: StoreWorkerSession, ownWorker?: boolean}} options
|
|
291
|
+
* @returns {Promise<WorkerStoreHandle>}
|
|
292
|
+
*/
|
|
293
|
+
export async function openStoreHandleOnWorker (root, options = {}) {
|
|
294
|
+
if (!workerRouteAvailable() || workerRefused(options)) {
|
|
295
|
+
return await openHere(root, options)
|
|
296
|
+
}
|
|
297
|
+
if (options.session instanceof StoreWorkerSession) {
|
|
298
|
+
return await options.session.open(root, options)
|
|
299
|
+
}
|
|
300
|
+
if (options.ownWorker === true) {
|
|
301
|
+
const session = await startWorker()
|
|
302
|
+
const handle = await session.open(root, options)
|
|
303
|
+
handle.ownSession = true
|
|
304
|
+
return handle
|
|
305
|
+
}
|
|
306
|
+
const session = await sharedStoreWorkerSession()
|
|
307
|
+
return await session.open(root, options)
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// -------------------------------- the in-process facade, for Deno
|
|
311
|
+
//
|
|
312
|
+
// Same two methods, same envelopes, no thread. It exists so one caller
|
|
313
|
+
// works on both runtimes; on Deno the stack must come from the host
|
|
314
|
+
// (`--v8-flags=--stack-size=65536`), because Deno's worker_threads shim
|
|
315
|
+
// does not raise it (see `workerRouteAvailable`).
|
|
316
|
+
|
|
317
|
+
/** A handle held in this process, behind the asynchronous interface. */
|
|
318
|
+
export class LocalStoreHandle {
|
|
319
|
+
constructor (handle) {
|
|
320
|
+
this.local = handle
|
|
321
|
+
this.handle = handle.handle
|
|
322
|
+
this.identity = handle.identity
|
|
323
|
+
this.layout = handle.layout
|
|
324
|
+
this.wireVersion = handle.wireVersion
|
|
325
|
+
this.artifacts = handle.artifacts
|
|
326
|
+
this.bytes = handle.bytes
|
|
327
|
+
this.rows = handle.rows
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
get closed () { return this.local.closed }
|
|
331
|
+
|
|
332
|
+
async query (sparql) { return this.local.query(sparql) }
|
|
333
|
+
|
|
334
|
+
async close () { this.local.close() }
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** Open a handle in this process, behind the asynchronous interface. */
|
|
338
|
+
async function openHere (root, options) {
|
|
339
|
+
const engine = await loadEngine()
|
|
340
|
+
const store = openStore(root,
|
|
341
|
+
typeof options.generation === 'string' ? options.generation : null)
|
|
342
|
+
const pick = {}
|
|
343
|
+
if (Array.isArray(options.keys)) pick.keys = options.keys
|
|
344
|
+
else if (typeof options.sparql === 'string') pick.sparql = options.sparql
|
|
345
|
+
return new LocalStoreHandle(openStoreHandle(engine, store, pick))
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// ------------------------------------------------- the one-shot retry
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Run one stateless query on a worker thread, then stop the thread.
|
|
352
|
+
*
|
|
353
|
+
* What `factoidal query` retries with after the in-process attempt ran
|
|
354
|
+
* out of frames. It answers exactly what `queryStore` answers.
|
|
355
|
+
*
|
|
356
|
+
* @returns {Promise<{plan: object, result: object, blobBytes: number}>}
|
|
357
|
+
*/
|
|
358
|
+
export async function queryStoreOnWorker (root, generation, sparql) {
|
|
359
|
+
if (!workerRouteAvailable()) {
|
|
360
|
+
const engine = await loadEngine()
|
|
361
|
+
const store = openStore(root, generation ?? null)
|
|
362
|
+
const answer = queryStore(engine, store, sparql)
|
|
363
|
+
return { plan: answer.plan, result: answer.result, blobBytes: answer.blobBytes }
|
|
364
|
+
}
|
|
365
|
+
const session = await startWorker()
|
|
366
|
+
try {
|
|
367
|
+
return await session.send({
|
|
368
|
+
kind: 'query-once', root, generation: generation ?? null, sparql
|
|
369
|
+
})
|
|
370
|
+
} finally {
|
|
371
|
+
await session.terminate()
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* Plan one query on a worker thread, then stop the thread.
|
|
377
|
+
*
|
|
378
|
+
* `storeQueryPlan` walks the manifest, and on a collection of a few
|
|
379
|
+
* thousand blocks that walk alone exceeds the default stack. What
|
|
380
|
+
* `factoidal query --explain` retries with.
|
|
381
|
+
*
|
|
382
|
+
* @returns {Promise<object>} the plan envelope
|
|
383
|
+
*/
|
|
384
|
+
export async function planQueryOnWorker (root, generation, sparql) {
|
|
385
|
+
if (!workerRouteAvailable()) {
|
|
386
|
+
const engine = await loadEngine()
|
|
387
|
+
return planQuery(engine, openStore(root, generation ?? null), sparql)
|
|
388
|
+
}
|
|
389
|
+
const session = await startWorker()
|
|
390
|
+
try {
|
|
391
|
+
return (await session.send({
|
|
392
|
+
kind: 'plan', root, generation: generation ?? null, sparql
|
|
393
|
+
})).plan
|
|
394
|
+
} finally {
|
|
395
|
+
await session.terminate()
|
|
396
|
+
}
|
|
397
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// The thread the store operations run on under Node, so that a query
|
|
2
|
+
// against a large generation has a call stack big enough to finish.
|
|
3
|
+
// https://github.com/danbri/factoidal/issues/653
|
|
4
|
+
//
|
|
5
|
+
// WHAT THIS FILE IS ALLOWED TO DO
|
|
6
|
+
// Load the engine, open a store, hold store handles, run the same store
|
|
7
|
+
// operations the in-process path runs, and post the answers back. It
|
|
8
|
+
// reads no manifest field, verifies no digest, decodes no block and
|
|
9
|
+
// chooses no artifact: `bin/store.mjs` drives the engine here exactly as
|
|
10
|
+
// it does on the main thread (iron rule 7 of CLAUDE.md).
|
|
11
|
+
//
|
|
12
|
+
// THE ENGINE AND THE HANDLES LIVE HERE, NOT ON THE MAIN THREAD.
|
|
13
|
+
// A loaded WebAssembly instance does not cross a thread boundary, and a
|
|
14
|
+
// store handle is state inside that instance: the verified, decoded,
|
|
15
|
+
// indexed blocks. So a handle opened here can only be queried from here.
|
|
16
|
+
// That is why the protocol below carries `query` and `close` as messages
|
|
17
|
+
// rather than returning a handle object. One worker holds many handles,
|
|
18
|
+
// up to the engine's own handle cap.
|
|
19
|
+
|
|
20
|
+
import { parentPort } from 'node:worker_threads'
|
|
21
|
+
import { loadEngine } from './engine.mjs'
|
|
22
|
+
import { describeError } from './pack-host.mjs'
|
|
23
|
+
import {
|
|
24
|
+
listStoreHandles, openStore, openStoreHandle, planQuery, queryStore
|
|
25
|
+
} from './store.mjs'
|
|
26
|
+
|
|
27
|
+
const port = parentPort
|
|
28
|
+
|
|
29
|
+
/** The handles this worker holds, by the id the engine gave them. */
|
|
30
|
+
const handles = new Map()
|
|
31
|
+
|
|
32
|
+
let engine = null
|
|
33
|
+
async function theEngine () {
|
|
34
|
+
if (engine === null) engine = await loadEngine()
|
|
35
|
+
return engine
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** One request. Every branch answers with a plain object, so nothing
|
|
39
|
+
* that crosses the boundary is an engine reference. */
|
|
40
|
+
async function serve (request) {
|
|
41
|
+
const active = await theEngine()
|
|
42
|
+
if (request.kind === 'open') {
|
|
43
|
+
const store = openStore(request.root, request.generation ?? null)
|
|
44
|
+
const options = {}
|
|
45
|
+
if (Array.isArray(request.keys)) options.keys = request.keys
|
|
46
|
+
else if (typeof request.sparql === 'string') options.sparql = request.sparql
|
|
47
|
+
const handle = openStoreHandle(active, store, options)
|
|
48
|
+
handles.set(handle.handle, handle)
|
|
49
|
+
return {
|
|
50
|
+
handle: handle.handle,
|
|
51
|
+
identity: handle.identity,
|
|
52
|
+
layout: handle.layout,
|
|
53
|
+
wireVersion: handle.wireVersion,
|
|
54
|
+
artifacts: handle.artifacts,
|
|
55
|
+
bytes: handle.bytes,
|
|
56
|
+
rows: handle.rows
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (request.kind === 'query') {
|
|
60
|
+
const handle = handles.get(request.handle)
|
|
61
|
+
if (handle === undefined) {
|
|
62
|
+
throw new Error(`this worker holds no store handle ${request.handle}`)
|
|
63
|
+
}
|
|
64
|
+
return { result: handle.query(request.sparql) }
|
|
65
|
+
}
|
|
66
|
+
if (request.kind === 'close') {
|
|
67
|
+
const handle = handles.get(request.handle)
|
|
68
|
+
if (handle === undefined) return { closed: false }
|
|
69
|
+
handle.close()
|
|
70
|
+
handles.delete(request.handle)
|
|
71
|
+
return { closed: true }
|
|
72
|
+
}
|
|
73
|
+
if (request.kind === 'list') {
|
|
74
|
+
return { list: listStoreHandles(active) }
|
|
75
|
+
}
|
|
76
|
+
if (request.kind === 'plan') {
|
|
77
|
+
const store = openStore(request.root, request.generation ?? null)
|
|
78
|
+
return { plan: planQuery(active, store, request.sparql) }
|
|
79
|
+
}
|
|
80
|
+
if (request.kind === 'query-once') {
|
|
81
|
+
// The stateless path: read the artifacts the plan names, hand them
|
|
82
|
+
// over, drop them. Used by the one-shot `factoidal query` after an
|
|
83
|
+
// in-process attempt ran out of frames.
|
|
84
|
+
const store = openStore(request.root, request.generation ?? null)
|
|
85
|
+
const answer = queryStore(active, store, request.sparql)
|
|
86
|
+
return {
|
|
87
|
+
plan: answer.plan,
|
|
88
|
+
result: answer.result,
|
|
89
|
+
blobBytes: answer.blobBytes
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (request.kind === 'warm') return { warm: true }
|
|
93
|
+
throw new Error(`the store worker was sent an unknown request "${request.kind}"`)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
port.on('message', (request) => {
|
|
97
|
+
serve(request).then(
|
|
98
|
+
(answer) => port.postMessage({ id: request.id, kind: 'ok', answer }),
|
|
99
|
+
(error) => port.postMessage({ id: request.id, kind: 'error', error: describeError(error) }))
|
|
100
|
+
})
|
package/bin/store.mjs
CHANGED
|
@@ -97,7 +97,10 @@ export function stackLimitAdvice (remedy) {
|
|
|
97
97
|
|
|
98
98
|
/** The remedies for each command that can run out of frames. */
|
|
99
99
|
export const STACK_REMEDY = {
|
|
100
|
-
query: '
|
|
100
|
+
query: 'A worker thread with a raised stack normally runs this again ' +
|
|
101
|
+
'(bin/store-worker-host.mjs). It was refused or is unavailable here: ' +
|
|
102
|
+
'drop --no-worker, give Deno --allow-run and --allow-env, raise the ' +
|
|
103
|
+
'stack with node --stack-size=60000, or add a LIMIT.',
|
|
101
104
|
pack: 'Raise it with node --stack-size=8000, or ' +
|
|
102
105
|
'deno run --v8-flags=--stack-size=8000.'
|
|
103
106
|
}
|
|
@@ -174,8 +177,12 @@ export function planQuery (engine, store, sparql) {
|
|
|
174
177
|
*/
|
|
175
178
|
function capDecision (engine, store, sparql) {
|
|
176
179
|
try {
|
|
177
|
-
|
|
178
|
-
|
|
180
|
+
// callBlobIO, not callBlob: the blob-IO entry is the one that reaches
|
|
181
|
+
// the SPARQL 1.1 section 17.6 extension registry (Wasm/Dispatch.lean's
|
|
182
|
+
// callBlobIO), so a caller registration is in scope on the stateless
|
|
183
|
+
// store path too. The envelope is identical.
|
|
184
|
+
return engine.callBlobIO('storeQuery',
|
|
185
|
+
[store.manifestHex, sparql, '[]'], new Uint8Array(0)).envelope
|
|
179
186
|
} catch (error) {
|
|
180
187
|
const refusal = asStoreError(error)
|
|
181
188
|
if (refusal.message.indexOf('no bytes were supplied for artifact') >= 0) {
|
|
@@ -191,7 +198,7 @@ function capDecision (engine, store, sparql) {
|
|
|
191
198
|
* The sequence is: plan, cap decision, read exactly the artifacts the
|
|
192
199
|
* plan named, concatenate them into one buffer, and call `storeQuery`
|
|
193
200
|
* with a `{"key","offset","len"}` window per artifact. The buffer is
|
|
194
|
-
* written straight into the wasm heap by `engine.
|
|
201
|
+
* written straight into the wasm heap by `engine.callBlobIO` with no
|
|
195
202
|
* encoding, and the engine bounds-checks every window.
|
|
196
203
|
*
|
|
197
204
|
* @returns {{plan: object, result: object, blobBytes: number,
|
|
@@ -216,8 +223,8 @@ export function queryStore (engine, store, sparql) {
|
|
|
216
223
|
}
|
|
217
224
|
let result
|
|
218
225
|
try {
|
|
219
|
-
result = engine.
|
|
220
|
-
[store.manifestHex, sparql, JSON.stringify(artifacts)], blob)
|
|
226
|
+
result = engine.callBlobIO('storeQuery',
|
|
227
|
+
[store.manifestHex, sparql, JSON.stringify(artifacts)], blob).envelope
|
|
221
228
|
} catch (error) {
|
|
222
229
|
throw asStoreError(error)
|
|
223
230
|
}
|
|
@@ -258,9 +265,21 @@ export function turtleOfNQuads (engine, nquads) {
|
|
|
258
265
|
// The stateless path above stays exactly as it was. A one-shot CLI query
|
|
259
266
|
// should not pay to build a handle it will drop.
|
|
260
267
|
|
|
261
|
-
/**
|
|
268
|
+
/**
|
|
269
|
+
* The artifact keys a manifest declares, in manifest order: every block, and
|
|
270
|
+
* every index sidecar the entry names. The KEYS come from the engine; this
|
|
271
|
+
* function chooses none of them. A sidecar is what lets a literal search skip
|
|
272
|
+
* the scan (SBM8's LGI1) or a geometry FILTER skip the WKT parse (SBM9's
|
|
273
|
+
* GBI1); a generation that declares none is unaffected. New sidecar roles
|
|
274
|
+
* need no change here: the engine names them under `entry.sidecars`.
|
|
275
|
+
*/
|
|
262
276
|
function manifestKeys (engine, store) {
|
|
263
|
-
|
|
277
|
+
const keys = []
|
|
278
|
+
for (const entry of inspectManifest(engine, store).entries) {
|
|
279
|
+
keys.push(entry.key)
|
|
280
|
+
for (const key of Object.values(entry.sidecars ?? {})) keys.push(key)
|
|
281
|
+
}
|
|
282
|
+
return keys
|
|
264
283
|
}
|
|
265
284
|
|
|
266
285
|
/** Read the named artifacts and concatenate them into one region. */
|
|
@@ -346,7 +365,8 @@ export function openStoreHandle (engine, store, options = {}) {
|
|
|
346
365
|
if (Array.isArray(options.keys)) {
|
|
347
366
|
keys = options.keys
|
|
348
367
|
} else if (typeof options.sparql === 'string') {
|
|
349
|
-
|
|
368
|
+
const plan = planQuery(engine, store, options.sparql)
|
|
369
|
+
keys = plan.keys.concat(plan.sidecarKeys ?? [])
|
|
350
370
|
} else {
|
|
351
371
|
keys = manifestKeys(engine, store)
|
|
352
372
|
}
|
package/l4-assets/l4factoidal.js
CHANGED