ergo-supervisor 0.1.0-alpha.1

Kernel supervisor for deterministic execution, capture, and replay in the Ergo graph engine
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
//! capture
//!
//! Purpose:
//! - Define the kernel-owned capture bundle/session types plus the typed capture
//!   artifact write boundary.
//!
//! Owns:
//! - `CapturingSession` and `CapturingDecisionLog` for bundle accumulation.
//! - `CaptureWriteError` and atomic capture-artifact write policy.
//!
//! Does not own:
//! - Host capture orchestration or product-facing write-error rendering.
//! - Replay validation semantics over completed capture bundles.
//!
//! Connects to:
//! - Host and SDK capture write paths through `write_capture_bundle`.
//! - Supervisor demo/fixture helpers that persist capture artifacts.
//!
//! Safety notes:
//! - Artifact writes remain atomic through temp-file write + sync + rename.
//! - `CaptureWriteError` preserves the exact write stage and chained source so
//!   higher layers can stop flattening capture write failures into strings.

use std::fs::{self, OpenOptions};
use std::io::{ErrorKind, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use ergo_adapter::capture::ExternalEventRecord;
use ergo_adapter::{ExternalEvent, GraphId, RuntimeInvoker};

use crate::{
    CaptureBundle, Constraints, DecisionLog, DecisionLogEntry, EpisodeInvocationRecord, Supervisor,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CaptureJsonStyle {
    Compact,
    Pretty,
}

#[derive(Debug)]
#[non_exhaustive]
pub enum CaptureWriteError {
    CreateOutputDirectory {
        path: PathBuf,
        source: std::io::Error,
    },
    Serialize {
        path: PathBuf,
        style: CaptureJsonStyle,
        source: serde_json::Error,
    },
    InvalidDestination {
        path: PathBuf,
    },
    CreateTempFile {
        destination: PathBuf,
        temp_path: PathBuf,
        source: std::io::Error,
    },
    ExhaustedTempFileAttempts {
        destination: PathBuf,
    },
    WriteTempFile {
        destination: PathBuf,
        temp_path: PathBuf,
        source: std::io::Error,
    },
    SyncTempFile {
        destination: PathBuf,
        temp_path: PathBuf,
        source: std::io::Error,
    },
    RenameTempFile {
        destination: PathBuf,
        temp_path: PathBuf,
        source: std::io::Error,
    },
}

impl std::fmt::Display for CaptureWriteError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::CreateOutputDirectory { source, .. } => {
                write!(f, "create capture output directory: {source}")
            }
            Self::Serialize {
                path,
                style,
                source,
            } => write!(
                f,
                "serialize capture bundle '{}' ({}): {source}",
                path.display(),
                match style {
                    CaptureJsonStyle::Compact => "compact",
                    CaptureJsonStyle::Pretty => "pretty",
                }
            ),
            Self::InvalidDestination { path } => write!(
                f,
                "write capture bundle '{}': destination must include a file name",
                path.display()
            ),
            Self::CreateTempFile {
                destination,
                temp_path,
                source,
            } => write!(
                f,
                "write capture bundle '{}': create temp file '{}': {source}",
                destination.display(),
                temp_path.display()
            ),
            Self::ExhaustedTempFileAttempts { destination } => write!(
                f,
                "write capture bundle '{}': exhausted temp file creation attempts",
                destination.display()
            ),
            Self::WriteTempFile {
                destination,
                temp_path,
                source,
            } => write!(
                f,
                "write capture bundle '{}': write temp file '{}': {source}",
                destination.display(),
                temp_path.display()
            ),
            Self::SyncTempFile {
                destination,
                temp_path,
                source,
            } => write!(
                f,
                "write capture bundle '{}': sync temp file '{}': {source}",
                destination.display(),
                temp_path.display()
            ),
            Self::RenameTempFile {
                destination,
                temp_path,
                source,
            } => write!(
                f,
                "write capture bundle '{}': rename temp file '{}': {source}",
                destination.display(),
                temp_path.display()
            ),
        }
    }
}

impl std::error::Error for CaptureWriteError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::CreateOutputDirectory { source, .. } => Some(source),
            Self::Serialize { source, .. } => Some(source),
            Self::CreateTempFile { source, .. } => Some(source),
            Self::WriteTempFile { source, .. } => Some(source),
            Self::SyncTempFile { source, .. } => Some(source),
            Self::RenameTempFile { source, .. } => Some(source),
            Self::InvalidDestination { .. } | Self::ExhaustedTempFileAttempts { .. } => None,
        }
    }
}

