返回 CodeWhale
placement.rs
根目录 / crates / engine / src / fleet / placement.rs
1 use std::collections::BTreeSet;
2
3 use anyhow::{Result, ensure};
4 use codewhale_protocol::fleet::{FleetHostSpec, FleetTaskSpec, FleetWorkerSpec};
5 use codewhale_protocol::placement::{
6 EnvironmentKind, EnvironmentResources, ExecutionEnvironment, PlacementCandidate,
7 PlacementDecision, PlacementRefusal, PlacementRefusalCode, PlacementRequirements,
8 };
9
10 pub fn environment(worker: &FleetWorkerSpec) -> ExecutionEnvironment {
11 worker
12 .environment
13 .clone()
14 .unwrap_or_else(|| ExecutionEnvironment {
15 id: match &worker.host {
16 FleetHostSpec::Local => "local".to_string(),
17 FleetHostSpec::Ssh { host, .. } => format!("ssh:{host}"),
18 FleetHostSpec::Tailscale { node_id, .. } => format!("tailscale:{node_id}"),
19 FleetHostSpec::Docker { image, .. } => format!("docker:{image}"),
20 },
21 kind: match worker.host {
22 FleetHostSpec::Local | FleetHostSpec::Docker { .. } => EnvironmentKind::Local,
23 _ => EnvironmentKind::Remote,
24 },
25 resources: EnvironmentResources::default(),
26 capabilities: worker.capabilities.clone(),
27 data: Vec::new(),
28 persistent: None,
29 cost_per_hour_microusd: None,
30 })
31 }
32
33 pub fn requirements(task: &FleetTaskSpec) -> PlacementRequirements {
34 task.workspace
35 .as_ref()
36 .and_then(|workspace| workspace.placement.clone())
37 .unwrap_or_default()
38 }
39
40 pub fn validate(task: &FleetTaskSpec) -> Result<()> {
41 let requirements = requirements(task);
42 validate_tokens(&requirements.environments)?;
43 validate_tokens(&requirements.capabilities)?;
44 validate_tokens(&requirements.data)?;
45 validate_tokens(&requirements.prefer)?;
46 ensure!(requirements.kinds.len() <= 3, "too many environment kinds");
47 Ok(())
48 }
49
50 pub fn validate_worker(worker: &FleetWorkerSpec) -> Result<()> {
51 let environment = environment(worker);
52 validate_tokens(std::slice::from_ref(&environment.id))?;
53 validate_tokens(&environment.capabilities)?;
54 validate_tokens(&environment.data)?;
55 Ok(())
56 }
57
58 fn validate_tokens(values: &[String]) -> Result<()> {
59 ensure!(
60 values.len() <= 64,
61 "environment lists cannot exceed 64 entries"
62 );
63 for value in values {
64 ensure!(
65 !value.is_empty()
66 && value.trim() == value
67 && value.len() <= 256
68 && value.chars().all(|c| !c.is_control()),
69 "environment identifiers must contain 1 to 256 printable characters"
70 );
71 }
72 Ok(())
73 }
74
75 pub fn decide(
76 task: &FleetTaskSpec,
77 workers: &[FleetWorkerSpec],
78 unavailable: &BTreeSet<String>,
79 ) -> PlacementDecision {
80 let required = requirements(task);
81 let mut candidates: Vec<_> = workers
82 .iter()
83 .map(|worker| {
84 let environment = environment(worker);
85 let mut refusals = Vec::new();
86 let mut refuse = |code, detail| refusals.push(PlacementRefusal { code, detail });
87 if unavailable.contains(&worker.id) {
88 refuse(
89 PlacementRefusalCode::WorkerBusy,
90 "Worker is already occupied or unavailable".to_string(),
91 );
92 }
93 if matches!(worker.host, FleetHostSpec::Docker { .. }) {
94 refuse(
95 PlacementRefusalCode::UnsupportedHost,
96 "Container execution is not available".to_string(),
97 );
98 }
99 if !required.environments.is_empty() && !required.environments.contains(&environment.id)
100 {
101 refuse(
102 PlacementRefusalCode::EnvironmentNotAllowed,
103 "Environment is outside the task's allowed set".to_string(),
104 );
105 }
106 if !required.kinds.is_empty() && !required.kinds.contains(&environment.kind) {
107 refuse(
108 PlacementRefusalCode::KindNotAllowed,
109 "Environment kind does not match the task".to_string(),
110 );
111 }
112 for capability in &required.capabilities {
113 if !environment.capabilities.contains(capability) {
114 refuse(PlacementRefusalCode::MissingCapability, capability.clone());
115 }
116 }
117 for data in &required.data {
118 if !environment.data.contains(data) {
119 refuse(PlacementRefusalCode::MissingData, data.clone());
120 }
121 }
122 for (name, minimum, available) in [
123 (
124 "cpu_cores",
125 required.resources.cpu_cores.map(u64::from),
126 environment.resources.cpu_cores.map(u64::from),
127 ),
128 (
129 "memory_mib",
130 required.resources.memory_mib,
131 environment.resources.memory_mib,
132 ),
133 (
134 "gpus",
135 required.resources.gpus.map(u64::from),
136 environment.resources.gpus.map(u64::from),
137 ),
138 ] {
139 if let Some(minimum) = minimum
140 && available.is_none_or(|available| available < minimum)
141 {
142 refuse(
143 PlacementRefusalCode::InsufficientResources,
144 format!(
145 "{name}: requires {minimum}, declared {}",
146 available
147 .map(|value| value.to_string())
148 .unwrap_or_else(|| "unknown".to_string())
149 ),
150 );
151 }
152 }
153 if required
154 .persistent
155 .is_some_and(|persistent| Some(persistent) != environment.persistent)
156 {
157 refuse(
158 PlacementRefusalCode::PersistenceMismatch,
159 "Environment persistence does not match the task".to_string(),
160 );
161 }
162 if let Some(limit) = required.max_cost_per_hour_microusd {
163 match environment.cost_per_hour_microusd {
164 None => refuse(
165 PlacementRefusalCode::CostUnknown,
166 "No declared compute rate".to_string(),
167 ),
168 Some(cost) if cost > limit => refuse(
169 PlacementRefusalCode::CostLimit,
170 format!("Declared compute rate {cost} exceeds {limit} micro-USD/hour"),
171 ),
172 _ => {}
173 }
174 }
175 PlacementCandidate {
176 worker_id: worker.id.clone(),
177 environment,
178 eligible: refusals.is_empty(),
179 refusals,
180 }
181 })
182 .collect();
183 candidates.sort_by_key(|candidate| {
184 (
185 !candidate.eligible,
186 required
187 .prefer
188 .iter()
189 .position(|id| id == &candidate.environment.id)
190 .unwrap_or(usize::MAX),
191 )
192 });
193 let selected = candidates.iter().find(|candidate| candidate.eligible);
194 PlacementDecision {
195 task_id: task.id.clone(),
196 worker_id: selected.map(|candidate| candidate.worker_id.clone()),
197 environment_id: selected.map(|candidate| candidate.environment.id.clone()),
198 reason: match selected {
199 Some(candidate) if required.prefer.contains(&candidate.environment.id) => {
200 "Highest preferred available environment satisfying every declared requirement"
201 .to_string()
202 }
203 Some(_) => {
204 "First available environment satisfying every declared requirement".to_string()
205 }
206 None => "No available environment satisfies every declared requirement".to_string(),
207 },
208 candidates,
209 }
210 }
211
212 pub fn require_match(task: &FleetTaskSpec, worker: &FleetWorkerSpec) -> Result<PlacementDecision> {
213 let decision = decide(task, std::slice::from_ref(worker), &BTreeSet::new());
214 ensure!(
215 decision.worker_id.is_some(),
216 "Task {} cannot run on worker {}: {}",
217 task.id,
218 worker.id,
219 serde_json::to_string(&decision.candidates[0].refusals)?
220 );
221 Ok(decision)
222 }
223
224 pub fn write_receipt(
225 workspace: &std::path::Path,
226 run_id: &codewhale_protocol::fleet::FleetRunId,
227 attempt: u32,
228 decision: &PlacementDecision,
229 ) -> Result<codewhale_protocol::fleet::FleetArtifactRef> {
230 use codewhale_protocol::fleet::FleetArtifactKind;
231 let bytes = serde_json::to_vec_pretty(&serde_json::json!({
232 "kind": "environment_placement",
233 "run_id": run_id,
234 "attempt": attempt,
235 "evidence": "operator_declared",
236 "execution_authority": "existing_runtime_policy",
237 "decision": decision,
238 }))?;
239 let checksum = codewhale_runtime::hashing::sha256_hex(&bytes);
240 super::task_spec::write_fleet_artifact_ref(
241 workspace,
242 run_id,
243 &decision.task_id,
244 decision.worker_id.as_deref().unwrap_or("unplaced"),
245 FleetArtifactKind::Receipt,
246 &format!("placement-{attempt}-{checksum}.json"),
247 &bytes,
248 Some("application/json"),
249 )
250 }
251
251 lines RUST