juncture-core 0.2.0

Core types and traits for Juncture state machine framework
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! Configuration types for graph execution
//!
//! Provides [`RunnableConfig`] for controlling graph execution behavior,
//! including concurrency limits, checkpoint settings, caching, and
//! cancellation.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use crate::checkpoint::CheckpointSaver;
use crate::interrupt::ResumeValue;
use crate::observability::{
    CachePolicy as LlmCachePolicy, GraphLifecycleCallback, MetricsCollector,
};
use crate::pregel::{BudgetConfig, BudgetTracker, Durability};
use crate::runtime::Heartbeat;
use crate::store::Store;

/// Configuration for graph execution
#[derive(Clone, Default)]
pub struct RunnableConfig {
    /// Thread ID for checkpoint isolation
    pub thread_id: Option<String>,

    /// Checkpoint ID to resume from (time-travel)
    pub checkpoint_id: Option<String>,

    /// Maximum superstep count (default 25)
    pub recursion_limit: usize,

    /// Maximum parallel tasks (for bounded concurrency)
    pub max_parallel_tasks: usize,

    /// Run name for observability
    pub run_name: Option<String>,

    /// Graph name for observability (specified at graph construction time)
    pub graph_name: Option<String>,

    /// Unique run identifier for logging, stream resumption, and cancellation.
    ///
    /// When `None`, the execution layer (`CompiledGraph::stream`, `invoke`, etc.)
    /// generates a new `UUIDv4` automatically before creating the Pregel loop.
    /// Callers may set this explicitly to correlate multiple operations with
    /// the same run ID (e.g., for stream resumption or distributed tracing).
    pub run_id: Option<String>,

    /// Checkpoint namespace (for subgraph isolation)
    pub checkpoint_ns: Option<crate::checkpoint::CheckpointNamespace>,

    /// Cache configuration
    pub cache: Option<CacheConfig>,

    /// Tags for filtering
    pub tags: Vec<String>,

    /// User metadata
    pub metadata: HashMap<String, serde_json::Value>,

    /// Cancellation token for aborting execution
    pub cancellation_token: Option<tokio_util::sync::CancellationToken>,

    /// Budget configuration for execution limits
    pub budget: Option<BudgetConfig>,

    /// Checkpoint durability mode
    pub durability: Option<Durability>,

    /// Callback invoked when a node finishes execution
    #[allow(
        clippy::type_complexity,
        reason = "trait object callback requires full signature"
    )]
    pub node_finished_callback: Option<Arc<dyn Fn(&str) + Send + Sync>>,

    /// Resume value for HITL interrupt continuation
    ///
    /// Supports single value, ID-based resume, and namespace-based resume
    /// for multi-interrupt workflows.
    pub resume_value: Option<ResumeValue>,

    /// Nodes that should interrupt before execution (HITL)
    pub interrupt_before: Option<Vec<String>>,

    /// Nodes that should interrupt after execution (HITL)
    pub interrupt_after: Option<Vec<String>>,

    /// Optional metrics collector for OpenTelemetry or in-memory metrics
    pub metrics_collector: Option<Arc<dyn MetricsCollector>>,

    /// Optional callback handler for graph lifecycle events
    ///
    /// Receives notifications at key points during graph execution:
    /// node start/end/error, graph completion, and checkpoint saves.
    /// All methods have default no-op implementations.
    pub callback_handler: Option<Arc<dyn GraphLifecycleCallback>>,

    /// LLM response cache policy for controlling key generation and TTL
    pub llm_cache_policy: Option<LlmCachePolicy>,

    /// Optional heartbeat sender for long-running node liveness signals
    ///
    /// When set by the execution engine, nodes can call
    /// `config.heartbeat.as_ref().map(Heartbeat::ping)` periodically
    /// to prevent idle timeout detection.
    pub heartbeat: Option<Heartbeat>,

    /// Runtime budget tracker shared across nodes for token/cost tracking
    ///
    /// Set by the execution engine when a [`BudgetConfig`] is configured.
    /// Nodes can access this via [`Self::budget_tracker`] to report LLM
    /// token usage for automatic budget enforcement.
    pub budget_tracker: Option<Arc<BudgetTracker>>,

    /// Resource limits for concurrent LLM/tool calls and state size
    pub resource_limits: Option<ResourceLimits>,
}

