ironflow-api 2.52.5

REST API for ironflow run management and observability
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! `GET /api/v1/runs/:id` — Get run details with steps.

use std::collections::{HashMap, HashSet};

use axum::extract::{Path, State};
use axum::response::IntoResponse;
use ironflow_auth::extractor::Authenticated;
use ironflow_store::entities::ApiKeyScope;
use ironflow_store::models::RunStatus;
use tokio::join;
use uuid::Uuid;

use crate::authorization::AuthorizeExt;
use crate::entities::{
    ArtifactResponse, RunDetailResponse, RunResponse, StepAccountResponse, StepResponse,
};
use crate::error::ApiError;
use crate::response::ok;
use crate::state::AppState;

/// Get a run by ID, including all its steps and dependency edges.
///
/// While the run waits in the queue, `worker_routing` counts the workers seen
/// recently and those able to take it, so a run no worker can take shows up.
///
/// Returns 404 if the run does not exist.
#[cfg_attr(
    feature = "openapi",
    utoipa::path(
        get,
        path = "/api/v1/runs/{id}",
        tags = ["runs"],
        params(("id" = Uuid, Path, description = "Run ID")),
        responses(
            (status = 200, description = "Run details with steps", body = RunDetailResponse),
            (status = 401, description = "Unauthorized"),
            (status = 404, description = "Run not found")
        ),
        security(("Bearer" = []))
    )
)]
pub async fn get_run(
    auth: Authenticated,
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
) -> Result<impl IntoResponse, ApiError> {
    auth.require(ApiKeyScope::RunsRead, false)?;
    let run = state.get_run_or_404(id).await?;

    // Artifacts are fetched for the whole run in one call and grouped by step,
    // exactly like the dependency edges: one query, never one per step.
    let (steps, deps, artifacts) = join!(
        state.store.list_steps(id),
        state.store.list_step_dependencies(id),
        state.store.list_artifacts_for_run(id)
    );
    let steps = steps?;
    let deps = deps?;
    let artifacts = artifacts?;

    let mut deps_map: HashMap<Uuid, Vec<Uuid>> = HashMap::new();
    for dep in &deps {
        deps_map
            .entry(dep.step_id)
            .or_default()
            .push(dep.depends_on);
    }

    let mut artifacts_map: HashMap<Uuid, Vec<ArtifactResponse>> = HashMap::new();
    for artifact in artifacts {
        artifacts_map
            .entry(artifact.step_id)
            .or_default()
            .push(ArtifactResponse::from(artifact));
    }

    // Accounts are resolved once for the whole run, deduplicated. A deleted
    // account is absent from the map and the step keeps only its `account_id`.
    let account_ids: Vec<Uuid> = steps
        .iter()
        .filter_map(|step| step.account_id)
        .collect::<HashSet<Uuid>>()
        .into_iter()
        .collect();
    let accounts_map: HashMap<Uuid, StepAccountResponse> = if account_ids.is_empty() {
        HashMap::new()
    } else {
        state
            .store
            .list_provider_accounts_by_ids(account_ids)
            .await?
            .into_iter()
            .map(|account| (account.id, StepAccountResponse::from(account)))
            .collect()
    };

    let step_responses: Vec<StepResponse> = steps
        .into_iter()
        .map(|step| {
            let step_deps = deps_map.remove(&step.id).unwrap_or_default();
            let step_artifacts = artifacts_map.remove(&step.id).unwrap_or_default();
            let account = step
                .account_id
                .and_then(|account_id| accounts_map.get(&account_id).cloned());
            let response =
                StepResponse::with_dependencies_and_artifacts(step, step_deps, step_artifacts);
            match account {
                Some(account) => response.with_account(account),
                None => response,
            }
        })
        .collect();

    let active_descendant_count = state.store.list_active_descendants(id).await?.len() as u64;
    // Only a run waiting in the queue needs a worker: once it runs or ends,
    // who could take it no longer matters.
    let worker_routing = if matches!(run.status.state, RunStatus::Pending | RunStatus::Retrying) {
        let registry = &state.worker_registry;
        Some(registry.routing_for(&run.workflow_name, &run.worker_tags))
    } else {
        None
    };
    let payload = run.payload.clone();
    let response = RunDetailResponse {
        run: RunResponse::from(run),
        steps: step_responses,
        payload,
        active_descendant_count,
        worker_routing,
    };

    Ok(ok(response))
}

