escher-execution-engine 0.1.2

Production-ready async execution engine for system commands
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# Output & Error Stream Storage - Detailed Explanation

This document explains exactly where and how stdout/stderr are stored during command execution in the Execution Engine.

---

## Quick Answer

**Output streams are stored in TWO places simultaneously:**

1. **In-Memory**`ExecutionState.stdout` and `ExecutionState.stderr` (String fields)
2. **Event Stream** → Emitted line-by-line to `EventHandler` implementations

---

## Detailed Flow

### 1. Data Structure: ExecutionState

**Location**: [src/types.rs:277-287](src/types.rs#L277-L287)

```rust
pub struct ExecutionState {
    pub id: Uuid,
    pub request: ExecutionRequest,
    pub status: ExecutionStatus,
    pub started_at: DateTime<Utc>,
    pub completed_at: Option<DateTime<Utc>>,

    // OUTPUT STORAGE - Two String buffers
    pub stdout: String,  // ← Accumulates all stdout lines
    pub stderr: String,  // ← Accumulates all stderr lines

    pub exit_code: Option<i32>,
    pub error: Option<String>,
}
```

**Initialization**: [src/types.rs:298-299](src/types.rs#L298-L299)
```rust
stdout: String::new(),  // Starts empty
stderr: String::new(),  // Starts empty
```

**Storage Location in Engine**: [src/engine.rs:26](src/engine.rs#L26)
```rust
pub struct ExecutionEngine {
    // ...
    executions: Arc<RwLock<HashMap<Uuid, Arc<RwLock<ExecutionState>>>>>,
    //                                          ^^^^^^^^^^^^^^^^^^^^
    //                                          Each execution has its own state
}
```

---

### 2. Capture Process: Spawning the Command

**Location**: [src/executor.rs:66-79](src/executor.rs#L66-L79)

```rust
// Build and spawn command
let mut cmd = build_command(&request)?;
let mut child = cmd.spawn()?;

// Capture stdout and stderr handles from spawned process
let stdout = child.stdout.take()  // ← Take ownership of stdout pipe
    .ok_or_else(|| ExecutionError::Internal("Failed to capture stdout"))?;

let stderr = child.stderr.take()  // ← Take ownership of stderr pipe
    .ok_or_else(|| ExecutionError::Internal("Failed to capture stderr"))?;
```

**Key Point**: These are `tokio::process::ChildStdout` and `ChildStderr` - async streams from the child process.

---

### 3. Parallel Streaming: Two Background Tasks

**Location**: [src/executor.rs:81-92](src/executor.rs#L81-L92)

```rust
// Spawn STDOUT streaming task
let state_clone = Arc::clone(&state);
let event_handler = self.event_handler.clone();
let stdout_handle = tokio::spawn(async move {
    Self::stream_stdout_static(execution_id, stdout, state_clone, event_handler).await
});

// Spawn STDERR streaming task (in parallel)
let state_clone = Arc::clone(&state);
let event_handler = self.event_handler.clone();
let stderr_handle = tokio::spawn(async move {
    Self::stream_stderr_static(execution_id, stderr, state_clone, event_handler).await
});
```

**Important**: Both streams are processed **in parallel**, not sequentially!

---

### 4. Line-by-Line Accumulation: STDOUT

**Location**: [src/executor.rs:203-232](src/executor.rs#L203-L232)

```rust
async fn stream_stdout_static(
    execution_id: uuid::Uuid,
    stdout: ChildStdout,
    state: Arc<RwLock<ExecutionState>>,
    event_handler: Option<Arc<dyn EventHandler>>,
) -> Result<()> {
    // Create async buffered reader
    let reader = BufReader::new(stdout);
    let mut lines = reader.lines();

    // Read line by line
    while let Some(line) = lines.next_line().await? {

        // 1. EMIT EVENT (if handler exists)
        if let Some(handler) = &event_handler {
            handler.handle_event(ExecutionEvent::Stdout {
                execution_id,
                line: line.clone(),
                timestamp: Utc::now(),
            }).await;
        }

        // 2. APPEND TO IN-MEMORY STATE
        let mut state_lock = state.write().await;  // Acquire write lock

        // Add newline if not first line
        if !state_lock.stdout.is_empty() {
            state_lock.stdout.push('\n');
        }

        // Append the line
        state_lock.stdout.push_str(&line);

        // Lock released automatically when state_lock drops
    }

    Ok(())
}
```

**Flow**:
1. Read one line from stdout pipe
2. **Emit event** → Sent to EventHandler (e.g., Tauri frontend)
3. **Append to state** → Added to `ExecutionState.stdout` String
4. Repeat until stream closes

---

### 5. Line-by-Line Accumulation: STDERR

**Location**: [src/executor.rs:234-263](src/executor.rs#L234-L263)

```rust
async fn stream_stderr_static(
    execution_id: uuid::Uuid,
    stderr: ChildStderr,
    state: Arc<RwLock<ExecutionState>>,
    event_handler: Option<Arc<dyn EventHandler>>,
) -> Result<()> {
    let reader = BufReader::new(stderr);
    let mut lines = reader.lines();

    while let Some(line) = lines.next_line().await? {

        // 1. EMIT EVENT
        if let Some(handler) = &event_handler {
            handler.handle_event(ExecutionEvent::Stderr {
                execution_id,
                line: line.clone(),
                timestamp: Utc::now(),
            }).await;
        }

        // 2. APPEND TO IN-MEMORY STATE
        let mut state_lock = state.write().await;
        if !state_lock.stderr.is_empty() {
            state_lock.stderr.push('\n');
        }
        state_lock.stderr.push_str(&line);
    }

    Ok(())
}
```

**Identical logic to stdout**, just different field (`stderr` instead of `stdout`).

---

### 6. Waiting for Completion

**Location**: [src/executor.rs:94-104](src/executor.rs#L94-L104)

```rust
// Wait for process with timeout
let wait_result = self.wait_with_timeout_and_cancel(
    child,
    timeout_ms,
    cancel_token
).await;

// Wait for output streaming to complete
let _ = stdout_handle.await;  // ← Wait for stdout task to finish
let _ = stderr_handle.await;  // ← Wait for stderr task to finish
```

**Critical**: Process might finish before all output is read, so we explicitly wait for streaming tasks.

---

### 7. Final Result Assembly

**Location**: [src/executor.rs:107-132](src/executor.rs#L107-L132)

```rust
let result = match wait_result {
    Ok(exit_status) => {
        let exit_code = exit_status.code().unwrap_or(-1);
        let state_lock = state.read().await;  // Read lock

        let final_status = if exit_code == 0 {
            ExecutionStatus::Completed
        } else {
            ExecutionStatus::Failed
        };

        // Create result - COPIES from state
        let result = ExecutionResult {
            id: execution_id,
            status: final_status,
            success: exit_code == 0,
            exit_code,
            stdout: state_lock.stdout.clone(),  // ← Copy accumulated stdout
            stderr: state_lock.stderr.clone(),  // ← Copy accumulated stderr
            duration: (Utc::now() - state_lock.started_at).to_std().unwrap_or(Duration::from_secs(0)),
            started_at: state_lock.started_at,
            completed_at: Some(Utc::now()),
            error: None,
        };

        Ok(result)
    }
    // ... handle errors
}
```

**Key**: Output is **copied** from `ExecutionState` into `ExecutionResult`.

---

## Storage Lifecycle

### Timeline:

```
1. Command Spawned
   └─ ExecutionState created with empty stdout/stderr

2. Process Running
   ├─ STDOUT Task: Read line → Emit event → Append to state.stdout
   └─ STDERR Task: Read line → Emit event → Append to state.stderr
      (Both happen in parallel, continuously)

3. Process Completes
   ├─ Wait for both streaming tasks to finish
   └─ Copy stdout/stderr from state into ExecutionResult

4. Result Returned
   └─ ExecutionResult contains complete output

5. State Retained in Memory
   └─ ExecutionState remains in engine.executions HashMap
      (Until cleanup task removes it after retention period)
```

---

## Memory Implications

### Per Execution Memory Usage:

```rust
ExecutionState memory footprint:
- Uuid: 16 bytes
- ExecutionRequest: ~100-500 bytes (depends on command length)
- ExecutionStatus: 1 byte (enum)
- Timestamps: 24 bytes (DateTime<Utc> = 12 bytes each)
- stdout: Variable (all stdout accumulated as String)
- stderr: Variable (all stderr accumulated as String)
- exit_code: 8 bytes (Option<i32>)
- error: Variable (Option<String>)

Total: ~150 bytes + stdout.len() + stderr.len() + request size
```

### Example Calculation:

| Command | Stdout Size | Stderr Size | State Size | Notes |
|---------|-------------|-------------|------------|-------|
| `echo hello` | 6 bytes | 0 bytes | ~156 bytes | Minimal |
| `aws s3 ls` | 10 KB | 0 bytes | ~10.15 KB | Typical |
| `docker build` | 500 KB | 50 KB | ~550 KB | Build logs |
| Verbose script | 5 MB | 100 KB | ~5.1 MB | Large output |
| **Runaway command** | 100 MB | 10 MB | ~110 MB | **Problem!** |

### Memory Risk:

**Current Implementation** (as of this analysis):
- **No size limit enforced** during streaming
-`max_output_size_bytes` config exists but not checked
- ⚠️ **Risk**: Commands with unbounded output can cause OOM

**Example OOM Scenario**:
```bash
# This would accumulate 1GB in memory!
cat /dev/urandom | head -c 1000000000
```

---

## What About Log Files?

### Log Writing (Separate from Memory Storage)

**Location**: [src/executor.rs:100-103](src/executor.rs#L100-L103)

```rust
// Write logs if successful
if let Ok(ref exec_result) = result {
    let _ = executor.write_logs(execution_id, exec_result).await;
}
```

**Logs are written AFTER execution completes**, not during streaming.

**Log Contents**: The complete stdout+stderr from `ExecutionResult` is written to a file.

**Log Path**: Determined by `config.log_dir` or temp directory.

**Important**: Logs are **separate** from in-memory storage. They're a persistent copy.

---

## Retrieval: How Users Get Output

### Method 1: Get Result (After Completion)

```rust
let result = engine.get_result(execution_id).await?;
println!("Stdout: {}", result.stdout);  // ← Complete output as String
println!("Stderr: {}", result.stderr);  // ← Complete errors as String
```

**Source**: Copied from `ExecutionState` → `ExecutionResult`

### Method 2: Wait for Completion

```rust
let result = engine.wait_for_completion(execution_id).await?;
// Same as get_result but blocks until complete
```

### Method 3: Real-Time Events (During Execution)

```rust
// In Tauri app or custom EventHandler
impl EventHandler for MyHandler {
    async fn handle_event(&self, event: ExecutionEvent) {
        match event {
            ExecutionEvent::Stdout { execution_id, line, timestamp } => {
                println!("STDOUT: {}", line);  // ← Line-by-line as it happens
            }
            ExecutionEvent::Stderr { execution_id, line, timestamp } => {
                eprintln!("STDERR: {}", line);  // ← Line-by-line as it happens
            }
            _ => {}
        }
    }
}
```

**Source**: Emitted during streaming, before accumulation in state

---

## Comparison with Design Specification

### What Design Expected (architecture.md):

- ✅ Line-by-line streaming via async IO
- ✅ Parallel stdout/stderr processing
- ✅ Event emission per line
- ✅ Accumulated in execution state
- ⚠️ **Output size limiting** (MISSING - not enforced)

### What's Implemented:

- ✅ All streaming mechanisms work correctly
- ✅ State storage pattern matches design
- ✅ Event system fully functional
-**No size checking during accumulation**
-**`OversizedOutputStrategy` not applied**

---

## Critical Issue: Unbounded Memory Growth

### Problem:

Current implementation appends **indefinitely** to `state.stdout` and `state.stderr`:

```rust
// No size check!
state_lock.stdout.push_str(&line);
```

### Solution Needed:

Add size tracking and apply `OversizedOutputStrategy`:

```rust
// Pseudocode fix:
while let Some(line) = lines.next_line().await? {
    let mut state_lock = state.write().await;

    // Check size before appending
    if state_lock.stdout.len() + line.len() > max_output_size {
        match config.oversized_output_strategy {
            TruncateWithWarning => {
                state_lock.stdout.push_str("\n[... output truncated ...]");
                break;  // Stop reading
            }
            FailExecution => {
                return Err(ExecutionError::OutputSizeExceeded);
            }
            StreamToFile => {
                // Switch to file streaming
            }
        }
    }

    state_lock.stdout.push_str(&line);
}
```

---

## Summary

### Where Output is Stored:

1. **Primary Storage**: `ExecutionState.stdout` / `ExecutionState.stderr` (in-memory Strings)
2. **Secondary Storage**: Log files (written after completion)
3. **Event Stream**: Emitted line-by-line to EventHandler (not stored, just transmitted)

### How It's Stored:

- **Format**: Plain text Strings (not structured)
- **Accumulation**: Line-by-line with newline separators
- **Concurrency**: Protected by `RwLock<ExecutionState>`
- **Lifetime**: Retained until cleanup task removes execution

### Current Status:

- **Streaming works correctly**
-**Storage mechanism is sound**
-**Size limiting not enforced** (HIGH PRIORITY FIX NEEDED)

### Memory Usage Per Execution:

```
~150 bytes (metadata) + stdout.len() + stderr.len()
```

For 1000 executions with average 100 KB output each:
```
1000 * (150 bytes + 100 KB) ≈ 100 MB
```

**Without cleanup or size limiting, memory grows unbounded!**