peat-schema 0.9.0-rc.10

Wire format (Protobuf) definitions for the Peat Coordination Protocol
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
//! Product validators (AI/ML Products)
//!
//! Validates Product messages and their content types for Peat Protocol.

use super::{ValidationError, ValidationResult};
use crate::product::v1::{
    AlertProduct, AlertSeverity, AlertType, ChatProduct, ClassificationProduct, DetectionProduct,
    EmbeddingProduct, ImageFormat, ImageProduct, Product, ProductType, SegmentationProduct,
    SummaryProduct, SummaryType, TranscriptionProduct,
};

/// Validate a Product message
///
/// Validates:
/// - product_id is present
/// - product_type is specified (not unspecified)
/// - source_platform is present
/// - timestamp is present
/// - confidence is in valid range (0.0 - 1.0)
/// - content is present and valid for the product type
pub fn validate_product(product: &Product) -> ValidationResult<()> {
    // Check required fields
    if product.product_id.is_empty() {
        return Err(ValidationError::MissingField("product_id".to_string()));
    }

    // Product type must be specified
    if product.product_type == ProductType::Unspecified as i32 {
        return Err(ValidationError::InvalidValue(
            "product_type must be specified".to_string(),
        ));
    }

    if product.source_platform.is_empty() {
        return Err(ValidationError::MissingField("source_platform".to_string()));
    }

    // Timestamp is required
    if product.timestamp.is_none() {
        return Err(ValidationError::MissingField("timestamp".to_string()));
    }

    // Confidence must be in valid range
    if product.confidence < 0.0 || product.confidence > 1.0 {
        return Err(ValidationError::InvalidConfidence(product.confidence));
    }

    // Validate model_source if present
    if let Some(ref source) = product.model_source {
        if source.model_id.is_empty() {
            return Err(ValidationError::MissingField(
                "model_source.model_id".to_string(),
            ));
        }
    }

    // Validate content based on type
    use crate::product::v1::product::Content;
    match &product.content {
        Some(Content::Image(img)) => validate_image_product(img)?,
        Some(Content::Classification(cls)) => validate_classification_product(cls)?,
        Some(Content::Detection(det)) => validate_detection_product(det)?,
        Some(Content::Summary(sum)) => validate_summary_product(sum)?,
        Some(Content::Chat(chat)) => validate_chat_product(chat)?,
        Some(Content::Alert(alert)) => validate_alert_product(alert)?,
        Some(Content::Embedding(emb)) => validate_embedding_product(emb)?,
        Some(Content::Segmentation(seg)) => validate_segmentation_product(seg)?,
        Some(Content::Transcription(trans)) => validate_transcription_product(trans)?,
        None => {
            return Err(ValidationError::MissingField("content".to_string()));
        }
    }

    Ok(())
}

/// Validate an ImageProduct (chipout, thumbnail, etc.)
pub fn validate_image_product(image: &ImageProduct) -> ValidationResult<()> {
    // Format must be specified
    if image.format == ImageFormat::Unspecified as i32 {
        return Err(ValidationError::InvalidValue(
            "image format must be specified".to_string(),
        ));
    }

    // Dimensions must be positive
    if image.width == 0 {
        return Err(ValidationError::InvalidValue(
            "image width must be positive".to_string(),
        ));
    }

    if image.height == 0 {
        return Err(ValidationError::InvalidValue(
            "image height must be positive".to_string(),
        ));
    }

    // Must have image data (one of data, data_base64, url, or blob_hash)
    use crate::product::v1::image_product::ImageData;
    match &image.image_data {
        Some(ImageData::Data(bytes)) => {
            if bytes.is_empty() {
                return Err(ValidationError::InvalidValue(
                    "image data must not be empty".to_string(),
                ));
            }
        }
        Some(ImageData::DataBase64(b64)) => {
            if b64.is_empty() {
                return Err(ValidationError::InvalidValue(
                    "image data_base64 must not be empty".to_string(),
                ));
            }
        }
        Some(ImageData::Url(url)) => {
            if url.is_empty() {
                return Err(ValidationError::InvalidValue(
                    "image url must not be empty".to_string(),
                ));
            }
            if !url.contains("://") {
                return Err(ValidationError::InvalidValue(
                    "image url must be a valid URL with scheme".to_string(),
                ));
            }
        }
        Some(ImageData::BlobHash(hash)) => {
            if hash.is_empty() {
                return Err(ValidationError::InvalidValue(
                    "image blob_hash must not be empty".to_string(),
                ));
            }
        }
        None => {
            return Err(ValidationError::MissingField("image_data".to_string()));
        }
    }

    Ok(())
}

/// Validate a ClassificationProduct
pub fn validate_classification_product(cls: &ClassificationProduct) -> ValidationResult<()> {
    if cls.label.is_empty() {
        return Err(ValidationError::MissingField("label".to_string()));
    }

    if cls.confidence < 0.0 || cls.confidence > 1.0 {
        return Err(ValidationError::InvalidConfidence(cls.confidence));
    }

    // Validate top_k scores
    for score in &cls.top_k {
        if score.score < 0.0 || score.score > 1.0 {
            return Err(ValidationError::InvalidConfidence(score.score));
        }
    }

    Ok(())
}