#[cfg(test)]
mod tests {
    use axum::Router;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use axum::routing::get;
    use chrono::{TimeDelta, Utc};
    use http_body_util::BodyExt;
    use ironflow_core::providers::claude::ClaudeCodeProvider;
    use ironflow_engine::engine::Engine;
    use ironflow_engine::notify::Event;
    use ironflow_store::entities::{
        NewProviderAccount, WorkerCapabilities, provider_account_secret_key,
    };
    use ironflow_store::memory::InMemoryStore;
    use ironflow_store::models::{
        NewRun, NewStep, NewUser, RunActor, RunUpdate, StepKind, StepUpdate, TriggerKind,
        step_trace_id,
    };
    use ironflow_store::store::RunStore;
    use serde_json::{Value as JsonValue, from_slice, json};
    use std::sync::Arc;
    use tokio::sync::broadcast;
    use tower::ServiceExt;
    use uuid::Uuid;

    use super::*;
    use crate::routes::test_helpers::create_user_auth_header;

    fn test_state() -> AppState {
        let store = Arc::new(InMemoryStore::new());
        Arc::new(InMemoryStore::new());
        let provider = Arc::new(ClaudeCodeProvider::new());
        let engine = Arc::new(Engine::new(store.clone(), provider));
        let jwt_config = Arc::new(ironflow_auth::jwt::JwtConfig {
            secret: "test-secret".to_string(),
            access_token_ttl_secs: 900,
            refresh_token_ttl_secs: 604800,
            cookie_domain: None,
            cookie_secure: false,
        });
        let (event_sender, _) = broadcast::channel::<Event>(1);
        AppState::new(
            store,
            engine,
            jwt_config,
            "test-worker-token".to_string(),
            event_sender,
        )
    }

    #[tokio::test]
    async fn existing_run() {
        let store = Arc::new(InMemoryStore::new());
        let run = store
            .create_run(NewRun {
                created_by: None,
                workflow_name: "test".to_string(),
                trigger: TriggerKind::Manual,
                payload: json!({}),
                max_retries: 3,
                handler_version: None,
                labels: HashMap::new(),
                scheduled_at: None,
                idempotency_key: None,
                concurrency_key: None,
                priority: 0,
                concurrency_limits: Vec::new(),
                max_cost_usd: None,
                worker_tags: Vec::new(),
            })
            .await
            .unwrap()
            .into_run();

        let provider = Arc::new(ClaudeCodeProvider::new());
        let engine = Arc::new(Engine::new(store.clone(), provider));
        Arc::new(InMemoryStore::new());
        let jwt_config = Arc::new(ironflow_auth::jwt::JwtConfig {
            secret: "test-secret".to_string(),
            access_token_ttl_secs: 900,
            refresh_token_ttl_secs: 604800,
            cookie_domain: None,
            cookie_secure: false,
        });
        let (event_sender, _) = broadcast::channel::<Event>(1);
        let state = AppState::new(
            store,
            engine,
            jwt_config,
            "test-worker-token".to_string(),
            event_sender,
        );
        let auth_header = create_user_auth_header(&state, "testuser", false).await;
        let app = Router::new().route("/{id}", get(get_run)).with_state(state);

        let req = Request::builder()
            .uri(format!("/{}", run.id))
            .header("authorization", auth_header)
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
        assert_eq!(json_val["data"]["run"]["id"], run.id.to_string());
    }

