gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit5d7cc7005d7cc700Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre5d7cc700/plugins/mpackdb/README.md

12.3 KB

  1. # `hl:mpackdb` — the MessagePack file database
  2. A document store in plain files. Server realm. The class surface and its
  3. generated API docs live in `MPackDB.hl` and `cursor.hl`
  4. (`projects/homepage/generated/pages/mpackdb.md`).
  5. ```hybriel
  6. import { MPackDB } from 'hl:mpackdb'
  7. db = new MPackDB(file = 'users.db', primaryKey = '*id', indexes = ['!email', 'age'])
  8. id = db.put({ name = "Alice"; email = "[email protected]"; age = 30; }) \\ 1
  9. ```
  10. ## Primary keys
  11. | declaration | key | generated by `put()` |
  12. |---|---|---|
  13. | `*name` | a number | the table's counter: **1, 2, 3, …** |
  14. | `@name` | a string | a random 12-character id |
  15. | `name` | a string | nothing — the record must carry it |
  16. **A fresh `*id` table starts at 1** (ticket #4, the creator's ruling "start at
  17. 1"). The counter is stored as `nextId` in `<base>.meta.json`, and an existing
  18. table keeps counting from its stored value. A table written before this rule
  19. therefore goes on from wherever it was, and its record 0 remains record 0.
  20. A record put with an explicit key takes that key if it is free, 0 included.
  21. ## One open table per process (ticket #110)
  22. Within one process, a table path has **one** open table, shared by every
  23. `open()` — another module instance, another realm, it doesn't matter, they
  24. all get the same handle. The file is never compacted or rewritten while a
  25. handle on it is live; compaction happens only when asked for explicitly
  26. (`compactNow()` / `#handle.compact()`) or when the **last** handle on that
  27. path closes. A second `open()` of an already-open table ignores its own
  28. `primaryKey`/`indexes`/`compact` arguments — the schema was fixed by whoever
  29. opened it first.
  30. This matters because compaction rewrites `<base>.mpack` and shifts every
  31. record after the first tombstone to a new offset. Before this rule, a second
  32. `open()` from anywhere in the process ran its own compact-on-open (ticket
  33. #21) against the same file, and the first handle's already-looked-up offsets
  34. went stale under it — reads through the first handle then missed or
  35. misread records until something compacted again. Related: ticket #21
  36. ("opening a table rewrote its files").
  37. ## Compaction never loses data (ticket #176)
  38. - **Across processes**, too: every open handle holds a shared `flock` on
  39. `<base>.flock`. A compaction (on open, `compactNow()`, or the last close)
  40. needs it exclusive and is **skipped** — not an error; `lastError()` says
  41. so — while another process has the store open.
  42. - A handle notices when its data file was rewritten anyway (another
  43. process's compaction, the JS mpackdb): the inode, a shrink, or a newer
  44. compaction generation in the meta. It re-reads the meta and re-indexes the
  45. new file before it answers a read. Before, it read its old offsets in the
  46. new file — the middle of other records.
  47. - Compaction checks every frame before it renames anything. A frame of size
  48. <= 4, a size past the end of the file that is not a torn tail, a live
  49. frame that does not decode to exactly one map, or a deleted offset that is
  50. not a frame start makes it **refuse**: the error names the offset, the data
  51. file and meta stay as they were. A refused compaction on open does not fail
  52. the open. The one thing dropped is a torn tail (an append cut short by a
  53. crash), and it is reported.
  54. - The new data file is fsynced, renamed, its directory fsynced, and only
  55. then the meta written. The meta's `dataFile` names the data file it was
  56. written for (inode, size, compaction generation, a checksum of its deleted
  57. list); a meta of a replaced file has its tombstones dropped, not applied
  58. to the new file. `idxstate.json`'s `dataIno` does the same for the index
  59. files.
  60. ## `find(null, null)` over a big table warns (mission 390)
  61. `find()` collects every match into one array, so `find(null, null)` holds the WHOLE table at once
  62. (measured: about 27 times the file's size in RAM; the tracker's 621 K persons took 5.6 GB, and the
  63. object table and heap grow to match). When such a call builds an array of more than 100 000
  64. records, the plugin prints ONE line per table (per open handle) on stderr:
  65. mpackdb: <file>: find(null, null) built an array of <n> records; use iterate()
  66. The result and the behaviour are unchanged. Stream instead: `for (rec of db.iterate(null, null)) { ... }`
  67. (or `db.cursor(null, null)`); a row is freed when the loop is done with it.
  68. ## Cursors stream, and they are snapshots (mission 393)
  69. `iterate(null, null)` (the full scan), `iterate(field, value)` and the index
  70. range behind `range()` answer an iterator that decodes **one record per
  71. `next()`** into a per-record arena that is reset each time. `iterate(null,
  72. null)` holds no record at all (memory is O(1) in the table size: the tracker's
  73. 1.4 M-row episodes walk in the memory of one row); an index query keeps only
  74. the matching locations (16 bytes each) and reads each record when asked.
  75. `find()` / `range()` still drain the cursor into one array, with the same
  76. results as before.
  77. **The rule when the store changes while a cursor is open: the cursor is a
  78. snapshot of the moment the query ran.**
  79. - It yields the records that existed and were live then: the file size and the
  80. set of tombstones are frozen at the start (a record deleted before is never
  81. seen).
  82. - A record inserted, or the new version an `update` appends, after the start is
  83. not seen; the old version, if it was live at the start, still is.
  84. - A record deleted after the start is still yielded (the cursor reads the
  85. bytes it saw).
  86. - A compaction, by this process or another, or a foreign rewrite of the file
  87. does **not** invalidate it and raises no error: the cursor holds a
  88. reference to the data file it started on (the handle's own open file, shared
  89. and reference-counted: a cursor costs **no file descriptor of its own**, so
  90. thousands of abandoned cursors cannot exhaust `ulimit -n`) and reads that (by
  91. then unlinked) file to the end. After a compaction that file stays open, and
  92. its disk space lives, until the last cursor on it is exhausted or collected.
  93. - Another process's writes completed before this query starts are visible.
  94. Writes completed after the cursor starts do not change its snapshot.
  95. - A read error mid-stream ends the cursor early.
  96. The tombstone set is built once per handle and kept in step with every delete;
  97. it is rebuilt after a compaction or when a meta another writer changed is
  98. adopted. Lookups, ranges and scans no longer rebuild it on every call, so the
  99. cost of a slice no longer grows with the number of tombstones.
  100. `count()` counts frame headers without decoding a record.
  101. ## Leaving a loop early closes the cursor (mission 404)
  102. `break` or `return` out of `for (row of db.iterate(...))` (or `find`-style raw
  103. iterators) releases the cursor's snapshot **at that moment** — its reference to
  104. the data generation, its scanner, its locations and buffers — instead of when
  105. the collector finalizes it. Exhausting the cursor does the same; closing twice
  106. is harmless. After an early close the iterator answers `null` from `next()`.
  107. `db.openCursors()` counts the cursors of the process that are neither exhausted
  108. nor closed and `db.earlyCloses()` counts those closed by an early exit; both are
  109. meant for tests. `for (r of db.cursor(...))` iterates the `Cursor` class, which
  110. declares `close()` (mission 418): a loop left early calls it once, and it releases
  111. the same snapshot (`cursor.close()` by hand works too, twice is harmless).
  112. ## The index file line format (mission 486)
  113. `<base>.<field>.txt` holds one line per entry, sorted: `key,offset,length` and a newline.
  114. Offset and length are whole numbers: the place of the record in `<base>.mpack` and its size.
  115. - Writing: the key is written as it is, raw, so a key with commas (`a, b`) stays a plain line
  116. and a file without special keys is byte for byte what it always was. Only a key that holds a
  117. newline, a carriage return, or starts with a double quote is written as a JSON string
  118. (what `JSON.stringify` makes of it), for example `"x\ny",30,31`.
  119. - Reading: a line that starts with a double quote is a JSON string followed by `,offset,length`.
  120. Any other line is split from the RIGHT: the last two comma separated parts are offset and
  121. length, everything before them is the key. So files written before this rule with a comma in a
  122. key read correctly. On a numeric index (`*field`) a raw key is read as a number when it starts
  123. like one; a quoted key always stays a string.
  124. - Until this rule the reader cut a line at its first comma and dropped the entry; the next
  125. close then wrote the index file without it, so records went missing from sorted lists after
  126. a restart. The records in `<base>.mpack` were never touched. `idxstate.json` therefore carries
  127. `"idxFmt":2` now: an index whose idxstate lacks it is rebuilt from the data once when it is
  128. opened, which brings every dropped entry back.
  129. - `tools/check-index-keys.mjs <directory>` (node, read only) lists the records whose indexed
  130. text holds a comma, newline, carriage return or leading quote and says which of them are
  131. missing from their index file.
  132. ## Compatibility with the JS mpackdb
  133. The on-disk format is the JS mpackdb 1.0.7 format: `<base>.mpack`,
  134. `<base>.meta.json`, one `<base>.<field>.txt` per index, `<base>.idxstate.json`
  135. and the `<base>.lock` protocol (`<base>.flock` and the #176 fields above are
  136. this engine's additions; the JS mpackdb ignores them). Either side reads and changes the other's
  137. files. The first id is not part of the format; `nextId` is. Therefore:
  138. - a table the JS mpackdb created carries `nextId` and keeps its sequence here,
  139. even when that sequence started at 0;
  140. - a table Hybriel created carries `nextId` too, and the JS mpackdb continues it;
  141. - the one divergence is a table with **no** `.meta.json` yet: Hybriel's first
  142. id is 1, the JS mpackdb's is 0.
  143. The other documented divergences are listed at the top of `engine.zig`.
  144. ## Checking a store after the open race (mission 559/560)
  145. Run on a quiescent copy of the store directory:
  146. ```sh
  147. node plugins/mpackdb/tools/check-integrity.mjs /path/to/store-copy
  148. node plugins/mpackdb/tools/check-integrity.mjs /path/to/store-copy --json
  149. ```
  150. The checker only reads files. It reports multiple live versions of a primary key,
  151. all offsets, the newest offset and short field differences. It also checks unique
  152. (`!`) fields declared in the metadata schema against live data, even if index files
  153. are stale. Each table has record, live, tombstoned and duplicate counts; duplicates
  154. counts extra live versions beyond the first. Exit 1 means findings or unreadable
  155. input; exit 2 means incorrect usage. Missing primary-key schema is reported as an
  156. incomplete check. Tombstones come from the copied metadata; malformed frames or
  157. invalid tombstone offsets are errors. No database engine is opened.
  158. A lost tombstone for a plain delete leaves no trace: that row simply looks live.
  159. Only update-resurrections with multiple live versions are detectable for sure.
  160. Newest means greatest file offset, not a recommendation to keep that version.
  161. Repair is NOT part of this tool: the owner decides per record.
  162. ## Two processes on one store
  163. A fresh `fetch`, `find`, index lookup or new cursor sees another process's
  164. completed writes. An already started cursor keeps its snapshot. Reading a row
  165. and then calling `update` can overwrite another writer's change.
  166. `compareAndSet(key, replacement, expect)` holds `<base>.lock` across refresh,
  167. comparison, unique checks and replacement. Each named expectation field uses
  168. Hybriel `==`: scalars compare by value, missing fields equal null, and copied
  169. hybrids have different identities (nested hybrids therefore do not match).
  170. Ordered expectation entries are ignored; an empty expectation checks existence.
  171. It returns true on replacement, false for an absent key or mismatch, and null
  172. on failure, like `update` (`lastError()` gives duplicate-key details). The
  173. replacement is complete, not merged; a missing primary key comes from `key`.
  174. Unique conflicts are checked before deleting the old row. `update` is unchanged.
  175. For a counter initialized with `db.put({ id = 'counter'; seq = 0 })`:
  176. ```hybriel
  177. let done = false
  178. while (!done) {
  179. old = db.fetch('counter').seq
  180. result = db.compareAndSet('counter', { seq = old + 1 }, { seq = old })
  181. if (result == null) { hlError(db.lastError()) }
  182. done = result
  183. }
  184. ```
  185. This is native-only (`MPackDB.hl` / `server.hl`); the JavaScript target has no
  186. mpackdb implementation in `js/src/runtime`. The separate JS mpackdb package
  187. has no new API here. All writers must cooperate with the `.lock` protocol;
  188. this adds no crash transaction, multi-table transaction or ABA protection.

Branches

Latest commits

  • 5d7cc700Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
  • 3e07b1cfVendor complete Hybriel day39 plugin sources and librariesmre
  • d7366702Check session cookie flags after login and assert anonymous GET stays cookielessmre
  • 16bc8fd8Re-vendor Hybriel day38b with the mpackdb store-open race fixmre
  • d860dc2dnotes#12: the markup names its own rules instead of hand-written class strings: the selected row is `aria-current="page"` (the list-first theme rule styles it, no class), the delete question is `Style.pAsk` and follows its own `open` attribute (bound to `asking`), the error line is `Style.pMessage` (body once in lib/looks.hl, rule in notes.hl, main.hl and loginfailed.hl). The CSS declarations are the same, only selectors changed (.ask -> p.ask, .ask.open -> p.ask[open], .message -> p.message); the pages look the same (AE 0 at 4 sizes). main.hl's selectorClass in/out stays (login.js reads it).mre
  • 2e7f8664notes#13: the list and back links pass the note key from the loop (emit pick(e, r.key)) instead of writing data-note into the View and reading it back with getAttribute; the two window.history.replaceState calls and the identcode e.target.value read stay (hl:web has no replace-navigation, a bound hidden input is not adopted on a script's change event), see NO13 reportmre
  • 4dc98282notes#15: a deleted note made in this tab leaves the list at once (the delete now removes this tab's edit under every key the row has: local id, server id); gate: browser.mjs notes#15 section, red on the old codemre
  • e4e7402fnotes#11: plain declarations instead of let for variables never reassigned (components/notes.hl 3, lib/jsoncheck.hl 5, lib/util.hl 2, tools/migrate-short-ids.hl 8)mre
  • 27b6a09enotes#8: Style blocks in the nested form (note-list, note-editor, .ask with their children nested, :empty as a nested pseudo-class); the same CSS rules, the pages look the samemre
  • 71a9538bnotes: B27W report, log linemre
  • 78ba0073notes: an ident access key (Authorization: Bearer idt_…) reads and writes its identity's notes through /api/me and /api/notes; gate tests/ident-access-notes.mjs (ident#27)mre
  • 3de46dacnotes: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 73+5 failing → 78 passedmre
  • 5909d458notes: MdEditor from components 59704ce (text on the clipboard always pastes, a file manager copy still attaches; pipe rows without a delimiter row; tickets#49, notes#5)mre
  • 98bd6a98N5b: pipe rows without a delimiter row are a table (MdEditor ad4e929, plain copy); gate tests/dashboard-table.mjs; reportmre
  • dbf93319N5 report: components gate rerun 613 passed, 0 failedmre
  • 3a8bc0d2N5: empty Table-button table is written as a real pipe table (MdEditor 4bd1112, plain copy); gate tests/table-button.mjs; reportmre
  • c16bd443N5: step 1 report (tables pass locally; his DASHBOARD note has no delimiter row)mre
  • 6091320anotes: MdEditor 7437e32 (surface drawn at once when the page is claimed); gate measures claim-to-text on 5 note loads at 1280 and 390mre
  • 0aa9277enotes: move each component's styles into its own Style block (shell and header selector in main.hl, list, editor frame and delete question in notes.hl); styles.hl keeps the theme inherit, the accent and the message colour; .gitignore ignores a bin symlink too; tests/shots.mjs for the pixel comparemre
  • 9ba01de3notes: write the standby service out in full so the boot gate can read the main servicemre