vyre-foundation 0.7.2

Foundation layer: IR, type system, memory model, wire format. Zero application semantics. Part of the vyre GPU compiler.
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
//! Structured validation issues for vyre IR programs.

use core::fmt;
use std::borrow::Cow;
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use crate::diagnostics::{
    Diagnostic, DiagnosticCode, DiagnosticStage, OpLocation, RetryClass, Severity,
};

/// Stable validation rule identity.
///
/// Codes are explicit at every emission site. New validator rules use a new
/// identity rather than encoding ownership in prose.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize)]
#[serde(transparent)]
pub struct ValidationCode(Cow<'static, str>);

impl<'de> Deserialize<'de> for ValidationCode {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let code = String::deserialize(deserializer)?;
        let validation_code = Self(Cow::Owned(code));
        if validation_code.phase().is_none() {
            return Err(serde::de::Error::custom(format!(
                "unknown validation code `{validation_code}`"
            )));
        }
        Ok(validation_code)
    }
}

const VALIDATION_RULES: &[(&str, ValidationPhase)] = &[
    ("V008", ValidationPhase::Node),
    ("V009", ValidationPhase::Memory),
    ("V010", ValidationPhase::Memory),
    ("V011", ValidationPhase::Node),
    ("V012", ValidationPhase::Expression),
    ("V013", ValidationPhase::Memory),
    ("V014", ValidationPhase::Memory),
    ("V016", ValidationPhase::Expression),
    ("V018", ValidationPhase::Limits),
    ("V019", ValidationPhase::Limits),
    ("V020", ValidationPhase::Expression),
    ("V021", ValidationPhase::Expression),
    ("V022", ValidationPhase::Expression),
    ("V023", ValidationPhase::Expression),
    ("V025", ValidationPhase::Memory),
    ("V027", ValidationPhase::Memory),
    ("V028", ValidationPhase::Type),
    ("V029", ValidationPhase::Expression),
    ("V030", ValidationPhase::Expression),
    ("V031", ValidationPhase::Node),
    ("V032", ValidationPhase::Node),
    ("V033", ValidationPhase::Limits),
    ("V034", ValidationPhase::Expression),
    ("V035", ValidationPhase::Type),
    ("V036", ValidationPhase::Node),
    ("V041", ValidationPhase::Expression),
    ("V042", ValidationPhase::Memory),
    ("V043", ValidationPhase::Memory),
    ("V044", ValidationPhase::Type),
    ("V045", ValidationPhase::Node),
    ("V046", ValidationPhase::Node),
    ("V047", ValidationPhase::Expression),
    ("V051", ValidationPhase::Expression),
    ("V052", ValidationPhase::Expression),
    ("V053", ValidationPhase::Expression),
    ("V054", ValidationPhase::Expression),
    ("V055", ValidationPhase::Memory),
    ("V056", ValidationPhase::Capability),
    ("V057", ValidationPhase::Memory),
    ("V058", ValidationPhase::Memory),
    ("V059", ValidationPhase::Memory),
    ("V060", ValidationPhase::Memory),
    ("V061", ValidationPhase::Memory),
    ("V063", ValidationPhase::Memory),
    ("V064", ValidationPhase::Memory),
    ("V065", ValidationPhase::Memory),
    ("V066", ValidationPhase::Expression),
    ("V067", ValidationPhase::Expression),
    ("V068", ValidationPhase::Expression),
    ("V070", ValidationPhase::Program),
    ("V083", ValidationPhase::Program),
    ("V084", ValidationPhase::Type),
    ("V085", ValidationPhase::Type),
    ("V086", ValidationPhase::Type),
    ("V087", ValidationPhase::Type),
    ("V088", ValidationPhase::Type),
    ("V089", ValidationPhase::Type),
    ("V090", ValidationPhase::Type),
    ("V091", ValidationPhase::Type),
    ("V092", ValidationPhase::Type),
    ("V093", ValidationPhase::Type),
    ("V094", ValidationPhase::Type),
    ("V095", ValidationPhase::Type),
    ("V096", ValidationPhase::Type),
    ("V097", ValidationPhase::Type),
    ("V098", ValidationPhase::Type),
    ("V099", ValidationPhase::Type),
    ("V100", ValidationPhase::Type),
    ("V101", ValidationPhase::Type),
    ("V102", ValidationPhase::Type),
    ("V103", ValidationPhase::Type),
    ("V104", ValidationPhase::Type),
    ("V105", ValidationPhase::Program),
    ("V106", ValidationPhase::Program),
    ("V107", ValidationPhase::Program),
    ("V108", ValidationPhase::Program),
    ("V109", ValidationPhase::Program),
    ("V110", ValidationPhase::Program),
    ("V111", ValidationPhase::Node),
    ("V112", ValidationPhase::Node),
    ("V113", ValidationPhase::Node),
    ("V114", ValidationPhase::Node),
    ("V115", ValidationPhase::Composition),
    ("V116", ValidationPhase::Composition),
    ("V117", ValidationPhase::Node),
    ("V118", ValidationPhase::Node),
    ("V119", ValidationPhase::Node),
    ("V120", ValidationPhase::Node),
    ("V121", ValidationPhase::Node),
    ("V122", ValidationPhase::Node),
    ("V123", ValidationPhase::Node),
    ("V124", ValidationPhase::Node),
    ("V125", ValidationPhase::Node),
    ("V126", ValidationPhase::Node),
    ("V127", ValidationPhase::Node),
    ("V128", ValidationPhase::Node),
    ("V129", ValidationPhase::Memory),
    ("V130", ValidationPhase::Program),
];

impl ValidationCode {
    /// Backend capability rejected an operation used by the program.
    pub const V056: Self = Self(Cow::Borrowed("V056"));

    /// Construct a stable rule identity.
    #[must_use]
    pub(crate) const fn new(code: &'static str) -> Self {
        Self(Cow::Borrowed(code))
    }

    /// Return the stable code spelling.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Iterate every registered validation rule and its sole owning phase.
    ///
    /// The registry is the source for diagnostics tooling and documentation
    /// coverage. New rules must be added here before they can deserialize.
    pub fn registered() -> impl ExactSizeIterator<Item = (&'static str, ValidationPhase)> + Clone {
        VALIDATION_RULES.iter().copied()
    }

    /// Return the sole validator phase allowed to emit this rule.
    #[must_use]
    pub fn phase(&self) -> Option<ValidationPhase> {
        VALIDATION_RULES
            .iter()
            .find_map(|(code, phase)| (*code == self.as_str()).then_some(*phase))
    }
}

impl fmt::Display for ValidationCode {
    fn fmt(&self, output: &mut fmt::Formatter<'_>) -> fmt::Result {
        output.write_str(&self.0)
    }
}

/// Validator phase that owns a rule emission.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ValidationPhase {
    /// Program header, workgroup, and buffer declarations.
    Program,
    /// Node structure, scope, and control flow.
    Node,
    /// Expression structure and call validation.
    Expression,
    /// Static type rules.
    Type,
    /// Memory access and ordering rules.
    Memory,
    /// Backend capability-sensitive validation.
    Capability,
    /// Whole-program composition and fusion rules.
    Composition,
    /// Resource and recursion bounds.
    Limits,
}

impl ValidationPhase {
    /// Stable phase spelling used by structured causes and traces.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Program => "program",
            Self::Node => "node",
            Self::Expression => "expression",
            Self::Type => "type",
            Self::Memory => "memory",
            Self::Capability => "capability",
            Self::Composition => "composition",
            Self::Limits => "limits",
        }
    }
}

