multicast-codemode-local 2.0.0

Local QuickJS executor for multicast Code Mode
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
//! Exporter-backed workflow telemetry through the native actor and durable heap.
#![cfg(all(feature = "quickjs", feature = "sqlite"))]

use std::collections::BTreeMap;
use std::sync::{
    Arc,
    atomic::{AtomicU64, AtomicUsize, Ordering},
};
use std::time::Duration;

use multicast::cli::Cli;
use multicast::command::{
    CommandContext, CommandDef, CommandHandler, McpAnnotations, McpCommandOptions,
};
use multicast::output::CommandResult;
use multicast::tool::ToolCallOptions;
use multicast_codemode::opentelemetry::{
    Context, global,
    trace::{TraceContextExt, Tracer, TracerProvider},
};
use multicast_codemode::{
    Clock, CodeMode, CodeModeRunOptions, CodeModeService, ExecutionState, ExecutionStatus,
    MulticastConnector, WorkflowIdentity,
};
use multicast_codemode_local::{DurableStore, LocalCodeModeService, LocalExecutor};
use opentelemetry_sdk::metrics::{
    InMemoryMetricExporter, PeriodicReader, SdkMeterProvider,
    data::{AggregatedMetrics, MetricData},
};
use opentelemetry_sdk::trace::{InMemorySpanExporter, SdkTracerProvider, SpanData};
use serde_json::json;

const SECRET: &str = "private-workflow-payload-92742";

struct TestClock(Arc<AtomicU64>);
impl Clock for TestClock {
    fn now_ms(&self) -> u64 {
        self.0.load(Ordering::SeqCst)
    }
}
struct Save(Arc<AtomicUsize>);
#[async_trait::async_trait]
impl CommandHandler for Save {
    async fn run(&self, _: CommandContext) -> CommandResult {
        let span = Context::current().span().span_context().clone();
        tokio::task::yield_now().await;
        assert_eq!(*Context::current().span().span_context(), span);
        assert!(span.is_valid());
        self.0.fetch_add(1, Ordering::SeqCst);
        CommandResult::Ok {
            data: json!(SECRET),
            cta: None,
            exit_code: None,
        }
    }
}
struct Wait(Arc<AtomicUsize>);
#[async_trait::async_trait]
impl CommandHandler for Wait {
    async fn run(&self, _: CommandContext) -> CommandResult {
        self.0.fetch_add(1, Ordering::SeqCst);
        std::future::pending().await
    }
}
struct DisabledRun(LocalCodeModeService);
#[async_trait::async_trait]
impl CommandHandler for DisabledRun {
    async fn run(&self, _: CommandContext) -> CommandResult {
        let state = self
            .0
            .execute(
                "return await fixture.save({});".into(),
                CodeModeRunOptions::default(),
            )
            .await
            .unwrap();
        let paused = settle(&self.0, &state.id).await;
        assert_eq!(paused.status, ExecutionStatus::Paused);
        assert!(paused.trace.is_none());
        self.0.reject(paused.id, 0).await.unwrap();
        CommandResult::Ok {
            data: json!(true),
            cta: None,
            exit_code: None,
        }
    }
}
async fn settle(service: &LocalCodeModeService, id: &str) -> ExecutionState {
    tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            let state = service.execution(id.into()).await.unwrap();
            if state.status != ExecutionStatus::Running {
                return state;
            }
            tokio::task::yield_now().await;
        }
    })
    .await
    .unwrap()
}
fn attr(span: &SpanData, key: &str) -> Option<String> {
    span.attributes
        .iter()
        .find(|kv| kv.key.as_str() == key)
        .map(|kv| kv.value.to_string())
}
fn service(
    store: Arc<DurableStore>,
    now: Arc<AtomicU64>,
    count: Arc<AtomicUsize>,
) -> LocalCodeModeService {
    let cli = Cli::create("fixture")
        .command(
            "save",
            CommandDef::build("save", Save(count.clone())).done(),
        )
        .command(
            "wait",
            CommandDef::build("wait", Wait(count))
                .mcp(McpCommandOptions {
                    annotations: Some(McpAnnotations {
                        read_only_hint: Some(true),
                        ..Default::default()
                    }),
                    ..Default::default()
                })
                .done(),
        );
    LocalCodeModeService::spawn(move || {
        CodeMode::with_clock_and_artifact_store(
            store.clone(),
            store,
            LocalExecutor::default(),
            vec![Arc::new(MulticastConnector::new(cli.tool_catalog()))],
            TestClock(now),
        )
    })
    .unwrap()
}

