返回 CodeWhale
validate.rs
根目录 / crates / engine / src / work_graph / validate.rs
1 //! Invariant validation — fail closed.
2 //!
3 //! [`validate`] checks every whole-snapshot invariant (V1–V8 below, plus
4 //! structural well-formedness). The reducer calls it on the candidate
5 //! snapshot after every change and rejects the change on any violation,
6 //! leaving the input snapshot untouched. There is no fail-open path: if a
7 //! node cannot be verified, it does not become Verified — verification
8 //! infrastructure trouble must surface as a rejection (callers then mark the
9 //! node Blocked), never as silently-assumed success.
10 //!
11 //! Invariants:
12 //! - V1 `DependsOn` edges are acyclic.
13 //! - V2 every live (`Initializing`/`Active`/`Waiting`) Operation reaches an
14 //! Objective/PlanStep via `Contains` ancestry — no orphaned live work.
15 //! - V3 `binding.is_some()` ⇒ `kind == Operation`.
16 //! - V4 `Verified` ⇒ acceptance non-empty ⇒ a `Verifies`-edge evidence path
17 //! satisfies every requirement. Completion is never verification.
18 //! - V5 `Blocked` ⇒ an incoming `Blocks` edge, an unmet `DependsOn`, or a
19 //! pending `RequiresApproval` path exists.
20 //! - V6 each binding's `external` matches exactly one identity scheme and no
21 //! two operations bind the same external identity.
22 //! - V7 `RuntimeRef`/`LaneRef` nodes never carry liveness state — the
23 //! owning subsystems are the only liveness source.
24 //! - V8 history is bounded and its revisions strictly increase.
25 //! - V9 terminal states are never overwritten except via explicit
26 //! `Supersede` (enforced in the reducer, which sees the predecessor
27 //! snapshot; single-snapshot validation cannot observe overwrites).
28 //! - V10 compat projections are pure functions of the snapshot — enforced at
29 //! the type level: projection functions take `&WorkGraphSnapshot` (see
30 //! `compat.rs`); nothing hands them mutable graph access.
31
32 use std::collections::{HashMap, HashSet};
33
34 use serde::{Deserialize, Serialize};
35
36 use super::ids::WorkNodeId;
37 use super::model::{
38 ACTIVITY_CAP, EdgeKind, HISTORY_CAP, NodeKind, NodeState, SCHEMA_VERSION, WorkActivityEvent,
39 WorkGraphSnapshot, WorkNode, external_identity_is_well_formed,
40 };
41
42 /// Which rule a violation belongs to.
43 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
44 #[serde(rename_all = "snake_case")]
45 pub enum ValidationCode {
46 /// Basic well-formedness (unique IDs, resolvable endpoints, schema).
47 Structural,
48 V1,
49 V2,
50 V3,
51 V4,
52 V5,
53 V6,
54 V7,
55 V8,
56 V9,
57 /// Never emitted at runtime: enforced by projection function signatures.
58 V10,
59 }
60
61 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62 pub struct Violation {
63 pub code: ValidationCode,
64 pub message: String,
65 }
66
67 /// Result of a failed validation. A change producing any violation is
68 /// rejected wholesale; the pre-change snapshot is returned to the caller
69 /// untouched.
70 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
71 pub struct ValidationReport {
72 pub violations: Vec<Violation>,
73 }
74
75 impl ValidationReport {
76 #[must_use]
77 pub fn single(code: ValidationCode, message: impl Into<String>) -> Self {
78 ValidationReport {
79 violations: vec![Violation {
80 code,
81 message: message.into(),
82 }],
83 }
84 }
85
86 #[must_use]
87 pub fn contains_code(&self, code: ValidationCode) -> bool {
88 self.violations.iter().any(|v| v.code == code)
89 }
90 }
91
92 impl std::fmt::Display for ValidationReport {
93 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94 write!(f, "work graph validation failed:")?;
95 for v in &self.violations {
96 write!(f, " [{:?}] {};", v.code, v.message)?;
97 }
98 Ok(())
99 }
100 }
101
102 impl std::error::Error for ValidationReport {}
103
104 /// Validate a whole snapshot. `Ok(())` or every violation found.
105 pub fn validate(snapshot: &WorkGraphSnapshot) -> Result<(), ValidationReport> {
106 let mut violations = Vec::new();
107
108 check_structural(snapshot, &mut violations);
109 check_v1_depends_on_acyclic(snapshot, &mut violations);
110 check_v2_live_operations_rooted(snapshot, &mut violations);
111 check_v3_binding_only_on_operations(snapshot, &mut violations);
112 check_v4_verified_requires_evidence(snapshot, &mut violations);
113 check_v5_blocked_has_cause(snapshot, &mut violations);
114 check_v6_binding_identity(snapshot, &mut violations);
115 check_v7_refs_inert(snapshot, &mut violations);
116 check_v8_history_bounded_monotonic(snapshot, &mut violations);
117
118 if violations.is_empty() {
119 Ok(())
120 } else {
121 Err(ValidationReport { violations })
122 }
123 }
124
125 fn check_structural(snapshot: &WorkGraphSnapshot, out: &mut Vec<Violation>) {
126 if snapshot.schema != SCHEMA_VERSION {
127 out.push(Violation {
128 code: ValidationCode::Structural,
129 message: format!("unknown schema {}", snapshot.schema),
130 });
131 }
132 let mut node_ids = HashSet::new();
133 for node in &snapshot.nodes {
134 if !node_ids.insert(&node.id) {
135 out.push(Violation {
136 code: ValidationCode::Structural,
137 message: format!("duplicate node id {}", node.id),
138 });
139 }
140 if node.evidence.is_some() && !matches!(node.kind, NodeKind::Evidence) {
141 out.push(Violation {
142 code: ValidationCode::Structural,
143 message: format!(
144 "node {} carries evidence but is not an Evidence node",
145 node.id
146 ),
147 });
148 }
149 }
150 let mut edge_ids = HashSet::new();
151 for edge in &snapshot.edges {
152 if !edge_ids.insert(&edge.id) {
153 out.push(Violation {
154 code: ValidationCode::Structural,
155 message: format!("duplicate edge id {}", edge.id),
156 });
157 }
158 for endpoint in [&edge.from, &edge.to] {
159 if !node_ids.contains(endpoint) {
160 out.push(Violation {
161 code: ValidationCode::Structural,
162 message: format!("edge {} references missing node {}", edge.id, endpoint),
163 });
164 }
165 }
166 }
167
168 let mut plan_ids = HashSet::new();
169 for id in &snapshot.compat.plan_order {
170 if !plan_ids.insert(id) {
171 out.push(Violation {
172 code: ValidationCode::Structural,
173 message: format!("duplicate plan projection node {id}"),
174 });
175 }
176 match snapshot.node(id) {
177 Some(node) if matches!(node.kind, NodeKind::PlanStep) => {}
178 Some(_) => out.push(Violation {
179 code: ValidationCode::Structural,
180 message: format!("plan projection node {id} is not a PlanStep"),
181 }),
182 None => out.push(Violation {
183 code: ValidationCode::Structural,
184 message: format!("plan projection references missing node {id}"),
185 }),
186 }
187 }
188
189 let mut todo_ids = HashSet::new();
190 let mut active_todos = 0usize;
191 for binding in &snapshot.compat.todos {
192 if binding.legacy_id == 0 || !todo_ids.insert(binding.legacy_id) {
193 out.push(Violation {
194 code: ValidationCode::Structural,
195 message: format!("invalid or duplicate legacy To-do id {}", binding.legacy_id),
196 });
197 }
198 match snapshot.node(&binding.node) {
199 Some(node) => {
200 if node.kind != NodeKind::PlanStep {
201 out.push(Violation {
202 code: ValidationCode::Structural,
203 message: format!(
204 "To-do projection {} node {} is not a PlanStep",
205 binding.legacy_id, binding.node
206 ),
207 });
208 }
209 if matches!(node.state, NodeState::Active) {
210 active_todos += 1;
211 }
212 }
213 None => out.push(Violation {
214 code: ValidationCode::Structural,
215 message: format!(
216 "To-do projection {} references missing node {}",
217 binding.legacy_id, binding.node
218 ),
219 }),
220 }
221 if let Some(index) = binding.plan_index {
222 let aliased = usize::try_from(index)
223 .ok()
224 .and_then(|index| snapshot.compat.plan_order.get(index));
225 if aliased != Some(&binding.node) {
226 out.push(Violation {
227 code: ValidationCode::Structural,
228 message: format!(
229 "To-do projection {} has an invalid plan alias",
230 binding.legacy_id
231 ),
232 });
233 }
234 }
235 }
236 if active_todos > 1 {
237 out.push(Violation {
238 code: ValidationCode::Structural,
239 message: "legacy To-do projection has more than one active row".to_string(),
240 });
241 }
242
243 if snapshot.activities.len() > ACTIVITY_CAP {
244 out.push(Violation {
245 code: ValidationCode::Structural,
246 message: format!(
247 "activity length {} exceeds bound {ACTIVITY_CAP}",
248 snapshot.activities.len()
249 ),
250 });
251 }
252 for activity in snapshot.activities.iter() {
253 let (requested, effective, provider_kind, provider, endpoint_identity, model, operation) =
254 match activity {
255 WorkActivityEvent::ReasoningEffortChanged {
256 requested,
257 effective,
258 provider_kind,
259 provider,
260 endpoint_identity,
261 model,
262 operation,
263 ..
264 } => (
265 requested,
266 effective,
267 provider_kind,
268 provider,
269 endpoint_identity,
270 model,
271 operation,
272 ),
273 };
274 if matches!(
275 requested,
276 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::ThinkingEnabledGranularityUnavailable
277 | codewhale_models::reasoning_effort_tier::ReasoningEffortTier::Unavailable
278 ) {
279 out.push(Violation {
280 code: ValidationCode::Structural,
281 message: "requested reasoning effort is not an operator-selectable tier"
282 .to_string(),
283 });
284 }
285 if provider.is_empty()
286 || provider.chars().count() > 128
287 || provider
288 .chars()
289 .any(|ch| ch.is_whitespace() || ch.is_control())
290 {
291 out.push(Violation {
292 code: ValidationCode::Structural,
293 message: "activity provider is not a bounded route identity".to_string(),
294 });
295 }
296 let provenance_is_bounded = provider_kind.is_some()
297 && endpoint_identity.as_ref().is_some_and(|endpoint| {
298 !endpoint.is_empty()
299 && endpoint.chars().count() <= 512
300 && !endpoint.chars().any(char::is_control)
301 })
302 && model.as_ref().is_some_and(|model| {
303 !model.trim().is_empty()
304 && model.chars().count() <= 256
305 && !model.chars().any(char::is_control)
306 });
307 if !provenance_is_bounded {
308 if *effective
309 != codewhale_models::reasoning_effort_tier::ReasoningEffortTier::Unavailable
310 {
311 out.push(Violation {
312 code: ValidationCode::Structural,
313 message:
314 "activity without bounded route provenance must be effective unavailable"
315 .to_string(),
316 });
317 }
318 } else {
319 let api_provider = provider_kind.expect("provenance bounded above");
320 if api_provider != codewhale_config::ProviderKind::Custom
321 && provider != api_provider.as_str()
322 {
323 out.push(Violation {
324 code: ValidationCode::Structural,
325 message: "activity provider identity does not match its recorded kind"
326 .to_string(),
327 });
328 continue;
329 }
330 let constrained = match api_provider {
331 codewhale_config::ProviderKind::Custom => {
332 Some(codewhale_models::reasoning_effort_tier::ReasoningEffortTier::Unavailable)
333 }
334 api_provider => super::model::constrained_effective_reasoning_for_route(
335 *requested,
336 api_provider,
337 endpoint_identity.as_deref().expect("bounded above"),
338 model.as_deref().expect("bounded above"),
339 ),
340 };
341 if constrained.is_some_and(|expected| *effective != expected) {
342 out.push(Violation {
343 code: ValidationCode::Structural,
344 message: "activity effective reasoning is impossible for its recorded route"
345 .to_string(),
346 });
347 } else if constrained.is_none()
348 && matches!(
349 effective,
350 codewhale_models::reasoning_effort_tier::ReasoningEffortTier::ThinkingEnabledGranularityUnavailable
351 )
352 {
353 out.push(Violation {
354 code: ValidationCode::Structural,
355 message: "granularity-unavailable receipt is not valid for this recorded route"
356 .to_string(),
357 });
358 }
359 }
360 if let Some(operation) = operation {
361 match snapshot.node(operation) {
362 Some(node) if node.kind == NodeKind::Operation => {}
363 Some(_) => out.push(Violation {
364 code: ValidationCode::Structural,
365 message: format!("activity operation {operation} is not an Operation node"),
366 }),
367 None => out.push(Violation {
368 code: ValidationCode::Structural,
369 message: format!("activity references missing operation {operation}"),
370 }),
371 }
372 }
373 }
374 }
375
376 /// V1: DFS three-color cycle detection over `DependsOn` edges.
377 fn check_v1_depends_on_acyclic(snapshot: &WorkGraphSnapshot, out: &mut Vec<Violation>) {
378 let mut adjacency: HashMap<&WorkNodeId, Vec<&WorkNodeId>> = HashMap::new();
379 for edge in &snapshot.edges {
380 if matches!(edge.kind, EdgeKind::DependsOn) {
381 adjacency.entry(&edge.from).or_default().push(&edge.to);
382 }
383 }
384 let mut done: HashSet<&WorkNodeId> = HashSet::new();
385 let mut in_progress: HashSet<&WorkNodeId> = HashSet::new();
386
387 fn visit<'a>(
388 node: &'a WorkNodeId,
389 adjacency: &HashMap<&'a WorkNodeId, Vec<&'a WorkNodeId>>,
390 done: &mut HashSet<&'a WorkNodeId>,
391 in_progress: &mut HashSet<&'a WorkNodeId>,
392 ) -> bool {
393 if done.contains(node) {
394 return true;
395 }
396 if !in_progress.insert(node) {
397 return false; // back edge → cycle
398 }
399 let acyclic = adjacency
400 .get(node)
401 .map(|next| next.iter().all(|n| visit(n, adjacency, done, in_progress)))
402 .unwrap_or(true);
403 in_progress.remove(node);
404 done.insert(node);
405 acyclic
406 }
407
408 for node in &snapshot.nodes {
409 if !visit(&node.id, &adjacency, &mut done, &mut in_progress) {
410 out.push(Violation {
411 code: ValidationCode::V1,
412 message: format!("depends_on cycle reachable from node {}", node.id),
413 });
414 return; // one report is enough; graph is already invalid
415 }
416 }
417 }
418
419 /// V2: every live Operation climbs `Contains` ancestry to an
420 /// Objective/PlanStep. `Contains` points parent → child, so we walk incoming
421 /// edges upward with a visited set (defensive against malformed cycles).
422 fn check_v2_live_operations_rooted(snapshot: &WorkGraphSnapshot, out: &mut Vec<Violation>) {
423 for node in &snapshot.nodes {
424 if !(matches!(node.kind, NodeKind::Operation) && node.state.is_live()) {
425 continue;
426 }
427 let mut visited: HashSet<&WorkNodeId> = HashSet::new();
428 let mut frontier: Vec<&WorkNodeId> = vec![&node.id];
429 let mut rooted = false;
430 while let Some(current) = frontier.pop() {
431 if !visited.insert(current) {
432 continue;
433 }
434 for edge in &snapshot.edges {
435 if matches!(edge.kind, EdgeKind::Contains)
436 && &edge.to == current
437 && let Some(parent) = snapshot.node(&edge.from)
438 {
439 if matches!(parent.kind, NodeKind::Objective | NodeKind::PlanStep) {
440 rooted = true;
441 }
442 frontier.push(&parent.id);
443 }
444 }
445 if rooted {
446 break;
447 }
448 }
449 if !rooted {
450 out.push(Violation {
451 code: ValidationCode::V2,
452 message: format!(
453 "live operation {} has no Objective/PlanStep ancestry",
454 node.id
455 ),
456 });
457 }
458 }
459 }
460
461 fn check_v3_binding_only_on_operations(snapshot: &WorkGraphSnapshot, out: &mut Vec<Violation>) {
462 for node in &snapshot.nodes {
463 if node.binding.is_some() && !matches!(node.kind, NodeKind::Operation) {
464 out.push(Violation {
465 code: ValidationCode::V3,
466 message: format!("non-operation node {} carries a binding", node.id),
467 });
468 }
469 }
470 }
471
472 /// V4: `Verified` demands non-empty acceptance and, for every requirement, at
473 /// least one Evidence node linked by a `Verifies` edge whose payload
474 /// satisfies it. There is no fail-open branch: absence of satisfying
475 /// evidence — for any reason, including verification infrastructure being
476 /// unavailable — is a rejection.
477 fn check_v4_verified_requires_evidence(snapshot: &WorkGraphSnapshot, out: &mut Vec<Violation>) {
478 for node in &snapshot.nodes {
479 if !matches!(node.state, NodeState::Verified) {
480 continue;
481 }
482 if node.acceptance.is_empty() {
483 out.push(Violation {
484 code: ValidationCode::V4,
485 message: format!("verified node {} has no acceptance requirements", node.id),
486 });
487 continue;
488 }
489 let evidence: Vec<&WorkNode> = snapshot
490 .edges
491 .iter()
492 .filter(|e| matches!(e.kind, EdgeKind::Verifies) && e.to == node.id)
493 .filter_map(|e| snapshot.node(&e.from))
494 .filter(|n| matches!(n.kind, NodeKind::Evidence))
495 .collect();
496 for requirement in &node.acceptance {
497 let satisfied = evidence.iter().any(|ev| {
498 ev.evidence
499 .as_ref()
500 .is_some_and(|payload| requirement.is_satisfied_by(payload))
501 });
502 if !satisfied {
503 out.push(Violation {
504 code: ValidationCode::V4,
505 message: format!(
506 "verified node {} lacks satisfying evidence for {:?}",
507 node.id, requirement
508 ),
509 });
510 }
511 }
512 }
513 }
514
515 /// V5: `Blocked` must have a visible cause.
516 fn check_v5_blocked_has_cause(snapshot: &WorkGraphSnapshot, out: &mut Vec<Violation>) {
517 for node in &snapshot.nodes {
518 if !matches!(node.state, NodeState::Blocked) {
519 continue;
520 }
521 let blocked_by_edge = snapshot
522 .edges
523 .iter()
524 .any(|e| matches!(e.kind, EdgeKind::Blocks) && e.to == node.id);
525 let unmet_dependency = snapshot.edges.iter().any(|e| {
526 matches!(e.kind, EdgeKind::DependsOn)
527 && e.from == node.id
528 && snapshot
529 .node(&e.to)
530 .is_some_and(|dep| !WorkGraphSnapshot::node_is_done(dep))
531 });
532 let pending_approval = snapshot.edges.iter().any(|e| {
533 matches!(e.kind, EdgeKind::RequiresApproval)
534 && e.from == node.id
535 && snapshot
536 .node(&e.to)
537 .is_some_and(|approval| !WorkGraphSnapshot::node_is_done(approval))
538 });
539 if !(blocked_by_edge || unmet_dependency || pending_approval) {
540 out.push(Violation {
541 code: ValidationCode::V5,
542 message: format!("blocked node {} has no blocking cause", node.id),
543 });
544 }
545 }
546 }
547
548 /// V6: binding externals are well-formed under exactly one scheme prefix and
549 /// unique across operations. (Cross-checking against the owners' live
550 /// registries is the liveness slice's job; within the snapshot this is the
551 /// enforceable core.)
552 fn check_v6_binding_identity(snapshot: &WorkGraphSnapshot, out: &mut Vec<Violation>) {
553 let mut seen: HashMap<&str, &WorkNodeId> = HashMap::new();
554 for node in &snapshot.nodes {
555 let Some(binding) = &node.binding else {
556 continue;
557 };
558 if !external_identity_is_well_formed(&binding.external) {
559 out.push(Violation {
560 code: ValidationCode::V6,
561 message: format!(
562 "node {} binding external {:?} matches no identity scheme",
563 node.id, binding.external
564 ),
565 });
566 }
567 if let Some(previous) = seen.insert(binding.external.as_str(), &node.id) {
568 out.push(Violation {
569 code: ValidationCode::V6,
570 message: format!(
571 "external {:?} bound by both {} and {}",
572 binding.external, previous, node.id
573 ),
574 });
575 }
576 }
577 }
578
579 /// V7: reference nodes are inert — they never carry liveness state, because
580 /// the owning subsystems are the only source of liveness truth.
581 fn check_v7_refs_inert(snapshot: &WorkGraphSnapshot, out: &mut Vec<Violation>) {
582 for node in &snapshot.nodes {
583 if matches!(node.kind, NodeKind::RuntimeRef | NodeKind::LaneRef)
584 && !matches!(node.state, NodeState::Ready)
585 {
586 out.push(Violation {
587 code: ValidationCode::V7,
588 message: format!(
589 "reference node {} carries liveness state {:?}",
590 node.id, node.state
591 ),
592 });
593 }
594 }
595 }
596
597 /// V8: bounded history with strictly increasing revisions. (The exactly-once
598 /// revision increment itself is a reducer property, covered by tests.)
599 fn check_v8_history_bounded_monotonic(snapshot: &WorkGraphSnapshot, out: &mut Vec<Violation>) {
600 if snapshot.history.len() > HISTORY_CAP {
601 out.push(Violation {
602 code: ValidationCode::V8,
603 message: format!(
604 "history length {} exceeds bound {HISTORY_CAP}",
605 snapshot.history.len()
606 ),
607 });
608 }
609 let mut previous: Option<u64> = None;
610 for receipt in snapshot.history.iter() {
611 if let Some(prev) = previous
612 && receipt.revision <= prev
613 {
614 out.push(Violation {
615 code: ValidationCode::V8,
616 message: format!(
617 "history revisions not strictly increasing ({} then {})",
618 prev, receipt.revision
619 ),
620 });
621 break;
622 }
623 previous = Some(receipt.revision);
624 }
625 if let Some(last) = snapshot.history.last() {
626 // During apply, validation runs before the increment, so the newest
627 // receipt may equal the current revision but never exceed it by >1.
628 if last.revision > snapshot.revision.saturating_add(1) {
629 out.push(Violation {
630 code: ValidationCode::V8,
631 message: format!(
632 "history revision {} ahead of snapshot revision {}",
633 last.revision, snapshot.revision
634 ),
635 });
636 }
637 }
638 }
639
639 lines RUST