icydb-cli 0.220.0

Developer CLI tools for IcyDB
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
//! Module: diagnostic artifact.
//! Responsibility: export and validate bounded accepted-schema identity for host diagnostics.
//! Does not own: runtime schema authority, mutation admission, or canister persistence.
//! Boundary: an artifact can label an exact fingerprint only; it cannot authorize runtime work.

use std::{
    collections::{BTreeMap, BTreeSet},
    fs::{File, OpenOptions},
    io::{Read, Write},
    path::Path,
};

use serde::{Deserialize, Serialize};

const DIAGNOSTIC_ARTIFACT_FORMAT: &str = "icydb-diagnostic-schema";
const DIAGNOSTIC_ARTIFACT_VERSION: u8 = 1;
const MAX_DIAGNOSTIC_ARTIFACT_BYTES: usize = icydb_schema::MAX_SCHEMA_PROPOSAL_BYTES;

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct DiagnosticSchemaArtifact {
    format: String,
    version: u8,
    provenance: DiagnosticArtifactOwner,
    entities: Vec<DiagnosticArtifactEntity>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields, tag = "kind", rename_all = "snake_case")]
enum DiagnosticArtifactOwner {
    Deployment {
        environment: String,
        canister: String,
    },
    Source {
        source: String,
    },
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct DiagnosticArtifactEntity {
    fingerprint_method: u8,
    fingerprint: [u8; 16],
    entity_tag: u64,
    entity_name: String,
    entity_path: String,
    fields: Vec<DiagnosticArtifactIdentity>,
    constraints: Vec<DiagnosticArtifactConstraint>,
    indexes: Vec<DiagnosticArtifactIdentity>,
    relations: Vec<DiagnosticArtifactIdentity>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct DiagnosticArtifactIdentity {
    id: u32,
    name: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct DiagnosticArtifactConstraint {
    id: u32,
    name: String,
    kind: String,
    field_ids: Vec<u32>,
    index_id: Option<u32>,
    relation_id: Option<u32>,
}

pub(crate) struct ResolvedDiagnosticEntity<'a> {
    entity: &'a DiagnosticArtifactEntity,
    constraint: Option<&'a DiagnosticArtifactConstraint>,
}

impl DiagnosticSchemaArtifact {
    pub(crate) fn from_report(
        environment: &str,
        canister: &str,
        report: &[icydb::db::EntitySchemaDescription],
    ) -> Result<Self, String> {
        let mut entities = report
            .iter()
            .map(DiagnosticArtifactEntity::from_description)
            .collect::<Result<Vec<_>, _>>()?;
        entities.sort_by_key(|entity| {
            (
                entity.fingerprint_method,
                entity.fingerprint,
                entity.entity_tag,
            )
        });

        let artifact = Self {
            format: DIAGNOSTIC_ARTIFACT_FORMAT.to_string(),
            version: DIAGNOSTIC_ARTIFACT_VERSION,
            provenance: DiagnosticArtifactOwner::Deployment {
                environment: environment.to_string(),
                canister: canister.to_string(),
            },
            entities,
        };
        artifact.validate()?;
        Ok(artifact)
    }

    pub(crate) fn read_deployment(path: &Path) -> Result<Self, String> {
        let artifact = Self::read(path)?;
        if !matches!(
            &artifact.provenance,
            DiagnosticArtifactOwner::Deployment { .. }
        ) {
            return Err(format!(
                "diagnostic artifact '{}' is source metadata, not a deployment artifact",
                path.display()
            ));
        }
        Ok(artifact)
    }

    pub(crate) fn read_source_metadata(path: &Path) -> Result<Self, String> {
        let artifact = Self::read(path)?;
        if !matches!(&artifact.provenance, DiagnosticArtifactOwner::Source { .. }) {
            return Err(format!(
                "diagnostic source metadata '{}' is a deployment artifact",
                path.display()
            ));
        }
        Ok(artifact)
    }

    pub(crate) fn bind_to_source(mut self, source: &str) -> Result<Self, String> {
        validate_text("source", source)?;
        self.provenance = DiagnosticArtifactOwner::Source {
            source: source.to_string(),
        };
        self.validate()?;
        Ok(self)
    }

    fn read(path: &Path) -> Result<Self, String> {
        let file = File::open(path).map_err(|err| {
            format!(
                "failed to open diagnostic artifact '{}': {err}",
                path.display()
            )
        })?;
        let metadata = file.metadata().map_err(|err| {
            format!(
                "failed to inspect diagnostic artifact '{}': {err}",
                path.display()
            )
        })?;
        let byte_len = usize::try_from(metadata.len())
            .map_err(|_| "diagnostic artifact length does not fit this host".to_string())?;
        if byte_len > MAX_DIAGNOSTIC_ARTIFACT_BYTES {
            return Err(format!(
                "diagnostic artifact is {byte_len} bytes; maximum is {MAX_DIAGNOSTIC_ARTIFACT_BYTES}"
            ));
        }

        let mut bytes = Vec::with_capacity(byte_len);
        file.take((MAX_DIAGNOSTIC_ARTIFACT_BYTES + 1) as u64)
            .read_to_end(&mut bytes)
            .map_err(|err| {
                format!(
                    "failed to read diagnostic artifact '{}': {err}",
                    path.display()
                )
            })?;
        if bytes.len() > MAX_DIAGNOSTIC_ARTIFACT_BYTES {
            return Err(format!(
                "diagnostic artifact exceeds {MAX_DIAGNOSTIC_ARTIFACT_BYTES} bytes"
            ));
        }
        let artifact = serde_json::from_slice::<Self>(bytes.as_slice()).map_err(|err| {
            format!(
                "failed to decode current diagnostic artifact '{}': {err}",
                path.display()
            )
        })?;
        artifact.validate()?;
        Ok(artifact)
    }

    pub(crate) fn write_new(&self, path: &Path) -> Result<(), String> {
        self.validate()?;
        let bytes = serde_json::to_vec_pretty(self)
            .map_err(|err| format!("failed to encode diagnostic artifact: {err}"))?;
        if bytes.len() > MAX_DIAGNOSTIC_ARTIFACT_BYTES {
            return Err(format!(
                "encoded diagnostic artifact is {} bytes; maximum is {MAX_DIAGNOSTIC_ARTIFACT_BYTES}",
                bytes.len()
            ));
        }
        let mut output = OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(path)
            .map_err(|err| {
                format!(
                    "failed to create diagnostic artifact '{}': {err}",
                    path.display()
                )
            })?;
        output.write_all(bytes.as_slice()).map_err(|err| {
            format!(
                "failed to write diagnostic artifact '{}': {err}",
                path.display()
            )
        })
    }

    pub(crate) fn provenance_matches(&self, environment: &str, canister: &str) -> bool {
        matches!(
            &self.provenance,
            DiagnosticArtifactOwner::Deployment {
                environment: artifact_environment,
                canister: artifact_canister,
            } if artifact_environment == environment && artifact_canister == canister
        )
    }

    pub(crate) fn resolve(
        &self,
        fingerprint_method: u8,
        fingerprint: [u8; 16],
        entity_tag: u64,
        constraint_id: Option<u32>,
    ) -> Option<ResolvedDiagnosticEntity<'_>> {
        let entity = self.entities.iter().find(|entity| {
            entity.fingerprint_method == fingerprint_method
                && entity.fingerprint == fingerprint
                && entity.entity_tag == entity_tag
        })?;
        let constraint = match constraint_id {
            Some(constraint_id) => Some(entity.constraint(constraint_id)?),
            None => None,
        };
        Some(ResolvedDiagnosticEntity { entity, constraint })
    }

    fn validate(&self) -> Result<(), String> {
        if self.format != DIAGNOSTIC_ARTIFACT_FORMAT || self.version != DIAGNOSTIC_ARTIFACT_VERSION
        {
            return Err(format!(
                "unsupported diagnostic artifact format/version '{}'/{}; expected '{}'/{}",
                self.format, self.version, DIAGNOSTIC_ARTIFACT_FORMAT, DIAGNOSTIC_ARTIFACT_VERSION
            ));
        }
        match &self.provenance {
            DiagnosticArtifactOwner::Deployment {
                environment,
                canister,
            } => {
                validate_text("environment", environment.as_str())?;
                validate_text("canister", canister.as_str())?;
            }
            DiagnosticArtifactOwner::Source { source } => {
                validate_text("source", source.as_str())?;
            }
        }
        validate_count(
            "entities",
            self.entities.len(),
            icydb_schema::MAX_FRAGMENT_ENTITIES,
        )?;

        let mut entity_keys = BTreeSet::new();
        let mut entity_tags = BTreeSet::new();
        for entity in &self.entities {
            entity.validate()?;
            if !entity_keys.insert((
                entity.fingerprint_method,
                entity.fingerprint,
                entity.entity_tag,
            )) {
                return Err("diagnostic artifact contains duplicate entity identity".to_string());
            }
            if !entity_tags.insert(entity.entity_tag) {
                return Err("diagnostic artifact contains a duplicate entity tag".to_string());
            }
        }
        Ok(())
    }

    #[cfg(test)]
    pub(super) fn test_fixture() -> Self {
        Self {
            format: DIAGNOSTIC_ARTIFACT_FORMAT.to_string(),
            version: DIAGNOSTIC_ARTIFACT_VERSION,
            provenance: DiagnosticArtifactOwner::Deployment {
                environment: "demo".to_string(),
                canister: "app".to_string(),
            },
            entities: vec![DiagnosticArtifactEntity {
                fingerprint_method: 1,
                fingerprint: [7; 16],
                entity_tag: 42,
                entity_name: "Account".to_string(),
                entity_path: "schema::Account".to_string(),
                fields: vec![],
                constraints: vec![DiagnosticArtifactConstraint {
                    id: 3,
                    name: "account_name_unique".to_string(),
                    kind: "unique".to_string(),
                    field_ids: vec![],
                    index_id: None,
                    relation_id: None,
                }],
                indexes: vec![],
                relations: vec![],
            }],
        }
    }

    #[cfg(test)]
    pub(super) fn test_source_fixture() -> Self {
        let mut artifact = Self::test_fixture();
        artifact.provenance = DiagnosticArtifactOwner::Source {
            source: "schema/account.rs".to_string(),
        };
        artifact.entities[0].entity_name = "SourceAccount".to_string();
        artifact.entities[0].entity_path = "schema::source::Account".to_string();
        artifact.entities[0].constraints[0].name = "source_account_name_unique".to_string();
        artifact
    }
}

impl DiagnosticArtifactEntity {
    fn from_description(entity: &icydb::db::EntitySchemaDescription) -> Result<Self, String> {
        let mut fields = BTreeMap::<u32, String>::new();
        let mut indexes = BTreeMap::<u32, String>::new();
        let mut relations = BTreeMap::<u32, String>::new();
        let mut constraints = Vec::with_capacity(entity.constraints().len());

        for constraint in entity.constraints() {
            let mut field_ids = Vec::new();
            if let Some(field_id) = constraint.field_id() {
                let field_name = constraint.fields().first().ok_or_else(|| {
                    format!(
                        "constraint {} exposes field ID {field_id} without a field name",
                        constraint.id()
                    )
                })?;
                insert_exact_name(&mut fields, field_id, field_name, "field")?;
                field_ids.push(field_id);
            }
            if let (Some(index_id), Some(index_name)) = (constraint.index_id(), constraint.index())
            {
                insert_exact_name(&mut indexes, index_id, index_name, "index")?;
            }
            if let (Some(relation_id), Some(relation_name)) =
                (constraint.relation_id(), constraint.relation())
            {
                insert_exact_name(&mut relations, relation_id, relation_name, "relation")?;
            }
            constraints.push(DiagnosticArtifactConstraint {
                id: constraint.id(),
                name: constraint.name().to_string(),
                kind: constraint.kind().to_string(),
                field_ids,
                index_id: constraint.index_id(),
                relation_id: constraint.relation_id(),
            });
        }
        constraints.sort_by_key(|constraint| constraint.id);

        let entity = Self {
            fingerprint_method: entity.accepted_schema_fingerprint_method(),
            fingerprint: entity.accepted_schema_fingerprint(),
            entity_tag: entity.entity_tag(),
            entity_name: entity.entity_name().to_string(),
            entity_path: entity.entity_path().to_string(),
            fields: identities(fields),
            constraints,
            indexes: identities(indexes),
            relations: identities(relations),
        };
        entity.validate()?;
        Ok(entity)
    }

