selene-db-gql 1.3.0

ISO/IEC 39075:2024 GQL parser, planner, optimizer, and executor for selene-db.
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
//! `selene.text_search_nodes` and candidate text-scoring native built-ins.
//!
//! Read-only graph-tier procedure exposing BM25 full-text search over
//! string-valued node properties. A registered maintained text index is used
//! when present; otherwise global search falls back to the exact scan oracle.
//! Candidate-scoped scoring requires a registered text index so a read call does
//! not unexpectedly build a full transient postings index. These are
//! intentionally `CALL selene.*` surfaces rather than grammar syntax: full-text
//! search is an implementation-defined engine capability layered on ISO GQL
//! values.

use selene_core::{DbString, Value};
use selene_graph::{GraphError, RowIndex, SeleneGraph, TextSearchError};

use super::meta::{StaticOutputColumn, StaticParameter};
use super::vector_candidate_state_common::{
    CandidateStateOperation, candidate_state_error, operation_arg,
};
use super::vector_common::{
    BatchMismatch, candidate_set_arg, candidate_sets_arg, cardinality_arg, expansion_direction_arg,
    invalid_arg, node_list_arg, node_list_sets_arg, query_index_too_large, string_arg,
    vector_search_error,
};
use crate::procedure_registry::ProcedureError;
use crate::{GqlType, GraphContext, ProcedureOutputColumn, ProcedureParameter, ProcedureResult};

const PROC_NAME: &str = "selene.text_search_nodes";
const SCORE_PROC_NAME: &str = "selene.text_score_nodes";
const SCORE_BATCH_PROC_NAME: &str = "selene.text_score_nodes_batch";
const SCORE_STATE_PROC_NAME: &str = "selene.text_score_candidate_state";
const SCORE_STATE_NODES_PROC_NAME: &str = "selene.text_score_candidate_state_nodes";
const SCORE_STATE_EXPANDED_BATCH_PROC_NAME: &str =
    "selene.text_score_candidate_state_expanded_batch";

static TEXT_SEARCH_PARAMS: [StaticParameter; 4] = [
    StaticParameter::new("label", GqlType::String, false).with_description("Node label."),
    StaticParameter::new("property", GqlType::String, false).with_description("Property name."),
    StaticParameter::new("query", GqlType::String, false)
        .with_description("Full-text query string."),
    StaticParameter::new("k", GqlType::Integer, false).with_description("Maximum result count."),
];

static TEXT_SEARCH_OUTPUTS: [StaticOutputColumn; 2] = [
    StaticOutputColumn::new("node_id", GqlType::NodeRef).with_description("Matched node id."),
    StaticOutputColumn::new("score", GqlType::Float64)
        .with_description("Higher-is-better BM25 score."),
];
static TEXT_SCORE_BATCH_OUTPUTS: [StaticOutputColumn; 3] = [
    StaticOutputColumn::new("query_index", GqlType::Uint64)
        .with_description("Zero-based query position."),
    StaticOutputColumn::new("node_id", GqlType::NodeRef).with_description("Matched node id."),
    StaticOutputColumn::new("score", GqlType::Float64)
        .with_description("Higher-is-better BM25 score."),
];

pub(super) fn signature() -> Vec<ProcedureParameter> {
    let mut params: Vec<_> = TEXT_SEARCH_PARAMS
        .iter()
        .cloned()
        .map(StaticParameter::into_parameter)
        .collect();
    params.push(
        StaticParameter::new("filter_property", GqlType::String, true)
            .with_description("Indexed scalar property used to admit matching nodes.")
            .with_default_doc("NULL (no property filter)")
            .with_default(crate::ProcedureDefaultValue::Null)
            .into_parameter(),
    );
    params.push(
        StaticParameter::new(
            "filter_values",
            GqlType::List(Box::new(GqlType::AnyProperty)),
            true,
        )
        .with_description("Indexed scalar values admitted by filter_property.")
        .with_default_doc("NULL (no property filter)")
        .with_default(crate::ProcedureDefaultValue::Null)
        .into_parameter(),
    );
    params
}

pub(super) fn score_signature() -> Vec<ProcedureParameter> {
    [
        StaticParameter::new("label", GqlType::String, false).with_description("Node label."),
        StaticParameter::new("property", GqlType::String, false).with_description("Property name."),
        StaticParameter::new("query", GqlType::String, false)
            .with_description("Full-text query string."),
        StaticParameter::new("nodes", GqlType::List(Box::new(GqlType::NodeRef)), false)
            .with_description("Candidate nodes to score."),
        StaticParameter::new("k", GqlType::Integer, false)
            .with_description("Maximum result count."),
    ]
    .into_iter()
    .map(StaticParameter::into_parameter)
    .collect()
}

