返回 CodeWhale
events.rs
根目录 / crates / tui / src / conformance / events.rs
1 //! Golden-events family: one full turn through the one turn loop.
2 //!
3 //! Each case drives `Engine::run` (and so `Engine::run_turn`) with a scripted
4 //! provider — a queue of normalized stream events per model request, written
5 //! in the [`super::stream_json`] format — and a small host driver that
6 //! answers approvals or cancels on cue. The golden is the protocol projection
7 //! (`protocol_parity::event_to_protocol`, the `EventMsg` wire shape every
8 //! frontend consumes), normalized, plus one trailing `harness_summary` line
9 //! with the provider request count and the workspace after the turn.
10 //!
11 //! Normalization (also stated in the fixture README): the per-session
12 //! `thread_id`/`session_id` routing envelope is dropped; liveness heartbeats
13 //! are dropped; UUIDs, timestamps, temp paths and durations are masked; the
14 //! system prompt and tool catalog bodies are replaced by a marker because the
15 //! prompt family owns those bytes; an uninterrupted run of completion events
16 //! is put in a canonical order because parallel completions race and their
17 //! pairs interleave: `operation_activity_completed` by span id, then
18 //! `tool_call_complete` by tool call id. The activity events of one announced
19 //! parallel batch (the events after the `Executing N ... parallel chunk(s)`
20 //! status) are ordered the same way, starts first, because a fast tool can
21 //! finish before its sibling has started. Only a causally valid batch is
22 //! reordered; no error or other event is crossed.
23
24 use std::collections::{BTreeMap, VecDeque};
25 use std::path::Path;
26 use std::sync::Mutex;
27 use std::sync::atomic::{AtomicUsize, Ordering};
28 use std::time::Duration;
29
30 use anyhow::{Result, anyhow};
31 use serde_json::{Value, json};
32
33 use codewhale_config::AppMode;
34 use codewhale_execpolicy::ApprovalMode;
35 use codewhale_models::{MessageRequest, MessageResponse, StreamEvent};
36 use codewhale_protocol::ids::{SessionId, ThreadId};
37
38 use super::golden::{self, Failures, Masker, Sandbox};
39 use super::stream_json;
40 use codewhale_engine::compaction::CompactionConfig;
41 use codewhale_engine::core::engine::{Engine, EngineConfig};
42 use codewhale_engine::core::events::Event;
43 use codewhale_engine::core::ops::{Op, TurnSpec, UserInputProvenance};
44 use codewhale_engine::core::protocol_parity::{ProtocolIds, event_to_protocol};
45 use codewhale_engine::llm_client::{LlmClient, StreamEventBox};
46 use codewhale_runtime::config::Config;
47
48 const FAMILY: &str = "events";
49 pub(super) const PREFIX_OWNED_BY_PROMPT_FAMILY: &str = "<pinned by the prompt family>";
50
51 /// Keys whose values are clocks or durations.
52 const VOLATILE_KEYS: &[&str] = &[
53 "created_at",
54 "duration_ms",
55 "first_token_ms",
56 "request_ms",
57 "elapsed_ms",
58 "pinned_combined_hash",
59 "request_id",
60 "source_id",
61 ];
62
63 fn event_deadline() -> Duration {
64 if cfg!(windows) {
65 Duration::from_secs(60)
66 } else {
67 Duration::from_secs(20)
68 }
69 }
70
71 enum Step {
72 Stream {
73 events: Vec<StreamEvent>,
74 hang: bool,
75 },
76 Refuse(String),
77 }
78
79 /// The scripted fake provider: one queued step per model request. Unlike the
80 /// general-purpose `MockLlmClient` it appends nothing — a script without
81 /// `message_stop` is a truncated stream, exactly as written.
82 pub(super) struct ScriptedProvider {
83 model: String,
84 steps: Mutex<VecDeque<Step>>,
85 stream_requests: AtomicUsize,
86 other_requests: AtomicUsize,
87 captured: Mutex<Vec<MessageRequest>>,
88 }
89
90 impl ScriptedProvider {
91 pub(super) fn from_script(model: &str, script: &Value) -> Self {
92 assert!(
93 script.as_array().is_some_and(|steps| !steps.is_empty()),
94 "provider_script must contain at least one response"
95 );
96 let steps = script
97 .as_array()
98 .expect("provider_script is an array")
99 .iter()
100 .map(|step| {
101 if let Some(message) = step.get("request_error").and_then(Value::as_str) {
102 return Step::Refuse(message.to_string());
103 }
104 let events = step["events"]
105 .as_array()
106 .expect("provider_script step has events")
107 .iter()
108 .map(|event| {
109 stream_json::from_json(event)
110 .unwrap_or_else(|error| panic!("script event {event}: {error}"))
111 })
112 .collect();
113 Step::Stream {
114 events,
115 hang: step.get("then").and_then(Value::as_str) == Some("hang"),
116 }
117 })
118 .collect();
119 Self {
120 model: model.to_string(),
121 steps: Mutex::new(steps),
122 stream_requests: AtomicUsize::new(0),
123 other_requests: AtomicUsize::new(0),
124 captured: Mutex::new(Vec::new()),
125 }
126 }
127
128 pub(super) fn stream_requests(&self) -> usize {
129 self.stream_requests.load(Ordering::SeqCst)
130 }
131
132 pub(super) fn other_requests(&self) -> usize {
133 self.other_requests.load(Ordering::SeqCst)
134 }
135
136 pub(super) fn captured(&self) -> Vec<MessageRequest> {
137 self.captured.lock().expect("captured requests").clone()
138 }
139 }
140
141 impl LlmClient for ScriptedProvider {
142 fn provider_name(&self) -> &'static str {
143 "conformance"
144 }
145
146 fn model(&self) -> &str {
147 &self.model
148 }
149
150 async fn create_message(&self, _request: MessageRequest) -> Result<MessageResponse> {
151 self.other_requests.fetch_add(1, Ordering::SeqCst);
152 Err(anyhow!(
153 "conformance provider serves streaming turns only; a non-streaming request is not scripted"
154 ))
155 }
156
157 async fn create_message_stream(&self, request: MessageRequest) -> Result<StreamEventBox> {
158 let call = self.stream_requests.fetch_add(1, Ordering::SeqCst) + 1;
159 self.captured
160 .lock()
161 .expect("captured requests")
162 .push(request);
163 let step = self.steps.lock().expect("script").pop_front();
164 match step {
165 None => Err(anyhow!(
166 "conformance script exhausted: model request #{call} has no scripted response"
167 )),
168 Some(Step::Refuse(message)) => Err(anyhow!(message)),
169 Some(Step::Stream { events, hang }) => {
170 let stream: StreamEventBox = Box::pin(async_stream::stream! {
171 for event in events {
172 yield Ok::<StreamEvent, anyhow::Error>(event);
173 }
174 if hang {
175 std::future::pending::<()>().await;
176 }
177 });
178 Ok(stream)
179 }
180 }
181 }
182 }
183
184 fn app_mode(case: &Value) -> AppMode {
185 match case["mode"].as_str().unwrap_or("agent") {
186 "agent" => AppMode::Agent,
187 "plan" => AppMode::Plan,
188 "operate" => AppMode::Agent,
189 other => panic!("unknown mode `{other}`"),
190 }
191 }
192
193 fn approval_mode(case: &Value) -> ApprovalMode {
194 match case["approval_mode"].as_str().unwrap_or("suggest") {
195 "suggest" => ApprovalMode::Suggest,
196 "accept_edits" => ApprovalMode::AcceptEdits,
197 "auto" => ApprovalMode::Auto,
198 "bypass" => ApprovalMode::Bypass,
199 "never" => ApprovalMode::Never,
200 other => panic!("unknown approval_mode `{other}`"),
201 }
202 }
203
204 pub(super) fn send_message_op(case: &Value, config: &Config) -> Op {
205 let model = case["model"].as_str().expect("case.model");
206 let route = codewhale_engine::route_runtime::resolve_runtime_route(
207 config,
208 config.active_provider_identity().unwrap().provider,
209 Some(model),
210 )
211 .expect("resolve conformance route");
212 Op::SendMessage(TurnSpec {
213 profile_constitution: None,
214 max_output_tokens: None,
215 submission_id: None,
216 content: case["user_message"]
217 .as_str()
218 .expect("case.user_message")
219 .to_string(),
220 images: Vec::new(),
221 mode: app_mode(case),
222 route: Box::new(route),
223 compaction: Box::new(CompactionConfig::default()),
224 initial_routed_usage: Box::default(),
225 goal_objective: None,
226 goal_token_budget: None,
227 goal_status: codewhale_engine::tools::goal::GoalStatus::Active,
228 reasoning_effort: None,
229 reasoning_effort_auto: false,
230 auto_model: false,
231 allow_shell: case["allow_shell"].as_bool().unwrap_or(true),
232 trust_mode: false,
233 auto_approve: case["auto_approve"].as_bool().unwrap_or(false),
234 approval_mode: approval_mode(case),
235 translation_enabled: false,
236 allowed_tools: None,
237 dynamic_tools: Vec::new(),
238 hook_executor: None,
239 verbosity: None,
240 provenance: UserInputProvenance::ExternalUser,
241 input_authorship: codewhale_engine::core::ops::TurnInputAuthorship::NotPerson,
242 })
243 }
244
245 /// Relative path → sha256 prefix for every file left in the workspace.
246 fn workspace_listing(workspace: &Path) -> BTreeMap<String, String> {
247 fn walk(root: &Path, dir: &Path, out: &mut BTreeMap<String, String>) {
248 let Ok(entries) = std::fs::read_dir(dir) else {
249 return;
250 };
251 for entry in entries.flatten() {
252 let path = entry.path();
253 if path.is_dir() {
254 walk(root, &path, out);
255 } else if let Ok(bytes) = std::fs::read(&path) {
256 let relative = path
257 .strip_prefix(root)
258 .expect("inside workspace")
259 .to_string_lossy()
260 .replace('\\', "/");
261 if relative.contains("subagents.v3.writer.boot_") {
262 continue;
263 }
264 let digest = codewhale_runtime::hashing::sha256_hex(&bytes);
265 out.insert(relative, digest[..16].to_string());
266 }
267 }
268 }
269 let mut out = BTreeMap::new();
270 walk(workspace, workspace, &mut out);
271 out
272 }
273
274 pub(super) struct TurnRecord {
275 pub(super) events: Vec<Event>,
276 pub(super) failure: Option<String>,
277 }
278
279 /// Drive one scripted turn inside `sandbox` on a fresh current-thread
280 /// runtime, dropping the runtime (and its blocking post-turn work) before
281 /// returning so nothing outlives the sandboxed environment.
282 pub(super) fn run_scripted_turn(
283 sandbox: &Sandbox,
284 case: &Value,
285 script: &Value,
286 ) -> (TurnRecord, std::sync::Arc<ScriptedProvider>) {
287 run_scripted_turn_with_deadline(sandbox, case, script, event_deadline())
288 }
289
290 fn run_scripted_turn_with_deadline(
291 sandbox: &Sandbox,
292 case: &Value,
293 script: &Value,
294 deadline: Duration,
295 ) -> (TurnRecord, std::sync::Arc<ScriptedProvider>) {
296 let model = case["model"].as_str().expect("case.model");
297 let provider = std::sync::Arc::new(ScriptedProvider::from_script(model, script));
298 let driver = case["driver"].as_array().cloned().unwrap_or_default();
299 let runtime = tokio::runtime::Builder::new_current_thread()
300 .enable_all()
301 .build()
302 .expect("runtime");
303 let (os, shell) = recorded_environment(case);
304 // Held across the whole turn: the engine builds and refreshes its system
305 // prompt on this thread's current-thread runtime.
306 let _environment = codewhale_engine::prompts::pin_recorded_environment(&os, &shell);
307 let _host_tools = codewhale_dependencies::pin_recorded_host_tools(recorded_host_tools(case));
308 let record = runtime.block_on(async {
309 let config = Config::default();
310 let engine_config = EngineConfig {
311 workspace: sandbox.workspace.clone(),
312 snapshots_enabled: false,
313 subagents_enabled: false,
314 session_id: Some("conformance-session".to_string()),
315 ..EngineConfig::default()
316 };
317 let client: codewhale_engine::core::model_client::SharedModelClient = provider.clone();
318 let (mut engine, handle) = Engine::new_with_model_client(engine_config, &config, client);
319 let (enforcement, no_new_privs_active) = recorded_platform(case);
320 engine.pin_recorded_platform_posture(enforcement, no_new_privs_active);
321 let op = send_message_op(case, &config);
322 drive_turn(engine, handle, op, &driver, deadline).await
323 });
324 drop(runtime);
325 (record, provider)
326 }
327
328 /// The execution boundary a case's golden was recorded under.
329 ///
330 /// The Engine names its sandbox posture to the model in `<turn_meta>`, and a
331 /// live probe makes that line a fact about the runner: macOS applies a local
332 /// OS sandbox, a Linux runner without bubblewrap is policy-only, and Linux
333 /// startup may relax no-new-privs. Every scripted case therefore declares the
334 /// recorded facts and the harness replays exactly those, so a golden states
335 /// what the Engine does on that platform rather than which machine ran it.
336 /// A case without them fails loud instead of silently probing the host. The
337 /// label for each platform is owned and tested by `sandbox::policy`.
338 fn recorded_platform(
339 case: &Value,
340 ) -> (codewhale_sandbox::policy::SandboxEnforcement, Option<bool>) {
341 use codewhale_sandbox::policy::SandboxEnforcement;
342 let platform = case
343 .get("recorded_platform")
344 .expect("scripted conformance case must declare `recorded_platform`");
345 let enforcement = match platform.get("sandbox_enforcement").and_then(Value::as_str) {
346 Some("local_os") => SandboxEnforcement::LocalOs,
347 Some("unavailable") => SandboxEnforcement::Unavailable,
348 Some("external_backend") => SandboxEnforcement::ExternalBackend,
349 other => panic!("unknown recorded_platform.sandbox_enforcement: {other:?}"),
350 };
351 let no_new_privs_active = match platform.get("no_new_privs_active") {
352 Some(Value::Null) => None,
353 Some(Value::Bool(active)) => Some(*active),
354 other => panic!("recorded_platform.no_new_privs_active must be null or a bool: {other:?}"),
355 };
356 (enforcement, no_new_privs_active)
357 }
358
359 /// The OS and shell the golden's `## Environment` block was recorded with.
360 /// They enter the frozen prompt prefix, and so its hash in
361 /// `prefix_cache_change`; a case without them fails loud.
362 fn recorded_environment(case: &Value) -> (String, String) {
363 let platform = case
364 .get("recorded_platform")
365 .expect("scripted conformance case must declare `recorded_platform`");
366 let field = |name: &str| {
367 platform
368 .get(name)
369 .and_then(Value::as_str)
370 .filter(|value| !value.trim().is_empty())
371 .unwrap_or_else(|| panic!("recorded_platform.{name} must be a non-empty string"))
372 .to_string()
373 };
374 (field("os"), field("shell"))
375 }
376
377 /// The optional host-backed tools the recording machine had (see
378 /// `dependencies::host_tool_available`). They change the registry the golden
379 /// snapshot counts; a case without the list fails loud.
380 fn recorded_host_tools(case: &Value) -> Vec<String> {
381 case.get("recorded_platform")
382 .and_then(|platform| platform.get("host_tools"))
383 .and_then(Value::as_array)
384 .expect("recorded_platform.host_tools must list the recording host's optional tools")
385 .iter()
386 .map(|tool| {
387 tool.as_str()
388 .expect("recorded_platform.host_tools entries are tool names")
389 .to_string()
390 })
391 .collect()
392 }
393
394 /// Run one turn and return every engine event up to and including
395 /// `TurnComplete`, then everything the engine emits while it shuts down.
396 async fn drive_turn(
397 engine: Engine,
398 handle: codewhale_engine::core::engine::EngineHandle,
399 op: Op,
400 driver: &[Value],
401 deadline: Duration,
402 ) -> TurnRecord {
403 let mut run = tokio::spawn(engine.run());
404 handle.send(op).await.expect("send conformance turn");
405 let rx = handle.rx_event.clone();
406 let ids = protocol_ids();
407 let mut events = Vec::new();
408 let mut fired = vec![false; driver.len()];
409 let mut failure = None;
410 let mut completed = false;
411 let expires = tokio::time::Instant::now() + deadline;
412 loop {
413 if tokio::time::Instant::now() >= expires {
414 failure = Some(format!(
415 "harness timeout: engine turn did not complete within {deadline:?}"
416 ));
417 break;
418 }
419 let next = golden::complete_within(
420 "engine turn",
421 expires.saturating_duration_since(tokio::time::Instant::now()),
422 async { rx.write().await.recv().await },
423 )
424 .await;
425 let event = match next {
426 Ok(Some(event)) => event,
427 Ok(None) => break,
428 Err(error) => {
429 failure = Some(error);
430 break;
431 }
432 };
433 let projected = serde_json::to_value(event_to_protocol(&event, &ids)).expect("EventMsg");
434 for (index, rule) in driver.iter().enumerate() {
435 if fired[index] || !rule_matches(&rule["when"], &projected) {
436 continue;
437 }
438 fired[index] = true;
439 match rule["action"].as_str().expect("driver action") {
440 "cancel" => handle.cancel(),
441 action @ ("approve" | "deny") => {
442 let Event::ApprovalRequired { id, .. } = &event else {
443 panic!("driver `{action}` must match an approval_required event");
444 };
445 let answered = if action == "approve" {
446 handle.approve_tool_call(id.clone()).await
447 } else {
448 handle.deny_tool_call(id.clone()).await
449 };
450 answered.expect("answer approval");
451 }
452 other => panic!("unknown driver action `{other}`"),
453 }
454 }
455 let terminal = matches!(event, Event::TurnComplete { .. });
456 events.push(event);
457 if terminal {
458 completed = true;
459 break;
460 }
461 }
462 if !completed && failure.is_none() {
463 failure = Some("engine closed before TurnComplete".to_string());
464 }
465 handle.cancel();
466 match golden::complete_within(
467 "engine shutdown request",
468 deadline,
469 handle.send(Op::Shutdown),
470 )
471 .await
472 {
473 Ok(Ok(())) => {}
474 Ok(Err(error)) => {
475 failure.get_or_insert_with(|| format!("engine shutdown request failed: {error}"));
476 }
477 Err(error) => {
478 failure.get_or_insert(error);
479 }
480 }
481 match golden::complete_within("engine shutdown", deadline, &mut run).await {
482 Ok(Ok(_)) => {}
483 Ok(Err(error)) => {
484 failure.get_or_insert_with(|| format!("engine task failed: {error}"));
485 }
486 Err(error) => {
487 failure.get_or_insert(error);
488 run.abort();
489 let _ = run.await;
490 }
491 }
492 let mut rx = rx.write().await;
493 while let Ok(event) = rx.try_recv() {
494 events.push(event);
495 }
496 TurnRecord { events, failure }
497 }
498
499 fn rule_matches(when: &Value, projected: &Value) -> bool {
500 if when["event"].as_str() != projected["event"].as_str() {
501 return false;
502 }
503 if let Some(needle) = when.get("delta_contains").and_then(Value::as_str) {
504 return projected["delta"]
505 .as_str()
506 .is_some_and(|delta| delta.contains(needle));
507 }
508 true
509 }
510
511 fn protocol_ids() -> ProtocolIds {
512 ProtocolIds {
513 thread_id: ThreadId::from_string("conformance-thread"),
514 session_id: SessionId::from_string("conformance-session"),
515 }
516 }
517
518 /// Project, drop, mask and order engine events into golden lines.
519 pub(super) fn normalize_events(events: &[Event], masker: &mut Masker) -> Vec<Value> {
520 let ids = protocol_ids();
521 let mut lines: Vec<Value> = Vec::new();
522 for event in events {
523 let mut value = serde_json::to_value(event_to_protocol(event, &ids)).expect("EventMsg");
524 let kind = value["event"].as_str().unwrap_or_default().to_string();
525 if kind == "tool_call_heartbeat" {
526 continue;
527 }
528 if let Some(map) = value.as_object_mut() {
529 map.remove("thread_id");
530 map.remove("session_id");
531 for owned in ["tool_catalog", "system_prompt"] {
532 if map.get(owned).is_some_and(|value| !value.is_null()) {
533 map.insert(owned.to_string(), json!(PREFIX_OWNED_BY_PROMPT_FAMILY));
534 }
535 }
536 }
537 masker.value(&mut value);
538 lines.push(golden::canonical(&value));
539 }
540 order_parallel_batches(&mut lines);
541 order_parallel_completions(&mut lines);
542 lines
543 }
544
545 /// The activity and tool events a parallel batch emits.
546 fn batch_rank(line: &Value) -> Option<(u8, &'static str)> {
547 match line["event"].as_str() {
548 Some("tool_execution_started") => Some((0, "tool_call_id")),
549 Some("operation_activity_started") => Some((1, "span_id")),
550 Some("operation_activity_completed") => Some((2, "span_id")),
551 Some("tool_call_complete") => Some((3, "tool_call_id")),
552 _ => None,
553 }
554 }
555
556 /// Whether `run` is a legal interleaving of parallel tools: every call starts
557 /// executing at most once, every span starts once and completes at most once
558 /// after its start, and a tool's completion follows its own activity
559 /// completion. A run that fails this is left in its recorded order so the
560 /// golden reports the violation.
561 fn batch_is_causal(run: &[Value]) -> bool {
562 let mut executing = std::collections::BTreeSet::new();
563 let mut started = std::collections::BTreeSet::new();
564 let mut completed = std::collections::BTreeSet::new();
565 let mut finished_calls = std::collections::BTreeSet::new();
566 for line in run {
567 let span = line["span_id"].as_str().unwrap_or_default();
568 let call = span.split('#').next().unwrap_or_default();
569 match line["event"].as_str() {
570 Some("tool_execution_started") => {
571 if !executing.insert(line["tool_call_id"].as_str().unwrap_or_default()) {
572 return false;
573 }
574 }
575 Some("operation_activity_started") => {
576 if !started.insert(span) {
577 return false;
578 }
579 }
580 Some("operation_activity_completed") => {
581 if !started.contains(span) || !completed.insert(span) {
582 return false;
583 }
584 }
585 Some("tool_call_complete") => {
586 finished_calls.insert(line["tool_call_id"].as_str().unwrap_or_default());
587 }
588 _ => {}
589 }
590 // A tool completion may not precede its own activity completion.
591 if line["event"].as_str() == Some("operation_activity_completed")
592 && finished_calls.contains(call)
593 {
594 return false;
595 }
596 }
597 true
598 }
599
600 /// Parallel tools in one announced batch run concurrently, so one tool can
601 /// start, finish and report before its sibling has started (a blocking-pool
602 /// read that completes before its first poll). The run of execution, activity
603 /// and tool events after the batch's `Executing N ... parallel chunk(s)`
604 /// status is put in one canonical order: execution starts by call id,
605 /// activity starts by span, activity completions by span, tool completions by
606 /// call id. Only a causally valid run is reordered, and every
607 /// event, outcome and boundary is kept.
608 fn order_parallel_batches(lines: &mut [Value]) {
609 let mut at = 0;
610 while at < lines.len() {
611 let announces_batch = lines[at]["event"].as_str() == Some("status")
612 && lines[at]["message"].as_str().is_some_and(|message| {
613 message.starts_with("Executing ") && message.ends_with(" parallel chunk(s)")
614 });
615 at += 1;
616 if !announces_batch {
617 continue;
618 }
619 let start = at;
620 let mut end = start;
621 while end < lines.len() && batch_rank(&lines[end]).is_some() {
622 end += 1;
623 }
624 if batch_is_causal(&lines[start..end]) {
625 lines[start..end].sort_by(|left, right| {
626 let (left_rank, left_key) = batch_rank(left).unwrap_or((0, "span_id"));
627 let (right_rank, right_key) = batch_rank(right).unwrap_or((0, "span_id"));
628 left_rank
629 .cmp(&right_rank)
630 .then_with(|| left[left_key].as_str().cmp(&right[right_key].as_str()))
631 });
632 }
633 at = end;
634 }
635 }
636
637 /// Parallel tools race to report: each emits its activity completion and then
638 /// its tool completion, and under load the two tools' pairs interleave. One
639 /// uninterrupted run of completion events is therefore put in a canonical
640 /// order: activity completions by span, then tool completions by call id.
641 /// Every event, its outcome and the run's boundaries are kept; only the order
642 /// inside the run is normalized.
643 fn order_parallel_completions(lines: &mut [Value]) {
644 fn completion(line: &Value) -> Option<(u8, &'static str)> {
645 match line["event"].as_str() {
646 Some("operation_activity_completed") => Some((0, "span_id")),
647 Some("tool_call_complete") => Some((1, "tool_call_id")),
648 _ => None,
649 }
650 }
651 let mut start = 0;
652 while start < lines.len() {
653 if completion(&lines[start]).is_none() {
654 start += 1;
655 continue;
656 }
657 let mut end = start;
658 while end < lines.len() && completion(&lines[end]).is_some() {
659 end += 1;
660 }
661 lines[start..end].sort_by(|left, right| {
662 let (left_kind, left_key) = completion(left).unwrap_or((0, "span_id"));
663 let (right_kind, right_key) = completion(right).unwrap_or((0, "span_id"));
664 left_kind
665 .cmp(&right_kind)
666 .then_with(|| left[left_key].as_str().cmp(&right[right_key].as_str()))
667 });
668 start = end;
669 }
670 }
671
672 #[test]
673 fn parallel_completion_projection_keeps_outcomes_spans_and_causal_boundaries() {
674 let first = json!({"event": "operation_activity_completed", "span_id": "call_a#1", "outcome": "succeeded"});
675 let second = json!({"event": "operation_activity_completed", "span_id": "call_b#2", "outcome": "failed"});
676 let boundary = json!({"event": "error", "message": "exact error bytes"});
677 let start = json!({"event": "operation_activity_started", "span_id": "call_a#1"});
678 let original = vec![
679 start.clone(),
680 second.clone(),
681 first.clone(),
682 boundary.clone(),
683 second.clone(),
684 start.clone(),
685 first.clone(),
686 ];
687 let expected = vec![
688 start.clone(),
689 first.clone(),
690 second.clone(),
691 boundary,
692 second,
693 start,
694 first,
695 ];
696 let mut normalized = original.clone();
697 order_parallel_completions(&mut normalized);
698 assert_eq!(normalized, expected);
699 assert_eq!(normalized.len(), original.len());
700
701 // Two tools' completion pairs interleaved under load normalize to the
702 // same order as the uninterleaved run.
703 let tool = |id: &str| json!({"event": "tool_call_complete", "tool_call_id": id});
704 let activity = |span: &str| json!({"event": "operation_activity_completed", "span_id": span, "outcome": "succeeded"});
705 let mut interleaved = vec![
706 activity("call_b#2"),
707 tool("call_b"),
708 activity("call_a#1"),
709 tool("call_a"),
710 ];
711 order_parallel_completions(&mut interleaved);
712 assert_eq!(
713 interleaved,
714 vec![
715 activity("call_a#1"),
716 activity("call_b#2"),
717 tool("call_a"),
718 tool("call_b")
719 ]
720 );
721
722 let mut wrong_outcome = original.clone();
723 wrong_outcome[1]["outcome"] = json!("succeeded");
724 order_parallel_completions(&mut wrong_outcome);
725 assert_ne!(wrong_outcome, expected, "wrong outcome was normalized away");
726
727 let mut wrong_span = original;
728 wrong_span[1]["span_id"] = json!("call_other#2");
729 order_parallel_completions(&mut wrong_span);
730 assert_ne!(
731 wrong_span, expected,
732 "wrong span relationship was normalized away"
733 );
734 }
735
736 #[test]
737 fn parallel_batch_projection_orders_legal_interleavings_and_keeps_violations() {
738 let status =
739 json!({"event": "status", "message": "Executing 2 read-only tools in 1 parallel chunk(s)"});
740 let start = |span: &str| json!({"event": "operation_activity_started", "span_id": span});
741 let done = |span: &str, outcome: &str| json!({"event": "operation_activity_completed", "span_id": span, "outcome": outcome});
742 let tool = |id: &str| json!({"event": "tool_call_complete", "tool_call_id": id});
743 let tail = json!({"event": "session_updated"});
744 let canonical = vec![
745 status.clone(),
746 start("a#1"),
747 start("b#2"),
748 done("a#1", "succeeded"),
749 done("b#2", "succeeded"),
750 tool("a"),
751 tool("b"),
752 tail.clone(),
753 ];
754 let with_tail = |run: Vec<Value>| {
755 let mut lines = vec![status.clone()];
756 lines.extend(run);
757 lines.push(tail.clone());
758 lines
759 };
760 // Recorded: both start, then both finish. Hosted CI also saw one tool
761 // finish before its sibling started, and both pairs fully interleaved.
762 for run in [
763 vec![
764 start("a#1"),
765 start("b#2"),
766 done("a#1", "succeeded"),
767 done("b#2", "succeeded"),
768 tool("a"),
769 tool("b"),
770 ],
771 vec![
772 start("a#1"),
773 done("a#1", "succeeded"),
774 start("b#2"),
775 done("b#2", "succeeded"),
776 tool("a"),
777 tool("b"),
778 ],
779 vec![
780 start("a#1"),
781 done("a#1", "succeeded"),
782 tool("a"),
783 start("b#2"),
784 done("b#2", "succeeded"),
785 tool("b"),
786 ],
787 vec![
788 start("b#2"),
789 start("a#1"),
790 done("b#2", "succeeded"),
791 tool("b"),
792 done("a#1", "succeeded"),
793 tool("a"),
794 ],
795 ] {
796 let mut lines = with_tail(run);
797 order_parallel_batches(&mut lines);
798 order_parallel_completions(&mut lines);
799 assert_eq!(lines, canonical);
800 }
801
802 // Outcomes survive the reordering.
803 let mut lines = with_tail(vec![
804 start("a#1"),
805 done("a#1", "failed"),
806 start("b#2"),
807 done("b#2", "succeeded"),
808 tool("a"),
809 tool("b"),
810 ]);
811 order_parallel_batches(&mut lines);
812 assert_eq!(lines[3], done("a#1", "failed"));
813
814 // An illegal run is left exactly as recorded: a completion with no start,
815 // a repeated start, a repeated completion, a tool completion before its
816 // activity completion.
817 for run in [
818 vec![done("a#1", "succeeded"), start("a#1"), tool("a")],
819 vec![
820 start("a#1"),
821 start("a#1"),
822 done("a#1", "succeeded"),
823 tool("a"),
824 ],
825 vec![
826 start("a#1"),
827 done("a#1", "succeeded"),
828 done("a#1", "succeeded"),
829 tool("a"),
830 ],
831 vec![start("a#1"), tool("a"), done("a#1", "succeeded")],
832 ] {
833 let recorded = with_tail(run);
834 let mut lines = recorded.clone();
835 order_parallel_batches(&mut lines);
836 assert_eq!(lines, recorded, "an illegal run was normalized away");
837 }
838
839 // Without an announced parallel batch nothing is reordered: a serial run
840 // that starts its second tool early is a real change.
841 let serial = vec![start("b#2"), done("b#2", "succeeded"), start("a#1")];
842 let mut lines = serial.clone();
843 order_parallel_batches(&mut lines);
844 assert_eq!(lines, serial);
845 }
846
847 fn check_invariants(case: &Value, workspace: &Path, provider: &ScriptedProvider) -> Vec<String> {
848 let mut violations = Vec::new();
849 for invariant in case["invariants"].as_array().into_iter().flatten() {
850 if let Some(file) = invariant
851 .get("workspace_file_absent")
852 .and_then(Value::as_str)
853 && workspace.join(file).exists()
854 {
855 violations.push(format!(
856 "`{file}` exists: a tool side effect ran that the scenario forbids"
857 ));
858 }
859 if let Some(file) = invariant
860 .get("workspace_file_present")
861 .and_then(Value::as_str)
862 && !workspace.join(file).exists()
863 {
864 violations.push(format!(
865 "`{file}` is gone: a tool side effect ran that the scenario forbids"
866 ));
867 }
868 if let Some(max) = invariant.get("max_model_requests").and_then(Value::as_u64)
869 && provider.stream_requests() as u64 > max
870 {
871 violations.push(format!(
872 "{} model requests were issued; at most {max} allowed",
873 provider.stream_requests()
874 ));
875 }
876 }
877 violations
878 }
879
880 fn run_case(name: &str, case: &Value, failures: &mut Failures) {
881 run_case_with_deadline(name, case, failures, event_deadline());
882 }
883
884 fn run_case_with_deadline(name: &str, case: &Value, failures: &mut Failures, deadline: Duration) {
885 let sandbox = Sandbox::new(case);
886 let workspace = sandbox.workspace.clone();
887 let (record, provider) =
888 run_scripted_turn_with_deadline(&sandbox, case, &case["provider_script"], deadline);
889 if let Some(error) = record.failure {
890 failures.push(name, error);
891 return;
892 }
893 let mut masker = sandbox.masker(VOLATILE_KEYS);
894 let mut lines = normalize_events(&record.events, &mut masker);
895 let summary = json!({
896 "model_requests": provider.stream_requests(),
897 "non_streaming_requests": provider.other_requests(),
898 "workspace_after": workspace_listing(&workspace),
899 });
900 lines.push(json!({ "harness_summary": summary }));
901
902 let violations = check_invariants(case, &workspace, &provider);
903 if !violations.is_empty() {
904 failures.push(name, format!("invariant broken: {}", violations.join("; ")));
905 return;
906 }
907
908 failures.record(
909 name,
910 golden::check_golden(
911 &golden::family_dir(FAMILY).join(format!("{name}.golden.jsonl")),
912 &golden::jsonl(&lines),
913 ),
914 );
915 }
916
917 #[test]
918 fn harness_timeout_rejects_a_real_stalled_turn() {
919 let mut case = golden::read_case(FAMILY, "plain_answer");
920 case["provider_script"][0]["then"] = json!("hang");
921 case["provider_script"][0]["events"] = json!([]);
922 let mut failures = Failures::default();
923 // This is the same recording path as normal cases. In update mode it must
924 // still fail and must not create this deliberately absent golden.
925 let name = "harness_timeout_control";
926 let path = golden::family_dir(FAMILY).join(format!("{name}.golden.jsonl"));
927 assert!(!path.exists());
928 run_case_with_deadline(name, &case, &mut failures, Duration::from_secs(1));
929 assert!(failures.contains("harness timeout"));
930 assert!(
931 !path.exists(),
932 "an incomplete turn was recorded as a golden"
933 );
934 }
935
936 #[test]
937 fn golden_turn_events_match() {
938 // The goldens carry the span numbers of one pass over the cases in an
939 // otherwise idle process (`one_tool_call` #1, `parallel_tool_calls` #2
940 // and #3); replay that numbering whatever else this process runs.
941 let _spans = codewhale_engine::core::engine::pin_replay_span_sequence();
942 let names = golden::case_names(FAMILY);
943 let mut failures = Failures::default();
944 for name in &names {
945 let case = golden::read_case(FAMILY, name);
946 run_case(name, &case, &mut failures);
947 }
948 failures.finish(FAMILY, names.len());
949 }
950
950 lines RUST