This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: pg17-hnsw-memory-boundary-enclaves

PostgreSQL 17 Pgvector HNSW Indexing Memory Boundary Enclaves

Enforces deterministic memory boundaries and scalar quantization enclaves during pgvector HNSW index builds on PostgreSQL 17. Prevents Linux cgroup OOM killer panics by mathematically budgeting session-scoped maintenance_work_mem against vector dimensionality, maximum graph out-degrees (m), and parallel maintenance workers.

Prohibited Anti-Pattern: Unbounded HNSW Graph Materialization with Default maintenance_work_mem and Full-Precision Float32 Vectors

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Pgvector HNSW Indexing Memory Boundary Enclaves - Enforces deterministic memory boundaries and scalar quantization enclaves during pgvector HNSW index builds on PostgreSQL 17. Prevents Linux cgroup OOM killer panics by mathematically budgeting session-scoped maintenance_work_mem against vector dimensionality, maximum graph out-degrees (m), and parallel maintenance workers.
globs: migrations/**/*.ts, src/db/**/*.ts, src/infrastructure/db/**/*.ts, src/services/vector/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-hnsw-memory-boundary-enclaves"
---

# PostgreSQL 17 Pgvector HNSW Indexing Memory Boundary Enclaves

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded HNSW Graph Materialization with Default maintenance_work_mem and Full-Precision Float32 Vectors

## System Constraints
You are a Principal Database Infrastructure Architect enforcing zero-downtime vector operations on PostgreSQL 17 using pgvector. Mandate strict memory boundary enclaves for Hierarchical Navigable Small World (HNSW) index builds. You must reject any migration or dynamic index build that uses global cluster-wide maintenance memory defaults, unquantized high-dimension (>768d) vector storage during continuous writes, or unthrottled concurrent index generation. Force strict session-level allocation, explicit worker budgeting, and scalar quantization (halfvec/SQ8) to eliminate cgroup memory exhaustion.

## Strict Guidelines
- Engineers MUST ALWAYS isolate HNSW index creation into dedicated session-level memory enclaves using 'SET LOCAL maintenance_work_mem' bounded strictly to: (Allocated_Container_RAM - shared_buffers) / (max_parallel_maintenance_workers * 2).
- Engineers MUST ALWAYS acquire an exclusive advisory lock via 'pg_advisory_xact_lock' prior to executing vector index DDL to serialize builds and prevent concurrent graph synthesis memory spikes.
- Engineers MUST use half-precision ('halfvec') or scalar quantization (SQ8 via dynamic cast or bit vectors) for embeddings with dimensions >= 1024 (e.g., text-embedding-3-large, Cohere v3) to reduce HNSW graph construction RAM footprint by 50-75%.
- Engineers MUST NEVER run 'CREATE INDEX ... USING hnsw' without the 'CONCURRENTLY' directive on active production tables subject to semantic vector ingestion.
- Code MUST set 'max_parallel_maintenance_workers' to an explicitly budgeted core count (<= 4) in the migration session before building HNSW indexes to avoid multiplication of maintenance memory boundaries.
- Services MUST verify existing physical node memory headroom using database metric enclaves before launching vector reindexing tasks.

## Bad vs Good Implementations
### Unbounded FP32 HNSW Index Creation via Migration Runner

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: This operation executes an unconstrained HNSW graph build on 1536-dimensional FP32 vectors using default session parameters. In production with continuous ingestion, the unthrottled worker count combined with unbounded maintenance memory requirements triggers cgroup memory limits, causing the host OS to terminate the PostgreSQL postmaster process.
```typescript
import { Client } from 'pg';

export async function runVectorMigration(client: Client): Promise<void> {
  // FAILS: Inherits cluster-wide maintenance_work_mem which can exceed cgroup limits
  // FAILS: Uses full float32 1536-dim vector without quantization or concurrency safety
  // FAILS: No serialization, concurrent migrations will multiply maintenance memory
  await client.query(`
    CREATE INDEX idx_document_embeddings_hnsw 
    ON document_embeddings 
    USING hnsw (embedding vector_cosine_ops)
    WITH (m = 32, ef_construction = 128);
  `);
}
```

