gitoria
All repositories: gitoria
33.0 KB
// hl:mpackdb plugin — native shared library (mission 066)// Zig port of mpackdb v1.0.7 (MessagePack DB with binary-search indexes).//// Layout:// msgpack.zig — MessagePack codec (msgpackr-compatible, see D12)// engine.zig — DB engine (MPackDB/IndexManager semantics)// mpackdb.zig — this file: plugin ABI surface//// Exports:// hl_mpackdb_open(path, primaryKey, indexes, compact) → handle// handle ops: insert(record) / find_all() / find_pk(v) /// find_index(field, v) / find_range(field, from, to) /// delete_pk(v) / update_pk(v, record) / count() /// compact() / persist() / last_error() / pk_name()//// The `hl:mpackdb` .hl surface (MPackDB.hl, cursor.hl, server.hl) is the public// API; these ops are its transport.//// Cursors STREAM (mission 393): find_all and the index queries decode ONE record per// next() into a per-record arena (see "Streaming iterator" below for the snapshot rule);// only the eager fallback (no open data file) and find_pk/fetch-sized results are// materialized. The runtime deep-copies each record on next().const std = @import("std");const api = @import("plugin_api");pub const msgpack = @import("msgpack.zig");pub const engine = @import("engine.zig");const HlValue = api.HlValue;const HlObject = api.HlObject;const HlField = api.HlField;const HlIterator = api.HlIterator;const HlHandle = api.HlHandle;const HlString = api.HlString;// the plugins' allocator (plugin_api.zig): a DebugAllocator here mapped and unmapped every// buffer of a page or more, which the per-operation buffers made a syscall pair per callconst gpa = api.allocator;fn hlStr(comptime s: []const u8) HlString {return .{ .ptr = s.ptr, .len = s.len };}// =========================================================================// Path resolution (mission 077, 074 GAP 9)//// CONTRACT — the same one hl:fs got in mission 068: a relative db path resolves// against the MAIN SCRIPT's directory, not the process CWD. `cd /tmp && hybriel// /srv/app/main.hl` must find /srv/app's database, not create a second one in// /tmp. Absolute paths are used as-is. The runtime injects the directory through// the optional plugin hook hl_mpackdb_set_script_dir right after dlopen.// =========================================================================var script_dir: ?[]u8 = null;export fn hl_mpackdb_set_script_dir(ptr: [*]const u8, len: usize) callconv(.c) void {if (script_dir) |old| gpa.free(old);script_dir = gpa.dupe(u8, ptr[0..len]) catch null;}/// Resolve a (possibly relative) db path against the script dir. The returned/// slice is gpa-allocated; caller frees.fn resolvePath(path: []const u8) ?[]u8 {if (path.len == 0 or path[0] == '/') return gpa.dupe(u8, path) catch null;if (script_dir) |sd| return std.fmt.allocPrint(gpa, "{s}/{s}", .{ sd, path }) catch null;return gpa.dupe(u8, path) catch null;}// =========================================================================// HlValue ⇄ msgpack.Value conversion// =========================================================================/// AN EMPTY LIST is marked by its `fields` address (ticket #58) — the runtime's/// contract, stated in native/src/plugin_loader.zig beside the same constant. Zero/// fields alone read back as an empty hybrid, and `tags = []` was stored as a map.const EMPTY_LIST_FIELDS: [*]HlField = @ptrFromInt(0x4C49_5354_0000_0008);fn isEmptyList(obj: *const HlObject) bool {return obj.field_count == 0 and obj.fields == EMPTY_LIST_FIELDS;}/// Hybriel value (as HlObject tree) → msgpack value, allocated in `arena`./// An HlObject whose keys are exactly the sequence "0".."n-1" (in order)/// becomes a msgpack array; everything else becomes a map. Hybriel null and/// undefined both arrive as hl_null → msgpack nil.fn hlToMsgpack(arena: std.mem.Allocator, v: HlValue) msgpack.Value {switch (v.type) {.hl_null => return .nil,.hl_bool => return .{ .boolean = v.data.boolean },.hl_number => return .{ .number = v.data.number },.hl_string => {const s = v.data.string.ptr[0..v.data.string.len];const copy = arena.dupe(u8, s) catch return .nil;return .{ .str = copy };},.hl_object => {const obj = v.data.object;const fields = obj.fields[0..obj.field_count];// strict numeric sequence "0".."n-1" → array; an empty list carries its// mark (ticket #58), or `tags = []` was stored as an empty mapvar is_array = fields.len > 0 or isEmptyList(obj);for (fields, 0..) |f, i| {const k = f.key.ptr[0..f.key.len];var buf: [20]u8 = undefined;const expect = std.fmt.bufPrint(&buf, "{d}", .{i}) catch "";if (!std.mem.eql(u8, k, expect)) {is_array = false;break;}}if (is_array) {const items = arena.alloc(msgpack.Value, fields.len) catch return .nil;for (fields, 0..) |f, i| items[i] = hlToMsgpack(arena, f.value);return .{ .array = items };}const entries = arena.alloc(msgpack.Entry, fields.len) catch return .nil;for (fields, 0..) |f, i| {const k = arena.dupe(u8, f.key.ptr[0..f.key.len]) catch return .nil;entries[i] = .{ .key = .{ .str = k }, .value = hlToMsgpack(arena, f.value) };}return .{ .map = entries };},else => return .nil,}}/// msgpack value → HlValue tree allocated in `arena` (no deinit hooks — the/// runtime deep-copies immediately; the arena outlives the call).fn msgpackToHl(arena: std.mem.Allocator, v: msgpack.Value) HlValue {switch (v) {.nil, .undef => return api.makeNull(),.boolean => |b| return api.makeBool(b),.number => |n| return api.makeNumber(n),.str => |s| return api.makeString(s),.bin => |b| return api.makeString(b),.array => |items| {const fields = arena.alloc(HlField, items.len) catch return api.makeNull();for (items, 0..) |it, i| {var buf: [20]u8 = undefined;const k = std.fmt.bufPrint(&buf, "{d}", .{i}) catch "";const key = arena.dupe(u8, k) catch return api.makeNull();fields[i] = .{ .key = .{ .ptr = key.ptr, .len = key.len }, .value = msgpackToHl(arena, it) };}const obj = arena.create(HlObject) catch return api.makeNull();obj.* = .{ .fields = if (items.len == 0) EMPTY_LIST_FIELDS else fields.ptr, .field_count = fields.len, .deinit_fn = null };return api.makeObject(obj);},.map => |entries| {const fields = arena.alloc(HlField, entries.len) catch return api.makeNull();var n: usize = 0;for (entries) |e| {const key: []const u8 = switch (e.key) {.str => |s| s,.number => |num| blk: {var buf: [40]u8 = undefined;const k = engine.jsNumFmt(&buf, num);break :blk arena.dupe(u8, k) catch continue;},else => continue,};fields[n] = .{ .key = .{ .ptr = key.ptr, .len = key.len }, .value = msgpackToHl(arena, e.value) };n += 1;}const obj = arena.create(HlObject) catch return api.makeNull();obj.* = .{ .fields = fields.ptr, .field_count = n, .deinit_fn = null };return api.makeObject(obj);},.ext => {if (v.timestampMs()) |ms| return api.makeNumber(ms);return api.makeNull();},}}fn hlKey(v: HlValue) ?engine.Key {return switch (v.type) {.hl_number => .{ .num = v.data.number },.hl_string => .{ .str = v.data.string.ptr[0..v.data.string.len] },else => null,};}// =========================================================================// Record iterator (eagerly materialized)// =========================================================================const RecIterState = struct {// THE ITERATOR LIVES IN ITS STATE (the emit soak, 2026-10-02): the runtime frees// only its own wrapper and hands deinit the context, so a separately created// HlIterator was never freed — 40 bytes per find/range/fetch, for good.iter: HlIterator = undefined,arena_state: std.heap.ArenaAllocator,records: []msgpack.Value = &.{},idx: usize = 0,};fn recIterNext(ctx: ?*anyopaque) callconv(.c) HlValue {const state: *RecIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));if (state.idx >= state.records.len) {// THE LAST RECORD IS ALREADY COPIED OUT: the arena goes now, not when the// collector sweeps the iterator, which counts none of these bytes and so can// leave thousands of drained lookups' records waiting (hybriel#126, notes)state.records = &.{};_ = state.arena_state.reset(.free_all);return api.makeNull();}const v = state.records[state.idx];state.idx += 1;return msgpackToHl(state.arena_state.allocator(), v);}fn recIterDeinit(ctx: ?*anyopaque) callconv(.c) void {const state: *RecIterState = @ptrCast(@alignCast(ctx orelse return));state.arena_state.deinit();gpa.destroy(state);}fn makeRecordIterator(records: []msgpack.Value, arena_state: std.heap.ArenaAllocator) HlValue {const state = gpa.create(RecIterState) catch return api.makeNull();state.* = .{ .arena_state = arena_state, .records = records };state.iter = .{.context = @ptrCast(state),.next_fn = &recIterNext,.deinit_fn = &recIterDeinitOuter,};return api.makeIterator(&state.iter);}// The runtime's IterWrapper deinit calls iter.deinit_fn then frees its own// wrapper — but the HlIterator struct itself is ours to free.fn recIterDeinitOuter(ctx: ?*anyopaque) callconv(.c) void {recIterDeinit(ctx);}// =========================================================================// Streaming iterator (mission 393)// =========================================================================//// find_all (iterate(null, null)) and the index lookups / range scans hand out a cursor// that decodes ONE record per next() into a per-record arena that is reset each time,// so memory is O(1) in the table size (O(matches * 16 B) of locations for an index// query). THE RULE when the store changes while the cursor is open — it is a SNAPSHOT:// - it yields the records that existed AND were live when the query started (the// file size and the tombstone set are frozen then);// - appends / inserts / updates made later (a new version is an append) are not seen;// - a record deleted later is still yielded (the cursor reads the bytes it saw);// - a compaction (by this or another process) or a foreign rewrite does not// invalidate it: the cursor holds its own dup of the data file it started on, and// keeps reading that (unlinked) file to the end. The price: that file's disk space// lives until the cursor is exhausted or collected.// A read error mid-stream ends the cursor early and sets lastError().// mission 404: the stream cursors alive (made, not yet finished/closed) and how many were// closed by a loop that was left early. Read through db.openCursors() / db.earlyCloses().var open_cursors: usize = 0;var early_closes: usize = 0;const StreamIterState = struct {iter: HlIterator = undefined,arena_state: std.heap.ArenaAllocator,// find_all: a scanner over the whole filescanner: ?engine.Db.Scanner = null,// locations (queries): decoded one at a time from `fd`locs: []engine.Loc = &.{},pos: usize = 0,fd: i32 = -1,gen: ?*engine.DataGen = null, // the reference that keeps `fd` open (fd403: no dup per cursor)done: bool = false,fn finish(self: *StreamIterState) void {if (self.done) return;self.done = true;if (open_cursors > 0) open_cursors -= 1;if (self.scanner) |*sc| sc.deinit();self.scanner = null;if (self.gen) |g| g.release();self.gen = null;self.fd = -1;if (self.locs.len > 0) gpa.free(self.locs);self.locs = &.{};_ = self.arena_state.reset(.free_all);}};fn streamNext(ctx: ?*anyopaque) callconv(.c) HlValue {const state: *StreamIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));if (state.done) return api.makeNull();_ = state.arena_state.reset(.retain_capacity);const arena = state.arena_state.allocator();if (state.scanner) |*sc| {const maybe = sc.next(arena) catch {state.finish();return api.makeNull();};const rec = maybe orelse {state.finish();return api.makeNull();};return msgpackToHl(arena, rec.value);}while (state.pos < state.locs.len) {const loc = state.locs[state.pos];state.pos += 1;const v = engine.Db.readAtFd(state.fd, arena, loc) catch continue;return msgpackToHl(arena, v);}state.finish();return api.makeNull();}fn streamDeinit(ctx: ?*anyopaque) callconv(.c) void {const state: *StreamIterState = @ptrCast(@alignCast(ctx orelse return));state.finish();state.arena_state.deinit();gpa.destroy(state);}// A `for` loop left by break/return (mission 404): release the snapshot (data generation// ref, scanner, locations, buffers) now. Idempotent: an exhausted cursor already finished.fn streamClose(ctx: ?*anyopaque) callconv(.c) void {const state: *StreamIterState = @ptrCast(@alignCast(ctx orelse return));if (state.done) return;early_closes += 1;state.finish();}fn finishStream(state: *StreamIterState) HlValue {open_cursors += 1;state.iter = .{.context = @ptrCast(state),.next_fn = &streamNext,.deinit_fn = &streamDeinit,.close_fn = &streamClose,};return api.makeIterator(&state.iter);}fn makeStreamIterator(db: *engine.Db) HlValue {const state = gpa.create(StreamIterState) catch return api.makeNull();state.* = .{ .arena_state = std.heap.ArenaAllocator.init(gpa) };state.scanner = engine.Db.Scanner.initOpt(db, gpa, true, true);return finishStream(state);}// =========================================================================// DB handle// =========================================================================//// Process-wide table registry (ticket #110). Within one process, a table// path has ONE open engine.Db, shared by every hl_mpackdb_open() on it —// whatever module instance or realm calls it. `hl:mpackdb`'s .so is loaded// once and mapped once by the dynamic linker no matter how many realms// dlopen it (same path, same mapping), so these are already process-wide// statics; the registry just gives multiple opens of the same table a// single Db to share instead of a fresh one each time. A single realm's// event loop drives every call here — mpackdb has never been thread-safe —// so no mutex.//// The file is never compacted or rewritten while a handle on it is live:// only the FIRST open of a path in this process actually runs// engine.Db.open (and so is the only one that can compact-on-open, per// ticket #21's existing rule); every later open of the same path reuses// that live Db untouched, and its own primaryKey/indexes/compact args are// ignored — the table's schema was fixed by the first opener. Compaction// happens only when asked for explicitly (compactNow()) or when the LAST// handle on a path closes — unless the first opener passed compact=false.const SharedDb = struct {db: *engine.Db,key: []const u8, // owned; also the registry's stored key for this entryrefcount: usize,};var registry: std.StringHashMapUnmanaged(*SharedDb) = .empty;fn acquireShared(path: []const u8, opts: engine.OpenOptions) ?*SharedDb {const key = engine.tableKey(gpa, path) catch return null;if (registry.get(key)) |existing| {gpa.free(key);existing.refcount += 1;return existing;}const db = engine.Db.open(gpa, path, opts) catch |e| {std.debug.print("mpackdb plugin: open failed: {s}\n", .{@errorName(e)});gpa.free(key);return null;};const shared = gpa.create(SharedDb) catch {db.close();gpa.free(key);return null;};shared.* = .{ .db = db, .key = key, .refcount = 1 };registry.put(gpa, key, shared) catch {db.close();gpa.destroy(shared);gpa.free(key);return null;};return shared;}/// Drop this handle's reference. On the LAST reference: compact away any/// tombstones (ticket #110 — the one moment compaction may run implicitly, and/// only when the first opener did not say compact=false, ticket #192) and/// close for real.fn releaseShared(shared: *SharedDb) void {shared.refcount -= 1;if (shared.refcount > 0) return;_ = registry.remove(shared.key);// compact=false of the opener is honoured here too (ticket #192): the tracker// opens its stores with compact=false and a stop shrank shows.mpack 1.12 GB -> 424 MB.if (shared.db.compact_on_open and shared.db.deleted.items.len > 0) {shared.db.compact() catch |e| {std.debug.print("mpackdb plugin: close-compact failed: {s}\n", .{@errorName(e)});};}shared.db.close();gpa.free(shared.key);gpa.destroy(shared);}const DbState = struct {shared: *SharedDb,};export fn hl_mpackdb_open(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();const raw_path = argv[0].data.string.ptr[0..argv[0].data.string.len];// mission 077: script-relative, like every other path in Hybriel.const path = resolvePath(raw_path) orelse return api.makeNull();defer gpa.free(path);var opts = engine.OpenOptions{};if (argc > 1 and argv[1].type == .hl_string and argv[1].data.string.len > 0) {opts.primary_key = argv[1].data.string.ptr[0..argv[1].data.string.len];}var index_names: [64][]const u8 = undefined;var index_count: usize = 0;if (argc > 2 and argv[2].type == .hl_object) {const obj = argv[2].data.object;for (obj.fields[0..obj.field_count]) |f| {if (f.value.type != .hl_string) continue;if (index_count >= index_names.len) break;index_names[index_count] = f.value.data.string.ptr[0..f.value.data.string.len];index_count += 1;}}opts.indexes = index_names[0..index_count];if (argc > 3 and argv[3].type == .hl_bool) {opts.compact = argv[3].data.boolean;}const shared = acquireShared(path, opts) orelse return api.makeNull();const state = gpa.create(DbState) catch {releaseShared(shared);return api.makeNull();};state.* = .{ .shared = shared };const handle = gpa.create(HlHandle) catch {releaseShared(shared);gpa.destroy(state);return api.makeNull();};handle.* = .{.context = @ptrCast(state),.call_fn = &handleCall,.close_fn = &handleClose,.type_name = hlStr("MPackDB"),};return api.makeHandle(handle);}fn errDeinit(val: *HlValue) callconv(.c) void {if (val.type == .hl_error) {const s = val.data.string;gpa.free(@constCast(s.ptr[0..s.len]));}}/// mission 077 (074 GAP 10): querying a field that carries no index is a/// MISTAKE, not an empty result — mpackdb only answers through binary-searched/// indexes, so `[]` was indistinguishable from "no such record" and hid the/// missing declaration. The message names the field, the op and every index the/// db was actually opened with (insertion order: primary key first).fn makeNoIndexError(db: *engine.Db, op: []const u8, field: []const u8) HlValue {var list: std.ArrayList(u8) = .empty;defer list.deinit(gpa);for (db.idx.keys()) |k| {if (list.items.len > 0) list.appendSlice(gpa, ", ") catch {};list.append(gpa, '\'') catch {};list.appendSlice(gpa, k) catch {};list.append(gpa, '\'') catch {};}const declared = if (list.items.len == 0) "none" else list.items;const msg = std.fmt.allocPrint(gpa,"mpackdb.{s}: no index on field '{s}' — this db is indexed on [{s}]; every query goes through an index (declare it in `indexes` when opening, or query the primary key)",.{ op, field, declared },) catch return api.makeError("mpackdb: no index on that field");var v = api.makeError(msg);v.deinit_fn = &errDeinit;return v;}fn handleClose(ctx: ?*anyopaque) callconv(.c) void {const state: *DbState = @ptrCast(@alignCast(ctx orelse return));releaseShared(state.shared);gpa.destroy(state);}fn pkStringDeinit(val: *HlValue) callconv(.c) void {if (val.type == .hl_string) {const s = val.data.string;gpa.free(@constCast(s.ptr[0..s.len]));}}fn handleCall(ctx: ?*anyopaque, op: HlString, argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {const state: *DbState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));const db = state.shared.db;const method = op.ptr[0..op.len];if (std.mem.eql(u8, method, "insert")) {if (argc < 1 or argv[0].type != .hl_object) return api.makeNull();var arena_state = std.heap.ArenaAllocator.init(gpa);defer arena_state.deinit();const arena = arena_state.allocator();const rec = hlToMsgpack(arena, argv[0]);if (rec != .map) return api.makeNull();const res = db.insert(arena, rec, false) catch |e| {if (e != error.DuplicateKey) {std.debug.print("mpackdb plugin: insert failed: {s}\n", .{@errorName(e)});db.last_error = std.fmt.bufPrint(&db.last_error_buf, "insert failed: {s}", .{@errorName(e)}) catch "insert failed";}return api.makeNull();};switch (res) {.pk_num => |n| return api.makeNumber(n),.pk_str => |s| {const copy = gpa.dupe(u8, s) catch return api.makeNull();var out = api.makeString(copy);out.deinit_fn = &pkStringDeinit;return out;},.record => return api.makeBool(true),}}if (std.mem.eql(u8, method, "open_cursors")) return api.makeNumber(@floatFromInt(open_cursors));if (std.mem.eql(u8, method, "early_closes")) return api.makeNumber(@floatFromInt(early_closes));if (std.mem.eql(u8, method, "find_all")) {db.refresh();return makeStreamIterator(db);}if (std.mem.eql(u8, method, "find_pk")) {if (argc < 1) return api.makeNull();const key = hlKey(argv[0]) orelse return api.makeNull();var arena_state = std.heap.ArenaAllocator.init(gpa);const arena = arena_state.allocator();var locs: std.ArrayList(engine.Loc) = .empty;db.findPkLocs(arena, key, &locs) catch {arena_state.deinit();return api.makeNull();};return locsToIterator(db, arena_state, locs.items);}if (std.mem.eql(u8, method, "find_index")) {if (argc < 2 or argv[0].type != .hl_string) return api.makeNull();const field = argv[0].data.string.ptr[0..argv[0].data.string.len];const key = hlKey(argv[1]) orelse return api.makeNull();var arena_state = std.heap.ArenaAllocator.init(gpa);const arena = arena_state.allocator();var locs: std.ArrayList(engine.Loc) = .empty;db.findIndexLocs(arena, field, key, &locs) catch |e| {arena_state.deinit();if (e == error.NoSuchIndex) return makeNoIndexError(db, "find", field);return api.makeNull();};return locsToIterator(db, arena_state, locs.items);}if (std.mem.eql(u8, method, "find_range")) {if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();const field = argv[0].data.string.ptr[0..argv[0].data.string.len];const from: ?engine.Key = if (argc > 1) hlKey(argv[1]) else null;const to: ?engine.Key = if (argc > 2) hlKey(argv[2]) else null;var arena_state = std.heap.ArenaAllocator.init(gpa);const arena = arena_state.allocator();var locs: std.ArrayList(engine.Loc) = .empty;db.findRangeLocs(arena, field, from, to, &locs) catch |e| {arena_state.deinit();if (e == error.NoSuchIndex) return makeNoIndexError(db, "range", field);return api.makeNull();};return locsToIterator(db, arena_state, locs.items);}if (std.mem.eql(u8, method, "delete_pk")) {if (argc < 1) return api.makeNull();const key = hlKey(argv[0]) orelse return api.makeNull();var arena_state = std.heap.ArenaAllocator.init(gpa);defer arena_state.deinit();const arena = arena_state.allocator();var deleted: std.ArrayList(msgpack.Value) = .empty;const n = db.deletePk(arena, key, &deleted) catch |e| {std.debug.print("mpackdb plugin: delete failed: {s}\n", .{@errorName(e)});return api.makeNull();};return api.makeNumber(@floatFromInt(n));}if (std.mem.eql(u8, method, "update_pk")) {if (argc < 2 or argv[1].type != .hl_object) return api.makeNull();const key = hlKey(argv[0]) orelse return api.makeNull();var arena_state = std.heap.ArenaAllocator.init(gpa);defer arena_state.deinit();const arena = arena_state.allocator();const rec = hlToMsgpack(arena, argv[1]);if (rec != .map) return api.makeNull();// THE KEY COMES FROM THE ARGUMENT (ticket #171, as in the JS mpackdb): a record// that does not carry the primary key gets it from `key`, so update never// refuses or silently drops a record for want of it.var full = rec;if (db.pk) |p| {var carried = false;for (rec.map) |en| {if (en.key == .str and std.mem.eql(u8, en.key.str, p)) {carried = en.value != .nil and en.value != .undef;break;}}if (!carried) {var list: std.ArrayList(msgpack.Entry) = .empty;for (rec.map) |en| {if (en.key == .str and std.mem.eql(u8, en.key.str, p)) continue;list.append(arena, en) catch return api.makeNull();}const kv: msgpack.Value = switch (key) {.num => |x| .{ .number = x },.str => |x| .{ .str = x },};list.append(arena, .{ .key = .{ .str = p }, .value = kv }) catch return api.makeNull();full = .{ .map = list.items };}}const n = db.updatePk(arena, key, full) catch |e| {if (e == error.RecordLacksPrimaryKey) {db.last_error = std.fmt.bufPrint(&db.last_error_buf, "update refused: the record carries no '{s}' (update's record must carry the primary key)", .{db.pk orelse ""}) catch "update refused: the record carries no primary key";return api.makeNull();}if (e != error.DuplicateKey) {std.debug.print("mpackdb plugin: update failed: {s}\n", .{@errorName(e)});}return api.makeNull();};return api.makeNumber(@floatFromInt(n));}if (std.mem.eql(u8, method, "count")) {var arena_state = std.heap.ArenaAllocator.init(gpa);defer arena_state.deinit();const arena = arena_state.allocator();db.refresh();var scanner = engine.Db.Scanner.init(db, arena, true);defer scanner.deinit();const n = scanner.countLive() catch 0;return api.makeNumber(@floatFromInt(n));}if (std.mem.eql(u8, method, "compact")) {db.compact() catch |e| {std.debug.print("mpackdb plugin: compact failed: {s}\n", .{@errorName(e)});};return api.makeNull();}if (std.mem.eql(u8, method, "persist")) {db.persistNow() catch |e| {std.debug.print("mpackdb plugin: persist failed: {s}\n", .{@errorName(e)});};return api.makeNull();}if (std.mem.eql(u8, method, "last_error")) {return api.makeString(db.last_error);}// The primary key field name with its */@/! prefixes stripped — the .hl// wrapper needs the bare name to route find(field, …) to find_pk.if (std.mem.eql(u8, method, "pk_name")) {const p = db.pk orelse return api.makeNull();return api.makeString(p);}return api.makeNull();}/// The matches at `locs` as a cursor that decodes ONE record per next() from the/// (refcounted) data file the offsets are into (mission 393). The locations and the tombstone filter/// were fixed when the query ran, so the cursor is a snapshot: later writes, deletes or a/// compaction do not change what it yields. Without an open data file it falls back to/// decoding eagerly.fn locsToIterator(db: *engine.Db, arena_state: std.heap.ArenaAllocator, locs: []const engine.Loc) HlValue {var st = arena_state;if (db.retainDataGen()) |gen| {const state = gpa.create(StreamIterState) catch {gen.release();st.deinit();return api.makeNull();};const copy = gpa.dupe(engine.Loc, locs) catch {gen.release();gpa.destroy(state);st.deinit();return api.makeNull();};st.deinit(); // the query arena (locs) is done withstate.* = .{ .arena_state = std.heap.ArenaAllocator.init(gpa), .locs = copy, .fd = gen.fd, .gen = gen };return finishStream(state);}const arena = st.allocator();var records: std.ArrayList(msgpack.Value) = .empty;for (locs) |loc| {const rec = db.readAt(arena, loc) catch continue;records.append(arena, rec) catch break;}const slice = records.toOwnedSlice(arena) catch &.{};return makeRecordIterator(@constCast(slice), st);}fn dataIdSize(path: [:0]const u8) struct { ino: u64, size: u64 } {const linux = std.os.linux;var stx: linux.Statx = undefined;std.debug.assert(linux.statx(linux.AT.FDCWD, path, 0, linux.STATX.BASIC_STATS, &stx) == 0);return .{ .ino = stx.ino, .size = stx.size };}fn closeKeepsFile(compact: bool, name: []const u8) !struct { before: @TypeOf(dataIdSize("")), after: @TypeOf(dataIdSize("")) } {const testing = std.testing;const dir: []const u8 = if (std.c.getenv("TMPDIR")) |t| std.mem.span(t) else "/tmp";var buf: [512]u8 = undefined;const base = try std.fmt.bufPrint(&buf, "{s}/mpackdb-192-{d}-{s}", .{ dir, std.os.linux.getpid(), name });var pbuf: [520]u8 = undefined;const data = try std.fmt.bufPrintZ(&pbuf, "{s}.mpack", .{base});const suffixes = [_][]const u8{ ".mpack", ".meta.json", ".idxstate.json", ".lock", ".flock", ".id.txt" };for (suffixes) |sf| {var b: [530]u8 = undefined;const f = try std.fmt.bufPrintZ(&b, "{s}{s}", .{ base, sf });_ = std.os.linux.unlink(f);}defer for (suffixes) |sf| {var b: [530]u8 = undefined;const f = std.fmt.bufPrintZ(&b, "{s}{s}", .{ base, sf }) catch continue;_ = std.os.linux.unlink(f);};var arena_state = std.heap.ArenaAllocator.init(testing.allocator);defer arena_state.deinit();const arena = arena_state.allocator();// first process life: write rows and tombstones, close (compact=false: nothing may compact){const sh = acquireShared(base, .{ .primary_key = "*id", .compact = false }) orelse return error.OpenFailed;for (0..20) |i| {const entries = try arena.alloc(msgpack.Entry, 1);entries[0] = .{ .key = .{ .str = "n" }, .value = .{ .number = @floatFromInt(i) } };_ = try sh.db.insert(arena, .{ .map = entries }, false);}releaseShared(sh);}const sh = acquireShared(base, .{ .primary_key = "*id", .compact = compact }) orelse return error.OpenFailed;const before = dataIdSize(data);var gone: std.ArrayList(msgpack.Value) = .empty;for (1..11) |i| _ = try sh.db.deletePk(arena, .{ .num = @floatFromInt(i) }, &gone);releaseShared(sh);return .{ .before = before, .after = dataIdSize(data) };}test "#192: closing the last handle of a compact=false table leaves the data file alone" {const r = try closeKeepsFile(false, "off");try std.testing.expectEqual(r.before.ino, r.after.ino);try std.testing.expectEqual(r.before.size, r.after.size);}test "#192: closing the last handle of a compact=true table still compacts" {const r = try closeKeepsFile(true, "on");try std.testing.expect(r.after.size < r.before.size);}test {_ = msgpack;_ = engine;}
Branches
- f1-broken-json
- f2-api-bugs
- gp-gate-ports
- heap-revert
- hl25-records
- ident-chooser-selector
- mainmain branch
- p51-public-pr-reads
- records-1112
- s25-no-session-on-login-error
- v59
- w52-person-approval
- w52b-approval-followup
- w52c-header-phone
- w53-pulls-speed-pr
- w54-repo-rename-pr
- w55-rename-org
- w56-owner-members
- w62-pr-close
- w63-force-push
- w64-org-slash
Latest commits
- 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
- 48a6154bre-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre