sprawling-kernel 0.0.12

Every decision of a sprawling city - addresses, events, gates, plans and errors - with nothing that touches a disk.
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
// 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

//! AxError: the one error shape of the whole city, and ErrorDraft, the
//! only way to reach it.
//! The part `crates/kernel/spec/Error.lean` specifies this module with the
//! rest of `kernel::error`.

use serde::{Deserialize, Serialize};

use super::code::AxCode;
use super::provider::{AccountDisposition, ProviderFailureKind};
use super::refusal::GateRefusal;

/// The unified error shape: seven wire fields and two that are left out
/// when absent, serialized in declaration order (determinism rule 6).
/// The model is the recovery subject: `nearby` and `recovery` must hold
/// directly executable information, not apologies.
///
/// Everything but `code` sits behind one Box so the type stays cheap in
/// every seam's return slot (`result_large_err`); serde flatten keeps the
/// wire shape flat and the field order unchanged.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
#[error("{code}: cannot {} on {}", detail.action, detail.subject)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AxError {
    code: AxCode,
    #[serde(flatten)]
    detail: Box<ErrorDetail>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
struct ErrorDetail {
    action: String,
    subject: String,
    nearby: Vec<String>,
    recovery: String,
    #[serde(alias = "retriable")]
    retry: Retry,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    retry_after_ms: Option<u64>,
    #[serde(skip_serializing_if = "AccountDisposition::is_keep", default)]
    account: AccountDisposition,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    gate: Option<GateRefusal>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    provider: Option<ProviderFailureKind>,
}

/// Whether the same request may go out again, said together with
/// whether its effect already landed. On the wire `"yes"`, `"no"` or
/// `"unknown"`; a ledger record written as `retriable: true/false`
/// reads as `Yes`/`No`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum Retry {
    /// The effect did not land, and the same request may succeed later.
    Yes,
    /// The same request would fail the same way again.
    No,
    /// The request went out and its answer was lost: whether its effect
    /// landed is not known, so only a caller who knows the action is
    /// idempotent sends it again.
    Unknown,
}

impl<'de> Deserialize<'de> for Retry {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Spelling {
            Word(String),
            Flag(bool),
        }
        match Spelling::deserialize(deserializer)? {
            Spelling::Flag(true) => Ok(Retry::Yes),
            Spelling::Flag(false) => Ok(Retry::No),
            Spelling::Word(word) => match word.as_str() {
                "yes" => Ok(Retry::Yes),
                "no" => Ok(Retry::No),
                "unknown" => Ok(Retry::Unknown),
                other => Err(serde::de::Error::unknown_variant(
                    other,
                    &["yes", "no", "unknown"],
                )),
            },
        }
    }
}

/// An error that still owes the reader its recovery sentence.
///
/// Both constructors return this rather than an [`AxError`], and
/// [`ErrorDraft::with_recovery`] is the only way across, so a failure that
/// never says what to do next cannot be spelled. Shaping happens here;
/// an `AxError` is finished the moment it exists.
#[derive(Debug, Clone, PartialEq, Eq)]
#[must_use = "an ErrorDraft becomes an AxError only through with_recovery"]
pub struct ErrorDraft {
    pending: AxError,
}

impl AxError {
    /// Non-gate failure. `retry` starts `No` (fail-closed) and
    /// `nearby` starts empty; both grow on the draft.
    pub fn failure(
        code: AxCode,
        action: impl Into<String>,
        subject: impl Into<String>,
    ) -> ErrorDraft {
        ErrorDraft {
            pending: AxError {
                code,
                detail: Box::new(ErrorDetail {
                    action: action.into(),
                    subject: subject.into(),
                    nearby: Vec::new(),
                    recovery: String::new(),
                    retry: Retry::No,
                    retry_after_ms: None,
                    account: AccountDisposition::Keep,
                    gate: None,
                    provider: None,
                }),
            },
        }
    }

    /// Gate refusal: the only constructor that sets the three mandatory
    /// parts. Gate-carrier codes must come through here (kernel::gate is
    /// their sole producer).
    pub fn refusal(
        code: AxCode,
        action: impl Into<String>,
        subject: impl Into<String>,
        gate: GateRefusal,
    ) -> ErrorDraft {
        let mut draft = AxError::failure(code, action, subject);
        draft.pending.detail.gate = Some(gate);
        draft
    }

    /// An `E_PROVIDER` error that names the kind of failure a model
    /// call met. `retry` starts `No` like any failure: whether the
    /// request may go out again is decided by the gateway's
    /// `ProviderFailure::retry`, which sees more than the kind does.
    pub fn provider(
        kind: ProviderFailureKind,
        action: impl Into<String>,
        subject: impl Into<String>,
    ) -> ErrorDraft {
        let mut draft = AxError::failure(AxCode::Provider, action, subject);
        draft.pending.detail.provider = Some(kind);
        draft
    }

    pub fn code(&self) -> &AxCode {
        &self.code
    }

    pub fn action(&self) -> &str {
        &self.detail.action
    }

    pub fn subject(&self) -> &str {
        &self.detail.subject
    }

    pub fn nearby(&self) -> &[String] {
        &self.detail.nearby
    }

    pub fn recovery(&self) -> &str {
        &self.detail.recovery
    }

    pub fn retry(&self) -> Retry {
        self.detail.retry
    }

    /// The least the raiser says to wait before asking again, when it
    /// said one; present only on a `Retry::Yes` error.
    pub fn retry_after_ms(&self) -> Option<u64> {
        self.detail.retry_after_ms
    }

    /// Whether the account this request went out on can still take it;
    /// `Advance` comes only with `Retry::No` (D53).
    pub fn account(&self) -> AccountDisposition {
        self.detail.account
    }

    pub fn gate(&self) -> Option<&GateRefusal> {
        self.detail.gate.as_ref()
    }

    pub fn provider_failure(&self) -> Option<ProviderFailureKind> {
        self.detail.provider
    }

    /// Replaces the recovery sentence of an error raised further down,
    /// for a caller who knows a better next step than its raiser did.
    /// Named apart from [`ErrorDraft::with_recovery`] because it destroys
    /// a sentence rather than supplying the first one.
    #[must_use]
    pub fn rewrite_recovery(mut self, recovery: impl Into<String>) -> Self {
        self.detail.recovery = recovery.into();
        self
    }
}

impl ErrorDraft {
    /// Names the spellings the caller could have used instead. Directly
    /// usable values only, not a description of them.
    pub fn with_nearby(mut self, nearby: Vec<String>) -> Self {
        self.pending.detail.nearby = nearby;
        self
    }

    /// Declares the action safe to retry as-is. Explicit opt-in only.
    /// Puts the account back to `Keep`: a request worth sending again
    /// on this account is no reason to leave it.
    pub fn retriable(mut self) -> Self {
        self.pending.detail.retry = Retry::Yes;
        self.pending.detail.account = AccountDisposition::Keep;
        self
    }

    /// Declares that the request went out and its answer was lost, so
    /// whether its effect landed is not known. Drops any wait set
    /// before it, because a wait belongs to `Retry::Yes` alone, and keeps
    /// the account, because a lost answer is no evidence against it.
    pub fn effect_unknown(mut self) -> Self {
        self.pending.detail.retry = Retry::Unknown;
        self.pending.detail.retry_after_ms = None;
        self.pending.detail.account = AccountDisposition::Keep;
        self
    }

    /// Declares that the account the request went out on cannot take it,
    /// so the next account should (D53). Sets `Retry::No` and drops any
    /// wait in the same step: the same request on the same account would
    /// fail the same way, however long it waited.
    pub fn account_unusable(mut self) -> Self {
        self.pending.detail.retry = Retry::No;
        self.pending.detail.retry_after_ms = None;
        self.pending.detail.account = AccountDisposition::Advance;
        self
    }

    /// Declares the action safe to retry, and no sooner than `wait_ms`
    /// from now: the other side's own word on when it recovers.
    pub fn retriable_after(mut self, wait_ms: u64) -> Self {
        self.pending.detail.retry_after_ms = Some(wait_ms);
        self.retriable()
    }

    /// Writes the one sentence that tells the reader what to do next, and
    /// hands back the finished error. The reader is as often a model as a
    /// person, so the sentence names a key, a file and line, or a command.
    pub fn with_recovery(mut self, recovery: impl Into<String>) -> AxError {
        self.pending.detail.recovery = recovery.into();
        self.pending
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::indexing_slicing,
    reason = "test code"
)]
mod tests {
    use super::*;
    #[test]
    fn failure_has_no_gate_and_is_not_retriable_by_default() {
        let err = AxError::failure(AxCode::PathNotFound, "read file", "docs/a.md")
            .with_recovery("create docs/a.md, or read one of the paths `ls docs` lists");
        assert!(err.gate().is_none());
        assert_eq!(err.retry(), Retry::No);
        assert_eq!(err.code(), &AxCode::PathNotFound);
    }

    #[test]
    fn builders_extend_without_touching_the_rest() {
        let err = AxError::failure(AxCode::ToolUnknown, "call tool", "grep")
            .with_nearby(vec!["exec".into(), "edit".into(), "status".into()])
            .retriable()
            .with_recovery("use an L0 tool");
        assert_eq!(err.retry(), Retry::Yes);
        let json = serde_json::to_value(&err).unwrap();
        assert_eq!(json["code"], "E_TOOL_UNKNOWN");
        assert_eq!(json["nearby"][0], "exec");
        assert_eq!(json["recovery"], "use an L0 tool");
        assert_eq!(json.get("gate"), None);
    }

    /// A wait belongs to a retriable error and to nothing else: the
    /// raiser's word on when to ask again reads back as given, and
    /// declaring the effect unknown takes it away with the retry.
    #[test]
    fn a_stated_wait_reads_back_until_the_effect_is_declared_unknown() {
        let draft = AxError::failure(AxCode::Provider, "call model", "429").retriable_after(1500);
        let waiting = draft.with_recovery("wait, then send the request again");
        assert_eq!(
            (waiting.retry(), waiting.retry_after_ms()),
            (Retry::Yes, Some(1500))
        );
        let unknown = AxError::failure(AxCode::Provider, "call model", "cut")
            .retriable_after(1500)
            .effect_unknown()
            .with_recovery("read the ledger before sending it again");
        assert_eq!(
            (unknown.retry(), unknown.retry_after_ms()),
            (Retry::Unknown, None)
        );
    }

    /// A provider error names the kind of failure it met, and an error
    /// raised any other way names none.
    #[test]
    fn only_a_provider_error_names_a_provider_failure() {
        let kind = ProviderFailureKind::Refused { status: 503 };
        let named = AxError::provider(kind, "call model", "503").with_recovery("try later");
        assert_eq!(
            (named.code(), named.provider_failure()),
            (&AxCode::Provider, Some(kind))
        );
        let plain = AxError::failure(AxCode::Provider, "call model", "503").with_recovery("r");
        assert_eq!(plain.provider_failure(), None);
    }

    /// A switch is never said beside a resend: whatever order the
    /// builders run in, `Advance` comes with `Retry::No` and no wait, and
    /// a wait comes with `Retry::Yes` alone. Derived from
    /// `crates/kernel/spec/Error.lean`
    /// (`no_order_of_calls_advances_a_resendable_failure`,
    /// `no_order_of_calls_waits_without_retrying`).
    #[derive(Debug, Clone)]
    enum Builder {
        Retriable,
        RetriableAfter(u64),
        EffectUnknown,
        AccountUnusable,
    }

    fn builder() -> impl proptest::strategy::Strategy<Value = Builder> {
        use proptest::prelude::*;
        prop_oneof![
            Just(Builder::Retriable),
            any::<u64>().prop_map(Builder::RetriableAfter),
            Just(Builder::EffectUnknown),
            Just(Builder::AccountUnusable),
        ]
    }

    proptest::proptest! {
        #[test]
        fn no_order_of_calls_advances_a_resendable_failure(
            steps in proptest::collection::vec(builder(), 0..12)
        ) {
            let draft = steps.into_iter().fold(
                AxError::failure(AxCode::Provider, "call model", "s"),
                |draft, step| match step {
                    Builder::Retriable => draft.retriable(),
                    Builder::RetriableAfter(wait_ms) => draft.retriable_after(wait_ms),
                    Builder::EffectUnknown => draft.effect_unknown(),
                    Builder::AccountUnusable => draft.account_unusable(),
                },
            );
            let err = draft.with_recovery("r");
            if err.account() == AccountDisposition::Advance {
                proptest::prop_assert_eq!((err.retry(), err.retry_after_ms()), (Retry::No, None));
            }
            if err.retry_after_ms().is_some() {
                proptest::prop_assert_eq!(err.retry(), Retry::Yes);
            }
        }
    }

