@wazootech/worlds-cloudflare 0.15.8 → 0.15.10

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/README.md CHANGED
@@ -286,9 +286,13 @@ const { results } = await sdk.provenance({ subject });
286
286
  - **What is recorded.** Only real changes. Importing quads the world already holds
287
287
  adds nothing, where the SDK's in-memory store records every insertion again.
288
288
  Quads written before the option was on have no records, and none are made up.
289
- - **Atomicity.** Records are written in the same D1 batch as their quads. A commit
290
- too large for one batch is not atomic, with or without provenance; if it fails
291
- partway, its cleanup corrects the records too.
289
+ - **Atomicity.** Records are written in the same D1 batch as their quads, and
290
+ decided there, so overlapping writes of one fact leave the records that writes
291
+ one after the other would. A commit too large for one batch is not atomic, with
292
+ or without provenance. Its records go first, and if it fails partway, its cleanup
293
+ corrects them. If another write to the same facts runs between its batches, a
294
+ record can be missing or written twice. If the cleanup fails too, the records can
295
+ name facts that were never stored.
292
296
  - **Writers.** Imports and SPARQL updates both take `provenance`:
293
297
  `sdk.sparql({ query, provenance: { writer } })`. Without it they are recorded
294
298
  with a time only. Inferred quads have no records. Writes that go
@@ -296,7 +300,7 @@ const { results } = await sdk.provenance({ subject });
296
300
  recorded.
297
301
  - **Cost.** Measured on miniflare with 1,000 and 10,000 short quads: 2 more rows
298
302
  written per new quad (11 instead of 9) and about 230 bytes per record. A
299
- replace import also reads the whole world first.
303
+ replace import also reads the world twice in its batch.
300
304
  - **Deletion.** `purgeWorld` removes a world's records. A replace import keeps
301
305
  them.
302
306
 
@@ -1,3 +1,10 @@
1
+ // src/cloudflare/shacl/shapes-graph.ts
2
+ /**
3
+ * SHAPES_GRAPH is the named graph that holds a world's SHACL shapes. It is the
4
+ * constant of the same name in `@wazootech/worlds-sdk/shacl`, written out so that
5
+ * a world without shapes never loads the validator.
6
+ */
7
+ const SHAPES_GRAPH = "https://wazoo.dev/ns/worlds#shapes";
1
8
  // src/cloudflare/provenance/d1-provenance-sql.ts
2
9
  /**
3
10
  * PROVENANCE_IDS_PER_STATEMENT is how many quads one provenance statement
@@ -35,17 +42,6 @@ function buildInsertProvenance(type, entries, stamp, worldId) {
35
42
  ]
36
43
  }));
37
44
  }
38
- /** buildDeleteWriteRecords takes back one commit's write records for quads it could not keep. */
39
- function buildDeleteWriteRecords(quadIds, recordedAt, worldId) {
40
- return chunk(quadIds).map((group) => ({
41
- sql: `DELETE FROM provenance WHERE type = 'write' AND recorded_at = ? AND quad_id IN (SELECT value FROM json_each(?))${worldId ? " AND world_id = ?" : ""}`,
42
- args: [
43
- recordedAt,
44
- JSON.stringify(group),
45
- ...worldId ? [worldId] : []
46
- ]
47
- }));
48
- }
49
45
  /** buildSelectProvenance lists records oldest first, narrowed by quad and type. */
