gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitd25bd14ad25bd14amission 044: sliced merge prepare + sliced collections prepare; jobs-dump old/new check + bulk fixturemred25bd14a/plugins/mpackdb/engine.zig

114.1 KB

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

Only the first lines are shown.

Branches

Latest commits

  • d25bd14amission 044: sliced merge prepare + sliced collections prepare; jobs-dump old/new check + bulk fixturemre
  • 633ee210mission 044: sliced table scans (slices.hl, pk-range slices) for the adult/kind/status/art/credits/details-repair queuesmre
  • 6648ba44mission 042: real-browser E2E on ce6f2e0a re-vendor 69/0 at 390 + 1280mre
  • 3ed3a0efmission 042: gates old/new equal (browser #41 route-table regex accepts unescaped hl:web output), real-data TTFB, E2E blocked by lisbeth lockmre
  • d5b61e90LOG 042mre
  • 4acdbaccmission 042: memory comparison old vs ce6f2e0a (stopped: warm VmHWM higher), reportmre
  • d0f620d6mission 042: re-vendor Hybriel ce6f2e0a (plugins incl. mpackdb; bin runtime built from the same archive, git-ignored), compact=false keptmre
  • 5bd14e12mission 040: theme 76f99f6 gates + E2E green; 44 px fixes (skeleton row, type-word, genre-link/pill); README, reportmre
  • 77cfa45cmission 040: partial report (theme/modal/pagination re-copied, tilelist onPage, 44 px taps; gates new + E2E pending)mre
  • 4b14822fe2e-theme: menu marker by colourmre
  • 09780f4emission 040 WIP: theme, modal, pagination, tokens re-copied from layouts 76f99f6; tilelist uses onPage; tap sizes 44 px for tracker's own small buttons; tests/e2e-theme.mjsmre
  • fb80bb8chotfix: open the 5 show stores without compaction (compact = false) — compact-on-open left another handle on stale offsets, every read gave a bare Number (hybriel mpackdb refresh after a shrink); live down 2026-10-20 05:11mre
  • e00d3bf7paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • a8c7f234tracker#36 (mission 039): tools/tmdb-check.hl survives a dropped connection (on Error, asked again, failed lines) and resumes with --from N; tests/tmdbcheck.mjs 6/6 against a fake TMDBmre
  • 9c230516mission brief w39mre
  • 3609121dmission 038 docs + report (quota stop): README/kinds.md for #43 #42 #36, STATUS, LOG; HEAD browser gate 374/8 in the in-app daily run block (hour-boundary suspected, rerun pending), other gates green; #36 real run needs TMDB_READ_TOKENmre
  • a5d06e79tracker#36 (mission 038): tools/tmdb-check.hl + lib/tmdbcheck.hl — every live migrated title's migrated title + year against its TMDB entry (one GET /movie|tv/<id>?append_to_response=alternative_titles, 260 ms apart, passing failures asked once more): ok / ambiguous (one of title, year disagrees) / clear (both, or 404); read-only; token only from TMDB_READ_TOKEN; --stored = a title-only preview from the TMDB names already stored (no request). Tested against a fake TMDB (.scratch/w38/t36): 7 titles, 3 ok, 2 ambiguous, 2 clear, data unchangedmre
  • 982554f3tracker#42 (mission 038): series pages — an unknown slug no longer scans every title (lib/shows.hl showBySlug: the slug map only; new titles are noted by refreshTitleCaches, which both title puts already reach): 10.7–15.7 s → 0.013 s on the real copy (the one-request-at-a-time server was blocked meanwhile); cast/crew rows take name + slug from a person-link cache (personLinkOf) instead of whole person records (SNL: 303 cast with 4,761 credits, ~49k allocations per render) — allocations per series page −5…−40 %; HTML of 20 pages identical to beforemre
  • 4586b6e3docker-compose: init: true (hybriel#156)mre
  • 085c2e5ftracker#43 (mission 038): TVmaze's type makes Variety / Talk Show / Game Show / Reality / News / Panel Show / Award Show / Sports titles Shows (TMDB calls Saturday Night Live UK Scripted) — the #43 part of parked w37-wip a79c8c1 only (no re-vendor, no cache volume): tvmazeType stored by the sync and the TVmaze status backfill (asks every series with a TVmaze id once), kindOfTitle/kindWithTvmaze, tools/tvmaze-types.hl, gate fixture Variety Gate Series; start waits 150 smre