    fn constraint(&self, id: u32) -> Option<&DiagnosticArtifactConstraint> {
        self.constraints
            .binary_search_by_key(&id, |constraint| constraint.id)
            .ok()
            .map(|index| &self.constraints[index])
    }

    fn validate(&self) -> Result<(), String> {
        if self.fingerprint_method == 0 {
            return Err("diagnostic artifact fingerprint method must be non-zero".to_string());
        }
        validate_text("entity name", self.entity_name.as_str())?;
        validate_text("entity path", self.entity_path.as_str())?;
        validate_identities(
            "fields",
            self.fields.as_slice(),
            icydb_schema::MAX_FRAGMENT_FIELDS,
        )?;
        validate_identities(
            "indexes",
            self.indexes.as_slice(),
            icydb_schema::MAX_FRAGMENT_INDEXES,
        )?;
        validate_identities(
            "relations",
            self.relations.as_slice(),
            icydb_schema::MAX_FRAGMENT_RELATIONS,
        )?;
        validate_count(
            "constraints",
            self.constraints.len(),
            icydb_schema::MAX_FRAGMENT_CONSTRAINTS,
        )?;

        let mut constraint_ids = BTreeSet::new();
        for constraint in &self.constraints {
            if constraint.id == 0 || !constraint_ids.insert(constraint.id) {
                return Err("diagnostic artifact contains an invalid constraint ID".to_string());
            }
            validate_text("constraint name", constraint.name.as_str())?;
            validate_text("constraint kind", constraint.kind.as_str())?;
            validate_count(
                "constraint field IDs",
                constraint.field_ids.len(),
                icydb_schema::MAX_FRAGMENT_FIELDS,
            )?;
            if constraint
                .field_ids
                .iter()
                .any(|id| !self.fields.iter().any(|field| field.id == *id))
            {
                return Err(
                    "diagnostic artifact constraint references an unknown field ID".to_string(),
                );
            }
            if constraint
                .index_id
                .is_some_and(|id| !self.indexes.iter().any(|index| index.id == id))
            {
                return Err(
                    "diagnostic artifact constraint references an unknown index ID".to_string(),
                );
            }
            if constraint
                .relation_id
                .is_some_and(|id| !self.relations.iter().any(|relation| relation.id == id))
            {
                return Err(
                    "diagnostic artifact constraint references an unknown relation ID".to_string(),
                );
            }
        }
        Ok(())
    }
}

impl ResolvedDiagnosticEntity<'_> {
    pub(crate) const fn entity_name(&self) -> &str {
        self.entity.entity_name.as_str()
    }

