Skip to content

bug(storage): settings.json, atomic replace has no durability fence and a corrupted file is unrecoverable; the atomic-write pattern drifts across stores #4285

Closed

Description

@chinawch007

What happened

Two coupled defects in packages/storage/src/settings-store.ts, one on the write path and one on the read path:

1. write() (settings-store.ts:209-214) performs temp + rename with no durability fence at all.

private async write(settings: AppSettings): Promise<void> {
  await mkdir(dirname(this.settingsPath), { recursive: true });
  const tempPath = `${this.settingsPath}.${process.pid}.${Date.now()}.tmp`;
  await writeFile(tempPath, JSON.stringify(settings, null, 2) + '\n', 'utf8');
  await rename(tempPath, this.settingsPath);
}

There is no handle.sync() on the temp file and no directory sync after the rename, so nothing orders the rename behind the file's data blocks. On a power loss or hard crash inside the write window, POSIX does not guarantee the data reached disk even though the rename did (the classic rename-without-fsync hazard — ext4's delayed-allocation zero-length files being the well-known instance), leaving settings.json present but zero-length or truncated. Additionally, the temp name is predictable (pid + Date.now()), the file is created without wx/O_EXCL, and a failed rename leaves the temp file behind.

2. readOrCreate() (settings-store.ts:92-102) only treats ENOENT as recoverable.

try {
  const text = await readFile(this.settingsPath, 'utf8');
  return normalizeSettings(JSON.parse(text));
} catch (error) {
  if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
  /* first run: write defaults */
}

A zero-length or truncated file makes JSON.parse throw a SyntaxError, which has no .code, so it falls into the rethrow branch: no fallback to defaults and no recovery guidance. The error propagates out of get(), and the desktop main call sites I checked invoke it without a catch (e.g. apps/desktop/src/main/runtime-host-settings-ipc-main.ts:146 and :179, apps/desktop/src/main/client-settings-ipc-main.ts:41-42), so settings loading fails outright.

Net effect: the write path can produce a corrupt file, and the read path treats corrupt as fatal. A missing settings.json gracefully gets defaults; a corrupted one bricks settings load until the user figures out they must delete <workspaceRoot>/settings.json by hand. mcp-config-store.ts:181-190 has the same ENOENT-only readOrCreate, so its read path shares the recovery gap.

How to reproduce

Real-world trigger (intermittent, low probability, deterministic consequence): change any setting, then lose power / hard reset inside the write window.

Deterministic simulation of the post-crash state:

  1. Locate the workspace settings file <workspaceRoot>/settings.json (constructed at settings-store.ts:80)
  2. Truncate it — either empty it completely or keep the first ~20 bytes so the JSON is cut mid-token
  3. Start the desktop app (or call settingsStore.get() directly)

Expected: settings load falls back to defaults, the same grace already extended to a missing file. Actual: a SyntaxError propagates out of get() and settings loading fails with no recovery path.

Environment

  • Maka version or commit: 8c491e6 (main)
  • OS and version: macOS 14 (the code paths are cross-platform; the missing-fsync hazard is POSIX-relevant)
  • Surface: Desktop / @maka/storage from source
  • Node.js version, if running from source: 24.x

Logs, screenshots, or additional context

The deeper issue is divergence: the same "atomic JSON file replace" pattern is implemented three times inside one package, at three different strictness levels — and the strictest one is the package's own documented standard.

hardening settings-store write() (:209) mcp-config-store write() (:197) credential-store writeSecretFileAtomic() (:261)
unpredictable temp name ✗ pid+Date.now() ✓ randomUUID() ✓ randomUUID()
exclusive create (wx / O_EXCL) ✗ ✓ ✓
0600 temp + chmod ✗ ✓ ✓
fsync temp before rename ✗ ✗ ✓ handle.sync()
fsync parent dir after rename ✗ ✗ ✓ syncDirectory()
temp cleanup on failure ✗ ✓ (swallows the error) ✓ (rethrows)

credential-store's JSDoc states the standard explicitly:

