diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index 78a436a1424e..3e0e89f7c4fa 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -369,6 +369,187 @@ it.effect.each(["interrupt", "timeout", "success"] as const)( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect.each(["interrupt", "timeout"] as const)( + "checkpoint staging $0 removes the Git LFS temp files its clean filter wrote", + (stop) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-lfs-checkpoint-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + const lfsTmp = path.join(cwd, ".git/lfs/tmp"); + yield* fs.makeDirectory(lfsTmp, { recursive: true }); + const otherOperation = path.join(lfsTmp, "owned-by-another-git-lfs"); + yield* fs.writeFileString(otherOperation, "another git-lfs process is hashing this"); + + const connected = Promise.withResolvers(); + const sockets = new Set(); + const server = yield* Effect.acquireRelease( + Effect.sync(() => + NodeNet.createServer((socket) => { + sockets.add(socket); + connected.resolve(); + }), + ), + (server) => + Effect.sync(() => { + for (const socket of sockets) socket.destroy(); + server.close(); + }), + ); + yield* Effect.promise( + () => + new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }), + ); + const address = server.address(); + assert.isTrue(address !== null && typeof address !== "string"); + if (address === null || typeof address === "string") return; + // Like git-lfs clean: copy the content into /tmp while hashing, and only + // move or remove that copy once hashing finishes. A killed filter strands it. + const filter = path.join(sandbox, "lfs-clean.cjs"); + yield* fs.writeFileString( + filter, + [ + "const fs = require('node:fs');", + `const storage = require('node:child_process').execSync('git config --default .git/lfs lfs.storage').toString().trim();`, + "fs.mkdirSync(storage + '/tmp', { recursive: true });", + "fs.writeFileSync(storage + '/tmp/' + process.pid, Buffer.alloc(1024 * 1024));", + `const s = require('node:net').connect(${address.port}, '127.0.0.1');`, + "s.resume(); process.stdin.resume();", + "s.on('close', () => process.exit(0));", + ].join("\n"), + ); + // Not "lfs": a machine-wide git-lfs install sets filter.lfs.process, which wins over clean. + yield* git(["config", "filter.lfs-standin.clean", `"${process.execPath}" "${filter}"`]); + yield* git(["config", "filter.lfs-standin.required", "true"]); + yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "*.npz filter=lfs-standin\n"); + yield* fs.writeFileString(path.join(cwd, "weights.npz"), "large untracked data\n"); + + const fiber = yield* driver.checkpoints + .captureCheckpoint({ cwd, checkpointRef }) + .pipe(Effect.exit, Effect.forkScoped); + yield* Effect.promise(() => connected.promise); + const laterOperation = path.join(lfsTmp, "started-during-capture"); + yield* fs.writeFileString(laterOperation, "another git-lfs process started later"); + if (stop === "interrupt") yield* Fiber.interrupt(fiber); + else yield* TestClock.adjust("30 seconds"); + const result = yield* Fiber.await(fiber); + if (stop === "interrupt") + assert.isTrue(Exit.isFailure(result) && Cause.hasInterruptsOnly(result.cause)); + else assert.isTrue(Exit.isSuccess(result) && Exit.isFailure(result.value)); + + assert.sameMembers(yield* fs.readDirectory(lfsTmp), [ + "owned-by-another-git-lfs", + "started-during-capture", + ]); + assert.strictEqual( + yield* fs.readFileString(otherOperation), + "another git-lfs process is hashing this", + ); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("checkpoint staging moves Git LFS objects its clean filter wrote into LFS storage", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-lfs-checkpoint-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + // Like git-lfs clean: hash through /tmp, then move the copy into objects. + const filter = path.join(sandbox, "lfs-clean.cjs"); + yield* fs.writeFileString( + filter, + [ + "const fs = require('node:fs');", + `const storage = require('node:child_process').execSync('git config --default .git/lfs lfs.storage').toString().trim();`, + "const content = fs.readFileSync(0);", + "const oid = require('node:crypto').createHash('sha256').update(content).digest('hex');", + "fs.mkdirSync(storage + '/tmp', { recursive: true });", + "const dir = storage + '/objects/' + oid.slice(0, 2) + '/' + oid.slice(2, 4);", + "fs.mkdirSync(dir, { recursive: true });", + "fs.writeFileSync(storage + '/tmp/' + process.pid, content);", + "fs.renameSync(storage + '/tmp/' + process.pid, dir + '/' + oid);", + "process.stdout.write('oid sha256:' + oid + '\\n');", + ].join("\n"), + ); + // Not "lfs": a machine-wide git-lfs install sets filter.lfs.process, which wins over clean. + yield* git(["config", "filter.lfs-standin.clean", `"${process.execPath}" "${filter}"`]); + yield* git(["config", "filter.lfs-standin.required", "true"]); + yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "*.npz filter=lfs-standin\n"); + yield* fs.writeFileString(path.join(cwd, "weights.npz"), "large untracked data\n"); + + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + + const pointer = yield* git(["show", `${checkpointRef}:weights.npz`]); + const oid = pointer.stdout.trim().slice("oid sha256:".length); + assert.strictEqual( + yield* fs.readFileString( + path.join(cwd, ".git/lfs/objects", oid.slice(0, 2), oid.slice(2, 4), oid), + ), + "large untracked data\n", + ); + assert.isFalse(yield* fs.exists(path.join(cwd, ".git/lfs/tmp"))); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("checkpoint capture fails instead of dropping Git LFS objects it cannot list", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-lfs-checkpoint-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + // A file where git-lfs keeps its objects makes the store unreadable without being absent. + const filter = path.join(sandbox, "lfs-clean.cjs"); + yield* fs.writeFileString( + filter, + [ + "const fs = require('node:fs');", + `const storage = require('node:child_process').execSync('git config --default .git/lfs lfs.storage').toString().trim();`, + "fs.readFileSync(0);", + "fs.mkdirSync(storage, { recursive: true });", + "fs.writeFileSync(storage + '/objects', 'not a directory');", + "process.stdout.write('pointer\\n');", + ].join("\n"), + ); + // Not "lfs": a machine-wide git-lfs install sets filter.lfs.process, which wins over clean. + yield* git(["config", "filter.lfs-standin.clean", `"${process.execPath}" "${filter}"`]); + yield* git(["config", "filter.lfs-standin.required", "true"]); + yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "*.npz filter=lfs-standin\n"); + yield* fs.writeFileString(path.join(cwd, "weights.npz"), "large untracked data\n"); + + const result = yield* driver.checkpoints + .captureCheckpoint({ cwd, checkpointRef }) + .pipe(Effect.exit); + + const error = Exit.isFailure(result) ? Cause.findErrorOption(result.cause) : Option.none(); + assert.isTrue( + Option.isSome(error) && + error.value._tag === "VcsCheckpointStorageError" && + error.value.stage === "publish", + ); + const ref = yield* driver.execute({ + operation: "checkpoint-test", + cwd, + args: ["rev-parse", "--verify", "--quiet", checkpointRef], + allowNonZeroExit: true, + }); + assert.strictEqual(ref.exitCode, 1); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect.each(["failure", "interrupt"] as const)( "checkpoint publication $0 preserves existing refs and permits retry", (stop) => diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 56b4b44d0156..ab32bc7d9e5a 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -1259,6 +1259,71 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ), ), ); + // git-lfs's clean filter copies each file into /tmp while hashing it and strands + // that copy when killed. Give it storage that is removed with the capture's private objects. + const privateLfs = path.join(privateObjects, "lfs"); + const publishLfsObjects = Effect.gen(function* () { + const source = path.join(privateLfs, "objects"); + const objects = (yield* fileSystem.readDirectory(source, { recursive: true }).pipe( + // Absent when no file went through the filter; any other failure must stop publication. + Effect.catchIf( + (cause) => cause.reason._tag === "NotFound", + () => Effect.succeed([]), + ), + Effect.mapError( + (cause) => + new VcsCheckpointStorageError({ + operation, + cwd: input.cwd, + stage: "publish", + cause, + }), + ), + )).filter((entry) => /^[0-9a-f]{2}[\\/][0-9a-f]{2}[\\/][0-9a-f]{64}$/.test(entry)); + if (objects.length === 0) return; + const configured = yield* execute({ + operation, + cwd: input.cwd, + args: ["config", "--get", "lfs.storage"], + allowNonZeroExit: true, + }); + // git-lfs resolves a relative lfs.storage against the common Git directory. + const storage = path.resolve(gitCommonDir, configured.stdout.trim() || "lfs"); + yield* Effect.forEach( + objects, + (entry) => + Effect.gen(function* () { + const from = path.join(source, entry); + const to = path.join(storage, "objects", entry); + if (yield* fileSystem.exists(to)) return; + yield* fileSystem.makeDirectory(path.dirname(to), { recursive: true }); + // Identical oids are interchangeable, so losing a race to another writer is fine. + // lfs.storage may be on another volume, where only a copy can move the object. + const partial = `${to}.${indexId}`; + yield* fileSystem.rename(from, to).pipe( + Effect.catch((cause) => + Effect.flatMap(fileSystem.exists(to), (exists) => + exists + ? Effect.void + : fileSystem.copyFile(from, partial).pipe( + Effect.andThen(fileSystem.rename(partial, to)), + Effect.ensuring( + fileSystem.remove(partial, { force: true }).pipe(Effect.ignore), + ), + Effect.mapError(() => cause), + ), + ), + ), + ); + }), + { concurrency: 16, discard: true }, + ).pipe( + Effect.mapError( + (cause) => + new VcsCheckpointStorageError({ operation, cwd: input.cwd, stage: "publish", cause }), + ), + ); + }); const commitEnv: NodeJS.ProcessEnv = { GIT_INDEX_FILE: tempIndexPath, GIT_OBJECT_DIRECTORY: privateObjects, @@ -1272,6 +1337,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com", GIT_COMMITTER_NAME: "T3 Code", GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com", + // Any command on the scratch index can run the clean filter, not just add. + ...VcsProcess.gitConfigEnv(hostEnv, "lfs.storage", privateLfs, hostPlatform), }; const cleanupTempIndex = Effect.forEach( @@ -1791,6 +1858,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }); } + yield* publishLfsObjects; // Git writers have exited; bound publication by fanout directory. yield* fileSystem.readDirectory(privateObjects).pipe( Effect.flatMap((directories) =>