    #[tokio::test]
    async fn not_found() {
        let state = test_state();
        let auth_header = create_user_auth_header(&state, "testuser", false).await;
        let app = Router::new().route("/{id}", get(get_run)).with_state(state);

        let req = Request::builder()
            .uri(format!("/{}", Uuid::nil()))
            .header("authorization", auth_header)
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    /// A run with one agent step, optionally bound to a freshly created
    /// account. Returns the app, the auth header, the run id and the account id.
    async fn run_with_account_step(
        bind: bool,
        delete_account: bool,
    ) -> (Router, String, Uuid, Uuid) {
        let state = test_state();
        let auth_header = create_user_auth_header(&state, "testuser", false).await;
        let account_id = Uuid::now_v7();
        state
            .store
            .create_provider_account(NewProviderAccount {
                id: account_id,
                name: "perso".to_string(),
                display_name: "Compte perso".to_string(),
                kind: "claude_subscription".to_string(),
                secret_key: provider_account_secret_key(account_id),
                enabled: true,
                priority: 100,
                tags: Vec::new(),
                max_concurrency: None,
                alert_threshold: 0.8,
                expires_at: Utc::now() + TimeDelta::days(30),
                plan: None,
                created_by: None,
            })
            .await
            .unwrap();
        let run = state
            .store
            .create_run(NewRun {
                workflow_name: "test".to_string(),
                trigger: TriggerKind::Api,
                payload: json!({}),
                max_retries: 0,
                handler_version: None,
                labels: Default::default(),
                scheduled_at: None,
                created_by: None,
                idempotency_key: None,
                concurrency_key: None,
                priority: 0,
                concurrency_limits: Vec::new(),
                max_cost_usd: None,
                worker_tags: Vec::new(),
            })
            .await
            .unwrap()
            .into_run();
        let step = state
            .store
            .create_step(NewStep {
                run_id: run.id,
                trace_id: step_trace_id(run.id, "ask", 0),
                name: "ask".to_string(),
                kind: StepKind::Agent,
                position: 0,
                input: None,
                is_error_handler: false,
            })
            .await
            .unwrap();
        if bind {
            state
                .store
                .update_step(
                    step.id,
                    StepUpdate {
                        account_id: Some(account_id),
                        ..StepUpdate::default()
                    },
                )
                .await
                .unwrap();
        }
        if delete_account {
            state
                .store
                .delete_provider_account(account_id)
                .await
                .unwrap();
        }
        let app = Router::new().route("/{id}", get(get_run)).with_state(state);
        (app, auth_header, run.id, account_id)
    }

    async fn first_step_of(app: Router, auth_header: String, run_id: Uuid) -> JsonValue {
        let req = Request::builder()
            .uri(format!("/{run_id}"))
            .header("authorization", auth_header)
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
        json_val["data"]["steps"][0].clone()
    }

    #[tokio::test]
    async fn step_exposes_its_account() {
        let (app, auth_header, run_id, account_id) = run_with_account_step(true, false).await;
        let step = first_step_of(app, auth_header, run_id).await;
        assert_eq!(step["account_id"], account_id.to_string());
        assert_eq!(step["account"]["name"], "perso");
        assert_eq!(step["account"]["display_name"], "Compte perso");
    }

    #[tokio::test]
    async fn step_without_account_has_null_account() {
        let (app, auth_header, run_id, _) = run_with_account_step(false, false).await;
        let step = first_step_of(app, auth_header, run_id).await;
        assert!(step["account_id"].is_null());
        assert!(step["account"].is_null());
    }

    #[tokio::test]
    async fn step_whose_account_was_deleted_has_null_account() {
        let (app, auth_header, run_id, _) = run_with_account_step(true, true).await;
        let step = first_step_of(app, auth_header, run_id).await;
        assert!(step["account"].is_null());
    }

    #[tokio::test]
    async fn detail_exposes_the_run_author() {
        let state = test_state();
        let auth_header = create_user_auth_header(&state, "testuser", false).await;
        let user = state
            .store
            .create_user(NewUser {
                email: "alice@example.com".to_string(),
                username: "alice".to_string(),
                password_hash: "hash".to_string(),
                is_admin: Some(false),
            })
            .await
            .unwrap();

        let run = state
            .store
            .create_run(NewRun {
                workflow_name: "test".to_string(),
                trigger: TriggerKind::Api,
                payload: json!({}),
                max_retries: 0,
                handler_version: None,
                labels: Default::default(),
                scheduled_at: None,
                created_by: Some(RunActor::User { user_id: user.id }),
                idempotency_key: None,
                concurrency_key: None,
                priority: 0,
                concurrency_limits: Vec::new(),
                max_cost_usd: None,
                worker_tags: Vec::new(),
            })
            .await
            .unwrap()
            .into_run();

        let app = Router::new().route("/{id}", get(get_run)).with_state(state);

        let req = Request::builder()
            .uri(format!("/{}", run.id))
            .header("authorization", auth_header)
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
        assert_eq!(json_val["data"]["run"]["created_by"]["kind"], "user");
        assert_eq!(
            json_val["data"]["run"]["created_by"]["id"],
            user.id.to_string()
        );
        assert_eq!(json_val["data"]["run"]["created_by"]["label"], "alice");
    }
    /// Fetch the detail of a run whose handler set `output`, or nothing.
    async fn run_detail_with_output(output: Option<JsonValue>) -> JsonValue {
        let state = test_state();
        let auth_header = create_user_auth_header(&state, "testuser", false).await;
        let run = state
            .store
            .create_run(NewRun {
                workflow_name: "review".to_string(),
                trigger: TriggerKind::Manual,
                payload: json!({}),
                max_retries: 0,
                handler_version: None,
                labels: HashMap::new(),
                scheduled_at: None,
                created_by: None,
                idempotency_key: None,
                concurrency_key: None,
                priority: 0,
                concurrency_limits: Vec::new(),
                max_cost_usd: None,
                worker_tags: Vec::new(),
            })
            .await
            .unwrap()
            .into_run();
        state
            .store
            .update_run(
                run.id,
                RunUpdate {
                    output,
                    ..RunUpdate::default()
                },
            )
            .await
            .unwrap();

        let app = Router::new().route("/{id}", get(get_run)).with_state(state);
        let req = Request::builder()
            .uri(format!("/{}", run.id))
            .header("authorization", auth_header)
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        from_slice(&body).unwrap()
    }

    #[tokio::test]
    async fn detail_exposes_the_run_output() {
        let output = json!({"verdict": "approved", "score": 9, "note": "très bien"});

        let detail = run_detail_with_output(Some(output.clone())).await;

        assert_eq!(detail["data"]["run"]["output"], output);
    }

    #[tokio::test]
    async fn detail_keeps_a_falsy_output() {
        let detail = run_detail_with_output(Some(json!(false))).await;

        assert_eq!(detail["data"]["run"]["output"], json!(false));
    }

    #[tokio::test]
    async fn detail_omits_the_output_key_when_the_handler_set_none() {
        let detail = run_detail_with_output(None).await;

        let run = detail["data"]["run"].as_object().expect("a run object");
        assert!(!run.contains_key("output"), "unexpected output: {run:?}");
    }

    async fn gpu_run(state: &AppState) -> Uuid {
        state
            .store
            .create_run(NewRun {
                workflow_name: "transcode".to_string(),
                trigger: TriggerKind::Manual,
                payload: json!({}),
                max_retries: 0,
                handler_version: None,
                labels: HashMap::new(),
                scheduled_at: None,
                created_by: None,
                idempotency_key: None,
                concurrency_key: None,
                priority: 0,
                concurrency_limits: Vec::new(),
                max_cost_usd: None,
                worker_tags: vec!["gpu".to_string()],
            })
            .await
            .unwrap()
            .into_run()
            .id
    }

    async fn detail_of(state: &AppState, run_id: Uuid) -> JsonValue {
        let auth_header = create_user_auth_header(state, "testuser", false).await;
        let app = Router::new()
            .route("/{id}", get(get_run))
            .with_state(state.clone());
        let req = Request::builder()
            .uri(format!("/{run_id}"))
            .header("authorization", auth_header)
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        from_slice(&body).unwrap()
    }

    #[tokio::test]
    async fn pending_run_reports_no_eligible_worker() {
        let state = test_state();
        let run_id = gpu_run(&state).await;
        let cpu_only = WorkerCapabilities::new(None, vec!["arm".to_string()]);
        state.worker_registry.record("cpu-1", Some(cpu_only));

        let detail = detail_of(&state, run_id).await;

        assert_eq!(detail["data"]["run"]["worker_tags"], json!(["gpu"]));
        assert_eq!(
            detail["data"]["worker_routing"],
            json!({"seen_workers": 1, "eligible_workers": 0})
        );
    }

    #[tokio::test]
    async fn pending_run_reports_no_worker_seen() {
        let state = test_state();
        let run_id = gpu_run(&state).await;

        let detail = detail_of(&state, run_id).await;

        assert_eq!(
            detail["data"]["worker_routing"],
            json!({"seen_workers": 0, "eligible_workers": 0})
        );
    }

    #[tokio::test]
    async fn pending_run_counts_the_workers_able_to_take_it() {
        let state = test_state();
        let run_id = gpu_run(&state).await;
        let gpu = WorkerCapabilities::new(None, vec!["gpu".to_string()]);
        state.worker_registry.record("gpu-1", Some(gpu));
        state.worker_registry.record("legacy", None);

        let detail = detail_of(&state, run_id).await;

        assert_eq!(
            detail["data"]["worker_routing"],
            json!({"seen_workers": 2, "eligible_workers": 2})
        );
    }

    #[tokio::test]
    async fn running_run_omits_worker_routing() {
        let state = test_state();
        let run_id = gpu_run(&state).await;
        state
            .store
            .update_run_status(run_id, RunStatus::Running)
            .await
            .unwrap();

        let detail = detail_of(&state, run_id).await;

        let detail = detail["data"].as_object().expect("a detail object");
        assert!(!detail.contains_key("worker_routing"), "{detail:?}");
    }
}