/// Typed location within the validated program.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ValidationLocation {
    /// The complete program.
    Program,
    /// One workgroup axis.
    WorkgroupAxis(u8),
    /// One declared buffer.
    Buffer(Cow<'static, str>),
    /// One node in pre-order traversal.
    Node(u32),
    /// One expression owned by a node.
    Expression {
        /// Pre-order node identity.
        node: u32,
        /// Expression depth below the node.
        depth: u32,
    },
    /// One operand of an expression or call.
    Operand {
        /// Pre-order node identity.
        node: u32,
        /// Zero-based operand index.
        operand: u32,
    },
    /// One issue within a deterministic validator traversal.
    Traversal {
        /// Zero-based node or issue order within the owning validation phase.
        ordinal: u64,
    },
    /// One registered semantic operation.
    Operation(Cow<'static, str>),
}

impl ValidationLocation {
    pub(crate) fn diagnostic_location(&self) -> OpLocation {
        match self {
            Self::Program => OpLocation::op("program"),
            Self::WorkgroupAxis(axis) => {
                OpLocation::op("program.workgroup_size").with_operand(u32::from(*axis))
            }
            Self::Buffer(name) => OpLocation::op("program.buffer").with_attr(name.clone()),
            Self::Node(node) => OpLocation::op("program.node").with_graph_node(*node),
            Self::Expression { node, depth } => OpLocation::op("program.expression")
                .with_graph_node(*node)
                .with_operand(*depth),
            Self::Operand { node, operand } => OpLocation::op("program.expression")
                .with_graph_node(*node)
                .with_operand(*operand),
            Self::Traversal { ordinal } => OpLocation::op("program.validation")
                .with_graph_node(u32::try_from(*ordinal).unwrap_or(u32::MAX)),
            Self::Operation(op_id) => OpLocation::op(op_id.clone()),
        }
    }
}

/// One trace record produced at the shared validation issue choke point.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ValidationTraceEvent {
    /// Emitted rule identity.
    pub code: ValidationCode,
    /// Rule-owning validator phase.
    pub phase: ValidationPhase,
    /// Typed program location.
    pub location: ValidationLocation,
}

/// A structured validation issue.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ValidationError {
    /// Stable validation rule identity.
    code: ValidationCode,
    /// Rule-owning validator phase.
    phase: ValidationPhase,
    /// Typed program location.
    location: ValidationLocation,
    /// Deterministic cause detail without a code or corrective-action prefix.
    cause: Cow<'static, str>,
    /// Corrective action.
    corrective_action: Cow<'static, str>,
    /// Retry policy.
    retry: RetryClass,
}

#[derive(Deserialize)]
struct ValidationErrorWire {
    code: ValidationCode,
    phase: ValidationPhase,
    location: ValidationLocation,
    cause: Cow<'static, str>,
    corrective_action: Cow<'static, str>,
    retry: RetryClass,
}

impl<'de> Deserialize<'de> for ValidationError {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let wire = ValidationErrorWire::deserialize(deserializer)?;
        if wire.code.phase() != Some(wire.phase) {
            return Err(serde::de::Error::custom(format!(
                "validation rule {} belongs to phase {:?}, not {:?}",
                wire.code,
                wire.code.phase(),
                wire.phase
            )));
        }
        if wire.retry != RetryClass::Never {
            return Err(serde::de::Error::custom(format!(
                "validation rule {} has invalid retry class {:?}",
                wire.code, wire.retry
            )));
        }
        Ok(Self {
            code: wire.code,
            phase: wire.phase,
            location: wire.location,
            cause: wire.cause,
            corrective_action: wire.corrective_action,
            retry: wire.retry,
        })
    }
}

impl ValidationError {
    /// Construct one validation issue at the shared choke point.
    #[must_use]
    pub(crate) fn new(
        code: ValidationCode,
        phase: ValidationPhase,
        location: ValidationLocation,
        cause: impl Into<Cow<'static, str>>,
        corrective_action: impl Into<Cow<'static, str>>,
    ) -> Self {
        assert_eq!(
            code.phase(),
            Some(phase),
            "validation rule {code} emitted from the wrong phase"
        );
        Self {
            code,
            phase,
            location,
            cause: cause.into(),
            corrective_action: corrective_action.into(),
            retry: RetryClass::Never,
        }
    }

    /// Build an unsupported-operation diagnostic for backend capability checks.
    #[must_use]
    pub fn unsupported_op(backend: &'static str, op_id: &Arc<str>, node_index: usize) -> Self {
        Self::new(
            ValidationCode::V056,
            ValidationPhase::Capability,
            ValidationLocation::Operation(Cow::Owned(op_id.to_string())),
            format!(
                "backend `{backend}` does not support operation `{op_id}` at node {node_index}"
            ),
            format!(
                "choose a backend whose capability set includes this operation, lower the program through a supported backend pipeline, or register an implementation for `{op_id}`"
            ),
        )
    }

    /// Stable rule identity.
    #[must_use]
    pub fn code(&self) -> &ValidationCode {
        &self.code
    }

    /// Rule-owning validation phase.
    #[must_use]
    pub const fn phase(&self) -> ValidationPhase {
        self.phase
    }

    /// Typed program location.
    #[must_use]
    pub const fn location(&self) -> &ValidationLocation {
        &self.location
    }

    /// Deterministic cause detail.
    #[must_use]
    pub fn cause(&self) -> &str {
        &self.cause
    }

    /// Corrective action.
    #[must_use]
    pub fn corrective_action(&self) -> &str {
        &self.corrective_action
    }

    /// Retry policy.
    #[must_use]
    pub const fn retry(&self) -> RetryClass {
        self.retry
    }

    pub(crate) fn set_location(&mut self, location: ValidationLocation) {
        self.location = location;
    }

    /// Render the stable human-readable issue detail.
    #[must_use]
    pub fn message(&self) -> Cow<'_, str> {
        Cow::Owned(format!(
            "{}: {}. Fix: {}",
            self.code, self.cause, self.corrective_action
        ))
    }

    /// Return the trace event for this emission.
    #[must_use]
    pub fn trace_event(&self) -> ValidationTraceEvent {
        ValidationTraceEvent {
            code: self.code.clone(),
            phase: self.phase,
            location: self.location.clone(),
        }
    }

    /// Project the issue into the shared diagnostic protocol.
    #[must_use]
    pub fn diagnostic(&self) -> Diagnostic {
        Diagnostic {
            severity: Severity::Error,
            code: DiagnosticCode::from_owned(self.code.as_str().to_string()),
            stage: DiagnosticStage::Validate,
            message: self.cause.clone(),
            location: Some(self.location.diagnostic_location()),
            suggested_fix: Some(self.corrective_action.clone()),
            cause: Some(crate::diagnostics::DiagnosticCause {
                kind: self.phase.as_str().to_string(),
                detail: self.cause.to_string(),
            }),
            retry: self.retry,
            doc_url: Some(Cow::Owned(format!(
                "https://docs.vyre.dev/validator-errors#{}",
                self.code.as_str().to_ascii_lowercase()
            ))),
        }
    }
}

impl From<&ValidationError> for Diagnostic {
    fn from(issue: &ValidationError) -> Self {
        issue.diagnostic()
    }
}

impl From<ValidationError> for Diagnostic {
    fn from(issue: ValidationError) -> Self {
        issue.diagnostic()
    }
}

impl fmt::Display for ValidationError {
    fn fmt(&self, output: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(output, "vyre IR validation: {}", self.message())
    }
}

impl std::error::Error for ValidationError {}

#[cfg(test)]
mod tests {
    use super::*;

    fn issue() -> ValidationError {
        ValidationError::new(
            ValidationCode::new("V028"),
            ValidationPhase::Type,
            ValidationLocation::Operand {
                node: 7,
                operand: 1,
            },
            "Fma operand has type i32, expected f32",
            "cast the operand to f32",
        )
    }

