Skip to main content

lean_ctx/core/ocla/
reference_scheduler.rs

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