Skip to content

fix(kimi): don't crash if config.toml is deleted mid-write - #23293

Merged
nwparker merged 2 commits into
mainfrom
nwparker/kimi-statsync-race
Sep 27, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/kimi-statsync-race

Conversation

@nwparker

@nwparker nwparker commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​91 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​91
Prod 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​9 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​8

ELI5

Orca writes a small hook config file for the Kimi CLI agent. Right before writing it, Orca peeks at the file's current permissions so it can keep them unchanged. If something deletes that file in the split second between "does it exist?" and "read its permissions," Orca was crashing instead of just writing a fresh file.

What Changed

writeConfigToml in src/main/kimi/hook-service.ts checks existsSync(configPath) and then calls statSync(configPath) to read the file's current permission bits so the rewrite preserves them. Nothing handled the case where the file disappears in between those two calls (e.g. a concurrent uninstall, or the user deleting ~/.kimi-code/config.toml by hand) — statSync throws ENOENT, and that throw was outside any try, so it escaped uncaught out of install()/getStatus().

Before: config file deleted mid-write → uncaught exception.
After: config file deleted mid-write → falls back to the same default 0o600 mode used for a brand-new file, and the write proceeds normally. Any other stat failure (e.g. an unreadable file) still throws, same as before — this fix only recognizes the file's-already-gone case.

Why

The minimal fix is to catch the statSync error at the exact point it can now fail, and only swallow it when the failure means "the file is gone" (ENOENT). This keeps the existing deliberate behavior for other stat failures — there's already a test (hook-service-mode-read-failure.test.ts) documenting that Orca intentionally aborts rather than risk silently dropping permissions when it truly cannot determine the current mode. Widening the catch to swallow all errors would have broken that safety property; narrowing it to just the race condition preserves it while closing the crash.

Linked Issue

