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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Copyright (c) 2026 2youg1 and the sprawling contributors
//! Which account of a provider a request goes out on, and after a failure
//! whether it goes out again on the same account, moves to another, or
//! stops.
//! The part `crates/kernel/spec/AccountRecovery.lean` specifies this
//! module (`crates/kernel/Spec.lean` ยง8-86, kernel D54 and D55).
//!
//! **One round is one logical request**, from its first send to an
//! answer, a stop or a `Halt`. Both drivers - the model path in the
//! runtime and the `web_search` tool in accounting - only carry out the
//! [`AccountStep`] a round gives them, so neither grows a retry loop or
//! an account choice of its own. [`AccountRound::next`] answers and
//! changes nothing; [`AccountRound::apply`] changes and answers nothing.
//!
//! A round is neither recorded nor persisted: a restarted process opens
//! the next round from the binding the ledger rebuilds.
use std::collections::BTreeSet;
use crate::error::{AccountDisposition, AxError, Retry};
use crate::retries::Retries;
use crate::tool::ServerLabel;
/// How many more times one account is asked the same request before the
/// round moves on. A person picks one or two on the provider's advanced
/// form; it is read only where the roster has two accounts or more. On
/// the wire and in the ledger `"one"` or `"two"`; the default lives in
/// gateway's `EndpointTuning::DEFAULTS` alone.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum AccountRetries {
One,
Two,
}
impl AccountRetries {
const fn count(self) -> u32 {
match self {
AccountRetries::One => 1,
AccountRetries::Two => 2,
}
}
}
/// The accounts a round can send on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Roster {
/// A registration with one credential, or with one listed account:
/// there is no second account, so a failure is handled as it was
/// before accounts existed - `retry` alone decides, up to the
/// person's ceiling.
Single,
/// Two accounts or more. The order is the priority.
Several {
accounts: Vec<ServerLabel>,
retries: AccountRetries,
},
}
/// Why a round stopped.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RoundEnd {
/// The request itself is wrong, or the store every account shares
/// failed: sent again anywhere it would fail the same way.
Refused,
/// The answer was lost on the last account's last allowed send, and
/// whether its effect landed is not known.
Unknown,
/// The person's ceiling on retries was reached.
Cap,
/// No account is left to switch to.
Exhausted,
}
/// What the driver does after one failed send.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AccountStep {
/// Send the same request again on the same account, after the
/// driver's back-off.
Resend,
/// Send the same request on this account at once.
Switch { to: ServerLabel },
/// Send nothing more; hand the failure on.
Stop { why: RoundEnd },
}
/// One round's state. Every field is private: a round moves only through
/// [`AccountRound::apply`] and [`AccountRound::repaired`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountRound {
roster: Roster,
/// The accounts whose reference could be redeemed when the round
/// opened (D55); asked once, never re-read mid-round.
usable: BTreeSet<ServerLabel>,
cap: Retries,
current: Option<ServerLabel>,
/// The accounts this round has sent on.
tried: BTreeSet<ServerLabel>,
/// Sends on the current account.
here: u32,
/// Sends in this round.
total: u32,
}
impl AccountRound {
/// Opens a round before its first send, and counts that send. The
/// account `held` - the Session's binding on the model path, absent
/// for `web_search` - opens the round while it is listed and
/// redeemable; otherwise the first redeemable account in roster
/// order does.
///
/// # Errors
/// [`RoundEnd::Exhausted`] when no listed account is redeemable: the
/// round sends nothing.
pub fn start(
roster: Roster,
usable: BTreeSet<ServerLabel>,
cap: Retries,
held: Option<ServerLabel>,
) -> Result<AccountRound, RoundEnd> {
let current = match &roster {
Roster::Single => None,
Roster::Several { accounts, .. } => {
let opening = held
.filter(|account| accounts.contains(account) && usable.contains(account))
.or_else(|| {
accounts
.iter()
.find(|account| usable.contains(*account))
.cloned()
});
Some(opening.ok_or(RoundEnd::Exhausted)?)
}
};
Ok(AccountRound {
roster,
usable,
cap,
tried: current.iter().cloned().collect(),
current,
here: 1,
total: 1,
})
}
/// The account the next send goes out on; `None` for a single-account
/// roster, which names none.
#[must_use]
pub fn current(&self) -> Option<&ServerLabel> {
self.current.as_ref()
}
/// What to do after `failure`, read from its `retry` and its
/// `account` disposition alone (D54).
#[must_use]
pub fn next(&self, failure: &AxError) -> AccountStep {
match &self.roster {
Roster::Single => match failure.retry() {
Retry::No => AccountStep::Stop {
why: RoundEnd::Refused,
},
Retry::Yes | Retry::Unknown => self.resend(),
},
Roster::Several { retries, .. } => {
let spare = self.here <= retries.count();
match (failure.retry(), failure.account()) {
(Retry::Unknown, AccountDisposition::Keep | AccountDisposition::Advance) => {
if spare {
self.resend()
} else {
AccountStep::Stop {
why: RoundEnd::Unknown,
}
}
}
(Retry::Yes | Retry::No, AccountDisposition::Advance) => self.switch(),
(Retry::Yes, AccountDisposition::Keep) => {
if spare {
self.resend()
} else {
self.switch()
}
}
(Retry::No, AccountDisposition::Keep) => AccountStep::Stop {
why: RoundEnd::Refused,
},
}
}
}
}
/// The round after the driver carried out `step`. `Stop` changes
/// nothing. The counts saturate rather than wrap: a single-account
/// round under `UntilHalted` resends until a `Halt`, and a count that
/// wrapped would read as a fresh account's spare sends.
#[must_use]
pub fn apply(self, step: &AccountStep) -> AccountRound {
match step {
AccountStep::Resend => AccountRound {
here: self.here.saturating_add(1),
total: self.total.saturating_add(1),
..self
},
AccountStep::Switch { to } => {
let mut tried = self.tried;
tried.insert(to.clone());
AccountRound {
current: Some(to.clone()),
tried,
here: 1,
total: self.total.saturating_add(1),
..self
}
}
AccountStep::Stop { .. } => self,
}
}
/// Whether the repair stage may send the request again through the
/// blocking door. With several accounts that send is one more on the
/// current account, so it needs the account's spare sends and the
/// person's ceiling; a single-account roster is let through as
/// before.
#[must_use]
pub fn admits_repair(&self) -> bool {
match &self.roster {
Roster::Single => true,
Roster::Several { retries, .. } => {
self.here <= retries.count() && admits(self.cap, self.total)
}
}
}
/// The round after the repair stage sent again: one more send on the
/// current account with several accounts, uncounted with one.
#[must_use]
pub fn repaired(self) -> AccountRound {
match self.roster {
Roster::Single => self,
Roster::Several { .. } => self.apply(&AccountStep::Resend),
}
}
fn resend(&self) -> AccountStep {
if admits(self.cap, self.total) {
AccountStep::Resend
} else {
AccountStep::Stop { why: RoundEnd::Cap }
}
}
/// Switches to the first listed account that is redeemable and not
/// yet tried this round. Running out is said before the ceiling is,
/// because "no account is left" points at the way out (D54, rule 7).
fn switch(&self) -> AccountStep {
let Roster::Several { accounts, .. } = &self.roster else {
return AccountStep::Stop {
why: RoundEnd::Exhausted,
};
};
match accounts
.iter()
.find(|account| self.usable.contains(*account) && !self.tried.contains(*account))
{
None => AccountStep::Stop {
why: RoundEnd::Exhausted,
},
Some(to) if admits(self.cap, self.total) => AccountStep::Switch { to: to.clone() },
Some(_) => AccountStep::Stop { why: RoundEnd::Cap },
}
}
}
/// Whether the person's ceiling lets one more send follow `sent` sends.
/// `AtMost(0)` sends once and stops, as the watchdog has always read it.
fn admits(cap: Retries, sent: u32) -> bool {
match cap {
Retries::UntilHalted => true,
Retries::AtMost(retries) => sent <= retries,
}
}
#[cfg(test)]
#[allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing,
clippy::arithmetic_side_effects,
reason = "test code"
)]
mod tests {
use std::collections::BTreeMap;
use proptest::prelude::*;
use super::*;
use crate::error::AxCode;
/// What a driver meets in a round: the four failures the error
/// builders can spell (`Advance` only ever comes with `Retry::No`,
/// kernel D53), and the repair stage wanting to send again.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Event {
Busy,
Unusable,
Refused,
Lost,
Repair,
}
fn failure(event: Event) -> Option<AxError> {
let draft = AxError::failure(AxCode::Provider, "call model", "account");
match event {
Event::Busy => Some(draft.retriable().with_recovery("r")),
Event::Unusable => Some(draft.account_unusable().with_recovery("r")),
Event::Refused => Some(draft.with_recovery("r")),
Event::Lost => Some(draft.effect_unknown().with_recovery("r")),
Event::Repair => None,
}
}
fn label(name: &str) -> ServerLabel {
ServerLabel::parse(name).unwrap()
}
fn several(names: &[&str], retries: AccountRetries) -> Roster {
Roster::Several {
accounts: names.iter().map(|name| label(name)).collect(),
retries,
}
}
/// Lean's `AccountRound.decisions`: a failure asks `next` and stops
/// on `Stop`; a repair asks `admits_repair`, and is `None` when it is
/// not let through.
fn decisions(mut round: AccountRound, events: &[Event]) -> Vec<(Event, Option<AccountStep>)> {
let mut out = Vec::new();
for &event in events {
match failure(event) {
None if round.admits_repair() => {
out.push((event, Some(AccountStep::Resend)));
round = round.repaired();
}
None => out.push((event, None)),
Some(err) => {
let step = round.next(&err);
out.push((event, Some(step.clone())));
if let AccountStep::Stop { .. } = step {
break;
}
round = round.apply(&step);
}
}
}
out
}
type Decided = Option<(Option<ServerLabel>, Vec<(Event, Option<AccountStep>)>)>;
/// Lean's `vector`: open the round, then walk the events.
fn vector(
roster: Roster,
missing: &[&str],
cap: Retries,
held: Option<&str>,
events: &[Event],
) -> Decided {
let usable = match &roster {
Roster::Single => BTreeSet::new(),
Roster::Several { accounts, .. } => accounts
.iter()
.filter(|account| !missing.contains(&account.as_str()))
.cloned()
.collect(),
};
let round = AccountRound::start(roster, usable, cap, held.map(label)).ok()?;
Some((round.current().cloned(), decisions(round, events)))
}
fn resend() -> Option<AccountStep> {
Some(AccountStep::Resend)
}
fn switch(to: &str) -> Option<AccountStep> {
Some(AccountStep::Switch { to: label(to) })
}
fn stop(why: RoundEnd) -> Option<AccountStep> {
Some(AccountStep::Stop { why })
}
/// The trace vectors `crates/kernel/spec/AccountRecovery.lean` prints
/// with `#eval`, in its order, each with the answer Lean gave, and
/// the `decide` example after them.
#[test]
fn the_lean_trace_vectors_replay_one_by_one() {
use Event::{Busy, Lost, Refused, Repair, Unusable};
let two = || several(&["a", "b"], AccountRetries::Two);
let a = Some(label("a"));
let b = Some(label("b"));
let found = [
vector(
two(),
&[],
Retries::UntilHalted,
None,
&[Busy, Busy, Busy, Busy],
),
vector(
two(),
&[],
Retries::UntilHalted,
None,
&[Unusable, Unusable],
),
vector(two(), &[], Retries::UntilHalted, None, &[Refused]),
vector(two(), &[], Retries::UntilHalted, None, &[Lost, Lost, Lost]),
vector(two(), &[], Retries::AtMost(1), None, &[Busy, Busy]),
vector(
several(&["a", "b", "c"], AccountRetries::One),
&["b"],
Retries::UntilHalted,
Some("c"),
&[Busy, Busy, Unusable],
),
vector(
several(&["a", "b"], AccountRetries::One),
&[],
Retries::UntilHalted,
Some("b"),
&[Repair, Busy, Repair],
),
vector(two(), &["a", "b"], Retries::UntilHalted, None, &[]),
vector(
Roster::Single,
&[],
Retries::AtMost(2),
None,
&[Busy, Lost, Busy],
),
vector(
Roster::Single,
&[],
Retries::UntilHalted,
None,
&[Repair, Unusable],
),
vector(two(), &[], Retries::UntilHalted, Some("b"), &[Busy]),
];
let lean: [Decided; 11] = [
Some((
a.clone(),
vec![
(Busy, resend()),
(Busy, resend()),
(Busy, switch("b")),
(Busy, resend()),
],
)),
Some((
a.clone(),
vec![
(Unusable, switch("b")),
(Unusable, stop(RoundEnd::Exhausted)),
],
)),
Some((a.clone(), vec![(Refused, stop(RoundEnd::Refused))])),
Some((
a.clone(),
vec![
(Lost, resend()),
(Lost, resend()),
(Lost, stop(RoundEnd::Unknown)),
],
)),
Some((a, vec![(Busy, resend()), (Busy, stop(RoundEnd::Cap))])),
Some((
Some(label("c")),
vec![
(Busy, resend()),
(Busy, switch("a")),
(Unusable, stop(RoundEnd::Exhausted)),
],
)),
Some((
b.clone(),
vec![(Repair, resend()), (Busy, switch("a")), (Repair, resend())],
)),
None,
Some((
None,
vec![
(Busy, resend()),
(Lost, resend()),
(Busy, stop(RoundEnd::Cap)),
],
)),
Some((
None,
vec![(Repair, resend()), (Unusable, stop(RoundEnd::Refused))],
)),
Some((b, vec![(Busy, resend())])),
];
assert_eq!(found, lean);
}
fn switched(step: &AccountStep) -> bool {
matches!(step, AccountStep::Switch { .. })
}
fn event() -> impl Strategy<Value = Event> {
prop_oneof![
Just(Event::Busy),
Just(Event::Unusable),
Just(Event::Refused),
Just(Event::Lost),
Just(Event::Repair),
]
}
fn cap() -> impl Strategy<Value = Retries> {
prop_oneof![
Just(Retries::UntilHalted),
(0u32..8).prop_map(Retries::AtMost)
]
}
/// Five names a roster draws from, and one it never lists, so a held
/// account can be one the person removed.
const NAMES: [&str; 6] = ["a", "b", "c", "d", "e", "z"];
proptest! {
/// The quantified theorems of `crates/kernel/spec/AccountRecovery.lean`
/// on any roster of two to five accounts, any redeemable subset,
/// any ceiling, any held account (listed or not) and any trace:
/// `a_request_error_is_never_sent_again`,
/// `an_unusable_account_is_never_asked_again`,
/// `an_unknown_effect_never_switches`,
/// `sends_on_one_account_stay_within_the_budget`,
/// `a_round_visits_each_account_once`, `the_cap_bounds_every_round`,
/// `a_held_account_opens_the_round` and
/// `a_roster_with_nothing_redeemable_sends_nothing`. The sends are
/// counted here from the steps the driver carries out, not read
/// from the round.
#[test]
fn every_round_keeps_the_lean_properties(
listed in 2usize..=5,
missing in proptest::collection::vec(any::<bool>(), 5),
two in any::<bool>(),
cap in cap(),
held in proptest::option::of(0usize..6),
events in proptest::collection::vec(event(), 0..40),
) {
let accounts: Vec<ServerLabel> = NAMES[..listed].iter().map(|name| label(name)).collect();
let usable: BTreeSet<ServerLabel> = accounts
.iter()
.zip(&missing)
.filter(|(_, gone)| !**gone)
.map(|(account, _)| account.clone())
.collect();
let retries = if two { AccountRetries::Two } else { AccountRetries::One };
let budget = if two { 3 } else { 2 };
let held = held.map(|at| label(NAMES[at]));
let opened = AccountRound::start(
Roster::Several { accounts: accounts.clone(), retries },
usable.clone(),
cap,
held.clone(),
);
if usable.is_empty() {
prop_assert_eq!(opened, Err(RoundEnd::Exhausted));
return Ok(());
}
let mut round = opened.unwrap();
let first = held
.filter(|account| usable.contains(account))
.or_else(|| accounts.iter().find(|account| usable.contains(*account)).cloned());
prop_assert_eq!(round.current().cloned(), first.clone());
let mut on = first.unwrap();
let mut visited = vec![on.clone()];
let mut sends = BTreeMap::from([(on.clone(), 1u32)]);
let mut total = 1u32;
for event in events {
let Some(err) = failure(event) else {
if round.admits_repair() {
*sends.get_mut(&on).unwrap() += 1;
total += 1;
round = round.repaired();
}
continue;
};
let step = round.next(&err);
match event {
Event::Refused => {
prop_assert_eq!(&step, &AccountStep::Stop { why: RoundEnd::Refused });
}
Event::Unusable => prop_assert_ne!(&step, &AccountStep::Resend),
Event::Lost => prop_assert_ne!(switched(&step), true),
Event::Busy | Event::Repair => {}
}
match &step {
AccountStep::Resend => {
*sends.get_mut(&on).unwrap() += 1;
}
AccountStep::Switch { to } => {
prop_assert!(
usable.contains(to) && !visited.contains(to),
"{to} was tried already or is not redeemable"
);
visited.push(to.clone());
sends.insert(to.clone(), 1);
on = to.clone();
}
AccountStep::Stop { .. } => break,
}
total += 1;
round = round.apply(&step);
prop_assert_eq!(round.current(), Some(&on));
}
prop_assert!(sends.values().all(|&sent| sent <= budget), "{sends:?} over {budget}");
prop_assert!(total <= u32::try_from(listed).unwrap() * budget);
if let Retries::AtMost(retries) = cap {
prop_assert!(total <= retries + 1, "{total} sends under AtMost({retries})");
}
}
/// A single-account roster reads `retry` alone
/// (`a_single_account_ignores_the_disposition`): it never switches,
/// a refusal stops it whether or not it says to switch, the repair
/// stage is always let through uncounted, and the person's ceiling
/// bounds its sends.
#[test]
fn a_single_account_round_reads_retry_alone(
cap in cap(),
events in proptest::collection::vec(event(), 0..40),
) {
let mut round = AccountRound::start(Roster::Single, BTreeSet::new(), cap, None).unwrap();
prop_assert_eq!(round.current(), None);
let mut total = 1u32;
for event in events {
let Some(err) = failure(event) else {
prop_assert!(round.admits_repair());
round = round.repaired();
continue;
};
let step = round.next(&err);
match event {
Event::Refused | Event::Unusable => {
prop_assert_eq!(&step, &AccountStep::Stop { why: RoundEnd::Refused });
}
Event::Busy | Event::Lost | Event::Repair => {
prop_assert_ne!(switched(&step), true);
}
}
if let AccountStep::Stop { .. } = step {
break;
}
total += 1;
round = round.apply(&step);
}
if let Retries::AtMost(retries) = cap {
prop_assert!(total <= retries + 1);
}
}
}
}