Repository navigation
refactor(snapshot): persist gitdir config in one atomic write instead of eight git config spawns - #876
Conversation
…eight git config spawns Refs #872
|
Hey! Your PR title Please update it to start with one of:
Where See CONTRIBUTING.md for details. |
| const configure = Effect.fnUntraced(function* (gitdir: string) { | ||
| const file = path.join(gitdir, "config") | ||
| yield* Effect.gen(function* () { | ||
| const info = yield* fs.stat(file) |
There was a problem hiding this comment.
SUGGESTION: TOCTOU race between config read and overwrite
fs.stat/fs.readFileString read the previous config, then fs.rename(tmp, file) overwrites it. Concurrent modification between read and rename could be lost. Runs once per fresh gitdir under an in-memory lock, so cross-process risk is low but real.
| yield* Effect.gen(function* () { | ||
| const info = yield* fs.stat(file) | ||
| const previous = yield* fs.readFileString(file) | ||
| const tmp = `${file}.tmp-${process.pid}` |
There was a problem hiding this comment.
SUGGESTION: tmp filename uses only process.pid — collision risk
${file}.tmp-${process.pid} is not unique across concurrent calls for the same gitdir or across processes. Currently protected by the locked semaphore in track, but a future refactor or direct call could race, causing the second rename to clobber the first. Consider adding a random suffix.
| const info = yield* fs.stat(file) | ||
| const previous = yield* fs.readFileString(file) | ||
| const tmp = `${file}.tmp-${process.pid}` | ||
| yield* fs.writeFileString(tmp, previous + SNAPSHOT_CONFIG_APPEND) |
There was a problem hiding this comment.
SUGGESTION: orphaned tmp file if rename fails after write succeeds
fs.writeFileString(tmp, ...) creates the tmp file, but if fs.rename(tmp, file) subsequently fails, the .tmp-${process.pid} file is left behind in the gitdir with no cleanup.
| const before = yield* snapshot.track() | ||
| expect(before).toBeTruthy() | ||
| const config = yield* Effect.promise(async () => { | ||
| const root = path.join(Global.Path.data, "snapshot") |
There was a problem hiding this comment.
SUGGESTION: test walks entire snapshot root tree
The test recursively walks Global.Path.data/snapshot looking for config files and expects exactly one match. In environments with many snapshot gitdirs (CI, parallel test runs), this could be slow or flaky. Consider narrowing the search to the known gitdir path.
Code Review SummaryStatus: 2 Issues Found | Recommendation: Address before merge Overview
Issue Details (click to expand)SUGGESTION
Files Reviewed (2 files)
Fix these issues in Kilo Cloud Previous Review Summaries (3 snapshots, latest commit 95c742a)Current summary above is authoritative. Previous snapshots are kept for context only. Previous review (commit 95c742a)Status: 4 Issues Found | Recommendation: Address before merge Overview
Issue Details (click to expand)SUGGESTION
Files Reviewed (2 files)
Fix these issues in Kilo Cloud Previous review (commit 920ff73)Status: 4 Issues Found | Recommendation: Address before merge Overview
Issue Details (click to expand)SUGGESTION
Files Reviewed (2 files)
Fix these issues in Kilo Cloud Previous review (commit 708739c)Status: 4 Issues Found | Recommendation: Address before merge Overview
Issue Details (click to expand)SUGGESTION
Files Reviewed (2 files)
Reviewed by free · Input: 41.3K · Output: 3.6K · Cached: 211.1K |
… config Review findings on #876: git init writes core.symlinks=false on Windows, leaving a duplicated key after the append (later plain git config set fails, exit 5). Strip the eight appended keys from the existing config first, and narrow the header comment: the block intentionally wins over include.path and the write bypasses config.lock; both are inert for a private gitdir whose only writer is this module.
Second-round review on #876: the regex strip could corrupt valid config syntax (orphaned continuation lines) and removed keys from quoted subsections. Replace it with append-only write (which cannot corrupt) plus duplicate collapse driven by git's own parser: one 'git config --local --list -z' to find multiply-assigned tuning keys and one 'git config --local --replace-all' per duplicate. Worst tolerated failure leaves a duplicate key (correct reads, last wins), never a broken file.
…tes on includes Third-round review on #876: a config ending in an unterminated continuation swallowed the appended section header, silently mutating the previous value (reproduced). Normalize the existing content to end with a newline so the continuation consumes only the empty line the append starts with; regression test covers it against real git. Include directives (include.path/includeIf.*) or an unparsable config now keep the original eight git config spawns, preserving git's own include precedence and tolerated failures exactly. Detected via git config --local --get-regexp ^include (1 = none, 0 = present, >1 = parse error). Also addresses Kilo review: unique tmp suffix per configure call and orphaned tmp cleanup on rename failure.
Issue for this PR
Refs #872 — reduces snapshot test/setup cost; it does not claim to resolve the slow-suite root cause.
Type of change
What does this PR do?
Snapshot.track()on a fresh gitdir ran eight separategit configsubprocess spawns on every init (src/snapshot/index.ts): core.autocrlf, core.longpaths, core.symlinks, core.fsmonitor, core.untrackedCache, feature.manyFiles, index.version, index.threads. The gitdir is keyed by worktree hash, so every new worktree pays this in production, and every{ git: true }snapshot test pays it per test (56 tests, ~12-14 git spawns each on first track).Evaluation of alternatives:
git configsets one key per invocation (no supported batched persistent set), andGIT_CONFIG_*env vars and-cflags are ephemeral per command, so there is no supported Git batching mechanism for equivalent persistent values. The replacement has two paths, chosen per gitdir:include.path/includeIf.*) or git cannot parse it (detected viagit config --local --get-regexp ^include: exit 0 = present, 1 = none, >1 = parse error): the original eightgit config <key> <value>spawns run unchanged, preserving git's own include precedence and tolerated-failure behavior exactly.git initwritescore.symlinks=false) are collapsed via git itself: onegit config --local --list -zfinds multiply-assigned tuning keys, onegit config --local --replace-allper duplicate rewrites them with git's own parser. No config-file syntax is parsed by this code, so it cannot corrupt the file: the worst tolerated outcome is a leftover duplicate key (reads stay correct, last assignment wins). Cost: 2 config spawns on the default path, 3 on Windows-init default.The write bypasses git's
config.lockprotocol; this module is the only writer of the file,track()serializes access per gitdir, and a cross-process race converges to the same appended block. Every snapshot git call also passes the core values as-cflags, so this file only carries performance tuning. Failures degrade to the same tolerated behavior as the previous unchecked spawns (git init defaults remain valid), now with a logged warning.No workflow changes. Saves ~6 subprocess spawns per fresh gitdir in both production and tests on the default path.
Honesty note: the motivation is #872's Windows suite cost — Windows snapshot tests show ~15-20 git spawns per test at an inferred ~150-200ms per spawn. The per-spawn cost and the resulting time saving are unmeasured hypotheses (no Windows host available locally); the spawn elimination itself is the proven part.
Independent review disposition
Round 1 (54ac465): F1 duplicate key → fixed (round 2); F2 comment overclaim → fixed; F3 config.lock bypass → assessed, documented (sole writer, per-gitdir serialization, converging race); F4 no rename retry → accepted residual (same tolerated-failure envelope as the old unchecked spawns, now with a warning; tuning-only loss); F5 utf8/fsync/orphan tmp → accepted (fresh init configs are ASCII); F6 no config-content test → fixed (
fresh gitdir persists the snapshot tuning config).Round 2 (920ff73): regex strip could corrupt valid config (orphaned continuation) and mishandled subsections/bare keys → strip removed entirely; append-only write (cannot corrupt) + git-driven dedupe via
--list -z/--replace-all; regression testduplicatedSnapshotConfigKeys finds only multiply-assigned tuning keyscovers bare keys, continuations, quoted values with embedded newlines, quoted subsections (index.x.version≠index.version), unrelated keys.Round 3 (95c742a):
val\with and without trailing newline): pre-existing value preserved, block parses under[core], all keys effective. Committed regression testjoinSnapshotConfig preserves a trailing unterminated continuationasserts value preservation, all eight keys in correct sections, and clean parse via real git.include.pathand false-conditionincludeIfboth detected (exit 0), clean config exits 1, unparsable config exits 128 → fallback.core.symlinksvalue, reviewer's exit-5 repro succeeds, init keys preserved, parse clean.Kilo review reconciliation (head 95c742a)
locked()semaphore; this module is the sole writer; a cross-process race converges to the identical appended block. Deliberate tradeoff (no config.lock protocol), documented in the header comment.tmp-<pid>-<counter>).XDG_DATA_HOMEis pid-scoped bytest/preload.tsand deleted after the suite, so the walk only ever sees this process's gitdirs (bounded, no cross-process flakiness).How did you verify your code works?
git --git-dir <dir> config --local --listoutput is identical between the old code (eight spawns) and this patch — same 13 keys, same values, only the per-test worktree path differs. Init-generated keys are preserved.bun test test/snapshot/snapshot.test.ts— 58 pass, 1 pre-existing skip, 0 fail on Bun 1.3.14 (same as CI), including the three new tests.tsc --noEmitcould not complete on the 2 GB dev box (V8 heap OOM); typecheck is covered by the CI typecheck job on this head.Screenshots / recordings
N/A.
Checklist