impl std::fmt::Debug for RunnableConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RunnableConfig")
            .field("thread_id", &self.thread_id)
            .field("checkpoint_id", &self.checkpoint_id)
            .field("recursion_limit", &self.recursion_limit)
            .field("max_parallel_tasks", &self.max_parallel_tasks)
            .field("run_name", &self.run_name)
            .field("graph_name", &self.graph_name)
            .field("run_id", &self.run_id)
            .field("checkpoint_ns", &self.checkpoint_ns)
            .field("cache", &self.cache)
            .field("tags", &self.tags)
            .field("metadata", &self.metadata)
            .field(
                "cancellation_token",
                &self
                    .cancellation_token
                    .as_ref()
                    .map(|_| "CancellationToken"),
            )
            .field("budget", &self.budget)
            .field("durability", &self.durability)
            .field(
                "node_finished_callback",
                &self.node_finished_callback.as_ref().map(|_| "<fn>"),
            )
            .field("resume_value", &self.resume_value)
            .field("interrupt_before", &self.interrupt_before)
            .field("interrupt_after", &self.interrupt_after)
            .field(
                "metrics_collector",
                &self
                    .metrics_collector
                    .as_ref()
                    .map(|_| "<MetricsCollector>"),
            )
            .field(
                "callback_handler",
                &self
                    .callback_handler
                    .as_ref()
                    .map(|_| "<GraphLifecycleCallback>"),
            )
            .field(
                "llm_cache_policy",
                &self.llm_cache_policy.as_ref().map(|_| "<CachePolicy>"),
            )
            .field("heartbeat", &self.heartbeat.as_ref().map(|_| "<Heartbeat>"))
            .field(
                "budget_tracker",
                &self.budget_tracker.as_ref().map(|_| "<BudgetTracker>"),
            )
            .field("resource_limits", &self.resource_limits)
            .finish()
    }
}

impl RunnableConfig {
    /// Create a new configuration with sensible defaults
    #[must_use]
    pub fn new() -> Self {
        Self {
            recursion_limit: 25,
            max_parallel_tasks: 100,
            heartbeat: None,
            ..Default::default()
        }
    }

    /// Set the thread ID for checkpoint isolation
    #[must_use]
    pub fn with_thread_id(mut self, id: impl Into<String>) -> Self {
        self.thread_id = Some(id.into());
        self
    }

    /// Set the checkpoint ID for time-travel resume
    #[must_use]
    pub fn with_checkpoint_id(mut self, id: impl Into<String>) -> Self {
        self.checkpoint_id = Some(id.into());
        self
    }

    /// Set the run ID for stream resumption and observability correlation
    #[must_use]
    pub fn with_run_id(mut self, id: impl Into<String>) -> Self {
        self.run_id = Some(id.into());
        self
    }

    /// Set the recursion limit (maximum superstep count)
    #[must_use]
    pub const fn with_recursion_limit(mut self, limit: usize) -> Self {
        self.recursion_limit = limit;
        self
    }

    /// Set the maximum number of parallel tasks
    #[must_use]
    pub const fn with_max_parallel_tasks(mut self, max: usize) -> Self {
        self.max_parallel_tasks = max;
        self
    }

    /// Set the run name for observability
    #[must_use]
    pub fn with_run_name(mut self, name: impl Into<String>) -> Self {
        self.run_name = Some(name.into());
        self
    }

    /// Set the graph name for observability
    #[must_use]
    pub fn with_graph_name(mut self, name: impl Into<String>) -> Self {
        self.graph_name = Some(name.into());
        self
    }

    /// Set the checkpoint namespace for subgraph isolation
    #[must_use]
    pub fn with_checkpoint_ns(mut self, ns: crate::checkpoint::CheckpointNamespace) -> Self {
        self.checkpoint_ns = Some(ns);
        self
    }