pub(super) fn score_batch_signature() -> Vec<ProcedureParameter> {
    [
        StaticParameter::new("label", GqlType::String, false).with_description("Node label."),
        StaticParameter::new("property", GqlType::String, false).with_description("Property name."),
        StaticParameter::new("queries", GqlType::List(Box::new(GqlType::String)), false)
            .with_description("Full-text query strings."),
        StaticParameter::new(
            "nodes",
            GqlType::List(Box::new(GqlType::List(Box::new(GqlType::NodeRef)))),
            false,
        )
        .with_description("Per-query candidate nodes to score."),
        StaticParameter::new("k", GqlType::Integer, false)
            .with_description("Maximum result count per query."),
    ]
    .into_iter()
    .map(StaticParameter::into_parameter)
    .collect()
}

pub(super) fn score_state_signature() -> Vec<ProcedureParameter> {
    [
        StaticParameter::new("label", GqlType::String, false).with_description("Node label."),
        StaticParameter::new("property", GqlType::String, false).with_description("Property name."),
        StaticParameter::new("query", GqlType::String, false)
            .with_description("Full-text query string."),
        StaticParameter::new("state_name", GqlType::String, false)
            .with_description("Maintained candidate-state name."),
        StaticParameter::new("k", GqlType::Integer, false)
            .with_description("Maximum result count."),
    ]
    .into_iter()
    .map(StaticParameter::into_parameter)
    .collect()
}

pub(super) fn score_state_nodes_signature() -> Vec<ProcedureParameter> {
    [
        StaticParameter::new("label", GqlType::String, false).with_description("Node label."),
        StaticParameter::new("property", GqlType::String, false).with_description("Property name."),
        StaticParameter::new("query", GqlType::String, false)
            .with_description("Full-text query string."),
        StaticParameter::new("state_name", GqlType::String, false)
            .with_description("Maintained candidate-state name."),
        StaticParameter::new("nodes", GqlType::List(Box::new(GqlType::NodeRef)), false)
            .with_description("Explicit candidate nodes to compose with the maintained state."),
        StaticParameter::new("k", GqlType::Integer, false)
            .with_description("Maximum result count."),
        StaticParameter::new("operation", GqlType::String, false)
            .with_description("Candidate-set algebra operation.")
            .with_default_doc("intersection")
            .with_default(crate::ProcedureDefaultValue::String("intersection")),
    ]
    .into_iter()
    .map(StaticParameter::into_parameter)
    .collect()
}

pub(super) fn score_state_expanded_batch_signature() -> Vec<ProcedureParameter> {
    [
        StaticParameter::new("label", GqlType::String, false).with_description("Node label."),
        StaticParameter::new("property", GqlType::String, false).with_description("Property name."),
        StaticParameter::new("queries", GqlType::List(Box::new(GqlType::String)), false)
            .with_description("Full-text query strings."),
        StaticParameter::new("state_name", GqlType::String, false)
            .with_description("Maintained candidate-state name."),
        StaticParameter::new(
            "roots",
            GqlType::List(Box::new(GqlType::List(Box::new(GqlType::NodeRef)))),
            false,
        )
        .with_description("Per-query root candidate nodes to preserve and graph-expand."),
        StaticParameter::new("edge_label", GqlType::String, false)
            .with_description("Edge label used to expand root candidates."),
        StaticParameter::new("k", GqlType::Integer, false)
            .with_description("Maximum result count per query."),
        StaticParameter::new("operation", GqlType::String, false)
            .with_description("Candidate-set algebra operation.")
            .with_default_doc("intersection")
            .with_default(crate::ProcedureDefaultValue::String("intersection")),
        StaticParameter::new("direction", GqlType::String, false)
            .with_description("Expansion direction: outgoing, incoming, or both.")
            .with_default_doc("outgoing")
            .with_default(crate::ProcedureDefaultValue::String("outgoing")),
    ]
    .into_iter()
    .map(StaticParameter::into_parameter)
    .collect()
}

pub(super) fn output_columns() -> Vec<ProcedureOutputColumn> {
    TEXT_SEARCH_OUTPUTS
        .iter()
        .cloned()
        .map(StaticOutputColumn::into_output_column)
        .collect()
}

pub(super) fn score_batch_output_columns() -> Vec<ProcedureOutputColumn> {
    TEXT_SCORE_BATCH_OUTPUTS
        .iter()
        .cloned()
        .map(StaticOutputColumn::into_output_column)
        .collect()
}

pub(super) fn execute(
    ctx: &GraphContext<'_>,
    args: &[Value],
) -> Result<ProcedureResult, ProcedureError> {
    if args.len() != 4 && args.len() != 6 {
        return Err(invalid_arg(format!("{PROC_NAME} expects 4 or 6 arguments")));
    }

    let label = string_arg(PROC_NAME, &args[0], "label")?;
    let property = string_arg(PROC_NAME, &args[1], "property")?;
    let query = query_arg(PROC_NAME, &args[2])?;
    let k = cardinality_arg(PROC_NAME, &args[3], "k")?;

    let snapshot = ctx.snapshot();
    let filter_rows = if args.len() == 6 {
        optional_filter_rows(PROC_NAME, snapshot, &label, &args[4], &args[5])?
    } else {
        None
    };
    let hits = match snapshot.text_index_for(&label, &property) {
        Some(index) => {
            if let Some(rows) = &filter_rows {
                let nodes = node_ids_for_rows(PROC_NAME, snapshot, rows)?;
                index
                    .search_candidates_checked(query, &nodes, k, ctx.cancellation_checker())
                    .map_err(text_search_error)?
            } else {
                index
                    .search_checked(query, k, ctx.cancellation_checker())
                    .map_err(text_search_error)?
            }
        }
        None => {
            if let Some(rows) = &filter_rows {
                snapshot
                    .exact_text_search_nodes_in_rows_checked(
                        &label,
                        &property,
                        query,
                        k,
                        rows,
                        ctx.cancellation_checker(),
                    )
                    .map_err(text_search_error)?
            } else {
                snapshot
                    .exact_text_search_nodes_checked(
                        &label,
                        &property,
                        query,
                        k,
                        ctx.cancellation_checker(),
                    )
                    .map_err(text_search_error)?
            }
        }
    };
    Ok(ProcedureResult {
        rows: hits
            .into_iter()
            .map(|hit| vec![Value::NodeRef(hit.node_id), Value::Float(hit.score)])
            .collect(),
    })
}

pub(super) fn execute_score(
    ctx: &GraphContext<'_>,
    args: &[Value],
) -> Result<ProcedureResult, ProcedureError> {
    if args.len() != 5 {
        return Err(invalid_arg(format!(
            "{SCORE_PROC_NAME} expects 5 arguments"
        )));
    }

    let label = string_arg(SCORE_PROC_NAME, &args[0], "label")?;
    let property = string_arg(SCORE_PROC_NAME, &args[1], "property")?;
    let query = query_arg(SCORE_PROC_NAME, &args[2])?;
    let nodes = node_list_arg(SCORE_PROC_NAME, &args[3], "nodes")?;
    let k = cardinality_arg(SCORE_PROC_NAME, &args[4], "k")?;

    let snapshot = ctx.snapshot();
    let Some(index) = snapshot.text_index_for(&label, &property) else {
        return Err(invalid_arg(format!(
            "{SCORE_PROC_NAME} requires a text index for {}.{}; call selene.create_text_index first",
            label.as_str(),
            property.as_str()
        )));
    };
    let hits = index
        .search_candidates_checked(query, &nodes, k, ctx.cancellation_checker())
        .map_err(text_search_error)?;

    Ok(ProcedureResult {
        rows: hits
            .into_iter()
            .map(|hit| vec![Value::NodeRef(hit.node_id), Value::Float(hit.score)])
            .collect(),
    })
}

