saddle-observability 0.2.0

Saddle structured logging and trace correlation
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
//! Deterministic, non-authoritative Observability input for the 0.2 machine manifest.
//!
//! The emitted facts describe only the component's release/default file-core
//! observation and writer termination work. They do not verify a signature,
//! issue authority, or carry global root and generation facts.

use std::sync::atomic::{AtomicBool, Ordering};

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::file::{
    ObservabilityGeneratedLayoutSource, observe_release_fixed_core_layout,
    writer_component_work_proof,
};

const SCHEMA: &str = "saddle-0.2-observability-production-fact/1";
const DOMAIN: &str = "observability";
const MANIFEST_LEAF: &str = "observability";
const OBSERVABILITY_COMMITMENT: &str = "observability";
const WRITER_MANIFEST_FACT: &str = "writer_work_identity";
const WRITER_COMMITMENT: &str = "writer_work";
const APPROVED_SOURCE: &str = "da64568f31bfacd38f6c0807588dd2cc59c258fe";
const APPROVED_WHOLE: &[u8] = include_bytes!("approved-inputs/candidate-fact-whole.json");
const APPROVED_PERMIT: &[u8] = include_bytes!("approved-inputs/permit.json");
static OBSERVABILITY_CANDIDATE_CONSUMED: AtomicBool = AtomicBool::new(false);

/// The sole Observability-produced input for its 0.2 machine facts.
///
/// Fields are private and this type implements neither `Clone` nor
/// serialization. Its bytes remain non-authoritative until the complete
/// rendezvous manifest is verified.
///
/// ```compile_fail
/// use saddle_observability::ObservabilityProductionFactInput;
/// let _ = ObservabilityProductionFactInput {};
/// ```
///
/// ```compile_fail
/// use saddle_observability::ObservabilityProductionFactInput;
/// fn duplicate(input: ObservabilityProductionFactInput) {
///     let _ = input.clone();
/// }
/// ```
#[doc(hidden)]
pub struct ObservabilityProductionFactInput {
    document: ObservabilityProductionFactDocument,
}

/// The exact approved semantic whole and validation permit for OB-02.
///
/// ```compile_fail
/// use saddle_observability::ObservabilitySourceCandidateInput;
/// fn duplicate(input: ObservabilitySourceCandidateInput) { let _ = input.clone(); }
/// ```
#[doc(hidden)]
pub struct ObservabilitySourceCandidateInput {
    whole: &'static [u8],
    permit: &'static [u8],
}

/// Observability's opaque one-shot result inside the approved source candidate.
///
/// ```compile_fail
/// use saddle_observability::VerifiedObservabilitySourceCandidateOwner;
/// let _ = VerifiedObservabilitySourceCandidateOwner { _private: () };
/// ```
///
/// ```compile_fail
/// use saddle_observability::VerifiedObservabilitySourceCandidateOwner;
/// fn duplicate(owner: VerifiedObservabilitySourceCandidateOwner) {
///     let _ = owner.clone();
/// }
/// ```
///
/// ```compile_fail
/// use saddle_observability::VerifiedObservabilitySourceCandidateOwner;
/// fn borrowed(owner: &VerifiedObservabilitySourceCandidateOwner) {
///     let _ = owner.rollback();
/// }
/// ```
#[doc(hidden)]
pub struct VerifiedObservabilitySourceCandidateOwner {
    fact: ObservabilityProductionFactInput,
    candidate: ObservabilitySourceCandidateInput,
}

impl VerifiedObservabilitySourceCandidateOwner {
    /// Abandons the successful bind before final commit and restores its inputs.
    #[doc(hidden)]
    pub fn rollback(
        self,
    ) -> (
        ObservabilityProductionFactInput,
        ObservabilitySourceCandidateInput,
    ) {
        OBSERVABILITY_CANDIDATE_CONSUMED.store(false, Ordering::Release);
        (self.fact, self.candidate)
    }
}

/// A rejected pairing restores both original inputs unchanged.
#[doc(hidden)]
pub struct ObservabilitySourceCandidateRejection {
    fact: ObservabilityProductionFactInput,
    candidate: ObservabilitySourceCandidateInput,
}

impl ObservabilitySourceCandidateRejection {
    #[doc(hidden)]
    pub fn into_inputs(
        self,
    ) -> (
        ObservabilityProductionFactInput,
        ObservabilitySourceCandidateInput,
    ) {
        (self.fact, self.candidate)
    }
}

/// Failure returned while observing or serializing the fixed component facts.
#[derive(Debug)]
#[doc(hidden)]
pub enum ObservabilityProductionFactError {
    Observation,
    Serialization(serde_json::Error),
}

impl core::fmt::Display for ObservabilityProductionFactError {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Observation => {
                formatter.write_str("Observability production fact observation failed")
            }
            Self::Serialization(_) => {
                formatter.write_str("Observability production fact serialization failed")
            }
        }
    }
}

impl std::error::Error for ObservabilityProductionFactError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Observation => None,
            Self::Serialization(error) => Some(error),
        }
    }
}

impl ObservabilityProductionFactInput {
    /// Consumes the unique typed source and emits compact canonical JSON.
    #[doc(hidden)]
    pub fn into_canonical_json(self) -> Result<Box<[u8]>, ObservabilityProductionFactError> {
        serde_json::to_vec(&self.document)
            .map(Vec::into_boxed_slice)
            .map_err(ObservabilityProductionFactError::Serialization)
    }
}

/// Observes the fixed component without accepting caller-supplied facts.
#[doc(hidden)]
pub fn observability_production_fact_input()
-> Result<ObservabilityProductionFactInput, ObservabilityProductionFactError> {
    let observation = observe_release_fixed_core_layout()
        .map_err(|_| ObservabilityProductionFactError::Observation)?;
    let identities = observation.identities();
    let profile = observation.profile();
    let work = writer_component_work_proof();
    let payload_machine_bytes = profile[0]
        .checked_mul(profile[1])
        .ok_or(ObservabilityProductionFactError::Observation)?;

    Ok(ObservabilityProductionFactInput {
        document: ObservabilityProductionFactDocument {
            schema: SCHEMA,
            domain: DOMAIN,
            authority: false,
            observation: ObservationFact {
                manifest_leaf: MANIFEST_LEAF,
                commitment: OBSERVABILITY_COMMITMENT,
                leaf_identity: hex_identity(observation.leaf_identity()),
                profile_identity: hex_identity(identities[2]),
                component_identities: identities.map(hex_identity),
                profile,
                config_schema_identity: hex_identity(observation.config_schema_identity()),
                config_identity: hex_identity(observation.config_identity()),
                config_values: observation.config(),
                sizes: observation.sizes(),
                alignments: observation.alignments(),
                offsets: observation.offsets(),
                aggregate_layout: [
                    observation.aggregate_size(),
                    observation.aggregate_alignment(),
                ],
                payload_machine_bytes,
                source_identity: hex_identity(identities[0]),
                build_identity: hex_identity(identities[1]),
            },
            writer_termination: WriterTerminationFact {
                manifest_fact: WRITER_MANIFEST_FACT,
                commitment: WRITER_COMMITMENT,
                work_identity: hex_identity(work.identity()),
                version: work.version(),
                routed_files: work.routed_files(),
                reliability_domains: work.reliability_domains(),
                max_parallel_filesystem_ops: work.max_parallel_filesystem_ops(),
                shutdown_barrier_files: work.shutdown_barrier_files(),
                write_interrupt_retries: work.write_interrupt_retries(),
                rotation_publish_attempts: work.rotation_publish_attempts(),
                directory_syncs_per_rotation: work.directory_syncs_per_rotation(),
                hard_link_no_replace: work.hard_link_no_replace(),
                rename_ops_per_rotation: work.rename_ops_per_rotation(),
                bounded_retention_scan: work.bounded_retention_scan(),
                shutdown_requires_zero_encoding_owners: work
                    .shutdown_requires_zero_encoding_owners(),
                requires_deployment_filesystem_proof: work.requires_deployment_filesystem_proof(),
            },
        },
    })
}

/// Returns the sole source-controlled whole/permit pair approved for OB-02.
#[doc(hidden)]
pub fn observability_source_candidate_input() -> ObservabilitySourceCandidateInput {
    ObservabilitySourceCandidateInput {
        whole: APPROVED_WHOLE,
        permit: APPROVED_PERMIT,
    }
}

/// Binds the real Observability facts to the exact approved whole and permit.
///
/// All fallible validation precedes the one-shot commit. Foreign, drifted or
/// replayed inputs are rejected with both original owners restored.
#[doc(hidden)]
#[allow(clippy::result_large_err)]
pub fn bind_observability_source_candidate(
    fact: ObservabilityProductionFactInput,
    candidate: ObservabilitySourceCandidateInput,
) -> Result<VerifiedObservabilitySourceCandidateOwner, ObservabilitySourceCandidateRejection> {
    if !matches_approved_candidate(&fact, &candidate)
        || OBSERVABILITY_CANDIDATE_CONSUMED
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
    {
        return Err(ObservabilitySourceCandidateRejection { fact, candidate });
    }
    Ok(VerifiedObservabilitySourceCandidateOwner { fact, candidate })
}

