gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit109cfc5c109cfc5ctests/ticketskit: keep the rotated session cookie of the tickets login (tickets ST2 session rotation)mre109cfc5c/plugins/mpackdb/engine.zig

148.5 KB

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

Only the first lines are shown.

Branches

Latest commits

  • 109cfc5ctests/ticketskit: keep the rotated session cookie of the tickets login (tickets ST2 session rotation)mre
  • 7eb6be27sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • b3911918reports/MG-mobile.md: 404 fixed, rebased gatesMG
  • 9da65b42tests/browser.mjs: 404 checks (host, no hydration wait)MG
  • 00517fafgitoria: shell 404 page for unknown paths (catch-all route, status 404, JSON 404 under /api), 390 gate checksMG
  • d9e977f0reports/MG-mobile.md, LOGMG
  • 2f2725actests/browser.mjs: commit-row check (one row, centred date)MG
  • 4df1ea01tests/browser.mjs: MG phone checks (list first, no dead strip, one branch heading, tab grid, commit rows, PR title row, ticket columns, wrapping commands)MG
  • c52424e9gitoria mobile: repo list before the forms, 3x2 tab grid, no duplicate branch heading, ordered commit rows, aligned ticket rows, pull title on its own row, wrapping clone commands, no dead strip under formsMG
  • 3a95252dG3: cache parsed README blocks by sha256 of the text (bounded LRU), reportmre
  • 570138cddeploy: security gate (tests/security.mjs)mre
  • da6b20fcgitoria SG: security audit fixes (uploadMax 0, Secure cookie on https, session rotation at login, nosniff on function routes, no identity in page data) + tests/security.mjs gate + reportmre
  • f98c981fgitoria B1: report wordingmre
  • c6364cedgitoria B1: compact Markdown blocks (one kind flag per block/span, empty and false fields omitted); same rendered HTML, page values -67%mre
  • cd99d2feWIP gitoria#22: always render the repo level's slot (missing-repo boot hang), pages render nothing without a repo; hydration diagnosis in reports/G2-hydrate.mdmre
  • e5404b9breport: commit idsmre
  • 63cfa21ereports/G2-repotabs.mdmre
  • 9b0516fdgitoria#22: mark the tab underline functional (check-theme), chain E2E: serve/measure split, bring the lisbeth tab to frontmre
  • 19bc1df8gitoria#22: all repo pages under ONE layout level (components/repo.hl, hl:web D-CHAIN): a tab click replaces only the page in the slot; head and tab nav stay the same DOM nodesmre
  • 40658417tests/browser.mjs: wait for the page to be live (hydrated) before clicking Merge — a click on the server-rendered button before the client mounted was lost (flaky 'Clashing change' under load)mre