From 70db002796a76596badfed86c25d5af6c0331e69 Mon Sep 17 00:00:00 2001 From: Giancarlo Erra Date: Tue, 5 May 2026 11:20:33 +0100 Subject: [PATCH] feat(qdrant): add QDRANT_COLLECTION_PREFIX env var for shared instances MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolves #49. Reported by @awbait. When sharing a single Qdrant server across multiple applications (SocratiCode + Open-WebUI + custom RAG, etc.) or across multiple SocratiCode instances (per-project, per-environment, per-user), the fixed `codebase_` / `codegraph_` / `context_` / `_symgraph_*` / `socraticode_metadata` collection names risk colliding with other apps and prevent isolation between SocratiCode instances. This patch adds an optional QDRANT_COLLECTION_PREFIX env var that, when set, is prepended verbatim to every Qdrant collection name SocratiCode creates, queries, lists, or deletes. Default empty string preserves the existing collection names exactly: fully backwards compatible. Touchpoints (mechanical, no logic changes): - src/constants.ts: new QDRANT_COLLECTION_PREFIX export with eager validation. Qdrant accepts only [a-zA-Z0-9_-] in collection names; an invalid prefix throws at module load with a message naming the offending value, before any Qdrant call is attempted. - src/config.ts: all six collection-name generators (collectionName, graphCollectionName, contextCollectionName, symgraphMetaCollectionName, symgraphFileCollectionName, symgraphIndexCollectionName) prepend the prefix. Generator semantics are otherwise unchanged. - src/services/qdrant.ts: METADATA_COLLECTION (the global socraticode_metadata collection used for cross-project state) also honours the prefix, so two SocratiCode instances on one Qdrant keep their metadata isolated as well as their per-project collections. The two startsWith() filters in listCodebaseCollections — used by codebase_list_projects to discover this instance's collections — build the match prefix from QDRANT_COLLECTION_PREFIX so a prefixed instance only sees its own collections, not those of co-tenants. - src/tools/manage-tools.ts: codebase_list_projects similarly uses the prefix in its filters. The projectId extraction (formerly c.replace("codebase_", "")) now slices the full ${prefix}codebase_ token so the recovered id is correct under any prefix; the codegraph cross-reference uses the same prefixed name. Tests: 20 new test cases in tests/unit/qdrant-collection-prefix.test.ts covering: - Default empty prefix preserves the legacy collection-name forms for all six generators (regression guard against backward-compat break). - Empty-string env var is treated identically to unset. - Non-empty prefix prepends correctly to all six generators, including the suffix-style symgraph names. - Two different prefixes produce disjoint collection-name sets for the same projectId (the multi-instance isolation property). - Validation rejects whitespace, slash, colon, and unicode characters. - The error message includes the offending value for discoverability. - Validation accepts the full set of legal characters. Existing 752 unit tests continue to pass unchanged. Total: 772. typecheck, biome, and CodeRabbit local review all clean. README updated to document the new env var alongside the other QDRANT_* settings, including the user-side responsibility to remove old collections when changing prefix between runs. Co-authored-by: awbait --- README.md | 1 + src/config.ts | 20 ++- src/constants.ts | 26 +++ src/services/qdrant.ts | 27 ++- src/tools/manage-tools.ts | 18 +- tests/unit/qdrant-collection-prefix.test.ts | 178 ++++++++++++++++++++ 6 files changed, 253 insertions(+), 17 deletions(-) create mode 100644 tests/unit/qdrant-collection-prefix.test.ts diff --git a/README.md b/README.md index 8e99526..44e3db4 100644 --- a/README.md +++ b/README.md @@ -1143,6 +1143,7 @@ The rest of this section documents the variables themselves. Pass them using whi | `QDRANT_GRPC_PORT` | `16334` | Qdrant gRPC port (managed mode only) | | `QDRANT_HOST` | `localhost` | Qdrant hostname (alternative to `QDRANT_URL` for non-HTTPS external instances) | | `QDRANT_API_KEY` | *(none)* | Qdrant API key (required for Qdrant Cloud and other authenticated deployments). When set, the URL must be `https://...` so the key is not transmitted over plain HTTP. Loopback URLs (`localhost`, `127.0.0.1`, `[::1]`) are accepted on `http://` for local development. | +| `QDRANT_COLLECTION_PREFIX` | *(empty)* | Optional prefix prepended to every Qdrant collection name SocratiCode creates. Useful when sharing one Qdrant instance with other applications (Open-WebUI, custom RAG, etc.) or running multiple SocratiCode instances against one Qdrant for separation between projects, environments, or per-user indexes. Default empty string keeps collection names unchanged from previous releases (fully backwards compatible). Must match `[a-zA-Z0-9_-]+` if set; an invalid prefix throws at startup. Changing the prefix between runs orphans the previous collections; use `codebase_remove` first if you need to migrate. | ### Indexing Behaviour diff --git a/src/config.ts b/src/config.ts index e443484..ae09198 100644 --- a/src/config.ts +++ b/src/config.ts @@ -4,6 +4,7 @@ import { execFileSync } from "node:child_process"; import { createHash } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; +import { QDRANT_COLLECTION_PREFIX } from "./constants.js"; // ── Branch detection ───────────────────────────────────────────────────── @@ -89,40 +90,47 @@ function coreProjectId(folderPath: string): string { /** * Derive a Qdrant collection name for a project's code chunks. + * + * The optional `QDRANT_COLLECTION_PREFIX` env var is prepended verbatim to + * isolate this SocratiCode instance's collections when sharing a Qdrant + * server with other applications or other SocratiCode instances. Empty + * prefix (the default) preserves the legacy `codebase_` form exactly. */ export function collectionName(projectId: string): string { - return `codebase_${projectId}`; + return `${QDRANT_COLLECTION_PREFIX}codebase_${projectId}`; } /** * Derive a Qdrant collection name for a project's code graph. + * See {@link collectionName} for the prefix semantics. */ export function graphCollectionName(projectId: string): string { - return `codegraph_${projectId}`; + return `${QDRANT_COLLECTION_PREFIX}codegraph_${projectId}`; } /** * Derive a Qdrant collection name for a project's context artifacts. + * See {@link collectionName} for the prefix semantics. */ export function contextCollectionName(projectId: string): string { - return `context_${projectId}`; + return `${QDRANT_COLLECTION_PREFIX}context_${projectId}`; } // ── Symbol graph collections ───────────────────────────────────────────── /** Top-level metadata point for a project's symbol graph. */ export function symgraphMetaCollectionName(projectId: string): string { - return `${projectId}_symgraph_meta`; + return `${QDRANT_COLLECTION_PREFIX}${projectId}_symgraph_meta`; } /** Per-file payloads for a project's symbol graph. */ export function symgraphFileCollectionName(projectId: string): string { - return `${projectId}_symgraph_file`; + return `${QDRANT_COLLECTION_PREFIX}${projectId}_symgraph_file`; } /** Sharded indices (name index + reverse-call file index). */ export function symgraphIndexCollectionName(projectId: string): string { - return `${projectId}_symgraph_index`; + return `${QDRANT_COLLECTION_PREFIX}${projectId}_symgraph_index`; } // ── Linked projects ────────────────────────────────────────────────────── diff --git a/src/constants.ts b/src/constants.ts index 183209c..38e9f35 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -30,6 +30,32 @@ export const QDRANT_MODE: "managed" | "external" = export const QDRANT_CONTAINER_NAME = "socraticode-qdrant"; export const QDRANT_IMAGE = "qdrant/qdrant:v1.17.0"; +/** + * Optional prefix prepended to every Qdrant collection name SocratiCode + * creates, queries or deletes. Useful when sharing one Qdrant instance with + * other applications (Open-WebUI, custom RAG tools, etc.) or when running + * multiple SocratiCode instances against one Qdrant for separation between + * projects, environments, or per-user indexes. + * + * Default is the empty string, which keeps every collection name unchanged + * from previous releases — fully backwards compatible. + * + * Validated at module load: Qdrant accepts only `[a-zA-Z0-9_-]` in + * collection names, so the prefix must too. An invalid prefix throws + * before any Qdrant call is made, with a message naming the offending + * value so the misconfiguration is obvious. + */ +export const QDRANT_COLLECTION_PREFIX = (() => { + const raw = process.env.QDRANT_COLLECTION_PREFIX || ""; + if (raw && !/^[a-zA-Z0-9_-]+$/.test(raw)) { + throw new Error( + `Invalid QDRANT_COLLECTION_PREFIX: "${raw}". Qdrant collection names ` + + "accept only alphanumeric characters, underscore, and hyphen.", + ); + } + return raw; +})(); + /** * Resolve the Qdrant REST port from a URL. * Returns the explicit port if present (e.g. `:8443`), diff --git a/src/services/qdrant.ts b/src/services/qdrant.ts index 4a644dd..fff6492 100644 --- a/src/services/qdrant.ts +++ b/src/services/qdrant.ts @@ -2,7 +2,7 @@ // Copyright (C) 2026 Giancarlo Erra - Altaire Limited import { createHash } from "node:crypto"; import { QdrantClient } from "@qdrant/js-client-rest"; -import { QDRANT_API_KEY, QDRANT_HOST, QDRANT_PORT, QDRANT_URL, resolveQdrantPort } from "../constants.js"; +import { QDRANT_API_KEY, QDRANT_COLLECTION_PREFIX, QDRANT_HOST, QDRANT_PORT, QDRANT_URL, resolveQdrantPort } from "../constants.js"; import type { ArtifactIndexState, CodeGraph, FileChunk, SearchResult } from "../types.js"; import { getEmbeddingConfig } from "./embedding-config.js"; import { generateEmbeddings, generateQueryEmbedding, prepareDocumentText } from "./embeddings.js"; @@ -134,13 +134,23 @@ export async function deleteCollection(name: string): Promise { } /** List all codebase, codegraph, and context artifact entries. - * Codebase and context entries are actual collections; codegraph entries come from metadata. */ + * Codebase and context entries are actual collections; codegraph entries come from metadata. + * + * The collection-name filters honour `QDRANT_COLLECTION_PREFIX` so when + * sharing a Qdrant server with other applications or other SocratiCode + * instances, only this instance's collections are listed. */ export async function listCodebaseCollections(): Promise { const qdrant = getClient(); const collections = await qdrant.getCollections(); + const p = QDRANT_COLLECTION_PREFIX; const result = collections.collections .map((c) => c.name) - .filter((n) => n.startsWith("codebase_") || n.startsWith("codegraph_") || n.startsWith("context_")); + .filter( + (n) => + n.startsWith(`${p}codebase_`) || + n.startsWith(`${p}codegraph_`) || + n.startsWith(`${p}context_`), + ); // Also check metadata for graph and context entries (stored as metadata points, not real collections) try { @@ -152,7 +162,7 @@ export async function listCodebaseCollections(): Promise { for (const point of metaPoints.points) { const collName = point.payload?.collectionName as string | undefined; if ( - (collName?.startsWith("codegraph_") || collName?.startsWith("context_")) && + (collName?.startsWith(`${p}codegraph_`) || collName?.startsWith(`${p}context_`)) && !result.includes(collName) ) { result.push(collName); @@ -533,7 +543,14 @@ export async function getCollectionInfo(name: string): Promise<{ // ── Project metadata collection ────────────────────────────────────────── -const METADATA_COLLECTION = "socraticode_metadata"; +/** + * Global per-instance metadata collection. Stores cross-project state such + * as graph metadata pointers and context-artifact metadata. Honours + * `QDRANT_COLLECTION_PREFIX` so two SocratiCode instances sharing one + * Qdrant server keep their metadata isolated as well as their per-project + * code/graph/context collections. + */ +const METADATA_COLLECTION = `${QDRANT_COLLECTION_PREFIX}socraticode_metadata`; /** Cached flag: once the metadata collection is confirmed to exist, skip re-checking */ let metadataCollectionReady = false; diff --git a/src/tools/manage-tools.ts b/src/tools/manage-tools.ts index bc56cb2..fa563fa 100644 --- a/src/tools/manage-tools.ts +++ b/src/tools/manage-tools.ts @@ -1,7 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only // Copyright (C) 2026 Giancarlo Erra - Altaire Limited -import { QDRANT_HOST, QDRANT_MODE, QDRANT_PORT, QDRANT_URL, SOCRATICODE_VERSION } from "../constants.js"; +import { QDRANT_COLLECTION_PREFIX, QDRANT_HOST, QDRANT_MODE, QDRANT_PORT, QDRANT_URL, SOCRATICODE_VERSION } from "../constants.js"; import { getArtifactStatusSummary } from "../services/context-artifacts.js"; import { isDockerAvailable, isQdrantImagePresent, isQdrantRunning } from "../services/docker.js"; import { getEmbeddingConfig } from "../services/embedding-config.js"; @@ -136,14 +136,20 @@ export async function handleManageTool( return "No projects have been indexed yet. Use codebase_index to index a project."; } - const codebaseCollections = collections.filter((c) => c.startsWith("codebase_")); - const graphCollections = collections.filter((c) => c.startsWith("codegraph_")); + // All four references below honour QDRANT_COLLECTION_PREFIX so this + // tool keeps working on shared Qdrant deployments where SocratiCode's + // collection names carry an instance-specific prefix. + const p = QDRANT_COLLECTION_PREFIX; + const codebasePrefix = `${p}codebase_`; + const graphPrefix = `${p}codegraph_`; + const codebaseCollections = collections.filter((c) => c.startsWith(codebasePrefix)); + const graphCollections = collections.filter((c) => c.startsWith(graphPrefix)); const lines = ["Indexed projects:\n"]; for (const c of codebaseCollections) { - const projectId = c.replace("codebase_", ""); - const hasGraph = graphCollections.includes(`codegraph_${projectId}`); + const projectId = c.slice(codebasePrefix.length); + const hasGraph = graphCollections.includes(`${graphPrefix}${projectId}`); const metadata = await getProjectMetadata(c); const pathInfo = metadata?.projectPath || "(path unknown — indexed before path tracking)"; lines.push(` - ${pathInfo}`); @@ -159,7 +165,7 @@ export async function handleManageTool( } } if (hasGraph) { - const graphMeta = await getGraphMetadata(`codegraph_${projectId}`); + const graphMeta = await getGraphMetadata(`${graphPrefix}${projectId}`); if (graphMeta) { lines.push(` Code graph: ${graphMeta.nodeCount} files, ${graphMeta.edgeCount} edges (built: ${graphMeta.lastBuiltAt})`); } else { diff --git a/tests/unit/qdrant-collection-prefix.test.ts b/tests/unit/qdrant-collection-prefix.test.ts new file mode 100644 index 0000000..1b64e9e --- /dev/null +++ b/tests/unit/qdrant-collection-prefix.test.ts @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Giancarlo Erra - Altaire Limited +// +// Tests for QDRANT_COLLECTION_PREFIX (issue #49). +// +// QDRANT_COLLECTION_PREFIX is read once at module load in +// `src/constants.ts` and used by `src/config.ts` collection-name +// generators (and by `src/services/qdrant.ts` for the metadata +// collection). To exercise multiple prefix values in one test run we +// reset the module cache between cases and dynamically re-import the +// modules under test, which forces the env-var-reading IIFE in +// constants.ts to execute again. + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const ENV_KEY = "QDRANT_COLLECTION_PREFIX"; + +describe("QDRANT_COLLECTION_PREFIX", () => { + const original = process.env[ENV_KEY]; + + beforeEach(() => { + vi.resetModules(); + }); + + afterEach(() => { + if (original === undefined) { + delete process.env[ENV_KEY]; + } else { + process.env[ENV_KEY] = original; + } + vi.resetModules(); + }); + + describe("default (empty prefix) — backwards compatibility", () => { + it("collectionName returns the legacy `codebase_` form", async () => { + delete process.env[ENV_KEY]; + const { collectionName } = await import("../../src/config.js"); + expect(collectionName("abc123def456")).toBe("codebase_abc123def456"); + }); + + it("graphCollectionName returns the legacy `codegraph_` form", async () => { + delete process.env[ENV_KEY]; + const { graphCollectionName } = await import("../../src/config.js"); + expect(graphCollectionName("abc123def456")).toBe("codegraph_abc123def456"); + }); + + it("contextCollectionName returns the legacy `context_` form", async () => { + delete process.env[ENV_KEY]; + const { contextCollectionName } = await import("../../src/config.js"); + expect(contextCollectionName("abc123def456")).toBe("context_abc123def456"); + }); + + it("symgraphMetaCollectionName returns the legacy `_symgraph_meta` form", async () => { + delete process.env[ENV_KEY]; + const { symgraphMetaCollectionName } = await import("../../src/config.js"); + expect(symgraphMetaCollectionName("abc123def456")).toBe("abc123def456_symgraph_meta"); + }); + + it("symgraphFileCollectionName returns the legacy `_symgraph_file` form", async () => { + delete process.env[ENV_KEY]; + const { symgraphFileCollectionName } = await import("../../src/config.js"); + expect(symgraphFileCollectionName("abc123def456")).toBe("abc123def456_symgraph_file"); + }); + + it("symgraphIndexCollectionName returns the legacy `_symgraph_index` form", async () => { + delete process.env[ENV_KEY]; + const { symgraphIndexCollectionName } = await import("../../src/config.js"); + expect(symgraphIndexCollectionName("abc123def456")).toBe("abc123def456_symgraph_index"); + }); + + it("treats empty-string env var the same as unset", async () => { + process.env[ENV_KEY] = ""; + const { collectionName } = await import("../../src/config.js"); + expect(collectionName("abc")).toBe("codebase_abc"); + }); + }); + + describe("non-empty prefix", () => { + it("prepends the prefix to collectionName", async () => { + process.env[ENV_KEY] = "myapp_"; + const { collectionName } = await import("../../src/config.js"); + expect(collectionName("abc123")).toBe("myapp_codebase_abc123"); + }); + + it("prepends the prefix to graphCollectionName", async () => { + process.env[ENV_KEY] = "myapp_"; + const { graphCollectionName } = await import("../../src/config.js"); + expect(graphCollectionName("abc123")).toBe("myapp_codegraph_abc123"); + }); + + it("prepends the prefix to contextCollectionName", async () => { + process.env[ENV_KEY] = "myapp_"; + const { contextCollectionName } = await import("../../src/config.js"); + expect(contextCollectionName("abc123")).toBe("myapp_context_abc123"); + }); + + it("prepends the prefix to symgraph collection names (suffix-style still gets prefix)", async () => { + process.env[ENV_KEY] = "myapp_"; + const { + symgraphMetaCollectionName, + symgraphFileCollectionName, + symgraphIndexCollectionName, + } = await import("../../src/config.js"); + expect(symgraphMetaCollectionName("abc")).toBe("myapp_abc_symgraph_meta"); + expect(symgraphFileCollectionName("abc")).toBe("myapp_abc_symgraph_file"); + expect(symgraphIndexCollectionName("abc")).toBe("myapp_abc_symgraph_index"); + }); + + it("accepts prefixes without trailing separator (user choice)", async () => { + process.env[ENV_KEY] = "myapp"; + const { collectionName } = await import("../../src/config.js"); + // The user may or may not include a separator; we prepend verbatim. + expect(collectionName("abc")).toBe("myappcodebase_abc"); + }); + + it("accepts prefixes with hyphen separator", async () => { + process.env[ENV_KEY] = "team-alpha-"; + const { collectionName } = await import("../../src/config.js"); + expect(collectionName("abc")).toBe("team-alpha-codebase_abc"); + }); + + it("two different prefixes produce disjoint collection-name sets for the same projectId", async () => { + process.env[ENV_KEY] = "instance_a_"; + const { collectionName: collA } = await import("../../src/config.js"); + const nameA = collA("project1"); + + vi.resetModules(); + process.env[ENV_KEY] = "instance_b_"; + const { collectionName: collB } = await import("../../src/config.js"); + const nameB = collB("project1"); + + expect(nameA).toBe("instance_a_codebase_project1"); + expect(nameB).toBe("instance_b_codebase_project1"); + expect(nameA).not.toBe(nameB); + }); + }); + + describe("validation", () => { + it("rejects a prefix containing whitespace", async () => { + process.env[ENV_KEY] = "my app"; + await expect(import("../../src/constants.js")).rejects.toThrow( + /Invalid QDRANT_COLLECTION_PREFIX/, + ); + }); + + it("rejects a prefix containing a slash", async () => { + process.env[ENV_KEY] = "team/alpha"; + await expect(import("../../src/constants.js")).rejects.toThrow( + /Invalid QDRANT_COLLECTION_PREFIX/, + ); + }); + + it("rejects a prefix containing a colon", async () => { + process.env[ENV_KEY] = "team:alpha"; + await expect(import("../../src/constants.js")).rejects.toThrow( + /Invalid QDRANT_COLLECTION_PREFIX/, + ); + }); + + it("rejects a prefix containing emoji or other unicode", async () => { + process.env[ENV_KEY] = "rocket🚀"; + await expect(import("../../src/constants.js")).rejects.toThrow( + /Invalid QDRANT_COLLECTION_PREFIX/, + ); + }); + + it("includes the offending value in the error message for discoverability", async () => { + process.env[ENV_KEY] = "bad value"; + await expect(import("../../src/constants.js")).rejects.toThrow(/"bad value"/); + }); + + it("accepts a prefix containing only ASCII letters, digits, underscore, hyphen", async () => { + process.env[ENV_KEY] = "a_B-9-z_"; + const constants = await import("../../src/constants.js"); + expect(constants.QDRANT_COLLECTION_PREFIX).toBe("a_B-9-z_"); + }); + }); +});