Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

docs(agents): improve `Agents.md` (#13372)

Tobias Wochinger205d896a311b
diff --git a/.agents/AGENTS.md b/.agents/AGENTS.md
index 5802a6d468..4bf0a118b0 100644
--- a/.agents/AGENTS.md
+++ b/.agents/AGENTS.md
@@ -98,8 +98,8 @@ langfuse/
- Build check: `pnpm run build:check`
- Full build: `pnpm run build`
- Full reset/bootstrap (destructive): `pnpm run dx`
-- Codex environment bootstrap: `bash scripts/codex/setup.sh`
-- Codex environment maintenance: `bash scripts/codex/maintenance.sh`
+- Environment/worktree bootstrap: `bash scripts/codex/setup.sh`
+- Environment/worktree maintenance: `bash scripts/codex/maintenance.sh`
- Install Playwright Chromium for agent browser review: `pnpm run playwright:install`
Minimum verification matrix:
@@ -125,6 +125,8 @@ Minimum verification matrix:
- `packages/shared/prisma/generated/*`
- Public API contract changes must update Fern sources in `fern/apis/**` and
regenerated outputs. Never hand-edit `generated/**`.
+- Before adding constants, value lists, or display mappings, search for an
+ existing owner and reuse or extend that source of truth.
- Keep tests independent and parallel-safe.
- For bug fixes, write the failing test first, confirm it fails, then fix the
bug.
diff --git a/.agents/skills/backend-dev-guidelines/AGENTS.md b/.agents/skills/backend-dev-guidelines/AGENTS.md
index ff3baba9bb..fcb0d64c0d 100644
--- a/.agents/skills/backend-dev-guidelines/AGENTS.md
+++ b/.agents/skills/backend-dev-guidelines/AGENTS.md
@@ -2,7 +2,12 @@
## Purpose
-Establish consistency and best practices across Langfuse's backend packages (web, worker, packages/shared) using Next.js 14, tRPC, BullMQ, and TypeScript patterns.
+Establish consistency and best practices across Langfuse's backend packages
+(`web`, `worker`, `packages/shared`) using Next.js, tRPC, BullMQ, and TypeScript
+patterns. Check package manifests such as `web/package.json` for current
+framework versions before version-sensitive work.
+Keep this file as an entrypoint; open reference files only when the task needs
+their details.
## When to Use This Skill
@@ -64,7 +69,7 @@ Use this guide when working on:
### Layered Architecture
```
-# Web Package (Next.js 14)
+# Web Package (Next.js)
β”Œβ”€ tRPC API ──────────────────┐ β”Œβ”€β”€ Public REST API ──────────┐
β”‚ β”‚ β”‚ β”‚
@@ -105,150 +110,6 @@ for complete details.
---
-## Directory Structure
-
-### Web Package (`/web/`)
-
-```
-web/src/
-β”œβ”€β”€ features/ # Feature-organized code
-β”‚ β”œβ”€β”€ [feature-name]/
-β”‚ β”‚ β”œβ”€β”€ server/ # Backend logic
-β”‚ β”‚ β”‚ β”œβ”€β”€ *Router.ts # tRPC router
-β”‚ β”‚ β”‚ └── service.ts # Business logic
-β”‚ β”‚ β”œβ”€β”€ components/ # React components
-β”‚ β”‚ └── types/ # Feature types
-β”œβ”€β”€ server/
-β”‚ β”œβ”€β”€ api/
-β”‚ β”‚ β”œβ”€β”€ routers/ # tRPC routers
-β”‚ β”‚ β”œβ”€β”€ trpc.ts # tRPC setup & middleware
-β”‚ β”‚ └── root.ts # Main router
-β”‚ β”œβ”€β”€ auth.ts # NextAuth.js config
-β”‚ └── db.ts # Database client
-β”œβ”€β”€ pages/
-β”‚ β”œβ”€β”€ api/
-β”‚ β”‚ β”œβ”€β”€ public/ # Public REST APIs
-β”‚ β”‚ └── trpc/ # tRPC endpoint
-β”‚ └── [routes].tsx # Next.js pages
-β”œβ”€β”€ __tests__/ # Vitest tests
-β”‚ └── server/ # Integration tests
-β”œβ”€β”€ instrumentation.ts # OpenTelemetry (FIRST IMPORT)
-└── env.mjs # Environment config
-```
-
-### Worker Package (`/worker/`)
-
-```
-worker/src/
-β”œβ”€β”€ queues/ # BullMQ processors
-β”‚ β”œβ”€β”€ evalQueue.ts
-β”‚ β”œβ”€β”€ ingestionQueue.ts
-β”‚ └── workerManager.ts
-β”œβ”€β”€ features/ # Business logic
-β”‚ └── [feature]/
-β”‚ └── service.ts
-β”œβ”€β”€ instrumentation.ts # OpenTelemetry (FIRST IMPORT)
-β”œβ”€β”€ app.ts # Express setup + queue registration
-β”œβ”€β”€ env.ts # Environment config
-└── index.ts # Server start
-```
-
-### Shared Package (`/packages/shared/`)
-
-```
-shared/src/
-β”œβ”€β”€ server/ # Server utilities
-β”‚ β”œβ”€β”€ auth/ # Authentication helpers
-β”‚ β”œβ”€β”€ clickhouse/ # ClickHouse client & schema
-β”‚ β”œβ”€β”€ instrumentation/ # OpenTelemetry helpers
-β”‚ β”œβ”€β”€ llm/ # LLM integration utilities
-β”‚ β”œβ”€β”€ redis/ # Redis queues & cache
-β”‚ β”œβ”€β”€ repositories/ # Data repositories
-β”‚ β”œβ”€β”€ services/ # Shared services
-β”‚ β”œβ”€β”€ utils/ # Server utilities
-β”‚ β”œβ”€β”€ logger.ts
-β”‚ └── queues.ts
-β”œβ”€β”€ encryption/ # Encryption utilities
-β”œβ”€β”€ features/ # Feature-specific code
-β”œβ”€β”€ tableDefinitions/ # Table schemas
-β”œβ”€β”€ utils/ # Shared utilities
-β”œβ”€β”€ constants.ts
-β”œβ”€β”€ db.ts # Prisma client
-β”œβ”€β”€ env.ts # Environment config
-└── index.ts # Main exports
-```
-
-**Import Paths (package.json exports):**
-
-The shared package exposes specific import paths for different use cases:
-
-| Import Path | Maps To | Use For |
-| ------------------------------------------ | --------------------------------- | --------------------------------------------------------------- |
-| `@langfuse/shared` | `dist/src/index.js` | General types, schemas, utilities, constants |
-| `@langfuse/shared/src/db` | `dist/src/db.js` | Prisma client and database types |
-| `@langfuse/shared/src/server` | `dist/src/server/index.js` | Server-side utilities (queues, auth, services, instrumentation) |
-| `@langfuse/shared/src/server/auth/apiKeys` | `dist/src/server/auth/apiKeys.js` | API key management utilities |
-| `@langfuse/shared/encryption` | `dist/src/encryption/index.js` | Encryption and signature utilities |
-
-**Usage Examples:**
-
-```typescript
-// General imports - types, schemas, constants, interfaces
-import {
- CloudConfigSchema,
- StringNoHTML,
- AnnotationQueueObjectType,
- type APIScoreV2,
- type ColumnDefinition,
- Role,
-} from "@langfuse/shared";
-
-// Database - Prisma client and types
-import { prisma, Prisma, JobExecutionStatus } from "@langfuse/shared/src/db";
-import { type DB as Database } from "@langfuse/shared";
-
-// Server utilities - queues, services, auth, instrumentation
-import {
- logger,
- instrumentAsync,
- traceException,
- redis,
- getTracesTable,
- StorageService,
- sendMembershipInvitationEmail,
- invalidateApiKeysForProject,
- recordIncrement,
- recordHistogram,
-} from "@langfuse/shared/src/server";
-
-// API key management (specific path)
-import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";
-
-// Encryption utilities
-import { encrypt, decrypt, sign, verify } from "@langfuse/shared/encryption";
-```
-
-**What Goes Where:**
-
-The shared package provides types, utilities, and server code used by both web and worker packages. It has **5 export paths** that control frontend vs backend access:
-
-| Import Path | Usage | What's Included |
-| ------------------------------------------ | --------------------- | ---------------------------------------------------------------------------------- |
-| `@langfuse/shared` | βœ… Frontend + Backend | Prisma types, Zod schemas, constants, table definitions, domain models, utilities |
-| `@langfuse/shared/src/db` | πŸ”’ Backend only | Prisma client instance |
-| `@langfuse/shared/src/server` | πŸ”’ Backend only | Services, repositories, queues, auth, ClickHouse, LLM integration, instrumentation |
-| `@langfuse/shared/src/server/auth/apiKeys` | πŸ”’ Backend only | API key management (separated to avoid circular deps) |
-| `@langfuse/shared/encryption` | πŸ”’ Backend only | Database field encryption/decryption |
-
-**Naming Conventions:**
-
-- tRPC Routers: `camelCaseRouter.ts` - `datasetRouter.ts`
-- Services: `service.ts` in feature directory
-- Queue Processors: `camelCaseQueue.ts` - `evalQueue.ts`
-- Public APIs: `kebab-case.ts` - `dataset-items.ts`
-
----
-
## Core Principles
### 1. tRPC Procedures Delegate to Services
@@ -355,51 +216,10 @@ const result = await instrumentAsync(
### 7. Comprehensive Testing Required
-Write tests for all new features and bug fixes. See [testing-guide.md](references/testing-guide.md) for detailed examples.
-
-**Test Types:**
-
-| Type | Framework | Location | Purpose |
-| ----------- | --------- | ------------------------------------------ | ---------------------------- |
-| Integration | Vitest | `web/src/__tests__/server/` | Full API endpoint testing |
-| tRPC | Vitest | `web/src/__tests__/server/` | tRPC procedures with auth |
-| Service | Vitest | `web/src/__tests__/server/repositories/` | Repository/service functions |
-| Worker | Vitest | `worker/src/__tests__/` | Queue processors & streams |
-
-**Quick Examples:**
-
-```typescript
-// Integration Test (Public API)
-const res = await makeZodVerifiedAPICall(
- PostDatasetsV1Response, "POST", "/api/public/datasets",
- { name: "test-dataset" }, auth
-);
-expect(res.status).toBe(200);
-
-// tRPC Test
-const { caller } = await prepare(); // Creates session + caller
-const response = await caller.automations.getAutomations({ projectId });
-expect(response).toHaveLength(1);
-
-// Service Test
-const result = await getObservationsWithModelDataFromEventsTable({
- projectId, filter: [...], limit: 1000, offset: 0
-});
-expect(result.length).toBeGreaterThan(0);
-
-// Worker Test (vitest)
-const stream = await getObservationStream({ projectId, filter: [] });
-const rows = [];
-for await (const chunk of stream) rows.push(chunk);
-expect(rows).toHaveLength(2);
-```
-
-**Key Principles:**
-
-- Use unique IDs (`randomUUID()`) to avoid test interference
-- Clean up test data or use unique project IDs
-- Tests must be independent and runnable in any order
-- Prefer scoped cleanup or unique project IDs over global reset helpers
+Add targeted tests for new backend behavior and bug fixes. Keep tests
+independent and parallel-safe. See
+[testing-guide.md](references/testing-guide.md) for tRPC, public API, service,
+repository, and worker examples.
### 8. Always Filter by projectId for Tenant Isolation
@@ -448,72 +268,26 @@ Trace:
---
-## Common Imports
+## Live Examples
-```typescript
-// tRPC (Web)
-import { z } from "zod/v4";
-import {
- createTRPCRouter,
- protectedProjectProcedure,
-} from "@/src/server/api/trpc";
-import { TRPCError } from "@trpc/server";
-
-// Database
-import { prisma } from "@langfuse/shared/src/db";
-import type { Prisma } from "@prisma/client";
-
-// ClickHouse
-import {
- queryClickhouse,
- queryClickhouseStream,
- upsertClickhouse,
-} from "@langfuse/shared/src/server";
-
-// Observability - OpenTelemetry + DataDog (NOT Sentry for backend)
-import {
- logger, // Winston logger with OTEL/DataDog trace context
- traceException, // Record exceptions to OpenTelemetry spans
- instrumentAsync, // Create instrumented spans for operations
-} from "@langfuse/shared/src/server";
-
-// Config
-import { env } from "@/src/env.mjs"; // web
-// or
-import { env } from "./env"; // worker
-
-// Public API (Web)
-import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
-import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
-
-// Queue Processing (Worker)
-import { Job } from "bullmq";
-import { QueueName, TQueueJobTypes } from "@langfuse/shared/src/server";
-```
+Reference existing Langfuse features for implementation patterns:
+- tRPC router with project auth and Zod input:
+ `web/src/features/events/server/eventsRouter.ts`
+- Public API route with middleware and typed request/response schemas:
+ `web/src/pages/api/public/datasets.ts`
+- Worker queue processor with typed jobs, logging, and retry behavior:
+ `worker/src/queues/evalQueue.ts`
+- Tenant filters for Prisma and ClickHouse:
+ `references/database-patterns.md`
---
-## Quick Reference
+## Naming Conventions
-### HTTP Status Codes
-
-| Code | Use Case |
-| ---- | ------------ |
-| 200 | Success |
-| 201 | Created |
-| 400 | Bad Request |
-| 401 | Unauthorized |
-| 403 | Forbidden |
-| 404 | Not Found |
-| 500 | Server Error |
-
-### Example Features to Reference
-
-Reference existing Langfuse features for implementation patterns:
-- **Datasets** (`web/src/features/datasets/`) - Complete feature with tRPC router, public API, and service
-- **Prompts** (`web/src/features/prompts/`) - Feature with versioning and templates
-- **Evaluations** (`web/src/features/evals/`) - Complex feature with worker integration
-- **Public API** (`web/src/features/public-api/`) - Middleware and route patterns
+- tRPC routers: `camelCaseRouter.ts`, e.g. `datasetRouter.ts`
+- Services: `service.ts` in the feature server directory
+- Queue processors: `camelCaseQueue.ts`, e.g. `evalQueue.ts`
+- Public API routes: kebab-case filenames, e.g. `dataset-items.ts`
---
@@ -530,6 +304,9 @@ Reference existing Langfuse features for implementation patterns:
## Navigation Guide
+Keep detailed backend guidance in these focused reference files and open only
+the one that matches the task.
+
| Need to... | Read this |
| ------------------------- | ------------------------------------------------------------ |
| Understand architecture | [architecture-overview.md](references/architecture-overview.md) |
@@ -541,37 +318,3 @@ Reference existing Langfuse features for implementation patterns:
| Write tests | [testing-guide.md](references/testing-guide.md) |
---
-
-## Reference Files
-
-### [architecture-overview.md](references/architecture-overview.md)
-
-Three-layer architecture (tRPC/Public API β†’ Services β†’ Data Access), request lifecycle for tRPC/Public API/Worker, Next.js 14 directory structure, dual database system (PostgreSQL + ClickHouse), separation of concerns, repository pattern for complex queries
-
-### [routing-and-controllers.md](references/routing-and-controllers.md)
-
-Next.js file-based routing, tRPC router patterns, Public REST API routes, layered architecture (Entry Points β†’ Services β†’ Repositories β†’ Database), service layer organization, anti-patterns to avoid
-
-### [services-and-repositories.md](references/services-and-repositories.md)
-
-Service layer overview, dependency injection patterns, singleton patterns, repository pattern for data access, service design principles, caching strategies, testing services
-
-### [middleware-guide.md](references/middleware-guide.md)
-
-tRPC middleware (withErrorHandling, withOtelInstrumentation, enforceUserIsAuthed), seven tRPC procedure types (publicProcedure, authenticatedProcedure, protectedProjectProcedure, etc.), Public API middleware (withMiddlewares, createAuthedProjectAPIRoute), authentication patterns (NextAuth for tRPC, Basic Auth for Public API)
-
-### [database-patterns.md](references/database-patterns.md)
-
-Dual database architecture (PostgreSQL via Prisma + ClickHouse via direct client), PostgreSQL CRUD operations, ClickHouse query patterns (queryClickhouse, queryClickhouseStream, upsertClickhouse), repository pattern for complex queries, tenant isolation with projectId filtering, when to use which database
-
-### [configuration.md](references/configuration.md)
-
-Environment variable validation with Zod, package-specific configs (web/env.mjs with t3-oss/env-nextjs, worker/env.ts, shared/env.ts), NEXT_PUBLIC_LANGFUSE_CLOUD_REGION usage, LANGFUSE_EE_LICENSE_KEY for enterprise features, best practices for env management
-
-### [testing-guide.md](references/testing-guide.md)
-
-Integration tests (Public API with makeZodVerifiedAPICall), tRPC tests (createInnerTRPCContext, appRouter.createCaller), service-level tests (repository/service functions), worker tests (vitest with streams), test isolation principles, running tests (Vitest for web and worker)
-
-**Skill Status**: COMPLETE βœ…
-**Line Count**: ~540 lines
-**Progressive Disclosure**: 7 reference files βœ…
diff --git a/.agents/skills/backend-dev-guidelines/SKILL.md b/.agents/skills/backend-dev-guidelines/SKILL.md
index cff41f10f1..3e8b98ffef 100644
--- a/.agents/skills/backend-dev-guidelines/SKILL.md
+++ b/.agents/skills/backend-dev-guidelines/SKILL.md
@@ -1,6 +1,6 @@
---
name: backend-dev-guidelines
-description: Shared backend guide for Langfuse's Next.js 14, tRPC, BullMQ, and TypeScript monorepo. Use when creating or reviewing tRPC routers, public REST endpoints, BullMQ queue processors, backend services, middleware, Prisma or ClickHouse data access, OpenTelemetry instrumentation, Zod validation, env configuration, or backend tests across web, worker, or packages/shared.
+description: Shared backend guide for Langfuse's Next.js, tRPC, BullMQ, and TypeScript monorepo. Use when creating or reviewing tRPC routers, public REST endpoints, BullMQ queue processors, backend services, middleware, Prisma or ClickHouse data access, OpenTelemetry instrumentation, Zod validation, env configuration, or backend tests across web, worker, or packages/shared.
---
# Backend Development Guidelines
diff --git a/.agents/skills/backend-dev-guidelines/references/architecture-overview.md b/.agents/skills/backend-dev-guidelines/references/architecture-overview.md
index 288292a2f2..896a96fd7a 100644
--- a/.agents/skills/backend-dev-guidelines/references/architecture-overview.md
+++ b/.agents/skills/backend-dev-guidelines/references/architecture-overview.md
@@ -1,6 +1,6 @@
# Architecture Overview - Langfuse Backend
-Complete guide to the layered architecture pattern used in Langfuse's Next.js 14/tRPC/Express monorepo.
+Complete guide to the layered architecture pattern used in Langfuse's Next.js/tRPC/Express monorepo. Check package manifests such as `web/package.json` for current framework versions before version-sensitive work.
## Table of Contents
@@ -20,7 +20,7 @@ Langfuse uses a **three-layer architecture** with two primary entry points (tRPC
### The Three Layers
```
-# Web Package (Next.js 14)
+# Web Package (Next.js)
β”Œβ”€ tRPC API ──────────────────┐ β”Œβ”€β”€ Public REST API ──────────┐
β”‚ β”‚ β”‚ β”‚
diff --git a/.agents/skills/backend-dev-guidelines/references/services-and-repositories.md b/.agents/skills/backend-dev-guidelines/references/services-and-repositories.md
index 3b2e66ea39..2eb73ed9f9 100644
--- a/.agents/skills/backend-dev-guidelines/references/services-and-repositories.md
+++ b/.agents/skills/backend-dev-guidelines/references/services-and-repositories.md
@@ -412,190 +412,19 @@ Repository: "Here's the Prisma query that does that"
- ❌ Know about HTTP
- ❌ Make decisions (that's service layer)
-### Repository Template
+### Langfuse Repository Examples
-```typescript
-// repositories/UserRepository.ts
-import { PrismaService } from "@project-lifecycle-portal/database";
-import type { User, Prisma } from "@project-lifecycle-portal/database";
-
-export class UserRepository {
- /**
- * Find user by ID with optimized query
- */
- async findById(userId: string): Promise<User | null> {
- try {
- return await PrismaService.main.user.findUnique({
- where: { userID: userId },
- select: {
- userID: true,
- email: true,
- name: true,
- isActive: true,
- roles: true,
- createdAt: true,
- updatedAt: true,
- },
- });
- } catch (error) {
- console.error("[UserRepository] Error finding user by ID:", error);
- throw new Error(`Failed to find user: ${userId}`);
- }
- }
-
- /**
- * Find all active users
- */
- async findActive(options?: {
- orderBy?: Prisma.UserOrderByWithRelationInput;
- }): Promise<User[]> {
- try {
- return await PrismaService.main.user.findMany({
- where: { isActive: true },
- orderBy: options?.orderBy || { name: "asc" },
- select: {
- userID: true,
- email: true,
- name: true,
- roles: true,
- },
- });
- } catch (error) {
- console.error("[UserRepository] Error finding active users:", error);
- throw new Error("Failed to find active users");
- }
- }
-
- /**
- * Find user by email
- */
- async findByEmail(email: string): Promise<User | null> {
- try {
- return await PrismaService.main.user.findUnique({
- where: { email },
- });
- } catch (error) {
- console.error("[UserRepository] Error finding user by email:", error);
- throw new Error(`Failed to find user with email: ${email}`);
- }
- }
-
- /**
- * Create new user
- */
- async create(data: Prisma.UserCreateInput): Promise<User> {
- try {
- return await PrismaService.main.user.create({ data });
- } catch (error) {
- console.error("[UserRepository] Error creating user:", error);
- throw new Error("Failed to create user");
- }
- }
-
- /**
- * Update user
- */
- async update(userId: string, data: Prisma.UserUpdateInput): Promise<User> {
- try {
- return await PrismaService.main.user.update({
- where: { userID: userId },
- data,
- });
- } catch (error) {
- console.error("[UserRepository] Error updating user:", error);
- throw new Error(`Failed to update user: ${userId}`);
- }
- }
-
- /**
- * Delete user (soft delete by setting isActive = false)
- */
- async delete(userId: string): Promise<User> {
- try {
- return await PrismaService.main.user.update({
- where: { userID: userId },
- data: { isActive: false },
- });
- } catch (error) {
- console.error("[UserRepository] Error deleting user:", error);
- throw new Error(`Failed to delete user: ${userId}`);
- }
- }
-
- /**
- * Check if email exists
- */
- async emailExists(email: string): Promise<boolean> {
- try {
- const count = await PrismaService.main.user.count({
- where: { email },
- });
- return count > 0;
- } catch (error) {
- console.error("[UserRepository] Error checking email exists:", error);
- throw new Error("Failed to check if email exists");
- }
- }
-}
-
-// Export singleton instance
-export const userRepository = new UserRepository();
-```
-
-**Using Repository in Service:**
-
-```typescript
-// services/userService.ts
-import { userRepository } from "../repositories/UserRepository";
-import { ConflictError, NotFoundError } from "../utils/errors";
-
-export class UserService {
- /**
- * Create new user with business rules
- */
- async createUser(data: {
- email: string;
- name: string;
- roles: string[];
- }): Promise<User> {
- // Business rule: Check if email already exists
- const emailExists = await userRepository.emailExists(data.email);
- if (emailExists) {
- throw new ConflictError("Email already exists");
- }
-
- // Business rule: Validate roles
- const validRoles = ["admin", "operations", "user"];
- const invalidRoles = data.roles.filter(
- (role) => !validRoles.includes(role),
- );
- if (invalidRoles.length > 0) {
- throw new ValidationError(`Invalid roles: ${invalidRoles.join(", ")}`);
- }
-
- // Create user via repository
- return await userRepository.create({
- email: data.email,
- name: data.name,
- roles: data.roles,
- isActive: true,
- });
- }
-
- /**
- * Get user by ID
- */
- async getUser(userId: string): Promise<User> {
- const user = await userRepository.findById(userId);
+Use these current Langfuse files as repository templates:
- if (!user) {
- throw new NotFoundError(`User not found: ${userId}`);
- }
+- PostgreSQL repository with project-scoped filters:
+ `packages/shared/src/server/repositories/comments.ts`
+- ClickHouse repository with project-scoped filters and query helpers:
+ `packages/shared/src/server/repositories/traces.ts`
+- Repository tests:
+ `web/src/__tests__/server/repositories/event-repository.servertest.ts`
- return user;
- }
-}
-```
+Keep data-access concerns in repositories and business decisions in services.
+Project-scoped queries must include `projectId` or `project_id` filters.
---
@@ -803,70 +632,13 @@ class UserService {
## Testing Services
-### Unit Tests
+Use `testing-guide.md` for backend test patterns. Prefer current Langfuse tests
+over invented examples:
-```typescript
-// tests/userService.test.ts
-import { UserService } from "../services/userService";
-import { userRepository } from "../repositories/UserRepository";
-import { ConflictError } from "../utils/errors";
-import type { Mock } from "vitest";
-
-// Mock repository
-vi.mock("../repositories/UserRepository");
-
-describe("UserService", () => {
- let userService: UserService;
-
- beforeEach(() => {
- userService = new UserService();
- vi.clearAllMocks();
- });
-
- describe("createUser", () => {
- it("should create user when email does not exist", async () => {
- // Arrange
- const userData = {
- email: "[email protected]",
- name: "Test User",
- roles: ["user"],
- };
-
- (userRepository.emailExists as Mock).mockResolvedValue(false);
- (userRepository.create as Mock).mockResolvedValue({
- userID: "123",
- ...userData,
- });
-
- // Act
- const user = await userService.createUser(userData);
-
- // Assert
- expect(user).toBeDefined();
- expect(user.email).toBe(userData.email);
- expect(userRepository.emailExists).toHaveBeenCalledWith(userData.email);
- expect(userRepository.create).toHaveBeenCalled();
- });
-
- it("should throw ConflictError when email exists", async () => {
- // Arrange
- const userData = {
- email: "[email protected]",
- name: "Test User",
- roles: ["user"],
- };
-
- (userRepository.emailExists as Mock).mockResolvedValue(true);
-
- // Act & Assert
- await expect(userService.createUser(userData)).rejects.toThrow(
- ConflictError,
- );
- expect(userRepository.create).not.toHaveBeenCalled();
- });
- });
-});
-```
+- Repository tests:
+ `web/src/__tests__/server/repositories/event-repository.servertest.ts`
+- Pure service unit tests:
+ `web/src/__tests__/server/unit/`
---
diff --git a/.agents/skills/backend-dev-guidelines/references/testing-guide.md b/.agents/skills/backend-dev-guidelines/references/testing-guide.md
index 9db03aac1a..2e89b86c6e 100644
--- a/.agents/skills/backend-dev-guidelines/references/testing-guide.md
+++ b/.agents/skills/backend-dev-guidelines/references/testing-guide.md
@@ -4,16 +4,56 @@ Complete guide to testing Langfuse backend services across web, worker, and shar
## Table of Contents
+- [Key Testing Principles](#key-testing-principles)
- [Test Types Overview](#test-types-overview)
- [Integration Tests (Public API)](#integration-tests-public-api)
- [Service-Level Tests (Repository/Service)](#service-level-tests-repositoryservice)
- [tRPC Tests (Procedure Testing)](#trpc-tests-procedure-testing)
- [Worker Tests (Queue Processing)](#worker-tests-queue-processing)
-- [Key Testing Principles](#key-testing-principles)
- [Running Tests](#running-tests)
---
+## Key Testing Principles
+
+### General Principles
+
+1. **Test Isolation**: Each test should be independent and runnable in any order
+2. **Unique IDs**: Use `randomUUID()` or unique project IDs to avoid test interference
+3. **Cleanup**: Always clean up test data in service tests (or use unique project IDs)
+4. **Avoid Global Resets**: Prefer scoped cleanup or unique project IDs over global reset helpers
+5. **Flags and Fallbacks**: When code branches on env flags, feature flags, or fallback data paths, test both branches and ensure fixtures are written to the same store the branch reads from
+
+### By Test Type
+
+| Test Type | Key Principles |
+|-----------|----------------|
+| **Integration** | Test HTTP endpoints, validate status codes and response shapes |
+| **tRPC** | Use `createInnerTRPCContext` and `appRouter.createCaller`, test auth/permissions |
+| **Service** | Test individual functions with isolated data, always cleanup |
+| **Worker** | Use vitest, test streams with async iteration, test filtering logic |
+
+### Test Data Management
+
+```typescript
+// βœ… GOOD: Use unique IDs
+const projectId = randomUUID();
+const traceId = randomUUID();
+
+// βœ… GOOD: Cleanup in service tests
+afterAll(async () => {
+ await prisma.model.delete({ where: { id: modelId } });
+});
+
+// βœ… GOOD: Use unique projects (no cleanup needed)
+const { projectId } = await createOrgProjectAndApiKey();
+
+// ❌ BAD: Shared test data between tests
+const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+```
+
+---
+
## Test Types Overview
Langfuse uses multiple testing strategies for different layers:
@@ -464,75 +504,15 @@ describe("batch export test suite", () => {
---
-## Key Testing Principles
-
-### General Principles
-
-1. **Test Isolation**: Each test should be independent and runnable in any order
-2. **Unique IDs**: Use `randomUUID()` or unique project IDs to avoid test interference
-3. **Cleanup**: Always clean up test data in service tests (or use unique project IDs)
-4. **Avoid Global Resets**: Prefer scoped cleanup or unique project IDs over global reset helpers
-
-### By Test Type
-
-| Test Type | Key Principles |
-|-----------|----------------|
-| **Integration** | Test HTTP endpoints, validate status codes and response shapes |
-| **tRPC** | Use `createInnerTRPCContext` and `appRouter.createCaller`, test auth/permissions |
-| **Service** | Test individual functions with isolated data, always cleanup |
-| **Worker** | Use vitest, test streams with async iteration, test filtering logic |
-
-### Test Data Management
-
-```typescript
-// βœ… GOOD: Use unique IDs
-const projectId = randomUUID();
-const traceId = randomUUID();
-
-// βœ… GOOD: Cleanup in service tests
-afterAll(async () => {
- await prisma.model.delete({ where: { id: modelId } });
-});
-
-// βœ… GOOD: Use unique projects (no cleanup needed)
-const { projectId } = await createOrgProjectAndApiKey();
-
-// ❌ BAD: Shared test data between tests
-const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
-```
-
----
-
## Running Tests
-### Web Tests (Vitest)
-
-```bash
-# Run all server tests
-pnpm --filter web run test
+Use the nearest package `AGENTS.md` as the source of truth for current test
+commands.
-# Run all client tests
-pnpm --filter web run test-client
-
-# Run specific test file
-pnpm --filter web run test -- datasets-api
-
-# Run watch mode
-pnpm --filter web run test:watch
-```
-
-### Worker Tests (Vitest)
-
-```bash
-# Run all worker tests
-pnpm run test --filter=worker
-
-# Run specific test file
-pnpm run test --filter=worker -- batchExport
-
-# Run specific test
-pnpm run test --filter=worker -- batchExport -t "should export observations"
-```
+Common targeted forms:
+- Web server tests: `pnpm --filter web run test -- <pattern>`
+- Web client tests: `pnpm --filter web run test-client -- <pattern>`
+- Worker tests: `pnpm --filter worker run test <file-or-pattern>`
---
diff --git a/.agents/skills/clickhouse-best-practices/AGENTS.md b/.agents/skills/clickhouse-best-practices/AGENTS.md
index fc35e41dbb..bf5a6f6159 100644
--- a/.agents/skills/clickhouse-best-practices/AGENTS.md
+++ b/.agents/skills/clickhouse-best-practices/AGENTS.md
@@ -1,1572 +1,56 @@
# ClickHouse Best Practices
-**Version 0.1.0**
-ClickHouse Inc
-January 2026
-ClickHouse 24.1+
-
-> **Note:**
-> This document is mainly for agents and LLMs to follow when designing,
-> optimizing, or maintaining ClickHouse databases. Humans may also find it
-> useful, but guidance here is optimized for automation and consistency by
-> AI-assisted workflows.
-
----
-
-## Abstract
-
-Comprehensive best practices for ClickHouse database optimization. Covers schema design, query optimization, table engines, indexing strategies, materialized views, distributed operations, and operational best practices. Each rule includes detailed explanations, SQL examples comparing incorrect vs. correct implementations, and specific impact metrics to guide database design and query optimization.
-
----
-
-## Table of Contents
-
-1. [Schema Design](#1-schema-design) β€” **CRITICAL**
- - 1.1 [Avoid Nullable Unless Semantically Required](#11-avoid-nullable-unless-semantically-required)
- - 1.2 [Consider Starting Without Partitioning](#12-consider-starting-without-partitioning)
- - 1.3 [Filter on ORDER BY Columns in Queries](#13-filter-on-order-by-columns-in-queries)
- - 1.4 [Keep Partition Cardinality Low (100-1,000 Values)](#14-keep-partition-cardinality-low-100-1000-values)
- - 1.5 [Minimize Bit-Width for Numeric Types](#15-minimize-bit-width-for-numeric-types)
- - 1.6 [Order Columns by Cardinality (Low to High)](#16-order-columns-by-cardinality-low-to-high)
- - 1.7 [Plan PRIMARY KEY Before Table Creation](#17-plan-primary-key-before-table-creation)
- - 1.8 [Prioritize Filter Columns in ORDER BY](#18-prioritize-filter-columns-in-order-by)
- - 1.9 [Understand Partition Query Performance Trade-offs](#19-understand-partition-query-performance-trade-offs)
- - 1.10 [Use Enum for Finite Value Sets](#110-use-enum-for-finite-value-sets)
- - 1.11 [Use JSON Type for Dynamic Schemas](#111-use-json-type-for-dynamic-schemas)
- - 1.12 [Use LowCardinality for Repeated Strings](#112-use-lowcardinality-for-repeated-strings)
- - 1.13 [Use Native Types Instead of String](#113-use-native-types-instead-of-string)
- - 1.14 [Use Partitioning for Data Lifecycle Management](#114-use-partitioning-for-data-lifecycle-management)
-2. [Query Optimization](#2-query-optimization) β€” **CRITICAL**
- - 2.1 [Choose the Right JOIN Algorithm](#21-choose-the-right-join-algorithm)
- - 2.2 [Consider Alternatives to JOINs](#22-consider-alternatives-to-joins)
- - 2.3 [Filter Tables Before Joining](#23-filter-tables-before-joining)
- - 2.4 [Optimize NULL Handling in Outer JOINs](#24-optimize-null-handling-in-outer-joins)
- - 2.5 [Use ANY JOIN When Only One Match Needed](#25-use-any-join-when-only-one-match-needed)
- - 2.6 [Use Data Skipping Indices for Non-ORDER BY Filters](#26-use-data-skipping-indices-for-non-order-by-filters)
- - 2.7 [Use Incremental MVs for Real-Time Aggregations](#27-use-incremental-mvs-for-real-time-aggregations)
- - 2.8 [Use Refreshable MVs for Complex Joins and Batch Workflows](#28-use-refreshable-mvs-for-complex-joins-and-batch-workflows)
-3. [Insert Strategy](#3-insert-strategy) β€” **CRITICAL**
- - 3.1 [Avoid ALTER TABLE DELETE](#31-avoid-alter-table-delete)
- - 3.2 [Avoid ALTER TABLE UPDATE](#32-avoid-alter-table-update)
- - 3.3 [Avoid OPTIMIZE TABLE FINAL](#33-avoid-optimize-table-final)
- - 3.4 [Batch Inserts Appropriately (10K-100K rows)](#34-batch-inserts-appropriately-10k-100k-rows)
- - 3.5 [Use Async Inserts for High-Frequency Small Batches](#35-use-async-inserts-for-high-frequency-small-batches)
- - 3.6 [Use Native Format for Best Insert Performance](#36-use-native-format-for-best-insert-performance)
-
----
-
-## 1. Schema Design
-
-**Impact: CRITICAL**
-
-Proper schema design is foundational to ClickHouse performance. ORDER BY is immutable after table creation; wrong choices require full data migration. Includes primary key selection, data types, partitioning strategy, and JSON usage. Column types and ordering can impact query speed by orders of magnitude.
-
-### 1.1 Avoid Nullable Unless Semantically Required
-
-**Impact: HIGH (Nullable adds storage overhead; use DEFAULT values instead)**
-
-Nullable columns maintain a separate UInt8 column for tracking null values, increasing storage and degrading performance. Use DEFAULT values instead when feasible.
-
-**Incorrect: Nullable everywhere**
-
-```sql
-CREATE TABLE users (
- id Nullable(UInt64), -- IDs should never be null
- name Nullable(String), -- Empty string is fine
- age Nullable(UInt8), -- 0 is a valid default
- login_count Nullable(UInt32) -- 0 is a valid default
-)
-```
-
-**Correct: DEFAULT values, Nullable only when semantic**
-
-```sql
-CREATE TABLE users (
- id UInt64, -- Never null
- name String DEFAULT '', -- Empty = unknown
- age UInt8 DEFAULT 0, -- 0 = unknown
- login_count UInt32 DEFAULT 0, -- 0 = never logged in
- deleted_at Nullable(DateTime), -- NULL = not deleted (semantic!)
- parent_id Nullable(UInt64) -- NULL = no parent (semantic!)
-)
-```
-
-**When Nullable IS appropriate:**
-
-| Use Case | Why |
-
-|----------|-----|
-
-| `deleted_at` | NULL = "not deleted", timestamp = "deleted at X" |
-
-| `parent_id` | NULL = "no parent", value = "has parent" |
-
-| `discount_percent` | NULL = "no discount", 0 = "0% discount" |
-
-**Defaults instead of Nullable:**
-
-| Type | Default |
-
-|------|---------|
-
-| String | `''` (empty string) |
-
-| UInt*/Int* | `0` |
-
-| DateTime | `now()` or `toDateTime(0)` |
-
-| UUID | `generateUUIDv4()` |
-
-Reference: [https://clickhouse.com/docs/best-practices/select-data-types](https://clickhouse.com/docs/best-practices/select-data-types)
-
-### 1.2 Consider Starting Without Partitioning
-
-**Impact: MEDIUM (Add partitioning later when you have clear lifecycle requirements)**
-
-Start without partitioning and add it later only if:
-
-- You have clear data lifecycle requirements (retention, archiving)
-
-- Your access patterns clearly benefit from partition pruning
-
-- You understand the cardinality implications
-
-**Example: start simple**
-
-```sql
--- Start simple, no partitioning
-CREATE TABLE events (
- timestamp DateTime,
- event_type LowCardinality(String),
- user_id UInt64
-)
-ENGINE = MergeTree()
-ORDER BY (event_type, timestamp);
-
--- Add partitioning later if needed for lifecycle management
--- (requires table recreation or materialized view migration)
-```
-
-**When to add partitioning:**
-
-| Need | Add Partitioning? |
-
-|------|-------------------|
-
-| Time-based data retention | Yes |
-
-| Archive old data to cold storage | Yes |
-
-| Query performance on time ranges | Maybe (test first) |
-
-| No specific lifecycle needs | No |
-
-Reference: [https://clickhouse.com/docs/best-practices/choosing-a-partitioning-key](https://clickhouse.com/docs/best-practices/choosing-a-partitioning-key)
-
-### 1.3 Filter on ORDER BY Columns in Queries
-
-**Impact: CRITICAL (Skipping prefix columns prevents index usage)**
-
-Even with good schema design, queries must use ORDER BY columns to benefit. Skipping prefix columns or filtering on non-ORDER BY columns prevents index usage.
-
-**Incorrect: skips prefix or uses non-ORDER BY columns**
-
-```sql
--- Given: ORDER BY (tenant_id, event_type, timestamp)
-
--- Skips prefix columns - can't use index effectively
-SELECT * FROM events WHERE event_type = 'click';
-
--- Filter on column not in ORDER BY - full table scan
-SELECT * FROM events WHERE user_agent LIKE '%Chrome%';
-```
-
-**Correct: uses ORDER BY prefix**
-
-```sql
--- Given: ORDER BY (tenant_id, event_type, timestamp)
-
--- Full prefix match - best performance
-SELECT * FROM events
-WHERE tenant_id = 123 AND event_type = 'click';
-
--- Partial prefix - still uses index
-SELECT * FROM events WHERE tenant_id = 123;
-
--- Range on later column after equality on earlier
-SELECT * FROM events
-WHERE tenant_id = 123 AND event_type = 'click' AND timestamp >= '2024-01-01';
-```
-
-**Index usage reference:**
-
-| Filter | Index Used? |
-
-|--------|-------------|
-
-| `WHERE tenant_id = 123` | Full |
-
-| `WHERE tenant_id = 123 AND event_type = 'click'` | Full |
-
-| `WHERE event_type = 'click'` | None (skipped prefix) |
-
-| `WHERE timestamp > '2024-01-01'` | None (skipped both) |
-
-Reference: [https://clickhouse.com/docs/best-practices/choosing-a-primary-key](https://clickhouse.com/docs/best-practices/choosing-a-primary-key)
-
-### 1.4 Keep Partition Cardinality Low (100-1,000 Values)
-
-**Impact: HIGH (Too many partitions cause part explosion and 'too many parts' errors)**
-
-Too many distinct partition values create excessive data parts, eventually triggering "too many parts" errors. ClickHouse enforces limits via `max_parts_in_total` and `parts_to_throw_insert` settings.
-
-**Incorrect: high cardinality partitioning**
-
-```sql
--- High cardinality = too many partitions
-CREATE TABLE events (...)
-ENGINE = MergeTree()
-PARTITION BY user_id -- Millions of partitions!
-ORDER BY (timestamp);
-
--- Daily partitions can grow unbounded over years
-CREATE TABLE logs (...)
-ENGINE = MergeTree()
-PARTITION BY toDate(timestamp) -- 3650 partitions over 10 years
-ORDER BY (service, timestamp);
-```
-
-**Correct: bounded cardinality**
-
-```sql
--- Monthly partitions = 12 per year, bounded cardinality
-CREATE TABLE events (
- timestamp DateTime,
- event_type LowCardinality(String),
- user_id UInt64
-)
-ENGINE = MergeTree()
-PARTITION BY toStartOfMonth(timestamp)
-ORDER BY (event_type, timestamp);
-```
-
-**Validation:**
-
-```sql
--- Check partition count and health
-SELECT
- partition,
- count() as parts,
- sum(rows) as rows,
- formatReadableSize(sum(bytes_on_disk)) as size
-FROM system.parts
-WHERE table = 'events' AND active
-GROUP BY partition
-ORDER BY partition;
-
--- Warning signs: hundreds or thousands of partitions
-```
-
-Reference: [https://clickhouse.com/docs/best-practices/choosing-a-partitioning-key](https://clickhouse.com/docs/best-practices/choosing-a-partitioning-key)
-
-### 1.5 Minimize Bit-Width for Numeric Types
-
-**Impact: HIGH (Smaller types reduce storage and improve cache efficiency)**
-
-Select the smallest numeric type that accommodates your data range. Prefer unsigned types when negative values aren't needed.
-
-**Incorrect: oversized types**
-
-```sql
-CREATE TABLE metrics (
- status_code Int64, -- HTTP codes are 100-599
- age Int64, -- Human age fits in UInt8
- year Int64, -- Years fit in UInt16
- item_count Int64 -- Often small numbers
-)
-```
-
-**Correct: right-sized types**
-
-```sql
-CREATE TABLE metrics (
- status_code UInt16, -- 0-65,535 (HTTP codes fit easily)
- age UInt8, -- 0-255 (sufficient for age)
- year UInt16, -- 0-65,535 (sufficient for years)
- item_count UInt32 -- 0-4 billion (adjust based on actual max)
-)
-```
-
-**Numeric Type Reference:**
-
-| Type | Range | Bytes |
-
-|------|-------|-------|
-
-| UInt8 | 0 to 255 | 1 |
-
-| UInt16 | 0 to 65,535 | 2 |
-
-| UInt32 | 0 to 4.3 billion | 4 |
-
-| UInt64 | 0 to 18 quintillion | 8 |
-
-| Int8 | -128 to 127 | 1 |
-
-| Int16 | -32,768 to 32,767 | 2 |
-
-| Int32 | -2.1 billion to 2.1 billion | 4 |
-
-| Int64 | -9 quintillion to 9 quintillion | 8 |
-
-Reference: [https://clickhouse.com/docs/best-practices/select-data-types](https://clickhouse.com/docs/best-practices/select-data-types)
-
-### 1.6 Order Columns by Cardinality (Low to High)
-
-**Impact: CRITICAL (Enables granule skipping; high-cardinality first prevents index pruning)**
-
-Since the sparse primary index operates on data blocks (granules) rather than individual rows, low-cardinality leading columns create more useful index entries that can skip entire blocks. Place lower-cardinality columns before higher-cardinality ones in the ordering key.
-
-**Incorrect: high cardinality first**
-
-```sql
--- UUID first means no pruning benefit
-CREATE TABLE events (...)
-ENGINE = MergeTree()
-ORDER BY (event_id, event_type, timestamp);
--- Every granule has different event_id values, index can't skip anything
-```
-
-**Correct: low cardinality first**
-
-```sql
--- Low cardinality first enables pruning
-CREATE TABLE events (...)
-ENGINE = MergeTree()
-ORDER BY (event_type, event_date, event_id);
--- Index can skip entire event_type groups
-```
-
-**Column Order Guidelines:**
-
-| Position | Cardinality | Examples |
-
-|----------|-------------|----------|
-
-| 1st | Low (few distinct values) | event_type, status, country |
-
-| 2nd | Date (coarse granularity) | toDate(timestamp) |
-
-| 3rd+ | Medium-High | user_id, session_id |
-
-| Last | High (if needed) | event_id, uuid |
-
-**Tip:** Use `toDate(timestamp)` instead of raw `DateTime` columns when day-level filtering suffices - this reduces index size from 32-bit to 16-bit representations.
-
-Reference: [https://clickhouse.com/docs/best-practices/choosing-a-primary-key](https://clickhouse.com/docs/best-practices/choosing-a-primary-key)
-
-### 1.7 Plan PRIMARY KEY Before Table Creation
-
-**Impact: CRITICAL (ORDER BY is immutable; wrong choice requires full data migration)**
-
-ClickHouse's ORDER BY clause defines physical data ordering and the sparse index. Unlike other databases, **ORDER BY cannot be modified after table creation**. A wrong choice requires creating a new table and migrating all data.
-
-**Incorrect: arbitrary ORDER BY without query analysis**
-
-```sql
--- Creating table without analyzing query patterns
-CREATE TABLE events (
- event_id UUID,
- user_id UInt64,
- timestamp DateTime
-)
-ENGINE = MergeTree()
-ORDER BY (event_id); -- Chosen arbitrarily
-
--- Later: "Most queries filter by user_id!"
--- Cannot fix with: ALTER TABLE events MODIFY ORDER BY (user_id, timestamp)
--- ERROR: Cannot modify ORDER BY
-```
-
-**Correct: query-driven ORDER BY selection**
-
-```sql
--- Step 1: Document query patterns BEFORE creating table
-/*
-Query Analysis:
-- 60% of queries: WHERE user_id = ? AND timestamp BETWEEN ? AND ?
-- 25% of queries: WHERE event_type = ? AND timestamp > ?
-- 15% of queries: WHERE event_id = ?
-
-Conclusion: user_id and event_type are primary filters
-*/
-
--- Step 2: Create table with correct ORDER BY
-CREATE TABLE events (
- event_id UUID DEFAULT generateUUIDv4(),
- user_id UInt64,
- event_type LowCardinality(String),
- timestamp DateTime,
- event_date Date DEFAULT toDate(timestamp)
-)
-ENGINE = MergeTree()
-PARTITION BY toYYYYMM(event_date)
-ORDER BY (user_id, event_date, event_id);
-```
-
-**Pre-creation checklist:**
-
-- [ ] Listed top 5-10 query patterns
-
-- [ ] Identified columns in WHERE clauses with frequency
-
-- [ ] Prioritized columns that exclude large numbers of rows
-
-- [ ] Ordered columns by cardinality (low first, high last)
-
-- [ ] Limited to 4-5 key columns (typically sufficient)
-
-Reference: [https://clickhouse.com/docs/best-practices/choosing-a-primary-key](https://clickhouse.com/docs/best-practices/choosing-a-primary-key)
-
-### 1.8 Prioritize Filter Columns in ORDER BY
-
-**Impact: CRITICAL (Columns not in ORDER BY cause full table scans)**
-
-Prioritize columns frequently used in query filters (WHERE clause), especially those that exclude large numbers of rows. Queries filtering on columns not in ORDER BY result in full table scans.
-
-**Incorrect: ORDER BY doesn't match query patterns**
-
-```sql
--- If most queries filter by tenant_id:
-CREATE TABLE events (...)
-ENGINE = MergeTree()
-ORDER BY (event_id); -- Queries by tenant_id will full-scan!
-```
-
-**Correct: ORDER BY matches filter patterns**
-
-```sql
--- ORDER BY matches query filter patterns
-CREATE TABLE events (...)
-ENGINE = MergeTree()
-ORDER BY (tenant_id, event_date, event_id);
-
--- Query now uses primary index:
-SELECT * FROM events WHERE tenant_id = 123 AND event_date >= '2024-01-01';
-```
-
-**Validation:**
-
-```sql
--- Verify index usage
-EXPLAIN indexes = 1
-SELECT * FROM events WHERE tenant_id = 123;
--- Look for "PrimaryKey" with Key Condition
-```
-
-Reference: [https://clickhouse.com/docs/best-practices/choosing-a-primary-key](https://clickhouse.com/docs/best-practices/choosing-a-primary-key)
-
-### 1.9 Understand Partition Query Performance Trade-offs
-
-**Impact: MEDIUM (Partition pruning helps some queries; spanning many partitions hurts others)**
-
-Partitioning can help or hurt query performance:
-
-- **Potential improvement**: Queries filtering by partition key may benefit from partition pruning
-
-- **Potential degradation**: Queries spanning many partitions increase total parts scanned
-
-ClickHouse automatically builds **MinMax indexes** on partition columns. Data merges occur **within partitions only**, not across them.
-
-**Incorrect: query scans all partitions**
-
-```sql
--- Query must scan all partitions
-SELECT count(*) FROM events
-WHERE event_type = 'click'; -- No partition pruning
-```
-
-**Correct: query prunes to single partition**
-
-```sql
--- Query prunes to single partition
-SELECT count(*) FROM events
-WHERE timestamp >= '2024-01-01' AND timestamp < '2024-02-01'
- AND event_type = 'click';
-```
-
-Reference: [https://clickhouse.com/docs/best-practices/choosing-a-partitioning-key](https://clickhouse.com/docs/best-practices/choosing-a-partitioning-key)
-
-### 1.10 Use Enum for Finite Value Sets
-
-**Impact: MEDIUM (Insert-time validation and natural ordering; 1-2 bytes storage)**
-
-Enum types provide validation at insert time and enable queries that exploit natural ordering. Use Enum8 (up to 256 values) or Enum16 (up to 65,536 values).
-
-**Incorrect: String without validation**
-
-```sql
-CREATE TABLE orders (
- status String -- No validation, typos like "shiped" allowed
-)
-
--- Ordering requires CASE statements
-SELECT * FROM orders ORDER BY
- CASE status
- WHEN 'pending' THEN 1
- WHEN 'processing' THEN 2
- WHEN 'shipped' THEN 3
- END;
-```
-
-**Correct: Enum with validation and ordering**
-
-```sql
-CREATE TABLE orders (
- status Enum8('pending' = 1, 'processing' = 2, 'shipped' = 3, 'delivered' = 4)
-)
-
--- Insert validation: invalid values rejected
-INSERT INTO orders VALUES ('shiped'); -- ERROR: Unknown element 'shiped'
-
--- Natural ordering works automatically
-SELECT * FROM orders ORDER BY status; -- Orders by enum value (1, 2, 3, 4)
-
--- Comparisons use natural order
-SELECT * FROM orders WHERE status > 'processing'; -- shipped and delivered
-```
-
-**Enum Guidelines:**
-
-| Scenario | Use |
-
-|----------|-----|
-
-| Fixed set of values known at schema time | Enum8/Enum16 |
-
-| Values may change frequently | LowCardinality(String) |
-
-| Need insert-time validation | Enum |
-
-| Need natural ordering in queries | Enum |
-
-| < 256 distinct values | Enum8 (1 byte) |
-
-| 256-65,536 distinct values | Enum16 (2 bytes) |
-
-Reference: [https://clickhouse.com/docs/best-practices/select-data-types](https://clickhouse.com/docs/best-practices/select-data-types)
-
-### 1.11 Use JSON Type for Dynamic Schemas
-
-**Impact: MEDIUM (Field-level querying for semi-structured data; use typed columns for known schemas)**
-
-ClickHouse's JSON type splits JSON objects into separate sub-columns, enabling field-level query optimization. Use it for truly dynamic data, not everything.
-
-**Incorrect: schema bloat or opaque String**
-
-```sql
--- BAD: Hundreds of nullable columns for event properties
-CREATE TABLE events (
- event_id UUID,
- prop_page_url Nullable(String),
- prop_button_id Nullable(String),
- -- ... 100 more nullable columns
-)
-
--- BAD: JSON as String when you need field queries
-CREATE TABLE events (
- event_id UUID,
- properties String -- No field-level optimization
-)
-```
-
-**Correct: JSON for dynamic, typed for known**
-
-```sql
--- Use JSON type for dynamic properties
-CREATE TABLE events (
- event_id UUID DEFAULT generateUUIDv4(),
- event_type LowCardinality(String),
- timestamp DateTime DEFAULT now(),
- properties JSON -- Flexible schema with type inference
-)
-ENGINE = MergeTree()
-ORDER BY (event_type, timestamp);
-
--- Query JSON paths directly
-SELECT
- event_type,
- properties.url as page_url,
- properties.amount as purchase_amount
-FROM events
-WHERE event_type = 'page_view' AND properties.url = '/home';
-```
-
-**When to use JSON:**
-
-```sql
-CREATE TABLE events (
- properties JSON(
- url String,
- amount Float64,
- product_id UInt64
- )
-)
-```
-
-| Scenario | Use JSON? |
-
-|----------|-----------|
-
-| Data structure varies unpredictably | Yes |
-
-| Field types/schemas change over time | Yes |
-
-| Need field-level querying | Yes |
-
-| Fixed, known schema | No (use typed columns) |
-
-| JSON as opaque blob (no field queries) | No (use String) |
-
-**Optimization: specify types for known paths:**
-
-Reference: [https://clickhouse.com/docs/best-practices/use-json-where-appropriate](https://clickhouse.com/docs/best-practices/use-json-where-appropriate)
-
-### 1.12 Use LowCardinality for Repeated Strings
-
-**Impact: HIGH (Dictionary encoding for <10K unique values; significant storage reduction)**
-
-String columns with repeated values store each value repeatedly. LowCardinality uses dictionary encoding for significant storage reduction.
-
-**Incorrect: plain String for repeated values**
-
-```sql
-CREATE TABLE events (
- country String, -- "United States" stored 500M times
- browser String, -- "Chrome" stored 300M times
- event_type String -- "page_view" stored 800M times
-)
-```
-
-**Correct: LowCardinality for low unique counts**
-
-```sql
-CREATE TABLE events (
- country LowCardinality(String), -- ~200 unique values
- browser LowCardinality(String), -- ~50 unique values
- event_type LowCardinality(String) -- ~100 unique values
-)
-```
-
-**When to use LowCardinality:**
-
-```sql
--- Check cardinality before deciding
-SELECT uniq(column_name) FROM table_name;
-```
-
-| Unique Values | Recommendation |
-
-|---------------|----------------|
-
-| < 10,000 | Use LowCardinality |
-
-| > 10,000 | Use regular String |
-
-**LowCardinality vs FixedString:**
-
-```sql
--- FixedString: Only for truly fixed-length data
-country_code FixedString(2), -- "US", "DE", "JP" - always 2 chars
-
--- LowCardinality: For variable-length low-cardinality strings
-country_name LowCardinality(String), -- "United States", "Germany"
-```
-
-Reserve `FixedString` for strictly fixed-length data (e.g., 2-char country codes). For most low-cardinality text, `LowCardinality(String)` outperforms `FixedString`.
-
-Reference: [https://clickhouse.com/docs/best-practices/select-data-types](https://clickhouse.com/docs/best-practices/select-data-types)
-
-### 1.13 Use Native Types Instead of String
-
-**Impact: CRITICAL (2-10x storage reduction; enables compression and correct semantics)**
-
-Using String for all data wastes storage, prevents compression optimization, and makes comparisons slower. ClickHouse's column-oriented architecture benefits directly from optimal type selection.
-
-**Incorrect: String for everything**
-
-```sql
-CREATE TABLE events (
- event_id String, -- "550e8400-e29b-41d4-a716-446655440000" = 36 bytes
- user_id String, -- "12345" = 5 bytes (no numeric operations)
- created_at String, -- "2024-01-15 10:30:00" = 19 bytes
- count String, -- "42" - can't do math!
- is_active String -- "true" = 4 bytes
-)
-```
-
-**Correct: native types**
-
-```sql
-CREATE TABLE events (
- event_id UUID DEFAULT generateUUIDv4(), -- 16 bytes (vs 36)
- user_id UInt64, -- 8 bytes, numeric ops
- created_at DateTime DEFAULT now(), -- 4 bytes (vs 19)
- count UInt32 DEFAULT 0, -- 4 bytes, math works
- is_active Bool DEFAULT true -- 1 byte (vs 4)
-)
-```
-
-**Type Selection Quick Reference:**
-
-| Data | Use | Avoid |
-
-|------|-----|-------|
-
-| Sequential IDs | UInt32/UInt64 | String |
-
-| UUIDs | UUID | String |
-
-| Status/Category | Enum8 or LowCardinality(String) | String |
-
-| Timestamps | DateTime | DateTime64, String |
-
-| Dates only | Date or Date32 | DateTime, String |
-
-| Counts | UInt8/16/32 (smallest that fits) | Int64, String |
-
-| Money | Decimal(P,S) or Int64 (cents) | Float64, String |
-
-| Booleans | Bool or UInt8 | String |
-
-Reference: [https://clickhouse.com/docs/best-practices/select-data-types](https://clickhouse.com/docs/best-practices/select-data-types)
-
-### 1.14 Use Partitioning for Data Lifecycle Management
-
-**Impact: HIGH (DROP PARTITION is instant; DELETE is expensive row-by-row scan)**
-
-Partitioning is **primarily a data management technique, not a query optimization tool**. It excels at:
-
-- **Dropping data**: Remove entire partitions as single metadata operations
-
-- **TTL retention**: Implement time-based retention policies efficiently
-
-- **Tiered storage**: Move old partitions to cold storage
-
-- **Archiving**: Move partitions between tables
-
-**Incorrect: no time alignment for lifecycle**
-
-```sql
--- Cannot efficiently drop old data by time
-CREATE TABLE events (...)
-ENGINE = MergeTree()
-PARTITION BY event_type -- No time alignment
-ORDER BY (timestamp);
-
--- Slow: must scan and delete row by row
-DELETE FROM events WHERE timestamp < '2023-01-01';
-```
-
-**Correct: time-based for lifecycle**
-
-```sql
-CREATE TABLE events (
- timestamp DateTime,
- event_type LowCardinality(String)
-)
-ENGINE = MergeTree()
-PARTITION BY toStartOfMonth(timestamp)
-ORDER BY (event_type, timestamp)
-TTL timestamp + INTERVAL 1 YEAR DELETE; -- Drops whole partitions
-
--- Fast: metadata-only operation
-ALTER TABLE events DROP PARTITION '202301';
-
--- Archive to cold storage
-ALTER TABLE events_archive ATTACH PARTITION '202301' FROM events;
-```
-
-Reference: [https://clickhouse.com/docs/best-practices/choosing-a-partitioning-key](https://clickhouse.com/docs/best-practices/choosing-a-partitioning-key)
-
----
-
-## 2. Query Optimization
-
-**Impact: CRITICAL**
-
-Query patterns dramatically affect performance. JOIN algorithms, filtering strategies, skipping indices, and materialized views can reduce query time from minutes to milliseconds. Pre-computed aggregations read thousands of rows instead of billions.
-
-### 2.1 Choose the Right JOIN Algorithm
-
-**Impact: CRITICAL (Wrong algorithm causes OOM; right algorithm handles large tables efficiently)**
-
-ClickHouse's default hash join loads the RIGHT table entirely into memory. Choose the right algorithm based on table sizes and constraints.
-
-**Algorithm selection:**
-
-| Algorithm | Best For | Trade-off |
-
-|-----------|----------|-----------|
-
-| `parallel_hash` | Small-to-medium in-memory tables | Default since 24.11; fast, concurrent |
-
-| `hash` | General purpose, all join types | Single-threaded hash table build |
-
-| `direct` | Dictionary lookups (INNER/LEFT only) | Fastest; no hash table construction |
-
-| `full_sorting_merge` | Tables already sorted on join key | Skips sort if pre-ordered; low memory |
-
-| `partial_merge` | Large tables, memory-constrained | Minimized memory; slower execution |
-
-| `grace_hash` | Large datasets, tunable memory | Flexible; disk-spilling capability |
-
-| `auto` | Adaptive algorithm selection | Tries hash first, falls back on memory pressure |
-
-**Example usage:**
-
-```sql
--- Let ClickHouse choose automatically
-SET join_algorithm = 'auto';
-
--- For large-to-large joins where memory is constrained
-SET join_algorithm = 'partial_merge';
-SELECT * FROM large_a JOIN large_b ON large_b.id = large_a.id;
-
--- When joining by primary key columns, sort-merge skips sorting step
-SET join_algorithm = 'full_sorting_merge';
-SELECT * FROM table_a a JOIN table_b b ON b.pk_col = a.pk_col;
-```
-
-**Note:** ClickHouse 24.12+ automatically positions smaller tables on the right side. For earlier versions, manually ensure the smaller table is on the RIGHT.
-
-Reference: [https://clickhouse.com/docs/best-practices/minimize-optimize-joins](https://clickhouse.com/docs/best-practices/minimize-optimize-joins)
-
-### 2.2 Consider Alternatives to JOINs
-
-**Impact: CRITICAL (Dictionaries and denormalization shift work from query time to insert time)**
-
-Repeated JOINs to dimension tables add overhead. Dictionaries or denormalization shift computational work from query time to insert/pre-processing time.
-
-**Incorrect: JOIN on every query**
-
-```sql
--- JOIN on every query
-SELECT o.order_id, c.name, c.email
-FROM orders o
-JOIN customers c ON c.id = o.customer_id
-WHERE o.created_at > '2024-01-01';
-```
-
-**Correct - Dictionary Lookup:**
-
-```sql
--- Create dictionary
-CREATE DICTIONARY customer_dict (
- id UInt64,
- name String,
- email String
-)
-PRIMARY KEY id
-SOURCE(CLICKHOUSE(TABLE 'customers'))
-LAYOUT(HASHED())
-LIFETIME(MIN 300 MAX 360);
-
--- Use dictGet instead of JOIN (uses direct join algorithm - fastest)
-SELECT
- order_id,
- dictGet('customer_dict', 'name', customer_id) as customer_name,
- dictGet('customer_dict', 'email', customer_id) as customer_email
-FROM orders
-WHERE created_at > '2024-01-01';
-```
-
-**Correct - Denormalization:**
-
-```sql
--- Denormalized table with materialized view
-CREATE MATERIALIZED VIEW orders_enriched_mv TO orders_enriched AS
-SELECT
- o.order_id, o.customer_id,
- c.name as customer_name,
- c.email as customer_email,
- o.total, o.created_at
-FROM orders o
-JOIN customers c ON c.id = o.customer_id;
-```
-
-**Approach comparison:**
-
-| Approach | Use Case | Performance |
-
-|----------|----------|-------------|
-
-| Dictionary | Frequent lookups to small dimension | Fastest (in-memory) |
-
-| Denormalization | Analytics always need enriched data | Fast (no join at query) |
-
-| IN subquery | Existence filtering | Often faster than JOIN |
-
-| JOIN | Infrequent or complex joins | Acceptable |
-
-**Critical dictionary caveat:** Dictionaries silently deduplicate duplicate keys, retaining only the final value. Only use when source has unique keys.
-
-Reference: [https://clickhouse.com/docs/best-practices/minimize-optimize-joins](https://clickhouse.com/docs/best-practices/minimize-optimize-joins)
-
-### 2.3 Filter Tables Before Joining
-
-**Impact: CRITICAL (Joining full tables then filtering wastes resources)**
-
-Joining full tables then filtering wastes resources. Add filtering in `WHERE` or `JOIN ON` clauses. If automatic pushdown fails, restructure as a subquery.
-
-**Incorrect: join then filter**
-
-```sql
--- Joins entire tables, then filters
-SELECT o.order_id, c.name, o.total
-FROM orders o
-JOIN customers c ON c.id = o.customer_id
-WHERE o.created_at > '2024-01-01' AND c.country = 'US';
-```
-
-**Correct: filter in subqueries before joining**
-
-```sql
--- Filter in subqueries before joining
-SELECT o.order_id, c.name, o.total
-FROM (
- SELECT order_id, customer_id, total
- FROM orders
- WHERE created_at > '2024-01-01'
-) o
-JOIN (
- SELECT id, name
- FROM customers
- WHERE country = 'US'
-) c ON c.id = o.customer_id;
-```
-
-**Even better - aggregate before joining:**
-
-```sql
-SELECT c.country, o.total_revenue
-FROM (
- SELECT customer_id, sum(total) as total_revenue
- FROM orders
- WHERE created_at > '2024-01-01'
- GROUP BY customer_id
-) o
-JOIN customers c ON c.id = o.customer_id;
-```
-
-Reference: [https://clickhouse.com/docs/best-practices/minimize-optimize-joins](https://clickhouse.com/docs/best-practices/minimize-optimize-joins)
-
-### 2.4 Optimize NULL Handling in Outer JOINs
-
-**Impact: MEDIUM (Default values instead of NULL reduces memory overhead)**
-
-Set `join_use_nulls = 0` to use default column values instead of NULL markers, reducing memory overhead compared to Nullable wrappers.
-
-**Example:**
-
-```sql
--- Use default values instead of NULLs for non-matching rows
-SET join_use_nulls = 0;
-
-SELECT o.order_id, c.name
-FROM orders o
-LEFT JOIN customers c ON c.id = o.customer_id;
--- Non-matching rows get '' for name instead of NULL
-```
-
-**When to use:**
-
-| Setting | Behavior | Use Case |
-
-|---------|----------|----------|
-
-| `join_use_nulls = 0` | Default values (empty string, 0) for non-matches | When you can handle default values |
-
-| `join_use_nulls = 1` (default) | NULL for non-matches | When you need to distinguish "no match" from "matched with default" |
-
-Reference: [https://clickhouse.com/docs/best-practices/minimize-optimize-joins](https://clickhouse.com/docs/best-practices/minimize-optimize-joins)
-
-### 2.5 Use ANY JOIN When Only One Match Needed
-
-**Impact: HIGH (Returns first match only; less memory and faster execution)**
-
-Use `ANY` JOINs when you only need a single match rather than all matches. They consume less memory and execute faster.
-
-**Incorrect: returns all matches**
-
-```sql
--- Returns all matching rows, uses more memory
-SELECT o.order_id, c.name
-FROM orders o
-LEFT JOIN customers c ON c.id = o.customer_id;
-```
-
-**Correct: returns first match only**
-
-```sql
--- Returns only first match per row, faster and less memory
-SELECT o.order_id, c.name
-FROM orders o
-LEFT ANY JOIN customers c ON c.id = o.customer_id;
-```
-
-**ANY JOIN types:**
-
-| Type | Behavior |
-
-|------|----------|
-
-| `LEFT ANY JOIN` | At most one match from right table |
-
-| `INNER ANY JOIN` | At most one match, only matching rows |
-
-| `RIGHT ANY JOIN` | At most one match from left table |
-
-Reference: [https://clickhouse.com/docs/best-practices/minimize-optimize-joins](https://clickhouse.com/docs/best-practices/minimize-optimize-joins)
-
-### 2.6 Use Data Skipping Indices for Non-ORDER BY Filters
-
-**Impact: HIGH (Up to 60x faster queries by skipping irrelevant granules)**
-
-Queries filtering on columns not in ORDER BY cannot use the primary index and result in full scans. Data skipping indices store metadata about blocks and skip granules that definitely don't match.
-
-**Important:** Skip indices should be considered **after** optimizing data types, primary key selection, and materialized views.
-
-**When to use:**
-
-- High overall cardinality but low cardinality within blocks
-
-- Rare values critical for search (error codes, specific IDs)
-
-- Column correlates with primary key
-
-**When NOT to use:**
-
-- As a first optimization step
-
-- Matching values scattered across many blocks
-
-- Without testing on real data
-
-**Incorrect: filtering on non-ORDER BY column**
-
-```sql
-CREATE TABLE events (
- event_type LowCardinality(String),
- timestamp DateTime,
- user_id UInt64 -- Not in ORDER BY
-)
-ENGINE = MergeTree()
-ORDER BY (event_type, toDate(timestamp));
-
--- Query filters on user_id - scans all matching event_type
-SELECT * FROM events
-WHERE event_type = 'click' AND user_id = 12345;
-```
-
-**Correct: add skipping index**
-
-```sql
-CREATE TABLE events (
- event_type LowCardinality(String),
- timestamp DateTime,
- user_id UInt64,
- INDEX idx_user_id user_id TYPE bloom_filter GRANULARITY 4
-)
-ENGINE = MergeTree()
-ORDER BY (event_type, toDate(timestamp));
-
--- Or add to existing table
-ALTER TABLE events ADD INDEX idx_user_id user_id TYPE bloom_filter GRANULARITY 4;
-ALTER TABLE events MATERIALIZE INDEX idx_user_id;
-```
-
-**Index types:**
-
-| Type | Best For | Example Filter |
-
-|------|----------|----------------|
-
-| `bloom_filter` | Equality on high-cardinality | `WHERE user_id = 123` |
-
-| `set(N)` | Low cardinality (N unique values) | `WHERE status IN ('a','b')` |
-
-| `minmax` | Range queries | `WHERE amount > 1000` |
-
-| `ngrambf_v1` | Text search | `WHERE text LIKE '%term%'` |
-
-| `tokenbf_v1` | Token search | `WHERE hasToken(text, 'word')` |
-
-**Validation:**
-
-```sql
-EXPLAIN indexes = 1
-SELECT * FROM events WHERE user_id = 12345;
--- Look for "Skip" in output showing granules skipped
-```
-
-Reference: [https://clickhouse.com/docs/best-practices/use-data-skipping-indices-where-appropriate](https://clickhouse.com/docs/best-practices/use-data-skipping-indices-where-appropriate)
-
-### 2.7 Use Incremental MVs for Real-Time Aggregations
-
-**Impact: HIGH (Read thousands of rows instead of billions; minimal cluster overhead)**
-
-Incremental MVs automatically apply the view's query to new data blocks at insert time. Results are written to a target table and partial results merge over time.
-
-**Incorrect: full aggregation on every query**
-
-```sql
--- Full aggregation on every dashboard load
-SELECT
- event_type,
- toStartOfHour(timestamp) as hour,
- count() as events,
- uniq(user_id) as unique_users
-FROM events
-WHERE timestamp >= now() - INTERVAL 7 DAY
-GROUP BY event_type, hour;
--- Scans 7 days of data every time (billions of rows)
-```
-
-**Correct: incremental MV with pre-aggregation**
-
-```sql
--- Create target table for aggregated data
-CREATE TABLE events_hourly (
- event_type LowCardinality(String),
- hour DateTime,
- events AggregateFunction(count),
- unique_users AggregateFunction(uniq, UInt64)
-)
-ENGINE = AggregatingMergeTree()
-ORDER BY (event_type, hour);
-
--- Create materialized view to populate incrementally
-CREATE MATERIALIZED VIEW events_hourly_mv TO events_hourly AS
-SELECT
- event_type,
- toStartOfHour(timestamp) as hour,
- countState() as events,
- uniqState(user_id) as unique_users
-FROM events
-GROUP BY event_type, hour;
-
--- Query the pre-aggregated data
-SELECT
- event_type, hour,
- countMerge(events) as events,
- uniqMerge(unique_users) as unique_users
-FROM events_hourly
-WHERE hour >= now() - INTERVAL 7 DAY
-GROUP BY event_type, hour;
--- Reads thousands of rows instead of billions
-```
-
-**Key points:**
-
-- Use `-State` functions in MV, `-Merge` functions in query
-
-- Incremental - existing data not automatically included (backfill separately)
-
-- Minimal cluster overhead at insert time
-
-Reference: [https://clickhouse.com/docs/best-practices/use-materialized-views](https://clickhouse.com/docs/best-practices/use-materialized-views)
-
-### 2.8 Use Refreshable MVs for Complex Joins and Batch Workflows
-
-**Impact: HIGH (Sub-millisecond queries with periodic refresh; ideal for complex joins)**
-
-Refreshable MVs execute queries periodically on a schedule. The full query re-executes and overwrites (or appends to) the target table.
-
-**Best for:**
-
-- Sub-millisecond latency where minor staleness is acceptable
-
-- Caching "top N" results or lookup tables
-
-- Complex multi-table joins requiring denormalization
-
-- Batch workflows and DAG dependencies
-
-**Incorrect: expensive join on every request**
-
-```sql
--- Complex join executed on every request
-SELECT
- o.order_id, o.total,
- c.name as customer_name,
- p.name as product_name
-FROM orders o
-JOIN customers c ON o.customer_id = c.id
-JOIN products p ON o.product_id = p.id
-WHERE o.created_at >= now() - INTERVAL 1 DAY;
-```
-
-**Correct: refreshable MV**
-
-```sql
--- Create refreshable MV that runs every 5 minutes
-CREATE MATERIALIZED VIEW orders_denormalized
-REFRESH EVERY 5 MINUTE
-ENGINE = MergeTree()
-ORDER BY (created_at, order_id)
-AS SELECT
- o.order_id, o.created_at, o.total,
- c.name as customer_name, c.segment,
- p.name as product_name
-FROM orders o
-JOIN customers c ON o.customer_id = c.id
-JOIN products p ON o.product_id = p.id
-WHERE o.created_at >= now() - INTERVAL 1 DAY;
-
--- Query the pre-joined data (sub-millisecond)
-SELECT * FROM orders_denormalized WHERE segment = 'enterprise';
-```
-
-**APPEND vs REPLACE modes:**
-
-| Mode | Behavior | Use Case |
-
-|------|----------|----------|
-
-| `REPLACE` (default) | Overwrites previous contents | Current state, lookup tables |
-
-| `APPEND` | Adds new rows to existing data | Periodic snapshots, historical accumulation |
-
-**Critical warning:** Query should run quickly compared to refresh interval. Don't schedule every 10 seconds if the query takes 10+ seconds.
-
-Reference: [https://clickhouse.com/docs/best-practices/use-materialized-views](https://clickhouse.com/docs/best-practices/use-materialized-views)
-
----
-
-## 3. Insert Strategy
-
-**Impact: CRITICAL**
-
-Each INSERT creates a data part. Single-row inserts overwhelm the merge process. Proper batching (10K-100K rows), async inserts for high-frequency writes, mutation avoidance, and letting background merges work are essential for stable cluster performance.
-
-### 3.1 Avoid ALTER TABLE DELETE
-
-**Impact: CRITICAL (Use lightweight DELETE, CollapsingMergeTree, or DROP PARTITION instead)**
-
-`ALTER TABLE DELETE` is a mutation that rewrites entire data parts. Use alternatives like lightweight DELETE, CollapsingMergeTree, or DROP PARTITION.
-
-**Incorrect: mutation delete**
-
-```sql
--- Mutation delete for cleanup
-ALTER TABLE orders DELETE WHERE status = 'cancelled';
-
--- Time-based cleanup via mutation (very expensive)
-ALTER TABLE sessions DELETE WHERE created_at < now() - INTERVAL 7 DAY;
-```
-
-**Correct - CollapsingMergeTree:**
-
-```sql
-CREATE TABLE orders (
- order_id UInt64,
- customer_id UInt64,
- total Decimal(10,2),
- sign Int8 -- 1 = active, -1 = deleted
-)
-ENGINE = CollapsingMergeTree(sign)
-ORDER BY order_id;
-
--- Insert order
-INSERT INTO orders VALUES (123, 456, 99.99, 1);
-
--- "Delete" by inserting with sign = -1
-INSERT INTO orders VALUES (123, 456, 99.99, -1);
-
--- Query collapses +1 and -1 pairs
-SELECT order_id, sum(total * sign) as total
-FROM orders GROUP BY order_id HAVING sum(sign) > 0;
-```
-
-**Correct - Lightweight Deletes (23.3+):**
-
-```sql
--- Marks rows, doesn't rewrite immediately
-DELETE FROM orders WHERE status = 'cancelled';
--- Physical deletion happens during normal merges
-```
-
-**Correct - DROP PARTITION for Bulk Deletion:**
-
-```sql
--- Instant deletion of old data
-ALTER TABLE events DROP PARTITION '202301';
-
--- Much faster than:
-ALTER TABLE events DELETE WHERE toYYYYMM(timestamp) = 202301;
-```
-
-**Delete strategy comparison:**
-
-| Method | Speed | When to Use |
-
-|--------|-------|-------------|
-
-| ALTER DELETE | Slow | Rare corrections only |
-
-| CollapsingMergeTree | Fast | Frequent soft deletes |
-
-| Lightweight DELETE | Medium | Occasional deletes |
-
-| DROP PARTITION | Instant | Bulk deletion by partition |
-
-Reference: [https://clickhouse.com/docs/best-practices/avoid-mutations](https://clickhouse.com/docs/best-practices/avoid-mutations)
-
-### 3.2 Avoid ALTER TABLE UPDATE
-
-**Impact: CRITICAL (Mutations rewrite entire parts; use ReplacingMergeTree instead)**
-
-`ALTER TABLE UPDATE` is a mutation - an asynchronous background process that rewrites entire data parts affected by the change. This is extremely expensive for frequent or large-scale operations.
-
-**Why mutations are problematic:**
-
-- **Write amplification:** Rewrite complete parts even for minor changes
-
-- **Disk I/O spike:** Degrades overall cluster performance
-
-- **No rollback:** Cannot be rolled back after submission
-
-- **Inconsistent reads:** SELECT may read mix of mutated and unmutated parts
-
-**Incorrect: mutation for updates**
-
-```sql
--- Rewrites potentially huge amounts of data
-ALTER TABLE users UPDATE status = 'inactive'
-WHERE last_login < now() - INTERVAL 90 DAY;
-
--- Frequent row updates via mutation
-ALTER TABLE inventory UPDATE quantity = quantity - 1
-WHERE product_id = 123;
--- If product exists across 100 parts, rewrites ALL 100 parts
-```
-
-**Correct: ReplacingMergeTree**
-
-```sql
--- Table design for updates
-CREATE TABLE users (
- user_id UInt64,
- name String,
- status LowCardinality(String),
- updated_at DateTime DEFAULT now()
-)
-ENGINE = ReplacingMergeTree(updated_at)
-ORDER BY user_id;
-
--- "Update" by inserting new version
-INSERT INTO users (user_id, name, status)
-VALUES (123, 'John', 'inactive');
-
--- Query with FINAL to get latest version
-SELECT * FROM users FINAL WHERE user_id = 123;
-
--- Or use aggregation
-SELECT user_id, argMax(status, updated_at) as status
-FROM users GROUP BY user_id;
-```
-
-Reference: [https://clickhouse.com/docs/best-practices/avoid-mutations](https://clickhouse.com/docs/best-practices/avoid-mutations)
-
-### 3.3 Avoid OPTIMIZE TABLE FINAL
-
-**Impact: HIGH (Forces expensive merge of all parts; let background merges work)**
-
-`OPTIMIZE TABLE ... FINAL` forces immediate merge of all parts into one part per partition. This is resource-intensive and rarely necessary. ClickHouse already performs smart background merges.
-
-**Note:** `OPTIMIZE FINAL` is not the same as `FINAL`. The `FINAL` modifier in SELECT queries may be necessary for deduplicated results in ReplacingMergeTree and is generally fine to use.
-
-**Incorrect: OPTIMIZE FINAL after inserts**
-
-```sql
--- Running OPTIMIZE FINAL after every batch insert
-INSERT INTO events SELECT * FROM staging_events;
-OPTIMIZE TABLE events FINAL; -- Expensive and unnecessary!
-
--- Scheduled OPTIMIZE FINAL jobs
--- Cron: 0 * * * * clickhouse-client -q "OPTIMIZE TABLE events FINAL"
-```
-
-**Correct: let background merges work**
-
-```sql
--- Let background merges handle optimization
-INSERT INTO events SELECT * FROM staging_events;
--- Done! ClickHouse merges automatically
-
--- For ReplacingMergeTree deduplication, use FINAL in queries
-SELECT * FROM events FINAL WHERE user_id = 123;
--- Instead of running OPTIMIZE FINAL to deduplicate
-```
-
-**Problems with OPTIMIZE FINAL:**
-
-- Rewrites entire partition regardless of need
-
-- Ignores the ~150 GB part size safeguard
-
-- Can cause memory pressure or OOM errors
-
-- Lengthy execution time for large datasets
-
-**When OPTIMIZE FINAL may be acceptable:**
-
-- Finalizing data before table freezing
-
-- Preparing data for export operations
-
-- One-time operations, not regular workflows
-
-**Better alternatives:**
-
-| Need | Alternative |
-
-|------|-------------|
-
-| Deduplicate ReplacingMergeTree | Use `FINAL` modifier in SELECT |
-
-| Reduce part count | Rely on background merges |
-
-Reference: [https://clickhouse.com/docs/best-practices/avoid-optimize-final](https://clickhouse.com/docs/best-practices/avoid-optimize-final)
-
-### 3.4 Batch Inserts Appropriately (10K-100K rows)
-
-**Impact: CRITICAL (Each INSERT creates a part; single-row inserts overwhelm merge process)**
-
-Each INSERT creates a new data part. Single-row or small-batch inserts create thousands of tiny parts, overwhelming the merge process and causing cluster instability.
-
-**Incorrect: single-row or tiny batches**
-
-```python
-# Single-row inserts - creates 10,000 parts!
-for event in events:
- client.execute("INSERT INTO events VALUES", [event])
-
-# Tiny batches - still too many parts
-for batch in chunks(events, 100): # 100 rows per INSERT
- client.execute("INSERT INTO events VALUES", batch)
-```
-
-**Correct: proper batch size**
-
-```python
-# Ideal batch size: 10,000-100,000 rows
-BATCH_SIZE = 10_000
-for batch in chunks(events, BATCH_SIZE):
- client.execute("INSERT INTO events VALUES", batch)
-```
-
-**Recommended batch sizes:**
-
-| Threshold | Value |
-
-|-----------|-------|
-
-| Minimum | 1,000 rows |
-
-| Ideal range | 10,000-100,000 rows |
-
-| Insert rate (sync) | ~1 insert per second |
-
-**Validation:**
-
-```sql
--- Monitor part count (>3000 per partition blocks inserts)
-SELECT table, count() as parts, sum(rows) as total_rows
-FROM system.parts
-WHERE active AND database = 'default'
-GROUP BY table
-ORDER BY parts DESC;
-```
-
-Reference: [https://clickhouse.com/docs/best-practices/selecting-an-insert-strategy](https://clickhouse.com/docs/best-practices/selecting-an-insert-strategy)
-
-### 3.5 Use Async Inserts for High-Frequency Small Batches
-
-**Impact: HIGH (Server-side buffering when client batching isn't practical)**
-
-When client-side batching isn't practical, async inserts buffer server-side and create larger parts automatically.
-
-**Incorrect: small batches without async**
-
-```python
-# Small batches without async_insert - creates too many parts
-for batch in chunks(events, 100):
- client.execute("INSERT INTO events VALUES", batch)
-```
-
-**Correct: enable async inserts**
-
-```sql
--- Configure server-side for specific users
-ALTER USER my_app_user SETTINGS
- async_insert = 1,
- wait_for_async_insert = 1,
- async_insert_max_data_size = 10000000, -- Flush at 10MB
- async_insert_busy_timeout_ms = 1000; -- Flush after 1s
-```
-
-**Flush conditions: whichever occurs first**
-
-- Buffer reaches `async_insert_max_data_size`
-
-- Time threshold `async_insert_busy_timeout_ms` elapses
-
-- Maximum insert queries accumulate
-
-**Return modes:**
-
-| Setting | Behavior | Use Case |
-
-|---------|----------|----------|
-
-| `wait_for_async_insert=1` | Waits for flush, confirms durability | **Recommended** |
-
-| `wait_for_async_insert=0` | Fire-and-forget, unaware of errors | **Risky** - only if you accept data loss |
-
-Reference: [https://clickhouse.com/docs/best-practices/selecting-an-insert-strategy](https://clickhouse.com/docs/best-practices/selecting-an-insert-strategy)
-
-### 3.6 Use Native Format for Best Insert Performance
-
-**Impact: MEDIUM (Native format is most efficient; JSONEachRow is expensive to parse)**
-
-Data format affects insert performance. Native format is column-oriented with minimal parsing overhead.
-
-**Performance Ranking: fastest to slowest**
-
-| Format | Notes |
-
-|--------|-------|
-
-| **Native** | Most efficient. Column-oriented, minimal parsing. Recommended. |
-
-| **RowBinary** | Efficient row-based alternative |
-
-| **JSONEachRow** | Easier to use but expensive to parse |
-
-**Example:**
-
-```python
-# Use Native format for best performance
-client.execute("INSERT INTO events VALUES", data, settings={'input_format': 'Native'})
-```
-
-Reference: [https://clickhouse.com/docs/best-practices/selecting-an-insert-strategy](https://clickhouse.com/docs/best-practices/selecting-an-insert-strategy)
-
----
-
-## References
-
-1. [https://clickhouse.com/docs](https://clickhouse.com/docs)
-2. [https://github.com/ClickHouse/ClickHouse](https://github.com/ClickHouse/ClickHouse)
+Start with `SKILL.md` for the ClickHouse review workflow, rule-selection
+process, and response format. This file exists as a concise compatibility
+entrypoint for agents that open `AGENTS.md` directly.
+
+Detailed rules live in `rules/`. Read only the rule files that match the schema,
+query, or ingestion issue under review, and cite the specific rule names in
+responses.
+
+## Langfuse-Specific Rules
+
+- Use `packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts`
+ for queries against the `events` table. Do not hand-roll `events` SQL unless
+ you first confirm the query builder cannot express the query.
+- Never use `FINAL` on the `events` table; it is designed so `FINAL` is not
+ required and the keyword hurts performance.
+
+## Rule Index
+
+### Schema Design
+
+- `rules/schema-pk-plan-before-creation.md`
+- `rules/schema-pk-cardinality-order.md`
+- `rules/schema-pk-prioritize-filters.md`
+- `rules/schema-pk-filter-on-orderby.md`
+- `rules/schema-types-native-types.md`
+- `rules/schema-types-minimize-bitwidth.md`
+- `rules/schema-types-lowcardinality.md`
+- `rules/schema-types-enum.md`
+- `rules/schema-types-avoid-nullable.md`
+- `rules/schema-partition-start-without.md`
+- `rules/schema-partition-low-cardinality.md`
+- `rules/schema-partition-query-tradeoffs.md`
+- `rules/schema-partition-lifecycle.md`
+- `rules/schema-json-when-to-use.md`
+
+### Query Optimization
+
+- `rules/query-join-choose-algorithm.md`
+- `rules/query-join-consider-alternatives.md`
+- `rules/query-join-filter-before.md`
+- `rules/query-join-null-handling.md`
+- `rules/query-join-use-any.md`
+- `rules/query-index-skipping-indices.md`
+- `rules/query-mv-incremental.md`
+- `rules/query-mv-refreshable.md`
+
+### Insert Strategy
+
+- `rules/insert-batch-size.md`
+- `rules/insert-async-small-batches.md`
+- `rules/insert-format-native.md`
+- `rules/insert-mutation-avoid-delete.md`
+- `rules/insert-mutation-avoid-update.md`
+- `rules/insert-optimize-avoid-final.md`
diff --git a/.agents/skills/clickhouse-best-practices/SKILL.md b/.agents/skills/clickhouse-best-practices/SKILL.md
index 3f41170359..a5add65c29 100644
--- a/.agents/skills/clickhouse-best-practices/SKILL.md
+++ b/.agents/skills/clickhouse-best-practices/SKILL.md
@@ -25,9 +25,13 @@ Comprehensive guidance for ClickHouse covering schema design, query optimization
**Why rules take priority:** ClickHouse has specific behaviors (columnar storage, sparse indexes, merge tree mechanics) where general database intuition can be misleading. The rules encode validated, ClickHouse-specific guidance.
-### For Formal Reviews
+## Langfuse-Specific Rules
-When performing a formal review of schemas, queries, or data ingestion:
+- Use `packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts`
+ for queries against the `events` table. Do not hand-roll `events` SQL unless
+ you first confirm the query builder cannot express the query.
+- Never use `FINAL` on the `events` table; it is designed so `FINAL` is not
+ required and the keyword hurts performance.
---
@@ -227,8 +231,8 @@ Each rule file in `rules/` contains:
---
-## Full Compiled Document
+## Compatibility Entrypoint
-For the complete guide with all rules expanded inline: `AGENTS.md`
-
-Use `AGENTS.md` when you need to check multiple rules quickly without reading individual files.
+`AGENTS.md` is a short compatibility index for agents that open that file
+directly. The authoritative workflow lives in this `SKILL.md`, and detailed rule
+bodies live in `rules/`.
diff --git a/scripts/codex/maintenance.sh b/scripts/codex/maintenance.sh
index 4d0d986527..1cf7de5d5c 100755
--- a/scripts/codex/maintenance.sh
+++ b/scripts/codex/maintenance.sh
@@ -3,7 +3,7 @@
set -euo pipefail
if ! command -v corepack >/dev/null 2>&1; then
- echo "corepack is required. Use a Codex base environment with Node.js 24 support."
+ echo "corepack is required. Use an environment with Node.js 24 support."
exit 1
fi
diff --git a/scripts/codex/setup.sh b/scripts/codex/setup.sh
index 56f5fbc96a..0c531fc4cd 100755
--- a/scripts/codex/setup.sh
+++ b/scripts/codex/setup.sh
@@ -14,7 +14,7 @@ ensure_env_file() {
}
if ! command -v corepack >/dev/null 2>&1; then
- echo "corepack is required. Use a Codex base environment with Node.js 24 support."
+ echo "corepack is required. Use an environment with Node.js 24 support."
exit 1
fi
@@ -34,5 +34,5 @@ pnpm run playwright:install
# the workspace-wide db:generate task, which may be satisfied by Turbo cache.
pnpm --filter=shared run db:generate
-# Prisma client generation is needed for typecheck/build tasks in Codex.
+# Prisma client generation is needed for typecheck/build tasks.
pnpm run db:generate
diff --git a/web/AGENTS.md b/web/AGENTS.md
index be43284614..491d541c47 100644
--- a/web/AGENTS.md
+++ b/web/AGENTS.md
@@ -5,7 +5,9 @@ Use root [AGENTS.md](../AGENTS.md) for monorepo-level rules.
## Purpose
-- Next.js 15 application with UI, tRPC backend, and public REST API routes.
+- Next.js application with UI, tRPC backend, and public REST API routes.
+- Check `web/package.json` for current Next.js, React, and tRPC versions before
+ version-sensitive work.
- Primary package for frontend and most request/response surface changes.
## Maintenance Contract
@@ -82,6 +84,24 @@ signoff of user-visible changes.
must be installed, ask the user before doing so.
- Tailwind is the default styling layer; use the shared palette and globals in
`src/styles/globals.css`.
+- When changing shared UI/table patterns, update sibling variants consistently,
+ including default-visible and hidden columns or states.
+- For component style variants, prefer `cva` with `VariantProps` and merge
+ caller classes through `cn`, following existing `src/components/ui/*`
+ components:
+
+ ```tsx
+ const cardVariants = cva("rounded-md border", {
+ variants: { intent: { default: "bg-background", error: "border-destructive" } },
+ defaultVariants: { intent: "default" },
+ });
+
+ type CardProps = React.HTMLAttributes<HTMLDivElement> &
+ VariantProps<typeof cardVariants>;
+
+ const className = cn(cardVariants({ intent }), props.className);
+ ```
+
- When anchoring sticky, fixed, or absolute elements to the viewport, use
`top-banner-offset`, `pt-banner-offset`, `h-screen-with-banner`, or
`min-h-screen-with-banner` instead of raw `top-0` so banners do not overlap