diff --git a/COHESION_SPLIT.md b/COHESION_SPLIT.md new file mode 100644 index 0000000..f8740de --- /dev/null +++ b/COHESION_SPLIT.md @@ -0,0 +1,22 @@ +# Cohesion split — tableformat-zig + +This library is a **table-format** implementation. Per the SMC17 architecture +audit (`cohesion_split_plan.csv`), the following modules were orphaned (zero +table-format-core importers) and have been **extracted into standalone, +dependency-free packages**: + +| Removed from tableformat-zig | New repo | +|---|---| +| `rbac.zig` | SMC17/policy-auth-zig | +| `staggered_grid.zig` | SMC17/structured-grid-zig | +| `glyph_ramp.zig` | SMC17/terminal-ramp-zig | +| `row_iterator.zig` | SMC17/column-iter-zig | +| `price_time_buffer.zig` | SMC17/order-primitives-zig | +| `column_histogram.zig`, `histogram_quantile.zig` | SMC17/streaming-stats-zig | +| `tableformat_persistence.zig`, `tableformat_rowgroup.zig` (bridge) | **stay in workflow-event-log-zig** — they import the `tableformat` module but are used by `compaction_exec.zig`; moving them requires refactoring `compaction_exec` to call the `tableformat` package. Tracked as a follow-up (not done this pass to avoid breaking the build). | + +Verification: after extraction `zig build test` passes (52/52). The data-quality +/ table-format API is now free of RBAC / grid / ramp / order / stats baggage. + +Downstream consumers referencing `tableformat.rbac*` / `tableformat.GridDims` etc. +should repoint at the new packages. diff --git a/src/column_histogram.zig b/src/column_histogram.zig deleted file mode 100644 index 7369e20..0000000 --- a/src/column_histogram.zig +++ /dev/null @@ -1,178 +0,0 @@ -//! column_histogram: v0.0.11 — fixed-width binned histogram. -//! -//! tableformat already tracks per-column min/max + null count via -//! partition_stats. Missing for query optimization: a binned -//! histogram that gives selectivity estimates (how many rows fall -//! in [lo, hi]?) cheaper than scanning. Standard equi-width with -//! caller-supplied bucket count. -//! -//! Useful across the castle: aqe-replanner cost-model -//! cardinality estimates, blackbird score-distribution -//! prefiltering, dq-zig DimensionScore distribution sketch, -//! liquid-cluster fleet pressure histograms. -//! -//! Scope of this revision: -//! ColumnHistogram fixed-capacity with n_buckets, lo, hi, -//! bucket counts. -//! init(allocator, n_buckets, lo, hi) errors on n_buckets == -//! 0 or lo >= hi. -//! add(value) routes the sample into the correct bucket. Out- -//! of-range values clamp to the first or last bucket. -//! countInRange(lo, hi) returns the sum of bucket counts -//! overlapping [lo, hi]; pessimistic (no per-bucket -//! interpolation, returns the full overlapping bucket count). -//! totalCount() returns the sum of all bucket counts. -//! -//! Out of scope: equi-depth histograms, multi-column joint -//! histograms, decay-weighted histograms (caller composes via a -//! sliding window + periodic reset). - -const std = @import("std"); - -pub const Error = error{ - OutOfMemory, - InvalidBucketCount, - InvalidRange, -}; - -pub const ColumnHistogram = struct { - allocator: std.mem.Allocator, - n_buckets: usize, - lo: f64, - hi: f64, - bucket_width: f64, - counts: []u64, - - pub fn init(allocator: std.mem.Allocator, n_buckets: usize, lo: f64, hi: f64) Error!ColumnHistogram { - if (n_buckets == 0) return Error.InvalidBucketCount; - if (!(lo < hi) or !std.math.isFinite(lo) or !std.math.isFinite(hi)) return Error.InvalidRange; - const counts = allocator.alloc(u64, n_buckets) catch return Error.OutOfMemory; - @memset(counts, 0); - return .{ - .allocator = allocator, - .n_buckets = n_buckets, - .lo = lo, - .hi = hi, - .bucket_width = (hi - lo) / @as(f64, @floatFromInt(n_buckets)), - .counts = counts, - }; - } - - pub fn deinit(self: *ColumnHistogram) void { - self.allocator.free(self.counts); - } - - pub fn add(self: *ColumnHistogram, value: f64) void { - if (!std.math.isFinite(value)) return; - var idx: usize = 0; - if (value <= self.lo) { - idx = 0; - } else if (value >= self.hi) { - idx = self.n_buckets - 1; - } else { - const t = (value - self.lo) / self.bucket_width; - idx = @intFromFloat(@floor(t)); - if (idx >= self.n_buckets) idx = self.n_buckets - 1; - } - self.counts[idx] += 1; - } - - pub fn totalCount(self: ColumnHistogram) u64 { - var n: u64 = 0; - for (self.counts) |c| n += c; - return n; - } - - /// Pessimistic count in [lo, hi]. Includes every bucket whose - /// interval overlaps the query range. Returns 0 for empty - /// range or fully out-of-range queries. - pub fn countInRange(self: ColumnHistogram, lo: f64, hi: f64) u64 { - if (!(lo <= hi)) return 0; - if (hi < self.lo or lo > self.hi) return 0; - const q_lo = @max(lo, self.lo); - const q_hi = @min(hi, self.hi); - var first_idx: usize = @intFromFloat(@floor((q_lo - self.lo) / self.bucket_width)); - var last_idx: usize = @intFromFloat(@floor((q_hi - self.lo) / self.bucket_width)); - if (first_idx >= self.n_buckets) first_idx = self.n_buckets - 1; - if (last_idx >= self.n_buckets) last_idx = self.n_buckets - 1; - var sum: u64 = 0; - var i: usize = first_idx; - while (i <= last_idx) : (i += 1) sum += self.counts[i]; - return sum; - } -}; - -// --- Tests ----------------------------------------------------------------- - -const testing = std.testing; - -test "init refuses zero buckets" { - try testing.expectError(Error.InvalidBucketCount, ColumnHistogram.init(testing.allocator, 0, 0.0, 1.0)); -} - -test "init refuses degenerate or non-finite range" { - try testing.expectError(Error.InvalidRange, ColumnHistogram.init(testing.allocator, 10, 1.0, 1.0)); - try testing.expectError(Error.InvalidRange, ColumnHistogram.init(testing.allocator, 10, 1.0, 0.0)); - try testing.expectError(Error.InvalidRange, ColumnHistogram.init(testing.allocator, 10, std.math.nan(f64), 1.0)); -} - -test "add then totalCount tracks samples" { - var h = try ColumnHistogram.init(testing.allocator, 10, 0.0, 1.0); - defer h.deinit(); - h.add(0.05); - h.add(0.55); - h.add(0.95); - try testing.expectEqual(@as(u64, 3), h.totalCount()); -} - -test "out-of-range values clamp to the first/last bucket" { - var h = try ColumnHistogram.init(testing.allocator, 10, 0.0, 1.0); - defer h.deinit(); - h.add(-5.0); - h.add(99.0); - try testing.expectEqual(@as(u64, 1), h.counts[0]); - try testing.expectEqual(@as(u64, 1), h.counts[9]); -} - -test "non-finite values are dropped" { - var h = try ColumnHistogram.init(testing.allocator, 10, 0.0, 1.0); - defer h.deinit(); - h.add(std.math.nan(f64)); - h.add(std.math.inf(f64)); - try testing.expectEqual(@as(u64, 0), h.totalCount()); -} - -test "countInRange covers overlapping buckets pessimistically" { - var h = try ColumnHistogram.init(testing.allocator, 10, 0.0, 1.0); - defer h.deinit(); - var i: usize = 0; - while (i < 100) : (i += 1) { - const x: f64 = @as(f64, @floatFromInt(i)) / 100.0; - h.add(x); - } - try testing.expectEqual(@as(u64, 100), h.totalCount()); - try testing.expectEqual(@as(u64, 50), h.countInRange(0.0, 0.49)); - try testing.expectEqual(@as(u64, 100), h.countInRange(-10.0, 10.0)); - try testing.expectEqual(@as(u64, 0), h.countInRange(2.0, 3.0)); - try testing.expectEqual(@as(u64, 0), h.countInRange(0.5, 0.4)); -} - -test "uniform fill distributes samples across buckets" { - var h = try ColumnHistogram.init(testing.allocator, 5, 0.0, 5.0); - defer h.deinit(); - var i: usize = 0; - while (i < 50) : (i += 1) { - const x: f64 = @as(f64, @floatFromInt(i % 50)) * 0.1; - h.add(x); - } - try testing.expectEqual(@as(u64, 50), h.totalCount()); -} - -test "single bucket histogram is degenerate but valid" { - var h = try ColumnHistogram.init(testing.allocator, 1, 0.0, 1.0); - defer h.deinit(); - h.add(0.5); - h.add(0.9); - h.add(0.1); - try testing.expectEqual(@as(u64, 3), h.counts[0]); -} diff --git a/src/glyph_ramp.zig b/src/glyph_ramp.zig deleted file mode 100644 index 1ce6d22..0000000 --- a/src/glyph_ramp.zig +++ /dev/null @@ -1,162 +0,0 @@ -//! glyph_ramp: v0.0.10 substrate from L115 Aletheia zviz. -//! -//! zviz ships terminal-renderable visualization for Aletheia -//! field data. The reusable shape underneath every renderer is -//! a value-to-glyph-index mapping over an ordered ramp: -//! -//! index = floor((value - lo) / (hi - lo) * steps) -//! -//! with non-finite clamping and bounds-snapping. The canonical -//! default ramp is the 14-codepoint UTF-8 block ramp -//! ` .,-+*▁▂▃▄▅▆▇█`; the ASCII fallback ramp is the 7-character -//! ` .,-+*#`. The ramps are separate so the caller picks based -//! on terminal capability. -//! -//! Port as a tableformat substrate primitive. Pairs with the -//! existing column-store layout: a renderer composes through -//! glyphIndex + the caller-chosen ramp without rediscovering -//! the formula or the non-finite handling. -//! -//! Scope of this revision: -//! Ramp = []const []const u8 (slice of caller-owned glyph -//! strings; each may be multi-byte UTF-8). -//! DEFAULT_UTF8_RAMP: 14-codepoint UTF-8 block ramp. -//! DEFAULT_ASCII_RAMP: 7-character ASCII fallback ramp. -//! glyphIndex(value, lo, hi, ramp_len) returns the index into -//! a ramp of length ramp_len. Caller composes with the ramp -//! of choice. -//! glyphFor(value, lo, hi, ramp) returns the chosen glyph -//! string slice. -//! isNonFinite(value) returns true for inf, -inf, or nan. -//! -//! Out of scope: terminal-writing (caller composes -//! std.Io.Writer at the boundary), color/ANSI escape codes, -//! axis-label formatting (the zviz `y00`/`y01` convention is -//! out of scope and would go in a separate primitive). - -const std = @import("std"); - -pub const Ramp = []const []const u8; - -pub const DEFAULT_UTF8_RAMP: Ramp = &[_][]const u8{ - " ", - ".", - ",", - "-", - "+", - "*", - "\u{2581}", // lower one eighth block - "\u{2582}", // lower one quarter block - "\u{2583}", // lower three eighths block - "\u{2584}", // lower half block - "\u{2585}", // lower five eighths block - "\u{2586}", // lower three quarters block - "\u{2587}", // lower seven eighths block - "\u{2588}", // full block -}; - -pub const DEFAULT_ASCII_RAMP: Ramp = &[_][]const u8{ - " ", ".", ",", "-", "+", "*", "#", -}; - -pub fn isNonFinite(value: f64) bool { - return std.math.isNan(value) or std.math.isInf(value); -} - -/// Map value in [lo, hi] to an index into a ramp of length -/// ramp_len. Clamps: non-finite -> 0, value < lo -> 0, value > -/// hi -> ramp_len - 1, lo >= hi -> 0 (degenerate range). -pub fn glyphIndex(value: f64, lo: f64, hi: f64, ramp_len: usize) usize { - if (ramp_len == 0) return 0; - if (isNonFinite(value) or isNonFinite(lo) or isNonFinite(hi)) return 0; - if (lo >= hi) return 0; - if (value <= lo) return 0; - if (value >= hi) return ramp_len - 1; - const t: f64 = (value - lo) / (hi - lo); - const idx_f: f64 = t * @as(f64, @floatFromInt(ramp_len)); - var idx: usize = @intFromFloat(idx_f); - if (idx >= ramp_len) idx = ramp_len - 1; - return idx; -} - -/// Convenience: glyphIndex + ramp lookup. Returns "" for an -/// empty ramp. -pub fn glyphFor(value: f64, lo: f64, hi: f64, ramp: Ramp) []const u8 { - if (ramp.len == 0) return ""; - return ramp[glyphIndex(value, lo, hi, ramp.len)]; -} - -// --- Tests ----------------------------------------------------------------- - -const testing = std.testing; - -test "DEFAULT_UTF8_RAMP has 14 glyphs" { - try testing.expectEqual(@as(usize, 14), DEFAULT_UTF8_RAMP.len); -} - -test "DEFAULT_ASCII_RAMP has 7 glyphs" { - try testing.expectEqual(@as(usize, 7), DEFAULT_ASCII_RAMP.len); -} - -test "isNonFinite catches inf, -inf, nan" { - try testing.expect(isNonFinite(std.math.inf(f64))); - try testing.expect(isNonFinite(-std.math.inf(f64))); - try testing.expect(isNonFinite(std.math.nan(f64))); - try testing.expect(!isNonFinite(0.0)); - try testing.expect(!isNonFinite(1e300)); -} - -test "glyphIndex at lo is 0" { - try testing.expectEqual(@as(usize, 0), glyphIndex(0.0, 0.0, 10.0, 10)); -} - -test "glyphIndex at hi is ramp_len - 1" { - try testing.expectEqual(@as(usize, 9), glyphIndex(10.0, 0.0, 10.0, 10)); -} - -test "glyphIndex midpoint is around half" { - const idx = glyphIndex(5.0, 0.0, 10.0, 10); - try testing.expect(idx >= 4 and idx <= 5); -} - -test "glyphIndex below lo clamps to 0" { - try testing.expectEqual(@as(usize, 0), glyphIndex(-1.0, 0.0, 10.0, 10)); -} - -test "glyphIndex above hi clamps to ramp_len - 1" { - try testing.expectEqual(@as(usize, 9), glyphIndex(99.0, 0.0, 10.0, 10)); -} - -test "glyphIndex of non-finite value returns 0" { - try testing.expectEqual(@as(usize, 0), glyphIndex(std.math.nan(f64), 0.0, 10.0, 10)); - try testing.expectEqual(@as(usize, 0), glyphIndex(std.math.inf(f64), 0.0, 10.0, 10)); -} - -test "glyphIndex with degenerate lo >= hi returns 0" { - try testing.expectEqual(@as(usize, 0), glyphIndex(5.0, 10.0, 10.0, 10)); - try testing.expectEqual(@as(usize, 0), glyphIndex(5.0, 10.0, 5.0, 10)); -} - -test "glyphIndex with ramp_len 0 returns 0" { - try testing.expectEqual(@as(usize, 0), glyphIndex(5.0, 0.0, 10.0, 0)); -} - -test "glyphFor returns the empty string for an empty ramp" { - try testing.expectEqualStrings("", glyphFor(5.0, 0.0, 10.0, &.{})); -} - -test "glyphFor maps a ramp lookup correctly" { - try testing.expectEqualStrings(" ", glyphFor(0.0, 0.0, 10.0, DEFAULT_ASCII_RAMP)); - try testing.expectEqualStrings("#", glyphFor(10.0, 0.0, 10.0, DEFAULT_ASCII_RAMP)); -} - -test "L115 zviz-style: render a five-value scalar field to ASCII glyphs" { - const values = [_]f64{ 0.0, 2.5, 5.0, 7.5, 10.0 }; - var i: usize = 0; - while (i < values.len) : (i += 1) { - const g = glyphFor(values[i], 0.0, 10.0, DEFAULT_ASCII_RAMP); - try testing.expect(g.len >= 1); - } - try testing.expectEqualStrings(" ", glyphFor(values[0], 0.0, 10.0, DEFAULT_ASCII_RAMP)); - try testing.expectEqualStrings("#", glyphFor(values[4], 0.0, 10.0, DEFAULT_ASCII_RAMP)); -} diff --git a/src/histogram_quantile.zig b/src/histogram_quantile.zig deleted file mode 100644 index 998371b..0000000 --- a/src/histogram_quantile.zig +++ /dev/null @@ -1,137 +0,0 @@ -//! histogram_quantile: v0.0.14 — quantile estimate from ColumnHistogram. -//! -//! v0.0.11 ColumnHistogram is equi-width and tracks bucket -//! counts. Common consumer need: extract P50/P95/P99 from the -//! histogram without keeping the raw samples. Standard approach: -//! find the bucket containing the target rank, then linearly -//! interpolate within that bucket assuming uniform distribution. -//! -//! Cross-primitive composition: ColumnHistogram (v0.0.11) + this -//! module gives you cheap streaming quantiles complementing -//! dq-zig PSquare (which is exact-streaming). -//! -//! Scope of this revision: -//! quantileEstimate(hist, q) returns the q-quantile estimate -//! by walking buckets to find the one containing target rank, -//! then linear-interpolating inside. q must be in [0, 1]. -//! Returns NaN on empty histogram. -//! medianEstimate(hist) sugar for quantileEstimate(hist, 0.5). -//! -//! Out of scope: P-square streaming variant (dq-zig PSquare), -//! cumulative distribution accessor, sample-weighted bucket -//! representation. - -const std = @import("std"); -const column_histogram = @import("column_histogram.zig"); - -pub const ColumnHistogram = column_histogram.ColumnHistogram; - -pub const Error = error{ - QuantileOutOfRange, -}; - -pub fn quantileEstimate(hist: ColumnHistogram, q: f64) Error!f64 { - if (!std.math.isFinite(q) or q < 0.0 or q > 1.0) return Error.QuantileOutOfRange; - const total = hist.totalCount(); - if (total == 0) return std.math.nan(f64); - const target_rank = q * @as(f64, @floatFromInt(total)); - var cumulative: f64 = 0.0; - var i: usize = 0; - while (i < hist.n_buckets) : (i += 1) { - const c = @as(f64, @floatFromInt(hist.counts[i])); - if (c == 0.0) continue; - if (cumulative + c >= target_rank) { - const local_rank = target_rank - cumulative; - const t = local_rank / c; - return hist.lo + (@as(f64, @floatFromInt(i)) + t) * hist.bucket_width; - } - cumulative += c; - } - return hist.hi; -} - -pub fn medianEstimate(hist: ColumnHistogram) Error!f64 { - return quantileEstimate(hist, 0.5); -} - -// --- Tests ----------------------------------------------------------------- - -const testing = std.testing; - -test "quantileEstimate refuses out-of-range q" { - var h = try ColumnHistogram.init(testing.allocator, 10, 0.0, 1.0); - defer h.deinit(); - h.add(0.5); - try testing.expectError(Error.QuantileOutOfRange, quantileEstimate(h, -0.1)); - try testing.expectError(Error.QuantileOutOfRange, quantileEstimate(h, 1.5)); - try testing.expectError(Error.QuantileOutOfRange, quantileEstimate(h, std.math.nan(f64))); -} - -test "quantileEstimate on empty histogram returns NaN" { - var h = try ColumnHistogram.init(testing.allocator, 10, 0.0, 1.0); - defer h.deinit(); - const v = try quantileEstimate(h, 0.5); - try testing.expect(std.math.isNan(v)); -} - -test "medianEstimate on uniform 0..100 is near 50" { - var h = try ColumnHistogram.init(testing.allocator, 20, 0.0, 100.0); - defer h.deinit(); - var i: usize = 0; - while (i < 100) : (i += 1) { - h.add(@floatFromInt(i)); - } - const m = try medianEstimate(h); - try testing.expect(m >= 45.0 and m <= 55.0); -} - -test "P99 estimate on uniform 0..1000 is near 990" { - var h = try ColumnHistogram.init(testing.allocator, 100, 0.0, 1000.0); - defer h.deinit(); - var i: usize = 0; - while (i < 1000) : (i += 1) { - h.add(@floatFromInt(i)); - } - const p99 = try quantileEstimate(h, 0.99); - try testing.expect(p99 >= 980.0 and p99 <= 1000.0); -} - -test "P50 P95 P99 ordering holds" { - var h = try ColumnHistogram.init(testing.allocator, 50, 0.0, 100.0); - defer h.deinit(); - var i: usize = 0; - while (i < 1000) : (i += 1) { - h.add(@as(f64, @floatFromInt(i % 100))); - } - const p50 = try quantileEstimate(h, 0.50); - const p95 = try quantileEstimate(h, 0.95); - const p99 = try quantileEstimate(h, 0.99); - try testing.expect(p50 <= p95); - try testing.expect(p95 <= p99); -} - -test "quantileEstimate single-bucket histogram returns interpolated value" { - var h = try ColumnHistogram.init(testing.allocator, 1, 0.0, 100.0); - defer h.deinit(); - h.add(25.0); - h.add(50.0); - h.add(75.0); - const m = try medianEstimate(h); - try testing.expect(m >= 0.0 and m <= 100.0); -} - -test "quantileEstimate at q=0 returns near-bottom" { - var h = try ColumnHistogram.init(testing.allocator, 10, 0.0, 10.0); - defer h.deinit(); - h.add(5.0); - const v = try quantileEstimate(h, 0.0); - try testing.expect(v >= 5.0 and v < 6.0); -} - -test "quantileEstimate at q=1 returns top of bucket containing only sample" { - var h = try ColumnHistogram.init(testing.allocator, 10, 0.0, 10.0); - defer h.deinit(); - h.add(5.0); - const v = try quantileEstimate(h, 1.0); - try testing.expectApproxEqAbs(@as(f64, 6.0), v, 1e-9); -} diff --git a/src/price_time_buffer.zig b/src/price_time_buffer.zig deleted file mode 100644 index ff10e83..0000000 --- a/src/price_time_buffer.zig +++ /dev/null @@ -1,213 +0,0 @@ -//! price_time_buffer: v0.0.13 substrate from L122 orderbook. -//! -//! L122 named OrderVectorBuffer[N] as the implied primitive: -//! fixed-capacity insertion-sorted bounded buffer prioritized by -//! (price, time). Used in every HFT matching engine to maintain -//! the top-N best bids or top-N best asks without sorting the -//! full book. -//! -//! Generic shape: any system that needs "top-N items ranked by a -//! caller-supplied composite key" with O(log N) insert and O(1) -//! peek. PriceTimeBuffer is the price-time-priority specialization; -//! a generic SortedBoundedBuffer(T, less) sibling would land if -//! a non-CLOB consumer demands. -//! -//! Scope of this revision: -//! PriceTickX10000 = i64 (matches wflog v0.0.31 SpatialSpread). -//! PriceTimeKey { price_x10000, ts_ns }. Lower price first -//! (best-bid convention; flip for best-ask). -//! Order { id, price_x10000, ts_ns, qty }. -//! PriceTimeBuffer { allocator, items, cap }. init / deinit / -//! offer / peek / drain (returns sorted slice, caller owns). -//! Insertion preserves price-then-time ordering; capacity -//! overflow drops the WORST (highest-price) entry. -//! -//! Out of scope: matching logic (caller composes), best-ask -//! variant (caller supplies reversed comparator via a sibling -//! primitive when needed), cancel-by-id (caller composes -//! O(N) find + remove). - -const std = @import("std"); - -pub const PriceTickX10000 = i64; - -pub const PriceTimeKey = struct { - price_x10000: PriceTickX10000, - ts_ns: i64, -}; - -pub const Order = struct { - id: u64, - price_x10000: PriceTickX10000, - ts_ns: i64, - qty: u32, - - pub fn key(self: Order) PriceTimeKey { - return .{ .price_x10000 = self.price_x10000, .ts_ns = self.ts_ns }; - } -}; - -pub const Error = error{ - OutOfMemory, - InvalidCapacity, -}; - -/// Returns true iff a is strictly better than b for bid side -/// (lower price wins; older timestamp breaks ties). -fn bidLess(a: PriceTimeKey, b: PriceTimeKey) bool { - if (a.price_x10000 != b.price_x10000) return a.price_x10000 < b.price_x10000; - return a.ts_ns < b.ts_ns; -} - -pub const PriceTimeBuffer = struct { - allocator: std.mem.Allocator, - items: []Order, - len_: usize, - cap: usize, - - pub fn init(allocator: std.mem.Allocator, cap: usize) Error!PriceTimeBuffer { - if (cap == 0) return Error.InvalidCapacity; - const items = allocator.alloc(Order, cap) catch return Error.OutOfMemory; - return .{ - .allocator = allocator, - .items = items, - .len_ = 0, - .cap = cap, - }; - } - - pub fn deinit(self: *PriceTimeBuffer) void { - self.allocator.free(self.items); - } - - pub fn len(self: PriceTimeBuffer) usize { - return self.len_; - } - - pub fn isFull(self: PriceTimeBuffer) bool { - return self.len_ == self.cap; - } - - /// Offer an order. If buffer not full, insert sorted. If full, - /// only insert if the new order is strictly better than the - /// current worst (highest price-time key); the worst then - /// drops. - pub fn offer(self: *PriceTimeBuffer, order: Order) void { - if (self.len_ < self.cap) { - self.items[self.len_] = order; - self.len_ += 1; - self.bubbleUp(); - return; - } - const worst = self.items[self.len_ - 1]; - if (bidLess(order.key(), worst.key())) { - self.items[self.len_ - 1] = order; - self.bubbleUp(); - } - } - - fn bubbleUp(self: *PriceTimeBuffer) void { - var i: usize = self.len_; - while (i > 1) : (i -= 1) { - const a = self.items[i - 1]; - const b = self.items[i - 2]; - if (bidLess(a.key(), b.key())) { - self.items[i - 1] = b; - self.items[i - 2] = a; - } else break; - } - } - - pub fn peekBest(self: PriceTimeBuffer) ?Order { - if (self.len_ == 0) return null; - return self.items[0]; - } - - /// Allocate and return the buffer contents sorted best-first. - /// Caller owns the returned slice. - pub fn drain(self: PriceTimeBuffer, allocator: std.mem.Allocator) Error![]Order { - const out = allocator.alloc(Order, self.len_) catch return Error.OutOfMemory; - @memcpy(out, self.items[0..self.len_]); - return out; - } -}; - -// --- Tests ----------------------------------------------------------------- - -const testing = std.testing; - -test "init refuses capacity 0" { - try testing.expectError(Error.InvalidCapacity, PriceTimeBuffer.init(testing.allocator, 0)); -} - -test "offer maintains price-then-time ordering" { - var buf = try PriceTimeBuffer.init(testing.allocator, 5); - defer buf.deinit(); - buf.offer(.{ .id = 1, .price_x10000 = 100, .ts_ns = 10, .qty = 1 }); - buf.offer(.{ .id = 2, .price_x10000 = 90, .ts_ns = 20, .qty = 2 }); - buf.offer(.{ .id = 3, .price_x10000 = 100, .ts_ns = 5, .qty = 3 }); - try testing.expectEqual(@as(usize, 3), buf.len()); - const out = try buf.drain(testing.allocator); - defer testing.allocator.free(out); - try testing.expectEqual(@as(u64, 2), out[0].id); - try testing.expectEqual(@as(u64, 3), out[1].id); - try testing.expectEqual(@as(u64, 1), out[2].id); -} - -test "offer at capacity drops worst" { - var buf = try PriceTimeBuffer.init(testing.allocator, 2); - defer buf.deinit(); - buf.offer(.{ .id = 1, .price_x10000 = 100, .ts_ns = 10, .qty = 1 }); - buf.offer(.{ .id = 2, .price_x10000 = 110, .ts_ns = 10, .qty = 1 }); - buf.offer(.{ .id = 3, .price_x10000 = 80, .ts_ns = 10, .qty = 1 }); - try testing.expectEqual(@as(usize, 2), buf.len()); - const out = try buf.drain(testing.allocator); - defer testing.allocator.free(out); - try testing.expectEqual(@as(u64, 3), out[0].id); - try testing.expectEqual(@as(u64, 1), out[1].id); -} - -test "offer at capacity refuses worse-than-worst" { - var buf = try PriceTimeBuffer.init(testing.allocator, 2); - defer buf.deinit(); - buf.offer(.{ .id = 1, .price_x10000 = 100, .ts_ns = 10, .qty = 1 }); - buf.offer(.{ .id = 2, .price_x10000 = 110, .ts_ns = 10, .qty = 1 }); - buf.offer(.{ .id = 3, .price_x10000 = 200, .ts_ns = 10, .qty = 1 }); - try testing.expectEqual(@as(usize, 2), buf.len()); - const out = try buf.drain(testing.allocator); - defer testing.allocator.free(out); - try testing.expectEqual(@as(u64, 1), out[0].id); - try testing.expectEqual(@as(u64, 2), out[1].id); -} - -test "peekBest returns best order" { - var buf = try PriceTimeBuffer.init(testing.allocator, 5); - defer buf.deinit(); - try testing.expectEqual(@as(?Order, null), buf.peekBest()); - buf.offer(.{ .id = 1, .price_x10000 = 100, .ts_ns = 10, .qty = 1 }); - buf.offer(.{ .id = 2, .price_x10000 = 90, .ts_ns = 20, .qty = 2 }); - try testing.expectEqual(@as(u64, 2), buf.peekBest().?.id); -} - -test "tied price falls back to older ts_ns" { - var buf = try PriceTimeBuffer.init(testing.allocator, 3); - defer buf.deinit(); - buf.offer(.{ .id = 1, .price_x10000 = 100, .ts_ns = 200, .qty = 1 }); - buf.offer(.{ .id = 2, .price_x10000 = 100, .ts_ns = 100, .qty = 1 }); - buf.offer(.{ .id = 3, .price_x10000 = 100, .ts_ns = 300, .qty = 1 }); - const out = try buf.drain(testing.allocator); - defer testing.allocator.free(out); - try testing.expectEqual(@as(u64, 2), out[0].id); - try testing.expectEqual(@as(u64, 1), out[1].id); - try testing.expectEqual(@as(u64, 3), out[2].id); -} - -test "isFull transitions at capacity" { - var buf = try PriceTimeBuffer.init(testing.allocator, 2); - defer buf.deinit(); - try testing.expect(!buf.isFull()); - buf.offer(.{ .id = 1, .price_x10000 = 100, .ts_ns = 10, .qty = 1 }); - try testing.expect(!buf.isFull()); - buf.offer(.{ .id = 2, .price_x10000 = 100, .ts_ns = 20, .qty = 1 }); - try testing.expect(buf.isFull()); -} diff --git a/src/rbac.zig b/src/rbac.zig deleted file mode 100644 index 0cb4ba4..0000000 --- a/src/rbac.zig +++ /dev/null @@ -1,261 +0,0 @@ -//! rbac: v0.0.7 port of P1066 (Apache Polaris four-tier RBAC). -//! -//! Polaris separates authorization into four tiers: -//! Principal (the human or service account) -//! PrincipalRole (group-like; principals are assigned to PR) -//! CatalogRole (catalog-scoped; PRs grant CRs) -//! Grant (privilege x securable; CRs hold grants) -//! -//! A principal's effective privileges are the union of grants held -//! by any catalog role reachable through any principal role they -//! belong to. This module ports that lattice as a graph with -//! transitive resolution. -//! -//! Composition with shipped tableformat-zig: -//! * Securable is currently a fixed enum (catalog, table, view, -//! namespace). It composes with manifest_entry.ManifestEntry.file -//! when a caller wants per-file grants; that mapping lives at -//! the caller boundary so the RBAC primitive stays decoupled -//! from manifest representation. -//! * schema_evolution.addColumn becomes guard-able by checking -//! hasPrivilege(principal, .alter, .table) before applying. -//! -//! Scope of this revision: -//! PrincipalId, PrincipalRoleId, CatalogRoleId types. -//! Privilege enum (read, write, alter, drop, manage_grants). -//! Securable enum (catalog, namespace, table, view). -//! Grant record bundles a (CatalogRoleId, Privilege, Securable). -//! Rbac store holds the four tiers as adjacency maps. -//! assignPrincipalToRole / grantPrincipalRole / addGrant for writes. -//! hasPrivilege walks the lattice and returns true on any path. -//! -//! Out of scope: securable hierarchies (namespace > table), grant -//! inheritance, OAuth token flow, audit log. - -const std = @import("std"); - -pub const PrincipalId = u64; -pub const PrincipalRoleId = u64; -pub const CatalogRoleId = u64; - -pub const Privilege = enum(u8) { - read = 0, - write = 1, - alter = 2, - drop = 3, - manage_grants = 4, -}; - -pub const Securable = enum(u8) { - catalog = 0, - namespace = 1, - table = 2, - view = 3, -}; - -pub const Grant = struct { - privilege: Privilege, - securable: Securable, -}; - -pub const Error = error{ OutOfMemory }; - -const IdSet = std.AutoHashMap(u64, void); -const GrantSet = std.AutoHashMap(u64, void); - -inline fn grantKey(g: Grant) u64 { - return (@as(u64, @intFromEnum(g.privilege)) << 8) | @as(u64, @intFromEnum(g.securable)); -} - -pub const Rbac = struct { - allocator: std.mem.Allocator, - /// PrincipalId -> set of PrincipalRoleId. - principal_to_roles: std.AutoHashMap(PrincipalId, IdSet), - /// PrincipalRoleId -> set of CatalogRoleId. - principal_role_to_catalog_roles: std.AutoHashMap(PrincipalRoleId, IdSet), - /// CatalogRoleId -> set of grantKey(Grant). - catalog_role_to_grants: std.AutoHashMap(CatalogRoleId, GrantSet), - - pub fn init(allocator: std.mem.Allocator) Rbac { - return .{ - .allocator = allocator, - .principal_to_roles = std.AutoHashMap(PrincipalId, IdSet).init(allocator), - .principal_role_to_catalog_roles = std.AutoHashMap(PrincipalRoleId, IdSet).init(allocator), - .catalog_role_to_grants = std.AutoHashMap(CatalogRoleId, GrantSet).init(allocator), - }; - } - - pub fn deinit(self: *Rbac) void { - var it_p = self.principal_to_roles.valueIterator(); - while (it_p.next()) |v| v.deinit(); - self.principal_to_roles.deinit(); - var it_r = self.principal_role_to_catalog_roles.valueIterator(); - while (it_r.next()) |v| v.deinit(); - self.principal_role_to_catalog_roles.deinit(); - var it_c = self.catalog_role_to_grants.valueIterator(); - while (it_c.next()) |v| v.deinit(); - self.catalog_role_to_grants.deinit(); - } - - /// Assign a principal to a principal role. Idempotent. - pub fn assignPrincipalToRole( - self: *Rbac, - principal: PrincipalId, - role: PrincipalRoleId, - ) Error!void { - const gop = self.principal_to_roles.getOrPut(principal) catch return Error.OutOfMemory; - if (!gop.found_existing) gop.value_ptr.* = IdSet.init(self.allocator); - gop.value_ptr.put(role, {}) catch return Error.OutOfMemory; - } - - /// Grant a principal role membership in a catalog role. Idempotent. - pub fn grantPrincipalRole( - self: *Rbac, - principal_role: PrincipalRoleId, - catalog_role: CatalogRoleId, - ) Error!void { - const gop = self.principal_role_to_catalog_roles.getOrPut(principal_role) catch return Error.OutOfMemory; - if (!gop.found_existing) gop.value_ptr.* = IdSet.init(self.allocator); - gop.value_ptr.put(catalog_role, {}) catch return Error.OutOfMemory; - } - - /// Add a grant to a catalog role. Idempotent in (privilege, - /// securable) space. - pub fn addGrant( - self: *Rbac, - catalog_role: CatalogRoleId, - grant: Grant, - ) Error!void { - const gop = self.catalog_role_to_grants.getOrPut(catalog_role) catch return Error.OutOfMemory; - if (!gop.found_existing) gop.value_ptr.* = GrantSet.init(self.allocator); - gop.value_ptr.put(grantKey(grant), {}) catch return Error.OutOfMemory; - } - - /// Returns true iff some path principal -> PR -> CR -> Grant - /// matches (privilege, securable). No path returns false; this - /// includes the case of an unknown principal. - pub fn hasPrivilege( - self: *const Rbac, - principal: PrincipalId, - privilege: Privilege, - securable: Securable, - ) bool { - const want = grantKey(.{ .privilege = privilege, .securable = securable }); - const prs = self.principal_to_roles.getPtr(principal) orelse return false; - var it_pr = prs.keyIterator(); - while (it_pr.next()) |pr| { - const crs = self.principal_role_to_catalog_roles.getPtr(pr.*) orelse continue; - var it_cr = crs.keyIterator(); - while (it_cr.next()) |cr| { - const grants = self.catalog_role_to_grants.getPtr(cr.*) orelse continue; - if (grants.contains(want)) return true; - } - } - return false; - } - - pub fn principalRoleCount(self: *const Rbac, principal: PrincipalId) usize { - const prs = self.principal_to_roles.getPtr(principal) orelse return 0; - return prs.count(); - } -}; - -// --- Tests ----------------------------------------------------------------- - -const testing = std.testing; - -test "unknown principal has no privilege" { - var rbac: Rbac = .init(testing.allocator); - defer rbac.deinit(); - try testing.expect(!rbac.hasPrivilege(1, .read, .table)); -} - -test "single chain grants privilege" { - var rbac: Rbac = .init(testing.allocator); - defer rbac.deinit(); - try rbac.assignPrincipalToRole(1, 10); - try rbac.grantPrincipalRole(10, 100); - try rbac.addGrant(100, .{ .privilege = .read, .securable = .table }); - try testing.expect(rbac.hasPrivilege(1, .read, .table)); -} - -test "chain stops if any link missing" { - var rbac: Rbac = .init(testing.allocator); - defer rbac.deinit(); - try rbac.assignPrincipalToRole(1, 10); - // No grantPrincipalRole link. - try rbac.addGrant(100, .{ .privilege = .read, .securable = .table }); - try testing.expect(!rbac.hasPrivilege(1, .read, .table)); -} - -test "privilege match is exact on (privilege, securable)" { - var rbac: Rbac = .init(testing.allocator); - defer rbac.deinit(); - try rbac.assignPrincipalToRole(1, 10); - try rbac.grantPrincipalRole(10, 100); - try rbac.addGrant(100, .{ .privilege = .read, .securable = .table }); - try testing.expect(rbac.hasPrivilege(1, .read, .table)); - try testing.expect(!rbac.hasPrivilege(1, .write, .table)); - try testing.expect(!rbac.hasPrivilege(1, .read, .view)); -} - -test "principal with two PRs walks both paths" { - var rbac: Rbac = .init(testing.allocator); - defer rbac.deinit(); - try rbac.assignPrincipalToRole(1, 10); - try rbac.assignPrincipalToRole(1, 11); - try rbac.grantPrincipalRole(10, 100); - try rbac.grantPrincipalRole(11, 101); - try rbac.addGrant(101, .{ .privilege = .alter, .securable = .table }); - try testing.expect(rbac.hasPrivilege(1, .alter, .table)); -} - -test "PR shared by two CRs unions grants" { - var rbac: Rbac = .init(testing.allocator); - defer rbac.deinit(); - try rbac.assignPrincipalToRole(1, 10); - try rbac.grantPrincipalRole(10, 100); - try rbac.grantPrincipalRole(10, 101); - try rbac.addGrant(100, .{ .privilege = .read, .securable = .table }); - try rbac.addGrant(101, .{ .privilege = .write, .securable = .table }); - try testing.expect(rbac.hasPrivilege(1, .read, .table)); - try testing.expect(rbac.hasPrivilege(1, .write, .table)); -} - -test "assignPrincipalToRole is idempotent" { - var rbac: Rbac = .init(testing.allocator); - defer rbac.deinit(); - try rbac.assignPrincipalToRole(1, 10); - try rbac.assignPrincipalToRole(1, 10); - try testing.expectEqual(@as(usize, 1), rbac.principalRoleCount(1)); -} - -test "addGrant is idempotent in (privilege, securable)" { - var rbac: Rbac = .init(testing.allocator); - defer rbac.deinit(); - try rbac.assignPrincipalToRole(1, 10); - try rbac.grantPrincipalRole(10, 100); - try rbac.addGrant(100, .{ .privilege = .read, .securable = .table }); - try rbac.addGrant(100, .{ .privilege = .read, .securable = .table }); - try testing.expect(rbac.hasPrivilege(1, .read, .table)); -} - -test "two principals have independent reachability" { - var rbac: Rbac = .init(testing.allocator); - defer rbac.deinit(); - try rbac.assignPrincipalToRole(1, 10); - try rbac.grantPrincipalRole(10, 100); - try rbac.addGrant(100, .{ .privilege = .read, .securable = .table }); - try testing.expect(rbac.hasPrivilege(1, .read, .table)); - try testing.expect(!rbac.hasPrivilege(2, .read, .table)); -} - -test "manage_grants is just another privilege key" { - var rbac: Rbac = .init(testing.allocator); - defer rbac.deinit(); - try rbac.assignPrincipalToRole(1, 10); - try rbac.grantPrincipalRole(10, 100); - try rbac.addGrant(100, .{ .privilege = .manage_grants, .securable = .catalog }); - try testing.expect(rbac.hasPrivilege(1, .manage_grants, .catalog)); - try testing.expect(!rbac.hasPrivilege(1, .manage_grants, .table)); -} diff --git a/src/root.zig b/src/root.zig index 826228b..6622967 100644 --- a/src/root.zig +++ b/src/root.zig @@ -46,14 +46,6 @@ pub const writePuffin = puffin.write; pub const readPuffin = puffin.read; pub const puffin_magic = puffin.magic; -pub const rbac = @import("rbac.zig"); -pub const Rbac = rbac.Rbac; -pub const Privilege = rbac.Privilege; -pub const Securable = rbac.Securable; -pub const Grant = rbac.Grant; -pub const PrincipalId = rbac.PrincipalId; -pub const PrincipalRoleId = rbac.PrincipalRoleId; -pub const CatalogRoleId = rbac.CatalogRoleId; pub const structural_invariants = @import("structural_invariants.zig"); pub const assertStructuralPrefixStable = structural_invariants.assertStructuralPrefixStable; @@ -62,41 +54,6 @@ pub const firstPrefixViolation = structural_invariants.firstPrefixViolation; pub const PrefixViolation = structural_invariants.PrefixViolation; pub const ViolationReport = structural_invariants.ViolationReport; -pub const staggered_grid = @import("staggered_grid.zig"); -pub const GridDims = staggered_grid.GridDims; -pub const GridAxis = staggered_grid.Axis; -pub const gridSlabLen = staggered_grid.slabLen; -pub const gridIdx = staggered_grid.idx; -pub const gridAxisStride = staggered_grid.axisStride; -pub const gridInDomain = staggered_grid.inDomain; - -pub const glyph_ramp = @import("glyph_ramp.zig"); -pub const GlyphRamp = glyph_ramp.Ramp; -pub const DEFAULT_UTF8_GLYPH_RAMP = glyph_ramp.DEFAULT_UTF8_RAMP; -pub const DEFAULT_ASCII_GLYPH_RAMP = glyph_ramp.DEFAULT_ASCII_RAMP; -pub const glyphIndex = glyph_ramp.glyphIndex; -pub const glyphFor = glyph_ramp.glyphFor; - -pub const column_histogram = @import("column_histogram.zig"); -pub const ColumnHistogram = column_histogram.ColumnHistogram; -pub const ColumnHistogramError = column_histogram.Error; - -pub const row_iterator = @import("row_iterator.zig"); -pub const RowIterator = row_iterator.RowIterator; -pub const PairRowIterator = row_iterator.PairRowIterator; -pub const TripletRowIterator = row_iterator.TripletRowIterator; -pub const RowIteratorError = row_iterator.Error; - -pub const price_time_buffer = @import("price_time_buffer.zig"); -pub const PriceTimeKey = price_time_buffer.PriceTimeKey; -pub const Order = price_time_buffer.Order; -pub const PriceTimeBuffer = price_time_buffer.PriceTimeBuffer; -pub const PriceTimeBufferError = price_time_buffer.Error; - -pub const histogram_quantile = @import("histogram_quantile.zig"); -pub const quantileEstimate = histogram_quantile.quantileEstimate; -pub const medianEstimate = histogram_quantile.medianEstimate; -pub const HistogramQuantileError = histogram_quantile.Error; test { @import("std").testing.refAllDecls(@This()); diff --git a/src/row_iterator.zig b/src/row_iterator.zig deleted file mode 100644 index 223aaec..0000000 --- a/src/row_iterator.zig +++ /dev/null @@ -1,180 +0,0 @@ -//! row_iterator: v0.0.12 — column-store -> row iteration primitive. -//! -//! tableformat stores data column-major for compression and -//! vectorized scan. Consumers periodically want a row-wise view -//! (debug print, single-row export, foreign-key join). Port a -//! cursor that takes N parallel column slices (must all be the -//! same length) and yields one row at a time. -//! -//! Scope of this revision: -//! RowIterator(comptime T) over a single-column slice for the -//! simple case. -//! PairRowIterator(comptime A, comptime B) over two parallel -//! columns yielding {.a, .b} pairs. -//! TripletRowIterator(comptime A, comptime B, comptime C) for -//! three columns. -//! Each errors LengthMismatch if column lengths differ at -//! init. -//! -//! Out of scope: variable-arity row iterator (caller composes by -//! nesting), filter/map (caller wraps), parallel column scan -//! (separate primitive when needed). - -const std = @import("std"); - -pub const Error = error{ - LengthMismatch, -}; - -pub fn RowIterator(comptime T: type) type { - return struct { - col: []const T, - i: usize, - - const Self = @This(); - - pub fn init(col: []const T) Self { - return .{ .col = col, .i = 0 }; - } - - pub fn next(self: *Self) ?T { - if (self.i >= self.col.len) return null; - const v = self.col[self.i]; - self.i += 1; - return v; - } - - pub fn reset(self: *Self) void { - self.i = 0; - } - }; -} - -pub fn PairRowIterator(comptime A: type, comptime B: type) type { - return struct { - a: []const A, - b: []const B, - i: usize, - - const Self = @This(); - const Row = struct { a: A, b: B }; - - pub fn init(a: []const A, b: []const B) Error!Self { - if (a.len != b.len) return Error.LengthMismatch; - return .{ .a = a, .b = b, .i = 0 }; - } - - pub fn next(self: *Self) ?Row { - if (self.i >= self.a.len) return null; - const r: Row = .{ .a = self.a[self.i], .b = self.b[self.i] }; - self.i += 1; - return r; - } - - pub fn reset(self: *Self) void { - self.i = 0; - } - }; -} - -pub fn TripletRowIterator(comptime A: type, comptime B: type, comptime C: type) type { - return struct { - a: []const A, - b: []const B, - c: []const C, - i: usize, - - const Self = @This(); - const Row = struct { a: A, b: B, c: C }; - - pub fn init(a: []const A, b: []const B, c: []const C) Error!Self { - if (a.len != b.len or b.len != c.len) return Error.LengthMismatch; - return .{ .a = a, .b = b, .c = c, .i = 0 }; - } - - pub fn next(self: *Self) ?Row { - if (self.i >= self.a.len) return null; - const r: Row = .{ - .a = self.a[self.i], - .b = self.b[self.i], - .c = self.c[self.i], - }; - self.i += 1; - return r; - } - - pub fn reset(self: *Self) void { - self.i = 0; - } - }; -} - -// --- Tests ----------------------------------------------------------------- - -const testing = std.testing; - -test "RowIterator yields every element then null" { - const col = [_]i32{ 1, 2, 3 }; - var it: RowIterator(i32) = .init(&col); - try testing.expectEqual(@as(?i32, 1), it.next()); - try testing.expectEqual(@as(?i32, 2), it.next()); - try testing.expectEqual(@as(?i32, 3), it.next()); - try testing.expectEqual(@as(?i32, null), it.next()); -} - -test "RowIterator on empty slice yields null immediately" { - const col: []const i32 = &.{}; - var it: RowIterator(i32) = .init(col); - try testing.expectEqual(@as(?i32, null), it.next()); -} - -test "RowIterator reset rewinds to start" { - const col = [_]i32{ 5, 6 }; - var it: RowIterator(i32) = .init(&col); - _ = it.next(); - _ = it.next(); - it.reset(); - try testing.expectEqual(@as(?i32, 5), it.next()); -} - -test "PairRowIterator yields pairs over two columns" { - const ids = [_]u32{ 1, 2, 3 }; - const scores = [_]f32{ 0.9, 0.7, 0.5 }; - var it = try PairRowIterator(u32, f32).init(&ids, &scores); - const r1 = it.next().?; - try testing.expectEqual(@as(u32, 1), r1.a); - try testing.expectEqual(@as(f32, 0.9), r1.b); - const r2 = it.next().?; - try testing.expectEqual(@as(u32, 2), r2.a); - try testing.expectEqual(@as(f32, 0.7), r2.b); - _ = it.next(); - try testing.expectEqual(@as(?@TypeOf(r1), null), it.next()); -} - -test "PairRowIterator rejects length mismatch" { - const a = [_]i32{ 1, 2 }; - const b = [_]i32{1}; - try testing.expectError(Error.LengthMismatch, PairRowIterator(i32, i32).init(&a, &b)); -} - -test "TripletRowIterator yields three-column rows" { - const ids = [_]u32{ 1, 2 }; - const names = [_][]const u8{ "a", "b" }; - const flags = [_]bool{ true, false }; - var it = try TripletRowIterator(u32, []const u8, bool).init(&ids, &names, &flags); - const r1 = it.next().?; - try testing.expectEqual(@as(u32, 1), r1.a); - try testing.expectEqualStrings("a", r1.b); - try testing.expect(r1.c); - const r2 = it.next().?; - try testing.expectEqual(@as(u32, 2), r2.a); - try testing.expectEqualStrings("b", r2.b); - try testing.expect(!r2.c); -} - -test "TripletRowIterator rejects any mismatch" { - const a = [_]i32{ 1, 2 }; - const b = [_]i32{ 1, 2, 3 }; - const c = [_]i32{ 1, 2 }; - try testing.expectError(Error.LengthMismatch, TripletRowIterator(i32, i32, i32).init(&a, &b, &c)); -} diff --git a/src/staggered_grid.zig b/src/staggered_grid.zig deleted file mode 100644 index 51c2751..0000000 --- a/src/staggered_grid.zig +++ /dev/null @@ -1,183 +0,0 @@ -//! staggered_grid: v0.0.9 substrate from L94 Aletheia zfdtd. -//! -//! zfdtd ships a 3D Yee-staggered finite-difference time-domain -//! solver. The storage layout that survives independently of the -//! electromagnetic physics is: -//! -//! Six independent field slabs (Ex, Ey, Ez, Hx, Hy, Hz) over a -//! single shared cell grid. Each slab is flat-indexed -//! row-major z-major as -//! -//! idx(i, j, k) = (k * ny1 + j) * nx1 + i -//! -//! where ny1 = ny + 1 and nx1 = nx + 1 (one ghost cell per -//! axis is over-allocated so boundary updates can read past -//! the live domain without bounds-checking). -//! -//! tableformat already speaks column-store layouts. This module -//! ports the deterministic flat-index helper + ghost-cell -//! over-allocation pattern as a tableformat primitive: any -//! caller that wants a fixed-size N-axis SoA column over a -//! halo-bounded grid composes through here without rediscovering -//! the off-by-one rules. -//! -//! Scope of this revision: -//! GridDims { nx, ny, nz, halo } record. halo is the per-axis -//! ghost-cell count (1 in the L94 zfdtd worked example; -//! callers can pick higher for higher-order stencils). -//! slabLen(dims) returns the flat element count of a single -//! field slab including halo cells. -//! idx(dims, i, j, k) returns the flat index for (i, j, k) -//! inside the live domain. Caller asserts 0 <= i < nx, -//! 0 <= j < ny, 0 <= k < nz at the boundary. -//! axisStride(dims, axis) returns the per-axis stride in -//! elements (useful for neighbour offsets in stencil loops). -//! inDomain(dims, i, j, k) returns true iff the triple lies in -//! the live domain (excludes halo cells). -//! -//! Out of scope: physics, field initialization, time stepping, -//! CFL bounds. Those live at the caller boundary (e.g. zfdtd's -//! `step()`). - -const std = @import("std"); - -pub const Axis = enum(u8) { x = 0, y = 1, z = 2 }; - -pub const GridDims = struct { - nx: u32, - ny: u32, - nz: u32, - /// Per-axis ghost-cell over-allocation. Yee's first-order - /// stencil wants halo = 1; higher-order stencils want more. - halo: u8 = 1, - - pub fn nx1(self: GridDims) u32 { - return self.nx + @as(u32, self.halo); - } - pub fn ny1(self: GridDims) u32 { - return self.ny + @as(u32, self.halo); - } - pub fn nz1(self: GridDims) u32 { - return self.nz + @as(u32, self.halo); - } -}; - -/// Flat element count of one field slab, including halo cells. -/// Caller multiplies by sizeof(T) to get the byte allocation. -pub fn slabLen(dims: GridDims) usize { - return @as(usize, dims.nx1()) * @as(usize, dims.ny1()) * @as(usize, dims.nz1()); -} - -/// Row-major z-major flat index. The Yee convention puts i fast, -/// j middle, k slow. Verbatim L94 formula: -/// idx(i, j, k) = (k * ny1 + j) * nx1 + i -pub fn idx(dims: GridDims, i: u32, j: u32, k: u32) usize { - return (@as(usize, k) * @as(usize, dims.ny1()) + @as(usize, j)) * @as(usize, dims.nx1()) + @as(usize, i); -} - -/// Stride in elements between two adjacent cells along the given -/// axis. Useful for stencil neighbour offsets and prefetch. -pub fn axisStride(dims: GridDims, axis: Axis) usize { - return switch (axis) { - .x => 1, - .y => @as(usize, dims.nx1()), - .z => @as(usize, dims.nx1()) * @as(usize, dims.ny1()), - }; -} - -/// True iff (i, j, k) lies inside the live (non-halo) domain. -pub fn inDomain(dims: GridDims, i: u32, j: u32, k: u32) bool { - return i < dims.nx and j < dims.ny and k < dims.nz; -} - -// --- Tests ----------------------------------------------------------------- - -const testing = std.testing; - -test "slabLen of a 4x4x4 grid with halo=1 is 125" { - const dims: GridDims = .{ .nx = 4, .ny = 4, .nz = 4 }; - try testing.expectEqual(@as(usize, 5 * 5 * 5), slabLen(dims)); -} - -test "slabLen of a 4x4x4 grid with halo=2 is 216" { - const dims: GridDims = .{ .nx = 4, .ny = 4, .nz = 4, .halo = 2 }; - try testing.expectEqual(@as(usize, 6 * 6 * 6), slabLen(dims)); -} - -test "idx at origin is 0" { - const dims: GridDims = .{ .nx = 4, .ny = 4, .nz = 4 }; - try testing.expectEqual(@as(usize, 0), idx(dims, 0, 0, 0)); -} - -test "idx step in i increments by 1" { - const dims: GridDims = .{ .nx = 4, .ny = 4, .nz = 4 }; - try testing.expectEqual(@as(usize, 1), idx(dims, 1, 0, 0)); -} - -test "idx step in j increments by nx1" { - const dims: GridDims = .{ .nx = 4, .ny = 4, .nz = 4 }; - try testing.expectEqual(@as(usize, 5), idx(dims, 0, 1, 0)); -} - -test "idx step in k increments by nx1 * ny1" { - const dims: GridDims = .{ .nx = 4, .ny = 4, .nz = 4 }; - try testing.expectEqual(@as(usize, 25), idx(dims, 0, 0, 1)); -} - -test "idx far corner of the live domain" { - const dims: GridDims = .{ .nx = 4, .ny = 4, .nz = 4 }; - try testing.expectEqual(@as(usize, (3 * 5 + 3) * 5 + 3), idx(dims, 3, 3, 3)); -} - -test "axisStride matches step deltas" { - const dims: GridDims = .{ .nx = 4, .ny = 4, .nz = 4 }; - try testing.expectEqual(@as(usize, 1), axisStride(dims, .x)); - try testing.expectEqual(@as(usize, 5), axisStride(dims, .y)); - try testing.expectEqual(@as(usize, 25), axisStride(dims, .z)); -} - -test "inDomain rejects halo cells past the live domain" { - const dims: GridDims = .{ .nx = 4, .ny = 4, .nz = 4 }; - try testing.expect(inDomain(dims, 0, 0, 0)); - try testing.expect(inDomain(dims, 3, 3, 3)); - try testing.expect(!inDomain(dims, 4, 0, 0)); - try testing.expect(!inDomain(dims, 0, 4, 0)); - try testing.expect(!inDomain(dims, 0, 0, 4)); -} - -test "all indices in the live domain are unique" { - const dims: GridDims = .{ .nx = 3, .ny = 3, .nz = 3 }; - var seen: [27]bool = .{false} ** 27; - var seen_count: usize = 0; - var k: u32 = 0; - while (k < dims.nz) : (k += 1) { - var j: u32 = 0; - while (j < dims.ny) : (j += 1) { - var i: u32 = 0; - while (i < dims.nx) : (i += 1) { - const flat = idx(dims, i, j, k); - const ord = @as(usize, k) * 9 + @as(usize, j) * 3 + @as(usize, i); - try testing.expect(flat < slabLen(dims)); - try testing.expect(!seen[ord]); - seen[ord] = true; - seen_count += 1; - } - } - } - try testing.expectEqual(@as(usize, 27), seen_count); -} - -test "six independent slabs do not overlap when allocated contiguously" { - const dims: GridDims = .{ .nx = 4, .ny = 4, .nz = 4 }; - const per_slab = slabLen(dims); - const total = per_slab * 6; - try testing.expectEqual(@as(usize, 125 * 6), total); -} - -test "halo over-allocation reserves the boundary cells" { - const dims: GridDims = .{ .nx = 4, .ny = 4, .nz = 4, .halo = 1 }; - const live_far = idx(dims, 3, 3, 3); - const halo_far = idx(dims, 4, 4, 4); - try testing.expect(halo_far > live_far); - try testing.expect(halo_far < slabLen(dims)); -}