Skip to main content

lean_ctx/core/ocla/
reference_scheduler.rs

1//! Frozen, deterministic OSS reference scheduler.
2//!
3//! This implementation is Class B/C reference behavior only. Production
4//! Class D code may implement [`SchedulerService`] with private decision
5//! intelligence, but this scheduler performs no adaptation, learning, or
6//! ranking from private data.
7
8use std::cmp::Ordering;
9
10use lean_ctx_protocol::{
11    CapabilityId, CapabilityManifestV1, ContextStrategy, ExecutionPlanV1, PlanId, StopCondition,
12    TaskEnvelopeV1,
13};
14
15use super::catalogue::{ProviderEntry, TechnicalCatalogue};
16use super::policy_constraints::PolicyConstraints;
17use super::scheduler_service::{ExecutionCandidate, SchedulerDecision, SchedulerService};
18use super::types::{OclaError, OclaResult};
19
20/// Maximum number of public candidates enumerated by the reference scheduler.
21pub const MAX_CANDIDATES: usize = 100;
22
23const SCHEDULER_REF: &str = "scheduler:reference-v1";
24const FALLBACK_CAPABILITY: &str = "capability://leanctx/passthrough";
25const FALLBACK_MODEL: &str = "manual";
26const FALLBACK_PROVIDER: &str = "leanctx";
27
28/// Deterministic, non-adaptive scheduler supplied for OSS conformance.
29#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
30pub struct ReferenceScheduler;
31
32impl ReferenceScheduler {
33    /// Construct the frozen reference scheduler.
34    #[must_use]
35    pub const fn new() -> Self {
36        Self
37    }
38
39    /// Produce a recommendation, including a fallback, from public inputs.
40    pub fn schedule(
41        &self,
42        envelope: &TaskEnvelopeV1,
43        eligible: &[CapabilityManifestV1],
44        catalogue: &TechnicalCatalogue,
45        policy: &PolicyConstraints,
46    ) -> OclaResult<SchedulerDecision> {
47        let candidates = self.generate_candidates(envelope, eligible, catalogue)?;
48        let fallback = self.fallback_candidate(envelope)?;
49        let (filtered, excluded) = filter_with_report(candidates, policy);
50        let mut decision = self.select_plan(&filtered, &fallback);
51        decision.candidates_evaluated = filtered
52            .len()
53            .saturating_add(excluded.len())
54            .try_into()
55            .unwrap_or(u32::MAX);
56        decision.candidates_excluded = excluded.len().try_into().unwrap_or(u32::MAX);
57        decision.decision_ref = decision_ref(&filtered, &excluded, &fallback);
58        Ok(decision)
59    }
60
61    /// Alias suitable for callers that use recommendation terminology.
62    pub fn recommend(
63        &self,
64        envelope: &TaskEnvelopeV1,
65        eligible: &[CapabilityManifestV1],
66        catalogue: &TechnicalCatalogue,
67        policy: &PolicyConstraints,
68    ) -> OclaResult<SchedulerDecision> {
69        self.schedule(envelope, eligible, catalogue, policy)
70    }
71
72    /// Build the deterministic fallback plan used when no candidate survives.
73    pub fn fallback_plan(&self, envelope: &TaskEnvelopeV1) -> OclaResult<ExecutionPlanV1> {
74        Ok(self.fallback_candidate(envelope)?.plan)
75    }
76
77    fn fallback_candidate(&self, envelope: &TaskEnvelopeV1) -> OclaResult<ExecutionCandidate> {
78        envelope.validate().map_err(|error| {
79            OclaError::InvalidRequest(format!("invalid task envelope: {error}"))
80        })?;
81        let capability_id =
82            CapabilityId::try_from(FALLBACK_CAPABILITY.to_owned()).map_err(|error| {
83                OclaError::InvalidRequest(format!("invalid fallback capability: {error}"))
84            })?;
85        let plan = plan_for(
86            envelope,
87            &capability_id,
88            FALLBACK_MODEL,
89            FALLBACK_PROVIDER,
90            Some("fallback"),
91        )?;
92        Ok(ExecutionCandidate::new(
93            plan,
94            FALLBACK_CAPABILITY,
95            FALLBACK_MODEL,
96            FALLBACK_PROVIDER,
97            Some(0),
98            envelope.quality_requirement_milli.map(u32::from),
99            envelope.latency_budget_ms,
100        ))
101    }
102}
103
104impl SchedulerService for ReferenceScheduler {
105    fn generate_candidates(
106        &self,
107        envelope: &TaskEnvelopeV1,
108        eligible: &[CapabilityManifestV1],
109        catalogue: &TechnicalCatalogue,
110    ) -> OclaResult<Vec<ExecutionCandidate>> {
111        envelope.validate().map_err(|error| {
112            OclaError::InvalidRequest(format!("invalid task envelope: {error}"))
113        })?;
114
115        let mut manifests = eligible
116            .iter()
117            .filter(|manifest| catalogue_allows_manifest(catalogue, manifest))
118            .cloned()
119            .collect::<Vec<_>>();
120        manifests.sort_by_key(manifest_key);
121
122        let mut candidates = Vec::new();
123        for manifest in manifests {
124            manifest.validate().map_err(|error| {
125                OclaError::InvalidRequest(format!("invalid capability manifest: {error}"))
126            })?;
127
128            let provider_options = provider_options(&manifest, catalogue);
129            for (provider, models) in provider_options {
130                for model in models {
131                    if candidates.len() == MAX_CANDIDATES {
132                        return Ok(candidates);
133                    }
134                    let plan =
135                        plan_for(envelope, &manifest.capability_id, &model, &provider, None)?;
136                    candidates.push(ExecutionCandidate::new(
137                        plan,
138                        manifest.capability_id.as_str(),
139                        model,
140                        provider.clone(),
141                        // Public catalogues do not contain pricing data.
142                        None,
143                        envelope.quality_requirement_milli.map(u32::from),
144                        envelope.latency_budget_ms,
145                    ));
146                }
147            }
148        }
149        Ok(candidates)
150    }
151
152    fn filter_candidates(
153        &self,
154        candidates: Vec<ExecutionCandidate>,
155        policy: &PolicyConstraints,
156    ) -> Vec<ExecutionCandidate> {
157        filter_with_report(candidates, policy).0
158    }
159
160    fn select_plan(
161        &self,
162        filtered: &[ExecutionCandidate],
163        fallback: &ExecutionCandidate,
164    ) -> SchedulerDecision {
165        let selected = filtered
166            .iter()
167            .min_by(|left, right| compare_candidates(left, right))
168            .unwrap_or(fallback);
169        let has_candidate = !filtered.is_empty();
170        let rationale_code = if has_candidate {
171            "reference_score_cost_latency_quality"
172        } else {
173            "fallback_no_permitted_candidates"
174        };
175        SchedulerDecision {
176            selected: selected.plan.clone(),
177            fallback: fallback.plan.clone(),
178            decision_ref: decision_ref(filtered, &[], fallback),
179            rationale_code: rationale_code.to_owned(),
180            confidence_milli: if has_candidate { 1000 } else { 0 },
181            candidates_evaluated: filtered.len().try_into().unwrap_or(u32::MAX),
182            candidates_excluded: 0,
183        }
184    }
185}
186
187fn catalogue_allows_manifest(
188    catalogue: &TechnicalCatalogue,
189    manifest: &CapabilityManifestV1,
190) -> bool {
191    catalogue
192        .capability(manifest.capability_id.as_str(), &manifest.version)
193        .is_none_or(|entry| entry.available)
194}
195
196fn manifest_key(manifest: &CapabilityManifestV1) -> (String, String, String) {
197    (
198        manifest.capability_id.as_str().to_owned(),
199        manifest.version.clone(),
200        manifest.provider.clone(),
201    )
202}
203
204fn provider_options(
205    manifest: &CapabilityManifestV1,
206    catalogue: &TechnicalCatalogue,
207) -> Vec<(String, Vec<String>)> {
208    let mut entries = catalogue
209        .providers
210        .iter()
211        .filter(|entry| entry.provider_id == manifest.provider)
212        .collect::<Vec<_>>();
213    entries.sort_by(|left, right| left.provider_id.cmp(&right.provider_id));
214
215    if entries.is_empty() {
216        return vec![(manifest.provider.clone(), model_options(catalogue, None))];
217    }
218
219    entries
220        .into_iter()
221        .map(|entry| {
222            (
223                entry.provider_id.clone(),
224                model_options(catalogue, Some(entry)),
225            )
226        })
227        .collect()
228}
229
230fn model_options(catalogue: &TechnicalCatalogue, provider: Option<&ProviderEntry>) -> Vec<String> {
231    let mut models = match provider {
232        Some(provider) if !provider.models_available.is_empty() => {
233            provider.models_available.clone()
234        }
235        _ => catalogue
236            .models
237            .iter()
238            .map(|model| model.model_id.clone())
239            .collect(),
240    };
241    models.retain(|model| !model.is_empty());
242    models.sort();
243    models.dedup();
244    if models.is_empty() {
245        models.push(FALLBACK_MODEL.to_owned());
246    }
247    models
248}
249
250fn plan_for(
251    envelope: &TaskEnvelopeV1,
252    capability_id: &CapabilityId,
253    model: &str,
254    provider: &str,
255    fallback_marker: Option<&str>,
256) -> OclaResult<ExecutionPlanV1> {
257    let seed = format!(
258        "reference-v1:{}:{}:{}:{}",
259        envelope.task_id.as_str(),
260        capability_id.as_str(),
261        model,
262        provider
263    );
264    let plan_id = PlanId::try_from(format!("plan:{}", blake3::hash(seed.as_bytes()).to_hex()))
265        .map_err(|error| {
266            OclaError::InvalidRequest(format!("invalid deterministic plan id: {error}"))
267        })?;
268    let mut fallback_refs = Vec::new();
269    if let Some(marker) = fallback_marker {
270        fallback_refs.push(marker.to_owned());
271    }
272    let plan = ExecutionPlanV1 {
273        schema_version: 1,
274        plan_id,
275        task_id: envelope.task_id.clone(),
276        context_budget_tokens: 0,
277        context_strategy: ContextStrategy::Balanced,
278        knowledge_refs: Vec::new(),
279        capability_ids: vec![capability_id.clone()],
280        model: model.to_owned(),
281        provider: provider.to_owned(),
282        reasoning_allocation_milli: 0,
283        max_retries: 0,
284        fallback_refs,
285        stop_condition: StopCondition::OnCompletion,
286        expected_cost_micros: 0,
287        expected_quality_milli: envelope.quality_requirement_milli.unwrap_or(0),
288        expected_latency_ms: envelope.latency_budget_ms.unwrap_or(0),
289        policy_decision_ref: None,
290        scheduler_decision_ref: Some(SCHEDULER_REF.to_owned()),
291    };
292    plan.validate().map_err(|error| {
293        OclaError::InvalidRequest(format!("invalid deterministic execution plan: {error}"))
294    })?;
295    Ok(plan)
296}
297
298fn filter_with_report(
299    candidates: Vec<ExecutionCandidate>,
300    policy: &PolicyConstraints,
301) -> (Vec<ExecutionCandidate>, Vec<ExecutionCandidate>) {
302    let mut permitted = Vec::with_capacity(candidates.len());
303    let mut excluded = Vec::new();
304    for mut candidate in candidates {
305        match policy.permits(&candidate) {
306            Ok(()) => {
307                candidate.exclusion_reason = None;
308                permitted.push(candidate);
309            }
310            Err(error) => {
311                candidate.exclusion_reason = Some(error.to_string());
312                excluded.push(candidate);
313            }
314        }
315    }
316    (permitted, excluded)
317}
318
319fn compare_candidates(left: &ExecutionCandidate, right: &ExecutionCandidate) -> Ordering {
320    let left_cost = left
321        .expected_cost_micros
322        .unwrap_or(left.plan.expected_cost_micros);
323    let right_cost = right
324        .expected_cost_micros
325        .unwrap_or(right.plan.expected_cost_micros);
326    let left_latency = left
327        .expected_latency_ms
328        .unwrap_or(left.plan.expected_latency_ms);
329    let right_latency = right
330        .expected_latency_ms
331        .unwrap_or(right.plan.expected_latency_ms);
332    let left_quality = left
333        .expected_quality_milli
334        .unwrap_or(u32::from(left.plan.expected_quality_milli));
335    let right_quality = right
336        .expected_quality_milli
337        .unwrap_or(u32::from(right.plan.expected_quality_milli));
338
339    left_cost
340        .cmp(&right_cost)
341        .then_with(|| left_latency.cmp(&right_latency))
342        .then_with(|| right_quality.cmp(&left_quality))
343}
344
345fn decision_ref(
346    filtered: &[ExecutionCandidate],
347    excluded: &[ExecutionCandidate],
348    fallback: &ExecutionCandidate,
349) -> String {
350    let mut seed = String::from("reference-v1|");
351    for candidate in filtered {
352        seed.push_str("permit:");
353        seed.push_str(&candidate.identity());
354        seed.push('|');
355    }
356    for candidate in excluded {
357        seed.push_str("exclude:");
358        seed.push_str(&candidate.identity());
359        seed.push(':');
360        seed.push_str(candidate.exclusion_reason.as_deref().unwrap_or("unknown"));
361        seed.push('|');
362    }
363    seed.push_str("fallback:");
364    seed.push_str(&fallback.identity());
365    format!(
366        "decision:reference-v1:{}",
367        blake3::hash(seed.as_bytes()).to_hex()
368    )
369}
370
371#[cfg(test)]
372mod tests {
373    use std::collections::BTreeMap;
374
375    use super::*;
376    use crate::core::ocla::catalogue::{CatalogueEntry, ModelEntry, ProviderEntry};
377    use lean_ctx_protocol::{
378        CapabilityKind, DataClassification, DataMovement, Determinism, MeasurementSupportV1,
379        Reversibility, SurfaceSupportV1, TaskComplexity,
380    };
381
382    fn manifest(capability_id: &str, provider: &str) -> CapabilityManifestV1 {
383        CapabilityManifestV1 {
384            schema_version: 1,
385            capability_id: CapabilityId::try_from(capability_id).expect("capability id"),
386            provider: provider.to_owned(),
387            kind: CapabilityKind::Tool,
388            version: "1.0.0".to_owned(),
389            surfaces: vec!["context".to_owned()],
390            support_matrix: BTreeMap::from([(
391                "context".to_owned(),
392                SurfaceSupportV1 {
393                    supported: true,
394                    input_schema_ref: None,
395                    output_schema_ref: None,
396                },
397            )]),
398            local: true,
399            remote: false,
400            reversibility: Reversibility::Reversible,
401            determinism: Determinism::Deterministic,
402            data_movement: DataMovement::LocalOnly,
403            supported_classifications: vec![DataClassification::Public],
404            measurement_support: MeasurementSupportV1 {
405                latency: true,
406                tokens: true,
407                quality: true,
408            },
409            input_schema_ref: None,
410            output_schema_ref: None,
411            conformance_version: 1,
412            extra: BTreeMap::new(),
413        }
414    }
415
416    fn envelope() -> TaskEnvelopeV1 {
417        TaskEnvelopeV1 {
418            schema_version: 1,
419            task_id: "task-reference".try_into().expect("task id"),
420            trace_id: "trace-reference".try_into().expect("trace id"),
421            project_id: "project-reference".try_into().expect("project id"),
422            session_id: "session-reference".try_into().expect("session id"),
423            agent_id: "agent-reference".try_into().expect("agent id"),
424            complexity: TaskComplexity::Low,
425            created_at: "2026-08-09T00:00:00Z".to_owned(),
426            parent_task_id: None,
427            tenant_id: None,
428            intent: Some("inspect".to_owned()),
429            task_class: None,
430            risk_class: None,
431            quality_requirement_milli: Some(700),
432            cost_budget_micros: None,
433            latency_budget_ms: Some(500),
434            data_classification: Some(DataClassification::Public),
435            region_policy_ref: None,
436            model_policy_ref: None,
437            context_state_ref: None,
438            outcome_contract_ref: None,
439        }
440    }
441
442    #[test]
443    fn generate_candidates_enumerates_models_and_is_capped() {
444        let capability = manifest("capability://search", "provider-a");
445        let mut catalogue = TechnicalCatalogue {
446            capabilities: vec![CatalogueEntry {
447                capability_id: capability.capability_id.as_str().to_owned(),
448                version: capability.version.clone(),
449                manifest: capability.clone(),
450                available: true,
451            }],
452            models: vec![
453                ModelEntry {
454                    model_id: "model-b".to_owned(),
455                    context_window: 8_000,
456                    supports_reasoning: false,
457                    supports_streaming: true,
458                },
459                ModelEntry {
460                    model_id: "model-a".to_owned(),
461                    context_window: 8_000,
462                    supports_reasoning: true,
463                    supports_streaming: true,
464                },
465            ],
466            providers: vec![ProviderEntry {
467                provider_id: "provider-a".to_owned(),
468                models_available: vec!["model-b".to_owned(), "model-a".to_owned()],
469                regions: vec!["CH".to_owned()],
470            }],
471        };
472        catalogue.models.reverse();
473
474        let candidates = ReferenceScheduler::new()
475            .generate_candidates(&envelope(), &[capability], &catalogue)
476            .expect("candidate generation");
477
478        assert_eq!(candidates.len(), 2);
479        assert_eq!(candidates[0].model, "model-a");
480        assert_eq!(candidates[1].model, "model-b");
481        assert!(candidates.len() <= MAX_CANDIDATES);
482    }
483
484    #[test]
485    fn filter_candidates_applies_provider_policy() {
486        let scheduler = ReferenceScheduler::new();
487        let task = envelope();
488        let allowed = manifest("capability://allowed", "provider-a");
489        let blocked = manifest("capability://blocked", "provider-b");
490        let candidates = scheduler
491            .generate_candidates(
492                &task,
493                &[allowed.clone(), blocked],
494                &TechnicalCatalogue::from_manifests([allowed]),
495            )
496            .expect("candidate generation");
497        let policy = PolicyConstraints {
498            allowed_providers: Some(vec!["provider-a".to_owned()]),
499            ..PolicyConstraints::default()
500        };
501
502        let filtered = scheduler.filter_candidates(candidates, &policy);
503
504        assert_eq!(filtered.len(), 1);
505        assert_eq!(filtered[0].provider, "provider-a");
506    }
507
508    #[test]
509    fn selection_is_deterministic_by_cost_then_latency() {
510        let scheduler = ReferenceScheduler::new();
511        let task = envelope();
512        let first_capability = CapabilityId::try_from("capability://first").expect("capability");
513        let second_capability = CapabilityId::try_from("capability://second").expect("capability");
514        let first_plan = plan_for(&task, &first_capability, "model-first", "provider", None)
515            .expect("first plan");
516        let second_plan = plan_for(&task, &second_capability, "model-second", "provider", None)
517            .expect("second plan");
518        let candidates = vec![
519            ExecutionCandidate::new(
520                first_plan,
521                "capability://first",
522                "model-first",
523                "provider",
524                Some(20),
525                Some(700),
526                Some(100),
527            ),
528            ExecutionCandidate::new(
529                second_plan,
530                "capability://second",
531                "model-second",
532                "provider",
533                Some(10),
534                Some(600),
535                Some(900),
536            ),
537        ];
538        let fallback = scheduler
539            .fallback_candidate(&task)
540            .expect("fallback candidate");
541
542        let decision = scheduler.select_plan(&candidates, &fallback);
543
544        assert_eq!(decision.selected.model, "model-second");
545        assert_eq!(decision.fallback, fallback.plan);
546        assert_eq!(decision.confidence_milli, 1000);
547    }
548}