    pub(crate) const fn entity_path(&self) -> &str {
        self.entity.entity_path.as_str()
    }

    pub(crate) fn constraint_name(&self) -> Option<&str> {
        self.constraint.map(|constraint| constraint.name.as_str())
    }

    pub(crate) fn constraint_kind(&self) -> Option<&str> {
        self.constraint.map(|constraint| constraint.kind.as_str())
    }

    pub(crate) fn field_name(&self, id: u32) -> Option<&str> {
        identity_name(self.entity.fields.as_slice(), id)
    }

    pub(crate) fn index_name(&self, id: u32) -> Option<&str> {
        identity_name(self.entity.indexes.as_slice(), id)
    }

    pub(crate) fn relation_name(&self, id: u32) -> Option<&str> {
        identity_name(self.entity.relations.as_slice(), id)
    }
}

fn identities(names: BTreeMap<u32, String>) -> Vec<DiagnosticArtifactIdentity> {
    names
        .into_iter()
        .map(|(id, name)| DiagnosticArtifactIdentity { id, name })
        .collect()
}

fn identity_name(identities: &[DiagnosticArtifactIdentity], id: u32) -> Option<&str> {
    identities
        .binary_search_by_key(&id, |identity| identity.id)
        .ok()
        .map(|index| identities[index].name.as_str())
}