50
46
  function buildSelectProvenance(query, worldId) {
51
47
  const filters = Object.entries({
@@ -96,11 +92,4 @@ function buildSelectProvenanceChains(quadIds, worldId) {
96
92
  ]
97
93
  };
98
94
  }
99
- // src/cloudflare/shacl/shapes-graph.ts
100
- /**
101
- * SHAPES_GRAPH is the named graph that holds a world's SHACL shapes. It is the
102
- * constant of the same name in `@wazootech/worlds-sdk/shacl`, written out so that
103
- * a world without shapes never loads the validator.
104
- */
105
- const SHAPES_GRAPH = "https://wazoo.dev/ns/worlds#shapes";
106
- export { buildProvenanceTable as a, buildSelectQuadRecords as c, buildInsertProvenance as i, chunk as l, PROVENANCE_IDS_PER_STATEMENT as n, buildSelectProvenance as o, buildDeleteWriteRecords as r, buildSelectProvenanceChains as s, SHAPES_GRAPH as t };
95
+ export { buildSelectQuadRecords as a, buildSelectProvenanceChains as i, buildProvenanceTable as n, chunk as o, buildSelectProvenance as r, SHAPES_GRAPH as s, buildInsertProvenance as t };
@@ -1,4 +1,4 @@
1
- import { a as buildProvenanceTable, t as SHAPES_GRAPH } from "./shapes-graph-6g22feyx.js";
1
+ import { n as buildProvenanceTable, s as SHAPES_GRAPH } from "./d1-provenance-sql-BRu7mIGI.js";
2
2
  import { buildChunksQuadIdIndex } from "@wazootech/worlds-sqlite/sql-core";
3
3
  // src/cloudflare/validate-world-id.ts
4
4
  /**
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";
2
2
  import { WorldsSdk } from "@wazootech/worlds-sdk";
3
- import { a as createD1SearchIndexRebuilder, c as emptyVectorSyncReport, d as recordVectorSyncError, f as vectorSyncSucceeded, h as sanitizeFtsQuery, i as CloudflareSearchIndex, l as logVectorSyncDrift, m as RRF_REFERENCE_CONSTANT, n as buildSearchResultId, o as rebuildD1SearchIndexFromQuads, p as D1SearchQueryBuilder, r as D1SearchIndexProjector, s as D1VectorSync, t as buildChunkFtsValue, u as mergeVectorSyncReports } from "./search-index-DVbbsc3z.js";
4
- import { a as loadAssertedQuads, i as InferenceSizeGuardError, n as D1ProvenanceStore, o as planInference, t as D1QuadStore } from "./quad-store-C1IJEz2D.js";
3
+ import { a as createD1SearchIndexRebuilder, c as emptyVectorSyncReport, d as recordVectorSyncError, f as vectorSyncSucceeded, h as sanitizeFtsQuery, i as CloudflareSearchIndex, l as logVectorSyncDrift, m as RRF_REFERENCE_CONSTANT, n as buildSearchResultId, o as rebuildD1SearchIndexFromQuads, p as D1SearchQueryBuilder, r as D1SearchIndexProjector, s as D1VectorSync, t as buildChunkFtsValue, u as mergeVectorSyncReports } from "./search-index-_yyeZAVm.js";
4
+ import { a as loadAssertedQuads, i as InferenceSizeGuardError, n as D1ProvenanceStore, o as planInference, t as D1QuadStore } from "./quad-store-DfUksTZ2.js";
5
5
  import { a as DEFAULT_D1_MAX_BATCH_WEIGHT, o as d1StatementWeight } from "./project-search-chunks-options-qI9m5FWz.js";
6
6
  import { WazooSparqlEngine } from "@wazootech/sparql-engine";
7
7
  import { RE2JS } from "re2js";
8
- import { i as D1QuadStream, n as assertD1SchemaCompatible, r as checkD1SchemaCompatibility, t as D1RdfjsStore } from "./rdfjs-store-DfmCIuVz.js";
9
- import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-emxvwyf9.js";
8
+ import { i as D1QuadStream, n as assertD1SchemaCompatible, r as checkD1SchemaCompatibility, t as D1RdfjsStore } from "./rdfjs-store-8V0H0fGC.js";
9
+ import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-Dj0dTBxX.js";
10
10
  import { g as DEFAULT_D1_MAX_WRITE_BATCH_SIZE, h as D1BatchExecutor, m as quadToInsertRow, s as buildDeleteAllDerivedQuads, t as buildBulkInsertQuads, u as buildWipeAllGraphDataStatements } from "./d1-quad-insert-sql-B4ZiZZe8.js";
11
11
  // src/cloudflare/search-index/vector-search/vectorize-provisioning.ts
12
12
  /**
@@ -1,100 +1,277 @@
1
- import { InMemoryProvenanceStore, Transaction, exportFromRdfjsStore, filterQuads, hashQuads, importViaTransaction, isReplaceImportCommit, preparePatch } from "@wazootech/worlds-sdk/quad-store";
1
+ import { InMemoryProvenanceStore, Transaction, exportFromRdfjsStore, filterQuads, hashQuads, importViaTransaction, isReplaceImportCommit, preparePatch, selectNovelQuads } from "@wazootech/worlds-sdk/quad-store";
2
2
  import { planSearchIndexing } from "@wazootech/worlds-sdk/search-index";
3
3
  import { commitSqlPatch } from "@wazootech/worlds-sqlite/sql-core";
4
4
  import { _ as effectiveLookupChunkSize, a as buildSelectAssertedQuadsPage, d as DEFAULT_D1_MATCH_PAGE_SIZE, f as buildInsertRow, n as buildCountAssertedQuads, p as quadFromD1Row } from "./d1-quad-insert-sql-B4ZiZZe8.js";
5
- import { c as buildSelectQuadRecords, i as buildInsertProvenance, l as chunk, n as PROVENANCE_IDS_PER_STATEMENT, o as buildSelectProvenance, r as buildDeleteWriteRecords, s as buildSelectProvenanceChains, t as SHAPES_GRAPH } from "./shapes-graph-6g22feyx.js";
6
5
  import { Reasoner } from "@wazootech/reasoner";
6
+ import { a as buildSelectQuadRecords, i as buildSelectProvenanceChains, o as chunk, r as buildSelectProvenance, s as SHAPES_GRAPH, t as buildInsertProvenance } from "./d1-provenance-sql-BRu7mIGI.js";
7
7
  import { i as createD1CommitDriver, s as createD1CommitDialect, t as isFullRebuild } from "./project-search-chunks-options-qI9m5FWz.js";
8
8
  import { r as matchD1Pages } from "./d1-rdfjs-store-read-2QTEEe_a.js";
9
- // src/cloudflare/provenance/read-stored-quads.ts
10
- /** selectStored runs one read; it names `derived` only when inference guarantees the column. */
11
- async function selectStored(condition, arg, options) {
12
- const { rows } = await options.connection.execute({
13
- sql: `SELECT quad_id AS id, s, p, g FROM quads WHERE ${condition}${options.worldId ? " AND world_id = ?" : ""}${options.inferenceEnabled ? " AND derived = 0" : ""} ORDER BY quad_id LIMIT ${PROVENANCE_IDS_PER_STATEMENT}`,
14
- args: [arg, ...options.worldId ? [options.worldId] : []]
9
+ /** LISTS_PER_STATEMENT keeps a statement inside D1's 100 parameters and a batch's byte budget. */
10
+ const LISTS_PER_STATEMENT = 16;
11
+ /** packLists splits items over as many JSON lists as D1's value size needs, and at least one. */
12
+ function packLists(items) {
13
+ const lists = [];
14
+ let list = "";
15
+ for (const item of items) {
16
+ const json = JSON.stringify(item);
17
+ if (list && list.length + json.length > 5e5) {
18
+ lists.push(`[${list}]`);
19
+ list = "";
20
+ }
21
+ list += list ? `,${json}` : json;
22
+ }
23
+ return [...lists, `[${list}]`];
24
+ }
25
+ /** groupLists splits items over statements; no items need no statement. */
26
+ function groupLists(items) {
27
+ if (items.length === 0) return [];
28
+ const lists = packLists(items);
29
+ const groups = [];
30
+ for (let i = 0; i < lists.length; i += LISTS_PER_STATEMENT) groups.push(lists.slice(i, i + LISTS_PER_STATEMENT));
31
+ return groups;
32
+ }
33
+ /** fromLists reads the items of several lists as rows of `item`. */
34
+ function fromLists(lists) {
35
+ return {
36
+ sql: `(VALUES ${lists.map(() => "(?)").join(", ")}) lists CROSS JOIN json_each(lists.column1) item`,
37
+ args: [...lists]
38
+ };
39
+ }
40
+ /** insertRecords starts an INSERT of one record per row, with these values for its quad and the one it replaced. */
41
+ function insertRecords(type, values, scope) {
42
+ const { worldId, recordedAt, writer, source } = scope;
43
+ return {
44
+ sql: `INSERT INTO provenance (quad_id, supersedes_quad_id, type, recorded_at, writer, source${worldId ? ", world_id" : ""}) SELECT ${values}, '${type}', ?, ?, ?${worldId ? ", ?" : ""} FROM`,
45
+ args: [
46
+ recordedAt,
47
+ writer ?? null,
48
+ source ?? null,
49
+ ...worldId ? [worldId] : []
50
+ ]
51
+ };
52
+ }
53
+ /** latestRecord reads a value from the newest record `r` of a quad; it is NULL if there is none. */
54
+ function latestRecord(value, quadId, { worldId }) {
55
+ return {
56
+ sql: `(SELECT ${value.sql} FROM provenance r WHERE r.quad_id = ${quadId}${worldId ? " AND r.world_id = ?" : ""} ORDER BY r.record_id DESC LIMIT 1)`,
57
+ args: [...value.args, ...worldId ? [worldId] : []]
58
+ };
59
+ }
60
+ /** asserted limits the quads `q` to the world's asserted ones; it names `derived` only when inference guarantees the column. */
61
+ function asserted({ worldId, inferenceEnabled }) {
62
+ return {
63
+ sql: `${worldId ? " AND q.world_id = ?" : ""}${inferenceEnabled ? " AND q.derived = 0" : ""}`,
64
+ args: worldId ? [worldId] : []
65
+ };
66
+ }
67
+ /** fromStored reads, as rows of `q`, the listed quads that the world holds at that moment, or all of them. */
68
+ function fromStored(lists, scope) {
69
+ const held = asserted(scope);
70
+ if (lists === "world") return {
71
+ sql: `quads q WHERE TRUE${held.sql}`,
72
+ args: held.args
73
+ };
74
+ const ids = fromLists(lists);
75
+ return {
76
+ sql: `${ids.sql} CROSS JOIN quads q WHERE q.quad_id = item.value${held.sql}`,
77
+ args: [...ids.args, ...held.args]
78
+ };
79
+ }
80
+ // src/cloudflare/provenance/commit-records-sql.ts
81
+ /** buildRemoveRecords records the stored quads a commit takes out. It has to run before anything is deleted. */
82
+ function buildRemoveRecords(leaving, addedIds, scope) {
83
+ const insert = insertRecords("remove", "q.quad_id, NULL", scope);
84
+ if (leaving !== "world") return groupLists(leaving).map((lists) => {
85
+ const stored = fromStored(lists, scope);
86
+ return {
87
+ sql: `${insert.sql} ${stored.sql}`,
88
+ args: [...insert.args, ...stored.args]
89
+ };
90
+ });
91
+ const stored = fromStored("world", scope);
92
+ const kept = fromLists(packLists(addedIds));
93
+ return [{
94
+ sql: `${insert.sql} ${stored.sql} AND q.quad_id NOT IN (SELECT item.value FROM ${kept.sql})`,
95
+ args: [
96
+ ...insert.args,
97
+ ...stored.args,
98
+ ...kept.args
99
+ ]
100
+ }];
101
+ }
102
+ /**
103
+ * buildWriteRecords records the added quads that the world does not hold yet,
104
+ * each linked to the quad it replaces: one at the same position that has just
105
+ * got this commit's remove record. It has to run between those and the first
106
+ * delete. The `+` keeps SQLite off the index by subject, which worlds share.
107
+ */
108
+ function buildWriteRecords(added, leaving, scope) {
109
+ const old = fromStored(leaving === "world" ? leaving : packLists(leaving), scope);
110
+ const justRemoved = latestRecord({
111
+ sql: "r.type = 'remove' AND r.recorded_at = ?",
112
+ args: [scope.recordedAt]
113
+ }, "q.quad_id", scope);
114
+ const held = asserted(scope);
115
+ const insert = insertRecords("write", "added.id, replaced.id", scope);
116
+ return groupLists(added).map((lists) => {
117
+ const items = fromLists(lists);
118
+ return {
119
+ sql: `WITH added(id, s, p, g) AS MATERIALIZED (
120
+ SELECT json_extract(item.value, '$[0]'), json_extract(item.value, '$[1]'),
121
+ json_extract(item.value, '$[2]'), json_extract(item.value, '$[3]')
122
+ FROM ${items.sql}
123
+ ), replaced(id, s, p, g) AS MATERIALIZED (
124
+ SELECT MAX(q.quad_id), q.s, q.p, q.g FROM ${old.sql}
125
+ AND (+q.s, +q.p, +q.g) IN (SELECT s, p, g FROM added)
126
+ AND ${justRemoved.sql}
127
+ GROUP BY q.s, q.p, q.g
128
+ ) ${insert.sql} added LEFT JOIN replaced
129
+ ON replaced.s = added.s AND replaced.p = added.p AND replaced.g = added.g
130
+ WHERE NOT EXISTS (SELECT 1 FROM quads q WHERE q.quad_id = added.id${held.sql})`,
131
+ args: [
132
+ ...items.args,
133
+ ...old.args,
134
+ ...justRemoved.args,
135
+ ...insert.args,
136
+ ...held.args
137
+ ]
138
+ };
15
139
  });
16
- return rows;
17
140
  }
18
- /** lookupStoredQuads yields the quads among `ids` that the world holds. */
19
- async function* lookupStoredQuads(ids, options) {
20
- for (const group of chunk([...new Set(ids)])) yield* await selectStored("quad_id IN (SELECT value FROM json_each(?))", JSON.stringify(group), options);
141
+ // src/cloudflare/provenance/undo-records-sql.ts
142
+ /**
143
+ * buildUndoRecords makes the records true again after a commit that was too
144
+ * large for one batch failed partway. It has to run before the commit's cleanup,
145
+ * which deletes every added quad, even one that was stored before. `recorded`
146
+ * says that all the commit's records were written; before that, it deleted nothing.
147
+ */
148
+ function buildUndoRecords(leaving, addedIds, recorded, scope) {
149
+ const added = groupLists(addedIds).map(fromLists);
150
+ return [
151
+ ...(leaving === "world" ? [leaving] : groupLists(leaving)).map((lists) => takeBackRemoves(lists, scope)),
152
+ ...added.map((ids) => {
153
+ const insert = insertRecords("remove", "item.value, NULL", scope);
154
+ const lost = wasStored(recorded, scope);
155
+ return {
156
+ sql: `${insert.sql} ${ids.sql} WHERE ${lost.sql}`,
157
+ args: [
158
+ ...insert.args,
159
+ ...ids.args,
160
+ ...lost.args
161
+ ]
162
+ };
163
+ }),
164
+ ...added.map((ids) => ({
165
+ sql: `DELETE FROM provenance WHERE type = 'write' AND recorded_at = ? AND quad_id IN (SELECT item.value FROM ${ids.sql})${scope.worldId ? " AND world_id = ?" : ""}`,
166
+ args: [
167
+ scope.recordedAt,
168
+ ...ids.args,
169
+ ...scope.worldId ? [scope.worldId] : []
170
+ ]
171
+ }))
172
+ ];
21
173
  }
22
- /** streamStoredQuads yields every quad of the world, a page at a time. */
23
- async function* streamStoredQuads(options) {
24
- let after = "";
25
- for (;;) {
26
- const rows = await selectStored("quad_id > ?", after, options);
27
- yield* rows;
28
- if (rows.length < 5e3) return;
29
- after = rows[rows.length - 1].id;
30
- }
174
+ /** takeBackRemoves deletes the commit's remove records of quads that are still stored. */
175
+ function takeBackRemoves(lists, scope) {
176
+ const stored = fromStored(lists, scope);
177
+ const own = latestRecord({
178
+ sql: "CASE WHEN r.type = 'remove' AND r.recorded_at = ? THEN r.record_id END",
179
+ args: [scope.recordedAt]
180
+ }, "q.quad_id", scope);
181
+ return {
182
+ sql: `DELETE FROM provenance WHERE record_id IN (SELECT ${own.sql} FROM ${stored.sql})`,
183
+ args: [...own.args, ...stored.args]
184
+ };
31
185
  }
32
- // src/cloudflare/provenance/plan-d1-provenance.ts
33
- /** positionKey identifies the statement a quad makes; a correction changes only the object. */
34
- function positionKey(s, p, g) {
35
- return JSON.stringify([
36
- s,
37
- p,
38
- g
39
- ]);
186
+ /**
187
+ * wasStored is true for an added quad `item` that another commit wrote, so that
188
+ * the cleanup loses it. A quad from before the world had provenance has no
189
+ * record: it was stored if this commit didn't record a write, or if it still is.
190
+ */
191
+ function wasStored(recorded, scope) {
192
+ const written = latestRecord({
193
+ sql: "r.type = 'write' AND r.recorded_at <> ?",
194
+ args: [scope.recordedAt]
195
+ }, "item.value", scope);
196
+ const held = asserted(scope);
197
+ return {
198
+ sql: `COALESCE(${written.sql}, ${recorded ? "TRUE" : `EXISTS (SELECT 1 FROM quads q WHERE q.quad_id = item.value${held.sql})`})`,
199
+ args: [...written.args, ...recorded ? [] : held.args]
200
+ };
40
201
  }
41
- function positionOf(quad) {
42
- return positionKey(quad.subject.value, quad.predicate.value, quad.graph.value);
202
+ // src/cloudflare/provenance/plan-d1-provenance.ts
203
+ /** positionOf names the statement a quad makes; a correction changes only the object. */
204
+ function positionOf({ subject, predicate, graph }) {
205
+ return [
206
+ subject.value,
207
+ predicate.value,
208
+ graph.value
209
+ ];
43
210
  }
44
211
  /**
45
- * planD1Provenance works out, before anything is written, which quads a commit
46
- * really adds and removes. A quad the world already holds gets no new record, so
47
- * importing the same data again neither grows the table nor makes an old quad
48
- * look newly written. The SDK's in-memory store records every insertion instead.
212
+ * planD1Provenance builds the statements that record a commit. They decide what
213
+ * the commit really adds and removes when its batch runs, not now, because
214
+ * another commit may get in between. A quad the world already holds gets no new
215
+ * record, so importing the same data again neither grows the table nor makes an
216
+ * old quad look newly written. The SDK's in-memory store records every insertion
217
+ * instead.
49
218
  */
50
- async function planD1Provenance(patch, context, options) {
51
- const { worldId } = options;
219
+ async function planD1Provenance(patch, context, driver, options) {
52
220
  const replacing = isReplaceImportCommit(context);
53
221
  const prepared = preparePatch(patch, options);
54
- const inserted = new Map(prepared.insertionIds.map((id, i) => [id, prepared.insertions[i]]));
55
- const insertedPositions = new Set([...inserted.values()].map(positionOf));
56
- const kept = [];
57
- const removed = [];
58
- const supersededAt = /* @__PURE__ */ new Map();
59
- const stored = replacing ? streamStoredQuads(options) : lookupStoredQuads([...inserted.keys(), ...prepared.deletionIds], options);
60
- for await (const row of stored) {
61
- if (inserted.has(row.id)) {
62
- kept.push(row.id);
63
- continue;
64
- }
65
- removed.push([row.id]);
66
- const position = positionKey(row.s, row.p, row.g);
67
- if (insertedPositions.has(position)) supersededAt.set(position, row.id);
68
- }
69
- const keptIds = new Set(kept);
70
- const written = [];
71
- for (const [id, quad] of inserted) if (!keptIds.has(id)) written.push([id, supersededAt.get(positionOf(quad))]);
72
- const lostByCleanup = replacing ? kept : [];
73
- const stamp = {
222
+ let existing;
223
+ const lookupExisting = (ids) => existing ??= driver.lookupExisting(ids);
224
+ const novel = await selectNovelQuads(prepared, {
225
+ replacing,
226
+ lookupExisting
227
+ });
228
+ const inserted = new Map(novel.novelQuadIds.map((id, i) => [id, novel.novelInsertions[i]]));
229
+ const deleted = new Map(prepared.deletionIds.map((id, i) => [id, prepared.deletions[i]]).filter(([id]) => !inserted.has(id)));
230
+ const key = (quad) => JSON.stringify(positionOf(quad));
231
+ const freed = new Set([...deleted.values()].map(key));
232
+ const filled = new Set([...inserted.values()].map(key));
233
+ const added = [...inserted].map(([id, quad]) => replacing || freed.has(key(quad)) ? [id, ...positionOf(quad)] : [id]);
234
+ const replaceable = [...deleted].filter(([, quad]) => filled.has(key(quad))).map(([id]) => id);
235
+ const scope = {
74
236
  ...context?.provenance,
75
- recordedAt: (/* @__PURE__ */ new Date()).toISOString()
237
+ recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
238
+ worldId: options.worldId,
239
+ inferenceEnabled: options.inferenceEnabled
76
240
  };
241
+ const ids = [...inserted.keys()];
242
+ const leaving = replacing ? "world" : [...deleted.keys()];
77
243
  return {
78
- removals: buildInsertProvenance("remove", removed, stamp, worldId),
79
- writes: buildInsertProvenance("write", written, stamp, worldId),
80
- cleanup: [...buildDeleteWriteRecords(written.map(([id]) => id), stamp.recordedAt, worldId), ...buildInsertProvenance("remove", lostByCleanup.map((id) => [id]), stamp, worldId)]
244
+ records: [...buildRemoveRecords(leaving, ids, scope), ...buildWriteRecords(added, replacing ? "world" : replaceable, scope)],
245
+ lookupExisting,
246
+ undo: (recorded) => buildUndoRecords(leaving, ids, recorded, scope)
81
247
  };
82
248
  }
83
249
  // src/cloudflare/provenance/with-provenance.ts
84
250
  /**
85
- * withProvenance adds a plan's statements to a commit dialect, so they join the
86
- * commit's own batch: removals before the first delete or wipe, writes after the
87
- * quads they describe. Create one per commit, like the dialect itself.
251
+ * withProvenance adds a plan's statements to a commit's driver and dialect, so
252
+ * they join the commit's own batch, before its first delete or wipe. Create one
253
+ * per commit, like the dialect itself.
88
254
  */
89
- function withProvenance(dialect, plan) {
90
- const pendingRemovals = [...plan.removals];
91
- const takeRemovals = () => pendingRemovals.splice(0);
255
+ function withProvenance(driver, dialect, plan) {
256
+ const pending = [...plan.records];
257
+ const takeRecords = () => pending.splice(0);
258
+ const last = plan.records.at(-1);
259
+ let recorded = false;
92
260
  return {
93
- ...dialect,
94
- buildWipe: () => [...takeRemovals(), ...dialect.buildWipe()],
95
- buildDeletions: (keys, hashes) => [...takeRemovals(), ...dialect.buildDeletions(keys, hashes)],
96
- buildInserts: (quads, keys, hashes) => [...dialect.buildInserts(quads, keys, hashes), ...plan.writes],
97
- buildCleanup: (keys, hashes) => [...dialect.buildCleanup(keys, hashes), ...plan.cleanup]
261
+ driver: {
262
+ ...driver,
263
+ lookupExisting: plan.lookupExisting,
264
+ executeBatch: async (statements) => {
265
+ await driver.executeBatch(statements);
266
+ recorded ||= last !== void 0 && statements.includes(last);
267
+ }
268
+ },
269
+ dialect: {
270
+ ...dialect,
271
+ buildWipe: () => [...takeRecords(), ...dialect.buildWipe()],
272
+ buildDeletions: (keys, hashes) => [...takeRecords(), ...dialect.buildDeletions(keys, hashes)],
273
+ buildCleanup: (keys, hashes) => [...plan.undo(recorded), ...dialect.buildCleanup(keys, hashes)]
274
+ }
98
275
  };
99
276
  }
100
277
  // src/cloudflare/inference/inference-planner.ts
@@ -329,7 +506,8 @@ async function commitD1Patch(patch, context, options) {
329
506
  };
330
507
  const derived = options.inference?.enabled ? await planD1DerivedChanges(patch, context, options.inference, driverOptions) : void 0;
331
508
  await checkD1Patch(patch, context, options, derived);
332
- const provenance = options.provenance?.enabled ? await planD1Provenance(patch, context, driverOptions) : void 0;
509
+ const driver = createD1CommitDriver(driverOptions);
510
+ const provenance = options.provenance?.enabled ? await planD1Provenance(patch, context, driver, driverOptions) : void 0;
333
511
  const indexing = planSearchIndexing(options.searchIndexOnImport, context);
334
512
  const dialect = createD1CommitDialect({
335
513
  searchQueryBuilder: options.searchQueryBuilder,
@@ -338,7 +516,11 @@ async function commitD1Patch(patch, context, options) {
338
516
  derived,
339
517
  onChunkRows: sync?.collect
340
518
  });
341
- await commitSqlPatch(patch, context, createD1CommitDriver(driverOptions), provenance ? withProvenance(dialect, provenance) : dialect, {
519
+ const commit = provenance ? withProvenance(driver, dialect, provenance) : {
520
+ driver,
521
+ dialect
522
+ };
523
+ await commitSqlPatch(patch, context, commit.driver, commit.dialect, {
342
524
  filter: options,
343
525
  searchIndexOnImport: options.searchIndexOnImport,
344
526
  projection: projector?.projection,
@@ -1 +1 @@
1
- export { t as D1QuadStore } from "./quad-store-C1IJEz2D.js";
1
+ export { t as D1QuadStore } from "./quad-store-DfUksTZ2.js";
@@ -1,6 +1,6 @@
1
1
  import { DataFactory } from "@wazootech/sparql-engine";
2
2
  import { _ as effectiveLookupChunkSize, h as D1BatchExecutor, l as buildDeleteQuadsByQuadIds, m as quadToInsertRow, o as buildSelectExistingQuadIds, t as buildBulkInsertQuads, u as buildWipeAllGraphDataStatements } from "./d1-quad-insert-sql-B4ZiZZe8.js";
3
- import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-emxvwyf9.js";
3
+ import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-Dj0dTBxX.js";
4
4
  import { hashQuads, isReplaceImportCommit } from "@wazootech/worlds-sdk/quad-store";
5
5
  import { i as removeMatchedQuads, n as countD1Matches, r as matchD1Pages, t as collectQuads } from "./d1-rdfjs-store-read-2QTEEe_a.js";
6
6
  // src/cloudflare/rdfjs-store/d1-quad-stream.ts
@@ -168,7 +168,7 @@ var D1TransactionImpl = class {
168
168
  this.inserted.set(quadKey(quad), quad);
169
169
  }
170
170
  delete(quad) {
171
- if (this.inserted.delete(quadKey(quad))) return;
171
+ this.inserted.delete(quadKey(quad));
172
172
  this.deleted.set(quadKey(quad), quad);
173
173
  }
174
174
  commit() {
@@ -1 +1 @@
1
- export { i as D1QuadStream, t as D1RdfjsStore } from "./rdfjs-store-DfmCIuVz.js";
1
+ export { i as D1QuadStream, t as D1RdfjsStore } from "./rdfjs-store-8V0H0fGC.js";
package/dist/schema.js CHANGED
@@ -1 +1 @@
1
- export { t as D1SchemaBuilder } from "./d1-schema-builder-emxvwyf9.js";
1
+ export { t as D1SchemaBuilder } from "./d1-schema-builder-Dj0dTBxX.js";
@@ -2,7 +2,8 @@ import { RRF_FUSION_K, buildChunkFtsValue, buildIncludeExcludeFilterClauses, bui
2
2
  import { normalizeRrfScore } from "@wazootech/worlds-sdk/search-index";
3
3
  import { _ as effectiveLookupChunkSize } from "./d1-quad-insert-sql-B4ZiZZe8.js";
4
4
  import { i as createD1CommitDriver, n as toProjectionOptions, r as vectorSyncEnabled, s as createD1CommitDialect, t as isFullRebuild } from "./project-search-chunks-options-qI9m5FWz.js";
5
- import { hashQuads } from "@wazootech/worlds-sdk/quad-store";
5
+ import { filterQuads, hashQuads } from "@wazootech/worlds-sdk/quad-store";
6
+ import { DataFactory } from "@wazootech/sparql-engine/data-model";
6
7
  // src/cloudflare/search-index/d1-world-scoped-fts.ts
7
8
  /** RRF constant shared with the generic keyword plan (1 / (60 + rank)). */
8
9
  const RRF_K = 60;
@@ -489,6 +490,20 @@ function hitToSearchResult(hit) {
489
490
  function clampCosine(score) {
490
491
  return Math.max(0, Math.min(1, score));
491
492
  }
493
+ // src/cloudflare/search-index/filter-vector-hits.ts
494
+ const { literal, namedNode, quad } = DataFactory;
495
+ /**
496
+ * filterVectorHits keeps the hits that match a request's include and exclude,
497
+ * in order, with the meaning they have for stored facts and for the keyword
498
+ * query. The vector index can only filter on `world_id`, so this runs after its
499
+ * query. The index then returns its nearest `candidateCount` hits of the whole
500
+ * world, and a narrow filter can leave fewer vector results than that. The
501
+ * keyword query filters in SQL and is not affected.
502
+ */
503
+ function filterVectorHits(hits, filter) {
504
+ const matches = filterQuads(filter);
505
+ return hits.filter(({ metadata }) => matches(quad(namedNode(metadata?.subject ?? ""), namedNode(metadata?.predicate ?? ""), literal(metadata?.value ?? ""), namedNode(metadata?.graph ?? ""))));
506
+ }
492
507
  // src/cloudflare/search-index/cloudflare-search-index.ts
493
508
  /**
494
509
  * CloudflareSearchIndex implements the query pathway over D1's FTS5
@@ -540,10 +555,10 @@ var CloudflareSearchIndex = class {
540
555
  if (this.options.embeddingService && this.options.vectorSearch) try {
541
556
  const embedded = await this.options.embeddingService.embed([request.query]);
542
557
  const queryVector = embedded[0] ? new Float32Array(embedded[0]) : void 0;
543
- if (queryVector) vectorHits = await this.options.vectorSearch.query(Array.from(queryVector), {
558
+ if (queryVector) vectorHits = filterVectorHits(await this.options.vectorSearch.query(Array.from(queryVector), {
544
559
  topK: candidateCount,
545
560
  ...this.options.worldId ? { filter: { world_id: this.options.worldId } } : {}
546
- });
561
+ }), request);
547
562
  } catch (error) {
548
563
  console.warn("[Search Warning] vector query failed; falling back to keyword-only", error);
549
564
  }
@@ -1 +1 @@
1
- export { i as CloudflareSearchIndex, r as D1SearchIndexProjector, p as D1SearchQueryBuilder, s as D1VectorSync, m as RRF_REFERENCE_CONSTANT, t as buildChunkFtsValue, n as buildSearchResultId, a as createD1SearchIndexRebuilder, c as emptyVectorSyncReport, l as logVectorSyncDrift, u as mergeVectorSyncReports, o as rebuildD1SearchIndexFromQuads, d as recordVectorSyncError, h as sanitizeFtsQuery, f as vectorSyncSucceeded } from "./search-index-DVbbsc3z.js";
1
+ export { i as CloudflareSearchIndex, r as D1SearchIndexProjector, p as D1SearchQueryBuilder, s as D1VectorSync, m as RRF_REFERENCE_CONSTANT, t as buildChunkFtsValue, n as buildSearchResultId, a as createD1SearchIndexRebuilder, c as emptyVectorSyncReport, l as logVectorSyncDrift, u as mergeVectorSyncReports, o as rebuildD1SearchIndexFromQuads, d as recordVectorSyncError, h as sanitizeFtsQuery, f as vectorSyncSucceeded } from "./search-index-_yyeZAVm.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wazootech/worlds-cloudflare",
3
- "version": "0.15.8",
3
+ "version": "0.15.10",
4
4
  "description": "Store a Worlds knowledge graph in Cloudflare D1, with keyword search, optional Vectorize search, SPARQL and provenance. Made for Cloudflare Workers.",
5
5
  "keywords": [
6
6
  "wazoo",
@@ -72,9 +72,9 @@
72
72
  "@langchain/textsplitters": "^1.0.1",
73
73
  "@rdfjs/types": "^2.0.1",
74
74
  "@wazootech/reasoner": "^0.4.4",
75
- "@wazootech/sparql-engine": "^0.5.11",
76
- "@wazootech/worlds-sdk": "^0.11.5",
77
- "@wazootech/worlds-sqlite": "^0.8.4",
75
+ "@wazootech/sparql-engine": "^0.5.12",
76
+ "@wazootech/worlds-sdk": "^0.11.6",
77
+ "@wazootech/worlds-sqlite": "^0.8.5",
78
78
  "re2js": "2.10.0"
79
79
  },
80
80
  "devDependencies": {