converge-optimization 0.1.1

Optimization algorithms for converge.zone - Rust reimplementation of OR-Tools subset
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
//! Converge platform integration
//!
//! This module provides the interface for using optimization
//! algorithms as converge-provider capabilities.
//!
//! ## Usage in Converge
//!
//! ```rust,ignore
//! use converge_optimization::provider::{OptimizationProvider, OptimizationType};
//!
//! // Register as a capability
//! let provider = OptimizationProvider::new(OptimizationType::Assignment);
//! capability_registry.register("optimize.assignment", provider);
//! ```
//!
//! ## Gate-Based Solving
//!
//! For domain-specific optimization with invariants and promotion gates:
//!
//! ```rust,ignore
//! use converge_optimization::provider::GateProvider;
//! use converge_optimization::gate::ProblemSpec;
//!
//! let provider = GateProvider::new();
//! let result = provider.solve("meeting-scheduler", &spec)?;
//! assert!(result.gate.is_promoted());
//! ```

use crate::{
    assignment::{self, AssignmentProblem},
    gate::{ProblemSpec, PromotionGate, ProposedPlan, SolverReport},
    knapsack::{self, KnapsackProblem},
    graph::dijkstra,
    packs::{InvariantResult, PackRegistry},
    SolverParams,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// Types of optimization available
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OptimizationType {
    /// Linear assignment problem
    Assignment,
    /// Knapsack problem
    Knapsack,
    /// Shortest path
    ShortestPath,
    /// Max flow
    MaxFlow,
    /// Min cost flow
    MinCostFlow,
    /// Set cover
    SetCover,
    /// Scheduling
    Scheduling,
    /// Vehicle routing (requires FFI)
    VehicleRouting,
    /// Constraint programming (requires FFI)
    ConstraintProgramming,
}

/// Request for optimization
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum OptimizationRequest {
    /// Assignment problem
    Assignment {
        /// Cost matrix
        costs: Vec<Vec<i64>>,
    },
    /// Knapsack problem
    Knapsack {
        /// Item weights
        weights: Vec<i64>,
        /// Item values
        values: Vec<i64>,
        /// Capacity
        capacity: i64,
    },
    /// Shortest path problem
    ShortestPath {
        /// Edges as (from, to, cost)
        edges: Vec<(usize, usize, i64)>,
        /// Source node
        source: usize,
        /// Target node
        target: usize,
    },
}

/// Response from optimization
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum OptimizationResponse {
    /// Assignment solution
    Assignment {
        /// Assignment: assignments[agent] = task
        assignments: Vec<usize>,
        /// Total cost
        total_cost: i64,
    },
    /// Knapsack solution
    Knapsack {
        /// Selected items
        selected: Vec<usize>,
        /// Total value
        total_value: i64,
        /// Total weight
        total_weight: i64,
    },
    /// Shortest path solution
    ShortestPath {
        /// Path nodes
        path: Vec<usize>,
        /// Total cost
        cost: i64,
    },
    /// Error response
    Error {
        /// Error message
        message: String,
    },
}

/// Optimization provider for converge platform
#[derive(Debug, Clone)]
pub struct OptimizationProvider {
    /// Type of optimization
    pub optimization_type: OptimizationType,
    /// Solver parameters
    pub params: SolverParams,
}

impl Default for OptimizationProvider {
    fn default() -> Self {
        Self::new(OptimizationType::Assignment)
    }
}

impl OptimizationProvider {
    /// Create a new provider
    pub fn new(optimization_type: OptimizationType) -> Self {
        Self {
            optimization_type,
            params: SolverParams::default(),
        }
    }

    /// Set solver parameters
    pub fn with_params(mut self, params: SolverParams) -> Self {
        self.params = params;
        self
    }

    /// Solve an optimization problem
    pub fn solve(&self, request: OptimizationRequest) -> OptimizationResponse {
        match request {
            OptimizationRequest::Assignment { costs } => {
                self.solve_assignment(costs)
            }
            OptimizationRequest::Knapsack { weights, values, capacity } => {
                self.solve_knapsack(weights, values, capacity)
            }
            OptimizationRequest::ShortestPath { edges, source, target } => {
                self.solve_shortest_path(edges, source, target)
            }
        }
    }

    fn solve_assignment(&self, costs: Vec<Vec<i64>>) -> OptimizationResponse {
        let problem = AssignmentProblem::from_costs(costs);
        match assignment::solve(&problem) {
            Ok(solution) => OptimizationResponse::Assignment {
                assignments: solution.assignments,
                total_cost: solution.total_cost,
            },
            Err(e) => OptimizationResponse::Error {
                message: e.to_string(),
            },
        }
    }

    fn solve_knapsack(&self, weights: Vec<i64>, values: Vec<i64>, capacity: i64) -> OptimizationResponse {
        match KnapsackProblem::new(weights, values, capacity) {
            Ok(problem) => match knapsack::solve(&problem) {
                Ok(solution) => OptimizationResponse::Knapsack {
                    selected: solution.selected,
                    total_value: solution.total_value,
                    total_weight: solution.total_weight,
                },
                Err(e) => OptimizationResponse::Error {
                    message: e.to_string(),
                },
            },
            Err(e) => OptimizationResponse::Error {
                message: e.to_string(),
            },
        }
    }

    fn solve_shortest_path(
        &self,
        edges: Vec<(usize, usize, i64)>,
        source: usize,
        target: usize,
    ) -> OptimizationResponse {
        use petgraph::graph::DiGraph;

        // Build graph
        let mut graph: DiGraph<(), i64> = DiGraph::new();
        let max_node = edges.iter()
            .flat_map(|(a, b, _)| [*a, *b])
            .max()
            .unwrap_or(0);

        // Add nodes
        let nodes: Vec<_> = (0..=max_node).map(|_| graph.add_node(())).collect();

        // Add edges
        for (from, to, cost) in edges {
            if from <= max_node && to <= max_node {
                graph.add_edge(nodes[from], nodes[to], cost);
            }
        }

        if source > max_node || target > max_node {
            return OptimizationResponse::Error {
                message: "source or target node out of range".to_string(),
            };
        }

        match dijkstra::shortest_path(&graph, nodes[source], nodes[target], |&w| w) {
            Ok(Some(path)) => OptimizationResponse::ShortestPath {
                path: vec![source, target], // Simplified
                cost: path.cost,
            },
            Ok(None) => OptimizationResponse::Error {
                message: "no path exists".to_string(),
            },
            Err(e) => OptimizationResponse::Error {
                message: e.to_string(),
            },
        }
    }
}

// ============================================================================
// Gate-Based Provider
// ============================================================================

/// Gate-based optimization provider
///
/// Provides access to domain packs through the solver gate architecture.
/// Each solve returns a complete result including the proposed plan,
/// solver reports, invariant checks, and promotion gate decision.
#[derive(Clone)]
pub struct GateProvider {
    registry: Arc<PackRegistry>,
}

impl Default for GateProvider {
    fn default() -> Self {
        Self::new()
    }
}

impl GateProvider {
    /// Create with default built-in packs
    pub fn new() -> Self {
        Self {
            registry: Arc::new(PackRegistry::with_builtins()),
        }
    }

    /// Create with custom registry
    pub fn with_registry(registry: Arc<PackRegistry>) -> Self {
        Self { registry }
    }

    /// Get the underlying registry
    pub fn registry(&self) -> &PackRegistry {
        &self.registry
    }

    /// List available packs
    pub fn list_packs(&self) -> Vec<&str> {
        self.registry.list()
    }

    /// Check if a pack is available
    pub fn has_pack(&self, name: &str) -> bool {
        self.registry.contains(name)
    }

    /// Solve a problem through the gate
    ///
    /// This method:
    /// 1. Validates inputs against the pack schema
    /// 2. Solves the problem using the pack's solver
    /// 3. Checks all invariants
    /// 4. Evaluates the promotion gate
    ///
    /// Returns a complete result including all artifacts.
    pub fn solve(&self, pack_name: &str, spec: &ProblemSpec) -> crate::Result<GateSolveResult> {
        // Get the pack
        let pack = self
            .registry
            .get(pack_name)
            .ok_or_else(|| crate::Error::invalid_input(format!("unknown pack: {}", pack_name)))?;

        // Validate inputs against pack schema
        pack.validate_inputs(&spec.inputs)?;

        // Solve
        let solve_result = pack.solve(spec)?;

        // Check invariants
        let invariant_results = pack.check_invariants(&solve_result.plan)?;

        // Evaluate gate
        let gate = pack.evaluate_gate(&solve_result.plan, &invariant_results);

        Ok(GateSolveResult {
            plan: solve_result.plan,
            reports: solve_result.reports,
            invariant_results,
            gate,
        })
    }
}

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

/// Complete result from gate-based solving
#[derive(Debug)]
pub struct GateSolveResult {
    /// The proposed plan
    pub plan: ProposedPlan,
    /// Solver reports (may have tried multiple solvers)
    pub reports: Vec<SolverReport>,
    /// Results of invariant checks
    pub invariant_results: Vec<InvariantResult>,
    /// The promotion gate decision
    pub gate: PromotionGate,
}

impl GateSolveResult {
    /// Check if the solution is feasible
    pub fn is_feasible(&self) -> bool {
        self.reports.iter().any(|r| r.feasible)
    }

    /// Check if the plan was promoted
    pub fn is_promoted(&self) -> bool {
        self.gate.is_promoted()
    }

    /// Check if the plan was rejected
    pub fn is_rejected(&self) -> bool {
        self.gate.is_rejected()
    }

    /// Check if escalation is required
    pub fn requires_escalation(&self) -> bool {
        self.gate.requires_escalation()
    }

    /// Get failed invariants
    pub fn failed_invariants(&self) -> Vec<&str> {
        self.invariant_results
            .iter()
            .filter(|r| !r.passed)
            .map(|r| r.invariant.as_str())
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::gate::ObjectiveSpec;
    use crate::packs::meeting_scheduler::{
        Attendee, MeetingRequirements, MeetingSchedulerInput, SlotPreference, TimeSlot,
    };

    #[test]
    fn test_assignment_provider() {
        let provider = OptimizationProvider::new(OptimizationType::Assignment);
        let request = OptimizationRequest::Assignment {
            costs: vec![
                vec![10, 5],
                vec![3, 8],
            ],
        };

        let response = provider.solve(request);
        match response {
            OptimizationResponse::Assignment { total_cost, .. } => {
                // (0,1)=5, (1,0)=3 -> 8
                // (0,0)=10, (1,1)=8 -> 18
                // Optimal is 8
                assert_eq!(total_cost, 8);
            }
            _ => panic!("unexpected response"),
        }
    }

    #[test]
    fn test_knapsack_provider() {
        let provider = OptimizationProvider::new(OptimizationType::Knapsack);
        let request = OptimizationRequest::Knapsack {
            weights: vec![10, 20, 30],
            values: vec![60, 100, 120],
            capacity: 50,
        };

        let response = provider.solve(request);
        match response {
            OptimizationResponse::Knapsack { total_value, .. } => {
                assert_eq!(total_value, 220);
            }
            _ => panic!("unexpected response"),
        }
    }

    #[test]
    fn test_gate_provider_new() {
        let provider = GateProvider::new();
        assert!(provider.has_pack("meeting-scheduler"));
        assert!(provider.has_pack("inventory-rebalancing"));
        assert!(!provider.has_pack("nonexistent"));
    }

    #[test]
    fn test_gate_provider_list_packs() {
        let provider = GateProvider::new();
        let packs = provider.list_packs();
        assert!(packs.contains(&"meeting-scheduler"));
        assert!(packs.contains(&"inventory-rebalancing"));
    }

    #[test]
    fn test_gate_provider_solve_meeting_scheduler() {
        let provider = GateProvider::new();

        let input = MeetingSchedulerInput {
            slots: vec![TimeSlot {
                id: "slot-1".to_string(),
                start: 1000,
                end: 2000,
                room: Some("Room A".to_string()),
                capacity: 10,
            }],
            attendees: vec![Attendee {
                id: "alice".to_string(),
                name: "Alice".to_string(),
                required: true,
                available_slots: vec!["slot-1".to_string()],
                preferences: vec![SlotPreference {
                    slot_id: "slot-1".to_string(),
                    score: 10.0,
                }],
            }],
            requirements: MeetingRequirements {
                duration_minutes: 60,
                min_attendees: 1,
                require_room: false,
            },
        };

        let spec = ProblemSpec::builder("test-gate-001", "test-tenant")
            .objective(ObjectiveSpec::maximize("attendance"))
            .inputs(&input)
            .unwrap()
            .seed(42)
            .build()
            .unwrap();

        let result = provider.solve("meeting-scheduler", &spec).unwrap();

        assert!(result.is_feasible());
        assert!(result.is_promoted());
        assert!(result.failed_invariants().is_empty());
    }

    #[test]
    fn test_gate_provider_unknown_pack() {
        let provider = GateProvider::new();

        let spec = ProblemSpec::builder("test", "tenant")
            .objective(ObjectiveSpec::minimize("cost"))
            .inputs_raw(serde_json::json!({}))
            .build()
            .unwrap();

        let result = provider.solve("nonexistent-pack", &spec);
        assert!(result.is_err());
    }

    #[test]
    fn test_gate_solve_result_methods() {
        let provider = GateProvider::new();

        let input = MeetingSchedulerInput {
            slots: vec![TimeSlot {
                id: "slot-1".to_string(),
                start: 1000,
                end: 2000,
                room: None,
                capacity: 10,
            }],
            attendees: vec![Attendee {
                id: "alice".to_string(),
                name: "Alice".to_string(),
                required: true,
                available_slots: vec!["slot-1".to_string()],
                preferences: vec![SlotPreference {
                    slot_id: "slot-1".to_string(),
                    score: 10.0, // Add preference to pass advisory invariant
                }],
            }],
            requirements: MeetingRequirements {
                duration_minutes: 60,
                min_attendees: 1,
                require_room: false,
            },
        };

        let spec = ProblemSpec::builder("test-methods", "tenant")
            .objective(ObjectiveSpec::maximize("attendance"))
            .inputs(&input)
            .unwrap()
            .seed(42)
            .build()
            .unwrap();

        let result = provider.solve("meeting-scheduler", &spec).unwrap();

        // Test all helper methods
        assert!(result.is_feasible());
        assert!(result.is_promoted());
        assert!(!result.is_rejected());
        assert!(!result.requires_escalation());
    }
}