1use std::fmt;
8use std::sync::Arc;
9
10use serde::{Deserialize, Serialize};
11
12use super::super::invocation::{
13 CapabilityFailureMode, CapabilityInvocation, CapabilityObservationV1,
14};
15use super::comparison_receipt::{
16 ComparisonDecision, ComparisonReceipt, QualityCheck, decide, evaluate_quality,
17};
18use super::rtk_shell::{CapabilityFailure, RtkShellAdapter};
19use crate::core::ocla::{OclaError, OclaResult};
20
21#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
23pub struct QualityAssessment {
24 pub check: QualityCheck,
25 pub native_score: u64,
26 pub external_score: Option<u64>,
27}
28
29#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
31pub struct StructuralQualityAssessment {
32 pub structurally_equal: bool,
33 pub quality_floor_passed: bool,
34 pub native_output_tokens: u64,
35 pub rtk_output_tokens: u64,
36}
37
38#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
40pub enum ShadowDecision {
41 #[serde(rename = "external_preferred")]
42 ExternalPreferred,
43 #[serde(rename = "native_preferred")]
44 NativePreferred,
45 #[serde(rename = "inconclusive")]
46 Inconclusive,
47 #[serde(rename = "external_unavailable")]
48 ExternalUnavailable,
49 #[serde(rename = "LOWER_ETPAO_POLICY_EQUIVALENT")]
50 LowerEtpaoPolicyEquivalent,
51 #[serde(rename = "QUALITY_FLOOR_FAILED")]
52 QualityFloorFailed,
53 #[serde(rename = "CAPABILITY_UNAVAILABLE")]
54 CapabilityUnavailable,
55}
56
57impl ShadowDecision {
58 #[must_use]
60 pub const fn label(self) -> &'static str {
61 match self {
62 Self::ExternalPreferred => "external_preferred",
63 Self::NativePreferred => "native_preferred",
64 Self::Inconclusive => "inconclusive",
65 Self::ExternalUnavailable => "external_unavailable",
66 Self::LowerEtpaoPolicyEquivalent => "LOWER_ETPAO_POLICY_EQUIVALENT",
67 Self::QualityFloorFailed => "QUALITY_FLOOR_FAILED",
68 Self::CapabilityUnavailable => "CAPABILITY_UNAVAILABLE",
69 }
70 }
71}
72
73impl From<ComparisonDecision> for ShadowDecision {
74 fn from(decision: ComparisonDecision) -> Self {
75 match decision {
76 ComparisonDecision::ExternalPreferred { .. } => Self::ExternalPreferred,
77 ComparisonDecision::NativePreferred { .. } => Self::NativePreferred,
78 ComparisonDecision::Inconclusive { .. } => Self::Inconclusive,
79 ComparisonDecision::ExternalUnavailable => Self::ExternalUnavailable,
80 }
81 }
82}
83
84#[derive(Clone, Debug, Serialize)]
86pub struct ShadowComparisonReport {
87 pub receipt: ComparisonReceipt,
88 pub decision: ShadowDecision,
89 pub quality: QualityAssessment,
90 pub native_observation: CapabilityObservationV1,
91 pub rtk_observation: CapabilityObservationV1,
92 pub tokens_saved: i64,
93 pub latency_difference_ms: i64,
94 pub quality_assessment: StructuralQualityAssessment,
95 pub rtk_failure: Option<CapabilityFailure>,
96 pub production_unchanged: bool,
98}
99
100#[derive(Clone, Default)]
102pub struct ShadowRunner {
103 adapter: Option<Arc<RtkShellAdapter>>,
104}
105
106impl fmt::Debug for ShadowRunner {
107 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
108 formatter
109 .debug_struct("ShadowRunner")
110 .field("adapter_configured", &self.adapter.is_some())
111 .finish()
112 }
113}
114
115impl ShadowRunner {
116 #[must_use]
118 pub const fn new() -> Self {
119 Self { adapter: None }
120 }
121
122 #[must_use]
124 pub fn with_adapter(adapter: RtkShellAdapter) -> Self {
125 Self {
126 adapter: Some(Arc::new(adapter)),
127 }
128 }
129
130 #[must_use]
132 pub fn with_shared_adapter(adapter: Arc<RtkShellAdapter>) -> Self {
133 Self {
134 adapter: Some(adapter),
135 }
136 }
137
138 #[must_use]
140 #[allow(clippy::needless_pass_by_value)]
141 pub fn compare(
142 &self,
143 task_id: impl Into<String>,
144 native_observation: CapabilityObservationV1,
145 external_observation: Option<CapabilityObservationV1>,
146 ) -> ShadowComparisonReport {
147 let quality_check = evaluate_quality(&native_observation, external_observation.as_ref());
148 let native_score = quality_score(&native_observation, 100);
149 let external_score = external_observation
150 .as_ref()
151 .and_then(|observation| observation.metrics.get("quality_score").copied());
152 let decision = decide(
153 native_observation.output_tokens,
154 external_observation
155 .as_ref()
156 .map(|observation| observation.output_tokens),
157 &quality_check,
158 );
159 let native_for_report = native_observation.clone();
160 let rtk_for_report = external_observation.clone().unwrap_or_else(|| {
161 unavailable_observation(
162 &native_for_report,
163 &CapabilityFailure::new_for_report("external observation unavailable"),
164 )
165 });
166 let structural_equal =
167 observations_structurally_equal(&native_for_report, external_observation.as_ref());
168 ShadowComparisonReport {
169 receipt: ComparisonReceipt::new(
170 task_id,
171 native_observation,
172 external_observation.clone(),
173 decision,
174 quality_check.clone(),
175 ),
176 decision: decision.into(),
177 quality: QualityAssessment {
178 check: quality_check.clone(),
179 native_score,
180 external_score,
181 },
182 native_observation: native_for_report.clone(),
183 rtk_observation: rtk_for_report.clone(),
184 tokens_saved: signed_delta(
185 native_for_report.output_tokens,
186 external_observation
187 .as_ref()
188 .map_or(0, |observation| observation.output_tokens),
189 ),
190 latency_difference_ms: signed_delta(
191 native_for_report.latency_ms,
192 external_observation
193 .as_ref()
194 .map_or(0, |observation| observation.latency_ms),
195 ),
196 quality_assessment: StructuralQualityAssessment {
197 structurally_equal: structural_equal,
198 quality_floor_passed: quality_check.meets_floor(),
199 native_output_tokens: native_for_report.output_tokens,
200 rtk_output_tokens: rtk_for_report.output_tokens,
201 },
202 rtk_failure: external_observation
203 .is_none()
204 .then(|| CapabilityFailure::new_for_report("external observation unavailable")),
205 production_unchanged: true,
206 }
207 }
208
209 pub fn run(&self, invocation: CapabilityInvocation) -> OclaResult<ShadowComparisonReport> {
211 let Some(adapter) = self.adapter.as_ref() else {
212 return Err(OclaError::InvalidRequest(
213 "shadow runner has no RTK adapter configured".to_string(),
214 ));
215 };
216 let native = adapter.observe_native(&invocation)?;
217 let native_observation = native.observation.clone();
218 match adapter.observe_rtk(&invocation) {
219 Ok(rtk) => Ok(self.report_for_pair(invocation, native_observation, rtk.observation)),
220 Err(failure) => Ok(self.report_for_failure(invocation, native_observation, failure)),
221 }
222 }
223
224 pub fn compare_preserving<T>(
229 &self,
230 production_response: &T,
231 invocation: CapabilityInvocation,
232 ) -> OclaResult<ShadowComparisonReport> {
233 let _production_response = production_response;
234 self.run(invocation)
235 }
236
237 fn report_for_pair(
238 &self,
239 invocation: CapabilityInvocation,
240 native_observation: CapabilityObservationV1,
241 rtk_observation: CapabilityObservationV1,
242 ) -> ShadowComparisonReport {
243 let structural_equal =
244 observations_structurally_equal(&native_observation, Some(&rtk_observation));
245 let quality_check = if !native_observation.success || !rtk_observation.success {
246 QualityCheck::QualityFloorFailed
247 } else if structural_equal {
248 evaluate_quality(&native_observation, Some(&rtk_observation))
249 } else {
250 QualityCheck::QualityFloorFailed
251 };
252 let old_decision = decide(
253 native_observation.output_tokens,
254 Some(rtk_observation.output_tokens),
255 &quality_check,
256 );
257 let quality_floor_passed =
258 structural_equal && rtk_observation.success && quality_check.meets_floor();
259 let decision = if quality_floor_passed
260 && rtk_observation.output_tokens <= native_observation.output_tokens
261 {
262 ShadowDecision::LowerEtpaoPolicyEquivalent
263 } else {
264 ShadowDecision::QualityFloorFailed
265 };
266 self.build_report(
267 invocation,
268 native_observation,
269 rtk_observation,
270 old_decision,
271 decision,
272 quality_check,
273 structural_equal,
274 quality_floor_passed,
275 None,
276 )
277 }
278
279 fn report_for_failure(
280 &self,
281 invocation: CapabilityInvocation,
282 native_observation: CapabilityObservationV1,
283 failure: CapabilityFailure,
284 ) -> ShadowComparisonReport {
285 let rtk_observation = unavailable_observation(&native_observation, &failure);
286 self.build_report(
287 invocation,
288 native_observation,
289 rtk_observation,
290 ComparisonDecision::ExternalUnavailable,
291 ShadowDecision::CapabilityUnavailable,
292 QualityCheck::QualityFloorFailed,
293 false,
294 false,
295 Some(failure),
296 )
297 }
298
299 #[allow(clippy::too_many_arguments)]
300 fn build_report(
301 &self,
302 invocation: CapabilityInvocation,
303 native_observation: CapabilityObservationV1,
304 rtk_observation: CapabilityObservationV1,
305 old_decision: ComparisonDecision,
306 decision: ShadowDecision,
307 quality_check: QualityCheck,
308 structural_equal: bool,
309 quality_floor_passed: bool,
310 rtk_failure: Option<CapabilityFailure>,
311 ) -> ShadowComparisonReport {
312 let native_score = quality_score(&native_observation, 100);
313 let external_score = Some(quality_score(&rtk_observation, 0));
314 ShadowComparisonReport {
315 receipt: ComparisonReceipt::new(
316 invocation.task_id,
317 native_observation.clone(),
318 rtk_failure.is_none().then(|| rtk_observation.clone()),
319 old_decision,
320 quality_check.clone(),
321 ),
322 decision,
323 quality: QualityAssessment {
324 check: quality_check,
325 native_score,
326 external_score,
327 },
328 tokens_saved: signed_delta(
329 native_observation.output_tokens,
330 rtk_observation.output_tokens,
331 ),
332 latency_difference_ms: signed_delta(
333 native_observation.latency_ms,
334 rtk_observation.latency_ms,
335 ),
336 quality_assessment: StructuralQualityAssessment {
337 structurally_equal: structural_equal,
338 quality_floor_passed,
339 native_output_tokens: native_observation.output_tokens,
340 rtk_output_tokens: rtk_observation.output_tokens,
341 },
342 native_observation,
343 rtk_observation,
344 rtk_failure,
345 production_unchanged: true,
346 }
347 }
348}
349
350fn quality_score(observation: &CapabilityObservationV1, default: u64) -> u64 {
351 observation
352 .metrics
353 .get("quality_score")
354 .copied()
355 .unwrap_or(default)
356}
357
358fn signed_delta(native: u64, external: u64) -> i64 {
359 native as i64 - external as i64
360}
361
362fn observations_structurally_equal(
363 native: &CapabilityObservationV1,
364 external: Option<&CapabilityObservationV1>,
365) -> bool {
366 let Some(external) = external else {
367 return false;
368 };
369 native.success
370 && external.success
371 && native.output_ref.is_some()
372 && native.output_ref == external.output_ref
373}
374
375fn unavailable_observation(
376 native: &CapabilityObservationV1,
377 failure: &CapabilityFailure,
378) -> CapabilityObservationV1 {
379 let mut metrics = native.metrics.clone();
380 metrics.insert("capability_unavailable".to_string(), 1);
381 CapabilityObservationV1 {
382 schema_version: native.schema_version,
383 task_id: native.task_id.clone(),
384 capability_id: "rtk-shell-output".to_string(),
385 capability_version: native.capability_version.clone(),
386 success: false,
387 input_tokens: native.input_tokens,
388 output_tokens: 0,
389 latency_ms: 0,
390 failure_mode: Some(failure.failure_mode),
391 output_ref: None,
392 metrics,
393 }
394}
395
396impl CapabilityFailure {
397 fn new_for_report(reason: &str) -> Self {
398 Self {
399 failure_mode: CapabilityFailureMode::Unavailable,
400 reason: reason.to_string(),
401 fallback_available: true,
402 evidence_ref: Some(crate::core::ocla::invocation::evidence_ref(reason)),
403 }
404 }
405}
406
407#[cfg(test)]
408mod tests {
409
410 use super::{ShadowDecision, ShadowRunner};
411 use crate::core::ocla::invocation::{
412 CapabilityInput, CapabilityInvocation, CapabilityObservationV1, PolicyConstraints,
413 };
414
415 fn observation(id: &str, tokens: u64) -> CapabilityObservationV1 {
416 CapabilityObservationV1 {
417 schema_version: 1,
418 task_id: "task".to_string(),
419 capability_id: id.to_string(),
420 capability_version: "v1".to_string(),
421 success: true,
422 input_tokens: 2,
423 output_tokens: tokens,
424 latency_ms: 1,
425 failure_mode: None,
426 output_ref: None,
427 metrics: std::collections::BTreeMap::from([(String::from("quality_score"), 100)]),
428 }
429 }
430
431 fn invocation(command: &str) -> CapabilityInvocation {
432 CapabilityInvocation {
433 task_id: "shadow-task".to_string(),
434 capability_id: "rtk-shell-output".to_string(),
435 capability_version: "1.0.0".to_string(),
436 input: CapabilityInput::ShellCommand {
437 command: command.to_string(),
438 workdir: None,
439 },
440 policy_constraints: PolicyConstraints::default(),
441 timeout_ms: 5_000,
444 }
445 }
446
447 #[test]
448 fn runner_records_external_win_without_routing() {
449 let report = ShadowRunner::new().compare(
450 "task",
451 observation("native", 100),
452 Some(observation("external", 40)),
453 );
454 assert_eq!(report.decision, ShadowDecision::ExternalPreferred);
455 assert!(report.receipt.decision.is_external_preferred());
456 assert!(report.production_unchanged);
457 }
458
459 #[test]
460 fn missing_adapter_is_not_a_production_route() {
461 let production = String::from("native production response");
462 let result =
463 ShadowRunner::new().compare_preserving(&production, invocation("printf unchanged"));
464 assert!(result.is_err());
465 assert_eq!(production, "native production response");
466 }
467
468 #[cfg(unix)]
469 #[test]
470 fn live_shadow_produces_a_valid_observation_pair_without_mutating_response() {
471 use crate::core::ocla::reference_adapters::{RtkConfig, RtkShellAdapter};
472 const TEST_VERSION_PROBE_TIMEOUT_MS: u64 = 10_000;
473 const TEST_INVOCATION_TIMEOUT_MS: u64 = 30_000;
474 let directory = tempfile::tempdir().expect("temporary directory");
475 let binary = directory.path().join("rtk");
476 {
483 use std::io::Write as _;
484 use std::os::unix::fs::OpenOptionsExt as _;
485 let mut file = std::fs::OpenOptions::new()
486 .create(true)
487 .truncate(true)
488 .write(true)
489 .mode(0o755)
490 .open(&binary)
491 .expect("create fake RTK");
492 file.write_all(
493 b"#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then echo 'rtk 1.2.3'; exit 0; fi\nprintf '%s\\n' \"$2\"\n",
494 )
495 .expect("write fake RTK");
496 file.sync_all().expect("flush fake RTK");
497 }
498 let hash = super::super::rtk_shell::sha256_file(&binary).expect("hash fake RTK");
499 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
507 let prepared = loop {
508 match crate::core::process_capture::run_with_output_limits(
509 std::process::Command::new(&binary).arg("--version"),
510 Some(std::time::Duration::from_secs(10)),
511 16 * 1024,
512 16 * 1024,
513 ) {
514 Err(error)
515 if error.contains("Text file busy") && std::time::Instant::now() < deadline =>
516 {
517 std::thread::sleep(std::time::Duration::from_millis(20));
518 }
519 result => break result,
520 }
521 }
522 .expect("prepare RTK fixture");
523 assert!(!prepared.timed_out && prepared.output.status.success());
524 let adapter = RtkShellAdapter::new(
525 RtkConfig::new(&binary)
526 .with_pins("1.2.3", hash)
527 .with_timeout_ms(TEST_INVOCATION_TIMEOUT_MS)
528 .with_test_version_probe_timeout_ms(TEST_VERSION_PROBE_TIMEOUT_MS)
529 .with_working_dir(directory.path())
530 .with_sandbox_root(directory.path()),
531 );
532 let runner = ShadowRunner::with_adapter(adapter);
533 let production = String::from("production response stays native");
534 let mut test_invocation = invocation("printf unchanged");
535 test_invocation.timeout_ms = TEST_INVOCATION_TIMEOUT_MS;
536 let report = runner
537 .compare_preserving(&production, test_invocation)
538 .expect("shadow pair");
539 assert_eq!(production, "production response stays native");
540 assert_eq!(
541 report.native_observation.task_id,
542 report.rtk_observation.task_id
543 );
544 assert!(report.native_observation.output_ref.is_some());
545 assert!(
546 report.rtk_observation.output_ref.is_some(),
547 "RTK output missing: {:?}; observation: {:?}",
548 report.rtk_failure,
549 report.rtk_observation
550 );
551 assert!(matches!(
552 report.decision,
553 ShadowDecision::LowerEtpaoPolicyEquivalent | ShadowDecision::QualityFloorFailed
554 ));
555 assert!(report.production_unchanged);
556 }
557}