pub(super) fn execute_score_batch(
    ctx: &GraphContext<'_>,
    args: &[Value],
) -> Result<ProcedureResult, ProcedureError> {
    if args.len() != 5 {
        return Err(invalid_arg(format!(
            "{SCORE_BATCH_PROC_NAME} expects 5 arguments"
        )));
    }

    let label = string_arg(SCORE_BATCH_PROC_NAME, &args[0], "label")?;
    let property = string_arg(SCORE_BATCH_PROC_NAME, &args[1], "property")?;
    let queries = query_list_arg(SCORE_BATCH_PROC_NAME, &args[2])?;
    let node_sets = node_list_sets_arg(SCORE_BATCH_PROC_NAME, &args[3], "nodes")?;
    if queries.len() != node_sets.len() {
        return Err(invalid_arg(format!(
            "{SCORE_BATCH_PROC_NAME} queries and nodes must have the same length"
        )));
    }
    let k = cardinality_arg(SCORE_BATCH_PROC_NAME, &args[4], "k")?;

    let snapshot = ctx.snapshot();
    let Some(index) = snapshot.text_index_for(&label, &property) else {
        return Err(invalid_arg(format!(
            "{SCORE_BATCH_PROC_NAME} requires a text index for {}.{}; call selene.create_text_index first",
            label.as_str(),
            property.as_str()
        )));
    };

    let mut rows = Vec::new();
    for (query_index, (query, nodes)) in queries.iter().zip(node_sets.iter()).enumerate() {
        let query_index = u64::try_from(query_index)
            .map_err(|err| query_index_too_large(SCORE_BATCH_PROC_NAME, err))?;
        let hits = index
            .search_candidates_checked(query.as_str(), nodes, k, ctx.cancellation_checker())
            .map_err(text_search_error)?;
        rows.reserve(hits.len());
        for hit in hits {
            rows.push(vec![
                Value::Uint(query_index),
                Value::NodeRef(hit.node_id),
                Value::Float(hit.score),
            ]);
        }
    }
    Ok(ProcedureResult { rows })
}

pub(super) fn execute_score_state(
    ctx: &GraphContext<'_>,
    args: &[Value],
) -> Result<ProcedureResult, ProcedureError> {
    if args.len() != 5 {
        return Err(invalid_arg(format!(
            "{SCORE_STATE_PROC_NAME} expects 5 arguments"
        )));
    }

    let label = string_arg(SCORE_STATE_PROC_NAME, &args[0], "label")?;
    let property = string_arg(SCORE_STATE_PROC_NAME, &args[1], "property")?;
    let query = query_arg(SCORE_STATE_PROC_NAME, &args[2])?;
    let state_name = string_arg(SCORE_STATE_PROC_NAME, &args[3], "state_name")?;
    let k = cardinality_arg(SCORE_STATE_PROC_NAME, &args[4], "k")?;

    let candidates = ctx
        .vector_candidate_set(&state_name)
        .map_err(|error| candidate_state_error(SCORE_STATE_PROC_NAME, error))?
        .ok_or_else(|| {
            invalid_arg(format!(
                "{SCORE_STATE_PROC_NAME} unknown maintained candidate-state set '{}'",
                state_name.as_str()
            ))
        })?;
    let hits = text_index_for_score(ctx, SCORE_STATE_PROC_NAME, &label, &property)?
        .search_candidates_checked(query, candidates.as_nodes(), k, ctx.cancellation_checker())
        .map_err(text_search_error)?;

    Ok(ProcedureResult {
        rows: hits
            .into_iter()
            .map(|hit| vec![Value::NodeRef(hit.node_id), Value::Float(hit.score)])
            .collect(),
    })
}

pub(super) fn execute_score_state_nodes(
    ctx: &GraphContext<'_>,
    args: &[Value],
) -> Result<ProcedureResult, ProcedureError> {
    if !(6..=7).contains(&args.len()) {
        return Err(invalid_arg(format!(
            "{SCORE_STATE_NODES_PROC_NAME} expects 6 or 7 arguments"
        )));
    }

    let label = string_arg(SCORE_STATE_NODES_PROC_NAME, &args[0], "label")?;
    let property = string_arg(SCORE_STATE_NODES_PROC_NAME, &args[1], "property")?;
    let query = query_arg(SCORE_STATE_NODES_PROC_NAME, &args[2])?;
    let state_name = string_arg(SCORE_STATE_NODES_PROC_NAME, &args[3], "state_name")?;
    let nodes = candidate_set_arg(SCORE_STATE_NODES_PROC_NAME, &args[4], "nodes")?;
    let k = cardinality_arg(SCORE_STATE_NODES_PROC_NAME, &args[5], "k")?;
    let operation = args
        .get(6)
        .map(|arg| operation_arg(SCORE_STATE_NODES_PROC_NAME, arg))
        .transpose()?
        .unwrap_or(CandidateStateOperation::Intersection);

    let state = ctx
        .vector_candidate_set(&state_name)
        .map_err(|error| candidate_state_error(SCORE_STATE_NODES_PROC_NAME, error))?
        .ok_or_else(|| {
            invalid_arg(format!(
                "{SCORE_STATE_NODES_PROC_NAME} unknown maintained candidate-state set '{}'",
                state_name.as_str()
            ))
        })?;
    let candidates = operation.compose(&state, &nodes);
    let hits = text_index_for_score(ctx, SCORE_STATE_NODES_PROC_NAME, &label, &property)?
        .search_candidates_checked(query, candidates.as_nodes(), k, ctx.cancellation_checker())
        .map_err(text_search_error)?;

    Ok(ProcedureResult {
        rows: hits
            .into_iter()
            .map(|hit| vec![Value::NodeRef(hit.node_id), Value::Float(hit.score)])
            .collect(),
    })
}

pub(super) fn execute_score_state_expanded_batch(
    ctx: &GraphContext<'_>,
    args: &[Value],
) -> Result<ProcedureResult, ProcedureError> {
    if !(7..=9).contains(&args.len()) {
        return Err(invalid_arg(format!(
            "{SCORE_STATE_EXPANDED_BATCH_PROC_NAME} expects 7 to 9 arguments"
        )));
    }

    let label = string_arg(SCORE_STATE_EXPANDED_BATCH_PROC_NAME, &args[0], "label")?;
    let property = string_arg(SCORE_STATE_EXPANDED_BATCH_PROC_NAME, &args[1], "property")?;
    let queries = query_list_arg(SCORE_STATE_EXPANDED_BATCH_PROC_NAME, &args[2])?;
    let state_name = string_arg(SCORE_STATE_EXPANDED_BATCH_PROC_NAME, &args[3], "state_name")?;
    let root_sets = candidate_sets_arg(SCORE_STATE_EXPANDED_BATCH_PROC_NAME, &args[4], "roots")?;
    if queries.len() != root_sets.len() {
        return Err(invalid_arg(format!(
            "{SCORE_STATE_EXPANDED_BATCH_PROC_NAME} queries and roots must have the same length"
        )));
    }
    let edge_label = string_arg(SCORE_STATE_EXPANDED_BATCH_PROC_NAME, &args[5], "edge_label")?;
    let k = cardinality_arg(SCORE_STATE_EXPANDED_BATCH_PROC_NAME, &args[6], "k")?;
    let operation = args
        .get(7)
        .map(|arg| operation_arg(SCORE_STATE_EXPANDED_BATCH_PROC_NAME, arg))
        .transpose()?
        .unwrap_or(CandidateStateOperation::Intersection);
    let direction = args
        .get(8)
        .map(|arg| expansion_direction_arg(SCORE_STATE_EXPANDED_BATCH_PROC_NAME, arg))
        .transpose()?
        .unwrap_or(selene_graph::VectorNeighborDirection::Outgoing);

    let state = ctx
        .vector_candidate_set(&state_name)
        .map_err(|error| candidate_state_error(SCORE_STATE_EXPANDED_BATCH_PROC_NAME, error))?
        .ok_or_else(|| {
            invalid_arg(format!(
                "{SCORE_STATE_EXPANDED_BATCH_PROC_NAME} unknown maintained candidate-state set '{}'",
                state_name.as_str()
            ))
        })?;

    let snapshot = ctx.snapshot();
    let Some(index) = snapshot.text_index_for(&label, &property) else {
        return Err(invalid_arg(format!(
            "{SCORE_STATE_EXPANDED_BATCH_PROC_NAME} requires a text index for {}.{}; call selene.create_text_index first",
            label.as_str(),
            property.as_str()
        )));
    };

    let expanded_sets = snapshot
        .expand_vector_candidate_sets_batch_checked(
            &root_sets,
            &edge_label,
            direction,
            k,
            ctx.cancellation_checker(),
        )
        .map_err(|error| {
            vector_search_error(
                error,
                "batched maintained candidate-state expanded BM25 scoring",
                BatchMismatch::Internal(
                    "batched maintained candidate-state text expansion received batched-only error",
                ),
                "batched maintained candidate-state expanded BM25 scoring",
            )
        })?;

    let mut rows = Vec::new();
    for (query_index, (query, expanded)) in queries.iter().zip(expanded_sets.iter()).enumerate() {
        let query_index = u64::try_from(query_index)
            .map_err(|err| query_index_too_large(SCORE_STATE_EXPANDED_BATCH_PROC_NAME, err))?;
        let candidates = operation.compose(&state, expanded);
        let hits = index
            .search_candidates_checked(
                query.as_str(),
                candidates.as_nodes(),
                k,
                ctx.cancellation_checker(),
            )
            .map_err(text_search_error)?;
        rows.reserve(hits.len());
        for hit in hits {
            rows.push(vec![
                Value::Uint(query_index),
                Value::NodeRef(hit.node_id),
                Value::Float(hit.score),
            ]);
        }
    }
    Ok(ProcedureResult { rows })
}

