swarm-engine-core 0.1.6

Core types and orchestration for SwarmEngine
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
//! Termination Judge - Single Source of Truth for termination decisions
//!
//! Centralizes all termination logic to prevent race conditions and ensure
//! consistent behavior across the orchestrator.

use tracing::{debug, info};

use crate::types::WorkerId;

use super::config::{ExhaustedBehavior, MultiWorkerStrategy, TerminationConfig};
use super::reason::{FailureReason, SuccessReason, TerminationVerdict};
use super::state::CompletionState;

/// External termination request
#[derive(Debug, Clone)]
pub struct TerminationRequest {
    /// Reason for termination
    pub reason: String,
    /// Tick when requested
    pub tick: u64,
}

/// Termination Judge - Single Source of Truth
///
/// All termination-related decisions go through this struct.
/// This prevents race conditions between different completion signals.
#[derive(Debug)]
pub struct TerminationJudge {
    /// Configuration
    config: TerminationConfig,

    /// Completion state
    state: CompletionState,

    /// External termination request
    external_request: Option<TerminationRequest>,

    /// Current tick (updated each tick)
    current_tick: u64,

    /// Total worker count
    worker_count: usize,

    /// Consecutive error count
    consecutive_errors: u64,
}

impl TerminationJudge {
    /// Create a new termination judge
    pub fn new(config: TerminationConfig, worker_count: usize) -> Self {
        Self {
            config,
            state: CompletionState::new(),
            external_request: None,
            current_tick: 0,
            worker_count,
            consecutive_errors: 0,
        }
    }

    /// Update the current tick
    pub fn set_tick(&mut self, tick: u64) {
        self.current_tick = tick;
    }

    /// Get the current tick
    pub fn current_tick(&self) -> u64 {
        self.current_tick
    }

    // =========================================================================
    // Notification Methods - Called by Orchestrator
    // =========================================================================

    /// Notify that a worker completed
    ///
    /// Called when WorkResult::Done is received.
    pub fn notify_worker_done(
        &mut self,
        worker_id: WorkerId,
        success: bool,
        message: Option<String>,
    ) {
        info!(
            worker_id = worker_id.0,
            success = success,
            message = ?message,
            tick = self.current_tick,
            "TerminationJudge: worker done notification"
        );

        self.state
            .record_worker_done(worker_id, success, message.clone(), self.current_tick);

        // Reset consecutive errors on success
        if success {
            self.consecutive_errors = 0;
        }

        // Reevaluate termination
        self.reevaluate();
    }

    /// Notify that exploration completed or exhausted
    ///
    /// Called when ExplorationSpace signals completion.
    pub fn notify_exploration_complete(&mut self, exhausted: bool) {
        info!(
            exhausted = exhausted,
            tick = self.current_tick,
            "TerminationJudge: exploration complete notification"
        );

        self.state.mark_exploration_done(exhausted);

        // Reevaluate termination
        self.reevaluate();
    }

    /// Notify that an error occurred
    pub fn notify_error(&mut self) {
        self.consecutive_errors += 1;

        if let Some(max) = self.config.max_consecutive_errors {
            if self.consecutive_errors >= max {
                info!(
                    errors = self.consecutive_errors,
                    max = max,
                    "TerminationJudge: max consecutive errors exceeded"
                );
                self.state.set_verdict(TerminationVerdict::Failure {
                    reason: FailureReason::MaxErrorsExceeded {
                        count: self.consecutive_errors,
                        limit: max,
                    },
                });
            }
        }
    }

    /// Request external termination
    pub fn request_terminate(&mut self, reason: impl Into<String>) {
        let reason = reason.into();
        info!(
            reason = %reason,
            tick = self.current_tick,
            "TerminationJudge: external termination requested"
        );

        self.external_request = Some(TerminationRequest {
            reason: reason.clone(),
            tick: self.current_tick,
        });

        // Set verdict immediately
        self.state
            .set_verdict(TerminationVerdict::ExternalStop { reason });
    }

    // =========================================================================
    // Query Methods - Called by Orchestrator
    // =========================================================================

    /// Check if the orchestrator should terminate
    ///
    /// This is the ONLY method that should be used to decide loop termination.
    pub fn should_terminate(&self) -> bool {
        // External request always terminates immediately
        if self.external_request.is_some() {
            return true;
        }

        // Verdict determined
        if self.state.has_verdict() {
            return true;
        }

        // Max ticks exceeded
        if self.config.max_ticks > 0 && self.current_tick >= self.config.max_ticks {
            return true;
        }

        false
    }

    /// Check if guidance generation should be skipped
    ///
    /// Returns true if we're in a terminal state and shouldn't generate new work.
    pub fn should_skip_guidance(&self) -> bool {
        // External request - stop immediately
        if self.external_request.is_some() {
            return true;
        }

        // Verdict already determined
        if self.state.has_verdict() {
            return true;
        }

        // Environment done (worker completed successfully)
        if self.state.is_environment_done() {
            return true;
        }

        // Exploration done
        if self.state.is_exploration_done() {
            return true;
        }

        false
    }

    /// Get the final verdict
    ///
    /// Call this after should_terminate() returns true.
    pub fn verdict(&self) -> TerminationVerdict {
        // Already determined
        if let Some(verdict) = self.state.verdict() {
            return verdict.clone();
        }

        // External request
        if let Some(ref req) = self.external_request {
            return TerminationVerdict::ExternalStop {
                reason: req.reason.clone(),
            };
        }

        // Timeout
        if self.config.max_ticks > 0 && self.current_tick >= self.config.max_ticks {
            let partial_success = self.state.any_worker_succeeded();
            return TerminationVerdict::Timeout { partial_success };
        }

        // Should not reach here if called correctly
        TerminationVerdict::Failure {
            reason: FailureReason::InternalError {
                message: "verdict() called without termination condition".to_string(),
            },
        }
    }

    /// Check if environment is done
    pub fn is_environment_done(&self) -> bool {
        self.state.is_environment_done()
    }

    /// Get completion state reference
    pub fn completion_state(&self) -> &CompletionState {
        &self.state
    }

    // =========================================================================
    // Internal Methods
    // =========================================================================

    /// Reevaluate termination based on current state
    fn reevaluate(&mut self) {
        // Already have a verdict
        if self.state.has_verdict() {
            return;
        }

        // Check worker completion based on strategy
        if let Some(verdict) = self.evaluate_worker_completion() {
            debug!(verdict = ?verdict, "TerminationJudge: verdict from worker completion");
            self.state.set_verdict(verdict);
            return;
        }

        // Check exploration exhaustion
        if self.state.is_exploration_exhausted() {
            let verdict = self.evaluate_exhaustion();
            debug!(verdict = ?verdict, "TerminationJudge: verdict from exploration exhaustion");
            self.state.set_verdict(verdict);
        }
    }

    /// Evaluate worker completion based on multi-worker strategy
    fn evaluate_worker_completion(&self) -> Option<TerminationVerdict> {
        let completed = self.state.completed_workers();

        match self.config.multi_worker_strategy {
            MultiWorkerStrategy::FirstSuccess => {
                // First successful worker triggers success
                if let Some((worker_id, result)) = self.state.first_success() {
                    return Some(TerminationVerdict::Success {
                        reason: SuccessReason::WorkerDone {
                            worker_id: worker_id.0,
                            message: result.message.clone(),
                        },
                    });
                }
                None
            }

            MultiWorkerStrategy::AllComplete => {
                // All workers must complete
                if completed.len() >= self.worker_count {
                    if self.state.any_worker_succeeded() {
                        return Some(TerminationVerdict::Success {
                            reason: SuccessReason::ConditionsMet,
                        });
                    } else {
                        return Some(TerminationVerdict::Failure {
                            reason: FailureReason::WorkerFailed {
                                worker_id: 0,
                                message: Some("All workers failed".to_string()),
                            },
                        });
                    }
                }
                None
            }

            MultiWorkerStrategy::AllSuccess => {
                // All workers must succeed
                if completed.len() >= self.worker_count {
                    if self.state.all_completed_workers_succeeded() {
                        return Some(TerminationVerdict::Success {
                            reason: SuccessReason::ConditionsMet,
                        });
                    } else {
                        return Some(TerminationVerdict::Failure {
                            reason: FailureReason::WorkerFailed {
                                worker_id: 0,
                                message: Some("Not all workers succeeded".to_string()),
                            },
                        });
                    }
                }
                None
            }

            MultiWorkerStrategy::Conditions => {
                // Let external conditions handle it
                None
            }
        }
    }

