Skip to content

refactor(snapshot): persist gitdir config in one atomic write instead of eight git config spawns - #876

Merged
agenteinstinct1-max merged 5 commits into
dev-vibecodedfrom
fix/snapshot-config-spawns-872
Nov 28, 2026
Merged

agenteinstinct1-max merged 5 commits into
dev-vibecodedfrom
fix/snapshot-config-spawns-872

Conversation

@agenteinstinct1-max

@agenteinstinct1-max agenteinstinct1-max commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • Refactor / code improvement

What does this PR do?

Snapshot.track() on a fresh gitdir ran eight separate git config subprocess 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 config sets one key per invocation (no supported batched persistent set), and GIT_CONFIG_* env vars and -c flags are ephemeral per command, so there is no supported Git batching mechanism for equivalent persistent values. The replacement has two paths, chosen per gitdir:

  • Config carries include directives (include.path/includeIf.*) or git cannot parse it (detected via git config --local --get-regexp ^include: exit 0 = present, 1 = none, >1 = parse error): the original eight git config <key> <value> spawns run unchanged, preserving git's own include precedence and tolerated-failure behavior exactly.
  • Otherwise: the eight values are appended in one atomic write (existing content normalized to end with a newline, then tmp file + rename), and any pre-existing assignments of the same keys (Windows git init writes core.symlinks=false) are collapsed via git itself: one git config --local --list -z finds multiply-assigned tuning keys, one git config --local --replace-all per 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.lock protocol; 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 -c flags, 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 test duplicatedSnapshotConfigKeys finds only multiply-assigned tuning keys covers bare keys, continuations, quoted values with embedded newlines, quoted subsections (index.x.version ≠ index.version), unrelated keys.

Round 3 (95c742a):

  • Terminal continuation swallows appended header (blocking, reproduced): fixed by normalizing existing content to end with a newline — the continuation then consumes only the empty line the append starts with. Verified against real git 2.34.1 in both forms (val\ with and without trailing newline): pre-existing value preserved, block parses under [core], all keys effective. Committed regression test joinSnapshotConfig preserves a trailing unterminated continuation asserts value preservation, all eight keys in correct sections, and clean parse via real git.
  • Include precedence divergence: fixed by fallback, not by documentation. Configs with include directives keep the original eight-spawn git-owned path; the append path only runs when no include directives exist, where no precedence divergence can occur. Detection verified against real git: include.path and false-condition includeIf both detected (exit 0), clean config exits 1, unparsable config exits 128 → fallback.
  • Empirical dedupe evidence (round 2) re-verified on this design: Windows-init-like config collapses to a single core.symlinks value, reviewer's exit-5 repro succeeds, init keys preserved, parse clean.

Kilo review reconciliation (head 95c742a)

  1. TOCTOU read/rename: rebutted with scope — fresh gitdir created by init inside the per-gitdir 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.
  2. tmp name pid-only: fixed — per-call counter suffix added (tmp-<pid>-<counter>).
  3. Orphaned tmp on rename failure: fixed — failed rename now attempts tmp cleanup (ignored on error).
  4. Config-content test walks snapshot root: rebutted with evidence — the test process's XDG_DATA_HOME is pid-scoped by test/preload.ts and 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?

  • Config equivalence (real code path): git --git-dir <dir> config --local --list output 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.
  • Duplicate-key collapse and terminal-continuation safety: see rounds 2-3 above (real git 2.34.1).
  • Include detection: see round 3 above (real git exit-code matrix).
  • Full suite: 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.
  • Types: local tsc --noEmit could 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

  • I have tested my changes locally
  • I have not included unrelated changes in this PR

@github-actions

Copy link
Copy Markdown

Hey! Your PR title perf(snapshot): persist gitdir config in one atomic write instead of eight git config spawns doesn't follow conventional commit format.

Please update it to start with one of:

  • feat: or feat(scope): new feature
  • fix: or fix(scope): bug fix
  • docs: or docs(scope): documentation changes
  • chore: or chore(scope): maintenance tasks
  • refactor: or refactor(scope): code refactoring
  • test: or test(scope): adding or updating tests

Where scope is the package name (e.g., app, desktop, opencode).

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread packages/opencode/src/snapshot/index.ts Outdated
yield* Effect.gen(function* () {
const info = yield* fs.stat(file)
const previous = yield* fs.readFileString(file)
const tmp = `${file}.tmp-${process.pid}`

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread packages/opencode/src/snapshot/index.ts Outdated
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

@kilo-code-bot

kilo-code-bot Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Code Review Summary

Status: 2 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 2
Issue Details (click to expand)

SUGGESTION

File Line Issue
packages/opencode/src/snapshot/index.ts 405 TOCTOU race between config read and overwrite
packages/opencode/test/snapshot/snapshot.test.ts 176 test walks entire snapshot root tree
Files Reviewed (2 files)
  • packages/opencode/src/snapshot/index.ts - 1 issue
  • packages/opencode/test/snapshot/snapshot.test.ts - 1 issue

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

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 4
Issue Details (click to expand)

SUGGESTION

File Line Issue
packages/opencode/src/snapshot/index.ts 383 TOCTOU race between config read and overwrite
packages/opencode/src/snapshot/index.ts 385 tmp filename uses only process.pid — collision risk
packages/opencode/src/snapshot/index.ts 386 orphaned tmp file if rename fails after write succeeds
packages/opencode/test/snapshot/snapshot.test.ts 175 test walks entire snapshot root tree
Files Reviewed (2 files)
  • packages/opencode/src/snapshot/index.ts - 3 issues
  • packages/opencode/test/snapshot/snapshot.test.ts - 1 issue

Fix these issues in Kilo Cloud

Previous review (commit 920ff73)

Status: 4 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 4
Issue Details (click to expand)

SUGGESTION

File Line Issue
packages/opencode/src/snapshot/index.ts 383 TOCTOU race between config read and overwrite
packages/opencode/src/snapshot/index.ts 385 tmp filename uses only process.pid — collision risk
packages/opencode/src/snapshot/index.ts 386 orphaned tmp file if rename fails after write succeeds
packages/opencode/test/snapshot/snapshot.test.ts 175 test walks entire snapshot root tree
Files Reviewed (2 files)
  • packages/opencode/src/snapshot/index.ts - 3 issues
  • packages/opencode/test/snapshot/snapshot.test.ts - 1 issue

Fix these issues in Kilo Cloud

Previous review (commit 708739c)

Status: 4 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 4
Issue Details (click to expand)

SUGGESTION

File Line Issue
packages/opencode/src/snapshot/index.ts 345 TOCTOU race between config read and overwrite
packages/opencode/src/snapshot/index.ts 347 tmp filename uses only process.pid — collision risk
packages/opencode/src/snapshot/index.ts 348 orphaned tmp file if rename fails after write succeeds
packages/opencode/test/snapshot/snapshot.test.ts 175 test walks entire snapshot root tree
Files Reviewed (2 files)
  • packages/opencode/src/snapshot/index.ts - 3 issues
  • packages/opencode/test/snapshot/snapshot.test.ts - 1 issue

Fix these issues in Kilo Cloud


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.
@agenteinstinct1-max agenteinstinct1-max changed the title perf(snapshot): persist gitdir config in one atomic write instead of eight git config spawns refactor(snapshot): persist gitdir config in one atomic write instead of eight git config spawns Nov 28, 2026
@agenteinstinct1-max
agenteinstinct1-max merged commit 2a13600 into dev-vibecoded Nov 28, 2026
10 checks passed
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