返回 CodeWhale
turn.rs
根目录 / crates / engine / src / rlm / turn.rs
1 //! Pure RLM result and feedback facts. The canonical Engine owns every model
2 //! request, code round, cancellation, session message and permission settlement.
3 use codewhale_models::{ContentBlock, Message, Role, Usage};
4 use std::time::Duration;
5
6 pub const STDOUT_METADATA_PREVIEW_LEN: usize = 800;
7 const PROMPT_PREVIEW_LEN: usize = 500;
8
9 /// How an RLM turn ended.
10 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
11 pub enum RlmTermination {
12 /// `FINAL(value)` was called inside the REPL or `FINAL(...)` appeared
13 /// at the top of the model's response on its own line.
14 Final,
15 /// The model failed to emit a `repl` block for too many rounds in a
16 /// row. The accumulated last response text is surfaced as the answer
17 /// rather than being thrown away.
18 NoCode,
19 /// Iteration cap reached without `FINAL`. The last root response is
20 /// surfaced as the answer alongside the error.
21 Exhausted,
22 /// Hard error — LLM call failed, REPL crashed, timeout.
23 Error,
24 }
25
26 /// Per-round trace entry. Surfaced in the tool result so the user can see
27 /// exactly what the sub-agent did.
28 #[derive(Debug, Clone)]
29 pub struct RlmRoundTrace {
30 pub round: u32,
31 pub code_summary: String,
32 pub stdout_preview: String,
33 pub had_error: bool,
34 pub rpc_count: u32,
35 pub elapsed_ms: u64,
36 }
37
38 /// Result of an RLM turn.
39 #[derive(Debug, Clone)]
40 pub struct RlmTurnResult {
41 pub answer: String,
42 pub iterations: u32,
43 pub duration: Duration,
44 pub error: Option<String>,
45 pub usage: Usage,
46 /// One exact frozen route/quote receipt per admitted provider request.
47 /// Distinct calls are never coalesced, even when they share a route.
48 pub routed_usage: Vec<crate::cost_status::RuntimeUsageRecord>,
49 /// Exact routes for provider-success responses that omitted authoritative
50 /// usage metadata.
51 pub routed_usage_drop_records: Vec<crate::cost_status::RuntimeUsageDropRecord>,
52 pub routed_usage_dropped_records: u64,
53 pub termination: RlmTermination,
54 /// Per-round trace. Empty when the loop never reached the REPL.
55 pub trace: Vec<RlmRoundTrace>,
56 /// Total sub-LLM RPCs made by the sub-agent (sum of `rpc_count` across
57 /// rounds). Useful for verifying that the model engaged with `context`
58 /// rather than answering directly.
59 pub total_rpcs: u32,
60 }
61
62 impl RlmTurnResult {
63 pub fn failed(error: String, duration: Duration) -> Self {
64 Self {
65 answer: String::new(),
66 iterations: 0,
67 duration,
68 error: Some(error),
69 usage: Usage::default(),
70 routed_usage: Vec::new(),
71 routed_usage_drop_records: Vec::new(),
72 routed_usage_dropped_records: 0,
73 termination: RlmTermination::Error,
74 trace: Vec::new(),
75 total_rpcs: 0,
76 }
77 }
78 pub fn require_answer_or_error(mut self) -> Self {
79 if self.termination != RlmTermination::Final
80 && self.answer.trim().is_empty()
81 && self.error.is_none()
82 {
83 self.error = Some(format!(
84 "RLM ended ({:?}) after {} iteration(s) with an empty answer",
85 self.termination, self.iterations
86 ));
87 }
88 self
89 }
90 }
91
92 pub fn metadata_text(
93 prompt: &str,
94 iteration: u32,
95 code: Option<&str>,
96 stdout: Option<&str>,
97 ) -> String {
98 extract_text_blocks(&build_metadata_message(prompt, None, iteration, code, stdout).content)
99 }
100
101 fn build_metadata_message(
102 prompt: &str,
103 root_prompt: Option<&str>,
104 iteration: u32,
105 previous_code: Option<&str>,
106 previous_stdout: Option<&str>,
107 ) -> Message {
108 let prompt_len = prompt.chars().count();
109 let prompt_preview = truncate_text(prompt, PROMPT_PREVIEW_LEN);
110
111 let mut parts = Vec::new();
112 parts.push(format!("## REPL state (round {iteration})"));
113 parts.push(String::new());
114 if let Some(rp) = root_prompt
115 && !rp.trim().is_empty()
116 {
117 parts.push("**Original task** (re-shown every round)".to_string());
118 parts.push(format!("> {}", truncate_text(rp.trim(), 600)));
119 parts.push(String::new());
120 }
121 parts.push("**`_context`** — the long input lives in the REPL only".to_string());
122 parts.push(format!("- Length: {prompt_len} chars"));
123 parts.push(format!("- Preview: \"{prompt_preview}\""));
124 parts.push(String::new());
125
126 parts.push("**REPL helpers** (use inside ```repl blocks)".to_string());
127 parts.push(
128 "- `_context` / `_ctx` / `content` — the full input string"
129 .to_string(),
130 );
131 parts.push(
132 "- `len(_context)` / `_context[a:b]` / `_context.splitlines()` — slice it".to_string(),
133 );
134 parts.push(
135 "- `chunk(max_chars=20000, overlap=0)` — full-coverage chunks with index/start/end/text"
136 .to_string(),
137 );
138 parts.push(
139 "- `chunk_coverage(chunks)` — coverage report for chunk output".to_string(),
140 );
141 parts.push(
142 "- `llm_query(prompt, model=None)` — one-shot child LLM; `model` is ignored and child calls keep the captured Core route"
143 .to_string(),
144 );
145 parts.push(
146 "- `llm_query_batched([p1, p2, ...], dependency_mode=\"independent\")` — concurrent fan-out for independent prompts only; `model` is ignored"
147 .to_string(),
148 );
149 parts.push(
150 "- `rlm_query(prompt, model=None)` — recursive sub-RLM; `model` is ignored"
151 .to_string(),
152 );
153 parts.push(
154 "- `rlm_query_batched([p1, p2, ...], dependency_mode=\"independent\")` — concurrent recursive sub-RLMs for independent prompts only; `model` is ignored"
155 .to_string(),
156 );
157 parts.push(
158 "- `sub_query_sequence(prompt, slices)` — sequential child calls for A->B dependencies and rollback-sensitive work"
159 .to_string(),
160 );
161 parts.push(
162 "- Batch safety: never batch dependent steps, global-state refactors, schema migrations, or rollback-sensitive tasks"
163 .to_string(),
164 );
165 parts.push("- `SHOW_VARS()` — list user variables".to_string());
166 parts.push("- `repl_set(name, value)` / `repl_get(name)` — explicit store".to_string());
167 parts.push(
168 "- `FINAL(value)` — end the loop with this answer".to_string(),
169 );
170 parts.push(
171 "- `FINAL_VAR(name)` — end the loop with a variable's value"
172 .to_string(),
173 );
174 parts.push(String::new());
175
176 if iteration > 0 {
177 parts.push("**Previous round**".to_string());
178 if let Some(code) = previous_code {
179 parts.push(format!("- Code: {}", summarize_code(code)));
180 }
181 if let Some(stdout) = previous_stdout {
182 let stdout_clean = stdout.trim();
183 if !stdout_clean.is_empty() {
184 parts.push(format!("- Stdout preview: \"{stdout_clean}\""));
185 } else {
186 parts.push("- Stdout: (empty)".to_string());
187 }
188 }
189 }
190
191 let text = parts.join("\n");
192
193 Message {
194 role: Role::User,
195 content: vec![ContentBlock::Text {
196 text,
197 cache_control: None,
198 }],
199 }
200 }
201
202 pub fn summarize_code(code: &str) -> String {
203 let lines: Vec<&str> = code.lines().collect();
204 if lines.len() <= 8 {
205 return code.to_string();
206 }
207 let head = lines[..4].join("\n");
208 let tail = lines[lines.len() - 4..].join("\n");
209 format!("{} lines:\n{head}\n…\n{tail}", lines.len())
210 }
211
212 fn extract_text_blocks(blocks: &[ContentBlock]) -> String {
213 blocks
214 .iter()
215 .filter_map(|b| match b {
216 ContentBlock::Text { text, .. } => Some(text.as_str()),
217 _ => None,
218 })
219 .collect::<Vec<_>>()
220 .join("\n")
221 }
222
223 /// Extract the first ` ```repl ` block from `text`. Falls back to
224 /// ` ```python `/`` ```py `` for compatibility with prompts that learned
225 /// the older fence style.
226 ///
227 /// The opening fence must start its own line (up to three spaces of indent,
228 /// as in Markdown) with no other info string, so prose that mentions a fence
229 /// mid-line is never code to run.
230 pub fn extract_repl_code(text: &str) -> Option<String> {
231 let mut lines = text.split_inclusive('\n');
232 let mut offset = 0;
233 let code_start = loop {
234 let line = lines.next()?;
235 offset += line.len();
236 let indent = line.len() - line.trim_start_matches(' ').len();
237 if indent <= 3
238 && line[indent..].strip_prefix("```").is_some_and(|info| {
239 matches!(info.trim(), "repl" | "python" | "py") && line.ends_with('\n')
240 })
241 {
242 break offset;
243 }
244 };
245 let after_fence = &text[code_start..];
246 let end_idx = if after_fence.starts_with("```") {
247 0
248 } else {
249 after_fence.find("\n```")?
250 };
251
252 let code = after_fence[..end_idx].trim().to_string();
253 if code.is_empty() {
254 return None;
255 }
256 Some(code)
257 }
258
259 /// Parse a top-level `FINAL(...)` directive from the model's raw text.
260 /// Mirrors the reference RLM's `find_final_answer`: directive must appear
261 /// at the start of a line, *outside* any code fence.
262 pub fn parse_text_final(text: &str) -> Option<String> {
263 let outside_fence = strip_code_fences(text);
264
265 for line in outside_fence.lines() {
266 let trimmed = line.trim_start();
267 if trimmed.starts_with("FINAL_VAR(") {
268 // FINAL_VAR can't be resolved from text alone — defer to REPL.
269 continue;
270 }
271 if let Some(rest) = trimmed.strip_prefix("FINAL(") {
272 let inner = rest.trim_end();
273 if let Some(end) = inner.rfind(')') {
274 let value = inner[..end].trim();
275 if !value.is_empty() {
276 return Some(strip_quotes(value));
277 }
278 }
279 }
280 }
281 None
282 }
283
284 fn strip_code_fences(text: &str) -> String {
285 let mut out = String::with_capacity(text.len());
286 let mut in_fence = false;
287 for line in text.lines() {
288 if line.trim_start().starts_with("```") {
289 in_fence = !in_fence;
290 continue;
291 }
292 if !in_fence {
293 out.push_str(line);
294 out.push('\n');
295 }
296 }
297 out
298 }
299
300 fn strip_quotes(s: &str) -> String {
301 let bytes = s.as_bytes();
302 if bytes.len() >= 2
303 && ((bytes[0] == b'"' && bytes[bytes.len() - 1] == b'"')
304 || (bytes[0] == b'\'' && bytes[bytes.len() - 1] == b'\''))
305 {
306 return s[1..s.len() - 1].to_string();
307 }
308 s.to_string()
309 }
310
311 pub fn truncate_text(text: &str, max_chars: usize) -> String {
312 let count = text.chars().count();
313 if count <= max_chars {
314 return text.to_string();
315 }
316 let take = max_chars.saturating_sub(3);
317 let mut result: String = text.chars().take(take).collect();
318 result.push_str("...");
319 result
320 }
321
322 #[cfg(test)]
323 mod tests {
324 use super::*;
325 use crate::core::engine::tests::rlm_host::{Replies, run_admitted_fixture, run_fixture};
326 use crate::core::events::Event;
327 use crate::llm_client::mock::MockLlmClient;
328 use crate::rlm::bridge::RlmUsageAccumulator;
329 use codewhale_models::{MessageRequest, MessageResponse};
330 use std::sync::Arc;
331 use tokio::sync::mpsc;
332
333 /// One model round whose code writes a marker file, run under `gate`.
334 async fn marker_round(
335 gate: Option<crate::tools::codemode::NestedCallGate>,
336 ) -> (RlmTurnResult, bool) {
337 let workspace = tempfile::tempdir().expect("tempdir");
338 let marker = workspace.path().join("rlm-round-executed.txt");
339 let marker_literal = serde_json::to_string(&marker.to_string_lossy()).expect("literal");
340 let mock = Arc::new(MockLlmClient::new(Vec::new()));
341 mock.push_message_response(MessageResponse {
342 tool_projection_warning: None,
343 id: "mock_gated_rlm".to_string(),
344 r#type: "message".to_string(),
345 role: "assistant".to_string(),
346 content: vec![ContentBlock::Text {
347 text: format!(
348 "```repl\nfrom pathlib import Path\nPath({marker_literal}).write_text('executed')\nFINAL('ran')\n```"
349 ),
350 cache_control: None,
351 }],
352 model: "mock-model".to_string(),
353 stop_reason: Some("end_turn".to_string()),
354 stop_sequence: None,
355 container: None,
356 usage: Usage::default(),
357 title: None,
358 stop_details: None,
359 refusal: None,
360 });
361 let client: Arc<dyn Replies> = mock;
362 let (tx, _rx) = mpsc::channel(8);
363 let result = run_admitted_fixture(
364 client,
365 "root-model".to_string(),
366 "long context".to_string(),
367 None,
368 "child-model".to_string(),
369 tx,
370 0,
371 RlmUsageAccumulator::new(),
372 tokio::time::Instant::now() + Duration::from_secs(60),
373 gate,
374 )
375 .await;
376 (result, marker.exists())
377 }
378
379 #[tokio::test]
380 async fn code_round_runs_only_when_the_gate_admits_exactly_that_code() {
381 use crate::tools::codemode::{NestedCallGate, NestedCallVerdict, NestedDecision};
382
383 let (result, ran) = marker_round(Some(NestedCallGate::admitting_for_test())).await;
384 assert!(ran, "an admitted round runs: {:?}", result.error);
385 assert_eq!(result.termination, RlmTermination::Final);
386
387 let (result, ran) = marker_round(None).await;
388 assert!(!ran, "no gate, no code");
389 assert_eq!(result.termination, RlmTermination::Error);
390 let error = result.error.expect("refusal is reported");
391 assert!(error.contains("no permission gate"), "{error}");
392
393 let refusing = NestedCallGate::answering_for_test(|_, _| NestedCallVerdict::Refused {
394 error: crate::tools::spec::ToolError::permission_denied("not approved"),
395 decision: NestedDecision::Denied,
396 });
397 let (result, ran) = marker_round(Some(refusing)).await;
398 assert!(!ran, "a refused round does not run");
399 let error = result.error.expect("refusal is reported");
400 assert!(error.contains("not approved"), "{error}");
401
402 // A hook-rewritten or otherwise different admitted input is not
403 // permission for the code the model wrote.
404 let rewriting = NestedCallGate::answering_for_test(|name, _| NestedCallVerdict::Run {
405 name: name.to_string(),
406 input: serde_json::json!({ "code": "print('something else')" }),
407 supports_parallel: false,
408 decision: NestedDecision::Auto,
409 hook_context: None,
410 });
411 let (result, ran) = marker_round(Some(rewriting)).await;
412 assert!(!ran, "a different admitted input does not run this code");
413 assert!(
414 result
415 .error
416 .is_some_and(|error| error.contains("was not this code"))
417 );
418 }
419
420 #[tokio::test]
421 async fn max_tokens_complete_repl_is_not_executed_or_accepted() {
422 let workspace = tempfile::tempdir().expect("tempdir");
423 let marker = workspace.path().join("truncated-repl-executed.txt");
424 let marker_literal = serde_json::to_string(&marker.to_string_lossy())
425 .expect("marker path should serialize as a Python string literal");
426 let partial = format!(
427 "```repl\nfrom pathlib import Path\nPath({marker_literal}).write_text('executed')\nFINAL('partial answer')\n```"
428 );
429 let usage = Usage {
430 input_tokens: 17,
431 output_tokens: 4096,
432 ..Usage::default()
433 };
434 let mock = Arc::new(MockLlmClient::new(Vec::new()));
435 mock.push_message_response(MessageResponse {
436 tool_projection_warning: None,
437 id: "mock_truncated_rlm".to_string(),
438 r#type: "message".to_string(),
439 role: "assistant".to_string(),
440 content: vec![ContentBlock::Text {
441 text: partial,
442 cache_control: None,
443 }],
444 model: "mock-model".to_string(),
445 stop_reason: Some("max_tokens".to_string()),
446 stop_sequence: None,
447 container: None,
448 usage: usage.clone(),
449 title: None,
450 stop_details: None,
451 refusal: None,
452 });
453 let client: Arc<dyn Replies> = mock.clone();
454 let (tx, _rx) = mpsc::channel(8);
455
456 let result = run_fixture(
457 client,
458 "root-model".to_string(),
459 "long context".to_string(),
460 None,
461 "child-model".to_string(),
462 tx,
463 0,
464 )
465 .await;
466
467 assert_eq!(result.termination, RlmTermination::Error);
468 assert!(
469 result.answer.is_empty(),
470 "partial FINAL must not be accepted"
471 );
472 let error = result.error.expect("truncation must fail the RLM turn");
473 assert!(error.contains("incomplete"), "{error}");
474 assert!(error.contains("max_tokens"), "{error}");
475 let mut expected_usage = usage.clone();
476 expected_usage.request_usages = vec![usage.clone()];
477 assert_eq!(
478 result.usage, expected_usage,
479 "billed usage must still be charged"
480 );
481 assert_eq!(result.routed_usage.len(), 1);
482 assert_eq!(result.routed_usage[0].usage.usage, usage);
483 assert_eq!(result.routed_usage_dropped_records, 0);
484 assert_eq!(mock.call_count(), 1, "truncation must not retry");
485 assert!(
486 !marker.exists(),
487 "complete-looking code from a truncated response must not execute"
488 );
489 }
490
491 #[tokio::test]
492 async fn root_provider_success_without_usage_retains_exact_missing_receipt() {
493 let mock = Arc::new(MockLlmClient::new(Vec::new()));
494 mock.push_message_response(MessageResponse {
495 tool_projection_warning: None,
496 id: "mock_missing_rlm_usage".to_string(),
497 r#type: "message".to_string(),
498 role: "assistant".to_string(),
499 content: vec![ContentBlock::Text {
500 text: "partial".to_string(),
501 cache_control: None,
502 }],
503 model: "mock-model".to_string(),
504 stop_reason: Some("max_tokens".to_string()),
505 stop_sequence: None,
506 container: None,
507 usage: Usage::default(),
508 title: None,
509 stop_details: None,
510 refusal: None,
511 });
512 let client: Arc<dyn Replies> = mock;
513 let (tx, _rx) = mpsc::channel(8);
514
515 let result = run_fixture(
516 client,
517 "root-model".to_string(),
518 "long context".to_string(),
519 None,
520 "child-model".to_string(),
521 tx,
522 0,
523 )
524 .await;
525
526 assert_eq!(result.termination, RlmTermination::Error);
527 assert_eq!(result.usage.input_tokens, 0);
528 assert_eq!(result.usage.output_tokens, 0);
529 assert_eq!(result.routed_usage.len(), 1);
530 let revision = result.routed_usage[0]
531 .settlement
532 .as_ref()
533 .expect("settled missing-usage receipt");
534 assert_eq!(
535 revision.coverage,
536 crate::llm_client::ProviderUsageCoverage::Missing
537 );
538 assert_eq!(
539 revision.reason,
540 Some(crate::cost_status::RuntimeUsageMissingReason::SuccessWithoutUsage)
541 );
542 assert!(result.routed_usage_drop_records.is_empty());
543 assert_eq!(result.routed_usage_dropped_records, 0);
544 assert_eq!(result.routed_usage[0].usage.route.model, "root-model");
545 }
546
547 fn text_response(text: &str) -> MessageResponse {
548 MessageResponse {
549 tool_projection_warning: None,
550 id: "mock_rlm_round".to_string(),
551 r#type: "message".to_string(),
552 role: "assistant".to_string(),
553 content: vec![ContentBlock::Text {
554 text: text.to_string(),
555 cache_control: None,
556 }],
557 model: "mock-model".to_string(),
558 stop_reason: Some("end_turn".to_string()),
559 stop_sequence: None,
560 container: None,
561 title: None,
562 stop_details: None,
563 refusal: None,
564 usage: Usage {
565 input_tokens: 5,
566 output_tokens: 5,
567 ..Usage::default()
568 },
569 }
570 }
571
572 #[tokio::test]
573 async fn recursive_work_continues_past_twenty_five_rounds_and_keeps_history() {
574 let mock = Arc::new(MockLlmClient::new(Vec::new()));
575 let rounds = 26;
576 let preparation_rounds = 4;
577 for _ in 0..preparation_rounds {
578 mock.push_message_response(text_response("I will inspect the computation next."));
579 }
580 for round in 0..rounds {
581 let code = if round < 4 {
582 format!("```repl\nx = {round}\n```")
583 } else {
584 format!("```repl\nprint('round {round}')\n```")
585 };
586 mock.push_message_response(text_response(&code));
587 }
588 mock.push_message_response(text_response("FINAL('complete')"));
589 let client: Arc<dyn Replies> = mock.clone();
590 let (tx, mut rx) = mpsc::channel(1024);
591 let result = run_fixture(
592 client,
593 "root-model".to_string(),
594 "long context".to_string(),
595 None,
596 "child-model".to_string(),
597 tx,
598 0,
599 )
600 .await;
601 assert_eq!(
602 result.termination,
603 RlmTermination::Final,
604 "{:?}",
605 result.error
606 );
607 assert_eq!(result.iterations, rounds + preparation_rounds + 1);
608 assert_eq!(result.answer, "complete");
609 assert!(result.error.is_none(), "{:?}", result.error);
610 let requests = mock.captured_requests();
611 assert_eq!(requests.len(), (rounds + preparation_rounds + 1) as usize);
612 assert_eq!(
613 requests
614 .last()
615 .expect("last request")
616 .messages
617 .iter()
618 .filter(|message| message.role == Role::Assistant)
619 .count(),
620 (rounds + preparation_rounds) as usize
621 );
622 let mut statuses = Vec::new();
623 while let Ok(event) = rx.try_recv() {
624 if let Event::Status { message } = event {
625 statuses.push(message);
626 }
627 }
628 assert!(
629 statuses
630 .iter()
631 .any(|line| line.contains("RLM finished: Final")),
632 "{statuses:#?}"
633 );
634 }
635
636 struct PendingAfterResponses(MockLlmClient, usize, tokio::sync::Notify);
637
638 impl Replies for PendingAfterResponses {
639 fn effective_route_envelope(
640 &self,
641 model: &str,
642 dispatched_at: chrono::DateTime<chrono::Utc>,
643 ) -> crate::cost_status::EffectiveRouteEnvelope {
644 self.0.effective_route_envelope(model, dispatched_at)
645 }
646
647 fn effective_max_output_tokens(&self, model: &str) -> u32 {
648 self.0.effective_max_output_tokens(model)
649 }
650
651 fn create_message_boxed(
652 &self,
653 request: MessageRequest,
654 ) -> std::pin::Pin<
655 Box<dyn std::future::Future<Output = anyhow::Result<MessageResponse>> + Send + '_>,
656 > {
657 if self.0.call_count() < self.1 {
658 self.0.create_message_boxed(request)
659 } else {
660 self.2.notify_one();
661 Box::pin(std::future::pending())
662 }
663 }
664 }
665
666 /// Checking time only between rounds cannot stop a pending root
667 /// request, a Python block, or an event send within the current round.
668 #[tokio::test]
669 async fn wall_clock_deadline_interrupts_pending_work_and_keeps_partial_result() {
670 let _home = crate::test_support::SealedHome::new();
671 use codewhale_dependencies::ExternalTool as _;
672 assert!(codewhale_dependencies::Python::resolve().is_some());
673 let warm = MockLlmClient::new(Vec::new());
674 warm.push_message_response(text_response("FINAL('warm')"));
675 let (warm_tx, _warm_rx) = mpsc::channel(32);
676 let started = std::time::Instant::now();
677 let warmed = run_fixture(
678 Arc::new(warm),
679 "root-model".to_string(),
680 "long context".to_string(),
681 None,
682 "child-model".to_string(),
683 warm_tx,
684 0,
685 )
686 .await;
687 assert_eq!(
688 warmed.termination,
689 RlmTermination::Final,
690 "{:?}",
691 warmed.error
692 );
693 let budget = Duration::from_secs(5) + started.elapsed() * 2;
694 for pending_model in [true, false] {
695 let partial = if pending_model {
696 "```repl\nprint(len(content))\n```"
697 } else {
698 "```repl\nimport time\ntime.sleep(600)\nFINAL('too late')\n```"
699 };
700 let mock = MockLlmClient::new(Vec::new());
701 mock.push_message_response(text_response(partial));
702 let client = Arc::new(PendingAfterResponses(mock, 1, tokio::sync::Notify::new()));
703 let (tx, mut rx) = mpsc::channel(32);
704 let usage = RlmUsageAccumulator::new();
705 // Admission reads configuration and constructs the captured route.
706 // It is fixture setup, before this invocation's budget.
707 let caller =
708 crate::core::engine::tests::rlm_host::caller_for(client.clone(), "root-model");
709
710 let call = caller.dispatch(crate::core::engine::rlm_host::RlmInvocation {
711 prompt: "long context".to_string(),
712 mode: crate::core::engine::rlm_host::RlmMode::Recursive { depth_remaining: 0 },
713 prompt_policy: crate::core::engine::rlm_host::RlmPromptPolicy::Session,
714 max_tokens: None,
715 task_instructions: None,
716 deadline: Some(tokio::time::Instant::now() + budget),
717 gate: Some(crate::tools::codemode::NestedCallGate::admitting_for_test()),
718 events: Some(tx),
719 usage: usage.clone(),
720 });
721 tokio::pin!(call);
722 let result = tokio::time::timeout(budget + Duration::from_secs(10), async {
723 if pending_model {
724 tokio::select! {
725 biased;
726 () = client.2.notified() => {},
727 result = &mut call => panic!(
728 "pending model request was not reached: error={:?}, iterations={}, calls={}, trace={:?}",
729 result.error,
730 result.iterations,
731 client.0.call_count(),
732 result.trace
733 ),
734 }
735 }
736 call.await
737 })
738 .await
739 .expect("the turn deadline must interrupt in-flight work");
740
741 assert_eq!(result.termination, RlmTermination::Error);
742 assert_eq!(
743 result.answer,
744 partial,
745 "error={:?}, iterations={}, calls={}, trace={:?}",
746 result.error,
747 result.iterations,
748 client.0.call_count(),
749 result.trace
750 );
751 assert_eq!(
752 result.iterations,
753 if pending_model { 2 } else { 1 },
754 "error={:?}, calls={}, trace={:?}",
755 result.error,
756 client.0.call_count(),
757 result.trace
758 );
759 assert!(
760 result
761 .error
762 .as_deref()
763 .unwrap()
764 .contains("wall-clock deadline")
765 );
766 let mut expected_usage = text_response(partial).usage;
767 expected_usage.request_usages = vec![text_response(partial).usage];
768 if pending_model {
769 expected_usage.request_usages.push(Usage::default());
770 }
771 assert_eq!(result.usage, expected_usage);
772 assert_eq!(client.0.call_count(), 1);
773 let snapshot = usage.snapshot().await;
774 assert_eq!(
775 snapshot.records.len(),
776 1 + usize::from(pending_model),
777 "keep completed usage and the unknown pending request"
778 );
779 assert_eq!(snapshot.dropped_records, 0);
780 assert!(snapshot.drop_records.is_empty());
781 if pending_model {
782 let revision = snapshot.records[1]
783 .settlement
784 .as_ref()
785 .expect("pending request keeps a settled receipt");
786 assert_eq!(
787 revision.coverage,
788 crate::llm_client::ProviderUsageCoverage::Missing
789 );
790 }
791 if pending_model {
792 assert_eq!(result.trace.len(), 1, "keep completed rounds");
793 assert!(!result.trace[0].had_error);
794 assert_eq!(
795 result.trace[0].stdout_preview.trim(),
796 "12",
797 "the kernel received its context over stdin"
798 );
799 }
800 let mut saw_timeout = false;
801 while let Ok(event) = rx.try_recv() {
802 if let Event::Status { message } = event {
803 saw_timeout |= message.contains("RLM finished: Error")
804 && message.contains("wall-clock deadline");
805 }
806 }
807 assert!(saw_timeout, "timeout must record how the turn ended");
808 let terminal_receipts: Vec<_> = snapshot
809 .nested_events
810 .iter()
811 .filter(|event| {
812 event["kind"] == "status"
813 && event["content"].as_str().is_some_and(|content| {
814 content.contains("RLM finished: Error")
815 && content.contains("wall-clock deadline")
816 })
817 })
818 .collect();
819 assert_eq!(terminal_receipts.len(), 1, "one canonical terminal receipt");
820 }
821 }
822
823 #[tokio::test]
824 async fn wall_clock_deadline_returns_when_event_stream_is_full() {
825 let _home = crate::test_support::SealedHome::new();
826 // An empty response queue fails immediately and cannot test the deadline.
827 // Observe the admitted provider future before filling the host channel.
828 let client = Arc::new(PendingAfterResponses(
829 MockLlmClient::new(Vec::new()),
830 0,
831 tokio::sync::Notify::new(),
832 ));
833 let caller = crate::core::engine::tests::rlm_host::caller_for(client.clone(), "root-model");
834 let usage = RlmUsageAccumulator::new();
835 let (tx, mut rx) = mpsc::channel(1);
836 let result = tokio::time::timeout(
837 Duration::from_secs(5),
838 async {
839 // Completion uses the same host/deadline/Drop authority without
840 // making Python startup part of this event-channel fixture.
841 let call = caller.dispatch(crate::core::engine::rlm_host::RlmInvocation {
842 prompt: "long context".to_string(),
843 mode: crate::core::engine::rlm_host::RlmMode::Completion,
844 prompt_policy: crate::core::engine::rlm_host::RlmPromptPolicy::Session,
845 max_tokens: None,
846 task_instructions: None,
847 deadline: Some(tokio::time::Instant::now() + Duration::from_secs(1)),
848 gate: None,
849 events: Some(tx.clone()),
850 usage: usage.clone(),
851 });
852 tokio::pin!(call);
853 loop {
854 tokio::select! {
855 biased;
856 () = client.2.notified() => break,
857 result = &mut call => panic!("provider request was not reached: {:?}", result.error),
858 event = rx.recv() => assert!(event.is_some()),
859 }
860 }
861 let _ = tx.try_send(Event::status("fixture occupies the caller event channel"));
862 assert_eq!(tx.capacity(), 0, "caller event channel must be full");
863 call.await
864 },
865 )
866 .await
867 .expect("deadline hand-back must not wait on a full event stream");
868
869 assert_eq!(result.termination, RlmTermination::Error);
870 assert!(
871 result
872 .error
873 .as_deref()
874 .unwrap()
875 .contains("wall-clock deadline"),
876 "{:?}",
877 result.error
878 );
879 assert_eq!(client.0.call_count(), 0, "no scripted response completed");
880 let snapshot = usage.snapshot().await;
881 assert_eq!(snapshot.records.len(), 1, "one pending admitted request");
882 let revision = snapshot.records[0]
883 .settlement
884 .as_ref()
885 .expect("pending request keeps a settled receipt");
886 assert_eq!(
887 revision.coverage,
888 crate::llm_client::ProviderUsageCoverage::Missing
889 );
890 assert_eq!(
891 revision.reason,
892 Some(crate::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown)
893 );
894 assert_eq!(snapshot.dropped_records, 0);
895 assert_eq!(
896 snapshot
897 .nested_events
898 .iter()
899 .filter(|event| {
900 event["kind"] == "status"
901 && event["content"].as_str().is_some_and(|content| {
902 content.contains("RLM finished: Error")
903 && content.contains("wall-clock deadline")
904 })
905 })
906 .count(),
907 1,
908 "full host channel must retain one canonical terminal receipt"
909 );
910 }
911
912 #[test]
913 fn empty_answer_is_never_returned_without_an_error() {
914 let empty = |termination| RlmTurnResult {
915 answer: " ".to_string(),
916 iterations: 2,
917 duration: Duration::ZERO,
918 error: None,
919 usage: Usage::default(),
920 routed_usage: Vec::new(),
921 routed_usage_drop_records: Vec::new(),
922 routed_usage_dropped_records: 0,
923 termination,
924 trace: Vec::new(),
925 total_rpcs: 0,
926 };
927 let error = empty(RlmTermination::NoCode)
928 .require_answer_or_error()
929 .error
930 .expect("empty answer needs a reason");
931 assert!(error.contains("empty answer"), "{error}");
932 assert!(error.contains("NoCode"), "{error}");
933
934 // `FINAL("")` is an answer the model chose; callers keep getting "".
935 let deliberate = empty(RlmTermination::Final).require_answer_or_error();
936 assert!(deliberate.error.is_none(), "{:?}", deliberate.error);
937 }
938
939 #[test]
940 fn extract_repl_code_finds_simple_block() {
941 let text = "Here:\n```repl\nprint('hi')\n```\nEnd.";
942 let code = extract_repl_code(text).unwrap();
943 assert_eq!(code, "print('hi')");
944 }
945
946 #[test]
947 fn extract_repl_code_falls_back_to_python_marker() {
948 let text = "Code:\n```python\nx = 1 + 2\n```";
949 let code = extract_repl_code(text).unwrap();
950 assert_eq!(code, "x = 1 + 2");
951 }
952
953 #[test]
954 fn extract_repl_code_returns_none_when_missing() {
955 assert!(extract_repl_code("Just text.").is_none());
956 }
957
958 #[test]
959 fn extract_repl_code_returns_none_on_empty_block() {
960 assert!(extract_repl_code("```repl\n\n```").is_none());
961 }
962
963 #[test]
964 fn extract_repl_code_handles_multiple_blocks() {
965 let text = "```repl\na=1\n```\n```repl\nb=2\n```";
966 let code = extract_repl_code(text).unwrap();
967 assert_eq!(code, "a=1");
968 }
969
970 #[test]
971 fn extract_repl_code_ignores_other_fences() {
972 let text = "```\nfoo\n```\n```repl\nreal_code()\n```";
973 let code = extract_repl_code(text).unwrap();
974 assert_eq!(code, "real_code()");
975 }
976
977 #[test]
978 fn extract_repl_code_requires_a_line_anchored_fence() {
979 assert!(extract_repl_code("see ```python\nx = 1\n```").is_none());
980 assert!(extract_repl_code("a ```repl mention\nx = 1\n```").is_none());
981 assert!(extract_repl_code("```python-output\nx = 1\n```").is_none());
982 let text = "prose ```py inline\n```py\nreal()\n```";
983 assert_eq!(extract_repl_code(text).as_deref(), Some("real()"));
984 }
985
986 #[test]
987 fn parse_text_final_extracts_simple_value() {
988 let text = "OK.\nFINAL(42)\nThanks.";
989 assert_eq!(parse_text_final(text).as_deref(), Some("42"));
990 }
991
992 #[test]
993 fn parse_text_final_strips_quotes() {
994 let text = "FINAL(\"the answer is yes\")";
995 assert_eq!(parse_text_final(text).as_deref(), Some("the answer is yes"));
996 }
997
998 #[test]
999 fn parse_text_final_ignores_inside_code_fence() {
1000 let text =
1001 "Some prose.\n```repl\n# Note: when ready, call FINAL(value)\nx = 1\n```\nMore prose.";
1002 assert!(parse_text_final(text).is_none());
1003 }
1004
1005 #[test]
1006 fn parse_text_final_returns_none_when_absent() {
1007 assert!(parse_text_final("just talking, no final.").is_none());
1008 }
1009
1010 #[test]
1011 fn build_metadata_contains_key_information() {
1012 let msg = build_metadata_message("Hello, world!", None, 0, None, None);
1013 let text = extract_text_blocks(&msg.content);
1014 assert!(text.contains("context"));
1015 assert!(text.contains("Hello, world!"));
1016 assert!(text.contains("round 0"));
1017 assert!(text.contains("llm_query"));
1018 assert!(text.contains("rlm_query"));
1019 assert!(text.contains("FINAL"));
1020 }
1021
1022 #[test]
1023 fn build_metadata_truncates_long_context_without_leaking_tail() {
1024 let secret_tail = "DO_NOT_LEAK_CONTEXT_TAIL";
1025 let prompt = format!("{}{}", "a".repeat(PROMPT_PREVIEW_LEN + 100), secret_tail);
1026 let msg = build_metadata_message(&prompt, None, 0, None, None);
1027 let text = extract_text_blocks(&msg.content);
1028
1029 assert!(text.contains(&format!("- Length: {} chars", prompt.chars().count())));
1030 assert!(text.contains("- Preview: \""));
1031 assert!(text.contains("..."));
1032 assert!(
1033 !text.contains(secret_tail),
1034 "metadata leaked the non-preview tail of context"
1035 );
1036 }
1037
1038 #[tokio::test]
1039 async fn build_root_request_keeps_context_tail_out_of_root_payload() {
1040 let secret_tail = "DO_NOT_LEAK_ROOT_REQUEST";
1041 let prompt = format!("{}{}", "a".repeat(PROMPT_PREVIEW_LEN + 100), secret_tail);
1042 let mock = Arc::new(MockLlmClient::new(Vec::new()));
1043 mock.push_message_response(MessageResponse {
1044 tool_projection_warning: None,
1045 id: "context-metadata".into(),
1046 r#type: "message".into(),
1047 role: "assistant".into(),
1048 content: vec![ContentBlock::Text {
1049 text: "```repl\nFINAL('metadata only')\n```".into(),
1050 cache_control: None,
1051 }],
1052 model: "root-model".into(),
1053 stop_reason: Some("end_turn".into()),
1054 stop_sequence: None,
1055 container: None,
1056 usage: Usage::default(),
1057 title: None,
1058 stop_details: None,
1059 refusal: None,
1060 });
1061 let (tx, _rx) = mpsc::channel(64);
1062 let result = run_fixture(
1063 mock.clone(),
1064 "root-model".into(),
1065 prompt.clone(),
1066 Some("answer from the long context".into()),
1067 "child-model".into(),
1068 tx,
1069 0,
1070 )
1071 .await;
1072 assert_eq!(
1073 result.termination,
1074 RlmTermination::Final,
1075 "{:?}",
1076 result.error
1077 );
1078 let requests = mock.captured_requests();
1079 assert_eq!(requests.len(), 1);
1080 let request = &requests[0];
1081 let payload = serde_json::to_string(request).expect("actual Core request serializes");
1082 assert_eq!(request.temperature, None);
1083 assert_eq!(request.top_p, None);
1084 assert!(payload.contains(&format!("- Length: {} chars", prompt.chars().count())));
1085 assert!(
1086 !payload.contains(secret_tail),
1087 "Core request leaked the non-preview context tail"
1088 );
1089 assert!(payload.contains("Captured operator Core policy"));
1090 assert!(payload.contains("answer from the long context"));
1091 }
1092
1093 #[test]
1094 fn build_metadata_with_iteration_shows_previous_code() {
1095 let msg = build_metadata_message("Test prompt", None, 3, Some("print('hi')"), Some("hi"));
1096 let text = extract_text_blocks(&msg.content);
1097 assert!(text.contains("round 3"));
1098 assert!(text.contains("print('hi')"));
1099 assert!(text.contains("hi"));
1100 }
1101
1102 #[test]
1103 fn build_metadata_includes_root_prompt() {
1104 let msg = build_metadata_message(
1105 "long context",
1106 Some("Summarize the security model"),
1107 1,
1108 Some("# noop"),
1109 Some("ok"),
1110 );
1111 let text = extract_text_blocks(&msg.content);
1112 assert!(text.contains("Original task"));
1113 assert!(text.contains("Summarize the security model"));
1114 }
1115
1116 #[test]
1117 fn truncate_text_leaves_short_alone() {
1118 assert_eq!(truncate_text("hello", 100), "hello");
1119 }
1120
1121 #[test]
1122 fn truncate_text_shortens_long_text() {
1123 let long = "a".repeat(1000);
1124 let truncated = truncate_text(&long, 10);
1125 assert_eq!(truncated.chars().count(), 10);
1126 assert!(truncated.ends_with("..."));
1127 }
1128
1129 #[test]
1130 fn truncate_text_is_unicode_safe() {
1131 let s = "日本語テスト";
1132 let out = truncate_text(s, 4);
1133 assert_eq!(out.chars().count(), 4);
1134 assert!(out.ends_with("..."));
1135 assert!(std::str::from_utf8(out.as_bytes()).is_ok());
1136 }
1137
1138 #[test]
1139 fn extract_text_blocks_joins_text() {
1140 let blocks = vec![
1141 ContentBlock::Text {
1142 text: "first".to_string(),
1143 cache_control: None,
1144 },
1145 ContentBlock::Thinking {
1146 signature: None,
1147 state: None,
1148 redacted_data: None,
1149 thinking: "skip".to_string(),
1150 },
1151 ContentBlock::Text {
1152 text: "second".to_string(),
1153 cache_control: None,
1154 },
1155 ];
1156 assert_eq!(extract_text_blocks(&blocks), "first\nsecond");
1157 }
1158
1159 #[test]
1160 fn metadata_msg_role_is_user() {
1161 let msg = build_metadata_message("test", None, 0, None, None);
1162 assert_eq!(msg.role, "user");
1163 }
1164
1165 #[test]
1166 fn summarize_code_keeps_short() {
1167 assert_eq!(summarize_code("a\nb\nc"), "a\nb\nc");
1168 }
1169
1170 #[test]
1171 fn summarize_code_compresses_long() {
1172 let lines: Vec<String> = (0..20).map(|i| format!("line{i}")).collect();
1173 let code = lines.join("\n");
1174 let s = summarize_code(&code);
1175 assert!(s.starts_with("20 lines:"));
1176 assert!(s.contains("line0"));
1177 assert!(s.contains("line19"));
1178 assert!(s.contains("…"));
1179 }
1180 }
1181
1181 lines RUST