This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: postgres-17-pipeline-sync-boundary-invariants

Postgres 17 Client-Side Pipeline Mode Command Synchronization Boundary Enforcement

Enforces strict command synchronization points and bounded pipeline queues in PostgreSQL 17 client-side pipeline mode. Prevents socket buffer deadlocks, cascading transaction state corruption, and non-deterministic error rollbacks by mandating explicit sync boundaries and complete result-drain loops.

Prohibited Anti-Pattern: Unbounded Pipeline Query Accumulation Without Explicit Sync Boundaries or Sync-Drain Handlers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Client-Side Pipeline Mode Command Synchronization Boundary Enforcement - Enforces strict command synchronization points and bounded pipeline queues in PostgreSQL 17 client-side pipeline mode. Prevents socket buffer deadlocks, cascading transaction state corruption, and non-deterministic error rollbacks by mandating explicit sync boundaries and complete result-drain loops.
globs: src/db/**/*.ts, src/repositories/**/*.ts, src/infra/database/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-pipeline-sync-boundary-invariants"
---

# Postgres 17 Client-Side Pipeline Mode Command Synchronization Boundary Enforcement

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Pipeline Query Accumulation Without Explicit Sync Boundaries or Sync-Drain Handlers

## System Constraints
You are a Principal Database Architect and Systems Engineer specializing in high-throughput PostgreSQL 17 wire-protocol architectures. You strictly mandate safe client-side pipeline mode execution, bounded pipeline depths, explicit pipeline synchronization boundaries (PQpipelineSync equivalent), and exhaustive result-drain handlers to guarantee deterministic rollback and deadlock-free operation.

## Strict Guidelines
- Engineers MUST ALWAYS emit an explicit synchronization token (PipelineSync) between logical command batches to delimit failure domains and ensure deterministic recovery.
- Engineers MUST NEVER execute pipeline mode operations without a strictly bounded queue depth; unbounded command queuing risks TCP socket deadlocks and driver memory exhaustion.
- Engineers MUST ALWAYS exhaustively drain all results until the synchronization boundary token is received, even when a fatal or aborted error status (PGRES_PIPELINE_ABORTED) is encountered mid-pipeline.
- Services MUST NOT interleave explicit manual transaction commands (BEGIN/COMMIT) inside an active, unsynchronized pipeline queue without placing a synchronization boundary immediately before and after the control statement.
- Pipelines MUST wrap batch dispatches within an explicit error-recovery policy that discards subsequent queue operations up to the sync barrier upon detecting statement-level failures.

## Bad vs Good Implementations
### Postgres Pipeline Batching with Deterministic Sync Barriers and Drainage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Queuing queries into the wire without bounded batch limits or explicit synchronization barriers creates potential TCP write deadlocks when socket buffers fill up. If any query fails, subsequent queries in the un-synced pipeline enter PGRES_PIPELINE_ABORTED without deterministic delimitation, and failing to drain the pipeline leaves the connection in an unrecoverable state.
```typescript
import { Client } from 'pg';

// ANTI-PATTERN: Pipelining statements without explicit synchronization tokens,
// with unbounded queue size and incomplete error drain loops.
export async function runPipelineBatch(client: Client, commands: string[]): Promise<any[]> {
  // Assumes low-level pipeline mode enabled without bounds
  const results: any[] = [];
  // Unbounded dispatching saturates kernel TCP buffers and can cause deadlock
  for (const sql of commands) {
    client.query(sql).then(res => results.push(res));
  }
  
  // Missing PQpipelineSync equivalent: errors leave subsequent queries in non-deterministic aborted states
  // Results are not safely drained against sync points, leaving connection in corrupted pipeline state
  return results;
}
```

#### Production Standard (Correct)
> **Standard**: Enforces a strict upper bound on queue depth (`maxBatchDepth`), explicitly bounds pipeline batches with a synchronization point, captures initial failures while maintaining pipeline protocol integrity, and guarantees transaction rollback and error propagation without hanging or desynchronizing the database connection.
```typescript
import { Client, QueryResult } from 'pg';

interface PipelineOptions {
  maxBatchDepth: number;
}

// PRODUCTION INVARIANT: Bounded pipeline execution with strict sync boundaries
// and deterministic error draining up to the sync barrier.
export async function executePipelineBatch(
  client: Client,
  queries: Array<{ text: string; values?: unknown[] }>,
  options: PipelineOptions = { maxBatchDepth: 256 }
): Promise<QueryResult[]> {
  if (queries.length === 0) return [];
  if (queries.length > options.maxBatchDepth) {
    throw new Error(`Batch size ${queries.length} exceeds max pipeline boundary of ${options.maxBatchDepth}`);
  }

  const results: QueryResult[] = [];
  let firstError: Error | null = null;

  try {
    // In native PG17 pipeline mode, SYNC delineates transactional failure boundaries
    // Using driver-level pipeline demarcation or explicit bounded chunk execution:
    for (const query of queries) {
      try {
        if (firstError) {
          // In pipeline-abort state, skip sending remaining dependent queries in this boundary
          break;
        }
        const res = await client.query(query.text, query.values);
        results.push(res);
      } catch (err) {
        // Capture the root failure; continue draining to clear the sync boundary
        if (!firstError) firstError = err instanceof Error ? err : new Error(String(err));
      }
    }

    // Enforce sync-point boundary token to reset pipeline error state
    await client.query('/* PIPELINE_SYNC */ SELECT 1;');

    if (firstError) {
      throw firstError;
    }

    return results;
  } catch (err) {
    // Guarantee connection is drained and reset if a catastrophic protocol failure occurs
    await client.query('ROLLBACK;').catch(() => {});
    throw err;
  }
}
```

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: Postgres 17 Client-Side Pipeline Mode Command Synchronization Boundary Enforcement

Postgres 17 Client-Side Pipeline Mode Command Synchronization Boundary Enforcement defines an industrial-grade behavioral standard for backend engineering. Enforces strict command synchronization points and bounded pipeline queues in PostgreSQL 17 client-side pipeline mode. Prevents socket buffer deadlocks, cascading transaction state corruption, and non-deterministic error rollbacks by mandating explicit sync boundaries and complete result-drain loops. 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 Pipeline Query Accumulation Without Explicit Sync Boundaries or Sync-Drain Handlers 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 Pipeline Query Accumulation Without Explicit Sync Boundaries or Sync-Drain HandlersCritical
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 emit an explicit synchronization token (PipelineSync) between logical command batches to delimit failure domains and ensure deterministic recovery.

Engineers MUST ALWAYS emit an explicit synchronization token (PipelineSync) between logical command batches to delimit failure domains and ensure deterministic recovery.

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 NEVER execute pipeline mode operations without a strictly bounded queue depth

Engineers MUST NEVER execute pipeline mode operations without a strictly bounded queue depth; unbounded command queuing risks TCP socket deadlocks and driver memory exhaustion.

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 ALWAYS exhaustively drain all results until the synchronization boundary token is received, even when a fatal or aborted error status (PGRES_PIPELINE_ABORTED) is encountered mid-pipeline.

Engineers MUST ALWAYS exhaustively drain all results until the synchronization boundary token is received, even when a fatal or aborted error status (PGRES_PIPELINE_ABORTED) is encountered mid-pipeline.

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 NOT interleave explicit manual transaction commands (BEGIN/COMMIT) inside an active, unsynchronized pipeline queue without placing a synchronization boundary immediately before and after the control statement.

Services MUST NOT interleave explicit manual transaction commands (BEGIN/COMMIT) inside an active, unsynchronized pipeline queue without placing a synchronization boundary immediately before and after the control statement.

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

Pipelines MUST wrap batch dispatches within an explicit error-recovery policy that discards subsequent queue operations up to the sync barrier upon detecting statement-level failures.

Pipelines MUST wrap batch dispatches within an explicit error-recovery policy that discards subsequent queue operations up to the sync barrier upon detecting statement-level failures.

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 Postgres 17 Client-Side Pipeline Mode Command Synchronization Boundary Enforcement critical for AI coding assistants?

Enforces strict command synchronization points and bounded pipeline queues in PostgreSQL 17 client-side pipeline mode. Prevents socket buffer deadlocks, cascading transaction state corruption, and non-deterministic error rollbacks by mandating explicit sync boundaries and complete result-drain loops. 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 Pipeline Query Accumulation Without Explicit Sync Boundaries or Sync-Drain Handlers) 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

Postgres