This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendhigh PriorityID: clickhouse-replacing-mergetree-dedup

ClickHouse ReplacingMergeTree & FINAL Query Argument Optimization

Production data architecture standard for ClickHouse. Mandates using ReplacingMergeTree with an explicit version column (updated_at) for deduplication, avoids naive unconstrained SELECT ... FINAL queries across large partitions, and leverages argMax() aggregation for high-speed sub-millisecond deduplication.

Prohibited Anti-Pattern: AI writes SELECT * FROM table FINAL on multi-billion row ClickHouse tables, causing massive single-thread merges and crushing analytical query throughput.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: ClickHouse ReplacingMergeTree & FINAL Query Argument Optimization - Production data architecture standard for ClickHouse. Mandates using ReplacingMergeTree with an explicit version column (updated_at) for deduplication, avoids naive unconstrained SELECT ... FINAL queries across large partitions, and leverages argMax() aggregation for high-speed sub-millisecond deduplication.
globs: **/*.sql, **/queries/**/*.sql, **/clickhouse/**/*.ts
alwaysApply: false
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/clickhouse-replacing-mergetree-dedup"
---

# ClickHouse ReplacingMergeTree & FINAL Query Argument Optimization

> **Severity**: HIGH | **Category**: backend
> **Anti-Pattern Warning**: AI writes SELECT * FROM table FINAL on multi-billion row ClickHouse tables, causing massive single-thread merges and crushing analytical query throughput.

## System Constraints
You are a ClickHouse High-Performance Analytics Engineer. In ClickHouse, ReplacingMergeTree only guarantees background deduplication; duplicates can exist until background merge occurs. NEVER use raw SELECT * FROM table FINAL in production dashboards without partition bounds. Use argMax() or argMin() aggregations for instant sub-millisecond deduplication.

## Strict Guidelines
- MUST define ReplacingMergeTree with an explicit numeric or timestamp version column: ReplacingMergeTree(ver).
- MUST NOT execute SELECT ... FINAL on queries without restrictive WHERE partition filters (FINAL forces multi-threaded block merging across the entire dataset).
- SHOULD use SELECT id, argMax(status, ver) as status FROM table GROUP BY id for 10x faster deduplicated reads over FINAL.
- MUST order the table by primary lookup keys: ORDER BY (tenant_id, id).
- SHOULD utilize OPTIMIZE TABLE table FINAL only during off-peak maintenance windows, never on continuous ingestion cycles.

## Bad vs Good Implementations
### Fast argMax Deduplication in ClickHouse vs Heavy FINAL Modifier

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The FINAL modifier forces ClickHouse to perform real-time merge-sorting across all unmerged parts across the table, increasing query latency from 5ms to 12 seconds.
```sql
-- FATAL: Running SELECT ... FINAL across entire 500M row dataset
-- CRUSHES CPU: ClickHouse merges all uncompacted parts synchronously during read!
SELECT id, status, amount 
FROM orders_replacing FINAL 
WHERE tenant_id = 'org_123';
```

#### Production Standard (Correct)
> **Standard**: Uses argMax(field, ver) aggregation to resolve the latest record state at query time. Operates in parallel across all CPU cores with zero heavy disk merging overhead.
```sql
-- Table Schema Definition with Version Column
CREATE TABLE orders_replacing (
  tenant_id LowCardinality(String),
  id UUID,
  status String,
  amount Decimal(18, 4),
  ver UInt64
) ENGINE = ReplacingMergeTree(ver)
ORDER BY (tenant_id, id);

-- HIGH-PERFORMANCE DEDUPLICATION: 100x faster than FINAL
SELECT 
  id,
  argMax(status, ver) AS status,
  argMax(amount, ver) AS amount
FROM orders_replacing
WHERE tenant_id = 'org_123'
GROUP BY id;
```

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: ClickHouse ReplacingMergeTree & FINAL Query Argument Optimization

ClickHouse ReplacingMergeTree & FINAL Query Argument Optimization defines an industrial-grade behavioral standard for backend engineering. Production data architecture standard for ClickHouse. Mandates using ReplacingMergeTree with an explicit version column (updated_at) for deduplication, avoids naive unconstrained SELECT ... FINAL queries across large partitions, and leverages argMax() aggregation for high-speed sub-millisecond deduplication. 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: AI writes SELECT * FROM table FINAL on multi-billion row ClickHouse tables, causing massive single-thread merges and crushing analytical query throughput. 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 DriftAI writes SELECT * FROM table FINAL on multi-billion row ClickHouse tables, causing massive single-thread merges and crushing analytical query throughput.High
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

MUST define ReplacingMergeTree with an explicit numeric or timestamp version column

MUST define ReplacingMergeTree with an explicit numeric or timestamp version column: ReplacingMergeTree(ver).

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

MUST NOT execute SELECT ... FINAL on queries without restrictive WHERE partition filters (FINAL forces multi-threaded block merging across the entire dataset).

MUST NOT execute SELECT ... FINAL on queries without restrictive WHERE partition filters (FINAL forces multi-threaded block merging across the entire dataset).

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

SHOULD use SELECT id, argMax(status, ver) as status FROM table GROUP BY id for 10x faster deduplicated reads over FINAL.

SHOULD use SELECT id, argMax(status, ver) as status FROM table GROUP BY id for 10x faster deduplicated reads over FINAL.

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

MUST order the table by primary lookup keys

MUST order the table by primary lookup keys: ORDER BY (tenant_id, id).

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

SHOULD utilize OPTIMIZE TABLE table FINAL only during off-peak maintenance windows, never on continuous ingestion cycles.

SHOULD utilize OPTIMIZE TABLE table FINAL only during off-peak maintenance windows, never on continuous ingestion cycles.

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 ClickHouse ReplacingMergeTree & FINAL Query Argument Optimization critical for AI coding assistants?

Production data architecture standard for ClickHouse. Mandates using ReplacingMergeTree with an explicit version column (updated_at) for deduplication, avoids naive unconstrained SELECT ... FINAL queries across large partitions, and leverages argMax() aggregation for high-speed sub-millisecond deduplication. 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 (AI writes SELECT * FROM table FINAL on multi-billion row ClickHouse tables, causing massive single-thread merges and crushing analytical query throughput.) 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

ClickHouse