kividb 1.2.1

A fast Redis®-compatible in-memory store written in Rust
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
// src/commands/vset.rs
//
// Vector Set commands: VADD, VREM, VSIM, VCARD, VDIM, VEMB,
//                      VISMEMBER, VINFO, VLINKS, VRANDMEMBER,
//                      VGETATTR, VSETATTR, VRANGE
//
// These are Redis 8's standalone vector data structure.
// Unlike FT.* (which indexes existing hashes), VectorSets store
// vectors directly at a key — like a sorted set but with N-dim vectors.

use crate::commands::ctx::Ctx;
use crate::resp::write::*;
use crate::store;
use crate::store::ValueRef;
use crate::types::{KiviDBValue, VSetEntry, VectorSetInner};
use crate::{read_lock, write_lock};
use parking_lot::RwLock;
use std::sync::Arc;

pub fn handle(ctx: &mut Ctx, name: &str) -> Option<Vec<u8>> {
    match name {
        "VADD" => vadd(ctx),
        "VREM" => vrem(ctx),
        "VSIM" => vsim(ctx),
        "VCARD" => vcard(ctx),
        "VDIM" => vdim(ctx),
        "VEMB" => vemb(ctx),
        "VISMEMBER" => vismember(ctx),
        "VINFO" => vinfo(ctx),
        "VLINKS" => vlinks(ctx),
        "VRANDMEMBER" => vrandmember(ctx),
        "VGETATTR" => vgetattr(ctx),
        "VSETATTR" => vsetattr(ctx),
        "VRANGE" => vrange(ctx),
        _ => None,
    }
}

// ── helpers ───────────────────────────────────────────────────────────────────

/// Get or create a VectorSet at `key` with a given dimension.
/// Returns Err(resp bytes) on type mismatch or dim mismatch, or when
/// `asked` names a `DISTANCE` other than the existing set's.
fn get_or_create_vset(
    ctx: &mut Ctx,
    key: &[u8],
    dim: usize,
    asked: Option<crate::vector::DistanceMetric>,
) -> Result<Arc<RwLock<VectorSetInner>>, Vec<u8>> {
    let metric = asked
        .clone()
        .unwrap_or(crate::vector::DistanceMetric::Cosine);
    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let mut map = write_lock!(shard);

    match map.get(key) {
        Some(ValueRef::VectorSet(vs)) => {
            let inner = vs.read();
            if inner.dim != dim {
                // Redis's words.
                return Err(resp_error(&format!(
                    "ERR Vector dimension mismatch - got {} but set has {}",
                    dim, inner.dim
                )));
            }
            // A `DISTANCE` the set was not made with is refused, as Redis
            // refuses a quantization the set was not made with. One not
            // given takes the set's.
            if asked.as_ref().is_some_and(|m| *m != inner.metric) {
                return Err(resp_error(
                    "ERR asked distance mismatch with existing vector set",
                ));
            }
            Ok(Arc::clone(vs))
        }
        Some(_) => Err(resp_error(
            "WRONGTYPE Operation against a key holding the wrong kind of value",
        )),
        None => {
            let vs = Arc::new(RwLock::new(VectorSetInner::with_metric(dim, metric)));
            map.insert(key, KiviDBValue::VectorSet(Arc::clone(&vs)));
            Ok(vs)
        }
    }
}

/// An integer written as Redis reads one: digits with an optional `-`, no
/// `+`, no leading zero (`010` and `+8` are not numbers to Redis).
fn strict_integer(arg: &[u8]) -> Option<i64> {
    let digits = arg.strip_prefix(b"-").unwrap_or(arg);
    let leading_zero = digits.len() > 1 && digits[0] == b'0';
    if digits.is_empty() || leading_zero || !digits.iter().all(u8::is_ascii_digit) {
        return None;
    }
    std::str::from_utf8(arg).ok()?.parse().ok()
}

