greentic-runner 1.2.2

Greentic runner binaries and re-exported host/new-runner APIs
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
use std::path::{Path, PathBuf};
use std::sync::Arc;

use anyhow::{Context, Result, anyhow, bail};
use clap::{ArgAction, Parser};
use serde_json::Value;

use greentic_runner_host::RunnerWasiPolicy;
use greentic_runner_host::component_api::node::{
    ExecCtx as ComponentExecCtx, TenantCtx as ComponentTenantCtx,
};
use greentic_runner_host::config::{
    FlowRetryConfig, HostConfig, OperatorPolicy, RateLimits, SecretsPolicy, StateStorePolicy,
    WebhookPolicy,
};
use greentic_runner_host::pack::{ComponentResolution, PackRuntime};
use greentic_runner_host::secrets::default_manager;
use greentic_runner_host::storage::{new_session_store, new_state_store};
use greentic_runner_host::trace::{TraceEnvelope, TraceHash};

#[derive(Debug, Parser)]
pub struct ReplayArgs {
    /// Path to trace.json
    #[arg(value_name = "TRACE")]
    pub trace: PathBuf,

    /// Optional pack path override (.gtpack or directory)
    #[arg(long, value_name = "PATH")]
    pub pack: Option<PathBuf>,

    /// Stop after reaching the failing step (default true; `--until-failure=false` to disable)
    #[arg(long, action = ArgAction::Set, default_value_t = true, value_name = "BOOL")]
    pub until_failure: bool,

    /// Run a specific 1-based step index
    #[arg(long, value_name = "N")]
    pub step: Option<usize>,

    /// Compare hashes when available (default true; `--compare-hashes=false` to disable)
    #[arg(long, action = ArgAction::Set, default_value_t = true, value_name = "BOOL")]
    pub compare_hashes: bool,
}

pub async fn run(args: ReplayArgs) -> Result<()> {
    let trace = load_trace(&args.trace)?;
    let pack_path = resolve_pack_path(&trace, args.pack.as_deref())?;
    let pack = load_pack(&pack_path).await?;

    let target_step = resolve_target_step(args.step, trace.steps.len())?;
    let last_index = trace.steps.len().saturating_sub(1);
    let mut divergences = 0usize;

    for (idx, step) in trace.steps.iter().enumerate() {
        if let Some(target) = target_step
            && idx != target
        {
            continue;
        }

        println!("step {}: {} {}", idx + 1, step.component_id, step.operation);
        let Some(invocation) = step.invocation_json.as_ref() else {
            println!("  missing invocation_json; skipping replay");
            if target_step.is_some() {
                break;
            }
            continue;
        };

        let output = replay_step(&pack, &trace, step, invocation)
            .await
            .with_context(|| format!("replay failed at step {}", idx + 1))?;

        let Some(output) = output else {
            println!("  host-managed step; not re-executed, output hash not compared");
            if step.error.is_some() && args.until_failure {
                println!("  stopping at failing step");
                break;
            }
            continue;
        };

        if args.compare_hashes {
            if let Some(expected) = step.output_hash.as_ref() {
                match compare_output_hash(&output, expected)? {
                    HashCheck::Match => println!("  output hash matches"),
                    HashCheck::Diverged { expected, actual } => {
                        divergences += 1;
                        println!("  divergence: expected output hash {expected}, got {actual}");
                    }
                }
            } else {
                println!("  output hash missing; skipping compare");
            }
        }

        if step.error.is_some() && args.until_failure {
            println!("  stopping at failing step");
            break;
        }

        if idx == last_index {
            println!("  reached end of trace");
        }
    }

    if divergences > 0 {
        bail!("replay diverged from the recorded trace at {divergences} step(s)");
    }
    Ok(())
}

/// Convert the 1-based `--step` value into a 0-based index, rejecting `0` and
/// values beyond the end of the trace instead of silently doing nothing.
fn resolve_target_step(step: Option<usize>, total: usize) -> Result<Option<usize>> {
    match step {
        None => Ok(None),
        Some(0) => bail!("--step is 1-based; 0 is not a valid step"),
        Some(n) if n > total => bail!("--step {n} is out of range: the trace has {total} step(s)"),
        Some(n) => Ok(Some(n - 1)),
    }
}

/// Steps the host executes itself (no component to re-run), so replay has no
/// output to compare against the recorded hash.
fn is_host_managed_step(component_id: &str) -> bool {
    component_id.starts_with("emit.")
        || component_id == "flow.call"
        || component_id == "session.wait"
}

fn load_trace(path: &Path) -> Result<TraceEnvelope> {
    let bytes =
        std::fs::read(path).with_context(|| format!("failed to read trace {}", path.display()))?;
    serde_json::from_slice(&bytes).context("failed to parse trace.json")
}

