@devries-cameron20 / t3code-1 / commits / 3fdcef0994
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): recover pulls from unrelated ref locks (#22107)

Yash Singh committed Oct 19, 2026 at 23:14 UTC 3fdcef09944955a3e94e906ecf892bfbc1f7efc4
3 files changed +638 -48
apps/server/src/vcs/GitVcsDriver.ts
+1
@@ -50,6 +50,7 @@ export interface ExecuteGitInput {
50 readonly env?: NodeJS.ProcessEnv;
51 readonly allowNonZeroExit?: boolean;
52 readonly timeoutMs?: number | null;
53 + readonly forceKillAfterMs?: number;
54 readonly maxOutputBytes?: number;
55 readonly appendTruncationMarker?: boolean;
56 /**
apps/server/src/vcs/GitVcsDriverCore.test.ts
+484 -4
@@ -2,6 +2,7 @@
2 import * as NodeFS from "node:fs";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import * as HostProcess from "@t3tools/shared/HostProcess";
5 +import { writeFakeCli } from "@t3tools/provider-testing/fakeCli";
6 import { assert, it, describe } from "@effect/vitest";
7 import * as Deferred from "effect/Deferred";
8 import * as Effect from "effect/Effect";
@@ -39,6 +40,7 @@ import {
40 } from "./GitVcsDriverCore.ts";
41 import * as GitVcsDriver from "./GitVcsDriver.ts";
42 import { gitConfigEnv } from "./VcsProcess.ts";
43 +import { makeProcessProbe, processProbeSource } from "../testUtils/processProbe.ts";
44
45 const encodeGitCommandError = Schema.encodeEffect(Schema.fromJsonString(GitCommandError));
46
@@ -492,10 +494,259 @@ it.effect("coalesces concurrent ref pages into one repository snapshot", () =>
494 ).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))),
495 );
496
495 -describe("pull output beyond the output cap", () => {
497 +describe("pullCurrentBranch", () => {
498 + const controlledStatusFetch = Effect.gen(function* () {
499 + const fs = yield* FileSystem.FileSystem;
500 + const cwd = yield* makeTmpDir();
501 + yield* fs.makeDirectory(`${cwd}/.git`);
502 + const started = yield* Queue.unbounded<{
503 + cwd: string;
504 + release: Deferred.Deferred<ChildProcessSpawner.ExitCode>;
505 + }>();
506 + const finalized = yield* Queue.unbounded<string>();
507 + const warnings = yield* Queue.unbounded<void>();
508 + const attempts = yield* Ref.make(0);
509 + const pulls = yield* Ref.make(0);
510 + const fetching = yield* Ref.make(false);
511 + const head = yield* Ref.make("before");
512 + const pullRemoteRead = yield* Deferred.make<void>();
513 + const logger = Logger.make<unknown, void>(() => {
514 + Queue.offerUnsafe(warnings, undefined);
515 + });
516 + const spawner = ChildProcessSpawner.make((command) =>
517 + Effect.gen(function* () {
518 + if (!ChildProcess.isStandardCommand(command)) return makeNonRepositoryHandle();
519 + const workingDirectory = command.options.cwd ?? cwd;
520 + const args = command.args;
521 + if (args.includes("fetch")) {
522 + const release = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
523 + yield* Ref.set(fetching, true);
524 + yield* Ref.update(attempts, (count) => count + 1);
525 + yield* Queue.offer(started, { cwd: workingDirectory, release });
526 + yield* Effect.addFinalizer(() => Queue.offer(finalized, workingDirectory));
527 + yield* Effect.addFinalizer(() => Ref.set(fetching, false));
528 + return ChildProcessSpawner.makeHandle({
529 + ...makeSuccessfulHandle(""),
530 + stderr: Stream.encodeText(Stream.make("fatal: remote unavailable\n")),
531 + exitCode: Deferred.await(release),
532 + });
533 + }
534 + if (args[0] === "pull") {
535 + yield* Ref.update(pulls, (count) => count + 1);
536 + if (yield* Ref.get(fetching)) {
537 + return ChildProcessSpawner.makeHandle({
538 + ...makeSuccessfulHandle(""),
539 + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
540 + stderr: Stream.encodeText(
541 + Stream.make("error: cannot lock ref 'refs/remotes/origin/main': File exists\n"),
542 + ),
543 + });
544 + }
545 + yield* Ref.set(head, "after");
546 + return makeSuccessfulHandle("");
547 + }
548 + if (args.includes("branch.main.remote")) {
549 + yield* Deferred.succeed(pullRemoteRead, undefined);
550 + return makeSuccessfulHandle("origin\n");
551 + }
552 + if (args[0] === "status")
553 + return makeSuccessfulHandle(
554 + "# branch.oid before\0# branch.head main\0# branch.upstream origin/main\0# branch.ab +0 -1\0",
555 + );
556 + if (args[0] === "diff-index") return makeSuccessfulHandle("");
557 + if (args.length === 2 && args[0] === "rev-parse" && args[1] === "HEAD")
558 + return makeSuccessfulHandle(`${yield* Ref.get(head)}\n`);
559 + if (args.includes("--git-common-dir"))
560 + return makeSuccessfulHandle(`${workingDirectory}/.git\n`);
561 + if (args.includes("--show-toplevel")) return makeSuccessfulHandle(`${workingDirectory}\n`);
562 + if (args.includes("@{upstream}")) return makeSuccessfulHandle("origin/main\n");
563 + if (args[0] === "remote") return makeSuccessfulHandle("origin\n");
564 + if (args[0] === "rev-list") return makeSuccessfulHandle("0\t0\n");
565 + if (args.includes("refs/remotes/origin/HEAD"))
566 + return makeSuccessfulHandle("refs/remotes/origin/main\n");
567 + return makeSuccessfulHandle("main\n");
568 + }),
569 + );
570 + const driver = yield* makeGitVcsDriverCore().pipe(
571 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
572 + );
573 + const status = Effect.fn("test.controlledStatusFetch.status")((directory = cwd) =>
574 + driver
575 + .statusDetailsRemote(directory)
576 + .pipe(Effect.provideService(Logger.CurrentLoggers, new Set([logger]))),
577 + );
578 + return { cwd, driver, status, started, finalized, warnings, attempts, pulls, pullRemoteRead };
579 + });
580 +
581 + it.effect.each([0, 128])(
582 + "waits for an existing status fetch before pulling after fetch exit %s",
583 + (exitCode) =>
584 + Effect.gen(function* () {
585 + const fixture = yield* controlledStatusFetch;
586 + const status = yield* fixture.status().pipe(Effect.forkScoped);
587 + const fetch = yield* Queue.take(fixture.started);
588 + yield* TestClock.adjust("5 seconds");
589 + yield* Fiber.join(status);
590 +
591 + const pull = yield* fixture.driver.pullCurrentBranch(fixture.cwd).pipe(Effect.forkScoped);
592 + yield* Deferred.await(fixture.pullRemoteRead);
593 + yield* TestClock.adjust("30 seconds");
594 + assert.equal(yield* Ref.get(fixture.pulls), 0);
595 + yield* Deferred.succeed(fetch.release, ChildProcessSpawner.ExitCode(exitCode));
596 +
597 + assert.equal((yield* Fiber.join(pull)).status, "pulled");
598 + assert.equal(yield* Ref.get(fixture.pulls), 1);
599 + assert.equal(yield* Ref.get(fixture.attempts), 1);
600 + }).pipe(
601 + Effect.scoped,
602 + Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer))),
603 + ),
604 + );
605 +
606 + it.effect("does not start a status fetch while pulling", () =>
607 + Effect.gen(function* () {
608 + const fixture = yield* controlledStatusFetch;
609 +
610 + assert.equal((yield* fixture.driver.pullCurrentBranch(fixture.cwd)).status, "pulled");
611 + assert.equal(yield* Ref.get(fixture.pulls), 1);
612 + assert.equal(yield* Ref.get(fixture.attempts), 0);
613 + }).pipe(
614 + Effect.scoped,
615 + Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer))),
616 + ),
617 + );
618 +
619 + it.effect("backs off failures after the status waiter has returned", () =>
620 + Effect.gen(function* () {
621 + const fixture = yield* controlledStatusFetch;
622 + const firstStatus = yield* fixture.status().pipe(Effect.forkScoped);
623 + const first = yield* Queue.take(fixture.started);
624 + yield* TestClock.adjust("5 seconds");
625 + yield* Fiber.join(firstStatus);
626 + yield* Deferred.succeed(first.release, ChildProcessSpawner.ExitCode(128));
627 + yield* Queue.take(fixture.finalized);
628 + yield* Queue.take(fixture.warnings);
629 +
630 + yield* TestClock.adjust("15 seconds");
631 + yield* fixture.status();
632 + assert.equal(yield* Ref.get(fixture.attempts), 1);
633 +
634 + yield* TestClock.adjust("15 seconds");
635 + const secondStatus = yield* fixture.status().pipe(Effect.forkScoped);
636 + const second = yield* Queue.take(fixture.started);
637 + yield* TestClock.adjust("5 seconds");
638 + yield* Fiber.join(secondStatus);
639 + yield* Deferred.succeed(second.release, ChildProcessSpawner.ExitCode(128));
640 + yield* Queue.take(fixture.finalized);
641 + yield* Queue.take(fixture.warnings);
642 +
643 + for (let i = 0; i < 3; i++) {
644 + yield* TestClock.adjust("15 seconds");
645 + yield* fixture.status();
646 + assert.equal(yield* Ref.get(fixture.attempts), 2);
647 + }
648 + yield* TestClock.adjust("15 seconds");
649 + const recoveredStatus = yield* fixture.status().pipe(Effect.forkScoped);
650 + const recovered = yield* Queue.take(fixture.started);
651 + yield* Deferred.succeed(recovered.release, ChildProcessSpawner.ExitCode(0));
652 + yield* Fiber.join(recoveredStatus);
653 + assert.equal(yield* Ref.get(fixture.attempts), 3);
654 +
655 + yield* TestClock.adjust("15 seconds");
656 + const failedAgainStatus = yield* fixture.status().pipe(Effect.forkScoped);
657 + const failedAgain = yield* Queue.take(fixture.started);
658 + yield* Deferred.succeed(failedAgain.release, ChildProcessSpawner.ExitCode(128));
659 + yield* Fiber.join(failedAgainStatus);
660 + yield* Queue.take(fixture.warnings);
661 + yield* TestClock.adjust("15 seconds");
662 + yield* fixture.status();
663 + assert.equal(yield* Ref.get(fixture.attempts), 4);
664 +
665 + yield* TestClock.adjust("15 seconds");
666 + const resetStatus = yield* fixture.status().pipe(Effect.forkScoped);
667 + yield* TestClock.adjust("5 seconds");
668 + yield* Fiber.join(resetStatus);
669 + assert.equal(yield* Ref.get(fixture.attempts), 5);
670 + const reset = yield* Queue.take(fixture.started);
671 + yield* Deferred.succeed(reset.release, ChildProcessSpawner.ExitCode(0));
672 + }).pipe(
673 + Effect.scoped,
674 + Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer))),
675 + ),
676 + );
677 +
678 + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
679 + "bounds cleanup when a Git subprocess ignores SIGTERM",
680 + () =>
681 + Effect.gen(function* () {
682 + const driver = yield* GitVcsDriver.GitVcsDriver;
683 + const directory = yield* makeTmpDir();
684 + const probe = yield* makeProcessProbe;
685 + writeFakeCli({
686 + directory,
687 + name: "git",
688 + source: `process.on("SIGTERM", () => {}); ${processProbeSource(probe.port)}`,
689 + });
690 + const run = yield* driver
691 + .execute({
692 + operation: "test.stalledStatusFetch",
693 + cwd: directory,
694 + args: ["fetch"],
695 + env: { PATH: `${directory}:${process.env.PATH ?? ""}` },
696 + timeoutMs: 1_000,
697 + forceKillAfterMs: 100,
698 + })
699 + .pipe(Effect.flip, Effect.forkScoped);
700 + yield* probe.started;
701 +
702 + yield* TestClock.adjust("1 second");
703 +
704 + yield* probe.exited;
705 + assert.equal((yield* Fiber.join(run)).detail, "Git command timed out.");
706 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
707 + );
708 +
709 + it.effect("releases stalled background worker slots at their lifetime limit", () =>
710 + Effect.gen(function* () {
711 + const fs = yield* FileSystem.FileSystem;
712 + const fixture = yield* controlledStatusFetch;
713 + yield* fixture.driver.listRefs({ cwd: fixture.cwd });
714 + const statuses = [];
715 + for (let i = 0; i < 4; i++) {
716 + const cwd = `${fixture.cwd}/repo-${i}`;
717 + yield* fs.makeDirectory(`${cwd}/.git`, { recursive: true });
718 + statuses.push(yield* fixture.status(cwd).pipe(Effect.forkScoped));
719 + yield* Queue.take(fixture.started);
720 + }
721 + yield* TestClock.adjust("5 seconds");
722 + yield* Effect.forEach(statuses, Fiber.join);
723 + const waiting = yield* fixture.status().pipe(Effect.forkScoped);
724 + yield* TestClock.adjust("5 seconds");
725 + yield* Fiber.join(waiting);
726 + assert.equal(yield* Ref.get(fixture.attempts), 4);
727 +
728 + yield* TestClock.adjust(290_000);
729 + assert.equal(yield* Ref.get(fixture.attempts), 5);
730 + for (let i = 0; i < 4; i++) yield* Queue.take(fixture.finalized);
731 + const healthy = yield* Queue.take(fixture.started);
732 + assert.equal(
733 + NodeFS.realpathSync.native(healthy.cwd),
734 + NodeFS.realpathSync.native(fixture.cwd),
735 + );
736 + yield* Deferred.succeed(healthy.release, ChildProcessSpawner.ExitCode(0));
737 + yield* Queue.take(fixture.finalized);
738 + }).pipe(
739 + Effect.scoped,
740 + Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer))),
741 + ),
742 + );
743 +
744 // A fast-forward that prints over 1 MB takes thousands of files, so the real pull's output is
745 // padded past the cap instead.
498 - const withPaddedPull = (stream: "stdout" | "stderr") =>
746 + const withPaddedPull = (
747 + stream: "stdout" | "stderr",
748 + onPull?: (args: ReadonlyArray<string>) => void,
749 + ) =>
750 Effect.gen(function* () {
751 const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
752 const padding = new Uint8Array(1_000_001).fill(0x20);
@@ -506,6 +757,7 @@ describe("pull output beyond the output cap", () => {
757 ChildProcess.isStandardCommand(command) &&
758 command.args.includes("pull") &&
759 command.args.includes("--ff-only");
760 + if (isPull) onPull?.(command.args);
761 return isPull
762 ? ChildProcessSpawner.makeHandle({
763 ...handle,
@@ -534,9 +786,235 @@ describe("pull output beyond the output cap", () => {
786 yield* git(updater, ["add", "remote.txt"]);
787 yield* git(updater, ["commit", "-m", "remote commit"]);
788 yield* git(updater, ["push", "origin", initialBranch]);
537 - return { cwd, remoteHead: yield* git(updater, ["rev-parse", "HEAD"]) };
789 + return {
790 + cwd,
791 + remote,
792 + updater,
793 + initialBranch,
794 + remoteHead: yield* git(updater, ["rev-parse", "HEAD"]),
795 + };
796 });
797
798 + it.effect("still fetches other branches on the first pull", () =>
799 + Effect.gen(function* () {
800 + const driver = yield* GitVcsDriver.GitVcsDriver;
801 + const { cwd, updater, remoteHead } = yield* cloneBehindRemote;
802 + yield* git(updater, ["push", "origin", "HEAD:refs/heads/other"]);
803 +
804 + const result = yield* driver.pullCurrentBranch(cwd);
805 +
806 + assert.equal(result.status, "pulled");
807 + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead);
808 + assert.equal(yield* git(cwd, ["rev-parse", "refs/remotes/origin/other"]), remoteHead);
809 + }).pipe(Effect.provide(layerTest)),
810 + );
811 +
812 + it.effect.each([false, true])(
813 + "pulls past an unrelated lock with custom fetch mapping=%s",
814 + (customMapping) =>
815 + Effect.gen(function* () {
816 + const driver = yield* GitVcsDriver.GitVcsDriver;
817 + const fs = yield* FileSystem.FileSystem;
818 + const { cwd, updater, initialBranch, remoteHead } = yield* cloneBehindRemote;
819 + yield* git(updater, ["push", "origin", "HEAD:refs/heads/other"]);
820 + const remoteName = customMapping ? "team/upstream" : "origin";
821 + const refPrefix = customMapping
822 + ? `refs/remotes/${remoteName}/mapped`
823 + : "refs/remotes/origin";
824 + if (customMapping) {
825 + yield* git(cwd, ["remote", "rename", "origin", remoteName]);
826 + yield* git(cwd, ["config", `remote.${remoteName}.fetch`, `+refs/heads/*:${refPrefix}/*`]);
827 + yield* git(cwd, ["update-ref", `${refPrefix}/${initialBranch}`, "HEAD"]);
828 + }
829 + const lock = `.git/${refPrefix}/other.lock`;
830 + yield* writeTextFile(cwd, lock, "");
831 +
832 + const result = yield* driver.pullCurrentBranch(cwd);
833 +
834 + assert.equal(result.status, "pulled");
835 + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead);
836 + assert.equal(yield* git(cwd, ["rev-parse", `${refPrefix}/${initialBranch}`]), remoteHead);
837 + assert.isTrue(yield* fs.exists(`${cwd}/${lock}`));
838 + assert.equal(yield* fs.readFileString(`${cwd}/${lock}`), "");
839 + }).pipe(Effect.provide(layerTest)),
840 + );
841 +
842 + it.effect("reports an upstream lock after the fallback without removing it", () =>
843 + Effect.gen(function* () {
844 + const driver = yield* GitVcsDriver.GitVcsDriver;
845 + const fs = yield* FileSystem.FileSystem;
846 + const { cwd, initialBranch } = yield* cloneBehindRemote;
847 + const before = yield* git(cwd, ["rev-parse", "HEAD"]);
848 + const lock = `.git/refs/remotes/origin/${initialBranch}.lock`;
849 + yield* writeTextFile(cwd, lock, "");
850 +
851 + const error = yield* Effect.flip(driver.pullCurrentBranch(cwd));
852 +
853 + assert.include(error.detail, "could not update a local reference");
854 + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), before);
855 + assert.isTrue(yield* fs.exists(`${cwd}/${lock}`));
856 + }).pipe(Effect.provide(layerTest)),
857 + );
858 +
859 + it.effect.each(["branch", "HEAD"] as const)(
860 + "does not retry a failed fetch if another operation moved %s",
861 + (moved) =>
862 + Effect.gen(function* () {
863 + const fixtureDriver = yield* GitVcsDriver.GitVcsDriver;
864 + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
865 + const { cwd, updater } = yield* cloneBehindRemote;
866 + yield* git(updater, ["push", "origin", "HEAD:refs/heads/other"]);
867 + yield* writeTextFile(cwd, ".git/refs/remotes/origin/other.lock", "");
868 + let pulls = 0;
869 + const spawner = ChildProcessSpawner.make((command) =>
870 + Effect.gen(function* () {
871 + const handle = yield* delegate.spawn(command);
872 + if (!ChildProcess.isStandardCommand(command) || !command.args.includes("pull")) {
873 + return handle;
874 + }
875 + pulls += 1;
876 + return ChildProcessSpawner.makeHandle({
877 + ...handle,
878 + exitCode: handle.exitCode.pipe(
879 + Effect.tap(() =>
880 + git(
881 + cwd,
882 + moved === "branch"
883 + ? ["checkout", "-b", "moved"]
884 + : ["commit", "--allow-empty", "-m", "concurrent commit"],
885 + ).pipe(
886 + Effect.provideService(GitVcsDriver.GitVcsDriver, fixtureDriver),
887 + Effect.orDie,
888 + ),
889 + ),
890 + ),
891 + });
892 + }),
893 + );
894 + const driver = yield* makeGitVcsDriverCore().pipe(
895 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
896 + );
897 +
898 + const error = yield* Effect.flip(driver.pullCurrentBranch(cwd));
899 +
900 + assert.include(error.detail, "could not update a local reference");
901 + assert.equal(pulls, 1);
902 + }).pipe(Effect.scoped, Effect.provide(layerServerConfig.pipe(Layer.provideMerge(layerTest)))),
903 + );
904 +
905 + it.effect.each(["deadline", "subscriber cancellation"] as const)(
906 + "lets a background fetch finish after %s without leaving its lock behind",
907 + (interruption) =>
908 + Effect.gen(function* () {
909 + const fs = yield* FileSystem.FileSystem;
910 + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
911 + const { cwd } = yield* cloneBehindRemote;
912 + const lockPath = `${cwd}/.git/refs/remotes/origin/in-flight.lock`;
913 + const started = yield* Deferred.make<void>();
914 + const release = yield* Deferred.make<void>();
915 + const finalized = yield* Deferred.make<void>();
916 + const spawner = ChildProcessSpawner.make((command) =>
917 + Effect.gen(function* () {
918 + if (!ChildProcess.isStandardCommand(command) || !command.args.includes("fetch")) {
919 + return yield* delegate.spawn(command);
920 + }
921 + // Model Git's gap between creating a lock and registering signal cleanup.
922 + yield* fs.writeFileString(lockPath, "");
923 + yield* Effect.addFinalizer(() => Deferred.succeed(finalized, undefined));
924 + yield* Deferred.succeed(started, undefined);
925 + return ChildProcessSpawner.makeHandle({
926 + ...makeSuccessfulHandle(""),
927 + exitCode: Deferred.await(release).pipe(
928 + Effect.andThen(fs.remove(lockPath)),
929 + Effect.as(ChildProcessSpawner.ExitCode(0)),
930 + ),
931 + });
932 + }),
933 + );
934 + const driver = yield* makeGitVcsDriverCore().pipe(
935 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
936 + );
937 + const status = yield* driver.statusDetailsRemote(cwd).pipe(Effect.forkScoped);
938 + yield* Deferred.await(started);
939 +
940 + if (interruption === "deadline") {
941 + yield* TestClock.adjust("5 seconds");
942 + yield* Fiber.join(status);
943 + } else {
944 + yield* Fiber.interrupt(status);
945 + }
946 +
947 + assert.isFalse(yield* Deferred.isDone(finalized));
948 + assert.isTrue(yield* fs.exists(lockPath));
949 +
950 + yield* Deferred.succeed(release, undefined);
951 + yield* Deferred.await(finalized);
952 + assert.isFalse(yield* fs.exists(lockPath));
953 + }).pipe(Effect.scoped, Effect.provide(layerServerConfig.pipe(Layer.provideMerge(layerTest)))),
954 + );
955 +
956 + it.effect("reuses a background fetch across status wait deadlines", () =>
957 + Effect.gen(function* () {
958 + const fs = yield* FileSystem.FileSystem;
959 + const cwd = yield* makeTmpDir();
960 + yield* fs.makeDirectory(`${cwd}/.git`);
961 + const started = yield* Deferred.make<void>();
962 + const release = yield* Deferred.make<void>();
963 + const finalized = yield* Deferred.make<void>();
964 + const attempts = yield* Ref.make(0);
965 + const spawner = ChildProcessSpawner.make((command) =>
966 + Effect.gen(function* () {
967 + if (!ChildProcess.isStandardCommand(command)) return makeNonRepositoryHandle();
968 + if (command.args.includes("fetch")) {
969 + yield* Ref.update(attempts, (count) => count + 1);
970 + yield* Deferred.succeed(started, undefined);
971 + yield* Effect.addFinalizer(() => Deferred.succeed(finalized, undefined));
972 + return ChildProcessSpawner.makeHandle({
973 + ...makeSuccessfulHandle(""),
974 + exitCode: Deferred.await(release).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
975 + });
976 + }
977 + const args = command.args;
978 + return makeSuccessfulHandle(
979 + args.includes("--git-common-dir")
980 + ? `${cwd}/.git\n`
981 + : args.includes("--show-toplevel")
982 + ? `${cwd}\n`
983 + : args.includes("@{upstream}")
984 + ? "origin/main\n"
985 + : args[0] === "remote"
986 + ? "origin\n"
987 + : args[0] === "rev-list"
988 + ? "0\t0\n"
989 + : args.includes("refs/remotes/origin/HEAD")
990 + ? "refs/remotes/origin/main\n"
991 + : "main\n",
992 + );
993 + }),
994 + );
995 + const driver = yield* makeGitVcsDriverCore().pipe(
996 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
997 + );
998 + const first = yield* driver.statusDetailsRemote(cwd).pipe(Effect.forkScoped);
999 + yield* Deferred.await(started);
1000 + yield* TestClock.adjust("5 seconds");
1001 + yield* Fiber.join(first);
1002 +
1003 + yield* TestClock.adjust("15 seconds");
1004 + const second = yield* driver.statusDetailsRemote(cwd).pipe(Effect.forkScoped);
1005 + yield* TestClock.adjust("5 seconds");
1006 + yield* Fiber.join(second);
1007 +
1008 + assert.equal(yield* Ref.get(attempts), 1);
1009 + assert.isFalse(yield* Deferred.isDone(finalized));
1010 + yield* Deferred.succeed(release, undefined);
1011 + yield* Deferred.await(finalized);
1012 + }).pipe(
1013 + Effect.scoped,
1014 + Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer))),
1015 + ),
1016 + );
1017 +
1018 it.effect.each(["stdout", "stderr"] as const)(
1019 "reports a fast-forward whose %s passes the cap as pulled",
1020 (stream) =>
@@ -558,7 +1036,8 @@ describe("pull output beyond the output cap", () => {
1036 it.effect("still fails a pull that Git rejects, whatever its output size", () =>
1037 Effect.scoped(
1038 Effect.gen(function* () {
561 - const driver = yield* withPaddedPull("stderr");
1039 + const pulls: ReadonlyArray<string>[] = [];
1040 + const driver = yield* withPaddedPull("stderr", (args) => pulls.push(args));
1041 yield* Effect.gen(function* () {
1042 const { cwd } = yield* cloneBehindRemote;
1043 yield* writeTextFile(cwd, "local.txt", "local\n");
@@ -570,6 +1049,7 @@ describe("pull output beyond the output cap", () => {
1049 assert.equal(error.operation, "GitVcsDriver.pullCurrentBranch.pull");
1050 assert.equal(error.exitCode, 128);
1051 assert.notInclude(error.detail, "exceeded");
1052 + assert.lengthOf(pulls, 1);
1053 }).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver));
1054 }),
1055 ).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))),
apps/server/src/vcs/GitVcsDriverCore.ts
+153 -44
@@ -1,5 +1,6 @@
1 import * as Cache from "effect/Cache";
2 import * as Cause from "effect/Cause";
3 +import * as Clock from "effect/Clock";
4 import * as Data from "effect/Data";
5 import * as Crypto from "effect/Crypto";
6 import * as DateTime from "effect/DateTime";
@@ -7,6 +8,7 @@ import * as Duration from "effect/Duration";
8 import * as Effect from "effect/Effect";
9 import * as Hex from "effect/encoding/Hex";
10 import * as Exit from "effect/Exit";
11 +import * as Fiber from "effect/Fiber";
12 import * as FileSystem from "effect/FileSystem";
13 import * as Option from "effect/Option";
14 import * as Path from "effect/Path";
@@ -80,6 +82,7 @@ const REVIEW_DIFF_ARGS = [
82 ];
83 const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
84 const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
85 +const STATUS_UPSTREAM_FETCH_TIMEOUT = Duration.minutes(5);
86
87 const STATUS_UPSTREAM_REFRESH_FAILURE_BASE_COOLDOWN = Duration.seconds(30);
88 const STATUS_UPSTREAM_REFRESH_FAILURE_MAX_COOLDOWN = Duration.minutes(15);
@@ -170,6 +173,7 @@ interface GitRefsSnapshot {
173 interface ExecuteGitOptions {
174 stdin?: string | undefined;
175 timeoutMs?: number | null | undefined;
176 + forceKillAfterMs?: number | undefined;
177 allowNonZeroExit?: boolean | undefined;
178 fallbackErrorDetail?: string | undefined;
179 env?: NodeJS.ProcessEnv | undefined;
@@ -916,6 +920,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
920 const { worktreesDir } = yield* ServerConfig.ServerConfig;
921 const crypto = yield* Crypto.Crypto;
922 const hostPlatform = yield* HostProcess.Platform;
923 + const serviceScope = yield* Effect.scope;
924 + const statusFetches = new Map<string, Fiber.Fiber<void, GitCommandError>>();
925 + const statusFetchProcesses = yield* Semaphore.make(4);
926
927 const executeRaw: GitVcsDriver.GitVcsDriver["Service"]["execute"] = Effect.fnUntraced(
928 function* (input) {
@@ -959,6 +966,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
966 ChildProcess.make(executable, commandInput.args, {
967 cwd: commandInput.cwd,
968 env: spawnEnv,
969 + forceKillAfter: input.forceKillAfterMs,
970 }),
971 )
972 .pipe(
@@ -1096,6 +1104,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1104 ...(options.env !== undefined ? { env: options.env } : {}),
1105 allowNonZeroExit: true,
1106 ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
1107 + ...(options.forceKillAfterMs !== undefined
1108 + ? { forceKillAfterMs: options.forceKillAfterMs }
1109 + : {}),
1110 ...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
1111 ...(options.appendTruncationMarker !== undefined
1112 ? { appendTruncationMarker: options.appendTruncationMarker }
@@ -1244,36 +1255,71 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1255 );
1256 });
1257
1247 - const fetchRemoteForStatus = (
1258 + const fetchRemoteForStatus = Effect.fn("GitVcsDriver.fetchRemoteForStatus.wait")(function* (
1259 gitCommonDir: string,
1260 remoteName: string,
1250 - ): Effect.Effect<void, GitCommandError> => {
1261 + ) {
1262 const fetchCwd =
1263 path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
1264 // `--no-auto-gc` (a synonym of `--no-auto-maintenance` that older Git also knows) keeps
1265 // this poll from starting `git gc --auto`. When that gc fails, for example on a repository
1266 // with missing objects, Git retries it on every fetch and leaves a full-size `tmp_pack_*`
1267 // behind each time, so a background poll could fill the disk.
1257 - return executeGit(
1258 - "GitVcsDriver.fetchRemoteForStatus",
1259 - fetchCwd,
1260 - [
1261 - "--git-dir",
1262 - gitCommonDir,
1263 - "fetch",
1264 - "--quiet",
1265 - "--no-tags",
1266 - "--no-auto-gc",
1267 - "--",
1268 - remoteName,
1269 - ],
1270 - {
1271 - env: STATUS_UPSTREAM_REFRESH_ENV,
1272 - fallbackErrorDetail: "Background Git fetch exited with a non-zero status.",
1273 - timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
1274 - },
1275 - ).pipe(Effect.asVoid);
1276 - };
1268 + const args = [
1269 + "--git-dir",
1270 + gitCommonDir,
1271 + "fetch",
1272 + "--quiet",
1273 + "--no-tags",
1274 + "--no-auto-gc",
1275 + "--",
1276 + remoteName,
1277 + ];
1278 + const key = `${gitCommonDir}\0${remoteName}`;
1279 + const failure = statusRemoteRefreshFailures.get(key);
1280 + if (failure && (yield* Clock.currentTimeMillis) < failure.retryAt) return;
1281 + const fiber = yield* Effect.uninterruptible(
1282 + Effect.gen(function* () {
1283 + const pending = statusFetches.get(key);
1284 + if (pending) return pending;
1285 + // Frequent poll deadlines and disconnected clients must not interrupt a
1286 + // healthy writer. A separate safety limit prevents a hung transport from
1287 + // occupying its worker slot indefinitely.
1288 + const started = yield* executeGit("GitVcsDriver.fetchRemoteForStatus", fetchCwd, args, {
1289 + env: STATUS_UPSTREAM_REFRESH_ENV,
1290 + fallbackErrorDetail: "Background Git fetch exited with a non-zero status.",
1291 + timeoutMs: Duration.toMillis(STATUS_UPSTREAM_FETCH_TIMEOUT),
1292 + forceKillAfterMs: 1_000,
1293 + }).pipe(
1294 + Effect.asVoid,
1295 + Effect.tap(() =>
1296 + Effect.sync(() => {
1297 + statusRemoteRefreshFailures.delete(key);
1298 + }),
1299 + ),
1300 + Effect.tapError(() => recordStatusRemoteRefreshFailure(key)),
1301 + Effect.tapCause((cause) => Effect.logWarning("Background Git fetch failed", cause)),
1302 + statusFetchProcesses.withPermits(1),
1303 + Effect.onExit(() =>
1304 + Effect.sync(() => {
1305 + statusFetches.delete(key);
1306 + }),
1307 + ),
1308 + Effect.forkIn(serviceScope, { startImmediately: false, uninterruptible: false }),
1309 + );
1310 + statusFetches.set(key, started);
1311 + return started;
1312 + }),
1313 + );
1314 + const result = yield* Fiber.join(fiber).pipe(
1315 + Effect.timeoutOption(STATUS_UPSTREAM_REFRESH_TIMEOUT),
1316 + );
1317 + if (Option.isNone(result)) {
1318 + yield* Effect.logDebug(
1319 + "Background Git fetch is still running; using the last fetched references.",
1320 + );
1321 + }
1322 + });
1323
1324 const resolveRepositoryPathsUncached = Effect.fn("resolveRepositoryPathsUncached")(function* (
1325 cwd: string,
@@ -1468,31 +1514,30 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1514 });
1515 });
1516
1471 - const statusRemoteRefreshFailureCounts = new Map<string, number>();
1517 + const statusRemoteRefreshFailures = new Map<string, { count: number; retryAt: number }>();
1518 const statusRemoteRefreshFailureKey = (cacheKey: StatusRemoteRefreshCacheKey) =>
1519 `${cacheKey.gitCommonDir}\0${cacheKey.remoteName}`;
1474 - const recordStatusRemoteRefreshFailure = (cacheKey: StatusRemoteRefreshCacheKey) => {
1475 - const key = statusRemoteRefreshFailureKey(cacheKey);
1476 - const nextCount = (statusRemoteRefreshFailureCounts.get(key) ?? 0) + 1;
1477 - statusRemoteRefreshFailureCounts.delete(key);
1478 - statusRemoteRefreshFailureCounts.set(key, nextCount);
1479 - if (statusRemoteRefreshFailureCounts.size > STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY) {
1480 - const oldestKey = statusRemoteRefreshFailureCounts.keys().next().value;
1520 + const recordStatusRemoteRefreshFailure = Effect.fn(
1521 + "GitVcsDriver.recordStatusRemoteRefreshFailure",
1522 + )(function* (key: string) {
1523 + const nextCount = (statusRemoteRefreshFailures.get(key)?.count ?? 0) + 1;
1524 + const now = yield* Clock.currentTimeMillis;
1525 + statusRemoteRefreshFailures.delete(key);
1526 + statusRemoteRefreshFailures.set(key, {
1527 + count: nextCount,
1528 + retryAt: now + Duration.toMillis(statusUpstreamRefreshFailureCooldown(nextCount)),
1529 + });
1530 + if (statusRemoteRefreshFailures.size > STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY) {
1531 + const oldestKey = statusRemoteRefreshFailures.keys().next().value;
1532 if (oldestKey !== undefined) {
1482 - statusRemoteRefreshFailureCounts.delete(oldestKey);
1533 + statusRemoteRefreshFailures.delete(oldestKey);
1534 }
1535 }
1485 - };
1486 - const clearStatusRemoteRefreshFailures = (cacheKey: StatusRemoteRefreshCacheKey) => {
1487 - statusRemoteRefreshFailureCounts.delete(statusRemoteRefreshFailureKey(cacheKey));
1488 - };
1536 + });
1537 const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* (
1538 cacheKey: StatusRemoteRefreshCacheKey,
1539 ) {
1540 return yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName).pipe(
1493 - Effect.tap(() => Effect.sync(() => clearStatusRemoteRefreshFailures(cacheKey))),
1494 - Effect.tapError(() => Effect.sync(() => recordStatusRemoteRefreshFailure(cacheKey))),
1495 - Effect.tapCause((cause) => Effect.logWarning("Background Git fetch failed", cause)),
1541 Effect.as(true as const),
1542 );
1543 });
@@ -1507,7 +1552,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1552 Exit.isSuccess(exit)
1553 ? STATUS_UPSTREAM_REFRESH_INTERVAL
1554 : statusUpstreamRefreshFailureCooldown(
1510 - statusRemoteRefreshFailureCounts.get(statusRemoteRefreshFailureKey(cacheKey)) ?? 1,
1555 + statusRemoteRefreshFailures.get(statusRemoteRefreshFailureKey(cacheKey))?.count ?? 1,
1556 ),
1557 });
1558
@@ -2594,7 +2639,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2639 const pullCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pullCurrentBranch"] = Effect.fn(
2640 "pullCurrentBranch",
2641 )(function* (cwd) {
2597 - const details = yield* statusDetails(cwd);
2642 + const details = yield* readStatusDetailsLocal(cwd);
2643 const refName = details.branch;
2644 if (!refName) {
2645 return yield* new GitCommandError({
@@ -2616,6 +2661,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2661 detail: "Current branch has no upstream configured. Push with upstream first.",
2662 });
2663 }
2664 + const remote = yield* readConfigValue(cwd, `branch.${refName}.remote`);
2665 + if (remote) {
2666 + const gitCommonDir = yield* resolveGitCommonDir(cwd);
2667 + const pending = statusFetches.get(`${gitCommonDir}\0${remote}`);
2668 + // The status wait can finish while its fetch still owns reference locks.
2669 + // Let our existing writer finish before starting the pull's fetch.
2670 + if (pending) yield* Fiber.await(pending);
2671 + }
2672 const beforeSha = yield* runGitStdout(
2673 "GitVcsDriver.pullCurrentBranch.beforeSha",
2674 cwd,
@@ -2625,11 +2678,67 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2678 // After a successful pull, HEAD before and after decides the result, so its output is not
2679 // needed. A large fast-forward's diffstat can exceed the output cap, which must not fail a
2680 // pull Git applied.
2628 - yield* executeGit("GitVcsDriver.pullCurrentBranch.pull", cwd, ["pull", "--ff-only"], {
2681 + const options = {
2682 timeoutMs: 30_000,
2630 - fallbackErrorDetail: "git pull failed",
2683 appendTruncationMarker: true,
2632 - });
2684 + allowNonZeroExit: true,
2685 + };
2686 + let args = ["pull", "--ff-only"];
2687 + let result = yield* executeGitWithStableDiagnostics(
2688 + "GitVcsDriver.pullCurrentBranch.pull",
2689 + cwd,
2690 + args,
2691 + options,
2692 + );
2693 + if (result.exitCode !== 0 && isRefLockFailure(result.stderr)) {
2694 + const [remote, mergeRefs, currentBranch, currentSha] = yield* Effect.all([
2695 + readConfigValue(cwd, `branch.${refName}.remote`),
2696 + runGitStdout(
2697 + "GitVcsDriver.pullCurrentBranch.mergeRefs",
2698 + cwd,
2699 + ["config", "--get-all", `branch.${refName}.merge`],
2700 + true,
2701 + ).pipe(Effect.map((stdout) => stdout.trim().split("\n").filter(Boolean))),
2702 + runGitStdout(
2703 + "GitVcsDriver.pullCurrentBranch.currentBranch",
2704 + cwd,
2705 + ["symbolic-ref", "--quiet", "--short", "HEAD"],
2706 + true,
2707 + ).pipe(Effect.map((stdout) => stdout.trim())),
2708 + runGitStdout("GitVcsDriver.pullCurrentBranch.currentSha", cwd, ["rev-parse", "HEAD"]).pipe(
2709 + Effect.map((stdout) => stdout.trim()),
2710 + ),
2711 + ]);
2712 + // A full fetch can fail on an unrelated branch's lock. Keep that fetch as the
2713 + // default, but retry only the configured upstream before any checkout movement.
2714 + const [mergeRef] = mergeRefs;
2715 + if (
2716 + remote &&
2717 + mergeRef &&
2718 + mergeRefs.length === 1 &&
2719 + currentBranch === refName &&
2720 + currentSha === beforeSha
2721 + ) {
2722 + args = ["pull", "--ff-only", "--", remote, mergeRef];
2723 + result = yield* executeGitWithStableDiagnostics(
2724 + "GitVcsDriver.pullCurrentBranch.pull",
2725 + cwd,
2726 + args,
2727 + options,
2728 + );
2729 + }
2730 + }
2731 + if (result.exitCode !== 0) {
2732 + const reason = classifyGitFailure(result.stderr);
2733 + return yield* new GitCommandError({
2734 + ...gitCommandContext({ operation: "GitVcsDriver.pullCurrentBranch.pull", cwd, args }),
2735 + ...(reason === null ? {} : { reason }),
2736 + detail: fetchFailureDetail(result.stderr) ?? "git pull failed",
2737 + exitCode: result.exitCode,
2738 + stdoutLength: result.stdout.length,
2739 + stderrLength: result.stderr.length,
2740 + });
2741 + }
2742 const afterSha = yield* runGitStdout(
2743 "GitVcsDriver.pullCurrentBranch.afterSha",
2744 cwd,
@@ -2637,7 +2746,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2746 true,
2747 ).pipe(Effect.map((stdout) => stdout.trim()));
2748
2640 - const refreshed = yield* statusDetails(cwd);
2749 + const refreshed = yield* readStatusDetailsLocal(cwd);
2750 return {
2751 status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
2752 refName,