1use rusqlite::types::ValueRef;
4use serde::{Deserialize, Serialize};
5use serde_json::{Value, json};
6use std::collections::BTreeMap;
7use std::fmt;
8use std::io::{BufRead, BufReader, Write};
9use std::path::{Path, PathBuf};
10use std::process::{Child, ChildStdin, Command, Stdio};
11use std::sync::mpsc::{self, Receiver, RecvTimeoutError, TrySendError};
12use std::thread::JoinHandle;
13use std::time::{Duration, Instant};
14
15const MAX_KERNEL_OUTPUT_BYTES: usize = 1024 * 1024;
16const MAX_KERNEL_CODE_BYTES: usize = 512 * 1024;
17const MAX_KERNEL_SESSIONS: usize = 32;
18const MAX_KERNEL_MESSAGES: usize = 64;
19const DEFAULT_KERNEL_TIMEOUT: Duration = Duration::from_secs(30);
20
21const PYTHON_WORKER: &str = r#"
22import ast, contextlib, io, json, sys, traceback
23state = {"__name__": "__glass_kernel__"}
24for line in sys.stdin:
25 try:
26 request = json.loads(line)
27 source = request["code"]
28 output = io.StringIO()
29 result = None
30 with contextlib.redirect_stdout(output), contextlib.redirect_stderr(output):
31 tree = ast.parse(source, mode="exec")
32 if tree.body and isinstance(tree.body[-1], ast.Expr):
33 prefix = ast.Module(body=tree.body[:-1], type_ignores=[])
34 exec(compile(prefix, "<glass>", "exec"), state, state)
35 result = eval(compile(ast.Expression(tree.body[-1].value), "<glass>", "eval"), state, state)
36 else:
37 exec(compile(tree, "<glass>", "exec"), state, state)
38 response = {"ok": True, "output": output.getvalue(), "value": repr(result) if result is not None else None}
39 except Exception:
40 response = {"ok": False, "output": "", "error": traceback.format_exc(limit=16)}
41 print(json.dumps(response, ensure_ascii=True), flush=True)
42"#;
43
44const JAVASCRIPT_WORKER: &str = r#"
45const readline = require('readline');
46const vm = require('vm');
47const context = vm.createContext({});
48const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
49input.on('line', async (line) => {
50 let request;
51 try {
52 request = JSON.parse(line);
53 const output = [];
54 context.console = {
55 log: (...values) => output.push(values.map(String).join(' ')),
56 error: (...values) => output.push(values.map(String).join(' ')),
57 };
58 let value = new vm.Script(request.code, { filename: '<glass>' })
59 .runInContext(context, { timeout: request.timeoutMs });
60 if (value && typeof value.then === 'function') value = await value;
61 process.stdout.write(JSON.stringify({ ok: true, output: output.join('\n') + (output.length ? '\n' : ''), value: value === undefined ? null : String(value) }) + '\n');
62 } catch (error) {
63 process.stdout.write(JSON.stringify({ ok: false, output: '', error: String(error && error.stack || error) }) + '\n');
64 }
65});
66"#;
67
68pub type KernelResult<T> = Result<T, KernelError>;
69
70#[derive(Debug)]
71pub enum KernelError {
72 Io(std::io::Error),
73 Sql(rusqlite::Error),
74 InvalidInput(String),
75 Unavailable(String),
76 Protocol(String),
77 Execution(String),
78 Timeout(String),
79}
80
81impl fmt::Display for KernelError {
82 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
83 match self {
84 Self::Io(error) => write!(formatter, "kernel I/O error: {error}"),
85 Self::Sql(error) => write!(formatter, "SQL kernel error: {error}"),
86 Self::InvalidInput(message) => write!(formatter, "invalid kernel input: {message}"),
87 Self::Unavailable(message) => write!(formatter, "kernel unavailable: {message}"),
88 Self::Protocol(message) => write!(formatter, "kernel protocol error: {message}"),
89 Self::Execution(message) => write!(formatter, "kernel execution failed: {message}"),
90 Self::Timeout(message) => write!(formatter, "kernel execution timed out: {message}"),
91 }
92 }
93}
94
95impl std::error::Error for KernelError {}
96
97impl From<std::io::Error> for KernelError {
98 fn from(error: std::io::Error) -> Self {
99 Self::Io(error)
100 }
101}
102
103impl From<rusqlite::Error> for KernelError {
104 fn from(error: rusqlite::Error) -> Self {
105 Self::Sql(error)
106 }
107}
108
109#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
110#[serde(rename_all = "camelCase")]
111pub enum KernelKind {
112 Python,
113 JavaScript,
114 Shell,
115 Sql,
116}
117
118#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
119#[serde(rename_all = "camelCase")]
120pub enum KernelState {
121 Ready,
122 Failed,
123 Stopped,
124}
125
126#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
127#[serde(rename_all = "camelCase")]
128pub struct KernelSnapshot {
129 pub name: String,
130 pub kind: KernelKind,
131 pub state: KernelState,
132 pub executions: u64,
133 pub actor_id: String,
134 pub workspace_revision: u64,
135}
136
137#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
138#[serde(rename_all = "camelCase")]
139pub struct KernelExecution {
140 pub name: String,
141 pub kind: KernelKind,
142 pub sequence: u64,
143 pub actor_id: String,
144 pub workspace_revision: u64,
145 pub duration_ms: u64,
146 pub output: String,
147 pub value: Value,
148 pub truncated: bool,
149}
150
151enum KernelBackend {
152 Json(JsonProcessKernel),
153 Shell(ShellKernel),
154 Sql(SqlKernel),
155}
156
157struct KernelSession {
158 snapshot: KernelSnapshot,
159 backend: KernelBackend,
160}
161
162pub struct KernelManager {
163 root: PathBuf,
164 sessions: BTreeMap<String, KernelSession>,
165}
166
167impl KernelManager {
168 pub fn new(root: impl AsRef<Path>) -> KernelResult<Self> {
169 Ok(Self {
170 root: root.as_ref().canonicalize()?,
171 sessions: BTreeMap::new(),
172 })
173 }
174
175 pub fn start(&mut self, name: &str, kind: KernelKind, actor_id: &str) -> KernelResult<()> {
176 validate_name(name, "kernel")?;
177 validate_name(actor_id, "kernel actor")?;
178 if self.sessions.contains_key(name) {
179 return Err(KernelError::InvalidInput(format!(
180 "kernel {name} already exists"
181 )));
182 }
183 if self.sessions.len() == MAX_KERNEL_SESSIONS {
184 return Err(KernelError::InvalidInput(format!(
185 "kernel session limit is {MAX_KERNEL_SESSIONS}"
186 )));
187 }
188 let backend = match kind {
189 KernelKind::Python => KernelBackend::Json(JsonProcessKernel::spawn(
190 &self.root,
191 if cfg!(windows) { "python" } else { "python3" },
192 &["-u", "-c", PYTHON_WORKER],
193 )?),
194 KernelKind::JavaScript => KernelBackend::Json(JsonProcessKernel::spawn(
195 &self.root,
196 "node",
197 &["-e", JAVASCRIPT_WORKER],
198 )?),
199 KernelKind::Shell => KernelBackend::Shell(ShellKernel::spawn(&self.root)?),
200 KernelKind::Sql => KernelBackend::Sql(SqlKernel::new()?),
201 };
202 self.sessions.insert(
203 name.to_string(),
204 KernelSession {
205 snapshot: KernelSnapshot {
206 name: name.to_string(),
207 kind,
208 state: KernelState::Ready,
209 executions: 0,
210 actor_id: actor_id.to_string(),
211 workspace_revision: 0,
212 },
213 backend,
214 },
215 );
216 Ok(())
217 }
218
219 pub fn execute(
220 &mut self,
221 name: &str,
222 code: &str,
223 actor_id: &str,
224 workspace_revision: u64,
225 timeout: Option<Duration>,
226 ) -> KernelResult<KernelExecution> {
227 validate_code(code)?;
228 validate_name(actor_id, "kernel actor")?;
229 let timeout = timeout.unwrap_or(DEFAULT_KERNEL_TIMEOUT);
230 if timeout.is_zero() || timeout > Duration::from_secs(600) {
231 return Err(KernelError::InvalidInput(
232 "kernel timeout must be between 1 ms and 600 seconds".into(),
233 ));
234 }
235 let session = self
236 .sessions
237 .get_mut(name)
238 .ok_or_else(|| KernelError::InvalidInput(format!("unknown kernel {name}")))?;
239 if session.snapshot.state != KernelState::Ready {
240 return Err(KernelError::Execution(format!(
241 "kernel {name} is not ready"
242 )));
243 }
244 let started = Instant::now();
245 let result = match &mut session.backend {
246 KernelBackend::Json(kernel) => kernel.execute(code, timeout),
247 KernelBackend::Shell(kernel) => kernel.execute(code, timeout),
248 KernelBackend::Sql(kernel) => kernel.execute(code),
249 };
250 let (output, value, truncated) = match result {
251 Ok(result) => result,
252 Err(error) => {
253 if matches!(error, KernelError::Protocol(_) | KernelError::Timeout(_)) {
254 session.snapshot.state = KernelState::Failed;
255 }
256 return Err(error);
257 }
258 };
259 session.snapshot.executions = session
260 .snapshot
261 .executions
262 .checked_add(1)
263 .ok_or_else(|| KernelError::Protocol("kernel sequence overflowed".into()))?;
264 session.snapshot.actor_id = actor_id.to_string();
265 session.snapshot.workspace_revision = workspace_revision;
266 Ok(KernelExecution {
267 name: name.to_string(),
268 kind: session.snapshot.kind,
269 sequence: session.snapshot.executions,
270 actor_id: actor_id.to_string(),
271 workspace_revision,
272 duration_ms: started.elapsed().as_millis() as u64,
273 output,
274 value,
275 truncated,
276 })
277 }
278
279 pub fn snapshots(&self) -> impl Iterator<Item = &KernelSnapshot> {
280 self.sessions.values().map(|session| &session.snapshot)
281 }
282
283 pub fn snapshot(&self, name: &str) -> Option<&KernelSnapshot> {
284 self.sessions.get(name).map(|session| &session.snapshot)
285 }
286
287 pub fn stop(&mut self, name: &str) -> KernelResult<KernelSnapshot> {
288 let mut session = self
289 .sessions
290 .remove(name)
291 .ok_or_else(|| KernelError::InvalidInput(format!("unknown kernel {name}")))?;
292 session.stop();
293 Ok(session.snapshot.clone())
294 }
295
296 pub fn reset(&mut self, name: &str, actor_id: &str) -> KernelResult<()> {
297 let kind = self
298 .sessions
299 .get(name)
300 .ok_or_else(|| KernelError::InvalidInput(format!("unknown kernel {name}")))?
301 .snapshot
302 .kind;
303 self.stop(name)?;
304 self.start(name, kind, actor_id)
305 }
306}
307
308impl KernelSession {
309 fn stop(&mut self) {
310 match &mut self.backend {
311 KernelBackend::Json(kernel) => kernel.stop(),
312 KernelBackend::Shell(kernel) => kernel.stop(),
313 KernelBackend::Sql(_) => {}
314 }
315 self.snapshot.state = KernelState::Stopped;
316 }
317}
318
319impl Drop for KernelSession {
320 fn drop(&mut self) {
321 self.stop();
322 }
323}
324
325struct JsonProcessKernel {
326 child: Child,
327 stdin: ChildStdin,
328 responses: Receiver<KernelResult<Value>>,
329 reader: Option<JoinHandle<()>>,
330 stderr_drain: Option<JoinHandle<()>>,
331}
332
333impl JsonProcessKernel {
334 fn spawn(root: &Path, program: &str, arguments: &[&str]) -> KernelResult<Self> {
335 let mut child = Command::new(program)
336 .args(arguments)
337 .current_dir(root)
338 .stdin(Stdio::piped())
339 .stdout(Stdio::piped())
340 .stderr(Stdio::piped())
341 .spawn()
342 .map_err(|error| {
343 if error.kind() == std::io::ErrorKind::NotFound {
344 KernelError::Unavailable(format!("{program} was not found"))
345 } else {
346 KernelError::Io(error)
347 }
348 })?;
349 let stdin = child
350 .stdin
351 .take()
352 .ok_or_else(|| KernelError::Protocol("kernel stdin was unavailable".into()))?;
353 let stdout = child
354 .stdout
355 .take()
356 .ok_or_else(|| KernelError::Protocol("kernel stdout was unavailable".into()))?;
357 let stderr = child
358 .stderr
359 .take()
360 .ok_or_else(|| KernelError::Protocol("kernel stderr was unavailable".into()))?;
361 let (sender, responses) = mpsc::sync_channel(MAX_KERNEL_MESSAGES);
362 let reader = std::thread::spawn(move || {
363 for line in BufReader::new(stdout).lines() {
364 let response = line.map_err(KernelError::Io).and_then(|line| {
365 if line.len() > MAX_KERNEL_OUTPUT_BYTES {
366 return Err(KernelError::Protocol(
367 "kernel response exceeded the output limit".into(),
368 ));
369 }
370 serde_json::from_str(&line).map_err(|error| {
371 KernelError::Protocol(format!("invalid kernel response: {error}"))
372 })
373 });
374 match sender.try_send(response) {
375 Ok(()) => {}
376 Err(TrySendError::Full(_) | TrySendError::Disconnected(_)) => break,
377 }
378 }
379 });
380 let stderr_drain = std::thread::spawn(move || {
381 let mut stderr = stderr;
382 let _ = std::io::copy(&mut stderr, &mut std::io::sink());
383 });
384 Ok(Self {
385 child,
386 stdin,
387 responses,
388 reader: Some(reader),
389 stderr_drain: Some(stderr_drain),
390 })
391 }
392
393 fn execute(&mut self, code: &str, timeout: Duration) -> KernelResult<KernelOutput> {
394 serde_json::to_writer(
395 &mut self.stdin,
396 &json!({"code": code, "timeoutMs": timeout.as_millis()}),
397 )
398 .map_err(|error| {
399 KernelError::Protocol(format!("could not encode kernel input: {error}"))
400 })?;
401 self.stdin.write_all(b"\n")?;
402 self.stdin.flush()?;
403 let response = match self.responses.recv_timeout(timeout) {
404 Ok(response) => response?,
405 Err(RecvTimeoutError::Timeout) => {
406 self.stop();
407 return Err(KernelError::Timeout(format!(
408 "execution exceeded {} ms",
409 timeout.as_millis()
410 )));
411 }
412 Err(RecvTimeoutError::Disconnected) => {
413 return Err(KernelError::Protocol(
414 "kernel response stream closed".into(),
415 ));
416 }
417 };
418 if response.get("ok").and_then(Value::as_bool) != Some(true) {
419 return Err(KernelError::Execution(
420 response
421 .get("error")
422 .and_then(Value::as_str)
423 .unwrap_or("kernel returned an unsuccessful response")
424 .to_string(),
425 ));
426 }
427 bounded_output(
428 response
429 .get("output")
430 .and_then(Value::as_str)
431 .unwrap_or_default(),
432 response.get("value").cloned().unwrap_or(Value::Null),
433 )
434 }
435
436 fn stop(&mut self) {
437 if self.child.try_wait().ok().flatten().is_none() {
438 let _ = self.child.kill();
439 let _ = self.child.wait();
440 }
441 if let Some(reader) = self.reader.take() {
442 let _ = reader.join();
443 }
444 if let Some(stderr_drain) = self.stderr_drain.take() {
445 let _ = stderr_drain.join();
446 }
447 }
448}
449
450struct ShellKernel {
451 child: Child,
452 stdin: ChildStdin,
453 lines: Receiver<KernelResult<String>>,
454 reader: Option<JoinHandle<()>>,
455 sequence: u64,
456}
457
458impl ShellKernel {
459 #[cfg(unix)]
460 fn spawn(root: &Path) -> KernelResult<Self> {
461 let mut child = Command::new("/bin/sh")
462 .current_dir(root)
463 .stdin(Stdio::piped())
464 .stdout(Stdio::piped())
465 .stderr(Stdio::null())
466 .spawn()?;
467 let stdin = child
468 .stdin
469 .take()
470 .ok_or_else(|| KernelError::Protocol("shell stdin was unavailable".into()))?;
471 let stdout = child
472 .stdout
473 .take()
474 .ok_or_else(|| KernelError::Protocol("shell stdout was unavailable".into()))?;
475 let (sender, lines) = mpsc::sync_channel(MAX_KERNEL_MESSAGES);
476 let reader = std::thread::spawn(move || {
477 for line in BufReader::new(stdout).lines() {
478 let line = line.map_err(KernelError::Io);
479 match sender.try_send(line) {
480 Ok(()) => {}
481 Err(TrySendError::Full(_) | TrySendError::Disconnected(_)) => break,
482 }
483 }
484 });
485 Ok(Self {
486 child,
487 stdin,
488 lines,
489 reader: Some(reader),
490 sequence: 0,
491 })
492 }
493
494 #[cfg(windows)]
495 fn spawn(_root: &Path) -> KernelResult<Self> {
496 Err(KernelError::Unavailable(
497 "persistent shell kernels are not yet available on Windows".into(),
498 ))
499 }
500
501 #[cfg(unix)]
502 fn execute(&mut self, code: &str, timeout: Duration) -> KernelResult<KernelOutput> {
503 self.sequence = self
504 .sequence
505 .checked_add(1)
506 .ok_or_else(|| KernelError::Protocol("shell sequence overflowed".into()))?;
507 let marker = format!("__GLASS_SHELL_{}__", self.sequence);
508 writeln!(
509 self.stdin,
510 "{{\n{code}\n}} 2>&1\nglass_status=$?\nprintf '{marker}:%s\\n' \"$glass_status\""
511 )?;
512 self.stdin.flush()?;
513 let deadline = Instant::now() + timeout;
514 let mut output = String::new();
515 let mut truncated = false;
516 loop {
517 let remaining = deadline.saturating_duration_since(Instant::now());
518 if remaining.is_zero() {
519 self.stop();
520 return Err(KernelError::Timeout(format!(
521 "execution exceeded {} ms",
522 timeout.as_millis()
523 )));
524 }
525 let line = match self.lines.recv_timeout(remaining) {
526 Ok(line) => line?,
527 Err(RecvTimeoutError::Timeout) => {
528 self.stop();
529 return Err(KernelError::Timeout(format!(
530 "execution exceeded {} ms",
531 timeout.as_millis()
532 )));
533 }
534 Err(RecvTimeoutError::Disconnected) => {
535 return Err(KernelError::Protocol("shell output stream closed".into()));
536 }
537 };
538 let marker_prefix = format!("{marker}:");
539 if let Some(marker_index) = line.find(&marker_prefix) {
540 append_bounded(&mut output, &line[..marker_index], &mut truncated);
541 let status = &line[marker_index + marker_prefix.len()..];
542 let status = status.parse::<i32>().map_err(|_| {
543 KernelError::Protocol("shell returned an invalid exit status".into())
544 })?;
545 if status != 0 {
546 return Err(KernelError::Execution(format!(
547 "shell command exited with status {status}: {output}"
548 )));
549 }
550 return Ok((output, json!({"exitCode": status}), truncated));
551 }
552 append_bounded(&mut output, &line, &mut truncated);
553 append_bounded(&mut output, "\n", &mut truncated);
554 }
555 }
556
557 #[cfg(windows)]
558 fn execute(&mut self, _code: &str, _timeout: Duration) -> KernelResult<KernelOutput> {
559 Err(KernelError::Unavailable(
560 "persistent shell kernels are not yet available on Windows".into(),
561 ))
562 }
563
564 fn stop(&mut self) {
565 if self.child.try_wait().ok().flatten().is_none() {
566 let _ = self.child.kill();
567 let _ = self.child.wait();
568 }
569 if let Some(reader) = self.reader.take() {
570 let _ = reader.join();
571 }
572 }
573}
574
575struct SqlKernel {
576 connection: rusqlite::Connection,
577}
578
579impl SqlKernel {
580 fn new() -> KernelResult<Self> {
581 Ok(Self {
582 connection: rusqlite::Connection::open_in_memory()?,
583 })
584 }
585
586 fn execute(&mut self, code: &str) -> KernelResult<KernelOutput> {
587 let leading = code.trim_start().to_ascii_uppercase();
588 if !["SELECT", "WITH", "PRAGMA", "EXPLAIN"]
589 .iter()
590 .any(|keyword| leading.starts_with(keyword))
591 {
592 self.connection.execute_batch(code)?;
593 return Ok((String::new(), Value::Null, false));
594 }
595 let mut statement = self.connection.prepare(code)?;
596 if statement.column_count() == 0 {
597 drop(statement);
598 self.connection.execute_batch(code)?;
599 return Ok((String::new(), Value::Null, false));
600 }
601 let names = statement
602 .column_names()
603 .into_iter()
604 .map(str::to_string)
605 .collect::<Vec<_>>();
606 let column_count = names.len();
607 let rows = statement.query_map([], |row| {
608 let mut record = serde_json::Map::new();
609 for (index, name) in names.iter().enumerate().take(column_count) {
610 record.insert(name.clone(), sql_value(row.get_ref(index)?));
611 }
612 Ok(Value::Object(record))
613 })?;
614 let mut values = Vec::new();
615 for row in rows.take(100_000) {
616 values.push(row?);
617 if serde_json::to_vec(&values)
618 .map_err(|error| KernelError::Protocol(error.to_string()))?
619 .len()
620 > MAX_KERNEL_OUTPUT_BYTES
621 {
622 values.pop();
623 return Ok((String::new(), Value::Array(values), true));
624 }
625 }
626 Ok((String::new(), Value::Array(values), false))
627 }
628}
629
630type KernelOutput = (String, Value, bool);
631
632fn sql_value(value: ValueRef<'_>) -> Value {
633 match value {
634 ValueRef::Null => Value::Null,
635 ValueRef::Integer(value) => json!(value),
636 ValueRef::Real(value) => json!(value),
637 ValueRef::Text(value) => String::from_utf8_lossy(value).into_owned().into(),
638 ValueRef::Blob(value) => json!({"blobBytes": value.len()}),
639 }
640}
641
642fn bounded_output(output: &str, value: Value) -> KernelResult<KernelOutput> {
643 let mut retained = String::new();
644 let mut truncated = false;
645 append_bounded(&mut retained, output, &mut truncated);
646 let encoded_value = serde_json::to_vec(&value).map_err(|error| {
647 KernelError::Protocol(format!("could not encode kernel value: {error}"))
648 })?;
649 if encoded_value.len() > MAX_KERNEL_OUTPUT_BYTES {
650 return Ok((retained, Value::Null, true));
651 }
652 Ok((retained, value, truncated))
653}
654
655fn append_bounded(output: &mut String, value: &str, truncated: &mut bool) {
656 let remaining = MAX_KERNEL_OUTPUT_BYTES.saturating_sub(output.len());
657 if value.len() <= remaining {
658 output.push_str(value);
659 } else {
660 let boundary = value
661 .char_indices()
662 .take_while(|(index, _)| *index <= remaining)
663 .map(|(index, _)| index)
664 .last()
665 .unwrap_or(0);
666 output.push_str(&value[..boundary]);
667 *truncated = true;
668 }
669}
670
671fn validate_code(code: &str) -> KernelResult<()> {
672 if code.is_empty() || code.len() > MAX_KERNEL_CODE_BYTES {
673 return Err(KernelError::InvalidInput(format!(
674 "kernel code must contain 1..={MAX_KERNEL_CODE_BYTES} bytes"
675 )));
676 }
677 Ok(())
678}
679
680fn validate_name(name: &str, description: &str) -> KernelResult<()> {
681 if name.is_empty()
682 || name.len() > 128
683 || !name
684 .chars()
685 .all(|character| character.is_ascii_alphanumeric() || "-_.".contains(character))
686 {
687 return Err(KernelError::InvalidInput(format!(
688 "{description} must be 1..=128 ASCII letters, digits, '-', '_' or '.'"
689 )));
690 }
691 Ok(())
692}
693
694#[cfg(test)]
695mod tests {
696 use super::*;
697 use std::sync::atomic::{AtomicU64, Ordering};
698
699 static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
700
701 fn root() -> PathBuf {
702 let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
703 let root = std::env::temp_dir().join(format!(
704 "glass-kernel-manager-{}-{sequence}",
705 std::process::id()
706 ));
707 std::fs::create_dir_all(&root).unwrap();
708 root
709 }
710
711 #[test]
712 fn python_kernel_preserves_state_and_attribution() {
713 let root = root();
714 let mut kernels = KernelManager::new(&root).unwrap();
715 kernels
716 .start("python", KernelKind::Python, "human")
717 .unwrap();
718 kernels
719 .execute("python", "answer = 40", "human", 1, None)
720 .unwrap();
721 let result = kernels
722 .execute("python", "answer + 2", "agent", 2, None)
723 .unwrap();
724 assert_eq!(result.value, "42");
725 assert_eq!(result.actor_id, "agent");
726 assert_eq!(result.workspace_revision, 2);
727 assert_eq!(kernels.snapshot("python").unwrap().executions, 2);
728 kernels.stop("python").unwrap();
729 std::fs::remove_dir_all(root).unwrap();
730 }
731
732 #[cfg(unix)]
733 #[test]
734 fn shell_kernel_preserves_environment_and_directory_state() {
735 let root = root();
736 let mut kernels = KernelManager::new(&root).unwrap();
737 kernels.start("shell", KernelKind::Shell, "human").unwrap();
738 kernels
739 .execute("shell", "value=glass", "human", 1, None)
740 .unwrap();
741 let result = kernels
742 .execute("shell", "printf '%s' \"$value\"", "human", 1, None)
743 .unwrap();
744 assert_eq!(result.output, "glass");
745 kernels.stop("shell").unwrap();
746 std::fs::remove_dir_all(root).unwrap();
747 }
748
749 #[test]
750 fn sql_kernel_preserves_tables_and_returns_structured_rows() {
751 let root = root();
752 let mut kernels = KernelManager::new(&root).unwrap();
753 kernels.start("sql", KernelKind::Sql, "agent").unwrap();
754 kernels
755 .execute(
756 "sql",
757 "CREATE TABLE inventory (sku TEXT, count INTEGER); INSERT INTO inventory VALUES ('x', 0);",
758 "agent",
759 1,
760 None,
761 )
762 .unwrap();
763 let result = kernels
764 .execute("sql", "SELECT sku, count FROM inventory", "agent", 1, None)
765 .unwrap();
766 assert_eq!(result.value[0]["sku"], "x");
767 assert_eq!(result.value[0]["count"], 0);
768 std::fs::remove_dir_all(root).unwrap();
769 }
770
771 #[test]
772 fn kernel_names_code_and_timeouts_fail_closed() {
773 assert!(validate_name("python-1", "kernel").is_ok());
774 assert!(validate_name("../escape", "kernel").is_err());
775 assert!(validate_code("").is_err());
776 assert!(validate_code(&"x".repeat(MAX_KERNEL_CODE_BYTES + 1)).is_err());
777 }
778}