Skip to content

Commit 9c82541

Browse files
committed
perf(server): a new worktree's code index starts from its main checkout's
1 parent b7fd440 commit 9c82541

2 files changed

Lines changed: 122 additions & 9 deletions

File tree

‎apps/server/src/project/knowledge/CodeIntelligence.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1283,6 +1283,49 @@ it.effect("indexes a worktree for its active agent and never merely because it i
12831283
),
12841284
);
12851285

1286+
it.effect("starts a linked worktree's first index from its main checkout's", () =>
1287+
withFixture((fixture) =>
1288+
Effect.gen(function* () {
1289+
// Git reports physical paths, and the main checkout's index is keyed by its path.
1290+
const root = NodeFS.realpathSync(fixture.root);
1291+
const linked = NodePath.join(NodeFS.realpathSync(fixture.worktree), "linked");
1292+
const git = (...args: ReadonlyArray<string>) =>
1293+
NodeChildProcess.execFileSync(
1294+
"git",
1295+
["-c", "user.email=t3@example.com", "-c", "user.name=T3", ...args],
1296+
{ cwd: root, encoding: "utf8" },
1297+
);
1298+
git("init", "--quiet");
1299+
git("add", "--all");
1300+
git("commit", "--quiet", "-m", "fixture");
1301+
git("worktree", "add", "--quiet", "--detach", linked);
1302+
yield* Effect.promise(() =>
1303+
NodeFSP.writeFile(
1304+
NodePath.join(linked, "src/work.ts"),
1305+
"export function workOnly() { return 2; }\n",
1306+
),
1307+
);
1308+
const worktree = { threadId: worktreeThreadId, path: linked };
1309+
// The worktree lists only its new file, so `greet` can only come from the main checkout's.
1310+
const { run, refresh, indexRoot } = yield* checkoutService(
1311+
root,
1312+
(cwd) => (cwd === linked ? ["src/work.ts"] : ["src/defs.ts"]),
1313+
{ worktree, repository: true },
1314+
);
1315+
assert.deepEqual(yield* refresh(), { _tag: "Published", generation: 1 });
1316+
1317+
assert.deepEqual(yield* refresh(worktreeThreadId), { _tag: "Published", generation: 1 });
1318+
assert.equal(yield* indexedSymbolCount(indexRoot(linked), "greet"), 1);
1319+
const own = yield* run({ operation: "symbols", name: "workOnly" }, worktreeThreadId);
1320+
assert.ok(own.nodes.some((node) => node.path === "src/work.ts"));
1321+
// The main checkout's own index is untouched and still serves.
1322+
const main = yield* run({ operation: "freshness" });
1323+
assert.equal(main.index?.generation, 1);
1324+
assert.equal(main.index?.state, "ready");
1325+
}),
1326+
),
1327+
);
1328+
12861329
it.effect("leaves a worktree index stale until its agent acts again", () =>
12871330
withFixture((fixture) =>
12881331
Effect.gen(function* () {

‎apps/server/src/project/knowledge/codeIntelligenceWorker.ts‎

Lines changed: 79 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,11 @@ import type {
3636
import {
3737
CHECKOUT_CONFIG_ENTRIES,
3838
clearCheckoutSources,
39+
generationDirectory,
40+
indexRootFor,
3941
linkCheckoutSources,
4042
} from "./codeIndexLayout.ts";
43+
import { pinPublishedGeneration } from "./codeIndexLocks.ts";
4144

4245
const CATALOG_REVISION = "@colbymchenry/codegraph@1.6.2";
4346
// Programming languages outside the SDK's catalog, which it reports as unknown like any asset.
@@ -318,6 +321,53 @@ function headCommit(checkoutPath: string): string | null {
318321
}
319322
}
320323

324+
/** The repository's main checkout when `checkoutPath` is a linked worktree of one. */
325+
function mainCheckoutOf(checkoutPath: string): string | null {
326+
try {
327+
const [gitDir, commonDir] = NodeChildProcess.execFileSync(
328+
"git",
329+
["rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir"],
330+
{ cwd: checkoutPath, encoding: "utf8", timeout: 2_000, stdio: ["ignore", "pipe", "ignore"] },
331+
)
332+
.trim()
333+
.split("\n");
334+
// A bare repository's worktrees have no main checkout to share an index with.
335+
if (!gitDir || !commonDir || gitDir === commonDir || NodePath.basename(commonDir) !== ".git")
336+
return null;
337+
return NodePath.dirname(commonDir);
338+
} catch {
339+
return null;
340+
}
341+
}
342+
343+
interface SeedGeneration {
344+
readonly indexRoot: string;
345+
readonly directory: string;
346+
readonly release: () => void;
347+
}
348+
349+
/**
350+
* The main checkout's published generation, pinned against retirement, for a linked worktree
351+
* that has none yet. Its paths are checkout-relative, so the worktree only re-parses what differs.
352+
*/
353+
function pinMainCheckoutGeneration(input: CodeIndexBuildInput): SeedGeneration | null {
354+
const main = mainCheckoutOf(input.checkoutPath);
355+
if (main === null) return null;
356+
const indexRoot = indexRootFor(NodePath.dirname(input.indexRoot), main);
357+
if (indexRoot === input.indexRoot) return null;
358+
let pin: ReturnType<typeof pinPublishedGeneration>;
359+
try {
360+
pin = pinPublishedGeneration(indexRoot);
361+
} catch {
362+
return null;
363+
}
364+
if (pin.generation === null) {
365+
pin.release();
366+
return null;
367+
}
368+
return { indexRoot, directory: generationDirectory(pin.generation), release: pin.release };
369+
}
370+
321371
// Mirrors the SDK's file limit: it never parses a larger file and stores a hash of a size
322372
// stamp in place of its content.
323373
const MAX_SOURCE_FILE_SIZE_BYTES = 1024 * 1024;
@@ -671,9 +721,10 @@ function hasUnauthorizedFiles(checkoutPath: string, graph: CodeGraphInstance): b
671721
}
672722

673723
/**
674-
* Builds the generation `input.to` from a copy of the published one, or from scratch, and reports
675-
* whether it differs from the published one. An unchanged checkout is detected before anything is
676-
* copied, and then `input.to` is never created.
724+
* Builds the generation `input.to` from a copy of the published one, from a copy of the main
725+
* checkout's when a linked worktree has none, or from scratch, and reports whether it differs from
726+
* the published one. An unchanged checkout is detected before anything is copied, and then
727+
* `input.to` is never created.
677728
*/
678729
export async function buildIndexInWorker(
679730
input: CodeIndexBuildInput,
@@ -721,24 +772,43 @@ export async function buildIndexInWorker(
721772
const target = NodePath.join(input.indexRoot, input.to);
722773
// Exclusive: a leftover entry, link or not, fails the build instead of being written through.
723774
NodeFS.mkdirSync(target);
724-
if (from !== null) {
775+
let copied = false;
776+
const copyDatabase = (sourceRoot: string, sourceDirectory: string) => {
725777
for (const name of INDEX_DATABASE_FILES) {
726-
const source = NodePath.join(input.indexRoot, from, name);
778+
const source = NodePath.join(sourceRoot, sourceDirectory, name);
727779
if (NodeFS.existsSync(source)) {
728780
NodeFS.copyFileSync(
729781
source,
730782
NodePath.join(target, name),
731783
// FICLONE falls back to a normal copy where reflinks are unavailable.
732784
NodeFS.constants.COPYFILE_EXCL | NodeFS.constants.COPYFILE_FICLONE,
733785
);
786+
copied = true;
787+
}
788+
}
789+
};
790+
if (from !== null) {
791+
copyDatabase(input.indexRoot, from);
792+
} else {
793+
const seed = pinMainCheckoutGeneration(input);
794+
if (seed !== null) {
795+
try {
796+
const meta = readIndexMeta(seed.indexRoot, seed.directory);
797+
// The same rules that let a successor inherit its predecessor's files.
798+
if (
799+
meta.configurationDigest === configurationDigest &&
800+
(!isListingTruncated(input) || meta.ranked)
801+
)
802+
copyDatabase(seed.indexRoot, seed.directory);
803+
} finally {
804+
seed.release();
734805
}
735806
}
736807
}
737808
useIndexDirectory(input.to);
738-
let graph =
739-
from !== null
740-
? await CodeGraph.open(input.indexRoot, { sync: false })
741-
: await CodeGraph.init(input.indexRoot, { index: false });
809+
let graph = copied
810+
? await CodeGraph.open(input.indexRoot, { sync: false })
811+
: await CodeGraph.init(input.indexRoot, { index: false });
742812
try {
743813
if (hasUnauthorizedFiles(input.checkoutPath, graph)) {
744814
graph.close();

0 commit comments

Comments
 (0)