{"owner":"rudderlabs","repo":"rudder-server","hasSkills":true,"totalSkillsCount":5,"totalTokensCount":8528,"categories":["cursor-rule","anthropic-skill","root-instruction"],"hasMcp":false,"mcpConfig":null,"found":["warehouse/.cursor/rules/testing.mdc","cmd/devtool/commands/payloads/batch.json","warehouse/.cursor/rules/plan-act-workflow.mdc","warehouse/.cursor/rules/documentation.mdc","AGENTS.md"],"skills":{"warehouse/.cursor/rules/testing.mdc":"---\ndescription: Testing guidelines for the warehouse directory in RudderStack.\nglobs:\n  - \"**/*_test.go\"\nalwaysApply: true\n---\n\n# Warehouse Testing Guidelines\n\nThis document outlines the testing conventions and best practices for the `warehouse/` directory in the RudderStack server codebase.\n\n## Table of Contents\n\n- [Assertion Library](mdc:#assertion-library)\n- [Test Structure](mdc:#test-structure)\n- [Parallelization](mdc:#parallelization)\n- [Context Management](mdc:#context-management)\n- [Setup and Teardown](mdc:#setup-and-teardown)\n- [Database Testing](mdc:#database-testing)\n- [Mocking](mdc:#mocking)\n- [File Management](mdc:#file-management)\n- [Configuration](mdc:#configuration)\n- [Test Naming](mdc:#test-naming)\n- [Error Testing](mdc:#error-testing)\n- [Helper Patterns](mdc:#helper-patterns)\n- [Integration Test Patterns](mdc:#integration-test-patterns)\n- [Common Anti-patterns to Avoid](mdc:#common-anti-patterns-to-avoid)\n- [Example Test Structure](mdc:#example-test-structure)\n\n## Assertion Library\n\n**ALWAYS** use `github.com/stretchr/testify/require` for assertions in warehouse tests.\n\n- Prefer `require` over `assert` to fail fast on critical assertions\n- Use `require.NoError(t, err)` for error checking\n- Use `require.Equal(t, expected, actual)` for equality checks\n- Use `require.True(t, condition)` and `require.False(t, condition)` for boolean checks\n\n```go\nimport (\n    \"github.com/stretchr/testify/require\"\n)\n\nfunc TestExample(t *testing.T) {\n    result, err := someFunction()\n    require.NoError(t, err)\n    require.Equal(t, expected, result)\n}\n```\n\n## Test Structure\n\nUse **table-driven tests** for multiple scenarios:\n\n- Structure table-driven tests with `name`, input, and `expected` fields\n- Always use `t.Run(tc.name, func(t *testing.T) {})` for subtests\n- Group related subtests under a parent `t.Run(\"group name\", ...)` block for clarity and maintainability.\n- Include both positive and negative test cases\n\n```go\n// Table-driven tests for parameterized scenarios\nfunc TestWarehouseFunction(t *testing.T) {\n    testCases := []struct {\n        name     string\n        input    InputType\n        expected ExpectedType\n        wantErr  bool\n    }{\n        {\n            name:     \"successful case\",\n            input:    validInput,\n            expected: expectedOutput,\n            wantErr:  false,\n        },\n        {\n            name:    \"error case\",\n            input:   invalidInput,\n            wantErr: true,\n        },\n    }\n    \n    for _, tc := range testCases {\n        t.Run(tc.name, func(t *testing.T) {\n            // test implementation\n        })\n    }\n}\n\n// Grouped subtests for related functionality\nfunc TestWarehouseComponent(t *testing.T) {\n    t.Run(\"initialization\", func(t *testing.T) {\n        t.Run(\"valid configuration\", func(t *testing.T) { /* ... */ })\n        t.Run(\"invalid configuration\", func(t *testing.T) { /* ... */ })\n        t.Run(\"missing configuration\", func(t *testing.T) { /* ... */ })\n    })\n    \n    t.Run(\"data processing\", func(t *testing.T) {\n        t.Run(\"single record\", func(t *testing.T) { /* ... */ })\n        t.Run(\"batch processing\", func(t *testing.T) { /* ... */ })\n        t.Run(\"empty input\", func(t *testing.T) { /* ... */ })\n    })\n}\n```\n\n## Parallelization\n\n- Use `t.Parallel()` for tests that can run concurrently\n- Apply parallelization to both main tests and subtests where safe\n- Avoid parallelization for tests that modify shared resources\n\n```go\nfunc TestConcurrentFunction(t *testing.T) {\n    t.Parallel()\n    \n    for _, tc := range testCases {\n        t.Run(tc.name, func(t *testing.T) {\n            t.Parallel()\n            // test implementation\n        })\n    }\n}\n```\n\n## Context Management\n\n- Use `context.Background()` as the default context for most tests\n- Use `context.WithTimeout()` for tests with time constraints\n- Always pass context as the first parameter to functions under test\n\n```go\nfunc TestWithContext(t *testing.T) {\n    ctx := context.Background()\n    // or for timeouts:\n    ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n    defer cancel()\n    \n    result, err := functionUnderTest(ctx, input)\n    require.NoError(t, err)\n}\n```\n\n## Setup and Teardown\n\n- Use `t.Cleanup()` for resource cleanup (files, database connections, etc.)\n- Clean up temporary files with `require.NoError(t, os.Remove(filePath))`\n- Use `defer` for cleanup when `t.Cleanup()` is not sufficient\n- Create helper functions for complex test setup\n\n```go\nfunc TestWithCleanup(t *testing.T) {\n    tempFile, err := os.CreateTemp(\"\", \"test_*.txt\")\n    require.NoError(t, err)\n    \n    t.Cleanup(func() {\n        require.NoError(t, os.Remove(tempFile.Name()))\n    })\n    \n    // test implementation\n}\n```\n\n## Database Testing\n\n- Use `dockertest` for PostgreSQL integration tests\n- Set up database migrations with `migrator.Migrator`\n- Use `sqlmiddleware.New()` for database connections\n- Clean up database resources properly in `t.Cleanup()`\n\n```go\nfunc TestDatabaseIntegration(t *testing.T) {\n    pool, err := dockertest.NewPool(\"\")\n    require.NoError(t, err)\n    \n    pgResource, err := postgres.Setup(pool, t)\n    require.NoError(t, err)\n    \n    err = (&migrator.Migrator{\n        Handle:          pgResource.DB,\n        MigrationsTable: \"wh_schema_migrations\",\n    }).Migrate(\"warehouse\")\n    require.NoError(t, err)\n    \n    db := sqlmiddleware.New(pgResource.DB)\n    \n    // test implementation\n}\n```\n\n## Mocking\n\n- Use `go.uber.org/mock/gomock` for interface mocking\n- Create mock expectations with clear `.EXPECT()` calls\n- Use `gomock.NewController(t)` for mock controller setup\n- Place mock generation comments: `//go:generate go run go.uber.org/mock/mockgen`\n- For error path testing, prefer extending mocks with error fields or behaviors rather than creating many separate mock types.\n\n```go\ntype mockRepository struct {\n    data map[string]interface{}\n    err  error\n}\n\nfunc (m *mockRepository) Get(key string) (interface{}, error) {\n    if m.err != nil {\n        return nil, m.err\n    }\n    return m.data[key], nil\n}\n\n// Usage in tests:\nsuccessMock := &mockRepository{data: map[string]interface{}{\"key\": \"value\"}}\nerrorMock := &mockRepository{err: errors.New(\"connection failed\")}\n```\n\n## File Management\n\n- Create temporary files with `os.CreateTemp()` or `t.TempDir()`\n- Always clean up files with `t.Cleanup(func() { require.NoError(t, os.Remove(fileName)) })`\n- Use proper file handling patterns for testing file operations\n- Test both successful file operations and error cases\n\n```go\nfunc TestFileOperations(t *testing.T) {\n    tempDir := t.TempDir()\n    \n    tempFile, err := os.CreateTemp(tempDir, \"test_*.json\")\n    require.NoError(t, err)\n    \n    t.Cleanup(func() {\n        require.NoError(t, tempFile.Close())\n    })\n    \n    // test file operations\n}\n```\n\n## Configuration\n\n- Use `config.New()` for test configuration\n- Override config values with `c.Set(key, value)` for test scenarios\n- Use environment variable overrides when testing config behavior\n- Test both default and custom configuration values\n\n```go\nfunc TestConfiguration(t *testing.T) {\n    c := config.New()\n    c.Set(\"Warehouse.testKey\", \"testValue\")\n    \n    // test with configuration\n}\n```\n\n## Test Naming\n\n- Use descriptive test function names: `TestFunctionName_Scenario`\n- Use underscores to separate components in test names\n- Include the component being tested in the function name\n- Use clear, descriptive names for table-driven test cases\n\n```go\nfunc TestWarehouse_GetBoolDestinationConfig(t *testing.T) { /* ... */ }\nfunc TestLoadFileGenerator_GetLoadFilePrefix(t *testing.T) { /* ... */ }\nfunc TestStagingFileRepo_GetPending(t *testing.T) { /* ... */ }\n```\n\n## Error Testing\n\n- Test both success and error scenarios\n- Use `require.Error(t, err)` for expected errors\n- Use `require.ErrorIs(t, err, expectedError)` for specific error types\n- Use `require.EqualError(t, err, expectedMessage)` for exact error messages\n- For fallback or multi-source logic, ensure tests cover all branches, including \"no data,\" \"empty but present,\" and error propagation.\n\n```go\nt.Run(\"data retrieval with fallback\", func(t *testing.T) {\n    t.Run(\"primary source succeeds\", func(t *testing.T) { /* ... */ })\n    t.Run(\"primary source fails, fallback succeeds\", func(t *testing.T) { /* ... */ })\n    t.Run(\"both primary and fallback fail\", func(t *testing.T) { /* ... */ })\n    t.Run(\"primary source returns empty, no fallback\", func(t *testing.T) { /* ... */ })\n})\n```\n\n## Helper Patterns\n\n- Create test helper functions for complex setups\n- Use `t.Helper()` in helper functions to get correct line numbers\n- Extract common test data into helper functions or constants\n- Create factory functions for test models and objects\n\n```go\nfunc createTestWarehouse(t *testing.T) model.Warehouse {\n    t.Helper()\n    \n    return model.Warehouse{\n        WorkspaceID: \"test-workspace\",\n        Source: backendconfig.SourceT{\n            ID: \"test-source\",\n        },\n        Destination: backendconfig.DestinationT{\n            ID: \"test-destination\",\n        },\n    }\n}\n\nfunc setupTestDatabase(t *testing.T) (*sql.DB, func()) {\n    t.Helper()\n    \n    // setup logic\n    \n    cleanup := func() {\n        // cleanup logic\n    }\n    \n    return db, cleanup\n}\n```\n\n## Integration Test Patterns\n\n- Use docker-compose for complex integration test setups\n- Set up real warehouse connections for integration tests\n- Use conditional skips: `if os.Getenv(\"SLOW\") != \"1\" { t.Skip() }`\n- Test end-to-end workflows with real data\n\n```go\nfunc TestIntegration(t *testing.T) {\n    if os.Getenv(\"SLOW\") != \"1\" {\n        t.Skip(\"Skipping integration tests. Add 'SLOW=1' env var to run test.\")\n    }\n    \n    // integration test implementation\n}\n```\n\n## Common Anti-patterns to Avoid\n\n- ❌ Don't use `testing.T.Fatal()` or `t.Fatalf()` - use `require` instead\n- ❌ Don't ignore cleanup errors - always check with `require.NoError()`\n- ❌ Don't create tests without cleanup for temporary resources\n- ❌ Don't use sleep for timing - use proper synchronization or timeouts\n- ❌ Don't test implementation details - focus on behavior\n\n## Example Test Structure\n\nHere's a complete example following all the guidelines:\n\n```go\npackage warehouse_test\n\nimport (\n    \"context\"\n    \"os\"\n    \"testing\"\n    \"time\"\n\n    \"github.com/stretchr/testify/require\"\n    \"go.uber.org/mock/gomock\"\n\n    \"github.com/rudderlabs/rudder-go-kit/config\"\n    \"github.com/rudderlabs/rudder-server/warehouse/internal/model\"\n)\n\nfunc TestWarehouseFunction_Scenario(t *testing.T) {\n    testCases := []struct {\n        name     string\n        input    InputType\n        expected ExpectedType\n        wantErr  bool\n    }{\n        {\n            name:     \"successful case\",\n            input:    validInput,\n            expected: expectedOutput,\n            wantErr:  false,\n        },\n        {\n            name:    \"error case\",\n            input:   invalidInput,\n            wantErr: true,\n        },\n    }\n    \n    for _, tc := range testCases {\n        t.Run(tc.name, func(t *testing.T) {\n            t.Parallel()\n            \n            // Setup\n            ctx := context.Background()\n            ctrl := gomock.NewController(t)\n            defer ctrl.Finish()\n            \n            tempFile, err := os.CreateTemp(\"\", \"test_*.json\")\n            require.NoError(t, err)\n            \n            t.Cleanup(func() {\n                require.NoError(t, os.Remove(tempFile.Name()))\n            })\n            \n            // Test execution\n            result, err := functionUnderTest(ctx, tc.input)\n            \n            // Assertions\n            if tc.wantErr {\n                require.Error(t, err)\n                return\n            }\n            \n            require.NoError(t, err)\n            require.Equal(t, tc.expected, result)\n        })\n    }\n}\n```\n\n## Reference\n\nThis document is based on analysis of existing test patterns in the warehouse directory. For questions or suggestions about these guidelines, please refer to the test files in the warehouse directory for examples of these patterns in practice. ","cmd/devtool/commands/payloads/batch.json":"{\n  \"batch\": [\n    {\n      \"anonymousId\": \"{{.AnonymousId}}\",\n      \"channel\": \"android-sdk\",\n      \"context\": {\n        \"app\": {\n          \"build\": \"1\",\n          \"name\": \"RudderAndroidClient\",\n          \"namespace\": \"com.rudderlabs.android.sdk\",\n          \"version\": \"1.0\"\n        },\n        \"device\": {\n          \"id\": \"49e4bdd1c280bc00\",\n          \"manufacturer\": \"Google\",\n          \"model\": \"Android SDK built for x86\",\n          \"name\": \"generic_x86\"\n        },\n        \"locale\": \"en-US\",\n        \"network\": {\n          \"carrier\": \"Android\"\n        },\n        \"screen\": {\n          \"density\": 420,\n          \"height\": 1794,\n          \"width\": 1080\n        },\n        \"library\": {\n          \"name\": \"com.rudderstack.android.sdk.core\"\n        },\n        \"traits\": {\n          \"anonymousId\": \"{{.AnonymousId}}\"\n        },\n        \"user_agent\": \"Dalvik/2.1.0 (Linux; U; Android 9; Android SDK built for x86 Build/PSR1.180720.075)\"\n      },\n      \"event\": \"Demo Track\",\n      \"integrations\": {\n        \"All\": true\n      },\n      \"properties\": {\n        \"label\": \"Demo Label\",\n        \"category\": \"Demo Category\",\n        \"value\": 5,\n        \"testMap\": {\n          \"t1\": \"a\",\n          \"t2\": 4\n        },\n        \"floatVal\": 4.501,\n        \"testArray\": [\n          {\n            \"id\": \"elem1\",\n            \"value\": \"e1\"\n          },\n          {\n            \"id\": \"elem2\",\n            \"value\": \"e2\"\n          }\n        ]\n      },\n      \"type\": \"track\",\n      \"originalTimestamp\": \"{{.Timestamp}}\",\n      \"sentAt\": \"{{.Timestamp}}\"\n    }\n  ]\n}\n","warehouse/.cursor/rules/plan-act-workflow.mdc":"---\ndescription: \nglobs: \nalwaysApply: true\n---\n# 🚨 CRITICAL PLAN-ACT WORKFLOW RULE 🚨\n\n## ⚠️ MANDATORY REQUIREMENT FOR ALL DEVELOPMENT TASKS ⚠️\n\n**This is a CRITICAL rule that MUST be followed without exception when working on any development task in the warehouse directory.**\n\n## 🔄 TWO MODES OF OPERATION: PLAN → ACT\n\n### 📋 MODE 1: PLAN (Planning Phase)\n**In PLAN mode, you focus EXCLUSIVELY on planning and analysis. NO CODE IMPLEMENTATION is allowed.**\n\n### ⚡ MODE 2: ACT (Implementation Phase)  \n**In ACT mode, you execute the approved plan. NO NEW PLANNING or scope changes without returning to PLAN mode.**\n\n**🚫 CRITICAL RULE: You CANNOT be in both modes simultaneously. You must explicitly transition from PLAN → ACT.**\n\n---\n\n### RULE: COMPREHENSIVE PLANNING BEFORE IMPLEMENTATION\n\n### 📋 PLAN MODE REQUIREMENTS\n\n**At any step in PLAN mode, always ask the user for clarifications—even for minor uncertainties or assumptions—whenever needed. This applies to requirement gathering, planning, challenge identification, and documentation/approval.**\n\nComplete ALL of the following before transitioning to ACT mode:\n\n#### 0. 📝 REQUIREMENT GATHERING & CLARIFICATION\n- Begin by gathering requirements and understanding the user's goals, constraints, and expectations for the task.\n\n#### 1. 📋 COMPREHENSIVE PLAN\n- Break down task into actionable steps with dependencies and complexity estimates\n- Identify all affected components and define clear success criteria\n\n#### 2. 🔍 CHALLENGE IDENTIFICATION  \n- Technical risks (algorithms, performance, integration, edge cases)\n- Testing requirements (mocks, data, coverage strategy)\n- Compatibility and resource constraints (migrations, external dependencies)\n\n#### 3. 📝 DOCUMENTATION & APPROVAL\n- Document step-by-step approach with risk mitigation and rollback plan\n- **GET EXPLICIT APPROVAL** - ACT mode forbidden until plan is approved\n- **DECLARE TRANSITION**: \"Moving from PLAN mode to ACT mode\"\n\n### ⚡ ACT MODE REQUIREMENTS\n\nIn ACT mode, you MUST:\n\n#### 1. 🎯 EXECUTE THE APPROVED PLAN\n- Follow documented steps exactly, implement only what was planned\n- **DECLARE MODE**: \"Currently in ACT mode\"\n\n#### 2. 🚫 NO SCOPE CHANGES  \n- Any unexpected issues or new requirements require **RETURN TO PLAN MODE**\n- Track progress and report deviations immediately\n\n### 🚫 VIOLATIONS - STRICTLY PROHIBITED\n\n- **PLAN Mode**: Implementing code, skipping planning steps, proceeding without approval\n- **ACT Mode**: Changing scope without returning to PLAN, deviating from approved plan  \n- **Mode Mixing**: Operating in both modes, transitions without declarations\n\n### ✅ COMPLIANCE CHECKLIST\n\n#### PLAN Mode:\n- [ ] Declared \"Currently in PLAN mode\"\n- [ ] **Gathered requirements and clarified all uncertainties with the user (and sought clarifications at any step as needed)**\n- [ ] Completed comprehensive plan with steps, challenges, and risks\n- [ ] Received explicit approval  \n- [ ] **Declared transition**: \"Moving from PLAN mode to ACT mode\"\n\n#### ACT Mode:\n- [ ] Declared \"Currently in ACT mode\" \n- [ ] Following approved plan exactly\n- [ ] **If scope changes needed**: Return to PLAN mode first\n\n### 🎯 WHY THIS RULE EXISTS\n\n**Prevents costly mistakes** through upfront planning, **ensures focused execution** by mode separation, **reduces context switching**, and **maintains scope discipline**.\n\n---\n\n**Remember: The PLAN → ACT workflow creates mental clarity and prevents the costly mistake of \"planning while coding.\" This two-mode approach is non-negotiable for maintaining the quality and reliability of the warehouse codebase.** ","warehouse/.cursor/rules/documentation.mdc":"---\ndescription: \nglobs: \nalwaysApply: false\n---\n# Documentation Guidelines for Docs Folder\n\nThis document provides guidelines for creating and updating documentation files in the `docs/` directory after implementing features or making significant changes.\n\n## When to Create Documentation\n\nCreate new documentation files when:\n- **Major flow implementations** that involve multiple components/layers\n- **Cross-cutting architectural changes** that affect how future work should be done\n- **Complex patterns** that will be repeated by other developers\n- **Integration points** between different subsystems\n\nUpdate existing documentation files when:\n- **Implementation details change** the documented flow\n- **New patterns emerge** that should be captured\n- **Common pitfalls are discovered** during implementation\n\n## Documentation Structure\n\n### Essential Sections\n\n1. **Brief Overview** - What the document covers in 1-2 sentences\n2. **Flow Architecture** - Clear description of data/control flow between components\n3. **Step-by-step Components** - Each layer/step explained concisely\n4. **Implementation Checklist** - Actionable steps for making similar changes\n5. **Key Concepts** - Important patterns or principles\n6. **Common Pitfalls** - Issues encountered during implementation\n7. **File Organization** - Quick reference for relevant locations\n\n### Optional Sections\n- **Reference Patterns** - If there are reusable patterns worth highlighting\n- **Backward Compatibility** - If relevant to the change type\n\n## Writing Principles\n\n### Be Concept-Focused, Not Code-Specific\n- ❌ **Avoid:** Specific method names, exact file paths, code snippets, struct field names\n- ✅ **Use:** Component roles, architectural patterns, responsibility boundaries\n- ✅ **Preserve:** Architectural component names that are part of the system design\n\n**What to Avoid (Implementation Details):**\n- ❌ \"Update `pingWarehouse()` method in `router/batchrouter/handle.go`\"\n- ❌ \"Modify the `StagingFile` struct in `internal/model/staging.go`\"\n- ❌ \"Call `repo.GetByWorkspaceID(workspaceID)`\"\n\n**What to Keep (Architectural Components):**\n- ✅ \"Set field value in batch router's warehouse notification\"\n- ✅ \"Batch router creates staging file payload after uploading to object storage\"\n- ✅ \"Warehouse client converts staging file to HTTP payload format\"\n- ✅ \"Calls warehouse API endpoint `POST /v1/process` to notify about staging files\"\n\n**Key Distinction:** Preserve named architectural components (batch router, warehouse client, warehouse API), API endpoints, and service contracts while avoiding implementation details (method names, file paths, struct fields).\n\n### Keep Examples Generic\n- ❌ **Avoid:** Detailed field examples that might become outdated\n- ✅ **Use:** General patterns or simple references to \"existing fields\"\n\n**Example:**\n- ❌ \"String from environment: Like instance ID, server name, pod ID\"\n- ✅ \"Look at existing staging file fields for implementation patterns\"\n\n### Focus on Architectural Boundaries\n- Emphasize **who is responsible** for what\n- Highlight **data flow direction** and transformation points\n- Document **responsibility separation** between components\n- Include **API endpoints and service contracts** that define integration points\n\n### Include Essential Architectural Information\n- ✅ **Service boundaries:** Component names and their responsibilities\n- ✅ **Integration contracts:** API endpoints, message formats, service protocols\n- ✅ **Data flow patterns:** How information moves between components\n- ✅ **Configuration points:** Where system behavior can be modified\n- ❌ **Implementation details:** Method names, variable names, file paths\n- ❌ **Code specifics:** Function signatures, class hierarchies, internal APIs\n\n### Use Timeless Language\n- ❌ **Avoid:** \"Currently\", \"at the moment\", version-specific details\n- ✅ **Use:** Present tense, architectural statements\n\n## Implementation Workflow\n\n### During Implementation\n1. **Take notes** on architectural insights and patterns discovered\n2. **Document pitfalls** encountered and how they were resolved\n3. **Track flow dependencies** between components\n4. **Note responsibility boundaries** that become clear\n\n### After Implementation\n1. **Create outline** based on the flow you implemented\n2. **Write concept-focused descriptions** of each component's role\n3. **Create actionable checklist** for similar future changes\n4. **Document common pitfalls** observed during implementation\n5. **Review for code-specific details** and generalize them\n\n### Before Finalizing\n1. **Remove implementation specifics** (method names, file paths, code snippets) while **preserving architectural component names**\n2. **Test readability** - would someone unfamiliar understand the flow?\n3. **Verify checklist completeness** - does it cover all necessary steps?\n4. **Check for redundancy** between sections\n\n## File Organization Strategy\n\n### Naming Convention\n- Use descriptive, hyphenated names: `staging-file-flow.md`\n- Focus on the **process or flow**, not specific features\n- Keep names **broad enough** to encompass related future changes\n- All documentation files use `.md` extension\n\n### File Scope\n- **One major flow per file** - don't combine unrelated processes\n- **Component-focused files** for complex subsystems\n- **Architectural flows and patterns** that help future development\n\n## Maintenance Strategy\n\n### Regular Reviews\n- **After major refactors** - verify documentation still reflects reality\n- **During onboarding** - check if documentation helps new developers\n- **When patterns change** - update to reflect new approaches\n\n### Update Triggers\n- **Flow architecture changes** affecting multiple components\n- **New responsibility boundaries** emerging\n- **Repeated questions** from team members about the same flow\n\n### Deprecation\n- **Remove outdated files** when flows no longer exist\n- **Merge related files** if they become too similar\n- **Archive rather than delete** if historical context is valuable\n\n## Quality Checklist\n\nBefore committing documentation:\n\n- [ ] **Flow is clear** without code knowledge\n- [ ] **Checklist is actionable** and complete  \n- [ ] **Examples are generic** and won't become outdated\n- [ ] **Pitfalls are architectural** not implementation-specific\n- [ ] **Integration points are documented** (API endpoints, service contracts)\n- [ ] **File organization is helpful** for quick reference\n- [ ] **Language is timeless** and concept-focused (preserves architectural component names, avoids implementation details)\n- [ ] **Redundancy is eliminated** between sections\n\n## Benefits of Good Documentation\n\n### For Current Implementation\n- **Validates understanding** of the architectural flow\n- **Identifies gaps** in the implementation approach\n- **Creates shared vocabulary** for the team\n\n### For Future Development\n- **Reduces onboarding time** for new team members\n- **Prevents repeated mistakes** through pitfall documentation\n- **Enables consistent patterns** across similar changes\n- **Speeds up similar implementations** with clear checklists\n\nThis approach ensures documentation remains valuable and current while capturing the essential architectural knowledge needed for future development.\n","AGENTS.md":"<!-- FOR AI AGENTS - Human readability is a side effect, not a goal -->\n<!-- Managed by agent: keep sections and order; edit content, not structure -->\n<!-- Generated with the agent-rules skill v3.14.1 — https://github.com/netresearch/agent-rules-skill -->\n<!-- Last updated: 2026-08-18 | Last verified: 2026-08-18 -->\n\n# AGENTS.md\n\n**Precedence:** the **closest `AGENTS.md`** to the files you're changing wins. Root holds global defaults only.\n\nRudderStack Server — open-source Customer Data Platform (CDP). Go 1.26 monolith: events flow Gateway → Processor →\nRouter/BatchRouter → 90+ destinations and warehouses. Segment API-compatible. Jobs are queued in PostgreSQL (`jobsdb`).\n\n## Commands\n\n> Source: Makefile + `.github/workflows/verify.yml` / `tests.yaml` — CI runs these exact targets\n\n<!-- AGENTS-GENERATED:START commands -->\n\n| Task                    | Command                                                       | Notes                                                                  |\n|-------------------------|---------------------------------------------------------------|------------------------------------------------------------------------|\n| Build                   | `make build`                                                  | Also builds `wait-for-go` and `regulation-worker`                      |\n| Run                     | `make run` (`go run main.go`)                                 | `make run-mt` for multi-tenant via devtool+etcd                        |\n| Format                  | `make fmt`                                                    | gofumpt + gci + matrixchecker; CI fails on `git diff` after this       |\n| Lint                    | `make lint`                                                   | golangci-lint v2.14.0 + actionlint + `make sec` (gitleaks, govulncheck) |\n| Test (all)              | `make test`                                                   | gotestsum, `-p=1 -failfast -shuffle=on`, 15m timeout                   |\n| Test (one package)      | `make test package=gateway`                                   | Path relative to repo root; `exclude=` regex also supported            |\n| Test (single test)      | `go test -count 1 -run TestName ./gateway/...`                |                                                                        |\n| Warehouse integration   | `make test-warehouse package=warehouse/integrations/postgres` | `SLOW=1`, 30m timeout; needs Docker                                    |\n| Regenerate mocks        | `make mocks`                                                  | `go generate ./...` via mockgen v0.6.0; CI diffs the result            |\n| Regenerate protobuf     | `make proto`                                                  | Needs `protoc`; CI diffs the result                                    |\n| Regenerate OpenAPI docs | `make generate-openapi-spec`                                  | Needs Docker; run after editing `gateway/openapi.yaml`                 |\n\n<!-- AGENTS-GENERATED:END commands -->\n\n> If commands fail, verify against the Makefile or ask the user to update this file.\n\n## Response Style\n\n- Answer first, elaborate only if needed. No sycophantic openers.\n- For yes/no or status questions, lead with the answer.\n- Skip preamble. Match response length to task complexity.\n\n## Workflow\n\n1. **Before coding**: Read the nearest `AGENTS.md`, then the README/docs for the subsystem you're touching (see File\n   Map).\n2. **After each change**: Run the smallest relevant check (`make fmt` → `go build ./<pkg>/...` → single test).\n3. **Before committing**: Run `make lint` and tests for every package you touched; run `go mod tidy` if deps changed (CI\n   diffs `go.mod`).\n4. **Before claiming done**: Run verification and **show output as evidence** — never say \"tested\" or \"all green\"\n   without pasted command output in the same turn.\n\n## File Map\n\n<!-- AGENTS-GENERATED:START filemap -->\n\n```\nmain.go                     Entry point: signal handling, config init, launches runner/\nrunner/                     Bootstrap: stats init, service orchestration\napp/                        App interface, enterprise feature registry\napp/apphandlers/            Per-mode startup wiring (EMBEDDED / GATEWAY / PROCESSOR)\ngateway/                    HTTP ingestion API (webhooks, auth, throttling, openapi.yaml)\nprocessor/                  Core pipeline: transformations, enrichment, bot detection\nrouter/                     Per-destination event delivery\nrouter/batchrouter/         Batch + async destinations (see asyncdestinationmanager/README.md)\njobsdb/                     PostgreSQL-backed job queue; dataset rotation, migrations\nwarehouse/                  Warehouse loading; backends in warehouse/integrations/\nbackend-config/             Workspace config fetch/cache from control plane; pub-sub\nservices/                   Shared services: OAuth (see services/oauth/README.md), debuggers, rsources\nenterprise/                 Enterprise-only: suppression, reporting, config env override\ninternal/                   Enrichers (geo, bot), drain-config, transformer client\ncmd/                        CLI tools: devtool (see cmd/devtool/README.md), rudder-cli, backupfilemigrator\nconfig/                     Config key constants and defaults\nproto/                      Protobuf definitions (regenerate with make proto)\nmocks/                      Generated mocks — never edit by hand, run make mocks\nintegration_test/           Docker-based end-to-end tests\ntesthelper/                 Reusable test fixtures: docker resources, backendconfigtest, transformertest\nregulation-worker/          GDPR/regulation compliance worker (separate binary)\nsuppression-backup-service/ Suppression data backup/export (separate binary + Dockerfile)\nsql/                        SQL migration files (golang-migrate) — never delete\n```\n\n<!-- AGENTS-GENERATED:END filemap -->\n\n## Golden Samples (follow these patterns)\n\n<!-- AGENTS-GENERATED:START golden-samples -->\n\n| For                                      | Reference                                              |\n|------------------------------------------|--------------------------------------------------------|\n| Adding an async/batch destination        | `router/batchrouter/asyncdestinationmanager/README.md` |\n| Warehouse staging pipeline changes       | `warehouse/.cursor/docs/staging-file-flow.md`          |\n| OAuth destination flows                  | `services/oauth/README.md`                             |\n| Gateway API contract                     | `gateway/openapi.yaml`                                 |\n| Dev tooling (etcd modes, sending events) | `cmd/devtool/README.md`                                |\n\n<!-- AGENTS-GENERATED:END golden-samples -->\n\n## Utilities (check before creating new)\n\n<!-- AGENTS-GENERATED:START utilities -->\n\n| Need                                                 | Use                                                    | Location                                                                      |\n|------------------------------------------------------|--------------------------------------------------------|-------------------------------------------------------------------------------|\n| JSON marshal/unmarshal                               | `jsonrs`                                               | `github.com/rudderlabs/rudder-go-kit/jsonrs` (linter forbids `encoding/json`) |\n| Config values (env/file/hot-reload)                  | `config`                                               | `github.com/rudderlabs/rudder-go-kit/config`                                  |\n| Structured logging                                   | `logger` non-sugared (`Infon`, `Errorn`, typed fields) | `github.com/rudderlabs/rudder-go-kit/logger`                                  |\n| Error fields in logs                                 | `obskit.Error(err)`                                    | `github.com/rudderlabs/rudder-observability-kit/go/labels`                    |\n| Metrics                                              | `stats.NewTaggedStat`                                  | `github.com/rudderlabs/rudder-go-kit/stats`                                   |\n| Goroutine lifecycle                                  | `errgroup`                                             | `golang.org/x/sync/errgroup`                                                  |\n| Docker test resources (postgres, etcd, transformer…) | testhelper packages                                    | `testhelper/`, `github.com/rudderlabs/rudder-go-kit/testhelper/docker`        |\n\n<!-- AGENTS-GENERATED:END utilities -->\n\n## Heuristics (quick decisions)\n\n<!-- AGENTS-GENERATED:START heuristics -->\n\n| When                                   | Do                                                                                                                         |\n|----------------------------------------|----------------------------------------------------------------------------------------------------------------------------|\n| Async assertion in tests               | `require.Eventually` — never `time.Sleep`; return bool only inside the callback                                            |\n| Touching an interface with a mock      | Regenerate with `make mocks` and commit the diff                                                                           |\n| Editing `proto/**/*.proto`             | Run `make proto` and commit generated files                                                                                |\n| Editing `gateway/openapi.yaml`         | Validate + `make generate-openapi-spec`, commit output                                                                     |\n| Adding a warehouse integration package | Add it to the `warehouse-integration` matrix in `.github/workflows/tests.yaml` (matrixchecker in `make fmt` enforces this) |\n| Adding dependency                      | Ask first — then `go mod tidy` (CI diffs go.mod); no pseudo-version `rudderlabs` deps                                      |\n| Unsure about pattern                   | Check Golden Samples above                                                                                                 |\n\n<!-- AGENTS-GENERATED:END heuristics -->\n\n## Repository Settings\n\n<!-- AGENTS-GENERATED:START repo-settings -->\n\n- Default branch: `master`; release branches: `release/*`. Releases via release-please.\n- PR titles must be conventional commits (enforced by semantic-pr workflow). Allowed types:\n  `fix feat chore refactor exp doc test`. Optional scopes:\n  `core multi-tenant tooling gateway jobsdb warehouse processor router batchrouter destination startup shutdown ci`.\n  Subject must not start with an uppercase letter.\n\n<!-- AGENTS-GENERATED:END repo-settings -->\n\n<!-- AGENTS-GENERATED:START ci-rules -->\n\n### CI Quality Gates (`.github/workflows/verify.yml`, `tests.yaml`)\n\n- `go mod tidy` must produce no diff.\n- `make mocks`, `make proto`, `make fmt`, `make generate-openapi-spec` must each produce no diff.\n- golangci-lint (`.golangci.yml`): depguard, forbidigo, gosec, bodyclose, nilerr, and more.\n- Unit tests run per-package with coverage; integration tests run against Docker (oss + enterprise matrices).\n\n<!-- AGENTS-GENERATED:END ci-rules -->\n\n## Key Decisions\n\n<!-- AGENTS-GENERATED:START key-decisions -->\n\n- Job queue is PostgreSQL (`jobsdb`) with dataset rotation — not a message broker.\n- One binary, three modes via `APP_TYPE` env: `EMBEDDED` (default), `GATEWAY`, `PROCESSOR` (`app/apphandlers/setup.go`).\n- Enterprise features live in `enterprise/` behind `ENTERPRISE_TOKEN`; OSS build must keep working without it.\n- All JSON goes through `jsonrs` (pluggable implementation), enforced by linter.\n\n<!-- AGENTS-GENERATED:END key-decisions -->\n\n## Boundaries\n\n### Always Do\n\n- Run `make fmt` and relevant tests before committing\n- Add tests for new code paths\n- Use conventional commit format: `type(scope): subject` (lowercase subject)\n- Use **atomic commits** (one logical change per commit)\n- **Show test output as evidence before claiming work is complete**\n- Wrap errors with context: `fmt.Errorf(\"starting server: %w\", err)` — active voice, no \"failed to\"\n- Pass `context.Context` as the first parameter; propagate cancellation\n\n### Ask First\n\n- Adding new dependencies\n- Modifying CI/CD configuration (`.github/workflows/`)\n- Changing public API contracts (`gateway/openapi.yaml`, `proto/`)\n- Running full integration test suites (they need Docker and take 30m+)\n- Repo-wide refactoring or rewrites\n\n### Never Do\n\n- Commit secrets or credentials (gitleaks runs in `make lint`)\n- Hand-edit generated files: `mocks/`, protobuf `*.pb.go`, `gateway/openapi/`\n- Push directly to `master` or `release/*` — open a PR\n- Delete SQL migration files under `sql/`\n- Use `encoding/json` (→ `jsonrs`), `github.com/gofrs/uuid` (→ `google/uuid`), `golang.org/x/exp/slices` (→ stdlib\n  `slices`), `aws-sdk-go` v1 (→ v2), `cenkalti/backoff` < v5 (→ v5) — all linter-enforced\n- Use `errors.As` — use `errors.AsType[T](err)`, which returns the typed value and an `ok` bool (linter-enforced)\n- Use sugared logger methods (`Logger.Info`, `Logger.Errorf`, …) — use `Infon`/`Errorn` with typed field constructors\n  and `obskit.Error(err)`\n- Write new tests with Ginkgo/Gomega: use plain `testing` + testify (`require`/`assert`). Existing Ginkgo suites are legacy; don't add new `_test.go` files that import `github.com/onsi/ginkgo` and try to avoid adding `Describe`/`It` blocks to existing ones.\n\n## Contributing (for AI agents)\n\n- **Comprehension**: Understand *why* a change is needed before submitting code; read the linked issue.\n- **Context**: Explain trade-offs in the PR description and link the issue it addresses (see `CONTRIBUTING.md`).\n- **Continuity**: Respond to review feedback; drive-by PRs without follow-up will be closed.\n\n## Terminology\n\n| Term          | Means                                                                                         |\n|---------------|-----------------------------------------------------------------------------------------------|\n| Gateway       | HTTP ingestion service; writes raw events to jobsdb                                           |\n| Processor     | Transforms/enriches events; routes them to router or batchrouter queues                       |\n| Router        | Streams events to cloud destinations one-by-one with retries                                  |\n| Batch router  | Batches events for warehouses and async destinations                                          |\n| jobsdb        | PostgreSQL-backed append-only job queue with dataset rotation                                 |\n| Transformer   | Separate JS service applying destination/user transformations (`internal/transformer-client`) |\n| Control plane | RudderStack hosted config service (`CONFIG_BACKEND_URL`); `backend-config/` syncs from it     |\n| Workspace     | Tenant unit; identified by `WORKSPACE_TOKEN`                                                  |\n| rsources      | Job-status/failed-records service for sources (`services/rsources`)                           |\n| RETL          | Reverse ETL — warehouse-to-destination pipelines                                              |\n\n## When instructions conflict\n\nThe nearest `AGENTS.md` wins. Explicit user prompts override files.\n"},"files":{"warehouse/.cursor/rules/testing.mdc":"---\ndescription: Testing guidelines for the warehouse directory in RudderStack.\nglobs:\n  - \"**/*_test.go\"\nalwaysApply: true\n---\n\n# Warehouse Testing Guidelines\n\nThis document outlines the testing conventions and best practices for the `warehouse/` directory in the RudderStack server codebase.\n\n## Table of Contents\n\n- [Assertion Library](mdc:#assertion-library)\n- [Test Structure](mdc:#test-structure)\n- [Parallelization](mdc:#parallelization)\n- [Context Management](mdc:#context-management)\n- [Setup and Teardown](mdc:#setup-and-teardown)\n- [Database Testing](mdc:#database-testing)\n- [Mocking](mdc:#mocking)\n- [File Management](mdc:#file-management)\n- [Configuration](mdc:#configuration)\n- [Test Naming](mdc:#test-naming)\n- [Error Testing](mdc:#error-testing)\n- [Helper Patterns](mdc:#helper-patterns)\n- [Integration Test Patterns](mdc:#integration-test-patterns)\n- [Common Anti-patterns to Avoid](mdc:#common-anti-patterns-to-avoid)\n- [Example Test Structure](mdc:#example-test-structure)\n\n## Assertion Library\n\n**ALWAYS** use `github.com/stretchr/testify/require` for assertions in warehouse tests.\n\n- Prefer `require` over `assert` to fail fast on critical assertions\n- Use `require.NoError(t, err)` for error checking\n- Use `require.Equal(t, expected, actual)` for equality checks\n- Use `require.True(t, condition)` and `require.False(t, condition)` for boolean checks\n\n```go\nimport (\n    \"github.com/stretchr/testify/require\"\n)\n\nfunc TestExample(t *testing.T) {\n    result, err := someFunction()\n    require.NoError(t, err)\n    require.Equal(t, expected, result)\n}\n```\n\n## Test Structure\n\nUse **table-driven tests** for multiple scenarios:\n\n- Structure table-driven tests with `name`, input, and `expected` fields\n- Always use `t.Run(tc.name, func(t *testing.T) {})` for subtests\n- Group related subtests under a parent `t.Run(\"group name\", ...)` block for clarity and maintainability.\n- Include both positive and negative test cases\n\n```go\n// Table-driven tests for parameterized scenarios\nfunc TestWarehouseFunction(t *testing.T) {\n    testCases := []struct {\n        name     string\n        input    InputType\n        expected ExpectedType\n        wantErr  bool\n    }{\n        {\n            name:     \"successful case\",\n            input:    validInput,\n            expected: expectedOutput,\n            wantErr:  false,\n        },\n        {\n            name:    \"error case\",\n            input:   invalidInput,\n            wantErr: true,\n        },\n    }\n    \n    for _, tc := range testCases {\n        t.Run(tc.name, func(t *testing.T) {\n            // test implementation\n        })\n    }\n}\n\n// Grouped subtests for related functionality\nfunc TestWarehouseComponent(t *testing.T) {\n    t.Run(\"initialization\", func(t *testing.T) {\n        t.Run(\"valid configuration\", func(t *testing.T) { /* ... */ })\n        t.Run(\"invalid configuration\", func(t *testing.T) { /* ... */ })\n        t.Run(\"missing configuration\", func(t *testing.T) { /* ... */ })\n    })\n    \n    t.Run(\"data processing\", func(t *testing.T) {\n        t.Run(\"single record\", func(t *testing.T) { /* ... */ })\n        t.Run(\"batch processing\", func(t *testing.T) { /* ... */ })\n        t.Run(\"empty input\", func(t *testing.T) { /* ... */ })\n    })\n}\n```\n\n## Parallelization\n\n- Use `t.Parallel()` for tests that can run concurrently\n- Apply parallelization to both main tests and subtests where safe\n- Avoid parallelization for tests that modify shared resources\n\n```go\nfunc TestConcurrentFunction(t *testing.T) {\n    t.Parallel()\n    \n    for _, tc := range testCases {\n        t.Run(tc.name, func(t *testing.T) {\n            t.Parallel()\n            // test implementation\n        })\n    }\n}\n```\n\n## Context Management\n\n- Use `context.Background()` as the default context for most tests\n- Use `context.WithTimeout()` for tests with time constraints\n- Always pass context as the first parameter to functions under test\n\n```go\nfunc TestWithContext(t *testing.T) {\n    ctx := context.Background()\n    // or for timeouts:\n    ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n    defer cancel()\n    \n    result, err := functionUnderTest(ctx, input)\n    require.NoError(t, err)\n}\n```\n\n## Setup and Teardown\n\n- Use `t.Cleanup()` for resource cleanup (files, database connections, etc.)\n- Clean up temporary files with `require.NoError(t, os.Remove(filePath))`\n- Use `defer` for cleanup when `t.Cleanup()` is not sufficient\n- Create helper functions for complex test setup\n\n```go\nfunc TestWithCleanup(t *testing.T) {\n    tempFile, err := os.CreateTemp(\"\", \"test_*.txt\")\n    require.NoError(t, err)\n    \n    t.Cleanup(func() {\n        require.NoError(t, os.Remove(tempFile.Name()))\n    })\n    \n    // test implementation\n}\n```\n\n## Database Testing\n\n- Use `dockertest` for PostgreSQL integration tests\n- Set up database migrations with `migrator.Migrator`\n- Use `sqlmiddleware.New()` for database connections\n- Clean up database resources properly in `t.Cleanup()`\n\n```go\nfunc TestDatabaseIntegration(t *testing.T) {\n    pool, err := dockertest.NewPool(\"\")\n    require.NoError(t, err)\n    \n    pgResource, err := postgres.Setup(pool, t)\n    require.NoError(t, err)\n    \n    err = (&migrator.Migrator{\n        Handle:          pgResource.DB,\n        MigrationsTable: \"wh_schema_migrations\",\n    }).Migrate(\"warehouse\")\n    require.NoError(t, err)\n    \n    db := sqlmiddleware.New(pgResource.DB)\n    \n    // test implementation\n}\n```\n\n## Mocking\n\n- Use `go.uber.org/mock/gomock` for interface mocking\n- Create mock expectations with clear `.EXPECT()` calls\n- Use `gomock.NewController(t)` for mock controller setup\n- Place mock generation comments: `//go:generate go run go.uber.org/mock/mockgen`\n- For error path testing, prefer extending mocks with error fields or behaviors rather than creating many separate mock types.\n\n```go\ntype mockRepository struct {\n    data map[string]interface{}\n    err  error\n}\n\nfunc (m *mockRepository) Get(key string) (interface{}, error) {\n    if m.err != nil {\n        return nil, m.err\n    }\n    return m.data[key], nil\n}\n\n// Usage in tests:\nsuccessMock := &mockRepository{data: map[string]interface{}{\"key\": \"value\"}}\nerrorMock := &mockRepository{err: errors.New(\"connection failed\")}\n```\n\n## File Management\n\n- Create temporary files with `os.CreateTemp()` or `t.TempDir()`\n- Always clean up files with `t.Cleanup(func() { require.NoError(t, os.Remove(fileName)) })`\n- Use proper file handling patterns for testing file operations\n- Test both successful file operations and error cases\n\n```go\nfunc TestFileOperations(t *testing.T) {\n    tempDir := t.TempDir()\n    \n    tempFile, err := os.CreateTemp(tempDir, \"test_*.json\")\n    require.NoError(t, err)\n    \n    t.Cleanup(func() {\n        require.NoError(t, tempFile.Close())\n    })\n    \n    // test file operations\n}\n```\n\n## Configuration\n\n- Use `config.New()` for test configuration\n- Override config values with `c.Set(key, value)` for test scenarios\n- Use environment variable overrides when testing config behavior\n- Test both default and custom configuration values\n\n```go\nfunc TestConfiguration(t *testing.T) {\n    c := config.New()\n    c.Set(\"Warehouse.testKey\", \"testValue\")\n    \n    // test with configuration\n}\n```\n\n## Test Naming\n\n- Use descriptive test function names: `TestFunctionName_Scenario`\n- Use underscores to separate components in test names\n- Include the component being tested in the function name\n- Use clear, descriptive names for table-driven test cases\n\n```go\nfunc TestWarehouse_GetBoolDestinationConfig(t *testing.T) { /* ... */ }\nfunc TestLoadFileGenerator_GetLoadFilePrefix(t *testing.T) { /* ... */ }\nfunc TestStagingFileRepo_GetPending(t *testing.T) { /* ... */ }\n```\n\n## Error Testing\n\n- Test both success and error scenarios\n- Use `require.Error(t, err)` for expected errors\n- Use `require.ErrorIs(t, err, expectedError)` for specific error types\n- Use `require.EqualError(t, err, expectedMessage)` for exact error messages\n- For fallback or multi-source logic, ensure tests cover all branches, including \"no data,\" \"empty but present,\" and error propagation.\n\n```go\nt.Run(\"data retrieval with fallback\", func(t *testing.T) {\n    t.Run(\"primary source succeeds\", func(t *testing.T) { /* ... */ })\n    t.Run(\"primary source fails, fallback succeeds\", func(t *testing.T) { /* ... */ })\n    t.Run(\"both primary and fallback fail\", func(t *testing.T) { /* ... */ })\n    t.Run(\"primary source returns empty, no fallback\", func(t *testing.T) { /* ... */ })\n})\n```\n\n## Helper Patterns\n\n- Create test helper functions for complex setups\n- Use `t.Helper()` in helper functions to get correct line numbers\n- Extract common test data into helper functions or constants\n- Create factory functions for test models and objects\n\n```go\nfunc createTestWarehouse(t *testing.T) model.Warehouse {\n    t.Helper()\n    \n    return model.Warehouse{\n        WorkspaceID: \"test-workspace\",\n        Source: backendconfig.SourceT{\n            ID: \"test-source\",\n        },\n        Destination: backendconfig.DestinationT{\n            ID: \"test-destination\",\n        },\n    }\n}\n\nfunc setupTestDatabase(t *testing.T) (*sql.DB, func()) {\n    t.Helper()\n    \n    // setup logic\n    \n    cleanup := func() {\n        // cleanup logic\n    }\n    \n    return db, cleanup\n}\n```\n\n## Integration Test Patterns\n\n- Use docker-compose for complex integration test setups\n- Set up real warehouse connections for integration tests\n- Use conditional skips: `if os.Getenv(\"SLOW\") != \"1\" { t.Skip() }`\n- Test end-to-end workflows with real data\n\n```go\nfunc TestIntegration(t *testing.T) {\n    if os.Getenv(\"SLOW\") != \"1\" {\n        t.Skip(\"Skipping integration tests. Add 'SLOW=1' env var to run test.\")\n    }\n    \n    // integration test implementation\n}\n```\n\n## Common Anti-patterns to Avoid\n\n- ❌ Don't use `testing.T.Fatal()` or `t.Fatalf()` - use `require` instead\n- ❌ Don't ignore cleanup errors - always check with `require.NoError()`\n- ❌ Don't create tests without cleanup for temporary resources\n- ❌ Don't use sleep for timing - use proper synchronization or timeouts\n- ❌ Don't test implementation details - focus on behavior\n\n## Example Test Structure\n\nHere's a complete example following all the guidelines:\n\n```go\npackage warehouse_test\n\nimport (\n    \"context\"\n    \"os\"\n    \"testing\"\n    \"time\"\n\n    \"github.com/stretchr/testify/require\"\n    \"go.uber.org/mock/gomock\"\n\n    \"github.com/rudderlabs/rudder-go-kit/config\"\n    \"github.com/rudderlabs/rudder-server/warehouse/internal/model\"\n)\n\nfunc TestWarehouseFunction_Scenario(t *testing.T) {\n    testCases := []struct {\n        name     string\n        input    InputType\n        expected ExpectedType\n        wantErr  bool\n    }{\n        {\n            name:     \"successful case\",\n            input:    validInput,\n            expected: expectedOutput,\n            wantErr:  false,\n        },\n        {\n            name:    \"error case\",\n            input:   invalidInput,\n            wantErr: true,\n        },\n    }\n    \n    for _, tc := range testCases {\n        t.Run(tc.name, func(t *testing.T) {\n            t.Parallel()\n            \n            // Setup\n            ctx := context.Background()\n            ctrl := gomock.NewController(t)\n            defer ctrl.Finish()\n            \n            tempFile, err := os.CreateTemp(\"\", \"test_*.json\")\n            require.NoError(t, err)\n            \n            t.Cleanup(func() {\n                require.NoError(t, os.Remove(tempFile.Name()))\n            })\n            \n            // Test execution\n            result, err := functionUnderTest(ctx, tc.input)\n            \n            // Assertions\n            if tc.wantErr {\n                require.Error(t, err)\n                return\n            }\n            \n            require.NoError(t, err)\n            require.Equal(t, tc.expected, result)\n        })\n    }\n}\n```\n\n## Reference\n\nThis document is based on analysis of existing test patterns in the warehouse directory. For questions or suggestions about these guidelines, please refer to the test files in the warehouse directory for examples of these patterns in practice. ","cmd/devtool/commands/payloads/batch.json":"{\n  \"batch\": [\n    {\n      \"anonymousId\": \"{{.AnonymousId}}\",\n      \"channel\": \"android-sdk\",\n      \"context\": {\n        \"app\": {\n          \"build\": \"1\",\n          \"name\": \"RudderAndroidClient\",\n          \"namespace\": \"com.rudderlabs.android.sdk\",\n          \"version\": \"1.0\"\n        },\n        \"device\": {\n          \"id\": \"49e4bdd1c280bc00\",\n          \"manufacturer\": \"Google\",\n          \"model\": \"Android SDK built for x86\",\n          \"name\": \"generic_x86\"\n        },\n        \"locale\": \"en-US\",\n        \"network\": {\n          \"carrier\": \"Android\"\n        },\n        \"screen\": {\n          \"density\": 420,\n          \"height\": 1794,\n          \"width\": 1080\n        },\n        \"library\": {\n          \"name\": \"com.rudderstack.android.sdk.core\"\n        },\n        \"traits\": {\n          \"anonymousId\": \"{{.AnonymousId}}\"\n        },\n        \"user_agent\": \"Dalvik/2.1.0 (Linux; U; Android 9; Android SDK built for x86 Build/PSR1.180720.075)\"\n      },\n      \"event\": \"Demo Track\",\n      \"integrations\": {\n        \"All\": true\n      },\n      \"properties\": {\n        \"label\": \"Demo Label\",\n        \"category\": \"Demo Category\",\n        \"value\": 5,\n        \"testMap\": {\n          \"t1\": \"a\",\n          \"t2\": 4\n        },\n        \"floatVal\": 4.501,\n        \"testArray\": [\n          {\n            \"id\": \"elem1\",\n            \"value\": \"e1\"\n          },\n          {\n            \"id\": \"elem2\",\n            \"value\": \"e2\"\n          }\n        ]\n      },\n      \"type\": \"track\",\n      \"originalTimestamp\": \"{{.Timestamp}}\",\n      \"sentAt\": \"{{.Timestamp}}\"\n    }\n  ]\n}\n","warehouse/.cursor/rules/plan-act-workflow.mdc":"---\ndescription: \nglobs: \nalwaysApply: true\n---\n# 🚨 CRITICAL PLAN-ACT WORKFLOW RULE 🚨\n\n## ⚠️ MANDATORY REQUIREMENT FOR ALL DEVELOPMENT TASKS ⚠️\n\n**This is a CRITICAL rule that MUST be followed without exception when working on any development task in the warehouse directory.**\n\n## 🔄 TWO MODES OF OPERATION: PLAN → ACT\n\n### 📋 MODE 1: PLAN (Planning Phase)\n**In PLAN mode, you focus EXCLUSIVELY on planning and analysis. NO CODE IMPLEMENTATION is allowed.**\n\n### ⚡ MODE 2: ACT (Implementation Phase)  \n**In ACT mode, you execute the approved plan. NO NEW PLANNING or scope changes without returning to PLAN mode.**\n\n**🚫 CRITICAL RULE: You CANNOT be in both modes simultaneously. You must explicitly transition from PLAN → ACT.**\n\n---\n\n### RULE: COMPREHENSIVE PLANNING BEFORE IMPLEMENTATION\n\n### 📋 PLAN MODE REQUIREMENTS\n\n**At any step in PLAN mode, always ask the user for clarifications—even for minor uncertainties or assumptions—whenever needed. This applies to requirement gathering, planning, challenge identification, and documentation/approval.**\n\nComplete ALL of the following before transitioning to ACT mode:\n\n#### 0. 📝 REQUIREMENT GATHERING & CLARIFICATION\n- Begin by gathering requirements and understanding the user's goals, constraints, and expectations for the task.\n\n#### 1. 📋 COMPREHENSIVE PLAN\n- Break down task into actionable steps with dependencies and complexity estimates\n- Identify all affected components and define clear success criteria\n\n#### 2. 🔍 CHALLENGE IDENTIFICATION  \n- Technical risks (algorithms, performance, integration, edge cases)\n- Testing requirements (mocks, data, coverage strategy)\n- Compatibility and resource constraints (migrations, external dependencies)\n\n#### 3. 📝 DOCUMENTATION & APPROVAL\n- Document step-by-step approach with risk mitigation and rollback plan\n- **GET EXPLICIT APPROVAL** - ACT mode forbidden until plan is approved\n- **DECLARE TRANSITION**: \"Moving from PLAN mode to ACT mode\"\n\n### ⚡ ACT MODE REQUIREMENTS\n\nIn ACT mode, you MUST:\n\n#### 1. 🎯 EXECUTE THE APPROVED PLAN\n- Follow documented steps exactly, implement only what was planned\n- **DECLARE MODE**: \"Currently in ACT mode\"\n\n#### 2. 🚫 NO SCOPE CHANGES  \n- Any unexpected issues or new requirements require **RETURN TO PLAN MODE**\n- Track progress and report deviations immediately\n\n### 🚫 VIOLATIONS - STRICTLY PROHIBITED\n\n- **PLAN Mode**: Implementing code, skipping planning steps, proceeding without approval\n- **ACT Mode**: Changing scope without returning to PLAN, deviating from approved plan  \n- **Mode Mixing**: Operating in both modes, transitions without declarations\n\n### ✅ COMPLIANCE CHECKLIST\n\n#### PLAN Mode:\n- [ ] Declared \"Currently in PLAN mode\"\n- [ ] **Gathered requirements and clarified all uncertainties with the user (and sought clarifications at any step as needed)**\n- [ ] Completed comprehensive plan with steps, challenges, and risks\n- [ ] Received explicit approval  \n- [ ] **Declared transition**: \"Moving from PLAN mode to ACT mode\"\n\n#### ACT Mode:\n- [ ] Declared \"Currently in ACT mode\" \n- [ ] Following approved plan exactly\n- [ ] **If scope changes needed**: Return to PLAN mode first\n\n### 🎯 WHY THIS RULE EXISTS\n\n**Prevents costly mistakes** through upfront planning, **ensures focused execution** by mode separation, **reduces context switching**, and **maintains scope discipline**.\n\n---\n\n**Remember: The PLAN → ACT workflow creates mental clarity and prevents the costly mistake of \"planning while coding.\" This two-mode approach is non-negotiable for maintaining the quality and reliability of the warehouse codebase.** ","warehouse/.cursor/rules/documentation.mdc":"---\ndescription: \nglobs: \nalwaysApply: false\n---\n# Documentation Guidelines for Docs Folder\n\nThis document provides guidelines for creating and updating documentation files in the `docs/` directory after implementing features or making significant changes.\n\n## When to Create Documentation\n\nCreate new documentation files when:\n- **Major flow implementations** that involve multiple components/layers\n- **Cross-cutting architectural changes** that affect how future work should be done\n- **Complex patterns** that will be repeated by other developers\n- **Integration points** between different subsystems\n\nUpdate existing documentation files when:\n- **Implementation details change** the documented flow\n- **New patterns emerge** that should be captured\n- **Common pitfalls are discovered** during implementation\n\n## Documentation Structure\n\n### Essential Sections\n\n1. **Brief Overview** - What the document covers in 1-2 sentences\n2. **Flow Architecture** - Clear description of data/control flow between components\n3. **Step-by-step Components** - Each layer/step explained concisely\n4. **Implementation Checklist** - Actionable steps for making similar changes\n5. **Key Concepts** - Important patterns or principles\n6. **Common Pitfalls** - Issues encountered during implementation\n7. **File Organization** - Quick reference for relevant locations\n\n### Optional Sections\n- **Reference Patterns** - If there are reusable patterns worth highlighting\n- **Backward Compatibility** - If relevant to the change type\n\n## Writing Principles\n\n### Be Concept-Focused, Not Code-Specific\n- ❌ **Avoid:** Specific method names, exact file paths, code snippets, struct field names\n- ✅ **Use:** Component roles, architectural patterns, responsibility boundaries\n- ✅ **Preserve:** Architectural component names that are part of the system design\n\n**What to Avoid (Implementation Details):**\n- ❌ \"Update `pingWarehouse()` method in `router/batchrouter/handle.go`\"\n- ❌ \"Modify the `StagingFile` struct in `internal/model/staging.go`\"\n- ❌ \"Call `repo.GetByWorkspaceID(workspaceID)`\"\n\n**What to Keep (Architectural Components):**\n- ✅ \"Set field value in batch router's warehouse notification\"\n- ✅ \"Batch router creates staging file payload after uploading to object storage\"\n- ✅ \"Warehouse client converts staging file to HTTP payload format\"\n- ✅ \"Calls warehouse API endpoint `POST /v1/process` to notify about staging files\"\n\n**Key Distinction:** Preserve named architectural components (batch router, warehouse client, warehouse API), API endpoints, and service contracts while avoiding implementation details (method names, file paths, struct fields).\n\n### Keep Examples Generic\n- ❌ **Avoid:** Detailed field examples that might become outdated\n- ✅ **Use:** General patterns or simple references to \"existing fields\"\n\n**Example:**\n- ❌ \"String from environment: Like instance ID, server name, pod ID\"\n- ✅ \"Look at existing staging file fields for implementation patterns\"\n\n### Focus on Architectural Boundaries\n- Emphasize **who is responsible** for what\n- Highlight **data flow direction** and transformation points\n- Document **responsibility separation** between components\n- Include **API endpoints and service contracts** that define integration points\n\n### Include Essential Architectural Information\n- ✅ **Service boundaries:** Component names and their responsibilities\n- ✅ **Integration contracts:** API endpoints, message formats, service protocols\n- ✅ **Data flow patterns:** How information moves between components\n- ✅ **Configuration points:** Where system behavior can be modified\n- ❌ **Implementation details:** Method names, variable names, file paths\n- ❌ **Code specifics:** Function signatures, class hierarchies, internal APIs\n\n### Use Timeless Language\n- ❌ **Avoid:** \"Currently\", \"at the moment\", version-specific details\n- ✅ **Use:** Present tense, architectural statements\n\n## Implementation Workflow\n\n### During Implementation\n1. **Take notes** on architectural insights and patterns discovered\n2. **Document pitfalls** encountered and how they were resolved\n3. **Track flow dependencies** between components\n4. **Note responsibility boundaries** that become clear\n\n### After Implementation\n1. **Create outline** based on the flow you implemented\n2. **Write concept-focused descriptions** of each component's role\n3. **Create actionable checklist** for similar future changes\n4. **Document common pitfalls** observed during implementation\n5. **Review for code-specific details** and generalize them\n\n### Before Finalizing\n1. **Remove implementation specifics** (method names, file paths, code snippets) while **preserving architectural component names**\n2. **Test readability** - would someone unfamiliar understand the flow?\n3. **Verify checklist completeness** - does it cover all necessary steps?\n4. **Check for redundancy** between sections\n\n## File Organization Strategy\n\n### Naming Convention\n- Use descriptive, hyphenated names: `staging-file-flow.md`\n- Focus on the **process or flow**, not specific features\n- Keep names **broad enough** to encompass related future changes\n- All documentation files use `.md` extension\n\n### File Scope\n- **One major flow per file** - don't combine unrelated processes\n- **Component-focused files** for complex subsystems\n- **Architectural flows and patterns** that help future development\n\n## Maintenance Strategy\n\n### Regular Reviews\n- **After major refactors** - verify documentation still reflects reality\n- **During onboarding** - check if documentation helps new developers\n- **When patterns change** - update to reflect new approaches\n\n### Update Triggers\n- **Flow architecture changes** affecting multiple components\n- **New responsibility boundaries** emerging\n- **Repeated questions** from team members about the same flow\n\n### Deprecation\n- **Remove outdated files** when flows no longer exist\n- **Merge related files** if they become too similar\n- **Archive rather than delete** if historical context is valuable\n\n## Quality Checklist\n\nBefore committing documentation:\n\n- [ ] **Flow is clear** without code knowledge\n- [ ] **Checklist is actionable** and complete  \n- [ ] **Examples are generic** and won't become outdated\n- [ ] **Pitfalls are architectural** not implementation-specific\n- [ ] **Integration points are documented** (API endpoints, service contracts)\n- [ ] **File organization is helpful** for quick reference\n- [ ] **Language is timeless** and concept-focused (preserves architectural component names, avoids implementation details)\n- [ ] **Redundancy is eliminated** between sections\n\n## Benefits of Good Documentation\n\n### For Current Implementation\n- **Validates understanding** of the architectural flow\n- **Identifies gaps** in the implementation approach\n- **Creates shared vocabulary** for the team\n\n### For Future Development\n- **Reduces onboarding time** for new team members\n- **Prevents repeated mistakes** through pitfall documentation\n- **Enables consistent patterns** across similar changes\n- **Speeds up similar implementations** with clear checklists\n\nThis approach ensures documentation remains valuable and current while capturing the essential architectural knowledge needed for future development.\n","AGENTS.md":"<!-- FOR AI AGENTS - Human readability is a side effect, not a goal -->\n<!-- Managed by agent: keep sections and order; edit content, not structure -->\n<!-- Generated with the agent-rules skill v3.14.1 — https://github.com/netresearch/agent-rules-skill -->\n<!-- Last updated: 2026-08-18 | Last verified: 2026-08-18 -->\n\n# AGENTS.md\n\n**Precedence:** the **closest `AGENTS.md`** to the files you're changing wins. Root holds global defaults only.\n\nRudderStack Server — open-source Customer Data Platform (CDP). Go 1.26 monolith: events flow Gateway → Processor →\nRouter/BatchRouter → 90+ destinations and warehouses. Segment API-compatible. Jobs are queued in PostgreSQL (`jobsdb`).\n\n## Commands\n\n> Source: Makefile + `.github/workflows/verify.yml` / `tests.yaml` — CI runs these exact targets\n\n<!-- AGENTS-GENERATED:START commands -->\n\n| Task                    | Command                                                       | Notes                                                                  |\n|-------------------------|---------------------------------------------------------------|------------------------------------------------------------------------|\n| Build                   | `make build`                                                  | Also builds `wait-for-go` and `regulation-worker`                      |\n| Run                     | `make run` (`go run main.go`)                                 | `make run-mt` for multi-tenant via devtool+etcd                        |\n| Format                  | `make fmt`                                                    | gofumpt + gci + matrixchecker; CI fails on `git diff` after this       |\n| Lint                    | `make lint`                                                   | golangci-lint v2.14.0 + actionlint + `make sec` (gitleaks, govulncheck) |\n| Test (all)              | `make test`                                                   | gotestsum, `-p=1 -failfast -shuffle=on`, 15m timeout                   |\n| Test (one package)      | `make test package=gateway`                                   | Path relative to repo root; `exclude=` regex also supported            |\n| Test (single test)      | `go test -count 1 -run TestName ./gateway/...`                |                                                                        |\n| Warehouse integration   | `make test-warehouse package=warehouse/integrations/postgres` | `SLOW=1`, 30m timeout; needs Docker                                    |\n| Regenerate mocks        | `make mocks`                                                  | `go generate ./...` via mockgen v0.6.0; CI diffs the result            |\n| Regenerate protobuf     | `make proto`                                                  | Needs `protoc`; CI diffs the result                                    |\n| Regenerate OpenAPI docs | `make generate-openapi-spec`                                  | Needs Docker; run after editing `gateway/openapi.yaml`                 |\n\n<!-- AGENTS-GENERATED:END commands -->\n\n> If commands fail, verify against the Makefile or ask the user to update this file.\n\n## Response Style\n\n- Answer first, elaborate only if needed. No sycophantic openers.\n- For yes/no or status questions, lead with the answer.\n- Skip preamble. Match response length to task complexity.\n\n## Workflow\n\n1. **Before coding**: Read the nearest `AGENTS.md`, then the README/docs for the subsystem you're touching (see File\n   Map).\n2. **After each change**: Run the smallest relevant check (`make fmt` → `go build ./<pkg>/...` → single test).\n3. **Before committing**: Run `make lint` and tests for every package you touched; run `go mod tidy` if deps changed (CI\n   diffs `go.mod`).\n4. **Before claiming done**: Run verification and **show output as evidence** — never say \"tested\" or \"all green\"\n   without pasted command output in the same turn.\n\n## File Map\n\n<!-- AGENTS-GENERATED:START filemap -->\n\n```\nmain.go                     Entry point: signal handling, config init, launches runner/\nrunner/                     Bootstrap: stats init, service orchestration\napp/                        App interface, enterprise feature registry\napp/apphandlers/            Per-mode startup wiring (EMBEDDED / GATEWAY / PROCESSOR)\ngateway/                    HTTP ingestion API (webhooks, auth, throttling, openapi.yaml)\nprocessor/                  Core pipeline: transformations, enrichment, bot detection\nrouter/                     Per-destination event delivery\nrouter/batchrouter/         Batch + async destinations (see asyncdestinationmanager/README.md)\njobsdb/                     PostgreSQL-backed job queue; dataset rotation, migrations\nwarehouse/                  Warehouse loading; backends in warehouse/integrations/\nbackend-config/             Workspace config fetch/cache from control plane; pub-sub\nservices/                   Shared services: OAuth (see services/oauth/README.md), debuggers, rsources\nenterprise/                 Enterprise-only: suppression, reporting, config env override\ninternal/                   Enrichers (geo, bot), drain-config, transformer client\ncmd/                        CLI tools: devtool (see cmd/devtool/README.md), rudder-cli, backupfilemigrator\nconfig/                     Config key constants and defaults\nproto/                      Protobuf definitions (regenerate with make proto)\nmocks/                      Generated mocks — never edit by hand, run make mocks\nintegration_test/           Docker-based end-to-end tests\ntesthelper/                 Reusable test fixtures: docker resources, backendconfigtest, transformertest\nregulation-worker/          GDPR/regulation compliance worker (separate binary)\nsuppression-backup-service/ Suppression data backup/export (separate binary + Dockerfile)\nsql/                        SQL migration files (golang-migrate) — never delete\n```\n\n<!-- AGENTS-GENERATED:END filemap -->\n\n## Golden Samples (follow these patterns)\n\n<!-- AGENTS-GENERATED:START golden-samples -->\n\n| For                                      | Reference                                              |\n|------------------------------------------|--------------------------------------------------------|\n| Adding an async/batch destination        | `router/batchrouter/asyncdestinationmanager/README.md` |\n| Warehouse staging pipeline changes       | `warehouse/.cursor/docs/staging-file-flow.md`          |\n| OAuth destination flows                  | `services/oauth/README.md`                             |\n| Gateway API contract                     | `gateway/openapi.yaml`                                 |\n| Dev tooling (etcd modes, sending events) | `cmd/devtool/README.md`                                |\n\n<!-- AGENTS-GENERATED:END golden-samples -->\n\n## Utilities (check before creating new)\n\n<!-- AGENTS-GENERATED:START utilities -->\n\n| Need                                                 | Use                                                    | Location                                                                      |\n|------------------------------------------------------|--------------------------------------------------------|-------------------------------------------------------------------------------|\n| JSON marshal/unmarshal                               | `jsonrs`                                               | `github.com/rudderlabs/rudder-go-kit/jsonrs` (linter forbids `encoding/json`) |\n| Config values (env/file/hot-reload)                  | `config`                                               | `github.com/rudderlabs/rudder-go-kit/config`                                  |\n| Structured logging                                   | `logger` non-sugared (`Infon`, `Errorn`, typed fields) | `github.com/rudderlabs/rudder-go-kit/logger`                                  |\n| Error fields in logs                                 | `obskit.Error(err)`                                    | `github.com/rudderlabs/rudder-observability-kit/go/labels`                    |\n| Metrics                                              | `stats.NewTaggedStat`                                  | `github.com/rudderlabs/rudder-go-kit/stats`                                   |\n| Goroutine lifecycle                                  | `errgroup`                                             | `golang.org/x/sync/errgroup`                                                  |\n| Docker test resources (postgres, etcd, transformer…) | testhelper packages                                    | `testhelper/`, `github.com/rudderlabs/rudder-go-kit/testhelper/docker`        |\n\n<!-- AGENTS-GENERATED:END utilities -->\n\n## Heuristics (quick decisions)\n\n<!-- AGENTS-GENERATED:START heuristics -->\n\n| When                                   | Do                                                                                                                         |\n|----------------------------------------|----------------------------------------------------------------------------------------------------------------------------|\n| Async assertion in tests               | `require.Eventually` — never `time.Sleep`; return bool only inside the callback                                            |\n| Touching an interface with a mock      | Regenerate with `make mocks` and commit the diff                                                                           |\n| Editing `proto/**/*.proto`             | Run `make proto` and commit generated files                                                                                |\n| Editing `gateway/openapi.yaml`         | Validate + `make generate-openapi-spec`, commit output                                                                     |\n| Adding a warehouse integration package | Add it to the `warehouse-integration` matrix in `.github/workflows/tests.yaml` (matrixchecker in `make fmt` enforces this) |\n| Adding dependency                      | Ask first — then `go mod tidy` (CI diffs go.mod); no pseudo-version `rudderlabs` deps                                      |\n| Unsure about pattern                   | Check Golden Samples above                                                                                                 |\n\n<!-- AGENTS-GENERATED:END heuristics -->\n\n## Repository Settings\n\n<!-- AGENTS-GENERATED:START repo-settings -->\n\n- Default branch: `master`; release branches: `release/*`. Releases via release-please.\n- PR titles must be conventional commits (enforced by semantic-pr workflow). Allowed types:\n  `fix feat chore refactor exp doc test`. Optional scopes:\n  `core multi-tenant tooling gateway jobsdb warehouse processor router batchrouter destination startup shutdown ci`.\n  Subject must not start with an uppercase letter.\n\n<!-- AGENTS-GENERATED:END repo-settings -->\n\n<!-- AGENTS-GENERATED:START ci-rules -->\n\n### CI Quality Gates (`.github/workflows/verify.yml`, `tests.yaml`)\n\n- `go mod tidy` must produce no diff.\n- `make mocks`, `make proto`, `make fmt`, `make generate-openapi-spec` must each produce no diff.\n- golangci-lint (`.golangci.yml`): depguard, forbidigo, gosec, bodyclose, nilerr, and more.\n- Unit tests run per-package with coverage; integration tests run against Docker (oss + enterprise matrices).\n\n<!-- AGENTS-GENERATED:END ci-rules -->\n\n## Key Decisions\n\n<!-- AGENTS-GENERATED:START key-decisions -->\n\n- Job queue is PostgreSQL (`jobsdb`) with dataset rotation — not a message broker.\n- One binary, three modes via `APP_TYPE` env: `EMBEDDED` (default), `GATEWAY`, `PROCESSOR` (`app/apphandlers/setup.go`).\n- Enterprise features live in `enterprise/` behind `ENTERPRISE_TOKEN`; OSS build must keep working without it.\n- All JSON goes through `jsonrs` (pluggable implementation), enforced by linter.\n\n<!-- AGENTS-GENERATED:END key-decisions -->\n\n## Boundaries\n\n### Always Do\n\n- Run `make fmt` and relevant tests before committing\n- Add tests for new code paths\n- Use conventional commit format: `type(scope): subject` (lowercase subject)\n- Use **atomic commits** (one logical change per commit)\n- **Show test output as evidence before claiming work is complete**\n- Wrap errors with context: `fmt.Errorf(\"starting server: %w\", err)` — active voice, no \"failed to\"\n- Pass `context.Context` as the first parameter; propagate cancellation\n\n### Ask First\n\n- Adding new dependencies\n- Modifying CI/CD configuration (`.github/workflows/`)\n- Changing public API contracts (`gateway/openapi.yaml`, `proto/`)\n- Running full integration test suites (they need Docker and take 30m+)\n- Repo-wide refactoring or rewrites\n\n### Never Do\n\n- Commit secrets or credentials (gitleaks runs in `make lint`)\n- Hand-edit generated files: `mocks/`, protobuf `*.pb.go`, `gateway/openapi/`\n- Push directly to `master` or `release/*` — open a PR\n- Delete SQL migration files under `sql/`\n- Use `encoding/json` (→ `jsonrs`), `github.com/gofrs/uuid` (→ `google/uuid`), `golang.org/x/exp/slices` (→ stdlib\n  `slices`), `aws-sdk-go` v1 (→ v2), `cenkalti/backoff` < v5 (→ v5) — all linter-enforced\n- Use `errors.As` — use `errors.AsType[T](err)`, which returns the typed value and an `ok` bool (linter-enforced)\n- Use sugared logger methods (`Logger.Info`, `Logger.Errorf`, …) — use `Infon`/`Errorn` with typed field constructors\n  and `obskit.Error(err)`\n- Write new tests with Ginkgo/Gomega: use plain `testing` + testify (`require`/`assert`). Existing Ginkgo suites are legacy; don't add new `_test.go` files that import `github.com/onsi/ginkgo` and try to avoid adding `Describe`/`It` blocks to existing ones.\n\n## Contributing (for AI agents)\n\n- **Comprehension**: Understand *why* a change is needed before submitting code; read the linked issue.\n- **Context**: Explain trade-offs in the PR description and link the issue it addresses (see `CONTRIBUTING.md`).\n- **Continuity**: Respond to review feedback; drive-by PRs without follow-up will be closed.\n\n## Terminology\n\n| Term          | Means                                                                                         |\n|---------------|-----------------------------------------------------------------------------------------------|\n| Gateway       | HTTP ingestion service; writes raw events to jobsdb                                           |\n| Processor     | Transforms/enriches events; routes them to router or batchrouter queues                       |\n| Router        | Streams events to cloud destinations one-by-one with retries                                  |\n| Batch router  | Batches events for warehouses and async destinations                                          |\n| jobsdb        | PostgreSQL-backed append-only job queue with dataset rotation                                 |\n| Transformer   | Separate JS service applying destination/user transformations (`internal/transformer-client`) |\n| Control plane | RudderStack hosted config service (`CONFIG_BACKEND_URL`); `backend-config/` syncs from it     |\n| Workspace     | Tenant unit; identified by `WORKSPACE_TOKEN`                                                  |\n| rsources      | Job-status/failed-records service for sources (`services/rsources`)                           |\n| RETL          | Reverse ETL — warehouse-to-destination pipelines                                              |\n\n## When instructions conflict\n\nThe nearest `AGENTS.md` wins. Explicit user prompts override files.\n"},"items":[{"name":"AGENTS.md","path":"AGENTS.md","rawUrl":"https://raw.githubusercontent.com/rudderlabs/rudder-server/HEAD/AGENTS.md","title":"AI Agent Protocol & Instructions","category":"root-instruction","format":"markdown","content":"<!-- FOR AI AGENTS - Human readability is a side effect, not a goal -->\n<!-- Managed by agent: keep sections and order; edit content, not structure -->\n<!-- Generated with the agent-rules skill v3.14.1 — https://github.com/netresearch/agent-rules-skill -->\n<!-- Last updated: 2026-08-18 | Last verified: 2026-08-18 -->\n\n# AGENTS.md\n\n**Precedence:** the **closest `AGENTS.md`** to the files you're changing wins. Root holds global defaults only.\n\nRudderStack Server — open-source Customer Data Platform (CDP). Go 1.26 monolith: events flow Gateway → Processor →\nRouter/BatchRouter → 90+ destinations and warehouses. Segment API-compatible. Jobs are queued in PostgreSQL (`jobsdb`).\n\n## Commands\n\n> Source: Makefile + `.github/workflows/verify.yml` / `tests.yaml` — CI runs these exact targets\n\n<!-- AGENTS-GENERATED:START commands -->\n\n| Task                    | Command                                                       | Notes                                                                  |\n|-------------------------|---------------------------------------------------------------|------------------------------------------------------------------------|\n| Build                   | `make build`                                                  | Also builds `wait-for-go` and `regulation-worker`                      |\n| Run                     | `make run` (`go run main.go`)                                 | `make run-mt` for multi-tenant via devtool+etcd                        |\n| Format                  | `make fmt`                                                    | gofumpt + gci + matrixchecker; CI fails on `git diff` after this       |\n| Lint                    | `make lint`                                                   | golangci-lint v2.14.0 + actionlint + `make sec` (gitleaks, govulncheck) |\n| Test (all)              | `make test`                                                   | gotestsum, `-p=1 -failfast -shuffle=on`, 15m timeout                   |\n| Test (one package)      | `make test package=gateway`                                   | Path relative to repo root; `exclude=` regex also supported            |\n| Test (single test)      | `go test -count 1 -run TestName ./gateway/...`                |                                                                        |\n| Warehouse integration   | `make test-warehouse package=warehouse/integrations/postgres` | `SLOW=1`, 30m timeout; needs Docker                                    |\n| Regenerate mocks        | `make mocks`                                                  | `go generate ./...` via mockgen v0.6.0; CI diffs the result            |\n| Regenerate protobuf     | `make proto`                                                  | Needs `protoc`; CI diffs the result                                    |\n| Regenerate OpenAPI docs | `make generate-openapi-spec`                                  | Needs Docker; run after editing `gateway/openapi.yaml`                 |\n\n<!-- AGENTS-GENERATED:END commands -->\n\n> If commands fail, verify against the Makefile or ask the user to update this file.\n\n## Response Style\n\n- Answer first, elaborate only if needed. No sycophantic openers.\n- For yes/no or status questions, lead with the answer.\n- Skip preamble. Match response length to task complexity.\n\n## Workflow\n\n1. **Before coding**: Read the nearest `AGENTS.md`, then the README/docs for the subsystem you're touching (see File\n   Map).\n2. **After each change**: Run the smallest relevant check (`make fmt` → `go build ./<pkg>/...` → single test).\n3. **Before committing**: Run `make lint` and tests for every package you touched; run `go mod tidy` if deps changed (CI\n   diffs `go.mod`).\n4. **Before claiming done**: Run verification and **show output as evidence** — never say \"tested\" or \"all green\"\n   without pasted command output in the same turn.\n\n## File Map\n\n<!-- AGENTS-GENERATED:START filemap -->\n\n```\nmain.go                     Entry point: signal handling, config init, launches runner/\nrunner/                     Bootstrap: stats init, service orchestration\napp/                        App interface, enterprise feature registry\napp/apphandlers/            Per-mode startup wiring (EMBEDDED / GATEWAY / PROCESSOR)\ngateway/                    HTTP ingestion API (webhooks, auth, throttling, openapi.yaml)\nprocessor/                  Core pipeline: transformations, enrichment, bot detection\nrouter/                     Per-destination event delivery\nrouter/batchrouter/         Batch + async destinations (see asyncdestinationmanager/README.md)\njobsdb/                     PostgreSQL-backed job queue; dataset rotation, migrations\nwarehouse/                  Warehouse loading; backends in warehouse/integrations/\nbackend-config/             Workspace config fetch/cache from control plane; pub-sub\nservices/                   Shared services: OAuth (see services/oauth/README.md), debuggers, rsources\nenterprise/                 Enterprise-only: suppression, reporting, config env override\ninternal/                   Enrichers (geo, bot), drain-config, transformer client\ncmd/                        CLI tools: devtool (see cmd/devtool/README.md), rudder-cli, backupfilemigrator\nconfig/                     Config key constants and defaults\nproto/                      Protobuf definitions (regenerate with make proto)\nmocks/                      Generated mocks — never edit by hand, run make mocks\nintegration_test/           Docker-based end-to-end tests\ntesthelper/                 Reusable test fixtures: docker resources, backendconfigtest, transformertest\nregulation-worker/          GDPR/regulation compliance worker (separate binary)\nsuppression-backup-service/ Suppression data backup/export (separate binary + Dockerfile)\nsql/                        SQL migration files (golang-migrate) — never delete\n```\n\n<!-- AGENTS-GENERATED:END filemap -->\n\n## Golden Samples (follow these patterns)\n\n<!-- AGENTS-GENERATED:START golden-samples -->\n\n| For                                      | Reference                                              |\n|------------------------------------------|--------------------------------------------------------|\n| Adding an async/batch destination        | `router/batchrouter/asyncdestinationmanager/README.md` |\n| Warehouse staging pipeline changes       | `warehouse/.cursor/docs/staging-file-flow.md`          |\n| OAuth destination flows                  | `services/oauth/README.md`                             |\n| Gateway API contract                     | `gateway/openapi.yaml`                                 |\n| Dev tooling (etcd modes, sending events) | `cmd/devtool/README.md`                                |\n\n<!-- AGENTS-GENERATED:END golden-samples -->\n\n## Utilities (check before creating new)\n\n<!-- AGENTS-GENERATED:START utilities -->\n\n| Need                                                 | Use                                                    | Location                                                                      |\n|------------------------------------------------------|--------------------------------------------------------|-------------------------------------------------------------------------------|\n| JSON marshal/unmarshal                               | `jsonrs`                                               | `github.com/rudderlabs/rudder-go-kit/jsonrs` (linter forbids `encoding/json`) |\n| Config values (env/file/hot-reload)                  | `config`                                               | `github.com/rudderlabs/rudder-go-kit/config`                                  |\n| Structured logging                                   | `logger` non-sugared (`Infon`, `Errorn`, typed fields) | `github.com/rudderlabs/rudder-go-kit/logger`                                  |\n| Error fields in logs                                 | `obskit.Error(err)`                                    | `github.com/rudderlabs/rudder-observability-kit/go/labels`                    |\n| Metrics                                              | `stats.NewTaggedStat`                                  | `github.com/rudderlabs/rudder-go-kit/stats`                                   |\n| Goroutine lifecycle                                  | `errgroup`                                             | `golang.org/x/sync/errgroup`                                                  |\n| Docker test resources (postgres, etcd, transformer…) | testhelper packages                                    | `testhelper/`, `github.com/rudderlabs/rudder-go-kit/testhelper/docker`        |\n\n<!-- AGENTS-GENERATED:END utilities -->\n\n## Heuristics (quick decisions)\n\n<!-- AGENTS-GENERATED:START heuristics -->\n\n| When                                   | Do                                                                                                                         |\n|----------------------------------------|----------------------------------------------------------------------------------------------------------------------------|\n| Async assertion in tests               | `require.Eventually` — never `time.Sleep`; return bool only inside the callback                                            |\n| Touching an interface with a mock      | Regenerate with `make mocks` and commit the diff                                                                           |\n| Editing `proto/**/*.proto`             | Run `make proto` and commit generated files                                                                                |\n| Editing `gateway/openapi.yaml`         | Validate + `make generate-openapi-spec`, commit output                                                                     |\n| Adding a warehouse integration package | Add it to the `warehouse-integration` matrix in `.github/workflows/tests.yaml` (matrixchecker in `make fmt` enforces this) |\n| Adding dependency                      | Ask first — then `go mod tidy` (CI diffs go.mod); no pseudo-version `rudderlabs` deps                                      |\n| Unsure about pattern                   | Check Golden Samples above                                                                                                 |\n\n<!-- AGENTS-GENERATED:END heuristics -->\n\n## Repository Settings\n\n<!-- AGENTS-GENERATED:START repo-settings -->\n\n- Default branch: `master`; release branches: `release/*`. Releases via release-please.\n- PR titles must be conventional commits (enforced by semantic-pr workflow). Allowed types:\n  `fix feat chore refactor exp doc test`. Optional scopes:\n  `core multi-tenant tooling gateway jobsdb warehouse processor router batchrouter destination startup shutdown ci`.\n  Subject must not start with an uppercase letter.\n\n<!-- AGENTS-GENERATED:END repo-settings -->\n\n<!-- AGENTS-GENERATED:START ci-rules -->\n\n### CI Quality Gates (`.github/workflows/verify.yml`, `tests.yaml`)\n\n- `go mod tidy` must produce no diff.\n- `make mocks`, `make proto`, `make fmt`, `make generate-openapi-spec` must each produce no diff.\n- golangci-lint (`.golangci.yml`): depguard, forbidigo, gosec, bodyclose, nilerr, and more.\n- Unit tests run per-package with coverage; integration tests run against Docker (oss + enterprise matrices).\n\n<!-- AGENTS-GENERATED:END ci-rules -->\n\n## Key Decisions\n\n<!-- AGENTS-GENERATED:START key-decisions -->\n\n- Job queue is PostgreSQL (`jobsdb`) with dataset rotation — not a message broker.\n- One binary, three modes via `APP_TYPE` env: `EMBEDDED` (default), `GATEWAY`, `PROCESSOR` (`app/apphandlers/setup.go`).\n- Enterprise features live in `enterprise/` behind `ENTERPRISE_TOKEN`; OSS build must keep working without it.\n- All JSON goes through `jsonrs` (pluggable implementation), enforced by linter.\n\n<!-- AGENTS-GENERATED:END key-decisions -->\n\n## Boundaries\n\n### Always Do\n\n- Run `make fmt` and relevant tests before committing\n- Add tests for new code paths\n- Use conventional commit format: `type(scope): subject` (lowercase subject)\n- Use **atomic commits** (one logical change per commit)\n- **Show test output as evidence before claiming work is complete**\n- Wrap errors with context: `fmt.Errorf(\"starting server: %w\", err)` — active voice, no \"failed to\"\n- Pass `context.Context` as the first parameter; propagate cancellation\n\n### Ask First\n\n- Adding new dependencies\n- Modifying CI/CD configuration (`.github/workflows/`)\n- Changing public API contracts (`gateway/openapi.yaml`, `proto/`)\n- Running full integration test suites (they need Docker and take 30m+)\n- Repo-wide refactoring or rewrites\n\n### Never Do\n\n- Commit secrets or credentials (gitleaks runs in `make lint`)\n- Hand-edit generated files: `mocks/`, protobuf `*.pb.go`, `gateway/openapi/`\n- Push directly to `master` or `release/*` — open a PR\n- Delete SQL migration files under `sql/`\n- Use `encoding/json` (→ `jsonrs`), `github.com/gofrs/uuid` (→ `google/uuid`), `golang.org/x/exp/slices` (→ stdlib\n  `slices`), `aws-sdk-go` v1 (→ v2), `cenkalti/backoff` < v5 (→ v5) — all linter-enforced\n- Use `errors.As` — use `errors.AsType[T](err)`, which returns the typed value and an `ok` bool (linter-enforced)\n- Use sugared logger methods (`Logger.Info`, `Logger.Errorf`, …) — use `Infon`/`Errorn` with typed field constructors\n  and `obskit.Error(err)`\n- Write new tests with Ginkgo/Gomega: use plain `testing` + testify (`require`/`assert`). Existing Ginkgo suites are legacy; don't add new `_test.go` files that import `github.com/onsi/ginkgo` and try to avoid adding `Describe`/`It` blocks to existing ones.\n\n## Contributing (for AI agents)\n\n- **Comprehension**: Understand *why* a change is needed before submitting code; read the linked issue.\n- **Context**: Explain trade-offs in the PR description and link the issue it addresses (see `CONTRIBUTING.md`).\n- **Continuity**: Respond to review feedback; drive-by PRs without follow-up will be closed.\n\n## Terminology\n\n| Term          | Means                                                                                         |\n|---------------|-----------------------------------------------------------------------------------------------|\n| Gateway       | HTTP ingestion service; writes raw events to jobsdb                                           |\n| Processor     | Transforms/enriches events; routes them to router or batchrouter queues                       |\n| Router        | Streams events to cloud destinations one-by-one with retries                                  |\n| Batch router  | Batches events for warehouses and async destinations                                          |\n| jobsdb        | PostgreSQL-backed append-only job queue with dataset rotation                                 |\n| Transformer   | Separate JS service applying destination/user transformations (`internal/transformer-client`) |\n| Control plane | RudderStack hosted config service (`CONFIG_BACKEND_URL`); `backend-config/` syncs from it     |\n| Workspace     | Tenant unit; identified by `WORKSPACE_TOKEN`                                                  |\n| rsources      | Job-status/failed-records service for sources (`services/rsources`)                           |\n| RETL          | Reverse ETL — warehouse-to-destination pipelines                                              |\n\n## When instructions conflict\n\nThe nearest `AGENTS.md` wins. Explicit user prompts override files.\n","isInternal":false,"tokens":2995,"sizeBytes":15381},{"name":"batch.json","path":"cmd/devtool/commands/payloads/batch.json","rawUrl":"https://raw.githubusercontent.com/rudderlabs/rudder-server/HEAD/cmd/devtool/commands/payloads/batch.json","title":"Payloads Skill","category":"anthropic-skill","format":"json","content":"{\n  \"batch\": [\n    {\n      \"anonymousId\": \"{{.AnonymousId}}\",\n      \"channel\": \"android-sdk\",\n      \"context\": {\n        \"app\": {\n          \"build\": \"1\",\n          \"name\": \"RudderAndroidClient\",\n          \"namespace\": \"com.rudderlabs.android.sdk\",\n          \"version\": \"1.0\"\n        },\n        \"device\": {\n          \"id\": \"49e4bdd1c280bc00\",\n          \"manufacturer\": \"Google\",\n          \"model\": \"Android SDK built for x86\",\n          \"name\": \"generic_x86\"\n        },\n        \"locale\": \"en-US\",\n        \"network\": {\n          \"carrier\": \"Android\"\n        },\n        \"screen\": {\n          \"density\": 420,\n          \"height\": 1794,\n          \"width\": 1080\n        },\n        \"library\": {\n          \"name\": \"com.rudderstack.android.sdk.core\"\n        },\n        \"traits\": {\n          \"anonymousId\": \"{{.AnonymousId}}\"\n        },\n        \"user_agent\": \"Dalvik/2.1.0 (Linux; U; Android 9; Android SDK built for x86 Build/PSR1.180720.075)\"\n      },\n      \"event\": \"Demo Track\",\n      \"integrations\": {\n        \"All\": true\n      },\n      \"properties\": {\n        \"label\": \"Demo Label\",\n        \"category\": \"Demo Category\",\n        \"value\": 5,\n        \"testMap\": {\n          \"t1\": \"a\",\n          \"t2\": 4\n        },\n        \"floatVal\": 4.501,\n        \"testArray\": [\n          {\n            \"id\": \"elem1\",\n            \"value\": \"e1\"\n          },\n          {\n            \"id\": \"elem2\",\n            \"value\": \"e2\"\n          }\n        ]\n      },\n      \"type\": \"track\",\n      \"originalTimestamp\": \"{{.Timestamp}}\",\n      \"sentAt\": \"{{.Timestamp}}\"\n    }\n  ]\n}\n","frontmatter":{"batch":[{"anonymousId":"{{.AnonymousId}}","channel":"android-sdk","context":{"app":{"build":"1","name":"RudderAndroidClient","namespace":"com.rudderlabs.android.sdk","version":"1.0"},"device":{"id":"49e4bdd1c280bc00","manufacturer":"Google","model":"Android SDK built for x86","name":"generic_x86"},"locale":"en-US","network":{"carrier":"Android"},"screen":{"density":420,"height":1794,"width":1080},"library":{"name":"com.rudderstack.android.sdk.core"},"traits":{"anonymousId":"{{.AnonymousId}}"},"user_agent":"Dalvik/2.1.0 (Linux; U; Android 9; Android SDK built for x86 Build/PSR1.180720.075)"},"event":"Demo Track","integrations":{"All":true},"properties":{"label":"Demo Label","category":"Demo Category","value":5,"testMap":{"t1":"a","t2":4},"floatVal":4.501,"testArray":[{"id":"elem1","value":"e1"},{"id":"elem2","value":"e2"}]},"type":"track","originalTimestamp":"{{.Timestamp}}","sentAt":"{{.Timestamp}}"}]},"isInternal":false,"tokens":423,"sizeBytes":1543},{"name":"documentation.mdc","path":"warehouse/.cursor/rules/documentation.mdc","rawUrl":"https://raw.githubusercontent.com/rudderlabs/rudder-server/HEAD/warehouse/.cursor/rules/documentation.mdc","title":"Cursor Rule: documentation","category":"cursor-rule","format":"mdc","content":"---\ndescription: \nglobs: \nalwaysApply: false\n---\n# Documentation Guidelines for Docs Folder\n\nThis document provides guidelines for creating and updating documentation files in the `docs/` directory after implementing features or making significant changes.\n\n## When to Create Documentation\n\nCreate new documentation files when:\n- **Major flow implementations** that involve multiple components/layers\n- **Cross-cutting architectural changes** that affect how future work should be done\n- **Complex patterns** that will be repeated by other developers\n- **Integration points** between different subsystems\n\nUpdate existing documentation files when:\n- **Implementation details change** the documented flow\n- **New patterns emerge** that should be captured\n- **Common pitfalls are discovered** during implementation\n\n## Documentation Structure\n\n### Essential Sections\n\n1. **Brief Overview** - What the document covers in 1-2 sentences\n2. **Flow Architecture** - Clear description of data/control flow between components\n3. **Step-by-step Components** - Each layer/step explained concisely\n4. **Implementation Checklist** - Actionable steps for making similar changes\n5. **Key Concepts** - Important patterns or principles\n6. **Common Pitfalls** - Issues encountered during implementation\n7. **File Organization** - Quick reference for relevant locations\n\n### Optional Sections\n- **Reference Patterns** - If there are reusable patterns worth highlighting\n- **Backward Compatibility** - If relevant to the change type\n\n## Writing Principles\n\n### Be Concept-Focused, Not Code-Specific\n- ❌ **Avoid:** Specific method names, exact file paths, code snippets, struct field names\n- ✅ **Use:** Component roles, architectural patterns, responsibility boundaries\n- ✅ **Preserve:** Architectural component names that are part of the system design\n\n**What to Avoid (Implementation Details):**\n- ❌ \"Update `pingWarehouse()` method in `router/batchrouter/handle.go`\"\n- ❌ \"Modify the `StagingFile` struct in `internal/model/staging.go`\"\n- ❌ \"Call `repo.GetByWorkspaceID(workspaceID)`\"\n\n**What to Keep (Architectural Components):**\n- ✅ \"Set field value in batch router's warehouse notification\"\n- ✅ \"Batch router creates staging file payload after uploading to object storage\"\n- ✅ \"Warehouse client converts staging file to HTTP payload format\"\n- ✅ \"Calls warehouse API endpoint `POST /v1/process` to notify about staging files\"\n\n**Key Distinction:** Preserve named architectural components (batch router, warehouse client, warehouse API), API endpoints, and service contracts while avoiding implementation details (method names, file paths, struct fields).\n\n### Keep Examples Generic\n- ❌ **Avoid:** Detailed field examples that might become outdated\n- ✅ **Use:** General patterns or simple references to \"existing fields\"\n\n**Example:**\n- ❌ \"String from environment: Like instance ID, server name, pod ID\"\n- ✅ \"Look at existing staging file fields for implementation patterns\"\n\n### Focus on Architectural Boundaries\n- Emphasize **who is responsible** for what\n- Highlight **data flow direction** and transformation points\n- Document **responsibility separation** between components\n- Include **API endpoints and service contracts** that define integration points\n\n### Include Essential Architectural Information\n- ✅ **Service boundaries:** Component names and their responsibilities\n- ✅ **Integration contracts:** API endpoints, message formats, service protocols\n- ✅ **Data flow patterns:** How information moves between components\n- ✅ **Configuration points:** Where system behavior can be modified\n- ❌ **Implementation details:** Method names, variable names, file paths\n- ❌ **Code specifics:** Function signatures, class hierarchies, internal APIs\n\n### Use Timeless Language\n- ❌ **Avoid:** \"Currently\", \"at the moment\", version-specific details\n- ✅ **Use:** Present tense, architectural statements\n\n## Implementation Workflow\n\n### During Implementation\n1. **Take notes** on architectural insights and patterns discovered\n2. **Document pitfalls** encountered and how they were resolved\n3. **Track flow dependencies** between components\n4. **Note responsibility boundaries** that become clear\n\n### After Implementation\n1. **Create outline** based on the flow you implemented\n2. **Write concept-focused descriptions** of each component's role\n3. **Create actionable checklist** for similar future changes\n4. **Document common pitfalls** observed during implementation\n5. **Review for code-specific details** and generalize them\n\n### Before Finalizing\n1. **Remove implementation specifics** (method names, file paths, code snippets) while **preserving architectural component names**\n2. **Test readability** - would someone unfamiliar understand the flow?\n3. **Verify checklist completeness** - does it cover all necessary steps?\n4. **Check for redundancy** between sections\n\n## File Organization Strategy\n\n### Naming Convention\n- Use descriptive, hyphenated names: `staging-file-flow.md`\n- Focus on the **process or flow**, not specific features\n- Keep names **broad enough** to encompass related future changes\n- All documentation files use `.md` extension\n\n### File Scope\n- **One major flow per file** - don't combine unrelated processes\n- **Component-focused files** for complex subsystems\n- **Architectural flows and patterns** that help future development\n\n## Maintenance Strategy\n\n### Regular Reviews\n- **After major refactors** - verify documentation still reflects reality\n- **During onboarding** - check if documentation helps new developers\n- **When patterns change** - update to reflect new approaches\n\n### Update Triggers\n- **Flow architecture changes** affecting multiple components\n- **New responsibility boundaries** emerging\n- **Repeated questions** from team members about the same flow\n\n### Deprecation\n- **Remove outdated files** when flows no longer exist\n- **Merge related files** if they become too similar\n- **Archive rather than delete** if historical context is valuable\n\n## Quality Checklist\n\nBefore committing documentation:\n\n- [ ] **Flow is clear** without code knowledge\n- [ ] **Checklist is actionable** and complete  \n- [ ] **Examples are generic** and won't become outdated\n- [ ] **Pitfalls are architectural** not implementation-specific\n- [ ] **Integration points are documented** (API endpoints, service contracts)\n- [ ] **File organization is helpful** for quick reference\n- [ ] **Language is timeless** and concept-focused (preserves architectural component names, avoids implementation details)\n- [ ] **Redundancy is eliminated** between sections\n\n## Benefits of Good Documentation\n\n### For Current Implementation\n- **Validates understanding** of the architectural flow\n- **Identifies gaps** in the implementation approach\n- **Creates shared vocabulary** for the team\n\n### For Future Development\n- **Reduces onboarding time** for new team members\n- **Prevents repeated mistakes** through pitfall documentation\n- **Enables consistent patterns** across similar changes\n- **Speeds up similar implementations** with clear checklists\n\nThis approach ensures documentation remains valuable and current while capturing the essential architectural knowledge needed for future development.\n","frontmatter":{"description":null,"globs":null,"alwaysApply":false},"isInternal":false,"tokens":1468,"sizeBytes":7243},{"name":"plan-act-workflow.mdc","path":"warehouse/.cursor/rules/plan-act-workflow.mdc","rawUrl":"https://raw.githubusercontent.com/rudderlabs/rudder-server/HEAD/warehouse/.cursor/rules/plan-act-workflow.mdc","title":"Cursor Rule: plan-act-workflow","category":"cursor-rule","format":"mdc","content":"---\ndescription: \nglobs: \nalwaysApply: true\n---\n# 🚨 CRITICAL PLAN-ACT WORKFLOW RULE 🚨\n\n## ⚠️ MANDATORY REQUIREMENT FOR ALL DEVELOPMENT TASKS ⚠️\n\n**This is a CRITICAL rule that MUST be followed without exception when working on any development task in the warehouse directory.**\n\n## 🔄 TWO MODES OF OPERATION: PLAN → ACT\n\n### 📋 MODE 1: PLAN (Planning Phase)\n**In PLAN mode, you focus EXCLUSIVELY on planning and analysis. NO CODE IMPLEMENTATION is allowed.**\n\n### ⚡ MODE 2: ACT (Implementation Phase)  \n**In ACT mode, you execute the approved plan. NO NEW PLANNING or scope changes without returning to PLAN mode.**\n\n**🚫 CRITICAL RULE: You CANNOT be in both modes simultaneously. You must explicitly transition from PLAN → ACT.**\n\n---\n\n### RULE: COMPREHENSIVE PLANNING BEFORE IMPLEMENTATION\n\n### 📋 PLAN MODE REQUIREMENTS\n\n**At any step in PLAN mode, always ask the user for clarifications—even for minor uncertainties or assumptions—whenever needed. This applies to requirement gathering, planning, challenge identification, and documentation/approval.**\n\nComplete ALL of the following before transitioning to ACT mode:\n\n#### 0. 📝 REQUIREMENT GATHERING & CLARIFICATION\n- Begin by gathering requirements and understanding the user's goals, constraints, and expectations for the task.\n\n#### 1. 📋 COMPREHENSIVE PLAN\n- Break down task into actionable steps with dependencies and complexity estimates\n- Identify all affected components and define clear success criteria\n\n#### 2. 🔍 CHALLENGE IDENTIFICATION  \n- Technical risks (algorithms, performance, integration, edge cases)\n- Testing requirements (mocks, data, coverage strategy)\n- Compatibility and resource constraints (migrations, external dependencies)\n\n#### 3. 📝 DOCUMENTATION & APPROVAL\n- Document step-by-step approach with risk mitigation and rollback plan\n- **GET EXPLICIT APPROVAL** - ACT mode forbidden until plan is approved\n- **DECLARE TRANSITION**: \"Moving from PLAN mode to ACT mode\"\n\n### ⚡ ACT MODE REQUIREMENTS\n\nIn ACT mode, you MUST:\n\n#### 1. 🎯 EXECUTE THE APPROVED PLAN\n- Follow documented steps exactly, implement only what was planned\n- **DECLARE MODE**: \"Currently in ACT mode\"\n\n#### 2. 🚫 NO SCOPE CHANGES  \n- Any unexpected issues or new requirements require **RETURN TO PLAN MODE**\n- Track progress and report deviations immediately\n\n### 🚫 VIOLATIONS - STRICTLY PROHIBITED\n\n- **PLAN Mode**: Implementing code, skipping planning steps, proceeding without approval\n- **ACT Mode**: Changing scope without returning to PLAN, deviating from approved plan  \n- **Mode Mixing**: Operating in both modes, transitions without declarations\n\n### ✅ COMPLIANCE CHECKLIST\n\n#### PLAN Mode:\n- [ ] Declared \"Currently in PLAN mode\"\n- [ ] **Gathered requirements and clarified all uncertainties with the user (and sought clarifications at any step as needed)**\n- [ ] Completed comprehensive plan with steps, challenges, and risks\n- [ ] Received explicit approval  \n- [ ] **Declared transition**: \"Moving from PLAN mode to ACT mode\"\n\n#### ACT Mode:\n- [ ] Declared \"Currently in ACT mode\" \n- [ ] Following approved plan exactly\n- [ ] **If scope changes needed**: Return to PLAN mode first\n\n### 🎯 WHY THIS RULE EXISTS\n\n**Prevents costly mistakes** through upfront planning, **ensures focused execution** by mode separation, **reduces context switching**, and **maintains scope discipline**.\n\n---\n\n**Remember: The PLAN → ACT workflow creates mental clarity and prevents the costly mistake of \"planning while coding.\" This two-mode approach is non-negotiable for maintaining the quality and reliability of the warehouse codebase.** ","frontmatter":{"description":null,"globs":null,"alwaysApply":true},"isInternal":false,"tokens":827,"sizeBytes":3644},{"name":"testing.mdc","path":"warehouse/.cursor/rules/testing.mdc","rawUrl":"https://raw.githubusercontent.com/rudderlabs/rudder-server/HEAD/warehouse/.cursor/rules/testing.mdc","title":"Cursor Rule: testing","category":"cursor-rule","format":"mdc","content":"---\ndescription: Testing guidelines for the warehouse directory in RudderStack.\nglobs:\n  - \"**/*_test.go\"\nalwaysApply: true\n---\n\n# Warehouse Testing Guidelines\n\nThis document outlines the testing conventions and best practices for the `warehouse/` directory in the RudderStack server codebase.\n\n## Table of Contents\n\n- [Assertion Library](mdc:#assertion-library)\n- [Test Structure](mdc:#test-structure)\n- [Parallelization](mdc:#parallelization)\n- [Context Management](mdc:#context-management)\n- [Setup and Teardown](mdc:#setup-and-teardown)\n- [Database Testing](mdc:#database-testing)\n- [Mocking](mdc:#mocking)\n- [File Management](mdc:#file-management)\n- [Configuration](mdc:#configuration)\n- [Test Naming](mdc:#test-naming)\n- [Error Testing](mdc:#error-testing)\n- [Helper Patterns](mdc:#helper-patterns)\n- [Integration Test Patterns](mdc:#integration-test-patterns)\n- [Common Anti-patterns to Avoid](mdc:#common-anti-patterns-to-avoid)\n- [Example Test Structure](mdc:#example-test-structure)\n\n## Assertion Library\n\n**ALWAYS** use `github.com/stretchr/testify/require` for assertions in warehouse tests.\n\n- Prefer `require` over `assert` to fail fast on critical assertions\n- Use `require.NoError(t, err)` for error checking\n- Use `require.Equal(t, expected, actual)` for equality checks\n- Use `require.True(t, condition)` and `require.False(t, condition)` for boolean checks\n\n```go\nimport (\n    \"github.com/stretchr/testify/require\"\n)\n\nfunc TestExample(t *testing.T) {\n    result, err := someFunction()\n    require.NoError(t, err)\n    require.Equal(t, expected, result)\n}\n```\n\n## Test Structure\n\nUse **table-driven tests** for multiple scenarios:\n\n- Structure table-driven tests with `name`, input, and `expected` fields\n- Always use `t.Run(tc.name, func(t *testing.T) {})` for subtests\n- Group related subtests under a parent `t.Run(\"group name\", ...)` block for clarity and maintainability.\n- Include both positive and negative test cases\n\n```go\n// Table-driven tests for parameterized scenarios\nfunc TestWarehouseFunction(t *testing.T) {\n    testCases := []struct {\n        name     string\n        input    InputType\n        expected ExpectedType\n        wantErr  bool\n    }{\n        {\n            name:     \"successful case\",\n            input:    validInput,\n            expected: expectedOutput,\n            wantErr:  false,\n        },\n        {\n            name:    \"error case\",\n            input:   invalidInput,\n            wantErr: true,\n        },\n    }\n    \n    for _, tc := range testCases {\n        t.Run(tc.name, func(t *testing.T) {\n            // test implementation\n        })\n    }\n}\n\n// Grouped subtests for related functionality\nfunc TestWarehouseComponent(t *testing.T) {\n    t.Run(\"initialization\", func(t *testing.T) {\n        t.Run(\"valid configuration\", func(t *testing.T) { /* ... */ })\n        t.Run(\"invalid configuration\", func(t *testing.T) { /* ... */ })\n        t.Run(\"missing configuration\", func(t *testing.T) { /* ... */ })\n    })\n    \n    t.Run(\"data processing\", func(t *testing.T) {\n        t.Run(\"single record\", func(t *testing.T) { /* ... */ })\n        t.Run(\"batch processing\", func(t *testing.T) { /* ... */ })\n        t.Run(\"empty input\", func(t *testing.T) { /* ... */ })\n    })\n}\n```\n\n## Parallelization\n\n- Use `t.Parallel()` for tests that can run concurrently\n- Apply parallelization to both main tests and subtests where safe\n- Avoid parallelization for tests that modify shared resources\n\n```go\nfunc TestConcurrentFunction(t *testing.T) {\n    t.Parallel()\n    \n    for _, tc := range testCases {\n        t.Run(tc.name, func(t *testing.T) {\n            t.Parallel()\n            // test implementation\n        })\n    }\n}\n```\n\n## Context Management\n\n- Use `context.Background()` as the default context for most tests\n- Use `context.WithTimeout()` for tests with time constraints\n- Always pass context as the first parameter to functions under test\n\n```go\nfunc TestWithContext(t *testing.T) {\n    ctx := context.Background()\n    // or for timeouts:\n    ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n    defer cancel()\n    \n    result, err := functionUnderTest(ctx, input)\n    require.NoError(t, err)\n}\n```\n\n## Setup and Teardown\n\n- Use `t.Cleanup()` for resource cleanup (files, database connections, etc.)\n- Clean up temporary files with `require.NoError(t, os.Remove(filePath))`\n- Use `defer` for cleanup when `t.Cleanup()` is not sufficient\n- Create helper functions for complex test setup\n\n```go\nfunc TestWithCleanup(t *testing.T) {\n    tempFile, err := os.CreateTemp(\"\", \"test_*.txt\")\n    require.NoError(t, err)\n    \n    t.Cleanup(func() {\n        require.NoError(t, os.Remove(tempFile.Name()))\n    })\n    \n    // test implementation\n}\n```\n\n## Database Testing\n\n- Use `dockertest` for PostgreSQL integration tests\n- Set up database migrations with `migrator.Migrator`\n- Use `sqlmiddleware.New()` for database connections\n- Clean up database resources properly in `t.Cleanup()`\n\n```go\nfunc TestDatabaseIntegration(t *testing.T) {\n    pool, err := dockertest.NewPool(\"\")\n    require.NoError(t, err)\n    \n    pgResource, err := postgres.Setup(pool, t)\n    require.NoError(t, err)\n    \n    err = (&migrator.Migrator{\n        Handle:          pgResource.DB,\n        MigrationsTable: \"wh_schema_migrations\",\n    }).Migrate(\"warehouse\")\n    require.NoError(t, err)\n    \n    db := sqlmiddleware.New(pgResource.DB)\n    \n    // test implementation\n}\n```\n\n## Mocking\n\n- Use `go.uber.org/mock/gomock` for interface mocking\n- Create mock expectations with clear `.EXPECT()` calls\n- Use `gomock.NewController(t)` for mock controller setup\n- Place mock generation comments: `//go:generate go run go.uber.org/mock/mockgen`\n- For error path testing, prefer extending mocks with error fields or behaviors rather than creating many separate mock types.\n\n```go\ntype mockRepository struct {\n    data map[string]interface{}\n    err  error\n}\n\nfunc (m *mockRepository) Get(key string) (interface{}, error) {\n    if m.err != nil {\n        return nil, m.err\n    }\n    return m.data[key], nil\n}\n\n// Usage in tests:\nsuccessMock := &mockRepository{data: map[string]interface{}{\"key\": \"value\"}}\nerrorMock := &mockRepository{err: errors.New(\"connection failed\")}\n```\n\n## File Management\n\n- Create temporary files with `os.CreateTemp()` or `t.TempDir()`\n- Always clean up files with `t.Cleanup(func() { require.NoError(t, os.Remove(fileName)) })`\n- Use proper file handling patterns for testing file operations\n- Test both successful file operations and error cases\n\n```go\nfunc TestFileOperations(t *testing.T) {\n    tempDir := t.TempDir()\n    \n    tempFile, err := os.CreateTemp(tempDir, \"test_*.json\")\n    require.NoError(t, err)\n    \n    t.Cleanup(func() {\n        require.NoError(t, tempFile.Close())\n    })\n    \n    // test file operations\n}\n```\n\n## Configuration\n\n- Use `config.New()` for test configuration\n- Override config values with `c.Set(key, value)` for test scenarios\n- Use environment variable overrides when testing config behavior\n- Test both default and custom configuration values\n\n```go\nfunc TestConfiguration(t *testing.T) {\n    c := config.New()\n    c.Set(\"Warehouse.testKey\", \"testValue\")\n    \n    // test with configuration\n}\n```\n\n## Test Naming\n\n- Use descriptive test function names: `TestFunctionName_Scenario`\n- Use underscores to separate components in test names\n- Include the component being tested in the function name\n- Use clear, descriptive names for table-driven test cases\n\n```go\nfunc TestWarehouse_GetBoolDestinationConfig(t *testing.T) { /* ... */ }\nfunc TestLoadFileGenerator_GetLoadFilePrefix(t *testing.T) { /* ... */ }\nfunc TestStagingFileRepo_GetPending(t *testing.T) { /* ... */ }\n```\n\n## Error Testing\n\n- Test both success and error scenarios\n- Use `require.Error(t, err)` for expected errors\n- Use `require.ErrorIs(t, err, expectedError)` for specific error types\n- Use `require.EqualError(t, err, expectedMessage)` for exact error messages\n- For fallback or multi-source logic, ensure tests cover all branches, including \"no data,\" \"empty but present,\" and error propagation.\n\n```go\nt.Run(\"data retrieval with fallback\", func(t *testing.T) {\n    t.Run(\"primary source succeeds\", func(t *testing.T) { /* ... */ })\n    t.Run(\"primary source fails, fallback succeeds\", func(t *testing.T) { /* ... */ })\n    t.Run(\"both primary and fallback fail\", func(t *testing.T) { /* ... */ })\n    t.Run(\"primary source returns empty, no fallback\", func(t *testing.T) { /* ... */ })\n})\n```\n\n## Helper Patterns\n\n- Create test helper functions for complex setups\n- Use `t.Helper()` in helper functions to get correct line numbers\n- Extract common test data into helper functions or constants\n- Create factory functions for test models and objects\n\n```go\nfunc createTestWarehouse(t *testing.T) model.Warehouse {\n    t.Helper()\n    \n    return model.Warehouse{\n        WorkspaceID: \"test-workspace\",\n        Source: backendconfig.SourceT{\n            ID: \"test-source\",\n        },\n        Destination: backendconfig.DestinationT{\n            ID: \"test-destination\",\n        },\n    }\n}\n\nfunc setupTestDatabase(t *testing.T) (*sql.DB, func()) {\n    t.Helper()\n    \n    // setup logic\n    \n    cleanup := func() {\n        // cleanup logic\n    }\n    \n    return db, cleanup\n}\n```\n\n## Integration Test Patterns\n\n- Use docker-compose for complex integration test setups\n- Set up real warehouse connections for integration tests\n- Use conditional skips: `if os.Getenv(\"SLOW\") != \"1\" { t.Skip() }`\n- Test end-to-end workflows with real data\n\n```go\nfunc TestIntegration(t *testing.T) {\n    if os.Getenv(\"SLOW\") != \"1\" {\n        t.Skip(\"Skipping integration tests. Add 'SLOW=1' env var to run test.\")\n    }\n    \n    // integration test implementation\n}\n```\n\n## Common Anti-patterns to Avoid\n\n- ❌ Don't use `testing.T.Fatal()` or `t.Fatalf()` - use `require` instead\n- ❌ Don't ignore cleanup errors - always check with `require.NoError()`\n- ❌ Don't create tests without cleanup for temporary resources\n- ❌ Don't use sleep for timing - use proper synchronization or timeouts\n- ❌ Don't test implementation details - focus on behavior\n\n## Example Test Structure\n\nHere's a complete example following all the guidelines:\n\n```go\npackage warehouse_test\n\nimport (\n    \"context\"\n    \"os\"\n    \"testing\"\n    \"time\"\n\n    \"github.com/stretchr/testify/require\"\n    \"go.uber.org/mock/gomock\"\n\n    \"github.com/rudderlabs/rudder-go-kit/config\"\n    \"github.com/rudderlabs/rudder-server/warehouse/internal/model\"\n)\n\nfunc TestWarehouseFunction_Scenario(t *testing.T) {\n    testCases := []struct {\n        name     string\n        input    InputType\n        expected ExpectedType\n        wantErr  bool\n    }{\n        {\n            name:     \"successful case\",\n            input:    validInput,\n            expected: expectedOutput,\n            wantErr:  false,\n        },\n        {\n            name:    \"error case\",\n            input:   invalidInput,\n            wantErr: true,\n        },\n    }\n    \n    for _, tc := range testCases {\n        t.Run(tc.name, func(t *testing.T) {\n            t.Parallel()\n            \n            // Setup\n            ctx := context.Background()\n            ctrl := gomock.NewController(t)\n            defer ctrl.Finish()\n            \n            tempFile, err := os.CreateTemp(\"\", \"test_*.json\")\n            require.NoError(t, err)\n            \n            t.Cleanup(func() {\n                require.NoError(t, os.Remove(tempFile.Name()))\n            })\n            \n            // Test execution\n            result, err := functionUnderTest(ctx, tc.input)\n            \n            // Assertions\n            if tc.wantErr {\n                require.Error(t, err)\n                return\n            }\n            \n            require.NoError(t, err)\n            require.Equal(t, tc.expected, result)\n        })\n    }\n}\n```\n\n## Reference\n\nThis document is based on analysis of existing test patterns in the warehouse directory. For questions or suggestions about these guidelines, please refer to the test files in the warehouse directory for examples of these patterns in practice. ","frontmatter":{"description":"Testing guidelines for the warehouse directory in RudderStack.","globs":["**/*_test.go"],"alwaysApply":true},"isInternal":false,"tokens":2815,"sizeBytes":12070}],"systemPromptSnippet":"<yakaai_skills repo=\"rudderlabs/rudder-server\">\n<!-- File: AGENTS.md (Tokens: ~2995 | Category: root-instruction) -->\n<!-- FOR AI AGENTS - Human readability is a side effect, not a goal -->\n<!-- Managed by agent: keep sections and order; edit content, not structure -->\n<!-- Generated with the agent-rules skill v3.14.1 — https://github.com/netresearch/agent-rules-skill -->\n<!-- Last updated: 2026-08-18 | Last verified: 2026-08-18 -->\n\n# AGENTS.md\n\n**Precedence:** the **closest `AGENTS.md`** to the files you're changing wins. Root holds global defaults only.\n\nRudderStack Server — open-source Customer Data Platform (CDP). Go 1.26 monolith: events flow Gateway → Processor →\nRouter/BatchRouter → 90+ destinations and warehouses. Segment API-compatible. Jobs are queued in PostgreSQL (`jobsdb`).\n\n## Commands\n\n> Source: Makefile + `.github/workflows/verify.yml` / `tests.yaml` — CI runs these exact targets\n\n<!-- AGENTS-GENERATED:START commands -->\n\n| Task                    | Command                                                       | Notes                                                                  |\n|-------------------------|---------------------------------------------------------------|------------------------------------------------------------------------|\n| Build                   | `make build`                                                  | Also builds `wait-for-go` and `regulation-worker`                      |\n| Run                     | `make run` (`go run main.go`)                                 | `make run-mt` for multi-tenant via devtool+etcd                        |\n| Format                  | `make fmt`                                                    | gofumpt + gci + matrixchecker; CI fails on `git diff` after this       |\n| Lint                    | `make lint`                                                   | golangci-lint v2.14.0 + actionlint + `make sec` (gitleaks, govulncheck) |\n| Test (all)              | `make test`                                                   | gotestsum, `-p=1 -failfast -shuffle=on`, 15m timeout                   |\n| Test (one package)      | `make test package=gateway`                                   | Path relative to repo root; `exclude=` regex also supported            |\n| Test (single test)      | `go test -count 1 -run TestName ./gateway/...`                |                                                                        |\n| Warehouse integration   | `make test-warehouse package=warehouse/integrations/postgres` | `SLOW=1`, 30m timeout; needs Docker                                    |\n| Regenerate mocks        | `make mocks`                                                  | `go generate ./...` via mockgen v0.6.0; CI diffs the result            |\n| Regenerate protobuf     | `make proto`                                                  | Needs `protoc`; CI diffs the result                                    |\n| Regenerate OpenAPI docs | `make generate-openapi-spec`                                  | Needs Docker; run after editing `gateway/openapi.yaml`                 |\n\n<!-- AGENTS-GENERATED:END commands -->\n\n> If commands fail, verify against the Makefile or ask the user to update this file.\n\n## Response Style\n\n- Answer first, elaborate only if needed. No sycophantic openers.\n- For yes/no or status questions, lead with the answer.\n- Skip preamble. Match response length to task complexity.\n\n## Workflow\n\n1. **Before coding**: Read the nearest `AGENTS.md`, then the README/docs for the subsystem you're touching (see File\n   Map).\n2. **After each change**: Run the smallest relevant check (`make fmt` → `go build ./<pkg>/...` → single test).\n3. **Before committing**: Run `make lint` and tests for every package you touched; run `go mod tidy` if deps changed (CI\n   diffs `go.mod`).\n4. **Before claiming done**: Run verification and **show output as evidence** — never say \"tested\" or \"all green\"\n   without pasted command output in the same turn.\n\n## File Map\n\n<!-- AGENTS-GENERATED:START filemap -->\n\n```\nmain.go                     Entry point: signal handling, config init, launches runner/\nrunner/                     Bootstrap: stats init, service orchestration\napp/                        App interface, enterprise feature registry\napp/apphandlers/            Per-mode startup wiring (EMBEDDED / GATEWAY / PROCESSOR)\ngateway/                    HTTP ingestion API (webhooks, auth, throttling, openapi.yaml)\nprocessor/                  Core pipeline: transformations, enrichment, bot detection\nrouter/                     Per-destination event delivery\nrouter/batchrouter/         Batch + async destinations (see asyncdestinationmanager/README.md)\njobsdb/                     PostgreSQL-backed job queue; dataset rotation, migrations\nwarehouse/                  Warehouse loading; backends in warehouse/integrations/\nbackend-config/             Workspace config fetch/cache from control plane; pub-sub\nservices/                   Shared services: OAuth (see services/oauth/README.md), debuggers, rsources\nenterprise/                 Enterprise-only: suppression, reporting, config env override\ninternal/                   Enrichers (geo, bot), drain-config, transformer client\ncmd/                        CLI tools: devtool (see cmd/devtool/README.md), rudder-cli, backupfilemigrator\nconfig/                     Config key constants and defaults\nproto/                      Protobuf definitions (regenerate with make proto)\nmocks/                      Generated mocks — never edit by hand, run make mocks\nintegration_test/           Docker-based end-to-end tests\ntesthelper/                 Reusable test fixtures: docker resources, backendconfigtest, transformertest\nregulation-worker/          GDPR/regulation compliance worker (separate binary)\nsuppression-backup-service/ Suppression data backup/export (separate binary + Dockerfile)\nsql/                        SQL migration files (golang-migrate) — never delete\n```\n\n<!-- AGENTS-GENERATED:END filemap -->\n\n## Golden Samples (follow these patterns)\n\n<!-- AGENTS-GENERATED:START golden-samples -->\n\n| For                                      | Reference                                              |\n|------------------------------------------|--------------------------------------------------------|\n| Adding an async/batch destination        | `router/batchrouter/asyncdestinationmanager/README.md` |\n| Warehouse staging pipeline changes       | `warehouse/.cursor/docs/staging-file-flow.md`          |\n| OAuth destination flows                  | `services/oauth/README.md`                             |\n| Gateway API contract                     | `gateway/openapi.yaml`                                 |\n| Dev tooling (etcd modes, sending events) | `cmd/devtool/README.md`                                |\n\n<!-- AGENTS-GENERATED:END golden-samples -->\n\n## Utilities (check before creating new)\n\n<!-- AGENTS-GENERATED:START utilities -->\n\n| Need                                                 | Use                                                    | Location                                                                      |\n|------------------------------------------------------|--------------------------------------------------------|-------------------------------------------------------------------------------|\n| JSON marshal/unmarshal                               | `jsonrs`                                               | `github.com/rudderlabs/rudder-go-kit/jsonrs` (linter forbids `encoding/json`) |\n| Config values (env/file/hot-reload)                  | `config`                                               | `github.com/rudderlabs/rudder-go-kit/config`                                  |\n| Structured logging                                   | `logger` non-sugared (`Infon`, `Errorn`, typed fields) | `github.com/rudderlabs/rudder-go-kit/logger`                                  |\n| Error fields in logs                                 | `obskit.Error(err)`                                    | `github.com/rudderlabs/rudder-observability-kit/go/labels`                    |\n| Metrics                                              | `stats.NewTaggedStat`                                  | `github.com/rudderlabs/rudder-go-kit/stats`                                   |\n| Goroutine lifecycle                                  | `errgroup`                                             | `golang.org/x/sync/errgroup`                                                  |\n| Docker test resources (postgres, etcd, transformer…) | testhelper packages                                    | `testhelper/`, `github.com/rudderlabs/rudder-go-kit/testhelper/docker`        |\n\n<!-- AGENTS-GENERATED:END utilities -->\n\n## Heuristics (quick decisions)\n\n<!-- AGENTS-GENERATED:START heuristics -->\n\n| When                                   | Do                                                                                                                         |\n|----------------------------------------|----------------------------------------------------------------------------------------------------------------------------|\n| Async assertion in tests               | `require.Eventually` — never `time.Sleep`; return bool only inside the callback                                            |\n| Touching an interface with a mock      | Regenerate with `make mocks` and commit the diff                                                                           |\n| Editing `proto/**/*.proto`             | Run `make proto` and commit generated files                                                                                |\n| Editing `gateway/openapi.yaml`         | Validate + `make generate-openapi-spec`, commit output                                                                     |\n| Adding a warehouse integration package | Add it to the `warehouse-integration` matrix in `.github/workflows/tests.yaml` (matrixchecker in `make fmt` enforces this) |\n| Adding dependency                      | Ask first — then `go mod tidy` (CI diffs go.mod); no pseudo-version `rudderlabs` deps                                      |\n| Unsure about pattern                   | Check Golden Samples above                                                                                                 |\n\n<!-- AGENTS-GENERATED:END heuristics -->\n\n## Repository Settings\n\n<!-- AGENTS-GENERATED:START repo-settings -->\n\n- Default branch: `master`; release branches: `release/*`. Releases via release-please.\n- PR titles must be conventional commits (enforced by semantic-pr workflow). Allowed types:\n  `fix feat chore refactor exp doc test`. Optional scopes:\n  `core multi-tenant tooling gateway jobsdb warehouse processor router batchrouter destination startup shutdown ci`.\n  Subject must not start with an uppercase letter.\n\n<!-- AGENTS-GENERATED:END repo-settings -->\n\n<!-- AGENTS-GENERATED:START ci-rules -->\n\n### CI Quality Gates (`.github/workflows/verify.yml`, `tests.yaml`)\n\n- `go mod tidy` must produce no diff.\n- `make mocks`, `make proto`, `make fmt`, `make generate-openapi-spec` must each produce no diff.\n- golangci-lint (`.golangci.yml`): depguard, forbidigo, gosec, bodyclose, nilerr, and more.\n- Unit tests run per-package with coverage; integration tests run against Docker (oss + enterprise matrices).\n\n<!-- AGENTS-GENERATED:END ci-rules -->\n\n## Key Decisions\n\n<!-- AGENTS-GENERATED:START key-decisions -->\n\n- Job queue is PostgreSQL (`jobsdb`) with dataset rotation — not a message broker.\n- One binary, three modes via `APP_TYPE` env: `EMBEDDED` (default), `GATEWAY`, `PROCESSOR` (`app/apphandlers/setup.go`).\n- Enterprise features live in `enterprise/` behind `ENTERPRISE_TOKEN`; OSS build must keep working without it.\n- All JSON goes through `jsonrs` (pluggable implementation), enforced by linter.\n\n<!-- AGENTS-GENERATED:END key-decisions -->\n\n## Boundaries\n\n### Always Do\n\n- Run `make fmt` and relevant tests before committing\n- Add tests for new code paths\n- Use conventional commit format: `type(scope): subject` (lowercase subject)\n- Use **atomic commits** (one logical change per commit)\n- **Show test output as evidence before claiming work is complete**\n- Wrap errors with context: `fmt.Errorf(\"starting server: %w\", err)` — active voice, no \"failed to\"\n- Pass `context.Context` as the first parameter; propagate cancellation\n\n### Ask First\n\n- Adding new dependencies\n- Modifying CI/CD configuration (`.github/workflows/`)\n- Changing public API contracts (`gateway/openapi.yaml`, `proto/`)\n- Running full integration test suites (they need Docker and take 30m+)\n- Repo-wide refactoring or rewrites\n\n### Never Do\n\n- Commit secrets or credentials (gitleaks runs in `make lint`)\n- Hand-edit generated files: `mocks/`, protobuf `*.pb.go`, `gateway/openapi/`\n- Push directly to `master` or `release/*` — open a PR\n- Delete SQL migration files under `sql/`\n- Use `encoding/json` (→ `jsonrs`), `github.com/gofrs/uuid` (→ `google/uuid`), `golang.org/x/exp/slices` (→ stdlib\n  `slices`), `aws-sdk-go` v1 (→ v2), `cenkalti/backoff` < v5 (→ v5) — all linter-enforced\n- Use `errors.As` — use `errors.AsType[T](err)`, which returns the typed value and an `ok` bool (linter-enforced)\n- Use sugared logger methods (`Logger.Info`, `Logger.Errorf`, …) — use `Infon`/`Errorn` with typed field constructors\n  and `obskit.Error(err)`\n- Write new tests with Ginkgo/Gomega: use plain `testing` + testify (`require`/`assert`). Existing Ginkgo suites are legacy; don't add new `_test.go` files that import `github.com/onsi/ginkgo` and try to avoid adding `Describe`/`It` blocks to existing ones.\n\n## Contributing (for AI agents)\n\n- **Comprehension**: Understand *why* a change is needed before submitting code; read the linked issue.\n- **Context**: Explain trade-offs in the PR description and link the issue it addresses (see `CONTRIBUTING.md`).\n- **Continuity**: Respond to review feedback; drive-by PRs without follow-up will be closed.\n\n## Terminology\n\n| Term          | Means                                                                                         |\n|---------------|-----------------------------------------------------------------------------------------------|\n| Gateway       | HTTP ingestion service; writes raw events to jobsdb                                           |\n| Processor     | Transforms/enriches events; routes them to router or batchrouter queues                       |\n| Router        | Streams events to cloud destinations one-by-one with retries                                  |\n| Batch router  | Batches events for warehouses and async destinations                                          |\n| jobsdb        | PostgreSQL-backed append-only job queue with dataset rotation                                 |\n| Transformer   | Separate JS service applying destination/user transformations (`internal/transformer-client`) |\n| Control plane | RudderStack hosted config service (`CONFIG_BACKEND_URL`); `backend-config/` syncs from it     |\n| Workspace     | Tenant unit; identified by `WORKSPACE_TOKEN`                                                  |\n| rsources      | Job-status/failed-records service for sources (`services/rsources`)                           |\n| RETL          | Reverse ETL — warehouse-to-destination pipelines                                              |\n\n## When instructions conflict\n\nThe nearest `AGENTS.md` wins. Explicit user prompts override files.\n\n<!-- File: cmd/devtool/commands/payloads/batch.json (Tokens: ~423 | Category: anthropic-skill) -->\n{\n  \"batch\": [\n    {\n      \"anonymousId\": \"{{.AnonymousId}}\",\n      \"channel\": \"android-sdk\",\n      \"context\": {\n        \"app\": {\n          \"build\": \"1\",\n          \"name\": \"RudderAndroidClient\",\n          \"namespace\": \"com.rudderlabs.android.sdk\",\n          \"version\": \"1.0\"\n        },\n        \"device\": {\n          \"id\": \"49e4bdd1c280bc00\",\n          \"manufacturer\": \"Google\",\n          \"model\": \"Android SDK built for x86\",\n          \"name\": \"generic_x86\"\n        },\n        \"locale\": \"en-US\",\n        \"network\": {\n          \"carrier\": \"Android\"\n        },\n        \"screen\": {\n          \"density\": 420,\n          \"height\": 1794,\n          \"width\": 1080\n        },\n        \"library\": {\n          \"name\": \"com.rudderstack.android.sdk.core\"\n        },\n        \"traits\": {\n          \"anonymousId\": \"{{.AnonymousId}}\"\n        },\n        \"user_agent\": \"Dalvik/2.1.0 (Linux; U; Android 9; Android SDK built for x86 Build/PSR1.180720.075)\"\n      },\n      \"event\": \"Demo Track\",\n      \"integrations\": {\n        \"All\": true\n      },\n      \"properties\": {\n        \"label\": \"Demo Label\",\n        \"category\": \"Demo Category\",\n        \"value\": 5,\n        \"testMap\": {\n          \"t1\": \"a\",\n          \"t2\": 4\n        },\n        \"floatVal\": 4.501,\n        \"testArray\": [\n          {\n            \"id\": \"elem1\",\n            \"value\": \"e1\"\n          },\n          {\n            \"id\": \"elem2\",\n            \"value\": \"e2\"\n          }\n        ]\n      },\n      \"type\": \"track\",\n      \"originalTimestamp\": \"{{.Timestamp}}\",\n      \"sentAt\": \"{{.Timestamp}}\"\n    }\n  ]\n}\n\n<!-- File: warehouse/.cursor/rules/documentation.mdc (Tokens: ~1468 | Category: cursor-rule) -->\n---\ndescription: \nglobs: \nalwaysApply: false\n---\n# Documentation Guidelines for Docs Folder\n\nThis document provides guidelines for creating and updating documentation files in the `docs/` directory after implementing features or making significant changes.\n\n## When to Create Documentation\n\nCreate new documentation files when:\n- **Major flow implementations** that involve multiple components/layers\n- **Cross-cutting architectural changes** that affect how future work should be done\n- **Complex patterns** that will be repeated by other developers\n- **Integration points** between different subsystems\n\nUpdate existing documentation files when:\n- **Implementation details change** the documented flow\n- **New patterns emerge** that should be captured\n- **Common pitfalls are discovered** during implementation\n\n## Documentation Structure\n\n### Essential Sections\n\n1. **Brief Overview** - What the document covers in 1-2 sentences\n2. **Flow Architecture** - Clear description of data/control flow between components\n3. **Step-by-step Components** - Each layer/step explained concisely\n4. **Implementation Checklist** - Actionable steps for making similar changes\n5. **Key Concepts** - Important patterns or principles\n6. **Common Pitfalls** - Issues encountered during implementation\n7. **File Organization** - Quick reference for relevant locations\n\n### Optional Sections\n- **Reference Patterns** - If there are reusable patterns worth highlighting\n- **Backward Compatibility** - If relevant to the change type\n\n## Writing Principles\n\n### Be Concept-Focused, Not Code-Specific\n- ❌ **Avoid:** Specific method names, exact file paths, code snippets, struct field names\n- ✅ **Use:** Component roles, architectural patterns, responsibility boundaries\n- ✅ **Preserve:** Architectural component names that are part of the system design\n\n**What to Avoid (Implementation Details):**\n- ❌ \"Update `pingWarehouse()` method in `router/batchrouter/handle.go`\"\n- ❌ \"Modify the `StagingFile` struct in `internal/model/staging.go`\"\n- ❌ \"Call `repo.GetByWorkspaceID(workspaceID)`\"\n\n**What to Keep (Architectural Components):**\n- ✅ \"Set field value in batch router's warehouse notification\"\n- ✅ \"Batch router creates staging file payload after uploading to object storage\"\n- ✅ \"Warehouse client converts staging file to HTTP payload format\"\n- ✅ \"Calls warehouse API endpoint `POST /v1/process` to notify about staging files\"\n\n**Key Distinction:** Preserve named architectural components (batch router, warehouse client, warehouse API), API endpoints, and service contracts while avoiding implementation details (method names, file paths, struct fields).\n\n### Keep Examples Generic\n- ❌ **Avoid:** Detailed field examples that might become outdated\n- ✅ **Use:** General patterns or simple references to \"existing fields\"\n\n**Example:**\n- ❌ \"String from environment: Like instance ID, server name, pod ID\"\n- ✅ \"Look at existing staging file fields for implementation patterns\"\n\n### Focus on Architectural Boundaries\n- Emphasize **who is responsible** for what\n- Highlight **data flow direction** and transformation points\n- Document **responsibility separation** between components\n- Include **API endpoints and service contracts** that define integration points\n\n### Include Essential Architectural Information\n- ✅ **Service boundaries:** Component names and their responsibilities\n- ✅ **Integration contracts:** API endpoints, message formats, service protocols\n- ✅ **Data flow patterns:** How information moves between components\n- ✅ **Configuration points:** Where system behavior can be modified\n- ❌ **Implementation details:** Method names, variable names, file paths\n- ❌ **Code specifics:** Function signatures, class hierarchies, internal APIs\n\n### Use Timeless Language\n- ❌ **Avoid:** \"Currently\", \"at the moment\", version-specific details\n- ✅ **Use:** Present tense, architectural statements\n\n## Implementation Workflow\n\n### During Implementation\n1. **Take notes** on architectural insights and patterns discovered\n2. **Document pitfalls** encountered and how they were resolved\n3. **Track flow dependencies** between components\n4. **Note responsibility boundaries** that become clear\n\n### After Implementation\n1. **Create outline** based on the flow you implemented\n2. **Write concept-focused descriptions** of each component's role\n3. **Create actionable checklist** for similar future changes\n4. **Document common pitfalls** observed during implementation\n5. **Review for code-specific details** and generalize them\n\n### Before Finalizing\n1. **Remove implementation specifics** (method names, file paths, code snippets) while **preserving architectural component names**\n2. **Test readability** - would someone unfamiliar understand the flow?\n3. **Verify checklist completeness** - does it cover all necessary steps?\n4. **Check for redundancy** between sections\n\n## File Organization Strategy\n\n### Naming Convention\n- Use descriptive, hyphenated names: `staging-file-flow.md`\n- Focus on the **process or flow**, not specific features\n- Keep names **broad enough** to encompass related future changes\n- All documentation files use `.md` extension\n\n### File Scope\n- **One major flow per file** - don't combine unrelated processes\n- **Component-focused files** for complex subsystems\n- **Architectural flows and patterns** that help future development\n\n## Maintenance Strategy\n\n### Regular Reviews\n- **After major refactors** - verify documentation still reflects reality\n- **During onboarding** - check if documentation helps new developers\n- **When patterns change** - update to reflect new approaches\n\n### Update Triggers\n- **Flow architecture changes** affecting multiple components\n- **New responsibility boundaries** emerging\n- **Repeated questions** from team members about the same flow\n\n### Deprecation\n- **Remove outdated files** when flows no longer exist\n- **Merge related files** if they become too similar\n- **Archive rather than delete** if historical context is valuable\n\n## Quality Checklist\n\nBefore committing documentation:\n\n- [ ] **Flow is clear** without code knowledge\n- [ ] **Checklist is actionable** and complete  \n- [ ] **Examples are generic** and won't become outdated\n- [ ] **Pitfalls are architectural** not implementation-specific\n- [ ] **Integration points are documented** (API endpoints, service contracts)\n- [ ] **File organization is helpful** for quick reference\n- [ ] **Language is timeless** and concept-focused (preserves architectural component names, avoids implementation details)\n- [ ] **Redundancy is eliminated** between sections\n\n## Benefits of Good Documentation\n\n### For Current Implementation\n- **Validates understanding** of the architectural flow\n- **Identifies gaps** in the implementation approach\n- **Creates shared vocabulary** for the team\n\n### For Future Development\n- **Reduces onboarding time** for new team members\n- **Prevents repeated mistakes** through pitfall documentation\n- **Enables consistent patterns** across similar changes\n- **Speeds up similar implementations** with clear checklists\n\nThis approach ensures documentation remains valuable and current while capturing the essential architectural knowledge needed for future development.\n\n<!-- File: warehouse/.cursor/rules/plan-act-workflow.mdc (Tokens: ~827 | Category: cursor-rule) -->\n---\ndescription: \nglobs: \nalwaysApply: true\n---\n# 🚨 CRITICAL PLAN-ACT WORKFLOW RULE 🚨\n\n## ⚠️ MANDATORY REQUIREMENT FOR ALL DEVELOPMENT TASKS ⚠️\n\n**This is a CRITICAL rule that MUST be followed without exception when working on any development task in the warehouse directory.**\n\n## 🔄 TWO MODES OF OPERATION: PLAN → ACT\n\n### 📋 MODE 1: PLAN (Planning Phase)\n**In PLAN mode, you focus EXCLUSIVELY on planning and analysis. NO CODE IMPLEMENTATION is allowed.**\n\n### ⚡ MODE 2: ACT (Implementation Phase)  \n**In ACT mode, you execute the approved plan. NO NEW PLANNING or scope changes without returning to PLAN mode.**\n\n**🚫 CRITICAL RULE: You CANNOT be in both modes simultaneously. You must explicitly transition from PLAN → ACT.**\n\n---\n\n### RULE: COMPREHENSIVE PLANNING BEFORE IMPLEMENTATION\n\n### 📋 PLAN MODE REQUIREMENTS\n\n**At any step in PLAN mode, always ask the user for clarifications—even for minor uncertainties or assumptions—whenever needed. This applies to requirement gathering, planning, challenge identification, and documentation/approval.**\n\nComplete ALL of the following before transitioning to ACT mode:\n\n#### 0. 📝 REQUIREMENT GATHERING & CLARIFICATION\n- Begin by gathering requirements and understanding the user's goals, constraints, and expectations for the task.\n\n#### 1. 📋 COMPREHENSIVE PLAN\n- Break down task into actionable steps with dependencies and complexity estimates\n- Identify all affected components and define clear success criteria\n\n#### 2. 🔍 CHALLENGE IDENTIFICATION  \n- Technical risks (algorithms, performance, integration, edge cases)\n- Testing requirements (mocks, data, coverage strategy)\n- Compatibility and resource constraints (migrations, external dependencies)\n\n#### 3. 📝 DOCUMENTATION & APPROVAL\n- Document step-by-step approach with risk mitigation and rollback plan\n- **GET EXPLICIT APPROVAL** - ACT mode forbidden until plan is approved\n- **DECLARE TRANSITION**: \"Moving from PLAN mode to ACT mode\"\n\n### ⚡ ACT MODE REQUIREMENTS\n\nIn ACT mode, you MUST:\n\n#### 1. 🎯 EXECUTE THE APPROVED PLAN\n- Follow documented steps exactly, implement only what was planned\n- **DECLARE MODE**: \"Currently in ACT mode\"\n\n#### 2. 🚫 NO SCOPE CHANGES  \n- Any unexpected issues or new requirements require **RETURN TO PLAN MODE**\n- Track progress and report deviations immediately\n\n### 🚫 VIOLATIONS - STRICTLY PROHIBITED\n\n- **PLAN Mode**: Implementing code, skipping planning steps, proceeding without approval\n- **ACT Mode**: Changing scope without returning to PLAN, deviating from approved plan  \n- **Mode Mixing**: Operating in both modes, transitions without declarations\n\n### ✅ COMPLIANCE CHECKLIST\n\n#### PLAN Mode:\n- [ ] Declared \"Currently in PLAN mode\"\n- [ ] **Gathered requirements and clarified all uncertainties with the user (and sought clarifications at any step as needed)**\n- [ ] Completed comprehensive plan with steps, challenges, and risks\n- [ ] Received explicit approval  \n- [ ] **Declared transition**: \"Moving from PLAN mode to ACT mode\"\n\n#### ACT Mode:\n- [ ] Declared \"Currently in ACT mode\" \n- [ ] Following approved plan exactly\n- [ ] **If scope changes needed**: Return to PLAN mode first\n\n### 🎯 WHY THIS RULE EXISTS\n\n**Prevents costly mistakes** through upfront planning, **ensures focused execution** by mode separation, **reduces context switching**, and **maintains scope discipline**.\n\n---\n\n**Remember: The PLAN → ACT workflow creates mental clarity and prevents the costly mistake of \"planning while coding.\" This two-mode approach is non-negotiable for maintaining the quality and reliability of the warehouse codebase.**\n\n<!-- File: warehouse/.cursor/rules/testing.mdc (Tokens: ~2815 | Category: cursor-rule) -->\n---\ndescription: Testing guidelines for the warehouse directory in RudderStack.\nglobs:\n  - \"**/*_test.go\"\nalwaysApply: true\n---\n\n# Warehouse Testing Guidelines\n\nThis document outlines the testing conventions and best practices for the `warehouse/` directory in the RudderStack server codebase.\n\n## Table of Contents\n\n- [Assertion Library](mdc:#assertion-library)\n- [Test Structure](mdc:#test-structure)\n- [Parallelization](mdc:#parallelization)\n- [Context Management](mdc:#context-management)\n- [Setup and Teardown](mdc:#setup-and-teardown)\n- [Database Testing](mdc:#database-testing)\n- [Mocking](mdc:#mocking)\n- [File Management](mdc:#file-management)\n- [Configuration](mdc:#configuration)\n- [Test Naming](mdc:#test-naming)\n- [Error Testing](mdc:#error-testing)\n- [Helper Patterns](mdc:#helper-patterns)\n- [Integration Test Patterns](mdc:#integration-test-patterns)\n- [Common Anti-patterns to Avoid](mdc:#common-anti-patterns-to-avoid)\n- [Example Test Structure](mdc:#example-test-structure)\n\n## Assertion Library\n\n**ALWAYS** use `github.com/stretchr/testify/require` for assertions in warehouse tests.\n\n- Prefer `require` over `assert` to fail fast on critical assertions\n- Use `require.NoError(t, err)` for error checking\n- Use `require.Equal(t, expected, actual)` for equality checks\n- Use `require.True(t, condition)` and `require.False(t, condition)` for boolean checks\n\n```go\nimport (\n    \"github.com/stretchr/testify/require\"\n)\n\nfunc TestExample(t *testing.T) {\n    result, err := someFunction()\n    require.NoError(t, err)\n    require.Equal(t, expected, result)\n}\n```\n\n## Test Structure\n\nUse **table-driven tests** for multiple scenarios:\n\n- Structure table-driven tests with `name`, input, and `expected` fields\n- Always use `t.Run(tc.name, func(t *testing.T) {})` for subtests\n- Group related subtests under a parent `t.Run(\"group name\", ...)` block for clarity and maintainability.\n- Include both positive and negative test cases\n\n```go\n// Table-driven tests for parameterized scenarios\nfunc TestWarehouseFunction(t *testing.T) {\n    testCases := []struct {\n        name     string\n        input    InputType\n        expected ExpectedType\n        wantErr  bool\n    }{\n        {\n            name:     \"successful case\",\n            input:    validInput,\n            expected: expectedOutput,\n            wantErr:  false,\n        },\n        {\n            name:    \"error case\",\n            input:   invalidInput,\n            wantErr: true,\n        },\n    }\n    \n    for _, tc := range testCases {\n        t.Run(tc.name, func(t *testing.T) {\n            // test implementation\n        })\n    }\n}\n\n// Grouped subtests for related functionality\nfunc TestWarehouseComponent(t *testing.T) {\n    t.Run(\"initialization\", func(t *testing.T) {\n        t.Run(\"valid configuration\", func(t *testing.T) { /* ... */ })\n        t.Run(\"invalid configuration\", func(t *testing.T) { /* ... */ })\n        t.Run(\"missing configuration\", func(t *testing.T) { /* ... */ })\n    })\n    \n    t.Run(\"data processing\", func(t *testing.T) {\n        t.Run(\"single record\", func(t *testing.T) { /* ... */ })\n        t.Run(\"batch processing\", func(t *testing.T) { /* ... */ })\n        t.Run(\"empty input\", func(t *testing.T) { /* ... */ })\n    })\n}\n```\n\n## Parallelization\n\n- Use `t.Parallel()` for tests that can run concurrently\n- Apply parallelization to both main tests and subtests where safe\n- Avoid parallelization for tests that modify shared resources\n\n```go\nfunc TestConcurrentFunction(t *testing.T) {\n    t.Parallel()\n    \n    for _, tc := range testCases {\n        t.Run(tc.name, func(t *testing.T) {\n            t.Parallel()\n            // test implementation\n        })\n    }\n}\n```\n\n## Context Management\n\n- Use `context.Background()` as the default context for most tests\n- Use `context.WithTimeout()` for tests with time constraints\n- Always pass context as the first parameter to functions under test\n\n```go\nfunc TestWithContext(t *testing.T) {\n    ctx := context.Background()\n    // or for timeouts:\n    ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n    defer cancel()\n    \n    result, err := functionUnderTest(ctx, input)\n    require.NoError(t, err)\n}\n```\n\n## Setup and Teardown\n\n- Use `t.Cleanup()` for resource cleanup (files, database connections, etc.)\n- Clean up temporary files with `require.NoError(t, os.Remove(filePath))`\n- Use `defer` for cleanup when `t.Cleanup()` is not sufficient\n- Create helper functions for complex test setup\n\n```go\nfunc TestWithCleanup(t *testing.T) {\n    tempFile, err := os.CreateTemp(\"\", \"test_*.txt\")\n    require.NoError(t, err)\n    \n    t.Cleanup(func() {\n        require.NoError(t, os.Remove(tempFile.Name()))\n    })\n    \n    // test implementation\n}\n```\n\n## Database Testing\n\n- Use `dockertest` for PostgreSQL integration tests\n- Set up database migrations with `migrator.Migrator`\n- Use `sqlmiddleware.New()` for database connections\n- Clean up database resources properly in `t.Cleanup()`\n\n```go\nfunc TestDatabaseIntegration(t *testing.T) {\n    pool, err := dockertest.NewPool(\"\")\n    require.NoError(t, err)\n    \n    pgResource, err := postgres.Setup(pool, t)\n    require.NoError(t, err)\n    \n    err = (&migrator.Migrator{\n        Handle:          pgResource.DB,\n        MigrationsTable: \"wh_schema_migrations\",\n    }).Migrate(\"warehouse\")\n    require.NoError(t, err)\n    \n    db := sqlmiddleware.New(pgResource.DB)\n    \n    // test implementation\n}\n```\n\n## Mocking\n\n- Use `go.uber.org/mock/gomock` for interface mocking\n- Create mock expectations with clear `.EXPECT()` calls\n- Use `gomock.NewController(t)` for mock controller setup\n- Place mock generation comments: `//go:generate go run go.uber.org/mock/mockgen`\n- For error path testing, prefer extending mocks with error fields or behaviors rather than creating many separate mock types.\n\n```go\ntype mockRepository struct {\n    data map[string]interface{}\n    err  error\n}\n\nfunc (m *mockRepository) Get(key string) (interface{}, error) {\n    if m.err != nil {\n        return nil, m.err\n    }\n    return m.data[key], nil\n}\n\n// Usage in tests:\nsuccessMock := &mockRepository{data: map[string]interface{}{\"key\": \"value\"}}\nerrorMock := &mockRepository{err: errors.New(\"connection failed\")}\n```\n\n## File Management\n\n- Create temporary files with `os.CreateTemp()` or `t.TempDir()`\n- Always clean up files with `t.Cleanup(func() { require.NoError(t, os.Remove(fileName)) })`\n- Use proper file handling patterns for testing file operations\n- Test both successful file operations and error cases\n\n```go\nfunc TestFileOperations(t *testing.T) {\n    tempDir := t.TempDir()\n    \n    tempFile, err := os.CreateTemp(tempDir, \"test_*.json\")\n    require.NoError(t, err)\n    \n    t.Cleanup(func() {\n        require.NoError(t, tempFile.Close())\n    })\n    \n    // test file operations\n}\n```\n\n## Configuration\n\n- Use `config.New()` for test configuration\n- Override config values with `c.Set(key, value)` for test scenarios\n- Use environment variable overrides when testing config behavior\n- Test both default and custom configuration values\n\n```go\nfunc TestConfiguration(t *testing.T) {\n    c := config.New()\n    c.Set(\"Warehouse.testKey\", \"testValue\")\n    \n    // test with configuration\n}\n```\n\n## Test Naming\n\n- Use descriptive test function names: `TestFunctionName_Scenario`\n- Use underscores to separate components in test names\n- Include the component being tested in the function name\n- Use clear, descriptive names for table-driven test cases\n\n```go\nfunc TestWarehouse_GetBoolDestinationConfig(t *testing.T) { /* ... */ }\nfunc TestLoadFileGenerator_GetLoadFilePrefix(t *testing.T) { /* ... */ }\nfunc TestStagingFileRepo_GetPending(t *testing.T) { /* ... */ }\n```\n\n## Error Testing\n\n- Test both success and error scenarios\n- Use `require.Error(t, err)` for expected errors\n- Use `require.ErrorIs(t, err, expectedError)` for specific error types\n- Use `require.EqualError(t, err, expectedMessage)` for exact error messages\n- For fallback or multi-source logic, ensure tests cover all branches, including \"no data,\" \"empty but present,\" and error propagation.\n\n```go\nt.Run(\"data retrieval with fallback\", func(t *testing.T) {\n    t.Run(\"primary source succeeds\", func(t *testing.T) { /* ... */ })\n    t.Run(\"primary source fails, fallback succeeds\", func(t *testing.T) { /* ... */ })\n    t.Run(\"both primary and fallback fail\", func(t *testing.T) { /* ... */ })\n    t.Run(\"primary source returns empty, no fallback\", func(t *testing.T) { /* ... */ })\n})\n```\n\n## Helper Patterns\n\n- Create test helper functions for complex setups\n- Use `t.Helper()` in helper functions to get correct line numbers\n- Extract common test data into helper functions or constants\n- Create factory functions for test models and objects\n\n```go\nfunc createTestWarehouse(t *testing.T) model.Warehouse {\n    t.Helper()\n    \n    return model.Warehouse{\n        WorkspaceID: \"test-workspace\",\n        Source: backendconfig.SourceT{\n            ID: \"test-source\",\n        },\n        Destination: backendconfig.DestinationT{\n            ID: \"test-destination\",\n        },\n    }\n}\n\nfunc setupTestDatabase(t *testing.T) (*sql.DB, func()) {\n    t.Helper()\n    \n    // setup logic\n    \n    cleanup := func() {\n        // cleanup logic\n    }\n    \n    return db, cleanup\n}\n```\n\n## Integration Test Patterns\n\n- Use docker-compose for complex integration test setups\n- Set up real warehouse connections for integration tests\n- Use conditional skips: `if os.Getenv(\"SLOW\") != \"1\" { t.Skip() }`\n- Test end-to-end workflows with real data\n\n```go\nfunc TestIntegration(t *testing.T) {\n    if os.Getenv(\"SLOW\") != \"1\" {\n        t.Skip(\"Skipping integration tests. Add 'SLOW=1' env var to run test.\")\n    }\n    \n    // integration test implementation\n}\n```\n\n## Common Anti-patterns to Avoid\n\n- ❌ Don't use `testing.T.Fatal()` or `t.Fatalf()` - use `require` instead\n- ❌ Don't ignore cleanup errors - always check with `require.NoError()`\n- ❌ Don't create tests without cleanup for temporary resources\n- ❌ Don't use sleep for timing - use proper synchronization or timeouts\n- ❌ Don't test implementation details - focus on behavior\n\n## Example Test Structure\n\nHere's a complete example following all the guidelines:\n\n```go\npackage warehouse_test\n\nimport (\n    \"context\"\n    \"os\"\n    \"testing\"\n    \"time\"\n\n    \"github.com/stretchr/testify/require\"\n    \"go.uber.org/mock/gomock\"\n\n    \"github.com/rudderlabs/rudder-go-kit/config\"\n    \"github.com/rudderlabs/rudder-server/warehouse/internal/model\"\n)\n\nfunc TestWarehouseFunction_Scenario(t *testing.T) {\n    testCases := []struct {\n        name     string\n        input    InputType\n        expected ExpectedType\n        wantErr  bool\n    }{\n        {\n            name:     \"successful case\",\n            input:    validInput,\n            expected: expectedOutput,\n            wantErr:  false,\n        },\n        {\n            name:    \"error case\",\n            input:   invalidInput,\n            wantErr: true,\n        },\n    }\n    \n    for _, tc := range testCases {\n        t.Run(tc.name, func(t *testing.T) {\n            t.Parallel()\n            \n            // Setup\n            ctx := context.Background()\n            ctrl := gomock.NewController(t)\n            defer ctrl.Finish()\n            \n            tempFile, err := os.CreateTemp(\"\", \"test_*.json\")\n            require.NoError(t, err)\n            \n            t.Cleanup(func() {\n                require.NoError(t, os.Remove(tempFile.Name()))\n            })\n            \n            // Test execution\n            result, err := functionUnderTest(ctx, tc.input)\n            \n            // Assertions\n            if tc.wantErr {\n                require.Error(t, err)\n                return\n            }\n            \n            require.NoError(t, err)\n            require.Equal(t, tc.expected, result)\n        })\n    }\n}\n```\n\n## Reference\n\nThis document is based on analysis of existing test patterns in the warehouse directory. For questions or suggestions about these guidelines, please refer to the test files in the warehouse directory for examples of these patterns in practice.\n</yakaai_skills>"}