jukebox
All repositories: gitoria
18.1 KB
# `hl:mpackdb` — the MessagePack file databaseA document store in plain files. Server realm. The class surface and itsgenerated API docs live in `MPackDB.hl` and `cursor.hl`(`projects/homepage/generated/pages/mpackdb.md`).```hybrielimport { MPackDB } from 'hl:mpackdb'db = new MPackDB(file = 'users.db', primaryKey = '*id', indexes = ['!email', 'age'])id = db.put({ name = "Alice"; email = "[email protected]"; age = 30; }) \\ 1```## Primary keys| declaration | key | generated by `put()` ||---|---|---|| `*name` | a number | the table's counter: **1, 2, 3, …** || `@name` | a string | a random 12-character id || `name` | a string | nothing — the record must carry it |**A fresh `*id` table starts at 1** (ticket #4, the creator's ruling "start at1"). The counter is stored as `nextId` in `<base>.meta.json`, and an existingtable keeps counting from its stored value. A table written before this ruletherefore goes on from wherever it was, and its record 0 remains record 0.A record put with an explicit key takes that key if it is free, 0 included.## One open table per process (ticket #110)Within one process, a table path has **one** open table, shared by every`open()` — another module instance, another realm, it doesn't matter, theyall get the same handle. The file is never compacted or rewritten while ahandle on it is live; compaction happens only when asked for explicitly(`compactNow()` / `#handle.compact()`) or when the **last** handle on thatpath closes. A second `open()` of an already-open table ignores its own`primaryKey`/`indexes`/`compact` arguments — the schema was fixed by whoeveropened it first.This matters because compaction rewrites `<base>.mpack` and shifts everyrecord after the first tombstone to a new offset. Before this rule, a second`open()` from anywhere in the process ran its own compact-on-open (ticket#21) against the same file, and the first handle's already-looked-up offsetswent stale under it — reads through the first handle then missed ormisread records until something compacted again. Related: ticket #21("opening a table rewrote its files").## Compaction never loses data (ticket #176)- **Across processes**, too: every open handle holds a shared `flock` on`<base>.flock`. A compaction (on open, `compactNow()`, or the last close)needs it exclusive and is **skipped** — not an error; `lastError()` saysso — while another process has the store open.- A handle notices when its data file was rewritten anyway (anotherprocess's compaction, the JS mpackdb): the inode, a shrink, or a newercompaction generation in the meta. It re-reads the meta and re-indexes thenew file before it answers a read. Before, it read its old offsets in thenew file — the middle of other records.- Compaction checks every frame before it renames anything. A frame of size<= 4, a size past the end of the file that is not a torn tail, a liveframe that does not decode to exactly one map, or a deleted offset that isnot a frame start makes it **refuse**: the error names the offset, the datafile and meta stay as they were. A refused compaction on open does not failthe open. The one thing dropped is a torn tail (an append cut short by acrash), and it is reported.- The new data file is fsynced, renamed, its directory fsynced, and onlythen the meta written. The meta's `dataFile` names the data file it waswritten for (inode, size, compaction generation, a checksum of its deletedlist); a meta of a replaced file has its tombstones dropped, not appliedto the new file. `idxstate.json`'s `dataIno` does the same for the indexfiles.## `find(null, null)` over a big table warns (mission 390)`find()` collects every match into one array, so `find(null, null)` holds the WHOLE table at once(measured: about 27 times the file's size in RAM; the tracker's 621 K persons took 5.6 GB, and theobject table and heap grow to match). When such a call builds an array of more than 100 000records, the plugin prints ONE line per table (per open handle) on stderr:mpackdb: <file>: find(null, null) built an array of <n> records; use iterate()The result and the behaviour are unchanged. Stream instead: `for (rec of db.iterate(null, null)) { ... }`(or `db.cursor(null, null)`); a row is freed when the loop is done with it.## Cursors stream, and they are snapshots (mission 393)`iterate(null, null)` (the full scan), `iterate(field, value)` and the indexrange behind `range()` answer an iterator that decodes **one record per`next()`** into a per-record arena that is reset each time. `iterate(null,null)` holds no record at all (memory is O(1) in the table size: the tracker's1.4 M-row episodes walk in the memory of one row); an index query keeps onlythe matching locations (16 bytes each) and reads each record when asked.`find()` / `range()` still drain the cursor into one array, with the sameresults as before.**The rule when the store changes while a cursor is open: the cursor is asnapshot of the moment the query ran.**- It yields the records that existed and were live then: the file size and theset of tombstones are frozen at the start (a record deleted before is neverseen).- A record inserted, or the new version an `update` appends, after the start isnot seen; the old version, if it was live at the start, still is.- A record deleted after the start is still yielded (the cursor reads thebytes it saw).- A compaction, by this process or another, or a foreign rewrite of the filedoes **not** invalidate it and raises no error: the cursor holds areference to the data file it started on (the handle's own open file, sharedand reference-counted: a cursor costs **no file descriptor of its own**, sothousands of abandoned cursors cannot exhaust `ulimit -n`) and reads that (bythen unlinked) file to the end. After a compaction that file stays open, andits disk space lives, until the last cursor on it is exhausted or collected.- Another process's writes completed before this query starts are visible.Writes completed after the cursor starts do not change its snapshot.- A read error mid-stream ends the cursor early.The tombstone set is built once per handle and kept in step with every delete;it is rebuilt after a compaction or when a meta another writer changed isadopted. Lookups, ranges and scans no longer rebuild it on every call, so thecost of a slice no longer grows with the number of tombstones.`count()` counts frame headers without decoding a record.## Leaving a loop early closes the cursor (mission 404)`break` or `return` out of `for (row of db.iterate(...))` (or `find`-style rawiterators) releases the cursor's snapshot **at that moment** — its reference tothe data generation, its scanner, its locations and buffers — instead of whenthe collector finalizes it. Exhausting the cursor does the same; closing twiceis harmless. After an early close the iterator answers `null` from `next()`.`db.openCursors()` counts the cursors of the process that are neither exhaustednor closed and `db.earlyCloses()` counts those closed by an early exit; both aremeant for tests. `for (r of db.cursor(...))` iterates the `Cursor` class, whichdeclares `close()` (mission 418): a loop left early calls it once, and it releasesthe same snapshot (`cursor.close()` by hand works too, twice is harmless).## The index file line format (mission 486)`<base>.<field>.txt` holds one line per entry, sorted: `key,offset,length` and a newline.Offset and length are whole numbers: the place of the record in `<base>.mpack` and its size.- Format 3 writes numbers as JavaScript String(number), including fractional values,NaN and infinities. Strings are always JSON quoted, with literal UTF-8.- Readers accept format 2 and 3. Quoted keys stay strings; raw numeric literals becomenumbers. Numeric indexes convert numeric caller strings using Number(), preserving fractions.Number and string keys otherwise compare separately; NaN sorts after other numbers.- Old stores rebuild once from live data on upgrade to idxFmt 3. Unknown idxstate fieldssurvive updates. Formats above 3 are refused without rewriting.- Phase A (this branch) commits write_format = 2: read formats 2 and 3, write format 2and idxFmt 2, preserving foreign state fields. Format 2 uses raw string text exceptwhen quoting is needed for line safety. Existing format 3 stores load without rebuilding.Rebuild decisions follow the writer constant, so a current format 2 store does not loop.- Phase B is a later separate one-line change by the conductor to write_format = 3.Run bash plugins/mpackdb/tools/test-index-formats.sh to check both settings.- The copied testdata/format3 corpus comes from mpackdb 1.4.0.## Compatibility with the JS mpackdbThe on-disk format is the JS mpackdb 1.4.0 format: `<base>.mpack`,`<base>.meta.json`, one `<base>.<field>.txt` per index, `<base>.idxstate.json`and the `<base>.lock` protocol (`<base>.flock` and the #176 fields above arethis engine's additions; the JS mpackdb ignores them). Either side reads and changes the other'sfiles. The first id is not part of the format; `nextId` is. Therefore:- a table the JS mpackdb created carries `nextId` and keeps its sequence here,even when that sequence started at 0;- a table Hybriel created carries `nextId` too, and the JS mpackdb continues it;- the one divergence is a table with **no** `.meta.json` yet: Hybriel's firstid is 1, the JS mpackdb's is 0.The other documented divergences are listed at the top of `engine.zig`.## Checking a store after the open race (mission 559/560)Run on a quiescent copy of the store directory:```shnode plugins/mpackdb/tools/check-integrity.mjs /path/to/store-copynode plugins/mpackdb/tools/check-integrity.mjs /path/to/store-copy --json```The checker only reads files. It reports multiple live versions of a primary key,all offsets, the newest offset and short field differences. It also checks unique(`!`) fields declared in the metadata schema against live data, even if index filesare stale. Each table has record, live, tombstoned and duplicate counts; duplicatescounts extra live versions beyond the first. Exit 1 means findings or unreadableinput; exit 2 means incorrect usage. Missing primary-key schema is reported as anincomplete check. Tombstones come from the copied metadata; malformed frames orinvalid tombstone offsets are errors. No database engine is opened.A lost tombstone for a plain delete leaves no trace: that row simply looks live.Only update-resurrections with multiple live versions are detectable for sure.Newest means greatest file offset, not a recommendation to keep that version.Repair is NOT part of this tool: the owner decides per record.## Two processes on one storeA fresh `fetch`, `find`, index lookup or new cursor sees another process'scompleted writes. An already started cursor keeps its snapshot. Reading a rowand then calling `update` can overwrite another writer's change.`compareAndSet(key, replacement, expect)` holds `<base>.lock` across refresh,comparison, unique checks and replacement. Each named expectation field usesHybriel `==`: numbers, booleans and strings compare by value, and missing fieldsand undefined equal null. A stored Date (MessagePack timestamp extension -1)matches the exact same milliseconds, including the number returned by `fetch`;a different instant does not match. Other extension types do not match.Copied hybrids have different identities (nested hybrids therefore do not match).Ordered expectation entries are ignored; an empty expectation checks existence.It returns true on replacement, false for an absent key or mismatch, and nullon failure, like `update` (`lastError()` gives duplicate-key details). Thereplacement is complete, not merged; a missing primary key comes from `key`.Unique conflicts are checked before deleting the old row. `update` is unchanged.For a counter initialized with `db.put({ id = 'counter'; seq = 0 })`:```hybriellet done = falsewhile (!done) {old = db.fetch('counter').seqresult = db.compareAndSet('counter', { seq = old + 1 }, { seq = old })if (result == null) { hlError(db.lastError()) }done = result}```This is native-only (`MPackDB.hl` / `server.hl`); the JavaScript target has nompackdb implementation in `js/src/runtime`. The separate JS mpackdb packagehas no new API here. All writers must cooperate with the `.lock` protocol;this adds no crash transaction, multi-table transaction or ABA protection.## Index coverage across a rollback (mission 588)`idxstate.json` keeps the compatible table-wide `coveredBytes`, `idxFmt`,`dataIno` and `dataFp` fields and adds `fields`, an object mapping each persistedindex's clean field name to the data byte count it covers. Only indexes thiswriter actually maintains are listed. Every requested index must have coverageequal to the table-wide count before any persisted indexes are accepted; otherwisethe engine rebuilds all requested indexes under the table lock. Valid indexesstill load and catch up an appended tail normally. File identity checks remain.An older Zig writer replaces idxstate without `fields`; a JS writer may retainunknown fields while advancing `coveredBytes`. Missing or unequal field coverageforces a rebuild in either case. A current writer opened with fewer indexes listsonly those indexes, so returning to a larger schema also rebuilds. Legacy storesrebuild once on their first open with this engine. Rebuilding all requestedindexes is deliberate: the scanner already handles all fields together, avoidingseparate coverage and tail offsets in memory. Index text and MessagePack formatsare unchanged, and older readers can ignore `fields`. Alternating schemas maycause repeated rebuilds; correctness takes precedence over that open-time cost.The JavaScript target has no mpackdb implementation in `js/src/runtime`; theseparate JS mpackdb package remains an external reader/writer of this format.## Restarting after a crash (mission 589)`<base>.lock` contains the mutation holder's positive decimal PID. A fresh lockis reclaimed immediately if `kill(pid, 0)` reports ESRCH, or if it names thisprocess but this handle does not hold it. EPERM counts as a live process. Thisassumes writers share one machine and PID namespace. A remote/foreign namespacePID cannot be identified from this legacy file format; do not use immediate PIDrecovery across those boundaries. A live reused PID from another process waitsas before. Empty, malformed and unreadable PID files retain the 30-second agefallback and the approximately 12-second acquisition timeout.Zig writers hold an advisory exclusive flock on the mutation lock inode untilrelease. Reclaimers take that same flock and verify the inode still occupies thepath before unlinking and retrying exclusive creation. Two restarters thereforecannot remove a replacement lock or both enter the protected operation. Anactively held Zig flock is never stolen, including after the age threshold.The file format remains compatible with external JS writers; those writers donot participate in the added advisory flock, so their legacy age-based takeoverstill requires operations to finish inside the stale timeout.## Read selected fields (mission 600)`fetch(key, fields = null)`, `iterate(field, value, fields = null)`,`find(field, value, fields = null)`, `cursor(field, value, fields = null)` and`range(field, low, high, fields = null)` accept an ordered list of top-levelfield names, for example `db.iterate(null, null, ['id', 'slug', 'tmdbId'])`.Omitting fields or passing null reads the whole record. An empty list yieldsone empty plain hybrid per matching record. Unknown names are absent; nullvalues remain present. Duplicate names appear once, in the requested order.Names are literal (a dot does not select a nested path). A selected nestedvalue is decoded in full. A non-list or a non-string entry raises an Error.Projection happens inside the MessagePack decoder: other keys and values arewalked and validated without allocating their decoded trees or Hybriel objects.The record bytes still have to be read. Matching still uses the existingprimary-key/index/range queries; projection does not add unindexed filtering.Cursor snapshots, early close and missing-index errors are unchanged. Thecursor owns a copy of its field list. Results are plain hybrids, not models.This API is native-only; the JavaScript target has no mpackdb implementation.## Change events (miserit-anthar #92)`on db.change(kind, op, key, doc, prev)` runs synchronously after a successfulmutation releases the store lock, before the method returns. There is one eventper affected record. `kind` is `insert`, `update` or `delete`; `op` is `insert`(for `put`), `update`, `upsert`, `delete` or `compareAndSet`. `key` is the record'sprimary key (null without a primary key). `doc` is the complete stored record,including a generated primary key, or null for deletion. `prev` is null for aninsert and the complete previous record for every replacement or deletion.Before-images are captured under the mutation lock, using the rows alreadyread by deletion, rather than a separate unlocked fetch. Handlers may reenterthe database; the event payload remains the snapshot of this mutation.`upsert(record)` inserts if its primary key is absent, otherwise replaces thecomplete record. It returns the primary key, true without a primary key, ornull on failure (`lastError()` gives the reason). Missing numeric/UUID keys aregenerated just as in `put`. The existence check and write share one store lock.It uses the CAS unique-field validation before replacing an existing row.No event fires for a rejected write, absent delete/update, false CAS, open,compaction, repair or index rebuild. A handler fault does not roll back thewrite. It follows the normal language fault rule: `on Error` sees the locatedfault and the current statement/delivery is abandoned, losing the method answer.```hybrielon db.change(String kind, String op, Number | String key, Hybrid doc, Hybrid prev) {echo(JSON.stringify({ =kind; =op; =key; =doc; =prev }))}db.upsert({ id = 'a'; v = 1 })```Run `node tests/mpackdb/change-event-sequence.mjs` for the six-line equivalencefixture and the run/compiled mutation and fault checks. The on-disk format andJS mpackdb 1.4.0 compatibility apply; the event API matches JS 1.2.0.
Branches
Latest commits
- 10f8a8c8Merge branch 'code-order' into mainJukebox
- 204fc828Merge branch 'day72' into mainJukebox
- 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
- 33072bb5|||PR Record day72 gates and Chrome proofmre
- 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
- 6422a020Sync media-player at 51c3818mre
- b582ba1cVendor complete Hybriel day72 plugin setmre
- 02dccbc9Merge branch 'records-1119' into mainJukebox
- a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
- fc7db075Merge branch 'reconnect-retry' into mainJukebox
- ac6f4c6fL2: plain declaration for a in pickedNextmre
- 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
- 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
- 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
- 1f0cd77bMerge branch 'records-day41' into mainJukebox
- 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
- 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
- 04f5d9d5Merge branch 'day41' into mainJukebox
- 8ed6da45|||PR README: media-player pin df9e7dfmre
- d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre