返回 CodeWhale
host_tests.rs
根目录 / crates / engine / src / tools / pdf / host_tests.rs
1 //! Real pinned Host plus local fake parser. These are author acceptance cases;
2 //! the parent must regenerate the canonical bundle/pin and run them after apply.
3 use super::*;
4 use crate::extension_host::test_support::node_for_tests;
5 use crate::extension_host::{ExtensionHostManager, ExtensionHostOptions, TestManagerGuard};
6 use crate::tools::spec::{ToolContext, ToolResult, ToolSpec};
7 use codewhale_plugins::activation::TestPolicyGuard;
8 use codewhale_runtime::features::{Feature, Features};
9 use std::sync::Arc;
10
11 fn context(root: &Path, host: bool) -> ToolContext {
12 let mut flags = Features::with_defaults();
13 if host {
14 flags.enable(Feature::PdfHost);
15 }
16 ToolContext::new(root).with_features(flags)
17 }
18 fn new_manager(node: PathBuf, root: &Path) -> Arc<ExtensionHostManager> {
19 Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
20 runtime: codewhale_config::extension_host::ExtensionHostRuntime::Node,
21 node_override: Some(node),
22 root: Some(root.join("host")),
23 ..ExtensionHostOptions::default()
24 }))
25 }
26 #[cfg(any(test, feature = "test-support"))]
27 #[cfg(unix)]
28 fn parser(root: &Path, script: &str) -> PathBuf {
29 use std::os::unix::fs::PermissionsExt;
30 let path = root.join("pdftotext");
31 std::fs::write(&path, format!("#!/bin/sh\n{script}\n")).unwrap();
32 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap();
33 path
34 }
35 fn decision(code: &str, message: Option<&str>) -> ToolResult {
36 ToolResult {
37 content: String::new(),
38 success: true,
39 metadata: Some(json!({"kind":"pdf_decision","code":code,"message":message})),
40 }
41 }
42
43 #[test]
44 fn pdf_host_is_independent_and_defaults_to_rust() {
45 let mut flags = Features::with_defaults();
46 assert!(!flags.enabled(Feature::PdfHost));
47 assert_eq!(
48 codewhale_runtime::features::feature_from_key("pdf_host"),
49 Some(Feature::PdfHost)
50 );
51 flags.enable(Feature::PdfHost);
52 assert!(!flags.enabled(Feature::ExtensionHost));
53 assert!(!flags.enabled(Feature::SpeechHost));
54 }
55
56 #[cfg(unix)]
57 #[tokio::test(flavor = "current_thread")]
58 async fn real_host_pdf_matches_default_stdout_page_arguments_and_faults() {
59 let _home = crate::test_support::SealedHome::new();
60 let _policy = TestPolicyGuard::extension_host(false);
61 let Some(node) = node_for_tests("real_host_pdf_parity") else {
62 return;
63 };
64 let root = tempfile::tempdir().unwrap();
65 let manager = new_manager(node, root.path());
66 let _manager = TestManagerGuard::install(Arc::clone(&manager));
67 let _secret =
68 crate::test_support::EnvVarGuard::set("DEEPSEEK_API_KEY", "test-only-parent-secret");
69 let input = root.path().join("input with spaces.pdf");
70 std::fs::write(&input, b"%PDF-1.7\nfixture\n%%EOF").unwrap();
71 for (index, script) in [
72 "printf 'args:%s\\n' \"$*\"; printf 'page one\\fpage two\\n'",
73 "printf 'bad\\033[31m\\000\\nnext' >&2; exit 2",
74 "exit 3",
75 "[ -z \"${DEEPSEEK_API_KEY+x}\" ] || exit 9; printf clean",
76 ]
77 .into_iter()
78 .enumerate()
79 {
80 let binary = parser(root.path(), script);
81 let rust = context(root.path(), false);
82 let host = context(root.path(), true);
83 let expected = extract_path(
84 &input,
85 Some((2, 4)),
86 PdfTextCommand::test(binary.as_os_str(), Duration::from_secs(10), None)
87 .with_context(&rust),
88 )
89 .await;
90 let actual = extract_path(
91 &input,
92 Some((2, 4)),
93 PdfTextCommand::test(binary.as_os_str(), Duration::from_secs(10), None)
94 .with_context(&host),
95 )
96 .await;
97 assert_eq!(actual, expected);
98 if let Ok(text) = actual
99 && index == 0
100 {
101 assert!(text.contains("-layout -f 2 -l 4"));
102 assert!(text.contains(input.to_string_lossy().as_ref()));
103 }
104 }
105 let missing = root.path().join("missing-parser");
106 assert_eq!(
107 extract_path(
108 &input,
109 None,
110 PdfTextCommand::test(missing.as_os_str(), Duration::from_secs(10), None)
111 .with_context(&context(root.path(), true))
112 )
113 .await,
114 Err(PdfTextError::BinaryUnavailable)
115 );
116 assert!(!codewhale_plugins::activation::extension_host_policy_enabled());
117 manager.shutdown().await;
118 }
119
120 #[cfg(unix)]
121 #[tokio::test(flavor = "current_thread")]
122 async fn real_host_read_file_and_web_document_use_the_shared_pdf_job() {
123 let _home = crate::test_support::SealedHome::new();
124 let _policy = TestPolicyGuard::extension_host(false);
125 let Some(node) = node_for_tests("real_host_pdf_consumers") else {
126 return;
127 };
128 let root = tempfile::tempdir().unwrap();
129 parser(root.path(), "printf 'page one\\fpage two\\n'");
130 let search = std::env::join_paths(std::iter::once(root.path().to_path_buf()).chain(
131 std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()),
132 ))
133 .unwrap();
134 let _path = crate::test_support::EnvVarGuard::set("PATH", search);
135 let manager = new_manager(node, root.path());
136 let _manager = TestManagerGuard::install(Arc::clone(&manager));
137 let bytes = b"%PDF-1.7\nfixture\n%%EOF";
138 std::fs::write(root.path().join("input.pdf"), bytes).unwrap();
139 let rust = context(root.path(), false);
140 let host = context(root.path(), true);
141 let tool = crate::tools::file::ReadFileTool;
142 let input = json!({"path":"input.pdf","pages":"1-2"});
143 let expected = tool.execute(input.clone(), &rust).await.unwrap();
144 let actual = tool.execute(input, &host).await.unwrap();
145 assert_eq!(actual.content, expected.content);
146 assert_eq!(actual.metadata, expected.metadata);
147 assert_eq!(actual.success, expected.success);
148 let expected = crate::tools::web::extract::extract_document(
149 "https://example.com/input.pdf",
150 Some("application/pdf"),
151 bytes,
152 false,
153 Some(&rust),
154 )
155 .await
156 .unwrap();
157 let actual = crate::tools::web::extract::extract_document(
158 "https://example.com/input.pdf",
159 Some("application/pdf"),
160 bytes,
161 false,
162 Some(&host),
163 )
164 .await
165 .unwrap();
166 assert_eq!(actual.text, expected.text);
167 assert_eq!(actual.markdown, expected.markdown);
168 assert_eq!(actual.pdf_pages, expected.pdf_pages);
169 let invalid = tool
170 .execute(json!({"path":"missing.pdf","pages":"bad"}), &host)
171 .await
172 .unwrap_err();
173 assert!(invalid.to_string().contains("Failed to read"));
174 manager.shutdown().await;
175 }
176
177 #[cfg(unix)]
178 #[tokio::test]
179 async fn pdf_private_output_guards_cannot_be_overridden_by_host_decisions() {
180 use std::os::unix::process::ExitStatusExt;
181 let output = |overflow, success| PdfProcessOutcome {
182 output: Ok((
183 BoundedOutput {
184 bytes: b"private extracted document".to_vec(),
185 truncated: overflow,
186 },
187 BoundedOutput {
188 bytes: vec![],
189 truncated: false,
190 },
191 std::process::ExitStatus::from_raw(if success { 0 } else { 2 << 8 }),
192 )),
193 };
194 assert!(
195 output(true, true)
196 .into_host_text(decision("success", None))
197 .is_err()
198 );
199 assert!(
200 output(false, false)
201 .into_host_text(decision("success", None))
202 .is_err()
203 );
204 assert!(
205 output(false, true)
206 .into_host_text(decision("execution", Some("fabricated error")))
207 .is_err()
208 );
209 assert!(
210 PdfProcessOutcome {
211 output: Err(PdfTextError::Cancelled)
212 }
213 .into_host_text(decision("success", None))
214 .is_err()
215 );
216 assert_eq!(
217 PdfProcessOutcome {
218 output: Err(PdfTextError::Cancelled)
219 }
220 .into_host_text(decision("cancelled", Some("ignored"))),
221 Err(PdfTextError::Cancelled)
222 );
223 let mut result = decision("success", None);
224 result.metadata.as_mut().unwrap()["extra"] = json!(true);
225 assert!(output(false, true).into_host_text(result).is_err());
226 let full = PdfProcessOutcome {
227 output: Ok((
228 BoundedOutput {
229 bytes: vec![b'x'; MAX_PDF_STDOUT_BYTES],
230 truncated: false,
231 },
232 BoundedOutput {
233 bytes: vec![],
234 truncated: false,
235 },
236 std::process::ExitStatus::from_raw(0),
237 )),
238 };
239 let wire = serde_json::to_vec(&full.projection()).unwrap();
240 assert!(wire.len() < 512);
241 assert!(!String::from_utf8(wire).unwrap().contains("xxxxx"));
242 assert_eq!(
243 full.into_host_text(decision("success", None))
244 .unwrap()
245 .len(),
246 MAX_PDF_STDOUT_BYTES
247 );
248 }
249
250 #[cfg(unix)]
251 #[tokio::test(flavor = "current_thread")]
252 async fn real_host_pdf_cancel_timeout_and_host_refusal_never_replay() {
253 let _home = crate::test_support::SealedHome::new();
254 let _policy = TestPolicyGuard::extension_host(false);
255 let Some(node) = node_for_tests("real_host_pdf_cancel") else {
256 return;
257 };
258 let root = tempfile::tempdir().unwrap();
259 let marker = root.path().join("launched");
260 let binary = parser(
261 root.path(),
262 &format!("printf x >> '{}'; exec /bin/sleep 30", marker.display()),
263 );
264 let input = root.path().join("input.pdf");
265 std::fs::write(&input, b"%PDF-1.7\n%%EOF").unwrap();
266 let manager = new_manager(node, root.path());
267 let _manager = TestManagerGuard::install(Arc::clone(&manager));
268 // Warm only the already admitted bounded Host; timeout is measured after startup.
269 let fast = parser(root.path(), "printf warm");
270 extract_path(
271 &input,
272 None,
273 PdfTextCommand::test(fast.as_os_str(), Duration::from_secs(10), None)
274 .with_context(&context(root.path(), true)),
275 )
276 .await
277 .unwrap();
278 parser(
279 root.path(),
280 &format!("printf x >> '{}'; exec /bin/sleep 30", marker.display()),
281 );
282 let cancel = CancellationToken::new();
283 let ctx = context(root.path(), true).with_cancel_token(cancel.clone());
284 let stop = cancel.clone();
285 let marker_clone = marker.clone();
286 tokio::spawn(async move {
287 for _ in 0..1000 {
288 if std::fs::read(&marker_clone).is_ok_and(|bytes| bytes == b"x") {
289 stop.cancel();
290 return;
291 }
292 tokio::time::sleep(Duration::from_millis(5)).await;
293 }
294 panic!("parser never launched");
295 });
296 let started = std::time::Instant::now();
297 assert_eq!(
298 extract_path(
299 &input,
300 None,
301 PdfTextCommand::test(binary.as_os_str(), Duration::from_secs(10), None)
302 .with_context(&ctx)
303 )
304 .await,
305 Err(PdfTextError::Cancelled)
306 );
307 assert!(started.elapsed() < Duration::from_secs(5));
308 assert_eq!(std::fs::read(&marker).unwrap(), b"x");
309 let error = extract_path(
310 &input,
311 None,
312 PdfTextCommand::test(binary.as_os_str(), Duration::from_millis(100), None)
313 .with_context(&context(root.path(), true)),
314 )
315 .await
316 .unwrap_err();
317 assert_eq!(error, PdfTextError::TimedOut);
318 assert_eq!(std::fs::read(&marker).unwrap(), b"xx");
319 manager.shutdown().await;
320 drop(_manager);
321 let unavailable = new_manager(root.path().join("no-runtime"), root.path());
322 let _manager = TestManagerGuard::install(unavailable);
323 let error = extract_path(
324 &input,
325 None,
326 PdfTextCommand::test(binary.as_os_str(), Duration::from_secs(2), None)
327 .with_context(&context(root.path(), true)),
328 )
329 .await
330 .unwrap_err();
331 assert!(error.to_string().contains("no Rust fallback"));
332 assert_eq!(std::fs::read(&marker).unwrap(), b"xx");
333 }
334
335 #[cfg(unix)]
336 #[tokio::test]
337 async fn pdf_driver_cancellation_kills_descendants_and_keeps_staged_input_alive() {
338 let root = tempfile::tempdir().unwrap();
339 let marker = root.path().join("child-alive");
340 let binary = parser(
341 root.path(),
342 &format!(
343 "(/bin/sleep 1; printf alive > '{}') &\n/bin/sleep 30",
344 marker.display()
345 ),
346 );
347 let cancel = CancellationToken::new();
348 let stop = cancel.clone();
349 tokio::spawn(async move {
350 tokio::time::sleep(Duration::from_millis(100)).await;
351 stop.cancel();
352 });
353 assert_eq!(
354 extract_bytes(
355 b"%PDF-1.7\n%%EOF",
356 None,
357 PdfTextCommand::test(binary.as_os_str(), Duration::from_secs(10), Some(&cancel))
358 )
359 .await,
360 Err(PdfTextError::Cancelled)
361 );
362 tokio::time::sleep(Duration::from_millis(1100)).await;
363 assert!(
364 !marker.exists(),
365 "parser descendant must be terminated with its parent"
366 );
367 parser(
368 root.path(),
369 "/bin/sleep 0.1; cat \"$2\"; printf '\\fpage two\\n'",
370 );
371 let text = extract_bytes(
372 b"%PDF-1.7\nstaged stays present",
373 None,
374 PdfTextCommand::test(binary.as_os_str(), Duration::from_secs(10), None),
375 )
376 .await
377 .unwrap();
378 assert!(text.starts_with("%PDF-1.7\nstaged stays present"));
379 }
380
381 #[tokio::test]
382 async fn pdf_core_terminal_status_precedes_a_generic_host_refusal() {
383 let refusal =
384 || ToolError::execution_failed("Builtin runner failed; no Rust fallback was attempted");
385 let now = tokio::time::Instant::now();
386 assert_eq!(
387 host_terminal_error(refusal(), now, None),
388 PdfTextError::TimedOut
389 );
390 let cancel = CancellationToken::new();
391 cancel.cancel();
392 assert_eq!(
393 host_terminal_error(refusal(), now, Some(&cancel)),
394 PdfTextError::Cancelled
395 );
396 assert_eq!(
397 host_terminal_error(
398 ToolError::cancelled("broker cancelled"),
399 now + Duration::from_secs(1),
400 None
401 ),
402 PdfTextError::Cancelled
403 );
404 let error = host_terminal_error(refusal(), now + Duration::from_secs(1), None);
405 assert!(matches!(error, PdfTextError::Execution(_)));
406 assert!(error.to_string().contains("no Rust fallback"));
407 }
408
408 lines RUST