fn resolve_pack_path(trace: &TraceEnvelope, override_path: Option<&Path>) -> Result<PathBuf> {
    if let Some(path) = override_path {
        return Ok(path.to_path_buf());
    }
    let candidate = Path::new(trace.pack.pack_ref.as_str());
    if candidate.exists() {
        return Ok(candidate.to_path_buf());
    }
    bail!(
        "pack path not found; provide --pack (trace pack_ref was {})",
        trace.pack.pack_ref
    );
}

async fn load_pack(path: &Path) -> Result<Arc<PackRuntime>> {
    let config = Arc::new(replay_host_config());
    let session_store = new_session_store();
    let state_store = new_state_store();
    let secrets = default_manager().context("failed to init secrets manager")?;
    let archive_source = if path.is_file() { Some(path) } else { None };
    let pack = PackRuntime::load(
        path,
        Arc::clone(&config),
        None,
        archive_source,
        Some(session_store),
        Some(state_store),
        Arc::new(RunnerWasiPolicy::default()),
        secrets,
        None,
        false,
        ComponentResolution::default(),
    )
    .await
    .context("failed to load pack for replay")?;
    Ok(Arc::new(pack))
}

fn replay_host_config() -> HostConfig {
    HostConfig {
        tenant: "replay".to_string(),
        bindings_path: PathBuf::from("<replay>"),
        flow_type_bindings: std::collections::HashMap::new(),
        rate_limits: RateLimits::default(),
        retry: FlowRetryConfig::default(),
        http_enabled: false,
        secrets_policy: SecretsPolicy::allow_all(),
        state_store_policy: StateStorePolicy::default(),
        webhook_policy: WebhookPolicy::default(),
        timers: Vec::new(),
        oauth: None,
        mocks: None,
        pack_bindings: Vec::new(),
        env_passthrough: Vec::new(),
        trace: greentic_runner_host::trace::TraceConfig::from_env(),
        validation: greentic_runner_host::validate::ValidationConfig::from_env(),
        operator_policy: OperatorPolicy::allow_all(),
        fast2flow: Default::default(),
        #[cfg(feature = "agentic-worker")]
        agents: std::collections::HashMap::new(),
        #[cfg(feature = "agentic-worker")]
        graphs: std::collections::HashMap::new(),
    }
}

async fn replay_step(
    pack: &PackRuntime,
    trace: &TraceEnvelope,
    step: &greentic_runner_host::trace::TraceStep,
    invocation: &Value,
) -> Result<Option<Value>> {
    let component_id = step.component_id.as_str();
    let payload = invocation.get("payload").cloned().unwrap_or(Value::Null);

    if is_host_managed_step(component_id) {
        return Ok(None);
    }
    if component_id == "provider.invoke" {
        return replay_provider(pack, trace, step, &payload).await.map(Some);
    }

    let (component_ref, operation, input, config) = if component_id == "component.exec" {
        let component_ref = payload
            .get("component")
            .or_else(|| payload.get("component_ref"))
            .and_then(Value::as_str)
            .ok_or_else(|| anyhow!("component.exec missing component ref"))?;
        let operation = payload
            .get("operation")
            .and_then(Value::as_str)
            .unwrap_or(step.operation.as_str());
        let input = payload.get("input").cloned().unwrap_or(Value::Null);
        let config = payload.get("config").cloned().unwrap_or(Value::Null);
        (
            component_ref.to_string(),
            operation.to_string(),
            input,
            config,
        )
    } else {
        (
            component_id.to_string(),
            step.operation.clone(),
            payload,
            Value::Null,
        )
    };

    let ctx = component_exec_ctx(trace, &step.node_id);
    let input_json = serde_json::to_string(&input)?;
    let config_json = if config.is_null() {
        None
    } else {
        Some(serde_json::to_string(&config)?)
    };
    pack.invoke_component(&component_ref, ctx, &operation, config_json, input_json)
        .await
        .context("component invoke failed")
        .map(Some)
}

async fn replay_provider(
    pack: &PackRuntime,
    trace: &TraceEnvelope,
    step: &greentic_runner_host::trace::TraceStep,
    payload: &Value,
) -> Result<Value> {
    let provider_id = payload.get("provider_id").and_then(Value::as_str);
    let provider_type = payload.get("provider_type").and_then(Value::as_str);
    let op = payload
        .get("op")
        .or_else(|| payload.get("operation"))
        .and_then(Value::as_str)
        .unwrap_or(step.operation.as_str());
    let input = payload.get("input").cloned().unwrap_or(Value::Null);
    let ctx = component_exec_ctx(trace, &step.node_id);
    let binding = pack.resolve_provider(provider_id, provider_type)?;
    let input_json = serde_json::to_vec(&input)?;
    pack.invoke_provider(&binding, ctx, op, input_json)
        .await
        .context("provider invoke failed")
}

