diff --git a/ocam/src/fuzz_tests.zig b/ocam/src/fuzz_tests.zig index d6a3884f..aff2b605 100644 --- a/ocam/src/fuzz_tests.zig +++ b/ocam/src/fuzz_tests.zig @@ -48,7 +48,6 @@ const Fuzzers = .{ .vsr_superblock_quorums = @import("./vsr/superblock_quorums_fuzz.zig"), .vsr_multi_batch = @import("./vsr/multi_batch_fuzz.zig"), .signal = @import("./clients/c/tb_client/signal_fuzz.zig"), - .state_machine = @import("./state_machine_fuzz.zig"), // A fuzzer that intentionally fails, to test fuzzing infrastructure itself .canary = {}, // Quickly run all fuzzers as a smoke test @@ -127,7 +126,6 @@ fn main_smoke(gpa: std.mem.Allocator) !void { .lsm_manifest_log => 2_000, .lsm_scan => 100, .lsm_tree => 400, - .state_machine => 10_000, .message_bus => 10, .storage => 1_000, .vsr_free_set => 10_000, diff --git a/ocam/src/scripts/cfo.zig b/ocam/src/scripts/cfo.zig index 828eca6a..e2e41e80 100644 --- a/ocam/src/scripts/cfo.zig +++ b/ocam/src/scripts/cfo.zig @@ -91,7 +91,6 @@ const Fuzzer = enum { vsr_superblock, vsr_multi_batch, signal, - state_machine, const weights = std.enums.EnumArray(Fuzzer, u32).init(.{ .canary = 1, @@ -116,7 +115,6 @@ const Fuzzer = enum { .vsr_superblock = 1, .vsr_multi_batch = 1, .signal = 1, - .state_machine = 2, }); fn args_build(comptime fuzzer: Fuzzer) []const []const u8 { diff --git a/ocam/src/state_machine/auditor.zig b/ocam/src/state_machine/auditor.zig deleted file mode 100644 index 24bcf407..00000000 --- a/ocam/src/state_machine/auditor.zig +++ /dev/null @@ -1,1010 +0,0 @@ -//! The Auditor constructs the expected state of its corresponding StateMachine from requests and -//! replies. It validates replies against its local state. -//! -//! The Auditor expects replies in ascending commit order. -const std = @import("std"); -const stdx = @import("stdx"); -const assert = std.debug.assert; -const maybe = stdx.maybe; -const log = std.log.scoped(.test_auditor); - -const tb = @import("../tigerbeetle.zig"); -const IdPermutation = @import("../testing/id.zig").IdPermutation; -const TimestampRange = @import("../lsm/timestamp_range.zig").TimestampRange; - -const PriorityQueue = std.PriorityQueue; -const Storage = @import("../testing/storage.zig").Storage; -const StateMachine = @import("../state_machine.zig").StateMachineType(Storage); - -pub const CreateAccountStatusSet = std.enums.EnumSet(tb.CreateAccountStatus); -// TODO(zig): See `Ordered` comments. -pub const CreateTransferStatusSet = std.enums.EnumSet(tb.CreateTransferStatus.Ordered); - -/// Batch sizes apply to both `create` and `lookup` operations. -/// (More ids would fit in the `lookup` request, but then the response wouldn't fit.) -const accounts_batch_size_max = StateMachine.batch_max.create_accounts; -const transfers_batch_size_max = StateMachine.batch_max.create_transfers; - -const InFlightKey = struct { - client_index: usize, - /// This index corresponds to Auditor.creates_sent/Auditor.creates_delivered. - client_request: usize, -}; - -/// Store expected possible results for an in-flight request. -/// This reply validation takes advantage of the Workload's additional context about the request. -const InFlight = union(enum) { - create_accounts: [accounts_batch_size_max]CreateAccountStatusSet, - create_transfers: [transfers_batch_size_max]CreateTransferStatusSet, -}; - -const InFlightQueue = std.AutoHashMapUnmanaged(InFlightKey, InFlight); - -const PendingTransfer = struct { - amount: u128, - debit_account_index: usize, - credit_account_index: usize, - query_intersection_index: usize, -}; - -const PendingExpiry = struct { - transfer_id: u128, - transfer_timestamp: u64, - expires_at: u64, -}; - -const PendingExpiryQueue = PriorityQueue(PendingExpiry, void, struct { - /// Order by ascending expiration date and then by transfer's timestamp. - fn compare(_: void, a: PendingExpiry, b: PendingExpiry) std.math.Order { - const order = switch (std.math.order(a.expires_at, b.expires_at)) { - .eq => std.math.order(a.transfer_timestamp, b.transfer_timestamp), - else => |order| order, - }; - assert(order != .eq); - return order; - } -}.compare); - -pub const AccountingAuditor = struct { - pub const AccountState = struct { - /// Set to true when `create_accounts` returns `.created` for an account. - created: bool = false, - /// The number of transfers created on the debit side. - dr_transfer_count: u32 = 0, - /// The number of transfers created on the credit side. - cr_transfer_count: u32 = 0, - /// Timestamp of the first transfer recorded. - transfer_timestamp_min: u64 = 0, - /// Timestamp of the last transfer recorded. - transfer_timestamp_max: u64 = 0, - - fn update( - state: *AccountState, - comptime entry: enum { dr, cr }, - transfer_timestamp: u64, - ) void { - assert(state.created); - switch (entry) { - .dr => state.dr_transfer_count += 1, - .cr => state.cr_transfer_count += 1, - } - - if (state.transfer_timestamp_min == 0) { - assert(state.transfer_timestamp_max == 0); - state.transfer_timestamp_min = transfer_timestamp; - } - state.transfer_timestamp_max = transfer_timestamp; - } - - pub fn transfers_count(self: *const AccountState, flags: tb.AccountFilterFlags) u32 { - var transfer_count: u32 = 0; - if (flags.debits) { - transfer_count += self.dr_transfer_count; - } - if (flags.credits) { - transfer_count += self.cr_transfer_count; - } - return transfer_count; - } - }; - - pub const Options = struct { - accounts_max: usize, - account_id_permutation: IdPermutation, - client_count: usize, - - /// The maximum number of pending transfers that can be expired per pulse. - pulse_expiries_max: u32, - - /// This is the maximum number of pending transfers, not counting those that have timed - /// out. - /// - /// NOTE: Transfers that have posted/voided successfully (or not) that have _not_ yet - /// reached their expiry are still included in this count — see `pending_expiries`. - transfers_pending_max: usize, - - /// This is the maximum number of changes events needs to be tracked. - changes_events_max: u32, - - /// From the Auditor's point-of-view, all stalled requests are still in-flight, even if - /// their reply has actually arrived at the ReplySequence. - /// - /// A request stops being "in-flight" when `on_reply` is called. - /// - /// This should equal the ReplySequence's `stalled_queue_capacity`. - in_flight_max: usize, - }; - - pub const QueryIntersection = struct { - user_data_64: u64, - user_data_32: u32, - code: u16, - - accounts: QueryIntersectionState = .{}, - transfers: QueryIntersectionState = .{}, - }; - - pub const QueryIntersectionState = struct { - /// The number of objects recorded. - count: u32 = 0, - /// Timestamp of the first object recorded. - timestamp_min: u64 = 0, - /// Timestamp of the last object recorded. - timestamp_max: u64 = 0, - }; - - pub const ChangesTracker = struct { - const EnumArray = std.EnumArray(tb.ChangeEventType, u32); - const Counter = struct { - /// The number of events recorded. - count: EnumArray, - /// Timestamp of the first event recorded. - timestamp_min: u64, - /// Timestamp of the last event recorded. - timestamp_max: u64, - - fn init() Counter { - return .{ - .count = EnumArray.initFill(0), - .timestamp_min = 0, - .timestamp_max = 0, - }; - } - - pub fn count_total(self: *const Counter) u32 { - const timestamp_valid: bool = - TimestampRange.valid(self.timestamp_min) and - TimestampRange.valid(self.timestamp_max); - maybe(timestamp_valid); - - var total: u32 = 0; - for (self.count.values) |value| total += value; - assert((total > 0) == timestamp_valid); - return total; - } - }; - - current: Counter, - snapshot: ?Counter, - changes_events_max: u32, - - fn init(changes_events_max: u32) ChangesTracker { - return .{ - .current = Counter.init(), - .snapshot = null, - .changes_events_max = changes_events_max, - }; - } - - fn update(self: *ChangesTracker, change: union(enum) { - transfer: struct { - timestamp: u64, - flags: tb.TransferFlags, - }, - expiry: struct { - timestamp: u64, - expired_count: u32, - }, - }) void { - defer assert(self.current.count_total() <= self.changes_events_max); - - const count: u32 = switch (change) { - .transfer => 1, - .expiry => |expiry| expiry.expired_count, - }; - assert(count > 0); - if (self.current.count_total() + count > self.changes_events_max) { - // Reset the counters if we reach the maximum size. - self.current = Counter.init(); - // Too many events to keep track of. - if (count > self.changes_events_max) return; - } - - switch (change) { - .transfer => |transfer| { - assert(TimestampRange.valid(transfer.timestamp)); - if (self.current.timestamp_min == 0 and - self.current.timestamp_max == 0) - { - self.current.timestamp_min = transfer.timestamp; - self.current.timestamp_max = transfer.timestamp; - } else { - assert(TimestampRange.valid(self.current.timestamp_min)); - assert(TimestampRange.valid(self.current.timestamp_max)); - assert(self.current.timestamp_min <= self.current.timestamp_max); - assert(transfer.timestamp > self.current.timestamp_max); - self.current.timestamp_max = transfer.timestamp; - } - - if (transfer.flags.pending) { - self.current.count.getPtr(.two_phase_pending).* += 1; - } else if (transfer.flags.post_pending_transfer) { - self.current.count.getPtr(.two_phase_posted).* += 1; - } else if (transfer.flags.void_pending_transfer) { - self.current.count.getPtr(.two_phase_voided).* += 1; - } else { - self.current.count.getPtr(.single_phase).* += 1; - } - }, - .expiry => |expiry| { - assert(TimestampRange.valid(expiry.timestamp)); - if (self.current.timestamp_min == 0 and - self.current.timestamp_max == 0) - { - const timestamp_first: u64 = expiry.timestamp - expiry.expired_count; - assert(TimestampRange.valid(timestamp_first)); - self.current.timestamp_min = timestamp_first; - self.current.timestamp_max = expiry.timestamp; - } else { - assert(TimestampRange.valid(self.current.timestamp_min)); - assert(TimestampRange.valid(self.current.timestamp_max)); - assert(self.current.timestamp_min <= self.current.timestamp_max); - assert(expiry.timestamp > self.current.timestamp_max); - self.current.timestamp_max = expiry.timestamp; - } - self.current.count.getPtr(.two_phase_expired).* += expiry.expired_count; - }, - } - } - - pub fn acquire_snapshot(self: *ChangesTracker) ?Counter { - // Snapshot already in use for another query. - if (self.snapshot != null) return null; - // No events. - if (self.current.count_total() == 0) return null; - - assert(self.snapshot == null); - self.snapshot = self.current; - return self.snapshot.?; - } - - fn release_snapshot(self: *ChangesTracker) Counter { - assert(self.snapshot != null); - defer self.snapshot = null; - - return self.snapshot.?; - } - }; - - prng: *stdx.PRNG, - options: Options, - - /// The timestamp of the last processed reply. - timestamp: u64 = 0, - - /// The account configuration. Balances are in sync with the remote StateMachine for a - /// given commit (double-double entry accounting). - accounts: []tb.Account, - - /// Additional account state. Keyed by account index. - accounts_state: []AccountState, - - /// Known intersection values for a particular combination of secondary indexes. - /// Counters are in sync with the remote StateMachine tracking the number of objects - /// with such fields. - query_intersections: []QueryIntersection, - - /// Map pending transfers to the (pending) amount and accounts. - /// - /// * Added in `on_create_transfers` for pending transfers. - /// * Removed after a transfer is posted, voided, or timed out. - /// - /// All entries in `pending_transfers` have a corresponding entry in `pending_expiries`. - pending_transfers: std.AutoHashMapUnmanaged(u128, PendingTransfer), - - /// After a transfer is posted/voided, the entry in `pending_expiries` is untouched. - /// The timeout will not impact account balances (because the `pending_transfers` entry is - /// removed), but until timeout the transfer still counts against `transfers_pending_max`. - pending_expiries: PendingExpiryQueue, - - /// Records the number of events in a given timestamp span. - /// Used to validate the `get_change_events` results. - changes_tracker: ChangesTracker, - - /// Track the expected result of the in-flight request for each client. - /// Each member queue corresponds to entries of the client's request queue, but omits - /// `register` messages. - in_flight: InFlightQueue, - - /// The number of `create_accounts`/`create_transfers` sent, per client. Keyed by client index. - creates_sent: []usize, - - /// The number of `create_accounts`/`create_transfers` delivered (i.e. replies received), - /// per client. Keyed by client index. - creates_delivered: []usize, - - pub fn init( - gpa: std.mem.Allocator, - prng: *stdx.PRNG, - options: Options, - ) !AccountingAuditor { - assert(options.accounts_max >= 2); - assert(options.client_count > 0); - - const accounts = try gpa.alloc(tb.Account, options.accounts_max); - errdefer gpa.free(accounts); - @memset(accounts, undefined); - - const accounts_state = try gpa.alloc(AccountState, options.accounts_max); - errdefer gpa.free(accounts_state); - @memset(accounts_state, AccountState{}); - - // The number of known intersection values for the secondary indices is kept low enough to - // explore different cardinalities. - const query_intersections = try gpa.alloc( - QueryIntersection, - options.accounts_max / 2, - ); - errdefer gpa.free(query_intersections); - for (query_intersections, 1..) |*query_intersection, index| { - query_intersection.* = .{ - .user_data_64 = @intCast(index * 1_000_000), - .user_data_32 = @intCast(index * 1_000), - .code = @intCast(index), // It will be used to recover the index. - }; - } - - var pending_transfers = std.AutoHashMapUnmanaged(u128, PendingTransfer){}; - errdefer pending_transfers.deinit(gpa); - try pending_transfers.ensureTotalCapacity( - gpa, - @intCast(options.transfers_pending_max), - ); - - var pending_expiries = PendingExpiryQueue.init(gpa, {}); - errdefer pending_expiries.deinit(); - try pending_expiries.ensureTotalCapacity(options.transfers_pending_max); - - var in_flight = InFlightQueue{}; - errdefer in_flight.deinit(gpa); - try in_flight.ensureTotalCapacity(gpa, @intCast(options.in_flight_max)); - - const creates_sent = try gpa.alloc(usize, options.client_count); - errdefer gpa.free(creates_sent); - @memset(creates_sent, 0); - - const creates_delivered = try gpa.alloc(usize, options.client_count); - errdefer gpa.free(creates_delivered); - @memset(creates_delivered, 0); - - return .{ - .prng = prng, - .options = options, - .accounts = accounts, - .accounts_state = accounts_state, - .query_intersections = query_intersections, - .pending_transfers = pending_transfers, - .pending_expiries = pending_expiries, - .changes_tracker = ChangesTracker.init(options.changes_events_max), - .in_flight = in_flight, - .creates_sent = creates_sent, - .creates_delivered = creates_delivered, - }; - } - - pub fn deinit(self: *AccountingAuditor, gpa: std.mem.Allocator) void { - gpa.free(self.creates_delivered); - gpa.free(self.creates_sent); - self.in_flight.deinit(gpa); - self.pending_expiries.deinit(); - self.pending_transfers.deinit(gpa); - gpa.free(self.query_intersections); - gpa.free(self.accounts_state); - gpa.free(self.accounts); - } - - pub fn done(self: *const AccountingAuditor) bool { - if (self.in_flight.count() != 0) return false; - - for (self.creates_sent, 0..) |sent, client_index| { - if (sent != self.creates_delivered[client_index]) return false; - } - // Don't check pending_transfers; the workload might not have posted/voided every transfer. - - return true; - } - - pub fn expect_create_accounts( - self: *AccountingAuditor, - client_index: usize, - ) []CreateAccountStatusSet { - const result = self.in_flight.getOrPutAssumeCapacity(.{ - .client_index = client_index, - .client_request = self.creates_sent[client_index], - }); - assert(!result.found_existing); - - self.creates_sent[client_index] += 1; - result.value_ptr.* = .{ .create_accounts = undefined }; - return result.value_ptr.*.create_accounts[0..]; - } - - pub fn expect_create_transfers( - self: *AccountingAuditor, - client_index: usize, - ) []CreateTransferStatusSet { - const result = self.in_flight.getOrPutAssumeCapacity(.{ - .client_index = client_index, - .client_request = self.creates_sent[client_index], - }); - assert(!result.found_existing); - - self.creates_sent[client_index] += 1; - result.value_ptr.* = .{ .create_transfers = undefined }; - return result.value_ptr.*.create_transfers[0..]; - } - - /// Expire pending transfers that have not been posted or voided. - pub fn expire_pending_transfers(self: *AccountingAuditor, timestamp: u64) void { - assert(self.timestamp < timestamp); - defer self.timestamp = timestamp; - - var expired_count: u32 = 0; - while (self.pending_expiries.peek()) |expiration| { - if (timestamp < expiration.expires_at) break; - defer _ = self.pending_expiries.remove(); - - // Ignore the transfer if it was already posted/voided. - const pending_transfer = - self.pending_transfers.get(expiration.transfer_id) orelse continue; - assert(self.pending_transfers.remove(expiration.transfer_id)); - assert(self.accounts_state[pending_transfer.debit_account_index].created); - assert(self.accounts_state[pending_transfer.credit_account_index].created); - - const dr = &self.accounts[pending_transfer.debit_account_index]; - const cr = &self.accounts[pending_transfer.credit_account_index]; - dr.debits_pending -= pending_transfer.amount; - cr.credits_pending -= pending_transfer.amount; - assert(!dr.debits_exceed_credits(0)); - assert(!dr.credits_exceed_debits(0)); - assert(!cr.debits_exceed_credits(0)); - assert(!cr.credits_exceed_debits(0)); - - // Each expiration round can expire at most one batch of transfers. - expired_count += 1; - if (expired_count == self.options.pulse_expiries_max) break; - } - - if (expired_count > 0) { - self.changes_tracker.update(.{ .expiry = .{ - .timestamp = timestamp, - .expired_count = expired_count, - } }); - } - } - - pub fn on_create_accounts_sparse( - self: *AccountingAuditor, - client_index: usize, - timestamp: u64, - accounts: []const tb.Account, - results_sparse: []const tb.CreateAccountErrorResult, - ) void { - assert(accounts.len >= results_sparse.len); - assert(self.timestamp < timestamp or - // Zero-sized batches packed in a multi-batch message: - (accounts.len == 0 and self.timestamp == timestamp)); - defer self.timestamp = timestamp; - - const results_expect = self.take_in_flight(client_index).create_accounts; - var iterator: ResultsSparseIteratorType(tb.CreateAccountErrorResult) = .init( - results_sparse, - ); - defer assert(iterator.results.len == 0); - - for (accounts, 0..) |*account, i| { - const account_timestamp = timestamp - accounts.len + i + 1; - - const result_actual = iterator.take(i) orelse .created; - if (!results_expect[i].contains(result_actual)) { - log.err("on_create_accounts_sparse: account={} expect={} result={}", .{ - account.*, - results_expect[i], - result_actual, - }); - @panic("on_create_accounts_sparse: unexpected result"); - } - - if (result_actual == .created) { - self.on_create_account_ok(account_timestamp, account); - } - } - } - - pub fn on_create_accounts( - self: *AccountingAuditor, - client_index: usize, - timestamp: u64, - accounts: []const tb.Account, - results: []const tb.CreateAccountResult, - ) void { - assert(accounts.len == results.len); - assert(self.timestamp < timestamp or - // Zero-sized batches packed in a multi-batch message: - (accounts.len == 0 and self.timestamp == timestamp)); - defer self.timestamp = timestamp; - - const results_expect = self.take_in_flight(client_index).create_accounts; - for (accounts, results, 0..) |*account, *result, i| { - assert(result.reserved == 0); - const account_timestamp = timestamp - accounts.len + i + 1; - - if (!results_expect[i].contains(result.status)) { - log.err("on_create_accounts: account={} expect={} result={}", .{ - account.*, - results_expect[i], - result, - }); - @panic("on_create_accounts: unexpected result"); - } - - switch (result.status) { - .created => { - assert(result.timestamp == account_timestamp); - self.on_create_account_ok(account_timestamp, account); - }, - .exists => assert(result.timestamp == self.get_account(account.id).?.timestamp), - else => assert(result.timestamp > 0), - } - } - } - - fn on_create_account_ok( - self: *AccountingAuditor, - timestamp: u64, - account: *const tb.Account, - ) void { - const account_index = self.account_id_to_index(account.id); - assert(account_index < self.accounts.len); - assert(!self.accounts_state[account_index].created); - self.accounts_state[account_index].created = true; - self.accounts[account_index] = account.*; - self.accounts[account_index].timestamp = timestamp; - - const query_intersection_index = account.code - 1; - const query_intersection = &self.query_intersections[query_intersection_index]; - assert(account.user_data_64 == query_intersection.user_data_64); - assert(account.user_data_32 == query_intersection.user_data_32); - assert(account.code == query_intersection.code); - query_intersection.accounts.count += 1; - if (query_intersection.accounts.timestamp_min == 0) { - query_intersection.accounts.timestamp_min = timestamp; - } - query_intersection.accounts.timestamp_max = timestamp; - } - - pub fn on_create_transfers_sparse( - self: *AccountingAuditor, - client_index: usize, - timestamp: u64, - transfers: []const tb.Transfer, - results_sparse: []const tb.CreateTransferErrorResult, - ) void { - assert(transfers.len >= results_sparse.len); - assert(self.timestamp < timestamp or - // Zero-sized batches packed in a multi-batch message: - (transfers.len == 0 and self.timestamp == timestamp)); - defer self.timestamp = timestamp; - - const results_expect = self.take_in_flight(client_index).create_transfers; - var iterator: ResultsSparseIteratorType(tb.CreateTransferErrorResult) = .init( - results_sparse, - ); - defer assert(iterator.results.len == 0); - - for (transfers, 0..) |*transfer, i| { - const transfer_timestamp = timestamp - transfers.len + i + 1; - - const result_actual = iterator.take(i) orelse .created; - if (!results_expect[i].contains(result_actual.to_ordered())) { - log.err("on_create_transfers_sparse: transfer={} expect={} result={}", .{ - transfer.*, - results_expect[i], - result_actual, - }); - @panic("on_create_transfers_sparse: unexpected result"); - } - - if (result_actual == .created) self.on_create_transfer_ok( - transfer_timestamp, - transfer, - ); - } - } - - pub fn on_create_transfers( - self: *AccountingAuditor, - client_index: usize, - timestamp: u64, - transfers: []const tb.Transfer, - results: []const tb.CreateTransferResult, - ) void { - assert(transfers.len == results.len); - assert(self.timestamp < timestamp or - // Zero-sized batches packed in a multi-batch message: - (transfers.len == 0 and self.timestamp == timestamp)); - defer self.timestamp = timestamp; - - const results_expect = self.take_in_flight(client_index).create_transfers; - for (transfers, results, 0..) | - *transfer, - result, - i, - | { - const transfer_timestamp = timestamp - transfers.len + i + 1; - - if (!results_expect[i].contains(result.status.to_ordered())) { - log.err("on_create_transfers: transfer={} expect={} result={}", .{ - transfer.*, - results_expect[i], - result, - }); - @panic("on_create_transfers: unexpected result"); - } - - assert(result.timestamp > 0); - switch (result.status) { - .created => { - assert(result.timestamp == transfer_timestamp); - self.on_create_transfer_ok(transfer_timestamp, transfer); - }, - .exists => assert(result.timestamp < transfer_timestamp), - else => {}, - } - } - } - - fn on_create_transfer_ok( - self: *AccountingAuditor, - timestamp: u64, - transfer: *const tb.Transfer, - ) void { - self.changes_tracker.update(.{ .transfer = .{ - .timestamp = timestamp, - .flags = transfer.flags, - } }); - - const query_intersection_index = transfer.code - 1; - const query_intersection = &self.query_intersections[query_intersection_index]; - assert(transfer.user_data_64 == query_intersection.user_data_64); - assert(transfer.user_data_32 == query_intersection.user_data_32); - assert(transfer.code == query_intersection.code); - query_intersection.transfers.count += 1; - if (query_intersection.transfers.timestamp_min == 0) { - query_intersection.transfers.timestamp_min = timestamp; - } - query_intersection.transfers.timestamp_max = timestamp; - - if (transfer.flags.post_pending_transfer or transfer.flags.void_pending_transfer) { - const p = self.pending_transfers.get(transfer.pending_id).?; - const dr_state = &self.accounts_state[p.debit_account_index]; - const cr_state = &self.accounts_state[p.credit_account_index]; - dr_state.update(.dr, timestamp); - cr_state.update(.cr, timestamp); - - const dr = &self.accounts[p.debit_account_index]; - const cr = &self.accounts[p.credit_account_index]; - - assert(self.pending_transfers.remove(transfer.pending_id)); - // The transfer may still be in `pending_expiries` — removal would be O(n), - // so don't bother. - - dr.debits_pending -= p.amount; - cr.credits_pending -= p.amount; - if (transfer.flags.post_pending_transfer) { - const amount = @min(transfer.amount, p.amount); - dr.debits_posted += amount; - cr.credits_posted += amount; - } - - assert(!dr.debits_exceed_credits(0)); - assert(!dr.credits_exceed_debits(0)); - assert(!cr.debits_exceed_credits(0)); - assert(!cr.credits_exceed_debits(0)); - } else { - const dr_index = self.account_id_to_index(transfer.debit_account_id); - const cr_index = self.account_id_to_index(transfer.credit_account_id); - const dr_state = &self.accounts_state[dr_index]; - const cr_state = &self.accounts_state[cr_index]; - dr_state.update(.dr, timestamp); - cr_state.update(.cr, timestamp); - - const dr = &self.accounts[dr_index]; - const cr = &self.accounts[cr_index]; - - if (transfer.flags.pending) { - if (transfer.timeout > 0) { - self.pending_transfers.putAssumeCapacity(transfer.id, .{ - .amount = transfer.amount, - .debit_account_index = dr_index, - .credit_account_index = cr_index, - .query_intersection_index = transfer.code - 1, - }); - self.pending_expiries.add(.{ - .transfer_id = transfer.id, - .transfer_timestamp = timestamp, - .expires_at = timestamp + transfer.timeout_ns(), - }) catch unreachable; - // PriorityQueue lacks an "unmanaged" API, so verify that the workload - // hasn't created more pending transfers than permitted. - assert(self.pending_expiries.count() <= self.options.transfers_pending_max); - } - dr.debits_pending += transfer.amount; - cr.credits_pending += transfer.amount; - } else { - dr.debits_posted += transfer.amount; - cr.credits_posted += transfer.amount; - } - - assert(!dr.debits_exceed_credits(0)); - assert(!dr.credits_exceed_debits(0)); - assert(!cr.debits_exceed_credits(0)); - assert(!cr.credits_exceed_debits(0)); - } - } - - pub fn on_lookup_accounts( - self: *AccountingAuditor, - client_index: usize, - timestamp: u64, - ids: []const u128, - results: []const tb.Account, - ) void { - _ = client_index; - assert(ids.len >= results.len); - assert(self.timestamp <= timestamp); - defer self.timestamp = timestamp; - - var results_iterator = IteratorForLookupType(tb.Account).init(results); - defer assert(results_iterator.results.len == 0); - - for (ids) |account_id| { - const account_index = self.account_id_to_index(account_id); - const account_lookup = results_iterator.take(account_id); - - if (account_index < self.accounts.len and - self.accounts_state[account_index].created) - { - // If this assertion fails, `lookup_accounts` didn't return an account when it - // should have. - assert(account_lookup != null); - assert(!account_lookup.?.debits_exceed_credits(0)); - assert(!account_lookup.?.credits_exceed_debits(0)); - - const account_expect = &self.accounts[account_index]; - if (!std.mem.eql( - u8, - std.mem.asBytes(account_lookup.?), - std.mem.asBytes(account_expect), - )) { - log.err("on_lookup_accounts: account data mismatch " ++ - "account_id={} expect={} lookup={}", .{ - account_id, - account_expect, - account_lookup.?, - }); - @panic("on_lookup_accounts: account data mismatch"); - } - } else { - // If this assertion fails, `lookup_accounts` returned an account when it shouldn't. - assert(account_lookup == null); - } - } - } - - /// Most `lookup_transfers` validation is handled by Workload. - /// (Workload has more context around transfers, so it can be much stricter.) - pub fn on_lookup_transfers( - self: *AccountingAuditor, - client_index: usize, - timestamp: u64, - ids: []const u128, - results: []const tb.Transfer, - ) void { - _ = client_index; - assert(ids.len >= results.len); - assert(self.timestamp <= timestamp); - defer self.timestamp = timestamp; - - var results_iterator = IteratorForLookupType(tb.Transfer).init(results); - defer assert(results_iterator.results.len == 0); - - for (ids) |id| { - const result = results_iterator.take(id); - assert(result == null or result.?.id == id); - } - } - - /// Returns a random account matching the given criteria. - /// Returns null when no account matches the given criteria. - pub fn pick_account( - self: *const AccountingAuditor, - match: struct { - /// Whether the account is known to be created - /// (we have received an `ok` for the respective `create_accounts`). - created: ?bool, - debits_must_not_exceed_credits: ?bool, - credits_must_not_exceed_debits: ?bool, - /// Don't match this account. - exclude: ?u128 = null, - }, - ) ?*const tb.Account { - const offset = self.prng.int_inclusive(usize, self.accounts.len - 1); - var i: usize = 0; - // Iterate `accounts`, starting from a random offset. - while (i < self.accounts.len) : (i += 1) { - const account_index = (offset + i) % self.accounts.len; - if (match.created) |expect_created| { - if (self.accounts_state[account_index].created) { - if (!expect_created) continue; - } else { - if (expect_created) continue; - } - } - - const account = &self.accounts[account_index]; - if (match.debits_must_not_exceed_credits) |b| { - if (account.flags.debits_must_not_exceed_credits != b) continue; - } - - if (match.credits_must_not_exceed_debits) |b| { - if (account.flags.credits_must_not_exceed_debits != b) continue; - } - - if (match.exclude) |exclude_id| { - if (account.id == exclude_id) continue; - } - return account; - } - return null; - } - - pub fn on_get_change_events( - self: *AccountingAuditor, - timestamp: u64, - filter: tb.ChangeEventsFilter, - results: []const tb.ChangeEvent, - ) void { - _ = timestamp; - const filter_valid = filter.limit != 0 and - TimestampRange.valid(filter.timestamp_min) and - TimestampRange.valid(filter.timestamp_max) and - stdx.zeroed(&filter.reserved) and - (filter.timestamp_max == 0 or filter.timestamp_min <= filter.timestamp_max); - if (!filter_valid) { - assert(results.len == 0); - return; - } - - const snapshot = self.changes_tracker.release_snapshot(); - assert(filter.limit >= snapshot.count_total()); - assert(filter.timestamp_min == snapshot.timestamp_min); - assert(filter.timestamp_max == snapshot.timestamp_max); - assert(results.len == snapshot.count_total()); - - var timestamp_previous: u64 = 0; - var count = ChangesTracker.EnumArray.initFill(0); - for (results) |*result| { - assert(result.timestamp > timestamp_previous); - timestamp_previous = result.timestamp; - - if (filter.timestamp_min > 0) { - assert(result.timestamp >= filter.timestamp_min); - } - if (filter.timestamp_max > 0) { - assert(result.timestamp <= filter.timestamp_max); - } - - count.getPtr(result.type).* += 1; - } - - var iterator = count.iterator(); - while (iterator.next()) |kv| { - const expected = snapshot.count.getPtrConst(kv.key).*; - assert(kv.value.* == expected); - } - } - - pub fn account_id_to_index(self: *const AccountingAuditor, id: u128) usize { - // -1 because id=0 is not valid, so index=0→id=1. - return @as(usize, @intCast(self.options.account_id_permutation.decode(id))) - 1; - } - - pub fn account_index_to_id(self: *const AccountingAuditor, index: usize) u128 { - // +1 so that index=0 is encoded as a valid id. - return self.options.account_id_permutation.encode(index + 1); - } - - pub fn get_account(self: *const AccountingAuditor, id: u128) ?*const tb.Account { - const index = self.account_id_to_index(id); - return if (index < self.accounts.len) &self.accounts[index] else null; - } - - pub fn get_account_state(self: *const AccountingAuditor, id: u128) ?*const AccountState { - const index = self.account_id_to_index(id); - return if (index < self.accounts_state.len) &self.accounts_state[index] else null; - } - - fn take_in_flight(self: *AccountingAuditor, client_index: usize) InFlight { - const key: InFlightKey = .{ - .client_index = client_index, - .client_request = self.creates_delivered[client_index], - }; - self.creates_delivered[client_index] += 1; - - const in_flight = self.in_flight.get(key).?; - assert(self.in_flight.remove(key)); - return in_flight; - } -}; - -pub fn ResultsSparseIteratorType(comptime Result: type) type { - assert(Result == tb.CreateAccountErrorResult or Result == tb.CreateTransferErrorResult); - - return struct { - const IteratorForCreate = @This(); - - results: []const Result, - - pub fn init(results: []const Result) IteratorForCreate { - return .{ .results = results }; - } - - pub fn take( - self: *IteratorForCreate, - event_index: usize, - ) ?@FieldType(Result, "result") { - if (self.results.len > 0 and self.results[0].index == event_index) { - defer self.results = self.results[1..]; - - return self.results[0].result; - } else { - return null; - } - } - }; -} - -pub fn IteratorForLookupType(comptime Result: type) type { - assert(Result == tb.Account or Result == tb.Transfer); - - return struct { - const IteratorForLookup = @This(); - - results: []const Result, - - pub fn init(results: []const Result) IteratorForLookup { - return .{ .results = results }; - } - - pub fn take(self: *IteratorForLookup, id: u128) ?*const Result { - if (self.results.len > 0 and self.results[0].id == id) { - defer self.results = self.results[1..]; - - return &self.results[0]; - } else { - return null; - } - } - }; -} diff --git a/ocam/src/state_machine/workload.zig b/ocam/src/state_machine/workload.zig deleted file mode 100644 index 6af099d7..00000000 --- a/ocam/src/state_machine/workload.zig +++ /dev/null @@ -1,2190 +0,0 @@ -//! The Workload drives an end-to-end test: from client requests, through consensus and the state -//! machine, down to the storage engine, and back. -//! -//! The Workload constructs messages to create and query accounts and transfers, and validates the -//! replies. -//! -//! Goals: -//! -//! * Run in a fixed amount of memory. (For long-running tests or performance testing). -//! * Query and verify transfers arbitrarily far back. (To exercise the storage engine). -//! -//! Transfer Encoding: -//! -//! * `Transfer.id` is a deterministic, reversible permutation of an ascending index. -//! * With the transfer's index as a seed, the Workload knows the eventual outcome of the transfer. -//! * `Transfer.user_data` is a checksum of the remainder of the transfer's data -//! (excluding `timestamp` and `user_data` itself). This helps `on_lookup_transfers` to -//! validate its results. -//! -const std = @import("std"); -const assert = std.debug.assert; - -const stdx = @import("stdx"); -const maybe = stdx.maybe; -const Ratio = stdx.PRNG.Ratio; -const ratio = stdx.PRNG.ratio; - -const constants = @import("../constants.zig"); -const tb = @import("../tigerbeetle.zig"); -const vsr = @import("../vsr.zig"); -const accounting_auditor = @import("auditor.zig"); -const Auditor = accounting_auditor.AccountingAuditor; -const ResultsSparseIteratorType = accounting_auditor.ResultsSparseIteratorType; -const IdPermutation = @import("../testing/id.zig").IdPermutation; -const TimestampRange = @import("../lsm/timestamp_range.zig").TimestampRange; -const fuzz = @import("../testing/fuzz.zig"); - -const PriorityQueue = std.PriorityQueue; - -const TransferOutcome = enum { - /// The transfer is guaranteed to commit. - /// For example, a single-phase transfer between valid accounts without balance limits. - success, - /// The transfer is invalid. For example, the `ledger` field is missing. - failure, - /// Due to races with timeouts or other transfers, the outcome of the transfer is uncertain. - /// For example, post/void-pending transfers race with their timeout. - unknown, -}; - -/// A Transfer generated from the plan is guaranteed to have a matching `outcome`, but it may use a -/// different Method. (For example, `method=pending` may fall back to `method=single_phase` if the -/// Auditor's pending transfer queue is full). -const TransferPlan = struct { - /// When false, send invalid payments that are guaranteed to be rejected with an error. - valid: bool, - - /// When `limit` is set, at least one of the following is true: - /// - /// * the debit account has debits_must_not_exceed_credits - /// * the credit account has credits_must_not_exceed_debits - /// - limit: bool, - - method: Method, - - const Method = enum { - single_phase, - pending, - post_pending, - void_pending, - }; - - fn outcome(self: TransferPlan) TransferOutcome { - if (!self.valid) return .failure; - if (self.limit) return .unknown; - return switch (self.method) { - .single_phase, .pending => .success, - .post_pending, .void_pending => .unknown, - }; - } -}; - -const TransferTemplate = struct { - ledger: u32, - result: accounting_auditor.CreateTransferStatusSet, -}; - -const TransferBatchQueue = PriorityQueue(TransferBatch, void, struct { - /// Ascending order. - fn compare(_: void, a: TransferBatch, b: TransferBatch) std.math.Order { - assert(a.min != b.min); - assert(a.max != b.max); - return std.math.order(a.min, b.min); - } -}.compare); - -const TransferBatch = struct { - /// Index of the first transfer in the batch. - min: usize, - /// Index of the last transfer in the batch. - max: usize, -}; - -/// Indexes: [valid:bool][limit:bool][method] -const transfer_templates = table: { - @setEvalBranchQuota(4_000); - - const SNGL = @intFromEnum(TransferPlan.Method.single_phase); - const PEND = @intFromEnum(TransferPlan.Method.pending); - const POST = @intFromEnum(TransferPlan.Method.post_pending); - const VOID = @intFromEnum(TransferPlan.Method.void_pending); - const Result = accounting_auditor.CreateTransferStatusSet; - const result = Result.init; - - const InitValues = std.enums.EnumFieldStruct( - tb.CreateTransferStatus.Ordered, - bool, - false, - ); - const two_phase_ok: InitValues = .{ - .created = true, - .pending_transfer_already_posted = true, - .pending_transfer_already_voided = true, - .pending_transfer_expired = true, - }; - - const limits = result(.{ - .exceeds_credits = true, - .exceeds_debits = true, - }); - - const either = struct { - fn either(a: Result, b: Result) Result { - var c = a; - c.setUnion(b); - return c; - } - }.either; - - const template = struct { - fn template(ledger: u32, transfer_result: Result) TransferTemplate { - return .{ - .ledger = ledger, - .result = transfer_result, - }; - } - }.template; - - // [valid:bool][limit:bool][method] - var templates: [2][2][std.meta.fields(TransferPlan.Method).len]TransferTemplate = undefined; - - // template(ledger, result) - templates[0][0][SNGL] = template(0, result(.{ .ledger_must_not_be_zero = true })); - templates[0][0][PEND] = template(0, result(.{ .ledger_must_not_be_zero = true })); - templates[0][0][POST] = template(9, result(.{ .pending_transfer_has_different_ledger = true })); - templates[0][0][VOID] = template(9, result(.{ .pending_transfer_has_different_ledger = true })); - - templates[0][1][SNGL] = template(0, result(.{ .ledger_must_not_be_zero = true })); - templates[0][1][PEND] = template(0, result(.{ .ledger_must_not_be_zero = true })); - templates[0][1][POST] = template(9, result(.{ .pending_transfer_has_different_ledger = true })); - templates[0][1][VOID] = template(9, result(.{ .pending_transfer_has_different_ledger = true })); - - templates[1][0][SNGL] = template(1, result(.{ .created = true })); - templates[1][0][PEND] = template(1, result(.{ .created = true })); - templates[1][0][POST] = template(1, result(two_phase_ok)); - templates[1][0][VOID] = template(1, result(two_phase_ok)); - - templates[1][1][SNGL] = template(1, either(limits, result(.{ .created = true }))); - templates[1][1][PEND] = template(1, either(limits, result(.{ .created = true }))); - templates[1][1][POST] = template(1, either(limits, result(two_phase_ok))); - templates[1][1][VOID] = template(1, either(limits, result(two_phase_ok))); - - break :table templates; -}; - -pub fn WorkloadType(comptime AccountingStateMachine: type) type { - const Operation = AccountingStateMachine.Operation; - - const Action = enum(u8) { - create_accounts = @intFromEnum(Operation.create_accounts), - create_transfers = @intFromEnum(Operation.create_transfers), - lookup_accounts = @intFromEnum(Operation.lookup_accounts), - lookup_transfers = @intFromEnum(Operation.lookup_transfers), - get_account_transfers = @intFromEnum(Operation.get_account_transfers), - get_account_balances = @intFromEnum(Operation.get_account_balances), - query_accounts = @intFromEnum(Operation.query_accounts), - query_transfers = @intFromEnum(Operation.query_transfers), - get_change_events = @intFromEnum(Operation.get_change_events), - - deprecated_create_accounts_sparse = @intFromEnum( - Operation.deprecated_create_accounts_sparse, - ), - deprecated_create_transfers_sparse = @intFromEnum( - Operation.deprecated_create_transfers_sparse, - ), - deprecated_create_accounts_unbatched = @intFromEnum( - Operation.deprecated_create_accounts_unbatched, - ), - deprecated_create_transfers_unbatched = @intFromEnum( - Operation.deprecated_create_transfers_unbatched, - ), - deprecated_lookup_accounts_unbatched = @intFromEnum( - Operation.deprecated_lookup_accounts_unbatched, - ), - deprecated_lookup_transfers_unbatched = @intFromEnum( - Operation.deprecated_lookup_transfers_unbatched, - ), - deprecated_get_account_transfers_unbatched = @intFromEnum( - Operation.deprecated_get_account_transfers_unbatched, - ), - deprecated_get_account_balances_unbatched = @intFromEnum( - Operation.deprecated_get_account_balances_unbatched, - ), - deprecated_query_accounts_unbatched = @intFromEnum( - Operation.deprecated_query_accounts_unbatched, - ), - deprecated_query_transfers_unbatched = @intFromEnum( - Operation.deprecated_query_transfers_unbatched, - ), - }; - - const Lookup = enum { - /// Query a transfer that has either been committed or rejected. - delivered, - /// Query a transfer whose `create_transfers` is in-flight. - sending, - }; - - return struct { - const Workload = @This(); - - pub const Options = OptionsType(AccountingStateMachine, Action, Lookup); - - prng: *stdx.PRNG, - auditor: Auditor, - options: Options, - - transfer_plan_seed: u64, - - /// Whether a `create_accounts` message has ever been sent. - accounts_sent: bool = false, - - /// The index of the next transfer to send. - transfers_sent: usize = 0, - - /// All transfers below this index have been delivered. - /// Any transfers above this index that have been delivered are stored in - /// `transfers_delivered_recently`. - transfers_delivered_past: usize = 0, - - /// Track index ranges of `create_transfers` batches that have committed but are greater - /// than or equal to `transfers_delivered_past` (which is still in-flight). - transfers_delivered_recently: TransferBatchQueue, - - /// Track the number of pending transfers that have been sent but not committed. - transfers_pending_in_flight: usize = 0, - - /// Transfers that succeeded and must result in `exists` when retried. - transfers_retry_exists: std.ArrayListUnmanaged(tb.Transfer), - - /// IDs of transfers that failed with transient codes - /// and must result in `id_already_failed` when retried. - transfers_retry_failed: std.AutoArrayHashMapUnmanaged(u128, void), - - pub fn init( - allocator: std.mem.Allocator, - prng: *stdx.PRNG, - options: Options, - ) !Workload { - assert(options.accounts_batch_size_span + options.accounts_batch_size_min <= - AccountingStateMachine.batch_max.create_accounts); - assert(options.accounts_batch_size_span >= 1); - assert(options.transfers_batch_size_span + options.transfers_batch_size_min <= - AccountingStateMachine.batch_max.create_transfers); - assert(options.transfers_batch_size_span >= 1); - - var auditor = try Auditor.init(allocator, prng, options.auditor_options); - errdefer auditor.deinit(allocator); - - var transfers_delivered_recently = TransferBatchQueue.init(allocator, {}); - errdefer transfers_delivered_recently.deinit(); - try transfers_delivered_recently.ensureTotalCapacity( - options.auditor_options.client_count * constants.client_request_queue_max, - ); - - for (auditor.accounts, 0..) |*account, i| { - const query_intersection = - auditor.query_intersections[prng.index(auditor.query_intersections)]; - - account.* = std.mem.zeroInit(tb.Account, .{ - .id = auditor.account_index_to_id(i), - .user_data_64 = query_intersection.user_data_64, - .user_data_32 = query_intersection.user_data_32, - .code = query_intersection.code, - .ledger = 1, - }); - - if (prng.chance(options.account_limit_probability)) { - const b = prng.boolean(); - account.flags.debits_must_not_exceed_credits = b; - account.flags.credits_must_not_exceed_debits = !b; - } - - account.flags.history = prng.chance(options.account_history_probability); - } - - var transfers_retry_failed: std.AutoArrayHashMapUnmanaged(u128, void) = .{}; - try transfers_retry_failed.ensureTotalCapacity( - allocator, - options.transfers_retry_failed_max, - ); - errdefer transfers_retry_failed.deinit(allocator); - - var transfers_retry_exists: std.ArrayListUnmanaged(tb.Transfer) = try .initCapacity( - allocator, - options.transfers_retry_exists_max, - ); - errdefer transfers_retry_exists.deinit(allocator); - - return .{ - .prng = prng, - .auditor = auditor, - .options = options, - .transfer_plan_seed = prng.int(u64), - .transfers_delivered_recently = transfers_delivered_recently, - .transfers_retry_failed = transfers_retry_failed, - .transfers_retry_exists = transfers_retry_exists, - }; - } - - pub fn deinit(self: *Workload, allocator: std.mem.Allocator) void { - self.auditor.deinit(allocator); - self.transfers_delivered_recently.deinit(); - self.transfers_retry_failed.deinit(allocator); - self.transfers_retry_exists.deinit(allocator); - } - - pub fn done(self: *const Workload) bool { - if (self.transfers_delivered_recently.len != 0) return false; - return self.auditor.done(); - } - - /// A client may build multiple requests to queue up while another is in-flight. - pub fn build_request( - self: *Workload, - client_index: usize, - body_buffer: []align(constants.cache_line_size) u8, - ) struct { - operation: Operation, - size: usize, - } { - assert(client_index < self.auditor.options.client_count); - assert(body_buffer.len == constants.message_body_size_max); - - const action = action: { - if (!self.accounts_sent and self.prng.boolean()) { - // Early in the test make sure some accounts get created. - self.accounts_sent = true; - break :action .create_accounts; - } - - break :action self.prng.enum_weighted(Action, self.options.operations); - }; - - const operation: Operation = @enumFromInt(@intFromEnum(action)); - const event_size: u32 = operation.event_size(); - const event_max: u32 = operation.event_max(self.options.batch_size_limit); - assert(event_max > 0); - assert(body_buffer.len >= event_size * event_max); - - const result_size: u32 = operation.result_size(); - const result_max = operation.result_max(self.options.batch_size_limit); - assert(result_max > 0); - assert(constants.message_body_size_max >= - result_size * result_max); - - if (!operation.is_multi_batch()) { - const size = self.build_request_batch( - client_index, - action, - body_buffer, - event_max, - ); - assert(size <= body_buffer.len); - return .{ - .operation = operation, - .size = size, - }; - } - assert(operation.is_multi_batch()); - - var body_encoder = vsr.multi_batch.MultiBatchEncoder.init( - body_buffer[0..self.options.batch_size_limit], - .{ - .element_size = event_size, - }, - ); - var event_count: u32 = 0; - var result_count: u32 = 0; - for (0..self.options.multi_batch_per_request_limit) |_| { - const writable = body_encoder.writable() orelse break; - if (writable.len == 0) break; - - const event_count_remain: u32 = - if (operation.is_batchable()) - event_max - event_count - else - 1; - const batch_size = self.build_request_batch( - client_index, - action, - writable, - event_count_remain, - ); - assert(batch_size <= writable.len); - - // Checking if the expected result will fit in the multi-batch reply. - const reply_trailer_size: u32 = vsr.multi_batch.trailer_total_size(.{ - .element_size = result_size, - .batch_count = body_encoder.batch_count + 1, - }); - const result_count_expected: u32 = - operation.result_count_expected(writable[0..batch_size]); - const reply_message_size: u32 = - ((result_count + result_count_expected) * result_size) + reply_trailer_size; - if (reply_message_size > constants.message_body_size_max) { - // For operations that produce 1:1 result per event - // (e.g., `create_*` and `lookup_*`), this was already validated - // when checking if `event_count` fits within the multi-batch request. - // For queries, this means the reply size cannot fit within the same message. - assert(body_encoder.batch_count > 0); - assert(!operation.is_batchable()); - break; - } - assert(result_count + result_count_expected <= result_max); - - body_encoder.add(@intCast(batch_size)); - event_count += @intCast(@divExact(batch_size, event_size)); - assert(event_count <= event_max); - - result_count += result_count_expected; - assert(result_count <= result_max); - - // Maybe single-batch request. - if (body_encoder.batch_count == 1 and self.prng.boolean()) break; - } - maybe(event_count == 0); - assert(result_count == 0 or event_count > 0); - assert(body_encoder.batch_count > 0); - assert(body_encoder.batch_count <= self.options.multi_batch_per_request_limit); - - const bytes_written = body_encoder.finish(); - assert(bytes_written <= self.options.batch_size_limit); - - return .{ - .operation = operation, - .size = bytes_written, - }; - } - - fn build_request_batch( - self: *Workload, - client_index: usize, - action: Action, - body: []u8, - batch_limit: u32, - ) usize { - switch (action) { - inline else => |action_comptime| { - const operation_comptime: Operation = comptime @enumFromInt(@intFromEnum( - action_comptime, - )); - const Event = operation_comptime.EventType(); - const event_size: u32 = operation_comptime.event_size(); - const batchable: []Event = self.batch( - Event, - action_comptime, - body, - batch_limit, - ); - assert(batchable.len <= batch_limit); - - const count = switch (action_comptime) { - .create_accounts, - .deprecated_create_accounts_sparse, - .deprecated_create_accounts_unbatched, - => self.build_create_accounts( - client_index, - batchable, - ), - .create_transfers, - .deprecated_create_transfers_sparse, - .deprecated_create_transfers_unbatched, - => self.build_create_transfers( - client_index, - batchable, - ), - .lookup_accounts, - .deprecated_lookup_accounts_unbatched, - => self.build_lookup_accounts(batchable), - .lookup_transfers, - .deprecated_lookup_transfers_unbatched, - => self.build_lookup_transfers(batchable), - .get_account_transfers, - .get_account_balances, - .deprecated_get_account_transfers_unbatched, - .deprecated_get_account_balances_unbatched, - => self.build_get_account_filter( - client_index, - action_comptime, - batchable, - ), - .query_accounts, - .query_transfers, - .deprecated_query_accounts_unbatched, - .deprecated_query_transfers_unbatched, - => self.build_query_filter( - client_index, - action_comptime, - batchable, - ), - .get_change_events => self.build_get_change_events_filter( - client_index, - batchable, - ), - }; - assert(count <= batchable.len); - assert(count <= batch_limit); - - const batch_size: usize = count * event_size; - assert(batch_size <= body.len); - maybe(batch_size == 0); - return batch_size; - }, - } - } - - /// `on_reply` is called for replies in commit order. - pub fn on_reply( - self: *Workload, - client_index: usize, - operation: Operation, - timestamp: u64, - request_body: []align(constants.cache_line_size) const u8, - reply_body: []align(constants.cache_line_size) const u8, - ) void { - assert(timestamp != 0); - assert(request_body.len <= constants.message_body_size_max); - assert(reply_body.len <= constants.message_body_size_max); - - if (!operation.is_multi_batch()) { - return self.on_reply_batch( - client_index, - operation, - timestamp, - request_body, - reply_body, - ); - } - assert(operation.is_multi_batch()); - - const event_size: u32 = operation.event_size(); - const result_size: u32 = operation.result_size(); - var body_decoder = vsr.multi_batch.MultiBatchDecoder.init(request_body, .{ - .element_size = event_size, - }) catch unreachable; - assert(body_decoder.batch_count() > 0); - var reply_decoder = vsr.multi_batch.MultiBatchDecoder.init(reply_body, .{ - .element_size = result_size, - }) catch unreachable; - assert(reply_decoder.batch_count() > 0); - assert(body_decoder.batch_count() == reply_decoder.batch_count()); - - const prepare_nanoseconds = struct { - fn prepare_nanoseconds( - operation_inner: Operation, - input_len: usize, - batch_size_limit: u32, - ) u64 { - return switch (operation_inner) { - .pulse => Operation.create_transfers.event_max( - batch_size_limit, - ), - .create_accounts, - .deprecated_create_accounts_sparse, - => @divExact(input_len, @sizeOf(tb.Account)), - .create_transfers, - .deprecated_create_transfers_sparse, - => @divExact(input_len, @sizeOf(tb.Transfer)), - .lookup_accounts => 0, - .lookup_transfers => 0, - .get_account_transfers => 0, - .get_account_balances => 0, - .query_accounts => 0, - .query_transfers => 0, - .get_change_events => 0, - else => unreachable, - }; - } - }.prepare_nanoseconds; - var batch_timestamp: u64 = timestamp - prepare_nanoseconds( - operation, - body_decoder.payload.len, - self.options.batch_size_limit, - ); - while (body_decoder.pop()) |batch_body| { - const batch_reply = reply_decoder.pop().?; - batch_timestamp += prepare_nanoseconds( - operation, - batch_body.len, - self.options.batch_size_limit, - ); - self.on_reply_batch( - client_index, - operation, - batch_timestamp, - batch_body, - batch_reply, - ); - } - assert(reply_decoder.pop() == null); - } - - pub fn on_reply_batch( - self: *Workload, - client_index: usize, - operation: Operation, - timestamp: u64, - request_body: []const u8, - reply_body: []const u8, - ) void { - switch (operation) { - .create_accounts, - => self.auditor.on_create_accounts( - client_index, - timestamp, - stdx.bytes_as_slice(.exact, tb.Account, request_body), - stdx.bytes_as_slice(.exact, tb.CreateAccountResult, reply_body), - ), - .deprecated_create_accounts_sparse, - .deprecated_create_accounts_unbatched, - => self.auditor.on_create_accounts_sparse( - client_index, - timestamp, - stdx.bytes_as_slice(.exact, tb.Account, request_body), - stdx.bytes_as_slice(.exact, tb.CreateAccountErrorResult, reply_body), - ), - .create_transfers, - => self.on_create_transfers( - client_index, - timestamp, - stdx.bytes_as_slice(.exact, tb.Transfer, request_body), - stdx.bytes_as_slice(.exact, tb.CreateTransferResult, reply_body), - ), - .deprecated_create_transfers_sparse, - .deprecated_create_transfers_unbatched, - => self.on_create_transfers_sparse( - client_index, - timestamp, - stdx.bytes_as_slice(.exact, tb.Transfer, request_body), - stdx.bytes_as_slice(.exact, tb.CreateTransferErrorResult, reply_body), - ), - .lookup_accounts, - .deprecated_lookup_accounts_unbatched, - => self.auditor.on_lookup_accounts( - client_index, - timestamp, - stdx.bytes_as_slice(.exact, u128, request_body), - stdx.bytes_as_slice(.exact, tb.Account, reply_body), - ), - .lookup_transfers, - .deprecated_lookup_transfers_unbatched, - => self.on_lookup_transfers( - client_index, - timestamp, - stdx.bytes_as_slice(.exact, u128, request_body), - stdx.bytes_as_slice(.exact, tb.Transfer, reply_body), - ), - inline .get_account_transfers, - .deprecated_get_account_transfers_unbatched, - => |operation_comptime| self.on_get_account_transfers( - operation_comptime, - timestamp, - stdx.bytes_as_slice(.exact, tb.AccountFilter, request_body), - stdx.bytes_as_slice(.exact, tb.Transfer, reply_body), - ), - inline .get_account_balances, - .deprecated_get_account_balances_unbatched, - => |operation_comptime| self.on_get_account_balances( - operation_comptime, - timestamp, - stdx.bytes_as_slice(.exact, tb.AccountFilter, request_body), - stdx.bytes_as_slice(.exact, tb.AccountBalance, reply_body), - ), - inline .query_accounts, - .deprecated_query_accounts_unbatched, - => |operation_comptime| self.on_query( - operation_comptime, - timestamp, - stdx.bytes_as_slice(.exact, tb.QueryFilter, request_body), - stdx.bytes_as_slice(.exact, tb.Account, reply_body), - ), - inline .query_transfers, - .deprecated_query_transfers_unbatched, - => |operation_comptime| self.on_query( - operation_comptime, - timestamp, - stdx.bytes_as_slice(.exact, tb.QueryFilter, request_body), - stdx.bytes_as_slice(.exact, tb.Transfer, reply_body), - ), - .get_change_events => self.on_get_change_events( - timestamp, - stdx.bytes_as_slice(.exact, tb.ChangeEventsFilter, request_body), - stdx.bytes_as_slice(.exact, tb.ChangeEvent, reply_body), - ), - //Not handled by the client. - .pulse => unreachable, - } - } - - /// `on_pulse` is called for pulse operations in commit order. - pub fn on_pulse( - self: *Workload, - operation: Operation, - timestamp: u64, - ) void { - assert(timestamp != 0); - assert(operation == .pulse); - - self.auditor.expire_pending_transfers(timestamp); - } - - fn build_create_accounts( - self: *Workload, - client_index: usize, - accounts: []tb.Account, - ) usize { - const results = self.auditor.expect_create_accounts(client_index); - for (accounts, 0..) |*account, i| { - const account_index = self.prng.index(self.auditor.accounts); - account.* = self.auditor.accounts[account_index]; - account.debits_pending = 0; - account.debits_posted = 0; - account.credits_pending = 0; - account.credits_posted = 0; - account.timestamp = 0; - results[i] = accounting_auditor.CreateAccountStatusSet{}; - - if (self.prng.chance(self.options.create_account_invalid_probability)) { - account.ledger = 0; - // The result depends on whether the id already exists: - results[i].insert(.exists_with_different_ledger); - results[i].insert(.ledger_must_not_be_zero); - } else { - if (!self.auditor.accounts_state[account_index].created) { - results[i].insert(.created); - } - // Even if the account doesn't exist yet, we may race another request. - results[i].insert(.exists); - } - assert(results[i].count() > 0); - } - return accounts.len; - } - - fn build_create_transfers( - self: *Workload, - client_index: usize, - transfers: []tb.Transfer, - ) usize { - const results = self.auditor.expect_create_transfers(client_index); - assert(results.len >= transfers.len); - var transfers_count: usize = transfers.len; - var i: usize = 0; - while (i < transfers_count) { - const transfer_index = self.transfers_sent; - const transfer_plan = self.transfer_index_to_plan(transfer_index); - const transfer_id = self.transfer_index_to_id(transfer_index); - results[i] = self.build_transfer( - transfer_id, - transfer_plan, - &transfers[i], - ) orelse { - // This transfer index can't be built; stop with what we have so far. - // Hopefully it will be unblocked before the next `create_transfers`. - transfers_count = i; - break; - }; - - if (i != 0 and results[i].count() == 1 and results[i - 1].count() == 1) { - // To support random `lookup_transfers`, linked transfers can't be planned. - // Instead, link transfers opportunistically, when consecutive transfers can be - // linked without altering any of their outcomes. - - if (results[i].contains(.created) and results[i - 1].contains(.created) and - self.prng.chance(self.options.linked_valid_probability)) - { - transfers[i - 1].flags.linked = true; - } - - if (!results[i].contains(.created) and !results[i - 1].contains(.created) and - self.prng.chance(self.options.linked_invalid_probability)) - { - // Convert the previous transfer to a single-phase no-limit transfer, but - // link it to the current transfer — it will still fail. - const result_set_opt = self.build_transfer(transfers[i - 1].id, .{ - .valid = true, - .limit = false, - .method = .single_phase, - }, &transfers[i - 1]); - if (result_set_opt) |result_set| { - assert(result_set.count() == 1); - assert(result_set.contains(.created)); - - transfers[i - 1].flags.linked = true; - results[i - 1] = accounting_auditor.CreateTransferStatusSet.init(.{ - .linked_event_failed = true, - }); - } - } - } - assert(results[i].count() > 0); - - if (transfers[i].flags.pending) self.transfers_pending_in_flight += 1; - i += 1; - self.transfers_sent += 1; - } - assert(transfers_count == i); - assert(transfers_count <= transfers.len); - - self.build_retry_transfers(transfers[0..transfers_count], results); - - // Checksum transfers only after the whole batch is ready. - // The opportunistic linking backtracks to modify transfers. - for (transfers[0..transfers_count]) |*transfer| { - transfer.user_data_128 = vsr.checksum(std.mem.asBytes(transfer)); - } - - return transfers_count; - } - - fn build_retry_transfers( - self: *Workload, - transfers: []tb.Transfer, - results: []accounting_auditor.CreateTransferStatusSet, - ) void { - assert(results.len >= transfers.len); - - // Neither the first nor the last id can regress to preserve the - // `transfers_delivered_recently` and `transfers_delivered_past` logic. - // So we must insert retries in the middle of the batch. - if (transfers.len <= 1) return; - for (1..transfers.len - 1) |i| { - if (self.transfers_retry_exists.items.len == 0 and - self.transfers_retry_failed.count() == 0) break; - - // To support random `lookup_transfers`, we replace the transfer with a retry, - // without altering the outcome for this specific `transfer_index`. - const transfer_index = self.transfer_id_to_index(transfers[i].id); - const transfer_plan = self.transfer_index_to_plan(transfer_index); - const can_retry = !transfer_plan.valid and - !transfers[i].flags.linked and - !transfers[i - 1].flags.linked; - if (can_retry and - self.prng.chance(self.options.create_transfer_retry_probability)) - { - switch (self.prng.chances(.{ - .exists = @intFromBool(self.transfers_retry_exists.items.len > 0), - .failed = @intFromBool(self.transfers_retry_failed.count() > 0), - })) { - .exists => { - // Retry a successfully completed transfer, result == `exists`. - const index = self.prng.index(self.transfers_retry_exists.items); - transfers[i] = self.transfers_retry_exists.swapRemove(index); - results[i] = .initOne(.exists); - }, - .failed => { - // Retry a failed transfer ID, result == `id_already_failed`. - const index = self.prng.index(self.transfers_retry_failed.keys()); - const id_failed = self.transfers_retry_failed.keys()[index]; - self.transfers_retry_failed.swapRemoveAt(index); - transfers[i] = std.mem.zeroInit(tb.Transfer, .{ .id = id_failed }); - results[i] = .initOne(.id_already_failed); - }, - } - } - } - } - - fn build_lookup_accounts(self: *Workload, lookup_ids: []u128) usize { - for (lookup_ids) |*id| { - if (self.prng.chance(self.options.lookup_account_invalid_probability)) { - // Pick an account with valid index (rather than "random.int(u128)") because the - // Auditor must decode the id to check for a matching account. - id.* = self.auditor.account_index_to_id(self.prng.int(usize)); - } else { - const account_index = self.prng.index(self.auditor.accounts); - id.* = self.auditor.accounts[account_index].id; - } - } - return lookup_ids.len; - } - - fn build_lookup_transfers(self: *const Workload, lookup_ids: []u128) usize { - const delivered = self.transfers_delivered_past; - const lookup_window = self.prng.enum_weighted(Lookup, self.options.lookup_transfer); - const lookup_window_start = switch (lookup_window) { - .delivered => self.prng.int_inclusive(usize, delivered), - .sending => self.prng.range_inclusive( - usize, - delivered, - self.transfers_sent, - ), - }; - - // +1 to make the span-max inclusive. - const lookup_window_size = @min( - fuzz.random_int_exponential( - self.prng, - usize, - self.options.lookup_transfer_span_mean, - ), - self.transfers_sent - lookup_window_start, - ); - if (lookup_window_size == 0) return 0; - - for (lookup_ids) |*lookup_id| { - lookup_id.* = self.transfer_index_to_id( - lookup_window_start + self.prng.int_inclusive(usize, lookup_window_size - 1), - ); - } - return lookup_ids.len; - } - - fn build_get_account_filter( - self: *const Workload, - client_index: usize, - comptime action: Action, - body: []tb.AccountFilter, - ) usize { - _ = client_index; - comptime assert(action == .get_account_transfers or - action == .get_account_balances or - action == .deprecated_get_account_transfers_unbatched or - action == .deprecated_get_account_balances_unbatched); - assert(body.len == 1); - const account_filter = &body[0]; - account_filter.* = tb.AccountFilter{ - .account_id = 0, - .user_data_128 = 0, - .user_data_64 = 0, - .user_data_32 = 0, - .code = 0, - .limit = 0, - .flags = .{ - .credits = false, - .debits = false, - .reversed = false, - }, - .timestamp_min = 0, - .timestamp_max = 0, - }; - - account_filter.account_id = if (self.auditor.pick_account(.{ - .created = null, - .debits_must_not_exceed_credits = null, - .credits_must_not_exceed_debits = null, - })) |account| account.id else - // Pick an account with valid index (rather than "random.int(u128)") because the - // Auditor must decode the id to check for a matching account. - self.auditor.account_index_to_id(self.prng.int(usize)); - - // It may be an invalid account. - const account_state: ?*const Auditor.AccountState = self.auditor.get_account_state( - account_filter.account_id, - ); - - account_filter.flags.reversed = self.prng.boolean(); - - const operation = comptime std.enums.nameCast(Operation, action); - const batch_result_max = operation.result_max(self.options.batch_size_limit); - - // The timestamp range is restrictive to the number of transfers inserted at the - // moment the filter was generated. Only when this filter is in place we can assert - // the expected result count. - if (account_state != null and - self.prng.chance(self.options.account_filter_timestamp_range_probability)) - { - account_filter.flags.credits = true; - account_filter.flags.debits = true; - account_filter.limit = @min( - account_state.?.transfers_count(account_filter.flags), - batch_result_max, - ); - account_filter.timestamp_min = account_state.?.transfer_timestamp_min; - account_filter.timestamp_max = account_state.?.transfer_timestamp_max; - - // Exclude the first or the last result depending on the sort order, - // if there are more than one single transfer. - account_filter.timestamp_min += @intFromBool(!account_filter.flags.reversed); - account_filter.timestamp_max -|= @intFromBool(account_filter.flags.reversed); - } else { - switch (self.prng.enum_uniform(enum { none, debits, credits, all })) { - .none => {}, // Testing invalid flags. - .debits => account_filter.flags.debits = true, - .credits => account_filter.flags.credits = true, - .all => { - account_filter.flags.debits = true; - account_filter.flags.credits = true; - }, - } - - account_filter.limit = switch (self.prng.enum_uniform(enum { - zero, - one, - random, - batch_max, - })) { - .zero => 0, - .one => 1, - .random => self.prng.int_inclusive(u32, batch_result_max), - .batch_max => batch_result_max, - }; - } - - return 1; - } - - fn build_query_filter( - self: *const Workload, - client_index: usize, - comptime action: Action, - body: []tb.QueryFilter, - ) usize { - _ = client_index; - comptime assert(action == .query_accounts or - action == .query_transfers or - action == .deprecated_query_accounts_unbatched or - action == .deprecated_query_transfers_unbatched); - assert(body.len == 1); - const query_filter = &body[0]; - - const operation = comptime std.enums.nameCast(Operation, action); - const batch_result_max = operation.result_max(self.options.batch_size_limit); - const limit: u32 = switch (self.prng.enum_uniform(enum { - zero, - one, - random, - batch_max, - })) { - .zero => 0, - .one => 1, - .random => self.prng.int_inclusive(u32, batch_result_max), - .batch_max => batch_result_max, - }; - - if (self.prng.chance(self.options.query_filter_not_found_probability)) { - query_filter.* = .{ - .user_data_128 = 0, - .user_data_64 = 0, - .user_data_32 = 0, - .code = 0, - .ledger = 999, // Non-existent ledger - .limit = limit, - .flags = .{ - .reversed = false, - }, - .timestamp_min = 0, - .timestamp_max = 0, - }; - } else { - const query_intersection_index = self.prng.index(self.auditor.query_intersections); - const query_intersection = - self.auditor.query_intersections[query_intersection_index]; - - query_filter.* = .{ - .user_data_128 = 0, - .user_data_64 = query_intersection.user_data_64, - .user_data_32 = query_intersection.user_data_32, - .code = query_intersection.code, - .ledger = 0, - .limit = limit, - .flags = .{ - .reversed = self.prng.boolean(), - }, - .timestamp_min = 0, - .timestamp_max = 0, - }; - - // Maybe filter by timestamp: - const state = switch (action) { - .query_accounts, - .deprecated_query_accounts_unbatched, - => &query_intersection.accounts, - .query_transfers, - .deprecated_query_transfers_unbatched, - => &query_intersection.transfers, - else => unreachable, - }; - - if (state.count > 1 and state.count <= batch_result_max and - self.prng.chance(self.options.query_filter_timestamp_range_probability)) - { - // Excluding the first or last object: - if (query_filter.flags.reversed) { - query_filter.timestamp_min = state.timestamp_min; - query_filter.timestamp_max = state.timestamp_max - 1; - } else { - query_filter.timestamp_min = state.timestamp_min + 1; - query_filter.timestamp_max = state.timestamp_max; - } - // Later we can assert that results.len == count - 1: - query_filter.limit = state.count; - } - } - - return 1; - } - - fn build_get_change_events_filter( - self: *Workload, - client_index: usize, - body: []tb.ChangeEventsFilter, - ) usize { - _ = client_index; - assert(body.len == 1); - const filter = &body[0]; - - const snapshot = self.auditor.changes_tracker.acquire_snapshot() orelse { - // We can only track a limited set of events, - // so we issue a query with an invalid filter when the results can't be asserted. - filter.* = switch (self.prng.enum_uniform(enum { - zeroed, - invalid_timestamps, - })) { - .zeroed => .{ - .limit = 0, - .timestamp_min = 0, - .timestamp_max = 0, - }, - .invalid_timestamps => filter: { - const timestamp: u64 = self.prng.range_inclusive( - u64, - TimestampRange.timestamp_min, - TimestampRange.timestamp_max, - ); - break :filter .{ - .limit = self.prng.int(u32), - .timestamp_min = timestamp + 1, - .timestamp_max = timestamp, - }; - }, - }; - return 1; - }; - assert(snapshot.count_total() > 0); - - const limit: u32 = switch (self.prng.enum_uniform(enum { - exact, - batch_max, - })) { - .exact => snapshot.count_total(), - .batch_max => Operation.get_change_events.result_max( - self.options.batch_size_limit, - ), - }; - filter.* = .{ - .limit = limit, - .timestamp_min = snapshot.timestamp_min, - .timestamp_max = snapshot.timestamp_max, - }; - return 1; - } - - /// The transfer built is guaranteed to match the TransferPlan's outcome. - /// The transfer built is _not_ guaranteed to match the TransferPlan's method. - /// - /// Returns `null` if the transfer plan cannot be fulfilled (because there aren't enough - /// accounts created). - fn build_transfer( - self: *Workload, - transfer_id: u128, - transfer_plan: TransferPlan, - transfer: *tb.Transfer, - ) ?accounting_auditor.CreateTransferStatusSet { - // If the specified method is unavailable, swap it. - // Changing the method may narrow the TransferOutcome (unknown→success, unknown→failure) - // but never broaden it (success→unknown, success→failure). - const method = method: { - const default = transfer_plan.method; - if (default == .pending and - self.auditor.pending_expiries.count() + self.transfers_pending_in_flight == - self.auditor.options.transfers_pending_max) - { - break :method .single_phase; - } - - if (default == .post_pending or default == .void_pending) { - if (self.auditor.pending_transfers.count() == 0) { - break :method .single_phase; - } - } - break :method default; - }; - - const index_valid = @intFromBool(transfer_plan.valid); - const index_limit = @intFromBool(transfer_plan.limit); - const index_method = @intFromEnum(method); - const transfer_template = &transfer_templates[index_valid][index_limit][index_method]; - - const limit_debits = transfer_plan.limit and self.prng.boolean(); - const limit_credits = transfer_plan.limit and (self.prng.boolean() or !limit_debits); - assert(transfer_plan.limit == (limit_debits or limit_credits)); - - const debit_account = self.auditor.pick_account(.{ - .created = true, - .debits_must_not_exceed_credits = limit_debits, - .credits_must_not_exceed_debits = null, - }) orelse return null; - assert(!limit_debits or debit_account.flags.debits_must_not_exceed_credits); - - const credit_account = self.auditor.pick_account(.{ - .created = true, - .debits_must_not_exceed_credits = null, - .credits_must_not_exceed_debits = limit_credits, - .exclude = debit_account.id, - }) orelse return null; - assert(!limit_credits or credit_account.flags.credits_must_not_exceed_debits); - - const query_intersection_index = self.prng.index( - self.auditor.query_intersections, - ); - const query_intersection = self.auditor.query_intersections[query_intersection_index]; - - transfer.* = .{ - .id = transfer_id, - .debit_account_id = debit_account.id, - .credit_account_id = credit_account.id, - // "user_data_128" will be set to a checksum of the Transfer. - .user_data_128 = 0, - .user_data_64 = query_intersection.user_data_64, - .user_data_32 = query_intersection.user_data_32, - .code = query_intersection.code, - .pending_id = 0, - .timeout = 0, - .ledger = transfer_template.ledger, - .flags = .{}, - .timestamp = 0, - .amount = self.prng.int_inclusive(u128, std.math.maxInt(u8)), - }; - - switch (method) { - .single_phase => {}, - .pending => { - transfer.flags = .{ .pending = true }; - // Bound the timeout to ensure we never hit `overflows_timeout`. - transfer.timeout = 1 + @as(u32, @min( - std.math.maxInt(u32) / 2, - fuzz.random_int_exponential( - self.prng, - u32, - self.options.pending_timeout_mean, - ), - )); - }, - .post_pending, .void_pending => { - // Don't depend on `HashMap.keyIterator()` being deterministic. - // Pick a random "target" key, then post/void the id it is nearest to. - const target = self.prng.int(u128); - var previous: ?u128 = null; - var iterator = self.auditor.pending_transfers.keyIterator(); - while (iterator.next()) |id| { - if (previous == null or - @max(target, id.*) - @min(target, id.*) < - @max(target, previous.?) - @min(target, previous.?)) - { - previous = id.*; - } - } - - // If there were no pending ids, the method would have been changed. - const pending_id = previous.?; - const pending_transfer = self.auditor.pending_transfers.getPtr(previous.?).?; - const dr = pending_transfer.debit_account_index; - const cr = pending_transfer.credit_account_index; - const pending_query_intersection = self.auditor - .query_intersections[pending_transfer.query_intersection_index]; - // Don't use the default '0' parameters because the StateMachine overwrites 0s - // with the pending transfer's values, invalidating the post/void transfer - // checksum. - transfer.debit_account_id = self.auditor.account_index_to_id(dr); - transfer.credit_account_id = self.auditor.account_index_to_id(cr); - transfer.user_data_64 = pending_query_intersection.user_data_64; - transfer.user_data_32 = pending_query_intersection.user_data_32; - transfer.code = pending_query_intersection.code; - if (method == .post_pending) { - transfer.amount = - self.prng.range_inclusive(u128, 0, pending_transfer.amount); - } else { - transfer.amount = pending_transfer.amount; - } - transfer.pending_id = pending_id; - transfer.flags = .{ - .post_pending_transfer = method == .post_pending, - .void_pending_transfer = method == .void_pending, - }; - }, - } - assert(transfer_template.result.count() > 0); - return transfer_template.result; - } - - fn batch( - self: *const Workload, - comptime T: type, - comptime action: Action, - body: []u8, - event_count_remain: u32, - ) []T { - const batch_min = switch (action) { - .create_accounts, - .lookup_accounts, - .deprecated_create_accounts_sparse, - .deprecated_create_accounts_unbatched, - .deprecated_lookup_accounts_unbatched, - => self.options.accounts_batch_size_min, - .create_transfers, - .lookup_transfers, - .deprecated_create_transfers_sparse, - .deprecated_create_transfers_unbatched, - .deprecated_lookup_transfers_unbatched, - => self.options.transfers_batch_size_min, - .get_account_transfers, - .get_account_balances, - .query_accounts, - .query_transfers, - .deprecated_get_account_transfers_unbatched, - .deprecated_get_account_balances_unbatched, - .deprecated_query_accounts_unbatched, - .deprecated_query_transfers_unbatched, - .get_change_events, - => 1, - }; - const batch_span = switch (action) { - .create_accounts, - .lookup_accounts, - .deprecated_create_accounts_sparse, - .deprecated_create_accounts_unbatched, - .deprecated_lookup_accounts_unbatched, - => self.options.accounts_batch_size_span, - .create_transfers, - .lookup_transfers, - .deprecated_create_transfers_sparse, - .deprecated_create_transfers_unbatched, - .deprecated_lookup_transfers_unbatched, - => self.options.transfers_batch_size_span, - .get_account_transfers, - .get_account_balances, - .query_accounts, - .query_transfers, - .deprecated_get_account_transfers_unbatched, - .deprecated_get_account_balances_unbatched, - .deprecated_query_accounts_unbatched, - .deprecated_query_transfers_unbatched, - .get_change_events, - => 0, - }; - - const slice = stdx.bytes_as_slice(.inexact, T, body); - const batch_size = @min( - batch_min + self.prng.int_inclusive(usize, batch_span), - event_count_remain, - ); - - return slice[0..batch_size]; - } - - fn transfer_id_to_index(self: *const Workload, id: u128) usize { - // -1 because id=0 is not valid, so index=0→id=1. - return @as(usize, @intCast(self.options.transfer_id_permutation.decode(id))) - 1; - } - - fn transfer_index_to_id(self: *const Workload, index: usize) u128 { - // +1 so that index=0 is encoded as a valid id. - return self.options.transfer_id_permutation.encode(index + 1); - } - - /// To support `lookup_transfers`, the `TransferPlan` is deterministic based on: - /// * `Workload.transfer_plan_seed`, and - /// * the transfer `index`. - fn transfer_index_to_plan(self: *const Workload, index: usize) TransferPlan { - var prng = stdx.PRNG.from_seed(self.transfer_plan_seed ^ @as(u64, index)); - const method: TransferPlan.Method = blk: { - if (prng.chance(self.options.create_transfer_pending_probability)) { - break :blk .pending; - } - if (prng.chance(self.options.create_transfer_post_probability)) { - break :blk .post_pending; - } - if (prng.chance(self.options.create_transfer_void_probability)) { - break :blk .void_pending; - } - break :blk .single_phase; - }; - return .{ - .valid = !prng.chance(self.options.create_transfer_invalid_probability), - .limit = prng.chance(self.options.create_transfer_limit_probability), - .method = method, - }; - } - - fn on_create_transfers_sparse( - self: *Workload, - client_index: usize, - timestamp: u64, - transfers: []const tb.Transfer, - results_sparse: []const tb.CreateTransferErrorResult, - ) void { - self.auditor.on_create_transfers_sparse( - client_index, - timestamp, - transfers, - results_sparse, - ); - if (transfers.len == 0) return; - - const transfer_index_min = self.transfer_id_to_index(transfers[0].id); - const transfer_index_max = self.transfer_id_to_index(transfers[transfers.len - 1].id); - assert(transfer_index_min <= transfer_index_max); - - self.transfers_delivered_recently.add(.{ - .min = transfer_index_min, - .max = transfer_index_max, - }) catch unreachable; - - while (self.transfers_delivered_recently.peek()) |delivered| { - if (self.transfers_delivered_past == delivered.min) { - self.transfers_delivered_past = delivered.max + 1; - _ = self.transfers_delivered_recently.remove(); - } else { - assert(self.transfers_delivered_past < delivered.min); - break; - } - } - - var iterator: ResultsSparseIteratorType(tb.CreateTransferErrorResult) = .init( - results_sparse, - ); - for (transfers, 0..) |*transfer, i| { - const result: tb.CreateTransferStatus = iterator.take(i) orelse .created; - if (transfer.flags.pending and result != .exists) { - self.transfers_pending_in_flight -= 1; - } - - // Add some successfully completed transfers to be retried in the next request. - if (result == .created and !transfer.flags.linked and - self.transfers_retry_exists.items.len < - self.options.transfers_retry_exists_max and - self.prng.chance(self.options.create_transfer_retry_probability)) - { - var transfer_exists = transfer.*; - assert(transfer_exists.timestamp == 0); - assert(transfer_exists.user_data_128 != 0); - - transfer_exists.user_data_128 = 0; // This will be replaced by the checksum. - self.transfers_retry_exists.appendAssumeCapacity(transfer_exists); - } - - // Enqueue the `id`s of transient errors to be retried in the next request. - if (result != .created and result.transient() and - self.transfers_retry_failed.count() < - self.options.transfers_retry_failed_max) - { - self.transfers_retry_failed.putAssumeCapacityNoClobber( - transfer.id, - {}, - ); - } - } - } - - fn on_create_transfers( - self: *Workload, - client_index: usize, - timestamp: u64, - transfers: []const tb.Transfer, - results: []const tb.CreateTransferResult, - ) void { - self.auditor.on_create_transfers( - client_index, - timestamp, - transfers, - results, - ); - if (transfers.len == 0) return; - - const transfer_index_min = self.transfer_id_to_index(transfers[0].id); - const transfer_index_max = self.transfer_id_to_index(transfers[transfers.len - 1].id); - assert(transfer_index_min <= transfer_index_max); - - self.transfers_delivered_recently.add(.{ - .min = transfer_index_min, - .max = transfer_index_max, - }) catch unreachable; - - while (self.transfers_delivered_recently.peek()) |delivered| { - if (self.transfers_delivered_past == delivered.min) { - self.transfers_delivered_past = delivered.max + 1; - _ = self.transfers_delivered_recently.remove(); - } else { - assert(self.transfers_delivered_past < delivered.min); - break; - } - } - - for (transfers, results) |*transfer, *result| { - assert(result.reserved == 0); - if (transfer.flags.pending and result.status != .exists) { - self.transfers_pending_in_flight -= 1; - } - - // Add some successfully completed transfers to be retried in the next request. - if (result.status == .created and !transfer.flags.linked and - self.transfers_retry_exists.items.len < - self.options.transfers_retry_exists_max and - self.prng.chance(self.options.create_transfer_retry_probability)) - { - var transfer_exists = transfer.*; - assert(transfer_exists.timestamp == 0); - assert(transfer_exists.user_data_128 != 0); - - transfer_exists.user_data_128 = 0; // This will be replaced by the checksum. - self.transfers_retry_exists.appendAssumeCapacity(transfer_exists); - } - - // Enqueue the `id`s of transient errors to be retried in the next request. - if (result.status != .created and result.status.transient() and - self.transfers_retry_failed.count() < - self.options.transfers_retry_failed_max) - { - self.transfers_retry_failed.putAssumeCapacityNoClobber( - transfer.id, - {}, - ); - } - } - } - - fn on_lookup_transfers( - self: *Workload, - client_index: usize, - timestamp: u64, - ids: []const u128, - results: []const tb.Transfer, - ) void { - self.auditor.on_lookup_transfers(client_index, timestamp, ids, results); - - var transfers = accounting_auditor.IteratorForLookupType(tb.Transfer).init(results); - for (ids) |transfer_id| { - const transfer_index = self.transfer_id_to_index(transfer_id); - const transfer_outcome = self.transfer_index_to_plan(transfer_index).outcome(); - const result = transfers.take(transfer_id); - - if (result) |transfer| validate_transfer_checksum(transfer); - - if (transfer_index >= self.transfers_sent) { - // This transfer hasn't been created yet. - assert(result == null); - continue; - } - - switch (transfer_outcome) { - .success => { - if (transfer_index < self.transfers_delivered_past) { - // The transfer was delivered; it must exist. - assert(result != null); - } else { - var it = self.transfers_delivered_recently.iterator(); - while (it.next()) |delivered| { - if (transfer_index >= delivered.min and - transfer_index <= delivered.max) - { - // The transfer was delivered recently; it must exist. - assert(result != null); - break; - } - } else { - // The `create_transfers` has not committed (it may be in-flight). - assert(result == null); - } - } - }, - // An invalid transfer is never persisted. - .failure => assert(result == null), - // Due to races and timeouts, these transfer types may not succeed. - .unknown => {}, - } - } - } - - fn on_get_account_transfers( - self: *Workload, - comptime operation: Operation, - timestamp: u64, - body: []const tb.AccountFilter, - results: []const tb.Transfer, - ) void { - _ = timestamp; - comptime assert(operation == .get_account_transfers or - operation == .deprecated_get_account_transfers_unbatched); - assert(body.len == 1); - - const batch_result_max = operation.result_max(self.options.batch_size_limit); - const account_filter = &body[0]; - assert(results.len <= account_filter.limit); - assert(results.len <= batch_result_max); - - const account_state = self.auditor.get_account_state( - account_filter.account_id, - ) orelse { - // Invalid account id. - assert(results.len == 0); - return; - }; - - const filter_valid = account_state.created and - (account_filter.flags.credits or account_filter.flags.debits) and - account_filter.limit > 0 and - account_filter.timestamp_min <= account_filter.timestamp_max; - if (!filter_valid) { - // Invalid filter. - assert(results.len == 0); - return; - } - - self.validate_account_filter_result_count( - operation, - account_state, - account_filter, - results.len, - ); - - var timestamp_previous: u64 = if (account_filter.flags.reversed) - account_state.transfer_timestamp_max +| 1 - else - account_state.transfer_timestamp_min -| 1; - - for (results) |*transfer| { - if (account_filter.flags.reversed) { - assert(transfer.timestamp < timestamp_previous); - } else { - assert(transfer.timestamp > timestamp_previous); - } - timestamp_previous = transfer.timestamp; - - assert(account_filter.timestamp_min == 0 or - transfer.timestamp >= account_filter.timestamp_min); - assert(account_filter.timestamp_max == 0 or - transfer.timestamp <= account_filter.timestamp_max); - - validate_transfer_checksum(transfer); - - const transfer_index = self.transfer_id_to_index(transfer.id); - assert(transfer_index < self.transfers_sent); - - const transfer_plan = self.transfer_index_to_plan(transfer_index); - assert(transfer_plan.valid); - assert(transfer_plan.outcome() != .failure); - if (transfer.flags.pending) assert(transfer_plan.method == .pending); - if (transfer.flags.post_pending_transfer) { - assert(transfer_plan.method == .post_pending); - } - if (transfer.flags.void_pending_transfer) { - assert(transfer_plan.method == .void_pending); - } - if (transfer_plan.method == .single_phase) assert(!transfer.flags.pending and - !transfer.flags.post_pending_transfer and - !transfer.flags.void_pending_transfer); - - assert(transfer.debit_account_id == account_filter.account_id or - transfer.credit_account_id == account_filter.account_id); - assert(account_filter.flags.credits or account_filter.flags.debits); - assert(account_filter.flags.credits or - transfer.debit_account_id == account_filter.account_id); - assert(account_filter.flags.debits or - transfer.credit_account_id == account_filter.account_id); - - if (transfer_plan.limit) { - // The plan does not guarantee the "limit" flag for posting - // or voiding pending transfers. - const post_or_void_pending_transfer = transfer.flags.post_pending_transfer or - transfer.flags.void_pending_transfer; - assert(post_or_void_pending_transfer == (transfer.pending_id != 0)); - - const dr_account = self.auditor.get_account(transfer.debit_account_id).?; - const cr_account = self.auditor.get_account(transfer.credit_account_id).?; - assert( - post_or_void_pending_transfer or - dr_account.flags.debits_must_not_exceed_credits or - cr_account.flags.credits_must_not_exceed_debits, - ); - } - } - } - - fn on_get_account_balances( - self: *Workload, - comptime operation: Operation, - timestamp: u64, - body: []const tb.AccountFilter, - results: []const tb.AccountBalance, - ) void { - _ = timestamp; - comptime assert(operation == .get_account_balances or - operation == .deprecated_get_account_balances_unbatched); - assert(body.len == 1); - - const batch_result_max = operation.result_max(self.options.batch_size_limit); - const account_filter = &body[0]; - assert(results.len <= account_filter.limit); - assert(results.len <= batch_result_max); - - const account_state = self.auditor.get_account_state( - account_filter.account_id, - ) orelse { - // Invalid account id. - assert(results.len == 0); - return; - }; - - const filter_valid = account_state.created and - self.auditor.get_account(account_filter.account_id).?.flags.history and - (account_filter.flags.credits or account_filter.flags.debits) and - account_filter.limit > 0 and - account_filter.timestamp_min <= account_filter.timestamp_max; - if (!filter_valid) { - // Invalid filter. - assert(results.len == 0); - return; - } - - self.validate_account_filter_result_count( - operation, - account_state, - account_filter, - results.len, - ); - - var timestamp_last: u64 = if (account_filter.flags.reversed) - account_state.transfer_timestamp_max +| 1 - else - account_state.transfer_timestamp_min -| 1; - - for (results) |*balance| { - assert(if (account_filter.flags.reversed) - balance.timestamp < timestamp_last - else - balance.timestamp > timestamp_last); - timestamp_last = balance.timestamp; - - assert(account_filter.timestamp_min == 0 or - balance.timestamp >= account_filter.timestamp_min); - assert(account_filter.timestamp_max == 0 or - balance.timestamp <= account_filter.timestamp_max); - } - } - - fn validate_account_filter_result_count( - self: *const Workload, - comptime operation: Operation, - account_state: *const Auditor.AccountState, - account_filter: *const tb.AccountFilter, - result_count: usize, - ) void { - comptime assert(operation == .get_account_transfers or - operation == .get_account_balances or - operation == .deprecated_get_account_transfers_unbatched or - operation == .deprecated_get_account_balances_unbatched); - maybe(account_filter.limit == 0); - - const batch_result_max = operation.result_max(self.options.batch_size_limit); - const transfer_count = account_state.transfers_count(account_filter.flags); - if (account_filter.timestamp_min == 0 and account_filter.timestamp_max == 0) { - assert(account_filter.limit <= batch_result_max); - assert(result_count == - @min(account_filter.limit, batch_result_max, transfer_count)); - } else { - // If timestamp range is set, then the limit is exactly the number of transfer - // at the time the filter was generated, but new transfers could have been - // inserted since then. - assert(account_filter.limit <= transfer_count); - assert(account_filter.timestamp_max >= account_filter.timestamp_min); - if (account_filter.flags.reversed) { - // This filter is only set if there is at least one transfer, so the first - // transfer timestamp never changes. - assert(account_filter.timestamp_min == account_state.transfer_timestamp_min); - // The filter `timestamp_max` was decremented to skip one result. - assert(account_filter.timestamp_max < account_state.transfer_timestamp_max); - } else { - // The filter `timestamp_min` was incremented to skip one result. - assert(account_filter.timestamp_min > account_state.transfer_timestamp_min); - // New transfers can update `transfer_timestamp_max`. - assert(account_filter.timestamp_max <= account_state.transfer_timestamp_max); - } - - // Either `transfer_count` is greater than the batch size (so removing a result - // doesn't make a difference) or there is exactly one less result that was - // excluded by the timestamp filter. - assert((result_count == batch_result_max and transfer_count > batch_result_max) or - result_count == account_filter.limit - 1); - } - } - - fn on_query( - self: *Workload, - comptime operation: Operation, - timestamp: u64, - body: []const tb.QueryFilter, - results: []const operation.ResultType(), - ) void { - _ = timestamp; - comptime assert(operation == .query_accounts or - operation == .query_transfers or - operation == .deprecated_query_accounts_unbatched or - operation == .deprecated_query_transfers_unbatched); - assert(body.len == 1); - - const batch_result_max: u32 = operation.result_max(self.options.batch_size_limit); - const filter = &body[0]; - - if (filter.ledger != 0) { - // No results expected. - assert(results.len == 0); - return; - } - - assert(filter.user_data_64 != 0); - assert(filter.user_data_32 != 0); - assert(filter.code != 0); - assert(filter.user_data_128 == 0); - assert(filter.ledger == 0); - maybe(filter.limit == 0); - maybe(filter.timestamp_min == 0); - maybe(filter.timestamp_max == 0); - - const query_intersection_index = filter.code - 1; - const query_intersection = self.auditor.query_intersections[query_intersection_index]; - const state = switch (operation) { - .query_accounts, - .deprecated_query_accounts_unbatched, - => &query_intersection.accounts, - .query_transfers, - .deprecated_query_transfers_unbatched, - => &query_intersection.transfers, - else => unreachable, - }; - - assert(results.len <= filter.limit); - assert(results.len <= batch_result_max); - - if (filter.timestamp_min > 0 or filter.timestamp_max > 0) { - assert(filter.limit <= state.count); - assert(filter.timestamp_min > 0); - assert(filter.timestamp_max > 0); - assert(filter.timestamp_min <= filter.timestamp_max); - - // Filtering by timestamp always exclude one single result. - assert(results.len == filter.limit - 1); - } else { - assert(results.len == @min( - filter.limit, - batch_result_max, - state.count, - )); - } - - var timestamp_previous: u64 = if (filter.flags.reversed) - std.math.maxInt(u64) - else - 0; - - for (results) |*result| { - if (filter.flags.reversed) { - assert(result.timestamp < timestamp_previous); - } else { - assert(result.timestamp > timestamp_previous); - } - timestamp_previous = result.timestamp; - - if (filter.timestamp_min > 0) { - assert(result.timestamp >= filter.timestamp_min); - } - if (filter.timestamp_max > 0) { - assert(result.timestamp <= filter.timestamp_max); - } - - assert(result.user_data_64 == filter.user_data_64); - assert(result.user_data_32 == filter.user_data_32); - assert(result.code == filter.code); - - if (operation == .query_transfers or - operation == .deprecated_query_transfers_unbatched) - { - validate_transfer_checksum(result); - } - } - } - - fn on_get_change_events( - self: *Workload, - timestamp: u64, - body: []const tb.ChangeEventsFilter, - results: []const tb.ChangeEvent, - ) void { - assert(body.len == 1); - self.auditor.on_get_change_events(timestamp, body[0], results); - - for (results) |*result| { - assert(stdx.zeroed(&result.reserved)); - switch (result.type) { - .single_phase => { - assert(result.timestamp == result.transfer_timestamp); - assert(!result.transfer_flags.pending); - assert(!result.transfer_flags.post_pending_transfer); - assert(!result.transfer_flags.void_pending_transfer); - assert(result.transfer_pending_id == 0); - assert(result.transfer_amount <= result.debit_account_debits_posted); - assert(result.transfer_amount <= result.credit_account_credits_posted); - }, - .two_phase_pending => { - assert(result.timestamp == result.transfer_timestamp); - assert(result.transfer_flags.pending); - assert(!result.transfer_flags.post_pending_transfer); - assert(!result.transfer_flags.void_pending_transfer); - assert(result.transfer_pending_id == 0); - assert(result.transfer_amount <= result.debit_account_debits_pending); - assert(result.transfer_amount <= result.credit_account_credits_pending); - }, - .two_phase_posted => { - assert(result.timestamp == result.transfer_timestamp); - assert(result.transfer_flags.post_pending_transfer); - assert(!result.transfer_flags.pending); - assert(!result.transfer_flags.void_pending_transfer); - assert(result.transfer_pending_id != 0); - assert(result.transfer_amount <= result.debit_account_debits_posted); - assert(result.transfer_amount <= result.credit_account_credits_posted); - }, - .two_phase_voided => { - assert(result.timestamp == result.transfer_timestamp); - assert(result.transfer_flags.void_pending_transfer); - assert(!result.transfer_flags.pending); - assert(!result.transfer_flags.post_pending_transfer); - assert(result.transfer_pending_id != 0); - }, - .two_phase_expired => { - assert(result.transfer_timeout > 0); - const timeout_ns: u64 = - @as(u64, result.transfer_timeout) * std.time.ns_per_s; - assert(result.timestamp >= result.transfer_timestamp + timeout_ns); - assert(result.transfer_flags.pending); - assert(!result.transfer_flags.post_pending_transfer); - assert(!result.transfer_flags.void_pending_transfer); - assert(result.transfer_pending_id == 0); - }, - } - assert(result.transfer_flags.closing_debit == result.debit_account_flags.closed); - assert(result.transfer_flags.closing_credit == result.credit_account_flags.closed); - validate_get_event_checksum(result); - } - } - - /// Verify the transfer's integrity. - fn validate_transfer_checksum(transfer: *const tb.Transfer) void { - const checksum_actual = transfer.user_data_128; - var check = transfer.*; - check.user_data_128 = 0; - check.timestamp = 0; - const checksum_expect = vsr.checksum(std.mem.asBytes(&check)); - assert(checksum_expect == checksum_actual); - } - - fn validate_get_event_checksum(event: *const tb.ChangeEvent) void { - const transfer: tb.Transfer = .{ - .id = event.transfer_id, - .debit_account_id = event.debit_account_id, - .credit_account_id = event.credit_account_id, - .amount = event.transfer_amount, - .pending_id = event.transfer_pending_id, - .user_data_128 = event.transfer_user_data_128, - .user_data_64 = event.transfer_user_data_64, - .user_data_32 = event.transfer_user_data_32, - .timeout = event.transfer_timeout, - .ledger = event.ledger, - .code = event.transfer_code, - .flags = event.transfer_flags, - .timestamp = event.timestamp, - }; - validate_transfer_checksum(&transfer); - } - }; -} - -fn OptionsType( - comptime AccountingStateMachine: type, - comptime Action: type, - comptime Lookup: type, -) type { - return struct { - batch_size_limit: u32, - multi_batch_per_request_limit: u32, - - auditor_options: Auditor.Options, - transfer_id_permutation: IdPermutation, - - operations: stdx.PRNG.EnumWeightsType(Action), - - create_account_invalid_probability: Ratio, - create_transfer_invalid_probability: Ratio, - create_transfer_limit_probability: Ratio, - create_transfer_pending_probability: Ratio, - create_transfer_post_probability: Ratio, - create_transfer_void_probability: Ratio, - create_transfer_retry_probability: Ratio, - lookup_account_invalid_probability: Ratio, - - account_filter_invalid_account_probability: Ratio, - account_filter_timestamp_range_probability: Ratio, - - query_filter_not_found_probability: Ratio, - query_filter_timestamp_range_probability: Ratio, - lookup_transfer: stdx.PRNG.EnumWeightsType(Lookup), - - // Size of timespan for querying, measured in transfers - lookup_transfer_span_mean: usize, - - account_limit_probability: Ratio, - account_history_probability: Ratio, - - /// This probability is only checked for consecutive guaranteed-successful transfers. - linked_valid_probability: Ratio, - /// This probability is only checked for consecutive invalid transfers. - linked_invalid_probability: Ratio, - - pending_timeout_mean: u32, - - accounts_batch_size_min: usize, - accounts_batch_size_span: usize, // inclusive - transfers_batch_size_min: usize, - transfers_batch_size_span: usize, // inclusive - - /// Maximum number of failed transfer IDs to keep in the retry list. - transfers_retry_failed_max: usize, - - /// Maximum number of successfully completed transfers to keep in the retry list. - transfers_retry_exists_max: usize, - - const Options = @This(); - const Operation = AccountingStateMachine.Operation; - - pub fn generate(prng: *stdx.PRNG, options: struct { - batch_size_limit: u32, - multi_batch_per_request_limit: u32, - client_count: usize, - in_flight_max: usize, - }) Options { - assert( - options.batch_size_limit <= constants.message_body_size_max, - ); - - const batch_create_accounts_limit = @min( - Operation.create_accounts.event_max(options.batch_size_limit), - Operation.deprecated_create_accounts_sparse.event_max(options.batch_size_limit), - Operation.deprecated_create_accounts_unbatched.event_max(options.batch_size_limit), - ); - assert(batch_create_accounts_limit > 0); - assert(batch_create_accounts_limit <= - AccountingStateMachine.batch_max.create_accounts); - - const batch_create_transfers_limit = @min( - Operation.create_transfers.event_max(options.batch_size_limit), - Operation.deprecated_create_transfers_sparse.event_max(options.batch_size_limit), - Operation.deprecated_create_transfers_unbatched.event_max( - options.batch_size_limit, - ), - ); - assert(batch_create_transfers_limit > 0); - assert(batch_create_transfers_limit <= - AccountingStateMachine.batch_max.create_transfers); - return .{ - .batch_size_limit = options.batch_size_limit, - .multi_batch_per_request_limit = options.multi_batch_per_request_limit, - .auditor_options = .{ - .accounts_max = prng.range_inclusive(usize, 2, 128), - .account_id_permutation = IdPermutation.generate(prng), - .client_count = options.client_count, - .transfers_pending_max = 256, - .changes_events_max = Operation - .get_change_events.event_max(options.batch_size_limit), - .in_flight_max = options.in_flight_max, - .pulse_expiries_max = @max( - Operation.create_transfers.event_max( - options.batch_size_limit, - ), - Operation.deprecated_create_transfers_sparse.event_max( - options.batch_size_limit, - ), - Operation.deprecated_create_transfers_unbatched.event_max( - options.batch_size_limit, - ), - ), - }, - .transfer_id_permutation = IdPermutation.generate(prng), - .operations = .{ - .create_accounts = prng.range_inclusive(u64, 1, 10), - .create_transfers = prng.range_inclusive(u64, 1, 100), - .lookup_accounts = prng.range_inclusive(u64, 1, 20), - .lookup_transfers = prng.range_inclusive(u64, 1, 20), - .get_account_transfers = prng.range_inclusive(u64, 1, 20), - .get_account_balances = prng.range_inclusive(u64, 1, 20), - .query_accounts = prng.range_inclusive(u64, 1, 20), - .query_transfers = prng.range_inclusive(u64, 1, 20), - .get_change_events = prng.range_inclusive(u64, 1, 20), - - .deprecated_create_accounts_sparse = prng.range_inclusive(u64, 1, 10), - .deprecated_create_transfers_sparse = prng.range_inclusive(u64, 1, 100), - - .deprecated_create_accounts_unbatched = prng.range_inclusive(u64, 1, 10), - .deprecated_create_transfers_unbatched = prng.range_inclusive(u64, 1, 100), - .deprecated_lookup_accounts_unbatched = prng.range_inclusive(u64, 1, 20), - .deprecated_lookup_transfers_unbatched = prng.range_inclusive(u64, 1, 20), - .deprecated_get_account_transfers_unbatched = prng.range_inclusive(u64, 1, 20), - .deprecated_get_account_balances_unbatched = prng.range_inclusive(u64, 1, 20), - .deprecated_query_accounts_unbatched = prng.range_inclusive(u64, 1, 20), - .deprecated_query_transfers_unbatched = prng.range_inclusive(u64, 1, 20), - }, - .create_account_invalid_probability = ratio(1, 100), - .create_transfer_invalid_probability = ratio(1, 100), - .create_transfer_limit_probability = ratio(prng.int_inclusive(u8, 100), 100), - .create_transfer_pending_probability = ratio(prng.range_inclusive(u8, 1, 100), 100), - .create_transfer_post_probability = ratio(prng.range_inclusive(u8, 1, 50), 100), - .create_transfer_void_probability = ratio(prng.range_inclusive(u8, 1, 50), 100), - .create_transfer_retry_probability = ratio(prng.range_inclusive(u8, 1, 10), 100), - .lookup_account_invalid_probability = ratio(1, 100), - - .account_filter_invalid_account_probability = ratio( - prng.range_inclusive(u8, 1, 20), - 100, - ), - .account_filter_timestamp_range_probability = ratio( - prng.range_inclusive(u8, 1, 80), - 100, - ), - - .query_filter_not_found_probability = ratio(prng.range_inclusive(u8, 1, 20), 100), - .query_filter_timestamp_range_probability = ratio( - prng.range_inclusive(u8, 1, 80), - 100, - ), - - .lookup_transfer = .{ - .delivered = prng.range_inclusive(u64, 1, 10), - .sending = prng.range_inclusive(u64, 1, 10), - }, - .lookup_transfer_span_mean = prng.range_inclusive(usize, 10, 1000), - .account_limit_probability = ratio(prng.int_inclusive(u8, 80), 100), - .account_history_probability = ratio(prng.int_inclusive(u8, 80), 100), - .linked_valid_probability = ratio(prng.int_inclusive(u8, 100), 100), - // 100% chance: this only applies to consecutive invalid transfers, which are rare. - .linked_invalid_probability = ratio(100, 100), - // One second. - .pending_timeout_mean = 1, - .accounts_batch_size_min = 0, - .accounts_batch_size_span = prng.range_inclusive( - usize, - 1, - batch_create_accounts_limit, - ), - .transfers_batch_size_min = 0, - .transfers_batch_size_span = prng.range_inclusive( - usize, - 1, - batch_create_transfers_limit, - ), - .transfers_retry_failed_max = 128, - .transfers_retry_exists_max = 128, - }; - } - }; -} diff --git a/ocam/src/state_machine_fuzz.zig b/ocam/src/state_machine_fuzz.zig deleted file mode 100644 index b468b50d..00000000 --- a/ocam/src/state_machine_fuzz.zig +++ /dev/null @@ -1,291 +0,0 @@ -//! Very simple state machine fuzzer. It looks for poison pill style ops that are otherwise valid -//! which cause a crash, then be replayed after said crash, resulting in a crash loop. -const std = @import("std"); -const assert = std.debug.assert; - -const vsr = @import("vsr.zig"); -const constants = vsr.constants; -const stdx = @import("stdx"); - -const tb = @import("tigerbeetle.zig"); -const TestContext = @import("state_machine_tests.zig").TestContext; -const fuzz = @import("./testing/fuzz.zig"); - -/// Generate a random number, biased towards all bit 'edges' of T. That is, given a u64, it's very -/// likely to not only get 0 or maxInt(u64), but also values around maxInt(u63), maxInt(u62), ..., -/// maxInt(u1). -pub fn int_edge_biased(prng: *stdx.PRNG, T: anytype) T { - const bits = @typeInfo(T).int.bits; - comptime assert(@typeInfo(T).int.signedness == .unsigned); - - // With bits * 2, there's a ~50% chance of generating a uniform integer within the full range, - // and a ~50% chance of generating an integer biased towards an edge. - const bias_to = prng.range_inclusive(T, 0, bits * 2); - - if (bias_to > bits) { - return prng.int(T); - } else { - const bias_center: T = if (bias_to == bits) - std.math.maxInt(T) - else - std.math.pow(T, 2, bias_to); - const bias_min = if (bias_to == 0) 0 else bias_center - @min(bias_center, 8); - const bias_max = if (bias_to == bits) bias_center else bias_center + 8; - - return prng.range_inclusive(T, bias_min, bias_max); - } -} - -pub fn main(allocator: std.mem.Allocator, args: fuzz.FuzzArgs) !void { - var context: TestContext = undefined; - try context.init(allocator); - defer context.deinit(allocator); - - const request_buffer = try allocator.alignedAlloc( - u8, - constants.cache_line_size, - vsr.constants.message_body_size_max, - ); - defer allocator.free(request_buffer); - - const reply_buffer = try allocator.alignedAlloc( - u8, - constants.cache_line_size, - vsr.constants.message_body_size_max, - ); - defer allocator.free(reply_buffer); - - var prng = stdx.PRNG.from_seed(args.seed); - - var op: u64 = 1; - - for (0..args.events_max orelse 50_000) |_| { - const operation = prng.enum_uniform(TestContext.StateMachine.Operation); - const size: usize = size: { - if (!operation.is_multi_batch()) { - break :size build_batch(&prng, operation, request_buffer); - } - assert(operation.is_multi_batch()); - - var body_encoder = vsr.multi_batch.MultiBatchEncoder.init(request_buffer, .{ - .element_size = operation.event_size(), - }); - - const batch_count = prng.enum_uniform(enum { one, random, max }); - while (body_encoder.writable()) |writable| { - const bytes_written: u32 = build_batch(&prng, operation, writable); - body_encoder.add(bytes_written); - switch (batch_count) { - .one => { - if (body_encoder.batch_count == 1) break; - }, - .random => if (prng.chance(.{ .numerator = 30, .denominator = 100 })) { - break; - }, - .max => {}, - } - } - - break :size body_encoder.finish(); - }; - - if (context.state_machine.input_valid(operation, request_buffer[0..size])) { - context.prepare(operation, request_buffer[0..size]); - const reply_size = context.execute( - op, - operation, - request_buffer[0..size], - @ptrCast(reply_buffer), - ); - stdx.maybe(reply_size == 0); - if (operation.is_multi_batch()) { - assert(reply_size > 0); - _ = vsr.multi_batch.MultiBatchDecoder.init(reply_buffer[0..reply_size], .{ - .element_size = operation.result_size(), - }) catch |err| switch (err) { - error.MultiBatchInvalid => unreachable, - }; - } - } - op += 1; - } -} - -fn build_batch( - prng: *stdx.PRNG, - operation: TestContext.StateMachine.Operation, - buffer: []u8, -) u32 { - return switch (operation) { - // No payload, so not very interesting yet. - .pulse => 0, - - // No payload, `create_*` require compaction to be hooked up. - .create_accounts, - .create_transfers, - => 0, - .deprecated_create_accounts_sparse, - .deprecated_create_transfers_sparse, - => 0, - .deprecated_create_accounts_unbatched, - .deprecated_create_transfers_unbatched, - => 0, - - .lookup_accounts, .lookup_transfers => build_lookup(prng, buffer), - .get_account_transfers, .get_account_balances => build_account_filter(prng, buffer), - .query_accounts, .query_transfers => build_query_filter(prng, buffer), - .get_change_events => build_get_change_events_filter(prng, buffer), - - .deprecated_lookup_accounts_unbatched, - .deprecated_lookup_transfers_unbatched, - => build_lookup(prng, buffer), - .deprecated_get_account_transfers_unbatched, - .deprecated_get_account_balances_unbatched, - => build_account_filter(prng, buffer), - .deprecated_query_accounts_unbatched, - .deprecated_query_transfers_unbatched, - => build_query_filter(prng, buffer), - }; -} - -fn build_lookup(prng: *stdx.PRNG, buffer: []u8) u32 { - const ids: []u128 = stdx.bytes_as_slice(.inexact, u128, buffer); - const size: u32 = prng.int_inclusive(u32, @intCast(ids.len)); - for (ids[0..size]) |*id| { - id.* = int_edge_biased(prng, u128); - } - return size * @sizeOf(u128); -} - -fn build_account_filter(prng: *stdx.PRNG, buffer: []u8) u32 { - const filter: *tb.AccountFilter = filter: { - const slice = stdx.bytes_as_slice( - .inexact, - tb.AccountFilter, - buffer, - ); - if (slice.len == 0) return 0; - break :filter &slice[0]; - }; - var reserved: [58]u8 = @splat(0); - if (prng.chance(.{ .numerator = 1, .denominator = 1000 })) { - prng.fill(&reserved); - } - - filter.* = .{ - .account_id = int_edge_biased(prng, u128), - .user_data_128 = int_edge_biased(prng, u128), - .user_data_64 = int_edge_biased(prng, u64), - .user_data_32 = int_edge_biased(prng, u32), - .code = int_edge_biased(prng, u16), - .timestamp_min = int_edge_biased(prng, u64), - .timestamp_max = int_edge_biased(prng, u64), - .limit = int_edge_biased(prng, u32), - .reserved = reserved, - .flags = .{ - .reversed = prng.boolean(), - .debits = prng.boolean(), - .credits = prng.boolean(), - .padding = if (prng.chance(.{ .numerator = 1, .denominator = 1000 })) - int_edge_biased(prng, u29) - else - 0, - }, - }; - - return @sizeOf(tb.AccountFilter); -} - -fn build_query_filter(prng: *stdx.PRNG, buffer: []u8) u32 { - const filter: *tb.QueryFilter = filter: { - const slice = stdx.bytes_as_slice( - .inexact, - tb.QueryFilter, - buffer, - ); - if (slice.len == 0) return 0; - break :filter &slice[0]; - }; - var reserved: [6]u8 = @splat(0); - if (prng.chance(.{ .numerator = 1, .denominator = 1000 })) { - prng.fill(&reserved); - } - - filter.* = .{ - .user_data_128 = int_edge_biased(prng, u128), - .user_data_64 = int_edge_biased(prng, u64), - .user_data_32 = int_edge_biased(prng, u32), - .ledger = int_edge_biased(prng, u32), - .code = int_edge_biased(prng, u16), - .timestamp_min = int_edge_biased(prng, u64), - .timestamp_max = int_edge_biased(prng, u64), - .limit = int_edge_biased(prng, u32), - .reserved = reserved, - .flags = .{ - .reversed = prng.boolean(), - .padding = if (prng.chance(.{ .numerator = 1, .denominator = 1000 })) - int_edge_biased(prng, u31) - else - 0, - }, - }; - - return @sizeOf(tb.QueryFilter); -} - -fn build_get_change_events_filter(prng: *stdx.PRNG, buffer: []u8) u32 { - const filter: *tb.ChangeEventsFilter = filter: { - const slice = stdx.bytes_as_slice( - .inexact, - tb.ChangeEventsFilter, - buffer, - ); - if (slice.len == 0) return 0; - break :filter &slice[0]; - }; - var reserved: [44]u8 = @splat(0); - if (prng.chance(.{ .numerator = 1, .denominator = 1000 })) { - prng.fill(&reserved); - } - - filter.* = .{ - .timestamp_min = int_edge_biased(prng, u64), - .timestamp_max = int_edge_biased(prng, u64), - .limit = int_edge_biased(prng, u32), - .reserved = reserved, - }; - - return @sizeOf(tb.ChangeEventsFilter); -} - -test "int_edge_biased" { - const seed = 42; - - var prng = stdx.PRNG.from_seed(seed); - var found_max_int: [129]bool = std.mem.zeroes([129]bool); - - // Currently takes ~20 000 random values to hit all maxInts (eg, 0, maxInt(u1), maxInt(u2), etc, - // for a u128 with a seed of 42. Even if the seed changes, we expect this to find them all - // within a relatively short space of time. - for (0..20_000) |_| { - const int = int_edge_biased(&prng, u128); - - if (int == 0) { - found_max_int[0] = true; - continue; - } - - inline for (1..129) |bits| { - const IntType = @Type(.{ .int = .{ - .signedness = .unsigned, - .bits = bits, - } }); - const max = std.math.maxInt(IntType); - if (int == max) { - found_max_int[bits] = true; - } - } - } - - assert(std.mem.allEqual(bool, &found_max_int, true)); -} diff --git a/ocam/src/state_machine_tests.zig b/ocam/src/state_machine_tests.zig deleted file mode 100644 index 0d099581..00000000 --- a/ocam/src/state_machine_tests.zig +++ /dev/null @@ -1,3219 +0,0 @@ -const std = @import("std"); -const assert = std.debug.assert; -const math = std.math; -const mem = std.mem; - -const stdx = @import("stdx"); -const maybe = stdx.maybe; - -const tb = @import("tigerbeetle.zig"); -const vsr = @import("vsr.zig"); -const constants = vsr.constants; - -const MultiBatchEncoder = vsr.multi_batch.MultiBatchEncoder; -const MultiBatchDecoder = vsr.multi_batch.MultiBatchDecoder; - -const TimestampRange = @import("lsm/timestamp_range.zig").TimestampRange; - -const Account = tb.Account; -const AccountBalance = tb.AccountBalance; -const Transfer = tb.Transfer; -const CreateAccountResult = tb.CreateAccountResult; -const CreateTransferResult = tb.CreateTransferResult; - -const CreateAccountStatus = tb.CreateAccountStatus; -const CreateTransferStatus = tb.CreateTransferStatus; - -const AccountFilter = tb.AccountFilter; -const QueryFilter = tb.QueryFilter; -const ChangeEventsFilter = tb.ChangeEventsFilter; -const ChangeEvent = tb.ChangeEvent; -const ChangeEventType = tb.ChangeEventType; - -const StateMachineType = @import("state_machine.zig").StateMachineType; - -const testing = std.testing; - -pub const TestContext = struct { - const TimeSim = @import("testing/time.zig").TimeSim; - const Storage = @import("testing/storage.zig").Storage; - const Tracer = Storage.Tracer; - const data_file_size_min = @import("vsr/superblock.zig").data_file_size_min; - const SuperBlock = @import("vsr/superblock.zig").SuperBlockType(Storage); - const Grid = @import("vsr/grid.zig").GridType(Storage); - const fixtures = @import("testing/fixtures.zig"); - - pub const StateMachine = StateMachineType(Storage); - - pub const Operation = enum { - create_accounts, - create_transfers, - lookup_accounts, - lookup_transfers, - get_account_transfers, - get_account_balances, - query_accounts, - query_transfers, - get_change_events, - - const VersionMap = std.EnumArray(Operation, StateMachine.Operation); - /// Variations of operations supported by the state machine, - /// including deprecated ones used by old clients. - const versions: []const VersionMap = &.{ - .init(.{ - .create_accounts = .create_accounts, - .create_transfers = .create_transfers, - .lookup_accounts = .lookup_accounts, - .lookup_transfers = .lookup_transfers, - .get_account_transfers = .get_account_transfers, - .get_account_balances = .get_account_balances, - .query_accounts = .query_accounts, - .query_transfers = .query_transfers, - .get_change_events = .get_change_events, - }), - .init(.{ - .create_accounts = .deprecated_create_accounts_sparse, - .create_transfers = .deprecated_create_transfers_sparse, - .lookup_accounts = .lookup_accounts, - .lookup_transfers = .lookup_transfers, - .get_account_transfers = .get_account_transfers, - .get_account_balances = .get_account_balances, - .query_accounts = .query_accounts, - .query_transfers = .query_transfers, - .get_change_events = .get_change_events, - }), - .init(.{ - .create_accounts = .deprecated_create_accounts_unbatched, - .create_transfers = .deprecated_create_transfers_unbatched, - .lookup_accounts = .deprecated_lookup_accounts_unbatched, - .lookup_transfers = .deprecated_lookup_transfers_unbatched, - .get_account_transfers = .deprecated_get_account_transfers_unbatched, - .get_account_balances = .deprecated_get_account_balances_unbatched, - .query_accounts = .deprecated_query_accounts_unbatched, - .query_transfers = .deprecated_query_transfers_unbatched, - .get_change_events = .get_change_events, - }), - }; - }; - - storage: Storage, - time_sim: TimeSim, - trace: Tracer, - superblock: SuperBlock, - grid: Grid, - state_machine: StateMachine, - op: u64, - busy: bool, - - pub fn init(ctx: *TestContext, allocator: mem.Allocator) !void { - ctx.storage = try fixtures.init_storage(allocator, .{ .size = 4096 }); - errdefer ctx.storage.deinit(allocator); - - ctx.time_sim = fixtures.init_time(.{}); - - ctx.trace = try fixtures.init_tracer(allocator, ctx.time_sim.time(), .{}); - errdefer ctx.trace.deinit(allocator); - - ctx.superblock = try fixtures.init_superblock(allocator, &ctx.storage, .{ - .storage_size_limit = data_file_size_min, - }); - errdefer ctx.superblock.deinit(allocator); - - // Pretend that the superblock is open so that the Forest can initialize. - ctx.superblock.opened = true; - ctx.superblock.working.vsr_state.checkpoint.header.op = 0; - - ctx.grid = try fixtures.init_grid(allocator, &ctx.trace, &ctx.superblock, .{}); - errdefer ctx.grid.deinit(allocator); - - const batch_size_limit = 30 * @max(@sizeOf(Account), @sizeOf(Transfer)); - assert(batch_size_limit <= constants.message_body_size_max); - try ctx.state_machine.init( - allocator, - ctx.time_sim.time(), - &ctx.grid, - .{ - .batch_size_limit = batch_size_limit, - .lsm_forest_compaction_block_count = StateMachine.Forest.Options - .compaction_block_count_min, - .lsm_forest_node_count = 1, - .cache_entries_accounts = 0, - .cache_entries_transfers = 0, - .cache_entries_transfers_pending = 0, - .log_trace = true, - .aof_recovery = false, - }, - ); - errdefer ctx.state_machine.deinit(allocator); - // Usually, `pulse_next_timestamp` starts in an unknown state, signaling that the state - // machine needs a `pulse` to scan for pending transfers and correctly determine when to - // process the next expiry. However, this initial `pulse` unnecessarily bumps time, making - // unit tests that depend on the `timestamp` harder to reason about. - // - // Since this is a newly created state machine, we can bypass the initial check, ensuring - // that there will be no `timestamp` bumps between operations unless actual pending - // transfers get expired. - ctx.state_machine.expire_pending_transfers - .pulse_next_timestamp = TimestampRange.timestamp_max; - - ctx.op = 1; - ctx.busy = false; - } - - pub fn deinit(ctx: *TestContext, allocator: mem.Allocator) void { - ctx.state_machine.deinit(allocator); - ctx.grid.deinit(allocator); - ctx.superblock.deinit(allocator); - ctx.trace.deinit(allocator); - ctx.storage.deinit(allocator); - ctx.* = undefined; - } - - fn callback(state_machine: *StateMachine) void { - const ctx: *TestContext = @fieldParentPtr("state_machine", state_machine); - assert(ctx.busy); - ctx.busy = false; - } - - fn submit( - context: *TestContext, - operation: TestContext.StateMachine.Operation, - input_buffer: []align(constants.cache_line_size) u8, - input_size: u32, - output_buffer: *align(constants.cache_line_size) [constants.message_body_size_max]u8, - ) []const u8 { - const message_body: []align(constants.cache_line_size) const u8 = message_body: { - if (!operation.is_multi_batch()) { - break :message_body input_buffer[0..input_size]; - } - assert(operation.is_multi_batch()); - const event_size = operation.event_size(); - var body_encoder = MultiBatchEncoder.init(input_buffer, .{ - .element_size = event_size, - }); - body_encoder.add(input_size); - const bytes_written = body_encoder.finish(); - assert(bytes_written > 0); - break :message_body input_buffer[0..bytes_written]; - }; - context.prepare(operation, message_body); - - const pulse_needed = context.state_machine.pulse_needed( - context.state_machine.prepare_timestamp, - ); - maybe(pulse_needed); - // Pulse is executed in a best-effort manner - // after committing the current pipelined operation. - defer if (pulse_needed) context.pulse(); - - const reply_actual_size = context.execute( - context.op, - operation, - message_body, - output_buffer, - ); - - if (!operation.is_multi_batch()) { - return output_buffer[0..reply_actual_size]; - } - assert(operation.is_multi_batch()); - - const result_size = operation.result_size(); - var reply_decoder = MultiBatchDecoder.init( - output_buffer[0..reply_actual_size], - .{ .element_size = result_size }, - ) catch unreachable; - assert(reply_decoder.batch_count() == 1); - return reply_decoder.peek(); - } - - pub fn prepare( - context: *TestContext, - operation: TestContext.StateMachine.Operation, - message_body_used: []align(constants.cache_line_size) const u8, - ) void { - context.state_machine.commit_timestamp = context.state_machine.prepare_timestamp; - context.state_machine.prepare_timestamp += 1; - context.state_machine.prepare( - operation, - message_body_used, - ); - } - - fn pulse(context: *TestContext) void { - if (context.state_machine.pulse_needed(context.state_machine.prepare_timestamp)) { - const operation = vsr.Operation.pulse.cast(TestContext.StateMachine.Operation); - context.prepare(operation, &.{}); - const pulse_size = context.execute( - context.op, - operation, - &.{}, - undefined, // Output is never used for pulse. - ); - assert(pulse_size == 0); - context.op += 1; - } - } - - pub fn execute( - context: *TestContext, - op: u64, - operation: TestContext.StateMachine.Operation, - message_body_used: []align(constants.cache_line_size) const u8, - output_buffer: *align(constants.cache_line_size) [constants.message_body_size_max]u8, - ) usize { - const timestamp = context.state_machine.prepare_timestamp; - context.busy = true; - context.state_machine.prefetch_timestamp = timestamp; - context.state_machine.prefetch( - TestContext.callback, - op, - op, - operation, - message_body_used, - ); - while (context.busy) context.storage.run(); - - return context.state_machine.commit( - 1, - op, - timestamp, - operation, - message_body_used, - output_buffer, - ); - } - - fn get_account_from_cache(context: *TestContext, id: u128) ?Account { - return switch (context.state_machine.forest.grooves.accounts.get(id)) { - .found_object => |object| object, - .not_found => null, - }; - } -}; - -const TestAction = union(enum) { - // Set the account's balance. - setup: struct { - account: u128, - debits_pending: u128, - debits_posted: u128, - credits_pending: u128, - credits_posted: u128, - }, - - tick: struct { - value: i64, - unit: enum { nanoseconds, seconds }, - }, - - commit: TestContext.Operation, - account: TestCreateAccount, - transfer: TestCreateTransfer, - - lookup_account: struct { - id: u128, - data: ?struct { - debits_pending: u128, - debits_posted: u128, - credits_pending: u128, - credits_posted: u128, - flag_closed: ?enum { CLSD } = null, - } = null, - }, - lookup_transfer: struct { - id: u128, - data: union(enum) { - exists: bool, - amount: u128, - timestamp: u64, - }, - }, - - get_account_balances: TestGetAccountBalances, - get_account_balances_result: struct { - transfer_id: u128, - debits_pending: u128, - debits_posted: u128, - credits_pending: u128, - credits_posted: u128, - }, - - get_account_transfers: TestGetAccountTransfers, - get_account_transfers_result: u128, - - query_accounts: TestQueryAccounts, - query_accounts_result: struct { - id: u128, - data: ?struct { - debits_pending: u128, - debits_posted: u128, - credits_pending: u128, - credits_posted: u128, - flag_closed: ?enum { CLSD } = null, - } = null, - }, - - query_transfers: TestQueryTransfers, - query_transfers_result: u128, - - get_change_events: TestGetChangeEventsFilter, - get_change_events_result: TestGetChangeEventsResult, -}; - -const TestCreateAccount = struct { - id: u128, - debits_pending: u128 = 0, - debits_posted: u128 = 0, - credits_pending: u128 = 0, - credits_posted: u128 = 0, - user_data_128: u128 = 0, - user_data_64: u64 = 0, - user_data_32: u32 = 0, - reserved: u1 = 0, - ledger: u32, - code: u16, - flags_linked: ?enum { LNK } = null, - flags_debits_must_not_exceed_credits: ?enum { @"D .two_phase_pending, - .POS => .two_phase_posted, - .VOI => .two_phase_voided, - .EXP => .two_phase_expired, - }; - if (event.type != expected) return false; - } else { - if (event.type != .single_phase) return false; - } - if (event.transfer_amount != self.amount) return false; - if (self.transfer_pending_id) |transfer_pending_id| { - switch (event.type) { - .two_phase_pending, .single_phase => return false, - .two_phase_posted, .two_phase_voided => { - if (event.transfer_pending_id != transfer_pending_id) return false; - }, - .two_phase_expired => { - const transfer = transfers.get(transfer_pending_id).?; - if (transfer.timeout == 0) return false; - if (event.timestamp < - transfer.timestamp + transfer.timeout_ns()) return false; - if (!match_transfer(event, &transfer)) return false; - }, - } - } - - const dr_account = accounts.get(self.dr_account.account_id).?; - if (dr_account.ledger != event.ledger) return false; - if (self.dr_account.account_id != event.debit_account_id) return false; - if (dr_account.timestamp != event.debit_account_timestamp) return false; - if (self.dr_account.debits_pending != event.debit_account_debits_pending) return false; - if (self.dr_account.debits_posted != event.debit_account_debits_posted) return false; - if (self.dr_account.credits_pending != event.debit_account_credits_pending) return false; - if (self.dr_account.credits_posted != event.debit_account_credits_posted) return false; - if ((self.dr_account.closed == .CLSD) != event.debit_account_flags.closed) return false; - - const cr_account = accounts.get(self.cr_account.account_id).?; - if (cr_account.ledger != event.ledger) return false; - if (self.cr_account.account_id != event.credit_account_id) return false; - if (cr_account.timestamp != event.credit_account_timestamp) return false; - if (self.cr_account.debits_pending != event.credit_account_debits_pending) return false; - if (self.cr_account.debits_posted != event.credit_account_debits_posted) return false; - if (self.cr_account.credits_pending != event.credit_account_credits_pending) return false; - if (self.cr_account.credits_posted != event.credit_account_credits_posted) return false; - if ((self.cr_account.closed == .CLSD) != event.credit_account_flags.closed) return false; - - return true; - } - - fn match_transfer(event: *const ChangeEvent, transfer: *const tb.Transfer) bool { - if (event.transfer_timestamp != transfer.timestamp) return false; - if (event.transfer_id != transfer.id) return false; - if (event.transfer_amount != transfer.amount and - // The in-memory model keeps the `AMOUNT_MAX`. - transfer.amount != std.math.maxInt(u128)) return false; - if (event.transfer_pending_id != transfer.pending_id) return false; - if (event.transfer_user_data_128 != transfer.user_data_128) return false; - if (event.transfer_user_data_64 != transfer.user_data_64) return false; - if (event.transfer_user_data_32 != transfer.user_data_32) return false; - if (event.transfer_code != transfer.code) return false; - if (event.ledger != transfer.ledger) return false; - if (event.ledger != transfer.ledger) return false; - if (@as(u16, @bitCast(transfer.flags)) != - @as(u16, @bitCast(event.transfer_flags))) return false; - return true; - } -}; - -// Operations that share the same input. -const TestGetAccountBalances = TestAccountFilter; -const TestGetAccountTransfers = TestAccountFilter; -const TestQueryAccounts = TestQueryFilter; -const TestQueryTransfers = TestQueryFilter; - -fn check(test_table: []const u8) !void { - const parse_table = @import("testing/table.zig").parse; - const test_actions = parse_table(TestAction, test_table); - - // Runs the same test for each variation of supported operations, - // simulating different client versions. - for (TestContext.Operation.versions) |*version_map| { - try check_version( - test_actions.const_slice(), - version_map, - ); - } -} - -fn check_version( - test_actions: []const TestAction, - version_map: *const TestContext.Operation.VersionMap, -) !void { - const allocator = std.testing.allocator; - - var context: TestContext = undefined; - try context.init(allocator); - defer context.deinit(allocator); - - var accounts = std.AutoHashMap(u128, Account).init(allocator); - defer accounts.deinit(); - - var transfers = std.AutoHashMap(u128, Transfer).init(allocator); - defer transfers.deinit(); - - // The result code `.exists` always returns the timestamp of the original event. - // Even if the existing event was created within a linked chain and rolled back. - // For example, the linked chain: - // events: { id=1, flags=linked; id=1 } - // results: { result=linked_event_failed, timestamp=100; result=exists, timestamp=100 } - // ^^^ ^^^ - var linked_events_failed: std.AutoHashMap(u128, u64) = .init(allocator); - defer linked_events_failed.deinit(); - - var request: std.ArrayListAligned(u8, constants.cache_line_size) = .init(allocator); - defer request.deinit(); - - try request.ensureTotalCapacity(constants.message_body_size_max); - - var reply: std.ArrayListAligned(u8, constants.cache_line_size) = .init(allocator); - defer reply.deinit(); - - var operation: ?TestContext.Operation = null; - for (test_actions) |test_action| { - switch (test_action) { - .setup => |b| { - assert(operation == null); - - const account = context.get_account_from_cache(b.account).?; - var account_new = account; - - account_new.debits_pending = b.debits_pending; - account_new.debits_posted = b.debits_posted; - account_new.credits_pending = b.credits_pending; - account_new.credits_posted = b.credits_posted; - assert(!account_new.debits_exceed_credits(0)); - assert(!account_new.credits_exceed_debits(0)); - - if (!stdx.equal_bytes(Account, &account_new, &account)) { - context.state_machine.forest.grooves.accounts.update(.{ - .old = &account, - .new = &account_new, - }); - } - }, - .tick => |ticks| { - assert(ticks.value != 0); - - const interval_ns: u64 = @abs(ticks.value) * - @as(u64, switch (ticks.unit) { - .nanoseconds => 1, - .seconds => std.time.ns_per_s, - }); - - // The `parse` logic already computes `maxInt - value` when a unsigned int is - // represented as a negative number. However, we need to use a signed int and - // perform our own calculation to account for the unit. - context.state_machine.prepare_timestamp += if (ticks.value > 0) - interval_ns - else - TimestampRange.timestamp_max - interval_ns; - - // Pulse is executed when the cluster is idle. - context.pulse(); - }, - .account => |a| { - assert(operation == null or operation.? == .create_accounts); - operation = .create_accounts; - - var event = a.event(); - try request.appendSlice(std.mem.asBytes(&event)); - - const timestamp_commit = context.state_machine.prepare_timestamp + 1 + - @divExact(request.items.len, @sizeOf(Account)); - if (event.timestamp == 0) event.timestamp = timestamp_commit; - if (a.status == .created) { - try accounts.put(a.id, event); - } - - switch (version_map.get(.create_accounts)) { - .create_accounts => { - const result = CreateAccountResult{ - .timestamp = timestamp_expected: { - if (a.status == .created or a.status == .linked_event_failed) { - break :timestamp_expected event.timestamp; - } - if (a.status == .exists) { - break :timestamp_expected if (accounts.get(a.id)) |exists| - exists.timestamp - else - linked_events_failed.get(a.id).?; - } - break :timestamp_expected timestamp_commit; - }, - .status = a.status, - }; - try reply.appendSlice(std.mem.asBytes(&result)); - - if (event.flags.linked) { - if (a.status == .linked_event_failed) { - try linked_events_failed.putNoClobber(event.id, event.timestamp); - } - } else { - linked_events_failed.clearRetainingCapacity(); - } - }, - .deprecated_create_accounts_sparse, - .deprecated_create_accounts_unbatched, - => if (a.status != .created) { - const result = tb.CreateAccountErrorResult{ - .index = @intCast(@divExact(request.items.len, @sizeOf(Account)) - 1), - .result = a.status, - }; - try reply.appendSlice(std.mem.asBytes(&result)); - }, - else => unreachable, - } - }, - .transfer => |t| { - assert(operation == null or operation.? == .create_transfers); - operation = .create_transfers; - - var event = t.event(); - try request.appendSlice(std.mem.asBytes(&event)); - - const timestamp_commit = context.state_machine.prepare_timestamp + 1 + - @divExact(request.items.len, @sizeOf(Transfer)); - if (t.timestamp == 0) event.timestamp = timestamp_commit; - if (t.status == .created) { - if (event.pending_id != 0) { - // Fill in default values. - const t_pending = transfers.get(event.pending_id).?; - inline for (.{ - "debit_account_id", - "credit_account_id", - "ledger", - "code", - "user_data_128", - "user_data_64", - "user_data_32", - }) |field| { - if (@field(event, field) == 0) { - @field(event, field) = @field(t_pending, field); - } - } - - if (event.flags.void_pending_transfer) { - if (event.amount == 0) event.amount = t_pending.amount; - } - } - try transfers.put(t.id, event); - } - - switch (version_map.get(.create_transfers)) { - .create_transfers => { - const result: CreateTransferResult = .{ - .timestamp = timestamp_expected: { - if (t.status == .created or t.status == .linked_event_failed) { - break :timestamp_expected event.timestamp; - } - if (t.status == .exists) { - break :timestamp_expected if (transfers.get(t.id)) |exists| - exists.timestamp - else - linked_events_failed.get(t.id).?; - } - break :timestamp_expected timestamp_commit; - }, - .status = t.status, - }; - try reply.appendSlice(std.mem.asBytes(&result)); - - if (event.flags.linked) { - if (t.status == .linked_event_failed) { - try linked_events_failed.putNoClobber(event.id, event.timestamp); - } - } else { - linked_events_failed.clearRetainingCapacity(); - } - }, - .deprecated_create_transfers_sparse, - .deprecated_create_transfers_unbatched, - => if (t.status != .created) { - const result: tb.CreateTransferErrorResult = .{ - .index = @intCast(@divExact(request.items.len, @sizeOf(Transfer)) - 1), - .result = t.status, - }; - try reply.appendSlice(std.mem.asBytes(&result)); - }, - else => unreachable, - } - }, - .lookup_account => |a| { - assert(operation == null or operation.? == .lookup_accounts); - operation = .lookup_accounts; - - try request.appendSlice(std.mem.asBytes(&a.id)); - if (a.data) |data| { - var account = accounts.get(a.id).?; - account.debits_pending = data.debits_pending; - account.debits_posted = data.debits_posted; - account.credits_pending = data.credits_pending; - account.credits_posted = data.credits_posted; - account.flags.closed = data.flag_closed != null; - try reply.appendSlice(std.mem.asBytes(&account)); - } - }, - .lookup_transfer => |t| { - assert(operation == null or operation.? == .lookup_transfers); - operation = .lookup_transfers; - - try request.appendSlice(std.mem.asBytes(&t.id)); - switch (t.data) { - .exists => |exists| { - if (exists) { - var transfer = transfers.get(t.id).?; - try reply.appendSlice(std.mem.asBytes(&transfer)); - } - }, - .amount => |amount| { - var transfer = transfers.get(t.id).?; - transfer.amount = amount; - try reply.appendSlice(std.mem.asBytes(&transfer)); - }, - .timestamp => |timestamp| { - var transfer = transfers.get(t.id).?; - transfer.timestamp = timestamp; - try reply.appendSlice(std.mem.asBytes(&transfer)); - }, - } - }, - .get_account_balances => |f| { - assert(operation == null or operation.? == .get_account_balances); - operation = .get_account_balances; - - const timestamp_min = - if (f.timestamp_min_transfer_id) |id| transfers.get(id).?.timestamp else 0; - const timestamp_max = - if (f.timestamp_max_transfer_id) |id| transfers.get(id).?.timestamp else 0; - - const event = AccountFilter{ - .account_id = f.account_id, - .user_data_128 = f.user_data_128 orelse 0, - .user_data_64 = f.user_data_64 orelse 0, - .user_data_32 = f.user_data_32 orelse 0, - .code = f.code orelse 0, - .timestamp_min = timestamp_min, - .timestamp_max = timestamp_max, - .limit = f.limit, - .flags = .{ - .debits = f.flags_debits != null, - .credits = f.flags_credits != null, - .reversed = f.flags_reversed != null, - }, - }; - try request.appendSlice(std.mem.asBytes(&event)); - }, - .get_account_balances_result => |r| { - assert(operation.? == .get_account_balances); - - const balance = AccountBalance{ - .debits_pending = r.debits_pending, - .debits_posted = r.debits_posted, - .credits_pending = r.credits_pending, - .credits_posted = r.credits_posted, - .timestamp = transfers.get(r.transfer_id).?.timestamp, - }; - try reply.appendSlice(std.mem.asBytes(&balance)); - }, - .get_account_transfers => |f| { - assert(operation == null or operation.? == .get_account_transfers); - operation = .get_account_transfers; - - const timestamp_min = - if (f.timestamp_min_transfer_id) |id| transfers.get(id).?.timestamp else 0; - const timestamp_max = - if (f.timestamp_max_transfer_id) |id| transfers.get(id).?.timestamp else 0; - - const event = AccountFilter{ - .account_id = f.account_id, - .user_data_128 = f.user_data_128 orelse 0, - .user_data_64 = f.user_data_64 orelse 0, - .user_data_32 = f.user_data_32 orelse 0, - .code = f.code orelse 0, - .timestamp_min = timestamp_min, - .timestamp_max = timestamp_max, - .limit = f.limit, - .flags = .{ - .debits = f.flags_debits != null, - .credits = f.flags_credits != null, - .reversed = f.flags_reversed != null, - }, - }; - try request.appendSlice(std.mem.asBytes(&event)); - }, - .get_account_transfers_result => |id| { - assert(operation.? == .get_account_transfers); - try reply.appendSlice(std.mem.asBytes(&transfers.get(id).?)); - }, - .query_accounts => |f| { - assert(operation == null or operation.? == .query_accounts); - operation = .query_accounts; - - const timestamp_min = if (f.timestamp_min_transfer_id) |id| - accounts.get(id).?.timestamp - else - 0; - const timestamp_max = if (f.timestamp_max_transfer_id) |id| - accounts.get(id).?.timestamp - else - 0; - - const event = QueryFilter{ - .user_data_128 = f.user_data_128, - .user_data_64 = f.user_data_64, - .user_data_32 = f.user_data_32, - .ledger = f.ledger, - .code = f.code, - .timestamp_min = timestamp_min, - .timestamp_max = timestamp_max, - .limit = f.limit, - .flags = .{ - .reversed = f.flags_reversed != null, - }, - }; - try request.appendSlice(std.mem.asBytes(&event)); - }, - .query_accounts_result => |a| { - assert(operation.? == .query_accounts); - var account = accounts.get(a.id).?; - if (a.data) |data| { - account.debits_pending = data.debits_pending; - account.debits_posted = data.debits_posted; - account.credits_pending = data.credits_pending; - account.credits_posted = data.credits_posted; - account.flags.closed = data.flag_closed != null; - } - try reply.appendSlice(std.mem.asBytes(&account)); - }, - .query_transfers => |f| { - assert(operation == null or operation.? == .query_transfers); - operation = .query_transfers; - - const timestamp_min = if (f.timestamp_min_transfer_id) |id| - transfers.get(id).?.timestamp - else - 0; - const timestamp_max = if (f.timestamp_max_transfer_id) |id| - transfers.get(id).?.timestamp - else - 0; - - const event = QueryFilter{ - .user_data_128 = f.user_data_128, - .user_data_64 = f.user_data_64, - .user_data_32 = f.user_data_32, - .ledger = f.ledger, - .code = f.code, - .timestamp_min = timestamp_min, - .timestamp_max = timestamp_max, - .limit = f.limit, - .flags = .{ - .reversed = f.flags_reversed != null, - }, - }; - try request.appendSlice(std.mem.asBytes(&event)); - }, - .query_transfers_result => |id| { - assert(operation.? == .query_transfers); - try reply.appendSlice(std.mem.asBytes(&transfers.get(id).?)); - }, - .get_change_events => |f| { - assert(operation == null or operation.? == .get_change_events); - operation = .get_change_events; - const timestamp_min = if (f.timestamp_min_transfer_id) |id| - transfers.get(id).?.timestamp - else - 0; - const timestamp_max = if (f.timestamp_max_transfer_id) |id| - transfers.get(id).?.timestamp - else - 0; - - const event = ChangeEventsFilter{ - .timestamp_min = timestamp_min, - .timestamp_max = timestamp_max, - .limit = f.limit, - }; - try request.appendSlice(std.mem.asBytes(&event)); - }, - .get_change_events_result => |*t| { - assert(operation.? == .get_change_events); - try reply.appendSlice(std.mem.asBytes(t)); - }, - .commit => |commit_operation| { - assert(operation == null or operation.? == commit_operation); - assert(!context.busy); - - const reply_actual_buffer = try allocator.alignedAlloc( - u8, - constants.cache_line_size, - constants.message_body_size_max, - ); - defer allocator.free(reply_actual_buffer); - - const payload_size: u32 = @intCast(request.items.len); - request.expandToCapacity(); - - const operation_actual = version_map.get(commit_operation); - const reply_actual = context.submit( - operation_actual, - request.items, - payload_size, - reply_actual_buffer[0..constants.message_body_size_max], - ); - - switch (operation_actual) { - inline else => |operation_actual_comptime| { - const Result = operation_actual_comptime.ResultType(); - try testing.expectEqualSlices( - Result, - stdx.bytes_as_slice(.exact, Result, reply.items), - stdx.bytes_as_slice(.exact, Result, reply_actual), - ); - }, - .get_change_events => { - const results_actual = stdx.bytes_as_slice( - .exact, - ChangeEvent, - reply_actual, - ); - const results_expected = stdx.bytes_as_slice( - .exact, - TestGetChangeEventsResult, - reply.items, - ); - try testing.expectEqual(results_expected.len, results_actual.len); - for (results_actual, results_expected) |*actual, *expected| { - try testing.expect(expected.match(&accounts, &transfers, actual)); - } - }, - .pulse => unreachable, - } - - request.clearRetainingCapacity(); - reply.clearRetainingCapacity(); - operation = null; - }, - } - } - - assert(operation == null); - assert(request.items.len == 0); - assert(reply.items.len == 0); -} - -test "create_accounts" { - try check( - \\ account A1 0 0 0 0 U2 U2 U2 _ L3 C4 _ _ _ _ _ _ _ _ created - \\ account A0 1 1 1 1 _ _ _ 1 L0 C0 _ D e.amount - \\ transfer T101 A0 A0 14 T2 U0 U0 U0 _ L0 C0 _ _ POS _ _ _ _ _ _ _ _ exists_with_different_amount - \\ transfer T101 A0 A0 12 T2 U0 U0 U0 _ L0 C0 _ _ POS _ _ _ _ _ _ _ _ exists_with_different_amount // t.amount < e.amount - \\ - \\ transfer T105 A0 A0 8 T5 U0 U0 U0 _ L0 C0 _ _ POS _ _ _ _ _ _ _ _ exceeds_pending_transfer_amount // t.amount > p.amount - \\ transfer T105 A0 A0 -0 T5 U0 U0 U0 _ L0 C0 _ _ POS _ _ _ _ _ _ _ _ created - \\ transfer T105 A0 A0 7 T5 U0 U0 U0 _ L1 C1 _ _ POS _ _ _ _ _ _ _ _ exists - \\ transfer T105 A0 A0 7 T5 U0 U0 U0 _ L0 C0 _ _ POS _ _ _ _ _ _ _ _ exists // ledger/code = 0 - \\ transfer T105 A0 A0 -0 T5 U0 U0 U0 _ L1 C1 _ _ POS _ _ _ _ _ _ _ _ exists // amount = max - \\ transfer T105 A0 A0 8 T5 U0 U0 U0 _ L0 C0 _ _ POS _ _ _ _ _ _ _ _ exists_with_different_amount // t.amount > p.amount - \\ transfer T105 A0 A0 6 T5 U0 U0 U0 _ L0 C0 _ _ POS _ _ _ _ _ _ _ _ exists_with_different_amount // t.amount < e.amount - \\ transfer T105 A0 A0 0 T5 U0 U0 U0 _ L1 C1 _ _ POS _ _ _ _ _ _ _ _ exists_with_different_amount - \\ - \\ transfer T106 A0 A0 -1 T6 U0 U0 U0 _ L1 C1 _ _ POS _ _ _ _ _ _ _ _ exceeds_pending_transfer_amount - \\ transfer T106 A0 A0 -0 T6 U0 U0 U0 _ L1 C1 _ _ POS _ _ _ _ _ _ _ _ created - \\ transfer T106 A0 A0 -0 T6 U0 U0 U0 _ L1 C1 _ _ POS _ _ _ _ _ _ _ _ exists - \\ transfer T106 A0 A0 1 T6 U0 U0 U0 _ L0 C0 _ _ POS _ _ _ _ _ _ _ _ exists - \\ transfer T106 A0 A0 2 T6 U0 U0 U0 _ L1 C1 _ _ POS _ _ _ _ _ _ _ _ exists_with_different_amount // t.amount > p.amount - \\ transfer T106 A0 A0 0 T6 U0 U0 U0 _ L1 C1 _ _ POS _ _ _ _ _ _ _ _ exists_with_different_amount // t.amount < p.amount - \\ - \\ transfer T107 A0 A0 0 T7 U0 U0 U0 _ L0 C0 _ _ POS _ _ _ _ _ _ _ _ created - \\ transfer T107 A0 A0 0 T7 U0 U0 U0 _ L0 C0 _ _ POS _ _ _ _ _ _ _ _ exists - \\ transfer T107 A0 A0 1 T7 U0 U0 U0 _ L0 C0 _ _ POS _ _ _ _ _ _ _ _ exists_with_different_amount // t.amount > e.amount - \\ commit create_transfers - - // Check balances after resolving. - \\ lookup_account A1 0 36 0 0 _ - \\ lookup_account A2 0 0 0 36 _ - \\ commit lookup_accounts - - // The posted transfer amounts are set to the actual amount posted (which may be less than - // the "client" set as the amount). - \\ lookup_transfer T101 amount 13 - \\ lookup_transfer T105 amount 7 - \\ lookup_transfer T106 amount 1 - \\ lookup_transfer T107 amount 0 - \\ commit lookup_transfers - ); -} - -test "create/lookup 2-phase transfers (amount=maxInt)" { - try check( - \\ account A1 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ account A2 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ commit create_accounts - - // Posting maxInt(u128) is a pun – it is interpreted as "send full pending amount", which in - // this case is exactly maxInt(u127). - \\ transfer T1 A1 A2 -0 _ _ _ _ _ L1 C1 _ PEN _ _ _ _ _ _ _ _ _ created - \\ transfer T2 A1 A2 -0 T1 _ _ _ _ L1 C1 _ _ POS _ _ _ _ _ _ _ _ created - \\ transfer T2 A1 A2 -0 T1 _ _ _ _ L1 C1 _ _ POS _ _ _ _ _ _ _ _ exists - \\ commit create_transfers - - // Check balances after resolving. - \\ lookup_account A1 0 -0 0 0 _ - \\ lookup_account A2 0 0 0 -0 _ - \\ commit lookup_accounts - \\ - \\ lookup_transfer T1 amount -0 - \\ lookup_transfer T2 amount -0 - \\ commit lookup_transfers - ); -} - -test "create/lookup expired transfers" { - try check( - \\ account A1 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ account A2 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ commit create_accounts - - // First phase. - \\ transfer T1 A1 A2 10 _ _ _ _ 0 L1 C1 _ PEN _ _ _ _ _ _ _ _ _ created // Timeout zero will never expire. - \\ transfer T2 A1 A2 11 _ _ _ _ 1 L1 C1 _ PEN _ _ _ _ _ _ _ _ _ created - \\ transfer T3 A1 A2 12 _ _ _ _ 2 L1 C1 _ PEN _ _ _ _ _ _ _ _ _ created - \\ transfer T4 A1 A2 13 _ _ _ _ 3 L1 C1 _ PEN _ _ _ _ _ _ _ _ _ created - \\ commit create_transfers - - // Check balances before expiration. - \\ lookup_account A1 46 0 0 0 _ - \\ lookup_account A2 0 0 46 0 _ - \\ commit lookup_accounts - - // Check balances after 1s. - \\ tick 1 seconds - \\ lookup_account A1 35 0 0 0 _ - \\ lookup_account A2 0 0 35 0 _ - \\ commit lookup_accounts - - // Check balances after 1s. - \\ tick 1 seconds - \\ lookup_account A1 23 0 0 0 _ - \\ lookup_account A2 0 0 23 0 _ - \\ commit lookup_accounts - - // Check balances after 1s. - \\ tick 1 seconds - \\ lookup_account A1 10 0 0 0 _ - \\ lookup_account A2 0 0 10 0 _ - \\ commit lookup_accounts - - // Second phase. - \\ transfer T101 A1 A2 10 T1 U1 U1 U1 _ L1 C1 _ _ POS _ _ _ _ _ _ _ _ created - \\ transfer T102 A1 A2 11 T2 U1 U1 U1 _ L1 C1 _ _ POS _ _ _ _ _ _ _ _ pending_transfer_expired - \\ transfer T103 A1 A2 12 T3 U1 U1 U1 _ L1 C1 _ _ POS _ _ _ _ _ _ _ _ pending_transfer_expired - \\ transfer T104 A1 A2 13 T4 U1 U1 U1 _ L1 C1 _ _ POS _ _ _ _ _ _ _ _ pending_transfer_expired - \\ commit create_transfers - - // Check final balances. - \\ lookup_account A1 0 10 0 0 _ - \\ lookup_account A2 0 0 0 10 _ - \\ commit lookup_accounts - - // Check transfers. - \\ lookup_transfer T101 exists true - \\ lookup_transfer T102 exists false - \\ lookup_transfer T103 exists false - \\ lookup_transfer T104 exists false - \\ commit lookup_transfers - ); -} - -test "create_transfers: empty" { - try check( - \\ commit create_transfers - ); -} - -test "create_transfers/lookup_transfers: failed transfer does not exist" { - try check( - \\ account A1 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ account A2 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ commit create_accounts - \\ - \\ transfer T1 A1 A2 15 _ _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ _ _ _ created - \\ transfer T2 A1 A2 15 _ _ _ _ _ L0 C1 _ _ _ _ _ _ _ _ _ _ _ ledger_must_not_be_zero - \\ commit create_transfers - \\ - \\ lookup_account A1 0 15 0 0 _ - \\ lookup_account A2 0 0 0 15 _ - \\ commit lookup_accounts - \\ - \\ lookup_transfer T1 exists true - \\ lookup_transfer T2 exists false - \\ commit lookup_transfers - ); -} - -test "create_transfers: failed linked-chains are undone" { - try check( - \\ account A1 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ account A2 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ commit create_accounts - \\ - \\ transfer T1 A1 A2 15 _ _ _ _ _ L1 C1 LNK _ _ _ _ _ _ _ _ _ _ linked_event_failed - \\ transfer T2 A1 A2 15 _ _ _ _ _ L0 C1 _ _ _ _ _ _ _ _ _ _ _ ledger_must_not_be_zero - \\ commit create_transfers - \\ - \\ transfer T3 A1 A2 15 _ _ _ _ 1 L1 C1 LNK PEN _ _ _ _ _ _ _ _ _ linked_event_failed - \\ transfer T4 A1 A2 15 _ _ _ _ _ L0 C1 _ _ _ _ _ _ _ _ _ _ _ ledger_must_not_be_zero - \\ commit create_transfers - \\ - \\ lookup_account A1 0 0 0 0 _ - \\ lookup_account A2 0 0 0 0 _ - \\ commit lookup_accounts - \\ - \\ lookup_transfer T1 exists false - \\ lookup_transfer T2 exists false - \\ lookup_transfer T3 exists false - \\ lookup_transfer T4 exists false - \\ commit lookup_transfers - ); -} - -test "create_transfers: failed linked-chains are undone within a commit" { - try check( - \\ account A1 0 0 0 0 _ _ _ _ L1 C1 _ D0. - \\ get_account_transfers A1 _ _ _ _ T3 _ 10 DR CR _ - \\ get_account_transfers_result T3 - \\ get_account_transfers_result T4 - \\ commit get_account_transfers - \\ - // Debits + credits, timestamp_max>0. - \\ get_account_transfers A1 _ _ _ _ _ T2 10 DR CR _ - \\ get_account_transfers_result T1 - \\ get_account_transfers_result T2 - \\ commit get_account_transfers - \\ - // Debits + credits, 0 < timestamp_min ≤ timestamp_max. - \\ get_account_transfers A1 _ _ _ _ T2 T3 10 DR CR _ - \\ get_account_transfers_result T2 - \\ get_account_transfers_result T3 - \\ commit get_account_transfers - \\ - // Debits + credits, reverse-chronological. - \\ get_account_transfers A1 _ _ _ _ _ _ 10 DR CR REV - \\ get_account_transfers_result T4 - \\ get_account_transfers_result T3 - \\ get_account_transfers_result T2 - \\ get_account_transfers_result T1 - \\ commit get_account_transfers - \\ - // Debits only. - \\ get_account_transfers A1 _ _ _ _ _ _ 10 DR _ _ - \\ get_account_transfers_result T1 - \\ get_account_transfers_result T3 - \\ commit get_account_transfers - \\ - // Credits only. - \\ get_account_transfers A1 _ _ _ _ _ _ 10 _ CR _ - \\ get_account_transfers_result T2 - \\ get_account_transfers_result T4 - \\ commit get_account_transfers - \\ - // Debits + credits + user_data_128, chronological. - \\ get_account_transfers A1 U1001 _ _ _ _ _ 10 DR CR _ - \\ get_account_transfers_result T2 - \\ get_account_transfers_result T4 - \\ commit get_account_transfers - \\ - // Debits + credits + user_data_64, chronological. - \\ get_account_transfers A1 _ U10 _ _ _ _ 10 DR CR _ - \\ get_account_transfers_result T1 - \\ get_account_transfers_result T2 - \\ commit get_account_transfers - \\ - // Debits + credits + user_data_32, chronological. - \\ get_account_transfers A1 _ _ U1 _ _ _ 10 DR CR _ - \\ get_account_transfers_result T1 - \\ get_account_transfers_result T4 - \\ commit get_account_transfers - \\ - // Debits + credits + code, chronological. - \\ get_account_transfers A1 _ _ _ C1 _ _ 10 DR CR _ - \\ get_account_transfers_result T1 - \\ get_account_transfers_result T3 - \\ commit get_account_transfers - \\ - // Debits + credits + all filters, 0 < timestamp_min ≤ timestamp_max, chronological. - \\ get_account_transfers A1 U1000 U10 U1 C1 T1 T3 10 DR CR _ - \\ get_account_transfers_result T1 - \\ commit get_account_transfers - \\ - // Debits only + all filters, 0 < timestamp_min ≤ timestamp_max, chronological. - \\ get_account_transfers A1 U1000 U10 U1 C1 T1 T3 10 DR _ _ - \\ get_account_transfers_result T1 - \\ commit get_account_transfers - \\ - // Credits only + all filters, 0 < timestamp_min ≤ timestamp_max, chronological. - \\ get_account_transfers A2 U1000 U10 U1 C1 T1 T3 10 _ CR _ - \\ get_account_transfers_result T1 - \\ commit get_account_transfers - \\ - // Not found. - \\ get_account_transfers A1 U1000 U20 U2 C2 _ _ 10 DR CR _ - \\ commit get_account_transfers - ); -} - -test "get_account_transfers: two-phase" { - try check( - \\ account A1 0 0 0 0 _ _ _ _ L1 C1 _ _ _ HIST _ _ _ _ created - \\ account A2 0 0 0 0 _ _ _ _ L1 C1 _ _ _ HIST _ _ _ _ created - \\ commit create_accounts - \\ - \\ transfer T1 A1 A2 2 _ _ _ _ 0 L1 C1 _ PEN _ _ _ _ _ _ _ _ _ created - \\ transfer T2 A1 A2 1 T1 _ _ _ 0 L1 C1 _ _ POS _ _ _ _ _ _ _ _ created - \\ commit create_transfers - \\ - \\ get_account_transfers A1 _ _ _ _ _ _ 10 DR CR _ - \\ get_account_transfers_result T1 - \\ get_account_transfers_result T2 - \\ commit get_account_transfers - ); -} - -test "get_account_transfers: invalid filter" { - try check( - \\ account A1 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ account A2 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ commit create_accounts - \\ - \\ transfer T1 A1 A2 2 _ _ _ _ 0 L1 C1 _ PEN _ _ _ _ _ _ _ _ _ created - \\ transfer T2 A1 A2 1 T1 _ _ _ 0 L1 C1 _ _ POS _ _ _ _ _ _ _ _ created - \\ commit create_transfers - \\ - // Invalid account. - \\ get_account_transfers A3 _ _ _ _ _ _ 10 DR CR _ - \\ commit get_account_transfers // Empty result. - \\ - // Invalid filter flags. - \\ get_account_transfers A1 _ _ _ _ _ _ 10 _ _ _ - \\ commit get_account_transfers // Empty result. - \\ - // Invalid timestamp_min > timestamp_max. - \\ get_account_transfers A1 _ _ _ _ T2 T1 10 DR CR _ - \\ commit get_account_transfers // Empty result. - \\ - // Invalid limit. - \\ get_account_transfers A1 _ _ _ _ _ _ 0 DR CR _ - \\ commit get_account_transfers // Empty result. - \\ - // Success. - \\ get_account_transfers A1 _ _ _ C1 _ _ 10 DR CR _ - \\ get_account_transfers_result T1 - \\ get_account_transfers_result T2 - \\ commit get_account_transfers - ); -} - -test "get_account_balances: single-phase" { - try check( - \\ account A1 0 0 0 0 _ _ _ _ L1 C1 _ _ _ HIST _ _ _ _ created - \\ account A2 0 0 0 0 _ _ _ _ L1 C1 _ _ _ HIST _ _ _ _ created - \\ commit create_accounts - \\ - \\ transfer T1 A1 A2 10 _ U1000 U10 U1 _ L1 C1 _ _ _ _ _ _ _ _ _ _ _ created - \\ transfer T2 A2 A1 11 _ U1001 U10 U2 _ L1 C2 _ _ _ _ _ _ _ _ _ _ _ created - \\ transfer T3 A1 A2 12 _ U1000 U20 U2 _ L1 C1 _ _ _ _ _ _ _ _ _ _ _ created - \\ transfer T4 A2 A1 13 _ U1001 U20 U1 _ L1 C2 _ _ _ _ _ _ _ _ _ _ _ created - \\ commit create_transfers - \\ - // Debits + credits, chronological. - \\ get_account_balances A1 _ _ _ _ _ _ 10 DR CR _ - \\ get_account_balances_result T1 0 10 0 0 - \\ get_account_balances_result T2 0 10 0 11 - \\ get_account_balances_result T3 0 22 0 11 - \\ get_account_balances_result T4 0 22 0 24 - \\ commit get_account_balances - \\ - // Debits + credits, limit=2. - \\ get_account_balances A1 _ _ _ _ _ _ 2 DR CR _ - \\ get_account_balances_result T1 0 10 0 0 - \\ get_account_balances_result T2 0 10 0 11 - \\ commit get_account_balances - \\ - // Debits + credits, timestamp_min>0. - \\ get_account_balances A1 _ _ _ _ T3 _ 10 DR CR _ - \\ get_account_balances_result T3 0 22 0 11 - \\ get_account_balances_result T4 0 22 0 24 - \\ commit get_account_balances - \\ - // Debits + credits, timestamp_max>0. - \\ get_account_balances A1 _ _ _ _ _ T2 10 DR CR _ - \\ get_account_balances_result T1 0 10 0 0 - \\ get_account_balances_result T2 0 10 0 11 - \\ commit get_account_balances - \\ - // Debits + credits, 0 < timestamp_min ≤ timestamp_max. - \\ get_account_balances A1 _ _ _ _ T2 T3 10 DR CR _ - \\ get_account_balances_result T2 0 10 0 11 - \\ get_account_balances_result T3 0 22 0 11 - \\ commit get_account_balances - \\ - // Debits + credits, reverse-chronological. - \\ get_account_balances A1 _ _ _ _ _ _ 10 DR CR REV - \\ get_account_balances_result T4 0 22 0 24 - \\ get_account_balances_result T3 0 22 0 11 - \\ get_account_balances_result T2 0 10 0 11 - \\ get_account_balances_result T1 0 10 0 0 - \\ commit get_account_balances - \\ - // Debits only. - \\ get_account_balances A1 _ _ _ _ _ _ 10 DR _ _ - \\ get_account_balances_result T1 0 10 0 0 - \\ get_account_balances_result T3 0 22 0 11 - \\ commit get_account_balances - \\ - // Credits only. - \\ get_account_balances A1 _ _ _ _ _ _ 10 _ CR _ - \\ get_account_balances_result T2 0 10 0 11 - \\ get_account_balances_result T4 0 22 0 24 - \\ commit get_account_balances - \\ - // Debits + credits + user_data_128, chronological. - \\ get_account_balances A1 U1001 _ _ _ _ _ 10 DR CR _ - \\ get_account_balances_result T2 0 10 0 11 - \\ get_account_balances_result T4 0 22 0 24 - \\ commit get_account_balances - \\ - // Debits + credits + user_data_64, chronological. - \\ get_account_balances A1 _ U10 _ _ _ _ 10 DR CR _ - \\ get_account_balances_result T1 0 10 0 0 - \\ get_account_balances_result T2 0 10 0 11 - \\ commit get_account_balances - \\ - // Debits + credits + user_data_32, chronological. - \\ get_account_balances A1 _ _ U1 _ _ _ 10 DR CR _ - \\ get_account_balances_result T1 0 10 0 0 - \\ get_account_balances_result T4 0 22 0 24 - \\ commit get_account_balances - \\ - // Debits + credits + code, chronological. - \\ get_account_balances A1 _ _ _ C1 _ _ 10 DR CR _ - \\ get_account_balances_result T1 0 10 0 0 - \\ get_account_balances_result T3 0 22 0 11 - \\ commit get_account_balances - \\ - // Debits + credits + all filters, 0 < timestamp_min ≤ timestamp_max, chronological. - \\ get_account_balances A1 U1000 U10 U1 C1 T1 T3 10 DR CR _ - \\ get_account_balances_result T1 0 10 0 0 - \\ commit get_account_balances - \\ - // Debits only + all filters, 0 < timestamp_min ≤ timestamp_max, chronological. - \\ get_account_balances A1 U1000 U10 U1 C1 T1 T3 10 DR _ _ - \\ get_account_balances_result T1 0 10 0 0 - \\ commit get_account_balances - \\ - // Credits only + all filters, 0 < timestamp_min ≤ timestamp_max, chronological. - \\ get_account_balances A2 U1000 U10 U1 C1 T1 T3 10 _ CR _ - \\ get_account_balances_result T1 0 0 0 10 - \\ commit get_account_balances - \\ - // Not found. - \\ get_account_balances A1 U1000 U20 U2 C2 _ _ 10 DR CR _ - \\ commit get_account_balances - ); -} - -test "get_account_balances: two-phase" { - try check( - \\ account A1 0 0 0 0 _ _ _ _ L1 C1 _ _ _ HIST _ _ _ _ created - \\ account A2 0 0 0 0 _ _ _ _ L1 C1 _ _ _ HIST _ _ _ _ created - \\ commit create_accounts - \\ - \\ transfer T1 A1 A2 1 _ _ _ _ 0 L1 C1 _ PEN _ _ _ _ _ _ _ _ _ created - \\ transfer T2 A1 A2 1 T1 _ _ _ 0 L1 C1 _ _ POS _ _ _ _ _ _ _ _ created - \\ commit create_transfers - \\ - \\ get_account_balances A1 _ _ _ _ _ _ 10 DR CR _ - \\ get_account_balances_result T1 1 0 0 0 - \\ get_account_balances_result T2 0 1 0 0 - \\ commit get_account_balances - ); -} - -test "get_account_balances: invalid filter" { - try check( - \\ account A1 0 0 0 0 _ _ _ _ L1 C1 _ _ _ HIST _ _ _ _ created - \\ account A2 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ commit create_accounts - \\ - \\ transfer T1 A1 A2 2 _ _ _ _ 0 L1 C1 _ _ _ _ _ _ _ _ _ _ _ created - \\ transfer T2 A1 A2 1 _ _ _ _ 0 L1 C1 _ _ _ _ _ _ _ _ _ _ _ created - \\ commit create_transfers - \\ - // Invalid account. - \\ get_account_balances A3 _ _ _ _ _ _ 10 DR CR _ - \\ commit get_account_balances // Empty result. - \\ - // Account without flags.history. - \\ get_account_balances A2 _ _ _ _ _ _ 10 DR CR _ - \\ commit get_account_balances // Empty result. - \\ - // Invalid filter flags. - \\ get_account_balances A1 _ _ _ _ _ _ 10 _ _ _ - \\ commit get_account_balances // Empty result. - \\ - // Invalid timestamp_min > timestamp_max. - \\ get_account_balances A1 _ _ _ _ T2 T1 10 DR CR _ - \\ commit get_account_balances // Empty result. - \\ - // Invalid limit. - \\ get_account_balances A1 _ _ _ _ _ _ 0 DR CR _ - \\ commit get_account_balances // Empty result. - \\ - // Success. - \\ get_account_balances A1 _ _ _ C1 _ _ 10 DR CR _ - \\ get_account_balances_result T1 0 2 0 0 - \\ get_account_balances_result T2 0 3 0 0 - \\ commit get_account_balances - ); -} - -test "query_accounts" { - try check( - \\ account A1 0 0 0 0 U1000 U10 U1 _ L1 C1 _ _ _ _ _ _ _ _ created - \\ account A2 0 0 0 0 U1000 U11 U2 _ L2 C2 _ _ _ _ _ _ _ _ created - \\ account A3 0 0 0 0 U1000 U10 U3 _ L3 C3 _ _ _ _ _ _ _ _ created - \\ account A4 0 0 0 0 U1000 U11 U4 _ L4 C4 _ _ _ _ _ _ _ _ created - \\ account A5 0 0 0 0 U2000 U10 U1 _ L3 C5 _ _ _ _ _ _ _ _ created - \\ account A6 0 0 0 0 U2000 U11 U2 _ L2 C6 _ _ _ _ _ _ _ _ created - \\ account A7 0 0 0 0 U2000 U10 U3 _ L1 C7 _ _ _ _ _ _ _ _ created - \\ account A8 0 0 0 0 U1000 U10 U1 _ L1 C1 _ _ _ _ _ _ _ _ created - \\ commit create_accounts - - // WHERE user_data_128=1000: - \\ query_accounts U1000 U0 U0 L0 C0 _ _ L-0 _ - \\ query_accounts_result A1 _ - \\ query_accounts_result A2 _ - \\ query_accounts_result A3 _ - \\ query_accounts_result A4 _ - \\ query_accounts_result A8 _ - \\ commit query_accounts - - // WHERE user_data_128=1000 ORDER BY DESC: - \\ query_accounts U1000 U0 U0 L0 C0 _ _ L-0 REV - \\ query_accounts_result A8 _ - \\ query_accounts_result A4 _ - \\ query_accounts_result A3 _ - \\ query_accounts_result A2 _ - \\ query_accounts_result A1 _ - \\ commit query_accounts - - // WHERE user_data_64=10 AND user_data_32=3 - \\ query_accounts U0 U10 U3 L0 C0 _ _ L-0 _ - \\ query_accounts_result A3 _ - \\ query_accounts_result A7 _ - \\ commit query_accounts - - // WHERE user_data_64=10 AND user_data_32=3 ORDER BY DESC: - \\ query_accounts U0 U10 U3 L0 C0 _ _ L-0 REV - \\ query_accounts_result A7 _ - \\ query_accounts_result A3 _ - \\ commit query_accounts - - // WHERE user_data_64=11 AND user_data_32=2 AND code=2: - \\ query_accounts U0 U11 U2 L2 C0 _ _ L-0 _ - \\ query_accounts_result A2 _ - \\ query_accounts_result A6 _ - \\ commit query_accounts - - // WHERE user_data_64=11 AND user_data_32=2 AND code=2 ORDER BY DESC: - \\ query_accounts U0 U11 U2 L2 C0 _ _ L-0 REV - \\ query_accounts_result A6 _ - \\ query_accounts_result A2 _ - \\ commit query_accounts - - // WHERE user_data_128=1000 AND user_data_64=10 - // AND user_data_32=1 AND ledger=1 AND code=1: - \\ query_accounts U1000 U10 U1 L1 C1 _ _ L-0 _ - \\ query_accounts_result A1 _ - \\ query_accounts_result A8 _ - \\ commit query_accounts - - // WHERE user_data_128=1000 AND user_data_64=10 - // AND user_data_32=1 AND ledger=1 AND code=1 ORDER BY DESC: - \\ query_accounts U1000 U10 U1 L1 C1 _ _ L-0 REV - \\ query_accounts_result A8 _ - \\ query_accounts_result A1 _ - \\ commit query_accounts - - // WHERE user_data_128=1000 AND timestamp >= A3.timestamp: - \\ query_accounts U1000 U0 U0 L0 C0 A3 _ L-0 _ - \\ query_accounts_result A3 _ - \\ query_accounts_result A4 _ - \\ query_accounts_result A8 _ - \\ commit query_accounts - - // WHERE user_data_128=1000 AND timestamp <= A3.timestamp: - \\ query_accounts U1000 U0 U0 L0 C0 _ A3 L-0 _ - \\ query_accounts_result A1 _ - \\ query_accounts_result A2 _ - \\ query_accounts_result A3 _ - \\ commit query_accounts - - // WHERE user_data_128=1000 AND timestamp BETWEEN A2.timestamp AND A4.timestamp: - \\ query_accounts U1000 U0 U0 L0 C0 A2 A4 L-0 _ - \\ query_accounts_result A2 _ - \\ query_accounts_result A3 _ - \\ query_accounts_result A4 _ - \\ commit query_accounts - - // SELECT * : - \\ query_accounts U0 U0 U0 L0 C0 _ _ L-0 _ - \\ query_accounts_result A1 _ - \\ query_accounts_result A2 _ - \\ query_accounts_result A3 _ - \\ query_accounts_result A4 _ - \\ query_accounts_result A5 _ - \\ query_accounts_result A6 _ - \\ query_accounts_result A7 _ - \\ query_accounts_result A8 _ - \\ commit query_accounts - - // SELECT * ORDER BY DESC: - \\ query_accounts U0 U0 U0 L0 C0 _ _ L-0 REV - \\ query_accounts_result A8 _ - \\ query_accounts_result A7 _ - \\ query_accounts_result A6 _ - \\ query_accounts_result A5 _ - \\ query_accounts_result A4 _ - \\ query_accounts_result A3 _ - \\ query_accounts_result A2 _ - \\ query_accounts_result A1 _ - \\ commit query_accounts - - // SELECT * WHERE timestamp >= A2.timestamp LIMIT 3: - \\ query_accounts U0 U0 U0 L0 C0 A2 _ L3 _ - \\ query_accounts_result A2 _ - \\ query_accounts_result A3 _ - \\ query_accounts_result A4 _ - \\ commit query_accounts - - // SELECT * LIMIT 1: - \\ query_accounts U0 U0 U0 L0 C0 _ _ L1 _ - \\ query_accounts_result A1 _ - \\ commit query_accounts - - // SELECT * ORDER BY DESC LIMIT 1: - \\ query_accounts U0 U0 U0 L0 C0 _ _ L1 REV - \\ query_accounts_result A8 _ - \\ commit query_accounts - - // NOT FOUND: - - // SELECT * LIMIT 0: - \\ query_accounts U0 U0 U0 L0 C0 _ _ L0 _ - \\ commit query_accounts - - // WHERE user_data_128=3000 - \\ query_accounts U3000 U0 U0 L0 C0 _ _ L-0 _ - \\ commit query_accounts - - // WHERE user_data_128=1000 AND code=5 - \\ query_accounts U1000 U0 U0 L0 C5 _ _ L-0 _ - \\ commit query_accounts - - // WHERE user_data_128=1000 AND user_data_64=10 - // AND user_data_32=1 AND ledger=1 AND code=2: - \\ query_accounts U1000 U10 U1 L1 C2 _ _ L-0 _ - \\ commit query_accounts - - // WHERE user_data_128=1000 AND timestamp BETWEEN A5.timestamp AND A7.timestamp: - \\ query_accounts U1000 U0 U0 L0 C0 A5 A7 L-0 _ - \\ commit query_accounts - ); -} - -test "query_transfers" { - try check( - \\ account A1 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ account A2 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ account A3 0 0 0 0 _ _ _ _ L2 C1 _ _ _ _ _ _ _ _ created - \\ account A4 0 0 0 0 _ _ _ _ L2 C1 _ _ _ _ _ _ _ _ created - \\ commit create_accounts - - // Creating transfers: - \\ transfer T1 A1 A2 0 _ U1000 U10 U1 _ L1 C1 _ _ _ _ _ _ _ _ _ _ _ created - \\ transfer T2 A3 A4 11 _ U1000 U11 U2 _ L2 C2 _ _ _ _ _ _ _ _ _ _ _ created - \\ transfer T3 A2 A1 12 _ U1000 U10 U3 _ L1 C3 _ _ _ _ _ _ _ _ _ _ _ created - \\ transfer T4 A4 A3 13 _ U1000 U11 U4 _ L2 C4 _ _ _ _ _ _ _ _ _ _ _ created - \\ transfer T5 A2 A1 14 _ U2000 U10 U1 _ L1 C5 _ _ _ _ _ _ _ _ _ _ _ created - \\ transfer T6 A4 A3 15 _ U2000 U11 U2 _ L2 C6 _ _ _ _ _ _ _ _ _ _ _ created - \\ transfer T7 A1 A2 16 _ U2000 U10 U3 _ L1 C7 _ _ _ _ _ _ _ _ _ _ _ created - \\ transfer T8 A2 A1 17 _ U1000 U10 U1 _ L1 C1 _ _ _ _ _ _ _ _ _ _ _ created - \\ commit create_transfers - - // WHERE user_data_128=1000: - \\ query_transfers U1000 U0 U0 L0 C0 _ _ L-0 _ - \\ query_transfers_result T1 - \\ query_transfers_result T2 - \\ query_transfers_result T3 - \\ query_transfers_result T4 - \\ query_transfers_result T8 - \\ commit query_transfers - - // WHERE user_data_128=1000 ORDER BY DESC: - \\ query_transfers U1000 U0 U0 L0 C0 _ _ L-0 REV - \\ query_transfers_result T8 - \\ query_transfers_result T4 - \\ query_transfers_result T3 - \\ query_transfers_result T2 - \\ query_transfers_result T1 - \\ commit query_transfers - - // WHERE user_data_64=10 AND user_data_32=3 - \\ query_transfers U0 U10 U3 L0 C0 _ _ L-0 _ - \\ query_transfers_result T3 - \\ query_transfers_result T7 - \\ commit query_transfers - - // WHERE user_data_64=10 AND user_data_32=3 ORDER BY DESC: - \\ query_transfers U0 U10 U3 L0 C0 _ _ L-0 REV - \\ query_transfers_result T7 - \\ query_transfers_result T3 - \\ commit query_transfers - - // WHERE user_data_64=11 AND user_data_32=2 AND code=2: - \\ query_transfers U0 U11 U2 L2 C0 _ _ L-0 _ - \\ query_transfers_result T2 - \\ query_transfers_result T6 - \\ commit query_transfers - - // WHERE user_data_64=11 AND user_data_32=2 AND code=2 ORDER BY DESC: - \\ query_transfers U0 U11 U2 L2 C0 _ _ L-0 REV - \\ query_transfers_result T6 - \\ query_transfers_result T2 - \\ commit query_transfers - - // WHERE user_data_128=1000 AND user_data_64=10 - // AND user_data_32=1 AND ledger=1 AND code=1: - \\ query_transfers U1000 U10 U1 L1 C1 _ _ L-0 _ - \\ query_transfers_result T1 - \\ query_transfers_result T8 - \\ commit query_transfers - - // WHERE user_data_128=1000 AND user_data_64=10 - // AND user_data_32=1 AND ledger=1 AND code=1 ORDER BY DESC: - \\ query_transfers U1000 U10 U1 L1 C1 _ _ L-0 REV - \\ query_transfers_result T8 - \\ query_transfers_result T1 - \\ commit query_transfers - - // WHERE user_data_128=1000 AND timestamp >= T3.timestamp: - \\ query_transfers U1000 U0 U0 L0 C0 A3 _ L-0 _ - \\ query_transfers_result T3 - \\ query_transfers_result T4 - \\ query_transfers_result T8 - \\ commit query_transfers - - // WHERE user_data_128=1000 AND timestamp <= T3.timestamp: - \\ query_transfers U1000 U0 U0 L0 C0 _ A3 L-0 _ - \\ query_transfers_result T1 - \\ query_transfers_result T2 - \\ query_transfers_result T3 - \\ commit query_transfers - - // WHERE user_data_128=1000 AND timestamp BETWEEN T2.timestamp AND T4.timestamp: - \\ query_transfers U1000 U0 U0 L0 C0 A2 A4 L-0 _ - \\ query_transfers_result T2 - \\ query_transfers_result T3 - \\ query_transfers_result T4 - \\ commit query_transfers - - // SELECT * : - \\ query_transfers U0 U0 U0 L0 C0 _ _ L-0 _ - \\ query_transfers_result T1 - \\ query_transfers_result T2 - \\ query_transfers_result T3 - \\ query_transfers_result T4 - \\ query_transfers_result T5 - \\ query_transfers_result T6 - \\ query_transfers_result T7 - \\ query_transfers_result T8 - \\ commit query_transfers - - // SELECT * ORDER BY DESC: - \\ query_transfers U0 U0 U0 L0 C0 _ _ L-0 REV - \\ query_transfers_result T8 - \\ query_transfers_result T7 - \\ query_transfers_result T6 - \\ query_transfers_result T5 - \\ query_transfers_result T4 - \\ query_transfers_result T3 - \\ query_transfers_result T2 - \\ query_transfers_result T1 - \\ commit query_transfers - - // SELECT * WHERE timestamp >= A2.timestamp LIMIT 3: - \\ query_transfers U0 U0 U0 L0 C0 A2 _ L3 _ - \\ query_transfers_result T2 - \\ query_transfers_result T3 - \\ query_transfers_result T4 - \\ commit query_transfers - - // SELECT * LIMIT 1: - \\ query_transfers U0 U0 U0 L0 C0 _ _ L1 _ - \\ query_transfers_result T1 - \\ commit query_transfers - - // SELECT * ORDER BY DESC LIMIT 1: - \\ query_transfers U0 U0 U0 L0 C0 _ _ L1 REV - \\ query_transfers_result T8 - \\ commit query_transfers - - // NOT FOUND: - - // SELECT * LIMIT 0: - \\ query_transfers U0 U0 U0 L0 C0 _ _ L0 _ - \\ commit query_transfers - - // WHERE user_data_128=3000 - \\ query_transfers U3000 U0 U0 L0 C0 _ _ L-0 _ - \\ commit query_transfers - - // WHERE user_data_128=1000 AND code=5 - \\ query_transfers U1000 U0 U0 L0 C5 _ _ L-0 _ - \\ commit query_transfers - - // WHERE user_data_128=1000 AND user_data_64=10 - // AND user_data_32=1 AND ledger=1 AND code=2: - \\ query_transfers U1000 U10 U1 L1 C2 _ _ L-0 _ - \\ commit query_transfers - - // WHERE user_data_128=1000 AND timestamp BETWEEN T5.timestamp AND T7.timestamp: - \\ query_transfers U1000 U0 U0 L0 C0 A5 A7 L-0 _ - \\ commit query_transfers - ); -} - -test "get_change_events" { - try check( - \\ account A1 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ account A2 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ account A3 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ account A4 0 0 0 0 _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ created - \\ commit create_accounts - - // First phase. - \\ transfer T1 A1 A2 10 _ _ _ _ _ L1 C1 _ _ _ _ _ _ _ _ _ _ _ created // Not pending. - \\ transfer T2 A1 A2 11 _ _ _ _ 0 L1 C1 _ PEN _ _ _ _ _ _ _ _ _ created // Timeout zero will never expire. - \\ transfer T3 A1 A2 12 _ _ _ _ 1 L1 C1 _ PEN _ _ _ _ _ _ _ _ _ created // Will expire. - \\ transfer T4 A1 A2 13 _ _ _ _ 2 L1 C1 _ PEN _ _ _ _ _ _ _ _ _ created // Will be posted. - \\ transfer T5 A1 A2 14 _ _ _ _ 2 L1 C1 _ PEN _ _ _ _ _ _ _ _ _ created // Will be voided. - // Closes the debit and credit accounts. - \\ transfer T6 A3 A1 0 _ _ _ _ 0 L1 C1 _ PEN _ _ _ _ _ CDR _ _ _ created - \\ transfer T7 A1 A4 0 _ _ _ _ 0 L1 C1 _ PEN _ _ _ _ _ _ CCR _ _ created - \\ commit create_transfers - - // Bump the state machine time in +1s for testing the timeout expiration. - \\ tick 1 seconds - - // Second phase. - \\ transfer T14 A0 A0 -0 T4 _ _ _ _ L0 C0 _ _ POS _ _ _ _ _ _ _ _ created // Posts T4. - \\ transfer T15 A0 A0 0 T5 _ _ _ _ L0 C0 _ _ _ VOI _ _ _ _ _ _ _ created // Voids T5. - // Reopens the debit and credit accounts. - \\ transfer T16 A0 A0 0 T6 _ _ _ _ L0 C0 _ _ _ VOI _ _ _ _ _ _ _ created - \\ transfer T17 A0 A0 0 T7 _ _ _ _ L0 C0 _ _ _ VOI _ _ _ _ _ _ _ created - \\ commit create_transfers - - // Check the events. - \\ get_change_events _ T6 5 - \\ get_change_events_result _ T1 10 _ D1 0 10 0 0 _ C2 0 0 0 10 _ - \\ get_change_events_result PEN T2 11 _ D1 11 10 0 0 _ C2 0 0 11 10 _ - \\ get_change_events_result PEN T3 12 _ D1 23 10 0 0 _ C2 0 0 23 10 _ - \\ get_change_events_result PEN T4 13 _ D1 36 10 0 0 _ C2 0 0 36 10 _ - \\ get_change_events_result PEN T5 14 _ D1 50 10 0 0 _ C2 0 0 50 10 _ - \\ commit get_change_events - \\ - \\ get_change_events T6 _ -0 - \\ get_change_events_result PEN T6 0 _ D3 0 0 0 0 CLSD A1 50 10 0 0 _ - \\ get_change_events_result PEN T7 0 _ D1 50 10 0 0 _ C4 0 0 0 0 CLSD - \\ get_change_events_result EXP _ 12 T3 D1 38 10 0 0 _ C2 0 0 38 10 _ - \\ get_change_events_result POS T14 13 T4 D1 25 23 0 0 _ C2 0 0 25 23 _ - \\ get_change_events_result VOI T15 14 T5 D1 11 23 0 0 _ C2 0 0 11 23 _ - \\ get_change_events_result VOI T16 0 T6 D3 0 0 0 0 _ C1 11 23 0 0 _ - \\ get_change_events_result VOI T17 0 T7 D1 11 23 0 0 _ C4 0 0 0 0 _ - \\ commit get_change_events - ); -} - -// Sanity test to check the maximum batch size. -// For a comprehensive test of all operations, see the `input_valid` test. -test "StateMachine: batch_elements_max" { - const Operation = vsr.tigerbeetle.Operation; - - const events_max: u32 = @divExact( - constants.message_body_size_max, - @max(@sizeOf(Account), @sizeOf(Transfer)), - ); - - // No multi-batch encode. - try testing.expectEqual(events_max, Operation.deprecated_create_accounts_unbatched.event_max( - constants.message_body_size_max, - )); - try testing.expectEqual(events_max, Operation.deprecated_lookup_accounts_unbatched.event_max( - constants.message_body_size_max, - )); - try testing.expectEqual(events_max, Operation.deprecated_create_transfers_unbatched.event_max( - constants.message_body_size_max, - )); - try testing.expectEqual(events_max, Operation.deprecated_lookup_transfers_unbatched.event_max( - constants.message_body_size_max, - )); - - // Multi-batch encoded (the size corresponding to one element is occupied by the trailer). - try testing.expectEqual(events_max - 1, Operation.create_accounts.event_max( - constants.message_body_size_max, - )); - try testing.expectEqual(events_max - 1, Operation.create_transfers.event_max( - constants.message_body_size_max, - )); - try testing.expectEqual(events_max - 1, Operation.lookup_accounts.event_max( - constants.message_body_size_max, - )); - try testing.expectEqual(events_max - 1, Operation.lookup_transfers.event_max( - constants.message_body_size_max, - )); -} - -// Tests the input validation logic for both multi-batch encoded messages and -// the former single-batch format. -test "StateMachine: input_valid" { - const allocator = std.testing.allocator; - const input = try allocator.alignedAlloc( - u8, - constants.cache_line_size, - 2 * constants.message_body_size_max, - ); - defer allocator.free(input); - - const build_input = struct { - fn build_input(buffer: []align(constants.cache_line_size) u8, options: struct { - operation: TestContext.StateMachine.Operation, - event_count: u32, - }) []align(constants.cache_line_size) const u8 { - const event_size = options.operation.event_size(); - const payload_size: u32 = options.event_count * event_size; - if (options.operation.is_multi_batch()) { - var body_encoder = vsr.multi_batch.MultiBatchEncoder.init(buffer, .{ - .element_size = event_size, - }); - assert(payload_size <= body_encoder.writable().?.len); - body_encoder.add(payload_size); - const bytes_written = body_encoder.finish(); - assert(bytes_written > 0); - return buffer[0..bytes_written]; - } - - return buffer[0..payload_size]; - } - }.build_input; - - var context: TestContext = undefined; - try context.init(std.testing.allocator); - defer context.deinit(std.testing.allocator); - - const operations = std.enums.values(TestContext.StateMachine.Operation); - for (operations) |operation| { - if (operation == .pulse) continue; - const event_size = operation.event_size(); - maybe(event_size == 0); - - const event_min: u32, const event_max: u32 = limits: { - if (event_size == 0) { - break :limits .{ 0, 0 }; - } - if (!operation.is_batchable()) { - break :limits .{ 1, 1 }; - } - break :limits .{ - 0, - operation.event_max(context.state_machine.batch_size_limit), - }; - }; - assert(event_min <= event_max); - - try std.testing.expect(context.state_machine.input_valid( - operation, - build_input(input, .{ - .event_count = 0, - .operation = operation, - }), - ) == (event_min == 0)); - if (event_size == 0) { - assert(event_min == 0); - assert(event_max == 0); - continue; - } - - try std.testing.expect(context.state_machine.input_valid( - operation, - build_input(input, .{ - .event_count = 1, - .operation = operation, - }), - )); - try std.testing.expect(context.state_machine.input_valid( - operation, - build_input(input, .{ - .event_count = event_max, - .operation = operation, - }), - )); - const too_much_data = build_input(input, .{ - .event_count = event_max + 1, - .operation = operation, - }); - if (too_much_data.len < constants.message_body_size_max) { - try std.testing.expect(!context.state_machine.input_valid( - operation, - too_much_data, - )); - } else { - // Don't test input larger than the message body limit, since input_valid() - // would panic on an assert. - } - } -} - -// Tests multi-batched query filters. -// Multi-batch filters are valid as long as the sum of `filter.limit` stays within the maximum -// number of results that can fit in the reply message. -test "StateMachine: query multi-batch input_valid" { - const allocator = std.testing.allocator; - const input = try allocator.alignedAlloc( - u8, - constants.cache_line_size, - 2 * constants.message_body_size_max, - ); - defer allocator.free(input); - - var context: TestContext = undefined; - try context.init(std.testing.allocator); - defer context.deinit(std.testing.allocator); - - const build_input = struct { - fn build_input( - operation: TestContext.StateMachine.Operation, - limits: []const u32, - buffer: []align(constants.cache_line_size) u8, - ) []align(constants.cache_line_size) const u8 { - switch (operation) { - .get_account_transfers, - .get_account_balances, - => { - var body_encoder = vsr.multi_batch.MultiBatchEncoder.init(buffer, .{ - .element_size = @sizeOf(AccountFilter), - }); - if (limits.len == 0) body_encoder.add(0) else for (limits) |limit| { - const batch: []u8 = body_encoder.writable().?; - const filter: *AccountFilter = @alignCast(std.mem.bytesAsValue( - AccountFilter, - batch[0..@sizeOf(AccountFilter)], - )); - filter.* = .{ - .account_id = 0, - .user_data_128 = 0, - .user_data_64 = 0, - .user_data_32 = 0, - .code = 0, - .timestamp_min = 0, - .timestamp_max = 0, - .limit = limit, - .flags = .{ - .debits = false, - .credits = false, - .reversed = false, - }, - }; - body_encoder.add(@sizeOf(AccountFilter)); - } - return buffer[0..body_encoder.finish()]; - }, - .query_accounts, - .query_transfers, - => { - var body_encoder = vsr.multi_batch.MultiBatchEncoder.init(buffer, .{ - .element_size = @sizeOf(QueryFilter), - }); - if (limits.len == 0) body_encoder.add(0) else for (limits) |limit| { - const batch: []u8 = body_encoder.writable().?; - const filter: *QueryFilter = @alignCast(std.mem.bytesAsValue( - QueryFilter, - batch[0..@sizeOf(QueryFilter)], - )); - filter.* = .{ - .user_data_128 = 0, - .user_data_64 = 0, - .user_data_32 = 0, - .code = 0, - .ledger = 0, - .timestamp_min = 0, - .timestamp_max = 0, - .limit = limit, - .flags = .{ - .reversed = false, - }, - }; - body_encoder.add(@sizeOf(QueryFilter)); - } - return buffer[0..body_encoder.finish()]; - }, - else => unreachable, - } - } - }.build_input; - - const operations = &[_]TestContext.StateMachine.Operation{ - .get_account_transfers, - .get_account_balances, - .query_accounts, - .query_transfers, - }; - - for (operations) |operation| { - const batch_max = operation.result_max(context.state_machine.batch_size_limit); - - // Valid inputs: - try std.testing.expect(context.state_machine.input_valid( - operation, - build_input(operation, &.{0}, input), - )); - try std.testing.expect(context.state_machine.input_valid( - operation, - build_input(operation, &.{ 0, 0 }, input), - )); - try std.testing.expect(context.state_machine.input_valid( - operation, - build_input(operation, &.{1}, input), - )); - try std.testing.expect(context.state_machine.input_valid( - operation, - build_input(operation, &.{ 1, 1, 1 }, input), - )); - try std.testing.expect(context.state_machine.input_valid( - operation, - build_input(operation, &.{batch_max}, input), - )); - try std.testing.expect(context.state_machine.input_valid( - operation, - build_input(operation, &.{ 0, batch_max }, input), - )); - try std.testing.expect(context.state_machine.input_valid( - operation, - build_input(operation, &.{ 0, 1, batch_max - 1 }, input), - )); - try std.testing.expect(context.state_machine.input_valid( - operation, - build_input(operation, &.{ 1, 1, batch_max - 2 }, input), - )); - try std.testing.expect(context.state_machine.input_valid( - operation, - build_input(operation, &.{ - @divFloor(batch_max, 2), - stdx.div_ceil(batch_max, 2), - }, input), - )); - try std.testing.expect(context.state_machine.input_valid( - operation, - build_input(operation, &.{std.math.maxInt(u32)}, input), - )); - - // Invalid inputs: - try std.testing.expect(!context.state_machine.input_valid( - operation, - build_input(operation, &.{}, input), - )); - try std.testing.expect(!context.state_machine.input_valid( - operation, - build_input(operation, &.{ 1, batch_max }, input), - )); - try std.testing.expect(!context.state_machine.input_valid( - operation, - build_input(operation, &.{ 1, std.math.maxInt(u32) }, input), - )); - try std.testing.expect(!context.state_machine.input_valid( - operation, - build_input(operation, &.{ batch_max, batch_max }, input), - )); - try std.testing.expect(!context.state_machine.input_valid( - operation, - build_input(operation, &.{ - @divFloor(batch_max, 2), - stdx.div_ceil(batch_max, 2), - 1, - }, input), - )); - } -} diff --git a/ocam/src/tidy.zig b/ocam/src/tidy.zig index ef751282..d1340756 100644 --- a/ocam/src/tidy.zig +++ b/ocam/src/tidy.zig @@ -399,15 +399,6 @@ fn tidy_line(file: SourceFile, line: []const u8, line_index: usize, errors: *Err const string_value_length = tidy_line_length(string_value); if (string_value_length <= 100) return; - if (std.mem.endsWith(u8, file.path, "state_machine_tests.zig") and - (std.mem.startsWith(u8, string_value, " account A") or - std.mem.startsWith(u8, string_value, " transfer T") or - std.mem.startsWith(u8, string_value, " transfer "))) - { - // Table tests from state_machine.zig. They are intentionally wide. - return; - } - // vsr.zig's Checkpoint ops diagram. if (std.mem.endsWith(u8, file.path, "vsr.zig") and std.mem.startsWith(u8, string_value, "OPS: ")) return; diff --git a/ocam/src/unit_tests.zig b/ocam/src/unit_tests.zig index 2fbfd328..9cc32ea6 100644 --- a/ocam/src/unit_tests.zig +++ b/ocam/src/unit_tests.zig @@ -39,9 +39,6 @@ comptime { _ = @import("scripts/cfo.zig"); _ = @import("scripts/changelog.zig"); _ = @import("stack.zig"); - _ = @import("state_machine.zig"); - _ = @import("state_machine_fuzz.zig"); - _ = @import("state_machine_tests.zig"); _ = @import("testing/exhaustigen.zig"); _ = @import("testing/id.zig"); _ = @import("testing/marks.zig");