gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commita6dfd6eca6dfd6ecdeploy: person-lookup gate (tracker#46)mrea6dfd6ec/plugins/mpackdb/engine.zig

147.1 KB

  1. // mpackdb DB engine — Zig port of mpackdb v1.0.7 (MPackDB.js / IndexManager.js)
  2. // semantics. File-level compatible with the JS implementation (D12):
  3. //
  4. // <base>.mpack append-only records: [4-byte LE total size][msgpack map]
  5. // <base>.meta.json { nextId?, deleted:[offsets], version, schema? }
  6. // <base>.<field>.txt sorted index lines "key,offset,length\n"
  7. // <base>.idxstate.json { coveredBytes }
  8. // <base>.lock lock file containing the holder's pid (O_EXCL protocol,
  9. // stale takeover after staleLockTimeout ms)
  10. // <base>.flock (this engine only, ticket #176) the store lock: every open
  11. // handle holds a shared flock on it, compaction needs it
  12. // exclusive and is skipped without it; the last handle out
  13. // removes the file
  14. //
  15. // Ticket #176 additions the JS mpackdb ignores (it keeps unknown meta fields):
  16. // meta.json `dataFile` {ino, size, gen, deletedSum} and idxstate.json `dataIno`
  17. // name the data file they were written for, so tombstones and index offsets of
  18. // a replaced data file are never applied to the new one.
  19. //
  20. // Ticket 387 (a COPY of an open store must read back as the store): the inode alone
  21. // is not the identity of a data file, a hot tar or a restore gives the same bytes a
  22. // new inode. dataFile also carries `fp`, a fingerprint of the first `size` bytes
  23. // (hash of the first 4 KB + hash of the 4 KB before `size`), idxstate carries
  24. // `dataFp` for the first `coveredBytes`. Binding rule: same inode -> bound; another
  25. // inode and equal fingerprint -> bound (a copy); a file shorter than `size` or a
  26. // different fingerprint -> stale (another process's compaction); an old meta without
  27. // `fp` on another inode -> bound only if all its tombstones are plausible frame
  28. // starts. See applyMetaJson.
  29. //
  30. // Divergences from the JS implementation (documented in the 066 report):
  31. // - the in-memory index is the COMPLETE entry set (JS keeps on-disk + delta);
  32. // persist() writes the full set instead of read-merge-write. Sequential
  33. // cross-process use (close one side, open the other) behaves identically.
  34. // - string index keys sort bytewise (JS: String.localeCompare, ICU collation).
  35. // Equality lookups are unaffected; range ordering can differ for
  36. // mixed-case/accented keys.
  37. // - null field values are not indexed (JS indexes them under the key "null").
  38. // - a data file replaced while open (inode change, shrink, newer compaction
  39. // generation) is detected and re-indexed before the next read (#176).
  40. // - the JS mpackdb does not take the .flock store lock: its compaction can still
  41. // rewrite a file this engine has open (which then re-indexes), and this
  42. // engine's compaction cannot see a JS process that has the store open.
  43. // - a fresh `*id` table's first id is 1 (JS: 0) — ticket #4, see FIRST_ID.
  44. const std = @import("std");
  45. const linux = std.os.linux;
  46. const msgpack = @import("msgpack.zig");
  47. pub const PkType = enum(u8) { number = 0, uuid = 1, string = 2 };
  48. /// A `*id` table's first auto-increment id (ticket #4, the creator's ruling:
  49. /// "start at 1"). Only a table WITHOUT a stored counter starts here: a
  50. /// .meta.json that carries `nextId` — every existing table, including one the
  51. /// JS mpackdb wrote — keeps counting from it. The file format is unchanged;
  52. /// the JS mpackdb 1.0.7 starts a fresh table at 0, which is the one divergence.
  53. pub const FIRST_ID: f64 = 1;
  54. pub const IdxType = enum(u8) { lexical = 0, numeric = 1 };
  55. pub const Error = error{
  56. NoDbFile,
  57. NoPrimaryKey,
  58. /// mission 077 (074 GAP 10): a query named a field with no index. There is
  59. /// no index to binary-search and mpackdb does not silently full-scan, so
  60. /// the answer used to be an empty result — indistinguishable from "no such
  61. /// record". It is a mistake, and it says so now.
  62. NoSuchIndex,
  63. DuplicateKey,
  64. /// ticket #29: update()'s record must carry the primary key. Without it
  65. /// the old record was deleted, the new one written without a key, and the
  66. /// table left corrupt (fetch null, a unique index still finding it).
  67. RecordLacksPrimaryKey,
  68. LockTimeout,
  69. /// ticket #176: compaction found a frame it cannot vouch for (or a tombstone
  70. /// that names no frame) and rewrote nothing; last_error names the offset.
  71. CompactRefused,
  72. CorruptRecord,
  73. IoError,
  74. OutOfMemory,
  75. InvalidFormat,
  76. Truncated,
  77. MapTooLarge,
  78. };
  79. pub const Key = union(enum) {
  80. num: f64,
  81. str: []const u8,
  82. };
  83. pub const Entry = struct {
  84. key: Key,
  85. off: u64,
  86. len: u64,
  87. };
  88. const FieldIndex = struct {
  89. typ: IdxType,
  90. entries: std.ArrayList(Entry) = .empty, // sorted by (key, off)
  91. };
  92. pub const Loc = struct { off: u64, len: u64 };
  93. pub const Record = struct {
  94. value: msgpack.Value,
  95. off: u64,
  96. len: u64,
  97. };
  98. // =========================================================================
  99. // Low-level file IO (raw linux syscalls — plugins avoid std.Io plumbing)
  100. // =========================================================================
  101. const fio = struct {
  102. fn openz(alloc: std.mem.Allocator, path: []const u8, flags: linux.O, mode: u32) ?i32 {
  103. const path_z = alloc.dupeZ(u8, path) catch return null;
  104. defer alloc.free(path_z);
  105. const rc = linux.open(path_z, flags, mode);
  106. const fd: i32 = @bitCast(@as(u32, @truncate(rc)));
  107. if (fd < 0) return null;
  108. return fd;
  109. }
  110. fn openRead(alloc: std.mem.Allocator, path: []const u8) ?i32 {
  111. return openz(alloc, path, .{}, 0);
  112. }
  113. fn openAppend(alloc: std.mem.Allocator, path: []const u8) ?i32 {
  114. return openz(alloc, path, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, 0o644);
  115. }
  116. fn openTrunc(alloc: std.mem.Allocator, path: []const u8) ?i32 {
  117. return openz(alloc, path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, 0o644);
  118. }
  119. /// O_CREAT|O_EXCL — returns null when the file already exists.
  120. fn openExcl(alloc: std.mem.Allocator, path: []const u8) ?i32 {
  121. return openz(alloc, path, .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true }, 0o644);
  122. }
  123. fn close(fd: i32) void {
  124. _ = linux.close(fd);
  125. }
  126. fn fsync(fd: i32) bool {
  127. return linux.fsync(fd) == 0;
  128. }
  129. /// fsync the directory holding `path`, so a rename in it is durable.
  130. fn fsyncDir(alloc: std.mem.Allocator, path: []const u8) void {
  131. const dir = std.fs.path.dirname(path) orelse ".";
  132. const fd = openz(alloc, dir, .{ .DIRECTORY = true }, 0) orelse return;
  133. _ = linux.fsync(fd);
  134. close(fd);
  135. }
  136. fn writeAll(fd: i32, bytes: []const u8) bool {
  137. var written: usize = 0;
  138. while (written < bytes.len) {
  139. const rc = linux.write(fd, bytes.ptr + written, bytes.len - written);
  140. if (@as(isize, @bitCast(rc)) <= 0) return false;
  141. written += rc;
  142. }
  143. return true;
  144. }
  145. fn pread(fd: i32, buf: []u8, offset: u64) ?usize {
  146. var got: usize = 0;
  147. while (got < buf.len) {
  148. const rc = linux.pread(fd, buf.ptr + got, buf.len - got, @intCast(offset + got));
  149. const n: isize = @bitCast(rc);
  150. if (n < 0) return null;
  151. if (n == 0) break;
  152. got += @intCast(n);
  153. }
  154. return got;
  155. }
  156. fn readAll(alloc: std.mem.Allocator, path: []const u8) ?[]u8 {
  157. const fd = openRead(alloc, path) orelse return null;
  158. defer close(fd);
  159. var content: std.ArrayList(u8) = .empty;
  160. var buf: [65536]u8 = undefined;
  161. while (true) {
  162. const rc = linux.read(fd, &buf, buf.len);
  163. if (@as(isize, @bitCast(rc)) <= 0) break;
  164. content.appendSlice(alloc, buf[0..rc]) catch return null;
  165. }
  166. return content.toOwnedSlice(alloc) catch null;
  167. }
  168. fn fileSize(alloc: std.mem.Allocator, path: []const u8) ?u64 {
  169. const path_z = alloc.dupeZ(u8, path) catch return null;
  170. defer alloc.free(path_z);
  171. var stx: linux.Statx = undefined;
  172. const rc = linux.statx(linux.AT.FDCWD, path_z, 0, linux.STATX.BASIC_STATS, &stx);
  173. if (rc != 0) return null;
  174. return stx.size;
  175. }
  176. const Stat = struct { ino: u64, size: u64, mtime_ns: i128 = 0 };
  177. // flock(2) operations
  178. const LOCK_SH: i32 = 1;
  179. const LOCK_EX: i32 = 2;
  180. const LOCK_NB: i32 = 4;
  181. fn flock(fd: i32, op: i32) bool {
  182. return linux.flock(fd, op) == 0;
  183. }
  184. fn fdStat(fd: i32) ?Stat {
  185. var stx: linux.Statx = undefined;
  186. const rc = linux.statx(fd, "", 0x1000, linux.STATX.BASIC_STATS, &stx); // AT_EMPTY_PATH
  187. if (rc != 0) return null;
  188. return .{ .ino = stx.ino, .size = stx.size, .mtime_ns = @as(i128, stx.mtime.sec) * 1_000_000_000 + stx.mtime.nsec };
  189. }
  190. fn fdIno(fd: i32) ?u64 {
  191. return if (fdStat(fd)) |st| st.ino else null;
  192. }
  193. fn stat(alloc: std.mem.Allocator, path: []const u8) ?Stat {
  194. const path_z = alloc.dupeZ(u8, path) catch return null;
  195. defer alloc.free(path_z);
  196. var stx: linux.Statx = undefined;
  197. const rc = linux.statx(linux.AT.FDCWD, path_z, 0, linux.STATX.BASIC_STATS, &stx);
  198. if (rc != 0) return null;
  199. return .{ .ino = stx.ino, .size = stx.size, .mtime_ns = @as(i128, stx.mtime.sec) * 1_000_000_000 + stx.mtime.nsec };
  200. }
  201. fn mtimeMs(alloc: std.mem.Allocator, path: []const u8) ?i64 {
  202. const path_z = alloc.dupeZ(u8, path) catch return null;
  203. defer alloc.free(path_z);
  204. var stx: linux.Statx = undefined;
  205. const rc = linux.statx(linux.AT.FDCWD, path_z, 0, linux.STATX.BASIC_STATS, &stx);
  206. if (rc != 0) return null;
  207. return @as(i64, stx.mtime.sec) * 1000 + @divTrunc(@as(i64, stx.mtime.nsec), 1_000_000);
  208. }
  209. fn rename(alloc: std.mem.Allocator, old_path: []const u8, new_path: []const u8) bool {
  210. const old_z = alloc.dupeZ(u8, old_path) catch return false;
  211. defer alloc.free(old_z);
  212. const new_z = alloc.dupeZ(u8, new_path) catch return false;
  213. defer alloc.free(new_z);
  214. return linux.renameat(linux.AT.FDCWD, old_z, linux.AT.FDCWD, new_z) == 0;
  215. }
  216. fn unlink(alloc: std.mem.Allocator, path: []const u8) bool {
  217. const path_z = alloc.dupeZ(u8, path) catch return false;
  218. defer alloc.free(path_z);
  219. return linux.unlinkat(linux.AT.FDCWD, path_z, 0) == 0;
  220. }
  221. fn mkdirAll(alloc: std.mem.Allocator, dir_path: []const u8) void {
  222. if (dir_path.len == 0 or std.mem.eql(u8, dir_path, ".")) return;
  223. var i: usize = 1;
  224. while (i <= dir_path.len) : (i += 1) {
  225. if (i == dir_path.len or dir_path[i] == '/') {
  226. const part = alloc.dupeZ(u8, dir_path[0..i]) catch return;
  227. defer alloc.free(part);
  228. _ = linux.mkdirat(linux.AT.FDCWD, part, 0o755);
  229. }
  230. }
  231. }
  232. fn sleepMs(ms: u64) void {
  233. var req: linux.timespec = .{ .sec = @intCast(ms / 1000), .nsec = @intCast((ms % 1000) * 1_000_000) };
  234. var rem: linux.timespec = undefined;
  235. _ = linux.nanosleep(&req, &rem);
  236. }
  237. fn nowMs() i64 {
  238. var ts: linux.timespec = undefined;
  239. _ = linux.clock_gettime(linux.CLOCK.REALTIME, &ts);
  240. return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000);
  241. }
  242. };
  243. // =========================================================================
  244. // JS-compatible helpers
  245. // =========================================================================
  246. /// Format an f64 the way JS String(n) does for the values mpackdb produces:
  247. /// integral values print without a decimal point. (Exotic floats may diverge
  248. /// from V8's shortest-round-trip formatting; index keys are ints/strings in
  249. /// practice.)
  250. pub fn jsNumFmt(buf: []u8, v: f64) []const u8 {
  251. if (v == @floor(v) and @abs(v) <= 9007199254740992.0) {
  252. const i: i64 = @intFromFloat(v);
  253. return std.fmt.bufPrint(buf, "{d}", .{i}) catch buf[0..0];
  254. }
  255. return std.fmt.bufPrint(buf, "{d}", .{v}) catch buf[0..0];
  256. }
  257. /// JS parseInt(s, 10) semantics: optional sign, leading digits, ignore rest.
  258. /// Returns null for NaN.
  259. fn jsParseInt(s: []const u8) ?f64 {
  260. var i: usize = 0;
  261. while (i < s.len and (s[i] == ' ' or s[i] == '\t')) i += 1;
  262. var sign: f64 = 1;
  263. if (i < s.len and (s[i] == '+' or s[i] == '-')) {
  264. if (s[i] == '-') sign = -1;
  265. i += 1;
  266. }
  267. var got = false;
  268. var v: f64 = 0;
  269. while (i < s.len and s[i] >= '0' and s[i] <= '9') : (i += 1) {
  270. v = v * 10 + @as(f64, @floatFromInt(s[i] - '0'));
  271. got = true;
  272. }
  273. if (!got) return null;
  274. return sign * v;
  275. }
  276. /// _compareKeys: numbers numerically; otherwise stringified byte compare
  277. /// (JS uses localeCompare — see divergence note in the header).
  278. pub fn cmpKeys(a: Key, b: Key) i32 {
  279. if (a == .num and b == .num) {
  280. if (a.num < b.num) return -1;
  281. if (a.num > b.num) return 1;
  282. return 0;
  283. }
  284. var buf_a: [32]u8 = undefined;
  285. var buf_b: [32]u8 = undefined;
  286. const sa = if (a == .str) a.str else jsNumFmt(&buf_a, a.num);
  287. const sb = if (b == .str) b.str else jsNumFmt(&buf_b, b.num);
  288. return switch (std.mem.order(u8, sa, sb)) {
  289. .lt => -1,
  290. .eq => 0,
  291. .gt => 1,
  292. };
  293. }
  294. fn entryLess(_: void, a: Entry, b: Entry) bool {
  295. const c = cmpKeys(a.key, b.key);
  296. if (c != 0) return c < 0;
  297. return a.off < b.off;
  298. }
  299. /// mpack.js uuid(): 9-char base36 ms timestamp (padStart '0') + 3 base36 chars.
  300. pub fn genUuid(buf: *[12]u8) []const u8 {
  301. const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
  302. const t: u64 = @intCast(fio.nowMs());
  303. var tmp: [16]u8 = undefined;
  304. var n: usize = 0;
  305. var v = t;
  306. while (v > 0) : (v /= 36) {
  307. tmp[n] = digits[@intCast(v % 36)];
  308. n += 1;
  309. }
  310. var i: usize = 0;
  311. while (i < 9) : (i += 1) {
  312. buf[8 - i] = if (i < n) tmp[i] else '0';
  313. }
  314. if (!rng_init) {
  315. var ts: linux.timespec = undefined;
  316. _ = linux.clock_gettime(linux.CLOCK.MONOTONIC, &ts);
  317. rng = std.Random.DefaultPrng.init(@bitCast(@as(i64, ts.sec) *% 1_000_000_000 +% ts.nsec));
  318. rng_init = true;
  319. }
  320. var r = rng.random();
  321. for (0..3) |j| {
  322. buf[9 + j] = digits[r.uintLessThan(u8, 36)];
  323. }
  324. return buf[0..12];
  325. }
  326. var rng: std.Random.DefaultPrng = .{ .s = undefined };
  327. var rng_init: bool = false;
  328. // =========================================================================
  329. // The database
  330. // =========================================================================
  331. pub const OpenOptions = struct {
  332. primary_key: ?[]const u8 = null, // with */@/! prefixes, like the JS API
  333. indexes: []const []const u8 = &.{}, // with prefixes
  334. compact: bool = true,
  335. stale_lock_timeout_ms: i64 = 30000,
  336. debug: bool = false,
  337. };
  338. /// The identity of a table on disk (ticket #110): dirname + basename with any
  339. /// extension stripped, exactly the computation `Db.open` uses to turn a given
  340. /// path into `<base>.mpack` — so two spellings of the same file (`x.db`, `x`)
  341. /// share one key. The plugin ABI layer (mpackdb.zig) keys its process-wide
  342. /// handle registry on this, so a table opened twice in one process — from any
  343. /// module instance or realm — shares the one live `Db` instead of each open
  344. /// racing the other's file state.
  345. pub fn tableKey(alloc: std.mem.Allocator, db_file: []const u8) Error![]u8 {
  346. const dir = std.fs.path.dirname(db_file) orelse ".";
  347. var base = std.fs.path.basename(db_file);
  348. if (std.mem.lastIndexOfScalar(u8, base, '.')) |dot| {
  349. if (dot > 0) base = base[0..dot];
  350. }
  351. return std.fmt.allocPrint(alloc, "{s}/{s}", .{ dir, base }) catch Error.OutOfMemory;
  352. }
  353. /// The set of tombstoned offsets, shared and reference-counted (mission 393). The Db
  354. /// keeps ONE of it, built lazily from `deleted` and kept in step with every delete,
  355. /// so a lookup / range / scan no longer rebuilds an N-entry hash set per call. A scan
  356. /// that streams (a cursor) holds a reference to the set it started with: a later
  357. /// delete copies the set first (copy on write) and a compaction / foreign meta
  358. /// drops the Db's reference, so the cursor's view of the tombstones never changes.
  359. pub const DelSet = struct {
  360. map: std.AutoHashMapUnmanaged(u64, void) = .empty,
  361. refs: u32 = 1,
  362. alloc: std.mem.Allocator,
  363. pub fn release(self: *DelSet) void {
  364. self.refs -= 1;
  365. if (self.refs == 0) {
  366. const a = self.alloc;
  367. self.map.deinit(a);
  368. a.destroy(self);
  369. }
  370. }
  371. };
  372. pub const Db = struct {
  373. arena_state: std.heap.ArenaAllocator,
  374. alloc: std.mem.Allocator, // arena — freed wholesale on close
  375. // THE BUFFERS OF ONE OPERATION ARE NOT THE HANDLE'S (hybriel#126): the meta read
  376. // back and rendered anew, the index files, the paths. On the arena they stayed for
  377. // the handle's life, and the meta grows with every tombstone, so each update leaked
  378. // more than the last (notes: 2000 updates of one note, +100 MB). They are freed now.
  379. tmp: std.mem.Allocator,
  380. // paths
  381. data_path: []const u8,
  382. meta_path: []const u8,
  383. lock_path: []const u8,
  384. idxstate_path: []const u8,
  385. flock_path: []const u8 = "",
  386. /// THE STORE LOCK (ticket #176): every open handle holds a shared flock on
  387. /// `<base>.flock` for its whole life; a compaction needs it exclusive and
  388. /// skips when it cannot have it at once — another process has the store open,
  389. /// and rewriting the file under it is what lost the tracker its reads.
  390. store_fd: i32 = -1,
  391. // schema
  392. pk: ?[]const u8 = null,
  393. pk_type: PkType = .string,
  394. index_fields: std.ArrayList([]const u8) = .empty, // pk first (when set), like JS
  395. unique_fields: std.ArrayList([]const u8) = .empty,
  396. idx: std.StringArrayHashMapUnmanaged(FieldIndex) = .empty,
  397. // meta
  398. next_id: f64 = FIRST_ID,
  399. deleted: std.ArrayList(u64) = .empty,
  400. /// lazily built set of `deleted` (mission 393); null = not built / invalidated
  401. del_cache: ?*DelSet = null,
  402. /// an index entry named a place that is no frame of its size (a stale persisted index):
  403. /// the next refresh() rebuilds every index from the data file (mission 393)
  404. index_bad: bool = false,
  405. index_retry: bool = false,
  406. version: u64 = 0,
  407. // THE META NAMES ITS DATA FILE (ticket #176): `dataFile` in .meta.json is the
  408. // inode and size of the data file it was written for, the compaction
  409. // generation, and a checksum of its own `deleted` list. A meta whose data file
  410. // was replaced under it (a crash between the rename and the meta write) has
  411. // tombstones that point into the WRONG file — they are dropped, not applied.
  412. // The checksum tells our dataFile from one another writer carried along: the
  413. // JS mpackdb rewrites the meta as `{...meta}` and keeps fields it does not
  414. // know, so a `deleted` list it changed no longer matches the sum, and such a
  415. // meta is taken as it is (as before #176).
  416. bind_known: bool = false, // the meta on disk carries a dataFile that is ours and true
  417. bind_ino: u64 = 0,
  418. bind_size: u64 = 0,
  419. bind_fp: [16]u8 = undefined, // content fingerprint of the data file's first `bind_size` bytes
  420. bind_fp_len: u8 = 0, // 0 = none known (an old meta whose data file was not read)
  421. data_gen: u64 = 0,
  422. meta_stale: bool = false, // the loaded meta belonged to another data file
  423. idx_bind_known: bool = false, // the idxstate on disk names the data file's inode
  424. // the data file this handle's offsets are into (ticket #176): its inode and
  425. // the compaction generation; refresh() compares them on every operation
  426. seen_ino: u64 = 0,
  427. // THE FILE THE OFFSETS ARE INTO, held open (ticket #176): every read and scan
  428. // goes through it, never through the path — a rewrite renamed in between a
  429. // lookup and its read (the tracker parsed 1.4 MB of meta between the two)
  430. // then still reads the file the offsets belong to, and the next refresh()
  431. // moves the handle to the new one.
  432. data_fd: i32 = -1,
  433. // The meta file as THIS handle last read or wrote it (ticket #188): it is only ever
  434. // replaced by tmp + rename, so a write changes its inode; refresh() stats it and
  435. // skips the read + parse of a (1.4 MB on the tracker) meta that is unchanged.
  436. meta_seen: ?fio.Stat = null,
  437. meta_reads: u64 = 0, // reads of the meta file by loadMeta/refresh (the test counts them)
  438. bulk_index: bool = false, // indexInsertEntry appends (a sorted pass follows): rebuild / long catch-up
  439. covered_bytes: u64 = 0,
  440. compact_on_open: bool = true,
  441. stale_lock_timeout_ms: i64 = 30000,
  442. debug: bool = false,
  443. // last DuplicateKey detail for the plugin surface
  444. last_error_buf: [256]u8 = undefined,
  445. last_error: []const u8 = "",
  446. pub fn open(gpa: std.mem.Allocator, db_file: []const u8, opts: OpenOptions) Error!*Db {
  447. if (db_file.len == 0) return Error.NoDbFile;
  448. const self = gpa.create(Db) catch return Error.OutOfMemory;
  449. self.* = .{
  450. .arena_state = std.heap.ArenaAllocator.init(gpa),
  451. .alloc = undefined,
  452. .tmp = gpa,
  453. .data_path = undefined,
  454. .meta_path = undefined,
  455. .lock_path = undefined,
  456. .idxstate_path = undefined,
  457. };
  458. self.alloc = self.arena_state.allocator();
  459. errdefer {
  460. self.arena_state.deinit();
  461. gpa.destroy(self);
  462. }
  463. const a = self.alloc;
  464. self.compact_on_open = opts.compact;
  465. self.stale_lock_timeout_ms = opts.stale_lock_timeout_ms;
  466. self.debug = opts.debug;
  467. // dirname / basename (extension stripped, like JS basename(f, extname(f)))
  468. const dir = std.fs.path.dirname(db_file) orelse ".";
  469. var base = std.fs.path.basename(db_file);
  470. if (std.mem.lastIndexOfScalar(u8, base, '.')) |dot| {
  471. if (dot > 0) base = base[0..dot];
  472. }
  473. fio.mkdirAll(a, dir);
  474. self.data_path = std.fmt.allocPrint(a, "{s}/{s}.mpack", .{ dir, base }) catch return Error.OutOfMemory;
  475. self.meta_path = std.fmt.allocPrint(a, "{s}/{s}.meta.json", .{ dir, base }) catch return Error.OutOfMemory;
  476. self.lock_path = std.fmt.allocPrint(a, "{s}/{s}.lock", .{ dir, base }) catch return Error.OutOfMemory;
  477. self.idxstate_path = std.fmt.allocPrint(a, "{s}/{s}.idxstate.json", .{ dir, base }) catch return Error.OutOfMemory;
  478. self.flock_path = std.fmt.allocPrint(a, "{s}/{s}.flock", .{ dir, base }) catch return Error.OutOfMemory;
  479. try self.openStoreLock();
  480. errdefer self.closeStoreLock();
  481. // ---- parse primary key ----
  482. if (opts.primary_key) |pk_raw| {
  483. if (pk_raw.len > 0) {
  484. if (pk_raw[0] == '*') {
  485. self.pk = a.dupe(u8, pk_raw[1..]) catch return Error.OutOfMemory;
  486. self.pk_type = .number;
  487. } else if (pk_raw[0] == '@') {
  488. self.pk = a.dupe(u8, pk_raw[1..]) catch return Error.OutOfMemory;
  489. self.pk_type = .uuid;
  490. } else {
  491. self.pk = a.dupe(u8, pk_raw) catch return Error.OutOfMemory;
  492. self.pk_type = .string;
  493. }
  494. }
  495. }
  496. if (self.pk) |p| self.unique_fields.append(a, p) catch return Error.OutOfMemory;
  497. // ---- parse indexes (pk first, then configured; dedupe) ----
  498. if (self.pk) |p| {
  499. self.index_fields.append(a, p) catch return Error.OutOfMemory;
  500. const t: IdxType = if (self.pk_type == .number) .numeric else .lexical;
  501. self.idx.put(a, p, .{ .typ = t }) catch return Error.OutOfMemory;
  502. }
  503. for (opts.indexes) |raw| {
  504. var clean = raw;
  505. var is_unique = false;
  506. if (clean.len > 0 and clean[0] == '!') {
  507. is_unique = true;
  508. clean = clean[1..];
  509. }
  510. var typ: IdxType = .lexical;
  511. if (clean.len > 0 and clean[0] == '*') {
  512. typ = .numeric;
  513. clean = clean[1..];
  514. } else if (clean.len > 0 and clean[0] == '@') {
  515. clean = clean[1..];
  516. }
  517. if (self.idx.contains(clean)) continue;
  518. const owned = a.dupe(u8, clean) catch return Error.OutOfMemory;
  519. self.index_fields.append(a, owned) catch return Error.OutOfMemory;
  520. self.idx.put(a, owned, .{ .typ = typ }) catch return Error.OutOfMemory;
  521. if (is_unique) self.unique_fields.append(a, owned) catch return Error.OutOfMemory;
  522. }
  523. // ---- load meta ----
  524. self.loadMeta();
  525. // ---- compact on init (JS default; also creates an empty data file) ----
  526. // AN OPEN WITH NOTHING TO CHANGE WRITES NOTHING (ticket #21): a store
  527. // with no tombstones has nothing to compact, and rewriting it anyway
  528. // made opening a backup change it.
  529. var did_compact = false;
  530. const nothing_to_compact = self.deleted.items.len == 0 and
  531. fio.fileSize(self.tmp, self.data_path) != null;
  532. if (self.compact_on_open and !nothing_to_compact) {
  533. try self.acquireLock();
  534. const cr = if (self.tryExclusive()) blk: {
  535. defer self.backToShared();
  536. break :blk self.compactLocked();
  537. } else self.skipCompaction();
  538. self.releaseLock();
  539. // A REFUSED compaction does not fail the open (ticket #176): nothing
  540. // was rewritten, the store is as it was, and it stays readable; the
  541. // refusal is on stderr and in last_error.
  542. if (cr) |ran| {
  543. did_compact = ran;
  544. } else |e| {
  545. if (e != Error.CompactRefused) return e;
  546. }
  547. }
  548. self.adoptDataFile();
  549. errdefer self.dropDataFile();
  550. // ---- persist schema into meta (JS: init-schema under lock).
  551. // compactLocked already wrote meta (with schema); skip the extra bump.
  552. // A meta found to belong to another data file is replaced at once, so a
  553. // stale one never outlives the open that saw it (ticket #176).
  554. if (!did_compact and (self.meta_stale or ((self.pk != null or self.index_fields.items.len > 0) and
  555. !self.metaOnDiskIsCurrent())))
  556. {
  557. try self.acquireLock();
  558. const mr = self.persistMetaLocked();
  559. self.releaseLock();
  560. try mr;
  561. }
  562. // ---- indexes (JS: (re)build under the lock; force after compaction) ----
  563. if (self.index_fields.items.len > 0) {
  564. try self.acquireLock();
  565. const ir = self.initIndexes(did_compact);
  566. self.releaseLock();
  567. try ir;
  568. }
  569. return self;
  570. }
  571. pub fn close(self: *Db) void {
  572. // persist indexes + idxstate (JS: IndexManager.close → persist under lock)
  573. if (self.index_fields.items.len > 0) {
  574. if (self.acquireLock()) {
  575. // MISSION 395 (#203): the index in memory is of the data file this handle holds. Another
  576. // process (the JS mpackdb, a build before #176: none takes the store lock) may have
  577. // rewritten it since; persisting before looking wrote that old generation's offsets
  578. // as the index files — beside an idxstate that named the NEW file.
  579. self.refresh();
  580. self.persistIndexesLocked() catch {};
  581. self.releaseLock();
  582. } else |_| {}
  583. }
  584. self.dropDataFile();
  585. self.delCacheDrop();
  586. self.closeStoreLock();
  587. const gpa = self.arena_state.child_allocator;
  588. self.arena_state.deinit();
  589. gpa.destroy(self);
  590. }
  591. fn dbg(self: *Db, comptime fmt: []const u8, args: anytype) void {
  592. if (self.debug) std.debug.print("[mpackdb] " ++ fmt ++ "\n", args);
  593. }
  594. // =====================================================================
  595. // Locking (JS _acquireFileLock protocol)
  596. // =====================================================================
  597. fn acquireLock(self: *Db) Error!void {
  598. var retries: u32 = 0;
  599. while (true) {
  600. if (fio.openExcl(self.tmp, self.lock_path)) |fd| {
  601. var pid_buf: [16]u8 = undefined;
  602. const pid_s = std.fmt.bufPrint(&pid_buf, "{d}", .{linux.getpid()}) catch "0";
  603. _ = fio.writeAll(fd, pid_s);
  604. fio.close(fd);
  605. return;
  606. }
  607. // stale lock takeover
  608. if (self.stale_lock_timeout_ms > 0) {
  609. if (fio.mtimeMs(self.tmp, self.lock_path)) |mt| {
  610. if (fio.nowMs() - mt > self.stale_lock_timeout_ms) {
  611. _ = fio.unlink(self.tmp, self.lock_path);
  612. continue;
  613. }
  614. }
  615. }
  616. if (retries > 480) return Error.LockTimeout; // ~12s at 25ms
  617. fio.sleepMs(25);
  618. retries += 1;
  619. }
  620. }
  621. fn releaseLock(self: *Db) void {
  622. _ = fio.unlink(self.tmp, self.lock_path);
  623. }
  624. /// Take the shared store lock. The lock file is unlinked by the last handle
  625. /// to close (under the exclusive lock), so a lock taken on a file that is no
  626. /// longer the one at the path is let go and taken anew.
  627. fn openStoreLock(self: *Db) Error!void {
  628. var tries: usize = 0;
  629. while (tries < 1000) : (tries += 1) {
  630. const fd = fio.openz(self.tmp, self.flock_path, .{ .ACCMODE = .RDWR, .CREAT = true, .CLOEXEC = true }, 0o644) orelse return Error.IoError;
  631. if (!fio.flock(fd, fio.LOCK_SH)) {
  632. fio.close(fd);
  633. return Error.IoError;
  634. }
  635. const held = fio.fdIno(fd);
  636. const at_path = fio.stat(self.tmp, self.flock_path);
  637. if (held != null and at_path != null and held.? == at_path.?.ino) {
  638. self.store_fd = fd;
  639. return;
  640. }
  641. fio.close(fd);
  642. }
  643. return Error.LockTimeout;
  644. }
  645. fn closeStoreLock(self: *Db) void {
  646. if (self.store_fd < 0) return;
  647. // the last one out removes the lock file — only while no one else holds it
  648. if (fio.flock(self.store_fd, fio.LOCK_EX | fio.LOCK_NB)) _ = fio.unlink(self.tmp, self.flock_path);
  649. fio.close(self.store_fd);
  650. self.store_fd = -1;
  651. }
  652. /// Exclusive, without waiting: true when no other handle (in any process)
  653. /// holds the store.
  654. fn tryExclusive(self: *Db) bool {
  655. if (self.store_fd < 0) return false;
  656. if (fio.flock(self.store_fd, fio.LOCK_EX | fio.LOCK_NB)) return true;
  657. // a failed conversion may have given up the shared lock: take it again
  658. _ = fio.flock(self.store_fd, fio.LOCK_SH);
  659. return false;
  660. }
  661. fn backToShared(self: *Db) void {
  662. if (self.store_fd >= 0) _ = fio.flock(self.store_fd, fio.LOCK_SH);
  663. }
  664. fn skipCompaction(self: *Db) Error!bool {
  665. self.last_error = "compaction skipped: the store is open in another process";
  666. self.dbg("{s}: {s}", .{ self.data_path, self.last_error });
  667. return false;
  668. }
  669. // =====================================================================
  670. // Meta (.meta.json)
  671. // =====================================================================
  672. fn appendFmt(self: *Db, list: *std.ArrayList(u8), comptime fmt: []const u8, args: anytype) Error!void {
  673. const s = std.fmt.allocPrint(self.tmp, fmt, args) catch return Error.OutOfMemory;
  674. defer self.tmp.free(s);
  675. list.appendSlice(self.tmp, s) catch return Error.OutOfMemory;
  676. }
  677. fn loadMeta(self: *Db) void {
  678. // stat BEFORE the read: a write racing in between then shows as a change next time
  679. self.meta_seen = fio.stat(self.tmp, self.meta_path);
  680. self.meta_reads += 1;
  681. const content = fio.readAll(self.tmp, self.meta_path) orelse return;
  682. defer self.tmp.free(content);
  683. self.applyMetaJson(content);
  684. }
  685. fn applyMetaJson(self: *Db, content: []const u8) void {
  686. const parsed = std.json.parseFromSlice(std.json.Value, self.tmp, content, .{}) catch return;
  687. defer parsed.deinit();
  688. if (parsed.value != .object) return;
  689. const obj = parsed.value.object;
  690. self.next_id = FIRST_ID;
  691. self.deleted.clearRetainingCapacity();
  692. self.delCacheDrop();
  693. self.version = 0;
  694. if (obj.get("nextId")) |v| {
  695. self.next_id = switch (v) {
  696. .integer => |i| @floatFromInt(i),
  697. .float => |f| f,
  698. else => FIRST_ID,
  699. };
  700. }
  701. if (obj.get("version")) |v| {
  702. if (v == .integer) self.version = @intCast(@max(v.integer, 0));
  703. }
  704. if (obj.get("deleted")) |v| {
  705. if (v == .array) {
  706. for (v.array.items) |it| {
  707. const off: u64 = switch (it) {
  708. .integer => |i| @intCast(@max(i, 0)),
  709. .float => |f| @intFromFloat(@max(f, 0)),
  710. else => continue,
  711. };
  712. self.deleted.append(self.alloc, off) catch {};
  713. }
  714. }
  715. }
  716. self.bind_known = false;
  717. self.meta_stale = false;
  718. const df_v = obj.get("dataFile") orelse return;
  719. if (df_v != .object) return;
  720. const df = df_v.object;
  721. const ino = jsonU64(df.get("ino")) orelse return;
  722. const size = jsonU64(df.get("size")) orelse return;
  723. if (jsonU64(df.get("gen"))) |g| self.data_gen = @max(self.data_gen, g);
  724. const sum_v = df.get("deletedSum") orelse return;
  725. if (sum_v != .string) return;
  726. var sum_buf: [16]u8 = undefined;
  727. if (!std.mem.eql(u8, sum_v.string, self.deletedSum(&sum_buf))) return; // another writer's
  728. const cur = fio.stat(self.tmp, self.data_path);
  729. // THE BINDING RULE (ticket 387, after #176): the inode is the fast path, the
  730. // content is the proof. A byte COPY of an open store (a hot tar, a deploy
  731. // backup, a restore) has a new inode but the same bytes, and its meta must
  732. // still apply — its tombstones and newer versions are the store's truth.
  733. // - same inode, file at least `size` bytes: bound (as in #176).
  734. // - file shorter than `size`, or gone: stale (a different file).
  735. // - another inode, meta carries `fp` (fingerprint of the first and last
  736. // 4 KB of the first `size` bytes): bound if the file's fingerprint over
  737. // that range equals it (the same content, copied or restored); a data
  738. // file a compaction replaced differs in content, so it stays stale.
  739. // - another inode, an OLD meta without `fp`: bound only if every tombstone
  740. // offset is a plausible frame start in the file (size > 4, fits, and the
  741. // next frame's header is plausible or EOF). Else stale.
  742. var bound = false;
  743. var fp_buf: [16]u8 = undefined;
  744. var have_fp: ?[]const u8 = null;
  745. if (cur) |c| {
  746. if (c.size >= size) {
  747. if (c.ino == ino) {
  748. bound = true;
  749. } else if (obj.get("dataFile").?.object.get("fp")) |fv| {
  750. if (fv == .string) {
  751. have_fp = self.dataFingerprint(size, &fp_buf);
  752. bound = have_fp != null and std.mem.eql(u8, have_fp.?, fv.string);
  753. }
  754. } else {
  755. bound = self.tombstonesAreFrameStarts(c.size);
  756. }
  757. }
  758. } else bound = size == 0;
  759. if (!bound) {
  760. if (self.deleted.items.len > 0) {
  761. 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 });
  762. }
  763. self.deleted.clearRetainingCapacity();
  764. self.delCacheDrop();
  765. self.meta_stale = true;
  766. return;
  767. }
  768. self.bind_known = true;
  769. self.bind_ino = if (cur) |c| c.ino else ino; // a copy: this file's inode from now on
  770. self.bind_size = size;
  771. self.bind_fp_len = 0;
  772. if (have_fp == null) have_fp = self.dataFingerprint(size, &fp_buf);
  773. if (have_fp) |f| {
  774. @memcpy(self.bind_fp[0..f.len], f);
  775. self.bind_fp_len = @intCast(f.len);
  776. }
  777. }
  778. /// Fingerprint (16 hex chars) of the first `n` bytes of the data file: a hash of
  779. /// its first 4 KB and one of the 4 KB before `n`. Appends past `n` do not change
  780. /// it; a replaced (compacted) file, with other records at those places, does.
  781. fn dataFingerprint(self: *Db, n: u64, buf: *[16]u8) ?[]const u8 {
  782. const fd = fio.openRead(self.tmp, self.data_path) orelse return null;
  783. defer fio.close(fd);
  784. return fingerprintFd(fd, n, buf);
  785. }
  786. fn fingerprintFd(fd: i32, n: u64, buf: *[16]u8) ?[]const u8 {
  787. var h = std.hash.Wyhash.init(387);
  788. var blk: [4096]u8 = undefined;
  789. const head: usize = @intCast(@min(n, 4096));
  790. const got = fio.pread(fd, blk[0..head], 0) orelse return null;
  791. if (got != head) return null;
  792. h.update(blk[0..head]);
  793. const tail_off = n - head;
  794. const got2 = fio.pread(fd, blk[0..head], tail_off) orelse return null;
  795. if (got2 != head) return null;
  796. h.update(blk[0..head]);
  797. return std.fmt.bufPrint(buf, "{x:0>16}", .{h.final()}) catch null;
  798. }
  799. /// An old meta (no fingerprint) beside a file of another inode: are its tombstones
  800. /// frame starts of this file? A frame start has a size > 4 that fits in the file,
  801. /// and is followed by EOF or another plausible frame header.
  802. fn tombstonesAreFrameStarts(self: *Db, file_size: u64) bool {
  803. const fd = fio.openRead(self.tmp, self.data_path) orelse return self.deleted.items.len == 0;
  804. defer fio.close(fd);
  805. for (self.deleted.items) |off| {
  806. if (!frameHeaderOk(fd, off, file_size)) return false;
  807. var hdr: [4]u8 = undefined;
  808. _ = fio.pread(fd, &hdr, off);
  809. const next = off + std.mem.readInt(u32, &hdr, .little);
  810. if (next != file_size and !frameHeaderOk(fd, next, file_size)) return false;
  811. }
  812. return true;
  813. }
  814. fn frameHeaderOk(fd: i32, off: u64, file_size: u64) bool {
  815. if (off + 4 > file_size) return false;
  816. var hdr: [4]u8 = undefined;
  817. const got = fio.pread(fd, &hdr, off) orelse return false;
  818. if (got < 4) return false;
  819. const sz: u64 = std.mem.readInt(u32, &hdr, .little);
  820. return sz > 4 and off + sz <= file_size;
  821. }
  822. fn jsonU64(v: ?std.json.Value) ?u64 {
  823. const x = v orelse return null;
  824. return switch (x) {
  825. .integer => |i| if (i < 0) null else @intCast(i),
  826. else => null,
  827. };
  828. }
  829. /// The checksum of the deleted list (hex), as dataFile.deletedSum carries it.
  830. fn deletedSum(self: *Db, buf: *[16]u8) []const u8 {
  831. var h = std.hash.Wyhash.init(176);
  832. for (self.deleted.items) |off| {
  833. var b: [8]u8 = undefined;
  834. std.mem.writeInt(u64, &b, off, .little);
  835. h.update(&b);
  836. }
  837. return std.fmt.bufPrint(buf, "{x:0>16}", .{h.final()}) catch buf[0..0];
  838. }
  839. /// Pick up other processes' persisted state (JS refresh()): adopt disk meta
  840. /// when its version is newer; index appended tail records.
  841. ///
  842. /// A HANDLE NOTICES A REWRITE (ticket #176). Another process's compaction
  843. /// replaces the data file and moves every record after its first tombstone;
  844. /// this handle's offsets are then into a file that no longer exists, and
  845. /// reading them read the middle of other records — a bare Number where a
  846. /// record was (the tracker, 2026-10-20). The data file's inode, a size below
  847. /// what was indexed, or a newer compaction generation in the meta says it
  848. /// happened; the handle then re-reads the meta (dropping a deleted list that
  849. /// belongs to the old file) and re-indexes the new file before it answers.
  850. pub fn refresh(self: *Db) void {
  851. if (self.data_fd < 0) self.adoptDataFile(); // a file created since the open
  852. if (self.index_bad) self.rebuildIndexesFromData();
  853. const cur = fio.stat(self.tmp, self.data_path);
  854. var rewritten = false;
  855. if (cur) |c| {
  856. if (self.seen_ino != 0 and c.ino != self.seen_ino) rewritten = true;
  857. if (self.index_fields.items.len > 0 and c.size < self.covered_bytes) rewritten = true;
  858. }
  859. const meta_now = fio.stat(self.tmp, self.meta_path);
  860. 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;
  861. // an unchanged meta says nothing new: its version and generation were taken when read
  862. // (a rewritten data file still re-reads it, to drop a deleted list of the old file)
  863. if (meta_same and !rewritten) {
  864. // nothing to read
  865. } else if (blk: {
  866. self.meta_seen = meta_now;
  867. self.meta_reads += 1;
  868. break :blk fio.readAll(self.tmp, self.meta_path);
  869. }) |content| {
  870. defer self.tmp.free(content);
  871. const parsed = std.json.parseFromSlice(std.json.Value, self.tmp, content, .{}) catch return;
  872. defer parsed.deinit();
  873. if (parsed.value == .object) {
  874. var disk_version: u64 = 0;
  875. if (parsed.value.object.get("version")) |v| {
  876. if (v == .integer) disk_version = @intCast(@max(v.integer, 0));
  877. }
  878. if (parsed.value.object.get("dataFile")) |df| {
  879. if (df == .object) {
  880. if (jsonU64(df.object.get("gen"))) |g| {
  881. if (g > self.data_gen) rewritten = true;
  882. }
  883. }
  884. }
  885. if (rewritten or disk_version > self.version) self.applyMetaJson(content);
  886. }
  887. }
  888. if (rewritten) {
  889. self.reindexRewritten();
  890. return;
  891. }
  892. // catchUp: index records another process appended
  893. if (self.index_fields.items.len > 0) {
  894. const size = if (cur) |c| c.size else 0;
  895. if (size > self.covered_bytes) self.catchUp(size);
  896. }
  897. }
  898. /// THE INDEX NAMED A PLACE THAT IS NO RECORD (mission 393): the tracker's persons.id.txt
  899. /// carried ~2100 entries with offsets past the end of the data file or into the middle of a
  900. /// frame (entries of an older generation of the file), so range('id', …) answered a Number
  901. /// where a record was ("reading 'id': the value is Number"). A hit is checked against its
  902. /// frame header before it is returned; a bad one is dropped and the indexes are rebuilt from
  903. /// the data file at the next refresh.
  904. fn hitOk(self: *Db, h: Entry) bool {
  905. if (self.data_fd < 0) return true;
  906. var hdr: [4]u8 = undefined;
  907. const got = fio.pread(self.data_fd, &hdr, h.off) orelse 0;
  908. if (got == 4 and std.mem.readInt(u32, &hdr, .little) == h.len) return true;
  909. self.index_bad = true;
  910. return false;
  911. }
  912. fn rebuildIndexesFromData(self: *Db) void {
  913. self.index_bad = false;
  914. self.covered_bytes = 0;
  915. var it0 = self.idx.iterator();
  916. while (it0.next()) |kv| kv.value_ptr.entries.clearRetainingCapacity();
  917. if (self.index_fields.items.len > 0) {
  918. const size: u64 = if (self.data_fd >= 0) (if (fio.fdStat(self.data_fd)) |st| st.size else 0) else 0;
  919. self.catchUp(size);
  920. }
  921. std.debug.print("mpackdb: {s}: an index named a place that is no record; indexes rebuilt from the data file\n", .{self.data_path});
  922. }
  923. /// The data file was replaced under this handle: index it anew, in memory —
  924. /// the index files are written when the handle persists or closes.
  925. fn reindexRewritten(self: *Db) void {
  926. const old_ino = self.seen_ino;
  927. self.adoptDataFile();
  928. 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 });
  929. self.covered_bytes = 0;
  930. var it0 = self.idx.iterator();
  931. while (it0.next()) |kv| kv.value_ptr.entries.clearRetainingCapacity();
  932. if (self.index_fields.items.len > 0) {
  933. const size: u64 = if (self.data_fd >= 0) (if (fio.fdStat(self.data_fd)) |st| st.size else 0) else 0;
  934. self.catchUp(size);
  935. }
  936. }
  937. /// Hold the data file now at the path; its inode is what the offsets are into.
  938. fn adoptDataFile(self: *Db) void {
  939. self.dropDataFile();
  940. self.data_fd = fio.openz(self.tmp, self.data_path, .{ .CLOEXEC = true }, 0) orelse -1;
  941. self.seen_ino = if (self.data_fd >= 0) (fio.fdIno(self.data_fd) orelse 0) else 0;
  942. }
  943. fn dropDataFile(self: *Db) void {
  944. if (self.data_fd >= 0) fio.close(self.data_fd);
  945. self.data_fd = -1;
  946. }
  947. fn persistMetaLocked(self: *Db) Error!void {
  948. self.version += 1;
  949. const cur = fio.stat(self.tmp, self.data_path);
  950. self.bind_ino = if (cur) |c| c.ino else 0;
  951. self.bind_size = if (cur) |c| c.size else 0;
  952. self.bind_fp_len = 0;
  953. var fpb: [16]u8 = undefined;
  954. if (self.dataFingerprint(self.bind_size, &fpb)) |f| {
  955. @memcpy(self.bind_fp[0..f.len], f);
  956. self.bind_fp_len = @intCast(f.len);
  957. }
  958. self.bind_known = true;
  959. self.meta_stale = false;
  960. var out: std.ArrayList(u8) = .empty;
  961. defer out.deinit(self.tmp);
  962. try self.renderMeta(&out);
  963. // atomic tmp + rename (JS: `${metaPath}.${pid}.tmp`)
  964. var tmp_buf: [512]u8 = undefined;
  965. const tmp_path = std.fmt.bufPrint(&tmp_buf, "{s}.{d}.tmp", .{ self.meta_path, linux.getpid() }) catch return Error.IoError;
  966. const fd = fio.openTrunc(self.tmp, tmp_path) orelse return Error.IoError;
  967. const ok = fio.writeAll(fd, out.items);
  968. // the tmp file's own stat: rename keeps the inode, and no other writer can slip in
  969. // between a stat of the path and our remembering it (ticket #188)
  970. const written = fio.fdStat(fd);
  971. fio.close(fd);
  972. if (!ok) return Error.IoError;
  973. if (!fio.rename(self.tmp, tmp_path, self.meta_path)) return Error.IoError;
  974. self.meta_seen = written;
  975. }
  976. /// Does .meta.json already say, byte for byte, what this handle would write
  977. /// at its current version? Then an open has nothing to persist (ticket #21).
  978. fn metaOnDiskIsCurrent(self: *Db) bool {
  979. const disk = fio.readAll(self.tmp, self.meta_path) orelse return false;
  980. defer self.tmp.free(disk);
  981. var out: std.ArrayList(u8) = .empty;
  982. defer out.deinit(self.tmp);
  983. self.renderMeta(&out) catch return false;
  984. return std.mem.eql(u8, disk, out.items);
  985. }
  986. fn renderMeta(self: *Db, out: *std.ArrayList(u8)) Error!void {
  987. try self.appendFmt(out, "{{", .{});
  988. if (self.pk != null and self.pk_type == .number) {
  989. var nbuf: [32]u8 = undefined;
  990. try self.appendFmt(out, "\"nextId\":{s},", .{jsNumFmt(&nbuf, self.next_id)});
  991. }
  992. try self.appendFmt(out, "\"deleted\":[", .{});
  993. for (self.deleted.items, 0..) |off, i| {
  994. if (i > 0) try self.appendFmt(out, ",", .{});
  995. try self.appendFmt(out, "{d}", .{off});
  996. }
  997. try self.appendFmt(out, "],\"version\":{d}", .{self.version});
  998. if (self.pk != null or self.index_fields.items.len > 0) {
  999. try self.appendFmt(out, ",\"schema\":{{", .{});
  1000. var first = true;
  1001. if (self.pk) |p| {
  1002. const prefix: []const u8 = switch (self.pk_type) {
  1003. .number => "*",
  1004. .uuid => "@",
  1005. .string => "",
  1006. };
  1007. try self.appendFmt(out, "\"primaryKey\":\"{s}{s}\"", .{ prefix, p });
  1008. first = false;
  1009. }
  1010. if (!first) try self.appendFmt(out, ",", .{});
  1011. try self.appendFmt(out, "\"indexes\":[", .{});
  1012. var n: usize = 0;
  1013. for (self.index_fields.items) |field| {
  1014. if (self.pk != null and std.mem.eql(u8, field, self.pk.?)) continue;
  1015. if (n > 0) try self.appendFmt(out, ",", .{});
  1016. const uni = for (self.unique_fields.items) |u| {
  1017. if (std.mem.eql(u8, u, field)) break true;
  1018. } else false;
  1019. const numeric = (self.idx.get(field) orelse FieldIndex{ .typ = .lexical }).typ == .numeric;
  1020. try self.appendFmt(out, "\"{s}{s}{s}\"", .{
  1021. if (uni) "!" else "",
  1022. if (numeric) "*" else "",
  1023. field,
  1024. });
  1025. n += 1;
  1026. }
  1027. try self.appendFmt(out, "]}}", .{});
  1028. }
  1029. if (self.bind_known) {
  1030. var sum_buf: [16]u8 = undefined;
  1031. 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) });
  1032. if (self.bind_fp_len > 0) try self.appendFmt(out, ",\"fp\":\"{s}\"", .{self.bind_fp[0..self.bind_fp_len]});
  1033. try self.appendFmt(out, "}}", .{});
  1034. }
  1035. try self.appendFmt(out, "}}", .{});
  1036. }
  1037. // =====================================================================
  1038. // Data file scanning
  1039. // =====================================================================
  1040. fn deletedSet(self: *Db, alloc: std.mem.Allocator) std.AutoHashMapUnmanaged(u64, void) {
  1041. var set: std.AutoHashMapUnmanaged(u64, void) = .empty;
  1042. for (self.deleted.items) |off| set.put(alloc, off, {}) catch {};
  1043. return set;
  1044. }
  1045. /// The cached tombstone set, built on first use (borrowed: valid until the next
  1046. /// delete / meta adoption / compaction; hold it with delSetAcquire to keep it).
  1047. fn delSetCached(self: *Db) *DelSet {
  1048. if (self.del_cache) |c| return c;
  1049. const c = self.tmp.create(DelSet) catch unreachable;
  1050. c.* = .{ .alloc = self.tmp };
  1051. c.map.ensureTotalCapacity(self.tmp, @intCast(self.deleted.items.len)) catch {};
  1052. for (self.deleted.items) |off| c.map.put(self.tmp, off, {}) catch {};
  1053. self.del_cache = c;
  1054. return c;
  1055. }
  1056. /// A reference the caller must release() — a frozen view of the tombstones.
  1057. pub fn delSetAcquire(self: *Db) *DelSet {
  1058. const c = self.delSetCached();
  1059. c.refs += 1;
  1060. return c;
  1061. }
  1062. fn delCacheDrop(self: *Db) void {
  1063. if (self.del_cache) |c| c.release();
  1064. self.del_cache = null;
  1065. }
  1066. fn delCacheAdd(self: *Db, off: u64) void {
  1067. const c = self.del_cache orelse return;
  1068. if (c.refs > 1) {
  1069. // a cursor holds this set: it keeps it unchanged, the Db goes on with a copy
  1070. const n = self.tmp.create(DelSet) catch {
  1071. self.delCacheDrop();
  1072. return;
  1073. };
  1074. n.* = .{ .alloc = self.tmp };
  1075. n.map = c.map.clone(self.tmp) catch {
  1076. self.tmp.destroy(n);
  1077. self.delCacheDrop();
  1078. return;
  1079. };
  1080. c.release();
  1081. self.del_cache = n;
  1082. }
  1083. self.del_cache.?.map.put(self.tmp, off, {}) catch self.delCacheDrop();
  1084. }
  1085. /// Sequential scan yielding all live records. Caller supplies an arena for
  1086. /// decoded values. Used for rebuilds, compaction and unindexed finds.
  1087. pub const Scanner = struct {
  1088. db: *Db,
  1089. fd: i32 = -1,
  1090. offset: u64 = 0,
  1091. size: u64 = 0,
  1092. skip_deleted: bool = true,
  1093. owns_fd: bool = true,
  1094. /// a frozen view of the tombstones (null when !skip_deleted); released by deinit
  1095. deleted_set: ?*DelSet = null,
  1096. scratch: std.mem.Allocator,
  1097. pub fn init(db: *Db, scratch: std.mem.Allocator, skip_deleted: bool) Scanner {
  1098. return initOpt(db, scratch, skip_deleted, false);
  1099. }
  1100. /// `detached` (a streaming cursor): the scanner dup()s the data fd, so a compaction
  1101. /// or a foreign rewrite that makes the Db move to a new file leaves the scan reading
  1102. /// the file it started on; it also freezes the size and the tombstones (mission 393).
  1103. pub fn initOpt(db: *Db, scratch: std.mem.Allocator, skip_deleted: bool, detached: bool) Scanner {
  1104. var s = Scanner{ .db = db, .scratch = scratch, .skip_deleted = skip_deleted };
  1105. if (db.data_fd >= 0) {
  1106. // the file the handle's offsets are into (#176), not whatever is at the path
  1107. if (detached) {
  1108. const rc = linux.dup(db.data_fd);
  1109. const nfd: i32 = @bitCast(@as(u32, @truncate(rc)));
  1110. if (nfd >= 0) {
  1111. s.fd = nfd;
  1112. s.owns_fd = true;
  1113. } else {
  1114. s.fd = db.data_fd;
  1115. s.owns_fd = false;
  1116. }
  1117. } else {
  1118. s.fd = db.data_fd;
  1119. s.owns_fd = false;
  1120. }
  1121. s.size = if (fio.fdStat(s.fd)) |st| st.size else 0;
  1122. } else {
  1123. s.size = fio.fileSize(scratch, db.data_path) orelse 0;
  1124. if (s.size > 0) {
  1125. s.fd = fio.openRead(scratch, db.data_path) orelse -1;
  1126. }
  1127. }
  1128. if (skip_deleted) s.deleted_set = db.delSetAcquire();
  1129. return s;
  1130. }
  1131. pub fn deinit(self: *Scanner) void {
  1132. if (self.fd >= 0 and self.owns_fd) fio.close(self.fd);
  1133. self.fd = -1;
  1134. if (self.deleted_set) |d| d.release();
  1135. self.deleted_set = null;
  1136. }
  1137. /// Returns the next record (decoded into `arena`) or null at EOF.
  1138. pub fn next(self: *Scanner, arena: std.mem.Allocator) Error!?Record {
  1139. while (true) {
  1140. if (self.fd < 0 or self.offset + 4 > self.size) return null;
  1141. var hdr: [4]u8 = undefined;
  1142. const got = fio.pread(self.fd, &hdr, self.offset) orelse return Error.IoError;
  1143. if (got < 4) return null;
  1144. const rec_size = std.mem.readInt(u32, &hdr, .little);
  1145. if (rec_size <= 4) return Error.CorruptRecord;
  1146. if (self.offset + rec_size > self.size) return null; // incomplete tail
  1147. const off = self.offset;
  1148. self.offset += rec_size;
  1149. if (self.deleted_set) |d| {
  1150. if (d.map.contains(off)) continue;
  1151. }
  1152. const buf = arena.alloc(u8, rec_size - 4) catch return Error.OutOfMemory;
  1153. const got2 = fio.pread(self.fd, buf, off + 4) orelse return Error.IoError;
  1154. if (got2 < rec_size - 4) return Error.Truncated;
  1155. const d = msgpack.decode(arena, buf) catch return Error.CorruptRecord;
  1156. return Record{ .value = d.value, .off = off, .len = rec_size };
  1157. }
  1158. }
  1159. /// The number of live records from here on, reading only the 4-byte frame headers:
  1160. /// nothing is decoded or kept (count() decoded the whole table into an arena, 2 GB
  1161. /// for the tracker's two big tables).
  1162. pub fn countLive(self: *Scanner) Error!usize {
  1163. var n: usize = 0;
  1164. while (true) {
  1165. if (self.fd < 0 or self.offset + 4 > self.size) return n;
  1166. var hdr: [4]u8 = undefined;
  1167. const got = fio.pread(self.fd, &hdr, self.offset) orelse return Error.IoError;
  1168. if (got < 4) return n;
  1169. const rec_size = std.mem.readInt(u32, &hdr, .little);
  1170. if (rec_size <= 4) return Error.CorruptRecord;
  1171. if (self.offset + rec_size > self.size) return n;
  1172. const off = self.offset;
  1173. self.offset += rec_size;
  1174. if (self.deleted_set) |d| {
  1175. if (d.map.contains(off)) continue;
  1176. }
  1177. n += 1;
  1178. }
  1179. }
  1180. /// Like next() but without decoding — yields the raw framed bytes.
  1181. pub fn nextRaw(self: *Scanner, arena: std.mem.Allocator) Error!?struct { bytes: []u8, off: u64 } {
  1182. while (true) {
  1183. if (self.fd < 0 or self.offset + 4 > self.size) return null;
  1184. var hdr: [4]u8 = undefined;
  1185. const got = fio.pread(self.fd, &hdr, self.offset) orelse return Error.IoError;
  1186. if (got < 4) return null;
  1187. const rec_size = std.mem.readInt(u32, &hdr, .little);
  1188. if (rec_size <= 4) return Error.CorruptRecord;
  1189. if (self.offset + rec_size > self.size) return null;
  1190. const off = self.offset;
  1191. self.offset += rec_size;
  1192. if (self.deleted_set) |d| {
  1193. if (d.map.contains(off)) continue;
  1194. }
  1195. const buf = arena.alloc(u8, rec_size) catch return Error.OutOfMemory;
  1196. const got2 = fio.pread(self.fd, buf, off) orelse return Error.IoError;
  1197. if (got2 < rec_size) return Error.Truncated;
  1198. return .{ .bytes = buf, .off = off };
  1199. }
  1200. }
  1201. };
  1202. /// A dup() of the data file the offsets are into, for a streaming cursor (-1: none).
  1203. pub fn dupDataFd(self: *Db) i32 {
  1204. if (self.data_fd < 0) return -1;
  1205. const rc = linux.dup(self.data_fd);
  1206. return @bitCast(@as(u32, @truncate(rc)));
  1207. }
  1208. pub fn closeFd(fd: i32) void {
  1209. if (fd >= 0) fio.close(fd);
  1210. }
  1211. /// Read + decode one record by location from `fd` (a dupDataFd of the file the loc is into).
  1212. pub fn readAtFd(fd: i32, arena: std.mem.Allocator, loc: Loc) Error!msgpack.Value {
  1213. if (loc.len <= 4) return Error.CorruptRecord;
  1214. const buf = arena.alloc(u8, loc.len - 4) catch return Error.OutOfMemory;
  1215. const got = fio.pread(fd, buf, loc.off + 4) orelse return Error.IoError;
  1216. if (got < buf.len) return Error.Truncated;
  1217. const d = msgpack.decode(arena, buf) catch return Error.CorruptRecord;
  1218. return d.value;
  1219. }
  1220. /// Read + decode one record by location.
  1221. pub fn readAt(self: *Db, arena: std.mem.Allocator, loc: Loc) Error!msgpack.Value {
  1222. const own = self.data_fd < 0;
  1223. const fd = if (own) (fio.openRead(self.tmp, self.data_path) orelse return Error.IoError) else self.data_fd;
  1224. defer if (own) fio.close(fd);
  1225. if (loc.len <= 4) return Error.CorruptRecord;
  1226. const buf = arena.alloc(u8, loc.len - 4) catch return Error.OutOfMemory;
  1227. const got = fio.pread(fd, buf, loc.off + 4) orelse return Error.IoError;
  1228. if (got < buf.len) return Error.Truncated;
  1229. const d = msgpack.decode(arena, buf) catch return Error.CorruptRecord;
  1230. return d.value;
  1231. }
  1232. // =====================================================================
  1233. // Index management
  1234. // =====================================================================
  1235. fn keyFromValue(v: msgpack.Value) ?Key {
  1236. return switch (v) {
  1237. .number => |n| Key{ .num = n },
  1238. .str => |s| Key{ .str = s },
  1239. else => null, // null/bool/objects are not indexed (see header note)
  1240. };
  1241. }
  1242. /// Duplicate a key's string into the db arena so it outlives the op arena.
  1243. fn ownKey(self: *Db, k: Key) Error!Key {
  1244. return switch (k) {
  1245. .num => k,
  1246. .str => |s| Key{ .str = self.alloc.dupe(u8, s) catch return Error.OutOfMemory },
  1247. };
  1248. }
  1249. fn lowerBound(entries: []const Entry, key: Key) usize {
  1250. var lo: usize = 0;
  1251. var hi: usize = entries.len;
  1252. while (lo < hi) {
  1253. const mid = lo + (hi - lo) / 2;
  1254. if (cmpKeys(entries[mid].key, key) < 0) {
  1255. lo = mid + 1;
  1256. } else {
  1257. hi = mid;
  1258. }
  1259. }
  1260. return lo;
  1261. }
  1262. /// Binary search: all entries whose key equals `key` (appended to `out`).
  1263. pub fn indexGet(self: *Db, field: []const u8, key: Key, alloc: std.mem.Allocator, out: *std.ArrayList(Entry)) Error!void {
  1264. const fi = self.idx.getPtr(field) orelse return Error.NoSuchIndex;
  1265. const parsed = self.parseKeyForField(field, key);
  1266. const entries = fi.entries.items;
  1267. var i = lowerBound(entries, parsed);
  1268. while (i < entries.len and cmpKeys(entries[i].key, parsed) == 0) : (i += 1) {
  1269. out.append(alloc, entries[i]) catch return Error.OutOfMemory;
  1270. }
  1271. }
  1272. /// Range scan [from, to] (either side optional), ascending.
  1273. pub fn indexRange(self: *Db, field: []const u8, from: ?Key, to: ?Key, alloc: std.mem.Allocator, out: *std.ArrayList(Entry)) Error!void {
  1274. const fi = self.idx.getPtr(field) orelse return Error.NoSuchIndex;
  1275. const entries = fi.entries.items;
  1276. var i: usize = if (from) |f| lowerBound(entries, self.parseKeyForField(field, f)) else 0;
  1277. const to_key: ?Key = if (to) |t| self.parseKeyForField(field, t) else null;
  1278. while (i < entries.len) : (i += 1) {
  1279. if (to_key) |t| {
  1280. if (cmpKeys(entries[i].key, t) > 0) break;
  1281. }
  1282. out.append(alloc, entries[i]) catch return Error.OutOfMemory;
  1283. }
  1284. }
  1285. /// _parseKey semantics: numeric index fields parse string keys via
  1286. /// parseInt; on NaN the key stays a string.
  1287. fn parseKeyForField(self: *Db, field: []const u8, key: Key) Key {
  1288. const fi = self.idx.get(field) orelse return key;
  1289. if (fi.typ == .numeric and key == .str) {
  1290. if (jsParseInt(key.str)) |n| return Key{ .num = n };
  1291. }
  1292. return key;
  1293. }
  1294. fn indexInsertEntry(self: *Db, field: []const u8, key: Key, loc: Loc) Error!void {
  1295. const fi = self.idx.getPtr(field) orelse return;
  1296. const owned = try self.ownKey(key);
  1297. const e = Entry{ .key = owned, .off = loc.off, .len = loc.len };
  1298. // a bulk scan (rebuild / big catch-up) appends and sorts once at the end: a sorted
  1299. // insert per record is a memmove of the whole list each time — quadratic (#376)
  1300. if (self.bulk_index) {
  1301. fi.entries.append(self.alloc, e) catch return Error.OutOfMemory;
  1302. return;
  1303. }
  1304. // insert at sorted position
  1305. const pos = blk: {
  1306. var lo: usize = 0;
  1307. var hi: usize = fi.entries.items.len;
  1308. while (lo < hi) {
  1309. const mid = lo + (hi - lo) / 2;
  1310. if (entryLess({}, fi.entries.items[mid], e)) {
  1311. lo = mid + 1;
  1312. } else {
  1313. hi = mid;
  1314. }
  1315. }
  1316. break :blk lo;
  1317. };
  1318. fi.entries.insert(self.alloc, pos, e) catch return Error.OutOfMemory;
  1319. }
  1320. /// Index a record's fields at loc.
  1321. fn indexInsertRecord(self: *Db, rec: msgpack.Value, loc: Loc) Error!void {
  1322. for (self.index_fields.items) |field| {
  1323. const v = rec.get(field) orelse continue;
  1324. const key = keyFromValue(v) orelse continue;
  1325. try self.indexInsertEntry(field, key, loc);
  1326. }
  1327. self.covered_bytes = @max(self.covered_bytes, loc.off + loc.len);
  1328. }
  1329. /// Remove all entries pointing at offset `off` (all fields).
  1330. fn indexRemoveOffset(self: *Db, off: u64) void {
  1331. var it = self.idx.iterator();
  1332. while (it.next()) |kv| {
  1333. const list = &kv.value_ptr.entries;
  1334. var i: usize = 0;
  1335. while (i < list.items.len) {
  1336. if (list.items[i].off == off) {
  1337. _ = list.orderedRemove(i);
  1338. } else {
  1339. i += 1;
  1340. }
  1341. }
  1342. }
  1343. }
  1344. fn indexPath(self: *Db, buf: []u8, field: []const u8) []const u8 {
  1345. // <dir>/<base>.<field>.txt — derive from idxstate path (…/base.idxstate.json)
  1346. const prefix = self.idxstate_path[0 .. self.idxstate_path.len - "idxstate.json".len];
  1347. return std.fmt.bufPrint(buf, "{s}{s}.txt", .{ prefix, field }) catch buf[0..0];
  1348. }
  1349. fn initIndexes(self: *Db, force_rebuild: bool) Error!void {
  1350. var need_rebuild = force_rebuild;
  1351. const data_size = fio.fileSize(self.tmp, self.data_path) orelse 0;
  1352. if (!need_rebuild) {
  1353. for (self.index_fields.items) |field| {
  1354. var pbuf: [512]u8 = undefined;
  1355. const p = self.indexPath(&pbuf, field);
  1356. const isize_ = fio.fileSize(self.tmp, p);
  1357. if (isize_ == null or isize_.? == 0) {
  1358. if (data_size > 0) {
  1359. need_rebuild = true;
  1360. break;
  1361. }
  1362. }
  1363. }
  1364. }
  1365. if (!need_rebuild) {
  1366. // coveredBytes from idxstate — no state file means rebuild (JS). An
  1367. // idxstate of another data file (its inode, or more bytes covered
  1368. // than there are) means the index files are another file's too:
  1369. // a crash between a compaction's rename and its rebuild (#176).
  1370. if (self.readIdxState()) |st| {
  1371. self.covered_bytes = st.covered;
  1372. const cur = fio.stat(self.tmp, self.data_path);
  1373. const cur_ino: u64 = if (cur) |c| c.ino else 0;
  1374. if (st.covered > data_size) need_rebuild = true;
  1375. if (st.ino) |i| {
  1376. self.idx_bind_known = true;
  1377. // another inode: a byte COPY of the store (ticket 387) has the same
  1378. // content over the covered bytes, so its index files are right
  1379. if (i != cur_ino) {
  1380. var fpb: [16]u8 = undefined;
  1381. const same = st.has_fp and st.covered <= data_size and
  1382. if (self.dataFingerprint(st.covered, &fpb)) |f| std.mem.eql(u8, f, &st.fp) else false;
  1383. if (!same) need_rebuild = true;
  1384. }
  1385. }
  1386. } else {
  1387. need_rebuild = true;
  1388. }
  1389. }
  1390. if (need_rebuild) {
  1391. try self.rebuildIndexes();
  1392. return;
  1393. }
  1394. // Load index files into memory
  1395. for (self.index_fields.items) |field| {
  1396. var pbuf: [512]u8 = undefined;
  1397. const p = self.indexPath(&pbuf, field);
  1398. const content = fio.readAll(self.tmp, p) orelse continue;
  1399. defer self.tmp.free(content);
  1400. self.loadIndexLines(field, content);
  1401. }
  1402. // sort (files are sorted by JS localeCompare; re-sort under our order)
  1403. var it = self.idx.iterator();
  1404. while (it.next()) |kv| {
  1405. std.sort.pdq(Entry, kv.value_ptr.entries.items, {}, entryLess);
  1406. }
  1407. if (data_size > self.covered_bytes) self.catchUp(data_size);
  1408. }
  1409. fn loadIndexLines(self: *Db, field: []const u8, content: []const u8) void {
  1410. const fi = self.idx.getPtr(field) orelse return;
  1411. var lines = std.mem.splitScalar(u8, content, '\n');
  1412. while (lines.next()) |line| {
  1413. if (line.len == 0) continue;
  1414. // key = up to FIRST comma (JS split(',')[0]); then offset, length
  1415. const c1 = std.mem.indexOfScalar(u8, line, ',') orelse continue;
  1416. const rest = line[c1 + 1 ..];
  1417. const c2 = std.mem.indexOfScalar(u8, rest, ',') orelse continue;
  1418. const off_s = rest[0..c2];
  1419. const len_s = rest[c2 + 1 ..];
  1420. const off = std.fmt.parseInt(u64, off_s, 10) catch continue;
  1421. const len = std.fmt.parseInt(u64, len_s, 10) catch continue;
  1422. if (len == 0) continue;
  1423. const key_s = line[0..c1];
  1424. var key: Key = undefined;
  1425. if (fi.typ == .numeric) {
  1426. key = if (jsParseInt(key_s)) |n| Key{ .num = n } else Key{ .str = self.alloc.dupe(u8, key_s) catch return };
  1427. } else {
  1428. key = Key{ .str = self.alloc.dupe(u8, key_s) catch return };
  1429. }
  1430. fi.entries.append(self.alloc, .{ .key = key, .off = off, .len = len }) catch return;
  1431. }
  1432. }
  1433. fn sortAllIndexes(self: *Db) void {
  1434. var it = self.idx.iterator();
  1435. while (it.next()) |kv| std.sort.pdq(Entry, kv.value_ptr.entries.items, {}, entryLess);
  1436. }
  1437. fn rebuildIndexes(self: *Db) Error!void {
  1438. var it0 = self.idx.iterator();
  1439. while (it0.next()) |kv| kv.value_ptr.entries.clearRetainingCapacity();
  1440. self.bulk_index = true;
  1441. defer self.bulk_index = false;
  1442. var scratch_state = std.heap.ArenaAllocator.init(self.arena_state.child_allocator);
  1443. defer scratch_state.deinit();
  1444. const scratch = scratch_state.allocator();
  1445. // JS rebuild scans ALL records (no tombstone filter — deleted offsets
  1446. // simply get filtered at read time). Mirror that.
  1447. var scanner = Scanner.init(self, scratch, false);
  1448. defer scanner.deinit();
  1449. while (try scanner.next(scratch)) |rec| {
  1450. try self.indexInsertRecord(rec.value, .{ .off = rec.off, .len = rec.len });
  1451. }
  1452. self.sortAllIndexes();
  1453. self.bulk_index = false;
  1454. self.covered_bytes = fio.fileSize(self.tmp, self.data_path) orelse 0;
  1455. self.idx_bind_known = true;
  1456. try self.writeIndexFiles();
  1457. try self.writeIdxState();
  1458. }
  1459. fn catchUp(self: *Db, file_size: u64) void {
  1460. var scratch_state = std.heap.ArenaAllocator.init(self.arena_state.child_allocator);
  1461. defer scratch_state.deinit();
  1462. const scratch = scratch_state.allocator();
  1463. var scanner = Scanner.init(self, scratch, false);
  1464. defer scanner.deinit();
  1465. scanner.offset = self.covered_bytes;
  1466. // a long tail is appended and sorted once; a short one (a refresh per op) is inserted
  1467. const bulk = file_size > self.covered_bytes and file_size - self.covered_bytes > 256 * 1024;
  1468. self.bulk_index = bulk;
  1469. defer self.bulk_index = false;
  1470. while (true) {
  1471. const maybe = scanner.next(scratch) catch break;
  1472. const rec = maybe orelse break;
  1473. self.indexInsertRecord(rec.value, .{ .off = rec.off, .len = rec.len }) catch break;
  1474. }
  1475. if (bulk) self.sortAllIndexes();
  1476. self.bulk_index = false;
  1477. self.covered_bytes = @max(self.covered_bytes, file_size);
  1478. }
  1479. /// A file that already holds these exact bytes is left alone — its mtime
  1480. /// included — so closing a handle that changed nothing writes nothing.
  1481. fn fileHolds(alloc: std.mem.Allocator, path: []const u8, bytes: []const u8) bool {
  1482. const disk = fio.readAll(alloc, path) orelse return false;
  1483. defer alloc.free(disk);
  1484. return std.mem.eql(u8, disk, bytes);
  1485. }
  1486. fn writeIndexFiles(self: *Db) Error!void {
  1487. for (self.index_fields.items) |field| {
  1488. const fi = self.idx.getPtr(field) orelse continue;
  1489. var out: std.ArrayList(u8) = .empty;
  1490. defer out.deinit(self.tmp);
  1491. for (fi.entries.items) |e| {
  1492. var kbuf: [32]u8 = undefined;
  1493. const ks = switch (e.key) {
  1494. .num => |n| jsNumFmt(&kbuf, n),
  1495. .str => |s| s,
  1496. };
  1497. try self.appendFmt(&out, "{s},{d},{d}\n", .{ ks, e.off, e.len });
  1498. }
  1499. var pbuf: [512]u8 = undefined;
  1500. const p = self.indexPath(&pbuf, field);
  1501. if (fileHolds(self.tmp, p, out.items)) continue;
  1502. var tbuf: [512]u8 = undefined;
  1503. const tmp = std.fmt.bufPrint(&tbuf, "{s}.{d}.tmp", .{ p, linux.getpid() }) catch return Error.IoError;
  1504. const fd = fio.openTrunc(self.tmp, tmp) orelse return Error.IoError;
  1505. const ok = fio.writeAll(fd, out.items);
  1506. fio.close(fd);
  1507. if (!ok) return Error.IoError;
  1508. if (!fio.rename(self.tmp, tmp, p)) return Error.IoError;
  1509. }
  1510. }
  1511. const IdxState = struct { covered: u64, ino: ?u64, fp: [16]u8 = undefined, has_fp: bool = false };
  1512. fn readIdxState(self: *Db) ?IdxState {
  1513. const content = fio.readAll(self.tmp, self.idxstate_path) orelse return null;
  1514. defer self.tmp.free(content);
  1515. const parsed = std.json.parseFromSlice(std.json.Value, self.tmp, content, .{}) catch return null;
  1516. defer parsed.deinit();
  1517. if (parsed.value != .object) return null;
  1518. const v = parsed.value.object.get("coveredBytes") orelse return null;
  1519. const covered: u64 = switch (v) {
  1520. .integer => |i| @intCast(@max(i, 0)),
  1521. .float => |f| @intFromFloat(@max(f, 0)),
  1522. else => return null,
  1523. };
  1524. var st = IdxState{ .covered = covered, .ino = jsonU64(parsed.value.object.get("dataIno")) };
  1525. if (parsed.value.object.get("dataFp")) |f| {
  1526. if (f == .string and f.string.len == 16) {
  1527. @memcpy(&st.fp, f.string);
  1528. st.has_fp = true;
  1529. }
  1530. }
  1531. return st;
  1532. }
  1533. /// idxstate.json: coveredBytes (JS) and, once this engine indexed the file,
  1534. /// the data file's inode — so index files of a replaced data file are known
  1535. /// for what they are (ticket #176). An idxstate without it (the JS mpackdb's)
  1536. /// is rewritten without it while it stays without a rebuild (ticket #21).
  1537. fn writeIdxState(self: *Db) Error!void {
  1538. var buf: [160]u8 = undefined;
  1539. const ino: u64 = if (fio.stat(self.tmp, self.data_path)) |c| c.ino else 0;
  1540. var fpb: [16]u8 = undefined;
  1541. const fp: ?[]const u8 = if (self.idx_bind_known) self.dataFingerprint(self.covered_bytes, &fpb) else null;
  1542. const json = (if (self.idx_bind_known and fp != null)
  1543. std.fmt.bufPrint(&buf, "{{\"coveredBytes\":{d},\"dataIno\":{d},\"dataFp\":\"{s}\"}}", .{ self.covered_bytes, ino, fp.? })
  1544. else if (self.idx_bind_known)
  1545. std.fmt.bufPrint(&buf, "{{\"coveredBytes\":{d},\"dataIno\":{d}}}", .{ self.covered_bytes, ino })
  1546. else
  1547. std.fmt.bufPrint(&buf, "{{\"coveredBytes\":{d}}}", .{self.covered_bytes})) catch return Error.IoError;
  1548. if (fileHolds(self.tmp, self.idxstate_path, json)) return;
  1549. var tbuf: [512]u8 = undefined;
  1550. const tmp = std.fmt.bufPrint(&tbuf, "{s}.{d}.tmp", .{ self.idxstate_path, linux.getpid() }) catch return Error.IoError;
  1551. const fd = fio.openTrunc(self.tmp, tmp) orelse return Error.IoError;
  1552. const ok = fio.writeAll(fd, json);
  1553. fio.close(fd);
  1554. if (!ok) return Error.IoError;
  1555. if (!fio.rename(self.tmp, tmp, self.idxstate_path)) return Error.IoError;
  1556. }
  1557. fn persistIndexesLocked(self: *Db) Error!void {
  1558. // never write an index of a data file that is no longer the one at the path (395)
  1559. if (self.data_fd >= 0) {
  1560. if (fio.stat(self.tmp, self.data_path)) |c| {
  1561. if (self.seen_ino != 0 and c.ino != self.seen_ino) return;
  1562. }
  1563. }
  1564. try self.writeIndexFiles();
  1565. // coverage can only grow (JS: max of ours and on-disk state)
  1566. if (self.readIdxState()) |st| {
  1567. const same_file = if (st.ino) |i| i == (if (fio.stat(self.tmp, self.data_path)) |c| c.ino else 0) else true;
  1568. if (same_file) self.covered_bytes = @max(self.covered_bytes, st.covered);
  1569. }
  1570. try self.writeIdxState();
  1571. }
  1572. // =====================================================================
  1573. // Operations
  1574. // =====================================================================
  1575. /// A mutable record under construction (op-arena entries).
  1576. pub const MutableRecord = struct {
  1577. entries: std.ArrayList(msgpack.Entry) = .empty,
  1578. pub fn get(self: *const MutableRecord, key: []const u8) ?msgpack.Value {
  1579. for (self.entries.items) |e| {
  1580. if (e.key == .str and std.mem.eql(u8, e.key.str, key)) return e.value;
  1581. }
  1582. return null;
  1583. }
  1584. pub fn set(self: *MutableRecord, alloc: std.mem.Allocator, key: []const u8, v: msgpack.Value) Error!void {
  1585. for (self.entries.items) |*e| {
  1586. if (e.key == .str and std.mem.eql(u8, e.key.str, key)) {
  1587. e.value = v;
  1588. return;
  1589. }
  1590. }
  1591. self.entries.append(alloc, .{ .key = .{ .str = key }, .value = v }) catch return Error.OutOfMemory;
  1592. }
  1593. pub fn toValue(self: *const MutableRecord) msgpack.Value {
  1594. return .{ .map = self.entries.items };
  1595. }
  1596. };
  1597. pub const InsertResult = union(enum) {
  1598. pk_num: f64,
  1599. pk_str: []const u8, // op-arena
  1600. record: msgpack.Value,
  1601. };
  1602. /// insert() — auto primary key, unique checks, append, index.
  1603. /// `record` must be a map value; `arena` is the op arena (record memory).
  1604. pub fn insert(self: *Db, arena: std.mem.Allocator, record: msgpack.Value, skip_pk: bool) Error!InsertResult {
  1605. if (record != .map) return Error.CorruptRecord;
  1606. try self.acquireLock();
  1607. defer self.releaseLock();
  1608. self.refresh();
  1609. return self.insertLocked(arena, record, skip_pk);
  1610. }
  1611. fn insertLocked(self: *Db, arena: std.mem.Allocator, record: msgpack.Value, skip_pk: bool) Error!InsertResult {
  1612. // copy into mutable form
  1613. var rec = MutableRecord{};
  1614. for (record.map) |e| rec.entries.append(arena, e) catch return Error.OutOfMemory;
  1615. // _hasPrimaryKeyValue: present and not null/undefined
  1616. var has_pk_value = false;
  1617. if (self.pk) |p| {
  1618. if (rec.get(p)) |v| {
  1619. has_pk_value = (v != .nil and v != .undef);
  1620. }
  1621. }
  1622. var auto_gen = false;
  1623. if (self.pk != null and !skip_pk and !has_pk_value) {
  1624. if (self.pk_type == .number) {
  1625. rec.set(arena, self.pk.?, .{ .number = self.next_id }) catch return Error.OutOfMemory;
  1626. self.next_id += 1;
  1627. auto_gen = true;
  1628. } else if (self.pk_type == .uuid) {
  1629. // A GENERATED ID IS CHECKED, NOT TRUSTED (ticket #113): the format is a
  1630. // millisecond stamp + 3 base36 chars, so a bulk put collides within a
  1631. // millisecond (two of 7800 in a measured run) and the unique check below
  1632. // skips generated keys — two live rows then shared one pk and the next
  1633. // update() deleted both and re-inserted one. Draw again until it is free.
  1634. var ubuf: [12]u8 = undefined;
  1635. var tries: usize = 0;
  1636. while (true) : (tries += 1) {
  1637. const u = genUuid(&ubuf);
  1638. var taken: std.ArrayList(Loc) = .empty;
  1639. defer taken.deinit(arena);
  1640. try self.findPkLocs(arena, .{ .str = u }, &taken);
  1641. if (taken.items.len == 0 or tries >= 64) break;
  1642. }
  1643. const owned = arena.dupe(u8, ubuf[0..12]) catch return Error.OutOfMemory;
  1644. rec.set(arena, self.pk.?, .{ .str = owned }) catch return Error.OutOfMemory;
  1645. auto_gen = true;
  1646. }
  1647. }
  1648. // unique constraints (skip auto-generated pk)
  1649. if (self.index_fields.items.len > 0 and self.unique_fields.items.len > 0) {
  1650. const del_set = &self.delSetCached().map;
  1651. for (self.unique_fields.items) |field| {
  1652. if (auto_gen and self.pk != null and std.mem.eql(u8, field, self.pk.?)) continue;
  1653. const v = rec.get(field) orelse continue;
  1654. if (v == .undef) continue;
  1655. const key = keyFromValue(v) orelse continue;
  1656. var hits: std.ArrayList(Entry) = .empty;
  1657. defer hits.deinit(arena);
  1658. try self.indexGet(field, key, arena, &hits);
  1659. var live: usize = 0;
  1660. for (hits.items) |h| {
  1661. if (!del_set.contains(h.off)) live += 1;
  1662. }
  1663. if (live > 0) {
  1664. var kbuf: [32]u8 = undefined;
  1665. const ks = switch (key) {
  1666. .num => |n| jsNumFmt(&kbuf, n),
  1667. .str => |s| s,
  1668. };
  1669. self.last_error = std.fmt.bufPrint(&self.last_error_buf, "Duplicate key: {s}={s}", .{ field, ks }) catch "Duplicate key";
  1670. return Error.DuplicateKey;
  1671. }
  1672. }
  1673. }
  1674. // serialize + append
  1675. const framed = msgpack.serialize(arena, rec.toValue()) catch return Error.OutOfMemory;
  1676. const offset = fio.fileSize(self.tmp, self.data_path) orelse 0;
  1677. const fd = fio.openAppend(self.tmp, self.data_path) orelse return Error.IoError;
  1678. const ok = fio.writeAll(fd, framed);
  1679. fio.close(fd);
  1680. if (!ok) return Error.IoError;
  1681. const loc = Loc{ .off = offset, .len = framed.len };
  1682. if (self.index_fields.items.len > 0) {
  1683. try self.indexInsertRecord(rec.toValue(), loc);
  1684. }
  1685. if (self.pk != null and self.pk_type == .number and !skip_pk and !has_pk_value) {
  1686. try self.persistMetaLocked();
  1687. }
  1688. if (self.pk) |p| {
  1689. const v = rec.get(p) orelse return Error.CorruptRecord;
  1690. return switch (v) {
  1691. .number => |n| InsertResult{ .pk_num = n },
  1692. .str => |s| InsertResult{ .pk_str = s },
  1693. else => InsertResult{ .record = rec.toValue() },
  1694. };
  1695. }
  1696. return InsertResult{ .record = rec.toValue() };
  1697. }
  1698. /// Locate live records by primary key (index-backed when available).
  1699. pub fn findPkLocs(self: *Db, arena: std.mem.Allocator, key: Key, out: *std.ArrayList(Loc)) Error!void {
  1700. if (self.pk == null) return Error.NoPrimaryKey;
  1701. self.refresh();
  1702. const del_set = &self.delSetCached().map;
  1703. if (self.index_fields.items.len > 0) {
  1704. var hits: std.ArrayList(Entry) = .empty;
  1705. defer hits.deinit(arena);
  1706. try self.indexGet(self.pk.?, key, arena, &hits);
  1707. for (hits.items) |h| {
  1708. if (del_set.contains(h.off)) continue;
  1709. if (!self.hitOk(h)) continue;
  1710. out.append(arena, .{ .off = h.off, .len = h.len }) catch return Error.OutOfMemory;
  1711. }
  1712. if (self.index_bad and !self.index_retry) {
  1713. self.index_retry = true;
  1714. defer self.index_retry = false;
  1715. out.clearRetainingCapacity();
  1716. return self.findPkLocs(arena, key, out);
  1717. }
  1718. return;
  1719. }
  1720. // no indexes: full scan comparing the pk field
  1721. var scanner = Scanner.init(self, arena, true);
  1722. defer scanner.deinit();
  1723. while (try scanner.next(arena)) |rec| {
  1724. const v = rec.value.get(self.pk.?) orelse continue;
  1725. const k = keyFromValue(v) orelse continue;
  1726. if (cmpKeys(self.parseKeyForField(self.pk.?, k), self.parseKeyForField(self.pk.?, key)) == 0) {
  1727. out.append(arena, .{ .off = rec.off, .len = rec.len }) catch return Error.OutOfMemory;
  1728. }
  1729. }
  1730. }
  1731. /// Locate live records by secondary index equality.
  1732. pub fn findIndexLocs(self: *Db, arena: std.mem.Allocator, field: []const u8, key: Key, out: *std.ArrayList(Loc)) Error!void {
  1733. self.refresh();
  1734. const del_set = &self.delSetCached().map;
  1735. var hits: std.ArrayList(Entry) = .empty;
  1736. defer hits.deinit(arena);
  1737. try self.indexGet(field, key, arena, &hits);
  1738. for (hits.items) |h| {
  1739. if (del_set.contains(h.off)) continue;
  1740. if (!self.hitOk(h)) continue;
  1741. out.append(arena, .{ .off = h.off, .len = h.len }) catch return Error.OutOfMemory;
  1742. }
  1743. if (self.index_bad and !self.index_retry) {
  1744. self.index_retry = true;
  1745. defer self.index_retry = false;
  1746. out.clearRetainingCapacity();
  1747. return self.findIndexLocs(arena, field, key, out);
  1748. }
  1749. }
  1750. /// Locate live records by index range [from, to] ascending.
  1751. pub fn findRangeLocs(self: *Db, arena: std.mem.Allocator, field: []const u8, from: ?Key, to: ?Key, out: *std.ArrayList(Loc)) Error!void {
  1752. self.refresh();
  1753. const del_set = &self.delSetCached().map;
  1754. var hits: std.ArrayList(Entry) = .empty;
  1755. defer hits.deinit(arena);
  1756. try self.indexRange(field, from, to, arena, &hits);
  1757. var seen: std.AutoHashMapUnmanaged(u64, void) = .empty;
  1758. for (hits.items) |h| {
  1759. if (del_set.contains(h.off)) continue;
  1760. if (!self.hitOk(h)) continue;
  1761. if (seen.contains(h.off)) continue;
  1762. seen.put(arena, h.off, {}) catch {};
  1763. out.append(arena, .{ .off = h.off, .len = h.len }) catch return Error.OutOfMemory;
  1764. }
  1765. if (self.index_bad and !self.index_retry) {
  1766. self.index_retry = true;
  1767. defer self.index_retry = false;
  1768. out.clearRetainingCapacity();
  1769. return self.findRangeLocs(arena, field, from, to, out);
  1770. }
  1771. }
  1772. /// delete by primary key. Returns the deleted records (decoded into arena).
  1773. pub fn deletePk(self: *Db, arena: std.mem.Allocator, key: Key, out_records: *std.ArrayList(msgpack.Value)) Error!usize {
  1774. try self.acquireLock();
  1775. defer self.releaseLock();
  1776. self.refresh();
  1777. return self.deletePkLocked(arena, key, out_records);
  1778. }
  1779. fn deletePkLocked(self: *Db, arena: std.mem.Allocator, key: Key, out_records: *std.ArrayList(msgpack.Value)) Error!usize {
  1780. var locs: std.ArrayList(Loc) = .empty;
  1781. defer locs.deinit(arena);
  1782. try self.findPkLocs(arena, key, &locs);
  1783. for (locs.items) |loc| {
  1784. const rec = try self.readAt(arena, loc);
  1785. out_records.append(arena, rec) catch return Error.OutOfMemory;
  1786. self.deleted.append(self.alloc, loc.off) catch return Error.OutOfMemory;
  1787. self.delCacheAdd(loc.off);
  1788. self.indexRemoveOffset(loc.off);
  1789. }
  1790. try self.persistMetaLocked();
  1791. return locs.items.len;
  1792. }
  1793. /// update by primary key: delete + insert(skip_pk) — JS update() semantics.
  1794. /// `new_record` must already carry the primary key (the JS callback
  1795. /// contract: the record keeps its pk unless the caller removes it).
  1796. pub fn updatePk(self: *Db, arena: std.mem.Allocator, key: Key, new_record: msgpack.Value) Error!usize {
  1797. if (self.pk) |p| {
  1798. const carried = for (new_record.map) |e| {
  1799. if (e.key == .str and std.mem.eql(u8, e.key.str, p)) break e.value != .nil and e.value != .undef;
  1800. } else false;
  1801. if (!carried) return Error.RecordLacksPrimaryKey;
  1802. }
  1803. try self.acquireLock();
  1804. defer self.releaseLock();
  1805. self.refresh();
  1806. var old: std.ArrayList(msgpack.Value) = .empty;
  1807. defer old.deinit(arena);
  1808. const n = try self.deletePkLocked(arena, key, &old);
  1809. if (n == 0) return 0;
  1810. var i: usize = 0;
  1811. while (i < n) : (i += 1) {
  1812. _ = try self.insertLocked(arena, new_record, true);
  1813. }
  1814. return n;
  1815. }
  1816. /// compact() — rewrite the data file without tombstones, rebuild indexes.
  1817. /// Skipped — not an error — while another process has the store open
  1818. /// (ticket #176); last_error then says so.
  1819. pub fn compact(self: *Db) Error!void {
  1820. try self.acquireLock();
  1821. defer self.releaseLock();
  1822. self.refresh();
  1823. if (!self.tryExclusive()) {
  1824. _ = try self.skipCompaction();
  1825. return;
  1826. }
  1827. defer self.backToShared();
  1828. _ = try self.compactLocked();
  1829. if (self.index_fields.items.len > 0) {
  1830. try self.rebuildIndexes();
  1831. }
  1832. }
  1833. /// Refuse a compaction (ticket #176): last_error says why and where; the
  1834. /// caller's rewrite is abandoned before anything was renamed.
  1835. fn refuse(self: *Db, comptime fmt: []const u8, args: anytype) Error {
  1836. self.last_error = std.fmt.bufPrint(&self.last_error_buf, "compaction refused: " ++ fmt, args) catch "compaction refused";

Only the first lines are shown.

Branches

Latest commits

  • a6dfd6ecdeploy: person-lookup gate (tracker#46)mre
  • 33ad4bd5Merge commit 'f57f64f'mre
  • 7d38cec4docker-compose: nofile 65536 (default soft 1024 refused boot: errno 24 in fs.listDir, Hybriel 528bc89f)mre
  • f57f64f0mission 046: report, LOGmre
  • 5965963adeploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • efe1b485mission 046: re-vendor Hybriel master 60b2817b (integration 8, #203): plugins mpackdb + web (bin/ git-ignored: hybriel, libhlrt.a, hlc.o, hlrt/ from native/zig-out)mre
  • 53099ffbmission 046: person page reads a slim per-title credit row cache (no whole-record fetch per credit); gate tests/person-lookup.mjsmre
  • 9b3828aemission 046a: report, LOGmre
  • 4b37356emission 046: franchise seed supersedeCollections reads the curated timelines once (10 s one-tick block at the end of boot)mre
  • ac6268e3mission 046a: re-vendor Hybriel 528bc89f (integration 6): plugins mpackdb/time/web (bin/ git-ignored)mre
  • 322b3293mission 046: photoQueue guard for non-row fetch results (damaged persons index)mre
  • e5b99aecmission 046: photoQueue in slices (people.hl photoQueueStart/Step, jobs.hl photoTick), tests/photoqueue.hlmre
  • 31dcf2admission 045: report, LOGmre
  • 9c3971d0tests/persons-skip-count.hlmre
  • 4d72e365mission 045mre
  • b9cae4c9slices: skip and count non-row values from range(); merge persons pass falls back to iterate; guard testmre
  • 3db7dc31merge w44-jobs-slices into w43-trkmemmre
  • 593dab6fmission 043: report, LOGmre
  • 1a5a4818boot scans back to iterate (slices measured slower: titles 114 s, episodes 141 s, persons failed); lambda per rowmre
  • 03d29893boot scans read primary-key slices (lib/slices.hl from mission 044): iterate is eager too; people view log line back; allShows/allEpisodes stay for toolsmre