wyrd-spec 0.4.1

Wyrd foundation types: Card envelope, SpecKinds, and pure data contracts.
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//! Canonical id newtypes shared across the vala surface.
//!
//! This module owns ids that more than one vala submodule consumes. Verifier-scoped
//! ids such as `TaskId` and `JsonPath` live in
//! [`crate::verification::ids`].

use std::str::FromStr;

use serde::{Deserialize, Deserializer, Serialize};

use crate::error::WyrdError;

/// Session-scoped identifier grouping related verification, record, and observation records.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(transparent)]
pub struct SessionId(pub uuid::Uuid);

/// Run identifier carried by every observation from one agent invocation.
///
/// UUIDv7 string at the wire boundary. Client-generated so retries converge on
/// the same id, and so observability surfaces can correlate records emitted
/// before the server first sees the run.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(transparent)]
pub struct RunId(String);

impl RunId {
    /// Generate a fresh UUIDv7 run identifier.
    #[must_use]
    pub fn new() -> Self {
        Self(crate::ids::uuid7())
    }

    /// Adopt a caller-supplied run identifier.
    #[must_use]
    pub fn from_string(value: String) -> Self {
        Self(value)
    }

    /// Borrow the identifier as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Deterministic bucket assignment for stable sampling decisions.
    ///
    /// SHA-256 over the id bytes; the first eight digest bytes are read
    /// big-endian as a `u64` and reduced modulo `buckets`.
    ///
    /// # Panics
    ///
    /// Panics if a remainder exceeds its `u32` divisor, which arithmetic rules out.
    #[must_use]
    pub fn hash_bucket(&self, buckets: u32) -> u32 {
        use sha2::{Digest, Sha256};

        if buckets == 0 {
            return 0;
        }
        let digest = Sha256::digest(self.0.as_bytes());
        let mut prefix = [0_u8; 8];
        prefix.copy_from_slice(&digest[..8]);
        let value = u64::from_be_bytes(prefix);
        u32::try_from(value % u64::from(buckets)).expect("a remainder is below its u32 divisor")
    }
}

impl Default for RunId {
    fn default() -> Self {
        Self::new()
    }
}

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

/// Identifier for a single vala record.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(transparent)]
pub struct RecordId(pub uuid::Uuid);

/// Identifier for one workflow execution against one target and input row.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(transparent)]
pub struct WorkflowUid(pub uuid::Uuid);

/// Stable user-facing entity identifier for the verification subject or observation subject.
///
/// Entity UIDs must be non-empty and no longer than 512 characters.
/// Deserialization goes through [`EntityUid::new`] so wire payloads cannot bypass
/// validation.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "server", schema(value_type = String))]
#[serde(transparent)]
pub struct EntityUid(String);

impl EntityUid {
    /// Constructs a validated entity uid.
    ///
    /// # Errors
    /// Returns [`WyrdError::Validation`] when the value is empty or longer than
    /// 512 characters.
    pub fn new(value: impl Into<String>) -> Result<Self, WyrdError> {
        let value = value.into();
        if value.is_empty() || value.len() > 512 {
            return Err(WyrdError::Validation {
                message: format!("entity_uid length must be 1..=512, got {}", value.len()),
                details: serde_json::Value::Null,
            });
        }
        Ok(Self(value))
    }

    /// Borrows the validated entity uid as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromStr for EntityUid {
    type Err = WyrdError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

impl<'de> Deserialize<'de> for EntityUid {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = String::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

impl schemars::JsonSchema for EntityUid {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "EntityUid".into()
    }

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({ "type": "string", "minLength": 1, "maxLength": 512 })
    }
}

/// Sixteen-byte OpenTelemetry trace identifier.
///
/// Wire format is a 32-character lower-case hex string. Deserialization also
/// accepts the legacy byte-array shape so existing callers can continue
/// to read older payloads. The all-zero id is the OTel invalid sentinel and is
/// rejected by public constructors and deserialization.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "server", schema(value_type = String))]
pub struct TraceId([u8; 16]);

impl TraceId {
    /// All-zero invalid-id sentinel.
    ///
    /// Constructors never return this value; it is exposed so validation code
    /// can compare against an explicitly invalid sentinel when needed.
    pub const ZERO: TraceId = TraceId([0u8; 16]);