fn text_index_for_score(
    ctx: &GraphContext<'_>,
    proc_name: &'static str,
    label: &DbString,
    property: &DbString,
) -> Result<std::sync::Arc<selene_graph::TextIndex>, ProcedureError> {
    ctx.snapshot()
        .text_index_for(label, property)
        .ok_or_else(|| {
            invalid_arg(format!(
                "{proc_name} requires a text index for {}.{}; call selene.create_text_index first",
                label.as_str(),
                property.as_str()
            ))
        })
}

fn query_arg<'a>(proc_name: &'static str, value: &'a Value) -> Result<&'a str, ProcedureError> {
    let Value::String(value) = value else {
        return Err(invalid_arg(format!("{proc_name} query must be a STRING")));
    };
    Ok(value.as_str())
}

fn optional_filter_rows(
    proc_name: &'static str,
    snapshot: &SeleneGraph,
    label: &DbString,
    property: &Value,
    values: &Value,
) -> Result<Option<roaring::RoaringBitmap>, ProcedureError> {
    match (property, values) {
        (Value::Null, Value::Null) => Ok(None),
        (Value::Null, _) | (_, Value::Null) => Err(invalid_arg(format!(
            "{proc_name} filter_property and filter_values must both be NULL or both be supplied"
        ))),
        (_, Value::List(values)) => {
            let property = string_arg(proc_name, property, "filter_property")?;
            snapshot
                .nodes_with_property_any(label, &property, values)
                .map(Some)
                .ok_or_else(|| {
                    invalid_arg(format!(
                        "{proc_name} filter_property must name an indexed scalar node property and filter_values must match that index kind"
                    ))
                })
        }
        (_, _) => Err(invalid_arg(format!(
            "{proc_name} filter_values must be a LIST<VALUE> or NULL"
        ))),
    }
}

fn node_ids_for_rows(
    proc_name: &'static str,
    snapshot: &SeleneGraph,
    rows: &roaring::RoaringBitmap,
) -> Result<Vec<selene_core::NodeId>, ProcedureError> {
    let mut nodes = Vec::with_capacity(usize::try_from(rows.len()).unwrap_or(usize::MAX));
    for raw_row in rows.iter() {
        let row = RowIndex::new(raw_row);
        let node_id = snapshot
            .node_id_for_row(row)
            .ok_or_else(|| ProcedureError::Internal {
                detail: format!("{proc_name} indexed filter row {raw_row} has no node id"),
            })?;
        nodes.push(node_id);
    }
    Ok(nodes)
}

fn query_list_arg(proc_name: &'static str, value: &Value) -> Result<Vec<DbString>, ProcedureError> {
    let Value::List(values) = value else {
        return Err(invalid_arg(format!(
            "{proc_name} queries must be a LIST<STRING>"
        )));
    };
    let mut queries = Vec::with_capacity(values.len());
    for (index, value) in values.iter().enumerate() {
        let Value::String(query) = value else {
            return Err(invalid_arg(format!(
                "{proc_name} queries[{index}] must be a STRING"
            )));
        };
        queries.push(query.clone());
    }
    Ok(queries)
}

fn text_search_error(error: TextSearchError) -> ProcedureError {
    match error {
        TextSearchError::Cancelled => ProcedureError::Cancelled,
        TextSearchError::Timeout { elapsed } => ProcedureError::Timeout { elapsed },
        TextSearchError::NodeScanBudgetExceeded { limit, scanned } => {
            ProcedureError::NodeScanBudgetExceeded { limit, scanned }
        }
        TextSearchError::Graph(GraphError::Inconsistent { reason }) => ProcedureError::Internal {
            detail: format!("graph inconsistency during text search: {reason}"),
        },
        TextSearchError::Graph(other) => ProcedureError::Internal {
            detail: format!("unexpected graph error during text search: {other}"),
        },
    }
}