@wazootech/worlds-cloudflare 0.15.9 → 0.15.11
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 +40 -6
- package/dist/{shapes-graph-6g22feyx.js → d1-provenance-sql-CV6Mly6b.js} +51 -19
- package/dist/{d1-schema-builder-BLPr77rK.d.ts → d1-schema-builder-BZMZ8CCv.d.ts} +1 -1
- package/dist/{d1-schema-builder-emxvwyf9.js → d1-schema-builder-hkZBWMiA.js} +3 -2
- package/dist/index.d.ts +14 -7
- package/dist/index.js +53 -28
- package/dist/{mod-BjVVdQCh.d.ts → mod-Bkjkds_5.d.ts} +1 -1
- package/dist/{mod-BfGKU5Gt.d.ts → mod-C6Nc-jgN.d.ts} +2 -2
- package/dist/{mod-B4BJr5j0.d.ts → mod-a3SVCa8c.d.ts} +20 -3
- package/dist/quad-store-BwIxBs51.js +794 -0
- package/dist/quad-store.d.ts +1 -1
- package/dist/quad-store.js +1 -1
- package/dist/{rdfjs-store-YJhcJ8eq.js → rdfjs-store-DjRonoBl.js} +1 -1
- package/dist/rdfjs-store.d.ts +1 -1
- package/dist/rdfjs-store.js +1 -1
- package/dist/schema.d.ts +1 -1
- package/dist/schema.js +1 -1
- package/dist/{search-index-_yyeZAVm.js → search-index-BgOTomws.js} +166 -11
- package/dist/search-index.d.ts +1 -1
- package/dist/search-index.js +1 -1
- package/package.json +1 -1
- package/dist/quad-store-C1IJEz2D.js +0 -492
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
|
|
@@ -286,9 +316,13 @@ const { results } = await sdk.provenance({ subject });
|
|
|
286
316
|
- **What is recorded.** Only real changes. Importing quads the world already holds
|
|
287
317
|
adds nothing, where the SDK's in-memory store records every insertion again.
|
|
288
318
|
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
|
|
290
|
-
|
|
291
|
-
|
|
319
|
+
- **Atomicity.** Records are written in the same D1 batch as their quads, and
|
|
320
|
+
decided there, so overlapping writes of one fact leave the records that writes
|
|
321
|
+
one after the other would. A commit too large for one batch is not atomic, with
|
|
322
|
+
or without provenance. Its records go first, and if it fails partway, its cleanup
|
|
323
|
+
corrects them. If another write to the same facts runs between its batches, a
|
|
324
|
+
record can be missing or written twice. If the cleanup fails too, the records can
|
|
325
|
+
name facts that were never stored.
|
|
292
326
|
- **Writers.** Imports and SPARQL updates both take `provenance`:
|
|
293
327
|
`sdk.sparql({ query, provenance: { writer } })`. Without it they are recorded
|
|
294
328
|
with a time only. Inferred quads have no records. Writes that go
|
|
@@ -296,7 +330,7 @@ const { results } = await sdk.provenance({ subject });
|
|
|
296
330
|
recorded.
|
|
297
331
|
- **Cost.** Measured on miniflare with 1,000 and 10,000 short quads: 2 more rows
|
|
298
332
|
written per new quad (11 instead of 9) and about 230 bytes per record. A
|
|
299
|
-
replace import also reads the
|
|
333
|
+
replace import also reads the world twice in its batch.
|
|
300
334
|
- **Deletion.** `purgeWorld` removes a world's records. A replace import keeps
|
|
301
335
|
them.
|
|
302
336
|
|
|
@@ -1,3 +1,53 @@
|
|
|
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";
|
|
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
|
+
}
|
|
1
51
|
// src/cloudflare/provenance/d1-provenance-sql.ts
|
|
2
52
|
/**
|
|
3
53
|
* PROVENANCE_IDS_PER_STATEMENT is how many quads one provenance statement
|
|
@@ -35,17 +85,6 @@ function buildInsertProvenance(type, entries, stamp, worldId) {
|
|
|
35
85
|
]
|
|
36
86
|
}));
|
|
37
87
|
}
|
|
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
88
|
/** buildSelectProvenance lists records oldest first, narrowed by quad and type. */
|
|
50
89
|
function buildSelectProvenance(query, worldId) {
|
|
51
90
|
const filters = Object.entries({
|
|
@@ -96,11 +135,4 @@ function buildSelectProvenanceChains(quadIds, worldId) {
|
|
|
96
135
|
]
|
|
97
136
|
};
|
|
98
137
|
}
|
|
99
|
-
|
|
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 };
|
|
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 };
|
|
@@ -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 {
|
|
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-
|
|
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-
|
|
5
|
-
import { i as D1QuadStream, n as D1RdfjsStoreOptions, r as D1Transaction, t as D1RdfjsStore } from "./mod-
|
|
6
|
-
import { n as D1QuadStoreOptions, t as D1QuadStore } from "./mod-
|
|
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,
|
|
188
|
-
* configured — every vector the index
|
|
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-
|
|
4
|
-
import { a as
|
|
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-BgOTomws.js";
|
|
4
|
+
import { a as InferenceSizeGuardError, n as D1ProvenanceStore, o as loadAssertedQuads, r as ConcurrentWriteError, s as planInference, t as D1QuadStore } from "./quad-store-BwIxBs51.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-
|
|
9
|
-
import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-
|
|
8
|
+
import { i as D1QuadStream, n as assertD1SchemaCompatible, r as checkD1SchemaCompatibility, t as D1RdfjsStore } from "./rdfjs-store-DjRonoBl.js";
|
|
9
|
+
import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-hkZBWMiA.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
|
+
// 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.
|
|
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.
|
|
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,
|
|
431
|
-
* configured — every vector the index
|
|
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
|
|
443
|
-
await options.connection.batch([...buildWipeAllGraphDataStatements(worldId), ...rows.
|
|
444
|
-
sql:
|
|
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 };
|
|
@@ -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-
|
|
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-
|
|
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-
|
|
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
|
|
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).
|
|
346
|
-
*
|
|
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 {
|