notes
All repositories: gitoria
148.5 KB
// mpackdb DB engine — Zig port of mpackdb v1.0.7 (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"// <base>.idxstate.json { coveredBytes }// <base>.lock lock file containing the holder's pid (O_EXCL protocol,// stale takeover after 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);var content: std.ArrayList(u8) = .empty;var buf: [65536]u8 = undefined;while (true) {const rc = linux.read(fd, &buf, buf.len);if (@as(isize, @bitCast(rc)) <= 0) break;content.appendSlice(alloc, buf[0..rc]) catch return null;}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// =========================================================================/// Format an f64 the way JS String(n) does for the values mpackdb produces:/// integral values print without a decimal point. (Exotic floats may diverge/// from V8's shortest-round-trip formatting; index keys are ints/strings in/// practice.)pub fn jsNumFmt(buf: []u8, v: f64) []const u8 {if (v == @floor(v) and @abs(v) <= 9007199254740992.0) {const i: i64 = @intFromFloat(v);return std.fmt.bufPrint(buf, "{d}", .{i}) catch buf[0..0];}return std.fmt.bufPrint(buf, "{d}", .{v}) catch buf[0..0];}/// JS parseInt(s, 10) semantics: optional sign, leading digits, ignore rest./// Returns null for NaN.fn jsParseInt(s: []const u8) ?f64 {var i: usize = 0;while (i < s.len and (s[i] == ' ' or s[i] == '\t')) i += 1;var sign: f64 = 1;if (i < s.len and (s[i] == '+' or s[i] == '-')) {if (s[i] == '-') sign = -1;i += 1;}var got = false;var v: f64 = 0;while (i < s.len and s[i] >= '0' and s[i] <= '9') : (i += 1) {v = v * 10 + @as(f64, @floatFromInt(s[i] - '0'));got = true;}if (!got) return null;return sign * v;}/// _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 == .num) {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;}/// 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,// 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-upcovered_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();const mr = self.persistMetaLocked();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)// =====================================================================fn acquireLock(self: *Db) Error!void {var retries: u32 = 0;while (true) {if (fio.openExcl(self.tmp, self.lock_path)) |fd| {var pid_buf: [16]u8 = undefined;const pid_s = std.fmt.bufPrint(&pid_buf, "{d}", .{linux.getpid()}) catch "0";_ = fio.writeAll(fd, pid_s);fio.close(fd);return;}// stale lock takeoverif (self.stale_lock_timeout_ms > 0) {if (fio.mtimeMs(self.tmp, self.lock_path)) |mt| {if (fio.nowMs() - mt > self.stale_lock_timeout_ms) {_ = fio.unlink(self.tmp, self.lock_path);continue;}}}if (retries > 480) return Error.LockTimeout; // ~12s at 25msfio.sleepMs(25);retries += 1;}}fn releaseLock(self: *Db) void {_ = fio.unlink(self.tmp, self.lock_path);}/// 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 {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);}fn applyMetaJson(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;const ino = jsonU64(df.get("ino")) orelse return;const size = jsonU64(df.get("size")) orelse return;if (jsonU64(df.get("gen"))) |g| self.data_gen = @max(self.data_gen, g);const sum_v = df.get("deletedSum") orelse return;if (sum_v != .string) return;var sum_buf: [16]u8 = undefined;if (!std.mem.eql(u8, sum_v.string, 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 (obj.get("dataFile").?.object.get("fp")) |fv| {if (fv == .string) {have_fp = self.dataFingerprint(size, &fp_buf);bound = have_fp != null and std.mem.eql(u8, have_fp.?, fv.string);}} 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);for (self.deleted.items) |off| {var b: [8]u8 = undefined;std.mem.writeInt(u64, &b, off, .little);h.update(&b);}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\":[", .{});for (self.deleted.items, 0..) |off, i| {if (i > 0) try self.appendFmt(out, ",", .{});try self.appendFmt(out, "{d}", .{off});}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 {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 d = msgpack.decode(arena, buf) catch return Error.CorruptRecord;return Record{ .value = d.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 {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;const d = msgpack.decode(arena, buf) catch return Error.CorruptRecord;return d.value;}/// Read + decode one record by location.pub fn readAt(self: *Db, arena: std.mem.Allocator, loc: Loc) 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;const d = msgpack.decode(arena, buf) catch return Error.CorruptRecord;return d.value;}// =====================================================================// 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 = self.alloc.dupe(u8, s) catch return Error.OutOfMemory },};}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 (jsParseInt(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 {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// idxstate of another data file (its inode, or more bytes covered// than there are) means the index files are another file's too:// a crash between a compaction's rename and its rebuild (#176).if (self.readIdxState()) |st| {self.covered_bytes = st.covered;const cur = fio.stat(self.tmp, self.data_path);const cur_ino: u64 = if (cur) |c| c.ino else 0;if (st.covered > data_size) need_rebuild = true;if (st.ino) |i| {self.idx_bind_known = true;// another inode: a byte COPY of the store (ticket 387) has the same// content over the covered bytes, so its index files are rightif (i != cur_ino) {var fpb: [16]u8 = undefined;const same = st.has_fp and st.covered <= data_size andif (self.dataFingerprint(st.covered, &fpb)) |f| std.mem.eql(u8, f, &st.fp) else false;if (!same) need_rebuild = true;}}} else {need_rebuild = true;}}if (need_rebuild) {try self.rebuildIndexes();return;}// Load index files into memoryfor (self.index_fields.items) |field| {var pbuf: [512]u8 = undefined;const p = self.indexPath(&pbuf, field);const content = fio.readAll(self.tmp, p) orelse continue;defer self.tmp.free(content);self.loadIndexLines(field, content);}// sort (files are sorted by JS localeCompare; re-sort under our order)var it = self.idx.iterator();while (it.next()) |kv| {std.sort.pdq(Entry, kv.value_ptr.entries.items, {}, entryLess);}if (data_size > self.covered_bytes) self.catchUp(data_size);}fn loadIndexLines(self: *Db, field: []const u8, content: []const u8) void {const fi = self.idx.getPtr(field) orelse return;var lines = std.mem.splitScalar(u8, content, '\n');while (lines.next()) |line| {if (line.len == 0) continue;// key = up to FIRST comma (JS split(',')[0]); then offset, lengthconst c1 = std.mem.indexOfScalar(u8, line, ',') orelse continue;const rest = line[c1 + 1 ..];const c2 = std.mem.indexOfScalar(u8, rest, ',') orelse continue;const off_s = rest[0..c2];const len_s = rest[c2 + 1 ..];const off = std.fmt.parseInt(u64, off_s, 10) catch continue;const len = std.fmt.parseInt(u64, len_s, 10) catch continue;if (len == 0) continue;const key_s = line[0..c1];var key: Key = undefined;if (fi.typ == .numeric) {key = if (jsParseInt(key_s)) |n| Key{ .num = n } else Key{ .str = self.alloc.dupe(u8, key_s) catch return };} else {key = Key{ .str = self.alloc.dupe(u8, key_s) catch return };}fi.entries.append(self.alloc, .{ .key = key, .off = off, .len = len }) catch return;}}fn sortAllIndexes(self: *Db) void {var it = self.idx.iterator();while (it.next()) |kv| std.sort.pdq(Entry, kv.value_ptr.entries.items, {}, entryLess);}fn rebuildIndexes(self: *Db) Error!void {var it0 = self.idx.iterator();while (it0.next()) |kv| kv.value_ptr.entries.clearRetainingCapacity();self.bulk_index = true;defer self.bulk_index = false;var scratch_state = std.heap.ArenaAllocator.init(self.arena_state.child_allocator);defer scratch_state.deinit();const scratch = scratch_state.allocator();// JS rebuild scans ALL records (no tombstone filter — deleted offsets// simply get filtered at read time). Mirror that.var scanner = Scanner.init(self, scratch, false);defer scanner.deinit();while (try scanner.next(scratch)) |rec| {try self.indexInsertRecord(rec.value, .{ .off = rec.off, .len = rec.len });}self.sortAllIndexes();self.bulk_index = false;self.covered_bytes = fio.fileSize(self.tmp, self.data_path) orelse 0;self.idx_bind_known = true;try self.writeIndexFiles();try self.writeIdxState();}fn catchUp(self: *Db, file_size: u64) void {var scratch_state = std.heap.ArenaAllocator.init(self.arena_state.child_allocator);defer scratch_state.deinit();const scratch = scratch_state.allocator();var scanner = Scanner.init(self, scratch, false);defer scanner.deinit();scanner.offset = self.covered_bytes;// a long tail is appended and sorted once; a short one (a refresh per op) is insertedconst bulk = file_size > self.covered_bytes and file_size - self.covered_bytes > 256 * 1024;self.bulk_index = bulk;defer self.bulk_index = false;while (true) {const maybe = scanner.next(scratch) catch break;const rec = maybe orelse break;self.indexInsertRecord(rec.value, .{ .off = rec.off, .len = rec.len }) catch break;}if (bulk) self.sortAllIndexes();self.bulk_index = false;self.covered_bytes = @max(self.covered_bytes, file_size);}/// A file that already holds these exact bytes is left alone — its mtime/// included — so closing a handle that changed nothing writes nothing.fn fileHolds(alloc: std.mem.Allocator, path: []const u8, bytes: []const u8) bool {const disk = fio.readAll(alloc, path) orelse return false;defer alloc.free(disk);return std.mem.eql(u8, disk, bytes);}fn writeIndexFiles(self: *Db) Error!void {for (self.index_fields.items) |field| {const fi = self.idx.getPtr(field) orelse continue;var out: std.ArrayList(u8) = .empty;defer out.deinit(self.tmp);for (fi.entries.items) |e| {var kbuf: [32]u8 = undefined;const ks = switch (e.key) {.num => |n| jsNumFmt(&kbuf, n),.str => |s| s,};try self.appendFmt(&out, "{s},{d},{d}\n", .{ ks, e.off, e.len });}var pbuf: [512]u8 = undefined;const p = self.indexPath(&pbuf, field);if (fileHolds(self.tmp, p, out.items)) continue;var tbuf: [512]u8 = undefined;const tmp = std.fmt.bufPrint(&tbuf, "{s}.{d}.tmp", .{ p, linux.getpid() }) catch return Error.IoError;const fd = fio.openTrunc(self.tmp, tmp) orelse return Error.IoError;const ok = fio.writeAll(fd, out.items);fio.close(fd);if (!ok) return Error.IoError;if (!fio.rename(self.tmp, tmp, p)) return Error.IoError;}}const IdxState = struct { covered: u64, ino: ?u64, fp: [16]u8 = undefined, has_fp: bool = false };fn readIdxState(self: *Db) ?IdxState {const content = fio.readAll(self.tmp, self.idxstate_path) orelse return null;defer self.tmp.free(content);const parsed = std.json.parseFromSlice(std.json.Value, self.tmp, content, .{}) catch return null;defer parsed.deinit();if (parsed.value != .object) return null;const v = parsed.value.object.get("coveredBytes") orelse return null;const covered: u64 = switch (v) {.integer => |i| @intCast(@max(i, 0)),.float => |f| @intFromFloat(@max(f, 0)),else => return null,};var st = IdxState{ .covered = covered, .ino = jsonU64(parsed.value.object.get("dataIno")) };if (parsed.value.object.get("dataFp")) |f| {if (f == .string and f.string.len == 16) {@memcpy(&st.fp, f.string);st.has_fp = true;}}return st;}/// idxstate.json: coveredBytes (JS) and, once this engine indexed the file,/// the data file's inode — so index files of a replaced data file are known/// for what they are (ticket #176). An idxstate without it (the JS mpackdb's)/// is rewritten without it while it stays without a rebuild (ticket #21).fn writeIdxState(self: *Db) Error!void {var buf: [160]u8 = undefined;const ino: u64 = if (fio.stat(self.tmp, self.data_path)) |c| c.ino else 0;var fpb: [16]u8 = undefined;const fp: ?[]const u8 = if (self.idx_bind_known) self.dataFingerprint(self.covered_bytes, &fpb) else null;const json = (if (self.idx_bind_known and fp != null)std.fmt.bufPrint(&buf, "{{\"coveredBytes\":{d},\"dataIno\":{d},\"dataFp\":\"{s}\"}}", .{ self.covered_bytes, ino, fp.? })else if (self.idx_bind_known)std.fmt.bufPrint(&buf, "{{\"coveredBytes\":{d},\"dataIno\":{d}}}", .{ self.covered_bytes, ino })elsestd.fmt.bufPrint(&buf, "{{\"coveredBytes\":{d}}}", .{self.covered_bytes})) catch return Error.IoError;if (fileHolds(self.tmp, self.idxstate_path, json)) return;var tbuf: [512]u8 = undefined;const tmp = std.fmt.bufPrint(&tbuf, "{s}.{d}.tmp", .{ self.idxstate_path, linux.getpid() }) catch return Error.IoError;const fd = fio.openTrunc(self.tmp, tmp) orelse return Error.IoError;const ok = fio.writeAll(fd, json);fio.close(fd);if (!ok) return Error.IoError;if (!fio.rename(self.tmp, tmp, self.idxstate_path)) return Error.IoError;}fn persistIndexesLocked(self: *Db) Error!void {// never write an index of a data file that is no longer the one at the path (395)if (self.data_fd >= 0) {if (fio.stat(self.tmp, self.data_path)) |c| {if (self.seen_ino != 0 and c.ino != self.seen_ino) return;}}try self.writeIndexFiles();// coverage can only grow (JS: max of ours and on-disk state)if (self.readIdxState()) |st| {const same_file = if (st.ino) |i| i == (if (fio.stat(self.tmp, self.data_path)) |c| c.ino else 0) else true;if (same_file) self.covered_bytes = @max(self.covered_bytes, st.covered);}try self.writeIdxState();}// =====================================================================// Operations// =====================================================================/// A mutable record under construction (op-arena entries).pub const MutableRecord = struct {entries: std.ArrayList(msgpack.Entry) = .empty,pub fn get(self: *const MutableRecord, key: []const u8) ?msgpack.Value {for (self.entries.items) |e| {if (e.key == .str and std.mem.eql(u8, e.key.str, key)) return e.value;}return null;}pub fn set(self: *MutableRecord, alloc: std.mem.Allocator, key: []const u8, v: msgpack.Value) Error!void {for (self.entries.items) |*e| {if (e.key == .str and std.mem.eql(u8, e.key.str, key)) {e.value = v;return;}}self.entries.append(alloc, .{ .key = .{ .str = key }, .value = v }) catch return Error.OutOfMemory;}pub fn toValue(self: *const MutableRecord) msgpack.Value {return .{ .map = self.entries.items };}};pub const InsertResult = union(enum) {pk_num: f64,pk_str: []const u8, // op-arenarecord: msgpack.Value,};/// insert() — auto primary key, unique checks, append, index./// `record` must be a map value; `arena` is the op arena (record memory).pub fn insert(self: *Db, arena: std.mem.Allocator, record: msgpack.Value, skip_pk: bool) Error!InsertResult {if (record != .map) return Error.CorruptRecord;try self.acquireLock();defer self.releaseLock();self.refresh();return self.insertLocked(arena, record, skip_pk);}fn insertLocked(self: *Db, arena: std.mem.Allocator, record: msgpack.Value, skip_pk: bool) Error!InsertResult {// copy into mutable formvar rec = MutableRecord{};for (record.map) |e| rec.entries.append(arena, e) catch return Error.OutOfMemory;// _hasPrimaryKeyValue: present and not null/undefinedvar has_pk_value = false;if (self.pk) |p| {if (rec.get(p)) |v| {has_pk_value = (v != .nil and v != .undef);}}var auto_gen = false;if (self.pk != null and !skip_pk and !has_pk_value) {if (self.pk_type == .number) {rec.set(arena, self.pk.?, .{ .number = self.next_id }) catch return Error.OutOfMemory;self.next_id += 1;auto_gen = true;} else if (self.pk_type == .uuid) {// A GENERATED ID IS CHECKED, NOT TRUSTED (ticket #113): the format is a// millisecond stamp + 3 base36 chars, so a bulk put collides within a// millisecond (two of 7800 in a measured run) and the unique check below// skips generated keys — two live rows then shared one pk and the next// update() deleted both and re-inserted one. Draw again until it is free.var ubuf: [12]u8 = undefined;var tries: usize = 0;while (true) : (tries += 1) {const u = genUuid(&ubuf);var taken: std.ArrayList(Loc) = .empty;defer taken.deinit(arena);try self.findPkLocs(arena, .{ .str = u }, &taken);if (taken.items.len == 0 or tries >= 64) break;}const owned = arena.dupe(u8, ubuf[0..12]) catch return Error.OutOfMemory;rec.set(arena, self.pk.?, .{ .str = owned }) catch return Error.OutOfMemory;auto_gen = true;}}// unique constraints (skip auto-generated pk)if (self.index_fields.items.len > 0 and self.unique_fields.items.len > 0) {const del_set = &self.delSetCached().map;for (self.unique_fields.items) |field| {if (auto_gen and self.pk != null and std.mem.eql(u8, field, self.pk.?)) continue;const v = rec.get(field) orelse continue;if (v == .undef) continue;const key = keyFromValue(v) orelse continue;var hits: std.ArrayList(Entry) = .empty;defer hits.deinit(arena);try self.indexGet(field, key, arena, &hits);var live: usize = 0;for (hits.items) |h| {if (!del_set.contains(h.off)) live += 1;}if (live > 0) {var kbuf: [32]u8 = undefined;const ks = switch (key) {.num => |n| jsNumFmt(&kbuf, n),.str => |s| s,};self.last_error = std.fmt.bufPrint(&self.last_error_buf, "Duplicate key: {s}={s}", .{ field, ks }) catch "Duplicate key";return Error.DuplicateKey;}}}// serialize + appendconst framed = msgpack.serialize(arena, rec.toValue()) catch return Error.OutOfMemory;const offset = fio.fileSize(self.tmp, self.data_path) orelse 0;const fd = fio.openAppend(self.tmp, self.data_path) orelse return Error.IoError;const ok = fio.writeAll(fd, framed);fio.close(fd);if (!ok) return Error.IoError;const loc = Loc{ .off = offset, .len = framed.len };if (self.index_fields.items.len > 0) {try self.indexInsertRecord(rec.toValue(), loc);}if (self.pk != null and self.pk_type == .number and !skip_pk and !has_pk_value) {try self.persistMetaLocked();}if (self.pk) |p| {const v = rec.get(p) orelse return Error.CorruptRecord;return switch (v) {.number => |n| InsertResult{ .pk_num = n },.str => |s| InsertResult{ .pk_str = s },else => InsertResult{ .record = rec.toValue() },};}return InsertResult{ .record = rec.toValue() };}/// Locate live records by primary key (index-backed when available).pub fn findPkLocs(self: *Db, arena: std.mem.Allocator, key: Key, out: *std.ArrayList(Loc)) Error!void {if (self.pk == null) return Error.NoPrimaryKey;self.refresh();const del_set = &self.delSetCached().map;if (self.index_fields.items.len > 0) {var hits: std.ArrayList(Entry) = .empty;defer hits.deinit(arena);try self.indexGet(self.pk.?, key, arena, &hits);for (hits.items) |h| {if (del_set.contains(h.off)) continue;if (!self.hitOk(h)) continue;out.append(arena, .{ .off = h.off, .len = h.len }) catch return Error.OutOfMemory;}if (self.index_bad and !self.index_retry) {self.index_retry = true;defer self.index_retry = false;out.clearRetainingCapacity();return self.findPkLocs(arena, key, out);}return;}// no indexes: full scan comparing the pk fieldvar scanner = Scanner.init(self, arena, true);defer scanner.deinit();while (try scanner.next(arena)) |rec| {const v = rec.value.get(self.pk.?) orelse continue;const k = keyFromValue(v) orelse continue;if (cmpKeys(self.parseKeyForField(self.pk.?, k), self.parseKeyForField(self.pk.?, key)) == 0) {out.append(arena, .{ .off = rec.off, .len = rec.len }) catch return Error.OutOfMemory;}}}/// Locate live records by secondary index equality.pub fn findIndexLocs(self: *Db, arena: std.mem.Allocator, field: []const u8, key: Key, out: *std.ArrayList(Loc)) Error!void {self.refresh();const del_set = &self.delSetCached().map;var hits: std.ArrayList(Entry) = .empty;defer hits.deinit(arena);try self.indexGet(field, key, arena, &hits);for (hits.items) |h| {if (del_set.contains(h.off)) continue;if (!self.hitOk(h)) continue;out.append(arena, .{ .off = h.off, .len = h.len }) catch return Error.OutOfMemory;}if (self.index_bad and !self.index_retry) {self.index_retry = true;defer self.index_retry = false;out.clearRetainingCapacity();return self.findIndexLocs(arena, field, key, out);}}/// Locate live records by index range [from, to] ascending.pub fn findRangeLocs(self: *Db, arena: std.mem.Allocator, field: []const u8, from: ?Key, to: ?Key, out: *std.ArrayList(Loc)) Error!void {self.refresh();const del_set = &self.delSetCached().map;var hits: std.ArrayList(Entry) = .empty;defer hits.deinit(arena);try self.indexRange(field, from, to, arena, &hits);var seen: std.AutoHashMapUnmanaged(u64, void) = .empty;for (hits.items) |h| {if (del_set.contains(h.off)) continue;if (!self.hitOk(h)) continue;if (seen.contains(h.off)) continue;seen.put(arena, h.off, {}) catch {};out.append(arena, .{ .off = h.off, .len = h.len }) catch return Error.OutOfMemory;}if (self.index_bad and !self.index_retry) {self.index_retry = true;defer self.index_retry = false;out.clearRetainingCapacity();return self.findRangeLocs(arena, field, from, to, out);}}/// delete by primary key. Returns the deleted records (decoded into arena).pub fn deletePk(self: *Db, arena: std.mem.Allocator, key: Key, out_records: *std.ArrayList(msgpack.Value)) Error!usize {try self.acquireLock();defer self.releaseLock();self.refresh();return self.deletePkLocked(arena, key, out_records);}fn deletePkLocked(self: *Db, arena: std.mem.Allocator, key: Key, out_records: *std.ArrayList(msgpack.Value)) Error!usize {var locs: std.ArrayList(Loc) = .empty;defer locs.deinit(arena);try self.findPkLocs(arena, key, &locs);for (locs.items) |loc| {const rec = try self.readAt(arena, loc);out_records.append(arena, rec) catch return Error.OutOfMemory;self.deleted.append(self.alloc, loc.off) catch return Error.OutOfMemory;self.delCacheAdd(loc.off);self.indexRemoveOffset(loc.off);}try self.persistMetaLocked();return locs.items.len;}/// update by primary key: delete + insert(skip_pk) — JS update() semantics./// `new_record` must already carry the primary key (the JS callback/// contract: the record keeps its pk unless the caller removes it).pub fn updatePk(self: *Db, arena: std.mem.Allocator, key: Key, new_record: msgpack.Value) Error!usize {if (self.pk) |p| {const carried = for (new_record.map) |e| {if (e.key == .str and std.mem.eql(u8, e.key.str, p)) break e.value != .nil and e.value != .undef;} else false;if (!carried) return Error.RecordLacksPrimaryKey;}try self.acquireLock();defer self.releaseLock();self.refresh();var old: std.ArrayList(msgpack.Value) = .empty;defer old.deinit(arena);
Only the first lines are shown.
Branches
Latest commits
- 39cf9fdfre-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
- db07aa84tests: short-id-switch ports from env (NOTES_SWITCH_IDENT_PORT/_PORT), defaults unchangedmre
- ef9f9feere-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
- 5485467cdocker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
- 86ea4a85deploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
- edeab20fnotes mission 015: mission, report, LOG, STATUSmre
- 542a0383notes mission 015: e2e-chrome E2E_HOST (own cookie jar in the shared Chrome)mre
- 8b30f510notes mission 015: main-menu from layouts 0bcc629, current = true kept (route marks only /), server-HTML marker checksmre
- 84b574c4notes mission 015: re-vendor plugins from hybriel f9614007 (incl. web, #117)mre
- 447da53dnotes mission 014: report — remaining gates and lisbeth E2E proofmre
- fd9f92c3notes mission 014: report (partial), LOG, STATUSmre
- b2501360notes mission 014: open() sets asking=false before flush(0) (hybriel#196)mre
- 9414ce59notes mission 014: merge theme 76f99f6, components 3794c59, strict single-press openAsk (fails on old open())mre
- c08c655anotes 013: theme re-copied from layouts 76f99f6 (menu marks the current page), current = true on the menu item, e2e marker checks, reportmre
- 21c8f65dnotes mission 012: STATUSmre
- 0bbb3dd9notes mission 012: delete section of the browser gate de-flaked (openAsk: calm wait, press again when the question closes by itself); report 012mre
- f431bdf8notes mission 011: notes on the layouts theme (ListFirst shell), styles cut, check-theme gate, E2E extended; reportmre
- 1a8603d1notes mission 011 WIP: deploy.sh gate summary also matches check-theme, browser.mjs logout via the user menumre
- dae2e508notes mission 011 WIP: theme dbe3de7, shell on AppHeader/MainMenu/UserMenu/Sidebar + ListFirst, styles cut to the app's own, check-theme gate, e2e auditmre
- fd36da27notes mission 010: the note editor is the Hybriel MdEditor block (components.hybriel 1442e58, verbatim); md-editor.js, its route, script tag and offlineFiles retired; gate 66/0, realdata-offline 12/0, round-trip and Chrome E2E tests; report 010mre