/// Parse a VALUES num v1 v2 ... segment into Vec<f32>.
fn parse_values_vector(args: &[&[u8]], start: usize) -> Result<(Vec<f32>, usize), Vec<u8>> {
    // args[start] should be the count
    let count_str = std::str::from_utf8(args[start])
        .map_err(|_| resp_error("ERR VALUES count must be UTF-8"))?;
    let count: usize = count_str
        .parse()
        .map_err(|_| resp_error("ERR VALUES count must be an integer"))?;

    if count > args.len().saturating_sub(start + 1) {
        return Err(resp_error("ERR not enough values for VALUES vector"));
    }

    let mut vec = Vec::with_capacity(count);
    for i in 0..count {
        let s = std::str::from_utf8(args[start + 1 + i])
            .map_err(|_| resp_error("ERR vector value must be UTF-8"))?;
        let f: f32 = s
            .parse()
            .map_err(|_| resp_error("ERR vector value must be a float"))?;
        vec.push(f);
    }
    Ok((vec, start + 1 + count)) // returns next cursor position
}

// ── VADD ──────────────────────────────────────────────────────────────────────
//
// VADD key [REDUCE dim] (FP32 | VALUES num) vector element
//      [CAS] [NOQUANT | Q8 | BIN] [EF n] [SETATTR attrs] [M n]
//
// and KiviDB's own `DISTANCE COSINE | L2 | IP` (before the vector, or among
// the options), which Redis 8.10 does not have: its sets are cosine only.
//
// Redis uses HNSW internally for VectorSets. We store vectors in
// VectorSetInner.entries and do brute-force VSIM (same trade-off as FLAT).
// HNSW for VectorSets is a natural next step.
//
// Returns: 1 if added, 0 if updated.

fn vadd(ctx: &mut Ctx) -> Option<Vec<u8>> {
    let cmd = &ctx.cmd;

    // Minimum: VADD key (FP32|VALUES) ... element
    if cmd.len() < 5 {
        return Some(resp_error(
            "ERR wrong number of arguments for 'vadd' command",
        ));
    }

    let key: Vec<u8> = cmd[1].to_vec();

    // Walk arguments to find vector encoding and element name
    let mut i = 2usize;
    let mut attrs: Option<String> = None;

    // REDUCE projects the vectors to fewer dimensions, at random, with a
    // projection kept with the set for every query after. It was taken and
    // ignored, and the set kept the dimension given (#132): refused.
    if cmd
        .get(i)
        .and_then(|b| std::str::from_utf8(b).ok())
        .map(|s| s.eq_ignore_ascii_case("REDUCE"))
        .unwrap_or(false)
    {
        return Some(resp_error(
            "ERR REDUCE is not supported by KiviDB: vectors are kept at the dimension they are \
             given",
        ));
    }

    // `DISTANCE` is KiviDB's own (Redis's vector sets are cosine only): it
    // may come before the vector or among the options after the element. A
    // value that names no metric is refused; it was taken as COSINE.
    let mut parsed_metric: Option<crate::vector::DistanceMetric> = None;
    let metric_of = |arg: Option<&&[u8]>| {
        arg.and_then(|b| std::str::from_utf8(b).ok())
            .and_then(crate::vector::DistanceMetric::metric_from_str)
            .ok_or_else(|| resp_error("ERR invalid DISTANCE: use COSINE, L2 or IP"))
    };

    if cmd
        .get(i)
        .and_then(|b| std::str::from_utf8(b).ok())
        .map(|s| s.eq_ignore_ascii_case("DISTANCE"))
        .unwrap_or(false)
    {
        match metric_of(cmd.get(i + 1)) {
            Ok(metric) => parsed_metric = Some(metric),
            Err(e) => return Some(e),
        }
        i += 2;
    }

    // What Redis answers for anything wrong in how the vector is given.
    let bad_vector = || Some(resp_error("ERR invalid vector specification"));

    // Next token must be FP32 or VALUES
    let encoding = match cmd.get(i).and_then(|b| std::str::from_utf8(b).ok()) {
        Some(s) => s.to_ascii_uppercase(),
        None => return bad_vector(),
    };
    i += 1;

    let (vec, next_i) = match encoding.as_str() {
        "FP32" => {
            // Next arg is the raw binary blob
            let blob = match cmd.get(i) {
                Some(b) => b,
                None => return bad_vector(),
            };
            // We don't know dim yet — infer from blob length
            if blob.is_empty() || blob.len() % 4 != 0 {
                return bad_vector();
            }
            let v: Vec<f32> = blob
                .as_chunks::<4>()
                .0
                .iter()
                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
                .collect();
            (v, i + 1)
        }
        "VALUES" => match parse_values_vector(cmd, i) {
            Ok((v, n)) if !v.is_empty() => (v, n),
            _ => return bad_vector(),
        },
        _ => return bad_vector(),
    };
    i = next_i;
    if vec.iter().any(|x| x.is_nan()) {
        return bad_vector();
    }

    let dim = vec.len();

    // Next: element name
    // Any bytes, as in Redis: a name that was not UTF-8 was taken for a
    // missing one.
    let element = match cmd.get(i) {
        Some(b) => crate::key_bytes::KeyBytes::from(*b),
        None => {
            return Some(resp_error(
                "ERR wrong number of arguments for 'vadd' command",
            ));
        }
    };
    i += 1;

    // The options after the element, checked as Redis checks them: an
    // option it does not know, or one missing its value, is an error, and
    // so is an `M` or `EF` out of Redis's range. They were skipped.
    let invalid_option = || Some(resp_error("ERR invalid option after element"));
    while i < cmd.len() {
        let tok = String::from_utf8_lossy(cmd[i]).to_ascii_uppercase();
        let value = cmd.get(i + 1);
        match tok.as_str() {
            // Kept at full precision whichever is asked for: `VINFO` says
            // so (`f32`).
            "NOQUANT" | "Q8" | "BIN" | "CAS" => {
                i += 1;
                continue;
            }
            _ if value.is_none() => return invalid_option(),
            "EF" | "M" => {
                let (lo, hi) = if tok == "EF" {
                    (1, 1_000_000)
                } else {
                    (4, 4096)
                };
                if !value
                    .and_then(|v| strict_integer(v))
                    .is_some_and(|n| (lo..=hi).contains(&n))
                {
                    return Some(resp_error(&format!("ERR invalid {tok}")));
                }
            }
            "SETATTR" => {
                attrs = value.map(|a| String::from_utf8_lossy(a).into_owned());
            }
            "DISTANCE" => match metric_of(value) {
                Ok(metric) => parsed_metric = Some(metric),
                Err(e) => return Some(e),
            },
            _ => return invalid_option(),
        }
        i += 2;
    }

    // Get or create the VectorSet
    let vs = match get_or_create_vset(ctx, &key, dim, parsed_metric) {
        Ok(v) => v,
        Err(e) => return Some(e),
    };

    let mut inner = vs.write();
    let is_new = !inner.entries.contains_key(&element);
    inner
        .entries
        .insert(element, VSetEntry { vector: vec, attrs });

    let result = resp_integer(if is_new { 1 } else { 0 });

    Some(result)
}

// ── VREM ──────────────────────────────────────────────────────────────────────
//
// VREM key element [element ...]
// Returns: number of elements actually removed.

fn vrem(ctx: &mut Ctx) -> Option<Vec<u8>> {
    let cmd = &ctx.cmd;
    if cmd.len() < 3 {
        return Some(resp_error(
            "ERR wrong number of arguments for 'vrem' command",
        ));
    }

    let key: &[u8] = cmd[1];

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    let vs = match map.get(key) {
        Some(ValueRef::VectorSet(vs)) => Arc::clone(vs),
        Some(_) => {
            return Some(resp_error(
                "WRONGTYPE Operation against a key holding the wrong kind of value",
            ));
        }
        None => return Some(resp_integer(0)),
    };
    // Drop shard lock before acquiring VectorSet write lock
    drop(map);

    let mut inner = vs.write();
    let mut removed = 0i64;
    // Any bytes: a name that was not UTF-8 was passed over.
    for elem_bytes in &cmd[2..] {
        if inner.entries.remove(*elem_bytes).is_some() {
            removed += 1;
        }
    }

    Some(resp_integer(removed))
}

// ── VCARD ─────────────────────────────────────────────────────────────────────
//
// VCARD key — number of elements in the vector set.

fn vcard(ctx: &mut Ctx) -> Option<Vec<u8>> {
    let cmd = &ctx.cmd;
    if cmd.len() != 2 {
        return Some(resp_error(
            "ERR wrong number of arguments for 'vcard' command",
        ));
    }
    let key: &[u8] = cmd[1];

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        Some(ValueRef::VectorSet(vs)) => Some(resp_integer(vs.read().entries.len() as i64)),
        Some(_) => Some(resp_error(
            "WRONGTYPE Operation against a key holding the wrong kind of value",
        )),
        None => Some(resp_integer(0)),
    }
}

// ── VDIM ──────────────────────────────────────────────────────────────────────
//
// VDIM key — returns the dimension of vectors in the set.

