uqa-storage 0.3.6

Document store, inverted index, IVF/HNSW vectors, B-tree, R*Tree, catalog
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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

use super::IndexedFieldMetadata;
use super::{
    counter_error, Analyzer, Arc, BTreeMap, BlockMaxScorer, DocId, FieldName, IndexStats,
    PostingEntry, PostingList, StorageBackendError, StorageBackendResult,
};
use crate::clustered_postings::BudgetedPostingReadCursor;
use crate::clustered_postings::{
    MaterializedPostingCursor, OccurrencePosting, PostingCursor, PostingScore,
};
use crate::read_control::StorageReadControl;
use crate::TokenTermKey;
use uqa_core::memory::Budgeted;
use uqa_core::TokenOccurrence;

/// Which side of the index/search pipeline a field analyzer applies to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AnalyzerPhase {
    /// Run only when *adding* documents.
    Index,
    /// Run only when *querying* documents (e.g. through `TermOperator`).
    Search,
    /// Run on both phases (the default).
    Both,
}

impl AnalyzerPhase {
    pub fn parse(s: &str) -> Result<Self, String> {
        match s {
            "index" => Ok(AnalyzerPhase::Index),
            "search" | "query" => Ok(AnalyzerPhase::Search),
            "both" => Ok(AnalyzerPhase::Both),
            _ => Err(format!("phase must be 'index'|'search'|'both', got `{s}`")),
        }
    }
}

impl std::str::FromStr for AnalyzerPhase {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

pub trait InvertedIndex: Send + Sync {
    /// Whether persisted positional data must be rebuilt from original sources before this index can be read or mutated. The owning engine performs this after restoring exact analyzer revisions, in the same initial-open transaction.
    fn source_rebuild_required(&self) -> StorageBackendResult<bool> {
        Ok(false)
    }

    fn analyzer(&self) -> &Analyzer;

    fn add_document(
        &mut self,
        doc_id: DocId,
        fields: BTreeMap<FieldName, String>,
    ) -> StorageBackendResult<()>;

    fn try_add_document(
        &mut self,
        doc_id: DocId,
        fields: BTreeMap<FieldName, String>,
    ) -> StorageBackendResult<()> {
        self.add_document(doc_id, fields)
    }

    /// Add or replace several documents in input order. The default preserves the point-mutation contract for custom backends; transactional persistent backends can override this to make the call atomic and coalesce writes that share physical posting clusters.
    fn try_add_documents(
        &mut self,
        documents: Vec<(DocId, BTreeMap<FieldName, String>)>,
    ) -> StorageBackendResult<()> {
        for (doc_id, fields) in documents {
            self.try_add_document(doc_id, fields)?;
        }
        Ok(())
    }

    fn remove_document(&mut self, doc_id: DocId) -> StorageBackendResult<()>;

    fn try_remove_document(&mut self, doc_id: DocId) -> StorageBackendResult<()> {
        self.remove_document(doc_id)
    }

    fn clear(&mut self) -> StorageBackendResult<()>;

    fn try_clear(&mut self) -> StorageBackendResult<()> {
        self.clear()
    }

    fn try_rebuild_documents(
        &mut self,
        documents: Vec<(DocId, BTreeMap<FieldName, String>)>,
    ) -> StorageBackendResult<()> {
        self.try_clear()?;
        for (doc_id, fields) in documents {
            if !fields.is_empty() {
                self.try_add_document(doc_id, fields)?;
            }
        }
        Ok(())
    }

    fn get_posting_list(&self, field: &str, term: &str) -> StorageBackendResult<PostingList>;

    /// Unique-position compatibility projection for an exact term key. Legacy providers accept scalar keys and reject unpaired UTF-16 explicitly.
    fn get_posting_list_key(
        &self,
        field: &str,
        term: &TokenTermKey,
    ) -> StorageBackendResult<PostingList> {
        self.get_posting_list(field, &term.to_term().into_string()?)
    }

