nemo-flow-adaptive 0.2.0

Adaptive runtime primitives and Redis-backed learning components for NeMo Flow.
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Unit tests for runtime in the NeMo Flow adaptive crate.

use nemo_flow::api::llm::{LlmRequest, llm_request_intercepts};
use nemo_flow::api::runtime::{
    NemoFlowContextState, create_scope_stack, global_context, set_thread_scope_stack,
};
use nemo_flow::api::scope::{PopScopeParams, PushScopeParams, ScopeType, pop_scope, push_scope};
use serde_json::{Map, Value as Json};

use crate::config::{
    AcgComponentConfig, AdaptiveConfig, BackendSpec, StateConfig, TelemetryComponentConfig,
    ToolParallelismComponentConfig,
};
use crate::error::AdaptiveError;
use crate::runtime::backend::build_backend;
use crate::runtime::features::AdaptiveRuntime;
use crate::runtime::validation::validate_config;
use nemo_flow::codec::request::{AnnotatedLlmRequest, Message, MessageContent};
use nemo_flow::plugin::{ConfigPolicy, UnsupportedBehavior};

#[cfg(feature = "redis-backend")]
const REDIS_TEST_ENV: &str = "NEMO_FLOW_RUN_REDIS_TESTS";

fn reset_runtime_context() {
    let context = global_context();
    let mut state = context.write().unwrap();
    *state = NemoFlowContextState::new();
    set_thread_scope_stack(create_scope_stack());
}

fn short_hash(value: &str) -> &str {
    value.get(..16).unwrap_or(value)
}

fn sample_annotated_request(model: Option<&str>) -> AnnotatedLlmRequest {
    AnnotatedLlmRequest {
        messages: vec![
            Message::System {
                content: MessageContent::Text("You are a careful planner".to_string()),
                name: None,
            },
            Message::User {
                content: MessageContent::Text("Summarize the latest findings".to_string()),
                name: None,
            },
        ],
        model: model.map(str::to_string),
        params: None,
        tools: None,
        tool_choice: None,
        store: None,
        previous_response_id: None,
        truncation: None,
        reasoning: None,
        include: None,
        user: None,
        metadata: None,
        service_tier: None,
        parallel_tool_calls: None,
        max_output_tokens: None,
        max_tool_calls: None,
        top_logprobs: None,
        stream: None,
        extra: Map::new(),
    }
}

fn sample_layered_request(model: Option<&str>, language_guide: &str) -> AnnotatedLlmRequest {
    AnnotatedLlmRequest {
        messages: vec![
            Message::System {
                content: MessageContent::Text("You are a careful planner".to_string()),
                name: None,
            },
            Message::User {
                content: MessageContent::Text(language_guide.to_string()),
                name: None,
            },
            Message::Assistant {
                content: Some(MessageContent::Text(
                    "Acknowledged. I will apply the stable review lens.".to_string(),
                )),
                tool_calls: None,
                name: None,
            },
            Message::User {
                content: MessageContent::Text("Bundle contents go here".to_string()),
                name: None,
            },
        ],
        model: model.map(str::to_string),
        params: None,
        tools: None,
        tool_choice: None,
        store: None,
        previous_response_id: None,
        truncation: None,
        reasoning: None,
        include: None,
        user: None,
        metadata: None,
        service_tier: None,
        parallel_tool_calls: None,
        max_output_tokens: None,
        max_tool_calls: None,
        top_logprobs: None,
        stream: None,
        extra: Map::new(),
    }
}

#[tokio::test(flavor = "current_thread")]
async fn build_backend_supports_in_memory_and_rejects_unknown_kinds() {
    let backend = build_backend(&BackendSpec::in_memory()).await.unwrap();
    assert!(backend.list_runs_dyn("agent").await.unwrap().is_empty());

    let invalid_backend = build_backend(&BackendSpec {
        kind: "bogus".to_string(),
        config: serde_json::Map::<String, Json>::new(),
    })
    .await;
    match invalid_backend {
        Err(AdaptiveError::InvalidConfig(message)) => {
            assert!(message.contains("unsupported backend"));
        }
        Err(other) => panic!("unexpected backend error: {other}"),
        Ok(_) => panic!("expected invalid backend to fail"),
    }
}

