TypeScript
perf(server): cut fff-node FFI marshaling overhead on large workspaces (#18514)
Max Weinbach6e5322b6cf37
diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.native.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.native.test.tsnew file mode 100644index 00000000000..973bf293905--- /dev/null+++ b/apps/server/src/workspace/WorkspaceSearchIndex.native.test.ts@@ -0,0 +1,115 @@+import * as NodeModule from "node:module";+import type { Result } from "@ff-labs/fff-node";+import * as NodeServices from "@effect/platform-node/NodeServices";+import { expect, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Path from "effect/Path";++// Use the same require export as WorkspaceSearchIndex, with the actual native library.+const requireForFff = NodeModule.createRequire(import.meta.url);+const { FileFinder } = requireForFff("@ff-labs/fff-node") as typeof import("@ff-labs/fff-node");++function valueOf<T>(result: Result<T>): T {+ if (!result.ok) throw new Error(result.error);+ return result.value;+}++it.effect("decodes native search and grep strings and keeps scores only through 200 results", () =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const basePath = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-fff-native-" });+ const names = [+ ...Array.from({ length: 205 }, (_, index) => `file-${String(index).padStart(3, "0")}`),+ "日本語",+ "café",+ "emoji-🦊",+ ];+ const relativePaths = names.map((name) => `${name}/${name}.ts`);+ const content = "prefix marker-日本語🦊\n";+ yield* Effect.forEach(+ names,+ (name) =>+ Effect.gen(function* () {+ yield* fileSystem.makeDirectory(path.join(basePath, name));+ yield* fileSystem.writeFileString(path.join(basePath, name, `${name}.ts`), content);+ }),+ { concurrency: "unbounded" },+ );+ expect(requireForFff.resolve("@ff-labs/fff-node").replaceAll("\\", "/")).toMatch(+ /\/dist\/index\.js$/u,+ );+ const finder = yield* Effect.acquireRelease(+ Effect.sync(() =>+ valueOf(FileFinder.create({ basePath, disableWatch: true, disableMmapCache: true })),+ ),+ (finder) => Effect.sync(() => finder.destroy()),+ );+ expect(valueOf(yield* Effect.promise(() => finder.waitForIndexReady(10_000)))).toBe(true);++ const files200 = valueOf(finder.fileSearch("", { pageSize: 200 }));+ const files201 = valueOf(finder.fileSearch("", { pageSize: 201 }));+ expect(files200.items).toHaveLength(200);+ expect(files200.scores).toHaveLength(200);+ expect(files201.items).toHaveLength(201);+ expect(files201.scores).toEqual([]);+ expect(files201.items.slice(0, 200)).toEqual(files200.items);+ const files = valueOf(finder.fileSearch("", { pageSize: 1000 }));+ expect(files.items.map((item) => item.relativePath.normalize("NFC")).toSorted()).toEqual(+ relativePaths.toSorted(),+ );+ for (const item of files.items) {+ expect(item.fileName.normalize("NFC")).toBe(+ path.basename(item.relativePath).normalize("NFC"),+ );+ expect(item.size).toBe(Buffer.byteLength(content));+ expect(Number.isFinite(item.modified)).toBe(true);+ }+ const exact = valueOf(finder.fileSearch("日本語.ts", { pageSize: 1 }));+ expect(exact.items[0]?.fileName.normalize("NFC")).toBe("日本語.ts");+ expect(exact.scores[0]).toMatchObject({ exactMatch: true, matchType: "exact_filename" });++ const dirs200 = valueOf(finder.directorySearch("", { pageSize: 200 }));+ const dirs201 = valueOf(finder.directorySearch("", { pageSize: 201 }));+ expect(dirs200.scores).toHaveLength(200);+ expect(dirs201.items).toHaveLength(201);+ expect(dirs201.scores).toEqual([]);+ expect(dirs201.items.slice(0, 200)).toEqual(dirs200.items);+ const directories = valueOf(finder.directorySearch("", { pageSize: 1000 }));+ expect(+ directories.items+ .map((item) => item.relativePath.normalize("NFC"))+ .filter(Boolean)+ .toSorted(),+ ).toEqual(names.map((name) => `${name}/`).toSorted());++ const mixed200 = valueOf(finder.mixedSearch("", { pageSize: 200 }));+ const mixed201 = valueOf(finder.mixedSearch("", { pageSize: 201 }));+ expect(mixed200.scores).toHaveLength(200);+ expect(mixed201.items).toHaveLength(201);+ expect(mixed201.scores).toEqual([]);+ expect(mixed201.items.slice(0, 200)).toEqual(mixed200.items);+ const mixed = valueOf(finder.mixedSearch("", { pageSize: 1000 }));+ expect(mixed.items.filter((item) => item.type === "file").map(({ item }) => item)).toEqual(+ files.items,+ );+ expect(mixed.items.filter((item) => item.type === "directory").map(({ item }) => item)).toEqual(+ directories.items,+ );++ const grep = valueOf(finder.grep("marker", { mode: "plain", pageSize: 1000 }));+ expect(grep.items.map((item) => item.relativePath.normalize("NFC")).toSorted()).toEqual(+ relativePaths.toSorted(),+ );+ for (const item of grep.items) {+ expect(item.fileName.normalize("NFC")).toBe(+ path.basename(item.relativePath).normalize("NFC"),+ );+ expect(item.lineContent).toBe(content.trimEnd());+ expect(item.lineNumber).toBe(1);+ expect(item.col).toBe(7);+ expect(item.matchRanges).toEqual([[7, 13]]);+ }+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+);diff --git a/patches/@[email protected] b/patches/@[email protected]index d3db2152544..76e45e152a5 100644--- a/patches/@[email protected]+++ b/patches/@[email protected]@@ -1,5 +1,4 @@diff --git a/package.json b/package.json-index e000a78..8432546 100644--- a/package.json+++ b/package.json@@ -11,7 +11,7 @@@@ -11,8 +10,37 @@ index e000a78..8432546 100644"default": "./dist/index.js"},"./package.json": "./package.json"+diff --git a/dist/fff-api.d.ts b/dist/fff-api.d.ts+--- a/dist/fff-api.d.ts++++ b/dist/fff-api.d.ts+@@ -199,7 +199,7 @@ export type Location = {+ export interface SearchResult {+ /** Matched file items */+ items: FileItem[];+- /** Corresponding scores for each item */++ /** Corresponding scores for each item. Empty when the page has more than 200 items (patched in T3 Code to skip per-item score FFI calls). */+ scores: Score[];+ /** Total number of files that matched */+ totalMatched: number;+@@ -238,7 +238,7 @@ export interface DirSearchOptions {+ export interface DirSearchResult {+ /** Matched directory items */+ items: DirItem[];+- /** Corresponding scores for each item */++ /** Corresponding scores for each item. Empty when the page has more than 200 items (patched in T3 Code to skip per-item score FFI calls). */+ scores: Score[];+ /** Total number of directories that matched */+ totalMatched: number;+@@ -262,7 +262,7 @@ export type MixedItem = {+ export interface MixedSearchResult {+ /** Matched items (files and directories interleaved by score) */+ items: MixedItem[];+- /** Corresponding scores for each item */++ /** Corresponding scores for each item. Empty when the page has more than 200 items (patched in T3 Code to skip per-item score FFI calls). */+ scores: Score[];+ /** Total number of items (files + dirs) that matched */+ totalMatched: number;diff --git a/dist/index.js b/dist/index.js-index 7c1d722..1d0bc27 100644--- a/dist/index.js+++ b/dist/index.js@@ -1,7 +1,7 @@@@ -50,3 +78,188 @@ index 7c1d722..1d0bc27 100644}} catch {}+@@ -262,6 +272,7 @@ function snakeToCamel(obj) {+ return result;+ }+ function readCString(ptr) {++ if (typeof ptr === "string") return ptr;+ if (isNullPointer(ptr)) return null;+ try {+ const [str] = restorePointer({+@@ -426,9 +437,9 @@ function ffiDestroy(handle) {+ });+ }+ var FFF_FILE_ITEM_STRUCT = {+- relative_path: DataType.External,+- file_name: DataType.External,+- git_status: DataType.External,++ relative_path: DataType.String,++ file_name: DataType.String,++ git_status: DataType.String,+ size: DataType.U64,+ modified: DataType.U64,+ access_frecency_score: DataType.I64,+@@ -445,8 +456,9 @@ var FFF_SCORE_STRUCT = {+ distance_penalty: DataType.I32,+ current_file_penalty: DataType.I32,+ combo_match_boost: DataType.I32,++ path_alignment_bonus: DataType.I32,+ exact_match: DataType.U8,+- match_type: DataType.External++ match_type: DataType.String+ };+ var FFF_SEARCH_RESULT_STRUCT = {+ items: DataType.External,+@@ -462,8 +474,8 @@ var FFF_SEARCH_RESULT_STRUCT = {+ location_end_col: DataType.I32+ };+ var FFF_DIR_ITEM_STRUCT = {+- relative_path: DataType.External,+- dir_name: DataType.External,++ relative_path: DataType.String,++ dir_name: DataType.String,+ max_access_frecency: DataType.I32+ };+ var FFF_DIR_SEARCH_RESULT_STRUCT = {+@@ -475,9 +487,9 @@ var FFF_DIR_SEARCH_RESULT_STRUCT = {+ };+ var FFF_MIXED_ITEM_STRUCT = {+ item_type: DataType.U8,+- relative_path: DataType.External,+- display_name: DataType.External,+- git_status: DataType.External,++ relative_path: DataType.String,++ display_name: DataType.String,++ git_status: DataType.String,+ size: DataType.U64,+ modified: DataType.U64,+ access_frecency_score: DataType.I64,+@@ -500,10 +512,10 @@ var FFF_MIXED_SEARCH_RESULT_STRUCT = {+ location_end_col: DataType.I32+ };+ var FFF_GREP_MATCH_STRUCT = {+- relative_path: DataType.External,+- file_name: DataType.External,+- git_status: DataType.External,+- line_content: DataType.External,++ relative_path: DataType.String,++ file_name: DataType.String,++ git_status: DataType.String,++ line_content: DataType.String,+ match_ranges: DataType.External,+ context_before: DataType.External,+ context_after: DataType.External,+@@ -598,18 +610,13 @@ function readMixedItemFromRaw(raw) {+ }+ function callAccessor(funcName, resultPtr, index, structDef) {+ loadLibrary();+- const elemPtr = load({++ return load({+ library: LIBRARY_KEY,+ funcName,+- retType: DataType.External,++ retType: structDef,+ paramsType: [DataType.External, DataType.U32],+ paramsValue: [resultPtr, index]+ });+- const [raw] = restorePointer({+- retType: [structDef],+- paramsValue: wrapPointer([elemPtr])+- });+- return raw;+ }+ function ptrOffset(base, bytes) {+ return load({+@@ -766,6 +773,7 @@ function parseSearchResult(rawPtr) {+ }+ const items = [];+ const scores = [];++ const includeScores = count <= 200;+ for (let i = 0; i < count; i++) {+ const rawItem = callAccessor(+ "fff_search_result_get_item",+@@ -774,13 +782,15 @@ function parseSearchResult(rawPtr) {+ FFF_FILE_ITEM_STRUCT+ );+ items.push(readFileItemFromRaw(rawItem));+- const rawScore = callAccessor(+- "fff_search_result_get_score",+- handlePtr,+- i,+- FFF_SCORE_STRUCT+- );+- scores.push(readScoreFromRaw(rawScore));++ if (includeScores) {++ const rawScore = callAccessor(++ "fff_search_result_get_score",++ handlePtr,++ i,++ FFF_SCORE_STRUCT++ );++ scores.push(readScoreFromRaw(rawScore));++ }+ }+ load({+ library: LIBRARY_KEY,+@@ -824,6 +834,7 @@ function parseDirSearchResult(rawPtr) {+ const count = sr.count;+ const items = [];+ const scores = [];++ const includeScores = count <= 200;+ for (let i = 0; i < count; i++) {+ const rawItem = callAccessor(+ "fff_dir_search_result_get_item",+@@ -832,13 +843,15 @@ function parseDirSearchResult(rawPtr) {+ FFF_DIR_ITEM_STRUCT+ );+ items.push(readDirItemFromRaw(rawItem));+- const rawScore = callAccessor(+- "fff_dir_search_result_get_score",+- handlePtr,+- i,+- FFF_SCORE_STRUCT+- );+- scores.push(readScoreFromRaw(rawScore));++ if (includeScores) {++ const rawScore = callAccessor(++ "fff_dir_search_result_get_score",++ handlePtr,++ i,++ FFF_SCORE_STRUCT++ );++ scores.push(readScoreFromRaw(rawScore));++ }+ }+ load({+ library: LIBRARY_KEY,+@@ -897,6 +910,7 @@ function parseMixedSearchResult(rawPtr) {+ }+ const items = [];+ const scores = [];++ const includeScores = count <= 200;+ for (let i = 0; i < count; i++) {+ const rawItem = callAccessor(+ "fff_mixed_search_result_get_item",+@@ -905,13 +919,15 @@ function parseMixedSearchResult(rawPtr) {+ FFF_MIXED_ITEM_STRUCT+ );+ items.push(readMixedItemFromRaw(rawItem));+- const rawScore = callAccessor(+- "fff_mixed_search_result_get_score",+- handlePtr,+- i,+- FFF_SCORE_STRUCT+- );+- scores.push(readScoreFromRaw(rawScore));++ if (includeScores) {++ const rawScore = callAccessor(++ "fff_mixed_search_result_get_score",++ handlePtr,++ i,++ FFF_SCORE_STRUCT++ );++ scores.push(readScoreFromRaw(rawScore));++ }+ }+ load({+ library: LIBRARY_KEY,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b6cc9b75ca8..3661aa4d9c3 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -146,7 +146,7 @@ patchedDependencies:'@clerk/[email protected]': b8b22ab733de5bea846ad9e88046c10582352fe9ad86f314f368b2a823f0f281'@effect/[email protected]': ebaec66c6bdd25e1b8d5bfd4a14f25ab959bdcca6e22ed8871d061e50e2db0ad'@expo/[email protected]': 90fa980e8b6480631fb2fbb04559834e3c612db40c550cd828f11be297d8d760- '@ff-labs/[email protected]': 8956d6ed6938a1bce69b2d0b067ff258dd9ca753c5bbe7006f7b68f760ea3ad2+ '@ff-labs/[email protected]': cc71fcec015f4d39bc96ae2e2bf6b0ca678124c722c66a7841efce9d34b5983c'@legendapp/[email protected]': 680cc6a5c5b4a4032e467e7b3fde22f89a84c0ee2e6eac6fda737d6277cc0806'@pierre/[email protected]': 298e94372dbd51846a4e26ece2ecc3e22eb1f94b0450b1f1a9c6fec127809be7'@react-native-ai/[email protected]': 2d09870c2848d185cb05b53ed823a46e12dba519324d8dd8e584e28731990f9d@@ -620,7 +620,7 @@ importers:'@ff-labs/fff-node':specifier: 0.11.0- version: 0.11.0(patch_hash=8956d6ed6938a1bce69b2d0b067ff258dd9ca753c5bbe7006f7b68f760ea3ad2)+ version: 0.11.0(patch_hash=cc71fcec015f4d39bc96ae2e2bf6b0ca678124c722c66a7841efce9d34b5983c)'@muse-code/sdk':specifier: 1.4.6version: 1.4.6(@types/[email protected])@@ -14786,7 +14786,7 @@ snapshots:'@ff-labs/[email protected]':optional: true- '@ff-labs/[email protected](patch_hash=8956d6ed6938a1bce69b2d0b067ff258dd9ca753c5bbe7006f7b68f760ea3ad2)':+ '@ff-labs/[email protected](patch_hash=cc71fcec015f4d39bc96ae2e2bf6b0ca678124c722c66a7841efce9d34b5983c)':dependencies:ffi-rs: 1.3.2optionalDependencies: