pacta-conformance 0.2.0

Backend-agnostic conformance suite for Pacta Registry implementations.
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
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
//! A backend-agnostic conformance suite for [`Registry`] implementations.
//!
//! The suite is generic over `Registry` and takes a constructor closure that
//! returns a seeded backend, so it defines no seeding trait: a backend runs the
//! suite from its own `#[cfg(test)]` module and keeps `pacta-conformance` a pure
//! dev-dependency. Time is driven entirely through the trait by passing controlled
//! [`Timestamp`] values, never a wall clock.

#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::fmt::Debug;

use pacta_contract::{Pact, Registry, Retainer, Timestamp};
use uuid::Uuid;

/// The lease duration, in milliseconds, the suite constructs every backend with.
pub const LEASE_MILLIS: u64 = 1000;

const DOCKET: &str = "conformance";

fn at(millis: u64) -> Timestamp {
    Timestamp::from_millis(millis)
}

fn a_pact_on(docket: &str) -> Pact {
    Pact::new(
        Uuid::new_v4(),
        docket.to_string(),
        "conformance".to_string(),
        Vec::new(),
    )
}

fn a_pact() -> Pact {
    a_pact_on(DOCKET)
}

/// Run the full conformance suite against a backend built by `make`.
///
/// `make(pacts, lease_millis)` must return a fresh registry seeded with `pacts`
/// and configured to lease claims for `lease_millis`. The suite calls it once per
/// scenario. A failing assertion panics, failing the calling test.
pub fn run<R, F>(make: F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    no_available_pact_returns_none(&make);
    unrequested_docket_is_not_claimed(&make);
    claim_returns_claim_with_lease(&make);
    held_pact_not_reclaimable_before_expiry(&make);
    expired_lease_lapses_and_reclaims_with_rotated_retainer(&make);
    stale_retainer_settle_rejected_after_reclaim(&make);
    late_fulfill_before_reclaim_succeeds(&make);
    fulfill_settles_and_pact_not_claimable(&make);
    breach_settles_terminally(&make);
    released_pact_withheld_until_reclaimable(&make);
    released_pact_reclaimable_at_its_instant(&make);
    immediate_reclaim_reclaims_like_lapse(&make);
    release_rotates_authority_from_prior_holder(&make);
    heartbeat_extends_lease_preventing_lapse(&make);
    heartbeat_on_lapsed_lease_rejected(&make);
    heartbeat_unknown_retainer_rejected(&make);
}

/// Async conformance: hold an [`AsyncRegistry`](pacta_contract::AsyncRegistry) backend to the
/// exact same scenarios as the sync suite.
///
/// The async runner reuses [`run`] rather than a duplicated scenario set: it adapts the async
/// backend into the sync [`Registry`] by driving each operation to completion, so sync and async
/// coverage cannot drift. This proves state-machine parity — the same bar the sync suite meets, which
/// itself exercises no concurrency. The at-most-once invariant under concurrent contention is a
/// separate, *portable* check (`run_async_contention`) that any async backend runs.
///
/// The adapter drives futures with a poll loop, so it fits backends whose futures make progress
/// without an external reactor (the in-memory reference backend); a real-reactor durable backend
/// proves itself against the same scenarios through its own async harness.
#[cfg(feature = "async")]
mod async_runner {
    use core::future::Future;

    use pacta_contract::AsyncRegistry;
    use pacta_contract::{Claim, Pact, Registry, Retainer, Timestamp, Transition};

    /// Drive a future to completion on the current thread with a no-op waker. Correct for futures
    /// that make progress without an external reactor; keeps the crate dependency- and unsafe-free.
    fn block_on<F: Future>(future: F) -> F::Output {
        use core::task::{Context, Poll};

        let mut future = core::pin::pin!(future);
        let mut cx = Context::from_waker(core::task::Waker::noop());
        loop {
            match future.as_mut().poll(&mut cx) {
                Poll::Ready(output) => return output,
                Poll::Pending => core::hint::spin_loop(),
            }
        }
    }

    /// Adapts an [`AsyncRegistry`] into the sync [`Registry`] by blocking on each primitive, so the
    /// async binding runs the sync suite verbatim. Because both bindings share one transition port,
    /// the adapter forwards only the primitives (`claim`, `lease_millis`, `apply`); the four
    /// transition ops come from the sync trait's default methods over `apply`.
    struct BlockOn<R>(R);

    impl<R: AsyncRegistry> Registry for BlockOn<R> {
        type Error = R::Error;

        fn claim(&self, dockets: &[&str], now: Timestamp) -> Result<Option<Claim>, Self::Error> {
            block_on(self.0.claim(dockets, now))
        }

        fn lease_millis(&self) -> u64 {
            self.0.lease_millis()
        }

        fn apply(
            &self,
            retainer: &Retainer,
            transition: &Transition<'_>,
        ) -> Result<(), Self::Error> {
            block_on(self.0.apply(retainer, transition))
        }
    }

    /// Run the full conformance suite against an async backend built by `make`.
    ///
    /// `make(pacts, lease_millis)` returns a fresh async registry seeded with `pacts`, exactly as
    /// [`run`](crate::run) expects for the sync binding.
    pub fn run_async<R, F>(make: F)
    where
        R: AsyncRegistry,
        R::Error: core::fmt::Debug,
        F: Fn(Vec<Pact>, u64) -> R,
    {
        crate::run(move |pacts, lease_millis| BlockOn(make(pacts, lease_millis)));
    }

    /// Verify the at-most-once invariant under concurrent contention, for any async backend.
    ///
    /// Two workers race a settlement on a single claimed pact; the transition port must apply it at
    /// most once, so exactly one worker succeeds and the other resolves to a not-current-holder. The
    /// check asserts this through the public op (never inspecting the backend's concurrency
    /// mechanism), so it holds for a lock, a transaction, or a compare-and-set backend alike.
    ///
    /// Parallelism is real (OS threads); each thread drives its future to completion with
    /// `block_on`, so a future never migrates across threads and **no `Send` bound on the future is
    /// required** — the suite pulls no async runtime.
    pub fn run_async_contention<R, F>(make: F)
    where
        R: AsyncRegistry + 'static,
        R::Error: core::fmt::Debug + Send,
        F: Fn(Vec<Pact>, u64) -> R,
    {
        use std::sync::Arc;

        // Enough rounds that an interleaving loading the same state in both threads is hit, and a
        // broken (non-atomic) `apply` would overwhelmingly double-apply on some round.
        for _ in 0..2000 {
            let reg = Arc::new(make(vec![crate::a_pact()], crate::LEASE_MILLIS));
            let retainer = block_on(reg.claim(&[crate::DOCKET], crate::at(0)))
                .expect("claim should not error")
                .expect("a pact should be claimable")
                .retainer;

            let a = {
                let reg = Arc::clone(&reg);
                let retainer = retainer.clone();
                std::thread::spawn(move || block_on(reg.fulfill(&retainer)))
            };
            let b = {
                let reg = Arc::clone(&reg);
                let retainer = retainer.clone();
                std::thread::spawn(move || block_on(reg.fulfill(&retainer)))
            };
            let (ra, rb) = (a.join().unwrap(), b.join().unwrap());

            let winners = [ra.is_ok(), rb.is_ok()]
                .into_iter()
                .filter(|&ok| ok)
                .count();
            assert_eq!(
                winners, 1,
                "settlement must apply exactly once: a={ra:?} b={rb:?}"
            );
            assert!(
                block_on(reg.claim(&[crate::DOCKET], crate::at(0)))
                    .expect("claim should not error")
                    .is_none(),
                "a settled pact must not be claimable again"
            );
        }
    }
}

#[cfg(feature = "async")]
pub use async_runner::{run_async, run_async_contention};

fn no_available_pact_returns_none<R, F>(make: &F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    let registry = make(Vec::new(), LEASE_MILLIS);
    assert!(
        registry
            .claim(&[DOCKET], at(0))
            .expect("claim should not error")
            .is_none(),
        "an empty registry must yield no claim"
    );
}

fn unrequested_docket_is_not_claimed<R, F>(make: &F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    let registry = make(vec![a_pact_on("other")], LEASE_MILLIS);
    assert!(
        registry
            .claim(&[DOCKET], at(0))
            .expect("claim should not error")
            .is_none(),
        "a pact on an unrequested docket must not be claimed"
    );
    assert!(
        registry
            .claim(&["other"], at(0))
            .expect("claim should not error")
            .is_some(),
        "the same pact must be claimable from its own docket"
    );
}

fn claim_returns_claim_with_lease<R, F>(make: &F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    let registry = make(vec![a_pact()], LEASE_MILLIS);
    let claim = registry
        .claim(&[DOCKET], at(100))
        .expect("claim should not error")
        .expect("a pact should be claimable");
    assert_eq!(
        claim.lease_expiry,
        at(100 + LEASE_MILLIS),
        "lease expiry must be now plus the lease duration"
    );
}

fn held_pact_not_reclaimable_before_expiry<R, F>(make: &F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    let registry = make(vec![a_pact()], LEASE_MILLIS);
    let _first = registry
        .claim(&[DOCKET], at(0))
        .expect("claim should not error")
        .expect("a pact should be claimable");
    assert!(
        registry
            .claim(&[DOCKET], at(500))
            .expect("claim should not error")
            .is_none(),
        "a held pact must not be reclaimable before its lease expires"
    );
}

fn expired_lease_lapses_and_reclaims_with_rotated_retainer<R, F>(make: &F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    let registry = make(vec![a_pact()], LEASE_MILLIS);
    let first = registry
        .claim(&[DOCKET], at(0))
        .expect("claim should not error")
        .expect("a pact should be claimable");
    let second = registry
        .claim(&[DOCKET], at(1500))
        .expect("claim should not error")
        .expect("an expired pact should be reclaimable through the claim path");
    assert_ne!(
        first.retainer.id(),
        second.retainer.id(),
        "reclaiming a lapsed pact must rotate the retainer"
    );
    assert_eq!(
        second.lease_expiry,
        at(1500 + LEASE_MILLIS),
        "the reclaim must set a fresh lease"
    );
}

fn stale_retainer_settle_rejected_after_reclaim<R, F>(make: &F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    let registry = make(vec![a_pact()], LEASE_MILLIS);
    let first = registry
        .claim(&[DOCKET], at(0))
        .expect("claim should not error")
        .expect("a pact should be claimable");
    let _second = registry
        .claim(&[DOCKET], at(1500))
        .expect("claim should not error")
        .expect("an expired pact should be reclaimable");
    assert!(
        registry.fulfill(&first.retainer).is_err(),
        "the prior holder must not settle after a reclaim (at-least-once safety)"
    );
}

fn late_fulfill_before_reclaim_succeeds<R, F>(make: &F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    let registry = make(vec![a_pact()], LEASE_MILLIS);
    let claim = registry
        .claim(&[DOCKET], at(0))
        .expect("claim should not error")
        .expect("a pact should be claimable");
    // The lease has expired but nobody reclaimed; the holder's retainer still
    // matches, so a late fulfill of genuinely-done work settles. No time involved.
    assert!(
        registry.fulfill(&claim.retainer).is_ok(),
        "a late fulfill before any reclaim must settle"
    );
    assert!(
        registry
            .claim(&[DOCKET], at(9999))
            .expect("claim should not error")
            .is_none(),
        "a settled pact must not be claimable"
    );
}

fn fulfill_settles_and_pact_not_claimable<R, F>(make: &F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    let registry = make(vec![a_pact()], LEASE_MILLIS);
    let claim = registry
        .claim(&[DOCKET], at(0))
        .expect("claim should not error")
        .expect("a pact should be claimable");
    registry
        .fulfill(&claim.retainer)
        .expect("fulfill should settle");
    assert!(
        registry
            .claim(&[DOCKET], at(0))
            .expect("claim should not error")
            .is_none(),
        "a fulfilled pact must not be claimable"
    );
}

fn breach_settles_terminally<R, F>(make: &F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    let registry = make(vec![a_pact()], LEASE_MILLIS);
    let claim = registry
        .claim(&[DOCKET], at(0))
        .expect("claim should not error")
        .expect("a pact should be claimable");
    registry
        .breach(&claim.retainer)
        .expect("breach should settle");
    assert!(
        registry
            .claim(&[DOCKET], at(5000))
            .expect("claim should not error")
            .is_none(),
        "a breached pact must not be claimable, even after its lease would have expired"
    );
}

fn released_pact_withheld_until_reclaimable<R, F>(make: &F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    let registry = make(vec![a_pact()], LEASE_MILLIS);
    let claim = registry
        .claim(&[DOCKET], at(0))
        .expect("claim should not error")
        .expect("a pact should be claimable");
    registry
        .release(&claim.retainer, at(5000))
        .expect("release should succeed for the current holder");
    // at(3000) is past the original lease (1000) — a lapse would make it claimable —
    // but the reclaimable instant (5000) is later, so release must withhold it.
    assert!(
        registry
            .claim(&[DOCKET], at(3000))
            .expect("claim should not error")
            .is_none(),
        "a released pact must not be claimable before its reclaimable instant"
    );
}

fn released_pact_reclaimable_at_its_instant<R, F>(make: &F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    let registry = make(vec![a_pact()], LEASE_MILLIS);
    let first = registry
        .claim(&[DOCKET], at(0))
        .expect("claim should not error")
        .expect("a pact should be claimable");
    registry
        .release(&first.retainer, at(5000))
        .expect("release should succeed");
    let second = registry
        .claim(&[DOCKET], at(5000))
        .expect("claim should not error")
        .expect("a released pact must be claimable at its reclaimable instant");
    assert_ne!(
        first.retainer.id(),
        second.retainer.id(),
        "reclaiming a released pact must rotate the retainer"
    );
}

fn immediate_reclaim_reclaims_like_lapse<R, F>(make: &F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    let registry = make(vec![a_pact()], LEASE_MILLIS);
    let claim = registry
        .claim(&[DOCKET], at(0))
        .expect("claim should not error")
        .expect("a pact should be claimable");
    registry
        .release(&claim.retainer, at(0))
        .expect("release with an immediate reclaim should succeed");
    assert!(
        registry
            .claim(&[DOCKET], at(0))
            .expect("claim should not error")
            .is_some(),
        "an immediate reclaim must make the pact claimable at once, as a voluntary lapse"
    );
}

fn release_rotates_authority_from_prior_holder<R, F>(make: &F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    let registry = make(vec![a_pact()], LEASE_MILLIS);
    let claim = registry
        .claim(&[DOCKET], at(0))
        .expect("claim should not error")
        .expect("a pact should be claimable");
    registry
        .release(&claim.retainer, at(0))
        .expect("release should succeed");
    assert!(
        registry.fulfill(&claim.retainer).is_err(),
        "the prior holder must not settle after releasing (release rotates authority)"
    );
}

fn heartbeat_extends_lease_preventing_lapse<R, F>(make: &F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    let registry = make(vec![a_pact()], LEASE_MILLIS);
    let claim = registry
        .claim(&[DOCKET], at(0))
        .expect("claim should not error")
        .expect("a pact should be claimable");
    registry
        .heartbeat(&claim.retainer, at(800))
        .expect("an in-window heartbeat should extend the lease");
    // The original lease (expiry 1000) would have lapsed by 1500, but the
    // heartbeat pushed expiry to 1800, so the pact is still held.
    assert!(
        registry
            .claim(&[DOCKET], at(1500))
            .expect("claim should not error")
            .is_none(),
        "a heartbeat within the window must prevent a lapse"
    );
}

fn heartbeat_on_lapsed_lease_rejected<R, F>(make: &F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    let registry = make(vec![a_pact()], LEASE_MILLIS);
    let claim = registry
        .claim(&[DOCKET], at(0))
        .expect("claim should not error")
        .expect("a pact should be claimable");
    assert!(
        registry.heartbeat(&claim.retainer, at(1200)).is_err(),
        "a heartbeat after the lease expired must be rejected, forcing a re-claim"
    );
}

fn heartbeat_unknown_retainer_rejected<R, F>(make: &F)
where
    R: Registry,
    R::Error: Debug,
    F: Fn(Vec<Pact>, u64) -> R,
{
    let registry = make(vec![a_pact()], LEASE_MILLIS);
    let _claim = registry
        .claim(&[DOCKET], at(0))
        .expect("claim should not error")
        .expect("a pact should be claimable");
    let unknown = Retainer::new(Uuid::new_v4());
    assert!(
        registry.heartbeat(&unknown, at(100)).is_err(),
        "a heartbeat with an unissued retainer must be rejected"
    );
}