fix: address remaining CodeRabbit production code issues

- Scope dedupe key to label::relativePath in mergeMultiCollectionResults
  so same file in different projects is not collapsed
- Compute embedding once in searchMultipleCollections via internal
  searchChunksWithVector helper (avoids N redundant API calls)
- Compare base project hashes (not branch-suffixed names) when skipping
  duplicate linked projects in resolveLinkedCollections
- Use path.resolve() for platform-neutral assertion in query-tools tests
- Update multi-collection-search tests for new cross-project dedup semantics
This commit is contained in:
Giancarlo Erra
2026-04-11 17:34:21 +01:00
parent f09f417c6e
commit f745d59ddd
5 changed files with 75 additions and 20 deletions
+7 -3
View File
@@ -67,7 +67,10 @@ export function projectIdFromPath(folderPath: string): string {
if (process.env.SOCRATICODE_BRANCH_AWARE === "true") {
const branch = detectGitBranch(path.resolve(folderPath));
if (branch) {
id = `${id}__${sanitizeBranchName(branch)}`;
const sanitized = sanitizeBranchName(branch);
if (sanitized) {
id = `${id}__${sanitized}`;
}
}
}
@@ -173,6 +176,7 @@ export function resolveLinkedCollections(
): Array<{ name: string; label: string }> {
const resolvedRoot = path.resolve(projectPath);
const currentId = projectIdFromPath(resolvedRoot);
const currentCoreId = coreProjectId(resolvedRoot);
const collections: Array<{ name: string; label: string }> = [
{ name: collectionName(currentId), label: path.basename(resolvedRoot) },
];
@@ -182,8 +186,8 @@ export function resolveLinkedCollections(
// Use base hash (no branch suffix) — linked projects are resolved by their
// standard collection name regardless of SOCRATICODE_BRANCH_AWARE.
const linkedId = coreProjectId(linkedPath);
// Skip if same base project (e.g. worktrees sharing SOCRATICODE_PROJECT_ID)
if (collectionName(linkedId) === collections[0].name) continue;
// Skip if same base project (e.g. worktrees sharing the same path hash)
if (linkedId === currentCoreId) continue;
collections.push({
name: collectionName(linkedId),
label: path.basename(linkedPath),
+22 -4
View File
@@ -309,8 +309,21 @@ export async function searchChunks(
fileFilter?: string,
languageFilter?: string,
): Promise<SearchResult[]> {
const qdrant = getClient();
const queryVector = await generateQueryEmbedding(query);
return searchChunksWithVector(collectionName, query, queryVector, limit, fileFilter, languageFilter);
}
/** Internal: hybrid search using a pre-computed dense embedding vector.
* Avoids recomputing the same embedding when querying multiple collections. */
async function searchChunksWithVector(
collectionName: string,
query: string,
queryVector: number[],
limit: number,
fileFilter?: string,
languageFilter?: string,
): Promise<SearchResult[]> {
const qdrant = getClient();
const filter: { must: Array<{ key: string; match: { value: string } }> } = { must: [] };
if (fileFilter) {
@@ -355,7 +368,9 @@ export async function searchChunks(
}
/** Merge results from multiple collection queries using client-side Reciprocal Rank Fusion.
* Deduplicates by relativePath — first (higher-priority) collection wins on conflict.
* Deduplicates by `label::relativePath` so that files with the same relative path
* in different projects are kept as separate hits. Within a single project,
* the first (higher-priority) occurrence wins on conflict.
* Exported for unit testing. */
export function mergeMultiCollectionResults(
collectionResults: Array<{ label: string; results: SearchResult[] }>,
@@ -367,7 +382,7 @@ export function mergeMultiCollectionResults(
for (const { label, results } of collectionResults) {
for (let rank = 0; rank < results.length; rank++) {
const r = results[rank];
const key = r.relativePath;
const key = `${label}::${r.relativePath}`;
const rrfContribution = 1 / (RRF_K + rank + 1);
const existing = scored.get(key);
@@ -414,6 +429,9 @@ export async function searchMultipleCollections(
return results.map((r) => ({ ...r, project: collections[0].label }));
}
// Compute the dense embedding once for all collections
const queryVector = await generateQueryEmbedding(query);
// Query all collections in parallel, requesting extra candidates for RRF re-ranking
const perCollectionLimit = Math.max(limit * 2, 20);
const collectionResults: Array<{ label: string; results: SearchResult[] }> = [];
@@ -421,7 +439,7 @@ export async function searchMultipleCollections(
const allResults = await Promise.all(
collections.map(async ({ name, label }) => {
try {
const results = await searchChunks(name, query, perCollectionLimit, fileFilter, languageFilter);
const results = await searchChunksWithVector(name, query, queryVector, perCollectionLimit, fileFilter, languageFilter);
return { label, results };
} catch (err) {
logger.warn("searchMultipleCollections: collection query failed, skipping", {
+6
View File
@@ -353,6 +353,12 @@ describe("config", () => {
it("replaces special characters", () => {
expect(sanitizeBranchName("feat@v2.0")).toBe("feat_v2_0");
});
it("returns empty string when all characters are invalid", () => {
expect(sanitizeBranchName("///")).toBe("");
expect(sanitizeBranchName("@@@")).toBe("");
expect(sanitizeBranchName("...")).toBe("");
});
});
/** Create a temporary git repo with a named branch and initial commit. */
+38 -12
View File
@@ -88,7 +88,7 @@ describe("mergeMultiCollectionResults", () => {
expect(results.find((r) => r.relativePath === "src/file3.ts")?.project).toBe("project-b");
});
it("deduplicates by relativePath — first (higher-priority) collection wins", () => {
it("keeps same relativePath from different projects as separate entries", () => {
const results = mergeMultiCollectionResults(
[
{
@@ -103,13 +103,35 @@ describe("mergeMultiCollectionResults", () => {
10,
);
// Dedupe key is label::relativePath, so same file in different projects stays separate
const sharedResults = results.filter((r) => r.relativePath === "src/shared.ts");
expect(sharedResults).toHaveLength(1);
expect(sharedResults[0].content).toBe("content from A");
expect(sharedResults[0].project).toBe("project-a");
expect(sharedResults).toHaveLength(2);
expect(sharedResults.map((r) => r.project)).toEqual(
expect.arrayContaining(["project-a", "project-b"]),
);
});
it("RRF scores accumulate for files appearing in multiple collections", () => {
it("deduplicates same relativePath within the same project", () => {
const results = mergeMultiCollectionResults(
[
{
label: "project-a",
results: [
makeResult("src/shared.ts", 0.90, { content: "first chunk" }),
makeResult("src/shared.ts", 0.80, { content: "second chunk" }),
],
},
],
10,
);
// Same label + same relativePath → deduplicated, first (higher-ranked) wins
const sharedResults = results.filter((r) => r.relativePath === "src/shared.ts");
expect(sharedResults).toHaveLength(1);
expect(sharedResults[0].content).toBe("first chunk");
});
it("same relativePath from different projects has independent RRF scores", () => {
const results = mergeMultiCollectionResults(
[
{
@@ -130,13 +152,17 @@ describe("mergeMultiCollectionResults", () => {
10,
);
// popular.ts should rank first due to accumulated RRF score from both collections
expect(results[0].relativePath).toBe("src/popular.ts");
// Its score should be higher than single-collection results
expect(results[0].score).toBeGreaterThan(results[1].score);
// The accumulated score = 1/(60+1) + 1/(60+1) = 2 * 1/61 ≈ 0.0328
const expectedAccumulated = 2 * (1 / 61);
expect(results[0].score).toBeCloseTo(expectedAccumulated, 6);
// With label-scoped keys, src/popular.ts from A and B are separate entries
const popularResults = results.filter((r) => r.relativePath === "src/popular.ts");
expect(popularResults).toHaveLength(2);
// Each has a single-collection RRF score: 1/(60+rank)
// project-a's popular.ts is rank 1 → 1/61
// project-b's popular.ts is rank 1 → 1/61
const expectedSingle = 1 / 61;
for (const r of popularResults) {
expect(r.score).toBeCloseTo(expectedSingle, 6);
}
});
it("respects the limit parameter", () => {
+2 -1
View File
@@ -7,6 +7,7 @@
* provider, and uses getEmbeddingProvider() for OpenAI/Google.
*/
import path from "node:path";
import { beforeEach, describe, expect, it, vi } from "vitest";
// ── Mocks ────────────────────────────────────────────────────────────────
@@ -245,7 +246,7 @@ describe("codebase_search — includeLinked parameter", () => {
});
expect(mockResolveLinkedCollections).toHaveBeenCalledWith(
expect.stringContaining(TEST_PATH),
expect.stringContaining(path.resolve(TEST_PATH)),
);
expect(mockSearchMultipleCollections).toHaveBeenCalledWith(
[