#[cfg(feature = "redis-backend")]
#[tokio::test(flavor = "current_thread")]
async fn build_backend_redis_requires_url_and_maps_invalid_client_urls() {
    let missing_url = build_backend(&BackendSpec {
        kind: "redis".to_string(),
        config: serde_json::Map::<String, Json>::new(),
    })
    .await;
    match missing_url {
        Err(AdaptiveError::InvalidConfig(message)) => {
            assert!(message.contains("missing url"));
        }
        Err(other) => panic!("unexpected missing-url error: {other}"),
        Ok(_) => panic!("expected missing redis url to fail"),
    }

    let invalid_url = build_backend(&BackendSpec {
        kind: "redis".to_string(),
        config: serde_json::Map::from_iter([(
            "url".to_string(),
            Json::String("not-a-redis-url".to_string()),
        )]),
    })
    .await;
    match invalid_url {
        Err(AdaptiveError::Storage(message)) => {
            assert!(message.contains("redis client"));
        }
        Err(other) => panic!("unexpected invalid-url error: {other}"),
        Ok(_) => panic!("expected invalid redis url to fail"),
    }
}

#[cfg(feature = "redis-backend")]
#[tokio::test(flavor = "current_thread")]
async fn build_backend_redis_supports_success_path_when_server_is_available() {
    if std::env::var_os(REDIS_TEST_ENV).is_none() {
        eprintln!("SKIP: set {REDIS_TEST_ENV}=1 to run Redis-backed tests");
        return;
    }

    if crate::redis::RedisBackend::new("redis://127.0.0.1/", "probe:".to_string())
        .await
        .is_err()
    {
        eprintln!("SKIP: Redis not available at 127.0.0.1:6379");
        return;
    }

    let backend = build_backend(&BackendSpec {
        kind: "redis".to_string(),
        config: serde_json::Map::from_iter([
            (
                "url".to_string(),
                Json::String("redis://127.0.0.1/".to_string()),
            ),
            (
                "key_prefix".to_string(),
                Json::String("runtime-success:".to_string()),
            ),
        ]),
    })
    .await
    .expect("expected redis backend to build");

    let runs = backend
        .list_runs_dyn("runtime-success-agent")
        .await
        .expect("expected empty run listing");
    assert!(runs.is_empty());
}

#[cfg(not(feature = "redis-backend"))]
#[tokio::test(flavor = "current_thread")]
async fn build_backend_redis_reports_feature_disabled_when_compiled_out() {
    let disabled = build_backend(&BackendSpec {
        kind: "redis".to_string(),
        config: serde_json::Map::from_iter([(
            "url".to_string(),
            Json::String("redis://127.0.0.1/".to_string()),
        )]),
    })
    .await;

    match disabled {
        Err(AdaptiveError::InvalidConfig(message)) => {
            assert!(message.contains("not enabled"));
        }
        Err(other) => panic!("unexpected feature-disabled error: {other}"),
        Ok(_) => panic!("expected redis backend to be disabled in this build"),
    }
}

#[test]
fn validate_config_reports_version_mode_and_telemetry_gaps() {
    let report = validate_config(&AdaptiveConfig {
        version: 2,
        telemetry: Some(TelemetryComponentConfig::default()),
        tool_parallelism: Some(ToolParallelismComponentConfig {
            mode: "invalid".to_string(),
            ..ToolParallelismComponentConfig::default()
        }),
        policy: ConfigPolicy {
            unsupported_value: UnsupportedBehavior::Error,
            ..ConfigPolicy::default()
        },
        ..AdaptiveConfig::default()
    });

    assert!(report.has_errors());
    assert!(
        report
            .diagnostics
            .iter()
            .any(|diag| diag.code == "adaptive.unsupported_config_version")
    );
    assert!(
        report
            .diagnostics
            .iter()
            .any(|diag| diag.code == "adaptive.unsupported_value")
    );
    assert!(
        report
            .diagnostics
            .iter()
            .any(|diag| diag.code == "adaptive.section_disabled_missing_state")
    );
}