    /// Set cache configuration
    #[must_use]
    pub fn with_cache(mut self, cache: CacheConfig) -> Self {
        self.cache = Some(cache);
        self
    }

    /// Add a tag for filtering
    #[must_use]
    pub fn with_tag(mut self, tag: impl Into<String>) -> Self {
        self.tags.push(tag.into());
        self
    }

    /// Add metadata key-value pair
    #[must_use]
    pub fn with_metadata(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.metadata.insert(key.into(), value);
        self
    }

    /// Set the cancellation token for aborting execution
    #[must_use]
    pub fn with_cancellation_token(mut self, token: tokio_util::sync::CancellationToken) -> Self {
        self.cancellation_token = Some(token);
        self
    }

    /// Set the budget configuration for execution limits
    #[must_use]
    pub fn with_budget(mut self, budget: BudgetConfig) -> Self {
        self.budget = Some(budget);
        self
    }

    /// Set `interrupt_before` nodes (HITL - interrupt before node execution)
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use juncture_core::config::RunnableConfig;
    ///
    /// let config = RunnableConfig::new()
    ///     .with_interrupt_before(vec!["human_input".to_string()]);
    /// ```
    #[must_use]
    pub fn with_interrupt_before(mut self, nodes: Vec<String>) -> Self {
        self.interrupt_before = Some(nodes);
        self
    }

    /// Set `interrupt_after` nodes (HITL - interrupt after node execution)
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use juncture_core::config::RunnableConfig;
    ///
    /// let config = RunnableConfig::new()
    ///     .with_interrupt_after(vec!["confirmation".to_string()]);
    /// ```
    #[must_use]
    pub fn with_interrupt_after(mut self, nodes: Vec<String>) -> Self {
        self.interrupt_after = Some(nodes);
        self
    }

    /// Set the metrics collector for observability
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use std::sync::Arc;
    /// use juncture_core::config::RunnableConfig;
    /// use juncture_core::observability::MetricsCollector;
    ///
    /// let collector: Arc<dyn MetricsCollector> = /* ... */;
    /// let config = RunnableConfig::new()
    ///     .with_metrics_collector(collector);
    /// ```
    #[must_use]
    pub fn with_metrics_collector(mut self, collector: Arc<dyn MetricsCollector>) -> Self {
        self.metrics_collector = Some(collector);
        self
    }

    /// Set the callback handler for graph lifecycle events
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use std::sync::Arc;
    /// use juncture_core::config::RunnableConfig;
    /// use juncture_core::observability::GraphLifecycleCallback;
    ///
    /// let handler: Arc<dyn GraphLifecycleCallback> = /* ... */;
    /// let config = RunnableConfig::new()
    ///     .with_callback_handler(handler);
    /// ```
    #[must_use]
    pub fn with_callback_handler(mut self, handler: Arc<dyn GraphLifecycleCallback>) -> Self {
        self.callback_handler = Some(handler);
        self
    }

    /// Set the LLM response cache policy
    #[must_use]
    pub fn with_llm_cache_policy(mut self, policy: LlmCachePolicy) -> Self {
        self.llm_cache_policy = Some(policy);
        self
    }

    /// Get a reference to the budget tracker, if configured
    ///
    /// Nodes can call this to report LLM token usage for automatic
    /// budget enforcement during graph execution.
    #[must_use]
    pub const fn budget_tracker(&self) -> Option<&Arc<BudgetTracker>> {
        self.budget_tracker.as_ref()
    }

    /// Set resource limits for concurrent LLM/tool calls and state size
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use juncture_core::config::{RunnableConfig, ResourceLimits};
    ///
    /// let limits = ResourceLimits::new()
    ///     .with_max_state_size_bytes(10 * 1024 * 1024);
    /// let config = RunnableConfig::new()
    ///     .with_resource_limits(limits);
    /// ```
    #[must_use]
    pub const fn with_resource_limits(mut self, limits: ResourceLimits) -> Self {
        self.resource_limits = Some(limits);
        self
    }
}