    /// Evaluate exhaustion based on config
    fn evaluate_exhaustion(&self) -> TerminationVerdict {
        match self.config.on_exhausted {
            ExhaustedBehavior::Fail => TerminationVerdict::Failure {
                reason: FailureReason::ExplorationExhausted,
            },

            ExhaustedBehavior::Success => TerminationVerdict::Success {
                reason: SuccessReason::ExplorationComplete,
            },

            ExhaustedBehavior::CheckConditions => {
                // If any worker succeeded, consider it success
                if self.state.any_worker_succeeded() {
                    TerminationVerdict::Success {
                        reason: SuccessReason::ExplorationComplete,
                    }
                } else {
                    TerminationVerdict::Failure {
                        reason: FailureReason::ExplorationExhausted,
                    }
                }
            }
        }
    }
}

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

    fn default_judge() -> TerminationJudge {
        TerminationJudge::new(TerminationConfig::default(), 1)
    }

    #[test]
    fn test_initial_state() {
        let judge = default_judge();
        assert!(!judge.should_terminate());
        assert!(!judge.should_skip_guidance());
    }

    #[test]
    fn test_worker_done_success() {
        let mut judge = default_judge();
        judge.set_tick(5);

        judge.notify_worker_done(WorkerId(0), true, Some("Done!".to_string()));

        assert!(judge.should_terminate());
        assert!(judge.should_skip_guidance());
        assert!(judge.verdict().is_success());
    }

    #[test]
    fn test_external_termination() {
        let mut judge = default_judge();

        judge.request_terminate("User requested stop");

        assert!(judge.should_terminate());
        assert!(judge.should_skip_guidance());
        assert!(matches!(
            judge.verdict(),
            TerminationVerdict::ExternalStop { .. }
        ));
    }

    #[test]
    fn test_max_ticks_timeout() {
        let config = TerminationConfig::with_max_ticks(100);
        let mut judge = TerminationJudge::new(config, 1);

        judge.set_tick(100);

        assert!(judge.should_terminate());
        assert!(matches!(
            judge.verdict(),
            TerminationVerdict::Timeout { .. }
        ));
    }

    #[test]
    fn test_exploration_exhausted() {
        let mut judge = default_judge();

        judge.notify_exploration_complete(true); // exhausted

        assert!(judge.should_terminate());
        assert!(matches!(
            judge.verdict(),
            TerminationVerdict::Failure {
                reason: FailureReason::ExplorationExhausted
            }
        ));
    }

    #[test]
    fn test_all_success_strategy() {
        let config =
            TerminationConfig::default().multi_worker_strategy(MultiWorkerStrategy::AllSuccess);
        let mut judge = TerminationJudge::new(config, 2);

        // First worker succeeds
        judge.notify_worker_done(WorkerId(0), true, None);
        assert!(!judge.should_terminate()); // Not yet

        // Second worker succeeds
        judge.notify_worker_done(WorkerId(1), true, None);
        assert!(judge.should_terminate());
        assert!(judge.verdict().is_success());
    }

    #[test]
    fn test_first_success_strategy() {
        let mut judge = default_judge();

        // First worker succeeds - should terminate immediately
        judge.notify_worker_done(WorkerId(0), true, None);

        assert!(judge.should_terminate());
        assert!(judge.verdict().is_success());
    }
}