#[test]
fn validate_config_reports_unknown_backend_and_acg_provider_per_policy() {
    let warn_report = validate_config(&AdaptiveConfig {
        state: Some(StateConfig {
            backend: BackendSpec {
                kind: "mystery".to_string(),
                config: Map::new(),
            },
        }),
        acg: Some(AcgComponentConfig {
            provider: "custom".to_string(),
            ..AcgComponentConfig::default()
        }),
        policy: ConfigPolicy {
            unknown_component: UnsupportedBehavior::Warn,
            unsupported_value: UnsupportedBehavior::Warn,
            ..ConfigPolicy::default()
        },
        ..AdaptiveConfig::default()
    });
    assert!(
        warn_report
            .diagnostics
            .iter()
            .any(|diag| diag.code == "adaptive.unknown_backend"
                && diag.level == nemo_flow::plugin::DiagnosticLevel::Warning)
    );
    assert!(
        warn_report
            .diagnostics
            .iter()
            .any(|diag| diag.code == "adaptive.unsupported_value"
                && diag.field.as_deref() == Some("provider"))
    );

    let ignore_report = validate_config(&AdaptiveConfig {
        state: Some(StateConfig {
            backend: BackendSpec {
                kind: "mystery".to_string(),
                config: Map::new(),
            },
        }),
        policy: ConfigPolicy {
            unknown_component: UnsupportedBehavior::Ignore,
            unsupported_value: UnsupportedBehavior::Ignore,
            ..ConfigPolicy::default()
        },
        acg: Some(AcgComponentConfig {
            provider: "custom".to_string(),
            ..AcgComponentConfig::default()
        }),
        ..AdaptiveConfig::default()
    });
    assert!(ignore_report.diagnostics.is_empty());
}

#[tokio::test(flavor = "current_thread")]
async fn adaptive_runtime_new_accepts_valid_in_memory_configuration() {
    let runtime = AdaptiveRuntime::new(AdaptiveConfig {
        state: Some(StateConfig {
            backend: BackendSpec::in_memory(),
        }),
        ..AdaptiveConfig::default()
    })
    .await
    .unwrap();

    let rendered = format!("{runtime:?}");
    assert!(rendered.contains("AdaptiveRuntime"));
    assert!(rendered.contains("registered"));
}

#[test]
fn adaptive_owned_runtime_sources_use_canonical_acg_module_paths() {
    let owned_sources: [(&str, &str, &[&str]); 7] = [
        (
            "src/config.rs",
            include_str!("../../src/config.rs"),
            &["crate::acg::stability::StabilityThresholds"],
        ),
        (
            "src/runtime/features.rs",
            include_str!("../../src/runtime/features.rs"),
            &["use crate::acg::CacheRequestFacts;"],
        ),
        (
            "src/acg_component.rs",
            include_str!("../../src/acg_component.rs"),
            &["use crate::acg::plugin::{PluginInput, ProviderPlugin};"],
        ),
        (
            "src/acg_learner.rs",
            include_str!("../../src/acg_learner.rs"),
            &["use crate::acg::ir_builder::build_prompt_ir;"],
        ),
        (
            "src/acg_profile.rs",
            include_str!("../../src/acg_profile.rs"),
            &["use crate::acg::canonicalize::{canonicalize_value, sha256_hex};"],
        ),
        (
            "src/cache_diagnostics.rs",
            include_str!("../../src/cache_diagnostics.rs"),
            &[
                "use crate::acg::canonicalize::sha256_hex;",
                "use crate::acg::ir_builder::build_prompt_ir;",
            ],
        ),
        (
            "src/tool_parallelism_learner.rs",
            include_str!("../../src/tool_parallelism_learner.rs"),
            &["use crate::acg::canonicalize::sha256_hex;"],
        ),
    ];

    for (path, source, canonical_patterns) in owned_sources {
        assert!(
            !source.contains("nemo_flow_acg::"),
            "{path} should not fall back to the compatibility shim",
        );
        for canonical_pattern in canonical_patterns {
            assert!(
                source.contains(canonical_pattern),
                "{path} should import ACG through `{canonical_pattern}`",
            );
        }
    }
}

