@wazootech/worlds-cloudflare 0.15.10 → 0.15.12

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
@@ -32,6 +32,15 @@ vector query is filtered on it, and vector ids are namespaced per world, so
32
32
  identical triple text in two worlds never shares a vector
33
33
  ([worlds-cloudflare#41](https://github.com/wazootech/worlds-cloudflare/issues/41)).
34
34
 
35
+ **Filters and semantic search.** Vectorize can only filter on `world_id`. When a
36
+ search's `include` and `exclude` leave at most 100 chunks of text, the search
37
+ reads their vectors by id and scores each one, so it finds the nearest of them.
38
+ Otherwise it filters the nearest `candidateCount` chunks of the whole world, and
39
+ can miss matches. It also does that when no criterion finds the facts within
40
+ 5,000 quads, or when the `vectorize` binding has no `getByIds`. Keyword matches
41
+ are always filtered first
42
+ ([worlds-cloudflare#122](https://github.com/wazootech/worlds-cloudflare/issues/122)).
43
+
35
44
  **Vector sync is reported, not swallowed.** A failed vector upsert or
36
45
  stale-vector delete never fails an import (D1 is the source of truth and keyword
37
46
  search keeps serving), but it is logged as a structured `[vector-sync]` error
@@ -258,12 +267,33 @@ try {
258
267
  validator isn't loaded. Otherwise a check reads the shapes and the facts they
259
268
  look at, up to `shacl.maxCheckedFacts` (default 50,000). A write that needs more
260
269
  fails with `ShaclLimitError`.
261
- - **Simultaneous writes.** D1 has no transaction that could hold both the check and
262
- the write. Two valid writes at the same moment can break a shape together.
263
270
  - **Not checked.** Writes that go through `D1RdfjsStore` directly.
264
271
  - **Existing databases.** Opening a world in a database that worlds share adds the
265
272
  small index `idx_quads_shapes`. No migration is needed.
266
273
 
274
+ ## Simultaneous writes
275
+
276
+ SHACL checks and inference read the world before they write, and D1 has no
277
+ transaction that could hold both. So each world's writes are counted in the
278
+ `world_versions` table. If another write got in between, the commit writes nothing
279
+ and is planned again, with the other write in view.
280
+
281
+ - **Which worlds.** Those with shapes or inference. Other worlds only check that no
282
+ shapes have appeared, and their writes don't hold each other up.
283
+ - **Giving up.** After 8 attempts the write fails with `ConcurrentWriteError`.
284
+ Nothing was written, so it can be sent again.
285
+ - **Cost.** One more row written per commit, and one more small read when inference
286
+ is on or the write adds shapes. Writes sent together to a world with shapes or
287
+ inference follow one another: 16 at once had a median of 1.2 to 1.9 seconds in a
288
+ local `worlds-api`, instead of 0.4 to 0.5.
289
+ - **Large commits.** One that doesn't fit in a batch checks only before its first
290
+ batch. A write between its batches can still break a shape with it or leave an
291
+ inferred fact wrong.
292
+ - **Not covered.** `backfillInference`, and writes that go through `D1RdfjsStore`
293
+ directly. Don't write to a world while it is backfilled.
294
+ - **Existing databases.** Opening a world adds the table. No migration is needed.
295
+ Writes from an older version aren't counted, so update every writer.
296
+
267
297
  ## Provenance (opt-in)
268
298
 
269
299
  A world can keep a record of when each quad was written or removed, by what, from
@@ -5,6 +5,49 @@
5
5
  * a world without shapes never loads the validator.
6
6
  */
7
7
  const SHAPES_GRAPH = "https://wazoo.dev/ns/worlds#shapes";
8
+ // src/cloudflare/commit/world-version.ts
9
+ /** A world that was never written has no row, which counts as version 0. */
10
+ const CURRENT_VERSION = "COALESCE((SELECT version FROM world_versions WHERE world_id = ?), 0)";
11
+ /**
12
+ * selectWorldVersion is the current version as a column of another query, so that
13
+ * both come from one moment.
14
+ */
15
+ function selectWorldVersion({ worldId }) {
16
+ return {
17
+ sql: `${CURRENT_VERSION} AS world_version`,
18
+ args: [worldId ?? ""]
19
+ };
20
+ }
21
+ /** buildWorldVersionsTable returns the DDL of the table that counts each world's writes. */
22
+ function buildWorldVersionsTable() {
23
+ return "CREATE TABLE IF NOT EXISTS world_versions (world_id TEXT PRIMARY KEY, version INTEGER NOT NULL) WITHOUT ROWID";
24
+ }
25
+ /** readWorldVersion reads the version. Call it before the reads that a commit relies on. */
26
+ async function readWorldVersion(connection, scope) {
27
+ const { sql, args } = selectWorldVersion(scope);
28
+ const { rows } = await connection.execute({
29
+ sql: `SELECT ${sql}`,
30
+ args
31
+ });
32
+ return Number(rows[0].world_version);
33
+ }
34
+ /**
35
+ * buildRaiseVersion counts one write. When `condition` no longer holds, it fails,
36
+ * and the rest of its batch with it: the version it then writes is NULL, which the
37
+ * table refuses. SQLite has no other way to stop a batch without a trigger.
38
+ */
39
+ function buildRaiseVersion({ worldId }, condition) {
40
+ const world = worldId ?? "";
41
+ const [holds, args] = condition === void 0 ? ["TRUE", []] : condition === "no shapes" ? [`NOT EXISTS (SELECT 1 FROM quads WHERE g = '${SHAPES_GRAPH}'${worldId ? " AND world_id = ?" : ""})`, worldId ? [worldId] : []] : [`${CURRENT_VERSION} = ?`, [world, condition.version]];
42
+ return {
43
+ sql: `INSERT INTO world_versions (world_id, version) VALUES (?, CASE WHEN ${holds} THEN 1 END) ON CONFLICT (world_id) DO UPDATE SET version = version + 1`,
44
+ args: [world, ...args]
45
+ };
46
+ }
47
+ /** isVersionConflict is true for the error of a batch that `buildRaiseVersion` stopped. */
48
+ function isVersionConflict(error) {
49
+ return error instanceof Error && error.message.includes("NOT NULL constraint failed: world_versions.version");
50
+ }
8
51
  // src/cloudflare/provenance/d1-provenance-sql.ts
9
52
  /**
10
53
  * PROVENANCE_IDS_PER_STATEMENT is how many quads one provenance statement
@@ -92,4 +135,4 @@ function buildSelectProvenanceChains(quadIds, worldId) {
92
135
  ]
93
136
  };
94
137
  }
95
- export { buildSelectQuadRecords as a, buildSelectProvenanceChains as i, buildProvenanceTable as n, chunk as o, buildSelectProvenance as r, SHAPES_GRAPH as s, buildInsertProvenance as t };
138
+ export { buildSelectQuadRecords as a, buildWorldVersionsTable as c, selectWorldVersion as d, SHAPES_GRAPH as f, buildSelectProvenanceChains as i, isVersionConflict as l, buildProvenanceTable as n, chunk as o, buildSelectProvenance as r, buildRaiseVersion as s, buildInsertProvenance as t, readWorldVersion as u };
@@ -310,4 +310,4 @@ function buildBulkInsertQuads(insertQuadRows, options = {}) {
310
310
  }
311
311
  return statements;
312
312
  }
313
- export { effectiveLookupChunkSize as _, buildSelectAssertedQuadsPage as a, buildDeleteDerivedQuadsByQuadIds as c, DEFAULT_D1_MATCH_PAGE_SIZE as d, buildInsertRow as f, DEFAULT_D1_MAX_WRITE_BATCH_SIZE as g, D1BatchExecutor as h, buildMatchQuadsQuery as i, buildDeleteQuadsByQuadIds as l, quadToInsertRow as m, buildCountAssertedQuads as n, buildSelectExistingQuadIds as o, quadFromD1Row as p, buildCountQuadsQuery as r, buildDeleteAllDerivedQuads as s, buildBulkInsertQuads as t, buildWipeAllGraphDataStatements as u };
313
+ export { DEFAULT_D1_MAX_WRITE_BATCH_SIZE as _, buildSelectAssertedQuadsPage as a, buildDeleteAllDerivedQuads as c, buildWipeAllGraphDataStatements as d, DEFAULT_D1_MATCH_PAGE_SIZE as f, D1BatchExecutor as g, quadToInsertRow as h, buildMatchQuadsQuery as i, buildDeleteDerivedQuadsByQuadIds as l, quadFromD1Row as m, buildCountAssertedQuads as n, buildSelectExistingQuadIds as o, buildInsertRow as p, buildCountQuadsQuery as r, buildD1QuadPatternWhereClause as s, buildBulkInsertQuads as t, buildDeleteQuadsByQuadIds as u, effectiveLookupChunkSize as v };
@@ -19,7 +19,7 @@ declare class D1SchemaBuilder {
19
19
  constructor(vectorDimensions: number, options?: D1SchemaBuilderOptions);
20
20
  /**
21
21
  * buildTables returns the idempotent DDL that creates the quads and chunks
22
- * tables in dependency order.
22
+ * tables in dependency order, and the table that counts each world's writes.
23
23
  */
24
24
  buildTables(): string[];
25
25
  /**
@@ -1,4 +1,4 @@
1
- import { n as buildProvenanceTable, s as SHAPES_GRAPH } from "./d1-provenance-sql-BRu7mIGI.js";
1
+ import { c as buildWorldVersionsTable, f as SHAPES_GRAPH, n as buildProvenanceTable } from "./d1-provenance-sql-CV6Mly6b.js";
2
2
  import { buildChunksQuadIdIndex } from "@wazootech/worlds-sqlite/sql-core";
3
3
  // src/cloudflare/validate-world-id.ts
4
4
  /**
@@ -29,12 +29,13 @@ var D1SchemaBuilder = class {
29
29
  }
30
30
  /**
31
31
  * buildTables returns the idempotent DDL that creates the quads and chunks
32
- * tables in dependency order.
32
+ * tables in dependency order, and the table that counts each world's writes.
33
33
  */
34
34
  buildTables() {
35
35
  return [
36
36
  this.buildD1QuadsTable(),
37
37
  this.buildD1ChunksTable(),
38
+ buildWorldVersionsTable(),
38
39
  ...this.provenance ? buildProvenanceTable(this.worldId) : []
39
40
  ];
40
41
  }
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { WorldsSdkInterface } from "@wazootech/worlds-sdk";
2
- import { A as ShaclOptions, C as D1SearchQueryBuilder, D as D1ClientBaseOptions, E as sanitizeFtsQuery, O as InferenceOptions, S as VectorizeIndexLike, T as RRF_REFERENCE_CONSTANT, _ as logVectorSyncDrift, a as RebuildD1SearchIndexFromQuadsResult, b as vectorSyncSucceeded, c as D1SearchIndexProjector, d as ProjectSearchChunksOptions, f as CloudflareSearchIndex, g as emptyVectorSyncReport, h as VectorSyncReport, i as ReadProjectSearchChunksOptions, k as ProvenanceOptions, l as D1SearchIndexProjectorOptions, m as CloudflareSearchIndexOptions, n as buildChunkFtsValue, o as createD1SearchIndexRebuilder, p as CloudflareReindexResponse, r as buildSearchResultId, s as rebuildD1SearchIndexFromQuads, t as BuildSearchResultIdOptions, u as D1VectorSync, v as mergeVectorSyncReports, w as D1SearchQueryBuilderOptions, x as VectorSearchIndex, y as recordVectorSyncError } from "./mod-B4BJr5j0.js";
2
+ import { A as ShaclOptions, C as D1SearchQueryBuilder, D as D1ClientBaseOptions, E as sanitizeFtsQuery, O as InferenceOptions, S as VectorizeIndexLike, T as RRF_REFERENCE_CONSTANT, _ as logVectorSyncDrift, a as RebuildD1SearchIndexFromQuadsResult, b as vectorSyncSucceeded, c as D1SearchIndexProjector, d as ProjectSearchChunksOptions, f as CloudflareSearchIndex, g as emptyVectorSyncReport, h as VectorSyncReport, i as ReadProjectSearchChunksOptions, k as ProvenanceOptions, l as D1SearchIndexProjectorOptions, m as CloudflareSearchIndexOptions, n as buildChunkFtsValue, o as createD1SearchIndexRebuilder, p as CloudflareReindexResponse, r as buildSearchResultId, s as rebuildD1SearchIndexFromQuads, t as BuildSearchResultIdOptions, u as D1VectorSync, v as mergeVectorSyncReports, w as D1SearchQueryBuilderOptions, x as VectorSearchIndex, y as recordVectorSyncError } from "./mod-a3SVCa8c.js";
3
3
  import { a as D1Statement, i as D1Result, n as D1DatabaseLike, r as D1PreparedStatementLike, t as D1ConnectionDriver } from "./d1-connection-driver-DfBsnVwn.js";
4
- import { t as D1SchemaBuilder } from "./d1-schema-builder-BLPr77rK.js";
5
- import { i as D1QuadStream, n as D1RdfjsStoreOptions, r as D1Transaction, t as D1RdfjsStore } from "./mod-BjVVdQCh.js";
6
- import { n as D1QuadStoreOptions, t as D1QuadStore } from "./mod-BfGKU5Gt.js";
4
+ import { t as D1SchemaBuilder } from "./d1-schema-builder-BZMZ8CCv.js";
5
+ import { i as D1QuadStream, n as D1RdfjsStoreOptions, r as D1Transaction, t as D1RdfjsStore } from "./mod-Bkjkds_5.js";
6
+ import { n as D1QuadStoreOptions, t as D1QuadStore } from "./mod-C6Nc-jgN.js";
7
7
  import { InMemoryProvenanceStore, ProvenanceHistory, ProvenanceListQuery, ProvenanceRecord, ProvenanceRecordInput, ProvenanceStore } from "@wazootech/worlds-sdk/quad-store";
8
8
  import "@rdfjs/types";
9
9
  import { Inconsistency } from "@wazootech/reasoner";
@@ -125,6 +125,13 @@ export declare class InferenceSizeGuardError extends Error {
125
125
  readonly maxAssertedQuads: number;
126
126
  constructor(assertedQuads: number, maxAssertedQuads: number);
127
127
  }
128
+ /**
129
+ * ConcurrentWriteError is thrown when other writes changed the world during every
130
+ * attempt to commit. Nothing was written, so the same write can be sent again.
131
+ */
132
+ export declare class ConcurrentWriteError extends Error {
133
+ constructor(options?: ErrorOptions);
134
+ }
128
135
  /** BackfillInferenceOptions selects the world and the reasoning settings. */
129
136
  interface BackfillInferenceOptions {
130
137
  /** database is the D1 binding. */
@@ -184,9 +191,9 @@ interface PurgeWorldResult {
184
191
  /**
185
192
  * purgeWorld deletes every derived copy of a world's data: the `quads` rows
186
193
  * (asserted and inference-derived alike), the `chunks` rows (whose AFTER
187
- * DELETE trigger maintains `chunks_fts`), its `provenance` records, and — when a vectorSearch is
188
- * configured — every vector the index holds for the world
189
- * (worlds-cloudflare#71 item 6).
194
+ * DELETE trigger maintains `chunks_fts`), its `provenance` records, the count of
195
+ * its writes, and — when a vectorSearch is configured — every vector the index
196
+ * holds for the world (worlds-cloudflare#71 item 6).
190
197
  *
191
198
  * The D1 statements run as one atomic batch, so the store is either fully
192
199
  * purged or untouched. The vector purge runs after the D1 batch commits:
package/dist/index.js CHANGED
@@ -1,13 +1,28 @@
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-_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
- import { a as DEFAULT_D1_MAX_BATCH_WEIGHT, o as d1StatementWeight } from "./project-search-chunks-options-qI9m5FWz.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-Cw8CTAjm.js";
4
+ import { a as InferenceSizeGuardError, n as D1ProvenanceStore, o as loadAssertedQuads, r as ConcurrentWriteError, s as planInference, t as D1QuadStore } from "./quad-store-DW0XVyvC.js";
5
+ import { a as DEFAULT_D1_MAX_BATCH_WEIGHT, o as d1StatementWeight } from "./project-search-chunks-options-CAxR9V4v.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-8V0H0fGC.js";
9
- import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-Dj0dTBxX.js";
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";
8
+ import { i as D1QuadStream, n as assertD1SchemaCompatible, r as checkD1SchemaCompatibility, t as D1RdfjsStore } from "./rdfjs-store-CES_vSLm.js";
9
+ import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-hkZBWMiA.js";
10
+ import { _ as DEFAULT_D1_MAX_WRITE_BATCH_SIZE, c as buildDeleteAllDerivedQuads, d as buildWipeAllGraphDataStatements, g as D1BatchExecutor, h as quadToInsertRow, t as buildBulkInsertQuads } from "./d1-quad-insert-sql-Cp5oSqIG.js";
11
+ // src/cloudflare/search-index/vector-search/physical-vector-id.ts
12
+ /**
13
+ * physicalVectorId namespaces a contract search-result id by world. Vectorize
14
+ * caps ids at 64 bytes, so the pair is hashed (SHA-256, base64url: 45
15
+ * characters with the prefix) instead of concatenated.
16
+ */
17
+ async function physicalVectorId(worldId, resultId) {
18
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${worldId}\u0000${resultId}`));
19
+ return `v.${base64Url(new Uint8Array(digest))}`;
20
+ }
21
+ function base64Url(bytes) {
22
+ let binary = "";
23
+ for (const byte of bytes) binary += String.fromCharCode(byte);
24
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
25
+ }
11
26
  // src/cloudflare/search-index/vector-search/vectorize-provisioning.ts
12
27
  /**
13
28
  * Vectorize provisioning contract (worlds-cloudflare#38).
@@ -29,6 +44,12 @@ const RESULT_ID_KEY = "result_id";
29
44
  /** WORLD_ID_KEY is the filterable metadata key that scopes vectors per world. */
30
45
  const WORLD_ID_KEY = VECTORIZE_FILTERABLE_PROPERTY;
31
46
  /**
47
+ * MAX_IDS_PER_READ is the most ids one `getByIds` call accepts. Cloudflare's
48
+ * limits page leaves it out; the API rejects more with error 40007, "max id count
49
+ * is 20".
50
+ */
51
+ const MAX_IDS_PER_READ = 20;
52
+ /**
32
53
  * VectorizeVectorSearchIndex implements VectorSearchIndex over a Cloudflare
33
54
  * Vectorize binding.
34
55
  *
@@ -51,10 +72,13 @@ const WORLD_ID_KEY = VECTORIZE_FILTERABLE_PROPERTY;
51
72
  var VectorizeVectorSearchIndex = class {
52
73
  options;
53
74
  worldId;
75
+ /** getByIds is missing when the binding cannot read vectors. */
76
+ getByIds;
54
77
  constructor(options) {
55
78
  this.options = options;
56
79
  if (typeof options.worldId !== "string" || options.worldId.length === 0) throw new Error("VectorizeVectorSearchIndex requires a worldId: the Vectorize index is shared across worlds");
57
80
  this.worldId = options.worldId;
81
+ if (options.index.getByIds) this.getByIds = (ids) => this.readByIds(ids);
58
82
  }
59
83
  async query(vector, options) {
60
84
  const requested = options.filter?.[WORLD_ID_KEY];
@@ -83,7 +107,7 @@ var VectorizeVectorSearchIndex = class {
83
107
  const stated = entry.metadata[WORLD_ID_KEY];
84
108
  if (stated !== void 0 && stated !== this.worldId) throw new Error(`Vector ${entry.id} is labelled for world ${stated}, but this index is scoped to ${this.worldId}`);
85
109
  vectors.push({
86
- id: await this.physicalId(entry.id),
110
+ id: await physicalVectorId(this.worldId, entry.id),
87
111
  values: Array.from(entry.vector),
88
112
  metadata: {
89
113
  ...entry.metadata,
@@ -96,28 +120,29 @@ var VectorizeVectorSearchIndex = class {
96
120
  }
97
121
  async deleteByIds(ids) {
98
122
  if (ids.length === 0) return;
99
- await this.options.index.deleteByIds(await Promise.all(ids.map((id) => this.physicalId(id))));
123
+ await this.options.index.deleteByIds(await Promise.all(ids.map((id) => physicalVectorId(this.worldId, id))));
124
+ }
125
+ /** readByIds reads vectors with as many calls at once as the ids need. */
126
+ async readByIds(ids) {
127
+ const resultIds = /* @__PURE__ */ new Map();
128
+ for (const id of ids) resultIds.set(await physicalVectorId(this.worldId, id), id);
129
+ const physicalIds = [...resultIds.keys()];
130
+ const reads = [];
131
+ for (let at = 0; at < physicalIds.length; at += MAX_IDS_PER_READ) {
132
+ const page = physicalIds.slice(at, at + MAX_IDS_PER_READ);
133
+ reads.push(this.options.index.getByIds(page));
134
+ }
135
+ return (await Promise.all(reads)).flat().map(({ id, values }) => ({
136
+ id: resultIds.get(id),
137
+ vector: values
138
+ }));
100
139
  }
101
140
  async deleteAll() {
102
141
  const deleter = this.options.index.deleteByMetadataFilter;
103
142
  if (typeof deleter !== "function") throw new Error("deleteAll requires a Vectorize binding with deleteByMetadataFilter (and a metadata index on world_id); upgrade the binding and re-provision the metadata index");
104
143
  await deleter.call(this.options.index, { filter: { [WORLD_ID_KEY]: this.worldId } });
105
144
  }
106
- /**
107
- * physicalId namespaces a contract search-result id by world. Vectorize
108
- * caps ids at 64 bytes, so the pair is hashed (SHA-256, base64url: 45
109
- * characters with the prefix) instead of concatenated.
110
- */
111
- async physicalId(resultId) {
112
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${this.worldId}\u0000${resultId}`));
113
- return `v.${base64Url(new Uint8Array(digest))}`;
114
- }
115
145
  };
116
- function base64Url(bytes) {
117
- let binary = "";
118
- for (const byte of bytes) binary += String.fromCharCode(byte);
119
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
120
- }
121
146
  function metadataToRecord(metadata) {
122
147
  if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return;
123
148
  const result = {};
@@ -427,9 +452,9 @@ async function backfillInference(options) {
427
452
  /**
428
453
  * purgeWorld deletes every derived copy of a world's data: the `quads` rows
429
454
  * (asserted and inference-derived alike), the `chunks` rows (whose AFTER
430
- * DELETE trigger maintains `chunks_fts`), its `provenance` records, and — when a vectorSearch is
431
- * configured — every vector the index holds for the world
432
- * (worlds-cloudflare#71 item 6).
455
+ * DELETE trigger maintains `chunks_fts`), its `provenance` records, the count of
456
+ * its writes, and — when a vectorSearch is configured — every vector the index
457
+ * holds for the world (worlds-cloudflare#71 item 6).
433
458
  *
434
459
  * The D1 statements run as one atomic batch, so the store is either fully
435
460
  * purged or untouched. The vector purge runs after the D1 batch commits:
@@ -439,11 +464,11 @@ async function backfillInference(options) {
439
464
  async function purgeWorld(options) {
440
465
  const { worldId } = options;
441
466
  if (typeof worldId !== "string" || worldId.length === 0) throw new Error("purgeWorld: worldId must be a non-empty string; refusing to run an unscoped purge across every world in the database");
442
- const { rows } = await options.connection.execute({ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'provenance'" });
443
- await options.connection.batch([...buildWipeAllGraphDataStatements(worldId), ...rows.length > 0 ? [{
444
- sql: "DELETE FROM provenance WHERE world_id = ?",
467
+ const { rows } = await options.connection.execute({ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('provenance', 'world_versions')" });
468
+ await options.connection.batch([...buildWipeAllGraphDataStatements(worldId), ...rows.map(({ name }) => ({
469
+ sql: `DELETE FROM ${name} WHERE world_id = ?`,
445
470
  args: [worldId]
446
- }] : []]);
471
+ }))]);
447
472
  if (!options.vectorSearch) return {
448
473
  vectorsPurged: false,
449
474
  vectorsSkipped: true
@@ -454,4 +479,4 @@ async function purgeWorld(options) {
454
479
  vectorsSkipped: false
455
480
  };
456
481
  }
457
- export { CloudflareSearchIndex, D1ConnectionDriver, D1ProvenanceStore, D1QuadStore, D1QuadStream, D1RdfjsStore, D1SchemaBuilder, D1SearchIndexProjector, D1SearchQueryBuilder, D1VectorSync, DEFAULT_D1_MAX_BATCH_WEIGHT, DEFAULT_D1_MAX_WRITE_BATCH_SIZE, InferenceSizeGuardError, RRF_REFERENCE_CONSTANT, assertD1SchemaCompatible, backfillInference, buildChunkFtsValue, buildSearchResultId, checkD1SchemaCompatibility, createCloudflareWorldsSdk, createD1SearchIndexRebuilder, d1StatementWeight, emptyVectorSyncReport, logVectorSyncDrift, mergeVectorSyncReports, purgeWorld, rebuildD1SearchIndexFromQuads, recordVectorSyncError, sanitizeFtsQuery, validateWorldId, vectorSyncSucceeded };
482
+ export { CloudflareSearchIndex, ConcurrentWriteError, D1ConnectionDriver, D1ProvenanceStore, D1QuadStore, D1QuadStream, D1RdfjsStore, D1SchemaBuilder, D1SearchIndexProjector, D1SearchQueryBuilder, D1VectorSync, DEFAULT_D1_MAX_BATCH_WEIGHT, DEFAULT_D1_MAX_WRITE_BATCH_SIZE, InferenceSizeGuardError, RRF_REFERENCE_CONSTANT, assertD1SchemaCompatible, backfillInference, buildChunkFtsValue, buildSearchResultId, checkD1SchemaCompatibility, createCloudflareWorldsSdk, createD1SearchIndexRebuilder, d1StatementWeight, emptyVectorSyncReport, logVectorSyncDrift, mergeVectorSyncReports, purgeWorld, rebuildD1SearchIndexFromQuads, recordVectorSyncError, sanitizeFtsQuery, validateWorldId, vectorSyncSucceeded };
@@ -0,0 +1,128 @@
1
+ import { m as quadFromD1Row, s as buildD1QuadPatternWhereClause } from "./d1-quad-insert-sql-Cp5oSqIG.js";
2
+ // src/cloudflare/quad-store/d1-quad-page-sql.ts
3
+ /** TEXT_COLUMNS hold the text of a quad, which can be any length. */
4
+ const TEXT_COLUMNS = [
5
+ "s",
6
+ "p",
7
+ "o",
8
+ "o_datatype",
9
+ "o_lang",
10
+ "g"
11
+ ];
12
+ /**
13
+ * ROW_BYTES is how many bytes of text a row holds. SQLite stores the length of
14
+ * a value before the value, so octet_length does not read the text itself.
15
+ */
16
+ const ROW_BYTES = TEXT_COLUMNS.map((column) => column === "o_datatype" || column === "o_lang" ? `COALESCE(octet_length(${column}), 0)` : `octet_length(${column})`).join(" + ");
17
+ /**
18
+ * buildMatchQuadsPage reads one page of the quads matching the pattern, in the
19
+ * order of their ids. A row with more text than `maxRowBytes` comes without its
20
+ * text, and with its size as `large_bytes` (otherwise null).
21
+ */
22
+ function buildMatchQuadsPage(pattern, page, worldId) {
23
+ const { conditions, args } = buildD1QuadPatternWhereClause(pattern);
24
+ if (worldId) {
25
+ conditions.push("world_id = ?");
26
+ args.push(worldId);
27
+ }
28
+ if (page.afterQuadId) {
29
+ conditions.push("quad_id > ?");
30
+ args.push(page.afterQuadId);
31
+ }
32
+ args.push(String(Math.max(1, Math.floor(page.limit))));
33
+ const fits = `${ROW_BYTES} <= ${Math.max(0, Math.floor(page.maxRowBytes))}`;
34
+ return {
35
+ sql: `SELECT quad_id AS id, s_type, o_type, g_type, ${TEXT_COLUMNS.map((column) => `CASE WHEN ${fits} THEN ${column} END AS ${column}`).join(", ")}, CASE WHEN NOT (${fits}) THEN ${ROW_BYTES} END AS large_bytes FROM quads ${conditions.length > 0 ? `WHERE ${conditions.join(" AND ")} ` : ""}ORDER BY quad_id ASC LIMIT ?`,
36
+ args
37
+ };
38
+ }
39
+ /**
40
+ * buildSelectQuadsById reads whole rows by their ids, in any order. CROSS JOIN
41
+ * makes SQLite look up each id, and never scan the quads instead.
42
+ */
43
+ function buildSelectQuadsById(quadIds, worldId) {
44
+ return {
45
+ sql: `SELECT quad_id AS id, s, s_type, p, o, o_type, o_datatype, o_lang, g, g_type FROM json_each(?) AS ids CROSS JOIN quads ON quad_id = ids.value${worldId ? " AND world_id = ?" : ""}`,
46
+ args: [JSON.stringify(quadIds), ...worldId ? [worldId] : []]
47
+ };
48
+ }
49
+ // src/cloudflare/rdfjs-store/match-d1-pages.ts
50
+ /**
51
+ * D1_READ_BYTES is the most bytes of text that one query of a read returns,
52
+ * unless a single quad has more.
53
+ */
54
+ const D1_READ_BYTES = 4e6;
55
+ /** MAX_IDS is the most rows one query looks up, so that their ids fit in a parameter. */
56
+ const MAX_IDS = 1e3;
57
+ /** matchD1Pages keyset-pages the quads matching a pattern, in the order of their ids. */
58
+ async function* matchD1Pages(connection, matchPageSize, worldId, subject, predicate, object, graph, readBytes = D1_READ_BYTES) {
59
+ const pattern = {
60
+ subject: subject ?? null,
61
+ predicate: predicate ?? null,
62
+ object: object ?? null,
63
+ graph: graph ?? null
64
+ };
65
+ const limit = Math.max(1, Math.floor(matchPageSize));
66
+ let afterQuadId;
67
+ for (;;) {
68
+ const { rows } = await connection.execute(buildMatchQuadsPage(pattern, {
69
+ afterQuadId,
70
+ limit,
71
+ maxRowBytes: readBytes / limit
72
+ }, worldId));
73
+ const large = new LargeRows(connection, rows, worldId, readBytes);
74
+ for (const [index, row] of rows.entries()) {
75
+ const whole = row.large_bytes === null ? row : await large.read(index);
76
+ if (whole) yield quadFromD1Row(whole);
77
+ }
78
+ if (rows.length < limit) return;
79
+ afterQuadId = String(rows[rows.length - 1].id);
80
+ }
81
+ }
82
+ /**
83
+ * LargeRows reads the rows of a page that came without their text, when the page
84
+ * gets to them: as many at a time as fit in `readBytes`, or one that does not fit
85
+ * on its own.
86
+ */
87
+ var LargeRows = class {
88
+ connection;
89
+ page;
90
+ worldId;
91
+ readBytes;
92
+ loaded = /* @__PURE__ */ new Map();
93
+ loadedUntil = 0;
94
+ constructor(connection, page, worldId, readBytes) {
95
+ this.connection = connection;
96
+ this.page = page;
97
+ this.worldId = worldId;
98
+ this.readBytes = readBytes;
99
+ }
100
+ /** read returns the row at `index`, or undefined if it was deleted since. */
101
+ async read(index) {
102
+ if (index >= this.loadedUntil) {
103
+ const { rows } = await this.connection.execute(buildSelectQuadsById(this.nextIds(index), this.worldId));
104
+ for (const row of rows) this.loaded.set(String(row.id), row);
105
+ }
106
+ const id = String(this.page[index].id);
107
+ const row = this.loaded.get(id);
108
+ this.loaded.delete(id);
109
+ return row;
110
+ }
111
+ /** nextIds takes the large rows from `index` on that fit in one read. */
112
+ nextIds(index) {
113
+ const ids = [];
114
+ let bytes = 0;
115
+ let next = index;
116
+ for (; next < this.page.length; next++) {
117
+ const row = this.page[next];
118
+ if (row.large_bytes === null) continue;
119
+ bytes += Number(row.large_bytes);
120
+ if (ids.length > 0 && bytes > this.readBytes) break;
121
+ if (ids.length === MAX_IDS) break;
122
+ ids.push(String(row.id));
123
+ }
124
+ this.loadedUntil = next;
125
+ return ids;
126
+ }
127
+ };
128
+ export { matchD1Pages as t };
@@ -1,7 +1,7 @@
1
1
  import * as rdfjs from "@rdfjs/types";
2
2
  import { Patch, TransactionContext } from "@wazootech/worlds-sdk/quad-store";
3
3
  import { t as D1ConnectionDriver } from "./d1-connection-driver-DfBsnVwn.js";
4
- import { t as D1SchemaBuilder } from "./d1-schema-builder-BLPr77rK.js";
4
+ import { t as D1SchemaBuilder } from "./d1-schema-builder-BZMZ8CCv.js";
5
5
  type Listener = (...args: any[]) => void;
6
6
  /**
7
7
  * D1QuadStream is a minimal RDF/JS Stream backed by an async page generator
@@ -1,7 +1,7 @@
1
1
  import { ExportRequest, ExportResponse, ImportRequest, ProvenanceQueryHandler, ProvenanceQueryRequest, ProvenanceQueryResponse, QuadStoreInterface, Transaction, TransactionContext } from "@wazootech/worlds-sdk/quad-store";
2
- import { C as D1SearchQueryBuilder, D as D1ClientBaseOptions, c as D1SearchIndexProjector } from "./mod-B4BJr5j0.js";
2
+ import { C as D1SearchQueryBuilder, D as D1ClientBaseOptions, c as D1SearchIndexProjector } from "./mod-a3SVCa8c.js";
3
3
  import { t as D1ConnectionDriver } from "./d1-connection-driver-DfBsnVwn.js";
4
- import { t as D1RdfjsStore } from "./mod-BjVVdQCh.js";
4
+ import { t as D1RdfjsStore } from "./mod-Bkjkds_5.js";
5
5
  /**
6
6
  * D1QuadStoreOptions defines the configurations for the D1QuadStore.
7
7
  */
@@ -185,7 +185,7 @@ interface VectorSearchQueryOptions {
185
185
  }
186
186
  /**
187
187
  * VectorizeIndexLike is the minimal Vectorize binding surface the hosted
188
- * seam uses: query (similarity search), upsert, and deleteByIds. Cloudflare's
188
+ * seam uses: query (similarity search), upsert, deleteByIds, and getByIds. Cloudflare's
189
189
  * real `VectorizeIndex` binding satisfies it structurally (like
190
190
  * D1DatabaseLike), so tests can also exercise it with call-sites that accept
191
191
  * either.
@@ -206,6 +206,15 @@ interface VectorizeIndexLike {
206
206
  metadata?: Record<string, string>;
207
207
  }>): Promise<unknown>;
208
208
  deleteByIds(ids: string[]): Promise<unknown>;
209
+ /**
210
+ * getByIds reads stored vectors, and skips unknown ids. Optional so older
211
+ * bindings and test doubles stay structurally assignable; without it, every
212
+ * search filter runs after the index's ranking.
213
+ */
214
+ getByIds?(ids: string[]): Promise<Array<{
215
+ id: string;
216
+ values: ArrayLike<number>;
217
+ }>>;
209
218
  /**
210
219
  * deleteByMetadataFilter deletes every vector whose metadata matches the
211
220
  * filter. Requires a metadata index on the filtered property (provisioning
@@ -240,6 +249,14 @@ interface VectorSearchIndex {
240
249
  upsert(entries: VectorSearchEntry[]): Promise<void>;
241
250
  /** deleteByIds removes entries by id (best-effort for unknown ids). */
242
251
  deleteByIds(ids: string[]): Promise<void>;
252
+ /**
253
+ * getByIds returns the stored vectors of these entry ids, in any order and
254
+ * without the unknown ones. Searches use it to score a small filtered set.
255
+ */
256
+ getByIds?(ids: string[]): Promise<Array<{
257
+ id: string;
258
+ vector: ArrayLike<number>;
259
+ }>>;
243
260
  /**
244
261
  * deleteAll removes every vector this index instance owns (worlds-cloudflare#71 item 3).
245
262
  * The Vectorize implementation is world-scoped, so this purges one world;
@@ -342,8 +359,8 @@ interface CloudflareSearchIndexOptions extends D1ClientBaseOptions {
342
359
  * vectorSearch are wired, the query is embedded and the two lists fuse.
343
360
  *
344
361
  * Ranked semantics come from the reported `mode` — hybrid (both lists),
345
- * semantic (vector-only), keyword (FTS-only). No JS cosine fallback exists
346
- * per the cloudflare architecture decision (worlds-sdk-ts#63); any vector
362
+ * semantic (vector-only), keyword (FTS-only). Only a filter that leaves few
363
+ * chunks is scored here instead of by the index (see searchVectors); any vector
347
364
  * failure degrades gracefully to keyword-only.
348
365
  */
349
366
  declare class CloudflareSearchIndex implements SearchIndexInterface {
@@ -1,4 +1,4 @@
1
- import { _ as effectiveLookupChunkSize, a as buildSelectAssertedQuadsPage, c as buildDeleteDerivedQuadsByQuadIds, f as buildInsertRow, i as buildMatchQuadsQuery, l as buildDeleteQuadsByQuadIds, o as buildSelectExistingQuadIds, p as quadFromD1Row, t as buildBulkInsertQuads, u as buildWipeAllGraphDataStatements } from "./d1-quad-insert-sql-B4ZiZZe8.js";
1
+ import { a as buildSelectAssertedQuadsPage, d as buildWipeAllGraphDataStatements, i as buildMatchQuadsQuery, l as buildDeleteDerivedQuadsByQuadIds, m as quadFromD1Row, o as buildSelectExistingQuadIds, p as buildInsertRow, t as buildBulkInsertQuads, u as buildDeleteQuadsByQuadIds, v as effectiveLookupChunkSize } from "./d1-quad-insert-sql-Cp5oSqIG.js";
2
2
  import { buildChunkFtsValue } from "@wazootech/worlds-sqlite/sql-core";
3
3
  import { filterQuads } from "@wazootech/worlds-sdk/quad-store";
4
4
  // src/cloudflare/commit/d1-commit-dialect.ts
@@ -1,11 +1,11 @@
1
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
- 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";
4
+ import { a as buildSelectAssertedQuadsPage, f as DEFAULT_D1_MATCH_PAGE_SIZE, m as quadFromD1Row, n as buildCountAssertedQuads, p as buildInsertRow, v as effectiveLookupChunkSize } from "./d1-quad-insert-sql-Cp5oSqIG.js";
5
+ import { a as buildSelectQuadRecords, d as selectWorldVersion, f as SHAPES_GRAPH, i as buildSelectProvenanceChains, l as isVersionConflict, o as chunk, r as buildSelectProvenance, s as buildRaiseVersion, t as buildInsertProvenance, u as readWorldVersion } from "./d1-provenance-sql-CV6Mly6b.js";
5
6
  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
- import { i as createD1CommitDriver, s as createD1CommitDialect, t as isFullRebuild } from "./project-search-chunks-options-qI9m5FWz.js";
8
- import { r as matchD1Pages } from "./d1-rdfjs-store-read-2QTEEe_a.js";
7
+ import { i as createD1CommitDriver, o as d1StatementWeight, s as createD1CommitDialect, t as isFullRebuild } from "./project-search-chunks-options-CAxR9V4v.js";
8
+ import { t as matchD1Pages } from "./match-d1-pages-hRKVbawI.js";
9
9
  /** LISTS_PER_STATEMENT keeps a statement inside D1's 100 parameters and a batch's byte budget. */
10
10
  const LISTS_PER_STATEMENT = 16;
11
11
  /** packLists splits items over as many JSON lists as D1's value size needs, and at least one. */
@@ -324,12 +324,29 @@ function dedupe(quads) {
324
324
  const MAX_SHAPE_QUADS = 1e4;
325
325
  const VALUES_PER_STATEMENT = 2e3;
326
326
  const CHARACTERS_PER_STATEMENT = 4e5;
327
+ const COLUMNS = "s, s_type, p, o, o_type, o_datatype, o_lang, g, g_type";
328
+ /**
329
+ * readShapes reads a world's shapes, and the version the world had then. Without
330
+ * shapes there is no version, because no row carries it.
331
+ */
332
+ async function readShapes(options) {
333
+ const { connection, worldId, inferenceEnabled } = options;
334
+ const version = selectWorldVersion(options);
335
+ const { rows } = await connection.execute({
336
+ sql: `SELECT ${COLUMNS}, ${version.sql} FROM quads WHERE g = '${SHAPES_GRAPH}'${inferenceEnabled ? " AND derived = 0" : ""}${worldId ? " AND world_id = ?" : ""} LIMIT 10001`,
337
+ args: [...version.args, ...worldId ? [worldId] : []]
338
+ });
339
+ return {
340
+ shapes: rows.map(quadFromD1Row),
341
+ version: rows[0] && Number(rows[0].world_version)
342
+ };
343
+ }
327
344
  /** createD1ShaclSource reads the facts that a SHACL check asks for from D1. */
328
345
  function createD1ShaclSource(options) {
329
- const { connection, worldId, inferenceEnabled } = options;
330
- async function select(condition, args, limit, world = "world_id") {
346
+ const { connection, worldId } = options;
347
+ async function select(condition, args, limit) {
331
348
  const { rows } = await connection.execute({
332
- sql: `SELECT s, s_type, p, o, o_type, o_datatype, o_lang, g, g_type FROM quads WHERE ${condition}${worldId ? ` AND ${world} = ?` : ""} LIMIT ${Math.min(Math.floor(limit), Number.MAX_SAFE_INTEGER)}`,
349
+ sql: `SELECT ${COLUMNS} FROM quads WHERE ${condition}${worldId ? " AND +world_id = ?" : ""} LIMIT ${Math.min(Math.floor(limit), Number.MAX_SAFE_INTEGER)}`,
333
350
  args: worldId ? [...args, worldId] : args
334
351
  });
335
352
  return rows.map(quadFromD1Row);
@@ -339,14 +356,14 @@ function createD1ShaclSource(options) {
339
356
  const found = [];
340
357
  const among = (name) => `${name} IN (SELECT value FROM json_each(?))`;
341
358
  for (const values of groupValues(terms)) {
342
- const rows = await select(`${predicates ? `${among("p")} AND ` : ""}${among(column)} AND g <> '${SHAPES_GRAPH}'`, [...predicates ? [JSON.stringify(predicates)] : [], values], limit + 1 - found.length, "+world_id");
359
+ const rows = await select(`${predicates ? `${among("p")} AND ` : ""}${among(column)} AND g <> '${SHAPES_GRAPH}'`, [...predicates ? [JSON.stringify(predicates)] : [], values], limit + 1 - found.length);
343
360
  for (const row of rows) found.push(row);
344
361
  if (found.length > limit) break;
345
362
  }
346
363
  return found;
347
364
  }
348
365
  return {
349
- shapes: () => select(`g = '${SHAPES_GRAPH}'${inferenceEnabled ? " AND derived = 0" : ""}`, [], 10001),
366
+ shapes: async () => (await readShapes(options)).shapes,
350
367
  outgoing: ({ subjects, predicates, limit }) => selectAmong("s", subjects, predicates, limit),
351
368
  incoming: ({ objects, predicate, limit }) => selectAmong("o", objects, [predicate], limit)
352
369
  };
@@ -372,19 +389,26 @@ function* groupValues(terms) {
372
389
  * shapes, counting the inferred quads it adds and removes. Call it before
373
390
  * anything is written. A world without shapes costs one indexed read, and never
374
391
  * loads the validator.
392
+ *
393
+ * It returns what must still be true when the commit is written for the check to
394
+ * count. A replace import relies on nothing that is stored.
375
395
  */
376
396
  async function checkD1Patch(patch, context, options, derived) {
377
- if (options.shacl?.enabled === false) return;
397
+ if (options.shacl?.enabled === false) return void 0;
378
398
  const matches = filterQuads(options);
379
399
  const insertions = patch.insertions.filter(matches);
380
400
  const deletions = patch.deletions.filter(matches);
381
- const source = createD1ShaclSource({
401
+ const sourceOptions = {
382
402
  connection: options.connection,
383
403
  worldId: options.worldId,
384
404
  inferenceEnabled: options.inference?.enabled === true
385
- });
386
- const shapes = isReplaceImportCommit(context) ? [] : await source.shapes();
387
- if (shapes.length === 0 && !insertions.some(isShape)) return;
405
+ };
406
+ const source = createD1ShaclSource(sourceOptions);
407
+ const replacing = isReplaceImportCommit(context);
408
+ const addsShapes = insertions.some(isShape);
409
+ const before = addsShapes && !replacing ? await readWorldVersion(options.connection, options) : void 0;
410
+ const { shapes, version = before } = replacing ? { shapes: [] } : await readShapes(sourceOptions);
411
+ if (shapes.length === 0 && !addsShapes) return replacing ? void 0 : "no shapes";
388
412
  const { InvalidShapesError, validateWrite } = await import("@wazootech/worlds-sdk/shacl");
389
413
  if (countShapesAfter(shapes, insertions, deletions) > 1e4) throw new InvalidShapesError([`A world can have at most ${MAX_SHAPE_QUADS} quads of shapes.`]);
390
414
  await validateWrite({
@@ -399,6 +423,7 @@ async function checkD1Patch(patch, context, options, derived) {
399
423
  },
400
424
  maxCheckedFacts: options.shacl?.maxCheckedFacts
401
425
  });
426
+ return version === void 0 ? void 0 : { version };
402
427
  }
403
428
  function isShape(quad) {
404
429
  return quad.graph.value === SHAPES_GRAPH;
@@ -484,6 +509,86 @@ async function planD1DerivedChanges(patch, context, inference, driverOptions) {
484
509
  added: derived
485
510
  };
486
511
  }
512
+ // src/cloudflare/commit/remember-embeddings.ts
513
+ /**
514
+ * rememberEmbeddings embeds each text once, however often a commit is planned.
515
+ * Embedding is the slow and paid part, and the longer an attempt takes, the likelier
516
+ * another write gets in between.
517
+ */
518
+ function rememberEmbeddings(service) {
519
+ const known = /* @__PURE__ */ new Map();
520
+ return { async embed(texts) {
521
+ const unknown = texts.filter((text) => !known.has(text));
522
+ if (unknown.length > 0) (await service.embed(unknown)).forEach((vector, i) => known.set(unknown[i], vector));
523
+ return texts.map((text) => known.get(text));
524
+ } };
525
+ }
526
+ /** No single wait is longer than this, in milliseconds. */
527
+ const LONGEST_WAIT = 5e3;
528
+ /**
529
+ * ConcurrentWriteError is thrown when other writes changed the world during every
530
+ * attempt to commit. Nothing was written, so the same write can be sent again.
531
+ */
532
+ var ConcurrentWriteError = class extends Error {
533
+ constructor(options) {
534
+ super(`Other writes changed this world during all 8 attempts to commit. Nothing was written. Try again.`, options);
535
+ this.name = "ConcurrentWriteError";
536
+ }
537
+ };
538
+ /**
539
+ * retryOnConflict runs `attempt` again when another write got in between its reads
540
+ * and its batch. Any other error would come back the same, so it is thrown.
541
+ *
542
+ * Writes that collide need random waits that are long compared with an attempt, or
543
+ * they collide again. So a wait is at most twice as long as the attempt before it
544
+ * took, and that factor doubles each time.
545
+ */
546
+ async function retryOnConflict(attempt) {
547
+ for (let tried = 1;; tried++) {
548
+ const start = performance.now();
549
+ try {
550
+ return await attempt();
551
+ } catch (error) {
552
+ if (!isVersionConflict(error)) throw error;
553
+ if (tried === 8) throw new ConcurrentWriteError({ cause: error });
554
+ }
555
+ const took = performance.now() - start;
556
+ const longest = Math.min(took * 2 ** tried, LONGEST_WAIT);
557
+ const wait = Math.random() * longest;
558
+ await new Promise((resolve) => setTimeout(resolve, wait));
559
+ }
560
+ }
561
+ // src/cloudflare/commit/with-world-version.ts
562
+ /**
563
+ * withWorldVersion makes a commit's first statement the one that counts it and
564
+ * checks `condition`, so a commit that can't go ahead writes nothing. Apply it last,
565
+ * and create one per commit.
566
+ *
567
+ * A commit too large for one batch checks the condition in its first batch only. Its
568
+ * other batches count as writes too, so a commit that read a half-written world
569
+ * plans again. Call `finish` when the last one is written.
570
+ */
571
+ function withWorldVersion(driver, dialect, scope, condition) {
572
+ const first = buildRaiseVersion(scope, condition);
573
+ const counting = buildRaiseVersion(scope);
574
+ const pending = [first];
575
+ let writing = true;
576
+ return {
577
+ driver: {
578
+ ...driver,
579
+ maxBatchWeight: driver.maxBatchWeight && Math.max(0, driver.maxBatchWeight - d1StatementWeight(counting)),
580
+ executeBatch: (statements) => driver.executeBatch(!writing || statements.includes(first) ? statements : [...statements, counting])
581
+ },
582
+ dialect: {
583
+ ...dialect,
584
+ buildWipe: () => [...pending.splice(0), ...dialect.buildWipe()],
585
+ buildDeletions: (keys, hashes) => [...pending.splice(0), ...dialect.buildDeletions(keys, hashes)]
586
+ },
587
+ finish: () => {
588
+ writing = false;
589
+ }
590
+ };
591
+ }
487
592
  // src/cloudflare/commit/commit-d1-patch.ts
488
593
  /**
489
594
  * commitD1Patch runs one D1 commit through the shared SQL commit core
@@ -494,8 +599,20 @@ async function planD1DerivedChanges(patch, context, inference, driverOptions) {
494
599
  * violation. Imports project
495
600
  * chunks during the commit (`searchIndexOnImport` defaults to the shared
496
601
  * `"incremental"`); `"deferred"` stays available as an option.
602
+ *
603
+ * Inference and SHACL checks read the world before the batch. When another write
604
+ * gets in between, the batch fails and the commit is planned again.
497
605
  */
498
606
  async function commitD1Patch(patch, context, options) {
607
+ const projection = options.searchIndexProjector?.projection;
608
+ const embeddingService = projection?.embeddingService && rememberEmbeddings(projection.embeddingService);
609
+ await retryOnConflict(() => tryCommit(patch, context, options, projection && {
610
+ ...projection,
611
+ embeddingService
612
+ }));
613
+ }
614
+ /** tryCommit plans and writes the commit once. */
615
+ async function tryCommit(patch, context, options, projection) {
499
616
  const { connection, worldId, searchIndexProjector: projector } = options;
500
617
  const sync = projector?.createVectorSync();
501
618
  const driverOptions = {
@@ -504,8 +621,9 @@ async function commitD1Patch(patch, context, options) {
504
621
  inferenceEnabled: options.inference?.enabled === true,
505
622
  beforePage: sync?.beforePage
506
623
  };
624
+ const version = options.inference?.enabled && !isReplaceImportCommit(context) ? await readWorldVersion(connection, options) : void 0;
507
625
  const derived = options.inference?.enabled ? await planD1DerivedChanges(patch, context, options.inference, driverOptions) : void 0;
508
- await checkD1Patch(patch, context, options, derived);
626
+ const checked = await checkD1Patch(patch, context, options, derived);
509
627
  const driver = createD1CommitDriver(driverOptions);
510
628
  const provenance = options.provenance?.enabled ? await planD1Provenance(patch, context, driver, driverOptions) : void 0;
511
629
  const indexing = planSearchIndexing(options.searchIndexOnImport, context);
@@ -516,16 +634,18 @@ async function commitD1Patch(patch, context, options) {
516
634
  derived,
517
635
  onChunkRows: sync?.collect
518
636
  });
519
- const commit = provenance ? withProvenance(driver, dialect, provenance) : {
637
+ const recorded = provenance ? withProvenance(driver, dialect, provenance) : {
520
638
  driver,
521
639
  dialect
522
640
  };
641
+ const commit = withWorldVersion(recorded.driver, recorded.dialect, options, version === void 0 ? checked : { version });
523
642
  await commitSqlPatch(patch, context, commit.driver, commit.dialect, {
524
643
  filter: options,
525
644
  searchIndexOnImport: options.searchIndexOnImport,
526
- projection: projector?.projection,
645
+ projection,
527
646
  rebuildPageSize: DEFAULT_D1_MATCH_PAGE_SIZE,
528
647
  afterWrite: async () => {
648
+ commit.finish();
529
649
  if (indexing.reindexAfterCommit ? isFullRebuild(options) : isReplaceImportCommit(context) && indexing.projectDuringCommit) await sync?.purgeWorld();
530
650
  await sync?.flush();
531
651
  }
@@ -671,4 +791,4 @@ var D1QuadStore = class {
671
791
  return new Transaction({ commit: (patch, context) => commitD1Patch(patch, context ?? defaults, this.options) });
672
792
  }
673
793
  };
674
- export { loadAssertedQuads as a, InferenceSizeGuardError as i, D1ProvenanceStore as n, planInference as o, DEFAULT_MAX_ASSERTED_QUADS as r, D1QuadStore as t };
794
+ export { InferenceSizeGuardError as a, DEFAULT_MAX_ASSERTED_QUADS as i, D1ProvenanceStore as n, loadAssertedQuads as o, ConcurrentWriteError as r, planInference as s, D1QuadStore as t };
@@ -1,2 +1,2 @@
1
- import { n as D1QuadStoreOptions, t as D1QuadStore } from "./mod-BfGKU5Gt.js";
1
+ import { n as D1QuadStoreOptions, t as D1QuadStore } from "./mod-C6Nc-jgN.js";
2
2
  export { D1QuadStore, type D1QuadStoreOptions };
@@ -1 +1 @@
1
- export { t as D1QuadStore } from "./quad-store-DfUksTZ2.js";
1
+ export { t as D1QuadStore } from "./quad-store-DW0XVyvC.js";
@@ -1,8 +1,8 @@
1
1
  import { DataFactory } from "@wazootech/sparql-engine";
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-Dj0dTBxX.js";
2
+ import { d as buildWipeAllGraphDataStatements, g as D1BatchExecutor, h as quadToInsertRow, o as buildSelectExistingQuadIds, r as buildCountQuadsQuery, t as buildBulkInsertQuads, u as buildDeleteQuadsByQuadIds, v as effectiveLookupChunkSize } from "./d1-quad-insert-sql-Cp5oSqIG.js";
3
+ import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-hkZBWMiA.js";
4
4
  import { hashQuads, isReplaceImportCommit } from "@wazootech/worlds-sdk/quad-store";
5
- import { i as removeMatchedQuads, n as countD1Matches, r as matchD1Pages, t as collectQuads } from "./d1-rdfjs-store-read-2QTEEe_a.js";
5
+ import { t as matchD1Pages } from "./match-d1-pages-hRKVbawI.js";
6
6
  // src/cloudflare/rdfjs-store/d1-quad-stream.ts
7
7
  /**
8
8
  * D1QuadStream is a minimal RDF/JS Stream backed by an async page generator
@@ -135,12 +135,12 @@ var D1QuadStream = class {
135
135
  if (this._ended) return;
136
136
  try {
137
137
  for await (const quad of this.quads()) {
138
- if (this._ended) return;
139
138
  if (this._flowing) this.emit("data", quad);
140
- else if (this._readStarted) {
139
+ else if (this._readStarted && !this._ended) {
141
140
  this._buffer.push(quad);
142
141
  this.emit("readable");
143
142
  }
143
+ if (this._ended) return;
144
144
  }
145
145
  if (!this._ended) this._end();
146
146
  } catch (error) {
@@ -515,6 +515,42 @@ var D1WriteQueue = class {
515
515
  };
516
516
  /** flush() reports at most this many of the failures it aggregates. */
517
517
  const MAX_REPORTED_FAILURES = 10;
518
+ // src/cloudflare/rdfjs-store/d1-rdfjs-store-read.ts
519
+ /** collectQuads drains a quad stream into an array. */
520
+ async function collectQuads(stream) {
521
+ const quads = [];
522
+ await new Promise((resolve, reject) => {
523
+ stream.on("data", (quad) => quads.push(quad));
524
+ stream.on("end", () => resolve());
525
+ stream.on("error", reject);
526
+ });
527
+ return quads;
528
+ }
529
+ /** countD1Matches returns the number of quads matching the pattern. */
530
+ async function countD1Matches(connection, worldId, subject, predicate, object, graph) {
531
+ const { sql, args } = buildCountQuadsQuery({
532
+ subject: subject ?? null,
533
+ predicate: predicate ?? null,
534
+ object: object ?? null,
535
+ graph: graph ?? null
536
+ }, worldId);
537
+ const result = await connection.execute({
538
+ sql,
539
+ args
540
+ });
541
+ return Number(result.rows[0]?.count ?? 0);
542
+ }
543
+ /** removeMatchedQuads deletes every matching quad in one patch and yields the removed quads. */
544
+ async function* removeMatchedQuads(store, subject, predicate, object, graph) {
545
+ const matches = await store.getQuads(subject, predicate, object, graph);
546
+ if (matches.length > 0) {
547
+ await store.applyPatch({
548
+ insertions: [],
549
+ deletions: matches
550
+ });
551
+ for (const quad of matches) yield quad;
552
+ }
553
+ }
518
554
  // src/cloudflare/rdfjs-store/d1-rdfjs-store.ts
519
555
  /**
520
556
  * logWriteFailure reports a fire-and-forget write failure (addQuad/removeQuad
@@ -1,2 +1,2 @@
1
- import { i as D1QuadStream, n as D1RdfjsStoreOptions, r as D1Transaction, t as D1RdfjsStore } from "./mod-BjVVdQCh.js";
1
+ import { i as D1QuadStream, n as D1RdfjsStoreOptions, r as D1Transaction, t as D1RdfjsStore } from "./mod-Bkjkds_5.js";
2
2
  export { D1QuadStream, D1RdfjsStore, type D1RdfjsStoreOptions, type D1Transaction };
@@ -1 +1 @@
1
- export { i as D1QuadStream, t as D1RdfjsStore } from "./rdfjs-store-8V0H0fGC.js";
1
+ export { i as D1QuadStream, t as D1RdfjsStore } from "./rdfjs-store-CES_vSLm.js";
package/dist/schema.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { n as D1SchemaBuilderOptions, t as D1SchemaBuilder } from "./d1-schema-builder-BLPr77rK.js";
1
+ import { n as D1SchemaBuilderOptions, t as D1SchemaBuilder } from "./d1-schema-builder-BZMZ8CCv.js";
2
2
  export { D1SchemaBuilder, D1SchemaBuilderOptions };
package/dist/schema.js CHANGED
@@ -1 +1 @@
1
- export { t as D1SchemaBuilder } from "./d1-schema-builder-Dj0dTBxX.js";
1
+ export { t as D1SchemaBuilder } from "./d1-schema-builder-hkZBWMiA.js";
@@ -1,7 +1,7 @@
1
1
  import { RRF_FUSION_K, buildChunkFtsValue, buildIncludeExcludeFilterClauses, buildKeywordFtsStatement, buildSearchResultId, buildSearchResultId as buildSearchResultId$1, generatePlaceholders, rebuildSqlSearchIndex, sanitizeFtsQuery, sanitizeFtsQuery as sanitizeFtsQuery$1 } from "@wazootech/worlds-sqlite/sql-core";
2
2
  import { normalizeRrfScore } from "@wazootech/worlds-sdk/search-index";
3
- import { _ as effectiveLookupChunkSize } from "./d1-quad-insert-sql-B4ZiZZe8.js";
4
- import { i as createD1CommitDriver, n as toProjectionOptions, r as vectorSyncEnabled, s as createD1CommitDialect, t as isFullRebuild } from "./project-search-chunks-options-qI9m5FWz.js";
3
+ import { v as effectiveLookupChunkSize } from "./d1-quad-insert-sql-Cp5oSqIG.js";
4
+ import { i as createD1CommitDriver, n as toProjectionOptions, r as vectorSyncEnabled, s as createD1CommitDialect, t as isFullRebuild } from "./project-search-chunks-options-CAxR9V4v.js";
5
5
  import { filterQuads, hashQuads } from "@wazootech/worlds-sdk/quad-store";
6
6
  import { DataFactory } from "@wazootech/sparql-engine/data-model";
7
7
  // src/cloudflare/search-index/d1-world-scoped-fts.ts
@@ -490,6 +490,24 @@ function hitToSearchResult(hit) {
490
490
  function clampCosine(score) {
491
491
  return Math.max(0, Math.min(1, score));
492
492
  }
493
+ // src/cloudflare/search-index/cosine-similarity.ts
494
+ /**
495
+ * cosineSimilarity scores two vectors from -1 to 1, as a Vectorize index with the
496
+ * `cosine` metric does. Vectors of different lengths cannot be compared and throw.
497
+ */
498
+ function cosineSimilarity(a, b) {
499
+ if (a.length !== b.length) throw new Error(`cannot compare vectors of ${a.length} and ${b.length} dimensions`);
500
+ let dot = 0;
501
+ let squaresA = 0;
502
+ let squaresB = 0;
503
+ for (let i = 0; i < a.length; i++) {
504
+ dot += a[i] * b[i];
505
+ squaresA += a[i] * a[i];
506
+ squaresB += b[i] * b[i];
507
+ }
508
+ const length = Math.sqrt(squaresA) * Math.sqrt(squaresB);
509
+ return length === 0 ? 0 : dot / length;
510
+ }
493
511
  // src/cloudflare/search-index/filter-vector-hits.ts
494
512
  const { literal, namedNode, quad } = DataFactory;
495
513
  /**
@@ -497,13 +515,155 @@ const { literal, namedNode, quad } = DataFactory;
497
515
  * in order, with the meaning they have for stored facts and for the keyword
498
516
  * query. The vector index can only filter on `world_id`, so this runs after its
499
517
  * 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.
518
+ * world, and this can leave fewer vector results than that. searchVectors only
519
+ * uses it when a filter leaves too many chunks to score each one. The keyword
520
+ * query filters in SQL and is not affected.
502
521
  */
503
522
  function filterVectorHits(hits, filter) {
504
523
  const matches = filterQuads(filter);
505
524
  return hits.filter(({ metadata }) => matches(quad(namedNode(metadata?.subject ?? ""), namedNode(metadata?.predicate ?? ""), literal(metadata?.value ?? ""), namedNode(metadata?.graph ?? ""))));
506
525
  }
526
+ // src/cloudflare/search-index/filter-candidates-sql.ts
527
+ /**
528
+ * filterScans lists the ways to find a filter's facts, usually the narrowest
529
+ * first. Reading the world's own quads comes last and works for any filter.
530
+ */
531
+ function filterScans({ include }) {
532
+ return [...[
533
+ "subjects",
534
+ "predicates",
535
+ "graphs"
536
+ ].filter((key) => include?.[key]?.length), "world"];
537
+ }
538
+ /**
539
+ * buildFilterCandidatesStatement selects the distinct chunks of the facts that
540
+ * match `filter`, at most `maxCandidates + 1` of them. It checks at most
541
+ * `maxScanned + 1` quads, which `scan` alone finds: with more conditions, D1
542
+ * could read any number of quads to find a few matches. Every row has the number
543
+ * of quads checked as `scanned`, and one row of NULLs says nothing matched.
544
+ */
545
+ function buildFilterCandidatesStatement(options) {
546
+ const { scan, worldId } = options;
547
+ const { include, exclude } = options.filter;
548
+ const first = scan === "world" ? {
549
+ whereClauses: worldId ? ["world_id = ?"] : [],
550
+ filterArgs: worldId ? [worldId] : []
551
+ } : buildIncludeExcludeFilterClauses({ include: { [scan]: include?.[scan] } }, {
552
+ subjects: "s",
553
+ predicates: "p",
554
+ graphs: "g"
555
+ });
556
+ const rest = buildIncludeExcludeFilterClauses({
557
+ include: {
558
+ ...include,
559
+ [scan]: void 0
560
+ },
561
+ exclude
562
+ }, {
563
+ subjects: "scanned.s",
564
+ predicates: "scanned.p",
565
+ graphs: "scanned.g"
566
+ });
567
+ if (worldId && scan !== "world") {
568
+ rest.whereClauses.push("scanned.world_id = ?");
569
+ rest.filterArgs.push(worldId);
570
+ }
571
+ return {
572
+ sql: `
573
+ WITH scanned AS MATERIALIZED (
574
+ SELECT quad_id, s, p, g${worldId ? ", world_id" : ""}
575
+ FROM quads ${where(first.whereClauses)}
576
+ LIMIT ${options.maxScanned + 1}
577
+ )
578
+ SELECT total.scanned, matched.*
579
+ FROM (SELECT COUNT(*) AS scanned FROM scanned) AS total
580
+ LEFT JOIN (
581
+ SELECT DISTINCT chunks.subject, chunks.predicate, chunks.graph, chunks.value
582
+ FROM scanned CROSS JOIN chunks ON chunks.quad_id = scanned.quad_id${worldId ? " AND chunks.world_id = scanned.world_id" : ""}
583
+ ${where(rest.whereClauses)}
584
+ LIMIT ${options.maxCandidates + 1}
585
+ ) AS matched ON TRUE
586
+ `,
587
+ args: [...first.filterArgs, ...rest.filterArgs]
588
+ };
589
+ }
590
+ function where(clauses) {
591
+ return clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
592
+ }
593
+ /** MAX_SCANNED_QUADS is the most quads one query checks to find those chunks. */
594
+ const MAX_SCANNED_QUADS = 5e3;
595
+ /**
596
+ * readFilterCandidates returns every chunk that `filter` lets through. It
597
+ * returns undefined when there is no filter, when there are more than
598
+ * MAX_EXACT_CANDIDATES chunks, or when finding them takes too much reading: at
599
+ * most one query per included criterion and one over the world.
600
+ */
601
+ async function readFilterCandidates(options, filter) {
602
+ const { whereClauses } = buildIncludeExcludeFilterClauses(filter, {
603
+ subjects: "s",
604
+ predicates: "p",
605
+ graphs: "g"
606
+ });
607
+ if (whereClauses.length === 0) return void 0;
608
+ for (const scan of filterScans(filter)) {
609
+ const { rows } = await options.connection.execute(buildFilterCandidatesStatement({
610
+ filter,
611
+ scan,
612
+ worldId: options.worldId,
613
+ maxScanned: MAX_SCANNED_QUADS,
614
+ maxCandidates: 100
615
+ }));
616
+ if (rows.length > 100) return void 0;
617
+ if (Number(rows[0]?.scanned) > 5e3) continue;
618
+ return rows.filter((row) => row.subject !== null).map(({ subject, predicate, graph, value }) => ({
619
+ subject: String(subject),
620
+ predicate: String(predicate),
621
+ graph: String(graph),
622
+ value: String(value)
623
+ }));
624
+ }
625
+ }
626
+ // src/cloudflare/search-index/search-vectors.ts
627
+ /**
628
+ * searchVectors returns the chunks nearest to the request's query, best first,
629
+ * at most `topK`. The vector index can only filter on `world_id`, so a filter
630
+ * that leaves few chunks is answered by scoring those chunks here. Any other
631
+ * filter runs on the index's nearest `topK` chunks of the whole world.
632
+ */
633
+ async function searchVectors(options, request, topK) {
634
+ const { embeddingService, vectorSearch, worldId } = options;
635
+ if (!embeddingService || !vectorSearch) return [];
636
+ const [embedded, candidates] = await Promise.all([embeddingService.embed([request.query]), vectorSearch.getByIds ? readFilterCandidates(options, request).catch(warnNotExact) : void 0]);
637
+ if (!embedded[0]) return [];
638
+ const queryVector = Array.from(new Float32Array(embedded[0]));
639
+ if (candidates) {
640
+ const hits = await scoreCandidates(options, queryVector, candidates).catch(warnNotExact);
641
+ if (hits) return hits.slice(0, topK);
642
+ }
643
+ return filterVectorHits(await vectorSearch.query(queryVector, {
644
+ topK,
645
+ ...worldId ? { filter: { world_id: worldId } } : {}
646
+ }), request);
647
+ }
648
+ /** scoreCandidates ranks every candidate that has a vector. The index does the same with cosine. */
649
+ async function scoreCandidates({ vectorSearch }, queryVector, candidates) {
650
+ const byId = /* @__PURE__ */ new Map();
651
+ for (const candidate of candidates) {
652
+ const { value: text, ...fact } = candidate;
653
+ byId.set(await buildSearchResultId$1({
654
+ ...fact,
655
+ text
656
+ }), candidate);
657
+ }
658
+ return (await vectorSearch?.getByIds?.([...byId.keys()]))?.map(({ id, vector }) => ({
659
+ id,
660
+ score: cosineSimilarity(queryVector, vector),
661
+ metadata: { ...byId.get(id) }
662
+ })).sort((a, b) => b.score - a.score);
663
+ }
664
+ function warnNotExact(error) {
665
+ console.warn("[Search Warning] could not score the filtered facts; filtering the nearest vectors instead", error);
666
+ }
507
667
  // src/cloudflare/search-index/cloudflare-search-index.ts
508
668
  /**
509
669
  * CloudflareSearchIndex implements the query pathway over D1's FTS5
@@ -513,8 +673,8 @@ function filterVectorHits(hits, filter) {
513
673
  * vectorSearch are wired, the query is embedded and the two lists fuse.
514
674
  *
515
675
  * Ranked semantics come from the reported `mode` — hybrid (both lists),
516
- * semantic (vector-only), keyword (FTS-only). No JS cosine fallback exists
517
- * per the cloudflare architecture decision (worlds-sdk-ts#63); any vector
676
+ * semantic (vector-only), keyword (FTS-only). Only a filter that leaves few
677
+ * chunks is scored here instead of by the index (see searchVectors); any vector
518
678
  * failure degrades gracefully to keyword-only.
519
679
  */
520
680
  var CloudflareSearchIndex = class {
@@ -552,13 +712,8 @@ var CloudflareSearchIndex = class {
552
712
  });
553
713
  }
554
714
  let vectorHits = [];
555
- if (this.options.embeddingService && this.options.vectorSearch) try {
556
- const embedded = await this.options.embeddingService.embed([request.query]);
557
- const queryVector = embedded[0] ? new Float32Array(embedded[0]) : void 0;
558
- if (queryVector) vectorHits = filterVectorHits(await this.options.vectorSearch.query(Array.from(queryVector), {
559
- topK: candidateCount,
560
- ...this.options.worldId ? { filter: { world_id: this.options.worldId } } : {}
561
- }), request);
715
+ try {
716
+ vectorHits = await searchVectors(this.options, request, candidateCount);
562
717
  } catch (error) {
563
718
  console.warn("[Search Warning] vector query failed; falling back to keyword-only", error);
564
719
  }
@@ -1,2 +1,2 @@
1
- import { C as D1SearchQueryBuilder, E as sanitizeFtsQuery, T as RRF_REFERENCE_CONSTANT, _ as logVectorSyncDrift, a as RebuildD1SearchIndexFromQuadsResult, b as vectorSyncSucceeded, c as D1SearchIndexProjector, d as ProjectSearchChunksOptions, f as CloudflareSearchIndex, g as emptyVectorSyncReport, h as VectorSyncReport, i as ReadProjectSearchChunksOptions, l as D1SearchIndexProjectorOptions, m as CloudflareSearchIndexOptions, n as buildChunkFtsValue, o as createD1SearchIndexRebuilder, p as CloudflareReindexResponse, r as buildSearchResultId, s as rebuildD1SearchIndexFromQuads, t as BuildSearchResultIdOptions, u as D1VectorSync, v as mergeVectorSyncReports, w as D1SearchQueryBuilderOptions, y as recordVectorSyncError } from "./mod-B4BJr5j0.js";
1
+ import { C as D1SearchQueryBuilder, E as sanitizeFtsQuery, T as RRF_REFERENCE_CONSTANT, _ as logVectorSyncDrift, a as RebuildD1SearchIndexFromQuadsResult, b as vectorSyncSucceeded, c as D1SearchIndexProjector, d as ProjectSearchChunksOptions, f as CloudflareSearchIndex, g as emptyVectorSyncReport, h as VectorSyncReport, i as ReadProjectSearchChunksOptions, l as D1SearchIndexProjectorOptions, m as CloudflareSearchIndexOptions, n as buildChunkFtsValue, o as createD1SearchIndexRebuilder, p as CloudflareReindexResponse, r as buildSearchResultId, s as rebuildD1SearchIndexFromQuads, t as BuildSearchResultIdOptions, u as D1VectorSync, v as mergeVectorSyncReports, w as D1SearchQueryBuilderOptions, y as recordVectorSyncError } from "./mod-a3SVCa8c.js";
2
2
  export { type BuildSearchResultIdOptions, type CloudflareReindexResponse, CloudflareSearchIndex, type CloudflareSearchIndexOptions, D1SearchIndexProjector, D1SearchIndexProjectorOptions, D1SearchQueryBuilder, D1SearchQueryBuilderOptions, D1VectorSync, type ProjectSearchChunksOptions, RRF_REFERENCE_CONSTANT, ReadProjectSearchChunksOptions, RebuildD1SearchIndexFromQuadsResult, VectorSyncReport, buildChunkFtsValue, buildSearchResultId, createD1SearchIndexRebuilder, emptyVectorSyncReport, logVectorSyncDrift, mergeVectorSyncReports, rebuildD1SearchIndexFromQuads, recordVectorSyncError, sanitizeFtsQuery, vectorSyncSucceeded };
@@ -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-_yyeZAVm.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-Cw8CTAjm.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wazootech/worlds-cloudflare",
3
- "version": "0.15.10",
3
+ "version": "0.15.12",
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,7 +72,7 @@
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.12",
75
+ "@wazootech/sparql-engine": "^0.5.13",
76
76
  "@wazootech/worlds-sdk": "^0.11.6",
77
77
  "@wazootech/worlds-sqlite": "^0.8.5",
78
78
  "re2js": "2.10.0"
@@ -1,64 +0,0 @@
1
- import { i as buildMatchQuadsQuery, p as quadFromD1Row, r as buildCountQuadsQuery } from "./d1-quad-insert-sql-B4ZiZZe8.js";
2
- // src/cloudflare/rdfjs-store/d1-rdfjs-store-read.ts
3
- /** matchD1Pages keyset-pages the quads matching a pattern, one SQL round-trip per page. */
4
- async function* matchD1Pages(connection, matchPageSize, worldId, subject, predicate, object, graph) {
5
- const pattern = {
6
- subject: subject ?? null,
7
- predicate: predicate ?? null,
8
- object: object ?? null,
9
- graph: graph ?? null
10
- };
11
- let afterQuadId;
12
- for (;;) {
13
- const { sql, args } = buildMatchQuadsQuery(pattern, {
14
- afterQuadId,
15
- limit: matchPageSize
16
- }, worldId);
17
- const result = await connection.execute({
18
- sql,
19
- args
20
- });
21
- if (result.rows.length === 0) return;
22
- for (const row of result.rows) {
23
- afterQuadId = String(row.id);
24
- yield quadFromD1Row(row);
25
- }
26
- if (result.rows.length < matchPageSize) return;
27
- }
28
- }
29
- /** collectQuads drains a quad stream into an array. */
30
- async function collectQuads(stream) {
31
- const quads = [];
32
- await new Promise((resolve, reject) => {
33
- stream.on("data", (quad) => quads.push(quad));
34
- stream.on("end", () => resolve());
35
- stream.on("error", reject);
36
- });
37
- return quads;
38
- }
39
- /** countD1Matches returns the number of quads matching the pattern. */
40
- async function countD1Matches(connection, worldId, subject, predicate, object, graph) {
41
- const { sql, args } = buildCountQuadsQuery({
42
- subject: subject ?? null,
43
- predicate: predicate ?? null,
44
- object: object ?? null,
45
- graph: graph ?? null
46
- }, worldId);
47
- const result = await connection.execute({
48
- sql,
49
- args
50
- });
51
- return Number(result.rows[0]?.count ?? 0);
52
- }
53
- /** removeMatchedQuads deletes every matching quad in one patch and yields the removed quads. */
54
- async function* removeMatchedQuads(store, subject, predicate, object, graph) {
55
- const matches = await store.getQuads(subject, predicate, object, graph);
56
- if (matches.length > 0) {
57
- await store.applyPatch({
58
- insertions: [],
59
- deletions: matches
60
- });
61
- for (const quad of matches) yield quad;
62
- }
63
- }
64
- export { removeMatchedQuads as i, countD1Matches as n, matchD1Pages as r, collectQuads as t };