Skip to main content

hol_cigar/
graph.rs

1use crate::{ContextError, digest};
2use serde::{Deserialize, Serialize};
3use std::collections::{BTreeMap, BTreeSet};
4use std::sync::Arc;
5
6/// A source document. IDs and graph relations are application metadata, never inferred authority.
7#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)]
8#[serde(deny_unknown_fields)]
9pub struct Document {
10    /// Stable, application-assigned ID, at most 128 printable ASCII characters.
11    pub id: String,
12    /// Source locator retained in citations; not opened by this library.
13    pub source: String,
14    /// Exact UTF-8 source text.
15    pub text: String,
16    /// One-based offset in the original source, for application-provided fragments.
17    #[serde(default = "first_line")]
18    pub start_line: usize,
19}
20
21const fn first_line() -> usize {
22    1
23}
24
25impl Document {
26    pub(crate) fn validate_shape(&self) -> Result<(), ContextError> {
27        if !valid_id(&self.id)
28            || self.source.is_empty()
29            || self.source.len() > 2048
30            || self.source.chars().any(char::is_control)
31            || self.text.trim().is_empty()
32            || self.start_line == 0
33        {
34            return Err(ContextError::InvalidInput);
35        }
36        Ok(())
37    }
38
39    pub(crate) fn validate_bounds(&self, max_document_bytes: usize) -> Result<(), ContextError> {
40        if self.text.len() > max_document_bytes
41            || self
42                .start_line
43                .checked_add(self.text.lines().count().saturating_sub(1))
44                .is_none()
45        {
46            return Err(ContextError::LimitExceeded);
47        }
48        Ok(())
49    }
50
51    /// Constructs an input document. The graph validates bounds before indexing.
52    pub fn new(id: impl Into<String>, source: impl Into<String>, text: impl Into<String>) -> Self {
53        Self {
54            id: id.into(),
55            source: source.into(),
56            text: text.into(),
57            start_line: 1,
58        }
59    }
60
61    /// Splits explicit text into overlapping line chunks, preserving original line numbers and
62    /// UTF-8/line terminators. This is not an AST parser: choose complete symbols yourself when
63    /// syntax must remain intact. At most 4096 chunks and 16 MiB of input are accepted.
64    /// Replace/withdraw obsolete chunk IDs after source edits; this method does not mutate a graph.
65    pub fn chunks(
66        &self,
67        max_lines: usize,
68        overlap_lines: usize,
69    ) -> Result<Vec<Self>, ContextError> {
70        if max_lines == 0
71            || overlap_lines >= max_lines
72            || !valid_id(&self.id)
73            || self.id.len() > 100
74            || self.start_line == 0
75            || self.text.trim().is_empty()
76        {
77            return Err(ContextError::InvalidInput);
78        }
79        if self.text.len() > 16_777_216 {
80            return Err(ContextError::LimitExceeded);
81        }
82        let lines = self.text.split_inclusive('\n').collect::<Vec<_>>();
83        let mut chunks = Vec::new();
84        let mut start = 0;
85        while start < lines.len() {
86            let end = start.saturating_add(max_lines).min(lines.len());
87            let text = lines
88                .get(start..end)
89                .ok_or(ContextError::Integrity)?
90                .concat();
91            if !text.trim().is_empty() {
92                if chunks.len() >= 4096 {
93                    return Err(ContextError::LimitExceeded);
94                }
95                let start_line = self
96                    .start_line
97                    .checked_add(start)
98                    .ok_or(ContextError::LimitExceeded)?;
99                chunks.push(Self {
100                    id: format!("{}:L{start_line}", self.id),
101                    source: self.source.clone(),
102                    text,
103                    start_line,
104                });
105            }
106            if end == lines.len() {
107                break;
108            }
109            start = end - overlap_lines;
110        }
111        Ok(chunks)
112    }
113}
114
115impl std::fmt::Debug for Document {
116    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        f.debug_struct("Document")
118            .field("bytes", &self.text.len())
119            .finish_non_exhaustive()
120    }
121}
122
123/// Semantics of a directed relation from one document to another.
124#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
125#[serde(rename_all = "snake_case")]
126pub enum EdgeKind {
127    /// Selecting the source requires the target's complete text and its hard closure.
128    Requires,
129    /// Selecting either side includes the other's complete text, preserving counterevidence.
130    Contradicts,
131    /// The target is supporting evidence, considered during bounded graph expansion.
132    Supports,
133    /// The target is a related lead, with a smaller expansion score.
134    Related,
135}
136
137/// Memory and ingestion limits enforced before graph mutation.
138#[derive(Clone, Copy, Debug)]
139pub struct GraphLimits {
140    /// Maximum live documents.
141    pub max_documents: usize,
142    /// Maximum UTF-8 bytes per document.
143    pub max_document_bytes: usize,
144    /// Maximum total live text bytes.
145    pub max_total_bytes: usize,
146    /// Maximum outgoing edges per document.
147    pub max_edges_per_document: usize,
148    /// Maximum retained directed edges, including edges to withdrawn sources.
149    pub max_edges: usize,
150}
151
152impl Default for GraphLimits {
153    fn default() -> Self {
154        Self {
155            max_documents: 100_000,
156            max_document_bytes: 262_144,
157            max_total_bytes: 256 * 1024 * 1024,
158            max_edges_per_document: 128,
159            max_edges: 1_000_000,
160        }
161    }
162}
163
164#[derive(Clone)]
165pub(crate) struct IndexedDocument {
166    pub slot: usize,
167    pub document: Document,
168    pub terms: BTreeMap<String, IndexedTerm>,
169    pub digest: String,
170    pub text_digest: String,
171    pub declarations: BTreeSet<String>,
172}
173
174#[derive(Clone)]
175pub(crate) struct IndexedTerm {
176    pub count: u8,
177    // None encodes the common line-zero occurrence (or no text occurrence when !in_text).
178    // Box only exceptional positions so every short-document term stays small and allocation-free.
179    positions: Option<Box<LinePosting>>,
180    in_text: bool,
181    pub in_source: bool,
182}
183
184#[derive(Clone)]
185enum LinePosting {
186    Single(usize),
187    Multiple(Vec<usize>),
188}
189
190impl LinePosting {
191    fn lines(&self) -> impl Iterator<Item = usize> + '_ {
192        let (single, multiple) = match self {
193            Self::Single(line) => (Some(*line), &[][..]),
194            Self::Multiple(lines) => (None, lines.as_slice()),
195        };
196        single.into_iter().chain(multiple.iter().copied())
197    }
198
199    fn intersects(&self, start: usize, end: usize) -> bool {
200        match self {
201            Self::Single(line) => *line >= start && *line <= end,
202            Self::Multiple(lines) => {
203                let index = lines.partition_point(|line| *line < start);
204                lines.get(index).is_some_and(|line| *line <= end)
205            }
206        }
207    }
208}
209
210impl IndexedTerm {
211    fn new() -> Self {
212        Self {
213            count: 0,
214            positions: None,
215            in_text: false,
216            in_source: false,
217        }
218    }
219
220    pub fn lines(&self) -> impl Iterator<Item = usize> + '_ {
221        (self.in_text && self.positions.is_none())
222            .then_some(0)
223            .into_iter()
224            .chain(self.positions.iter().flat_map(|posting| posting.lines()))
225    }
226
227    pub fn intersects(&self, start: usize, end: usize) -> bool {
228        self.positions
229            .as_ref()
230            .map_or(self.in_text && start == 0, |posting| {
231                posting.intersects(start, end)
232            })
233    }
234
235    fn add_line(&mut self, line: usize) {
236        match self.positions.as_deref_mut() {
237            Some(LinePosting::Multiple(lines)) => lines.push(line),
238            Some(posting @ LinePosting::Single(_)) => {
239                if let LinePosting::Single(first) = posting {
240                    *posting = LinePosting::Multiple(vec![*first, line]);
241                }
242            }
243            None if self.in_text => {
244                self.positions = Some(Box::new(LinePosting::Multiple(vec![0, line])))
245            }
246            None if line > 0 => self.positions = Some(Box::new(LinePosting::Single(line))),
247            None => {}
248        }
249        self.in_text = true;
250    }
251}
252
253/// Result of one atomic source replacement. An identical replacement does not advance revision.
254#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
255pub struct SourceUpdate {
256    /// New node IDs.
257    pub inserted: usize,
258    /// Existing node IDs whose document changed.
259    pub replaced: usize,
260    /// Obsolete node IDs withdrawn from this source.
261    pub removed: usize,
262    /// Identical documents retained.
263    pub unchanged: usize,
264    /// Graph revision after this transaction.
265    pub revision: u64,
266}
267
268/// An incrementally updated in-memory graph belonging to one caller-controlled privacy domain.
269pub struct ContextGraph {
270    pub(crate) domain: String,
271    pub(crate) limits: GraphLimits,
272    pub(crate) documents: BTreeMap<String, Arc<IndexedDocument>>,
273    // Reusable slots let broad queries accumulate exact scores without hashing source IDs.
274    // Slots never escape the graph or participate in a snapshot identity.
275    pub(crate) slots: Vec<Option<Arc<IndexedDocument>>>,
276    free_slots: Vec<usize>,
277    pub(crate) postings: BTreeMap<String, BTreeMap<Arc<str>, Posting>>,
278    pub(crate) edges: BTreeMap<String, BTreeSet<(EdgeKind, String)>>,
279    pub(crate) revision: u64,
280    pub(crate) sources: BTreeMap<String, BTreeSet<String>>,
281    bytes: usize,
282    edge_count: usize,
283}
284
285pub(crate) struct Posting {
286    pub slot: usize,
287    pub count: u8,
288}
289
290impl ContextGraph {
291    /// Enumerate the exact live authorization intersection in canonical ID order.
292    /// Sparse scopes use direct lookups; dense scopes merge the two ordered trees
293    /// instead of repeating O(log N) document lookups for every authorized ID.
294    /// This caches no authority or graph state and admits no absent/denied IDs.
295    pub(crate) fn authorized_documents<'a>(
296        &'a self,
297        ids: &'a BTreeSet<String>,
298    ) -> impl Iterator<Item = (&'a String, &'a Arc<IndexedDocument>)> {
299        let dense = ids.len() > self.documents.len() / 8;
300        let mut wanted = ids.iter().peekable();
301        let mut documents = self.documents.iter().peekable();
302        std::iter::from_fn(move || {
303            if !dense {
304                for id in wanted.by_ref() {
305                    if let Some(entry) = self.documents.get_key_value(id) {
306                        return Some(entry);
307                    }
308                }
309                return None;
310            }
311            loop {
312                let (id, _) = documents.peek()?;
313                let allowed = wanted.peek()?;
314                match id.as_str().cmp(allowed.as_str()) {
315                    std::cmp::Ordering::Less => {
316                        documents.next();
317                    }
318                    std::cmp::Ordering::Greater => {
319                        wanted.next();
320                    }
321                    std::cmp::Ordering::Equal => {
322                        wanted.next();
323                        return documents.next();
324                    }
325                }
326            }
327        })
328    }
329
330    /// Creates an empty graph. The domain must identify the application's privacy boundary.
331    pub fn new(domain: impl Into<String>, limits: GraphLimits) -> Result<Self, ContextError> {
332        let domain = domain.into();
333        if domain.is_empty()
334            || domain.len() > 256
335            || limits.max_documents == 0
336            || limits.max_document_bytes == 0
337            || limits.max_total_bytes == 0
338            || limits.max_edges_per_document == 0
339            || limits.max_edges == 0
340        {
341            return Err(ContextError::InvalidInput);
342        }
343        Ok(Self {
344            domain,
345            limits,
346            documents: BTreeMap::new(),
347            slots: Vec::new(),
348            free_slots: Vec::new(),
349            postings: BTreeMap::new(),
350            edges: BTreeMap::new(),
351            revision: 0,
352            sources: BTreeMap::new(),
353            bytes: 0,
354            edge_count: 0,
355        })
356    }
357
358    /// Number of live source documents.
359    #[must_use]
360    pub fn len(&self) -> usize {
361        self.documents.len()
362    }
363
364    /// Whether the graph has no live documents.
365    #[must_use]
366    pub fn is_empty(&self) -> bool {
367        self.documents.is_empty()
368    }
369
370    /// Current local mutation sequence. Identical upserts do not advance it.
371    #[must_use]
372    pub const fn revision(&self) -> u64 {
373        self.revision
374    }
375
376    /// Inserts or replaces one source and updates only its term postings. Returns whether changed.
377    pub fn upsert(&mut self, document: Document) -> Result<bool, ContextError> {
378        document.validate_shape()?;
379        let old = self.documents.get(&document.id);
380        if old.is_some_and(|value| value.document == document) {
381            return Ok(false);
382        }
383        let bytes = self
384            .bytes
385            .saturating_sub(old.map_or(0, |v| v.document.text.len()))
386            .checked_add(document.text.len())
387            .ok_or(ContextError::LimitExceeded)?;
388        if document.text.len() > self.limits.max_document_bytes
389            || bytes > self.limits.max_total_bytes
390            || (old.is_none() && self.len() >= self.limits.max_documents)
391        {
392            return Err(ContextError::LimitExceeded);
393        }
394        document.validate_bounds(self.limits.max_document_bytes)?;
395        let revision = self
396            .revision
397            .checked_add(1)
398            .ok_or(ContextError::LimitExceeded)?;
399        let content_digest = digest("cigar.document.v1", &document)?;
400        let text_digest = digest("cigar.document-text.v1", &document.text)?;
401        let declarations = declarations(&document.text);
402        let mut terms = BTreeMap::<String, IndexedTerm>::new();
403        for (line, text) in document.text.lines().enumerate() {
404            for (term, count) in term_counts(text) {
405                let value = terms.entry(term).or_insert_with(IndexedTerm::new);
406                value.count = (usize::from(value.count) + count.min(3)).min(3) as u8;
407                value.add_line(line);
408            }
409        }
410        for (term, count) in term_counts(&document.source) {
411            let value = terms.entry(term).or_insert_with(IndexedTerm::new);
412            value.count = (usize::from(value.count) + count.min(3)).min(3) as u8;
413            value.in_source = true;
414        }
415        self.unindex(&document.id);
416        self.index(IndexedDocument {
417            slot: 0,
418            document,
419            terms,
420            digest: content_digest,
421            text_digest,
422            declarations,
423        });
424        self.bytes = bytes;
425        self.revision = revision;
426        Ok(true)
427    }
428
429    /// Atomically replaces all documents with this exact source locator, withdrawing obsolete IDs.
430    /// Empty input withdraws the source. Every input must use this locator and a distinct ID; IDs
431    /// owned by another source are rejected. Validation/indexing completes before live mutation.
432    /// Existing edges remain, so references to withdrawn chunks continue to fail closed. This is
433    /// not automatic edge migration: callers repair semantic relations explicitly.
434    pub fn replace_source(
435        &mut self,
436        source: &str,
437        documents: Vec<Document>,
438    ) -> Result<SourceUpdate, ContextError> {
439        if source.is_empty() || source.len() > 2048 || source.chars().any(char::is_control) {
440            return Err(ContextError::InvalidInput);
441        }
442        if documents.len() > self.limits.max_documents {
443            return Err(ContextError::LimitExceeded);
444        }
445        let mut staged = Self::new(self.domain.clone(), self.limits)?;
446        let mut result = SourceUpdate::default();
447        let mut incoming = BTreeSet::new();
448        let mut retained = BTreeSet::new();
449        let mut incoming_bytes = 0_usize;
450        for document in documents {
451            if document.source != source || !incoming.insert(document.id.clone()) {
452                return Err(ContextError::InvalidInput);
453            }
454            incoming_bytes = incoming_bytes
455                .checked_add(document.text.len())
456                .ok_or(ContextError::LimitExceeded)?;
457            match self.documents.get(&document.id) {
458                Some(old) if old.document.source != source => {
459                    return Err(ContextError::InvalidInput);
460                }
461                Some(old) if old.document == document => {
462                    result.unchanged += 1;
463                    retained.insert(document.id);
464                    continue;
465                }
466                Some(_) => result.replaced += 1,
467                None => result.inserted += 1,
468            }
469            staged.upsert(document)?;
470        }
471        let old_ids = self.sources.get(source).cloned().unwrap_or_default();
472        result.removed = old_ids.iter().filter(|id| !incoming.contains(*id)).count();
473        if result.inserted + result.replaced + result.removed == 0 {
474            result.revision = self.revision;
475            return Ok(result);
476        }
477        let removed_bytes = old_ids
478            .iter()
479            .filter_map(|id| self.documents.get(id))
480            .map(|node| node.document.text.len())
481            .sum::<usize>();
482        let bytes = self
483            .bytes
484            .checked_sub(removed_bytes)
485            .and_then(|v| v.checked_add(incoming_bytes))
486            .ok_or(ContextError::LimitExceeded)?;
487        let count = self.len() - old_ids.len() + incoming.len();
488        if bytes > self.limits.max_total_bytes || count > self.limits.max_documents {
489            return Err(ContextError::LimitExceeded);
490        }
491        result.revision = self
492            .revision
493            .checked_add(1)
494            .ok_or(ContextError::LimitExceeded)?;
495        // No fallible operations after this point. The temporary index bounds staging work and
496        // leaves the live graph unchanged on all validation/limit failures.
497        for id in old_ids {
498            if !retained.contains(&id) {
499                self.unindex(&id);
500            }
501        }
502        // Release the staging slot references before moving its immutable nodes. Live slots
503        // are assigned here, so a staged ordinal cannot refer to an unrelated live document.
504        drop(staged.slots);
505        for (_, node) in staged.documents {
506            self.index(Arc::unwrap_or_clone(node));
507        }
508        self.bytes = bytes;
509        self.revision = result.revision;
510        Ok(result)
511    }
512
513    /// Withdraws a document. Incoming hard edges remain so dependents fail closed until repaired.
514    pub fn remove(&mut self, id: &str) -> Result<bool, ContextError> {
515        let Some(value) = self.documents.get(id) else {
516            return Ok(false);
517        };
518        let bytes = self.bytes.saturating_sub(value.document.text.len());
519        let revision = self
520            .revision
521            .checked_add(1)
522            .ok_or(ContextError::LimitExceeded)?;
523        self.unindex(id);
524        self.bytes = bytes;
525        self.revision = revision;
526        Ok(true)
527    }
528
529    /// Adds a typed edge. Both endpoints must exist. Contradiction links are symmetric and atomic.
530    pub fn link(&mut self, from: &str, to: &str, kind: EdgeKind) -> Result<bool, ContextError> {
531        if from == to || !self.documents.contains_key(from) || !self.documents.contains_key(to) {
532            return Err(ContextError::InvalidInput);
533        }
534        let mut additions = vec![(from, to)];
535        if kind == EdgeKind::Contradicts {
536            additions.push((to, from));
537        }
538        let changed = additions.iter().any(|(a, b)| {
539            !self
540                .edges
541                .get(*a)
542                .is_some_and(|edges| edges.contains(&(kind, (*b).to_owned())))
543        });
544        if !changed {
545            return Ok(false);
546        }
547        let added_count = additions
548            .iter()
549            .filter(|(a, b)| {
550                !self
551                    .edges
552                    .get(*a)
553                    .is_some_and(|edges| edges.contains(&(kind, (*b).to_owned())))
554            })
555            .count();
556        let edge_count = self
557            .edge_count
558            .checked_add(added_count)
559            .ok_or(ContextError::LimitExceeded)?;
560        if edge_count > self.limits.max_edges {
561            return Err(ContextError::LimitExceeded);
562        }
563        for (a, b) in &additions {
564            if self.edges.get(*a).is_some_and(|edges| {
565                edges.len() >= self.limits.max_edges_per_document
566                    && !edges.contains(&(kind, (*b).to_owned()))
567            }) {
568                return Err(ContextError::LimitExceeded);
569            }
570        }
571        let revision = self
572            .revision
573            .checked_add(1)
574            .ok_or(ContextError::LimitExceeded)?;
575        for (a, b) in additions {
576            self.edges
577                .entry(a.to_owned())
578                .or_default()
579                .insert((kind, b.to_owned()));
580        }
581        self.edge_count = edge_count;
582        self.revision = revision;
583        Ok(true)
584    }
585
586    /// Explicitly removes an edge, including both directions of a contradiction.
587    pub fn unlink(&mut self, from: &str, to: &str, kind: EdgeKind) -> Result<bool, ContextError> {
588        let present = self
589            .edges
590            .get(from)
591            .is_some_and(|e| e.contains(&(kind, to.to_owned())));
592        if !present {
593            return Ok(false);
594        }
595        let revision = self
596            .revision
597            .checked_add(1)
598            .ok_or(ContextError::LimitExceeded)?;
599        if let Some(edges) = self.edges.get_mut(from) {
600            if edges.remove(&(kind, to.to_owned())) {
601                self.edge_count -= 1;
602            }
603            if edges.is_empty() {
604                self.edges.remove(from);
605            }
606        }
607        if kind == EdgeKind::Contradicts
608            && let Some(edges) = self.edges.get_mut(to)
609        {
610            if edges.remove(&(kind, from.to_owned())) {
611                self.edge_count -= 1;
612            }
613            if edges.is_empty() {
614                self.edges.remove(to);
615            }
616        }
617        self.revision = revision;
618        Ok(true)
619    }
620
621    /// Restore validated relationships, including intentionally withdrawn endpoints. Only the
622    /// broker recovery path supplies the separate historical endpoint ownership checks.
623    #[cfg(feature = "broker")]
624    pub(crate) fn restore_relationships(
625        &mut self,
626        edges: BTreeMap<String, BTreeSet<(EdgeKind, String)>>,
627    ) -> Result<(), ContextError> {
628        let count = edges.values().try_fold(0_usize, |count, outgoing| {
629            count
630                .checked_add(outgoing.len())
631                .ok_or(ContextError::LimitExceeded)
632        })?;
633        if count > self.limits.max_edges
634            || edges
635                .values()
636                .any(|outgoing| outgoing.len() > self.limits.max_edges_per_document)
637        {
638            return Err(ContextError::LimitExceeded);
639        }
640        for (from, outgoing) in &edges {
641            if !valid_id(from) || outgoing.is_empty() {
642                return Err(ContextError::Integrity);
643            }
644            for (kind, to) in outgoing {
645                if !valid_id(to)
646                    || from == to
647                    || (*kind == EdgeKind::Contradicts
648                        && !edges
649                            .get(to)
650                            .is_some_and(|reverse| reverse.contains(&(*kind, from.clone()))))
651                {
652                    return Err(ContextError::Integrity);
653                }
654            }
655        }
656        self.edges = edges;
657        self.edge_count = count;
658        Ok(())
659    }
660
661    fn index(&mut self, mut node: IndexedDocument) {
662        let slot = self.free_slots.pop().unwrap_or(self.slots.len());
663        node.slot = slot;
664        let node = Arc::new(node);
665        let document = &node.document;
666        let posting_id: Arc<str> = Arc::from(document.id.as_str());
667        for (term, value) in &node.terms {
668            self.postings.entry(term.clone()).or_default().insert(
669                Arc::clone(&posting_id),
670                Posting {
671                    slot,
672                    count: value.count,
673                },
674            );
675        }
676        self.sources
677            .entry(document.source.clone())
678            .or_default()
679            .insert(document.id.clone());
680        self.documents
681            .insert(document.id.clone(), Arc::clone(&node));
682        if slot == self.slots.len() {
683            self.slots.push(Some(node));
684        } else if let Some(entry) = self.slots.get_mut(slot) {
685            *entry = Some(node);
686        }
687    }
688
689    fn unindex(&mut self, id: &str) {
690        if let Some(old) = self.documents.remove(id) {
691            if let Some(ids) = self.sources.get_mut(&old.document.source) {
692                ids.remove(id);
693                if ids.is_empty() {
694                    self.sources.remove(&old.document.source);
695                }
696            }
697            for term in old.terms.keys() {
698                if let Some(ids) = self.postings.get_mut(term) {
699                    ids.remove(id);
700                    if ids.is_empty() {
701                        self.postings.remove(term);
702                    }
703                }
704            }
705            if let Some(slot) = self.slots.get_mut(old.slot) {
706                *slot = None;
707                self.free_slots.push(old.slot);
708            }
709        }
710    }
711}
712
713pub(crate) fn valid_id(id: &str) -> bool {
714    !id.is_empty() && id.len() <= 128 && id.bytes().all(|b| b.is_ascii_graphic())
715}
716
717// Lexical relevance, not a parser or authority assertion. Prefer named declarations over
718// mentions. Applications requiring exact syntax should supply AST-aware chunks.
719fn declarations(text: &str) -> BTreeSet<String> {
720    let mut result = BTreeSet::new();
721    for line in text.lines() {
722        let tokens = line
723            .split(|ch: char| !ch.is_alphanumeric() && ch != '_')
724            .filter(|word| !word.is_empty())
725            .take(8)
726            .collect::<Vec<_>>();
727        for pair in tokens.windows(2) {
728            if pair.first().is_some_and(|word| {
729                [
730                    "fn",
731                    "def",
732                    "function",
733                    "class",
734                    "struct",
735                    "enum",
736                    "trait",
737                    "interface",
738                ]
739                .contains(word)
740            }) && let Some(name) = pair.get(1)
741            {
742                result.insert(name.to_lowercase());
743            }
744        }
745    }
746    result
747}
748
749pub(crate) fn term_counts(text: &str) -> BTreeMap<String, usize> {
750    let mut terms = BTreeMap::new();
751    // Keep complete technical identifiers as well as their searchable components. Splitting
752    // resolve_reference_tokenizer_target into only common words destroys its strongest signal.
753    for token in text.split(|ch: char| !ch.is_alphanumeric() && ch != '_') {
754        let camel = token
755            .chars()
756            .zip(token.chars().skip(1))
757            .any(|(a, b)| a.is_lowercase() && b.is_uppercase());
758        if token.len() >= 2 && (token.contains('_') || camel) {
759            *terms.entry(token.to_lowercase()).or_default() += 1;
760        }
761    }
762    let mut split = String::with_capacity(text.len());
763    let mut previous_lower = false;
764    for ch in text.chars() {
765        if previous_lower && ch.is_uppercase() {
766            split.push(' ');
767        }
768        split.push(ch);
769        previous_lower = ch.is_lowercase();
770    }
771    for term in split.split(|ch: char| !ch.is_alphanumeric()) {
772        if term.len() >= 2 {
773            *terms.entry(term.to_lowercase()).or_default() += 1;
774        }
775    }
776    terms
777}
778
779#[cfg(test)]
780mod authorization_iteration_tests {
781    use super::*;
782
783    #[test]
784    fn dense_and_sparse_intersections_preserve_exact_live_identity_order()
785    -> Result<(), ContextError> {
786        let mut graph = ContextGraph::new("authorized-iteration", GraphLimits::default())?;
787        for count in [0, 1, 7, 8, 16, 17, 128] {
788            graph.replace_source(
789                "docs",
790                (0..count)
791                    .map(|index| {
792                        Document::new(
793                            format!("id-{index:04}"),
794                            "docs",
795                            format!("document {index}"),
796                        )
797                    })
798                    .collect(),
799            )?;
800            for stride in [1, 2, 7, 16, 127] {
801                for extra in [false, true] {
802                    let mut ids = (0..=128)
803                        .step_by(stride)
804                        .map(|index| format!("id-{index:04}"))
805                        .collect::<BTreeSet<_>>();
806                    if extra {
807                        ids.extend([
808                            "before-all".into(),
809                            "id-0000-missing".into(),
810                            "zz-after-all".into(),
811                        ]);
812                    }
813                    // Independent legacy lookup oracle, including IDs before/between/after
814                    // current keys, empty graphs, withdrawal and both density branches.
815                    let expected = ids
816                        .iter()
817                        .filter_map(|id| graph.documents.get(id).map(|doc| (id, &doc.digest)))
818                        .collect::<Vec<_>>();
819                    let actual = graph
820                        .authorized_documents(&ids)
821                        .map(|(id, doc)| (id, &doc.digest))
822                        .collect::<Vec<_>>();
823                    assert_eq!(actual, expected);
824                    assert_eq!(
825                        crate::digest("comparison", &actual)?,
826                        crate::digest("comparison", &expected)?
827                    );
828                }
829            }
830            assert_eq!(graph.authorized_documents(&BTreeSet::new()).count(), 0);
831        }
832        let ids = BTreeSet::from(["id-0000".into()]);
833        let before = graph
834            .authorized_documents(&ids)
835            .map(|(_, doc)| doc.digest.clone())
836            .collect::<Vec<_>>();
837        graph.upsert(Document::new("id-0000", "docs", "replacement"))?;
838        let after = graph
839            .authorized_documents(&ids)
840            .map(|(_, doc)| doc.digest.clone())
841            .collect::<Vec<_>>();
842        assert_ne!(before, after);
843        graph.replace_source("docs", Vec::new())?;
844        assert_eq!(graph.authorized_documents(&ids).count(), 0);
845        Ok(())
846    }
847}