fn matches_approved_candidate(
    fact: &ObservabilityProductionFactInput,
    candidate: &ObservabilitySourceCandidateInput,
) -> bool {
    if candidate.whole.as_ptr() != APPROVED_WHOLE.as_ptr()
        || candidate.whole.len() != APPROVED_WHOLE.len()
        || candidate.permit.as_ptr() != APPROVED_PERMIT.as_ptr()
        || candidate.permit.len() != APPROVED_PERMIT.len()
    {
        return false;
    }
    let Ok(fact_bytes) = serde_json::to_vec(&fact.document) else {
        return false;
    };
    let Ok(whole) = serde_json::from_slice::<CandidateWhole>(candidate.whole) else {
        return false;
    };
    let Ok(permit) = serde_json::from_slice::<ValidationPermit>(candidate.permit) else {
        return false;
    };
    whole.schema == "saddle-0.2-semantic-fact-whole-candidate/1"
        && !whole.authority
        && whole.projection.domain_sha256.observability == hex_sha256(&fact_bytes)
        && whole
            .projection
            .termination_work_identities
            .iter()
            .any(|identity| identity == &fact.document.writer_termination.work_identity)
        && permit.schema == "saddle-0.2-golden-c8-source-validation-permit/1"
        && permit.authority_scope == "golden-c8-listener-preclosure-only"
        && permit.source_candidate_identity == APPROVED_SOURCE
        && permit.candidate_fact_whole_identity == hex_sha256(candidate.whole)
        && permit.candidate_semantic_identity == whole.semantic_identity
        && permit.single_use
        && permit.minimum_terminal_stage == "listener"
        && !permit.signing_authority
        && !permit.enterprise_production_authority
        && !permit.rust_skill_artifact_combination_authority
        && !permit.component_production_wiring_authority
        && !permit.publish_authority
        && !permit.release_authority
}

fn hex_sha256(bytes: &[u8]) -> String {
    hex_identity(Sha256::digest(bytes).into())
}

#[derive(Deserialize)]
struct CandidateWhole {
    schema: String,
    authority: bool,
    semantic_identity: String,
    projection: CandidateProjection,
}

#[derive(Deserialize)]
struct CandidateProjection {
    domain_sha256: CandidateDomainDigests,
    termination_work_identities: Vec<String>,
}

#[derive(Deserialize)]
struct CandidateDomainDigests {
    observability: String,
}

#[derive(Deserialize)]
struct ValidationPermit {
    schema: String,
    authority_scope: String,
    source_candidate_identity: String,
    candidate_fact_whole_identity: String,
    candidate_semantic_identity: String,
    single_use: bool,
    minimum_terminal_stage: String,
    signing_authority: bool,
    enterprise_production_authority: bool,
    rust_skill_artifact_combination_authority: bool,
    component_production_wiring_authority: bool,
    publish_authority: bool,
    release_authority: bool,
}

#[derive(Deserialize, Serialize)]
struct ObservabilityProductionFactDocument {
    schema: &'static str,
    domain: &'static str,
    authority: bool,
    observation: ObservationFact,
    writer_termination: WriterTerminationFact,
}

#[derive(Deserialize, Serialize)]
struct ObservationFact {
    manifest_leaf: &'static str,
    commitment: &'static str,
    leaf_identity: String,
    profile_identity: String,
    component_identities: [String; 4],
    profile: [usize; 6],
    config_schema_identity: String,
    config_identity: String,
    config_values: [u64; 5],
    sizes: [usize; 4],
    alignments: [usize; 4],
    offsets: [usize; 4],
    aggregate_layout: [usize; 2],
    payload_machine_bytes: usize,
    source_identity: String,
    build_identity: String,
}

#[derive(Deserialize, Serialize)]
struct WriterTerminationFact {
    manifest_fact: &'static str,
    commitment: &'static str,
    work_identity: String,
    version: u8,
    routed_files: u8,
    reliability_domains: u8,
    max_parallel_filesystem_ops: u8,
    shutdown_barrier_files: u8,
    write_interrupt_retries: u8,
    rotation_publish_attempts: u8,
    directory_syncs_per_rotation: u8,
    hard_link_no_replace: bool,
    rename_ops_per_rotation: u8,
    bounded_retention_scan: bool,
    shutdown_requires_zero_encoding_owners: bool,
    requires_deployment_filesystem_proof: bool,
}

fn hex_identity(identity: [u8; 32]) -> String {
    use core::fmt::Write as _;

    let mut encoded = String::with_capacity(64);
    for byte in identity {
        write!(&mut encoded, "{byte:02x}").expect("writing to String cannot fail");
    }
    encoded
}

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

    fn approved_fact() -> ObservabilityProductionFactInput {
        let document =
            serde_json::from_slice(include_bytes!("approved-inputs/production-fact.json"))
                .expect("approved release/default Observability fact parses");
        ObservabilityProductionFactInput { document }
    }

    #[test]
    fn production_fact_is_canonical_stable_and_non_authoritative() {
        let first = observability_production_fact_input()
            .unwrap()
            .into_canonical_json()
            .unwrap();
        let second = observability_production_fact_input()
            .unwrap()
            .into_canonical_json()
            .unwrap();
        assert_eq!(first, second);
        assert!(!first.contains(&b'\n'));

        let document: serde_json::Value = serde_json::from_slice(&first).unwrap();
        assert_eq!(document["authority"], false);
        assert_eq!(
            document["writer_termination"]["work_identity"],
            "6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f6f"
        );
        assert!(document.get("root_identity").is_none());
        assert!(document.get("owner_generation").is_none());
    }

    #[test]
    fn approved_candidate_is_exact_recoverable_and_retryable_after_rollback() {
        let fact = approved_fact();
        let mut foreign = observability_source_candidate_input();
        foreign.whole = b"{}";
        let foreign_whole = foreign.whole.as_ptr();
        let foreign_permit = foreign.permit.as_ptr();
        let rejected = bind_observability_source_candidate(fact, foreign)
            .err()
            .expect("foreign whole must reject");
        let (fact, foreign) = rejected.into_inputs();
        assert_eq!(foreign.whole.as_ptr(), foreign_whole);
        assert_eq!(foreign.permit.as_ptr(), foreign_permit);
        assert_eq!(foreign.whole, b"{}");

        let mut drifted = approved_fact();
        drifted
            .document
            .writer_termination
            .rotation_publish_attempts += 1;
        let drift_candidate = observability_source_candidate_input();
        let drift_whole = drift_candidate.whole.as_ptr();
        let drift_permit = drift_candidate.permit.as_ptr();
        let rejected = bind_observability_source_candidate(drifted, drift_candidate)
            .err()
            .expect("drifted fact must reject");
        let (drifted, candidate) = rejected.into_inputs();
        assert_eq!(
            drifted
                .document
                .writer_termination
                .rotation_publish_attempts,
            9
        );
        assert_eq!(candidate.whole.as_ptr(), drift_whole);
        assert_eq!(candidate.permit.as_ptr(), drift_permit);

        let candidate = observability_source_candidate_input();
        let fact_bytes = serde_json::to_vec(&fact.document).unwrap();
        let whole: CandidateWhole = serde_json::from_slice(candidate.whole).unwrap();
        let permit: ValidationPermit = serde_json::from_slice(candidate.permit).unwrap();
        assert_eq!(
            whole.projection.domain_sha256.observability,
            hex_sha256(&fact_bytes)
        );
        assert!(
            whole
                .projection
                .termination_work_identities
                .contains(&fact.document.writer_termination.work_identity)
        );
        assert_eq!(permit.source_candidate_identity, APPROVED_SOURCE);
        assert_eq!(
            permit.candidate_fact_whole_identity,
            hex_sha256(candidate.whole)
        );
        assert_eq!(permit.candidate_semantic_identity, whole.semantic_identity);
        assert!(matches_approved_candidate(&fact, &candidate));
        let owner = bind_observability_source_candidate(fact, candidate)
            .unwrap_or_else(|_| panic!("approved pair must bind"));
        let replay_candidate = observability_source_candidate_input();
        let replay_whole = replay_candidate.whole.as_ptr();
        let replay_permit = replay_candidate.permit.as_ptr();
        let rejected = bind_observability_source_candidate(approved_fact(), replay_candidate)
            .err()
            .expect("approved permit must not replay");
        let (replayed_fact, replayed_candidate) = rejected.into_inputs();
        assert_eq!(
            hex_sha256(&serde_json::to_vec(&replayed_fact.document).unwrap()),
            whole.projection.domain_sha256.observability
        );
        assert_eq!(replayed_candidate.whole.as_ptr(), replay_whole);
        assert_eq!(replayed_candidate.permit.as_ptr(), replay_permit);

        let (fact, candidate) = owner.rollback();
        let retried = bind_observability_source_candidate(fact, candidate)
            .unwrap_or_else(|_| panic!("rolled-back pair must retry"));
        let _restored = retried.rollback();
    }
}