fn component_exec_ctx(trace: &TraceEnvelope, node_id: &str) -> ComponentExecCtx {
    ComponentExecCtx {
        tenant: ComponentTenantCtx {
            tenant: "replay".to_string(),
            team: None,
            user: None,
            trace_id: None,
            i18n_id: None,
            correlation_id: None,
            deadline_unix_ms: None,
            attempt: 1,
            idempotency_key: None,
        },
        i18n_id: None,
        flow_id: trace.flow.id.clone(),
        node_id: Some(node_id.to_string()),
    }
}

#[derive(Debug, PartialEq, Eq)]
enum HashCheck {
    Match,
    Diverged { expected: String, actual: String },
}

/// Hash the replayed output with the algorithm the trace recorded and compare.
fn compare_output_hash(value: &Value, expected: &TraceHash) -> Result<HashCheck> {
    let actual = hash_value(value, expected)?;
    if actual.value == expected.value {
        Ok(HashCheck::Match)
    } else {
        Ok(HashCheck::Diverged {
            expected: expected.value.clone(),
            actual: actual.value,
        })
    }
}

fn hash_value(value: &Value, expected: &TraceHash) -> Result<TraceHash> {
    let bytes = serde_json::to_vec(value).context("failed to serialize replay output")?;
    let digest = match expected.algorithm.as_str() {
        "blake3" => blake3::hash(&bytes).to_hex().to_string(),
        other => bail!("unsupported trace hash algorithm `{other}`"),
    };
    Ok(TraceHash {
        algorithm: expected.algorithm.clone(),
        value: digest,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn recorded(value: &Value) -> TraceHash {
        TraceHash {
            algorithm: "blake3".to_string(),
            value: blake3::hash(&serde_json::to_vec(value).expect("serialize"))
                .to_hex()
                .to_string(),
        }
    }

    #[test]
    fn matching_output_is_not_a_divergence() {
        let out = json!({"a": 1});
        assert_eq!(
            compare_output_hash(&out, &recorded(&out)).expect("compare"),
            HashCheck::Match
        );
    }

    #[test]
    fn changed_output_is_a_divergence() {
        let expected = recorded(&json!({"a": 1}));
        let check = compare_output_hash(&json!({"a": 2}), &expected).expect("compare");
        assert!(matches!(check, HashCheck::Diverged { .. }));
    }

    #[test]
    fn emit_flow_call_and_session_wait_are_not_re_executed() {
        // Their recorded output hash covers the node payload, which replay
        // cannot reproduce, so they must be skipped rather than hashed as null.
        assert!(is_host_managed_step("emit.response"));
        assert!(is_host_managed_step("flow.call"));
        assert!(is_host_managed_step("session.wait"));
        assert!(!is_host_managed_step("component.exec"));
        assert!(!is_host_managed_step("provider.invoke"));
        let recorded_emit = recorded(&json!({"text": "hi"}));
        assert!(matches!(
            compare_output_hash(&Value::Null, &recorded_emit).expect("compare"),
            HashCheck::Diverged { .. }
        ));
    }

    #[test]
    fn step_selection_is_validated() {
        assert_eq!(resolve_target_step(None, 3).expect("none"), None);
        assert_eq!(resolve_target_step(Some(1), 3).expect("first"), Some(0));
        assert_eq!(resolve_target_step(Some(3), 3).expect("last"), Some(2));
        assert!(resolve_target_step(Some(0), 3).is_err());
        assert!(resolve_target_step(Some(4), 3).is_err());
        assert!(resolve_target_step(Some(1), 0).is_err());
    }

    #[test]
    fn unknown_hash_algorithm_is_an_error() {
        let mut expected = recorded(&json!(1));
        expected.algorithm = "md5".to_string();
        assert!(compare_output_hash(&json!(1), &expected).is_err());
    }

    #[test]
    fn bool_flags_can_be_turned_off() {
        #[derive(Parser)]
        struct W {
            #[command(flatten)]
            args: ReplayArgs,
        }
        let on = W::try_parse_from(["x", "trace.json"]).expect("parse");
        assert!(on.args.until_failure && on.args.compare_hashes);
        let off = W::try_parse_from([
            "x",
            "trace.json",
            "--until-failure=false",
            "--compare-hashes",
            "false",
        ])
        .expect("parse");
        assert!(!off.args.until_failure && !off.args.compare_hashes);
    }
}