saddle-db 0.2.0-rc.19

Saddle managed asynchronous database access and transactions
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
//! Deterministic, non-authoritative Database input for the 0.2 machine manifest.
//!
//! This boundary describes the fixed production implementation.  It does not
//! verify a signature, issue an authority receipt, or bind a startup owner.

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

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

use crate::c1_normal_return::db_normal_return_work_proof;

const SCHEMA: &str = "saddle-0.2-database-production-fact/1";
const DOMAIN: &str = "database-termination";
const MANIFEST_FACT: &str = "db_normal_return_work_identity";
const COMMITMENT: &str = "db_normal_return_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 DB_CANDIDATE_CONSUMED: AtomicBool = AtomicBool::new(false);

/// The sole Database-produced input for its 0.2 termination fact.
///
/// Fields are private and this type deliberately implements neither `Clone`,
/// serialization nor an extension trait. Its bytes are machine input only and
/// have no authority before the whole manifest is verified.
///
/// ```compile_fail
/// use saddle_db::internal::DatabaseProductionFactInput;
/// let _ = DatabaseProductionFactInput {};
/// ```
///
/// ```compile_fail
/// use saddle_db::internal::DatabaseProductionFactInput;
/// fn duplicate(input: DatabaseProductionFactInput) {
///     let _ = input.clone();
/// }
/// ```
#[doc(hidden)]
pub struct DatabaseProductionFactInput {
    document: DatabaseProductionFactDocument,
}

/// The exact approved whole and validation permit paired with a DB fact.
///
/// This input is field-private and non-cloneable. It is limited to the
/// approved source-validation candidate and is not enterprise authority.
///
/// ```compile_fail
/// use saddle_db::internal::DatabaseSourceCandidateInput;
/// fn duplicate(input: DatabaseSourceCandidateInput) {
///     let _ = input.clone();
/// }
/// ```
#[doc(hidden)]
pub struct DatabaseSourceCandidateInput {
    whole: &'static [u8],
    permit: &'static [u8],
}

/// Database's one-shot result inside the approved source candidate.
///
/// It exposes no identities or raw fact bytes. Later assembly can only carry
/// it linearly into the exact DB domain of the same candidate.
///
/// ```compile_fail
/// use saddle_db::internal::VerifiedDatabaseSourceCandidateOwner;
/// let _ = VerifiedDatabaseSourceCandidateOwner { _private: () };
/// ```
///
/// ```compile_fail
/// use saddle_db::internal::VerifiedDatabaseSourceCandidateOwner;
/// fn duplicate(owner: VerifiedDatabaseSourceCandidateOwner) {
///     let _ = owner.clone();
/// }
/// ```
#[doc(hidden)]
pub struct VerifiedDatabaseSourceCandidateOwner {
    fact: DatabaseProductionFactInput,
    candidate: DatabaseSourceCandidateInput,
}

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

impl DatabaseSourceCandidateRejection {
    #[doc(hidden)]
    pub fn into_inputs(self) -> (DatabaseProductionFactInput, DatabaseSourceCandidateInput) {
        (self.fact, self.candidate)
    }
}

/// Reproducible failure returned by the canonical machine serializer.
#[derive(Debug)]
#[doc(hidden)]
pub struct DatabaseProductionFactError(serde_json::Error);

impl core::fmt::Display for DatabaseProductionFactError {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter.write_str("Database production fact serialization failed")
    }
}

impl std::error::Error for DatabaseProductionFactError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.0)
    }
}

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

/// Produces the fixed Database fact without accepting caller-supplied values.
#[doc(hidden)]
pub fn database_production_fact_input() -> DatabaseProductionFactInput {
    let work = db_normal_return_work_proof();
    DatabaseProductionFactInput {
        document: DatabaseProductionFactDocument {
            schema: SCHEMA,
            domain: DOMAIN,
            manifest_fact: MANIFEST_FACT,
            commitment: COMMITMENT,
            authority: false,
            body: DatabaseTerminationWorkBody {
                backend: "mysql",
                driver: "sqlx",
                driver_version: work.sqlx_version().into(),
                max_ping_commands: work.max_ping_commands(),
                max_protocol_writes: work.max_protocol_writes(),
                max_protocol_reads: work.max_protocol_reads(),
                max_parallel_returns: 1,
                requires_open_pool: work.requires_open_pool(),
                requires_no_after_release_hook: work.requires_no_after_release_hook(),
                requires_no_max_lifetime: work.requires_no_max_lifetime(),
                requires_zero_min_connections: work.requires_zero_min_connections(),
                requires_deployment_service_attestation: work
                    .requires_deployment_service_attestation(),
                supports_budget_to_poison_discard: work.supports_budget_to_poison_discard(),
                work_identity: hex_identity(work.identity()),
            },
        },
    }
}

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

/// Pairs the real DB production fact with the exact approved whole and permit.
///
/// Every fallible check precedes the one-shot commit. Foreign, replayed or
/// drifted inputs return the original pair for exact recovery.
#[doc(hidden)]
#[allow(clippy::result_large_err)]
pub fn bind_database_source_candidate(
    fact: DatabaseProductionFactInput,
    candidate: DatabaseSourceCandidateInput,
) -> Result<VerifiedDatabaseSourceCandidateOwner, DatabaseSourceCandidateRejection> {
    if !matches_approved_candidate(&fact, &candidate)
        || DB_CANDIDATE_CONSUMED
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
    {
        return Err(DatabaseSourceCandidateRejection { fact, candidate });
    }
    Ok(VerifiedDatabaseSourceCandidateOwner { fact, candidate })
}

/// Rolls an accepted DB pair back before the later transaction commits.
///
/// The successful owner is consumed and the exact original inputs are
/// restored. Releasing the one-shot claim makes that same pair eligible for a
/// subsequent bind attempt; no other fact or candidate can be introduced.
#[doc(hidden)]
pub fn rollback_database_source_candidate(
    owner: VerifiedDatabaseSourceCandidateOwner,
) -> (DatabaseProductionFactInput, DatabaseSourceCandidateInput) {
    let VerifiedDatabaseSourceCandidateOwner { fact, candidate } = owner;
    DB_CANDIDATE_CONSUMED.store(false, Ordering::Release);
    (fact, candidate)
}

fn matches_approved_candidate(
    fact: &DatabaseProductionFactInput,
    candidate: &DatabaseSourceCandidateInput,
) -> 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.database == hex_sha256(&fact_bytes)
        && whole.projection.termination_work_identities.first()
            == Some(&fact.document.body.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 {
    database: 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(Serialize)]
struct DatabaseProductionFactDocument {
    schema: &'static str,
    domain: &'static str,
    manifest_fact: &'static str,
    commitment: &'static str,
    authority: bool,
    body: DatabaseTerminationWorkBody,
}

#[derive(Serialize)]
struct DatabaseTerminationWorkBody {
    backend: &'static str,
    driver: &'static str,
    driver_version: DriverVersion,
    max_ping_commands: u8,
    max_protocol_writes: u8,
    max_protocol_reads: u8,
    max_parallel_returns: u8,
    requires_open_pool: bool,
    requires_no_after_release_hook: bool,
    requires_no_max_lifetime: bool,
    requires_zero_min_connections: bool,
    requires_deployment_service_attestation: bool,
    supports_budget_to_poison_discard: bool,
    work_identity: String,
}

#[derive(Serialize)]
struct DriverVersion {
    major: u16,
    minor: u16,
    patch: u16,
}

impl From<(u16, u16, u16)> for DriverVersion {
    fn from((major, minor, patch): (u16, u16, u16)) -> Self {
        Self {
            major,
            minor,
            patch,
        }
    }
}

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::*;

    #[test]
    fn production_fact_audit_emission() {
        let Some(output) = std::env::var_os("SADDLE_DB_PRODUCTION_FACT_AUDIT_OUTPUT") else {
            return;
        };
        let fact = database_production_fact_input()
            .into_canonical_json()
            .expect("fixed fact serializes");
        std::fs::write(output, fact).expect("audit output is writable");
    }

    #[test]
    fn production_fact_is_canonical_and_stable() {
        let first = database_production_fact_input()
            .into_canonical_json()
            .expect("fixed fact serializes");
        let second = database_production_fact_input()
            .into_canonical_json()
            .expect("fixed fact serializes twice");
        assert_eq!(first, second);
        assert!(!first.contains(&b'\n'));

        let document: serde_json::Value = serde_json::from_slice(&first).unwrap();
        assert_eq!(document["schema"], SCHEMA);
        assert_eq!(document["authority"], false);
        assert_eq!(document["manifest_fact"], MANIFEST_FACT);
        assert_eq!(document["commitment"], COMMITMENT);
        assert_eq!(document["body"]["max_parallel_returns"], 1);
        assert_eq!(
            document["body"]["work_identity"],
            "53444c2d44422d52455455524e2d30312d53514c582d303830362d4d5953514c"
        );
    }

    #[test]
    fn approved_candidate_is_current_exact_recoverable_and_one_shot() {
        let foreign_whole = Box::leak(APPROVED_WHOLE.to_vec().into_boxed_slice());
        let foreign = DatabaseSourceCandidateInput {
            whole: foreign_whole,
            permit: APPROVED_PERMIT,
        };
        let foreign_whole_pointer = foreign.whole.as_ptr();
        let foreign_permit_pointer = foreign.permit.as_ptr();
        let rejected = bind_database_source_candidate(database_production_fact_input(), foreign)
            .err()
            .expect("foreign whole must reject");
        let (_fact, foreign) = rejected.into_inputs();
        assert_eq!(foreign.whole.as_ptr(), foreign_whole_pointer);
        assert_eq!(foreign.permit.as_ptr(), foreign_permit_pointer);

        let foreign_permit = Box::leak(APPROVED_PERMIT.to_vec().into_boxed_slice());
        let foreign = DatabaseSourceCandidateInput {
            whole: APPROVED_WHOLE,
            permit: foreign_permit,
        };
        let foreign_whole_pointer = foreign.whole.as_ptr();
        let foreign_permit_pointer = foreign.permit.as_ptr();
        let rejected = bind_database_source_candidate(database_production_fact_input(), foreign)
            .err()
            .expect("foreign permit must reject");
        let (fact, foreign) = rejected.into_inputs();
        assert_eq!(foreign.whole.as_ptr(), foreign_whole_pointer);
        assert_eq!(foreign.permit.as_ptr(), foreign_permit_pointer);

        let mut drifted = database_production_fact_input();
        drifted.document.body.max_protocol_reads += 1;
        let drift_candidate = database_source_candidate_input();
        let drift_whole = drift_candidate.whole.as_ptr();
        let drift_permit = drift_candidate.permit.as_ptr();
        let rejected = bind_database_source_candidate(drifted, drift_candidate)
            .err()
            .expect("drifted Database fact must reject");
        let (drifted, drift_candidate) = rejected.into_inputs();
        assert_eq!(drifted.document.body.max_protocol_reads, 2);
        assert_eq!(drift_candidate.whole.as_ptr(), drift_whole);
        assert_eq!(drift_candidate.permit.as_ptr(), drift_permit);

        let candidate = database_source_candidate_input();
        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.database,
            hex_sha256(&serde_json::to_vec(&fact.document).unwrap())
        );
        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);

        let owner = bind_database_source_candidate(fact, candidate)
            .unwrap_or_else(|_| panic!("approved pair must bind"));

        let replay_candidate = database_source_candidate_input();
        let replay_whole = replay_candidate.whole.as_ptr();
        let replay_permit = replay_candidate.permit.as_ptr();
        let rejected =
            bind_database_source_candidate(database_production_fact_input(), replay_candidate)
                .err()
                .expect("approved permit must not replay");
        let (replay_fact, replay_candidate) = rejected.into_inputs();
        assert_eq!(
            hex_sha256(&serde_json::to_vec(&replay_fact.document).unwrap()),
            whole.projection.domain_sha256.database
        );
        assert_eq!(replay_candidate.whole.as_ptr(), replay_whole);
        assert_eq!(replay_candidate.permit.as_ptr(), replay_permit);

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