jukebox
All repositories: gitoria
223.5 KB
// mpackdb DB engine — Zig port compatible with mpackdb v1.4.0 (MPackDB.js / IndexManager.js)// semantics. File-level compatible with the JS implementation (D12)://// <base>.mpack append-only records: [4-byte LE total size][msgpack map]// <base>.meta.json { nextId?, deleted:[offsets], version, schema? }// <base>.<field>.txt sorted index lines "key,offset,length\n" (a key with a newline, CR or leading quote is a JSON string; read from the right: mission 486)// <base>.idxstate.json { coveredBytes, fields: {field: coveredBytes}, idxFmt: 3, dataIno?, dataFp? }// <base>.lock lock file containing the holder's pid (O_EXCL protocol,// dead-pid takeover or staleLockTimeout ms)// <base>.flock (this engine only, ticket #176) the store lock: every open// handle holds a shared flock on it, compaction needs it// exclusive and is skipped without it; the last handle out// removes the file//// Ticket #176 additions the JS mpackdb ignores (it keeps unknown meta fields):// meta.json `dataFile` {ino, size, gen, deletedSum} and idxstate.json `dataIno`// name the data file they were written for, so tombstones and index offsets of// a replaced data file are never applied to the new one.//// Ticket 387 (a COPY of an open store must read back as the store): the inode alone// is not the identity of a data file, a hot tar or a restore gives the same bytes a// new inode. dataFile also carries `fp`, a fingerprint of the first `size` bytes// (hash of the first 4 KB + hash of the 4 KB before `size`), idxstate carries// `dataFp` for the first `coveredBytes`. Binding rule: same inode -> bound; another// inode and equal fingerprint -> bound (a copy); a file shorter than `size` or a// different fingerprint -> stale (another process's compaction); an old meta without// `fp` on another inode -> bound only if all its tombstones are plausible frame// starts. See applyMetaJson.//// Divergences from the JS implementation (documented in the 066 report):// - the in-memory index is the COMPLETE entry set (JS keeps on-disk + delta);// persist() writes the full set instead of read-merge-write. Sequential// cross-process use (close one side, open the other) behaves identically.// - string index keys sort bytewise (JS: String.localeCompare, ICU collation).// Equality lookups are unaffected; range ordering can differ for// mixed-case/accented keys.// - null field values are not indexed (JS indexes them under the key "null").// - a data file replaced while open (inode change, shrink, newer compaction// generation) is detected and re-indexed before the next read (#176).// - the JS mpackdb does not take the .flock store lock: its compaction can still// rewrite a file this engine has open (which then re-indexes), and this// engine's compaction cannot see a JS process that has the store open.// - a fresh `*id` table's first id is 1 (JS: 0) — ticket #4, see FIRST_ID.const std = @import("std");const linux = std.os.linux;const msgpack = @import("msgpack.zig");pub const PkType = enum(u8) { number = 0, uuid = 1, string = 2 };/// A `*id` table's first auto-increment id (ticket #4, the creator's ruling:/// "start at 1"). Only a table WITHOUT a stored counter starts here: a/// .meta.json that carries `nextId` — every existing table, including one the/// JS mpackdb wrote — keeps counting from it. The file format is unchanged;/// the JS mpackdb 1.0.7 starts a fresh table at 0, which is the one divergence.pub const FIRST_ID: f64 = 1;pub const IdxType = enum(u8) { lexical = 0, numeric = 1 };pub const Error = error{NoDbFile,NoPrimaryKey,/// mission 077 (074 GAP 10): a query named a field with no index. There is/// no index to binary-search and mpackdb does not silently full-scan, so/// the answer used to be an empty result — indistinguishable from "no such/// record". It is a mistake, and it says so now.NoSuchIndex,DuplicateKey,/// ticket #29: update()'s record must carry the primary key. Without it/// the old record was deleted, the new one written without a key, and the/// table left corrupt (fetch null, a unique index still finding it).RecordLacksPrimaryKey,LockTimeout,/// ticket #176: compaction found a frame it cannot vouch for (or a tombstone/// that names no frame) and rewrote nothing; last_error names the offset.CompactRefused,CorruptRecord,IoError,OutOfMemory,InvalidFormat,Truncated,MapTooLarge,};pub const Key = union(enum) {num: f64,str: []const u8,};pub const Entry = struct {key: Key,off: u64,len: u64,};const FieldIndex = struct {typ: IdxType,entries: std.ArrayList(Entry) = .empty, // sorted by (key, off)};pub const Loc = struct { off: u64, len: u64 };pub const Record = struct {value: msgpack.Value,off: u64,len: u64,};// =========================================================================// Low-level file IO (raw linux syscalls — plugins avoid std.Io plumbing)// =========================================================================const fio = struct {fn openz(alloc: std.mem.Allocator, path: []const u8, flags: linux.O, mode: u32) ?i32 {const path_z = alloc.dupeZ(u8, path) catch return null;defer alloc.free(path_z);const rc = linux.open(path_z, flags, mode);const fd: i32 = @bitCast(@as(u32, @truncate(rc)));if (fd < 0) return null;return fd;}fn openRead(alloc: std.mem.Allocator, path: []const u8) ?i32 {return openz(alloc, path, .{}, 0);}fn openAppend(alloc: std.mem.Allocator, path: []const u8) ?i32 {return openz(alloc, path, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, 0o644);}fn openTrunc(alloc: std.mem.Allocator, path: []const u8) ?i32 {return openz(alloc, path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, 0o644);}/// O_CREAT|O_EXCL — returns null when the file already exists.fn openExcl(alloc: std.mem.Allocator, path: []const u8) ?i32 {return openz(alloc, path, .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true }, 0o644);}fn close(fd: i32) void {_ = linux.close(fd);}fn fsync(fd: i32) bool {return linux.fsync(fd) == 0;}/// fsync the directory holding `path`, so a rename in it is durable.fn fsyncDir(alloc: std.mem.Allocator, path: []const u8) void {const dir = std.fs.path.dirname(path) orelse ".";const fd = openz(alloc, dir, .{ .DIRECTORY = true }, 0) orelse return;_ = linux.fsync(fd);close(fd);}fn writeAll(fd: i32, bytes: []const u8) bool {var written: usize = 0;while (written < bytes.len) {const rc = linux.write(fd, bytes.ptr + written, bytes.len - written);if (@as(isize, @bitCast(rc)) <= 0) return false;written += rc;}return true;}fn pread(fd: i32, buf: []u8, offset: u64) ?usize {var got: usize = 0;while (got < buf.len) {const rc = linux.pread(fd, buf.ptr + got, buf.len - got, @intCast(offset + got));const n: isize = @bitCast(rc);if (n < 0) return null;if (n == 0) break;got += @intCast(n);}return got;}fn readAll(alloc: std.mem.Allocator, path: []const u8) ?[]u8 {const fd = openRead(alloc, path) orelse return null;defer close(fd);// ONE read into a buffer of the file's size (mission 436): the 64 KB read + append// loop copied a 25 MB index file twice and regrew the list ~100 timesvar content: std.ArrayList(u8) = .empty;errdefer content.deinit(alloc);const hint: usize = if (fdStat(fd)) |st| @intCast(st.size) else 0;content.ensureTotalCapacityPrecise(alloc, hint + 1) catch return null;while (true) {if (content.capacity - content.items.len < 4096) content.ensureUnusedCapacity(alloc, 65536) catch return null;const spare = content.unusedCapacitySlice();const rc = linux.read(fd, spare.ptr, spare.len);if (@as(isize, @bitCast(rc)) <= 0) break;content.items.len += rc;}return content.toOwnedSlice(alloc) catch null;}fn fileSize(alloc: std.mem.Allocator, path: []const u8) ?u64 {const path_z = alloc.dupeZ(u8, path) catch return null;defer alloc.free(path_z);var stx: linux.Statx = undefined;const rc = linux.statx(linux.AT.FDCWD, path_z, 0, linux.STATX.BASIC_STATS, &stx);if (rc != 0) return null;return stx.size;}const Stat = struct { ino: u64, size: u64, mtime_ns: i128 = 0 };// flock(2) operationsconst LOCK_SH: i32 = 1;const LOCK_EX: i32 = 2;const LOCK_NB: i32 = 4;fn flock(fd: i32, op: i32) bool {return linux.flock(fd, op) == 0;}fn fdStat(fd: i32) ?Stat {var stx: linux.Statx = undefined;const rc = linux.statx(fd, "", 0x1000, linux.STATX.BASIC_STATS, &stx); // AT_EMPTY_PATHif (rc != 0) return null;return .{ .ino = stx.ino, .size = stx.size, .mtime_ns = @as(i128, stx.mtime.sec) * 1_000_000_000 + stx.mtime.nsec };}fn fdIno(fd: i32) ?u64 {return if (fdStat(fd)) |st| st.ino else null;}fn stat(alloc: std.mem.Allocator, path: []const u8) ?Stat {const path_z = alloc.dupeZ(u8, path) catch return null;defer alloc.free(path_z);var stx: linux.Statx = undefined;const rc = linux.statx(linux.AT.FDCWD, path_z, 0, linux.STATX.BASIC_STATS, &stx);if (rc != 0) return null;return .{ .ino = stx.ino, .size = stx.size, .mtime_ns = @as(i128, stx.mtime.sec) * 1_000_000_000 + stx.mtime.nsec };}fn mtimeMs(alloc: std.mem.Allocator, path: []const u8) ?i64 {const path_z = alloc.dupeZ(u8, path) catch return null;defer alloc.free(path_z);var stx: linux.Statx = undefined;const rc = linux.statx(linux.AT.FDCWD, path_z, 0, linux.STATX.BASIC_STATS, &stx);if (rc != 0) return null;return @as(i64, stx.mtime.sec) * 1000 + @divTrunc(@as(i64, stx.mtime.nsec), 1_000_000);}fn rename(alloc: std.mem.Allocator, old_path: []const u8, new_path: []const u8) bool {const old_z = alloc.dupeZ(u8, old_path) catch return false;defer alloc.free(old_z);const new_z = alloc.dupeZ(u8, new_path) catch return false;defer alloc.free(new_z);return linux.renameat(linux.AT.FDCWD, old_z, linux.AT.FDCWD, new_z) == 0;}fn unlink(alloc: std.mem.Allocator, path: []const u8) bool {const path_z = alloc.dupeZ(u8, path) catch return false;defer alloc.free(path_z);return linux.unlinkat(linux.AT.FDCWD, path_z, 0) == 0;}fn mkdirAll(alloc: std.mem.Allocator, dir_path: []const u8) void {if (dir_path.len == 0 or std.mem.eql(u8, dir_path, ".")) return;var i: usize = 1;while (i <= dir_path.len) : (i += 1) {if (i == dir_path.len or dir_path[i] == '/') {const part = alloc.dupeZ(u8, dir_path[0..i]) catch return;defer alloc.free(part);_ = linux.mkdirat(linux.AT.FDCWD, part, 0o755);}}}fn sleepMs(ms: u64) void {var req: linux.timespec = .{ .sec = @intCast(ms / 1000), .nsec = @intCast((ms % 1000) * 1_000_000) };var rem: linux.timespec = undefined;_ = linux.nanosleep(&req, &rem);}fn nowMs() i64 {var ts: linux.timespec = undefined;_ = linux.clock_gettime(linux.CLOCK.REALTIME, &ts);return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000);}};// =========================================================================// JS-compatible helpers// =========================================================================/// JS String(number): shortest digits with JS decimal/exponent thresholds.pub fn jsNumFmt(buf: []u8, v: f64) []const u8 {if (std.math.isNan(v)) return "NaN";if (std.math.isInf(v)) return if (v < 0) "-Infinity" else "Infinity";if (v == 0) return "0";var scratch: [64]u8 = undefined;const scientific = std.fmt.bufPrint(&scratch, "{e}", .{v}) catch unreachable;const ep = std.mem.indexOfScalar(u8, scientific, 'e').?;const exponent = std.fmt.parseInt(i32, scientific[ep + 1 ..], 10) catch unreachable;var digits: [32]u8 = undefined;var n: usize = 0;for (scientific[0..ep]) |c| {if (c >= '0' and c <= '9') {digits[n] = c;n += 1;}}while (n > 1 and digits[n - 1] == '0') n -= 1;var pos: usize = 0;if (v < 0) {buf[pos] = '-';pos += 1;}if (exponent >= 21 or exponent < -6) {buf[pos] = digits[0];pos += 1;if (n > 1) {buf[pos] = '.';pos += 1;@memcpy(buf[pos..][0 .. n - 1], digits[1..n]);pos += n - 1;}const tail = std.fmt.bufPrint(buf[pos..], "e{s}{d}", .{ if (exponent >= 0) "+" else "-", @abs(exponent) }) catch unreachable;return buf[0 .. pos + tail.len];}const point = exponent + 1;if (point <= 0) {buf[pos] = '0';buf[pos + 1] = '.';pos += 2;for (0..@intCast(-point)) |_| {buf[pos] = '0';pos += 1;}@memcpy(buf[pos..][0..n], digits[0..n]);pos += n;} else {const whole: usize = @intCast(point);for (0..@max(whole, n)) |i| {if (i == whole) {buf[pos] = '.';pos += 1;}buf[pos] = if (i < n) digits[i] else '0';pos += 1;}}return buf[0..pos];}/// Index line key text (mission 486). A key is written raw, as it always was, unless it holds/// a newline or a carriage return (it would split the line) or starts with a double quote (it/// would look like the quoted form); only then it is written as a JSON string.fn keyNeedsQuote(ks: []const u8) bool {if (ks.len > 0 and ks[0] == '"') return true;return std.mem.indexOfAny(u8, ks, "\n\r") != null;}fn quoteForFormat(format: u64, key: Key, text: []const u8) bool {return (format == 3 and key == .str) or keyNeedsQuote(text);}/// Append `ks` as a JSON string (the escapes of JSON.stringify).fn appendQuotedKey(out: *std.ArrayList(u8), a: std.mem.Allocator, ks: []const u8) !void {try out.append(a, '"');for (ks) |c| {switch (c) {'"' => try out.appendSlice(a, "\\\""),'\\' => try out.appendSlice(a, "\\\\"),'\n' => try out.appendSlice(a, "\\n"),'\r' => try out.appendSlice(a, "\\r"),'\t' => try out.appendSlice(a, "\\t"),8 => try out.appendSlice(a, "\\b"),12 => try out.appendSlice(a, "\\f"),0...7, 11, 14...31 => {var b: [6]u8 = undefined;try out.appendSlice(a, std.fmt.bufPrint(&b, "\\u{x:0>4}", .{c}) catch unreachable);},else => try out.append(a, c),}}try out.append(a, '"');}/// The key text of an index line: raw, or quoted when it has to be.fn appendKeyText(out: *std.ArrayList(u8), a: std.mem.Allocator, ks: []const u8) !void {if (keyNeedsQuote(ks)) try appendQuotedKey(out, a, ks) else try out.appendSlice(a, ks);}/// Decode the JSON string that starts at line[0] (a double quote). Returns the key and the/// index just after the closing quote, or null when it is no valid JSON string.fn decodeQuotedKey(a: std.mem.Allocator, line: []const u8) ?struct { key: []const u8, end: usize } {var i: usize = 1;var plain = true;while (i < line.len and line[i] != '"') : (i += 1) {if (line[i] == '\\') {plain = false;i += 1; // the escaped character is skipped here, decoded below}}if (i >= line.len) return null;if (plain) return .{ .key = line[1..i], .end = i + 1 };var out: std.ArrayList(u8) = .empty;var j: usize = 1;while (j < i) {const c = line[j];if (c != '\\') {out.append(a, c) catch return null;j += 1;continue;}j += 1;if (j >= i) return null;const e = line[j];j += 1;switch (e) {'"', '\\', '/' => out.append(a, e) catch return null,'n' => out.append(a, '\n') catch return null,'r' => out.append(a, '\r') catch return null,'t' => out.append(a, '\t') catch return null,'b' => out.append(a, 8) catch return null,'f' => out.append(a, 12) catch return null,'u' => {if (j + 4 > i) return null;var cp: u21 = std.fmt.parseInt(u16, line[j .. j + 4], 16) catch return null;j += 4;if (cp >= 0xD800 and cp < 0xDC00 and j + 6 <= i and line[j] == '\\' and line[j + 1] == 'u') {const lo = std.fmt.parseInt(u16, line[j + 2 .. j + 6], 16) catch return null;if (lo >= 0xDC00 and lo < 0xE000) {cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);j += 6;}}var ub: [4]u8 = undefined;const n = std.unicode.utf8Encode(cp, &ub) catch blk: {// a lone surrogate has no UTF-8 form: the replacement characterbreak :blk std.unicode.utf8Encode(0xFFFD, &ub) catch return null;};out.appendSlice(a, ub[0..n]) catch return null;},else => return null,}}return .{ .key = out.items, .end = i + 1 };}/// JS numericText grammar followed by Number(), preserving fractional keys./// Returns null for NaN.fn numericText(s: []const u8) ?f64 {if (std.mem.eql(u8, s, "NaN")) return std.math.nan(f64);if (std.mem.eql(u8, s, "Infinity") or std.mem.eql(u8, s, "+Infinity")) return std.math.inf(f64);if (std.mem.eql(u8, s, "-Infinity")) return -std.math.inf(f64);var i: usize = 0;if (i < s.len and (s[i] == '+' or s[i] == '-')) i += 1;var digits: usize = 0;while (i < s.len and std.ascii.isDigit(s[i])) : (i += 1) {digits += 1;}if (i < s.len and s[i] == '.') {i += 1;while (i < s.len and std.ascii.isDigit(s[i])) : (i += 1) {digits += 1;}}if (digits == 0) return null;if (i < s.len and (s[i] == 'e' or s[i] == 'E')) {i += 1;if (i < s.len and (s[i] == '+' or s[i] == '-')) i += 1;const start = i;while (i < s.len and std.ascii.isDigit(s[i])) : (i += 1) {}if (i == start) return null;}if (i != s.len) return null;return std.fmt.parseFloat(f64, s) catch null;}/// _compareKeys: numbers numerically; otherwise stringified byte compare/// (JS uses localeCompare — see divergence note in the header).pub fn cmpKeys(a: Key, b: Key) i32 {if (a == .num and b == .str) return -1;if (a == .str and b == .num) return 1;if (a == .num and b == .num) {if (std.math.isNan(a.num)) return if (std.math.isNan(b.num)) 0 else 1;if (std.math.isNan(b.num)) return -1;if (a.num < b.num) return -1;if (a.num > b.num) return 1;return 0;}var buf_a: [32]u8 = undefined;var buf_b: [32]u8 = undefined;const sa = if (a == .str) a.str else jsNumFmt(&buf_a, a.num);const sb = if (b == .str) b.str else jsNumFmt(&buf_b, b.num);return switch (std.mem.order(u8, sa, sb)) {.lt => -1,.eq => 0,.gt => 1,};}fn entryLess(_: void, a: Entry, b: Entry) bool {const c = cmpKeys(a.key, b.key);if (c != 0) return c < 0;return a.off < b.off;}/// Sorts `items` by entryLess. Comparing two string keys follows two pointers into memory the/// sort has long left (a cache miss each, ~20 per entry): for a list of string keys the sort/// runs over (first 16 key bytes, index) records instead and compares the whole keys only for/// equal prefixes; the entries are then moved once (mission 436: 1 M ids, 3.4 s -> see report).fn sortEntries(alloc: std.mem.Allocator, items: []Entry) void {const plain = items.len < 512;var all_str = !plain;if (all_str) {for (items) |e| {if (e.key != .str) {all_str = false;break;}}}if (!all_str) return std.sort.pdq(Entry, items, {}, entryLess);const P = struct {p0: u64,p1: u64,i: u32,};if (items.len >= std.math.maxInt(u32)) return std.sort.pdq(Entry, items, {}, entryLess);const ps = alloc.alloc(P, items.len) catch return std.sort.pdq(Entry, items, {}, entryLess);defer alloc.free(ps);const copy = alloc.dupe(Entry, items) catch return std.sort.pdq(Entry, items, {}, entryLess);defer alloc.free(copy);for (copy, 0..) |e, i| {var b: [16]u8 = @splat(0);const k = e.key.str;@memcpy(b[0..@min(k.len, 16)], k[0..@min(k.len, 16)]);ps[i] = .{ .p0 = std.mem.readInt(u64, b[0..8], .big), .p1 = std.mem.readInt(u64, b[8..16], .big), .i = @intCast(i) };}const Ctx = struct {es: []const Entry,fn less(c: @This(), a: P, b: P) bool {if (a.p0 != b.p0) return a.p0 < b.p0;if (a.p1 != b.p1) return a.p1 < b.p1;const ea = c.es[a.i];const eb = c.es[b.i];return switch (std.mem.order(u8, ea.key.str, eb.key.str)) {.lt => true,.gt => false,.eq => ea.off < eb.off,};}};std.sort.pdq(P, ps, Ctx{ .es = copy }, Ctx.less);for (ps, 0..) |p, k| items[k] = copy[p.i];}/// mpack.js uuid(): 9-char base36 ms timestamp (padStart '0') + 3 base36 chars.pub fn genUuid(buf: *[12]u8) []const u8 {const digits = "0123456789abcdefghijklmnopqrstuvwxyz";const t: u64 = @intCast(fio.nowMs());var tmp: [16]u8 = undefined;var n: usize = 0;var v = t;while (v > 0) : (v /= 36) {tmp[n] = digits[@intCast(v % 36)];n += 1;}var i: usize = 0;while (i < 9) : (i += 1) {buf[8 - i] = if (i < n) tmp[i] else '0';}if (!rng_init) {var ts: linux.timespec = undefined;_ = linux.clock_gettime(linux.CLOCK.MONOTONIC, &ts);rng = std.Random.DefaultPrng.init(@bitCast(@as(i64, ts.sec) *% 1_000_000_000 +% ts.nsec));rng_init = true;}var r = rng.random();for (0..3) |j| {buf[9 + j] = digits[r.uintLessThan(u8, 36)];}return buf[0..12];}var rng: std.Random.DefaultPrng = .{ .s = undefined };var rng_init: bool = false;// =========================================================================// The database// =========================================================================pub const OpenOptions = struct {primary_key: ?[]const u8 = null, // with */@/! prefixes, like the JS APIindexes: []const []const u8 = &.{}, // with prefixescompact: bool = true,stale_lock_timeout_ms: i64 = 30000,debug: bool = false,};/// The identity of a table on disk (ticket #110): dirname + basename with any/// extension stripped, exactly the computation `Db.open` uses to turn a given/// path into `<base>.mpack` — so two spellings of the same file (`x.db`, `x`)/// share one key. The plugin ABI layer (mpackdb.zig) keys its process-wide/// handle registry on this, so a table opened twice in one process — from any/// module instance or realm — shares the one live `Db` instead of each open/// racing the other's file state.pub fn tableKey(alloc: std.mem.Allocator, db_file: []const u8) Error![]u8 {const dir = std.fs.path.dirname(db_file) orelse ".";var base = std.fs.path.basename(db_file);if (std.mem.lastIndexOfScalar(u8, base, '.')) |dot| {if (dot > 0) base = base[0..dot];}return std.fmt.allocPrint(alloc, "{s}/{s}", .{ dir, base }) catch Error.OutOfMemory;}/// The set of tombstoned offsets, shared and reference-counted (mission 393). The Db/// keeps ONE of it, built lazily from `deleted` and kept in step with every delete,/// so a lookup / range / scan no longer rebuilds an N-entry hash set per call. A scan/// that streams (a cursor) holds a reference to the set it started with: a later/// delete copies the set first (copy on write) and a compaction / foreign meta/// drops the Db's reference, so the cursor's view of the tombstones never changes.pub const DelSet = struct {map: std.AutoHashMapUnmanaged(u64, void) = .empty,refs: u32 = 1,alloc: std.mem.Allocator,pub fn release(self: *DelSet) void {self.refs -= 1;if (self.refs == 0) {const a = self.alloc;self.map.deinit(a);a.destroy(self);}}};/// One open data file, shared by the Db and the cursors that started on it (fd403).pub const DataGen = struct {fd: i32,refs: std.atomic.Value(u32),gpa: std.mem.Allocator,fn create(gpa: std.mem.Allocator, fd: i32) ?*DataGen {const g = gpa.create(DataGen) catch return null;g.* = .{ .fd = fd, .refs = std.atomic.Value(u32).init(1), .gpa = gpa };return g;}pub fn retain(self: *DataGen) *DataGen {_ = self.refs.fetchAdd(1, .monotonic);return self;}pub fn release(self: *DataGen) void {if (self.refs.fetchSub(1, .acq_rel) == 1) {fio.close(self.fd);self.gpa.destroy(self);}}};pub const Db = struct {arena_state: std.heap.ArenaAllocator,alloc: std.mem.Allocator, // arena — freed wholesale on close// THE BUFFERS OF ONE OPERATION ARE NOT THE HANDLE'S (hybriel#126): the meta read// back and rendered anew, the index files, the paths. On the arena they stayed for// the handle's life, and the meta grows with every tombstone, so each update leaked// more than the last (notes: 2000 updates of one note, +100 MB). They are freed now.tmp: std.mem.Allocator,// pathsdata_path: []const u8,meta_path: []const u8,lock_path: []const u8,idxstate_path: []const u8,flock_path: []const u8 = "",/// THE STORE LOCK (ticket #176): every open handle holds a shared flock on/// `<base>.flock` for its whole life; a compaction needs it exclusive and/// skips when it cannot have it at once — another process has the store open,/// and rewriting the file under it is what lost the tracker its reads.store_fd: i32 = -1,// Held until unlink on release; also serializes stale-file inspection/removal.lock_fd: i32 = -1,// schemapk: ?[]const u8 = null,pk_type: PkType = .string,index_fields: std.ArrayList([]const u8) = .empty, // pk first (when set), like JSunique_fields: std.ArrayList([]const u8) = .empty,idx: std.StringArrayHashMapUnmanaged(FieldIndex) = .empty,// metanext_id: f64 = FIRST_ID,deleted: std.ArrayList(u64) = .empty,/// lazily built set of `deleted` (mission 393); null = not built / invalidateddel_cache: ?*DelSet = null,/// an index entry named a place that is no frame of its size (a stale persisted index):/// the next refresh() rebuilds every index from the data file (mission 393)index_bad: bool = false,index_retry: bool = false,version: u64 = 0,// THE META NAMES ITS DATA FILE (ticket #176): `dataFile` in .meta.json is the// inode and size of the data file it was written for, the compaction// generation, and a checksum of its own `deleted` list. A meta whose data file// was replaced under it (a crash between the rename and the meta write) has// tombstones that point into the WRONG file — they are dropped, not applied.// The checksum tells our dataFile from one another writer carried along: the// JS mpackdb rewrites the meta as `{...meta}` and keeps fields it does not// know, so a `deleted` list it changed no longer matches the sum, and such a// meta is taken as it is (as before #176).bind_known: bool = false, // the meta on disk carries a dataFile that is ours and truebind_ino: u64 = 0,bind_size: u64 = 0,bind_fp: [16]u8 = undefined, // content fingerprint of the data file's first `bind_size` bytesbind_fp_len: u8 = 0, // 0 = none known (an old meta whose data file was not read)data_gen: u64 = 0,meta_stale: bool = false, // the loaded meta belonged to another data fileidx_bind_known: bool = false, // the idxstate on disk names the data file's inode// the data file this handle's offsets are into (ticket #176): its inode and// the compaction generation; refresh() compares them on every operationseen_ino: u64 = 0,// THE FILE THE OFFSETS ARE INTO, held open (ticket #176): every read and scan// goes through it, never through the path — a rewrite renamed in between a// lookup and its read (the tracker parsed 1.4 MB of meta between the two)// then still reads the file the offsets belong to, and the next refresh()// moves the handle to the new one.data_fd: i32 = -1,// fd403: the refcounted holder of data_fd. A streaming cursor takes a reference to the// generation it started on instead of dup()ing the fd (a dup per query held thousands of// fds until the GC finalized abandoned cursors: > 1024 at the tracker's boot). The fd is// closed when the Db has moved on (compaction, close) AND the last cursor is gone.fd_gen: ?*DataGen = null,// The meta file as THIS handle last read or wrote it (ticket #188): it is only ever// replaced by tmp + rename, so a write changes its inode; refresh() stats it and// skips the read + parse of a (1.4 MB on the tracker) meta that is unchanged.meta_seen: ?fio.Stat = null,meta_reads: u64 = 0, // reads of the meta file by loadMeta/refresh (the test counts them)bulk_index: bool = false, // indexInsertEntry appends (a sorted pass follows): rebuild / long catch-up/// keys of a rebuild live here until the sort has put the entries in order; then they are/// copied side by side in that order (a rebuilt index is read in sorted order, again and/// again: written, compared, searched) and this arena is freed (mission 436)bulk_keys: ?*std.heap.ArenaAllocator = null,covered_bytes: u64 = 0,compact_on_open: bool = true,stale_lock_timeout_ms: i64 = 30000,debug: bool = false,// last DuplicateKey detail for the plugin surfacelast_error_buf: [256]u8 = undefined,last_error: []const u8 = "",pub fn open(gpa: std.mem.Allocator, db_file: []const u8, opts: OpenOptions) Error!*Db {if (db_file.len == 0) return Error.NoDbFile;const self = gpa.create(Db) catch return Error.OutOfMemory;self.* = .{.arena_state = std.heap.ArenaAllocator.init(gpa),.alloc = undefined,.tmp = gpa,.data_path = undefined,.meta_path = undefined,.lock_path = undefined,.idxstate_path = undefined,};self.alloc = self.arena_state.allocator();errdefer {self.arena_state.deinit();gpa.destroy(self);}const a = self.alloc;self.compact_on_open = opts.compact;self.stale_lock_timeout_ms = opts.stale_lock_timeout_ms;self.debug = opts.debug;// dirname / basename (extension stripped, like JS basename(f, extname(f)))const dir = std.fs.path.dirname(db_file) orelse ".";var base = std.fs.path.basename(db_file);if (std.mem.lastIndexOfScalar(u8, base, '.')) |dot| {if (dot > 0) base = base[0..dot];}fio.mkdirAll(a, dir);self.data_path = std.fmt.allocPrint(a, "{s}/{s}.mpack", .{ dir, base }) catch return Error.OutOfMemory;self.meta_path = std.fmt.allocPrint(a, "{s}/{s}.meta.json", .{ dir, base }) catch return Error.OutOfMemory;self.lock_path = std.fmt.allocPrint(a, "{s}/{s}.lock", .{ dir, base }) catch return Error.OutOfMemory;self.idxstate_path = std.fmt.allocPrint(a, "{s}/{s}.idxstate.json", .{ dir, base }) catch return Error.OutOfMemory;self.flock_path = std.fmt.allocPrint(a, "{s}/{s}.flock", .{ dir, base }) catch return Error.OutOfMemory;try self.openStoreLock();errdefer self.closeStoreLock();// ---- parse primary key ----if (opts.primary_key) |pk_raw| {if (pk_raw.len > 0) {if (pk_raw[0] == '*') {self.pk = a.dupe(u8, pk_raw[1..]) catch return Error.OutOfMemory;self.pk_type = .number;} else if (pk_raw[0] == '@') {self.pk = a.dupe(u8, pk_raw[1..]) catch return Error.OutOfMemory;self.pk_type = .uuid;} else {self.pk = a.dupe(u8, pk_raw) catch return Error.OutOfMemory;self.pk_type = .string;}}}if (self.pk) |p| self.unique_fields.append(a, p) catch return Error.OutOfMemory;// ---- parse indexes (pk first, then configured; dedupe) ----if (self.pk) |p| {self.index_fields.append(a, p) catch return Error.OutOfMemory;const t: IdxType = if (self.pk_type == .number) .numeric else .lexical;self.idx.put(a, p, .{ .typ = t }) catch return Error.OutOfMemory;}for (opts.indexes) |raw| {var clean = raw;var is_unique = false;if (clean.len > 0 and clean[0] == '!') {is_unique = true;clean = clean[1..];}var typ: IdxType = .lexical;if (clean.len > 0 and clean[0] == '*') {typ = .numeric;clean = clean[1..];} else if (clean.len > 0 and clean[0] == '@') {clean = clean[1..];}if (self.idx.contains(clean)) continue;const owned = a.dupe(u8, clean) catch return Error.OutOfMemory;self.index_fields.append(a, owned) catch return Error.OutOfMemory;self.idx.put(a, owned, .{ .typ = typ }) catch return Error.OutOfMemory;if (is_unique) self.unique_fields.append(a, owned) catch return Error.OutOfMemory;}// ---- load meta ----self.loadMeta();// ---- compact on init (JS default; also creates an empty data file) ----// AN OPEN WITH NOTHING TO CHANGE WRITES NOTHING (ticket #21): a store// with no tombstones has nothing to compact, and rewriting it anyway// made opening a backup change it.var did_compact = false;const nothing_to_compact = self.deleted.items.len == 0 andfio.fileSize(self.tmp, self.data_path) != null;if (self.compact_on_open and !nothing_to_compact) {try self.acquireLock();const cr = if (self.tryExclusive()) blk: {defer self.backToShared();break :blk self.compactLocked();} else self.skipCompaction();self.releaseLock();// A REFUSED compaction does not fail the open (ticket #176): nothing// was rewritten, the store is as it was, and it stays readable; the// refusal is on stderr and in last_error.if (cr) |ran| {did_compact = ran;} else |e| {if (e != Error.CompactRefused) return e;}}self.adoptDataFile();errdefer self.dropDataFile();// ---- persist schema into meta (JS: init-schema under lock).// compactLocked already wrote meta (with schema); skip the extra bump.// A meta found to belong to another data file is replaced at once, so a// stale one never outlives the open that saw it (ticket #176).if (!did_compact and (self.meta_stale or ((self.pk != null or self.index_fields.items.len > 0) and!self.metaOnDiskIsCurrent()))){try self.acquireLock();// Opening read metadata before taking the mutation lock. Another// writer may have replaced rows since then: never publish our old// tombstones/version over its committed state. Indexes initialize below,// so reload metadata alone rather than catching up empty indexes.self.loadMeta();const mr = if (self.meta_stale or !self.metaOnDiskIsCurrent()) self.persistMetaLocked() else {};self.releaseLock();try mr;}// ---- indexes (JS: (re)build under the lock; force after compaction) ----if (self.index_fields.items.len > 0) {try self.acquireLock();const ir = self.initIndexes(did_compact);self.releaseLock();try ir;}return self;}pub fn close(self: *Db) void {// persist indexes + idxstate (JS: IndexManager.close → persist under lock)if (self.index_fields.items.len > 0) {if (self.acquireLock()) {// MISSION 395 (#203): the index in memory is of the data file this handle holds. Another// process (the JS mpackdb, a build before #176: none takes the store lock) may have// rewritten it since; persisting before looking wrote that old generation's offsets// as the index files — beside an idxstate that named the NEW file.self.refresh();self.persistIndexesLocked() catch {};self.releaseLock();} else |_| {}}self.dropDataFile();self.delCacheDrop();self.closeStoreLock();const gpa = self.arena_state.child_allocator;self.arena_state.deinit();gpa.destroy(self);}fn dbg(self: *Db, comptime fmt: []const u8, args: anytype) void {if (self.debug) std.debug.print("[mpackdb] " ++ fmt ++ "\n", args);}// =====================================================================// Locking (JS _acquireFileLock protocol)// =====================================================================/// Inspect only while holding this inode's flock. Recheck the path after/// taking it: a competing restarter may already have replaced the file.fn removeStaleLock(self: *Db) bool {const fd = fio.openz(self.tmp, self.lock_path, .{ .CLOEXEC = true }, 0) orelse return false;defer fio.close(fd);if (!fio.flock(fd, fio.LOCK_EX | fio.LOCK_NB)) return false;const held = fio.fdStat(fd) orelse return false;const at_path = fio.stat(self.tmp, self.lock_path) orelse return false;if (held.ino != at_path.ino) return false;var buf: [32]u8 = undefined;const n = fio.pread(fd, &buf, 0) orelse 0;const pid = std.fmt.parseInt(i32, std.mem.trim(u8, buf[0..n], " \t\r\n"), 10) catch 0;// Positive local PIDs only. EPERM means alive; errors other than ESRCH// cannot establish death. The legacy age rule remains the fallback.const dead = pid > 0 and (pid == linux.getpid() orlinux.errno(linux.kill(pid, @enumFromInt(0))) == .SRCH);const old = self.stale_lock_timeout_ms > 0 andfio.nowMs() - @divTrunc(held.mtime_ns, 1_000_000) > self.stale_lock_timeout_ms;return (dead or old) and fio.unlink(self.tmp, self.lock_path);}fn acquireLock(self: *Db) Error!void {var retries: u32 = 0;while (true) {if (fio.openz(self.tmp, self.lock_path, .{.ACCMODE = .WRONLY,.CREAT = true,.EXCL = true,.CLOEXEC = true,}, 0o644)) |fd| {// Empty fresh files are not reclaimed while we publish the pid.// A taker can briefly flock this inode first; verify its path too.if (!fio.flock(fd, fio.LOCK_EX)) {fio.close(fd);return Error.IoError;}const held = fio.fdIno(fd);const at_path = fio.stat(self.tmp, self.lock_path);if (held == null or at_path == null or held.? != at_path.?.ino) {fio.close(fd);continue;}var pid_buf: [16]u8 = undefined;const pid_s = std.fmt.bufPrint(&pid_buf, "{d}", .{linux.getpid()}) catch unreachable;if (!fio.writeAll(fd, pid_s)) {_ = fio.unlink(self.tmp, self.lock_path);fio.close(fd);return Error.IoError;}self.lock_fd = fd;return;}if (self.removeStaleLock()) continue;if (retries > 480) return Error.LockTimeout; // ~12s at 25msfio.sleepMs(25);retries += 1;}}fn releaseLock(self: *Db) void {if (self.lock_fd < 0) return;_ = fio.unlink(self.tmp, self.lock_path);fio.close(self.lock_fd);self.lock_fd = -1;}/// Take the shared store lock. The lock file is unlinked by the last handle/// to close (under the exclusive lock), so a lock taken on a file that is no/// longer the one at the path is let go and taken anew.fn openStoreLock(self: *Db) Error!void {var tries: usize = 0;while (tries < 1000) : (tries += 1) {const fd = fio.openz(self.tmp, self.flock_path, .{ .ACCMODE = .RDWR, .CREAT = true, .CLOEXEC = true }, 0o644) orelse return Error.IoError;if (!fio.flock(fd, fio.LOCK_SH)) {fio.close(fd);return Error.IoError;}const held = fio.fdIno(fd);const at_path = fio.stat(self.tmp, self.flock_path);if (held != null and at_path != null and held.? == at_path.?.ino) {self.store_fd = fd;return;}fio.close(fd);}return Error.LockTimeout;}fn closeStoreLock(self: *Db) void {if (self.store_fd < 0) return;// the last one out removes the lock file — only while no one else holds itif (fio.flock(self.store_fd, fio.LOCK_EX | fio.LOCK_NB)) _ = fio.unlink(self.tmp, self.flock_path);fio.close(self.store_fd);self.store_fd = -1;}/// Exclusive, without waiting: true when no other handle (in any process)/// holds the store.fn tryExclusive(self: *Db) bool {if (self.store_fd < 0) return false;if (fio.flock(self.store_fd, fio.LOCK_EX | fio.LOCK_NB)) return true;// a failed conversion may have given up the shared lock: take it again_ = fio.flock(self.store_fd, fio.LOCK_SH);return false;}fn backToShared(self: *Db) void {if (self.store_fd >= 0) _ = fio.flock(self.store_fd, fio.LOCK_SH);}fn skipCompaction(self: *Db) Error!bool {self.last_error = "compaction skipped: the store is open in another process";self.dbg("{s}: {s}", .{ self.data_path, self.last_error });return false;}// =====================================================================// Meta (.meta.json)// =====================================================================fn appendFmt(self: *Db, list: *std.ArrayList(u8), comptime fmt: []const u8, args: anytype) Error!void {// a short piece is formatted on the stack (mission 436: one heap allocation per// tombstone / index line made rendering a 3 MB meta cost more than parsing it)var sbuf: [256]u8 = undefined;if (std.fmt.bufPrint(&sbuf, fmt, args)) |piece| {list.appendSlice(self.tmp, piece) catch return Error.OutOfMemory;return;} else |_| {}const s = std.fmt.allocPrint(self.tmp, fmt, args) catch return Error.OutOfMemory;defer self.tmp.free(s);list.appendSlice(self.tmp, s) catch return Error.OutOfMemory;}fn loadMeta(self: *Db) void {// stat BEFORE the read: a write racing in between then shows as a change next timeself.meta_seen = fio.stat(self.tmp, self.meta_path);self.meta_reads += 1;const content = fio.readAll(self.tmp, self.meta_path) orelse return;defer self.tmp.free(content);self.applyMetaJson(content);}/// What applyMetaJson needs of the meta's `dataFile` object.const DataFileMeta = struct {ino: ?u64 = null,size: ?u64 = null,gen: ?u64 = null,sum: ?[]const u8 = null, // deletedSum when it is a stringfp_present: bool = false,fp: ?[]const u8 = null, // fp when it is a string};/// A JSON number token the way std.json.Value would hold it: an integer, or a float.const JNum = union(enum) { int: i64, float: f64 };fn jnum(text: []const u8) ?JNum {if (std.mem.indexOfAny(u8, text, ".eE") == null) {return .{ .int = std.fmt.parseInt(i64, text, 10) catch return null };}return .{ .float = std.fmt.parseFloat(f64, text) catch return null };}/// MISSION 436: the meta of a big table is megabytes (the tracker's shows: 308 K tombstones);/// std.json.Value built a tagged value per offset, then freed them again. This walks the/// tokens and keeps only what applyMetaJson reads. It returns false — having changed/// nothing — for anything it does not recognise or any malformed text, and the Value/// path below then decides, exactly as before.fn applyMetaFast(self: *Db, content: []const u8) bool {var sc = std.json.Scanner.initCompleteInput(self.tmp, content);defer sc.deinit();var del: std.ArrayList(u64) = .empty;defer del.deinit(self.tmp);var next_id: f64 = FIRST_ID;var version: u64 = 0;var df: ?DataFileMeta = null;const t0 = sc.next() catch return false;if (t0 != .object_begin) return false;while (true) {const kt = sc.next() catch return false;const key = switch (kt) {.object_end => break,.string => |k| k,else => return false,};if (std.mem.eql(u8, key, "nextId")) {const t = sc.next() catch return false;next_id = switch (t) {.number => |n| switch (jnum(n) orelse return false) {.int => |i| @floatFromInt(i),.float => |f| f,},.string, .true, .false, .null => FIRST_ID,else => return false,};} else if (std.mem.eql(u8, key, "version")) {const t = sc.next() catch return false;version = switch (t) {.number => |n| switch (jnum(n) orelse return false) {.int => |i| @intCast(@max(i, 0)),.float => 0,},.string, .true, .false, .null => 0,else => return false,};} else if (std.mem.eql(u8, key, "deleted")) {del.clearRetainingCapacity();const t = sc.next() catch return false;switch (t) {.array_begin => while (true) {const e = sc.next() catch return false;switch (e) {.array_end => break,.number => |n| {const off: u64 = switch (jnum(n) orelse return false) {.int => |i| @intCast(@max(i, 0)),.float => |f| @intFromFloat(@max(f, 0)),};del.append(self.tmp, off) catch return false;},.string, .true, .false, .null => {},else => return false,}},.string, .number, .true, .false, .null => {},else => return false,}} else if (std.mem.eql(u8, key, "dataFile")) {df = null;const t = sc.next() catch return false;switch (t) {.object_begin => {var d = DataFileMeta{};while (true) {const ik = sc.next() catch return false;const k2 = switch (ik) {.object_end => break,.string => |k| k,else => return false,};const v = sc.next() catch return false;const is_u64: ?u64 = switch (v) {.number => |n| switch (jnum(n) orelse return false) {.int => |i| if (i < 0) null else @intCast(i),.float => null,},.string, .true, .false, .null => null,else => return false,};const str: ?[]const u8 = if (v == .string) v.string else null;if (std.mem.eql(u8, k2, "ino")) {d.ino = is_u64;} else if (std.mem.eql(u8, k2, "size")) {d.size = is_u64;} else if (std.mem.eql(u8, k2, "gen")) {d.gen = is_u64;} else if (std.mem.eql(u8, k2, "deletedSum")) {d.sum = str;} else if (std.mem.eql(u8, k2, "fp")) {d.fp_present = true;d.fp = str;}}df = d;},.string, .number, .true, .false, .null => {},else => return false,}} else {sc.skipValue() catch return false;}}const te = sc.next() catch return false;if (te != .end_of_document) return false;// parsed whole: applyself.next_id = next_id;self.deleted.clearRetainingCapacity();self.delCacheDrop();self.version = version;self.deleted.appendSlice(self.alloc, del.items) catch {};self.bind_known = false;self.meta_stale = false;if (df) |d| self.applyBinding(d);return true;}fn applyMetaJson(self: *Db, content: []const u8) void {if (self.applyMetaFast(content)) return;self.applyMetaSlow(content);}/// The meta through std.json.Value (the reading before mission 436; also the fallback).fn applyMetaSlow(self: *Db, content: []const u8) void {const parsed = std.json.parseFromSlice(std.json.Value, self.tmp, content, .{}) catch return;defer parsed.deinit();if (parsed.value != .object) return;const obj = parsed.value.object;self.next_id = FIRST_ID;self.deleted.clearRetainingCapacity();self.delCacheDrop();self.version = 0;if (obj.get("nextId")) |v| {self.next_id = switch (v) {.integer => |i| @floatFromInt(i),.float => |f| f,else => FIRST_ID,};}if (obj.get("version")) |v| {if (v == .integer) self.version = @intCast(@max(v.integer, 0));}if (obj.get("deleted")) |v| {if (v == .array) {for (v.array.items) |it| {const off: u64 = switch (it) {.integer => |i| @intCast(@max(i, 0)),.float => |f| @intFromFloat(@max(f, 0)),else => continue,};self.deleted.append(self.alloc, off) catch {};}}}self.bind_known = false;self.meta_stale = false;const df_v = obj.get("dataFile") orelse return;if (df_v != .object) return;const df = df_v.object;var d = DataFileMeta{ .ino = jsonU64(df.get("ino")), .size = jsonU64(df.get("size")), .gen = jsonU64(df.get("gen")) };if (df.get("deletedSum")) |sv| {if (sv == .string) d.sum = sv.string;}if (df.get("fp")) |fv| {d.fp_present = true;if (fv == .string) d.fp = fv.string;}self.applyBinding(d);}/// The tail of applyMetaJson: does the meta's `dataFile` bind it to the data file at the path?fn applyBinding(self: *Db, df: DataFileMeta) void {const ino = df.ino orelse return;const size = df.size orelse return;if (df.gen) |g| self.data_gen = @max(self.data_gen, g);const sum = df.sum orelse return;var sum_buf: [16]u8 = undefined;if (!std.mem.eql(u8, sum, self.deletedSum(&sum_buf))) return; // another writer'sconst cur = fio.stat(self.tmp, self.data_path);// THE BINDING RULE (ticket 387, after #176): the inode is the fast path, the// content is the proof. A byte COPY of an open store (a hot tar, a deploy// backup, a restore) has a new inode but the same bytes, and its meta must// still apply — its tombstones and newer versions are the store's truth.// - same inode, file at least `size` bytes: bound (as in #176).// - file shorter than `size`, or gone: stale (a different file).// - another inode, meta carries `fp` (fingerprint of the first and last// 4 KB of the first `size` bytes): bound if the file's fingerprint over// that range equals it (the same content, copied or restored); a data// file a compaction replaced differs in content, so it stays stale.// - another inode, an OLD meta without `fp`: bound only if every tombstone// offset is a plausible frame start in the file (size > 4, fits, and the// next frame's header is plausible or EOF). Else stale.var bound = false;var fp_buf: [16]u8 = undefined;var have_fp: ?[]const u8 = null;if (cur) |c| {if (c.size >= size) {if (c.ino == ino) {bound = true;} else if (df.fp_present) {if (df.fp) |fv| {have_fp = self.dataFingerprint(size, &fp_buf);bound = have_fp != null and std.mem.eql(u8, have_fp.?, fv);}} else {bound = self.tombstonesAreFrameStarts(c.size);}}} else bound = size == 0;if (!bound) {if (self.deleted.items.len > 0) {std.debug.print("mpackdb: {s}: the meta belongs to another data file (inode {d}, {d} bytes); its {d} tombstones are not applied\n", .{ self.data_path, ino, size, self.deleted.items.len });}self.deleted.clearRetainingCapacity();self.delCacheDrop();self.meta_stale = true;return;}self.bind_known = true;self.bind_ino = if (cur) |c| c.ino else ino; // a copy: this file's inode from now onself.bind_size = size;self.bind_fp_len = 0;if (have_fp == null) have_fp = self.dataFingerprint(size, &fp_buf);if (have_fp) |f| {@memcpy(self.bind_fp[0..f.len], f);self.bind_fp_len = @intCast(f.len);}}/// Fingerprint (16 hex chars) of the first `n` bytes of the data file: a hash of/// its first 4 KB and one of the 4 KB before `n`. Appends past `n` do not change/// it; a replaced (compacted) file, with other records at those places, does.fn dataFingerprint(self: *Db, n: u64, buf: *[16]u8) ?[]const u8 {const fd = fio.openRead(self.tmp, self.data_path) orelse return null;defer fio.close(fd);return fingerprintFd(fd, n, buf);}fn fingerprintFd(fd: i32, n: u64, buf: *[16]u8) ?[]const u8 {var h = std.hash.Wyhash.init(387);var blk: [4096]u8 = undefined;const head: usize = @intCast(@min(n, 4096));const got = fio.pread(fd, blk[0..head], 0) orelse return null;if (got != head) return null;h.update(blk[0..head]);const tail_off = n - head;const got2 = fio.pread(fd, blk[0..head], tail_off) orelse return null;if (got2 != head) return null;h.update(blk[0..head]);return std.fmt.bufPrint(buf, "{x:0>16}", .{h.final()}) catch null;}/// An old meta (no fingerprint) beside a file of another inode: are its tombstones/// frame starts of this file? A frame start has a size > 4 that fits in the file,/// and is followed by EOF or another plausible frame header.fn tombstonesAreFrameStarts(self: *Db, file_size: u64) bool {const fd = fio.openRead(self.tmp, self.data_path) orelse return self.deleted.items.len == 0;defer fio.close(fd);for (self.deleted.items) |off| {if (!frameHeaderOk(fd, off, file_size)) return false;var hdr: [4]u8 = undefined;_ = fio.pread(fd, &hdr, off);const next = off + std.mem.readInt(u32, &hdr, .little);if (next != file_size and !frameHeaderOk(fd, next, file_size)) return false;}return true;}fn frameHeaderOk(fd: i32, off: u64, file_size: u64) bool {if (off + 4 > file_size) return false;var hdr: [4]u8 = undefined;const got = fio.pread(fd, &hdr, off) orelse return false;if (got < 4) return false;const sz: u64 = std.mem.readInt(u32, &hdr, .little);return sz > 4 and off + sz <= file_size;}fn jsonU64(v: ?std.json.Value) ?u64 {const x = v orelse return null;return switch (x) {.integer => |i| if (i < 0) null else @intCast(i),else => null,};}/// The checksum of the deleted list (hex), as dataFile.deletedSum carries it.fn deletedSum(self: *Db, buf: *[16]u8) []const u8 {var h = std.hash.Wyhash.init(176);// the stream of little-endian u64s, fed in blocks (the hash does not depend on the split)var blk: [512]u64 = undefined;var i: usize = 0;while (i < self.deleted.items.len) {const n = @min(blk.len, self.deleted.items.len - i);for (0..n) |j| blk[j] = std.mem.nativeToLittle(u64, self.deleted.items[i + j]);h.update(std.mem.sliceAsBytes(blk[0..n]));i += n;}return std.fmt.bufPrint(buf, "{x:0>16}", .{h.final()}) catch buf[0..0];}/// Pick up other processes' persisted state (JS refresh()): adopt disk meta/// when its version is newer; index appended tail records.////// A HANDLE NOTICES A REWRITE (ticket #176). Another process's compaction/// replaces the data file and moves every record after its first tombstone;/// this handle's offsets are then into a file that no longer exists, and/// reading them read the middle of other records — a bare Number where a/// record was (the tracker, 2026-10-20). The data file's inode, a size below/// what was indexed, or a newer compaction generation in the meta says it/// happened; the handle then re-reads the meta (dropping a deleted list that/// belongs to the old file) and re-indexes the new file before it answers.pub fn refresh(self: *Db) void {if (self.data_fd < 0) self.adoptDataFile(); // a file created since the openif (self.index_bad) self.rebuildIndexesFromData();const cur = fio.stat(self.tmp, self.data_path);var rewritten = false;if (cur) |c| {if (self.seen_ino != 0 and c.ino != self.seen_ino) rewritten = true;if (self.index_fields.items.len > 0 and c.size < self.covered_bytes) rewritten = true;}const meta_now = fio.stat(self.tmp, self.meta_path);const meta_same = if (meta_now) |m| (if (self.meta_seen) |o| (m.ino == o.ino and m.size == o.size and m.mtime_ns == o.mtime_ns) else false) else true;// an unchanged meta says nothing new: its version and generation were taken when read// (a rewritten data file still re-reads it, to drop a deleted list of the old file)if (meta_same and !rewritten) {// nothing to read} else if (blk: {self.meta_seen = meta_now;self.meta_reads += 1;break :blk fio.readAll(self.tmp, self.meta_path);}) |content| {defer self.tmp.free(content);const parsed = std.json.parseFromSlice(std.json.Value, self.tmp, content, .{}) catch return;defer parsed.deinit();if (parsed.value == .object) {var disk_version: u64 = 0;if (parsed.value.object.get("version")) |v| {if (v == .integer) disk_version = @intCast(@max(v.integer, 0));}if (parsed.value.object.get("dataFile")) |df| {if (df == .object) {if (jsonU64(df.object.get("gen"))) |g| {if (g > self.data_gen) rewritten = true;}}}if (rewritten or disk_version > self.version) self.applyMetaJson(content);}}if (rewritten) {self.reindexRewritten();return;}// catchUp: index records another process appendedif (self.index_fields.items.len > 0) {const size = if (cur) |c| c.size else 0;if (size > self.covered_bytes) self.catchUp(size);}}/// THE INDEX NAMED A PLACE THAT IS NO RECORD (mission 393): the tracker's persons.id.txt/// carried ~2100 entries with offsets past the end of the data file or into the middle of a/// frame (entries of an older generation of the file), so range('id', …) answered a Number/// where a record was ("reading 'id': the value is Number"). A hit is checked against its/// frame header before it is returned; a bad one is dropped and the indexes are rebuilt from/// the data file at the next refresh.fn hitOk(self: *Db, h: Entry) bool {if (self.data_fd < 0) return true;var hdr: [4]u8 = undefined;const got = fio.pread(self.data_fd, &hdr, h.off) orelse 0;if (got == 4 and std.mem.readInt(u32, &hdr, .little) == h.len) return true;self.index_bad = true;return false;}fn rebuildIndexesFromData(self: *Db) void {self.index_bad = false;self.covered_bytes = 0;var it0 = self.idx.iterator();while (it0.next()) |kv| kv.value_ptr.entries.clearRetainingCapacity();if (self.index_fields.items.len > 0) {const size: u64 = if (self.data_fd >= 0) (if (fio.fdStat(self.data_fd)) |st| st.size else 0) else 0;self.catchUp(size);}std.debug.print("mpackdb: {s}: an index named a place that is no record; indexes rebuilt from the data file\n", .{self.data_path});}/// The data file was replaced under this handle: index it anew, in memory —/// the index files are written when the handle persists or closes.fn reindexRewritten(self: *Db) void {const old_ino = self.seen_ino;self.adoptDataFile();std.debug.print("mpackdb: {s}: the data file was rewritten by another process (inode {d} -> {d}); re-indexing before reading\n", .{ self.data_path, old_ino, self.seen_ino });self.covered_bytes = 0;var it0 = self.idx.iterator();while (it0.next()) |kv| kv.value_ptr.entries.clearRetainingCapacity();if (self.index_fields.items.len > 0) {const size: u64 = if (self.data_fd >= 0) (if (fio.fdStat(self.data_fd)) |st| st.size else 0) else 0;self.catchUp(size);}}/// Hold the data file now at the path; its inode is what the offsets are into.fn adoptDataFile(self: *Db) void {self.dropDataFile();self.data_fd = fio.openz(self.tmp, self.data_path, .{ .CLOEXEC = true }, 0) orelse -1;if (self.data_fd >= 0) self.fd_gen = DataGen.create(self.tmp, self.data_fd);self.seen_ino = if (self.data_fd >= 0) (fio.fdIno(self.data_fd) orelse 0) else 0;}fn dropDataFile(self: *Db) void {if (self.fd_gen) |g| g.release() else if (self.data_fd >= 0) fio.close(self.data_fd);self.fd_gen = null;self.data_fd = -1;}fn persistMetaLocked(self: *Db) Error!void {self.version += 1;const cur = fio.stat(self.tmp, self.data_path);self.bind_ino = if (cur) |c| c.ino else 0;self.bind_size = if (cur) |c| c.size else 0;self.bind_fp_len = 0;var fpb: [16]u8 = undefined;if (self.dataFingerprint(self.bind_size, &fpb)) |f| {@memcpy(self.bind_fp[0..f.len], f);self.bind_fp_len = @intCast(f.len);}self.bind_known = true;self.meta_stale = false;var out: std.ArrayList(u8) = .empty;defer out.deinit(self.tmp);try self.renderMeta(&out);// atomic tmp + rename (JS: `${metaPath}.${pid}.tmp`)var tmp_buf: [512]u8 = undefined;const tmp_path = std.fmt.bufPrint(&tmp_buf, "{s}.{d}.tmp", .{ self.meta_path, linux.getpid() }) catch return Error.IoError;const fd = fio.openTrunc(self.tmp, tmp_path) orelse return Error.IoError;const ok = fio.writeAll(fd, out.items);// the tmp file's own stat: rename keeps the inode, and no other writer can slip in// between a stat of the path and our remembering it (ticket #188)const written = fio.fdStat(fd);fio.close(fd);if (!ok) return Error.IoError;if (!fio.rename(self.tmp, tmp_path, self.meta_path)) return Error.IoError;self.meta_seen = written;}/// Does .meta.json already say, byte for byte, what this handle would write/// at its current version? Then an open has nothing to persist (ticket #21).fn metaOnDiskIsCurrent(self: *Db) bool {const disk = fio.readAll(self.tmp, self.meta_path) orelse return false;defer self.tmp.free(disk);var out: std.ArrayList(u8) = .empty;defer out.deinit(self.tmp);self.renderMeta(&out) catch return false;return std.mem.eql(u8, disk, out.items);}fn renderMeta(self: *Db, out: *std.ArrayList(u8)) Error!void {try self.appendFmt(out, "{{", .{});if (self.pk != null and self.pk_type == .number) {var nbuf: [32]u8 = undefined;try self.appendFmt(out, "\"nextId\":{s},", .{jsNumFmt(&nbuf, self.next_id)});}try self.appendFmt(out, "\"deleted\":[", .{});out.ensureUnusedCapacity(self.tmp, self.deleted.items.len * 9 + 64) catch return Error.OutOfMemory;for (self.deleted.items, 0..) |off, i| {out.ensureUnusedCapacity(self.tmp, 24) catch return Error.OutOfMemory;if (i > 0) out.appendAssumeCapacity(',');const spare = out.unusedCapacitySlice();const w = std.fmt.bufPrint(spare, "{d}", .{off}) catch return Error.OutOfMemory;out.items.len += w.len;}try self.appendFmt(out, "],\"version\":{d}", .{self.version});if (self.pk != null or self.index_fields.items.len > 0) {try self.appendFmt(out, ",\"schema\":{{", .{});var first = true;if (self.pk) |p| {const prefix: []const u8 = switch (self.pk_type) {.number => "*",.uuid => "@",.string => "",};try self.appendFmt(out, "\"primaryKey\":\"{s}{s}\"", .{ prefix, p });first = false;}if (!first) try self.appendFmt(out, ",", .{});try self.appendFmt(out, "\"indexes\":[", .{});var n: usize = 0;for (self.index_fields.items) |field| {if (self.pk != null and std.mem.eql(u8, field, self.pk.?)) continue;if (n > 0) try self.appendFmt(out, ",", .{});const uni = for (self.unique_fields.items) |u| {if (std.mem.eql(u8, u, field)) break true;} else false;const numeric = (self.idx.get(field) orelse FieldIndex{ .typ = .lexical }).typ == .numeric;try self.appendFmt(out, "\"{s}{s}{s}\"", .{if (uni) "!" else "",if (numeric) "*" else "",field,});n += 1;}try self.appendFmt(out, "]}}", .{});}if (self.bind_known) {var sum_buf: [16]u8 = undefined;try self.appendFmt(out, ",\"dataFile\":{{\"ino\":{d},\"size\":{d},\"gen\":{d},\"deletedSum\":\"{s}\"", .{ self.bind_ino, self.bind_size, self.data_gen, self.deletedSum(&sum_buf) });if (self.bind_fp_len > 0) try self.appendFmt(out, ",\"fp\":\"{s}\"", .{self.bind_fp[0..self.bind_fp_len]});try self.appendFmt(out, "}}", .{});}try self.appendFmt(out, "}}", .{});}// =====================================================================// Data file scanning// =====================================================================fn deletedSet(self: *Db, alloc: std.mem.Allocator) std.AutoHashMapUnmanaged(u64, void) {var set: std.AutoHashMapUnmanaged(u64, void) = .empty;for (self.deleted.items) |off| set.put(alloc, off, {}) catch {};return set;}/// The cached tombstone set, built on first use (borrowed: valid until the next/// delete / meta adoption / compaction; hold it with delSetAcquire to keep it).fn delSetCached(self: *Db) *DelSet {if (self.del_cache) |c| return c;const c = self.tmp.create(DelSet) catch unreachable;c.* = .{ .alloc = self.tmp };c.map.ensureTotalCapacity(self.tmp, @intCast(self.deleted.items.len)) catch {};for (self.deleted.items) |off| c.map.put(self.tmp, off, {}) catch {};self.del_cache = c;return c;}/// A reference the caller must release() — a frozen view of the tombstones.pub fn delSetAcquire(self: *Db) *DelSet {const c = self.delSetCached();c.refs += 1;return c;}fn delCacheDrop(self: *Db) void {if (self.del_cache) |c| c.release();self.del_cache = null;}fn delCacheAdd(self: *Db, off: u64) void {const c = self.del_cache orelse return;if (c.refs > 1) {// a cursor holds this set: it keeps it unchanged, the Db goes on with a copyconst n = self.tmp.create(DelSet) catch {self.delCacheDrop();return;};n.* = .{ .alloc = self.tmp };n.map = c.map.clone(self.tmp) catch {self.tmp.destroy(n);self.delCacheDrop();return;};c.release();self.del_cache = n;}self.del_cache.?.map.put(self.tmp, off, {}) catch self.delCacheDrop();}/// Sequential scan yielding all live records. Caller supplies an arena for/// decoded values. Used for rebuilds, compaction and unindexed finds.pub const Scanner = struct {db: *Db,fd: i32 = -1,offset: u64 = 0,size: u64 = 0,skip_deleted: bool = true,owns_fd: bool = true,/// a detached scanner's reference to the data file generation (instead of a dup)gen: ?*DataGen = null,/// a frozen view of the tombstones (null when !skip_deleted); released by deinitdeleted_set: ?*DelSet = null,scratch: std.mem.Allocator,pub fn init(db: *Db, scratch: std.mem.Allocator, skip_deleted: bool) Scanner {return initOpt(db, scratch, skip_deleted, false);}/// `detached` (a streaming cursor): the scanner holds a reference to the data file generation (no dup), so a compaction/// or a foreign rewrite that makes the Db move to a new file leaves the scan reading/// the file it started on; it also freezes the size and the tombstones (mission 393).pub fn initOpt(db: *Db, scratch: std.mem.Allocator, skip_deleted: bool, detached: bool) Scanner {var s = Scanner{ .db = db, .scratch = scratch, .skip_deleted = skip_deleted };if (db.data_fd >= 0) {// the file the handle's offsets are into (#176), not whatever is at the pathif (detached) {if (db.fd_gen) |g| {s.gen = g.retain();s.fd = g.fd;s.owns_fd = false;} else {s.fd = db.data_fd;s.owns_fd = false;}} else {s.fd = db.data_fd;s.owns_fd = false;}s.size = if (fio.fdStat(s.fd)) |st| st.size else 0;} else {s.size = fio.fileSize(scratch, db.data_path) orelse 0;if (s.size > 0) {s.fd = fio.openRead(scratch, db.data_path) orelse -1;}}if (skip_deleted) s.deleted_set = db.delSetAcquire();return s;}pub fn deinit(self: *Scanner) void {if (self.gen) |g| g.release();self.gen = null;if (self.fd >= 0 and self.owns_fd) fio.close(self.fd);self.fd = -1;if (self.deleted_set) |d| d.release();self.deleted_set = null;}/// Returns the next record (decoded into `arena`) or null at EOF.pub fn next(self: *Scanner, arena: std.mem.Allocator) Error!?Record {return self.nextProjected(arena, null);}pub fn nextProjected(self: *Scanner, arena: std.mem.Allocator, fields: ?[]const []const u8) Error!?Record {while (true) {if (self.fd < 0 or self.offset + 4 > self.size) return null;var hdr: [4]u8 = undefined;const got = fio.pread(self.fd, &hdr, self.offset) orelse return Error.IoError;if (got < 4) return null;const rec_size = std.mem.readInt(u32, &hdr, .little);if (rec_size <= 4) return Error.CorruptRecord;if (self.offset + rec_size > self.size) return null; // incomplete tailconst off = self.offset;self.offset += rec_size;if (self.deleted_set) |d| {if (d.map.contains(off)) continue;}const buf = arena.alloc(u8, rec_size - 4) catch return Error.OutOfMemory;const got2 = fio.pread(self.fd, buf, off + 4) orelse return Error.IoError;if (got2 < rec_size - 4) return Error.Truncated;const value = msgpack.decodeRecord(arena, buf, fields) catch return Error.CorruptRecord;return Record{ .value = value, .off = off, .len = rec_size };}}/// The number of live records from here on, reading only the 4-byte frame headers:/// nothing is decoded or kept (count() decoded the whole table into an arena, 2 GB/// for the tracker's two big tables).pub fn countLive(self: *Scanner) Error!usize {var n: usize = 0;while (true) {if (self.fd < 0 or self.offset + 4 > self.size) return n;var hdr: [4]u8 = undefined;const got = fio.pread(self.fd, &hdr, self.offset) orelse return Error.IoError;if (got < 4) return n;const rec_size = std.mem.readInt(u32, &hdr, .little);if (rec_size <= 4) return Error.CorruptRecord;if (self.offset + rec_size > self.size) return n;const off = self.offset;self.offset += rec_size;if (self.deleted_set) |d| {if (d.map.contains(off)) continue;}n += 1;}}/// Like next() but without decoding — yields the raw framed bytes.pub fn nextRaw(self: *Scanner, arena: std.mem.Allocator) Error!?struct { bytes: []u8, off: u64 } {while (true) {if (self.fd < 0 or self.offset + 4 > self.size) return null;var hdr: [4]u8 = undefined;const got = fio.pread(self.fd, &hdr, self.offset) orelse return Error.IoError;if (got < 4) return null;const rec_size = std.mem.readInt(u32, &hdr, .little);if (rec_size <= 4) return Error.CorruptRecord;if (self.offset + rec_size > self.size) return null;const off = self.offset;self.offset += rec_size;if (self.deleted_set) |d| {if (d.map.contains(off)) continue;}const buf = arena.alloc(u8, rec_size) catch return Error.OutOfMemory;const got2 = fio.pread(self.fd, buf, off) orelse return Error.IoError;if (got2 < rec_size) return Error.Truncated;return .{ .bytes = buf, .off = off };}}};/// A reference to the data file the offsets are into, for a streaming cursor (null: none)./// Release it with `DataGen.release`; the fd (`.fd`) stays valid until then.pub fn retainDataGen(self: *Db) ?*DataGen {const g = self.fd_gen orelse return null;return g.retain();}/// Read + decode one record by location from `fd` (a dupDataFd of the file the loc is into).pub fn readAtFd(fd: i32, arena: std.mem.Allocator, loc: Loc) Error!msgpack.Value {return readAtFdProjected(fd, arena, loc, null);}pub fn readAtFdProjected(fd: i32, arena: std.mem.Allocator, loc: Loc, fields: ?[]const []const u8) Error!msgpack.Value {if (loc.len <= 4) return Error.CorruptRecord;const buf = arena.alloc(u8, loc.len - 4) catch return Error.OutOfMemory;const got = fio.pread(fd, buf, loc.off + 4) orelse return Error.IoError;if (got < buf.len) return Error.Truncated;return msgpack.decodeRecord(arena, buf, fields) catch return Error.CorruptRecord;}/// Read + decode one record by location.pub fn readAt(self: *Db, arena: std.mem.Allocator, loc: Loc) Error!msgpack.Value {return self.readAtProjected(arena, loc, null);}pub fn readAtProjected(self: *Db, arena: std.mem.Allocator, loc: Loc, fields: ?[]const []const u8) Error!msgpack.Value {const own = self.data_fd < 0;const fd = if (own) (fio.openRead(self.tmp, self.data_path) orelse return Error.IoError) else self.data_fd;defer if (own) fio.close(fd);if (loc.len <= 4) return Error.CorruptRecord;const buf = arena.alloc(u8, loc.len - 4) catch return Error.OutOfMemory;const got = fio.pread(fd, buf, loc.off + 4) orelse return Error.IoError;if (got < buf.len) return Error.Truncated;return msgpack.decodeRecord(arena, buf, fields) catch return Error.CorruptRecord;}// =====================================================================// Index management// =====================================================================fn keyFromValue(v: msgpack.Value) ?Key {return switch (v) {.number => |n| Key{ .num = n },.str => |s| Key{ .str = s },else => null, // null/bool/objects are not indexed (see header note)};}/// Duplicate a key's string into the db arena so it outlives the op arena.fn ownKey(self: *Db, k: Key) Error!Key {return switch (k) {.num => k,.str => |s| Key{ .str = (if (self.bulk_keys) |ka| ka.allocator() else self.alloc).dupe(u8, s) catch return Error.OutOfMemory },};}/// Copy every string key of every index into one run of memory, in the lists' order.fn packKeys(self: *Db) void {for (self.idx.values()) |*fi| {var total: usize = 0;for (fi.entries.items) |e| {if (e.key == .str) total += e.key.str.len;}if (total == 0) continue;const slab = self.alloc.alloc(u8, total) catch continue;var pos: usize = 0;for (fi.entries.items) |*e| {if (e.key == .str) {const k = e.key.str;@memcpy(slab[pos..][0..k.len], k);e.key = .{ .str = slab[pos..][0..k.len] };pos += k.len;}}}}fn lowerBound(entries: []const Entry, key: Key) usize {var lo: usize = 0;var hi: usize = entries.len;while (lo < hi) {const mid = lo + (hi - lo) / 2;if (cmpKeys(entries[mid].key, key) < 0) {lo = mid + 1;} else {hi = mid;}}return lo;}/// Binary search: all entries whose key equals `key` (appended to `out`).pub fn indexGet(self: *Db, field: []const u8, key: Key, alloc: std.mem.Allocator, out: *std.ArrayList(Entry)) Error!void {const fi = self.idx.getPtr(field) orelse return Error.NoSuchIndex;const parsed = self.parseKeyForField(field, key);const entries = fi.entries.items;var i = lowerBound(entries, parsed);while (i < entries.len and cmpKeys(entries[i].key, parsed) == 0) : (i += 1) {out.append(alloc, entries[i]) catch return Error.OutOfMemory;}}/// Range scan [from, to] (either side optional), ascending.pub fn indexRange(self: *Db, field: []const u8, from: ?Key, to: ?Key, alloc: std.mem.Allocator, out: *std.ArrayList(Entry)) Error!void {const fi = self.idx.getPtr(field) orelse return Error.NoSuchIndex;const entries = fi.entries.items;var i: usize = if (from) |f| lowerBound(entries, self.parseKeyForField(field, f)) else 0;const to_key: ?Key = if (to) |t| self.parseKeyForField(field, t) else null;while (i < entries.len) : (i += 1) {if (to_key) |t| {if (cmpKeys(entries[i].key, t) > 0) break;}out.append(alloc, entries[i]) catch return Error.OutOfMemory;}}/// _parseKey semantics: numeric index fields parse string keys via/// parseInt; on NaN the key stays a string.fn parseKeyForField(self: *Db, field: []const u8, key: Key) Key {const fi = self.idx.get(field) orelse return key;if (fi.typ == .numeric and key == .str) {if (numericText(key.str)) |n| return Key{ .num = n };}return key;}fn indexInsertEntry(self: *Db, field: []const u8, key: Key, loc: Loc) Error!void {const fi = self.idx.getPtr(field) orelse return;const owned = try self.ownKey(key);const e = Entry{ .key = owned, .off = loc.off, .len = loc.len };// a bulk scan (rebuild / big catch-up) appends and sorts once at the end: a sorted// insert per record is a memmove of the whole list each time — quadratic (#376)if (self.bulk_index) {fi.entries.append(self.alloc, e) catch return Error.OutOfMemory;return;}// insert at sorted positionconst pos = blk: {var lo: usize = 0;var hi: usize = fi.entries.items.len;while (lo < hi) {const mid = lo + (hi - lo) / 2;if (entryLess({}, fi.entries.items[mid], e)) {lo = mid + 1;} else {hi = mid;}}break :blk lo;};fi.entries.insert(self.alloc, pos, e) catch return Error.OutOfMemory;}/// Index a record's fields at loc.fn indexInsertRecord(self: *Db, rec: msgpack.Value, loc: Loc) Error!void {for (self.index_fields.items) |field| {const v = rec.get(field) orelse continue;const key = keyFromValue(v) orelse continue;try self.indexInsertEntry(field, key, loc);}self.covered_bytes = @max(self.covered_bytes, loc.off + loc.len);}/// Remove all entries pointing at offset `off` (all fields).fn indexRemoveOffset(self: *Db, off: u64) void {var it = self.idx.iterator();while (it.next()) |kv| {const list = &kv.value_ptr.entries;var i: usize = 0;while (i < list.items.len) {if (list.items[i].off == off) {_ = list.orderedRemove(i);} else {i += 1;}}}}fn indexPath(self: *Db, buf: []u8, field: []const u8) []const u8 {// <dir>/<base>.<field>.txt — derive from idxstate path (…/base.idxstate.json)const prefix = self.idxstate_path[0 .. self.idxstate_path.len - "idxstate.json".len];return std.fmt.bufPrint(buf, "{s}{s}.txt", .{ prefix, field }) catch buf[0..0];}fn initIndexes(self: *Db, force_rebuild: bool) Error!void {if (self.readIdxState()) |st| {if (st.fmt > 3) {std.debug.print("mpackdb: {s}: unsupported index format {d}\n", .{ self.idxstate_path, st.fmt });return Error.InvalidFormat;}}var need_rebuild = force_rebuild;const data_size = fio.fileSize(self.tmp, self.data_path) orelse 0;if (!need_rebuild) {for (self.index_fields.items) |field| {var pbuf: [512]u8 = undefined;const p = self.indexPath(&pbuf, field);const isize_ = fio.fileSize(self.tmp, p);if (isize_ == null or isize_.? == 0) {if (data_size > 0) {need_rebuild = true;break;}}}}if (!need_rebuild) {// coveredBytes from idxstate — no state file means rebuild (JS). An
Only the first lines are shown.
Branches
Latest commits
- 10f8a8c8Merge branch 'code-order' into mainJukebox
- 204fc828Merge branch 'day72' into mainJukebox
- 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
- 33072bb5|||PR Record day72 gates and Chrome proofmre
- 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
- 6422a020Sync media-player at 51c3818mre
- b582ba1cVendor complete Hybriel day72 plugin setmre
- 02dccbc9Merge branch 'records-1119' into mainJukebox
- a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
- fc7db075Merge branch 'reconnect-retry' into mainJukebox
- ac6f4c6fL2: plain declaration for a in pickedNextmre
- 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
- 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
- 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
- 1f0cd77bMerge branch 'records-day41' into mainJukebox
- 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
- 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
- 04f5d9d5Merge branch 'day41' into mainJukebox
- 8ed6da45|||PR README: media-player pin df9e7dfmre
- d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre