follow-up: Stateful Sense 持久化加固 (RFC #308) #313

Closed
opened 2026-05-01 11:55:51 +00:00 by xiaoju · 0 comments
Owner

来源

PR #312 code review 中的非阻塞建议,需要 follow-up 修复。

待办

1. writeState 原子写入(防 crash 损坏)

当前 writeFileSync 直接写目标文件,如果写入过程中 crash 会导致 state.json 损坏。

修复: 改为 write-temp + rename:

function writeState(statePath: string, state: unknown): void {
  const tmp = statePath + ".tmp";
  writeFileSync(tmp, JSON.stringify(state, null, 2));
  renameSync(tmp, statePath);
}

2. readState 错误处理

当前 readState 静默吞掉所有错误(包括 JSON 解析失败)。应区分「文件不存在」和「文件损坏」:

  • 文件不存在 → 正常,返回 initialState
  • JSON 解析失败 → 记录警告,返回 initialState(但不要完全静默)

3. State 内存更新时序

当前 executeCompute 先更新 runtime.state = result.state,再 writeState。如果写盘失败,内存 state 已变但磁盘未同步。

修复: 先写盘成功,再更新内存:

writeState(runtime.statePath, result.state);
runtime.state = result.state;  // only after disk success

4. SenseInfo.triggers 类型加固

triggers: string[] 改为 triggers: ReadonlyArray<string>,防止外部误修改。

5. JSON state 持久化文档

在 CLAUDE.md 或 docs/ 补充一段说明 Sense state 持久化的机制:

  • 文件路径: data/senses/<name>.json
  • 读取时机: worker 启动
  • 写入时机: 每次 compute 成功后
  • 初始状态: initialState export

优先级

中 — 不影响功能但影响可靠性

Ref: #308

## 来源 PR #312 code review 中的非阻塞建议,需要 follow-up 修复。 ## 待办 ### 1. writeState 原子写入(防 crash 损坏) 当前 `writeFileSync` 直接写目标文件,如果写入过程中 crash 会导致 state.json 损坏。 **修复:** 改为 write-temp + rename: ```typescript function writeState(statePath: string, state: unknown): void { const tmp = statePath + ".tmp"; writeFileSync(tmp, JSON.stringify(state, null, 2)); renameSync(tmp, statePath); } ``` ### 2. readState 错误处理 当前 `readState` 静默吞掉所有错误(包括 JSON 解析失败)。应区分「文件不存在」和「文件损坏」: - 文件不存在 → 正常,返回 initialState - JSON 解析失败 → 记录警告,返回 initialState(但不要完全静默) ### 3. State 内存更新时序 当前 `executeCompute` 先更新 `runtime.state = result.state`,再 `writeState`。如果写盘失败,内存 state 已变但磁盘未同步。 **修复:** 先写盘成功,再更新内存: ```typescript writeState(runtime.statePath, result.state); runtime.state = result.state; // only after disk success ``` ### 4. SenseInfo.triggers 类型加固 `triggers: string[]` 改为 `triggers: ReadonlyArray<string>`,防止外部误修改。 ### 5. JSON state 持久化文档 在 CLAUDE.md 或 docs/ 补充一段说明 Sense state 持久化的机制: - 文件路径: `data/senses/<name>.json` - 读取时机: worker 启动 - 写入时机: 每次 compute 成功后 - 初始状态: `initialState` export ## 优先级 中 — 不影响功能但影响可靠性 Ref: #308
This repo is archived. You cannot comment on issues.
No Label
1 Participants
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: uncaged/nerve#313