Skip to content

Commit aaa7275

Browse files
navidnadaliclaude
andcommitted
fix(server): a git config snapshot answers only for its own environment
Git commands now run with HostProcess.Environment, which a caller can override, instead of process.env. The snapshot still keyed its environment on process.env, so a read under one environment could be answered from a snapshot loaded under another, such as one with a different GIT_CONFIG_GLOBAL. Snapshots are now kept per directory and config environment, read from HostProcess.Environment in the reading fiber. A load runs Git in the environment of the read that started it and checks that it matches the key. Two environments reading the same repository each keep their own snapshot instead of reloading each other's. The tests set their environment through HostProcess.Environment instead of process.env. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 5e85d6f commit aaa7275

2 files changed

Lines changed: 122 additions & 94 deletions

File tree

‎apps/server/src/vcs/GitVcsDriverCore.test.ts‎

Lines changed: 86 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -449,11 +449,16 @@ describe("config reads", () => {
449449
type TestError = GitCommandError | PlatformError.PlatformError;
450450
interface ConfigChange {
451451
readonly name: string;
452-
// Prepares the repository at `cwd` and returns the directory to read from.
453-
readonly setup: (cwd: string) => Effect.Effect<string, TestError, Scope.Scope | TestServices>;
452+
// Prepares the repository at `cwd` and returns the directory to read from. `env` is the
453+
// environment the test runs Git in, which setup and change may extend.
454+
readonly setup: (
455+
cwd: string,
456+
env: NodeJS.ProcessEnv,
457+
) => Effect.Effect<string, TestError, Scope.Scope | TestServices>;
454458
readonly change: (
455459
cwd: string,
456460
readCwd: string,
461+
env: NodeJS.ProcessEnv,
457462
) => Effect.Effect<void, TestError, Scope.Scope | TestServices>;
458463
readonly read: (
459464
driver: GitVcsDriver.GitVcsDriver["Service"],
@@ -468,39 +473,26 @@ describe("config reads", () => {
468473
driver.readConfigValue(cwd, key);
469474
const readPrimaryRemote = (driver: GitVcsDriver.GitVcsDriver["Service"], cwd: string) =>
470475
driver.resolvePrimaryRemoteName(cwd).pipe(Effect.orElseSucceed(() => null));
471-
const setEnv = (name: string, value: string) =>
476+
// An empty safe.directory drops any configured exception, so Git checks owners.
477+
const trustNoOtherOwner = (env: NodeJS.ProcessEnv) =>
478+
Effect.sync(() => {
479+
Object.assign(env, {
480+
GIT_CONFIG_COUNT: "1",
481+
GIT_CONFIG_KEY_0: "safe.directory",
482+
GIT_CONFIG_VALUE_0: "",
483+
});
484+
});
485+
const changeOwner = (env: NodeJS.ProcessEnv) => (file: string) =>
472486
Effect.acquireRelease(
473487
Effect.sync(() => {
474-
const previous = process.env[name];
475-
process.env[name] = value;
476-
return previous;
488+
statOwner.path = file;
489+
env.GIT_TEST_ASSUME_DIFFERENT_OWNER = "1";
477490
}),
478-
(previous) =>
491+
() =>
479492
Effect.sync(() => {
480-
if (previous === undefined) Reflect.deleteProperty(process.env, name);
481-
else process.env[name] = previous;
493+
statOwner.path = null;
482494
}),
483495
);
484-
const setGlobalConfig = (file: string) => setEnv("GIT_CONFIG_GLOBAL", file);
485-
// An empty safe.directory drops any configured exception, so Git checks owners.
486-
const trustNoOtherOwner = Effect.all([
487-
setEnv("GIT_CONFIG_COUNT", "1"),
488-
setEnv("GIT_CONFIG_KEY_0", "safe.directory"),
489-
setEnv("GIT_CONFIG_VALUE_0", ""),
490-
]);
491-
const changeOwner = (file: string) =>
492-
Effect.all([
493-
Effect.acquireRelease(
494-
Effect.sync(() => {
495-
statOwner.path = file;
496-
}),
497-
() =>
498-
Effect.sync(() => {
499-
statOwner.path = null;
500-
}),
501-
),
502-
setEnv("GIT_TEST_ASSUME_DIFFERENT_OWNER", "1"),
503-
]).pipe(Effect.asVoid);
504496
const writeInclude = (file: string, value: string) =>
505497
Effect.sync(() => NodeFS.writeFileSync(file, `[t3]\n\tvalue = ${value}\n`));
506498
const changes: ReadonlyArray<ConfigChange> = [
@@ -596,14 +588,14 @@ describe("config reads", () => {
596588
},
597589
{
598590
name: "an edit to the global config",
599-
setup: (cwd) =>
591+
setup: (cwd, env) =>
600592
Effect.gen(function* () {
601593
const global = NodePath.join(yield* makeTmpDir("git-global-"), "gitconfig");
602594
yield* writeInclude(global, "first");
603-
yield* setGlobalConfig(global);
595+
env.GIT_CONFIG_GLOBAL = global;
604596
return cwd;
605597
}),
606-
change: () => writeInclude(process.env.GIT_CONFIG_GLOBAL!, "second"),
598+
change: (_cwd, _readCwd, env) => writeInclude(env.GIT_CONFIG_GLOBAL!, "second"),
607599
read: readValue("t3.value"),
608600
before: "first",
609601
after: "second",
@@ -679,32 +671,32 @@ describe("config reads", () => {
679671
}))),
680672
{
681673
name: "a new owner of the top level above the directory read from",
682-
setup: (cwd) =>
674+
setup: (cwd, env) =>
683675
Effect.gen(function* () {
684676
yield* git(cwd, ["config", "t3.value", "first"]);
685-
yield* trustNoOtherOwner;
677+
yield* trustNoOtherOwner(env);
686678
NodeFS.mkdirSync(NodePath.join(cwd, "sub"));
687679
return NodePath.join(cwd, "sub");
688680
}),
689-
change: (_cwd, sub) =>
690-
git(sub, ["rev-parse", "--show-toplevel"]).pipe(Effect.flatMap(changeOwner)),
681+
change: (_cwd, sub, env) =>
682+
git(sub, ["rev-parse", "--show-toplevel"]).pipe(Effect.flatMap(changeOwner(env))),
691683
read: readValue("t3.value"),
692684
before: "first",
693685
after: null,
694686
reused: true,
695687
},
696688
{
697689
name: "a new owner of a linked worktree's git dir",
698-
setup: (cwd) =>
690+
setup: (cwd, env) =>
699691
Effect.gen(function* () {
700692
const worktree = NodePath.join(yield* makeTmpDir("git-worktrees-"), "linked");
701693
yield* git(cwd, ["config", "t3.value", "first"]);
702694
yield* git(cwd, ["worktree", "add", "-b", "linked", worktree]);
703-
yield* trustNoOtherOwner;
695+
yield* trustNoOtherOwner(env);
704696
return worktree;
705697
}),
706-
change: (_cwd, worktree) =>
707-
git(worktree, ["rev-parse", "--absolute-git-dir"]).pipe(Effect.flatMap(changeOwner)),
698+
change: (_cwd, worktree, env) =>
699+
git(worktree, ["rev-parse", "--absolute-git-dir"]).pipe(Effect.flatMap(changeOwner(env))),
708700
read: readValue("t3.value"),
709701
before: "first",
710702
after: null,
@@ -758,23 +750,26 @@ describe("config reads", () => {
758750
];
759751

760752
it.effect.each(changes)("sees $name on the next read", (change) =>
761-
Effect.scoped(
762-
Effect.gen(function* () {
763-
const { driver, spawned } = yield* makeCountingDriver;
764-
const cwd = yield* makeTmpDir();
765-
yield* initRepoWithCommit(cwd);
766-
const readCwd = yield* change.setup(cwd);
767-
assert.equal(yield* change.read(driver, readCwd), change.before);
768-
assert.equal(yield* change.read(driver, readCwd), change.before);
769-
spawned.length = 0;
770-
assert.equal(yield* change.read(driver, readCwd), change.before);
771-
assert.equal(spawned.filter(readsOnlyConfig).length === 0, change.reused);
753+
Effect.flatMap(HostProcess.Environment, (hostEnv) => {
754+
const env = { ...hostEnv };
755+
return Effect.scoped(
756+
Effect.gen(function* () {
757+
const { driver, spawned } = yield* makeCountingDriver;
758+
const cwd = yield* makeTmpDir();
759+
yield* initRepoWithCommit(cwd);
760+
const readCwd = yield* change.setup(cwd, env);
761+
assert.equal(yield* change.read(driver, readCwd), change.before);
762+
assert.equal(yield* change.read(driver, readCwd), change.before);
763+
spawned.length = 0;
764+
assert.equal(yield* change.read(driver, readCwd), change.before);
765+
assert.equal(spawned.filter(readsOnlyConfig).length === 0, change.reused);
772766

773-
yield* change.change(cwd, readCwd);
767+
yield* change.change(cwd, readCwd, env);
774768

775-
assert.equal(yield* change.read(driver, readCwd), change.after);
776-
}),
777-
).pipe(Effect.provide(layerTest)),
769+
assert.equal(yield* change.read(driver, readCwd), change.after);
770+
}),
771+
).pipe(Effect.provideService(HostProcess.Environment, env));
772+
}).pipe(Effect.provide(layerTest)),
778773
);
779774

780775
it.effect.skipIf(!caseInsensitiveFileSystem)(
@@ -810,18 +805,11 @@ describe("config reads", () => {
810805
const sub = NodePath.join(cwd, "sub");
811806
NodeFS.mkdirSync(sub);
812807
const workTree = yield* makeTmpDir("git-work-tree-");
813-
const readWithWorkTree = Effect.acquireUseRelease(
814-
Effect.sync(() => {
815-
const previous = process.env.GIT_WORK_TREE;
816-
process.env.GIT_WORK_TREE = workTree;
817-
return previous;
808+
const readWithWorkTree = driver.readConfigValue(sub, "t3.value").pipe(
809+
Effect.provideService(HostProcess.Environment, {
810+
...(yield* HostProcess.Environment),
811+
GIT_WORK_TREE: workTree,
818812
}),
819-
() => driver.readConfigValue(sub, "t3.value"),
820-
(previous) =>
821-
Effect.sync(() => {
822-
if (previous === undefined) delete process.env.GIT_WORK_TREE;
823-
else process.env.GIT_WORK_TREE = previous;
824-
}),
825813
);
826814
assert.equal(yield* readWithWorkTree, "parent");
827815
assert.equal(yield* readWithWorkTree, "parent");
@@ -834,6 +822,38 @@ describe("config reads", () => {
834822
).pipe(Effect.provide(layerTest)),
835823
);
836824

825+
it.effect("answers each read from the config of the environment it runs in", () =>
826+
Effect.scoped(
827+
Effect.gen(function* () {
828+
const { driver, spawned } = yield* makeCountingDriver;
829+
const cwd = yield* makeTmpDir();
830+
yield* initRepoWithCommit(cwd);
831+
const hostEnv = yield* HostProcess.Environment;
832+
const readWithGlobal = Effect.fnUntraced(function* (value: string) {
833+
const global = NodePath.join(yield* makeTmpDir("git-global-"), "gitconfig");
834+
yield* writeInclude(global, value);
835+
return driver.readConfigValue(cwd, "t3.value").pipe(
836+
Effect.provideService(HostProcess.Environment, {
837+
...hostEnv,
838+
GIT_CONFIG_GLOBAL: global,
839+
}),
840+
);
841+
});
842+
const readFirst = yield* readWithGlobal("first");
843+
const readSecond = yield* readWithGlobal("second");
844+
for (const _ of [1, 2]) {
845+
assert.equal(yield* readFirst, "first");
846+
assert.equal(yield* readSecond, "second");
847+
}
848+
spawned.length = 0;
849+
850+
assert.equal(yield* readFirst, "first");
851+
assert.equal(yield* readSecond, "second");
852+
assert.deepStrictEqual(spawned.filter(readsOnlyConfig), []);
853+
}),
854+
).pipe(Effect.provide(layerTest)),
855+
);
856+
837857
it.effect("reads what git config --get and git remote read", () =>
838858
Effect.scoped(
839859
Effect.gen(function* () {

‎apps/server/src/vcs/gitConfigSnapshot.ts‎

Lines changed: 36 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,6 @@ export interface GitConfigSnapshot {
227227
}
228228

229229
interface CachedGitConfigSnapshot {
230-
readonly environment: string;
231230
readonly dependencies: ReadonlyArray<GitConfigDependency>;
232231
readonly fingerprint: string;
233232
// null: a value may depend on something the dependencies miss, so every read runs Git.
@@ -240,6 +239,10 @@ type RunGit = (
240239
args: ReadonlyArray<string>,
241240
) => Effect.Effect<GitVcsDriver.ExecuteGitResult, GitCommandError>;
242241

242+
// Snapshots are per directory and config environment, so a read never sees another environment's
243+
// config. JSON escapes NUL and a path cannot hold one, so the key splits at its first NUL.
244+
const snapshotKey = (cwd: string, environment: string) => `${environment}\0${cwd}`;
245+
243246
const CONFIG_SNAPSHOT_CACHE_CAPACITY = 2_048;
244247
const CONFIG_SNAPSHOT_RETRY_TTL = Duration.seconds(1);
245248
const CONFIG_SNAPSHOT_LOAD_ATTEMPTS = 3;
@@ -271,9 +274,9 @@ const REPOSITORY_PATH_ARGS = [
271274
] as const;
272275

273276
/**
274-
* Per-directory snapshots of `git config --list`, reused while the files that chose and supplied
275-
* those values keep the same stat. Every dependency is stat'ed before the read that depends on it,
276-
* so a write during a load leaves the snapshot stale rather than wrong.
277+
* Snapshots of `git config --list` per directory and config environment, reused while the files
278+
* that chose and supplied those values keep the same stat. Every dependency is stat'ed before the
279+
* read that depends on it, so a write during a load leaves the snapshot stale rather than wrong.
277280
*/
278281
export const makeGitConfigSnapshots = Effect.fn("makeGitConfigSnapshots")(function* (
279282
runGit: RunGit,
@@ -326,6 +329,7 @@ export const makeGitConfigSnapshots = Effect.fn("makeGitConfigSnapshots")(functi
326329
const readConfigState = Effect.fn("GitVcsDriver.configSnapshot.read")(function* (
327330
cwd: string,
328331
environment: string,
332+
home: string | undefined,
329333
) {
330334
const pathsResult = yield* runGit(
331335
"GitVcsDriver.configSnapshot.paths",
@@ -419,7 +423,7 @@ export const makeGitConfigSnapshots = Effect.fn("makeGitConfigSnapshots")(functi
419423
snapshotSupported = false;
420424
} else {
421425
const listed = gitConfigListDependencies(entries, {
422-
home: process.env.HOME,
426+
home,
423427
windows,
424428
isAbsolute: path.isAbsolute,
425429
});
@@ -433,14 +437,18 @@ export const makeGitConfigSnapshots = Effect.fn("makeGitConfigSnapshots")(functi
433437
});
434438

435439
const load = Effect.fn("GitVcsDriver.configSnapshot.load")(
436-
function* (cwd: string) {
437-
const environment = gitConfigEnvironmentSignature(process.env);
438-
if (environment === null) return null;
439-
let dependencies = reloadDependencies.get(cwd) ?? [];
440-
reloadDependencies.delete(cwd);
440+
function* (key: string) {
441+
const separator = key.indexOf("\0");
442+
const environment = key.slice(0, separator);
443+
const cwd = key.slice(separator + 1);
444+
// Git runs in the environment of the read that started the load, which the key names.
445+
const env = yield* HostProcess.Environment;
446+
if (gitConfigEnvironmentSignature(env) !== environment) return null;
447+
let dependencies = reloadDependencies.get(key) ?? [];
448+
reloadDependencies.delete(key);
441449
for (let attempt = 0; attempt < CONFIG_SNAPSHOT_LOAD_ATTEMPTS; attempt++) {
442450
const fingerprints = yield* fingerprintDependencies(dependencies);
443-
const state = yield* readConfigState(cwd, environment);
451+
const state = yield* readConfigState(cwd, environment, env.HOME);
444452
if (state === null) return null;
445453
const fingerprintByKey = new Map(
446454
dependencies.map((dependency, index) => [
@@ -462,7 +470,6 @@ export const makeGitConfigSnapshots = Effect.fn("makeGitConfigSnapshots")(functi
462470
dependency.kind !== "absent" || fingerprint[index]!.startsWith("!"),
463471
);
464472
return {
465-
environment,
466473
dependencies: unique,
467474
fingerprint: fingerprint.join("\n"),
468475
snapshot:
@@ -486,37 +493,38 @@ export const makeGitConfigSnapshots = Effect.fn("makeGitConfigSnapshots")(functi
486493
});
487494

488495
const isCurrent = (cached: CachedGitConfigSnapshot) =>
489-
cached.environment === gitConfigEnvironmentSignature(process.env)
490-
? fingerprintDependencies(cached.dependencies).pipe(
491-
Effect.map((fingerprints) => fingerprints.join("\n") === cached.fingerprint),
492-
)
493-
: Effect.succeed(false);
496+
fingerprintDependencies(cached.dependencies).pipe(
497+
Effect.map((fingerprints) => fingerprints.join("\n") === cached.fingerprint),
498+
);
494499

495500
// A one-off read runs one command; a directory read again, such as on every refresh, is loaded.
496-
const isReadAgain = (cwd: string) => {
497-
if (readOnce.has(cwd)) return true;
501+
const isReadAgain = (key: string) => {
502+
if (readOnce.has(key)) return true;
498503
if (readOnce.size >= CONFIG_SNAPSHOT_CACHE_CAPACITY) {
499504
readOnce.delete(readOnce.values().next().value!);
500505
}
501-
readOnce.add(cwd);
506+
readOnce.add(key);
502507
return false;
503508
};
504509

505510
/**
506-
* The current snapshot for `cwd`, or null when this read must run Git. Untraced: it runs on every
507-
* config read, several per status refresh; loads keep their spans.
511+
* The current snapshot for `cwd` in this read's environment, or null when this read must run Git.
512+
* Untraced: it runs on every config read, several per status refresh; loads keep their spans.
508513
*/
509514
const read = Effect.fnUntraced(function* (cwd: string) {
510515
if (!supported) return null;
511-
if (!(yield* Cache.has(snapshots, cwd)) && !isReadAgain(cwd)) return null;
512-
const cached = yield* Cache.get(snapshots, cwd);
516+
const environment = gitConfigEnvironmentSignature(yield* HostProcess.Environment);
517+
if (environment === null) return null;
518+
const key = snapshotKey(cwd, environment);
519+
if (!(yield* Cache.has(snapshots, key)) && !isReadAgain(key)) return null;
520+
const cached = yield* Cache.get(snapshots, key);
513521
if (cached === null) return null;
514522
if (yield* isCurrent(cached)) return cached.snapshot;
515-
reloadDependencies.set(cwd, cached.dependencies);
516-
yield* Cache.invalidateWhen(snapshots, cwd, (current) => current === cached);
523+
reloadDependencies.set(key, cached.dependencies);
524+
yield* Cache.invalidateWhen(snapshots, key, (current) => current === cached);
517525
// Whatever replaces the stale entry loaded after this read began, so it needs no check.
518-
const reloaded = yield* Cache.get(snapshots, cwd);
519-
reloadDependencies.delete(cwd);
526+
const reloaded = yield* Cache.get(snapshots, key);
527+
reloadDependencies.delete(key);
520528
return reloaded?.snapshot ?? null;
521529
});
522530

0 commit comments

Comments
 (0)