Merge pull request #50 from giancarloerra/feat/qdrant-collection-prefix

feat(qdrant): add QDRANT_COLLECTION_PREFIX env var for shared instances
This commit is contained in:
Giancarlo Erra
2026-05-05 11:29:28 +01:00
committed by GitHub
6 changed files with 253 additions and 17 deletions
+1
View File
@@ -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
+14 -6
View File
@@ -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_<id>` 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 ──────────────────────────────────────────────────────
+26
View File
@@ -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`),
+22 -5
View File
@@ -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<void> {
}
/** 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<string[]> {
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<string[]> {
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;
+12 -6
View File
@@ -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 {
+178
View File
@@ -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_<id>` 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_<id>` 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_<id>` 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 `<id>_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 `<id>_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 `<id>_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_");
});
});
});