fp-runtime 0.1.0

Runtime policies, evidence ledgers, and asupersync interop for the frankenpandas execution layer.
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
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};

use crate::asupersync::{
    codec::ArtifactCodec,
    config::AsupersyncConfig,
    error::AsupersyncError,
    integrity::{IntegrityProof, IntegrityVerifier},
    transport::{TransferStatus, TransportLayer},
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RecoveryOutcome {
    Recovered,
    RetryScheduled,
    Rejected,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RecoveryPlan {
    pub artifact_id: String,
    pub max_attempts: u32,
    pub deadline_unix_ms: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RecoveryReport {
    pub artifact_id: String,
    pub attempts: u32,
    pub outcome: RecoveryOutcome,
    pub transfer_status: TransferStatus,
    pub integrity: Option<IntegrityProof>,
}

pub trait RecoveryPolicy {
    fn should_retry(&self, attempt: u32, max_attempts: u32) -> bool;

    fn classify(
        &self,
        transfer_status: TransferStatus,
        attempt: u32,
        max_attempts: u32,
    ) -> RecoveryOutcome {
        match transfer_status {
            TransferStatus::Completed => RecoveryOutcome::Recovered,
            TransferStatus::RetryableFailure => {
                if self.should_retry(attempt, max_attempts) {
                    RecoveryOutcome::RetryScheduled
                } else {
                    RecoveryOutcome::Rejected
                }
            }
            TransferStatus::PermanentFailure => RecoveryOutcome::Rejected,
        }
    }
}

#[derive(Debug, Clone, Copy, Default)]
pub struct ConservativeRecoveryPolicy;

impl RecoveryPolicy for ConservativeRecoveryPolicy {
    fn should_retry(&self, attempt: u32, max_attempts: u32) -> bool {
        attempt < max_attempts
    }
}

fn current_unix_ms() -> u64 {
    let millis = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |duration| duration.as_millis());
    u64::try_from(millis).unwrap_or(u64::MAX)
}

fn recovery_deadline_expired(deadline_unix_ms: u64) -> bool {
    deadline_unix_ms != 0 && current_unix_ms() > deadline_unix_ms
}

pub fn recover_once<C, T, V, P>(
    codec: &C,
    transport: &T,
    verifier: &V,
    policy: &P,
    config: &AsupersyncConfig,
    plan: &RecoveryPlan,
    expected_digest: &str,
) -> Result<RecoveryReport, AsupersyncError>
where
    C: ArtifactCodec,
    T: TransportLayer,
    V: IntegrityVerifier,
    P: RecoveryPolicy,
{
    if plan.max_attempts == 0 {
        return Err(AsupersyncError::Configuration(
            "max_attempts must be greater than zero",
        ));
    }

    // Per br-frankenpandas-bc6fa4: enforce a hard ceiling at max_attempts even
    // if a buggy RecoveryPolicy returns should_retry=true past the limit.
    // saturating_add prevents u32 overflow panics in debug; the explicit
    // attempts >= max_attempts gate makes the contract independent of the
    // policy implementation.
    let mut attempts = 0_u32;
    let should_retry = |attempt: u32| {
        attempt < plan.max_attempts && policy.should_retry(attempt, plan.max_attempts)
    };
    loop {
        if recovery_deadline_expired(plan.deadline_unix_ms) {
            return Err(AsupersyncError::RecoveryExhausted {
                artifact_id: plan.artifact_id.clone(),
                attempts,
            });
        }

        attempts = attempts.saturating_add(1);

        let encoded = match transport.receive(&plan.artifact_id, config) {
            Ok(encoded) => encoded,
            Err(_) => {
                if should_retry(attempts) {
                    continue;
                }
                return Err(AsupersyncError::RecoveryExhausted {
                    artifact_id: plan.artifact_id.clone(),
                    attempts,
                });
            }
        };

        let payload = match codec.decode(&encoded, config) {
            Ok(p) => p,
            Err(_) => {
                if should_retry(attempts) {
                    continue;
                }
                return Err(AsupersyncError::RecoveryExhausted {
                    artifact_id: plan.artifact_id.clone(),
                    attempts,
                });
            }
        };
        match verifier.verify(&plan.artifact_id, &payload.bytes, expected_digest) {
            Ok(integrity) => {
                return Ok(RecoveryReport {
                    artifact_id: plan.artifact_id.clone(),
                    attempts,
                    outcome: RecoveryOutcome::Recovered,
                    transfer_status: TransferStatus::Completed,
                    integrity: Some(integrity),
                });
            }
            Err(_) => {
                if should_retry(attempts) {
                    continue;
                }
                return Err(AsupersyncError::RecoveryExhausted {
                    artifact_id: plan.artifact_id.clone(),
                    attempts,
                });
            }
        }
    }
}

#[cfg(test)]
mod test_recover_once_bounded_loop_bc6fa4 {
    use std::cell::Cell;

    use super::*;
    use crate::asupersync::{
        codec::{ArtifactPayload, EncodedArtifact, PassthroughCodec},
        config::{AsupersyncConfig, CapabilitySet, CxCapability},
        integrity::{Fnv1aVerifier, IntegrityProof},
        transport::InMemoryTransport,
    };

    /// A buggy policy that always says "retry" — without the hard ceiling fix
    /// in br-bc6fa4, recover_once would loop forever and eventually overflow
    /// attempts: u32 in release builds (or panic in debug).
    struct AlwaysRetryPolicy;

    impl RecoveryPolicy for AlwaysRetryPolicy {
        fn should_retry(&self, _attempt: u32, _max_attempts: u32) -> bool {
            true
        }
    }

    /// A transport that always fails so the policy gets a chance to keep retrying.
    struct AlwaysFailingTransport;

    impl TransportLayer for AlwaysFailingTransport {
        fn send(
            &self,
            _artifact: EncodedArtifact,
            _config: &AsupersyncConfig,
        ) -> Result<crate::asupersync::transport::TransferReport, AsupersyncError> {
            Err(AsupersyncError::Transport(
                "always-failing send".to_string(),
            ))
        }
        fn receive(
            &self,
            _artifact_id: &str,
            _config: &AsupersyncConfig,
        ) -> Result<EncodedArtifact, AsupersyncError> {
            Err(AsupersyncError::Transport(
                "always-failing receive".to_string(),
            ))
        }
        fn required_capabilities(&self) -> CapabilitySet {
            CapabilitySet::for_capability(CxCapability::Io)
        }
    }

    struct CountingFailingTransport {
        receive_calls: Cell<u32>,
    }

    impl CountingFailingTransport {
        fn new() -> Self {
            Self {
                receive_calls: Cell::new(0),
            }
        }
    }

    impl TransportLayer for CountingFailingTransport {
        fn send(
            &self,
            _artifact: EncodedArtifact,
            _config: &AsupersyncConfig,
        ) -> Result<crate::asupersync::transport::TransferReport, AsupersyncError> {
            Err(AsupersyncError::Transport(
                "counting-failing send".to_string(),
            ))
        }
        fn receive(
            &self,
            _artifact_id: &str,
            _config: &AsupersyncConfig,
        ) -> Result<EncodedArtifact, AsupersyncError> {
            self.receive_calls
                .set(self.receive_calls.get().saturating_add(1));
            Err(AsupersyncError::Transport(
                "counting-failing receive".to_string(),
            ))
        }
        fn required_capabilities(&self) -> CapabilitySet {
            CapabilitySet::for_capability(CxCapability::Io)
        }
    }

    struct FailingVerifier;

    impl IntegrityVerifier for FailingVerifier {
        fn verify(
            &self,
            _artifact_id: &str,
            _bytes: &[u8],
            _expected_digest: &str,
        ) -> Result<IntegrityProof, AsupersyncError> {
            Err(AsupersyncError::IntegrityMismatch {
                artifact_id: "failing-verifier".to_string(),
                expected: "x".to_string(),
                observed: "y".to_string(),
            })
        }
    }

    fn fnv1a_hex_for_test(bytes: &[u8]) -> String {
        let mut hash = 0xcbf29ce484222325_u64;
        for byte in bytes {
            hash ^= u64::from(*byte);
            hash = hash.wrapping_mul(0x100000001b3);
        }
        format!("{hash:016x}")
    }

    #[test]
    fn recover_once_terminates_at_max_attempts_under_buggy_policy() {
        // Without the hard ceiling fix, this test would never return.
        let plan = RecoveryPlan {
            artifact_id: "test-artifact".to_string(),
            max_attempts: 5,
            deadline_unix_ms: 0,
        };
        let config = AsupersyncConfig::default()
            .with_capabilities(CapabilitySet::for_capability(CxCapability::Io));
        let result = recover_once(
            &PassthroughCodec,
            &AlwaysFailingTransport,
            &FailingVerifier,
            &AlwaysRetryPolicy,
            &config,
            &plan,
            "any-digest",
        );
        assert!(
            matches!(
                &result,
                Err(AsupersyncError::RecoveryExhausted {
                    artifact_id,
                    attempts,
                }) if artifact_id == "test-artifact" && *attempts == 5
            ),
            "expected RecoveryExhausted after exactly 5 attempts, got {result:?}"
        );
    }

    #[test]
    fn recover_once_zero_max_attempts_returns_configuration_error() {
        let plan = RecoveryPlan {
            artifact_id: "test".to_string(),
            max_attempts: 0,
            deadline_unix_ms: 0,
        };
        let config = AsupersyncConfig::default()
            .with_capabilities(CapabilitySet::for_capability(CxCapability::Io));
        let result = recover_once(
            &PassthroughCodec,
            &AlwaysFailingTransport,
            &FailingVerifier,
            &AlwaysRetryPolicy,
            &config,
            &plan,
            "x",
        );
        assert!(matches!(result, Err(AsupersyncError::Configuration(_))));
    }

    #[test]
    fn recover_once_expired_deadline_makes_zero_transport_attempts_ehn2c() {
        let transport = CountingFailingTransport::new();
        let plan = RecoveryPlan {
            artifact_id: "expired-artifact".to_string(),
            max_attempts: 3,
            deadline_unix_ms: 1,
        };
        let config = AsupersyncConfig::default()
            .with_capabilities(CapabilitySet::for_capability(CxCapability::Io));

        let result = recover_once(
            &PassthroughCodec,
            &transport,
            &FailingVerifier,
            &AlwaysRetryPolicy,
            &config,
            &plan,
            "any-digest",
        );

        assert!(
            matches!(
                &result,
                Err(AsupersyncError::RecoveryExhausted {
                    artifact_id,
                    attempts,
                }) if artifact_id == "expired-artifact" && *attempts == 0
            ),
            "expected deadline RecoveryExhausted, got {result:?}"
        );
        assert_eq!(
            transport.receive_calls.get(),
            0,
            "expired recovery plans must fail before transport.receive"
        );
    }

    #[test]
    fn recover_once_future_deadline_preserves_retry_budget_ehn2c() {
        let transport = CountingFailingTransport::new();
        let plan = RecoveryPlan {
            artifact_id: "future-artifact".to_string(),
            max_attempts: 2,
            deadline_unix_ms: current_unix_ms().saturating_add(60_000),
        };
        let config = AsupersyncConfig::default()
            .with_capabilities(CapabilitySet::for_capability(CxCapability::Io));

        let result = recover_once(
            &PassthroughCodec,
            &transport,
            &FailingVerifier,
            &AlwaysRetryPolicy,
            &config,
            &plan,
            "any-digest",
        );

        assert!(
            matches!(
                &result,
                Err(AsupersyncError::RecoveryExhausted {
                    artifact_id,
                    attempts,
                }) if artifact_id == "future-artifact" && *attempts == 2
            ),
            "expected retry-budget RecoveryExhausted, got {result:?}"
        );
        assert_eq!(transport.receive_calls.get(), 2);
    }

    #[test]
    fn recover_once_round_trips_real_codec_transport_and_verifier_2ryvf()
    -> Result<(), AsupersyncError> {
        let codec = PassthroughCodec;
        let transport = InMemoryTransport::new();
        let verifier = Fnv1aVerifier;
        let config = AsupersyncConfig::default().with_capabilities(
            CapabilitySet::for_capability(CxCapability::Io)
                .union(CapabilitySet::for_capability(CxCapability::Remote)),
        );
        let bytes = b"recoverable artifact payload".to_vec();
        let expected_digest = fnv1a_hex_for_test(&bytes);
        let payload = ArtifactPayload {
            artifact_id: "recoverable-artifact".to_string(),
            bytes,
            expected_digest: Some(expected_digest.clone()),
        };
        let encoded = codec.encode(&payload, &config)?;
        transport.send(encoded, &config)?;

        let plan = RecoveryPlan {
            artifact_id: payload.artifact_id.clone(),
            max_attempts: 3,
            deadline_unix_ms: 0,
        };
        let report = recover_once(
            &codec,
            &transport,
            &verifier,
            &ConservativeRecoveryPolicy,
            &config,
            &plan,
            &expected_digest,
        )?;

        assert_eq!(report.artifact_id, "recoverable-artifact");
        assert_eq!(report.attempts, 1);
        assert_eq!(report.outcome, RecoveryOutcome::Recovered);
        assert_eq!(report.transfer_status, TransferStatus::Completed);
        let Some(proof) = report.integrity else {
            return Err(AsupersyncError::IntegrityMismatch {
                artifact_id: "recoverable-artifact".to_string(),
                expected: expected_digest,
                observed: "<missing proof>".to_string(),
            });
        };
        assert!(proof.verified);
        assert_eq!(proof.algorithm, "fnv1a64");
        assert_eq!(proof.expected_digest, proof.observed_digest);
        Ok(())
    }
}