fn vdim(ctx: &mut Ctx) -> Option<Vec<u8>> {
    let cmd = &ctx.cmd;
    if cmd.len() != 2 {
        return Some(resp_error(
            "ERR wrong number of arguments for 'vdim' command",
        ));
    }
    let key: &[u8] = cmd[1];

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        Some(ValueRef::VectorSet(vs)) => Some(resp_integer(vs.read().dim as i64)),
        Some(_) => Some(resp_error(
            "WRONGTYPE Operation against a key holding the wrong kind of value",
        )),
        None => Some(resp_null_bulk()),
    }
}

// ── VEMB ──────────────────────────────────────────────────────────────────────
//
// VEMB key element [RAW]
// Returns the vector as an array of bulk strings (floats) or as a raw FP32 blob.

fn vemb(ctx: &mut Ctx) -> Option<Vec<u8>> {
    let cmd = &ctx.cmd;
    if cmd.len() < 3 {
        return Some(resp_error(
            "ERR wrong number of arguments for 'vemb' command",
        ));
    }
    let key: &[u8] = cmd[1];
    let element: &[u8] = cmd[2];
    // As the vector-sets module: RAW, as often as given, and nothing else.
    if cmd[3..].iter().any(|opt| !opt.eq_ignore_ascii_case(b"RAW")) {
        return Some(resp_error("ERR invalid option"));
    }
    let raw = cmd.len() > 3;

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        Some(ValueRef::VectorSet(vs)) => {
            let inner = vs.read();
            match inner.entries.get(element) {
                None => Some(resp_null_bulk()),
                Some(entry) => {
                    if raw {
                        // Return raw little-endian FP32 bytes
                        let bytes: Vec<u8> =
                            entry.vector.iter().flat_map(|f| f.to_le_bytes()).collect();
                        Some(resp_bulk(&bytes))
                    } else {
                        // Return as array of float strings — easier to read in redis-cli
                        let items: Vec<Vec<u8>> = entry
                            .vector
                            .iter()
                            .map(|f| resp_bulk_str(&f.to_string()))
                            .collect();
                        Some(resp_array(items))
                    }
                }
            }
        }
        Some(_) => Some(resp_error(
            "WRONGTYPE Operation against a key holding the wrong kind of value",
        )),
        None => Some(resp_null_bulk()),
    }
}

// ── VISMEMBER ─────────────────────────────────────────────────────────────────
//
// VISMEMBER key element
// Returns 1 if the element exists, 0 otherwise.

fn vismember(ctx: &mut Ctx) -> Option<Vec<u8>> {
    let cmd = &ctx.cmd;
    if cmd.len() != 3 {
        return Some(resp_error(
            "ERR wrong number of arguments for 'vismember' command",
        ));
    }
    let key: &[u8] = cmd[1];
    let element: &[u8] = cmd[2];

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        Some(ValueRef::VectorSet(vs)) => {
            let found = vs.read().entries.contains_key(element);
            Some(resp_integer(found as i64))
        }
        Some(_) => Some(resp_error(
            "WRONGTYPE Operation against a key holding the wrong kind of value",
        )),
        None => Some(resp_integer(0)),
    }
}

// ── VGETATTR / VSETATTR ───────────────────────────────────────────────────────
//
// VGETATTR key element         → returns the JSON attrs string or nil
// VSETATTR key element "json"  → sets attrs; use empty string "" to remove

fn vgetattr(ctx: &mut Ctx) -> Option<Vec<u8>> {
    let cmd = &ctx.cmd;
    if cmd.len() != 3 {
        return Some(resp_error(
            "ERR wrong number of arguments for 'vgetattr' command",
        ));
    }
    let key: &[u8] = cmd[1];
    let element: &[u8] = cmd[2];

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        Some(ValueRef::VectorSet(vs)) => {
            let inner = vs.read();
            match inner.entries.get(element) {
                None => Some(resp_null_bulk()),
                Some(entry) => match &entry.attrs {
                    None => Some(resp_null_bulk()),
                    Some(s) => Some(resp_bulk_str(s)),
                },
            }
        }
        Some(_) => Some(resp_error(
            "WRONGTYPE Operation against a key holding the wrong kind of value",
        )),
        None => Some(resp_null_bulk()),
    }
}

