fix: coordinate sqlite index writers

Implement the full ADR-0006 plan: three-layer separation of transaction
correctness, retry policy, and cross-process writer coordination.

Layer 1 — scripts/tx.ts (transaction correctness):
- runWriteTransaction executes work exactly once; no internal retry.
- BEGIN IMMEDIATE takes the write lock up front (avoids SQLITE_BUSY_SNAPSHOT).
- Guarded rollback: checks inTransaction() via adapter before attempting
  ROLLBACK; never masks the primary exception.
- WriteTxDiagnostics attached to errors: phase, code, label,
  rollbackSucceeded, rollbackError, transactionActive.
- Binding adapters (betterSqliteTransactionAdapter, nodeSqliteTransactionAdapter)
  mapping better-sqlite3's `.inTransaction` and node:sqlite's `.isTransaction`.
- configureConnection centralizes WAL + synchronous + busy_timeout.

Layer 2 — scripts/write-coordinator.ts (retry policy):
- runRetryableWriteTransaction: bounded retry with total time budget.
- Only retries when the transaction confirmed ended (transactionActive=false)
  and the error is SQLITE_BUSY during work/commit phase.
- BEGIN-phase BUSY = abort entire build (isBeginBusyFailure); the caller
  returns `{ deferred: true, reason: 'writer_busy' }` instead of waiting.
- hasUnusableTransaction detects a still-active transaction after failure;
  aborts the build immediately, never retries.

Layer 3 — scripts/writer-lease.ts (cross-process coordination):
- acquireWriterLease: dedicated writer.lock.sqlite with busy_timeout=0 +
  BEGIN IMMEDIATE. Non-blocking attempt; bounded wait with retryDelayMs.
- writerLockPathFor derives lock path from the target DB path.
- Lease held for the entire build; released on completion or failure.
- Lock DB uses DELETE journal (not WAL); crash/close auto-releases.
- All consumers obey: skill acquires at build start (returns deferred if
  unavailable); app daemon (via worker) acquires for its build cycle.

Build semantics changes:
- affectedSessionIds updated only after successful commit.
- BuildIndexResult gains skipped/skippedFiles for observability.
- Skill finalize failure now fails the build (was silently warned).
- Checkpoint changed to PASSIVE (TRUNCATE reserved for maintenance/exit).
- Skill buildIndex returns { deferred, reason } on lease contention;
  indexer-service reschedules the build (deferredRetryMs) without publishing
  a heartbeat (so the build-deferred state is visible to cross-process
  arbitration).
- Service publishes heartbeat immediately on start() for correct arbitration.

Tests:
- tests/write-transaction.test.mjs: single-shot execution, diagnostics
  propagation, auto-rolled-back transaction detected, rollback failure
  captured as metadata, BEGIN IMMEDIATE semantics.
- tests/writer-lease.test.mjs: acquire/release, contention returns null,
  bounded wait with release during budget.
- tests/app-writer-lease.test.mjs: better-sqlite3 adapter integration.
- tests/app-rollback-guard.test.mjs: rewritten — transient BUSY recovered
  by coordinator, persistent BUSY skips file, begin-busy aborts build,
  live-transaction aborts build, phantom affectedSessionIds prevented.
- tests/daemon-arbitration.test.mjs: skill defers to fresh app heartbeat,
  builds when heartbeat is stale.
- tests/app-indexer-service.test.mjs: new cases for deferred-retry
  scheduling and immediate heartbeat on start.
- app/tests/electron-concurrency.mjs + child: dual-child IPC structure for
  real better-sqlite3 contention (holder acquires lock → build child starts
  → delayed release → result collected; persistent contention bounded).

ADR-0006 updated to reflect the implemented design.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
tommy0103
2026-07-11 00:42:43 +08:00
co-authored by Claude Opus 4.8
parent 44029676d4
commit e3e61cc7ab
25 changed files with 2173 additions and 471 deletions
+97
View File
@@ -0,0 +1,97 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { buildIndex } from '../app/src/main/indexer.ts';
import { acquireWriterLease, writerLockPathFor } from '../scripts/writer-lease.ts';
const require = createRequire(import.meta.url);
const { DatabaseSync } = require('node:sqlite');
class TestDatabase {
constructor(dbPath) {
this.db = new DatabaseSync(dbPath);
}
get inTransaction() { return this.db.isTransaction; }
exec(sql) { return this.db.exec(sql); }
pragma(statement) { return this.db.exec(`PRAGMA ${statement}`); }
prepare(sql) { return this.db.prepare(sql); }
close() { return this.db.close(); }
}
test('an app build defers without opening the target database when another writer owns the lease', () => {
const home = mkdtempSync(join(tmpdir(), 'obelisk-app-writer-lease-'));
const claudeDir = join(home, '.claude');
const projectsDir = join(claudeDir, 'projects');
const projectDir = join(projectsDir, '-tmp-project');
const dbPath = join(home, '.obelisk', 'obelisk.sqlite');
mkdirSync(projectDir, { recursive: true });
mkdirSync(join(home, '.obelisk'), { recursive: true });
writeFileSync(join(projectDir, 'session.jsonl'), JSON.stringify({
uuid: 'message-1',
type: 'user',
timestamp: '2026-07-10T00:00:00Z',
message: { role: 'user', content: 'hello' },
}) + '\n');
const lease = acquireWriterLease({
lockPath: writerLockPathFor(dbPath),
openDb: path => new DatabaseSync(path),
});
assert.ok(lease);
try {
const result = buildIndex({
claudeDir,
projectsDir,
dbPath,
DatabaseImpl: TestDatabase,
writerLeaseWaitMs: 0,
});
assert.equal(result.deferred, true);
assert.equal(result.reason, 'writer_busy');
assert.equal(existsSync(dbPath), false);
} finally {
lease.release();
}
});
test('a failed force cleanup leaves the existing index intact', () => {
const home = mkdtempSync(join(tmpdir(), 'obelisk-app-force-atomic-'));
const claudeDir = join(home, '.claude');
const projectsDir = join(claudeDir, 'projects');
const projectDir = join(projectsDir, '-tmp-project');
const dbPath = join(home, '.obelisk', 'obelisk.sqlite');
mkdirSync(projectDir, { recursive: true });
mkdirSync(join(home, '.obelisk'), { recursive: true });
writeFileSync(join(projectDir, 'session.jsonl'), JSON.stringify({
uuid: 'message-1',
type: 'user',
timestamp: '2026-07-10T00:00:00Z',
message: { role: 'user', content: 'hello' },
}) + '\n');
buildIndex({ claudeDir, projectsDir, dbPath, DatabaseImpl: TestDatabase });
class FailingCleanupDatabase extends TestDatabase {
prepare(sql) {
const statement = super.prepare(sql);
if (!sql.includes('DELETE FROM sessions')) return statement;
return {
get: (...args) => statement.get(...args),
all: (...args) => statement.all(...args),
run: () => { throw new Error('cleanup interrupted'); },
};
}
}
assert.throws(
() => buildIndex({ claudeDir, projectsDir, dbPath, DatabaseImpl: FailingCleanupDatabase, force: true }),
/cleanup interrupted/,
);
const check = new DatabaseSync(dbPath, { readOnly: true });
assert.equal(check.prepare('SELECT COUNT(*) AS count FROM sessions').get().count, 1);
assert.equal(check.prepare('SELECT COUNT(*) AS count FROM messages').get().count, 1);
check.close();
});