gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitfeeaa701feeaa701|||PR gates: explicit ports only, deploy.sh passes themmrefeeaa701/plugins/mpackdb/tools/check-integrity.mjs

11.7 KB

  1. #!/usr/bin/env node
  2. // READ ONLY: plain filesystem reads, never opens the database engine, locks or repairs.
  3. // Usage: node check-integrity.mjs <directory> [--json]
  4. // A plain delete whose tombstone was lost leaves no trace: the row looks live.
  5. // Only update-resurrections (multiple live versions) are detectable for sure.
  6. // Run on a quiescent COPY. Tombstones are taken from that copy's metadata;
  7. // this tool does not reconstruct or repair metadata from older file generations.
  8. import { readFileSync, readdirSync, openSync, readSync, closeSync, fstatSync } from 'node:fs'
  9. import { createHash } from 'node:crypto'
  10. import { join } from 'node:path'
  11. import { isDeepStrictEqual } from 'node:util'
  12. function decode(buf, start) {
  13. let p = start
  14. const need = n => { if (p + n > buf.length) throw new Error("truncated MessagePack") }
  15. const val = () => {
  16. need(1)
  17. const b = buf[p++]
  18. if (b <= 0x7f) return b
  19. if (b >= 0xe0) return b - 256
  20. if ((b & 0xe0) === 0xa0) return str(b & 0x1f)
  21. if ((b & 0xf0) === 0x80) return map(b & 0x0f)
  22. if ((b & 0xf0) === 0x90) return arr(b & 0x0f)
  23. switch (b) {
  24. case 0xc0: return null
  25. case 0xc2: return false
  26. case 0xc3: return true
  27. case 0xc4: need(1); return bin(buf[p++])
  28. case 0xc5: { const n = buf.readUInt16BE(p); p += 2; return bin(n) }
  29. case 0xc6: { const n = buf.readUInt32BE(p); p += 4; return bin(n) }
  30. case 0xca: { const v = buf.readFloatBE(p); p += 4; return v }
  31. case 0xcb: { const v = buf.readDoubleBE(p); p += 8; return v }
  32. case 0xcc: need(1); return buf[p++]
  33. case 0xcd: { const v = buf.readUInt16BE(p); p += 2; return v }
  34. case 0xce: { const v = buf.readUInt32BE(p); p += 4; return v }
  35. case 0xcf: { const v = Number(buf.readBigUInt64BE(p)); p += 8; return v }
  36. case 0xd0: return buf.readInt8(p++)
  37. case 0xd1: { const v = buf.readInt16BE(p); p += 2; return v }
  38. case 0xd2: { const v = buf.readInt32BE(p); p += 4; return v }
  39. case 0xd3: { const v = Number(buf.readBigInt64BE(p)); p += 8; return v }
  40. case 0xd9: need(1); return str(buf[p++])
  41. case 0xda: { const n = buf.readUInt16BE(p); p += 2; return str(n) }
  42. case 0xdb: { const n = buf.readUInt32BE(p); p += 4; return str(n) }
  43. case 0xdc: { const n = buf.readUInt16BE(p); p += 2; return arr(n) }
  44. case 0xdd: { const n = buf.readUInt32BE(p); p += 4; return arr(n) }
  45. case 0xde: { const n = buf.readUInt16BE(p); p += 2; return map(n) }
  46. case 0xdf: { const n = buf.readUInt32BE(p); p += 4; return map(n) }
  47. case 0xc7: { const n = buf.readUInt8(p++); return ext(n) }
  48. case 0xc8: { const n = buf.readUInt16BE(p); p += 2; return ext(n) }
  49. case 0xc9: { const n = buf.readUInt32BE(p); p += 4; return ext(n) }
  50. case 0xd4: return ext(1)
  51. case 0xd5: return ext(2)
  52. case 0xd6: return ext(4)
  53. case 0xd7: return ext(8)
  54. case 0xd8: return ext(16)
  55. default: throw new Error('unsupported msgpack byte 0x' + b.toString(16))
  56. }
  57. }
  58. const ext = n => { need(n + 1); const type = buf.readInt8(p++); return { extension: type, ...bin(n) } }
  59. const str = (n) => { need(n); const s = buf.toString('utf8', p, p + n); p += n; return s }
  60. const bin = (n) => { need(n); const b = buf.subarray(p, p + n); p += n; return { binary: b.toString("hex") } }
  61. const arr = (n) => { const a = []; for (let i = 0; i < n; i++) a.push(val()); return a }
  62. const map = (n) => { const o = Object.create(null); for (let i = 0; i < n; i++) { const k = val(); o[k] = val() } return o }
  63. const result = val()
  64. if (p !== buf.length) throw new Error("trailing bytes in record")
  65. return result
  66. }
  67. // Reuse one chunk; carry only the current frame across chunk boundaries.
  68. function* frames(fd, length) {
  69. const chunk = Buffer.allocUnsafe(1024 * 1024)
  70. let available = 0, cursor = 0, position = 0
  71. const take = (target, count, offset) => {
  72. let copied = 0
  73. while (copied < count) {
  74. if (cursor === available) {
  75. available = readSync(fd, chunk, 0, chunk.length, position)
  76. position += available
  77. cursor = 0
  78. if (!available) throw new Error(`damaged or truncated frame at ${offset}`)
  79. }
  80. const n = Math.min(count - copied, available - cursor)
  81. chunk.copy(target, copied, cursor, cursor + n)
  82. cursor += n
  83. copied += n
  84. }
  85. }
  86. const header = Buffer.allocUnsafe(4)
  87. for (let offset = 0; offset < length;) {
  88. if (offset + 4 > length) throw new Error(`truncated frame header at ${offset}`)
  89. take(header, 4, offset)
  90. const size = header.readUInt32LE(0)
  91. if (size < 5 || offset + size > length) throw new Error(`damaged or truncated frame at ${offset}`)
  92. const payload = Buffer.allocUnsafe(size - 4)
  93. take(payload, payload.length, offset)
  94. yield { offset, payload }
  95. offset += size
  96. }
  97. }
  98. function rowAt(fd, offset) {
  99. const header = Buffer.allocUnsafe(4)
  100. const read = (buf, position) => {
  101. let n = 0
  102. while (n < buf.length) {
  103. const got = readSync(fd, buf, n, buf.length - n, position + n)
  104. if (!got) throw new Error(`damaged or truncated frame at ${offset}`)
  105. n += got
  106. }
  107. }
  108. read(header, offset)
  109. const payload = Buffer.allocUnsafe(header.readUInt32LE(0) - 4)
  110. read(payload, offset + 4)
  111. return decode(payload, 0)
  112. }
  113. const args = process.argv.slice(2)
  114. if (args.length < 1 || args.length > 2 || args[0].startsWith('--') || (args[1] && args[1] !== '--json')) {
  115. console.error('usage: node check-integrity.mjs <directory> [--json]')
  116. process.exit(2)
  117. }
  118. const [dir] = args
  119. const json = args.includes('--json')
  120. const short = v => {
  121. const s = v === undefined ? '<missing>' : JSON.stringify(v)
  122. return s.length > 100 ? s.slice(0, 97) + '...' : s
  123. }
  124. // keyFromValue/cmpKeys in engine.zig: numbers and strings compare by their
  125. // string form when mixed; null, objects, arrays and binary are not indexed.
  126. const key = v => typeof v === 'string' || typeof v === 'number' ? String(v) : null
  127. const report = { directory: dir, tables: [], errors: [] }
  128. try {
  129. const files = readdirSync(dir)
  130. for (const file of files.filter(f => f.endsWith('.mpack')).sort()) {
  131. const name = file.slice(0, -6)
  132. const table = { name, records: 0, live: 0, tombstoned: 0, duplicates: 0, primaryKey: null,
  133. generation: null, duplicatePrimaryKeys: [], uniqueCollisions: [], errors: [] }
  134. report.tables.push(table)
  135. let fd
  136. try {
  137. fd = openSync(join(dir, file), 'r')
  138. const length = fstatSync(fd).size
  139. const meta = files.includes(name + '.meta.json')
  140. ? JSON.parse(readFileSync(join(dir, name + '.meta.json'), 'utf8')) : {}
  141. if (!Array.isArray(meta.deleted ?? [])) throw new Error('invalid deleted list')
  142. const deleted = new Set(meta.deleted ?? [])
  143. if ([...deleted].some(n => !Number.isSafeInteger(n) || n < 0)) throw new Error('invalid tombstone offset')
  144. if (meta.dataFile?.size > length) throw new Error('metadata names a longer data generation; cannot classify live rows')
  145. table.generation = meta.dataFile?.gen ?? null
  146. const schema = meta.schema
  147. if (!schema || typeof schema.primaryKey !== 'string' || !schema.primaryKey) {
  148. table.errors.push('primary-key schema unavailable; duplicate primary keys cannot be checked')
  149. } else table.primaryKey = schema.primaryKey.replace(/^[*@]/, '')
  150. const unique = (schema?.indexes ?? []).filter(f => f.startsWith('!')).map(f => f.slice(1).replace(/^\*/, ''))
  151. const fields = [...new Set([table.primaryKey, ...unique].filter(Boolean))]
  152. const groups = new Map(fields.map(f => [f, new Map()]))
  153. const unmatchedDeleted = new Set(deleted)
  154. for (const { offset, payload } of frames(fd, length)) {
  155. unmatchedDeleted.delete(offset)
  156. table.records++
  157. if (deleted.has(offset)) table.tombstoned++
  158. else {
  159. table.live++
  160. const first = payload[0]
  161. if ((first & 0xf0) !== 0x80 && first !== 0xde && first !== 0xdf) throw new Error(`record at ${offset} is not a map`)
  162. const row = decode(payload, 0)
  163. if (!row || typeof row !== 'object' || Array.isArray(row)) throw new Error(`record at ${offset} is not a map`)
  164. for (const [field, values] of groups) {
  165. const k = key(row[field])
  166. if (k === null) {
  167. if (field === table.primaryKey) table.errors.push(`record at ${offset} lacks an indexable primary key`)
  168. continue
  169. }
  170. if (!values.has(k)) values.set(k, [])
  171. values.get(k).push({ offset, digest: createHash('sha256').update(payload).digest('hex') })
  172. }
  173. }
  174. }
  175. for (const offset of unmatchedDeleted) table.errors.push(`tombstone ${offset} is not a record start`)
  176. for (const [field, values] of groups) for (const [value, rows] of values) {
  177. if (rows.length < 2) continue
  178. const offsets = rows.map(r => r.offset)
  179. if (field === table.primaryKey) {
  180. const firstRow = rowAt(fd, rows[0].offset)
  181. const allFields = new Set(Object.keys(firstRow))
  182. const differing = new Set()
  183. for (const r of rows.slice(1)) {
  184. const row = rowAt(fd, r.offset)
  185. for (const f of Object.keys(row)) allFields.add(f)
  186. for (const f of allFields) if (!isDeepStrictEqual(row[f], firstRow[f])) differing.add(f)
  187. }
  188. const differingFields = [...differing].sort()
  189. table.duplicatePrimaryKeys.push({ field, value, offsets, newestOffset: offsets.at(-1), differingFields,
  190. versions: rows.map(r => {
  191. const row = rowAt(fd, r.offset)
  192. return { offset: r.offset, newest: r.offset === offsets.at(-1),
  193. differences: Object.fromEntries(differingFields.map(f => [f, short(row[f])])) }
  194. }) })
  195. table.duplicates += rows.length - 1
  196. } else table.uniqueCollisions.push({ field, value, offsets })
  197. }
  198. } catch (e) { table.errors.push(e.message) }
  199. finally { if (fd !== undefined) closeSync(fd) }
  200. }
  201. } catch (e) { report.errors.push(e.message) }
  202. const failed = report.errors.length || report.tables.some(t => t.errors.length || t.duplicates || t.uniqueCollisions.length)
  203. if (json) console.log(JSON.stringify(report, null, 2))
  204. else {
  205. if (!report.tables.length) console.log('no .mpack tables found')
  206. for (const t of report.tables) {
  207. console.log(`${t.name}: records=${t.records} live=${t.live} tombstoned=${t.tombstoned} duplicates=${t.duplicates} uniqueCollisions=${t.uniqueCollisions.length} generation=${t.generation ?? 'unknown'}`)
  208. for (const d of t.duplicatePrimaryKeys) {
  209. console.log(` DUPLICATE ${d.field}=${JSON.stringify(d.value)} offsets=[${d.offsets}] newest=${d.newestOffset}; differing fields: ${d.differingFields.join(', ') || '(identical)'}`)
  210. for (const v of d.versions) console.log(` offset=${v.offset}${v.newest ? ' newest' : ''} ${JSON.stringify(v.differences)}`)
  211. }
  212. for (const c of t.uniqueCollisions) console.log(` UNIQUE COLLISION ${c.field}=${JSON.stringify(c.value)} offsets=[${c.offsets}]`)
  213. for (const e of t.errors) console.log(` ERROR: ${e}`)
  214. }
  215. for (const e of report.errors) console.error(`ERROR: ${e}`)
  216. }
  217. process.exitCode = failed ? 1 : 0

Branches

Latest commits

  • feeaa701|||PR gates: explicit ports only, deploy.sh passes themmre
  • 6cc1f943Merge branch 'records-1112' into mainGitoria
  • 9448c438|||PR records: LOG, missions and reports since 11-09mre
  • 6dc08a8eMerge branch 'p51-public-pr-reads' into mainGitoria
  • 7b88cfe0Type publicReaderOfRequest parameters (L10)Gitoria
  • 2a4b3dc1|||PR Anonymous reads of public repos' pulls and statusesmre
  • 21b2c141Merge branch 's25-no-session-on-login-error' into mainGitoria
  • 698458e2|||PR No session for cookieless login errors: READMEmre
  • cce7b785|||PR No session for cookieless login errorsmre
  • 678d6303Merge branch 'v59' into mainGitoria
  • 5803cf4f|||PR vendor: Hybriel set-day59 and GC budget 32 MiBmre
  • 9eff6627Merge branch 'f2-api-bugs' into mainGitoria
  • 26117255|||PR apps API: review comments on files with spaces in their namemre
  • b8796cecMerge branch 'f1-broken-json' into mainGitoria
  • 2f2959c5|||PR apps API: broken JSON body gives 400 invalid_json, not 500mre
  • f7c6ca07Merge branch 'ident-chooser-selector' into mainGitoria
  • 691abb8e|||PR tests: find ident identity choice without the removed .choose classmre
  • 16a3530fMerge branch 'heap-revert' into mainGitoria
  • 220a80e0|||PR Remove temporary /__heap route and heap helper; logmre
  • 13f0c342Merge branch 'hl25-records' into mainGitoria