thruput-testkit 0.42.0

Multi-agent integration-test harness for Thruput contract applications
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
//! Error type for the test harness.

use std::fmt;

use thruput_json_rpc_types::{responses::TransactionStatus, transaction::TxHash};
use thruput_node_supervisor::BlockProductionError;

/// Result alias used throughout `thruput-testkit`.
pub type Result<T, E = TestkitError> = std::result::Result<T, E>;

/// One agent error retained after every non-panicking agent has finished.
#[derive(Debug)]
pub struct AgentFailure {
    name: String,
    index: usize,
    error: TestkitError,
}

impl AgentFailure {
    pub(crate) fn new(name: String, index: usize, error: TestkitError) -> Self {
        Self { name, index, error }
    }

    /// Name of the failed agent.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Position of the failed agent in the scenario's agent list.
    pub fn index(&self) -> usize {
        self.index
    }

    /// Error returned by the agent body.
    pub fn error(&self) -> &TestkitError {
        &self.error
    }
}

/// Ordered collection of errors returned by agents in one scenario run.
#[derive(Debug)]
pub struct AgentFailures {
    failures: Vec<AgentFailure>,
}

impl AgentFailures {
    pub(crate) fn new(failures: Vec<AgentFailure>) -> Self {
        debug_assert!(!failures.is_empty());
        Self { failures }
    }

    /// Agent failures ordered by their position in the scenario's agent list.
    pub fn failures(&self) -> &[AgentFailure] {
        &self.failures
    }
}

impl fmt::Display for AgentFailures {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let count = self.failures.len();
        write!(
            f,
            "{count} agent{} failed",
            if count == 1 { "" } else { "s" }
        )?;
        for failure in &self.failures {
            write!(
                f,
                "; {} (index {}): {}",
                failure.name, failure.index, failure.error
            )?;
        }
        Ok(())
    }
}

