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

pgvector 0.8+ HNSW Iterative Scan Memory and Traversal Boundary Invariant

Mandates deterministic resource boundaries for pgvector 0.8+ HNSW iterative scans during hybrid metadata filtering. Low-selectivity predicates during graph traversals must be constrained by explicit hnsw.max_scan_tuples caps, localized statement timeouts, and bounded index memory parameters to prevent unbounded backend memory expansion and catastrophic connection pool exhaustion.

Prohibited Anti-Pattern: Unbounded HNSW Iterative Scan on Low-Selectivity Predicates Causing Graph Traversal Runaway and OOM

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: pgvector 0.8+ HNSW Iterative Scan Memory and Traversal Boundary Invariant - Mandates deterministic resource boundaries for pgvector 0.8+ HNSW iterative scans during hybrid metadata filtering. Low-selectivity predicates during graph traversals must be constrained by explicit hnsw.max_scan_tuples caps, localized statement timeouts, and bounded index memory parameters to prevent unbounded backend memory expansion and catastrophic connection pool exhaustion.
globs: src/repositories/**/*.ts, src/db/**/*.ts, src/services/**/*.ts, src/queries/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pgvector-hnsw-iterative-scan-memory-boundary"
---

# pgvector 0.8+ HNSW Iterative Scan Memory and Traversal Boundary Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded HNSW Iterative Scan on Low-Selectivity Predicates Causing Graph Traversal Runaway and OOM

## System Constraints
You are a Principal Database Architect enforcing strict memory and traversal boundaries for pgvector 0.8+ HNSW iterative index scans. In pgvector 0.8+, iterative scans resolve the post-filter over-filtering issue, but unbounded iterative graph traversal on low-selectivity metadata filters causes extreme memory allocation, shared buffer churn, and query engine lockups. You MUST mandate transaction-scoped GUC boundaries (hnsw.iterative_scan, hnsw.max_scan_tuples, statement_timeout) for any hybrid vector query, or enforce partitioned/two-stage subquery filtering when selectivity cannot be statically proven.

## Strict Guidelines
- Engineers MUST ALWAYS set a strict transaction-local 'hnsw.max_scan_tuples' threshold (e.g., 20,000 to 50,000) whenever enabling 'hnsw.iterative_scan = relaxed' or 'hnsw.iterative_scan = strict' in pgvector 0.8+ hybrid queries.
- Engineers MUST NOT execute hybrid vector search (vector similarity + scalar WHERE filters) using global pool connections without explicit 'SET LOCAL' transaction boundaries or bound parameterized session resets.
- Services MUST enforce a strict transaction-level 'statement_timeout' (e.g., <= 3000ms) on all iterative vector scans to fail fast before exhausting backend process memory.
- Code SHOULD fall back to scalar index pre-filtering (subqueries with indexed partition/foreign keys) or multi-index intersections when metadata filtering selectivity is estimated to filter out > 95% of candidate tuples.
- Components NEVER execute raw unbounded '<->' or '<=>' HNSW operations alongside arbitrary user-defined metadata filters without an index scan ceiling.

## Bad vs Good Implementations
### Unbounded pgvector 0.8+ Iterative Graph Scan vs Bound Transactional Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Enabling 'hnsw.iterative_scan' without 'hnsw.max_scan_tuples' and outside a discrete transaction block leaks the setting to subsequent connection users. For sparse predicates (e.g., a multi-tenant org_id with few documents relative to the entire table), the iterative scan will traverse the entire index graph, causing buffer thrashing, multi-gigabyte memory spikes, and eventual backend connection termination.
```typescript
import { Pool } from 'pg';

export async function searchDocumentsUnsafe(
  pool: Pool,
  orgId: string,
  embedding: number[],
  limit: number
) {
  // FAILS INVARIANT: Global connection without max_scan_tuples bound.
  // If orgId has high selectivity (e.g., accounts for 0.01% of total rows),
  // iterative_scan will traverse millions of HNSW graph nodes, exhausting memory and hanging the connection.
  const query = `
    SET hnsw.iterative_scan = 'relaxed';
    SELECT id, title, embedding <=> $1::vector AS distance
    FROM documents
    WHERE org_id = $2
    ORDER BY embedding <=> $1::vector
    LIMIT $3;
  `;
  const result = await pool.query(query, [JSON.stringify(embedding), orgId, limit]);
  return result.rows;
}
```

#### Production Standard (Correct)
> **Standard**: Wraps the iterative vector search in a transaction utilizing 'SET LOCAL' to isolate configuration GUCs. Sets 'hnsw.max_scan_tuples = 25000' and 'statement_timeout = 2500ms' to ensure that if metadata selectivity is too low to find candidates within safety limits, the query fails gracefully without exhausting server RAM or causing OOM cascade across PostgreSQL backends.
```typescript
import { Pool, PoolClient } from 'pg';

interface DocumentResult {
  id: string;
  title: string;
  distance: number;
}

export async function searchDocumentsBounded(
  pool: Pool,
  orgId: string,
  embedding: number[],
  limit: number
): Promise<DocumentResult[]> {
  const client: PoolClient = await pool.connect();
  const vectorParam = JSON.stringify(embedding);

  try {
    await client.query('BEGIN');
    // Invariant: Confine scan boundaries strictly to this transaction
    await client.query(`
      SET LOCAL statement_timeout = '2500ms';
      SET LOCAL hnsw.iterative_scan = 'relaxed';
      SET LOCAL hnsw.max_scan_tuples = 25000;
      SET LOCAL hnsw.ef_search = 100;
    `);

    const sql = `
      SELECT id, title, (embedding <=> $1::vector) AS distance
      FROM documents
      WHERE org_id = $2
      ORDER BY embedding <=> $1::vector
      LIMIT $3;
    `;

    const { rows } = await client.query<DocumentResult>(sql, [vectorParam, orgId, limit]);
    await client.query('COMMIT');
    return rows;
  } catch (err: unknown) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}
```

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: pgvector 0.8+ HNSW Iterative Scan Memory and Traversal Boundary Invariant

pgvector 0.8+ HNSW Iterative Scan Memory and Traversal Boundary Invariant defines an industrial-grade behavioral standard for backend engineering. Mandates deterministic resource boundaries for pgvector 0.8+ HNSW iterative scans during hybrid metadata filtering. Low-selectivity predicates during graph traversals must be constrained by explicit hnsw.max_scan_tuples caps, localized statement timeouts, and bounded index memory parameters to prevent unbounded backend memory expansion and catastrophic connection pool exhaustion. 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 Iterative Scan on Low-Selectivity Predicates Causing Graph Traversal Runaway and OOM 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 Iterative Scan on Low-Selectivity Predicates Causing Graph Traversal Runaway and OOMCritical
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 set a strict transaction-local 'hnsw.max_scan_tuples' threshold (e.g., 20,000 to 50,000) whenever enabling 'hnsw.iterative_scan = relaxed' or 'hnsw.iterative_scan = strict' in pgvector 0.8+ hybrid queries.

Engineers MUST ALWAYS set a strict transaction-local 'hnsw.max_scan_tuples' threshold (e.g., 20,000 to 50,000) whenever enabling 'hnsw.iterative_scan = relaxed' or 'hnsw.iterative_scan = strict' in pgvector 0.8+ hybrid queries.

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 execute hybrid vector search (vector similarity + scalar WHERE filters) using global pool connections without explicit 'SET LOCAL' transaction boundaries or bound parameterized session resets.

Engineers MUST NOT execute hybrid vector search (vector similarity + scalar WHERE filters) using global pool connections without explicit 'SET LOCAL' transaction boundaries or bound parameterized session resets.

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

Services MUST enforce a strict transaction-level 'statement_timeout' (e.g., <= 3000ms) on all iterative vector scans to fail fast before exhausting backend process memory.

Services MUST enforce a strict transaction-level 'statement_timeout' (e.g., <= 3000ms) on all iterative vector scans to fail fast before exhausting backend process memory.

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

Code SHOULD fall back to scalar index pre-filtering (subqueries with indexed partition/foreign keys) or multi-index intersections when metadata filtering selectivity is estimated to filter out > 95% of candidate tuples.

Code SHOULD fall back to scalar index pre-filtering (subqueries with indexed partition/foreign keys) or multi-index intersections when metadata filtering selectivity is estimated to filter out > 95% of candidate tuples.

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 execute raw unbounded '<->' or '<=>' HNSW operations alongside arbitrary user-defined metadata filters without an index scan ceiling.

Components NEVER execute raw unbounded '<->' or '<=>' HNSW operations alongside arbitrary user-defined metadata filters without an index scan ceiling.

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 pgvector 0.8+ HNSW Iterative Scan Memory and Traversal Boundary Invariant critical for AI coding assistants?

Mandates deterministic resource boundaries for pgvector 0.8+ HNSW iterative scans during hybrid metadata filtering. Low-selectivity predicates during graph traversals must be constrained by explicit hnsw.max_scan_tuples caps, localized statement timeouts, and bounded index memory parameters to prevent unbounded backend memory expansion and catastrophic connection pool exhaustion. 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 Iterative Scan on Low-Selectivity Predicates Causing Graph Traversal Runaway and OOM) 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

pgvector