/// Validate a DetectionProduct
pub fn validate_detection_product(det: &DetectionProduct) -> ValidationResult<()> {
    if det.label.is_empty() {
        return Err(ValidationError::MissingField("label".to_string()));
    }

    if det.confidence < 0.0 || det.confidence > 1.0 {
        return Err(ValidationError::InvalidConfidence(det.confidence));
    }

    // Bounding box should have 4 elements [x, y, width, height]
    if det.bbox.len() != 4 {
        return Err(ValidationError::InvalidValue(format!(
            "bbox must have 4 elements, got {}",
            det.bbox.len()
        )));
    }

    // Frame size should have 2 elements [width, height]
    if det.frame_size.len() != 2 {
        return Err(ValidationError::InvalidValue(format!(
            "frame_size must have 2 elements, got {}",
            det.frame_size.len()
        )));
    }

    Ok(())
}

/// Validate a SummaryProduct
pub fn validate_summary_product(summary: &SummaryProduct) -> ValidationResult<()> {
    if summary.text.is_empty() {
        return Err(ValidationError::MissingField("text".to_string()));
    }

    // Summary type must be specified
    if summary.summary_type == SummaryType::Unspecified as i32 {
        return Err(ValidationError::InvalidValue(
            "summary_type must be specified".to_string(),
        ));
    }

    Ok(())
}

/// Validate a ChatProduct
pub fn validate_chat_product(chat: &ChatProduct) -> ValidationResult<()> {
    if chat.response.is_empty() {
        return Err(ValidationError::MissingField("response".to_string()));
    }

    if chat.model_name.is_empty() {
        return Err(ValidationError::MissingField("model_name".to_string()));
    }

    // Temperature should be non-negative
    if chat.temperature < 0.0 {
        return Err(ValidationError::InvalidValue(
            "temperature must be non-negative".to_string(),
        ));
    }

    // top_p should be in [0, 1]
    if chat.top_p < 0.0 || chat.top_p > 1.0 {
        return Err(ValidationError::InvalidValue(format!(
            "top_p {} must be between 0.0 and 1.0",
            chat.top_p
        )));
    }

    Ok(())
}

/// Validate an AlertProduct
pub fn validate_alert_product(alert: &AlertProduct) -> ValidationResult<()> {
    // Alert type must be specified
    if alert.alert_type == AlertType::Unspecified as i32 {
        return Err(ValidationError::InvalidValue(
            "alert_type must be specified".to_string(),
        ));
    }

    // Severity must be specified
    if alert.severity == AlertSeverity::Unspecified as i32 {
        return Err(ValidationError::InvalidValue(
            "severity must be specified".to_string(),
        ));
    }

    if alert.message.is_empty() {
        return Err(ValidationError::MissingField("message".to_string()));
    }

    Ok(())
}

/// Validate an EmbeddingProduct
pub fn validate_embedding_product(emb: &EmbeddingProduct) -> ValidationResult<()> {
    if emb.vector.is_empty() {
        return Err(ValidationError::MissingField("vector".to_string()));
    }

    if emb.dimensions == 0 {
        return Err(ValidationError::InvalidValue(
            "dimensions must be positive".to_string(),
        ));
    }

    // Vector length should match dimensions
    if emb.vector.len() != emb.dimensions as usize {
        return Err(ValidationError::ConstraintViolation(format!(
            "vector length {} does not match dimensions {}",
            emb.vector.len(),
            emb.dimensions
        )));
    }

    if emb.embedding_model.is_empty() {
        return Err(ValidationError::MissingField("embedding_model".to_string()));
    }

    Ok(())
}

/// Validate a SegmentationProduct
pub fn validate_segmentation_product(seg: &SegmentationProduct) -> ValidationResult<()> {
    if seg.mask_data.is_empty() {
        return Err(ValidationError::MissingField("mask_data".to_string()));
    }

    if seg.width == 0 {
        return Err(ValidationError::InvalidValue(
            "width must be positive".to_string(),
        ));
    }

    if seg.height == 0 {
        return Err(ValidationError::InvalidValue(
            "height must be positive".to_string(),
        ));
    }

    Ok(())
}

