Skip to main content

swarm_engine_llm/
batch_processor.rs

1//! Batch Processor - ManagerAgent 向け Batch LLM 処理
2//!
3//! ManagerAgent の `BatchDecisionRequest` を処理するための抽象化レイヤー。
4//!
5//! # 設計
6//!
7//! ```text
8//! Core Layer
9//! ├── ManagerAgent trait (prepare / finalize)
10//! ├── DefaultBatchManagerAgent   ← Core層のデフォルト実装
11//! ├── ContextStore / ContextView ← 正規化されたコンテキスト
12//! └── ContextResolver            ← スコープ解決
13//!
14//! LLM Layer
15//! ├── PromptBuilder              ← ResolvedContext → プロンプト
16//! ├── BatchProcessor trait       ← Batch 処理の抽象
17//! │   └── LlmBatchProcessor   ← Ollama 実装(仮想バッチ)
18//! │
19//! └── BatchInvoker 実装          ← LLM Batch 呼び出し
20//!     └── OllamaBatchInvoker
21//! ```
22//!
23//! # 仮想バッチ vs 真のバッチ
24//!
25//! Ollama は真の Batch API を持たないため、`LlmBatchProcessor` は
26//! 内部で並列/順次処理を行う「仮想バッチ」として実装されます。
27//! 将来 vLLM 等の真の Batch API を持つバックエンドに切り替える際は、
28//! `BatchProcessor` trait の別実装を提供するだけで対応可能です。
29//!
30//! # 型の統一
31//!
32//! LLM層はCore層の型を直接使用するため、変換ロジックは不要です:
33//! - `WorkerDecisionRequest` - リクエスト
34//! - `DecisionResponse` - レスポンス
35
36use std::future::Future;
37use std::pin::Pin;
38use std::sync::Arc;
39
40use std::collections::HashMap;
41
42use swarm_engine_core::actions::ActionDef;
43use swarm_engine_core::agent::{BatchDecisionRequest, DecisionResponse, WorkerDecisionRequest};
44use swarm_engine_core::exploration::DependencyGraph;
45use swarm_engine_core::types::{LoraConfig, WorkerId};
46
47use crate::decider::{LlmDecider, LlmError};
48
49// ============================================================================
50// BatchProcessor Trait
51// ============================================================================
52
53/// Batch 処理結果
54pub type BatchProcessResult = Vec<(WorkerId, Result<DecisionResponse, BatchProcessError>)>;
55
56/// Batch 処理エラー
57#[derive(Debug, Clone, thiserror::Error)]
58pub enum BatchProcessError {
59    /// 一時的エラー(リトライ可能)
60    #[error("Batch process error (transient): {0}")]
61    Transient(String),
62
63    /// 恒久的エラー(リトライ不可)
64    #[error("Batch process error: {0}")]
65    Permanent(String),
66}
67
68impl BatchProcessError {
69    pub fn transient(message: impl Into<String>) -> Self {
70        Self::Transient(message.into())
71    }
72
73    pub fn permanent(message: impl Into<String>) -> Self {
74        Self::Permanent(message.into())
75    }
76
77    pub fn is_transient(&self) -> bool {
78        matches!(self, Self::Transient(_))
79    }
80
81    pub fn message(&self) -> &str {
82        match self {
83            Self::Transient(msg) => msg,
84            Self::Permanent(msg) => msg,
85        }
86    }
87}
88
89impl From<LlmError> for BatchProcessError {
90    fn from(e: LlmError) -> Self {
91        if e.is_transient() {
92            Self::Transient(e.message().to_string())
93        } else {
94            Self::Permanent(e.message().to_string())
95        }
96    }
97}
98
99impl From<swarm_engine_core::error::SwarmError> for BatchProcessError {
100    fn from(err: swarm_engine_core::error::SwarmError) -> Self {
101        if err.is_transient() {
102            Self::Transient(err.message())
103        } else {
104            Self::Permanent(err.message())
105        }
106    }
107}
108
109impl From<BatchProcessError> for swarm_engine_core::error::SwarmError {
110    fn from(err: BatchProcessError) -> Self {
111        match err {
112            BatchProcessError::Transient(message) => {
113                swarm_engine_core::error::SwarmError::LlmTransient { message }
114            }
115            BatchProcessError::Permanent(message) => {
116                swarm_engine_core::error::SwarmError::LlmPermanent { message }
117            }
118        }
119    }
120}
121
122/// Batch Processor trait
123///
124/// `BatchDecisionRequest` を受け取り、各 Worker への決定を返す。
125/// バックエンド(Ollama, vLLM 等)に応じた実装を提供する。
126pub trait BatchProcessor: Send + Sync {
127    /// Batch リクエストを処理
128    ///
129    /// # Arguments
130    /// * `request` - Core の `BatchDecisionRequest`
131    ///
132    /// # Returns
133    /// 各 Worker への決定結果(WorkerId とペア)
134    fn process(
135        &self,
136        request: BatchDecisionRequest,
137    ) -> Pin<Box<dyn Future<Output = BatchProcessResult> + Send + '_>>;
138
139    /// タスクとアクション一覧からアクション依存グラフを生成
140    ///
141    /// Swarm の Ticks 開始前に呼び出され、アクション間の依存関係を計画する。
142    /// LLM を使用して動的に依存グラフを生成する。
143    ///
144    /// # Default
145    /// デフォルトでは None を返す(依存グラフ生成をスキップ)。
146    fn plan_dependencies(
147        &self,
148        _task: &str,
149        _actions: &[ActionDef],
150    ) -> Pin<Box<dyn Future<Output = Option<DependencyGraph>> + Send + '_>> {
151        Box::pin(async { None })
152    }
153
154    /// ヘルスチェック
155    fn is_healthy(&self) -> Pin<Box<dyn Future<Output = bool> + Send + '_>>;
156
157    /// プロセッサ名
158    fn name(&self) -> &str;
159}
160
161// ============================================================================
162// LlmBatchProcessor
163// ============================================================================
164
165/// Ollama Batch Processor 設定
166#[derive(Debug, Clone)]
167pub struct LlmBatchProcessorConfig {
168    /// 並列実行するか(false の場合は順次処理)
169    pub parallel: bool,
170    /// 並列実行時の最大同時実行数
171    pub max_concurrency: usize,
172    /// DependencyGraph 生成時の最大リトライ回数
173    pub max_retries: Option<usize>,
174}
175
176impl Default for LlmBatchProcessorConfig {
177    fn default() -> Self {
178        Self {
179            parallel: true,
180            max_concurrency: 4,
181            max_retries: Some(5),
182        }
183    }
184}
185
186/// Ollama Batch Processor
187///
188/// Ollama は真の Batch API を持たないため、仮想バッチとして実装。
189/// 内部で `LlmDecider` を使用して並列/順次処理を行う。
190pub struct LlmBatchProcessor<D: LlmDecider> {
191    decider: Arc<D>,
192    config: LlmBatchProcessorConfig,
193}
194
195impl<D: LlmDecider> LlmBatchProcessor<D> {
196    /// 新しい LlmBatchProcessor を作成
197    pub fn new(decider: D) -> Self {
198        Self {
199            decider: Arc::new(decider),
200            config: LlmBatchProcessorConfig::default(),
201        }
202    }
203
204    /// Arc でラップされた Decider から作成
205    pub fn from_arc(decider: Arc<D>) -> Self {
206        Self {
207            decider,
208            config: LlmBatchProcessorConfig::default(),
209        }
210    }
211
212    /// 設定を指定して作成
213    pub fn with_config(mut self, config: LlmBatchProcessorConfig) -> Self {
214        self.config = config;
215        self
216    }
217}
218
219impl<D: LlmDecider + 'static> BatchProcessor for LlmBatchProcessor<D> {
220    fn process(
221        &self,
222        request: BatchDecisionRequest,
223    ) -> Pin<Box<dyn Future<Output = BatchProcessResult> + Send + '_>> {
224        Box::pin(async move {
225            if request.requests.is_empty() {
226                return vec![];
227            }
228
229            // Core の WorkerDecisionRequest をそのまま使用(変換不要)
230            let requests: Vec<(WorkerId, WorkerDecisionRequest)> = request
231                .requests
232                .into_iter()
233                .map(|r| (r.worker_id, r))
234                .collect();
235
236            if self.config.parallel {
237                self.process_parallel(requests).await
238            } else {
239                self.process_sequential(requests).await
240            }
241        })
242    }
243
244    fn plan_dependencies(
245        &self,
246        task: &str,
247        actions: &[ActionDef],
248    ) -> Pin<Box<dyn Future<Output = Option<DependencyGraph>> + Send + '_>> {
249        let task = task.to_string();
250        let actions: Vec<ActionDef> = actions.to_vec();
251        let decider = Arc::clone(&self.decider);
252
253        Box::pin(async move {
254            use std::time::Instant;
255            use swarm_engine_core::actions::ActionCategory;
256            use swarm_engine_core::exploration::DependencyGraphBuilder;
257
258            let start_time = Instant::now();
259            let action_names: Vec<String> = actions.iter().map(|a| a.name.clone()).collect();
260
261            // 1. Discover (NodeExpand) と NotDiscover (NodeStateChange) に分離
262            let discover: Vec<&ActionDef> = actions
263                .iter()
264                .filter(|a| a.category == ActionCategory::NodeExpand)
265                .collect();
266            let not_discover: Vec<&ActionDef> = actions
267                .iter()
268                .filter(|a| a.category == ActionCategory::NodeStateChange)
269                .collect();
270
271            tracing::debug!(
272                discover = ?discover.iter().map(|a| &a.name).collect::<Vec<_>>(),
273                not_discover = ?not_discover.iter().map(|a| &a.name).collect::<Vec<_>>(),
274                "Separated actions by category"
275            );
276
277            // 2. Discover も Binary + Vote でソート(順序関係を保持)
278            let discover_sort_start = Instant::now();
279            let sorted_discover = if discover.len() <= 1 {
280                discover.iter().map(|a| a.name.clone()).collect()
281            } else {
282                binary_sort_actions(&task, &discover, decider.as_ref()).await
283            };
284            let discover_sort_ms = discover_sort_start.elapsed().as_millis();
285
286            tracing::debug!(
287                sorted = ?sorted_discover,
288                elapsed_ms = discover_sort_ms,
289                "Sorted Discover actions via binary comparison"
290            );
291
292            // 3. NotDiscover を Binary + Vote でソート
293            let not_discover_sort_start = Instant::now();
294            let sorted_not_discover = if not_discover.len() <= 1 {
295                not_discover.iter().map(|a| a.name.clone()).collect()
296            } else {
297                binary_sort_actions(&task, &not_discover, decider.as_ref()).await
298            };
299            let not_discover_sort_ms = not_discover_sort_start.elapsed().as_millis();
300
301            tracing::debug!(
302                sorted = ?sorted_not_discover,
303                elapsed_ms = not_discover_sort_ms,
304                "Sorted NotDiscover actions via binary comparison"
305            );
306
307            // 4. グラフ構築: Discover(線形)→ NotDiscover(線形)
308            let mut builder = DependencyGraphBuilder::new()
309                .task(&task)
310                .available_actions(action_names.clone());
311
312            // 最初の Discover を Start node として設定
313            if !sorted_discover.is_empty() {
314                builder = builder.start_node(&sorted_discover[0]);
315            } else if !sorted_not_discover.is_empty() {
316                // Discover がなければ最初の NotDiscover を Start に
317                builder = builder.start_node(&sorted_not_discover[0]);
318            }
319
320            // NotDiscover の最後を Terminal に
321            if let Some(last) = sorted_not_discover.last() {
322                builder = builder.terminal_node(last);
323            } else if !sorted_discover.is_empty() {
324                // NotDiscover がなければ最後の Discover を Terminal に
325                builder = builder.terminal_node(sorted_discover.last().unwrap());
326            }
327
328            // Discover 間のエッジ(線形)
329            for window in sorted_discover.windows(2) {
330                builder = builder.edge(&window[0], &window[1], 0.9);
331            }
332
333            // 最後の Discover → 最初の NotDiscover へのエッジ
334            if !sorted_discover.is_empty() && !sorted_not_discover.is_empty() {
335                builder = builder.edge(
336                    sorted_discover.last().unwrap(),
337                    &sorted_not_discover[0],
338                    0.9,
339                );
340            }
341
342            // NotDiscover 間のエッジ(線形)
343            for window in sorted_not_discover.windows(2) {
344                builder = builder.edge(&window[0], &window[1], 0.9);
345            }
346
347            let mut graph = builder.build();
348            let total_ms = start_time.elapsed().as_millis();
349
350            // Store action order for caching
351            graph.set_action_order(sorted_discover.clone(), sorted_not_discover.clone());
352
353            tracing::info!(
354                discover_order = ?sorted_discover,
355                not_discover_order = ?sorted_not_discover,
356                edges = graph.edges().len(),
357                discover_sort_ms = discover_sort_ms,
358                not_discover_sort_ms = not_discover_sort_ms,
359                total_ms = total_ms,
360                "DependencyGraph generated via LLM binary sort"
361            );
362
363            Some(graph)
364        })
365    }
366
367    fn is_healthy(&self) -> Pin<Box<dyn Future<Output = bool> + Send + '_>> {
368        let decider = Arc::clone(&self.decider);
369        Box::pin(async move { decider.is_healthy().await })
370    }
371
372    fn name(&self) -> &str {
373        self.decider.model_name()
374    }
375}
376
377impl<D: LlmDecider + 'static> LlmBatchProcessor<D> {
378    /// 並列実行(LoRA グルーピング + Semaphore で同時実行数を制限)
379    ///
380    /// # LoRA グルーピング
381    ///
382    /// llama.cpp の continuous batching では、同じ LoRA 設定のリクエストは
383    /// 効率的にバッチ処理される。異なる LoRA を混ぜると効率が落ちるため、
384    /// リクエストを LoRA 設定でグルーピングして処理する。
385    ///
386    /// ```text
387    /// リクエスト群
388    /// ├── LoRA A のリクエスト群 → 並列実行(グループ内)
389    /// ├── LoRA B のリクエスト群 → 並列実行(グループ内)
390    /// └── LoRA なしのリクエスト群 → 並列実行(グループ内)
391    /// ```
392    ///
393    /// グループ間は順次処理(同じ LoRA を連続して処理することで効率化)
394    async fn process_parallel(
395        &self,
396        requests: Vec<(WorkerId, WorkerDecisionRequest)>,
397    ) -> BatchProcessResult {
398        // リクエストを LoRA 設定でグルーピング
399        let grouped = group_by_lora(requests);
400
401        let group_count = grouped.len();
402        if group_count > 1 {
403            tracing::debug!(
404                groups = group_count,
405                "Processing requests in {} LoRA groups",
406                group_count
407            );
408        }
409
410        // 各グループを順次処理(グループ内は並列)
411        let mut all_results = Vec::new();
412        for (lora_config, group_requests) in grouped {
413            if group_count > 1 {
414                tracing::trace!(
415                    lora = ?lora_config,
416                    count = group_requests.len(),
417                    "Processing LoRA group"
418                );
419            }
420            let results = self.process_group(group_requests).await;
421            all_results.extend(results);
422        }
423
424        all_results
425    }
426
427    /// 単一グループの並列処理(Semaphore で同時実行数を制限)
428    async fn process_group(
429        &self,
430        requests: Vec<(WorkerId, WorkerDecisionRequest)>,
431    ) -> BatchProcessResult {
432        use futures::future::join_all;
433        use tokio::sync::Semaphore;
434
435        // サーバーからスロット数を取得、取得できなければconfig値を使用
436        let max_concurrency = self
437            .decider
438            .max_concurrency()
439            .await
440            .unwrap_or(self.config.max_concurrency);
441
442        let semaphore = Arc::new(Semaphore::new(max_concurrency));
443
444        let futures: Vec<_> = requests
445            .into_iter()
446            .map(|(worker_id, req)| {
447                let decider = Arc::clone(&self.decider);
448                let sem = Arc::clone(&semaphore);
449                async move {
450                    // スロットを取得してから実行
451                    let _permit = sem.acquire().await.expect("Semaphore closed");
452                    let result = decider.decide(req).await;
453                    (worker_id, result)
454                }
455            })
456            .collect();
457
458        let results = join_all(futures).await;
459
460        results
461            .into_iter()
462            .map(|(worker_id, result)| {
463                let mapped = result.map_err(BatchProcessError::from);
464                (worker_id, mapped)
465            })
466            .collect()
467    }
468
469    /// 順次実行
470    async fn process_sequential(
471        &self,
472        requests: Vec<(WorkerId, WorkerDecisionRequest)>,
473    ) -> BatchProcessResult {
474        let mut results = Vec::with_capacity(requests.len());
475
476        for (worker_id, req) in requests {
477            let result = self.decider.decide(req).await;
478            let mapped = result.map_err(BatchProcessError::from);
479            results.push((worker_id, mapped));
480        }
481
482        results
483    }
484}
485
486/// リクエストを LoRA 設定でグルーピング
487///
488/// 同じ LoRA 設定(または LoRA なし)のリクエストをまとめる。
489/// HashMap の順序は不定だが、グループ内の順序は保持される。
490fn group_by_lora(
491    requests: Vec<(WorkerId, WorkerDecisionRequest)>,
492) -> HashMap<Option<LoraConfig>, Vec<(WorkerId, WorkerDecisionRequest)>> {
493    let mut groups: HashMap<Option<LoraConfig>, Vec<(WorkerId, WorkerDecisionRequest)>> =
494        HashMap::new();
495
496    for (worker_id, req) in requests {
497        let lora_key = req.lora.clone();
498        groups.entry(lora_key).or_default().push((worker_id, req));
499    }
500
501    groups
502}
503
504// ============================================================================
505// Helper Functions
506// ============================================================================
507
508/// Binary + Vote でアクションをソート(バッチ版)
509///
510/// 全ペア × 3回分のプロンプトを一括でバッチ送信し、結果を集計。
511/// 勝ち数でソート(勝ち数が少ない = 先に来る)。
512async fn binary_sort_actions<D: LlmDecider>(
513    task: &str,
514    actions: &[&ActionDef],
515    decider: &D,
516) -> Vec<String> {
517    use futures::future::join_all;
518    use std::collections::HashMap;
519
520    if actions.len() <= 1 {
521        return actions.iter().map(|a| a.name.clone()).collect();
522    }
523
524    // 全ペア × 3回分のリクエストを作成
525    // (pair_index, vote_index, prompt, a_name, b_name)
526    let mut requests: Vec<(usize, usize, String, String, String)> = Vec::new();
527    let mut pair_index = 0;
528
529    for i in 0..actions.len() {
530        for j in (i + 1)..actions.len() {
531            let a = actions[i];
532            let b = actions[j];
533            let prompt = format!(
534                "Goal: {}\n- {}: {}\n- {}: {}\nWhich comes first: {} or {}?\nAnswer (one word):",
535                task, a.name, a.description, b.name, b.description, a.name, b.name
536            );
537
538            // 同じペアを3回投げる
539            for vote_idx in 0..3 {
540                requests.push((
541                    pair_index,
542                    vote_idx,
543                    prompt.clone(),
544                    a.name.clone(),
545                    b.name.clone(),
546                ));
547            }
548            pair_index += 1;
549        }
550    }
551
552    let total_requests = requests.len();
553    tracing::debug!(
554        pairs = pair_index,
555        total_requests = total_requests,
556        "Binary sort: sending batch requests"
557    );
558
559    // 全リクエストを並列で送信
560    // Note: Binary sort does not use LoRA (base model only)
561    let futures: Vec<_> = requests
562        .into_iter()
563        .map(|(pair_idx, vote_idx, prompt, a_name, b_name)| {
564            let decider_ref = decider;
565            async move {
566                let result = decider_ref.call_raw(&prompt, None).await;
567                (pair_idx, vote_idx, result, a_name, b_name)
568            }
569        })
570        .collect();
571
572    let results = join_all(futures).await;
573
574    // ペアごとに投票結果を集計
575    // pair_index -> (a_count, b_count, a_name, b_name)
576    let mut pair_votes: HashMap<usize, (usize, usize, String, String)> = HashMap::new();
577
578    for (pair_idx, _vote_idx, result, a_name, b_name) in results {
579        let entry = pair_votes
580            .entry(pair_idx)
581            .or_insert((0, 0, a_name.clone(), b_name.clone()));
582
583        if let Ok(response) = result {
584            let response_upper = response.to_uppercase();
585            let a_upper = a_name.to_uppercase();
586            let b_upper = b_name.to_uppercase();
587
588            if response_upper.contains(&a_upper) {
589                entry.0 += 1;
590            } else if response_upper.contains(&b_upper) {
591                entry.1 += 1;
592            }
593        }
594    }
595
596    // 各アクションの「勝ち数」をカウント
597    let mut wins: HashMap<String, usize> = HashMap::new();
598    for a in actions {
599        wins.insert(a.name.clone(), 0);
600    }
601
602    for (_pair_idx, (a_count, b_count, a_name, b_name)) in pair_votes {
603        // winner = 「先に来る方」なので、もう一方が「後」= 勝ち
604        if a_count >= b_count {
605            // a が先 → b に勝ち+1
606            *wins.get_mut(&b_name).unwrap() += 1;
607        } else {
608            // b が先 → a に勝ち+1
609            *wins.get_mut(&a_name).unwrap() += 1;
610        }
611    }
612
613    // 勝ち数が少ない順にソート(先に来るものが少ない)
614    let mut sorted: Vec<_> = wins.into_iter().collect();
615    sorted.sort_by_key(|(_, count)| *count);
616
617    tracing::debug!(
618        sorted = ?sorted.iter().map(|(n, c)| format!("{}:{}", n, c)).collect::<Vec<_>>(),
619        "Binary sort completed"
620    );
621
622    sorted.into_iter().map(|(name, _)| name).collect()
623}
624
625// ============================================================================
626// Tests
627// ============================================================================
628
629#[cfg(test)]
630mod tests {
631    use super::*;
632
633    #[test]
634    fn test_batch_process_error_transient() {
635        let err = BatchProcessError::transient("connection timeout");
636        assert!(err.is_transient());
637        assert_eq!(err.message(), "connection timeout");
638    }
639
640    #[test]
641    fn test_batch_process_error_permanent() {
642        let err = BatchProcessError::permanent("invalid model");
643        assert!(!err.is_transient());
644        assert_eq!(err.message(), "invalid model");
645    }
646
647    #[test]
648    fn test_batch_process_error_from_llm_error() {
649        let llm_err = LlmError::transient("timeout");
650        let batch_err: BatchProcessError = llm_err.into();
651        assert!(batch_err.is_transient());
652        assert_eq!(batch_err.message(), "timeout");
653    }
654
655    #[test]
656    fn test_ollama_batch_processor_config_default() {
657        let config = LlmBatchProcessorConfig::default();
658        assert!(config.parallel);
659        assert_eq!(config.max_concurrency, 4);
660    }
661
662    // =========================================================================
663    // Binary Sort Tests
664    // =========================================================================
665
666    use std::collections::HashMap;
667
668    /// 同期版の binary_sort (テスト用)
669    /// wins の計算ロジックをテスト
670    fn binary_sort_sync(
671        actions: &[&str],
672        // (a, b) -> winner (先に来る方)
673        comparator: impl Fn(&str, &str) -> String,
674    ) -> Vec<String> {
675        if actions.len() <= 1 {
676            return actions.iter().map(|s| s.to_string()).collect();
677        }
678
679        let mut wins: HashMap<String, usize> = HashMap::new();
680        for &a in actions {
681            wins.insert(a.to_string(), 0);
682        }
683
684        for i in 0..actions.len() {
685            for j in (i + 1)..actions.len() {
686                let a = actions[i];
687                let b = actions[j];
688                let winner = comparator(a, b);
689
690                // winner = 先に来る方 → もう一方が後 = 勝ち
691                if winner == a {
692                    *wins.get_mut(b).unwrap() += 1;
693                } else {
694                    *wins.get_mut(a).unwrap() += 1;
695                }
696            }
697        }
698
699        let mut sorted: Vec<_> = wins.into_iter().collect();
700        sorted.sort_by_key(|(_, count)| *count);
701        sorted.into_iter().map(|(name, _)| name).collect()
702    }
703
704    #[test]
705    fn test_binary_sort_two_actions() {
706        // Fetch が先、Summarize が後
707        let result = binary_sort_sync(
708            &["Fetch", "Summarize"],
709            |a, _b| a.to_string(), // 常に a が先
710        );
711        assert_eq!(result, vec!["Fetch", "Summarize"]);
712
713        // Summarize が先、Fetch が後
714        let result = binary_sort_sync(
715            &["Fetch", "Summarize"],
716            |_a, b| b.to_string(), // 常に b が先
717        );
718        assert_eq!(result, vec!["Summarize", "Fetch"]);
719    }
720
721    #[test]
722    fn test_binary_sort_three_actions() {
723        // Test -> Deploy の順
724        // comparator: 常に正しい順序を返す
725        let result = binary_sort_sync(&["Test", "Deploy", "Build"], |a, b| {
726            let order = ["Build", "Test", "Deploy"];
727            let a_idx = order.iter().position(|&x| x == a).unwrap();
728            let b_idx = order.iter().position(|&x| x == b).unwrap();
729            if a_idx < b_idx {
730                a.to_string()
731            } else {
732                b.to_string()
733            }
734        });
735        assert_eq!(result, vec!["Build", "Test", "Deploy"]);
736    }
737
738    #[test]
739    fn test_binary_sort_wins_calculation() {
740        // 3つのアクション: A, B, C
741        // 正しい順序: A -> B -> C
742        // 比較結果:
743        //   A vs B -> A が先 -> B に+1
744        //   A vs C -> A が先 -> C に+1
745        //   B vs C -> B が先 -> C に+1
746        // wins = {A: 0, B: 1, C: 2}
747        // ソート後: A(0), B(1), C(2)
748
749        let mut wins: HashMap<String, usize> = HashMap::new();
750        wins.insert("A".to_string(), 0);
751        wins.insert("B".to_string(), 0);
752        wins.insert("C".to_string(), 0);
753
754        // A vs B: A が先 → B に+1
755        *wins.get_mut("B").unwrap() += 1;
756        // A vs C: A が先 → C に+1
757        *wins.get_mut("C").unwrap() += 1;
758        // B vs C: B が先 → C に+1
759        *wins.get_mut("C").unwrap() += 1;
760
761        assert_eq!(wins["A"], 0);
762        assert_eq!(wins["B"], 1);
763        assert_eq!(wins["C"], 2);
764
765        let mut sorted: Vec<_> = wins.into_iter().collect();
766        sorted.sort_by_key(|(_, count)| *count);
767        let result: Vec<_> = sorted.into_iter().map(|(name, _)| name).collect();
768
769        assert_eq!(result, vec!["A", "B", "C"]);
770    }
771
772    /// response から winner を抽出するロジックのテスト
773    fn extract_winner(response: &str, a: &str, b: &str) -> Option<String> {
774        let response_upper = response.to_uppercase();
775        let a_upper = a.to_uppercase();
776        let b_upper = b.to_uppercase();
777
778        if response_upper.contains(&a_upper) {
779            Some(a.to_string())
780        } else if response_upper.contains(&b_upper) {
781            Some(b.to_string())
782        } else {
783            None
784        }
785    }
786
787    #[test]
788    fn test_extract_winner() {
789        // 正常ケース
790        assert_eq!(
791            extract_winner("Fetch", "Fetch", "Summarize"),
792            Some("Fetch".to_string())
793        );
794        assert_eq!(
795            extract_winner("Summarize", "Fetch", "Summarize"),
796            Some("Summarize".to_string())
797        );
798
799        // 先頭スペース
800        assert_eq!(
801            extract_winner(" Fetch", "Fetch", "Summarize"),
802            Some("Fetch".to_string())
803        );
804
805        // 大文字小文字
806        assert_eq!(
807            extract_winner("fetch", "Fetch", "Summarize"),
808            Some("Fetch".to_string())
809        );
810        assert_eq!(
811            extract_winner("FETCH", "Fetch", "Summarize"),
812            Some("Fetch".to_string())
813        );
814
815        // 文中に含まれる
816        assert_eq!(
817            extract_winner("The answer is Fetch.", "Fetch", "Summarize"),
818            Some("Fetch".to_string())
819        );
820
821        // どちらも含まれない
822        assert_eq!(extract_winner("Unknown", "Fetch", "Summarize"), None);
823
824        // 両方含まれる場合は先にマッチした方
825        assert_eq!(
826            extract_winner("Fetch then Summarize", "Fetch", "Summarize"),
827            Some("Fetch".to_string())
828        );
829    }
830
831    #[test]
832    fn test_vote_majority() {
833        // 3回の投票で多数決
834        fn vote_majority(responses: &[&str], a: &str, b: &str) -> String {
835            let mut a_count = 0;
836            let mut b_count = 0;
837
838            for response in responses {
839                if let Some(winner) = extract_winner(response, a, b) {
840                    if winner == a {
841                        a_count += 1;
842                    } else {
843                        b_count += 1;
844                    }
845                }
846            }
847
848            if a_count >= b_count {
849                a.to_string()
850            } else {
851                b.to_string()
852            }
853        }
854
855        // 3回とも Fetch
856        assert_eq!(
857            vote_majority(&["Fetch", "Fetch", "Fetch"], "Fetch", "Summarize"),
858            "Fetch"
859        );
860
861        // 2回 Fetch, 1回 Summarize
862        assert_eq!(
863            vote_majority(&["Fetch", "Summarize", "Fetch"], "Fetch", "Summarize"),
864            "Fetch"
865        );
866
867        // 2回 Summarize, 1回 Fetch
868        assert_eq!(
869            vote_majority(&["Summarize", "Summarize", "Fetch"], "Fetch", "Summarize"),
870            "Summarize"
871        );
872
873        // 同数の場合は a (Fetch) を返す
874        assert_eq!(
875            vote_majority(&["Fetch", "Summarize", "Unknown"], "Fetch", "Summarize"),
876            "Fetch"
877        );
878    }
879
880    // =========================================================================
881    // LoRA Grouping Tests
882    // =========================================================================
883
884    use swarm_engine_core::context::{ContextTarget, GlobalContext, ResolvedContext};
885
886    fn create_test_request(
887        worker_id: usize,
888        lora: Option<LoraConfig>,
889    ) -> (WorkerId, WorkerDecisionRequest) {
890        let global = GlobalContext {
891            tick: 0,
892            max_ticks: 100,
893            progress: 0.0,
894            success_rate: 0.0,
895            task_description: Some("test".to_string()),
896            hint: None,
897        };
898        let context = ResolvedContext::new(global, ContextTarget::Worker(WorkerId(worker_id)));
899
900        (
901            WorkerId(worker_id),
902            WorkerDecisionRequest {
903                worker_id: WorkerId(worker_id),
904                query: format!("query_{}", worker_id),
905                context,
906                lora,
907            },
908        )
909    }
910
911    #[test]
912    fn test_group_by_lora_single_group_no_lora() {
913        let requests = vec![
914            create_test_request(0, None),
915            create_test_request(1, None),
916            create_test_request(2, None),
917        ];
918
919        let groups = group_by_lora(requests);
920
921        assert_eq!(groups.len(), 1);
922        assert!(groups.contains_key(&None));
923        assert_eq!(groups[&None].len(), 3);
924    }
925
926    #[test]
927    fn test_group_by_lora_single_group_with_lora() {
928        let lora = LoraConfig::with_id(0);
929        let requests = vec![
930            create_test_request(0, Some(lora.clone())),
931            create_test_request(1, Some(lora.clone())),
932        ];
933
934        let groups = group_by_lora(requests);
935
936        assert_eq!(groups.len(), 1);
937        assert!(groups.contains_key(&Some(lora)));
938    }
939
940    #[test]
941    fn test_group_by_lora_multiple_groups() {
942        let lora_a = LoraConfig::with_id(0);
943        let lora_b = LoraConfig::with_id(1);
944
945        let requests = vec![
946            create_test_request(0, Some(lora_a.clone())),
947            create_test_request(1, Some(lora_b.clone())),
948            create_test_request(2, Some(lora_a.clone())),
949            create_test_request(3, None),
950            create_test_request(4, Some(lora_b.clone())),
951        ];
952
953        let groups = group_by_lora(requests);
954
955        assert_eq!(groups.len(), 3);
956        assert_eq!(groups[&Some(lora_a)].len(), 2);
957        assert_eq!(groups[&Some(lora_b)].len(), 2);
958        assert_eq!(groups[&None].len(), 1);
959    }
960
961    #[test]
962    fn test_group_by_lora_preserves_order_within_group() {
963        let lora = LoraConfig::with_id(0);
964        let requests = vec![
965            create_test_request(5, Some(lora.clone())),
966            create_test_request(3, Some(lora.clone())),
967            create_test_request(7, Some(lora.clone())),
968        ];
969
970        let groups = group_by_lora(requests);
971        let group = &groups[&Some(lora)];
972
973        // グループ内の順序は保持される
974        assert_eq!(group[0].0, WorkerId(5));
975        assert_eq!(group[1].0, WorkerId(3));
976        assert_eq!(group[2].0, WorkerId(7));
977    }
978
979    #[test]
980    fn test_group_by_lora_different_scales() {
981        // 同じ ID でも scale が違えば別グループ
982        let lora_full = LoraConfig::new(0, 1.0);
983        let lora_half = LoraConfig::new(0, 0.5);
984
985        let requests = vec![
986            create_test_request(0, Some(lora_full.clone())),
987            create_test_request(1, Some(lora_half.clone())),
988            create_test_request(2, Some(lora_full.clone())),
989        ];
990
991        let groups = group_by_lora(requests);
992
993        assert_eq!(groups.len(), 2);
994        assert_eq!(groups[&Some(lora_full)].len(), 2);
995        assert_eq!(groups[&Some(lora_half)].len(), 1);
996    }
997
998    #[test]
999    fn test_group_by_lora_empty() {
1000        let requests: Vec<(WorkerId, WorkerDecisionRequest)> = vec![];
1001        let groups = group_by_lora(requests);
1002        assert!(groups.is_empty());
1003    }
1004}