    /// Constructs a trace id from a 32-character hex string.
    ///
    /// # Errors
    /// Returns [`WyrdError::Validation`] when the string has the wrong length,
    /// contains non-hex characters, or represents the all-zero sentinel.
    pub fn from_hex(value: &str) -> Result<Self, WyrdError> {
        if value.len() != 32 {
            return Err(WyrdError::Validation {
                message: format!("trace_id hex length must be 32, got {}", value.len()),
                details: serde_json::Value::Null,
            });
        }

        let mut bytes = [0u8; 16];
        for (index, chunk) in value.as_bytes().chunks(2).enumerate() {
            let hi = hex_nibble(chunk[0])?;
            let lo = hex_nibble(chunk[1])?;
            bytes[index] = (hi << 4) | lo;
        }

        Self::from_bytes(bytes)
    }

    /// Constructs a trace id from raw bytes.
    ///
    /// # Errors
    /// Returns [`WyrdError::Validation`] when the bytes are all zero.
    pub fn from_bytes(bytes: [u8; 16]) -> Result<Self, WyrdError> {
        if bytes == [0u8; 16] {
            return Err(WyrdError::Validation {
                message: "trace_id all-zero is the OTel invalid sentinel".to_string(),
                details: serde_json::Value::Null,
            });
        }

        Ok(Self(bytes))
    }

    /// Returns the 32-character lower-case hex representation.
    #[must_use]
    pub fn to_hex(&self) -> String {
        let mut out = String::with_capacity(32);
        for byte in &self.0 {
            out.push(hex_char(byte >> 4));
            out.push(hex_char(byte & 0x0f));
        }
        out
    }

    /// Borrows the underlying bytes.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8; 16] {
        &self.0
    }
}

impl Serialize for TraceId {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.to_hex())
    }
}

impl<'de> Deserialize<'de> for TraceId {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Wire {
            Hex(String),
            Bytes([u8; 16]),
        }

        match Wire::deserialize(deserializer)? {
            Wire::Hex(value) => Self::from_hex(&value).map_err(serde::de::Error::custom),
            Wire::Bytes(bytes) => Self::from_bytes(bytes).map_err(serde::de::Error::custom),
        }
    }
}

impl schemars::JsonSchema for TraceId {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "TraceId".into()
    }

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({ "type": "string", "minLength": 32, "maxLength": 32, "pattern": r"^[0-9a-f]{32}$" })
    }
}

impl std::fmt::Display for TraceId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.to_hex())
    }
}

impl FromStr for TraceId {
    type Err = WyrdError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::from_hex(s)
    }
}

/// Eight-byte OpenTelemetry span identifier.
///
/// Wire format is a 16-character lower-case hex string. Deserialization also
/// accepts the legacy byte-array shape so existing callers can continue
/// to read older payloads. The all-zero id is the OTel invalid sentinel and is
/// rejected by public constructors and deserialization.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "server", schema(value_type = String))]
pub struct SpanId([u8; 8]);

impl SpanId {
    /// All-zero invalid-id sentinel.
    ///
    /// Constructors never return this value; it is exposed so validation code
    /// can compare against an explicitly invalid sentinel when needed.
    pub const ZERO: SpanId = SpanId([0u8; 8]);

    /// Constructs a span id from a 16-character hex string.
    ///
    /// # Errors
    /// Returns [`WyrdError::Validation`] when the string has the wrong length,
    /// contains non-hex characters, or represents the all-zero sentinel.
    pub fn from_hex(value: &str) -> Result<Self, WyrdError> {
        if value.len() != 16 {
            return Err(WyrdError::Validation {
                message: format!("span_id hex length must be 16, got {}", value.len()),
                details: serde_json::Value::Null,
            });
        }

        let mut bytes = [0u8; 8];
        for (index, chunk) in value.as_bytes().chunks(2).enumerate() {
            let hi = hex_nibble(chunk[0])?;
            let lo = hex_nibble(chunk[1])?;
            bytes[index] = (hi << 4) | lo;
        }

        Self::from_bytes(bytes)
    }

