Repository navigation
Expand file tree
/
Copy pathdeterministic.zig
More file actions
2356 lines (2189 loc) · 95.4 KB
/
Copy pathdeterministic.zig
File metadata and controls
2356 lines (2189 loc) · 95.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A deterministic runtime that randomly selects tasks to run based on a seed
//! (commonware `runtime/src/deterministic.rs`).
//!
//! Tasks are stackful fibers on one OS thread. Each iteration of the event loop drains the
//! ready tasks, shuffles them with the seeded RNG (rand 0.10's shuffle over commonware's
//! `StdRng`), and runs each until it blocks. Then simulated time advances by one `cycle`; when
//! nothing is ready it jumps straight to the next timer. A run with the same seed and the same
//! code replays exactly, and the `Auditor` hashes every scheduling decision so two runs can be
//! compared.
//!
//! The executor implements `std.Io` (`Runner.io`): async/concurrent tasks, groups, futexes,
//! sleep, clocks, and randomness, with file and network operations failing. Every `std.Io`
//! primitive built on those (Mutex, Condition, Event, Queue, Select) is therefore
//! deterministic too, and library code written against `std.Io` runs unmodified.
//!
//! Differences from commonware, by necessity:
//! - Zig has no unwinding, so a task cannot be dropped mid-await. Aborting a task is a
//! `std.Io` cancelation request: its next cancelation point returns `error.Canceled`. When
//! the root task finishes, every other task is canceled and drained the same way; tasks
//! still blocked after that (uncancelable waits) are discarded without running their defers.
//! - Panics abort the process (no `catch_panics`); a stall or timeout is returned as
//! `error.Stalled` / `error.Timeout` from `Runner.start` instead of a panic.
//! - The auditor hashes the same kinds of events with the same hasher, but fibers block at
//! different points than polled futures, so its digests are not comparable with Rust's.
const std = @import("std");
const build_options = @import("build_options");
const assert = std.debug.assert;
const Io = std.Io;
const utils = @import("utils");
const cryptography = @import("cryptography");
const fiber = @import("fiber.zig");
const storage_mod = @import("storage.zig");
const network_mod = @import("network.zig");
const context_mod = @import("context.zig");
const telemetry = @import("telemetry/mod.zig");
const resolver_mod = @import("resolver.zig");
const rng_helpers = @import("rng.zig");
const Rng = utils.rng.TestRng;
/// Configuration for the deterministic runtime.
pub const Config = struct {
/// Seed of the runtime RNG (commonware's default is 42).
seed: u64 = 42,
/// Simulated time added after every iteration of the event loop.
cycle_ns: u64 = std.time.ns_per_ms,
/// Simulated time the runtime starts at, in nanoseconds since the Unix epoch.
start_time_ns: u64 = 0,
/// If the runtime is still executing this long after `start_time_ns`, `start` returns
/// `error.Timeout`.
timeout_ns: ?u64 = null,
/// Upper bound on live tasks, including the root.
max_tasks: u32 = 4096,
/// Bytes of stack mapped for each task (only touched pages are backed by memory).
stack_size_bytes: usize = 8 * 1024 * 1024,
/// Capacity of the supervision tree: contexts alive at once.
max_contexts: u32 = context_mod.default_max_contexts,
/// Storage fault injection (commonware `with_storage_fault_config`); none by default.
storage_faults: storage_mod.faulty.Config = .{},
/// Receives the events of `Context.tracer` (tracing's installed subscriber); none drops
/// them unformatted.
subscriber: ?telemetry.traces.Subscriber = null,
/// commonware's `external` feature, for tests of code that waits on processes outside the
/// runtime: a real `Io` (such as `std.Io.Threaded`'s). Each iteration then really sleeps
/// `cycle_ns` on it, idle time is never skipped, the runner never stalls, and a task whose
/// futex word another thread changed (an `Io.Event` set by an external thread) wakes on
/// the next iteration. `pace` needs it. Runs are no longer reproducible from the seed
/// alone. Never set it for code that can mock its external processes.
external: ?Io = null,
pub fn validate(config: Config) void {
assert(config.cycle_ns > 0 or config.timeout_ns == null);
assert(config.max_tasks >= 1);
assert(config.stack_size_bytes >= 64 * 1024);
if (config.timeout_ns) |timeout_ns| {
assert(config.start_time_ns +| timeout_ns > config.start_time_ns);
}
}
};
pub const Error = error{
/// No task can make progress and no timer is pending.
Stalled,
/// Simulated time reached `start_time_ns + timeout_ns`.
Timeout,
OutOfMemory,
};
/// Hashes an unambiguous sequence of length-prefixed fields (commonware `AuditHasher`).
///
/// Short fields are staged in an aligned buffer and checksummed together: CRC-32C costs one
/// serially dependent instruction per unaligned byte, so checksumming each small field where
/// it lies took most of a scheduler cycle. The checksum streams, so the digest is the same.
pub const AuditHasher = struct {
crc: cryptography.Crc32 = cryptography.Crc32.init(),
staged: [staged_size]u8 align(8) = undefined,
staged_len: u32 = 0,
const staged_size = 128;
pub fn update(hasher: *AuditHasher, value: []const u8) void {
var length: [8]u8 = undefined;
std.mem.writeInt(u64, &length, value.len, .big);
hasher.absorb(&length);
hasher.absorb(value);
}
fn absorb(hasher: *AuditHasher, bytes: []const u8) void {
assert(hasher.staged_len <= staged_size);
if (hasher.staged_len + bytes.len > staged_size) {
hasher.flush();
if (bytes.len >= staged_size) return hasher.crc.update(bytes);
}
assert(hasher.staged_len + bytes.len <= staged_size);
@memcpy(hasher.staged[hasher.staged_len..][0..bytes.len], bytes);
hasher.staged_len += @intCast(bytes.len);
}
fn flush(hasher: *AuditHasher) void {
hasher.crc.update(hasher.staged[0..hasher.staged_len]);
hasher.staged_len = 0;
}
pub fn update_int(hasher: *AuditHasher, comptime T: type, value: T) void {
var bytes: [@sizeOf(T)]u8 = undefined;
std.mem.writeInt(T, &bytes, value, .big);
hasher.update(&bytes);
}
/// Adds `chunks` as one length-prefixed field: their boundaries are not hashed
/// (commonware `AuditHasher::update_bufs`).
pub fn update_chunks(hasher: *AuditHasher, chunks: []const []const u8) void {
var total: u64 = 0;
for (chunks) |chunk| total += chunk.len;
var length: [8]u8 = undefined;
std.mem.writeInt(u64, &length, total, .big);
hasher.absorb(&length);
for (chunks) |chunk| hasher.absorb(chunk);
}
pub fn finalize(hasher: *AuditHasher) [4]u8 {
hasher.flush();
assert(hasher.staged_len == 0);
return hasher.crc.finalize().bytes;
}
};
/// The `process_task` audit event without hashing it per resume. The event hashes
/// `len(4) digest len(12) "process_task" len(16) id len(L) label`, and only the previous
/// digest varies. CRC-32C is affine, so the checksum is the task's `base` (the event with a
/// zero digest) XOR a linear function of the digest's 4 bytes followed by the `52 + L` fixed
/// bytes, which four 256-entry tables per label length `L` give.
pub const ProcessAudit = struct {
tables: [4][256]u32,
const label = "process_task";
/// Bytes after the digest, less the label's: three length prefixes, `label`, the id.
const suffix_fixed = 8 + label.len + 8 + 16 + 8;
/// The event's checksum for task `id` named `name`, with a zero previous digest.
pub fn base(id: u128, name: []const u8) u32 {
var hasher: AuditHasher = .{};
hasher.update(&@as([4]u8, @splat(0)));
hasher.update(label);
var id_bytes: [16]u8 = undefined;
std.mem.writeInt(u128, &id_bytes, id, .big);
hasher.update(&id_bytes);
hasher.update(name);
return std.mem.readInt(u32, &hasher.finalize(), .big);
}
/// Tables for labels of `label_len` bytes: entry `[i][b]` is the zero-state CRC register
/// after digest byte `i` = `b`, the other digest bytes zero, and the suffix zero.
pub fn init(audit: *ProcessAudit, label_len: usize) void {
const zeros = suffix_fixed + label_len;
// The contributions of single bits, then each byte value as an XOR of its bits.
var bits: [4][8]u32 = undefined;
for (0..4) |position| {
for (0..8) |bit| {
bits[position][bit] = shifted(position, @as(u8, 1) << @intCast(bit), zeros);
}
}
for (0..4) |position| {
for (0..256) |value| {
var sum: u32 = 0;
for (0..8) |bit| {
if (value >> @intCast(bit) & 1 != 0) sum ^= bits[position][bit];
}
audit.tables[position][value] = sum;
}
}
assert(audit.tables[0][0] == 0);
}
/// The zero-state register over 4 digest bytes (only `position` set to `value`) and
/// `zeros` zero bytes, bit by bit (CRC-32C, reflected, no final xor).
fn shifted(position: usize, value: u8, zeros: usize) u32 {
var crc: u32 = 0;
for (0..4 + zeros) |index| {
crc ^= if (index == position) value else 0;
for (0..8) |_| crc = (crc >> 1) ^ (0x82f63b78 & (0 -% (crc & 1)));
}
return crc;
}
/// The next digest after a `process_task` event of the task with `base_value`.
pub fn event(audit: *const ProcessAudit, base_value: u32, previous: [4]u8) [4]u8 {
var value = base_value;
for (previous, 0..) |byte, position| value ^= audit.tables[position][byte];
var digest: [4]u8 = undefined;
std.mem.writeInt(u32, &digest, value, .big);
return digest;
}
};
/// Tracks the state of the runtime for determinism auditing (commonware `Auditor`).
pub const Auditor = struct {
digest: [4]u8 = @splat(0),
/// Record an event: the new digest hashes the old digest, `label`, and `fields`.
pub fn event(auditor: *Auditor, label: []const u8, fields: []const []const u8) void {
var hasher: AuditHasher = .{};
hasher.update(&auditor.digest);
hasher.update(label);
for (fields) |field| hasher.update(field);
auditor.digest = hasher.finalize();
}
/// Like `event`, with `chunks` hashed as one field between `before` and `after`.
pub fn event_chunked(
auditor: *Auditor,
label: []const u8,
before: []const []const u8,
chunks: []const []const u8,
after: []const []const u8,
) void {
var hasher: AuditHasher = .{};
hasher.update(&auditor.digest);
hasher.update(label);
for (before) |field| hasher.update(field);
hasher.update_chunks(chunks);
for (after) |field| hasher.update(field);
auditor.digest = hasher.finalize();
}
/// Hex encoding of the current digest (commonware `Auditor::state`).
pub fn state(auditor: *const Auditor) [8]u8 {
return std.fmt.bytesToHex(auditor.digest, .lower);
}
};
const max_closure_bytes = 1024;
const max_result_bytes = 1024;
const max_alignment: std.mem.Alignment = .@"16";
const TaskLabel = telemetry.metrics.task.Label;
const PollCounter = telemetry.metrics.raw.Counter;
const PollFamily = telemetry.metrics.raw.Family(TaskLabel, PollCounter);
const label_size_max = telemetry.metrics.scope.prefix_size_max;
const Task = struct {
id: u64,
/// The task's name (commonware `Label::name`): the spawning `Context`'s label, the
/// spawning task's name for a plain `io.concurrent` fiber, empty for the root. Copied, so
/// it outlives whatever named it.
label_buffer: [label_size_max]u8,
label_len: u8,
label_kind: telemetry.metrics.task.Kind,
/// This task's `runtime_task_polls` entry.
polls: *PollCounter,
/// The `process_task` audit event's checksum with a zero previous digest (`ProcessAudit`).
audit_base: u32,
context: fiber.Context,
stack: ?fiber.Stack,
state: enum { ready, running, blocked, finished },
kind: union(enum) {
root,
future: struct { awaiter: ?*Task },
group: *Group,
},
start: union(enum) {
with_result: *const fn (context: *const anyopaque, result: *anyopaque) void,
without_result: *const fn (context: *const anyopaque) void,
},
closure: [max_closure_bytes]u8 align(max_alignment.toByteUnits()),
result: [max_result_bytes]u8 align(max_alignment.toByteUnits()),
/// A cancelation was requested; it fires at the next unblocked cancelation point.
cancel_requested: bool,
/// `error.Canceled` was returned and not re-armed with `recancel`.
cancel_acknowledged: bool,
cancel_protection: Io.CancelProtection,
/// Whether the current block may be interrupted by a cancelation request.
wait_cancelable: bool,
/// Bumped on every wake, so timers armed for an earlier wait are ignored.
wait_generation: u64,
/// Alarms in `Runner.alarms` that point at this task, stale ones included.
alarms_queued: u32,
wake_reason: enum { notified, timeout, canceled },
futex_address: usize,
/// The value `futex_address` held when the task waited (for `Config.external`).
futex_expected: u32,
futex_node: std.DoublyLinkedList.Node,
group_node: std.DoublyLinkedList.Node,
all_node: std.DoublyLinkedList.Node,
fn label(task: *const Task) []const u8 {
return task.label_buffer[0..task.label_len];
}
fn task_label(task: *const Task) TaskLabel {
return .{ .name = task.label(), .kind = task.label_kind, .execution = .shared };
}
/// With `-Dcancel-audit` (the default), panics when the task reaches a cancelation point
/// while holding a cancel it already acknowledged and never re-armed: it caught
/// `error.Canceled` without propagating it or calling `io.recancel()`, so this point cannot
/// deliver the cancel and a cancelable wait here is never woken by it. Deliberate work
/// after a cancel opts out by blocking cancelation (`io.swapCancelProtection(.blocked)`).
fn audit_cancel(task: *const Task) void {
if (!build_options.cancel_audit) return;
if (!task.cancel_requested or !task.cancel_acknowledged) return;
if (task.cancel_protection != .unblocked) return;
std.debug.panic(
"deterministic: task '{s}' caught error.Canceled without propagating it or " ++
"calling io.recancel(), then reached another cancelation point",
.{task.label()},
);
}
fn cancel_point_open(task: *const Task) bool {
return task.cancel_protection == .unblocked and !task.cancel_acknowledged;
}
};
const Group = struct {
members: std.DoublyLinkedList = .{},
count: u32 = 0,
awaiter: ?*Task = null,
/// Set once the group is canceled: members it starts later begin canceled, as in
/// `std.Io.Threaded`.
canceled: bool = false,
/// In `Runner.groups`, so groups never awaited are freed when `start` returns.
node: std.DoublyLinkedList.Node = .{},
};
const Alarm = struct {
deadline_ns: u64,
sequence: u64,
task: *Task,
generation: u64,
fn order(_: void, a: Alarm, b: Alarm) std.math.Order {
const by_time = std.math.order(a.deadline_ns, b.deadline_ns);
return if (by_time != .eq) by_time else std.math.order(a.sequence, b.sequence);
}
};
/// The deterministic runtime's context (see `context.zig`).
pub const Context = context_mod.Context(network_mod.deterministic.Network);
/// commonware's `Pacer::pace`: wait for `event`, which an external thread sets, as if it took
/// exactly `latency` of simulated time. Sleeps `latency`, then, if `event` is still unset,
/// blocks the runtime's thread until it is, so the result surfaces at the same simulated time
/// however long the external work really took. `io` is the task's deterministic `Io`, built
/// with `Config.external`.
pub fn pace(io: Io, latency: Io.Duration, event: *Io.Event) Io.Cancelable!void {
assert(io.vtable == &Runner.vtable);
const runner = Runner.from(io.userdata);
const real = runner.config.external.?; // `pace` needs `Config.external`.
const target_ns = runner.time_ns +| Runner.clamp_ns(latency.nanoseconds);
try io.sleep(latency, .awake);
assert(runner.time_ns >= target_ns);
event.waitUncancelable(real);
assert(event.isSet());
}
/// Implementation of the deterministic runtime. One `Runner` may `start` several root tasks in
/// sequence: simulated time, the RNG, and the auditor carry over, like recovering from
/// commonware's `Checkpoint`.
pub const Runner = struct {
allocator: std.mem.Allocator,
config: Config,
rng: Rng,
auditor: Auditor = .{},
/// `ProcessAudit` tables by task label length, built on first use.
process_audit: [label_size_max + 1]?*ProcessAudit = @splat(null),
time_ns: u64,
deadline_ns: ?u64,
iterations: u64 = 0,
next_task_id: u64 = 0,
next_alarm_sequence: u64 = 0,
scheduler_context: fiber.Context = .{},
current: ?*Task = null,
root_finished: bool = false,
tasks: std.DoublyLinkedList = .{},
task_count: u32 = 0,
ready: std.ArrayList(*Task),
batch: std.ArrayList(*Task),
alarms: std.PriorityQueue(Alarm, void, Alarm.order) = .empty,
futex_waiters: std.DoublyLinkedList = .{},
groups: std.DoublyLinkedList = .{},
stack_pool: std.ArrayList(fiber.Stack),
/// In-memory storage; durable contents carry over between starts.
memory_storage: storage_mod.memory.Storage,
/// Fault injection over `memory_storage`, drawing from the runtime RNG; created on first
/// use.
faulty_storage: ?storage_mod.faulty.Storage(Rng) = null,
/// Audits every storage operation, over `faulty_storage`; created on first use.
audited_storage: ?storage_mod.audited.Storage = null,
/// Counts storage operations in the `runtime` metrics, over `audited_storage`.
metered_storage: ?storage_mod.metered.Storage = null,
/// Counts `simulated_network`'s connections and bytes in the `runtime` metrics.
network_metrics: ?network_mod.metered.Metrics = null,
/// The simulated network, created on first use; it carries over between starts.
simulated_network: ?network_mod.deterministic.Network = null,
/// What every `Context` shares, created by the first `start_context`.
context_runtime: ?context_mod.Runtime = null,
/// The metrics registry; it carries over between starts. Release every handle before
/// `deinit`.
metrics_registry: telemetry.metrics.Registry,
/// `runtime_iterations` (commonware's executor metric): scheduler cycles run. Registered
/// by the first `start`, once the runner no longer moves (a handle points at its registry).
iterations_counter: ?telemetry.metrics.Registered(telemetry.metrics.raw.Counter) = null,
/// `runtime_task_polls`: fiber resumes per task label, registered with the counter above.
task_polls: ?telemetry.metrics.Registered(PollFamily) = null,
/// The name `Context.spawn` gave the fiber it is about to start (`label_next`).
next_label: ?[]const u8 = null,
/// DNS records (`Context.resolver_register`); they carry over between starts.
dns: resolver_mod.Dns,
pub fn init(allocator: std.mem.Allocator, config: Config) Error!Runner {
config.validate();
comptime assert(fiber.supported);
var ready: std.ArrayList(*Task) = try .initCapacity(allocator, config.max_tasks);
errdefer ready.deinit(allocator);
var batch: std.ArrayList(*Task) = try .initCapacity(allocator, config.max_tasks);
errdefer batch.deinit(allocator);
const stack_pool: std.ArrayList(fiber.Stack) = try .initCapacity(allocator, 16);
const deadline_ns = if (config.timeout_ns) |t| config.start_time_ns + t else null;
return .{
.allocator = allocator,
.config = config,
.rng = Rng.init(config.seed),
.time_ns = config.start_time_ns,
.deadline_ns = deadline_ns,
.ready = ready,
.batch = batch,
.stack_pool = stack_pool,
.memory_storage = .init(allocator),
.metrics_registry = .init(allocator),
.dns = .init(allocator),
};
}
pub fn deinit(runner: *Runner) void {
assert(runner.current == null);
assert(runner.task_count == 0);
for (runner.stack_pool.items) |stack| stack.unmap();
runner.stack_pool.deinit(runner.allocator);
for (runner.process_audit) |tables| if (tables) |t| runner.allocator.destroy(t);
runner.ready.deinit(runner.allocator);
runner.batch.deinit(runner.allocator);
runner.alarms.deinit(runner.allocator);
if (runner.metered_storage) |*metered| metered.deinit();
if (runner.audited_storage) |*audited| audited.deinit();
if (runner.faulty_storage) |*faults| faults.deinit();
runner.memory_storage.deinit();
if (runner.context_runtime) |*runtime| runtime.deinit();
if (runner.simulated_network) |*net| net.deinit();
if (runner.network_metrics) |*counts| counts.deinit();
if (runner.iterations_counter) |*counter| counter.deinit();
if (runner.task_polls) |*polls| polls.deinit();
runner.dns.deinit();
runner.metrics_registry.deinit();
runner.* = undefined;
}
/// The `std.Io` backed by this runtime: simulated clock, seeded randomness, and tasks.
pub fn io(runner: *Runner) Io {
return .{ .userdata = runner, .vtable = &vtable };
}
/// The runtime's in-memory storage, with `Config.storage_faults` injected, every operation
/// audited, and counted in the `runtime_storage_*` and `runtime_open_blobs` metrics
/// (commonware's `Metered(Audited(Faulty(Memory)))`). The runner must not move once it is
/// used. Panics if registering the metrics runs out of memory.
pub fn storage(runner: *Runner) storage_mod.Storage {
if (runner.metered_storage == null) {
assert(runner.audited_storage == null);
runner.memory_storage.io = runner.io();
const inner = runner.storage_faulty().storage();
runner.audited_storage = .init(runner.allocator, inner, &runner.auditor);
const audited = runner.audited_storage.?.storage();
const scope = runner.metrics().sub_registry(telemetry.metrics.metrics_prefix);
runner.metered_storage = storage_mod.metered.Storage.init(
runner.allocator,
audited,
&scope,
) catch @panic("deterministic: registering storage metrics: out of memory");
}
return runner.metered_storage.?.storage();
}
/// The live fault configuration (commonware `storage_fault_config`): changes take effect
/// at the next storage operation and carry over between starts.
pub fn storage_fault_config(runner: *Runner) *storage_mod.faulty.Config {
return &runner.storage_faulty().config;
}
fn storage_faulty(runner: *Runner) *storage_mod.faulty.Storage(Rng) {
if (runner.faulty_storage == null) {
const faults = runner.config.storage_faults;
const memory = &runner.memory_storage;
runner.faulty_storage = .init(runner.allocator, memory, &runner.rng, faults);
}
assert(runner.faulty_storage.?.inner == &runner.memory_storage);
return &runner.faulty_storage.?;
}
/// Crash storage as a run ends (commonware `Runner::run`): unsynced writes and resizes
/// survive as the fault configuration selected, only durable contents remain, and the
/// run's handles can no longer publish.
fn crash_storage(runner: *Runner) void {
if (runner.faulty_storage) |*faults| {
faults.crash() catch @panic("deterministic: replaying storage crash failed");
}
runner.memory_storage.crash();
}
/// The runtime's deterministic network, audited and counted in the `runtime_*_connections`
/// and `runtime_*_bandwidth` metrics (commonware's `Metered(Audited(Deterministic))`). The
/// runner must not move once it is used. Panics if registering the metrics runs out of
/// memory.
pub fn network(runner: *Runner) *network_mod.deterministic.Network {
if (runner.simulated_network == null) {
assert(runner.network_metrics == null);
const scope = runner.metrics().sub_registry(telemetry.metrics.metrics_prefix);
runner.network_metrics = network_mod.metered.Metrics.init(&scope) catch
@panic("deterministic: registering network metrics: out of memory");
runner.simulated_network = .init(runner.allocator, runner.io());
runner.simulated_network.?.auditor = &runner.auditor;
runner.simulated_network.?.metrics = &runner.network_metrics.?;
}
return &runner.simulated_network.?;
}
/// The root metrics scope (commonware's `Metrics` on the root context): empty label, no
/// attributes. The runner must not move once it is used.
pub fn metrics(runner: *Runner) telemetry.metrics.Scope {
return .init(&runner.metrics_registry);
}
/// CRC32C digest of all durable blob contents (commonware `storage_audit`).
pub fn storage_audit(runner: *Runner) [4]u8 {
return runner.memory_storage.audit();
}
/// Simulated time, in nanoseconds since the Unix epoch.
pub fn now_ns(runner: *const Runner) u64 {
return runner.time_ns;
}
/// Run `function(ctx, args...)` as the root task with a root `Context`: storage, the
/// network, metrics, and supervision (commonware `Runner::start`). Tasks it spawns are
/// aborted when it returns.
pub fn start_context(
runner: *Runner,
comptime function: anytype,
args: anytype,
) Error!context_mod.Return(function) {
const Result = context_mod.Return(function);
const Args = @TypeOf(args);
if (runner.context_runtime == null) {
const auditor = &runner.auditor;
const max = runner.config.max_contexts;
const scope = runner.metrics();
runner.context_runtime = try .init(runner.allocator, runner.io(), max, auditor, scope);
runner.context_runtime.?.label_hook = .{ .userdata = runner, .label_next = label_next };
runner.context_runtime.?.subscriber = runner.config.subscriber;
runner.context_runtime.?.strategy_inline = true;
}
const runtime = &runner.context_runtime.?;
// The runner may have moved since the last start: point at it again.
runner.dns.auditor = &runner.auditor;
runtime.dns = &runner.dns;
runtime.resolver = runner.dns.resolver();
const ctx: Context = .root(runtime, runner.storage(), runner.network(), runner.metrics());
const Root = struct {
fn call(root_ctx: *const Context, root_args: *const Args) Result {
return root_ctx.run_root(function, root_args.*);
}
};
return runner.start(Root.call, .{ &ctx, &args });
}
/// Run `function(args...)` as the root task until it returns, then cancel and drain every
/// task it left behind. Returns the root's result.
pub fn start(
runner: *Runner,
comptime function: anytype,
args: std.meta.ArgsTuple(@TypeOf(function)),
) Error!@typeInfo(@TypeOf(function)).@"fn".return_type.? {
const Result = @typeInfo(@TypeOf(function)).@"fn".return_type.?;
const Args = @TypeOf(args);
const Closure = struct {
fn call(context: *const anyopaque, result: *anyopaque) void {
const call_args: *const Args = @ptrCast(@alignCast(context));
const result_ptr: *Result = @ptrCast(@alignCast(result));
result_ptr.* = @call(.auto, function, call_args.*);
}
};
assert(runner.current == null);
assert(runner.task_count == 0);
if (runner.iterations_counter == null) {
const scope = runner.metrics().sub_registry("runtime");
const help = "Total number of iterations";
runner.iterations_counter = try scope.counter("iterations", help);
const polls_help = "Total number of task polls";
runner.task_polls = try scope.family(TaskLabel, PollCounter, "task_polls", polls_help);
}
const root = try runner.spawn_task(
std.mem.asBytes(&args),
.of(Args),
@sizeOf(Result),
.of(Result),
.{ .with_result = Closure.call },
.root,
);
runner.root_finished = false;
const outcome = runner.run_until_root();
runner.shutdown();
// A restart recovers like commonware's checkpoint: only what survived the crash.
runner.crash_storage();
outcome catch |err| {
runner.destroy_task(root);
return err;
};
const result_ptr: *const Result = @ptrCast(@alignCast(&root.result));
const result = result_ptr.*;
runner.destroy_task(root);
assert(runner.task_count == 0);
return result;
}
fn spawn_task(
runner: *Runner,
closure: []const u8,
closure_alignment: std.mem.Alignment,
result_len: usize,
result_alignment: std.mem.Alignment,
start_fn: @FieldType(Task, "start"),
kind: @FieldType(Task, "kind"),
) error{OutOfMemory}!*Task {
assert(closure.len <= max_closure_bytes);
assert(result_len <= max_result_bytes);
assert(closure_alignment.compare(.lte, max_alignment));
assert(result_alignment.compare(.lte, max_alignment));
if (runner.task_count >= runner.config.max_tasks) return error.OutOfMemory;
// A name set for this spawn applies to it alone, even if the spawn fails.
const named = runner.next_label;
runner.next_label = null;
var label_buffer: [label_size_max]u8 = undefined;
const task_label = runner.spawn_label(kind, named, &label_buffer);
const polls = try runner.task_polls.?.metric().get_or_create(task_label);
const label_len = task_label.name.len;
if (runner.process_audit[label_len] == null) {
const tables = try runner.allocator.create(ProcessAudit);
tables.init(label_len);
runner.process_audit[label_len] = tables;
}
const stack = try runner.acquire_stack();
errdefer runner.release_stack(stack);
const task = try runner.allocator.create(Task);
task.* = .{
.id = runner.next_task_id,
.label_buffer = label_buffer,
.label_len = @intCast(task_label.name.len),
.label_kind = task_label.kind,
.polls = polls,
.audit_base = ProcessAudit.base(runner.next_task_id, task_label.name),
.context = undefined,
.stack = stack,
.state = .ready,
.kind = kind,
.start = start_fn,
.closure = undefined,
.result = undefined,
.cancel_requested = false,
.cancel_acknowledged = false,
.cancel_protection = .unblocked,
.wait_cancelable = false,
.wait_generation = 0,
.alarms_queued = 0,
.wake_reason = .notified,
.futex_address = 0,
.futex_expected = 0,
.futex_node = .{},
.group_node = .{},
.all_node = .{},
};
@memcpy(task.closure[0..closure.len], closure);
task.context = fiber.prepare(stack, task_entry, task);
runner.next_task_id += 1;
runner.task_count += 1;
runner.tasks.append(&task.all_node);
runner.ready.appendAssumeCapacity(task);
return task;
}
fn destroy_task(runner: *Runner, task: *Task) void {
assert(task.state == .finished or runner.current == null);
assert(runner.task_count > 0);
if (task.stack) |stack| runner.release_stack(stack);
runner.drop_alarms(task);
runner.tasks.remove(&task.all_node);
runner.task_count -= 1;
runner.allocator.destroy(task);
}
/// Removes the stale alarms of a task being destroyed: a wait that ended before its
/// timeout leaves its alarm queued, and firing it later would read the freed task.
fn drop_alarms(runner: *Runner, task: *Task) void {
var index: usize = 0;
while (task.alarms_queued > 0 and index < runner.alarms.items.len) {
if (runner.alarms.items[index].task != task) {
index += 1;
continue;
}
assert(task.state == .finished or runner.current == null);
_ = runner.alarms.popIndex(index);
task.alarms_queued -= 1;
// Removal reorders the heap, so scan again from the start.
index = 0;
}
}
fn acquire_stack(runner: *Runner) error{OutOfMemory}!fiber.Stack {
if (runner.stack_pool.pop()) |stack| return stack;
return fiber.Stack.map(runner.config.stack_size_bytes);
}
fn release_stack(runner: *Runner, stack: fiber.Stack) void {
runner.stack_pool.append(runner.allocator, stack) catch stack.unmap();
}
fn task_entry(argument: *anyopaque) callconv(.c) noreturn {
const task: *Task = @ptrCast(@alignCast(argument));
assert(task.state == .running);
switch (task.start) {
.with_result => |start_fn| start_fn(&task.closure, &task.result),
.without_result => |start_fn| start_fn(&task.closure),
}
const runner = runner_of(task);
runner.finish(task);
fiber.switch_to(&task.context, &runner.scheduler_context);
unreachable; // A finished task is never resumed.
}
fn runner_of(task: *Task) *Runner {
_ = task;
return active_runner.?;
}
/// The runner whose event loop is on this thread's stack (fibers reach it here).
threadlocal var active_runner: ?*Runner = null;
fn finish(runner: *Runner, task: *Task) void {
assert(runner.current == task);
task.state = .finished;
switch (task.kind) {
.root => runner.root_finished = true,
.future => |future| if (future.awaiter) |awaiter| runner.wake(awaiter, .notified),
.group => |group| {
group.members.remove(&task.group_node);
group.count -= 1;
// An awaiter canceled in the same batch is ready already and reads the count
// when it runs.
if (group.count == 0) {
if (group.awaiter) |awaiter| {
if (awaiter.state == .blocked) runner.wake(awaiter, .notified);
}
}
},
}
}
/// Switch from the scheduler to `task` until it blocks or finishes.
fn resume_task(runner: *Runner, task: *Task) void {
assert(runner.current == null);
assert(task.state == .ready);
task.state = .running;
runner.current = task;
fiber.switch_to(&runner.scheduler_context, &task.context);
assert(runner.current == task);
runner.current = null;
assert(task.state != .running);
if (task.state != .finished) return;
// Off the task's stack now, so it can be reused.
if (task.stack) |stack| runner.release_stack(stack);
task.stack = null;
// Group members are owned by nobody once finished; futures wait for their awaiter
// and the root for `start`.
if (task.kind == .group) runner.destroy_task(task);
}
/// Block the current task until `wake`. Returns why it woke.
fn block(runner: *Runner, cancelable: bool) @FieldType(Task, "wake_reason") {
const task = runner.current.?;
assert(task.state == .running);
if (cancelable) task.audit_cancel();
task.state = .blocked;
task.wait_cancelable = cancelable;
fiber.switch_to(&task.context, &runner.scheduler_context);
assert(runner.current == task);
assert(task.state == .running);
return task.wake_reason;
}
fn wake(runner: *Runner, task: *Task, reason: @FieldType(Task, "wake_reason")) void {
assert(task.state == .blocked);
if (task.futex_address != 0) {
runner.futex_waiters.remove(&task.futex_node);
task.futex_address = 0;
}
task.state = .ready;
task.wake_reason = reason;
task.wait_generation += 1;
runner.ready.appendAssumeCapacity(task);
}
fn request_cancel(runner: *Runner, task: *Task) void {
task.cancel_requested = true;
if (task.state == .blocked and task.wait_cancelable and task.cancel_point_open()) {
runner.wake(task, .canceled);
}
}
/// A cancelation point for the current task.
fn check_cancel(runner: *Runner) Io.Cancelable!void {
const task = runner.current.?;
task.audit_cancel();
if (task.cancel_requested and task.cancel_point_open()) {
task.cancel_acknowledged = true;
return error.Canceled;
}
}
fn arm_alarm(runner: *Runner, task: *Task, deadline_ns: u64) void {
const alarm: Alarm = .{
.deadline_ns = deadline_ns,
.sequence = runner.next_alarm_sequence,
.task = task,
.generation = task.wait_generation,
};
runner.next_alarm_sequence += 1;
runner.alarms.push(runner.allocator, alarm) catch @panic("deterministic: out of memory");
task.alarms_queued += 1;
}
fn run_until_root(runner: *Runner) Error!void {
const previous = active_runner;
active_runner = runner;
defer active_runner = previous;
while (true) {
try runner.check_deadline();
runner.run_batch(true);
if (runner.root_finished) return;
// commonware's `external` feature sleeps each cycle so external processes progress.
if (runner.config.external) |real| {
real.sleep(.fromNanoseconds(runner.config.cycle_ns), .awake) catch {};
}
runner.time_ns = std.math.add(u64, runner.time_ns, runner.config.cycle_ns) catch
@panic("deterministic: executor time overflowed");
try runner.wake_until_progress();
runner.iterations += 1;
increment(runner.iterations_counter.?.metric());
}
}
/// Run every task that is ready now, in seeded random order.
fn run_batch(runner: *Runner, stop_at_root: bool) void {
assert(runner.batch.items.len == 0);
std.mem.swap(std.ArrayList(*Task), &runner.ready, &runner.batch);
defer runner.batch.clearRetainingCapacity();
if (runner.batch.items.len > 1) {
rng_helpers.shuffle(&runner.rng, *Task, runner.batch.items);
}
for (runner.batch.items) |task| {
assert(task.state == .ready);
runner.audit_process(task);
increment(task.polls);
runner.resume_task(task);
if (stop_at_root and runner.root_finished) {
// Tasks not reached this iteration stay ready for the drain.
const index = std.mem.indexOfScalar(*Task, runner.batch.items, task).?;
for (runner.batch.items[index + 1 ..]) |rest| {
runner.ready.appendAssumeCapacity(rest);
}
return;
}
}
}
/// Records `task`'s `process_task` audit event from its precomputed checksum.
fn audit_process(runner: *Runner, task: *const Task) void {
const tables = runner.process_audit[task.label_len].?;
const previous = runner.auditor.digest;
runner.auditor.digest = tables.event(task.audit_base, previous);
if (std.debug.runtime_safety) {
var expected: Auditor = .{ .digest = previous };
var id: [16]u8 = undefined;
std.mem.writeInt(u128, &id, task.id, .big);
expected.event("process_task", &.{ &id, task.label() });
assert(std.mem.eql(u8, &expected.digest, &runner.auditor.digest));
}
}
/// Bumps one of the runner's counters. Only the runner's thread writes them, so a plain
/// load and store replace the locked add (readers still see whole values).
fn increment(counter: *telemetry.metrics.raw.Counter) void {
const value = counter.value.load(.monotonic);
counter.value.store(value +% 1, .monotonic);
assert(counter.value.raw == value +% 1);
}
fn check_deadline(runner: *const Runner) Error!void {
if (runner.deadline_ns) |deadline_ns| {
if (runner.time_ns >= deadline_ns) return error.Timeout;
}
}
/// Fire timers until some task is ready, jumping over idle time. With `Config.external`,
/// fire due timers and wake the tasks external threads woke, then continue: the passage of
/// time is progress.
fn wake_until_progress(runner: *Runner) Error!void {
if (runner.config.external != null) {
try runner.check_deadline();
runner.fire_alarms();
runner.wake_external();
return;
}
while (true) {
if (runner.ready.items.len == 0) {
if (runner.alarms.peek()) |next| {
if (next.deadline_ns > runner.time_ns) runner.time_ns = next.deadline_ns;
}
}
try runner.check_deadline();
runner.fire_alarms();
if (runner.ready.items.len != 0) return;
if (runner.alarms.items.len == 0) return error.Stalled;
}
}
/// Wake every futex waiter whose word no longer holds the value it waited on: another
/// thread changed it (commonware's waker called from an external thread).
fn wake_external(runner: *Runner) void {
assert(runner.config.external != null);
var node = runner.futex_waiters.first;
while (node) |n| {
node = n.next;
const task: *Task = @alignCast(@fieldParentPtr("futex_node", n));
const word: *const u32 = @ptrFromInt(task.futex_address);
if (@atomicLoad(u32, word, .acquire) != task.futex_expected) {
runner.wake(task, .notified);
}
}
}
fn fire_alarms(runner: *Runner) void {
while (runner.alarms.peek()) |next| {
if (next.deadline_ns > runner.time_ns) return;
const alarm = runner.alarms.pop().?;
const task = alarm.task;
assert(task.alarms_queued > 0);
task.alarms_queued -= 1;
// A stale alarm (its wait already ended) wakes nobody, as in commonware.
if (task.state == .blocked and task.wait_generation == alarm.generation) {
runner.wake(task, .timeout);
}
}
}
/// After the root returns (or the run fails): cancel every other task and run what is
/// ready, without advancing time, until nothing more can run. Then discard the rest.
fn shutdown(runner: *Runner) void {
const previous = active_runner;
active_runner = runner;
defer active_runner = previous;
var rounds: u32 = 0;
while (rounds < runner.config.max_tasks * 4) : (rounds += 1) {
var node = runner.tasks.first;
while (node) |n| : (node = n.next) {
const task: *Task = @alignCast(@fieldParentPtr("all_node", n));
if (task.state != .finished) runner.request_cancel(task);