Owner-only atomic write for a credentials file: a 0700 dir, an exclusive 0600 temp ('wx'/O_EXCL so we never follow a pre-planted symlink at a predictable path), a durability fence before and after the atomic rename, and temp cleanup on failure.

settings-store meets none of these properties; mcp-config-store meets all but the durability fence. Meanwhile the fence primitives already exist and are exported — stable-storage.ts:90-133 provides syncFile / syncDirectory / syncDirectoryChain, already used by marker-file, memory-bundle-io and the session-bundle paths — and credential-store.ts:281 even carries a private duplicate of syncDirectory.

Suggested direction (happy to take this once triaged):

  1. Extract one shared atomic-write helper implementing the credential-store standard (randomUUID temp, wx, 0600, fsync file → rename → fsync dir, cleanup that rethrows) and point settings-store and mcp-config-store at it — removing the drift rather than patching each site.
  2. Harden both readOrCreate() implementations to distinguish "missing" from "corrupt": on corrupt, move the file aside (e.g. settings.json.corrupt-<timestamp>), rewrite defaults, and surface a warning — or at minimum throw a typed error naming the file to remove, instead of letting a bare SyntaxError propagate through startup.

Activity

  1. added
    bug
    on Aug 30, 2026
  2. chinawch007 commented on Aug 30, 2026

    @chinawch007
    ContributorAuthor

    take

  3. chinawch007 commented on Sep 1, 2026

    @chinawch007
    ContributorAuthor

    修复计划:storage 包 JSON store 写侧耐久性统一 + settings.json 损坏恢复

    对应 issue:#4285(写侧无 durability fence / 损坏文件无恢复路径 / 三处原子写实现严格度漂移)。PR2 的恢复策略为方案 A:备份 + 回默认 + 恢复通知,如维护者对此有异议,请在 PR2 开工前否决。

    拆分总览

    PR1 PR2
    分支 fix/storage-json-store-durability-fence fix/storage-settings-corrupt-recovery
    范围 写侧统一加固:新增共享 atomic write 工具,三个 store 接入 settings 读侧损坏恢复:备份 + 回默认 + 桌面通知
    行为变化 仅一处有意收紧:settings.json 0644→0600(见行为变化清单) 损坏文件从「抛错且字节不动」变为「备份后回默认并通知」
    依赖 无 依赖 PR1 的加固写入路径
    回滚影响 只损失加固,回到现状写入 回到现状「损坏即抛错」

    前置排查(已完成)

    1. 撞车排查:全仓 git 历史无 fsync / atomic-write / durability 相关的 storage 写侧提交;settings / mcp / credential 三个文件近期改动均为功能性。
    2. 调用方核实:createSettingsStore 生产调用仅 runtime-host-boot.ts:367,另有 e2e/fixtures.ts:178——PR2 的签名扩展为可选参数,两者均不受影响。

    PR1:写侧统一加固

    1. 新建共享工具 packages/storage/src/atomic-file-write.ts(内部模块)

    硬约束(违反会被现有守卫拦截,均已核实):

    • 不加进 package.json exports——public-entrypoints.test.ts:222-233 要求每个 published subpath 必须有包外消费者
    • 禁止 import node:sqlite——public-entrypoints.test.ts:255-270 的 SQLite 边界探测要求 settings/mcp/credential 入口的模块图不含 SQLite
    • 文件头 18 行 Apache 许可头(根 package.json check:asf-headers 强制)
    • 复用 stable-storage.ts:125 的 syncDirectory(包内相对导入,不触发 exports 守卫),不新建副本

    API(协议 = credential-store.ts:263-281 writeSecretFileAtomic 的标准,参数化三处差异):

    export interface AtomicFileWriteOptions {
      fileMode?: number;          // 默认 0o600
      dir?: 'none' | 'harden';    // none=目录逻辑由调用方自理;harden=写入前 mkdir 0700 + fail-closed chmod(credential 语义)
      dirMode?: number;           // 默认 0o700,仅 dir:'harden' 时生效
    }
    export interface AtomicFileWriteDependencies {
      open?: typeof open;         // 故障注入用,照抄 marker-file.ts:32-35 的依赖注入模式
      randomUUID?: () => string;  // 注入后 temp 路径可预测,symlink 测试依赖它
    }
    export async function writeAtomicFile(
      path: string,
      contents: string,
      options?: AtomicFileWriteOptions,
      dependencies?: AtomicFileWriteDependencies,
    ): Promise<void>;

    dir 只设两档:settings 保留自身 mkdir(workspaceRoot 是用户目录,不做 0700 harden)、mcp 保留 withUpdateLock 的 ensureDirectory,只有 credential 需要 fail-closed 目录语义——中间档没有消费者,不预设。

    chmod 策略作为文档化不变量写死在 helper JSDoc 中(这正是本 issue 要消灭的「漂移」):

    • 文件 chmod:POSIX fail-loud、win32 跳过。与 mcp 现状(mcp-config-store.ts:207-209)完全一致;与 credential 的 chmodStrict 在 POSIX 上等价,win32 差异(best-effort vs 跳过)不可观察——credential-store.test.ts 的 mode 断言全部 skip: !isPosix
    • dir 'harden':chmodStrict 语义(POSIX fail-loud;win32 best-effort),即 credential-store.ts:252-255 ensureSecretDir 的行为

    协议(顺序与 credential 现版一致):

    [dir:'harden' 时先执行 ensureSecretDir 等价逻辑] → 写 ${path}.${randomUUID()}.tmp → open('wx', fileMode) → writeFile → handle.sync() → close → chmod 文件(按上述策略)→ rename → syncDirectory(dirname) → 任一步失败:rm(temp, {force:true}).catch(() => {}) 后重抛原错误。

    顺带修掉 credential 现版的小缺陷:credential-store.ts:278 的 rm 未挂 catch,rm 失败会掩盖原始错误;统一路径以「catch 后重抛」保证原错误始终优先。

    2. 三个 store 接入与行为变化清单

    • settings-store.ts:209-214 write():保留原 mkdir(dirname, {recursive:true}),写入主体换为 writeAtomicFile(path, json, { fileMode: 0o600 })
    • mcp-config-store.ts:197-213 write():同参数调用;目录逻辑不动(ensureDirectory 继续承担);补上缺失的文件/目录 fsync 栅栏
    • credential-store.ts:263-281 writeSecretFileAtomic:ensureSecretDir 改由 helper 的 dir:'harden' 承担,写入主体改为 helper 调用;删除 :283-291 的私有 syncDirectory 副本。credential-store.test.ts 现有测试全绿即为行为保持证明

    PR1 行为变化清单(在 PR 描述中显式列出,不以「零行为变化」表述兜底):

    项 前 后 性质
    settings.json 文件 mode umask 默认(通常 0644) 0600 有意收紧:文件含明文凭据(bot appSecret/token 经 bot-onboarding-main.ts:310-320 写入;代理密码为明文字段,core/src/settings.ts:93-103)
    settings/mcp temp 命名 pid.Date.now / .mcp-uuid 统一 uuid 不可观察
    settings/mcp 写入耐久性 无 fsync 文件 + 目录 fsync 加固
    credential 写入 已有完整协议 等价;rm 失败不再掩盖原错误 等价 + 顺带修复

    3. 测试(照抄既有模式)

    新 src/tests/atomic-file-write.test.ts:

    • 故障注入:write/sync/close 各阶段失败 → 抛原错误且 readdir 无 temp 残留(照抄 marker-file.test.ts:58 起的三阶段循环)
    • mode 断言:新建 0600、预存在宽松文件回收 0600、dir:'harden' 0700(照抄 credential-store.test.ts:114-152)
    • 补包内空白:预植符号链接到 temp 路径 → wx 拒绝(posix only;win32 skip 沿用 pet-pack-store.test.ts:177-186 的惯例;预植需注入 randomUUID 使 temp 路径可预测)

    settings-store 测试补:写后 0600(posix)、无 temp 残留;损坏文件仍 reject(PR1 不动读侧,settings-store-onboarding.test.ts:309-322 的 pin 保持原样)。

    mcp-config-store 测试补:无 temp 残留;损坏 JSON reject 测试保持不变。

    新测试文件用 describe + test + import assert from 'node:assert/strict'(包内最常见组合),import 带 .js 扩展名,带许可头。

    4. 验证与提交

    npm run lint && npm run format:check && npm run typecheck && npm run build
    npm --workspace @maka/storage test   # public-entrypoints 全仓扫描 60-120s 属正常

    PR 标题:fix(storage): enforce a durability fence on JSON config store writes
    模板:Summary(引用 issue、credential-store JSDoc 标准、三档分歧表格 + 行为变化清单)/ Verification / AI use(勾选 AI 实质贡献,commit 加 Generated-by: trailer)/ Checklist;正文 Fixes #4285。

    PR2:settings 读侧损坏恢复(方案 A:备份 + 回默认 + 恢复通知)

    1. storage 侧:settings-store.ts 恢复逻辑

    工厂签名增量扩展(现有调用方 runtime-host-boot.ts:367 与 e2e/fixtures.ts:178 均不受影响):

    export interface CorruptSettingsRecovery {
      readonly backupPath: string;
    }
    export interface SettingsStoreOptions {
      onCorruptRecovery?: (recovery: CorruptSettingsRecovery) => void;
    }
    export function createSettingsStore(
      workspaceRoot: string,
      options?: SettingsStoreOptions,
    ): SettingsStore;

    readOrCreate(settings-store.ts:92-102)改造,读错误与解析错误分开处理:

    private async readOrCreate(): Promise<AppSettings> {
      let text: string;
      try {
        text = await readFile(this.settingsPath, 'utf8');
      } catch (error) {
        if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
          // 现状保留:首次运行,写默认值
          const settings = createDefaultSettings();
          await this.write(settings);
          return settings;
        }
        throw error;  // EACCES 等真实 IO 错误 fail-loud
      }
      try {
        return normalizeSettings(JSON.parse(text));
      } catch (error) {
        if (!(error instanceof SyntaxError)) throw error;
        const backupPath = `${this.settingsPath}.corrupt-${Date.now()}`;
        await rename(this.settingsPath, backupPath);       // 原字节完整保留
        await chmod(backupPath, 0o600).catch(() => {});    // 收紧备份权限,见边界说明
        const settings = createDefaultSettings();
        await this.write(settings);                        // 走 PR1 加固后的写入
        try {
          this.onCorruptRecovery?.({ backupPath });        // 通知失败不拖垮启动
        } catch { /* 回调异常吞掉并继续 */ }
        return settings;
      }
    }

    (错误判型沿用文件内现有强转风格;包内没有 isNodeError 一类 helper,不为此新造。)

    边界处理:

    • normalizeSettings 永不抛错(coerce-to-default,core/src/settings.ts:848),SyntaxError 是唯一的损坏信号,无需覆盖结构校验
    • 备份 rename 失败(如权限)→ 重抛原 SyntaxError,不把状况弄得更糟
    • 备份权限:rename 保留原文件 mode,旧版写入的 settings.json 是 0644(正是本 issue 的安全发现之一),而备份含明文凭据、通知文案还会引导用户去备份找回凭据——故 rename 后对备份补一次 best-effort 的 chmod 0600;失败不阻断恢复(此时权限不比损坏前更差)
    • 回调在默认值成功落盘后调用;回调内部异常吞掉并继续
    • 恢复发生在 withQueue 串行段内,天然无并发问题;同进程二次 get() 走正常读路径(get() 每次都 readFile,无缓存)

    2. desktop 侧:注册恢复通知

    • runtime-host-boot.ts:367 改为传入回调:
      createSettingsStore(workspaceRoot, { onCorruptRecovery: ({ backupPath }) => showSettingsRecoveryNotification(backupPath) })
    • 新增通知实现(apps/desktop/src/main,Electron Notification,参考 notifications-ipc-main.ts 现有模式):
      • 标题:「设置已重置」
      • 正文:「设置文件损坏,已恢复为默认设置。原文件备份在 {backupPath};机器人凭据、代理密码等可从备份中找回。」
      • E2E isolated 模式下跳过(沿用 main.ts:169 的 isIsolatedE2e 守卫模式)

    3. 测试更新

    改写 settings-store-onboarding.test.ts:309-322(现 pin「损坏即抛错且字节不动」)为新语义:

    • 原损坏字节完整保留在 .corrupt-<ts> 备份文件
    • get() 返回默认设置且 settings.json 已是合法默认内容
    • 备份文件为 0600(posix)
    • onCorruptRecovery 回调收到正确 backupPath
    • 未传回调时恢复照常(可选参数不强制)
    • 恢复后二次 get() 直接读文件(幂等)
    • EACCES 等非 SyntaxError 路径仍 rethrow 的负向测试

    4. PR 描述要点(预先列好,防止遗漏)

    • 引用 docs/architecture/mcp-runtime-architecture-draft.zh-CN.md:102 说明为何 mcp.json 读侧明确不做恢复(must-reject malformed JSON 是文档化设计决策,且被测试 pin)——settings 与 mcp 的不对称是刻意而非遗漏
    • 主动点名隐私回退:privacy.incognitoActive 若损坏前为 true,恢复后回默认 false(core/src/settings.ts:1000)——唯一一处「回退方向对用户不利」的字段,通知文案已让用户知情
    • 影响面边界:重置仅限应用偏好层,会话数据 / credentials.json / mcp.json / runtime policy 均为独立文件不受影响;原字节保留在备份中可手工找回凭据
    • 备份权限收紧:0644 遗留文件恢复后,备份不再 world-readable
    • PR 标题:fix(storage): recover from a corrupted settings.json with backup and notification
    • 同样填 AI use + Generated-by: trailer;正文 Refs #4285(PR1 已带 Fixes,issue 在 PR1 合并时关闭,本 PR 用 Refs)

    5. 验证

    npm run lint && npm run format:check && npm run typecheck && npm run build
    npm --workspace @maka/storage test
    npx knip --workspace apps/desktop   # desktop 在 knip 范围内

    (apps/desktop 无 test script,已核实;desktop 侧行为由 E2E 覆盖,通知在 isolated 模式下有跳过守卫。)

    执行顺序与依赖

    1. PR1 先行;PR2 依赖 PR1 的 writeAtomicFile(恢复写入走加固路径),串行开发
    2. 两者共用本 issue;PR1 Fixes,PR2 Refs
    3. 每个 PR 独立可回滚:PR1 回滚只损失加固;PR2 回滚恢复「损坏即抛错」现状

    明确不做(后续 issue 素材,不塞进本 PR)

    • document-io / memory-bundle-io / marker-file / encrypted-file-managed-secret-store / sqlite-context-offload-store 等近亲原子写实现的收编
    • settings-store 跨进程写保护(当前仅 desktop 单实例写入,无实际并发方)
    • 通知点击定位备份文件、或「从备份部分恢复字段」(如只找回 botChat 段)的增强交互
  4. chinawch007 commented on Sep 4, 2026

    @chinawch007
    ContributorAuthor

    Implementation note for PR #4505:

    The shared writer in PR #4505 is intentionally scoped to the three legacy
    JSON config stores named in this issue: settings.json, mcp.json, and
    credentials.json.

    It does not replace marker-file publication, whose create path uses link()
    and a pre-publication hook, or the Runtime Policy document writer, which
    owns bounded serialization, typed commit-outcome errors, and stale-temp
    recovery.

    The PR establishes the strongest write ordering available through the
    current Node filesystem APIs. It does not claim platform-uniform power-loss
    durability: Linux remains conditional on the filesystem/hardware fsync
    contract, macOS FileHandle.sync() is not F_FULLFSYNC, and Windows has no
    POSIX-equivalent parent-directory synchronization through Node.

    The read-side corrupt-document recovery remains the planned follow-up.

  5. 42 remaining items

  6. added a commit that references this issue on Sep 27, 2026
    14c0d76
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions