linkrs-server 0.1.0

Linkrs network service layer (HTTP/gRPC)
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
use axum::{
    extract::{Extension, Json, Path, State},
    response::Json as JsonResponse,
};
use serde::{Deserialize, Serialize};

use crate::http::{error::HttpError, state::AppState};
use crate::storage::{
    StorageClient, StorageOperationContextOps, StorageSchemaContextOps, StorageSyncContextOps,
};
use linkrs_sync::vector_sync::SearchOptions;
use simvec::{DistanceMetric, VectorFilter};

/// Vector index creation request
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct CreateVectorIndexRequest {
    pub space_id: u64,
    /// Vertex tag name. Vector indexes are vertex-only; edge type names are
    /// rejected.
    pub tag_name: String,
    pub field_name: String,
    pub vector_size: usize,
    #[serde(default = "default_distance")]
    pub distance: DistanceMetric,
    /// HNSW overrides
    pub hnsw_m: Option<usize>,
    pub hnsw_ef_construct: Option<usize>,
    /// Quantization: scalar/binary/product/none (case-insensitive). None = disabled.
    pub quantization: Option<String>,
    /// Scalar only: quantile in (0,1]
    pub quantile: Option<f32>,
    /// Product only: x4/x8/x16/x32/x64 or integer 4/8/16/32/64
    pub compression: Option<String>,
    /// Keep quantized vectors in RAM
    pub always_ram: Option<bool>,
}

fn default_distance() -> DistanceMetric {
    DistanceMetric::Cosine
}

/// Vector index information
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct VectorIndexInfo {
    pub name: String,
    pub space_id: u64,
    pub tag_name: String,
    pub field_name: String,
    pub vector_size: usize,
    pub distance: String,
    pub points_count: u64,
}

/// Vector search request
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct VectorSearchRequest {
    pub space_id: u64,
    pub tag_name: String,
    pub field_name: String,
    pub query_vector: Vec<f32>,
    #[serde(default = "default_limit")]
    pub limit: usize,
    pub threshold: Option<f32>,
    pub filter: Option<VectorFilter>,
    /// Consistency level: "eventual" (default) or "read_your_writes"
    #[serde(default)]
    pub consistency: Option<String>,
    /// Timeout in milliseconds when consistency is read_your_writes
    pub consistency_timeout_ms: Option<u64>,
    /// Minimum LSN to wait for (when RYW)
    pub minimum_lsn: Option<u64>,
}

fn default_limit() -> usize {
    10
}

/// Parse the gRPC `SearchFilter.expression` wire string.
///
/// The wire carries a JSON-encoded `VectorFilter` with the same shape as the
/// HTTP search filter. There is no expression language; arbitrary strings
/// fail with the underlying JSON error.
#[allow(dead_code)]
pub(crate) fn parse_vector_filter_expression(expression: &str) -> Result<VectorFilter, String> {
    serde_json::from_str(expression).map_err(|e| {
        format!("filter.expression must be a JSON VectorFilter with the same shape as the HTTP search filter: {e}")
    })
}

/// Vector search result
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct VectorSearchResponse {
    pub results: Vec<VectorSearchResult>,
    pub count: usize,
}

/// Single vector search result
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct VectorSearchResult {
    pub id: String,
    pub score: f32,
    pub vector: Option<Vec<f32>>,
    pub payload: Option<serde_json::Map<String, serde_json::Value>>,
}

/// List of vector indexes response
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct ListVectorIndexesResponse {
    pub indexes: Vec<String>,
    pub count: usize,
}

/// Vector index details response
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct VectorIndexDetailsResponse {
    pub collection_name: String,
    pub status: String,
    pub vectors_count: u64,
    pub points_count: u64,
    pub indexed_vectors_count: u64,
    pub vector_size: usize,
    pub distance: String,
}

#[utoipa::path(
    post,
    operation_id = "post_v1_vector_indexes",
    path = "/v1/vector/indexes",
    tag = "Vector",
    request_body = CreateVectorIndexRequest,
    responses(
        (status = 200, body = serde_json::Value, description = "Vector index created"),
        (status = 500, description = "Internal error")
    )
)]
/// Create a vector index
pub async fn create_index<
    S: StorageClient
        + StorageSchemaContextOps
        + StorageSyncContextOps
        + StorageOperationContextOps
        + Clone
        + Send
        + Sync
        + 'static,
>(
    State(state): State<AppState<S>>,
    Extension(session_id): Extension<i64>,
    Json(request): Json<CreateVectorIndexRequest>,
) -> Result<JsonResponse<serde_json::Value>, HttpError> {
    super::authz::require_admin_session(&state, session_id)?;
    let graph_service = state.server.get_graph_service();
    let vector_api = graph_service.vector_api();

    if let Some(vector_api) = vector_api {
        // Vector indexes are vertex-only: point IDs, payloads, and rebuild
        // sources are all modeled per vertex. Reject edge type names up
        // front instead of creating an index that can never receive data.
        {
            let storage = state.server.get_storage();
            let storage = storage.read();
            let space_name = storage
                .get_space_by_id(request.space_id)
                .map_err(|error| HttpError::InternalError(error.to_string()))?
                .map(|info| info.space_name)
                .ok_or_else(|| {
                    HttpError::NotFound(format!("space id {} not found", request.space_id))
                })?;
            let is_edge_type = storage
                .get_edge_type(&space_name, &request.tag_name)
                .map_err(|error| HttpError::InternalError(error.to_string()))?
                .is_some();
            if is_edge_type {
                return Err(HttpError::BadRequest(format!(
                    "Vector indexes are vertex-only: '{}' is an edge type, create the index on a vertex tag instead",
                    request.tag_name
                )));
            }
        }
        // Shared DDL semantics: metric/quantization mapping and validation
        // live in linkrs_query::vector_ddl so this endpoint cannot drift from
        // the CREATE VECTOR INDEX statement pipeline.
        let quantization = match request.quantization.as_deref() {
            Some(raw) => match linkrs_query::vector_ddl::quantization_kind_from_str(raw) {
                Some(parsed) => parsed,
                None => {
                    return Err(HttpError::BadRequest(format!(
                        "unknown quantization '{}', expected scalar/binary/product/none",
                        raw
                    )))
                }
            },
            None => None,
        };
        let compression = match request.compression.as_deref() {
            Some(raw) => match linkrs_query::vector_ddl::compression_from_str(raw) {
                Some(parsed) => Some(parsed),
                None => {
                    return Err(HttpError::BadRequest(format!(
                        "unknown compression '{}', expected x4/x8/x16/x32/x64",
                        raw
                    )))
                }
            },
            None => None,
        };
        let config = linkrs_query::vector_ddl::build_collection_config(
            request.vector_size,
            request.distance,
            request.hnsw_m,
            request.hnsw_ef_construct,
            quantization,
            request.quantile,
            compression,
            request.always_ram,
        )
        .map_err(HttpError::BadRequest)?;
        let collection_name = vector_api
            .create_index_with_config(
                request.space_id,
                &request.tag_name,
                &request.field_name,
                config,
            )
            .await
            .map_err(|e| HttpError::InternalError(e.to_string()))?;

        Ok(JsonResponse(serde_json::json!({
            "success": true,
            "message": "Vector index created successfully",
            "collection_name": collection_name
        })))
    } else {
        Err(HttpError::InternalError(
            "Vector API is not available".to_string(),
        ))
    }
}

#[utoipa::path(
    delete,
    path = "/v1/vector/indexes/{space_id}/{tag_name}/{field_name}",
    tag = "Vector",
    params(
        ("space_id" = u64, Path, description = "Space id"),
        ("tag_name" = String, Path, description = "Tag name"),
        ("field_name" = String, Path, description = "Vector field name")
    ),
    responses(
        (status = 200, body = serde_json::Value, description = "Vector index dropped"),
        (status = 500, description = "Internal error")
    )
)]
/// Drop a vector index
pub async fn drop_index<
    S: StorageClient
        + StorageSchemaContextOps
        + StorageSyncContextOps
        + StorageOperationContextOps
        + Clone
        + Send
        + Sync
        + 'static,
>(
    State(state): State<AppState<S>>,
    Extension(session_id): Extension<i64>,
    Path((space_id, tag_name, field_name)): Path<(u64, String, String)>,
) -> Result<JsonResponse<serde_json::Value>, HttpError> {
    super::authz::require_admin_session(&state, session_id)?;
    let graph_service = state.server.get_graph_service();
    let vector_api = graph_service.vector_api();

    if let Some(vector_api) = vector_api {
        vector_api
            .drop_index(space_id, &tag_name, &field_name)
            .await
            .map_err(|e| HttpError::InternalError(e.to_string()))?;

        Ok(JsonResponse(serde_json::json!({
            "success": true,
            "message": "Vector index dropped successfully"
        })))
    } else {
        Err(HttpError::InternalError(
            "Vector API is not available".to_string(),
        ))
    }
}

