reddb-io-server 1.46.4

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
Documentation
//! Bounded, immutable ASK continuations local to this database runtime.
use super::statement_frame::EffectiveScope;
use crate::api::{RedDBError, RedDBResult};
use crate::auth::{Role, UserId};
use crate::crypto::Uuid;
use lru::LruCache;
use parking_lot::Mutex;
use std::num::NonZeroUsize;

const MAX_TURNS: usize = 8;
const MAX_QUESTION_BYTES: usize = 4096;
const MAX_CONTINUATIONS: usize = 256;

#[derive(Clone, PartialEq, Eq)]
struct Owner {
    principal: Option<UserId>,
    identity: Option<(String, Role)>,
    tenant: Option<String>,
}

#[derive(Clone)]
pub(super) struct History {
    owner: Owner,
    questions: Vec<String>,
}

pub(super) struct AskThreads(Mutex<LruCache<String, History>>);

impl Default for AskThreads {
    fn default() -> Self {
        Self(Mutex::new(LruCache::new(
            NonZeroUsize::new(MAX_CONTINUATIONS).unwrap(),
        )))
    }
}

impl AskThreads {
    pub(super) fn open(
        &self,
        token: &str,
        scope: &EffectiveScope,
        question: &str,
    ) -> RedDBResult<History> {
        if question.len() > MAX_QUESTION_BYTES {
            return Err(RedDBError::Query(
                "ASK thread question exceeds 4096 bytes".into(),
            ));
        }
        let owner = Owner {
            principal: scope.auth_principal.clone(),
            identity: scope.identity.clone(),
            tenant: scope.tenant.clone(),
        };
        if token == "new" {
            return Ok(History {
                owner,
                questions: Vec::new(),
            });
        }
        let mut entries = self.0.lock();
        if token.len() == 36
            && entries
                .peek(token)
                .is_some_and(|history| history.owner == owner)
        {
            return Ok(entries.get(token).unwrap().clone());
        }
        Err(RedDBError::Query(
            "ASK conversation unavailable for this session; start a new conversation".into(),
        ))
    }

    pub(super) fn finish(&self, mut history: History, question: &str) -> String {
        if history.questions.len() == MAX_TURNS {
            history.questions.remove(0);
        }
        history.questions.push(question.to_owned());
        let token = Uuid::new_v4().to_string();
        self.0.lock().put(token.clone(), history);
        token
    }
}

impl History {
    pub(super) fn prompt(&self, question: &str) -> String {
        if self.questions.is_empty() {
            return question.to_owned();
        }
        // Re-read evidence with the current grants. Only user-supplied questions
        // survive a turn, never previous rows, model output or tool results.
        use crate::json::Value;
        let previous = self.questions.iter().cloned().map(Value::String).collect();
        Value::Object(
            [
                ("previous_user_questions".into(), Value::Array(previous)),
                (
                    "current_question".into(),
                    Value::String(question.to_owned()),
                ),
            ]
            .into_iter()
            .collect(),
        )
        .to_string_compact()
    }
}