-
Notifications
You must be signed in to change notification settings - Fork 336
/
Copy pathvectordiskann.c
1789 lines (1596 loc) · 62.8 KB
/
vectordiskann.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
** 2024-03-23
**
** Copyright 2024 the libSQL authors
**
** Permission is hereby granted, free of charge, to any person obtaining a copy of
** this software and associated documentation files (the "Software"), to deal in
** the Software without restriction, including without limitation the rights to
** use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
** the Software, and to permit persons to whom the Software is furnished to do so,
** subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in all
** copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
** FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
** COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
** IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**
******************************************************************************
**
** DiskANN for SQLite/libSQL.
**
** The algorithm is described in the following publications:
**
** Suhas Jayaram Subramanya et al (2019). DiskANN: Fast Accurate Billion-point
** Nearest Neighbor Search on a Single Node. In NeurIPS 2019.
**
** Aditi Singh et al (2021). FreshDiskANN: A Fast and Accurate Graph-Based ANN
** Index for Streaming Similarity Search. ArXiv.
**
** Yu Pan et al (2023). LM-DiskANN: Low Memory Footprint in Disk-Native
** Dynamic Graph-Based ANN Indexing. In IEEE BIGDATA 2023.
**
** Here is the (internal, non-API) interface between this module and the
** rest of the SQLite system:
**
** diskAnnCreateIndex() Create new index and fill default values for diskann parameters (if some of them are omitted)
** diskAnnDropIndex() Delete existing index
** diskAnnClearIndex() Truncate existing index
** diskAnnOpenIndex() Open index for operations (allocate all necessary internal structures)
** diskAnnCloseIndex() Close index and free associated resources
** diskAnnSearch() Search K nearest neighbours to the query vector in an opened index
** diskAnnInsert() Insert single new(!) vector in an opened index
** diskAnnDelete() Delete row by key from an opened index
*/
#ifndef SQLITE_OMIT_VECTOR
#include "math.h"
#include "sqliteInt.h"
#include "vectorIndexInt.h"
// #define SQLITE_VECTOR_TRACE
#if defined(SQLITE_DEBUG) && defined(SQLITE_VECTOR_TRACE)
#define DiskAnnTrace(X) sqlite3DebugPrintf X;
#else
#define DiskAnnTrace(X)
#endif
// limit to the sql part which we render in order to perform operations with shadow table
// we render this parts of SQL on stack - thats why we have hard limit on this
// stack simplify memory managment code and also doesn't impose very strict limits here since 128 bytes for column names should be enough for almost all use cases
#define DISKANN_SQL_RENDER_LIMIT 128
// limit to the maximum size of DiskANN block (128 MB)
// even with 1MB we can store tens of thousands of nodes in several GBs - which is already too much
// but we are "generous" here and allow user to store up to 128MB blobs
#define DISKANN_MAX_BLOCK_SZ 134217728
/*
* Due to historical reasons parameter for index block size were stored as u16 value and divided by 512 (2^9)
* So, we will make inverse transform before initializing index from stored parameters
*/
#define DISKANN_BLOCK_SIZE_SHIFT 9
typedef struct VectorPair VectorPair;
typedef struct DiskAnnSearchCtx DiskAnnSearchCtx;
typedef struct DiskAnnNode DiskAnnNode;
// VectorPair represents single vector where pNode is an exact representation and pEdge - compressed representation
// (pEdge pointer always equals to pNode if pNodeType == pEdgeType)
struct VectorPair {
int nodeType;
int edgeType;
Vector *pNode;
Vector *pEdge;
};
// DiskAnnNode represents single node in the DiskAnn graph
struct DiskAnnNode {
u64 nRowid; /* node id */
int visited; /* is this node visited? */
DiskAnnNode *pNext; /* next node in the visited list */
BlobSpot *pBlobSpot; /* reference to the blob with node data (can be NULL when data actually is not needed; for example - node waiting in the queue) */
};
/*
* DiskAnnSearchCtx stores information required for search operation to succeed
*
* search context usually "borrows" candidates (storing them in aCandidates or visitedList)
* so caller which puts nodes in the context can forget about resource managmenet (context will take care of this)
*/
struct DiskAnnSearchCtx {
VectorPair query; /* initial query vector; user query for SELECT and row vector for INSERT */
DiskAnnNode **aCandidates; /* array of unvisited candidates ordered by distance (possibly approximate) to the query (ascending) */
float *aDistances; /* array of distances (possible approximate) to the query vector */
unsigned int nCandidates; /* current size of aCandidates/aDistances arrays */
unsigned int maxCandidates; /* max size of aCandidates/aDistances arrays */
DiskAnnNode **aTopCandidates; /* top candidates with exact distance calculated */
float *aTopDistances; /* top candidates exact distances */
int nTopCandidates; /* current size of aTopCandidates/aTopDistances arrays */
int maxTopCandidates; /* max size of aTopCandidates/aTopDistances arrays */
DiskAnnNode *visitedList; /* list of all visited candidates (so, candidates from aCandidates array either got replaced or moved to the visited list) */
unsigned int nUnvisited; /* amount of unvisited candidates in the aCadidates array */
int blobMode; /* DISKANN_BLOB_READONLY if we wont modify node blobs; DISKANN_BLOB_WRITABLE - otherwise */
};
/**************************************************************************
** Serialization utilities
**************************************************************************/
static inline u16 readLE16(const unsigned char *p){
return (u16)p[0] | (u16)p[1] << 8;
}
static inline u32 readLE32(const unsigned char *p){
return (u32)p[0] | (u32)p[1] << 8 | (u32)p[2] << 16 | (u32)p[3] << 24;
}
static inline u64 readLE64(const unsigned char *p){
return (u64)p[0]
| (u64)p[1] << 8
| (u64)p[2] << 16
| (u64)p[3] << 24
| (u64)p[4] << 32
| (u64)p[5] << 40
| (u64)p[6] << 48
| (u64)p[7] << 56;
}
static inline void writeLE16(unsigned char *p, u16 v){
p[0] = v;
p[1] = v >> 8;
}
static inline void writeLE32(unsigned char *p, u32 v){
p[0] = v;
p[1] = v >> 8;
p[2] = v >> 16;
p[3] = v >> 24;
}
static inline void writeLE64(unsigned char *p, u64 v){
p[0] = v;
p[1] = v >> 8;
p[2] = v >> 16;
p[3] = v >> 24;
p[4] = v >> 32;
p[5] = v >> 40;
p[6] = v >> 48;
p[7] = v >> 56;
}
/**************************************************************************
** BlobSpot utilities
**************************************************************************/
// sqlite3_blob_* API return SQLITE_ERROR in any case but we need to distinguish between "row not found" and other errors in some cases
static int blobSpotConvertRc(const DiskAnnIndex *pIndex, int rc){
if( rc == SQLITE_ERROR && strncmp(sqlite3_errmsg(pIndex->db), "no such rowid", 13) == 0 ){
return DISKANN_ROW_NOT_FOUND;
}
return rc;
}
int blobSpotCreate(const DiskAnnIndex *pIndex, BlobSpot **ppBlobSpot, u64 nRowid, int nBufferSize, int isWritable) {
int rc = SQLITE_OK;
BlobSpot *pBlobSpot;
u8 *pBuffer;
DiskAnnTrace(("blob spot created: rowid=%lld, isWritable=%d\n", nRowid, isWritable));
assert( nBufferSize > 0 );
pBlobSpot = sqlite3_malloc(sizeof(BlobSpot));
if( pBlobSpot == NULL ){
rc = SQLITE_NOMEM_BKPT;
goto out;
}
pBuffer = sqlite3_malloc(nBufferSize);
if( pBuffer == NULL ){
rc = SQLITE_NOMEM_BKPT;
goto out;
}
// open blob in the end so we don't need to close it in error case
rc = sqlite3_blob_open(pIndex->db, pIndex->zDbSName, pIndex->zShadow, "data", nRowid, isWritable, &pBlobSpot->pBlob);
rc = blobSpotConvertRc(pIndex, rc);
if( rc != SQLITE_OK ){
goto out;
}
pBlobSpot->nRowid = nRowid;
pBlobSpot->pBuffer = pBuffer;
pBlobSpot->nBufferSize = nBufferSize;
pBlobSpot->isWritable = isWritable;
pBlobSpot->isInitialized = 0;
pBlobSpot->isAborted = 0;
*ppBlobSpot = pBlobSpot;
return SQLITE_OK;
out:
if( pBlobSpot != NULL ){
sqlite3_free(pBlobSpot);
}
if( pBuffer != NULL ){
sqlite3_free(pBuffer);
}
return rc;
}
int blobSpotReload(DiskAnnIndex *pIndex, BlobSpot *pBlobSpot, u64 nRowid, int nBufferSize) {
int rc;
DiskAnnTrace(("blob spot reload: rowid=%lld\n", nRowid));
assert( pBlobSpot != NULL && (pBlobSpot->pBlob != NULL || pBlobSpot->isAborted ) );
assert( pBlobSpot->nBufferSize == nBufferSize );
if( pBlobSpot->nRowid == nRowid && pBlobSpot->isInitialized ){
return SQLITE_OK;
}
// if last blob open/reopen operation aborted - we need to close current blob and open new one
// (as all operations over aborted blob will return SQLITE_ABORT error)
if( pBlobSpot->isAborted ){
if( pBlobSpot->pBlob != NULL ){
sqlite3_blob_close(pBlobSpot->pBlob);
}
pBlobSpot->pBlob = NULL;
pBlobSpot->isInitialized = 0;
pBlobSpot->isAborted = 0;
pBlobSpot->nRowid = nRowid;
rc = sqlite3_blob_open(pIndex->db, pIndex->zDbSName, pIndex->zShadow, "data", nRowid, pBlobSpot->isWritable, &pBlobSpot->pBlob);
rc = blobSpotConvertRc(pIndex, rc);
if( rc != SQLITE_OK ){
goto abort;
}
}
if( pBlobSpot->nRowid != nRowid ){
rc = sqlite3_blob_reopen(pBlobSpot->pBlob, nRowid);
rc = blobSpotConvertRc(pIndex, rc);
if( rc != SQLITE_OK ){
goto abort;
}
pBlobSpot->nRowid = nRowid;
pBlobSpot->isInitialized = 0;
}
rc = sqlite3_blob_read(pBlobSpot->pBlob, pBlobSpot->pBuffer, nBufferSize, 0);
if( rc != SQLITE_OK ){
goto abort;
}
pIndex->nReads++;
pBlobSpot->isInitialized = 1;
return SQLITE_OK;
abort:
pBlobSpot->isAborted = 1;
pBlobSpot->isInitialized = 0;
return rc;
}
int blobSpotFlush(DiskAnnIndex* pIndex, BlobSpot *pBlobSpot) {
int rc = sqlite3_blob_write(pBlobSpot->pBlob, pBlobSpot->pBuffer, pBlobSpot->nBufferSize, 0);
if( rc != SQLITE_OK ){
return rc;
}
pIndex->nWrites++;
return rc;
}
void blobSpotFree(BlobSpot *pBlobSpot) {
if( pBlobSpot->pBlob != NULL ){
sqlite3_blob_close(pBlobSpot->pBlob);
}
if( pBlobSpot->pBuffer != NULL ){
sqlite3_free(pBlobSpot->pBuffer);
}
sqlite3_free(pBlobSpot);
}
/**************************************************************************
** Layout specific utilities
**************************************************************************/
int nodeMetadataSize(int nFormatVersion){
if( nFormatVersion <= VECTOR_FORMAT_V2 ){
return (sizeof(u64) + sizeof(u16));
}else{
return (sizeof(u64) + sizeof(u64));
}
}
int edgeMetadataSize(int nFormatVersion){
return (sizeof(u64) + sizeof(u64));
}
int nodeEdgeOverhead(int nFormatVersion, int nEdgeVectorSize){
return nEdgeVectorSize + edgeMetadataSize(nFormatVersion);
}
int nodeOverhead(int nFormatVersion, int nNodeVectorSize){
return nNodeVectorSize + nodeMetadataSize(nFormatVersion);
}
int nodeEdgesMaxCount(const DiskAnnIndex *pIndex){
unsigned int nMaxEdges = (pIndex->nBlockSize - nodeOverhead(pIndex->nFormatVersion, pIndex->nNodeVectorSize)) / nodeEdgeOverhead(pIndex->nFormatVersion, pIndex->nEdgeVectorSize);
assert( nMaxEdges > 0);
return nMaxEdges;
}
int nodeEdgesMetadataOffset(const DiskAnnIndex *pIndex){
unsigned int offset;
unsigned int nMaxEdges = nodeEdgesMaxCount(pIndex);
offset = nodeMetadataSize(pIndex->nFormatVersion) + pIndex->nNodeVectorSize + nMaxEdges * pIndex->nEdgeVectorSize;
assert( offset <= pIndex->nBlockSize );
return offset;
}
void nodeBinInit(const DiskAnnIndex *pIndex, BlobSpot *pBlobSpot, u64 nRowid, Vector *pVector){
assert( nodeMetadataSize(pIndex->nFormatVersion) + pIndex->nNodeVectorSize <= pBlobSpot->nBufferSize );
memset(pBlobSpot->pBuffer, 0, pBlobSpot->nBufferSize);
writeLE64(pBlobSpot->pBuffer, nRowid);
// neighbours count already zero after memset - no need to set it explicitly
vectorSerializeToBlob(pVector, pBlobSpot->pBuffer + nodeMetadataSize(pIndex->nFormatVersion), pIndex->nNodeVectorSize);
}
void nodeBinVector(const DiskAnnIndex *pIndex, const BlobSpot *pBlobSpot, Vector *pVector) {
assert( nodeMetadataSize(pIndex->nFormatVersion) + pIndex->nNodeVectorSize <= pBlobSpot->nBufferSize );
vectorInitStatic(pVector, pIndex->nNodeVectorType, pIndex->nVectorDims, pBlobSpot->pBuffer + nodeMetadataSize(pIndex->nFormatVersion));
}
u16 nodeBinEdges(const DiskAnnIndex *pIndex, const BlobSpot *pBlobSpot) {
assert( nodeMetadataSize(pIndex->nFormatVersion) <= pBlobSpot->nBufferSize );
return readLE16(pBlobSpot->pBuffer + sizeof(u64));
}
void nodeBinEdge(const DiskAnnIndex *pIndex, const BlobSpot *pBlobSpot, int iEdge, u64 *pRowid, float *pDistance, Vector *pVector) {
u32 distance;
int offset = nodeEdgesMetadataOffset(pIndex);
if( pRowid != NULL ){
assert( offset + (iEdge + 1) * edgeMetadataSize(pIndex->nFormatVersion) <= pBlobSpot->nBufferSize );
*pRowid = readLE64(pBlobSpot->pBuffer + offset + iEdge * edgeMetadataSize(pIndex->nFormatVersion) + sizeof(u64));
}
if( pIndex->nFormatVersion != VECTOR_FORMAT_V1 && pDistance != NULL ){
distance = readLE32(pBlobSpot->pBuffer + offset + iEdge * edgeMetadataSize(pIndex->nFormatVersion) + sizeof(u32));
*pDistance = *((float*)&distance);
}
if( pVector != NULL ){
assert( nodeMetadataSize(pIndex->nFormatVersion) + pIndex->nNodeVectorSize + iEdge * pIndex->nEdgeVectorSize < offset );
vectorInitStatic(
pVector,
pIndex->nEdgeVectorType,
pIndex->nVectorDims,
pBlobSpot->pBuffer + nodeMetadataSize(pIndex->nFormatVersion) + pIndex->nNodeVectorSize + iEdge * pIndex->nEdgeVectorSize
);
}
}
int nodeBinEdgeFindIdx(const DiskAnnIndex *pIndex, const BlobSpot *pBlobSpot, u64 nRowid) {
int i, nEdges = nodeBinEdges(pIndex, pBlobSpot);
// todo: if edges will be sorted by identifiers we can use binary search here (although speed up will be visible only on pretty loaded nodes: >128 edges)
for(i = 0; i < nEdges; i++){
u64 edgeId;
nodeBinEdge(pIndex, pBlobSpot, i, &edgeId, NULL, NULL);
if( edgeId == nRowid ){
return i;
}
}
return -1;
}
void nodeBinPruneEdges(const DiskAnnIndex *pIndex, BlobSpot *pBlobSpot, int nPruned) {
assert( 0 <= nPruned && nPruned <= nodeBinEdges(pIndex, pBlobSpot) );
writeLE16(pBlobSpot->pBuffer + sizeof(u64), nPruned);
}
// replace edge at position iReplace or add new one if iReplace == nEdges
void nodeBinReplaceEdge(const DiskAnnIndex *pIndex, BlobSpot *pBlobSpot, int iReplace, u64 nRowid, float distance, Vector *pVector) {
int nMaxEdges = nodeEdgesMaxCount(pIndex);
int nEdges = nodeBinEdges(pIndex, pBlobSpot);
int edgeVectorOffset, edgeMetaOffset, itemsToMove;
assert( 0 <= iReplace && iReplace < nMaxEdges );
assert( 0 <= iReplace && iReplace <= nEdges );
if( iReplace == nEdges ){
nEdges++;
}
edgeVectorOffset = nodeMetadataSize(pIndex->nFormatVersion) + pIndex->nNodeVectorSize + iReplace * pIndex->nEdgeVectorSize;
edgeMetaOffset = nodeEdgesMetadataOffset(pIndex) + iReplace * edgeMetadataSize(pIndex->nFormatVersion);
assert( edgeVectorOffset + pIndex->nEdgeVectorSize <= pBlobSpot->nBufferSize );
assert( edgeMetaOffset + edgeMetadataSize(pIndex->nFormatVersion) <= pBlobSpot->nBufferSize );
vectorSerializeToBlob(pVector, pBlobSpot->pBuffer + edgeVectorOffset, pIndex->nEdgeVectorSize);
writeLE32(pBlobSpot->pBuffer + edgeMetaOffset + sizeof(u32), *((u32*)&distance));
writeLE64(pBlobSpot->pBuffer + edgeMetaOffset + sizeof(u64), nRowid);
writeLE16(pBlobSpot->pBuffer + sizeof(u64), nEdges);
}
// delete edge at position iDelete by swapping it with the last edge
void nodeBinDeleteEdge(const DiskAnnIndex *pIndex, BlobSpot *pBlobSpot, int iDelete) {
int nEdges = nodeBinEdges(pIndex, pBlobSpot);
int edgeVectorOffset, edgeMetaOffset, lastVectorOffset, lastMetaOffset;
assert( 0 <= iDelete && iDelete < nEdges );
edgeVectorOffset = nodeMetadataSize(pIndex->nFormatVersion) + pIndex->nNodeVectorSize + iDelete * pIndex->nEdgeVectorSize;
lastVectorOffset = nodeMetadataSize(pIndex->nFormatVersion) + pIndex->nNodeVectorSize + (nEdges - 1) * pIndex->nEdgeVectorSize;
edgeMetaOffset = nodeEdgesMetadataOffset(pIndex) + iDelete * edgeMetadataSize(pIndex->nFormatVersion);
lastMetaOffset = nodeEdgesMetadataOffset(pIndex) + (nEdges - 1) * edgeMetadataSize(pIndex->nFormatVersion);
assert( edgeVectorOffset + pIndex->nEdgeVectorSize <= pBlobSpot->nBufferSize );
assert( lastVectorOffset + pIndex->nEdgeVectorSize <= pBlobSpot->nBufferSize );
assert( edgeMetaOffset + edgeMetadataSize(pIndex->nFormatVersion) <= pBlobSpot->nBufferSize );
assert( lastMetaOffset + edgeMetadataSize(pIndex->nFormatVersion) <= pBlobSpot->nBufferSize );
if( edgeVectorOffset < lastVectorOffset ){
memmove(pBlobSpot->pBuffer + edgeVectorOffset, pBlobSpot->pBuffer + lastVectorOffset, pIndex->nEdgeVectorSize);
memmove(pBlobSpot->pBuffer + edgeMetaOffset, pBlobSpot->pBuffer + lastMetaOffset, edgeMetadataSize(pIndex->nFormatVersion));
}
writeLE16(pBlobSpot->pBuffer + sizeof(u64), nEdges - 1);
}
void nodeBinDebug(const DiskAnnIndex *pIndex, const BlobSpot *pBlobSpot) {
#if defined(SQLITE_DEBUG) && defined(SQLITE_VECTOR_TRACE)
int nEdges, nMaxEdges, i;
u64 nRowid;
float distance = 0;
Vector vector;
nEdges = nodeBinEdges(pIndex, pBlobSpot);
nMaxEdges = nodeEdgesMaxCount(pIndex);
nodeBinVector(pIndex, pBlobSpot, &vector);
DiskAnnTrace(("debug blob content for root=%lld (buffer size=%d)\n", pBlobSpot->nRowid, pBlobSpot->nBufferSize));
DiskAnnTrace((" nEdges=%d, nMaxEdges=%d, vector=", nEdges, nMaxEdges));
vectorDump(&vector);
for(i = 0; i < nEdges; i++){
nodeBinEdge(pIndex, pBlobSpot, i, &nRowid, &distance, &vector);
DiskAnnTrace((" to=%lld, distance=%f, vector=", nRowid, distance));
vectorDump(&vector);
}
#endif
}
/*******************************************************************************
** DiskANN shadow index operations (some of them exposed as DiskANN internal API)
********************************************************************************/
int diskAnnCreateIndex(
sqlite3 *db,
const char *zDbSName,
const char *zIdxName,
const VectorIdxKey *pKey,
VectorIdxParams *pParams,
const char **pzErrMsg
){
int rc;
int type, dims, metric, neighbours;
u64 maxNeighborsParam, blockSizeBytes;
char *zSql;
const char *zRowidColumnName;
char columnSqlDefs[VECTOR_INDEX_SQL_RENDER_LIMIT]; // definition of columns (e.g. index_key INTEGER BINARY, index_key1 TEXT, ...)
char columnSqlNames[VECTOR_INDEX_SQL_RENDER_LIMIT]; // just column names (e.g. index_key, index_key1, index_key2, ...)
if( vectorIdxKeyDefsRender(pKey, "index_key", columnSqlDefs, sizeof(columnSqlDefs)) != 0 ){
return SQLITE_ERROR;
}
if( vectorIdxKeyNamesRender(pKey->nKeyColumns, "index_key", columnSqlNames, sizeof(columnSqlNames)) != 0 ){
return SQLITE_ERROR;
}
if( vectorIdxParamsPutU64(pParams, VECTOR_INDEX_TYPE_PARAM_ID, VECTOR_INDEX_TYPE_DISKANN) != 0 ){
return SQLITE_ERROR;
}
type = vectorIdxParamsGetU64(pParams, VECTOR_TYPE_PARAM_ID);
if( type == 0 ){
return SQLITE_ERROR;
}
dims = vectorIdxParamsGetU64(pParams, VECTOR_DIM_PARAM_ID);
if( dims == 0 ){
return SQLITE_ERROR;
}
assert( 0 < dims && dims <= MAX_VECTOR_SZ );
metric = vectorIdxParamsGetU64(pParams, VECTOR_METRIC_TYPE_PARAM_ID);
if( metric == 0 ){
metric = VECTOR_METRIC_TYPE_COS;
if( vectorIdxParamsPutU64(pParams, VECTOR_METRIC_TYPE_PARAM_ID, metric) != 0 ){
return SQLITE_ERROR;
}
}
neighbours = vectorIdxParamsGetU64(pParams, VECTOR_COMPRESS_NEIGHBORS_PARAM_ID);
if( neighbours == VECTOR_TYPE_FLOAT1BIT && metric != VECTOR_METRIC_TYPE_COS ){
*pzErrMsg = "1-bit compression available only for cosine metric";
return SQLITE_ERROR;
}
if( neighbours == 0 ){
neighbours = type;
}
maxNeighborsParam = vectorIdxParamsGetU64(pParams, VECTOR_MAX_NEIGHBORS_PARAM_ID);
if( maxNeighborsParam == 0 ){
// 3 D**(1/2) gives good recall values (90%+)
// we also want to keep disk overhead at moderate level - 50x of the disk size increase is the current upper bound
maxNeighborsParam = MIN(3 * ((int)(sqrt(dims)) + 1), (50 * nodeOverhead(VECTOR_FORMAT_DEFAULT, vectorDataSize(type, dims))) / nodeEdgeOverhead(VECTOR_FORMAT_DEFAULT, vectorDataSize(neighbours, dims)) + 1);
}
blockSizeBytes = nodeOverhead(VECTOR_FORMAT_DEFAULT, vectorDataSize(type, dims)) + maxNeighborsParam * (u64)nodeEdgeOverhead(VECTOR_FORMAT_DEFAULT, vectorDataSize(neighbours, dims));
if( blockSizeBytes > DISKANN_MAX_BLOCK_SZ ){
return SQLITE_ERROR;
}
if( vectorIdxParamsPutU64(pParams, VECTOR_BLOCK_SIZE_PARAM_ID, MAX(256, blockSizeBytes)) != 0 ){
return SQLITE_ERROR;
}
if( vectorIdxParamsGetF64(pParams, VECTOR_PRUNING_ALPHA_PARAM_ID) == 0 ){
if( vectorIdxParamsPutF64(pParams, VECTOR_PRUNING_ALPHA_PARAM_ID, VECTOR_PRUNING_ALPHA_DEFAULT) != 0 ){
return SQLITE_ERROR;
}
}
if( vectorIdxParamsGetU64(pParams, VECTOR_INSERT_L_PARAM_ID) == 0 ){
if( vectorIdxParamsPutU64(pParams, VECTOR_INSERT_L_PARAM_ID, VECTOR_INSERT_L_DEFAULT) != 0 ){
return SQLITE_ERROR;
}
}
if( vectorIdxParamsGetU64(pParams, VECTOR_SEARCH_L_PARAM_ID) == 0 ){
if( vectorIdxParamsPutU64(pParams, VECTOR_SEARCH_L_PARAM_ID, VECTOR_SEARCH_L_DEFAULT) != 0 ){
return SQLITE_ERROR;
}
}
// we want to preserve rowid - so it must be explicit in the schema
// also, we don't want to store redundant set of fields - so the strategy is like that:
// 1. If we have single PK with INTEGER affinity and BINARY collation we only need single PK of same type
// 2. In other case we need rowid PK and unique index over other fields
if( vectorIdxKeyRowidLike(pKey) ){
zSql = sqlite3MPrintf(
db,
"CREATE TABLE IF NOT EXISTS \"%w\".%s_shadow (%s, data BLOB, PRIMARY KEY (%s))",
zDbSName,
zIdxName,
columnSqlDefs,
columnSqlNames
);
zRowidColumnName = "index_key";
}else{
zSql = sqlite3MPrintf(
db,
"CREATE TABLE IF NOT EXISTS \"%w\".%s_shadow (rowid INTEGER PRIMARY KEY, %s, data BLOB, UNIQUE (%s))",
zDbSName,
zIdxName,
columnSqlDefs,
columnSqlNames
);
zRowidColumnName = "rowid";
}
rc = sqlite3_exec(db, zSql, 0, 0, 0);
sqlite3DbFree(db, zSql);
if( rc != SQLITE_OK ){
return rc;
}
/*
* vector blobs are usually pretty huge (more than a page size, for example, node block for 1024d f32 embeddings with 1bit compression will occupy ~20KB)
* in this case, main table B-Tree takes on redundant shape where all leaf nodes has only 1 cell
*
* as we have a query which selects random row using OFFSET/LIMIT trick - we will need to read all these leaf nodes pages just to skip them
* so, in order to remove this overhead for random row selection - we creating an index with just single column used
* in this case B-Tree leafs will be full of rowids and the overhead for page reads will be very small
*/
zSql = sqlite3MPrintf(
db,
"CREATE INDEX IF NOT EXISTS \"%w\".%s_shadow_idx ON %s_shadow (%s)",
zDbSName,
zIdxName,
zIdxName,
zRowidColumnName
);
rc = sqlite3_exec(db, zSql, 0, 0, 0);
sqlite3DbFree(db, zSql);
return rc;
}
int diskAnnClearIndex(sqlite3 *db, const char *zDbSName, const char *zIdxName) {
char *zSql = sqlite3MPrintf(db, "DELETE FROM \"%w\".%s_shadow", zDbSName, zIdxName);
int rc = sqlite3_exec(db, zSql, 0, 0, 0);
sqlite3DbFree(db, zSql);
return rc;
}
int diskAnnDropIndex(sqlite3 *db, const char *zDbSName, const char *zIdxName){
char *zSql = sqlite3MPrintf(db, "DROP TABLE \"%w\".%s_shadow", zDbSName, zIdxName);
int rc = sqlite3_exec(db, zSql, 0, 0, 0);
sqlite3DbFree(db, zSql);
return rc;
}
/*
* Select random row from the shadow table and set its rowid to pRowid
* returns SQLITE_DONE if no row found (this will be used to determine case when table is empty)
* TODO: we need to make this selection procedure faster - now it works in linear time
*/
static int diskAnnSelectRandomShadowRow(const DiskAnnIndex *pIndex, u64 *pRowid){
int rc;
sqlite3_stmt *pStmt = NULL;
char *zSql = NULL;
zSql = sqlite3MPrintf(
pIndex->db,
"SELECT rowid FROM \"%w\".%s LIMIT 1 OFFSET ABS(RANDOM()) %% MAX((SELECT COUNT(*) FROM \"%w\".%s), 1)",
pIndex->zDbSName, pIndex->zShadow, pIndex->zDbSName, pIndex->zShadow
);
if( zSql == NULL ){
rc = SQLITE_NOMEM_BKPT;
goto out;
}
rc = sqlite3_prepare_v2(pIndex->db, zSql, -1, &pStmt, 0);
if( rc != SQLITE_OK ){
goto out;
}
rc = sqlite3_step(pStmt);
if( rc != SQLITE_ROW ){
goto out;
}
assert( sqlite3_column_type(pStmt, 0) == SQLITE_INTEGER );
*pRowid = sqlite3_column_int64(pStmt, 0);
// check that we has only single row matching the criteria (otherwise - this is a bug)
assert( sqlite3_step(pStmt) == SQLITE_DONE );
rc = SQLITE_OK;
out:
if( pStmt != NULL ){
sqlite3_finalize(pStmt);
}
if( zSql != NULL ){
sqlite3DbFree(pIndex->db, zSql);
}
return rc;
}
/*
* Find row by keys from pInRow and set its rowid to pRowid
* returns SQLITE_DONE if no row found (this will be used to determine case when table is empty)
*/
static int diskAnnGetShadowRowid(const DiskAnnIndex *pIndex, const VectorInRow *pInRow, u64 *pRowid) {
int rc, i;
sqlite3_stmt *pStmt = NULL;
char *zSql = NULL;
char columnSqlNames[VECTOR_INDEX_SQL_RENDER_LIMIT]; // just column names (e.g. index_key, index_key1, index_key2, ...)
char columnSqlPlaceholders[VECTOR_INDEX_SQL_RENDER_LIMIT]; // just placeholders (e.g. ?,?,?, ...)
if( vectorIdxKeyNamesRender(pInRow->nKeys, "index_key", columnSqlNames, sizeof(columnSqlNames)) != 0 ){
rc = SQLITE_ERROR;
goto out;
}
if( vectorInRowPlaceholderRender(pInRow, columnSqlPlaceholders, sizeof(columnSqlPlaceholders)) != 0 ){
rc = SQLITE_ERROR;
goto out;
}
zSql = sqlite3MPrintf(
pIndex->db,
"SELECT rowid FROM \"%w\".%s WHERE (%s) = (%s)",
pIndex->zDbSName, pIndex->zShadow, columnSqlNames, columnSqlPlaceholders
);
if( zSql == NULL ){
rc = SQLITE_NOMEM;
goto out;
}
rc = sqlite3_prepare_v2(pIndex->db, zSql, -1, &pStmt, 0);
if( rc != SQLITE_OK ){
goto out;
}
for(i = 0; i < pInRow->nKeys; i++){
rc = sqlite3_bind_value(pStmt, i + 1, vectorInRowKey(pInRow, i));
if( rc != SQLITE_OK ){
goto out;
}
}
rc = sqlite3_step(pStmt);
if( rc != SQLITE_ROW ){
goto out;
}
assert( sqlite3_column_type(pStmt, 0) == SQLITE_INTEGER );
*pRowid = sqlite3_column_int64(pStmt, 0);
// check that we has only single row matching the criteria (otherwise - this is a bug)
assert( sqlite3_step(pStmt) == SQLITE_DONE );
rc = SQLITE_OK;
out:
if( pStmt != NULL ){
sqlite3_finalize(pStmt);
}
if( zSql != NULL ){
sqlite3DbFree(pIndex->db, zSql);
}
return rc;
}
/*
* Find row keys by rowid and put them in right into pRows structure
*/
static int diskAnnGetShadowRowKeys(const DiskAnnIndex *pIndex, u64 nRowid, const VectorIdxKey *pKey, VectorOutRows *pRows, int iRow) {
int rc, i;
sqlite3_stmt *pStmt = NULL;
char *zSql = NULL;
char columnSqlNames[VECTOR_INDEX_SQL_RENDER_LIMIT]; // just column names (e.g. index_key, index_key1, index_key2, ...)
if( vectorIdxKeyNamesRender(pKey->nKeyColumns, "index_key", columnSqlNames, sizeof(columnSqlNames)) != 0 ){
rc = SQLITE_ERROR;
goto out;
}
zSql = sqlite3MPrintf(
pIndex->db,
"SELECT %s FROM \"%w\".%s WHERE rowid = ?",
columnSqlNames, pIndex->zDbSName, pIndex->zShadow
);
if( zSql == NULL ){
rc = SQLITE_NOMEM;
goto out;
}
rc = sqlite3_prepare_v2(pIndex->db, zSql, -1, &pStmt, 0);
if( rc != SQLITE_OK ){
goto out;
}
rc = sqlite3_bind_int64(pStmt, 1, nRowid);
if( rc != SQLITE_OK ){
goto out;
}
rc = sqlite3_step(pStmt);
if( rc != SQLITE_ROW ){
goto out;
}
for(i = 0; i < pRows->nCols; i++){
rc = vectorOutRowsPut(pRows, iRow, i, NULL, sqlite3_column_value(pStmt, i));
if( rc != SQLITE_OK ){
goto out;
}
}
// check that we has only single row matching the criteria (otherwise - this is a bug)
assert( sqlite3_step(pStmt) == SQLITE_DONE );
rc = SQLITE_OK;
out:
if( pStmt != NULL ){
sqlite3_finalize(pStmt);
}
if( zSql != NULL ){
sqlite3DbFree(pIndex->db, zSql);
}
return rc;
}
/*
* Insert new empty row to the shadow table and set new rowid to the pRowid (data will be zeroe-filled blob of size pIndex->nBlockSize)
*/
static int diskAnnInsertShadowRow(const DiskAnnIndex *pIndex, const VectorInRow *pVectorInRow, u64 *pRowid){
int rc, i;
sqlite3_stmt *pStmt = NULL;
char *zSql = NULL;
char columnSqlPlaceholders[VECTOR_INDEX_SQL_RENDER_LIMIT]; // just placeholders (e.g. ?,?,?, ...)
char columnSqlNames[VECTOR_INDEX_SQL_RENDER_LIMIT]; // just column names (e.g. index_key, index_key1, index_key2, ...)
if( vectorInRowPlaceholderRender(pVectorInRow, columnSqlPlaceholders, sizeof(columnSqlPlaceholders)) != 0 ){
rc = SQLITE_ERROR;
goto out;
}
if( vectorIdxKeyNamesRender(pVectorInRow->nKeys, "index_key", columnSqlNames, sizeof(columnSqlNames)) != 0 ){
return SQLITE_ERROR;
}
zSql = sqlite3MPrintf(
pIndex->db,
"INSERT INTO \"%w\".%s(%s, data) VALUES (%s, ?) RETURNING rowid",
pIndex->zDbSName, pIndex->zShadow, columnSqlNames, columnSqlPlaceholders
);
if( zSql == NULL ){
rc = SQLITE_NOMEM_BKPT;
goto out;
}
rc = sqlite3_prepare_v2(pIndex->db, zSql, -1, &pStmt, 0);
if( rc != SQLITE_OK ){
goto out;
}
for(i = 0; i < pVectorInRow->nKeys; i++){
rc = sqlite3_bind_value(pStmt, i + 1, vectorInRowKey(pVectorInRow, i));
if( rc != SQLITE_OK ){
goto out;
}
}
rc = sqlite3_bind_zeroblob(pStmt, pVectorInRow->nKeys + 1, pIndex->nBlockSize);
if( rc != SQLITE_OK ){
goto out;
}
rc = sqlite3_step(pStmt);
if( rc != SQLITE_ROW ){
rc = SQLITE_ERROR;
goto out;
}
assert( sqlite3_column_type(pStmt, 0) == SQLITE_INTEGER );
*pRowid = sqlite3_column_int64(pStmt, 0);
// check that we has only single row matching the criteria (otherwise - this is a bug)
assert( sqlite3_step(pStmt) == SQLITE_DONE );
rc = SQLITE_OK;
out:
if( pStmt != NULL ){
sqlite3_finalize(pStmt);
}
if( zSql != NULL ){
sqlite3DbFree(pIndex->db, zSql);
}
return rc;
}
/*
* Delete row from the shadow table
*/
static int diskAnnDeleteShadowRow(const DiskAnnIndex *pIndex, i64 nRowid){
int rc;
sqlite3_stmt *pStmt = NULL;
char *zSql = sqlite3MPrintf(
pIndex->db,
"DELETE FROM \"%w\".%s WHERE rowid = ?",
pIndex->zDbSName, pIndex->zShadow
);
if( zSql == NULL ){
rc = SQLITE_NOMEM_BKPT;
goto out;
}
rc = sqlite3_prepare_v2(pIndex->db, zSql, -1, &pStmt, 0);
if( rc != SQLITE_OK ){
goto out;
}
rc = sqlite3_bind_int64(pStmt, 1, nRowid);
if( rc != SQLITE_OK ){
goto out;
}
rc = sqlite3_step(pStmt);
if( rc != SQLITE_DONE ){
goto out;
}
rc = SQLITE_OK;
out:
if( pStmt != NULL ){
sqlite3_finalize(pStmt);
}
if( zSql != NULL ){
sqlite3DbFree(pIndex->db, zSql);
}
return rc;
}
/**************************************************************************
** Generic utilities
**************************************************************************/
int initVectorPair(int nodeType, int edgeType, int dims, VectorPair *pPair){
pPair->nodeType = nodeType;
pPair->edgeType = edgeType;
pPair->pNode = NULL;
pPair->pEdge = NULL;
if( pPair->nodeType == pPair->edgeType ){
return 0;
}
pPair->pEdge = vectorAlloc(edgeType, dims);
if( pPair->pEdge == NULL ){
return SQLITE_NOMEM_BKPT;
}
return 0;
}
void loadVectorPair(VectorPair *pPair, const Vector *pVector){
pPair->pNode = (Vector*)pVector;
if( pPair->edgeType != pPair->nodeType ){
vectorConvert(pPair->pNode, pPair->pEdge);
}else{
pPair->pEdge = pPair->pNode;
}
}
void deinitVectorPair(VectorPair *pPair) {
if( pPair->pEdge != NULL && pPair->pNode != pPair->pEdge ){
vectorFree(pPair->pEdge);
}
}
int distanceBufferInsertIdx(const float *aDistances, int nSize, int nMaxSize, float distance){
int i;
#ifdef SQLITE_DEBUG
for(i = 0; i < nSize - 1; i++){
assert(aDistances[i] <= aDistances[i + 1]);
}
#endif
for(i = 0; i < nSize; i++){
if( distance < aDistances[i] ){
return i;
}
}
return nSize < nMaxSize ? nSize : -1;
}
void bufferInsert(u8 *aBuffer, int nSize, int nMaxSize, int iInsert, int nItemSize, const u8 *pItem, u8 *pLast) {
int itemsToMove;
assert( nMaxSize > 0 && nItemSize > 0 );
assert( nSize <= nMaxSize );
assert( 0 <= iInsert && iInsert <= nSize && iInsert < nMaxSize );
if( nSize == nMaxSize ){
if( pLast != NULL ){
memcpy(pLast, aBuffer + (nSize - 1) * nItemSize, nItemSize);
}
nSize--;
}
itemsToMove = nSize - iInsert;
memmove(aBuffer + (iInsert + 1) * nItemSize, aBuffer + iInsert * nItemSize, itemsToMove * nItemSize);
memcpy(aBuffer + iInsert * nItemSize, pItem, nItemSize);
}
void bufferDelete(u8 *aBuffer, int nSize, int iDelete, int nItemSize) {
int itemsToMove;
assert( nItemSize > 0 );
assert( 0 <= iDelete && iDelete < nSize );
itemsToMove = nSize - iDelete - 1;
memmove(aBuffer + iDelete * nItemSize, aBuffer + (iDelete + 1) * nItemSize, itemsToMove * nItemSize);
}
/**************************************************************************
** DiskANN internals
**************************************************************************/
static float diskAnnVectorDistance(const DiskAnnIndex *pIndex, const Vector *pVec1, const Vector *pVec2){
switch( pIndex->nDistanceFunc ){
case VECTOR_METRIC_TYPE_COS:
return vectorDistanceCos(pVec1, pVec2);
case VECTOR_METRIC_TYPE_L2:
return vectorDistanceL2(pVec1, pVec2);
default:
assert(0);
break;
}
return 0.0;
}
static DiskAnnNode *diskAnnNodeAlloc(const DiskAnnIndex *pIndex, u64 nRowid){
DiskAnnNode *pNode = sqlite3_malloc(sizeof(DiskAnnNode));
if( pNode == NULL ){
return NULL;
}
pNode->nRowid = nRowid;
pNode->visited = 0;
pNode->pNext = NULL;
pNode->pBlobSpot = NULL;
return pNode;
}
static void diskAnnNodeFree(DiskAnnNode *pNode){
if( pNode->pBlobSpot != NULL ){
blobSpotFree(pNode->pBlobSpot);
}
sqlite3_free(pNode);
}
static int diskAnnSearchCtxInit(const DiskAnnIndex *pIndex, DiskAnnSearchCtx *pCtx, const Vector* pQuery, int maxCandidates, int topCandidates, int blobMode){
if( initVectorPair(pIndex->nNodeVectorType, pIndex->nEdgeVectorType, pIndex->nVectorDims, &pCtx->query) != 0 ){
return SQLITE_NOMEM_BKPT;
}
loadVectorPair(&pCtx->query, pQuery);
pCtx->aDistances = sqlite3_malloc(maxCandidates * sizeof(double));
pCtx->aCandidates = sqlite3_malloc(maxCandidates * sizeof(DiskAnnNode*));
pCtx->nCandidates = 0;
pCtx->maxCandidates = maxCandidates;
pCtx->aTopDistances = sqlite3_malloc(topCandidates * sizeof(double));