@yaks/embedding 0.0.0-stage → 0.2.36

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.
Files changed (132) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +549 -2
  3. package/_dist/compile.d.ts +34 -0
  4. package/_dist/compile.d.ts.map +1 -0
  5. package/_dist/ddl.d.ts +31 -0
  6. package/_dist/ddl.d.ts.map +1 -0
  7. package/_dist/embedder.d.ts +55 -0
  8. package/_dist/embedder.d.ts.map +1 -0
  9. package/_dist/fields.d.ts +70 -0
  10. package/_dist/fields.d.ts.map +1 -0
  11. package/_dist/graph.d.ts +63 -0
  12. package/_dist/graph.d.ts.map +1 -0
  13. package/_dist/held.d.ts +16 -0
  14. package/_dist/held.d.ts.map +1 -0
  15. package/_dist/image.d.ts +20 -0
  16. package/_dist/image.d.ts.map +1 -0
  17. package/_dist/mod.d.ts +105 -0
  18. package/_dist/mod.d.ts.map +1 -0
  19. package/_dist/native.d.ts +20 -0
  20. package/_dist/native.d.ts.map +1 -0
  21. package/_dist/near.d.ts +35 -0
  22. package/_dist/near.d.ts.map +1 -0
  23. package/_dist/neighbours.d.ts +29 -0
  24. package/_dist/neighbours.d.ts.map +1 -0
  25. package/_dist/options.d.ts +37 -0
  26. package/_dist/options.d.ts.map +1 -0
  27. package/_dist/outage.d.ts +64 -0
  28. package/_dist/outage.d.ts.map +1 -0
  29. package/_dist/owed.d.ts +79 -0
  30. package/_dist/owed.d.ts.map +1 -0
  31. package/_dist/remote.d.ts +116 -0
  32. package/_dist/remote.d.ts.map +1 -0
  33. package/_dist/score.d.ts +10 -0
  34. package/_dist/score.d.ts.map +1 -0
  35. package/_dist/search.d.ts +24 -0
  36. package/_dist/search.d.ts.map +1 -0
  37. package/_dist/service.d.ts +23 -0
  38. package/_dist/service.d.ts.map +1 -0
  39. package/_dist/sleeper.d.ts +37 -0
  40. package/_dist/sleeper.d.ts.map +1 -0
  41. package/_dist/sweep.d.ts +71 -0
  42. package/_dist/sweep.d.ts.map +1 -0
  43. package/_dist/tools.d.ts +14 -0
  44. package/_dist/tools.d.ts.map +1 -0
  45. package/_dist/vector.d.ts +30 -0
  46. package/_dist/vector.d.ts.map +1 -0
  47. package/_dist/vocab.d.ts +6 -0
  48. package/_dist/vocab.d.ts.map +1 -0
  49. package/coded.js +98 -0
  50. package/coded.js.map +1 -0
  51. package/coded.ts +85 -0
  52. package/compile.js +145 -0
  53. package/compile.js.map +1 -0
  54. package/compile.ts +206 -0
  55. package/ddl.js +476 -0
  56. package/ddl.js.map +1 -0
  57. package/ddl.ts +346 -0
  58. package/deno.json +1 -0
  59. package/embedder.js +85 -0
  60. package/embedder.js.map +1 -0
  61. package/embedder.ts +113 -0
  62. package/fields.js +178 -0
  63. package/fields.js.map +1 -0
  64. package/fields.ts +259 -0
  65. package/fill.js +177 -0
  66. package/fill.js.map +1 -0
  67. package/fill.ts +144 -0
  68. package/graph.js +113 -0
  69. package/graph.js.map +1 -0
  70. package/graph.ts +167 -0
  71. package/held.js +680 -0
  72. package/held.js.map +1 -0
  73. package/held.ts +726 -0
  74. package/image.js +202 -0
  75. package/image.js.map +1 -0
  76. package/image.ts +185 -0
  77. package/mod.js +105 -0
  78. package/mod.js.map +1 -0
  79. package/mod.ts +113 -0
  80. package/native.js +236 -0
  81. package/native.js.map +1 -0
  82. package/native.ts +288 -0
  83. package/near.js +123 -0
  84. package/near.js.map +1 -0
  85. package/near.ts +192 -0
  86. package/neighbours.js +223 -0
  87. package/neighbours.js.map +1 -0
  88. package/neighbours.ts +303 -0
  89. package/options.js +187 -0
  90. package/options.js.map +1 -0
  91. package/options.ts +269 -0
  92. package/outage.js +128 -0
  93. package/outage.js.map +1 -0
  94. package/outage.ts +132 -0
  95. package/owed.js +287 -0
  96. package/owed.js.map +1 -0
  97. package/owed.ts +346 -0
  98. package/package.json +45 -4
  99. package/remote.js +264 -0
  100. package/remote.js.map +1 -0
  101. package/remote.ts +391 -0
  102. package/score.js +46 -0
  103. package/score.js.map +1 -0
  104. package/score.ts +60 -0
  105. package/search.js +65 -0
  106. package/search.js.map +1 -0
  107. package/search.ts +118 -0
  108. package/service.js +107 -0
  109. package/service.js.map +1 -0
  110. package/service.ts +133 -0
  111. package/sleeper.js +107 -0
  112. package/sleeper.js.map +1 -0
  113. package/sleeper.ts +166 -0
  114. package/sparse.js +36 -0
  115. package/sparse.js.map +1 -0
  116. package/sparse.ts +49 -0
  117. package/sweep.js +374 -0
  118. package/sweep.js.map +1 -0
  119. package/sweep.ts +446 -0
  120. package/tools.js +57 -0
  121. package/tools.js.map +1 -0
  122. package/tools.ts +88 -0
  123. package/vector.js +78 -0
  124. package/vector.js.map +1 -0
  125. package/vector.ts +96 -0
  126. package/visibility.js +83 -0
  127. package/visibility.js.map +1 -0
  128. package/visibility.ts +111 -0
  129. package/vocab.js +22 -0
  130. package/vocab.js.map +1 -0
  131. package/vocab.json +19 -0
  132. package/vocab.ts +22 -0