/// Cache configuration for node results
#[derive(Clone, Debug)]
pub struct CacheConfig {
    /// Cache policy
    pub policy: CachePolicy,
}

/// Cache policy controlling how node results are cached
///
/// Supports default (state-hash-based), TTL-based, and custom key
/// function caching strategies.
#[derive(Clone)]
pub struct CachePolicy {
    /// Optional custom key function for cache key generation
    ///
    /// When set, this function computes the cache key from the current
    /// state value and execution config. When unset, the default
    /// state-hash-based key is used.
    #[allow(
        clippy::type_complexity,
        reason = "trait object requires full signature"
    )]
    pub key_func: Option<Arc<dyn Fn(&serde_json::Value, &RunnableConfig) -> String + Send + Sync>>,

    /// Optional time-to-live for cached entries
    pub ttl: Option<Duration>,

    /// Optional maximum number of cache entries
    pub max_entries: Option<usize>,
}

impl std::fmt::Debug for CachePolicy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CachePolicy")
            .field("key_func", &self.key_func.as_ref().map(|_| "<fn>"))
            .field("ttl", &self.ttl)
            .field("max_entries", &self.max_entries)
            .finish()
    }
}

impl Default for CachePolicy {
    fn default() -> Self {
        Self::default_policy()
    }
}

impl CachePolicy {
    /// Create the default cache policy (state-hash-based, no TTL)
    #[must_use]
    pub fn default_policy() -> Self {
        Self {
            key_func: None,
            ttl: None,
            max_entries: None,
        }
    }

    /// Create a TTL-based cache policy
    ///
    /// Cached entries expire after the specified duration.
    #[must_use]
    pub fn ttl(duration: Duration) -> Self {
        Self {
            key_func: None,
            ttl: Some(duration),
            max_entries: None,
        }
    }

    /// Create a custom-key cache policy
    ///
    /// Uses the provided function to compute cache keys instead of
    /// the default state-hash-based approach.
    #[must_use]
    pub fn custom_key(
        key_func: impl Fn(&serde_json::Value, &RunnableConfig) -> String + Send + Sync + 'static,
    ) -> Self {
        Self {
            key_func: Some(Arc::new(key_func)),
            ttl: None,
            max_entries: None,
        }
    }
}

/// Task-level configuration for node execution
///
/// Overrides or supplements the graph-level [`RunnableConfig`] for
/// individual tasks, providing per-node retry, caching, and timeout
/// settings.
#[derive(Clone, Debug, Default)]
pub struct TaskConfig {
    /// Retry policy for this task
    pub retry_policy: Option<crate::graph::RetryPolicy>,

    /// Cache policy for this task
    pub cache_policy: Option<CachePolicy>,

    /// Timeout duration for this task
    pub timeout: Option<Duration>,

    /// Optional task name override
    pub name: Option<String>,
}

/// Entry point configuration for graph execution
///
/// Specifies the checkpointer and store to use when starting
/// a graph execution, enabling persistence and cross-thread
/// state management.
#[derive(Clone, Default)]
pub struct EntrypointConfig {
    /// Optional checkpointer for state persistence
    pub checkpointer: Option<Arc<dyn CheckpointSaver>>,

    /// Optional store for cross-thread state
    pub store: Option<Arc<dyn Store>>,
}

impl std::fmt::Debug for EntrypointConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EntrypointConfig")
            .field(
                "checkpointer",
                &self.checkpointer.as_ref().map(|_| "<CheckpointSaver>"),
            )
            .field("store", &self.store.as_ref().map(|_| "<Store>"))
            .finish()
    }
}

/// Resource limits for graph execution
///
/// Controls concurrent access to shared resources like LLM calls and tool
/// executions, and enforces state size limits to prevent unbounded memory growth.
///
/// # Examples
///
/// ```ignore
/// use juncture_core::config::ResourceLimits;
///
/// let limits = ResourceLimits::new()
///     .with_max_state_size_bytes(10 * 1024 * 1024); // 10 MB
/// ```
#[derive(Clone, Default)]
pub struct ResourceLimits {
    /// Maximum state size in bytes after serialization (None = unlimited)
    pub max_state_size_bytes: Option<usize>,
}