#### Production Standard (Correct)
> **Standard**: This pattern establishes a strict resource enclave: it limits parallel maintenance workers, constrains session-scoped maintenance_work_mem, synchronizes builds using an advisory lock, runs CONCURRENTLY to prevent blocking live writes, and uses halfvec (scalar quantization) to cut working memory requirements by half.
```typescript
import { PoolClient } from 'pg';

interface HnswEnclaveConfig {
  advisoryLockId: number;
  budgetedMaintenanceMemMb: number;
  maxMaintenanceWorkers: number;
  m: number;
  efConstruction: number;
}

export async function buildHnswIndexEnclave(
  client: PoolClient,
  config: HnswEnclaveConfig = {
    advisoryLockId: 8941042,
    budgetedMaintenanceMemMb: 1024,
    maxMaintenanceWorkers: 2,
    m: 16,
    efConstruction: 64,
  }
): Promise<void> {
  // Acquire transaction-scoped advisory lock to prevent parallel memory spikes
  await client.query('BEGIN');
  try {
    await client.query('SELECT pg_advisory_xact_lock($1)', [config.advisoryLockId]);
    
    // Establish strict memory boundary enclave for this dedicated session
    await client.query(`SET LOCAL maintenance_work_mem = '${config.budgetedMaintenanceMemMb}MB'`);
    await client.query(`SET LOCAL max_parallel_maintenance_workers = ${config.maxMaintenanceWorkers}`);
    await client.query('COMMIT');
  } catch (error) {
    await client.query('ROLLBACK');
    throw error;
  }

  // CREATE INDEX CONCURRENTLY cannot run inside an outer transaction block.
  // Use scalar quantization (halfvec) on vectors >= 1024 dimensions to cut memory by 50%.
  await client.query(`
    CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_document_embeddings_hnsw_sq
    ON document_embeddings 
    USING hnsw ((embedding::halfvec(1536)) halfvec_cosine_ops)
    WITH (
      m = ${config.m}, 
      ef_construction = ${config.efConstruction}
    );
  `);
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: PostgreSQL 17 Pgvector HNSW Indexing Memory Boundary Enclaves

PostgreSQL 17 Pgvector HNSW Indexing Memory Boundary Enclaves defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic memory boundaries and scalar quantization enclaves during pgvector HNSW index builds on PostgreSQL 17. Prevents Linux cgroup OOM killer panics by mathematically budgeting session-scoped maintenance_work_mem against vector dimensionality, maximum graph out-degrees (m), and parallel maintenance workers. 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: Unbounded HNSW Graph Materialization with Default maintenance_work_mem and Full-Precision Float32 Vectors 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 DriftUnbounded HNSW Graph Materialization with Default maintenance_work_mem and Full-Precision Float32 VectorsCritical
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 HNSW index creation into dedicated session-level memory enclaves using 'SET LOCAL maintenance_work_mem' bounded strictly to

Engineers MUST ALWAYS isolate HNSW index creation into dedicated session-level memory enclaves using 'SET LOCAL maintenance_work_mem' bounded strictly to: (Allocated_Container_RAM - shared_buffers) / (max_parallel_maintenance_workers * 2).

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 ALWAYS acquire an exclusive advisory lock via 'pg_advisory_xact_lock' prior to executing vector index DDL to serialize builds and prevent concurrent graph synthesis memory spikes.

Engineers MUST ALWAYS acquire an exclusive advisory lock via 'pg_advisory_xact_lock' prior to executing vector index DDL to serialize builds and prevent concurrent graph synthesis memory spikes.

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

Engineers MUST use half-precision ('halfvec') or scalar quantization (SQ8 via dynamic cast or bit vectors) for embeddings with dimensions >= 1024 (e.g., text-embedding-3-large, Cohere v3) to reduce HNSW graph construction RAM footprint by 50-75%.

Engineers MUST use half-precision ('halfvec') or scalar quantization (SQ8 via dynamic cast or bit vectors) for embeddings with dimensions >= 1024 (e.g., text-embedding-3-large, Cohere v3) to reduce HNSW graph construction RAM footprint by 50-75%.

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

Engineers MUST NEVER run 'CREATE INDEX ... USING hnsw' without the 'CONCURRENTLY' directive on active production tables subject to semantic vector ingestion.

Engineers MUST NEVER run 'CREATE INDEX ... USING hnsw' without the 'CONCURRENTLY' directive on active production tables subject to semantic vector ingestion.

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

Code MUST set 'max_parallel_maintenance_workers' to an explicitly budgeted core count (<= 4) in the migration session before building HNSW indexes to avoid multiplication of maintenance memory boundaries.

Code MUST set 'max_parallel_maintenance_workers' to an explicitly budgeted core count (<= 4) in the migration session before building HNSW indexes to avoid multiplication of maintenance memory boundaries.

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.
6

Services MUST verify existing physical node memory headroom using database metric enclaves before launching vector reindexing tasks.

Services MUST verify existing physical node memory headroom using database metric enclaves before launching vector reindexing tasks.

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 PostgreSQL 17 Pgvector HNSW Indexing Memory Boundary Enclaves critical for AI coding assistants?

Enforces deterministic memory boundaries and scalar quantization enclaves during pgvector HNSW index builds on PostgreSQL 17. Prevents Linux cgroup OOM killer panics by mathematically budgeting session-scoped maintenance_work_mem against vector dimensionality, maximum graph out-degrees (m), and parallel maintenance workers. 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 (Unbounded HNSW Graph Materialization with Default maintenance_work_mem and Full-Precision Float32 Vectors) 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

PostgreSQL