fn vsetattr(ctx: &mut Ctx) -> Option<Vec<u8>> {
    let cmd = &ctx.cmd;
    if cmd.len() != 4 {
        return Some(resp_error(
            "ERR wrong number of arguments for 'vsetattr' command",
        ));
    }
    let key: Vec<u8> = cmd[1].to_vec();
    let element: Vec<u8> = cmd[2].to_vec();
    let attr_str = match std::str::from_utf8(cmd[3]) {
        Ok(s) => s.to_string(),
        Err(_) => return Some(resp_error("ERR attrs must be valid UTF-8")),
    };

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, &key);
    let map = read_lock!(shard);

    match map.get(key.as_slice()) {
        Some(ValueRef::VectorSet(vs)) => {
            let mut inner = vs.write();
            // 1 when set, 0 when there is no such element or key, as the
            // vector-sets module replies (#561).
            match inner.entries.get_mut(element.as_slice()) {
                None => Some(resp_integer(0)),
                Some(entry) => {
                    entry.attrs = if attr_str.is_empty() {
                        None
                    } else {
                        Some(attr_str)
                    };
                    Some(resp_integer(1))
                }
            }
        }
        Some(_) => Some(resp_error(
            "WRONGTYPE Operation against a key holding the wrong kind of value",
        )),
        None => Some(resp_integer(0)),
    }
}

// ── VINFO ─────────────────────────────────────────────────────────────────────
//
// VINFO key — returns metadata about the vector set as a flat key-value array.
// Mirrors what Redis 8 returns.

fn vinfo(ctx: &mut Ctx) -> Option<Vec<u8>> {
    let cmd = &ctx.cmd;
    if cmd.len() != 2 {
        return Some(resp_error(
            "ERR wrong number of arguments for 'vinfo' command",
        ));
    }
    let key: &[u8] = cmd[1];

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        Some(ValueRef::VectorSet(vs)) => {
            let inner = vs.read();
            let count = inner.entries.len();
            let dim = inner.dim;
            // We always use brute-force (FLAT equivalent)
            let out = vec![
                resp_bulk_str("vector-dim"),
                resp_integer(dim as i64),
                resp_bulk_str("vector-count"),
                resp_integer(count as i64),
                // Redis's name for vectors kept unquantized.
                resp_bulk_str("quant-type"),
                resp_bulk_str("f32"),
                resp_bulk_str("index-type"),
                resp_bulk_str("FLAT"),
                resp_bulk_str("max-level"),
                resp_integer(0),
            ];
            Some(resp_array(out))
        }
        Some(_) => Some(resp_error(
            "WRONGTYPE Operation against a key holding the wrong kind of value",
        )),
        None => Some(resp_null_bulk()),
    }
}

// ── VLINKS ────────────────────────────────────────────────────────────────────
//
/// The score `VSIM` and `VLINKS` give an element, from its distance to the
/// query. Cosine, the only metric Redis's vector sets have, is Redis's
/// `1 - distance / 2`: from 1 (the same direction) through 0.5 (at right
/// angles) to 0 (opposite), as `(1 + cosine) / 2`. It was the cosine
/// itself, from -1 to 1, which put a threshold such as `score > 0.8` in
/// another place than on Redis (#171). The other metrics are KiviDB's own
/// (`METRIC`): the dot product, and `1 / (1 + distance)` for L2.
fn similarity(metric: &crate::vector::DistanceMetric, distance: f32) -> f32 {
    match metric {
        crate::vector::DistanceMetric::Cosine => 1.0 - distance / 2.0,
        crate::vector::DistanceMetric::InnerProduct => 1.0 - distance,
        crate::vector::DistanceMetric::L2 => 1.0 / (1.0 + distance),
    }
}

// VLINKS key element [WITHSCORES]
// Returns the HNSW graph neighbours of an element.
// Since we use brute-force, every other element is a "neighbour".
// We return the top-16 nearest instead — this is honest and useful.

fn vlinks(ctx: &mut Ctx) -> Option<Vec<u8>> {
    let cmd = &ctx.cmd;
    if cmd.len() < 3 {
        return Some(resp_error(
            "ERR wrong number of arguments for 'vlinks' command",
        ));
    }
    let key: &[u8] = cmd[1];
    let element: &[u8] = cmd[2];
    let with_scores = cmd
        .get(3)
        .and_then(|b| std::str::from_utf8(b).ok())
        .map(|s| s.eq_ignore_ascii_case("WITHSCORES"))
        .unwrap_or(false);

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        Some(ValueRef::VectorSet(vs)) => {
            let inner = vs.read();
            let query_vec = match inner.entries.get(element) {
                None => return Some(resp_null_bulk()),
                Some(e) => e.vector.clone(),
            };

            // Brute-force: find 16 nearest neighbours
            let mut scored: Vec<(f32, &[u8])> = inner
                .entries
                .iter()
                .filter(|(name, _)| *name != element)
                .map(|(name, entry)| {
                    (
                        crate::vector::distance(&inner.metric, &query_vec, &entry.vector),
                        name.as_bytes(),
                    )
                })
                .collect();
            scored.sort_unstable_by(|a, b| a.0.total_cmp(&b.0));
            scored.truncate(16);

            // VLINKS returns an array of arrays (one per HNSW layer).
            // We return a single layer 0.
            let layer_items: Vec<Vec<u8>> = scored
                .iter()
                .flat_map(|(score, name)| {
                    let mut items = vec![resp_bulk(name)];
                    if with_scores {
                        let similarity = similarity(&inner.metric, *score);
                        items.push(resp_bulk_str(&format!("{:.6}", similarity)));
                    }
                    items
                })
                .collect();

            Some(resp_array(vec![resp_array(layer_items)]))
        }
        Some(_) => Some(resp_error(
            "WRONGTYPE Operation against a key holding the wrong kind of value",
        )),
        None => Some(resp_null_bulk()),
    }
}

// ── VRANDMEMBER ───────────────────────────────────────────────────────────────
//
// VRANDMEMBER key [count]
// Returns one or more random elements. No repeats when count > 0.

fn vrandmember(ctx: &mut Ctx) -> Option<Vec<u8>> {
    let cmd = &ctx.cmd;
    if cmd.len() != 2 && cmd.len() != 3 {
        return Some(resp_error(
            "ERR wrong number of arguments for 'vrandmember' command",
        ));
    }
    let key: &[u8] = cmd[1];

    let count: Option<i64> = match cmd.get(2) {
        None => None,
        Some(arg) => match std::str::from_utf8(arg).ok().and_then(|s| s.parse().ok()) {
            Some(i64::MIN) => return Some(resp_error("ERR COUNT value is out of range")),
            Some(n) => Some(n),
            None => return Some(resp_error("ERR COUNT value is not an integer")),
        },
    };

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        Some(ValueRef::VectorSet(vs)) => {
            let inner = vs.read();
            let names: Vec<&[u8]> = inner.entries.keys().map(|s| s.as_bytes()).collect();

            if names.is_empty() {
                return if count.is_some() {
                    Some(resp_array(vec![]))
                } else {
                    Some(resp_null_bulk())
                };
            }

            match count {
                None => {
                    // Return a single random element
                    let idx = rand::random::<usize>() % names.len();
                    Some(resp_bulk(names[idx]))
                }
                Some(n) => {
                    let n_abs = n.unsigned_abs() as usize;
                    let mut result: Vec<Vec<u8>> = Vec::new();

                    if n > 0 {
                        // Positive: distinct elements, up to count
                        // Fisher-Yates partial shuffle using indices
                        let mut indices: Vec<usize> = (0..names.len()).collect();
                        let take = n_abs.min(names.len());
                        for i in 0..take {
                            let j = i + rand::random::<usize>() % (names.len() - i);
                            indices.swap(i, j);
                            result.push(resp_bulk(names[indices[i]]));
                        }
                    } else {
                        // Negative: may repeat, return exactly |count| elements
                        for _ in 0..n_abs {
                            let idx = rand::random::<usize>() % names.len();
                            result.push(resp_bulk(names[idx]));
                        }
                    }
                    Some(resp_array(result))
                }
            }
        }
        Some(_) => Some(resp_error(
            "WRONGTYPE Operation against a key holding the wrong kind of value",
        )),
        None => {
            if count.is_some() {
                Some(resp_array(vec![]))
            } else {
                Some(resp_null_bulk())
            }
        }
    }
}

// ── VRANGE ────────────────────────────────────────────────────────────────────
//
// VRANGE key start end [count]
// Returns elements in lexicographical range of element names.
// "start" and "end" follow the same bracket convention as ZRANGEBYLEX:
//   "[foo"  = inclusive from "foo"
//   "(foo"  = exclusive from "foo"
//   "-"     = negative infinity (beginning)
//   "+"     = positive infinity (end)
//
// Why a standalone fn instead of a closure?
// Closures that take &str and return Option<&str> referencing the *same*
// input can't express that relationship — Rust infers two separate lifetimes
// and refuses to unify them. A named fn with `'a` ties input to output
// explicitly, making the borrow checker happy.

fn parse_lex_bound(s: &[u8]) -> (Option<&[u8]>, bool) {
    match s {
        b"-" | b"+" => (None, true),
        [b'[', rest @ ..] => (Some(rest), true),
        [b'(', rest @ ..] => (Some(rest), false),
        s => (Some(s), true), // bare string: treat as inclusive
    }
}

fn vrange(ctx: &mut Ctx) -> Option<Vec<u8>> {
    let cmd = &ctx.cmd;
    if cmd.len() < 4 {
        return Some(resp_error(
            "ERR wrong number of arguments for 'vrange' command",
        ));
    }
    let key: &[u8] = cmd[1];
    // Element names are any bytes, and so are the bounds.
    let start_raw: &[u8] = cmd[2];
    let end_raw: &[u8] = cmd[3];
    let count: Option<usize> = cmd
        .get(4)
        .and_then(|b| std::str::from_utf8(b).ok())
        .and_then(|s| s.parse().ok());

    let (start_str, start_inc) = parse_lex_bound(start_raw);
    let (end_str, end_inc) = parse_lex_bound(end_raw);

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        Some(ValueRef::VectorSet(vs)) => {
            let inner = vs.read();
            let mut names: Vec<&[u8]> = inner.entries.keys().map(|s| s.as_bytes()).collect();
            names.sort_unstable();

            let matches_start = |name: &[u8]| -> bool {
                match start_str {
                    None => true,
                    Some(s) => {
                        if start_inc {
                            name >= s
                        } else {
                            name > s
                        }
                    }
                }
            };
            let matches_end = |name: &[u8]| -> bool {
                match end_str {
                    None => true,
                    Some(s) => {
                        if end_inc {
                            name <= s
                        } else {
                            name < s
                        }
                    }
                }
            };

            let iter = names
                .iter()
                .filter(|&&name| matches_start(name) && matches_end(name));

            let result: Vec<Vec<u8>> = if let Some(n) = count {
                iter.take(n).map(|name| resp_bulk(name)).collect()
            } else {
                iter.map(|name| resp_bulk(name)).collect()
            };

            Some(resp_array(result))
        }
        Some(_) => Some(resp_error(
            "WRONGTYPE Operation against a key holding the wrong kind of value",
        )),
        None => Some(resp_array(vec![])),
    }
}

// ── VSIM ──────────────────────────────────────────────────────────────────────
//
// VSIM key (ELE | FP32 | VALUES num) (vector | element)
//      [WITHSCORES] [WITHATTRIBS] [COUNT num]
//      [EF n] [FILTER expr] [TRUTH] [NOTHREAD]
//
// Finds the most similar vectors.
// ELE: use an existing element's vector as query
// FP32: raw binary blob
// VALUES: space-separated floats

fn vsim(ctx: &mut Ctx) -> Option<Vec<u8>> {
    let cmd = &ctx.cmd;
    if cmd.len() < 4 {
        return Some(resp_error(
            "ERR wrong number of arguments for 'vsim' command",
        ));
    }

    let key: Vec<u8> = cmd[1].to_vec();

    let encoding = match std::str::from_utf8(cmd[2]) {
        Ok(s) => s.to_ascii_uppercase(),
        Err(_) => return Some(resp_error("ERR encoding must be UTF-8")),
    };

    // Parse the query vector
    let (query_vec, mut i) = match encoding.as_str() {
        "ELE" => {
            // The query is identified by an element name stored in the set
            let elem_name: Vec<u8> = cmd[3].to_vec();
            // We'll resolve it after acquiring the lock — placeholder for now
            // We store a sentinel and handle below
            (Err(elem_name), 4usize)
        }
        "FP32" => {
            let blob = match cmd.get(3) {
                Some(b) => b,
                None => return Some(resp_error("ERR missing FP32 blob")),
            };
            if blob.len() % 4 != 0 {
                return Some(resp_error("ERR FP32 blob must be a multiple of 4 bytes"));
            }
            let v: Vec<f32> = blob
                .as_chunks::<4>()
                .0
                .iter()
                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
                .collect();
            (Ok(v), 4usize)
        }
        "VALUES" => match parse_values_vector(cmd, 3) {
            Ok((v, n)) => (Ok(v), n),
            Err(e) => return Some(e),
        },
        _ => return Some(resp_error("ERR expected ELE, FP32, or VALUES")),
    };

    // Parse optional flags
    let mut with_scores = false;
    let mut with_attribs = false;
    let mut count = 10usize;
    let mut filter: Option<super::vset_filter::Filter> = None;

    while i < cmd.len() {
        let tok = match std::str::from_utf8(cmd[i]) {
            Ok(s) => s.to_ascii_uppercase(),
            Err(_) => {
                i += 1;
                continue;
            }
        };
        match tok.as_str() {
            "WITHSCORES" => {
                with_scores = true;
                i += 1;
            }
            "WITHATTRIBS" => {
                with_attribs = true;
                i += 1;
            }
            "COUNT" => {
                if let Some(n) = cmd
                    .get(i + 1)
                    .and_then(|b| std::str::from_utf8(b).ok())
                    .and_then(|s| s.parse().ok())
                {
                    count = n;
                }
                i += 2;
            }
            // The search is exact: how far it looks is not a choice.
            "EF" | "FILTER-EF" => {
                i += 2;
            }
            // Only the elements whose attributes pass are scored (#132).
            "FILTER" => {
                let Some(expr) = cmd.get(i + 1).and_then(|b| std::str::from_utf8(b).ok()) else {
                    return Some(resp_error(super::vset_filter::SYNTAX_ERROR));
                };
                match super::vset_filter::Filter::compile(expr) {
                    Some(compiled) => filter = Some(compiled),
                    None => return Some(resp_error(super::vset_filter::SYNTAX_ERROR)),
                }
                i += 2;
            }
            "TRUTH" | "NOTHREAD" => {
                i += 1;
            }
            _ => {
                i += 1;
            }
        }
    }

    // Now acquire the VectorSet and do the search
    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, &key);
    let map = read_lock!(shard);

    let vs = match map.get(key.as_slice()) {
        Some(ValueRef::VectorSet(vs)) => Arc::clone(vs),
        Some(_) => {
            return Some(resp_error(
                "WRONGTYPE Operation against a key holding the wrong kind of value",
            ));
        }
        None => return Some(resp_array(vec![])),
    };
    drop(map);

    let inner = vs.read();

    // Resolve ELE query — look up from the VectorSet
    let query_vec: Vec<f32> = match query_vec {
        Ok(v) => v,
        Err(elem_name) => match inner.entries.get(elem_name.as_slice()) {
            Some(e) => e.vector.clone(),
            None => return Some(resp_error("ERR element not found in vector set")),
        },
    };

    // Brute-force cosine similarity search
    // Using select_nth_unstable: O(n) average, same trick as FT flat search
    let mut scored: Vec<(f32, &[u8])> = inner
        .entries
        .iter()
        .filter(|(_, entry)| entry.vector.len() == query_vec.len())
        .filter(|(_, entry)| {
            filter
                .as_ref()
                .is_none_or(|filter| filter.matches(entry.attrs.as_deref()))
        })
        .map(|(name, entry)| {
            (
                crate::vector::distance(&inner.metric, &query_vec, &entry.vector),
                name.as_bytes(),
            )
        })
        .collect();

    if scored.len() > count {
        scored.select_nth_unstable_by(count, |a, b| a.0.total_cmp(&b.0));
        scored.truncate(count);
    }
    scored.sort_unstable_by(|a, b| a.0.total_cmp(&b.0));

    // Build response
    // Redis VSIM returns: [element, [score?, attribs?], ...]
    // Flat array with optional interleaved scores/attribs
    let mut out: Vec<Vec<u8>> = Vec::new();
    for (score, name) in &scored {
        out.push(resp_bulk(name));
        if with_scores {
            out.push(resp_bulk_str(&format!(
                "{:.6}",
                similarity(&inner.metric, *score)
            )));
        }
        if with_attribs {
            let attrs = inner
                .entries
                .get(*name)
                .and_then(|e| e.attrs.as_deref())
                .unwrap_or("{}");
            out.push(resp_bulk_str(attrs));
        }
    }

    Some(resp_array(out))
}