    /// Score cursor with exact term identity and occurrence frequency independent of unique positions.
    fn posting_cursor_key(
        &self,
        field: &str,
        term: &TokenTermKey,
    ) -> StorageBackendResult<Box<dyn PostingCursor>> {
        self.posting_cursor(field, &term.to_term().into_string()?)
    }

    /// Traverse candidates while retaining this index read. Providers with borrowed posting maps can avoid copying the entire term support; owned persistent cursors keep their incremental reads.
    fn posting_read_cursor_key<'a>(
        &'a self,
        field: &'a str,
        term: &TokenTermKey,
    ) -> StorageBackendResult<Box<dyn crate::clustered_postings::PostingReadCursor + 'a>> {
        Ok(Box::new(crate::clustered_postings::OwnedPostingReadCursor(
            self.posting_cursor_key(field, term)?,
        )))
    }

    /// Open a cursor that owns every query allocation under the supplied allowance. Providers must implement this capability without an unbounded materialization fallback.
    fn posting_read_cursor_key_budgeted<'a>(
        &'a self,
        field: &'a str,
        term: &'a TokenTermKey,
        control: &StorageReadControl,
    ) -> StorageBackendResult<BudgetedPostingReadCursor<'a>> {
        crate::clustered_postings::open_controlled_cursor(self, field, term, control)
    }

    /// Visit encoded score clusters in ascending order under the retained provider read. Temporary payloads must be reserved before fetching; callbacks must not reenter the provider.
    fn visit_score_clusters(
        &self,
        _field: &str,
        _term: &TokenTermKey,
        _after: Option<u64>,
        _limit: usize,
        control: &StorageReadControl,
        _visit: &mut crate::clustered_postings::ScoreClusterVisitor<'_>,
    ) -> StorageBackendResult<()> {
        control.check()?;
        Err(StorageBackendError::Other(
            "controlled score cluster reads are not supported by this backend".into(),
        ))
    }

    /// Decode one document's exact occurrences with provider-owned input and output reservations and cancellation checks.
    fn get_occurrences_budgeted(
        &self,
        _doc_id: DocId,
        _field: &str,
        _term: &TokenTermKey,
        control: &StorageReadControl,
    ) -> StorageBackendResult<Budgeted<Vec<TokenOccurrence>>> {
        control.check()?;
        Err(StorageBackendError::Other(
            "controlled occurrence reads are not supported by this backend".into(),
        ))
    }

    /// Complete graph edges in document order, preserving occurrence multiplicity and original source coordinates. Legacy positions cannot implement this contract without a source rebuild.
    fn get_occurrence_postings(
        &self,
        _field: &str,
        _term: &TokenTermKey,
    ) -> StorageBackendResult<Vec<OccurrencePosting>> {
        Err(StorageBackendError::Other(
            "lossless occurrence storage is not supported by this backend".into(),
        ))
    }

    /// Exact occurrences for one document and term; an absent document or term has no occurrences.
    fn get_occurrences(
        &self,
        doc_id: DocId,
        field: &str,
        term: &TokenTermKey,
    ) -> StorageBackendResult<Vec<TokenOccurrence>> {
        Ok(self
            .get_occurrence_postings(field, term)?
            .into_iter()
            .find(|posting| posting.doc_id == doc_id)
            .map_or_else(Vec::new, |posting| posting.occurrences))
    }

    /// Original stream-end state and revision metadata published with a document field, including fields that emitted no tokens.
    fn indexed_field_metadata(
        &self,
        _doc_id: DocId,
        _field: &str,
    ) -> StorageBackendResult<Option<IndexedFieldMetadata>> {
        Err(StorageBackendError::Other(
            "indexed field analysis metadata is not supported by this backend".into(),
        ))
    }

    fn doc_freq_key(&self, field: &str, term: &TokenTermKey) -> StorageBackendResult<u64> {
        self.doc_freq(field, &term.to_term().into_string()?)
    }

    fn get_term_freq_key(
        &self,
        doc_id: DocId,
        field: &str,
        term: &TokenTermKey,
    ) -> StorageBackendResult<u64> {
        self.get_term_freq(doc_id, field, &term.to_term().into_string()?)
    }

    /// Sorted canonical term keys, including unpaired units. String-only vocabulary APIs must return an error if projection would lose identity.
    fn vocabulary_keys(&self, field: &str) -> StorageBackendResult<Vec<TokenTermKey>> {
        Ok(self
            .vocabulary_terms(field)?
            .iter()
            .map(|term| TokenTermKey::from_text(term))
            .collect())
    }

    fn get_posting_lists_bulk(
        &self,
        field: &str,
        terms: &[String],
    ) -> StorageBackendResult<Vec<PostingList>> {
        terms
            .iter()
            .map(|term| self.get_posting_list(field, term))
            .collect()
    }

    /// Open a doc-id ordered score cursor for one term.
    ///
    /// The cursor carries term frequency and document length directly so
    /// ranking does not need positional payloads or per-document length
    /// lookups. Persistent backends override this with lazy clustered
    /// cursors; the default preserves compatibility for custom backends.
    fn posting_cursor(
        &self,
        field: &str,
        term: &str,
    ) -> StorageBackendResult<Box<dyn PostingCursor>> {
        let posting_list = self.get_posting_list(field, term)?;
        let mut entries = Vec::with_capacity(posting_list.len());
        for posting in posting_list {
            let term_freq = self.get_term_freq(posting.doc_id, field, term)?;
            entries.push(PostingScore {
                doc_id: posting.doc_id,
                term_freq,
                doc_length: self.get_doc_length(posting.doc_id, field)?,
            });
        }
        Ok(Box::new(MaterializedPostingCursor::new(entries)?))
    }

    fn posting_cursors_bulk(
        &self,
        field: &str,
        terms: &[String],
    ) -> StorageBackendResult<Vec<Box<dyn PostingCursor>>> {
        terms
            .iter()
            .map(|term| self.posting_cursor(field, term))
            .collect()
    }

    /// Open exact-key cursors in input order, retaining repeated query terms. Scalar custom backends retain their optimized bulk implementation.
    fn posting_cursors_keys_bulk(
        &self,
        field: &str,
        terms: &[TokenTermKey],
    ) -> StorageBackendResult<Vec<Box<dyn PostingCursor>>> {
        if let Some(scalar) = terms
            .iter()
            .map(|key| key.as_str().map(str::to_owned))
            .collect::<Option<Vec<_>>>()
        {
            return self.posting_cursors_bulk(field, &scalar);
        }
        terms
            .iter()
            .map(|term| self.posting_cursor_key(field, term))
            .collect()
    }

    /// Read exact-key support without projecting UTF-16 term identity.
    fn get_posting_lists_keys_bulk(
        &self,
        field: &str,
        terms: &[TokenTermKey],
    ) -> StorageBackendResult<Vec<PostingList>> {
        if let Some(scalar) = terms
            .iter()
            .map(|key| key.as_str().map(str::to_owned))
            .collect::<Option<Vec<_>>>()
        {
            return self.get_posting_lists_bulk(field, &scalar);
        }
        terms
            .iter()
            .map(|term| self.get_posting_list_key(field, term))
            .collect()
    }

    /// Load exact-key scorer-versioned bounds. Custom scalar providers expose no raw-key materialization by default.
    fn persisted_block_max_scores_keys_bulk(
        &self,
        field: &str,
        terms: &[TokenTermKey],
        scorer_fingerprint: &str,
    ) -> StorageBackendResult<Vec<Option<Vec<f64>>>> {
        if let Some(scalar) = terms
            .iter()
            .map(|key| key.as_str().map(str::to_owned))
            .collect::<Option<Vec<_>>>()
        {
            return self.persisted_block_max_scores_bulk(field, &scalar, scorer_fingerprint);
        }
        terms
            .iter()
            .map(|key| match key.as_str() {
                Some(term) => self.persisted_block_max_scores(field, term, scorer_fingerprint),
                None => Ok(None),
            })
            .collect()
    }

    /// Exact-key scoring inputs aligned with both the document and query-term arrays, including repetitions.
    fn get_scoring_inputs_keys_bulk(
        &self,
        doc_ids: &[DocId],
        field: &str,
        terms: &[TokenTermKey],
    ) -> StorageBackendResult<Vec<(u64, Vec<u64>)>> {
        if let Some(scalar) = terms
            .iter()
            .map(|key| key.as_str().map(str::to_owned))
            .collect::<Option<Vec<_>>>()
        {
            return self.get_scoring_inputs_bulk(doc_ids, field, &scalar);
        }
        doc_ids
            .iter()
            .map(|id| {
                Ok((
                    self.get_doc_length(*id, field)?,
                    terms
                        .iter()
                        .map(|key| self.get_term_freq_key(*id, field, key))
                        .collect::<StorageBackendResult<_>>()?,
                ))
            })
            .collect()
    }

    /// Persist scorer-specific block maxima for every term in `field`.
    ///
    /// Backends that do not provide durable auxiliary indexes return `false`.
    /// The fingerprint must include every scorer and corpus statistic that can
    /// affect a term contribution; reads only expose rows with an exact match.
    fn rebuild_persisted_block_max(
        &mut self,
        _field: &str,
        _scorer: &dyn BlockMaxScorer,
        _scorer_fingerprint: &str,
    ) -> StorageBackendResult<bool> {
        Ok(false)
    }

    /// Load scorer-versioned block maxima for one posting list. `None` means
    /// the backend has no complete, valid materialization for this scorer.
    fn persisted_block_max_scores(
        &self,
        _field: &str,
        _term: &str,
        _scorer_fingerprint: &str,
    ) -> StorageBackendResult<Option<Vec<f64>>> {
        Ok(None)
    }

    /// Load scorer-versioned block maxima for several terms while preserving input order; persistent backends override this to avoid one storage round trip per term.
    fn persisted_block_max_scores_bulk(
        &self,
        field: &str,
        terms: &[String],
        scorer_fingerprint: &str,
    ) -> StorageBackendResult<Vec<Option<Vec<f64>>>> {
        terms
            .iter()
            .map(|term| self.persisted_block_max_scores(field, term, scorer_fingerprint))
            .collect()
    }

    /// Visit every posting entry for `(field, term)` in ascending
    /// doc-id order without handing out an owned list.
    ///
    /// [`InvertedIndex::get_posting_list`] deep-copies each entry's
    /// payload (positions vector included), which costs one heap
    /// allocation per matching document. Read-only scoring walks use
    /// this instead; backends whose postings already live in memory
    /// override it to iterate in place.
    fn for_each_posting(
        &self,
        field: &str,
        term: &str,
        visit: &mut dyn FnMut(&PostingEntry),
    ) -> StorageBackendResult<()> {
        for entry in &self.get_posting_list(field, term)? {
            visit(entry);
        }
        Ok(())
    }

    /// Visit `(doc_id, term_frequency)` pairs without requiring callers to
    /// materialize or decode payload details they do not use. The default
    /// uses posting support and the authoritative frequency accessor;
    /// persistent backends can stream compact frequency projections.
    fn for_each_term_freq(
        &self,
        field: &str,
        term: &str,
        visit: &mut dyn FnMut(DocId, u64),
    ) -> StorageBackendResult<()> {
        for entry in &self.get_posting_list(field, term)? {
            visit(entry.doc_id, self.get_term_freq(entry.doc_id, field, term)?);
        }
        Ok(())
    }

    fn doc_freq(&self, field: &str, term: &str) -> StorageBackendResult<u64>;

    fn get_doc_length(&self, doc_id: DocId, field: &str) -> StorageBackendResult<u64>;

    fn get_term_freq(&self, doc_id: DocId, field: &str, term: &str) -> StorageBackendResult<u64>;

    fn doc_count(&self) -> StorageBackendResult<u64>;

    fn total_field_length(&self, field: &str) -> StorageBackendResult<u64>;

    /// Number of documents that have indexed content for `field`.
    fn field_doc_count(&self, field: &str) -> StorageBackendResult<u64> {
        self.doc_length_count(Some(field))
    }

    /// Field-specific statistics for BM25 scoring.
    ///
    /// BM25 length normalization and IDF collection size are defined for
    /// one field. Reusing table-wide totals mixes unrelated field lengths
    /// and produces scores that cannot match a field-scoped BM25 scorer.
    fn field_stats(&self, field: &str) -> StorageBackendResult<IndexStats> {
        let mut stats = self.stats()?;
        let field_docs = self.field_doc_count(field)?;
        stats.total_docs = field_docs;
        stats.avg_doc_length = if field_docs > 0 {
            self.total_field_length(field)? as f64 / field_docs as f64
        } else {
            0.0
        };
        Ok(stats)
    }

    /// [`InvertedIndex::field_stats`] without the vocabulary-wide
    /// document-frequency map.
    ///
    /// Query execution that already knows its terms' document
    /// frequencies (it read them off the posting lists) only needs the
    /// field's document count and average length; copying the whole
    /// term dictionary per query is O(vocabulary) for nothing.
    fn field_stats_scalar(&self, field: &str) -> StorageBackendResult<IndexStats> {
        let mut stats = IndexStats::default();
        let field_docs = self.field_doc_count(field)?;
        stats.total_docs = field_docs;
        stats.avg_doc_length = if field_docs > 0 {
            self.total_field_length(field)? as f64 / field_docs as f64
        } else {
            0.0
        };
        Ok(stats)
    }

    /// Read only field scoring scalars with producer-owned temporary reservations.
    fn field_stats_scalar_budgeted(
        &self,
        _field: &str,
        control: &StorageReadControl,
    ) -> StorageBackendResult<IndexStats> {
        control.check()?;
        Err(StorageBackendError::Other(
            "controlled field statistics are not supported by this backend".into(),
        ))
    }

    /// Sorted unique indexed terms for `field`.
    ///
    /// Backends implement this from their term dictionary rather than by
    /// re-analyzing stored documents. This is the source used by Bayesian
    /// calibration reservoir sampling.
    fn vocabulary_terms(&self, _field: &str) -> StorageBackendResult<Vec<String>> {
        Ok(Vec::new())
    }

    /// Fully-populated [`IndexStats`] snapshot for the cost model and
    /// scoring layer. Implementations may cache this between mutations.
    fn stats(&self) -> StorageBackendResult<IndexStats>;

    /// Number of posting rows. With `field = Some(..)`, limits the count
    /// to one indexed field.
    fn posting_count(&self, _field: Option<&str>) -> StorageBackendResult<u64> {
        Ok(0)
    }

    /// Number of `(doc_id, field)` length rows. With `field = Some(..)`,
    /// this is the number of documents indexed for that field.
    fn doc_length_count(&self, _field: Option<&str>) -> StorageBackendResult<u64> {
        Ok(0)
    }

    /// Number of distinct indexed terms. With `field = Some(..)`, limits
    /// the count to one indexed field.
    fn term_count(&self, _field: Option<&str>) -> StorageBackendResult<u64> {
        Ok(0)
    }

    /// Read-only handle suitable for an `ExecutionContext`.
    fn snapshot(&self) -> StorageBackendResult<Arc<dyn InvertedIndex>>;

    /// Independent writable copy used to restore an in-memory engine
    /// transaction without reconstructing analyzer state from documents.
    fn writable_snapshot(&self) -> StorageBackendResult<Box<dyn InvertedIndex>> {
        Err(StorageBackendError::Other(
            "writable inverted-index snapshots are not supported by this backend".into(),
        ))
    }

    // -- Extended inverted-index surface ---

    /// Names of every field with at least one indexed document.
    /// Default implementation walks the [`IndexStats`] snapshot's
    /// total-length map. Backends with a richer schema can override.
    fn field_names(&self) -> StorageBackendResult<Vec<FieldName>> {
        Ok(Vec::new())
    }

    /// Posting list for `term` across every indexed field, unioned
    /// together. Default implementation sums per-field posting lists
    /// via [`PostingList::merge_union`].
    fn get_posting_list_any_field(&self, term: &str) -> StorageBackendResult<PostingList> {
        let mut result = PostingList::new();
        for field in self.field_names()? {
            let pl = self.get_posting_list(&field, term)?;
            result = result.merge_union(&pl);
        }
        Ok(result)
    }

    /// Document frequency of `term` across every indexed field.
    fn doc_freq_any_field(&self, term: &str) -> StorageBackendResult<u64> {
        let mut total = 0_u64;
        for field in self.field_names()? {
            total = total
                .checked_add(self.doc_freq(&field, term)?)
                .ok_or_else(|| counter_error("document frequency"))?;
        }
        Ok(total)
    }

    /// Sum of all per-field token lengths for a single doc.
    fn get_total_doc_length(&self, doc_id: DocId) -> StorageBackendResult<u64> {
        let mut total = 0_u64;
        for field in self.field_names()? {
            total = total
                .checked_add(self.get_doc_length(doc_id, &field)?)
                .ok_or_else(|| counter_error("document length"))?;
        }
        Ok(total)
    }

    /// Bulk doc-length lookup. Default falls back to per-id calls.
    fn get_doc_lengths_bulk(
        &self,
        doc_ids: &[DocId],
        field: &str,
    ) -> StorageBackendResult<BTreeMap<DocId, u64>> {
        let mut out = BTreeMap::new();
        for doc_id in doc_ids {
            out.insert(*doc_id, self.get_doc_length(*doc_id, field)?);
        }
        Ok(out)
    }

    /// Bulk term-frequency lookup. Default falls back to per-id calls.
    fn get_term_freqs_bulk(
        &self,
        doc_ids: &[DocId],
        field: &str,
        term: &str,
    ) -> StorageBackendResult<BTreeMap<DocId, u64>> {
        let mut out = BTreeMap::new();
        for doc_id in doc_ids {
            out.insert(*doc_id, self.get_term_freq(*doc_id, field, term)?);
        }
        Ok(out)
    }

    /// Fetch the document length and one term frequency per query term for
    /// every requested document. Results stay aligned with `doc_ids`.
    /// Persistent backends override this to collapse the scoring loop's
    /// per-document point reads into a small number of set-oriented queries.
    fn get_scoring_inputs_bulk(
        &self,
        doc_ids: &[DocId],
        field: &str,
        terms: &[String],
    ) -> StorageBackendResult<Vec<(u64, Vec<u64>)>> {
        let mut out = Vec::with_capacity(doc_ids.len());
        for doc_id in doc_ids {
            let mut term_freqs = Vec::with_capacity(terms.len());
            for term in terms {
                term_freqs.push(self.get_term_freq(*doc_id, field, term)?);
            }
            out.push((self.get_doc_length(*doc_id, field)?, term_freqs));
        }
        Ok(out)
    }

    /// Total term frequency for a doc summed across every indexed
    /// field.
    fn get_total_term_freq(&self, doc_id: DocId, term: &str) -> StorageBackendResult<u64> {
        let mut total = 0_u64;
        for field in self.field_names()? {
            total = total
                .checked_add(self.get_term_freq(doc_id, &field, term)?)
                .ok_or_else(|| counter_error("term frequency"))?;
        }
        Ok(total)
    }

    /// Bind an analyzer to a single field for the given phase.
    /// `Both` writes to both the index-side and search-side maps; the
    /// default impl errors so backends that don't support per-field
    /// analyzers fail loud rather than silently dropping the request.
    fn set_field_analyzer(
        &mut self,
        _field: &str,
        _analyzer: Analyzer,
        _phase: AnalyzerPhase,
    ) -> Result<(), String> {
        Err("set_field_analyzer not supported by this InvertedIndex backend".into())
    }

    /// Remove every per-field analyzer override for `field`.  This is the
    /// inverse of `set_field_analyzer(..., Both)` and is required when the
    /// final logical FTS index for a field is dropped.  The default errors so
    /// a backend cannot silently retain stale analysis behavior.
    fn remove_field_analyzers(&mut self, _field: &str) -> Result<(), String> {
        Err("remove_field_analyzers not supported by this InvertedIndex backend".into())
    }

    /// Index-time analyzer for `field`; falls back to
    /// [`InvertedIndex::analyzer`] when no override is set.
    fn get_field_analyzer(&self, _field: &str) -> Analyzer {
        self.analyzer().clone()
    }

    /// Compatibility configuration for search. Built-in providers return their independent retained search revision's inputs; this default preserves the index fallback for custom legacy providers. Use `search_analyzer_revision` for execution with exact resource ownership.
    fn get_search_analyzer(&self, field: &str) -> Analyzer {
        self.get_field_analyzer(field)
    }

    /// Retain the exact executable index revision. Built-in providers resolve their default once and keep field revisions immutable.
    fn index_analyzer_revision(
        &self,
        field: &str,
    ) -> StorageBackendResult<Arc<uqa_analysis::CompiledAnalyzer>> {
        Ok(self.get_field_analyzer(field).compile()?)
    }

    /// Retain the exact executable search revision independently of subsequent index assignments.
    fn search_analyzer_revision(
        &self,
        field: &str,
    ) -> StorageBackendResult<Arc<uqa_analysis::CompiledAnalyzer>> {
        Ok(self.get_search_analyzer(field).compile()?)
    }

    /// Install a validated revision without reopening its resources. This does not rebuild existing documents; graph providers reject a different index revision on a populated field and require `rebuild_with_analyzer_revision` instead.
    fn set_field_analyzer_revision(
        &mut self,
        _field: &str,
        _revision: Arc<uqa_analysis::CompiledAnalyzer>,
        _phase: AnalyzerPhase,
    ) -> Result<(), String> {
        Err("immutable analyzer revisions are not supported by this backend".into())
    }

    /// Install a complete retained pair atomically. Failure changes neither side; this does not rebuild existing postings.
    fn set_field_analyzer_revisions(
        &mut self,
        _field: &str,
        _index: Arc<uqa_analysis::CompiledAnalyzer>,
        _search: Arc<uqa_analysis::CompiledAnalyzer>,
    ) -> Result<(), String> {
        Err("atomic analyzer revision pairs are not supported by this backend".into())
    }

    /// Replace the complete indexed document set and selected analyzer sides together. Failure retains the previous postings and bindings; providers must implement their own atomic publication.
    fn rebuild_with_analyzer_revision(
        &mut self,
        _field: &str,
        _revision: Arc<uqa_analysis::CompiledAnalyzer>,
        _phase: AnalyzerPhase,
        _documents: Vec<(DocId, BTreeMap<FieldName, String>)>,
    ) -> StorageBackendResult<()> {
        Err(StorageBackendError::Other(
            "atomic analyzer revision rebuild is not supported by this backend".into(),
        ))
    }

    /// Rebuild under the caller's cancellation token. Cancellation must retain the complete previous index; custom providers must implement atomic staging and cancellation.
    fn try_rebuild_documents_cancellable(
        &mut self,
        _documents: Vec<(DocId, BTreeMap<FieldName, String>)>,
        cancellation: &uqa_core::CancellationToken,
    ) -> StorageBackendResult<()> {
        cancellation.check()?;
        Err(StorageBackendError::Other(
            "cancellable atomic index rebuild is not supported by this backend".into(),
        ))
    }

    /// Replace postings and selected analyzer revisions together, retaining both on cancellation before publication.
    fn rebuild_with_analyzer_revision_cancellable(
        &mut self,
        _field: &str,
        _revision: Arc<uqa_analysis::CompiledAnalyzer>,
        _phase: AnalyzerPhase,
        _documents: Vec<(DocId, BTreeMap<FieldName, String>)>,
        cancellation: &uqa_core::CancellationToken,
    ) -> StorageBackendResult<()> {
        cancellation.check()?;
        Err(StorageBackendError::Other(
            "cancellable atomic analyzer revision rebuild is not supported by this backend".into(),
        ))
    }
}