// Exactly one test owns global providers in this integration binary.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn durable_pass_links_actor_context_and_approval_wait_are_exported() {
    let spans = InMemorySpanExporter::default();
    let traces = SdkTracerProvider::builder()
        .with_simple_exporter(spans.clone())
        .build();
    let metrics = InMemoryMetricExporter::default();
    let meters = SdkMeterProvider::builder()
        .with_reader(
            PeriodicReader::builder(metrics.clone())
                .with_interval(Duration::from_secs(3600))
                .build(),
        )
        .build();
    global::set_tracer_provider(traces.clone());
    global::set_meter_provider(meters.clone());
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("workflow.sqlite");
    let clock = Arc::new(AtomicU64::new(1000));
    let count = Arc::new(AtomicUsize::new(0));
    let actor = service(
        Arc::new(DurableStore::open(&path).unwrap()),
        clock.clone(),
        count.clone(),
    );
    let first_parent = Context::new().with_span(traces.tracer("host").start("first-request"));
    let options = CodeModeRunOptions {
        telemetry_context: first_parent.clone(),
        workflow: Some(WorkflowIdentity {
            name: "daily-report".into(),
            version: "literal-version".into(),
        }),
        ..Default::default()
    };
    let running = actor
        .execute("return await fixture.save({});".into(), options)
        .await
        .unwrap();
    let paused = settle(&actor, &running.id).await;
    assert_eq!(paused.status, ExecutionStatus::Paused);
    assert_eq!(count.load(Ordering::SeqCst), 0);
    let first = paused
        .trace
        .clone()
        .expect("trace link persisted before pause");
    // Old executions remain readable when they predate trace persistence.
    let mut old = serde_json::to_value(&paused).unwrap();
    old.as_object_mut().unwrap().remove("trace");
    assert!(
        serde_json::from_value::<ExecutionState>(old)
            .unwrap()
            .trace
            .is_none()
    );
    drop(actor);
    let store = tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            if let Ok(store) = DurableStore::open(&path) {
                return Arc::new(store);
            }
            tokio::task::yield_now().await;
        }
    })
    .await
    .unwrap();
    let actor = service(store, clock.clone(), count.clone());
    assert_eq!(
        actor
            .execution(running.id.clone())
            .await
            .unwrap()
            .trace
            .unwrap()
            .span_id,
        first.span_id
    );
    clock.store(6000, Ordering::SeqCst);
    let second_parent = Context::new().with_span(traces.tracer("host").start("approval-request"));
    let options = CodeModeRunOptions {
        telemetry_context: second_parent.clone(),
        ..Default::default()
    };
    let completed = actor
        .approve(running.id.clone(), 0, options.clone())
        .await
        .unwrap();
    assert_eq!(completed.status, ExecutionStatus::Completed);
    assert_eq!(completed.result, Some(json!(SECRET)));
    assert_eq!(count.load(Ordering::SeqCst), 1);
    assert_eq!(
        completed
            .trace
            .as_ref()
            .unwrap()
            .workflow
            .as_ref()
            .unwrap()
            .name,
        "daily-report"
    );
    actor.approve(running.id.clone(), 0, options).await.unwrap();
    let before = spans.get_finished_spans().unwrap().len();
    let disabled = Cli::create("disabled").open_telemetry(false).command(
        "run",
        CommandDef::build("run", DisabledRun(actor.clone())).done(),
    );
    disabled
        .tool_catalog()
        .call("run", BTreeMap::new(), ToolCallOptions::isolated())
        .await;
    assert_eq!(
        spans.get_finished_spans().unwrap().len(),
        before,
        "opt-out reaches detached passes and approval decisions"
    );
    let failure = actor
        .execute(
            format!("throw new Error('{SECRET}');"),
            CodeModeRunOptions::default(),
        )
        .await
        .unwrap();
    assert_eq!(
        settle(&actor, &failure.id).await.status,
        ExecutionStatus::Error
    );
    let exported = spans.get_finished_spans().unwrap();
    let passes: Vec<_> = exported
        .iter()
        .filter(|s| s.name == "incurs.codemode.pass")
        .collect();
    assert_eq!(passes.len(), 3);
    let first_pass = passes
        .iter()
        .find(|s| s.span_context.span_id().to_string() == first.span_id)
        .unwrap();
    assert_eq!(
        first_pass.parent_span_id,
        first_parent.span().span_context().span_id()
    );
    let second = passes
        .iter()
        .find(|s| s.span_context.span_id().to_string() == completed.trace.as_ref().unwrap().span_id)
        .unwrap();
    assert_eq!(
        second.parent_span_id,
        second_parent.span().span_context().span_id()
    );
    assert_eq!(second.links.links.len(), 1);
    assert_eq!(
        second.links.links[0].span_context.span_id().to_string(),
        first.span_id
    );
    assert_eq!(
        attr(second, "incurs.workflow.version").as_deref(),
        Some("literal-version")
    );
    assert_eq!(
        attr(second, "incurs.execution.id").as_deref(),
        Some(running.id.as_str())
    );
    let call = exported
        .iter()
        .find(|s| {
            s.name == "incurs.codemode.call" && s.parent_span_id == second.span_context.span_id()
        })
        .unwrap();
    let command = exported
        .iter()
        .find(|s| s.name == "incurs.command save")
        .unwrap();
    assert_eq!(
        command.parent_span_id,
        call.span_context.span_id(),
        "command is a child of the actual tool dispatch"
    );
    let approvals: Vec<_> = exported
        .iter()
        .filter(|s| s.name == "incurs.codemode.approval")
        .collect();
    assert_eq!(
        approvals.len(),
        1,
        "duplicate decisions do not double count"
    );
    assert_eq!(
        approvals[0].parent_span_id,
        second_parent.span().span_context().span_id()
    );
    assert_eq!(
        approvals[0].links.links[0]
            .span_context
            .span_id()
            .to_string(),
        first.span_id
    );
    assert!(!format!("{exported:?}").contains(SECRET));
    meters.force_flush().unwrap();
    let mut counts = BTreeMap::new();
    for batch in metrics.get_finished_metrics().unwrap() {
        for scope in batch.scope_metrics() {
            for metric in scope.metrics() {
                if !metric.name().starts_with("incurs.codemode.") {
                    continue;
                }
                assert_eq!(metric.unit(), "s");
                let AggregatedMetrics::F64(MetricData::Histogram(hist)) = metric.data() else {
                    panic!("histogram")
                };
                for point in hist.data_points() {
                    *counts.entry(metric.name().to_string()).or_insert(0) += point.count();
                    assert!(point.attributes().all(|kv| {
                        ![
                            "incurs.execution.id",
                            "incurs.workflow.name",
                            "incurs.workflow.version",
                        ]
                        .contains(&kv.key.as_str())
                    }));
                    if metric.name() == "incurs.codemode.approval.duration" {
                        assert_eq!(point.sum(), 5.0);
                    }
                    if metric.name() == "incurs.codemode.pass.duration" {
                        assert!(point.sum() < 5.0, "paused time excluded from active passes");
                    }
                }
            }
        }
    }
    assert_eq!(counts["incurs.codemode.pass.duration"], 3);
    assert_eq!(counts["incurs.codemode.call.duration"], 2);
    assert_eq!(counts["incurs.codemode.approval.duration"], 1);
    let active = actor
        .execute(
            "return await fixture.wait({});".into(),
            CodeModeRunOptions::default(),
        )
        .await
        .unwrap();
    tokio::time::timeout(Duration::from_secs(5), async {
        while count.load(Ordering::SeqCst) != 2 {
            tokio::task::yield_now().await;
        }
    })
    .await
    .unwrap();
    assert_eq!(
        actor.cancel(active.id.clone()).await.unwrap().status,
        ExecutionStatus::Cancelled
    );
    tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            if spans.get_finished_spans().unwrap().iter().any(|s| {
                s.name == "incurs.codemode.pass"
                    && attr(s, "incurs.execution.id").as_deref() == Some(active.id.as_str())
            }) {
                break;
            }
            tokio::task::yield_now().await;
        }
    })
    .await
    .unwrap();
    let cancelled: Vec<_> = spans
        .get_finished_spans()
        .unwrap()
        .into_iter()
        .filter(|s| attr(s, "incurs.execution.id").as_deref() == Some(active.id.as_str()))
        .collect();
    assert_eq!(cancelled.len(), 2);
    assert!(
        cancelled
            .iter()
            .all(|s| attr(s, "incurs.outcome").as_deref() == Some("cancelled")),
        "cancelled execution spans: {cancelled:?}"
    );
    meters.force_flush().unwrap();
    let mut cancelled_counts = BTreeMap::new();
    for batch in metrics.get_finished_metrics().unwrap() {
        for scope in batch.scope_metrics() {
            for metric in scope.metrics() {
                if !metric.name().starts_with("incurs.codemode.") {
                    continue;
                }
                let AggregatedMetrics::F64(MetricData::Histogram(hist)) = metric.data() else {
                    panic!("histogram")
                };
                for point in hist.data_points() {
                    if point.attributes().any(|kv| {
                        kv.key.as_str() == "incurs.outcome" && kv.value.to_string() == "cancelled"
                    }) {
                        cancelled_counts.insert(metric.name().to_string(), point.count());
                    }
                }
            }
        }
    }
    assert_eq!(cancelled_counts["incurs.codemode.pass.duration"], 1);
    assert_eq!(cancelled_counts["incurs.codemode.call.duration"], 1);
    let tree = actor.execute("async () => { const f=await codemode.workflows.define('async n=>n+1'); return await f(2); }".into(), CodeModeRunOptions::default()).await.unwrap();
    let tree = tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            let state = actor.execution(tree.id.clone()).await.unwrap();
            if state.status == ExecutionStatus::Completed {
                break state;
            }
            assert_ne!(state.status, ExecutionStatus::Error, "{:?}", state.error);
            tokio::task::yield_now().await;
        }
    })
    .await
    .unwrap();
    assert_eq!(tree.result, Some(json!(3)));
    let child = &tree.workflow_children[0];
    let child_span = spans
        .get_finished_spans()
        .unwrap()
        .into_iter()
        .find(|s| {
            s.name == "incurs.codemode.pass"
                && attr(s, "incurs.execution.id").as_deref() == Some(child.id.as_str())
        })
        .unwrap();
    assert_eq!(
        attr(&child_span, "incurs.workflow.root.id").as_deref(),
        Some(tree.id.as_str())
    );
    assert_eq!(
        attr(&child_span, "incurs.workflow.parent.id").as_deref(),
        Some(tree.id.as_str())
    );
    assert_eq!(
        attr(&child_span, "incurs.workflow.definition.version").as_deref(),
        Some(child.reference.as_ref().unwrap().version.as_str())
    );
    first_parent.span().end();
    second_parent.span().end();
    traces.shutdown().unwrap();
    meters.shutdown().unwrap();
}