#[test]
fn adaptive_acg_defaults_and_profile_key_behavior_stay_stable() {
    let config = AdaptiveConfig::default();
    assert!(config.acg.is_none());

    let acg = AcgComponentConfig::default();
    assert_eq!(acg.provider, "passthrough");
    assert_eq!(acg.observation_window, 100);
    assert_eq!(acg.priority, 50);
    assert_eq!(
        acg.stability_thresholds,
        crate::acg::stability::StabilityThresholds::default()
    );

    let profile_key = crate::acg_profile::derive_acg_profile_key(
        "agent-1",
        &sample_annotated_request(Some("claude-sonnet-4")),
    );
    assert_eq!(
        profile_key,
        "agent-1::model=claude-sonnet-4::roles=system.user::system=sha256:97f793c76::anchor=no-anchor::tools=no-tools"
    );
    let learning_key = crate::acg_profile::derive_acg_learning_key(
        "agent-1",
        &sample_annotated_request(Some("claude-sonnet-4")),
    );
    let expected_learning_key = format!(
        "agent-1::model=claude-sonnet-4::seed={}::system={}::tools=no-tools",
        short_hash(&format!(
            "user:{}",
            crate::acg::sha256_hex("Summarize the latest findings")
        )),
        short_hash(&crate::acg::sha256_hex("You are a careful planner")),
    );
    assert_eq!(learning_key, expected_learning_key,);

    let grown_chat_request = AnnotatedLlmRequest {
        messages: vec![
            Message::System {
                content: MessageContent::Text("You are a careful planner".to_string()),
                name: None,
            },
            Message::User {
                content: MessageContent::Text("Summarize the latest findings".to_string()),
                name: None,
            },
            Message::Assistant {
                content: Some(MessageContent::Text(
                    "I found several stable observations.".to_string(),
                )),
                tool_calls: None,
                name: None,
            },
            Message::User {
                content: MessageContent::Text("Continue with the next batch.".to_string()),
                name: None,
            },
        ],
        model: Some("claude-sonnet-4".to_string()),
        params: None,
        tools: None,
        tool_choice: None,
        store: None,
        previous_response_id: None,
        truncation: None,
        reasoning: None,
        include: None,
        user: None,
        metadata: None,
        service_tier: None,
        parallel_tool_calls: None,
        max_output_tokens: None,
        max_tool_calls: None,
        top_logprobs: None,
        stream: None,
        extra: Map::new(),
    };
    assert_eq!(
        crate::acg_profile::derive_acg_learning_key("agent-1", &grown_chat_request),
        learning_key,
        "growing direct chats should reuse the same learning bucket",
    );
    assert_ne!(
        crate::acg_profile::derive_acg_profile_key("agent-1", &grown_chat_request),
        profile_key,
        "diagnostic keys should still reflect the exact live role shape",
    );

    let rust_key = crate::acg_profile::derive_acg_profile_key(
        "agent-1",
        &sample_layered_request(Some("claude-sonnet-4"), "Rust review guide"),
    );
    let python_key = crate::acg_profile::derive_acg_profile_key(
        "agent-1",
        &sample_layered_request(Some("claude-sonnet-4"), "Python review guide"),
    );
    assert_ne!(
        rust_key, python_key,
        "layered requests should separate profiles when the stable guide layer differs",
    );
    let rust_learning_key = crate::acg_profile::derive_acg_learning_key(
        "agent-1",
        &sample_layered_request(Some("claude-sonnet-4"), "Rust review guide"),
    );
    let python_learning_key = crate::acg_profile::derive_acg_learning_key(
        "agent-1",
        &sample_layered_request(Some("claude-sonnet-4"), "Python review guide"),
    );
    assert_ne!(
        rust_learning_key, python_learning_key,
        "layered requests should still separate learning buckets when the stable anchor differs",
    );

    let rust_bundle_variant = AnnotatedLlmRequest {
        messages: vec![
            Message::System {
                content: MessageContent::Text("You are a careful planner".to_string()),
                name: None,
            },
            Message::User {
                content: MessageContent::Text("Rust review guide".to_string()),
                name: None,
            },
            Message::Assistant {
                content: Some(MessageContent::Text(
                    "Acknowledged. I will apply the stable review lens.".to_string(),
                )),
                tool_calls: None,
                name: None,
            },
            Message::User {
                content: MessageContent::Text("Different bundle contents go here".to_string()),
                name: None,
            },
        ],
        model: Some("claude-sonnet-4".to_string()),
        params: None,
        tools: None,
        tool_choice: None,
        store: None,
        previous_response_id: None,
        truncation: None,
        reasoning: None,
        include: None,
        user: None,
        metadata: None,
        service_tier: None,
        parallel_tool_calls: None,
        max_output_tokens: None,
        max_tool_calls: None,
        top_logprobs: None,
        stream: None,
        extra: Map::new(),
    };
    let rust_bundle_variant_key =
        crate::acg_profile::derive_acg_profile_key("agent-1", &rust_bundle_variant);
    assert_eq!(
        rust_key, rust_bundle_variant_key,
        "layered requests should keep the same profile when only later bundle or turn content changes",
    );
    let rust_bundle_variant_learning_key =
        crate::acg_profile::derive_acg_learning_key("agent-1", &rust_bundle_variant);
    assert_eq!(
        rust_learning_key, rust_bundle_variant_learning_key,
        "layered requests should keep the same learning bucket when only later bundle or turn content changes",
    );
}

