notes
All repositories: gitoria
11.7 KB
#!/usr/bin/env node// READ ONLY: plain filesystem reads, never opens the database engine, locks or repairs.// Usage: node check-integrity.mjs <directory> [--json]// A plain delete whose tombstone was lost leaves no trace: the row looks live.// Only update-resurrections (multiple live versions) are detectable for sure.// Run on a quiescent COPY. Tombstones are taken from that copy's metadata;// this tool does not reconstruct or repair metadata from older file generations.import { readFileSync, readdirSync, openSync, readSync, closeSync, fstatSync } from 'node:fs'import { createHash } from 'node:crypto'import { join } from 'node:path'import { isDeepStrictEqual } from 'node:util'function decode(buf, start) {let p = startconst need = n => { if (p + n > buf.length) throw new Error("truncated MessagePack") }const val = () => {need(1)const b = buf[p++]if (b <= 0x7f) return bif (b >= 0xe0) return b - 256if ((b & 0xe0) === 0xa0) return str(b & 0x1f)if ((b & 0xf0) === 0x80) return map(b & 0x0f)if ((b & 0xf0) === 0x90) return arr(b & 0x0f)switch (b) {case 0xc0: return nullcase 0xc2: return falsecase 0xc3: return truecase 0xc4: need(1); return bin(buf[p++])case 0xc5: { const n = buf.readUInt16BE(p); p += 2; return bin(n) }case 0xc6: { const n = buf.readUInt32BE(p); p += 4; return bin(n) }case 0xca: { const v = buf.readFloatBE(p); p += 4; return v }case 0xcb: { const v = buf.readDoubleBE(p); p += 8; return v }case 0xcc: need(1); return buf[p++]case 0xcd: { const v = buf.readUInt16BE(p); p += 2; return v }case 0xce: { const v = buf.readUInt32BE(p); p += 4; return v }case 0xcf: { const v = Number(buf.readBigUInt64BE(p)); p += 8; return v }case 0xd0: return buf.readInt8(p++)case 0xd1: { const v = buf.readInt16BE(p); p += 2; return v }case 0xd2: { const v = buf.readInt32BE(p); p += 4; return v }case 0xd3: { const v = Number(buf.readBigInt64BE(p)); p += 8; return v }case 0xd9: need(1); return str(buf[p++])case 0xda: { const n = buf.readUInt16BE(p); p += 2; return str(n) }case 0xdb: { const n = buf.readUInt32BE(p); p += 4; return str(n) }case 0xdc: { const n = buf.readUInt16BE(p); p += 2; return arr(n) }case 0xdd: { const n = buf.readUInt32BE(p); p += 4; return arr(n) }case 0xde: { const n = buf.readUInt16BE(p); p += 2; return map(n) }case 0xdf: { const n = buf.readUInt32BE(p); p += 4; return map(n) }case 0xc7: { const n = buf.readUInt8(p++); return ext(n) }case 0xc8: { const n = buf.readUInt16BE(p); p += 2; return ext(n) }case 0xc9: { const n = buf.readUInt32BE(p); p += 4; return ext(n) }case 0xd4: return ext(1)case 0xd5: return ext(2)case 0xd6: return ext(4)case 0xd7: return ext(8)case 0xd8: return ext(16)default: throw new Error('unsupported msgpack byte 0x' + b.toString(16))}}const ext = n => { need(n + 1); const type = buf.readInt8(p++); return { extension: type, ...bin(n) } }const str = (n) => { need(n); const s = buf.toString('utf8', p, p + n); p += n; return s }const bin = (n) => { need(n); const b = buf.subarray(p, p + n); p += n; return { binary: b.toString("hex") } }const arr = (n) => { const a = []; for (let i = 0; i < n; i++) a.push(val()); return a }const map = (n) => { const o = Object.create(null); for (let i = 0; i < n; i++) { const k = val(); o[k] = val() } return o }const result = val()if (p !== buf.length) throw new Error("trailing bytes in record")return result}// Reuse one chunk; carry only the current frame across chunk boundaries.function* frames(fd, length) {const chunk = Buffer.allocUnsafe(1024 * 1024)let available = 0, cursor = 0, position = 0const take = (target, count, offset) => {let copied = 0while (copied < count) {if (cursor === available) {available = readSync(fd, chunk, 0, chunk.length, position)position += availablecursor = 0if (!available) throw new Error(`damaged or truncated frame at ${offset}`)}const n = Math.min(count - copied, available - cursor)chunk.copy(target, copied, cursor, cursor + n)cursor += ncopied += n}}const header = Buffer.allocUnsafe(4)for (let offset = 0; offset < length;) {if (offset + 4 > length) throw new Error(`truncated frame header at ${offset}`)take(header, 4, offset)const size = header.readUInt32LE(0)if (size < 5 || offset + size > length) throw new Error(`damaged or truncated frame at ${offset}`)const payload = Buffer.allocUnsafe(size - 4)take(payload, payload.length, offset)yield { offset, payload }offset += size}}function rowAt(fd, offset) {const header = Buffer.allocUnsafe(4)const read = (buf, position) => {let n = 0while (n < buf.length) {const got = readSync(fd, buf, n, buf.length - n, position + n)if (!got) throw new Error(`damaged or truncated frame at ${offset}`)n += got}}read(header, offset)const payload = Buffer.allocUnsafe(header.readUInt32LE(0) - 4)read(payload, offset + 4)return decode(payload, 0)}const args = process.argv.slice(2)if (args.length < 1 || args.length > 2 || args[0].startsWith('--') || (args[1] && args[1] !== '--json')) {console.error('usage: node check-integrity.mjs <directory> [--json]')process.exit(2)}const [dir] = argsconst json = args.includes('--json')const short = v => {const s = v === undefined ? '<missing>' : JSON.stringify(v)return s.length > 100 ? s.slice(0, 97) + '...' : s}// keyFromValue/cmpKeys in engine.zig: numbers and strings compare by their// string form when mixed; null, objects, arrays and binary are not indexed.const key = v => typeof v === 'string' || typeof v === 'number' ? String(v) : nullconst report = { directory: dir, tables: [], errors: [] }try {const files = readdirSync(dir)for (const file of files.filter(f => f.endsWith('.mpack')).sort()) {const name = file.slice(0, -6)const table = { name, records: 0, live: 0, tombstoned: 0, duplicates: 0, primaryKey: null,generation: null, duplicatePrimaryKeys: [], uniqueCollisions: [], errors: [] }report.tables.push(table)let fdtry {fd = openSync(join(dir, file), 'r')const length = fstatSync(fd).sizeconst meta = files.includes(name + '.meta.json')? JSON.parse(readFileSync(join(dir, name + '.meta.json'), 'utf8')) : {}if (!Array.isArray(meta.deleted ?? [])) throw new Error('invalid deleted list')const deleted = new Set(meta.deleted ?? [])if ([...deleted].some(n => !Number.isSafeInteger(n) || n < 0)) throw new Error('invalid tombstone offset')if (meta.dataFile?.size > length) throw new Error('metadata names a longer data generation; cannot classify live rows')table.generation = meta.dataFile?.gen ?? nullconst schema = meta.schemaif (!schema || typeof schema.primaryKey !== 'string' || !schema.primaryKey) {table.errors.push('primary-key schema unavailable; duplicate primary keys cannot be checked')} else table.primaryKey = schema.primaryKey.replace(/^[*@]/, '')const unique = (schema?.indexes ?? []).filter(f => f.startsWith('!')).map(f => f.slice(1).replace(/^\*/, ''))const fields = [...new Set([table.primaryKey, ...unique].filter(Boolean))]const groups = new Map(fields.map(f => [f, new Map()]))const unmatchedDeleted = new Set(deleted)for (const { offset, payload } of frames(fd, length)) {unmatchedDeleted.delete(offset)table.records++if (deleted.has(offset)) table.tombstoned++else {table.live++const first = payload[0]if ((first & 0xf0) !== 0x80 && first !== 0xde && first !== 0xdf) throw new Error(`record at ${offset} is not a map`)const row = decode(payload, 0)if (!row || typeof row !== 'object' || Array.isArray(row)) throw new Error(`record at ${offset} is not a map`)for (const [field, values] of groups) {const k = key(row[field])if (k === null) {if (field === table.primaryKey) table.errors.push(`record at ${offset} lacks an indexable primary key`)continue}if (!values.has(k)) values.set(k, [])values.get(k).push({ offset, digest: createHash('sha256').update(payload).digest('hex') })}}}for (const offset of unmatchedDeleted) table.errors.push(`tombstone ${offset} is not a record start`)for (const [field, values] of groups) for (const [value, rows] of values) {if (rows.length < 2) continueconst offsets = rows.map(r => r.offset)if (field === table.primaryKey) {const firstRow = rowAt(fd, rows[0].offset)const allFields = new Set(Object.keys(firstRow))const differing = new Set()for (const r of rows.slice(1)) {const row = rowAt(fd, r.offset)for (const f of Object.keys(row)) allFields.add(f)for (const f of allFields) if (!isDeepStrictEqual(row[f], firstRow[f])) differing.add(f)}const differingFields = [...differing].sort()table.duplicatePrimaryKeys.push({ field, value, offsets, newestOffset: offsets.at(-1), differingFields,versions: rows.map(r => {const row = rowAt(fd, r.offset)return { offset: r.offset, newest: r.offset === offsets.at(-1),differences: Object.fromEntries(differingFields.map(f => [f, short(row[f])])) }}) })table.duplicates += rows.length - 1} else table.uniqueCollisions.push({ field, value, offsets })}} catch (e) { table.errors.push(e.message) }finally { if (fd !== undefined) closeSync(fd) }}} catch (e) { report.errors.push(e.message) }const failed = report.errors.length || report.tables.some(t => t.errors.length || t.duplicates || t.uniqueCollisions.length)if (json) console.log(JSON.stringify(report, null, 2))else {if (!report.tables.length) console.log('no .mpack tables found')for (const t of report.tables) {console.log(`${t.name}: records=${t.records} live=${t.live} tombstoned=${t.tombstoned} duplicates=${t.duplicates} uniqueCollisions=${t.uniqueCollisions.length} generation=${t.generation ?? 'unknown'}`)for (const d of t.duplicatePrimaryKeys) {console.log(` DUPLICATE ${d.field}=${JSON.stringify(d.value)} offsets=[${d.offsets}] newest=${d.newestOffset}; differing fields: ${d.differingFields.join(', ') || '(identical)'}`)for (const v of d.versions) console.log(` offset=${v.offset}${v.newest ? ' newest' : ''} ${JSON.stringify(v.differences)}`)}for (const c of t.uniqueCollisions) console.log(` UNIQUE COLLISION ${c.field}=${JSON.stringify(c.value)} offsets=[${c.offsets}]`)for (const e of t.errors) console.log(` ERROR: ${e}`)}for (const e of report.errors) console.error(`ERROR: ${e}`)}process.exitCode = failed ? 1 : 0
Branches
Latest commits
- 23758cd6Re-vendor complete Hybriel plugins and runtime to day44mre
- 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