gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit7557c0257557c025log: CB deploy try 2mre7557c025/plugins/mpackdb/engine.zig

195.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" (a key with a newline, CR or leading quote is a JSON string; read from the right: mission 486)
  7. // <base>.idxstate.json { coveredBytes, idxFmt (2 since mission 486; absent means rebuild once) }
  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. // 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. // schema
  556. pk: ?[]const u8 = null,
  557. pk_type: PkType = .string,
  558. index_fields: std.ArrayList([]const u8) = .empty, // pk first (when set), like JS
  559. unique_fields: std.ArrayList([]const u8) = .empty,
  560. idx: std.StringArrayHashMapUnmanaged(FieldIndex) = .empty,
  561. // meta
  562. next_id: f64 = FIRST_ID,
  563. deleted: std.ArrayList(u64) = .empty,
  564. /// lazily built set of `deleted` (mission 393); null = not built / invalidated
  565. del_cache: ?*DelSet = null,
  566. /// an index entry named a place that is no frame of its size (a stale persisted index):
  567. /// the next refresh() rebuilds every index from the data file (mission 393)
  568. index_bad: bool = false,
  569. index_retry: bool = false,
  570. version: u64 = 0,
  571. // THE META NAMES ITS DATA FILE (ticket #176): `dataFile` in .meta.json is the
  572. // inode and size of the data file it was written for, the compaction
  573. // generation, and a checksum of its own `deleted` list. A meta whose data file
  574. // was replaced under it (a crash between the rename and the meta write) has
  575. // tombstones that point into the WRONG file — they are dropped, not applied.
  576. // The checksum tells our dataFile from one another writer carried along: the
  577. // JS mpackdb rewrites the meta as `{...meta}` and keeps fields it does not
  578. // know, so a `deleted` list it changed no longer matches the sum, and such a
  579. // meta is taken as it is (as before #176).
  580. bind_known: bool = false, // the meta on disk carries a dataFile that is ours and true
  581. bind_ino: u64 = 0,
  582. bind_size: u64 = 0,
  583. bind_fp: [16]u8 = undefined, // content fingerprint of the data file's first `bind_size` bytes
  584. bind_fp_len: u8 = 0, // 0 = none known (an old meta whose data file was not read)
  585. data_gen: u64 = 0,
  586. meta_stale: bool = false, // the loaded meta belonged to another data file
  587. idx_bind_known: bool = false, // the idxstate on disk names the data file's inode
  588. // the data file this handle's offsets are into (ticket #176): its inode and
  589. // the compaction generation; refresh() compares them on every operation
  590. seen_ino: u64 = 0,
  591. // THE FILE THE OFFSETS ARE INTO, held open (ticket #176): every read and scan
  592. // goes through it, never through the path — a rewrite renamed in between a
  593. // lookup and its read (the tracker parsed 1.4 MB of meta between the two)
  594. // then still reads the file the offsets belong to, and the next refresh()
  595. // moves the handle to the new one.
  596. data_fd: i32 = -1,
  597. // fd403: the refcounted holder of data_fd. A streaming cursor takes a reference to the
  598. // generation it started on instead of dup()ing the fd (a dup per query held thousands of
  599. // fds until the GC finalized abandoned cursors: > 1024 at the tracker's boot). The fd is
  600. // closed when the Db has moved on (compaction, close) AND the last cursor is gone.
  601. fd_gen: ?*DataGen = null,
  602. // The meta file as THIS handle last read or wrote it (ticket #188): it is only ever
  603. // replaced by tmp + rename, so a write changes its inode; refresh() stats it and
  604. // skips the read + parse of a (1.4 MB on the tracker) meta that is unchanged.
  605. meta_seen: ?fio.Stat = null,
  606. meta_reads: u64 = 0, // reads of the meta file by loadMeta/refresh (the test counts them)
  607. bulk_index: bool = false, // indexInsertEntry appends (a sorted pass follows): rebuild / long catch-up
  608. /// keys of a rebuild live here until the sort has put the entries in order; then they are
  609. /// copied side by side in that order (a rebuilt index is read in sorted order, again and
  610. /// again: written, compared, searched) and this arena is freed (mission 436)
  611. bulk_keys: ?*std.heap.ArenaAllocator = null,
  612. covered_bytes: u64 = 0,
  613. compact_on_open: bool = true,
  614. stale_lock_timeout_ms: i64 = 30000,
  615. debug: bool = false,
  616. // last DuplicateKey detail for the plugin surface
  617. last_error_buf: [256]u8 = undefined,
  618. last_error: []const u8 = "",
  619. pub fn open(gpa: std.mem.Allocator, db_file: []const u8, opts: OpenOptions) Error!*Db {
  620. if (db_file.len == 0) return Error.NoDbFile;
  621. const self = gpa.create(Db) catch return Error.OutOfMemory;
  622. self.* = .{
  623. .arena_state = std.heap.ArenaAllocator.init(gpa),
  624. .alloc = undefined,
  625. .tmp = gpa,
  626. .data_path = undefined,
  627. .meta_path = undefined,
  628. .lock_path = undefined,
  629. .idxstate_path = undefined,
  630. };
  631. self.alloc = self.arena_state.allocator();
  632. errdefer {
  633. self.arena_state.deinit();
  634. gpa.destroy(self);
  635. }
  636. const a = self.alloc;
  637. self.compact_on_open = opts.compact;
  638. self.stale_lock_timeout_ms = opts.stale_lock_timeout_ms;
  639. self.debug = opts.debug;
  640. // dirname / basename (extension stripped, like JS basename(f, extname(f)))
  641. const dir = std.fs.path.dirname(db_file) orelse ".";
  642. var base = std.fs.path.basename(db_file);
  643. if (std.mem.lastIndexOfScalar(u8, base, '.')) |dot| {
  644. if (dot > 0) base = base[0..dot];
  645. }
  646. fio.mkdirAll(a, dir);
  647. self.data_path = std.fmt.allocPrint(a, "{s}/{s}.mpack", .{ dir, base }) catch return Error.OutOfMemory;
  648. self.meta_path = std.fmt.allocPrint(a, "{s}/{s}.meta.json", .{ dir, base }) catch return Error.OutOfMemory;
  649. self.lock_path = std.fmt.allocPrint(a, "{s}/{s}.lock", .{ dir, base }) catch return Error.OutOfMemory;
  650. self.idxstate_path = std.fmt.allocPrint(a, "{s}/{s}.idxstate.json", .{ dir, base }) catch return Error.OutOfMemory;
  651. self.flock_path = std.fmt.allocPrint(a, "{s}/{s}.flock", .{ dir, base }) catch return Error.OutOfMemory;
  652. try self.openStoreLock();
  653. errdefer self.closeStoreLock();
  654. // ---- parse primary key ----
  655. if (opts.primary_key) |pk_raw| {
  656. if (pk_raw.len > 0) {
  657. if (pk_raw[0] == '*') {
  658. self.pk = a.dupe(u8, pk_raw[1..]) catch return Error.OutOfMemory;
  659. self.pk_type = .number;
  660. } else if (pk_raw[0] == '@') {
  661. self.pk = a.dupe(u8, pk_raw[1..]) catch return Error.OutOfMemory;
  662. self.pk_type = .uuid;
  663. } else {
  664. self.pk = a.dupe(u8, pk_raw) catch return Error.OutOfMemory;
  665. self.pk_type = .string;
  666. }
  667. }
  668. }
  669. if (self.pk) |p| self.unique_fields.append(a, p) catch return Error.OutOfMemory;
  670. // ---- parse indexes (pk first, then configured; dedupe) ----
  671. if (self.pk) |p| {
  672. self.index_fields.append(a, p) catch return Error.OutOfMemory;
  673. const t: IdxType = if (self.pk_type == .number) .numeric else .lexical;
  674. self.idx.put(a, p, .{ .typ = t }) catch return Error.OutOfMemory;
  675. }
  676. for (opts.indexes) |raw| {
  677. var clean = raw;
  678. var is_unique = false;
  679. if (clean.len > 0 and clean[0] == '!') {
  680. is_unique = true;
  681. clean = clean[1..];
  682. }
  683. var typ: IdxType = .lexical;
  684. if (clean.len > 0 and clean[0] == '*') {
  685. typ = .numeric;
  686. clean = clean[1..];
  687. } else if (clean.len > 0 and clean[0] == '@') {
  688. clean = clean[1..];
  689. }
  690. if (self.idx.contains(clean)) continue;
  691. const owned = a.dupe(u8, clean) catch return Error.OutOfMemory;
  692. self.index_fields.append(a, owned) catch return Error.OutOfMemory;
  693. self.idx.put(a, owned, .{ .typ = typ }) catch return Error.OutOfMemory;
  694. if (is_unique) self.unique_fields.append(a, owned) catch return Error.OutOfMemory;
  695. }
  696. // ---- load meta ----
  697. self.loadMeta();
  698. // ---- compact on init (JS default; also creates an empty data file) ----
  699. // AN OPEN WITH NOTHING TO CHANGE WRITES NOTHING (ticket #21): a store
  700. // with no tombstones has nothing to compact, and rewriting it anyway
  701. // made opening a backup change it.
  702. var did_compact = false;
  703. const nothing_to_compact = self.deleted.items.len == 0 and
  704. fio.fileSize(self.tmp, self.data_path) != null;
  705. if (self.compact_on_open and !nothing_to_compact) {
  706. try self.acquireLock();
  707. const cr = if (self.tryExclusive()) blk: {
  708. defer self.backToShared();
  709. break :blk self.compactLocked();
  710. } else self.skipCompaction();
  711. self.releaseLock();
  712. // A REFUSED compaction does not fail the open (ticket #176): nothing
  713. // was rewritten, the store is as it was, and it stays readable; the
  714. // refusal is on stderr and in last_error.
  715. if (cr) |ran| {
  716. did_compact = ran;
  717. } else |e| {
  718. if (e != Error.CompactRefused) return e;
  719. }
  720. }
  721. self.adoptDataFile();
  722. errdefer self.dropDataFile();
  723. // ---- persist schema into meta (JS: init-schema under lock).
  724. // compactLocked already wrote meta (with schema); skip the extra bump.
  725. // A meta found to belong to another data file is replaced at once, so a
  726. // stale one never outlives the open that saw it (ticket #176).
  727. if (!did_compact and (self.meta_stale or ((self.pk != null or self.index_fields.items.len > 0) and
  728. !self.metaOnDiskIsCurrent())))
  729. {
  730. try self.acquireLock();
  731. // Opening read metadata before taking the mutation lock. Another
  732. // writer may have replaced rows since then: never publish our old
  733. // tombstones/version over its committed state. Indexes initialize below,
  734. // so reload metadata alone rather than catching up empty indexes.
  735. self.loadMeta();
  736. const mr = if (self.meta_stale or !self.metaOnDiskIsCurrent()) self.persistMetaLocked() else {};
  737. self.releaseLock();
  738. try mr;
  739. }
  740. // ---- indexes (JS: (re)build under the lock; force after compaction) ----
  741. if (self.index_fields.items.len > 0) {
  742. try self.acquireLock();
  743. const ir = self.initIndexes(did_compact);
  744. self.releaseLock();
  745. try ir;
  746. }
  747. return self;
  748. }
  749. pub fn close(self: *Db) void {
  750. // persist indexes + idxstate (JS: IndexManager.close → persist under lock)
  751. if (self.index_fields.items.len > 0) {
  752. if (self.acquireLock()) {
  753. // MISSION 395 (#203): the index in memory is of the data file this handle holds. Another
  754. // process (the JS mpackdb, a build before #176: none takes the store lock) may have
  755. // rewritten it since; persisting before looking wrote that old generation's offsets
  756. // as the index files — beside an idxstate that named the NEW file.
  757. self.refresh();
  758. self.persistIndexesLocked() catch {};
  759. self.releaseLock();
  760. } else |_| {}
  761. }
  762. self.dropDataFile();
  763. self.delCacheDrop();
  764. self.closeStoreLock();
  765. const gpa = self.arena_state.child_allocator;
  766. self.arena_state.deinit();
  767. gpa.destroy(self);
  768. }
  769. fn dbg(self: *Db, comptime fmt: []const u8, args: anytype) void {
  770. if (self.debug) std.debug.print("[mpackdb] " ++ fmt ++ "\n", args);
  771. }
  772. // =====================================================================
  773. // Locking (JS _acquireFileLock protocol)
  774. // =====================================================================
  775. fn acquireLock(self: *Db) Error!void {
  776. var retries: u32 = 0;
  777. while (true) {
  778. if (fio.openExcl(self.tmp, self.lock_path)) |fd| {
  779. var pid_buf: [16]u8 = undefined;
  780. const pid_s = std.fmt.bufPrint(&pid_buf, "{d}", .{linux.getpid()}) catch "0";
  781. _ = fio.writeAll(fd, pid_s);
  782. fio.close(fd);
  783. return;
  784. }
  785. // stale lock takeover
  786. if (self.stale_lock_timeout_ms > 0) {
  787. if (fio.mtimeMs(self.tmp, self.lock_path)) |mt| {
  788. if (fio.nowMs() - mt > self.stale_lock_timeout_ms) {
  789. _ = fio.unlink(self.tmp, self.lock_path);
  790. continue;
  791. }
  792. }
  793. }
  794. if (retries > 480) return Error.LockTimeout; // ~12s at 25ms
  795. fio.sleepMs(25);
  796. retries += 1;
  797. }
  798. }
  799. fn releaseLock(self: *Db) void {
  800. _ = fio.unlink(self.tmp, self.lock_path);
  801. }
  802. /// Take the shared store lock. The lock file is unlinked by the last handle
  803. /// to close (under the exclusive lock), so a lock taken on a file that is no
  804. /// longer the one at the path is let go and taken anew.
  805. fn openStoreLock(self: *Db) Error!void {
  806. var tries: usize = 0;
  807. while (tries < 1000) : (tries += 1) {
  808. const fd = fio.openz(self.tmp, self.flock_path, .{ .ACCMODE = .RDWR, .CREAT = true, .CLOEXEC = true }, 0o644) orelse return Error.IoError;
  809. if (!fio.flock(fd, fio.LOCK_SH)) {
  810. fio.close(fd);
  811. return Error.IoError;
  812. }
  813. const held = fio.fdIno(fd);
  814. const at_path = fio.stat(self.tmp, self.flock_path);
  815. if (held != null and at_path != null and held.? == at_path.?.ino) {
  816. self.store_fd = fd;
  817. return;
  818. }
  819. fio.close(fd);
  820. }
  821. return Error.LockTimeout;
  822. }
  823. fn closeStoreLock(self: *Db) void {
  824. if (self.store_fd < 0) return;
  825. // the last one out removes the lock file — only while no one else holds it
  826. if (fio.flock(self.store_fd, fio.LOCK_EX | fio.LOCK_NB)) _ = fio.unlink(self.tmp, self.flock_path);
  827. fio.close(self.store_fd);
  828. self.store_fd = -1;
  829. }
  830. /// Exclusive, without waiting: true when no other handle (in any process)
  831. /// holds the store.
  832. fn tryExclusive(self: *Db) bool {
  833. if (self.store_fd < 0) return false;
  834. if (fio.flock(self.store_fd, fio.LOCK_EX | fio.LOCK_NB)) return true;
  835. // a failed conversion may have given up the shared lock: take it again
  836. _ = fio.flock(self.store_fd, fio.LOCK_SH);
  837. return false;
  838. }
  839. fn backToShared(self: *Db) void {
  840. if (self.store_fd >= 0) _ = fio.flock(self.store_fd, fio.LOCK_SH);
  841. }
  842. fn skipCompaction(self: *Db) Error!bool {
  843. self.last_error = "compaction skipped: the store is open in another process";
  844. self.dbg("{s}: {s}", .{ self.data_path, self.last_error });
  845. return false;
  846. }
  847. // =====================================================================
  848. // Meta (.meta.json)
  849. // =====================================================================
  850. fn appendFmt(self: *Db, list: *std.ArrayList(u8), comptime fmt: []const u8, args: anytype) Error!void {
  851. // a short piece is formatted on the stack (mission 436: one heap allocation per
  852. // tombstone / index line made rendering a 3 MB meta cost more than parsing it)
  853. var sbuf: [256]u8 = undefined;
  854. if (std.fmt.bufPrint(&sbuf, fmt, args)) |piece| {
  855. list.appendSlice(self.tmp, piece) catch return Error.OutOfMemory;
  856. return;
  857. } else |_| {}
  858. const s = std.fmt.allocPrint(self.tmp, fmt, args) catch return Error.OutOfMemory;
  859. defer self.tmp.free(s);
  860. list.appendSlice(self.tmp, s) catch return Error.OutOfMemory;
  861. }
  862. fn loadMeta(self: *Db) void {
  863. // stat BEFORE the read: a write racing in between then shows as a change next time
  864. self.meta_seen = fio.stat(self.tmp, self.meta_path);
  865. self.meta_reads += 1;
  866. const content = fio.readAll(self.tmp, self.meta_path) orelse return;
  867. defer self.tmp.free(content);
  868. self.applyMetaJson(content);
  869. }
  870. /// What applyMetaJson needs of the meta's `dataFile` object.
  871. const DataFileMeta = struct {
  872. ino: ?u64 = null,
  873. size: ?u64 = null,
  874. gen: ?u64 = null,
  875. sum: ?[]const u8 = null, // deletedSum when it is a string
  876. fp_present: bool = false,
  877. fp: ?[]const u8 = null, // fp when it is a string
  878. };
  879. /// A JSON number token the way std.json.Value would hold it: an integer, or a float.
  880. const JNum = union(enum) { int: i64, float: f64 };
  881. fn jnum(text: []const u8) ?JNum {
  882. if (std.mem.indexOfAny(u8, text, ".eE") == null) {
  883. return .{ .int = std.fmt.parseInt(i64, text, 10) catch return null };
  884. }
  885. return .{ .float = std.fmt.parseFloat(f64, text) catch return null };
  886. }
  887. /// MISSION 436: the meta of a big table is megabytes (the tracker's shows: 308 K tombstones);
  888. /// std.json.Value built a tagged value per offset, then freed them again. This walks the
  889. /// tokens and keeps only what applyMetaJson reads. It returns false — having changed
  890. /// nothing — for anything it does not recognise or any malformed text, and the Value
  891. /// path below then decides, exactly as before.
  892. fn applyMetaFast(self: *Db, content: []const u8) bool {
  893. var sc = std.json.Scanner.initCompleteInput(self.tmp, content);
  894. defer sc.deinit();
  895. var del: std.ArrayList(u64) = .empty;
  896. defer del.deinit(self.tmp);
  897. var next_id: f64 = FIRST_ID;
  898. var version: u64 = 0;
  899. var df: ?DataFileMeta = null;
  900. const t0 = sc.next() catch return false;
  901. if (t0 != .object_begin) return false;
  902. while (true) {
  903. const kt = sc.next() catch return false;
  904. const key = switch (kt) {
  905. .object_end => break,
  906. .string => |k| k,
  907. else => return false,
  908. };
  909. if (std.mem.eql(u8, key, "nextId")) {
  910. const t = sc.next() catch return false;
  911. next_id = switch (t) {
  912. .number => |n| switch (jnum(n) orelse return false) {
  913. .int => |i| @floatFromInt(i),
  914. .float => |f| f,
  915. },
  916. .string, .true, .false, .null => FIRST_ID,
  917. else => return false,
  918. };
  919. } else if (std.mem.eql(u8, key, "version")) {
  920. const t = sc.next() catch return false;
  921. version = switch (t) {
  922. .number => |n| switch (jnum(n) orelse return false) {
  923. .int => |i| @intCast(@max(i, 0)),
  924. .float => 0,
  925. },
  926. .string, .true, .false, .null => 0,
  927. else => return false,
  928. };
  929. } else if (std.mem.eql(u8, key, "deleted")) {
  930. del.clearRetainingCapacity();
  931. const t = sc.next() catch return false;
  932. switch (t) {
  933. .array_begin => while (true) {
  934. const e = sc.next() catch return false;
  935. switch (e) {
  936. .array_end => break,
  937. .number => |n| {
  938. const off: u64 = switch (jnum(n) orelse return false) {
  939. .int => |i| @intCast(@max(i, 0)),
  940. .float => |f| @intFromFloat(@max(f, 0)),
  941. };
  942. del.append(self.tmp, off) catch return false;
  943. },
  944. .string, .true, .false, .null => {},
  945. else => return false,
  946. }
  947. },
  948. .string, .number, .true, .false, .null => {},
  949. else => return false,
  950. }
  951. } else if (std.mem.eql(u8, key, "dataFile")) {
  952. df = null;
  953. const t = sc.next() catch return false;
  954. switch (t) {
  955. .object_begin => {
  956. var d = DataFileMeta{};
  957. while (true) {
  958. const ik = sc.next() catch return false;
  959. const k2 = switch (ik) {
  960. .object_end => break,
  961. .string => |k| k,
  962. else => return false,
  963. };
  964. const v = sc.next() catch return false;
  965. const is_u64: ?u64 = switch (v) {
  966. .number => |n| switch (jnum(n) orelse return false) {
  967. .int => |i| if (i < 0) null else @intCast(i),
  968. .float => null,
  969. },
  970. .string, .true, .false, .null => null,
  971. else => return false,
  972. };
  973. const str: ?[]const u8 = if (v == .string) v.string else null;
  974. if (std.mem.eql(u8, k2, "ino")) {
  975. d.ino = is_u64;
  976. } else if (std.mem.eql(u8, k2, "size")) {
  977. d.size = is_u64;
  978. } else if (std.mem.eql(u8, k2, "gen")) {
  979. d.gen = is_u64;
  980. } else if (std.mem.eql(u8, k2, "deletedSum")) {
  981. d.sum = str;
  982. } else if (std.mem.eql(u8, k2, "fp")) {
  983. d.fp_present = true;
  984. d.fp = str;
  985. }
  986. }
  987. df = d;
  988. },
  989. .string, .number, .true, .false, .null => {},
  990. else => return false,
  991. }
  992. } else {
  993. sc.skipValue() catch return false;
  994. }
  995. }
  996. const te = sc.next() catch return false;
  997. if (te != .end_of_document) return false;
  998. // parsed whole: apply
  999. self.next_id = next_id;
  1000. self.deleted.clearRetainingCapacity();
  1001. self.delCacheDrop();
  1002. self.version = version;
  1003. self.deleted.appendSlice(self.alloc, del.items) catch {};
  1004. self.bind_known = false;
  1005. self.meta_stale = false;
  1006. if (df) |d| self.applyBinding(d);
  1007. return true;
  1008. }
  1009. fn applyMetaJson(self: *Db, content: []const u8) void {
  1010. if (self.applyMetaFast(content)) return;
  1011. self.applyMetaSlow(content);
  1012. }
  1013. /// The meta through std.json.Value (the reading before mission 436; also the fallback).
  1014. fn applyMetaSlow(self: *Db, content: []const u8) void {
  1015. const parsed = std.json.parseFromSlice(std.json.Value, self.tmp, content, .{}) catch return;
  1016. defer parsed.deinit();
  1017. if (parsed.value != .object) return;
  1018. const obj = parsed.value.object;
  1019. self.next_id = FIRST_ID;
  1020. self.deleted.clearRetainingCapacity();
  1021. self.delCacheDrop();
  1022. self.version = 0;
  1023. if (obj.get("nextId")) |v| {
  1024. self.next_id = switch (v) {
  1025. .integer => |i| @floatFromInt(i),
  1026. .float => |f| f,
  1027. else => FIRST_ID,
  1028. };
  1029. }
  1030. if (obj.get("version")) |v| {
  1031. if (v == .integer) self.version = @intCast(@max(v.integer, 0));
  1032. }
  1033. if (obj.get("deleted")) |v| {
  1034. if (v == .array) {
  1035. for (v.array.items) |it| {
  1036. const off: u64 = switch (it) {
  1037. .integer => |i| @intCast(@max(i, 0)),
  1038. .float => |f| @intFromFloat(@max(f, 0)),
  1039. else => continue,
  1040. };
  1041. self.deleted.append(self.alloc, off) catch {};
  1042. }
  1043. }
  1044. }
  1045. self.bind_known = false;
  1046. self.meta_stale = false;
  1047. const df_v = obj.get("dataFile") orelse return;
  1048. if (df_v != .object) return;
  1049. const df = df_v.object;
  1050. var d = DataFileMeta{ .ino = jsonU64(df.get("ino")), .size = jsonU64(df.get("size")), .gen = jsonU64(df.get("gen")) };
  1051. if (df.get("deletedSum")) |sv| {
  1052. if (sv == .string) d.sum = sv.string;
  1053. }
  1054. if (df.get("fp")) |fv| {
  1055. d.fp_present = true;
  1056. if (fv == .string) d.fp = fv.string;
  1057. }
  1058. self.applyBinding(d);
  1059. }
  1060. /// The tail of applyMetaJson: does the meta's `dataFile` bind it to the data file at the path?
  1061. fn applyBinding(self: *Db, df: DataFileMeta) void {
  1062. const ino = df.ino orelse return;
  1063. const size = df.size orelse return;
  1064. if (df.gen) |g| self.data_gen = @max(self.data_gen, g);
  1065. const sum = df.sum orelse return;
  1066. var sum_buf: [16]u8 = undefined;
  1067. if (!std.mem.eql(u8, sum, self.deletedSum(&sum_buf))) return; // another writer's
  1068. const cur = fio.stat(self.tmp, self.data_path);
  1069. // THE BINDING RULE (ticket 387, after #176): the inode is the fast path, the
  1070. // content is the proof. A byte COPY of an open store (a hot tar, a deploy
  1071. // backup, a restore) has a new inode but the same bytes, and its meta must
  1072. // still apply — its tombstones and newer versions are the store's truth.
  1073. // - same inode, file at least `size` bytes: bound (as in #176).
  1074. // - file shorter than `size`, or gone: stale (a different file).
  1075. // - another inode, meta carries `fp` (fingerprint of the first and last
  1076. // 4 KB of the first `size` bytes): bound if the file's fingerprint over
  1077. // that range equals it (the same content, copied or restored); a data
  1078. // file a compaction replaced differs in content, so it stays stale.
  1079. // - another inode, an OLD meta without `fp`: bound only if every tombstone
  1080. // offset is a plausible frame start in the file (size > 4, fits, and the
  1081. // next frame's header is plausible or EOF). Else stale.
  1082. var bound = false;
  1083. var fp_buf: [16]u8 = undefined;
  1084. var have_fp: ?[]const u8 = null;
  1085. if (cur) |c| {
  1086. if (c.size >= size) {
  1087. if (c.ino == ino) {
  1088. bound = true;
  1089. } else if (df.fp_present) {
  1090. if (df.fp) |fv| {
  1091. have_fp = self.dataFingerprint(size, &fp_buf);
  1092. bound = have_fp != null and std.mem.eql(u8, have_fp.?, fv);
  1093. }
  1094. } else {
  1095. bound = self.tombstonesAreFrameStarts(c.size);
  1096. }
  1097. }
  1098. } else bound = size == 0;
  1099. if (!bound) {
  1100. if (self.deleted.items.len > 0) {
  1101. 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 });
  1102. }
  1103. self.deleted.clearRetainingCapacity();
  1104. self.delCacheDrop();
  1105. self.meta_stale = true;
  1106. return;
  1107. }
  1108. self.bind_known = true;
  1109. self.bind_ino = if (cur) |c| c.ino else ino; // a copy: this file's inode from now on
  1110. self.bind_size = size;
  1111. self.bind_fp_len = 0;
  1112. if (have_fp == null) have_fp = self.dataFingerprint(size, &fp_buf);
  1113. if (have_fp) |f| {
  1114. @memcpy(self.bind_fp[0..f.len], f);
  1115. self.bind_fp_len = @intCast(f.len);
  1116. }
  1117. }
  1118. /// Fingerprint (16 hex chars) of the first `n` bytes of the data file: a hash of
  1119. /// its first 4 KB and one of the 4 KB before `n`. Appends past `n` do not change
  1120. /// it; a replaced (compacted) file, with other records at those places, does.
  1121. fn dataFingerprint(self: *Db, n: u64, buf: *[16]u8) ?[]const u8 {
  1122. const fd = fio.openRead(self.tmp, self.data_path) orelse return null;
  1123. defer fio.close(fd);
  1124. return fingerprintFd(fd, n, buf);
  1125. }
  1126. fn fingerprintFd(fd: i32, n: u64, buf: *[16]u8) ?[]const u8 {
  1127. var h = std.hash.Wyhash.init(387);
  1128. var blk: [4096]u8 = undefined;
  1129. const head: usize = @intCast(@min(n, 4096));
  1130. const got = fio.pread(fd, blk[0..head], 0) orelse return null;
  1131. if (got != head) return null;
  1132. h.update(blk[0..head]);
  1133. const tail_off = n - head;
  1134. const got2 = fio.pread(fd, blk[0..head], tail_off) orelse return null;
  1135. if (got2 != head) return null;
  1136. h.update(blk[0..head]);
  1137. return std.fmt.bufPrint(buf, "{x:0>16}", .{h.final()}) catch null;
  1138. }
  1139. /// An old meta (no fingerprint) beside a file of another inode: are its tombstones
  1140. /// frame starts of this file? A frame start has a size > 4 that fits in the file,
  1141. /// and is followed by EOF or another plausible frame header.
  1142. fn tombstonesAreFrameStarts(self: *Db, file_size: u64) bool {
  1143. const fd = fio.openRead(self.tmp, self.data_path) orelse return self.deleted.items.len == 0;
  1144. defer fio.close(fd);
  1145. for (self.deleted.items) |off| {
  1146. if (!frameHeaderOk(fd, off, file_size)) return false;
  1147. var hdr: [4]u8 = undefined;
  1148. _ = fio.pread(fd, &hdr, off);
  1149. const next = off + std.mem.readInt(u32, &hdr, .little);
  1150. if (next != file_size and !frameHeaderOk(fd, next, file_size)) return false;
  1151. }
  1152. return true;
  1153. }
  1154. fn frameHeaderOk(fd: i32, off: u64, file_size: u64) bool {
  1155. if (off + 4 > file_size) return false;
  1156. var hdr: [4]u8 = undefined;
  1157. const got = fio.pread(fd, &hdr, off) orelse return false;
  1158. if (got < 4) return false;
  1159. const sz: u64 = std.mem.readInt(u32, &hdr, .little);
  1160. return sz > 4 and off + sz <= file_size;
  1161. }
  1162. fn jsonU64(v: ?std.json.Value) ?u64 {
  1163. const x = v orelse return null;
  1164. return switch (x) {
  1165. .integer => |i| if (i < 0) null else @intCast(i),
  1166. else => null,
  1167. };
  1168. }
  1169. /// The checksum of the deleted list (hex), as dataFile.deletedSum carries it.
  1170. fn deletedSum(self: *Db, buf: *[16]u8) []const u8 {
  1171. var h = std.hash.Wyhash.init(176);
  1172. // the stream of little-endian u64s, fed in blocks (the hash does not depend on the split)
  1173. var blk: [512]u64 = undefined;
  1174. var i: usize = 0;
  1175. while (i < self.deleted.items.len) {
  1176. const n = @min(blk.len, self.deleted.items.len - i);
  1177. for (0..n) |j| blk[j] = std.mem.nativeToLittle(u64, self.deleted.items[i + j]);
  1178. h.update(std.mem.sliceAsBytes(blk[0..n]));
  1179. i += n;
  1180. }
  1181. return std.fmt.bufPrint(buf, "{x:0>16}", .{h.final()}) catch buf[0..0];
  1182. }
  1183. /// Pick up other processes' persisted state (JS refresh()): adopt disk meta
  1184. /// when its version is newer; index appended tail records.
  1185. ///
  1186. /// A HANDLE NOTICES A REWRITE (ticket #176). Another process's compaction
  1187. /// replaces the data file and moves every record after its first tombstone;
  1188. /// this handle's offsets are then into a file that no longer exists, and
  1189. /// reading them read the middle of other records — a bare Number where a
  1190. /// record was (the tracker, 2026-10-20). The data file's inode, a size below
  1191. /// what was indexed, or a newer compaction generation in the meta says it
  1192. /// happened; the handle then re-reads the meta (dropping a deleted list that
  1193. /// belongs to the old file) and re-indexes the new file before it answers.
  1194. pub fn refresh(self: *Db) void {
  1195. if (self.data_fd < 0) self.adoptDataFile(); // a file created since the open
  1196. if (self.index_bad) self.rebuildIndexesFromData();
  1197. const cur = fio.stat(self.tmp, self.data_path);
  1198. var rewritten = false;
  1199. if (cur) |c| {
  1200. if (self.seen_ino != 0 and c.ino != self.seen_ino) rewritten = true;
  1201. if (self.index_fields.items.len > 0 and c.size < self.covered_bytes) rewritten = true;
  1202. }
  1203. const meta_now = fio.stat(self.tmp, self.meta_path);
  1204. 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;
  1205. // an unchanged meta says nothing new: its version and generation were taken when read
  1206. // (a rewritten data file still re-reads it, to drop a deleted list of the old file)
  1207. if (meta_same and !rewritten) {
  1208. // nothing to read
  1209. } else if (blk: {
  1210. self.meta_seen = meta_now;
  1211. self.meta_reads += 1;
  1212. break :blk fio.readAll(self.tmp, self.meta_path);
  1213. }) |content| {
  1214. defer self.tmp.free(content);
  1215. const parsed = std.json.parseFromSlice(std.json.Value, self.tmp, content, .{}) catch return;
  1216. defer parsed.deinit();
  1217. if (parsed.value == .object) {
  1218. var disk_version: u64 = 0;
  1219. if (parsed.value.object.get("version")) |v| {
  1220. if (v == .integer) disk_version = @intCast(@max(v.integer, 0));
  1221. }
  1222. if (parsed.value.object.get("dataFile")) |df| {
  1223. if (df == .object) {
  1224. if (jsonU64(df.object.get("gen"))) |g| {
  1225. if (g > self.data_gen) rewritten = true;
  1226. }
  1227. }
  1228. }
  1229. if (rewritten or disk_version > self.version) self.applyMetaJson(content);
  1230. }
  1231. }
  1232. if (rewritten) {
  1233. self.reindexRewritten();
  1234. return;
  1235. }
  1236. // catchUp: index records another process appended
  1237. if (self.index_fields.items.len > 0) {
  1238. const size = if (cur) |c| c.size else 0;
  1239. if (size > self.covered_bytes) self.catchUp(size);
  1240. }
  1241. }
  1242. /// THE INDEX NAMED A PLACE THAT IS NO RECORD (mission 393): the tracker's persons.id.txt
  1243. /// carried ~2100 entries with offsets past the end of the data file or into the middle of a
  1244. /// frame (entries of an older generation of the file), so range('id', …) answered a Number
  1245. /// where a record was ("reading 'id': the value is Number"). A hit is checked against its
  1246. /// frame header before it is returned; a bad one is dropped and the indexes are rebuilt from
  1247. /// the data file at the next refresh.
  1248. fn hitOk(self: *Db, h: Entry) bool {
  1249. if (self.data_fd < 0) return true;
  1250. var hdr: [4]u8 = undefined;
  1251. const got = fio.pread(self.data_fd, &hdr, h.off) orelse 0;
  1252. if (got == 4 and std.mem.readInt(u32, &hdr, .little) == h.len) return true;
  1253. self.index_bad = true;
  1254. return false;
  1255. }
  1256. fn rebuildIndexesFromData(self: *Db) void {
  1257. self.index_bad = false;
  1258. self.covered_bytes = 0;
  1259. var it0 = self.idx.iterator();
  1260. while (it0.next()) |kv| kv.value_ptr.entries.clearRetainingCapacity();
  1261. if (self.index_fields.items.len > 0) {
  1262. const size: u64 = if (self.data_fd >= 0) (if (fio.fdStat(self.data_fd)) |st| st.size else 0) else 0;
  1263. self.catchUp(size);
  1264. }
  1265. std.debug.print("mpackdb: {s}: an index named a place that is no record; indexes rebuilt from the data file\n", .{self.data_path});
  1266. }
  1267. /// The data file was replaced under this handle: index it anew, in memory —
  1268. /// the index files are written when the handle persists or closes.
  1269. fn reindexRewritten(self: *Db) void {
  1270. const old_ino = self.seen_ino;
  1271. self.adoptDataFile();
  1272. 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 });
  1273. self.covered_bytes = 0;
  1274. var it0 = self.idx.iterator();
  1275. while (it0.next()) |kv| kv.value_ptr.entries.clearRetainingCapacity();
  1276. if (self.index_fields.items.len > 0) {
  1277. const size: u64 = if (self.data_fd >= 0) (if (fio.fdStat(self.data_fd)) |st| st.size else 0) else 0;
  1278. self.catchUp(size);
  1279. }
  1280. }
  1281. /// Hold the data file now at the path; its inode is what the offsets are into.
  1282. fn adoptDataFile(self: *Db) void {
  1283. self.dropDataFile();
  1284. self.data_fd = fio.openz(self.tmp, self.data_path, .{ .CLOEXEC = true }, 0) orelse -1;
  1285. if (self.data_fd >= 0) self.fd_gen = DataGen.create(self.tmp, self.data_fd);
  1286. self.seen_ino = if (self.data_fd >= 0) (fio.fdIno(self.data_fd) orelse 0) else 0;
  1287. }
  1288. fn dropDataFile(self: *Db) void {
  1289. if (self.fd_gen) |g| g.release() else if (self.data_fd >= 0) fio.close(self.data_fd);
  1290. self.fd_gen = null;
  1291. self.data_fd = -1;
  1292. }
  1293. fn persistMetaLocked(self: *Db) Error!void {
  1294. self.version += 1;
  1295. const cur = fio.stat(self.tmp, self.data_path);
  1296. self.bind_ino = if (cur) |c| c.ino else 0;
  1297. self.bind_size = if (cur) |c| c.size else 0;
  1298. self.bind_fp_len = 0;
  1299. var fpb: [16]u8 = undefined;
  1300. if (self.dataFingerprint(self.bind_size, &fpb)) |f| {
  1301. @memcpy(self.bind_fp[0..f.len], f);
  1302. self.bind_fp_len = @intCast(f.len);
  1303. }
  1304. self.bind_known = true;
  1305. self.meta_stale = false;
  1306. var out: std.ArrayList(u8) = .empty;
  1307. defer out.deinit(self.tmp);
  1308. try self.renderMeta(&out);
  1309. // atomic tmp + rename (JS: `${metaPath}.${pid}.tmp`)
  1310. var tmp_buf: [512]u8 = undefined;
  1311. const tmp_path = std.fmt.bufPrint(&tmp_buf, "{s}.{d}.tmp", .{ self.meta_path, linux.getpid() }) catch return Error.IoError;
  1312. const fd = fio.openTrunc(self.tmp, tmp_path) orelse return Error.IoError;
  1313. const ok = fio.writeAll(fd, out.items);
  1314. // the tmp file's own stat: rename keeps the inode, and no other writer can slip in
  1315. // between a stat of the path and our remembering it (ticket #188)
  1316. const written = fio.fdStat(fd);
  1317. fio.close(fd);
  1318. if (!ok) return Error.IoError;
  1319. if (!fio.rename(self.tmp, tmp_path, self.meta_path)) return Error.IoError;
  1320. self.meta_seen = written;
  1321. }
  1322. /// Does .meta.json already say, byte for byte, what this handle would write
  1323. /// at its current version? Then an open has nothing to persist (ticket #21).
  1324. fn metaOnDiskIsCurrent(self: *Db) bool {
  1325. const disk = fio.readAll(self.tmp, self.meta_path) orelse return false;
  1326. defer self.tmp.free(disk);
  1327. var out: std.ArrayList(u8) = .empty;
  1328. defer out.deinit(self.tmp);
  1329. self.renderMeta(&out) catch return false;
  1330. return std.mem.eql(u8, disk, out.items);
  1331. }
  1332. fn renderMeta(self: *Db, out: *std.ArrayList(u8)) Error!void {
  1333. try self.appendFmt(out, "{{", .{});
  1334. if (self.pk != null and self.pk_type == .number) {
  1335. var nbuf: [32]u8 = undefined;
  1336. try self.appendFmt(out, "\"nextId\":{s},", .{jsNumFmt(&nbuf, self.next_id)});
  1337. }
  1338. try self.appendFmt(out, "\"deleted\":[", .{});
  1339. out.ensureUnusedCapacity(self.tmp, self.deleted.items.len * 9 + 64) catch return Error.OutOfMemory;
  1340. for (self.deleted.items, 0..) |off, i| {
  1341. out.ensureUnusedCapacity(self.tmp, 24) catch return Error.OutOfMemory;
  1342. if (i > 0) out.appendAssumeCapacity(',');
  1343. const spare = out.unusedCapacitySlice();
  1344. const w = std.fmt.bufPrint(spare, "{d}", .{off}) catch return Error.OutOfMemory;
  1345. out.items.len += w.len;
  1346. }
  1347. try self.appendFmt(out, "],\"version\":{d}", .{self.version});
  1348. if (self.pk != null or self.index_fields.items.len > 0) {
  1349. try self.appendFmt(out, ",\"schema\":{{", .{});
  1350. var first = true;
  1351. if (self.pk) |p| {
  1352. const prefix: []const u8 = switch (self.pk_type) {
  1353. .number => "*",
  1354. .uuid => "@",
  1355. .string => "",
  1356. };
  1357. try self.appendFmt(out, "\"primaryKey\":\"{s}{s}\"", .{ prefix, p });
  1358. first = false;
  1359. }
  1360. if (!first) try self.appendFmt(out, ",", .{});
  1361. try self.appendFmt(out, "\"indexes\":[", .{});
  1362. var n: usize = 0;
  1363. for (self.index_fields.items) |field| {
  1364. if (self.pk != null and std.mem.eql(u8, field, self.pk.?)) continue;
  1365. if (n > 0) try self.appendFmt(out, ",", .{});
  1366. const uni = for (self.unique_fields.items) |u| {
  1367. if (std.mem.eql(u8, u, field)) break true;
  1368. } else false;
  1369. const numeric = (self.idx.get(field) orelse FieldIndex{ .typ = .lexical }).typ == .numeric;
  1370. try self.appendFmt(out, "\"{s}{s}{s}\"", .{
  1371. if (uni) "!" else "",
  1372. if (numeric) "*" else "",
  1373. field,
  1374. });
  1375. n += 1;
  1376. }
  1377. try self.appendFmt(out, "]}}", .{});
  1378. }
  1379. if (self.bind_known) {
  1380. var sum_buf: [16]u8 = undefined;
  1381. 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) });
  1382. if (self.bind_fp_len > 0) try self.appendFmt(out, ",\"fp\":\"{s}\"", .{self.bind_fp[0..self.bind_fp_len]});
  1383. try self.appendFmt(out, "}}", .{});
  1384. }
  1385. try self.appendFmt(out, "}}", .{});
  1386. }
  1387. // =====================================================================
  1388. // Data file scanning
  1389. // =====================================================================
  1390. fn deletedSet(self: *Db, alloc: std.mem.Allocator) std.AutoHashMapUnmanaged(u64, void) {
  1391. var set: std.AutoHashMapUnmanaged(u64, void) = .empty;
  1392. for (self.deleted.items) |off| set.put(alloc, off, {}) catch {};
  1393. return set;
  1394. }
  1395. /// The cached tombstone set, built on first use (borrowed: valid until the next
  1396. /// delete / meta adoption / compaction; hold it with delSetAcquire to keep it).
  1397. fn delSetCached(self: *Db) *DelSet {
  1398. if (self.del_cache) |c| return c;
  1399. const c = self.tmp.create(DelSet) catch unreachable;
  1400. c.* = .{ .alloc = self.tmp };
  1401. c.map.ensureTotalCapacity(self.tmp, @intCast(self.deleted.items.len)) catch {};
  1402. for (self.deleted.items) |off| c.map.put(self.tmp, off, {}) catch {};
  1403. self.del_cache = c;
  1404. return c;
  1405. }
  1406. /// A reference the caller must release() — a frozen view of the tombstones.
  1407. pub fn delSetAcquire(self: *Db) *DelSet {
  1408. const c = self.delSetCached();
  1409. c.refs += 1;
  1410. return c;
  1411. }
  1412. fn delCacheDrop(self: *Db) void {
  1413. if (self.del_cache) |c| c.release();
  1414. self.del_cache = null;
  1415. }
  1416. fn delCacheAdd(self: *Db, off: u64) void {
  1417. const c = self.del_cache orelse return;
  1418. if (c.refs > 1) {
  1419. // a cursor holds this set: it keeps it unchanged, the Db goes on with a copy
  1420. const n = self.tmp.create(DelSet) catch {
  1421. self.delCacheDrop();
  1422. return;
  1423. };
  1424. n.* = .{ .alloc = self.tmp };
  1425. n.map = c.map.clone(self.tmp) catch {
  1426. self.tmp.destroy(n);
  1427. self.delCacheDrop();
  1428. return;
  1429. };
  1430. c.release();
  1431. self.del_cache = n;
  1432. }
  1433. self.del_cache.?.map.put(self.tmp, off, {}) catch self.delCacheDrop();
  1434. }
  1435. /// Sequential scan yielding all live records. Caller supplies an arena for
  1436. /// decoded values. Used for rebuilds, compaction and unindexed finds.
  1437. pub const Scanner = struct {
  1438. db: *Db,
  1439. fd: i32 = -1,
  1440. offset: u64 = 0,
  1441. size: u64 = 0,
  1442. skip_deleted: bool = true,
  1443. owns_fd: bool = true,
  1444. /// a detached scanner's reference to the data file generation (instead of a dup)
  1445. gen: ?*DataGen = null,
  1446. /// a frozen view of the tombstones (null when !skip_deleted); released by deinit
  1447. deleted_set: ?*DelSet = null,
  1448. scratch: std.mem.Allocator,
  1449. pub fn init(db: *Db, scratch: std.mem.Allocator, skip_deleted: bool) Scanner {
  1450. return initOpt(db, scratch, skip_deleted, false);
  1451. }
  1452. /// `detached` (a streaming cursor): the scanner holds a reference to the data file generation (no dup), so a compaction
  1453. /// or a foreign rewrite that makes the Db move to a new file leaves the scan reading
  1454. /// the file it started on; it also freezes the size and the tombstones (mission 393).
  1455. pub fn initOpt(db: *Db, scratch: std.mem.Allocator, skip_deleted: bool, detached: bool) Scanner {
  1456. var s = Scanner{ .db = db, .scratch = scratch, .skip_deleted = skip_deleted };
  1457. if (db.data_fd >= 0) {
  1458. // the file the handle's offsets are into (#176), not whatever is at the path
  1459. if (detached) {
  1460. if (db.fd_gen) |g| {
  1461. s.gen = g.retain();
  1462. s.fd = g.fd;
  1463. s.owns_fd = false;
  1464. } else {
  1465. s.fd = db.data_fd;
  1466. s.owns_fd = false;
  1467. }
  1468. } else {
  1469. s.fd = db.data_fd;
  1470. s.owns_fd = false;
  1471. }
  1472. s.size = if (fio.fdStat(s.fd)) |st| st.size else 0;
  1473. } else {
  1474. s.size = fio.fileSize(scratch, db.data_path) orelse 0;
  1475. if (s.size > 0) {
  1476. s.fd = fio.openRead(scratch, db.data_path) orelse -1;
  1477. }
  1478. }
  1479. if (skip_deleted) s.deleted_set = db.delSetAcquire();
  1480. return s;
  1481. }
  1482. pub fn deinit(self: *Scanner) void {
  1483. if (self.gen) |g| g.release();
  1484. self.gen = null;
  1485. if (self.fd >= 0 and self.owns_fd) fio.close(self.fd);
  1486. self.fd = -1;
  1487. if (self.deleted_set) |d| d.release();
  1488. self.deleted_set = null;
  1489. }
  1490. /// Returns the next record (decoded into `arena`) or null at EOF.
  1491. pub fn next(self: *Scanner, arena: std.mem.Allocator) Error!?Record {
  1492. while (true) {
  1493. if (self.fd < 0 or self.offset + 4 > self.size) return null;
  1494. var hdr: [4]u8 = undefined;
  1495. const got = fio.pread(self.fd, &hdr, self.offset) orelse return Error.IoError;
  1496. if (got < 4) return null;
  1497. const rec_size = std.mem.readInt(u32, &hdr, .little);
  1498. if (rec_size <= 4) return Error.CorruptRecord;
  1499. if (self.offset + rec_size > self.size) return null; // incomplete tail
  1500. const off = self.offset;
  1501. self.offset += rec_size;
  1502. if (self.deleted_set) |d| {
  1503. if (d.map.contains(off)) continue;
  1504. }
  1505. const buf = arena.alloc(u8, rec_size - 4) catch return Error.OutOfMemory;
  1506. const got2 = fio.pread(self.fd, buf, off + 4) orelse return Error.IoError;
  1507. if (got2 < rec_size - 4) return Error.Truncated;
  1508. const d = msgpack.decode(arena, buf) catch return Error.CorruptRecord;
  1509. return Record{ .value = d.value, .off = off, .len = rec_size };
  1510. }
  1511. }
  1512. /// The number of live records from here on, reading only the 4-byte frame headers:
  1513. /// nothing is decoded or kept (count() decoded the whole table into an arena, 2 GB
  1514. /// for the tracker's two big tables).
  1515. pub fn countLive(self: *Scanner) Error!usize {
  1516. var n: usize = 0;
  1517. while (true) {
  1518. if (self.fd < 0 or self.offset + 4 > self.size) return n;
  1519. var hdr: [4]u8 = undefined;
  1520. const got = fio.pread(self.fd, &hdr, self.offset) orelse return Error.IoError;
  1521. if (got < 4) return n;
  1522. const rec_size = std.mem.readInt(u32, &hdr, .little);
  1523. if (rec_size <= 4) return Error.CorruptRecord;
  1524. if (self.offset + rec_size > self.size) return n;
  1525. const off = self.offset;
  1526. self.offset += rec_size;
  1527. if (self.deleted_set) |d| {
  1528. if (d.map.contains(off)) continue;
  1529. }
  1530. n += 1;
  1531. }
  1532. }
  1533. /// Like next() but without decoding — yields the raw framed bytes.
  1534. pub fn nextRaw(self: *Scanner, arena: std.mem.Allocator) Error!?struct { bytes: []u8, off: u64 } {
  1535. while (true) {
  1536. if (self.fd < 0 or self.offset + 4 > self.size) return null;
  1537. var hdr: [4]u8 = undefined;
  1538. const got = fio.pread(self.fd, &hdr, self.offset) orelse return Error.IoError;
  1539. if (got < 4) return null;
  1540. const rec_size = std.mem.readInt(u32, &hdr, .little);
  1541. if (rec_size <= 4) return Error.CorruptRecord;
  1542. if (self.offset + rec_size > self.size) return null;
  1543. const off = self.offset;
  1544. self.offset += rec_size;
  1545. if (self.deleted_set) |d| {
  1546. if (d.map.contains(off)) continue;
  1547. }
  1548. const buf = arena.alloc(u8, rec_size) catch return Error.OutOfMemory;
  1549. const got2 = fio.pread(self.fd, buf, off) orelse return Error.IoError;
  1550. if (got2 < rec_size) return Error.Truncated;
  1551. return .{ .bytes = buf, .off = off };
  1552. }
  1553. }
  1554. };
  1555. /// A reference to the data file the offsets are into, for a streaming cursor (null: none).
  1556. /// Release it with `DataGen.release`; the fd (`.fd`) stays valid until then.
  1557. pub fn retainDataGen(self: *Db) ?*DataGen {
  1558. const g = self.fd_gen orelse return null;
  1559. return g.retain();
  1560. }
  1561. /// Read + decode one record by location from `fd` (a dupDataFd of the file the loc is into).
  1562. pub fn readAtFd(fd: i32, arena: std.mem.Allocator, loc: Loc) Error!msgpack.Value {
  1563. if (loc.len <= 4) return Error.CorruptRecord;
  1564. const buf = arena.alloc(u8, loc.len - 4) catch return Error.OutOfMemory;
  1565. const got = fio.pread(fd, buf, loc.off + 4) orelse return Error.IoError;
  1566. if (got < buf.len) return Error.Truncated;
  1567. const d = msgpack.decode(arena, buf) catch return Error.CorruptRecord;
  1568. return d.value;
  1569. }
  1570. /// Read + decode one record by location.
  1571. pub fn readAt(self: *Db, arena: std.mem.Allocator, loc: Loc) Error!msgpack.Value {
  1572. const own = self.data_fd < 0;
  1573. const fd = if (own) (fio.openRead(self.tmp, self.data_path) orelse return Error.IoError) else self.data_fd;
  1574. defer if (own) fio.close(fd);
  1575. if (loc.len <= 4) return Error.CorruptRecord;
  1576. const buf = arena.alloc(u8, loc.len - 4) catch return Error.OutOfMemory;
  1577. const got = fio.pread(fd, buf, loc.off + 4) orelse return Error.IoError;
  1578. if (got < buf.len) return Error.Truncated;
  1579. const d = msgpack.decode(arena, buf) catch return Error.CorruptRecord;
  1580. return d.value;
  1581. }
  1582. // =====================================================================
  1583. // Index management
  1584. // =====================================================================
  1585. fn keyFromValue(v: msgpack.Value) ?Key {
  1586. return switch (v) {
  1587. .number => |n| Key{ .num = n },
  1588. .str => |s| Key{ .str = s },
  1589. else => null, // null/bool/objects are not indexed (see header note)
  1590. };
  1591. }
  1592. /// Duplicate a key's string into the db arena so it outlives the op arena.
  1593. fn ownKey(self: *Db, k: Key) Error!Key {
  1594. return switch (k) {
  1595. .num => k,
  1596. .str => |s| Key{ .str = (if (self.bulk_keys) |ka| ka.allocator() else self.alloc).dupe(u8, s) catch return Error.OutOfMemory },
  1597. };
  1598. }
  1599. /// Copy every string key of every index into one run of memory, in the lists' order.
  1600. fn packKeys(self: *Db) void {
  1601. for (self.idx.values()) |*fi| {
  1602. var total: usize = 0;
  1603. for (fi.entries.items) |e| {
  1604. if (e.key == .str) total += e.key.str.len;
  1605. }
  1606. if (total == 0) continue;
  1607. const slab = self.alloc.alloc(u8, total) catch continue;
  1608. var pos: usize = 0;
  1609. for (fi.entries.items) |*e| {
  1610. if (e.key == .str) {
  1611. const k = e.key.str;
  1612. @memcpy(slab[pos..][0..k.len], k);
  1613. e.key = .{ .str = slab[pos..][0..k.len] };
  1614. pos += k.len;
  1615. }
  1616. }
  1617. }
  1618. }
  1619. fn lowerBound(entries: []const Entry, key: Key) usize {
  1620. var lo: usize = 0;
  1621. var hi: usize = entries.len;
  1622. while (lo < hi) {
  1623. const mid = lo + (hi - lo) / 2;
  1624. if (cmpKeys(entries[mid].key, key) < 0) {
  1625. lo = mid + 1;
  1626. } else {
  1627. hi = mid;
  1628. }
  1629. }
  1630. return lo;
  1631. }
  1632. /// Binary search: all entries whose key equals `key` (appended to `out`).
  1633. pub fn indexGet(self: *Db, field: []const u8, key: Key, alloc: std.mem.Allocator, out: *std.ArrayList(Entry)) Error!void {
  1634. const fi = self.idx.getPtr(field) orelse return Error.NoSuchIndex;
  1635. const parsed = self.parseKeyForField(field, key);
  1636. const entries = fi.entries.items;
  1637. var i = lowerBound(entries, parsed);
  1638. while (i < entries.len and cmpKeys(entries[i].key, parsed) == 0) : (i += 1) {
  1639. out.append(alloc, entries[i]) catch return Error.OutOfMemory;
  1640. }
  1641. }
  1642. /// Range scan [from, to] (either side optional), ascending.
  1643. pub fn indexRange(self: *Db, field: []const u8, from: ?Key, to: ?Key, alloc: std.mem.Allocator, out: *std.ArrayList(Entry)) Error!void {
  1644. const fi = self.idx.getPtr(field) orelse return Error.NoSuchIndex;
  1645. const entries = fi.entries.items;
  1646. var i: usize = if (from) |f| lowerBound(entries, self.parseKeyForField(field, f)) else 0;
  1647. const to_key: ?Key = if (to) |t| self.parseKeyForField(field, t) else null;
  1648. while (i < entries.len) : (i += 1) {
  1649. if (to_key) |t| {
  1650. if (cmpKeys(entries[i].key, t) > 0) break;
  1651. }
  1652. out.append(alloc, entries[i]) catch return Error.OutOfMemory;
  1653. }
  1654. }
  1655. /// _parseKey semantics: numeric index fields parse string keys via
  1656. /// parseInt; on NaN the key stays a string.
  1657. fn parseKeyForField(self: *Db, field: []const u8, key: Key) Key {
  1658. const fi = self.idx.get(field) orelse return key;
  1659. if (fi.typ == .numeric and key == .str) {
  1660. if (jsParseInt(key.str)) |n| return Key{ .num = n };
  1661. }
  1662. return key;
  1663. }
  1664. fn indexInsertEntry(self: *Db, field: []const u8, key: Key, loc: Loc) Error!void {
  1665. const fi = self.idx.getPtr(field) orelse return;
  1666. const owned = try self.ownKey(key);
  1667. const e = Entry{ .key = owned, .off = loc.off, .len = loc.len };
  1668. // a bulk scan (rebuild / big catch-up) appends and sorts once at the end: a sorted
  1669. // insert per record is a memmove of the whole list each time — quadratic (#376)
  1670. if (self.bulk_index) {
  1671. fi.entries.append(self.alloc, e) catch return Error.OutOfMemory;
  1672. return;
  1673. }
  1674. // insert at sorted position
  1675. const pos = blk: {
  1676. var lo: usize = 0;
  1677. var hi: usize = fi.entries.items.len;
  1678. while (lo < hi) {
  1679. const mid = lo + (hi - lo) / 2;
  1680. if (entryLess({}, fi.entries.items[mid], e)) {
  1681. lo = mid + 1;
  1682. } else {
  1683. hi = mid;
  1684. }
  1685. }
  1686. break :blk lo;
  1687. };
  1688. fi.entries.insert(self.alloc, pos, e) catch return Error.OutOfMemory;
  1689. }
  1690. /// Index a record's fields at loc.
  1691. fn indexInsertRecord(self: *Db, rec: msgpack.Value, loc: Loc) Error!void {
  1692. for (self.index_fields.items) |field| {
  1693. const v = rec.get(field) orelse continue;
  1694. const key = keyFromValue(v) orelse continue;
  1695. try self.indexInsertEntry(field, key, loc);
  1696. }
  1697. self.covered_bytes = @max(self.covered_bytes, loc.off + loc.len);
  1698. }
  1699. /// Remove all entries pointing at offset `off` (all fields).
  1700. fn indexRemoveOffset(self: *Db, off: u64) void {
  1701. var it = self.idx.iterator();
  1702. while (it.next()) |kv| {
  1703. const list = &kv.value_ptr.entries;
  1704. var i: usize = 0;
  1705. while (i < list.items.len) {
  1706. if (list.items[i].off == off) {
  1707. _ = list.orderedRemove(i);
  1708. } else {
  1709. i += 1;
  1710. }
  1711. }
  1712. }
  1713. }
  1714. fn indexPath(self: *Db, buf: []u8, field: []const u8) []const u8 {
  1715. // <dir>/<base>.<field>.txt — derive from idxstate path (…/base.idxstate.json)
  1716. const prefix = self.idxstate_path[0 .. self.idxstate_path.len - "idxstate.json".len];
  1717. return std.fmt.bufPrint(buf, "{s}{s}.txt", .{ prefix, field }) catch buf[0..0];
  1718. }
  1719. fn initIndexes(self: *Db, force_rebuild: bool) Error!void {
  1720. var need_rebuild = force_rebuild;
  1721. const data_size = fio.fileSize(self.tmp, self.data_path) orelse 0;
  1722. if (!need_rebuild) {
  1723. for (self.index_fields.items) |field| {
  1724. var pbuf: [512]u8 = undefined;
  1725. const p = self.indexPath(&pbuf, field);
  1726. const isize_ = fio.fileSize(self.tmp, p);
  1727. if (isize_ == null or isize_.? == 0) {
  1728. if (data_size > 0) {
  1729. need_rebuild = true;
  1730. break;
  1731. }
  1732. }
  1733. }
  1734. }
  1735. if (!need_rebuild) {
  1736. // coveredBytes from idxstate — no state file means rebuild (JS). An
  1737. // idxstate of another data file (its inode, or more bytes covered
  1738. // than there are) means the index files are another file's too:
  1739. // a crash between a compaction's rename and its rebuild (#176).
  1740. if (self.readIdxState()) |st| {
  1741. self.covered_bytes = st.covered;
  1742. const cur = fio.stat(self.tmp, self.data_path);
  1743. const cur_ino: u64 = if (cur) |c| c.ino else 0;
  1744. if (st.covered > data_size) need_rebuild = true;
  1745. if (st.fmt < idx_format) need_rebuild = true;
  1746. if (st.ino) |i| {
  1747. self.idx_bind_known = true;
  1748. // another inode: a byte COPY of the store (ticket 387) has the same
  1749. // content over the covered bytes, so its index files are right
  1750. if (i != cur_ino) {
  1751. var fpb: [16]u8 = undefined;
  1752. const same = st.has_fp and st.covered <= data_size and
  1753. if (self.dataFingerprint(st.covered, &fpb)) |f| std.mem.eql(u8, f, &st.fp) else false;
  1754. if (!same) need_rebuild = true;
  1755. }
  1756. }
  1757. } else {
  1758. need_rebuild = true;
  1759. }
  1760. }
  1761. if (need_rebuild) {
  1762. try self.rebuildIndexes();
  1763. return;
  1764. }
  1765. // Load index files into memory
  1766. for (self.index_fields.items) |field| {
  1767. var pbuf: [512]u8 = undefined;
  1768. const p = self.indexPath(&pbuf, field);
  1769. // the keys point INTO the file's bytes (mission 436: one allocation + copy per key
  1770. // was most of the load); a numeric index keeps no key text, so its buffer goes back
  1771. const numeric = (self.idx.get(field) orelse continue).typ == .numeric;
  1772. const content = fio.readAll(if (numeric) self.tmp else self.alloc, p) orelse continue;
  1773. var keep = false;
  1774. self.loadIndexLines(field, content, &keep);
  1775. if (numeric and !keep) self.tmp.free(content);
  1776. }
  1777. // sort (files are sorted by JS localeCompare; re-sort under our order). A file we wrote
  1778. // is in our order already: checking is a pass, pdq with a key compare per step is more.
  1779. var it = self.idx.iterator();
  1780. while (it.next()) |kv| {
  1781. const items = kv.value_ptr.entries.items;
  1782. if (!std.sort.isSorted(Entry, items, {}, entryLess)) sortEntries(self.tmp, items);
  1783. }
  1784. if (data_size > self.covered_bytes) self.catchUp(data_size);
  1785. }
  1786. /// parseInt(u64, s, 10) with a loop for the plain all-digits case.
  1787. fn parseU64(s: []const u8) ?u64 {
  1788. if (s.len == 0 or s.len > 19) return std.fmt.parseInt(u64, s, 10) catch null;
  1789. var v: u64 = 0;
  1790. for (s) |c| {
  1791. if (c < '0' or c > '9') return std.fmt.parseInt(u64, s, 10) catch null;
  1792. v = v * 10 + (c - '0');
  1793. }
  1794. return v;
  1795. }
  1796. /// `content` must outlive the entries when `keep` is set: string keys are slices of it.
  1797. fn loadIndexLines(self: *Db, field: []const u8, content: []const u8, keep: *bool) void {
  1798. const fi = self.idx.getPtr(field) orelse return;
  1799. // sizing: the first line's length says how many lines to expect
  1800. const nl_first = std.mem.indexOfScalar(u8, content, '\n') orelse content.len;
  1801. fi.entries.ensureUnusedCapacity(self.alloc, content.len / @max(nl_first + 1, 8) + 16) catch {};
  1802. const numeric = fi.typ == .numeric;
  1803. const c = content;
  1804. var pos: usize = 0;
  1805. while (pos < c.len) {
  1806. // one pass over the line: key up to the first comma, then two runs of digits
  1807. const start = pos;
  1808. var i = pos;
  1809. while (i < c.len and c[i] != ',' and c[i] != '\n') i += 1;
  1810. if (i >= c.len or c[i] == '\n') { // no comma: nothing to read (an empty line included)
  1811. pos = i + 1;
  1812. continue;
  1813. }
  1814. const key_end = i;
  1815. i += 1;
  1816. var off: u64 = 0;
  1817. var nd: usize = 0;
  1818. while (i < c.len and c[i] >= '0' and c[i] <= '9') : (i += 1) {
  1819. off = off *% 10 +% (c[i] - '0');
  1820. nd += 1;
  1821. }
  1822. var fast = nd >= 1 and nd <= 19 and i < c.len and c[i] == ',';
  1823. var len: u64 = 0;
  1824. if (fast) {
  1825. i += 1;
  1826. nd = 0;
  1827. while (i < c.len and c[i] >= '0' and c[i] <= '9') : (i += 1) {
  1828. len = len *% 10 +% (c[i] - '0');
  1829. nd += 1;
  1830. }
  1831. fast = nd >= 1 and nd <= 19 and (i >= c.len or c[i] == '\n');
  1832. }
  1833. if (c[start] == '"') fast = false; // a quoted key: the careful reading
  1834. if (!fast) {
  1835. // anything unusual: the careful reading of the whole line
  1836. const end = std.mem.indexOfScalarPos(u8, c, start, '\n') orelse c.len;
  1837. self.loadIndexLineSlow(fi, c[start..end], numeric, keep);
  1838. pos = end + 1;
  1839. continue;
  1840. }
  1841. pos = i + 1;
  1842. if (len == 0) continue;
  1843. const key_s = c[start..key_end];
  1844. var key: Key = undefined;
  1845. if (numeric) {
  1846. key = if (jsParseInt(key_s)) |n| Key{ .num = n } else Key{ .str = key_s };
  1847. if (key == .str) keep.* = true;
  1848. } else {
  1849. key = Key{ .str = key_s };
  1850. keep.* = true;
  1851. }
  1852. fi.entries.append(self.alloc, .{ .key = key, .off = off, .len = len }) catch return;
  1853. }
  1854. }

Only the first lines are shown.

Branches

Latest commits

  • 7557c025log: CB deploy try 2mre
  • 06a7534aMerge branch 'cb'mre
  • 2f8030d6log: CB gates greenmre
  • 498bf644log: CB gates startmre
  • f59c2847gc1: bound the five request caches (shows.hl cacheLimit)mre
  • 6ea2c6d6log: morning re-measure 11-04mre
  • 446290f0log: GC1 livemre
  • 8e6aa91dlog: GC1 deploy retrymre
  • 87ad2dc1log: GC1 deployingmre
  • 53f10fb8Merge branch 'gc1-deploy'mre
  • 7fcbf1d2log: GC1 deploy GOmre
  • 1fb6664bcompose: TRACKER_QSTATS=1 (GC1 measurement)mre
  • 6576c1cdgc1: release the people-view scan lists once the view is builtmre
  • 94f8a373gc1: back out the kept episode-id set (no measurable gain on /my/unwatched: 4.69 -> 4.61 GB per 150 loads)mre
  • a1a88bd4gc1: search skips the stale-key string while no entry is stale; /my/unwatched asks a kept id set instead of building a key string per episode rowmre
  • cd830744gc1: dbSearch: no split / map / list copy per candidate (scores from the stored text, top list touched only when the hit can enter)mre
  • 451db7cdgc1: show page and check clicks read the kept watched set instead of building one from a by-value copy of every watchmre
  • ddb4127egc1: TRACKER_QSTATS=1 logs queue and cache sizes every 10 s (measurement only)mre
  • da60547fstatus: GC1 done, backup bugmre
  • e4171021log: GC1 result, backup hard-link bugmre