static TEMP_FILE_COUNTER: AtomicU64 = AtomicU64::new(0);
const MAX_TEMP_FILE_ATTEMPTS: u32 = 64;
#[cfg(windows)]
const MAX_REPLACE_RETRY_ATTEMPTS: u32 = 64;
#[cfg(windows)]
const REPLACE_RETRY_DELAY_MS: u64 = 10;

pub struct CapturingDecisionLog<L: DecisionLog> {
    inner: L,
    bundle: Arc<Mutex<CaptureBundle>>,
}

impl<L: DecisionLog> CapturingDecisionLog<L> {
    pub fn new(inner: L, bundle: Arc<Mutex<CaptureBundle>>) -> Self {
        Self { inner, bundle }
    }
}

impl<L: DecisionLog> DecisionLog for CapturingDecisionLog<L> {
    fn log(&self, entry: DecisionLogEntry) {
        self.inner.log(entry.clone());

        let record = EpisodeInvocationRecord::from(&entry);

        let mut guard = self.bundle.lock().expect("capture bundle poisoned");
        guard.decisions.push(record);
    }
}

pub struct CapturingSession<L: DecisionLog, R: RuntimeInvoker> {
    supervisor: Supervisor<CapturingDecisionLog<L>, R>,
    bundle: Arc<Mutex<CaptureBundle>>,
}

impl<L: DecisionLog, R: RuntimeInvoker> CapturingSession<L, R> {
    pub fn new(
        graph_id: GraphId,
        constraints: Constraints,
        inner_log: L,
        runtime: R,
        runtime_provenance: String,
    ) -> Self {
        Self::new_with_provenance(
            graph_id,
            constraints,
            inner_log,
            runtime,
            crate::NO_ADAPTER_PROVENANCE.to_string(),
            runtime_provenance,
        )
    }

    pub fn new_with_provenance(
        graph_id: GraphId,
        constraints: Constraints,
        inner_log: L,
        runtime: R,
        adapter_provenance: String,
        runtime_provenance: String,
    ) -> Self {
        let bundle = Arc::new(Mutex::new(CaptureBundle {
            capture_version: crate::CAPTURE_FORMAT_VERSION.to_string(),
            graph_id: graph_id.clone(),
            config: constraints.clone(),
            events: Vec::new(),
            decisions: Vec::new(),
            adapter_provenance,
            runtime_provenance,
            egress_provenance: None,
        }));

        let capturing_log = CapturingDecisionLog::new(inner_log, Arc::clone(&bundle));
        let supervisor = Supervisor::with_runtime(graph_id, constraints, capturing_log, runtime);

        Self { supervisor, bundle }
    }

    pub fn on_event(&mut self, event: ExternalEvent) {
        {
            let mut guard = self.bundle.lock().expect("capture bundle poisoned");
            guard.events.push(ExternalEventRecord::from_event(&event));
        }

        self.supervisor.on_event(event);
    }

    pub fn into_bundle(self) -> CaptureBundle {
        let CapturingSession { supervisor, bundle } = self;
        drop(supervisor);

        match Arc::try_unwrap(bundle) {
            Ok(mutex) => mutex.into_inner().expect("capture bundle poisoned"),
            Err(shared) => shared.lock().expect("capture bundle poisoned").clone(),
        }
    }
}

pub fn write_capture_bundle(
    path: &Path,
    bundle: &CaptureBundle,
    style: CaptureJsonStyle,
) -> Result<(), CaptureWriteError> {
    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() {
            fs::create_dir_all(parent).map_err(|source| {
                CaptureWriteError::CreateOutputDirectory {
                    path: parent.to_path_buf(),
                    source,
                }
            })?;
        }
    }

    let mut bytes = match style {
        CaptureJsonStyle::Compact => {
            serde_json::to_vec(bundle).map_err(|source| CaptureWriteError::Serialize {
                path: path.to_path_buf(),
                style,
                source,
            })?
        }
        CaptureJsonStyle::Pretty => {
            serde_json::to_vec_pretty(bundle).map_err(|source| CaptureWriteError::Serialize {
                path: path.to_path_buf(),
                style,
                source,
            })?
        }
    };
    bytes.push(b'\n');

    write_bytes_atomic(path, &bytes)
}

fn write_bytes_atomic(path: &Path, bytes: &[u8]) -> Result<(), CaptureWriteError> {
    let parent = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));
    let file_name = path
        .file_name()
        .ok_or_else(|| CaptureWriteError::InvalidDestination {
            path: path.to_path_buf(),
        })?;
    let (temp_path, mut file) = create_temp_file(path, parent, file_name)?;

    if let Err(source) = file.write_all(bytes) {
        let _ = fs::remove_file(&temp_path);
        return Err(CaptureWriteError::WriteTempFile {
            destination: path.to_path_buf(),
            temp_path,
            source,
        });
    }

    if let Err(source) = file.sync_all() {
        let _ = fs::remove_file(&temp_path);
        return Err(CaptureWriteError::SyncTempFile {
            destination: path.to_path_buf(),
            temp_path,
            source,
        });
    }

    drop(file);
    if let Err(source) = replace_destination_with_retry(&temp_path, path) {
        let _ = fs::remove_file(&temp_path);
        return Err(CaptureWriteError::RenameTempFile {
            destination: path.to_path_buf(),
            temp_path,
            source,
        });
    }

    Ok(())
}

fn create_temp_file(
    destination: &Path,
    parent: &Path,
    file_name: &std::ffi::OsStr,
) -> Result<(std::path::PathBuf, std::fs::File), CaptureWriteError> {
    for _ in 0..MAX_TEMP_FILE_ATTEMPTS {
        let suffix = TEMP_FILE_COUNTER.fetch_add(1, Ordering::Relaxed);
        let temp_name = format!(
            "{}.{}.{}.tmp",
            file_name.to_string_lossy(),
            std::process::id(),
            suffix
        );
        let temp_path = parent.join(temp_name);
        match OpenOptions::new()
            .create_new(true)
            .write(true)
            .open(&temp_path)
        {
            Ok(file) => return Ok((temp_path, file)),
            Err(err) if err.kind() == ErrorKind::AlreadyExists => continue,
            Err(source) => {
                return Err(CaptureWriteError::CreateTempFile {
                    destination: destination.to_path_buf(),
                    temp_path,
                    source,
                });
            }
        }
    }

    Err(CaptureWriteError::ExhaustedTempFileAttempts {
        destination: destination.to_path_buf(),
    })
}

#[cfg(not(windows))]
fn replace_destination_with_retry(temp_path: &Path, destination: &Path) -> std::io::Result<()> {
    fs::rename(temp_path, destination)
}

#[cfg(windows)]
fn replace_destination_with_retry(temp_path: &Path, destination: &Path) -> std::io::Result<()> {
    use std::time::Duration;

    let mut last_permission_error = None;
    for attempt in 0..MAX_REPLACE_RETRY_ATTEMPTS {
        match replace_destination_once(temp_path, destination) {
            Ok(()) => return Ok(()),
            Err(err)
                if err.kind() == ErrorKind::PermissionDenied
                    && attempt + 1 < MAX_REPLACE_RETRY_ATTEMPTS =>
            {
                last_permission_error = Some(err);
                // Windows can transiently deny atomic replace when the destination is contended.
                std::thread::sleep(Duration::from_millis(REPLACE_RETRY_DELAY_MS));
            }
            Err(err) => return Err(err),
        }
    }

    Err(last_permission_error.unwrap_or_else(|| {
        std::io::Error::new(
            ErrorKind::PermissionDenied,
            "atomic replace failed after retry attempts",
        )
    }))
}

#[cfg(windows)]
fn replace_destination_once(temp_path: &Path, destination: &Path) -> std::io::Result<()> {
    use std::iter;
    use std::os::windows::ffi::OsStrExt;
    type Dword = u32;
    type WinBool = i32;

    const MOVEFILE_REPLACE_EXISTING: Dword = 0x0000_0001;
    const MOVEFILE_WRITE_THROUGH: Dword = 0x0000_0008;

    #[link(name = "Kernel32")]
    extern "system" {
        fn MoveFileExW(
            existing_file_name: *const u16,
            new_file_name: *const u16,
            flags: Dword,
        ) -> WinBool;
    }

    let temp_wide: Vec<u16> = temp_path
        .as_os_str()
        .encode_wide()
        .chain(iter::once(0))
        .collect();
    let destination_wide: Vec<u16> = destination
        .as_os_str()
        .encode_wide()
        .chain(iter::once(0))
        .collect();

    // SAFETY: pointers are valid for the duration of the call and NUL terminated.
    let ok = unsafe {
        MoveFileExW(
            temp_wide.as_ptr(),
            destination_wide.as_ptr(),
            MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
        )
    };
    if ok == 0 {
        Err(std::io::Error::last_os_error())
    } else {
        Ok(())
    }
}

#[cfg(test)]
mod tests;