gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit5525785255257852log: #53 live, #56 mergedmre55257852/plugins/mpackdb/engine.zig

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

Only the first lines are shown.

Branches

Latest commits

  • 55257852log: #53 live, #56 mergedmre
  • 78b39f1bMerge hm56-rows: tracker#56 list builders insert oncemre
  • 6da612fclog: T36A tool defectmre
  • 08e55255log: HM56 done, T36A startedmre
  • 91bcdf0eAvoid per-row list copies and reproduce keyed-row blockersmre
  • 5fd2ac75status: #36 GOmre
  • 0d253b45mission: T36Amre
  • 2aa22d23log: #36 GOmre
  • 833aee2flog: #50 closed, HM56 startedmre
  • ac58c1e5mission: HM56mre
  • 58979c0clog: HM54 held for decision, DP65 startedmre
  • bb2ebc67log: #64 live, #53 mergedmre
  • 27cde42fMerge hm53-dom: tracker#53 inputs bound to membersmre
  • 2156cc7flog: HM54 reviewmre
  • 9fb82efclog: HM54 gap, fill continuesmre
  • b632eb8dlog: HM53 done, HM54 startedmre
  • ccb1a263tracker#53: bind editor drafts and use key event focus targetmre
  • 3356fcfclog: #52 blocked, HM53 startedmre
  • 833dcfc9Merge hm52-search: report only, tracker#52 blocked by framework gapmre
  • 73010cc0HM52: report replace-navigation search draft regressionmre