/// Validate a TranscriptionProduct
pub fn validate_transcription_product(trans: &TranscriptionProduct) -> ValidationResult<()> {
    if trans.text.is_empty() {
        return Err(ValidationError::MissingField("text".to_string()));
    }

    if trans.language.is_empty() {
        return Err(ValidationError::MissingField("language".to_string()));
    }

    if trans.confidence < 0.0 || trans.confidence > 1.0 {
        return Err(ValidationError::InvalidConfidence(trans.confidence));
    }

    if trans.duration_seconds < 0.0 {
        return Err(ValidationError::InvalidValue(
            "duration_seconds must be non-negative".to_string(),
        ));
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::v1::Timestamp;
    use crate::product::v1::product::Content;

    fn valid_detection_product() -> Product {
        Product {
            product_id: "det-001".to_string(),
            product_type: ProductType::Detection as i32,
            source_platform: "Alpha-3".to_string(),
            timestamp: Some(Timestamp {
                seconds: 1702000000,
                nanos: 0,
            }),
            confidence: 0.92,
            model_source: None,
            track_id: String::new(),
            position: None,
            content: Some(Content::Detection(DetectionProduct {
                label: "person".to_string(),
                confidence: 0.92,
                bbox: vec![100, 200, 50, 100],
                frame_size: vec![1920, 1080],
                frame_number: 0,
                detection_index: 0,
            })),
            attributes_json: String::new(),
        }
    }

    #[test]
    fn test_valid_detection_product() {
        let product = valid_detection_product();
        assert!(validate_product(&product).is_ok());
    }

    #[test]
    fn test_missing_product_id() {
        let mut product = valid_detection_product();
        product.product_id = String::new();
        let err = validate_product(&product).unwrap_err();
        assert!(matches!(err, ValidationError::MissingField(f) if f == "product_id"));
    }

    #[test]
    fn test_unspecified_product_type() {
        let mut product = valid_detection_product();
        product.product_type = ProductType::Unspecified as i32;
        let err = validate_product(&product).unwrap_err();
        assert!(matches!(err, ValidationError::InvalidValue(_)));
    }

    #[test]
    fn test_missing_source_platform() {
        let mut product = valid_detection_product();
        product.source_platform = String::new();
        let err = validate_product(&product).unwrap_err();
        assert!(matches!(err, ValidationError::MissingField(f) if f == "source_platform"));
    }

    #[test]
    fn test_invalid_confidence() {
        let mut product = valid_detection_product();
        product.confidence = 1.5;
        let err = validate_product(&product).unwrap_err();
        assert!(matches!(err, ValidationError::InvalidConfidence(_)));
    }

    #[test]
    fn test_missing_content() {
        let mut product = valid_detection_product();
        product.content = None;
        let err = validate_product(&product).unwrap_err();
        assert!(matches!(err, ValidationError::MissingField(f) if f == "content"));
    }

    #[test]
    fn test_invalid_bbox_length() {
        let mut product = valid_detection_product();
        product.content = Some(Content::Detection(DetectionProduct {
            label: "person".to_string(),
            confidence: 0.92,
            bbox: vec![100, 200], // Should have 4 elements
            frame_size: vec![1920, 1080],
            frame_number: 0,
            detection_index: 0,
        }));
        let err = validate_product(&product).unwrap_err();
        assert!(matches!(err, ValidationError::InvalidValue(_)));
    }

    #[test]
    fn test_valid_classification_product() {
        let product = Product {
            product_id: "cls-001".to_string(),
            product_type: ProductType::Classification as i32,
            source_platform: "Alpha-3".to_string(),
            timestamp: Some(Timestamp {
                seconds: 1702000000,
                nanos: 0,
            }),
            confidence: 0.95,
            model_source: None,
            track_id: String::new(),
            position: None,
            content: Some(Content::Classification(ClassificationProduct {
                label: "vehicle".to_string(),
                confidence: 0.95,
                top_k: vec![],
                taxonomy: "coco".to_string(),
            })),
            attributes_json: String::new(),
        };
        assert!(validate_product(&product).is_ok());
    }

    #[test]
    fn test_valid_embedding_product() {
        let product = Product {
            product_id: "emb-001".to_string(),
            product_type: ProductType::Embedding as i32,
            source_platform: "Alpha-3".to_string(),
            timestamp: Some(Timestamp {
                seconds: 1702000000,
                nanos: 0,
            }),
            confidence: 1.0,
            model_source: None,
            track_id: String::new(),
            position: None,
            content: Some(Content::Embedding(EmbeddingProduct {
                vector: vec![0.1, 0.2, 0.3, 0.4],
                dimensions: 4,
                embedding_model: "test-model".to_string(),
                source_hash: String::new(),
                normalized: false,
            })),
            attributes_json: String::new(),
        };
        assert!(validate_product(&product).is_ok());
    }

    #[test]
    fn test_embedding_dimension_mismatch() {
        let product = Product {
            product_id: "emb-001".to_string(),
            product_type: ProductType::Embedding as i32,
            source_platform: "Alpha-3".to_string(),
            timestamp: Some(Timestamp {
                seconds: 1702000000,
                nanos: 0,
            }),
            confidence: 1.0,
            model_source: None,
            track_id: String::new(),
            position: None,
            content: Some(Content::Embedding(EmbeddingProduct {
                vector: vec![0.1, 0.2, 0.3, 0.4],
                dimensions: 8, // Mismatch with vector length
                embedding_model: "test-model".to_string(),
                source_hash: String::new(),
                normalized: false,
            })),
            attributes_json: String::new(),
        };
        let err = validate_product(&product).unwrap_err();
        assert!(matches!(err, ValidationError::ConstraintViolation(_)));
    }
}