#[tokio::test(flavor = "current_thread")]
async fn adaptive_runtime_build_cache_request_facts_keeps_missing_stability_semantics() {
    let runtime = AdaptiveRuntime::new(AdaptiveConfig::default())
        .await
        .expect("default adaptive runtime should construct");

    let facts = runtime
        .build_cache_request_facts(
            "agent-1",
            "anthropic",
            &sample_annotated_request(Some("claude-sonnet-4")),
        )
        .expect("runtime should still emit request facts without stability state");

    assert_eq!(facts.provider, "anthropic");
    assert_eq!(facts.stable_prefix_length, 0);
    assert_eq!(facts.stable_prefix_tokens, None);
    assert_eq!(facts.required_min_tokens, None);
    assert_eq!(facts.missing_facts, vec!["acg_stability_unavailable"]);
}

#[tokio::test(flavor = "current_thread")]
async fn adaptive_runtime_bind_scope_requires_registration_and_passes_through_without_state() {
    reset_runtime_context();
    let mut runtime = AdaptiveRuntime::new(AdaptiveConfig {
        agent_id: Some("agent-1".to_string()),
        state: Some(StateConfig {
            backend: BackendSpec::in_memory(),
        }),
        acg: Some(AcgComponentConfig::default()),
        ..AdaptiveConfig::default()
    })
    .await
    .expect("adaptive runtime with acg should construct");
    let scope = push_scope(
        PushScopeParams::builder()
            .name("adaptive-runtime-scope")
            .scope_type(ScopeType::Agent)
            .build(),
    )
    .expect("scope push should succeed");

    let registration_err = match runtime.bind_scope(scope.uuid) {
        Ok(_) => panic!("expected scope binding to require registration"),
        Err(err) => err,
    };
    assert!(matches!(
        registration_err,
        AdaptiveError::RegistrationFailed(message)
            if message.contains("must be registered before binding ACG request intercepts")
    ));

    runtime
        .register()
        .await
        .expect("adaptive runtime should register");

    runtime
        .bind_scope(scope.uuid)
        .expect("registered runtime should bind acg to the active scope");
    let request = LlmRequest {
        headers: Map::new(),
        content: serde_json::json!({
            "messages": [{"role": "user", "content": "Hello"}],
            "system": "You are helpful.",
            "model": "claude-sonnet-4-20250514",
        }),
    };

    let translated = llm_request_intercepts("anthropic", request.clone())
        .expect("request intercept chain should pass through when no hot-cache state exists");

    assert_eq!(translated.content, request.content);
    pop_scope(PopScopeParams::builder().handle_uuid(&scope.uuid).build())
        .expect("scope pop should succeed");
}