create-feltdb 0.11.4 → 0.11.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,599 @@
1
+ //! Semantic query composition over a bounded candidate page.
2
+ //!
3
+ //! This module implements `docs/reference/semantic-query.md`: a semantic
4
+ //! decision participates in a FeltDB query only as a bounded transformation of
5
+ //! an already-authorized deterministic candidate page. The deterministic query
6
+ //! decides which records exist in the page and in what order; this module may
7
+ //! annotate, filter, or rank those records with the existing semantic decision
8
+ //! primitive and may never enlarge the page, refill it, touch an index, or
9
+ //! reach a record outside it.
10
+ //!
11
+ //! It is deliberately not a query engine. Every judgment is produced by
12
+ //! `semantic_decision::decide_record` or reused through
13
+ //! `semantic_decision::reuse_record_judgment`, so authorization, judgment
14
+ //! identity, durable supersession, evidence, and provenance are exactly what
15
+ //! the record-scoped primitive already provides.
16
+
17
+ use crate::semantic_decision::{
18
+ decide_record, reuse_record_judgment, validate_decision_definition,
19
+ DecisionAuthorizationConfig, DecisionAuthorizationGate, DecisionDefinition, DecisionError,
20
+ DecisionKind, DecisionOptions, DecisionPrincipal, DecisionProvenance, DecisionRecordRef,
21
+ DecisionRequest, DecisionResult, DecisionRuntime, DecisionRuntimeCapabilities,
22
+ DecisionRuntimeMetadata, DecisionTransportAuthorization, TransportAuthorizationGate,
23
+ };
24
+ use crate::FeltDb;
25
+ use serde::{Deserialize, Serialize};
26
+ use serde_json::Value;
27
+ use sha2::{Digest, Sha256};
28
+ use std::cell::Cell;
29
+
30
+ /// The largest candidate page one semantic query request may transform; the
31
+ /// bounded authority query's own limit.
32
+ pub const MAX_SEMANTIC_CANDIDATES: usize = 1_000;
33
+
34
+ #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
35
+ #[serde(rename_all = "kebab-case")]
36
+ pub enum SemanticQueryMode {
37
+ /// Reuse a durable judgment where one exists; execute the runtime for every
38
+ /// other candidate with a non-empty authorized context.
39
+ #[default]
40
+ Evaluate,
41
+ /// Never reach the runtime. Candidates without a reusable judgment are
42
+ /// reported as unevaluated.
43
+ ReuseOnly,
44
+ }
45
+
46
+ /// The typed filter a semantic clause applies to each candidate's result.
47
+ ///
48
+ /// Which keys are valid depends on the decision kind: `binary` takes `is`,
49
+ /// `choice` takes `in`, and `score` takes `in`, `atLeast`, and `atMost`, all
50
+ /// compared by the ordinal position of the selected level. `option_mass` is
51
+ /// never a filter operand.
52
+ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
53
+ #[serde(deny_unknown_fields)]
54
+ pub struct SemanticQueryFilter {
55
+ #[serde(default, skip_serializing_if = "Option::is_none")]
56
+ pub is: Option<bool>,
57
+ #[serde(default, rename = "in", skip_serializing_if = "Option::is_none")]
58
+ pub within: Option<Vec<String>>,
59
+ #[serde(default, rename = "atLeast", skip_serializing_if = "Option::is_none")]
60
+ pub at_least: Option<String>,
61
+ #[serde(default, rename = "atMost", skip_serializing_if = "Option::is_none")]
62
+ pub at_most: Option<String>,
63
+ }
64
+
65
+ #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
66
+ #[serde(rename_all = "lowercase")]
67
+ pub enum SemanticOrderDirection {
68
+ Asc,
69
+ Desc,
70
+ }
71
+
72
+ /// Ordering within the candidate page by the ordinal of a `score` level.
73
+ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
74
+ #[serde(deny_unknown_fields)]
75
+ pub struct SemanticQueryOrder {
76
+ pub direction: SemanticOrderDirection,
77
+ }
78
+
79
+ /// The semantic clause of a bounded authority query.
80
+ ///
81
+ /// Unknown keys are refused rather than ignored: a clause a runtime does not
82
+ /// understand must fail the request, never execute the deterministic part and
83
+ /// return it as though the clause had been honored.
84
+ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
85
+ #[serde(deny_unknown_fields)]
86
+ pub struct SemanticQueryClause {
87
+ pub decision: DecisionDefinition,
88
+ #[serde(default)]
89
+ pub mode: SemanticQueryMode,
90
+ #[serde(default, skip_serializing_if = "Option::is_none")]
91
+ pub filter: Option<SemanticQueryFilter>,
92
+ #[serde(default, rename = "orderBy", skip_serializing_if = "Option::is_none")]
93
+ pub order_by: Option<SemanticQueryOrder>,
94
+ /// Explicit field selection, narrowed further by authorization.
95
+ #[serde(default, skip_serializing_if = "Option::is_none")]
96
+ pub fields: Option<Vec<String>>,
97
+ #[serde(
98
+ default,
99
+ rename = "schemaVersion",
100
+ skip_serializing_if = "Option::is_none"
101
+ )]
102
+ pub schema_version: Option<String>,
103
+ /// Field-level authorization narrowing, in the same shape the
104
+ /// semantic-decision transport accepts. The principal is bound by the
105
+ /// authority to the authenticated principal before evaluation.
106
+ #[serde(default, skip_serializing_if = "Option::is_none")]
107
+ pub authorization: Option<DecisionTransportAuthorization>,
108
+ }
109
+
110
+ /// One record of the deterministic page, as the deterministic stage returned it.
111
+ #[derive(Debug, Clone, PartialEq)]
112
+ pub struct SemanticCandidate {
113
+ pub record_id: String,
114
+ pub record: Value,
115
+ }
116
+
117
+ /// The semantic annotation of one page record.
118
+ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
119
+ pub struct SemanticAnnotation {
120
+ pub record_id: String,
121
+ pub result: DecisionResult,
122
+ pub cached: bool,
123
+ pub provenance: DecisionProvenance,
124
+ }
125
+
126
+ #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
127
+ #[serde(rename_all = "kebab-case")]
128
+ pub enum SemanticUnevaluatedReason {
129
+ /// The authorized context was empty, so the primitive refused to evaluate.
130
+ Unauthorized,
131
+ /// `reuse-only` mode found no reusable judgment.
132
+ NoJudgment,
133
+ /// The record left authoritative state between the deterministic page
134
+ /// and the semantic stage.
135
+ Missing,
136
+ }
137
+
138
+ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
139
+ pub struct SemanticUnevaluated {
140
+ pub record_id: String,
141
+ pub reason: SemanticUnevaluatedReason,
142
+ }
143
+
144
+ /// Stage-level provenance and the measured execution counts of one request.
145
+ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
146
+ pub struct SemanticStageSummary {
147
+ pub definition_hash: String,
148
+ pub schema_version: String,
149
+ pub runtime: DecisionRuntimeMetadata,
150
+ pub mode: SemanticQueryMode,
151
+ pub candidates: usize,
152
+ pub reused: usize,
153
+ pub evaluated: usize,
154
+ pub unevaluated: usize,
155
+ pub filtered: usize,
156
+ }
157
+
158
+ /// The candidate page after the semantic stage.
159
+ ///
160
+ /// `records` and `annotations` are aligned: `annotations[i]` describes
161
+ /// `records[i]`, and is `None` for a record that could not be evaluated.
162
+ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
163
+ pub struct SemanticPage {
164
+ pub records: Vec<Value>,
165
+ pub annotations: Vec<Option<SemanticAnnotation>>,
166
+ pub unevaluated: Vec<SemanticUnevaluated>,
167
+ pub complete: bool,
168
+ pub stage: SemanticStageSummary,
169
+ }
170
+
171
+ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
172
+ pub struct SemanticQueryError {
173
+ pub code: String,
174
+ pub message: String,
175
+ }
176
+
177
+ impl SemanticQueryError {
178
+ pub fn new(code: &str, message: impl Into<String>) -> Self {
179
+ Self {
180
+ code: code.into(),
181
+ message: message.into(),
182
+ }
183
+ }
184
+
185
+ fn invalid(message: impl Into<String>) -> Self {
186
+ Self::new("INVALID_QUERY", message)
187
+ }
188
+ }
189
+
190
+ impl std::fmt::Display for SemanticQueryError {
191
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
192
+ write!(f, "{}: {}", self.code, self.message)
193
+ }
194
+ }
195
+
196
+ impl std::error::Error for SemanticQueryError {}
197
+
198
+ /// Validate a semantic clause before any deterministic work runs.
199
+ ///
200
+ /// Returns the validated (whitespace-canonical) decision definition, which is
201
+ /// the definition every candidate is evaluated with.
202
+ pub fn validate_semantic_clause(
203
+ clause: &SemanticQueryClause,
204
+ ) -> Result<DecisionDefinition, SemanticQueryError> {
205
+ let definition = validate_decision_definition(&clause.decision)
206
+ .map_err(|error| SemanticQueryError::invalid(error.message))?;
207
+ let kind = definition.kind();
208
+ let declared = definition.schema_values();
209
+ if let Some(filter) = &clause.filter {
210
+ let keys = [
211
+ filter.is.is_some(),
212
+ filter.within.is_some(),
213
+ filter.at_least.is_some(),
214
+ filter.at_most.is_some(),
215
+ ];
216
+ if !keys.iter().any(|set| *set) {
217
+ return Err(SemanticQueryError::invalid(
218
+ "semantic filter requires at least one operator",
219
+ ));
220
+ }
221
+ match kind {
222
+ DecisionKind::Binary => {
223
+ if filter.is.is_none() || keys[1] || keys[2] || keys[3] {
224
+ return Err(SemanticQueryError::invalid(
225
+ "binary semantic filters take exactly `is`",
226
+ ));
227
+ }
228
+ }
229
+ DecisionKind::Choice => {
230
+ if filter.within.is_none() || keys[0] || keys[2] || keys[3] {
231
+ return Err(SemanticQueryError::invalid(
232
+ "choice semantic filters take exactly `in`",
233
+ ));
234
+ }
235
+ }
236
+ DecisionKind::Score => {
237
+ if keys[0] {
238
+ return Err(SemanticQueryError::invalid(
239
+ "score semantic filters take `in`, `atLeast`, and `atMost`",
240
+ ));
241
+ }
242
+ }
243
+ }
244
+ for value in filter
245
+ .within
246
+ .iter()
247
+ .flatten()
248
+ .chain(filter.at_least.iter())
249
+ .chain(filter.at_most.iter())
250
+ {
251
+ if !declared.contains(value) {
252
+ return Err(SemanticQueryError::invalid(format!(
253
+ "semantic filter names \"{value}\", which the decision does not declare"
254
+ )));
255
+ }
256
+ }
257
+ if let Some(values) = &filter.within {
258
+ if values.is_empty() {
259
+ return Err(SemanticQueryError::invalid(
260
+ "semantic `in` filter requires at least one declared value",
261
+ ));
262
+ }
263
+ }
264
+ }
265
+ if clause.order_by.is_some() && kind != DecisionKind::Score {
266
+ return Err(SemanticQueryError::invalid(
267
+ "only score decisions order a semantic page",
268
+ ));
269
+ }
270
+ if let Some(fields) = &clause.fields {
271
+ if fields.is_empty() || fields.iter().any(|field| field.trim().is_empty()) {
272
+ return Err(SemanticQueryError::invalid(
273
+ "semantic field selection must name at least one non-empty field",
274
+ ));
275
+ }
276
+ }
277
+ Ok(definition)
278
+ }
279
+
280
+ /// Stable identity of a decision definition for stage provenance and cursor
281
+ /// binding.
282
+ pub fn semantic_definition_hash(definition: &DecisionDefinition) -> String {
283
+ let mut hasher = Sha256::new();
284
+ hasher.update(b"semantic-query-definition-v1");
285
+ hasher.update([0x1f]);
286
+ hasher.update(serde_json::to_vec(definition).unwrap_or_default());
287
+ format!("sha256:{:x}", hasher.finalize())
288
+ }
289
+
290
+ /// Stable identity of a whole semantic clause, for binding a continuation
291
+ /// cursor to the clause it was issued under.
292
+ pub fn semantic_clause_hash(clause: &SemanticQueryClause) -> String {
293
+ let mut hasher = Sha256::new();
294
+ hasher.update(b"semantic-query-clause-v1");
295
+ hasher.update([0x1f]);
296
+ hasher.update(serde_json::to_vec(clause).unwrap_or_default());
297
+ format!("sha256:{:x}", hasher.finalize())
298
+ }
299
+
300
+ /// Wraps the configured runtime so a failure inside the provider can be told
301
+ /// apart from a result the provider returned but FeltDB rejected.
302
+ struct ProviderBoundary<'a> {
303
+ inner: &'a dyn DecisionRuntime,
304
+ failed: Cell<Option<DecisionError>>,
305
+ }
306
+
307
+ impl DecisionRuntime for ProviderBoundary<'_> {
308
+ fn metadata(&self) -> DecisionRuntimeMetadata {
309
+ self.inner.metadata()
310
+ }
311
+
312
+ fn capabilities(&self) -> DecisionRuntimeCapabilities {
313
+ self.inner.capabilities()
314
+ }
315
+
316
+ fn decide(&self, request: &DecisionRequest) -> Result<DecisionResult, DecisionError> {
317
+ self.inner
318
+ .execute(request)
319
+ .inspect_err(|error| self.failed.set(Some(error.clone())))
320
+ }
321
+ }
322
+
323
+ fn ordinal(definition: &DecisionDefinition, value: &str) -> Option<usize> {
324
+ definition
325
+ .schema_values()
326
+ .iter()
327
+ .position(|declared| declared == value)
328
+ }
329
+
330
+ fn selected_value(result: &DecisionResult) -> Option<&str> {
331
+ match result {
332
+ DecisionResult::Binary { .. } => None,
333
+ DecisionResult::Choice { selected, .. } | DecisionResult::Score { selected, .. } => {
334
+ Some(selected.as_str())
335
+ }
336
+ }
337
+ }
338
+
339
+ fn filter_keeps(
340
+ definition: &DecisionDefinition,
341
+ filter: &SemanticQueryFilter,
342
+ result: &DecisionResult,
343
+ ) -> bool {
344
+ match result {
345
+ DecisionResult::Binary { decision, .. } => filter.is == Some(*decision),
346
+ DecisionResult::Choice { selected, .. } => filter
347
+ .within
348
+ .as_ref()
349
+ .is_some_and(|values| values.iter().any(|value| value == selected)),
350
+ DecisionResult::Score { selected, .. } => {
351
+ let Some(position) = ordinal(definition, selected) else {
352
+ return false;
353
+ };
354
+ let within = filter
355
+ .within
356
+ .as_ref()
357
+ .is_none_or(|values| values.iter().any(|value| value == selected));
358
+ let at_least = filter
359
+ .at_least
360
+ .as_ref()
361
+ .and_then(|level| ordinal(definition, level))
362
+ .is_none_or(|floor| position >= floor);
363
+ let at_most = filter
364
+ .at_most
365
+ .as_ref()
366
+ .and_then(|level| ordinal(definition, level))
367
+ .is_none_or(|ceiling| position <= ceiling);
368
+ within && at_least && at_most
369
+ }
370
+ }
371
+ }
372
+
373
+ fn map_stage_error(error: DecisionError, provider_failed: bool) -> SemanticQueryError {
374
+ match error.code.as_str() {
375
+ "DECISION_UNSUPPORTED" => SemanticQueryError::new("SEMANTIC_UNSUPPORTED", error.message),
376
+ "DECISION_STORAGE_ERROR" => SemanticQueryError::new(&error.code, error.message),
377
+ _ if provider_failed => SemanticQueryError::new(
378
+ "SEMANTIC_PROVIDER_UNAVAILABLE",
379
+ format!("semantic runtime could not evaluate a candidate: {error}"),
380
+ ),
381
+ _ => SemanticQueryError::new(
382
+ "SEMANTIC_INVALID_RESULT",
383
+ format!("semantic runtime returned a result FeltDB rejected: {error}"),
384
+ ),
385
+ }
386
+ }
387
+
388
+ /// Transform one deterministic candidate page with a semantic clause.
389
+ ///
390
+ /// `candidates` is the page exactly as the deterministic stage produced it,
391
+ /// in its total order. `runtime` is the deployment's configured binding; with
392
+ /// none configured the request fails with `SEMANTIC_PROVIDER_UNAVAILABLE` in
393
+ /// either mode, because even `reuse-only` needs the binding's identity to
394
+ /// name the judgments it may reuse. `principal` is the authenticated principal
395
+ /// the authority binds field-level authorization to.
396
+ pub fn compose_semantic_page(
397
+ db: &FeltDb,
398
+ collection: &str,
399
+ candidates: Vec<SemanticCandidate>,
400
+ clause: &SemanticQueryClause,
401
+ runtime: Option<&dyn DecisionRuntime>,
402
+ principal: Option<DecisionPrincipal>,
403
+ ) -> Result<SemanticPage, SemanticQueryError> {
404
+ let definition = validate_semantic_clause(clause)?;
405
+ if candidates.len() > MAX_SEMANTIC_CANDIDATES {
406
+ return Err(SemanticQueryError::invalid(format!(
407
+ "semantic composition is bounded to {MAX_SEMANTIC_CANDIDATES} candidates per page"
408
+ )));
409
+ }
410
+ let runtime = runtime.ok_or_else(|| {
411
+ SemanticQueryError::new(
412
+ "SEMANTIC_PROVIDER_UNAVAILABLE",
413
+ "no semantic runtime binding is configured for this authority",
414
+ )
415
+ })?;
416
+ let capabilities = runtime.capabilities();
417
+ let supported = match definition.kind() {
418
+ DecisionKind::Binary => capabilities.binary,
419
+ DecisionKind::Choice => capabilities.choice,
420
+ DecisionKind::Score => capabilities.score,
421
+ };
422
+ if !supported {
423
+ return Err(SemanticQueryError::new(
424
+ "SEMANTIC_UNSUPPORTED",
425
+ format!(
426
+ "the configured semantic runtime does not support {:?} decisions",
427
+ definition.kind()
428
+ ),
429
+ ));
430
+ }
431
+ let boundary = ProviderBoundary {
432
+ inner: runtime,
433
+ failed: Cell::new(None),
434
+ };
435
+ let runtime_metadata = boundary.metadata();
436
+ let options = DecisionOptions {
437
+ fields: clause.fields.clone(),
438
+ application_id: principal
439
+ .as_ref()
440
+ .map(|principal| principal.application_id.clone()),
441
+ decision_collection: None,
442
+ schema_version: clause
443
+ .schema_version
444
+ .clone()
445
+ .or_else(|| DecisionOptions::default().schema_version),
446
+ };
447
+ let gate = clause.authorization.as_ref().map(|authorization| {
448
+ (
449
+ TransportAuthorizationGate::new(&authorization.allowed_fields),
450
+ DecisionAuthorizationConfig {
451
+ principal: principal.clone(),
452
+ },
453
+ )
454
+ });
455
+ let authorization = gate
456
+ .as_ref()
457
+ .map(|(gate, config)| (gate as &dyn DecisionAuthorizationGate, config));
458
+
459
+ let mut stage = SemanticStageSummary {
460
+ definition_hash: semantic_definition_hash(&definition),
461
+ schema_version: options.schema_version.clone().unwrap_or_default(),
462
+ runtime: runtime_metadata.clone(),
463
+ mode: clause.mode,
464
+ candidates: candidates.len(),
465
+ reused: 0,
466
+ evaluated: 0,
467
+ unevaluated: 0,
468
+ filtered: 0,
469
+ };
470
+
471
+ // Evaluate every candidate of the page and nothing else. Each entry keeps
472
+ // its deterministic position so ordering can break ties with it.
473
+ let mut evaluated: Vec<(usize, SemanticCandidate, Option<SemanticAnnotation>)> =
474
+ Vec::with_capacity(candidates.len());
475
+ let mut unevaluated = Vec::new();
476
+ for (position, candidate) in candidates.into_iter().enumerate() {
477
+ let target = DecisionRecordRef {
478
+ collection: collection.into(),
479
+ record_id: candidate.record_id.clone(),
480
+ };
481
+ let reused = reuse_record_judgment(
482
+ db,
483
+ &target,
484
+ &definition,
485
+ &runtime_metadata,
486
+ &options,
487
+ authorization,
488
+ );
489
+ let evaluation = match reused {
490
+ Ok(Some(evaluation)) => {
491
+ stage.reused += 1;
492
+ Some(evaluation)
493
+ }
494
+ Ok(None) => match clause.mode {
495
+ SemanticQueryMode::ReuseOnly => {
496
+ unevaluated.push(SemanticUnevaluated {
497
+ record_id: candidate.record_id.clone(),
498
+ reason: SemanticUnevaluatedReason::NoJudgment,
499
+ });
500
+ None
501
+ }
502
+ SemanticQueryMode::Evaluate => {
503
+ let evaluation =
504
+ decide_record(db, &target, &definition, &boundary, &options, authorization)
505
+ .map_err(|error| {
506
+ let failed = boundary.failed.take().is_some();
507
+ map_stage_error(error, failed)
508
+ })?;
509
+ if evaluation.cached {
510
+ // A judgment written between the lookup and the
511
+ // execution is still a reuse, not an execution.
512
+ stage.reused += 1;
513
+ } else {
514
+ stage.evaluated += 1;
515
+ }
516
+ Some(evaluation)
517
+ }
518
+ },
519
+ Err(error) => match error.code.as_str() {
520
+ "DECISION_CONTEXT_EMPTY" => {
521
+ unevaluated.push(SemanticUnevaluated {
522
+ record_id: candidate.record_id.clone(),
523
+ reason: SemanticUnevaluatedReason::Unauthorized,
524
+ });
525
+ None
526
+ }
527
+ "DECISION_RECORD_NOT_FOUND" => {
528
+ unevaluated.push(SemanticUnevaluated {
529
+ record_id: candidate.record_id.clone(),
530
+ reason: SemanticUnevaluatedReason::Missing,
531
+ });
532
+ None
533
+ }
534
+ _ => return Err(map_stage_error(error, false)),
535
+ },
536
+ };
537
+ let annotation = evaluation.map(|evaluation| SemanticAnnotation {
538
+ record_id: candidate.record_id.clone(),
539
+ result: evaluation.result,
540
+ cached: evaluation.cached,
541
+ provenance: evaluation.provenance,
542
+ });
543
+ evaluated.push((position, candidate, annotation));
544
+ }
545
+ stage.unevaluated = unevaluated.len();
546
+
547
+ // Filter within the page. An unevaluated candidate cannot satisfy a
548
+ // filter, and its absence is reported, never silently assumed.
549
+ if let Some(filter) = &clause.filter {
550
+ let before = evaluated.len();
551
+ evaluated.retain(|(_, _, annotation)| {
552
+ annotation
553
+ .as_ref()
554
+ .is_some_and(|annotation| filter_keeps(&definition, filter, &annotation.result))
555
+ });
556
+ stage.filtered = before - evaluated.len();
557
+ }
558
+
559
+ // Order within the page: semantic ordinal, then the deterministic order
560
+ // the page arrived in. Unevaluated candidates sort after every evaluated
561
+ // one, in deterministic order.
562
+ if let Some(order) = &clause.order_by {
563
+ evaluated.sort_by(|left, right| {
564
+ let key = |entry: &(usize, SemanticCandidate, Option<SemanticAnnotation>)| {
565
+ entry
566
+ .2
567
+ .as_ref()
568
+ .and_then(|annotation| selected_value(&annotation.result))
569
+ .and_then(|selected| ordinal(&definition, selected))
570
+ };
571
+ match (key(left), key(right)) {
572
+ (Some(l), Some(r)) => {
573
+ let ordered = l.cmp(&r);
574
+ let ordered = match order.direction {
575
+ SemanticOrderDirection::Asc => ordered,
576
+ SemanticOrderDirection::Desc => ordered.reverse(),
577
+ };
578
+ ordered.then(left.0.cmp(&right.0))
579
+ }
580
+ (Some(_), None) => std::cmp::Ordering::Less,
581
+ (None, Some(_)) => std::cmp::Ordering::Greater,
582
+ (None, None) => left.0.cmp(&right.0),
583
+ }
584
+ });
585
+ }
586
+
587
+ let complete = unevaluated.is_empty();
588
+ let (records, annotations) = evaluated
589
+ .into_iter()
590
+ .map(|(_, candidate, annotation)| (candidate.record, annotation))
591
+ .unzip();
592
+ Ok(SemanticPage {
593
+ records,
594
+ annotations,
595
+ unevaluated,
596
+ complete,
597
+ stage,
598
+ })
599
+ }