This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: chromadb-hnsw-metadata-filtering-tenant-isolation

ChromaDB 0.6 HNSW Filtering, Multi-Tenant Namespaces, and Shard Architecture

Enforces strict tenant namespace isolation and calibrated HNSW graph indexing for ChromaDB 0.6+. Prevents catastrophic recall drop caused by graph candidate exhaustion during metadata pre-filtering by mandating tenant/database client scoping, metadata index alignment, and dynamic search_ef compensation.

Prohibited Anti-Pattern: Global Monolith Collections with Blind Metadata Filtering and Uncalibrated HNSW Traversal

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: ChromaDB 0.6 HNSW Filtering, Multi-Tenant Namespaces, and Shard Architecture - Enforces strict tenant namespace isolation and calibrated HNSW graph indexing for ChromaDB 0.6+. Prevents catastrophic recall drop caused by graph candidate exhaustion during metadata pre-filtering by mandating tenant/database client scoping, metadata index alignment, and dynamic search_ef compensation.
globs: src/lib/vector/**/*.ts, src/services/chroma/**/*.ts, src/repositories/embeddings/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/chromadb-hnsw-metadata-filtering-tenant-isolation"
---

# ChromaDB 0.6 HNSW Filtering, Multi-Tenant Namespaces, and Shard Architecture

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Global Monolith Collections with Blind Metadata Filtering and Uncalibrated HNSW Traversal

## System Constraints
You are a Principal Vector Database Architect enforcing ChromaDB 0.6+ standards. Mandate physical tenant isolation, calibrated HNSW construction parameters, and resilient metadata filtering. Ban global monolithic collections filtered by tenant_id keys in application-level queries.

## Strict Guidelines
- Engineers MUST ALWAYS isolate tenant workloads using ChromaDB 0.6 native tenant and database namespaces or partitioned collection prefixes (e.g., `tenant_<uuid>_<domain>`) instead of metadata-only segregation.
- Engineers MUST NOT rely on single-collection metadata filters (e.g., `where: { "tenant_id": "..." }`) for enterprise multi-tenancy due to cross-tenant leak risks and HNSW graph neighbor connectivity degradation.
- Code MUST explicitly set HNSW collection metadata during initialization, specifically specifying `hnsw:space`, `hnsw:construction_ef`, `hnsw:search_ef`, and `hnsw:M` tailored to dataset volume.
- Services MUST scale query-time `hnsw:search_ef` upward via query options whenever selective compound metadata filters (`$and`, `$in`) are applied to avoid the 'filtered HNSW disconnect' where candidate vectors are exhausted before reaching `nResults`.
- Components NEVER store complex nested objects or unindexed free-form JSON in ChromaDB metadata; metadata values MUST strictly conform to scalar primitives (string, number, boolean) supported by Chroma 0.6 filtering.

## Bad vs Good Implementations
### ChromaDB Tenant Isolation and Calibrated HNSW Metadata Querying

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Querying a global collection with tenant_id metadata causes graph starvation: HNSW searches nearby nodes, but if nearby nodes belong to other tenants, the search terminates early, returning fewer than `limit` results (or none). It also creates severe cross-tenant security and compliance risks.
```typescript
import { ChromaClient } from 'chromadb';

const client = new ChromaClient();

// ANTI-PATTERN: Single shared monolithic collection across all tenants.
// Relies purely on metadata filtering which breaks down under high cardinality
// and causes HNSW search to return fewer results than requested.
export async function searchDocuments(
  tenantId: string,
  queryEmbedding: number[],
  docType: string,
  limit: number = 10
) {
  const collection = await client.getOrCreateCollection({
    name: 'all_tenant_documents',
  });

  return await collection.query({
    queryEmbeddings: [queryEmbedding],
    nResults: limit,
    where: {
      $and: [
        { tenant_id: { $eq: tenantId } },
        { type: { $eq: docType } }
      ]
    }
  });
}
```