    /// `Keep` is the absence of the field, so a ledger line written
    /// before the field existed keeps its bytes and reads back as `Keep`;
    /// `Advance` is spelled `"advance"`.
    #[test]
    fn only_a_switch_is_written_and_an_old_record_reads_as_keep() {
        let kept = AxError::failure(AxCode::Provider, "call model", "s").with_recovery("r");
        let advanced = AxError::failure(AxCode::Provider, "call model", "s")
            .retriable_after(500)
            .account_unusable()
            .with_recovery("r");
        let old = serde_json::json!({"code": "E_PROVIDER", "action": "call model",
            "subject": "s", "nearby": [], "recovery": "r", "retry": "no"});
        assert_eq!(
            (
                serde_json::to_value(&kept).unwrap(),
                serde_json::to_value(&advanced).unwrap()["account"].clone(),
                serde_json::from_value::<AxError>(old.clone())
                    .unwrap()
                    .account(),
            ),
            (old, serde_json::json!("advance"), AccountDisposition::Keep)
        );
        assert_eq!(
            serde_json::from_value::<AxError>(serde_json::to_value(&advanced).unwrap()).unwrap(),
            advanced
        );
    }

    #[test]
    fn axerror_serde_field_order_is_declaration_order() {
        let err = AxError::failure(AxCode::Timeout, "run exec", "build.sh").with_recovery(
            "raise `[tool] exec_timeout_ms` in CONFIG.toml, or run a shorter script",
        );
        let json = serde_json::to_string(&err).unwrap();
        let code_at = json.find("\"code\"").unwrap();
        let action_at = json.find("\"action\"").unwrap();
        let subject_at = json.find("\"subject\"").unwrap();
        let retriable_at = json.find("\"retry\"").unwrap();
        assert!(code_at < action_at && action_at < subject_at && subject_at < retriable_at);
    }

    #[test]
    fn a_ledger_record_written_with_the_retriable_flag_still_reads() {
        let record = |flag: bool| {
            serde_json::json!({"code": "E_PROVIDER", "action": "call model", "subject": "s",
                "nearby": [], "recovery": "r", "retriable": flag})
        };
        let retry = |flag| {
            serde_json::from_value::<AxError>(record(flag))
                .unwrap()
                .retry()
        };
        assert_eq!([retry(true), retry(false)], [Retry::Yes, Retry::No]);
    }

    #[test]
    fn an_unknown_effect_carries_no_wait_whatever_the_builder_order() {
        let err = AxError::failure(AxCode::Provider, "call model", "s")
            .retriable_after(1_500)
            .effect_unknown()
            .with_recovery("r");
        assert_eq!((err.retry(), err.retry_after_ms()), (Retry::Unknown, None));
    }

    #[test]
    fn display_names_code_action_subject() {
        let err = AxError::failure(AxCode::BudgetExhausted, "call model", "run-1")
            .with_recovery("raise `[budget]` in CONFIG.toml, then resume run-1");
        let text = err.to_string();
        assert!(text.contains("E_BUDGET_EXHAUSTED"));
        assert!(text.contains("call model"));
        assert!(text.contains("run-1"));
    }

    #[test]
    fn refusal_carries_the_three_mandatory_parts() {
        let gate = GateRefusal::new("rule", "violation", "alternative");
        let err = AxError::refusal(AxCode::GateDenied, "wire funds", "acct-9", gate)
            .with_recovery("alternative");
        let got = err.gate().expect("gate refusal must carry the three parts");
        assert_eq!(got.rule(), "rule");
        assert_eq!(got.violation(), "violation");
        assert_eq!(got.alternative(), "alternative");
    }

    #[test]
    fn every_constructed_error_carries_a_recovery_sentence() {
        let failure = AxError::failure(AxCode::InvalidArgs, "parse address", "city//")
            .with_recovery("write `city/<building>/<room>`");
        let refusal = AxError::refusal(
            AxCode::GateDenied,
            "write file",
            "/etc/hosts",
            GateRefusal::new("rule", "violation", "alternative"),
        )
        .with_recovery("write inside the run's write domain");
        assert!(!failure.recovery().is_empty());
        assert!(!refusal.recovery().is_empty());
    }
}