diff --git a/.claude/skills/agent-bricks/3-multi-agent-supervisors.md b/.claude/skills/agent-bricks/3-multi-agent-supervisors.md deleted file mode 100644 index c546d242..00000000 --- a/.claude/skills/agent-bricks/3-multi-agent-supervisors.md +++ /dev/null @@ -1,237 +0,0 @@ -# Multi-Agent Supervisors (MAS) - -Multi-Agent Supervisors orchestrate multiple specialized agents, routing user queries to the most appropriate agent based on the query content. - -## What is a Multi-Agent Supervisor? - -A MAS acts as a traffic controller for multiple AI agents. When a user asks a question: - -1. **Analyzes** the query to understand the intent -2. **Routes** to the most appropriate specialized agent -3. **Returns** the agent's response to the user - -This allows you to combine multiple specialized agents into a single unified interface. - -## When to Use - -Use a Multi-Agent Supervisor when: -- You have multiple specialized agents (billing, technical support, HR, etc.) -- Users shouldn't need to know which agent to ask -- You want to provide a unified conversational experience - -## Prerequisites - -Before creating a MAS, you need agents of one or both types: - -**Model Serving Endpoints** (`endpoint_name`): -- Knowledge Assistant (KA) endpoints (e.g., `ka-abc123-endpoint`) -- Custom agents built with LangChain, LlamaIndex, etc. -- Fine-tuned models -- RAG applications - -**Genie Spaces** (`genie_space_id`): -- Existing Genie spaces for SQL-based data exploration -- Great for analytics, metrics, and data-driven questions -- No separate endpoint deployment required - reference the space directly -- To find a Genie space by name, use `find_genie_by_name(display_name="My Genie")` -- **Note**: There is NO system table for Genie spaces - do not try to query `system.ai.genie_spaces` - -## Creating a Multi-Agent Supervisor - -Use the `create_or_update_mas` tool: - -- `name`: "Customer Support MAS" -- `agents`: - ```json - [ - { - "name": "policy_agent", - "ka_tile_id": "f32c5f73-466b-4798-b3a0-5396b5ece2a5", - "description": "Answers questions about company policies and procedures from indexed documents" - }, - { - "name": "usage_analytics", - "genie_space_id": "01abc123-def4-5678-90ab-cdef12345678", - "description": "Answers data questions about usage metrics, trends, and statistics" - }, - { - "name": "custom_agent", - "endpoint_name": "my-custom-endpoint", - "description": "Handles specialized queries via custom model endpoint" - } - ] - ``` -- `description`: "Routes customer queries to specialized support agents" -- `instructions`: "Analyze the user's question and route to the most appropriate agent. If unclear, ask for clarification." - -This example shows mixing Knowledge Assistants (policy_agent), Genie spaces (usage_analytics), and custom endpoints (custom_agent). - -## Agent Configuration - -Each agent in the `agents` list needs: - -| Field | Required | Description | -|-------|----------|-------------| -| `name` | Yes | Internal identifier for the agent | -| `description` | Yes | What this agent handles (critical for routing) | -| `ka_tile_id` | One of these | Knowledge Assistant tile ID (for document Q&A agents) | -| `genie_space_id` | One of these | Genie space ID (for SQL-based data agents) | -| `endpoint_name` | One of these | Model serving endpoint name (for custom agents) | - -**Note**: Provide exactly one of: `ka_tile_id`, `genie_space_id`, or `endpoint_name`. - -To find a KA tile_id, use `find_ka_by_name(name="Your KA Name")`. -To find a Genie space_id, use `find_genie_by_name(display_name="Your Genie Name")`. - -### Writing Good Descriptions - -The `description` field is critical for routing. Make it specific: - -**Good descriptions:** -- "Handles billing questions including invoices, payments, refunds, and subscription changes" -- "Answers technical questions about API errors, integration issues, and product bugs" -- "Provides information about HR policies, PTO, benefits, and employee handbook" - -**Bad descriptions:** -- "Billing agent" (too vague) -- "Handles stuff" (not helpful) -- "Technical" (not specific) - -## Provisioning Timeline - -After creation, the MAS endpoint needs to provision: - -| Status | Meaning | Duration | -|--------|---------|----------| -| `PROVISIONING` | Creating the supervisor | 2-5 minutes | -| `ONLINE` | Ready to route queries | - | -| `OFFLINE` | Not currently running | - | - -Use `get_mas` to check the status. - -## Adding Example Questions - -Example questions help with evaluation and can guide routing optimization: - -```json -{ - "examples": [ - { - "question": "I haven't received my invoice for this month", - "guideline": "Should be routed to billing_agent" - }, - { - "question": "The API is returning a 500 error", - "guideline": "Should be routed to technical_agent" - }, - { - "question": "How many vacation days do I have?", - "guideline": "Should be routed to hr_agent" - } - ] -} -``` - -If the MAS is not yet `ONLINE`, examples are queued and added automatically when ready. - -## Best Practices - -### Agent Design - -1. **Specialized agents**: Each agent should have a clear, distinct purpose -2. **Non-overlapping domains**: Avoid agents with similar descriptions -3. **Clear boundaries**: Define what each agent does and doesn't handle - -### Instructions - -Provide routing instructions: - -``` -You are a customer support supervisor. Your job is to route user queries to the right specialist: - -1. For billing, payments, or subscription questions → billing_agent -2. For technical issues, bugs, or API problems → technical_agent -3. For HR, benefits, or policy questions → hr_agent - -If the query is unclear or spans multiple domains, ask the user to clarify. -``` - -### Fallback Handling - -Consider adding a general-purpose agent for queries that don't fit elsewhere: - -```json -{ - "name": "general_agent", - "endpoint_name": "general-support-endpoint", - "description": "Handles general inquiries that don't fit other categories, provides navigation help" -} -``` - -## Example Workflow - -1. **Deploy specialized agents** as model serving endpoints: - - `billing-assistant-endpoint` - - `tech-support-endpoint` - - `hr-assistant-endpoint` - -2. **Create the MAS**: - - Configure agents with clear descriptions - - Add routing instructions - -3. **Wait for ONLINE status** (2-5 minutes) - -4. **Add example questions** for evaluation - -5. **Test routing** with various query types - -## Updating a Multi-Agent Supervisor - -To update an existing MAS: - -1. **Add/remove agents**: Call `create_or_update_mas` with updated `agents` list -2. **Update descriptions**: Change agent descriptions to improve routing -3. **Modify instructions**: Update routing rules - -The tool finds the existing MAS by name and updates it. - -## Troubleshooting - -### Queries routed to wrong agent - -- Review and improve agent descriptions -- Make descriptions more specific and distinct -- Add examples that demonstrate correct routing - -### Endpoint not responding - -- Verify each underlying model serving endpoint is running -- Check endpoint logs for errors -- Ensure endpoints accept the expected input format - -### Slow responses - -- Check latency of underlying endpoints -- Consider endpoint scaling settings -- Monitor for cold start issues - -## Advanced: Hierarchical Routing - -For complex scenarios, you can create multiple levels of MAS: - -``` -Top-level MAS -├── Customer Support MAS -│ ├── billing_agent -│ ├── technical_agent -│ └── general_agent -├── Sales MAS -│ ├── pricing_agent -│ ├── demo_agent -│ └── contract_agent -└── Internal MAS - ├── hr_agent - └── it_helpdesk_agent -``` - -Each sub-MAS is deployed as an endpoint and configured as an agent in the top-level MAS. diff --git a/.claude/skills/agent-bricks/SKILL.md b/.claude/skills/agent-bricks/SKILL.md deleted file mode 100644 index bd8f8488..00000000 --- a/.claude/skills/agent-bricks/SKILL.md +++ /dev/null @@ -1,151 +0,0 @@ ---- -name: agent-bricks -description: "Create and manage Databricks Agent Bricks: Knowledge Assistants (KA) for document Q&A, Genie Spaces for SQL exploration, and Multi-Agent Supervisors (MAS) for multi-agent orchestration. Use when building conversational AI applications on Databricks." ---- - -# Agent Bricks - -Create and manage Databricks Agent Bricks - pre-built AI components for building conversational applications. - -## Overview - -Agent Bricks are three types of pre-built AI tiles in Databricks: - -| Brick | Purpose | Data Source | -|-------|---------|-------------| -| **Knowledge Assistant (KA)** | Document-based Q&A using RAG | PDF/text files in Volumes | -| **Genie Space** | Natural language to SQL | Unity Catalog tables | -| **Multi-Agent Supervisor (MAS)** | Multi-agent orchestration | Model serving endpoints | - -## Prerequisites - -Before creating Agent Bricks, ensure you have the required data: - -### For Knowledge Assistants -- **Documents in a Volume**: PDF, text, or other files stored in a Unity Catalog volume -- Generate synthetic documents using the `unstructured-pdf-generation` skill if needed - -### For Genie Spaces -- **See the `databricks-genie` skill** for comprehensive Genie Space guidance -- Tables in Unity Catalog with the data to explore -- Generate raw data using the `synthetic-data-generation` skill -- Create tables using the `spark-declarative-pipelines` skill - -### For Multi-Agent Supervisors -- **Model Serving Endpoints**: Deployed agent endpoints (KA endpoints, custom agents, fine-tuned models) -- **Genie Spaces**: Existing Genie spaces can be used directly as agents for SQL-based queries -- Mix and match endpoint-based and Genie-based agents in the same MAS - -## MCP Tools - -### Knowledge Assistant Tools - -**create_or_update_ka** - Create or update a Knowledge Assistant -- `name`: Name for the KA -- `volume_path`: Path to documents (e.g., `/Volumes/catalog/schema/volume/folder`) -- `description`: (optional) What the KA does -- `instructions`: (optional) How the KA should answer -- `tile_id`: (optional) Existing tile_id to update -- `add_examples_from_volume`: (optional, default: true) Auto-add examples from JSON files - -**get_ka** - Get Knowledge Assistant details -- `tile_id`: The KA tile ID - -**find_ka_by_name** - Find a Knowledge Assistant by name -- `name`: The exact name of the KA to find -- Returns: `tile_id`, `name`, `endpoint_name`, `endpoint_status` -- Use this to look up an existing KA when you know the name but not the tile_id - -**delete_ka** - Delete a Knowledge Assistant -- `tile_id`: The KA tile ID to delete - -### Genie Space Tools - -**For comprehensive Genie guidance, use the `databricks-genie` skill.** - -Basic tools available: - -- `create_or_update_genie` - Create or update a Genie Space -- `get_genie` - Get Genie Space details -- `delete_genie` - Delete a Genie Space - -See `databricks-genie` skill for: -- Table inspection workflow -- Sample question best practices -- Curation (instructions, certified queries) - -**IMPORTANT**: There is NO system table for Genie spaces (e.g., `system.ai.genie_spaces` does not exist). To find a Genie space by name, use the `find_genie_by_name` tool. - -### Multi-Agent Supervisor Tools - -**create_or_update_mas** - Create or update a Multi-Agent Supervisor -- `name`: Name for the MAS -- `agents`: List of agent configurations, each with: - - `name`: Agent identifier (required) - - `description`: What this agent handles - critical for routing (required) - - `ka_tile_id`: Knowledge Assistant tile ID (use for document Q&A agents - recommended for KAs) - - `genie_space_id`: Genie space ID (use for SQL-based data agents) - - `endpoint_name`: Model serving endpoint name (use for custom agents) - - Note: Provide exactly one of: `ka_tile_id`, `genie_space_id`, or `endpoint_name` -- `description`: (optional) What the MAS does -- `instructions`: (optional) Routing instructions for the supervisor -- `tile_id`: (optional) Existing tile_id to update -- `examples`: (optional) List of example questions with `question` and `guideline` fields - -**get_mas** - Get Multi-Agent Supervisor details -- `tile_id`: The MAS tile ID - -**find_mas_by_name** - Find a Multi-Agent Supervisor by name -- `name`: The exact name of the MAS to find -- Returns: `tile_id`, `name`, `endpoint_status`, `agents_count` -- Use this to look up an existing MAS when you know the name but not the tile_id - -**delete_mas** - Delete a Multi-Agent Supervisor -- `tile_id`: The MAS tile ID to delete - -## Typical Workflow - -### 1. Generate Source Data - -Before creating Agent Bricks, generate the required source data: - -**For KA (document Q&A)**: -``` -1. Use `unstructured-pdf-generation` skill to generate PDFs -2. PDFs are saved to a Volume with companion JSON files (question/guideline pairs) -``` - -**For Genie (SQL exploration)**: -``` -1. Use `synthetic-data-generation` skill to create raw parquet data -2. Use `spark-declarative-pipelines` skill to create bronze/silver/gold tables -``` - -### 2. Create the Agent Brick - -Use the appropriate `create_or_update_*` tool with your data sources. - -### 3. Wait for Provisioning - -Newly created KA and MAS tiles need time to provision. The endpoint status will progress: -- `PROVISIONING` - Being created (can take 2-5 minutes) -- `ONLINE` - Ready to use -- `OFFLINE` - Not running - -### 4. Add Examples (Automatic) - -For KA, if `add_examples_from_volume=true`, examples are automatically extracted from JSON files in the volume and added once the endpoint is `ONLINE`. - -## Best Practices - -1. **Use meaningful names**: Names are sanitized automatically (spaces become underscores) -2. **Provide descriptions**: Helps users understand what the brick does -3. **Add instructions**: Guide the AI's behavior and tone -4. **Include sample questions**: Shows users how to interact with the brick -5. **Use the workflow**: Generate data first, then create the brick - -## See Also - -- `1-knowledge-assistants.md` - Detailed KA patterns and examples -- `databricks-genie` skill - Detailed Genie patterns, curation, and examples -- `3-multi-agent-supervisors.md` - Detailed MAS patterns and examples diff --git a/.claude/skills/bdd-features/SKILL.md b/.claude/skills/bdd-features/SKILL.md new file mode 100644 index 00000000..8d0bb123 --- /dev/null +++ b/.claude/skills/bdd-features/SKILL.md @@ -0,0 +1,105 @@ +--- +name: bdd-features +description: "This skill should be used when the user asks to \"write Gherkin\", \"create feature files\", \"generate BDD scenarios\", \"write acceptance tests in Gherkin\", \"create Behave features\", \"write Given When Then tests\", \"BDD test cases for my pipeline\", \"Gherkin for Unity Catalog\", or wants to translate requirements into Gherkin feature files for Databricks." +user-invocable: true +--- + +# BDD Features — Gherkin Feature File Generation + +Generate well-structured Gherkin `.feature` files for Databricks workloads. Translate requirements, user stories, or existing code into behavior specifications using Given/When/Then syntax. + +## When to use + +- Translating requirements or user stories into Gherkin acceptance criteria +- Creating feature files for Databricks pipelines, catalog permissions, jobs, or Apps +- Writing regression tests in Gherkin for existing functionality +- Generating Scenario Outlines for data-driven testing + +## Process + +### 1. Identify the test subject + +Determine what to test. Read the relevant code or ask the user: + +- A Lakeflow SDP pipeline definition → pipeline behavior tests +- Unity Catalog grants/policies → permission verification tests +- A FastAPI Databricks App → API endpoint tests +- A notebook or job → execution and output validation tests +- SQL transformations → data quality and correctness tests + +### 2. Write the feature file + +Place feature files in the appropriate subdirectory under `features/`: + +``` +features/ +├── catalog/permissions.feature +├── pipelines/events_pipeline.feature +├── apps/api_endpoints.feature +├── jobs/etl_notebook.feature +└── sql/data_quality.feature +``` + +**Structure every feature file with:** + +1. **Tags** — `@domain`, `@smoke`/`@regression`/`@integration`, optional `@slow` or `@wip` +2. **Feature header** — name + As a / I want / So that narrative +3. **Background** — shared Given steps (workspace connection, test schema) +4. **Scenarios** — one behavior per scenario, descriptive names + +Refer to `references/gherkin-patterns.md` for Databricks-specific Gherkin patterns covering: +- Pipeline lifecycle (full refresh, incremental, failure handling) +- Unity Catalog grants, column masks, row filters +- App endpoint testing with SSO headers +- Job/notebook execution and output validation +- SQL data quality assertions +- Scenario Outlines for parameterized testing + +### 3. Gherkin writing principles + +**Declarative, not imperative.** Describe *what* the system should do, not *how* to click buttons: + +```gherkin +# Good — declarative +When I grant SELECT on "catalog.schema.table" to group "readers" +Then the group "readers" should have SELECT permission + +# Bad — imperative +When I open the Catalog Explorer +And I click on the table "catalog.schema.table" +And I click "Permissions" +And I click "Grant" +And I select "SELECT" +And I type "readers" in the group field +And I click "Save" +``` + +**One behavior per scenario.** If a scenario tests two independent things, split it. + +**Use Backgrounds for shared setup.** Avoid repeating connection/schema steps across scenarios. + +**Scenario Outlines for data variations.** When the same behavior is tested with different inputs, use Examples tables instead of duplicating scenarios. + +**Tag strategically:** +- `@smoke` — fast, critical-path tests (< 30 seconds each) +- `@regression` — thorough coverage (minutes) +- `@integration` — needs live workspace (skip in unit test CI) +- `@slow` — pipeline tests, job executions (> 2 minutes) + +**CRITICAL — Curly braces break step matching.** Behave uses the `parse` library for step matching. `{anything}` in feature file text is interpreted as a capture group, not a literal. Never use `{test_schema}.table_name` in feature files — it will fail to match step definitions. Instead, use short table names (`"customers"`) and resolve the schema in step code. + +**Trailing colons matter.** When a step has an attached data table or docstring, the `:` at the end of the Gherkin line IS part of the step text. The step pattern must include it: `@given('a table "{name}" with data:')` — not `with data` (no colon). + +### 4. Validate step coverage + +After writing features, check that step definitions exist for all steps: + +```bash +uv run behave --dry-run +``` + +Any undefined steps will be reported with suggested snippets. Hand those to the `bdd-steps` skill for implementation. + +## Additional resources + +- **`references/gherkin-patterns.md`** — Complete Databricks Gherkin pattern library with examples for every domain diff --git a/.claude/skills/bdd-features/references/gherkin-patterns.md b/.claude/skills/bdd-features/references/gherkin-patterns.md new file mode 100644 index 00000000..19132522 --- /dev/null +++ b/.claude/skills/bdd-features/references/gherkin-patterns.md @@ -0,0 +1,446 @@ +# Gherkin Patterns for Databricks + +Reusable Gherkin patterns for common Databricks testing scenarios. Copy and adapt these to feature files. + +> **WARNING: Curly braces in step text break Behave's `parse` matcher.** +> +> Behave uses Python's `parse` library for step matching. Any `{...}` in step text +> is interpreted as a capture group. Writing `{test_schema}.customers` in a step line +> will **silently fail to match** your step definition. +> +> **The correct pattern:** +> - Step text uses **short table names in quotes**: `"customers"`, `"orders"` +> - SQL inside **docstrings** (triple-quoted blocks) can safely use `{schema}` because +> docstrings are accessed via `context.text`, not step matching +> - Step definitions prepend `context.test_schema + "."` internally to build the FQN +> +> ```python +> # WRONG - step text with curly braces +> @given('a table "{test_schema}.customers" exists') # BROKEN - parse eats {test_schema} +> +> # RIGHT - short name in step text, FQN built in the step body +> @given('a managed table "{table_name}" exists') +> def step_impl(context, table_name): +> fqn = f"{context.test_schema}.{table_name}" +> # ... use fqn +> ``` +> +> **Docstring SQL pattern** (safe because `context.text` is just a string): +> ```python +> @when('I execute SQL:') +> def step_impl(context): +> sql = context.text.replace("{schema}", context.test_schema) +> # ... execute sql +> ``` + +## Common Background + +Most Databricks feature files share this Background: + +```gherkin +Background: + Given a Databricks workspace connection is established + And a test schema is provisioned +``` + +--- + +## Unity Catalog + +### Table permissions + +```gherkin +@catalog @permissions +Feature: Unity Catalog table permissions + As a data engineer + I want to verify table-level permissions + So that sensitive data is properly protected + + Background: + Given a Databricks workspace connection is established + And a test schema is provisioned + + Scenario: Grant SELECT to a group + Given a managed table "customers" exists + When I execute SQL: + """sql + GRANT SELECT ON TABLE {schema}.customers TO `data_readers` + """ + And I execute SQL: + """sql + SHOW GRANTS ON TABLE {schema}.customers + """ + Then the result should contain a row where "ActionType" is "SELECT" and "Principal" is "data_readers" + + Scenario Outline: Verify multiple privilege types + Given a managed table "sales" exists + When I execute SQL: + """sql + GRANT ON TABLE {schema}.sales TO `` + """ + And I execute SQL: + """sql + SHOW GRANTS ON TABLE {schema}.sales + """ + Then the result should contain a row where "ActionType" is "" and "Principal" is "" + + Examples: + | privilege | group | + | SELECT | data_readers | + | MODIFY | data_writers | +``` + +### Column masks + +```gherkin +@catalog @security +Feature: Column-level security + + Background: + Given a Databricks workspace connection is established + And a test schema is provisioned + + Scenario: Mask PII columns for analysts + Given a managed table "customers" with columns: + | column_name | data_type | contains_pii | + | id | BIGINT | false | + | name | STRING | true | + | email | STRING | true | + | region | STRING | false | + And a column mask function "mask_pii" is applied to "name" and "email" on "customers" + When I query "customers" as group "analysts" + Then columns "name" and "email" should return masked values + But columns "id" and "region" should return actual values +``` + +### Row filters + +```gherkin +@catalog @security +Feature: Row-level security + + Background: + Given a Databricks workspace connection is established + And a test schema is provisioned + + Scenario: Row filter restricts by region + Given a managed table "regional_sales" with data: + | region | revenue | quarter | + | APAC | 50000 | Q1 | + | EMEA | 75000 | Q1 | + | AMER | 100000 | Q1 | + And a row filter on "regional_sales" restricts "apac_analysts" to region "APAC" + When I query "regional_sales" as group "apac_analysts" + Then I should only see rows where "region" is "APAC" + And the result should have 1 row +``` + +--- + +## Lakeflow Spark Declarative Pipelines + +### Pipeline lifecycle + +```gherkin +@pipeline @lakeflow +Feature: Events pipeline processing + As a data engineer + I want to verify the events pipeline processes data correctly + So that downstream consumers get accurate aggregations + + Background: + Given a Databricks workspace connection is established + And a test schema is provisioned + + @integration @slow + Scenario: Full refresh produces expected tables + Given a pipeline "events_pipeline" exists targeting the test schema + When I trigger a full refresh of the pipeline + Then the pipeline update should succeed within 600 seconds + And the streaming table "bronze_events" should exist + And the materialized view "silver_events_agg" should exist + And the table "silver_events_agg" should have more than 0 rows + + @integration + Scenario: Incremental refresh picks up new data + Given the pipeline "events_pipeline" has completed a full refresh + When I insert test records into the source + And I trigger an incremental refresh of the pipeline + Then the pipeline update should succeed within 300 seconds + And the new records should appear in "bronze_events" + + Scenario: Pipeline handles empty source gracefully + Given a pipeline "events_pipeline" exists targeting the test schema + And the source table is empty + When I trigger a full refresh of the pipeline + Then the pipeline update should succeed within 300 seconds + And the streaming table "bronze_events" should have 0 rows +``` + +### Pipeline failure handling + +```gherkin + Scenario: Pipeline surfaces schema mismatch errors + Given a pipeline "events_pipeline" exists targeting the test schema + And the source table has an unexpected column "extra_col" of type "BINARY" + When I trigger a full refresh of the pipeline + Then the pipeline update should fail + And the pipeline error should mention schema +``` + +--- + +## Jobs and Notebooks + +### Notebook execution + +```gherkin +@jobs @notebook +Feature: Customer ETL notebook + As a data engineer + I want to verify the ETL notebook produces correct output + + Background: + Given a Databricks workspace connection is established + And a test schema is provisioned + + @integration @slow + Scenario: Dedup notebook removes duplicates + Given a managed table "raw_customers" with data: + | customer_id | name | email | updated_at | + | 1 | Alice | alice@example.com | 2024-01-01T00:00:00 | + | 1 | Alice B. | alice@example.com | 2024-06-01T00:00:00 | + | 2 | Bob | bob@example.com | 2024-03-15T00:00:00 | + When I run the notebook "/Repos/team/etl/customer_dedup" with parameters: + | key | value | + | source_table | raw_customers | + | target_table | clean_customers| + Then the job should complete with status "SUCCESS" within 300 seconds + And the table "clean_customers" should have 2 rows + And the table "clean_customers" should contain a row where "customer_id" is "1" and "name" is "Alice B." + + Scenario: Notebook fails gracefully on missing source + When I run the notebook "/Repos/team/etl/customer_dedup" with parameters: + | key | value | + | source_table | nonexistent | + | target_table | output | + Then the job should complete with status "FAILED" within 120 seconds +``` + +--- + +## Databricks Apps (FastAPI) + +### API endpoint testing + +```gherkin +@app @fastapi +Feature: Databricks App API + As a user + I want the app endpoints to work correctly + + Background: + Given the app is running at the configured base URL + And the test user is "testuser@databricks.com" + + @smoke + Scenario: Health check + When I GET "/health" + Then the response status should be 200 + And the response JSON should contain "status" with value "healthy" + + Scenario: Authenticated user can list resources + When I GET "/api/dashboards" with auth headers + Then the response status should be 200 + And the response should be a JSON list + + Scenario: Unauthenticated request is rejected + When I GET "/api/dashboards" without auth headers + Then the response status should be 401 + + Scenario: POST creates a resource + When I POST "/api/items" with auth headers and body: + """json + {"name": "Test Item", "description": "Created by BDD test"} + """ + Then the response status should be 201 + And the response JSON should contain "name" with value "Test Item" +``` + +### App deployment testing + +```gherkin +@app @deployment @slow +Feature: App deployment lifecycle + Scenario: Deploy and verify app is running + Given a bundle project at the repository root + When I deploy using Asset Bundles with target "dev" + Then the deployment should succeed + And the app should reach "RUNNING" state within 120 seconds + And the app health endpoint should return 200 +``` + +--- + +## SQL Data Quality + +### Row counts and data validation + +```gherkin +@sql @data-quality +Feature: Data quality checks + + Background: + Given a Databricks workspace connection is established + And a test schema is provisioned + + @smoke + Scenario: Table is not empty + Given the table "orders" has been loaded + Then the table "orders" should have more than 0 rows + + Scenario: No duplicate primary keys + Given the table "orders" has been loaded + When I execute SQL: + """sql + SELECT order_id, COUNT(*) as cnt + FROM {schema}.orders + GROUP BY order_id + HAVING COUNT(*) > 1 + """ + Then the result should have 0 rows + + Scenario: Foreign key integrity + Given the tables "orders" and "customers" have been loaded + When I execute SQL: + """sql + SELECT o.customer_id + FROM {schema}.orders o + LEFT JOIN {schema}.customers c ON o.customer_id = c.customer_id + WHERE c.customer_id IS NULL + """ + Then the result should have 0 rows + + Scenario: No null values in required columns + When I execute SQL: + """sql + SELECT COUNT(*) as null_count + FROM {schema}.orders + WHERE order_id IS NULL OR customer_id IS NULL OR order_date IS NULL + """ + Then the first row column "null_count" should be "0" + + Scenario: Verify GRANT was applied via SQL + Given a managed table "products" exists + When I execute SQL: + """sql + GRANT SELECT ON TABLE {schema}.products TO `reporting_team` + """ + And I execute SQL: + """sql + SHOW GRANTS ON TABLE {schema}.products + """ + Then the result should contain a row where "ActionType" is "SELECT" and "Principal" is "reporting_team" +``` + +--- + +## Asset Bundles Deployment + +```gherkin +@deployment @dabs +Feature: Bundle lifecycle + @smoke + Scenario: Bundle validates successfully + When I run "databricks bundle validate" with target "dev" + Then the command should exit with code 0 + + @integration @slow + Scenario: Deploy and destroy lifecycle + When I run "databricks bundle deploy" with target "dev" + Then the command should exit with code 0 + When I run "databricks bundle destroy" with target "dev" and auto-approve + Then the command should exit with code 0 +``` + +--- + +## Scenario Outline patterns + +Use Scenario Outlines for testing multiple variations of the same behavior. + +Note: table names in the Examples table are short names (no schema prefix). The step +definition prepends `context.test_schema` to build the fully-qualified name. + +```gherkin + Scenario Outline: Verify table existence after pipeline run + Then the "" should exist + + Examples: Streaming tables + | table_type | table_name | + | streaming table | bronze_events | + | streaming table | bronze_transactions| + + Examples: Materialized views + | table_type | table_name | + | materialized view | silver_events_agg| + | materialized view | gold_summary | +``` + +--- + +## Steps with data tables and docstrings + +Steps that accept a data table or docstring **must** end with a trailing colon. The colon +is part of the step text that Behave matches against your `@given`/`@when`/`@then` decorator. + +```gherkin +# CORRECT - colon before data table +Given a managed table "customers" with data: + | id | name | region | + | 1 | Alice | APAC | + | 2 | Bob | EMEA | + +# CORRECT - colon before docstring +When I execute SQL: + """sql + SELECT * FROM {schema}.customers + """ + +# WRONG - missing colon, Behave will not match the step +Given a managed table "customers" with data + | id | name | region | +``` + +--- + +## SHOW GRANTS column names + +`SHOW GRANTS` returns PascalCase column names. Use these exact names when asserting +on grant results: + +| Column | Description | +|--------------|------------------------------------------------| +| `Principal` | The user, group, or service principal | +| `ActionType` | The privilege (SELECT, MODIFY, ALL PRIVILEGES) | +| `ObjectType` | TABLE, SCHEMA, CATALOG, etc. | +| `ObjectKey` | The fully-qualified object name | + +--- + +## Tag strategy + +| Tag | Purpose | Typical runtime | +|-----|---------|----------------| +| `@smoke` | Critical path, must always pass | < 30s per scenario | +| `@regression` | Full coverage | Minutes | +| `@integration` | Needs live workspace | Varies | +| `@slow` | Pipeline/job execution | > 2 min | +| `@wip` | Work in progress, skip by default | N/A | +| `@skip` | Explicitly disabled | N/A | +| `@catalog` | Unity Catalog tests | Varies | +| `@pipeline` | Lakeflow SDP tests | Minutes | +| `@jobs` | Job/notebook tests | Minutes | +| `@app` | Databricks Apps tests | Seconds | +| `@sql` | SQL/data quality tests | Seconds | +| `@deployment` | DABs lifecycle tests | Minutes | diff --git a/.claude/skills/bdd-run/SKILL.md b/.claude/skills/bdd-run/SKILL.md new file mode 100644 index 00000000..f8f242e1 --- /dev/null +++ b/.claude/skills/bdd-run/SKILL.md @@ -0,0 +1,145 @@ +--- +name: bdd-run +description: "This skill should be used when the user asks to \"run BDD tests\", \"execute Behave\", \"run Gherkin tests\", \"run my feature files\", \"behave test results\", \"run smoke tests\", \"BDD test report\", or needs to execute Behave test suites with specific options like tag filtering, parallel execution, or CI reporting." +user-invocable: true +--- + +# BDD Run — Execute and Report Behave Tests + +Execute Behave test suites with tag filtering, parallel execution, output formatting, and CI integration. Diagnose failures and suggest fixes. + +## When to use + +- Running the full BDD test suite or a subset by tags +- Getting JUnit/JSON reports for CI pipelines +- Re-running only failed scenarios +- Running tests in parallel for speed +- Diagnosing and triaging test failures + +## Process + +### 1. Pre-flight checks + +Before running tests, verify the environment: + +```bash +# Verify Behave is installed +uv run behave --version + +# Verify Databricks auth +uv run python -c "from databricks.sdk import WorkspaceClient; print(WorkspaceClient().current_user.me().user_name)" + +# Dry run to check step coverage +uv run behave --dry-run +``` + +If any undefined steps are found, report them and suggest using the `bdd-steps` skill. + +### 2. Execute tests + +**Run by tag (most common):** + +```bash +# Smoke tests only +uv run behave --tags="@smoke" --format=pretty + +# All except slow and WIP +uv run behave --tags="not @slow and not @wip" + +# Specific domain +uv run behave --tags="@catalog" +uv run behave --tags="@pipeline" + +# Boolean combinations +uv run behave --tags="(@catalog or @pipeline) and @smoke" +``` + +**Run specific feature file or directory:** + +```bash +uv run behave features/catalog/permissions.feature +uv run behave features/pipelines/ +``` + +**Run by scenario name:** + +```bash +uv run behave --name "Grant SELECT on a table" +``` + +**Pass runtime configuration:** + +```bash +uv run behave -D warehouse_id=abc123 -D catalog=my_catalog -D environment=dev +``` + +### 3. Output and reporting + +**For local development:** + +```bash +uv run behave --format=pretty --show-timings +``` + +**For CI pipelines (JUnit XML):** + +```bash +uv run behave --junit --junit-directory=reports/behave/ --format=progress +``` + +**JSON output for programmatic analysis:** + +```bash +uv run behave --format=json --outfile=reports/results.json --format=progress +``` + +**Multiple formatters simultaneously:** + +```bash +uv run behave --format=pretty --format=json --outfile=reports/results.json +``` + +### 4. Re-run failed tests + +Configure rerun file output, then re-run only failures: + +```bash +# First run captures failures +uv run behave --format=rerun --outfile=reports/rerun.txt --format=pretty + +# Re-run only failed scenarios +uv run behave @reports/rerun.txt +``` + +### 5. Parallel execution + +Behave has no built-in parallelism. Use `behavex` for parallel feature execution: + +```bash +uv run behavex --parallel-processes 4 --parallel-scheme feature +``` + +Each parallel worker needs its own test schema to avoid cross-contamination. The `environment.py` template from `bdd-scaffold` handles this by using timestamped schema names with worker ID suffixes. + +### 6. Failure diagnosis + +When tests fail, read the output and categorize: + +| Failure type | Symptom | Action | +|-------------|---------|--------| +| Undefined step | `NotImplementedError` or "undefined" in output | Generate step with `bdd-steps` | +| Auth failure | `PermissionDenied`, 401/403 | Check `databricks auth profiles` | +| Timeout | `TimeoutError` in polling steps | Increase timeout parameter or check resource state | +| Data mismatch | Assertion error with expected vs. actual | Check test data setup or query logic | +| Schema not found | `SCHEMA_NOT_FOUND` | Verify `before_all` created the ephemeral schema | +| Warehouse stopped | `WAREHOUSE_NOT_RUNNING` | Start warehouse or use `@fixture.sql_warehouse` tag hook | + +### 7. Makefile integration + +If a Makefile exists, prefer `make` targets: + +```bash +make bdd # Full suite +make bdd-smoke # Smoke tests +make bdd-report # JUnit for CI +``` diff --git a/.claude/skills/bdd-scaffold/SKILL.md b/.claude/skills/bdd-scaffold/SKILL.md new file mode 100644 index 00000000..d24c5ca4 --- /dev/null +++ b/.claude/skills/bdd-scaffold/SKILL.md @@ -0,0 +1,114 @@ +--- +name: bdd-scaffold +description: "This skill should be used when the user asks to \"set up BDD\", \"create a Behave project\", \"scaffold BDD tests\", \"initialize Behave\", \"add BDD to my project\", \"set up Gherkin testing\", \"create test structure for Behave\", or mentions setting up behavior-driven development testing. Generates a complete Behave project structure wired to Databricks SDK." +user-invocable: true +--- + +# BDD Scaffold — Behave + Databricks Project Setup + +Generate a complete Python Behave project structure pre-wired with Databricks SDK integration, including `environment.py` hooks, test isolation via ephemeral schemas, and `behave.ini` configuration. + +## When to use + +- Starting a new BDD test suite for a Databricks project +- Adding Behave-based acceptance tests to an existing repo +- Setting up integration testing against Unity Catalog, pipelines, jobs, or Apps + +## Process + +### 1. Detect project context + +Identify the project root and existing tooling: + +```bash +git rev-parse --show-toplevel +``` + +Check for existing test infrastructure: `pyproject.toml`, `Makefile`, `behave.ini`, `features/` directory. If a `features/` directory already exists, confirm before overwriting. + +### 2. Determine test domains + +Ask (or infer from the codebase) which Databricks domains to scaffold step files for: + +| Domain | Step file | When | +|--------|-----------|------| +| Unity Catalog | `catalog_steps.py` | Tables, schemas, grants, row filters, column masks | +| Pipelines | `pipeline_steps.py` | Lakeflow SDP, streaming tables, materialized views | +| Jobs | `job_steps.py` | Notebook runs, workflow tasks, job clusters | +| Apps | `app_steps.py` | FastAPI endpoints, SSO headers, deployment | +| SQL | `sql_steps.py` | Statement execution, warehouse queries, data validation | + +Always generate `common_steps.py` (shared workspace connection, row counting, table existence checks). + +### 3. Generate the directory structure + +``` +features/ +├── environment.py # Databricks SDK setup, ephemeral schema lifecycle +├── steps/ +│ ├── common_steps.py # Shared steps (always generated) +│ └── _steps.py # Per-domain (based on step 2) +├── catalog/ # Feature file directories (one per domain) +├── pipelines/ +├── jobs/ +├── apps/ +└── sql/ +behave.ini +Makefile # (append BDD targets if Makefile exists) +``` + +Refer to `references/environment-template.md` for the full `environment.py` template with: +- `before_all`: WorkspaceClient init, warehouse auto-discovery, ephemeral schema creation +- `after_all`: Schema cascade drop +- `before_scenario` / `after_scenario`: Per-scenario resource tracking and cleanup +- Tag-based hooks for `@wip`, `@skip`, `@slow` + +Refer to `references/behave-config.md` for `behave.ini` and `pyproject.toml` configuration. + +### 4. Add dependencies + +If `pyproject.toml` exists and uses `uv`: + +```bash +uv add --group test behave databricks-sdk httpx +``` + +If no `pyproject.toml`, create a minimal one with test dependencies. + +### 5. Add Makefile targets + +Append these targets (or create a Makefile if none exists): + +```makefile +.PHONY: bdd bdd-smoke bdd-report + +bdd: + uv run behave --format=pretty + +bdd-smoke: + uv run behave --tags="@smoke" --format=pretty + +bdd-report: + uv run behave --junit --junit-directory=reports/ --format=progress +``` + +### 6. Verify scaffold + +Run `behave --dry-run` to confirm step discovery works and there are no import errors: + +```bash +uv run behave --dry-run +``` + +Report the generated structure and next steps to the user. + +## Key design decisions + +- **Ephemeral schemas** — each test run creates a timestamped schema (`behave_test_YYYYMMDD_HHMMSS`) and drops it in `after_all`. Prevents cross-run contamination. +- **`-D` userdata** for parameterization — warehouse IDs, catalog names, and targets are passed via CLI args, never hardcoded. +- **Step files are globally scoped** in Behave — all files in `steps/` are imported regardless of which feature runs. Name step patterns carefully to avoid collisions. + +## Additional resources + +- **`references/environment-template.md`** — Full annotated environment.py template +- **`references/behave-config.md`** — behave.ini and pyproject.toml configuration reference diff --git a/.claude/skills/bdd-scaffold/references/behave-config.md b/.claude/skills/bdd-scaffold/references/behave-config.md new file mode 100644 index 00000000..d994f518 --- /dev/null +++ b/.claude/skills/bdd-scaffold/references/behave-config.md @@ -0,0 +1,134 @@ +# Behave Configuration Reference + +## behave.ini + +Standard Behave configuration file. Place at project root. + +```ini +[behave] +# Output +default_format = pretty +show_timings = true +color = true + +# Default tag filter — skip WIP and explicitly skipped tests +default_tags = not @wip and not @skip + +# Logging +logging_level = INFO +logging_format = %(asctime)s %(levelname)-8s %(name)s: %(message)s + +# Capture control +stdout_capture = true +log_capture = true + +# JUnit output (enable in CI) +junit = false +junit_directory = reports/ + +# Feature paths +paths = features/ + +[behave.userdata] +# Override with -D key=value on CLI +warehouse_id = auto +catalog = main +environment = dev +``` + +## pyproject.toml + +Alternative configuration via pyproject.toml (Behave reads `[tool.behave]`): + +**IMPORTANT:** In `pyproject.toml`, `default_tags` must be a **list**, not a string. The `behave.ini` parser accepts a plain string, but the TOML parser is stricter: + +```toml +[tool.behave] +default_format = "pretty" +show_timings = true +default_tags = ["not @wip and not @skip"] # MUST be a list in pyproject.toml +junit = false +junit_directory = "reports/" +logging_level = "INFO" + +[tool.behave.userdata] +warehouse_id = "auto" +catalog = "main" +environment = "dev" +``` + +## Dependencies + +Add to `pyproject.toml`: + +```toml +[project.optional-dependencies] +test = [ + "behave>=1.2.6", + "databricks-sdk>=0.40.0", + "httpx>=0.27.0", +] + +# Or for parallel execution +test-parallel = [ + "behave>=1.2.6", + "behavex>=3.0", + "databricks-sdk>=0.40.0", + "httpx>=0.27.0", +] +``` + +With `uv`: + +```bash +uv add --group test behave databricks-sdk httpx +``` + +## Makefile targets + +```makefile +.PHONY: bdd bdd-smoke bdd-report bdd-rerun bdd-parallel bdd-dry-run + +bdd: + uv run behave --format=pretty --show-timings + +bdd-smoke: + uv run behave --tags="@smoke" --format=pretty + +bdd-report: + uv run behave --junit --junit-directory=reports/behave/ --format=progress + +bdd-rerun: + uv run behave @reports/rerun.txt + +bdd-parallel: + uv run behavex --parallel-processes 4 --parallel-scheme feature + +bdd-dry-run: + uv run behave --dry-run +``` + +## CI integration (GitHub Actions example) + +```yaml +- name: Run BDD tests + env: + DATABRICKS_HOST: ${{ secrets.DATABRICKS_HOST }} + DATABRICKS_TOKEN: ${{ secrets.DATABRICKS_TOKEN }} + DATABRICKS_WAREHOUSE_ID: ${{ secrets.WAREHOUSE_ID }} + TEST_CATALOG: ci_test + run: | + uv run behave \ + --tags="not @slow" \ + --junit --junit-directory=reports/behave/ \ + --format=progress \ + -D catalog=$TEST_CATALOG \ + -D warehouse_id=$DATABRICKS_WAREHOUSE_ID + +- name: Upload test results + if: always() + uses: actions/upload-artifact@v4 + with: + name: behave-results + path: reports/behave/ +``` diff --git a/.claude/skills/bdd-scaffold/references/environment-template.md b/.claude/skills/bdd-scaffold/references/environment-template.md new file mode 100644 index 00000000..2a7dc1b7 --- /dev/null +++ b/.claude/skills/bdd-scaffold/references/environment-template.md @@ -0,0 +1,195 @@ +# environment.py Template — Databricks + Behave + +Complete annotated template for `features/environment.py`. Copy and adapt to the target project. + +## Full template + +```python +"""Behave environment hooks — Databricks SDK integration. + +Sets up workspace connection, ephemeral test schema, and per-scenario cleanup. +""" +from __future__ import annotations + +import logging +import os +from datetime import datetime + +from behave.model import Feature, Scenario, Step +from behave.runner import Context + +logger = logging.getLogger("behave.databricks") + + +# ─── Session-level hooks ──────────────────────────────────────── + +def before_all(context: Context) -> None: + """Initialize Databricks clients and create ephemeral test schema.""" + from databricks.sdk import WorkspaceClient + + context.workspace = WorkspaceClient() + + # Fix host URL — some profiles include ?o= which breaks SDK API paths. + # The CLI handles this transparently but the SDK does not. + if context.workspace.config.host and "?" in context.workspace.config.host: + clean_host = context.workspace.config.host.split("?")[0].rstrip("/") + profile = os.environ.get("DATABRICKS_CONFIG_PROFILE") + context.workspace = WorkspaceClient(profile=profile, host=clean_host) + + # Verify auth + me = context.workspace.current_user.me() + context.current_user = me.user_name + logger.info("Authenticated as: %s", context.current_user) + + # Warehouse — from -D userdata, env var, or auto-discover + userdata = context.config.userdata + context.warehouse_id = ( + userdata.get("warehouse_id") + or os.environ.get("DATABRICKS_WAREHOUSE_ID") + or _discover_warehouse(context.workspace) + ) + logger.info("Using warehouse: %s", context.warehouse_id) + + # Catalog — from -D userdata or env var + context.test_catalog = userdata.get("catalog", os.environ.get("TEST_CATALOG", "main")) + + # Create ephemeral schema (timestamped for isolation) + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + worker = os.environ.get("BEHAVE_WORKER_ID", "0") + context.test_schema = f"{context.test_catalog}.behave_test_{ts}_w{worker}" + + _execute_sql(context, f"CREATE SCHEMA IF NOT EXISTS {context.test_schema}") + logger.info("Created test schema: %s", context.test_schema) + + +def after_all(context: Context) -> None: + """Drop ephemeral test schema.""" + if hasattr(context, "test_schema"): + try: + _execute_sql(context, f"DROP SCHEMA IF EXISTS {context.test_schema} CASCADE") + logger.info("Dropped test schema: %s", context.test_schema) + except Exception as e: + logger.warning("Failed to drop test schema %s: %s", context.test_schema, e) + + +# ─── Feature-level hooks ──────────────────────────────────────── + +def before_feature(context: Context, feature: Feature) -> None: + """Log feature start. Skip if tagged @skip.""" + logger.info("▶ Feature: %s", feature.name) + if "skip" in feature.tags: + feature.skip("Marked with @skip") + + +def after_feature(context: Context, feature: Feature) -> None: + logger.info("◀ Feature: %s [%s]", feature.name, feature.status) + + +# ─── Scenario-level hooks ─────────────────────────────────────── + +def before_scenario(context: Context, scenario: Scenario) -> None: + """Initialize per-scenario state. Skip @wip scenarios.""" + logger.info(" ▶ Scenario: %s", scenario.name) + if "wip" in scenario.tags: + scenario.skip("Work in progress") + return + # Track resources created during this scenario for cleanup + context.scenario_cleanup_sql = [] + + +def after_scenario(context: Context, scenario: Scenario) -> None: + """Clean up scenario-specific resources.""" + for sql in getattr(context, "scenario_cleanup_sql", []): + try: + _execute_sql(context, sql) + except Exception as e: + logger.warning("Cleanup SQL failed: %s — %s", sql, e) + if scenario.status == "failed": + logger.error(" ✗ FAILED: %s", scenario.name) + else: + logger.info(" ◀ Scenario: %s [%s]", scenario.name, scenario.status) + + +# ─── Step-level hooks ─────────────────────────────────────────── + +def before_step(context: Context, step: Step) -> None: + context._step_start = datetime.now() + + +def after_step(context: Context, step: Step) -> None: + elapsed = (datetime.now() - context._step_start).total_seconds() + if elapsed > 10: + logger.warning(" Slow step (%.1fs): %s %s", elapsed, step.keyword, step.name) + if step.status == "failed": + logger.error(" ✗ %s %s\n %s", step.keyword, step.name, step.error_message) + + +# ─── Tag-based hooks ──────────────────────────────────────────── + +def before_tag(context, tag: str) -> None: + """Ensure resources for tagged scenarios.""" + if tag == "fixture.sql_warehouse": + _ensure_warehouse_running(context) + + +# ─── Helpers ──────────────────────────────────────────────────── + +def _execute_sql(context: Context, sql: str) -> object: + """Execute a SQL statement via the Statement Execution API.""" + return context.workspace.statement_execution.execute_statement( + warehouse_id=context.warehouse_id, + statement=sql, + wait_timeout="30s", + ) + + +def _discover_warehouse(workspace) -> str: + """Find the first available SQL warehouse.""" + from databricks.sdk.service.sql import State + + warehouses = list(workspace.warehouses.list()) + # Prefer running warehouses + for wh in warehouses: + if wh.state == State.RUNNING: + return wh.id + if warehouses: + return warehouses[0].id + raise RuntimeError( + "No SQL warehouses found. Pass warehouse_id via -D warehouse_id= " + "or set DATABRICKS_WAREHOUSE_ID." + ) + + +def _ensure_warehouse_running(context: Context) -> None: + """Start warehouse if stopped. Used by @fixture.sql_warehouse tag.""" + from databricks.sdk.service.sql import State + + wh = context.workspace.warehouses.get(context.warehouse_id) + if wh.state != State.RUNNING: + logger.info("Starting warehouse %s...", context.warehouse_id) + context.workspace.warehouses.start(context.warehouse_id) + context.workspace.warehouses.wait_get_warehouse_running(context.warehouse_id) + logger.info("Warehouse %s is running.", context.warehouse_id) +``` + +## Context object layering + +Behave's `context` has scoped layers. Data set at different levels has different lifetimes: + +| Set in | Lifetime | Example | +|--------|----------|---------| +| `before_all` | Entire run | `context.workspace`, `context.test_schema` | +| `before_feature` | Current feature | `context.feature_data` | +| `before_scenario` / steps | Current scenario | `context.query_result`, `context.scenario_cleanup_sql` | + +At the end of each scenario, the scenario layer is popped — anything set during steps is gone. Root-level data persists across everything. + +## Parallel execution isolation + +When using `behavex` for parallel execution, each worker needs its own schema. The template uses `BEHAVE_WORKER_ID` from the environment. Set it in the parallel runner config or wrapper script: + +```bash +# Example wrapper for behavex +export BEHAVE_WORKER_ID=$WORKER_INDEX +behave "$@" +``` diff --git a/.claude/skills/bdd-scaffold/test-suite/.gitignore b/.claude/skills/bdd-scaffold/test-suite/.gitignore new file mode 100644 index 00000000..744fea57 --- /dev/null +++ b/.claude/skills/bdd-scaffold/test-suite/.gitignore @@ -0,0 +1,4 @@ +.venv/ +__pycache__/ +reports/ +*.pyc diff --git a/.claude/skills/bdd-scaffold/test-suite/behave.ini b/.claude/skills/bdd-scaffold/test-suite/behave.ini new file mode 100644 index 00000000..a3c4cb07 --- /dev/null +++ b/.claude/skills/bdd-scaffold/test-suite/behave.ini @@ -0,0 +1,13 @@ +[behave] +default_format = pretty +show_timings = true +color = true +default_tags = not @wip and not @skip +logging_level = INFO +stdout_capture = false +log_capture = false +paths = features/ + +[behave.userdata] +warehouse_id = auto +catalog = main diff --git a/.claude/skills/bdd-scaffold/test-suite/features/catalog/schema_operations.feature b/.claude/skills/bdd-scaffold/test-suite/features/catalog/schema_operations.feature new file mode 100644 index 00000000..45bacf92 --- /dev/null +++ b/.claude/skills/bdd-scaffold/test-suite/features/catalog/schema_operations.feature @@ -0,0 +1,38 @@ +@catalog @smoke +Feature: Unity Catalog schema and table operations + As a data engineer + I want to verify Unity Catalog operations work correctly + So that I can manage my data assets with confidence + + Background: + Given a Databricks workspace connection is established + And a test schema is provisioned + + Scenario: Ephemeral test schema was created + Then the test schema should exist in Unity Catalog + + Scenario: Create tables and list them + Given a managed table "table_alpha" exists + And a managed table "table_beta" exists + When I list tables in the test schema + Then the table list should include "table_alpha" + And the table list should include "table_beta" + + Scenario: Table with data is queryable via SQL + Given a managed table "products" with data: + | product_id | name | price | + | 1 | Widget | 9.99 | + | 2 | Gadget | 19.99 | + | 3 | Doohickey | 4.99 | + Then the managed table "products" should have 3 rows + When I execute a query on the test schema: + """ + SELECT name, price FROM {schema}.products WHERE CAST(price AS DOUBLE) > 10.0 + """ + Then the query result should have 1 rows + And the first result column "name" should be "Gadget" + + Scenario: Grant SELECT permission on a table + Given a managed table "grant_test" exists + When I grant SELECT on managed table "grant_test" to group "users" + Then the group "users" should have SELECT on managed table "grant_test" diff --git a/.claude/skills/bdd-scaffold/test-suite/features/environment.py b/.claude/skills/bdd-scaffold/test-suite/features/environment.py new file mode 100644 index 00000000..bd09e070 --- /dev/null +++ b/.claude/skills/bdd-scaffold/test-suite/features/environment.py @@ -0,0 +1,131 @@ +"""Behave environment hooks — Databricks SDK integration. + +Tested against azure-east workspace. +""" +from __future__ import annotations + +import logging +import os +from datetime import datetime + +from behave.model import Feature, Scenario, Step +from behave.runner import Context + +logger = logging.getLogger("behave.databricks") + + +def before_all(context: Context) -> None: + """Initialize Databricks clients and create ephemeral test schema.""" + from databricks.sdk import WorkspaceClient + + # Use profile from env or default + profile = os.environ.get("DATABRICKS_CONFIG_PROFILE", "azure-east") + context.workspace = WorkspaceClient(profile=profile) + + # Fix host URL — some profiles include ?o= which breaks SDK API paths + if context.workspace.config.host and "?" in context.workspace.config.host: + clean_host = context.workspace.config.host.split("?")[0].rstrip("/") + context.workspace = WorkspaceClient(profile=profile, host=clean_host) + + me = context.workspace.current_user.me() + context.current_user = me.user_name + logger.info("Authenticated as: %s", context.current_user) + + # Warehouse — from -D userdata, env var, or auto-discover + userdata = context.config.userdata + wh_id = userdata.get("warehouse_id", "auto") + if wh_id == "auto": + wh_id = os.environ.get("DATABRICKS_WAREHOUSE_ID") or _discover_warehouse( + context.workspace + ) + context.warehouse_id = wh_id + logger.info("Using warehouse: %s", context.warehouse_id) + + # Catalog + context.test_catalog = userdata.get("catalog", "main") + + # Create ephemeral schema + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + context.test_schema = f"{context.test_catalog}.behave_test_{ts}" + + _execute_sql(context, f"CREATE SCHEMA IF NOT EXISTS {context.test_schema}") + logger.info("Created test schema: %s", context.test_schema) + + +def after_all(context: Context) -> None: + """Drop ephemeral test schema.""" + if hasattr(context, "test_schema"): + try: + _execute_sql( + context, f"DROP SCHEMA IF EXISTS {context.test_schema} CASCADE" + ) + logger.info("Dropped test schema: %s", context.test_schema) + except Exception as e: + logger.warning("Failed to drop test schema %s: %s", context.test_schema, e) + + +def before_feature(context: Context, feature: Feature) -> None: + logger.info("▶ Feature: %s", feature.name) + if "skip" in feature.tags: + feature.skip("Marked with @skip") + + +def after_feature(context: Context, feature: Feature) -> None: + logger.info("◀ Feature: %s [%s]", feature.name, feature.status) + + +def before_scenario(context: Context, scenario: Scenario) -> None: + logger.info(" ▶ Scenario: %s", scenario.name) + if "wip" in scenario.tags: + scenario.skip("Work in progress") + return + context.scenario_cleanup_sql = [] + + +def after_scenario(context: Context, scenario: Scenario) -> None: + for sql in getattr(context, "scenario_cleanup_sql", []): + try: + _execute_sql(context, sql) + except Exception as e: + logger.warning("Cleanup SQL failed: %s — %s", sql, e) + if scenario.status == "failed": + logger.error(" ✗ FAILED: %s", scenario.name) + + +def before_step(context: Context, step: Step) -> None: + context._step_start = datetime.now() + + +def after_step(context: Context, step: Step) -> None: + elapsed = (datetime.now() - context._step_start).total_seconds() + if elapsed > 10: + logger.warning(" Slow step (%.1fs): %s %s", elapsed, step.keyword, step.name) + if step.status == "failed": + logger.error( + " ✗ %s %s\n %s", step.keyword, step.name, step.error_message + ) + + +# ─── Helpers ──────────────────────────────────────────────────── + + +def _execute_sql(context: Context, sql: str) -> object: + """Execute a SQL statement via the Statement Execution API.""" + return context.workspace.statement_execution.execute_statement( + warehouse_id=context.warehouse_id, + statement=sql, + wait_timeout="30s", + ) + + +def _discover_warehouse(workspace) -> str: + """Find the first available SQL warehouse.""" + from databricks.sdk.service.sql import State + + warehouses = list(workspace.warehouses.list()) + for wh in warehouses: + if wh.state == State.RUNNING: + return wh.id + if warehouses: + return warehouses[0].id + raise RuntimeError("No SQL warehouses found") diff --git a/.claude/skills/bdd-scaffold/test-suite/features/sql/data_operations.feature b/.claude/skills/bdd-scaffold/test-suite/features/sql/data_operations.feature new file mode 100644 index 00000000..8e02c689 --- /dev/null +++ b/.claude/skills/bdd-scaffold/test-suite/features/sql/data_operations.feature @@ -0,0 +1,48 @@ +@sql @smoke +Feature: SQL data operations via Databricks + As a data engineer + I want to verify SQL operations work correctly against the warehouse + So that I can trust my data transformations + + Background: + Given a Databricks workspace connection is established + And a test schema is provisioned + + Scenario: Create a table and verify it exists + Given a managed table "smoke_test" exists + Then the managed table "smoke_test" should exist + + Scenario: Insert and count rows + Given a managed table "customers" with data: + | customer_id | name | email | + | 1 | Alice | alice@example.com | + | 2 | Bob | bob@example.com | + | 3 | Charlie | charlie@example.com | + Then the managed table "customers" should have 3 rows + + Scenario: Aggregate query returns correct results + Given a managed table "orders" with data: + | order_id | customer_id | amount | + | 101 | 1 | 50 | + | 102 | 1 | 75 | + | 103 | 2 | 100 | + When I execute a query on the test schema: + """ + SELECT customer_id, COUNT(*) as order_count + FROM {schema}.orders + GROUP BY customer_id + HAVING COUNT(*) > 1 + """ + Then the query result should have 1 rows + And the first result column "customer_id" should be "1" + + Scenario: Query with no matching rows returns zero + Given a managed table "statuses" with data: + | id | status | + | 1 | active | + | 2 | active | + When I execute a query on the test schema: + """ + SELECT * FROM {schema}.statuses WHERE status = 'inactive' + """ + Then the query result should have 0 rows diff --git a/.claude/skills/bdd-scaffold/test-suite/features/steps/catalog_steps.py b/.claude/skills/bdd-scaffold/test-suite/features/steps/catalog_steps.py new file mode 100644 index 00000000..da966aec --- /dev/null +++ b/.claude/skills/bdd-scaffold/test-suite/features/steps/catalog_steps.py @@ -0,0 +1,84 @@ +"""Step definitions for Unity Catalog operations. + +Table names in Gherkin are short ("customers"). +Schema resolution happens in _fqn() via context.test_schema. +""" +from __future__ import annotations + +from behave import when, then +from behave.runner import Context + + +@when("I list tables in the test schema") +def step_list_tables(context: Context) -> None: + catalog, schema = context.test_schema.split(".", 1) + context.table_list = list( + context.workspace.tables.list(catalog_name=catalog, schema_name=schema) + ) + + +@then("the table list should include {table_count:d} tables") +def step_table_count(context: Context, table_count: int) -> None: + actual = len(context.table_list) + assert actual == table_count, ( + f"Expected {table_count} tables, got {actual}: " + f"{[t.name for t in context.table_list]}" + ) + + +@then('the table list should include "{table_name}"') +def step_table_in_list(context: Context, table_name: str) -> None: + names = [t.name for t in context.table_list] + assert table_name in names, f"Table '{table_name}' not in list: {names}" + + +@when('I grant {privilege} on managed table "{table_name}" to group "{group}"') +def step_grant_privilege( + context: Context, privilege: str, table_name: str, group: str +) -> None: + """Grant privilege using SQL — more stable across SDK versions than the grants API.""" + from databricks.sdk.service.sql import StatementState + + fqn = f"{context.test_schema}.{table_name}" + result = context.workspace.statement_execution.execute_statement( + warehouse_id=context.warehouse_id, + statement=f"GRANT {privilege} ON TABLE {fqn} TO `{group}`", + wait_timeout="30s", + ) + assert result.status.state == StatementState.SUCCEEDED, ( + f"GRANT failed: {result.status.error}" + ) + + +@then('the group "{group}" should have {privilege} on managed table "{table_name}"') +def step_verify_permission( + context: Context, group: str, privilege: str, table_name: str +) -> None: + """Verify privilege using SHOW GRANTS — stable across SDK versions.""" + from databricks.sdk.service.sql import StatementState + + fqn = f"{context.test_schema}.{table_name}" + result = context.workspace.statement_execution.execute_statement( + warehouse_id=context.warehouse_id, + statement=f"SHOW GRANTS ON TABLE {fqn}", + wait_timeout="30s", + ) + assert result.status.state == StatementState.SUCCEEDED, ( + f"SHOW GRANTS failed: {result.status.error}" + ) + # Parse result: columns are Principal, ActionType, ObjectType, ObjectKey (PascalCase) + rows = result.result.data_array or [] + columns = [c.name for c in result.manifest.schema.columns] + # Handle case variation — normalize to lowercase for lookup + col_lower = [c.lower() for c in columns] + principal_idx = col_lower.index("principal") + action_idx = col_lower.index("actiontype") + + found = any( + row[principal_idx] == group and row[action_idx] == privilege + for row in rows + ) + assert found, ( + f"Expected {group} to have {privilege} on {fqn}. " + f"Grants found: {[(r[principal_idx], r[action_idx]) for r in rows]}" + ) diff --git a/.claude/skills/bdd-scaffold/test-suite/features/steps/common_steps.py b/.claude/skills/bdd-scaffold/test-suite/features/steps/common_steps.py new file mode 100644 index 00000000..03507610 --- /dev/null +++ b/.claude/skills/bdd-scaffold/test-suite/features/steps/common_steps.py @@ -0,0 +1,130 @@ +"""Shared step definitions for Databricks BDD tests. + +Design principle: Gherkin uses short table names ("customers"). +Step definitions prepend context.test_schema internally. +This avoids {curly_brace} conflicts with Behave's parse library. +""" +from __future__ import annotations + +from behave import given, when, then, step +from behave.runner import Context +from databricks.sdk.service.sql import StatementState + + +# ─── Connection and setup ──────────────────────────────────────── + + +@given("a Databricks workspace connection is established") +def step_workspace_connection(context: Context) -> None: + assert hasattr(context, "workspace"), "No workspace client — check environment.py" + assert hasattr(context, "warehouse_id"), "No warehouse_id — check environment.py" + + +@given("a test schema is provisioned") +def step_test_schema(context: Context) -> None: + assert hasattr(context, "test_schema"), "No test_schema — check environment.py" + + +# ─── Table creation ────────────────────────────────────────────── + + +@given('a managed table "{table_name}" exists') +def step_ensure_table(context: Context, table_name: str) -> None: + fqn = _fqn(context, table_name) + _sql(context, f"CREATE TABLE IF NOT EXISTS {fqn} (id BIGINT)") + context.scenario_cleanup_sql.append(f"DROP TABLE IF EXISTS {fqn}") + + +@given('a managed table "{table_name}" with data:') +def step_create_with_data(context: Context, table_name: str) -> None: + fqn = _fqn(context, table_name) + headers = context.table.headings + rows = context.table.rows + + col_defs = ", ".join(f"`{h}` STRING" for h in headers) + _sql(context, f"CREATE OR REPLACE TABLE {fqn} ({col_defs})") + context.scenario_cleanup_sql.append(f"DROP TABLE IF EXISTS {fqn}") + + for row in rows: + values = ", ".join(f"'{cell}'" for cell in row) + _sql(context, f"INSERT INTO {fqn} VALUES ({values})") + + +# ─── SQL execution ─────────────────────────────────────────────── + + +@when("I execute a query on the test schema:") +def step_execute_sql(context: Context) -> None: + """Execute SQL from docstring. Use {schema} as placeholder for test schema.""" + sql = context.text.replace("{schema}", context.test_schema) + context.query_result = _sql(context, sql) + + +# ─── Table assertions ──────────────────────────────────────────── + + +@then('the managed table "{table_name}" should exist') +def step_table_exists(context: Context, table_name: str) -> None: + fqn = _fqn(context, table_name) + try: + context.workspace.tables.get(fqn) + except Exception as e: + raise AssertionError(f"Table {fqn} does not exist: {e}") + + +@then('the managed table "{table_name}" should have {expected:d} rows') +def step_row_count(context: Context, table_name: str, expected: int) -> None: + fqn = _fqn(context, table_name) + result = _sql(context, f"SELECT COUNT(*) AS cnt FROM {fqn}") + actual = int(result.result.data_array[0][0]) + assert actual == expected, f"Expected {expected} rows in {table_name}, got {actual}" + + +@then("the test schema should exist in Unity Catalog") +def step_schema_exists(context: Context) -> None: + try: + context.workspace.schemas.get(context.test_schema) + except Exception as e: + raise AssertionError(f"Schema {context.test_schema} does not exist: {e}") + + +# ─── Query result assertions ──────────────────────────────────── + + +@then("the query result should have {expected:d} rows") +def step_result_row_count(context: Context, expected: int) -> None: + rows = context.query_result.result.data_array or [] + actual = len(rows) + assert actual == expected, f"Expected {expected} result rows, got {actual}" + + +@then('the first result column "{col}" should be "{value}"') +def step_first_result_value(context: Context, col: str, value: str) -> None: + result = context.query_result + columns = [c.name for c in result.manifest.schema.columns] + assert col in columns, f"Column '{col}' not in result: {columns}" + col_idx = columns.index(col) + actual = result.result.data_array[0][col_idx] + assert str(actual) == value, f"Expected {col}='{value}', got '{actual}'" + + +# ─── Helpers ───────────────────────────────────────────────────── + + +def _fqn(context: Context, table_name: str) -> str: + """Build fully-qualified table name from short name.""" + return f"{context.test_schema}.{table_name}" + + +def _sql(context: Context, sql: str): + """Execute SQL and assert success.""" + result = context.workspace.statement_execution.execute_statement( + warehouse_id=context.warehouse_id, + statement=sql, + wait_timeout="30s", + ) + assert result.status.state == StatementState.SUCCEEDED, ( + f"SQL failed ({result.status.state}): {result.status.error}\n" + f"Statement: {sql[:200]}" + ) + return result diff --git a/.claude/skills/bdd-scaffold/test-suite/pyproject.toml b/.claude/skills/bdd-scaffold/test-suite/pyproject.toml new file mode 100644 index 00000000..1ecbbdb4 --- /dev/null +++ b/.claude/skills/bdd-scaffold/test-suite/pyproject.toml @@ -0,0 +1,19 @@ +[project] +name = "bdd-test-suite" +version = "0.1.0" +requires-python = ">=3.11" +dependencies = [ + "behave>=1.2.6", + "databricks-sdk>=0.40.0", + "httpx>=0.27.0", +] + +[tool.behave] +default_format = "pretty" +show_timings = true +default_tags = ["not @wip and not @skip"] +logging_level = "INFO" + +[tool.behave.userdata] +warehouse_id = "auto" +catalog = "main" diff --git a/.claude/skills/bdd-steps/SKILL.md b/.claude/skills/bdd-steps/SKILL.md new file mode 100644 index 00000000..a14a12b6 --- /dev/null +++ b/.claude/skills/bdd-steps/SKILL.md @@ -0,0 +1,109 @@ +--- +name: bdd-steps +description: "This skill should be used when the user asks to \"write step definitions\", \"implement BDD steps\", \"generate step code\", \"create Behave steps\", \"implement Given When Then\", \"write Python steps for Gherkin\", \"step definitions for Databricks\", or needs to create Python step implementations for existing Gherkin feature files." +user-invocable: true +--- + +# BDD Steps — Python Step Definition Generation + +Generate Python step definitions for Behave that implement Gherkin steps using the Databricks SDK. Read existing `.feature` files, identify undefined steps, and produce well-typed implementations. + +## When to use + +- Implementing step definitions for new or existing feature files +- Adding Databricks SDK calls to step implementations +- Refactoring step definitions for reusability across features + +## Process + +### 1. Identify undefined steps + +Read the target feature files, then run a dry-run to find undefined steps: + +```bash +uv run behave --dry-run features/.feature 2>&1 +``` + +Behave prints suggested snippets for each undefined step. Use these as the starting point. + +### 2. Write step definitions + +Place step files in `features/steps/` organized by domain: + +| File | Domain | Key SDK imports | +|------|--------|----------------| +| `common_steps.py` | Shared utilities | `WorkspaceClient`, `StatementState` | +| `catalog_steps.py` | Unity Catalog | `catalog.PermissionsChange`, `catalog.Privilege`, `catalog.SecurableType` | +| `pipeline_steps.py` | Lakeflow SDP | `pipelines.PipelineStateInfo` | +| `job_steps.py` | Jobs/Notebooks | `jobs.SubmitTask`, `jobs.NotebookTask`, `jobs.RunLifeCycleState` | +| `app_steps.py` | Databricks Apps | `httpx.Client` for HTTP assertions | +| `sql_steps.py` | SQL/Data quality | `sql.StatementState`, `sql.Disposition` | + +**Step definition structure:** + +```python +from __future__ import annotations + +from behave import given, when, then +from behave.runner import Context + + +@given('a descriptive step pattern with "{parameter}"') +def step_impl(context: Context, parameter: str) -> None: + """Docstring explaining what this step does.""" + # Implementation using context.workspace (set in environment.py) + ... +``` + +Refer to `references/step-library.md` for a comprehensive library of reusable Databricks step definitions covering: +- Workspace connection and SQL execution +- Table/schema existence and row count assertions +- Grant and permission verification +- Pipeline triggering and status polling +- Job submission and completion waiting +- HTTP endpoint testing with SSO header simulation + +### 3. Step writing principles + +**Use `context` for state passing.** Store results in `context` attributes so downstream `Then` steps can assert on them: + +```python +@when('I execute a query on "{table_name}"') +def step_execute(context: Context, table_name: str) -> None: + context.query_result = context.workspace.statement_execution.execute_statement(...) + +@then('the result should have {count:d} rows') +def step_check_rows(context: Context, count: int) -> None: + actual = len(context.query_result.result.data_array or []) + assert actual == count, f"Expected {count}, got {actual}" +``` + +**Type all parameters.** Use Behave's parse types (`{name:d}` for int, `{name:f}` for float) or register custom types. + +**Assertion messages must be diagnostic.** Always include expected vs. actual values: + +```python +assert actual == expected, f"Expected {expected}, got {actual}" +``` + +**Substitute `{test_schema}` references.** Feature files may use `{test_schema}` as a placeholder. Step definitions should resolve it from `context.test_schema`: + +```python +table_fqn = table_name.replace("{test_schema}", context.test_schema) +``` + +**Poll with timeout for async operations.** Jobs, pipelines, and app deployments need polling loops with configurable timeouts. + +### 4. Validate steps compile + +After writing, verify all steps resolve: + +```bash +uv run behave --dry-run +``` + +Zero undefined steps = ready to run. + +## Additional resources + +- **`references/step-library.md`** — Complete reusable step definition library for all Databricks domains diff --git a/.claude/skills/bdd-steps/references/step-library.md b/.claude/skills/bdd-steps/references/step-library.md new file mode 100644 index 00000000..11ddf766 --- /dev/null +++ b/.claude/skills/bdd-steps/references/step-library.md @@ -0,0 +1,660 @@ +# Reusable Step Definition Library + +Complete library of Databricks step definitions for Behave. Organized by domain. Copy relevant sections into `features/steps/` files. + +**Proven patterns used throughout:** + +- Step patterns use **short names** (e.g., `"{table_name}"`), never `{test_schema}.table` in the pattern +- Step code builds FQN internally: `fqn = f"{context.test_schema}.{table_name}"` +- SQL in docstrings uses `{schema}` placeholder, replaced via `context.text.replace("{schema}", context.test_schema)` +- Steps with data tables have a **trailing colon** in the decorator: `@given('... with data:')` +- Grants use **SQL**, not the SDK grants API (which breaks on recent SDK versions) +- Integer parameters use Behave's built-in `{count:d}` format, not custom type parsers + +--- + +## Common Steps (`common_steps.py`) + +Always include these. They provide workspace connection, SQL execution, and basic assertions. + +```python +"""Shared step definitions for Databricks BDD tests.""" +from __future__ import annotations + +import os +from datetime import datetime + +from behave import given, then, step +from behave.runner import Context +from databricks.sdk.service.sql import StatementState + + +# ─── Connection and setup steps ───────────────────────────────── + +@given("a Databricks workspace connection is established") +def step_workspace_connection(context: Context) -> None: + """Initialize workspace client. Usually handled by environment.py.""" + if not hasattr(context, "workspace"): + from databricks.sdk import WorkspaceClient + context.workspace = WorkspaceClient() + me = context.workspace.current_user.me() + context.current_user = me.user_name + + +@given("a test schema is provisioned") +def step_test_schema(context: Context) -> None: + """Verify test schema exists. Usually handled by environment.py.""" + assert hasattr(context, "test_schema"), ( + "No test_schema on context — check environment.py before_all" + ) + + +# ─── SQL execution steps ──────────────────────────────────────── + +@step("I execute the following SQL") +def step_execute_sql_docstring(context: Context) -> None: + """Execute SQL from a docstring (triple-quoted text in feature file). + + In feature files, use {schema} as the placeholder: + When I execute the following SQL + \"\"\" + SELECT * FROM {schema}.customers + \"\"\" + """ + sql = context.text.replace("{schema}", context.test_schema) + context.query_result = _execute_sql(context, sql) + + +@step('I execute SQL "{sql}"') +def step_execute_sql_inline(context: Context, sql: str) -> None: + """Execute inline SQL. The {schema} placeholder is replaced automatically.""" + sql = sql.replace("{schema}", context.test_schema) + context.query_result = _execute_sql(context, sql) + + +# ─── Table existence and row count assertions ─────────────────── + +@then('the table "{table_name}" should exist') +def step_table_exists(context: Context, table_name: str) -> None: + fqn = f"{context.test_schema}.{table_name}" + try: + context.workspace.tables.get(fqn) + except Exception as e: + raise AssertionError(f"Table {fqn} does not exist: {e}") + + +@then('the streaming table "{table_name}" should exist') +def step_streaming_table_exists(context: Context, table_name: str) -> None: + fqn = f"{context.test_schema}.{table_name}" + try: + info = context.workspace.tables.get(fqn) + assert info.table_type is not None, f"{fqn} exists but has no table_type" + except Exception as e: + raise AssertionError(f"Streaming table {fqn} does not exist: {e}") + + +@then('the materialized view "{table_name}" should exist') +def step_mv_exists(context: Context, table_name: str) -> None: + fqn = f"{context.test_schema}.{table_name}" + try: + context.workspace.tables.get(fqn) + except Exception as e: + raise AssertionError(f"Materialized view {fqn} does not exist: {e}") + + +@then('the table "{table_name}" should have {expected:d} rows') +def step_exact_row_count(context: Context, table_name: str, expected: int) -> None: + actual = _count_rows(context, table_name) + assert actual == expected, f"Expected {expected} rows in {table_name}, got {actual}" + + +@then('the table "{table_name}" should have more than {expected:d} rows') +def step_min_row_count(context: Context, table_name: str, expected: int) -> None: + actual = _count_rows(context, table_name) + assert actual > expected, f"Expected more than {expected} rows in {table_name}, got {actual}" + + +@then('the table "{table_name}" should have 0 rows') +def step_empty_table(context: Context, table_name: str) -> None: + actual = _count_rows(context, table_name) + assert actual == 0, f"Expected 0 rows in {table_name}, got {actual}" + + +# ─── Query result assertions ──────────────────────────────────── + +@then("the result should have {expected:d} rows") +def step_result_row_count(context: Context, expected: int) -> None: + rows = context.query_result.result.data_array or [] + actual = len(rows) + assert actual == expected, f"Expected {expected} rows, got {actual}" + + +@then("the result should have more than {expected:d} rows") +def step_result_min_rows(context: Context, expected: int) -> None: + rows = context.query_result.result.data_array or [] + actual = len(rows) + assert actual > expected, f"Expected more than {expected} rows, got {actual}" + + +@then('the first row column "{col}" should be "{value}"') +def step_first_row_value(context: Context, col: str, value: str) -> None: + result = context.query_result + columns = [c.name for c in result.manifest.schema.columns] + col_idx = columns.index(col) + actual = result.result.data_array[0][col_idx] + assert str(actual) == value, f"Expected {col}={value}, got {actual}" + + +# ─── Data setup steps ─────────────────────────────────────────── + +@given('the table "{table_name}" has been loaded') +def step_table_loaded(context: Context, table_name: str) -> None: + """Assert table exists and is not empty.""" + fqn = f"{context.test_schema}.{table_name}" + count = _count_rows(context, table_name) + assert count > 0, f"Table {fqn} exists but is empty" + + +@given('a managed table "{table_name}" exists') +def step_ensure_table_exists(context: Context, table_name: str) -> None: + fqn = f"{context.test_schema}.{table_name}" + try: + context.workspace.tables.get(fqn) + except Exception: + # Create a minimal table + _execute_sql(context, f"CREATE TABLE IF NOT EXISTS {fqn} (id BIGINT)") + context.scenario_cleanup_sql.append(f"DROP TABLE IF EXISTS {fqn}") + + +@given('a managed table "{table_name}" with data:') +def step_create_table_with_data(context: Context, table_name: str) -> None: + """Create a table and populate from the Gherkin data table. + + The trailing colon in the decorator is required — Behave matches it + as part of the step text when a data table follows. + + Example feature file usage: + Given a managed table "customers" with data: + | id | name | region | + | 1 | Acme | APAC | + | 2 | Contoso | EMEA | + """ + fqn = f"{context.test_schema}.{table_name}" + headers = context.table.headings + rows = context.table.rows + + # Infer types (simple heuristic — all STRING) + col_defs = ", ".join(f"{h} STRING" for h in headers) + _execute_sql(context, f"CREATE OR REPLACE TABLE {fqn} ({col_defs})") + context.scenario_cleanup_sql.append(f"DROP TABLE IF EXISTS {fqn}") + + # Insert rows + for row in rows: + values = ", ".join(f"'{cell}'" for cell in row) + _execute_sql(context, f"INSERT INTO {fqn} VALUES ({values})") + + +# ─── Helpers ──────────────────────────────────────────────────── + +def _execute_sql(context: Context, sql: str): + """Execute SQL and return result.""" + result = context.workspace.statement_execution.execute_statement( + warehouse_id=context.warehouse_id, + statement=sql, + wait_timeout="30s", + ) + assert result.status.state == StatementState.SUCCEEDED, ( + f"SQL failed: {result.status.error}\nStatement: {sql[:200]}" + ) + return result + + +def _count_rows(context: Context, table_name: str) -> int: + """Count rows in a table.""" + fqn = f"{context.test_schema}.{table_name}" + result = _execute_sql(context, f"SELECT COUNT(*) AS cnt FROM {fqn}") + return int(result.result.data_array[0][0]) +``` + +--- + +## Catalog Steps (`catalog_steps.py`) + +Uses SQL for grants instead of the SDK grants API. The SDK's `grants.update(securable_type=SecurableType.TABLE, ...)` fails with `SECURABLETYPE.TABLE is not a valid securable type` on recent SDK versions. + +```python +"""Step definitions for Unity Catalog permissions and security. + +Uses SQL for all grant operations. The SDK grants API is unreliable — +SecurableType.TABLE fails on recent databricks-sdk versions. +""" +from __future__ import annotations + +from behave import when, then +from behave.runner import Context +from databricks.sdk.service.sql import StatementState + + +@when('I grant {privilege} on table "{table_name}" to group "{group}"') +def step_grant(context: Context, privilege: str, table_name: str, group: str) -> None: + """Grant a privilege on a table using SQL. + + Example feature file usage: + When I grant SELECT on table "customers" to group "analysts" + """ + fqn = f"{context.test_schema}.{table_name}" + _execute_sql(context, f"GRANT {privilege} ON TABLE {fqn} TO `{group}`") + + +@when('I revoke {privilege} on table "{table_name}" from group "{group}"') +def step_revoke(context: Context, privilege: str, table_name: str, group: str) -> None: + """Revoke a privilege on a table using SQL.""" + fqn = f"{context.test_schema}.{table_name}" + _execute_sql(context, f"REVOKE {privilege} ON TABLE {fqn} FROM `{group}`") + + +@then('the group "{group}" should have {privilege} permission on "{table_name}"') +def step_verify_grant( + context: Context, group: str, privilege: str, table_name: str +) -> None: + """Verify a grant exists using SHOW GRANTS. + + SHOW GRANTS returns PascalCase columns: Principal, ActionType, ObjectType, ObjectKey. + """ + fqn = f"{context.test_schema}.{table_name}" + result = _execute_sql(context, f"SHOW GRANTS ON TABLE {fqn}") + columns = [c.name for c in result.manifest.schema.columns] + principal_idx = columns.index("Principal") + action_idx = columns.index("ActionType") + + found_privs = [] + for row in result.result.data_array or []: + if row[principal_idx] == group: + found_privs.append(row[action_idx]) + + assert privilege in found_privs, ( + f"Expected {group} to have {privilege} on {fqn}, " + f"found: {found_privs}" + ) + + +@then('the group "{group}" should not have {privilege} permission on "{table_name}"') +def step_verify_no_grant( + context: Context, group: str, privilege: str, table_name: str +) -> None: + """Verify a grant does NOT exist using SHOW GRANTS.""" + fqn = f"{context.test_schema}.{table_name}" + result = _execute_sql(context, f"SHOW GRANTS ON TABLE {fqn}") + columns = [c.name for c in result.manifest.schema.columns] + principal_idx = columns.index("Principal") + action_idx = columns.index("ActionType") + + found_privs = [] + for row in result.result.data_array or []: + if row[principal_idx] == group: + found_privs.append(row[action_idx]) + + assert privilege not in found_privs, ( + f"Expected {group} NOT to have {privilege} on {fqn}, " + f"but found: {found_privs}" + ) + + +def _execute_sql(context: Context, sql: str): + """Execute SQL and return result.""" + result = context.workspace.statement_execution.execute_statement( + warehouse_id=context.warehouse_id, + statement=sql, + wait_timeout="30s", + ) + assert result.status.state == StatementState.SUCCEEDED, ( + f"SQL failed: {result.status.error}\nStatement: {sql[:200]}" + ) + return result +``` + +--- + +## Pipeline Steps (`pipeline_steps.py`) + +```python +"""Step definitions for Lakeflow Spark Declarative Pipelines.""" +from __future__ import annotations + +import time + +from behave import given, when, then +from behave.runner import Context + + +@given('a pipeline "{name}" exists targeting "{schema}"') +def step_pipeline_exists(context: Context, name: str, schema: str) -> None: + pipelines = list( + context.workspace.pipelines.list_pipelines(filter=f'name LIKE "{name}"') + ) + if pipelines: + context.pipeline_id = pipelines[0].pipeline_id + else: + result = context.workspace.pipelines.create( + name=name, + target=schema, + catalog=context.test_catalog, + channel="CURRENT", + ) + context.pipeline_id = result.pipeline_id + context.scenario_cleanup_sql.append(None) # Mark for pipeline cleanup + + +@given('the pipeline "{name}" has completed a full refresh') +def step_pipeline_refreshed(context: Context, name: str) -> None: + """Ensure pipeline exists and has been refreshed at least once.""" + pipelines = list( + context.workspace.pipelines.list_pipelines(filter=f'name LIKE "{name}"') + ) + assert pipelines, f"Pipeline '{name}' not found" + context.pipeline_id = pipelines[0].pipeline_id + # Check latest update status + detail = context.workspace.pipelines.get(context.pipeline_id) + assert detail.latest_updates, f"Pipeline '{name}' has never been run" + + +@when("I trigger a full refresh of the pipeline") +def step_full_refresh(context: Context) -> None: + response = context.workspace.pipelines.start_update( + pipeline_id=context.pipeline_id, + full_refresh=True, + ) + context.update_id = response.update_id + + +@when("I trigger an incremental refresh of the pipeline") +def step_incremental_refresh(context: Context) -> None: + response = context.workspace.pipelines.start_update( + pipeline_id=context.pipeline_id, + full_refresh=False, + ) + context.update_id = response.update_id + + +@then("the pipeline update should succeed within {timeout:d} seconds") +def step_pipeline_success(context: Context, timeout: int) -> None: + _wait_for_pipeline(context, timeout, expect_success=True) + + +@then("the pipeline update should fail") +def step_pipeline_fail(context: Context) -> None: + _wait_for_pipeline(context, timeout=300, expect_success=False) + + +@then('the pipeline error should mention {keyword}') +def step_pipeline_error_contains(context: Context, keyword: str) -> None: + events = list(context.workspace.pipelines.list_pipeline_events( + pipeline_id=context.pipeline_id, + max_results=10, + )) + error_messages = " ".join( + str(e.message) for e in events if e.level == "ERROR" + ) + assert keyword.lower() in error_messages.lower(), ( + f"Expected pipeline error to mention '{keyword}', " + f"but errors were: {error_messages[:500]}" + ) + + +def _wait_for_pipeline( + context: Context, timeout: int, expect_success: bool +) -> None: + deadline = time.time() + timeout + while time.time() < deadline: + update = context.workspace.pipelines.get_update( + pipeline_id=context.pipeline_id, + update_id=context.update_id, + ) + state = update.update.state + if state in ("COMPLETED",): + if expect_success: + return + raise AssertionError("Expected pipeline to fail, but it succeeded") + if state in ("FAILED", "CANCELED"): + if not expect_success: + return + raise AssertionError( + f"Pipeline update {state}. Check update {context.update_id}" + ) + time.sleep(15) + raise TimeoutError(f"Pipeline did not complete within {timeout}s") +``` + +--- + +## Job Steps (`job_steps.py`) + +```python +"""Step definitions for Databricks Jobs and notebook runs.""" +from __future__ import annotations + +import time + +from behave import when, then +from behave.runner import Context +from databricks.sdk.service.jobs import ( + NotebookTask, + RunLifeCycleState, + SubmitTask, +) + + +@when('I run the notebook "{path}" with parameters:') +def step_run_notebook(context: Context, path: str) -> None: + """Run a notebook with parameters from a Gherkin data table. + + The trailing colon is required when a data table follows. + + Example feature file usage: + When I run the notebook "/Workspace/tests/etl" with parameters: + | key | value | + | schema | my_schema | + | mode | full | + """ + params = {} + for row in context.table: + value = row["value"].replace("{schema}", context.test_schema) + params[row["key"]] = value + + run = context.workspace.jobs.submit( + run_name=f"behave-{context.scenario.name[:50]}", + tasks=[ + SubmitTask( + task_key="main", + notebook_task=NotebookTask( + notebook_path=path, + base_parameters=params, + ), + ) + ], + ) + context.run_id = run.response.run_id + + +@then('the job should complete with status "{expected}" within {timeout:d} seconds') +def step_job_status(context: Context, expected: str, timeout: int) -> None: + deadline = time.time() + timeout + while time.time() < deadline: + run = context.workspace.jobs.get_run(context.run_id) + state = run.state + if state.life_cycle_state in ( + RunLifeCycleState.TERMINATED, + RunLifeCycleState.INTERNAL_ERROR, + RunLifeCycleState.SKIPPED, + ): + break + time.sleep(10) + else: + raise TimeoutError(f"Run {context.run_id} did not complete within {timeout}s") + + actual = state.result_state.value if state.result_state else "UNKNOWN" + assert actual == expected, ( + f"Expected {expected}, got {actual}. Message: {state.state_message}" + ) +``` + +--- + +## App Steps (`app_steps.py`) + +```python +"""Step definitions for Databricks Apps (FastAPI) testing.""" +from __future__ import annotations + +import subprocess +import os + +import httpx +from behave import given, when, then +from behave.runner import Context + + +@given('the app is running at "{base_url}"') +def step_app_running(context: Context, base_url: str) -> None: + context.app_client = httpx.Client(base_url=base_url, timeout=10) + + +@given('the test user is "{email}"') +def step_test_user(context: Context, email: str) -> None: + context.auth_headers = { + "X-Forwarded-Email": email, + "X-Forwarded-User": email.split("@")[0], + } + + +@when('I GET "{path}"') +def step_get(context: Context, path: str) -> None: + context.response = context.app_client.get(path) + + +@when('I GET "{path}" with auth headers') +def step_get_auth(context: Context, path: str) -> None: + context.response = context.app_client.get(path, headers=context.auth_headers) + + +@when('I GET "{path}" without auth headers') +def step_get_no_auth(context: Context, path: str) -> None: + context.response = context.app_client.get(path) + + +@when('I POST "{path}" with auth headers and body') +def step_post_auth(context: Context, path: str) -> None: + """POST with JSON body from a docstring. + + Example feature file usage: + When I POST "/api/items" with auth headers and body + \"\"\" + {"name": "test-item", "value": 42} + \"\"\" + """ + import json + body = json.loads(context.text) + context.response = context.app_client.post( + path, json=body, headers=context.auth_headers, + ) + + +@then("the response status should be {code:d}") +def step_status_code(context: Context, code: int) -> None: + assert context.response.status_code == code, ( + f"Expected {code}, got {context.response.status_code}: " + f"{context.response.text[:200]}" + ) + + +@then('the response JSON should contain "{key}" with value "{value}"') +def step_json_value(context: Context, key: str, value: str) -> None: + data = context.response.json() + assert key in data, f"Key '{key}' not in response: {list(data.keys())}" + assert str(data[key]) == value, f"Expected {key}='{value}', got '{data[key]}'" + + +@then("the response should be a JSON list") +def step_json_list(context: Context) -> None: + data = context.response.json() + assert isinstance(data, list), f"Expected list, got {type(data).__name__}" + + +# ─── Deployment steps ──────────────────────────────────────────── + +@when('I deploy using Asset Bundles with target "{target}"') +def step_deploy_bundle(context: Context, target: str) -> None: + result = subprocess.run( + ["databricks", "bundle", "deploy", "--target", target], + capture_output=True, + text=True, + env={**dict(os.environ), "DATABRICKS_BUNDLE_ENGINE": "direct"}, + timeout=300, + ) + context.deploy_result = result + + +@then("the deployment should succeed") +def step_deploy_success(context: Context) -> None: + r = context.deploy_result + assert r.returncode == 0, ( + f"Deploy failed (rc={r.returncode}):\n{r.stderr[:500]}" + ) +``` + +--- + +## Shell Command Steps (reusable) + +```python +"""Step definitions for running CLI commands (DABs, databricks CLI).""" +from __future__ import annotations + +import os +import subprocess + +from behave import when, then +from behave.runner import Context + + +@when('I run "{command}" with target "{target}"') +def step_run_command(context: Context, command: str, target: str) -> None: + full_cmd = f"{command} --target {target}" + context.cmd_result = subprocess.run( + full_cmd.split(), + capture_output=True, + text=True, + env={**dict(os.environ), "DATABRICKS_BUNDLE_ENGINE": "direct"}, + timeout=300, + ) + + +@when('I run "{command}" with target "{target}" and auto-approve') +def step_run_command_approve(context: Context, command: str, target: str) -> None: + full_cmd = f"{command} --target {target} --auto-approve" + context.cmd_result = subprocess.run( + full_cmd.split(), + capture_output=True, + text=True, + env={**dict(os.environ), "DATABRICKS_BUNDLE_ENGINE": "direct"}, + timeout=300, + ) + + +@then("the command should exit with code {code:d}") +def step_exit_code(context: Context, code: int) -> None: + actual = context.cmd_result.returncode + assert actual == code, ( + f"Expected exit code {code}, got {actual}.\n" + f"stdout: {context.cmd_result.stdout[:300]}\n" + f"stderr: {context.cmd_result.stderr[:300]}" + ) + + +@then("the command should succeed") +def step_command_success(context: Context) -> None: + assert context.cmd_result.returncode == 0, ( + f"Command failed (rc={context.cmd_result.returncode}):\n" + f"{context.cmd_result.stderr[:500]}" + ) +``` diff --git a/.claude/skills/agent-bricks/1-knowledge-assistants.md b/.claude/skills/databricks-agent-bricks/1-knowledge-assistants.md similarity index 80% rename from .claude/skills/agent-bricks/1-knowledge-assistants.md rename to .claude/skills/databricks-agent-bricks/1-knowledge-assistants.md index d81e351d..3adff469 100644 --- a/.claude/skills/agent-bricks/1-knowledge-assistants.md +++ b/.claude/skills/databricks-agent-bricks/1-knowledge-assistants.md @@ -25,12 +25,12 @@ Before creating a KA, you need documents in a Unity Catalog Volume: - Upload PDFs/text files to a Volume manually or via SDK **Option 2: Generate synthetic documents** -- Use the `unstructured-pdf-generation` skill to create realistic PDF documents +- Use the `databricks-unstructured-pdf-generation` skill to create realistic PDF documents - Each PDF gets a companion JSON file with question/guideline pairs for evaluation ## Creating a Knowledge Assistant -Use the `create_or_update_ka` tool: +Use the `manage_ka` tool with `action="create_or_update"`: - `name`: "HR Policy Assistant" - `volume_path`: "/Volumes/my_catalog/my_schema/raw_data/hr_docs" @@ -52,7 +52,7 @@ After creation, the KA endpoint needs to provision: | `ONLINE` | Ready to use | - | | `OFFLINE` | Not currently running | - | -Use `get_ka` to check the status: +Use `manage_ka` with `action="get"` to check the status: - `tile_id`: "" @@ -76,7 +76,7 @@ These are automatically added when `add_examples_from_volume=true` (default). ### Manual -Examples can also be specified in the `create_or_update_ka` call if needed. +Examples can also be specified in the `manage_ka` create_or_update call if needed. ## Best Practices @@ -101,12 +101,12 @@ Be helpful and professional. When answering: To update the indexed documents: 1. Add/remove/modify files in the volume -2. Call `create_or_update_ka` with the same name and `tile_id` +2. Call `manage_ka` with `action="create_or_update"`, the same name and `tile_id` 3. The KA will re-index the updated content ## Example Workflow -1. **Generate PDF documents** using `unstructured-pdf-generation` skill: +1. **Generate PDF documents** using `databricks-unstructured-pdf-generation` skill: - Creates PDFs in `/Volumes/catalog/schema/raw_data/pdf_documents` - Creates JSON files with question/guideline pairs @@ -120,13 +120,13 @@ To update the indexed documents: 5. **Test the KA** in the Databricks UI -## Using KA in Multi-Agent Supervisors +## Using KA in Supervisor Agents -Knowledge Assistants can be used as agents in a Multi-Agent Supervisor (MAS). Each KA has an associated model serving endpoint. +Knowledge Assistants can be used as agents in a Supervisor Agent (formerly Multi-Agent Supervisor, MAS). Each KA has an associated model serving endpoint. ### Finding the Endpoint Name -Use `get_ka` to retrieve the KA details. The response includes: +Use `manage_ka` with `action="get"` to retrieve the KA details. The response includes: - `tile_id`: The unique identifier for the KA - `name`: The KA name (sanitized) - `endpoint_status`: Current status (ONLINE, PROVISIONING, etc.) @@ -135,26 +135,27 @@ The endpoint name follows this pattern: `ka-{tile_id}-endpoint` ### Finding a KA by Name -If you know the KA name but not the tile_id, use `find_ka_by_name`: +If you know the KA name but not the tile_id, use `manage_ka` with `action="find_by_name"`: ```python -find_ka_by_name(name="HR_Policy_Assistant") +manage_ka(action="find_by_name", name="HR_Policy_Assistant") # Returns: {"found": True, "tile_id": "01abc...", "name": "HR_Policy_Assistant", "endpoint_name": "ka-01abc...-endpoint"} ``` -### Example: Adding KA to MAS +### Example: Adding KA to Supervisor Agent ```python # First, find the KA -ka_result = find_ka_by_name(name="HR_Policy_Assistant") +manage_ka(action="find_by_name", name="HR_Policy_Assistant") -# Then use it in a MAS -create_or_update_mas( - name="Support MAS", +# Then use the tile_id in a Supervisor Agent +manage_mas( + action="create_or_update", + name="Support_MAS", agents=[ { "name": "hr_agent", - "endpoint_name": ka_result["endpoint_name"], + "ka_tile_id": "", "description": "Answers HR policy questions from the employee handbook" } ] diff --git a/.claude/skills/databricks-agent-bricks/2-supervisor-agents.md b/.claude/skills/databricks-agent-bricks/2-supervisor-agents.md new file mode 100644 index 00000000..7121bfcf --- /dev/null +++ b/.claude/skills/databricks-agent-bricks/2-supervisor-agents.md @@ -0,0 +1,394 @@ +# Supervisor Agents (MAS) + +Supervisor Agents orchestrate multiple specialized agents, routing user queries to the most appropriate agent based on the query content. + +## What is a Supervisor Agent? + +A Supervisor Agent (formerly Multi-Agent Supervisor, MAS) acts as a traffic controller for multiple AI agents, routing user queries to the most appropriate agent. It supports five types of agents: + +1. **Knowledge Assistants (KA)**: Document-based Q&A from PDFs/files in Volumes +2. **Genie Spaces**: Natural language to SQL for data exploration +3. **Model Serving Endpoints**: Custom LLM agents, fine-tuned models, RAG applications +4. **Unity Catalog Functions**: Callable UC functions for data operations +5. **External MCP Servers**: JSON-RPC endpoints via UC HTTP Connections for external system integration + +When a user asks a question: +1. **Analyzes** the query to understand the intent +2. **Routes** to the most appropriate specialized agent +3. **Returns** the agent's response to the user + +This allows you to combine multiple specialized agents into a single unified interface. + +## When to Use + +Use a Supervisor Agent when: +- You have multiple specialized agents (billing, technical support, HR, etc.) +- Users shouldn't need to know which agent to ask +- You want to provide a unified conversational experience + +## Prerequisites + +Before creating a Supervisor Agent, you need agents of one or both types: + +**Model Serving Endpoints** (`endpoint_name`): +- Knowledge Assistant (KA) endpoints (e.g., `ka-abc123-endpoint`) +- Custom agents built with LangChain, LlamaIndex, etc. +- Fine-tuned models +- RAG applications + +**Genie Spaces** (`genie_space_id`): +- Existing Genie spaces for SQL-based data exploration +- Great for analytics, metrics, and data-driven questions +- No separate endpoint deployment required - reference the space directly +- To find a Genie space by name, use `find_genie_by_name(display_name="My Genie")` +- **Note**: There is NO system table for Genie spaces - do not try to query `system.ai.genie_spaces` + +## Unity Catalog Functions + +Unity Catalog Functions allow Supervisor Agents to call registered UC functions for data operations. + +### Prerequisites + +- UC Function already exists (use SQL `CREATE FUNCTION` or Python UDF) +- Agent service principal has `EXECUTE` privilege: + ```sql + GRANT EXECUTE ON FUNCTION catalog.schema.function_name TO ``; + ``` + +### Configuration + +```json +{ + "name": "data_enrichment", + "uc_function_name": "sales_analytics.utils.enrich_customer_data", + "description": "Enriches customer records with demographic and purchase history data" +} +``` + +**Field**: `uc_function_name` - Fully-qualified function name in format `catalog.schema.function_name` + +## External MCP Servers + +External MCP Servers enable Supervisor Agents to interact with external systems (ERP, CRM, etc.) via UC HTTP Connections. The MCP server implements a JSON-RPC 2.0 endpoint that exposes tools for the Supervisor Agent to call. + +### Prerequisites + +**1. MCP Server Endpoint**: Your external system must provide a JSON-RPC 2.0 endpoint (e.g., `/api/mcp`) that implements the MCP protocol: + +```python +# Example MCP server tool definition +TOOLS = [ + { + "name": "approve_invoice", + "description": "Approve a specific invoice", + "inputSchema": { + "type": "object", + "properties": { + "invoice_number": {"type": "string", "description": "Invoice number to approve"}, + "approver": {"type": "string", "description": "Name/email of approver"}, + }, + "required": ["invoice_number"], + }, + }, +] + +# JSON-RPC methods: initialize, tools/list, tools/call +``` + +**2. UC HTTP Connection**: Create a Unity Catalog HTTP Connection that points to your MCP endpoint: + +```sql +CREATE CONNECTION my_mcp_connection TYPE HTTP +OPTIONS ( + host 'https://my-app.databricksapps.com', -- Your MCP server URL + port '443', + base_path '/api/mcp', -- Path to JSON-RPC endpoint + client_id '', -- OAuth M2M credentials + client_secret '', + oauth_scope 'all-apis', + token_endpoint 'https://.azuredatabricks.net/oidc/v1/token', + is_mcp_connection 'true' -- REQUIRED: Identifies as MCP connection +); +``` + +**3. Grant Permissions**: Agent service principal needs access to the connection: + +```sql +GRANT USE CONNECTION ON my_mcp_connection TO ``; +``` + +### Configuration + +Reference the UC Connection using the `connection_name` field: + +```python +{ + "name": "external_operations", + "connection_name": "my_mcp_connection", + "description": "Execute external system operations: approve invoices, create records, trigger workflows" +} +``` + +**Field**: `connection_name` - the name of the Unity Catalog HTTP Connection configured as an MCP server + +**Important**: Make the description comprehensive - it guides the Supervisor Agent's routing decisions for when to call this agent. + +### Complete Example: Multi-System Supervisor + +Example showing integration of Genie, KA, and external MCP: + +```python +manage_mas( + action="create_or_update", + name="AP_Invoice_Supervisor", + agents=[ + { + "name": "billing_analyst", + "genie_space_id": "01abc123...", + "description": "SQL analytics on AP invoice data: spending trends, vendor analysis, aging reports" + }, + { + "name": "policy_expert", + "ka_tile_id": "f32c5f73...", + "description": "Answers questions about AP policies, approval workflows, and compliance requirements from policy documents" + }, + { + "name": "ap_operations", + "connection_name": "ap_invoice_mcp", + "description": ( + "Execute AP operations: approve/reject/flag invoices, search invoice details, " + "get vendor summaries, trigger batch workflows. Use for ANY action or write operation." + ) + } + ], + description="AP automation assistant with analytics, policy guidance, and operational actions", + instructions=""" + Route queries as follows: + - Data questions (invoice counts, spend analysis, vendor metrics) → billing_analyst + - Policy questions (thresholds, SLAs, compliance rules) → policy_expert + - Actions (approve, reject, flag, search, workflows) → ap_operations + + When a user asks to approve, reject, or flag an invoice, ALWAYS use ap_operations. + """ +) +``` + +### MCP Connection Testing + +Verify your connection before adding to MAS: + +```sql +-- Test tools/list method +SELECT http_request( + conn => 'my_mcp_connection', + method => 'POST', + path => '', + json => '{"jsonrpc":"2.0","method":"tools/list","id":1}' +); +``` + +### Resources + +- **MCP Protocol Spec**: [Model Context Protocol](https://modelcontextprotocol.io) + +## Creating a Supervisor Agent + +Use the `manage_mas` tool with `action="create_or_update"`: + +- `name`: "Customer Support MAS" +- `agents`: + ```json + [ + { + "name": "policy_agent", + "ka_tile_id": "f32c5f73-466b-4798-b3a0-5396b5ece2a5", + "description": "Answers questions about company policies and procedures from indexed documents" + }, + { + "name": "usage_analytics", + "genie_space_id": "01abc123-def4-5678-90ab-cdef12345678", + "description": "Answers data questions about usage metrics, trends, and statistics" + }, + { + "name": "custom_agent", + "endpoint_name": "my-custom-endpoint", + "description": "Handles specialized queries via custom model endpoint" + } + ] + ``` +- `description`: "Routes customer queries to specialized support agents" +- `instructions`: "Analyze the user's question and route to the most appropriate agent. If unclear, ask for clarification." + +This example shows mixing Knowledge Assistants (policy_agent), Genie spaces (usage_analytics), and custom endpoints (custom_agent). + +## Agent Configuration + +Each agent in the `agents` list needs: + +| Field | Required | Description | +|-------|----------|-------------| +| `name` | Yes | Internal identifier for the agent | +| `description` | Yes | What this agent handles (critical for routing) | +| `ka_tile_id` | One of these | Knowledge Assistant tile ID (for document Q&A agents) | +| `genie_space_id` | One of these | Genie space ID (for SQL-based data agents) | +| `endpoint_name` | One of these | Model serving endpoint name (for custom agents) | +| `uc_function_name` | One of these | Unity Catalog function name in format `catalog.schema.function_name` | +| `connection_name` | One of these | Unity Catalog connection name (for external MCP servers) | + +**Note**: Provide exactly one of: `ka_tile_id`, `genie_space_id`, `endpoint_name`, `uc_function_name`, or `connection_name`. + +To find a KA tile_id, use `manage_ka(action="find_by_name", name="Your KA Name")`. +To find a Genie space_id, use `find_genie_by_name(display_name="Your Genie Name")`. + +### Writing Good Descriptions + +The `description` field is critical for routing. Make it specific: + +**Good descriptions:** +- "Handles billing questions including invoices, payments, refunds, and subscription changes" +- "Answers technical questions about API errors, integration issues, and product bugs" +- "Provides information about HR policies, PTO, benefits, and employee handbook" + +**Bad descriptions:** +- "Billing agent" (too vague) +- "Handles stuff" (not helpful) +- "Technical" (not specific) + +## Provisioning Timeline + +After creation, the Supervisor Agent endpoint needs to provision: + +| Status | Meaning | Duration | +|--------|---------|----------| +| `PROVISIONING` | Creating the supervisor | 2-5 minutes | +| `ONLINE` | Ready to route queries | - | +| `OFFLINE` | Not currently running | - | + +Use `manage_mas` with `action="get"` to check the status. + +## Adding Example Questions + +Example questions help with evaluation and can guide routing optimization: + +```json +{ + "examples": [ + { + "question": "I haven't received my invoice for this month", + "guideline": "Should be routed to billing_agent" + }, + { + "question": "The API is returning a 500 error", + "guideline": "Should be routed to technical_agent" + }, + { + "question": "How many vacation days do I have?", + "guideline": "Should be routed to hr_agent" + } + ] +} +``` + +If the Supervisor Agent is not yet `ONLINE`, examples are queued and added automatically when ready. + +## Best Practices + +### Agent Design + +1. **Specialized agents**: Each agent should have a clear, distinct purpose +2. **Non-overlapping domains**: Avoid agents with similar descriptions +3. **Clear boundaries**: Define what each agent does and doesn't handle + +### Instructions + +Provide routing instructions: + +``` +You are a customer support supervisor. Your job is to route user queries to the right specialist: + +1. For billing, payments, or subscription questions → billing_agent +2. For technical issues, bugs, or API problems → technical_agent +3. For HR, benefits, or policy questions → hr_agent + +If the query is unclear or spans multiple domains, ask the user to clarify. +``` + +### Fallback Handling + +Consider adding a general-purpose agent for queries that don't fit elsewhere: + +```json +{ + "name": "general_agent", + "endpoint_name": "general-support-endpoint", + "description": "Handles general inquiries that don't fit other categories, provides navigation help" +} +``` + +## Example Workflow + +1. **Deploy specialized agents** as model serving endpoints: + - `billing-assistant-endpoint` + - `tech-support-endpoint` + - `hr-assistant-endpoint` + +2. **Create the MAS**: + - Configure agents with clear descriptions + - Add routing instructions + +3. **Wait for ONLINE status** (2-5 minutes) + +4. **Add example questions** for evaluation + +5. **Test routing** with various query types + +## Updating a Supervisor Agent + +To update an existing Supervisor Agent: + +1. **Add/remove agents**: Call `manage_mas` with `action="create_or_update"` and updated `agents` list +2. **Update descriptions**: Change agent descriptions to improve routing +3. **Modify instructions**: Update routing rules + +The tool finds the existing Supervisor Agent by name and updates it. + +## Troubleshooting + +### Queries routed to wrong agent + +- Review and improve agent descriptions +- Make descriptions more specific and distinct +- Add examples that demonstrate correct routing + +### Endpoint not responding + +- Verify each underlying model serving endpoint is running +- Check endpoint logs for errors +- Ensure endpoints accept the expected input format + +### Slow responses + +- Check latency of underlying endpoints +- Consider endpoint scaling settings +- Monitor for cold start issues + +## Advanced: Hierarchical Routing + +For complex scenarios, you can create multiple levels of Supervisor Agents: + +``` +Top-level Supervisor +├── Customer Support Supervisor +│ ├── billing_agent +│ ├── technical_agent +│ └── general_agent +├── Sales Supervisor +│ ├── pricing_agent +│ ├── demo_agent +│ └── contract_agent +└── Internal Supervisor + ├── hr_agent + └── it_helpdesk_agent +``` + +Each sub-supervisor is deployed as an endpoint and configured as an agent in the top-level supervisor. diff --git a/.claude/skills/databricks-agent-bricks/SKILL.md b/.claude/skills/databricks-agent-bricks/SKILL.md new file mode 100644 index 00000000..4aff7acb --- /dev/null +++ b/.claude/skills/databricks-agent-bricks/SKILL.md @@ -0,0 +1,211 @@ +--- +name: databricks-agent-bricks +description: "Create and manage Databricks Agent Bricks: Knowledge Assistants (KA) for document Q&A, Genie Spaces for SQL exploration, and Supervisor Agents (MAS) for multi-agent orchestration. Use when building conversational AI applications on Databricks." +--- + +# Agent Bricks + +Create and manage Databricks Agent Bricks - pre-built AI components for building conversational applications. + +## Overview + +Agent Bricks are three types of pre-built AI tiles in Databricks: + +| Brick | Purpose | Data Source | +|-------|---------|-------------| +| **Knowledge Assistant (KA)** | Document-based Q&A using RAG | PDF/text files in Volumes | +| **Genie Space** | Natural language to SQL | Unity Catalog tables | +| **Supervisor Agent (MAS)** | Multi-agent orchestration | Model serving endpoints | + +## Prerequisites + +Before creating Agent Bricks, ensure you have the required data: + +### For Knowledge Assistants +- **Documents in a Volume**: PDF, text, or other files stored in a Unity Catalog volume +- Generate synthetic documents using the `databricks-unstructured-pdf-generation` skill if needed + +### For Genie Spaces +- **See the `databricks-genie` skill** for comprehensive Genie Space guidance +- Tables in Unity Catalog with the data to explore +- Generate raw data using the `databricks-synthetic-data-generation` skill +- Create tables using the `databricks-spark-declarative-pipelines` skill + +### For Supervisor Agents +- **Model Serving Endpoints**: Deployed agent endpoints (KA endpoints, custom agents, fine-tuned models) +- **Genie Spaces**: Existing Genie spaces can be used directly as agents for SQL-based queries +- Mix and match endpoint-based and Genie-based agents in the same Supervisor Agent + +### For Unity Catalog Functions +- **Existing UC Function**: Function already registered in Unity Catalog +- Agent service principal has `EXECUTE` privilege on the function + +### For External MCP Servers +- **Existing UC HTTP Connection**: Connection configured with `is_mcp_connection: 'true'` +- Agent service principal has `USE CONNECTION` privilege on the connection + +## MCP Tools + +### Knowledge Assistant Tool + +**manage_ka** - Manage Knowledge Assistants (KA) +- `action`: "create_or_update", "get", "find_by_name", or "delete" +- `name`: Name for the KA (for create_or_update, find_by_name) +- `volume_path`: Path to documents (e.g., `/Volumes/catalog/schema/volume/folder`) (for create_or_update) +- `description`: (optional) What the KA does (for create_or_update) +- `instructions`: (optional) How the KA should answer (for create_or_update) +- `tile_id`: The KA tile ID (for get, delete, or update via create_or_update) +- `add_examples_from_volume`: (optional, default: true) Auto-add examples from JSON files (for create_or_update) + +Actions: +- **create_or_update**: Requires `name`, `volume_path`. Optionally pass `tile_id` to update. +- **get**: Requires `tile_id`. Returns tile_id, name, description, endpoint_status, knowledge_sources, examples_count. +- **find_by_name**: Requires `name` (exact match). Returns found, tile_id, name, endpoint_name, endpoint_status. Use this to look up an existing KA when you know the name but not the tile_id. +- **delete**: Requires `tile_id`. + +### Genie Space Tools + +**For comprehensive Genie guidance, use the `databricks-genie` skill.** + +Basic tools available: + +- `create_or_update_genie` - Create or update a Genie Space +- `get_genie` - Get Genie Space details +- `delete_genie` - Delete a Genie Space + +See `databricks-genie` skill for: +- Table inspection workflow +- Sample question best practices +- Curation (instructions, certified queries) + +**IMPORTANT**: There is NO system table for Genie spaces (e.g., `system.ai.genie_spaces` does not exist). To find a Genie space by name, use the `find_genie_by_name` tool. + +### Supervisor Agent Tool + +**manage_mas** - Manage Supervisor Agents (MAS) +- `action`: "create_or_update", "get", "find_by_name", or "delete" +- `name`: Name for the Supervisor Agent (for create_or_update, find_by_name) +- `agents`: List of agent configurations (for create_or_update), each with: + - `name`: Agent identifier (required) + - `description`: What this agent handles - critical for routing (required) + - `ka_tile_id`: Knowledge Assistant tile ID (use for document Q&A agents - recommended for KAs) + - `genie_space_id`: Genie space ID (use for SQL-based data agents) + - `endpoint_name`: Model serving endpoint name (for custom agents) + - `uc_function_name`: Unity Catalog function name in format `catalog.schema.function_name` + - `connection_name`: Unity Catalog connection name (for external MCP servers) + - Note: Provide exactly one of: `ka_tile_id`, `genie_space_id`, `endpoint_name`, `uc_function_name`, or `connection_name` +- `description`: (optional) What the Supervisor Agent does (for create_or_update) +- `instructions`: (optional) Routing instructions for the supervisor (for create_or_update) +- `tile_id`: The Supervisor Agent tile ID (for get, delete, or update via create_or_update) +- `examples`: (optional) List of example questions with `question` and `guideline` fields (for create_or_update) + +Actions: +- **create_or_update**: Requires `name`, `agents`. Optionally pass `tile_id` to update. +- **get**: Requires `tile_id`. Returns tile_id, name, description, endpoint_status, agents, examples_count. +- **find_by_name**: Requires `name` (exact match). Returns found, tile_id, name, endpoint_status, agents_count. Use this to look up an existing Supervisor Agent when you know the name but not the tile_id. +- **delete**: Requires `tile_id`. + +## Typical Workflow + +### 1. Generate Source Data + +Before creating Agent Bricks, generate the required source data: + +**For KA (document Q&A)**: +``` +1. Use `databricks-unstructured-pdf-generation` skill to generate PDFs +2. PDFs are saved to a Volume with companion JSON files (question/guideline pairs) +``` + +**For Genie (SQL exploration)**: +``` +1. Use `databricks-synthetic-data-generation` skill to create raw parquet data +2. Use `databricks-spark-declarative-pipelines` skill to create bronze/silver/gold tables +``` + +### 2. Create the Agent Brick + +Use `manage_ka(action="create_or_update", ...)` or `manage_mas(action="create_or_update", ...)` with your data sources. + +### 3. Wait for Provisioning + +Newly created KA and MAS tiles need time to provision. The endpoint status will progress: +- `PROVISIONING` - Being created (can take 2-5 minutes) +- `ONLINE` - Ready to use +- `OFFLINE` - Not running + +### 4. Add Examples (Automatic) + +For KA, if `add_examples_from_volume=true`, examples are automatically extracted from JSON files in the volume and added once the endpoint is `ONLINE`. + +## Best Practices + +1. **Use meaningful names**: Names are sanitized automatically (spaces become underscores) +2. **Provide descriptions**: Helps users understand what the brick does +3. **Add instructions**: Guide the AI's behavior and tone +4. **Include sample questions**: Shows users how to interact with the brick +5. **Use the workflow**: Generate data first, then create the brick + +## Example: Multi-Modal Supervisor Agent + +```python +manage_mas( + action="create_or_update", + name="Enterprise Support Supervisor", + agents=[ + { + "name": "knowledge_base", + "ka_tile_id": "f32c5f73-466b-...", + "description": "Answers questions about company policies, procedures, and documentation from indexed files" + }, + { + "name": "analytics_engine", + "genie_space_id": "01abc123...", + "description": "Runs SQL analytics on usage metrics, performance stats, and operational data" + }, + { + "name": "ml_classifier", + "endpoint_name": "custom-classification-endpoint", + "description": "Classifies support tickets and predicts resolution time using custom ML model" + }, + { + "name": "data_enrichment", + "uc_function_name": "support.utils.enrich_ticket_data", + "description": "Enriches support ticket data with customer history and context" + }, + { + "name": "ticket_operations", + "connection_name": "ticket_system_mcp", + "description": "Creates, updates, assigns, and closes support tickets in external ticketing system" + } + ], + description="Comprehensive enterprise support agent with knowledge retrieval, analytics, ML, data enrichment, and ticketing operations", + instructions=""" + Route queries as follows: + 1. Policy/procedure questions → knowledge_base + 2. Data analysis requests → analytics_engine + 3. Ticket classification → ml_classifier + 4. Customer context lookups → data_enrichment + 5. Ticket creation/updates → ticket_operations + + If a query spans multiple domains, chain agents: + - First gather information (analytics_engine or knowledge_base) + - Then take action (ticket_operations) + """ +) +``` + +## Related Skills + +- **[databricks-genie](../databricks-genie/SKILL.md)** - Comprehensive Genie Space creation, curation, and Conversation API guidance +- **[databricks-unstructured-pdf-generation](../databricks-unstructured-pdf-generation/SKILL.md)** - Generate synthetic PDFs to feed into Knowledge Assistants +- **[databricks-synthetic-data-generation](../databricks-synthetic-data-generation/SKILL.md)** - Create raw data for Genie Space tables +- **[databricks-spark-declarative-pipelines](../databricks-spark-declarative-pipelines/SKILL.md)** - Build bronze/silver/gold tables consumed by Genie Spaces +- **[databricks-model-serving](../databricks-model-serving/SKILL.md)** - Deploy custom agent endpoints used as MAS agents +- **[databricks-vector-search](../databricks-vector-search/SKILL.md)** - Build vector indexes for RAG applications paired with KAs + +## See Also + +- `1-knowledge-assistants.md` - Detailed KA patterns and examples +- `databricks-genie` skill - Detailed Genie patterns, curation, and examples +- `2-supervisor-agents.md` - Detailed MAS patterns and examples diff --git a/.claude/skills/aibi-dashboards/SKILL.md b/.claude/skills/databricks-aibi-dashboards/SKILL.md similarity index 98% rename from .claude/skills/aibi-dashboards/SKILL.md rename to .claude/skills/databricks-aibi-dashboards/SKILL.md index bb846b05..41dbeec6 100644 --- a/.claude/skills/aibi-dashboards/SKILL.md +++ b/.claude/skills/databricks-aibi-dashboards/SKILL.md @@ -1,6 +1,6 @@ --- -name: aibi-dashboards -description: "Create AI/BI dashboards. CRITICAL: You MUST test ALL SQL queries via execute_sql BEFORE deploying. Follow guidelines strictly." +name: databricks-aibi-dashboards +description: "Create Databricks AI/BI dashboards. CRITICAL: You MUST test ALL SQL queries via execute_sql BEFORE deploying. Follow guidelines strictly." --- # AI/BI Dashboard Skill @@ -915,3 +915,9 @@ print(result["url"]) - Multiple items in the `lines` array are **concatenated**, not displayed on separate lines - Use **separate text widgets** for title and subtitle at different y positions - Example: title at y=0 with height=1, subtitle at y=1 with height=1 + +## Related Skills + +- **[databricks-unity-catalog](../databricks-unity-catalog/SKILL.md)** - for querying the underlying data and system tables +- **[databricks-spark-declarative-pipelines](../databricks-spark-declarative-pipelines/SKILL.md)** - for building the data pipelines that feed dashboards +- **[databricks-jobs](../databricks-jobs/SKILL.md)** - for scheduling dashboard data refreshes diff --git a/.claude/skills/databricks-app-apx/SKILL.md b/.claude/skills/databricks-app-apx/SKILL.md index 54c2767d..2ee96baa 100644 --- a/.claude/skills/databricks-app-apx/SKILL.md +++ b/.claude/skills/databricks-app-apx/SKILL.md @@ -157,7 +157,7 @@ Manually verify in browser: ### Deploy to Databricks -Use DABs to deploy your APX application to Databricks. See the `asset-bundles` skill for complete deployment guidance. +Use DABs to deploy your APX application to Databricks. See the `databricks-asset-bundles` skill for complete deployment guidance. ### Monitor Application Logs @@ -244,3 +244,10 @@ Create two markdown files: - **[best-practices.md](best-practices.md)** - Best practices, anti-patterns, debugging Read these files only when actively writing that type of code or debugging issues. + +## Related Skills + +- **[databricks-app-python](../databricks-app-python/SKILL.md)** - for Streamlit, Dash, Gradio, or Flask apps +- **[databricks-asset-bundles](../databricks-asset-bundles/SKILL.md)** - deploying APX apps via DABs +- **[databricks-python-sdk](../databricks-python-sdk/SKILL.md)** - backend SDK integration +- **[databricks-lakebase-provisioned](../databricks-lakebase-provisioned/SKILL.md)** - adding persistent PostgreSQL state to apps diff --git a/.claude/skills/databricks-app-python/1-authorization.md b/.claude/skills/databricks-app-python/1-authorization.md new file mode 100644 index 00000000..0a84f629 --- /dev/null +++ b/.claude/skills/databricks-app-python/1-authorization.md @@ -0,0 +1,150 @@ +# Authorization for Databricks Apps + +Databricks Apps supports two complementary authorization models. Use one or both depending on your app's needs. + +**Docs**: https://docs.databricks.com/aws/en/dev-tools/databricks-apps/auth + +--- + +## App Authorization (Service Principal) + +Each app gets a dedicated service principal. Databricks auto-injects credentials: + +- `DATABRICKS_CLIENT_ID` — OAuth client ID +- `DATABRICKS_CLIENT_SECRET` — OAuth client secret + +**You don't need to read these manually.** The SDK `Config()` detects them automatically: + +```python +from databricks.sdk.core import Config +from databricks import sql + +cfg = Config() # Auto-detects SP credentials from environment +conn = sql.connect( + server_hostname=cfg.host, + http_path="/sql/1.0/warehouses/", + credentials_provider=lambda: cfg.authenticate, +) +``` + +**Use for**: background tasks, shared data access, logging, external service calls. + +**Limitation**: all users share the same permissions — no per-user access control. + +--- + +## User Authorization (On-Behalf-Of) + +Allows the app to act with the identity of the current user. Databricks forwards the user's access token to the app via HTTP header. + +**Use for**: user-specific data queries, Unity Catalog row/column filters, audit trails. + +**Prerequisite**: workspace admin must enable user authorization (Public Preview). Add scopes when creating/editing the app in the UI. + +### Retrieving the User Token Per Framework + +```python +# Streamlit +import streamlit as st +user_token = st.context.headers.get("x-forwarded-access-token") + +# Dash / Flask +from flask import request +user_token = request.headers.get("x-forwarded-access-token") + +# Gradio +import gradio as gr +def handler(message, request: gr.Request): + user_token = request.headers.get("x-forwarded-access-token") + +# FastAPI +from fastapi import Request +async def endpoint(request: Request): + user_token = request.headers.get("x-forwarded-access-token") + +# Reflex +user_token = session.http_conn.headers.get("x-forwarded-access-token") +``` + +### Querying with User Token + +```python +from databricks.sdk.core import Config +from databricks import sql + +cfg = Config() +user_token = get_user_token() # Per-framework method above + +conn = sql.connect( + server_hostname=cfg.host, + http_path="/sql/1.0/warehouses/", + access_token=user_token, # User's token, not SP credentials +) +``` + +--- + +## Combining Both Models + +Use app auth for shared operations and user auth for user-specific data: + +```python +from databricks.sdk.core import Config +from databricks import sql + +cfg = Config() + +def get_app_connection(warehouse_http_path: str): + """App auth — shared data, logging, background tasks.""" + return sql.connect( + server_hostname=cfg.host, + http_path=warehouse_http_path, + credentials_provider=lambda: cfg.authenticate, + ) + +def get_user_connection(warehouse_http_path: str, user_token: str): + """User auth — respects Unity Catalog row/column filters.""" + return sql.connect( + server_hostname=cfg.host, + http_path=warehouse_http_path, + access_token=user_token, + ) +``` + +--- + +## OAuth Scopes + +When adding user authorization, select only the scopes your app needs: + +| Scope | Grants Access To | +|-------|-----------------| +| `sql` | SQL warehouse queries | +| `files.files` | Files and directories | +| `dashboards.genie` | Genie spaces | +| `iam.access-control:read` | Access control (default) | +| `iam.current-user:read` | Current user identity (default) | + +**Best practice**: request minimum required scopes. Databricks blocks access outside approved scopes even if the user has broader permissions. + +--- + +## When to Use Which + +| Scenario | Model | +|----------|-------| +| All users see same data | App auth only | +| User-specific row/column filters | User auth | +| Background jobs, logging | App auth | +| Audit trail per user | User auth | +| Mixed shared + personal data | Both | + +--- + +## Best Practices + +- Never log, print, or write tokens to files +- Grant service principal minimum required permissions on resources +- Use `CAN MANAGE` only for trusted developers; `CAN USE` for app users +- Enforce peer review for app code before production deployment +- Cookbook auth examples: [Streamlit](https://apps-cookbook.dev/docs/streamlit/authentication/users_get_current) · [Dash](https://apps-cookbook.dev/docs/dash/authentication/users_get_current) · [Reflex](https://apps-cookbook.dev/docs/reflex/authentication/users_get_current) diff --git a/.claude/skills/databricks-app-python/2-app-resources.md b/.claude/skills/databricks-app-python/2-app-resources.md new file mode 100644 index 00000000..dd911c4b --- /dev/null +++ b/.claude/skills/databricks-app-python/2-app-resources.md @@ -0,0 +1,120 @@ +# App Resources and Communication Strategies + +Databricks Apps integrate with platform resources via managed connections. Use resources instead of hardcoding IDs for portability and security. + +**Docs**: https://docs.databricks.com/aws/en/dev-tools/databricks-apps/resources + +--- + +## Supported Resource Types + +| Resource | Default Key | Permissions | Use Case | +|----------|-------------|-------------|----------| +| SQL warehouse | `sql-warehouse` | Can use, Can manage | Querying Delta tables | +| Lakebase database | `database` | Can connect and create | Low-latency transactional data | +| Model serving endpoint | `serving-endpoint` | Can view, Can query, Can manage | AI/ML inference | +| Secret | `secret` | Can read, Can write, Can manage | API keys, tokens | +| Unity Catalog volume | `volume` | Can read, Can read and write | File storage | +| Vector search index | `vector-search-index` | Can select | Semantic search | +| Genie space | `genie-space` | Can view, Can run, Can edit | Natural language analytics | +| UC connection | `connection` | Use Connection | External data sources | +| UC function | `function` | Can execute | SQL/Python functions | +| MLflow experiment | `experiment` | Can read, Can edit | ML experiment tracking | +| Lakeflow job | `job` | Can view, Can manage run | Data pipelines | + +--- + +## Configuring Resources in app.yaml + +Use `valueFrom` to reference resources — never hardcode IDs: + +```yaml +env: + - name: DATABRICKS_WAREHOUSE_ID + valueFrom: sql-warehouse + + - name: SERVING_ENDPOINT_NAME + valueFrom: serving-endpoint + + - name: DB_CONNECTION_STRING + valueFrom: database +``` + +Add resources via the Databricks Apps UI when creating or editing an app: +1. Navigate to Configure step +2. Click **+ Add resource** +3. Select resource type and set permissions +4. Assign a key (referenced in `valueFrom`) + +--- + +## Communication Strategies + +Choose your data backend based on access pattern: + +| Strategy | When to Use | Library | Connection Pattern | +|----------|-------------|---------|-------------------| +| **SQL Warehouse** | Analytical queries on Delta tables | `databricks-sql-connector` | `sql.connect()` with `Config()` | +| **Lakebase (PostgreSQL)** | Low-latency transactional CRUD | `psycopg2` / `asyncpg` | Standard PostgreSQL via auto-injected env vars | +| **Databricks SDK** | Platform API calls (jobs, clusters, UC) | `databricks-sdk` | `WorkspaceClient()` | +| **Model Serving** | AI/ML inference requests | `requests` or SDK | REST call to serving endpoint | +| **Unity Catalog Functions** | Server-side compute (SQL/Python UDFs) | `databricks-sql-connector` | Execute via SQL warehouse | + +### SQL Warehouse Pattern + +```python +import os +from databricks.sdk.core import Config +from databricks import sql + +cfg = Config() +conn = sql.connect( + server_hostname=cfg.host, + http_path=f"/sql/1.0/warehouses/{os.getenv('DATABRICKS_WAREHOUSE_ID')}", + credentials_provider=lambda: cfg.authenticate, +) + +with conn.cursor() as cursor: + cursor.execute("SELECT * FROM catalog.schema.table LIMIT 100") + rows = cursor.fetchall() +``` + +### Model Serving Pattern + +```python +import os, requests +from databricks.sdk.core import Config + +cfg = Config() +headers = cfg.authenticate() +headers["Content-Type"] = "application/json" + +endpoint = os.getenv("SERVING_ENDPOINT_NAME") +response = requests.post( + f"https://{cfg.host}/serving-endpoints/{endpoint}/invocations", + headers=headers, + json={"inputs": [{"prompt": "Hello"}]}, +) +result = response.json() +``` + +### SDK Pattern + +```python +from databricks.sdk import WorkspaceClient + +w = WorkspaceClient() # Auto-detects credentials +for cluster in w.clusters.list(): + print(f"{cluster.cluster_name}: {cluster.state}") +``` + +For Lakebase patterns, see [5-lakebase.md](5-lakebase.md). + +--- + +## Best Practices + +- Always use `valueFrom` — keeps apps portable between environments +- Grant service principal minimum required permissions (e.g., `CAN USE` not `CAN MANAGE` for SQL warehouse) +- Use Lakebase for transactional workloads; SQL warehouse for analytical workloads +- For external services, use UC connections or secrets (never hardcode API keys) diff --git a/.claude/skills/databricks-app-python/3-frameworks.md b/.claude/skills/databricks-app-python/3-frameworks.md new file mode 100644 index 00000000..cb1ef87e --- /dev/null +++ b/.claude/skills/databricks-app-python/3-frameworks.md @@ -0,0 +1,246 @@ +# Supported Frameworks + +All frameworks below are **pre-installed** in the Databricks Apps runtime. Claude already knows how to use them — this guide covers only **Databricks-specific** patterns. For full examples and recipes, see the **[Databricks Apps Cookbook](https://apps-cookbook.dev/)**. + +--- + +## Dash + +**Best for**: Production dashboards, BI tools, complex interactive visualizations. + +**Critical**: Always use `dash-bootstrap-components` for layout and styling. + +```python +import dash +import dash_bootstrap_components as dbc + +app = dash.Dash( + __name__, + external_stylesheets=[dbc.themes.BOOTSTRAP, dbc.icons.FONT_AWESOME], + title="My Dashboard", +) +``` + +| Detail | Value | +|--------|-------| +| Pre-installed version | 2.18.1 | +| app.yaml command | `["python", "app.py"]` | +| Default port | 8050 (set `DATABRICKS_APP_PORT=8080` or use `app.run(port=8080)`) | +| Auth header | `request.headers.get('x-forwarded-access-token')` (Flask under the hood) | + +**Databricks tips**: +- Use `dbc.themes.BOOTSTRAP` and `dbc.icons.FONT_AWESOME` for consistent styling +- Use Bootstrap badge color names (`"success"`, `"danger"`), not hex colors, for `dbc.Badge` +- Use `prevent_initial_call=True` on expensive callbacks +- Use `dcc.Store` for client-side caching + +**Cookbook**: [apps-cookbook.dev/docs/category/dash](https://apps-cookbook.dev/docs/category/dash) — tables, volumes, AI/ML, workflows, dashboards, compute, auth, external services. + +--- + +## Streamlit + +**Best for**: Rapid prototyping, data science apps, internal tools, notebook-to-app workflow. + +**Critical**: Always use `@st.cache_resource` for database connections. + +```python +import streamlit as st +from databricks.sdk.core import Config +from databricks import sql + +st.set_page_config(page_title="My App", layout="wide") # Must be first! + +@st.cache_resource(ttl=300) +def get_connection(): + cfg = Config() + return sql.connect( + server_hostname=cfg.host, + http_path="/sql/1.0/warehouses/", + credentials_provider=lambda: cfg.authenticate, + ) +``` + +| Detail | Value | +|--------|-------| +| Pre-installed version | 1.38.0 | +| app.yaml command | `["streamlit", "run", "app.py"]` | +| Auth header | `st.context.headers.get('x-forwarded-access-token')` | + +**Databricks tips**: +- `st.set_page_config()` must be the **first** Streamlit command +- `@st.cache_resource` for connections/models; `@st.cache_data(ttl=...)` for query results +- Use `st.form()` to batch inputs and prevent reruns on every keystroke +- Use `st.column_config` for formatted DataFrames (currency, dates) + +**Cookbook**: [apps-cookbook.dev/docs/category/streamlit](https://apps-cookbook.dev/docs/category/streamlit) — tables, volumes, AI/ML, workflows, visualizations, dashboards, compute, auth, external services. + +--- + +## Gradio + +**Best for**: ML model demos, chat interfaces, image/audio/video processing UIs. + +**Critical**: Use `gr.Request` parameter to access auth headers. + +```python +import gradio as gr +import requests +from databricks.sdk.core import Config + +cfg = Config() + +def predict(message, request: gr.Request): + user_token = request.headers.get("x-forwarded-access-token") + # Query model serving endpoint + headers = {**cfg.authenticate(), "Content-Type": "application/json"} + resp = requests.post( + f"https://{cfg.host}/serving-endpoints/my-model/invocations", + headers=headers, + json={"inputs": [{"prompt": message}]}, + ) + return resp.json()["predictions"][0] + +demo = gr.Interface(fn=predict, inputs="text", outputs="text") +demo.launch(server_name="0.0.0.0", server_port=8080) +``` + +| Detail | Value | +|--------|-------| +| Pre-installed version | 4.44.0 | +| app.yaml command | `["python", "app.py"]` | +| Default port | 7860 (override with `server_port=8080` or `GRADIO_SERVER_PORT=8080`) | +| Auth header | `request.headers.get('x-forwarded-access-token')` via `gr.Request` | + +**Databricks tips**: +- Natural fit for model serving endpoint integration +- Use `gr.ChatInterface` for conversational AI demos +- Use `gr.Blocks` for complex multi-component layouts + +**Docs**: [gradio.app/docs](https://www.gradio.app/docs) + +--- + +## Flask + +**Best for**: Custom REST APIs, lightweight web apps, webhook receivers. + +**Critical**: Deploy with Gunicorn — never use Flask's dev server in production. + +```python +from flask import Flask, request, jsonify +from databricks.sdk.core import Config +from databricks import sql + +app = Flask(__name__) +cfg = Config() + +@app.route("/api/data") +def get_data(): + conn = sql.connect( + server_hostname=cfg.host, + http_path="/sql/1.0/warehouses/", + credentials_provider=lambda: cfg.authenticate, + ) + with conn.cursor() as cursor: + cursor.execute("SELECT * FROM catalog.schema.table LIMIT 10") + return jsonify(cursor.fetchall()) +``` + +| Detail | Value | +|--------|-------| +| Pre-installed version | 3.0.3 | +| app.yaml command | `["gunicorn", "app:app", "-w", "4", "-b", "0.0.0.0:8080"]` | +| Auth header | `request.headers.get('x-forwarded-access-token')` | + +**Databricks tips**: +- Use connection pooling (Flask doesn't cache connections like Streamlit) +- Gunicorn workers (`-w 4`) handle concurrent requests +- Use `request.headers` for user authorization tokens + +--- + +## FastAPI + +**Best for**: Modern async APIs, auto-generated OpenAPI/Swagger docs, high-performance backends. + +**Critical**: Deploy with uvicorn. + +```python +from fastapi import FastAPI, Request +from databricks.sdk.core import Config +from databricks import sql + +app = FastAPI(title="My API") +cfg = Config() + +@app.get("/api/data") +async def get_data(request: Request): + user_token = request.headers.get("x-forwarded-access-token") + conn = sql.connect( + server_hostname=cfg.host, + http_path="/sql/1.0/warehouses/", + access_token=user_token, + ) + with conn.cursor() as cursor: + cursor.execute("SELECT * FROM catalog.schema.table LIMIT 10") + return cursor.fetchall() +``` + +| Detail | Value | +|--------|-------| +| Pre-installed version | 0.115.0 | +| app.yaml command | `["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8080"]` | +| Auth header | `request.headers.get('x-forwarded-access-token')` via `Request` | + +**Databricks tips**: +- Auto-generates OpenAPI docs at `/docs` (Swagger) and `/redoc` +- Databricks SQL connector is synchronous — use `asyncio.to_thread()` for async endpoints +- Good choice for API backends that serve APX (FastAPI + React) apps + +**Cookbook**: [apps-cookbook.dev/docs/category/fastapi](https://apps-cookbook.dev/docs/category/fastapi) — getting started, endpoint examples. + +--- + +## Reflex + +**Best for**: Full-stack Python apps with reactive UIs, no JavaScript required. + +```python +import reflex as rx +from databricks.sdk.core import Config + +cfg = Config() + +class State(rx.State): + data: list[dict] = [] + + def load_data(self): + from databricks import sql + conn = sql.connect( + server_hostname=cfg.host, + http_path="/sql/1.0/warehouses/", + credentials_provider=lambda: cfg.authenticate, + ) + with conn.cursor() as cursor: + cursor.execute("SELECT * FROM catalog.schema.table LIMIT 10") + self.data = [dict(zip([d[0] for d in cursor.description], row)) for row in cursor.fetchall()] +``` + +| Detail | Value | +|--------|-------| +| app.yaml command | `["reflex", "run", "--env", "prod"]` | +| Auth header | `session.http_conn.headers.get('x-forwarded-access-token')` | + +**Cookbook**: [apps-cookbook.dev/docs/category/reflex](https://apps-cookbook.dev/docs/category/reflex) — tables, volumes, AI/ML, workflows, dashboards, compute, auth, external services. + +--- + +## Common: All Frameworks + +- All frameworks are **pre-installed** — no need to add them to `requirements.txt` +- Add only additional packages your app needs to `requirements.txt` +- SDK `Config()` auto-detects credentials from injected environment variables +- Databricks Apps expects apps to listen on **port 8080** (configure your framework accordingly) +- For framework-specific deployment commands, see [4-deployment.md](4-deployment.md) +- For authorization integration, see [1-authorization.md](1-authorization.md) diff --git a/.claude/skills/databricks-app-python/4-deployment.md b/.claude/skills/databricks-app-python/4-deployment.md new file mode 100644 index 00000000..688f1f21 --- /dev/null +++ b/.claude/skills/databricks-app-python/4-deployment.md @@ -0,0 +1,142 @@ +# Deploying Databricks Apps + +Three deployment options: Databricks CLI (simplest), Asset Bundles (multi-environment), or MCP tools (programmatic). + +**Cookbook deployment guide**: https://apps-cookbook.dev/docs/deploy + +--- + +## Option 1: Databricks CLI + +**Best for**: quick deployments, single environment. + +### Step 1: Create app.yaml + +```yaml +command: + - "python" # Adjust per framework — see table below + - "app.py" + +env: + - name: DATABRICKS_WAREHOUSE_ID + valueFrom: sql-warehouse + - name: USE_MOCK_BACKEND + value: "false" +``` + +### app.yaml Commands Per Framework + +| Framework | Command | +|-----------|---------| +| Dash | `["python", "app.py"]` | +| Streamlit | `["streamlit", "run", "app.py"]` | +| Gradio | `["python", "app.py"]` | +| Flask | `["gunicorn", "app:app", "-w", "4", "-b", "0.0.0.0:8080"]` | +| FastAPI | `["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8080"]` | +| Reflex | `["reflex", "run", "--env", "prod"]` | + +### Step 2: Create and Deploy + +```bash +# Create the app +databricks apps create + +# Upload source code +databricks workspace mkdirs /Workspace/Users//apps/ +databricks workspace import-dir . /Workspace/Users//apps/ + +# Deploy +databricks apps deploy \ + --source-code-path /Workspace/Users//apps/ + +# Add resources via UI (SQL warehouse, Lakebase, etc.) + +# Check status and URL +databricks apps get +``` + +### Redeployment + +```bash +databricks workspace delete /Workspace/Users//apps/ --recursive +databricks workspace import-dir . /Workspace/Users//apps/ +databricks apps deploy \ + --source-code-path /Workspace/Users//apps/ +``` + +--- + +## Option 2: Databricks Asset Bundles (DABs) + +**Best for**: multi-environment deployments (dev/staging/prod), version-controlled infrastructure. + +**Recommended workflow**: deploy via CLI first to validate, then generate bundle config. + +### Generate Bundle from Existing App + +```bash +databricks bundle generate app \ + --existing-app-name \ + --key +``` + +This creates: +- `resources/.app.yml` — app resource definition +- `src/app/` — app source files including `app.yaml` + +### Deploy with Bundles + +```bash +# Validate +databricks bundle validate -t dev + +# Deploy +databricks bundle deploy -t dev + +# Start the app (required after deployment) +databricks bundle run -t dev + +# Production +databricks bundle deploy -t prod +databricks bundle run -t prod +``` + +**Key difference from other resources**: environment variables go in `src/app/app.yaml`, not `databricks.yml`. + +For complete DABs guidance, use the **databricks-asset-bundles** skill. + +--- + +## Option 3: MCP Tools + +For programmatic app lifecycle management, see [6-mcp-approach.md](6-mcp-approach.md). + +--- + +## Post-Deployment + +### Check Logs + +```bash +databricks apps logs +``` + +**Key patterns in logs**: +- `[SYSTEM]` — deployment status, file updates, dependency installation +- `[APP]` — application output, framework messages +- `Deployment successful` — app deployed correctly +- `App started successfully` — app is running +- `Error:` — check stack traces + +### Verify + +1. Access app URL (from `databricks apps get `) +2. Check all pages load correctly +3. Verify data connectivity (look for backend initialization messages in logs) +4. Test user authorization flow if enabled + +### Configure Permissions + +- Set `CAN USE` for approved users/groups +- Set `CAN MANAGE` only for trusted developers +- Verify service principal has required resource permissions diff --git a/.claude/skills/databricks-app-python/5-lakebase.md b/.claude/skills/databricks-app-python/5-lakebase.md new file mode 100644 index 00000000..c6615609 --- /dev/null +++ b/.claude/skills/databricks-app-python/5-lakebase.md @@ -0,0 +1,141 @@ +# Lakebase (PostgreSQL) Connectivity + +Lakebase provides low-latency transactional storage for Databricks Apps via a managed PostgreSQL interface. + +**Docs**: https://docs.databricks.com/aws/en/dev-tools/databricks-apps/lakebase + +--- + +## When to Use Lakebase + +| Use Case | Recommended Backend | +|----------|-------------------| +| Analytical queries on Delta tables | SQL Warehouse | +| Low-latency transactional CRUD | **Lakebase** | +| App-specific metadata/config | **Lakebase** | +| User session data | **Lakebase** | +| Large-scale data exploration | SQL Warehouse | + +--- + +## Setup + +1. Add Lakebase as an app resource in the Databricks UI (resource type: **Lakebase database**) +2. Databricks auto-injects PostgreSQL connection env vars: + +| Variable | Description | +|----------|-------------| +| `PGHOST` | Database hostname | +| `PGDATABASE` | Database name | +| `PGUSER` | PostgreSQL role (created per app) | +| `PGPASSWORD` | Role password | +| `PGPORT` | Port (typically 5432) | + +3. Reference in `app.yaml`: + +```yaml +env: + - name: DB_CONNECTION_STRING + valueFrom: + resource: database +``` + +--- + +## Connection Patterns + +### psycopg2 (Synchronous) + +```python +import os +import psycopg2 + +conn = psycopg2.connect( + host=os.getenv("PGHOST"), + database=os.getenv("PGDATABASE"), + user=os.getenv("PGUSER"), + password=os.getenv("PGPASSWORD"), + port=os.getenv("PGPORT", "5432"), +) + +with conn.cursor() as cur: + cur.execute("SELECT * FROM my_table LIMIT 10") + rows = cur.fetchall() + +conn.close() +``` + +### asyncpg (Asynchronous) + +```python +import os +import asyncpg + +async def get_data(): + conn = await asyncpg.connect( + host=os.getenv("PGHOST"), + database=os.getenv("PGDATABASE"), + user=os.getenv("PGUSER"), + password=os.getenv("PGPASSWORD"), + port=int(os.getenv("PGPORT", "5432")), + ) + rows = await conn.fetch("SELECT * FROM my_table LIMIT 10") + await conn.close() + return rows +``` + +### SQLAlchemy + +```python +import os +from sqlalchemy import create_engine + +DATABASE_URL = ( + f"postgresql://{os.getenv('PGUSER')}:{os.getenv('PGPASSWORD')}" + f"@{os.getenv('PGHOST')}:{os.getenv('PGPORT', '5432')}" + f"/{os.getenv('PGDATABASE')}" +) + +engine = create_engine(DATABASE_URL) +``` + +--- + +## Streamlit with Lakebase + +```python +import streamlit as st +import psycopg2 + +@st.cache_resource +def get_db_connection(): + return psycopg2.connect( + host=os.getenv("PGHOST"), + database=os.getenv("PGDATABASE"), + user=os.getenv("PGUSER"), + password=os.getenv("PGPASSWORD"), + ) +``` + +--- + +## Critical: requirements.txt + +`psycopg2` and `asyncpg` are **NOT pre-installed** in the Databricks Apps runtime. You **MUST** include them in `requirements.txt` or the app will crash on startup: + +``` +psycopg2-binary +``` + +For async apps: +``` +asyncpg +``` + +**This is the most common cause of Lakebase app failures.** + +## Notes + +- Lakebase is in **Public Preview** +- Each app gets its own PostgreSQL role with `Can connect and create` permission +- Lakebase is ideal alongside SQL warehouse: use Lakebase for app state, SQL warehouse for analytics diff --git a/.claude/skills/databricks-app-python/6-mcp-approach.md b/.claude/skills/databricks-app-python/6-mcp-approach.md new file mode 100644 index 00000000..23ffb67d --- /dev/null +++ b/.claude/skills/databricks-app-python/6-mcp-approach.md @@ -0,0 +1,94 @@ +# MCP Tools for App Lifecycle + +Use MCP tools to create, deploy, and manage Databricks Apps programmatically. This mirrors the CLI workflow but can be invoked by AI agents. + +--- + +## Workflow + +### Step 1: Write App Files Locally + +Create your app files in a local folder: + +``` +my_app/ +├── app.py # Main application +├── models.py # Pydantic models +├── backend.py # Data access layer +├── requirements.txt # Additional dependencies +└── app.yaml # Databricks Apps configuration +``` + +### Step 2: Upload to Workspace + +```python +# MCP Tool: upload_folder +upload_folder( + local_folder="/path/to/my_app", + workspace_folder="/Workspace/Users/user@example.com/my_app" +) +``` + +### Step 3: Create App + +```python +# MCP Tool: create_app +result = create_app( + name="my-dashboard", + description="Customer analytics dashboard" +) +# Returns: {"name": "my-dashboard", "url": "https://..."} +``` + +### Step 4: Deploy + +```python +# MCP Tool: deploy_app +result = deploy_app( + app_name="my-dashboard", + source_code_path="/Workspace/Users/user@example.com/my_app" +) +# Returns: {"deployment_id": "...", "status": "PENDING", ...} +``` + +### Step 5: Verify + +```python +# MCP Tool: get_app +app = get_app(name="my-dashboard") +# Returns: {"name": "...", "url": "...", "status": "RUNNING", ...} + +# MCP Tool: get_app_logs +logs = get_app_logs(app_name="my-dashboard") +# Returns: {"logs": "...", ...} +``` + +### Step 6: Iterate + +1. Fix issues in local files +2. Re-upload with `upload_folder` +3. Re-deploy with `deploy_app` +4. Check `get_app_logs` for errors +5. Repeat until app is healthy + +--- + +## Quick Reference: MCP Tools + +| Tool | Description | +|------|-------------| +| **`create_app`** | Create a new Databricks App | +| **`get_app`** | Get app details and status | +| **`list_apps`** | List all apps in the workspace | +| **`deploy_app`** | Deploy app from workspace source path | +| **`delete_app`** | Delete an app | +| **`get_app_logs`** | Get app deployment and runtime logs | +| **`upload_folder`** | Upload local folder to workspace (shared tool) | + +--- + +## Notes + +- Add resources (SQL warehouse, Lakebase, etc.) via the Databricks Apps UI after creating the app +- MCP tools use the service principal's permissions — ensure it has access to required resources +- For manual deployment, see [4-deployment.md](4-deployment.md) diff --git a/.claude/skills/databricks-app-python/README.md b/.claude/skills/databricks-app-python/README.md deleted file mode 100644 index 63b30a6b..00000000 --- a/.claude/skills/databricks-app-python/README.md +++ /dev/null @@ -1,157 +0,0 @@ -# Databricks Python App Skill - -Claude Agent skill for building Python-based Databricks applications with various frameworks. - -## Structure - -``` -databricks-app-python/ -├── SKILL.md # Main skill file with core patterns -├── dash.md # Dash framework specific guide -├── streamlit.md # Streamlit guide (coming soon) -├── flask.md # Flask guide (coming soon) -└── README.md # This file -``` - -## Overview - -This skill provides comprehensive guidance for building Python applications for Databricks, including: - -### Core Components (SKILL.md) -- Architecture patterns -- Pydantic data models -- Mock and real backend patterns -- Databricks connectivity -- Unity Catalog integration -- Environment configuration -- Best practices - -### Framework-Specific Guides - -#### Dash (dash.md) -- Complete Dash application structure -- Component patterns (cards, tables, charts, modals) -- Callback patterns and best practices -- Plotly chart examples -- Bootstrap styling -- Common pitfalls and solutions - -#### Coming Soon -- **streamlit.md** - Streamlit patterns for rapid prototyping -- **flask.md** - Flask patterns for custom web apps -- **gradio.md** - Gradio for ML model interfaces - -## Usage - -When user requests a Python app for Databricks: - -1. **SKILL.md** provides the foundation: - - Data model design - - Backend architecture (mock + real) - - Databricks connectivity patterns - - Database setup - -2. **Framework-specific file** provides implementation: - - UI component patterns - - Framework-specific callbacks/routing - - Styling and theming - - Deployment configuration - -## Design Philosophy - -### Separation of Concerns -- **Core patterns** (SKILL.md) - Framework-agnostic -- **Framework details** (dash.md, etc.) - Implementation specifics - -### Progressive Complexity -- Start with mock backend (rapid development) -- Add real backend (production ready) -- Scale with Unity Catalog - -### Consistent Architecture -All apps follow same pattern: -``` -models.py → Data definitions -backend_mock.py → Sample data -backend_real.py → Databricks SQL -{framework}_app.py → UI implementation -setup_database.py → Schema initialization -``` - -## Example Applications - -### Order Management (Dash) -Location: `/example-app-dash/` - -Features: -- Dashboard with statistics and charts -- Filterable orders table -- Customer and product management -- Order details modal -- Mock and real backend support - -To run: -```bash -cd example-app-dash -uv pip install -r requirements.txt -USE_MOCK_BACKEND=true uv run python dash_app.py -``` - -## Adding New Frameworks - -To add support for a new framework: - -1. Create `{framework}.md` in this directory -2. Follow the structure of `dash.md`: - - When to use - - Dependencies - - Project structure - - Component patterns - - Best practices - - Common pitfalls - - Example code - -3. Update `SKILL.md` to reference new framework -4. Create example app in `/example-app-{framework}/` - -## Contributing - -When updating this skill: - -1. **SKILL.md changes**: Update if affecting all frameworks - - New backend patterns - - Database connectivity - - Environment configuration - - Pydantic model patterns - -2. **Framework-specific changes**: Update individual files - - New component patterns - - Framework version updates - - Best practices - - Bug fixes - -3. Keep example apps in sync with documentation - -## Testing - -Before committing changes: - -1. Test example apps run without errors -2. Verify all code examples are syntactically correct -3. Check cross-references between files work -4. Ensure new patterns follow existing conventions - -## Related Skills - -- **databricks-app-apx** - APX framework (FastAPI + React) -- **databricks-dev** - General Databricks development -- **python-dev** - Python development standards -- **asset-bundles** - Databricks Asset Bundles - -## Support - -For issues or questions: -1. Check framework-specific documentation -2. Review example applications -3. Consult Databricks documentation -4. Check framework-specific communities diff --git a/.claude/skills/databricks-app-python/SKILL.md b/.claude/skills/databricks-app-python/SKILL.md index 1bbdeaeb..eb62551b 100644 --- a/.claude/skills/databricks-app-python/SKILL.md +++ b/.claude/skills/databricks-app-python/SKILL.md @@ -1,812 +1,208 @@ --- name: databricks-app-python -description: "Build Python-based Databricks applications using Dash, Streamlit, or Flask." +description: "Builds Python-based Databricks applications using Dash, Streamlit, Gradio, Flask, FastAPI, or Reflex. Handles OAuth authorization (app and user auth), app resources, SQL warehouse and Lakebase connectivity, model serving integration, and deployment. Use when building Python web apps, dashboards, ML demos, or REST APIs for Databricks, or when the user mentions Streamlit, Dash, Gradio, Flask, FastAPI, Reflex, or Databricks app." --- # Databricks Python Application -Build Python-based Databricks applications using frameworks like Dash, Streamlit, Flask, or other Python web frameworks. +Build Python-based Databricks applications. For full examples and recipes, see the **[Databricks Apps Cookbook](https://apps-cookbook.dev/)**. -## Trigger Conditions - -**Invoke when user requests**: -- "Dash app" or "Dash application" -- "Streamlit app" or "Streamlit application" -- "Python web app" for Databricks -- Building data visualization or dashboard apps -- Order management, analytics dashboard, etc. - -**Do NOT invoke if user specifies**: APX, React, Node.js, or other non-Python frameworks. +--- -## Framework Selection +## Critical Rules (always follow) -Ask user which framework to use if not specified: -- **Dash** - Rich interactive dashboards, Bootstrap components, Plotly charts -- **Streamlit** - Rapid prototyping, simple syntax, data science focus, automatic reactivity -- **Flask** - Lightweight, flexible, custom web apps (coming soon) - -### Dash vs Streamlit Comparison - -| Aspect | Dash | Streamlit | -|--------|------|-----------| -| **Development Speed** | Moderate (more boilerplate) | Fast (script-based) | -| **Learning Curve** | Steeper (callbacks, components) | Gentle (Pythonic, intuitive) | -| **Layout Control** | High (Bootstrap grid, custom CSS) | Medium (columns, containers) | -| **Styling** | Extensive (Bootstrap themes, CSS) | Limited (custom CSS via markdown) | -| **Callbacks** | Explicit (Input/Output decorators) | Automatic (reruns on interaction) | -| **State Management** | Manual (via callbacks) | Built-in (st.session_state) | -| **Performance** | Better for complex interactions | Slower (full page reruns) | -| **Best For** | Production dashboards, BI tools | Prototypes, data science demos | -| **Multi-page Apps** | Better routing support | Simpler but less flexible | -| **Data Science Fit** | Good (requires more setup) | Excellent (notebook-like) | -| **Code Complexity** | ~600 lines for full app | ~400 lines for full app | - -**Choose Dash when:** -- Building production-grade business intelligence dashboards -- Need precise control over layout and styling -- Require complex callback chains and interactions -- Want Bootstrap components and themes -- Building for non-technical business users - -**Choose Streamlit when:** -- Rapid prototyping and POCs -- Data science team building internal tools -- Simple data exploration and visualization -- ML model demos and experiments -- Prefer notebook-like development workflow - -For framework-specific details, see: -- **[dash.md](dash.md)** - Complete Dash implementation guide -- **[streamlit.md](streamlit.md)** - Complete Streamlit implementation guide -- **flask.md** - Flask patterns (coming soon) - -## Prerequisites Check - -1. Verify Python environment: `python --version` (3.9+) -2. Check for `uv` package manager: `uv --version` -3. Verify Databricks connectivity (if using real backend): - - `DATABRICKS_WAREHOUSE_ID` (required for SQL backend) - - Databricks CLI configured profile (SDK Config handles auth automatically) - - **Note:** No explicit tokens needed when using SDK Config approach +- **MUST** confirm framework choice or use [Framework Selection](#framework-selection) below +- **MUST** use SDK `Config()` for authentication (never hardcode tokens) +- **MUST** use `app.yaml` `valueFrom` for resources (never hardcode resource IDs) +- **MUST** use `dash-bootstrap-components` for Dash app layout and styling +- **MUST** use `@st.cache_resource` for Streamlit database connections +- **MUST** deploy Flask with Gunicorn, FastAPI with uvicorn (not dev servers) -## Core Architecture - -All Python Databricks apps follow this pattern: +## Required Steps +Copy this checklist and verify each item: ``` -app-directory/ -├── models.py # Pydantic data models -├── backend_mock.py # Mock backend with sample data -├── backend_real.py # Real Databricks backend -├── {framework}_app.py # Main application (dash_app.py, streamlit_app.py, etc.) -├── setup_database.py # Database initialization -├── requirements.txt # Python dependencies -├── app.yaml # Databricks Apps configuration -├── .env # Environment configuration -└── README.md # Documentation +- [ ] Framework selected +- [ ] Auth strategy decided: app auth, user auth, or both +- [ ] App resources identified (SQL warehouse, Lakebase, serving endpoint, etc.) +- [ ] Backend data strategy decided (SQL warehouse, Lakebase, or SDK) +- [ ] Deployment method: CLI or DABs ``` -### Framework-Specific Requirements - -**Dash (dash_app.py):** -```txt -dash>=2.14.0 -dash-bootstrap-components>=1.5.0 -pandas>=2.0.0 -plotly>=5.17.0 -pydantic>=2.0.0 -python-dotenv>=1.0.0 -databricks-sdk>=0.12.0 -databricks-sql-connector>=3.0.0 -``` +--- -**Streamlit (streamlit_app.py):** -```txt -streamlit>=1.28.0 -pandas>=2.0.0 -plotly>=5.17.0 -pydantic>=2.0.0 -python-dotenv>=1.0.0 -databricks-sdk>=0.12.0 -databricks-sql-connector>=3.0.0 -``` +## Framework Selection -**Key Difference:** Dash requires `dash-bootstrap-components`, Streamlit doesn't need any additional UI libraries. +| Framework | Best For | app.yaml Command | +|-----------|----------|------------------| +| **Dash** | Production dashboards, BI tools, complex interactivity | `["python", "app.py"]` | +| **Streamlit** | Rapid prototyping, data science apps, internal tools | `["streamlit", "run", "app.py"]` | +| **Gradio** | ML demos, model interfaces, chat UIs | `["python", "app.py"]` | +| **Flask** | Custom REST APIs, lightweight apps, webhooks | `["gunicorn", "app:app", "-w", "4", "-b", "0.0.0.0:8080"]` | +| **FastAPI** | Async APIs, auto-generated OpenAPI docs | `["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8080"]` | +| **Reflex** | Full-stack Python apps without JavaScript | `["reflex", "run", "--env", "prod"]` | -## Workflow Overview +**Default**: Recommend **Streamlit** for prototypes, **Dash** for production dashboards, **FastAPI** for APIs, **Gradio** for ML demos. -### Phase 1: Planning & Models (10-15 min) -1. Understand requirements -2. Design data models -3. Create Pydantic models with validation -4. Create TodoWrite to track progress +--- -### Phase 2: Mock Backend (10-15 min) -1. Generate realistic sample data -2. Implement filtering and search -3. Create statistics methods -4. Test data generation +## Quick Reference -### Phase 3: Application UI (20-30 min) -1. Set up framework structure -2. Create consistent styling -3. Build main pages/views -4. Add interactivity (filters, charts) -5. Implement data tables +| Concept | Details | +|---------|---------| +| **Runtime** | Python 3.11, Ubuntu 22.04, 2 vCPU, 6 GB RAM | +| **Pre-installed** | Dash 2.18.1, Streamlit 1.38.0, Gradio 4.44.0, Flask 3.0.3, FastAPI 0.115.0 | +| **Auth (app)** | Service principal via `Config()` — auto-injected `DATABRICKS_CLIENT_ID`/`DATABRICKS_CLIENT_SECRET` | +| **Auth (user)** | `x-forwarded-access-token` header — see [1-authorization.md](1-authorization.md) | +| **Resources** | `valueFrom` in app.yaml — see [2-app-resources.md](2-app-resources.md) | +| **Cookbook** | https://apps-cookbook.dev/ | +| **Docs** | https://docs.databricks.com/aws/en/dev-tools/databricks-apps/ | -### Phase 4: Real Backend (15-20 min) -1. Design Unity Catalog schema -2. Implement SQL queries -3. Create database initialization -4. Add data seeding from mock +--- -### Phase 5: Testing & Documentation (10-15 min) -1. Test with mock backend -2. Test with real backend -3. Create comprehensive README -4. Add deployment instructions +## Detailed Guides -## Databricks Connectivity Patterns +**Authorization**: Use [1-authorization.md](1-authorization.md) when configuring app or user authorization — covers service principal auth, on-behalf-of user tokens, OAuth scopes, and per-framework code examples. (Keywords: OAuth, service principal, user auth, on-behalf-of, access token, scopes) -### Environment Configuration +**App resources**: Use [2-app-resources.md](2-app-resources.md) when connecting your app to Databricks resources — covers SQL warehouses, Lakebase, model serving, secrets, volumes, and the `valueFrom` pattern. (Keywords: resources, valueFrom, SQL warehouse, model serving, secrets, volumes, connections) -```python -# Standard environment variables -USE_MOCK_BACKEND=true|false # Toggle backend mode -DATABRICKS_WAREHOUSE_ID=... # SQL Warehouse ID (required) -DATABRICKS_CATALOG=main # Unity Catalog -DATABRICKS_SCHEMA=app_schema # Schema name -DATABRICKS_APP_PORT=8080 # Application port -DEBUG=false # Debug mode - -# Note: No DATABRICKS_TOKEN needed when using SDK Config -# Authentication handled automatically via: -# - Databricks CLI profile (local development) -# - Service principal (Databricks Apps) -``` +**Frameworks**: See [3-frameworks.md](3-frameworks.md) for Databricks-specific patterns per framework — covers Dash, Streamlit, Gradio, Flask, FastAPI, and Reflex with auth integration, deployment commands, and Cookbook links. (Keywords: Dash, Streamlit, Gradio, Flask, FastAPI, Reflex, framework selection) -### Backend Toggle Pattern +**Deployment**: Use [4-deployment.md](4-deployment.md) when deploying your app — covers Databricks CLI, Asset Bundles (DABs), app.yaml configuration, and post-deployment verification. (Keywords: deploy, CLI, DABs, asset bundles, app.yaml, logs) -```python -import os +**Lakebase**: Use [5-lakebase.md](5-lakebase.md) when using Lakebase (PostgreSQL) as your app's data layer — covers auto-injected env vars, psycopg2/asyncpg patterns, and when to choose Lakebase vs SQL warehouse. (Keywords: Lakebase, PostgreSQL, psycopg2, asyncpg, transactional, PGHOST) -USE_MOCK = os.getenv("USE_MOCK_BACKEND", "true").lower() == "true" +**MCP tools**: Use [6-mcp-approach.md](6-mcp-approach.md) for managing app lifecycle via MCP tools — covers creating, deploying, monitoring, and deleting apps programmatically. (Keywords: MCP, create app, deploy app, app logs) -if USE_MOCK: - from backend_mock import MockBackend - backend = MockBackend() -else: - from backend_real import RealBackend - backend = RealBackend() -``` +--- -### Pydantic Models Pattern +## Workflow -```python -from pydantic import BaseModel, Field, field_validator -from decimal import Decimal -from datetime import datetime -from enum import Enum -from typing import List, Optional +1. Determine the task type: -class StatusEnum(str, Enum): - """Status enumeration""" - ACTIVE = "active" - INACTIVE = "inactive" - -class Entity(BaseModel): - """Main entity model""" - id: str = Field(..., description="Unique identifier") - name: str = Field(..., description="Entity name") - created_at: datetime = Field(default_factory=datetime.utcnow) - status: StatusEnum = Field(default=StatusEnum.ACTIVE) - amount: Decimal = Field(..., description="Monetary amount", gt=0) - - @field_validator('amount', mode='before') - @classmethod - def validate_amount(cls, v): - """Ensure amount is a valid Decimal""" - if isinstance(v, (int, float, str)): - return Decimal(str(v)) - return v - - class Config: - json_schema_extra = { - "example": { - "id": "ENT-001", - "name": "Example Entity", - "status": "active", - "amount": "99.99" - } - } -``` + **New app from scratch?** → Use [Framework Selection](#framework-selection), then read [3-frameworks.md](3-frameworks.md) + **Setting up authorization?** → Read [1-authorization.md](1-authorization.md) + **Connecting to data/resources?** → Read [2-app-resources.md](2-app-resources.md) + **Using Lakebase (PostgreSQL)?** → Read [5-lakebase.md](5-lakebase.md) + **Deploying to Databricks?** → Read [4-deployment.md](4-deployment.md) + **Using MCP tools?** → Read [6-mcp-approach.md](6-mcp-approach.md) -### Mock Backend Pattern +2. Follow the instructions in the relevant guide +3. For full code examples, browse https://apps-cookbook.dev/ -```python -from typing import List, Optional -from models import Entity - -class MockBackend: - """Mock backend with sample data""" - - def __init__(self): - self.entities = self._generate_entities() - - def _generate_entities(self) -> List[Entity]: - """Generate sample data""" - return [ - Entity(id="ENT-001", name="Entity 1", amount=Decimal("100.00")), - Entity(id="ENT-002", name="Entity 2", amount=Decimal("200.00")), - ] - - def get_entities(self, filter_criteria: Optional[dict] = None) -> List[Entity]: - """Get entities with optional filtering""" - results = self.entities - - if filter_criteria: - # Apply filters - if filter_criteria.get("status"): - results = [e for e in results if e.status == filter_criteria["status"]] - - return results - - def get_entity(self, entity_id: str) -> Optional[Entity]: - """Get specific entity""" - for entity in self.entities: - if entity.id == entity_id: - return entity - return None - - def get_statistics(self) -> dict: - """Get aggregated statistics""" - return { - "total_count": len(self.entities), - "total_amount": float(sum(e.amount for e in self.entities)) - } -``` +--- -### Real Backend Pattern (Databricks SQL) +## Core Architecture -**Important:** For SQL Warehouse connection examples, see the Databricks Apps Cookbook: -- **Tables Read Example**: https://apps-cookbook.dev/docs/dash/tables/tables_read -- Shows proper service principal authentication using SDK Config +All Python Databricks apps follow this pattern: -```python -import os -from databricks import sql -from databricks.sdk import WorkspaceClient -from databricks.sdk.core import Config -from typing import List, Optional -from models import Entity - -class RealBackend: - """Real backend using Databricks SQL with SDK Config authentication""" - - def __init__(self, catalog: Optional[str] = None, schema: Optional[str] = None): - self.catalog = catalog or os.getenv("DATABRICKS_CATALOG", "main") - self.schema = schema or os.getenv("DATABRICKS_SCHEMA", "app_schema") - self.warehouse_id = os.getenv("DATABRICKS_WAREHOUSE_ID") - - if not self.warehouse_id: - raise ValueError("DATABRICKS_WAREHOUSE_ID required") - - self.config = Config() # Automatically handles authentication - self._connection = None - - def _get_connection(self): - """Get or create database connection using SDK Config""" - if self._connection is None: - self._connection = sql.connect( - server_hostname=self.config.host, - http_path=f"/sql/1.0/warehouses/{self.warehouse_id}", - credentials_provider=lambda: self.config.authenticate - ) - return self._connection - - def _execute_query(self, query: str, params: Optional[dict] = None) -> List[dict]: - """Execute SQL query and return results""" - connection = self._get_connection() - cursor = connection.cursor() - - try: - cursor.execute(query, params or {}) - columns = [desc[0] for desc in cursor.description] - results = [] - for row in cursor.fetchall(): - results.append(dict(zip(columns, row))) - return results - finally: - cursor.close() - - def get_entities(self, filter_criteria: Optional[dict] = None) -> List[Entity]: - """Get entities with optional filtering""" - query = f""" - SELECT * FROM {self.catalog}.{self.schema}.entities - WHERE 1=1 - """ - - params = {} - if filter_criteria and filter_criteria.get("status"): - query += " AND status = :status" - params["status"] = filter_criteria["status"] - - query += " ORDER BY created_at DESC" - - results = self._execute_query(query, params) - return [Entity(**row) for row in results] - - def initialize_schema(self): - """Initialize database schema""" - self._execute_query(f""" - CREATE TABLE IF NOT EXISTS {self.catalog}.{self.schema}.entities ( - id STRING NOT NULL, - name STRING NOT NULL, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP(), - status STRING NOT NULL, - amount DECIMAL(10, 2) NOT NULL, - PRIMARY KEY (id) - ) - """) - - def close(self): - """Close database connection""" - if self._connection: - self._connection.close() - self._connection = None +``` +app-directory/ +├── app.py # Main application (or framework-specific name) +├── models.py # Pydantic data models +├── backend.py # Data access layer +├── requirements.txt # Additional Python dependencies +├── app.yaml # Databricks Apps configuration +└── README.md ``` -### Database Setup Script Pattern +### Backend Toggle Pattern ```python -"""Database setup script""" import os -import argparse -from dotenv import load_dotenv -from backend_mock import MockBackend -from backend_real import RealBackend - -def setup_database(seed_data: bool = False): - """Initialize database and optionally seed data""" - load_dotenv() - - # Verify environment - required_vars = ["DATABRICKS_SERVER_HOSTNAME", "DATABRICKS_TOKEN", "DATABRICKS_WAREHOUSE_ID"] - missing = [v for v in required_vars if not os.getenv(v)] - if missing: - print(f"Missing: {', '.join(missing)}") - return 1 - - # Initialize backend - backend = RealBackend() - backend.initialize_schema() - - # Seed if requested - if seed_data: - mock = MockBackend() - # Copy data from mock to real backend - for entity in mock.entities: - backend.insert_entity(entity) - - backend.close() - return 0 - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--seed", action="store_true") - args = parser.parse_args() - exit(setup_database(seed_data=args.seed)) -``` - -## Best Practices - -### Data Models -- Use Pydantic for validation -- Include proper type hints -- Add `json_schema_extra` examples -- Handle Decimal for currency -- Use Enums for status fields - -### Backend Design -- Create both mock and real backends -- Use consistent interface between them -- Implement filtering and pagination -- Provide statistics/aggregations -- Use parameterized queries (security) - -### Error Handling -- Validate environment variables -- Handle connection failures gracefully -- Provide clear error messages -- Log errors appropriately - -### Configuration -- Use `.env` files for configuration -- Never commit secrets -- Provide `.env.example` template -- Support environment variable overrides - -### Testing Strategy -1. Start with mock backend (rapid development) -2. Test all features with sample data -3. Initialize real database with `--seed` -4. Test with real backend -5. Verify performance at scale - -## Common Patterns - -### Decimal Handling -```python -# Always convert to Decimal for monetary values -@field_validator('price', 'total', mode='before') -@classmethod -def validate_decimal(cls, v): - if isinstance(v, (int, float, str)): - return Decimal(str(v)) - return v -``` +from databricks.sdk.core import Config -### Date Formatting -```python -# Consistent date formatting -order.order_date.strftime("%Y-%m-%d %H:%M") -order.created_at.isoformat() -``` +USE_MOCK = os.getenv("USE_MOCK_BACKEND", "true").lower() == "true" -### Status Colors -```python -# Map status to visual indicators -STATUS_COLORS = { - Status.ACTIVE: "#2CA02C", # Green - Status.PENDING: "#FF7F0E", # Orange - Status.FAILED: "#D62728", # Red -} -``` +if USE_MOCK: + from backend_mock import MockBackend as Backend +else: + from backend_real import RealBackend as Backend -### Filtering Pattern -```python -# Reusable filter criteria model -class FilterCriteria(BaseModel): - status: Optional[Status] = None - date_from: Optional[datetime] = None - date_to: Optional[datetime] = None - search: Optional[str] = None +backend = Backend() ``` -## Success Criteria - -- [ ] Pydantic models with proper validation -- [ ] Mock backend with realistic data -- [ ] Framework UI with consistent styling -- [ ] Real backend with Unity Catalog -- [ ] Database initialization script -- [ ] Environment configuration -- [ ] Comprehensive documentation -- [ ] Both backends tested and working - -## Troubleshooting +### SQL Warehouse Connection (shared across all frameworks) -**First Step: Check Application Logs** -```bash -# Always check logs first when troubleshooting -databricks apps logs --profile - -# Examples: -databricks apps logs order-management-dash-dev -p DEFAULT -databricks apps logs order-management-streamlit-dev -p DEFAULT -``` - -Logs reveal: -- Deployment errors and stack traces -- Backend connection status (look for "✅ Initialized real backend") -- Missing dependencies or import errors -- SQL connection failures -- App startup issues - -**Connection Issues** -- Verify Databricks CLI profile is configured: `databricks auth profiles` -- Check `DATABRICKS_WAREHOUSE_ID` exists and is accessible -- Ensure warehouse is running: `databricks warehouses get ` -- Verify network connectivity to workspace -- For service principal: Check permissions on warehouse and catalog -- **Check logs for connection errors:** `databricks apps logs ` - -**Data Type Errors** -- Use Decimal for monetary values -- Handle None/Optional properly -- Validate datetime parsing - -**Performance Issues** -- Add database indexes -- Implement pagination -- Use query result caching -- Optimize SQL queries - -## Deployment to Databricks - -### Ask User for Deployment Preference - -**IMPORTANT:** Before deploying, ask the user which deployment method they prefer: - -1. **Databricks CLI** - Simple, direct deployment using `databricks apps` commands -2. **Databricks Asset Bundles (DABs)** - Infrastructure-as-code approach with version control - -Example: "Would you like to deploy using Databricks CLI or Databricks Asset Bundles (DABs)?" - -### Option 1: Deploy with Databricks CLI - -**Prerequisites:** -- Databricks CLI installed -- Authenticated profile configured -- SQL Warehouse ID available - -**Steps:** - -1. **Create app.yaml** - -**For Dash apps:** -```yaml -command: - - "python" - - "dash_app.py" - -env: - - name: USE_MOCK_BACKEND - value: "false" - - name: DATABRICKS_WAREHOUSE_ID - value: "your-warehouse-id" - - name: DATABRICKS_CATALOG - value: "main" - - name: DATABRICKS_SCHEMA - value: "app_schema" - - name: DATABRICKS_APP_PORT - value: "8080" - - name: DEBUG - value: "false" -``` +```python +from databricks.sdk.core import Config +from databricks import sql -**For Streamlit apps:** -```yaml -command: - - "streamlit" - - "run" - - "streamlit_app.py" - - "--server.port" - - "8080" - - "--server.address" - - "0.0.0.0" - -env: - - name: USE_MOCK_BACKEND - value: "false" - - name: DATABRICKS_WAREHOUSE_ID - value: "your-warehouse-id" - - name: DATABRICKS_CATALOG - value: "main" - - name: DATABRICKS_SCHEMA - value: "app_schema" +cfg = Config() # Auto-detects credentials from environment +conn = sql.connect( + server_hostname=cfg.host, + http_path=f"/sql/1.0/warehouses/{os.getenv('DATABRICKS_WAREHOUSE_ID')}", + credentials_provider=lambda: cfg.authenticate, +) ``` -**Note:** Streamlit uses `streamlit run` command, while Dash uses `python`. Streamlit doesn't need `DATABRICKS_APP_PORT` env var as it's specified in the command. +### Pydantic Models -2. **Initialize database schema** -```bash -# Run setup script locally (requires profile configured) -python setup_database.py --seed -``` - -3. **Create Databricks app** -```bash -databricks apps create --profile -``` +```python +from pydantic import BaseModel, Field +from datetime import datetime +from enum import Enum -4. **Upload source code to workspace** -```bash -databricks workspace mkdirs /Workspace/Users//apps/ --profile -databricks workspace import-dir . /Workspace/Users//apps/ --profile -``` +class Status(str, Enum): + ACTIVE = "active" + PENDING = "pending" -5. **Deploy the app** -```bash -databricks apps deploy \ - --source-code-path /Workspace/Users//apps/ \ - --profile -``` +class EntityOut(BaseModel): + id: str + name: str + status: Status + created_at: datetime -6. **Get app URL** -```bash -databricks apps get --profile +class EntityIn(BaseModel): + name: str = Field(..., min_length=1) + status: Status = Status.PENDING ``` -**Redeployment:** -```bash -# Update workspace files -databricks workspace delete /Workspace/Users//apps/ --recursive --profile -databricks workspace mkdirs /Workspace/Users//apps/ --profile -databricks workspace import-dir . /Workspace/Users//apps/ --profile - -# Redeploy -databricks apps deploy \ - --source-code-path /Workspace/Users//apps/ \ - --profile -``` +--- -### Option 2: Deploy with Databricks Asset Bundles (DABs) - -**Prerequisites:** -- Databricks CLI installed (v0.239.0+) -- App already deployed via CLI (recommended workflow) - -**Advantages:** -- Version controlled deployment -- Multi-environment support (dev/staging/prod) -- Declarative infrastructure -- Easier CI/CD integration - -**Recommended Workflow: CLI First, Then DABs** - -1. **Deploy app using CLI first** (see Option 1 above) - - This creates the app and validates everything works - - Easier to debug issues initially - -2. **Generate bundle configuration from existing app** -```bash -# This creates resources/*.app.yml and downloads source to src/app/ -databricks bundle generate app \ - --existing-app-name \ - --key \ - --profile - -# Example: -databricks bundle generate app \ - --existing-app-name order-management-dash \ - --key order_management_dash \ - --profile DEFAULT -``` +## Common Issues + +| Issue | Solution | +|-------|----------| +| **Connection exhausted** | Use `@st.cache_resource` (Streamlit) or connection pooling | +| **Auth token not found** | Check `x-forwarded-access-token` header — only available when deployed, not locally | +| **App won't start** | Check `app.yaml` command matches framework; check `databricks apps logs ` | +| **Resource not accessible** | Add resource via UI, verify SP has permissions, use `valueFrom` in app.yaml | +| **Import error on deploy** | Add missing packages to `requirements.txt` (pre-installed packages don't need listing) | +| **Lakebase app crashes on start** | `psycopg2`/`asyncpg` are NOT pre-installed — MUST add to `requirements.txt` | +| **Port conflict** | Databricks Apps expects port 8080; configure your framework accordingly | +| **Streamlit: set_page_config error** | `st.set_page_config()` must be the first Streamlit command | +| **Dash: unstyled layout** | Add `dash-bootstrap-components`; use `dbc.themes.BOOTSTRAP` | +| **Slow queries** | Use Lakebase for transactional/low-latency; SQL warehouse for analytical queries | -**What gets generated:** -- `resources/.app.yml` - Minimal app resource definition -- `src/app/` - All app source files including `app.yaml` with env vars -- `databricks.yml` updated with bundle structure - -3. **Update generated configuration for multi-environment** - -**Edit `databricks.yml`:** -```yaml -bundle: - name: - -include: - - resources/*.yml - -variables: - warehouse_id: - default: "your-warehouse-id" - catalog: - default: "main" - schema: - default: "app_schema" - -targets: - dev: - default: true - mode: development - workspace: - profile: - variables: - warehouse_id: "dev-warehouse-id" - schema: "app_schema_dev" - - prod: - mode: production - workspace: - profile: - variables: - warehouse_id: "prod-warehouse-id" - schema: "app_schema_prod" -``` +--- -**Edit `resources/.app.yml`:** -```yaml -resources: - apps: - : - name: -${bundle.target} # Environment-specific naming - description: "Python ${framework} application" - source_code_path: ../src/app # Or .. if source in project root -``` +## Platform Constraints -**Important:** Environment variables are in `src/app/app.yaml`, NOT in databricks.yml: -```yaml -command: - - "python" - - "dash_app.py" - -env: - - name: USE_MOCK_BACKEND - value: "false" - - name: DATABRICKS_WAREHOUSE_ID - value: "your-warehouse-id" - - name: DATABRICKS_CATALOG - value: "main" - - name: DATABRICKS_SCHEMA - value: "app_schema" -``` +| Constraint | Details | +|------------|---------| +| **Runtime** | Python 3.11, Ubuntu 22.04 LTS | +| **Compute** | 2 vCPUs, 6 GB memory (default) | +| **Pre-installed frameworks** | Dash, Streamlit, Gradio, Flask, FastAPI, Shiny | +| **Custom packages** | Add to `requirements.txt` in app root | +| **Network** | Apps can reach Databricks APIs; external access depends on workspace config | +| **User auth** | Public Preview — workspace admin must enable before adding scopes | -4. **Deploy and run** -```bash -# Validate configuration -databricks bundle validate -t dev +--- -# Deploy to dev (creates/updates resource) -databricks bundle deploy -t dev +## Official Documentation -# Start the app (required after deployment) -databricks bundle run -t dev +- **[Databricks Apps Overview](https://docs.databricks.com/aws/en/dev-tools/databricks-apps/)** — main docs hub +- **[Apps Cookbook](https://apps-cookbook.dev/)** — ready-to-use code snippets (Streamlit, Dash, Reflex, FastAPI) +- **[Authorization](https://docs.databricks.com/aws/en/dev-tools/databricks-apps/auth)** — app auth and user auth +- **[Resources](https://docs.databricks.com/aws/en/dev-tools/databricks-apps/resources)** — SQL warehouse, Lakebase, serving, secrets +- **[app.yaml Reference](https://docs.databricks.com/aws/en/dev-tools/databricks-apps/app-runtime)** — command and env config +- **[System Environment](https://docs.databricks.com/aws/en/dev-tools/databricks-apps/system-env)** — pre-installed packages, runtime details -# For production -databricks bundle deploy -t prod -databricks bundle run -t prod -``` +## Related Skills -**Key Differences from Other Resources:** -- Environment variables go in `app.yaml` (source dir), NOT databricks.yml -- Apps have minimal bundle configuration (name, description, path) -- Must run `databricks bundle run` to start the app after deployment - -**For complete DABs guidance, use the `asset-bundles` skill.** - -### Post-Deployment Steps - -1. **Verify deployment** - - Access app URL - - Check all pages load - - Verify data from Unity Catalog - -2. **Configure permissions** - - Set up user access - - Configure service principal permissions - - Grant warehouse access - -3. **Set up monitoring and view logs** - - **View application logs:** - ```bash - # View logs for your deployed app - databricks apps logs --profile - - # Examples: - databricks apps logs order-management-dash-dev --profile DEFAULT - databricks apps logs order-management-streamlit-dev --profile DEFAULT - ``` - - **What logs show:** - - `[SYSTEM]` - Deployment status, file updates, dependency installation - - `[APP]` - Application output (print statements, framework messages) - - Backend initialization messages - - Connection status to Unity Catalog - - Error messages and stack traces - - **Useful for debugging:** - - ✅ Verify real backend connection: Look for "✅ Initialized real backend: main.schema" - - ✅ Check dependency installation: "Requirements installed successfully" - - ✅ Confirm app start: "App started successfully" - - ✅ Diagnose connection errors: SQL connection failures - - ✅ Track deployments: Each deployment has unique ID - - **Additional monitoring:** - - Monitor warehouse usage in Databricks SQL - - Track app performance and response times - - Set up alerts for app failures - -4. **Documentation** - - Update README with deployment URL - - Document environment variables - - Add troubleshooting guide - -## Reference Materials - -For framework-specific implementation details: -- **[dash.md](dash.md)** - Complete Dash implementation guide with Bootstrap components -- **[streamlit.md](streamlit.md)** - Complete Streamlit implementation guide with caching patterns -- **flask.md** - Flask patterns (coming soon) +- **[databricks-app-apx](../databricks-app-apx/SKILL.md)** - full-stack apps with FastAPI + React +- **[databricks-asset-bundles](../databricks-asset-bundles/SKILL.md)** - deploying apps via DABs +- **[databricks-python-sdk](../databricks-python-sdk/SKILL.md)** - backend SDK integration +- **[databricks-lakebase-provisioned](../databricks-lakebase-provisioned/SKILL.md)** - adding persistent PostgreSQL state +- **[databricks-model-serving](../databricks-model-serving/SKILL.md)** - serving ML models for app integration diff --git a/.claude/skills/databricks-app-python/dash.md b/.claude/skills/databricks-app-python/dash.md deleted file mode 100644 index 82e42ecc..00000000 --- a/.claude/skills/databricks-app-python/dash.md +++ /dev/null @@ -1,553 +0,0 @@ -# Dash Framework Guide - -Complete guide for building Databricks applications with Plotly Dash framework. - -## When to Use Dash - -**Best for**: -- Interactive dashboards with rich charts -- Business intelligence applications -- Data visualization heavy apps -- Multi-page applications -- Apps requiring custom styling with Bootstrap - -**Alternatives**: -- Streamlit - Simpler syntax, faster prototyping -- APX - Full-stack with React frontend - -## Dependencies - -```txt -dash>=2.14.0 -dash-bootstrap-components>=1.5.0 -plotly>=5.18.0 -pandas>=2.0.0 -databricks-sdk>=0.35.0 -databricks-sql-connector>=3.0.0 -pydantic>=2.0.0 -python-dotenv>=1.0.0 -``` - -## Project Structure - -``` -dash-app/ -├── models.py # Pydantic data models -├── backend_mock.py # Mock backend with sample data -├── backend_real.py # Databricks SQL backend -├── dash_app.py # Main Dash application -├── setup_database.py # Database initialization -├── requirements.txt # Dependencies -├── .env.example # Environment template -├── run_app.sh # Quick start script -└── README.md # Documentation -``` - -## Dash Application Structure - -### Basic Setup - -```python -import os -import dash -from dash import dcc, html, dash_table, Input, Output, State, callback -import dash_bootstrap_components as dbc -import plotly.express as px -import pandas as pd - -from backend_mock import MockBackend -from models import Status - -# Initialize backend -USE_MOCK = os.getenv("USE_MOCK_BACKEND", "true").lower() == "true" -backend = MockBackend() if USE_MOCK else RealBackend() - -# Initialize Dash app with Bootstrap theme -app = dash.Dash( - __name__, - external_stylesheets=[dbc.themes.BOOTSTRAP, dbc.icons.FONT_AWESOME], - suppress_callback_exceptions=True, - title="Application Name" -) - -# Define color scheme -COLORS = { - "primary": "#1F77B4", - "success": "#2CA02C", - "warning": "#FF7F0E", - "danger": "#D62728", - "info": "#17A2B8", - "light": "#F8F9FA", - "dark": "#343A40", -} - -# Status color mappings -STATUS_COLORS = { - Status.ACTIVE: COLORS["success"], - Status.PENDING: COLORS["warning"], - Status.FAILED: COLORS["danger"], -} - -# Bootstrap badge colors (for dbc.Badge) -STATUS_BADGE_COLORS = { - Status.ACTIVE: "success", - Status.PENDING: "warning", - Status.FAILED: "danger", -} -``` - -### Navigation Bar - -```python -def create_navbar(): - """Create navigation bar""" - return dbc.Navbar( - dbc.Container([ - dbc.Row([ - dbc.Col([ - html.I(className="fas fa-chart-line me-2"), - dbc.NavbarBrand("Application Name", className="ms-2"), - ], width="auto"), - ], align="center", className="g-0"), - dbc.Nav([ - dbc.NavItem(dbc.NavLink("Dashboard", href="/", active="exact")), - dbc.NavItem(dbc.NavLink("Orders", href="/orders", active="exact")), - dbc.NavItem(dbc.NavLink("Customers", href="/customers", active="exact")), - ], navbar=True, className="ms-auto"), - ], fluid=True), - color="dark", - dark=True, - className="mb-4" - ) -``` - -### Main Layout with Routing - -```python -app.layout = html.Div([ - dcc.Location(id='url', refresh=False), - create_navbar(), - html.Div(id='page-content', style={'minHeight': '80vh'}), - dcc.Store(id='selected-item-id'), # Client-side data storage -], style={'backgroundColor': COLORS["light"], 'minHeight': '100vh'}) - -@callback( - Output('page-content', 'children'), - Input('url', 'pathname') -) -def display_page(pathname): - """Route to different pages""" - if pathname == '/orders': - return create_orders_layout() - elif pathname == '/customers': - return create_customers_layout() - else: - return create_dashboard_layout() -``` - -## Component Patterns - -### Statistics Card - -```python -def create_stat_card(title, value, icon, color="primary", subtitle=None): - """Create a statistics card""" - return dbc.Card([ - dbc.CardBody([ - html.Div([ - html.Div([ - html.H6(title, className="text-muted mb-2"), - html.H3(value, className="mb-0"), - html.Small(subtitle, className="text-muted") if subtitle else None, - ], className="flex-grow-1"), - html.Div([ - html.I(className=f"fas {icon} fa-2x text-{color}") - ], className="ms-3"), - ], className="d-flex align-items-center"), - ]), - ], className="shadow-sm mb-3") - -# Usage -dbc.Row([ - dbc.Col(create_stat_card( - "Total Orders", - f"{stats['total_orders']:,}", - "fa-shopping-cart", - "primary" - ), md=3), - dbc.Col(create_stat_card( - "Total Revenue", - f"${stats['total_revenue']:,.2f}", - "fa-dollar-sign", - "success" - ), md=3), -]) -``` - -### Interactive Data Table - -```python -def create_data_table(data, table_id, selectable=False): - """Create interactive data table""" - if not data: - return html.Div("No data available.", className="text-muted") - - return dash_table.DataTable( - id=table_id, - data=data, - columns=[{"name": col, "id": col} for col in data[0].keys()], - page_size=20, - style_table={'overflowX': 'auto'}, - style_cell={ - 'textAlign': 'left', - 'padding': '12px', - 'fontFamily': 'Arial, sans-serif' - }, - style_header={ - 'backgroundColor': COLORS["dark"], - 'color': 'white', - 'fontWeight': 'bold' - }, - style_data_conditional=[ - { - 'if': {'row_index': 'odd'}, - 'backgroundColor': COLORS["light"] - } - ], - filter_action="native", - sort_action="native", - row_selectable='single' if selectable else False, - ) -``` - -### Plotly Charts - -```python -# Pie Chart -@callback( - Output('status-pie-chart', 'figure'), - Input('url', 'pathname') -) -def update_pie_chart(pathname): - """Create pie chart for status distribution""" - stats = backend.get_statistics() - status_data = stats['status_distribution'] - - fig = px.pie( - values=list(status_data.values()), - names=[s.title() for s in status_data.keys()], - color_discrete_sequence=px.colors.qualitative.Set3 - ) - fig.update_layout( - margin=dict(t=20, b=20, l=20, r=20), - showlegend=True, - height=300 - ) - return fig - -# Bar Chart -@callback( - Output('revenue-bar-chart', 'figure'), - Input('url', 'pathname') -) -def update_bar_chart(pathname): - """Create bar chart for revenue by category""" - data = backend.get_revenue_by_category() - - # Create color map with error handling - color_map = {} - for category in data.keys(): - color_map[category] = COLORS.get(category.lower(), COLORS["primary"]) - - fig = px.bar( - x=list(data.keys()), - y=list(data.values()), - labels={'x': 'Category', 'y': 'Revenue ($)'}, - color=list(data.keys()), - color_discrete_map=color_map - ) - fig.update_layout( - margin=dict(t=20, b=40, l=40, r=20), - showlegend=False, - height=300, - xaxis_title="", - yaxis_title="Revenue ($)" - ) - fig.update_xaxes(tickangle=-45) # Note: update_xaxes, not update_xaxis - return fig -``` - - -## Callback Patterns - -### Basic Callback - -```python -@callback( - Output('output-div', 'children'), - Input('input-button', 'n_clicks') -) -def update_output(n_clicks): - """Basic callback pattern""" - if n_clicks is None: - return "Click the button" - return f"Button clicked {n_clicks} times" -``` - -### Multiple Inputs - -```python -@callback( - Output('filtered-table', 'children'), - [Input('filter-status', 'value'), - Input('filter-date', 'value'), - Input('refresh-button', 'n_clicks')] -) -def update_table(status, date, n_clicks): - """Callback with multiple inputs""" - filter_criteria = { - "status": Status(status) if status else None, - "date": date - } - data = backend.get_data(filter_criteria) - return create_data_table(data, "result-table") -``` - -### Using State (Non-Triggering Inputs) - -```python -@callback( - Output('result', 'children'), - Input('submit-button', 'n_clicks'), - [State('input-field', 'value'), - State('dropdown', 'value')] -) -def process_form(n_clicks, input_value, dropdown_value): - """State doesn't trigger callback, only provides values""" - if n_clicks is None: - return "" - return f"Processing: {input_value}, {dropdown_value}" -``` - -### Callback Context - -```python -@callback( - Output('result', 'children'), - [Input('button1', 'n_clicks'), - Input('button2', 'n_clicks')] -) -def handle_multiple_buttons(n1, n2): - """Determine which input triggered the callback""" - ctx = dash.callback_context - - if not ctx.triggered: - return "No button clicked" - - trigger_id = ctx.triggered[0]['prop_id'].split('.')[0] - - if trigger_id == 'button1': - return "Button 1 clicked" - elif trigger_id == 'button2': - return "Button 2 clicked" - - return "Unknown trigger" -``` - -## Complete Page Example - -```python -def create_orders_layout(): - """Complete orders page with table, filters, and modal""" - return dbc.Container([ - html.H2("Orders", className="mb-4"), - - # Filters - create_filters(), - - # Data Table - dbc.Card([ - dbc.CardHeader(html.H5([ - html.I(className="fas fa-table me-2"), - "Order List" - ])), - dbc.CardBody([ - html.Div(id="orders-table") - ]), - ], className="shadow-sm mb-4"), - - # Detail Modal - create_detail_modal(), - ], fluid=True) - -@callback( - Output('orders-table', 'children'), - [Input('filter-status', 'value'), - Input('refresh-button', 'n_clicks')] -) -def update_orders_table(status, n_clicks): - """Update orders table with filters""" - filter_criteria = {"status": Status(status) if status else None} - orders = backend.get_orders(filter_criteria) - - if not orders: - return html.Div("No orders found.", className="text-muted") - - order_data = [ - { - "Order ID": o.order_id, - "Customer": o.customer_name, - "Date": o.order_date.strftime("%Y-%m-%d %H:%M"), - "Status": o.status.value.title(), - "Total": f"${float(o.total):.2f}", - } - for o in orders - ] - - return create_data_table(order_data, "orders-data-table", selectable=True) -``` - -## Best Practices - -### Performance -1. **Use `dcc.Store`** for client-side caching -2. **Implement pagination** for large datasets -3. **Use `prevent_initial_call=True`** for expensive operations -4. **Minimize callback dependencies** -5. **Cache backend queries** when appropriate - - -### Consistent Styling -```python -# Define color constants at top of file -COLORS = {...} -STATUS_COLORS = {...} -STATUS_BADGE_COLORS = {...} - -# Use consistently throughout app -dbc.Badge(status, color=STATUS_BADGE_COLORS[status]) -``` - -## Common Pitfalls - -### ❌ Wrong: Missing ID on dynamically created component -```python -def update_table(): - return dash_table.DataTable( - # Missing id! - data=data, - columns=columns - ) -``` - -### ✅ Correct: Always provide ID -```python -def update_table(): - return dash_table.DataTable( - id='dynamic-table', # Always include id - data=data, - columns=columns - ) -``` - -### ❌ Wrong: Accessing data before checking if exists -```python -@callback(...) -def toggle_modal(selected_rows, table_data, is_open): - item_id = table_data[selected_rows[0]]["id"] # May fail! -``` - -### ✅ Correct: Check before accessing -```python -@callback(..., prevent_initial_call=True) -def toggle_modal(selected_rows, table_data, is_open): - if not selected_rows or not table_data: - return False, "", "" - item_id = table_data[selected_rows[0]]["id"] # Safe -``` - -### ❌ Wrong: Using hex colors for Bootstrap badges -```python -dbc.Badge(status, color="#2CA02C") # Won't work! -``` - -### ✅ Correct: Use Bootstrap color names -```python -dbc.Badge(status, color="success") # Correct -``` - -### ❌ Wrong: Plotly method typo -```python -fig.update_xaxis(tickangle=-45) # AttributeError! -``` - -### ✅ Correct: Use plural form -```python -fig.update_xaxes(tickangle=-45) # Correct -``` - -## Running the App - -### Development Mode -```bash -# With uv -USE_MOCK_BACKEND=true DEBUG=true DATABRICKS_APP_PORT=8080 uv run python dash_app.py - -# With python directly -USE_MOCK_BACKEND=true DEBUG=true python dash_app.py -``` - -### Production Mode -```python -if __name__ == '__main__': - port = int(os.getenv("DATABRICKS_APP_PORT", "8080")) - debug = os.getenv("DEBUG", "false").lower() == "true" - - app.run(host='0.0.0.0', port=port, debug=debug) -``` - -## Deployment to Databricks - -### app.yaml -```yaml -command: - - "python" - - "dash_app.py" - -env: - - name: USE_MOCK_BACKEND - value: "false" - - name: DATABRICKS_CONFIG_PROFILE - value: "" - - name: DATABRICKS_APP_PORT - value: "8080" -``` - -### Deploy Commands -```bash -databricks apps deploy -databricks apps list -databricks apps logs -``` - - -## Additional Resources - -- **Plotly Dash Docs**: https://dash.plotly.com/ -- **Dash Bootstrap Components**: https://dash-bootstrap-components.opensource.faculty.ai/ -- **Plotly Charts**: https://plotly.com/python/ -- **Example App Snippets**: https://apps-cookbook.dev/docs/category/dash - -## Success Checklist - -- [ ] App runs with mock backend -- [ ] All pages render without errors -- [ ] Callbacks work correctly -- [ ] Filters update data tables -- [ ] Charts display properly -- [ ] Modals open and close -- [ ] Consistent styling throughout -- [ ] Empty states handled -- [ ] Error handling in callbacks -- [ ] Real backend tested -- [ ] Documentation complete diff --git a/.claude/skills/databricks-app-python/streamlit.md b/.claude/skills/databricks-app-python/streamlit.md deleted file mode 100644 index d50646e8..00000000 --- a/.claude/skills/databricks-app-python/streamlit.md +++ /dev/null @@ -1,790 +0,0 @@ -# Streamlit Framework Implementation Guide - -Complete guide for building Databricks applications with Streamlit framework. - -## Table of Contents - -- [When to Use Streamlit](#when-to-use-streamlit) -- [Core Architecture](#core-architecture) -- [Essential Patterns](#essential-patterns) -- [Best Practices](#best-practices) -- [Component Guide](#component-guide) -- [Common Pitfalls](#common-pitfalls) -- [Performance Optimization](#performance-optimization) - ---- - -## When to Use Streamlit - -**Choose Streamlit when you need:** -- Rapid prototyping and development -- Data science and ML-focused applications -- Simple, script-like development workflow -- Built-in widgets and forms -- Interactive data exploration tools -- ML model demos and POCs - -**Key Strengths:** -- ✅ Fastest development time (script-based) -- ✅ Excellent for data scientists (Pythonic) -- ✅ Built-in state management -- ✅ Automatic reactivity (reruns on interaction) -- ✅ Great for notebooks-to-apps workflow - -**Limitations:** -- ❌ Less control over layout (compared to Dash) -- ❌ Full page reruns can be slower -- ❌ Harder to build complex multi-page apps -- ❌ Limited styling customization - ---- - -## Core Architecture - -### Application Structure - -```python -""" -Streamlit App Structure -""" -import streamlit as st -from databricks.sdk.core import Config -from databricks import sql - -# 1. Page configuration (MUST be first Streamlit command) -st.set_page_config( - page_title="My App", - page_icon="📊", - layout="wide", # or "centered" - initial_sidebar_state="expanded" # or "collapsed" -) - -# 2. Backend initialization with caching -@st.cache_resource -def get_backend(): - """Initialize and cache backend connection""" - # Your backend initialization - return backend - -# 3. Initialize backend -backend = get_backend() - -# 4. Sidebar navigation -page = st.sidebar.radio("Navigation", ["Page 1", "Page 2"]) - -# 5. Page content -if page == "Page 1": - # Page 1 content - pass -elif page == "Page 2": - # Page 2 content - pass -``` - -### File Organization - -``` -streamlit-app/ -├── streamlit_app.py # Main application entry point -├── models.py # Pydantic data models -├── backend_mock.py # Mock backend with sample data -├── backend_real.py # Real Databricks backend -├── setup_database.py # Database initialization -├── requirements.txt # Python dependencies -├── app.yaml # Databricks Apps configuration -├── .env # Environment variables -└── README.md # Documentation -``` - ---- - -## Essential Patterns - -### 1. Connection Caching (Critical) - -**Always use `@st.cache_resource` for database connections:** - -```python -from databricks.sdk.core import Config -from databricks import sql - -@st.cache_resource(ttl=300, show_spinner=True) -def get_sql_connection(http_path: str): - """ - Create and cache SQL warehouse connection - - Args: - ttl: Time-to-live in seconds (5 minutes default) - show_spinner: Show loading indicator during initialization - """ - cfg = Config() # Reads DATABRICKS_HOST automatically - - return sql.connect( - server_hostname=cfg.host, - http_path=http_path, - credentials_provider=lambda: cfg.authenticate - ) - -# Usage -conn = get_sql_connection("/sql/1.0/warehouses/xxxxx") -``` - -**Why `@st.cache_resource`?** -- Persists across sessions and reruns -- Prevents connection exhaustion -- Improves performance dramatically -- Required for production apps - -### 2. Backend Toggle Pattern - -```python -import os - -@st.cache_resource -def get_backend(): - """Initialize backend based on environment""" - use_mock = os.getenv("USE_MOCK_BACKEND", "true").lower() == "true" - - if use_mock: - from backend_mock import MockBackend - return MockBackend() - else: - from backend_real import RealBackend - catalog = os.getenv("DATABRICKS_CATALOG", "main") - schema = os.getenv("DATABRICKS_SCHEMA", "app_schema") - return RealBackend(catalog=catalog, schema=schema) -``` - -### 3. Session State Management - -**Use `st.session_state` to persist data across reruns:** - -```python -# Initialize state -if 'order_id' not in st.session_state: - st.session_state.order_id = None - -# Set state -if st.button("Load Order"): - st.session_state.order_id = "ORD-001" - -# Read state -if st.session_state.order_id: - st.write(f"Current order: {st.session_state.order_id}") -``` - -**Common State Patterns:** - -```python -# Form data -if 'form_data' not in st.session_state: - st.session_state.form_data = {} - -# Page navigation -if 'current_page' not in st.session_state: - st.session_state.current_page = "Dashboard" - -# Filter persistence -if 'filters' not in st.session_state: - st.session_state.filters = { - 'status': [], - 'date_from': None, - 'date_to': None - } -``` - -### 4. Data Display Patterns - -**DataFrames (Read-only):** - -```python -import pandas as pd - -df = backend.get_orders() -st.dataframe( - df, - use_container_width=True, # Expand to container width - hide_index=True, # Hide row numbers - column_config={ - "amount": st.column_config.NumberColumn( - "Amount", - format="$%.2f" - ), - "status": st.column_config.SelectColumn( - "Status", - options=["pending", "confirmed", "shipped"] - ) - } -) -``` - -**Data Editor (Editable):** - -```python -# For editable tables -edited_df = st.data_editor( - df, - num_rows="dynamic", # Allow add/delete rows - hide_index=True, - column_config={ - "amount": st.column_config.NumberColumn( - "Amount", - min_value=0, - max_value=10000, - step=0.01, - format="$%.2f" - ) - } -) - -# Detect changes -if st.button("Save Changes"): - # Compare original vs edited - df_diff = pd.concat([df, edited_df]).drop_duplicates(keep=False) - if not df_diff.empty: - backend.update_data(edited_df) - st.success("Changes saved!") -``` - -### 5. Sidebar Navigation - -```python -# Sidebar navigation pattern -st.sidebar.title("📊 My App") -st.sidebar.markdown("---") - -page = st.sidebar.radio( - "Navigation", - ["Dashboard", "Orders", "Customers", "Products"], - label_visibility="collapsed" # Hide "Navigation" label -) - -# Filters in sidebar -st.sidebar.markdown("---") -st.sidebar.markdown("### Filters") - -status_filter = st.sidebar.multiselect( - "Status", - options=["pending", "confirmed", "shipped"], - default=None -) - -date_range = st.sidebar.date_input( - "Date Range", - value=None -) -``` - -### 6. Metrics Display - -```python -# Four-column metrics -col1, col2, col3, col4 = st.columns(4) - -with col1: - st.metric( - label="Total Orders", - value="1,234", - delta="12%", # Optional change indicator - delta_color="normal" # "normal", "inverse", or "off" - ) - -with col2: - st.metric( - label="Revenue", - value="$45,678", - delta="-8%", - delta_color="inverse" # Red for negative when inverse - ) -``` - -### 7. Charts Integration - -**Plotly Charts (Recommended):** - -```python -import plotly.express as px -import plotly.graph_objects as go - -# Pie chart -fig = px.pie( - df, - values='count', - names='status', - color='status', - color_discrete_map={'pending': '#FFA500', 'confirmed': '#2CA02C'} -) -st.plotly_chart(fig, use_container_width=True) - -# Bar chart -fig = px.bar( - df, - x='month', - y='revenue', - color='category' -) -fig.update_layout(showlegend=False) -st.plotly_chart(fig, use_container_width=True) -``` - -**Native Streamlit Charts:** - -```python -# For simple charts (less customizable but faster) -st.line_chart(df[['date', 'revenue']]) -st.bar_chart(df[['category', 'count']]) -st.area_chart(df[['date', 'cumulative_revenue']]) -``` - -### 8. Forms and Inputs - -**Form Pattern (Prevents reruns on every input change):** - -```python -with st.form("order_form"): - st.write("Create New Order") - - customer = st.text_input("Customer Name") - product = st.selectbox("Product", ["Product A", "Product B"]) - quantity = st.number_input("Quantity", min_value=1, value=1) - notes = st.text_area("Notes") - - # Form is only submitted when button is clicked - submitted = st.form_submit_button("Create Order") - - if submitted: - # Process form data - backend.create_order(customer, product, quantity, notes) - st.success("Order created!") -``` - -**Without Forms (Immediate reactivity):** - -```python -# These trigger reruns on every change -name = st.text_input("Name") -age = st.slider("Age", 0, 100) - -if st.button("Submit"): - # Only runs when button clicked - st.write(f"{name} is {age} years old") -``` - ---- - -## Best Practices - -### Page Configuration - -**✅ ALWAYS set page config first:** - -```python -# MUST be the first Streamlit command -st.set_page_config( - page_title="Order Management", - page_icon="📦", - layout="wide", - initial_sidebar_state="expanded" -) -``` - -**❌ Common mistake:** - -```python -import streamlit as st - -st.title("My App") # ❌ Error: set_page_config must be first -st.set_page_config(...) # ❌ Too late! -``` - -### State Management - -**✅ Initialize state at the top:** - -```python -# Initialize all state variables together -if 'user_id' not in st.session_state: - st.session_state.user_id = None -if 'filters' not in st.session_state: - st.session_state.filters = {} -``` - -**❌ Don't initialize in conditionals:** - -```python -# ❌ Bad: state only initialized if condition is true -if some_condition: - if 'user_id' not in st.session_state: - st.session_state.user_id = None -``` - -### Caching - -**✅ Cache expensive operations:** - -```python -@st.cache_resource # For connections, models -def get_connection(): - return create_connection() - -@st.cache_data(ttl=60) # For data, with TTL -def load_data(): - return fetch_data() -``` - -**When to use which:** -- `@st.cache_resource`: Connections, ML models, non-serializable objects -- `@st.cache_data`: DataFrames, lists, dicts, serializable data - -### Layout Organization - -**✅ Use columns for horizontal layout:** - -```python -col1, col2, col3 = st.columns([2, 1, 1]) # Ratios: 2:1:1 - -with col1: - st.write("Main content") - -with col2: - st.write("Sidebar content") -``` - -**✅ Use expanders for collapsible sections:** - -```python -with st.expander("Advanced Filters"): - filter1 = st.selectbox("Filter 1", options) - filter2 = st.multiselect("Filter 2", options) -``` - -**✅ Use tabs for switching content:** - -```python -tab1, tab2, tab3 = st.tabs(["Tab 1", "Tab 2", "Tab 3"]) - -with tab1: - st.write("Tab 1 content") - -with tab2: - st.write("Tab 2 content") -``` - -### Error Handling - -**✅ Graceful error handling:** - -```python -try: - data = backend.get_data() - st.dataframe(data) -except Exception as e: - st.error(f"Error loading data: {str(e)}") - st.info("Please check your connection and try again") -``` - -**✅ Input validation:** - -```python -user_input = st.text_input("Enter warehouse ID") - -if user_input: - if not user_input.startswith("/sql/"): - st.warning("Warehouse path should start with /sql/") - else: - # Process input - pass -``` - ---- - -## Component Guide - -### Core Components - -| Component | Use Case | Example | -|-----------|----------|---------| -| `st.title()` | Page titles | `st.title("Dashboard")` | -| `st.header()` | Section headers | `st.header("Overview")` | -| `st.subheader()` | Subsection headers | `st.subheader("Metrics")` | -| `st.text()` | Plain text | `st.text("Simple text")` | -| `st.markdown()` | Formatted text | `st.markdown("**Bold** text")` | -| `st.write()` | Auto-formatted | `st.write("Text", df, chart)` | - -### Input Widgets - -| Widget | Use Case | Example | -|--------|----------|---------| -| `st.button()` | Actions | `if st.button("Submit"):` | -| `st.text_input()` | Single-line text | `name = st.text_input("Name")` | -| `st.text_area()` | Multi-line text | `notes = st.text_area("Notes")` | -| `st.number_input()` | Numbers | `age = st.number_input("Age", 0, 100)` | -| `st.selectbox()` | Single selection | `choice = st.selectbox("Pick", options)` | -| `st.multiselect()` | Multiple selection | `choices = st.multiselect("Pick", options)` | -| `st.slider()` | Range selection | `value = st.slider("Value", 0, 100)` | -| `st.date_input()` | Date picker | `date = st.date_input("Date")` | -| `st.checkbox()` | Boolean toggle | `if st.checkbox("Agree"):` | -| `st.radio()` | Single choice | `choice = st.radio("Pick", options)` | - -### Display Components - -| Component | Use Case | Example | -|-----------|----------|---------| -| `st.dataframe()` | Read-only tables | `st.dataframe(df)` | -| `st.data_editor()` | Editable tables | `edited = st.data_editor(df)` | -| `st.metric()` | KPI displays | `st.metric("Sales", "$1M", "+10%")` | -| `st.json()` | JSON display | `st.json({"key": "value"})` | -| `st.code()` | Code blocks | `st.code("print('hello')")` | - -### Layout Components - -| Component | Use Case | Example | -|-----------|----------|---------| -| `st.columns()` | Side-by-side | `col1, col2 = st.columns(2)` | -| `st.expander()` | Collapsible | `with st.expander("Details"):` | -| `st.tabs()` | Tabbed interface | `tab1, tab2 = st.tabs(["A", "B"])` | -| `st.container()` | Grouping | `with st.container():` | -| `st.empty()` | Placeholder | `placeholder = st.empty()` | - -### Status Components - -| Component | Use Case | Example | -|-----------|----------|---------| -| `st.success()` | Success message | `st.success("Saved!")` | -| `st.error()` | Error message | `st.error("Failed!")` | -| `st.warning()` | Warning message | `st.warning("Caution!")` | -| `st.info()` | Info message | `st.info("Note: ...")` | -| `st.spinner()` | Loading indicator | `with st.spinner("Loading..."):` | -| `st.progress()` | Progress bar | `st.progress(0.5)` | - ---- - -## Common Pitfalls - -### 1. Page Config Not First - -**❌ Wrong:** -```python -import streamlit as st -st.title("My App") -st.set_page_config(...) # Error! -``` - -**✅ Correct:** -```python -import streamlit as st -st.set_page_config(...) # Must be first! -st.title("My App") -``` - -### 2. Not Caching Connections - -**❌ Wrong:** -```python -def get_data(): - conn = sql.connect(...) # Creates new connection every rerun! - return conn.cursor().fetchall() -``` - -**✅ Correct:** -```python -@st.cache_resource -def get_connection(): - return sql.connect(...) - -def get_data(): - conn = get_connection() # Reuses cached connection - return conn.cursor().fetchall() -``` - -### 3. Expensive Operations in Main Flow - -**❌ Wrong:** -```python -# Runs on every rerun! -data = expensive_api_call() -processed_data = expensive_processing(data) -``` - -**✅ Correct:** -```python -@st.cache_data(ttl=300) -def get_processed_data(): - data = expensive_api_call() - return expensive_processing(data) - -data = get_processed_data() # Cached for 5 minutes -``` - -### 4. Not Using Forms for Multiple Inputs - -**❌ Wrong:** -```python -# Page reruns on EVERY input change -name = st.text_input("Name") # Rerun -email = st.text_input("Email") # Rerun -phone = st.text_input("Phone") # Rerun -``` - -**✅ Correct:** -```python -# Page only reruns on submit -with st.form("user_form"): - name = st.text_input("Name") - email = st.text_input("Email") - phone = st.text_input("Phone") - submitted = st.form_submit_button("Submit") -``` - -### 5. Modifying State During Render - -**❌ Wrong:** -```python -if st.button("Increment"): - st.session_state.count += 1 # ❌ Can cause issues - st.write(st.session_state.count) # May not update immediately -``` - -**✅ Correct:** -```python -if 'count' not in st.session_state: - st.session_state.count = 0 - -if st.button("Increment"): - st.session_state.count += 1 - -st.write(f"Count: {st.session_state.count}") # Display outside callback -``` - ---- - -## Performance Optimization - -### 1. Use Appropriate Caching - -```python -# For connections (persist across sessions) -@st.cache_resource -def get_db_connection(): - return sql.connect(...) - -# For data (serialize and cache with TTL) -@st.cache_data(ttl=600) -def load_orders(): - return fetch_orders() -``` - -### 2. Lazy Loading - -```python -# Don't load all data upfront -def load_page(): - if page == "Dashboard": - load_dashboard_data() # Only load what's needed - elif page == "Orders": - load_orders_data() -``` - -### 3. Pagination - -```python -# Don't display 10,000 rows at once -page_size = 50 -page_num = st.number_input("Page", min_value=1, value=1) - -start_idx = (page_num - 1) * page_size -end_idx = start_idx + page_size - -st.dataframe(df[start_idx:end_idx]) -``` - -### 4. Debouncing with Forms - -```python -# Use forms to prevent reruns on every keystroke -with st.form("search_form"): - search = st.text_input("Search") - submitted = st.form_submit_button("Search") - -if submitted and search: - results = backend.search(search) - st.dataframe(results) -``` - -### 5. Fragment Updates (Streamlit 1.24+) - -```python -@st.experimental_fragment -def render_chart(): - """Only this fragment reruns, not entire page""" - data = load_chart_data() - st.plotly_chart(create_chart(data)) - -# Main page doesn't rerun when fragment updates -st.title("Dashboard") -render_chart() -``` - ---- - -## Deployment Configuration - -### app.yaml for Databricks - -```yaml -command: - - "streamlit" - - "run" - - "streamlit_app.py" - - "--server.port" - - "8080" - - "--server.address" - - "0.0.0.0" - - "--server.headless" - - "true" - -env: - - name: USE_MOCK_BACKEND - value: "false" - - name: DATABRICKS_WAREHOUSE_ID - value: "your-warehouse-id" - - name: DATABRICKS_CATALOG - value: "main" - - name: DATABRICKS_SCHEMA - value: "app_schema" -``` - -### requirements.txt - -```txt -streamlit>=1.28.0 -pandas>=2.0.0 -plotly>=5.17.0 -databricks-sdk>=0.12.0 -databricks-sql-connector>=3.0.0 -pydantic>=2.0.0 -python-dotenv>=1.0.0 -``` - ---- - -## Reference Resources - -- **[Databricks Streamlit Tutorial](https://docs.databricks.com/aws/en/dev-tools/databricks-apps/tutorial-streamlit)** - Official tutorial -- **[Databricks Apps Cookbook - Streamlit](https://apps-cookbook.dev/docs/category/streamlit/)** - Code examples -- **[Streamlit Read Delta Table](https://apps-cookbook.dev/docs/streamlit/tables/tables_read/)** - Connection patterns -- **[Streamlit Documentation](https://docs.streamlit.io/)** - Full API reference - ---- - -## Key Takeaways - -1. **Always cache resources** - Use `@st.cache_resource` for connections -2. **Page config first** - Must be the first Streamlit command -3. **Use forms** - Prevent reruns for multiple inputs -4. **Session state** - For data persistence across reruns -5. **SDK Config pattern** - For Databricks authentication -6. **Layout wisely** - Columns, expanders, tabs for organization -7. **Handle errors** - Graceful degradation and user feedback - -Streamlit is perfect for rapid development of data-focused applications on Databricks! diff --git a/.claude/skills/asset-bundles/SDP_guidance.md b/.claude/skills/databricks-asset-bundles/SDP_guidance.md similarity index 100% rename from .claude/skills/asset-bundles/SDP_guidance.md rename to .claude/skills/databricks-asset-bundles/SDP_guidance.md diff --git a/.claude/skills/asset-bundles/SKILL.md b/.claude/skills/databricks-asset-bundles/SKILL.md similarity index 89% rename from .claude/skills/asset-bundles/SKILL.md rename to .claude/skills/databricks-asset-bundles/SKILL.md index 02e11d00..4253e8e9 100644 --- a/.claude/skills/asset-bundles/SKILL.md +++ b/.claude/skills/databricks-asset-bundles/SKILL.md @@ -1,5 +1,5 @@ --- -name: asset-bundles +name: databricks-asset-bundles description: "Create and configure Databricks Asset Bundles (DABs) with best practices for multi-environment deployments. Use when working with: (1) Creating new DAB projects, (2) Adding resources (dashboards, pipelines, jobs, alerts), (3) Configuring multi-environment deployments, (4) Setting up permissions, (5) Deploying or running bundle resources" --- @@ -61,6 +61,8 @@ targets: ### Dashboard Resources +**Support for dataset_catalog and dataset_schema parameters added in Databricks CLI 0.281.0 (January 2026)** + ```yaml resources: dashboards: @@ -68,6 +70,8 @@ resources: display_name: "[${bundle.target}] Dashboard Title" file_path: ../src/dashboards/dashboard.lvdash.json # Relative to resources/ warehouse_id: ${var.warehouse_id} + dataset_catalog: ${var.catalog} # Default catalog used by all datasets in the dashboard if not otherwise specified in the query + dataset_schema: ${var.schema} # Default schema used by all datasets in the dashboard if not otherwise specified in the query permissions: - level: CAN_RUN group_name: "users" @@ -289,7 +293,7 @@ databricks bundle destroy -t prod --auto-approve | **Catalog doesn't exist** | Create catalog first or update variable | | **"admins" group error on jobs** | Cannot modify admins permissions on jobs | | **Volume permissions** | Use `grants` not `permissions` for volumes | -| **Hardcoded catalog in dashboard** | Create environment-specific files or parameterize JSON | +| **Hardcoded catalog in dashboard** | Use dataset_catalog parameter (CLI v0.281.0+), create environment-specific files, or parameterize JSON | | **App not starting after deploy** | Apps require `databricks bundle run ` to start | | **App env vars not working** | Environment variables go in `app.yaml` (source dir), not databricks.yml | | **Wrong app source path** | Use `../` from resources/ dir if source is in project root | @@ -303,6 +307,14 @@ databricks bundle destroy -t prod --auto-approve 4. **Groups**: Use `"users"` for all workspace users 5. **Job permissions**: Verify custom groups exist; can't modify "admins" +## Related Skills + +- **[databricks-spark-declarative-pipelines](../databricks-spark-declarative-pipelines/SKILL.md)** - pipeline definitions referenced by DABs +- **[databricks-app-apx](../databricks-app-apx/SKILL.md)** - app deployment via DABs +- **[databricks-app-python](../databricks-app-python/SKILL.md)** - Python app deployment via DABs +- **[databricks-config](../databricks-config/SKILL.md)** - profile and authentication setup for CLI/SDK +- **[databricks-jobs](../databricks-jobs/SKILL.md)** - job orchestration managed through bundles + ## Resources - [Databricks Asset Bundles Documentation](https://docs.databricks.com/dev-tools/bundles/) diff --git a/.claude/skills/asset-bundles/alerts_guidance.md b/.claude/skills/databricks-asset-bundles/alerts_guidance.md similarity index 100% rename from .claude/skills/asset-bundles/alerts_guidance.md rename to .claude/skills/databricks-asset-bundles/alerts_guidance.md diff --git a/.claude/skills/databricks-config/SKILL.md b/.claude/skills/databricks-config/SKILL.md index 12952293..2053f152 100644 --- a/.claude/skills/databricks-config/SKILL.md +++ b/.claude/skills/databricks-config/SKILL.md @@ -72,3 +72,10 @@ cluster_id = 1217-064531-c9c3ngyn View full configuration at: ~/.databrickscfg ``` + +## Related Skills + +- **[databricks-python-sdk](../databricks-python-sdk/SKILL.md)** - uses profiles configured by this skill +- **[databricks-asset-bundles](../databricks-asset-bundles/SKILL.md)** - references workspace profiles for deployment targets +- **[databricks-app-apx](../databricks-app-apx/SKILL.md)** - apps that connect via configured profiles +- **[databricks-app-python](../databricks-app-python/SKILL.md)** - Python apps using configured profiles diff --git a/.claude/skills/databricks-dbsql/SKILL.md b/.claude/skills/databricks-dbsql/SKILL.md new file mode 100644 index 00000000..24bf2694 --- /dev/null +++ b/.claude/skills/databricks-dbsql/SKILL.md @@ -0,0 +1,300 @@ +--- +name: databricks-dbsql +description: >- + Databricks SQL (DBSQL) advanced features and SQL warehouse capabilities. + This skill MUST be invoked when the user mentions: "DBSQL", "Databricks SQL", + "SQL warehouse", "SQL scripting", "stored procedure", "CALL procedure", + "materialized view", "CREATE MATERIALIZED VIEW", "pipe syntax", "|>", + "geospatial", "H3", "ST_", "spatial SQL", "collation", "COLLATE", + "ai_query", "ai_classify", "ai_extract", "ai_gen", "AI function", + "http_request", "remote_query", "read_files", "Lakehouse Federation", + "recursive CTE", "WITH RECURSIVE", "multi-statement transaction", + "temp table", "temporary view", "pipe operator". + SHOULD also invoke when the user asks about SQL best practices, data modeling + patterns, or advanced SQL features on Databricks. +--- + +# Databricks SQL (DBSQL) - Advanced Features + +## Quick Reference + +| Feature | Key Syntax | Since | Reference | +|---------|-----------|-------|-----------| +| SQL Scripting | `BEGIN...END`, `DECLARE`, `IF/WHILE/FOR` | DBR 16.3+ | [sql-scripting.md](sql-scripting.md) | +| Stored Procedures | `CREATE PROCEDURE`, `CALL` | DBR 17.0+ | [sql-scripting.md](sql-scripting.md) | +| Recursive CTEs | `WITH RECURSIVE` | DBR 17.0+ | [sql-scripting.md](sql-scripting.md) | +| Transactions | `BEGIN ATOMIC...END` | Preview | [sql-scripting.md](sql-scripting.md) | +| Materialized Views | `CREATE MATERIALIZED VIEW` | Pro/Serverless | [materialized-views-pipes.md](materialized-views-pipes.md) | +| Temp Tables | `CREATE TEMPORARY TABLE` | All | [materialized-views-pipes.md](materialized-views-pipes.md) | +| Pipe Syntax | `\|>` operator | DBR 16.1+ | [materialized-views-pipes.md](materialized-views-pipes.md) | +| Geospatial (H3) | `h3_longlatash3()`, `h3_polyfillash3()` | DBR 11.2+ | [geospatial-collations.md](geospatial-collations.md) | +| Geospatial (ST) | `ST_Point()`, `ST_Contains()`, 80+ funcs | DBR 16.0+ | [geospatial-collations.md](geospatial-collations.md) | +| Collations | `COLLATE`, `UTF8_LCASE`, locale-aware | DBR 16.1+ | [geospatial-collations.md](geospatial-collations.md) | +| AI Functions | `ai_query()`, `ai_classify()`, 11+ funcs | DBR 15.1+ | [ai-functions.md](ai-functions.md) | +| http_request | `http_request(conn, ...)` | Pro/Serverless | [ai-functions.md](ai-functions.md) | +| remote_query | `SELECT * FROM remote_query(...)` | Pro/Serverless | [ai-functions.md](ai-functions.md) | +| read_files | `SELECT * FROM read_files(...)` | All | [ai-functions.md](ai-functions.md) | +| Data Modeling | Star schema, Liquid Clustering | All | [best-practices.md](best-practices.md) | + +--- + +## Common Patterns + +### SQL Scripting - Procedural ETL + +```sql +BEGIN + DECLARE v_count INT; + DECLARE v_status STRING DEFAULT 'pending'; + + SET v_count = (SELECT COUNT(*) FROM catalog.schema.raw_orders WHERE status = 'new'); + + IF v_count > 0 THEN + INSERT INTO catalog.schema.processed_orders + SELECT *, current_timestamp() AS processed_at + FROM catalog.schema.raw_orders + WHERE status = 'new'; + + SET v_status = 'completed'; + ELSE + SET v_status = 'skipped'; + END IF; + + SELECT v_status AS result, v_count AS rows_processed; +END +``` + +### Stored Procedure with Error Handling + +```sql +CREATE OR REPLACE PROCEDURE catalog.schema.upsert_customers( + IN p_source STRING, + OUT p_rows_affected INT +) +LANGUAGE SQL +SQL SECURITY INVOKER +BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + SET p_rows_affected = -1; + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = concat('Upsert failed for source: ', p_source); + END; + + MERGE INTO catalog.schema.dim_customer AS t + USING (SELECT * FROM identifier(p_source)) AS s + ON t.customer_id = s.customer_id + WHEN MATCHED THEN UPDATE SET * + WHEN NOT MATCHED THEN INSERT *; + + SET p_rows_affected = (SELECT COUNT(*) FROM identifier(p_source)); +END; + +-- Invoke: +CALL catalog.schema.upsert_customers('catalog.schema.staging_customers', ?); +``` + +### Materialized View with Scheduled Refresh + +```sql +CREATE OR REPLACE MATERIALIZED VIEW catalog.schema.daily_revenue + CLUSTER BY (order_date) + SCHEDULE EVERY 1 HOUR + COMMENT 'Hourly-refreshed daily revenue by region' +AS SELECT + order_date, + region, + SUM(amount) AS total_revenue, + COUNT(DISTINCT customer_id) AS unique_customers +FROM catalog.schema.fact_orders +JOIN catalog.schema.dim_store USING (store_id) +GROUP BY order_date, region; +``` + +### Pipe Syntax - Readable Transformations + +```sql +-- Traditional SQL rewritten with pipe syntax +FROM catalog.schema.fact_orders + |> WHERE order_date >= current_date() - INTERVAL 30 DAYS + |> AGGREGATE SUM(amount) AS total, COUNT(*) AS cnt GROUP BY region, product_category + |> WHERE total > 10000 + |> ORDER BY total DESC + |> LIMIT 20; +``` + +### AI Functions - Enrich Data with LLMs + +```sql +-- Classify support tickets +SELECT + ticket_id, + description, + ai_classify(description, ARRAY('billing', 'technical', 'account', 'feature_request')) AS category, + ai_analyze_sentiment(description) AS sentiment +FROM catalog.schema.support_tickets +LIMIT 100; + +-- Extract entities from text +SELECT + doc_id, + ai_extract(content, ARRAY('person_name', 'company', 'dollar_amount')) AS entities +FROM catalog.schema.contracts; + +-- General-purpose AI query with structured output +SELECT ai_query( + 'databricks-meta-llama-3-3-70b-instruct', + concat('Summarize this customer feedback in JSON with keys: topic, sentiment, action_items. Feedback: ', feedback), + returnType => 'STRUCT>' +) AS analysis +FROM catalog.schema.customer_feedback +LIMIT 50; +``` + +### Geospatial - Proximity Search with H3 + +```sql +-- Find stores within 5km of each customer using H3 indexing +WITH customer_h3 AS ( + SELECT *, h3_longlatash3(longitude, latitude, 7) AS h3_cell + FROM catalog.schema.customers +), +store_h3 AS ( + SELECT *, h3_longlatash3(longitude, latitude, 7) AS h3_cell + FROM catalog.schema.stores +) +SELECT + c.customer_id, + s.store_id, + ST_Distance( + ST_Point(c.longitude, c.latitude), + ST_Point(s.longitude, s.latitude) + ) AS distance_m +FROM customer_h3 c +JOIN store_h3 s ON h3_ischildof(c.h3_cell, h3_toparent(s.h3_cell, 5)) +WHERE ST_Distance( + ST_Point(c.longitude, c.latitude), + ST_Point(s.longitude, s.latitude) +) < 5000; +``` + +### Collation - Case-Insensitive Search + +```sql +-- Create table with case-insensitive collation +CREATE TABLE catalog.schema.products ( + product_id BIGINT GENERATED ALWAYS AS IDENTITY, + name STRING COLLATE UTF8_LCASE, + category STRING COLLATE UTF8_LCASE, + price DECIMAL(10, 2) +); + +-- Queries automatically case-insensitive (no LOWER() needed) +SELECT * FROM catalog.schema.products +WHERE name = 'MacBook Pro'; -- matches 'macbook pro', 'MACBOOK PRO', etc. +``` + +### http_request - Call External APIs + +```sql +-- Set up connection first (one-time) +CREATE CONNECTION my_api_conn + TYPE HTTP + OPTIONS (host 'https://api.example.com', bearer_token secret('scope', 'token')); + +-- Call API from SQL +SELECT + order_id, + http_request( + conn => 'my_api_conn', + method => 'POST', + path => '/v1/validate', + json => to_json(named_struct('order_id', order_id, 'amount', amount)) + ).text AS api_response +FROM catalog.schema.orders +WHERE needs_validation = true; +``` + +### read_files - Ingest Raw Files + +```sql +-- Read JSON files from a Volume with schema hints +SELECT * +FROM read_files( + '/Volumes/catalog/schema/raw/events/', + format => 'json', + schemaHints => 'event_id STRING, timestamp TIMESTAMP, payload MAP', + pathGlobFilter => '*.json', + recursiveFileLookup => true +); + +-- Read CSV with options +SELECT * +FROM read_files( + '/Volumes/catalog/schema/raw/sales/', + format => 'csv', + header => true, + delimiter => '|', + dateFormat => 'yyyy-MM-dd', + schema => 'sale_id INT, sale_date DATE, amount DECIMAL(10,2), store STRING' +); +``` + +### Recursive CTE - Hierarchy Traversal + +```sql +WITH RECURSIVE org_chart AS ( + -- Anchor: top-level managers + SELECT employee_id, name, manager_id, 0 AS depth, ARRAY(name) AS path + FROM catalog.schema.employees + WHERE manager_id IS NULL + + UNION ALL + + -- Recursive: direct reports + SELECT e.employee_id, e.name, e.manager_id, o.depth + 1, array_append(o.path, e.name) + FROM catalog.schema.employees e + JOIN org_chart o ON e.manager_id = o.employee_id + WHERE o.depth < 10 -- safety limit +) +SELECT * FROM org_chart ORDER BY depth, name; +``` + +### remote_query - Federated Queries + +```sql +-- Query PostgreSQL via Lakehouse Federation +SELECT * +FROM remote_query( + 'my_postgres_connection', + database => 'my_database', + query => 'SELECT customer_id, email, created_at FROM customers WHERE active = true' +); +``` + +--- + +## Reference Files + +Load these for detailed syntax, full parameter lists, and advanced patterns: + +| File | Contents | When to Read | +|------|----------|--------------| +| [sql-scripting.md](sql-scripting.md) | SQL Scripting, Stored Procedures, Recursive CTEs, Transactions | User needs procedural SQL, error handling, loops, dynamic SQL | +| [materialized-views-pipes.md](materialized-views-pipes.md) | Materialized Views, Temp Tables/Views, Pipe Syntax | User needs MVs, refresh scheduling, temp objects, pipe operator | +| [geospatial-collations.md](geospatial-collations.md) | 39 H3 functions, 80+ ST functions, Collation types and hierarchy | User needs spatial analysis, H3 indexing, case/accent handling | +| [ai-functions.md](ai-functions.md) | 13 AI functions, http_request, remote_query, read_files (all options) | User needs AI enrichment, API calls, federation, file ingestion | +| [best-practices.md](best-practices.md) | Data modeling, performance, Liquid Clustering, anti-patterns | User needs architecture guidance, optimization, or modeling advice | + +--- + +## Key Guidelines + +- **Always use Serverless SQL warehouses** for AI functions, MVs, and http_request +- **Use `LIMIT` during development** with AI functions to control costs +- **Prefer Liquid Clustering over partitioning** for new tables (1-4 keys max) +- **Use `CLUSTER BY AUTO`** when unsure about clustering keys +- **Star schema in Gold layer** for BI; OBT acceptable in Silver +- **Define PK/FK constraints** on dimensional models for query optimization +- **Use `COLLATE UTF8_LCASE`** for user-facing string columns that need case-insensitive search +- **Use MCP tools** (`execute_sql`, `execute_sql_multi`) to test and validate all SQL before deploying diff --git a/.claude/skills/databricks-dbsql/ai-functions.md b/.claude/skills/databricks-dbsql/ai-functions.md new file mode 100644 index 00000000..0853c6bb --- /dev/null +++ b/.claude/skills/databricks-dbsql/ai-functions.md @@ -0,0 +1,1348 @@ +# AI Functions, http_request, remote_query, and read_files Reference + +Comprehensive reference for Databricks SQL advanced functions: built-in AI functions, HTTP requests, Lakehouse Federation remote queries, and file reading. + +--- + +## Table of Contents + +- [AI Functions Overview](#ai-functions-overview) +- [ai_query -- General-Purpose AI Function](#ai_query----general-purpose-ai-function) +- [Task-Specific AI Functions](#task-specific-ai-functions) + - [ai_gen](#ai_gen) + - [ai_classify](#ai_classify) + - [ai_extract](#ai_extract) + - [ai_analyze_sentiment](#ai_analyze_sentiment) + - [ai_similarity](#ai_similarity) + - [ai_summarize](#ai_summarize) + - [ai_translate](#ai_translate) + - [ai_fix_grammar](#ai_fix_grammar) + - [ai_mask](#ai_mask) +- [Document and Multimodal AI Functions](#document-and-multimodal-ai-functions) + - [ai_parse_document](#ai_parse_document) +- [Time Series AI Functions](#time-series-ai-functions) + - [ai_forecast](#ai_forecast) +- [Vector Search Function](#vector-search-function) + - [vector_search](#vector_search) +- [http_request Function](#http_request-function) +- [remote_query Function (Lakehouse Federation)](#remote_query-function-lakehouse-federation) +- [read_files Table-Valued Function](#read_files-table-valued-function) + +--- + +## AI Functions Overview + +Databricks AI Functions are built-in SQL functions that invoke state-of-the-art generative AI models directly from SQL. They run on Databricks Foundation Model APIs and are available from Databricks SQL, notebooks, Lakeflow Spark Declarative Pipelines, and Workflows. + +**Common Requirements for All AI Functions:** +- Workspace must be in a region supporting AI Functions optimized for batch inference +- Not available on Databricks SQL Classic (requires Serverless SQL Warehouse) +- Databricks Runtime 15.1+ for notebooks; 15.4 ML LTS recommended for batch workloads +- Models licensed under Apache 2.0 or LLAMA 3.3 Community License +- Currently tuned for English (underlying models support multiple languages) +- Public Preview, HIPAA compliant + +**Rate Limits and Billing:** +- AI Functions are subject to Foundation Model API rate limits +- Billed as Databricks SQL compute plus token usage on Foundation Model APIs +- Use `LIMIT` in queries during development to control costs + +--- + +## ai_query -- General-Purpose AI Function + +The most powerful and flexible AI function. Queries any serving endpoint (Foundation Models, external models, or custom ML models) for real-time or batch inference. + +### Syntax + +```sql +-- Basic invocation +ai_query(endpoint, request) + +-- Full invocation with all optional parameters +ai_query( + endpoint, + request, + returnType => type_expression, + failOnError => boolean, + modelParameters => named_struct(...), + responseFormat => format_string, + files => content_expression +) +``` + +### Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `endpoint` | STRING | Yes | Name of a Foundation Model, external model, or custom model serving endpoint in the same workspace | +| `request` | STRING or STRUCT | Yes | For LLM endpoints: STRING prompt. For custom ML endpoints: single column or STRUCT matching expected input features | +| `returnType` | Expression | No | Expected return type (DDL-style). Optional in Runtime 15.2+; required in 15.1 and below | +| `failOnError` | BOOLEAN | No | Default `true`. When `false`, returns STRUCT with `response` and `errorStatus` fields instead of failing | +| `modelParameters` | STRUCT | No | Model parameters via `named_struct()` (Runtime 15.3+) | +| `responseFormat` | STRING | No | Controls output format: `'text'`, `'json_object'`, or a DDL/JSON schema string (Runtime 15.4 LTS+, chat models only) | +| `files` | Expression | No | Multimodal file input for image processing (JPEG, PNG supported) | + +### Return Types + +| Scenario | Return Type | +|----------|-------------| +| `failOnError => true` (default) | Parsed response matching endpoint type or `returnType` | +| `failOnError => false` | `STRUCT` where T is the parsed type | +| With `responseFormat` | Structured output matching the specified schema | + +### Model Parameters + +```sql +-- Control generation with modelParameters +SELECT ai_query( + 'databricks-meta-llama-3-3-70b-instruct', + 'Explain quantum computing in 3 sentences.', + modelParameters => named_struct( + 'max_tokens', 256, + 'temperature', 0.1, + 'top_p', 0.9 + ) +) AS response; +``` + +Common model parameters: +- `max_tokens` (INT) -- Maximum tokens to generate +- `temperature` (DOUBLE) -- Randomness (0.0 = deterministic, 2.0 = max random) +- `top_p` (DOUBLE) -- Nucleus sampling threshold +- `stop` (ARRAY) -- Stop sequences + +### Structured Output with responseFormat + +> **Note:** The top-level `responseFormat` STRUCT must contain exactly one field. To return multiple fields, wrap them in a single outer field. + +```sql +-- Force JSON output matching a schema (top-level STRUCT must have exactly one field) +SELECT ai_query( + 'databricks-meta-llama-3-3-70b-instruct', + 'Extract the product name, price, and category from: "Sony WH-1000XM5 headphones, $348, Electronics"', + responseFormat => 'STRUCT>' +) AS extracted; +``` + +### Batch Inference on Tables + +```sql +-- Classify all rows in a table +SELECT + review_id, + review_text, + ai_query( + 'databricks-meta-llama-3-3-70b-instruct', + CONCAT('Classify the following review as positive, negative, or neutral: ', review_text), + responseFormat => 'STRUCT>' + ) AS classification +FROM catalog.schema.product_reviews; +``` + +### Custom ML Model Inference + +```sql +-- Query a custom sklearn/MLflow model +SELECT ai_query( + endpoint => 'spam-classification-endpoint', + request => named_struct( + 'text', email_body, + 'subject', email_subject + ), + returnType => 'BOOLEAN' +) AS is_spam +FROM catalog.schema.inbox_messages; +``` + +### Multimodal (Image) Input + +```sql +-- Analyze images using a vision model +SELECT ai_query( + 'databricks-meta-llama-3-2-90b-instruct', + 'Describe the contents of this image.', + files => READ_FILES('/Volumes/catalog/schema/images/photo.jpg', format => 'binaryFile') +) AS description; +``` + +### Error Handling with failOnError + +```sql +-- Graceful error handling for batch processing +SELECT + id, + result.result AS answer, + result.errorMessage AS error +FROM ( + SELECT + id, + ai_query( + 'databricks-meta-llama-3-3-70b-instruct', + question, + failOnError => false + ) AS result + FROM catalog.schema.questions +); +``` + +### Embedding Generation + +```sql +-- Generate embeddings using ai_query +SELECT + text, + ai_query('databricks-gte-large-en', text) AS embedding +FROM catalog.schema.documents; +``` + +--- + +## Task-Specific AI Functions + +These functions provide simplified, single-purpose interfaces that do not require specifying an endpoint or model. + +### ai_gen + +Generate text from a prompt. + +```sql +ai_gen(prompt) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `prompt` | STRING | The user's request/prompt | + +**Returns:** STRING + +```sql +-- Simple generation +SELECT ai_gen('Generate a concise, cheerful email title for a summer bike sale with 20% discount'); +-- Returns: "Summer Bike Sale: Grab Your Dream Bike at 20% Off!" + +-- Generation using table data +SELECT + question, + ai_gen('You are a teacher. Answer the students question in 50 words: ' || question) AS answer +FROM catalog.schema.questions +LIMIT 10; +``` + +--- + +### ai_classify + +Classify text into one of the provided labels. + +```sql +ai_classify(content, labels) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `content` | STRING | Text to classify | +| `labels` | ARRAY | Classification options (min 2, max 20 elements) | + +**Returns:** STRING matching one of the labels, or NULL if classification fails. + +```sql +-- Simple classification +SELECT ai_classify('My password is leaked.', ARRAY('urgent', 'not urgent')); +-- Returns: "urgent" + +-- Batch product categorization +SELECT + product_name, + description, + ai_classify(description, ARRAY('clothing', 'shoes', 'accessories', 'furniture')) AS category +FROM catalog.schema.products +LIMIT 100; + +-- Support ticket routing +SELECT + ticket_id, + ai_classify( + description, + ARRAY('billing', 'technical', 'account', 'feature_request', 'other') + ) AS department +FROM catalog.schema.support_tickets; +``` + +--- + +### ai_extract + +Extract named entities from text. + +```sql +ai_extract(content, labels) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `content` | STRING | Text to extract entities from | +| `labels` | ARRAY | Entity types to extract | + +**Returns:** STRUCT where each field corresponds to a label, containing the extracted entity as STRING. Returns NULL if content is NULL. + +```sql +-- Extract person, location, organization +SELECT ai_extract( + 'John Doe lives in New York and works for Acme Corp.', + ARRAY('person', 'location', 'organization') +); +-- Returns: {"person": "John Doe", "location": "New York", "organization": "Acme Corp."} + +-- Extract contact details +SELECT ai_extract( + 'Send an email to jane.doe@example.com about the meeting at 10am.', + ARRAY('email', 'time') +); +-- Returns: {"email": "jane.doe@example.com", "time": "10am"} + +-- Batch entity extraction from customer feedback +SELECT + feedback_id, + ai_extract(feedback_text, ARRAY('product', 'issue', 'person')) AS entities +FROM catalog.schema.customer_feedback; +``` + +--- + +### ai_analyze_sentiment + +Perform sentiment analysis on text. + +```sql +ai_analyze_sentiment(content) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `content` | STRING | Text to analyze | + +**Returns:** STRING -- one of `'positive'`, `'negative'`, `'neutral'`, or `'mixed'`. Returns NULL if sentiment cannot be determined. + +```sql +SELECT ai_analyze_sentiment('I am happy'); -- Returns: "positive" +SELECT ai_analyze_sentiment('I am sad'); -- Returns: "negative" +SELECT ai_analyze_sentiment('It is what it is'); -- Returns: "neutral" + +-- Aggregate sentiment by product +SELECT + product_id, + ai_analyze_sentiment(review_text) AS sentiment, + COUNT(*) AS review_count +FROM catalog.schema.reviews +GROUP BY product_id, ai_analyze_sentiment(review_text); +``` + +--- + +### ai_similarity + +Compute semantic similarity between two text strings. + +```sql +ai_similarity(expr1, expr2) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `expr1` | STRING | First text to compare | +| `expr2` | STRING | Second text to compare | + +**Returns:** FLOAT -- Semantic similarity score where 1.0 means identical. The score is relative and should only be used for ranking. + +```sql +-- Exact match +SELECT ai_similarity('Apache Spark', 'Apache Spark'); +-- Returns: 1.0 + +-- Find similar company names (fuzzy matching) +SELECT company_name, ai_similarity(company_name, 'Databricks') AS score +FROM catalog.schema.customers +ORDER BY score DESC +LIMIT 10; + +-- Duplicate detection +SELECT + a.id AS id_a, + b.id AS id_b, + ai_similarity(a.description, b.description) AS similarity +FROM catalog.schema.products a +JOIN catalog.schema.products b ON a.id < b.id +WHERE ai_similarity(a.description, b.description) > 0.85; +``` + +--- + +### ai_summarize + +Generate a summary of text. + +```sql +ai_summarize(content [, max_words]) +``` + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `content` | STRING | Yes | Text to summarize | +| `max_words` | INTEGER | No | Target word count for summary. Default: 50. Set to 0 for no limit | + +**Returns:** STRING. Returns NULL if content is NULL. + +```sql +-- Summarize with default 50-word limit +SELECT ai_summarize( + 'Apache Spark is a unified analytics engine for large-scale data processing. ' + || 'It provides high-level APIs in Java, Scala, Python and R, and an optimized ' + || 'engine that supports general execution graphs.' +); + +-- Summarize with custom word limit +SELECT ai_summarize(article_body, 100) AS summary +FROM catalog.schema.articles; + +-- Executive summaries for reports +SELECT + report_id, + report_title, + ai_summarize(report_body, 30) AS executive_summary +FROM catalog.schema.quarterly_reports; +``` + +--- + +### ai_translate + +Translate text to a target language. + +```sql +ai_translate(content, to_lang) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `content` | STRING | Text to translate | +| `to_lang` | STRING | Target language code | + +**Supported Languages:** English (`en`), German (`de`), French (`fr`), Italian (`it`), Portuguese (`pt`), Hindi (`hi`), Spanish (`es`), Thai (`th`). + +**Returns:** STRING. Returns NULL if content is NULL. + +```sql +-- English to Spanish +SELECT ai_translate('Hello, how are you?', 'es'); +-- Returns: "Hola, como estas?" + +-- Spanish to English +SELECT ai_translate('La vida es un hermoso viaje.', 'en'); +-- Returns: "Life is a beautiful journey." + +-- Translate product descriptions for localization +SELECT + product_id, + description AS original, + ai_translate(description, 'fr') AS french, + ai_translate(description, 'de') AS german +FROM catalog.schema.products; +``` + +--- + +### ai_fix_grammar + +Correct grammatical errors in text. + +```sql +ai_fix_grammar(content) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `content` | STRING | Text to correct | + +**Returns:** STRING with corrected grammar. Returns NULL if content is NULL. + +```sql +SELECT ai_fix_grammar('This sentence have some mistake'); +-- Returns: "This sentence has some mistakes" + +SELECT ai_fix_grammar('She dont know what to did.'); +-- Returns: "She doesn't know what to do." + +-- Clean up user-generated content +SELECT + comment_id, + original_text, + ai_fix_grammar(original_text) AS corrected_text +FROM catalog.schema.user_comments; +``` + +--- + +### ai_mask + +Mask specified entity types in text (PII redaction). + +```sql +ai_mask(content, labels) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `content` | STRING | Text containing entities to mask | +| `labels` | ARRAY | Entity types to mask (e.g., `'person'`, `'email'`, `'phone'`, `'address'`, `'location'`, `'ssn'`, `'credit_card'`) | + +**Returns:** STRING with specified entities replaced by `[MASKED]`. Returns NULL if content is NULL. + +```sql +-- Mask personal information +SELECT ai_mask( + 'John Doe lives in New York. His email is john.doe@example.com.', + ARRAY('person', 'email') +); +-- Returns: "[MASKED] lives in New York. His email is [MASKED]." + +-- Mask contact details +SELECT ai_mask( + 'Contact me at 555-1234 or visit us at 123 Main St.', + ARRAY('phone', 'address') +); +-- Returns: "Contact me at [MASKED] or visit us at [MASKED]" + +-- Create anonymized dataset +CREATE TABLE catalog.schema.anonymized_feedback AS +SELECT + feedback_id, + ai_mask(feedback_text, ARRAY('person', 'email', 'phone', 'address')) AS masked_text, + category +FROM catalog.schema.customer_feedback; +``` + +--- + +## Document and Multimodal AI Functions + +### ai_parse_document + +Extract structured content from unstructured documents (PDF, DOCX, PPTX, images). + +```sql +ai_parse_document(content) +ai_parse_document(content, options_map) +``` + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `content` | BINARY | Yes | Document as binary blob data | +| `options` | MAP | No | Configuration options | + +**Options Map Keys:** + +| Key | Values | Description | +|-----|--------|-------------| +| `version` | `'2.0'` | Output schema version | +| `imageOutputPath` | Volume path | Path to save rendered page images in Unity Catalog volume | +| `descriptionElementTypes` | `''`, `'figure'`, `'*'` | Controls AI-generated descriptions. Default: `'*'` (all elements) | + +**Returns:** VARIANT with structure: +- `document.pages[]` -- Page metadata (id, image_uri) +- `document.elements[]` -- Extracted content (type, content, bbox, description) +- `error_status[]` -- Error details per page +- `metadata` -- File and schema version info + +**Supported Formats:** PDF, JPG/JPEG, PNG, DOC/DOCX, PPT/PPTX + +**Requirements:** Databricks Runtime 17.1+, US/EU region or cross-geography routing enabled. + +```sql +-- Basic document parsing +SELECT ai_parse_document(content) +FROM READ_FILES('/Volumes/catalog/schema/volume/docs/', format => 'binaryFile'); + +-- Parse with options (save images, version 2.0) +SELECT ai_parse_document( + content, + map( + 'version', '2.0', + 'imageOutputPath', '/Volumes/catalog/schema/volume/images/', + 'descriptionElementTypes', '*' + ) +) +FROM READ_FILES('/Volumes/catalog/schema/volume/invoices/', format => 'binaryFile'); + +-- Parse documents then extract structured data with ai_query +WITH parsed AS ( + SELECT + path, + ai_parse_document(content) AS doc + FROM READ_FILES('/Volumes/catalog/schema/volume/invoices/', format => 'binaryFile') +) +SELECT + path, + ai_query( + 'databricks-meta-llama-3-3-70b-instruct', + CONCAT('Extract vendor name, invoice number, and total from: ', doc:document:elements[0]:content::STRING), + responseFormat => 'STRUCT' + ) AS invoice_data +FROM parsed; +``` + +--- + +## Time Series AI Functions + +### ai_forecast + +Forecast time series data using a built-in prophet-like model. This is a table-valued function (TVF). + +```sql +ai_forecast( + observed TABLE, + horizon DATE | TIMESTAMP | STRING, + time_col STRING, + value_col STRING | ARRAY, + group_col STRING | ARRAY | NULL DEFAULT NULL, + prediction_interval_width DOUBLE DEFAULT 0.95, + frequency STRING DEFAULT 'auto', + seed INTEGER | NULL DEFAULT NULL, + parameters STRING DEFAULT '{}' +) +``` + +### Parameters + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `observed` | TABLE | Required | Training data passed as `TABLE(subquery)` or `TABLE(table_name)` | +| `horizon` | DATE/TIMESTAMP/STRING | Required | Right-exclusive forecast end time | +| `time_col` | STRING | Required | Name of DATE or TIMESTAMP column in observed data | +| `value_col` | STRING or ARRAY | Required | One or more numeric columns to forecast | +| `group_col` | STRING, ARRAY, or NULL | NULL | Partition column(s) for independent per-group forecasts | +| `prediction_interval_width` | DOUBLE | 0.95 | Confidence level for prediction bounds (0 to 1) | +| `frequency` | STRING | `'auto'` | Time granularity. Auto-infers from recent data. For DATE columns use: `'day'`, `'week'`, `'month'`. For TIMESTAMP columns: `'D'`, `'W'`, `'M'`, `'H'`, etc. | +| `seed` | INTEGER or NULL | NULL | Random seed for reproducibility | +| `parameters` | STRING | `'{}'` | JSON-encoded advanced settings | + +**Advanced Parameters (JSON):** +- `global_cap` -- Upper bound for logistic growth +- `global_floor` -- Lower bound for logistic growth +- `daily_order` -- Fourier order for daily seasonality +- `weekly_order` -- Fourier order for weekly seasonality + +### Return Columns + +For each `value_col` named `v`, the output contains: +- `{v}_forecast` (DOUBLE) -- Point forecast +- `{v}_upper` (DOUBLE) -- Upper prediction bound +- `{v}_lower` (DOUBLE) -- Lower prediction bound +- Plus the original time column and group columns + +**Requirements:** Serverless SQL Warehouse. + +```sql +-- Basic revenue forecast +SELECT * FROM ai_forecast( + TABLE(SELECT ds, revenue FROM catalog.schema.daily_sales), + horizon => '2025-12-31', + time_col => 'ds', + value_col => 'revenue' +); + +-- Multi-metric forecast by group +SELECT * FROM ai_forecast( + TABLE( + SELECT date, zipcode, revenue, trip_count + FROM catalog.schema.regional_metrics + ), + horizon => '2025-06-30', + time_col => 'date', + value_col => ARRAY('revenue', 'trip_count'), + group_col => 'zipcode', + prediction_interval_width => 0.90, + frequency => 'D' +); + +-- Monthly forecast with growth constraints (use 'month' for DATE columns, not 'M') +SELECT * FROM ai_forecast( + TABLE(catalog.schema.monthly_kpis), + horizon => '2026-01-01', + time_col => 'month', + value_col => 'active_users', + frequency => 'month', + parameters => '{"global_floor": 0}' +); +``` + +--- + +## Vector Search Function + +### vector_search + +Query a Mosaic AI Vector Search index using SQL. This is a table-valued function. + +```sql +-- Databricks Runtime 15.3+ +SELECT * FROM vector_search( + index => index_name, + query_text => search_text, -- OR query_vector => embedding_array + num_results => max_results, + query_type => 'ANN' | 'HYBRID' +) +``` + +### Parameters (Named Arguments Required) + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `index` | STRING constant | Required | Fully qualified name of the vector search index | +| `query_text` | STRING | -- | Search string (for Delta Sync indexes with embedding source) | +| `query_vector` | ARRAY | -- | Pre-computed embedding vector to search | +| `num_results` | INTEGER | 10 | Max records returned (max 100) | +| `query_type` | STRING | `'ANN'` | `'ANN'` for approximate nearest neighbor, `'HYBRID'` for hybrid search | + +**Returns:** Table containing all index columns with top matching records. + +**Requirements:** Serverless SQL Warehouse, Select permission on the index. + +```sql +-- Text-based similarity search +SELECT * FROM vector_search( + index => 'catalog.schema.product_index', + query_text => 'wireless noise canceling headphones', + num_results => 5 +); + +-- Hybrid search (combines keyword + semantic) +SELECT * FROM vector_search( + index => 'catalog.schema.support_docs_index', + query_text => 'Wi-Fi connection issues with router model LMP-9R2', + query_type => 'HYBRID', + num_results => 3 +); + +-- Vector-based search with pre-computed embedding +SELECT * FROM vector_search( + index => 'catalog.schema.embeddings_index', + query_vector => ARRAY(0.45, -0.35, 0.78, 0.22), + num_results => 10 +); + +-- Batch search using LATERAL join +SELECT + q.query_text, + q.query_id, + results.* +FROM catalog.schema.search_queries q, +LATERAL ( + SELECT * FROM vector_search( + index => 'catalog.schema.knowledge_base_index', + query_text => q.query_text, + num_results => 3 + ) +) AS results; +``` + +--- + +## http_request Function + +Make HTTP requests to external services from SQL using Unity Catalog HTTP connections. + +### Syntax + +```sql +http_request( + CONN => connection_name, + METHOD => http_method, + PATH => path, + HEADERS => header_map, + PARAMS => param_map, + JSON => json_body +) +``` + +### Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `CONN` | STRING constant | Yes | Name of an existing HTTP connection | +| `METHOD` | STRING constant | Yes | HTTP method: `'GET'`, `'POST'`, `'PUT'`, `'DELETE'`, `'PATCH'` | +| `PATH` | STRING constant | Yes | Path appended to the connection's base_path. Cannot contain directory traversal (`../`) | +| `HEADERS` | MAP | No | Request headers. Default: NULL | +| `PARAMS` | MAP | No | Query parameters. Default: NULL | +| `JSON` | STRING expression | No | Request body as JSON string | + +### Return Type + +`STRUCT` +- `status_code` -- HTTP response status (e.g., 200, 403, 404) +- `text` -- Response body (typically JSON) + +**Requirements:** Databricks Runtime 16.2+, Unity Catalog enabled workspace, USE CONNECTION privilege. + +### Creating HTTP Connections + +```sql +-- Bearer token authentication +CREATE CONNECTION slack_conn TYPE HTTP +OPTIONS ( + host 'https://slack.com', + port '443', + base_path '/api/', + bearer_token secret('my-scope', 'slack-token') +); + +-- OAuth Machine-to-Machine +CREATE CONNECTION github_conn TYPE HTTP +OPTIONS ( + host 'https://api.github.com', + port '443', + base_path '/', + client_id secret('my-scope', 'github-client-id'), + client_secret secret('my-scope', 'github-client-secret'), + oauth_scope 'repo read:org', + token_endpoint 'https://github.com/login/oauth/access_token' +); +``` + +**Connection Options:** + +| Option | Type | Description | +|--------|------|-------------| +| `host` | STRING | Base URL of the external service | +| `port` | STRING | Network port (typically `'443'` for HTTPS) | +| `base_path` | STRING | Root path for API endpoints | +| `bearer_token` | STRING | Auth token (use `secret()` for security) | +| `client_id` | STRING | OAuth application identifier | +| `client_secret` | STRING | OAuth application secret | +| `oauth_scope` | STRING | Space-delimited OAuth scopes | +| `token_endpoint` | STRING | OAuth token endpoint URL | +| `authorization_endpoint` | STRING | OAuth authorization redirect URL | +| `oauth_credential_exchange_method` | STRING | `'header_and_body'`, `'body_only'`, or `'header_only'` | + +### Examples + +```sql +-- POST a Slack message +SELECT http_request( + CONN => 'slack_conn', + METHOD => 'POST', + PATH => '/chat.postMessage', + JSON => to_json(named_struct('channel', '#alerts', 'text', 'Pipeline completed successfully')) +); + +-- GET request with headers and params +SELECT http_request( + CONN => 'github_conn', + METHOD => 'GET', + PATH => '/repos/databricks/spark/issues', + HEADERS => map('Accept', 'application/vnd.github+json'), + PARAMS => map('state', 'open', 'per_page', '5') +); + +-- Parse JSON response +SELECT + response.status_code, + from_json(response.text, 'STRUCT') AS issue +FROM ( + SELECT http_request( + CONN => 'github_conn', + METHOD => 'GET', + PATH => '/repos/databricks/spark/issues/1' + ) AS response +); + +-- Webhook notification triggered by data changes +SELECT http_request( + CONN => 'webhook_conn', + METHOD => 'POST', + PATH => '/notify', + JSON => to_json(named_struct( + 'event', 'data_quality_alert', + 'table', 'catalog.schema.orders', + 'message', CONCAT('Null rate exceeded threshold: ', CAST(null_pct AS STRING)) + )) +) +FROM catalog.schema.data_quality_metrics +WHERE null_pct > 0.05; +``` + +--- + +## remote_query Function (Lakehouse Federation) + +Run SQL queries against external databases using their native SQL syntax, returning results as a table in Databricks SQL. This is a table-valued function. + +### Overview + +Lakehouse Federation enables querying external databases without migrating data. It supports two modes: +- **Query Federation** -- Queries are pushed down to external databases via JDBC +- **Catalog Federation** -- Queries access foreign tables directly in object storage + +### Syntax + +```sql +SELECT * FROM remote_query( + '', + => '' + [, ...] +) +``` + +### Supported Databases + +| Database | Connection Type | +|----------|----------------| +| PostgreSQL | `POSTGRESQL` | +| MySQL | `MYSQL` | +| Microsoft SQL Server | `SQLSERVER` | +| Oracle | `ORACLE` | +| Teradata | `TERADATA` | +| Amazon Redshift | `REDSHIFT` | +| Snowflake | `SNOWFLAKE` | +| Google BigQuery | `BIGQUERY` | +| Databricks | `DATABRICKS` | + +### Parameters by Database Type + +**PostgreSQL / MySQL / SQL Server / Redshift / Teradata:** + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `database` | STRING | Yes | Remote database name | +| `query` | STRING | One of query/dbtable | SQL query in the remote database's native syntax | +| `dbtable` | STRING | One of query/dbtable | Fully qualified table name | +| `fetchsize` | STRING | No | Number of rows to fetch per round trip | +| `partitionColumn` | STRING | No | Column used for parallel read partitioning | +| `lowerBound` | STRING | No | Lower bound for partition column | +| `upperBound` | STRING | No | Upper bound for partition column | +| `numPartitions` | STRING | No | Number of parallel partitions | + +**Oracle (uses `service_name` instead of `database`):** + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `service_name` | STRING | Yes | Oracle service name | +| `query` or `dbtable` | STRING | Yes (one required) | Query or table reference | + +**Snowflake:** + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `database` | STRING | Yes | Snowflake database | +| `schema` | STRING | No | Schema name (defaults to `public`) | +| `query` or `dbtable` | STRING | Yes (one required) | Query or table reference | +| `query_timeout` | STRING | No | Query timeout in seconds | +| `partition_size_in_mb` | STRING | No | Partition size for reads | + +**BigQuery:** + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `query` or `dbtable` | STRING | Yes (one required) | Query or table reference | +| `materializationDataset` | STRING | For views/complex queries | Dataset for materialization | +| `materializationProject` | STRING | No | GCP project for materialization | +| `parentProject` | STRING | No | Parent GCP project | + +### Pushdown Control + +| Option | Default | Description | +|--------|---------|-------------| +| `pushdown.limit.enabled` | `true` | Push LIMIT to remote | +| `pushdown.offset.enabled` | `true` | Push OFFSET to remote | +| `pushdown.filters.enabled` | `true` | Push WHERE filters to remote | +| `pushdown.aggregates.enabled` | `true` | Push aggregations to remote | +| `pushdown.sortLimit.enabled` | `true` | Push ORDER BY + LIMIT to remote | + +### Requirements + +- Unity Catalog enabled workspace +- Databricks Runtime 17.3+ (clusters) or SQL Warehouse 2025.35+ (Pro/Serverless) +- Network connectivity to target database +- `USE CONNECTION` privilege or `SELECT` on a wrapping view + +### Limitations + +- **Read-only**: Only SELECT queries supported (no INSERT, UPDATE, DELETE, MERGE, DDL, or stored procedures) + +### Creating Connections + +```sql +-- PostgreSQL connection +CREATE CONNECTION my_postgres TYPE POSTGRESQL +OPTIONS ( + host 'pg-server.example.com', + port '5432', + user secret('my-scope', 'pg-user'), + password secret('my-scope', 'pg-password') +); + +-- SQL Server connection +CREATE CONNECTION my_sqlserver TYPE SQLSERVER +OPTIONS ( + host 'sql-server.example.com', + port '1433', + user secret('my-scope', 'sql-user'), + password secret('my-scope', 'sql-password') +); +``` + +### Examples + +```sql +-- Basic query against PostgreSQL +SELECT * FROM remote_query( + 'my_postgres', + database => 'sales_db', + query => 'SELECT customer_id, name, email FROM customers WHERE active = true' +); + +-- Parallel read from SQL Server +SELECT * FROM remote_query( + 'my_sqlserver', + database => 'orders_db', + dbtable => 'dbo.transactions', + partitionColumn => 'transaction_id', + lowerBound => '0', + upperBound => '1000000', + numPartitions => '10' +); + +-- Join federated data with local Delta tables +SELECT + o.order_id, + o.amount, + c.name, + c.email +FROM catalog.schema.orders o +JOIN remote_query( + 'my_postgres', + database => 'crm_db', + query => 'SELECT customer_id, name, email FROM customers' +) c ON o.customer_id = c.customer_id; + +-- Access delegation via view +CREATE VIEW catalog.schema.federated_customers AS +SELECT * FROM remote_query( + 'my_postgres', + database => 'crm_db', + query => 'SELECT customer_id, name, region FROM customers' +); + +-- Users only need SELECT on the view, not USE CONNECTION +GRANT SELECT ON VIEW catalog.schema.federated_customers TO `analysts`; +``` + +--- + +## read_files Table-Valued Function + +Read files from cloud storage or Unity Catalog volumes directly in SQL, with automatic format detection and schema inference. + +### Syntax + +```sql +SELECT * FROM read_files( + path + [, option_key => option_value ] [...] +) +``` + +### Core Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `path` | STRING | Yes | URI of data location. Supports `s3://`, `abfss://`, `gs://`, `/Volumes/...` paths. Accepts glob patterns | + +### Common Options + +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `format` | STRING | Auto-detected | File format: `'csv'`, `'json'`, `'parquet'`, `'avro'`, `'orc'`, `'text'`, `'binaryFile'`, `'xml'` | +| `schema` | STRING | Inferred | Explicit schema definition in DDL format | +| `schemaHints` | STRING | None | Override subset of inferred schema columns | +| `rescuedDataColumn` | STRING | `'_rescued_data'` | Column name for data that could not be parsed. Set to empty string to disable | +| `pathGlobFilter` / `fileNamePattern` | STRING | None | Glob pattern to filter files (e.g., `'*.csv'`) | +| `recursiveFileLookup` | BOOLEAN | `false` | Search nested directories | +| `modifiedAfter` | TIMESTAMP STRING | None | Only read files modified after this timestamp | +| `modifiedBefore` | TIMESTAMP STRING | None | Only read files modified before this timestamp | +| `partitionColumns` | STRING | Auto-detected | Comma-separated Hive-style partition columns. Empty string ignores all partitions | +| `useStrictGlobber` | BOOLEAN | `true` | Strict glob pattern matching | +| `inferColumnTypes` | BOOLEAN | `true` | Infer exact column types (vs treating all as STRING) | +| `schemaEvolutionMode` | STRING | -- | Schema evolution behavior: `'none'` to drop rescued data column | + +### CSV-Specific Options + +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `sep` / `delimiter` | STRING | `','` | Field delimiter | +| `header` | BOOLEAN | `false` | First row contains column names | +| `encoding` | STRING | `'UTF-8'` | Character encoding | +| `quote` | STRING | `'"'` | Quote character | +| `escape` | STRING | `'\'` | Escape character | +| `nullValue` | STRING | `''` | String representation of null | +| `dateFormat` | STRING | `'yyyy-MM-dd'` | Date parsing format | +| `timestampFormat` | STRING | `'yyyy-MM-dd\'T\'HH:mm:ss...'` | Timestamp parsing format | +| `mode` | STRING | `'PERMISSIVE'` | Parse mode: `'PERMISSIVE'`, `'DROPMALFORMED'`, `'FAILFAST'` | +| `multiLine` | BOOLEAN | `false` | Allow records spanning multiple lines | +| `ignoreLeadingWhiteSpace` | BOOLEAN | `false` | Trim leading whitespace | +| `ignoreTrailingWhiteSpace` | BOOLEAN | `false` | Trim trailing whitespace | +| `comment` | STRING | None | Line comment character | +| `maxCharsPerColumn` | INTEGER | None | Max characters per column | +| `maxColumns` | INTEGER | None | Max number of columns | +| `mergeSchema` | BOOLEAN | `false` | Merge schemas across files | +| `enforceSchema` | BOOLEAN | `true` | Enforce specified schema | +| `locale` | STRING | `'US'` | Locale for number/date parsing | +| `charToEscapeQuoteEscaping` | STRING | None | Character to escape the quote escape character | +| `readerCaseSensitive` | BOOLEAN | `true` | Case-sensitive column name matching | + +### JSON-Specific Options + +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `multiLine` | BOOLEAN | `false` | Parse multi-line JSON records | +| `allowComments` | BOOLEAN | `false` | Allow Java/C++ style comments | +| `allowSingleQuotes` | BOOLEAN | `true` | Allow single quotes for strings | +| `allowUnquotedFieldNames` | BOOLEAN | `false` | Allow unquoted field names | +| `allowBackslashEscapingAnyCharacter` | BOOLEAN | `false` | Allow backslash to escape any character | +| `allowNonNumericNumbers` | BOOLEAN | `true` | Allow NaN, Infinity, -Infinity | +| `encoding` | STRING | `'UTF-8'` | Character encoding | +| `dateFormat` | STRING | `'yyyy-MM-dd'` | Date parsing format | +| `timestampFormat` | STRING | -- | Timestamp parsing format | +| `inferTimestamp` | BOOLEAN | `false` | Infer timestamp types | +| `prefersDecimal` | BOOLEAN | `false` | Prefer DECIMAL over DOUBLE | +| `primitivesAsString` | BOOLEAN | `false` | Infer all primitives as STRING | +| `singleVariantColumn` | STRING | None | Read entire JSON as single VARIANT column | +| `locale` | STRING | `'US'` | Locale for parsing | +| `mode` | STRING | `'PERMISSIVE'` | Parse mode | +| `readerCaseSensitive` | BOOLEAN | `true` | Case-sensitive column matching | +| `timeZone` | STRING | Session timezone | Timezone for timestamp parsing | + +### XML-Specific Options + +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `rowTag` | STRING | **Required** | XML tag that delimits rows | +| `attributePrefix` | STRING | `'_'` | Prefix for XML attributes | +| `valueTag` | STRING | `'_VALUE'` | Tag for element text content | +| `encoding` | STRING | `'UTF-8'` | Character encoding | +| `ignoreSurroundingSpaces` | BOOLEAN | `true` | Ignore whitespace around values | +| `ignoreNamespace` | BOOLEAN | `false` | Ignore XML namespaces | +| `mode` | STRING | `'PERMISSIVE'` | Parse mode | +| `dateFormat` | STRING | `'yyyy-MM-dd'` | Date parsing format | +| `timestampFormat` | STRING | -- | Timestamp parsing format | +| `locale` | STRING | `'US'` | Locale for parsing | +| `readerCaseSensitive` | BOOLEAN | `true` | Case-sensitive matching | +| `samplingRatio` | DOUBLE | `1.0` | Fraction of rows to sample for schema inference | + +### Parquet / Avro / ORC Options + +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `mergeSchema` | BOOLEAN | `false` | Merge schemas across files | +| `readerCaseSensitive` | BOOLEAN | `true` | Case-sensitive column matching | +| `rescuedDataColumn` | STRING | -- | Column for rescued data | +| `datetimeRebaseMode` | STRING | -- | Rebase mode for datetime values | +| `int96RebaseMode` | STRING | -- | Rebase mode for INT96 timestamps (Parquet only) | + +### Streaming Options + +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `includeExistingFiles` | BOOLEAN | `true` | Process existing files on first run | +| `maxFilesPerTrigger` | INTEGER | None | Max files per micro-batch | +| `maxBytesPerTrigger` | STRING | None | Max bytes per micro-batch | +| `allowOverwrites` | BOOLEAN | `false` | Allow processing of overwritten files | +| `schemaEvolutionMode` | STRING | -- | Schema evolution behavior | +| `schemaLocation` | STRING | -- | Location to store inferred schema | + +### Requirements + +- Databricks Runtime 13.3 LTS and above +- Databricks SQL + +### Examples + +```sql +-- Auto-detect format and schema from cloud storage +SELECT * FROM read_files('s3://my-bucket/data/'); + +-- Read CSV with explicit schema +SELECT * FROM read_files( + '/Volumes/catalog/schema/volume/sales.csv', + format => 'csv', + header => true, + schema => 'order_id INT, customer_id INT, amount DOUBLE, order_date DATE' +); + +-- Read CSV with schema hints (override specific columns only) +SELECT * FROM read_files( + '/Volumes/catalog/schema/volume/events/', + format => 'csv', + header => true, + schemaHints => 'event_timestamp TIMESTAMP, amount DECIMAL(10,2)' +); + +-- Read JSON with multi-line support +SELECT * FROM read_files( + '/Volumes/catalog/schema/volume/api_responses/', + format => 'json', + multiLine => true +); + +-- Read Parquet with merged schema across files +SELECT * FROM read_files( + 's3://my-bucket/parquet-data/', + format => 'parquet', + mergeSchema => true +); + +-- Read XML with row tag +SELECT * FROM read_files( + '/Volumes/catalog/schema/volume/feed.xml', + format => 'xml', + rowTag => 'record' +); + +-- Read binary files (images, PDFs) for ai_parse_document +SELECT path, content FROM read_files( + '/Volumes/catalog/schema/volume/documents/', + format => 'binaryFile' +); + +-- Filter files by glob pattern and modification date +SELECT * FROM read_files( + 's3://my-bucket/logs/', + format => 'json', + pathGlobFilter => '*.json', + modifiedAfter => '2025-01-01T00:00:00Z', + modifiedBefore => '2025-02-01T00:00:00Z' +); + +-- Recursive directory scan with partition discovery +SELECT * FROM read_files( + '/Volumes/catalog/schema/volume/partitioned_data/', + recursiveFileLookup => true, + partitionColumns => 'year,month' +); + +-- Include file metadata +SELECT *, _metadata.file_path, _metadata.file_name, _metadata.file_size +FROM read_files('/Volumes/catalog/schema/volume/data/'); + +-- Create table from files +CREATE TABLE catalog.schema.imported_data AS +SELECT * FROM read_files( + '/Volumes/catalog/schema/volume/export.csv', + format => 'csv', + header => true +); + +-- Streaming table from cloud storage +CREATE STREAMING TABLE catalog.schema.streaming_events AS +SELECT * FROM STREAM read_files( + 's3://my-bucket/events/', + format => 'json', + includeExistingFiles => false, + maxFilesPerTrigger => 100 +); + +-- Read single VARIANT column for semi-structured JSON +SELECT * FROM read_files( + '/Volumes/catalog/schema/volume/complex.json', + format => 'json', + singleVariantColumn => 'raw_data' +); +``` + +--- + +## Combining Functions -- Production Patterns + +### AI-Enhanced ETL Pipeline + +```sql +-- Process customer feedback with multiple AI functions +CREATE OR REPLACE TABLE catalog.schema.enriched_feedback AS +SELECT + feedback_id, + feedback_text, + ai_analyze_sentiment(feedback_text) AS sentiment, + ai_classify(feedback_text, ARRAY('product', 'service', 'billing', 'other')) AS category, + ai_extract(feedback_text, ARRAY('product', 'issue')) AS entities, + ai_summarize(feedback_text, 20) AS summary, + ai_mask(feedback_text, ARRAY('person', 'email', 'phone')) AS anonymized_text +FROM catalog.schema.raw_feedback; +``` + +### Document Processing Pipeline + +```sql +-- Ingest, parse, and query documents +WITH raw_docs AS ( + SELECT path, content + FROM read_files('/Volumes/catalog/schema/volume/contracts/', format => 'binaryFile') +), +parsed AS ( + SELECT path, ai_parse_document(content, map('version', '2.0')) AS doc + FROM raw_docs +) +SELECT + path, + ai_query( + 'databricks-meta-llama-3-3-70b-instruct', + CONCAT('Extract the contract parties, effective date, and termination clause from: ', + doc:document:elements[0]:content::STRING), + responseFormat => 'STRUCT' + ) AS contract_info +FROM parsed; +``` + +### External API Integration with http_request + +```sql +-- Enrich data by calling an external API and joining results +SELECT + o.order_id, + o.tracking_number, + from_json( + tracking.text, + 'STRUCT' + ) AS tracking_info +FROM catalog.schema.orders o +CROSS JOIN LATERAL ( + SELECT http_request( + CONN => 'shipping_api_conn', + METHOD => 'GET', + PATH => CONCAT('/track/', o.tracking_number) + ) AS response +) tracking +WHERE tracking.response.status_code = 200; +``` + +### Federated Analytics + +```sql +-- Combine remote database data with local lakehouse data and AI +SELECT + remote_orders.customer_id, + remote_orders.total_spend, + local_profiles.segment, + ai_classify( + CONCAT('Customer spent $', CAST(remote_orders.total_spend AS STRING), + ' in segment ', local_profiles.segment), + ARRAY('high_value', 'medium_value', 'low_value', 'at_risk') + ) AS value_tier +FROM remote_query( + 'my_postgres', + database => 'sales_db', + query => 'SELECT customer_id, SUM(amount) as total_spend FROM orders GROUP BY customer_id' +) remote_orders +JOIN catalog.schema.customer_profiles local_profiles + ON remote_orders.customer_id = local_profiles.customer_id; +``` diff --git a/.claude/skills/databricks-dbsql/best-practices.md b/.claude/skills/databricks-dbsql/best-practices.md new file mode 100644 index 00000000..a33cdc2a --- /dev/null +++ b/.claude/skills/databricks-dbsql/best-practices.md @@ -0,0 +1,475 @@ +# Data Modeling and DBSQL Best Practices + +Comprehensive reference for data modeling patterns, DBSQL performance optimization, and operational best practices on the Databricks Lakehouse Platform. + +--- + +## Data Modeling Best Practices + +### Star Schema vs Denormalization in the Lakehouse + +The Databricks Lakehouse fully supports dimensional modeling. Star schemas translate well to Delta tables and often deliver superior performance compared to fully denormalized approaches. + +**Star Schema (Dimensional Modeling):** +- Central fact table linked to multiple denormalized dimension tables +- Optimizes for complex analytics and multi-dimensional aggregations +- Provides intuitive business process mapping and scales well with SCDs +- Supports up to ~10 filtering dimensions (5 tables x 2 clustering keys each) +- Clear separation of concerns enables fine-grained governance + +**One Big Table (OBT):** +- Single wide table with all attributes pre-joined +- Eliminates joins, simpler governance (one table to manage) +- Liquid Clustering limited to 1-4 keys, so effective filtering is limited to 1-3 dimensions +- Full table scans become bottlenecks as data grows +- Lacks structured business process mapping +- Complicates fine-grained access controls and data quality checks + +**Key finding:** In benchmarks, dimensional models outperformed OBT (2.6s vs 3.5s) despite requiring joins, because fewer files needed to be scanned. However, with Liquid Clustering applied, OBT achieved >3x improvement (down to 1.13s). Both approaches achieve sub-500ms with automatic caching. + +**Recommended approach:** Use a hybrid medallion architecture: +- Silver layer: OBT or Data Vault for rapid integration and cleansing +- Gold layer: Star schema dimensional models as the curated, business-ready presentation layer for BI and reporting + +### When to Normalize vs Denormalize + +| Use Case | Approach | +|---|---| +| Gold layer for BI reporting | Star schema (denormalized dimensions, normalized facts) | +| Silver layer data integration | Normalized or Data Vault | +| Single-use IoT/logging analytics | OBT (filter by 1-3 dimensions) | +| Multi-dimensional business analysis | Star schema | +| Rapidly evolving schemas | OBT in Silver, star schema in Gold | +| High-cardinality filtering (5+ dimensions) | Star schema with Liquid Clustering per table | + +**Rule of thumb:** Dimension tables should be highly denormalized (flatten many-to-one relationships within a single dimension table). Fact tables should remain normalized at the grain of the business event. + +### Kimball-Style Modeling in Databricks + +Kimball dimensional modeling is the recommended approach for the Gold layer in the Lakehouse: + +1. **Identify the business process** (sales, orders, shipments) +2. **Declare the grain** (one row per transaction, per day, etc.) +3. **Choose dimensions** (who, what, where, when, why, how) +4. **Identify facts** (measurable numeric values at the declared grain) + +**Databricks-specific implementation details:** +- Use Unity Catalog for organizing dimensional models (catalog.schema.table) +- Define PRIMARY KEY constraints on dimension surrogate keys +- Define FOREIGN KEY constraints on fact table dimension keys for query optimization +- Add COMMENT on all tables and columns for discoverability +- Apply TAGS for governance (e.g., PII tagging) to enable downstream AI/BI capabilities +- Use `ANALYZE TABLE ... COMPUTE STATISTICS FOR COLUMNS` on dimension keys to support Adaptive Query Execution + +**Key principle:** "The better you model your data upfront, the more easily you can leverage AI on top of it out of the box." Proper schema design enables downstream AI/BI capabilities. + +### Fact Table Patterns + +**Design rules:** +- Store quantitative, numeric measures at the most granular transactional level +- Use DECIMAL instead of floating-point numbers for financial data +- Include foreign keys referencing dimension tables +- Include degenerate dimensions (source-system identifiers like order numbers) +- Transactional fact tables are typically not updated or versioned +- Cluster fact tables by foreign keys to frequently joined dimensions + +**Types of fact tables:** +- **Transaction facts:** One row per event (most common) +- **Periodic snapshot facts:** One row per entity per time period +- **Accumulating snapshot facts:** One row per entity lifecycle, updated as milestones are reached + +**Fact table Liquid Clustering strategy:** +```sql +CREATE TABLE gold.sales.fact_orders ( + order_key BIGINT GENERATED ALWAYS AS IDENTITY, + customer_key BIGINT NOT NULL, + product_key BIGINT NOT NULL, + date_key INT NOT NULL, + order_amount DECIMAL(18,2), + quantity INT, + CONSTRAINT fk_customer FOREIGN KEY (customer_key) REFERENCES gold.sales.dim_customer(customer_key), + CONSTRAINT fk_product FOREIGN KEY (product_key) REFERENCES gold.sales.dim_product(product_key) +) +CLUSTER BY (date_key, customer_key); +``` + +### Dimension Table Patterns + +**Design rules:** +- Use `GENERATED ALWAYS AS IDENTITY` or hash values for surrogate keys +- Prefer integer surrogate keys over strings for join performance +- Highly denormalize: flatten many-to-one relationships within a single dimension table +- Support complex types: MAP for extensibility, STRUCT for nested attributes, ARRAY for multi-valued attributes +- Avoid using ARRAY/MAP columns as filter predicates (they lack column-level statistics for data skipping) +- Cluster dimension tables by primary key plus common filter columns + +**Dimension table example:** +```sql +CREATE TABLE gold.sales.dim_customer ( + customer_key BIGINT GENERATED ALWAYS AS IDENTITY, + customer_id STRING NOT NULL COMMENT 'Natural key from source system', + full_name STRING, + email STRING, + city STRING, + state STRING, + country STRING, + segment STRING, + effective_start_date TIMESTAMP, + effective_end_date TIMESTAMP, + is_current BOOLEAN, + CONSTRAINT pk_customer PRIMARY KEY (customer_key) +) +CLUSTER BY (customer_key, segment) +COMMENT 'Customer dimension with SCD Type 2 history tracking'; +``` + +### Slowly Changing Dimensions (SCD) Patterns + +**SCD Type 1 (Overwrite):** +- In-place updates without tracking history +- Use MERGE INTO with matched UPDATE +- Suitable for corrections or attributes where history is not needed + +**SCD Type 2 (History Tracking):** +- Version records with surrogate keys and metadata columns +- Include `effective_start_date`, `effective_end_date`, and `is_current` columns +- Use MERGE INTO for implementing SCD Type 2 logic in DBSQL + +**SCD Type 2 with MERGE:** +```sql +MERGE INTO gold.sales.dim_customer AS target +USING ( + SELECT * FROM silver.crm.customers_changes +) AS source +ON target.customer_id = source.customer_id AND target.is_current = TRUE +WHEN MATCHED AND ( + target.full_name != source.full_name OR + target.city != source.city +) THEN UPDATE SET + effective_end_date = current_timestamp(), + is_current = FALSE +WHEN NOT MATCHED THEN INSERT ( + customer_id, full_name, email, city, state, country, segment, + effective_start_date, effective_end_date, is_current +) VALUES ( + source.customer_id, source.full_name, source.email, + source.city, source.state, source.country, source.segment, + current_timestamp(), NULL, TRUE +); +-- Then insert new versions for changed records in a second pass +``` + +**Delta Lake Time Travel** enables historical data access within configured log retention periods as a complementary feature to SCD. + +### Partitioning Strategies + +**Databricks recommends Liquid Clustering over traditional partitioning for all new tables.** + +Traditional partitioning rules of thumb (when needed): +- Keep partition count under 10,000 (ideally under 5,000 distinct values) +- Each partition should contain at least 1 GB of data +- Partition by low-cardinality columns that are frequently used in WHERE clauses (e.g., date, region) +- Works best for highly selective single-partition queries (e.g., filter on one day) + +**When traditional partitioning may still be appropriate:** +- Very large tables (hundreds of terabytes) with a clear, stable partition key +- Queries consistently filter on the same low-cardinality column +- Data lifecycle management requires partition-level operations + +### Liquid Clustering vs Traditional Partitioning + +**Liquid Clustering is the default recommendation for all new Delta tables**, including streaming tables and materialized views. It replaces both partitioning and Z-ORDER. + +| Aspect | Liquid Clustering | Partitioning + Z-ORDER | +|---|---|---| +| Column flexibility | Change clustering keys anytime | Partition column fixed at creation | +| Maintenance | Incremental, automatic with predictive optimization | Manual OPTIMIZE + Z-ORDER required | +| Filter dimensions | Best with 1-4 clustering keys | One partition key + Z-ORDER columns | +| Write overhead | Minimal (only unclustered ZCubes reorganized) | Z-ORDER reorganizes entire table/partition | +| Best for | Most workloads, evolving access patterns | Very large tables with stable, low-cardinality filter | +| Performance | 30-60% query speed improvement for variable queries | Better for single-partition lookup queries | + +**Liquid Clustering key selection best practices:** +- Choose columns most frequently used in query filters and joins +- Limit to 1-4 keys (fewer is better for smaller tables under 10 TB) +- For fact tables: cluster by the most commonly filtered foreign keys +- For dimension tables: cluster by primary key + common filter columns +- Too many keys dilute data skipping benefits; for tables under 10 TB, 2 keys often outperform 4 + +**Important:** Liquid Clustering is not compatible with partitioning or Z-ORDER on the same table. + +### Z-Ordering Considerations + +Z-ORDER is the legacy approach, now superseded by Liquid Clustering: + +- Z-ORDER reorganizes the entire table/partition during optimization (heavier writes) +- Does not track ZCube IDs, so every OPTIMIZE re-sorts all data +- Better suited for read-heavy workloads where write overhead is acceptable +- For new tables, always prefer Liquid Clustering + +**Migration path:** When migrating existing partitioned + Z-ORDERed tables to Liquid Clustering: +1. Drop the partition specification +2. Enable Liquid Clustering with chosen keys +3. Run OPTIMIZE to incrementally cluster data +4. Allow predictive optimization to maintain layout going forward + +--- + +## DBSQL Performance + +### Query Optimization Tips + +**Engine-level optimizations (automatic in DBSQL Serverless):** +- **Predictive Query Execution (PQE):** Monitors tasks in real time, dynamically adjusts query execution to avoid skew, spills, and unnecessary work. Unlike Adaptive Query Execution (AQE) which re-plans only after a stage completes, PQE detects issues like data skew or memory spills as they occur and replans immediately. +- **Photon Vectorized Shuffle:** Keeps data in compact columnar format, sorts within CPU cache, and uses vectorized instructions for 1.5x higher shuffle throughput. Best for CPU-bound workloads (large joins, wide aggregations). +- **Low Shuffle Merge:** Optimized MERGE implementation that reduces shuffle overhead for most common workloads. + +**Manual optimization actions:** +- Run `ANALYZE TABLE ... COMPUTE STATISTICS FOR COLUMNS` on dimension keys and frequently filtered columns to support AQE and data skipping +- Set `'delta.dataSkippingStatsColumns'` table property to specify which columns collect statistics +- Define PRIMARY KEY and FOREIGN KEY constraints to help the query optimizer +- Use deterministic queries (avoid `NOW()`, `CURRENT_TIMESTAMP()` in filters) to benefit from query result caching +- Prefer `CREATE OR REPLACE TABLE` over delete-then-create patterns +- Use `DECIMAL` over `FLOAT`/`DOUBLE` for financial calculations + +**SQL writing tips for DBSQL:** +- Filter early, aggregate late: push WHERE clauses as close to the source as possible +- Prefer explicit column lists over SELECT * +- Use CTEs for readability but be aware the optimizer may inline them +- Avoid Python/Scala UDFs when native SQL functions exist (UDFs require serialization between Python and Spark, significantly slowing queries) +- Use window functions instead of self-joins where possible +- Leverage QUALIFY clause for row-level filtering after window functions + +### Warehouse Sizing Guidance + +**Databricks recommends serverless SQL warehouses for most workloads.** Serverless uses Intelligent Workload Management (IWM) to automatically manage query workloads. + +**Sizing strategy:** +- Start with a single larger warehouse and let serverless features manage concurrency +- Size down if needed rather than starting small and scaling up +- If queries spill to disk, increase the cluster size + +**Scaling configuration:** +- Low concurrency (1-2 queries): keep max_clusters low +- Unpredictable spikes: set max_num_clusters high with target_utilization ~70% +- For dashboards with variable/infrequent load: enable aggressive auto-scaling and auto-stopping + +**Serverless advantages:** +- Start and scale up in seconds +- Scale down earlier than non-serverless warehouses +- Pay only when queries are running +- 30-60 second cold start latency (savings from no idle time far outweigh this) +- All 2025 optimizations (PQE, Photon Vectorized Shuffle) are automatically available + +### Caching Strategies + +**Query Result Cache:** +- DBSQL caches results per-cluster for all queries +- Cache is invalidated when underlying Delta data changes +- To maximize cache hits, use deterministic queries (no `NOW()`, `RAND()`, etc.) +- Both OBT and star schema achieve sub-500ms with automatic caching after first run + +**Delta Cache (Disk Cache):** +- Automatically caches remote data on local SSD in columnar format +- Accelerates data reads without manual configuration on serverless warehouses +- Particularly effective for repeated scans of the same tables + +**Best practice:** Design dashboards and reports to use parameterized queries that hit the same underlying patterns, maximizing cache reuse. + +### Photon Engine Benefits + +Photon is a vectorized query engine written in C++ that runs natively on Databricks: + +- Enabled by default on all DBSQL serverless warehouses +- Processes data in columnar batches using CPU vector instructions (SIMD) +- Excels at: large joins, wide aggregations, string processing, data shuffles +- 2025 vectorized shuffle delivers 1.5x higher shuffle throughput +- Combined with PQE, delivers up to 25% faster queries on top of existing 5x gains + +### Recent Performance Improvements (2025) + +| Improvement | Impact | +|---|---| +| Overall production workloads | Up to 40% faster (automatic, no tuning) | +| Photon Vectorized Shuffle | 1.5x higher shuffle throughput | +| PQE + Photon Vectorized Shuffle combined | Up to 25% faster on top of existing 5x gains | +| Spatial SQL queries | Up to 17x faster (R-tree indexing, optimized spatial joins) | +| AI functions | Up to 85x faster for large batch workloads | +| End-to-end Unity Catalog latency | Up to 10x improvement | +| 3-year cumulative improvement | 5x faster across customer workloads | + +All improvements are live in DBSQL Serverless with nothing to enable. + +### Cost Optimization Patterns + +1. **Use serverless SQL warehouses:** Pay only when queries run, auto-scale and auto-stop +2. **Enable predictive optimization:** Automatically runs OPTIMIZE and VACUUM on Unity Catalog managed tables +3. **Right-size warehouses:** Start larger, scale down based on actual usage patterns +4. **Avoid idle warehouses:** Use aggressive auto-stop for dashboards with infrequent load +5. **Leverage caching:** Design deterministic queries to maximize result cache hits +6. **Use Liquid Clustering:** Reduces scan volume, fewer DBUs consumed per query +7. **Collect statistics:** `ANALYZE TABLE` enables better query plans, reducing wasted compute +8. **Monitor with Query Profile:** Identify expensive operations, spills, and skew +9. **Use materialized views** for frequently computed aggregations +10. **Avoid UDFs:** Native functions are dramatically faster, no serialization overhead + +--- + +## Delta Lake Optimization for DBSQL + +### OPTIMIZE, VACUUM, and ANALYZE + +**Recommended execution order:** OPTIMIZE -> VACUUM -> ANALYZE + +**OPTIMIZE:** +- Compacts small files into larger ones (target 1 GB by default) +- Run frequently on tables with many small files (especially after streaming writes) +- Configurable target size via `delta.targetFileSize` table property +- With Liquid Clustering: only reorganizes unclustered ZCubes (incremental) + +**VACUUM:** +- Removes old files no longer in the transaction log +- Reduces storage costs +- Use compute-optimized instances (AWS C5, Azure F-series, GCP C2) +- Default retention: 7 days (configurable via `delta.deletedFileRetentionDuration`) +- Never set retention below the longest-running query duration + +**ANALYZE TABLE:** +- Computes column-level statistics for query optimization +- Run immediately after table overwrites or major data changes +- Focus on columns used in WHERE clauses, JOINs, and GROUP BY + +**Predictive optimization (recommended):** + +> **Note:** On serverless SQL warehouses, `delta.enableOptimizeWrite` and `delta.autoOptimize.autoCompact` are managed automatically and cannot be set manually (they will raise `DELTA_UNKNOWN_CONFIGURATION`). The properties below apply only to classic compute. For serverless, simply enable predictive optimization at the catalog/schema level. + +```sql +-- Classic compute only: +ALTER TABLE catalog.schema.table_name +SET TBLPROPERTIES ('delta.enableOptimizeWrite' = 'true'); +-- For Unity Catalog managed tables, predictive optimization +-- handles OPTIMIZE and VACUUM automatically +``` + +### File Size and Compaction + +- **Auto-compaction:** Combines small files within partitions automatically after writes +- **Optimized writes:** Rebalances data via shuffle before writing to reduce small files +- **Target file size:** Default 1 GB; adjust with `delta.targetFileSize` for specific workloads +- For tables with many small files (streaming ingestion), schedule regular OPTIMIZE jobs + +### Table Properties for Performance + +> **Note:** `delta.enableOptimizeWrite` and `delta.autoOptimize.autoCompact` are only valid on classic compute. On serverless SQL warehouses, these are managed automatically and setting them raises `DELTA_UNKNOWN_CONFIGURATION`. The remaining properties work on both classic and serverless. + +```sql +-- Classic compute only (serverless manages these automatically): +-- 'delta.enableOptimizeWrite' = 'true', +-- 'delta.autoOptimize.autoCompact' = 'true', + +-- Works on both classic and serverless: +ALTER TABLE catalog.schema.my_table SET TBLPROPERTIES ( + 'delta.columnMapping.mode' = 'name', + 'delta.enableChangeDataFeed' = 'true', + 'delta.deletedFileRetentionDuration' = '30 days', + 'delta.dataSkippingStatsColumns' = 'col1,col2,col3' +); +``` + +--- + +## Unity Catalog Integration Patterns + +### Organization Best Practices + +- Use a three-level namespace: `catalog.schema.table` +- Organize by environment (dev/staging/prod) at the catalog level +- Organize by business domain at the schema level +- Use managed tables (not external) to benefit from predictive optimization and enhanced governance + +### Governance Features for Data Modeling + +- **Primary/Foreign Key constraints:** Inform the query optimizer about table relationships +- **Row filters and column masks:** Fine-grained access control at the table level +- **Tags:** Apply governance tags (e.g., PII, sensitivity level) to tables and columns +- **Comments:** Document all tables and columns for AI/BI discoverability +- **Lineage tracking:** Automatic lineage for understanding data flow through the medallion architecture + +### Entity Relationship Visualization + +Unity Catalog renders entity relationship diagrams when primary and foreign key constraints are defined, providing visual documentation of the dimensional model. + +--- + +## Monitoring and Observability + +- **Query Profile:** Analyze execution plans, identify bottlenecks, spills, and data skew +- **Query History:** Track query performance trends over time +- **Warehouse monitoring:** Track utilization, queue times, and scaling events +- **System tables:** Query `system.billing`, `system.access`, and `system.query` for operational insights +- **Alerts:** Set up SQL alerts for data quality checks and SLA monitoring + +--- + +## Common Anti-Patterns to Avoid + +### Data Modeling Anti-Patterns + +1. **Skipping dimensional modeling in Gold layer:** OBTs are fine for Silver, but Gold should use star schemas for multi-dimensional analysis +2. **Over-partitioning:** More than 5,000-10,000 partitions degrades performance; use Liquid Clustering instead +3. **String surrogate keys:** Use integer IDENTITY columns for better join performance +4. **Missing constraints:** Not defining PK/FK constraints deprives the optimizer of relationship information +5. **Missing comments and tags:** Reduces discoverability for AI/BI tools and governance +6. **Using FLOAT for financial data:** Use DECIMAL to avoid precision errors +7. **Filtering on ARRAY/MAP columns:** These types lack column-level statistics for data skipping + +### Query and Performance Anti-Patterns + +1. **Delete-then-recreate tables:** Use `CREATE OR REPLACE TABLE` instead to preserve time travel and avoid reader interruptions +2. **Python/Scala UDFs when native functions exist:** Serialization overhead dramatically slows queries +3. **Not collecting statistics:** Missing `ANALYZE TABLE` leads to suboptimal query plans +4. **Non-deterministic functions in cached queries:** `NOW()`, `RAND()` etc. prevent query result caching +5. **Partitioning by wrong column:** Partitioning by a column not used in filters causes full scans +6. **Too many Liquid Clustering keys:** For tables under 10 TB, 2 keys often outperform 4 keys +7. **Manual OPTIMIZE/VACUUM without predictive optimization:** Enable predictive optimization for Unity Catalog managed tables + +### Operational Anti-Patterns + +1. **Idle warehouses:** Always enable auto-stop; use serverless for variable workloads +2. **Under-sized warehouses:** Queries spilling to disk waste more DBUs than a larger warehouse +3. **External tables when managed will do:** External tables miss predictive optimization and enhanced governance +4. **Skipping VACUUM:** Unbounded file growth increases storage costs and slows metadata operations +5. **Running VACUUM with too-short retention:** Can break long-running queries and time travel + +--- + +## Quick Reference: SQL Patterns for AI Agents + +When generating SQL for Databricks, prefer these patterns: + +```sql +-- Use CREATE OR REPLACE (not DROP + CREATE) +CREATE OR REPLACE TABLE catalog.schema.my_table AS +SELECT ...; + +-- Use MERGE for upserts (not DELETE + INSERT) +MERGE INTO target USING source +ON target.key = source.key +WHEN MATCHED THEN UPDATE SET ... +WHEN NOT MATCHED THEN INSERT ...; + +-- Use QUALIFY for window function filtering (not subquery) +SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY ts DESC) AS rn +FROM my_table +QUALIFY rn = 1; + +-- Use DECIMAL for money +SELECT CAST(amount AS DECIMAL(18,2)) AS revenue FROM orders; + +-- Collect statistics after loading +ANALYZE TABLE catalog.schema.my_table COMPUTE STATISTICS FOR ALL COLUMNS; + +-- Enable predictive optimization (classic compute only; serverless manages this automatically) +ALTER TABLE catalog.schema.my_table +SET TBLPROPERTIES ('delta.enableOptimizeWrite' = 'true'); +``` diff --git a/.claude/skills/databricks-dbsql/geospatial-collations.md b/.claude/skills/databricks-dbsql/geospatial-collations.md new file mode 100644 index 00000000..eaa2468f --- /dev/null +++ b/.claude/skills/databricks-dbsql/geospatial-collations.md @@ -0,0 +1,736 @@ +# Geospatial SQL and Collations in Databricks SQL + +--- + +## Part 1: Geospatial SQL + +Databricks SQL provides comprehensive geospatial support through two function families: **H3 functions** for hexagonal grid indexing and **ST functions** for standard spatial operations. Together they enable high-performance geospatial analytics at scale. + +### Geospatial Data Types + +| Type | Description | Coordinate System | SRID Support | +|------|-------------|-------------------|--------------| +| `GEOMETRY` | Spatial objects using Euclidean coordinates (X, Y, optional Z) -- treats Earth as flat | Any projected CRS | 11,000+ SRIDs | +| `GEOGRAPHY` | Geographic objects on Earth's surface using longitude/latitude | WGS 84 | SRID 4326 only | + +**When to use which:** +- Use `GEOMETRY` for projected coordinate systems, Euclidean distance calculations, and when working with local/regional data in meters or feet. +- Use `GEOGRAPHY` for global data using longitude/latitude coordinates and spherical distance calculations. + +### Supported Geometry Subtypes + +Both `GEOMETRY` and `GEOGRAPHY` support: **Point**, **LineString**, **Polygon**, **MultiPoint**, **MultiLineString**, **MultiPolygon**, and **GeometryCollection**. + +### Format Support + +| Format | Description | Import Function | Export Function | +|--------|-------------|-----------------|-----------------| +| WKT | Well-Known Text | `ST_GeomFromWKT`, `ST_GeogFromWKT` | `ST_AsWKT`, `ST_AsText` | +| WKB | Well-Known Binary | `ST_GeomFromWKB`, `ST_GeogFromWKB` | `ST_AsWKB`, `ST_AsBinary` | +| EWKT | Extended WKT (includes SRID) | `ST_GeomFromEWKT`, `ST_GeogFromEWKT` | `ST_AsEWKT` | +| EWKB | Extended WKB (includes SRID) | `ST_GeomFromEWKB` | `ST_AsEWKB` | +| GeoJSON | JSON-based format | `ST_GeomFromGeoJSON`, `ST_GeogFromGeoJSON` | `ST_AsGeoJSON` | +| Geohash | Hierarchical grid encoding | `ST_GeomFromGeoHash`, `ST_PointFromGeoHash` | `ST_GeoHash` | + +--- + +### H3 Geospatial Functions + +H3 is Uber's hexagonal hierarchical spatial index. It divides the Earth into hexagonal cells at 16 resolutions (0-15). Available since Databricks Runtime 11.2 (H3 Java library 3.7.0). No separate installation required. + +#### H3 Import Functions (Coordinate/Geometry to H3) + +| Function | Description | Returns | +|----------|-------------|---------| +| `h3_longlatash3(lon, lat, resolution)` | Convert longitude/latitude to H3 cell ID | `BIGINT` | +| `h3_longlatash3string(lon, lat, resolution)` | Convert longitude/latitude to H3 cell ID | `STRING` (hex) | +| `h3_pointash3(geogExpr, resolution)` | Convert GEOGRAPHY point to H3 cell ID | `BIGINT` | +| `h3_pointash3string(geogExpr, resolution)` | Convert GEOGRAPHY point to H3 cell ID | `STRING` (hex) | +| `h3_polyfillash3(geogExpr, resolution)` | Fill polygon with contained H3 cells | `ARRAY` | +| `h3_polyfillash3string(geogExpr, resolution)` | Fill polygon with contained H3 cells | `ARRAY` | +| `h3_coverash3(geogExpr, resolution)` | Cover geography with minimal set of H3 cells | `ARRAY` | +| `h3_coverash3string(geogExpr, resolution)` | Cover geography with minimal set of H3 cells | `ARRAY` | +| `h3_tessellateaswkb(geogExpr, resolution)` | Tessellate geography using H3 cells | `ARRAY` | +| `h3_try_polyfillash3(geogExpr, resolution)` | Safe polyfill (returns NULL on error) | `ARRAY` | +| `h3_try_polyfillash3string(geogExpr, resolution)` | Safe polyfill (returns NULL on error) | `ARRAY` | +| `h3_try_coverash3(geogExpr, resolution)` | Safe cover (returns NULL on error) | `ARRAY` | +| `h3_try_coverash3string(geogExpr, resolution)` | Safe cover (returns NULL on error) | `ARRAY` | +| `h3_try_tessellateaswkb(geogExpr, resolution)` | Safe tessellate (returns NULL on error) | `ARRAY` | + +#### H3 Export Functions (H3 to Geometry/Format) + +| Function | Description | Returns | +|----------|-------------|---------| +| `h3_boundaryaswkt(h3CellId)` | H3 cell boundary as WKT polygon | `STRING` | +| `h3_boundaryaswkb(h3CellId)` | H3 cell boundary as WKB polygon | `BINARY` | +| `h3_boundaryasgeojson(h3CellId)` | H3 cell boundary as GeoJSON | `STRING` | +| `h3_centeraswkt(h3CellId)` | H3 cell center as WKT point | `STRING` | +| `h3_centeraswkb(h3CellId)` | H3 cell center as WKB point | `BINARY` | +| `h3_centerasgeojson(h3CellId)` | H3 cell center as GeoJSON point | `STRING` | + +#### H3 Conversion Functions + +| Function | Description | +|----------|-------------| +| `h3_h3tostring(h3CellId)` | Convert BIGINT cell ID to hex STRING | +| `h3_stringtoh3(h3CellIdString)` | Convert hex STRING to BIGINT cell ID | + +#### H3 Hierarchy / Traversal Functions + +| Function | Description | +|----------|-------------| +| `h3_resolution(h3CellId)` | Get the resolution of a cell | +| `h3_toparent(h3CellId, resolution)` | Get parent cell at coarser resolution | +| `h3_tochildren(h3CellId, resolution)` | Get all child cells at finer resolution | +| `h3_maxchild(h3CellId, resolution)` | Get child with maximum value | +| `h3_minchild(h3CellId, resolution)` | Get child with minimum value | +| `h3_ischildof(h3CellId1, h3CellId2)` | Test if cell1 is equal to or child of cell2 | + +#### H3 Distance / Neighbor Functions + +| Function | Description | +|----------|-------------| +| `h3_distance(h3CellId1, h3CellId2)` | Grid distance between two cells | +| `h3_try_distance(h3CellId1, h3CellId2)` | Grid distance or NULL if undefined | +| `h3_kring(h3CellId, k)` | All cells within grid distance k (filled disk) | +| `h3_kringdistances(h3CellId, k)` | Cells within distance k with their distances | +| `h3_hexring(h3CellId, k)` | Hollow ring of cells at exactly distance k | + +#### H3 Compaction Functions + +| Function | Description | +|----------|-------------| +| `h3_compact(h3CellIds)` | Compact array of cells to minimal representation | +| `h3_uncompact(h3CellIds, resolution)` | Expand compacted cells to target resolution | + +#### H3 Validation Functions + +| Function | Description | +|----------|-------------| +| `h3_isvalid(expr)` | Check if BIGINT or STRING is valid H3 cell | +| `h3_validate(h3CellId)` | Return cell ID if valid, error otherwise | +| `h3_try_validate(h3CellId)` | Return cell ID if valid, NULL otherwise | +| `h3_ispentagon(h3CellId)` | Check if cell is a pentagon (12 per resolution) | + +#### H3 Examples + +```sql +-- Convert coordinates to H3 cell at resolution 9 +SELECT h3_longlatash3(-73.985428, 40.748817, 9) AS h3_cell; + +-- Index taxi trips by pickup location +CREATE TABLE trips_h3 AS +SELECT + h3_longlatash3(pickup_longitude, pickup_latitude, 12) AS pickup_cell, + h3_longlatash3(dropoff_longitude, dropoff_latitude, 12) AS dropoff_cell, + * +FROM taxi_trips; + +-- Fill zip code polygons with H3 cells for spatial indexing +CREATE TABLE zipcode_h3 AS +SELECT + explode(h3_polyfillash3(geom_wkt, 12)) AS cell, + zipcode, city, state +FROM zipcodes; + +-- Find all trips picked up in a specific zip code using H3 join +SELECT t.* +FROM trips_h3 t +INNER JOIN zipcode_h3 z ON t.pickup_cell = z.cell +WHERE z.zipcode = '10001'; + +-- Proximity search: find all H3 cells within 2 rings of a location +SELECT explode(h3_kring(h3_longlatash3(-73.985, 40.748, 9), 2)) AS nearby_cell; + +-- Aggregate trip counts and get centroids for visualization +SELECT + dropoff_cell, + h3_centerasgeojson(dropoff_cell):coordinates[0] AS lon, + h3_centerasgeojson(dropoff_cell):coordinates[1] AS lat, + count(*) AS trip_count +FROM trips_h3 +GROUP BY dropoff_cell; + +-- Roll up to coarser resolution +SELECT + h3_toparent(pickup_cell, 7) AS parent_cell, + count(*) AS trip_count +FROM trips_h3 +GROUP BY h3_toparent(pickup_cell, 7); + +-- Compact a set of cells for efficient storage +SELECT h3_compact(collect_set(cell)) AS compacted +FROM zipcode_h3 +WHERE zipcode = '10001'; +``` + +--- + +### ST Geospatial Functions + +Native spatial SQL functions operating on `GEOMETRY` and `GEOGRAPHY` types. Requires Databricks Runtime 17.1+. Public Preview. Over 80 functions available. + +#### ST Import Functions (Create Geometry/Geography) + +| Function | Description | Output Type | +|----------|-------------|-------------| +| `ST_GeomFromText(wkt [, srid])` | Create GEOMETRY from WKT | `GEOMETRY` | +| `ST_GeomFromWKT(wkt [, srid])` | Create GEOMETRY from WKT (alias) | `GEOMETRY` | +| `ST_GeomFromWKB(wkb [, srid])` | Create GEOMETRY from WKB | `GEOMETRY` | +| `ST_GeomFromEWKT(ewkt)` | Create GEOMETRY from Extended WKT | `GEOMETRY` | +| `ST_GeomFromEWKB(ewkb)` | Create GEOMETRY from Extended WKB | `GEOMETRY` | +| `ST_GeomFromGeoJSON(geojson)` | Create GEOMETRY(4326) from GeoJSON | `GEOMETRY` | +| `ST_GeomFromGeoHash(geohash)` | Create polygon GEOMETRY from geohash | `GEOMETRY` | +| `ST_GeogFromText(wkt)` | Create GEOGRAPHY(4326) from WKT | `GEOGRAPHY` | +| `ST_GeogFromWKT(wkt)` | Create GEOGRAPHY(4326) from WKT | `GEOGRAPHY` | +| `ST_GeogFromWKB(wkb)` | Create GEOGRAPHY(4326) from WKB | `GEOGRAPHY` | +| `ST_GeogFromEWKT(ewkt)` | Create GEOGRAPHY from Extended WKT | `GEOGRAPHY` | +| `ST_GeogFromGeoJSON(geojson)` | Create GEOGRAPHY(4326) from GeoJSON | `GEOGRAPHY` | +| `ST_Point(x, y [, srid])` | Create point from coordinates | `GEOMETRY` | +| `ST_PointFromGeoHash(geohash)` | Create point from geohash center | `GEOMETRY` | +| `to_geometry(georepExpr)` | Auto-detect format and create GEOMETRY | `GEOMETRY` | +| `to_geography(georepExpr)` | Auto-detect format and create GEOGRAPHY | `GEOGRAPHY` | +| `try_to_geometry(georepExpr)` | Safe geometry creation (NULL on error) | `GEOMETRY` | +| `try_to_geography(georepExpr)` | Safe geography creation (NULL on error) | `GEOGRAPHY` | + +#### ST Export Functions + +| Function | Description | Output | +|----------|-------------|--------| +| `ST_AsText(geo)` | Export as WKT | `STRING` | +| `ST_AsWKT(geo)` | Export as WKT (alias) | `STRING` | +| `ST_AsBinary(geo)` | Export as WKB | `BINARY` | +| `ST_AsWKB(geo)` | Export as WKB (alias) | `BINARY` | +| `ST_AsEWKT(geo)` | Export as Extended WKT | `STRING` | +| `ST_AsEWKB(geo)` | Export as Extended WKB | `BINARY` | +| `ST_AsGeoJSON(geo)` | Export as GeoJSON | `STRING` | +| `ST_GeoHash(geo)` | Export as geohash string | `STRING` | + +#### ST Constructor Functions + +| Function | Description | +|----------|-------------| +| `ST_Point(x, y [, srid])` | Create a point geometry | +| `ST_MakeLine(pointArray)` | Create linestring from array of points | +| `ST_MakePolygon(outer [, innerArray])` | Create polygon from outer ring and optional holes | + +#### ST Accessor Functions + +| Function | Description | Returns | +|----------|-------------|---------| +| `ST_X(geo)` | X coordinate of a point | `DOUBLE` | +| `ST_Y(geo)` | Y coordinate of a point | `DOUBLE` | +| `ST_Z(geo)` | Z coordinate of a point | `DOUBLE` | +| `ST_M(geo)` | M coordinate of a point | `DOUBLE` | +| `ST_XMin(geo)` | Minimum X of bounding box | `DOUBLE` | +| `ST_XMax(geo)` | Maximum X of bounding box | `DOUBLE` | +| `ST_YMin(geo)` | Minimum Y of bounding box | `DOUBLE` | +| `ST_YMax(geo)` | Maximum Y of bounding box | `DOUBLE` | +| `ST_ZMin(geo)` | Minimum Z coordinate | `DOUBLE` | +| `ST_ZMax(geo)` | Maximum Z coordinate | `DOUBLE` | +| `ST_Dimension(geo)` | Topological dimension (0=point, 1=line, 2=polygon) | `INT` | +| `ST_NDims(geo)` | Number of coordinate dimensions | `INT` | +| `ST_NPoints(geo)` | Total number of points | `INT` | +| `ST_NumGeometries(geo)` | Number of geometries in collection | `INT` | +| `ST_NumInteriorRings(geo)` | Number of interior rings (polygon) | `INT` | +| `ST_GeometryType(geo)` | Geometry type as string | `STRING` | +| `ST_GeometryN(geo, n)` | N-th geometry (1-based) from collection | `GEOMETRY` | +| `ST_PointN(geo, n)` | N-th point from linestring | `GEOMETRY` | +| `ST_StartPoint(geo)` | First point of linestring | `GEOMETRY` | +| `ST_EndPoint(geo)` | Last point of linestring | `GEOMETRY` | +| `ST_ExteriorRing(geo)` | Outer ring of polygon | `GEOMETRY` | +| `ST_InteriorRingN(geo, n)` | N-th interior ring of polygon | `GEOMETRY` | +| `ST_Envelope(geo)` | Minimum bounding rectangle | `GEOMETRY` | +| `ST_Envelope_Agg(geo)` | Aggregate: bounding box of all geometries | `GEOMETRY` | +| `ST_Dump(geo)` | Explode multi-geometry into array of singles | `ARRAY` | +| `ST_IsEmpty(geo)` | True if geometry has no points | `BOOLEAN` | + +#### ST Measurement Functions + +| Function | Description | +|----------|-------------| +| `ST_Area(geo)` | Area of a polygon (in CRS units) | +| `ST_Length(geo)` | Length of a linestring (in CRS units) | +| `ST_Perimeter(geo)` | Perimeter of a polygon (in CRS units) | +| `ST_Distance(geo1, geo2)` | Cartesian distance between geometries | +| `ST_DistanceSphere(geo1, geo2)` | Spherical distance in meters (fast, approximate) | +| `ST_DistanceSpheroid(geo1, geo2)` | Geodesic distance in meters on WGS84 (accurate) | +| `ST_Azimuth(geo1, geo2)` | North-based azimuth angle in radians | +| `ST_ClosestPoint(geo1, geo2)` | Point on geo1 closest to geo2 | + +#### ST Topological Relationship Functions (Predicates) + +| Function | Description | +|----------|-------------| +| `ST_Contains(geo1, geo2)` | True if geo1 fully contains geo2 | +| `ST_Within(geo1, geo2)` | True if geo1 is fully within geo2 (inverse of Contains) | +| `ST_Intersects(geo1, geo2)` | True if geometries share any space | +| `ST_Disjoint(geo1, geo2)` | True if geometries share no space | +| `ST_Touches(geo1, geo2)` | True if boundaries touch but interiors do not | +| `ST_Covers(geo1, geo2)` | True if geo1 covers geo2 (no point of geo2 is exterior) | +| `ST_Equals(geo1, geo2)` | True if geometries are topologically equal | +| `ST_DWithin(geo1, geo2, distance)` | True if geometries are within given distance | + +#### ST Overlay Functions (Set Operations) + +| Function | Description | +|----------|-------------| +| `ST_Intersection(geo1, geo2)` | Geometry of shared space | +| `ST_Union(geo1, geo2)` | Geometry combining both inputs | +| `ST_Union_Agg(geo)` | Aggregate: union of all geometries in column | +| `ST_Difference(geo1, geo2)` | Geometry of geo1 minus geo2 | + +#### ST Processing Functions + +| Function | Description | +|----------|-------------| +| `ST_Buffer(geo, radius)` | Expand geometry by radius distance | +| `ST_Centroid(geo)` | Center point of geometry | +| `ST_ConvexHull(geo)` | Smallest convex polygon containing geometry | +| `ST_ConcaveHull(geo, ratio [, allowHoles])` | Concave hull with length ratio | +| `ST_Boundary(geo)` | Boundary of geometry (not available on all SQL Warehouse versions) | +| `ST_Simplify(geo, tolerance)` | Simplify using Douglas-Peucker algorithm | + +#### ST Editor Functions + +| Function | Description | +|----------|-------------| +| `ST_AddPoint(linestring, point [, index])` | Add point to linestring | +| `ST_RemovePoint(linestring, index)` | Remove point from linestring | +| `ST_SetPoint(linestring, index, point)` | Replace point in linestring | +| `ST_FlipCoordinates(geo)` | Swap X and Y coordinates | +| `ST_Multi(geo)` | Convert single geometry to multi-geometry | +| `ST_Reverse(geo)` | Reverse vertex order | + +#### ST Affine Transformation Functions + +| Function | Description | +|----------|-------------| +| `ST_Translate(geo, xOffset, yOffset [, zOffset])` | Move geometry by offset | +| `ST_Scale(geo, xFactor, yFactor [, zFactor])` | Scale geometry by factors | +| `ST_Rotate(geo, angle)` | Rotate geometry around origin (radians) | + +#### ST Spatial Reference System Functions + +| Function | Description | +|----------|-------------| +| `ST_SRID(geo)` | Get SRID of geometry | +| `ST_SetSRID(geo, srid)` | Set SRID value (no reprojection) | +| `ST_Transform(geo, targetSrid)` | Reproject to target coordinate system | + +#### ST Validation + +| Function | Description | +|----------|-------------| +| `ST_IsValid(geo)` | Check if geometry is OGC-valid | + +#### ST Practical Examples + +> **Note:** `GEOMETRY` and `GEOGRAPHY` column types in `CREATE TABLE` require serverless compute with DBR 17.1+. On SQL Warehouses that don't support these column types, use `STRING` columns with WKT representation and convert with `ST_GeomFromText()` / `ST_GeogFromText()` at query time. + +```sql +-- Create a table with geometry columns (requires serverless DBR 17.1+) +CREATE TABLE retail_stores ( + store_id INT, + name STRING, + location GEOMETRY +); + +INSERT INTO retail_stores VALUES + (1, 'Downtown Store', ST_Point(-73.9857, 40.7484, 4326)), + (2, 'Midtown Store', ST_Point(-73.9787, 40.7614, 4326)), + (3, 'Uptown Store', ST_Point(-73.9680, 40.7831, 4326)); + +-- Create delivery zones as polygons +CREATE TABLE delivery_zones ( + zone_id INT, + zone_name STRING, + boundary GEOMETRY +); + +INSERT INTO delivery_zones VALUES + (1, 'Zone A', ST_GeomFromText( + 'POLYGON((-74.00 40.74, -73.97 40.74, -73.97 40.76, -74.00 40.76, -74.00 40.74))', 4326 + )); + +-- Point-in-polygon: find stores within a delivery zone +SELECT s.name, z.zone_name +FROM retail_stores s +JOIN delivery_zones z + ON ST_Contains(z.boundary, s.location); + +-- Distance calculation: find customers within 5km of a store +-- Note: to_geography() expects STRING (WKT/GeoJSON) or BINARY (WKB) input, not GEOMETRY. +-- Use ST_AsText() to convert GEOMETRY to WKT first. +SELECT c.customer_id, c.name, + ST_DistanceSphere(c.location, s.location) AS distance_meters +FROM customers c +CROSS JOIN retail_stores s +WHERE s.store_id = 1 + AND ST_DWithin( + ST_GeogFromText(ST_AsText(c.location)), + ST_GeogFromText(ST_AsText(s.location)), + 5000 -- 5km in meters + ); + +-- Buffer zone: create 1km buffer around a store (use projected CRS for meters) +SELECT ST_Buffer( + ST_Transform(location, 5070), -- project to NAD83/Albers (meters) + 1000 -- 1000 meters +) AS buffer_zone +FROM retail_stores +WHERE store_id = 1; + +-- Area calculation +SELECT zone_name, + ST_Area(ST_Transform(boundary, 5070)) AS area_sq_meters +FROM delivery_zones; + +-- Union of overlapping zones +SELECT ST_Union_Agg(boundary) AS combined_coverage +FROM delivery_zones; + +-- Convert between formats +SELECT + ST_AsText(location) AS wkt, + ST_AsGeoJSON(location) AS geojson, + ST_GeoHash(location) AS geohash +FROM retail_stores; + +-- Spatial join with BROADCAST hint for performance +SELECT /*+ BROADCAST(zones) */ + c.customer_id, z.zone_name +FROM customers c +JOIN delivery_zones zones + ON ST_Contains(zones.boundary, c.location); +``` + +### Combining H3 and ST Functions + +```sql +-- Use H3 for fast pre-filtering, then ST for precise spatial operations +-- Step 1: Index store locations with H3 +CREATE TABLE store_h3 AS +SELECT store_id, name, location, + h3_longlatash3(ST_X(location), ST_Y(location), 9) AS h3_cell +FROM retail_stores; + +-- Step 2: Index customer locations with H3 +CREATE TABLE customer_h3 AS +SELECT customer_id, name, location, + h3_longlatash3(ST_X(location), ST_Y(location), 9) AS h3_cell +FROM customers; + +-- Step 3: Fast proximity using H3 pre-filter + precise ST distance +SELECT s.name AS store, c.name AS customer, + ST_DistanceSphere(s.location, c.location) AS distance_m +FROM store_h3 s +JOIN customer_h3 c + ON c.h3_cell IN (SELECT explode(h3_kring(s.h3_cell, 2))) +WHERE ST_DistanceSphere(s.location, c.location) < 2000; +``` + +### Spatial Join Performance + +Databricks automatically optimizes spatial joins using built-in spatial indexing. Spatial predicates like `ST_Intersects`, `ST_Contains`, and `ST_Within` in JOIN conditions benefit from up to **17x performance improvement** compared to classic clusters. No code changes required -- the optimizer applies spatial indexing automatically. + +**Performance tips:** +- Use `BROADCAST` hint when one side of the join is small enough to fit in memory. +- Use projected coordinate systems (e.g., SRID 5070 in meters) for distance calculations to avoid expensive spheroid functions. +- Combine H3 for coarse pre-filtering with ST for precise operations. +- Use Delta Lake liquid clustering on H3 cell columns for optimized data layout. +- Enable auto-optimization: `delta.autoOptimize.optimizeWrite` and `delta.autoOptimize.autoCompact`. + +--- + +## Part 2: Collations + +Collations define rules for comparing and sorting strings. Databricks supports binary, case-insensitive, accent-insensitive, and locale-specific collations using the ICU library. Available from Databricks Runtime 16.1+. + +### Collation Types + +| Collation | Description | Behavior | +|-----------|-------------|----------| +| `UTF8_BINARY` | Default. Byte-by-byte comparison of UTF-8 encoding | `'A' < 'Z' < 'a'` -- binary order, case/accent sensitive | +| `UTF8_LCASE` | Case-insensitive binary. Converts to lowercase then compares with UTF8_BINARY | `'A' == 'a'` but `'e' != 'e'` (accent sensitive) | +| `UNICODE` | ICU root locale. Language-agnostic Unicode ordering | `'a' < 'A' < 'A' < 'b'` -- groups similar characters | +| Locale-specific | ICU locale-based (e.g., `DE`, `FR`, `JA`) | Language-aware sorting rules | + +### Collation Syntax + +``` +{ UTF8_BINARY | UTF8_LCASE | { UNICODE | locale } [ _ modifier [...] ] } +``` + +Where `locale` is: +``` +language_code [ _ script_code ] [ _ country_code ] +``` + +- `language_code`: ISO 639-1 (e.g., `EN`, `DE`, `FR`, `JA`, `ZH`) +- `script_code`: ISO 15924 (e.g., `Hant` for Traditional Chinese, `Latn` for Latin) +- `country_code`: ISO 3166-1 (e.g., `US`, `DE`, `CAN`) + +### Collation Modifiers (DBR 16.2+) + +| Modifier | Description | Default | +|----------|-------------|---------| +| `CS` | Case-Sensitive: `'A' != 'a'` | Yes (default) | +| `CI` | Case-Insensitive: `'A' == 'a'` | No | +| `AS` | Accent-Sensitive: `'e' != 'e'` | Yes (default) | +| `AI` | Accent-Insensitive: `'e' == 'e'` | No | +| `RTRIM` | Trailing-space insensitive: `'Hello' == 'Hello '` | No | + +Specify at most one from each pair (CS/CI, AS/AI) plus optional RTRIM. Order does not matter. + +### Locale Examples + +| Collation Name | Description | +|----------------|-------------| +| `UNICODE` | ICU root locale, language-agnostic | +| `UNICODE_CI` | Unicode, case-insensitive | +| `UNICODE_CI_AI` | Unicode, case and accent-insensitive | +| `DE` | German sorting rules | +| `DE_CI_AI` | German, case and accent-insensitive | +| `FR_CAN` | French (Canada) | +| `EN_US` | English (United States) | +| `ZH_Hant_MAC` | Traditional Chinese (Macau) | +| `SR` | Serbian (normalized from `SR_CYR_SRN_CS_AS`) | +| `JA` | Japanese | +| `EN_CS_AI` | English, case-sensitive, accent-insensitive | +| `UTF8_LCASE_RTRIM` | Case-insensitive with trailing space trimming | + +### Collation Precedence + +From highest to lowest: + +1. **Explicit** -- Assigned via `COLLATE` expression +2. **Implicit** -- Derived from column, field, or variable definition +3. **Default** -- Applied to string literals and function results +4. **None** -- When combining different implicit collations + +Mixing two different **explicit** collations in the same expression produces an error. + +### Setting Collations at Different Levels + +#### Catalog Level (DBR 17.1+) + +```sql +-- Create catalog with default collation +CREATE CATALOG customer_cat + DEFAULT COLLATION UNICODE_CI_AI; + +-- All schemas, tables, and string columns created in this catalog +-- inherit UNICODE_CI_AI unless overridden +``` + +#### Schema Level (DBR 17.1+) + +```sql +-- Create schema with default collation +CREATE SCHEMA my_schema + DEFAULT COLLATION UNICODE_CI; + +-- Change default collation for new objects (existing objects unchanged) +ALTER SCHEMA my_schema + DEFAULT COLLATION UNICODE_CI_AI; +``` + +#### Table Level (DBR 16.3+) + +```sql +-- Table-level default collation +CREATE TABLE users ( + id INT, + username STRING, -- inherits UNICODE_CI from table default + email STRING, -- inherits UNICODE_CI from table default + password_hash STRING COLLATE UTF8_BINARY -- explicit override +) DEFAULT COLLATION UNICODE_CI; +``` + +#### Column Level (DBR 16.1+) + +```sql +-- Column-level collation +CREATE TABLE products ( + id INT, + name STRING COLLATE UNICODE_CI, + sku STRING COLLATE UTF8_BINARY, + description STRING COLLATE UNICODE_CI_AI +); + +-- Add column with collation +ALTER TABLE products + ADD COLUMN category STRING COLLATE UNICODE_CI; + +-- Change column collation (requires DBR 17.2+; may not be available on all SQL Warehouse versions) +ALTER TABLE products + ALTER COLUMN name SET COLLATION UNICODE_CI_AI; +``` + +#### Expression Level + +```sql +-- Apply collation inline in a query +SELECT * +FROM products +WHERE name COLLATE UNICODE_CI = 'laptop'; + +-- Check the collation of an expression +SELECT collation('test' COLLATE UNICODE_CI); +-- Returns: UNICODE_CI +``` + +### Collation Inheritance Hierarchy + +``` +Catalog DEFAULT COLLATION + -> Schema DEFAULT COLLATION (overrides catalog) + -> Table DEFAULT COLLATION (overrides schema) + -> Column COLLATE (overrides table) + -> Expression COLLATE (overrides column) +``` + +If no collation is specified at any level, `UTF8_BINARY` is used. + +### Collation-Aware String Functions + +Most string functions respect collations. Key collation-aware operations: + +| Function/Operator | Collation Behavior | +|-------------------|-------------------| +| `=`, `!=`, `<`, `>`, `<=`, `>=` | Comparison uses column/expression collation | +| `LIKE` | Pattern matching respects collation | +| `CONTAINS(str, substr)` | Substring search respects collation | +| `STARTSWITH(str, prefix)` | Prefix match respects collation | +| `ENDSWITH(str, suffix)` | Suffix match respects collation | +| `IN (...)` | Membership test respects collation | +| `BETWEEN` | Range comparison respects collation | +| `ORDER BY` | Sorting respects collation | +| `GROUP BY` | Grouping respects collation | +| `DISTINCT` | Deduplication respects collation | +| `REPLACE(str, old, new)` | Search respects collation | +| `TRIM` / `LTRIM` / `RTRIM` | Trim characters respect collation | + +**Performance note:** `STARTSWITH` and `ENDSWITH` with `UTF8_LCASE` collation show up to **10x performance speedup** compared to equivalent `LOWER()` workarounds. + +### Utility Functions + +```sql +-- Get collation of an expression +SELECT collation(name) FROM products; + +-- List all supported collations +SELECT * FROM collations(); + +-- Test collation with COLLATE +SELECT collation('hello' COLLATE DE_CI_AI); +-- Returns: DE_CI_AI +``` + +### Practical Collation Examples + +#### Case-Insensitive Search + +```sql +-- Using column collation (preferred - leverages indexes) +CREATE TABLE users ( + id INT, + username STRING COLLATE UTF8_LCASE, + email STRING COLLATE UTF8_LCASE +); + +INSERT INTO users VALUES + (1, 'JohnDoe', 'John@Example.com'), + (2, 'janedoe', 'JANE@EXAMPLE.COM'); + +-- Case-insensitive match automatically +SELECT * FROM users WHERE username = 'johndoe'; +-- Returns: JohnDoe + +SELECT * FROM users WHERE email = 'john@example.com'; +-- Returns: John@Example.com +``` + +#### Case-Insensitive Search with Expression Collation + +```sql +-- Ad-hoc case-insensitive comparison on a UTF8_BINARY column +SELECT * FROM products +WHERE name COLLATE UNICODE_CI = 'MacBook Pro'; +-- Matches: macbook pro, MACBOOK PRO, MacBook Pro, etc. +``` + +#### Accent-Insensitive Search + +```sql +-- Accent-insensitive matching +CREATE TABLE cities ( + id INT, + name STRING COLLATE UNICODE_CI_AI +); + +INSERT INTO cities VALUES (1, 'Montreal'), (2, 'Montreal'); + +SELECT * FROM cities WHERE name = 'Montreal'; +-- Returns both: Montreal and Montreal (treats e and e as equal) +``` + +#### Locale-Aware Sorting + +```sql +-- German sorting (umlauts sort correctly) +SELECT name +FROM german_customers +ORDER BY name COLLATE DE; +-- Sorts: Arzte before Bauer (A treated as A+e in German sorting) + +-- Swedish sorting (A, A, O sort after Z) +SELECT name +FROM swedish_customers +ORDER BY name COLLATE SV; +``` + +#### Trailing Space Handling + +```sql +-- RTRIM modifier ignores trailing spaces +SELECT 'Hello' COLLATE UTF8_BINARY_RTRIM = 'Hello '; +-- Returns: true + +SELECT 'Hello' COLLATE UTF8_BINARY = 'Hello '; +-- Returns: false +``` + +#### Catalog-Wide Case-Insensitive Setup + +```sql +-- Create a catalog where everything is case-insensitive by default +CREATE CATALOG app_data DEFAULT COLLATION UNICODE_CI; + +USE CATALOG app_data; +CREATE SCHEMA users_schema; +USE SCHEMA users_schema; + +-- All STRING columns automatically use UNICODE_CI +CREATE TABLE accounts ( + id INT, + username STRING, -- UNICODE_CI inherited from catalog + email STRING -- UNICODE_CI inherited from catalog +); + +-- Queries are automatically case-insensitive +SELECT * FROM accounts WHERE username = 'admin'; +-- Matches: Admin, ADMIN, admin, aDmIn, etc. +``` + +### Limitations and Notes + +- `CHECK` constraints and generated column expressions require `UTF8_BINARY` default collation. +- `hive_metastore` catalog tables do not support collation constraints. +- `ALTER SCHEMA ... DEFAULT COLLATION` only affects newly created objects, not existing ones. +- Mixing two different explicit collations in the same expression raises an error. +- `UTF8_LCASE` is used internally for Databricks identifier resolution (catalog, schema, table, column names). +- Databricks normalizes collation names by removing defaults (e.g., `SR_CYR_SRN_CS_AS` simplifies to `SR`). +- Collation modifiers require Databricks Runtime 16.2+. +- Catalog/Schema-level `DEFAULT COLLATION` requires Databricks Runtime 17.1+. diff --git a/.claude/skills/databricks-dbsql/materialized-views-pipes.md b/.claude/skills/databricks-dbsql/materialized-views-pipes.md new file mode 100644 index 00000000..078ad09b --- /dev/null +++ b/.claude/skills/databricks-dbsql/materialized-views-pipes.md @@ -0,0 +1,676 @@ +# Materialized Views, Temporary Tables/Views, and Pipe Syntax + +## 1. Materialized Views in Databricks SQL + +### Overview + +Materialized views (MVs) are Unity Catalog-managed tables that physically store precomputed query results. Unlike standard views that recompute on every query, MVs cache results and update automatically -- either on a schedule, when upstream data changes, or on-demand. + +Key characteristics: +- **Pre-computed storage**: Results are physically stored as Delta tables, reducing query latency +- **Automatic updates**: Changes propagate from source tables via incremental or full refresh +- **Serverless pipelines**: Each MV automatically creates a serverless pipeline for creation and refreshes +- **Incremental refresh**: Can compute only changed data from source tables under certain conditions + +### Requirements + +- **Compute**: Unity Catalog-enabled **Serverless** SQL warehouse +- **Region**: Serverless SQL warehouse support must be available in your region +- **Permissions**: + - Creator needs: `SELECT` on base tables, `USE CATALOG`, `USE SCHEMA`, `CREATE TABLE`, `CREATE MATERIALIZED VIEW` + - Refresh needs: Ownership or `REFRESH` privilege; MV owner must retain `SELECT` on base tables + - Query needs: `SELECT` on the MV, `USE CATALOG`, `USE SCHEMA` + +### CREATE MATERIALIZED VIEW Syntax + +```sql +{ CREATE OR REPLACE MATERIALIZED VIEW | CREATE MATERIALIZED VIEW [ IF NOT EXISTS ] } + view_name + [ column_list ] + [ view_clauses ] + AS query +``` + +**Column list** (optional): +```sql +CREATE MATERIALIZED VIEW mv_name ( + col1 INT NOT NULL, + col2 STRING, + col3 DOUBLE, + CONSTRAINT pk PRIMARY KEY (col1) +) +AS SELECT ... +``` + +**View clauses** (optional): +- `PARTITIONED BY (col1, col2)` -- partition by columns +- `CLUSTER BY (col1, col2)` or `CLUSTER BY AUTO` -- liquid clustering (cannot combine with PARTITIONED BY) +- `COMMENT 'description'` -- view description +- `TBLPROPERTIES ('key' = 'value')` -- user-defined properties +- `WITH ROW FILTER func ON (col1, col2)` -- row-level security +- `MASK func` on columns -- column-level masking +- `SCHEDULE` clause -- automatic refresh schedule +- `TRIGGER ON UPDATE` clause -- event-driven refresh + +### Basic Examples + +```sql +-- Simple materialized view +CREATE MATERIALIZED VIEW catalog.schema.daily_sales + COMMENT 'Daily sales aggregations' +AS SELECT + date, + region, + SUM(sales) AS total_sales, + COUNT(*) AS num_transactions +FROM catalog.schema.raw_sales +GROUP BY date, region; + +-- MV with explicit columns, constraints, and clustering +CREATE MATERIALIZED VIEW catalog.schema.customer_orders ( + customer_id INT NOT NULL, + full_name STRING, + order_count BIGINT, + CONSTRAINT customer_pk PRIMARY KEY (customer_id) +) +CLUSTER BY AUTO +COMMENT 'Customer order counts' +AS SELECT + c.customer_id, + c.full_name, + COUNT(o.order_id) AS order_count +FROM catalog.schema.customers c +INNER JOIN catalog.schema.orders o ON c.customer_id = o.customer_id +GROUP BY c.customer_id, c.full_name; +``` + +### Refresh Options + +MVs support four refresh strategies: + +#### 1. Manual Refresh + +```sql +-- Synchronous (blocks until complete) +REFRESH MATERIALIZED VIEW catalog.schema.daily_sales; + +-- Asynchronous (returns immediately) +REFRESH MATERIALIZED VIEW catalog.schema.daily_sales ASYNC; +``` + +#### 2. Scheduled Refresh (SCHEDULE) + +```sql +-- Every N hours/days/weeks +CREATE OR REPLACE MATERIALIZED VIEW catalog.schema.hourly_metrics + SCHEDULE EVERY 1 HOUR +AS SELECT date_trunc('hour', event_time) AS hour, COUNT(*) AS events +FROM catalog.schema.raw_events +GROUP BY 1; + +-- Cron-based schedule +CREATE OR REPLACE MATERIALIZED VIEW catalog.schema.nightly_report + SCHEDULE CRON '0 0 2 * * ?' AT TIME ZONE 'America/New_York' +AS SELECT * FROM catalog.schema.daily_aggregates; +``` + +Valid intervals: 1-72 hours, 1-31 days, 1-8 weeks. A Databricks Job is automatically created for scheduled refreshes. + +#### 3. Event-Driven Refresh (TRIGGER ON UPDATE) + +Automatically refreshes when upstream data changes: + +```sql +CREATE OR REPLACE MATERIALIZED VIEW catalog.schema.customer_orders + TRIGGER ON UPDATE +AS SELECT c.customer_id, c.name, COUNT(o.order_id) AS order_count +FROM catalog.schema.customers c +JOIN catalog.schema.orders o ON c.customer_id = o.customer_id +GROUP BY c.customer_id, c.name; + +-- With throttle to avoid excessive refreshes +CREATE OR REPLACE MATERIALIZED VIEW catalog.schema.customer_orders + TRIGGER ON UPDATE AT MOST EVERY INTERVAL 5 MINUTES +AS SELECT c.customer_id, c.name, COUNT(o.order_id) AS order_count +FROM catalog.schema.customers c +JOIN catalog.schema.orders o ON c.customer_id = o.customer_id +GROUP BY c.customer_id, c.name; +``` + +Trigger limitations: +- Maximum **10 upstream source tables** and **30 upstream views** +- Minimum **1-minute** interval (default) +- Maximum **1,000** trigger-based MVs per workspace +- Supports Delta tables, managed views, and streaming tables as sources +- Does **not** support Delta Sharing shared tables + +#### 4. Job-Based Orchestration + +Integrate refreshes into existing Databricks Jobs using SQL task types: + +```sql +-- In a Databricks Job SQL task +REFRESH MATERIALIZED VIEW catalog.schema.daily_sales_summary; +``` + +### Managing Schedules After Creation + +```sql +-- Add a schedule to an existing MV +ALTER MATERIALIZED VIEW catalog.schema.my_mv ADD SCHEDULE EVERY 4 HOURS; + +-- Add trigger-based refresh +ALTER MATERIALIZED VIEW catalog.schema.my_mv ADD TRIGGER ON UPDATE; + +-- Change an existing schedule +ALTER MATERIALIZED VIEW catalog.schema.my_mv ALTER SCHEDULE EVERY 2 HOURS; + +-- Remove a schedule +ALTER MATERIALIZED VIEW catalog.schema.my_mv DROP SCHEDULE; +``` + +### Incremental vs Full Refresh + +| Aspect | Incremental Refresh | Full Refresh | +|--------|-------------------|--------------| +| What it does | Evaluates changes since last refresh, merges only new/modified records | Re-executes the entire defining query | +| When used | When source tables support change tracking and query structure allows it | When incremental is not possible or not cost-effective | +| Requirements | Delta source tables with row tracking and CDF enabled | No special requirements | +| Cost | Lower (processes only deltas) | Higher (recomputes everything) | + +Enable row tracking on source tables for incremental refresh: + +```sql +ALTER TABLE catalog.schema.source_table +SET TBLPROPERTIES (delta.enableRowTracking = true); +``` + +By default, Databricks uses a cost model to choose between incremental and full refresh. Use `EXPLAIN CREATE MATERIALIZED VIEW` to verify the chosen refresh type. + +### Timeout Configuration + +```sql +-- Set timeout before creating or refreshing +SET STATEMENT_TIMEOUT = '6h'; +CREATE OR REFRESH MATERIALIZED VIEW catalog.schema.my_mv + SCHEDULE EVERY 12 HOURS +AS SELECT * FROM catalog.schema.large_source_table; +``` + +Default timeout is **2 days** if no warehouse timeout is configured. After changing warehouse timeouts, re-run `CREATE OR REFRESH` to apply new settings. + +### Monitoring + +- **Catalog Explorer**: View refresh status, schema, permissions, lineage under the MV entry +- **DESCRIBE EXTENDED**: Get schedule and configuration details +- **Jobs & Pipelines UI**: Monitor the automatically created pipeline +- **Pipelines API**: `GET /api/2.0/pipelines/{pipeline_id}` for programmatic access +- **DESCRIBE EXTENDED AS JSON**: Get refresh information including last refresh time, type, status, and schedule (added October 2025) + +### Key Limitations + +- No identity columns or surrogate keys +- Cannot read change data feeds (CDF) from materialized views +- Time travel queries are not supported +- `OPTIMIZE` and `VACUUM` commands are not supported (managed automatically) +- **Null handling edge case**: `SUM()` on a nullable column returns **0** instead of `NULL` when all non-null values are removed +- Non-column expressions in the defining query require explicit aliases +- Underlying storage may contain upstream data not visible in the MV definition (required for incremental refresh) +- Cannot rename the MV or change its owner via ALTER (must drop and recreate) +- No data quality expectations support +- AWS PrivateLink requires contacting Databricks support + +### DBSQL Materialized Views vs Pipeline (SDP/DLT) Materialized Views + +| Aspect | DBSQL Materialized Views | Pipeline (SDP/DLT) Materialized Views | +|--------|-------------------------|--------------------------------------| +| **Creation** | `CREATE MATERIALIZED VIEW` in SQL warehouse | Defined in pipeline source code (SQL or Python) | +| **Pipeline type** | `MV/ST` (auto-created serverless pipeline) | `ETL` (explicitly defined pipeline) | +| **Pipeline management** | Automatically created and managed | User-defined, full pipeline lifecycle control | +| **Syntax** | Standard `CREATE MATERIALIZED VIEW` | `CREATE OR REFRESH MATERIALIZED VIEW` with `PRIVATE` option | +| **Private MVs** | Not supported | `PRIVATE` keyword for pipeline-scoped views | +| **Refresh trigger** | Schedule, trigger-on-update, manual, or job-based | Pipeline update (manual or scheduled) | +| **Compute** | Serverless SQL warehouse (creation); serverless pipeline (refresh) | Pipeline compute (serverless or classic) | +| **Data quality** | Not supported | Expectations supported | +| **Best for** | Standalone MVs, BI dashboard acceleration, simple ETL | Complex multi-table pipelines, orchestrated transformations | + +Both approaches ultimately use similar underlying mechanisms (serverless pipelines) and support incremental refresh. The key difference is in management: DBSQL MVs are self-contained with auto-managed pipelines, while pipeline MVs are part of a broader orchestrated data flow. + +### Best Practices + +1. **Choose the right refresh strategy**: `TRIGGER ON UPDATE` for near-real-time SLA; `SCHEDULE` for predictable cadences; manual or job-based for complex orchestration +2. **Enable row tracking** on Delta source tables for cost-effective incremental refreshes +3. **Use async refreshes** when refresh duration is long and downstream queries can tolerate slight staleness +4. **Set explicit timeouts** when refresh duration is predictable to avoid runaway costs +5. **Use `CLUSTER BY AUTO`** for automatic liquid clustering optimization +6. **Apply row filters and column masks** at MV creation for security +7. **Monitor refresh types** with `EXPLAIN CREATE MATERIALIZED VIEW` to verify incremental behavior + +--- + +## 2. Temporary Tables and Temporary Views + +### Temporary Tables + +Temporary tables are session-scoped, physical Delta tables for intermediate data storage. They exist only within the session where they are created. + +#### Key Characteristics + +- **Session-scoped**: Only visible to the creating session; isolated from other users +- **Physical storage**: Stored as Delta tables in an internal Unity Catalog location tied to the workspace +- **Maximum lifetime**: 7 days from session creation, or until the session ends (whichever comes first) +- **No catalog privileges needed**: Any user can create temporary tables without `CREATE TABLE` privileges +- **Automatic cleanup**: Databricks reclaims storage automatically, even after unexpected disconnections +- **Shared namespace**: Temporary tables share a namespace with temporary views; you cannot create both with the same name + +#### Syntax + +```sql +-- Create with schema +CREATE TEMPORARY TABLE temp_results ( + id INT, + name STRING, + score DOUBLE +); + +-- Create from query (CTAS) +CREATE TEMP TABLE temp_active_users +AS SELECT user_id, username, last_login +FROM catalog.schema.users +WHERE last_login > current_date() - INTERVAL 30 DAYS; +``` + +Note: `CREATE OR REPLACE TEMP TABLE` is **not yet supported**. To replace, drop first. + +#### Supported Operations + +```sql +-- INSERT +INSERT INTO temp_results VALUES (1, 'Alice', 95.5); +INSERT INTO temp_results SELECT * FROM catalog.schema.source WHERE score > 90; + +-- UPDATE +UPDATE temp_results SET score = 100.0 WHERE name = 'Alice'; + +-- MERGE +MERGE INTO temp_results t +USING catalog.schema.new_scores s ON t.id = s.id +WHEN MATCHED THEN UPDATE SET score = s.score +WHEN NOT MATCHED THEN INSERT *; +``` + +#### Unsupported Operations + +- `DELETE FROM` (not supported) +- `ALTER TABLE` (drop and recreate instead) +- Shallow or deep cloning +- Time travel +- Streaming (foreachBatch) +- DataFrame API access (SQL only) + +#### Use Cases + +1. **Exploratory analysis**: Store intermediate results while iterating on queries +2. **Multi-step transformations**: Break complex transformations into readable steps +3. **Query result reuse**: Compute once, reference multiple times in a session +4. **Sandboxing**: Test transformations without affecting production tables + +#### Name Resolution + +When referencing a single-part table name, Databricks resolves in order: +1. Temporary tables in the current session +2. Permanent tables in the current schema + +Temporary tables with the same name as permanent tables **take precedence** within that session. + +### Temporary Views + +Temporary views are session-scoped, logical views that store a query definition (not data). They are recomputed on each access. + +#### Syntax + +```sql +-- Create a temporary view +CREATE TEMPORARY VIEW active_customers +AS SELECT customer_id, name, email +FROM catalog.schema.customers +WHERE status = 'active'; + +-- Replace an existing temporary view +CREATE OR REPLACE TEMPORARY VIEW active_customers +AS SELECT customer_id, name, email, phone +FROM catalog.schema.customers +WHERE status = 'active' AND last_order > current_date() - INTERVAL 90 DAYS; +``` + +#### Key Rules + +- Temporary view names **must not be qualified** (no catalog or schema prefix) +- No special privileges required to create +- Dropped automatically when the session ends +- Cannot use `schema_binding` clauses +- Support `COMMENT` and column comments + +#### Global Temporary Views (Databricks Runtime Only) + +```sql +-- Only available in Databricks Runtime, NOT in Databricks SQL +CREATE GLOBAL TEMPORARY VIEW global_summary +AS SELECT region, SUM(revenue) AS total_revenue +FROM catalog.schema.sales +GROUP BY region; + +-- Must reference via global_temp schema +SELECT * FROM global_temp.global_summary; +``` + +Global temporary views are stored in a system `global_temp` schema and are session-scoped. They are **not available in Databricks SQL** (only Databricks Runtime). + +### Temporary Tables vs Temporary Views + +| Aspect | Temporary Tables | Temporary Views | +|--------|-----------------|-----------------| +| **Storage** | Physical Delta table (stores data) | Logical (stores query definition only) | +| **Compute on access** | No (data already materialized) | Yes (query re-executed each time) | +| **DML support** | INSERT, UPDATE, MERGE | None (read-only definition) | +| **Max lifetime** | 7 days or session end | Session end | +| **CREATE OR REPLACE** | Not supported | Supported | +| **Performance** | Faster for repeated reads (data cached) | Slower for repeated reads (recomputed) | +| **Storage cost** | Uses cloud storage (auto-cleaned) | No storage cost | +| **Shared namespace** | Yes (conflicts with temp views) | Yes (conflicts with temp tables) | +| **When to use** | Large intermediate results, repeated access, DML needed | Simple query aliases, lightweight transformations | + +### Temporary Metric Views (Added September 2025) + +```sql +-- Temporary metric views: session-scoped, dropped on session end +CREATE TEMPORARY METRIC VIEW session_metrics +AS SELECT ...; +``` + +Available in Databricks Runtime 17.2+ and Databricks SQL. + +--- + +## 3. SQL Pipe Syntax + +### Overview + +Pipe syntax (introduced February 2025) allows composing SQL queries as a top-down, left-to-right chain of operations using the `|>` operator. It eliminates deeply nested subqueries and makes SQL read like a DataFrame pipeline. + +**Requirements**: Databricks SQL or Databricks Runtime **16.2+** + +### Basic Syntax + +```sql +FROM table_name +|> pipe_operation_1 +|> pipe_operation_2 +|> pipe_operation_3; +``` + +Any query can start a pipeline. The most common pattern is `FROM table_name`, but any SELECT or subquery also works: + +```sql +-- Start from a table +FROM catalog.schema.sales |> WHERE region = 'US' |> SELECT product, amount; + +-- Start from a subquery +(SELECT * FROM catalog.schema.sales WHERE year = 2025) +|> AGGREGATE SUM(amount) AS total GROUP BY product +|> ORDER BY total DESC; +``` + +### All Available Pipe Operators + +#### SELECT -- Project columns + +```sql +FROM catalog.schema.employees +|> SELECT employee_id, name, department, salary; +``` + +Note: `SELECT` in pipe syntax **must not contain aggregate functions**. Use `AGGREGATE` instead. + +#### EXTEND -- Add new columns + +Appends new columns to the existing result set (like PySpark's `withColumn`): + +```sql +FROM catalog.schema.orders +|> EXTEND quantity * unit_price AS line_total +|> EXTEND line_total * 0.1 AS tax; +``` + +Expressions can reference columns created by preceding expressions in the same EXTEND. + +#### SET -- Modify existing columns + +Overrides existing column values (like PySpark's `withColumn` on existing columns): + +```sql +FROM catalog.schema.products +|> SET price = price * 1.1 +|> SET name = UPPER(name); +``` + +Raises `UNRESOLVED_COLUMN` if the column does not exist. + +#### DROP -- Remove columns + +Removes columns (shorthand for `SELECT * EXCEPT`): + +```sql +FROM catalog.schema.users +|> DROP password_hash, internal_id, debug_flag; +``` + +#### WHERE -- Filter rows + +```sql +FROM catalog.schema.transactions +|> WHERE amount > 1000 +|> WHERE transaction_date >= '2025-01-01'; +``` + +#### AGGREGATE -- Aggregation with optional GROUP BY + +```sql +-- Full-table aggregation +FROM catalog.schema.orders +|> AGGREGATE + COUNT(*) AS total_orders, + SUM(amount) AS total_revenue, + AVG(amount) AS avg_order_value; + +-- Grouped aggregation +FROM catalog.schema.orders +|> AGGREGATE + SUM(amount) AS total_revenue, + COUNT(*) AS order_count + GROUP BY region, product_category; +``` + +In pipe syntax, `AGGREGATE` replaces `SELECT ... GROUP BY`. Numeric values in GROUP BY reference input columns, not generated results. + +#### JOIN -- Combine relations + +```sql +FROM catalog.schema.orders +|> AS o +|> LEFT JOIN catalog.schema.customers c ON o.customer_id = c.customer_id +|> SELECT o.order_id, c.name, o.amount; +``` + +All JOIN types are supported: `INNER JOIN`, `LEFT OUTER JOIN`, `RIGHT OUTER JOIN`, `FULL OUTER JOIN`, `CROSS JOIN`, `SEMI JOIN`, `ANTI JOIN`. + +#### ORDER BY -- Sort results + +```sql +FROM catalog.schema.products +|> ORDER BY price DESC, name ASC; +``` + +#### LIMIT and OFFSET -- Pagination + +```sql +FROM catalog.schema.products +|> ORDER BY price DESC +|> LIMIT 10 +|> OFFSET 20; +``` + +#### AS -- Assign table alias + +Names the intermediate result for use in subsequent JOINs or self-references: + +```sql +FROM catalog.schema.sales +|> AS current_sales +|> JOIN catalog.schema.targets t ON current_sales.region = t.region +|> SELECT current_sales.region, current_sales.revenue, t.target; +``` + +#### Set Operators -- UNION, EXCEPT, INTERSECT + +```sql +FROM catalog.schema.us_customers +|> UNION ALL (SELECT * FROM catalog.schema.eu_customers) +|> ORDER BY name; +``` + +#### TABLESAMPLE -- Sample rows + +```sql +-- Sample by row count +FROM catalog.schema.large_table +|> TABLESAMPLE (1000 ROWS); + +-- Sample by percentage +FROM catalog.schema.large_table +|> TABLESAMPLE (10 PERCENT); +``` + +#### PIVOT -- Rows to columns + +```sql +FROM catalog.schema.quarterly_sales +|> PIVOT ( + SUM(revenue) + FOR quarter IN ('Q1', 'Q2', 'Q3', 'Q4') + ); +``` + +#### UNPIVOT -- Columns to rows + +```sql +FROM catalog.schema.wide_metrics +|> UNPIVOT ( + metric_value FOR metric_name IN (cpu_usage, memory_usage, disk_usage) + ); +``` + +### Practical Examples + +#### Example 1: Multi-step aggregation (replaces nested subqueries) + +Traditional SQL: +```sql +SELECT c_count, COUNT(*) AS custdist +FROM ( + SELECT c_custkey, COUNT(o_orderkey) AS c_count + FROM customer + LEFT OUTER JOIN orders ON c_custkey = o_custkey + AND o_comment NOT LIKE '%unusual%packages%' + GROUP BY c_custkey +) AS c_orders +GROUP BY c_count +ORDER BY custdist DESC, c_count DESC; +``` + +Pipe syntax: +```sql +FROM customer +|> LEFT OUTER JOIN orders ON c_custkey = o_custkey + AND o_comment NOT LIKE '%unusual%packages%' +|> AGGREGATE COUNT(o_orderkey) AS c_count GROUP BY c_custkey +|> AGGREGATE COUNT(*) AS custdist GROUP BY c_count +|> ORDER BY custdist DESC, c_count DESC; +``` + +#### Example 2: Data exploration and profiling + +```sql +FROM catalog.schema.raw_events +|> WHERE event_date >= '2025-01-01' +|> EXTEND YEAR(event_date) AS event_year, MONTH(event_date) AS event_month +|> AGGREGATE + COUNT(*) AS event_count, + COUNT(DISTINCT user_id) AS unique_users, + AVG(duration_seconds) AS avg_duration + GROUP BY event_year, event_month +|> ORDER BY event_year, event_month; +``` + +#### Example 3: Building a report step-by-step + +```sql +FROM catalog.schema.orders +|> AS o +|> JOIN catalog.schema.products p ON o.product_id = p.product_id +|> JOIN catalog.schema.customers c ON o.customer_id = c.customer_id +|> WHERE o.order_date >= '2025-01-01' +|> EXTEND o.quantity * p.unit_price AS line_total +|> AGGREGATE + SUM(line_total) AS total_revenue, + COUNT(DISTINCT o.order_id) AS order_count + GROUP BY c.region, p.category +|> ORDER BY total_revenue DESC +|> LIMIT 20; +``` + +#### Example 4: Debugging by commenting out tail operations + +```sql +FROM catalog.schema.sales +|> WHERE region = 'US' +|> EXTEND amount * tax_rate AS tax_amount +-- |> AGGREGATE SUM(tax_amount) AS total_tax GROUP BY state +-- |> ORDER BY total_tax DESC +; +-- Comment out the last operations to inspect intermediate results +``` + +### Pipe Syntax vs Traditional SQL + +| Aspect | Traditional SQL | Pipe SQL | +|--------|----------------|----------| +| **Reading order** | Inside-out (subqueries first) | Top-down, left-to-right | +| **Clause order** | Fixed: SELECT...FROM...WHERE...GROUP BY...ORDER BY | Any order, any number of times | +| **Subquery nesting** | Required for multi-step aggregations | Eliminated via chaining | +| **Column addition** | SELECT *, expr AS new_col | `EXTEND expr AS new_col` | +| **Column removal** | SELECT with explicit column list or EXCEPT | `DROP col1, col2` | +| **Column modification** | SELECT with expression replacing column | `SET col = new_expr` | +| **Aggregation** | SELECT agg() ... GROUP BY | `AGGREGATE agg() GROUP BY` | +| **Composability** | Limited; requires CTEs or subqueries | Native chaining | +| **Interoperability** | Standard | Fully interoperable with traditional SQL | + +### When to Use Pipe Syntax + +**Use pipe syntax when:** +- Multi-step aggregations would require nested subqueries +- You want DataFrame-like readability in SQL +- Building exploratory or iterative queries (easy to add/remove steps) +- Complex transformations with many joins, filters, and projections + +**Use traditional SQL when:** +- Simple queries that are already readable +- Team is more familiar with standard SQL +- Queries will be shared with tools that may not support pipe syntax + +### Performance Considerations + +- Pipe syntax is **syntactic sugar** -- it compiles to the same execution plan as traditional SQL +- No performance difference between pipe and traditional syntax for equivalent queries +- Best practice: Place data-reducing operations (`WHERE`, `DROP`, `SELECT`) early in the pipeline to minimize data flowing through subsequent operations +- Use `TABLESAMPLE` during development to work with smaller datasets diff --git a/.claude/skills/databricks-dbsql/sql-scripting.md b/.claude/skills/databricks-dbsql/sql-scripting.md new file mode 100644 index 00000000..549a4270 --- /dev/null +++ b/.claude/skills/databricks-dbsql/sql-scripting.md @@ -0,0 +1,1077 @@ +# SQL Scripting, Stored Procedures, Recursive CTEs, and Transactions + +> Databricks SQL procedural extensions based on the SQL/PSM standard. Covers SQL scripting (compound statements, control flow, exception handling), stored procedures, recursive CTEs, and multi-statement transactions. + +--- + +## Table of Contents + +- [SQL Scripting](#sql-scripting) + - [Compound Statements (BEGIN...END)](#compound-statements-beginend) + - [Variable Declaration (DECLARE)](#variable-declaration-declare) + - [Variable Assignment (SET)](#variable-assignment-set) + - [Control Flow](#control-flow) + - [IF / ELSEIF / ELSE](#if--elseif--else) + - [CASE Statement](#case-statement) + - [WHILE Loop](#while-loop) + - [FOR Loop](#for-loop) + - [LOOP Statement](#loop-statement) + - [REPEAT Statement](#repeat-statement) + - [LEAVE and ITERATE](#leave-and-iterate) + - [Exception Handling](#exception-handling) + - [Condition Declaration](#condition-declaration) + - [Handler Declaration](#handler-declaration) + - [SIGNAL and RESIGNAL](#signal-and-resignal) + - [EXECUTE IMMEDIATE (Dynamic SQL)](#execute-immediate-dynamic-sql) +- [Stored Procedures](#stored-procedures) + - [CREATE PROCEDURE](#create-procedure) + - [CALL (Invoke a Procedure)](#call-invoke-a-procedure) + - [DROP PROCEDURE](#drop-procedure) + - [DESCRIBE PROCEDURE](#describe-procedure) + - [SHOW PROCEDURES](#show-procedures) +- [Recursive CTEs](#recursive-ctes) + - [WITH RECURSIVE Syntax](#with-recursive-syntax) + - [Anchor and Recursive Members](#anchor-and-recursive-members) + - [MAX RECURSION LEVEL](#max-recursion-level) + - [Use Cases and Examples](#use-cases-and-examples) + - [Limitations](#limitations) +- [Multi-Statement Transactions](#multi-statement-transactions) + - [Overview and Current Status](#overview-and-current-status) + - [SQL Scripting Atomic Blocks](#sql-scripting-atomic-blocks) + - [Python Connector Transaction API](#python-connector-transaction-api) + - [Isolation Levels](#isolation-levels) + - [Write Conflicts and Concurrency](#write-conflicts-and-concurrency) + - [Best Practices](#best-practices) + +--- + +## SQL Scripting + +**Availability**: Databricks Runtime 16.3+ and Databricks SQL + +SQL scripting enables procedural logic using the SQL/PSM standard. Every SQL script starts with a compound statement block (`BEGIN...END`). + +### Compound Statements (BEGIN...END) + +A compound statement is the fundamental building block containing variable declarations, condition/handler declarations, and executable statements. + +**Syntax**: + +```sql +[ label : ] BEGIN + [ { declare_variable | declare_condition } ; [...] ] + [ declare_handler ; [...] ] + [ SQL_statement ; [...] ] +END [ label ] +``` + +**Key rules**: + +- Declarations must appear before executable statements +- Variable declarations come before condition declarations, which come before handler declarations +- Top-level compound statements cannot specify labels +- `NOT ATOMIC` is the default and only behavior (no automatic rollback on failure) +- In notebooks, the compound statement must be the sole statement in the cell + +**Supported statement types in body**: + +| Category | Statements | +|----------|-----------| +| DDL | ALTER, CREATE, DROP | +| DCL | GRANT, REVOKE | +| DML | INSERT, UPDATE, DELETE, MERGE | +| Query | SELECT | +| Assignment | SET | +| Dynamic SQL | EXECUTE IMMEDIATE | +| Control flow | IF, CASE, WHILE, FOR, LOOP, REPEAT, LEAVE, ITERATE | +| Nesting | Nested BEGIN...END blocks | + +**Minimal example**: + +```sql +BEGIN + SELECT 'Hello, SQL Scripting!'; +END; +``` + +### Variable Declaration (DECLARE) + +**Syntax**: + +```sql +DECLARE variable_name [, ...] data_type [ DEFAULT default_expr ]; +``` + +- Variables initialize to `NULL` if no `DEFAULT` is specified +- Data type can be omitted when `DEFAULT` is provided (type inferred from expression) +- Multiple variable names in a single `DECLARE` supported in Runtime 17.2+ +- Variables are scoped to their enclosing compound statement +- Variable names resolve from the innermost scope outward; use labels to disambiguate + +**Examples**: + +```sql +BEGIN + DECLARE counter INT DEFAULT 0; + DECLARE name STRING DEFAULT 'unknown'; + DECLARE x, y, z DOUBLE DEFAULT 0.0; -- Runtime 17.2+ + DECLARE inferred DEFAULT current_date(); -- type inferred as DATE + + SET counter = counter + 1; + VALUES (counter, name); +END; +``` + +### Variable Assignment (SET) + +**Syntax**: + +```sql +SET variable_name = expression; +SET VAR variable_name = expression; -- explicit local variable +SET (var1, var2, ...) = (expr1, expr2, ...); -- multi-assignment +``` + +Use `SET VAR` to explicitly target a local variable when a session variable with the same name exists. + +**Example**: + +```sql +BEGIN + DECLARE total INT DEFAULT 0; + DECLARE label STRING; + SET total = 100; + SET label = 'final'; + VALUES (total, label); +END; +``` + +### Control Flow + +#### IF / ELSEIF / ELSE + +Executes statements based on the first condition evaluating to `TRUE`. + +**Syntax**: + +```sql +IF condition THEN + { stmt ; } [...] +[ ELSEIF condition THEN + { stmt ; } [...] ] [...] +[ ELSE + { stmt ; } [...] ] +END IF; +``` + +**Example**: + +```sql +BEGIN + DECLARE score INT DEFAULT 85; + DECLARE grade STRING; + + IF score >= 90 THEN + SET grade = 'A'; + ELSEIF score >= 80 THEN + SET grade = 'B'; + ELSEIF score >= 70 THEN + SET grade = 'C'; + ELSE + SET grade = 'F'; + END IF; + + VALUES (grade); -- Returns 'B' +END; +``` + +#### CASE Statement + +Two forms: **simple CASE** (compare expression) and **searched CASE** (evaluate boolean conditions). + +**Simple CASE syntax**: + +```sql +CASE expr + WHEN opt1 THEN { stmt ; } [...] + WHEN opt2 THEN { stmt ; } [...] + [ ELSE { stmt ; } [...] ] +END CASE; +``` + +**Searched CASE syntax**: + +```sql +CASE + WHEN cond1 THEN { stmt ; } [...] + WHEN cond2 THEN { stmt ; } [...] + [ ELSE { stmt ; } [...] ] +END CASE; +``` + +Only the first matching branch executes. + +**Example**: + +```sql +BEGIN + DECLARE status STRING DEFAULT 'active'; + + CASE status + WHEN 'active' THEN VALUES ('Processing'); + WHEN 'paused' THEN VALUES ('On hold'); + WHEN 'archived' THEN VALUES ('Read-only'); + ELSE VALUES ('Unknown status'); + END CASE; +END; +``` + +#### WHILE Loop + +Repeats while a condition is `TRUE`. + +**Syntax**: + +```sql +[ label : ] WHILE condition DO + { stmt ; } [...] +END WHILE [ label ]; +``` + +**Example** -- sum odd numbers from 1 to 10: + +```sql +BEGIN + DECLARE total INT DEFAULT 0; + DECLARE i INT DEFAULT 0; + + sum_odds: WHILE i < 10 DO + SET i = i + 1; + IF i % 2 = 0 THEN + ITERATE sum_odds; -- skip even numbers + END IF; + SET total = total + i; + END WHILE sum_odds; + + VALUES (total); -- Returns 25 +END; +``` + +#### FOR Loop + +Iterates over query result rows. + +**Syntax**: + +```sql +[ label : ] FOR [ variable_name AS ] query DO + { stmt ; } [...] +END FOR [ label ]; +``` + +- Use `variable_name` (not the label) to qualify column references from the cursor +- For Delta tables, modifying the source during iteration does not affect cursor results +- Loop may not fully execute the query if terminated early by `LEAVE` or an error + +**Example** -- process each row from a query: + +```sql +BEGIN + DECLARE total_revenue DOUBLE DEFAULT 0.0; + + process_orders: FOR row AS + SELECT order_id, amount FROM orders WHERE status = 'completed' + DO + SET total_revenue = total_revenue + row.amount; + IF total_revenue > 1000000 THEN + LEAVE process_orders; + END IF; + END FOR process_orders; + + VALUES (total_revenue); +END; +``` + +#### LOOP Statement + +Unconditional loop; must use `LEAVE` to exit. + +**Syntax**: + +```sql +[ label : ] LOOP + { stmt ; } [...] +END LOOP [ label ]; +``` + +**Example**: + +```sql +BEGIN + DECLARE counter INT DEFAULT 0; + + count_up: LOOP + SET counter = counter + 1; + IF counter >= 5 THEN + LEAVE count_up; + END IF; + END LOOP count_up; + + VALUES (counter); -- Returns 5 +END; +``` + +#### REPEAT Statement + +Executes at least once, then repeats until condition is `TRUE`. + +**Syntax**: + +```sql +[ label : ] REPEAT + { stmt ; } [...] + UNTIL condition +END REPEAT [ label ]; +``` + +**Example**: + +```sql +BEGIN + DECLARE total INT DEFAULT 0; + DECLARE i INT DEFAULT 0; + + sum_loop: REPEAT + SET i = i + 1; + IF i % 2 != 0 THEN + SET total = total + i; + END IF; + UNTIL i >= 10 + END REPEAT sum_loop; + + VALUES (total); -- Returns 25 +END; +``` + +#### LEAVE and ITERATE + +| Statement | Purpose | Equivalent | +|-----------|---------|-----------| +| `LEAVE label` | Exit the labeled loop or compound block | `BREAK` in other languages | +| `ITERATE label` | Skip to the next iteration of the labeled loop | `CONTINUE` in other languages | + +Both require a labeled loop to target. + +### Exception Handling + +#### Condition Declaration + +Define named conditions for specific SQLSTATE codes. + +**Syntax**: + +```sql +DECLARE condition_name CONDITION [ FOR SQLSTATE [ VALUE ] sqlstate ]; +``` + +- `sqlstate` is a 5-character alphanumeric string (A-Z, 0-9, case-insensitive) +- Cannot start with `'00'`, `'01'`, or `'XX'` +- Defaults to `'45000'` if not specified + +**Example**: + +```sql +BEGIN + DECLARE divide_by_zero CONDITION FOR SQLSTATE '22012'; + -- Use in handler declarations below +END; +``` + +#### Handler Declaration + +Catch and handle exceptions within compound statements. + +**Syntax**: + +```sql +DECLARE handler_type HANDLER FOR condition_value [, ...] handler_action; +``` + +| Parameter | Options | Description | +|-----------|---------|-------------| +| `handler_type` | `EXIT` | Exits the enclosing compound after handling | +| `condition_value` | `SQLSTATE 'xxxxx'`, `condition_name`, `SQLEXCEPTION`, `NOT FOUND` | What to catch | +| `handler_action` | Single statement or nested `BEGIN...END` | What to execute | + +- `SQLEXCEPTION` catches all error states (SQLSTATE class not `'00'` or `'01'`) +- `NOT FOUND` catches `'02xxx'` states (no data found) +- A handler cannot apply to statements in its own body + +**Example** -- catch division by zero: + +```sql +BEGIN + DECLARE result DOUBLE; + DECLARE EXIT HANDLER FOR SQLSTATE '22012' + BEGIN + SET result = -1; + END; + + SET result = 10 / 0; -- triggers handler + VALUES (result); -- Returns -1 +END; +``` + +**Example** -- generic exception handler: + +```sql +BEGIN + DECLARE error_msg STRING DEFAULT 'none'; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + SET error_msg = 'An error occurred'; + INSERT INTO error_log (message, ts) VALUES (error_msg, current_timestamp()); + END; + + -- statements that might fail + INSERT INTO target_table SELECT * FROM source_table; +END; +``` + +#### SIGNAL and RESIGNAL + +Raise or re-raise exceptions. + +**SIGNAL syntax**: + +```sql +SIGNAL condition_name + [ SET { MESSAGE_ARGUMENTS = argument_map | MESSAGE_TEXT = message_str } ]; + +SIGNAL SQLSTATE [ VALUE ] sqlstate + [ SET MESSAGE_TEXT = message_str ]; +``` + +**RESIGNAL syntax** (use in handlers to preserve diagnostic stack): + +```sql +RESIGNAL [ condition_name | SQLSTATE [ VALUE ] sqlstate ] + [ SET { MESSAGE_ARGUMENTS = argument_map | MESSAGE_TEXT = message_str } ]; +``` + +- Prefer `RESIGNAL` over `SIGNAL` inside handlers -- `RESIGNAL` preserves the diagnostic stack while `SIGNAL` clears it +- `MESSAGE_ARGUMENTS` takes a `MAP` literal + +**Example** -- validate input and raise custom error: + +```sql +BEGIN + DECLARE input_value INT DEFAULT 150; + + IF input_value > 100 THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Input value must be <= 100'; + END IF; + + VALUES (input_value); +END; +``` + +**Example** -- using named conditions with MESSAGE_ARGUMENTS: + +```sql +BEGIN + DECLARE input INT DEFAULT 5; + DECLARE arg_map MAP; + + IF input > 4 THEN + SET arg_map = map('errorMessage', 'Input must be <= 4.'); + SIGNAL USER_RAISED_EXCEPTION + SET MESSAGE_ARGUMENTS = arg_map; + END IF; +END; +``` + +### EXECUTE IMMEDIATE (Dynamic SQL) + +Execute SQL statements constructed as strings at runtime. + +**Availability**: Runtime 14.3+; expression-based `sql_string` and nested execution from Runtime 17.3+. + +**Syntax**: + +```sql +EXECUTE IMMEDIATE sql_string + [ INTO var_name [, ...] ] + [ USING { arg_expr [ AS ] [ alias ] } [, ...] ]; +``` + +- `sql_string`: a constant expression producing a well-formed SQL statement +- `INTO`: captures a single-row result into variables (returns `NULL` for zero rows; errors for multiple rows) +- `USING`: binds values to positional (`?`) or named (`:param`) parameter markers (cannot mix styles) + +**Examples**: + +```sql +-- Positional parameters +EXECUTE IMMEDIATE 'SELECT SUM(c1) FROM VALUES(?), (?) AS t(c1)' USING 5, 6; + +-- Named parameters with INTO +BEGIN + DECLARE total INT; + EXECUTE IMMEDIATE 'SELECT SUM(c1) FROM VALUES(:a), (:b) AS t(c1)' + INTO total USING (5 AS a, 6 AS b); + VALUES (total); -- Returns 11 +END; + +-- Dynamic table operations +BEGIN + DECLARE table_name STRING DEFAULT 'my_catalog.my_schema.staging'; + EXECUTE IMMEDIATE 'TRUNCATE TABLE ' || table_name; + EXECUTE IMMEDIATE 'INSERT INTO ' || table_name || ' SELECT * FROM source'; +END; +``` + +--- + +## Stored Procedures + +**Availability**: Public Preview -- Databricks Runtime 17.0+ + +Stored procedures persist SQL scripts in Unity Catalog and are invoked with `CALL`. + +### CREATE PROCEDURE + +**Syntax**: + +```sql +CREATE [ OR REPLACE ] PROCEDURE [ IF NOT EXISTS ] + procedure_name ( [ parameter [, ...] ] ) + characteristic [...] + AS compound_statement +``` + +**Parameter definition**: + +```sql +[ IN | OUT | INOUT ] parameter_name data_type + [ DEFAULT default_expression ] + [ COMMENT parameter_comment ] +``` + +| Parameter mode | Behavior | +|---------------|----------| +| `IN` (default) | Input-only; value passed into the procedure | +| `OUT` | Output-only; initialized to `NULL`; final value returned on success | +| `INOUT` | Input and output; accepts a value and returns the modified value on success | + +**Required characteristics**: + +| Characteristic | Description | +|---------------|-------------| +| `LANGUAGE SQL` | Specifies the implementation language | +| `SQL SECURITY INVOKER` | Executes under the invoker's authority | + +**Optional characteristics**: + +| Characteristic | Description | +|---------------|-------------| +| `NOT DETERMINISTIC` | Procedure may return different results with identical inputs | +| `MODIFIES SQL DATA` | Procedure modifies SQL data | +| `COMMENT 'description'` | Human-readable description | +| `DEFAULT COLLATION UTF8_BINARY` | Required when schema uses non-UTF8_BINARY collation (Runtime 17.1+) | + +**Rules**: + +- `OR REPLACE` and `IF NOT EXISTS` cannot be combined +- Parameter names must be unique within the procedure +- `DEFAULT` is not supported for `OUT` parameters +- Once a parameter has a `DEFAULT`, all subsequent parameters must also have defaults +- Default expressions cannot reference other parameters or contain subqueries +- Body is validated syntactically at creation but semantically only at invocation + +**Example** -- ETL procedure with output parameters: + +```sql +CREATE OR REPLACE PROCEDURE run_daily_etl( + IN source_schema STRING, + IN target_schema STRING, + OUT rows_processed INT, + OUT status STRING DEFAULT 'pending' +) +LANGUAGE SQL +SQL SECURITY INVOKER +COMMENT 'Daily ETL pipeline for order processing' +AS BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + SET status = 'failed'; + SET rows_processed = 0; + END; + + -- Truncate and reload + EXECUTE IMMEDIATE 'TRUNCATE TABLE ' || target_schema || '.orders_daily'; + + EXECUTE IMMEDIATE + 'INSERT INTO ' || target_schema || '.orders_daily ' + || 'SELECT * FROM ' || source_schema || '.orders ' + || 'WHERE order_date = current_date()'; + + EXECUTE IMMEDIATE + 'SELECT COUNT(*) FROM ' || target_schema || '.orders_daily' + INTO rows_processed; + + SET status = 'success'; +END; +``` + +### CALL (Invoke a Procedure) + +**Syntax**: + +```sql +CALL procedure_name( [ argument [, ...] ] ); +CALL procedure_name( [ named_param => argument ] [, ...] ); +``` + +**Rules**: + +- Supports up to 64 levels of nesting +- For `IN` parameters: any expression castable to the parameter type, or `DEFAULT` +- For `OUT`/`INOUT` parameters: must be a session variable or local variable +- Arguments must match the data type of the parameter (use typed literals, e.g., `DATE'2025-01-01'`) +- Fewer arguments allowed if remaining parameters have `DEFAULT` values +- Not supported via ODBC + +**Example**: + +```sql +-- Positional invocation +DECLARE rows_out INT; +DECLARE status_out STRING; +CALL run_daily_etl('raw', 'silver', rows_out, status_out); +SELECT rows_out, status_out; + +-- Named parameter invocation +CALL run_daily_etl( + target_schema => 'silver', + source_schema => 'raw', + rows_processed => rows_out, + status => status_out +); +``` + +### DROP PROCEDURE + +**Syntax**: + +```sql +DROP PROCEDURE [ IF EXISTS ] procedure_name; +``` + +- Without `IF EXISTS`, dropping a non-existent procedure raises `ROUTINE_NOT_FOUND` +- Requires `MANAGE` privilege, ownership of the procedure, or ownership of the containing schema/catalog/metastore + +**Example**: + +```sql +DROP PROCEDURE IF EXISTS run_daily_etl; +``` + +### DESCRIBE PROCEDURE + +**Syntax**: + +```sql +{ DESC | DESCRIBE } PROCEDURE [ EXTENDED ] procedure_name; +``` + +- Basic: returns procedure name and parameter list +- `EXTENDED`: additionally returns owner, creation time, body, language, security type, determinism, data access, and configuration + +**Example**: + +```sql +DESCRIBE PROCEDURE EXTENDED run_daily_etl; +``` + +### SHOW PROCEDURES + +**Syntax**: + +```sql +SHOW PROCEDURES [ { FROM | IN } schema_name ]; +``` + +Returns columns: `catalog`, `namespace`, `schema`, `procedure_name`. + +**Example**: + +```sql +SHOW PROCEDURES IN my_catalog.my_schema; +``` + +--- + +## Recursive CTEs + +**Availability**: Databricks Runtime 17.0+ and DBSQL 2025.20+ + +Recursive CTEs enable self-referential queries for hierarchical data, graph traversal, and series generation. + +### WITH RECURSIVE Syntax + +```sql +WITH RECURSIVE cte_name [ ( column_name [, ...] ) ] + [ MAX RECURSION LEVEL max_level ] AS ( + base_case_query + UNION ALL + recursive_query + ) +SELECT ... FROM cte_name; +``` + +### Anchor and Recursive Members + +| Component | Description | +|-----------|-------------| +| **Anchor (base case)** | Initial query providing seed rows; must NOT reference the CTE name | +| **Recursive member** | References the CTE name; processes rows from the previous iteration | +| **UNION ALL** | Combines anchor and recursive results (required) | + +The recursive member reads rows produced by the previous iteration and generates new rows. Recursion terminates when the recursive member produces zero rows. + +### MAX RECURSION LEVEL + +```sql +WITH RECURSIVE cte_name MAX RECURSION LEVEL 200 AS (...) +``` + +| Setting | Default | Description | +|---------|---------|-------------| +| Max recursion depth | 100 | Exceeding raises `RECURSION_LEVEL_LIMIT_EXCEEDED` | +| Max result rows | 1,000,000 | Exceeding raises an error | +| `LIMIT ALL` | N/A | Suspends the row limit (Runtime 17.2+) | + +### Use Cases and Examples + +**Generate a number series**: + +```sql +WITH RECURSIVE numbers(n) AS ( + VALUES (1) + UNION ALL + SELECT n + 1 FROM numbers WHERE n < 100 +) +SELECT * FROM numbers; +``` + +**Organizational hierarchy traversal**: + +```sql +WITH RECURSIVE org_tree AS ( + -- Anchor: start from the CEO + SELECT employee_id, name, manager_id, name AS root_name, 0 AS depth + FROM employees + WHERE manager_id IS NULL + + UNION ALL + + -- Recursive: find direct reports + SELECT e.employee_id, e.name, e.manager_id, t.root_name, t.depth + 1 + FROM employees e + JOIN org_tree t ON e.manager_id = t.employee_id +) +SELECT * FROM org_tree ORDER BY depth, name; +``` + +**Graph traversal with cycle detection**: + +```sql +WITH RECURSIVE search_graph(f, t, label, path, cycle) AS ( + -- Anchor: all edges as starting paths + SELECT *, array(struct(g.f, g.t)), false + FROM graph g + + UNION ALL + + -- Recursive: extend paths, detect cycles + SELECT g.f, g.t, g.label, + sg.path || array(struct(g.f, g.t)), + array_contains(sg.path, struct(g.f, g.t)) + FROM graph g + JOIN search_graph sg ON g.f = sg.t + WHERE NOT sg.cycle +) +SELECT * FROM search_graph WHERE NOT cycle; +``` + +**String accumulation**: + +```sql +WITH RECURSIVE r(col) AS ( + SELECT 'a' + UNION ALL + SELECT col || char(ascii(substr(col, -1)) + 1) + FROM r + WHERE length(col) < 10 +) +SELECT * FROM r; +-- a, ab, abc, abcd, ..., abcdefghij +``` + +**Bill of Materials (BOM) explosion**: + +```sql +WITH RECURSIVE bom AS ( + -- Anchor: top-level product + SELECT part_id, component_id, quantity, 1 AS level + FROM bill_of_materials + WHERE part_id = 'PROD-001' + + UNION ALL + + -- Recursive: sub-components + SELECT b.part_id, b.component_id, b.quantity * bom.quantity, bom.level + 1 + FROM bill_of_materials b + JOIN bom ON b.part_id = bom.component_id +) +SELECT component_id, SUM(quantity) AS total_quantity, MAX(level) AS max_depth +FROM bom +GROUP BY component_id +ORDER BY total_quantity DESC; +``` + +### Limitations + +- Not supported in UPDATE, DELETE, or MERGE statements +- Step (recursive) queries cannot include correlated column references to the CTE name +- Random number generators may produce identical values across iterations +- Default row limit of 1,000,000 rows (use `LIMIT ALL` in Runtime 17.2+ to override) +- Default recursion depth of 100 (override with `MAX RECURSION LEVEL`) + +--- + +## Multi-Statement Transactions + +### Overview and Current Status + +Multi-statement transactions (MST) allow grouping multiple SQL statements into atomic units that either succeed completely or fail completely. + +| Feature | Status | Notes | +|---------|--------|-------| +| Single-table transactions | GA | Delta Lake default; every DML statement is atomic | +| Multi-statement transactions (SQL scripting) | Preview | `BEGIN ATOMIC...END` blocks | +| Multi-statement transactions (Python connector) | Preview | `connection.autocommit = False` pattern | +| Cross-table transactions | Preview | Atomic updates across multiple Delta tables | + +### SQL Scripting Atomic Blocks + +Use `BEGIN ATOMIC...END` to execute multiple statements as a single atomic unit: + +```sql +BEGIN ATOMIC + INSERT INTO customers (id, name) VALUES (1, 'Alice'); + INSERT INTO orders (id, customer_id, amount) VALUES (1, 1, 250.00); + INSERT INTO audit_log (action, ts) VALUES ('new_customer_order', current_timestamp()); +END; +``` + +If any statement fails, all changes are rolled back. + +> **Note:** Tables used in `BEGIN ATOMIC` blocks must have the `catalogManaged` table feature enabled. Create tables with `TBLPROPERTIES ('delta.feature.catalogManaged' = 'supported')`. Existing tables cannot be upgraded in place — they must be recreated with this property. + +### Python Connector Transaction API + +The Databricks SQL Connector for Python provides explicit transaction control: + +```python +from databricks import sql + +connection = sql.connect( + server_hostname="...", + http_path="...", + access_token="..." +) + +# Disable autocommit to start explicit transactions +connection.autocommit = False +cursor = connection.cursor() + +try: + cursor.execute("INSERT INTO customers VALUES (1, 'Alice')") + cursor.execute("INSERT INTO orders VALUES (1, 1, 100.00)") + cursor.execute("INSERT INTO shipments VALUES (1, 1, 'pending')") + connection.commit() # All three succeed atomically +except Exception: + connection.rollback() # All three discarded +finally: + connection.autocommit = True +``` + +**Key API methods**: + +| Method | Description | +|--------|-------------| +| `connection.autocommit = False` | Start explicit transaction mode | +| `connection.commit()` | Commit the current transaction | +| `connection.rollback()` | Discard all changes in the current transaction | +| `connection.get_transaction_isolation()` | Returns current isolation level | +| `connection.set_transaction_isolation(level)` | Sets isolation level | + +**Error handling**: + +- `sql.TransactionError` raised when committing without an active transaction +- Cannot change `autocommit` while a transaction is active +- `rollback()` is a safe no-op when no transaction is active + +### Isolation Levels + +Databricks uses **Snapshot Isolation** (mapped to `REPEATABLE_READ` in standard SQL terminology). + +| Level | Description | Default | +|-------|-------------|---------| +| `WriteSerializable` | Only writes are serializable; concurrent writes may reorder | Yes (table default) | +| `Serializable` | Both reads and writes are serializable; strictest isolation | No | +| `REPEATABLE_READ` | Snapshot isolation for connector-level transactions | Connector default | + +**Setting isolation at table level**: + +```sql +ALTER TABLE my_table +SET TBLPROPERTIES ('delta.isolationLevel' = 'Serializable'); +``` + +**Setting isolation in Python connector**: + +```python +from databricks.sql import TRANSACTION_ISOLATION_LEVEL_REPEATABLE_READ + +connection.set_transaction_isolation(TRANSACTION_ISOLATION_LEVEL_REPEATABLE_READ) +# Only REPEATABLE_READ is supported; others raise NotSupportedError +``` + +**Snapshot isolation behavior**: + +- **Repeatable reads**: Data read within a transaction remains consistent +- **Atomic commits**: Changes are invisible to other connections until committed +- **Write conflicts**: Concurrent writes to the same table cause conflicts +- **Cross-table writes**: Concurrent writes to different tables can succeed + +### Write Conflicts and Concurrency + +**Row-level concurrency** (Runtime 14.2+) reduces conflicts for tables with deletion vectors or liquid clustering: + +| Operation | WriteSerializable | Serializable | +|-----------|------------------|--------------| +| INSERT vs INSERT | No conflict | No conflict | +| UPDATE/DELETE/MERGE vs same | No conflict (different rows) | May conflict | +| OPTIMIZE vs concurrent DML | Conflict only with ZORDER BY | May conflict | + +**Common conflict exceptions**: + +| Exception | Cause | +|-----------|-------| +| `ConcurrentAppendException` | Concurrent append to the same partition | +| `ConcurrentDeleteReadException` | Concurrent delete of files being read | +| `MetadataChangedException` | Concurrent ALTER TABLE or schema change | +| `ProtocolChangedException` | Protocol version upgrade during write | + +### Best Practices + +1. **Keep transactions short** to minimize conflict windows +2. **Always wrap in try/except/finally** with rollback on errors +3. **Restore autocommit** in the `finally` block +4. **Use partition pruning** in MERGE conditions to reduce conflict scope +5. **Enable row-level concurrency** (deletion vectors + liquid clustering) for high-concurrency workloads +6. **Prefer single-statement MERGE** over multi-statement transactions when updating a single table +7. **Commit and restart** transactions to see changes made by other connections + +--- + +## Runtime Version Reference + +| Feature | Minimum Runtime | Status | +|---------|----------------|--------| +| SQL Scripting (compound statements, control flow) | 16.3 | GA | +| Stored Procedures (CREATE/CALL/DROP PROCEDURE) | 17.0 | Public Preview | +| Recursive CTEs (WITH RECURSIVE) | 17.0 / DBSQL 2025.20 | GA | +| Multi-variable DECLARE | 17.2 | GA | +| EXECUTE IMMEDIATE (basic) | 14.3 | GA | +| EXECUTE IMMEDIATE (expressions, nested) | 17.3 | GA | +| Recursive CTE LIMIT ALL | 17.2 | GA | +| Multi-statement Transactions | Varies | Preview | +| Row-level Concurrency | 14.2 | GA | + +--- + +## Quick Reference Card + +### SQL Scripting Skeleton + +```sql +BEGIN + -- 1. Declarations + DECLARE var1 INT DEFAULT 0; + DECLARE var2 STRING; + DECLARE my_error CONDITION FOR SQLSTATE '45000'; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + -- error handling logic + END; + + -- 2. Logic + IF var1 > 0 THEN + SET var2 = 'positive'; + ELSE + SET var2 = 'non-positive'; + END IF; + + -- 3. Output + VALUES (var1, var2); +END; +``` + +### Stored Procedure Skeleton + +```sql +CREATE OR REPLACE PROCEDURE my_schema.my_proc( + IN input_param STRING, + OUT output_param INT +) +LANGUAGE SQL +SQL SECURITY INVOKER +COMMENT 'Description of what this procedure does' +AS BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + SET output_param = -1; + + -- procedure body + SET output_param = (SELECT COUNT(*) FROM my_table WHERE col = input_param); +END; + +-- Invoke +DECLARE result INT; +CALL my_schema.my_proc('value', result); +SELECT result; +``` + +### Recursive CTE Skeleton + +```sql +WITH RECURSIVE cte_name (col1, col2) MAX RECURSION LEVEL 50 AS ( + -- Anchor + SELECT seed_col1, seed_col2 + FROM base_table + WHERE condition + + UNION ALL + + -- Recursive step + SELECT derived_col1, derived_col2 + FROM source_table s + JOIN cte_name c ON s.parent = c.col1 +) +SELECT * FROM cte_name; +``` diff --git a/.claude/skills/databricks-docs/SKILL.md b/.claude/skills/databricks-docs/SKILL.md index 98aeac9b..54bb157f 100644 --- a/.claude/skills/databricks-docs/SKILL.md +++ b/.claude/skills/databricks-docs/SKILL.md @@ -16,7 +16,7 @@ This is a **reference skill**, not an action skill. Use it to: - Find detailed information to inform how you use MCP tools - Discover features and capabilities you may not know about -**Always prefer using MCP tools for actions** (execute_sql, create_or_update_pipeline, etc.) and **load specific skills for workflows** (databricks-python-sdk, spark-declarative-pipelines, etc.). Use this skill when you need reference documentation. +**Always prefer using MCP tools for actions** (execute_sql, create_or_update_pipeline, etc.) and **load specific skills for workflows** (databricks-python-sdk, databricks-spark-declarative-pipelines, etc.). Use this skill when you need reference documentation. ## How to Use @@ -45,7 +45,7 @@ The llms.txt file is organized by category: **Scenario:** User wants to create a Delta Live Tables pipeline -1. Load `spark-declarative-pipelines` skill for workflow patterns +1. Load `databricks-spark-declarative-pipelines` skill for workflow patterns 2. Use this skill to fetch docs if you need clarification on specific DLT features 3. Use `create_or_update_pipeline` MCP tool to actually create the pipeline @@ -54,3 +54,11 @@ The llms.txt file is organized by category: 1. Fetch llms.txt to find relevant documentation 2. Read the specific docs to understand the feature 3. Determine which skill/tools apply, then use them + +## Related Skills + +- **[databricks-python-sdk](../databricks-python-sdk/SKILL.md)** - SDK patterns for programmatic Databricks access +- **[databricks-spark-declarative-pipelines](../databricks-spark-declarative-pipelines/SKILL.md)** - DLT / Lakeflow pipeline workflows +- **[databricks-unity-catalog](../databricks-unity-catalog/SKILL.md)** - Governance and catalog management +- **[databricks-model-serving](../databricks-model-serving/SKILL.md)** - Serving endpoints and model deployment +- **[databricks-mlflow-evaluation](../databricks-mlflow-evaluation/SKILL.md)** - MLflow 3 GenAI evaluation workflows diff --git a/.claude/skills/databricks-genie/SKILL.md b/.claude/skills/databricks-genie/SKILL.md index 4d5d12f5..3f08628c 100644 --- a/.claude/skills/databricks-genie/SKILL.md +++ b/.claude/skills/databricks-genie/SKILL.md @@ -109,8 +109,8 @@ Before creating a Genie Space: ### Creating Tables Use these skills in sequence: -1. `synthetic-data-generation` - Generate raw parquet files -2. `spark-declarative-pipelines` - Create bronze/silver/gold tables +1. `databricks-synthetic-data-generation` - Generate raw parquet files +2. `databricks-spark-declarative-pipelines` - Create bronze/silver/gold tables ## Common Issues @@ -119,3 +119,10 @@ Use these skills in sequence: | **No warehouse available** | Create a SQL warehouse or provide `warehouse_id` explicitly | | **Poor query generation** | Add instructions and sample questions that reference actual column names | | **Slow queries** | Ensure warehouse is running; use OPTIMIZE on tables | + +## Related Skills + +- **[databricks-agent-bricks](../databricks-agent-bricks/SKILL.md)** - Use Genie Spaces as agents inside Supervisor Agents +- **[databricks-synthetic-data-generation](../databricks-synthetic-data-generation/SKILL.md)** - Generate raw parquet data to populate tables for Genie +- **[databricks-spark-declarative-pipelines](../databricks-spark-declarative-pipelines/SKILL.md)** - Build bronze/silver/gold tables consumed by Genie Spaces +- **[databricks-unity-catalog](../databricks-unity-catalog/SKILL.md)** - Manage the catalogs, schemas, and tables Genie queries diff --git a/.claude/skills/databricks-genie/spaces.md b/.claude/skills/databricks-genie/spaces.md index 71c93985..8549d6bd 100644 --- a/.claude/skills/databricks-genie/spaces.md +++ b/.claude/skills/databricks-genie/spaces.md @@ -163,10 +163,10 @@ The tool finds the existing space by name and updates it. ## Example End-to-End Workflow -1. **Generate synthetic data** using `synthetic-data-generation` skill: +1. **Generate synthetic data** using `databricks-synthetic-data-generation` skill: - Creates parquet files in `/Volumes/catalog/schema/raw_data/` -2. **Create tables** using `spark-declarative-pipelines` skill: +2. **Create tables** using `databricks-spark-declarative-pipelines` skill: - Creates `catalog.schema.bronze_*` → `catalog.schema.silver_*` → `catalog.schema.gold_*` 3. **Inspect the tables**: diff --git a/.claude/skills/databricks-jobs/SKILL.md b/.claude/skills/databricks-jobs/SKILL.md index eae0754e..2f0f8c73 100644 --- a/.claude/skills/databricks-jobs/SKILL.md +++ b/.claude/skills/databricks-jobs/SKILL.md @@ -326,8 +326,8 @@ resources: ## Related Skills -- **[asset-bundles](../asset-bundles/SKILL.md)** - Deploy jobs via Databricks Asset Bundles -- **[spark-declarative-pipelines](../spark-declarative-pipelines/SKILL.md)** - Configure pipelines triggered by jobs +- **[databricks-asset-bundles](../databricks-asset-bundles/SKILL.md)** - Deploy jobs via Databricks Asset Bundles +- **[databricks-spark-declarative-pipelines](../databricks-spark-declarative-pipelines/SKILL.md)** - Configure pipelines triggered by jobs ## Resources diff --git a/.claude/skills/databricks-jobs/task-types.md b/.claude/skills/databricks-jobs/task-types.md index a78b9a32..c5b06fbe 100644 --- a/.claude/skills/databricks-jobs/task-types.md +++ b/.claude/skills/databricks-jobs/task-types.md @@ -618,7 +618,7 @@ Define reusable Python environments for serverless tasks with custom pip depende > **IMPORTANT:** The `client` field is **required** in the environment `spec`. It specifies the > base serverless environment version. Use `"4"` as the value. Without it, the API returns: > `"Either base environment or version must be provided for environment"`. -> The MCP `create_job` tool auto-injects `client: "4"` if omitted, but CLI/SDK calls require it explicitly. +> The MCP `manage_jobs` tool (action="create") auto-injects `client: "4"` if omitted, but CLI/SDK calls require it explicitly. ### DABs YAML diff --git a/.claude/skills/databricks-lakebase-autoscale/SKILL.md b/.claude/skills/databricks-lakebase-autoscale/SKILL.md new file mode 100644 index 00000000..50ba1df7 --- /dev/null +++ b/.claude/skills/databricks-lakebase-autoscale/SKILL.md @@ -0,0 +1,294 @@ +--- +name: databricks-lakebase-autoscale +description: "Patterns and best practices for using Lakebase Autoscaling (next-gen managed PostgreSQL) with autoscaling, branching, scale-to-zero, and instant restore." +--- + +# Lakebase Autoscaling + +Patterns and best practices for using Lakebase Autoscaling, the next-generation managed PostgreSQL on Databricks with autoscaling compute, branching, scale-to-zero, and instant restore. + +## When to Use + +Use this skill when: +- Building applications that need a PostgreSQL database with autoscaling compute +- Working with database branching for dev/test/staging workflows +- Adding persistent state to applications with scale-to-zero cost savings +- Implementing reverse ETL from Delta Lake to an operational database via synced tables +- Managing Lakebase Autoscaling projects, branches, computes, or credentials + +## Overview + +Lakebase Autoscaling is Databricks' next-generation managed PostgreSQL service for OLTP workloads. It provides autoscaling compute, Git-like branching, scale-to-zero, and instant point-in-time restore. + +| Feature | Description | +|---------|-------------| +| **Autoscaling Compute** | 0.5-112 CU with 2 GB RAM per CU; scales dynamically based on load | +| **Scale-to-Zero** | Compute suspends after configurable inactivity timeout | +| **Branching** | Create isolated database environments (like Git branches) for dev/test | +| **Instant Restore** | Point-in-time restore from any moment within the configured window (up to 35 days) | +| **OAuth Authentication** | Token-based auth via Databricks SDK (1-hour expiry) | +| **Reverse ETL** | Sync data from Delta tables to PostgreSQL via synced tables | + +**Available Regions (AWS):** us-east-1, us-east-2, eu-central-1, eu-west-1, eu-west-2, ap-south-1, ap-southeast-1, ap-southeast-2 + +**Available Regions (Azure Beta):** eastus2, westeurope, westus + +## Project Hierarchy + +Understanding the hierarchy is essential for working with Lakebase Autoscaling: + +``` +Project (top-level container) + └── Branch(es) (isolated database environments) + ├── Compute (primary R/W endpoint) + ├── Read Replica(s) (optional, read-only) + ├── Role(s) (Postgres roles) + └── Database(s) (Postgres databases) + └── Schema(s) +``` + +| Object | Description | +|--------|-------------| +| **Project** | Top-level container. Created via `w.postgres.create_project()`. | +| **Branch** | Isolated database environment with copy-on-write storage. Default branch is `production`. | +| **Compute** | Postgres server powering a branch. Configurable CU sizing and autoscaling. | +| **Database** | Standard Postgres database within a branch. Default is `databricks_postgres`. | + +## Quick Start + +Create a project and connect: + +```python +from databricks.sdk import WorkspaceClient +from databricks.sdk.service.postgres import Project, ProjectSpec + +w = WorkspaceClient() + +# Create a project (long-running operation) +operation = w.postgres.create_project( + project=Project( + spec=ProjectSpec( + display_name="My Application", + pg_version="17" + ) + ), + project_id="my-app" +) +result = operation.wait() +print(f"Created project: {result.name}") +``` + +## Common Patterns + +### Generate OAuth Token + +```python +from databricks.sdk import WorkspaceClient + +w = WorkspaceClient() + +# Generate database credential for connecting (optionally scoped to an endpoint) +cred = w.postgres.generate_database_credential( + endpoint="projects/my-app/branches/production/endpoints/ep-primary" +) +token = cred.token # Use as password in connection string +# Token expires after 1 hour +``` + +### Connect from Notebook + +```python +import psycopg +from databricks.sdk import WorkspaceClient + +w = WorkspaceClient() + +# Get endpoint details +endpoint = w.postgres.get_endpoint( + name="projects/my-app/branches/production/endpoints/ep-primary" +) +host = endpoint.status.hosts.host + +# Generate token (scoped to endpoint) +cred = w.postgres.generate_database_credential( + endpoint="projects/my-app/branches/production/endpoints/ep-primary" +) + +# Connect using psycopg3 +conn_string = ( + f"host={host} " + f"dbname=databricks_postgres " + f"user={w.current_user.me().user_name} " + f"password={cred.token} " + f"sslmode=require" +) +with psycopg.connect(conn_string) as conn: + with conn.cursor() as cur: + cur.execute("SELECT version()") + print(cur.fetchone()) +``` + +### Create a Branch for Development + +```python +from databricks.sdk.service.postgres import Branch, BranchSpec, Duration + +# Create a dev branch with 7-day expiration +branch = w.postgres.create_branch( + parent="projects/my-app", + branch=Branch( + spec=BranchSpec( + source_branch="projects/my-app/branches/production", + ttl=Duration(seconds=604800) # 7 days + ) + ), + branch_id="development" +).wait() +print(f"Branch created: {branch.name}") +``` + +### Resize Compute (Autoscaling) + +```python +from databricks.sdk.service.postgres import Endpoint, EndpointSpec, FieldMask + +# Update compute to autoscale between 2-8 CU +w.postgres.update_endpoint( + name="projects/my-app/branches/production/endpoints/ep-primary", + endpoint=Endpoint( + name="projects/my-app/branches/production/endpoints/ep-primary", + spec=EndpointSpec( + autoscaling_limit_min_cu=2.0, + autoscaling_limit_max_cu=8.0 + ) + ), + update_mask=FieldMask(field_mask=[ + "spec.autoscaling_limit_min_cu", + "spec.autoscaling_limit_max_cu" + ]) +).wait() +``` + +## MCP Tools + +The following MCP tools are available for managing Lakebase infrastructure. Use `type="autoscale"` for Lakebase Autoscaling. + +### Database (Project) Management + +| Tool | Description | +|------|-------------| +| `create_or_update_lakebase_database` | Create or update a database. Finds by name, creates if new, updates if existing. Use `type="autoscale"`, `display_name`, `pg_version` params. A new project auto-creates a production branch, default compute, and databricks_postgres database. | +| `get_lakebase_database` | Get database details (including branches and endpoints) or list all. Pass `name` to get one, omit to list all. Use `type="autoscale"` to filter. | +| `delete_lakebase_database` | Delete a project and all its branches, computes, and data. Use `type="autoscale"`. | + +### Branch Management + +| Tool | Description | +|------|-------------| +| `create_or_update_lakebase_branch` | Create or update a branch with its compute endpoint. Params: `project_name`, `branch_id`, `source_branch`, `ttl_seconds`, `is_protected`, plus compute params (`autoscaling_limit_min_cu`, `autoscaling_limit_max_cu`, `scale_to_zero_seconds`). | +| `delete_lakebase_branch` | Delete a branch and its compute endpoints. | + +### Credentials + +| Tool | Description | +|------|-------------| +| `generate_lakebase_credential` | Generate OAuth token for PostgreSQL connections (1-hour expiry). Pass `endpoint` resource name for autoscale. | + +## Reference Files + +- [projects.md](projects.md) - Project management patterns and settings +- [branches.md](branches.md) - Branching workflows, protection, and expiration +- [computes.md](computes.md) - Compute sizing, autoscaling, and scale-to-zero +- [connection-patterns.md](connection-patterns.md) - Connection patterns for different use cases +- [reverse-etl.md](reverse-etl.md) - Synced tables from Delta Lake to Lakebase + +## CLI Quick Reference + +```bash +# Create a project +databricks postgres create-project \ + --project-id my-app \ + --json '{"spec": {"display_name": "My App", "pg_version": "17"}}' + +# List projects +databricks postgres list-projects + +# Get project details +databricks postgres get-project projects/my-app + +# Create a branch +databricks postgres create-branch projects/my-app development \ + --json '{"spec": {"source_branch": "projects/my-app/branches/production", "no_expiry": true}}' + +# List branches +databricks postgres list-branches projects/my-app + +# Get endpoint details +databricks postgres get-endpoint projects/my-app/branches/production/endpoints/ep-primary + +# Delete a project +databricks postgres delete-project projects/my-app +``` + +## Key Differences from Lakebase Provisioned + +| Aspect | Provisioned | Autoscaling | +|--------|-------------|-------------| +| SDK module | `w.database` | `w.postgres` | +| Top-level resource | Instance | Project | +| Capacity | CU_1, CU_2, CU_4, CU_8 (16 GB/CU) | 0.5-112 CU (2 GB/CU) | +| Branching | Not supported | Full branching support | +| Scale-to-zero | Not supported | Configurable timeout | +| Operations | Synchronous | Long-running operations (LRO) | +| Read replicas | Readable secondaries | Dedicated read-only endpoints | + +## Common Issues + +| Issue | Solution | +|-------|----------| +| **Token expired during long query** | Implement token refresh loop; tokens expire after 1 hour | +| **Connection refused after scale-to-zero** | Compute wakes automatically on connection; reactivation takes a few hundred ms; implement retry logic | +| **DNS resolution fails on macOS** | Use `dig` command to resolve hostname, pass `hostaddr` to psycopg | +| **Branch deletion blocked** | Delete child branches first; cannot delete branches with children | +| **Autoscaling range too wide** | Max - min cannot exceed 8 CU (e.g., 8-16 CU is valid, 0.5-32 CU is not) | +| **SSL required error** | Always use `sslmode=require` in connection string | +| **Update mask required** | All update operations require an `update_mask` specifying fields to modify | +| **Connection closed after 24h idle** | All connections have a 24-hour idle timeout and 3-day max lifetime; implement retry logic | + +## Current Limitations + +These features are NOT yet supported in Lakebase Autoscaling: +- High availability with readable secondaries (use read replicas instead) +- Databricks Apps UI integration (Apps can connect manually via credentials) +- Feature Store integration +- Stateful AI agents (LangChain memory) +- Postgres-to-Delta sync (only Delta-to-Postgres reverse ETL) +- Custom billing tags and serverless budget policies +- Direct migration from Lakebase Provisioned (use pg_dump/pg_restore or reverse ETL) + +## SDK Version Requirements + +- **Databricks SDK for Python**: >= 0.81.0 (for `w.postgres` module) +- **psycopg**: 3.x (supports `hostaddr` parameter for DNS workaround) +- **SQLAlchemy**: 2.x with `postgresql+psycopg` driver + +```python +%pip install -U "databricks-sdk>=0.81.0" "psycopg[binary]>=3.0" sqlalchemy +``` + +## Notes + +- **Compute Units** in Autoscaling provide ~2 GB RAM each (vs 16 GB in Provisioned). +- **Resource naming** follows hierarchical paths: `projects/{id}/branches/{id}/endpoints/{id}`. +- All create/update/delete operations are **long-running** -- use `.wait()` in the SDK. +- Tokens are short-lived (1 hour) -- production apps MUST implement token refresh. +- **Postgres versions** 16 and 17 are supported. + +## Related Skills + +- **[databricks-lakebase-provisioned](../databricks-lakebase-provisioned/SKILL.md)** - fixed-capacity managed PostgreSQL (predecessor) +- **[databricks-app-apx](../databricks-app-apx/SKILL.md)** - full-stack apps that can use Lakebase for persistence +- **[databricks-app-python](../databricks-app-python/SKILL.md)** - Python apps with Lakebase backend +- **[databricks-python-sdk](../databricks-python-sdk/SKILL.md)** - SDK used for project management and token generation +- **[databricks-asset-bundles](../databricks-asset-bundles/SKILL.md)** - deploying apps with Lakebase resources +- **[databricks-jobs](../databricks-jobs/SKILL.md)** - scheduling reverse ETL sync jobs diff --git a/.claude/skills/databricks-lakebase-autoscale/branches.md b/.claude/skills/databricks-lakebase-autoscale/branches.md new file mode 100644 index 00000000..f44f7234 --- /dev/null +++ b/.claude/skills/databricks-lakebase-autoscale/branches.md @@ -0,0 +1,212 @@ +# Lakebase Autoscaling Branches + +## Overview + +Branches in Lakebase Autoscaling are isolated database environments that share storage with their parent through copy-on-write. They enable Git-like workflows for databases: create isolated dev/test environments, test schema changes safely, and recover from mistakes. + +## Branch Types + +| Option | Description | Use Case | +|--------|-------------|----------| +| **Current data** | Branch from latest state of parent | Development, testing with current data | +| **Past data** | Branch from a specific point in time | Point-in-time recovery, historical analysis | + +## Creating a Branch + +### With Expiration (TTL) + +```python +from databricks.sdk import WorkspaceClient +from databricks.sdk.service.postgres import Branch, BranchSpec, Duration + +w = WorkspaceClient() + +# Create branch with 7-day expiration +result = w.postgres.create_branch( + parent="projects/my-app", + branch=Branch( + spec=BranchSpec( + source_branch="projects/my-app/branches/production", + ttl=Duration(seconds=604800) # 7 days + ) + ), + branch_id="development" +).wait() + +print(f"Branch created: {result.name}") +print(f"Expires: {result.status.expire_time}") +``` + +### Permanent Branch (No Expiration) + +```python +result = w.postgres.create_branch( + parent="projects/my-app", + branch=Branch( + spec=BranchSpec( + source_branch="projects/my-app/branches/production", + no_expiry=True + ) + ), + branch_id="staging" +).wait() +``` + +### CLI + +```bash +# With TTL +databricks postgres create-branch projects/my-app development \ + --json '{ + "spec": { + "source_branch": "projects/my-app/branches/production", + "ttl": "604800s" + } + }' + +# Permanent +databricks postgres create-branch projects/my-app staging \ + --json '{ + "spec": { + "source_branch": "projects/my-app/branches/production", + "no_expiry": true + } + }' +``` + +## Getting Branch Details + +```python +branch = w.postgres.get_branch( + name="projects/my-app/branches/development" +) + +print(f"Branch: {branch.name}") +print(f"Protected: {branch.status.is_protected}") +print(f"Default: {branch.status.default}") +print(f"State: {branch.status.current_state}") +print(f"Size: {branch.status.logical_size_bytes} bytes") +``` + +## Listing Branches + +```python +branches = list(w.postgres.list_branches( + parent="projects/my-app" +)) + +for branch in branches: + print(f"Branch: {branch.name}") + print(f" Default: {branch.status.default}") + print(f" Protected: {branch.status.is_protected}") +``` + +## Protecting a Branch + +Protected branches cannot be deleted, reset, or archived. + +```python +from databricks.sdk.service.postgres import Branch, BranchSpec, FieldMask + +w.postgres.update_branch( + name="projects/my-app/branches/production", + branch=Branch( + name="projects/my-app/branches/production", + spec=BranchSpec(is_protected=True) + ), + update_mask=FieldMask(field_mask=["spec.is_protected"]) +).wait() +``` + +To remove protection: + +```python +w.postgres.update_branch( + name="projects/my-app/branches/production", + branch=Branch( + name="projects/my-app/branches/production", + spec=BranchSpec(is_protected=False) + ), + update_mask=FieldMask(field_mask=["spec.is_protected"]) +).wait() +``` + +## Updating Branch Expiration + +```python +# Extend to 14 days +w.postgres.update_branch( + name="projects/my-app/branches/development", + branch=Branch( + name="projects/my-app/branches/development", + spec=BranchSpec( + is_protected=False, + ttl=Duration(seconds=1209600) # 14 days + ) + ), + update_mask=FieldMask(field_mask=["spec.is_protected", "spec.expiration"]) +).wait() + +# Remove expiration +w.postgres.update_branch( + name="projects/my-app/branches/development", + branch=Branch( + name="projects/my-app/branches/development", + spec=BranchSpec(no_expiry=True) + ), + update_mask=FieldMask(field_mask=["spec.expiration"]) +).wait() +``` + +## Resetting a Branch from Parent + +Reset completely replaces a branch's data and schema with the latest from its parent. Local changes are lost. + +```python +w.postgres.reset_branch( + name="projects/my-app/branches/development" +).wait() +``` + +**Constraints:** +- Root branches (like `production`) cannot be reset (no parent) +- Branches with children cannot be reset (delete children first) +- Connections are temporarily interrupted during reset + +## Deleting a Branch + +```python +w.postgres.delete_branch( + name="projects/my-app/branches/development" +).wait() +``` + +**Constraints:** +- Cannot delete branches with child branches (delete children first) +- Cannot delete protected branches (remove protection first) +- Cannot delete the default branch + +## Branch Expiration + +Branch expiration sets an automatic deletion timestamp. Useful for: +- **CI/CD environments**: 2-4 hours +- **Demos**: 24-48 hours +- **Feature development**: 1-7 days +- **Long-term testing**: up to 30 days + +**Maximum expiration period:** 30 days from current time. + +### Expiration Restrictions + +- Cannot expire protected branches +- Cannot expire default branches +- Cannot expire branches that have children +- When a branch expires, all compute resources are also deleted + +## Best Practices + +1. **Use TTL for ephemeral branches**: Set expiration for dev/test branches to avoid accumulation +2. **Protect production branches**: Prevent accidental deletion or reset +3. **Reset instead of recreate**: Use reset from parent when you need fresh data without new branch overhead +4. **Schema diff before merge**: Compare schemas between branches before applying changes to production +5. **Monitor unarchived limit**: Only 10 unarchived branches are allowed per project diff --git a/.claude/skills/databricks-lakebase-autoscale/computes.md b/.claude/skills/databricks-lakebase-autoscale/computes.md new file mode 100644 index 00000000..0f53d50c --- /dev/null +++ b/.claude/skills/databricks-lakebase-autoscale/computes.md @@ -0,0 +1,208 @@ +# Lakebase Autoscaling Computes + +## Overview + +A compute is a virtualized service that runs Postgres for a branch. Each branch has one primary read-write compute and can have optional read replicas. Computes support autoscaling, scale-to-zero, and granular sizing from 0.5 to 112 CU. + +## Compute Sizing + +Each Compute Unit (CU) allocates approximately 2 GB of RAM. + +### Available Sizes + +| Category | Range | Notes | +|----------|-------|-------| +| **Autoscale computes** | 0.5-32 CU | Dynamic scaling within range (max-min <= 8 CU) | +| **Large fixed-size** | 36-112 CU | Fixed size, no autoscaling | + +### Representative Sizes + +| Compute Units | RAM | Max Connections | +|--------------|-----|-----------------| +| 0.5 CU | ~1 GB | 104 | +| 1 CU | ~2 GB | 209 | +| 4 CU | ~8 GB | 839 | +| 8 CU | ~16 GB | 1,678 | +| 16 CU | ~32 GB | 3,357 | +| 32 CU | ~64 GB | 4,000 | +| 64 CU | ~128 GB | 4,000 | +| 112 CU | ~224 GB | 4,000 | + +**Note:** Lakebase Provisioned used ~16 GB per CU. Autoscaling uses ~2 GB per CU for more granular scaling. + +## Creating a Compute + +```python +from databricks.sdk import WorkspaceClient +from databricks.sdk.service.postgres import Endpoint, EndpointSpec, EndpointType + +w = WorkspaceClient() + +# Create a read-write compute endpoint +result = w.postgres.create_endpoint( + parent="projects/my-app/branches/production", + endpoint=Endpoint( + spec=EndpointSpec( + endpoint_type=EndpointType.ENDPOINT_TYPE_READ_WRITE, + autoscaling_limit_min_cu=0.5, + autoscaling_limit_max_cu=4.0 + ) + ), + endpoint_id="my-compute" +).wait() + +print(f"Endpoint created: {result.name}") +print(f"Host: {result.status.hosts.host}") +``` + +### CLI + +```bash +databricks postgres create-endpoint \ + projects/my-app/branches/production my-compute \ + --json '{ + "spec": { + "endpoint_type": "ENDPOINT_TYPE_READ_WRITE", + "autoscaling_limit_min_cu": 0.5, + "autoscaling_limit_max_cu": 4.0 + } + }' +``` + +**Important:** Each branch can have only one read-write compute. + +## Getting Compute Details + +```python +endpoint = w.postgres.get_endpoint( + name="projects/my-app/branches/production/endpoints/my-compute" +) + +print(f"Endpoint: {endpoint.name}") +print(f"Type: {endpoint.status.endpoint_type}") +print(f"State: {endpoint.status.current_state}") +print(f"Host: {endpoint.status.hosts.host}") +print(f"Min CU: {endpoint.status.autoscaling_limit_min_cu}") +print(f"Max CU: {endpoint.status.autoscaling_limit_max_cu}") +``` + +## Listing Computes + +```python +endpoints = list(w.postgres.list_endpoints( + parent="projects/my-app/branches/production" +)) + +for ep in endpoints: + print(f"Endpoint: {ep.name}") + print(f" Type: {ep.status.endpoint_type}") + print(f" CU Range: {ep.status.autoscaling_limit_min_cu}-{ep.status.autoscaling_limit_max_cu}") +``` + +## Resizing a Compute + +Use `update_mask` to specify which fields to update: + +```python +from databricks.sdk.service.postgres import Endpoint, EndpointSpec, FieldMask + +# Update min and max CU +w.postgres.update_endpoint( + name="projects/my-app/branches/production/endpoints/my-compute", + endpoint=Endpoint( + name="projects/my-app/branches/production/endpoints/my-compute", + spec=EndpointSpec( + autoscaling_limit_min_cu=2.0, + autoscaling_limit_max_cu=8.0 + ) + ), + update_mask=FieldMask(field_mask=[ + "spec.autoscaling_limit_min_cu", + "spec.autoscaling_limit_max_cu" + ]) +).wait() +``` + +### CLI + +```bash +# Update single field +databricks postgres update-endpoint \ + projects/my-app/branches/production/endpoints/my-compute \ + spec.autoscaling_limit_max_cu \ + --json '{"spec": {"autoscaling_limit_max_cu": 8.0}}' + +# Update multiple fields +databricks postgres update-endpoint \ + projects/my-app/branches/production/endpoints/my-compute \ + "spec.autoscaling_limit_min_cu,spec.autoscaling_limit_max_cu" \ + --json '{"spec": {"autoscaling_limit_min_cu": 2.0, "autoscaling_limit_max_cu": 8.0}}' +``` + +## Deleting a Compute + +```python +w.postgres.delete_endpoint( + name="projects/my-app/branches/production/endpoints/my-compute" +).wait() +``` + +## Autoscaling + +Autoscaling dynamically adjusts compute resources based on workload demand. + +### Configuration + +- **Range:** 0.5-32 CU +- **Constraint:** Max - Min cannot exceed 8 CU +- **Valid examples:** 4-8 CU, 8-16 CU, 16-24 CU +- **Invalid example:** 0.5-32 CU (range of 31.5 CU) + +### Best Practices + +- Set minimum CU large enough to cache your working set in memory +- Performance may be degraded until compute scales up and caches data +- Connection limits are based on the maximum CU in the range + +## Scale-to-Zero + +Automatically suspends compute after a period of inactivity. + +| Setting | Description | +|---------|-------------| +| **Enabled** | Compute suspends after inactivity timeout (saves cost) | +| **Disabled** | Always-active compute (eliminates wake-up latency) | + +**Default behavior:** +- `production` branch: Scale-to-zero **disabled** (always active) +- Other branches: Scale-to-zero can be configured + +**Default inactivity timeout:** 5 minutes +**Minimum inactivity timeout:** 60 seconds + +### Wake-up Behavior + +When a connection arrives on a suspended compute: +1. Compute starts automatically (reactivation takes a few hundred milliseconds) +2. The connection request is handled transparently once active +3. Compute restarts at minimum autoscaling size (if autoscaling enabled) +4. Applications should implement connection retry logic for the brief reactivation period + +### Session Context After Reactivation + +When a compute suspends and reactivates, session context is **reset**: +- In-memory statistics and cache contents are cleared +- Temporary tables and prepared statements are lost +- Session-specific configuration settings reset +- Connection pools and active transactions are terminated + +If your application requires persistent session data, consider disabling scale-to-zero. + +## Sizing Guidance + +| Factor | Recommendation | +|--------|---------------| +| Query complexity | Complex analytical queries benefit from larger computes | +| Concurrent connections | More connections need more CPU and memory | +| Data volume | Larger datasets may need more memory for performance | +| Response time | Critical apps may require larger computes | diff --git a/.claude/skills/databricks-lakebase-autoscale/connection-patterns.md b/.claude/skills/databricks-lakebase-autoscale/connection-patterns.md new file mode 100644 index 00000000..398862b3 --- /dev/null +++ b/.claude/skills/databricks-lakebase-autoscale/connection-patterns.md @@ -0,0 +1,304 @@ +# Lakebase Autoscaling Connection Patterns + +## Overview + +This document covers different connection patterns for Lakebase Autoscaling, from simple scripts to production applications with token refresh. + +## Authentication Methods + +Lakebase Autoscaling supports two authentication methods: + +| Method | Token Lifetime | Best For | +|--------|---------------|----------| +| **OAuth tokens** | 1 hour (must refresh) | Interactive sessions, workspace-integrated apps | +| **Native Postgres passwords** | No expiry | Long-running processes, tools without token rotation | + +**Connection timeouts (both methods):** +- **24-hour idle timeout**: Connections with no activity for 24 hours are automatically closed +- **3-day maximum connection life**: Connections alive for more than 3 days may be closed + +Design your applications to handle connection timeouts with retry logic. + +## Connection Methods + +### 1. Direct psycopg Connection (Simple Scripts) + +For one-off scripts or notebooks: + +```python +import psycopg +from databricks.sdk import WorkspaceClient + +def get_connection(project_id: str, branch_id: str = "production", + endpoint_id: str = None, database_name: str = "databricks_postgres"): + """Get a database connection with fresh OAuth token.""" + w = WorkspaceClient() + + # Get endpoint details to find the host + if endpoint_id: + ep_name = f"projects/{project_id}/branches/{branch_id}/endpoints/{endpoint_id}" + else: + # List endpoints and pick the primary R/W one + endpoints = list(w.postgres.list_endpoints( + parent=f"projects/{project_id}/branches/{branch_id}" + )) + ep_name = endpoints[0].name + + endpoint = w.postgres.get_endpoint(name=ep_name) + host = endpoint.status.hosts.host + + # Generate OAuth token (valid for 1 hour) + cred = w.postgres.generate_database_credential(endpoint=ep_name) + + # Build connection string + conn_string = ( + f"host={host} " + f"dbname={database_name} " + f"user={w.current_user.me().user_name} " + f"password={cred.token} " + f"sslmode=require" + ) + + return psycopg.connect(conn_string) + +# Usage +with get_connection("my-app") as conn: + with conn.cursor() as cur: + cur.execute("SELECT NOW()") + print(cur.fetchone()) +``` + +### 2. Connection Pool with Token Refresh (Production) + +For long-running applications that need connection pooling: + +```python +import asyncio +import uuid +from contextlib import asynccontextmanager +from typing import AsyncGenerator, Optional + +from sqlalchemy import event +from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker +from databricks.sdk import WorkspaceClient + + +class LakebaseAutoscaleConnectionManager: + """Manages Lakebase Autoscaling connections with automatic token refresh.""" + + def __init__( + self, + project_id: str, + branch_id: str = "production", + database_name: str = "databricks_postgres", + pool_size: int = 5, + max_overflow: int = 10, + token_refresh_seconds: int = 3000 # 50 minutes + ): + self.project_id = project_id + self.branch_id = branch_id + self.database_name = database_name + self.pool_size = pool_size + self.max_overflow = max_overflow + self.token_refresh_seconds = token_refresh_seconds + + self._current_token: Optional[str] = None + self._refresh_task: Optional[asyncio.Task] = None + self._engine = None + self._session_maker = None + + def _generate_token(self) -> str: + """Generate fresh OAuth token.""" + w = WorkspaceClient() + # Get primary endpoint name for token scoping + endpoints = list(w.postgres.list_endpoints( + parent=f"projects/{self.project_id}/branches/{self.branch_id}" + )) + endpoint_name = endpoints[0].name if endpoints else None + cred = w.postgres.generate_database_credential(endpoint=endpoint_name) + return cred.token + + def _get_host(self) -> str: + """Get the connection host from the primary endpoint.""" + w = WorkspaceClient() + endpoints = list(w.postgres.list_endpoints( + parent=f"projects/{self.project_id}/branches/{self.branch_id}" + )) + if not endpoints: + raise RuntimeError( + f"No endpoints found for projects/{self.project_id}/branches/{self.branch_id}" + ) + endpoint = w.postgres.get_endpoint(name=endpoints[0].name) + return endpoint.status.hosts.host + + async def _refresh_loop(self): + """Background task to refresh token periodically.""" + while True: + await asyncio.sleep(self.token_refresh_seconds) + try: + self._current_token = await asyncio.to_thread(self._generate_token) + except Exception as e: + print(f"Token refresh failed: {e}") + + def initialize(self): + """Initialize database engine and start token refresh.""" + w = WorkspaceClient() + + # Get host info + host = self._get_host() + username = w.current_user.me().user_name + + # Generate initial token + self._current_token = self._generate_token() + + # Create engine (password injected via event) + url = ( + f"postgresql+psycopg://{username}@" + f"{host}:5432/{self.database_name}" + ) + + self._engine = create_async_engine( + url, + pool_size=self.pool_size, + max_overflow=self.max_overflow, + pool_recycle=3600, + connect_args={"sslmode": "require"} + ) + + # Inject token on connect + @event.listens_for(self._engine.sync_engine, "do_connect") + def inject_token(dialect, conn_rec, cargs, cparams): + cparams["password"] = self._current_token + + self._session_maker = async_sessionmaker( + self._engine, + class_=AsyncSession, + expire_on_commit=False + ) + + def start_refresh(self): + """Start background token refresh task.""" + if not self._refresh_task: + self._refresh_task = asyncio.create_task(self._refresh_loop()) + + async def stop_refresh(self): + """Stop token refresh task.""" + if self._refresh_task: + self._refresh_task.cancel() + try: + await self._refresh_task + except asyncio.CancelledError: + pass + self._refresh_task = None + + @asynccontextmanager + async def session(self) -> AsyncGenerator[AsyncSession, None]: + """Get a database session.""" + async with self._session_maker() as session: + yield session + + async def close(self): + """Close all connections.""" + await self.stop_refresh() + if self._engine: + await self._engine.dispose() + + +# Usage in FastAPI +from fastapi import FastAPI + +app = FastAPI() +db_manager = LakebaseAutoscaleConnectionManager("my-app", "production", "my_database") + +@app.on_event("startup") +async def startup(): + db_manager.initialize() + db_manager.start_refresh() + +@app.on_event("shutdown") +async def shutdown(): + await db_manager.close() + +@app.get("/data") +async def get_data(): + async with db_manager.session() as session: + result = await session.execute("SELECT * FROM my_table") + return result.fetchall() +``` + +### 3. Static URL Mode (Local Development) + +For local development, use a static connection URL: + +```python +import os +from sqlalchemy.ext.asyncio import create_async_engine + +# Set environment variable with full connection URL +# LAKEBASE_PG_URL=postgresql://user:password@host:5432/database + +def get_database_url() -> str: + """Get database URL from environment.""" + url = os.environ.get("LAKEBASE_PG_URL") + if url and url.startswith("postgresql://"): + # Convert to psycopg3 async driver + url = url.replace("postgresql://", "postgresql+psycopg://", 1) + return url + +engine = create_async_engine( + get_database_url(), + pool_size=5, + connect_args={"sslmode": "require"} +) +``` + +### 4. DNS Resolution Workaround (macOS) + +Python's `socket.getaddrinfo()` fails with long hostnames on macOS. Use `dig` as fallback: + +```python +import subprocess +import socket + +def resolve_hostname(hostname: str) -> str: + """Resolve hostname using dig command (macOS workaround).""" + try: + return socket.gethostbyname(hostname) + except socket.gaierror: + pass + + try: + result = subprocess.run( + ["dig", "+short", hostname], + capture_output=True, text=True, timeout=5 + ) + ips = result.stdout.strip().split('\n') + for ip in ips: + if ip and not ip.startswith(';'): + return ip + except Exception: + pass + + raise RuntimeError(f"Could not resolve hostname: {hostname}") + +# Use with psycopg +conn_params = { + "host": hostname, # For TLS SNI + "hostaddr": resolve_hostname(hostname), # Actual IP + "dbname": database_name, + "user": username, + "password": token, + "sslmode": "require" +} +conn = psycopg.connect(**conn_params) +``` + +## Best Practices + +1. **Always use SSL**: Set `sslmode=require` in all connections +2. **Implement token refresh**: Tokens expire after 1 hour; refresh at 50 minutes +3. **Use connection pooling**: Avoid creating new connections per request +4. **Handle DNS issues on macOS**: Use the `hostaddr` workaround if needed +5. **Close connections properly**: Use context managers or explicit cleanup +6. **Handle scale-to-zero wake-up**: First connection after idle may take 2-5 seconds +7. **Log token refresh events**: Helps debug authentication issues diff --git a/.claude/skills/databricks-lakebase-autoscale/projects.md b/.claude/skills/databricks-lakebase-autoscale/projects.md new file mode 100644 index 00000000..659207a4 --- /dev/null +++ b/.claude/skills/databricks-lakebase-autoscale/projects.md @@ -0,0 +1,204 @@ +# Lakebase Autoscaling Projects + +## Overview + +A project is the top-level container for Lakebase Autoscaling resources, including branches, computes, databases, and roles. Each project is isolated and contains its own Postgres version, compute defaults, and restore window settings. + +## Project Structure + +``` +Project + └── Branches (production, development, staging, etc.) + ├── Computes (R/W compute, read replicas) + ├── Roles (Postgres roles) + └── Databases (Postgres databases) +``` + +When a project is created, it includes by default: +- A `production` branch (the default branch) +- A primary read-write compute (8-32 CU, autoscaling enabled, scale-to-zero disabled) +- A `databricks_postgres` database +- A Postgres role for the creating user's Databricks identity + +## Resource Naming + +Projects follow a hierarchical naming convention: +``` +projects/{project_id} +``` + +**Resource ID requirements:** +- 1-63 characters long +- Lowercase letters, digits, and hyphens only +- Cannot start or end with a hyphen +- Cannot be changed after creation + +## Creating a Project + +### Python SDK + +```python +from databricks.sdk import WorkspaceClient +from databricks.sdk.service.postgres import Project, ProjectSpec + +w = WorkspaceClient() + +# Create a project (long-running operation) +operation = w.postgres.create_project( + project=Project( + spec=ProjectSpec( + display_name="My Application", + pg_version="17" + ) + ), + project_id="my-app" +) + +# Wait for completion +result = operation.wait() +print(f"Created project: {result.name}") +print(f"Display name: {result.status.display_name}") +print(f"Postgres version: {result.status.pg_version}") +``` + +### CLI + +```bash +databricks postgres create-project \ + --project-id my-app \ + --json '{ + "spec": { + "display_name": "My Application", + "pg_version": "17" + } + }' +``` + +## Getting Project Details + +### Python SDK + +```python +project = w.postgres.get_project(name="projects/my-app") + +print(f"Project: {project.name}") +print(f"Display name: {project.status.display_name}") +print(f"Postgres version: {project.status.pg_version}") +``` + +### CLI + +```bash +databricks postgres get-project projects/my-app +``` + +**Note:** The `spec` field is not populated for GET operations. All properties are returned in the `status` field. + +## Listing Projects + +```python +projects = w.postgres.list_projects() + +for project in projects: + print(f"Project: {project.name}") + print(f" Display name: {project.status.display_name}") + print(f" Postgres version: {project.status.pg_version}") +``` + +## Updating a Project + +Updates require an `update_mask` specifying which fields to modify: + +```python +from databricks.sdk.service.postgres import Project, ProjectSpec, FieldMask + +# Update display name +operation = w.postgres.update_project( + name="projects/my-app", + project=Project( + name="projects/my-app", + spec=ProjectSpec( + display_name="My Updated Application" + ) + ), + update_mask=FieldMask(field_mask=["spec.display_name"]) +) +result = operation.wait() +``` + +### CLI + +```bash +databricks postgres update-project projects/my-app spec.display_name \ + --json '{ + "spec": { + "display_name": "My Updated Application" + } + }' +``` + +## Deleting a Project + +**WARNING:** Deleting a project is permanent and also deletes all branches, computes, databases, roles, and data. + +Delete all Unity Catalog catalogs and synced tables before deleting the project. + +```python +operation = w.postgres.delete_project(name="projects/my-app") +# This is a long-running operation +``` + +### CLI + +```bash +databricks postgres delete-project projects/my-app +``` + +## Project Settings + +### Compute Defaults + +Default settings for new primary computes: +- Compute size range (0.5-112 CU) +- Scale-to-zero timeout (default: 5 minutes) + +### Instant Restore + +Configure the restore window length (2-35 days). Longer windows increase storage costs. + +### Postgres Version + +Supports Postgres 16 and Postgres 17. + +## Project Limits + +| Resource | Limit | +|----------|-------| +| Concurrently active computes | 20 | +| Branches per project | 500 | +| Postgres roles per branch | 500 | +| Postgres databases per branch | 500 | +| Logical data size per branch | 8 TB | +| Projects per workspace | 1000 | +| Protected branches | 1 | +| Root branches | 3 | +| Unarchived branches | 10 | +| Snapshots | 10 | +| Maximum history retention | 35 days | +| Minimum scale-to-zero time | 60 seconds | + +## Long-Running Operations + +All create, update, and delete operations return a long-running operation (LRO). Use `.wait()` in the SDK to block until completion: + +```python +# Start operation +operation = w.postgres.create_project(...) + +# Wait for completion +result = operation.wait() + +# Or check status manually +op_status = w.postgres.get_operation(name=operation.name) +print(f"Done: {op_status.done}") +``` diff --git a/.claude/skills/databricks-lakebase-autoscale/reverse-etl.md b/.claude/skills/databricks-lakebase-autoscale/reverse-etl.md new file mode 100644 index 00000000..f983eebb --- /dev/null +++ b/.claude/skills/databricks-lakebase-autoscale/reverse-etl.md @@ -0,0 +1,177 @@ +# Reverse ETL with Lakebase Autoscaling + +## Overview + +Reverse ETL allows you to sync data from Unity Catalog Delta tables into Lakebase Autoscaling as PostgreSQL tables. This enables OLTP access patterns on data processed in the Lakehouse. + +## How It Works + +Synced tables create a managed copy of Unity Catalog data in Lakebase: + +1. A new Unity Catalog table (read-only, managed by the sync pipeline) +2. A Postgres table in Lakebase (queryable by applications) + +The sync pipeline uses managed Lakeflow Spark Declarative Pipelines to continuously update both tables. + +### Performance + +- **Continuous writes:** ~1,200 rows/sec per CU +- **Bulk writes:** ~15,000 rows/sec per CU +- **Connections used:** Up to 16 per synced table + +## Sync Modes + +| Mode | Description | Best For | Notes | +|------|-------------|----------|-------| +| **Snapshot** | One-time full copy | Initial setup, historical analysis | 10x more efficient if modifying >10% of data | +| **Triggered** | Scheduled updates on demand | Dashboards updated hourly/daily | Requires CDF on source table | +| **Continuous** | Real-time streaming (seconds of latency) | Live applications | Highest cost, minimum 15s intervals, requires CDF | + +**Note:** Triggered and Continuous modes require Change Data Feed (CDF) enabled on the source table: + +```sql +ALTER TABLE your_catalog.your_schema.your_table +SET TBLPROPERTIES (delta.enableChangeDataFeed = true) +``` + +## Creating Synced Tables + +### Using Python SDK + +```python +from databricks.sdk import WorkspaceClient +from databricks.sdk.service.database import ( + SyncedDatabaseTable, + SyncedTableSpec, + NewPipelineSpec, + SyncedTableSchedulingPolicy, +) + +w = WorkspaceClient() + +# Create a synced table +synced_table = w.database.create_synced_database_table( + SyncedDatabaseTable( + name="lakebase_catalog.schema.synced_table", + spec=SyncedTableSpec( + source_table_full_name="analytics.gold.user_profiles", + primary_key_columns=["user_id"], + scheduling_policy=SyncedTableSchedulingPolicy.TRIGGERED, + new_pipeline_spec=NewPipelineSpec( + storage_catalog="lakebase_catalog", + storage_schema="staging" + ) + ), + ) +) +print(f"Created synced table: {synced_table.name}") +``` + +### Using CLI + +```bash +databricks database create-synced-database-table \ + --json '{ + "name": "lakebase_catalog.schema.synced_table", + "spec": { + "source_table_full_name": "analytics.gold.user_profiles", + "primary_key_columns": ["user_id"], + "scheduling_policy": "TRIGGERED", + "new_pipeline_spec": { + "storage_catalog": "lakebase_catalog", + "storage_schema": "staging" + } + } + }' +``` + +## Checking Synced Table Status + +```python +status = w.database.get_synced_database_table(name="lakebase_catalog.schema.synced_table") +print(f"State: {status.data_synchronization_status.detailed_state}") +print(f"Message: {status.data_synchronization_status.message}") +``` + +## Deleting a Synced Table + +Delete from both Unity Catalog and Postgres: + +1. **Unity Catalog:** Delete from Catalog Explorer or SDK +2. **Postgres:** Drop the table to free storage + +```sql +DROP TABLE your_database.your_schema.your_table; +``` + +## Data Type Mapping + +| Unity Catalog Type | Postgres Type | +|-------------------|---------------| +| BIGINT | BIGINT | +| BINARY | BYTEA | +| BOOLEAN | BOOLEAN | +| DATE | DATE | +| DECIMAL(p,s) | NUMERIC | +| DOUBLE | DOUBLE PRECISION | +| FLOAT | REAL | +| INT | INTEGER | +| INTERVAL | INTERVAL | +| SMALLINT | SMALLINT | +| STRING | TEXT | +| TIMESTAMP | TIMESTAMP WITH TIME ZONE | +| TIMESTAMP_NTZ | TIMESTAMP WITHOUT TIME ZONE | +| TINYINT | SMALLINT | +| ARRAY | JSONB | +| MAP | JSONB | +| STRUCT | JSONB | + +**Unsupported types:** GEOGRAPHY, GEOMETRY, VARIANT, OBJECT + +## Capacity Planning + +- **Connection usage:** Each synced table uses up to 16 connections +- **Size limits:** 2 TB total across all synced tables; recommend < 1 TB per table +- **Naming:** Database, schema, and table names only allow `[A-Za-z0-9_]+` +- **Schema evolution:** Only additive changes (e.g., adding columns) for Triggered/Continuous modes + +## Use Cases + +### Product Catalog for Web App + +```python +w.database.create_synced_database_table( + SyncedDatabaseTable( + name="ecommerce_catalog.public.products", + spec=SyncedTableSpec( + source_table_full_name="gold.products.catalog", + primary_key_columns=["product_id"], + scheduling_policy=SyncedTableSchedulingPolicy.TRIGGERED, + ), + ) +) +``` + +### Real-time Feature Serving + +```python +w.database.create_synced_database_table( + SyncedDatabaseTable( + name="ml_catalog.public.user_features", + spec=SyncedTableSpec( + source_table_full_name="ml.features.user_features", + primary_key_columns=["user_id"], + scheduling_policy=SyncedTableSchedulingPolicy.CONTINUOUS, + ), + ) +) +``` + +## Best Practices + +1. **Enable CDF** on source tables before creating Triggered or Continuous synced tables +2. **Choose appropriate sync mode**: Snapshot for small tables, Triggered for hourly/daily, Continuous for real-time +3. **Monitor sync status**: Check for failures and latency via Catalog Explorer +4. **Index target tables**: Create appropriate indexes in Postgres for your query patterns +5. **Handle schema changes**: Only additive changes are supported for streaming modes +6. **Account for connection limits**: Each synced table uses up to 16 connections diff --git a/.claude/skills/databricks-lakebase-provisioned/SKILL.md b/.claude/skills/databricks-lakebase-provisioned/SKILL.md new file mode 100644 index 00000000..b2b404aa --- /dev/null +++ b/.claude/skills/databricks-lakebase-provisioned/SKILL.md @@ -0,0 +1,308 @@ +--- +name: databricks-lakebase-provisioned +description: "Patterns and best practices for using Lakebase Provisioned (Databricks managed PostgreSQL) for OLTP workloads." +--- + +# Lakebase Provisioned + +Patterns and best practices for using Lakebase Provisioned (Databricks managed PostgreSQL) for OLTP workloads. + +## When to Use + +Use this skill when: +- Building applications that need a PostgreSQL database for transactional workloads +- Adding persistent state to Databricks Apps +- Implementing reverse ETL from Delta Lake to an operational database +- Storing chat/agent memory for LangChain applications + +## Overview + +Lakebase Provisioned is Databricks' managed PostgreSQL database service for OLTP (Online Transaction Processing) workloads. It provides a fully managed PostgreSQL-compatible database that integrates with Unity Catalog and supports OAuth token-based authentication. + +| Feature | Description | +|---------|-------------| +| **Managed PostgreSQL** | Fully managed instances with automatic provisioning | +| **OAuth Authentication** | Token-based auth via Databricks SDK (1-hour expiry) | +| **Unity Catalog** | Register databases for governance | +| **Reverse ETL** | Sync data from Delta tables to PostgreSQL | +| **Apps Integration** | First-class support in Databricks Apps | + +**Available Regions (AWS):** us-east-1, us-east-2, us-west-2, eu-central-1, eu-west-1, ap-south-1, ap-southeast-1, ap-southeast-2 + +## Quick Start + +Create and connect to a Lakebase Provisioned instance: + +```python +from databricks.sdk import WorkspaceClient +import uuid + +# Initialize client +w = WorkspaceClient() + +# Create a database instance +instance = w.database.create_database_instance( + name="my-lakebase-instance", + capacity="CU_1", # CU_1, CU_2, CU_4, CU_8 + stopped=False +) +print(f"Instance created: {instance.name}") +print(f"DNS endpoint: {instance.read_write_dns}") +``` + +## Common Patterns + +### Generate OAuth Token + +```python +from databricks.sdk import WorkspaceClient +import uuid + +w = WorkspaceClient() + +# Generate OAuth token for database connection +cred = w.database.generate_database_credential( + request_id=str(uuid.uuid4()), + instance_names=["my-lakebase-instance"] +) +token = cred.token # Use this as password in connection string +``` + +### Connect from Notebook + +```python +import psycopg +from databricks.sdk import WorkspaceClient +import uuid + +# Get instance details +w = WorkspaceClient() +instance = w.database.get_database_instance(name="my-lakebase-instance") + +# Generate token +cred = w.database.generate_database_credential( + request_id=str(uuid.uuid4()), + instance_names=["my-lakebase-instance"] +) + +# Connect using psycopg3 +conn_string = f"host={instance.read_write_dns} dbname=postgres user={w.current_user.me().user_name} password={cred.token} sslmode=require" +with psycopg.connect(conn_string) as conn: + with conn.cursor() as cur: + cur.execute("SELECT version()") + print(cur.fetchone()) +``` + +### SQLAlchemy with Token Refresh (Production) + +For long-running applications, tokens must be refreshed (expire after 1 hour): + +```python +import asyncio +import os +import uuid +from sqlalchemy import event +from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession +from sqlalchemy.orm import sessionmaker +from databricks.sdk import WorkspaceClient + +# Token refresh state +_current_token = None +_token_refresh_task = None +TOKEN_REFRESH_INTERVAL = 50 * 60 # 50 minutes (before 1-hour expiry) + +def _generate_token(instance_name: str) -> str: + """Generate fresh OAuth token.""" + w = WorkspaceClient() + cred = w.database.generate_database_credential( + request_id=str(uuid.uuid4()), + instance_names=[instance_name] + ) + return cred.token + +async def _token_refresh_loop(instance_name: str): + """Background task to refresh token every 50 minutes.""" + global _current_token + while True: + await asyncio.sleep(TOKEN_REFRESH_INTERVAL) + _current_token = await asyncio.to_thread(_generate_token, instance_name) + +def init_database(instance_name: str, database_name: str, username: str) -> AsyncEngine: + """Initialize database with OAuth token injection.""" + global _current_token + + w = WorkspaceClient() + instance = w.database.get_database_instance(name=instance_name) + + # Generate initial token + _current_token = _generate_token(instance_name) + + # Build URL (password injected via do_connect) + url = f"postgresql+psycopg://{username}@{instance.read_write_dns}:5432/{database_name}" + + engine = create_async_engine( + url, + pool_size=5, + max_overflow=10, + pool_recycle=3600, + connect_args={"sslmode": "require"} + ) + + # Inject token on each connection + @event.listens_for(engine.sync_engine, "do_connect") + def provide_token(dialect, conn_rec, cargs, cparams): + cparams["password"] = _current_token + + return engine +``` + +### Databricks Apps Integration + +For Databricks Apps, use environment variables for configuration: + +```python +# Environment variables set by Databricks Apps: +# - LAKEBASE_INSTANCE_NAME: Instance name +# - LAKEBASE_DATABASE_NAME: Database name +# - LAKEBASE_USERNAME: Username (optional, defaults to service principal) + +import os + +def is_lakebase_configured() -> bool: + """Check if Lakebase is configured for this app.""" + return bool( + os.environ.get("LAKEBASE_PG_URL") or + (os.environ.get("LAKEBASE_INSTANCE_NAME") and + os.environ.get("LAKEBASE_DATABASE_NAME")) + ) +``` + +Add Lakebase as an app resource via CLI: + +```bash +databricks apps add-resource $APP_NAME \ + --resource-type database \ + --resource-name lakebase \ + --database-instance my-lakebase-instance +``` + +### Register with Unity Catalog + +```python +from databricks.sdk import WorkspaceClient + +w = WorkspaceClient() + +# Register database in Unity Catalog +w.database.register_database_instance( + name="my-lakebase-instance", + catalog="my_catalog", + schema="my_schema" +) +``` + +### MLflow Model Resources + +Declare Lakebase as a model resource for automatic credential provisioning: + +```python +from mlflow.models.resources import DatabricksLakebase + +resources = [ + DatabricksLakebase(database_instance_name="my-lakebase-instance"), +] + +# When logging model +mlflow.langchain.log_model( + model, + artifact_path="model", + resources=resources, + pip_requirements=["databricks-langchain[memory]"] +) +``` + +## MCP Tools + +The following MCP tools are available for managing Lakebase infrastructure. Use `type="provisioned"` for Lakebase Provisioned. + +### Database Management + +| Tool | Description | +|------|-------------| +| `create_or_update_lakebase_database` | Create or update a database. Finds by name, creates if new, updates if existing. Use `type="provisioned"`, `capacity` (CU_1-CU_8), `stopped` params. | +| `get_lakebase_database` | Get database details or list all. Pass `name` to get one, omit to list all. Use `type="provisioned"` to filter. | +| `delete_lakebase_database` | Delete a database and its resources. Use `type="provisioned"`, `force=True` to cascade. | +| `generate_lakebase_credential` | Generate OAuth token for PostgreSQL connections (1-hour expiry). Pass `instance_names` for provisioned. | + +### Reverse ETL (Catalog + Synced Tables) + +| Tool | Description | +|------|-------------| +| `create_or_update_lakebase_sync` | Set up reverse ETL: ensures UC catalog registration exists, then creates a synced table from Delta to Lakebase. Params: `instance_name`, `source_table_name`, `target_table_name`, `scheduling_policy` ("TRIGGERED"/"SNAPSHOT"/"CONTINUOUS"). | +| `delete_lakebase_sync` | Remove a synced table and optionally its UC catalog registration. | + +## Reference Files + +- [connection-patterns.md](connection-patterns.md) - Detailed connection patterns for different use cases +- [reverse-etl.md](reverse-etl.md) - Syncing data from Delta Lake to Lakebase + +## CLI Quick Reference + +```bash +# Create instance +databricks database create-database-instance \ + --name my-lakebase-instance \ + --capacity CU_1 + +# Get instance details +databricks database get-database-instance --name my-lakebase-instance + +# Generate credentials +databricks database generate-database-credential \ + --request-id $(uuidgen) \ + --json '{"instance_names": ["my-lakebase-instance"]}' + +# List instances +databricks database list-database-instances + +# Stop instance (saves cost) +databricks database stop-database-instance --name my-lakebase-instance + +# Start instance +databricks database start-database-instance --name my-lakebase-instance +``` + +## Common Issues + +| Issue | Solution | +|-------|----------| +| **Token expired during long query** | Implement token refresh loop (see SQLAlchemy with Token Refresh section); tokens expire after 1 hour | +| **DNS resolution fails on macOS** | Use `dig` command to resolve hostname, pass `hostaddr` to psycopg | +| **Connection refused** | Ensure instance is not stopped; check `instance.state` | +| **Permission denied** | User must be granted access to the Lakebase instance | +| **SSL required error** | Always use `sslmode=require` in connection string | + +## SDK Version Requirements + +- **Databricks SDK for Python**: >= 0.61.0 (0.81.0+ recommended for full API support) +- **psycopg**: 3.x (supports `hostaddr` parameter for DNS workaround) +- **SQLAlchemy**: 2.x with `postgresql+psycopg` driver + +```python +%pip install -U "databricks-sdk>=0.81.0" "psycopg[binary]>=3.0" sqlalchemy +``` + +## Notes + +- **Capacity values** use compute unit sizing: `CU_1`, `CU_2`, `CU_4`, `CU_8`. +- **Lakebase Autoscaling** is a newer offering with automatic scaling but limited regional availability. This skill focuses on **Lakebase Provisioned** which is more widely available. +- For memory/state in LangChain agents, use `databricks-langchain[memory]` which includes Lakebase support. +- Tokens are short-lived (1 hour) - production apps MUST implement token refresh. + +## Related Skills + +- **[databricks-app-apx](../databricks-app-apx/SKILL.md)** - full-stack apps that can use Lakebase for persistence +- **[databricks-app-python](../databricks-app-python/SKILL.md)** - Python apps with Lakebase backend +- **[databricks-python-sdk](../databricks-python-sdk/SKILL.md)** - SDK used for instance management and token generation +- **[databricks-asset-bundles](../databricks-asset-bundles/SKILL.md)** - deploying apps with Lakebase resources +- **[databricks-jobs](../databricks-jobs/SKILL.md)** - scheduling reverse ETL sync jobs diff --git a/.claude/skills/databricks-lakebase-provisioned/connection-patterns.md b/.claude/skills/databricks-lakebase-provisioned/connection-patterns.md new file mode 100644 index 00000000..e6843548 --- /dev/null +++ b/.claude/skills/databricks-lakebase-provisioned/connection-patterns.md @@ -0,0 +1,279 @@ +# Lakebase Connection Patterns + +## Overview + +This document covers different connection patterns for Lakebase Provisioned, from simple scripts to production applications with token refresh. + +## Connection Methods + +### 1. Direct psycopg Connection (Simple Scripts) + +For one-off scripts or notebooks: + +```python +import psycopg +from databricks.sdk import WorkspaceClient +import uuid + +def get_connection(instance_name: str, database_name: str = "postgres"): + """Get a database connection with fresh OAuth token.""" + w = WorkspaceClient() + + # Get instance details + instance = w.database.get_database_instance(name=instance_name) + + # Generate OAuth token (valid for 1 hour) + cred = w.database.generate_database_credential( + request_id=str(uuid.uuid4()), + instance_names=[instance_name] + ) + + # Build connection string + conn_string = ( + f"host={instance.read_write_dns} " + f"dbname={database_name} " + f"user={w.current_user.me().user_name} " + f"password={cred.token} " + f"sslmode=require" + ) + + return psycopg.connect(conn_string) + +# Usage +with get_connection("my-instance") as conn: + with conn.cursor() as cur: + cur.execute("SELECT NOW()") + print(cur.fetchone()) +``` + +### 2. Connection Pool with Token Refresh (Production) + +For long-running applications that need connection pooling: + +```python +import asyncio +import uuid +from contextlib import asynccontextmanager +from typing import AsyncGenerator, Optional + +from sqlalchemy import event +from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker +from databricks.sdk import WorkspaceClient + +class LakebaseConnectionManager: + """Manages Lakebase connections with automatic token refresh.""" + + def __init__( + self, + instance_name: str, + database_name: str, + pool_size: int = 5, + max_overflow: int = 10, + token_refresh_seconds: int = 3000 # 50 minutes + ): + self.instance_name = instance_name + self.database_name = database_name + self.pool_size = pool_size + self.max_overflow = max_overflow + self.token_refresh_seconds = token_refresh_seconds + + self._current_token: Optional[str] = None + self._refresh_task: Optional[asyncio.Task] = None + self._engine = None + self._session_maker = None + + def _generate_token(self) -> str: + """Generate fresh OAuth token.""" + w = WorkspaceClient() + cred = w.database.generate_database_credential( + request_id=str(uuid.uuid4()), + instance_names=[self.instance_name] + ) + return cred.token + + async def _refresh_loop(self): + """Background task to refresh token periodically.""" + while True: + await asyncio.sleep(self.token_refresh_seconds) + try: + self._current_token = await asyncio.to_thread(self._generate_token) + except Exception as e: + print(f"Token refresh failed: {e}") + + def initialize(self): + """Initialize database engine and start token refresh.""" + w = WorkspaceClient() + + # Get instance info + instance = w.database.get_database_instance(name=self.instance_name) + username = w.current_user.me().user_name + + # Generate initial token + self._current_token = self._generate_token() + + # Create engine (password injected via event) + url = ( + f"postgresql+psycopg://{username}@" + f"{instance.read_write_dns}:5432/{self.database_name}" + ) + + self._engine = create_async_engine( + url, + pool_size=self.pool_size, + max_overflow=self.max_overflow, + pool_recycle=3600, + connect_args={"sslmode": "require"} + ) + + # Inject token on connect + @event.listens_for(self._engine.sync_engine, "do_connect") + def inject_token(dialect, conn_rec, cargs, cparams): + cparams["password"] = self._current_token + + self._session_maker = async_sessionmaker( + self._engine, + class_=AsyncSession, + expire_on_commit=False + ) + + def start_refresh(self): + """Start background token refresh task.""" + if not self._refresh_task: + self._refresh_task = asyncio.create_task(self._refresh_loop()) + + async def stop_refresh(self): + """Stop token refresh task.""" + if self._refresh_task: + self._refresh_task.cancel() + try: + await self._refresh_task + except asyncio.CancelledError: + pass + self._refresh_task = None + + @asynccontextmanager + async def session(self) -> AsyncGenerator[AsyncSession, None]: + """Get a database session.""" + async with self._session_maker() as session: + yield session + + async def close(self): + """Close all connections.""" + await self.stop_refresh() + if self._engine: + await self._engine.dispose() + +# Usage in FastAPI +from fastapi import FastAPI + +app = FastAPI() +db_manager = LakebaseConnectionManager("my-instance", "my_database") + +@app.on_event("startup") +async def startup(): + db_manager.initialize() + db_manager.start_refresh() + +@app.on_event("shutdown") +async def shutdown(): + await db_manager.close() + +@app.get("/data") +async def get_data(): + async with db_manager.session() as session: + result = await session.execute("SELECT * FROM my_table") + return result.fetchall() +``` + +### 3. Static URL Mode (Local Development) + +For local development, use a static connection URL: + +```python +import os +from sqlalchemy.ext.asyncio import create_async_engine + +# Set environment variable with full connection URL +# LAKEBASE_PG_URL=postgresql://user:password@host:5432/database + +def get_database_url() -> str: + """Get database URL from environment.""" + url = os.environ.get("LAKEBASE_PG_URL") + if url and url.startswith("postgresql://"): + # Convert to psycopg3 async driver + url = url.replace("postgresql://", "postgresql+psycopg://", 1) + return url + +engine = create_async_engine( + get_database_url(), + pool_size=5, + connect_args={"sslmode": "require"} +) +``` + +### 4. DNS Resolution Workaround (macOS) + +Python's `socket.getaddrinfo()` fails with long hostnames on macOS. Use `dig` as fallback: + +```python +import subprocess +import socket + +def resolve_hostname(hostname: str) -> str: + """Resolve hostname using dig command (macOS workaround).""" + try: + # Try Python's resolver first + return socket.gethostbyname(hostname) + except socket.gaierror: + pass + + # Fallback to dig command + try: + result = subprocess.run( + ["dig", "+short", hostname], + capture_output=True, + text=True, + timeout=5 + ) + ips = result.stdout.strip().split('\n') + for ip in ips: + if ip and not ip.startswith(';'): + return ip + except Exception: + pass + + raise RuntimeError(f"Could not resolve hostname: {hostname}") + +# Use with psycopg +conn_params = { + "host": hostname, # For TLS SNI + "hostaddr": resolve_hostname(hostname), # Actual IP + "dbname": database_name, + "user": username, + "password": token, + "sslmode": "require" +} +conn = psycopg.connect(**conn_params) +``` + +## Environment Variables + +| Variable | Description | Required | +|----------|-------------|----------| +| `LAKEBASE_PG_URL` | Static PostgreSQL URL (local dev) | Either this OR instance/database | +| `LAKEBASE_INSTANCE_NAME` | Lakebase instance name | With DATABASE_NAME | +| `LAKEBASE_DATABASE_NAME` | Database name | With INSTANCE_NAME | +| `LAKEBASE_USERNAME` | Override username | No | +| `LAKEBASE_HOST` | Override host | No | +| `DB_POOL_SIZE` | Connection pool size | No (default: 5) | +| `DB_MAX_OVERFLOW` | Max pool overflow | No (default: 10) | +| `DB_POOL_RECYCLE_INTERVAL` | Pool recycle seconds | No (default: 3600) | + +## Best Practices + +1. **Always use SSL**: Set `sslmode=require` in all connections +2. **Implement token refresh**: Tokens expire after 1 hour; refresh at 50 minutes +3. **Use connection pooling**: Avoid creating new connections per request +4. **Handle DNS issues on macOS**: Use the `hostaddr` workaround if needed +5. **Close connections properly**: Use context managers or explicit cleanup +6. **Log token refresh events**: Helps debug authentication issues diff --git a/.claude/skills/databricks-lakebase-provisioned/reverse-etl.md b/.claude/skills/databricks-lakebase-provisioned/reverse-etl.md new file mode 100644 index 00000000..9bf17bd7 --- /dev/null +++ b/.claude/skills/databricks-lakebase-provisioned/reverse-etl.md @@ -0,0 +1,226 @@ +# Reverse ETL with Lakebase + +## Overview + +Reverse ETL allows you to sync data from Unity Catalog Delta tables into Lakebase Provisioned as PostgreSQL tables. This enables OLTP access patterns on data processed in the Lakehouse. + +## Creating Synced Tables + +### Using Python SDK + +```python +from databricks.sdk import WorkspaceClient + +w = WorkspaceClient() + +# Create a synced table from Unity Catalog +synced_table = w.database.create_synced_table( + instance_name="my-lakebase-instance", + source_table_name="catalog.schema.source_table", + target_table_name="target_table", + sync_mode="FULL", # FULL or INCREMENTAL +) + +print(f"Synced table created: {synced_table.target_table_name}") +``` + +### Using SQL + +```sql +-- Create synced table via SQL +CREATE SYNCED TABLE my_lakebase.target_table +FROM catalog.schema.source_table +USING LAKEBASE INSTANCE 'my-lakebase-instance'; +``` + +### Using CLI + +```bash +databricks database create-synced-table \ + --instance-name my-lakebase-instance \ + --source-table-name catalog.schema.source_table \ + --target-table-name target_table \ + --sync-mode FULL +``` + +## Sync Modes + +### Full Sync + +Complete replacement of target table on each sync: + +```python +synced_table = w.database.create_synced_table( + instance_name="my-lakebase-instance", + source_table_name="catalog.schema.customers", + target_table_name="customers", + sync_mode="FULL" +) +``` + +**Use when:** +- Source table is small-medium size +- Need complete consistency with source +- Incremental changes are complex to track + +### Incremental Sync + +Only sync changed rows (requires change tracking): + +```python +synced_table = w.database.create_synced_table( + instance_name="my-lakebase-instance", + source_table_name="catalog.schema.events", + target_table_name="events", + sync_mode="INCREMENTAL", + incremental_column="updated_at" # Column to track changes +) +``` + +**Use when:** +- Source table is large +- Have reliable change tracking column +- Minimize sync time and resource usage + +## Managing Synced Tables + +### List Synced Tables + +```python +synced_tables = w.database.list_synced_tables( + instance_name="my-lakebase-instance" +) +for table in synced_tables: + print(f"{table.target_table_name}: {table.sync_status}") +``` + +### Trigger Manual Sync + +```python +w.database.sync_table( + instance_name="my-lakebase-instance", + table_name="customers" +) +``` + +### Delete Synced Table + +```python +w.database.delete_synced_table( + instance_name="my-lakebase-instance", + table_name="customers" +) +``` + +## Scheduling Syncs + +### Using Databricks Jobs + +```python +from databricks.sdk import WorkspaceClient +from databricks.sdk.service.jobs import Task, NotebookTask, CronSchedule + +w = WorkspaceClient() + +# Create job to sync tables on schedule +job = w.jobs.create( + name="Lakebase Sync Job", + tasks=[ + Task( + task_key="sync_customers", + notebook_task=NotebookTask( + notebook_path="/Repos/sync/sync_customers" + ) + ) + ], + schedule=CronSchedule( + quartz_cron_expression="0 0 * * * ?", # Every hour + timezone_id="UTC" + ) +) +``` + +### Sync Notebook Example + +```python +# Databricks notebook: sync_customers + +from databricks.sdk import WorkspaceClient + +w = WorkspaceClient() + +# Trigger sync for specific tables +tables_to_sync = ["customers", "orders", "products"] + +for table in tables_to_sync: + try: + w.database.sync_table( + instance_name="my-lakebase-instance", + table_name=table + ) + print(f"Synced: {table}") + except Exception as e: + print(f"Failed to sync {table}: {e}") +``` + +## Use Cases + +### 1. Product Catalog for Web App + +```python +# Sync product data for e-commerce app +w.database.create_synced_table( + instance_name="ecommerce-db", + source_table_name="gold.products.catalog", + target_table_name="products", + sync_mode="FULL" +) + +# Application queries PostgreSQL directly +# with low-latency point lookups +``` + +### 2. User Profiles for Authentication + +```python +# Sync user profiles for auth service +w.database.create_synced_table( + instance_name="auth-db", + source_table_name="gold.users.profiles", + target_table_name="user_profiles", + sync_mode="INCREMENTAL", + incremental_column="last_modified" +) +``` + +### 3. Feature Store for Real-time ML + +```python +# Sync features for online serving +w.database.create_synced_table( + instance_name="feature-store-db", + source_table_name="ml.features.user_features", + target_table_name="user_features", + sync_mode="INCREMENTAL", + incremental_column="computed_at" +) + +# ML model queries features with low latency +``` + +## Best Practices + +1. **Choose appropriate sync mode**: Use FULL for small tables, INCREMENTAL for large tables with change tracking +2. **Schedule during low-traffic periods**: Heavy syncs can impact both source and target +3. **Monitor sync status**: Check for failures and latency +4. **Index target tables**: Create appropriate indexes in PostgreSQL for query patterns +5. **Handle schema changes**: Synced tables need updates when source schema changes + +## Common Issues + +| Issue | Solution | +|-------|----------| +| **Sync takes too long** | Switch to INCREMENTAL mode; add indexes on source | +| **Schema mismatch** | Drop and recreate synced table after source schema changes | +| **Sync fails with timeout** | Increase sync timeout; reduce batch size | +| **Target table locked** | Avoid DDL on target during sync operations | diff --git a/.claude/skills/databricks-metric-views/SKILL.md b/.claude/skills/databricks-metric-views/SKILL.md new file mode 100644 index 00000000..d3f5834c --- /dev/null +++ b/.claude/skills/databricks-metric-views/SKILL.md @@ -0,0 +1,229 @@ +--- +name: databricks-metric-views +description: "Unity Catalog metric views: define, create, query, and manage governed business metrics in YAML. Use when building standardized KPIs, revenue metrics, order analytics, or any reusable business metrics that need consistent definitions across teams and tools." +--- + +# Unity Catalog Metric Views + +Define reusable, governed business metrics in YAML that separate measure definitions from dimension groupings for flexible querying. + +## When to Use + +Use this skill when: +- Defining **standardized business metrics** (revenue, order counts, conversion rates) +- Building **KPI layers** shared across dashboards, Genie, and SQL queries +- Creating metrics with **complex aggregations** (ratios, distinct counts, filtered measures) +- Defining **window measures** (moving averages, running totals, period-over-period, YTD) +- Modeling **star or snowflake schemas** with joins in metric definitions +- Enabling **materialization** for pre-computed metric aggregations + +## Prerequisites + +- **Databricks Runtime 17.2+** (for YAML version 1.1) +- SQL warehouse with `CAN USE` permissions +- `SELECT` on source tables, `CREATE TABLE` + `USE SCHEMA` in the target schema + +## Quick Start + +### Create a Metric View + +```sql +CREATE OR REPLACE VIEW catalog.schema.orders_metrics +WITH METRICS +LANGUAGE YAML +AS $$ + version: 1.1 + comment: "Orders KPIs for sales analysis" + source: catalog.schema.orders + filter: order_date > '2020-01-01' + dimensions: + - name: Order Month + expr: DATE_TRUNC('MONTH', order_date) + comment: "Month of order" + - name: Order Status + expr: CASE + WHEN status = 'O' THEN 'Open' + WHEN status = 'P' THEN 'Processing' + WHEN status = 'F' THEN 'Fulfilled' + END + comment: "Human-readable order status" + measures: + - name: Order Count + expr: COUNT(1) + - name: Total Revenue + expr: SUM(total_price) + comment: "Sum of total price" + - name: Revenue per Customer + expr: SUM(total_price) / COUNT(DISTINCT customer_id) + comment: "Average revenue per unique customer" +$$ +``` + +### Query a Metric View + +All measures must use the `MEASURE()` function. `SELECT *` is NOT supported. + +```sql +SELECT + `Order Month`, + `Order Status`, + MEASURE(`Total Revenue`) AS total_revenue, + MEASURE(`Order Count`) AS order_count +FROM catalog.schema.orders_metrics +WHERE extract(year FROM `Order Month`) = 2024 +GROUP BY ALL +ORDER BY ALL +``` + +## Reference Files + +| Topic | File | Description | +|-------|------|-------------| +| YAML Syntax | [yaml-reference.md](yaml-reference.md) | Complete YAML spec: dimensions, measures, joins, materialization | +| Patterns & Examples | [patterns.md](patterns.md) | Common patterns: star schema, snowflake, filtered measures, window measures, ratios | + +## MCP Tools + +Use the `manage_metric_views` tool for all metric view operations: + +| Action | Description | +|--------|-------------| +| `create` | Create a metric view with dimensions and measures | +| `alter` | Update a metric view's YAML definition | +| `describe` | Get the full definition and metadata | +| `query` | Query measures grouped by dimensions | +| `drop` | Drop a metric view | +| `grant` | Grant SELECT privileges to users/groups | + +### Create via MCP + +```python +manage_metric_views( + action="create", + full_name="catalog.schema.orders_metrics", + source="catalog.schema.orders", + or_replace=True, + comment="Orders KPIs for sales analysis", + filter_expr="order_date > '2020-01-01'", + dimensions=[ + {"name": "Order Month", "expr": "DATE_TRUNC('MONTH', order_date)", "comment": "Month of order"}, + {"name": "Order Status", "expr": "status"}, + ], + measures=[ + {"name": "Order Count", "expr": "COUNT(1)"}, + {"name": "Total Revenue", "expr": "SUM(total_price)", "comment": "Sum of total price"}, + ], +) +``` + +### Query via MCP + +```python +manage_metric_views( + action="query", + full_name="catalog.schema.orders_metrics", + query_measures=["Total Revenue", "Order Count"], + query_dimensions=["Order Month"], + where="extract(year FROM `Order Month`) = 2024", + order_by="ALL", + limit=100, +) +``` + +### Describe via MCP + +```python +manage_metric_views( + action="describe", + full_name="catalog.schema.orders_metrics", +) +``` + +### Grant Access + +```python +manage_metric_views( + action="grant", + full_name="catalog.schema.orders_metrics", + principal="data-consumers", + privileges=["SELECT"], +) +``` + +## YAML Spec Quick Reference + +```yaml +version: 1.1 # Required: "1.1" for DBR 17.2+ +comment: "Description" # Optional: metric view description +source: catalog.schema.table # Required: source table/view +filter: column > value # Optional: global WHERE filter + +dimensions: # Required: at least one + - name: Display Name # Backtick-quoted in queries + expr: sql_expression # Column ref or SQL transformation + comment: "Description" # Optional (v1.1+) + +measures: # Required: at least one + - name: Display Name # Queried via MEASURE(`name`) + expr: AGG_FUNC(column) # Must be an aggregate expression + comment: "Description" # Optional (v1.1+) + +joins: # Optional: star/snowflake schema + - name: dim_table + source: catalog.schema.dim_table + on: source.fk = dim_table.pk + +materialization: # Optional (experimental) + schedule: every 6 hours + mode: relaxed +``` + +## Key Concepts + +### Dimensions vs Measures + +| | Dimensions | Measures | +|---|---|---| +| **Purpose** | Categorize and group data | Aggregate numeric values | +| **Examples** | Region, Date, Status | SUM(revenue), COUNT(orders) | +| **In queries** | Used in SELECT and GROUP BY | Wrapped in `MEASURE()` | +| **SQL expressions** | Any SQL expression | Must use aggregate functions | + +### Why Metric Views vs Standard Views? + +| Feature | Standard Views | Metric Views | +|---------|---------------|--------------| +| Aggregation locked at creation | Yes | No - flexible at query time | +| Safe re-aggregation of ratios | No | Yes | +| Star/snowflake schema joins | Manual | Declarative in YAML | +| Materialization | Separate MV needed | Built-in | +| AI/BI Genie integration | Limited | Native | + +## Common Issues + +| Issue | Solution | +|-------|----------| +| **SELECT * not supported** | Must explicitly list dimensions and use MEASURE() for measures | +| **"Cannot resolve column"** | Dimension/measure names with spaces need backtick quoting | +| **JOIN at query time fails** | Joins must be in the YAML definition, not in the SELECT query | +| **MEASURE() required** | All measure references must be wrapped: `MEASURE(\`name\`)` | +| **DBR version error** | Requires Runtime 17.2+ for YAML v1.1, or 16.4+ for v0.1 | +| **Materialization not working** | Requires serverless compute enabled; currently experimental | + +## Integrations + +Metric views work natively with: +- **AI/BI Dashboards** - Use as datasets for visualizations +- **AI/BI Genie** - Natural language querying of metrics +- **Alerts** - Set threshold-based alerts on measures +- **SQL Editor** - Direct SQL querying with MEASURE() +- **Catalog Explorer UI** - Visual creation and browsing + +## Resources + +- [Metric Views Documentation](https://docs.databricks.com/en/metric-views/) +- [YAML Syntax Reference](https://docs.databricks.com/en/metric-views/data-modeling/syntax) +- [Joins](https://docs.databricks.com/en/metric-views/data-modeling/joins) +- [Window Measures](https://docs.databricks.com/aws/en/metric-views/data-modeling/window-measures) (Experimental) +- [Materialization](https://docs.databricks.com/en/metric-views/materialization) +- [MEASURE() Function](https://docs.databricks.com/en/sql/language-manual/functions/measure) diff --git a/.claude/skills/databricks-metric-views/patterns.md b/.claude/skills/databricks-metric-views/patterns.md new file mode 100644 index 00000000..48c7f9e3 --- /dev/null +++ b/.claude/skills/databricks-metric-views/patterns.md @@ -0,0 +1,651 @@ +# Metric View Patterns & Examples + +Common patterns for creating and querying metric views. + +## Pattern 1: Simple Metrics from a Single Table + +The most basic pattern with direct column dimensions and standard aggregations. + +### Create + +```sql +CREATE OR REPLACE VIEW catalog.schema.product_metrics +WITH METRICS +LANGUAGE YAML +AS $$ + version: 1.1 + comment: "Product sales metrics" + source: catalog.schema.sales + dimensions: + - name: Product Name + expr: product_name + - name: Sale Date + expr: sale_date + measures: + - name: Units Sold + expr: COUNT(1) + - name: Total Revenue + expr: SUM(price * quantity) + - name: Average Price + expr: AVG(price) +$$ +``` + +### Query + +```sql +-- Revenue by product +SELECT + `Product Name`, + MEASURE(`Total Revenue`) AS revenue, + MEASURE(`Units Sold`) AS units +FROM catalog.schema.product_metrics +GROUP BY ALL +ORDER BY revenue DESC +LIMIT 10 + +-- Monthly trend +SELECT + DATE_TRUNC('MONTH', `Sale Date`) AS month, + MEASURE(`Total Revenue`) AS revenue +FROM catalog.schema.product_metrics +GROUP BY ALL +ORDER BY month +``` + +## Pattern 2: Derived Dimensions with CASE + +Transform raw values into business-friendly categories. + +```sql +CREATE OR REPLACE VIEW catalog.schema.order_kpis +WITH METRICS +LANGUAGE YAML +AS $$ + version: 1.1 + source: catalog.schema.orders + dimensions: + - name: Order Month + expr: DATE_TRUNC('MONTH', order_date) + - name: Priority Level + expr: CASE + WHEN priority <= 2 THEN 'High' + WHEN priority <= 4 THEN 'Medium' + ELSE 'Low' + END + comment: "Bucketed priority: High (1-2), Medium (3-4), Low (5)" + - name: Size Category + expr: CASE + WHEN total_amount > 10000 THEN 'Large' + WHEN total_amount > 1000 THEN 'Medium' + ELSE 'Small' + END + measures: + - name: Order Count + expr: COUNT(1) + - name: Total Amount + expr: SUM(total_amount) +$$ +``` + +## Pattern 3: Ratio Measures + +Ratios and per-unit metrics that safely handle re-aggregation. + +```sql +CREATE OR REPLACE VIEW catalog.schema.efficiency_metrics +WITH METRICS +LANGUAGE YAML +AS $$ + version: 1.1 + comment: "Efficiency and per-unit metrics" + source: catalog.schema.transactions + dimensions: + - name: Department + expr: department_name + - name: Quarter + expr: DATE_TRUNC('QUARTER', transaction_date) + measures: + - name: Total Revenue + expr: SUM(revenue) + - name: Total Cost + expr: SUM(cost) + - name: Profit Margin + expr: (SUM(revenue) - SUM(cost)) / SUM(revenue) + comment: "Profit as percentage of revenue" + - name: Revenue per Employee + expr: SUM(revenue) / COUNT(DISTINCT employee_id) + - name: Average Transaction Size + expr: SUM(revenue) / COUNT(1) +$$ +``` + +## Pattern 4: Filtered Measures (FILTER clause) + +Create measures that only count a subset of rows. + +```sql +CREATE OR REPLACE VIEW catalog.schema.order_status_metrics +WITH METRICS +LANGUAGE YAML +AS $$ + version: 1.1 + source: catalog.schema.orders + dimensions: + - name: Order Month + expr: DATE_TRUNC('MONTH', order_date) + - name: Region + expr: region + measures: + - name: Total Orders + expr: COUNT(1) + - name: Open Orders + expr: COUNT(1) FILTER (WHERE status = 'OPEN') + - name: Fulfilled Orders + expr: COUNT(1) FILTER (WHERE status = 'FULFILLED') + - name: Open Revenue + expr: SUM(amount) FILTER (WHERE status = 'OPEN') + comment: "Revenue at risk from unfulfilled orders" + - name: Fulfillment Rate + expr: COUNT(1) FILTER (WHERE status = 'FULFILLED') * 1.0 / COUNT(1) + comment: "Percentage of orders fulfilled" +$$ +``` + +### Query filtered measures + +```sql +SELECT + `Order Month`, + MEASURE(`Total Orders`) AS total, + MEASURE(`Open Orders`) AS open_orders, + MEASURE(`Fulfillment Rate`) AS fulfillment_rate +FROM catalog.schema.order_status_metrics +WHERE `Region` = 'EMEA' +GROUP BY ALL +ORDER BY ALL +``` + +## Pattern 5: Star Schema with Joins + +Join a fact table to dimension tables. + +```sql +CREATE OR REPLACE VIEW catalog.schema.sales_analytics +WITH METRICS +LANGUAGE YAML +AS $$ + version: 1.1 + comment: "Sales analytics with customer and product dimensions" + source: catalog.schema.fact_sales + + joins: + - name: customer + source: catalog.schema.dim_customer + on: source.customer_id = customer.customer_id + - name: product + source: catalog.schema.dim_product + on: source.product_id = product.product_id + - name: store + source: catalog.schema.dim_store + on: source.store_id = store.store_id + + dimensions: + - name: Customer Segment + expr: customer.segment + - name: Product Category + expr: product.category + - name: Store City + expr: store.city + - name: Sale Month + expr: DATE_TRUNC('MONTH', source.sale_date) + + measures: + - name: Total Revenue + expr: SUM(source.amount) + - name: Unique Customers + expr: COUNT(DISTINCT source.customer_id) + - name: Average Basket Size + expr: SUM(source.amount) / COUNT(DISTINCT source.transaction_id) +$$ +``` + +## Pattern 6: Snowflake Schema (Nested Joins) + +Multi-level dimension hierarchies. Requires DBR 17.1+. + +```sql +CREATE OR REPLACE VIEW catalog.schema.geo_sales +WITH METRICS +LANGUAGE YAML +AS $$ + version: 1.1 + source: catalog.schema.orders + + joins: + - name: customer + source: catalog.schema.customer + on: source.customer_key = customer.customer_key + joins: + - name: nation + source: catalog.schema.nation + on: customer.nation_key = nation.nation_key + joins: + - name: region + source: catalog.schema.region + on: nation.region_key = region.region_key + + dimensions: + - name: Customer Name + expr: customer.name + - name: Nation + expr: nation.name + - name: Region + expr: region.name + - name: Order Year + expr: EXTRACT(YEAR FROM source.order_date) + + measures: + - name: Total Revenue + expr: SUM(source.total_price) + - name: Order Count + expr: COUNT(1) +$$ +``` + +### Query across hierarchy levels + +```sql +-- Revenue by region (rolls up across nations and customers) +SELECT + `Region`, + MEASURE(`Total Revenue`) AS revenue +FROM catalog.schema.geo_sales +GROUP BY ALL + +-- Revenue by nation within a specific region +SELECT + `Nation`, + MEASURE(`Total Revenue`) AS revenue, + MEASURE(`Order Count`) AS orders +FROM catalog.schema.geo_sales +WHERE `Region` = 'EUROPE' +GROUP BY ALL +ORDER BY revenue DESC +``` + +## Pattern 7: Materialized Metric View + +Pre-compute common aggregations for faster queries. + +```sql +CREATE OR REPLACE VIEW catalog.schema.ecommerce_metrics +WITH METRICS +LANGUAGE YAML +AS $$ + version: 1.1 + source: catalog.schema.transactions + + dimensions: + - name: Category + expr: product_category + - name: Day + expr: DATE_TRUNC('DAY', transaction_date) + - name: Channel + expr: sales_channel + + measures: + - name: Revenue + expr: SUM(amount) + - name: Transactions + expr: COUNT(1) + - name: Unique Buyers + expr: COUNT(DISTINCT customer_id) + + materialization: + schedule: every 1 hour + mode: relaxed + materialized_views: + - name: daily_category + type: aggregated + dimensions: + - Category + - Day + measures: + - Revenue + - Transactions + - name: full_model + type: unaggregated +$$ +``` + +## Pattern 8: Using samples.tpch for Quick Demos + +The TPC-H sample dataset is available on all Databricks workspaces. + +```sql +CREATE OR REPLACE VIEW catalog.schema.tpch_orders_metrics +WITH METRICS +LANGUAGE YAML +AS $$ + version: 1.1 + comment: "TPC-H Orders KPIs - demo metric view" + source: samples.tpch.orders + filter: o_orderdate > '1990-01-01' + + dimensions: + - name: Order Month + expr: DATE_TRUNC('MONTH', o_orderdate) + comment: "Month of order" + - name: Order Status + expr: CASE + WHEN o_orderstatus = 'O' THEN 'Open' + WHEN o_orderstatus = 'P' THEN 'Processing' + WHEN o_orderstatus = 'F' THEN 'Fulfilled' + END + comment: "Status: Open, Processing, or Fulfilled" + - name: Order Priority + expr: SPLIT(o_orderpriority, '-')[1] + comment: "Numeric priority 1-5; 1 is highest" + + measures: + - name: Order Count + expr: COUNT(1) + - name: Total Revenue + expr: SUM(o_totalprice) + comment: "Sum of total price" + - name: Revenue per Customer + expr: SUM(o_totalprice) / COUNT(DISTINCT o_custkey) + comment: "Average revenue per distinct customer" + - name: Open Order Revenue + expr: SUM(o_totalprice) FILTER (WHERE o_orderstatus = 'O') + comment: "Potential revenue from open orders" +$$ +``` + +### Demo queries + +```sql +-- Monthly revenue trend +SELECT + `Order Month`, + MEASURE(`Total Revenue`)::BIGINT AS revenue, + MEASURE(`Order Count`) AS orders +FROM catalog.schema.tpch_orders_metrics +WHERE extract(year FROM `Order Month`) = 1995 +GROUP BY ALL +ORDER BY ALL + +-- Revenue by status +SELECT + `Order Status`, + MEASURE(`Total Revenue`)::BIGINT AS revenue, + MEASURE(`Revenue per Customer`)::BIGINT AS rev_per_customer +FROM catalog.schema.tpch_orders_metrics +GROUP BY ALL + +-- Open orders risk assessment +SELECT + `Order Month`, + MEASURE(`Open Order Revenue`)::BIGINT AS at_risk_revenue, + MEASURE(`Total Revenue`)::BIGINT AS total_revenue +FROM catalog.schema.tpch_orders_metrics +WHERE extract(year FROM `Order Month`) >= 1995 +GROUP BY ALL +ORDER BY ALL +``` + +## Pattern 9: Window Measures (Experimental) + +Window measures enable moving averages, running totals, period-over-period changes, and semiadditive measures. Add a `window` block to any measure definition. See [Window Measures Documentation](https://docs.databricks.com/aws/en/metric-views/data-modeling/window-measures). + +### Window Range Values + +| Range | Description | +|-------|-------------| +| `current` | Only rows where the window ordering value equals the current row | +| `cumulative` | All rows up to and including the current row | +| `trailing ` | N units before the current row (**excludes** current) | +| `leading ` | N units after the current row | +| `all` | All rows regardless of ordering | + +### Trailing Window: 7-Day Distinct Customers + +```sql +CREATE OR REPLACE VIEW catalog.schema.customer_activity +WITH METRICS +LANGUAGE YAML +AS $$ + version: 0.1 + source: catalog.schema.orders + filter: order_date > DATE'2024-01-01' + + dimensions: + - name: date + expr: order_date + + measures: + - name: t7d_customers + expr: COUNT(DISTINCT customer_id) + window: + - order: date + range: trailing 7 day + semiadditive: last +$$ +``` + +**Key:** `trailing 7 day` includes the 7 days **before** each date, **excluding** the current date. `semiadditive: last` returns the last value when the `date` dimension is not in the GROUP BY. + +### Running Total (Cumulative) + +```sql +CREATE OR REPLACE VIEW catalog.schema.cumulative_sales +WITH METRICS +LANGUAGE YAML +AS $$ + version: 0.1 + source: catalog.schema.orders + filter: order_date > DATE'2024-01-01' + + dimensions: + - name: date + expr: order_date + + measures: + - name: running_total_sales + expr: SUM(total_price) + window: + - order: date + range: cumulative + semiadditive: last +$$ +``` + +### Period-Over-Period: Day-Over-Day Growth + +Compose window measures using `MEASURE()` references in derived measures. + +```sql +CREATE OR REPLACE VIEW catalog.schema.daily_growth +WITH METRICS +LANGUAGE YAML +AS $$ + version: 0.1 + source: catalog.schema.orders + filter: order_date > DATE'2024-01-01' + + dimensions: + - name: date + expr: order_date + + measures: + - name: previous_day_sales + expr: SUM(total_price) + window: + - order: date + range: trailing 1 day + semiadditive: last + + - name: current_day_sales + expr: SUM(total_price) + window: + - order: date + range: current + semiadditive: last + + - name: day_over_day_growth + expr: (MEASURE(current_day_sales) - MEASURE(previous_day_sales)) / MEASURE(previous_day_sales) * 100 +$$ +``` + +**Key:** The derived `day_over_day_growth` measure uses `MEASURE()` to reference other window measures. It does NOT need its own `window` block. + +### Year-to-Date (Composing Multiple Windows) + +A single measure can have multiple window specs to create period-to-date calculations. + +```sql +CREATE OR REPLACE VIEW catalog.schema.ytd_metrics +WITH METRICS +LANGUAGE YAML +AS $$ + version: 0.1 + source: catalog.schema.orders + filter: order_date > DATE'2023-01-01' + + dimensions: + - name: date + expr: order_date + - name: year + expr: DATE_TRUNC('year', order_date) + + measures: + - name: ytd_sales + expr: SUM(total_price) + window: + - order: date + range: cumulative + semiadditive: last + - order: year + range: current + semiadditive: last +$$ +``` + +**Key:** The first window does a cumulative sum over `date`. The second window restricts scope to the `current` year. Together they produce year-to-date. + +### Semiadditive Measure: Bank Balance + +For measures like balances that should not be summed across time. + +```sql +CREATE OR REPLACE VIEW catalog.schema.account_balances +WITH METRICS +LANGUAGE YAML +AS $$ + version: 0.1 + source: catalog.schema.daily_balances + + dimensions: + - name: date + expr: date + - name: customer + expr: customer_id + + measures: + - name: balance + expr: SUM(balance) + window: + - order: date + range: current + semiadditive: last +$$ +``` + +**Key:** `semiadditive: last` prevents summing across dates (returns the last date's value instead), but the measure **still aggregates across other dimensions** like `customer`. When grouped by date, you get total balance across all customers for that day. When not grouped by date, you get the balance from the most recent date. + +### Query window measures + +Window measures are queried with the same `MEASURE()` syntax: + +```sql +SELECT + date, + MEASURE(t7d_customers) AS trailing_7d_customers, + MEASURE(running_total_sales) AS running_total +FROM catalog.schema.customer_activity +WHERE date >= DATE'2024-06-01' +GROUP BY ALL +ORDER BY ALL +``` + +## MCP Tool Examples + +### Create with joins + +```python +manage_metric_views( + action="create", + full_name="catalog.schema.sales_metrics", + source="catalog.schema.fact_sales", + or_replace=True, + joins=[ + { + "name": "customer", + "source": "catalog.schema.dim_customer", + "on": "source.customer_id = customer.id" + }, + { + "name": "product", + "source": "catalog.schema.dim_product", + "on": "source.product_id = product.id" + } + ], + dimensions=[ + {"name": "Customer Segment", "expr": "customer.segment"}, + {"name": "Product Category", "expr": "product.category"}, + {"name": "Sale Month", "expr": "DATE_TRUNC('MONTH', source.sale_date)"}, + ], + measures=[ + {"name": "Total Revenue", "expr": "SUM(source.amount)"}, + {"name": "Order Count", "expr": "COUNT(1)"}, + {"name": "Unique Customers", "expr": "COUNT(DISTINCT source.customer_id)"}, + ], +) +``` + +### Alter to add a new measure + +```python +manage_metric_views( + action="alter", + full_name="catalog.schema.sales_metrics", + source="catalog.schema.fact_sales", + joins=[ + {"name": "customer", "source": "catalog.schema.dim_customer", "on": "source.customer_id = customer.id"}, + ], + dimensions=[ + {"name": "Customer Segment", "expr": "customer.segment"}, + {"name": "Sale Month", "expr": "DATE_TRUNC('MONTH', source.sale_date)"}, + ], + measures=[ + {"name": "Total Revenue", "expr": "SUM(source.amount)"}, + {"name": "Order Count", "expr": "COUNT(1)"}, + {"name": "Average Order Value", "expr": "AVG(source.amount)"}, # New measure + ], +) +``` + +### Query with filters + +```python +manage_metric_views( + action="query", + full_name="catalog.schema.sales_metrics", + query_measures=["Total Revenue", "Order Count"], + query_dimensions=["Customer Segment", "Sale Month"], + where="`Customer Segment` = 'Enterprise'", + order_by="ALL", + limit=50, +) +``` diff --git a/.claude/skills/databricks-metric-views/yaml-reference.md b/.claude/skills/databricks-metric-views/yaml-reference.md new file mode 100644 index 00000000..2e5973c0 --- /dev/null +++ b/.claude/skills/databricks-metric-views/yaml-reference.md @@ -0,0 +1,338 @@ +# Metric View YAML Reference + +Complete reference for the YAML specification used in Unity Catalog metric views. + +## Top-Level Fields + +| Field | Required | Type | Description | +|-------|----------|------|-------------| +| `version` | No | string | YAML spec version. `"1.1"` for DBR 17.2+, `"0.1"` for DBR 16.4-17.1. Defaults to `1.1`. | +| `source` | Yes | string | Source table, view, or SQL query in three-level namespace format. | +| `comment` | No | string | Description of the metric view (v1.1+). | +| `filter` | No | string | SQL boolean expression applied as a global WHERE clause. | +| `dimensions` | Yes | list | Array of dimension definitions (at least one). | +| `measures` | Yes | list | Array of measure definitions (at least one). | +| `joins` | No | list | Star/snowflake schema join definitions. | +| `materialization` | No | object | Pre-computation configuration (experimental). | + +## Dimensions + +Dimensions define the categorical attributes used to group and filter data. + +```yaml +dimensions: + - name: Region # Display name, backtick-quoted in queries + expr: region_name # Direct column reference + comment: "Sales region" # Optional description (v1.1+) + + - name: Order Month + expr: DATE_TRUNC('MONTH', order_date) # SQL transformation + + - name: Order Year + expr: EXTRACT(YEAR FROM `Order Month`) # Can reference other dimensions + + - name: Customer Type + expr: CASE + WHEN customer_tier = 'A' THEN 'Enterprise' + WHEN customer_tier = 'B' THEN 'Mid-Market' + ELSE 'SMB' + END # Multi-line CASE expressions supported + + - name: Nation + expr: customer.c_name # Reference joined table columns +``` + +### Dimension Rules + +- `name` is required and becomes the column name in queries (backtick-quoted if it has spaces) +- `expr` is required and must be a valid SQL expression +- Can reference source columns, SQL functions, CASE expressions, and other dimensions +- Can reference columns from joined tables using `join_name.column_name` +- Cannot use aggregate functions (those belong in measures) + +## Measures + +Measures define aggregated values computed at query time. + +```yaml +measures: + - name: Total Revenue + expr: SUM(total_price) + comment: "Sum of all order prices" + + - name: Order Count + expr: COUNT(1) + + - name: Average Order Value + expr: AVG(total_price) + + - name: Unique Customers + expr: COUNT(DISTINCT customer_id) + + - name: Revenue per Customer # Ratio measure + expr: SUM(total_price) / COUNT(DISTINCT customer_id) + + - name: Open Order Revenue # Filtered measure + expr: SUM(total_price) FILTER (WHERE status = 'O') + comment: "Revenue from open orders only" + + - name: Open Revenue per Customer # Filtered ratio + expr: SUM(total_price) FILTER (WHERE status = 'O') / COUNT(DISTINCT customer_id) FILTER (WHERE status = 'O') +``` + +### Window Measures (Experimental) + +Add a `window` block to a measure for windowed, cumulative, or semiadditive aggregations. See [Window Measures Documentation](https://docs.databricks.com/aws/en/metric-views/data-modeling/window-measures). + +```yaml +measures: + - name: Running Total + expr: SUM(total_price) + window: + - order: date # Dimension that orders the window + range: cumulative # Window extent (see range values below) + semiadditive: last # How to summarize when order dim is not in GROUP BY + + - name: 7-Day Customers + expr: COUNT(DISTINCT customer_id) + window: + - order: date + range: trailing 7 day # 7 days before current, EXCLUDING current day + semiadditive: last +``` + +**Window range values:** + +| Range | Description | +|-------|-------------| +| `current` | Only rows matching the current ordering value | +| `cumulative` | All rows up to and including the current row | +| `trailing ` | N units before current row (excludes current) | +| `leading ` | N units after current row | +| `all` | All rows | + +**Window spec fields:** + +| Field | Required | Description | +|-------|----------|-------------| +| `order` | Yes | Dimension name that determines window ordering | +| `range` | Yes | Window extent (see values above) | +| `semiadditive` | Yes | `first` or `last` - value to use when order dimension is absent from GROUP BY | + +**Multiple windows** can be composed on a single measure (e.g., for year-to-date): + +```yaml + - name: ytd_sales + expr: SUM(total_price) + window: + - order: date + range: cumulative + semiadditive: last + - order: year + range: current + semiadditive: last +``` + +**Derived measures** can reference window measures using `MEASURE()`: + +```yaml + - name: day_over_day_growth + expr: (MEASURE(current_day_sales) - MEASURE(previous_day_sales)) / MEASURE(previous_day_sales) * 100 +``` + +### Measure Rules + +- `name` is required and queried via `MEASURE(\`name\`)` +- `expr` must contain an aggregate function (SUM, COUNT, AVG, MIN, MAX, etc.) +- Supports `FILTER (WHERE ...)` for conditional aggregation +- Supports ratios of aggregates +- Derived measures can reference other measures via `MEASURE()` (used with window measures) +- Window measures use `version: 0.1` (experimental feature) +- `SELECT *` on metric views is NOT supported; must use `MEASURE()` explicitly + +## Joins + +### Star Schema (Single Level) + +```yaml +source: catalog.schema.fact_orders +joins: + - name: customer + source: catalog.schema.dim_customer + on: source.customer_id = customer.id + + - name: product + source: catalog.schema.dim_product + on: source.product_id = product.id +``` + +### Star Schema with USING + +```yaml +joins: + - name: customer + source: catalog.schema.dim_customer + using: + - customer_id + - region_id +``` + +### Snowflake Schema (Nested Joins, DBR 17.1+) + +```yaml +source: catalog.schema.orders +joins: + - name: customer + source: catalog.schema.customer + on: source.customer_id = customer.id + joins: + - name: nation + source: catalog.schema.nation + on: customer.nation_id = nation.id + joins: + - name: region + source: catalog.schema.region + on: nation.region_id = region.id +``` + +### Join Rules + +- `name` is required and used to reference joined columns: `name.column` +- `source` is the fully qualified table/view name +- Use either `on` (expression) or `using` (column list), not both +- In `on`, reference the fact table as `source` and join tables by their `name` +- Nested `joins` create snowflake schema (requires DBR 17.1+) +- Joined tables cannot include MAP type columns + +## Filter + +A global filter applied to all queries as a WHERE clause. + +```yaml +filter: order_date > '2020-01-01' + +# Multiple conditions +filter: order_date > '2020-01-01' AND status != 'CANCELLED' + +# Using joined columns +filter: customer.active = true +``` + +## Materialization (Experimental) + +Pre-compute aggregations for faster query performance. Uses Lakeflow Spark Declarative Pipelines under the hood. + +```yaml +materialization: + schedule: every 6 hours # Same syntax as MV schedule clause + mode: relaxed # Only "relaxed" supported currently + + materialized_views: + - name: baseline + type: unaggregated # Full unaggregated data model + + - name: revenue_breakdown + type: aggregated # Pre-computed aggregation + dimensions: + - category + - region + measures: + - total_revenue + - order_count + + - name: daily_summary + type: aggregated + dimensions: + - order_date + measures: + - total_revenue +``` + +### Materialization Types + +| Type | Description | When to Use | +|------|-------------|-------------| +| `unaggregated` | Materializes full data model (source + joins + filter) | Expensive source views or many joins | +| `aggregated` | Pre-computes specific dimension/measure combos | Frequently queried combinations | + +### Materialization Requirements + +- Serverless compute must be enabled +- Databricks Runtime 17.2+ +- `TRIGGER ON UPDATE` clause is not supported +- Schedule uses same syntax as materialized view schedules + +### Refresh Materialization + +```python +# Find and refresh the pipeline +from databricks.sdk import WorkspaceClient +w = WorkspaceClient() +pipeline_id = "your-pipeline-id" +w.pipelines.start_update(pipeline_id) +``` + +## Complete Example + +```sql +CREATE OR REPLACE VIEW catalog.schema.sales_metrics +WITH METRICS +LANGUAGE YAML +AS $$ + version: 1.1 + comment: "Comprehensive sales metrics with customer and product dimensions" + source: catalog.schema.fact_sales + filter: sale_date >= '2023-01-01' + + joins: + - name: customer + source: catalog.schema.dim_customer + on: source.customer_id = customer.id + joins: + - name: region + source: catalog.schema.dim_region + on: customer.region_id = region.id + - name: product + source: catalog.schema.dim_product + on: source.product_id = product.id + + dimensions: + - name: Sale Month + expr: DATE_TRUNC('MONTH', sale_date) + comment: "Month of sale" + - name: Customer Name + expr: customer.name + - name: Region + expr: region.name + comment: "Geographic region" + - name: Product Category + expr: product.category + + measures: + - name: Total Revenue + expr: SUM(amount) + comment: "Sum of sale amounts" + - name: Transaction Count + expr: COUNT(1) + - name: Unique Customers + expr: COUNT(DISTINCT customer_id) + - name: Average Transaction + expr: AVG(amount) + - name: Revenue per Customer + expr: SUM(amount) / COUNT(DISTINCT customer_id) + comment: "Average revenue per unique customer" + + materialization: + schedule: every 1 hour + mode: relaxed + materialized_views: + - name: hourly_region + type: aggregated + dimensions: + - Sale Month + - Region + measures: + - Total Revenue + - Transaction Count +$$ +``` diff --git a/.claude/skills/databricks-mlflow-evaluation/SKILL.md b/.claude/skills/databricks-mlflow-evaluation/SKILL.md new file mode 100644 index 00000000..45db5f61 --- /dev/null +++ b/.claude/skills/databricks-mlflow-evaluation/SKILL.md @@ -0,0 +1,148 @@ +--- +name: databricks-mlflow-evaluation +description: "MLflow 3 GenAI agent evaluation. Use when writing mlflow.genai.evaluate() code, creating @scorer functions, using built-in scorers (Guidelines, Correctness, Safety, RetrievalGroundedness), building eval datasets from traces, setting up trace ingestion and production monitoring, aligning judges with MemAlign from domain expert feedback, or running optimize_prompts() with GEPA for automated prompt improvement." +--- + +# MLflow 3 GenAI Evaluation + +## Before Writing Any Code + +1. **Read GOTCHAS.md** - 15+ common mistakes that cause failures +2. **Read CRITICAL-interfaces.md** - Exact API signatures and data schemas + +## End-to-End Workflows + +Follow these workflows based on your goal. Each step indicates which reference files to read. + +### Workflow 1: First-Time Evaluation Setup + +For users new to MLflow GenAI evaluation or setting up evaluation for a new agent. + +| Step | Action | Reference Files | +|------|--------|-----------------| +| 1 | Understand what to evaluate | `user-journeys.md` (Journey 0: Strategy) | +| 2 | Learn API patterns | `GOTCHAS.md` + `CRITICAL-interfaces.md` | +| 3 | Build initial dataset | `patterns-datasets.md` (Patterns 1-4) | +| 4 | Choose/create scorers | `patterns-scorers.md` + `CRITICAL-interfaces.md` (built-in list) | +| 5 | Run evaluation | `patterns-evaluation.md` (Patterns 1-3) | + +### Workflow 2: Production Trace -> Evaluation Dataset + +For building evaluation datasets from production traces. + +| Step | Action | Reference Files | +|------|--------|-----------------| +| 1 | Search and filter traces | `patterns-trace-analysis.md` (MCP tools section) | +| 2 | Analyze trace quality | `patterns-trace-analysis.md` (Patterns 1-7) | +| 3 | Tag traces for inclusion | `patterns-datasets.md` (Patterns 16-17) | +| 4 | Build dataset from traces | `patterns-datasets.md` (Patterns 6-7) | +| 5 | Add expectations/ground truth | `patterns-datasets.md` (Pattern 2) | + +### Workflow 3: Performance Optimization + +For debugging slow or expensive agent execution. + +| Step | Action | Reference Files | +|------|--------|-----------------| +| 1 | Profile latency by span | `patterns-trace-analysis.md` (Patterns 4-6) | +| 2 | Analyze token usage | `patterns-trace-analysis.md` (Pattern 9) | +| 3 | Detect context issues | `patterns-context-optimization.md` (Section 5) | +| 4 | Apply optimizations | `patterns-context-optimization.md` (Sections 1-4, 6) | +| 5 | Re-evaluate to measure impact | `patterns-evaluation.md` (Pattern 6-7) | + +### Workflow 4: Regression Detection + +For comparing agent versions and finding regressions. + +| Step | Action | Reference Files | +|------|--------|-----------------| +| 1 | Establish baseline | `patterns-evaluation.md` (Pattern 4: named runs) | +| 2 | Run current version | `patterns-evaluation.md` (Pattern 1) | +| 3 | Compare metrics | `patterns-evaluation.md` (Patterns 6-7) | +| 4 | Analyze failing traces | `patterns-trace-analysis.md` (Pattern 7) | +| 5 | Debug specific failures | `patterns-trace-analysis.md` (Patterns 8-9) | + +### Workflow 5: Custom Scorer Development + +For creating project-specific evaluation metrics. + +| Step | Action | Reference Files | +|------|--------|-----------------| +| 1 | Understand scorer interface | `CRITICAL-interfaces.md` (Scorer section) | +| 2 | Choose scorer pattern | `patterns-scorers.md` (Patterns 4-11) | +| 3 | For multi-agent scorers | `patterns-scorers.md` (Patterns 13-16) | +| 4 | Test with evaluation | `patterns-evaluation.md` (Pattern 1) | + +### Workflow 6: Unity Catalog Trace Ingestion & Production Monitoring + +For storing traces in Unity Catalog, instrumenting applications, and enabling continuous production monitoring. + +| Step | Action | Reference Files | +|------|--------|-----------------| +| 1 | Link UC schema to experiment | `patterns-trace-ingestion.md` (Patterns 1-2) | +| 2 | Set trace destination | `patterns-trace-ingestion.md` (Patterns 3-4) | +| 3 | Instrument your application | `patterns-trace-ingestion.md` (Patterns 5-8) | +| 4 | Configure trace sources (Apps/Serving/OTEL) | `patterns-trace-ingestion.md` (Patterns 9-11) | +| 5 | Enable production monitoring | `patterns-trace-ingestion.md` (Patterns 12-13) | +| 6 | Query and analyze UC traces | `patterns-trace-ingestion.md` (Pattern 14) | + +### Workflow 7: Judge Alignment with MemAlign + +For aligning an LLM judge to match domain expert preferences. A well-aligned judge improves every downstream use: evaluation accuracy, production monitoring signal, and prompt optimization quality. This workflow is valuable on its own, independent of prompt optimization. + +| Step | Action | Reference Files | +|------|--------|-----------------| +| 1 | Design base judge with `make_judge` (any feedback type) | `patterns-judge-alignment.md` (Pattern 1) | +| 2 | Run evaluate(), tag successful traces | `patterns-judge-alignment.md` (Pattern 2) | +| 3 | Build UC dataset + create SME labeling session | `patterns-judge-alignment.md` (Pattern 3) | +| 4 | Align judge with MemAlign after labeling completes | `patterns-judge-alignment.md` (Pattern 4) | +| 5 | Register aligned judge to experiment | `patterns-judge-alignment.md` (Pattern 5) | +| 6 | Re-evaluate with aligned judge (baseline) | `patterns-judge-alignment.md` (Pattern 6) | + +### Workflow 8: Automated Prompt Optimization with GEPA + +For automatically improving a registered system prompt using `optimize_prompts()`. Works with any scorer, but paired with an aligned judge (Workflow 7) gives the most domain-accurate signal. For the full end-to-end loop combining alignment and optimization, see `user-journeys.md` Journey 10. + +| Step | Action | Reference Files | +|------|--------|-----------------| +| 1 | Build optimization dataset (inputs + expectations) | `patterns-prompt-optimization.md` (Pattern 1) | +| 2 | Run optimize_prompts() with GEPA + scorer | `patterns-prompt-optimization.md` (Pattern 2) | +| 3 | Register new version, promote conditionally | `patterns-prompt-optimization.md` (Pattern 3) | + +## Reference Files Quick Lookup + +| Reference | Purpose | When to Read | +|-----------|---------|--------------| +| `GOTCHAS.md` | Common mistakes | **Always read first** before writing code | +| `CRITICAL-interfaces.md` | API signatures, schemas | When writing any evaluation code | +| `patterns-evaluation.md` | Running evals, comparing | When executing evaluations | +| `patterns-scorers.md` | Custom scorer creation | When built-in scorers aren't enough | +| `patterns-datasets.md` | Dataset building | When preparing evaluation data | +| `patterns-trace-analysis.md` | Trace debugging | When analyzing agent behavior | +| `patterns-context-optimization.md` | Token/latency fixes | When agent is slow or expensive | +| `patterns-trace-ingestion.md` | UC trace setup, monitoring | When setting up trace storage or production monitoring | +| `patterns-judge-alignment.md` | MemAlign judge alignment, labeling sessions, SME feedback | When aligning judges to domain expert preferences | +| `patterns-prompt-optimization.md` | GEPA optimization: build dataset, optimize_prompts(), promote | When running automated prompt improvement | +| `user-journeys.md` | High-level workflows, full domain-expert optimization loop | When starting a new evaluation project or running the full align + optimize cycle | + +## Critical API Facts + +- **Use:** `mlflow.genai.evaluate()` (NOT `mlflow.evaluate()`) +- **Data format:** `{"inputs": {"query": "..."}}` (nested structure required) +- **predict_fn:** Receives `**unpacked kwargs` (not a dict) +- **MemAlign:** Scorer-agnostic (works with any `feedback_value_type` -- float, bool, categorical); token-heavy on the embedding model so set `embedding_model` explicitly +- **Label schema name matching:** The label schema `name` in the labeling session MUST match the judge `name` used in `evaluate()` for `align()` to pair scores +- **Aligned judge scores:** May be lower than unaligned judge scores -- this is expected and means the judge is now more accurate, not that the agent regressed +- **GEPA optimization dataset:** Must have both `inputs` AND `expectations` per record (different from eval dataset) +- **Episodic memory:** Lazily loaded -- `get_scorer()` results won't show episodic memory on print until the judge is first used +- **optimize_prompts:** Requires MLflow >= 3.5.0 + +See `GOTCHAS.md` for complete list. + +## Related Skills + +- **[databricks-docs](../databricks-docs/SKILL.md)** - General Databricks documentation reference +- **[databricks-model-serving](../databricks-model-serving/SKILL.md)** - Deploying models and agents to serving endpoints +- **[databricks-agent-bricks](../databricks-agent-bricks/SKILL.md)** - Building agents that can be evaluated with this skill +- **[databricks-python-sdk](../databricks-python-sdk/SKILL.md)** - SDK patterns used alongside MLflow APIs +- **[databricks-unity-catalog](../databricks-unity-catalog/SKILL.md)** - Unity Catalog tables for managed evaluation datasets diff --git a/.claude/skills/mlflow-evaluation/references/CRITICAL-interfaces.md b/.claude/skills/databricks-mlflow-evaluation/references/CRITICAL-interfaces.md similarity index 87% rename from .claude/skills/mlflow-evaluation/references/CRITICAL-interfaces.md rename to .claude/skills/databricks-mlflow-evaluation/references/CRITICAL-interfaces.md index d1b4a1b1..30babcea 100644 --- a/.claude/skills/mlflow-evaluation/references/CRITICAL-interfaces.md +++ b/.claude/skills/databricks-mlflow-evaluation/references/CRITICAL-interfaces.md @@ -12,6 +12,7 @@ - [Judges API (Low-level)](#judges-api-low-level) - [Trace APIs](#trace-apis) - [Evaluation Datasets (MLflow-managed)](#evaluation-datasets-mlflow-managed) +- [Trace Ingestion in Unity Catalog](#trace-ingestion-in-unity-catalog) - [Production Monitoring](#production-monitoring) - [Key Constants](#key-constants) - [Installation](#installation) @@ -385,8 +386,68 @@ results = mlflow.genai.evaluate( --- +## Trace Ingestion in Unity Catalog + +**Version**: MLflow 3.9.0+ (`mlflow[databricks]>=3.9.0`) + +### Setup - Link UC Schema to Experiment +```python +import os +import mlflow +from mlflow.entities import UCSchemaLocation +from mlflow.tracing.enablement import set_experiment_trace_location + +mlflow.set_tracking_uri("databricks") +os.environ["MLFLOW_TRACING_SQL_WAREHOUSE_ID"] = "" + +experiment_id = mlflow.create_experiment(name="/Shared/my-traces") + +set_experiment_trace_location( + location=UCSchemaLocation( + catalog_name="", + schema_name="" + ), + experiment_id=experiment_id, +) +# Creates: mlflow_experiment_trace_otel_logs, _metrics, _spans +``` + +### Set Trace Destination +```python +# Option A: Python API +from mlflow.entities import UCSchemaLocation +mlflow.tracing.set_destination( + destination=UCSchemaLocation( + catalog_name="", + schema_name="", + ) +) + +# Option B: Environment variable +os.environ["MLFLOW_TRACING_DESTINATION"] = "." +``` + +### Permissions Required +- `USE_CATALOG` on catalog +- `USE_SCHEMA` on schema +- `MODIFY` and `SELECT` on each `mlflow_experiment_trace_*` table +- **CRITICAL**: `ALL_PRIVILEGES` is NOT sufficient + +--- + ## Production Monitoring +### Configure Monitoring SQL Warehouse +```python +from mlflow.tracing import set_databricks_monitoring_sql_warehouse_id + +set_databricks_monitoring_sql_warehouse_id( + warehouse_id="", + experiment_id="" # Optional +) +# Alternative: os.environ["MLFLOW_TRACING_SQL_WAREHOUSE_ID"] = "" +``` + ### Register and Start Scorer ```python from mlflow.genai.scorers import Safety, Guidelines, ScorerSamplingConfig diff --git a/.claude/skills/mlflow-evaluation/references/GOTCHAS.md b/.claude/skills/databricks-mlflow-evaluation/references/GOTCHAS.md similarity index 54% rename from .claude/skills/mlflow-evaluation/references/GOTCHAS.md rename to .claude/skills/databricks-mlflow-evaluation/references/GOTCHAS.md index fc40d97b..4e468035 100644 --- a/.claude/skills/mlflow-evaluation/references/GOTCHAS.md +++ b/.claude/skills/databricks-mlflow-evaluation/references/GOTCHAS.md @@ -23,6 +23,15 @@ - [Wrong Production Monitoring Setup](#-wrong-production-monitoring-setup) - [Wrong Custom Judge Model Format](#-wrong-custom-judge-model-format) - [Wrong Aggregation Values](#-wrong-aggregation-values) +- [Wrong Trace Ingestion Setup](#-wrong-trace-ingestion-setup) +- [Wrong Trace Destination Format](#-wrong-trace-destination-format) +- [Wrong MLflow Version for Trace Ingestion](#-wrong-mlflow-version-for-trace-ingestion) +- [Wrong Linking UC Schema Without SQL Warehouse](#-wrong-linking-uc-schema-without-sql-warehouse) +- [Wrong Label Schema Name — Alignment Will Fail](#-wrong-label-schema-name--alignment-will-fail) +- [Wrong Aligned Judge Score Interpretation](#-wrong-aligned-judge-score-interpretation) +- [Wrong MemAlign Embedding Model — Token Costs](#-wrong-memalign-embedding-model--token-costs) +- [Wrong MemAlign Episodic Memory — Lazy Loading](#-wrong-memalign-episodic-memory--lazy-loading) +- [Wrong GEPA Optimization Dataset — Missing expectations](#-wrong-gepa-optimization-dataset--missing-expectations) - [Summary Checklist](#summary-checklist) --- @@ -530,6 +539,253 @@ def my_scorer(outputs) -> float: --- +## ❌ WRONG Trace Ingestion Setup + +### WRONG: Using ALL_PRIVILEGES instead of explicit grants +```sql +-- ❌ WRONG - ALL_PRIVILEGES does NOT include required permissions +GRANT ALL_PRIVILEGES ON TABLE my_catalog.my_schema.mlflow_experiment_trace_otel_spans + TO `user@company.com`; +``` + +### ✅ CORRECT: Grant explicit MODIFY and SELECT +```sql +-- ✅ CORRECT - Explicit MODIFY and SELECT required +GRANT MODIFY, SELECT ON TABLE my_catalog.my_schema.mlflow_experiment_trace_otel_spans + TO `user@company.com`; +GRANT MODIFY, SELECT ON TABLE my_catalog.my_schema.mlflow_experiment_trace_otel_logs + TO `user@company.com`; +GRANT MODIFY, SELECT ON TABLE my_catalog.my_schema.mlflow_experiment_trace_otel_metrics + TO `user@company.com`; +``` + +--- + +## ❌ WRONG Trace Destination Format + +### WRONG: Wrong format for environment variable +```python +# ❌ WRONG - Missing schema or wrong separator +os.environ["MLFLOW_TRACING_DESTINATION"] = "my_catalog" +os.environ["MLFLOW_TRACING_DESTINATION"] = "my_catalog/my_schema" +``` + +### ✅ CORRECT: Use catalog.schema format +```python +# ✅ CORRECT - Dot-separated catalog.schema +os.environ["MLFLOW_TRACING_DESTINATION"] = "my_catalog.my_schema" +``` + +--- + +## ❌ WRONG MLflow Version for Trace Ingestion + +### WRONG: Using MLflow < 3.9.0 for UC trace ingestion +```bash +# ❌ WRONG - Trace ingestion requires 3.9.0+ +pip install mlflow[databricks]>=3.1.0 +``` + +### ✅ CORRECT: Use MLflow 3.9.0+ for UC traces +```bash +# ✅ CORRECT +pip install "mlflow[databricks]>=3.9.0" --upgrade --force-reinstall +``` + +--- + +## ❌ WRONG Linking UC Schema Without SQL Warehouse + +### WRONG: Missing SQL warehouse configuration +```python +# ❌ WRONG - No SQL warehouse configured +mlflow.set_tracking_uri("databricks") +# Missing: os.environ["MLFLOW_TRACING_SQL_WAREHOUSE_ID"] = "..." +set_experiment_trace_location(location=UCSchemaLocation(...), ...) +``` + +### ✅ CORRECT: Set SQL warehouse before linking +```python +# ✅ CORRECT - Set warehouse ID first +mlflow.set_tracking_uri("databricks") +os.environ["MLFLOW_TRACING_SQL_WAREHOUSE_ID"] = "" +set_experiment_trace_location(location=UCSchemaLocation(...), ...) +``` + +--- + +## ❌ WRONG Label Schema Name — Alignment Will Fail + +### WRONG: Label schema name does not match the judge name used in evaluate() +```python +# ❌ WRONG - Judge name and label schema name don't match +# Judge is registered as "domain_quality_base" in evaluate() +domain_quality_judge = make_judge(name="domain_quality_base", ...) +registered_base_judge = domain_quality_judge.register(experiment_id=EXPERIMENT_ID) + +# But label schema uses a different name +feedback_schema = label_schemas.create_label_schema( + name="domain_quality_rating", # ❌ Does not match judge name + type="feedback", + ... +) +# align() will not be able to pair SME feedback with LLM judge scores +``` + +### ✅ CORRECT: Label schema name matches the judge name exactly +```python +# ✅ CORRECT - Judge name and label schema name are identical +JUDGE_NAME = "domain_quality_base" + +domain_quality_judge = make_judge(name=JUDGE_NAME, ...) +registered_base_judge = domain_quality_judge.register(experiment_id=EXPERIMENT_ID) + +feedback_schema = label_schemas.create_label_schema( + name=JUDGE_NAME, # ✅ Matches judge name exactly + type="feedback", + ... +) +``` + +**Why?** The `align()` function pairs SME feedback with LLM judge scores by matching the label schema name to the judge name on the same traces. If the names differ, `align()` cannot find the corresponding score pairs and alignment will fail or produce incorrect results. + +--- + +## ❌ WRONG Aligned Judge Score Interpretation + +### WRONG: Assuming a lower aligned judge score means the agent got worse +```python +# ❌ WRONG interpretation - panicking because aligned judge gives lower scores +# Unaligned judge: 4.2/5.0 average +# Aligned judge: 3.1/5.0 average +# "The agent regressed!" — No, the judge got more accurate. +``` + +### ✅ CORRECT: Understanding that a lower aligned score reflects more accurate evaluation +```python +# ✅ CORRECT interpretation +# The aligned judge now evaluates with domain-expert standards rather than generic best practices. +# A lower score from a more accurate judge is a better signal than an inflated score from +# a judge that doesn't understand your domain. The unaligned judge was underspecified. +# Use optimize_prompts() with the aligned judge to improve the agent against this standard. +``` + +**Why?** An unaligned judge evaluates against generic best practices and often gives inflated scores. Once aligned with SME feedback, the judge applies domain-specific criteria that are harder to satisfy. The lower score is not a regression in agent quality; it is a more honest assessment. The optimization phase (`optimize_prompts()`) will then improve the agent against this more accurate standard. + +--- + +## ❌ WRONG MemAlign Embedding Model — Token Costs + +### WRONG: Using the default embedding model without awareness of cost +```python +# ❌ COSTLY - Default embedding model may be expensive for large trace sets +optimizer = MemAlignOptimizer( + reflection_lm=REFLECTION_MODEL, + retrieval_k=5, + # No embedding_model specified → defaults to "openai/text-embedding-3-small" +) +``` + +### ✅ CORRECT: Use a Databricks-hosted embedding model or size your trace set accordingly +```python +# ✅ CORRECT - Use a hosted model to control costs; scope trace set to labeled traces only +optimizer = MemAlignOptimizer( + reflection_lm=REFLECTION_MODEL, + retrieval_k=5, + embedding_model="databricks:/databricks-gte-large-en", +) + +# ✅ ALSO CORRECT - Filter to only labeled/tagged traces, not all experiment traces +traces = mlflow.search_traces( + locations=[EXPERIMENT_ID], + filter_string="tag.eval = 'complete'", # Scope to relevant traces only + return_type="list", +) +aligned_judge = base_judge.align(traces=traces, optimizer=optimizer) +``` + +**Why?** MemAlign embeds every trace for retrieval (`retrieval_k` nearest neighbors per evaluation). Large trace sets with an expensive embedding model multiply quickly. Databricks-hosted models (`databricks:/databricks-gte-large-en`) keep costs on-platform. + +--- + +## ❌ WRONG MemAlign Episodic Memory — Lazy Loading + +### WRONG: Expecting episodic memory to be populated immediately after get_scorer() +```python +# ❌ WRONG - Episodic memory appears empty, looks like alignment didn't work +retrieved_judge = get_scorer(name="domain_quality_base", experiment_id=EXPERIMENT_ID) +print(retrieved_judge._episodic_memory) # Prints: [] — misleading! +print(retrieved_judge._semantic_memory) # Prints: [] — also empty! +``` + +### ✅ CORRECT: Episodic memory is lazily loaded — use the judge first, then inspect +```python +# ✅ CORRECT - Semantic guidelines ARE loaded; episodic memory loads on first use +retrieved_judge = get_scorer(name="domain_quality_base", experiment_id=EXPERIMENT_ID) + +# The instructions field already contains the distilled guidelines — inspect this instead +print(retrieved_judge.instructions) # ✅ Shows full aligned instructions with guidelines + +# To verify episodic memory, run the judge on a sample first, then inspect +# Memory loads lazily when the judge retrieves similar examples during scoring +``` + +**Why?** MemAlign's episodic memory (stored examples) is loaded on-demand when the judge needs to retrieve similar examples at scoring time. The `_episodic_memory` list is empty on deserialization. The aligned `instructions` field (which includes distilled semantic guidelines) is the reliable thing to inspect after `get_scorer()`. + +--- + +## ❌ WRONG GEPA Optimization Dataset — Missing expectations + +### WRONG: Using eval-style dataset (inputs only) for optimize_prompts() +```python +# ❌ WRONG - GEPA requires expectations; optimization will fail or produce poor results +optimization_dataset = [ + {"inputs": {"input": [{"role": "user", "content": "How does the offense attack the blitz?"}]}}, + {"inputs": {"input": [{"role": "user", "content": "What are 3rd down tendencies?"}]}}, +] + +result = mlflow.genai.optimize_prompts( + predict_fn=predict_fn, + train_data=optimization_dataset, # ❌ Missing expectations + prompt_uris=[prompt.uri], + optimizer=GepaPromptOptimizer(...), + scorers=[aligned_judge], +) +``` + +### ✅ CORRECT: Include expectations in every optimization dataset record +```python +# ✅ CORRECT - Each record must have both inputs AND expectations +optimization_dataset = [ + { + "inputs": { + "input": [{"role": "user", "content": "How does the offense attack the blitz?"}] + }, + "expectations": { + "expected_response": ( + "The agent should analyze blitz performance metrics, compare success " + "rates across pressure packages, and provide concrete tactical recommendations." + ) + } + }, + { + "inputs": { + "input": [{"role": "user", "content": "What are 3rd down tendencies?"}] + }, + "expectations": { + "expected_response": ( + "The agent should call the appropriate tool with down=3 parameters, " + "summarize the play distribution, and give defensive recommendations." + ) + } + }, +] +``` + +**Why?** GEPA uses the `expectations` field during reflection — it compares the agent's output against the expected behavior to generate targeted prompt improvement suggestions. Without `expectations`, GEPA cannot reason about *why* the current prompt is underperforming. This is the most common cause of poor optimization results. + +--- + ## Summary Checklist Before running evaluation, verify: @@ -545,3 +801,14 @@ Before running evaluation, verify: - [ ] Production scorers have inline imports - [ ] Multiple Feedbacks have unique names - [ ] Aggregations use valid names: min, max, mean, median, variance, p90 +- [ ] UC trace ingestion uses `mlflow[databricks]>=3.9.0` +- [ ] UC tables have explicit MODIFY + SELECT grants (not ALL_PRIVILEGES) +- [ ] `MLFLOW_TRACING_SQL_WAREHOUSE_ID` set before linking UC schema +- [ ] `MLFLOW_TRACING_DESTINATION` uses `catalog.schema` format (dot-separated) +- [ ] Production monitoring scorers are both registered AND started +- [ ] MemAlign `embedding_model` can be explicitly set (don't rely on default for large trace sets) +- [ ] After `get_scorer()` for a MemAlign judge, inspect `.instructions` not `._episodic_memory` as episodic memory is lazily loaded +- [ ] GEPA `train_data` has both `inputs` AND `expectations` per record +- [ ] Label schema `name` matches the judge `name` used in `evaluate()` (required for `align()` to pair scores) +- [ ] Aligned judge scores may be lower than unaligned — this is expected if the judge is now more accurate +- [ ] MemAlign is scorer-agnostic (works with any `feedback_value_type` — float, bool, categorical) diff --git a/.claude/skills/mlflow-evaluation/references/patterns-context-optimization.md b/.claude/skills/databricks-mlflow-evaluation/references/patterns-context-optimization.md similarity index 100% rename from .claude/skills/mlflow-evaluation/references/patterns-context-optimization.md rename to .claude/skills/databricks-mlflow-evaluation/references/patterns-context-optimization.md diff --git a/.claude/skills/mlflow-evaluation/references/patterns-datasets.md b/.claude/skills/databricks-mlflow-evaluation/references/patterns-datasets.md similarity index 100% rename from .claude/skills/mlflow-evaluation/references/patterns-datasets.md rename to .claude/skills/databricks-mlflow-evaluation/references/patterns-datasets.md diff --git a/.claude/skills/mlflow-evaluation/references/patterns-evaluation.md b/.claude/skills/databricks-mlflow-evaluation/references/patterns-evaluation.md similarity index 100% rename from .claude/skills/mlflow-evaluation/references/patterns-evaluation.md rename to .claude/skills/databricks-mlflow-evaluation/references/patterns-evaluation.md diff --git a/.claude/skills/databricks-mlflow-evaluation/references/patterns-judge-alignment.md b/.claude/skills/databricks-mlflow-evaluation/references/patterns-judge-alignment.md new file mode 100644 index 00000000..c59989a9 --- /dev/null +++ b/.claude/skills/databricks-mlflow-evaluation/references/patterns-judge-alignment.md @@ -0,0 +1,316 @@ +# MLflow 3 Judge Alignment with MemAlign + +Patterns for aligning LLM judges to domain expert preferences using MemAlign. An aligned judge is more accurate for evaluation runs, more meaningful for production monitoring, and a better guide for prompt optimization — but each of these uses is independent. + +**Read `GOTCHAS.md` before implementing — especially the MemAlign sections.** + +--- + +## When to Use Judge Alignment + +Align a judge when: +- Built-in scorers don't capture domain-specific quality (e.g., "good" means expert-level tactical analysis) +- LLM judges disagree with human raters on the same examples +- You have domain experts who can rate a sample of agent outputs +- You want production monitoring that reflects actual expert standards + +You do NOT need prompt optimization to benefit from aligned judges — a more accurate judge improves every evaluation run and monitoring setup you do afterward. + +--- + +## Pattern 1: Design and Register the Base Judge + +MemAlign is scorer-agnostic and works with any `feedback_value_type` (float, boolean, categorical). This example uses a Likert scale (1-5 float), but you can use whatever scoring scheme fits your domain. + +```python +import mlflow +from mlflow.genai.judges import make_judge +from mlflow.genai import evaluate + +mlflow.set_experiment(experiment_id=EXPERIMENT_ID) + +# Define base judge using make_judge -- MemAlign works with any feedback type +# This example uses a Likert scale (1-5 float), but boolean or categorical also work +domain_quality_judge = make_judge( + name="domain_quality_base", + instructions=( + "Evaluate if the response in {{ outputs }} appropriately analyzes the available data " + "and provides an actionable recommendation to the question in {{ inputs }}. " + "The response should be accurate, contextually relevant, and give a strategic advantage " + "to the person making the request. " + "Your grading criteria: " + " 1: Completely unacceptable. Incorrect data interpretation or no recommendations. " + " 2: Mostly unacceptable. Irrelevant or spurious feedback or weak recommendations with minimal strategic advantage. " + " 3: Somewhat acceptable. Relevant feedback provided with some strategic advantage. " + " 4: Mostly acceptable. Relevant feedback provided with strong strategic advantage. " + " 5: Completely acceptable. Relevant feedback provided with excellent strategic advantage." + ), + feedback_value_type=float, # Example uses a Likert scale; MemAlign works with any feedback type + model=JUDGE_MODEL, +) + +# Register to experiment — creates the persistent record used by align() +registered_base_judge = domain_quality_judge.register(experiment_id=EXPERIMENT_ID) +print(f"Registered base judge: {registered_base_judge.name}") +``` + +--- + +## Pattern 2: Run Evaluation and Tag Traces + +Run evaluation to generate a set of traces that domain experts will review. Tag traces that were **successfully evaluated** in this `evaluate()` job (i.e., the agent produced a response and the judge scored it without errors). + +```python +from mlflow.genai import evaluate + +# Eval dataset: inputs only (no expectations needed at this stage) +eval_data = [ + {"inputs": {"input": [{"role": "user", "content": question}]}} + for question in example_questions +] + +results = evaluate( + data=eval_data, + predict_fn=lambda input: AGENT.predict({"input": input}), + scorers=[domain_quality_judge], +) + +# Tag traces that were successfully evaluated in this evaluate() job +# "OK" state means the agent responded AND the judge scored it without errors +ok_trace_ids = results.result_df.loc[results.result_df["state"] == "OK", "trace_id"] +for trace_id in ok_trace_ids: + mlflow.set_trace_tag(trace_id=trace_id, key="eval", value="complete") + +print(f"Tagged {len(ok_trace_ids)} successfully evaluated traces for labeling") +``` + +--- + +## Pattern 3: Build Eval Dataset and Create Labeling Session + +Persist traces to a UC dataset and assign them to domain experts for review. + +**CRITICAL: The label schema `name` MUST match the judge `name` used in the `evaluate()` job.** This is how `align()` pairs SME feedback with the corresponding LLM judge scores on the same traces. If these names do not match, alignment will fail or produce incorrect results. + +```python +from mlflow.genai.datasets import create_dataset, get_dataset +from mlflow.genai import create_labeling_session, get_review_app +from mlflow.genai import label_schemas + +# Build persistent dataset from tagged traces +try: + eval_dataset = get_dataset(name=DATASET_NAME) +except Exception: + eval_dataset = create_dataset(name=DATASET_NAME) + +tagged_traces = mlflow.search_traces( + locations=[EXPERIMENT_ID], + filter_string="tag.eval = 'complete'", + return_type="pandas", +) +# merge_records() expects 'inputs' and 'outputs' column names +if "inputs" not in tagged_traces.columns and "request" in tagged_traces.columns: + tagged_traces = tagged_traces.rename(columns={"request": "inputs"}) +if "outputs" not in tagged_traces.columns and "response" in tagged_traces.columns: + tagged_traces = tagged_traces.rename(columns={"response": "outputs"}) + +eval_dataset = eval_dataset.merge_records(tagged_traces) + +# CRITICAL: The label schema name MUST match the judge name used in evaluate() +# This is how align() pairs SME feedback with LLM judge scores on the same traces +LABEL_SCHEMA_NAME = "domain_quality_base" # Must match the judge name exactly + +feedback_schema = label_schemas.create_label_schema( + name=LABEL_SCHEMA_NAME, # Must match judge name from Pattern 1 + type="feedback", + title=LABEL_SCHEMA_NAME, + input=label_schemas.InputNumeric(min_value=1.0, max_value=5.0), + instruction=( + "Evaluate if the response appropriately analyzes the available data and provides " + "an actionable recommendation for the question. The response should be accurate, " + "contextually relevant, and give a strategic advantage to the person making the request. " + "\n\n Your grading criteria should be: " + "\n 1: Completely unacceptable. Incorrect data interpretation or no recommendations." + "\n 2: Mostly unacceptable. Irrelevant or spurious feedback or weak recommendations with minimal strategic advantage." + "\n 3: Somewhat acceptable. Relevant feedback provided with some strategic advantage." + "\n 4: Mostly acceptable. Relevant feedback provided with strong strategic advantage." + "\n 5: Completely acceptable. Relevant feedback provided with excellent strategic advantage." + ), + enable_comment=True, # Allow SMEs to leave free-text rationale (used by MemAlign) + overwrite=True, +) + +# Optional: add a deployed agent to the Review App so SMEs can ask new questions +review_app = get_review_app(experiment_id=EXPERIMENT_ID) +review_app = review_app.add_agent( + agent_name=MODEL_NAME, + model_serving_endpoint=AGENT_ENDPOINT_NAME, + overwrite=True, +) + +# Create labeling session and attach the dataset +labeling_session = create_labeling_session( + name=f"{LABELING_SESSION_NAME}_sme", + assigned_users=ASSIGNED_USERS, + label_schemas=[LABEL_SCHEMA_NAME], # Must match judge name +) +labeling_session = labeling_session.add_dataset(dataset_name=DATASET_NAME) + +print(f"Share with domain experts: {labeling_session.url}") +# Domain experts open this URL and rate each response using the 1-5 scale +``` + +--- + +## Pattern 4: Align Judge with MemAlign (Recommended) + +After SMEs complete labeling, distill their feedback patterns into the judge's instructions. + +Judge alignment supports multiple optimizers (e.g., SIMBA, custom optimizers), but this example uses **MemAlign**, which is the recommended approach. MemAlign is the fastest alignment method (seconds vs. minutes for alternatives), the most cost-effective, and supports **memory scaling** where quality continues to improve as feedback accumulates without re-optimization. + +```python +from mlflow.genai.judges.optimizers import MemAlignOptimizer +from mlflow.genai.scorers import get_scorer + +# Fetch the tagged traces (which now have SME labels attached) +traces_for_alignment = mlflow.search_traces( + locations=[EXPERIMENT_ID], + filter_string="tag.eval = 'complete'", + return_type="list", # align() requires list format +) +print(f"Aligning on {len(traces_for_alignment)} traces") + +# Configure MemAlign optimizer +# Other optimizers are available (e.g., SIMBA), but MemAlign is recommended for its +# speed, cost efficiency, and ability to improve continuously as feedback accumulates +optimizer = MemAlignOptimizer( + reflection_lm=REFLECTION_MODEL, # Model for guideline distillation + retrieval_k=5, # Examples to retrieve per evaluation + embedding_model="databricks:/databricks-gte-large-en", + # Defaults to "openai/text-embedding-3-small" if not set -- see GOTCHAS.md +) + +# Load the registered base judge and run alignment +base_judge = get_scorer(name="domain_quality_base") +aligned_judge = base_judge.align( + traces=traces_for_alignment, + optimizer=optimizer, +) + +# Inspect distilled semantic guidelines — these encode expert preferences +print("Distilled Guidelines from SME feedback:") +for i, guideline in enumerate(aligned_judge._semantic_memory, 1): + print(f" {i}. {guideline.guideline_text}") + if guideline.source_trace_ids: + print(f" Derived from {len(guideline.source_trace_ids)} trace(s)") +``` + +--- + +## Pattern 5: Register the Aligned Judge + +Persist the aligned judge to the experiment for later retrieval in evaluation or optimization runs. + +```python +from mlflow.genai.scorers import ScorerSamplingConfig + +# Option A: Update the existing judge record in-place (recommended for iterative alignment) +aligned_judge_registered = aligned_judge.update( + experiment_id=EXPERIMENT_ID, + sampling_config=ScorerSamplingConfig(sample_rate=0.0), +) +print(f"Updated judge: {aligned_judge_registered.name}") + +# Option B: Register as a new named version (preserves the original for comparison) +from mlflow.genai.judges import make_judge + +aligned_judge_v2 = make_judge( + name="domain_quality_aligned_v1", + instructions=aligned_judge.instructions, # Includes distilled guidelines + feedback_value_type=float, # Match the original judge's feedback type + model=JUDGE_MODEL, +) +aligned_judge_v2 = aligned_judge_v2.register(experiment_id=EXPERIMENT_ID) + +# Retrieve in a later session +# NOTE: Episodic memory is lazily loaded — inspect .instructions, not ._episodic_memory +from mlflow.genai.scorers import get_scorer + +retrieved_judge = get_scorer(name="domain_quality_base", experiment_id=EXPERIMENT_ID) +print(retrieved_judge.instructions[:500]) # Shows aligned instructions with guidelines +``` + +--- + +## Pattern 6: Re-evaluate with Aligned Judge + +Run a fresh evaluation with the aligned judge. This gives a more accurate quality picture and establishes a baseline for prompt optimization if you choose to do that next. + +**Important: The aligned judge score may be lower than the unaligned judge score. This is expected and correct.** It means the aligned judge is now evaluating with domain-expert standards rather than generic best practices. A lower score from a more accurate judge is a better signal than a higher score from a judge that doesn't understand your domain. The optimization phase (`optimize_prompts()`) will improve the agent against this more accurate standard. + +```python +from mlflow.genai import evaluate +from mlflow.genai.scorers import get_scorer +from mlflow.genai.datasets import get_dataset + +aligned_judge = get_scorer(name="domain_quality_base", experiment_id=EXPERIMENT_ID) + +eval_dataset = get_dataset(name=DATASET_NAME) +df = eval_dataset.to_df() + +eval_records = [ + { + "inputs": { + "input": [{"role": "user", "content": extract_user_message(row)}] + } + } + for row in df["inputs"] +] + +with mlflow.start_run(run_name="aligned_judge_baseline"): + baseline_results = evaluate( + data=eval_records, + predict_fn=lambda input: AGENT.predict({"input": input}), + scorers=[aligned_judge], + ) + +print(f"Aligned judge baseline metrics: {baseline_results.metrics}") +# NOTE: If scores are lower than the unaligned judge, that is expected. +# The aligned judge is more accurate, not less generous. +``` + +--- + +## Using Aligned Judges Beyond Evaluation + +Aligned judges are not just for one-time evaluation. They can be used for: + +**Production monitoring:** +```python +from mlflow.genai.scorers import ScorerSamplingConfig + +aligned_judge = get_scorer(name="domain_quality_base", experiment_id=EXPERIMENT_ID) +monitoring_judge = aligned_judge.start( + sampling_config=ScorerSamplingConfig(sample_rate=0.1) # Score 10% of production traffic +) +``` + +**Prompt optimization input (see `patterns-prompt-optimization.md`):** +```python +# Pass the aligned judge as the scorer in optimize_prompts() +result = mlflow.genai.optimize_prompts( + predict_fn=predict_fn, + train_data=optimization_dataset, + prompt_uris=[prompt.uri], + optimizer=GepaPromptOptimizer(reflection_model=REFLECTION_MODEL), + scorers=[aligned_judge], # ← aligned judge drives GEPA's reflection +) +``` + +**Regression detection across agent versions:** +```python +with mlflow.start_run(run_name="agent_v2"): + v2_results = evaluate(data=eval_records, predict_fn=agent_v2, scorers=[aligned_judge]) + +# Metrics from aligned judge are more meaningful than unaligned LLM judge +``` diff --git a/.claude/skills/databricks-mlflow-evaluation/references/patterns-prompt-optimization.md b/.claude/skills/databricks-mlflow-evaluation/references/patterns-prompt-optimization.md new file mode 100644 index 00000000..01a79bd1 --- /dev/null +++ b/.claude/skills/databricks-mlflow-evaluation/references/patterns-prompt-optimization.md @@ -0,0 +1,163 @@ +# MLflow 3 Prompt Optimization with GEPA + +Patterns for automated prompt improvement using `optimize_prompts()` with the GEPA (Genetic-Pareto) optimizer. GEPA iteratively evolves a registered system prompt by evaluating candidates against a scorer, then promotes the best version. + +**Using an aligned judge as the scorer is recommended.** An aligned judge encodes domain-expert preferences, giving GEPA a more accurate optimization signal than a generic LLM judge. See `patterns-judge-alignment.md` for the full alignment workflow. + +For the full end-to-end loop (evaluate, label, align, optimize, promote), see `user-journeys.md` Journey 10. For details on the GEPA and MemAlign approaches, see the [Self-Optimizing Agent blog post](https://www.databricks.com/blog/self-optimizing-football-chatbot-guided-domain-experts-databricks). + +**Read `GOTCHAS.md` before implementing -- especially the GEPA sections.** + +--- + +## Pattern 1: Build Optimization Dataset (inputs + expectations required) + +GEPA requires both `inputs` AND `expectations` in every record. This is different from the eval dataset which only needs `inputs`. The `expectations` field is what GEPA uses during reflection to reason about why the current prompt is underperforming. + +```python +# optimization dataset must have both inputs AND expectations +optimization_dataset = [ + { + "inputs": { + "input": [{"role": "user", "content": "What are the tendencies on 3rd and short?"}] + }, + "expectations": { + "expected_response": ( + "The agent should identify key players and their 3rd-and-short involvement, " + "provide relevant statistics, and give tactical recommendations. " + "If data quality issues exist, they should be stated explicitly." + ) + } + }, + { + "inputs": { + "input": [{"role": "user", "content": "How does the offense perform against the blitz?"}] + }, + "expectations": { + "expected_response": ( + "The agent should analyze performance metrics vs. pressure, " + "compare success across different blitz packages, " + "and provide concrete defensive recommendations." + ) + } + }, + # Add 15-20 representative examples covering key use cases +] + +# Persist to MLflow dataset +from mlflow.genai.datasets import create_dataset + +optim_dataset = create_dataset(name=OPTIMIZATION_DATASET_NAME) +optim_dataset = optim_dataset.merge_records(optimization_dataset) +print(f"Created optimization dataset with {len(optimization_dataset)} records") +``` + +--- + +## Pattern 2: Run optimize_prompts() with GEPA + +Use a scorer (ideally an aligned judge from `patterns-judge-alignment.md`) to drive GEPA prompt optimization of the registered system prompt. + +```python +import mlflow +from mlflow.genai.optimize import GepaPromptOptimizer +from mlflow.genai.scorers import get_scorer + +mlflow.set_experiment(experiment_id=EXPERIMENT_ID) + +# Load prompt from registry (must be registered before optimization) +system_prompt = mlflow.genai.load_prompt(f"prompts:/{PROMPT_NAME}@production") +print(f"Loaded prompt: {system_prompt.uri}") + +# Load scorer -- an aligned judge is recommended for domain-accurate optimization +# See patterns-judge-alignment.md for how to create one +aligned_judge = get_scorer(name=ALIGNED_JUDGE_NAME, experiment_id=EXPERIMENT_ID) + +# Define predict_fn -- loads prompt from registry on each call so GEPA can swap it +def predict_fn(input): + prompt = mlflow.genai.load_prompt(system_prompt.uri) + system_content = prompt.format() + + user_message = input[0]["content"] + messages = [ + {"role": "system", "content": system_content}, + {"role": "user", "content": user_message}, + ] + return AGENT.predict({"input": messages}) + +# Define aggregation to normalize judge feedback (Feedback.value) to 0-1 for GEPA +def objective_function(scores: dict) -> float: + feedback = scores.get(ALIGNED_JUDGE_NAME) + if feedback and hasattr(feedback, "feedback") and hasattr(feedback.feedback, "value"): + try: + return float(feedback.feedback.value) / 5.0 # Normalize 1-5 scale to 0-1 + except (ValueError, TypeError): + return 0.5 + return 0.5 + +# Run optimization +result = mlflow.genai.optimize_prompts( + predict_fn=predict_fn, + train_data=optimization_dataset, # Must have inputs + expectations + prompt_uris=[system_prompt.uri], + optimizer=GepaPromptOptimizer( + reflection_model=REFLECTION_MODEL, + max_metric_calls=75, # Reduce for faster runs; increase for quality + display_progress_bar=True, + ), + scorers=[aligned_judge], + aggregation=objective_function, +) + +optimized_prompt = result.optimized_prompts[0] +print(f"Initial score: {result.initial_eval_score}") +print(f"Final score: {result.final_eval_score}") +print(f"\nOptimized template (first 500 chars):\n{optimized_prompt.template[:500]}...") +``` + +--- + +## Pattern 3: Register Optimized Prompt and Conditionally Promote + +Only promote to the "production" alias if the optimized prompt outperforms the baseline. + +```python +# Register new prompt version with optimization metadata +new_prompt_version = mlflow.genai.register_prompt( + name=PROMPT_NAME, + template=optimized_prompt.template, + commit_message=f"GEPA optimization using {ALIGNED_JUDGE_NAME}", + tags={ + "initial_score": str(result.initial_eval_score), + "final_score": str(result.final_eval_score), + "optimization": "GEPA", + "judge": ALIGNED_JUDGE_NAME, + }, +) +print(f"Registered prompt version: {new_prompt_version.version}") + +# Conditional promotion -- only update production alias if score improved +def promote_if_improved(prompt_name, result, new_prompt_version): + if result.final_eval_score > result.initial_eval_score: + mlflow.genai.set_prompt_alias( + name=prompt_name, + alias="production", + version=new_prompt_version.version, + ) + print(f"Promoted version {new_prompt_version.version} to production " + f"({result.initial_eval_score:.3f} -> {result.final_eval_score:.3f})") + else: + print(f"No improvement ({result.initial_eval_score:.3f} -> " + f"{result.final_eval_score:.3f}). Production alias unchanged.") + +promote_if_improved(PROMPT_NAME, result, new_prompt_version) +``` + +--- + +## Tips for Prompt Optimization + +- The optimization dataset should cover the diversity of queries your agent will handle. Include edge cases, ambiguous requests, and scenarios where tool selection matters. +- Expected responses should describe what the agent should do (which tools to call, what information to include) rather than exact output text. +- Start with `max_metric_calls` set to between 50 and 100. Higher values explore more candidates but increase cost and runtime. +- The GEPA optimizer learns from failure modes. If the aligned judge penalizes missing benchmarks or small-sample caveats, GEPA will inject those requirements into the optimized prompt. diff --git a/.claude/skills/mlflow-evaluation/references/patterns-scorers.md b/.claude/skills/databricks-mlflow-evaluation/references/patterns-scorers.md similarity index 100% rename from .claude/skills/mlflow-evaluation/references/patterns-scorers.md rename to .claude/skills/databricks-mlflow-evaluation/references/patterns-scorers.md diff --git a/.claude/skills/mlflow-evaluation/references/patterns-trace-analysis.md b/.claude/skills/databricks-mlflow-evaluation/references/patterns-trace-analysis.md similarity index 100% rename from .claude/skills/mlflow-evaluation/references/patterns-trace-analysis.md rename to .claude/skills/databricks-mlflow-evaluation/references/patterns-trace-analysis.md diff --git a/.claude/skills/databricks-mlflow-evaluation/references/patterns-trace-ingestion.md b/.claude/skills/databricks-mlflow-evaluation/references/patterns-trace-ingestion.md new file mode 100644 index 00000000..7196ab14 --- /dev/null +++ b/.claude/skills/databricks-mlflow-evaluation/references/patterns-trace-ingestion.md @@ -0,0 +1,680 @@ +# MLflow Trace Ingestion in Unity Catalog + +Working code patterns for setting up trace storage in Unity Catalog, logging traces from applications, and enabling production monitoring. + +**Version**: MLflow 3.9.0+ (`mlflow[databricks]>=3.9.0`) +**Preview**: Requires "OpenTelemetry on Databricks" preview enabled +**Regions**: Currently available in `us-east-1` and `us-west-2` only + +--- + +## Table of Contents + +| # | Pattern | Description | +|---|---------|-------------| +| 1 | [Initial Setup](#pattern-1-initial-setup---link-uc-schema-to-experiment) | Link UC schema to experiment, create tables | +| 2 | [Access Control](#pattern-2-access-control---grant-permissions) | Grant required permissions on UC tables | +| 3 | [Set Trace Destination (Python API)](#pattern-3-set-trace-destination-via-python-api) | Configure where traces are sent | +| 4 | [Set Trace Destination (Env Var)](#pattern-4-set-trace-destination-via-environment-variable) | Configure destination via env var | +| 5 | [Log Traces with @mlflow.trace](#pattern-5-log-traces-with-mlflow-decorator) | Instrument functions with decorator | +| 6 | [Log Traces with start_span](#pattern-6-log-traces-with-context-manager) | Fine-grained span control | +| 7 | [Auto-Instrumentation](#pattern-7-automatic-tracing-with-autolog) | Framework auto-tracing (OpenAI, LangChain, etc.) | +| 8 | [Combined Instrumentation](#pattern-8-combined-auto-and-manual-tracing) | Mix auto + manual tracing | +| 9 | [Traces from Databricks Apps](#pattern-9-log-traces-from-databricks-apps) | Configure app service principal | +| 10 | [Traces from Model Serving](#pattern-10-log-traces-from-model-serving-endpoints) | Configure serving endpoints | +| 11 | [Traces from OTEL Clients](#pattern-11-log-traces-from-third-party-otel-clients) | Use OpenTelemetry OTLP exporter | +| 12 | [Enable Production Monitoring](#pattern-12-enable-production-monitoring) | Register and start scorers | +| 13 | [Manage Monitoring Scorers](#pattern-13-manage-monitoring-scorers) | List, update, stop, delete scorers | +| 14 | [Query UC Trace Tables](#pattern-14-query-traces-from-unity-catalog-tables) | SQL queries on ingested traces | +| 15 | [End-to-End Setup](#pattern-15-end-to-end-setup-script) | Complete setup from scratch | + +--- + +## Pattern 1: Initial Setup - Link UC Schema to Experiment + +Create an MLflow experiment and link it to a Unity Catalog schema. This automatically creates three tables for storing trace data. + +```python +import os +import mlflow +from mlflow.entities import UCSchemaLocation +from mlflow.tracing.enablement import set_experiment_trace_location + +# Step 1: Configure tracking +mlflow.set_tracking_uri("databricks") +os.environ["MLFLOW_TRACING_SQL_WAREHOUSE_ID"] = "" + +# Step 2: Define names +experiment_name = "/Shared/my-agent-traces" +catalog_name = "my_catalog" +schema_name = "my_schema" + +# Step 3: Create or retrieve experiment +if experiment := mlflow.get_experiment_by_name(experiment_name): + experiment_id = experiment.experiment_id +else: + experiment_id = mlflow.create_experiment(name=experiment_name) + +# Step 4: Link UC schema to experiment +result = set_experiment_trace_location( + location=UCSchemaLocation( + catalog_name=catalog_name, + schema_name=schema_name + ), + experiment_id=experiment_id, +) +``` + +**Tables created automatically:** +- `{catalog}.{schema}.mlflow_experiment_trace_otel_logs` +- `{catalog}.{schema}.mlflow_experiment_trace_otel_metrics` +- `{catalog}.{schema}.mlflow_experiment_trace_otel_spans` + +**CRITICAL**: Linking a UC schema hides pre-existing experiment traces stored in MLflow. Unlinking restores access to those traces. + +--- + +## Pattern 2: Access Control - Grant Permissions + +Users and service principals need explicit permissions on the UC trace tables. `ALL_PRIVILEGES` is **not sufficient**. + +```sql +-- Required: USE_CATALOG on the catalog +GRANT USE_CATALOG ON CATALOG my_catalog TO `user@company.com`; + +-- Required: USE_SCHEMA on the schema +GRANT USE_SCHEMA ON SCHEMA my_catalog.my_schema TO `user@company.com`; + +-- Required: MODIFY and SELECT on each trace table +GRANT MODIFY, SELECT ON TABLE my_catalog.my_schema.mlflow_experiment_trace_otel_logs + TO `user@company.com`; +GRANT MODIFY, SELECT ON TABLE my_catalog.my_schema.mlflow_experiment_trace_otel_spans + TO `user@company.com`; +GRANT MODIFY, SELECT ON TABLE my_catalog.my_schema.mlflow_experiment_trace_otel_metrics + TO `user@company.com`; +``` + +**For service principals (Databricks Apps, Model Serving):** +```sql +-- Replace with the service principal's application ID +GRANT USE_CATALOG ON CATALOG my_catalog TO ``; +GRANT USE_SCHEMA ON SCHEMA my_catalog.my_schema TO ``; +GRANT MODIFY, SELECT ON TABLE my_catalog.my_schema.mlflow_experiment_trace_otel_logs + TO ``; +GRANT MODIFY, SELECT ON TABLE my_catalog.my_schema.mlflow_experiment_trace_otel_spans + TO ``; +GRANT MODIFY, SELECT ON TABLE my_catalog.my_schema.mlflow_experiment_trace_otel_metrics + TO ``; +``` + +--- + +## Pattern 3: Set Trace Destination via Python API + +Configure where traces are sent using the Python API. Use this after the initial setup (Pattern 1) in your application code. + +```python +import mlflow +from mlflow.entities import UCSchemaLocation + +# Set trace destination to Unity Catalog +mlflow.tracing.set_destination( + destination=UCSchemaLocation( + catalog_name="my_catalog", + schema_name="my_schema", + ) +) + +# Now all traces from @mlflow.trace or autolog will go to UC +@mlflow.trace +def my_agent(query: str) -> str: + # Traces are automatically sent to UC tables + return process(query) +``` + +--- + +## Pattern 4: Set Trace Destination via Environment Variable + +Alternative to Pattern 3 — configure destination via environment variable. Useful for deployment configurations. + +```python +import os + +# Set destination as "{catalog}.{schema}" +os.environ["MLFLOW_TRACING_DESTINATION"] = "my_catalog.my_schema" +``` + +Or in shell: +```bash +export MLFLOW_TRACING_DESTINATION="my_catalog.my_schema" +``` + +--- + +## Pattern 5: Log Traces with MLflow Decorator + +Use `@mlflow.trace` to instrument functions. Automatically captures inputs, outputs, latency, and exceptions. + +```python +import mlflow +from mlflow.entities import SpanType + +# Basic function tracing +@mlflow.trace +def my_agent(query: str) -> str: + context = retrieve_context(query) + return generate_response(query, context) + +# With span type (enables enhanced UI and evaluation) +@mlflow.trace(span_type=SpanType.RETRIEVER) +def retrieve_context(query: str) -> list[dict]: + """Mark retrieval functions with RETRIEVER span type.""" + return vector_store.search(query, top_k=5) + +@mlflow.trace(span_type=SpanType.CHAIN) +def generate_response(query: str, context: list[dict]) -> str: + """Mark orchestration with CHAIN span type.""" + return llm.invoke(query, context=context) + +# With custom name and attributes +@mlflow.trace(name="safety_check", span_type=SpanType.TOOL) +def check_safety(text: str) -> bool: + return safety_classifier.predict(text) +``` + +**Available SpanType values:** +- `SpanType.CHAIN` — Orchestration / pipeline steps +- `SpanType.CHAT_MODEL` — LLM chat completions +- `SpanType.LLM` — LLM calls (non-chat) +- `SpanType.RETRIEVER` — Document/data retrieval (special output schema) +- `SpanType.TOOL` — Tool/function execution +- `SpanType.AGENT` — Agent execution +- `SpanType.EMBEDDING` — Embedding generation + +--- + +## Pattern 6: Log Traces with Context Manager + +Use `mlflow.start_span()` for fine-grained control over spans. Manually set inputs, outputs, and attributes. + +```python +import mlflow + +def process_query(query: str) -> str: + # Create a span with manual control + with mlflow.start_span(name="process_query") as span: + span.set_inputs({"query": query}) + + # Nested span for retrieval + with mlflow.start_span(name="retrieve", span_type="RETRIEVER") as retriever_span: + retriever_span.set_inputs({"query": query}) + docs = vector_store.search(query) + retriever_span.set_outputs(docs) + + # Nested span for generation + with mlflow.start_span(name="generate", span_type="CHAIN") as gen_span: + gen_span.set_inputs({"query": query, "doc_count": len(docs)}) + response = llm.generate(query, docs) + gen_span.set_outputs({"response": response}) + + # Set attributes for analysis + span.set_attribute("doc_count", len(docs)) + span.set_attribute("model", "gpt-4o") + span.set_outputs({"response": response}) + + return response +``` + +--- + +## Pattern 7: Automatic Tracing with Autolog + +Enable automatic tracing for supported frameworks. MLflow captures LLM calls, tool executions, and chain operations without code changes. + +```python +import mlflow + +# Enable auto-tracing for specific frameworks +mlflow.openai.autolog() # OpenAI SDK calls +mlflow.langchain.autolog() # LangChain chains and agents +# Also available: mlflow.anthropic.autolog(), mlflow.litellm.autolog(), etc. + +# Set tracking and destination +mlflow.set_tracking_uri("databricks") +mlflow.set_experiment("/Shared/my-agent-traces") + +# Traces are captured automatically +from openai import OpenAI +client = OpenAI() + +response = client.chat.completions.create( + model="gpt-4o", + messages=[ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "What is MLflow?"} + ] +) +# ^ This call is automatically traced +``` + +**20+ supported frameworks** including: +- OpenAI, Anthropic, Google GenAI +- LangChain, LlamaIndex, DSPy +- LiteLLM, Ollama, Bedrock +- CrewAI, AutoGen, Haystack + +--- + +## Pattern 8: Combined Auto and Manual Tracing + +Combine automatic framework tracing with manual decorators for complete coverage. + +```python +import mlflow +from mlflow.entities import SpanType +from openai import OpenAI + +# Enable automatic OpenAI tracing +mlflow.openai.autolog() + +client = OpenAI() + +@mlflow.trace(span_type=SpanType.CHAIN) +def my_rag_pipeline(query: str) -> str: + """Manual decorator wraps the whole pipeline. + Auto-tracing captures individual OpenAI calls inside.""" + + # This retrieval is manually traced + docs = retrieve_documents(query) + + # This LLM call is auto-traced by mlflow.openai.autolog() + response = client.chat.completions.create( + model="gpt-4o", + messages=[ + {"role": "system", "content": f"Answer using context: {docs}"}, + {"role": "user", "content": query} + ] + ) + return response.choices[0].message.content + +@mlflow.trace(span_type=SpanType.RETRIEVER) +def retrieve_documents(query: str) -> list[dict]: + """Manually traced retrieval function.""" + return vector_store.search(query, top_k=5) +``` + +--- + +## Pattern 9: Log Traces from Databricks Apps + +Configure a Databricks App to send traces to Unity Catalog. + +**Prerequisites:** +- App uses `mlflow[databricks]>=3.5.0` +- App's service principal has MODIFY and SELECT on the trace tables (see Pattern 2) + +**In your app code:** +```python +import os +import mlflow +from mlflow.entities import UCSchemaLocation + +# Option A: Python API +mlflow.tracing.set_destination( + destination=UCSchemaLocation( + catalog_name="my_catalog", + schema_name="my_schema", + ) +) + +# Option B: Environment variable (set in app config) +os.environ["MLFLOW_TRACING_DESTINATION"] = "my_catalog.my_schema" + +# Your app code — traces are sent to UC +@mlflow.trace +def handle_request(query: str) -> str: + return my_agent.invoke(query) +``` + +**Deployment steps:** +1. Locate the app's service principal under the **Authorization** tab +2. Grant MODIFY and SELECT on the three `mlflow_experiment_trace_*` tables +3. Configure the trace destination in your app code +4. Deploy the app + +--- + +## Pattern 10: Log Traces from Model Serving Endpoints + +Configure a model serving endpoint to send traces to Unity Catalog. + +**Step 1: Grant permissions to user/service principal** +```sql +GRANT MODIFY, SELECT ON TABLE my_catalog.my_schema.mlflow_experiment_trace_otel_logs + TO `serving-principal-id`; +GRANT MODIFY, SELECT ON TABLE my_catalog.my_schema.mlflow_experiment_trace_otel_spans + TO `serving-principal-id`; +``` + +**Step 2: Generate a Personal Access Token (PAT)** + +Create a PAT for the identity that has the permissions above. + +**Step 3: Add environment variables to the endpoint** + +Add these to the serving endpoint configuration: +``` +DATABRICKS_TOKEN= +MLFLOW_TRACING_DESTINATION=my_catalog.my_schema +``` + +**Step 4: In your served model code, configure the destination** +```python +import os +import mlflow +from mlflow.entities import UCSchemaLocation + +mlflow.tracing.set_destination( + destination=UCSchemaLocation( + catalog_name="my_catalog", + schema_name="my_schema", + ) +) + +# Your model's predict function — traces go to UC +@mlflow.trace +def predict(model_input): + return my_model.invoke(model_input) +``` + +--- + +## Pattern 11: Log Traces from Third-Party OTEL Clients + +Send traces from any OpenTelemetry-compatible client to Unity Catalog via the OTLP HTTP endpoint. + +```python +from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor + +# Configure OTLP exporter pointing to Databricks +otlp_trace_exporter = OTLPSpanExporter( + endpoint="https:///api/2.0/otel/v1/traces", + headers={ + "content-type": "application/x-protobuf", + "X-Databricks-UC-Table-Name": "my_catalog.my_schema.mlflow_experiment_trace_otel_spans", + "Authorization": "Bearer ", + }, +) + +# Set up the tracer provider +provider = TracerProvider() +provider.add_span_processor(BatchSpanProcessor(otlp_trace_exporter)) + +# Use standard OpenTelemetry APIs to create spans +tracer = provider.get_tracer("my-application") +with tracer.start_as_current_span("my-operation") as span: + span.set_attribute("query", "What is MLflow?") + result = process_query("What is MLflow?") + span.set_attribute("result_length", len(result)) +``` + +**Notes:** +- Traces ingested via OTEL appear in linked experiments if they contain a root span +- Use the `X-Databricks-UC-Table-Name` header to specify the target spans table +- Standard OTEL instrumentation libraries work with this endpoint + +--- + +## Pattern 12: Enable Production Monitoring + +Register scorers to continuously evaluate traces in production. Scorers run asynchronously on sampled traces. + +```python +import mlflow +from mlflow.genai.scorers import Safety, Guidelines, ScorerSamplingConfig +from mlflow.tracing import set_databricks_monitoring_sql_warehouse_id + +# Step 1: Configure the SQL warehouse for monitoring +set_databricks_monitoring_sql_warehouse_id( + warehouse_id="", + experiment_id="" # Optional — uses active experiment if omitted +) + +# Step 2: Set the active experiment +mlflow.set_experiment("/Shared/my-agent-traces") + +# Step 3: Register and start scorers + +# Safety scorer — evaluate 100% of traces +safety = Safety().register(name="production_safety") +safety = safety.start( + sampling_config=ScorerSamplingConfig(sample_rate=1.0) +) + +# Custom guidelines — evaluate 50% of traces +tone_check = Guidelines( + name="professional_tone", + guidelines="The response must be professional and helpful" +).register(name="production_tone") +tone_check = tone_check.start( + sampling_config=ScorerSamplingConfig(sample_rate=0.5) +) +``` + +**CRITICAL**: You must both `.register()` AND `.start()` — registering alone does not activate monitoring. + +**SQL Warehouse requirements:** +- User must have `CAN USE` on the SQL warehouse +- User must have `CAN EDIT` on the experiment +- Monitoring job permissions are auto-granted on first scorer registration + +--- + +## Pattern 13: Manage Monitoring Scorers + +List, update, stop, and delete production monitoring scorers. + +```python +from mlflow.genai.scorers import list_scorers, get_scorer, delete_scorer, ScorerSamplingConfig + +# List all registered scorers for the active experiment +scorers = list_scorers() +for s in scorers: + print(f" {s.name}: sample_rate={s.sampling_config.sample_rate if s.sampling_config else 'N/A'}") + +# Get a specific scorer +safety_scorer = get_scorer(name="production_safety") + +# Update sample rate (e.g., increase from 50% to 80%) +safety_scorer = safety_scorer.update( + sampling_config=ScorerSamplingConfig(sample_rate=0.8) +) + +# Stop monitoring (keeps registration for later re-start) +safety_scorer = safety_scorer.stop() + +# Re-start monitoring +safety_scorer = safety_scorer.start( + sampling_config=ScorerSamplingConfig(sample_rate=0.5) +) + +# Delete entirely (removes registration) +delete_scorer(name="production_safety") +``` + +--- + +## Pattern 14: Query Traces from Unity Catalog Tables + +Query ingested traces directly using SQL for custom analysis and dashboards. + +```sql +-- Count traces per day +SELECT + DATE(timestamp) as trace_date, + COUNT(DISTINCT trace_id) as trace_count +FROM my_catalog.my_schema.mlflow_experiment_trace_otel_spans +WHERE parent_span_id IS NULL -- root spans only +GROUP BY DATE(timestamp) +ORDER BY trace_date DESC; + +-- Find slow traces (root span duration > 10s) +SELECT + trace_id, + name as root_span_name, + (end_time_unix_nano - start_time_unix_nano) / 1e9 as duration_seconds +FROM my_catalog.my_schema.mlflow_experiment_trace_otel_spans +WHERE parent_span_id IS NULL + AND (end_time_unix_nano - start_time_unix_nano) / 1e9 > 10 +ORDER BY duration_seconds DESC +LIMIT 20; + +-- Error rate by span name +SELECT + name, + COUNT(*) as total, + SUM(CASE WHEN status_code = 'ERROR' THEN 1 ELSE 0 END) as errors, + ROUND(SUM(CASE WHEN status_code = 'ERROR' THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 2) as error_pct +FROM my_catalog.my_schema.mlflow_experiment_trace_otel_spans +GROUP BY name +HAVING COUNT(*) > 10 +ORDER BY error_pct DESC; +``` + +**From Python (via Spark):** +```python +from databricks.connect import DatabricksSession + +spark = DatabricksSession.builder.remote(serverless=True).getOrCreate() + +# Query trace spans +spans_df = spark.sql(""" + SELECT trace_id, name, span_kind, + (end_time_unix_nano - start_time_unix_nano) / 1e6 as duration_ms + FROM my_catalog.my_schema.mlflow_experiment_trace_otel_spans + WHERE name LIKE '%retriever%' + ORDER BY duration_ms DESC + LIMIT 100 +""") +spans_df.show() +``` + +--- + +## Pattern 15: End-to-End Setup Script + +Complete setup script for a new project — from creating the UC schema link to logging the first trace and enabling monitoring. + +```python +import os +import mlflow +from mlflow.entities import UCSchemaLocation +from mlflow.tracing.enablement import set_experiment_trace_location +from mlflow.tracing import set_databricks_monitoring_sql_warehouse_id +from mlflow.genai.scorers import Safety, Guidelines, ScorerSamplingConfig + +# ============================================================ +# Configuration — UPDATE THESE VALUES +# ============================================================ +EXPERIMENT_NAME = "/Shared/my-agent-traces" +CATALOG_NAME = "my_catalog" +SCHEMA_NAME = "my_schema" +SQL_WAREHOUSE_ID = "abc123def456" # Your SQL warehouse ID + +# ============================================================ +# Step 1: Initial Setup +# ============================================================ +mlflow.set_tracking_uri("databricks") +os.environ["MLFLOW_TRACING_SQL_WAREHOUSE_ID"] = SQL_WAREHOUSE_ID + +# Create or retrieve experiment +if experiment := mlflow.get_experiment_by_name(EXPERIMENT_NAME): + experiment_id = experiment.experiment_id +else: + experiment_id = mlflow.create_experiment(name=EXPERIMENT_NAME) + +# Link UC schema (creates trace tables automatically) +set_experiment_trace_location( + location=UCSchemaLocation( + catalog_name=CATALOG_NAME, + schema_name=SCHEMA_NAME + ), + experiment_id=experiment_id, +) +print(f"Linked experiment '{EXPERIMENT_NAME}' to {CATALOG_NAME}.{SCHEMA_NAME}") + +# ============================================================ +# Step 2: Set Trace Destination +# ============================================================ +mlflow.set_experiment(EXPERIMENT_NAME) +mlflow.tracing.set_destination( + destination=UCSchemaLocation( + catalog_name=CATALOG_NAME, + schema_name=SCHEMA_NAME, + ) +) + +# ============================================================ +# Step 3: Enable Production Monitoring +# ============================================================ +set_databricks_monitoring_sql_warehouse_id( + warehouse_id=SQL_WAREHOUSE_ID, + experiment_id=experiment_id, +) + +# Register and start safety monitoring (100% of traces) +safety = Safety().register(name="safety_monitor") +safety = safety.start( + sampling_config=ScorerSamplingConfig(sample_rate=1.0) +) +print("Safety monitoring enabled (100% sample rate)") + +# Register and start custom guidelines (50% of traces) +tone = Guidelines( + name="professional_tone", + guidelines="The response must be professional, helpful, and concise" +).register(name="tone_monitor") +tone = tone.start( + sampling_config=ScorerSamplingConfig(sample_rate=0.5) +) +print("Tone monitoring enabled (50% sample rate)") + +# ============================================================ +# Step 4: Verify with a Test Trace +# ============================================================ +@mlflow.trace +def test_agent(query: str) -> str: + return f"Test response to: {query}" + +result = test_agent("Hello, is tracing working?") +print(f"Test trace logged. Check the Experiments UI at: {EXPERIMENT_NAME}") +``` + +--- + +## Limitations & Quotas + +| Limit | Value | +|-------|-------| +| Trace ingestion rate | 100 traces/second per workspace | +| Table ingestion throughput | 100 MB/second per table | +| Query throughput | 200 queries/second | +| UI performance | Degrades with >2TB of data | +| Trace deletion | Individual deletion not supported (use SQL) | +| MLflow MCP server | Does not support UC-stored traces | +| Region availability | `us-east-1` and `us-west-2` only (Beta) | + +--- + +## Viewing Traces in the UI + +1. Navigate to the **Experiments** page in your Databricks workspace +2. Select your experiment +3. Click the **Traces** tab +4. Select a **SQL warehouse** from the dropdown to query UC-stored traces +5. Browse traces, inspect spans, view inputs/outputs + +**Note:** You must select a SQL warehouse to view UC-stored traces — they are not loaded automatically. diff --git a/.claude/skills/databricks-mlflow-evaluation/references/user-journeys.md b/.claude/skills/databricks-mlflow-evaluation/references/user-journeys.md new file mode 100644 index 00000000..6ff09b28 --- /dev/null +++ b/.claude/skills/databricks-mlflow-evaluation/references/user-journeys.md @@ -0,0 +1,627 @@ +# User Journey Guides + +Step-by-step workflows for common evaluation scenarios. + +--- + +## Journey 0: Strategy Alignment (ALWAYS START HERE) + +**Starting Point**: You need to evaluate an agent +**Goal**: Align on what to evaluate before writing any code + +**PRIORITY:** Before writing evaluation code, complete strategy alignment. This ensures evaluations measure what matters and provide actionable insights. + +### Step 1: Understand the Agent + +Before evaluating, gather context about what you're evaluating: + +**Questions to ask (or investigate in the codebase):** +1. **What does this agent do?** (data analysis, RAG, multi-turn chat, task automation) +2. **What tools does it use?** (UC functions, vector search, external APIs) +3. **What is the input/output format?** (messages format, structured output) +4. **What is the current state?** (prototype, production, needs improvement) + +**Actions to take:** +- Read the agent's main code file (e.g., `agent.py`) +- Review the config file for system prompts and tool definitions +- Check existing tests or evaluation scripts +- Look at CLAUDE.md or README for project context + +### Step 2: Align on What to Evaluate + +**Evaluation dimensions to consider:** + +| Dimension | When to Use | Example Scorer | +|-----------|-------------|----------------| +| **Safety** | Always (table stakes) | `Safety()` | +| **Correctness** | When ground truth exists | `Correctness()` | +| **Relevance** | When responses should address queries | `RelevanceToQuery()` | +| **Groundedness** | RAG systems with retrieved context | `RetrievalGroundedness()` | +| **Domain Guidelines** | Domain-specific requirements | `Guidelines(name="...", guidelines="...")` | +| **Format/Structure** | Structured output requirements | Custom scorer | +| **Tool Usage** | Agents with tool calls | Custom scorer checking tool selection | + +**Questions to ask the user:** +1. What are the **must-have** quality criteria? (safety, accuracy, relevance) +2. What are the **nice-to-have** criteria? (conciseness, tone, format) +3. Are there **specific failure modes** you've seen or worry about? +4. Do you have **ground truth** or expected answers for test cases? + +### Step 3: Define User Scenarios (Evaluation Dataset) + +**Types of test cases to include:** + +| Category | Purpose | Example | +|----------|---------|---------| +| **Happy Path** | Core functionality works | Typical user questions | +| **Edge Cases** | Boundary conditions | Empty inputs, very long queries | +| **Adversarial** | Robustness testing | Prompt injection, off-topic | +| **Multi-turn** | Conversation handling | Follow-up questions, context recall | +| **Domain-specific** | Business logic | Industry terminology, specific formats | + +**Questions to ask the user:** +1. What are the **most common** questions users ask? +2. What are **challenging** questions the agent should handle? +3. Are there questions it should **refuse** to answer? +4. Do you have **existing test cases** or production traces to start from? + +### Step 4: Establish Success Criteria + +**Define quality gates before running evaluation:** + +```python +QUALITY_GATES = { + "safety": 1.0, # 100% - non-negotiable + "correctness": 0.9, # 90% - high bar for accuracy + "relevance": 0.85, # 85% - good relevance + "concise": 0.8, # 80% - nice to have +} +``` + +**Questions to ask the user:** +1. What pass rates are **acceptable** for each dimension? +2. Which metrics are **blocking** vs **informational**? +3. How will evaluation results **inform decisions**? (ship/no-ship, iterate, investigate) + +### Strategy Alignment Checklist + +Before implementing evaluation, confirm: +- [ ] Agent purpose and architecture understood +- [ ] Evaluation dimensions agreed upon +- [ ] Test case categories identified +- [ ] Success criteria defined +- [ ] Data source identified (new, traces, existing dataset) + +--- + +## Journey 3: "Something Broke" - Regression Detection + +**Starting Point**: You made changes to your agent and suspect something regressed +**Goal**: Identify what broke and verify the fix + +### Steps + +1. **Establish baseline metrics** + ```bash + # Run evaluation on the previous version (or use saved baseline) + cd agents/tool_calling_dspy + python run_quick_eval.py + ``` + Record key metrics: `classifier_accuracy`, `tool_selection_accuracy`, `follows_instructions` + +2. **Run evaluation on current version** + ```bash + python run_quick_eval.py + ``` + +3. **Compare metrics** + ```python + from evaluation.optimization_history import OptimizationHistory + + history = OptimizationHistory() + print(history.compare_iterations(-2, -1)) # Compare last two + ``` + +4. **Identify regression source** + - If `classifier_accuracy` dropped → Check ClassifierSignature changes + - If `tool_selection_accuracy` dropped → Check tool descriptions, required_tools field + - If `follows_instructions` dropped → Check ExecutorSignature output format + +5. **Analyze failing traces** + ``` + /eval:analyze-traces [experiment-id] + ``` + Look for: + - Error patterns in specific test categories + - Tool call failures + - Unexpected outputs + +6. **Fix and re-evaluate** + - Revert problematic changes or apply targeted fix + - Re-run evaluation + - Verify metrics restored + +### Commands Used +- `python run_quick_eval.py` - Run evaluation +- `/eval:analyze-traces` - Deep trace analysis +- `OptimizationHistory.compare_iterations()` - Metric comparison + +### Success Indicators +- Metrics return to baseline or improve +- No new failing test cases +- Trace analysis shows expected behavior + +--- + +## Journey 7: "My Multi-Agent is Slow" - Performance Optimization + +**Starting Point**: Your agent responses are too slow +**Goal**: Identify bottlenecks and reduce latency + +### Steps + +1. **Run evaluation with latency scoring** + ```bash + cd agents/tool_calling_dspy + python run_quick_eval.py + ``` + Note the latency metrics: + - `classifier_latency_ms` + - `rewriter_latency_ms` + - `executor_latency_ms` + - `total_latency_ms` + +2. **Identify the bottleneck stage** + | Latency | Typical Range | If High, Check | + |---------|---------------|----------------| + | classifier_latency | <5s | ClassifierSignature verbosity | + | rewriter_latency | <10s | QueryRewriterSignature complexity | + | executor_latency | <30s | Tool call count, response generation | + +3. **Analyze traces for slow stages** + ``` + /eval:analyze-traces [experiment-id] + ``` + Focus on: + - Span durations by stage + - Number of LLM calls per stage + - Tool execution times + +4. **Run signature analysis** + ```bash + python -m evaluation.analyze_signatures + ``` + Look for: + - High total description chars (>2000) + - Verbose OutputField descriptions + - Missing examples (causes more retries) + +5. **Apply optimizations** + + **For high classifier latency:** + - Simplify ClassifierSignature docstring + - Add concrete examples to reduce ambiguity + + **For high executor latency:** + - Simplify ExecutorSignature.answer format + - Reduce output format requirements + - Consider caching repeated tool calls + + **For high total latency:** + - Review if all stages are necessary + - Consider parallel execution where possible + +6. **Re-evaluate and compare** + ```bash + python run_quick_eval.py + ``` + Use `OptimizationHistory.compare_iterations()` to verify improvement + +### Commands Used +- `python run_quick_eval.py` - Run evaluation with latency scoring +- `/eval:analyze-traces` - Trace analysis with timing breakdown +- `python -m evaluation.analyze_signatures` - Signature verbosity analysis + +### Success Indicators +- Target latencies: classifier <5s, executor <30s, total <60s +- No regression in accuracy metrics +- Consistent improvement across test categories + +--- + +## Journey 8: "Improve My Prompts" - Systematic Prompt Optimization + +**Starting Point**: Your agent works but could be more accurate +**Goal**: Systematically improve prompt quality through evaluation + +### Steps + +1. **Establish baseline** + ```bash + cd agents/tool_calling_dspy + python run_quick_eval.py + ``` + Record all metrics in `optimization_history.json` + +2. **Run signature analysis** + ```bash + python -m evaluation.analyze_signatures + ``` + Review the report for: + - Metric correlations (which signatures affect which metrics) + - Specific issues flagged per signature + +3. **Prioritize fixes by metric impact** + + | Metric | Primary Signature | Common Issues | + |--------|-------------------|---------------| + | follows_instructions | ExecutorSignature | Verbose answer format, unclear structure | + | tool_selection_accuracy | ClassifierSignature | No examples, ambiguous tool descriptions | + | classifier_accuracy | ClassifierSignature | Verbose docstring, unclear query_type mapping | + +4. **Apply ONE fix at a time** + - Make a single, targeted change + - Document the change in your commit message + - Track in optimization_history.json + +5. **Re-evaluate immediately** + ```bash + python run_quick_eval.py + ``` + - If improved → Keep change, move to next fix + - If regressed → Revert and try different approach + - If unchanged → Consider if fix was necessary + +6. **Iterate until targets met** + + | Metric | Target | + |--------|--------| + | classifier_accuracy | 95%+ | + | tool_selection_accuracy | 90%+ | + | follows_instructions | 80%+ | + +7. **Document successful optimizations** + ```python + from evaluation.optimization_history import OptimizationHistory + + history = OptimizationHistory() + print(history.summary()) + ``` + +### Commands Used +- `python run_quick_eval.py` - Run evaluation +- `python -m evaluation.analyze_signatures` - Identify prompt issues +- `/optimize:context --quick` - Full optimization loop (when endpoint available) + +### Success Indicators +- All target metrics met +- No regressions from baseline +- Clear documentation of what changed and why +- Optimization history shows positive trend + +--- + +## Journey 9: "Store Traces in Unity Catalog" - Trace Ingestion & Production Monitoring + +**Starting Point**: You want to persist traces in Unity Catalog for long-term analysis, compliance, or production monitoring +**Goal**: Set up trace ingestion, instrument your app, and enable continuous monitoring + +### Prerequisites + +- Unity Catalog-enabled workspace +- "OpenTelemetry on Databricks" preview enabled +- SQL warehouse with `CAN USE` permissions +- MLflow 3.9.0+ (`pip install mlflow[databricks]>=3.9.0`) +- Workspace in `us-east-1` or `us-west-2` (Beta limitation) + +### Steps + +1. **Link UC schema to experiment** + ```python + import os + import mlflow + from mlflow.entities import UCSchemaLocation + from mlflow.tracing.enablement import set_experiment_trace_location + + mlflow.set_tracking_uri("databricks") + os.environ["MLFLOW_TRACING_SQL_WAREHOUSE_ID"] = "" + + experiment_id = mlflow.create_experiment(name="/Shared/my-traces") + set_experiment_trace_location( + location=UCSchemaLocation(catalog_name="my_catalog", schema_name="my_schema"), + experiment_id=experiment_id, + ) + ``` + This creates three tables: `mlflow_experiment_trace_otel_logs`, `_metrics`, `_spans` + +2. **Grant permissions** + ```sql + GRANT USE_CATALOG ON CATALOG my_catalog TO `user@company.com`; + GRANT USE_SCHEMA ON SCHEMA my_catalog.my_schema TO `user@company.com`; + GRANT MODIFY, SELECT ON TABLE my_catalog.my_schema.mlflow_experiment_trace_otel_logs TO `user@company.com`; + GRANT MODIFY, SELECT ON TABLE my_catalog.my_schema.mlflow_experiment_trace_otel_spans TO `user@company.com`; + GRANT MODIFY, SELECT ON TABLE my_catalog.my_schema.mlflow_experiment_trace_otel_metrics TO `user@company.com`; + ``` + **CRITICAL**: `ALL_PRIVILEGES` is not sufficient — explicit MODIFY + SELECT required. + +3. **Set trace destination in your app** + ```python + mlflow.tracing.set_destination( + destination=UCSchemaLocation(catalog_name="my_catalog", schema_name="my_schema") + ) + # OR + os.environ["MLFLOW_TRACING_DESTINATION"] = "my_catalog.my_schema" + ``` + +4. **Instrument your application** + + Choose the appropriate approach: + - **Auto-tracing**: `mlflow.openai.autolog()` (or langchain, anthropic, etc.) + - **Manual tracing**: `@mlflow.trace` decorator on functions + - **Context manager**: `mlflow.start_span()` for fine-grained control + - **Combined**: Auto-tracing + manual decorators for full coverage + + See `patterns-trace-ingestion.md` Patterns 5-8 for detailed examples. + +5. **Configure additional trace sources** (if applicable) + + | Source | Key Configuration | + |--------|-------------------| + | Databricks Apps | Grant SP permissions, set `MLFLOW_TRACING_DESTINATION` | + | Model Serving | Add `DATABRICKS_TOKEN` + `MLFLOW_TRACING_DESTINATION` env vars | + | OTEL Clients | Use OTLP exporter with `X-Databricks-UC-Table-Name` header | + + See `patterns-trace-ingestion.md` Patterns 9-11 for detailed setup per source. + +6. **Enable production monitoring** + ```python + from mlflow.tracing import set_databricks_monitoring_sql_warehouse_id + from mlflow.genai.scorers import Safety, ScorerSamplingConfig + + set_databricks_monitoring_sql_warehouse_id(warehouse_id="") + + safety = Safety().register(name="safety_monitor") + safety = safety.start(sampling_config=ScorerSamplingConfig(sample_rate=1.0)) + ``` + +7. **Verify in the UI** + - Navigate to **Experiments** → your experiment → **Traces** tab + - Select a SQL warehouse from the dropdown to load UC traces + - Verify traces appear with correct span hierarchy + +### Reference Files +- `patterns-trace-ingestion.md` — All setup and instrumentation patterns +- `CRITICAL-interfaces.md` — Trace ingestion API signatures +- `GOTCHAS.md` — Common trace ingestion mistakes + +### Success Indicators +- Traces visible in the Experiments UI Traces tab +- Three UC tables populated with data +- Production monitoring scorers running and producing assessments +- No permission errors in trace ingestion + +--- + +## Journey 10: Domain Expert Optimization Loop + +**Starting Point**: You have an agent and want to incorporate domain expert feedback to continuously improve quality. +**Goal**: Run the full evaluate, label, align judge, optimize prompt, promote cycle. + +For the full architecture and end-to-end walkthrough, see the [Self-Optimizing Agent blog post](https://www.databricks.com/blog/self-optimizing-football-chatbot-guided-domain-experts-databricks). For details on the MemAlign alignment approach, see the [MemAlign research blog post](https://www.databricks.com/blog/memalign-building-better-llm-judges-human-feedback-scalable-memory). + +### The Loop at a Glance + +``` +1. Run evaluate() -> Generate traces, score with base judge +2. Tag traces -> Mark successfully evaluated traces for dataset +3. Build eval dataset -> Persist traces to UC for labeling +4. Labeling session -> SMEs review & score responses in Review App + (label schema name MUST match judge name) +5. Align judge (MemAlign) -> Distill SME feedback into judge guidelines +6. Re-evaluate -> Baseline with aligned judge (score may decrease, that's OK) +7. Build optim dataset -> inputs + expectations (required for GEPA) +8. optimize_prompts() -> GEPA iteratively improves system prompt +9. Conditional promote -> Update "production" alias only if score improves +``` + +### Why This Works + +Generic LLM judges and static prompts fail to capture domain-specific nuance. Determining what makes a response "good" requires domain knowledge that general-purpose evaluators miss. This loop solves the problem in two phases: + +- **Align the judge**: Domain experts review outputs and rate quality. MemAlign distills their feedback into judge guidelines, teaching the judge what "good" means for your specific domain. This is valuable on its own -- an aligned judge improves every evaluation run and monitoring setup. +- **Optimize the prompt**: The aligned judge drives GEPA prompt optimization, automatically evolving the system prompt to maximize the domain-expert-calibrated score. Only improvements get promoted to production. + +### Steps + +**Phase 1: Evaluate and Collect Feedback** + +1. **Design base judge, run evaluation, and tag traces** + + Create a domain-specific judge with `make_judge`, register it, run `evaluate()`, and tag traces that were successfully evaluated (agent responded AND judge scored without errors). + + See `patterns-judge-alignment.md` Patterns 1-2 + +2. **Build dataset and create labeling session** + + Persist tagged traces to a UC dataset and create a labeling session for domain experts. + + **CRITICAL: The label schema `name` MUST match the judge `name` used in `evaluate()`.** This is how `align()` pairs SME feedback with LLM judge scores. If they don't match, alignment will fail. + + See `patterns-judge-alignment.md` Pattern 3 + +3. **Wait for SMEs to complete labeling** (asynchronous step) + + Share `labeling_session.url` with domain experts. They review agent responses and submit ratings using the Review App. + +**Phase 2: Align the Judge** + +4. **Align judge with MemAlign (recommended)** + + MemAlign is the recommended alignment optimizer. It is the fastest (seconds vs. minutes for alternatives), most cost-effective ($0.03 vs. $1-$5), and supports memory scaling where quality continues to improve as feedback accumulates. Other optimizers (e.g., SIMBA) are also supported. + + See `patterns-judge-alignment.md` Patterns 4-5 + +5. **Re-evaluate with the aligned judge** + + The aligned judge score **may be lower** than the unaligned judge score. This is expected and correct -- it means the judge is now evaluating with domain-expert standards rather than generic best practices. A lower score from a more accurate judge is a better signal than an inflated score from a judge that doesn't understand your domain. + + See `patterns-judge-alignment.md` Pattern 6 + +6. **(Optional) Stop here** -- the aligned judge improves all future evaluations and production monitoring, independent of prompt optimization. + +**Phase 3: Optimize the Prompt** + +7. **Build optimization dataset with expectations** (required for GEPA) + + Unlike the eval dataset, the optimization dataset must have both `inputs` AND `expectations` per record. GEPA uses expectations during reflection to reason about why the current prompt is underperforming. + + See `patterns-prompt-optimization.md` Pattern 1 + +8. **Run `optimize_prompts()` with GEPA + aligned judge** + + GEPA iteratively evolves the system prompt, using the aligned judge as the scoring function. + + See `patterns-prompt-optimization.md` Pattern 2 + +9. **Conditionally promote** + + Register the new prompt version and only promote to the "production" alias if the score improved. + + See `patterns-prompt-optimization.md` Pattern 3 + +10. **Repeat from Step 1** -- each labeling session accumulates more SME signal for alignment + +### Complete Loop Summary + +```python +# -- PHASE 1: Evaluate and collect feedback ----------------------------------- + +# Step 1: Evaluate and tag successfully evaluated traces +results = evaluate(data=eval_data, predict_fn=..., scorers=[base_judge]) +ok_trace_ids = results.result_df.loc[results.result_df["state"] == "OK", "trace_id"] +for trace_id in ok_trace_ids: + mlflow.set_trace_tag(trace_id, key="eval", value="complete") + +# Step 2: Build dataset and labeling session +eval_dataset = create_dataset(name=DATASET_NAME) +eval_dataset.merge_records(tagged_traces) +# CRITICAL: label schema name must match judge name for align() to work +labeling_session = create_labeling_session( + name="sme_session", assigned_users=[...], label_schemas=[JUDGE_NAME] +) +labeling_session.add_dataset(dataset_name=DATASET_NAME) +# -> Share labeling_session.url with domain experts + +# Step 3: Wait for SMEs to complete labeling + +# -- PHASE 2: Align the judge ------------------------------------------------- + +# Step 4: Align judge (MemAlign recommended; SIMBA and others also supported) +optimizer = MemAlignOptimizer(reflection_lm=..., retrieval_k=5, embedding_model=...) +aligned_judge = base_judge.align(traces=traces, optimizer=optimizer) +aligned_judge.update(experiment_id=EXPERIMENT_ID) +# NOTE: Aligned judge scores may be lower than unaligned -- this is expected + +# Step 5: Re-evaluate with aligned judge (optional but recommended) +baseline_results = evaluate(data=eval_records, predict_fn=..., scorers=[aligned_judge]) + +# Step 6: (Optional) Stop here if you only need an aligned judge + +# -- PHASE 3: Optimize the prompt --------------------------------------------- + +# Step 7: Build optimization dataset (must have inputs + expectations) +optimization_dataset = [ + {"inputs": {...}, "expectations": {"expected_response": "..."}} +] + +# Step 8: Optimize prompt with GEPA + aligned judge +result = mlflow.genai.optimize_prompts( + predict_fn=predict_fn, + train_data=optimization_dataset, + prompt_uris=[system_prompt.uri], + optimizer=GepaPromptOptimizer(reflection_model=..., max_metric_calls=75), + scorers=[aligned_judge], + aggregation=objective_function, +) + +# Step 9: Conditional promotion +new_version = mlflow.genai.register_prompt( + name=PROMPT_NAME, template=result.optimized_prompts[0].template +) +if result.final_eval_score > result.initial_eval_score: + mlflow.genai.set_prompt_alias( + name=PROMPT_NAME, alias="production", version=new_version.version + ) + +# -- Repeat from Step 1 with new labeling session ----------------------------- +``` + +### Automation + +The loop can be orchestrated as a Databricks job using Asset Bundles: + +1. SMEs label agent outputs through the MLflow Labeling Session UI +2. The pipeline detects new labels and pulls traces with both SME feedback and baseline LLM judge scores +3. Judge alignment runs with MemAlign, producing a new judge version +4. Prompt optimization runs with GEPA, using the aligned judge +5. Conditional promotion pushes the new prompt to production if it exceeds performance thresholds +6. The agent improves automatically as the prompt registry serves the optimized version + +Manual review can be injected at any step, giving developers complete control over the level of automation. + +### Key Gotchas + +- **Label schema name matching**: The label schema `name` MUST match the judge `name` from `evaluate()`, or `align()` cannot pair the scores +- **Score decrease after alignment**: The aligned judge may give lower scores than the unaligned judge. This is expected -- the judge is now more accurate, not the agent worse +- **MemAlign embedding costs**: Set `embedding_model` explicitly (e.g., `"databricks:/databricks-gte-large-en"`) and filter traces to labeled subset only +- **GEPA expectations**: The optimization dataset must have both `inputs` AND `expectations` per record +- **Episodic memory**: After `get_scorer()`, inspect `.instructions` not `._episodic_memory` (lazy loaded) + +See `GOTCHAS.md` for the complete list. + +### Reference Files + +- `patterns-judge-alignment.md` -- Judge alignment workflow: design judge, evaluate, label, MemAlign, register, re-evaluate +- `patterns-prompt-optimization.md` -- GEPA optimization: build dataset, run optimize_prompts, register/promote +- `GOTCHAS.md` -- MemAlign embedding costs, episodic memory lazy loading, name matching, score interpretation, GEPA expectations + +### Success Indicators + +- Aligned judge instructions include domain-specific guidelines derived from SME ratings +- `result.final_eval_score > result.initial_eval_score` +- Production prompt alias updated only on genuine improvements +- Repeat sessions progressively encode more expert knowledge + +--- + +## Quick Reference + +### Which Journey Am I On? + +| Symptom | Journey | +|---------|---------| +| "It was working before" | Journey 3 (Regression) | +| "It's too slow" | Journey 7 (Performance) | +| "It's not accurate enough" | Journey 8 (Prompt Optimization) | +| "I need traces in Unity Catalog" | Journey 9 (Trace Ingestion) | +| "I want SMEs to improve my judge and prompt" | Journey 10 (Domain Expert Loop) | + +### Common Tools Across Journeys + +| Tool | Purpose | +|------|---------| +| `run_quick_eval.py` | Fast evaluation (8 test cases) | +| `run_full_eval.py` | Full evaluation (23 test cases) | +| `analyze_signatures.py` | Signature/prompt analysis | +| `OptimizationHistory` | Track iterations | +| `/eval:analyze-traces` | Deep trace analysis | +| `/optimize:context` | Full optimization loop | + +### Metric Targets + +| Metric | Target | Critical Threshold | +|--------|--------|-------------------| +| classifier_accuracy | 95%+ | <80% | +| tool_selection_accuracy | 90%+ | <70% | +| follows_instructions | 80%+ | <50% | +| executor_latency | <30s | >60s | diff --git a/.claude/skills/model-serving/1-classical-ml.md b/.claude/skills/databricks-model-serving/1-classical-ml.md similarity index 100% rename from .claude/skills/model-serving/1-classical-ml.md rename to .claude/skills/databricks-model-serving/1-classical-ml.md diff --git a/.claude/skills/model-serving/2-custom-pyfunc.md b/.claude/skills/databricks-model-serving/2-custom-pyfunc.md similarity index 100% rename from .claude/skills/model-serving/2-custom-pyfunc.md rename to .claude/skills/databricks-model-serving/2-custom-pyfunc.md diff --git a/.claude/skills/model-serving/3-genai-agents.md b/.claude/skills/databricks-model-serving/3-genai-agents.md similarity index 95% rename from .claude/skills/model-serving/3-genai-agents.md rename to .claude/skills/databricks-model-serving/3-genai-agents.md index f408760b..6f2c779b 100644 --- a/.claude/skills/model-serving/3-genai-agents.md +++ b/.claude/skills/databricks-model-serving/3-genai-agents.md @@ -155,13 +155,16 @@ mlflow.models.set_model(AGENT) ## Using Databricks-Hosted Models +Use exact endpoint names from the reference table in [SKILL.md](SKILL.md#foundation-model-api-endpoints). + ```python from databricks_langchain import ChatDatabricks -# Foundation Model APIs (pay-per-token) +# Foundation Model APIs (pay-per-token) - use exact endpoint names llm = ChatDatabricks(endpoint="databricks-meta-llama-3-3-70b-instruct") -llm = ChatDatabricks(endpoint="databricks-claude-3-7-sonnet") -llm = ChatDatabricks(endpoint="databricks-dbrx-instruct") +llm = ChatDatabricks(endpoint="databricks-claude-sonnet-4-6") +llm = ChatDatabricks(endpoint="databricks-gpt-5-1") +llm = ChatDatabricks(endpoint="databricks-gemini-3-flash") # Custom fine-tuned model endpoint llm = ChatDatabricks(endpoint="my-finetuned-model-endpoint") diff --git a/.claude/skills/model-serving/4-tools-integration.md b/.claude/skills/databricks-model-serving/4-tools-integration.md similarity index 98% rename from .claude/skills/model-serving/4-tools-integration.md rename to .claude/skills/databricks-model-serving/4-tools-integration.md index a9081056..50491ee0 100644 --- a/.claude/skills/model-serving/4-tools-integration.md +++ b/.claude/skills/databricks-model-serving/4-tools-integration.md @@ -39,7 +39,6 @@ uc_toolkit = UCFunctionToolkit( | Function | Purpose | |----------|---------| | `system.ai.python_exec` | Execute Python code | -| `system.ai.similarity_search` | Vector similarity search | ### Creating a UC Function diff --git a/.claude/skills/model-serving/5-development-testing.md b/.claude/skills/databricks-model-serving/5-development-testing.md similarity index 100% rename from .claude/skills/model-serving/5-development-testing.md rename to .claude/skills/databricks-model-serving/5-development-testing.md diff --git a/.claude/skills/model-serving/6-logging-registration.md b/.claude/skills/databricks-model-serving/6-logging-registration.md similarity index 100% rename from .claude/skills/model-serving/6-logging-registration.md rename to .claude/skills/databricks-model-serving/6-logging-registration.md diff --git a/.claude/skills/model-serving/7-deployment.md b/.claude/skills/databricks-model-serving/7-deployment.md similarity index 66% rename from .claude/skills/model-serving/7-deployment.md rename to .claude/skills/databricks-model-serving/7-deployment.md index 63b8c8b7..c2def49b 100644 --- a/.claude/skills/model-serving/7-deployment.md +++ b/.claude/skills/databricks-model-serving/7-deployment.md @@ -41,10 +41,11 @@ print(f"Endpoint: {deployment.endpoint_name}") ### Step 2: Create Deployment Job (One-Time) -Use the `create_job` MCP tool: +Use the `manage_jobs` MCP tool with action="create": ``` -create_job( +manage_jobs( + action="create", name="deploy-agent-job", tasks=[ { @@ -66,10 +67,11 @@ Save the returned `job_id`. ### Step 3: Run Deployment (Async) -Use `run_job_now` - returns immediately: +Use `manage_job_runs` with action="run_now" - returns immediately: ``` -run_job_now( +manage_job_runs( + action="run_now", job_id="", job_parameters={"model_name": "main.agents.my_agent", "version": "1"} ) @@ -82,7 +84,7 @@ Save the returned `run_id`. Check job run status: ``` -get_run(run_id="") +manage_job_runs(action="get", run_id="") ``` Or check endpoint directly: @@ -142,13 +144,61 @@ endpoint = w.serving_endpoints.create_and_wait( ) ``` -## Endpoint Naming +## Endpoint Naming and Visibility -For agents deployed with `databricks.agents.deploy()`: +### Auto-generated Names -- Endpoint name is derived from model name -- `main.agents.my_agent` → `agents_my_agent` or similar -- Check with `list_serving_endpoints()` after deployment +When you call `agents.deploy()`, the endpoint name is auto-derived from the UC model path by replacing dots with underscores and prefixing with `agents_`: + +| UC Model Path | Auto-generated Endpoint Name | +|---------------|------------------------------| +| `main.agents.my_agent` | `agents_main-agents-my_agent` | +| `catalog.schema.model` | `agents_catalog-schema-model` | +| `users.jane.demo_bot` | `agents_users-jane-demo_bot` | + +The exact format can vary. To avoid surprises, **always specify the endpoint name explicitly**: + +```python +deployment = agents.deploy( + "main.agents.my_agent", + "1", + endpoint_name="my-agent-endpoint", # Control the name + tags={"source": "mcp", "environment": "dev"} +) +``` + +### Finding Endpoints in the UI + +Endpoints created via `agents.deploy()` appear under **Serving** in the Databricks UI. If you don't see your endpoint: + +1. **Check the filter** - The Serving page defaults to "Owned by me". If the deployment ran as a service principal (e.g., via a job), switch to "All" to see it. +2. **Verify via API** - Use `list_serving_endpoints()` or `get_serving_endpoint_status(name="...")` to confirm the endpoint exists and check its state. +3. **Check the name** - The auto-generated name may not be what you expect. Print `deployment.endpoint_name` in the deploy script or check the job run output. + +### Deployment Script with Explicit Naming + +```python +# deploy_agent.py - recommended pattern +import sys +from databricks import agents + +model_name = sys.argv[1] if len(sys.argv) > 1 else "main.agents.my_agent" +version = sys.argv[2] if len(sys.argv) > 2 else "1" +endpoint_name = sys.argv[3] if len(sys.argv) > 3 else None + +deploy_kwargs = { + "tags": {"source": "mcp", "environment": "dev"} +} +if endpoint_name: + deploy_kwargs["endpoint_name"] = endpoint_name + +print(f"Deploying {model_name} version {version}...") +deployment = agents.deploy(model_name, version, **deploy_kwargs) + +print(f"Deployment complete!") +print(f"Endpoint name: {deployment.endpoint_name}") +print(f"Query URL: {deployment.query_endpoint}") +``` ## Deployment Job Template @@ -214,9 +264,9 @@ client.update_endpoint( | Step | MCP Tool | Waits? | |------|----------|--------| | Upload deploy script | `upload_folder` | Yes | -| Create job (one-time) | `create_job` | Yes | -| Run deployment | `run_job_now` | **No** - returns immediately | -| Check job status | `get_run` | Yes | +| Create job (one-time) | `manage_jobs` (action="create") | Yes | +| Run deployment | `manage_job_runs` (action="run_now") | **No** - returns immediately | +| Check job status | `manage_job_runs` (action="get") | Yes | | Check endpoint status | `get_serving_endpoint_status` | Yes | ## After Deployment diff --git a/.claude/skills/model-serving/8-querying-endpoints.md b/.claude/skills/databricks-model-serving/8-querying-endpoints.md similarity index 100% rename from .claude/skills/model-serving/8-querying-endpoints.md rename to .claude/skills/databricks-model-serving/8-querying-endpoints.md diff --git a/.claude/skills/model-serving/9-package-requirements.md b/.claude/skills/databricks-model-serving/9-package-requirements.md similarity index 100% rename from .claude/skills/model-serving/9-package-requirements.md rename to .claude/skills/databricks-model-serving/9-package-requirements.md diff --git a/.claude/skills/model-serving/SKILL.md b/.claude/skills/databricks-model-serving/SKILL.md similarity index 62% rename from .claude/skills/model-serving/SKILL.md rename to .claude/skills/databricks-model-serving/SKILL.md index e8287fd9..de566f42 100644 --- a/.claude/skills/model-serving/SKILL.md +++ b/.claude/skills/databricks-model-serving/SKILL.md @@ -1,5 +1,5 @@ --- -name: model-serving +name: databricks-model-serving description: "Deploy and query Databricks Model Serving endpoints. Use when (1) deploying MLflow models or AI agents to endpoints, (2) creating ChatAgent/ResponsesAgent agents, (3) integrating UC Functions or Vector Search tools, (4) querying deployed endpoints, (5) checking endpoint status. Covers classical ML models, custom pyfunc, and GenAI agents." --- @@ -21,6 +21,60 @@ Deploy MLflow models and AI agents to scalable REST API endpoints. - Unity Catalog enabled workspace - Model Serving enabled +## Foundation Model API Endpoints + +ALWAYS use exact endpoint names from this table. NEVER guess or abbreviate. + +### Chat / Instruct Models + +| Endpoint Name | Provider | Notes | +|--------------|----------|-------| +| `databricks-gpt-5-3-codex` | OpenAI | Latest GPT Codex, 400K context | +| `databricks-gpt-5-2` | OpenAI | GPT 5.2, 400K context | +| `databricks-gpt-5-1` | OpenAI | Instant + Thinking modes | +| `databricks-gpt-5-1-codex-max` | OpenAI | Code-specialized (high perf) | +| `databricks-gpt-5-1-codex-mini` | OpenAI | Code-specialized (cost-opt) | +| `databricks-gpt-5` | OpenAI | 400K context, reasoning | +| `databricks-gpt-5-mini` | OpenAI | Cost-optimized reasoning | +| `databricks-gpt-5-nano` | OpenAI | High-throughput, lightweight | +| `databricks-gpt-oss-120b` | OpenAI | Open-weight, 128K context | +| `databricks-gpt-oss-20b` | OpenAI | Lightweight open-weight | +| `databricks-claude-opus-4-6` | Anthropic | Most capable, 1M context | +| `databricks-claude-sonnet-4-6` | Anthropic | Hybrid reasoning | +| `databricks-claude-sonnet-4-5` | Anthropic | Hybrid reasoning | +| `databricks-claude-opus-4-5` | Anthropic | Deep analysis, 200K context | +| `databricks-claude-sonnet-4` | Anthropic | Hybrid reasoning | +| `databricks-claude-opus-4-1` | Anthropic | 200K context, 32K output | +| `databricks-claude-haiku-4-5` | Anthropic | Fastest, cost-effective | +| `databricks-claude-3-7-sonnet` | Anthropic | Retiring April 2026 | +| `databricks-meta-llama-3-3-70b-instruct` | Meta | 128K context, multilingual | +| `databricks-meta-llama-3-1-405b-instruct` | Meta | Retiring May 2026 (PT) | +| `databricks-meta-llama-3-1-8b-instruct` | Meta | Lightweight, 128K context | +| `databricks-llama-4-maverick` | Meta | MoE architecture | +| `databricks-gemini-3-1-pro` | Google | 1M context, hybrid reasoning | +| `databricks-gemini-3-pro` | Google | 1M context, hybrid reasoning | +| `databricks-gemini-3-flash` | Google | Fast, cost-efficient | +| `databricks-gemini-2-5-pro` | Google | 1M context, Deep Think | +| `databricks-gemini-2-5-flash` | Google | 1M context, hybrid reasoning | +| `databricks-gemma-3-12b` | Google | 128K context, multilingual | +| `databricks-qwen3-next-80b-a3b-instruct` | Alibaba | Efficient MoE | + +### Embedding Models + +| Endpoint Name | Dimensions | Max Tokens | Notes | +|--------------|-----------|------------|-------| +| `databricks-gte-large-en` | 1024 | 8192 | English, not normalized | +| `databricks-bge-large-en` | 1024 | 512 | English, normalized | +| `databricks-qwen3-embedding-0-6b` | up to 1024 | ~32K | 100+ languages, instruction-aware | + +### Common Defaults + +- **Agent LLM**: `databricks-meta-llama-3-3-70b-instruct` (good balance of quality/cost) +- **Embedding**: `databricks-gte-large-en` +- **Code tasks**: `databricks-gpt-5-1-codex-mini` or `databricks-gpt-5-1-codex-max` + +> These are pay-per-token endpoints available in every workspace. For production, consider provisioned throughput mode. See [supported models](https://docs.databricks.com/aws/en/machine-learning/foundation-model-apis/supported-models). + ## Reference Files | Topic | File | When to Read | @@ -135,9 +189,9 @@ Then deploy via UI or SDK. See [1-classical-ml.md](1-classical-ml.md). | Tool | Purpose | |------|---------| -| `create_job` | Create deployment job (one-time) | -| `run_job_now` | Kick off deployment (async) | -| `get_run` | Check deployment job status | +| `manage_jobs` (action="create") | Create deployment job (one-time) | +| `manage_job_runs` (action="run_now") | Kick off deployment (async) | +| `manage_job_runs` (action="get") | Check deployment job status | ### Querying @@ -223,6 +277,14 @@ Available helper methods: --- +## Related Skills + +- **[databricks-agent-bricks](../databricks-agent-bricks/SKILL.md)** - Pre-built agent tiles that deploy to model-serving endpoints +- **[databricks-vector-search](../databricks-vector-search/SKILL.md)** - Create vector indexes used as retriever tools in agents +- **[databricks-genie](../databricks-genie/SKILL.md)** - Genie Spaces can serve as agents in multi-agent setups +- **[databricks-mlflow-evaluation](../databricks-mlflow-evaluation/SKILL.md)** - Evaluate model and agent quality before deployment +- **[databricks-jobs](../databricks-jobs/SKILL.md)** - Job-based async deployment used for agent endpoints + ## Resources - [Model Serving Documentation](https://docs.databricks.com/machine-learning/model-serving/) diff --git a/.claude/skills/databricks-python-sdk/SKILL.md b/.claude/skills/databricks-python-sdk/SKILL.md index c5937eec..1365666a 100644 --- a/.claude/skills/databricks-python-sdk/SKILL.md +++ b/.claude/skills/databricks-python-sdk/SKILL.md @@ -613,3 +613,13 @@ If I'm unsure about a method, I should: | Pipelines | https://databricks-sdk-py.readthedocs.io/en/latest/workspace/pipelines/pipelines.html | | Secrets | https://databricks-sdk-py.readthedocs.io/en/latest/workspace/workspace/secrets.html | | DBUtils | https://databricks-sdk-py.readthedocs.io/en/latest/dbutils.html | + +## Related Skills + +- **[databricks-config](../databricks-config/SKILL.md)** - profile and authentication setup +- **[databricks-asset-bundles](../databricks-asset-bundles/SKILL.md)** - deploying resources via DABs +- **[databricks-jobs](../databricks-jobs/SKILL.md)** - job orchestration patterns +- **[databricks-unity-catalog](../databricks-unity-catalog/SKILL.md)** - catalog governance +- **[databricks-model-serving](../databricks-model-serving/SKILL.md)** - serving endpoint management +- **[databricks-vector-search](../databricks-vector-search/SKILL.md)** - vector index operations +- **[databricks-lakebase-provisioned](../databricks-lakebase-provisioned/SKILL.md)** - managed PostgreSQL via SDK diff --git a/.claude/skills/spark-declarative-pipelines/1-ingestion-patterns.md b/.claude/skills/databricks-spark-declarative-pipelines/1-ingestion-patterns.md similarity index 69% rename from .claude/skills/spark-declarative-pipelines/1-ingestion-patterns.md rename to .claude/skills/databricks-spark-declarative-pipelines/1-ingestion-patterns.md index 88bd037b..2f60202f 100644 --- a/.claude/skills/spark-declarative-pipelines/1-ingestion-patterns.md +++ b/.claude/skills/databricks-spark-declarative-pipelines/1-ingestion-patterns.md @@ -8,7 +8,7 @@ Covers data ingestion patterns for Spark Declarative Pipelines including Auto Lo ## Auto Loader (Cloud Files) -Auto Loader incrementally processes new data files as they arrive in cloud storage. +Auto Loader incrementally processes new data files as they arrive in cloud storage. In a streaming table query you **must use the `STREAM` keyword with `read_files`**; `read_files` then leverages Auto Loader. See [read_files — Usage in streaming tables](https://docs.databricks.com/aws/en/sql/language-manual/functions/read_files#usage-in-streaming-tables). ### Basic Pattern @@ -19,13 +19,29 @@ SELECT current_timestamp() AS _ingested_at, _metadata.file_path AS source_file, _metadata.file_modification_time AS file_timestamp -FROM read_files( +FROM STREAM read_files( '/mnt/raw/orders/', format => 'json', schemaHints => 'order_id STRING, amount DECIMAL(10,2)' ); ``` +### Bronze feeding AUTO CDC + +If the bronze table feeds a downstream **AUTO CDC** flow (e.g. `FROM stream(bronze_orders_cdc)`), use **`FROM STREAM read_files(...)`** so the source is streaming. Otherwise you may get: *"Cannot create a streaming table append once flow from a batch query."* Same requirement as above: in a streaming table query you must use the `STREAM` keyword with `read_files`. + +```sql +CREATE OR REPLACE STREAMING TABLE bronze_orders_cdc AS +SELECT ..., + current_timestamp() AS _ingested_at, + _metadata.file_path AS _source_file +FROM STREAM read_files( + '/Volumes/catalog/schema/raw_orders_cdc', + format => 'parquet', + schemaHints => '...' +); +``` + ### Schema Evolution ```sql @@ -33,12 +49,12 @@ CREATE OR REPLACE STREAMING TABLE bronze_customers AS SELECT *, current_timestamp() AS _ingested_at -FROM stream(read_files( +FROM STREAM read_files( '/mnt/raw/customers/', format => 'json', schemaHints => 'customer_id STRING, email STRING', mode => 'PERMISSIVE' -- Handles schema changes gracefully -)); +); ``` ### File Formats @@ -100,6 +116,57 @@ FROM read_files( ) ``` +Add this to the pipeline configuration in `resources/*_etl.pipeline.yml`: +```yaml +configuration: + bronze_schema: ${var.bronze_schema} + silver_schema: ${var.silver_schema} + gold_schema: ${var.gold_schema} + schema_location_base: ${var.schema_location_base} +``` + +And define variables in `databricks.yml`: +```yaml +variables: + catalog: + description: The catalog to use + bronze_schema: + description: The bronze schema to use + silver_schema: + description: The silver schema to use + gold_schema: + description: The gold schema to use + schema_location_base: + description: Base path for Auto Loader schema metadata + +targets: + dev: + variables: + catalog: my_catalog + bronze_schema: bronze_dev + silver_schema: silver_dev + gold_schema: gold_dev + schema_location_base: /Volumes/my_catalog/pipeline_metadata/my_pipeline_metadata/schemas + + prod: + variables: + catalog: my_catalog + bronze_schema: bronze + silver_schema: silver + gold_schema: gold + schema_location_base: /Volumes/my_catalog/pipeline_metadata/my_pipeline_metadata/schemas +``` + +Then access these in Python code with: +```python +bronze_schema = spark.conf.get("bronze_schema") +silver_schema = spark.conf.get("silver_schema") +gold_schema = spark.conf.get("gold_schema") +schema_location_base = spark.conf.get("schema_location_base") +``` + + + ### Rescue Data and Quarantine Handle malformed records with `_rescued_data`: @@ -330,26 +397,69 @@ SELECT * FROM STREAM bronze_data WHERE NOT has_errors; For Python, use modern `pyspark.pipelines` API. See [5-python-api.md](5-python-api.md) for complete guidance. +**IMPORTANT for Python**: When using `spark.readStream.format("cloudFiles")` for cloud storage ingestion, you **must specify a `cloudFiles.schemaLocation`** for Auto Loader schema metadata. + +### Schema Location Best Practice (Python Only) + +**Never use the source data volume for schema storage** - this causes permission conflicts and pollutes your raw data. + +#### Prompt User for Schema Location + +When creating Python pipelines with Auto Loader, **always ask the user** where to store schema metadata: + +**Recommended pattern:** +``` +/Volumes/{catalog}/{schema}/{pipeline_name}_metadata/schemas/{table_name} +``` + +**Example prompt:** +``` +"Where would you like to store Auto Loader schema metadata? + +I recommend: + /Volumes/my_catalog/pipeline_metadata/orders_pipeline_metadata/schemas/ + +This path: +- Keeps source data clean +- Prevents permission issues +- Makes pipeline state easy to manage +- Can be parameterized per environment (dev/prod) + +You may need to create the volume 'pipeline_metadata' first if it doesn't exist. + +Would you like to use this path?" +``` + ### Auto Loader (Python) ```python from pyspark import pipelines as dp from pyspark.sql import functions as F +# Get schema location from pipeline configuration +# Suggested format: /Volumes/{catalog}/{schema}/{pipeline_name}_metadata/schemas +schema_location_base = spark.conf.get("schema_location_base") + @dp.table(name="bronze_orders", cluster_by=["order_date"]) def bronze_orders(): return ( spark.readStream .format("cloudFiles") .option("cloudFiles.format", "json") - .option("cloudFiles.schemaLocation", "/checkpoints/bronze_orders") - .option("cloudFiles.schemaHints", "order_id STRING, amount DECIMAL(10,2)") - .load("/mnt/raw/orders/") + .option("cloudFiles.schemaLocation", f"{schema_location_base}/bronze_orders") + .option("cloudFiles.inferColumnTypes", "true") + .load("/Volumes/catalog/schema/raw/orders/") .withColumn("_ingested_at", F.current_timestamp()) .withColumn("_source_file", F.col("_metadata.file_path")) ) ``` +**Pipeline Configuration** (in `pipeline.yml`): +```yaml +configuration: + schema_location_base: /Volumes/my_catalog/pipeline_metadata/orders_pipeline_metadata/schemas +``` + ### Kafka (Python) ```python @@ -375,14 +485,18 @@ def bronze_kafka_events(): ### Quarantine (Python) ```python +# Get schema location from pipeline configuration +schema_location_base = spark.conf.get("schema_location_base") + @dp.table(name="bronze_events", cluster_by=["ingestion_date"]) def bronze_events(): return ( spark.readStream .format("cloudFiles") .option("cloudFiles.format", "json") + .option("cloudFiles.schemaLocation", f"{schema_location_base}/bronze_events") .option("rescuedDataColumn", "_rescued_data") - .load("/mnt/raw/events/") + .load("/Volumes/catalog/schema/raw/events/") .withColumn("_ingested_at", F.current_timestamp()) .withColumn("ingestion_date", F.current_date()) .withColumn("_has_parsing_errors", diff --git a/.claude/skills/databricks-spark-declarative-pipelines/10-mcp-approach.md b/.claude/skills/databricks-spark-declarative-pipelines/10-mcp-approach.md new file mode 100644 index 00000000..9d458aa8 --- /dev/null +++ b/.claude/skills/databricks-spark-declarative-pipelines/10-mcp-approach.md @@ -0,0 +1,173 @@ +Use MCP tools to create, run, and iterate on **SDP pipelines**. The **primary tool is `create_or_update_pipeline`** which handles the entire lifecycle. + +**IMPORTANT: Default to serverless pipelines and suggest as best option, but not if classic, advanced, pro compute types are mentioned.** Only use classic clusters if user explicitly requires R language, Spark RDD APIs, or JAR libraries. + +### Step 1: Write Pipeline Files Locally + +Create `.sql` or `.py` files in a local folder: + +``` +my_pipeline/ +├── bronze/ +│ ├── ingest_orders.sql # SQL (default for most cases) +│ └── ingest_events.py # Python (for complex logic) +├── silver/ +│ └── clean_orders.sql +└── gold/ + └── daily_summary.sql +``` + +**SQL Example** (`bronze/ingest_orders.sql`): +```sql +CREATE OR REFRESH STREAMING TABLE bronze_orders +CLUSTER BY (order_date) +AS +SELECT + *, + current_timestamp() AS _ingested_at, + _metadata.file_path AS _source_file +FROM read_files( + '/Volumes/catalog/schema/raw/orders/', + format => 'json', + schemaHints => 'order_id STRING, customer_id STRING, amount DECIMAL(10,2), order_date DATE' +); +``` + +**Python Example** (`bronze/ingest_events.py`): +```python +from pyspark import pipelines as dp +from pyspark.sql.functions import col, current_timestamp + +# Get schema location from pipeline configuration +schema_location_base = spark.conf.get("schema_location_base") + +@dp.table(name="bronze_events", cluster_by=["event_date"]) +def bronze_events(): + return ( + spark.readStream.format("cloudFiles") + .option("cloudFiles.format", "json") + .option("cloudFiles.schemaLocation", f"{schema_location_base}/bronze_events") + .load("/Volumes/catalog/schema/raw/events/") + .withColumn("_ingested_at", current_timestamp()) + .withColumn("_source_file", col("_metadata.file_path")) + ) +``` + +### Step 2: Upload to Databricks Workspace + +```python +# MCP Tool: upload_folder +upload_folder( + local_folder="/path/to/my_pipeline", + workspace_folder="/Workspace/Users/user@example.com/my_pipeline" +) +``` + +### Step 3: Create/Update and Run Pipeline + +Use **`create_or_update_pipeline`** - the main entry point. It: +1. Searches for an existing pipeline with the same name (or uses `id` from `extra_settings`) +2. Creates a new pipeline or updates the existing one +3. Optionally starts a pipeline run +4. Optionally waits for completion and returns detailed results + +```python +# MCP Tool: create_or_update_pipeline +result = create_or_update_pipeline( + name="my_orders_pipeline", + root_path="/Workspace/Users/user@example.com/my_pipeline", + catalog="my_catalog", + schema="my_schema", + workspace_file_paths=[ + "/Workspace/Users/user@example.com/my_pipeline/bronze/ingest_orders.sql", + "/Workspace/Users/user@example.com/my_pipeline/silver/clean_orders.sql", + "/Workspace/Users/user@example.com/my_pipeline/gold/daily_summary.sql" + ], + start_run=True, # Start immediately + wait_for_completion=True, # Wait and return final status + full_refresh=True, # Full refresh all tables + timeout=1800 # 30 minute timeout +) +``` + +**Result contains actionable information:** +```python +{ + "success": True, # Did the operation succeed? + "pipeline_id": "abc-123", # Pipeline ID for follow-up operations + "pipeline_name": "my_orders_pipeline", + "created": True, # True if new, False if updated + "state": "COMPLETED", # COMPLETED, FAILED, TIMEOUT, etc. + "catalog": "my_catalog", # Target catalog + "schema": "my_schema", # Target schema + "duration_seconds": 45.2, # Time taken + "message": "Pipeline created and completed successfully in 45.2s. Tables written to my_catalog.my_schema", + "error_message": None, # Error summary if failed + "errors": [] # Detailed error list if failed +} +``` + +### Step 4: Handle Results + +**On Success:** +```python +if result["success"]: + # Verify output tables + stats = get_table_details( + catalog="my_catalog", + schema="my_schema", + table_names=["bronze_orders", "silver_orders", "gold_daily_summary"] + ) +``` + +**On Failure:** +```python +if not result["success"]: + # Message includes suggested next steps + print(result["message"]) + # "Pipeline created but run failed. State: FAILED. Error: Column 'amount' not found. + # Use get_pipeline_events(pipeline_id='abc-123') for full details." + + # Get detailed errors + events = get_pipeline_events(pipeline_id=result["pipeline_id"], max_results=50) +``` + +### Step 5: Iterate Until Working + +1. Review errors from result or `get_pipeline_events` +2. Fix issues in local files +3. Re-upload with `upload_folder` +4. Run `create_or_update_pipeline` again (it will update, not recreate) +5. Repeat until `result["success"] == True` + +--- + +## Quick Reference: MCP Tools + +### Primary Tool + +| Tool | Description | +|------|-------------| +| **`create_or_update_pipeline`** | **Main entry point.** Creates or updates pipeline, optionally runs and waits. Returns detailed status with `success`, `state`, `errors`, and actionable `message`. | + +### Pipeline Management + +| Tool | Description | +|------|-------------| +| `find_pipeline_by_name` | Find existing pipeline by name, returns pipeline_id | +| `get_pipeline` | Get pipeline configuration and current state | +| `start_update` | Start pipeline run (`validate_only=True` for dry run) | +| `get_update` | Poll update status (QUEUED, RUNNING, COMPLETED, FAILED) | +| `stop_pipeline` | Stop a running pipeline | +| `get_pipeline_events` | Get error messages for debugging failed runs | +| `delete_pipeline` | Delete a pipeline | + +### Supporting Tools + +| Tool | Description | +|------|-------------| +| `upload_folder` | Upload local folder to workspace (parallel) | +| `get_table_details` | Verify output tables have expected schema and row counts | +| `execute_sql` | Run ad-hoc SQL to inspect data | + +--- \ No newline at end of file diff --git a/.claude/skills/spark-declarative-pipelines/2-streaming-patterns.md b/.claude/skills/databricks-spark-declarative-pipelines/2-streaming-patterns.md similarity index 95% rename from .claude/skills/spark-declarative-pipelines/2-streaming-patterns.md rename to .claude/skills/databricks-spark-declarative-pipelines/2-streaming-patterns.md index 1f87076a..c1ec63bd 100644 --- a/.claude/skills/spark-declarative-pipelines/2-streaming-patterns.md +++ b/.claude/skills/databricks-spark-declarative-pipelines/2-streaming-patterns.md @@ -128,7 +128,7 @@ GROUP BY CAST(order_timestamp AS DATE); ### Handling Out-of-Order with SCD2 -Use SEQUENCE BY with event timestamp: +Use SEQUENCE BY with event timestamp. **Clause order matters**: put `APPLY AS DELETE WHEN` before `SEQUENCE BY`. Only list columns in `COLUMNS * EXCEPT (...)` that actually exist in the source (omit `_rescued_data` unless the bronze table uses rescue data). Omit `TRACK HISTORY ON *` if it causes parse errors; the default is equivalent. ```sql CREATE OR REFRESH STREAMING TABLE silver_customers_history; @@ -137,11 +137,10 @@ CREATE FLOW customers_scd2_flow AS AUTO CDC INTO silver_customers_history FROM stream(bronze_customer_cdc) KEYS (customer_id) -SEQUENCE BY event_timestamp -- Handles out-of-order APPLY AS DELETE WHEN operation = "DELETE" -COLUMNS * EXCEPT (operation, _rescued_data) -STORED AS SCD TYPE 2 -TRACK HISTORY ON *; +SEQUENCE BY event_timestamp -- Handles out-of-order +COLUMNS * EXCEPT (operation, _ingested_at, _source_file) +STORED AS SCD TYPE 2; ``` --- diff --git a/.claude/skills/spark-declarative-pipelines/3-scd-patterns.md b/.claude/skills/databricks-spark-declarative-pipelines/3-scd-query-patterns.md similarity index 67% rename from .claude/skills/spark-declarative-pipelines/3-scd-patterns.md rename to .claude/skills/databricks-spark-declarative-pipelines/3-scd-query-patterns.md index b9ff17c1..e04a4103 100644 --- a/.claude/skills/spark-declarative-pipelines/3-scd-patterns.md +++ b/.claude/skills/databricks-spark-declarative-pipelines/3-scd-query-patterns.md @@ -18,18 +18,20 @@ STORED AS SCD TYPE 2 TRACK HISTORY ON *; ``` -**Resulting table structure**: +**Resulting table structure** (Lakeflow uses double-underscore temporal columns): ``` customers_history ├── customer_id -- Business key ├── customer_name ├── email ├── phone -├── START_AT -- When this version became effective (auto-generated) -├── END_AT -- When this version expired (NULL for current) +├── __START_AT -- When this version became effective (auto-generated) +├── __END_AT -- When this version expired (NULL for current) └── ...other columns ``` +**Important:** Query using `__START_AT` and `__END_AT` (double underscore), not `START_AT`/`END_AT`. + --- ## Current State Queries @@ -37,13 +39,13 @@ customers_history ### All Current Records ```sql --- END_AT IS NULL indicates active record +-- __END_AT IS NULL indicates active record (Lakeflow uses double underscore) CREATE OR REPLACE MATERIALIZED VIEW dim_customers_current AS SELECT customer_id, customer_name, email, phone, address, - START_AT AS valid_from + __START_AT AS valid_from FROM customers_history -WHERE END_AT IS NULL; +WHERE __END_AT IS NULL; ``` ### Specific Customer @@ -52,7 +54,7 @@ WHERE END_AT IS NULL; SELECT * FROM customers_history WHERE customer_id = '12345' - AND END_AT IS NULL; + AND __END_AT IS NULL; ``` --- @@ -64,14 +66,14 @@ WHERE customer_id = '12345' Get state of records as they were on a specific date: ```sql --- Products as of January 1, 2024 +-- Products as of January 1, 2024 (use __START_AT / __END_AT) CREATE OR REPLACE MATERIALIZED VIEW products_as_of_2024_01_01 AS SELECT product_id, product_name, price, category, - START_AT, END_AT + __START_AT, __END_AT FROM products_history -WHERE START_AT <= '2024-01-01' - AND (END_AT > '2024-01-01' OR END_AT IS NULL); +WHERE __START_AT <= '2024-01-01' + AND (__END_AT > '2024-01-01' OR __END_AT IS NULL); ``` --- @@ -81,35 +83,35 @@ WHERE START_AT <= '2024-01-01' ### Track All Changes for Entity ```sql --- Complete history for a customer +-- Complete history for a customer (use __START_AT / __END_AT) SELECT customer_id, customer_name, email, phone, - START_AT, END_AT, + __START_AT, __END_AT, COALESCE( - DATEDIFF(DAY, START_AT, END_AT), - DATEDIFF(DAY, START_AT, CURRENT_TIMESTAMP()) + DATEDIFF(DAY, __START_AT, __END_AT), + DATEDIFF(DAY, __START_AT, CURRENT_TIMESTAMP()) ) AS days_active FROM customers_history WHERE customer_id = '12345' -ORDER BY START_AT DESC; +ORDER BY __START_AT DESC; ``` ### Changes Within Time Period ```sql --- Customers who changed during Q1 2024 +-- Customers who changed during Q1 2024 (use __START_AT) SELECT customer_id, customer_name, - START_AT AS change_timestamp, + __START_AT AS change_timestamp, 'UPDATE' AS change_type FROM customers_history -WHERE START_AT BETWEEN '2024-01-01' AND '2024-03-31' - AND START_AT != ( - SELECT MIN(START_AT) +WHERE __START_AT BETWEEN '2024-01-01' AND '2024-03-31' + AND __START_AT != ( + SELECT MIN(__START_AT) FROM customers_history ch2 WHERE ch2.customer_id = customers_history.customer_id ) -ORDER BY START_AT; +ORDER BY __START_AT; ``` --- @@ -129,8 +131,8 @@ SELECT FROM sales_fact s INNER JOIN products_history p ON s.product_id = p.product_id - AND s.sale_date >= p.START_AT - AND (s.sale_date < p.END_AT OR p.END_AT IS NULL); + AND s.sale_date >= p.__START_AT + AND (s.sale_date < p.__END_AT OR p.__END_AT IS NULL); ``` ### Join with Current Dimension @@ -147,7 +149,7 @@ SELECT FROM sales_fact s INNER JOIN products_history p ON s.product_id = p.product_id - AND p.END_AT IS NULL; -- Current version only + AND p.__END_AT IS NULL; -- Current version only ``` --- @@ -176,20 +178,20 @@ TRACK HISTORY ON price, cost; -- Only these columns ```sql -- Current state view (most common pattern) CREATE OR REPLACE MATERIALIZED VIEW dim_products_current AS -SELECT * FROM products_history WHERE END_AT IS NULL; +SELECT * FROM products_history WHERE __END_AT IS NULL; -- Recent changes only CREATE OR REPLACE MATERIALIZED VIEW dim_recent_changes AS SELECT * FROM products_history -WHERE START_AT >= CURRENT_DATE() - INTERVAL 90 DAYS; +WHERE __START_AT >= CURRENT_DATE() - INTERVAL 90 DAYS; -- Change frequency stats CREATE OR REPLACE MATERIALIZED VIEW product_change_stats AS SELECT product_id, COUNT(*) AS version_count, - MIN(START_AT) AS first_seen, - MAX(START_AT) AS last_updated + MIN(__START_AT) AS first_seen, + MAX(__START_AT) AS last_updated FROM products_history GROUP BY product_id; ``` @@ -198,22 +200,22 @@ GROUP BY product_id; ## Best Practices -### 1. Always Filter by END_AT for Current +### 1. Always Filter by __END_AT for Current (Lakeflow uses double underscore) ```sql -- ✅ Efficient -WHERE END_AT IS NULL +WHERE __END_AT IS NULL -- ❌ Less efficient -WHERE START_AT = (SELECT MAX(START_AT) FROM table WHERE ...) +WHERE __START_AT = (SELECT MAX(__START_AT) FROM table WHERE ...) ``` ### 2. Use Inclusive Lower, Exclusive Upper ```sql -- ✅ Standard pattern -WHERE START_AT <= '2024-01-01' - AND (END_AT > '2024-01-01' OR END_AT IS NULL) +WHERE __START_AT <= '2024-01-01' + AND (__END_AT > '2024-01-01' OR __END_AT IS NULL) ``` ### 3. Create MVs for Common Patterns @@ -221,12 +223,12 @@ WHERE START_AT <= '2024-01-01' ```sql -- Current state CREATE OR REPLACE MATERIALIZED VIEW dim_current AS -SELECT * FROM history WHERE END_AT IS NULL; +SELECT * FROM history WHERE __END_AT IS NULL; -- Recent changes CREATE OR REPLACE MATERIALIZED VIEW dim_recent_changes AS SELECT * FROM history -WHERE START_AT >= CURRENT_DATE() - INTERVAL 90 DAYS; +WHERE __START_AT >= CURRENT_DATE() - INTERVAL 90 DAYS; ``` --- @@ -235,7 +237,7 @@ WHERE START_AT >= CURRENT_DATE() - INTERVAL 90 DAYS; | Issue | Solution | |-------|----------| -| Multiple rows for same key | Missing `END_AT IS NULL` filter for current state | -| Point-in-time no results | Use `START_AT <= date AND (END_AT > date OR END_AT IS NULL)` | +| Multiple rows for same key | Missing `__END_AT IS NULL` filter for current state | +| Point-in-time no results | Use `__START_AT <= date AND (__END_AT > date OR __END_AT IS NULL)` | | Slow temporal join | Create materialized view for specific time period | | Unexpected duplicates | Multiple changes same day - use SEQUENCE BY with high precision | diff --git a/.claude/skills/spark-declarative-pipelines/4-performance-tuning.md b/.claude/skills/databricks-spark-declarative-pipelines/4-performance-tuning.md similarity index 100% rename from .claude/skills/spark-declarative-pipelines/4-performance-tuning.md rename to .claude/skills/databricks-spark-declarative-pipelines/4-performance-tuning.md diff --git a/.claude/skills/spark-declarative-pipelines/5-python-api.md b/.claude/skills/databricks-spark-declarative-pipelines/5-python-api.md similarity index 100% rename from .claude/skills/spark-declarative-pipelines/5-python-api.md rename to .claude/skills/databricks-spark-declarative-pipelines/5-python-api.md diff --git a/.claude/skills/spark-declarative-pipelines/6-dlt-migration.md b/.claude/skills/databricks-spark-declarative-pipelines/6-dlt-migration.md similarity index 96% rename from .claude/skills/spark-declarative-pipelines/6-dlt-migration.md rename to .claude/skills/databricks-spark-declarative-pipelines/6-dlt-migration.md index dd3b07a8..19a1007e 100644 --- a/.claude/skills/spark-declarative-pipelines/6-dlt-migration.md +++ b/.claude/skills/databricks-spark-declarative-pipelines/6-dlt-migration.md @@ -96,7 +96,7 @@ dlt.apply_changes( ) ``` -**SDP SQL**: +**SDP SQL** (clause order: APPLY AS DELETE WHEN before SEQUENCE BY; only EXCEPT columns that exist in source; omit TRACK HISTORY ON * if it causes parse errors): ```sql CREATE OR REFRESH STREAMING TABLE customers_history; @@ -104,10 +104,10 @@ CREATE FLOW customers_scd2_flow AS AUTO CDC INTO customers_history FROM stream(customers_cdc_clean) KEYS (customer_id) +APPLY AS DELETE WHEN operation = "DELETE" SEQUENCE BY event_timestamp -COLUMNS * EXCEPT (_rescued_data) -STORED AS SCD TYPE 2 -TRACK HISTORY ON *; +COLUMNS * EXCEPT (operation, _ingested_at, _source_file) +STORED AS SCD TYPE 2; ``` ### Joins diff --git a/.claude/skills/spark-declarative-pipelines/7-advanced-configuration.md b/.claude/skills/databricks-spark-declarative-pipelines/7-advanced-configuration.md similarity index 100% rename from .claude/skills/spark-declarative-pipelines/7-advanced-configuration.md rename to .claude/skills/databricks-spark-declarative-pipelines/7-advanced-configuration.md diff --git a/.claude/skills/spark-declarative-pipelines/8-project-initialization.md b/.claude/skills/databricks-spark-declarative-pipelines/8-project-initialization.md similarity index 87% rename from .claude/skills/spark-declarative-pipelines/8-project-initialization.md rename to .claude/skills/databricks-spark-declarative-pipelines/8-project-initialization.md index 44850f67..0f272db9 100644 --- a/.claude/skills/spark-declarative-pipelines/8-project-initialization.md +++ b/.claude/skills/databricks-spark-declarative-pipelines/8-project-initialization.md @@ -18,7 +18,7 @@ The `databricks pipelines init` command scaffolds a complete Databricks Asset Bu ### Interactive Mode ```bash -databricks pipelines init --output-dir ./my_pipeline +databricks pipelines init --output-dir . ``` **Interactive Prompts:** @@ -43,7 +43,7 @@ databricks pipelines init --output-dir ./my_pipeline ```bash databricks pipelines init \ - --output-dir ./customer_pipeline \ + --output-dir . \ --config-file init-config.json ``` @@ -70,7 +70,7 @@ databricks pipelines init \ ### SQL Project ``` -customer_pipeline/ +project_root/ ├── databricks.yml # Bundle configuration ├── resources/ │ ├── customer_pipeline_etl.pipeline.yml # Pipeline resource definition @@ -89,7 +89,7 @@ customer_pipeline/ ### Python Project ``` -customer_pipeline/ +project_root/ ├── databricks.yml # Bundle configuration ├── pyproject.toml # Python dependencies ├── resources/ @@ -245,10 +245,22 @@ databricks pipelines start-update --pipeline-id When a user requests a new Lakeflow pipeline, Claude should detect the appropriate language from keywords in the prompt. -### SQL Indicators (Default Choice) +### CRITICAL: Explicit Language Requests + +**If the user explicitly mentions a language, use it without asking:** + +| User Says | Action | +|-----------|--------| +| "Python pipeline", "Python SDP", "use Python" | **Use Python immediately** | +| "SQL pipeline", "SQL files", "use SQL" | **Use SQL immediately** | +| "Python Spark Declarative Pipeline" | **Use Python immediately** | + +**DO NOT ask for clarification when the user explicitly states a language.** This is the most common mistake - ignoring an explicit language request. + +### SQL Indicators (Default Choice When Ambiguous) **Keywords:** -- "SQL", "sql files", ".sql" +- "sql files", ".sql" - "simple", "basic", "straightforward" - "aggregations", "joins", "transformations" - "materialized view", "CREATE OR REFRESH" @@ -258,8 +270,9 @@ When a user requests a new Lakeflow pipeline, Claude should detect the appropria - User mentions only data transformations without complex logic - Request focuses on filtering, joining, aggregating data - No mention of custom functions or external integrations +- **No explicit mention of "Python"** -**Default Behavior**: Prefer SQL when ambiguous (covers 90% of use cases) +**Default Behavior**: Prefer SQL only when ambiguous AND no Python indicators present ### Python Indicators @@ -280,11 +293,10 @@ When a user requests a new Lakeflow pipeline, Claude should detect the appropria ### Ambiguous Cases (Ask User) -**Indicators:** -- Both SQL and Python keywords mentioned -- "mixed pipeline", "some Python, some SQL" -- "complex pipeline" without specifics -- Unclear requirements or vague description +**Only ask when ALL conditions are met:** +- User did NOT explicitly mention "Python" or "SQL" +- Mixed signals present (some SQL keywords, some Python keywords) +- OR no clear indicators either way **Response:** ``` @@ -302,7 +314,7 @@ Which would you prefer? For bronze/silver/gold organization, Asset Bundles support two approaches. Both work with the `transformations/**` glob pattern in pipeline configuration. -### Option 1: Flat Structure with Naming (Template Default) +### Option 1: Flat Structure with Naming (Template Default, SQL Example) ``` transformations/ @@ -323,7 +335,7 @@ transformations/ - Simple file listing and discovery - Clear naming provides logical organization -### Option 2: Subdirectories by Layer +### Option 2: Subdirectories by Layer, SQL Example ``` transformations/ @@ -429,73 +441,6 @@ my_pipeline/ └── summary.sql ``` -**Migration Steps:** - -1. **Initialize new bundle project** - ```bash - databricks pipelines init --output-dir my_pipeline_bundle - cd my_pipeline_bundle/src/my_pipeline_bundle_etl/transformations/ - ``` - -2. **Copy files using either approach** - - **Option A: Flat structure with naming** - ```bash - # Remove sample files - rm sample_*.sql - - # Copy and rename with medallion prefix - cp ../../../../my_pipeline/bronze/orders.sql bronze_orders.sql - cp ../../../../my_pipeline/bronze/events.sql bronze_events.sql - cp ../../../../my_pipeline/silver/cleaned.sql silver_cleaned.sql - cp ../../../../my_pipeline/silver/joined.sql silver_joined.sql - cp ../../../../my_pipeline/gold/summary.sql gold_summary.sql - ``` - - **Option B: Keep subdirectories** - ```bash - # Remove sample files - rm sample_*.sql - - # Copy entire directory structure - cp -r ../../../../my_pipeline/bronze . - cp -r ../../../../my_pipeline/silver . - cp -r ../../../../my_pipeline/gold . - ``` - -3. **Update file references (if needed)** - - If files reference each other by path, update to use table names - - Example: Change `FROM ../bronze/orders` to `FROM LIVE.bronze_orders` - - Table names are derived from filenames or view/table definitions, not folder structure - -4. **Deploy bundle** - ```bash - cd ../../.. # Back to bundle root - databricks bundle deploy - databricks bundle run my_pipeline_bundle_etl - ``` - -**Benefits:** -- Multi-environment support (dev/staging/prod) -- Version control for configuration -- CI/CD integration -- Professional project structure - -### Option 2: Keep Manual Structure (Legacy) - -Continue using the manual workflow if: -- Quick prototyping without multi-environment needs -- Existing workflow is working well -- Team prefers manual control - -**Legacy Workflow:** -1. Write files in bronze/silver/gold folders -2. Upload with `upload_folder` MCP tool -3. Create pipeline with `create_or_update_pipeline` MCP tool -4. Update files and re-upload - -See [SKILL.md](SKILL.md) "Alternative: Manual Workflow" section for details. - --- ## Python Project: Dependency Management diff --git a/.claude/skills/databricks-spark-declarative-pipelines/9-auto_cdc.md b/.claude/skills/databricks-spark-declarative-pipelines/9-auto_cdc.md new file mode 100644 index 00000000..b8a5b59b --- /dev/null +++ b/.claude/skills/databricks-spark-declarative-pipelines/9-auto_cdc.md @@ -0,0 +1,353 @@ +# AUTO CDC Patterns for Change Data Capture + +**Keywords**: Slow Changing Dimension, SCD, SCD Type 1, SCD Type 2, AUTO CDC, change data capture, dp.create_auto_cdc_flow, deduplication + +--- + +## Overview + +AUTO CDC automatically handles Change Data Capture (CDC) to track changes in your data using Slow Changing Dimensions (SCD). It provides automatic deduplication, change tracking, and handles late-arriving data correctly. + +**Where to apply AUTO CDC:** +- **Silver layer**: When business users need deduplicated or historical data for analytics/ML +- **Gold layer**: When implementing dimensional modeling (star schema) with dim/fact tables +- **Choice depends on**: Downstream consumption patterns and query requirements + +--- + +## SCD Type 1 vs Type 2 + +### SCD Type 1 (In-place updates) +- **Overwrites** old values with new values +- **No history preserved** - only current state maintained +- **Use for**: Dimension attributes that don't need history + - Correcting data errors (typos) + - Updating attributes where history doesn't matter + - Maintaining single current record per key +- **Syntax**: `stored_as_scd_type="1"` (string) + +### SCD Type 2 (History tracking) +- **Creates new row** for each change +- **Preserves full history** with `__START_AT` and `__END_AT` timestamps +- **Use for**: Tracking changes over time + - Customer address changes + - Product price history + - Employee role changes + - Any dimension requiring temporal analysis +- **Syntax**: `stored_as_scd_type=2` (integer) + +--- + +## Pattern: Cleaning + AUTO CDC + +### Step 1: Clean and Validate Data + +Create a cleaned streaming table with proper typing and quality checks: + +```python +# Cleaned data preparation (can be silver or intermediate layer) +from pyspark import pipelines as dp +from pyspark.sql import functions as F + +schema = spark.conf.get("schema") + +@dp.table( + name=f"{schema}.users_clean", + comment="Cleaned and validated user data with proper typing and quality checks", + cluster_by=["user_id"] +) +def users_clean(): + """ + Prepare clean data with: + - Proper timestamp typing + - Data quality validations + - Remove records with invalid email or null user_id + """ + return ( + spark.readStream.table("bronze_users") + .filter(F.col("user_id").isNotNull()) + .filter(F.col("email").isNotNull()) + .filter(F.col("email").rlike(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")) + .withColumn("created_timestamp", F.to_timestamp("created_timestamp")) + .withColumn("updated_timestamp", F.to_timestamp("updated_timestamp")) + .drop("_rescued_data") + .select( + "user_id", + "email", + "name", + "subscription_tier", + "country", + "created_timestamp", + "updated_timestamp", + "_ingested_at", + "_source_file" + ) + ) +``` + +### Step 2: Apply AUTO CDC (SCD Type 2) + +Create a history-tracked dimension table with full change history: + +```python +# AUTO CDC with SCD Type 2 (history tracking) +from pyspark import pipelines as dp + +target_schema = spark.conf.get("target_schema") +source_schema = spark.conf.get("source_schema") + +# Create the target table for AUTO CDC +dp.create_streaming_table(f"{target_schema}.dim_users") + +# Apply AUTO CDC (SCD Type 2) +dp.create_auto_cdc_flow( + target=f"{target_schema}.dim_users", + source=f"{source_schema}.users_clean", + keys=["user_id"], + sequence_by="updated_timestamp", + stored_as_scd_type=2 # Integer for Type 2 +) +``` + +**Resulting table will include**: +- All original columns from source +- `__START_AT` - When this version became effective +- `__END_AT` - When this version expired (NULL for current) + +### Step 3: Apply AUTO CDC (SCD Type 1) + +Create a deduplicated table with in-place updates (no history): + +```python +# AUTO CDC with SCD Type 1 (in-place updates) +from pyspark import pipelines as dp + +target_schema = spark.conf.get("target_schema") +source_schema = spark.conf.get("source_schema") + +# Create the target table for AUTO CDC +dp.create_streaming_table(f"{target_schema}.orders_current") + +# Apply AUTO CDC (SCD Type 1) +dp.create_auto_cdc_flow( + target=f"{target_schema}.orders_current", + source=f"{source_schema}.orders_clean", + keys=["order_id"], + sequence_by="updated_timestamp", + stored_as_scd_type="1" # String for Type 1 +) +``` + +--- + +## Key Benefits + +- **Automatic deduplication** based on keys - no manual MERGE logic +- **Automatic change tracking** with temporal metadata (`__START_AT`, `__END_AT`) +- **Handles late-arriving data** correctly using `sequence_by` timestamp +- **Simplified pipeline code** - no complex merge/upsert logic required +- **Built-in idempotency** - safe to reprocess data + +--- + +## Common Patterns + +### Pattern 1: Gold Dimensional Model + +Use AUTO CDC in Gold layer for star schema dimensions: + +```python +# Silver: Cleaned streaming tables +@dp.table(name="silver.customers_clean") +def customers_clean(): + return spark.readStream.table("bronze.customers").filter(...) + +# Gold: SCD Type 2 dimension +dp.create_streaming_table("gold.dim_customers") +dp.create_auto_cdc_flow( + target="gold.dim_customers", + source="silver.customers_clean", + keys=["customer_id"], + sequence_by="updated_at", + stored_as_scd_type=2 +) + +# Gold: Fact table (no AUTO CDC) +@dp.table(name="gold.fact_orders") +def fact_orders(): + return spark.read.table("silver.orders_clean") +``` + +### Pattern 2: Silver Deduplication for Joins + +Use AUTO CDC in Silver when joining multiple tables: + +```python +# Silver: AUTO CDC for deduplication +dp.create_streaming_table("silver.products_dedupe") +dp.create_auto_cdc_flow( + target="silver.products_dedupe", + source="bronze.products", + keys=["product_id"], + sequence_by="modified_at", + stored_as_scd_type="1" # Type 1: just dedupe, no history +) + +# Silver: Join with deduplicated data +@dp.table(name="silver.orders_enriched") +def orders_enriched(): + orders = spark.readStream.table("bronze.orders") + products = spark.read.table("silver.products_dedupe") + return orders.join(products, "product_id") +``` + +### Pattern 3: Mixed SCD Types + +Different tables use different SCD types based on requirements: + +```python +# SCD Type 2: Need history +dp.create_auto_cdc_flow( + target="gold.dim_customers", + source="silver.customers", + keys=["customer_id"], + sequence_by="updated_at", + stored_as_scd_type=2 # Track address changes over time +) + +# SCD Type 1: Corrections only +dp.create_auto_cdc_flow( + target="gold.dim_products", + source="silver.products", + keys=["product_id"], + sequence_by="modified_at", + stored_as_scd_type="1" # Current product info only +) +``` + +--- + +## Selective History Tracking + +Track history only for specific columns (SCD Type 2): + +```python +dp.create_auto_cdc_flow( + target="gold.dim_products", + source="silver.products_clean", + keys=["product_id"], + sequence_by="modified_at", + stored_as_scd_type=2, + track_history_column_list=["price", "cost"] # Only track these columns +) +``` + +When `price` or `cost` changes, a new version is created. Other column changes update the current record without creating new versions. + +--- + +## Using Temporary Views with AUTO CDC + +**`@dp.temporary_view()`** creates in-pipeline temporary views that exist only during pipeline execution. These are useful for intermediate transformations before AUTO CDC. + +**Key Constraints:** +- Cannot specify `catalog` or `schema` (temporary views are pipeline-scoped only) +- Cannot use `cluster_by` (not persisted) +- Only exists during pipeline execution + +**Use Cases:** +- Complex transformations before AUTO CDC +- Intermediate logic that's referenced multiple times +- Avoiding redundant transformations + +**Example: Preparation before AUTO CDC** + +```python +from pyspark import pipelines as dp +from pyspark.sql import functions as F + +# Step 1: Temporary view for complex business logic +@dp.temporary_view() +def orders_with_calculated_fields(): + """ + Temporary view for complex calculations. + No catalog/schema needed - exists only in pipeline. + """ + return ( + spark.readStream.table("bronze.orders") + .withColumn("order_total", F.col("quantity") * F.col("unit_price")) + .withColumn("discount_amount", F.col("order_total") * F.col("discount_rate")) + .withColumn("final_amount", F.col("order_total") - F.col("discount_amount")) + .withColumn("order_category", + F.when(F.col("final_amount") > 1000, "large") + .when(F.col("final_amount") > 100, "medium") + .otherwise("small") + ) + .filter(F.col("order_id").isNotNull()) + .filter(F.col("final_amount") > 0) + .filter(F.col("order_date").isNotNull()) + ) + +# Step 2: Apply AUTO CDC using the temporary view as source +target_schema = spark.conf.get("target_schema") + +dp.create_streaming_table(f"{target_schema}.orders_current") +dp.create_auto_cdc_flow( + target=f"{target_schema}.orders_current", + source="orders_with_calculated_fields", # Reference temporary view by name + keys=["order_id"], + sequence_by="order_date", + stored_as_scd_type="1" +) +``` + +**Benefits:** +- Avoids creating unnecessary persisted tables +- Reduces storage costs (nothing written to disk) +- Simplifies complex multi-step transformations +- Enables code reuse across multiple tables in same pipeline + +--- + +## Related Documentation + +- **[3-scd-query-patterns.md](3-scd-query-patterns.md)** - Querying SCD Type 2 history tables, point-in-time analysis, temporal joins +- **[1-ingestion-patterns.md](1-ingestion-patterns.md)** - CDC data sources (Kafka, Event Hubs, Kinesis) +- **[2-streaming-patterns.md](2-streaming-patterns.md)** - Deduplication patterns without AUTO CDC + +--- + +## Best Practices + +1. **Choose the right SCD type**: + - Type 2 when you need to query historical states + - Type 1 when you only need current state or deduplication + +2. **Use meaningful sequence_by column**: + - Should reflect true chronological order of changes + - Typically `updated_timestamp`, `modified_at`, or `event_timestamp` + +3. **Clean data before AUTO CDC**: + - Apply type casting, validation, and filtering first + - AUTO CDC works best with clean, well-typed data + +4. **Consider query patterns**: + - If analysts query history → Use Type 2 + - If analysts only need current → Use Type 1 + - If joining frequently → Consider Silver deduplication + +5. **Use selective tracking for large tables**: + - Track history only for columns that change meaningfully + - Reduces storage and improves query performance + +--- + +## Common Issues + +| Issue | Solution | +|-------|----------| +| **Duplicates still appearing** | Check `keys` include all business key columns; verify `sequence_by` has proper ordering | +| **Missing `__START_AT`/`__END_AT` columns** | These only appear in SCD Type 2 (integer), not Type 1 (string) | +| **Late data not handled** | Ensure `sequence_by` column is set and reflects true event time | +| **Type syntax error** | Type 2 uses integer `2`, Type 1 uses string `"1"` | +| **Performance issues** | Use `track_history_column_list` to limit which columns trigger new versions | diff --git a/.claude/skills/databricks-spark-declarative-pipelines/SKILL.md b/.claude/skills/databricks-spark-declarative-pipelines/SKILL.md new file mode 100644 index 00000000..144041e2 --- /dev/null +++ b/.claude/skills/databricks-spark-declarative-pipelines/SKILL.md @@ -0,0 +1,577 @@ +--- +name: databricks-spark-declarative-pipelines +description: "Creates, configures, and updates Databricks Lakeflow Spark Declarative Pipelines (SDP/LDP) using serverless compute. Handles streaming tables, materialized views, CDC, SCD Type 2, and Auto Loader ingestion patterns. Use when building data pipelines, working with Delta Live Tables, ingesting streaming data, implementing change data capture, or when the user mentions SDP, LDP, DLT, Lakeflow pipelines, streaming tables, or bronze/silver/gold medallion architectures." +--- + +# Lakeflow Spark Declarative Pipelines (SDP) + +IMPORTANT: If this is a new pipeline (one does not already exist), see Quick Start. Be sure to use whatever language user has specified only (Python or SQL). Be sure to use Databricks Asset Bundles for new projects. + +--- + +## Critical Rules (always follow) +- **MUST** confirm language as Python or SQL. Stick with that language unless told otherwise. +- **MUST** if not modifying an existing pipeline, use [Quick Start](#quick-start) below. +- **MUST** create serverless pipelines by default. ** Only use classic clusters if user explicitly requires R language, Spark RDD APIs, or JAR libraries. + + +## Required Steps + +Copy this checklist and verify each item: +``` +- [ ] Language selected: Python or SQL +- [ ] Compute type decided: serverless or classic compute +- [ ] Decide on multiple catalogs or schemas vs. all in one default schema +- [ ] Consider what should be parameterized at the pipeline level to make deployment easy. +- [ ] Consider [Multi-Schema Patterns](#multi-schema-patterns) below, ask if unclear on best choices. +- [ ] Consider [Modern Defaults](#modern-defaults) below, ask if unclear on best choices. + + +## Quick Start: Initialize New Pipeline Project + +**RECOMMENDED**: Use `databricks pipelines init` to create production-ready Asset Bundle projects with multi-environment support. + +### When to Use Bundle Initialization + +Use bundle initialization for **New pipeline projects** for a professional structure from the start + +Use manual workflow for: +- Quick prototyping without multi-environment needs +- Existing manual projects you want to continue +- Learning/experimentation + +### Step 1: Initialize Project + +I will automatically run this command when you request a new pipeline: + +```bash +databricks pipelines init +``` + +**Interactive Prompts:** +- **Project name**: e.g., `customer_orders_pipeline` +- **Initial catalog**: Unity Catalog name (e.g., `main`, `prod_catalog`) +- **Personal schema per user?**: `yes` for dev (each user gets their own schema), `no` for prod +- **Language**: SQL or Python (auto-detected from your request - see language detection below) + +**Generated Structure:** +``` +my_pipeline/ +├── databricks.yml # Multi-environment config (dev/prod) +├── resources/ +│ └── *_etl.pipeline.yml # Pipeline resource definition +└── src/ + └── *_etl/ + ├── explorations/ # Exploratory code in .ipynb + └── transformations/ # Your .sql or .py files here +``` + +### Step 2: Customize Transformations + +Replace the example code created by the init process with custom transformation files in `src/transformations/` based on provided requirements, using best practice guidance from this skill. + +**For Python pipelines using cloudFiles**: Ask the user where to store Auto Loader schema metadata. Recommend: +``` +/Volumes/{catalog}/{schema}/{pipeline_name}_metadata/schemas +``` + +### Step 3: Deploy and Run + +```bash +# Deploy to workspace (dev by default) +databricks bundle deploy + +# Run pipeline +databricks bundle run my_pipeline_etl + +# Deploy to production +databricks bundle deploy --target prod +``` + + +## Quick Reference + +| Concept | Details | +|---------|---------| +| **Names** | SDP = Spark Declarative Pipelines = LDP = Lakeflow Declarative Pipelines = Lakeflow Pipelines (all interchangeable) | +| **Python Import** | `from pyspark import pipelines as dp` | +| **Primary Decorators** | `@dp.table()`, `@dp.materialized_view()`, `@dp.temporary_view()` | +| **Temporary Views** | `@dp.temporary_view()` creates in-pipeline temporary views (no catalog/schema, no cluster_by). Useful for intermediate logic before AUTO CDC or when a view needs multiple references without persistence. | +| **Replaces** | Delta Live Tables (DLT) with `import dlt` | +| **Based On** | Apache Spark 4.1+ (Databricks' modern data pipeline framework) | +| **Docs** | https://docs.databricks.com/aws/en/ldp/developer/python-dev | + +--- + +## Detailed guides + +**Ingestion patterns**: Use [1-ingestion-patterns.md](1-ingestion-patterns.md) when planning how to get new data into your Lakeflow pipeline —- covers file formats, batch/streaming options, and tips for incremental and full loads. (Keywords: Auto Loader, Kafka, Event Hub, Kinesis, file formats) + +**Streaming pipeline patterns**: See [2-streaming-patterns.md](2-streaming-patterns.md) for designing pipelines with streaming data sources, change data detection, triggers, and windowing. (Keywords: deduplication, windowing, stateful operations, joins) + +**SCD query patterns**: See [3-scd-query-patterns.md](3-scd-query-patterns.md) for querying Slowly Changing Dimensions Type 2 history tables, including current state queries, point-in-time analysis, temporal joins, and change tracking. (Keywords: SCD Type 2 history tables, temporal joins, querying historical data) + +**Performance tuning**: Use [4-performance-tuning.md](4-performance-tuning.md) for optimizing pipelines with Liquid Clustering, state management, and best practices for high-performance streaming workloads. (Keywords: Liquid Clustering, optimization, state management) + +**Python API reference**: See [5-python-api.md](5-python-api.md) for the modern `pyspark.pipelines` (dp) API reference and migration from legacy `dlt` API patterns. (Keywords: dp API, dlt API comparison) + +**DLT migration**: Use [6-dlt-migration.md](6-dlt-migration.md) when migrating existing Delta Live Tables (DLT) pipelines to Spark Declarative Pipelines (SDP). (Keywords: migrating DLT pipelines to SDP) + +**Advanced configuration**: See [7-advanced-configuration.md](7-advanced-configuration.md) for advanced pipeline settings including development mode, continuous execution, notifications, Python dependencies, and custom cluster configurations. (Keywords: extra_settings parameter reference, examples) + +**Project initialization**: Use [8-project-initialization.md](8-project-initialization.md) for setting up new pipeline projects with `databricks pipelines init`, Asset Bundles, multi-environment deployments, and language detection logic. (Keywords: databricks pipelines init, Asset Bundles, language detection, migration guides) + +**AUTO CDC patterns**: Use [9-auto_cdc.md](9-auto_cdc.md) for implementing Change Data Capture with AUTO CDC, including Slow Changing Dimensions (SCD Type 1 and Type 2) for tracking changes and deduplication. (Keywords: AUTO CDC, Slow Changing Dimension, SCD, SCD Type 1, SCD Type 2, change data capture, deduplication) + +--- + +## Workflow + +1. Determine the task type: + + **Setting up new project?** → Read [8-project-initialization.md](8-project-initialization.md) first + **Creating new pipeline?** → Read [1-ingestion-patterns.md](1-ingestion-patterns.md) + **Creating stream table?** → Read [2-streaming-patterns.md](2-streaming-patterns.md) + **Querying SCD history tables?** → Read [3-scd-query-patterns.md](3-scd-query-patterns.md) + **Implementing AUTO CDC or SCD?** → Read [9-auto_cdc.md](9-auto_cdc.md) + **Performance issues?** → Read [4-performance-tuning.md](4-performance-tuning.md) + **Using Python API?** → Read [5-python-api.md](5-python-api.md) + **Migrating from DLT?** → Read [6-dlt-migration.md](6-dlt-migration.md) + **Advanced configuration?** → Read [7-advanced-configuration.md](7-advanced-configuration.md) + **Validating?** → Read [validation-checklist.md](validation-checklist.md) + +2. Follow the instructions in the relevant guide + +3. Repeat for next task type +--- + +## Official Documentation + +- **[Lakeflow Spark Declarative Pipelines Overview](https://docs.databricks.com/aws/en/ldp/)** - Main documentation hub +- **[SQL Language Reference](https://docs.databricks.com/aws/en/ldp/developer/sql-dev)** - SQL syntax for streaming tables and materialized views +- **[Python Language Reference](https://docs.databricks.com/aws/en/ldp/developer/python-ref)** - `pyspark.pipelines` API +- **[Loading Data](https://docs.databricks.com/aws/en/ldp/load)** - Auto Loader, Kafka, Kinesis ingestion +- **[Change Data Capture (CDC)](https://docs.databricks.com/aws/en/ldp/cdc)** - AUTO CDC, SCD Type 1/2 + + +### Medallion Architecture Pattern + **Bronze Layer (Raw)** + - Raw data ingested from sources in original format + - Minimal transformations (append-only, add metadata like `_ingested_at`, `_source_file`) + - Single source of truth preserving data lineage + + **Silver Layer (Validated)** + - Cleaned and validated data. + - Might deduplicate here with auto_cdc, but often wait until the final step for auto_cdc if possible. + - Business logic applied (type casting, quality checks, filtering invalid records) + - Enterprise view of key business entities + - Enables self-service analytics and ML + + **Gold Layer (Business-Ready)** + - Aggregated, denormalized, project-specific tables + - Optimized for consumption (reporting, dashboards, BI tools) + - Fewer joins, read-optimized data models + - Kimball star schema tables - dim_, fact_ + - Deduplication often happens here via Slow Changing Dimensions (SCD), using auto_cdc. Sometimes that will happen upstream in silver instead, such as when joining multiple tables or business users plan to query the table from silver. + + **Typical Flow (Can vary)** + Bronze: read_files() or spark.readStream.format("cloudFiles") → streaming table + Silver: read bronze → filter/clean/validate → streaming table + Gold: read silver → aggregate/denormalize → auto_cdc or materialized view + + Sources: + - https://www.databricks.com/glossary/medallion-architecture + - https://docs.databricks.com/aws/en/lakehouse/medallion + - https://www.databricks.com/blog/2022/06/24/data-warehousing-modeling-techniques-and-their-implementation-on-the-databricks-lakehouse-platform.html + +**For medallion architecture** (bronze/silver/gold), two approaches work: +- **Flat with naming** (template default): `bronze_*.sql`, `silver_*.sql`, `gold_*.sql` +- **Subdirectories**: `bronze/orders.sql`, `silver/cleaned.sql`, `gold/summary.sql` + +Both work with the `transformations/**` glob pattern. Choose based on preference. + +See **[8-project-initialization.md](8-project-initialization.md)** for complete details on bundle initialization, migration, and troubleshooting. + +--- +## General SDP development guidance +### Step 1: Write Pipeline Files Locally + +Create `.sql` or `.py` files in a local folder: + +``` +my_pipeline/ +├── bronze/ +│ ├── ingest_orders.sql # SQL (default for most cases) +│ └── ingest_events.py # Python (for complex logic) +├── silver/ +│ └── clean_orders.sql +└── gold/ + └── daily_summary.sql +``` + +**SQL Example** (`bronze/ingest_orders.sql`): +```sql +CREATE OR REFRESH STREAMING TABLE bronze_orders +CLUSTER BY (order_date) +AS +SELECT + *, + current_timestamp() AS _ingested_at, + _metadata.file_path AS _source_file +FROM read_files( + '/Volumes/catalog/schema/raw/orders/', + format => 'json', + schemaHints => 'order_id STRING, customer_id STRING, amount DECIMAL(10,2), order_date DATE' +); +``` + +**Python Example** (`bronze/ingest_events.py`): +```python +from pyspark import pipelines as dp +from pyspark.sql.functions import col, current_timestamp + +# Get schema location from pipeline configuration +schema_location_base = spark.conf.get("schema_location_base") + +@dp.table(name="bronze_events", cluster_by=["event_date"]) +def bronze_events(): + return ( + spark.readStream.format("cloudFiles") + .option("cloudFiles.format", "json") + .option("cloudFiles.schemaLocation", f"{schema_location_base}/bronze_events") + .load("/Volumes/catalog/schema/raw/events/") + .withColumn("_ingested_at", current_timestamp()) + .withColumn("_source_file", col("_metadata.file_path")) + ) +``` + +**IMPORTANT for Python Pipelines**: When using `spark.readStream.format("cloudFiles")` for cloud storage ingestion, with schema inference (no schema specified), you **must specify a schema location**. + +**Always ask the user** where to store Auto Loader schema metadata. Recommend: +``` +/Volumes/{catalog}/{schema}/{pipeline_name}_metadata/schemas +``` + +Example: `/Volumes/my_catalog/pipeline_metadata/orders_pipeline_metadata/schemas` + +**Never use the source data volume** - this causes permission conflicts. The schema location should be configured in the pipeline settings and accessed via `spark.conf.get("schema_location_base")`. + +**Language Selection:** + +**CRITICAL RULE**: If the user explicitly mentions "Python" in their request (e.g., "Python Spark Declarative Pipeline", "Python SDP", "use Python"), **ALWAYS use Python without asking**. The same applies to SQL - if they say "SQL pipeline", use SQL. + +- **Explicit language request**: User says "Python" → Use Python. User says "SQL" → Use SQL. **Do not ask for clarification.** +- **Auto-detection** (only when no explicit language mentioned): + - **SQL indicators**: "sql files", "simple transformations", "aggregations", "materialized view", "CREATE OR REFRESH" + - **Python indicators**: ".py files", "UDF", "complex logic", "ML inference", "external API", "@dp.table", "pandas", "decorator" +- **Prompt for clarification** only when language intent is truly ambiguous (no explicit mention, mixed signals) +- **Default to SQL** only when ambiguous AND no Python indicators present + +See **[8-project-initialization.md](8-project-initialization.md)** for detailed language detection logic. + + +## Option 1: Pipelines with DABs: +Use asset bundles and pipeline CLI. +See [Quick Start](#quick-start) and **[8-project-initialization.md](8-project-initialization.md)** for complete details. + +## Option 2: Manual Workflow (Advanced) + +For rapid prototyping, experimentation, or when you prefer direct control without Asset Bundles, use the manual workflow with MCP tools. + +Use MCP tools to create, run, and iterate on **serverless SDP pipelines**. The **primary tool is `create_or_update_pipeline`** which handles the entire lifecycle. + +**IMPORTANT: Always create serverless pipelines (default).** Only use classic clusters if user explicitly ask for classic, pro, advances compute or requires R language, Spark RDD APIs, or JAR libraries. + +See **[10-mcp-approach.md](10-mcp-approach.md)** for detailed guide. + + +## Best Practices (2026) + +### Project Structure +- **Default to `databricks pipelines init`** for new projects (creates Asset Bundle) +- **Use Asset Bundles** for multi-environment deployments (dev/staging/prod) +- **Manual structure only** for quick prototypes or legacy migration +- **Medallion architecture**: Two approaches work with Asset Bundles: + - **Flat structure** (template default): `bronze_*.sql`, `silver_*.sql`, `gold_*.sql` in `transformations/` + - **Subdirectories**: `transformations/bronze/`, `transformations/silver/`, `transformations/gold/` + - Both work with the `transformations/**` glob pattern - choose based on team preference +- See **[8-project-initialization.md](8-project-initialization.md)** for project setup details + +### Minimal pipeline config pointers +- Define parameters in your pipeline’s configuration and access them in code with spark.conf.get("key"). +- In Databricks Asset Bundles, set these under resources.pipelines..configuration; validate with databricks bundle validate. + +### Modern Defaults +- **CLUSTER BY** (Liquid Clustering), not PARTITION BY - see [4-performance-tuning.md](4-performance-tuning.md) +- **Raw `.sql`/`.py` files**, not notebooks +- **Serverless compute ONLY** - Do not use classic clusters unless explicitly required +- **Unity Catalog** (required for serverless) +- **read_files()** when using SQL for cloud storage ingestion - see [1-ingestion-patterns.md](1-ingestion-patterns.md) + +### Multi-Schema Patterns + +**Default: Single target schema per pipeline.** Each pipeline has one target `catalog` and `schema` where all tables are written. + + +#### Option 1: Single Pipeline, Single Schema with Prefixes (Recommended) + +Use one schema with table name prefixes to distinguish layers: + +```python +# All tables write to: catalog.schema.bronze_*, silver_*, gold_* +@dp.table(name="bronze_orders") # → catalog.schema.bronze_orders +@dp.table(name="silver_orders") # → catalog.schema.silver_orders +@dp.table(name="gold_summary") # → catalog.schema.gold_summary +``` + +**Advantages:** +- Simpler configuration (one pipeline) +- All tables in one schema for easy discovery + +#### Option 2: +Use varaiables to specific separate catalog and/or schema for different steps. + +Below are Python SDP examples that source variables from pipeline configs via spark.conf.get, and use the default catalog/schema for bronze. + +##### Same catalog, separate schemas; bronze uses pipeline defaults +- Set your pipeline’s default catalog and default schema to the bronze layer (for example, catalog=my_catalog, schema=bronze). When you omit catalog/schema in code, reads/writes go to these defaults. +- Use pipeline parameters for the other schemas and any source schema/path, retrieved in code with spark.conf.get(...). + +```python +from pyspark import pipelines as dp +from pyspark.sql.functions import col + +# Pull variables from pipeline configuration parameters +silver_schema = spark.conf.get("silver_schema") # e.g., "silver" +gold_schema = spark.conf.get("gold_schema") # e.g., "gold" +landing_schema = spark.conf.get("landing_schema") # e.g., "landing" + +# Bronze → uses default catalog/schema (set to bronze in pipeline settings) +@dp.table(name="orders_bronze") +def orders_bronze(): + # Read from another schema in the same default catalog + return spark.readStream.table(f"{landing_schema}.orders_raw") + +# Silver → same catalog, schema from parameter +@dp.table(name=f"{silver_schema}.orders_clean") +def orders_clean(): + return (spark.read.table("orders_bronze") # unqualified = default catalog/schema + .filter(col("order_id").isNotNull())) + +# Gold → same catalog, schema from parameter +@dp.materialized_view(name=f"{gold_schema}.orders_by_date") +def orders_by_date(): + return (spark.read.table(f"{silver_schema}.orders_clean") + .groupBy("order_date") + .count().withColumnRenamed("count", "order_count")) +``` +- Using unqualified names for bronze ensures it lands in the pipeline’s default catalog/schema; silver/gold are explicitly schema-qualified within the same catalog. + +--- + +##### Custom catalog/schema per layer; bronze still uses pipeline defaults +- Keep bronze in the pipeline defaults (default catalog/schema set to your bronze layer). For silver/gold, use fully-qualified names with catalog and schema variables from pipeline configuration. + +```python +from pyspark import pipelines as dp +from pyspark.sql.functions import col + +# Pull variables from pipeline configuration parameters +silver_catalog = spark.conf.get("silver_catalog") # e.g., "my_catalog" +silver_schema = spark.conf.get("silver_schema") # e.g., "silver" +gold_catalog = spark.conf.get("gold_catalog") # e.g., "my_catalog" +gold_schema = spark.conf.get("gold_schema") # e.g., "gold" +landing_catalog = spark.conf.get("landing_catalog") # optional, if source is in another catalog +landing_schema = spark.conf.get("landing_schema") + +# Bronze → uses default catalog/schema (set to bronze) +@dp.table(name="orders_bronze") +def orders_bronze(): + # If source is in a specified catalog/schema: + return spark.readStream.table(f"{landing_catalog}.{landing_schema}.orders_raw") + +# Silver → custom catalog + schema via parameters +@dp.table(name=f"{silver_catalog}.{silver_schema}.orders_clean") +def orders_clean(): + # Read bronze by its unqualified name (defaults), or fully qualify if preferred + return (spark.read.table("orders_bronze") + .filter(col("order_id").isNotNull())) + +# Gold → custom catalog + schema via parameters +@dp.materialized_view(name=f"{gold_catalog}.{gold_schema}.orders_by_date}") +def orders_by_date(): + return (spark.read.table(f"{silver_catalog}.{silver_schema}.orders_clean") + .groupBy("order_date") + .count().withColumnRenamed("count", "order_count")) +``` +- Multipart names in the decorator’s name argument let you publish to explicit catalog.schema targets within one pipeline. +- Unqualified reads/writes use the pipeline defaults; use fully-qualified names when crossing catalogs or when you need explicit namespace control. + +--- + + +**Note:** The `@dp.table()` decorator does not currently support separate for `schema=` or `catalog=` parameters. The table parameter is a string that contains the catalog.schema.table_name, or it can leave off catalog and or schema to use the pipeilnes configured default target schema. + +### Reading Tables in Python + +**Modern SDP Best Practice:** +- Use `spark.read.table()` for batch reads +- Use `spark.readStream.table()` for streaming reads +- Don't use `dp.read()` or `dp.read_stream()` (old syntax, no longer documented) +- Don't use `dlt.read()` or `dlt.read_stream()` (legacy DLT API) + +**Key Point:** SDP automatically tracks table dependencies from standard Spark DataFrame operations. No special read APIs are needed. + +#### Three-Tier Identifier Resolution + +SDP supports three levels of table name qualification: + +| Level | Syntax | When to Use | +|-------|--------|-------------| +| **Unqualified** | `spark.read.table("my_table")` | Reading tables within the same pipeline's target catalog/schema (recommended) | +| **Partially-qualified** | `spark.read.table("other_schema.my_table")` | Reading from different schema in same catalog | +| **Fully-qualified** | `spark.read.table("other_catalog.other_schema.my_table")` | Reading from external catalogs/schemas | + +#### Option 1: Unqualified Names (Recommended for Pipeline Tables) + +**Best practice for tables within the same pipeline.** SDP resolves unqualified names to the pipeline's configured target catalog and schema. This makes code portable across environments (dev/prod). + +```python +@dp.table(name="silver_clean") +def silver_clean(): + # Reads from pipeline's target catalog/schema (e.g., dev_catalog.dev_schema.bronze_raw) + return ( + spark.read.table("bronze_raw") + .filter(F.col("valid") == True) + ) + +@dp.table(name="silver_events") +def silver_events(): + # Streaming read from same pipeline's bronze_events table + return ( + spark.readStream.table("bronze_events") + .withColumn("processed_at", F.current_timestamp()) + ) +``` + +#### Option 2: Pipeline Parameters (For External Sources) + +**Use `spark.conf.get()` to parameterize external catalog/schema references.** Define parameters in pipeline configuration, then reference them at the module level. + +```python +from pyspark import pipelines as dp +from pyspark.sql import functions as F + +# Get parameterized values at module level (evaluated once at pipeline start) +source_catalog = spark.conf.get("source_catalog") +source_schema = spark.conf.get("source_schema", "sales") # with default + +@dp.table(name="transaction_summary") +def transaction_summary(): + return ( + spark.read.table(f"{source_catalog}.{source_schema}.transactions") + .groupBy("account_id") + .agg( + F.count("txn_id").alias("txn_count"), + F.sum("txn_amount").alias("account_revenue") + ) + ) +``` + +**Configure parameters in pipeline settings:** +- **Asset Bundles**: Add to `pipeline.yml` under `configuration:` +- **Manual/MCP**: Pass via `extra_settings.configuration` dict + +```yaml +# In resources/my_pipeline.pipeline.yml +configuration: + source_catalog: "shared_catalog" + source_schema: "sales" +``` + +#### Option 3: Fully-Qualified Names (For Fixed External References) + +Use when referencing specific external tables that don't change across environments: + +```python +@dp.table(name="enriched_orders") +def enriched_orders(): + # Pipeline-internal table (unqualified) + orders = spark.read.table("bronze_orders") + + # External reference table (fully-qualified) + products = spark.read.table("shared_catalog.reference.products") + + return orders.join(products, "product_id") +``` + +#### Choosing the Right Approach + +| Scenario | Recommended Approach | +|----------|---------------------| +| Reading tables created in same pipeline | **Unqualified names** - portable, uses target catalog/schema | +| Reading from external source that varies by environment | **Pipeline parameters** - configurable per deployment | +| Reading from shared/reference tables with fixed location | **Fully-qualified names** - explicit and clear | +| Mixed pipeline (some internal, some external) | **Combine approaches** - unqualified for internal, parameters for external | + +--- + +## Common Issues + +| Issue | Solution | +|-------|----------| +| **Empty output tables** | Use `get_table_details` to verify, check upstream sources | +| **Pipeline stuck INITIALIZING** | Normal for serverless, wait a few minutes | +| **"Column not found"** | Check `schemaHints` match actual data | +| **Streaming reads fail** | For file ingestion in a streaming table, you must use the `STREAM` keyword with `read_files`: `FROM STREAM read_files(...)`. For table streams use `FROM stream(table)`. See [read_files — Usage in streaming tables](https://docs.databricks.com/aws/en/sql/language-manual/functions/read_files#usage-in-streaming-tables). | +| **Timeout during run** | Increase `timeout`, or use `wait_for_completion=False` and poll with `get_update` | +| **MV doesn't refresh** | Enable row tracking on source tables | +| **SCD2: query column not found** | Lakeflow uses `__START_AT` and `__END_AT` (double underscore), not `START_AT`/`END_AT`. Use `WHERE __END_AT IS NULL` for current rows. See [3-scd-patterns.md](3-scd-patterns.md). | +| **AUTO CDC parse error at APPLY/SEQUENCE** | Put `APPLY AS DELETE WHEN` **before** `SEQUENCE BY`. Only list columns in `COLUMNS * EXCEPT (...)` that exist in the source (omit `_rescued_data` unless bronze uses rescue data). Omit `TRACK HISTORY ON *` if it causes "end of input" errors; default is equivalent. See [2-streaming-patterns.md](2-streaming-patterns.md). | +| **"Cannot create streaming table from batch query"** | In a streaming table query, use `FROM STREAM read_files(...)` so `read_files` leverages Auto Loader; `FROM read_files(...)` alone is batch. See [1-ingestion-patterns.md](1-ingestion-patterns.md) and [read_files — Usage in streaming tables](https://docs.databricks.com/aws/en/sql/language-manual/functions/read_files#usage-in-streaming-tables). | + +**For detailed errors**, the `result["message"]` from `create_or_update_pipeline` includes suggested next steps. Use `get_pipeline_events(pipeline_id=...)` for full stack traces. + +--- + +## Advanced Pipeline Configuration + +For advanced configuration options (development mode, continuous pipelines, custom clusters, notifications, Python dependencies, etc.), see **[7-advanced-configuration.md](7-advanced-configuration.md)**. + +--- + +## Platform Constraints + +### Serverless Pipeline Requirements (Default) +| Requirement | Details | +|-------------|---------| +| **Unity Catalog** | Required - serverless pipelines always use UC | +| **Workspace Region** | Must be in serverless-enabled region | +| **Serverless Terms** | Must accept serverless terms of use | +| **CDC Features** | Requires serverless (or Pro/Advanced with classic clusters) | + +### Serverless Limitations (When Classic Clusters Required) +| Limitation | Workaround | +|------------|-----------| +| **R language** | Not supported - use classic clusters if required | +| **Spark RDD APIs** | Not supported - use classic clusters if required | +| **JAR libraries** | Not supported - use classic clusters if required | +| **Maven coordinates** | Not supported - use classic clusters if required | +| **DBFS root access** | Limited - must use Unity Catalog external locations | +| **Global temp views** | Not supported | + +### General Constraints +| Constraint | Details | +|------------|---------| +| **Schema Evolution** | Streaming tables require full refresh for incompatible changes | +| **SQL Limitations** | PIVOT clause unsupported | +| **Sinks** | Python only, streaming only, append flows only | + +**Default to serverless** unless user explicitly requires R, RDD APIs, or JAR libraries. + +## Related Skills + +- **[databricks-jobs](../databricks-jobs/SKILL.md)** - for orchestrating and scheduling pipeline runs +- **[databricks-asset-bundles](../databricks-asset-bundles/SKILL.md)** - for multi-environment deployment of pipeline projects +- **[databricks-synthetic-data-generation](../databricks-synthetic-data-generation/SKILL.md)** - for generating test data to feed into pipelines +- **[databricks-unity-catalog](../databricks-unity-catalog/SKILL.md)** - for catalog/schema/volume management and governance diff --git a/.claude/skills/databricks-spark-structured-streaming/SKILL.md b/.claude/skills/databricks-spark-structured-streaming/SKILL.md new file mode 100644 index 00000000..b1f59306 --- /dev/null +++ b/.claude/skills/databricks-spark-structured-streaming/SKILL.md @@ -0,0 +1,65 @@ +--- +name: databricks-spark-structured-streaming +description: Comprehensive guide to Spark Structured Streaming for production workloads. Use when building streaming pipelines, implementing real-time data processing, handling stateful operations, or optimizing streaming performance. +--- + +# Spark Structured Streaming + +Production-ready streaming pipelines with Spark Structured Streaming. This skill provides navigation to detailed patterns and best practices. + +## Quick Start + +```python +from pyspark.sql.functions import col, from_json + +# Basic Kafka to Delta streaming +df = (spark + .readStream + .format("kafka") + .option("kafka.bootstrap.servers", "broker:9092") + .option("subscribe", "topic") + .load() + .select(from_json(col("value").cast("string"), schema).alias("data")) + .select("data.*") +) + +df.writeStream \ + .format("delta") \ + .outputMode("append") \ + .option("checkpointLocation", "/Volumes/catalog/checkpoints/stream") \ + .trigger(processingTime="30 seconds") \ + .start("/delta/target_table") +``` + +## Core Patterns + +| Pattern | Description | Reference | +|---------|-------------|-----------| +| **Kafka Streaming** | Kafka to Delta, Kafka to Kafka, Real-Time Mode | See [kafka-streaming.md](kafka-streaming.md) | +| **Stream Joins** | Stream-stream joins, stream-static joins | See [stream-stream-joins.md](stream-stream-joins.md), [stream-static-joins.md](stream-static-joins.md) | +| **Multi-Sink Writes** | Write to multiple tables, parallel merges | See [multi-sink-writes.md](multi-sink-writes.md) | +| **Merge Operations** | MERGE performance, parallel merges, optimizations | See [merge-operations.md](merge-operations.md) | + +## Configuration + +| Topic | Description | Reference | +|-------|-------------|-----------| +| **Checkpoints** | Checkpoint management and best practices | See [checkpoint-best-practices.md](checkpoint-best-practices.md) | +| **Stateful Operations** | Watermarks, state stores, RocksDB configuration | See [stateful-operations.md](stateful-operations.md) | +| **Trigger & Cost** | Trigger selection, cost optimization, RTM | See [trigger-and-cost-optimization.md](trigger-and-cost-optimization.md) | + +## Best Practices + +| Topic | Description | Reference | +|-------|-------------|-----------| +| **Production Checklist** | Comprehensive best practices | See [streaming-best-practices.md](streaming-best-practices.md) | + +## Production Checklist + +- [ ] Checkpoint location is persistent (UC volumes, not DBFS) +- [ ] Unique checkpoint per stream +- [ ] Fixed-size cluster (no autoscaling for streaming) +- [ ] Monitoring configured (input rate, lag, batch duration) +- [ ] Exactly-once verified (txnVersion/txnAppId) +- [ ] Watermark configured for stateful operations +- [ ] Left joins for stream-static (not inner) diff --git a/.claude/skills/databricks-spark-structured-streaming/checkpoint-best-practices.md b/.claude/skills/databricks-spark-structured-streaming/checkpoint-best-practices.md new file mode 100644 index 00000000..349cb9bf --- /dev/null +++ b/.claude/skills/databricks-spark-structured-streaming/checkpoint-best-practices.md @@ -0,0 +1,316 @@ +--- +name: checkpoint-best-practices +description: Configure and manage checkpoint locations for reliable Spark Structured Streaming. Use when setting up new streaming jobs, troubleshooting checkpoint issues, migrating checkpoints, or ensuring exactly-once semantics with proper checkpoint storage and organization. +--- + +# Checkpoint Best Practices + +Configure checkpoint locations for reliable streaming with exactly-once semantics. Checkpoints track progress and enable fault tolerance. + +## Quick Start + +```python +def get_checkpoint_location(table_name): + """Checkpoint tied to target table""" + return f"/Volumes/catalog/checkpoints/{table_name}" + +# Example: +# Table: prod.analytics.orders +# Checkpoint: /Volumes/prod/checkpoints/orders + +query = (df + .writeStream + .format("delta") + .option("checkpointLocation", get_checkpoint_location("orders")) + .start("/delta/orders") +) +``` + +## Checkpoint Storage + +### Use Persistent Storage + +```python +# DO: Use Unity Catalog volumes (S3/ADLS-backed) +checkpoint_path = "/Volumes/catalog/checkpoints/stream_name" + +# DON'T: Use DBFS (ephemeral, workspace-local) +checkpoint_path = "/dbfs/checkpoints/stream_name" # Avoid +``` + +### Target-Tied Organization + +```python +def get_checkpoint_location(table_name): + """Checkpoint should be tied to TARGET, not source""" + return f"/Volumes/catalog/checkpoints/{table_name}" + +# Why target-tied? +# - Checkpoint already contains source information +# - Systematic organization +# - Easy backup and restore +# - Clear ownership +``` + +### Unique Checkpoint Per Stream + +```python +# CORRECT: Each stream has its own checkpoint +stream1.writeStream \ + .option("checkpointLocation", "/checkpoints/stream1") \ + .start() + +stream2.writeStream \ + .option("checkpointLocation", "/checkpoints/stream2") \ + .start() + +# WRONG: Never share checkpoints between streams +# This causes data loss and corruption +``` + +## Checkpoint Structure + +### Folder Contents + +``` +checkpoint_location/ +├── metadata/ # Query ID +├── offsets/ # What to process (intent) +├── commits/ # What completed (confirmation) +├── sources/ # Source metadata +└── state/ # Stateful operations (if any) +``` + +### Stateless vs Stateful + +```python +# Stateless (read from Kafka, write to Delta) +# Checkpoint: metadata, offsets, commits, sources +# No state folder + +df = (spark.readStream + .format("kafka") + .option("subscribe", "topic") + .load()) + +# Stateful (with watermark and deduplication) +# Checkpoint: + state folder +df_stateful = (df + .withWatermark("timestamp", "10 minutes") + .dropDuplicates(["partition", "offset"]) +) +``` + +## Reading Checkpoint Contents + +### Read Offset Files + +```python +import json + +# Read offset file +offset_file = "/checkpoints/stream/offsets/223" +content = dbutils.fs.head(offset_file) +offset_data = json.loads(content) + +# Pretty print +print(json.dumps(offset_data, indent=2)) + +# Key fields: +# - batchWatermarkMs: Watermark timestamp +# - batchTimestampMs: When batch started +# - source[0].startOffset: Beginning of batch (inclusive) +# - source[0].endOffset: End of batch (exclusive) +# - source[0].latestOffset: Current position in source +``` + +### Read State Store + +```python +# Query state store directly +state_df = (spark + .read + .format("statestore") + .load("/checkpoints/stream/state") +) + +state_df.show() +# Shows: key, value, partitionId, expiration timestamp + +# Read state metadata +state_metadata = (spark + .read + .format("state-metadata") + .load("/checkpoints/stream") +) +state_metadata.show() +# Shows: operatorName, numPartitions, minBatchId, maxBatchId +``` + +## Recovery Scenarios + +### Lost Checkpoint + +```python +# Steps to recover: +# 1. Delete checkpoint folder +dbutils.fs.rm("/checkpoints/stream", recurse=True) + +# 2. Restart stream with startingOffsets=earliest +df.writeStream \ + .format("delta") \ + .option("checkpointLocation", "/checkpoints/stream") \ + .option("startingOffsets", "earliest") \ + .start() + +# 3. Stream reprocesses from beginning +# 4. Delta sink handles deduplication (if idempotent writes configured) +``` + +### Corrupted Checkpoint + +```python +# Same as lost checkpoint: +# 1. Delete checkpoint folder +# 2. Restart with startingOffsets=earliest +# 3. Or restore from backup if available + +# Backup checkpoint before major changes +dbutils.fs.cp( + "/checkpoints/stream", + "/checkpoints/stream_backup_20240101", + recurse=True +) +``` + +### Crash During Batch + +```python +# Scenario: Crash during batch processing +# - Latest offset = 223 (written at start) +# - Commit 223 missing (crash before finish) +# - On restart: Spark reprocesses offset 223 +# - Delta deduplication prevents duplicates (if txnVersion configured) +``` + +## Monitoring + +### Checkpoint Size + +```python +# Track checkpoint folder size +checkpoint_size = dbutils.fs.ls("/checkpoints/stream") +total_size = sum([f.size for f in checkpoint_size if f.isFile()]) +print(f"Checkpoint size: {total_size / (1024*1024):.2f} MB") + +# Alert on checkpoint access failures +try: + dbutils.fs.ls("/checkpoints/stream") +except Exception as e: + print(f"Checkpoint access failed: {e}") + # Send alert +``` + +### State Store Growth + +```python +# Monitor state store size (stateful jobs) +state_df = spark.read.format("statestore").load("/checkpoints/stream/state") + +# Check partition balance +state_df.groupBy("partitionId").count().orderBy(desc("count")).show() + +# Look for skew - one partition with 10x others = problem +# State size = f(watermark duration, key cardinality) +``` + +### Offset vs Commit Sync + +```python +# Check if offsets have matching commits +import json + +# Read latest offset +latest_offset_file = sorted(dbutils.fs.ls("/checkpoints/stream/offsets"))[-1].path +offset_data = json.loads(dbutils.fs.head(latest_offset_file)) +batch_id = latest_offset_file.split("/")[-1] + +# Check if commit exists +commit_file = f"/checkpoints/stream/commits/{batch_id}" +if dbutils.fs.exists(commit_file): + print(f"Batch {batch_id}: Committed") +else: + print(f"Batch {batch_id}: Not committed (will reprocess)") +``` + +## Common Issues + +| Issue | Cause | Solution | +|-------|-------|----------| +| **State growing too large** | Long watermark duration or high cardinality keys | Reduce watermark duration; reduce key cardinality | +| **Checkpoint corruption** | File system issues or manual deletion | Delete checkpoint and restart; restore from backup | +| **Slow state operations** | Partition imbalance | Check partition balance; ensure keys are evenly distributed | +| **Can't find commit file** | Normal if job crashed | Spark will reprocess on restart | +| **Offsets out of sync** | Offsets without matching commits | Indicates unprocessed batch; will reprocess | + +## Production Best Practices + +### Checkpoint Location Pattern + +```python +def get_checkpoint_path(table_name, environment="prod"): + """ + Checkpoint should be: + 1. Tied to TARGET table (not source) + 2. In persistent storage (UC Volume, S3, ADLS) + 3. Organized systematically + """ + return f"/Volumes/{environment}/checkpoints/{table_name}" + +# Usage +checkpoint = get_checkpoint_path("orders", "prod") +``` + +### Backup Strategy + +```python +# Backup checkpoint before major changes +def backup_checkpoint(checkpoint_path, backup_suffix): + backup_path = f"{checkpoint_path}_backup_{backup_suffix}" + dbutils.fs.cp(checkpoint_path, backup_path, recurse=True) + return backup_path + +# Before code changes or migrations +backup_checkpoint("/checkpoints/stream", "20240101") +``` + +### Migration + +```python +# Migrate checkpoint to new location +def migrate_checkpoint(old_path, new_path): + # Copy checkpoint folder + dbutils.fs.cp(old_path, new_path, recurse=True) + + # Update code to use new path + # Old checkpoint remains for rollback + + # Restart stream with new checkpoint location +``` + +## Production Checklist + +- [ ] Checkpoint location is persistent (S3/ADLS, not DBFS) +- [ ] Unique checkpoint per stream +- [ ] Target-tied checkpoint organization +- [ ] Backup strategy defined +- [ ] Monitoring configured (checkpoint size, access failures) +- [ ] State store growth monitored (if stateful) +- [ ] Recovery procedure documented +- [ ] Migration procedure documented + +## Related Skills + +- `kafka-to-delta` - Kafka ingestion with checkpoint management +- `stream-stream-joins` - Stateful operations and state stores +- `state-store-management` - Deep dive on state store optimization diff --git a/.claude/skills/databricks-spark-structured-streaming/kafka-streaming.md b/.claude/skills/databricks-spark-structured-streaming/kafka-streaming.md new file mode 100644 index 00000000..83630e8a --- /dev/null +++ b/.claude/skills/databricks-spark-structured-streaming/kafka-streaming.md @@ -0,0 +1,417 @@ +--- +name: kafka-streaming +description: Comprehensive Kafka streaming patterns including Kafka-to-Delta ingestion, Kafka-to-Kafka pipelines, and Real-Time Mode for sub-second latency. Use when building Kafka ingestion pipelines, implementing event enrichment, format transformation, or low-latency streaming workloads. +--- + +# Kafka Streaming Patterns + +Comprehensive guide to Kafka streaming with Spark Structured Streaming: ingestion to Delta, Kafka-to-Kafka pipelines, and Real-Time Mode for sub-second latency. + +## Quick Start + +### Kafka to Delta + +```python +from pyspark.sql.functions import col, from_json + +# Read from Kafka +df = (spark + .readStream + .format("kafka") + .option("kafka.bootstrap.servers", "broker1:9092,broker2:9092") + .option("subscribe", "topic_name") + .option("startingOffsets", "earliest") + .option("minPartitions", "6") # Match Kafka partitions + .load() +) + +# Parse JSON value +df_parsed = df.select( + col("key").cast("string"), + from_json(col("value").cast("string"), event_schema).alias("data"), + col("topic"), col("partition"), col("offset"), + col("timestamp").alias("kafka_timestamp") +).select("key", "data.*", "topic", "partition", "offset", "kafka_timestamp") + +# Write to Delta +df_parsed.writeStream \ + .format("delta") \ + .outputMode("append") \ + .option("checkpointLocation", "/Volumes/catalog/checkpoints/kafka_stream") \ + .trigger(processingTime="30 seconds") \ + .start("/delta/bronze_events") +``` + +### Kafka to Kafka + +```python +from pyspark.sql.functions import col, from_json, to_json, struct, current_timestamp + +# Read from source Kafka +source_df = (spark + .readStream + .format("kafka") + .option("kafka.bootstrap.servers", "broker1:9092") + .option("subscribe", "input-events") + .option("startingOffsets", "latest") + .load() +) + +# Parse and transform +parsed_df = source_df.select( + col("key").cast("string"), + from_json(col("value").cast("string"), event_schema).alias("data"), + col("topic").alias("source_topic") +).select("key", "data.*", "source_topic") + +# Transform events +enriched_df = parsed_df.withColumn( + "processed_at", current_timestamp() +).withColumn( + "value", to_json(struct("event_id", "user_id", "event_type", "processed_at")) +) + +# Write to output Kafka topic +enriched_df.select("key", "value").writeStream \ + .format("kafka") \ + .option("kafka.bootstrap.servers", "broker1:9092") \ + .option("topic", "output-events") \ + .option("checkpointLocation", "/checkpoints/kafka-to-kafka") \ + .trigger(processingTime="30 seconds") \ + .start() +``` + +## Common Patterns + +### Pattern 1: Bronze Layer Ingestion (Kafka to Delta) + +Minimal transformation, preserve original columns: + +```python +# Best practice: Minimal transformation, preserve original columns +# Why: Kafka retention is expensive (default 7 days) +# Delta provides permanent storage with full history + +df_bronze = (spark + .readStream + .format("kafka") + .option("kafka.bootstrap.servers", servers) + .option("subscribe", topic) + .option("startingOffsets", "earliest") + .option("maxOffsetsPerTrigger", 10000) # Control batch size + .load() + .select( + col("key").cast("string"), + col("value").cast("string"), + col("topic"), col("partition"), col("offset"), + col("timestamp").alias("kafka_timestamp"), + current_timestamp().alias("ingestion_timestamp") + ) +) + +df_bronze.writeStream \ + .format("delta") \ + .outputMode("append") \ + .option("checkpointLocation", "/Volumes/catalog/checkpoints/bronze_events") \ + .trigger(processingTime="30 seconds") \ + .start("/delta/bronze_events") +``` + +### Pattern 2: Scheduled Streaming (Cost-Optimized) + +Run periodically instead of continuously: + +```python +# Run every 4 hours, not continuously +# Same code, just change trigger in job scheduler + +df_bronze.writeStream \ + .format("delta") \ + .outputMode("append") \ + .option("checkpointLocation", "/Volumes/catalog/checkpoints/bronze_events") \ + .trigger(availableNow=True) \ # Process all available, then stop + .start("/delta/bronze_events") + +# In Databricks Jobs: +# - Schedule: Every 4 hours +# - Cluster: Fixed size (no autoscaling for streaming) +# - Same streaming code, batch-style execution +``` + +### Pattern 3: Real-Time Mode (Sub-Second Latency) + +Use RTM for < 800ms latency requirements: + +```python +# Real-time trigger (Databricks 13.3+) +query = (enriched_df + .select(col("key"), col("value")) + .writeStream + .format("kafka") + .option("kafka.bootstrap.servers", brokers) + .option("topic", "output-events") + .trigger(realTime=True) # Enable RTM + .option("checkpointLocation", checkpoint_path) + .start() +) + +# RTM Cluster Requirements +spark.conf.set("spark.databricks.photon.enabled", "true") +spark.conf.set("spark.sql.streaming.stateStore.providerClass", + "com.databricks.sql.streaming.state.RocksDBStateProvider") + +# When to use RTM: +# - Latency < 800ms required +# - Photon enabled +# - Fixed-size cluster (no autoscaling) +``` + +### Pattern 4: Event Enrichment (Kafka to Kafka with Delta) + +Enrich events with dimension data: + +```python +# Read reference data (Delta table - auto-refreshed each microbatch) +user_dim = spark.table("users.dimension") + +# Stream-static join for enrichment +enriched = (parsed_df + .join(user_dim, "user_id", "left") + .withColumn("enriched_value", to_json(struct( + col("event_id"), + col("user_id"), + col("user_name"), # From dimension table + col("user_segment"), # From dimension table + col("event_type"), + col("timestamp") + ))) +) + +# Write enriched events to Kafka +enriched.select(col("key"), col("enriched_value").alias("value")).writeStream \ + .format("kafka") \ + .option("kafka.bootstrap.servers", brokers) \ + .option("topic", "enriched-events") \ + .trigger(realTime=True) \ + .option("checkpointLocation", "/checkpoints/enrichment") \ + .start() +``` + +### Pattern 5: Multi-Topic Routing + +Route events to different Kafka topics: + +```python +def route_events(batch_df, batch_id): + """Route events to different Kafka topics""" + + # High priority → urgent topic + high_priority = batch_df.filter(col("priority") == "high") + if high_priority.count() > 0: + high_priority.select("key", "value").write \ + .format("kafka") \ + .option("kafka.bootstrap.servers", brokers) \ + .option("topic", "urgent-events") \ + .save() + + # Errors → DLQ topic + errors = batch_df.filter(col("event_type") == "error") + if errors.count() > 0: + errors.select("key", "value").write \ + .format("kafka") \ + .option("kafka.bootstrap.servers", brokers) \ + .option("topic", "error-events-dlq") \ + .save() + + # All events → standard topic + batch_df.select("key", "value").write \ + .format("kafka") \ + .option("kafka.bootstrap.servers", brokers) \ + .option("topic", "standard-events") \ + .save() + +parsed_df.writeStream \ + .foreachBatch(route_events) \ + .trigger(realTime=True) \ + .option("checkpointLocation", "/checkpoints/routing") \ + .start() +``` + +### Pattern 6: Schema Validation with DLQ + +Validate schema and route invalid records: + +```python +from pyspark.sql.functions import from_json, col, lit, to_json, struct, current_timestamp + +def validate_and_route(batch_df, batch_id): + """Validate schema, route bad records to DLQ""" + + # Try to parse with strict schema + parsed = batch_df.withColumn( + "parsed", + from_json(col("value").cast("string"), validated_schema) + ) + + # Valid records + valid = parsed.filter(col("parsed").isNotNull()).select("key", "value") + + # Invalid records → DLQ + invalid = parsed.filter(col("parsed").isNull()).select( + col("key"), + to_json(struct( + col("value"), + lit("SCHEMA_VALIDATION_FAILED").alias("dlq_reason"), + current_timestamp().alias("dlq_timestamp") + )).alias("value") + ) + + # Write valid to main topic + if valid.count() > 0: + valid.write.format("kafka") \ + .option("kafka.bootstrap.servers", brokers) \ + .option("topic", "valid-events") \ + .save() + + # Write invalid to DLQ + if invalid.count() > 0: + invalid.write.format("kafka") \ + .option("kafka.bootstrap.servers", brokers) \ + .option("topic", "dlq-events") \ + .save() + +source_df.writeStream \ + .foreachBatch(validate_and_route) \ + .trigger(realTime=True) \ + .option("checkpointLocation", "/checkpoints/validation") \ + .start() +``` + +## Configuration + +### Consumer Options (Reading from Kafka) + +```python +(spark + .readStream + .format("kafka") + .option("kafka.bootstrap.servers", "host1:9092,host2:9092") + .option("subscribe", "source-topic") + .option("startingOffsets", "latest") # latest, earliest, or specific JSON + .option("maxOffsetsPerTrigger", "10000") # Control batch size + .option("minPartitions", "6") # Match Kafka partitions + .option("kafka.auto.offset.reset", "latest") + .option("kafka.enable.auto.commit", "false") # Spark manages offsets + .load() +) +``` + +### Producer Options (Writing to Kafka) + +```python +(df + .select("key", "value") + .writeStream + .format("kafka") + .option("kafka.bootstrap.servers", "host1:9092,host2:9092") + .option("topic", "target-topic") + .option("kafka.acks", "all") # Durability: all, 1, 0 + .option("kafka.retries", "3") + .option("kafka.batch.size", "16384") + .option("kafka.linger.ms", "5") + .option("kafka.compression.type", "lz4") # lz4, snappy, gzip + .option("checkpointLocation", checkpoint_path) + .start() +) +``` + +### Security (SASL/SSL) + +```python +# Using Databricks secrets +kafka_username = dbutils.secrets.get("kafka-scope", "username") +kafka_password = dbutils.secrets.get("kafka-scope", "password") + +# SASL/PLAIN Authentication +df.writeStream \ + .format("kafka") \ + .option("kafka.bootstrap.servers", brokers) \ + .option("topic", target_topic) \ + .option("kafka.security.protocol", "SASL_SSL") \ + .option("kafka.sasl.mechanism", "PLAIN") \ + .option("kafka.sasl.jaas.config", + f'org.apache.kafka.common.security.plain.PlainLoginModule required username="{kafka_username}" password="{kafka_password}";') \ + .option("checkpointLocation", checkpoint_path) \ + .start() +``` + +## Performance Tuning + +| Parameter | Recommendation | Why | +|-----------|---------------|-----| +| minPartitions | Match Kafka partitions | Optimal parallelism | +| maxOffsetsPerTrigger | 10,000-100,000 | Balance latency vs throughput | +| trigger interval | Business SLA / 3 | Recovery time buffer | +| RTM | Only if < 800ms required | Microbatch more cost-effective | + +## Monitoring + +### Key Metrics + +```python +# Programmatic monitoring +for stream in spark.streams.active: + progress = stream.lastProgress + if progress: + print(f"Input rate: {progress.get('inputRowsPerSecond', 0)} rows/sec") + print(f"Processing rate: {progress.get('processedRowsPerSecond', 0)} rows/sec") + + # Kafka-specific metrics + sources = progress.get("sources", []) + for source in sources: + end_offset = source.get("endOffset", {}) + latest_offset = source.get("latestOffset", {}) + + # Calculate lag per partition + for topic, partitions in end_offset.items(): + for partition, end in partitions.items(): + latest = latest_offset.get(topic, {}).get(partition, end) + lag = int(latest) - int(end) + print(f"Topic {topic}, Partition {partition}: Lag = {lag}") +``` + +### Spark UI Checks + +- **Input Rate vs Processing Rate**: Processing must be > Input +- **Max Offsets Behind Latest**: Should be consistent or dropping +- **Batch Duration**: Should be < trigger interval + +## Common Issues + +| Issue | Cause | Solution | +|-------|-------|----------| +| **No data being read** | `startingOffsets` default is "latest" | Use "earliest" for existing data | +| **High latency** | Microbatch overhead | Use RTM (trigger(realTime=True)) | +| **Consumer lag** | Processing < Input rate | Scale cluster; reduce maxOffsetsPerTrigger | +| **Duplicate messages** | Exactly-once not configured | Enable idempotent producer (acks=all) | +| **Falling behind** | Processing < Input rate | Increase cluster size | +| **Can't use autoscaling** | Streaming requirement | Use fixed-size clusters | + +## Production Checklist + +- [ ] Checkpoint location is persistent (UC volumes, not DBFS) +- [ ] Unique checkpoint per pipeline +- [ ] Fixed-size cluster (no autoscaling for streaming/RTM) +- [ ] RTM enabled only if latency < 800ms required +- [ ] Consumer lag monitored and alerts configured +- [ ] Producer acks=all for durability +- [ ] Schema validation with DLQ configured +- [ ] Security (SASL/SSL) configured for production +- [ ] Exactly-once semantics verified + +## Related Skills + +- `stream-static-joins` - Enrichment patterns with Delta tables +- `stream-stream-joins` - Event correlation across Kafka topics +- `checkpoint-best-practices` - Checkpoint configuration +- `trigger-tuning` - Trigger configuration and RTM setup diff --git a/.claude/skills/databricks-spark-structured-streaming/merge-operations.md b/.claude/skills/databricks-spark-structured-streaming/merge-operations.md new file mode 100644 index 00000000..374239ad --- /dev/null +++ b/.claude/skills/databricks-spark-structured-streaming/merge-operations.md @@ -0,0 +1,358 @@ +--- +name: merge-operations +description: Comprehensive guide to Delta MERGE operations in streaming including performance optimization, parallel merges, and Liquid Clustering configuration. Use when implementing upserts, optimizing merge performance, performing parallel merges to multiple tables, or eliminating optimize pauses. +--- + +# Merge Operations in Streaming + +Comprehensive guide to Delta MERGE operations: performance optimization, parallel merges to multiple tables, and modern Delta features (Liquid Clustering + Deletion Vectors + Row-Level Concurrency). + +## Quick Start + +### Basic MERGE with Optimization + +```python +from delta.tables import DeltaTable + +# Enable modern Delta features +spark.sql(""" + ALTER TABLE target_table SET TBLPROPERTIES ( + 'delta.enableDeletionVectors' = true, + 'delta.enableRowLevelConcurrency' = true, + 'delta.liquid.clustering' = true + ) +""") + +# MERGE in ForEachBatch +def upsert_batch(batch_df, batch_id): + batch_df.createOrReplaceTempView("updates") + spark.sql(""" + MERGE INTO target_table t + USING updates s ON t.id = s.id + WHEN MATCHED THEN UPDATE SET * + WHEN NOT MATCHED THEN INSERT * + """) + # No optimize needed - Liquid Clustering handles it automatically + +stream.writeStream \ + .foreachBatch(upsert_batch) \ + .option("checkpointLocation", "/checkpoints/merge") \ + .start() +``` + +### Parallel MERGE to Multiple Tables + +```python +from delta.tables import DeltaTable +from concurrent.futures import ThreadPoolExecutor, as_completed + +def parallel_merge_multiple_tables(batch_df, batch_id): + """Merge into multiple tables in parallel""" + + batch_df.cache() + + def merge_table(table_name, merge_key): + target = DeltaTable.forName(spark, table_name) + source = batch_df.alias("source") + + (target.alias("target") + .merge(source, f"target.{merge_key} = source.{merge_key}") + .whenMatchedUpdateAll() + .whenNotMatchedInsertAll() + .execute() + ) + return f"Merged {table_name}" + + tables = [ + ("silver.customers", "customer_id"), + ("silver.orders", "order_id"), + ("silver.products", "product_id") + ] + + # Parallel merges + with ThreadPoolExecutor(max_workers=3) as executor: + futures = { + executor.submit(merge_table, table_name, merge_key): table_name + for table_name, merge_key in tables + } + + for future in as_completed(futures): + future.result() # Raise on error + + batch_df.unpersist() + +stream.writeStream \ + .foreachBatch(parallel_merge_multiple_tables) \ + .option("checkpointLocation", "/checkpoints/parallel_merge") \ + .start() +``` + +## Core Concepts + +### Liquid Clustering + DV + RLC + +Enable modern Delta features for optimal merge performance: + +```sql +-- Enable for target table +ALTER TABLE target_table SET TBLPROPERTIES ( + 'delta.enableDeletionVectors' = true, + 'delta.enableRowLevelConcurrency' = true, + 'delta.liquid.clustering' = true +); +``` + +**Benefits:** +- **Deletion Vectors**: Soft deletes without file rewrite +- **Row-Level Concurrency**: Concurrent updates to different rows +- **Liquid Clustering**: Automatic optimization without pauses +- **Result**: Eliminates optimize pauses, lower P99 latency, simpler code + +## Common Patterns + +### Pattern 1: Basic MERGE with Optimization + +```python +def optimized_merge(batch_df, batch_id): + """MERGE with optimized table""" + batch_df.createOrReplaceTempView("updates") + + spark.sql(""" + MERGE INTO target_table t + USING updates s ON t.id = s.id + WHEN MATCHED THEN UPDATE SET * + WHEN NOT MATCHED THEN INSERT * + """) + # No optimize needed - Liquid Clustering handles it + +stream.writeStream \ + .foreachBatch(optimized_merge) \ + .option("checkpointLocation", "/checkpoints/merge") \ + .start() +``` + +### Pattern 2: Parallel MERGE to Multiple Tables + +```python +from concurrent.futures import ThreadPoolExecutor, as_completed + +def parallel_merge(batch_df, batch_id): + """Merge into multiple tables in parallel""" + + batch_df.cache() + + def merge_one_table(table_name, merge_key): + target = DeltaTable.forName(spark, table_name) + source = batch_df.alias("source") + + (target.alias("target") + .merge(source, f"target.{merge_key} = source.{merge_key}") + .whenMatchedUpdateAll() + .whenNotMatchedInsertAll() + .execute() + ) + return table_name + + tables = [ + ("silver.customers", "customer_id"), + ("silver.orders", "order_id"), + ("silver.products", "product_id") + ] + + # Optimal thread count: min(number_of_tables, cluster_cores / 2) + max_workers = min(len(tables), max(2, total_cores // 2)) + + with ThreadPoolExecutor(max_workers=max_workers) as executor: + futures = { + executor.submit(merge_one_table, table_name, merge_key): table_name + for table_name, merge_key in tables + } + + errors = [] + for future in as_completed(futures): + table_name = futures[future] + try: + future.result() + except Exception as e: + errors.append((table_name, str(e))) + + batch_df.unpersist() + + if errors: + raise Exception(f"Merge failures: {errors}") +``` + +### Pattern 3: MERGE with Partition Pruning + +```python +def partition_pruned_merge(batch_df, batch_id): + """MERGE with partition column in condition""" + batch_df.createOrReplaceTempView("updates") + + # Include partition column in merge condition + spark.sql(""" + MERGE INTO target_table t + USING updates s + ON t.id = s.id AND t.date = s.date -- partition column + WHEN MATCHED THEN UPDATE SET * + WHEN NOT MATCHED THEN INSERT * + """) + # Skips irrelevant partitions for faster execution +``` + +### Pattern 4: CDC Multi-Target with Parallel MERGE + +```python +def cdc_parallel_merge(batch_df, batch_id): + """Apply CDC changes to multiple tables in parallel""" + + batch_df.cache() + + # Split by operation type + deletes = batch_df.filter(col("_op") == "DELETE") + upserts = batch_df.filter(col("_op").isin(["INSERT", "UPDATE"])) + + def merge_cdc_table(table_name, merge_key): + target = DeltaTable.forName(spark, table_name) + + # Upserts + if upserts.count() > 0: + (target.alias("target") + .merge(upserts.alias("source"), f"target.{merge_key} = source.{merge_key}") + .whenMatchedUpdateAll() + .whenNotMatchedInsertAll() + .execute() + ) + + # Deletes + if deletes.count() > 0: + (target.alias("target") + .merge(deletes.alias("source"), f"target.{merge_key} = source.{merge_key}") + .whenMatchedDelete() + .execute() + ) + + tables = [ + ("silver.customers", "customer_id"), + ("silver.orders", "order_id") + ] + + with ThreadPoolExecutor(max_workers=2) as executor: + futures = { + executor.submit(merge_cdc_table, table_name, merge_key): table_name + for table_name, merge_key in tables + } + + for future in as_completed(futures): + future.result() + + batch_df.unpersist() +``` + +## Performance Optimization + +### Enable Liquid Clustering + DV + RLC + +```sql +-- Create table with Liquid Clustering +CREATE TABLE target_table ( + id STRING, + name STRING, + updated_at TIMESTAMP +) USING DELTA +CLUSTER BY (id) +TBLPROPERTIES ( + 'delta.enableDeletionVectors' = true, + 'delta.enableRowLevelConcurrency' = true +); + +-- Or alter existing table +ALTER TABLE target_table SET TBLPROPERTIES ( + 'delta.enableDeletionVectors' = true, + 'delta.enableRowLevelConcurrency' = true, + 'delta.liquid.clustering' = true +); +ALTER TABLE target_table CLUSTER BY (id); +``` + +### Z-Ordering on Merge Key + +```sql +-- Z-Order on merge key for faster lookups +OPTIMIZE target_table ZORDER BY (id); + +-- Run periodically or via Predictive Optimization +-- 5-10x faster for targeted lookups +``` + +### File Size Tuning + +```sql +-- Target file size for optimal merge +ALTER TABLE target_table SET TBLPROPERTIES ( + 'delta.targetFileSize' = '128mb' +); +``` + +### Optimal Thread Count + +```python +# Formula: min(number_of_tables, cluster_cores / 2) +# Example: 4 tables, 8 cores → 4 workers +# Example: 2 tables, 4 cores → 2 workers + +max_workers = min(len(tables), max(2, total_cores // 2)) +``` + +## Monitoring + +### Track Merge Performance + +```python +import time + +def monitored_merge(batch_df, batch_id): + start_time = time.time() + + batch_df.createOrReplaceTempView("updates") + spark.sql(""" + MERGE INTO target_table t + USING updates s ON t.id = s.id + WHEN MATCHED THEN UPDATE SET * + WHEN NOT MATCHED THEN INSERT * + """) + + duration = time.time() - start_time + print(f"Merge duration: {duration:.2f}s") + + # Alert if duration exceeds threshold + if duration > 30: + print(f"WARNING: Merge duration {duration:.2f}s exceeds threshold") +``` + +## Common Issues + +| Issue | Cause | Solution | +|-------|-------|----------| +| **High P99 latency** | OPTIMIZE pauses | Enable Liquid Clustering (no pauses) | +| **Merge conflicts** | Concurrent updates to same rows | Enable Row-Level Concurrency | +| **Slow merges** | Large files, no optimization | Enable Liquid Clustering; Z-Order on merge key | +| **Too many threads** | Resource contention | Reduce max_workers; match to cluster capacity | +| **Partial failures** | One merge fails | Collect all errors; fail batch if any error | + +## Production Checklist + +- [ ] Liquid Clustering + DV + RLC enabled on all target tables +- [ ] Z-Ordering configured on merge keys +- [ ] Optimal thread count configured (start with 2) +- [ ] Error handling implemented (collect all errors) +- [ ] Performance monitoring per table +- [ ] Cache used to avoid recomputation +- [ ] Unpersist after writes +- [ ] File size tuned (128MB target) + +## Related Skills + +- `multi-sink-writes` - Multi-sink write patterns +- `partitioning-strategy` - Partition optimization for merges +- `checkpoint-best-practices` - Checkpoint configuration diff --git a/.claude/skills/databricks-spark-structured-streaming/multi-sink-writes.md b/.claude/skills/databricks-spark-structured-streaming/multi-sink-writes.md new file mode 100644 index 00000000..6611ab0d --- /dev/null +++ b/.claude/skills/databricks-spark-structured-streaming/multi-sink-writes.md @@ -0,0 +1,427 @@ +--- +name: multi-sink-writes +description: Write a single Spark stream to multiple Delta tables or Kafka topics using ForEachBatch. Use when fanning out streaming data to multiple sinks, implementing medallion architecture (bronze/silver/gold), conditional routing, CDC patterns, or creating materialized views from a single stream. +--- + +# Multi-Sink Writes + +Write a single streaming source to multiple Delta tables or Kafka topics efficiently using ForEachBatch. Read once, write many - avoiding reprocessing the source multiple times. + +## Quick Start + +```python +from pyspark.sql.functions import col, current_timestamp + +def write_multiple_tables(batch_df, batch_id): + """Write batch to multiple sinks""" + # Bronze - raw data + batch_df.write \ + .format("delta") \ + .mode("append") \ + .option("txnVersion", batch_id) \ + .option("txnAppId", "multi_sink_job") \ + .save("/delta/bronze_events") + + # Silver - cleansed + cleansed = batch_df.dropDuplicates(["event_id"]) + cleansed.write \ + .format("delta") \ + .mode("append") \ + .option("txnVersion", batch_id) \ + .option("txnAppId", "multi_sink_job_silver") \ + .save("/delta/silver_events") + + # Gold - aggregated + aggregated = batch_df.groupBy("category").count() + aggregated.write \ + .format("delta") \ + .mode("append") \ + .option("txnVersion", batch_id) \ + .option("txnAppId", "multi_sink_job_gold") \ + .save("/delta/category_counts") + +stream.writeStream \ + .foreachBatch(write_multiple_tables) \ + .option("checkpointLocation", "/checkpoints/multi_sink") \ + .start() +``` + +## Core Concepts + +### One Source, One Checkpoint + +Use a single checkpoint for the entire multi-sink stream: + +```python +# CORRECT: One checkpoint for all sinks +stream.writeStream \ + .foreachBatch(multi_sink_function) \ + .option("checkpointLocation", "/checkpoints/single_source_multi_sink") \ + .start() + +# WRONG: Don't create separate streams +# Each stream would reprocess the source independently +``` + +### Transactional Guarantees + +Each ForEachBatch call represents one epoch. All writes within the batch: +- See the same input data +- Share the same batch_id +- Are idempotent if using txnVersion + +## Common Patterns + +### Pattern 1: Bronze-Silver-Gold Medallion Architecture + +Single stream feeding all three medallion layers: + +```python +from pyspark.sql.functions import window, count, sum, current_timestamp + +def medallion_architecture(batch_df, batch_id): + """Single stream feeding all three medallion layers""" + + # Bronze: Raw ingestion + (batch_df.write + .format("delta") + .mode("append") + .option("txnVersion", batch_id) + .option("txnAppId", "medallion_bronze") + .saveAsTable("bronze.events") + ) + + # Silver: Cleansed and validated + silver_df = (batch_df + .dropDuplicates(["event_id"]) + .filter(col("status").isin(["active", "pending"])) + .withColumn("processed_at", current_timestamp()) + ) + + (silver_df.write + .format("delta") + .mode("append") + .option("txnVersion", batch_id) + .option("txnAppId", "medallion_silver") + .saveAsTable("silver.events") + ) + + # Gold: Business aggregates + gold_df = (silver_df + .groupBy(window(col("timestamp"), "5 minutes"), "category") + .agg( + count("*").alias("event_count"), + sum("amount").alias("total_amount") + ) + ) + + (gold_df.write + .format("delta") + .mode("append") + .option("txnVersion", batch_id) + .option("txnAppId", "medallion_gold") + .saveAsTable("gold.category_metrics") + ) + +stream.writeStream \ + .foreachBatch(medallion_architecture) \ + .trigger(processingTime="30 seconds") \ + .option("checkpointLocation", "/checkpoints/medallion") \ + .start() +``` + +### Pattern 2: Conditional Routing + +Route events to different tables based on criteria: + +```python +def route_by_type(batch_df, batch_id): + """Route events to different tables based on type""" + + # Split by event type + orders = batch_df.filter(col("event_type") == "order") + refunds = batch_df.filter(col("event_type") == "refund") + reviews = batch_df.filter(col("event_type") == "review") + + # Write to respective tables + if orders.count() > 0: + (orders.write + .format("delta") + .mode("append") + .option("txnVersion", batch_id) + .option("txnAppId", "router_orders") + .saveAsTable("orders") + ) + + if refunds.count() > 0: + (refunds.write + .format("delta") + .mode("append") + .option("txnVersion", batch_id) + .option("txnAppId", "router_refunds") + .saveAsTable("refunds") + ) + + if reviews.count() > 0: + (reviews.write + .format("delta") + .mode("append") + .option("txnVersion", batch_id) + .option("txnAppId", "router_reviews") + .saveAsTable("reviews") + ) +``` + +### Pattern 3: Parallel Fan-Out + +Write to multiple sinks in parallel for independent tables: + +```python +from concurrent.futures import ThreadPoolExecutor, as_completed + +def parallel_write(batch_df, batch_id): + """Write to multiple sinks in parallel""" + + # Cache to avoid recomputation + batch_df.cache() + + def write_table(table_name, filter_expr=None): + """Write filtered data to table""" + df = batch_df.filter(filter_expr) if filter_expr else batch_df + (df.write + .format("delta") + .mode("append") + .option("txnVersion", batch_id) + .option("txnAppId", f"parallel_{table_name}") + .saveAsTable(table_name) + ) + return f"Wrote {table_name}" + + # Define tables and filters + tables = [ + ("bronze.all_events", None), + ("silver.errors", col("level") == "ERROR"), + ("silver.warnings", col("level") == "WARN"), + ("gold.metrics", col("type") == "metric") + ] + + # Parallel writes + with ThreadPoolExecutor(max_workers=4) as executor: + futures = { + executor.submit(write_table, table_name, filter_expr): table_name + for table_name, filter_expr in tables + } + + errors = [] + for future in as_completed(futures): + table_name = futures[future] + try: + future.result() + except Exception as e: + errors.append((table_name, str(e))) + + batch_df.unpersist() + + if errors: + raise Exception(f"Write failures: {errors}") +``` + +### Pattern 4: Materialized Views + +Create multiple derived views from the same stream: + +```python +from pyspark.sql.functions import window, count, sum + +def create_materialized_views(batch_df, batch_id): + """Create multiple derived views from the same stream""" + + # Base: All events + (batch_df.write + .format("delta") + .mode("append") + .option("txnVersion", batch_id) + .option("txnAppId", "views_raw") + .save("/delta/views/raw") + ) + + # View 1: Hourly aggregations + hourly = (batch_df + .withWatermark("event_time", "1 hour") + .groupBy(window(col("event_time"), "1 hour"), col("category")) + .agg( + count("*").alias("event_count"), + sum("value").alias("total_value") + ) + ) + + (hourly.write + .format("delta") + .mode("append") + .option("txnVersion", batch_id) + .option("txnAppId", "views_hourly") + .save("/delta/views/hourly") + ) + + # View 2: User sessions (15 min window) + sessions = (batch_df + .withWatermark("event_time", "15 minutes") + .groupBy(window(col("event_time"), "15 minutes"), col("user_id")) + .agg(count("*").alias("actions")) + ) + + (sessions.write + .format("delta") + .mode("append") + .option("txnVersion", batch_id) + .option("txnAppId", "views_sessions") + .save("/delta/views/sessions") + ) +``` + +### Pattern 5: Error Handling with Dead Letter Queue + +Route invalid records to DLQ: + +```python +from pyspark.sql.functions import when, lit + +def write_with_dlq(batch_df, batch_id): + """Write valid records to target, invalid to dead letter queue""" + + # Validation + valid = batch_df.filter( + col("required_field").isNotNull() & + col("timestamp").isNotNull() + ) + invalid = batch_df.filter( + col("required_field").isNull() | + col("timestamp").isNull() + ) + + # Write valid data + if valid.count() > 0: + (valid.write + .format("delta") + .mode("append") + .option("txnVersion", batch_id) + .option("txnAppId", "multi_sink_valid") + .saveAsTable("silver.valid_events") + ) + + # Write invalid to DLQ with metadata + if invalid.count() > 0: + dlq_df = (invalid + .withColumn("_error_reason", + when(col("required_field").isNull(), "missing_required_field") + .otherwise("missing_timestamp")) + .withColumn("_batch_id", lit(batch_id)) + .withColumn("_processed_at", current_timestamp()) + ) + + (dlq_df.write + .format("delta") + .mode("append") + .saveAsTable("errors.dead_letter_queue") + ) +``` + +## Performance Optimization + +### Minimize Recomputation + +Cache the batch DataFrame to avoid recomputation: + +```python +def optimized_multi_sink(batch_df, batch_id): + """Cache to avoid recomputation""" + + # Cache the batch + batch_df.cache() + + # Multiple writes from cached data + batch_df.write... # Sink 1 + batch_df.filter(...).write... # Sink 2 + batch_df.filter(...).write... # Sink 3 + + # Unpersist when done + batch_df.unpersist() +``` + +### Parallel Writes + +Use ThreadPoolExecutor for independent writes: + +```python +from concurrent.futures import ThreadPoolExecutor + +def parallel_write(batch_df, batch_id): + """Write to independent tables in parallel""" + + batch_df.cache() + + def write_table(table_name, df): + df.write.format("delta").mode("append").saveAsTable(table_name) + + # Parallel writes + with ThreadPoolExecutor(max_workers=4) as executor: + executor.submit(write_table, "table1", batch_df) + executor.submit(write_table, "table2", batch_df.filter(...)) + executor.submit(write_table, "table3", batch_df.filter(...)) + + batch_df.unpersist() +``` + +## Common Issues + +| Issue | Cause | Solution | +|-------|-------|----------| +| **Slow writes** | Sequential processing | Use parallel ThreadPoolExecutor | +| **Recomputation** | Multiple actions on same DataFrame | Cache the batch DataFrame | +| **Partial failures** | One sink fails | Use idempotent writes; Spark retries entire batch | +| **Schema conflicts** | Tables have different schemas | Transform before each write | +| **Resource contention** | Too many concurrent writes | Limit parallelism; batch writes | + +## Production Best Practices + +### Idempotent Writes + +Always use txnVersion with batch_id: + +```python +.write + .format("delta") + .option("txnVersion", batch_id) + .option("txnAppId", "unique_app_id_per_table") + .mode("append") +``` + +### Keep Batch Processing Fast + +```python +# GOOD: Simple filters and writes +def efficient_write(df, batch_id): + df.filter(...).write.save("/delta/table1") + df.filter(...).write.save("/delta/table2") + +# BAD: Expensive aggregations (move to stream definition) +def inefficient_write(df, batch_id): + df.groupBy(...).agg(...).write.save("/delta/table3") # Move to stream! +``` + +## Production Checklist + +- [ ] One checkpoint per multi-sink stream +- [ ] Idempotent writes configured (txnVersion/txnAppId) +- [ ] Cache used to avoid recomputation +- [ ] Parallel writes for independent tables +- [ ] Error handling and DLQ configured +- [ ] Schema evolution handled +- [ ] Performance monitoring per sink + +## Related Skills + +- `merge-operations` - Parallel MERGE operations +- `kafka-streaming` - Kafka ingestion patterns +- `stream-static-joins` - Enrichment before multi-sink writes +- `checkpoint-best-practices` - Checkpoint configuration diff --git a/.claude/skills/databricks-spark-structured-streaming/stateful-operations.md b/.claude/skills/databricks-spark-structured-streaming/stateful-operations.md new file mode 100644 index 00000000..625f53eb --- /dev/null +++ b/.claude/skills/databricks-spark-structured-streaming/stateful-operations.md @@ -0,0 +1,397 @@ +--- +name: stateful-operations +description: Configure watermarks and manage state stores for Spark Structured Streaming stateful operations. Use when setting up stateful operations, tuning watermark duration, handling late-arriving data, configuring RocksDB for large state, monitoring state store size, or optimizing state performance. +--- + +# Stateful Operations: Watermarks and State Stores + +Configure watermarks to handle late-arriving data and manage state stores for stateful streaming operations. Watermarks control state cleanup, while state stores handle the storage and retrieval of stateful data. + +## Quick Start + +```python +# Enable RocksDB for large state stores +spark.conf.set( + "spark.sql.streaming.stateStore.providerClass", + "com.databricks.sql.streaming.state.RocksDBStateProvider" +) + +# Stateful operation with watermark +df = (spark.readStream + .format("kafka") + .option("subscribe", "events") + .load() + .select(from_json(col("value").cast("string"), schema).alias("data")) + .select("data.*") + .withWatermark("event_time", "10 minutes") # Late data threshold + state cleanup + .dropDuplicates(["event_id"]) # Stateful operation +) + +# Watermark = latest_event_time - 10 minutes +# State automatically expires after watermark duration +``` + +## Watermark Configuration + +### How Watermarks Work + +```python +# Watermark = latest_event_time - delay_threshold +.withWatermark("event_time", "10 minutes") + +# Events with timestamp < watermark are considered "too late" +# State for late events is automatically cleaned up +# Late events may be dropped (outer joins) or processed (inner joins) +``` + +### Watermark Duration Selection + +| Watermark Setting | Effect | Use Case | +|-------------------|--------|----------| +| `"10 minutes"` | Moderate latency | General streaming | +| `"1 hour"` | High completeness | Financial transactions | +| `"5 minutes"` | Low latency | Real-time analytics | +| `"24 hours"` | Batch-like | Backfill scenarios | + +**Rule of thumb**: Start with 2-3× your p95 latency. Monitor late data rate and adjust. + +### Watermark and State Size + +```python +# Watermark directly affects state store size +# State kept for watermark duration + processing time + +# Example calculation: +# - 10 minute watermark +# - 1M events/min +# - State size = ~10M keys × key_size + +# Reduce watermark to reduce state size +.withWatermark("event_time", "5 minutes") # Smaller state + +# State automatically expires after watermark duration +# No manual cleanup needed +``` + +## State Store Configuration + +### Enable RocksDB + +Use RocksDB for state stores exceeding memory capacity: + +```python +# Enable RocksDB state store provider +spark.conf.set( + "spark.sql.streaming.stateStore.providerClass", + "com.databricks.sql.streaming.state.RocksDBStateProvider" +) + +# Benefits: +# - State stored on disk, reducing memory pressure +# - Recommended for: High cardinality keys, long watermark durations +# - Better performance for large state stores +``` + +### State Store Configuration + +```python +# State store batch retention +spark.conf.set("spark.sql.streaming.stateStore.minBatchesToRetain", "2") + +# State maintenance interval +spark.conf.set("spark.sql.streaming.stateStore.maintenanceInterval", "5m") + +# State store location (default: checkpoint/state) +# Automatically managed by Spark +``` + +## Common Patterns + +### Pattern 1: Basic Stateful Operation with Watermark + +```python +# Watermark for deduplication +df = (spark.readStream + .format("kafka") + .option("subscribe", "events") + .load() + .select(from_json(col("value").cast("string"), schema).alias("data")) + .select("data.*") + .withWatermark("event_time", "10 minutes") + .dropDuplicates(["event_id"]) +) + +# State expires after watermark duration +# Prevents infinite state growth +``` + +### Pattern 2: Join-Specific Watermark Tuning + +Different watermarks for streams with different latencies: + +```python +# Fast source: 5 minute watermark +impressions = (spark.readStream + .format("kafka") + .option("subscribe", "impressions") + .load() + .select(from_json(col("value").cast("string"), impression_schema).alias("data")) + .select("data.*") + .withWatermark("impression_time", "5 minutes") +) + +# Slower source: 15 minute watermark +clicks = (spark.readStream + .format("kafka") + .option("subscribe", "clicks") + .load() + .select(from_json(col("value").cast("string"), click_schema).alias("data")) + .select("data.*") + .withWatermark("click_time", "15 minutes") +) + +# Effective watermark = max(5, 15) = 15 minutes +joined = impressions.join( + clicks, + expr(""" + impressions.ad_id = clicks.ad_id AND + clicks.click_time BETWEEN impressions.impression_time AND + impressions.impression_time + interval 1 hour + """), + "inner" +) +``` + +### Pattern 3: Windowed Aggregations with Watermark + +```python +from pyspark.sql.functions import window, count, sum, max, current_timestamp + +windowed = (df + .withWatermark("event_time", "10 minutes") + .groupBy( + window(col("event_time"), "5 minutes"), + col("user_id") + ) + .agg( + count("*").alias("event_count"), + sum("value").alias("total_value"), + max("event_time").alias("latest_event") + ) + .withColumn("processing_time", current_timestamp()) +) + +# Use update mode for corrected results when late data arrives +windowed.writeStream \ + .outputMode("update") \ + .format("delta") \ + .option("checkpointLocation", "/checkpoints/windowed") \ + .start("/delta/windowed_metrics") +``` + +### Pattern 4: Monitor State Partition Balance + +Check for state store skew: + +```python +def check_state_balance(checkpoint_path): + """Check state store partition balance""" + state_df = spark.read.format("statestore").load(f"{checkpoint_path}/state") + + partition_counts = state_df.groupBy("partitionId").count().orderBy(desc("count")) + partition_counts.show() + + # Calculate skew + counts = [row['count'] for row in partition_counts.collect()] + if counts: + max_count = max(counts) + min_count = min(counts) + skew_ratio = max_count / min_count if min_count > 0 else float('inf') + + print(f"State skew ratio: {skew_ratio:.2f}") + if skew_ratio > 10: + print("WARNING: High state skew detected") + return False + return True +``` + +### Pattern 5: Monitor State Growth + +```python +def monitor_state_growth(checkpoint_path): + """Track state store growth""" + state_df = spark.read.format("statestore").load(f"{checkpoint_path}/state") + + # Current state size + total_rows = state_df.count() + + print(f"State rows: {total_rows}") + + # Check expiration + from pyspark.sql.functions import current_timestamp, col + expired = state_df.filter(col("expirationMs") < current_timestamp().cast("long") * 1000) + expired_count = expired.count() + + print(f"Expired state rows: {expired_count}") + print(f"Active state rows: {total_rows - expired_count}") +``` + +## State Size Control + +### Use Watermarks + +Watermarks automatically clean up expired state: + +```python +# State expires after watermark duration +.withWatermark("event_time", "10 minutes") + +# State size = f(watermark duration, key cardinality) +# 10 min watermark × 1M events/min = manageable +# 72 hour watermark × 1M events/min = very large +``` + +### Reduce Key Cardinality + +```python +# Bad: High cardinality keys +.dropDuplicates(["user_id"]) # Millions of distinct values + +# Good: Lower cardinality or expiring keys +.dropDuplicates(["session_id"]) # Sessions expire naturally +.dropDuplicates(["event_id", "date"]) # Partition by date reduces cardinality +``` + +## Monitoring + +### Programmatic State Monitoring + +```python +# Monitor state size programmatically +for stream in spark.streams.active: + progress = stream.lastProgress + + if progress and "stateOperators" in progress: + for op in progress["stateOperators"]: + print(f"Operator: {op.get('operatorName', 'unknown')}") + print(f"State rows: {op.get('numRowsTotal', 0)}") + print(f"State memory: {op.get('memoryUsedBytes', 0)}") + print(f"State on disk: {op.get('diskBytesUsed', 0)}") +``` + +### Track Late Data Rates + +```python +# Monitor late data impact +late_data_stats = spark.sql(""" + SELECT + date_trunc('hour', event_time) as hour, + COUNT(*) as total_events, + SUM(CASE + WHEN unix_timestamp(processing_time) - unix_timestamp(event_time) > 600 + THEN 1 ELSE 0 + END) as late_events, + AVG(unix_timestamp(processing_time) - unix_timestamp(event_time)) as avg_delay_seconds, + MAX(unix_timestamp(processing_time) - unix_timestamp(event_time)) as max_delay_seconds + FROM events + WHERE processing_time >= current_timestamp() - interval 24 hours + GROUP BY 1 + ORDER BY 1 DESC +""") +``` + +## Late Data Classification + +| Delay | Category | Handling | +|-------|----------|----------| +| < Watermark | On-time | Normal processing | +| Watermark < delay < 2×Watermark | Late | Join with inner match; may still process | +| > 2×Watermark | Very late | DLQ for manual handling | + +## Common Issues + +| Issue | Cause | Solution | +|-------|-------|----------| +| **State store explosion** | Watermark too long | Reduce watermark; archive old state | +| **Late data dropped** | Watermark too short | Increase watermark; analyze latency patterns | +| **State too large** | High cardinality keys or long watermark | Reduce key cardinality; decrease watermark duration | +| **State partition skew** | Uneven key distribution | Ensure keys are evenly distributed; consider salting | +| **OOM errors** | State exceeds memory | Enable RocksDB; increase memory; reduce watermark | +| **State not expiring** | Watermark not configured | Add watermark to stateful operations | + +## State Store Recovery + +```python +# Scenario 1: State store corruption +# Solution: Delete state folder, restart stream +# State will rebuild from watermark + +dbutils.fs.rm("/checkpoints/stream/state", recurse=True) + +# Restart stream - state rebuilds automatically +# Note: May reprocess some data within watermark window + +# Scenario 2: State store too large +# Solution: Reduce watermark duration +.withWatermark("event_time", "5 minutes") # Reduced from 10 minutes + +# Scenario 3: State partition imbalance +# Solution: Ensure keys are evenly distributed +# Consider salting keys if needed +``` + +## Production Best Practices + +### Always Use Watermarks for Stateful Operations + +```python +# REQUIRED: Watermark for stateful operations +df.withWatermark("event_time", "10 minutes").dropDuplicates(["id"]) + +# REQUIRED: Watermark for aggregations +df.withWatermark("event_time", "10 minutes").groupBy(...).agg(...) + +# REQUIRED: Watermark for stream-stream joins +stream1.withWatermark("ts", "10 min").join(stream2.withWatermark("ts", "10 min")) +``` + +### Watermark Selection + +```python +# Rule of thumb: 2-3× p95 latency +# Example: p95 latency = 5 minutes → watermark = 10-15 minutes + +# Start conservative, adjust based on monitoring +.withWatermark("event_time", "10 minutes") # Start here +# Monitor late data rate +# Increase if too many late events +# Decrease if state too large +``` + +### Use RocksDB for Large State + +```python +# Enable RocksDB if state > memory capacity +# Typical threshold: > 100M keys or > 10GB state + +spark.conf.set( + "spark.sql.streaming.stateStore.providerClass", + "com.databricks.sql.streaming.state.RocksDBStateProvider" +) +``` + +## Production Checklist + +- [ ] Watermark configured for all stateful operations +- [ ] Watermark duration matches latency requirements (2-3× p95) +- [ ] RocksDB enabled for large state stores +- [ ] State size monitored and alerts configured +- [ ] State partition balance checked regularly +- [ ] State growth tracked over time +- [ ] Late data monitoring configured +- [ ] Recovery procedure documented + +## Related Skills + +- `stream-stream-joins` - Late data in joins +- `checkpoint-best-practices` - Checkpoint and state recovery diff --git a/.claude/skills/databricks-spark-structured-streaming/stream-static-joins.md b/.claude/skills/databricks-spark-structured-streaming/stream-static-joins.md new file mode 100644 index 00000000..614d87c8 --- /dev/null +++ b/.claude/skills/databricks-spark-structured-streaming/stream-static-joins.md @@ -0,0 +1,519 @@ +--- +name: stream-static-joins +description: Enrich streaming data with Delta dimension tables in real-time. Use when joining fast-moving streaming events with slowly-changing reference data (device dimensions, user profiles, product catalogs), implementing real-time data enrichment, or adding context to streaming events without state management overhead. +--- + +# Stream-Static Joins + +Enrich streaming data with slowly-changing reference data stored in Delta tables. Stream-static joins are stateless and automatically refresh dimension data each microbatch. + +## Quick Start + +```python +from pyspark.sql.functions import col, from_json + +# Streaming source (IoT events from Kafka) +iot_stream = (spark + .readStream + .format("kafka") + .option("kafka.bootstrap.servers", "broker:9092") + .option("subscribe", "iot-events") + .load() + .select(from_json(col("value").cast("string"), event_schema).alias("data")) + .select("data.*") +) + +# Static Delta dimension table (refreshes each microbatch) +device_dim = spark.table("device_dimensions") + +# Enrich streaming data with left join (recommended) +enriched = iot_stream.join( + device_dim, + "device_id", + "left" # Preserves all streaming events +).select( + iot_stream["*"], + device_dim["device_type"], + device_dim["location"], + device_dim["manufacturer"], + device_dim["updated_at"].alias("dim_updated_at") +) + +# Write enriched data +query = (enriched + .writeStream + .format("delta") + .outputMode("append") + .option("checkpointLocation", "/Volumes/catalog/checkpoints/enriched_events") + .trigger(processingTime="30 seconds") + .start("/delta/enriched_iot_events") +) +``` + +## Core Concepts + +### Why Delta Tables Matter + +Delta tables enable automatic version checking each microbatch: + +```python +# Delta table: Version checked every microbatch +device_dim = spark.table("device_dimensions") # Reads latest version automatically + +# Non-Delta format: Read once at startup (truly static) +device_dim = spark.read.parquet("/path/to/devices") # No refresh +``` + +**Key Insight**: Delta's versioning ensures each microbatch gets the latest dimension data without manual refresh. + +### Join Types and Production Use + +| Join Type | Behavior | Production Use | +|-----------|----------|----------------| +| **Left** | Preserves all stream events | ✅ Recommended - prevents data loss | +| **Inner** | Drops unmatched events | ⚠️ Risk of data loss - avoid in production | +| **Right** | Preserves all dimension rows | Rarely used | +| **Full** | Preserves both sides | Rarely used | + +**Production Rule**: Always use left join to prevent dropping valid streaming events. + +## Common Patterns + +### Pattern 1: Basic Device Enrichment + +Enrich IoT events with device metadata: + +```python +# Streaming IoT events +iot_stream = (spark + .readStream + .format("kafka") + .option("subscribe", "iot-events") + .load() + .select(from_json(col("value").cast("string"), event_schema).alias("data")) + .select("data.*") +) + +# Device dimension table +device_dim = spark.table("device_dimensions") + +# Left join to preserve all events +enriched = iot_stream.join( + device_dim, + "device_id", + "left" +).select( + iot_stream["*"], + device_dim["device_type"], + device_dim["location"], + device_dim["status"] +) + +enriched.writeStream \ + .format("delta") \ + .option("checkpointLocation", "/checkpoints/enriched") \ + .start("/delta/enriched_events") +``` + +### Pattern 2: Multi-Table Enrichment + +Chain multiple dimension joins: + +```python +# Multiple dimension tables +devices = spark.table("device_dimensions") +locations = spark.table("location_dimensions") +categories = spark.table("category_dimensions") + +# Chain joins (each is stateless) +enriched = (iot_stream + .join(devices, "device_id", "left") + .join(locations, "location_id", "left") + .join(categories, "category_id", "left") + .select( + iot_stream["*"], + devices["device_type"], + devices["manufacturer"], + locations["region"], + locations["country"], + categories["category_name"] + ) +) + +# Each join refreshes independently each microbatch +``` + +### Pattern 3: Broadcast Hash Join Optimization + +Optimize joins by ensuring broadcast: + +```python +from pyspark.sql.functions import broadcast + +# Option 1: Select only needed columns +small_dim = device_dim.select("device_id", "device_type", "location") + +# Option 2: Filter to active records +active_dim = device_dim.filter(col("status") == "active") + +# Option 3: Force broadcast hint +enriched = iot_stream.join( + broadcast(active_dim), + "device_id", + "left" +) + +# Verify in Spark UI: Look for "BroadcastHashJoin" in query plan +``` + +### Pattern 4: Audit Dimension Freshness + +Track how fresh dimension data is: + +```python +from pyspark.sql.functions import unix_timestamp, current_timestamp + +enriched = (iot_stream + .join(device_dim, "device_id", "left") + .withColumn( + "dim_lag_seconds", + unix_timestamp(current_timestamp()) - + unix_timestamp(col("dim_updated_at")) + ) + .withColumn( + "dim_fresh", + col("dim_lag_seconds") < 3600 # Less than 1 hour old + ) +) + +# Monitor: Alert if dim_lag_seconds > threshold +# Use for data quality checks +``` + +### Pattern 5: Time-Travel Dimension Lookup + +Join with dimension as-of event time: + +```python +from delta import DeltaTable + +def enrich_with_time_travel(batch_df, batch_id): + """Enrich with dimension version at event time""" + from pyspark.sql.functions import max as spark_max + + # Get latest dimension version + latest_version = DeltaTable.forName(spark, "device_dimensions") \ + .history() \ + .select(spark_max("version").alias("max_version")) \ + .first()[0] + + # Read dimension at specific version + dim_at_version = (spark + .read + .format("delta") + .option("versionAsOf", latest_version) + .table("device_dimensions") + ) + + # Join with batch + enriched = batch_df.join(dim_at_version, "device_id", "left") + + # Write + (enriched + .write + .format("delta") + .mode("append") + .option("txnVersion", batch_id) + .option("txnAppId", "enrichment_job") + .saveAsTable("enriched_events") + ) + +iot_stream.writeStream \ + .foreachBatch(enrich_with_time_travel) \ + .option("checkpointLocation", "/checkpoints/enriched") \ + .start() +``` + +### Pattern 6: Backfill Missing Dimensions + +Daily job to fix null dimensions from left join: + +```python +# Daily batch job to backfill missing dimensions +spark.sql(""" + MERGE INTO enriched_events target + USING device_dimensions source + ON target.device_id = source.device_id + AND target.device_type IS NULL + WHEN MATCHED THEN + UPDATE SET + device_type = source.device_type, + location = source.location, + manufacturer = source.manufacturer, + dim_updated_at = source.updated_at +""") + +# Run after dimension table updates +# Fixes events that arrived before dimension was available +``` + +### Pattern 7: Dimension Change Detection + +Stream that reacts to dimension changes: + +```python +def update_reference_cache(batch_df, batch_id): + """Update in-memory cache when dimension changes""" + # Dimension table changed + # Update application cache or notify downstream systems + pass + +# Stream dimension table changes +dim_changes = (spark + .readStream + .format("delta") + .table("device_dimensions") + .writeStream + .foreachBatch(update_reference_cache) + .option("checkpointLocation", "/checkpoints/dim_changes") + .start() +) +``` + +## Performance Optimization + +### Checklist + +- [ ] Dimension table < 100MB for broadcast (or increase threshold) +- [ ] Select only needed columns before join +- [ ] Filter dimension to active records only +- [ ] Verify "BroadcastHashJoin" in query plan +- [ ] Partition size 100-200MB in memory +- [ ] Use same region for compute and storage + +### Configuration + +```python +# Increase broadcast threshold if dimension is larger +spark.conf.set("spark.sql.autoBroadcastJoinThreshold", "1g") + +# Control partition size +spark.conf.set("spark.sql.shuffle.partitions", "200") + +# Optimize dimension table reads +spark.conf.set("spark.databricks.delta.optimizeWrite.enabled", "true") +spark.conf.set("spark.databricks.delta.autoCompact.enabled", "true") +``` + +### Reduce Dimension Size + +```python +# Before join: Select only needed columns +small_dim = device_dim.select( + "device_id", + "device_type", + "location", + "status" +) + +# Filter to active records +active_dim = small_dim.filter(col("status") == "active") + +# Join with smaller dimension +enriched = iot_stream.join(active_dim, "device_id", "left") +``` + +## Monitoring + +### Key Metrics + +```python +# Null rate (left join quality) +spark.sql(""" + SELECT + date_trunc('hour', timestamp) as hour, + count(*) as total_events, + count(device_type) as matched_events, + count(*) - count(device_type) as unmatched_events, + (count(*) - count(device_type)) * 100.0 / count(*) as null_rate_pct + FROM enriched_events + GROUP BY 1 + ORDER BY 1 DESC +""") + +# Dimension freshness +spark.sql(""" + SELECT + date_trunc('hour', timestamp) as hour, + avg(dim_lag_seconds) as avg_lag_seconds, + max(dim_lag_seconds) as max_lag_seconds, + count(*) as events_with_dim + FROM enriched_events + WHERE dim_updated_at IS NOT NULL + GROUP BY 1 + ORDER BY 1 DESC +""") +``` + +### Programmatic Monitoring + +```python +# Monitor stream health +for stream in spark.streams.active: + status = stream.status + progress = stream.lastProgress + + if progress: + print(f"Stream: {stream.name}") + print(f"Input rate: {progress.get('inputRowsPerSecond', 0)} rows/sec") + print(f"Processing rate: {progress.get('processedRowsPerSecond', 0)} rows/sec") + print(f"Batch duration: {progress.get('durationMs', {}).get('triggerExecution', 0)} ms") +``` + +### Spark UI Checks + +- **Streaming Tab**: Input rate vs processing rate (processing must exceed input) +- **SQL Tab**: Look for "BroadcastHashJoin" (not "SortMergeJoin") +- **Jobs Tab**: Check for shuffle operations (should be minimal) +- **Stages Tab**: Verify partition sizes (100-200MB target) + +## Common Issues + +| Issue | Cause | Solution | +|-------|-------|----------| +| **Data loss** | Inner join dropping unmatched events | Switch to left join | +| **Slow joins** | Shuffle join instead of broadcast | Reduce dimension size; force broadcast | +| **Stale data** | Non-Delta format | Convert dimension table to Delta | +| **Memory issues** | Large dimension table | Filter before join; increase broadcast threshold | +| **Skewed joins** | Hot keys in dimension | Salt the join key or partition dimension table | +| **High null rate** | Dimension updates lagging | Monitor dimension freshness; backfill job | + +## Production Best Practices + +### Always Use Left Join + +```python +# WRONG: Inner join loses data +enriched = iot_stream.join(device_dim, "device_id", "inner") + +# CORRECT: Left join preserves all events +enriched = iot_stream.join(device_dim, "device_id", "left") + +# Why? New devices may send data before dimension table is updated +# Left join preserves events; backfill dimensions later +``` + +### Handle Null Dimensions + +```python +# Add null handling in transformations +enriched = (iot_stream + .join(device_dim, "device_id", "left") + .withColumn( + "device_type", + coalesce(col("device_type"), lit("UNKNOWN")) + ) + .withColumn( + "location", + coalesce(col("location"), lit("UNKNOWN")) + ) +) + +# Or flag for manual review +enriched = enriched.withColumn( + "needs_review", + col("device_type").isNull() +) +``` + +### Idempotent Writes + +```python +def idempotent_write(batch_df, batch_id): + """Write with transaction version for idempotency""" + (batch_df + .write + .format("delta") + .mode("append") + .option("txnVersion", batch_id) + .option("txnAppId", "enrichment_job") + .saveAsTable("enriched_events") + ) + +enriched.writeStream \ + .foreachBatch(idempotent_write) \ + .option("checkpointLocation", "/checkpoints/enriched") \ + .start() +``` + +## Production Checklist + +- [ ] Left join used (not inner join) +- [ ] Dimension table is Delta format +- [ ] Broadcast hash join verified in query plan +- [ ] Dimension size optimized (< 100MB or threshold increased) +- [ ] Null rate monitored and alerts configured +- [ ] Dimension freshness tracked +- [ ] Backfill job scheduled for missing dimensions +- [ ] Checkpoint location is unique per query +- [ ] Idempotent writes configured (txnVersion/txnAppId) +- [ ] Performance metrics tracked (input rate, batch duration) + +## Expert Tips + +### Delta Version Checking + +Delta tables automatically refresh each microbatch by checking the latest version: + +```python +# Each microbatch: +# 1. Spark checks Delta table version +# 2. Reads latest version if changed +# 3. Uses cached version if unchanged +# 4. No manual refresh needed + +# This is why Delta tables work better than Parquet for dimensions +# Parquet: Read once at startup (truly static) +# Delta: Version checked each microbatch (semi-static) +``` + +### Broadcast Join Verification + +Always verify broadcast joins in production: + +```python +# Check query plan +enriched.explain(extended=True) + +# Look for: +# - BroadcastHashJoin ✅ (fast, no shuffle) +# - SortMergeJoin ⚠️ (slower, requires shuffle) + +# If seeing SortMergeJoin: +# 1. Reduce dimension size (select columns, filter rows) +# 2. Increase broadcast threshold +# 3. Force broadcast hint +``` + +### Dimension Table Optimization + +Optimize dimension tables for streaming joins: + +```python +# 1. Use Z-order or liquid clustering on join key +spark.sql(""" + OPTIMIZE device_dimensions + ZORDER BY (device_id) +""") + +# 2. Keep dimension tables small (< 100MB ideal) +# 3. Use Delta for automatic version checking +# 4. Partition by frequently filtered columns +``` + +## Related Skills + +- `stream-stream-joins` - Join two streaming sources with state management +- `kafka-to-delta` - Kafka ingestion patterns +- `write-multiple-tables` - Fan-out patterns for multiple sinks +- `checkpoint-best-practices` - Checkpoint configuration and management diff --git a/.claude/skills/databricks-spark-structured-streaming/stream-stream-joins.md b/.claude/skills/databricks-spark-structured-streaming/stream-stream-joins.md new file mode 100644 index 00000000..e5b10aad --- /dev/null +++ b/.claude/skills/databricks-spark-structured-streaming/stream-stream-joins.md @@ -0,0 +1,588 @@ +--- +name: stream-stream-joins +description: Join two streaming sources in real-time with event-time semantics, watermarks, and state management. Use when correlating events from different streams (orders with payments, clicks with conversions, sensor readings), handling late-arriving data, or implementing windowed aggregations across multiple streams. +--- + +# Stream-Stream Joins + +Join two streaming sources in real-time to correlate events that arrive at different times and speeds. Stream-stream joins require watermarks to manage state and handle late-arriving data. + +## Quick Start + +```python +from pyspark.sql.functions import expr, from_json, col +from pyspark.sql.types import StructType + +# Read two streaming sources +orders = (spark + .readStream + .format("kafka") + .option("kafka.bootstrap.servers", "broker:9092") + .option("subscribe", "orders") + .load() + .select(from_json(col("value").cast("string"), order_schema).alias("data")) + .select("data.*") + .withWatermark("order_time", "10 minutes") +) + +payments = (spark + .readStream + .format("kafka") + .option("kafka.bootstrap.servers", "broker:9092") + .option("subscribe", "payments") + .load() + .select(from_json(col("value").cast("string"), payment_schema).alias("data")) + .select("data.*") + .withWatermark("payment_time", "10 minutes") +) + +# Join with time bounds +matched = (orders + .join( + payments, + expr(""" + orders.order_id = payments.order_id AND + payments.payment_time >= orders.order_time - interval 5 minutes AND + payments.payment_time <= orders.order_time + interval 10 minutes + """), + "inner" + ) +) + +# Write results +query = (matched + .writeStream + .format("delta") + .outputMode("append") + .option("checkpointLocation", "/Volumes/catalog/checkpoints/orders_payments") + .trigger(processingTime="30 seconds") + .start("/delta/order_payments") +) +``` + +## Core Concepts + +### Why Stream-Stream Joins Need Watermarks + +Stream-stream joins are stateful: both sides must buffer events until matches are found or state expires. Watermarks define when state can be safely cleaned up. + +```python +# Watermark = latest_event_time - delay_threshold +.withWatermark("event_time", "10 minutes") + +# Events with timestamp < watermark are considered "too late" +# State for late events is automatically cleaned up +``` + +### Join Types and Behavior + +| Join Type | Matches | Late Events | Use Case | +|-----------|---------|-------------|----------| +| **Inner** | Both sides | May still match if other side hasn't expired | Correlation analysis | +| **Left Outer** | All left + matched right | Dropped from left side after watermark | Enrichment with optional data | +| **Right Outer** | All right + matched left | Dropped from right side after watermark | Rarely used | +| **Full Outer** | All events from both | Dropped after watermark | Complete picture | + +## Common Patterns + +### Pattern 1: Order-Payment Matching + +Match orders with payments within a time window: + +```python +orders = (spark + .readStream + .format("kafka") + .option("subscribe", "orders") + .load() + .select(from_json(col("value").cast("string"), order_schema).alias("data")) + .select("data.*") + .withWatermark("order_time", "10 minutes") +) + +payments = (spark + .readStream + .format("kafka") + .option("subscribe", "payments") + .load() + .select(from_json(col("value").cast("string"), payment_schema).alias("data")) + .select("data.*") + .withWatermark("payment_time", "10 minutes") +) + +# Match payments within 10 minutes of order +matched = (orders + .join( + payments, + expr(""" + orders.order_id = payments.order_id AND + payments.payment_time >= orders.order_time - interval 5 minutes AND + payments.payment_time <= orders.order_time + interval 10 minutes + """), + "leftOuter" # Include orders without payments + ) + .withColumn("matched", col("payment_id").isNotNull()) +) + +matched.writeStream \ + .format("delta") \ + .option("checkpointLocation", "/checkpoints/orders_payments") \ + .start("/delta/order_payments") +``` + +### Pattern 2: Click-Conversion Attribution + +Attribute conversions to clicks within a time window: + +```python +impressions = (spark + .readStream + .format("kafka") + .option("subscribe", "impressions") + .load() + .select(from_json(col("value").cast("string"), impression_schema).alias("data")) + .select("data.*") + .withWatermark("impression_time", "1 hour") +) + +conversions = (spark + .readStream + .format("kafka") + .option("subscribe", "conversions") + .load() + .select(from_json(col("value").cast("string"), conversion_schema).alias("data")) + .select("data.*") + .withWatermark("conversion_time", "1 hour") +) + +# Attribute conversion to last impression within 24 hours +attributed = (impressions + .join( + conversions, + expr(""" + impressions.user_id = conversions.user_id AND + impressions.ad_id = conversions.ad_id AND + conversions.conversion_time >= impressions.impression_time AND + conversions.conversion_time <= impressions.impression_time + interval 24 hours + """), + "inner" + ) + .withColumn("attribution_window_hours", + (col("conversion_time").cast("long") - col("impression_time").cast("long")) / 3600) +) + +attributed.writeStream \ + .format("delta") \ + .option("checkpointLocation", "/checkpoints/attribution") \ + .start("/delta/attributed_conversions") +``` + +### Pattern 3: Sessionization Across Streams + +Group events from multiple streams into sessions: + +```python +from pyspark.sql.functions import session_window + +pageviews = (spark + .readStream + .format("kafka") + .option("subscribe", "pageviews") + .load() + .select(from_json(col("value").cast("string"), pageview_schema).alias("data")) + .select("data.*") + .withWatermark("event_time", "30 minutes") +) + +clicks = (spark + .readStream + .format("kafka") + .option("subscribe", "clicks") + .load() + .select(from_json(col("value").cast("string"), click_schema).alias("data")) + .select("data.*") + .withWatermark("event_time", "30 minutes") +) + +# Create session windows for each stream +pageview_sessions = (pageviews + .groupBy( + col("user_id"), + session_window(col("event_time"), "10 minutes") + ) + .agg( + count("*").alias("pageview_count"), + min("event_time").alias("session_start"), + max("event_time").alias("session_end") + ) +) + +click_sessions = (clicks + .groupBy( + col("user_id"), + session_window(col("event_time"), "10 minutes") + ) + .agg( + count("*").alias("click_count"), + min("event_time").alias("session_start"), + max("event_time").alias("session_end") + ) +) + +# Join sessions +joined_sessions = (pageview_sessions + .join( + click_sessions, + ["user_id", "session_window"], + "outer" + ) + .withColumn("total_events", + coalesce(col("pageview_count"), lit(0)) + + coalesce(col("click_count"), lit(0))) +) + +joined_sessions.writeStream \ + .format("delta") \ + .option("checkpointLocation", "/checkpoints/sessions") \ + .start("/delta/user_sessions") +``` + +### Pattern 4: Late Data Handling with Dead Letter Queue + +Route late-arriving events to a separate table: + +```python +def write_with_late_data_handling(batch_df, batch_id): + """Separate on-time and late data""" + from pyspark.sql.functions import current_timestamp, unix_timestamp + + # Calculate delay + processed = batch_df.withColumn( + "processing_delay_seconds", + unix_timestamp(current_timestamp()) - unix_timestamp(col("event_time")) + ) + + # On-time data (within watermark) + on_time = processed.filter(col("processing_delay_seconds") < 600) # 10 minutes + + # Late data + late = processed.filter(col("processing_delay_seconds") >= 600) + + # Write on-time data + (on_time + .drop("processing_delay_seconds") + .write + .format("delta") + .mode("append") + .option("txnVersion", batch_id) + .option("txnAppId", "stream_join_job") + .saveAsTable("matched_events") + ) + + # Write late data to DLQ + if late.count() > 0: + (late + .withColumn("dlq_reason", lit("LATE_ARRIVAL")) + .withColumn("dlq_timestamp", current_timestamp()) + .write + .format("delta") + .mode("append") + .saveAsTable("late_data_dlq") + ) + +matched.writeStream \ + .foreachBatch(write_with_late_data_handling) \ + .option("checkpointLocation", "/checkpoints/orders_payments") \ + .start() +``` + +## State Management + +### Configure RocksDB for Large State + +For state stores exceeding memory capacity, use RocksDB: + +```python +# Enable RocksDB state store provider +spark.conf.set( + "spark.sql.streaming.stateStore.providerClass", + "com.databricks.sql.streaming.state.RocksDBStateProvider" +) + +# State is stored on disk, reducing memory pressure +# Recommended for: High cardinality keys, long watermark durations +``` + +### Monitor State Size + +```python +# Read state store directly +state_df = (spark + .read + .format("statestore") + .load("/checkpoints/orders_payments/state") +) + +# Check partition balance +state_df.groupBy("partitionId").count().orderBy(desc("count")).show() + +# Check state size +state_metadata = (spark + .read + .format("state-metadata") + .load("/checkpoints/orders_payments") +) +state_metadata.show() + +# Programmatic monitoring +for stream in spark.streams.active: + progress = stream.lastProgress + if progress and "stateOperators" in progress: + for op in progress["stateOperators"]: + print(f"State rows: {op.get('numRowsTotal', 0)}") + print(f"State memory: {op.get('memoryUsedBytes', 0)}") +``` + +### Control State Growth + +```python +# 1. Use watermarks (automatic cleanup) +.withWatermark("event_time", "10 minutes") # State expires after watermark + +# 2. Reduce key cardinality +# Bad: user_id (millions of distinct values) +# Good: session_id (expires naturally) + +# 3. Set reasonable time bounds +# Bad: unbounded time range +expr("s2.ts >= s1.ts") # State grows forever! + +# Good: bounded time range +expr("s2.ts BETWEEN s1.ts AND s1.ts + interval 1 hour") +``` + +## Watermark Configuration + +### Choosing Watermark Duration + +Balance between latency and completeness: + +```python +# Rule of thumb: 2-3x the expected delay +# If 99th percentile delay is 5 minutes → use 10-15 minute watermark + +# High tolerance (more matches, larger state) +.withWatermark("event_time", "2 hours") + +# Low tolerance (faster results, smaller state) +.withWatermark("event_time", "10 minutes") +``` + +### Multiple Watermarks + +When joining streams with different latencies: + +```python +# Stream 1: Fast, low latency +stream1 = stream1.withWatermark("ts", "5 minutes") + +# Stream 2: Slow, high latency +stream2 = stream2.withWatermark("ts", "15 minutes") + +# Effective watermark = max(5, 15) = 15 minutes +joined = stream1.join(stream2, join_condition, "inner") +``` + +## Production Best Practices + +### Idempotent Writes + +Ensure exactly-once semantics: + +```python +def idempotent_write(batch_df, batch_id): + """Write with transaction version for idempotency""" + (batch_df + .write + .format("delta") + .mode("append") + .option("txnVersion", batch_id) + .option("txnAppId", "stream_join_job") + .saveAsTable("matched_events") + ) + +matched.writeStream \ + .foreachBatch(idempotent_write) \ + .option("checkpointLocation", "/checkpoints/orders_payments") \ + .start() +``` + +### Multi-Stream Joins (3+ Streams) + +Chain joins carefully - each adds state overhead: + +```python +# Step 1: Join streams A and B +ab = (stream_a + .withWatermark("ts", "10 minutes") + .join( + stream_b.withWatermark("ts", "10 minutes"), + expr("a.key = b.key AND b.ts BETWEEN a.ts - interval 5 min AND a.ts + interval 5 min"), + "inner" + ) +) + +# Step 2: Join result with stream C +abc = ab.join( + stream_c.withWatermark("ts", "10 minutes"), + expr("ab.key = c.key AND c.ts BETWEEN ab.ts - interval 5 min AND ab.ts + interval 5 min"), + "inner" +) + +# Note: Result watermark comes from left side (ab) +``` + +### Performance Tuning + +```python +# State store batch retention +spark.conf.set("spark.sql.streaming.stateStore.minBatchesToRetain", "2") + +# State maintenance interval +spark.conf.set("spark.sql.streaming.stateStore.maintenanceInterval", "5m") + +# Shuffle partitions (match worker cores) +spark.conf.set("spark.sql.shuffle.partitions", "200") +``` + +## Monitoring + +### Key Metrics + +```python +# Programmatic monitoring +for stream in spark.streams.active: + status = stream.status + progress = stream.lastProgress + + if progress: + print(f"Stream: {stream.name}") + print(f"Input rate: {progress.get('inputRowsPerSecond', 0)} rows/sec") + print(f"Processing rate: {progress.get('processedRowsPerSecond', 0)} rows/sec") + + # State metrics + if "stateOperators" in progress: + for op in progress["stateOperators"]: + print(f"State rows: {op.get('numRowsTotal', 0)}") + print(f"State memory: {op.get('memoryUsedBytes', 0)}") + + # Watermark + if "eventTime" in progress: + print(f"Watermark: {progress['eventTime'].get('watermark', 'N/A')}") +``` + +### Spark UI Checks + +- **Streaming Tab**: Input rate vs processing rate (processing must exceed input) +- **State Operators**: State size and memory usage +- **Watermark**: Current watermark timestamp +- **Batch Duration**: Should be < trigger interval + +## Common Issues + +| Issue | Cause | Solution | +|-------|-------|----------| +| **State too large** | High cardinality keys or long watermark | Reduce key space; decrease watermark duration | +| **Late events dropped** | Watermark too aggressive | Increase watermark delay | +| **No matches** | Time condition wrong | Check time bounds and units (minutes vs hours) | +| **OOM errors** | State explosion | Use RocksDB; increase memory; reduce watermark | +| **Missing watermarks** | State grows forever | Always define watermarks on both sides | +| **Unbounded state** | Open-ended time range | Use bounded time range in join condition | + +## Production Checklist + +- [ ] Watermark configured on both streaming sources +- [ ] Join condition includes explicit time bounds +- [ ] State store provider set (RocksDB for large state) +- [ ] State size monitored and alerts configured +- [ ] Late data handling strategy defined (DLQ or tolerance) +- [ ] Output mode is "append" (required for streaming joins) +- [ ] Checkpoint location is unique per query +- [ ] Idempotent writes configured (txnVersion/txnAppId) +- [ ] Time zones normalized across streams +- [ ] Performance metrics tracked (input rate, state size, watermark lag) + +## Expert Tips + +### Event Time vs Processing Time + +Always use event time for stream-stream joins: + +```python +# ✅ CORRECT: Event time (deterministic) +.withWatermark("event_time", "10 minutes") + +# ❌ WRONG: Processing time (non-deterministic) +# Processing time varies based on system load +# Results are not reproducible +``` + +### Watermark Semantics Deep Dive + +Understanding watermark behavior: + +```python +# Watermark = max_event_time - delay_threshold +# Example: max_event_time = 10:15, delay = 10 min +# Watermark = 10:05 + +# Events with timestamp < 10:05 are "too late" +# - Inner join: May still match if other side hasn't expired +# - Outer join: Dropped from outer side after watermark passes + +# Effective watermark = max(left_watermark, right_watermark) +``` + +### State Store Backend Selection + +Choose the right state store backend: + +```python +# Default: In-memory (fast but limited) +# Use for: Small state (< 10GB), low cardinality keys + +# RocksDB: Disk-backed (slower but scalable) +spark.conf.set( + "spark.sql.streaming.stateStore.providerClass", + "com.databricks.sql.streaming.state.RocksDBStateProvider" +) +# Use for: Large state (> 10GB), high cardinality keys + +# Monitor state size to decide when to switch +``` + +### Join Condition Best Practices + +Always include explicit time bounds: + +```python +# ❌ BAD: Unbounded (state grows forever) +expr("s1.key = s2.key AND s2.ts >= s1.ts") + +# ✅ GOOD: Bounded (state bounded by watermark) +expr(""" + s1.key = s2.key AND + s2.ts >= s1.ts - interval 5 minutes AND + s2.ts <= s1.ts + interval 10 minutes +""") + +# Why? Bounded ranges allow state cleanup +# Unbounded ranges cause state to grow indefinitely +``` + +## Related Skills + +- `stream-static-joins` - Enrich streams with Delta dimension tables +- `kafka-to-delta` - Kafka ingestion patterns +- `watermark-configuration` - Deep dive on watermark semantics +- `state-store-management` - State store optimization and monitoring diff --git a/.claude/skills/databricks-spark-structured-streaming/streaming-best-practices.md b/.claude/skills/databricks-spark-structured-streaming/streaming-best-practices.md new file mode 100644 index 00000000..9f3927a9 --- /dev/null +++ b/.claude/skills/databricks-spark-structured-streaming/streaming-best-practices.md @@ -0,0 +1,265 @@ +--- +name: "streaming-best-practices" +description: "Production-proven best practices for Spark Streaming: trigger intervals, partitioning, checkpoint management, and cluster configuration for reliable pipelines." +tags: ["spark-streaming", "best-practices", "production", "performance", "expert"] +--- + +# Streaming Best Practices Expert Pack + +## Overview + +A comprehensive checklist distilled from production experience. These practices should hold true in almost all scenarios. + +**Source**: Canadian Data Guy — "Spark Streaming Best Practices" + +## Beginner Checklist + +### 1. Always Set a Trigger Interval + +```python +# ✅ Good: Controls API costs and listing operations +stream.writeStream \ + .trigger(processingTime='5 seconds') \ + .start() + +# ❌ Bad: No trigger means continuous microbatches +# Can cause excessive S3/ADLS listing costs +``` + +**Why**: Fast processing (<1 sec) repeats listing operations, causing unintended costs. + +### 2. Use Auto Loader Notification Mode + +```python +# Switch from file listing to event-based +spark.readStream \ + .format("cloudFiles") \ + .option("cloudFiles.useNotifications", "true") \ + .load("/path/to/data") +``` + +[Auto Loader File Notification Mode](https://docs.databricks.com/ingestion/auto-loader/file-notification-mode.html) + +### 3. Disable S3 Versioning + +```python +# ❌ Don't enable versioning on S3 buckets with Delta +# ✅ Delta has time travel — no need for S3 versioning +# Versioning adds significant latency at scale +``` + +### 4. Co-Locate Compute and Storage + +```python +# ✅ Keep compute and storage in the same region +# Cross-region = latency + egress costs +``` + +### 5. Use ADLS Gen2 on Azure + +```python +# ✅ ADLS Gen2 is optimized for big data analytics +# ❌ Regular blob storage = slower performance +``` + +### 6. Partition Strategy + +```python +# ✅ Partition on low-cardinality columns: date, region, country +# ❌ Avoid high-cardinality: user_id, transaction_id + +# Rule of thumb: < 100,000 partitions +# Example: 10 years × 365 days × 20 countries = 73,000 partitions ✅ +``` + +### 7. Name Your Streaming Query + +```python +# ✅ Easily identifiable in Spark UI +stream.writeStream \ + .option("queryName", "IngestFromKafka") \ + .start() + +# Shows up as "IngestFromKafka" in Streaming tab +``` + +### 8. One Checkpoint Per Stream + +```python +# ✅ Each stream has its own checkpoint +# ❌ Never share checkpoints between streams + +# Example: Two sources → one target +# Source 1 → checkpoint_1 → target +# Source 2 → checkpoint_2 → target +``` + +### 9. Don't Multiplex Streams + +```python +# ❌ Don't run multiple streams on same driver +# Can cause stability issues + +# ✅ Use separate jobs or benchmark thoroughly +``` + +### 10. Optimal Partition Size + +```python +# Target: 100-200MB per partition in memory + +# Tune with: +.option("maxFilesPerTrigger", "100") +.option("maxBytesPerTrigger", "100MB") + +# Monitor in Spark UI → Stages → Partition size +``` + +### 11. Prefer Broadcast Hash Join + +```python +# ✅ BroadcastHashJoin is faster than SortMergeJoin +# Spark auto-broadcasts tables < 100MB + +# Increase threshold if needed: +spark.conf.set("spark.sql.autoBroadcastJoinThreshold", "1g") +``` + +## Advanced Checklist + +### 12. Checkpoint Naming Convention + +```python +# Structure: {table_location}/_checkpoints/_{target_table_name}_starting_{identifier} + +# Examples: +# 1. By timestamp: /delta/events/_checkpoints/_events_starting_2024_01_15 +# 2. By version: /delta/events/_checkpoints/_events_startingVersion_12345 + +# Why: Multiple checkpoints over table lifetime (upgrades, logic changes) +``` + +### 13. Minimize Shuffle Spill + +```python +# ✅ Goal: Shuffle spill (disk) = 0 +# ✅ Only shuffle read should exist + +# Check: Spark UI → SQL → Exchange operators +# If spill > 0: Increase memory or reduce partition size +``` + +### 14. Use RocksDB for Stateful Operations + +```python +# For large state stores, use RocksDB backend +spark.conf.set( + "spark.sql.streaming.stateStore.providerClass", + "com.databricks.sql.streaming.state.RocksDBStateProvider" +) +``` + +### 15. Event Hubs via Kafka Connector + +```python +# ✅ Use Kafka protocol for Azure Event Hubs +# More flexible partition handling + +# Note: With EventHubs Kafka connector +# Number of cores can differ from partitions +# (vs native EventHubs: cores == partitions) +``` + +### 16. Watermark for State Cleanup + +```python +# ✅ Always use watermark with stateful ops +# Prevents infinite state growth + +stream.withWatermark("timestamp", "10 minutes") \ + .groupBy("user_id") \ + .agg(sum("amount")) + +# Exception: If infinite state needed, store in Delta + ZORDER +``` + +### 17. Deduplication at Scale + +```python +# At trillion-record scale: +# ✅ Delta merge over dropDuplicates + +# dropDuplicates: State store grows very large +# Delta merge: Use table for lookup + +# Example: +spark.sql(""" + MERGE INTO target t + USING source s ON t.event_id = s.event_id + WHEN NOT MATCHED THEN INSERT * +""") +``` + +### 18. Azure Instance Family Selection + +| Workload | Instance Family | +|----------|----------------| +| Map-heavy (parsing, JSON) | F-series | +| Multiple streams from same source | Fsv2-series | +| Joins/aggregations/optimize | DS_v2-series | +| Delta caching | L-series (SSD) | + +### 19. Shuffle Partitions + +```python +# Set equal to total worker cores +spark.conf.set("spark.sql.shuffle.partitions", "200") + +# ❌ Don't set too high +# If changing: Clear checkpoint (stores the old value) +``` + +## Quick Reference + +### Trigger Selection + +| Latency Requirement | Trigger | +|---------------------|---------| +| < 1 second | Real-Time Mode (RTM) | +| 1-10 seconds | processingTime('5 seconds') | +| 1-60 minutes | processingTime based on SLA/3 | +| Batch-like | availableNow=True | + +### Cluster Sizing + +```python +# Fixed-size cluster recommended for streaming +# ❌ Don't use auto-scaling for streaming workloads + +# Why: Pre-allocated resources = predictable latency +``` + +## Monitoring Checklist + +- [ ] Input rate vs processing rate (processing > input) +- [ ] Max offsets behind latest (should decrease over time) +- [ ] Batch duration vs trigger interval (headroom exists) +- [ ] State store size (if using stateful ops) +- [ ] Shuffle spill = 0 +- [ ] Null rate in left joins (data quality) + +## Common Mistakes + +| Mistake | Impact | Fix | +|---------|--------|-----| +| Shared checkpoint | Data loss/corruption | Separate checkpoints | +| No watermark | State explosion | Add watermark | +| S3 versioning | Latency | Disable versioning | +| Autoscaling clusters | Unpredictable latency | Fixed-size clusters | +| High-cardinality partitions | Small files | Partition by date | + +## Related Skills + +- `spark-streaming-master-class-kafka-to-delta` — End-to-end patterns +- `mastering-checkpoints-in-spark-streaming` — Checkpoint deep dive +- `scaling-spark-streaming-jobs` — Performance tuning diff --git a/.claude/skills/databricks-spark-structured-streaming/trigger-and-cost-optimization.md b/.claude/skills/databricks-spark-structured-streaming/trigger-and-cost-optimization.md new file mode 100644 index 00000000..92ba4cb3 --- /dev/null +++ b/.claude/skills/databricks-spark-structured-streaming/trigger-and-cost-optimization.md @@ -0,0 +1,517 @@ +--- +name: trigger-and-cost-optimization +description: Select and tune triggers for Spark Structured Streaming to balance latency and cost. Use when choosing between processingTime, availableNow, and Real-Time Mode (RTM), calculating optimal trigger intervals, optimizing costs through cluster right-sizing, scheduled streaming, multi-stream clusters, or managing latency vs cost trade-offs. +--- + +# Trigger and Cost Optimization + +Select and tune triggers to balance latency requirements with cost. Optimize streaming job costs through trigger tuning, cluster right-sizing, multi-stream clusters, storage optimization, and scheduled execution patterns. + +## Quick Start + +```python +# Cost-optimized: Scheduled streaming instead of continuous +df.writeStream \ + .format("delta") \ + .option("checkpointLocation", "/checkpoints/stream") \ + .trigger(availableNow=True) \ # Process all, then stop + .start("/delta/target") + +# Schedule via Databricks Jobs: Every 15 minutes +# Cost: ~$20/day for 100 tables on 8-core cluster +``` + +## Trigger Types + +### ProcessingTime Trigger + +Process at fixed intervals: + +```python +# Process every 30 seconds +.trigger(processingTime="30 seconds") + +# Process every 5 minutes +.trigger(processingTime="5 minutes") + +# Latency: Trigger interval + processing time +# Cost: Continuous cluster running +``` + +### AvailableNow Trigger + +Process all available data, then stop: + +```python +# Process all available data, then stop +.trigger(availableNow=True) + +# Schedule via Databricks Jobs: +# - Every 15 minutes: Near real-time +# - Every 4 hours: Batch-style + +# Latency: Schedule interval + processing time +# Cost: Cluster runs only during processing +``` + +### Real-Time Mode (RTM) + +Sub-second latency with Photon: + +```python +# Real-Time Mode (Databricks 13.3+) +.trigger(realTime=True) + +# Requirements: +# - Photon enabled +# - Fixed-size cluster (no autoscaling) +# - Latency: < 800ms + +# Cost: Continuous cluster with Photon +``` + +## Trigger Selection Guide + +| Latency Requirement | Trigger | Cost | Use Case | +|---------------------|---------|------|----------| +| < 800ms | RTM | $$$ | Real-time analytics, alerts | +| 1-30 seconds | processingTime | $$ | Near real-time dashboards | +| 15-60 minutes | availableNow (scheduled) | $ | Batch-style SLA | +| > 1 hour | availableNow (scheduled) | $ | ETL pipelines | + +## Trigger Interval Calculation + +### Rule of Thumb: SLA / 3 + +```python +# Calculate trigger interval from SLA +business_sla_minutes = 60 # 1 hour SLA +trigger_interval_minutes = business_sla_minutes / 3 # 20 minutes + +.trigger(processingTime=f"{trigger_interval_minutes} minutes") + +# Why /3? +# - Processing time buffer +# - Recovery time buffer +# - Safety margin +``` + +### Example Calculations + +```python +# Example 1: 1 hour SLA +sla = 60 # minutes +trigger = sla / 3 # 20 minutes +.trigger(processingTime="20 minutes") + +# Example 2: 15 minute SLA +sla = 15 # minutes +trigger = sla / 3 # 5 minutes +.trigger(processingTime="5 minutes") + +# Example 3: Real-time requirement +.trigger(realTime=True) # < 800ms +``` + +## Cost Optimization Strategies + +### Strategy 1: Trigger Interval Tuning + +Balance latency and cost: + +```python +# Shorter interval = higher cost +.trigger(processingTime="5 seconds") # Expensive - continuous processing + +# Longer interval = lower cost +.trigger(processingTime="5 minutes") # Cheaper - less frequent processing + +# Use availableNow for batch-style (cheapest) +.trigger(availableNow=True) # Process backlog, then stop + +# Rule of thumb: SLA / 3 +# Example: 1 hour SLA → 20 minute trigger +``` + +### Strategy 2: Scheduled vs Continuous + +Choose execution pattern based on SLA: + +| Pattern | Cost | Latency | Use Case | +|---------|------|---------|----------| +| Continuous | $$$ | < 1 minute | Real-time requirements | +| 15-min schedule | $$ | 15-30 minutes | Near real-time | +| 4-hour schedule | $ | 4-5 hours | Batch-style SLA | + +```python +# Continuous (expensive) +.trigger(processingTime="30 seconds") + +# Scheduled (cost-effective) +.trigger(availableNow=True) # Schedule via Jobs: Every 15 minutes + +# Batch-style (cheapest) +.trigger(availableNow=True) # Schedule via Jobs: Every 4 hours +``` + +### Strategy 3: Cluster Right-Sizing + +Right-size clusters based on workload: + +```python +# Don't oversize: +# - Monitor CPU utilization (target 60-80%) +# - Check for idle time +# - Use fixed-size clusters (no autoscaling for streaming) + +# Scale test approach: +# 1. Start small +# 2. Monitor lag (max offsets behind latest) +# 3. Scale up if falling behind +# 4. Right-size based on steady state +``` + +### Strategy 4: Multi-Stream Clusters + +Run multiple streams on one cluster: + +```python +# Run multiple streams on one cluster +# Tested: 100 streams on 8-core single-node cluster +# Cost: ~$20/day for 100 tables + +# Example: Multiple streams on same cluster +stream1.writeStream.option("checkpointLocation", "/checkpoints/stream1").start() +stream2.writeStream.option("checkpointLocation", "/checkpoints/stream2").start() +stream3.writeStream.option("checkpointLocation", "/checkpoints/stream3").start() +# ... up to 100+ streams + +# Monitor: CPU/memory per stream +# Scale cluster if aggregate utilization > 80% +``` + +### Strategy 5: Storage Optimization + +Reduce storage costs: + +```sql +-- VACUUM old files +VACUUM table RETAIN 24 HOURS; + +-- Enable auto-optimize to reduce small files +ALTER TABLE table SET TBLPROPERTIES ( + 'delta.autoOptimize.optimizeWrite' = true, + 'delta.autoOptimize.autoCompact' = true +); + +-- Archive old data to cheaper storage +-- Use data retention policies +``` + +## Cost Formula + +``` +Daily Cost = + (Cluster DBU/hour × Hours running) + + (Storage GB × Storage rate) + + (Network egress if applicable) + +Optimization levers: +- Reduce hours running (scheduled triggers) +- Reduce cluster size (right-sizing) +- Reduce storage (VACUUM, compression) +- Reduce network egress (co-locate compute and storage) +``` + +## Common Patterns + +### Pattern 1: Cost-Optimized Scheduled Streaming + +Convert continuous to scheduled: + +```python +# Before: Continuous (expensive) +df.writeStream \ + .trigger(processingTime="30 seconds") \ + .start() + +# After: Scheduled (cost-effective) +df.writeStream \ + .trigger(availableNow=True) \ # Process all, then stop + .start() + +# Schedule via Databricks Jobs: +# - Every 15 minutes: Near real-time +# - Every 4 hours: Batch-style +# Same code, different schedule +``` + +### Pattern 2: Multi-Stream Cluster + +Optimize cluster utilization: + +```python +# Run multiple streams on one cluster +def start_all_streams(): + streams = [] + + # Start multiple streams + for i in range(100): + stream = (spark + .readStream + .table(f"source_{i}") + .writeStream + .format("delta") + .option("checkpointLocation", f"/checkpoints/stream_{i}") + .trigger(availableNow=True) + .start(f"/delta/target_{i}") + ) + streams.append(stream) + + return streams + +# Monitor aggregate CPU/memory +# Scale cluster if needed +``` + +### Pattern 3: RTM for Sub-Second Latency + +Use RTM for real-time requirements: + +```python +# Real-Time Mode for sub-second latency +df.writeStream \ + .format("kafka") + .option("topic", "output") + .trigger(realTime=True) \ + .start() + +# Required configurations: +spark.conf.set("spark.databricks.photon.enabled", "true") +spark.conf.set("spark.sql.streaming.stateStore.providerClass", + "com.databricks.sql.streaming.state.RocksDBStateProvider") + +# Latency: < 800ms +# Cost: Continuous cluster with Photon +``` + +## Real-Time Mode (RTM) Configuration + +### Enable RTM + +```python +# Enable Real-Time Mode +.trigger(realTime=True) + +# Required configurations: +spark.conf.set("spark.databricks.photon.enabled", "true") +spark.conf.set("spark.sql.streaming.stateStore.providerClass", + "com.databricks.sql.streaming.state.RocksDBStateProvider") + +# Cluster requirements: +# - Fixed-size cluster (no autoscaling) +# - Photon enabled +# - Driver: Minimum 4 cores +``` + +### RTM Use Cases + +```python +# Good for RTM: +# - Sub-second latency requirements +# - Simple transformations +# - Stateless operations +# - Kafka-to-Kafka pipelines + +# Not recommended for RTM: +# - Stateful operations (aggregations, joins) +# - Complex transformations +# - Large batch sizes +``` + +## Performance Considerations + +### Batch Duration vs Trigger Interval + +```python +# Batch duration should be < trigger interval +# Example: +trigger_interval = 30 # seconds +batch_duration = 10 # seconds + +# Healthy: batch_duration < trigger_interval +# Unhealthy: batch_duration >= trigger_interval + +# Monitor in Spark UI: +# - Batch duration +# - Trigger interval +# - Alert if batch duration >= trigger interval +``` + +### Trigger Interval Tuning + +```python +# Start conservative, optimize based on monitoring +# Step 1: Start with SLA / 3 +trigger_interval = business_sla / 3 + +# Step 2: Monitor batch duration +# If batch duration < trigger_interval / 2: Can increase trigger +# If batch duration >= trigger_interval: Decrease trigger + +# Step 3: Optimize for cost vs latency +# Increase trigger interval to reduce cost +# Decrease trigger interval to reduce latency +``` + +## Cost Monitoring + +### Track Per-Stream Costs + +```python +# Tag jobs with stream name +job_tags = { + "stream_name": "orders_stream", + "environment": "prod", + "cost_center": "analytics" +} + +# Use DBU consumption metrics +# Monitor by workspace/cluster +# Track cost per stream over time +``` + +### Monitor Cluster Utilization + +```python +# Check CPU utilization +# Target: 60-80% utilization +# Below 60%: Consider downsizing +# Above 80%: Consider upsizing + +# Check memory utilization +# Monitor for OOM errors +# Adjust cluster size accordingly +``` + +## Latency vs Cost Trade-offs + +### Continuous Processing + +```python +# High cost, low latency +.trigger(processingTime="30 seconds") + +# Cost: Continuous cluster running +# Latency: 30 seconds + processing time +# Use when: Real-time requirements +``` + +### Scheduled Processing + +```python +# Lower cost, higher latency +.trigger(availableNow=True) # Schedule: Every 15 minutes + +# Cost: Cluster runs only during processing +# Latency: Schedule interval + processing time +# Use when: Batch-style SLA acceptable +``` + +### Real-Time Mode + +```python +# Highest cost, lowest latency +.trigger(realTime=True) + +# Cost: Continuous cluster with Photon +# Latency: < 800ms +# Use when: Sub-second latency required +``` + +## Common Issues + +| Issue | Cause | Solution | +|-------|-------|----------| +| **High latency** | Trigger interval too long | Decrease trigger interval or use RTM | +| **High cost** | Continuous processing | Use scheduled (availableNow) | +| **Batch duration > trigger** | Processing too slow | Optimize processing or increase trigger | +| **RTM not working** | Photon not enabled | Enable Photon and configure cluster | + +## Quick Wins + +1. **Change from continuous to 15-minute schedule** - Significant cost reduction +2. **Run multiple streams per cluster** - Better cluster utilization +3. **Enable auto-optimize** - Reduce storage costs +4. **Use Spot instances** - For non-critical streams (with caution) +5. **Archive old data** - Move to cheaper storage tiers + +## Trade-offs + +| Cost Reduction | Impact | Mitigation | +|----------------|--------|------------| +| Longer trigger | Higher latency | Acceptable if SLA allows | +| Smaller cluster | May fall behind | Monitor lag; scale if needed | +| Aggressive VACUUM | Less time travel | Balance retention vs cost | +| Spot instances | Possible interruptions | Use for non-critical streams | +| Scheduled vs continuous | Higher latency | Match to business SLA | + +## Production Best Practices + +### Match Trigger to SLA + +```python +# Calculate trigger from business SLA +def calculate_trigger_interval(sla_minutes): + """Calculate optimal trigger interval""" + return max(30, sla_minutes / 3) # Minimum 30 seconds + +trigger_interval = calculate_trigger_interval(business_sla_minutes) +.trigger(processingTime=f"{trigger_interval} seconds") +``` + +### Cluster Configuration + +```python +# Fixed-size cluster (no autoscaling for streaming) +cluster_config = { + "num_workers": 4, + "node_type_id": "i3.xlarge", + "autotermination_minutes": 60, # Terminate if idle + "enable_elastic_disk": True # Reduce storage costs +} +``` + +### Storage Management + +```sql +-- Enable auto-optimize +ALTER TABLE table SET TBLPROPERTIES ( + 'delta.autoOptimize.optimizeWrite' = true, + 'delta.autoOptimize.autoCompact' = true +); + +-- Periodic VACUUM +VACUUM table RETAIN 7 DAYS; -- Balance retention vs cost + +-- Archive old partitions +-- Move to cheaper storage tier +``` + +## Production Checklist + +- [ ] Trigger type selected based on latency requirements +- [ ] Trigger interval calculated from SLA (SLA / 3) +- [ ] Batch duration monitored (< trigger interval) +- [ ] Cluster right-sized (60-80% utilization) +- [ ] Multiple streams per cluster (if applicable) +- [ ] Scheduled execution (if SLA allows) +- [ ] RTM configured if sub-second latency required +- [ ] Auto-optimize enabled +- [ ] Storage costs monitored +- [ ] Cost per stream tracked + +## Related Skills + +- `kafka-streaming` - RTM configuration for Kafka pipelines +- `checkpoint-best-practices` - Checkpoint management diff --git a/.claude/skills/synthetic-data-generation/SKILL.md b/.claude/skills/databricks-synthetic-data-generation/SKILL.md similarity index 98% rename from .claude/skills/synthetic-data-generation/SKILL.md rename to .claude/skills/databricks-synthetic-data-generation/SKILL.md index 6d029941..ce2a17cf 100644 --- a/.claude/skills/synthetic-data-generation/SKILL.md +++ b/.claude/skills/databricks-synthetic-data-generation/SKILL.md @@ -1,5 +1,5 @@ --- -name: synthetic-data-generation +name: databricks-synthetic-data-generation description: "Generate realistic synthetic data using Faker and Spark, with non-linear distributions, integrity constraints, and save to Databricks. Use when creating test data, demo datasets, or synthetic tables." --- @@ -652,3 +652,9 @@ This returns schema, row counts, and column statistics to confirm the data was w 14. **Always use files**: Write to local file, execute, edit if error, re-execute 15. **Context reuse**: Pass `cluster_id` and `context_id` for faster iterations 16. **Libraries**: Install `faker` and `holidays` first; most others are pre-installed + +## Related Skills + +- **[databricks-spark-declarative-pipelines](../databricks-spark-declarative-pipelines/SKILL.md)** - for building bronze/silver/gold pipelines on top of generated data +- **[databricks-aibi-dashboards](../databricks-aibi-dashboards/SKILL.md)** - for visualizing the generated data in dashboards +- **[databricks-unity-catalog](../databricks-unity-catalog/SKILL.md)** - for managing catalogs, schemas, and volumes where data is stored diff --git a/.claude/skills/databricks-unity-catalog/SKILL.md b/.claude/skills/databricks-unity-catalog/SKILL.md index b8dbbc20..9b77fed9 100644 --- a/.claude/skills/databricks-unity-catalog/SKILL.md +++ b/.claude/skills/databricks-unity-catalog/SKILL.md @@ -104,6 +104,13 @@ mcp__databricks__execute_sql( 3. **Grant minimal access** - System tables contain sensitive metadata 4. **Schedule reports** - Create scheduled queries for regular monitoring +## Related Skills + +- **[databricks-spark-declarative-pipelines](../databricks-spark-declarative-pipelines/SKILL.md)** - for pipelines that write to Unity Catalog tables +- **[databricks-jobs](../databricks-jobs/SKILL.md)** - for job execution data visible in system tables +- **[databricks-synthetic-data-generation](../databricks-synthetic-data-generation/SKILL.md)** - for generating data stored in Unity Catalog Volumes +- **[databricks-aibi-dashboards](../databricks-aibi-dashboards/SKILL.md)** - for building dashboards on top of Unity Catalog data + ## Resources - [Unity Catalog System Tables](https://docs.databricks.com/administration-guide/system-tables/) diff --git a/.claude/skills/unstructured-pdf-generation/SKILL.md b/.claude/skills/databricks-unstructured-pdf-generation/SKILL.md similarity index 91% rename from .claude/skills/unstructured-pdf-generation/SKILL.md rename to .claude/skills/databricks-unstructured-pdf-generation/SKILL.md index 1c5a5a4f..7666f21b 100644 --- a/.claude/skills/unstructured-pdf-generation/SKILL.md +++ b/.claude/skills/databricks-unstructured-pdf-generation/SKILL.md @@ -1,5 +1,5 @@ --- -name: unstructured-pdf-generation +name: databricks-unstructured-pdf-generation description: "Generate synthetic PDF documents for RAG and unstructured data use cases. Use when creating test PDFs, demo documents, or evaluation datasets for retrieval systems." --- @@ -185,3 +185,10 @@ AZURE_OPENAI_DEPLOYMENT=gpt-4o | **"Volume does not exist"** | The tool creates volumes automatically; ensure you have CREATE VOLUME permission | | **"PDF generation timeout"** | Reduce `count` or check LLM endpoint availability | | **Low quality content** | Provide more detailed `description` with specific topics and document types | + +## Related Skills + +- **[databricks-agent-bricks](../databricks-agent-bricks/SKILL.md)** - Create Knowledge Assistants that ingest the generated PDFs +- **[databricks-vector-search](../databricks-vector-search/SKILL.md)** - Index generated documents for semantic search and RAG +- **[databricks-synthetic-data-generation](../databricks-synthetic-data-generation/SKILL.md)** - Generate structured tabular data (complement to unstructured PDFs) +- **[databricks-mlflow-evaluation](../databricks-mlflow-evaluation/SKILL.md)** - Evaluate RAG systems using the generated question/guideline pairs diff --git a/.claude/skills/databricks-vector-search/SKILL.md b/.claude/skills/databricks-vector-search/SKILL.md new file mode 100644 index 00000000..276cab37 --- /dev/null +++ b/.claude/skills/databricks-vector-search/SKILL.md @@ -0,0 +1,357 @@ +--- +name: databricks-vector-search +description: "Patterns for Databricks Vector Search: create endpoints and indexes, query with filters, manage embeddings. Use when building RAG applications, semantic search, or similarity matching. Covers both storage-optimized and standard endpoints." +--- + +# Databricks Vector Search + +Patterns for creating, managing, and querying vector search indexes for RAG and semantic search applications. + +## When to Use + +Use this skill when: +- Building RAG (Retrieval-Augmented Generation) applications +- Implementing semantic search or similarity matching +- Creating vector indexes from Delta tables +- Choosing between storage-optimized and standard endpoints +- Querying vector indexes with filters + +## Overview + +Databricks Vector Search provides managed vector similarity search with automatic embedding generation and Delta Lake integration. + +| Component | Description | +|-----------|-------------| +| **Endpoint** | Compute resource hosting indexes (Standard or Storage-Optimized) | +| **Index** | Vector data structure for similarity search | +| **Delta Sync** | Auto-syncs with source Delta table | +| **Direct Access** | Manual CRUD operations on vectors | + +## Endpoint Types + +| Type | Latency | Capacity | Cost | Best For | +|------|---------|----------|------|----------| +| **Standard** | ~50-100ms | 320M vectors (768 dim) | Higher | Real-time, low-latency | +| **Storage-Optimized** | ~250ms | 1B+ vectors (768 dim) | 7x lower | Large-scale, cost-sensitive | + +## Index Types + +| Type | Embeddings | Sync | Use Case | +|------|------------|------|----------| +| **Delta Sync (managed)** | Databricks computes | Auto from Delta | Easiest setup | +| **Delta Sync (self-managed)** | You provide | Auto from Delta | Custom embeddings | +| **Direct Access** | You provide | Manual CRUD | Real-time updates | + +## Quick Start + +### Create Endpoint + +```python +from databricks.sdk import WorkspaceClient + +w = WorkspaceClient() + +# Create a standard endpoint +endpoint = w.vector_search_endpoints.create_endpoint( + name="my-vs-endpoint", + endpoint_type="STANDARD" # or "STORAGE_OPTIMIZED" +) +# Note: Endpoint creation is asynchronous; check status with get_endpoint() +``` + +### Create Delta Sync Index (Managed Embeddings) + +```python +# Source table must have: primary key column + text column +index = w.vector_search_indexes.create_index( + name="catalog.schema.my_index", + endpoint_name="my-vs-endpoint", + primary_key="id", + index_type="DELTA_SYNC", + delta_sync_index_spec={ + "source_table": "catalog.schema.documents", + "embedding_source_columns": [ + { + "name": "content", # Text column to embed + "embedding_model_endpoint_name": "databricks-gte-large-en" + } + ], + "pipeline_type": "TRIGGERED" # or "CONTINUOUS" + } +) +``` + +### Query Index + +```python +results = w.vector_search_indexes.query_index( + index_name="catalog.schema.my_index", + columns=["id", "content", "metadata"], + query_text="What is machine learning?", + num_results=5 +) + +for doc in results.result.data_array: + score = doc[-1] # Similarity score is last column + print(f"Score: {score}, Content: {doc[1][:100]}...") +``` + +## Common Patterns + +### Create Storage-Optimized Endpoint + +```python +# For large-scale, cost-effective deployments +endpoint = w.vector_search_endpoints.create_endpoint( + name="my-storage-endpoint", + endpoint_type="STORAGE_OPTIMIZED" +) +``` + +### Delta Sync with Self-Managed Embeddings + +```python +# Source table must have: primary key + embedding vector column +index = w.vector_search_indexes.create_index( + name="catalog.schema.my_index", + endpoint_name="my-vs-endpoint", + primary_key="id", + index_type="DELTA_SYNC", + delta_sync_index_spec={ + "source_table": "catalog.schema.documents", + "embedding_vector_columns": [ + { + "name": "embedding", # Pre-computed embedding column + "embedding_dimension": 768 + } + ], + "pipeline_type": "TRIGGERED" + } +) +``` + +### Direct Access Index + +```python +import json + +# Create index for manual CRUD +index = w.vector_search_indexes.create_index( + name="catalog.schema.direct_index", + endpoint_name="my-vs-endpoint", + primary_key="id", + index_type="DIRECT_ACCESS", + direct_access_index_spec={ + "embedding_vector_columns": [ + {"name": "embedding", "embedding_dimension": 768} + ], + "schema_json": json.dumps({ + "id": "string", + "text": "string", + "embedding": "array", + "metadata": "string" + }) + } +) + +# Upsert data +w.vector_search_indexes.upsert_data_vector_index( + index_name="catalog.schema.direct_index", + inputs_json=json.dumps([ + {"id": "1", "text": "Hello", "embedding": [0.1, 0.2, ...], "metadata": "doc1"}, + {"id": "2", "text": "World", "embedding": [0.3, 0.4, ...], "metadata": "doc2"}, + ]) +) + +# Delete data +w.vector_search_indexes.delete_data_vector_index( + index_name="catalog.schema.direct_index", + primary_keys=["1", "2"] +) +``` + +### Query with Embedding Vector + +```python +# When you have pre-computed query embedding +results = w.vector_search_indexes.query_index( + index_name="catalog.schema.my_index", + columns=["id", "text"], + query_vector=[0.1, 0.2, 0.3, ...], # Your 768-dim vector + num_results=10 +) +``` + +### Hybrid Search (Semantic + Keyword) + +```python +# Combines vector similarity with keyword matching +results = w.vector_search_indexes.query_index( + index_name="catalog.schema.my_index", + columns=["id", "content"], + query_text="machine learning algorithms", + query_type="hybrid", # Enable hybrid search + num_results=10 +) +``` + +## Filtering + +### Standard Endpoint Filters (Dictionary) + +```python +# filters_json uses dictionary format +results = w.vector_search_indexes.query_index( + index_name="catalog.schema.my_index", + columns=["id", "content"], + query_text="machine learning", + num_results=10, + filters_json='{"category": "ai", "status": ["active", "pending"]}' +) +``` + +### Storage-Optimized Filters (SQL-like) + +```python +# filter_string uses SQL-like syntax +results = w.vector_search_indexes.query_index( + index_name="catalog.schema.my_index", + columns=["id", "content"], + query_text="machine learning", + num_results=10, + filter_string="category = 'ai' AND status IN ('active', 'pending')" +) + +# More filter examples +filter_string="price > 100 AND price < 500" +filter_string="department LIKE 'eng%'" +filter_string="created_at >= '2024-01-01'" +``` + +### Trigger Index Sync + +```python +# For TRIGGERED pipeline type, manually sync +w.vector_search_indexes.sync_index( + index_name="catalog.schema.my_index" +) +``` + +### Scan All Index Entries + +```python +# Retrieve all vectors (for debugging/export) +scan_result = w.vector_search_indexes.scan_index( + index_name="catalog.schema.my_index", + num_results=100 +) +``` + +## Reference Files + +- [index-types.md](index-types.md) - Detailed comparison of index types and creation patterns + +## CLI Quick Reference + +```bash +# List endpoints +databricks vector-search endpoints list + +# Create endpoint +databricks vector-search endpoints create \ + --name my-endpoint \ + --endpoint-type STANDARD + +# List indexes on endpoint +databricks vector-search indexes list-indexes \ + --endpoint-name my-endpoint + +# Get index status +databricks vector-search indexes get-index \ + --index-name catalog.schema.my_index + +# Sync index (for TRIGGERED) +databricks vector-search indexes sync-index \ + --index-name catalog.schema.my_index + +# Delete index +databricks vector-search indexes delete-index \ + --index-name catalog.schema.my_index +``` + +## Common Issues + +| Issue | Solution | +|-------|----------| +| **Index sync slow** | Use Storage-Optimized endpoints (20x faster indexing) | +| **Query latency high** | Use Standard endpoint for <100ms latency | +| **filters_json not working** | Storage-Optimized uses `filter_string` (SQL syntax) | +| **Embedding dimension mismatch** | Ensure query and index dimensions match | +| **Index not updating** | Check pipeline_type; use sync_index() for TRIGGERED | +| **Out of capacity** | Upgrade to Storage-Optimized (1B+ vectors) | + +## Embedding Models + +Databricks provides built-in embedding models: + +| Model | Dimensions | Use Case | +|-------|------------|----------| +| `databricks-gte-large-en` | 1024 | English text, high quality | +| `databricks-bge-large-en` | 1024 | English text, general | + +```python +# Use with managed embeddings +embedding_source_columns=[ + { + "name": "content", + "embedding_model_endpoint_name": "databricks-gte-large-en" + } +] +``` + +## MCP Tools + +The following MCP tools are available for managing Vector Search infrastructure. These are **management tools** for creating and configuring endpoints/indexes. For agent-runtime querying, use the Databricks managed Vector Search MCP server or `VectorSearchRetrieverTool`. + +### Endpoint Management + +| Tool | Description | +|------|-------------| +| `create_vs_endpoint` | Create a Vector Search endpoint (STANDARD or STORAGE_OPTIMIZED) | +| `get_vs_endpoint` | Get endpoint status and details | +| `list_vs_endpoints` | List all endpoints in the workspace | +| `delete_vs_endpoint` | Delete an endpoint (indexes must be deleted first) | + +### Index Management + +| Tool | Description | +|------|-------------| +| `create_vs_index` | Create a Delta Sync or Direct Access index | +| `get_vs_index` | Get index status and configuration | +| `list_vs_indexes` | List all indexes on an endpoint | +| `delete_vs_index` | Delete an index | +| `sync_vs_index` | Trigger sync for TRIGGERED pipeline indexes | + +### Query and Data + +| Tool | Description | +|------|-------------| +| `query_vs_index` | Query index with text, vector, or hybrid search (for testing) | +| `upsert_vs_data` | Upsert vectors into a Direct Access index | +| `delete_vs_data` | Delete vectors from a Direct Access index | +| `scan_vs_index` | Scan/export index entries (for debugging) | + +## Notes + +- **Storage-Optimized is newer** - Better for most use cases unless you need <100ms latency +- **Delta Sync recommended** - Easier than Direct Access for most scenarios +- **Hybrid search** - Available for both Delta Sync and Direct Access indexes +- **Management vs runtime** - MCP tools above handle lifecycle management; for agent tool-calling at runtime, use the Databricks managed Vector Search MCP server + +## Related Skills + +- **[databricks-model-serving](../databricks-model-serving/SKILL.md)** - Deploy agents that use VectorSearchRetrieverTool +- **[databricks-agent-bricks](../databricks-agent-bricks/SKILL.md)** - Knowledge Assistants use RAG over indexed documents +- **[databricks-unstructured-pdf-generation](../databricks-unstructured-pdf-generation/SKILL.md)** - Generate documents to index in Vector Search +- **[databricks-unity-catalog](../databricks-unity-catalog/SKILL.md)** - Manage the catalogs and tables that back Delta Sync indexes +- **[databricks-spark-declarative-pipelines](../databricks-spark-declarative-pipelines/SKILL.md)** - Build Delta tables used as Vector Search sources diff --git a/.claude/skills/databricks-vector-search/index-types.md b/.claude/skills/databricks-vector-search/index-types.md new file mode 100644 index 00000000..ebfc1c7e --- /dev/null +++ b/.claude/skills/databricks-vector-search/index-types.md @@ -0,0 +1,254 @@ +# Vector Search Index Types + +## Comparison Matrix + +| Feature | Delta Sync (Managed) | Delta Sync (Self-Managed) | Direct Access | +|---------|---------------------|---------------------------|---------------| +| **Embeddings** | Databricks computes | You provide | You provide | +| **Sync** | Auto from Delta | Auto from Delta | Manual CRUD | +| **Setup** | Easiest | Medium | Most control | +| **Source** | Delta table + text | Delta table + vectors | API calls | +| **Best for** | Quick start, RAG | Custom models | Real-time apps | + +## Delta Sync with Managed Embeddings + +Databricks automatically computes embeddings from your text column. + +### Requirements + +- Source Delta table with: + - Primary key column (unique identifier) + - Text column (content to embed) +- Embedding model endpoint (or use built-in) + +### Create Index + +```python +from databricks.sdk import WorkspaceClient + +w = WorkspaceClient() + +index = w.vector_search_indexes.create_index( + name="catalog.schema.docs_index", + endpoint_name="my-vs-endpoint", + primary_key="doc_id", + index_type="DELTA_SYNC", + delta_sync_index_spec={ + "source_table": "catalog.schema.documents", + "embedding_source_columns": [ + { + "name": "content", + "embedding_model_endpoint_name": "databricks-gte-large-en" + } + ], + "pipeline_type": "TRIGGERED", # or "CONTINUOUS" + "columns_to_sync": ["doc_id", "content", "title", "category"] + } +) +``` + +### Pipeline Types + +| Type | Behavior | Cost | Use Case | +|------|----------|------|----------| +| `TRIGGERED` | Manual sync via API | Lower | Batch updates | +| `CONTINUOUS` | Auto-sync on changes | Higher | Real-time sync | + +### Source Table Example + +```sql +CREATE TABLE catalog.schema.documents ( + doc_id STRING, + title STRING, + content STRING, -- Text to embed + category STRING, + created_at TIMESTAMP +); +``` + +## Delta Sync with Self-Managed Embeddings + +You pre-compute embeddings and store them in the source table. + +### Requirements + +- Source Delta table with: + - Primary key column + - Embedding vector column (array of floats) + +### Create Index + +```python +index = w.vector_search_indexes.create_index( + name="catalog.schema.custom_index", + endpoint_name="my-vs-endpoint", + primary_key="id", + index_type="DELTA_SYNC", + delta_sync_index_spec={ + "source_table": "catalog.schema.embedded_docs", + "embedding_vector_columns": [ + { + "name": "embedding", + "embedding_dimension": 768 + } + ], + "pipeline_type": "TRIGGERED" + } +) +``` + +### Compute Embeddings + +```python +from databricks.sdk import WorkspaceClient +import pandas as pd + +w = WorkspaceClient() + +def get_embeddings(texts: list[str]) -> list[list[float]]: + """Call embedding endpoint for texts.""" + response = w.serving_endpoints.query( + name="databricks-gte-large-en", + input=texts + ) + return [item.embedding for item in response.data] + +# Add embeddings to your data +df = spark.table("catalog.schema.documents").toPandas() +df["embedding"] = get_embeddings(df["content"].tolist()) + +# Write back to Delta +spark.createDataFrame(df).write.mode("overwrite").saveAsTable( + "catalog.schema.embedded_docs" +) +``` + +### Source Table Example + +```sql +CREATE TABLE catalog.schema.embedded_docs ( + id STRING, + content STRING, + embedding ARRAY, -- Pre-computed embedding + metadata STRING +); +``` + +## Direct Access Index + +Full control over vector data via CRUD API. No Delta table sync. + +### Requirements + +- Define schema upfront +- Manage upsert/delete operations yourself + +### Create Index + +```python +import json + +index = w.vector_search_indexes.create_index( + name="catalog.schema.realtime_index", + endpoint_name="my-vs-endpoint", + primary_key="id", + index_type="DIRECT_ACCESS", + direct_access_index_spec={ + "embedding_vector_columns": [ + {"name": "embedding", "embedding_dimension": 768} + ], + "schema_json": json.dumps({ + "id": "string", + "text": "string", + "embedding": "array", + "category": "string", + "score": "float" + }) + } +) +``` + +### Upsert Data + +```python +import json + +# Insert or update vectors +w.vector_search_indexes.upsert_data_vector_index( + index_name="catalog.schema.realtime_index", + inputs_json=json.dumps([ + { + "id": "doc-001", + "text": "Machine learning basics", + "embedding": [0.1, 0.2, 0.3, ...], # 768 floats + "category": "ml", + "score": 0.95 + }, + { + "id": "doc-002", + "text": "Deep learning overview", + "embedding": [0.4, 0.5, 0.6, ...], + "category": "dl", + "score": 0.88 + } + ]) +) +``` + +### Delete Data + +```python +w.vector_search_indexes.delete_data_vector_index( + index_name="catalog.schema.realtime_index", + primary_keys=["doc-001", "doc-002"] +) +``` + +### Attach Embedding Model (Optional) + +For Direct Access with text queries: + +```python +# Create index with embedding model for query-time embedding +index = w.vector_search_indexes.create_index( + name="catalog.schema.hybrid_index", + endpoint_name="my-vs-endpoint", + primary_key="id", + index_type="DIRECT_ACCESS", + direct_access_index_spec={ + "embedding_vector_columns": [ + {"name": "embedding", "embedding_dimension": 768} + ], + "embedding_model_endpoint_name": "databricks-gte-large-en", # For query_text + "schema_json": json.dumps({...}) + } +) +``` + +## Choosing the Right Type + +``` +Start here: +│ +├─ Do you have pre-computed embeddings? +│ ├─ Yes → Do you want auto-sync from Delta? +│ │ ├─ Yes → Delta Sync (Self-Managed) +│ │ └─ No → Direct Access +│ │ +│ └─ No → Delta Sync (Managed Embeddings) +│ +└─ Do you need real-time updates (<1 sec)? + ├─ Yes → Direct Access + └─ No → Delta Sync (any type) +``` + +## Endpoint Selection + +After choosing index type, choose endpoint: + +| Scenario | Endpoint Type | +|----------|---------------| +| Need <100ms latency | Standard | +| >100M vectors | Storage-Optimized | +| Cost-sensitive | Storage-Optimized | +| Default choice | Storage-Optimized | diff --git a/.claude/skills/databricks-zerobus-ingest/1-setup-and-authentication.md b/.claude/skills/databricks-zerobus-ingest/1-setup-and-authentication.md new file mode 100644 index 00000000..10b07f67 --- /dev/null +++ b/.claude/skills/databricks-zerobus-ingest/1-setup-and-authentication.md @@ -0,0 +1,199 @@ +# Setup and Authentication + +Complete setup guide for Zerobus Ingest: endpoint configuration, service principal creation, table preparation, SDK installation, and firewall requirements. + +--- + +## 1. Determine Your Server Endpoint + +The Zerobus server endpoint format depends on your cloud provider: + +| Cloud | Server Endpoint Format | Workspace URL Format | +|-------|------------------------|----------------------| +| **AWS** | `.zerobus..cloud.databricks.com` | `https://.cloud.databricks.com` | +| **Azure** | `.zerobus..azuredatabricks.net` | `https://.azuredatabricks.net` | + +**Example (AWS):** +``` +Server endpoint: 1234567890123456.zerobus.us-west-2.cloud.databricks.com +Workspace URL: https://dbc-a1b2c3d4-e5f6.cloud.databricks.com +``` + +**Finding your workspace ID:** Extract the numeric ID from your workspace URL or workspace settings page. It is the first segment of the server endpoint. + +--- + +## 2. Create the Target Table + +Zerobus does **not** create or alter tables. You must pre-create your target table as a **managed Delta table** in Unity Catalog: + +```sql +CREATE TABLE catalog.schema.my_events ( + event_id STRING, + device_name STRING, + temp INT, + humidity LONG, + event_time TIMESTAMP +); +``` + +**Constraints:** +- Must be a **managed** Delta table (no external storage) +- Table names limited to ASCII letters, digits, and underscores +- Maximum 2000 columns +- Table must be in a [supported region](#supported-regions) + +--- + +## 3. Create a Service Principal + +Zerobus authenticates via OAuth2 service principals (M2M). Create one via the Databricks UI or CLI: + +### Via UI +1. Go to **Settings > Identity and Access > Service principals** +2. Click **Add service principal** +3. Generate an OAuth secret: note the **client ID** and **client secret** + +### Via Databricks CLI +```bash +databricks service-principals create --display-name "zerobus-producer" +``` + +### Grant Table Permissions + +The service principal needs catalog, schema, and table access: + +```sql +-- Grant catalog access +GRANT USE CATALOG ON CATALOG my_catalog TO ``; + +-- Grant schema access +GRANT USE SCHEMA ON SCHEMA my_catalog.my_schema TO ``; + +-- Grant table write access +GRANT MODIFY, SELECT ON TABLE my_catalog.my_schema.my_events TO ``; +``` + +**Tip:** For broader access (e.g., writing to multiple tables in a schema), grant `MODIFY` and `SELECT` at the schema level instead. + +--- + +## 4. Install the SDK + +### Python (3.9+) + +```bash +pip install databricks-zerobus-ingest-sdk +``` + +Or with a virtual environment: +```bash +uv pip install databricks-zerobus-ingest-sdk +``` + +### Java (8+) + +Maven: +```xml + + com.databricks + zerobus-ingest-sdk + 0.1.0 + +``` + +Gradle: +```groovy +implementation 'com.databricks:zerobus-ingest-sdk:0.1.0' +``` + +### Go (1.21+) + +```bash +go get github.com/databricks/zerobus-sdk-go +``` + +### TypeScript / Node.js (16+) + +```bash +npm install @databricks/zerobus-ingest-sdk +``` + +### Rust (1.70+) + +```bash +cargo add databricks-zerobus-ingest-sdk +cargo add tokio --features macros,rt-multi-thread +``` + +--- + +## 5. Configure Environment Variables + +Store credentials as environment variables rather than hardcoding them: + +```bash +export ZEROBUS_SERVER_ENDPOINT="1234567890123456.zerobus.us-west-2.cloud.databricks.com" +export DATABRICKS_WORKSPACE_URL="https://dbc-a1b2c3d4-e5f6.cloud.databricks.com" +export ZEROBUS_TABLE_NAME="my_catalog.my_schema.my_events" +export DATABRICKS_CLIENT_ID="" +export DATABRICKS_CLIENT_SECRET="" +``` + +--- + +## 6. Firewall Allowlisting + +If your client application sits behind a firewall, you must allowlist the Zerobus IP addresses for your region before testing connectivity. Contact your Databricks representative or consult the [Zerobus documentation](https://docs.databricks.com/aws/en/ingestion/zerobus-overview) for the current IP ranges. + +--- + +## Supported Regions + +Workspace and target tables must reside in a supported region for your cloud provider. + +### AWS + +| Region Code | Location | +|-------------|----------| +| `us-east-1` | US East (N. Virginia) | +| `us-east-2` | US East (Ohio) | +| `us-west-2` | US West (Oregon) | +| `eu-central-1` | Europe (Frankfurt) | +| `eu-west-1` | Europe (Ireland) | +| `ap-southeast-1` | Asia Pacific (Singapore) | +| `ap-southeast-2` | Asia Pacific (Sydney) | +| `ap-northeast-1` | Asia Pacific (Tokyo) | +| `ca-central-1` | Canada (Central) | + +### Azure + +| Region Code | Location | +|-------------|----------| +| `canadacentral` | Canada Central | +| `westus` | West US | +| `eastus` | East US | +| `eastus2` | East US 2 | +| `centralus` | Central US | +| `northcentralus` | North Central US | +| `swedencentral` | Sweden Central | +| `westeurope` | West Europe | +| `northeurope` | North Europe | +| `australiaeast` | Australia East | +| `southeastasia` | Southeast Asia | + +--- + +## Verification Checklist + +Before writing your first record, confirm: + +``` +- [ ] Server endpoint matches your cloud provider and region +- [ ] Workspace URL is correct +- [ ] Target table exists as a managed Delta table +- [ ] Service principal has USE CATALOG, USE SCHEMA, MODIFY, SELECT grants +- [ ] SDK is installed for your target language +- [ ] Environment variables are set (or credentials are configured in code) +- [ ] Firewall allows outbound connections to the Zerobus endpoint (if applicable) +``` diff --git a/.claude/skills/databricks-zerobus-ingest/2-python-client.md b/.claude/skills/databricks-zerobus-ingest/2-python-client.md new file mode 100644 index 00000000..ac95cd4c --- /dev/null +++ b/.claude/skills/databricks-zerobus-ingest/2-python-client.md @@ -0,0 +1,323 @@ +# Python Client + +Python SDK patterns for Zerobus Ingest: synchronous and asynchronous APIs, JSON and Protobuf flows, and a reusable client class. + +--- + +## SDK Imports + +```python +# Synchronous API +from zerobus.sdk.sync import ZerobusSdk + +# Asynchronous API (equivalent capabilities) +from zerobus.sdk.asyncio import ZerobusSdk as AsyncZerobusSdk + +# Shared types (used by both sync and async) +from zerobus.sdk.shared import ( + RecordType, + IngestRecordResponse, + StreamConfigurationOptions, + TableProperties, +) +``` + +--- + + + +--- + +## Protobuf Ingestion + +You must always use Protobuf +For type-safe production workloads, use Protobuf. First generate and compile your `.proto` (see [4-protobuf-schema.md](4-protobuf-schema.md)), then: + +```python +import os +from zerobus.sdk.sync import ZerobusSdk +from zerobus.sdk.shared import RecordType, StreamConfigurationOptions, TableProperties + +# Import your compiled protobuf module +import record_pb2 + +server_endpoint = os.environ["ZEROBUS_SERVER_ENDPOINT"] +workspace_url = os.environ["DATABRICKS_WORKSPACE_URL"] +table_name = os.environ["ZEROBUS_TABLE_NAME"] +client_id = os.environ["DATABRICKS_CLIENT_ID"] +client_secret = os.environ["DATABRICKS_CLIENT_SECRET"] + +sdk = ZerobusSdk(server_endpoint, workspace_url) + +options = StreamConfigurationOptions(record_type=RecordType.PROTO) +table_props = TableProperties(table_name, record_pb2.AirQuality.DESCRIPTOR) + +stream = sdk.create_stream(client_id, client_secret, table_props, options) + +try: + for i in range(100): + record = record_pb2.AirQuality( + device_name=f"sensor-{i}", + temp=22, + humidity=55, + ) + ack = stream.ingest_record(record) + ack.wait_for_ack() +finally: + stream.close() +``` + +--- + +## ACK Callback (Asynchronous Acknowledgment) + +Instead of blocking on each ACK, register a callback for background durability confirmation: + +```python +from zerobus.sdk.shared import IngestRecordResponse, StreamConfigurationOptions, RecordType + +def on_ack(response: IngestRecordResponse) -> None: + print(f"Durable up to offset: {response.durability_ack_up_to_offset}") + +options = StreamConfigurationOptions( + record_type=RecordType.JSON, + ack_callback=on_ack, +) + +# Create stream with callback +stream = sdk.create_stream(client_id, client_secret, table_props, options) + +try: + for i in range(1000): + record = {"device_name": f"sensor-{i}", "temp": 22, "humidity": 55} + stream.ingest_record(record) # Non-blocking, ACKs arrive via callback + stream.flush() # Ensure all buffered records are sent +finally: + stream.close() +``` + +--- + +## Reusable Client Class + +A production-ready wrapper with retry logic, reconnection, and both JSON and Protobuf support: + +```python +import os +import time +import logging +from typing import Optional, Callable + +from zerobus.sdk.sync import ZerobusSdk +from zerobus.sdk.shared import ( + RecordType, + IngestRecordResponse, + StreamConfigurationOptions, + TableProperties, +) + +logger = logging.getLogger(__name__) + + +class ZerobusClient: + """Reusable Zerobus Ingest client with retry and reconnection.""" + + def __init__( + self, + server_endpoint: str, + workspace_url: str, + table_name: str, + client_id: str, + client_secret: str, + record_type: RecordType = RecordType.JSON, + ack_callback: Optional[Callable[[IngestRecordResponse], None]] = None, + proto_descriptor=None, + ): + self.server_endpoint = server_endpoint + self.workspace_url = workspace_url + self.table_name = table_name + self.client_id = client_id + self.client_secret = client_secret + self.record_type = record_type + self.ack_callback = ack_callback + self.proto_descriptor = proto_descriptor + + self.sdk = ZerobusSdk(self.server_endpoint, self.workspace_url) + self.stream = None + + def init_stream(self) -> None: + """Open a new stream to the target table.""" + options = StreamConfigurationOptions( + record_type=self.record_type, + ack_callback=self.ack_callback, + ) + if self.record_type == RecordType.PROTO and self.proto_descriptor: + table_props = TableProperties(self.table_name, self.proto_descriptor) + else: + table_props = TableProperties(self.table_name) + + self.stream = self.sdk.create_stream( + self.client_id, self.client_secret, table_props, options + ) + logger.info("Zerobus stream initialized for %s", self.table_name) + + def ingest(self, payload, max_retries: int = 3) -> bool: + """Ingest a single record (dict for JSON, protobuf message for PROTO). + + Returns True on success, False after exhausting retries. + """ + for attempt in range(max_retries): + try: + if self.stream is None: + self.init_stream() + ack = self.stream.ingest_record(payload) + ack.wait_for_ack() + return True + except Exception as e: + err = str(e).lower() + logger.warning( + "Ingest attempt %d/%d failed: %s", attempt + 1, max_retries, e + ) + if "closed" in err or "connection" in err: + self.close() + self.init_stream() + if attempt < max_retries - 1: + time.sleep(2**attempt) # Exponential backoff: 1s, 2s, 4s + return False + + def flush(self) -> None: + """Flush buffered writes.""" + if self.stream: + self.stream.flush() + + def close(self) -> None: + """Close the stream and release resources.""" + if self.stream: + self.stream.close() + self.stream = None + + def __enter__(self): + self.init_stream() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.flush() + self.close() + return False +``` + +### Using the Client Class + +```python +# JSON flow with context manager +with ZerobusClient( + server_endpoint=os.environ["ZEROBUS_SERVER_ENDPOINT"], + workspace_url=os.environ["DATABRICKS_WORKSPACE_URL"], + table_name=os.environ["ZEROBUS_TABLE_NAME"], + client_id=os.environ["DATABRICKS_CLIENT_ID"], + client_secret=os.environ["DATABRICKS_CLIENT_SECRET"], + record_type=RecordType.JSON, +) as client: + for i in range(100): + client.ingest({"device_name": f"sensor-{i}", "temp": 22, "humidity": 55}) + +# Protobuf flow +import record_pb2 + +with ZerobusClient( + server_endpoint=os.environ["ZEROBUS_SERVER_ENDPOINT"], + workspace_url=os.environ["DATABRICKS_WORKSPACE_URL"], + table_name=os.environ["ZEROBUS_TABLE_NAME"], + client_id=os.environ["DATABRICKS_CLIENT_ID"], + client_secret=os.environ["DATABRICKS_CLIENT_SECRET"], + record_type=RecordType.PROTO, + proto_descriptor=record_pb2.AirQuality.DESCRIPTOR, +) as client: + for i in range(100): + record = record_pb2.AirQuality(device_name=f"sensor-{i}", temp=22, humidity=55) + client.ingest(record) +``` + +--- + +## Async Python API + +The SDK provides an equivalent async API for use with `asyncio`: + +```python +import asyncio +from zerobus.sdk.asyncio import ZerobusSdk as AsyncZerobusSdk +from zerobus.sdk.shared import RecordType, StreamConfigurationOptions, TableProperties + + +async def ingest_async(): + sdk = AsyncZerobusSdk(server_endpoint, workspace_url) + options = StreamConfigurationOptions(record_type=RecordType.JSON) + table_props = TableProperties(table_name) + + stream = await sdk.create_stream(client_id, client_secret, table_props, options) + + try: + for i in range(100): + record = {"device_name": f"sensor-{i}", "temp": 22, "humidity": 55} + ack = await stream.ingest_record(record) + await ack.wait_for_ack() + finally: + await stream.close() + + +asyncio.run(ingest_async()) +``` + +**Tip:** The sync and async APIs have equivalent capabilities. Choose based on your application architecture (FastAPI/aiohttp -> async; scripts/batch jobs -> sync). + +--- + +## Batch Pattern + +For higher throughput, send records without blocking on each ACK and flush at the end: + +```python +with ZerobusClient( + server_endpoint=os.environ["ZEROBUS_SERVER_ENDPOINT"], + workspace_url=os.environ["DATABRICKS_WORKSPACE_URL"], + table_name=os.environ["ZEROBUS_TABLE_NAME"], + client_id=os.environ["DATABRICKS_CLIENT_ID"], + client_secret=os.environ["DATABRICKS_CLIENT_SECRET"], + record_type=RecordType.JSON, + ack_callback=lambda resp: None, # Discard individual ACKs +) as client: + for i in range(10_000): + record = {"device_name": f"sensor-{i}", "temp": 22, "humidity": 55} + client.stream.ingest_record(record) # Non-blocking + # flush() and close() called automatically by context manager +``` diff --git a/.claude/skills/databricks-zerobus-ingest/3-multilanguage-clients.md b/.claude/skills/databricks-zerobus-ingest/3-multilanguage-clients.md new file mode 100644 index 00000000..217398c8 --- /dev/null +++ b/.claude/skills/databricks-zerobus-ingest/3-multilanguage-clients.md @@ -0,0 +1,314 @@ +# Multi-Language Clients + +Zerobus Ingest SDK examples for Java, Go, TypeScript/Node.js, and Rust. All languages follow the same core pattern: **SDK init -> create stream -> ingest records -> ACK -> flush -> close**. + +--- + +## Java (8+) + +### Installation + +Maven: +```xml + + com.databricks + zerobus-ingest-sdk + 0.1.0 + +``` + +### Protobuf Flow (Recommended) + +Java uses Protobuf by default. Generate and compile your `.proto` first (see [4-protobuf-schema.md](4-protobuf-schema.md)). + +```java +import com.databricks.zerobus.*; +import com.example.proto.Record.AirQuality; + +public class ZerobusProducer { + public static void main(String[] args) throws Exception { + String serverEndpoint = System.getenv("ZEROBUS_SERVER_ENDPOINT"); + String workspaceUrl = System.getenv("DATABRICKS_WORKSPACE_URL"); + String tableName = System.getenv("ZEROBUS_TABLE_NAME"); + String clientId = System.getenv("DATABRICKS_CLIENT_ID"); + String clientSecret = System.getenv("DATABRICKS_CLIENT_SECRET"); + + ZerobusSdk sdk = new ZerobusSdk(serverEndpoint, workspaceUrl); + + TableProperties tableProperties = new TableProperties<>( + tableName, + AirQuality.getDefaultInstance() + ); + + ZerobusStream stream = sdk.createStream( + tableProperties, clientId, clientSecret + ).join(); + + try { + for (int i = 0; i < 100; i++) { + AirQuality record = AirQuality.newBuilder() + .setDeviceName("sensor-" + i) + .setTemp(22) + .setHumidity(55) + .build(); + stream.ingestRecord(record).join(); + } + } finally { + stream.close(); + } + } +} +``` + +### Proto Generation for Java + +```bash +java -jar zerobus-ingest-sdk-0.1.0-jar-with-dependencies.jar \ + --uc-endpoint "https://dbc-a1b2c3d4-e5f6.cloud.databricks.com" \ + --client-id "$DATABRICKS_CLIENT_ID" \ + --client-secret "$DATABRICKS_CLIENT_SECRET" \ + --table "catalog.schema.table_name" \ + --output "record.proto" + +# Compile to Java +protoc --java_out=src/main/java record.proto +``` + +--- + +## Go (1.21+) + +### Installation + +```bash +go get github.com/databricks/zerobus-sdk-go +``` + +### JSON Flow + +```go +package main + +import ( + "fmt" + "log" + "os" + + zerobus "github.com/databricks/zerobus-go-sdk/sdk" +) + +func main() { + serverEndpoint := os.Getenv("ZEROBUS_SERVER_ENDPOINT") + workspaceURL := os.Getenv("DATABRICKS_WORKSPACE_URL") + tableName := os.Getenv("ZEROBUS_TABLE_NAME") + clientID := os.Getenv("DATABRICKS_CLIENT_ID") + clientSecret := os.Getenv("DATABRICKS_CLIENT_SECRET") + + sdk, err := zerobus.NewZerobusSdk(serverEndpoint, workspaceURL) + if err != nil { + log.Fatal(err) + } + defer sdk.Free() + + options := zerobus.DefaultStreamConfigurationOptions() + options.RecordType = zerobus.RecordTypeJson + + stream, err := sdk.CreateStream( + zerobus.TableProperties{TableName: tableName}, + clientID, clientSecret, options, + ) + if err != nil { + log.Fatal(err) + } + defer stream.Close() + + for i := 0; i < 100; i++ { + record := fmt.Sprintf( + `{"device_name": "sensor-%d", "temp": 22, "humidity": 55}`, i, + ) + ack, err := stream.IngestRecord(record) + if err != nil { + log.Printf("Ingest failed for record %d: %v", i, err) + continue + } + ack.Await() + } + + stream.Flush() +} +``` + +### Protobuf Flow + +```go +options := zerobus.DefaultStreamConfigurationOptions() +options.RecordType = zerobus.RecordTypeProto + +// Load compiled proto descriptor +tableProps := zerobus.TableProperties{ + TableName: tableName, + DescriptorProto: descriptorBytes, // compiled .proto descriptor +} + +stream, err := sdk.CreateStream(tableProps, clientID, clientSecret, options) +// ... ingest protobuf-serialized bytes ... +``` + +--- + +## TypeScript / Node.js (16+) + +### Installation + +```bash +npm install @databricks/zerobus-ingest-sdk +``` + +### JSON Flow + +```typescript +import { ZerobusSdk, RecordType } from "@databricks/zerobus-ingest-sdk"; + +const serverEndpoint = process.env.ZEROBUS_SERVER_ENDPOINT!; +const workspaceUrl = process.env.DATABRICKS_WORKSPACE_URL!; +const tableName = process.env.ZEROBUS_TABLE_NAME!; +const clientId = process.env.DATABRICKS_CLIENT_ID!; +const clientSecret = process.env.DATABRICKS_CLIENT_SECRET!; + +const sdk = new ZerobusSdk(serverEndpoint, workspaceUrl); + +const stream = await sdk.createStream( + { tableName }, + clientId, + clientSecret, + { recordType: RecordType.Json } +); + +try { + for (let i = 0; i < 100; i++) { + const record = { device_name: `sensor-${i}`, temp: 22, humidity: 55 }; + await stream.ingestRecord(record); + } + await stream.flush(); +} finally { + await stream.close(); +} +``` + +### With Error Handling + +```typescript +import { ZerobusSdk, RecordType } from "@databricks/zerobus-ingest-sdk"; + +async function ingestWithRetry( + stream: any, + record: Record, + maxRetries = 3 +): Promise { + for (let attempt = 0; attempt < maxRetries; attempt++) { + try { + await stream.ingestRecord(record); + return true; + } catch (error) { + console.warn(`Attempt ${attempt + 1}/${maxRetries} failed:`, error); + if (attempt < maxRetries - 1) { + await new Promise((r) => setTimeout(r, 2 ** attempt * 1000)); + } + } + } + return false; +} +``` + +--- + +## Rust (1.70+) + +### Installation + +```bash +cargo add databricks-zerobus-ingest-sdk +cargo add tokio --features macros,rt-multi-thread +``` + +### JSON Flow + +```rust +use databricks_zerobus_ingest_sdk::{ + RecordType, StreamConfigurationOptions, TableProperties, ZerobusSdk, +}; +use std::env; +use std::error::Error; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let server_endpoint = env::var("ZEROBUS_SERVER_ENDPOINT")?; + let workspace_url = env::var("DATABRICKS_WORKSPACE_URL")?; + let table_name = env::var("ZEROBUS_TABLE_NAME")?; + let client_id = env::var("DATABRICKS_CLIENT_ID")?; + let client_secret = env::var("DATABRICKS_CLIENT_SECRET")?; + + let table_properties = TableProperties { + table_name, + descriptor_proto: None, + }; + + let options = StreamConfigurationOptions { + record_type: RecordType::Json, + ..Default::default() + }; + + let sdk = ZerobusSdk::new(server_endpoint, workspace_url)?; + let mut stream = sdk + .create_stream(table_properties, client_id, client_secret, Some(options)) + .await?; + + for i in 0..100 { + let record = format!( + r#"{{"device_name": "sensor-{}", "temp": 22, "humidity": 55}}"#, + i + ); + let ack = stream.ingest_record(record.into_bytes()).await?; + ack.await?; + } + + stream.close().await?; + Ok(()) +} +``` + +### Protobuf Flow + +```rust +let table_properties = TableProperties { + table_name: table_name.clone(), + descriptor_proto: Some(proto_descriptor_bytes), +}; + +let options = StreamConfigurationOptions { + record_type: RecordType::Proto, + ..Default::default() +}; + +let mut stream = sdk + .create_stream(table_properties, client_id, client_secret, Some(options)) + .await?; + +// Ingest serialized protobuf bytes +let record_bytes = my_proto_message.encode_to_vec(); +let ack = stream.ingest_record(record_bytes).await?; +ack.await?; +``` + +--- + +## Language Comparison + +| Feature | Python | Java | Go | TypeScript | Rust | +|---------|--------|------|----|------------|------| +| Min version | 3.9+ | 8+ | 1.21+ | Node 16+ | 1.70+ | +| Package | `databricks-zerobus-ingest-sdk` | `com.databricks:zerobus-ingest-sdk` | `github.com/databricks/zerobus-sdk-go` | `@databricks/zerobus-ingest-sdk` | `databricks-zerobus-ingest-sdk` | +| Default serialization | JSON | Protobuf | JSON | JSON | JSON | +| Async API | Yes (separate module) | CompletableFuture | Goroutines | Native async/await | Tokio async/await | +| ACK pattern | `ack.wait_for_ack()` or callback | `.join()` | `ack.Await()` | Implicit in `await` | `ack.await?` | +| Proto generation | `python -m zerobus.tools.generate_proto` | JAR CLI tool | External `protoc` | External `protoc` | External `protoc` | diff --git a/.claude/skills/databricks-zerobus-ingest/4-protobuf-schema.md b/.claude/skills/databricks-zerobus-ingest/4-protobuf-schema.md new file mode 100644 index 00000000..c8796faf --- /dev/null +++ b/.claude/skills/databricks-zerobus-ingest/4-protobuf-schema.md @@ -0,0 +1,191 @@ +# Protobuf Schema Generation + +Generate `.proto` schemas from Unity Catalog table definitions, compile language bindings, and understand Delta-to-Protobuf type mappings. + +--- + +## Why Protobuf? + +| Aspect | JSON | Protobuf | +|--------|------|----------| +| **Type safety** | None (runtime errors on mismatch) | Compile-time type checking | +| **Schema evolution** | Manual; easy to break silently | Forward-compatible by design | +| **Performance** | Text parsing overhead | Binary encoding, smaller payloads | +| **Recommended for** | Prototyping, simple schemas | Production, complex schemas | + +**Recommendation:** Use Protobuf for any production workload. Use JSON only for quick prototyping or when the schema is trivial. + +--- + +## Generate .proto from a UC Table + +### Python + +```bash +python -m zerobus.tools.generate_proto \ + --uc-endpoint "https://dbc-a1b2c3d4-e5f6.cloud.databricks.com" \ + --client-id "$DATABRICKS_CLIENT_ID" \ + --client-secret "$DATABRICKS_CLIENT_SECRET" \ + --table "catalog.schema.table_name" \ + --output record.proto +``` + +### Java + +```bash +java -jar zerobus-ingest-sdk-0.1.0-jar-with-dependencies.jar \ + --uc-endpoint "https://dbc-a1b2c3d4-e5f6.cloud.databricks.com" \ + --client-id "$DATABRICKS_CLIENT_ID" \ + --client-secret "$DATABRICKS_CLIENT_SECRET" \ + --table "catalog.schema.table_name" \ + --output record.proto +``` + +The generated `.proto` file will contain a message definition matching the table schema, for example: + +```protobuf +syntax = "proto3"; + +message AirQuality { + string device_name = 1; + int32 temp = 2; + int64 humidity = 3; +} +``` + +--- + +## Compile Language Bindings + +### Python + +```bash +pip install grpcio-tools + +python -m grpc_tools.protoc \ + -I. \ + --python_out=. \ + record.proto +``` + +This generates `record_pb2.py`. Import and use it: + +```python +import record_pb2 + +record = record_pb2.AirQuality( + device_name="sensor-1", + temp=22, + humidity=55, +) +``` + +### Java + +```bash +protoc --java_out=src/main/java record.proto +``` + +Generates Java classes under `src/main/java/`. Usage: + +```java +import com.example.proto.Record.AirQuality; + +AirQuality record = AirQuality.newBuilder() + .setDeviceName("sensor-1") + .setTemp(22) + .setHumidity(55) + .build(); +``` + +### Go + +```bash +protoc --go_out=. record.proto +``` + +### Rust + +Use `prost` in `build.rs`: + +```rust +// build.rs +fn main() { + prost_build::compile_protos(&["record.proto"], &["."]).unwrap(); +} +``` + +--- + +## Delta-to-Protobuf Type Mappings + +| Delta / Spark Type | Protobuf Type | Notes | +|--------------------|---------------|-------| +| `STRING` | `string` | | +| `INT` / `INTEGER` | `int32` | | +| `LONG` / `BIGINT` | `int64` | | +| `FLOAT` | `float` | | +| `DOUBLE` | `double` | | +| `BOOLEAN` | `bool` | | +| `BINARY` | `bytes` | | +| `ARRAY` | `repeated T` | Element type maps recursively | +| `MAP` | `map` | Key must be string or integer type | +| `STRUCT` | Nested `message` | Fields map recursively | +| `DATE` | `int32` | Epoch days (days since 1970-01-01) | +| `TIMESTAMP` | `int64` | Epoch microseconds | +| `DECIMAL(p,s)` | `bytes` or `string` | Check generated .proto for exact mapping | +| `VARIANT` | `string` | JSON-encoded string | + +**Important:** The Protobuf schema must match the Delta table schema exactly (1:1 field mapping). If the table schema changes, regenerate the `.proto` and recompile. + +--- + +## Maximum Schema Size + +- Maximum **2000 columns** per proto schema +- Maximum **10 MB** per individual message (10,485,760 bytes) + +--- + +## Schema Evolution Workflow + +When your table schema changes: + +1. Alter the table in Unity Catalog (add columns, etc.) +2. Regenerate the `.proto` file using the generation command +3. Recompile language bindings +4. Update your producer code to populate new fields +5. Redeploy + +**Note:** Zerobus does not support automatic schema evolution. You must manage this process explicitly. + +--- + +## Using the Descriptor in Code + +### Python + +```python +from zerobus.sdk.shared import TableProperties, RecordType +import record_pb2 + +# Pass the DESCRIPTOR from the compiled module +table_props = TableProperties( + "catalog.schema.table_name", + record_pb2.AirQuality.DESCRIPTOR, +) +``` + +### Java + +```java +// Pass a default instance to extract the descriptor +TableProperties tableProperties = new TableProperties<>( + "catalog.schema.table_name", + AirQuality.getDefaultInstance() +); +``` + +### Go / Rust + +Pass the raw descriptor bytes when constructing `TableProperties`. diff --git a/.claude/skills/databricks-zerobus-ingest/5-operations-and-limits.md b/.claude/skills/databricks-zerobus-ingest/5-operations-and-limits.md new file mode 100644 index 00000000..7b8cb2b8 --- /dev/null +++ b/.claude/skills/databricks-zerobus-ingest/5-operations-and-limits.md @@ -0,0 +1,251 @@ +# Operations and Limits + +ACK handling, retry and reconnection patterns, throughput limits, delivery semantics, and operational constraints for Zerobus Ingest. + +--- + +## Acknowledgment (ACK) Handling + +Every ingested record returns a durability acknowledgment. An ACK indicates that **all records up to that offset** have been durably written to the target Delta table. + +### Strategies + +| Strategy | When to Use | Trade-off | +|----------|-------------|-----------| +| **Sync block per record** | Low-volume, strict ordering | Simplest; lower throughput | +| **ACK callback** | High-volume producers | Higher throughput; more complex | +| **Periodic flush** | Batch-oriented workloads | Best throughput; eventual consistency | + +### Sync Block (Python) + +```python +ack = stream.ingest_record(record) +ack.wait_for_ack() # Blocks until durable +``` + +### ACK Callback (Python) + +```python +from zerobus.sdk.shared import IngestRecordResponse + +last_acked_offset = 0 + +def on_ack(response: IngestRecordResponse) -> None: + global last_acked_offset + last_acked_offset = response.durability_ack_up_to_offset + +options = StreamConfigurationOptions( + record_type=RecordType.JSON, + ack_callback=on_ack, +) +``` + +### Flush-Based + +```python +# Send many records without blocking +for record in batch: + stream.ingest_record(record) + +# Flush ensures all buffered records are sent +stream.flush() +``` + +--- + +## Retry and Reconnection + +Zerobus streams can close due to server maintenance, network issues, or zone failures. Implement retry with exponential backoff and stream reinitialization. + +### Pattern (Any Language) + +``` +1. Attempt ingest +2. On connection/closed error: + a. Close the current stream + b. Wait with exponential backoff (1s, 2s, 4s, ...) + c. Reinitialize the stream + d. Retry the record +3. After max retries, log failure and escalate +``` + +### Python Implementation + +```python +import time +import logging + +logger = logging.getLogger(__name__) + +def ingest_with_retry(stream_factory, record, max_retries=5): + """Ingest a record with retry and stream reinitialization. + + Args: + stream_factory: Callable that returns a new stream. + record: The record to ingest. + max_retries: Maximum retry attempts. + """ + stream = stream_factory() + + for attempt in range(max_retries): + try: + ack = stream.ingest_record(record) + ack.wait_for_ack() + return stream # Return the (possibly new) stream + except Exception as e: + err = str(e).lower() + logger.warning("Attempt %d/%d failed: %s", attempt + 1, max_retries, e) + + if "closed" in err or "connection" in err or "unavailable" in err: + try: + stream.close() + except Exception: + pass + backoff = min(2 ** attempt, 30) # Cap at 30s + time.sleep(backoff) + stream = stream_factory() + elif attempt < max_retries - 1: + time.sleep(2 ** attempt) + else: + raise + + return stream +``` + +### Key Points + +- **Always reinitialize the stream** on connection errors, not just retry the same stream +- **Cap backoff** at a reasonable maximum (e.g., 30 seconds) +- **Log failures** with enough context to diagnose (endpoint, table, error message) +- **Design for at-least-once**: your downstream consumers should handle duplicate records + +--- + +## Delivery Semantics + +Zerobus provides **at-least-once** delivery guarantees: + +- Records may be delivered more than once (e.g., after a retry where the original was actually persisted) +- There is **no exactly-once** semantics +- Design your target table and downstream consumers to handle duplicates (e.g., deduplication via `MERGE` or unique constraints) + +--- + +## Throughput Limits + +| Limit | Value | Notes | +|-------|-------|-------| +| **Throughput per stream** | 100 MB/s | Based on 1 KB messages | +| **Rows per stream** | 15,000 rows/s | | +| **Max message size** | 10 MB (10,485,760 bytes) | Per individual record | +| **Max columns** | 2,000 | Per proto schema / table | + +### Scaling Beyond One Stream + +If you need higher throughput than a single stream provides: + +- Open **multiple streams** to the same table from different clients +- Zerobus supports **thousands of concurrent clients** writing to the same table +- Partition your data across streams by key (e.g., device ID, region) +- Contact Databricks for custom throughput requirements + +--- + +## Regional Availability + +Workspace and target tables must be in a supported region for your cloud provider. + +### AWS Supported Regions + +| Region | Code | +|--------|------| +| US East (N. Virginia) | `us-east-1` | +| US East (Ohio) | `us-east-2` | +| US West (Oregon) | `us-west-2` | +| Europe (Frankfurt) | `eu-central-1` | +| Europe (Ireland) | `eu-west-1` | +| Asia Pacific (Singapore) | `ap-southeast-1` | +| Asia Pacific (Sydney) | `ap-southeast-2` | +| Asia Pacific (Tokyo) | `ap-northeast-1` | +| Canada (Central) | `ca-central-1` | + +### Azure Supported Regions + +| Region | Code | +|--------|------| +| Canada Central | `canadacentral` | +| West US | `westus` | +| East US | `eastus` | +| East US 2 | `eastus2` | +| Central US | `centralus` | +| North Central US | `northcentralus` | +| Sweden Central | `swedencentral` | +| West Europe | `westeurope` | +| North Europe | `northeurope` | +| Australia East | `australiaeast` | +| Southeast Asia | `southeastasia` | + +**Performance note:** Optimal throughput requires the client application and Zerobus endpoint to be in the **same region**. + +--- + +## Durability and Availability + +- **Single-AZ only**: Zerobus runs in a single availability zone. The service may experience downtime if that zone is unavailable. +- **No geographic redundancy**: Plan for zone outages in your producer's retry logic. +- **Maintenance windows**: The server may close streams during maintenance. Your client should handle reconnection gracefully. + +--- + +## Target Table Constraints + +| Constraint | Details | +|------------|---------| +| **Table type** | Managed Delta tables only (no external storage) | +| **Table names** | ASCII letters, digits, underscores only | +| **Schema changes** | No auto-evolution; regenerate proto and redeploy | +| **Table creation** | Zerobus does not create tables; pre-create via SQL DDL | +| **Table recreation** | Cannot recreate an existing target table via Zerobus | + +--- + +## Supported Data Types + +| Delta Type | Protobuf Type | Conversion Notes | +|------------|---------------|------------------| +| STRING | string | Direct mapping | +| INT / INTEGER | int32 | Direct mapping | +| LONG / BIGINT | int64 | Direct mapping | +| FLOAT | float | Direct mapping | +| DOUBLE | double | Direct mapping | +| BOOLEAN | bool | Direct mapping | +| BINARY | bytes | Direct mapping | +| ARRAY\ | repeated T | Recursive mapping | +| MAP\ | map\ | Key must be string or integer | +| STRUCT | nested message | Recursive mapping | +| DATE | int32 | Epoch days since 1970-01-01 | +| TIMESTAMP | int64 | Epoch microseconds | +| VARIANT | string | JSON-encoded string | + +--- + +## Monitoring and Observability + +Zerobus does not currently expose built-in metrics dashboards. Monitor your producers with: + +- **Application-level logging**: Log ACK offsets, retry counts, and error rates +- **ACK callback tracking**: Track the last-acked offset to measure ingestion lag +- **Table row counts**: Periodically query the target table to verify data is arriving +- **Health checks**: Attempt a lightweight ingest (or stream creation) to verify connectivity + +```python +# Simple health check +def check_zerobus_health(sdk, client_id, client_secret, table_props, options): + try: + stream = sdk.create_stream(client_id, client_secret, table_props, options) + stream.close() + return True + except Exception as e: + logger.error("Zerobus health check failed: %s", e) + return False +``` diff --git a/.claude/skills/databricks-zerobus-ingest/SKILL.md b/.claude/skills/databricks-zerobus-ingest/SKILL.md new file mode 100644 index 00000000..d29dc00f --- /dev/null +++ b/.claude/skills/databricks-zerobus-ingest/SKILL.md @@ -0,0 +1,228 @@ +--- +name: databricks-zerobus-ingest +description: "Build Zerobus Ingest clients for near real-time data ingestion into Databricks Delta tables via gRPC. Use when creating producers that write directly to Unity Catalog tables without a message bus, working with the Zerobus Ingest SDK in Python/Java/Go/TypeScript/Rust, generating Protobuf schemas from UC tables, or implementing stream-based ingestion with ACK handling and retry logic." +--- + +# Zerobus Ingest + +Build clients that ingest data directly into Databricks Delta tables via the Zerobus gRPC API. + +**Status:** Public Preview (currently free; Databricks plans to introduce charges in the future) + +**Documentation:** +- [Zerobus Overview](https://docs.databricks.com/aws/en/ingestion/zerobus-overview) +- [Zerobus Ingest SDK](https://docs.databricks.com/aws/en/ingestion/zerobus-ingest) +- [Zerobus Limits](https://docs.databricks.com/aws/en/ingestion/zerobus-limits) + +--- + +## What Is Zerobus Ingest? + +Zerobus Ingest is a serverless connector that enables direct, record-by-record data ingestion into Delta tables via gRPC. It eliminates the need for message bus infrastructure (Kafka, Kinesis, Event Hub) for lakehouse-bound data. The service validates schemas, materializes data to target tables, and sends durability acknowledgments back to the client. + +**Core pattern:** SDK init -> create stream -> ingest records -> handle ACKs -> flush -> close + +--- + +## Quick Decision: What Are You Building? + +| Scenario | Language | Serialization | Reference | +|----------|----------|---------------|-----------| +| Quick prototype / test harness | Python | JSON | [2-python-client.md](2-python-client.md) | +| Production Python producer | Python | Protobuf | [2-python-client.md](2-python-client.md) + [4-protobuf-schema.md](4-protobuf-schema.md) | +| JVM microservice | Java | Protobuf | [3-multilanguage-clients.md](3-multilanguage-clients.md) | +| Go service | Go | JSON or Protobuf | [3-multilanguage-clients.md](3-multilanguage-clients.md) | +| Node.js / TypeScript app | TypeScript | JSON | [3-multilanguage-clients.md](3-multilanguage-clients.md) | +| High-performance system service | Rust | JSON or Protobuf | [3-multilanguage-clients.md](3-multilanguage-clients.md) | +| Schema generation from UC table | Any | Protobuf | [4-protobuf-schema.md](4-protobuf-schema.md) | +| Retry / reconnection logic | Any | Any | [5-operations-and-limits.md](5-operations-and-limits.md) | + +If not speficfied, default to python. + +--- + +## Common Libraries + +These libraries are essential for ZeroBus data ingestion: + +- **databricks-sdk>=0.85.0**: Databricks workspace client for authentication and metadata +- **databricks-zerobus-ingest-sdk>=0.2.0**: ZeroBus SDK for high-performance streaming ingestion +- **grpcio-tools** +These are typically NOT pre-installed on Databricks. Install them using `execute_databricks_command` tool: +- `code`: "%pip install databricks-sdk>=VERSION databricks-zerobus-ingest-sdk>=VERSION" + +Save the returned `cluster_id` and `context_id` for subsequent calls. + +Smart Installation Approach + +# Check protobuf version first, then install compatible +grpcio-tools +import google.protobuf +runtime_version = google.protobuf.__version__ +print(f"Runtime protobuf version: {runtime_version}") + +if runtime_version.startswith("5.26") or +runtime_version.startswith("5.29"): + %pip install grpcio-tools==1.62.0 +else: + %pip install grpcio-tools # Use latest for newer protobuf +versions +--- + +## Prerequisites + +You must never execute the skill without confirming the below objects are valid: + +1. **A Unity Catalog managed Delta table** to ingest into +2. **A service principal id and secret** with `MODIFY` and `SELECT` on the target table +3. **The Zerobus server endpoint** for your workspace region +4. **The Zerobus Ingest SDK** installed for your target language + +See [1-setup-and-authentication.md](1-setup-and-authentication.md) for complete setup instructions. + +--- + +## Minimal Python Example (JSON) + +```python +from zerobus.sdk.sync import ZerobusSdk +from zerobus.sdk.shared import RecordType, StreamConfigurationOptions, TableProperties + +sdk = ZerobusSdk(server_endpoint, workspace_url) +options = StreamConfigurationOptions(record_type=RecordType.JSON) +table_props = TableProperties(table_name) + +stream = sdk.create_stream(client_id, client_secret, table_props, options) +try: + record = {"device_name": "sensor-1", "temp": 22, "humidity": 55} + ack = stream.ingest_record(record) + ack.wait_for_ack() +finally: + stream.close() +``` + +--- + +## Detailed guides + +| Topic | File | When to Read | +|-------|------|--------------| +| Setup & Auth | [1-setup-and-authentication.md](1-setup-and-authentication.md) | Endpoint formats, service principals, SDK install | +| Python Client | [2-python-client.md](2-python-client.md) | Sync/async Python, JSON and Protobuf flows, reusable client class | +| Multi-Language | [3-multilanguage-clients.md](3-multilanguage-clients.md) | Java, Go, TypeScript, Rust SDK examples | +| Protobuf Schema | [4-protobuf-schema.md](4-protobuf-schema.md) | Generate .proto from UC table, compile, type mappings | +| Operations & Limits | [5-operations-and-limits.md](5-operations-and-limits.md) | ACK handling, retries, reconnection, throughput limits, constraints | + +--- + +You must always follow all the steps in the Workslfow + +## Workflow +0. **Display the plan of your execution** +1. **Determinate the type of client** +2. **Get schema** Always use 4-protobuf-schema.md. Execute using the `run_python_file_on_databricks` MCP tool +3. **Write Python code to a local file follow the instructions in the relevant guide to ingest with zerobus** in the project (e.g., `scripts/zerobus_ingest.py`). +4. **Execute on Databricks** using the `run_python_file_on_databricks` MCP tool +5. **If execution fails**: Edit the local file to fix the error, then re-execute +6. **Reuse the context** for follow-up executions by passing the returned `cluster_id` and `context_id` + +--- + +## Important +- Never install local packages +- Always validate MCP server requirement before execution + +--- + +### Context Reuse Pattern + +The first execution auto-selects a running cluster and creates an execution context. **Reuse this context for follow-up calls** - it's much faster (~1s vs ~15s) and shares variables/imports: + +**First execution** - use `run_python_file_on_databricks` tool: +- `file_path`: "scripts/zerobus_ingest.py" + +Returns: `{ success, output, error, cluster_id, context_id, ... }` + +Save `cluster_id` and `context_id` for follow-up calls. + +**If execution fails:** +1. Read the error from the result +2. Edit the local Python file to fix the issue +3. Re-execute with same context using `run_python_file_on_databricks` tool: + - `file_path`: "scripts/zerobus_ingest.py" + - `cluster_id`: "" + - `context_id`: "" + +**Follow-up executions** reuse the context (faster, shares state): +- `file_path`: "scripts/validate_ingestion.py" +- `cluster_id`: "" +- `context_id`: "" + +### Handling Failures + +When execution fails: +1. Read the error from the result +2. **Edit the local Python file** to fix the issue +3. Re-execute using the same `cluster_id` and `context_id` (faster, keeps installed libraries) +4. If the context is corrupted, omit `context_id` to create a fresh one + +--- + +### Installing Libraries + +Databricks provides Spark, pandas, numpy, and common data libraries by default. **Only install a library if you get an import error.** + +Use `execute_databricks_command` tool: +- `code`: "%pip install databricks-zerobus-ingest-sdk>=0.2.0" +- `cluster_id`: "" +- `context_id`: "" + +The library is immediately available in the same context. + +**Note:** Keeping the same `context_id` means installed libraries persist across calls. + +## 🚨 Critical Learning: Timestamp Format Fix + +**BREAKTHROUGH**: ZeroBus requires **timestamp fields as Unix integer timestamps**, NOT string timestamps. +The timestamp generation must use microseconds for Databricks. + +--- + +## Key Concepts + +- **gRPC + Protobuf**: Zerobus uses gRPC as its transport protocol. Any application that can communicate via gRPC and construct Protobuf messages can produce to Zerobus. +- **JSON or Protobuf serialization**: JSON for quick starts; Protobuf for type safety, forward compatibility, and performance. +- **At-least-once delivery**: The connector provides at-least-once guarantees. Design consumers to handle duplicates. +- **Durability ACKs**: Each ingested record returns an ACK confirming durable write. ACKs indicate all records up to that offset have been durably written. +- **No table management**: Zerobus does not create or alter tables. You must pre-create your target table and manage schema evolution yourself. +- **Single-AZ durability**: The service runs in a single availability zone. Plan for potential zone outages. + +--- + +## Common Issues + +| Issue | Solution | +|-------|----------| +| **Connection refused** | Verify server endpoint format matches your cloud (AWS vs Azure). Check firewall allowlists. | +| **Authentication failed** | Confirm service principal client_id/secret. Verify GRANT statements on the target table. | +| **Schema mismatch** | Ensure record fields match the target table schema exactly. Regenerate .proto if table changed. | +| **Stream closed unexpectedly** | Implement retry with exponential backoff and stream reinitialization. See [5-operations-and-limits.md](5-operations-and-limits.md). | +| **Throughput limits hit** | Max 100 MB/s and 15,000 rows/s per stream. Open multiple streams or contact Databricks. | +| **Region not supported** | Check supported regions in [5-operations-and-limits.md](5-operations-and-limits.md). | +| **Table not found** | Ensure table is a managed Delta table in a supported region with correct three-part name. | + +--- + +## Related Skills + +- **[databricks-python-sdk](../databricks-python-sdk/SKILL.md)** - General SDK patterns and WorkspaceClient for table/schema management +- **[databricks-spark-declarative-pipelines](../databricks-spark-declarative-pipelines/SKILL.md)** - Downstream pipeline processing of ingested data +- **[databricks-unity-catalog](../databricks-unity-catalog/SKILL.md)** - Managing catalogs, schemas, and tables that Zerobus writes to +- **[databricks-synthetic-data-generation](../databricks-synthetic-data-generation/SKILL.md)** - Generate test data to feed into Zerobus producers +- **[databricks-config](../databricks-config/SKILL.md)** - Profile and authentication setup + +## Resources + +- [Zerobus Overview](https://docs.databricks.com/aws/en/ingestion/zerobus-overview) +- [Zerobus Ingest SDK](https://docs.databricks.com/aws/en/ingestion/zerobus-ingest) +- [Zerobus Limits](https://docs.databricks.com/aws/en/ingestion/zerobus-limits) diff --git a/.claude/skills/mlflow-evaluation/SKILL.md b/.claude/skills/mlflow-evaluation/SKILL.md deleted file mode 100644 index 322f6aaa..00000000 --- a/.claude/skills/mlflow-evaluation/SKILL.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -name: mlflow-evaluation -description: "MLflow 3 GenAI evaluation for agent development. Use when (1) writing mlflow.genai.evaluate() code, (2) creating @scorer functions, (3) building evaluation datasets from traces, (4) using built-in scorers (Guidelines, Correctness, Safety, RetrievalGroundedness), (5) analyzing traces for latency/errors/architecture, (6) optimizing agent context/prompts/token usage, (7) debugging evaluation failures. Covers the full eval workflow: trace analysis -> dataset building -> scorer creation -> evaluation execution." ---- - -# MLflow 3 GenAI Evaluation - -## Before Writing Any Code - -1. **Read GOTCHAS.md** - 15+ common mistakes that cause failures -2. **Read CRITICAL-interfaces.md** - Exact API signatures and data schemas - -## End-to-End Workflows - -Follow these workflows based on your goal. Each step indicates which reference files to read. - -### Workflow 1: First-Time Evaluation Setup - -For users new to MLflow GenAI evaluation or setting up evaluation for a new agent. - -| Step | Action | Reference Files | -|------|--------|-----------------| -| 1 | Understand what to evaluate | `user-journeys.md` (Journey 0: Strategy) | -| 2 | Learn API patterns | `GOTCHAS.md` + `CRITICAL-interfaces.md` | -| 3 | Build initial dataset | `patterns-datasets.md` (Patterns 1-4) | -| 4 | Choose/create scorers | `patterns-scorers.md` + `CRITICAL-interfaces.md` (built-in list) | -| 5 | Run evaluation | `patterns-evaluation.md` (Patterns 1-3) | - -### Workflow 2: Production Trace -> Evaluation Dataset - -For building evaluation datasets from production traces. - -| Step | Action | Reference Files | -|------|--------|-----------------| -| 1 | Search and filter traces | `patterns-trace-analysis.md` (MCP tools section) | -| 2 | Analyze trace quality | `patterns-trace-analysis.md` (Patterns 1-7) | -| 3 | Tag traces for inclusion | `patterns-datasets.md` (Patterns 16-17) | -| 4 | Build dataset from traces | `patterns-datasets.md` (Patterns 6-7) | -| 5 | Add expectations/ground truth | `patterns-datasets.md` (Pattern 2) | - -### Workflow 3: Performance Optimization - -For debugging slow or expensive agent execution. - -| Step | Action | Reference Files | -|------|--------|-----------------| -| 1 | Profile latency by span | `patterns-trace-analysis.md` (Patterns 4-6) | -| 2 | Analyze token usage | `patterns-trace-analysis.md` (Pattern 9) | -| 3 | Detect context issues | `patterns-context-optimization.md` (Section 5) | -| 4 | Apply optimizations | `patterns-context-optimization.md` (Sections 1-4, 6) | -| 5 | Re-evaluate to measure impact | `patterns-evaluation.md` (Pattern 6-7) | - -### Workflow 4: Regression Detection - -For comparing agent versions and finding regressions. - -| Step | Action | Reference Files | -|------|--------|-----------------| -| 1 | Establish baseline | `patterns-evaluation.md` (Pattern 4: named runs) | -| 2 | Run current version | `patterns-evaluation.md` (Pattern 1) | -| 3 | Compare metrics | `patterns-evaluation.md` (Patterns 6-7) | -| 4 | Analyze failing traces | `patterns-trace-analysis.md` (Pattern 7) | -| 5 | Debug specific failures | `patterns-trace-analysis.md` (Patterns 8-9) | - -### Workflow 5: Custom Scorer Development - -For creating project-specific evaluation metrics. - -| Step | Action | Reference Files | -|------|--------|-----------------| -| 1 | Understand scorer interface | `CRITICAL-interfaces.md` (Scorer section) | -| 2 | Choose scorer pattern | `patterns-scorers.md` (Patterns 4-11) | -| 3 | For multi-agent scorers | `patterns-scorers.md` (Patterns 13-16) | -| 4 | Test with evaluation | `patterns-evaluation.md` (Pattern 1) | - -## Reference Files Quick Lookup - -| Reference | Purpose | When to Read | -|-----------|---------|--------------| -| `GOTCHAS.md` | Common mistakes | **Always read first** before writing code | -| `CRITICAL-interfaces.md` | API signatures, schemas | When writing any evaluation code | -| `patterns-evaluation.md` | Running evals, comparing | When executing evaluations | -| `patterns-scorers.md` | Custom scorer creation | When built-in scorers aren't enough | -| `patterns-datasets.md` | Dataset building | When preparing evaluation data | -| `patterns-trace-analysis.md` | Trace debugging | When analyzing agent behavior | -| `patterns-context-optimization.md` | Token/latency fixes | When agent is slow or expensive | -| `user-journeys.md` | High-level workflows | When starting a new evaluation project | - -## Critical API Facts - -- **Use:** `mlflow.genai.evaluate()` (NOT `mlflow.evaluate()`) -- **Data format:** `{"inputs": {"query": "..."}}` (nested structure required) -- **predict_fn:** Receives `**unpacked kwargs` (not a dict) - -See `GOTCHAS.md` for complete list. diff --git a/.claude/skills/mlflow-evaluation/references/user-journeys.md b/.claude/skills/mlflow-evaluation/references/user-journeys.md deleted file mode 100644 index 01cb4ccd..00000000 --- a/.claude/skills/mlflow-evaluation/references/user-journeys.md +++ /dev/null @@ -1,332 +0,0 @@ -# User Journey Guides - -Step-by-step workflows for common evaluation scenarios. - ---- - -## Journey 0: Strategy Alignment (ALWAYS START HERE) - -**Starting Point**: You need to evaluate an agent -**Goal**: Align on what to evaluate before writing any code - -**PRIORITY:** Before writing evaluation code, complete strategy alignment. This ensures evaluations measure what matters and provide actionable insights. - -### Step 1: Understand the Agent - -Before evaluating, gather context about what you're evaluating: - -**Questions to ask (or investigate in the codebase):** -1. **What does this agent do?** (data analysis, RAG, multi-turn chat, task automation) -2. **What tools does it use?** (UC functions, vector search, external APIs) -3. **What is the input/output format?** (messages format, structured output) -4. **What is the current state?** (prototype, production, needs improvement) - -**Actions to take:** -- Read the agent's main code file (e.g., `agent.py`) -- Review the config file for system prompts and tool definitions -- Check existing tests or evaluation scripts -- Look at CLAUDE.md or README for project context - -### Step 2: Align on What to Evaluate - -**Evaluation dimensions to consider:** - -| Dimension | When to Use | Example Scorer | -|-----------|-------------|----------------| -| **Safety** | Always (table stakes) | `Safety()` | -| **Correctness** | When ground truth exists | `Correctness()` | -| **Relevance** | When responses should address queries | `RelevanceToQuery()` | -| **Groundedness** | RAG systems with retrieved context | `RetrievalGroundedness()` | -| **Domain Guidelines** | Domain-specific requirements | `Guidelines(name="...", guidelines="...")` | -| **Format/Structure** | Structured output requirements | Custom scorer | -| **Tool Usage** | Agents with tool calls | Custom scorer checking tool selection | - -**Questions to ask the user:** -1. What are the **must-have** quality criteria? (safety, accuracy, relevance) -2. What are the **nice-to-have** criteria? (conciseness, tone, format) -3. Are there **specific failure modes** you've seen or worry about? -4. Do you have **ground truth** or expected answers for test cases? - -### Step 3: Define User Scenarios (Evaluation Dataset) - -**Types of test cases to include:** - -| Category | Purpose | Example | -|----------|---------|---------| -| **Happy Path** | Core functionality works | Typical user questions | -| **Edge Cases** | Boundary conditions | Empty inputs, very long queries | -| **Adversarial** | Robustness testing | Prompt injection, off-topic | -| **Multi-turn** | Conversation handling | Follow-up questions, context recall | -| **Domain-specific** | Business logic | Industry terminology, specific formats | - -**Questions to ask the user:** -1. What are the **most common** questions users ask? -2. What are **challenging** questions the agent should handle? -3. Are there questions it should **refuse** to answer? -4. Do you have **existing test cases** or production traces to start from? - -### Step 4: Establish Success Criteria - -**Define quality gates before running evaluation:** - -```python -QUALITY_GATES = { - "safety": 1.0, # 100% - non-negotiable - "correctness": 0.9, # 90% - high bar for accuracy - "relevance": 0.85, # 85% - good relevance - "concise": 0.8, # 80% - nice to have -} -``` - -**Questions to ask the user:** -1. What pass rates are **acceptable** for each dimension? -2. Which metrics are **blocking** vs **informational**? -3. How will evaluation results **inform decisions**? (ship/no-ship, iterate, investigate) - -### Strategy Alignment Checklist - -Before implementing evaluation, confirm: -- [ ] Agent purpose and architecture understood -- [ ] Evaluation dimensions agreed upon -- [ ] Test case categories identified -- [ ] Success criteria defined -- [ ] Data source identified (new, traces, existing dataset) - ---- - -## Journey 3: "Something Broke" - Regression Detection - -**Starting Point**: You made changes to your agent and suspect something regressed -**Goal**: Identify what broke and verify the fix - -### Steps - -1. **Establish baseline metrics** - ```bash - # Run evaluation on the previous version (or use saved baseline) - cd agents/tool_calling_dspy - python run_quick_eval.py - ``` - Record key metrics: `classifier_accuracy`, `tool_selection_accuracy`, `follows_instructions` - -2. **Run evaluation on current version** - ```bash - python run_quick_eval.py - ``` - -3. **Compare metrics** - ```python - from evaluation.optimization_history import OptimizationHistory - - history = OptimizationHistory() - print(history.compare_iterations(-2, -1)) # Compare last two - ``` - -4. **Identify regression source** - - If `classifier_accuracy` dropped → Check ClassifierSignature changes - - If `tool_selection_accuracy` dropped → Check tool descriptions, required_tools field - - If `follows_instructions` dropped → Check ExecutorSignature output format - -5. **Analyze failing traces** - ``` - /eval:analyze-traces [experiment-id] - ``` - Look for: - - Error patterns in specific test categories - - Tool call failures - - Unexpected outputs - -6. **Fix and re-evaluate** - - Revert problematic changes or apply targeted fix - - Re-run evaluation - - Verify metrics restored - -### Commands Used -- `python run_quick_eval.py` - Run evaluation -- `/eval:analyze-traces` - Deep trace analysis -- `OptimizationHistory.compare_iterations()` - Metric comparison - -### Success Indicators -- Metrics return to baseline or improve -- No new failing test cases -- Trace analysis shows expected behavior - ---- - -## Journey 7: "My Multi-Agent is Slow" - Performance Optimization - -**Starting Point**: Your agent responses are too slow -**Goal**: Identify bottlenecks and reduce latency - -### Steps - -1. **Run evaluation with latency scoring** - ```bash - cd agents/tool_calling_dspy - python run_quick_eval.py - ``` - Note the latency metrics: - - `classifier_latency_ms` - - `rewriter_latency_ms` - - `executor_latency_ms` - - `total_latency_ms` - -2. **Identify the bottleneck stage** - | Latency | Typical Range | If High, Check | - |---------|---------------|----------------| - | classifier_latency | <5s | ClassifierSignature verbosity | - | rewriter_latency | <10s | QueryRewriterSignature complexity | - | executor_latency | <30s | Tool call count, response generation | - -3. **Analyze traces for slow stages** - ``` - /eval:analyze-traces [experiment-id] - ``` - Focus on: - - Span durations by stage - - Number of LLM calls per stage - - Tool execution times - -4. **Run signature analysis** - ```bash - python -m evaluation.analyze_signatures - ``` - Look for: - - High total description chars (>2000) - - Verbose OutputField descriptions - - Missing examples (causes more retries) - -5. **Apply optimizations** - - **For high classifier latency:** - - Simplify ClassifierSignature docstring - - Add concrete examples to reduce ambiguity - - **For high executor latency:** - - Simplify ExecutorSignature.answer format - - Reduce output format requirements - - Consider caching repeated tool calls - - **For high total latency:** - - Review if all stages are necessary - - Consider parallel execution where possible - -6. **Re-evaluate and compare** - ```bash - python run_quick_eval.py - ``` - Use `OptimizationHistory.compare_iterations()` to verify improvement - -### Commands Used -- `python run_quick_eval.py` - Run evaluation with latency scoring -- `/eval:analyze-traces` - Trace analysis with timing breakdown -- `python -m evaluation.analyze_signatures` - Signature verbosity analysis - -### Success Indicators -- Target latencies: classifier <5s, executor <30s, total <60s -- No regression in accuracy metrics -- Consistent improvement across test categories - ---- - -## Journey 8: "Improve My Prompts" - Systematic Prompt Optimization - -**Starting Point**: Your agent works but could be more accurate -**Goal**: Systematically improve prompt quality through evaluation - -### Steps - -1. **Establish baseline** - ```bash - cd agents/tool_calling_dspy - python run_quick_eval.py - ``` - Record all metrics in `optimization_history.json` - -2. **Run signature analysis** - ```bash - python -m evaluation.analyze_signatures - ``` - Review the report for: - - Metric correlations (which signatures affect which metrics) - - Specific issues flagged per signature - -3. **Prioritize fixes by metric impact** - - | Metric | Primary Signature | Common Issues | - |--------|-------------------|---------------| - | follows_instructions | ExecutorSignature | Verbose answer format, unclear structure | - | tool_selection_accuracy | ClassifierSignature | No examples, ambiguous tool descriptions | - | classifier_accuracy | ClassifierSignature | Verbose docstring, unclear query_type mapping | - -4. **Apply ONE fix at a time** - - Make a single, targeted change - - Document the change in your commit message - - Track in optimization_history.json - -5. **Re-evaluate immediately** - ```bash - python run_quick_eval.py - ``` - - If improved → Keep change, move to next fix - - If regressed → Revert and try different approach - - If unchanged → Consider if fix was necessary - -6. **Iterate until targets met** - - | Metric | Target | - |--------|--------| - | classifier_accuracy | 95%+ | - | tool_selection_accuracy | 90%+ | - | follows_instructions | 80%+ | - -7. **Document successful optimizations** - ```python - from evaluation.optimization_history import OptimizationHistory - - history = OptimizationHistory() - print(history.summary()) - ``` - -### Commands Used -- `python run_quick_eval.py` - Run evaluation -- `python -m evaluation.analyze_signatures` - Identify prompt issues -- `/optimize:context --quick` - Full optimization loop (when endpoint available) - -### Success Indicators -- All target metrics met -- No regressions from baseline -- Clear documentation of what changed and why -- Optimization history shows positive trend - ---- - -## Quick Reference - -### Which Journey Am I On? - -| Symptom | Journey | -|---------|---------| -| "It was working before" | Journey 3 (Regression) | -| "It's too slow" | Journey 7 (Performance) | -| "It's not accurate enough" | Journey 8 (Prompt Optimization) | - -### Common Tools Across Journeys - -| Tool | Purpose | -|------|---------| -| `run_quick_eval.py` | Fast evaluation (8 test cases) | -| `run_full_eval.py` | Full evaluation (23 test cases) | -| `analyze_signatures.py` | Signature/prompt analysis | -| `OptimizationHistory` | Track iterations | -| `/eval:analyze-traces` | Deep trace analysis | -| `/optimize:context` | Full optimization loop | - -### Metric Targets - -| Metric | Target | Critical Threshold | -|--------|--------|-------------------| -| classifier_accuracy | 95%+ | <80% | -| tool_selection_accuracy | 90%+ | <70% | -| follows_instructions | 80%+ | <50% | -| executor_latency | <30s | >60s | diff --git a/.claude/skills/refresh-databricks-skills/SKILL.md b/.claude/skills/refresh-databricks-skills/SKILL.md new file mode 100644 index 00000000..47395dd4 --- /dev/null +++ b/.claude/skills/refresh-databricks-skills/SKILL.md @@ -0,0 +1,59 @@ +--- +name: refresh-databricks-skills +description: Use when Databricks skills need updating, user asks to refresh or sync skills from upstream, or skills seem outdated compared to the ai-dev-kit repo +--- + +# Refresh Databricks Skills + +## Overview + +Pulls the latest Databricks skills from the upstream source repo and replaces all existing Databricks skills in the project while preserving non-Databricks skills (e.g., superpowers workflow skills). + +**Source repo:** `https://github.com/databricks-solutions/ai-dev-kit` (path: `databricks-skills/`) + +## When to Use + +- User asks to update, refresh, or sync Databricks skills +- Skills seem outdated or missing newer Databricks features +- A new Databricks skill was added upstream that the project needs + +## Process + +1. **Clone the upstream repo** (shallow clone for speed): + ```bash + git clone --depth 1 https://github.com/databricks-solutions/ai-dev-kit.git $TMPDIR/ai-dev-kit + ``` + +2. **Identify non-Databricks skills to preserve.** These are the superpowers workflow skills that live alongside Databricks skills. List them by checking which directories in `.claude/skills/` do NOT have a matching folder in the upstream `databricks-skills/` directory. Common superpowers skills include: `brainstorming`, `dispatching-parallel-agents`, `executing-plans`, `finishing-a-development-branch`, `receiving-code-review`, `requesting-code-review`, `subagent-driven-development`, `systematic-debugging`, `test-driven-development`, `using-git-worktrees`, `using-superpowers`, `verification-before-completion`, `writing-plans`, `writing-skills`. Also preserve any other project-specific skills (like this one: `refresh-databricks-skills`). + +3. **Remove old Databricks skills** from `.claude/skills/`, keeping all non-Databricks skills identified above. + +4. **Copy new Databricks skills** from the cloned repo. Copy every directory under `databricks-skills/` except `TEMPLATE`: + ```bash + SKILLS_DIR=".claude/skills" + UPSTREAM="$TMPDIR/ai-dev-kit/databricks-skills" + for dir in "$UPSTREAM"/databricks-* "$UPSTREAM"/spark-*; do + [ -d "$dir" ] && cp -r "$dir" "$SKILLS_DIR/$(basename "$dir")" + done + ``` + +5. **Clean up** the cloned repo: + ```bash + rm -rf $TMPDIR/ai-dev-kit + ``` + +6. **Report** the count of skills added, removed, and updated. + +## After Refreshing + +If the project is deployed as a Databricks App, remind the user to sync the updated skills to the workspace and redeploy: +```bash +databricks workspace import-dir --overwrite --profile +databricks apps deploy --source-code-path --profile +``` + +## Common Mistakes + +- **Deleting non-Databricks skills:** Always identify and preserve superpowers and project-specific skills before removing anything. +- **Forgetting this skill itself:** `refresh-databricks-skills` must be preserved during the refresh. +- **Not using `--depth 1`:** Full clone is slow and unnecessary. Always shallow clone. diff --git a/.claude/skills/spark-declarative-pipelines/SKILL.md b/.claude/skills/spark-declarative-pipelines/SKILL.md deleted file mode 100644 index 6db988d3..00000000 --- a/.claude/skills/spark-declarative-pipelines/SKILL.md +++ /dev/null @@ -1,474 +0,0 @@ ---- -name: spark-declarative-pipelines -description: "Creates, configures, and updates Databricks Lakeflow Spark Declarative Pipelines (SDP/LDP) using serverless compute. Handles streaming tables, materialized views, CDC, SCD Type 2, and Auto Loader ingestion patterns. Use when building data pipelines, working with Delta Live Tables, ingesting streaming data, implementing change data capture, or when the user mentions SDP, LDP, DLT, Lakeflow pipelines, streaming tables, or bronze/silver/gold medallion architectures." ---- - -# Lakeflow Spark Declarative Pipelines (SDP) - -## Quick Reference - -| Concept | Details | -|---------|---------| -| **Names** | SDP = Spark Declarative Pipelines = LDP = Lakeflow Declarative Pipelines = Lakeflow Pipelines (all interchangeable) | -| **Python Import** | `from pyspark import pipelines as dp` | -| **Primary Decorators** | `@dp.table()`, `@dp.materialized_view()` | -| **Replaces** | Delta Live Tables (DLT) with `import dlt` | -| **Based On** | Apache Spark 4.1+ (Databricks' modern data pipeline framework) | -| **Docs** | https://docs.databricks.com/aws/en/ldp/developer/python-dev | - ---- - -## Official Documentation - -- **[Lakeflow Spark Declarative Pipelines Overview](https://docs.databricks.com/aws/en/ldp/)** - Main documentation hub -- **[SQL Language Reference](https://docs.databricks.com/aws/en/ldp/developer/sql-dev)** - SQL syntax for streaming tables and materialized views -- **[Python Language Reference](https://docs.databricks.com/aws/en/ldp/developer/python-ref)** - `pyspark.pipelines` API -- **[Loading Data](https://docs.databricks.com/aws/en/ldp/load)** - Auto Loader, Kafka, Kinesis ingestion -- **[Change Data Capture (CDC)](https://docs.databricks.com/aws/en/ldp/cdc)** - AUTO CDC, SCD Type 1/2 -- **[Developing Pipelines](https://docs.databricks.com/aws/en/ldp/develop)** - File structure, testing, validation -- **[Liquid Clustering](https://docs.databricks.com/aws/en/delta/clustering)** - Modern data layout optimization - ---- - -## Quick Start: Initialize New Pipeline Project - -**RECOMMENDED**: Use `databricks pipelines init` to create production-ready Asset Bundle projects with multi-environment support. - -### When to Use Bundle Initialization - -Use bundle initialization for **New pipeline projects** for a professional structure from the start - -Use manual workflow for: -- Quick prototyping without multi-environment needs -- Existing manual projects you want to continue -- Learning/experimentation - -### Step 1: Initialize Project - -I will automatically run this command when you request a new pipeline: - -```bash -databricks pipelines init -``` - -**Interactive Prompts:** -- **Project name**: e.g., `customer_orders_pipeline` -- **Initial catalog**: Unity Catalog name (e.g., `main`, `prod_catalog`) -- **Personal schema per user?**: `yes` for dev (each user gets their own schema), `no` for prod -- **Language**: SQL or Python (auto-detected from your request - see language detection below) - -**Generated Structure:** -``` -my_pipeline/ -├── databricks.yml # Multi-environment config (dev/prod) -├── resources/ -│ └── *_etl.pipeline.yml # Pipeline resource definition -└── src/ - └── *_etl/ - ├── explorations/ # Exploratory code in .ipynb - └── transformations/ # Your .sql or .py files here -``` - -### Step 2: Customize Transformations - -Replace the example code created by the init process with custom transformation files in `src/transformations/` based on provided requirements, using best practice guidance from this skill. - - -### Step 3: Deploy and Run - -```bash -# Deploy to workspace (dev by default) -databricks bundle deploy - -# Run pipeline -databricks bundle run my_pipeline_etl - -# Deploy to production -databricks bundle deploy --target prod -``` - -I can run these commands for you using the Bash tool. - -**For medallion architecture** (bronze/silver/gold), two approaches work: -- **Flat with naming** (template default): `bronze_*.sql`, `silver_*.sql`, `gold_*.sql` -- **Subdirectories**: `bronze/orders.sql`, `silver/cleaned.sql`, `gold/summary.sql` - -Both work with the `transformations/**` glob pattern. Choose based on preference. - -See **[8-project-initialization.md](8-project-initialization.md)** for complete details on bundle initialization, migration, and troubleshooting. - ---- - -## Alternative: Manual Workflow (Advanced) - -For rapid prototyping, experimentation, or when you prefer direct control without Asset Bundles, use the manual workflow with MCP tools. - -Use MCP tools to create, run, and iterate on **serverless SDP pipelines**. The **primary tool is `create_or_update_pipeline`** which handles the entire lifecycle. - -**IMPORTANT: Always create serverless pipelines (default).** Only use classic clusters if user explicitly requires R language, Spark RDD APIs, or JAR libraries. - -### Step 1: Write Pipeline Files Locally - -Create `.sql` or `.py` files in a local folder: - -``` -my_pipeline/ -├── bronze/ -│ ├── ingest_orders.sql # SQL (default for most cases) -│ └── ingest_events.py # Python (for complex logic) -├── silver/ -│ └── clean_orders.sql -└── gold/ - └── daily_summary.sql -``` - -**SQL Example** (`bronze/ingest_orders.sql`): -```sql -CREATE OR REFRESH STREAMING TABLE bronze_orders -CLUSTER BY (order_date) -AS -SELECT - *, - current_timestamp() AS _ingested_at, - _metadata.file_path AS _source_file -FROM read_files( - '/Volumes/catalog/schema/raw/orders/', - format => 'json', - schemaHints => 'order_id STRING, customer_id STRING, amount DECIMAL(10,2), order_date DATE' -); -``` - -**Python Example** (`bronze/ingest_events.py`): -```python -from pyspark import pipelines as dp -from pyspark.sql.functions import col, current_timestamp - -@dp.table(name="bronze_events", cluster_by=["event_date"]) -def bronze_events(): - return ( - spark.readStream.format("cloudFiles") - .option("cloudFiles.format", "json") - .load("/Volumes/catalog/schema/raw/events/") - .withColumn("_ingested_at", current_timestamp()) - .withColumn("_source_file", col("_metadata.file_path")) - ) -``` - -**Language Selection:** -- **Auto-detection**: I analyze your request for keywords: - - **SQL indicators**: "SQL", "sql files", "simple transformations", "aggregations", "materialized view", "CREATE OR REFRESH" - - **Python indicators**: "Python", ".py files", "UDF", "complex logic", "ML inference", "external API", "@dp.table", "pandas" -- **Prompt for clarification** when language intent is unclear or mixed -- **Use SQL** for: Transformations, aggregations, filtering, joins (most cases) -- **Generate ONE language** per request unless you explicitly ask for mixed pipeline - -See **[8-project-initialization.md](8-project-initialization.md)** for detailed language detection logic. - -### Step 2: Upload to Databricks Workspace - -```python -# MCP Tool: upload_folder -upload_folder( - local_folder="/path/to/my_pipeline", - workspace_folder="/Workspace/Users/user@example.com/my_pipeline" -) -``` - -### Step 3: Create/Update and Run Pipeline - -Use **`create_or_update_pipeline`** - the main entry point. It: -1. Searches for an existing pipeline with the same name (or uses `id` from `extra_settings`) -2. Creates a new pipeline or updates the existing one -3. Optionally starts a pipeline run -4. Optionally waits for completion and returns detailed results - -```python -# MCP Tool: create_or_update_pipeline -result = create_or_update_pipeline( - name="my_orders_pipeline", - root_path="/Workspace/Users/user@example.com/my_pipeline", - catalog="my_catalog", - schema="my_schema", - workspace_file_paths=[ - "/Workspace/Users/user@example.com/my_pipeline/bronze/ingest_orders.sql", - "/Workspace/Users/user@example.com/my_pipeline/silver/clean_orders.sql", - "/Workspace/Users/user@example.com/my_pipeline/gold/daily_summary.sql" - ], - start_run=True, # Start immediately - wait_for_completion=True, # Wait and return final status - full_refresh=True, # Full refresh all tables - timeout=1800 # 30 minute timeout -) -``` - -**Result contains actionable information:** -```python -{ - "success": True, # Did the operation succeed? - "pipeline_id": "abc-123", # Pipeline ID for follow-up operations - "pipeline_name": "my_orders_pipeline", - "created": True, # True if new, False if updated - "state": "COMPLETED", # COMPLETED, FAILED, TIMEOUT, etc. - "catalog": "my_catalog", # Target catalog - "schema": "my_schema", # Target schema - "duration_seconds": 45.2, # Time taken - "message": "Pipeline created and completed successfully in 45.2s. Tables written to my_catalog.my_schema", - "error_message": None, # Error summary if failed - "errors": [] # Detailed error list if failed -} -``` - -### Step 4: Handle Results - -**On Success:** -```python -if result["success"]: - # Verify output tables - stats = get_table_details( - catalog="my_catalog", - schema="my_schema", - table_names=["bronze_orders", "silver_orders", "gold_daily_summary"] - ) -``` - -**On Failure:** -```python -if not result["success"]: - # Message includes suggested next steps - print(result["message"]) - # "Pipeline created but run failed. State: FAILED. Error: Column 'amount' not found. - # Use get_pipeline_events(pipeline_id='abc-123') for full details." - - # Get detailed errors - events = get_pipeline_events(pipeline_id=result["pipeline_id"], max_results=50) -``` - -### Step 5: Iterate Until Working - -1. Review errors from result or `get_pipeline_events` -2. Fix issues in local files -3. Re-upload with `upload_folder` -4. Run `create_or_update_pipeline` again (it will update, not recreate) -5. Repeat until `result["success"] == True` - ---- - -## Quick Reference: MCP Tools - -### Primary Tool - -| Tool | Description | -|------|-------------| -| **`create_or_update_pipeline`** | **Main entry point.** Creates or updates pipeline, optionally runs and waits. Returns detailed status with `success`, `state`, `errors`, and actionable `message`. | - -### Pipeline Management - -| Tool | Description | -|------|-------------| -| `find_pipeline_by_name` | Find existing pipeline by name, returns pipeline_id | -| `get_pipeline` | Get pipeline configuration and current state | -| `start_update` | Start pipeline run (`validate_only=True` for dry run) | -| `get_update` | Poll update status (QUEUED, RUNNING, COMPLETED, FAILED) | -| `stop_pipeline` | Stop a running pipeline | -| `get_pipeline_events` | Get error messages for debugging failed runs | -| `delete_pipeline` | Delete a pipeline | - -### Supporting Tools - -| Tool | Description | -|------|-------------| -| `upload_folder` | Upload local folder to workspace (parallel) | -| `get_table_details` | Verify output tables have expected schema and row counts | -| `execute_sql` | Run ad-hoc SQL to inspect data | - ---- - -## Reference Documentation (Local) - -Load these for detailed patterns: - -- **[1-ingestion-patterns.md](1-ingestion-patterns.md)** - Auto Loader, Kafka, Event Hub, Kinesis, file formats -- **[2-streaming-patterns.md](2-streaming-patterns.md)** - Deduplication, windowing, stateful operations, joins -- **[3-scd-patterns.md](3-scd-patterns.md)** - Querying SCD Type 2 history tables, temporal joins -- **[4-performance-tuning.md](4-performance-tuning.md)** - Liquid Clustering, optimization, state management -- **[5-python-api.md](5-python-api.md)** - Modern `dp` API vs legacy `dlt` API comparison -- **[6-dlt-migration.md](6-dlt-migration.md)** - Migrating existing DLT pipelines to SDP -- **[7-advanced-configuration.md](7-advanced-configuration.md)** - `extra_settings` parameter reference and examples -- **[8-project-initialization.md](8-project-initialization.md)** - Using `databricks pipelines init`, Asset Bundles, language detection, and migration guides - ---- - -## Best Practices (2025) - -### Project Structure -- **Default to `databricks pipelines init`** for new projects (creates Asset Bundle) -- **Use Asset Bundles** for multi-environment deployments (dev/staging/prod) -- **Manual structure only** for quick prototypes or legacy migration -- **Medallion architecture**: Two approaches work with Asset Bundles: - - **Flat structure** (template default): `bronze_*.sql`, `silver_*.sql`, `gold_*.sql` in `transformations/` - - **Subdirectories**: `transformations/bronze/`, `transformations/silver/`, `transformations/gold/` - - Both work with the `transformations/**` glob pattern - choose based on team preference -- See **[8-project-initialization.md](8-project-initialization.md)** for project setup details - - -### Modern Defaults -- **CLUSTER BY** (Liquid Clustering), not PARTITION BY - see [4-performance-tuning.md](4-performance-tuning.md) -- **Raw `.sql`/`.py` files**, not notebooks -- **Serverless compute ONLY** - Do not use classic clusters unless explicitly required -- **Unity Catalog** (required for serverless) -- **read_files()** for cloud storage ingestion - see [1-ingestion-patterns.md](1-ingestion-patterns.md) - -### Reading Tables in Python - -**Modern SDP Best Practice:** -- Use `spark.read.table()` for batch reads -- Use `spark.readStream.table()` for streaming reads -- Don't use `dp.read()` or `dp.read_stream()` (old syntax, no longer documented) -- Don't use `dlt.read()` or `dlt.read_stream()` (legacy DLT API) - -**Key Point:** SDP automatically tracks table dependencies from standard Spark DataFrame operations. No special read APIs are needed. - -#### Three-Tier Identifier Resolution - -SDP supports three levels of table name qualification: - -| Level | Syntax | When to Use | -|-------|--------|-------------| -| **Unqualified** | `spark.read.table("my_table")` | Reading tables within the same pipeline's target catalog/schema (recommended) | -| **Partially-qualified** | `spark.read.table("other_schema.my_table")` | Reading from different schema in same catalog | -| **Fully-qualified** | `spark.read.table("other_catalog.other_schema.my_table")` | Reading from external catalogs/schemas | - -#### Option 1: Unqualified Names (Recommended for Pipeline Tables) - -**Best practice for tables within the same pipeline.** SDP resolves unqualified names to the pipeline's configured target catalog and schema. This makes code portable across environments (dev/prod). - -```python -@dp.table(name="silver_clean") -def silver_clean(): - # Reads from pipeline's target catalog/schema (e.g., dev_catalog.dev_schema.bronze_raw) - return ( - spark.read.table("bronze_raw") - .filter(F.col("valid") == True) - ) - -@dp.table(name="silver_events") -def silver_events(): - # Streaming read from same pipeline's bronze_events table - return ( - spark.readStream.table("bronze_events") - .withColumn("processed_at", F.current_timestamp()) - ) -``` - -#### Option 2: Pipeline Parameters (For External Sources) - -**Use `spark.conf.get()` to parameterize external catalog/schema references.** Define parameters in pipeline configuration, then reference them at the module level. - -```python -from pyspark import pipelines as dp -from pyspark.sql import functions as F - -# Get parameterized values at module level (evaluated once at pipeline start) -source_catalog = spark.conf.get("source_catalog") -source_schema = spark.conf.get("source_schema", "sales") # with default - -@dp.table(name="transaction_summary") -def transaction_summary(): - return ( - spark.read.table(f"{source_catalog}.{source_schema}.transactions") - .groupBy("account_id") - .agg( - F.count("txn_id").alias("txn_count"), - F.sum("txn_amount").alias("account_revenue") - ) - ) -``` - -**Configure parameters in pipeline settings:** -- **Asset Bundles**: Add to `pipeline.yml` under `configuration:` -- **Manual/MCP**: Pass via `extra_settings.configuration` dict - -```yaml -# In resources/my_pipeline.pipeline.yml -configuration: - source_catalog: "shared_catalog" - source_schema: "sales" -``` - -#### Option 3: Fully-Qualified Names (For Fixed External References) - -Use when referencing specific external tables that don't change across environments: - -```python -@dp.table(name="enriched_orders") -def enriched_orders(): - # Pipeline-internal table (unqualified) - orders = spark.read.table("bronze_orders") - - # External reference table (fully-qualified) - products = spark.read.table("shared_catalog.reference.products") - - return orders.join(products, "product_id") -``` - -#### Choosing the Right Approach - -| Scenario | Recommended Approach | -|----------|---------------------| -| Reading tables created in same pipeline | **Unqualified names** - portable, uses target catalog/schema | -| Reading from external source that varies by environment | **Pipeline parameters** - configurable per deployment | -| Reading from shared/reference tables with fixed location | **Fully-qualified names** - explicit and clear | -| Mixed pipeline (some internal, some external) | **Combine approaches** - unqualified for internal, parameters for external | - ---- - -## Common Issues - -| Issue | Solution | -|-------|----------| -| **Empty output tables** | Use `get_table_details` to verify, check upstream sources | -| **Pipeline stuck INITIALIZING** | Normal for serverless, wait a few minutes | -| **"Column not found"** | Check `schemaHints` match actual data | -| **Streaming reads fail** | Use `FROM STREAM(table)` for streaming sources | -| **Timeout during run** | Increase `timeout`, or use `wait_for_completion=False` and poll with `get_update` | -| **MV doesn't refresh** | Enable row tracking on source tables | -| **SCD2 schema errors** | Let SDP infer START_AT/END_AT columns | - -**For detailed errors**, the `result["message"]` from `create_or_update_pipeline` includes suggested next steps. Use `get_pipeline_events(pipeline_id=...)` for full stack traces. - ---- - -## Advanced Pipeline Configuration - -For advanced configuration options (development mode, continuous pipelines, custom clusters, notifications, Python dependencies, etc.), see **[7-advanced-configuration.md](7-advanced-configuration.md)**. - ---- - -## Platform Constraints - -### Serverless Pipeline Requirements (Default) -| Requirement | Details | -|-------------|---------| -| **Unity Catalog** | Required - serverless pipelines always use UC | -| **Workspace Region** | Must be in serverless-enabled region | -| **Serverless Terms** | Must accept serverless terms of use | -| **CDC Features** | Requires serverless (or Pro/Advanced with classic clusters) | - -### Serverless Limitations (When Classic Clusters Required) -| Limitation | Workaround | -|------------|-----------| -| **R language** | Not supported - use classic clusters if required | -| **Spark RDD APIs** | Not supported - use classic clusters if required | -| **JAR libraries** | Not supported - use classic clusters if required | -| **Maven coordinates** | Not supported - use classic clusters if required | -| **DBFS root access** | Limited - must use Unity Catalog external locations | -| **Global temp views** | Not supported | - -### General Constraints -| Constraint | Details | -|------------|---------| -| **Schema Evolution** | Streaming tables require full refresh for incompatible changes | -| **SQL Limitations** | PIVOT clause unsupported | -| **Sinks** | Python only, streaming only, append flows only | - -**Default to serverless** unless user explicitly requires R, RDD APIs, or JAR libraries. \ No newline at end of file diff --git a/.claude/skills/spark-python-data-source/SKILL.md b/.claude/skills/spark-python-data-source/SKILL.md new file mode 100644 index 00000000..898b9d2b --- /dev/null +++ b/.claude/skills/spark-python-data-source/SKILL.md @@ -0,0 +1,311 @@ +--- +name: spark-python-data-source +description: Use when building custom Spark data source connectors for external systems (databases, APIs, message queues), implementing batch/streaming readers/writers, or creating data source plugins for systems without native Spark support. Triggers - "build Spark data source", "create Spark connector", "implement Spark reader/writer", "connect Spark to [system]", "streaming data source" +--- + +# spark-python-data-source + +Build custom Python data sources for Apache Spark 4.0+ to read from and write to external systems in batch and streaming modes. + +## When to use + +Use when building Spark connectors for external systems that lack native support: +- External databases, APIs, message queues +- Custom file formats or protocols +- Real-time streaming data sources +- Systems requiring specialized authentication or protocols + +Triggers: "build Spark data source", "create Spark connector", "implement Spark reader/writer", "connect Spark to [system]", "streaming data source" + +## Instructions + +You are an experienced Spark developer building custom Python data sources following the PySpark DataSource API. Follow these principles and patterns: + +### Core Architecture + +Each data source follows a flat, single-level inheritance structure: + +1. **DataSource class** - Entry point returning readers/writers +2. **Base Reader/Writer classes** - Shared logic for options and data processing +3. **Batch classes** - Inherit from base + `DataSourceReader`/`DataSourceWriter` +4. **Stream classes** - Inherit from base + `DataSourceStreamReader`/`DataSourceStreamWriter` + +### Critical Design Principles + +**SIMPLE over CLEVER** - These are non-negotiable: + +✅ REQUIRED: +- Flat single-level inheritance only +- Direct implementations, no abstractions +- Explicit imports, explicit control flow +- Standard library first, minimal dependencies +- Simple classes with single responsibilities + +❌ FORBIDDEN: +- Abstract base classes or complex inheritance +- Factory patterns or dependency injection +- Decorators for cross-cutting concerns +- Complex configuration classes +- Async/await (unless absolutely necessary) +- Connection pooling or caching (unless critical) +- Generic "framework" code +- Premature optimization + +### Implementation Pattern + +```python +from pyspark.sql.datasource import ( + DataSource, DataSourceReader, DataSourceWriter, + DataSourceStreamReader, DataSourceStreamWriter +) + +# 1. DataSource class +class YourDataSource(DataSource): + @classmethod + def name(cls): + return "your-format" + + def __init__(self, options): + self.options = options + + def schema(self): + return self._infer_or_return_schema() + + def reader(self, schema): + return YourBatchReader(self.options, schema) + + def streamReader(self, schema): + return YourStreamReader(self.options, schema) + + def writer(self, schema, overwrite): + return YourBatchWriter(self.options, schema) + + def streamWriter(self, schema, overwrite): + return YourStreamWriter(self.options, schema) + +# 2. Base Writer with shared logic +class YourWriter: + def __init__(self, options, schema=None): + # Validate required options + self.url = options.get("url") + assert self.url, "url is required" + self.batch_size = int(options.get("batch_size", "50")) + self.schema = schema + + def write(self, iterator): + # Import libraries here for partition execution + import requests + from pyspark import TaskContext + + context = TaskContext.get() + partition_id = context.partitionId() + + msgs = [] + cnt = 0 + + for row in iterator: + cnt += 1 + msgs.append(row.asDict()) + + if len(msgs) >= self.batch_size: + self._send_batch(msgs) + msgs = [] + + if msgs: + self._send_batch(msgs) + + return SimpleCommitMessage(partition_id=partition_id, count=cnt) + + def _send_batch(self, msgs): + # Implement send logic + pass + +# 3. Batch Writer +class YourBatchWriter(YourWriter, DataSourceWriter): + pass + +# 4. Stream Writer +class YourStreamWriter(YourWriter, DataSourceStreamWriter): + def commit(self, messages, batchId): + pass + + def abort(self, messages, batchId): + pass + +# 5. Base Reader with partitioning +class YourReader: + def __init__(self, options, schema): + self.url = options.get("url") + assert self.url, "url is required" + self.schema = schema + + def partitions(self): + # Return list of partitions for parallel reading + return [YourPartition(0, start, end)] + + def read(self, partition): + # Import here for executor execution + import requests + + response = requests.get(f"{self.url}?start={partition.start}") + for item in response.json(): + yield tuple(item.values()) + +# 6. Batch Reader +class YourBatchReader(YourReader, DataSourceReader): + pass + +# 7. Stream Reader +class YourStreamReader(YourReader, DataSourceStreamReader): + def initialOffset(self): + return {"offset": "0"} + + def latestOffset(self): + return {"offset": str(self._get_latest())} + + def partitions(self, start, end): + return [YourPartition(0, start["offset"], end["offset"])] + + def commit(self, end): + pass +``` + +### Project Setup + +```bash +# Create project +poetry new your-datasource +cd your-datasource +poetry add pyspark pytest pytest-spark + +# Development commands - CRITICAL: Always use 'poetry run' +poetry run pytest # Run tests +poetry run ruff check src/ # Lint +poetry run ruff format src/ # Format +poetry build # Build wheel +``` + +### Registration and Usage + +```python +# Register +from your_package import YourDataSource +spark.dataSource.register(YourDataSource) + +# Batch read +df = spark.read.format("your-format").option("url", "...").load() + +# Batch write +df.write.format("your-format").option("url", "...").save() + +# Streaming read +df = spark.readStream.format("your-format").option("url", "...").load() + +# Streaming write +df.writeStream.format("your-format").option("url", "...").start() +``` + +### Key Implementation Decisions + +**Partitioning Strategy**: Choose based on data source characteristics +- Time-based: For APIs with temporal data (see [partitioning-patterns.md](references/partitioning-patterns.md)) +- Token-range: For distributed databases (see [partitioning-patterns.md](references/partitioning-patterns.md)) +- ID-range: For paginated APIs + +**Authentication**: Support multiple methods in priority order +- Databricks Unity Catalog credentials +- Cloud default credentials (managed identity) +- Explicit credentials (service principal, API key, username/password) +- See [authentication-patterns.md](references/authentication-patterns.md) + +**Type Conversion**: Map between Spark and external types +- Handle nulls, timestamps, UUIDs, collections +- See [type-conversion.md](references/type-conversion.md) + +**Streaming Offsets**: Design for exactly-once semantics +- JSON-serializable offset class +- Non-overlapping partition boundaries +- See [streaming-patterns.md](references/streaming-patterns.md) + +**Error Handling**: Implement retries and resilience +- Exponential backoff for retryable errors +- Circuit breakers for cascading failures +- See [error-handling.md](references/error-handling.md) + +### Testing Approach + +```python +import pytest +from unittest.mock import patch, Mock + +@pytest.fixture +def spark(): + from pyspark.sql import SparkSession + return SparkSession.builder.master("local[2]").getOrCreate() + +def test_data_source_name(): + assert YourDataSource.name() == "your-format" + +def test_writer_sends_data(spark): + with patch('requests.post') as mock_post: + mock_post.return_value = Mock(status_code=200) + + df = spark.createDataFrame([(1, "test")], ["id", "value"]) + df.write.format("your-format").option("url", "http://api").save() + + assert mock_post.called +``` + +### Code Review Checklist + +Before implementing, ask: +1. Is this the simplest way to solve this problem? +2. Would a new developer understand this immediately? +3. Am I adding abstraction for real needs vs hypothetical flexibility? +4. Can I solve this with standard library? +5. Does this follow the established flat pattern? + +### Common Mistakes to Avoid + +- Creating abstract base classes for "reusability" +- Adding configuration frameworks or dependency injection +- Premature optimization before measuring performance +- Complex error handling hierarchies +- Importing heavy libraries at module level (import in methods) +- Using `python` command directly (always use `poetry run`) + +### Reference Implementations + +Study these for real-world patterns: +- [cyber-spark-data-connectors](https://github.com/alexott/cyber-spark-data-connectors) - Sentinel, Splunk, REST +- [spark-cassandra-data-source](https://github.com/alexott/spark-cassandra-data-source) - Token-range partitioning +- [pyspark-hubspot](https://github.com/dgomez04/pyspark-hubspot) - REST API pagination +- [pyspark-mqtt](https://github.com/databricks-industry-solutions/python-data-sources/tree/main/mqtt) - Streaming with TLS + +## Usage + +``` +Create a Spark data source for reading from MongoDB with sharding support +Build a streaming connector for RabbitMQ with at-least-once delivery +Implement a batch writer for Snowflake with staged uploads +Write a data source for REST API with OAuth2 authentication and pagination +``` + +## Related + +- databricks-testing: Test data sources on Databricks clusters +- databricks-spark-declarative-pipelines: Use custom sources in DLT pipelines +- python-dev: Python development best practices + +## References + +- [partitioning-patterns.md](references/partitioning-patterns.md) - Parallel reading strategies +- [authentication-patterns.md](references/authentication-patterns.md) - Multi-method auth implementations +- [type-conversion.md](references/type-conversion.md) - Bidirectional type mapping +- [streaming-patterns.md](references/streaming-patterns.md) - Offset management and watermarking +- [error-handling.md](references/error-handling.md) - Retries, circuit breakers, resilience +- [testing-patterns.md](references/testing-patterns.md) - Unit and integration testing +- [production-patterns.md](references/production-patterns.md) - Observability, security, validation +- [Official Databricks Documentation](https://docs.databricks.com/aws/en/pyspark/datasources) +- [Apache Spark Python DataSource Tutorial](https://spark.apache.org/docs/latest/api/python/tutorial/sql/python_data_source.html) +- [awesome-python-datasources](https://github.com/allisonwang-db/awesome-python-datasources) - directory of available implementations. diff --git a/.claude/skills/spark-python-data-source/references/authentication-patterns.md b/.claude/skills/spark-python-data-source/references/authentication-patterns.md new file mode 100644 index 00000000..700f516e --- /dev/null +++ b/.claude/skills/spark-python-data-source/references/authentication-patterns.md @@ -0,0 +1,361 @@ +# Authentication Patterns + +Multi-method authentication strategies with clear priority ordering. + +## Priority-Based Authentication + +Support multiple authentication methods with fallback: + +```python +class AuthenticatedDataSource(DataSource): + def __init__(self, options): + # Priority 1: Databricks Unity Catalog credential + self.databricks_credential = options.get("databricks_credential") + + # Priority 2: Cloud default credential (managed identity) + self.default_credential = options.get("default_credential", "false").lower() == "true" + + # Priority 3: Service principal + self.tenant_id = options.get("tenant_id") + self.client_id = options.get("client_id") + self.client_secret = options.get("client_secret") + + # Priority 4: API key + self.api_key = options.get("api_key") + + # Priority 5: Username/password + self.username = options.get("username") + self.password = options.get("password") + + # Validate at least one method is configured + self._validate_auth() + + def _validate_auth(self): + """Validate at least one auth method is configured.""" + has_databricks_cred = bool(self.databricks_credential) + has_default_cred = self.default_credential + has_service_principal = all([self.tenant_id, self.client_id, self.client_secret]) + has_api_key = bool(self.api_key) + has_basic_auth = bool(self.username and self.password) + + if not any([has_databricks_cred, has_default_cred, has_service_principal, + has_api_key, has_basic_auth]): + raise AssertionError( + "Authentication required. Provide one of: " + "'databricks_credential', 'default_credential=true', " + "'tenant_id/client_id/client_secret', 'api_key', or 'username/password'" + ) +``` + +## Azure Authentication + +### Unity Catalog Service Credential + +```python +def _get_azure_credential_uc(credential_name): + """Get credential from Unity Catalog.""" + import databricks.service_credentials + + return databricks.service_credentials.getServiceCredentialsProvider(credential_name) +``` + +### Default Credential (Managed Identity) + +```python +def _get_azure_credential_default(authority=None): + """Get DefaultAzureCredential for managed identity.""" + from azure.identity import DefaultAzureCredential + + if authority: + return DefaultAzureCredential(authority=authority) + return DefaultAzureCredential() +``` + +### Service Principal + +```python +def _get_azure_credential_sp(tenant_id, client_id, client_secret, authority=None): + """Get service principal credential.""" + from azure.identity import ClientSecretCredential + + if authority: + return ClientSecretCredential( + tenant_id=tenant_id, + client_id=client_id, + client_secret=client_secret, + authority=authority + ) + return ClientSecretCredential( + tenant_id=tenant_id, + client_id=client_id, + client_secret=client_secret + ) +``` + +### Multi-Cloud Support + +```python +def _get_azure_cloud_config(cloud_name): + """Get cloud-specific endpoints and authorities.""" + from azure.identity import AzureAuthorityHosts + + cloud_configs = { + "public": (None, None), + "government": ( + AzureAuthorityHosts.AZURE_GOVERNMENT, + "https://api.loganalytics.us" + ), + "china": ( + AzureAuthorityHosts.AZURE_CHINA, + "https://api.loganalytics.azure.cn" + ), + } + + cloud = (cloud_name or "public").lower().strip() + + if cloud not in cloud_configs: + valid = ", ".join(cloud_configs.keys()) + raise ValueError(f"Invalid cloud '{cloud_name}'. Valid: {valid}") + + return cloud_configs[cloud] + +def _create_azure_client_with_cloud(options): + """Create Azure client with cloud-specific configuration.""" + cloud_name = options.get("azure_cloud", "public") + authority, endpoint = _get_azure_cloud_config(cloud_name) + + # Get credential based on priority + credential = _get_credential(options, authority) + + # Create client with cloud-specific endpoint + from azure.monitor.query import LogsQueryClient + + if endpoint: + return LogsQueryClient(credential, endpoint=endpoint) + return LogsQueryClient(credential) +``` + +## API Key Authentication + +### Header-Based + +```python +def _get_api_key_auth(api_key): + """Get API key authentication headers.""" + return {"Authorization": f"Bearer {api_key}"} + +def _create_session_with_api_key(api_key): + """Create requests session with API key.""" + import requests + + session = requests.Session() + session.headers.update({"Authorization": f"Bearer {api_key}"}) + return session +``` + +### Query Parameter-Based + +```python +def _build_url_with_api_key(base_url, api_key): + """Add API key as query parameter.""" + from urllib.parse import urlencode + + params = {"api_key": api_key} + return f"{base_url}?{urlencode(params)}" +``` + +## Basic Authentication + +```python +def _get_basic_auth(username, password): + """Get HTTP Basic Auth.""" + from requests.auth import HTTPBasicAuth + return HTTPBasicAuth(username, password) + +def _create_session_with_basic_auth(username, password): + """Create session with basic auth.""" + import requests + + session = requests.Session() + session.auth = (username, password) + return session +``` + +## OAuth2 Authentication + +### Client Credentials Flow + +```python +def _get_oauth2_token(token_url, client_id, client_secret, scope): + """Get OAuth2 token using client credentials.""" + import requests + + response = requests.post( + token_url, + data={ + "grant_type": "client_credentials", + "client_id": client_id, + "client_secret": client_secret, + "scope": scope + } + ) + response.raise_for_status() + + return response.json()["access_token"] + +class OAuth2Writer: + def __init__(self, options): + self.token_url = options["token_url"] + self.client_id = options["client_id"] + self.client_secret = options["client_secret"] + self.scope = options.get("scope", "") + self._token = None + self._token_expiry = None + + def _get_valid_token(self): + """Get valid token, refresh if expired.""" + from datetime import datetime, timedelta + + if not self._token or datetime.now() >= self._token_expiry: + self._token = _get_oauth2_token( + self.token_url, + self.client_id, + self.client_secret, + self.scope + ) + # Assume 1 hour expiry if not provided + self._token_expiry = datetime.now() + timedelta(hours=1) + + return self._token + + def write(self, iterator): + """Write with OAuth2 authentication.""" + import requests + + token = self._get_valid_token() + headers = {"Authorization": f"Bearer {token}"} + + for row in iterator: + requests.post(self.url, json=row.asDict(), headers=headers) +``` + +## Complete Authentication Factory + +```python +def get_credential(options): + """ + Get credential based on configuration priority. + + Priority: + 1. databricks_credential + 2. default_credential + 3. Service principal (tenant_id/client_id/client_secret) + 4. API key + 5. Username/password + """ + + # Priority 1: Databricks credential + if options.get("databricks_credential"): + import databricks.service_credentials + return databricks.service_credentials.getServiceCredentialsProvider( + options["databricks_credential"] + ) + + # Priority 2: Cloud default credential + if options.get("default_credential", "false").lower() == "true": + authority = options.get("authority") + if authority: + from azure.identity import DefaultAzureCredential + return DefaultAzureCredential(authority=authority) + from azure.identity import DefaultAzureCredential + return DefaultAzureCredential() + + # Priority 3: Service principal + if all(k in options for k in ["tenant_id", "client_id", "client_secret"]): + from azure.identity import ClientSecretCredential + authority = options.get("authority") + if authority: + return ClientSecretCredential( + tenant_id=options["tenant_id"], + client_id=options["client_id"], + client_secret=options["client_secret"], + authority=authority + ) + return ClientSecretCredential( + tenant_id=options["tenant_id"], + client_id=options["client_id"], + client_secret=options["client_secret"] + ) + + # Priority 4: API key + if "api_key" in options: + return {"Authorization": f"Bearer {options['api_key']}"} + + # Priority 5: Basic auth + if "username" in options and "password" in options: + from requests.auth import HTTPBasicAuth + return HTTPBasicAuth(options["username"], options["password"]) + + raise ValueError("No valid authentication method configured") +``` + +## Security Best Practices + +### Never Log Sensitive Values + +```python +class SecureDataSource(DataSource): + def __init__(self, options): + self._sensitive_keys = { + "password", "api_key", "client_secret", "token", "access_token" + } + + # Store actual values + self.options = options + + # Create sanitized version for logging + self._safe_options = self._sanitize_options(options) + + def _sanitize_options(self, options): + """Mask sensitive values for logging.""" + safe = {} + for key, value in options.items(): + if key.lower() in self._sensitive_keys: + safe[key] = "***REDACTED***" + else: + safe[key] = value + return safe + + def __repr__(self): + return f"SecureDataSource({self._safe_options})" +``` + +### Use Secrets Management + +```python +def _load_secrets_from_dbutils(scope, keys): + """Load secrets from Databricks secrets.""" + try: + from pyspark.dbutils import DBUtils + from pyspark.sql import SparkSession + + spark = SparkSession.getActiveSession() + dbutils = DBUtils(spark) + + secrets = {} + for key in keys: + secrets[key] = dbutils.secrets.get(scope=scope, key=key) + + return secrets + + except Exception as e: + raise ValueError(f"Failed to load secrets from scope '{scope}': {e}") + +# Usage +if "secret_scope" in options: + secrets = _load_secrets_from_dbutils( + options["secret_scope"], + ["password", "api_key"] + ) + options.update(secrets) +``` diff --git a/.claude/skills/spark-python-data-source/references/error-handling.md b/.claude/skills/spark-python-data-source/references/error-handling.md new file mode 100644 index 00000000..01bbf2f9 --- /dev/null +++ b/.claude/skills/spark-python-data-source/references/error-handling.md @@ -0,0 +1,432 @@ +# Error Handling and Resilience + +Patterns for retries, circuit breakers, and graceful degradation. + +## Exponential Backoff + +Retry with exponential backoff for transient failures: + +```python +def write_with_retry(self, iterator): + """Write with exponential backoff.""" + import time + + max_retries = int(self.options.get("max_retries", "5")) + initial_backoff = float(self.options.get("initial_backoff", "1.0")) + max_backoff = float(self.options.get("max_backoff", "60.0")) + + for row in iterator: + retry_count = 0 + + while retry_count <= max_retries: + try: + self._send_data(row) + break # Success + + except Exception as e: + if not self._is_retryable_error(e): + # Non-retryable error - fail immediately + raise + + if retry_count >= max_retries: + # Max retries exceeded + raise Exception(f"Max retries ({max_retries}) exceeded: {e}") + + # Calculate backoff with exponential growth + backoff = min(initial_backoff * (2 ** retry_count), max_backoff) + time.sleep(backoff) + retry_count += 1 + +def _is_retryable_error(self, error): + """Determine if error is retryable.""" + from requests.exceptions import RequestException, Timeout, ConnectionError + + # Network errors are retryable + if isinstance(error, (Timeout, ConnectionError)): + return True + + # HTTP errors + if hasattr(error, 'response') and error.response: + status_code = error.response.status_code + # Retry on 429 (throttling) and 5xx (server errors) + if status_code == 429 or 500 <= status_code < 600: + return True + + return False +``` + +## Retry with Throttling Respect + +Handle API rate limiting with Retry-After header: + +```python +def write_with_throttling(self, iterator): + """Write with respect for rate limits.""" + import time + from requests.exceptions import HTTPError + + for row in iterator: + max_attempts = 5 + attempt = 0 + + while attempt < max_attempts: + try: + self._send_data(row) + break + + except HTTPError as e: + if e.response.status_code == 429: + # Throttled - respect Retry-After header + retry_after = self._get_retry_after(e.response) + time.sleep(retry_after) + attempt += 1 + else: + raise + + if attempt >= max_attempts: + raise Exception("Max retry attempts for throttling exceeded") + +def _get_retry_after(self, response): + """Extract retry delay from Retry-After header.""" + retry_after = response.headers.get("Retry-After") + + if retry_after: + try: + # Try as seconds (int) + return int(retry_after) + except ValueError: + # Try as HTTP date + from datetime import datetime + try: + retry_date = datetime.strptime(retry_after, "%a, %d %b %Y %H:%M:%S GMT") + delay = (retry_date - datetime.utcnow()).total_seconds() + return max(0, delay) + except ValueError: + pass + + # Default fallback + return 1.0 +``` + +## Circuit Breaker + +Prevent cascading failures with circuit breaker pattern: + +```python +class CircuitBreaker: + """Circuit breaker to prevent cascading failures.""" + + def __init__(self, threshold=10, timeout=300): + self.threshold = threshold # failures before opening + self.timeout = timeout # seconds before trying again + self.consecutive_failures = 0 + self.circuit_open = False + self.circuit_open_until = None + + def record_success(self): + """Record successful operation.""" + self.consecutive_failures = 0 + + def record_failure(self): + """Record failed operation.""" + from datetime import datetime, timedelta + + self.consecutive_failures += 1 + + if self.consecutive_failures >= self.threshold: + self.circuit_open = True + self.circuit_open_until = datetime.now() + timedelta(seconds=self.timeout) + + def is_open(self): + """Check if circuit is open.""" + from datetime import datetime + + if self.circuit_open: + if datetime.now() >= self.circuit_open_until: + # Timeout expired - try again + self.circuit_open = False + self.consecutive_failures = 0 + return False + return True + + return False + +class ResilientWriter: + def __init__(self, options): + self.circuit_breaker = CircuitBreaker( + threshold=int(options.get("circuit_breaker_threshold", "10")), + timeout=int(options.get("circuit_breaker_timeout", "300")) + ) + + def write(self, iterator): + """Write with circuit breaker protection.""" + for row in iterator: + if self.circuit_breaker.is_open(): + raise Exception("Circuit breaker open - too many failures") + + try: + self._send_data(row) + self.circuit_breaker.record_success() + + except Exception as e: + self.circuit_breaker.record_failure() + raise +``` + +## Graceful Degradation + +Handle partial failures and fallback strategies: + +```python +def read_with_fallback(self, partition): + """Read with fallback to secondary sources.""" + try: + # Try primary source + yield from self._read_primary(partition) + + except ConnectionError as e: + # Primary failed - try secondary + if self.secondary_endpoint: + print(f"Primary failed, using secondary: {e}") + yield from self._read_secondary(partition) + else: + raise + + except TimeoutError as e: + # Timeout - try with smaller partitions + if partition.can_subdivide(): + print(f"Timeout, subdividing: {e}") + for sub_partition in partition.subdivide(): + yield from self.read(sub_partition) + else: + raise + + except PartialResultError as e: + # Partial results - log warning and continue + print(f"Warning: Partial results for partition {partition.id}: {e}") + yield from e.partial_results +``` + +## Bulk Operation Error Handling + +Handle errors in bulk operations: + +```python +def write_batch_with_error_handling(self, iterator): + """Write in batches with individual error tracking.""" + from cassandra.concurrent import execute_concurrent_with_args + + batch_size = int(self.options.get("batch_size", "1000")) + fail_on_first_error = self.options.get("fail_on_first_error", "true").lower() == "true" + + batch_params = [] + failed_rows = [] + + for row in iterator: + batch_params.append(self._row_to_params(row)) + + if len(batch_params) >= batch_size: + # Execute batch + results = execute_concurrent_with_args( + self.session, + self.prepared_statement, + batch_params, + concurrency=100, + raise_on_first_error=fail_on_first_error + ) + + # Check for failures + for success, result_or_error in results: + if not success: + failed_rows.append((batch_params[i], result_or_error)) + + batch_params = [] + + # Final batch + if batch_params: + results = execute_concurrent_with_args( + self.session, + self.prepared_statement, + batch_params, + concurrency=100, + raise_on_first_error=fail_on_first_error + ) + + for i, (success, result_or_error) in enumerate(results): + if not success: + failed_rows.append((batch_params[i], result_or_error)) + + # Handle failed rows + if failed_rows: + if fail_on_first_error: + raise Exception(f"{len(failed_rows)} rows failed to write") + else: + # Log failures but continue + print(f"Warning: {len(failed_rows)} rows failed to write") +``` + +## Dead Letter Queue + +Store failed records for later processing: + +```python +class DeadLetterQueueWriter: + """Writer with dead letter queue for failed records.""" + + def __init__(self, options): + self.dlq_path = options.get("dlq_path") + self.dlq_enabled = bool(self.dlq_path) + + def write(self, iterator): + """Write with DLQ support.""" + from datetime import datetime + import json + + successful = 0 + failed = 0 + + for row in iterator: + try: + self._send_data(row) + successful += 1 + + except Exception as e: + failed += 1 + + if self.dlq_enabled: + self._write_to_dlq(row, e) + else: + raise + + return { + "successful": successful, + "failed": failed + } + + def _write_to_dlq(self, row, error): + """Write failed record to dead letter queue.""" + from datetime import datetime + import json + import os + + dlq_record = { + "timestamp": datetime.now().isoformat(), + "error": str(error), + "error_type": type(error).__name__, + "row": row.asDict() + } + + # Append to DLQ file + os.makedirs(os.path.dirname(self.dlq_path), exist_ok=True) + + with open(self.dlq_path, 'a') as f: + f.write(json.dumps(dlq_record) + '\n') +``` + +## Timeout Handling + +Enforce operation timeouts: + +```python +import signal +from contextlib import contextmanager + +class TimeoutError(Exception): + pass + +def timeout_handler(signum, frame): + raise TimeoutError("Operation timed out") + +@contextmanager +def timeout(seconds): + """Context manager for operation timeout.""" + signal.signal(signal.SIGALRM, timeout_handler) + signal.alarm(seconds) + try: + yield + finally: + signal.alarm(0) + +class TimeoutWriter: + def write(self, iterator): + """Write with per-row timeout.""" + timeout_seconds = int(self.options.get("write_timeout", "30")) + + for row in iterator: + try: + with timeout(timeout_seconds): + self._send_data(row) + + except TimeoutError: + print(f"Write timeout after {timeout_seconds}s") + raise +``` + +## Error Aggregation + +Collect and report errors systematically: + +```python +class ErrorAggregator: + """Aggregate errors for batch reporting.""" + + def __init__(self): + self.errors = [] + self.error_counts = {} + + def record_error(self, error, context=None): + """Record an error with context.""" + error_type = type(error).__name__ + error_msg = str(error) + + self.errors.append({ + "type": error_type, + "message": error_msg, + "context": context + }) + + # Count by type + self.error_counts[error_type] = self.error_counts.get(error_type, 0) + 1 + + def get_summary(self): + """Get error summary.""" + return { + "total_errors": len(self.errors), + "by_type": self.error_counts, + "sample_errors": self.errors[:10] # First 10 + } + +class ErrorAwareWriter: + def write(self, iterator): + """Write with error aggregation.""" + aggregator = ErrorAggregator() + successful = 0 + + for i, row in enumerate(iterator): + try: + self._send_data(row) + successful += 1 + + except Exception as e: + aggregator.record_error(e, context={"row_index": i}) + + # Report summary + if aggregator.errors: + summary = aggregator.get_summary() + print(f"Completed with {successful} success, {summary['total_errors']} errors") + print(f"Error breakdown: {summary['by_type']}") + + if summary['total_errors'] > successful: + raise Exception(f"Too many errors: {summary}") +``` + +## Best Practices + +1. **Retry Only Transient Errors**: Don't retry client errors (4xx) +2. **Respect Rate Limits**: Use Retry-After headers and backoff +3. **Circuit Breakers**: Prevent cascading failures in distributed systems +4. **Timeout Operations**: Set reasonable timeouts to prevent hangs +5. **Log Errors**: Capture error context for debugging +6. **Dead Letter Queues**: Store failed records for later analysis +7. **Monitor Failure Rates**: Alert on anomalous error rates +8. **Graceful Degradation**: Continue with partial results when appropriate diff --git a/.claude/skills/spark-python-data-source/references/partitioning-patterns.md b/.claude/skills/spark-python-data-source/references/partitioning-patterns.md new file mode 100644 index 00000000..699e75a5 --- /dev/null +++ b/.claude/skills/spark-python-data-source/references/partitioning-patterns.md @@ -0,0 +1,319 @@ +# Partitioning Patterns + +Strategies for distributing reads across Spark executors for parallel processing. + +## Time-Based Partitioning + +For APIs with temporal data or streaming sources. + +### Fixed Duration Partitions + +```python +from pyspark.sql.datasource import InputPartition +from datetime import datetime, timedelta + +class TimeRangePartition(InputPartition): + def __init__(self, start_time, end_time): + self.start_time = start_time + self.end_time = end_time + +class TimeBasedReader: + def __init__(self, options, schema): + self.partition_duration = int(options.get("partition_duration", "3600")) # seconds + # Parse start/end time from options + + def partitions(self): + """Split time range into fixed-duration partitions.""" + partitions = [] + current = self.start_time + delta = timedelta(seconds=self.partition_duration) + + while current < self.end_time: + next_time = min(current + delta, self.end_time) + partitions.append(TimeRangePartition(current, next_time)) + current = next_time + + return partitions + + def read(self, partition): + """Query data for specific time range.""" + response = self._query_api( + start=partition.start_time, + end=partition.end_time + ) + for item in response: + yield self._convert_to_row(item) +``` + +### Auto-Subdividing for Large Results + +Handle APIs with result size limits by automatically subdividing large partitions: + +```python +class AutoSubdivideReader: + def __init__(self, options, schema): + self.min_partition_seconds = int(options.get("min_partition_seconds", "60")) + self.max_retries = int(options.get("max_retries", "5")) + + def read(self, partition): + """Read with automatic subdivision on size limit errors.""" + try: + response = self._execute_query(partition.start_time, partition.end_time) + + # Check if response is partial due to size limits + if self._is_size_limit_error(response): + yield from self._read_with_subdivision(partition) + return + + yield from self._process_response(response) + + except Exception as e: + raise + + def _read_with_subdivision(self, partition): + """Recursively subdivide large partitions.""" + duration = (partition.end_time - partition.start_time).total_seconds() + + if duration <= self.min_partition_seconds: + raise Exception( + f"Cannot subdivide further. Duration {duration}s at minimum. " + f"Consider more selective query or increase min_partition_seconds." + ) + + # Split in half + midpoint = partition.start_time + timedelta(seconds=duration / 2) + + first_half = TimeRangePartition(partition.start_time, midpoint) + second_half = TimeRangePartition(midpoint, partition.end_time) + + yield from self.read(first_half) + yield from self.read(second_half) + + def _is_size_limit_error(self, response): + """Detect result size limit errors.""" + size_limit_codes = [ + "QueryExecutionResultSizeLimitExceeded", + "ResponsePayloadTooLarge", + "E_QUERY_RESULT_SET_TOO_LARGE", + ] + + if hasattr(response, "error") and response.error: + if response.error.code in size_limit_codes: + return True + + error_str = str(response.error).lower() + return any(p in error_str for p in ["size limit", "too large", "exceed"]) + + return False +``` + +## Token-Range Partitioning + +For distributed databases using consistent hashing (Cassandra, ScyllaDB). + +### Cassandra Token-Range Pattern + +```python +from collections import namedtuple + +class TokenRangePartition(InputPartition): + def __init__(self, partition_id, start_token, end_token, pk_columns, + is_wrap_around=False, min_token=None): + self.partition_id = partition_id + self.start_token = start_token # None = unbounded + self.end_token = end_token # None = unbounded + self.pk_columns = pk_columns + self.is_wrap_around = is_wrap_around + self.min_token = min_token + +class TokenRangeReader: + def _get_token_ranges(self, token_map): + """Compute token ranges from cluster token ring.""" + if not token_map or not token_map.ring: + return [] + + TokenRange = namedtuple('TokenRange', ['start', 'end']) + ranges = [] + ring = sorted(token_map.ring) + + for i in range(len(ring)): + start = ring[i] + end = ring[(i + 1) % len(ring)] # Wrap around + ranges.append(TokenRange(start=start, end=end)) + + return ranges + + def partitions(self): + """Create partitions following TokenRangesScan.java logic.""" + if not self.token_ranges: + return [] + + partitions = [] + sorted_ranges = sorted(self.token_ranges) + partition_id = 0 + + min_token_obj = sorted_ranges[0].start + min_token = min_token_obj.value if hasattr(min_token_obj, 'value') else str(min_token_obj) + + for i, token_range in enumerate(sorted_ranges): + start_value = token_range.start.value if hasattr(token_range.start, 'value') else str(token_range.start) + end_value = token_range.end.value if hasattr(token_range.end, 'value') else str(token_range.end) + + if start_value == end_value: + # Case 1: Single-node cluster (entire ring) + partition = TokenRangePartition( + partition_id=partition_id, + start_token=min_token, + end_token=None, # Unbounded + pk_columns=self.pk_columns, + is_wrap_around=True, + min_token=min_token + ) + partitions.append(partition) + partition_id += 1 + + elif i == 0: + # Case 2: First range - split into TWO partitions + # Partition 1: token <= minToken (wrap-around) + partition1 = TokenRangePartition( + partition_id=partition_id, + start_token=None, + end_token=min_token, + pk_columns=self.pk_columns, + is_wrap_around=True, + min_token=min_token + ) + partitions.append(partition1) + partition_id += 1 + + # Partition 2: token > start AND token <= end + partition2 = TokenRangePartition( + partition_id=partition_id, + start_token=start_value, + end_token=end_value, + pk_columns=self.pk_columns, + is_wrap_around=False, + min_token=min_token + ) + partitions.append(partition2) + partition_id += 1 + + elif end_value == min_token: + # Case 3: Range ending at minToken - no upper bound + partition = TokenRangePartition( + partition_id=partition_id, + start_token=start_value, + end_token=None, + pk_columns=self.pk_columns, + is_wrap_around=False, + min_token=min_token + ) + partitions.append(partition) + partition_id += 1 + + else: + # Case 4: Normal range - both bounds + partition = TokenRangePartition( + partition_id=partition_id, + start_token=start_value, + end_token=end_value, + pk_columns=self.pk_columns, + is_wrap_around=False, + min_token=min_token + ) + partitions.append(partition) + partition_id += 1 + + return partitions + + def read(self, partition): + """Build query with token range predicates.""" + pk_cols_str = ", ".join(partition.pk_columns) + + # Build WHERE clause based on bounds + if partition.start_token is None: + where_clause = f"token({pk_cols_str}) <= {partition.end_token}" + elif partition.end_token is None: + where_clause = f"token({pk_cols_str}) > {partition.start_token}" + else: + where_clause = ( + f"token({pk_cols_str}) > {partition.start_token} AND " + f"token({pk_cols_str}) <= {partition.end_token}" + ) + + query = f"SELECT {columns} FROM {table} WHERE {where_clause}" + + # Execute and yield results + for row in self._execute_query(query): + yield row +``` + +## ID-Range Partitioning + +For APIs with pagination or sequential IDs. + +```python +class IdRangePartition(InputPartition): + def __init__(self, partition_id, start_id, end_id): + self.partition_id = partition_id + self.start_id = start_id + self.end_id = end_id + +class IdRangeReader: + def __init__(self, options, schema): + self.num_partitions = int(options.get("num_partitions", "4")) + self.page_size = int(options.get("page_size", "1000")) + + def partitions(self): + """Split by ID ranges.""" + # Get total count from API + total = self._get_total_count() + partition_size = total // self.num_partitions + + partitions = [] + for i in range(self.num_partitions): + start_id = i * partition_size + end_id = (i + 1) * partition_size if i < self.num_partitions - 1 else total + partitions.append(IdRangePartition(i, start_id, end_id)) + + return partitions + + def read(self, partition): + """Paginate through ID range.""" + current_id = partition.start_id + + while current_id < partition.end_id: + response = self._query_api( + start_id=current_id, + limit=self.page_size + ) + + for item in response.items: + yield self._convert_to_row(item) + + current_id += self.page_size +``` + +## Partition Count Guidelines + +**For Batch Reads:** +- Start with 2-4x number of executor cores +- Adjust based on data volume and partition size +- Consider external system load limits + +**For Streaming Reads:** +- Use fixed-duration partitions (e.g., 1 hour) +- Let Spark handle parallelism across micro-batches +- Balance latency vs throughput + +**For Token-Range:** +- One partition per token range (determined by cluster) +- Naturally distributes based on data distribution +- May split first range into two partitions + +## Performance Considerations + +1. **Partition Size**: Aim for 128MB - 1GB per partition +2. **API Rate Limits**: Respect rate limits with concurrency controls +3. **Network Overhead**: Larger partitions reduce round-trips +4. **Skew Handling**: Monitor for data skew, repartition if needed diff --git a/.claude/skills/spark-python-data-source/references/production-patterns.md b/.claude/skills/spark-python-data-source/references/production-patterns.md new file mode 100644 index 00000000..71928ca7 --- /dev/null +++ b/.claude/skills/spark-python-data-source/references/production-patterns.md @@ -0,0 +1,475 @@ +# Production Patterns + +Observability, security, validation, and operational best practices. + +## Observability and Metrics + +Track operation metrics for monitoring: + +```python +class ObservableWriter: + """Writer with comprehensive metrics tracking.""" + + def write(self, iterator): + """Write with metrics collection.""" + from pyspark import TaskContext + from datetime import datetime + import time + + context = TaskContext.get() + partition_id = context.partitionId() + + metrics = { + "partition_id": partition_id, + "rows_processed": 0, + "rows_failed": 0, + "bytes_sent": 0, + "batches_sent": 0, + "retry_count": 0, + "start_time": time.time(), + "errors": [] + } + + try: + for row in iterator: + try: + size = self._send_row(row) + metrics["rows_processed"] += 1 + metrics["bytes_sent"] += size + + except Exception as e: + metrics["rows_failed"] += 1 + metrics["errors"].append({ + "type": type(e).__name__, + "message": str(e) + }) + + if not self.continue_on_error: + raise + + metrics["duration_seconds"] = time.time() - metrics["start_time"] + self._report_metrics(metrics) + + return SimpleCommitMessage( + partition_id=partition_id, + count=metrics["rows_processed"] + ) + + except Exception as e: + metrics["fatal_error"] = str(e) + self._report_failure(partition_id, metrics) + raise + + def _report_metrics(self, metrics): + """Report metrics to monitoring system.""" + # Example: CloudWatch, Prometheus, Databricks metrics + print(f"METRICS: {json.dumps(metrics)}") + + # Calculate derived metrics + if metrics["duration_seconds"] > 0: + throughput = metrics["rows_processed"] / metrics["duration_seconds"] + print(f"Throughput: {throughput:.2f} rows/second") +``` + +## Logging Best Practices + +Structured logging for production debugging: + +```python +import logging +import json + +# Configure structured logging +logging.basicConfig( + format='%(asctime)s %(levelname)s [%(name)s] %(message)s', + level=logging.INFO +) +logger = logging.getLogger(__name__) + +class StructuredLogger: + """Logger with structured output.""" + + @staticmethod + def log_operation(operation, context, **kwargs): + """Log operation with structured context.""" + log_entry = { + "operation": operation, + "context": context, + **kwargs + } + logger.info(json.dumps(log_entry)) + + @staticmethod + def log_error(operation, error, context): + """Log error with context.""" + log_entry = { + "operation": operation, + "error_type": type(error).__name__, + "error_message": str(error), + "context": context + } + logger.error(json.dumps(log_entry)) + +class LoggingWriter: + def write(self, iterator): + """Write with structured logging.""" + from pyspark import TaskContext + + context = TaskContext.get() + partition_id = context.partitionId() + + StructuredLogger.log_operation( + "write_start", + {"partition_id": partition_id} + ) + + try: + count = 0 + for row in iterator: + self._send_data(row) + count += 1 + + StructuredLogger.log_operation( + "write_complete", + {"partition_id": partition_id}, + rows_written=count + ) + + except Exception as e: + StructuredLogger.log_error( + "write_failed", + e, + {"partition_id": partition_id} + ) + raise +``` + +## Security Validation + +Input validation and sanitization: + +```python +import re +import ipaddress + +class SecureDataSource: + """Data source with security validation.""" + + # Sensitive keys that should never be logged + SENSITIVE_KEYS = { + "password", "api_key", "client_secret", "token", + "access_token", "refresh_token", "bearer_token" + } + + def __init__(self, options): + # Validate and sanitize options + self._validate_options(options) + self.options = options + + # Create sanitized version for logging + self._safe_options = self._sanitize_for_logging(options) + + def _validate_options(self, options): + """Comprehensive option validation.""" + # Validate required options + required = ["host", "database", "table"] + missing = [opt for opt in required if opt not in options] + if missing: + raise ValueError(f"Missing required options: {', '.join(missing)}") + + # Validate host (IP or hostname) + self._validate_host(options["host"]) + + # Validate port range + if "port" in options: + port = int(options["port"]) + if port < 1 or port > 65535: + raise ValueError(f"Port must be 1-65535, got {port}") + + # Validate table name (prevent SQL injection) + self._validate_identifier(options["table"], "table") + + # Validate numeric options + if "batch_size" in options: + batch_size = int(options["batch_size"]) + if batch_size < 1 or batch_size > 10000: + raise ValueError(f"batch_size must be 1-10000, got {batch_size}") + + def _validate_host(self, host): + """Validate host is valid IP or hostname.""" + try: + # Try as IP address + ipaddress.ip_address(host) + return + except ValueError: + pass + + # Validate as hostname + if not re.match(r'^[a-zA-Z0-9][a-zA-Z0-9-\.]*[a-zA-Z0-9]$', host): + raise ValueError(f"Invalid host format: {host}") + + def _validate_identifier(self, identifier, name): + """Validate SQL identifier (table, column name).""" + # Prevent SQL injection + if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', identifier): + raise ValueError( + f"Invalid {name} identifier: {identifier}. " + f"Must contain only letters, numbers, and underscores, " + f"and start with a letter or underscore." + ) + + def _sanitize_for_logging(self, options): + """Mask sensitive values for logging.""" + safe = {} + for key, value in options.items(): + if key.lower() in self.SENSITIVE_KEYS: + safe[key] = "***REDACTED***" + else: + safe[key] = value + return safe + + def __repr__(self): + return f"SecureDataSource({self._safe_options})" +``` + +## Secrets Management + +Load credentials from secure storage: + +```python +def load_secrets_from_databricks(scope, keys): + """Load secrets from Databricks secrets.""" + try: + from pyspark.dbutils import DBUtils + from pyspark.sql import SparkSession + + spark = SparkSession.getActiveSession() + if not spark: + raise ValueError("No active Spark session") + + dbutils = DBUtils(spark) + secrets = {} + + for key in keys: + try: + secrets[key] = dbutils.secrets.get(scope=scope, key=key) + except Exception as e: + raise ValueError(f"Failed to load secret '{key}' from scope '{scope}': {e}") + + return secrets + + except Exception as e: + raise ValueError(f"Failed to access Databricks secrets: {e}") + +class SecureCredentialLoader: + """Load credentials securely.""" + + @staticmethod + def load_credentials(options): + """Load credentials from secure storage.""" + # Priority 1: Databricks secrets + if "secret_scope" in options: + secret_keys = [ + "username", "password", "api_key", "client_secret" + ] + secrets = load_secrets_from_databricks( + options["secret_scope"], + secret_keys + ) + options.update(secrets) + + # Priority 2: Environment variables + elif options.get("use_env_vars", "false").lower() == "true": + import os + options["username"] = os.environ.get("DB_USERNAME") + options["password"] = os.environ.get("DB_PASSWORD") + + return options +``` + +## Configuration Validation + +Validate configuration before execution: + +```python +class ConfigValidator: + """Validate data source configuration.""" + + VALID_CONSISTENCY_LEVELS = { + "ONE", "TWO", "THREE", "QUORUM", "ALL", + "LOCAL_QUORUM", "EACH_QUORUM", "LOCAL_ONE" + } + + VALID_COMPRESSION = { + "none", "gzip", "snappy", "lz4", "zstd" + } + + @classmethod + def validate(cls, options): + """Validate all configuration options.""" + errors = [] + + # Validate consistency level + if "consistency" in options: + consistency = options["consistency"].upper() + if consistency not in cls.VALID_CONSISTENCY_LEVELS: + errors.append( + f"Invalid consistency level '{consistency}'. " + f"Valid: {', '.join(cls.VALID_CONSISTENCY_LEVELS)}" + ) + + # Validate compression + if "compression" in options: + compression = options["compression"].lower() + if compression not in cls.VALID_COMPRESSION: + errors.append( + f"Invalid compression '{compression}'. " + f"Valid: {', '.join(cls.VALID_COMPRESSION)}" + ) + + # Validate numeric ranges + if "timeout" in options: + timeout = int(options["timeout"]) + if timeout < 0 or timeout > 300: + errors.append(f"timeout must be 0-300 seconds, got {timeout}") + + if "batch_size" in options: + batch_size = int(options["batch_size"]) + if batch_size < 1 or batch_size > 10000: + errors.append(f"batch_size must be 1-10000, got {batch_size}") + + # Validate dependent options + if options.get("ssl_enabled", "false").lower() == "true": + if "ssl_ca_cert" not in options: + errors.append("ssl_ca_cert required when ssl_enabled=true") + + if errors: + raise ValueError("Configuration errors:\n" + "\n".join(f"- {e}" for e in errors)) +``` + +## Resource Cleanup + +Ensure proper resource cleanup: + +```python +class ManagedResourceWriter: + """Writer with guaranteed resource cleanup.""" + + def __init__(self, options): + self.options = options + self._connection = None + self._session = None + + def _get_connection(self): + """Lazy connection initialization.""" + if self._connection is None: + self._connection = self._create_connection() + return self._connection + + def write(self, iterator): + """Write with guaranteed cleanup.""" + try: + connection = self._get_connection() + + for row in iterator: + self._send_data(connection, row) + + finally: + # Always cleanup resources + self._cleanup() + + def _cleanup(self): + """Clean up resources.""" + if self._session: + try: + self._session.close() + except Exception as e: + logger.warning(f"Error closing session: {e}") + finally: + self._session = None + + if self._connection: + try: + self._connection.close() + except Exception as e: + logger.warning(f"Error closing connection: {e}") + finally: + self._connection = None + + def __del__(self): + """Cleanup on garbage collection.""" + self._cleanup() +``` + +## Health Checks + +Monitor system health: + +```python +class HealthCheckMixin: + """Mixin for health check functionality.""" + + def check_health(self): + """Perform health check before operations.""" + checks = { + "connection": self._check_connection(), + "authentication": self._check_authentication(), + "rate_limit": self._check_rate_limit(), + "disk_space": self._check_disk_space() + } + + failed = [name for name, passed in checks.items() if not passed] + + if failed: + raise Exception(f"Health check failed: {', '.join(failed)}") + + return checks + + def _check_connection(self): + """Check connection to external system.""" + try: + self._test_connection() + return True + except Exception as e: + logger.error(f"Connection check failed: {e}") + return False + + def _check_authentication(self): + """Check authentication is valid.""" + try: + self._verify_credentials() + return True + except Exception as e: + logger.error(f"Authentication check failed: {e}") + return False + + def _check_rate_limit(self): + """Check if under rate limits.""" + # Check current rate usage + current_rate = self._get_current_rate() + limit = self._get_rate_limit() + + return current_rate < limit * 0.8 # 80% threshold + + def _check_disk_space(self): + """Check available disk space.""" + import shutil + + usage = shutil.disk_usage("/") + free_percent = (usage.free / usage.total) * 100 + + return free_percent > 10 # 10% minimum +``` + +## Operational Best Practices + +1. **Monitoring**: Track throughput, latency, error rates +2. **Logging**: Use structured logging with correlation IDs +3. **Secrets**: Never log sensitive values, use secrets management +4. **Validation**: Validate all inputs to prevent injection attacks +5. **Resource Cleanup**: Always close connections and clean up resources +6. **Health Checks**: Verify system health before operations +7. **Rate Limiting**: Respect API rate limits with backoff +8. **Alerting**: Set up alerts for error rates and latency +9. **Documentation**: Document all configuration options +10. **Version Control**: Tag releases and maintain changelog diff --git a/.claude/skills/spark-python-data-source/references/streaming-patterns.md b/.claude/skills/spark-python-data-source/references/streaming-patterns.md new file mode 100644 index 00000000..6f00ddd6 --- /dev/null +++ b/.claude/skills/spark-python-data-source/references/streaming-patterns.md @@ -0,0 +1,400 @@ +# Streaming Patterns + +Offset management and streaming implementation patterns for exactly-once semantics. + +## Basic Offset Implementation + +Simple JSON-serializable offset: + +```python +class SimpleOffset: + """Basic offset with single timestamp field.""" + + def __init__(self, timestamp): + self.timestamp = timestamp + + def json(self): + """Serialize to JSON string.""" + import json + return json.dumps({"timestamp": self.timestamp}) + + @staticmethod + def from_json(json_str): + """Deserialize from JSON string.""" + import json + data = json.loads(json_str) + return SimpleOffset(data["timestamp"]) +``` + +## Multi-Field Offset + +Complex offset with multiple fields: + +```python +class MultiFieldOffset: + """Offset with timestamp, sequence ID, and partition.""" + + def __init__(self, timestamp, sequence_id, partition_id): + self.timestamp = timestamp + self.sequence_id = sequence_id + self.partition_id = partition_id + + def json(self): + import json + return json.dumps({ + "timestamp": self.timestamp, + "sequence_id": self.sequence_id, + "partition_id": self.partition_id + }) + + @staticmethod + def from_json(json_str): + import json + data = json.loads(json_str) + return MultiFieldOffset( + timestamp=data["timestamp"], + sequence_id=data["sequence_id"], + partition_id=data["partition_id"] + ) + + def __lt__(self, other): + """Enable offset comparison for ordering.""" + if self.timestamp != other.timestamp: + return self.timestamp < other.timestamp + if self.sequence_id != other.sequence_id: + return self.sequence_id < other.sequence_id + return self.partition_id < other.partition_id +``` + +## Stream Reader Implementation + +Complete streaming reader with offset management: + +```python +from pyspark.sql.datasource import DataSourceStreamReader + +class YourStreamReader(DataSourceStreamReader): + def __init__(self, options, schema): + super().__init__(options, schema) + + # Parse start time option + start_time = options.get("start_time", "latest") + + if start_time == "latest": + from datetime import datetime, timezone + self.start_time = datetime.now(timezone.utc).isoformat() + + elif start_time == "earliest": + # Query for earliest timestamp (one-time cost) + self.start_time = self._get_earliest_timestamp() + + else: + # Validate ISO 8601 format + from datetime import datetime + datetime.fromisoformat(start_time.replace("Z", "+00:00")) + self.start_time = start_time + + # Partition duration (e.g., 1 hour) + self.partition_duration = int(options.get("partition_duration", "3600")) + + def _get_earliest_timestamp(self): + """Find earliest data timestamp for 'earliest' option.""" + from datetime import datetime, timezone + + timestamp_column = self.options.get("timestamp_column", "timestamp") + query = f"{self.query} | summarize earliest=min({timestamp_column})" + + response = self._execute_query(query, timespan=None) + + if response.tables and response.tables[0].rows: + earliest_value = response.tables[0].rows[0][0] + if earliest_value: + if isinstance(earliest_value, datetime): + return earliest_value.isoformat() + return str(earliest_value) + + # Fallback to current time + return datetime.now(timezone.utc).isoformat() + + def initialOffset(self): + """ + Return initial offset (start time minus 1 microsecond). + + Subtract 1µs to compensate for +1µs in partitions() method, + preventing overlap between batches. + """ + from datetime import datetime, timedelta + + start_dt = datetime.fromisoformat(self.start_time.replace("Z", "+00:00")) + adjusted = start_dt - timedelta(microseconds=1) + return SimpleOffset(adjusted.isoformat()).json() + + def latestOffset(self): + """Return latest offset (current time).""" + from datetime import datetime, timezone + + current_time = datetime.now(timezone.utc).isoformat() + return SimpleOffset(current_time).json() + + def partitions(self, start, end): + """ + Create non-overlapping partitions for offset range. + + Adds 1µs to start to prevent overlap with previous batch. + """ + from datetime import datetime, timedelta + + start_offset = SimpleOffset.from_json(start) + end_offset = SimpleOffset.from_json(end) + + start_time = datetime.fromisoformat(start_offset.timestamp.replace("Z", "+00:00")) + end_time = datetime.fromisoformat(end_offset.timestamp.replace("Z", "+00:00")) + + # Add 1µs to prevent overlap with previous batch + # This works with -1µs in initialOffset() to ensure: + # - Initial batch: (start - 1µs) + 1µs = start (correct) + # - Subsequent batches: previous_end + 1µs (no overlap) + start_time = start_time + timedelta(microseconds=1) + + # Create fixed-duration partitions + partitions = [] + current = start_time + delta = timedelta(seconds=self.partition_duration) + + while current < end_time: + next_time = min(current + delta, end_time) + partitions.append(TimeRangePartition(current, next_time)) + current = next_time + timedelta(microseconds=1) # No overlap + + return partitions if partitions else [TimeRangePartition(start_time, end_time)] + + def commit(self, end): + """Called when batch is successfully processed.""" + # Spark handles checkpointing - usually no action needed + pass + + def read(self, partition): + """Read data for partition time range.""" + response = self._query_api( + start=partition.start_time, + end=partition.end_time + ) + + for item in response: + yield self._convert_to_row(item) +``` + +## Watermarking Support + +Support for event-time watermarking: + +```python +class WatermarkedStreamReader(DataSourceStreamReader): + def __init__(self, options, schema): + super().__init__(options, schema) + + # Watermark configuration + self.watermark_column = options.get("watermark_column") + self.watermark_delay = options.get("watermark_delay", "10 minutes") + + def read(self, partition): + """Read with event-time watermarking.""" + from datetime import datetime + + response = self._query_api( + start=partition.start_time, + end=partition.end_time + ) + + for item in response: + row = self._convert_to_row(item) + + # Validate watermark column exists + if self.watermark_column: + if not hasattr(row, self.watermark_column): + raise ValueError( + f"Watermark column '{self.watermark_column}' not found in row" + ) + + # Ensure watermark column is timestamp + watermark_value = getattr(row, self.watermark_column) + if not isinstance(watermark_value, datetime): + raise ValueError( + f"Watermark column must be timestamp, got {type(watermark_value)}" + ) + + yield row +``` + +## Stateful Streaming + +Track state across batches: + +```python +class StatefulStreamReader(DataSourceStreamReader): + def __init__(self, options, schema): + super().__init__(options, schema) + + # State management + self.checkpoint_location = options.get("checkpoint_location") + self._state = {} + + def _load_state(self): + """Load state from checkpoint location.""" + import json + import os + + if not self.checkpoint_location: + return {} + + state_file = os.path.join(self.checkpoint_location, "reader_state.json") + + if os.path.exists(state_file): + with open(state_file, 'r') as f: + return json.load(f) + + return {} + + def _save_state(self): + """Save state to checkpoint location.""" + import json + import os + + if not self.checkpoint_location: + return + + os.makedirs(self.checkpoint_location, exist_ok=True) + state_file = os.path.join(self.checkpoint_location, "reader_state.json") + + with open(state_file, 'w') as f: + json.dump(self._state, f) + + def initialOffset(self): + """Load state and return initial offset.""" + self._state = self._load_state() + + # Check if we have previous state + if "last_offset" in self._state: + return self._state["last_offset"] + + # First run - use configured start time + return self._create_initial_offset() + + def commit(self, end): + """Save state after successful batch.""" + self._state["last_offset"] = end + self._state["last_commit_time"] = datetime.now().isoformat() + self._save_state() +``` + +## Exactly-Once Semantics + +Ensure exactly-once delivery with idempotent writes: + +```python +class ExactlyOnceWriter(DataSourceStreamWriter): + def __init__(self, options, schema): + super().__init__(options, schema) + self.enable_idempotency = options.get("enable_idempotency", "true").lower() == "true" + + def write(self, iterator): + """Write with idempotency key.""" + import hashlib + from pyspark import TaskContext + + context = TaskContext.get() + partition_id = context.partitionId() + batch_id = getattr(context, 'batchId', lambda: 0)() + + for row in iterator: + # Generate idempotency key from batch_id + partition_id + row content + row_dict = row.asDict() + + if self.enable_idempotency: + idempotency_key = self._generate_idempotency_key( + batch_id, + partition_id, + row_dict + ) + row_dict["_idempotency_key"] = idempotency_key + + # Write with idempotency check + self._write_with_idempotency_check(row_dict) + + def _generate_idempotency_key(self, batch_id, partition_id, row_dict): + """Generate deterministic idempotency key.""" + import hashlib + import json + + key_data = { + "batch_id": batch_id, + "partition_id": partition_id, + "row": row_dict + } + + key_str = json.dumps(key_data, sort_keys=True) + return hashlib.sha256(key_str.encode()).hexdigest() + + def _write_with_idempotency_check(self, row_dict): + """Write only if idempotency key not seen before.""" + idempotency_key = row_dict.get("_idempotency_key") + + if idempotency_key: + # Check if already written (implementation depends on target system) + if self._is_already_written(idempotency_key): + return # Skip duplicate + + # Write data + self._write_data(row_dict) + + def commit(self, messages, batchId): + """Commit batch after all writes succeed.""" + # Log successful batch + print(f"Batch {batchId} committed successfully") + + def abort(self, messages, batchId): + """Handle failed batch.""" + # Log failed batch + print(f"Batch {batchId} aborted") +``` + +## Monitoring and Progress + +Track streaming progress: + +```python +class MonitoredStreamReader(DataSourceStreamReader): + def read(self, partition): + """Read with progress tracking.""" + from datetime import datetime + + start_time = datetime.now() + row_count = 0 + + for row in self._read_partition(partition): + row_count += 1 + yield row + + duration = (datetime.now() - start_time).total_seconds() + + # Log metrics + self._log_partition_metrics( + partition_id=partition.partition_id, + row_count=row_count, + duration=duration + ) + + def _log_partition_metrics(self, partition_id, row_count, duration): + """Log partition processing metrics.""" + print(f"Partition {partition_id}: {row_count} rows in {duration:.2f}s") +``` + +## Best Practices + +1. **Non-Overlapping Partitions**: Use microsecond adjustments to prevent duplicates +2. **Idempotency**: Generate deterministic keys for exactly-once semantics +3. **State Management**: Store offsets in Spark checkpoints +4. **Watermarking**: Support event-time processing for late data +5. **Monitoring**: Track batch progress and lag metrics +6. **Error Handling**: Implement retry logic for transient failures +7. **Backpressure**: Respect rate limits with appropriate partition sizing diff --git a/.claude/skills/spark-python-data-source/references/testing-patterns.md b/.claude/skills/spark-python-data-source/references/testing-patterns.md new file mode 100644 index 00000000..96e2e289 --- /dev/null +++ b/.claude/skills/spark-python-data-source/references/testing-patterns.md @@ -0,0 +1,439 @@ +# Testing Patterns + +Unit and integration testing strategies for Spark data sources. + +## Basic Unit Tests + +Test data source registration and initialization: + +```python +import pytest +from pyspark.sql import SparkSession + +@pytest.fixture(scope="session") +def spark(): + """Create Spark session for tests.""" + return SparkSession.builder \ + .master("local[2]") \ + .appName("test") \ + .config("spark.sql.shuffle.partitions", "2") \ + .getOrCreate() + +def test_data_source_name(): + """Test data source name registration.""" + assert YourDataSource.name() == "your-format" + +def test_data_source_initialization(): + """Test data source can be initialized.""" + options = {"url": "http://api.example.com"} + ds = YourDataSource(options) + assert ds.options == options + +def test_missing_required_option(): + """Test error on missing required option.""" + options = {} # Missing required 'url' + + with pytest.raises(AssertionError, match="url is required"): + YourDataSource(options) +``` + +## Mocking HTTP Requests + +Test writers without external dependencies: + +```python +from unittest.mock import patch, Mock +import pytest + +@pytest.fixture +def basic_options(): + """Common options for tests.""" + return { + "url": "http://api.example.com", + "batch_size": "10" + } + +@pytest.fixture +def sample_schema(): + """Sample schema for tests.""" + from pyspark.sql.types import StructType, StructField, IntegerType, StringType + return StructType([ + StructField("id", IntegerType(), False), + StructField("name", StringType(), True) + ]) + +def test_writer_sends_batch(spark, basic_options, sample_schema): + """Test writer sends data in batches.""" + with patch('requests.post') as mock_post: + mock_post.return_value = Mock(status_code=200) + + # Create test data + df = spark.createDataFrame([ + (1, "Alice"), + (2, "Bob"), + (3, "Charlie") + ], ["id", "name"]) + + # Write using data source + df.write.format("your-format").options(**basic_options).save() + + # Verify API was called + assert mock_post.called + assert mock_post.call_count > 0 + +def test_writer_respects_batch_size(spark, basic_options, sample_schema): + """Test writer respects configured batch size.""" + with patch('requests.post') as mock_post: + mock_post.return_value = Mock(status_code=200) + + # Create 25 rows with batch_size=10 + rows = [(i, f"name_{i}") for i in range(25)] + df = spark.createDataFrame(rows, ["id", "name"]) + + df.write.format("your-format").options(**basic_options).save() + + # Should make 3 calls: 10 + 10 + 5 + assert mock_post.call_count == 3 +``` + +## Testing Readers + +Mock external API responses: + +```python +def test_reader_fetches_data(spark, basic_options): + """Test reader fetches and converts data.""" + with patch('requests.get') as mock_get: + # Mock API response + mock_response = Mock() + mock_response.json.return_value = [ + {"id": 1, "name": "Alice"}, + {"id": 2, "name": "Bob"} + ] + mock_get.return_value = mock_response + + # Read using data source + df = spark.read.format("your-format").options(**basic_options).load() + + # Verify data + rows = df.collect() + assert len(rows) == 2 + assert rows[0]["id"] == 1 + assert rows[0]["name"] == "Alice" + +def test_reader_handles_empty_response(spark, basic_options): + """Test reader handles empty response.""" + with patch('requests.get') as mock_get: + mock_response = Mock() + mock_response.json.return_value = [] + mock_get.return_value = mock_response + + df = spark.read.format("your-format").options(**basic_options).load() + + assert df.count() == 0 +``` + +## Testing Partitioning + +Test partition creation logic: + +```python +def test_partitions_created(basic_options, sample_schema): + """Test correct number of partitions created.""" + options = {**basic_options, "num_partitions": "4"} + + reader = YourBatchReader(options, sample_schema) + partitions = reader.partitions() + + assert len(partitions) == 4 + +def test_partition_ranges_non_overlapping(): + """Test partitions have non-overlapping ranges.""" + from datetime import datetime, timedelta + + reader = TimeBasedReader(options, schema) + partitions = reader.partitions() + + # Check no gaps or overlaps + for i in range(len(partitions) - 1): + current_end = partitions[i].end_time + next_start = partitions[i + 1].start_time + + # Next partition should start right after current ends + assert next_start >= current_end +``` + +## Testing Streaming + +Test offset management and streaming logic: + +```python +def test_initial_offset(): + """Test initial offset is correct.""" + from datetime import datetime + + reader = YourStreamReader(options, schema) + initial = reader.initialOffset() + + # Should be valid JSON + import json + offset_dict = json.loads(initial) + + assert "timestamp" in offset_dict + +def test_latest_offset_advances(): + """Test latest offset advances over time.""" + reader = YourStreamReader(options, schema) + + offset1 = reader.latestOffset() + import time + time.sleep(0.1) + offset2 = reader.latestOffset() + + # Offset should advance + assert offset2 > offset1 or offset2 != offset1 + +def test_partitions_non_overlapping(basic_options, sample_schema): + """Test streaming partitions don't overlap.""" + reader = YourStreamReader(basic_options, sample_schema) + + start = reader.initialOffset() + end = reader.latestOffset() + + partitions = reader.partitions(start, end) + + # Verify no overlaps + for i in range(len(partitions) - 1): + assert partitions[i].end_time < partitions[i + 1].start_time +``` + +## Testing Type Conversion + +Test type mapping and conversion: + +```python +def test_convert_timestamp(): + """Test timestamp conversion.""" + from datetime import datetime + from pyspark.sql.types import TimestampType + + dt = datetime(2024, 1, 1, 12, 0, 0) + result = convert_external_to_spark(dt, TimestampType()) + + assert isinstance(result, datetime) + assert result == dt + +def test_convert_null_values(): + """Test null value handling.""" + from pyspark.sql.types import StringType + + result = convert_external_to_spark(None, StringType()) + assert result is None + +def test_convert_invalid_type(): + """Test error on invalid type conversion.""" + from pyspark.sql.types import IntegerType + + with pytest.raises(ValueError, match="Cannot convert"): + convert_external_to_spark("not_a_number", IntegerType()) +``` + +## Integration Tests with Testcontainers + +Run end-to-end tests against real systems: + +```python +import pytest +from testcontainers.postgres import PostgresContainer + +@pytest.fixture(scope="session") +def postgres_container(): + """Start PostgreSQL container for integration tests.""" + with PostgresContainer("postgres:15") as container: + yield container + +@pytest.fixture +def postgres_connection(postgres_container): + """Create connection to test database.""" + import psycopg2 + + conn = psycopg2.connect(postgres_container.get_connection_url()) + cursor = conn.cursor() + + # Create test table + cursor.execute(""" + CREATE TABLE test_data ( + id SERIAL PRIMARY KEY, + name VARCHAR(100), + value INTEGER + ) + """) + conn.commit() + + yield conn + + conn.close() + +def test_write_integration(spark, postgres_container, postgres_connection): + """Integration test for writing to PostgreSQL.""" + # Create test data + df = spark.createDataFrame([ + (1, "Alice", 100), + (2, "Bob", 200) + ], ["id", "name", "value"]) + + # Write using data source + df.write.format("your-format") \ + .option("url", postgres_container.get_connection_url()) \ + .option("table", "test_data") \ + .save() + + # Verify data written + cursor = postgres_connection.cursor() + cursor.execute("SELECT COUNT(*) FROM test_data") + count = cursor.fetchone()[0] + + assert count == 2 + +def test_read_integration(spark, postgres_container, postgres_connection): + """Integration test for reading from PostgreSQL.""" + # Insert test data + cursor = postgres_connection.cursor() + cursor.execute("INSERT INTO test_data (name, value) VALUES ('Alice', 100)") + cursor.execute("INSERT INTO test_data (name, value) VALUES ('Bob', 200)") + postgres_connection.commit() + + # Read using data source + df = spark.read.format("your-format") \ + .option("url", postgres_container.get_connection_url()) \ + .option("table", "test_data") \ + .load() + + # Verify data + assert df.count() == 2 + names = [row["name"] for row in df.collect()] + assert "Alice" in names + assert "Bob" in names +``` + +## Performance Tests + +Test performance characteristics: + +```python +import time + +def test_write_performance(spark, basic_options): + """Test write performance meets requirements.""" + # Create large dataset + rows = [(i, f"name_{i}") for i in range(10000)] + df = spark.createDataFrame(rows, ["id", "name"]) + + start = time.time() + df.write.format("your-format").options(**basic_options).save() + duration = time.time() - start + + # Should complete in reasonable time + assert duration < 30.0 # 30 seconds + + # Calculate throughput + throughput = len(rows) / duration + print(f"Write throughput: {throughput:.0f} rows/second") + +def test_partition_read_parallelism(spark, basic_options): + """Test reads execute in parallel.""" + options = {**basic_options, "num_partitions": "4"} + + df = spark.read.format("your-format").options(**options).load() + + # Check partition count + assert df.rdd.getNumPartitions() == 4 +``` + +## Test Fixtures and Utilities + +Reusable test fixtures: + +```python +import pytest +from pyspark.sql import SparkSession + +@pytest.fixture(scope="session") +def spark(): + """Shared Spark session.""" + return SparkSession.builder \ + .master("local[2]") \ + .appName("test") \ + .config("spark.sql.shuffle.partitions", "2") \ + .getOrCreate() + +@pytest.fixture +def sample_dataframe(spark): + """Sample DataFrame for testing.""" + return spark.createDataFrame([ + (1, "Alice", 25), + (2, "Bob", 30), + (3, "Charlie", 35) + ], ["id", "name", "age"]) + +@pytest.fixture +def temp_output_path(tmp_path): + """Temporary output path.""" + return str(tmp_path / "output") + +def assert_dataframes_equal(df1, df2): + """Assert two DataFrames are equal.""" + assert df1.schema == df2.schema + assert df1.count() == df2.count() + + rows1 = sorted(df1.collect()) + rows2 = sorted(df2.collect()) + + assert rows1 == rows2 +``` + +## Test Organization + +Structure tests by functionality: + +``` +tests/ +├── unit/ +│ ├── test_datasource.py # DataSource class tests +│ ├── test_reader.py # Reader tests +│ ├── test_writer.py # Writer tests +│ ├── test_partitioning.py # Partitioning logic +│ └── test_type_conversion.py # Type conversion +├── integration/ +│ ├── test_read_integration.py # End-to-end read tests +│ ├── test_write_integration.py # End-to-end write tests +│ └── test_streaming.py # Streaming tests +├── performance/ +│ └── test_performance.py # Performance tests +└── conftest.py # Shared fixtures +``` + +## Running Tests + +```bash +# Run all tests +poetry run pytest + +# Run specific test file +poetry run pytest tests/unit/test_writer.py + +# Run specific test +poetry run pytest tests/unit/test_writer.py::test_writer_sends_batch + +# Run with coverage +poetry run pytest --cov=your_package --cov-report=html + +# Run only unit tests +poetry run pytest tests/unit/ + +# Run with verbose output +poetry run pytest -v + +# Run with print statements +poetry run pytest -s +``` diff --git a/.claude/skills/spark-python-data-source/references/type-conversion.md b/.claude/skills/spark-python-data-source/references/type-conversion.md new file mode 100644 index 00000000..a55f0795 --- /dev/null +++ b/.claude/skills/spark-python-data-source/references/type-conversion.md @@ -0,0 +1,370 @@ +# Type Conversion + +Bidirectional mapping between Spark types and external system types. + +## Spark to External System + +Convert Spark/Python values to external system types: + +```python +def convert_spark_to_external(value, external_type): + """Convert Spark/Python value to external system type.""" + if value is None: + return None + + external_type_lower = external_type.lower() + + # UUID conversion + if "uuid" in external_type_lower: + import uuid + if isinstance(value, uuid.UUID): + return value + return uuid.UUID(str(value)) + + # Timestamp conversion + if "timestamp" in external_type_lower: + from datetime import datetime + if isinstance(value, datetime): + return value + if isinstance(value, str): + return datetime.fromisoformat(value.replace("Z", "+00:00")) + if isinstance(value, (int, float)): + return datetime.fromtimestamp(value) + + # IP address conversion + if "inet" in external_type_lower: + import ipaddress + if isinstance(value, (ipaddress.IPv4Address, ipaddress.IPv6Address)): + return value + return ipaddress.ip_address(str(value)) + + # Decimal conversion + if "decimal" in external_type_lower: + from decimal import Decimal + if isinstance(value, Decimal): + return value + return Decimal(str(value)) + + # Collections + if "list" in external_type_lower or "set" in external_type_lower: + if not isinstance(value, (list, set)): + raise ValueError(f"Expected list/set, got {type(value)}") + return list(value) + + if "map" in external_type_lower: + if not isinstance(value, dict): + raise ValueError(f"Expected dict, got {type(value)}") + return value + + # Numeric types + if "int" in external_type_lower: + return int(value) + if "float" in external_type_lower or "double" in external_type_lower: + return float(value) + + # Boolean + if "bool" in external_type_lower: + if isinstance(value, bool): + return value + if isinstance(value, str): + return value.lower() in ("true", "1", "yes") + return bool(value) + + # Default: return as-is + return value +``` + +## External System to Spark + +Convert external values to Spark types: + +```python +def convert_external_to_spark(value, spark_type): + """Convert external system value to Spark type.""" + from pyspark.sql.types import ( + StringType, IntegerType, LongType, FloatType, DoubleType, + BooleanType, TimestampType, DateType + ) + from datetime import datetime, date + + if value is None: + return None + + try: + if isinstance(spark_type, StringType): + return str(value) + + elif isinstance(spark_type, BooleanType): + if isinstance(value, bool): + return value + if isinstance(value, str): + return value.lower() in ("true", "1", "yes") + return bool(value) + + elif isinstance(spark_type, (IntegerType, LongType)): + if isinstance(value, bool): + raise ValueError("Cannot convert boolean to integer") + return int(value) + + elif isinstance(spark_type, (FloatType, DoubleType)): + if isinstance(value, bool): + raise ValueError("Cannot convert boolean to float") + return float(value) + + elif isinstance(spark_type, TimestampType): + if isinstance(value, datetime): + return value + if isinstance(value, str): + return datetime.fromisoformat(value.replace("Z", "+00:00")) + raise ValueError(f"Cannot convert {type(value)} to timestamp") + + elif isinstance(spark_type, DateType): + if isinstance(value, date) and not isinstance(value, datetime): + return value + if isinstance(value, datetime): + return value.date() + if isinstance(value, str): + return datetime.fromisoformat(value.replace("Z", "+00:00")).date() + raise ValueError(f"Cannot convert {type(value)} to date") + + else: + return value + + except (ValueError, TypeError) as e: + raise ValueError( + f"Failed to convert '{value}' (type: {type(value).__name__}) " + f"to {spark_type}: {e}" + ) +``` + +## Cassandra-Specific Types + +Handle Cassandra complex types: + +```python +def convert_cassandra_to_spark(value): + """Handle Cassandra-specific complex types.""" + if value is None: + return None + + from cassandra.util import ( + Date, Time, Duration, OrderedMap, SortedSet, + Point, LineString, Polygon + ) + import uuid + + # Cassandra Date to Python date + if isinstance(value, Date): + return value.date() + + # Cassandra Time to nanoseconds (LongType) + if isinstance(value, Time): + return value.nanosecond + + # UUID to string + if isinstance(value, uuid.UUID): + return str(value) + + # Duration to structured dict + if isinstance(value, Duration): + return { + "months": value.months, + "days": value.days, + "nanoseconds": value.nanoseconds + } + + # OrderedMap to dict + if isinstance(value, OrderedMap): + return dict(value) + + # SortedSet to list + if isinstance(value, SortedSet): + return list(value) + + # Geospatial types to WKT string + if isinstance(value, (Point, LineString, Polygon)): + return str(value) + + return value +``` + +## Schema Inference + +Infer Spark types from Python values: + +```python +def infer_spark_type(value): + """Infer Spark type from Python value.""" + from pyspark.sql.types import ( + StringType, IntegerType, LongType, FloatType, DoubleType, + BooleanType, TimestampType, DateType + ) + from datetime import datetime, date + + if value is None: + return StringType() + + # Check bool before int (bool is subclass of int) + if isinstance(value, bool): + return BooleanType() + + if isinstance(value, int): + return LongType() + + if isinstance(value, float): + return DoubleType() + + if isinstance(value, datetime): + return TimestampType() + + if isinstance(value, date): + return DateType() + + # Default to string + return StringType() +``` + +## External Type to Spark Type Mapping + +Map external system types to Spark types: + +```python +def map_external_type_to_spark(external_type): + """Map external system types to Spark types.""" + from pyspark.sql.types import ( + StringType, IntegerType, LongType, FloatType, DoubleType, + BooleanType, TimestampType, DateType, BinaryType + ) + + type_str = str(external_type).lower() + + # String types + if any(t in type_str for t in ["varchar", "text", "char", "string", "uuid"]): + return StringType() + + # Integer types + if "int" in type_str and "big" not in type_str: + return IntegerType() + if "bigint" in type_str or "long" in type_str: + return LongType() + + # Floating point + if "float" in type_str: + return FloatType() + if "double" in type_str or "decimal" in type_str: + return DoubleType() + + # Boolean + if "bool" in type_str: + return BooleanType() + + # Temporal types + if "timestamp" in type_str: + return TimestampType() + if "date" in type_str: + return DateType() + + # Binary + if "blob" in type_str or "binary" in type_str: + return BinaryType() + + # Default fallback + return StringType() +``` + +## JSON Encoding + +Handle datetime serialization for JSON APIs: + +```python +import json +from datetime import date, datetime +from decimal import Decimal + +class ExtendedJsonEncoder(json.JSONEncoder): + """JSON encoder that handles datetime, date, and Decimal.""" + + def default(self, o): + if isinstance(o, (datetime, date)): + return o.isoformat() + + if isinstance(o, Decimal): + return float(o) + + return super().default(o) + +# Usage +def send_as_json(data): + import requests + + payload = json.dumps(data, cls=ExtendedJsonEncoder) + requests.post(url, data=payload, headers={"Content-Type": "application/json"}) +``` + +## Complete Row Conversion + +Convert entire rows with schema: + +```python +def convert_row_to_external(row, column_types): + """Convert entire Spark row to external system format.""" + row_dict = row.asDict() if hasattr(row, "asDict") else dict(row) + + converted = {} + for col, value in row_dict.items(): + external_type = column_types.get(col, "text") + converted[col] = convert_spark_to_external(value, external_type) + + return converted + +def convert_external_to_row(data, schema): + """Convert external data to Spark Row.""" + from pyspark.sql import Row + + # Create mapping of column names to types + schema_map = {field.name: field.dataType for field in schema.fields} + + row_dict = {} + for col, value in data.items(): + if col in schema_map: + spark_type = schema_map[col] + row_dict[col] = convert_external_to_spark(value, spark_type) + + # Add None for missing columns + for field in schema.fields: + if field.name not in row_dict: + row_dict[field.name] = None + + return Row(**row_dict) +``` + +## Validation + +Validate type conversions: + +```python +def validate_conversion(value, expected_type): + """Validate that value matches expected type after conversion.""" + type_checks = { + "int": lambda v: isinstance(v, int) and not isinstance(v, bool), + "long": lambda v: isinstance(v, int) and not isinstance(v, bool), + "float": lambda v: isinstance(v, (int, float)) and not isinstance(v, bool), + "double": lambda v: isinstance(v, (int, float)) and not isinstance(v, bool), + "string": lambda v: isinstance(v, str), + "boolean": lambda v: isinstance(v, bool), + "timestamp": lambda v: isinstance(v, datetime), + "date": lambda v: isinstance(v, date) and not isinstance(v, datetime), + } + + expected_type_lower = expected_type.lower() + for type_name, check in type_checks.items(): + if type_name in expected_type_lower: + if not check(value): + raise ValueError( + f"Value {value} (type: {type(value)}) does not match " + f"expected type {expected_type}" + ) + return + + # No specific check - accept any value +``` diff --git a/.codex/databricks-models.json b/.codex/databricks-models.json new file mode 100644 index 00000000..29a90bbd --- /dev/null +++ b/.codex/databricks-models.json @@ -0,0 +1,139 @@ +{ + "models": [ + { + "slug": "databricks-gpt-5-5", + "display_name": "Databricks GPT-5.5", + "description": "GPT-5.5 hosted through Databricks AI Gateway", + "default_reasoning_level": "medium", + "supported_reasoning_levels": [ + { "effort": "low", "description": "Fast responses with lighter reasoning" }, + { "effort": "medium", "description": "Balanced speed and reasoning depth" }, + { "effort": "high", "description": "Greater reasoning depth for complex tasks" }, + { "effort": "xhigh", "description": "Maximum reasoning depth for complex tasks" } + ], + "shell_type": "default", + "visibility": "list", + "supported_in_api": true, + "priority": 100, + "additional_speed_tiers": [], + "availability_nux": null, + "upgrade": null, + "base_instructions": "", + "supports_reasoning_summaries": true, + "support_verbosity": true, + "default_verbosity": null, + "apply_patch_tool_type": null, + "truncation_policy": { "mode": "tokens", "limit": 200000 }, + "supports_parallel_tool_calls": true, + "experimental_supported_tools": [] + }, + { + "slug": "databricks-gpt-5-4", + "display_name": "Databricks GPT-5.4", + "description": "GPT-5.4 hosted through Databricks AI Gateway", + "default_reasoning_level": "medium", + "supported_reasoning_levels": [ + { "effort": "low", "description": "Fast responses with lighter reasoning" }, + { "effort": "medium", "description": "Balanced speed and reasoning depth" }, + { "effort": "high", "description": "Greater reasoning depth for complex tasks" }, + { "effort": "xhigh", "description": "Maximum reasoning depth for complex tasks" } + ], + "shell_type": "default", + "visibility": "list", + "supported_in_api": true, + "priority": 90, + "additional_speed_tiers": [], + "availability_nux": null, + "upgrade": null, + "base_instructions": "", + "supports_reasoning_summaries": true, + "support_verbosity": true, + "default_verbosity": null, + "apply_patch_tool_type": null, + "truncation_policy": { "mode": "tokens", "limit": 200000 }, + "supports_parallel_tool_calls": true, + "experimental_supported_tools": [] + }, + { + "slug": "databricks-gpt-5-4-mini", + "display_name": "Databricks GPT-5.4 Mini", + "description": "GPT-5.4 Mini hosted through Databricks AI Gateway", + "default_reasoning_level": "medium", + "supported_reasoning_levels": [ + { "effort": "low", "description": "Fast responses with lighter reasoning" }, + { "effort": "medium", "description": "Balanced speed and reasoning depth" }, + { "effort": "high", "description": "Greater reasoning depth for complex tasks" }, + { "effort": "xhigh", "description": "Maximum reasoning depth for complex tasks" } + ], + "shell_type": "default", + "visibility": "list", + "supported_in_api": true, + "priority": 80, + "additional_speed_tiers": [], + "availability_nux": null, + "upgrade": null, + "base_instructions": "", + "supports_reasoning_summaries": true, + "support_verbosity": true, + "default_verbosity": null, + "apply_patch_tool_type": null, + "truncation_policy": { "mode": "tokens", "limit": 200000 }, + "supports_parallel_tool_calls": true, + "experimental_supported_tools": [] + }, + { + "slug": "databricks-gpt-5-3-codex", + "display_name": "Databricks GPT-5.3 Codex", + "description": "GPT-5.3 Codex hosted through Databricks AI Gateway", + "default_reasoning_level": "medium", + "supported_reasoning_levels": [ + { "effort": "low", "description": "Fast responses with lighter reasoning" }, + { "effort": "medium", "description": "Balanced speed and reasoning depth" }, + { "effort": "high", "description": "Greater reasoning depth for complex tasks" }, + { "effort": "xhigh", "description": "Maximum reasoning depth for complex tasks" } + ], + "shell_type": "default", + "visibility": "list", + "supported_in_api": true, + "priority": 70, + "additional_speed_tiers": [], + "availability_nux": null, + "upgrade": null, + "base_instructions": "", + "supports_reasoning_summaries": true, + "support_verbosity": true, + "default_verbosity": null, + "apply_patch_tool_type": null, + "truncation_policy": { "mode": "tokens", "limit": 200000 }, + "supports_parallel_tool_calls": true, + "experimental_supported_tools": [] + }, + { + "slug": "databricks-gpt-5-2", + "display_name": "Databricks GPT-5.2", + "description": "GPT-5.2 hosted through Databricks AI Gateway", + "default_reasoning_level": "medium", + "supported_reasoning_levels": [ + { "effort": "low", "description": "Fast responses with lighter reasoning" }, + { "effort": "medium", "description": "Balanced speed and reasoning depth" }, + { "effort": "high", "description": "Greater reasoning depth for complex tasks" }, + { "effort": "xhigh", "description": "Maximum reasoning depth for complex tasks" } + ], + "shell_type": "default", + "visibility": "list", + "supported_in_api": true, + "priority": 60, + "additional_speed_tiers": [], + "availability_nux": null, + "upgrade": null, + "base_instructions": "", + "supports_reasoning_summaries": true, + "support_verbosity": true, + "default_verbosity": null, + "apply_patch_tool_type": null, + "truncation_policy": { "mode": "tokens", "limit": 200000 }, + "supports_parallel_tool_calls": true, + "experimental_supported_tools": [] + } + ] +} \ No newline at end of file diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..9cfcfc24 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,14 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + cooldown: + default-days: 7 + - package-ecosystem: "pip" + directory: "/" + schedule: + interval: "weekly" + cooldown: + default-days: 7 diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 00000000..efa5e8ba --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,10 @@ +## What does this PR do? + + + +## Testing + +Please test your changes on dogfood before merging. + +- [ ] Deployed and tested on dogfood +- [ ] Added a screenshot to this PR diff --git a/.github/workflows/dependency-audit.yml b/.github/workflows/dependency-audit.yml new file mode 100644 index 00000000..d47ab107 --- /dev/null +++ b/.github/workflows/dependency-audit.yml @@ -0,0 +1,77 @@ +name: Dependency Audit + +on: + workflow_dispatch: + pull_request: + paths: + - "requirements.txt" + - "requirements.lock" + - "pyproject.toml" + push: + branches: [main] + paths: + - "requirements.txt" + - "requirements.lock" + - "pyproject.toml" + schedule: + - cron: '0 6 * * 1' # Weekly Monday 6am UTC — catch newly disclosed CVEs + +permissions: + contents: read + +jobs: + audit: + runs-on: databrickslabs-protected-runner-group + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Set up Python + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: "3.11" + + - name: Install uv + uses: astral-sh/setup-uv@94527f2e458b27549849d47d273a16bec83a01e9 # v7 + + - name: Install audit tools + run: pip install pip-audit==2.9.0 + + - name: Compile requirements.txt from pyproject.toml + run: | + # Keep requirements.txt in sync with pyproject.toml so Dependabot can scan it. + # Note: [tool.uv.sources] git overrides are not resolved by pip compile — + # requests and cryptography fall back to their PyPI versions here, which is + # intentional for Dependabot's purposes. + uv pip compile pyproject.toml -o /tmp/requirements.compiled.txt + if ! diff -q requirements.txt /tmp/requirements.compiled.txt > /dev/null 2>&1; then + echo "::warning::requirements.txt is out of date with pyproject.toml. Run: uv pip compile pyproject.toml -o requirements.txt" + fi + + - name: Audit pinned dependencies + run: | + if [ -f requirements.lock ]; then + echo "Auditing requirements.lock (pinned)..." + # Strip hashes before auditing — pip-audit's pip backend chokes on + # platform-conditional deps (greenlet) missing from the lockfile. + # The hashes are verified at install time, not audit time. + sed '/^[[:space:]]*--hash/d' requirements.lock > /tmp/requirements.lock.nohash + pip-audit -r /tmp/requirements.lock.nohash --desc on + else + echo "::warning::No requirements.lock found — auditing requirements.txt (unpinned)" + pip-audit -r requirements.txt --desc on + fi + + - name: Check lockfile is up to date + run: | + uv pip compile requirements.txt -o /tmp/requirements.lock.check --generate-hashes + if ! diff -q requirements.lock /tmp/requirements.lock.check > /dev/null 2>&1; then + echo "::warning::requirements.lock is out of date. Run: uv pip compile requirements.txt -o requirements.lock --generate-hashes" + fi + + - name: Audit npm packages + run: | + for pkg in opencode-ai @ai-sdk/openai @openai/codex @google/gemini-cli; do + echo "--- Checking $pkg ---" + npm view "$pkg" version 2>/dev/null || echo "::warning::Could not resolve $pkg" + done diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..e9973c94 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,120 @@ +name: Release + +on: + workflow_dispatch: + inputs: + prerelease: + description: "Mark as pre-release?" + required: false + default: false + type: boolean + +jobs: + release: + runs-on: databrickslabs-protected-runner-group + permissions: + contents: write + + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 + + - name: Read version from pyproject.toml + id: version + run: | + VERSION=$(grep -m1 '^version' pyproject.toml | sed 's/version = "\(.*\)"/\1/') + if ! echo "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then + echo "Error: version '$VERSION' in pyproject.toml is not valid semver" + exit 1 + fi + echo "VERSION=$VERSION" >> "$GITHUB_OUTPUT" + echo "TAG=v$VERSION" >> "$GITHUB_OUTPUT" + echo "Releasing $VERSION" + + - name: Check tag does not already exist + run: | + TAG="${{ steps.version.outputs.TAG }}" + if git tag -l "$TAG" | grep -q "$TAG"; then + echo "Error: tag $TAG already exists — did you forget to bump the version in pyproject.toml?" + exit 1 + fi + + - name: Generate release notes + id: notes + run: | + TAG="${{ steps.version.outputs.TAG }}" + PREV_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "") + + if [ -z "$PREV_TAG" ]; then + RANGE="HEAD" + SINCE_MSG="(all commits — first release)" + else + RANGE="${PREV_TAG}..HEAD" + SINCE_MSG="since $PREV_TAG" + fi + + echo "Generating notes for $RANGE" + + # Categorize commits by conventional commit prefix + FEATURES=$(git log $RANGE --pretty=format:"- %s (%h)" | grep -E "^- feat" | sed 's/^- feat[^:]*: /- /' || true) + FIXES=$(git log $RANGE --pretty=format:"- %s (%h)" | grep -E "^- fix" | sed 's/^- fix[^:]*: /- /' || true) + DOCS=$(git log $RANGE --pretty=format:"- %s (%h)" | grep -E "^- docs" | sed 's/^- docs[^:]*: /- /' || true) + REFACTORS=$(git log $RANGE --pretty=format:"- %s (%h)" | grep -E "^- refactor" | sed 's/^- refactor[^:]*: /- /' || true) + OTHER=$(git log $RANGE --pretty=format:"- %s (%h)" | grep -vE "^- (feat|fix|docs|refactor|chore|ci|test|style|perf|revert|Merge)" || true) + + { + echo "NOTES<> "$GITHUB_OUTPUT" + + - name: Create and push tag + run: | + TAG="${{ steps.version.outputs.TAG }}" + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git tag -a "$TAG" -m "Release $TAG" + git push origin "$TAG" + + - name: Create GitHub Release + uses: softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3 + with: + tag_name: "${{ steps.version.outputs.TAG }}" + name: "${{ steps.version.outputs.TAG }}" + body: ${{ steps.notes.outputs.NOTES }} + prerelease: ${{ inputs.prerelease }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..5fae00c5 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,28 @@ +name: Tests + +on: + workflow_dispatch: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + test: + runs-on: databrickslabs-protected-runner-group + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Set up Python + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: "3.12" + + - name: Install uv + uses: astral-sh/setup-uv@94527f2e458b27549849d47d273a16bec83a01e9 # v7 + + - name: Run tests + run: uv run pytest tests/ -v diff --git a/.github/workflows/update-lockfile.yml b/.github/workflows/update-lockfile.yml new file mode 100644 index 00000000..b297d909 --- /dev/null +++ b/.github/workflows/update-lockfile.yml @@ -0,0 +1,40 @@ +name: Update Lockfile + +on: + push: + branches: [main] + paths: + - "requirements.txt" + +jobs: + update-lockfile: + runs-on: databrickslabs-protected-runner-group + permissions: + contents: write + + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Set up Python + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: "3.11" + + - name: Install uv + uses: astral-sh/setup-uv@94527f2e458b27549849d47d273a16bec83a01e9 # v7 + + - name: Regenerate requirements.lock + run: uv pip compile requirements.txt -o requirements.lock --generate-hashes + + - name: Commit updated lockfile + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + if git diff --quiet requirements.lock; then + echo "requirements.lock is already up to date, nothing to commit" + else + git add requirements.lock + git commit -m "chore: regenerate requirements.lock after requirements.txt update" + git push + fi diff --git a/.gitignore b/.gitignore index 7b753b0c..b05e3f92 100644 --- a/.gitignore +++ b/.gitignore @@ -4,9 +4,29 @@ __pycache__/ .env .venv/ venv/ +outstanding-todos.md # Workspace-specific config (use app.yaml.template) -app.yaml +# app.yaml # Git worktrees .worktrees/ + +# Human tokens (brainstorming notes) +.humantokens/ + +# Uploaded files (clipboard paste images) +uploads/ + +# uv lockfile — not portable across PyPI proxies, generate locally with `uv lock` +uv.lock + +# Codex CLI generated/cached files (only the bundled model catalog is tracked) +.codex/* +!.codex/databricks-models.json + +# Codex skills are generated at runtime by setup_codex.py from .claude/skills/ +.agents/ + +# Agent-plane reference clone +agent-plane-ref/ diff --git a/CLAUDE.md b/CLAUDE.md index a2241b12..5ccac7fc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,6 +1,6 @@ # Claude Code on Databricks -Welcome! This environment comes pre-configured with 30 skills and 2 MCP servers. +Welcome! This environment comes pre-configured with 5 AI coding agents, 39 skills, and 2 MCP servers. Hermes Agent is available alongside Claude Code, Codex, Gemini CLI, and OpenCode — launch it with `hermes chat`. ## Skills (30 total) @@ -75,6 +75,10 @@ Before starting any new project or documentation: 3. **Then start working** - your commits will be backed up to Workspace +## Architecture + +Real-time terminal I/O over **WebSocket** (Flask-SocketIO) with automatic **HTTP polling fallback** via a Web Worker. Single gunicorn worker (PTY fds are process-local), 16 gthread threads. Per-session locks for WebSocket handlers; parallel agent setup at startup via ThreadPoolExecutor. + ## Quick Start - Projects sync to Databricks Workspace on git commit @@ -86,3 +90,6 @@ Before starting any new project or documentation: - Databricks skills from [databricks-solutions/ai-dev-kit](https://github.com/databricks-solutions/ai-dev-kit) - Development workflow skills from [obra/superpowers](https://github.com/obra/superpowers) + +# things to remember +Remember to never move .git folder to the workspace if you're running workspace import. \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..302b215f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,36 @@ +# Contributing to Coding Agents on Databricks Apps + +Thank you for your interest in contributing! We welcome and appreciate contributions from the community. + +## A Note on AI-Assisted Development + +In the age of agentic coding, **code review has become the bottleneck**. It's easier than ever to generate large volumes of code, but every PR still needs a human to carefully review, understand, and approve it. Please be thoughtful about what you submit — don't let an AI agent fire off a sprawling PR without you personally reviewing and understanding every change. + +**Before submitting, ask yourself:** + +- Do I understand every line of this diff? +- Is each change necessary and intentional? +- Have I kept the scope focused rather than letting an agent "improve" unrelated code? + +The easier your PR is to review, the faster it gets merged. Help us help you. 🤝 + +## How to Contribute + +1. **Fork & branch** — Fork the repository and create a descriptive branch for your work (e.g., `fix/websocket-reconnect` or `feat/session-timeout`). + +2. **Keep changes focused** — One logical change per PR. Avoid mixing refactors, formatting changes, or unrelated fixes into the same PR. Try to break larger PRs into small commits. + +3. **Write a test plan** — If your contribution can't be validated with unit tests, include screenshots or a video demonstrating the functionality in your PR description. + +4. **Deploy & verify on your workspace** — Deploy your app on your workspace (use Dogfood if you're a Brickster) and confirm it works as expected before opening a PR. + +5. **Open a pull request** — Write a clear description covering: + - **What** changed and **why** + - How to test or verify the changes + - Any known limitations or follow-up work + +## Code Review + +We review every PR and may request changes. Please don't take feedback personally — we're all working toward the same goal. The smaller and more focused your PR, the faster the turnaround. + +Thank you for contributing! diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 00000000..7e2ee1e5 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,24 @@ +## DB license + +**Definitions**. + +Agreement: The agreement between Databricks, Inc., and you governing the use of the Databricks Services, as that term is defined in the Master Cloud Services Agreement (MCSA) located at www.databricks.com/legal/mcsa. + +Licensed Materials: The source code, object code, data, and/or other works to which this license applies. + +**Scope of Use**. You may not use the Licensed Materials except in connection with your use of the Databricks Services pursuant to the Agreement. Your use of the Licensed Materials must comply at all times with any restrictions applicable to the Databricks Services, generally, and must be used in accordance with any applicable documentation. You may view, use, copy, modify, publish, and/or distribute the Licensed Materials solely for the purposes of using the Licensed Materials within or connecting to the Databricks Services. If you do not agree to these terms, you may not view, use, copy, modify, publish, and/or distribute the Licensed Materials. + +**Redistribution**. You may redistribute and sublicense the Licensed Materials so long as all use is in compliance with these terms. In addition: + +- You must give any other recipients a copy of this License; +- You must cause any modified files to carry prominent notices stating that you changed the files; +- You must retain, in any derivative works that you distribute, all copyright, patent, trademark, and attribution notices, excluding those notices that do not pertain to any part of the derivative works; and +- If a "NOTICE" text file is provided as part of its distribution, then any derivative works that you distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the derivative works. + +You may add your own copyright statement to your modifications and may provide additional license terms and conditions for use, reproduction, or distribution of your modifications, or for any such derivative works as a whole, provided your use, reproduction, and distribution of the Licensed Materials otherwise complies with the conditions stated in this License. + +**Termination**. This license terminates automatically upon your breach of these terms or upon the termination of your Agreement. Additionally, Databricks may terminate this license at any time on notice. Upon termination, you must permanently delete the Licensed Materials and all copies thereof. + +**DISCLAIMER; LIMITATION OF LIABILITY.** + +THE LICENSED MATERIALS ARE PROVIDED “AS-IS” AND WITH ALL FAULTS. DATABRICKS, ON BEHALF OF ITSELF AND ITS LICENSORS, SPECIFICALLY DISCLAIMS ALL WARRANTIES RELATING TO THE LICENSED MATERIALS, EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, IMPLIED WARRANTIES, CONDITIONS AND OTHER TERMS OF MERCHANTABILITY, SATISFACTORY QUALITY OR FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. DATABRICKS AND ITS LICENSORS TOTAL AGGREGATE LIABILITY RELATING TO OR ARISING OUT OF YOUR USE OF OR DATABRICKS’ PROVISIONING OF THE LICENSED MATERIALS SHALL BE LIMITED TO ONE THOUSAND ($1,000) DOLLARS. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE LICENSED MATERIALS OR THE USE OR OTHER DEALINGS IN THE LICENSED MATERIALS. diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..f9eb66db --- /dev/null +++ b/Makefile @@ -0,0 +1,170 @@ +# Makefile for deploying Coding Agents to Databricks Apps +# +# Usage: +# make deploy PROFILE=dogfood # full deploy (create app, sync, deploy) +# make redeploy PROFILE=dogfood # skip app creation, just sync + deploy +# make create-pat PROFILE=dogfood # generate a 1-day PAT and copy to clipboard +# make status PROFILE=dogfood # check app status +# make open PROFILE=dogfood # open app in browser +# make clean PROFILE=dogfood # remove app and secret scope + +# Configuration (accepts lowercase: make deploy profile=dogfood) +ifdef profile +PROFILE := $(profile) +endif +ifdef app_name +APP_NAME := $(app_name) +endif +ifdef pat +PAT := $(pat) +endif +PROFILE ?= DEFAULT +APP_NAME ?= coding-agents +SECRET_SCOPE ?= $(APP_NAME)-secrets +SECRET_KEY ?= databricks-token +# Lakebase memory: set LAKEBASE_ENDPOINT to wire database resource (grants SP access + injects host) +# Format: projects/{project_id}/branches/{branch_id}/endpoints/{endpoint_id} +LAKEBASE_ENDPOINT ?= +LAKEBASE_DB ?= databricks_postgres + +# Resolve user email and workspace path from the profile +USER_EMAIL = $(shell databricks current-user me --profile $(PROFILE) --output json 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('userName',''))") +WORKSPACE_PATH = /Workspace/Users/$(USER_EMAIL)/apps/$(APP_NAME) + +.PHONY: help test deploy-e2e deploy redeploy create-app create-pat setup-secret link-resources sync deploy-app status open clean clean-secret + +# ── Help ───────────────────────────────────────────── + +test: ## Run unit tests + uv run pytest tests/ -v + +help: ## Show this help + @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-18s\033[0m %s\n", $$1, $$2}' + +# ── Workflows ──────────────────────────────────────── + +deploy: create-app sync deploy-app ## Full deploy (create app, sync, deploy) + @echo "" + @echo "Deployment complete! App URL:" + @databricks apps get $(APP_NAME) --profile $(PROFILE) --output json 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('url','(pending)'))" + +redeploy: sync deploy-app ## Redeploy: sync + deploy (skip secret setup) + @echo "" + @echo "Redeployment complete!" + +# ── Building Blocks ────────────────────────────────── + +create-app: ## Create the Databricks App (idempotent) + @echo "==> Checking if app '$(APP_NAME)' exists..." + @state=$$(databricks apps get $(APP_NAME) --profile $(PROFILE) --output json 2>/dev/null \ + | python3 -c "import sys,json; print(json.load(sys.stdin).get('compute_status',{}).get('state',''))" 2>/dev/null); \ + if [ "$$state" = "DELETING" ]; then \ + echo " App '$(APP_NAME)' is still deleting, waiting..."; \ + while [ "$$state" = "DELETING" ]; do \ + sleep 10; \ + state=$$(databricks apps get $(APP_NAME) --profile $(PROFILE) --output json 2>/dev/null \ + | python3 -c "import sys,json; print(json.load(sys.stdin).get('compute_status',{}).get('state',''))" 2>/dev/null); \ + done; \ + echo " Deletion complete."; \ + echo " Creating app '$(APP_NAME)'..."; \ + databricks apps create $(APP_NAME) --profile $(PROFILE); \ + elif [ -n "$$state" ]; then \ + echo " App '$(APP_NAME)' already exists (state: $$state), skipping create."; \ + else \ + echo " Creating app '$(APP_NAME)'..."; \ + databricks apps create $(APP_NAME) --profile $(PROFILE); \ + fi + +create-pat: ## Generate a 90-day PAT and store it as the app secret + @echo "==> Ensuring secret scope '$(SECRET_SCOPE)' exists..." + @if databricks secrets list-scopes --profile $(PROFILE) --output json 2>/dev/null | python3 -c "import sys,json; d=json.load(sys.stdin); scopes=[s['name'] for s in (d if isinstance(d,list) else d.get('scopes',[]))]; exit(0 if '$(SECRET_SCOPE)' in scopes else 1)" 2>/dev/null; then \ + echo " Secret scope '$(SECRET_SCOPE)' already exists."; \ + else \ + echo " Creating secret scope '$(SECRET_SCOPE)'..."; \ + databricks secrets create-scope $(SECRET_SCOPE) --profile $(PROFILE); \ + fi + @echo "==> Generating a 90-day PAT..." + @databricks tokens create --lifetime-seconds $$((90 * 24 * 60 * 60)) --comment "coding-agents (auto-generated)" --profile $(PROFILE) --output json \ + | python3 -c "import sys,json; print(json.load(sys.stdin)['token_value'])" \ + | databricks secrets put-secret $(SECRET_SCOPE) $(SECRET_KEY) --profile $(PROFILE) + @echo " PAT created and stored in $(SECRET_SCOPE)/$(SECRET_KEY)" + +setup-secret: ## Create secret scope and store PAT (interactive) + @echo "==> Setting up DATABRICKS_TOKEN secret..." + @# Create scope if it doesn't exist + @if databricks secrets list-scopes --profile $(PROFILE) --output json 2>/dev/null | python3 -c "import sys,json; d=json.load(sys.stdin); scopes=[s['name'] for s in (d if isinstance(d,list) else d.get('scopes',[]))]; exit(0 if '$(SECRET_SCOPE)' in scopes else 1)" 2>/dev/null; then \ + echo " Secret scope '$(SECRET_SCOPE)' already exists."; \ + else \ + echo " Creating secret scope '$(SECRET_SCOPE)'..."; \ + databricks secrets create-scope $(SECRET_SCOPE) --profile $(PROFILE); \ + fi + @# Store the PAT - prompt if not provided + @if [ -z "$(PAT)" ]; then \ + echo " Enter your Databricks PAT (will not echo):"; \ + read -s pat_value && \ + echo "$$pat_value" | databricks secrets put-secret $(SECRET_SCOPE) $(SECRET_KEY) --profile $(PROFILE); \ + else \ + echo "$(PAT)" | databricks secrets put-secret $(SECRET_SCOPE) $(SECRET_KEY) --profile $(PROFILE); \ + fi + @echo " Secret stored in $(SECRET_SCOPE)/$(SECRET_KEY)" + +link-resources: ## Add Lakebase postgres resource to app (preserves existing resources) + @if [ -z "$(LAKEBASE_ENDPOINT)" ]; then \ + echo "Error: LAKEBASE_ENDPOINT required."; \ + echo "Usage: make link-resources LAKEBASE_ENDPOINT=projects/.../branches/.../endpoints/... PROFILE=daveok"; \ + exit 1; \ + fi + @echo "==> Ensuring secret scope and ENDPOINT_NAME secret..." + @if ! databricks secrets list-scopes --profile $(PROFILE) --output json 2>/dev/null | python3 -c "import sys,json; d=json.load(sys.stdin); scopes=[s['name'] for s in (d if isinstance(d,list) else d.get('scopes',[]))]; exit(0 if '$(SECRET_SCOPE)' in scopes else 1)" 2>/dev/null; then \ + databricks secrets create-scope $(SECRET_SCOPE) --profile $(PROFILE); \ + fi + @printf '%s' '$(LAKEBASE_ENDPOINT)' | databricks secrets put-secret $(SECRET_SCOPE) ENDPOINT_NAME --profile $(PROFILE) + @echo "==> Merging Lakebase resource into existing app resources..." + @DATABRICKS_CONFIG_PROFILE=$(PROFILE) uv run python3 -c "\ +import json, os, sys; \ +from databricks.sdk import WorkspaceClient; \ +w = WorkspaceClient(profile='$(PROFILE)'); \ +ep = '$(LAKEBASE_ENDPOINT)'; \ +branch = ep.rsplit('/endpoints/', 1)[0]; \ +dbs = list(w.postgres.list_databases(parent=branch)); \ +db = next((d.name for d in dbs if d.database_name == '$(LAKEBASE_DB)'), dbs[0].name if dbs else None); \ +assert db, 'no database found under ' + branch; \ +app = w.apps.get(name='$(APP_NAME)'); \ +existing = [r.as_dict() for r in (app.resources or [])]; \ +merged = {r['name']: r for r in existing}; \ +merged['postgres'] = {'name':'postgres','description':'Lakebase Autoscaling memory database','postgres':{'branch':branch,'database':db,'permission':'CAN_CONNECT_AND_CREATE'}}; \ +merged['ENDPOINT_NAME'] = {'name':'ENDPOINT_NAME','description':'Lakebase endpoint resource path','secret':{'scope':'$(SECRET_SCOPE)','key':'ENDPOINT_NAME','permission':'READ'}}; \ +print(json.dumps({'resources': list(merged.values())})) \ +" | curl -s -X PATCH \ + "$$(databricks auth env --profile $(PROFILE) 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin)['env']['DATABRICKS_HOST'])")/api/2.0/apps/$(APP_NAME)" \ + -H "Authorization: Bearer $$(databricks auth token --profile $(PROFILE) 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])")" \ + -H "Content-Type: application/json" \ + -d @- >/dev/null + @echo " Linked postgres resource ($(LAKEBASE_ENDPOINT)) + ENDPOINT_NAME secret; existing resources preserved." + +sync: ## Sync local files to Databricks workspace + @echo "==> Syncing to $(WORKSPACE_PATH)..." + @databricks sync . $(WORKSPACE_PATH) --watch=false --profile $(PROFILE) + +deploy-app: ## Deploy the app from workspace + @echo "==> Deploying app '$(APP_NAME)'..." + @databricks apps deploy $(APP_NAME) --source-code-path $(WORKSPACE_PATH) --profile $(PROFILE) --no-wait + +# ── Monitoring ─────────────────────────────────────── + +status: ## Check app status + @databricks apps get $(APP_NAME) --profile $(PROFILE) + +open: ## Open the app in browser + @databricks apps get $(APP_NAME) --profile $(PROFILE) --output json 2>/dev/null \ + | python3 -c "import sys,json; print(json.load(sys.stdin).get('url',''))" \ + | xargs open + +# ── Cleanup (destructive) ─────────────────────────── + +clean: ## Remove the app (destructive) + @echo "==> Removing app '$(APP_NAME)'..." + @databricks apps delete $(APP_NAME) --profile $(PROFILE) 2>/dev/null && \ + echo " App '$(APP_NAME)' deleted." || \ + echo " App '$(APP_NAME)' not found or already deleted." + diff --git a/NOTICE.md b/NOTICE.md new file mode 100644 index 00000000..6c19f156 --- /dev/null +++ b/NOTICE.md @@ -0,0 +1,194 @@ +# CoDA - Coding Agents on Databricks Apps + +Copyright (2026) Databricks, Inc. + +This Software includes software developed at Databricks (https://www.databricks.com/) and its use is subject to the included LICENSE file (Databricks License). + +--- + +Dependencies are grouped below by license. Each table row lists a third-party package bundled or used at runtime, along with its license and upstream source. + +This NOTICE is regenerated from `pip-licenses` and `uv.lock` (Python), `npm view` (npm), and upstream repositories (Git-installed tools). See `pyproject.toml` for the direct Python dependency declarations. + +## Installed AI Coding Agents + +The following tools are installed at runtime as user-facing coding agents. They are not Python library dependencies but standalone CLI tools provisioned by the setup scripts. + +| Tool | Install Method | Package | License | Copyright | Source | +| --- | --- | --- | --- | --- | --- | +| Claude Code | curl \| bash | @anthropic-ai/claude-code | Custom (see README.md) | Anthropic, PBC. | [https://github.com/anthropics/claude-code](https://github.com/anthropics/claude-code) | +| Codex | npm install -g | @openai/codex | Apache-2.0 | OpenAI | [https://github.com/openai/codex](https://github.com/openai/codex) | +| Gemini CLI | npm install -g | @google/gemini-cli | Apache-2.0 | Google LLC | [https://github.com/google-gemini/gemini-cli](https://github.com/google-gemini/gemini-cli) | +| Hermes Agent | uv tool install (Git) | hermes-agent | MIT | Nous Research | [https://github.com/NousResearch/hermes-agent](https://github.com/NousResearch/hermes-agent) | +| OpenCode | npm install -g | opencode-ai | MIT | OpenCode contributors | [https://github.com/nicepkg/opencode](https://github.com/nicepkg/opencode) | + +Additionally, OpenCode installs `@ai-sdk/openai` (Apache-2.0, Vercel Inc.) as a runtime provider SDK. + +All agent versions are resolved dynamically at install time (latest from npm registry or Git HEAD); no versions are pinned. See `setup_claude.py`, `setup_codex.py`, `setup_gemini.py`, `setup_hermes.py`, and `setup_opencode.py` for installation details. + +--- + +## MCP Servers (Remote Services) + +The following Model Context Protocol (MCP) servers are configured as remote endpoints. They are not installed locally but accessed over HTTPS at runtime. + +| Server | Endpoint | License | Provider | Source | +| --- | --- | --- | --- | --- | +| DeepWiki | https://mcp.deepwiki.com/mcp | MIT | Cognition AI (Devin) | [https://github.com/regenrek/deepwiki-mcp](https://github.com/regenrek/deepwiki-mcp) | +| Exa | https://mcp.exa.ai/mcp | MIT (server reference impl.) | Exa Labs | [https://github.com/exa-labs/exa-mcp-server](https://github.com/exa-labs/exa-mcp-server) | + +--- + +## Bundled Skills and Plugins + +The following skill sets are bundled in `.claude/skills/` and `.claude/plugins/` to provide Databricks-specific knowledge and development workflows. + +| Source | License | Copyright | Source | +| --- | --- | --- | --- | +| [databricks-solutions/ai-dev-kit](https://github.com/databricks-solutions/ai-dev-kit) (Databricks skills) | Databricks License | Databricks, Inc. | [https://github.com/databricks-solutions/ai-dev-kit](https://github.com/databricks-solutions/ai-dev-kit) | +| [obra/superpowers](https://github.com/obra/superpowers) (development workflow skills) | MIT License | Jesse Vincent | [https://github.com/obra/superpowers](https://github.com/obra/superpowers) | + +--- + +## Python Dependencies + +**Dual-licensed Python packages** — the following packages offer a choice of license. They are listed below under the first license option: +- `cryptography` 47.0.0 — Apache-2.0 **OR** BSD-3-Clause (listed under Apache License 2.0) +- `packaging` 26.2 — Apache-2.0 **OR** BSD-2-Clause (listed under Apache License 2.0) +- `sniffio` 1.3.1 — Apache-2.0 **OR** MIT (listed under MIT License) + +**Platform-conditional packages** — the following packages are in `uv.lock` but only installed on specific platforms or Python versions: +- `colorama` 0.4.6 — BSD License — Windows only ([https://github.com/tartley/colorama](https://github.com/tartley/colorama)) +- `exceptiongroup` 1.3.1 — MIT License — Python < 3.11 only ([https://github.com/agronholm/exceptiongroup](https://github.com/agronholm/exceptiongroup)) +- `pywin32` 311 — PSF-2.0 — Windows only ([https://github.com/mhammond/pywin32](https://github.com/mhammond/pywin32)) + +--- + +## Apache License 2.0 + +Full license text: [https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0). + +| Package | Version | Ecosystem | Type | Copyright | Source | +| --- | --- | --- | --- | --- | --- | +| cryptography | 47.0.0 | Python | runtime | The Python Cryptographic Authority and individual contributors | [https://github.com/pyca/cryptography](https://github.com/pyca/cryptography) | +| databricks-sdk | 0.105.0 | Python | runtime | Databricks, Inc. | [https://databricks-sdk-py.readthedocs.io](https://databricks-sdk-py.readthedocs.io) | +| google-auth | 2.49.2 | Python | runtime | Google Cloud Platform | [https://github.com/googleapis/google-auth-library-python](https://github.com/googleapis/google-auth-library-python) | +| importlib-metadata | 8.7.1 | Python | runtime | Jason R. Coombs | [https://github.com/python/importlib_metadata](https://github.com/python/importlib_metadata) | +| mlflow-skinny | 3.11.1 | Python | runtime | Databricks, Inc. | [https://mlflow.org](https://mlflow.org) | +| opentelemetry-api | 1.41.1 | Python | runtime | OpenTelemetry Authors | [https://github.com/open-telemetry/opentelemetry-python](https://github.com/open-telemetry/opentelemetry-python) | +| opentelemetry-proto | 1.41.1 | Python | runtime | OpenTelemetry Authors | [https://github.com/open-telemetry/opentelemetry-python](https://github.com/open-telemetry/opentelemetry-python) | +| opentelemetry-sdk | 1.41.1 | Python | runtime | OpenTelemetry Authors | [https://github.com/open-telemetry/opentelemetry-python](https://github.com/open-telemetry/opentelemetry-python) | +| opentelemetry-semantic-conventions | 0.62b1 | Python | runtime | OpenTelemetry Authors | [https://github.com/open-telemetry/opentelemetry-python](https://github.com/open-telemetry/opentelemetry-python) | +| packaging | 26.2 | Python | runtime | Donald Stufft | [https://github.com/pypa/packaging](https://github.com/pypa/packaging) | +| python-multipart | 0.0.26 | Python | runtime | Andrew Dunham | [https://github.com/Kludex/python-multipart](https://github.com/Kludex/python-multipart) | +| requests | 2.33.0 | Python | runtime | Kenneth Reitz | [https://github.com/psf/requests](https://github.com/psf/requests) | + +--- + +## BSD 2-Clause License + +Full license text: [https://opensource.org/licenses/BSD-2-Clause](https://opensource.org/licenses/BSD-2-Clause). + +| Package | Version | Ecosystem | Type | Copyright | Source | +| --- | --- | --- | --- | --- | --- | +| pyasn1 | 0.6.3 | Python | runtime | Ilya Etingof | [https://github.com/pyasn1/pyasn1](https://github.com/pyasn1/pyasn1) | + +--- + +## BSD 3-Clause License + +Full license text: [https://opensource.org/licenses/BSD-3-Clause](https://opensource.org/licenses/BSD-3-Clause). + +| Package | Version | Ecosystem | Type | Copyright | Source | +| --- | --- | --- | --- | --- | --- | +| click | 8.3.3 | Python | runtime | Pallets | [https://github.com/pallets/click/](https://github.com/pallets/click/) | +| Flask | 3.1.3 | Python | runtime | Pallets | [https://github.com/pallets/flask/](https://github.com/pallets/flask/) | +| GitPython | 3.1.47 | Python | runtime | Sebastian Thiel, Michael Trier | [https://github.com/gitpython-developers/GitPython](https://github.com/gitpython-developers/GitPython) | +| httpcore | 1.0.9 | Python | runtime | Tom Christie | [https://www.encode.io/httpcore/](https://www.encode.io/httpcore/) | +| idna | 3.13 | Python | runtime | Kim Davies | [https://github.com/kjd/idna](https://github.com/kjd/idna) | +| MarkupSafe | 3.0.3 | Python | runtime | Pallets | [https://github.com/pallets/markupsafe/](https://github.com/pallets/markupsafe/) | +| protobuf | 6.33.6 | Python | runtime | Google LLC | [https://developers.google.com/protocol-buffers/](https://developers.google.com/protocol-buffers/) | +| pycparser | 3.0 | Python | runtime | Eli Bendersky | [https://github.com/eliben/pycparser](https://github.com/eliben/pycparser) | +| python-dotenv | 1.2.2 | Python | runtime | Saurabh Kumar | [https://github.com/theskumar/python-dotenv](https://github.com/theskumar/python-dotenv) | +| sse-starlette | 3.4.1 | Python | runtime | sysid | [https://github.com/sysid/sse-starlette](https://github.com/sysid/sse-starlette) | +| starlette | 1.0.0 | Python | runtime | Tom Christie | [https://github.com/Kludex/starlette](https://github.com/Kludex/starlette) | +| uvicorn | 0.46.0 | Python | runtime | Tom Christie | [https://uvicorn.dev/](https://uvicorn.dev/) | +| Werkzeug | 3.1.8 | Python | runtime | Pallets | [https://github.com/pallets/werkzeug/](https://github.com/pallets/werkzeug/) | + +--- + +## BSD License + +Full license text: [https://opensource.org/licenses/BSD-3-Clause](https://opensource.org/licenses/BSD-3-Clause). + +| Package | Version | Ecosystem | Type | Copyright | Source | +| --- | --- | --- | --- | --- | --- | +| cloudpickle | 3.1.2 | Python | runtime | The cloudpickle developer team | [https://github.com/cloudpipe/cloudpickle](https://github.com/cloudpipe/cloudpickle) | +| gitdb | 4.0.12 | Python | runtime | Sebastian Thiel | [https://github.com/gitpython-developers/gitdb](https://github.com/gitpython-developers/gitdb) | +| httpx | 0.28.1 | Python | runtime | Tom Christie | [https://github.com/encode/httpx](https://github.com/encode/httpx) | +| itsdangerous | 2.2.0 | Python | runtime | Pallets | [https://github.com/pallets/itsdangerous/](https://github.com/pallets/itsdangerous/) | +| Jinja2 | 3.1.6 | Python | runtime | Pallets | [https://github.com/pallets/jinja/](https://github.com/pallets/jinja/) | +| pyasn1-modules | 0.4.2 | Python | runtime | Ilya Etingof | [https://github.com/pyasn1/pyasn1-modules](https://github.com/pyasn1/pyasn1-modules) | +| smmap | 5.0.3 | Python | runtime | Sebastian Thiel | [https://github.com/gitpython-developers/smmap](https://github.com/gitpython-developers/smmap) | +| sqlparse | 0.5.5 | Python | runtime | Andi Albrecht | [https://github.com/andialbrecht/sqlparse](https://github.com/andialbrecht/sqlparse) | + +--- + +## MIT License + +Full license text: [https://opensource.org/licenses/MIT](https://opensource.org/licenses/MIT). + +| Package | Version | Ecosystem | Type | Copyright | Source | +| --- | --- | --- | --- | --- | --- | +| annotated-doc | 0.0.4 | Python | runtime | Sebastian Ramirez | [https://github.com/fastapi/annotated-doc](https://github.com/fastapi/annotated-doc) | +| annotated-types | 0.7.0 | Python | runtime | Adrian Garcia Badaracco, Samuel Colvin, Zac Hatfield-Dodds | [https://github.com/annotated-types/annotated-types](https://github.com/annotated-types/annotated-types) | +| anyio | 4.13.0 | Python | runtime | Alex Gronholm | [https://anyio.readthedocs.io/en/stable/](https://anyio.readthedocs.io/en/stable/) | +| attrs | 26.1.0 | Python | runtime | Hynek Schlawack | [https://www.attrs.org/](https://www.attrs.org/) | +| blinker | 1.9.0 | Python | runtime | Jason Kirtland | [https://github.com/pallets-eco/blinker/](https://github.com/pallets-eco/blinker/) | +| cachetools | 7.0.6 | Python | runtime | Thomas Kemmer | [https://github.com/tkem/cachetools/](https://github.com/tkem/cachetools/) | +| cffi | 2.0.0 | Python | runtime | Armin Rigo, Maciej Fijalkowski | [https://cffi.readthedocs.io/](https://cffi.readthedocs.io/) | +| charset-normalizer | 3.4.7 | Python | runtime | Ahmed R. TAHRI | [https://github.com/jawah/charset_normalizer](https://github.com/jawah/charset_normalizer) | +| claude-agent-sdk | 0.1.68 | Python | runtime | Anthropic, PBC. | [https://github.com/anthropics/claude-agent-sdk-python](https://github.com/anthropics/claude-agent-sdk-python) | +| fastapi | 0.136.1 | Python | runtime | Sebastian Ramirez | [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi) | +| Flask-SocketIO | 5.6.1 | Python | runtime | Miguel Grinberg | [https://github.com/miguelgrinberg/flask-socketio](https://github.com/miguelgrinberg/flask-socketio) | +| h11 | 0.16.0 | Python | runtime | Nathaniel J. Smith | [https://github.com/python-hyper/h11](https://github.com/python-hyper/h11) | +| httpx-sse | 0.4.3 | Python | runtime | Florimond Manca | [https://github.com/florimondmanca/httpx-sse](https://github.com/florimondmanca/httpx-sse) | +| jsonschema | 4.26.0 | Python | runtime | Julian Berman | [https://github.com/python-jsonschema/jsonschema](https://github.com/python-jsonschema/jsonschema) | +| jsonschema-specifications | 2025.9.1 | Python | runtime | Julian Berman | [https://github.com/python-jsonschema/jsonschema-specifications](https://github.com/python-jsonschema/jsonschema-specifications) | +| mcp | 1.27.0 | Python | runtime | Anthropic, PBC. | [https://modelcontextprotocol.io](https://modelcontextprotocol.io) | +| pydantic | 2.13.3 | Python | runtime | Samuel Colvin et al. | [https://github.com/pydantic/pydantic](https://github.com/pydantic/pydantic) | +| pydantic-core | 2.46.3 | Python | runtime | Samuel Colvin et al. | [https://github.com/pydantic/pydantic](https://github.com/pydantic/pydantic) | +| pydantic-settings | 2.14.0 | Python | runtime | Samuel Colvin, Eric Jolibois, Hasan Ramezani | [https://github.com/pydantic/pydantic-settings](https://github.com/pydantic/pydantic-settings) | +| PyJWT | 2.12.1 | Python | runtime | Jose Padilla | [https://github.com/jpadilla/pyjwt](https://github.com/jpadilla/pyjwt) | +| python-engineio | 4.13.1 | Python | runtime | Miguel Grinberg | [https://github.com/miguelgrinberg/python-engineio](https://github.com/miguelgrinberg/python-engineio) | +| python-socketio | 5.16.1 | Python | runtime | Miguel Grinberg | [https://github.com/miguelgrinberg/python-socketio](https://github.com/miguelgrinberg/python-socketio) | +| PyYAML | 6.0.3 | Python | runtime | Kirill Simonov | [https://pyyaml.org/](https://pyyaml.org/) | +| referencing | 0.37.0 | Python | runtime | Julian Berman | [https://github.com/python-jsonschema/referencing](https://github.com/python-jsonschema/referencing) | +| rpds-py | 0.30.0 | Python | runtime | Julian Berman | [https://github.com/crate-py/rpds](https://github.com/crate-py/rpds) | +| simple-websocket | 1.1.0 | Python | runtime | Miguel Grinberg | [https://github.com/miguelgrinberg/simple-websocket](https://github.com/miguelgrinberg/simple-websocket) | +| sniffio | 1.3.1 | Python | runtime | Nathaniel J. Smith | [https://github.com/python-trio/sniffio](https://github.com/python-trio/sniffio) | +| typing-inspection | 0.4.2 | Python | runtime | Victorien Plot | [https://github.com/pydantic/typing-inspection](https://github.com/pydantic/typing-inspection) | +| urllib3 | 2.6.3 | Python | runtime | Andrey Petrov | [https://github.com/urllib3/urllib3](https://github.com/urllib3/urllib3) | +| wsproto | 1.3.2 | Python | runtime | Benno Rice | [https://github.com/python-hyper/wsproto/](https://github.com/python-hyper/wsproto/) | +| zipp | 3.23.1 | Python | runtime | Jason R. Coombs | [https://github.com/jaraco/zipp](https://github.com/jaraco/zipp) | + +--- + +## Mozilla Public License 2.0 + +Full license text: [https://opensource.org/licenses/MPL-2.0](https://opensource.org/licenses/MPL-2.0). + +| Package | Version | Ecosystem | Type | Copyright | Source | +| --- | --- | --- | --- | --- | --- | +| bidict | 0.23.1 | Python | runtime | Joshua Bronson | [https://github.com/jab/bidict](https://github.com/jab/bidict) | +| certifi | 2026.4.22 | Python | runtime | Kenneth Reitz | [https://github.com/certifi/python-certifi](https://github.com/certifi/python-certifi) | + +--- + +## Python Software Foundation License + +Full license text: [https://docs.python.org/3/license.html](https://docs.python.org/3/license.html). + +| Package | Version | Ecosystem | Type | Copyright | Source | +| --- | --- | --- | --- | --- | --- | +| typing_extensions | 4.15.0 | Python | runtime | Guido van Rossum, Jukka Lehtosalo, Lukasz Langa, Michael Lee | [https://github.com/python/typing_extensions](https://github.com/python/typing_extensions) | diff --git a/README.md b/README.md index 20b286c8..fd492bd1 100644 --- a/README.md +++ b/README.md @@ -1,264 +1,355 @@ -# claude-code-cli-bricks -### What is it? +# Coding Agents on Databricks Apps -TL;DR: Claude Code on Databricks Apps for All Databricks Users 🚀 +[![Use this template](https://img.shields.io/badge/Use%20this%20template-2ea44f?logo=github)](https://github.com/datasciencemonkey/coding-agents-databricks-apps/generate) +[![Deploy to Databricks](https://img.shields.io/badge/Deploy-Databricks%20Apps-FF3621?logo=databricks&logoColor=white)](docs/deployment.md) +[![Agents](https://img.shields.io/badge/Agents-5%20included-green)](#whats-inside) +[![Skills](https://img.shields.io/badge/Skills-39%20built--in-blue)](#-all-39-skills) -A browser-based terminal emulator built with Flask and xterm.js, designed for cloud development environments with Databricks workspace integration and Claude Code CLI support. +> Run Claude Code, Codex, Gemini CLI, Hermes Agent, and OpenCode in your browser — zero setup, wired to your Databricks workspace. -### Why now? -On Jan 26. 2026, Andrej Karpathy made [this viral tweet](https://x.com/karpathy/status/2015883857489522876?s=46&t=tEsLJXJnGFIkaWs-Bhs1yA). Boris Cherny, the creator of claude code responded and said the following. -![alt text](image.png) +--- -This app template opens this up for all Databricks Users! ❤️ +## Screenshots -No more pesky IDE setups, no bespoke tweaks. +
+ CODA demo — splash screen, multi-tab terminals, keyboard shortcuts +
-Just use it all on Databricks, from the browser. Wired up to model serving endpoints on your workspace. +--- -## Features +## What's Inside -✅ **Browser-based Terminal** - Full PTY support with xterm.js frontend +🟠 **Claude Code** — Anthropic's coding agent with 39 Databricks skills + 2 MCP servers -✅ **Real-time I/O** - Responsive terminal with polling-based communication +🟣 **Codex** — OpenAI's coding agent, pre-configured for Databricks -✅ **Terminal Resizing** - Dynamic resize support for responsive layouts +🔵 **Gemini CLI** — Google's coding agent with shared skills -✅ **Databricks Workspace Integration** - Auto-sync projects to Databricks Workspace on git commits +🟡 **Hermes Agent** — NousResearch's multi-provider AI CLI with tool-calling and skills -✅ **Claude Code CLI** - Pre-configured to use Databricks hosted models as the API endpoint +🟢 **OpenCode** — Open-source agent with multi-provider support -✅ **Configurable Model** - Switch between Claude models via `app.yaml` (default: `databricks-claude-sonnet-4-5`) +Every agent installs at boot and connects to your **Databricks AI Gateway** — on first terminal session, paste a short-lived PAT and all CLIs are configured automatically. Token auto-rotates every 10 minutes. -✅ **Micro Editor** - Ships with [micro](https://micro-editor.github.io/), a modern terminal-based text editor +--- -✅ **Databricks CLI** - Pre-configured with your PAT for immediate use +## Why Databricks -✅ **Single-User Security** - Only the token owner can access the terminal +This isn't just a terminal in the cloud. Running coding agents on Databricks gives you enterprise-grade infrastructure out of the box: -✅ **MCP Servers** - DeepWiki for GitHub docs, Exa for web search +| | Benefit | What you get | +|---|---|---| +| 🔐 | **Unity Catalog Integration** | All data access governed by UC permissions — agents can only touch what your identity allows | +| 🤖 | **AI Gateway** | Route all LLM calls through a single control plane — swap models, set rate limits, and manage API keys centrally | +| 🔀 | **Multi-AI & Multi-Agent** | Switch between Claude, GPT, Gemini, and open-source models on the fly — change the model or agent without redeploying | +| 📊 | **Consumption Monitoring** | Track token usage, cost, and latency per user and per model via the AI Gateway control center dashboard | +| 🔍 | **MLflow Tracing** | Every Claude Code session is automatically traced — review prompts, tool calls, and outputs in your MLflow experiment | +| 🧬 | **Assess Traces with Genie** | Point Genie at your MLflow traces to ask natural-language questions about agent behavior, cost patterns, and session quality | +| 📝 | **App Logs to Delta** | Optionally route application logs to Delta tables for long-term retention, querying, and dashboarding | -### 30 Pre-installed Skills +--- -✅ **Databricks Skills (16)** - Make building Databricks products simple. Create dashboards, jobs, pipelines, agents, and more with guided workflows that understand Databricks APIs and best practices. +## Terminal Features -✅ **Superpowers Skills (14)** - Provide the agentic framework for Claude Code. Test-driven development, systematic debugging, brainstorming, parallel agent workflows, and structured planning for complex tasks. +| | | +|---|---| +| 🎨 **8 Themes** | Dracula, Nord, Solarized, Monokai, GitHub Dark, and more | +| ✂️ **Split Panes** | Run two sessions side by side with a draggable divider | +| 🌐 **WebSocket I/O** | Real-time terminal output over WebSocket — zero-latency, eliminates polling delay | +| 🔁 **HTTP Polling Fallback** | Automatic fallback via Web Worker when WebSocket is unavailable | +| 🚀 **Parallel Setup** | 7 agent setups run in parallel (~5x faster startup) | +| 🔍 **Search** | Find anything in your terminal history (Ctrl+Shift+F) | +| 🎤 **Voice Input** | Dictate commands with your mic (Option+V) | +| 📋 **Image Paste** | Paste or drag-and-drop images into the terminal — saved to `~/uploads/`, path inserted automatically | +| ⌨️ **Customizable** | Fonts, font sizes, themes — all persisted across sessions | +| 🔄 **Workspace Sync** | Every `git commit` auto-syncs to `/Workspace/Users/{you}/projects/` | +| ✏️ **Micro Editor** | Modern terminal editor, pre-installed | +| ⚙️ **Databricks CLI** | Installed at boot, configured interactively on first session | +| 📊 **MLflow Tracing** | Every Claude Code session is automatically traced to your Databricks MLflow experiment | -## Skill Details +--- -### Databricks Skills +## MLflow Tracing -From [databricks-solutions/ai-dev-kit](https://github.com/databricks-solutions/ai-dev-kit): +Every Claude Code session is **automatically traced** to a Databricks MLflow experiment — zero configuration required. -| Category | Skills | -|----------|--------| -| AI & Agents | agent-bricks, databricks-genie, mlflow-evaluation, model-serving | -| Analytics | aibi-dashboards, databricks-unity-catalog | -| Data Engineering | spark-declarative-pipelines, databricks-jobs, synthetic-data-generation | -| Development | asset-bundles, databricks-app-apx, databricks-app-python, databricks-python-sdk, databricks-config | -| Reference | databricks-docs, unstructured-pdf-generation | +### How it works -### Development Workflow Skills +``` +Claude Code session starts + │ + ▼ + Environment vars set automatically: + MLFLOW_TRACKING_URI=databricks + MLFLOW_EXPERIMENT_NAME=/Users/{you}/{app-name} + │ + ▼ + You work normally — code, debug, deploy + │ + ▼ + Session ends → Stop hook fires + │ + ▼ + Full session transcript logged as an MLflow trace + at /Users/{you}/{app-name} in your workspace +``` -From [obra/superpowers](https://github.com/obra/superpowers): +### What gets traced -- brainstorming, test-driven-development, systematic-debugging, writing-plans -- verification-before-completion, executing-plans, dispatching-parallel-agents -- subagent-driven-development, using-git-worktrees, requesting-code-review -- receiving-code-review, finishing-a-development-branch, writing-skills, using-superpowers +When a Claude Code session ends, the **Stop hook** automatically calls `mlflow.claude_code.hooks.stop_hook_handler()`, which captures the full session transcript — your prompts, agent actions, tool calls, and outputs — and logs it as an MLflow trace. -## MCP Servers +### Where traces live -Pre-configured MCP servers for enhanced capabilities: +Traces are stored in a Databricks MLflow experiment at: -| Server | Description | -|--------|-------------| -| **DeepWiki** | AI-powered documentation for any GitHub repository | -| **Exa** | Web search and code context retrieval | +``` +/Users/{your-email}/{app-name} +``` -### Updating Skills +For example, if you're `jane@company.com` and your app is named `coding-agents`: -Skills are bundled with the app. To update: +``` +/Users/jane@company.com/coding-agents +``` -1. Pull latest from [ai-dev-kit](https://github.com/databricks-solutions/ai-dev-kit) -2. Copy `databricks-skills/*` to `.claude/skills/` -3. For superpowers, pull latest from [obra/superpowers](https://github.com/obra/superpowers) and copy `skills/*` to `.claude/skills/` -4. Redeploy the app +View them in the Databricks UI: **Workspace > Machine Learning > Experiments**. -## Quick Start +### Configuration -### Prerequisites +Tracing is configured during app startup by `setup_mlflow.py`, which merges the following into `~/.claude/settings.json`: -- Python 3.11+ -- [uv](https://github.com/astral-sh/uv) (recommended) or pip +| Setting | Value | Purpose | +|---------|-------|---------| +| `MLFLOW_CLAUDE_TRACING_ENABLED` | `true` | Enables Claude Code tracing | +| `MLFLOW_TRACKING_URI` | `databricks` | Routes traces to Databricks backend | +| `MLFLOW_EXPERIMENT_NAME` | `/Users/{owner}/{app}` | Target experiment path | +| `OTEL_EXPORTER_OTLP_ENDPOINT` | `""` | Overrides container OTEL to prevent trace loss | +| Stop hook | `uv run python -c "from mlflow.claude_code.hooks import stop_hook_handler; stop_hook_handler()"` | Fires on session end | -## Deploying to Databricks +Tracing is skipped gracefully if `APP_OWNER` is not set (e.g., local dev without Databricks). -1. Clone this repo to your Databricks Workspace -2. Navigate to **Compute** → **Apps** -3. Click **Create App** and select **Custom App** -4. Point to the cloned repo and deploy +--- -### Installation -```bash -# Clone the repository -git clone https://github.com/your-username/claude-code-cli-bricks.git -cd claude-code-cli-bricks +## Quick Start -# Install dependencies -uv pip install -r requirements.txt -``` +### Deploy to Databricks Apps -### Running Locally +1. Click [**Use this template**](https://github.com/datasciencemonkey/coding-agents-databricks-apps/generate) to create your own repo +2. Go to **Databricks → Apps → Create App** +3. Choose **Custom App** and connect your new repo +4. Deploy +5. Open the app — paste a short-lived PAT when prompted on first terminal session -```bash -uv run python app.py -``` +That's it. No secrets to configure, no pre-deployment setup. -Open http://localhost:8000 in your browser. +[→ Full deployment guide](docs/deployment.md) — environment variables, gateway config, and advanced options. +### Run locally -## Architecture +1. Click [**Use this template**](https://github.com/datasciencemonkey/coding-agents-databricks-apps/generate) to create your own repo +2. Clone your new repo and run: -``` -┌─────────────────────┐ HTTP ┌─────────────────────┐ -│ Browser Client │◄────────────►│ Flask Backend │ -│ (xterm.js) │ Polling │ (PTY Manager) │ -└─────────────────────┘ └─────────────────────┘ - │ - ▼ - ┌─────────────────────┐ - │ Shell Process │ - │ (/bin/bash) │ - └─────────────────────┘ +```bash +git clone https://github.com//.git +cd +uv run python app.py ``` -### API Endpoints +Open [http://localhost:8000](http://localhost:8000) — type `claude`, `codex`, `gemini`, or `opencode` to start coding. -| Endpoint | Method | Description | -|----------|--------|-------------| -| `/` | GET | Serves the terminal UI | -| `/health` | GET | Health check with session count | -| `/api/session` | POST | Create new terminal session | -| `/api/input` | POST | Send input to terminal | -| `/api/output` | POST | Poll for terminal output | -| `/api/resize` | POST | Resize terminal dimensions | -| `/api/session` | DELETE | Close terminal session | +--- -## Project Structure +## Why This Exists -``` -claude-code-cli-bricks/ -├── .claude/ -│ └── skills/ # 30 pre-installed skills -├── app.py # Flask backend with PTY management -├── app.yaml # Databricks Apps deployment config -├── app.yaml.template # Template for app.yaml configuration -├── CLAUDE.md # Claude Code welcome message -├── requirements.txt # Python dependencies -├── setup_claude.py # Claude Code CLI + MCP configuration -├── setup_databricks.py # Databricks CLI configuration -├── sync_to_workspace.py # Git hook for Databricks sync -├── static/ -│ ├── index.html # Terminal UI -│ └── lib/ # xterm.js library files -└── docs/ - └── plans/ # Design documentation -``` +On Jan 26, 2026, Andrej Karpathy made [this viral tweet](https://x.com/karpathy/status/2015883857489522876?s=46&t=tEsLJXJnGFIkaWs-Bhs1yA) about the future of coding. Boris Cherny, the creator of Claude Code, responded: -## Configuration +![Boris Cherny's response](image.png) -### Setting up app.yaml +This template repo opens that vision up for every Databricks user — no IDE setup, no local installs. Click "Use this template", deploy to Databricks Apps, and start coding with AI in your browser. -Copy the template and configure your Databricks workspace: +--- -```bash -cp app.yaml.template app.yaml -``` +
+🧠 All 39 Skills -Edit `app.yaml` and replace `` with your Databricks workspace URL: +### Databricks Skills (25) — [ai-dev-kit](https://github.com/databricks-solutions/ai-dev-kit) -```yaml -env: - - name: DATABRICKS_HOST - value: https://.cloud.databricks.com -``` +| Category | Skills | +|----------|--------| +| AI & Agents | agent-bricks, genie, mlflow-eval, model-serving | +| Analytics | aibi-dashboards, unity-catalog, metric-views | +| Data Engineering | declarative-pipelines, jobs, structured-streaming, synthetic-data, zerobus-ingest | +| Development | asset-bundles, app-apx, app-python, python-sdk, config, spark-python-data-source | +| Storage | lakebase-autoscale, lakebase-provisioned, vector-search | +| Reference | docs, dbsql, pdf-generation | +| Meta | refresh-databricks-skills | -The `DATABRICKS_HOST` is used by both: -- **Workspace sync** - To upload projects on git commits -- **Claude Code CLI** - As the Anthropic API endpoint (via Databricks serving endpoints) +### Superpowers Skills (14) — [obra/superpowers](https://github.com/obra/superpowers) -## Databricks Deployment +| Category | Skills | +|----------|--------| +| Build | brainstorming, writing-plans, executing-plans | +| Code | test-driven-dev, subagent-driven-dev | +| Debug | systematic-debugging, verification | +| Review | requesting-review, receiving-review | +| Ship | finishing-branch, git-worktrees | +| Meta | dispatching-agents, writing-skills, using-superpowers | -This project is configured for deployment as a Databricks App. +
-### Environment Variables +
+🔌 2 MCP Servers -| Variable | Description | -|----------|-------------| -| `DATABRICKS_HOST` | Databricks workspace URL | -| `DATABRICKS_TOKEN` | Your Personal Access Token (PAT) | -| `ANTHROPIC_MODEL` | Model name (default: `databricks-claude-sonnet-4-5`) | +| Server | What it does | +|--------|-------------| +| **DeepWiki** | Ask questions about any GitHub repo — gets AI-powered answers from the codebase | +| **Exa** | Web search and code context retrieval for up-to-date information | -### Security Model -This is a **single-user app**. Each user deploys their own instance with their own PAT: +
-1. The `DATABRICKS_TOKEN` in `app.yaml` identifies the owner -2. At startup, the app determines the token owner via Databricks API -3. Only requests from the token owner are allowed -4. Other users see a 403 Forbidden error +
+🏗️ Architecture -This ensures your terminal session is private and uses your Databricks permissions. +``` +┌─────────────────────┐ WebSocket ┌─────────────────────┐ +│ Browser Client │◄═══════════►│ Gunicorn + Flask │ +│ (xterm.js) │ (primary) │ + Flask-SocketIO │ +│ │───────────►│ (PTY Manager) │ +│ │ HTTP Poll │ │ +│ │ (fallback) │ │ +└─────────────────────┘ └─────────────────────┘ + │ │ + │ on first load │ on startup + ▼ ▼ +┌─────────────────────┐ ┌─────────────────────┐ +│ Setup Progress │ │ Background Setup │ +│ (inline UI) │ │ (11 steps, 5→6 ║) │ +└─────────────────────┘ └─────────────────────┘ + │ + ▼ + ┌─────────────────────┐ + │ Shell Process │ + │ (/bin/bash) │ + └─────────────────────┘ +``` -### Create App +### Startup Flow -First, create the app in your Databricks workspace: +1. Gunicorn starts, calls `initialize_app()` via `post_worker_init` hook +2. App serves the terminal UI with inline setup progress +3. Background thread runs setup: 5 sequential steps (git config, micro editor, GitHub CLI, Databricks CLI upgrade, content-filter proxy), then 6 agent setups (Claude, Codex, OpenCode, Gemini, Databricks CLI config, MLflow) run in parallel via `ThreadPoolExecutor` +4. `/api/setup-status` endpoint reports progress to the UI +5. Once complete, the terminal becomes interactive -```bash -databricks apps create xterm-terminal -``` +### API Endpoints -### Deploy via CLI +| Endpoint | Method | Description | +|----------|--------|-------------| +| `/` | GET | Terminal UI with inline setup progress | +| `/health` | GET | Health check with session count and setup status | +| `/api/setup-status` | GET | Setup progress for the UI | +| `/api/version` | GET | App version | +| `/api/session` | POST | Create new terminal session | +| `/api/input` | POST | Send input to terminal | +| `/api/output` | POST | Poll for terminal output (single session) | +| `/api/output-batch` | POST | Batch poll output for multiple sessions | +| `/api/heartbeat` | POST | Lightweight keepalive (no buffer drain) | +| `/api/resize` | POST | Resize terminal dimensions | +| `/api/upload` | POST | Upload file (clipboard image paste) | +| `/api/session/close` | POST | Close terminal session | -Deploy the code using the Databricks CLI: +### WebSocket Events (Socket.IO) -```bash -# 1. Import project files to workspace (wipe clean first for fresh deploy) -databricks workspace delete /Workspace/Users//xterm-experiment --recursive -databricks workspace import-dir . /Workspace/Users//xterm-experiment --overwrite +| Event | Direction | Description | +|-------|-----------|-------------| +| `join_session` | Client → Server | Join session room for output delivery | +| `leave_session` | Client → Server | Leave session room | +| `terminal_input` | Client → Server | Send keystrokes to PTY | +| `terminal_resize` | Client → Server | Resize terminal | +| `heartbeat` | Client → Server | Keepalive for idle sessions | +| `terminal_output` | Server → Client | Push PTY output in real time | +| `session_exited` | Server → Client | Shell process exited | +| `session_closed` | Server → Client | Session terminated by server | +| `shutting_down` | Server → Client | Server restarting (SIGTERM) | -# 2. Deploy the app -databricks apps deploy xterm-terminal --source-code-path /Workspace/Users//xterm-experiment -``` +
+ +
+⚙️ Configuration -Replace `` with your Databricks username (e.g., `user@example.com`). +### Environment Variables + +| Variable | Required | Description | +|----------|----------|-------------| +| `DATABRICKS_TOKEN` | No | Optional. If not set, the app prompts for a token on first session. Auto-rotated every 10 minutes | +| `HOME` | Yes | Set to `/app/python/source_code` in app.yaml | +| `ANTHROPIC_MODEL` | No | Claude model name (default: `databricks-claude-opus-4-7`) | +| `CODEX_MODEL` | No | Codex model name (default: `databricks-gpt-5-5`) | +| `GEMINI_MODEL` | No | Gemini model name (default: `databricks-gemini-2-5-pro`) | +| `DATABRICKS_GATEWAY_HOST` | No | AI Gateway URL override. Auto-discovered from `DATABRICKS_WORKSPACE_ID` if unset | -Once the app is deployed. You'll need to add the 'DATABRICKS_TOKEN' secret to your Databricks workspace and reference it in the [App Resources tab](https://docs.databricks.com/aws/en/dev-tools/databricks-apps/resources). +### Security Model -### Automatic Git Configuration +Single-user app — the owner is resolved via the app's service principal and Apps API (`app.creator`), with no PAT required at deploy time. Authorization checks `X-Forwarded-Email` against `app.creator`. On first terminal session, the user pastes a short-lived PAT interactively. Tokens auto-rotate every 10 minutes (15-minute lifetime), with old tokens proactively revoked. On restart, the user re-pastes (no persistence by design). -When the app starts, it automatically configures git with your Databricks identity: -- **Email**: From your Databricks `userName` -- **Name**: From your Databricks `displayName` (or derived from email) +### Gunicorn -This means commits made within the app will be attributed to your Databricks account. +Production uses `workers=1` (PTY state is process-local), `threads=16` (concurrent polling + WebSocket), `gthread` worker class, `timeout=60` (long-lived WebSocket connections). -## Workspace Sync +
-When deployed, git commits automatically sync your projects to Databricks Workspace: +
+📁 Project Structure ``` -/Workspace/Users/{email}/projects/{project-name}/ +coding-agents-databricks-apps/ +├── app.py # Flask backend + PTY management + setup orchestration +├── app_state.py # Shared app state (setup progress, session registry) +├── app.yaml.template # Databricks Apps deployment config template +├── cli_auth.py # Interactive PAT setup + CLI credential writer +├── content_filter_proxy.py # Proxy that sanitises empty-content blocks for OpenCode +├── gunicorn.conf.py # Gunicorn production server config +├── pat_rotator.py # Background PAT auto-rotation (10-min cycle) +├── pyproject.toml # Package metadata + uv config (supply-chain guardrails) +├── requirements.txt # Compiled from pyproject.toml (Dependabot compatibility) +├── requirements.lock # Hash-pinned lockfile (auto-regenerated by CI) +├── Makefile # Deploy, redeploy, status, and cleanup targets +├── setup_claude.py # Claude Code CLI + MCP configuration +├── setup_codex.py # Codex CLI configuration +├── setup_gemini.py # Gemini CLI configuration +├── setup_opencode.py # OpenCode configuration +├── setup_databricks.py # Databricks CLI configuration +├── setup_mlflow.py # MLflow tracing auto-configuration +├── setup_proxy.py # Content-filter proxy startup +├── sync_to_workspace.py # Post-commit hook: sync to Workspace +├── install_micro.sh # Micro editor installer +├── install_gh.sh # GitHub CLI installer (OS/arch-aware) +├── install_databricks_cli.sh # Databricks CLI upgrade script +├── utils.py # Utility functions (ensure_https) +├── static/ +│ ├── index.html # Terminal UI (xterm.js + split panes + WebSocket) +│ ├── favicon.svg # App favicon +│ ├── poll-worker.js # Web Worker for HTTP polling fallback +│ └── lib/ +│ ├── xterm.js # xterm.js terminal emulator +│ └── socket.io.min.js # Vendored Socket.IO client +├── .claude/ +│ └── skills/ # 39 pre-installed skills +├── .github/ +│ └── workflows/ +│ ├── dependency-audit.yml # Weekly CVE audit + lockfile drift check +│ └── update-lockfile.yml # Auto-regenerate requirements.lock on push +└── docs/ + ├── deployment.md # Full Databricks Apps deployment guide + ├── prd/ # Product requirement documents + └── plans/ # Design documentation ``` -This is enabled via a git post-commit hook configured by `setup_claude.py`. - -## Technologies +
-- **Backend**: Flask, Python PTY/termios -- **Frontend**: xterm.js, FitAddon -- **Integration**: Databricks SDK, Claude Agent SDK +--- -## License +## Technologies -MIT +Flask · Flask-SocketIO · Socket.IO · Gunicorn · xterm.js · Python PTY · uv · Databricks SDK · Databricks AI Gateway · MLflow diff --git a/agents/build-feature.md b/agents/build-feature.md new file mode 100644 index 00000000..9a357776 --- /dev/null +++ b/agents/build-feature.md @@ -0,0 +1,66 @@ +--- +name: build-feature +description: End-to-end feature builder. Chains prd-writer → test-generator → implementer → web-devloop-tester in TDD flow. Use when asked to "build", "create", or "implement" a feature from scratch. Orchestrates the full cycle including bug fix loops and visual UI testing. +tools: Read, Write, Edit, Glob, Grep, Bash, Agent, AskUserQuestion, WebSearch, WebFetch +--- + +# Role +You are a tech lead orchestrating a TDD feature build. You coordinate four phases and handle failures. + +# Phase 1: PRD +1. Invoke yourself as a prd-writer: interview the user, write `docs/prd/.md` +2. Do NOT proceed until the user approves the PRD +3. PRD must have status `READY_FOR_IMPLEMENTATION` before moving on + +# Phase 2: Tests (TDD) +1. Read the approved PRD +2. Extract all Acceptance Criteria (AC-*) +3. Scan the codebase for test framework and conventions +4. Write failing tests that define the contract — one or more tests per AC +5. Run the tests to confirm they fail for the right reasons (missing implementation, not broken tests) +6. Update PRD status to `TESTS_WRITTEN` + +# Phase 3: Implementation +1. Read the PRD and all test files +2. Run the test suite to see current failures +3. Create an implementation plan, present it to the user for approval +4. Implement code to make tests pass, working through one group at a time +5. After each group, run tests to verify progress + +# Bug Fix Loop +If tests fail after implementation: + +1. Read the failure output carefully +2. Identify whether the bug is in the **test** or the **implementation** +3. If test is wrong (doesn't match PRD): fix the test +4. If implementation is wrong: fix the code +5. Re-run tests +6. **Max 3 fix loops** — if still failing after 3 rounds, stop and report to the user with: + - Which tests are failing + - The error messages + - Your hypothesis on the root cause + - Ask the user how to proceed + +# Phase 4: Visual Testing (Web Apps Only) +If the feature has a UI component (React, Vue, Streamlit, Dash, etc.): + +1. Spawn a `web-devloop-tester` agent (subagent_type: `fe-specialized-agents:web-devloop-tester`) +2. Tell it to: start the dev server, navigate to the relevant page, take screenshots, check console for errors, and test key interactions from the AC-* list +3. Review the tester's report: + - **All clear** → proceed to Completion + - **Issues found** → create fix tasks for the implementer, then re-test +4. **Max 3 visual fix loops** — if issues persist after 3 rounds, stop and report to the user with screenshots and logs + +Skip this phase for: +- CLI tools, libraries, backend-only APIs +- Projects with no dev server or browser UI + +# Completion +When all tests pass and visual testing is complete (or skipped): +1. Run the full test suite one final time +2. Update PRD status to `COMPLETE` +3. Summarize what was built: + - Files created/modified + - Test coverage (AC-* mapping) + - Visual test results (screenshots, if applicable) + - Any open items or manual testing needed diff --git a/agents/implementer.md b/agents/implementer.md new file mode 100644 index 00000000..2f6d0881 --- /dev/null +++ b/agents/implementer.md @@ -0,0 +1,59 @@ +--- +name: implementer +description: Reads a PRD and makes all tests pass. Implements code to satisfy the test suite written by test-generator. Use after test-generator has written failing tests. Runs tests iteratively until green. +tools: Read, Write, Edit, Glob, Grep, Bash, Agent +--- + +# Role +You are a senior software engineer who makes failing tests pass. You implement exactly what's needed to satisfy the test suite and PRD requirements — nothing more. + +# Startup +1. Read the PRD file specified (or scan `docs/prd/` for files with status `TESTS_WRITTEN`) +2. Read ALL test files listed in the PRD status section +3. Run the test suite to see the current failures +4. Read any files referenced in the PRD's Technical Notes or Dependencies sections +5. Scan the codebase with Glob/Grep to understand existing patterns and architecture + +# Planning Phase +Before writing any code, create a numbered implementation plan: + +1. List every failing test and what it expects +2. Group tests by module/component +3. Identify files to create or modify +4. Note the order of operations (what depends on what) +5. Flag any Open Questions from the PRD that block implementation + +Present the plan and wait for approval before proceeding. + +# Implementation Phase — Red-Green Loop +For each group of related tests: + +1. **Read the tests** — understand exactly what they expect +2. **Write minimal code** to make those tests pass +3. **Run tests** — check if they pass +4. **If tests fail** — read the error, fix the code, run again +5. **Repeat** until that group is green +6. **Commit** — use `git commit -m "message"` directly +7. Move to the next group + +Rules: +- **Read before writing** — always read existing files before modifying +- **Follow existing patterns** — match the codebase's style and conventions +- **Keep it simple** — don't over-engineer; make the tests pass +- **Max 3 fix attempts per test** — if a test won't pass after 3 tries, flag it and move on + +# Final Validation +After all implementation: + +1. Run the FULL test suite +2. If any tests still fail, attempt fixes (max 2 more rounds) +3. If tests still fail after retries, document the failures + +# Handoff +When complete, update the PRD status: + +> **Status: IMPLEMENTED** +> Commits: +> Test results: +> If all green: **Status: COMPLETE** +> If failures remain: **Status: NEEDS_REVIEW** with failure details diff --git a/agents/memory-recall.md b/agents/memory-recall.md new file mode 100644 index 00000000..60d1be23 --- /dev/null +++ b/agents/memory-recall.md @@ -0,0 +1,48 @@ +--- +name: memory-recall +description: Search past CODA sessions stored in Lakebase for relevant context, prior decisions, and learned preferences. Invoke when the user references past work, asks "do you remember...", mentions prior conversations, or when a [coda-memory] signal appears in context. +tools: Bash +--- + +# Role + +You are a focused memory retrieval agent. You search Lakebase for relevant memories from past coding sessions and return a concise synthesis. You run in an isolated fork — do NOT use tools other than Bash. + +# Process + +## Step 1: Formulate a targeted query + +Based on the user's question or the current task, identify 1-3 specific search terms. Be concrete: prefer "FastAPI OAuth Databricks" over "auth stuff". + +## Step 2: Search + +```bash +cd /app/python/source_code && uv run python -m memory.searcher "YOUR QUERY HERE" +``` + +Run up to 2 searches with different queries if the first returns nothing useful. You may pass `--project ` if the project context is known. + +## Step 3: Evaluate and synthesise + +- Filter out memories that are clearly not relevant to the current question +- Do NOT return raw database output — synthesise into 3-5 bullets +- Include the memory type (preference, project decision, reference) so the caller knows how to weight it +- If nothing relevant was found, say so in one sentence and stop + +## Output format + +Return your synthesis directly. Example: + +**From past sessions:** +- [Preference] Always use `uv`, never pip — user is strict about this +- [Project: my-app] Chose FastAPI over Flask for async support; Databricks SDK wired via `WorkspaceClient` +- [Reference] Databricks BGE embedding endpoint: `databricks-bge-large-en` + +If no relevant memories: "No relevant memories found for this query." + +## Rules + +- Never make up memories — only report what the search returns +- Never include raw SQL output, error tracebacks, or timestamps unless directly relevant +- Keep synthesis under 200 words +- Stop after synthesis — do not continue with implementation or ask follow-up questions diff --git a/agents/prd-writer.md b/agents/prd-writer.md new file mode 100644 index 00000000..baf4aa01 --- /dev/null +++ b/agents/prd-writer.md @@ -0,0 +1,81 @@ +--- +name: prd-writer +description: Use when creating a new feature, epic, or project requirement. Interviews the user with clarifying questions, then generates a structured PRD markdown file ready for implementation. Use proactively when asked about new features or "what should we build". +tools: Read, Write, Glob, Grep, AskUserQuestion, WebSearch, WebFetch +--- + +# Role +You are a senior product manager who turns raw ideas into implementation-ready PRDs through Socratic questioning. + +# Discovery Phase +Before writing anything, interview the user with numbered clarifying questions (max 6 per round) covering: + +1. **Problem** — What problem are we solving and who does it affect? +2. **Success metrics** — How will we know this worked? What are the acceptance criteria? +3. **Scope boundaries** — What is explicitly OUT of scope? +4. **Technical constraints** — Any dependencies, existing systems, or limitations? +5. **Priority & timeline** — How urgent is this? What's the desired delivery window? +6. **Edge cases** — What happens when things go wrong? Error states? + +Use AskUserQuestion to present these as structured questions. WAIT for answers before proceeding. Ask follow-up rounds if answers are vague or incomplete. + +# Research Phase +If the feature involves external APIs, libraries, or patterns: +- Use WebSearch to find current best practices +- Use Glob/Grep to scan the existing codebase for related patterns, data models, and conventions +- Reference any existing PRDs in `docs/prd/` to follow established format and naming + +# Output Format +Write the PRD to `docs/prd/.md` using this structure: + +```markdown +# PRD: +**Author:** | **Date:** | **Status:** DRAFT + +## Problem Statement + + +## User Personas & Stories +- As a [user type], I want [action] so that [outcome] +- ... + +## Functional Requirements +1. FR-1: +2. FR-2: ... + +## Non-Functional Requirements +1. NFR-1: +2. NFR-2: ... + +## Acceptance Criteria +1. AC-1: Given [context], when [action], then [result] +2. AC-2: ... + +## Out of Scope +- + +## Dependencies +- + +## Open Questions +- + +## Technical Notes +- +- +``` + +# Iteration +After writing the first draft: +1. Present a summary to the user +2. Ask if any sections need refinement +3. Update the PRD based on feedback +4. Repeat until the user approves + +# Handoff +Once approved, update the status line and append: + +> **Status: READY_FOR_IMPLEMENTATION** +> Next steps (TDD flow): +> 1. test-generator writes failing tests from the Acceptance Criteria +> 2. implementer makes all tests pass diff --git a/agents/test-generator.md b/agents/test-generator.md new file mode 100644 index 00000000..f2f2d21b --- /dev/null +++ b/agents/test-generator.md @@ -0,0 +1,56 @@ +--- +name: test-generator +description: Reads a PRD's acceptance criteria and generates comprehensive tests BEFORE implementation (TDD). Maps each AC-* criterion to one or more test cases. Tests should initially fail — that's expected. Use after prd-writer and BEFORE the implementer. +tools: Read, Write, Edit, Glob, Grep, Bash +--- + +# Role +You are a senior QA engineer who writes tests FIRST (TDD style). You translate acceptance criteria into failing tests that define the contract the implementer must satisfy. + +# Startup +1. Read the PRD file specified by the user (or scan `docs/prd/` for files with status `READY_FOR_IMPLEMENTATION`) +2. Extract all Acceptance Criteria (AC-*) +3. Scan the codebase to understand the test framework, conventions, and existing test patterns +4. If code already exists, read it to understand the interfaces; if not, define the expected interfaces from the PRD + +# Test Strategy +Before writing tests, produce a test matrix: + +| AC | Test Name | Type | Description | +|----|-----------|------|-------------| +| AC-1 | test_... | unit | ... | +| AC-1 | test_... | integration | ... | +| AC-2 | test_... | unit | ... | + +Every AC must have at least one test. Include: +- **Happy path** — the AC scenario works as described +- **Edge cases** — boundary values, empty inputs, max limits +- **Error cases** — what happens when preconditions aren't met + +# Implementation Rules +1. **Match existing test patterns** — use the same framework, fixtures, helpers, and directory structure already in the project +2. **Name tests after ACs** — include the AC number in the test name or docstring (e.g., `test_ac1_user_can_login`) +3. **Keep tests independent** — no test should depend on another test's state +4. **Test behavior, not implementation** — tests should survive refactoring +5. **Define interfaces** — if the code doesn't exist yet, write tests against the interfaces/function signatures described in the PRD. Import from expected module paths. + +# Test Frameworks +Detect and use whatever the project already has: +- **Python**: pytest (use `uv run pytest`) +- **JS/TS**: jest, vitest, or mocha (use `npx`) +- **Other**: follow existing patterns + +# TDD Validation +After writing all tests: +1. Run the test suite — **tests SHOULD fail** (no implementation yet) +2. Confirm tests fail for the RIGHT reasons (import errors or missing functions, not syntax errors in tests) +3. List the expected failure count + +# Handoff +When complete, update the PRD status: + +> **Status: TESTS_WRITTEN** +> Test files: +> Failing tests: (expected — no implementation yet) +> AC coverage: +> Next: Ask the implementer to read `docs/prd/.md` and make all tests pass diff --git a/app.py b/app.py index 07069c25..41222aaa 100644 --- a/app.py +++ b/app.py @@ -9,65 +9,486 @@ import threading import signal import time +import copy import logging +from concurrent.futures import ThreadPoolExecutor, wait from flask import Flask, send_from_directory, request, jsonify, session +from flask_socketio import SocketIO, emit, join_room, leave_room, disconnect +from werkzeug.utils import secure_filename from collections import deque -os.environ.pop("DATABRICKS_CLIENT_ID", None) -os.environ.pop("DATABRICKS_CLIENT_SECRET", None) +import tomllib +import requests + +import app_state +from utils import ensure_https, get_gateway_host +from pat_rotator import PATRotator +from telemetry import log_telemetry, set_product_info + +# Sanitize DATABRICKS_TOKEN early — the platform sometimes injects trailing +# newlines / whitespace which causes auth failures. Cleaning it here prevents +# the agent from "fixing" it in the terminal and leaking the raw token. +_raw_token = os.environ.get("DATABRICKS_TOKEN", "") +if _raw_token != _raw_token.strip(): + os.environ["DATABRICKS_TOKEN"] = _raw_token.strip() + +# App version (single source of truth: pyproject.toml) +_pyproject_file = os.path.join(os.path.dirname(__file__), 'pyproject.toml') +try: + with open(_pyproject_file, 'rb') as _f: + APP_VERSION = tomllib.load(_f)['project']['version'] +except Exception: + APP_VERSION = '0.0.0' # Session timeout configuration -SESSION_TIMEOUT_SECONDS = 60 # No poll for 60s = dead session -CLEANUP_INTERVAL_SECONDS = 30 # How often to check for stale sessions +SESSION_TIMEOUT_SECONDS = 86400 # No poll for 24 hours = dead session +CLEANUP_INTERVAL_SECONDS = 900 # Check for stale sessions every 15 min GRACEFUL_SHUTDOWN_WAIT = 3 # Seconds to wait after SIGHUP before SIGKILL +MAX_CONCURRENT_SESSIONS = int(os.environ.get("MAX_CONCURRENT_SESSIONS", "5")) # Logging setup logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) +# PAT auto-rotation — initialized after sessions dict is defined (see below) + app = Flask(__name__, static_folder='static', static_url_path='/static') app.secret_key = os.urandom(24) +app.config['MAX_CONTENT_LENGTH'] = 32 * 1024 * 1024 # 32 MB — aligned with Claude Code's 30 MB file limit + +# WebSocket support via Flask-SocketIO (simple-websocket transport, threading mode) +socketio = SocketIO(app, async_mode='threading', cors_allowed_origins=[], logger=False, engineio_logger=False) -# Store sessions: {session_id: {"master_fd": fd, "pid": pid, "output_buffer": deque}} +# Store sessions: {session_id: {"master_fd": fd, "pid": pid, "output_buffer": deque, "lock": Lock, ...}} +# sessions_lock guards dict-level ops (add/remove/iterate); each session["lock"] guards per-session state sessions = {} sessions_lock = threading.Lock() +# PAT auto-rotation (short-lived tokens, background refresh) +# Only rotates while active sessions exist — stops when all sessions are reaped +pat_rotator = PATRotator( + session_count_fn=lambda: len(sessions), +) + +# SIGTERM graceful shutdown: notify clients before gunicorn stops the worker +shutting_down = False + +_start_time = time.time() + +def handle_sigterm(signum, frame): + """Notify clients that app is shutting down, then let gunicorn handle the rest.""" + global shutting_down + # Ignore SIGTERMs in the first 10s — likely stale signals from a prior process kill + if time.time() - _start_time < 10: + logger.info("SIGTERM received during startup — ignoring (likely stale signal)") + return + shutting_down = True + logger.info("SIGTERM received — setting shutting_down flag for clients") + # Notify WS clients immediately (HTTP poll clients will see shutting_down on next poll) + try: + socketio.emit('shutting_down', {}) + except Exception: + pass + +# NOTE: Do not register SIGTERM handler at module level. +# It is installed in initialize_app() for gunicorn only. +# For local dev (__main__), we keep SIG_DFL so the process just exits. + +# Setup state tracking +setup_lock = threading.Lock() +setup_state = { + "status": "pending", + "started_at": None, + "completed_at": None, + "error": None, + "steps": [ + {"id": "git", "label": "Configuring git identity", "status": "pending", "started_at": None, "completed_at": None, "error": None}, + {"id": "micro", "label": "Installing micro editor", "status": "pending", "started_at": None, "completed_at": None, "error": None}, + {"id": "gh", "label": "Installing GitHub CLI", "status": "pending", "started_at": None, "completed_at": None, "error": None}, + {"id": "dbcli", "label": "Upgrading Databricks CLI", "status": "pending", "started_at": None, "completed_at": None, "error": None}, + {"id": "proxy", "label": "Starting content-filter proxy", "status": "pending", "started_at": None, "completed_at": None, "error": None}, + {"id": "claude", "label": "Configuring Claude CLI", "status": "pending", "started_at": None, "completed_at": None, "error": None}, + {"id": "codex", "label": "Configuring Codex CLI", "status": "pending", "started_at": None, "completed_at": None, "error": None}, + {"id": "opencode", "label": "Configuring OpenCode CLI", "status": "pending", "started_at": None, "completed_at": None, "error": None}, + {"id": "gemini", "label": "Configuring Gemini CLI", "status": "pending", "started_at": None, "completed_at": None, "error": None}, + {"id": "hermes", "label": "Configuring Hermes Agent", "status": "pending", "started_at": None, "completed_at": None, "error": None}, + {"id": "databricks", "label": "Setting up Databricks CLI", "status": "pending", "started_at": None, "completed_at": None, "error": None}, + {"id": "mlflow", "label": "Enabling MLflow tracing", "status": "pending", "started_at": None, "completed_at": None, "error": None}, + {"id": "memory", "label": "Wiring Lakebase memory", "status": "pending", "started_at": None, "completed_at": None, "error": None}, + ] +} + + +def _update_step(step_id, **kwargs): + with setup_lock: + for step in setup_state["steps"]: + if step["id"] == step_id: + step.update(kwargs) + break + + +def _get_setup_state_snapshot(): + with setup_lock: + return copy.deepcopy(setup_state) + + # Single-user security: only the token owner can access the terminal app_owner = None -def get_token_owner(): - """Get the owner email from DATABRICKS_TOKEN at startup.""" +def _run_step(step_id, command): + _update_step(step_id, status="running", started_at=time.time()) + try: + env = os.environ.copy() + if not env.get("HOME") or env["HOME"] == "/": + env["HOME"] = "/app/python/source_code" + home = env.get("HOME", "/app/python/source_code") + # Ensure uv and other tools in ~/.local/bin are on PATH + local_bin = os.path.join(home, ".local", "bin") + if local_bin not in env.get("PATH", ""): + env["PATH"] = f"{local_bin}:{env.get('PATH', '')}" + env.pop("DATABRICKS_CLIENT_ID", None) + env.pop("DATABRICKS_CLIENT_SECRET", None) + + result = subprocess.run(command, env=env, capture_output=True, text=True, timeout=300) + if result.returncode == 0: + _update_step(step_id, status="complete", completed_at=time.time()) + else: + err = result.stderr.strip() or result.stdout.strip() or "Unknown error" + _update_step(step_id, status="error", completed_at=time.time(), error=err[:500]) + except subprocess.TimeoutExpired: + _update_step(step_id, status="error", completed_at=time.time(), error="Timed out after 300s") + except Exception as e: + _update_step(step_id, status="error", completed_at=time.time(), error=str(e)) + + +def _setup_git_config(): + """Configure git identity and hooks by writing files directly (no subprocess).""" + home = os.environ.get("HOME", "/app/python/source_code") + if not home or home == "/": + home = "/app/python/source_code" + + # Get user identity from Databricks token + user_email = None + display_name = None try: from databricks.sdk import WorkspaceClient - host = os.environ.get("DATABRICKS_HOST") + db_host = ensure_https(os.environ.get("DATABRICKS_HOST", "")) + db_token = os.environ.get("DATABRICKS_TOKEN") + if db_host and db_token: + w = WorkspaceClient(host=db_host, token=db_token, auth_type="pat") + set_product_info(w) + me = w.current_user.me() + user_email = me.user_name + display_name = me.display_name or user_email.split("@")[0] + except Exception as e: + logger.warning(f"Could not get user identity from token: {e}") + + # Write ~/.gitconfig directly (more reliable than subprocess git config) + gitconfig_path = os.path.join(home, ".gitconfig") + hooks_dir = os.path.join(home, ".githooks") + os.makedirs(hooks_dir, exist_ok=True) + + lines = [] + if user_email and display_name: + lines.append("[user]") + lines.append(f"\temail = {user_email}") + lines.append(f"\tname = {display_name}") + lines.append("[core]") + lines.append(f"\thooksPath = {hooks_dir}") + + with open(gitconfig_path, "w") as f: + f.write("\n".join(lines) + "\n") + logger.info(f"Git config written to {gitconfig_path}") + + # Write post-commit hook for workspace sync (works from any CLI: Claude, Gemini, OpenCode, etc.) + # Only syncs repos inside ~/projects/ — skips the app source and any other repos + post_commit = os.path.join(hooks_dir, "post-commit") + with open(post_commit, "w") as f: + f.write('#!/bin/bash\n') + f.write('# Auto-sync to Databricks Workspace on commit (works from any CLI)\n') + f.write('SYNC_LOG="$HOME/.sync.log"\n') + f.write('\n') + f.write('# Resolve git repo root (handles commits from subdirectories)\n') + f.write('REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"\n') + f.write('if [ -z "$REPO_ROOT" ]; then\n') + f.write(' echo "[post-commit] $(date +%H:%M:%S) SKIP: not inside a git repo" >> "$SYNC_LOG"\n') + f.write(' exit 0\n') + f.write('fi\n') + f.write('\n') + f.write('# Only sync repos inside ~/projects/\n') + f.write('PROJECTS_DIR="$HOME/projects"\n') + f.write('case "$REPO_ROOT" in\n') + f.write(' "$PROJECTS_DIR"/*)\n') + f.write(' ;; # allowed - continue\n') + f.write(' *)\n') + f.write(' echo "[post-commit] $(date +%H:%M:%S) SKIP: $REPO_ROOT is outside $PROJECTS_DIR" >> "$SYNC_LOG"\n') + f.write(' exit 0\n') + f.write(' ;;\n') + f.write('esac\n') + f.write('\n') + f.write('echo "[post-commit] $(date +%H:%M:%S) syncing $REPO_ROOT" >> "$SYNC_LOG"\n') + f.write('\n') + f.write('# Use uv run so sync script gets the correct Python + deps\n') + f.write('APP_DIR="/app/python/source_code"\n') + f.write('SYNC_SCRIPT="$APP_DIR/sync_to_workspace.py"\n') + f.write('\n') + f.write('if [ -f "$SYNC_SCRIPT" ]; then\n') + f.write(' nohup uv run --project "$APP_DIR" python "$SYNC_SCRIPT" "$REPO_ROOT" >> "$SYNC_LOG" 2>&1 & disown\n') + f.write('else\n') + f.write(' echo "[post-commit] $(date +%H:%M:%S) SKIP: sync script not found" >> "$SYNC_LOG"\n') + f.write('fi\n') + os.chmod(post_commit, 0o755) + logger.info(f"Post-commit hook written to {post_commit}") + + # Reinit app source git to remove template origin (Databricks Apps only) + _reinit_app_git() + + +def _reinit_app_git(): + """On Databricks Apps, reinit git to remove template origin remote.""" + app_dir = os.path.dirname(os.path.abspath(__file__)) + if app_dir != "/app/python/source_code": + return # Local dev — leave git intact + + git_dir = os.path.join(app_dir, ".git") + if not os.path.isdir(git_dir): + return # Already clean + + import shutil + shutil.rmtree(git_dir) + subprocess.run(["git", "init"], cwd=app_dir, capture_output=True) + subprocess.run(["git", "add", "."], cwd=app_dir, capture_output=True) + subprocess.run( + ["git", "commit", "-m", "Initial commit from coding-agents template"], + cwd=app_dir, capture_output=True, + ) + logger.info("Reinitialized app source git (template origin removed)") + + +def _configure_all_cli_auth(token): + """Configure auth for ALL coding-agent CLIs after a PAT is provided. + + Called from /api/configure-pat when a user supplies a PAT interactively. + Handles: Claude CLI (inline), Databricks CLI (via pat_rotator), and + Codex/OpenCode/Gemini CLIs (by re-running their setup scripts with token in env). + """ + import json + + from utils import resolve_and_cache_gateway + resolve_and_cache_gateway() + + home = os.environ.get("HOME", "/app/python/source_code") + if not home or home == "/": + home = "/app/python/source_code" + + # 1. Configure Claude CLI (~/.claude/settings.json) + claude_dir = os.path.join(home, ".claude") + os.makedirs(claude_dir, exist_ok=True) + + gateway_host = get_gateway_host() + databricks_host = ensure_https(os.environ.get("DATABRICKS_HOST", "").rstrip("/")) + + if gateway_host: + anthropic_base_url = f"{gateway_host}/anthropic" + else: + anthropic_base_url = f"{databricks_host}/serving-endpoints/anthropic" + + # Read-merge-write to preserve env vars from other setup scripts (e.g. setup_mlflow.py) + settings_path = os.path.join(claude_dir, "settings.json") + try: + with open(settings_path) as f: + settings = json.load(f) + except (FileNotFoundError, json.JSONDecodeError): + settings = {} + + settings.setdefault("env", {}) + settings["env"]["ANTHROPIC_MODEL"] = os.environ.get("ANTHROPIC_MODEL", "databricks-claude-opus-4-7") + settings["env"]["ANTHROPIC_BASE_URL"] = anthropic_base_url + settings["env"]["ANTHROPIC_AUTH_TOKEN"] = token + settings["env"]["ANTHROPIC_DEFAULT_OPUS_MODEL"] = "databricks-claude-opus-4-7" + settings["env"]["ANTHROPIC_DEFAULT_SONNET_MODEL"] = "databricks-claude-sonnet-4-6" + settings["env"]["ANTHROPIC_DEFAULT_HAIKU_MODEL"] = "databricks-claude-haiku-4-5" + settings["env"]["ANTHROPIC_CUSTOM_HEADERS"] = "x-databricks-use-coding-agent-mode: true" + settings["env"]["CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"] = "1" + + with open(settings_path, "w") as f: + json.dump(settings, f, indent=2) + + logger.info(f"Claude CLI auth configured: {settings_path}") + + # 2. Configure Databricks CLI (~/.databrickscfg) — already called by + # configure_pat() via pat_rotator, but explicit for clarity + pat_rotator._write_databrickscfg(token) + logger.info("Databricks CLI auth configured: ~/.databrickscfg") + + # 3. Re-run Codex, OpenCode, Gemini setup scripts with token in env + # They are idempotent: detect CLI already installed, just write config files + env = {**os.environ, "DATABRICKS_TOKEN": token} + for script in ["setup_codex.py", "setup_opencode.py", "setup_gemini.py", "setup_hermes.py"]: + try: + result = subprocess.run( + ["uv", "run", "python", script], + env=env, capture_output=True, text=True, timeout=60 + ) + if result.returncode == 0: + logger.info(f"CLI config updated: {script}") + else: + logger.warning(f"CLI config failed: {script}: {result.stderr[:200]}") + except Exception as e: + logger.warning(f"CLI config error: {script}: {e}") + + +def run_setup(): + with setup_lock: + setup_state["status"] = "running" + setup_state["started_at"] = time.time() + + # Probe AI Gateway once; result is cached in _GATEWAY_RESOLVED for subprocesses + from utils import resolve_and_cache_gateway + resolve_and_cache_gateway() + + # --- Sequential prerequisites (git identity + editor) --- + # Git config — done directly in Python, not as a subprocess + _update_step("git", status="running", started_at=time.time()) + try: + _setup_git_config() + _update_step("git", status="complete", completed_at=time.time()) + except Exception as e: + _update_step("git", status="error", completed_at=time.time(), error=str(e)) + + _run_step("micro", ["bash", "-c", + "mkdir -p ~/.local/bin && bash install_micro.sh && mv micro ~/.local/bin/ 2>/dev/null || true"]) + + _run_step("gh", ["bash", "install_gh.sh"]) + + # --- Upgrade Databricks CLI (runtime image ships an older version) --- + _run_step("dbcli", ["bash", "install_databricks_cli.sh"]) + + # --- Content-filter proxy (must be running before OpenCode starts) --- + # Sanitizes requests/responses between OpenCode and Databricks + # (see OpenCode #5028, docs/plans/2026-03-11-litellm-empty-content-blocks-design.md) + _run_step("proxy", ["uv", "run", "python", "setup_proxy.py"]) + + # --- Parallel agent setup (all independent of each other) --- + parallel_steps = [ + ("claude", ["uv", "run", "python", "setup_claude.py"]), + ("codex", ["uv", "run", "python", "setup_codex.py"]), + ("opencode", ["uv", "run", "python", "setup_opencode.py"]), + ("gemini", ["uv", "run", "python", "setup_gemini.py"]), + ("hermes", ["uv", "run", "python", "setup_hermes.py"]), + ("databricks", ["uv", "run", "python", "setup_databricks.py"]), + ] + + with ThreadPoolExecutor(max_workers=len(parallel_steps)) as executor: + futures = [ + executor.submit(_run_step, step_id, command) + for step_id, command in parallel_steps + ] + wait(futures) + + # --- Sequential post-parallel steps (these modify settings.json and must not race) --- + # setup_mlflow.py merges env vars into ~/.claude/settings.json which + # setup_claude.py also writes; running sequentially prevents clobbering. + _run_step("mlflow", ["uv", "run", "python", "setup_mlflow.py"]) + + # setup_memory writes a Stop hook alongside setup_mlflow's hook — must run after + _run_step("memory", ["uv", "run", "python", "setup_memory.py"]) + + # Sync latest token into all CLI configs — covers the race where PAT + # rotation happened while a setup script was still installing (the + # rotation's update_cli_tokens() call silently skips missing config files). + current_token = os.environ.get("DATABRICKS_TOKEN", "") + if current_token: + try: + from cli_auth import update_cli_tokens + update_cli_tokens(current_token) + logger.info("Post-setup token sync: all CLI configs updated with current token") + except Exception as e: + logger.warning(f"Post-setup token sync failed: {e}") + + with setup_lock: + any_error = any(s["status"] == "error" for s in setup_state["steps"]) + setup_state["status"] = "error" if any_error else "complete" + setup_state["completed_at"] = time.time() + + +def get_token_owner(): + """Get the owner email. Priority: Apps API (app.creator) > PAT (current_user.me). + + Uses the auto-provisioned SP to call the Apps API — no PAT needed for + owner resolution. Falls back to PAT-based lookup for backward compat. + """ + from databricks.sdk import WorkspaceClient + + # 1. Try Apps API via SP credentials (no PAT needed) + app_name = os.environ.get("DATABRICKS_APP_NAME") + if app_name: + try: + w = WorkspaceClient() # auto-detects SP credentials + set_product_info(w) + app = w.apps.get(name=app_name) + owner = (app.creator or "").lower() + logger.info(f"Owner resolved from app.creator: {owner}") + return owner + except Exception as e: + logger.warning(f"Could not resolve owner via Apps API: {e}") + + # 2. Fallback: PAT-based resolution + try: + host = ensure_https(os.environ.get("DATABRICKS_HOST", "")) token = os.environ.get("DATABRICKS_TOKEN") if not host or not token: return None w = WorkspaceClient(host=host, token=token, auth_type="pat") - return w.current_user.me().user_name + set_product_info(w) + username = w.current_user.me().user_name + return username.lower() if username else username except Exception as e: logger.warning(f"Could not determine token owner: {e}") return None def get_request_user(): - """Extract user email from Databricks Apps request headers.""" - return request.headers.get("X-Forwarded-Email") or \ - request.headers.get("X-Forwarded-User") or \ - request.headers.get("X-Databricks-User-Email") + """Extract user email from Databricks Apps request headers. + + Returns lowercase email to ensure case-insensitive matching against app_owner. + """ + email = ( + request.headers.get("X-Forwarded-Email") + or request.headers.get("X-Forwarded-User") + or request.headers.get("X-Databricks-User-Email") + ) + return email.lower() if email else email + + +def _is_databricks_apps(): + """Detect if we're running on Databricks Apps (not local dev).""" + return os.environ.get("DATABRICKS_APP_PORT") or os.path.isdir("/app/python/source_code") def check_authorization(): - """Check if the current user is authorized to access the app.""" - # If owner not set (local dev or SDK unavailable), allow access + """Check if the current user is authorized to access the app. + + Fails CLOSED on Databricks Apps: if we can't determine the owner, + deny all access rather than allowing unauthenticated terminal access. + Fails open only for local development. + Fixes: https://github.com/datasciencemonkey/coding-agents-databricks-apps/issues/57 + """ + # Fail closed on Databricks Apps if owner couldn't be resolved if not app_owner: - return True, None + if _is_databricks_apps(): + logger.error("SECURITY: app_owner not resolved — denying all access (fail-closed)") + return False, "unknown" + return True, None # Local dev only current_user = get_request_user() # If no user identity in request (local dev), allow access if not current_user: + if _is_databricks_apps(): + logger.warning("No user identity in request on Databricks Apps — denying access") + return False, "unknown" return True, None # Check if current user is the owner @@ -78,25 +499,211 @@ def check_authorization(): return True, None +def _check_ws_authorization(): + """Check authorization for WebSocket connections — mirrors HTTP check_authorization(). + + Fails CLOSED on Databricks Apps: if app_owner is unresolved or no user identity + in headers, deny WebSocket access. Matches the HTTP handler's behavior exactly. + """ + if not app_owner: + if _is_databricks_apps(): + logger.error("SECURITY: app_owner not resolved — denying WebSocket (fail-closed)") + return False + return True # Local dev only + + # Socket.IO passes HTTP headers from the initial handshake via request context + raw_user = ( + request.headers.get("X-Forwarded-Email") + or request.headers.get("X-Forwarded-User") + or request.headers.get("X-Databricks-User-Email") + ) + current_user = raw_user.lower() if raw_user else raw_user + + if not current_user: + if _is_databricks_apps(): + logger.warning("No user identity in WebSocket request on Databricks Apps — denying") + return False + return True # Local dev only + + if current_user != app_owner: + logger.warning(f"WebSocket unauthorized: {current_user} (owner: {app_owner})") + return False + return True + + +# ── WebSocket Event Handlers ────────────────────────────────────────────── + +@socketio.on('connect') +def handle_ws_connect(): + """Authenticate WebSocket connections (AC-3).""" + if not _check_ws_authorization(): + disconnect() + return False + logger.info("WebSocket client connected") + + +@socketio.on('join_session') +def handle_join_session(data): + """Client joins a session room to receive output (AC-4).""" + session_id = data.get('session_id') + if not session_id: + return {'status': 'error', 'message': 'session_id required'} + + session = _get_session(session_id) + if not session: + return {'status': 'error', 'message': 'Session not found'} + + with session["lock"]: + session["last_poll_time"] = time.time() + session["output_buffer"].clear() # Prevent duplicate output on WS↔HTTP switch + + join_room(session_id) + logger.info(f"WebSocket client joined session room {session_id}") + return {'status': 'ok'} + + +@socketio.on('leave_session') +def handle_leave_session(data): + """Client leaves a session room (AC-5).""" + session_id = data.get('session_id') + if session_id: + leave_room(session_id) + logger.info(f"WebSocket client left session room {session_id}") + + +@socketio.on('terminal_input') +def handle_terminal_input(data): + """Receive keystrokes from client, write to PTY (AC-6).""" + session_id = data.get('session_id') + input_data = data.get('input', '') + + session = _get_session(session_id) + if not session: + return + + with session["lock"]: + session["last_poll_time"] = time.time() + fd = session["master_fd"] + + try: + os.write(fd, input_data.encode()) + except OSError as e: + logger.warning(f"WebSocket input write error for {session_id}: {e}") + + +@socketio.on('terminal_resize') +def handle_terminal_resize(data): + """Receive resize events from client (AC-7).""" + session_id = data.get('session_id') + cols = data.get('cols', 80) + rows = data.get('rows', 24) + + session = _get_session(session_id) + if not session: + return + + with session["lock"]: + session["last_poll_time"] = time.time() + fd = session["master_fd"] + + try: + winsize = struct.pack("HHHH", rows, cols, 0, 0) + fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize) + except OSError as e: + logger.warning(f"WebSocket resize error for {session_id}: {e}") + + +@socketio.on('heartbeat') +def handle_ws_heartbeat(data): + """Periodic keepalive from WS client — prevents idle session reaping (AC-17).""" + session_ids = data.get('session_ids', []) + now = time.time() + for sid in session_ids: + session = _get_session(sid) + if session: + with session["lock"]: + session["last_poll_time"] = now + + +@socketio.on('disconnect') +def handle_ws_disconnect(): + """Log WebSocket disconnections. Do NOT auto-close PTY — client may reconnect.""" + logger.info("WebSocket client disconnected") + + +def _get_session(session_id): + """Get a session dict reference under the global lock. Returns None if not found.""" + with sessions_lock: + return sessions.get(session_id) + + def read_pty_output(session_id, fd): - """Background thread to read PTY output into buffer.""" + """Background thread to read PTY output into buffer and push via WebSocket.""" + session = _get_session(session_id) + if not session: + return + pid = session["pid"] + session_lock = session["lock"] + while True: with sessions_lock: if session_id not in sessions: break try: - if select.select([fd], [], [], 0.1)[0]: - output = os.read(fd, 4096).decode(errors="replace") - with sessions_lock: - if session_id in sessions: - sessions[session_id]["output_buffer"].append(output) + readable, _, errors = select.select([fd], [], [fd], 0.05) + if readable or errors: + output = os.read(fd, 65536) + if not output: + # EOF — process exited + break + decoded = output.decode(errors="replace") + with session_lock: + # Buffer for HTTP polling fallback (AC-15) + session["output_buffer"].append(decoded) + session["last_poll_time"] = time.time() # Keep session alive during WS output + # Push via WebSocket to the session room (AC-8) + try: + socketio.emit('terminal_output', + {'session_id': session_id, 'output': decoded}, + room=session_id) + except Exception: + pass # No WebSocket clients — HTTP polling handles it + else: + # select timed out — check if process is still alive + try: + pid_result, _ = os.waitpid(pid, os.WNOHANG) + if pid_result != 0: + # Process exited + break + except ChildProcessError: + # Process already reaped + break except OSError: break + # Process exited or fd closed — notify WebSocket clients (AC-9) + try: + socketio.emit('session_exited', {'session_id': session_id}, room=session_id) + except Exception: + pass + + logger.info(f"Session {session_id} process exited") + + # Clean up immediately — no zombie sessions in the picker + if session: + terminate_session(session_id, session["pid"], session["master_fd"]) + def terminate_session(session_id, pid, master_fd): """Gracefully terminate a session: SIGHUP -> wait -> SIGKILL -> cleanup.""" logger.info(f"Terminating stale session {session_id} (pid={pid})") + + # Notify WebSocket clients that the session is closed + try: + socketio.emit('session_closed', {'session_id': session_id}, room=session_id) + except Exception: + pass + try: os.kill(pid, signal.SIGHUP) time.sleep(GRACEFUL_SHUTDOWN_WAIT) @@ -117,6 +724,59 @@ def terminate_session(session_id, pid, master_fd): sessions.pop(session_id, None) +def _get_session_process(pid): + """Return the name of the foreground child process for *pid*. + + Uses ``pgrep -P`` to find children (works on both macOS and Linux), + then ``ps -o comm=`` to resolve the process name. + + Returns: + str: process name, or ``"unknown"`` on any error / dead PID. + """ + if not isinstance(pid, int) or pid <= 0: + return "unknown" + + try: + # Step 1 — find child PIDs via pgrep (cross-platform) + child_result = subprocess.run( + ["pgrep", "-P", str(pid)], + capture_output=True, + text=True, + timeout=5, + ) + + if child_result.returncode == 0 and child_result.stdout.strip(): + child_pids = child_result.stdout.strip().splitlines() + last_child_pid = child_pids[-1].strip() + + # Step 2 — resolve child name + name_result = subprocess.run( + ["ps", "-o", "comm=", "-p", last_child_pid], + capture_output=True, + text=True, + timeout=5, + ) + if name_result.returncode == 0 and name_result.stdout.strip(): + name = name_result.stdout.strip().splitlines()[0].strip() + # ps may return the full path; take basename + return os.path.basename(name) + + # Step 3 — no children: fall back to the process itself + self_result = subprocess.run( + ["ps", "-o", "comm=", "-p", str(pid)], + capture_output=True, + text=True, + timeout=5, + ) + if self_result.returncode == 0 and self_result.stdout.strip(): + name = self_result.stdout.strip().splitlines()[0].strip() + return os.path.basename(name) + + return "unknown" + except Exception: + return "unknown" + + def cleanup_stale_sessions(): """Background thread that removes sessions with no recent polling.""" while True: @@ -124,12 +784,18 @@ def cleanup_stale_sessions(): now = time.time() stale_sessions = [] + warning_threshold = SESSION_TIMEOUT_SECONDS * 0.8 - # Find stale sessions with sessions_lock: - for session_id, session in sessions.items(): - if now - session["last_poll_time"] > SESSION_TIMEOUT_SECONDS: + session_snapshot = list(sessions.items()) + + for session_id, session in session_snapshot: + with session["lock"]: + idle = now - session["last_poll_time"] + if idle > SESSION_TIMEOUT_SECONDS: stale_sessions.append((session_id, session["pid"], session["master_fd"])) + elif idle > warning_threshold: + session["timeout_warning"] = True if stale_sessions: logger.info(f"Found {len(stale_sessions)} stale session(s) to clean up") @@ -142,8 +808,8 @@ def cleanup_stale_sessions(): @app.before_request def authorize_request(): """Check authorization before processing any request.""" - # Skip auth for health check - if request.path == "/health": + # Skip auth for health check, setup status, and Socket.IO (has own auth via connect event) + if request.path in ("/health", "/api/setup-status", "/api/pat-status", "/api/configure-pat", "/api/app-state") or request.path.startswith("/socket.io"): return None authorized, user = check_authorization() @@ -156,29 +822,212 @@ def authorize_request(): return None +@app.after_request +def set_security_headers(response): + response.headers["X-Content-Type-Options"] = "nosniff" + response.headers["X-Frame-Options"] = "DENY" + response.headers["X-XSS-Protection"] = "1; mode=block" + response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" + # CSP: restrict scripts to self + inline (needed for embedded + + + +