use crate::{ContextError, digest};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Document {
pub id: String,
pub source: String,
pub text: String,
#[serde(default = "first_line")]
pub start_line: usize,
}
const fn first_line() -> usize {
1
}
impl Document {
pub(crate) fn validate_shape(&self) -> Result<(), ContextError> {
if !valid_id(&self.id)
|| self.source.is_empty()
|| self.source.len() > 2048
|| self.source.chars().any(char::is_control)
|| self.text.trim().is_empty()
|| self.start_line == 0
{
return Err(ContextError::InvalidInput);
}
Ok(())
}
pub(crate) fn validate_bounds(&self, max_document_bytes: usize) -> Result<(), ContextError> {
if self.text.len() > max_document_bytes
|| self
.start_line
.checked_add(self.text.lines().count().saturating_sub(1))
.is_none()
{
return Err(ContextError::LimitExceeded);
}
Ok(())
}
pub fn new(id: impl Into<String>, source: impl Into<String>, text: impl Into<String>) -> Self {
Self {
id: id.into(),
source: source.into(),
text: text.into(),
start_line: 1,
}
}
pub fn chunks(
&self,
max_lines: usize,
overlap_lines: usize,
) -> Result<Vec<Self>, ContextError> {
if max_lines == 0
|| overlap_lines >= max_lines
|| !valid_id(&self.id)
|| self.id.len() > 100
|| self.start_line == 0
|| self.text.trim().is_empty()
{
return Err(ContextError::InvalidInput);
}
if self.text.len() > 16_777_216 {
return Err(ContextError::LimitExceeded);
}
let lines = self.text.split_inclusive('\n').collect::<Vec<_>>();
let mut chunks = Vec::new();
let mut start = 0;
while start < lines.len() {
let end = start.saturating_add(max_lines).min(lines.len());
let text = lines
.get(start..end)
.ok_or(ContextError::Integrity)?
.concat();
if !text.trim().is_empty() {
if chunks.len() >= 4096 {
return Err(ContextError::LimitExceeded);
}
let start_line = self
.start_line
.checked_add(start)
.ok_or(ContextError::LimitExceeded)?;
chunks.push(Self {
id: format!("{}:L{start_line}", self.id),
source: self.source.clone(),
text,
start_line,
});
}
if end == lines.len() {
break;
}
start = end - overlap_lines;
}
Ok(chunks)
}
}
impl std::fmt::Debug for Document {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Document")
.field("bytes", &self.text.len())
.finish_non_exhaustive()
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EdgeKind {
Requires,
Contradicts,
Supports,
Related,
}
#[derive(Clone, Copy, Debug)]
pub struct GraphLimits {
pub max_documents: usize,
pub max_document_bytes: usize,
pub max_total_bytes: usize,
pub max_edges_per_document: usize,
pub max_edges: usize,
}
impl Default for GraphLimits {
fn default() -> Self {
Self {
max_documents: 100_000,
max_document_bytes: 262_144,
max_total_bytes: 256 * 1024 * 1024,
max_edges_per_document: 128,
max_edges: 1_000_000,
}
}
}
#[derive(Clone)]
pub(crate) struct IndexedDocument {
pub slot: usize,
pub document: Document,
pub terms: BTreeMap<String, IndexedTerm>,
pub digest: String,
pub text_digest: String,
pub declarations: BTreeSet<String>,
}
#[derive(Clone)]
pub(crate) struct IndexedTerm {
pub count: u8,
positions: Option<Box<LinePosting>>,
in_text: bool,
pub in_source: bool,
}
#[derive(Clone)]
enum LinePosting {
Single(usize),
Multiple(Vec<usize>),
}
impl LinePosting {
fn lines(&self) -> impl Iterator<Item = usize> + '_ {
let (single, multiple) = match self {
Self::Single(line) => (Some(*line), &[][..]),
Self::Multiple(lines) => (None, lines.as_slice()),
};
single.into_iter().chain(multiple.iter().copied())
}
fn intersects(&self, start: usize, end: usize) -> bool {
match self {
Self::Single(line) => *line >= start && *line <= end,
Self::Multiple(lines) => {
let index = lines.partition_point(|line| *line < start);
lines.get(index).is_some_and(|line| *line <= end)
}
}
}
}
impl IndexedTerm {
fn new() -> Self {
Self {
count: 0,
positions: None,
in_text: false,
in_source: false,
}
}
pub fn lines(&self) -> impl Iterator<Item = usize> + '_ {
(self.in_text && self.positions.is_none())
.then_some(0)
.into_iter()
.chain(self.positions.iter().flat_map(|posting| posting.lines()))
}
pub fn intersects(&self, start: usize, end: usize) -> bool {
self.positions
.as_ref()
.map_or(self.in_text && start == 0, |posting| {
posting.intersects(start, end)
})
}
fn add_line(&mut self, line: usize) {
match self.positions.as_deref_mut() {
Some(LinePosting::Multiple(lines)) => lines.push(line),
Some(posting @ LinePosting::Single(_)) => {
if let LinePosting::Single(first) = posting {
*posting = LinePosting::Multiple(vec![*first, line]);
}
}
None if self.in_text => {
self.positions = Some(Box::new(LinePosting::Multiple(vec![0, line])))
}
None if line > 0 => self.positions = Some(Box::new(LinePosting::Single(line))),
None => {}
}
self.in_text = true;
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct SourceUpdate {
pub inserted: usize,
pub replaced: usize,
pub removed: usize,
pub unchanged: usize,
pub revision: u64,
}
pub struct ContextGraph {
pub(crate) domain: String,
pub(crate) limits: GraphLimits,
pub(crate) documents: BTreeMap<String, Arc<IndexedDocument>>,
pub(crate) slots: Vec<Option<Arc<IndexedDocument>>>,
free_slots: Vec<usize>,
pub(crate) postings: BTreeMap<String, BTreeMap<Arc<str>, Posting>>,
pub(crate) edges: BTreeMap<String, BTreeSet<(EdgeKind, String)>>,
pub(crate) revision: u64,
pub(crate) sources: BTreeMap<String, BTreeSet<String>>,
bytes: usize,
edge_count: usize,
}
pub(crate) struct Posting {
pub slot: usize,
pub count: u8,
}
impl ContextGraph {
pub(crate) fn authorized_documents<'a>(
&'a self,
ids: &'a BTreeSet<String>,
) -> impl Iterator<Item = (&'a String, &'a Arc<IndexedDocument>)> {
let dense = ids.len() > self.documents.len() / 8;
let mut wanted = ids.iter().peekable();
let mut documents = self.documents.iter().peekable();
std::iter::from_fn(move || {
if !dense {
for id in wanted.by_ref() {
if let Some(entry) = self.documents.get_key_value(id) {
return Some(entry);
}
}
return None;
}
loop {
let (id, _) = documents.peek()?;
let allowed = wanted.peek()?;
match id.as_str().cmp(allowed.as_str()) {
std::cmp::Ordering::Less => {
documents.next();
}
std::cmp::Ordering::Greater => {
wanted.next();
}
std::cmp::Ordering::Equal => {
wanted.next();
return documents.next();
}
}
}
})
}
pub fn new(domain: impl Into<String>, limits: GraphLimits) -> Result<Self, ContextError> {
let domain = domain.into();
if domain.is_empty()
|| domain.len() > 256
|| limits.max_documents == 0
|| limits.max_document_bytes == 0
|| limits.max_total_bytes == 0
|| limits.max_edges_per_document == 0
|| limits.max_edges == 0
{
return Err(ContextError::InvalidInput);
}
Ok(Self {
domain,
limits,
documents: BTreeMap::new(),
slots: Vec::new(),
free_slots: Vec::new(),
postings: BTreeMap::new(),
edges: BTreeMap::new(),
revision: 0,
sources: BTreeMap::new(),
bytes: 0,
edge_count: 0,
})
}
#[must_use]
pub fn len(&self) -> usize {
self.documents.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.documents.is_empty()
}
#[must_use]
pub const fn revision(&self) -> u64 {
self.revision
}
pub fn upsert(&mut self, document: Document) -> Result<bool, ContextError> {
document.validate_shape()?;
let old = self.documents.get(&document.id);
if old.is_some_and(|value| value.document == document) {
return Ok(false);
}
let bytes = self
.bytes
.saturating_sub(old.map_or(0, |v| v.document.text.len()))
.checked_add(document.text.len())
.ok_or(ContextError::LimitExceeded)?;
if document.text.len() > self.limits.max_document_bytes
|| bytes > self.limits.max_total_bytes
|| (old.is_none() && self.len() >= self.limits.max_documents)
{
return Err(ContextError::LimitExceeded);
}
document.validate_bounds(self.limits.max_document_bytes)?;
let revision = self
.revision
.checked_add(1)
.ok_or(ContextError::LimitExceeded)?;
let content_digest = digest("cigar.document.v1", &document)?;
let text_digest = digest("cigar.document-text.v1", &document.text)?;
let declarations = declarations(&document.text);
let mut terms = BTreeMap::<String, IndexedTerm>::new();
for (line, text) in document.text.lines().enumerate() {
for (term, count) in term_counts(text) {
let value = terms.entry(term).or_insert_with(IndexedTerm::new);
value.count = (usize::from(value.count) + count.min(3)).min(3) as u8;
value.add_line(line);
}
}
for (term, count) in term_counts(&document.source) {
let value = terms.entry(term).or_insert_with(IndexedTerm::new);
value.count = (usize::from(value.count) + count.min(3)).min(3) as u8;
value.in_source = true;
}
self.unindex(&document.id);
self.index(IndexedDocument {
slot: 0,
document,
terms,
digest: content_digest,
text_digest,
declarations,
});
self.bytes = bytes;
self.revision = revision;
Ok(true)
}
pub fn replace_source(
&mut self,
source: &str,
documents: Vec<Document>,
) -> Result<SourceUpdate, ContextError> {
if source.is_empty() || source.len() > 2048 || source.chars().any(char::is_control) {
return Err(ContextError::InvalidInput);
}
if documents.len() > self.limits.max_documents {
return Err(ContextError::LimitExceeded);
}
let mut staged = Self::new(self.domain.clone(), self.limits)?;
let mut result = SourceUpdate::default();
let mut incoming = BTreeSet::new();
let mut retained = BTreeSet::new();
let mut incoming_bytes = 0_usize;
for document in documents {
if document.source != source || !incoming.insert(document.id.clone()) {
return Err(ContextError::InvalidInput);
}
incoming_bytes = incoming_bytes
.checked_add(document.text.len())
.ok_or(ContextError::LimitExceeded)?;
match self.documents.get(&document.id) {
Some(old) if old.document.source != source => {
return Err(ContextError::InvalidInput);
}
Some(old) if old.document == document => {
result.unchanged += 1;
retained.insert(document.id);
continue;
}
Some(_) => result.replaced += 1,
None => result.inserted += 1,
}
staged.upsert(document)?;
}
let old_ids = self.sources.get(source).cloned().unwrap_or_default();
result.removed = old_ids.iter().filter(|id| !incoming.contains(*id)).count();
if result.inserted + result.replaced + result.removed == 0 {
result.revision = self.revision;
return Ok(result);
}
let removed_bytes = old_ids
.iter()
.filter_map(|id| self.documents.get(id))
.map(|node| node.document.text.len())
.sum::<usize>();
let bytes = self
.bytes
.checked_sub(removed_bytes)
.and_then(|v| v.checked_add(incoming_bytes))
.ok_or(ContextError::LimitExceeded)?;
let count = self.len() - old_ids.len() + incoming.len();
if bytes > self.limits.max_total_bytes || count > self.limits.max_documents {
return Err(ContextError::LimitExceeded);
}
result.revision = self
.revision
.checked_add(1)
.ok_or(ContextError::LimitExceeded)?;
for id in old_ids {
if !retained.contains(&id) {
self.unindex(&id);
}
}
drop(staged.slots);
for (_, node) in staged.documents {
self.index(Arc::unwrap_or_clone(node));
}
self.bytes = bytes;
self.revision = result.revision;
Ok(result)
}
pub fn remove(&mut self, id: &str) -> Result<bool, ContextError> {
let Some(value) = self.documents.get(id) else {
return Ok(false);
};
let bytes = self.bytes.saturating_sub(value.document.text.len());
let revision = self
.revision
.checked_add(1)
.ok_or(ContextError::LimitExceeded)?;
self.unindex(id);
self.bytes = bytes;
self.revision = revision;
Ok(true)
}
pub fn link(&mut self, from: &str, to: &str, kind: EdgeKind) -> Result<bool, ContextError> {
if from == to || !self.documents.contains_key(from) || !self.documents.contains_key(to) {
return Err(ContextError::InvalidInput);
}
let mut additions = vec![(from, to)];
if kind == EdgeKind::Contradicts {
additions.push((to, from));
}
let changed = additions.iter().any(|(a, b)| {
!self
.edges
.get(*a)
.is_some_and(|edges| edges.contains(&(kind, (*b).to_owned())))
});
if !changed {
return Ok(false);
}
let added_count = additions
.iter()
.filter(|(a, b)| {
!self
.edges
.get(*a)
.is_some_and(|edges| edges.contains(&(kind, (*b).to_owned())))
})
.count();
let edge_count = self
.edge_count
.checked_add(added_count)
.ok_or(ContextError::LimitExceeded)?;
if edge_count > self.limits.max_edges {
return Err(ContextError::LimitExceeded);
}
for (a, b) in &additions {
if self.edges.get(*a).is_some_and(|edges| {
edges.len() >= self.limits.max_edges_per_document
&& !edges.contains(&(kind, (*b).to_owned()))
}) {
return Err(ContextError::LimitExceeded);
}
}
let revision = self
.revision
.checked_add(1)
.ok_or(ContextError::LimitExceeded)?;
for (a, b) in additions {
self.edges
.entry(a.to_owned())
.or_default()
.insert((kind, b.to_owned()));
}
self.edge_count = edge_count;
self.revision = revision;
Ok(true)
}
pub fn unlink(&mut self, from: &str, to: &str, kind: EdgeKind) -> Result<bool, ContextError> {
let present = self
.edges
.get(from)
.is_some_and(|e| e.contains(&(kind, to.to_owned())));
if !present {
return Ok(false);
}
let revision = self
.revision
.checked_add(1)
.ok_or(ContextError::LimitExceeded)?;
if let Some(edges) = self.edges.get_mut(from) {
if edges.remove(&(kind, to.to_owned())) {
self.edge_count -= 1;
}
if edges.is_empty() {
self.edges.remove(from);
}
}
if kind == EdgeKind::Contradicts
&& let Some(edges) = self.edges.get_mut(to)
{
if edges.remove(&(kind, from.to_owned())) {
self.edge_count -= 1;
}
if edges.is_empty() {
self.edges.remove(to);
}
}
self.revision = revision;
Ok(true)
}
#[cfg(feature = "broker")]
pub(crate) fn restore_relationships(
&mut self,
edges: BTreeMap<String, BTreeSet<(EdgeKind, String)>>,
) -> Result<(), ContextError> {
let count = edges.values().try_fold(0_usize, |count, outgoing| {
count
.checked_add(outgoing.len())
.ok_or(ContextError::LimitExceeded)
})?;
if count > self.limits.max_edges
|| edges
.values()
.any(|outgoing| outgoing.len() > self.limits.max_edges_per_document)
{
return Err(ContextError::LimitExceeded);
}
for (from, outgoing) in &edges {
if !valid_id(from) || outgoing.is_empty() {
return Err(ContextError::Integrity);
}
for (kind, to) in outgoing {
if !valid_id(to)
|| from == to
|| (*kind == EdgeKind::Contradicts
&& !edges
.get(to)
.is_some_and(|reverse| reverse.contains(&(*kind, from.clone()))))
{
return Err(ContextError::Integrity);
}
}
}
self.edges = edges;
self.edge_count = count;
Ok(())
}
fn index(&mut self, mut node: IndexedDocument) {
let slot = self.free_slots.pop().unwrap_or(self.slots.len());
node.slot = slot;
let node = Arc::new(node);
let document = &node.document;
let posting_id: Arc<str> = Arc::from(document.id.as_str());
for (term, value) in &node.terms {
self.postings.entry(term.clone()).or_default().insert(
Arc::clone(&posting_id),
Posting {
slot,
count: value.count,
},
);
}
self.sources
.entry(document.source.clone())
.or_default()
.insert(document.id.clone());
self.documents
.insert(document.id.clone(), Arc::clone(&node));
if slot == self.slots.len() {
self.slots.push(Some(node));
} else if let Some(entry) = self.slots.get_mut(slot) {
*entry = Some(node);
}
}
fn unindex(&mut self, id: &str) {
if let Some(old) = self.documents.remove(id) {
if let Some(ids) = self.sources.get_mut(&old.document.source) {
ids.remove(id);
if ids.is_empty() {
self.sources.remove(&old.document.source);
}
}
for term in old.terms.keys() {
if let Some(ids) = self.postings.get_mut(term) {
ids.remove(id);
if ids.is_empty() {
self.postings.remove(term);
}
}
}
if let Some(slot) = self.slots.get_mut(old.slot) {
*slot = None;
self.free_slots.push(old.slot);
}
}
}
}
pub(crate) fn valid_id(id: &str) -> bool {
!id.is_empty() && id.len() <= 128 && id.bytes().all(|b| b.is_ascii_graphic())
}
fn declarations(text: &str) -> BTreeSet<String> {
let mut result = BTreeSet::new();
for line in text.lines() {
let tokens = line
.split(|ch: char| !ch.is_alphanumeric() && ch != '_')
.filter(|word| !word.is_empty())
.take(8)
.collect::<Vec<_>>();
for pair in tokens.windows(2) {
if pair.first().is_some_and(|word| {
[
"fn",
"def",
"function",
"class",
"struct",
"enum",
"trait",
"interface",
]
.contains(word)
}) && let Some(name) = pair.get(1)
{
result.insert(name.to_lowercase());
}
}
}
result
}
pub(crate) fn term_counts(text: &str) -> BTreeMap<String, usize> {
let mut terms = BTreeMap::new();
for token in text.split(|ch: char| !ch.is_alphanumeric() && ch != '_') {
let camel = token
.chars()
.zip(token.chars().skip(1))
.any(|(a, b)| a.is_lowercase() && b.is_uppercase());
if token.len() >= 2 && (token.contains('_') || camel) {
*terms.entry(token.to_lowercase()).or_default() += 1;
}
}
let mut split = String::with_capacity(text.len());
let mut previous_lower = false;
for ch in text.chars() {
if previous_lower && ch.is_uppercase() {
split.push(' ');
}
split.push(ch);
previous_lower = ch.is_lowercase();
}
for term in split.split(|ch: char| !ch.is_alphanumeric()) {
if term.len() >= 2 {
*terms.entry(term.to_lowercase()).or_default() += 1;
}
}
terms
}
#[cfg(test)]
mod authorization_iteration_tests {
use super::*;
#[test]
fn dense_and_sparse_intersections_preserve_exact_live_identity_order()
-> Result<(), ContextError> {
let mut graph = ContextGraph::new("authorized-iteration", GraphLimits::default())?;
for count in [0, 1, 7, 8, 16, 17, 128] {
graph.replace_source(
"docs",
(0..count)
.map(|index| {
Document::new(
format!("id-{index:04}"),
"docs",
format!("document {index}"),
)
})
.collect(),
)?;
for stride in [1, 2, 7, 16, 127] {
for extra in [false, true] {
let mut ids = (0..=128)
.step_by(stride)
.map(|index| format!("id-{index:04}"))
.collect::<BTreeSet<_>>();
if extra {
ids.extend([
"before-all".into(),
"id-0000-missing".into(),
"zz-after-all".into(),
]);
}
let expected = ids
.iter()
.filter_map(|id| graph.documents.get(id).map(|doc| (id, &doc.digest)))
.collect::<Vec<_>>();
let actual = graph
.authorized_documents(&ids)
.map(|(id, doc)| (id, &doc.digest))
.collect::<Vec<_>>();
assert_eq!(actual, expected);
assert_eq!(
crate::digest("comparison", &actual)?,
crate::digest("comparison", &expected)?
);
}
}
assert_eq!(graph.authorized_documents(&BTreeSet::new()).count(), 0);
}
let ids = BTreeSet::from(["id-0000".into()]);
let before = graph
.authorized_documents(&ids)
.map(|(_, doc)| doc.digest.clone())
.collect::<Vec<_>>();
graph.upsert(Document::new("id-0000", "docs", "replacement"))?;
let after = graph
.authorized_documents(&ids)
.map(|(_, doc)| doc.digest.clone())
.collect::<Vec<_>>();
assert_ne!(before, after);
graph.replace_source("docs", Vec::new())?;
assert_eq!(graph.authorized_documents(&ids).count(), 0);
Ok(())
}
}