impl std::fmt::Debug for ResourceLimits {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ResourceLimits")
            .field("max_state_size_bytes", &self.max_state_size_bytes)
            .finish()
    }
}

impl ResourceLimits {
    /// Create a new resource limits configuration with no limits
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set maximum state size in bytes
    #[must_use]
    pub const fn with_max_state_size_bytes(mut self, max: usize) -> Self {
        self.max_state_size_bytes = Some(max);
        self
    }
}

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

    #[test]
    fn test_runnable_config_new() {
        let config = RunnableConfig::new();
        assert_eq!(config.recursion_limit, 25);
        assert_eq!(config.max_parallel_tasks, 100);
        assert!(config.thread_id.is_none());
        assert!(config.checkpoint_id.is_none());
        assert!(config.cancellation_token.is_none());
        assert!(config.budget.is_none());
        assert!(config.durability.is_none());
        assert!(config.resume_value.is_none());
        assert!(config.heartbeat.is_none());
    }

    #[test]
    fn test_runnable_config_with_cancellation_token() {
        let token = tokio_util::sync::CancellationToken::new();
        let config = RunnableConfig::new().with_cancellation_token(token);
        assert!(config.cancellation_token.is_some());
    }

    #[test]
    fn test_runnable_config_with_budget() {
        let budget = BudgetConfig::new().with_max_tokens(1000);
        let config = RunnableConfig::new().with_budget(budget);
        assert!(config.budget.is_some());
        assert_eq!(config.budget.as_ref().unwrap().max_tokens, Some(1000));
    }

    #[test]
    fn test_cache_policy_default() {
        let policy = CachePolicy::default_policy();
        assert!(policy.key_func.is_none());
        assert!(policy.ttl.is_none());
        assert!(policy.max_entries.is_none());
    }

    #[test]
    fn test_cache_policy_ttl() {
        let policy = CachePolicy::ttl(Duration::from_secs(60));
        assert!(policy.key_func.is_none());
        assert_eq!(policy.ttl, Some(Duration::from_secs(60)));
        assert!(policy.max_entries.is_none());
    }

    #[test]
    fn test_cache_policy_custom_key() {
        let policy =
            CachePolicy::custom_key(|val, _cfg| format!("key-{}", val.as_str().unwrap_or("")));
        assert!(policy.key_func.is_some());
        assert!(policy.ttl.is_none());
        assert!(policy.max_entries.is_none());

        // Verify the key function works
        let config = RunnableConfig::new();
        let key = (policy.key_func.as_ref().unwrap())(&serde_json::json!("test"), &config);
        assert_eq!(key, "key-test");
    }

    #[test]
    fn test_cache_policy_default_trait() {
        let policy = CachePolicy::default();
        assert!(policy.key_func.is_none());
        assert!(policy.ttl.is_none());
        assert!(policy.max_entries.is_none());
    }

    #[test]
    fn test_cache_policy_debug() {
        let policy = CachePolicy::ttl(Duration::from_secs(30));
        let debug_str = format!("{policy:?}");
        assert!(debug_str.contains("ttl"));
        assert!(debug_str.contains("30s"));
    }

    #[test]
    fn test_task_config_default() {
        let config = TaskConfig::default();
        assert!(config.retry_policy.is_none());
        assert!(config.cache_policy.is_none());
        assert!(config.timeout.is_none());
        assert!(config.name.is_none());
    }

    #[test]
    fn test_entrypoint_config_default() {
        let config = EntrypointConfig::default();
        assert!(config.checkpointer.is_none());
        assert!(config.store.is_none());
    }

    #[test]
    fn test_runnable_config_debug_format() {
        let config = RunnableConfig::new()
            .with_thread_id("t1")
            .with_run_name("test-run");
        let debug = format!("{config:?}");
        assert!(debug.contains("t1"));
        assert!(debug.contains("test-run"));
    }
}

// Rust guideline compliant 2026-05-19