package/coded.ts ADDED
@@ -0,0 +1,85 @@
1
+ // Each vector's int8 codes, kept beside it on shared storage, so a native scan
2
+ // reads 384 bytes a vector where its floats take 1,536 and a page holds two.
3
+ // A search that has to read the corpus from disk, the box's page cache having
4
+ // let it go, reads a fifth as much (./native.ts), and the nearest few are
5
+ // still scored from their floats (./near.ts).
6
+ //
7
+ // Triggers delete a vector's codes when the vector changes or goes, and keep
8
+ // the owners of vectors that have none (./ddl.ts), whoever wrote either table.
9
+ // So a scan trusts the codes once that set is empty, which is one row to ask
10
+ // however many vectors there are. {@link put} codes what the sweep stores;
11
+ // {@link heal} codes what anyone else stored (a migration, an older process,
12
+ // every vector stored before the table was made).
13
+
14
+ import { col, eq, lit, select, type Statements, table, val } from '@yaks/sql'
15
+ import { CODE, TABLE, UNCODED } from './ddl.js'
16
+ import { coded, floats } from './vector.js'
17
+
18
+ // Whether this database keeps codes, asked again once its schema changes. The
19
+ // uncoded set is made after the codes, so it standing means both do.
20
+ let made = new WeakMap<Statements, { version: number; has: boolean }>()
21
+ export let has = (db: Statements): boolean => {
22
+ let version = db.revision('schema')
23
+ let kept = made.get(db)
24
+ if (kept?.version == version) return kept.has
25
+ let found = !!db.query(select({
26
+ cols: [col('name')],
27
+ from: table('sqlite_master'),
28
+ where: eq(col('name'), val(UNCODED)),
29
+ }))[0]
30
+ made.set(db, { version, has: found })
31
+ return found
32
+ }
33
+
34
+ /** Whether every stored vector has its codes: whether any owner is noted
35
+ * uncoded, read off one row. */
36
+ export let complete = (db: Statements): boolean =>
37
+ has(db) &&
38
+ !db.query(select({
39
+ cols: [lit(1)],
40
+ from: table(UNCODED),
41
+ limit: lit(1),
42
+ })).length
43
+
44
+ /** Store the codes of the vector an owner was just given. */
45
+ export let put = (db: Statements, owner: number, vec: Float32Array): void => {
46
+ if (!has(db)) return
47
+ db.query({
48
+ t: 'insert',
49
+ or: 'replace',
50
+ into: CODE,
51
+ cols: ['owner', 'code'],
52
+ rows: [[val(owner), val(coded(vec))]],
53
+ })
54
+ }
55
+
56
+ /** Code up to `limit` stored vectors that have no codes, in owner order, and
57
+ * say how many owners it settled. An owner noted with no vector standing is
58
+ * forgotten. Nothing to code costs one row's read. */
59
+ export let heal = (db: Statements, limit = 2048): number | Promise<number> => {
60
+ if (!has(db)) return 0
61
+ return db.atomic(() => {
62
+ let rows = db.query(select({
63
+ cols: [col('owner', 'u'), col('vec', 'e')],
64
+ from: table(UNCODED, 'u'),
65
+ joins: [{
66
+ how: 'left',
67
+ src: table(TABLE, 'e'),
68
+ on: eq(col('owner', 'e'), col('owner', 'u')),
69
+ }],
70
+ order: [col('owner', 'u')],
71
+ limit: val(limit),
72
+ }))
73
+ for (let r of rows) {
74
+ let owner = Number(r.owner)
75
+ if (r.vec == null) {
76
+ db.query({
77
+ t: 'delete',
78
+ from: UNCODED,
79
+ where: eq(col('owner'), val(owner)),
80
+ })
81
+ } else put(db, owner, floats(r.vec as Uint8Array))
82
+ }
83
+ return rows.length
84
+ })
85
+ }
package/compile.js ADDED
@@ -0,0 +1,145 @@
1
+ // The query half: `.near=<entity>` becomes a condition, `.order=similar`
2
+ // becomes an ordering, and the similarity comes back as a component.
3
+ //
4
+ // A query mixes a neighbourhood with ordinary filters — `.near=cake-01
5
+ // .book.price<20` — and @yaks/query parses `.near` as a directive that @yaks/sql
6
+ // refuses on its own, because the vectors are here and not there. This module
7
+ // is the @yaks/sql extension that answers it, registered through
8
+ // `compile(ast, vocab, { extend: [semantic(db, embedder)] })`. It takes the
9
+ // embedder only for the vector space its model names, which is all a query
10
+ // needs of one.
11
+ //
12
+ // It compiles in three steps. The anchor's stored vector is read; the ranking
13
+ // returns the nearest entities; and that list becomes `owner in (?, ?, ?)` for
14
+ // the WHERE and a `case … when … then` for the ORDER BY. So the
15
+ // nearest-neighbor search itself runs where the vectors are — in this package —
16
+ // and what reaches SQL is a handful of integer ids, which is why the rest of
17
+ // the query still pages normally.
18
+ //
19
+ // Nearest among what the rest of the query selects. The ranking is cut down to
20
+ // `limit`, so cutting it before the other clauses filter would answer with the
21
+ // memories among the eight nearest entities of any kind — almost always none.
22
+ // @yaks/sql hands each extension the query's `Screen` (a statement selecting
23
+ // the ids of the entities the rest of the query admits) when it begins, and
24
+ // only those are candidates: filter, then rank, then cut.
25
+ //
26
+ // It remembers the neighbourhood the `.near` clause resolved, so the ordering
27
+ // can rank by it and the caller can read the scores back afterwards — and
28
+ // forgets it when the compiler reports that a new query has begun (@yaks/sql
29
+ // `Begin`). That is what lets a server register one of these when the plugin is
30
+ // composed and serve every query through it: each compilation answers from its
31
+ // own `.near`, and an `.order=similar` with none is refused as loudly as it was
32
+ // on the first query.
33
+ import { among, FALSE, lit, lookup, Unsupported, val } from "@yaks/sql";
34
+ import { nearest, vectorOf } from "./near.js";
35
+ import { fields, searched } from "./fields.js";
36
+ import { screened, visibleVectors } from "./visibility.js";
37
+ /** The `.order=` value that means "nearest first". */ export let SIMILAR = 'similar';
38
+ /** The name of the query-only component that carries the similarity back. */ export let RANK = 'rank';
39
+ /**
40
+ * A semantic query extension over a database's stored vectors.
41
+ *
42
+ * What it needs is the vector space, not the embedder: a `.near` anchor reads
43
+ * the vector already stored for it and never calls the network, because
44
+ * compiling a query is synchronous. Embedding text that has no entity yet is
45
+ * the sweep's job — which is why a server whose embedder is still waiting for a
46
+ * key ranks perfectly well over the vectors it already has.
47
+ */ export let semantic = (db, space, opts = {})=>{
48
+ let held = null;
49
+ // What the rest of this query selects — not asked for until a `.near` needs
50
+ // it.
51
+ let asked = null;
52
+ let rank = opts.rank ?? ((query, limit, within)=>space ? nearest(db, query, {
53
+ model: space.model,
54
+ limit,
55
+ within
56
+ }) : []);
57
+ // The fields over components a table stands for (@yaks/sql `Site.absent`):
58
+ // one nothing has written yet holds no text, and excludes no entity.
59
+ let live = (site)=>{
60
+ let all = opts.fields ?? fields(site.vocab, searched);
61
+ let gone = new Set(site.absent);
62
+ if (!gone.size) return all;
63
+ return all.filter((f)=>!gone.has(f.comp) && !(f.on && gone.has(f.on))).map((f)=>f.not?.some((n)=>gone.has(n)) ? {
64
+ ...f,
65
+ not: f.not.filter((n)=>!gone.has(n))
66
+ } : f);
67
+ };
68
+ let near = (anchor, site)=>{
69
+ let image = opts.image?.();
70
+ if (!image && !space) return null;
71
+ let fields = image ? [] : live(site);
72
+ let visible = visibleVectors(site.vocab, fields, site.visibility, site.absent);
73
+ let vec = image ? image.get(anchor, visible) : space && vectorOf(db, anchor, space.model, visible);
74
+ if (!vec) {
75
+ held = [];
76
+ return FALSE;
77
+ }
78
+ let limit = opts.limit ?? 8;
79
+ let scope = asked?.();
80
+ // The ordinary candidate screen already enforces entity visibility. Only
81
+ // vector-source restrictions add information to that screen; checking the
82
+ // same entity policy twice makes every broad scan pay twice per vector.
83
+ let sources = scope && site.visibility ? visibleVectors(site.vocab, fields, {
84
+ ...site.visibility,
85
+ entity: undefined
86
+ }, site.absent) : visible;
87
+ let within = screened(scope, sources);
88
+ // An anchor with no vector has no neighbourhood, and compiling that to a
89
+ // constant false selects nothing rather than widening to everything.
90
+ // The ranking is asked for one extra: the anchor scores 1 against itself
91
+ // and would otherwise eat a place, and nothing is its own neighbour.
92
+ held = (image?.nearest ?? rank)(vec, limit + 1, within).filter((n)=>n.entity != anchor && n.similarity >= (opts.floor ?? 0)).slice(0, limit);
93
+ if (!held.length) return FALSE;
94
+ return among(site.owner, held.map((n)=>val(n.owner)));
95
+ };
96
+ return {
97
+ name: 'embedding',
98
+ // A neighbourhood is `limit` owners at most, read by key.
99
+ few: ()=>[
100
+ 'near'
101
+ ],
102
+ begin: (screen)=>{
103
+ held = null;
104
+ asked = screen;
105
+ },
106
+ compile: {
107
+ near: (clause, site)=>clause.kind == 'near' ? near(clause.value, site) : null
108
+ },
109
+ order: (value, site)=>{
110
+ if (value != SIMILAR) return null;
111
+ if (!held) {
112
+ throw new Unsupported(`.order=${SIMILAR}`, 'nothing to rank by — it orders a .near neighbourhood', '@yaks/embedding');
113
+ }
114
+ // An empty neighbourhood selects no rows, so there is nothing to order.
115
+ if (!held.length) return lit(null);
116
+ // The neighbours are already in order, so their position is the sort key.
117
+ // Site.owner is this row's stable integer id, including cursor anchors.
118
+ return lookup(site.owner, held.map((n, i)=>[
119
+ n.owner,
120
+ lit(i)
121
+ ]), {
122
+ stable: true
123
+ }, lit(held.length));
124
+ },
125
+ neighbours: ()=>held ?? [],
126
+ rank: (bundles)=>{
127
+ let by = new Map((held ?? []).map((n)=>[
128
+ n.entity,
129
+ n.similarity
130
+ ]));
131
+ let score = (b)=>by.get(b.entity.eid) ?? -Infinity;
132
+ // A bundle the neighbourhood does not name keeps its shape and sorts
133
+ // last: this decorates an answer, it never silently drops one.
134
+ return [
135
+ ...bundles
136
+ ].sort((a, b)=>score(b) - score(a)).map((b)=>by.has(b.entity.eid) ? {
137
+ ...b,
138
+ [RANK]: {
139
+ score: score(b)
140
+ }
141
+ } : b);
142
+ }
143
+ };
144
+ };
145
+ //# sourceMappingURL=compile.js.map
package/compile.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile.js","sources":["./comp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AM,CAAC,GAAG,IAAI;UAAE,GAAG,CAAC;UAAE,CAAC,KAAK,EAAE;YAAE,OAAO,MAAM;UAAG;QAAE,IAAI;IAErE;EACF;AACF,EAAC"}
package/compile.ts ADDED
@@ -0,0 +1,206 @@
1
+ // The query half: `.near=<entity>` becomes a condition, `.order=similar`
2
+ // becomes an ordering, and the similarity comes back as a component.
3
+ //
4
+ // A query mixes a neighbourhood with ordinary filters — `.near=cake-01
5
+ // .book.price<20` — and @yaks/query parses `.near` as a directive that @yaks/sql
6
+ // refuses on its own, because the vectors are here and not there. This module
7
+ // is the @yaks/sql extension that answers it, registered through
8
+ // `compile(ast, vocab, { extend: [semantic(db, embedder)] })`. It takes the
9
+ // embedder only for the vector space its model names, which is all a query
10
+ // needs of one.
11
+ //
12
+ // It compiles in three steps. The anchor's stored vector is read; the ranking
13
+ // returns the nearest entities; and that list becomes `owner in (?, ?, ?)` for
14
+ // the WHERE and a `case … when … then` for the ORDER BY. So the
15
+ // nearest-neighbor search itself runs where the vectors are — in this package —
16
+ // and what reaches SQL is a handful of integer ids, which is why the rest of
17
+ // the query still pages normally.
18
+ //
19
+ // Nearest among what the rest of the query selects. The ranking is cut down to
20
+ // `limit`, so cutting it before the other clauses filter would answer with the
21
+ // memories among the eight nearest entities of any kind — almost always none.
22
+ // @yaks/sql hands each extension the query's `Screen` (a statement selecting
23
+ // the ids of the entities the rest of the query admits) when it begins, and
24
+ // only those are candidates: filter, then rank, then cut.
25
+ //
26
+ // It remembers the neighbourhood the `.near` clause resolved, so the ordering
27
+ // can rank by it and the caller can read the scores back afterwards — and
28
+ // forgets it when the compiler reports that a new query has begun (@yaks/sql
29
+ // `Begin`). That is what lets a server register one of these when the plugin is
30
+ // composed and serve every query through it: each compilation answers from its
31
+ // own `.near`, and an `.order=similar` with none is refused as loudly as it was
32
+ // on the first query.
33
+
34
+ import type { Bundle } from 'jsr:@yaks/graph@0.2.36'
35
+ import {
36
+ among,
37
+ type Expr,
38
+ type Extension,
39
+ FALSE,
40
+ lit,
41
+ lookup,
42
+ type Screen,
43
+ type Site,
44
+ Unsupported,
45
+ val,
46
+ } from '@yaks/sql'
47
+ import type { Statements } from '@yaks/sql'
48
+ import { type Near, nearest, type Rank, vectorOf } from './near.js'
49
+ import { type Field, fields, searched } from './fields.js'
50
+ import type { ImageIndex } from './image.ts'
51
+ import { screened, visibleVectors } from './visibility.js'
52
+
53
+ /** The `.order=` value that means "nearest first". */
54
+ export let SIMILAR = 'similar'
55
+
56
+ /** The name of the query-only component that carries the similarity back. */
57
+ export let RANK = 'rank'
58
+
59
+ /** How a `.near` neighbourhood is bounded. */
60
+ export type SemanticOpts = {
61
+ /** The configured text sources that fed the stored vectors. */
62
+ fields?: Field[]
63
+ /** how many neighbours the directive selects (default 8) */
64
+ limit?: number
65
+ /** the similarity a neighbour must reach to be selected at all (default 0) */
66
+ floor?: number
67
+ /** the ranking to use; the default is an exact scan over the stored vectors */
68
+ rank?: Rank
69
+ /** The private image index in a read that has authorized its use. */
70
+ image?: () => ImageIndex | undefined
71
+ }
72
+
73
+ /**
74
+ * The @yaks/sql extension, plus the two things a caller wants back from it: the
75
+ * neighbourhood it resolved, and the bundles with their scores attached.
76
+ */
77
+ export type Semantic = Extension & {
78
+ /** the neighbourhood the compiled `.near` selected, most similar first */
79
+ neighbours: () => Near[]
80
+ /** those bundles, nearest first, each carrying the query-only `rank` comp */
81
+ rank: (bundles: Bundle[]) => Bundle[]
82
+ }
83
+
84
+ /**
85
+ * A semantic query extension over a database's stored vectors.
86
+ *
87
+ * What it needs is the vector space, not the embedder: a `.near` anchor reads
88
+ * the vector already stored for it and never calls the network, because
89
+ * compiling a query is synchronous. Embedding text that has no entity yet is
90
+ * the sweep's job — which is why a server whose embedder is still waiting for a
91
+ * key ranks perfectly well over the vectors it already has.
92
+ */
93
+ export let semantic = (
94
+ db: Statements,
95
+ space: { model: string } | null,
96
+ opts: SemanticOpts = {},
97
+ ): Semantic => {
98
+ let held: Near[] | null = null
99
+ // What the rest of this query selects — not asked for until a `.near` needs
100
+ // it.
101
+ let asked: Screen | null = null
102
+ let rank: Rank = opts.rank ??
103
+ ((query, limit, within) =>
104
+ space ? nearest(db, query, { model: space.model, limit, within }) : [])
105
+
106
+ // The fields over components a table stands for (@yaks/sql `Site.absent`):
107
+ // one nothing has written yet holds no text, and excludes no entity.
108
+ let live = (site: Site): Field[] => {
109
+ let all = opts.fields ?? fields(site.vocab, searched)
110
+ let gone = new Set(site.absent)
111
+ if (!gone.size) return all
112
+ return all.filter((f) => !gone.has(f.comp) && !(f.on && gone.has(f.on)))
113
+ .map((f) =>
114
+ f.not?.some((n) => gone.has(n))
115
+ ? { ...f, not: f.not.filter((n) => !gone.has(n)) }
116
+ : f
117
+ )
118
+ }
119
+ let near = (anchor: string, site: Site): Expr | null => {
120
+ let image = opts.image?.()
121
+ if (!image && !space) return null
122
+ let fields = image ? [] : live(site)
123
+ let visible = visibleVectors(
124
+ site.vocab,
125
+ fields,
126
+ site.visibility,
127
+ site.absent,
128
+ )
129
+ let vec = image
130
+ ? image.get(anchor, visible)
131
+ : space && vectorOf(db, anchor, space.model, visible)
132
+ if (!vec) {
133
+ held = []
134
+ return FALSE
135
+ }
136
+ let limit = opts.limit ?? 8
137
+ let scope = asked?.()
138
+ // The ordinary candidate screen already enforces entity visibility. Only
139
+ // vector-source restrictions add information to that screen; checking the
140
+ // same entity policy twice makes every broad scan pay twice per vector.
141
+ let sources = scope && site.visibility
142
+ ? visibleVectors(
143
+ site.vocab,
144
+ fields,
145
+ { ...site.visibility, entity: undefined },
146
+ site.absent,
147
+ )
148
+ : visible
149
+ let within = screened(scope, sources)
150
+ // An anchor with no vector has no neighbourhood, and compiling that to a
151
+ // constant false selects nothing rather than widening to everything.
152
+ // The ranking is asked for one extra: the anchor scores 1 against itself
153
+ // and would otherwise eat a place, and nothing is its own neighbour.
154
+ held = (image?.nearest ?? rank)(vec, limit + 1, within)
155
+ .filter((n) => n.entity != anchor && n.similarity >= (opts.floor ?? 0))
156
+ .slice(0, limit)
157
+ if (!held.length) return FALSE
158
+ return among(site.owner, held.map((n) => val(n.owner)))
159
+ }
160
+
161
+ return {
162
+ name: 'embedding',
163
+ // A neighbourhood is `limit` owners at most, read by key.
164
+ few: () => ['near'],
165
+ begin: (screen) => {
166
+ held = null
167
+ asked = screen
168
+ },
169
+ compile: {
170
+ near: (clause, site) =>
171
+ clause.kind == 'near' ? near(clause.value, site) : null,
172
+ },
173
+ order: (value, site) => {
174
+ if (value != SIMILAR) return null
175
+ if (!held) {
176
+ throw new Unsupported(
177
+ `.order=${SIMILAR}`,
178
+ 'nothing to rank by — it orders a .near neighbourhood',
179
+ '@yaks/embedding',
180
+ )
181
+ }
182
+ // An empty neighbourhood selects no rows, so there is nothing to order.
183
+ if (!held.length) return lit(null)
184
+ // The neighbours are already in order, so their position is the sort key.
185
+ // Site.owner is this row's stable integer id, including cursor anchors.
186
+ return lookup(
187
+ site.owner,
188
+ held.map((n, i) => [n.owner, lit(i)]),
189
+ { stable: true },
190
+ lit(held.length),
191
+ )
192
+ },
193
+ neighbours: () => held ?? [],
194
+ rank: (bundles) => {
195
+ let by = new Map((held ?? []).map((n) => [n.entity, n.similarity]))
196
+ let score = (b: Bundle) => by.get(b.entity.eid) ?? -Infinity
197
+ // A bundle the neighbourhood does not name keeps its shape and sorts
198
+ // last: this decorates an answer, it never silently drops one.
199
+ return [...bundles]
200
+ .sort((a, b) => score(b) - score(a))
201
+ .map((b) =>
202
+ by.has(b.entity.eid) ? { ...b, [RANK]: { score: score(b) } } : b
203
+ )
204
+ },
205
+ }
206
+ }