/// Errors returned by the harness while building or running a scenario.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum TestkitError {
    /// The runtime manifest has no faucet account to fund test accounts.
    #[error("runtime manifest has no bootstrap faucet")]
    MissingFaucet,
    /// A pending request must be reconciled before changing its amount.
    #[error(
        "a retained funding request for {recipient:?} has a different amount; retry the original amount on this Network handle"
    )]
    FundingRequestMismatch {
        /// Recipient with retained funding intent.
        recipient: thruput_xdr::types::ContractAddress,
    },
    /// A receipt belongs to another transaction.
    #[error("receipt hash does not match {expected:?}")]
    ReceiptHashMismatch {
        /// Locally computed transaction identity.
        expected: TxHash,
        /// Complete conflicting receipt, including its claimed commitment and execution.
        receipt: Box<thruput_json_rpc_types::responses::TransactionReceipt>,
    },
    /// An ambiguous submission retains the exact original signed transaction.
    #[error("submission of {tx_hash:?} was not verified: {detail}")]
    Submission {
        /// Locally computed transaction identity.
        tx_hash: TxHash,
        /// Exact signed bytes. Observe the original hash before any further action.
        signed_transaction: String,
        /// Transport error or unexpected returned identity.
        detail: String,
        /// Original structured submission or funding failure.
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },
    /// A submitted deployment could not be verified; preserve the original attempt.
    #[error("deployment {tx_hash:?} at {predicted_address:?} was not verified: {detail}")]
    UnverifiedDeployment {
        /// Locally computed transaction identity.
        tx_hash: TxHash,
        /// Address predicted from the signed deployment effects.
        predicted_address: thruput_xdr::types::ContractAddress,
        /// Exact original signed bytes for reconciliation.
        signed_transaction: String,
        /// Failed receipt lookup or verification.
        detail: Box<str>,
        /// Original receipt-wait evidence, when waiting stopped before validation.
        #[source]
        source: Option<Box<TestkitError>>,
        /// Authoritative receipt whose deployment return did not match the prediction.
        receipt: Option<Box<thruput_json_rpc_types::responses::TransactionReceipt>>,
    },
    /// Retained deployment effects differ from a new request by the same caller.
    #[error("artifact {name} has a retained deployment with different funding or initialization")]
    DeploymentRequestMismatch {
        /// Artifact with the retained attempt.
        name: String,
    },
    /// A scenario was built without a network configuration.
    #[error("no network configured for the scenario")]
    NoNetwork,

    /// A JSON-RPC call to the target failed.
    #[error("rpc `{method}` failed: {detail}")]
    Rpc {
        /// The RPC method that failed.
        method: &'static str,
        /// Underlying error description.
        detail: String,
    },

    /// A chain operation was attempted against an offline target.
    #[error("operation `{operation}` requires a live target, but this scenario is offline")]
    Offline {
        /// The attempted operation.
        operation: &'static str,
    },

    /// The runtime manifest could not be read or parsed.
    #[error("failed to load runtime manifest `{path}`: {detail}")]
    ManifestLoad {
        /// Manifest path.
        path: String,
        /// Underlying error description.
        detail: String,
    },

    /// The runtime manifest declared an unsupported schema version.
    #[error("unsupported runtime manifest schema version {actual}")]
    ManifestSchema {
        /// The version found in the manifest.
        actual: u32,
    },

    /// A field could not be read from the runtime manifest.
    #[error("runtime manifest field `{field}` is invalid: {detail}")]
    Manifest {
        /// The manifest field at fault.
        field: &'static str,
        /// Underlying error description.
        detail: String,
    },

    /// The manifest used a bootstrap-account derivation scheme we do not support.
    #[error("unsupported bootstrap-account derivation scheme `{scheme}`")]
    UnsupportedDerivationScheme {
        /// The scheme string found in the manifest.
        scheme: String,
    },

    /// The manifest carried no bootstrap accounts to assign to agents.
    #[error("runtime manifest declares no bootstrap accounts")]
    NoBootstrapAccounts,

    /// A derived signer did not match the public key the manifest advertised.
    #[error("bootstrap account {index} public key does not match the derived signer")]
    BootstrapPublicKeyMismatch {
        /// The bootstrap account index at fault.
        index: u32,
    },

    /// The scenario has fewer accounts than it has agents.
    #[error("scenario needs {needed} accounts but only {available} are available")]
    NotEnoughAccounts {
        /// Number of agents that need accounts.
        needed: usize,
        /// Number of accounts available.
        available: usize,
    },

    /// Two agents in one run were given the same name.
    #[error("agent name `{name}` appears more than once in the scenario")]
    DuplicateAgent {
        /// The duplicated agent name.
        name: String,
    },

    /// One or more agent bodies returned errors.
    #[error("{failures}")]
    AgentsFailed {
        /// All returned agent errors, ordered by agent position.
        failures: AgentFailures,
    },

    /// An account exhausted its per-account nonce sequence.
    #[error("account {index} exhausted its nonce sequence")]
    NonceExhausted {
        /// The account index at fault.
        index: u32,
    },

    /// Building or signing a transaction failed.
    #[error("transaction build/sign failed: {detail}")]
    Signing {
        /// Underlying error description.
        detail: String,
    },

    /// Encoding calldata or a contract failed.
    #[error("xdr encoding failed: {detail}")]
    Encode {
        /// Underlying error description.
        detail: String,
    },

    /// Decoding a contract return value failed.
    #[error("xdr decoding failed: {detail}")]
    Decode {
        /// Underlying error description.
        detail: String,
    },

    /// A contract interface version is not valid `SemVer`.
    #[error("contract interface version `{version}` is not valid SemVer")]
    InvalidContractVersion {
        /// Version string used to derive the method selector.
        version: String,
    },

    /// A deploy transaction did not execute successfully.
    #[error("deploy did not succeed: {detail}")]
    Deploy {
        /// Description of the failing execution status.
        detail: String,
    },

    /// A contract call executed but its status was not `Ok`.
    ///
    /// Carries the method name; add call-site context with `map_err` where
    /// that alone does not identify which call reverted.
    #[error("contract call to `{method}` reverted: {status}")]
    Reverted {
        /// The method that was called.
        method: String,
        /// Description of the failing execution status.
        status: String,
    },

    /// A contract call or view did not return successfully.
    #[error("contract {kind} did not return a value: {detail}")]
    NoReturn {
        /// Whether it was a `call` or a `view`.
        kind: &'static str,
        /// Description of the non-returning status.
        detail: String,
    },

    /// Receipt waiting stopped with retained status, commitment and read errors.
    #[error("{source}")]
    ReceiptWait {
        /// Wait cause plus the strongest observed commitment and status.
        #[source]
        source: Box<thruput_json_rpc_client::native::receipt::ReceiptPollError>,
    },
    /// Native RPC failure, retaining the original application or malformed result.
    #[error("rpc `{method}` failed: {source}")]
    NativeCall {
        /// Native method that failed.
        method: &'static str,
        /// Original RPC error or malformed result, including raw data.
        #[source]
        source: Box<thruput_json_rpc_client::native::NativeClientError>,
    },
    /// Funding evidence could not be validated; retain the original RPC failure.
    #[error("invalid local funding evidence: {detail}")]
    InvalidFundingEvidence {
        /// Why the supplied evidence could not be accepted.
        detail: String,
        /// Original validated hash and signed bytes, if already retained.
        retained: Option<Box<(TxHash, thruput_json_rpc_types::hex::HexBytes)>>,
        /// Original RPC error carrying the conflicting or invalid evidence.
        #[source]
        source: Box<thruput_json_rpc_client::native::NativeClientError>,
    },
    /// A funding result conflicts with the retained request or its signed identity.
    #[error("invalid local funding response: {detail}")]
    InvalidFundingResponse {
        /// Original validated hash and signed bytes, if already retained.
        retained: Option<Box<(TxHash, thruput_json_rpc_types::hex::HexBytes)>>,
        /// Complete supplied result, retained without accepting its identity.
        response: Box<thruput_json_rpc_types::responses::FundingSubmission>,
        /// Why the response conflicts with the request or original evidence.
        detail: String,
    },
    /// An unfamiliar response is retained without asserting its meaning.
    #[error("unsupported `{method}` response")]
    UnsupportedResponse {
        /// Native method that returned an unfamiliar result.
        method: &'static str,
        /// Complete result, retained without interpreting unknown variants.
        raw: serde_json::Value,
    },
    /// Endpoint compatibility or identity validation failed.
    #[error("{source}")]
    NativeEndpoint {
        /// Compatibility, identity or discovery failure with its original evidence.
        #[source]
        source: Box<thruput_client::NativeRpcError>,
    },

    /// A submitted transaction did not become pending before the polling budget elapsed.
    #[error("timed out waiting for `{tx_hash}` to become pending (last status: {last_status:?})")]
    PendingTimeout {
        /// Transaction hash that never appeared as pending.
        tx_hash: String,
        /// Last status observed before timeout.
        last_status: Box<TransactionStatus>,
    },

    /// A submitted transaction reached a terminal or unexpected state before becoming pending.
    #[error("transaction `{tx_hash}` did not become pending: {status:?}")]
    TransactionNotPending {
        /// Transaction hash whose status was observed.
        tx_hash: String,
        /// Status observed instead of `Pending`.
        status: Box<TransactionStatus>,
    },

    /// Manual block production is unavailable for this target or driver mode.
    #[error("manual block production requires a harness-owned local node in manual mode")]
    ManualBlockProductionUnavailable,

    /// The local supervisor failed to produce a manually-requested block.
    #[error("manual block production failed: {source}")]
    BlockProduction {
        /// Underlying supervisor block-production error.
        #[source]
        source: BlockProductionError,
    },

    /// A contract artifact could not be read from disk.
    #[error("failed to load artifact `{name}` from `{path}`: {detail}")]
    ArtifactLoad {
        /// Registry name of the artifact.
        name: String,
        /// Path that failed to load.
        path: String,
        /// Underlying error description.
        detail: String,
    },

    /// A file artifact had an extension the harness does not recognize.
    #[error("cannot infer artifact kind from `{path}` (expected .rv32a)")]
    UnknownArtifactExtension {
        /// The path whose extension was unrecognized.
        path: String,
    },

    /// Two artifacts were registered under the same name.
    #[error("artifact `{name}` is registered more than once")]
    DuplicateArtifact {
        /// The duplicated artifact name.
        name: String,
    },

    /// An agent referenced an artifact name that was never registered.
    #[error("no artifact named `{name}` was registered with the scenario")]
    UnknownArtifact {
        /// The unrecognized artifact name.
        name: String,
    },

    /// An artifact registration transaction is still awaiting a receipt.
    #[error("artifact `{name}` registration transaction `{tx_hash:?}` is still pending")]
    ArtifactRegistrationPending {
        /// Registry artifact name.
        name: String,
        /// Transaction currently registering the artifact.
        tx_hash: TxHash,
        /// Original signed bytes for explicit caller-controlled reconciliation.
        signed_transaction: String,
    },

    /// The local node supervisor failed to start or stop the target.
    #[error("local node supervisor error: {detail}")]
    NodeSupervisor {
        /// Underlying error description.
        detail: String,
    },

    /// A started local node did not advertise a runtime manifest.
    #[error("local node did not advertise a runtime manifest")]
    MissingRuntimeManifest,

    /// A message was addressed to an agent that is not part of the scenario.
    #[error("no agent named `{name}` in the scenario roster")]
    UnknownAgent {
        /// The unrecognized recipient name.
        name: String,
    },

    /// The recipient agent's mailbox was already closed.
    #[error("mailbox for agent `{name}` is closed")]
    MailboxClosed {
        /// The recipient whose mailbox is closed.
        name: String,
    },

    /// An agent task failed to join for a reason other than a panic.
    #[error("agent task failed to join: {detail}")]
    AgentJoin {
        /// Description of the join failure.
        detail: String,
    },
}

impl TestkitError {
    pub(crate) fn native(source: thruput_client::NativeRpcError) -> Self {
        Self::NativeEndpoint {
            source: Box::new(source),
        }
    }
    /// Build an [`TestkitError::Rpc`] from a failing call.
    pub(crate) fn rpc(method: &'static str, error: impl std::fmt::Display) -> Self {
        Self::Rpc {
            method,
            detail: error.to_string(),
        }
    }

    pub(crate) fn signing(error: impl std::fmt::Display) -> Self {
        Self::Signing {
            detail: error.to_string(),
        }
    }

    pub(crate) fn encode(error: impl std::fmt::Display) -> Self {
        Self::Encode {
            detail: error.to_string(),
        }
    }

    pub(crate) fn decode(error: impl std::fmt::Display) -> Self {
        Self::Decode {
            detail: error.to_string(),
        }
    }
}