    #[test]
    fn every_validation_family_is_enforced_at_the_shared_choke_point() {
        let cases = [
            ("V105", ValidationPhase::Program),
            ("V112", ValidationPhase::Node),
            ("V012", ValidationPhase::Expression),
            ("V084", ValidationPhase::Type),
            ("V057", ValidationPhase::Memory),
            ("V056", ValidationPhase::Capability),
            ("V115", ValidationPhase::Composition),
            ("V018", ValidationPhase::Limits),
        ];
        for (code, phase) in cases {
            let issue = ValidationError::new(
                ValidationCode::new(code),
                phase,
                ValidationLocation::Program,
                "family mutation",
                "restore the owning phase",
            );
            assert_eq!(issue.code.phase(), Some(phase));
        }
    }

    #[test]
    #[should_panic(expected = "emitted from the wrong phase")]
    fn phase_mutation_fails_at_the_shared_choke_point() {
        let _ = ValidationError::new(
            ValidationCode::new("V105"),
            ValidationPhase::Node,
            ValidationLocation::Program,
            "mutated rule owner",
            "restore the program phase",
        );
    }

    #[test]
    fn typed_issue_projects_without_parsing_prose() {
        let issue = issue();
        assert_eq!(issue.code().as_str(), "V028");
        assert_eq!(
            issue.message(),
            "V028: Fma operand has type i32, expected f32. Fix: cast the operand to f32"
        );
        assert_eq!(issue.trace_event().phase, ValidationPhase::Type);

        let diagnostic = issue.diagnostic();
        assert_eq!(diagnostic.code.as_str(), "V028");
        assert_eq!(diagnostic.stage, DiagnosticStage::Validate);
        assert_eq!(diagnostic.retry, RetryClass::Never);
        assert_eq!(
            diagnostic
                .location
                .as_ref()
                .and_then(|location| location.graph_node),
            Some(7)
        );
        assert_eq!(
            diagnostic.suggested_fix.as_deref(),
            Some("cast the operand to f32")
        );
        assert_eq!(
            diagnostic.cause.as_ref().map(|cause| cause.kind.as_str()),
            Some("type")
        );
    }

    #[test]
    fn serialization_preserves_every_issue_field() {
        let issue = issue();
        let encoded = serde_json::to_vec(&issue).expect("validation issue must serialize");
        let decoded: ValidationError =
            serde_json::from_slice(&encoded).expect("validation issue must deserialize");
        assert_eq!(decoded, issue);
        assert_eq!(decoded.diagnostic(), issue.diagnostic());
    }

    #[test]
    fn deserialization_rejects_unknown_rule_identity() {
        let encoded = serde_json::to_value(issue()).expect("issue must serialize");
        let mut mutated = encoded;
        mutated["code"] = serde_json::Value::String(format!("V{}", 999));
        let error = serde_json::from_value::<ValidationError>(mutated)
            .expect_err("unknown validation rule must fail closed");
        assert!(error.to_string().contains("unknown validation code"));
    }

    #[test]
    fn deserialization_rejects_phase_mutation() {
        let encoded = serde_json::to_value(issue()).expect("issue must serialize");
        let mut mutated = encoded;
        mutated["phase"] = serde_json::Value::String("node".to_string());
        let error = serde_json::from_value::<ValidationError>(mutated)
            .expect_err("phase mutation must fail closed");
        assert!(error.to_string().contains("belongs to phase"));
    }

    #[test]
    fn unsupported_op_has_typed_capability_identity() {
        let issue = ValidationError::unsupported_op("backend-a", &Arc::from("math::fma"), 3);
        assert_eq!(issue.code().as_str(), "V056");
        assert_eq!(issue.phase(), ValidationPhase::Capability);
        assert!(issue.message().contains("backend-a"));
        assert!(issue.message().contains("math::fma"));
        assert!(issue.message().contains("3"));
        assert!(issue.message().contains("Fix:"));
    }
}