Found during a production release scan (introduced by #22422, "Preserve Kimi config permissions"); no separate tracking issue was filed.

Visual Proof

N/A — backend-only fix, no UI change.

Testing

  • Automated tests added/updated, or explained why not below

Added src/main/kimi/hook-service-config-delete-race.test.ts, which mocks node:fs's statSync to throw ENOENT for the config path (simulating the delete race) and asserts install() no longer throws and still writes a working config.

Before the fix: test fails with AssertionError: expected [Function] to not throw an error but 'Error: ENOENT: no such file or directory, stat' was thrown.
After the fix: test passes.

Ran the full Kimi hook-service suite (new test + hook-service.test.ts + hook-service-mode-read-failure.test.ts): 3 files, 7 tests, all passing. Also ran pnpm tc:node (clean) and pnpm run check:code-quality:changed (clean, 0 new findings).

This is a filesystem race, not platform-specific, so no separate OS verification was needed. Confirmed there's no separate Windows ACL-preserving code path in this function — chmodSync/statSync mode bits are applied the same way on every platform here, so the fix behaves identically on Windows.

AI Disclosure

Written by an Anthropic Claude agent (Claude Code) as part of an automated production-release scan follow-up. Reviewed and verified by the human author before opening.

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Ensure no issues in: Security, Cross-platoform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

writeConfigToml checked existsSync(configPath) then called statSync(configPath)
to preserve the file's mode, with no error handling in between. If the file
was deleted in that window (e.g. a concurrent uninstall), statSync threw
ENOENT and the exception escaped install()/getStatus() uncaught.

Now a missing-file stat during that race is treated the same as a missing
file at the check: fall back to the default 0o600 mode and continue the
write. Any other stat error still throws, preserving the existing
mode-read-failure behavior.
@coderabbitai

coderabbitai Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: dc00aa7f-95de-44f6-b17f-6dd593524edf

📥 Commits

Reviewing files that changed from the base of the PR and between 994e728 and 16ed326.

📒 Files selected for processing (2)
  • src/main/kimi/hook-service-config-delete-race.test.ts
  • src/main/kimi/hook-service.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.


📝 Walkthrough

Walkthrough

When statSync fails after the config existence check, writeConfigToml now uses isDefinitiveAbsence to decide whether to ignore the error. It rethrows errors that are not classified as definitive absence. The regression test simulates ENOENT and ENOTDIR and checks that installation completes with every KIMI_HOOK_EVENTS event in the config.

Priority: ⬇️ Low

Merge Risk: 🔵 Low · up to 16ed3

The changed error-handling path is exercised, but the regression test does not verify the deleted-file outcome or default permissions. The remaining risk is limited to test coverage.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary fix: preventing crashes when Kimi's config.toml is deleted during a write.
Description check ✅ Passed The description is detailed and covers the ELI5 explanation, behavior change, rationale, testing, AI disclosure, scope, and checklist. The Linked Issue section has no issue number, and the Review sect…
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 2 files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/main/kimi/hook-service-config-delete-race.test.ts (1)

16-17: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Delete the fixture before simulating the race.

The mocked statSync throws ENOENT, but the config file remains. The later existsSync(configPath) check therefore still sees the file and exercises the backup path. Unlink the file before throwing, then assert that installation recreates it with mode 0o600.

Suggested test fix
     if (typeof target === 'string' && target === deleteRace.path) {
+      actual.unlinkSync(target)
       throw Object.assign(new Error('ENOENT: no such file or directory, stat'), { code: 'ENOENT' })
     }
...
     const config = fs.readFileSync(configPath(), 'utf-8')
+    expect(fs.statSync(configPath()).mode & 0o777).toBe(0o600)
     for (const event of KIMI_HOOK_EVENTS) {

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 8db41468-eb31-4f9d-9351-e214f9907b17

📥 Commits

Reviewing files that changed from the base of the PR and between 46907de and 994e728.

📒 Files selected for processing (2)
  • src/main/kimi/hook-service-config-delete-race.test.ts
  • src/main/kimi/hook-service.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — one minor reuse suggestion inline.

Reviewed changes

  • Guarded the mode-preservation statSync — writeConfigToml now try/catches the permission read and only swallows the error when the file is gone, falling back to the existing 0o600 default instead of letting ENOENT escape install()/getStatus().
  • Delete-race regression test — hook-service-config-delete-race.test.ts mocks node:fs's statSync to throw ENOENT for the config path and asserts install() writes a complete config. Since install() is synchronous, the test genuinely fails against the unfixed code.

The fix is correct and well scoped: it closes exactly the window #22422 opened while preserving the deliberate abort-on-unreadable behavior covered by hook-service-mode-read-failure.test.ts (hook-service.ts:157 rethrows anything that is not ENOENT). No security, cross-platform, SSH, or mobile exposure — this is a local POSIX/Windows filesystem read with no ACL-specific branch.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/kimi/hook-service.ts Resolved
Reuse the repo's canonical absence check instead of a hand-rolled ENOENT
comparison, per review feedback on #23293. isDefinitiveAbsence also covers
ENOTDIR (an ancestor directory replaced by a file), which the inline check
missed but is equally "the config is definitively not there."

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes (delta since prior pullfrog review)

  • Adopted the canonical absence predicate — writeConfigToml now gates its rethrow on isDefinitiveAbsence(error) instead of an inline code !== 'ENOENT', so the ENOENT/ENOTDIR allowlist lives in src/shared/definitive-filesystem-absence.ts rather than being re-derived here.
  • Broadened the regression test — the delete-race test is parameterised over it.each(['ENOENT', 'ENOTDIR']), and the mocked statSync now throws whichever code the case supplies; the ENOTDIR arm would fail against the original inline check.

The prior reuse suggestion is fully addressed, and the widened predicate has no new blast radius: an ENOTDIR at the mode stat means a path component of config.toml is not a directory, so the subsequent temp write in the same dir fails on its own with a real error rather than being masked. ENOTDIR is also a legitimate "nothing to preserve" case. Tests pass locally (hook-service-config-delete-race.test.ts + hook-service-mode-read-failure.test.ts, 3 tests).

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit 98cfdc8 into main Sep 27, 2026
40 checks passed
@nwparker
nwparker deleted the nwparker/kimi-statsync-race branch September 27, 2026 03:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant