veritas-kanban/server/src/__tests__/atomic-write.test.ts
Brad Groux 5791622620
fix: harden file storage integrity and mutation ordering (#804)
* fix: atomic task writes, revision lock, activity perf, diagnostics cache (#776, #777, #782, #784)

- Add atomicWriteFile helper to fs-helpers (write-tmp + rename, cleanup on error)
- Apply atomic writes to task create/update/archive/restore paths (#776)
- Reorder archive/restore to write dest before removing source (#776)
- Lock updateTask on current filepath (stable per task ID, not tentative new path) (#777)
- Validate expectedRevision inside mutation lock against fresh task (#777)
- Extract loadAllFiltered in ActivityService; countActivities no longer double-scans (#782)
- Atomic writes for activity logActivity and clearActivities (#782)
- Back up corrupt activity file before reset instead of silent overwrite (#782)
- Cache task identity diagnostics in TaskService; invalidate on markWrite + watcher (#784)
- BacklogService mutations invalidate the shared diagnostics cache (#784)
- Add rename to node:fs/promises mocks in jwt-rotation and docker-paths tests
- Add test files: atomic-write, activity-service-perf, task-revision-atomicity, task-identity-diagnostics-cache
- Update CHANGELOG for all four fixes

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix: task-ID-keyed mutex for in-process mutation serialization (#777)

- Add withTaskMutex<T>(id, fn) keyed on immutable task ID (not filepath)
  so all in-process mutations for the same task serialize even when
  title/slug changes the filename between writes
- Cross-process protection is retained via the existing withFileLock on
  the current filepath inside the critical section
- Mutex map entry is deleted only if the finishing promise is still
  current, preventing an older finisher from erasing a newer waiter
- taskMutexes.clear() on service teardown
- Extract normalizedTaskRevision helper; apply consistently in
  expectedRevision check and revision increment path
- Propagate ENOENT-safe unlink on slug rename; re-throw other errors
- Atomic unlink for archive/restore sources (no silent swallow)
- Add regression tests:
  - serializes slug-changing updates without stale files
  - does not let older finisher clear newer queued waiter

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix: finalize storage integrity remediation

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-07-10 09:15:49 -05:00

75 lines
2.9 KiB
TypeScript

/**
* Tests for atomicWriteFile (#776)
*
* Verifies that:
* - A successful write is visible atomically (no partial state).
* - No temp files leak after a successful write.
* - A failed rename does not silently corrupt (no stray .tmp.* files remain).
*/
import { describe, it, expect, afterEach } from 'vitest';
import { promises as fs } from 'node:fs';
import path from 'path';
import os from 'os';
import { atomicWriteFile } from '../storage/fs-helpers.js';
describe('atomicWriteFile', () => {
let testDir: string;
afterEach(async () => {
if (testDir) {
await fs.rm(testDir, { recursive: true, force: true }).catch(() => {});
}
});
it('writes content atomically — final content matches what was written', async () => {
const suffix = Math.random().toString(36).substring(7);
testDir = path.join(os.tmpdir(), `vk-atomic-test-${suffix}`);
await fs.mkdir(testDir, { recursive: true });
const destPath = path.join(testDir, 'task.md');
const original = '# original content';
const updated = '# updated content';
await atomicWriteFile(destPath, original);
expect(await fs.readFile(destPath, 'utf-8')).toBe(original);
await atomicWriteFile(destPath, updated);
expect(await fs.readFile(destPath, 'utf-8')).toBe(updated);
});
it('leaves no stray temp files after a successful write', async () => {
const suffix = Math.random().toString(36).substring(7);
testDir = path.join(os.tmpdir(), `vk-atomic-noleak-${suffix}`);
await fs.mkdir(testDir, { recursive: true });
const destPath = path.join(testDir, 'task.md');
await atomicWriteFile(destPath, '# content');
const files = await fs.readdir(testDir);
const tmpFiles = files.filter((f) => f.includes('.tmp.'));
expect(tmpFiles).toHaveLength(0);
});
it('preserves an existing destination and cleans up when replacement rename fails', async () => {
const suffix = Math.random().toString(36).substring(7);
testDir = path.join(os.tmpdir(), `vk-atomic-fail-${suffix}`);
await fs.mkdir(testDir, { recursive: true });
// Point dest at an existing non-empty directory — rename will fail with EISDIR/ENOTDIR
const blockingDir = path.join(testDir, 'blocker');
const blockingFile = path.join(blockingDir, 'sentinel');
await fs.mkdir(blockingDir, { recursive: true });
await fs.writeFile(blockingFile, 'sentinel');
// Attempt to atomically write to the blocking directory path
await expect(atomicWriteFile(blockingDir, '# would overwrite dir')).rejects.toThrow();
// No stray .tmp.* files should remain in the parent dir
const files = await fs.readdir(testDir);
const tmpFiles = files.filter((f) => f.includes('.tmp.'));
expect(tmpFiles).toHaveLength(0);
// The blocking directory must still be intact — nothing was destroyed
await expect(fs.readFile(blockingFile, 'utf-8')).resolves.toBe('sentinel');
});
});