diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 8ae4c51c1..e94a543fe 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -3682,12 +3682,15 @@ const make = Effect.gen(function* () { } const checkpointStartedAtMs = yield* Clock.currentTimeMillis; - yield* capturePreTurnCheckpointForTurnStart({ threadId: event.payload.threadId }).pipe( + const checkpointFailed = yield* capturePreTurnCheckpointForTurnStart({ + threadId: event.payload.threadId, + }).pipe( + Effect.as(false), Effect.catchCause((cause) => Effect.logWarning("provider command reactor failed to capture pre-turn checkpoint", { threadId: event.payload.threadId, cause: Cause.pretty(cause), - }), + }).pipe(Effect.as(true)), ), ); @@ -3751,6 +3754,7 @@ const make = Effect.gen(function* () { queueMs, prepareMs: checkpointStartedAtMs - prepareStartedAtMs, checkpointMs: checkpointEndedAtMs - checkpointStartedAtMs, + checkpointFailed, }, }) .pipe( diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index f8435d129..d675a7403 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -505,6 +505,9 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( handoffQueueMs: latency.handoffSteps.queueMs, handoffPrepareMs: latency.handoffSteps.prepareMs, handoffCheckpointMs: latency.handoffSteps.checkpointMs, + ...(latency.handoffSteps.checkpointFailed !== undefined + ? { handoffCheckpointFailed: latency.handoffSteps.checkpointFailed } + : {}), } : {}), firstOutputMs: latency.firstOutputMs, @@ -1655,6 +1658,8 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( "provider.turn.handoff_queue_ms": input.handoffSteps.queueMs, "provider.turn.handoff_prepare_ms": input.handoffSteps.prepareMs, "provider.turn.handoff_checkpoint_ms": input.handoffSteps.checkpointMs, + "provider.turn.handoff_checkpoint_failed": + input.handoffSteps.checkpointFailed === true, } : {}), }); diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index cfec87f63..11f7a0c6b 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -1260,15 +1260,9 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( tree: headCommit, env: commitEnv, git: (args, env, options) => execute({ operation, cwd: input.cwd, args, env, ...options }), + stageCheckout: true, use: (env) => Effect.gen(function* () { - yield* execute({ - operation, - cwd: input.cwd, - args: ["add", "-A", "--", "."], - env, - }); - const writeTreeResult = yield* execute({ operation, cwd: input.cwd, diff --git a/apps/server/src/vcs/scratchIndex.test.ts b/apps/server/src/vcs/scratchIndex.test.ts index d119c983d..10bbd7c00 100644 --- a/apps/server/src/vcs/scratchIndex.test.ts +++ b/apps/server/src/vcs/scratchIndex.test.ts @@ -1,5 +1,5 @@ // @effect-diagnostics nodeBuiltinImport:off -import { execFileSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; import path from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -32,7 +32,8 @@ describe("makeScratchIndexes", () => { const git: ScratchIndexGit = (args, env) => Effect.try({ try: () => { - if (args[0] === "read-tree") { + // Loads of the scratch index itself, not of a listing's. + if (args[0] === "read-tree" && env.GIT_INDEX_FILE?.includes("t3-checkpoint-index-")) { loads.push(args); } return { stdout: run(args, env) }; @@ -63,4 +64,177 @@ describe("makeScratchIndexes", () => { expect(tree.stdout.trim()).toBe(run(["write-tree"]).trim()); }).pipe(Effect.provide(NodeServices.layer)), ); + + it.effect("stages a checkpoint over its cache to the same tree a cold one gets", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const repo = yield* fileSystem.makeTempDirectoryScoped({ prefix: "scratch-index-test-" }); + const write = (file: string, text: string) => + fileSystem.writeFileString(path.join(repo, file), text); + const run = (args: ReadonlyArray, env: NodeJS.ProcessEnv = {}) => + execFileSync("git", args, { cwd: repo, env: { ...process.env, ...env }, encoding: "utf8" }); + run(["init", "-q"]); + run(["config", "user.email", "test@test.com"]); + run(["config", "user.name", "Test"]); + // Every time git reads a .dat file's bytes, the counter grows. + const counter = path.join(repo, ".git", "reads"); + const script = `require("fs").appendFileSync(${JSON.stringify(counter)}, "x"); process.stdin.pipe(process.stdout)`; + run(["config", "filter.count.clean", `node -e '${script}'`]); + // As on Windows: a mode, and whether a path is a link, are whatever the index says. + run(["config", "core.filemode", "false"]); + run(["config", "core.symlinks", "false"]); + // Making a link on Windows takes rights a test run may not have. + const links = process.platform !== "win32"; + // `text=auto` reads a changed file's index blob to decide its line endings. + yield* write(".gitattributes", "*.dat filter=count\n*.txt text=auto\n"); + yield* write(".gitignore", "*.log\n"); + yield* write("tracked.txt", "committed\n"); + yield* write("tool.sh", "echo hi\n"); + yield* write("kept.log", "tracked though ignored\n"); + yield* write("old.sh", "echo old\n"); + run(["add", "."]); + run(["add", "-f", "kept.log"]); + run(["update-index", "--chmod=+x", "old.sh"]); + // Committed with Windows line endings, as text=auto would not store them. + yield* write("crlf.txt", "one\r\n"); + const crlfBlob = run(["hash-object", "-w", "--no-filters", "crlf.txt"]).trim(); + run(["update-index", "--add", "--cacheinfo", `100644,${crlfBlob},crlf.txt`]); + run(["commit", "-qm", "initial"]); + // A submodule that is not checked out: only the commit it records. + yield* fileSystem.makeDirectory(path.join(repo, "sub")); + const firstCommit = run(["rev-parse", "HEAD"]).trim(); + run(["update-index", "--add", "--cacheinfo", `160000,${firstCommit},sub`]); + run(["commit", "-qm", "submodule"]); + const reads = () => + fileSystem.readFileString(counter).pipe( + Effect.map((text) => text.length), + Effect.orElseSucceed(() => 0), + ); + + const git: ScratchIndexGit = (args, env, options) => + Effect.try({ + try: () => { + const result = spawnSync("git", args, { + cwd: repo, + env: { ...process.env, ...env }, + encoding: "utf8", + ...(options?.stdin !== undefined ? { input: options.stdin } : {}), + }); + if (result.status !== 0 && options?.allowNonZeroExit !== true) { + throw new Error(`git ${args.join(" ")} exited ${result.status}: ${result.stderr}`); + } + return { + stdout: result.stdout, + ...(result.status !== null ? { exitCode: result.status } : {}), + }; + }, + catch: (error) => new TestFailure({ message: String(error) }), + }); + const { withScratchIndex } = yield* makeScratchIndexes; + const snapshot = withScratchIndex({ + cwd: repo, + purpose: "checkpoint", + tree: "HEAD", + git, + stageCheckout: true, + use: (env) => git(["write-tree"], env).pipe(Effect.map((result) => result.stdout.trim())), + }); + const coldTree = () => { + const env = { GIT_INDEX_FILE: path.join(repo, ".git", "cold-index") }; + run(["read-tree", "HEAD"], env); + run(["add", "-A", "--", "."], env); + return run(["write-tree"], env).trim(); + }; + + // Files never committed: one that stays, one that becomes ignored. + yield* write("data.dat", "never committed\n"); + yield* write("draft.txt", "will be ignored\n"); + yield* write("notes.md", "renamed later by case alone\n"); + yield* write("crlf.txt", "two\n"); + if (links) { + yield* fileSystem.symlink("tracked.txt", path.join(repo, "link.txt")); + } + // Before the tree has a docs folder, under any spelling. + yield* fileSystem.makeDirectory(path.join(repo, "Docs")); + yield* write("Docs/guide.md", "a guide\n"); + // A folder renamed later by case alone, and a nested repository that + // later loses its .git. + yield* fileSystem.makeDirectory(path.join(repo, "notesdir")); + yield* write("notesdir/a.md", "in a folder\n"); + yield* fileSystem.makeDirectory(path.join(repo, "vendor")); + yield* write("vendor/source.txt", "vendored\n"); + execFileSync("git", ["init", "-q"], { cwd: path.join(repo, "vendor") }); + execFileSync("git", ["add", "."], { cwd: path.join(repo, "vendor") }); + execFileSync( + "git", + ["-c", "user.email=t@t.com", "-c", "user.name=T", "commit", "-qm", "vendored"], + { cwd: path.join(repo, "vendor") }, + ); + // Written well before the index, so git need not read it again to be + // sure it did not change in the instant the index was written. + const hourAgo = new Date(Date.now() - 3_600_000); + yield* fileSystem.utimes(path.join(repo, "data.dat"), hourAgo, hourAgo); + yield* snapshot; + const readsAfterFirst = yield* reads(); + expect(readsAfterFirst).toBeGreaterThan(0); + + // The tree gains an ignored file, one never-committed file is now + // ignored, a committed file changes and a new one appears. + yield* write("added.log", "tracked though ignored, after the cache\n"); + run(["add", "-f", "added.log"]); + // The tree also makes a file executable without touching its bytes, + // and moves the submodule to another commit. + run(["update-index", "--chmod=+x", "tool.sh"]); + // The tree stops tracking an executable file that stays on disk, and + // gains a docs folder spelled unlike the one on disk. + run(["rm", "--cached", "-q", "old.sh"]); + const indexBlob = run(["rev-parse", "HEAD:tracked.txt"]).trim(); + run(["update-index", "--add", "--cacheinfo", `100644,${indexBlob},docs/index.md`]); + run(["update-index", "--cacheinfo", `160000,${run(["rev-parse", "HEAD"]).trim()},sub`]); + run(["commit", "-qm", "second"]); + yield* write(".gitignore", "*.log\ndraft.txt\n"); + yield* write("tracked.txt", "edited\n"); + yield* write("fresh.md", "new\n"); + yield* fileSystem.rename(path.join(repo, "notes.md"), path.join(repo, "NOTES.md")); + yield* fileSystem.rename(path.join(repo, "notesdir"), path.join(repo, "NOTESDIR")); + yield* write("NOTESDIR/b.md", "new in the renamed folder\n"); + yield* write("crlf.txt", "three\r\n"); + if (links) { + // A file where a link was. + yield* fileSystem.remove(path.join(repo, "link.txt")); + yield* write("link.txt", "now a file\n"); + } + // The same folder as Docs where names ignore case, another one elsewhere. + yield* fileSystem.makeDirectory(path.join(repo, "docs"), { recursive: true }); + yield* write("docs/index.md", "committed\n"); + yield* fileSystem.remove(path.join(repo, "vendor", ".git"), { recursive: true }); + const tree = yield* snapshot; + + // The unchanged never-committed file was not read again. + expect(yield* reads()).toBe(readsAfterFirst); + expect(tree).toBe(coldTree()); + // Where the docs files land depends on whether the file system ignores case. + const names = run(["ls-tree", "-r", "--name-only", tree]) + .trim() + .split("\n") + .filter((name) => !name.toLowerCase().startsWith("docs/") && name !== "link.txt"); + expect(names).toEqual([ + ".gitattributes", + ".gitignore", + "NOTES.md", + "NOTESDIR/a.md", + "NOTESDIR/b.md", + "added.log", + "crlf.txt", + "data.dat", + "fresh.md", + "kept.log", + "old.sh", + "sub", + "tool.sh", + "tracked.txt", + "vendor/source.txt", + ]); + }).pipe(Effect.provide(NodeServices.layer)), + ); }); diff --git a/apps/server/src/vcs/scratchIndex.ts b/apps/server/src/vcs/scratchIndex.ts index ed4a5e335..a518585bd 100644 --- a/apps/server/src/vcs/scratchIndex.ts +++ b/apps/server/src/vcs/scratchIndex.ts @@ -34,12 +34,19 @@ export const isScratchIndexFileName = (fileName: string): boolean => fileName.startsWith(SCRATCH_INDEX_CACHE_PREFIX) || SCRATCH_INDEX_PURPOSES.some((purpose) => fileName.startsWith(`t3-${purpose}-index-`)); -/** Runs git in the checkout with `env`, failing on a non-zero exit. */ +/** Runs git in the checkout with `env`, failing on a non-zero exit unless allowed. */ export type ScratchIndexGit = ( args: ReadonlyArray, env: NodeJS.ProcessEnv, - options?: { readonly maxOutputBytes?: number }, -) => Effect.Effect<{ readonly stdout: string; readonly stdoutTruncated?: boolean }, GitError>; + options?: { + readonly maxOutputBytes?: number; + readonly stdin?: string; + readonly allowNonZeroExit?: boolean; + }, +) => Effect.Effect< + { readonly stdout: string; readonly stdoutTruncated?: boolean; readonly exitCode?: number }, + GitError +>; /** Output that must be complete to be used; a cut-off listing could leave out a rule. */ const completeOutput = (result: { readonly stdout: string; readonly stdoutTruncated?: boolean }) => @@ -58,6 +65,13 @@ export interface ScratchIndexInput { /** Environment for every git command; `GIT_INDEX_FILE` is added to it. */ readonly env?: NodeJS.ProcessEnv; readonly git: ScratchIndexGit; + /** + * Stage the checkout's changes (`git add -A -- .` from `cwd`) before `use`. + * Run from the checkout's top, the index may then start from the last one + * as it is, files never committed included, so git re-reads only the files + * that changed since. + */ + readonly stageCheckout?: boolean; /** Works in the scratch index, through the environment that selects it. */ readonly use: (env: NodeJS.ProcessEnv) => Effect.Effect; } @@ -141,6 +155,15 @@ const foldersOf = (files: Iterable): ReadonlyArray => { const splitNul = (stdout: string) => stdout.split("\0").filter((entry) => entry.length > 0); +/** The mode git records a symbolic link under. */ +const SYMLINK_MODE = "120000"; + +/** Paths for git's `-z --stdin`. */ +const joinNul = (paths: ReadonlyArray) => paths.map((entry) => `${entry}\0`).join(""); + +/** How git compares paths under `core.ignorecase`: ASCII letters only. */ +const foldAsciiCase = (file: string) => file.replace(/[A-Z]/g, (letter) => letter.toLowerCase()); + /** * The attribute sources git consults for the files a scratch index can stage, * gathered once per operation. Their contents are read by `fingerprintRules`. @@ -154,6 +177,46 @@ interface RuleSources { * checkout's copy is missing. */ readonly indexedAttributes: ReadonlyMap; + /** Every entry the tree holds, repository-relative. */ + readonly treeEntries: ReadonlyArray; + /** + * Every file in the checkout that is neither ignored nor in the tree, + * repository-relative, a nested repository by its folder. + */ + readonly untrackedFiles: ReadonlyArray; +} + +/** A file as git's index or a tree records it: its mode, its object and its path. */ +interface IndexEntry { + readonly mode: string; + readonly oid: string; + readonly path: string; +} + +/** ` \t`, as `ls-tree -z` and `ls-files -s -z` print. */ +const parseEntries = (stdout: string, oidField: 1 | 2): ReadonlyArray => + splitNul(stdout).map((entry) => { + const tab = entry.indexOf("\t"); + const fields = entry.slice(0, tab).split(" "); + return { mode: fields[0] ?? "", oid: fields[oidField] ?? "", path: entry.slice(tab + 1) }; + }); + +/** A path git printed in bytes that are not UTF-8: decoded, it may equal another one. */ +const hasUndecodablePath = (paths: Iterable) => { + for (const file of paths) { + if (file.includes("\uFFFD")) { + return true; + } + } + return false; +}; + +/** The rules a cache is built under, and how git compares paths under them. */ +interface Rules { + readonly fingerprint: string; + readonly ignoreCase: boolean; + /** Sparse checkout: `add -A` leaves files outside the cone alone. */ + readonly sparse: boolean; } /** @@ -172,6 +235,15 @@ interface RuleSources { * which git compares file times against to catch edits made in the instant * the index was written. * + * A checkpoint stages the whole checkout (`stageCheckout` from its top), so + * its index need not start as the tree: it starts as the cache as it is, and + * `add -A` re-reads only what changed, files never committed included + * (`read-tree` drops those, so every checkpoint read them all again). The + * cache is first brought in line with the tree and the ignore rules, so the + * result is the tree a cold build stages; see `stageOverCache`. A path git + * prints in bytes that are not UTF-8 takes the cold path, and a sparse + * checkout loads the tree over the cache as other purposes do. + * * Stat data says nothing about how git turns bytes into a blob, so a cache * only serves the rules it was built under. Its name fingerprints the git * version, the conversion settings, and every attributes file git reads for @@ -195,6 +267,37 @@ export const makeScratchIndexes = Effect.gen(function* () { Effect.orElseSucceed(() => null), ); + /** + * Every file neither ignored nor in `tree`. Listed against an index loaded + * from the tree: against no index at all git checks every committed file + * against the ignore rules too, over twice as slow in a large checkout. + */ + const listUntracked = ( + input: { + readonly git: ScratchIndexGit; + readonly env: NodeJS.ProcessEnv; + readonly gitCommonDir: string; + readonly tree: string | null; + }, + listingEnv: NodeJS.ProcessEnv, + ) => { + const listingIndex = path.join(input.gitCommonDir, scratchIndexFileName("preview")); + const list = input.git( + ["ls-files", "-z", "--full-name", "--others", "--exclude-standard", "--", ":/"], + { ...listingEnv, GIT_INDEX_FILE: listingIndex }, + { maxOutputBytes: LISTING_MAX_OUTPUT_BYTES }, + ); + if (input.tree === null) { + return list; + } + return input + .git(["read-tree", input.tree], { ...input.env, GIT_INDEX_FILE: listingIndex }) + .pipe( + Effect.andThen(list), + Effect.ensuring(fileSystem.remove(listingIndex, { force: true }).pipe(Effect.ignore)), + ); + }; + const readRuleSources = (input: { readonly git: ScratchIndexGit; readonly env: NodeJS.ProcessEnv; @@ -223,34 +326,26 @@ export const makeScratchIndexes = Effect.gen(function* () { : input.git(["ls-tree", "-r", "-z", "--full-tree", input.tree], input.env, { maxOutputBytes: LISTING_MAX_OUTPUT_BYTES, }), - // Against an index that does not exist: every file not ignored. - input.git( - ["ls-files", "-z", "--full-name", "--others", "--exclude-standard", "--", ":/"], - { - ...listingEnv, - GIT_INDEX_FILE: path.join(input.gitCommonDir, scratchIndexFileName("preview")), - }, - { maxOutputBytes: LISTING_MAX_OUTPUT_BYTES }, - ), + listUntracked(input, listingEnv), ], { concurrency: "unbounded" }, ); - const treeEntries = splitNul(yield* completeOutput(treeListing)); - const nonIgnoredFiles = splitNul(yield* completeOutput(fileListing)); - const treeFiles: Array = []; + const treeEntries = parseEntries(yield* completeOutput(treeListing), 2); + // `ls-files --others` names a nested repository by its folder, `sub/`. + const untrackedFiles = splitNul(yield* completeOutput(fileListing)).map((file) => + file.replace(/\/$/, ""), + ); const indexedAttributes = new Map(); for (const entry of treeEntries) { - const tab = entry.indexOf("\t"); - const file = entry.slice(tab + 1); - treeFiles.push(file); - if (file === ".gitattributes" || file.endsWith("/.gitattributes")) { - indexedAttributes.set(path.join(input.toplevel, file), entry.split(" ")[2] ?? ""); + if (entry.path === ".gitattributes" || entry.path.endsWith("/.gitattributes")) { + indexedAttributes.set(path.join(input.toplevel, entry.path), entry.oid); } } - const inTreeAttributes = foldersOf([...treeFiles, ...nonIgnoredFiles]).map((folder) => - path.join(input.toplevel, folder, ".gitattributes"), - ); + const inTreeAttributes = foldersOf([ + ...treeEntries.map((entry) => entry.path), + ...untrackedFiles, + ]).map((folder) => path.join(input.toplevel, folder, ".gitattributes")); // Git reads relative paths from its own working directory. const globalFiles = @@ -273,6 +368,8 @@ export const makeScratchIndexes = Effect.gen(function* () { ...systemFiles, ], indexedAttributes, + treeEntries, + untrackedFiles, } satisfies RuleSources; }).pipe(Effect.orElseSucceed(() => null)); @@ -345,6 +442,8 @@ export const makeScratchIndexes = Effect.gen(function* () { if (cacheUnsafe(settings, input.env)) { return null; } + const ignoreCase = lastValue(settings, "core.ignorecase"); + const sparse = lastValue(settings, "core.sparsecheckout"); const attributes = sources.attributeFiles.flatMap((file, index) => { const hash = hashes[index] ?? null; if (hash !== null) { @@ -353,19 +452,23 @@ export const makeScratchIndexes = Effect.gen(function* () { const indexed = sources.indexedAttributes.get(file); return indexed === undefined ? [] : [[file, `tree:${indexed}`]]; }); - return createHash("sha256") - .update( - JSON.stringify([ - sources.version, - settings.filter(([key]) => CONVERSION_SETTING.test(key)), - attributes, - ]), - ) - .digest("hex") - .slice(0, 16); - }).pipe(Effect.orElseSucceed(() => null)); - - /** Removes the checkout's caches built under other rules. */ + return { + fingerprint: createHash("sha256") + .update( + JSON.stringify([ + sources.version, + settings.filter(([key]) => CONVERSION_SETTING.test(key)), + attributes, + ]), + ) + .digest("hex") + .slice(0, 16), + ignoreCase: ignoreCase !== undefined && parseGitBool(ignoreCase[1]) === true, + sparse: sparse !== undefined && parseGitBool(sparse[1]) !== false, + } satisfies Rules; + }).pipe(Effect.orElseSucceed((): Rules | null => null)); + + /** Removes the checkout's other caches: built under other rules, or over another tree. */ const removeOtherCaches = (gitDir: string, keep: string) => fileSystem.readDirectory(gitDir).pipe( Effect.flatMap((names) => @@ -383,18 +486,29 @@ export const makeScratchIndexes = Effect.gen(function* () { ): Effect.Effect => Effect.gen(function* () { const baseEnv = input.env ?? {}; - const dirs = yield* input.git( - ["rev-parse", "--show-toplevel", "--git-dir", "--git-common-dir"], + // The tree's own id last: a cache names the tree it was staged over. + const revParse = yield* input.git( + [ + "rev-parse", + "--show-toplevel", + "--git-dir", + "--git-common-dir", + "--show-prefix", + ...(input.tree !== null ? [`${input.tree}^{tree}`] : []), + ], baseEnv, ); - const [toplevel, gitDir, gitCommonDir] = dirs.stdout - .split("\n") - .map((line) => line.replace(/\r$/, "")) + const lines = revParse.stdout.split("\n").map((line) => line.replace(/\r$/, "")); + const [toplevel, gitDir, gitCommonDir] = lines + .slice(0, 3) .filter((line) => line.length > 0) .map((dir) => path.resolve(input.cwd, dir)); if (toplevel === undefined || gitDir === undefined || gitCommonDir === undefined) { return yield* Effect.die(new Error("git rev-parse did not print the checkout's dirs.")); } + // Empty at the checkout's top: there `add -A -- .` stages all of it. + const stagesWholeCheckout = input.stageCheckout === true && (lines[3] ?? "") === ""; + const treeId = input.tree === null ? null : lines[4] || null; const indexPath = path.join(gitCommonDir, scratchIndexFileName(input.purpose)); const env: NodeJS.ProcessEnv = { ...baseEnv, GIT_INDEX_FILE: indexPath }; const removeIndex = fileSystem.remove(indexPath, { force: true }).pipe(Effect.ignore); @@ -407,49 +521,239 @@ export const makeScratchIndexes = Effect.gen(function* () { tree: input.tree, }); const rules = sources === null ? null : yield* fingerprintRules(rulesInput, sources); - const cacheName = rules === null ? null : `${SCRATCH_INDEX_CACHE_PREFIX}${rules}`; + const cachePrefix = + rules === null ? null : `${SCRATCH_INDEX_CACHE_PREFIX}${rules.fingerprint}`; + // A checkpoint's cache names the tree it was staged over: a file it + // holds that is not in that tree went in as a new file. + const cacheName = + cachePrefix === null + ? null + : stagesWholeCheckout && treeId !== null + ? `${cachePrefix}-${treeId}` + : cachePrefix; + + /** The checkout's cache under these rules, and the tree it was staged over when known. */ + const findCache = Effect.gen(function* () { + if (cachePrefix === null) { + return null; + } + const names = yield* fileSystem + .readDirectory(gitDir) + .pipe(Effect.orElseSucceed((): ReadonlyArray => [])); + const name = + names.find((entry) => entry === cacheName) ?? + names.find((entry) => entry === cachePrefix || entry.startsWith(`${cachePrefix}-`)); + if (name === undefined) { + return null; + } + const stagedOver = name.slice(cachePrefix.length + 1); + return { + path: path.join(gitDir, name), + stagedOver: stagedOver.length > 0 ? stagedOver : null, + }; + }); - const loadTree = (warmFrom: string | null) => + const stage = input.git(["add", "-A", "--", "."], env); + const listing = (args: ReadonlyArray) => + input + .git(args, env, { maxOutputBytes: LISTING_MAX_OUTPUT_BYTES }) + .pipe(Effect.flatMap(completeOutput)); + + /** + * Stages the whole checkout over the cache, keeping only what a cold + * build would stage the same way, so files never committed keep their + * stat data too. False when it could not be done and the index must + * be built cold. + * + * A cold build stages over the tree's entries, so a tree path keeps + * the cache's entry only when it is the tree's (as `read-tree -m` + * keeps it): git reads a changed file's index blob to decide line + * endings, and keeps a mode under `core.filemode=false` and a + * submodule's commit while it is not checked out. A cold build stages + * any other file as new, so the cache's entry for one stays only when + * it went in as new and is still what git would stage: listed under + * the same name (a nested repository that lost its .git lists its + * files instead), not in the tree the cache was staged over, and not + * under another spelling of a tree folder. Everything else git reads + * again. + */ + const stageOverCache = ( + cache: { readonly path: string; readonly stagedOver: string | null }, + tree: string, + ruleSources: RuleSources, + ruleSet: Rules, + ) => Effect.gen(function* () { - if (input.tree === null) { + const prepared = yield* Effect.gen(function* () { + yield* fileSystem.link(cache.path, indexPath); + const cached = parseEntries(yield* listing(["ls-files", "-s", "-z"]), 1); + if ( + hasUndecodablePath(cached.map((entry) => entry.path)) || + hasUndecodablePath(ruleSources.treeEntries.map((entry) => entry.path)) || + hasUndecodablePath(ruleSources.untrackedFiles) + ) { + return null; + } + const inTree = new Map(ruleSources.treeEntries.map((entry) => [entry.path, entry])); + const untracked = new Set(ruleSources.untrackedFiles); + const extras = cached.filter((entry) => !inTree.has(entry.path)); + // Unknown, or staged over another tree: what that tree held went in as tracked. + const leftTree = + extras.length === 0 || cache.stagedOver === tree + ? new Set() + : cache.stagedOver === null + ? null + : new Set( + splitNul( + yield* listing([ + "diff-tree", + "-r", + "-z", + "--name-only", + "--diff-filter=D", + cache.stagedOver, + tree, + ]), + ), + ); + // Under `core.ignorecase` git files a new file under the spelling + // of its folder the index already has, which in a cold build is + // the tree's or the first one staged: keep a cached file only + // where its folders are spelled one way. + const spellings = new Map>(); + if (ruleSet.ignoreCase) { + for (const folder of foldersOf([...inTree.keys(), ...untracked])) { + const folded = foldAsciiCase(folder); + spellings.set(folded, (spellings.get(folded) ?? new Set()).add(folder)); + } + } + const respelledFolder = (file: string) => + ruleSet.ignoreCase && + foldersOf([file]).some((folder) => { + const spelled = spellings.get(foldAsciiCase(folder)); + return spelled !== undefined && (spelled.size > 1 || !spelled.has(folder)); + }); + const drop = extras + .filter( + (entry) => + leftTree === null || + leftTree.has(entry.path) || + !untracked.has(entry.path) || + // Under `core.symlinks=false` git keeps a link's type for + // the file that replaces it. + entry.mode === SYMLINK_MODE || + respelledFolder(entry.path), + ) + .map((entry) => entry.path); + const cachedByPath = new Map(cached.map((entry) => [entry.path, entry])); + const fromTree = ruleSources.treeEntries.filter((entry) => { + const inCache = cachedByPath.get(entry.path); + return ( + inCache === undefined || inCache.mode !== entry.mode || inCache.oid !== entry.oid + ); + }); + if (drop.length > 0) { + yield* input.git(["update-index", "--force-remove", "-z", "--stdin"], env, { + stdin: joinNul(drop), + }); + } + if (fromTree.length > 0) { + yield* input.git(["update-index", "-z", "--index-info"], env, { + stdin: fromTree + .map((entry) => `${entry.mode} ${entry.oid}\t${entry.path}\0`) + .join(""), + }); + } + const dropped = new Set(drop); + return extras.map((entry) => entry.path).filter((file) => !dropped.has(file)); + }).pipe(Effect.orElseSucceed(() => null)); + if (prepared === null) { return false; } - const tree = input.tree; - const warm = - warmFrom !== null && - (yield* fileSystem.link(warmFrom, indexPath).pipe( - Effect.andThen(input.git(["read-tree", "-m", "-i", tree], env)), - Effect.as(true), - Effect.orElseSucceed(() => false), - )); - if (!warm) { - yield* removeIndex; - yield* input.git(["read-tree", tree], env); + // A failure here is the checkout's, not the cache's: a cold build would meet it too. + yield* stage; + if (prepared.length === 0) { + return true; + } + // An ignore rule added since the listing: a cold build would not stage the file now. + return yield* Effect.gen(function* () { + const result = yield* input.git(["check-ignore", "--no-index", "-z", "--stdin"], env, { + stdin: joinNul(prepared), + allowNonZeroExit: true, + }); + // 1: none of them is ignored. Anything else is git failing. + if (result.exitCode !== undefined && result.exitCode !== 0 && result.exitCode !== 1) { + return false; + } + const ignored = splitNul(result.stdout); + if (ignored.length > 0) { + yield* input.git(["update-index", "--force-remove", "-z", "--stdin"], env, { + stdin: joinNul(ignored), + }); + } + return true; + }).pipe(Effect.orElseSucceed(() => false)); + }); + + /** Builds the index, from the cache when there is a usable one; true when it was. */ + const build = ( + warmFrom: { readonly path: string; readonly stagedOver: string | null } | null, + ) => + Effect.gen(function* () { + if (warmFrom !== null && input.tree !== null) { + if (stagesWholeCheckout && sources !== null && rules !== null && !rules.sparse) { + if (treeId !== null && (yield* stageOverCache(warmFrom, treeId, sources, rules))) { + return true; + } + } else { + const loaded = yield* fileSystem.link(warmFrom.path, indexPath).pipe( + Effect.andThen(input.git(["read-tree", "-m", "-i", input.tree], env)), + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + if (loaded) { + if (input.stageCheckout === true) { + yield* stage; + } + return true; + } + } + } + yield* removeIndex; + if (input.tree !== null) { + yield* input.git(["read-tree", input.tree], env); } - return warm; + if (input.stageCheckout === true) { + yield* stage; + } + return false; }); return yield* Effect.gen(function* () { - const cachePath = cacheName === null ? null : path.join(gitDir, cacheName); - const warm = yield* loadTree(cachePath); - const result = yield* input.use(env); - if (sources === null || cacheName === null || cachePath === null) { + const warm = yield* build(yield* findCache); + // A cached entry may name an object git has since pruned (a snapshot + // of a deleted thread, a diff never committed): only a cold build + // writes every object again. + const result = yield* warm && stagesWholeCheckout + ? input + .use(env) + .pipe(Effect.catch(() => build(null).pipe(Effect.andThen(input.use(env))))) + : input.use(env); + if (sources === null || rules === null || cacheName === null) { return result; } - if ((yield* fingerprintRules(rulesInput, sources)) !== rules) { + if ((yield* fingerprintRules(rulesInput, sources))?.fingerprint !== rules.fingerprint) { // The rules moved while git staged under them: a warm index may // hold blobs from the old ones. Only a cold index is trusted. if (!warm) { return result; } - yield* loadTree(null); + yield* build(null); return yield* input.use(env); } // Last writer wins; any index built under these rules is a valid cache. - yield* fileSystem.rename(indexPath, cachePath).pipe(Effect.ignore); - if (!warm) { - yield* removeOtherCaches(gitDir, cacheName); - } + yield* fileSystem.rename(indexPath, path.join(gitDir, cacheName)).pipe(Effect.ignore); + yield* removeOtherCaches(gitDir, cacheName); return result; }).pipe(Effect.ensuring(removeIndex)); }); diff --git a/docs/telemetry.md b/docs/telemetry.md index 42905b2c4..717483cfe 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -38,7 +38,8 @@ Threadlines sends product and reliability events such as: - how long a sent message waited, in milliseconds, before Threadlines handed it to the agent and before the agent's first output, how much of the first wait went to each step (waiting behind the chat's earlier work, getting the agent - ready, saving the code snapshot), whether the agent had to + ready, saving the code snapshot), whether that snapshot failed to save, + whether the agent had to start up for it, and whether it was started early while you typed. When it was started for the message or early, also how long that start took and what kind of start it was (a new conversation, an existing one reopened, or a diff --git a/packages/contracts/src/provider.ts b/packages/contracts/src/provider.ts index 2c9ab5d5c..bdf836eee 100644 --- a/packages/contracts/src/provider.ts +++ b/packages/contracts/src/provider.ts @@ -293,12 +293,14 @@ export type ProviderTurnOrigin = typeof ProviderTurnOrigin.Type; * How long the steps before the agent gets a message took, for usage analytics * only. `queueMs`: waiting behind the thread's earlier work. `prepareMs`: getting * the agent ready, its startup included when it had to start. `checkpointMs`: - * saving the code snapshot the turn is measured against. + * saving the code snapshot the turn is measured against. `checkpointFailed`: + * that snapshot was not saved, so the wait bought nothing. */ export const ProviderTurnHandoffSteps = Schema.Struct({ queueMs: NonNegativeInt, prepareMs: NonNegativeInt, checkpointMs: NonNegativeInt, + checkpointFailed: Schema.optional(Schema.Boolean), }); export type ProviderTurnHandoffSteps = typeof ProviderTurnHandoffSteps.Type;