fn insert_exact_name(
    identities: &mut BTreeMap<u32, String>,
    id: u32,
    name: &str,
    label: &str,
) -> Result<(), String> {
    if let Some(existing) = identities.get(&id) {
        if existing != name {
            return Err(format!(
                "diagnostic artifact {label} ID {id} has conflicting names"
            ));
        }
        return Ok(());
    }
    identities.insert(id, name.to_string());
    Ok(())
}

fn validate_identities(
    label: &str,
    identities: &[DiagnosticArtifactIdentity],
    maximum: usize,
) -> Result<(), String> {
    validate_count(label, identities.len(), maximum)?;
    let mut ids = BTreeSet::new();
    for identity in identities {
        if !ids.insert(identity.id) {
            return Err(format!("diagnostic artifact contains duplicate {label} ID"));
        }
        validate_text(label, identity.name.as_str())?;
    }
    Ok(())
}

fn validate_count(label: &str, actual: usize, maximum: usize) -> Result<(), String> {
    if actual > maximum {
        return Err(format!(
            "diagnostic artifact {label} count {actual} exceeds {maximum}"
        ));
    }
    Ok(())
}

fn validate_text(label: &str, value: &str) -> Result<(), String> {
    if value.is_empty() || value.len() > icydb_schema::MAX_SOURCE_KEY_BYTES {
        return Err(format!(
            "diagnostic artifact {label} must contain 1..={} bytes",
            icydb_schema::MAX_SOURCE_KEY_BYTES
        ));
    }
    Ok(())
}

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

    #[test]
    fn wrong_version_and_unknown_fields_fail_closed() {
        let wrong_version = br#"{
            "format":"icydb-diagnostic-schema",
            "version":2,
            "provenance":{"kind":"deployment","environment":"demo","canister":"app"},
            "entities":[]
        }"#;
        let artifact: DiagnosticSchemaArtifact =
            serde_json::from_slice(wrong_version).expect("shape should decode");
        assert!(artifact.validate().is_err());

        let unknown_field = br#"{
            "format":"icydb-diagnostic-schema",
            "version":1,
            "provenance":{"kind":"deployment","environment":"demo","canister":"app"},
            "entities":[],
            "legacy":true
        }"#;
        assert!(serde_json::from_slice::<DiagnosticSchemaArtifact>(unknown_field).is_err());
    }

    #[test]
    fn exact_fingerprint_and_entity_tag_are_required_for_resolution() {
        let artifact = DiagnosticSchemaArtifact::test_fixture();

        assert!(artifact.resolve(1, [7; 16], 42, Some(3)).is_some());
        assert!(artifact.resolve(2, [7; 16], 42, Some(3)).is_none());
        assert!(artifact.resolve(1, [8; 16], 42, Some(3)).is_none());
        assert!(artifact.resolve(1, [7; 16], 43, Some(3)).is_none());
        assert!(artifact.resolve(1, [7; 16], 42, Some(4)).is_none());
    }

    #[test]
    fn artifact_identity_is_projected_from_the_accepted_description() {
        let report = [icydb::db::EntitySchemaDescription::new(
            "schema::Account".to_string(),
            "Account".to_string(),
            42,
            1,
            [7; 16],
            "id".to_string(),
            vec!["id".to_string()],
            Vec::new(),
            Vec::new(),
            Vec::new(),
            Vec::new(),
            1,
            1,
        )];
        let artifact = DiagnosticSchemaArtifact::from_report("demo", "app", &report)
            .expect("accepted description should export");

        assert!(artifact.provenance_matches("demo", "app"));
        let resolved = artifact
            .resolve(1, [7; 16], 42, None)
            .expect("exact accepted identity should resolve");
        assert_eq!(resolved.entity_name(), "Account");
        assert_eq!(resolved.entity_path(), "schema::Account");
    }

    #[test]
    fn current_artifact_roundtrips_without_overwriting_existing_output() {
        let artifact = DiagnosticSchemaArtifact::test_fixture();
        let path = std::env::temp_dir().join(format!(
            "icydb-diagnostic-artifact-{}.json",
            std::process::id()
        ));
        if path.exists() {
            std::fs::remove_file(path.as_path()).expect("stale test artifact should be removable");
        }

        artifact
            .write_new(path.as_path())
            .expect("current artifact should write");
        assert_eq!(
            DiagnosticSchemaArtifact::read_deployment(path.as_path())
                .expect("current artifact should read"),
            artifact
        );
        assert!(artifact.write_new(path.as_path()).is_err());

        std::fs::remove_file(path).expect("test artifact should be removable");
    }

    #[test]
    fn deployment_and_source_provenance_are_not_interchangeable() {
        let deployment = DiagnosticSchemaArtifact::test_fixture();
        let source = DiagnosticSchemaArtifact::test_source_fixture();
        let deployment_path = std::env::temp_dir().join(format!(
            "icydb-diagnostic-deployment-{}.json",
            std::process::id()
        ));
        let source_path = std::env::temp_dir().join(format!(
            "icydb-diagnostic-source-{}.json",
            std::process::id()
        ));
        for path in [&deployment_path, &source_path] {
            if path.exists() {
                std::fs::remove_file(path).expect("stale test artifact should be removable");
            }
        }

        deployment
            .write_new(deployment_path.as_path())
            .expect("deployment artifact should write");
        source
            .write_new(source_path.as_path())
            .expect("source metadata should write");

        assert!(
            DiagnosticSchemaArtifact::read_deployment(source_path.as_path()).is_err(),
            "source metadata must not impersonate a deployment artifact"
        );
        assert!(
            DiagnosticSchemaArtifact::read_source_metadata(deployment_path.as_path()).is_err(),
            "deployment provenance must not impersonate source metadata"
        );
        assert_eq!(
            DiagnosticSchemaArtifact::read_source_metadata(source_path.as_path())
                .expect("source metadata should read"),
            source
        );

        std::fs::remove_file(deployment_path).expect("test artifact should be removable");
        std::fs::remove_file(source_path).expect("test artifact should be removable");
    }

    #[test]
    fn source_binding_preserves_the_exact_accepted_artifact_mapping() {
        let deployment = DiagnosticSchemaArtifact::test_fixture();
        let source = deployment
            .clone()
            .bind_to_source("schema/account.rs")
            .expect("valid source identity should bind");

        assert!(!source.provenance_matches("demo", "app"));
        assert_eq!(source.entities, deployment.entities);
        assert!(source.resolve(1, [7; 16], 42, Some(3)).is_some());
        assert!(source.resolve(1, [7; 16], 42, Some(4)).is_none());
        assert!(deployment.bind_to_source("").is_err());
    }
}