#[utoipa::path(
    get,
    path = "/v1/vector/indexes/{space_id}/{tag_name}/{field_name}",
    tag = "Vector",
    params(
        ("space_id" = u64, Path, description = "Space id"),
        ("tag_name" = String, Path, description = "Tag name"),
        ("field_name" = String, Path, description = "Vector field name")
    ),
    responses(
        (status = 200, body = VectorIndexDetailsResponse, description = "Vector index details"),
        (status = 404, description = "Not found"),
        (status = 500, description = "Internal error")
    )
)]
/// Get vector index info
pub async fn get_index_info<
    S: StorageClient
        + StorageSchemaContextOps
        + StorageSyncContextOps
        + StorageOperationContextOps
        + Clone
        + Send
        + Sync
        + 'static,
>(
    State(state): State<AppState<S>>,
    Extension(session_id): Extension<i64>,
    Path((space_id, tag_name, field_name)): Path<(u64, String, String)>,
) -> Result<JsonResponse<VectorIndexDetailsResponse>, HttpError> {
    super::authz::require_space_read(&state, session_id, space_id as i64)?;
    let graph_service = state.server.get_graph_service();
    let vector_api = graph_service.vector_api();

    if let Some(vector_api) = vector_api {
        match vector_api.get_index_info(space_id, &tag_name, &field_name) {
            Ok(Some(info)) => Ok(JsonResponse(VectorIndexDetailsResponse {
                collection_name: format!("space_{}_{}_{}", space_id, tag_name, field_name),
                status: "green".to_string(),
                vectors_count: info.vector_count,
                points_count: 0,
                indexed_vectors_count: 0,
                vector_size: info.config.vector_size,
                distance: format!("{:?}", info.config.distance),
            })),
            Ok(None) => Err(HttpError::NotFound("Vector index not found".to_string())),
            Err(e) => Err(HttpError::InternalError(e.to_string())),
        }
    } else {
        Err(HttpError::InternalError(
            "Vector API is not available".to_string(),
        ))
    }
}

#[utoipa::path(
    get,
    operation_id = "get_v1_vector_indexes",
    path = "/v1/vector/indexes",
    tag = "Vector",
    responses(
        (status = 200, body = ListVectorIndexesResponse, description = "Vector index list"),
        (status = 500, description = "Internal error")
    )
)]
/// List all vector indexes
pub async fn list_indexes<
    S: StorageClient
        + StorageSchemaContextOps
        + StorageSyncContextOps
        + StorageOperationContextOps
        + Clone
        + Send
        + Sync
        + 'static,
>(
    State(state): State<AppState<S>>,
    Extension(session_id): Extension<i64>,
) -> Result<JsonResponse<ListVectorIndexesResponse>, HttpError> {
    // The listing spans every space, so it must not expose index names to
    // callers without cross-space visibility; create/drop on this route
    // already require the admin role.
    super::authz::require_admin_session(&state, session_id)?;
    let graph_service = state.server.get_graph_service();
    let vector_api = graph_service.vector_api();

    if let Some(vector_api) = vector_api {
        let indexes = vector_api.list_indexes();
        let count = indexes.len();
        Ok(JsonResponse(ListVectorIndexesResponse { indexes, count }))
    } else {
        Err(HttpError::InternalError(
            "Vector API is not available".to_string(),
        ))
    }
}

#[utoipa::path(
    post,
    operation_id = "post_v1_simvec",
    path = "/v1/vector/search",
    tag = "Vector",
    request_body = VectorSearchRequest,
    responses(
        (status = 200, body = VectorSearchResponse, description = "Vector search results"),
        (status = 500, description = "Internal error")
    )
)]
/// Search vectors
pub async fn search<
    S: StorageClient
        + StorageSchemaContextOps
        + StorageSyncContextOps
        + StorageOperationContextOps
        + Clone
        + Send
        + Sync
        + 'static,
>(
    State(state): State<AppState<S>>,
    Extension(session_id): Extension<i64>,
    Json(request): Json<VectorSearchRequest>,
) -> Result<JsonResponse<VectorSearchResponse>, HttpError> {
    super::authz::require_space_read(&state, session_id, request.space_id as i64)?;
    let graph_service = state.server.get_graph_service();
    let vector_api = graph_service.vector_api();

    if let Some(vector_api) = vector_api {
        let mut options = SearchOptions::new(
            request.space_id,
            &request.tag_name,
            &request.field_name,
            request.query_vector,
            request.limit,
        );

        if let Some(threshold) = request.threshold {
            options = options.with_threshold(threshold);
        }

        if let Some(filter) = request.filter {
            options = options.with_filter(filter);
        }
        if let Some(cons) = request.consistency.as_deref() {
            let is_ryw = cons.eq_ignore_ascii_case("read_your_writes")
                || cons.eq_ignore_ascii_case("ryw")
                || cons.eq_ignore_ascii_case("read-your-writes");
            if is_ryw {
                let timeout = request.consistency_timeout_ms.unwrap_or(2000);
                options.consistency = linkrs_sync::vector_sync::SearchConsistency::ReadYourWrites {
                    timeout_ms: timeout,
                };
                if let Some(lsn) = request.minimum_lsn {
                    options.minimum_lsn = Some(linkrs_core::types::CommitLsn::new(lsn));
                }
            }
        } else if let Some(timeout) = request.consistency_timeout_ms {
            options.consistency = linkrs_sync::vector_sync::SearchConsistency::ReadYourWrites {
                timeout_ms: timeout,
            };
            if let Some(lsn) = request.minimum_lsn {
                options.minimum_lsn = Some(linkrs_core::types::CommitLsn::new(lsn));
            }
        }

        let results = vector_api
            .search_with_options(options)
            .await
            .map_err(|e| HttpError::InternalError(e.to_string()))?;

        let count = results.len();
        let search_results: Vec<VectorSearchResult> = results
            .into_iter()
            .map(|r| VectorSearchResult {
                id: r.id.to_string(),
                score: r.score,
                vector: r.vector.map(|v| v.to_vec()),
                payload: r.payload.map(|p| p.into_iter().collect()),
            })
            .collect();

        Ok(JsonResponse(VectorSearchResponse {
            results: search_results,
            count,
        }))
    } else {
        Err(HttpError::InternalError(
            "Vector API is not available".to_string(),
        ))
    }
}

#[utoipa::path(
    get,
    path = "/v1/vector/{space_id}/{tag_name}/{field_name}/{point_id}",
    tag = "Vector",
    params(
        ("space_id" = u64, Path, description = "Space id"),
        ("tag_name" = String, Path, description = "Tag name"),
        ("field_name" = String, Path, description = "Vector field name"),
        ("point_id" = String, Path, description = "Vector point id")
    ),
    responses(
        (status = 200, body = serde_json::Value, description = "Vector point"),
        (status = 500, description = "Internal error")
    )
)]
/// Get vector point by ID
pub async fn get_vector<
    S: StorageClient
        + StorageSchemaContextOps
        + StorageSyncContextOps
        + StorageOperationContextOps
        + Clone
        + Send
        + Sync
        + 'static,
>(
    State(state): State<AppState<S>>,
    Extension(session_id): Extension<i64>,
    Path((space_id, tag_name, field_name, point_id)): Path<(u64, String, String, String)>,
) -> Result<JsonResponse<serde_json::Value>, HttpError> {
    super::authz::require_space_read(&state, session_id, space_id as i64)?;
    let graph_service = state.server.get_graph_service();
    let vector_api = graph_service.vector_api();

    if let Some(vector_api) = vector_api {
        let point = vector_api
            .get_vector(space_id, &tag_name, &field_name, &point_id)
            .await
            .map_err(|e: linkrs_api::api_core::error::CoreError| {
                HttpError::InternalError(e.to_string())
            })?;

        match point {
            Some(p) => Ok(JsonResponse(serde_json::json!({
                "success": true,
                "point": {
                    "id": p.id,
                    "vector": p.vector,
                    "payload": p.payload.map(|payload| serde_json::to_value(payload).unwrap_or(serde_json::Value::Null))
                }
            }))),
            None => Ok(JsonResponse(serde_json::json!({
                "success": false,
                "message": "Vector point not found"
            }))),
        }
    } else {
        Err(HttpError::InternalError(
            "Vector API is not available".to_string(),
        ))
    }
}

#[utoipa::path(
    get,
    path = "/v1/vector/{space_id}/{tag_name}/{field_name}/count",
    tag = "Vector",
    params(
        ("space_id" = u64, Path, description = "Space id"),
        ("tag_name" = String, Path, description = "Tag name"),
        ("field_name" = String, Path, description = "Vector field name")
    ),
    responses(
        (status = 200, body = serde_json::Value, description = "Vector point count"),
        (status = 500, description = "Internal error")
    )
)]
/// Get vector index count
pub async fn count<
    S: StorageClient
        + StorageSchemaContextOps
        + StorageSyncContextOps
        + StorageOperationContextOps
        + Clone
        + Send
        + Sync
        + 'static,
>(
    State(state): State<AppState<S>>,
    Extension(session_id): Extension<i64>,
    Path((space_id, tag_name, field_name)): Path<(u64, String, String)>,
) -> Result<JsonResponse<serde_json::Value>, HttpError> {
    super::authz::require_space_read(&state, session_id, space_id as i64)?;
    let graph_service = state.server.get_graph_service();
    let vector_api = graph_service.vector_api();

    if let Some(vector_api) = vector_api {
        let count = vector_api
            .count(space_id, &tag_name, &field_name)
            .await
            .map_err(|e: linkrs_api::api_core::error::CoreError| {
                HttpError::InternalError(e.to_string())
            })?;

        Ok(JsonResponse(serde_json::json!({
            "success": true,
            "count": count
        })))
    } else {
        Err(HttpError::InternalError(
            "Vector API is not available".to_string(),
        ))
    }
}

/// Set payload request
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct SetPayloadRequest {
    pub space_id: u64,
    pub tag_name: String,
    pub field_name: String,
    pub point_ids: Vec<String>,
    pub payload: serde_json::Map<String, serde_json::Value>,
}

/// Delete payload request
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct DeletePayloadRequest {
    pub space_id: u64,
    pub tag_name: String,
    pub field_name: String,
    pub point_ids: Vec<String>,
    pub keys: Vec<String>,
}

/// Scroll request
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct ScrollRequest {
    pub space_id: u64,
    pub tag_name: String,
    pub field_name: String,
    #[serde(default = "default_limit")]
    pub limit: usize,
    pub offset: Option<String>,
    pub with_payload: Option<bool>,
    pub with_vector: Option<bool>,
}

/// Scroll response
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct ScrollResponse {
    pub points: Vec<VectorSearchResult>,
    pub next_offset: Option<String>,
}

#[utoipa::path(
    put,
    path = "/v1/vector/payload",
    tag = "Vector",
    request_body = SetPayloadRequest,
    responses(
        (status = 200, body = serde_json::Value, description = "Payload set"),
        (status = 500, description = "Internal error")
    )
)]
/// Set payload for vector points
pub async fn set_payload<
    S: StorageClient
        + StorageSchemaContextOps
        + StorageSyncContextOps
        + StorageOperationContextOps
        + Clone
        + Send
        + Sync
        + 'static,
>(
    State(state): State<AppState<S>>,
    Extension(session_id): Extension<i64>,
    Json(request): Json<SetPayloadRequest>,
) -> Result<JsonResponse<serde_json::Value>, HttpError> {
    super::authz::require_space_write(&state, session_id, request.space_id as i64)?;
    let graph_service = state.server.get_graph_service();
    let vector_api = graph_service.vector_api();

    if let Some(vector_api) = vector_api {
        let payload: simvec::types::Payload = request.payload.into_iter().collect();
        let point_ids: Vec<&str> = request.point_ids.iter().map(|s| s.as_str()).collect();
        vector_api
            .set_payload(
                request.space_id,
                &request.tag_name,
                &request.field_name,
                point_ids,
                payload,
            )
            .await
            .map_err(|e| HttpError::InternalError(e.to_string()))?;

        Ok(JsonResponse(serde_json::json!({
            "success": true,
            "message": "Payload set successfully"
        })))
    } else {
        Err(HttpError::InternalError(
            "Vector API is not available".to_string(),
        ))
    }
}

#[utoipa::path(
    put,
    path = "/v1/vector/payload/fields",
    tag = "Vector",
    request_body = SetPayloadRequest,
    responses(
        (status = 200, body = serde_json::Value, description = "Payload fields merged"),
        (status = 500, description = "Internal error")
    )
)]
/// Merge fields into payload for vector points
pub async fn set_payload_fields<
    S: StorageClient
        + StorageSchemaContextOps
        + StorageSyncContextOps
        + StorageOperationContextOps
        + Clone
        + Send
        + Sync
        + 'static,
>(
    State(state): State<AppState<S>>,
    Extension(session_id): Extension<i64>,
    Json(request): Json<SetPayloadRequest>,
) -> Result<JsonResponse<serde_json::Value>, HttpError> {
    super::authz::require_space_write(&state, session_id, request.space_id as i64)?;
    let graph_service = state.server.get_graph_service();
    let vector_api = graph_service.vector_api();

    if let Some(vector_api) = vector_api {
        let fields: simvec::types::Payload = request.payload.into_iter().collect();
        let point_ids: Vec<&str> = request.point_ids.iter().map(|s| s.as_str()).collect();
        vector_api
            .set_payload_fields(
                request.space_id,
                &request.tag_name,
                &request.field_name,
                point_ids,
                fields,
            )
            .await
            .map_err(|e| HttpError::InternalError(e.to_string()))?;

        Ok(JsonResponse(serde_json::json!({
            "success": true,
            "message": "Payload fields merged successfully"
        })))
    } else {
        Err(HttpError::InternalError(
            "Vector API is not available".to_string(),
        ))
    }
}

#[utoipa::path(
    post,
    path = "/v1/vector/payload/delete",
    tag = "Vector",
    request_body = DeletePayloadRequest,
    responses(
        (status = 200, body = serde_json::Value, description = "Payload keys deleted"),
        (status = 500, description = "Internal error")
    )
)]
/// Delete payload keys from vector points
pub async fn delete_payload<
    S: StorageClient
        + StorageSchemaContextOps
        + StorageSyncContextOps
        + StorageOperationContextOps
        + Clone
        + Send
        + Sync
        + 'static,
>(
    State(state): State<AppState<S>>,
    Extension(session_id): Extension<i64>,
    Json(request): Json<DeletePayloadRequest>,
) -> Result<JsonResponse<serde_json::Value>, HttpError> {
    super::authz::require_space_write(&state, session_id, request.space_id as i64)?;
    let graph_service = state.server.get_graph_service();
    let vector_api = graph_service.vector_api();

    if let Some(vector_api) = vector_api {
        let point_ids: Vec<&str> = request.point_ids.iter().map(|s| s.as_str()).collect();
        let keys: Vec<&str> = request.keys.iter().map(|s| s.as_str()).collect();
        vector_api
            .delete_payload(
                request.space_id,
                &request.tag_name,
                &request.field_name,
                point_ids,
                keys,
            )
            .await
            .map_err(|e| HttpError::InternalError(e.to_string()))?;

        Ok(JsonResponse(serde_json::json!({
            "success": true,
            "message": "Payload keys deleted successfully"
        })))
    } else {
        Err(HttpError::InternalError(
            "Vector API is not available".to_string(),
        ))
    }
}

#[utoipa::path(
    post,
    path = "/v1/vector/scroll",
    tag = "Vector",
    request_body = ScrollRequest,
    responses(
        (status = 200, body = ScrollResponse, description = "Scrolled vector points"),
        (status = 500, description = "Internal error")
    )
)]
/// Paginated scroll over vector points
pub async fn scroll<
    S: StorageClient
        + StorageSchemaContextOps
        + StorageSyncContextOps
        + StorageOperationContextOps
        + Clone
        + Send
        + Sync
        + 'static,
>(
    State(state): State<AppState<S>>,
    Extension(session_id): Extension<i64>,
    Json(request): Json<ScrollRequest>,
) -> Result<JsonResponse<ScrollResponse>, HttpError> {
    super::authz::require_space_read(&state, session_id, request.space_id as i64)?;
    let graph_service = state.server.get_graph_service();
    let vector_api = graph_service.vector_api();

    if let Some(vector_api) = vector_api {
        let (points, next_offset) = vector_api
            .scroll(linkrs_api::api_core::vector_api::ScrollQuery {
                space_id: request.space_id,
                tag_name: &request.tag_name,
                field_name: &request.field_name,
                limit: request.limit,
                offset: request.offset.as_deref(),
                with_payload: request.with_payload,
                with_vector: request.with_vector,
            })
            .await
            .map_err(|e| HttpError::InternalError(e.to_string()))?;

        let results: Vec<VectorSearchResult> = points
            .into_iter()
            .map(|p| VectorSearchResult {
                id: p.id.to_string(),
                score: 0.0,
                vector: if request.with_vector.unwrap_or(false) {
                    Some(p.vector)
                } else {
                    None
                },
                payload: p.payload.map(|pay| pay.into_iter().collect()),
            })
            .collect();

        Ok(JsonResponse(ScrollResponse {
            points: results,
            next_offset,
        }))
    } else {
        Err(HttpError::InternalError(
            "Vector API is not available".to_string(),
        ))
    }
}