Skip to main content

qualia_core_db/inference/conditioning/
request_parts.rs

1//! Typed request parts and prioritized budget-bounded selection.
2//!
3//! Replaces blind byte-prefix truncation with prioritized selection across typed
4//! request components (required instructions, user prompt, tool schemas, evidence,
5//! and conversation history). Enforces that required instructions and the complete
6//! user prompt survive admission, or rejects with `ContextBudgetExceeded`.
7
8use super::spec::ConditioningError;
9
10/// Semantic category of a request part in the conditioning pipeline.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
12pub enum RequestPartKind {
13    /// Mandatory system instructions (never dropped, never truncated).
14    RequiredInstruction = 0,
15    /// User's core prompt / objective (never dropped, never truncated).
16    UserPrompt = 1,
17    /// Grounded conversational DAG thread (anchored fragments, branch links).
18    ChatGraphThread = 2,
19    /// Authorized tool definitions and schemas.
20    ToolSchema = 3,
21    /// Grounded evidence and citation context.
22    Evidence = 4,
23    /// Model deliberation scratchpad guidance or prior reasoning trace.
24    ThinkingScratchpad = 5,
25    /// Multimodal sensory descriptors (vision/audio/spatial token anchors).
26    MultimodalContext = 6,
27    /// Multi-turn linear conversation history (fallback ungrounded).
28    HistoryMessage = 7,
29}
30
31/// A borrowed typed part of an inference request.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct RequestPart<'a> {
34    pub kind: RequestPartKind,
35    pub content: &'a str,
36    pub source_id: Option<&'a str>,
37    pub qualifier: Option<&'a str>,
38    pub is_mandatory: bool,
39}
40
41impl<'a> RequestPart<'a> {
42    /// `RequestPart::required_instruction`.
43    pub const fn required_instruction(content: &'a str) -> Self {
44        Self {
45            kind: RequestPartKind::RequiredInstruction,
46            content,
47            source_id: None,
48            qualifier: None,
49            is_mandatory: true,
50        }
51    }
52
53    /// `RequestPart::user_prompt`.
54    pub const fn user_prompt(content: &'a str) -> Self {
55        Self {
56            kind: RequestPartKind::UserPrompt,
57            content,
58            source_id: None,
59            qualifier: None,
60            is_mandatory: true,
61        }
62    }
63
64    /// `RequestPart::tool_schema`.
65    pub const fn tool_schema(name: &'a str, schema: &'a str) -> Self {
66        Self {
67            kind: RequestPartKind::ToolSchema,
68            content: schema,
69            source_id: Some(name),
70            qualifier: None,
71            is_mandatory: false,
72        }
73    }
74
75    /// Grounded conversational DAG thread. `source_id` carries the target
76    /// fragment the user is replying to, when one exists.
77    pub const fn chat_graph(thread_content: &'a str, target_fragment_id: Option<&'a str>) -> Self {
78        Self {
79            kind: RequestPartKind::ChatGraphThread,
80            content: thread_content,
81            source_id: target_fragment_id,
82            qualifier: None,
83            is_mandatory: false,
84        }
85    }
86
87    /// Deliberation / reasoning scratchpad carried for thinking-model decode.
88    pub const fn thinking_scratchpad(scratchpad: &'a str) -> Self {
89        Self {
90            kind: RequestPartKind::ThinkingScratchpad,
91            content: scratchpad,
92            source_id: None,
93            qualifier: None,
94            is_mandatory: false,
95        }
96    }
97
98    /// Multimodal sensory descriptor (vision/audio/spatial token anchors).
99    pub const fn multimodal(modality_desc: &'a str, source: Option<&'a str>) -> Self {
100        Self {
101            kind: RequestPartKind::MultimodalContext,
102            content: modality_desc,
103            source_id: source,
104            qualifier: None,
105            is_mandatory: false,
106        }
107    }
108
109    /// `RequestPart::evidence`.
110    pub const fn evidence(
111        source_id: &'a str,
112        content: &'a str,
113        qualifier: Option<&'a str>,
114    ) -> Self {
115        Self {
116            kind: RequestPartKind::Evidence,
117            content,
118            source_id: Some(source_id),
119            qualifier,
120            is_mandatory: false,
121        }
122    }
123
124    /// `RequestPart::history`.
125    pub const fn history(content: &'a str) -> Self {
126        Self {
127            kind: RequestPartKind::HistoryMessage,
128            content,
129            source_id: None,
130            qualifier: None,
131            is_mandatory: false,
132        }
133    }
134
135    /// `byte` length.
136    pub fn byte_len(&self) -> usize {
137        self.content.len()
138    }
139}
140
141/// Select and pack request parts within a strict byte ceiling.
142///
143/// Guarantees:
144/// 1. All mandatory parts (RequiredInstruction, UserPrompt) MUST fit entirely;
145///    if the byte ceiling cannot accommodate them, returns `Err(ConditioningError::ContextBudgetExceeded)`.
146/// 2. Optional parts are admitted in order of priority
147///    (ChatGraphThread > ToolSchema > Evidence > ThinkingScratchpad >
148///    MultimodalContext > HistoryMessage). Grounded DAG context is therefore
149///    preserved while ungrounded linear history is pruned first.
150/// 3. Quoted evidence/tool outputs are NEVER promoted to instructions.
151pub fn select_prioritized_parts<'a>(
152    parts: &[RequestPart<'a>],
153    max_bytes: usize,
154    out: &mut [RequestPart<'a>],
155) -> Result<usize, ConditioningError> {
156    // Phase 1: Calculate mandatory byte total
157    let mandatory_bytes: usize = parts
158        .iter()
159        .filter(|p| p.is_mandatory)
160        .map(|p| p.byte_len())
161        .sum();
162
163    if mandatory_bytes > max_bytes {
164        return Err(ConditioningError::ContextBudgetExceeded);
165    }
166
167    let mut remaining_bytes = max_bytes - mandatory_bytes;
168    let mut selected_count = 0;
169
170    // Phase 2: Add mandatory parts first
171    for part in parts.iter().filter(|p| p.is_mandatory) {
172        if selected_count >= out.len() {
173            return Err(ConditioningError::OutputBufferFull);
174        }
175        out[selected_count] = *part;
176        selected_count += 1;
177    }
178
179    // Phase 3: Add optional parts by kind priority
180    let optional_kinds = [
181        RequestPartKind::ChatGraphThread,
182        RequestPartKind::ToolSchema,
183        RequestPartKind::Evidence,
184        RequestPartKind::ThinkingScratchpad,
185        RequestPartKind::MultimodalContext,
186        RequestPartKind::HistoryMessage,
187    ];
188
189    for kind in optional_kinds {
190        for part in parts.iter().filter(|p| !p.is_mandatory && p.kind == kind) {
191            let len = part.byte_len();
192            if len <= remaining_bytes {
193                if selected_count >= out.len() {
194                    return Err(ConditioningError::OutputBufferFull);
195                }
196                out[selected_count] = *part;
197                selected_count += 1;
198                remaining_bytes -= len;
199            }
200        }
201    }
202
203    Ok(selected_count)
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    #[test]
211    fn test_mandatory_instructions_and_prompt_survive() {
212        let req = RequestPart::required_instruction("SYSTEM: obey ethical laws.");
213        let user = RequestPart::user_prompt("USER: explain quantum mechanics.");
214        let ev = RequestPart::evidence("wiki", "Evidence text about atoms.", None);
215
216        let parts = [req, user, ev];
217        let mut out = [req; 4];
218
219        // Capacity large enough for all
220        let count = select_prioritized_parts(&parts, 200, &mut out).unwrap();
221        assert_eq!(count, 3);
222        assert_eq!(out[0].kind, RequestPartKind::RequiredInstruction);
223        assert_eq!(out[1].kind, RequestPartKind::UserPrompt);
224        assert_eq!(out[2].kind, RequestPartKind::Evidence);
225    }
226
227    #[test]
228    fn test_optional_evidence_dropped_when_budget_tight() {
229        let req = RequestPart::required_instruction("SYSTEM: adhere to safety.");
230        let user = RequestPart::user_prompt("USER: solve 2+2.");
231        let ev = RequestPart::evidence("doc1", "Extremely long evidence text...", None);
232
233        let parts = [req, user, ev];
234        let mut out = [req; 4];
235
236        let min_bytes = req.byte_len() + user.byte_len();
237        // Allow enough for mandatory, but not for evidence
238        let count = select_prioritized_parts(&parts, min_bytes + 5, &mut out).unwrap();
239        assert_eq!(count, 2);
240        assert_eq!(out[0].kind, RequestPartKind::RequiredInstruction);
241        assert_eq!(out[1].kind, RequestPartKind::UserPrompt);
242    }
243
244    #[test]
245    fn test_chat_graph_thread_outranks_ungrounded_history() {
246        let req = RequestPart::required_instruction("SYSTEM: rules.");
247        let user = RequestPart::user_prompt("USER: reply to the thread.");
248        let graph = RequestPart::chat_graph(
249            "[Chat graph thread context]\nfragment ab anchor=\"claim\"",
250            Some("ab"),
251        );
252        let hist = RequestPart::history("prior turn text that is ungrounded");
253
254        let parts = [req, user, graph, hist];
255        let mut out = [req; 8];
256
257        // Budget fits mandatory + chat-graph thread but not the flat history.
258        let cap = req.byte_len() + user.byte_len() + graph.byte_len();
259        let count = select_prioritized_parts(&parts, cap, &mut out).unwrap();
260        assert_eq!(count, 3);
261        assert_eq!(out[2].kind, RequestPartKind::ChatGraphThread);
262        assert_eq!(out[2].source_id, Some("ab"));
263        assert!(!out[..count]
264            .iter()
265            .any(|p| p.kind == RequestPartKind::HistoryMessage));
266    }
267
268    #[test]
269    fn test_thinking_and_multimodal_parts_admit_before_history() {
270        let req = RequestPart::required_instruction("S");
271        let user = RequestPart::user_prompt("U");
272        let think = RequestPart::thinking_scratchpad("prior <think> trace");
273        let mm = RequestPart::multimodal("image: 4x4 patch anchors", Some("img-1"));
274        let hist = RequestPart::history("older flat history");
275
276        let parts = [req, user, think, mm, hist];
277        let mut out = [req; 8];
278        let cap = req.byte_len() + user.byte_len() + think.byte_len() + mm.byte_len();
279        let count = select_prioritized_parts(&parts, cap, &mut out).unwrap();
280        assert_eq!(count, 4);
281        let kinds: Vec<RequestPartKind> = out[..count].iter().map(|p| p.kind).collect();
282        assert!(kinds.contains(&RequestPartKind::ThinkingScratchpad));
283        assert!(kinds.contains(&RequestPartKind::MultimodalContext));
284        assert!(!kinds.contains(&RequestPartKind::HistoryMessage));
285    }
286
287    #[test]
288    fn test_budget_exceeded_when_mandatory_cannot_fit() {
289        let req = RequestPart::required_instruction("SYSTEM: lengthy mandatory rule.");
290        let user = RequestPart::user_prompt("USER: lengthy prompt.");
291
292        let parts = [req, user];
293        let mut out = [req; 2];
294
295        // Less than mandatory byte total
296        let err = select_prioritized_parts(&parts, 10, &mut out);
297        assert_eq!(err, Err(ConditioningError::ContextBudgetExceeded));
298    }
299}