Skip to content

Commit 8ac922f

Browse files
jerry-xu0514jerryxu-at-reve
authored andcommitted
fix(core): detect NFS and use local database path to prevent corruption
SQLite's WAL mode uses shared memory mappings (mmap) via the -shm file, which are incoherent across NFS clients. This causes database corruption when multiple opencode sessions write concurrently on NFS-mounted home directories. Detect NFS via statfs magic number (0x6969) and fall back to a local tmpdir path. Also add integrity checks on startup with auto-recreation to make corruption self-healing instead of a hard crash. Fixes anomalyco#14970
1 parent 4551282 commit 8ac922f

1 file changed

Lines changed: 60 additions & 6 deletions

File tree

  • packages/opencode/src/storage

‎packages/opencode/src/storage/db.ts‎

Lines changed: 60 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ import { Log } from "../util/log"
1010
import { NamedError } from "@opencode-ai/util/error"
1111
import z from "zod"
1212
import path from "path"
13-
import { readFileSync, readdirSync, existsSync } from "fs"
13+
import { readFileSync, readdirSync, existsSync, statfsSync, unlinkSync, mkdirSync } from "fs"
14+
import os from "os"
1415
import * as schema from "./schema"
1516

1617
declare const OPENCODE_MIGRATIONS: { sql: string; timestamp: number }[] | undefined
@@ -25,7 +26,8 @@ export const NotFoundError = NamedError.create(
2526
const log = Log.create({ service: "db" })
2627

2728
export namespace Database {
28-
export const Path = path.join(Global.Path.data, "opencode.db")
29+
/** Actual database path, set when Client is initialized. Falls back to default. */
30+
export let Path = path.join(Global.Path.data, "opencode.db")
2931
type Schema = typeof schema
3032
export type Transaction = SQLiteTransaction<"sync", void, Schema>
3133

@@ -69,18 +71,70 @@ export namespace Database {
6971
return sql.sort((a, b) => a.timestamp - b.timestamp)
7072
}
7173

74+
function isNFS(dir: string): boolean {
75+
try {
76+
// NFS magic number: 0x6969
77+
return statfsSync(dir).type === 0x6969
78+
} catch {
79+
return false
80+
}
81+
}
82+
83+
function removeDatabase(dbPath: string) {
84+
for (const suffix of ["", "-shm", "-wal"]) {
85+
try {
86+
unlinkSync(dbPath + suffix)
87+
} catch {}
88+
}
89+
}
90+
91+
/** Resolve the database directory, falling back to a local path on NFS. */
92+
function resolveDbDir(): string {
93+
const dataDir = Global.Path.data
94+
if (!isNFS(dataDir)) return dataDir
95+
96+
// SQLite's WAL mode requires shared memory via mmap, which is broken on
97+
// NFS. Instead of downgrading journal mode (slower, still fragile), just
98+
// put the database on a local filesystem.
99+
const localDir = path.join(os.tmpdir(), "opencode-" + os.userInfo().uid)
100+
mkdirSync(localDir, { recursive: true })
101+
log.info("NFS detected, using local database path", { nfs: dataDir, local: localDir })
102+
return localDir
103+
}
104+
72105
export const Client = lazy(() => {
73-
log.info("opening database", { path: path.join(Global.Path.data, "opencode.db") })
106+
const dbDir = resolveDbDir()
107+
const dbPath = path.join(dbDir, "opencode.db")
108+
Path = dbPath
109+
log.info("opening database", { path: dbPath })
74110

75-
const sqlite = new BunDatabase(path.join(Global.Path.data, "opencode.db"), { create: true })
76-
state.sqlite = sqlite
111+
let sqlite: BunDatabase
112+
try {
113+
sqlite = new BunDatabase(dbPath, { create: true })
114+
115+
// Integrity check — detect corruption before it causes harder-to-debug errors
116+
const result = sqlite.prepare("PRAGMA integrity_check").get() as { integrity_check: string } | undefined
117+
if (result?.integrity_check !== "ok") {
118+
log.warn("database corrupted, recreating", { path: dbPath, integrity: result?.integrity_check })
119+
sqlite.close()
120+
removeDatabase(dbPath)
121+
sqlite = new BunDatabase(dbPath, { create: true })
122+
}
123+
} catch (e) {
124+
// Database file itself may be unreadable/corrupt — remove and retry
125+
log.warn("database open failed, recreating", { path: dbPath, error: String(e) })
126+
removeDatabase(dbPath)
127+
sqlite = new BunDatabase(dbPath, { create: true })
128+
}
77129

78130
sqlite.run("PRAGMA journal_mode = WAL")
131+
try { sqlite.run("PRAGMA wal_checkpoint(PASSIVE)") } catch {}
79132
sqlite.run("PRAGMA synchronous = NORMAL")
80133
sqlite.run("PRAGMA busy_timeout = 5000")
81134
sqlite.run("PRAGMA cache_size = -64000")
82135
sqlite.run("PRAGMA foreign_keys = ON")
83-
sqlite.run("PRAGMA wal_checkpoint(PASSIVE)")
136+
137+
state.sqlite = sqlite
84138

85139
const db = drizzle({ client: sqlite, schema })
86140

0 commit comments

Comments
 (0)