#### Production Standard (Correct)
> **Standard**: Uses ChromaDB 0.6 tenant and database isolation features so graphs are physically segmented per tenant, removing cross-tenant leakage. Tunes `hnsw:search_ef` and `hnsw:M` to ensure high recall when combined with post/pre-filtering clauses.
```typescript
import { ChromaClient, Collection } from 'chromadb';

// PRODUCTION INVARIANT: Dedicated tenant/database scope or strictly segmented collection
export class TenantVectorRepository {
  private client: ChromaClient;

  constructor(private readonly tenantId: string, database: string = 'default_database') {
    // Chroma 0.6 supports multi-tenant and database routing natively
    this.client = new ChromaClient({
      path: process.env.CHROMA_SERVER_URL,
      tenant: tenantId,
      database: database,
    });
  }

  async getOrInitializeCollection(domain: string): Promise<Collection> {
    // Calibrate HNSW index parameters for high-recall selective filtering
    return await this.client.getOrCreateCollection({
      name: `${domain}_embeddings`,
      metadata: {
        'hnsw:space': 'cosine',
        'hnsw:construction_ef': 128,
        'hnsw:M': 32,
        'hnsw:search_ef': 100 // High baseline search_ef to survive metadata filtering
      }
    });
  }

  async queryScoped(
    domain: string,
    queryEmbedding: number[],
    filterCategory: string,
    limit: number = 10
  ) {
    const collection = await this.getOrInitializeCollection(domain);

    // Metadata filtering on tenant-isolated collection with validated primitives
    return await collection.query({
      queryEmbeddings: [queryEmbedding],
      nResults: limit,
      where: {
        category: { $eq: filterCategory }
      }
    });
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: ChromaDB 0.6 HNSW Filtering, Multi-Tenant Namespaces, and Shard Architecture

ChromaDB 0.6 HNSW Filtering, Multi-Tenant Namespaces, and Shard Architecture defines an industrial-grade behavioral standard for backend engineering. Enforces strict tenant namespace isolation and calibrated HNSW graph indexing for ChromaDB 0.6+. Prevents catastrophic recall drop caused by graph candidate exhaustion during metadata pre-filtering by mandating tenant/database client scoping, metadata index alignment, and dynamic search_ef compensation. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Global Monolith Collections with Blind Metadata Filtering and Uncalibrated HNSW Traversal Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftGlobal Monolith Collections with Blind Metadata Filtering and Uncalibrated HNSW TraversalCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS isolate tenant workloads using ChromaDB 0.6 native tenant and database namespaces or partitioned collection prefixes (e.g., `tenant_<uuid>_<domain>`) instead of metadata-only segregation.

Engineers MUST ALWAYS isolate tenant workloads using ChromaDB 0.6 native tenant and database namespaces or partitioned collection prefixes (e.g., `tenant_<uuid>_<domain>`) instead of metadata-only segregation.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT rely on single-collection metadata filters (e.g., `where

Engineers MUST NOT rely on single-collection metadata filters (e.g., `where: { "tenant_id": "..." }`) for enterprise multi-tenancy due to cross-tenant leak risks and HNSW graph neighbor connectivity degradation.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code MUST explicitly set HNSW collection metadata during initialization, specifically specifying `hnsw

Code MUST explicitly set HNSW collection metadata during initialization, specifically specifying `hnsw:space`, `hnsw:construction_ef`, `hnsw:search_ef`, and `hnsw:M` tailored to dataset volume.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST scale query-time `hnsw

Services MUST scale query-time `hnsw:search_ef` upward via query options whenever selective compound metadata filters (`$and`, `$in`) are applied to avoid the 'filtered HNSW disconnect' where candidate vectors are exhausted before reaching `nResults`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER store complex nested objects or unindexed free-form JSON in ChromaDB metadata

Components NEVER store complex nested objects or unindexed free-form JSON in ChromaDB metadata; metadata values MUST strictly conform to scalar primitives (string, number, boolean) supported by Chroma 0.6 filtering.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is ChromaDB 0.6 HNSW Filtering, Multi-Tenant Namespaces, and Shard Architecture critical for AI coding assistants?

Enforces strict tenant namespace isolation and calibrated HNSW graph indexing for ChromaDB 0.6+. Prevents catastrophic recall drop caused by graph candidate exhaustion during metadata pre-filtering by mandating tenant/database client scoping, metadata index alignment, and dynamic search_ef compensation. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Global Monolith Collections with Blind Metadata Filtering and Uncalibrated HNSW Traversal) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

ChromaDB