gitoria

mpackdb

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmastercde6b2751.0.8: validate indexes against the data file on open, atomic index writes, invalidate index state before compaction; tests for pk find after compaction and hard killmremaster/tests/index-recovery.test.js

5.2 KB

  1. // 1.0.8: indexes must never be trusted blindly. Covers
  2. // - bug 1 (find(pk) after update/delete + restart compaction)
  3. // - bug 2 (hard kill without close, indexes not persisted)
  4. // - stale index files that do not match the data file (index from before a compaction, torn index line)
  5. // - stores written by mpackdb 1.0.6 (set MPACKDB_106=<path to 1.0.6 src/MPackDB.js> to enable)
  6. // MPACKDB_LIB=<path to MPackDB.js> runs the same checks against another version (e.g. 1.0.7) to show they fail there.
  7. import { rm, cp, readFile, writeFile, readdir } from 'node:fs/promises';
  8. import { resolve, dirname } from 'node:path';
  9. import { fileURLToPath } from 'node:url';
  10. import { spawnSync } from 'node:child_process';
  11. import assert from 'node:assert/strict';
  12. const here = dirname(fileURLToPath(import.meta.url));
  13. const lib = resolve(process.env.MPACKDB_LIB || resolve(here, '../src/MPackDB.js'));
  14. const { MPackDB } = await import(lib);
  15. const base = resolve(here, 'db/index-recovery');
  16. await rm(base, { recursive: true, force: true });
  17. const opts = { primaryKey: 'sessionId', indexes: ['userId'], indexPersistInterval: 0 };
  18. let failures = 0;
  19. async function check(name, fn) {
  20. try { await fn(); console.log('✓', name); } catch (e) { failures++; console.log('✗', name, '-', e.message.split('\n')[0]); }
  21. }
  22. async function findAll(db, ids) {
  23. for (const id of ids) {
  24. const r = await db.find(id).toArray();
  25. assert.equal(r.length, 1, `find(${id}) returned ${r.length}`);
  26. assert.equal(r[0].sessionId, id);
  27. }
  28. }
  29. const seed = async (dir, n = 7) => {
  30. const db = new MPackDB(`${dir}/sessions`, opts);
  31. for (let i = 0; i < n; i++) await db.insert({ sessionId: 's' + i, userId: 'u' + (i % 3), n: i, pad: 'x'.repeat(10 + i * 7) });
  32. return db;
  33. };
  34. await check('bug1: update+delete, close, reopen (compaction), find(pk) for all', async () => {
  35. const dir = `${base}/bug1`;
  36. let db = await seed(dir);
  37. await db.update('s1', r => ({ ...r, n: 100 }));
  38. await db.update('s4', r => ({ ...r, n: 400, extra: 'longer value'.repeat(5) }));
  39. await db.delete('s2');
  40. await db.close();
  41. db = new MPackDB(`${dir}/sessions`, opts);
  42. await findAll(db, ['s0', 's1', 's3', 's4', 's5', 's6']);
  43. assert.equal((await db.find('s2').toArray()).length, 0);
  44. assert.equal((await db.find(() => true).toArray()).length, 6);
  45. await db.close();
  46. });
  47. await check('bug2: SIGKILL without close, reopen, find(pk) for all', () => {
  48. const r = spawnSync(process.execPath, [resolve(here, 'repro-bug2-hardkill.mjs'), lib, `${base}/bug2`], { encoding: 'utf8' });
  49. assert.equal(r.status, 0, r.stdout.trim().split('\n').slice(-2).join(' | '));
  50. });
  51. await check('stale index files from before a compaction are detected (compact:false open)', async () => {
  52. const dir = `${base}/stale`;
  53. let db = await seed(dir);
  54. await db.close(); // persists indexes + idxstate for the 7 records
  55. const files = (await readdir(dir)).filter(f => f.endsWith('.txt') || f.endsWith('.idxstate.json'));
  56. const saved = {};
  57. for (const f of files) saved[f] = await readFile(`${dir}/${f}`);
  58. db = new MPackDB(`${dir}/sessions`, opts);
  59. await db.delete('s0'); await db.delete('s3');
  60. await db.close();
  61. db = new MPackDB(`${dir}/sessions`, opts); // compaction shifts every offset
  62. await db.init();
  63. assert.equal((await db.find(() => true).toArray()).length, 5);
  64. await db.close();
  65. for (const f of files) await writeFile(`${dir}/${f}`, saved[f]); // simulate crash before index rebuild
  66. db = new MPackDB(`${dir}/sessions`, { ...opts, compact: false });
  67. await findAll(db, ['s1', 's2', 's4', 's5', 's6']);
  68. assert.equal((await db.find('s0').toArray()).length, 0);
  69. await db.close();
  70. });
  71. await check('torn index line is detected and the index rebuilt', async () => {
  72. const dir = `${base}/torn`;
  73. let db = await seed(dir);
  74. await db.close();
  75. const f = `${dir}/sessions.sessionId.txt`;
  76. const txt = await readFile(f, 'utf8');
  77. await writeFile(f, txt.slice(0, txt.length - 6)); // cut the last line
  78. db = new MPackDB(`${dir}/sessions`, { ...opts, compact: false });
  79. await findAll(db, ['s0', 's1', 's2', 's3', 's4', 's5', 's6']);
  80. await db.close();
  81. });
  82. const old = process.env.MPACKDB_106;
  83. if (old) {
  84. for (const scenario of ['compact-bug', 'hardkill']) {
  85. await check(`1.0.6-written store (${scenario}) opens, repairs and finds every pk`, async () => {
  86. const dir = `${base}/old-${scenario}`;
  87. spawnSync(process.execPath, [resolve(here, 'helpers/stage-old.mjs'), resolve(old), dir, scenario]);
  88. const expect = scenario === 'compact-bug' ? ['s0', 's1', 's3', 's4', 's5', 's6'] : ['s0', 's1', 's2', 's3', 's4', 's6', 's7', 's8'];
  89. for (const compact of [false, true]) {
  90. const copy = `${dir}-copy-${compact}`;
  91. await cp(dir, copy, { recursive: true });
  92. const db = new MPackDB(`${copy}/sessions`, { ...opts, compact });
  93. await findAll(db, expect);
  94. assert.equal((await db.find(() => true).toArray()).length, expect.length);
  95. await db.close();
  96. // and a second open (now with 1.0.8 state files) still works
  97. const db2 = new MPackDB(`${copy}/sessions`, { ...opts, compact });
  98. await findAll(db2, expect);
  99. await db2.close();
  100. }
  101. });
  102. }
  103. } else console.log('- 1.0.6 compatibility checks skipped (set MPACKDB_106)');
  104. await rm(base, { recursive: true, force: true });
  105. console.log(failures ? `FAIL: ${failures}` : 'ALL PASS');
  106. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • cde6b2751.0.8: validate indexes against the data file on open, atomic index writes, invalidate index state before compaction; tests for pk find after compaction and hard killmre
  • 87888725release 1.0.7caramboleyo
  • c4cdb9b6node: import prefixes (Deno compat) + pre-existing index-state WIPcaramboleyo
  • 0afb8f4bupdate now must be a callbackcaramboleyo
  • cde73eb4release 1.0.6caramboleyo
  • d01dda02add index hints, intersection, boundingBox; remove findByIndexcaramboleyo
  • b8ffc1a0release 1.0.5caramboleyo
  • d47876a1reimplemented lost features like indexed find and more testscaramboleyo
  • 7f08da9afixed insert ignoring model definitioncaramboleyo
  • 705774a9added flush before findcaramboleyo
  • b4db6391initial commitcaramboleyo