    /// Constructs a span id from raw bytes.
    ///
    /// # Errors
    /// Returns [`WyrdError::Validation`] when the bytes are all zero.
    pub fn from_bytes(bytes: [u8; 8]) -> Result<Self, WyrdError> {
        if bytes == [0u8; 8] {
            return Err(WyrdError::Validation {
                message: "span_id all-zero is the OTel invalid sentinel".to_string(),
                details: serde_json::Value::Null,
            });
        }

        Ok(Self(bytes))
    }

    /// Returns the 16-character lower-case hex representation.
    #[must_use]
    pub fn to_hex(&self) -> String {
        let mut out = String::with_capacity(16);
        for byte in &self.0 {
            out.push(hex_char(byte >> 4));
            out.push(hex_char(byte & 0x0f));
        }
        out
    }

    /// Borrows the underlying bytes.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8; 8] {
        &self.0
    }
}

impl Serialize for SpanId {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.to_hex())
    }
}

impl<'de> Deserialize<'de> for SpanId {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Wire {
            Hex(String),
            Bytes([u8; 8]),
        }

        match Wire::deserialize(deserializer)? {
            Wire::Hex(value) => Self::from_hex(&value).map_err(serde::de::Error::custom),
            Wire::Bytes(bytes) => Self::from_bytes(bytes).map_err(serde::de::Error::custom),
        }
    }
}

impl schemars::JsonSchema for SpanId {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "SpanId".into()
    }

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({ "type": "string", "minLength": 16, "maxLength": 16, "pattern": r"^[0-9a-f]{16}$" })
    }
}

impl std::fmt::Display for SpanId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.to_hex())
    }
}

impl FromStr for SpanId {
    type Err = WyrdError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::from_hex(s)
    }
}

/// Version of one Bifrost table's complete immutable definition.
///
/// Creation publishes [`TableVersion::INITIAL`]; each effective definition
/// edit publishes the next version. Data, snapshot and housekeeping commits
/// keep it. The domain is `1..=i64::MAX`, and JSON carries it as a canonical
/// unsigned decimal string so no reader rounds it through a float.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "server", schema(value_type = String))]
pub struct TableVersion(i64);

impl TableVersion {
    /// The version a newly created table starts at.
    pub const INITIAL: TableVersion = TableVersion(1);

    /// Adopts a stored version.
    ///
    /// # Errors
    /// Returns [`WyrdError::Validation`] when `value` is not positive.
    pub fn new(value: i64) -> Result<Self, WyrdError> {
        if value > 0 {
            Ok(Self(value))
        } else {
            Err(WyrdError::Validation {
                message: format!("table_version must be positive, got {value}"),
                details: serde_json::Value::Null,
            })
        }
    }

    /// Returns the version as its stored integer.
    #[must_use]
    pub fn get(self) -> i64 {
        self.0
    }

    /// Returns the version an effective edit publishes, or `None` once the
    /// domain is exhausted.
    #[must_use]
    pub fn next(self) -> Option<Self> {
        self.0.checked_add(1).map(Self)
    }
}

impl std::fmt::Display for TableVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for TableVersion {
    type Err = WyrdError;

    /// Parses a canonical unsigned decimal: no sign, leading zero,
    /// whitespace, fraction or exponent.
    ///
    /// # Errors
    /// Returns [`WyrdError::Validation`] when `s` is not canonical decimal
    /// syntax or names a value outside `1..=i64::MAX`.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let canonical = s.bytes().all(|byte| byte.is_ascii_digit()) && !s.starts_with('0');
        match s.parse::<i64>() {
            Ok(value) if canonical => Self::new(value),
            _ => Err(WyrdError::Validation {
                message: format!(
                    "table_version must be a canonical decimal string in 1..=9223372036854775807, got {s:?}"
                ),
                details: serde_json::Value::Null,
            }),
        }
    }
}

impl Serialize for TableVersion {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for TableVersion {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = String::deserialize(deserializer)?;
        value.parse().map_err(serde::de::Error::custom)
    }
}

impl schemars::JsonSchema for TableVersion {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "TableVersion".into()
    }

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "type": "string",
            "minLength": 1,
            "maxLength": 19,
            "pattern": "^[1-9][0-9]*$"
        })
    }
}

fn hex_nibble(byte: u8) -> Result<u8, WyrdError> {
    match byte {
        b'0'..=b'9' => Ok(byte - b'0'),
        b'a'..=b'f' => Ok(byte - b'a' + 10),
        b'A'..=b'F' => Ok(byte - b'A' + 10),
        other => Err(WyrdError::Validation {
            message: format!("invalid hex character: {:?}", other as char),
            details: serde_json::Value::Null,
        }),
    }
}

fn hex_char(nibble: u8) -> char {
    assert!(nibble < 16, "hex_char received >15 nibble; caller bug");
    if nibble < 10 {
        (b'0' + nibble) as char
    } else {
        (b'a' + nibble - 10) as char
    }
}

#[cfg(test)]
mod tests {
    use super::{EntityUid, RecordId, SessionId, SpanId, TableVersion, TraceId, WorkflowUid};

    #[test]
    fn id_uuid_types_serde_round_trip() {
        let uuid = uuid::Uuid::nil();
        let session = SessionId(uuid);
        let record = RecordId(uuid);
        let workflow = WorkflowUid(uuid);

        assert_eq!(
            serde_json::to_string(&session).expect("session id serializes"),
            format!("\"{uuid}\"")
        );
        assert_eq!(
            session,
            serde_json::from_str(&format!("\"{uuid}\"")).expect("session id")
        );
        assert_eq!(
            record,
            serde_json::from_str(&format!("\"{uuid}\"")).expect("record id")
        );
        assert_eq!(
            workflow,
            serde_json::from_str(&format!("\"{uuid}\"")).expect("workflow id")
        );
    }

    #[test]
    fn entity_uid_serde_round_trip() {
        let entity = EntityUid::new("customer-123").expect("valid entity uid");
        let json = serde_json::to_string(&entity).expect("entity uid serializes");
        assert_eq!(json, "\"customer-123\"");
        let round_trip: EntityUid = serde_json::from_str(&json).expect("entity uid deserializes");
        assert_eq!(entity, round_trip);
    }

    #[test]
    fn trace_id_deserializes_legacy_byte_array_and_serializes_hex() {
        let trace: TraceId = serde_json::from_str("[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]")
            .expect("legacy byte array deserializes");
        let json = serde_json::to_string(&trace).expect("trace id serializes");
        assert_eq!(json, "\"0102030405060708090a0b0c0d0e0f10\"");
    }

    #[test]
    fn span_id_deserializes_legacy_byte_array_and_serializes_hex() {
        let span: SpanId =
            serde_json::from_str("[1,2,3,4,5,6,7,8]").expect("legacy byte array deserializes");
        let json = serde_json::to_string(&span).expect("span id serializes");
        assert_eq!(json, "\"0102030405060708\"");
    }

    /// JSON carries every version, including values a float cannot represent
    /// exactly, as the canonical decimal string it parses back from; the
    /// domain maximum has no successor.
    ///
    /// # Panics
    ///
    /// Panics when a positive value is refused, a version does not serialize
    /// to its canonical decimal string or parse back to itself, or the domain
    /// maximum has a successor.
    #[test]
    fn table_version_round_trips_canonical_strings_beyond_two_to_the_53() {
        for value in [1_i64, (1 << 53) + 1, i64::MAX] {
            let version = TableVersion::new(value).expect("positive");
            let json = serde_json::to_string(&version).expect("serialize");
            assert_eq!(json, format!("\"{value}\""));
            assert_eq!(
                serde_json::from_str::<TableVersion>(&json).expect("deserialize"),
                version
            );
        }
        assert_eq!(TableVersion::new(i64::MAX).expect("max").next(), None);
    }

    /// Bare numbers, null, zero, signs, padding, leading zeros, fractions,
    /// exponents and out-of-range decimals are refused rather than coerced,
    /// so one version has exactly one wire spelling.
    ///
    /// # Panics
    ///
    /// Panics when any noncanonical spelling deserializes or zero is accepted
    /// as a version.
    #[test]
    fn table_version_refuses_noncanonical_forms() {
        for json in [
            "1",
            "\"0\"",
            "\"01\"",
            "\"+1\"",
            "\"-1\"",
            "\" 1\"",
            "\"1 \"",
            "\"1.0\"",
            "\"1e3\"",
            "\"\"",
            "\"9223372036854775808\"",
            "null",
        ] {
            assert!(
                serde_json::from_str::<TableVersion>(json).is_err(),
                "{json} must be refused"
            );
        }
        assert!(TableVersion::new(0).is_err());
    }
}