@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.
@@ -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-C1IJEz2D.js";
1
+ export { t as D1QuadStore } from "./quad-store-BwIxBs51.js";
@@ -1,6 +1,6 @@
1
1
  import { DataFactory } from "@wazootech/sparql-engine";
2
2
  import { _ as effectiveLookupChunkSize, h as D1BatchExecutor, l as buildDeleteQuadsByQuadIds, m as quadToInsertRow, o as buildSelectExistingQuadIds, t as buildBulkInsertQuads, u as buildWipeAllGraphDataStatements } from "./d1-quad-insert-sql-B4ZiZZe8.js";
3
- import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-emxvwyf9.js";
3
+ import { n as validateWorldId, t as D1SchemaBuilder } from "./d1-schema-builder-hkZBWMiA.js";
4
4
  import { hashQuads, isReplaceImportCommit } from "@wazootech/worlds-sdk/quad-store";
5
5
  import { i as removeMatchedQuads, n as countD1Matches, r as matchD1Pages, t as collectQuads } from "./d1-rdfjs-store-read-2QTEEe_a.js";
6
6
  // src/cloudflare/rdfjs-store/d1-quad-stream.ts
@@ -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-YJhcJ8eq.js";
1
+ export { i as D1QuadStream, t as D1RdfjsStore } from "./rdfjs-store-DjRonoBl.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-emxvwyf9.js";
1
+ export { t as D1SchemaBuilder } from "./d1-schema-builder-hkZBWMiA.js";
@@ -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-BgOTomws.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wazootech/worlds-cloudflare",
3
- "version": "0.15.9",
3
+ "version": "0.15.11",
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",