@altimateai/altimate-code 0.5.20 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +57 -0
- package/package.json +14 -14
- package/skills/data-parity/SKILL.md +492 -0
- package/skills/dbt-test/SKILL.md +2 -0
- package/skills/dbt-unit-tests/SKILL.md +209 -0
- package/skills/dbt-unit-tests/references/altimate-dbt-commands.md +66 -0
- package/skills/dbt-unit-tests/references/edge-case-patterns.md +189 -0
- package/skills/dbt-unit-tests/references/incremental-testing.md +109 -0
- package/skills/dbt-unit-tests/references/unit-test-yaml-spec.md +174 -0
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,63 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [0.6.0] - 2026-04-21
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **Data parity (`data_diff` tool + skill)** — compare tables or SQL-query results row-by-row across Postgres, Snowflake, BigQuery, Databricks, ClickHouse, MySQL, Redshift, SQL Server, Microsoft Fabric, DuckDB, SQLite, and Oracle. Five algorithms: `auto` (JoinDiff same-dialect, HashDiff cross-dialect), `joindiff` (FULL OUTER JOIN), `hashdiff` (bisecting checksums — works at any scale without pulling data out), `profile` (column-level statistics, no row values leave the database), and `cascade` (profile first, then HashDiff on diverging columns). Partitioning supports date (`day`/`week`/`month`/`year`), numeric (`bucket_size`), and categorical (distinct values) modes so 100M+ row tables diff in independent batches. Auto-discovers comparable columns from `information_schema`, excludes audit/timestamp columns by name pattern AND by catalog default (`NOW()`, `CURRENT_TIMESTAMP`, `GETDATE()`, `SYSDATE`, `SYSTIMESTAMP`), and confirms exclusions with the user before diffing. (#493)
|
|
13
|
+
- **MSSQL and Microsoft Fabric support in data-parity** — dialect-aware date truncation (`DATETRUNC`), locale-safe date literals (`CONVERT(DATE, ..., 23)`), and seven Azure AD / Entra ID authentication flows (password, access-token, service-principal-secret, MSI-VM, MSI-app-service, default credential chain, token-credential) delegated to `tedious`. Upgrades `mssql` v11 → v12 with explicit `ConnectionPool` isolation and correct handling of unnamed-column result sets. (#705)
|
|
14
|
+
- **Databricks AI Gateway provider** — connect to Databricks serving endpoints (Foundation Model APIs) via PAT auth (`workspace-host::token`), with fallback to `DATABRICKS_HOST` / `DATABRICKS_TOKEN` environment variables. Registers 11 foundation models — Meta Llama 3.1 (405B / 70B / 8B), Claude Sonnet / Opus 4.6, GPT-5.4 / GPT-5 Mini, Gemini 3.1 Pro, DBRX Instruct, and Mixtral 8x7B. Host regex restricts credentials to `*.cloud.databricks.com`, `*.azuredatabricks.net`, and `*.gcp.databricks.com`. (#649, closes #602)
|
|
15
|
+
- **Amazon Bedrock custom-endpoints guide** — dedicated docs page covering bearer-token auth, AWS credential chain, `baseURL` configuration, cross-region model-ID prefixing, and troubleshooting. Provider key corrected from `bedrock` to `amazon-bedrock` across quickstart, providers, and models pages. (#706)
|
|
16
|
+
- **User-facing docs for the new features** — Databricks AI Gateway section in `configure/providers.md` and a full `data-engineering/guides/data-parity.md` covering supported warehouse pairs, algorithms, partition modes, Azure AD auth matrix for Fabric, and compliance guidance.
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
- **`@altimateai/altimate-core` 0.2.6 → 0.3.0** — enables the cross-dialect data-parity engine, T-SQL dialect support for MSSQL/Fabric, and refined hashdiff bisection. Rebuilt native binaries published for all five supported platforms. (#717, closes #716)
|
|
21
|
+
- **Altimate connect dialog polish** — `/connect` now accepts `instance-name::api-key` directly (default URL `https://api.myaltimate.com`). The three-part `api-url::instance-name::api-key` form still works for custom and self-hosted instances. Provider display name "Altimate" → "Altimate AI"; default model display "Altimate AI" → "Altimate LLM Gateway". The internal provider ID (`altimate-backend`) and model ID (`altimate-default`) are preserved — existing `model.json` favorites, recents, and pinned `model:` entries in `opencode.json` continue to work without migration. (#724)
|
|
22
|
+
|
|
23
|
+
### Fixed
|
|
24
|
+
|
|
25
|
+
- **Text contrast on light terminal backgrounds** — dark foreground (`#1a1a1a` or `palette[0]` when available) replaces the near-invisible `palette[7]` on light-mode system themes, and inline code blocks now render on an opaque background instead of transparent. Eager `COLORFGBG` env-var detection narrowed to `bg === 7 || bg === 15` skips the 1-second OSC 11 query altogether on light terminals that don't support it (urxvt, gnome-terminal). (#712, closes #704)
|
|
26
|
+
- **Historical `tool_use` blocks after agent switches or MCP disconnects** — the LiteLLM-only `_noop` workaround is replaced by a general fix: tool names are extracted from both `tool-call` and `tool-result` blocks in message history (using `Object.hasOwn()` for prototype-pollution safety), validated against `/^[a-zA-Z0-9_-]{1,64}$/`, and registered as stubs that return "tool no longer available" if the model attempts to call them. Eliminates the Anthropic API 400 error "Requests with 'tool_use' and 'tool_result' blocks must include tool definition." (#703, closes [AI-678])
|
|
27
|
+
- **`/docs` command and config links point to `docs.altimate.sh`** — the TUI "Open docs" action, Cloudflare AI Gateway help text, Anthropic system prompt, and `Config.command` / `Config.agent` schema descriptions previously linked to the wrong domain. Also updates paths to the `/configure/` prefix that matches the actual mkdocs site. (#715, closes #714)
|
|
28
|
+
|
|
29
|
+
### Security
|
|
30
|
+
|
|
31
|
+
- **Databricks host validation hardened** — new `isValidDatabricksHost` helper rejects CRLF/whitespace (JS regex `$` matches before `\n` by default), and the env-fallback path now validates host before constructing the `baseURL`.
|
|
32
|
+
- **Tool-name validation** — stub registration ignores names with shell metacharacters, ANSI escapes, control characters, or lengths > 64, guarding against tampered session-file replays.
|
|
33
|
+
- **Restricted `az` inherited env** — `az account get-access-token` is invoked with a whitelisted environment (`PATH`, `HOME`, `AZURE_*`, locale) so unrelated secrets (`DATABRICKS_TOKEN`, cloud provider keys) are not inherited by `az` or any `az` extension.
|
|
34
|
+
|
|
35
|
+
### Testing
|
|
36
|
+
|
|
37
|
+
- 38 new adversarial tests covering Databricks host validation (CRLF, anchoring, attacker suffixes), PAT parsing edge cases, body transform, tool-name tainted-input guards, and `data_diff` tool-description release contract.
|
|
38
|
+
- 139-test consolidation across dbt helpers, file status, project-scan, session/llm, and MCP discovery — symlink cache round-trips, seed/test node exclusion, JSON array edge cases, sessionId sanitization, pagination boundary math, and connection-string masking. Two broken `${VAR}`-in-MCP-`command` tests removed (resolution was always restricted to `env` and `headers`). (#709)
|
|
39
|
+
|
|
40
|
+
### Compliance note
|
|
41
|
+
|
|
42
|
+
`data_diff` includes up to 5 sample diff rows in its tool output, which becomes part of the LLM conversation. For PII / PHI / PCI data, use `algorithm: "profile"` — column statistics compare without sending row values. The `data-parity` skill asks for explicit confirmation before running row-level diffs against tables whose names match common regulated patterns (`customers`, `patients`, `orders`, `payments`, `accounts`, `users`). A hard env-var opt-out for sample values is tracked in [#729](https://github.com/AltimateAI/altimate-code/issues/729).
|
|
43
|
+
|
|
44
|
+
### Breaking
|
|
45
|
+
|
|
46
|
+
- **`mssql` upgraded to v12**. Users with `mssql@^11` pinned at the application level will see "mssql.ConnectionPool is not available" on first SQL Server connection. Pin to `^12` or let altimate resolve.
|
|
47
|
+
- **SQL Server result sets now expose `_`-prefixed columns**. The internal `startsWith("_")` column filter (introduced for partition-discovery noise suppression) was removed because it also stripped legitimate aliases like `_p` used by the partition engine. Queries that relied on this implicit filtering will see the extra columns in results.
|
|
48
|
+
|
|
49
|
+
## [0.5.21] - 2026-04-13
|
|
50
|
+
|
|
51
|
+
### Added
|
|
52
|
+
|
|
53
|
+
- **Automated dbt unit test generation** — generate dbt unit tests (v1.8+) from your terminal with `/dbt-unit-tests` or the `dbt_unit_test_gen` tool. Detects testable SQL constructs (CASE/WHEN, JOINs, NULLs, window functions, division, incremental models) and assembles complete YAML with type-correct mock data across 7 dialects. Includes `input: this` mocks for incremental models, `format: sql` for ephemeral deps, and handles seeds/snapshots as first-class `ref()` deps. Five-phase skill workflow: Analyze → Generate → Refine → Validate → Write. Requires dbt-core 1.8+. (#673)
|
|
54
|
+
- **Manifest parse cache** — `loadRawManifest()` caches by path+mtime so large manifests (100MB+) are parsed once per session, not once per tool call.
|
|
55
|
+
- **Model/source descriptions in manifest** — `DbtModelInfo` and `DbtSourceInfo` now surface descriptions from `schema.yml`, giving downstream tools richer semantic context.
|
|
56
|
+
- **`adapter_type` on `DbtManifestResult`** — exposes the dbt adapter type (snowflake, bigquery, etc.) from manifest metadata for dialect auto-detection.
|
|
57
|
+
|
|
58
|
+
### Fixed
|
|
59
|
+
|
|
60
|
+
- **MCP env-var `$${VAR}` escape and chain-injection vulnerability** — the two-layer env-var resolution design allowed `$${VAR}` escapes to be re-resolved (breaking literal `${VAR}` passthrough) and enabled variable-chain injection where `EVIL_VAR="${SECRET}"` could exfiltrate secrets the config never referenced. Collapsed to a single resolution pass scoped to `env` and `headers` fields only. (#697, relates to #656)
|
|
61
|
+
- **MCP server environment variables passed as literals** — `${VAR}`, `${VAR:-default}`, and `{env:VAR}` patterns in MCP server `env` blocks were passed as literal strings to child processes, causing auth failures for tools like `gitlab-mcp-server`. (#666, closes #656)
|
|
62
|
+
- **`sql_explain` and `altimate_core_validate` input hardening** — reject empty/placeholder SQL and warehouse names before hitting the warehouse. `sql_explain` now generates dialect-aware EXPLAIN statements for 12+ warehouse types. Driver errors are translated into actionable guidance (e.g., "No warehouses configured — run `warehouse_add`"). `altimate_core_validate` now runs even without a schema (previously hard-failed), with a `(no schema)` indicator and clear instructions for providing schema context. (#693, closes #691)
|
|
63
|
+
- **`sql_explain` alternatives for unsupported warehouses** — BigQuery, Oracle, and SQL Server now return specific guidance (dry-run API, `DBMS_XPLAN`, `SET SHOWPLAN_TEXT ON`) instead of a generic "not supported" message.
|
|
64
|
+
|
|
8
65
|
## [0.5.20] - 2026-04-09
|
|
9
66
|
|
|
10
67
|
### Added
|
package/package.json
CHANGED
|
@@ -7,24 +7,24 @@
|
|
|
7
7
|
"scripts": {
|
|
8
8
|
"postinstall": "bun ./postinstall.mjs || node ./postinstall.mjs"
|
|
9
9
|
},
|
|
10
|
-
"version": "0.
|
|
10
|
+
"version": "0.6.0",
|
|
11
11
|
"license": "MIT",
|
|
12
12
|
"dependencies": {
|
|
13
|
-
"@altimateai/altimate-core": "0.
|
|
13
|
+
"@altimateai/altimate-core": "0.3.0"
|
|
14
14
|
},
|
|
15
15
|
"optionalDependencies": {
|
|
16
|
-
"@altimateai/altimate-code-linux-
|
|
17
|
-
"@altimateai/altimate-code-
|
|
18
|
-
"@altimateai/altimate-code-windows-
|
|
19
|
-
"@altimateai/altimate-code-darwin-
|
|
20
|
-
"@altimateai/altimate-code-windows-
|
|
21
|
-
"@altimateai/altimate-code-linux-
|
|
22
|
-
"@altimateai/altimate-code-linux-
|
|
23
|
-
"@altimateai/altimate-code-
|
|
24
|
-
"@altimateai/altimate-code-
|
|
25
|
-
"@altimateai/altimate-code-darwin-x64
|
|
26
|
-
"@altimateai/altimate-code-linux-x64
|
|
27
|
-
"@altimateai/altimate-code-
|
|
16
|
+
"@altimateai/altimate-code-linux-x64-musl": "0.6.0",
|
|
17
|
+
"@altimateai/altimate-code-linux-x64-baseline": "0.6.0",
|
|
18
|
+
"@altimateai/altimate-code-windows-arm64": "0.6.0",
|
|
19
|
+
"@altimateai/altimate-code-darwin-arm64": "0.6.0",
|
|
20
|
+
"@altimateai/altimate-code-windows-x64-baseline": "0.6.0",
|
|
21
|
+
"@altimateai/altimate-code-linux-arm64": "0.6.0",
|
|
22
|
+
"@altimateai/altimate-code-linux-x64-baseline-musl": "0.6.0",
|
|
23
|
+
"@altimateai/altimate-code-darwin-x64-baseline": "0.6.0",
|
|
24
|
+
"@altimateai/altimate-code-windows-x64": "0.6.0",
|
|
25
|
+
"@altimateai/altimate-code-darwin-x64": "0.6.0",
|
|
26
|
+
"@altimateai/altimate-code-linux-x64": "0.6.0",
|
|
27
|
+
"@altimateai/altimate-code-linux-arm64-musl": "0.6.0"
|
|
28
28
|
},
|
|
29
29
|
"peerDependencies": {
|
|
30
30
|
"pg": ">=8",
|
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: data-parity
|
|
3
|
+
description: Validate that two tables or query results are identical — or diagnose exactly how they differ. Discover schema, identify keys, profile cheaply, then diff. Use for migration validation, ETL regression, and query refactor verification.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Data Parity (Table Diff)
|
|
7
|
+
|
|
8
|
+
## CRITICAL: Regulated / Sensitive Data
|
|
9
|
+
|
|
10
|
+
`data_diff` includes up to 5 **sample diff rows** in the tool output so you can see *which* values differ. Those rows are part of the conversation and are sent to the LLM provider you're using.
|
|
11
|
+
|
|
12
|
+
Before running `data_diff` against a table that might contain PII, PHI, PCI, or other regulated data:
|
|
13
|
+
|
|
14
|
+
1. **Ask the user** whether the target contains regulated columns.
|
|
15
|
+
2. If yes, prefer `algorithm: "profile"` — it compares column-level statistics (count, nulls, min/max, distinct count) without any row values leaving the database.
|
|
16
|
+
3. If a row-level diff is genuinely required, tell the user that up to 5 sample rows will be sent to the LLM and get explicit approval before calling the tool.
|
|
17
|
+
4. Consider scoping with `where_clause` to exclude sensitive customers/accounts first.
|
|
18
|
+
|
|
19
|
+
Default to profile mode whenever the table name suggests regulated data (`customers`, `patients`, `orders`, `payments`, `accounts`, `users`, etc.) unless the user explicitly requests row-level comparison.
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## CRITICAL: Always Start With a Plan
|
|
24
|
+
|
|
25
|
+
**Before doing anything else**, generate a numbered TODO list for the user:
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
Here's my plan:
|
|
29
|
+
1. [ ] List available warehouse connections
|
|
30
|
+
2. [ ] Inspect schema, discover primary key candidates, and detect auto-timestamp columns
|
|
31
|
+
3. [ ] Confirm primary keys with you
|
|
32
|
+
4. [ ] Confirm which auto-timestamp columns to exclude
|
|
33
|
+
5. [ ] Check row counts on both sides
|
|
34
|
+
6. [ ] Run column-level profile (cheap — no row scan)
|
|
35
|
+
7. [ ] Ask whether to proceed with row-level diff (may be expensive for large tables)
|
|
36
|
+
8. [ ] Run targeted row-level diff on diverging columns only
|
|
37
|
+
9. [ ] Present findings with scope, filters, time period, columns compared/excluded, and assumptions
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Update each item to `[x]` as you complete it. This plan should be visible before any tool is called.
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## CRITICAL: Use `data_diff` Tool — Never Write Manual Diff SQL
|
|
45
|
+
|
|
46
|
+
**NEVER** write SQL to diff tables manually (e.g., `EXCEPT`, `FULL OUTER JOIN`, `MINUS`).
|
|
47
|
+
**ALWAYS** use the `data_diff` tool for any comparison operation.
|
|
48
|
+
|
|
49
|
+
`sql_query` is only for:
|
|
50
|
+
- Schema inspection (`information_schema`, `SHOW COLUMNS`, `DESCRIBE`)
|
|
51
|
+
- Cardinality checks to identify keys
|
|
52
|
+
- Row count estimates
|
|
53
|
+
|
|
54
|
+
Everything else — profile, row diff, value comparison — goes through `data_diff`.
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## Step 1: List Connections
|
|
59
|
+
|
|
60
|
+
Use `warehouse_list` to show the user what connections are available and which warehouses map to source and target.
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## Step 2: Inspect Schema, Discover Primary Keys, and Detect Auto-Timestamp Columns
|
|
65
|
+
|
|
66
|
+
Use `sql_query` to get columns, defaults, and identify key candidates:
|
|
67
|
+
|
|
68
|
+
```sql
|
|
69
|
+
-- Postgres / Redshift / DuckDB
|
|
70
|
+
SELECT column_name, data_type, is_nullable, column_default
|
|
71
|
+
FROM information_schema.columns
|
|
72
|
+
WHERE table_schema = 'public' AND table_name = 'orders'
|
|
73
|
+
ORDER BY ordinal_position
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
```sql
|
|
77
|
+
-- Snowflake
|
|
78
|
+
SHOW COLUMNS IN TABLE orders
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
```sql
|
|
82
|
+
-- MySQL / MariaDB (also fetch EXTRA for ON UPDATE detection)
|
|
83
|
+
SELECT column_name, data_type, is_nullable, column_default, extra
|
|
84
|
+
FROM information_schema.columns
|
|
85
|
+
WHERE table_schema = 'mydb' AND table_name = 'orders'
|
|
86
|
+
ORDER BY ordinal_position
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
```sql
|
|
90
|
+
-- SQL Server / Fabric
|
|
91
|
+
SELECT c.name AS column_name, tp.name AS data_type, c.is_nullable,
|
|
92
|
+
dc.definition AS column_default
|
|
93
|
+
FROM sys.columns c
|
|
94
|
+
INNER JOIN sys.types tp ON c.user_type_id = tp.user_type_id
|
|
95
|
+
INNER JOIN sys.objects o ON c.object_id = o.object_id
|
|
96
|
+
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
|
|
97
|
+
LEFT JOIN sys.default_constraints dc ON c.default_object_id = dc.object_id
|
|
98
|
+
WHERE s.name = 'dbo' AND o.name = 'orders'
|
|
99
|
+
ORDER BY c.column_id
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
```sql
|
|
103
|
+
-- ClickHouse
|
|
104
|
+
DESCRIBE TABLE source_db.events
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
**Look for:** columns named `id`, `*_id`, `*_key`, `uuid`, or with `NOT NULL` + unique index.
|
|
108
|
+
|
|
109
|
+
**Also look for auto-timestamp columns** — any column whose `column_default` contains a time-generating function:
|
|
110
|
+
- PostgreSQL/DuckDB/Redshift: `now()`, `CURRENT_TIMESTAMP`, `clock_timestamp()`
|
|
111
|
+
- MySQL/MariaDB: `CURRENT_TIMESTAMP` (in default or EXTRA)
|
|
112
|
+
- Snowflake: `CURRENT_TIMESTAMP()`, `SYSDATE()`
|
|
113
|
+
- SQL Server: `getdate()`, `sysdatetime()`
|
|
114
|
+
- Oracle: `SYSDATE`, `SYSTIMESTAMP`
|
|
115
|
+
|
|
116
|
+
These columns auto-generate values on INSERT, so they inherently differ between source and target due to write timing — not because of actual data discrepancies. **Collect them for confirmation in Step 4.**
|
|
117
|
+
|
|
118
|
+
If no obvious PK, run a cardinality check:
|
|
119
|
+
|
|
120
|
+
```sql
|
|
121
|
+
SELECT
|
|
122
|
+
COUNT(*) AS total_rows,
|
|
123
|
+
COUNT(DISTINCT order_id) AS distinct_order_id,
|
|
124
|
+
COUNT(DISTINCT customer_id) AS distinct_customer_id
|
|
125
|
+
FROM orders
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
A valid key column: `distinct_count = total_rows`.
|
|
129
|
+
|
|
130
|
+
For composite keys:
|
|
131
|
+
```sql
|
|
132
|
+
SELECT order_id, line_item_id, COUNT(*) AS cnt
|
|
133
|
+
FROM order_lines
|
|
134
|
+
GROUP BY order_id, line_item_id
|
|
135
|
+
HAVING COUNT(*) > 1
|
|
136
|
+
LIMIT 5
|
|
137
|
+
```
|
|
138
|
+
If this returns 0 rows, `(order_id, line_item_id)` is a valid composite key.
|
|
139
|
+
|
|
140
|
+
## Step 3: Confirm Keys With the User
|
|
141
|
+
|
|
142
|
+
**Always confirm** the identified key columns before proceeding:
|
|
143
|
+
|
|
144
|
+
> "I identified `order_id` as the primary key (150,000 distinct values = 150,000 rows, no NULLs). Does that look right, or should I use a different column?"
|
|
145
|
+
|
|
146
|
+
Do not proceed to diff until the user confirms or corrects.
|
|
147
|
+
|
|
148
|
+
---
|
|
149
|
+
|
|
150
|
+
## Step 4: Confirm Auto-Timestamp Column Exclusions
|
|
151
|
+
|
|
152
|
+
If you detected any columns with auto-generating timestamp defaults in Step 2, **present them to the user and ask for confirmation** before excluding them.
|
|
153
|
+
|
|
154
|
+
**Example prompt when auto-timestamp columns are found:**
|
|
155
|
+
|
|
156
|
+
> "I found **3 columns** with auto-generating timestamp defaults that will inherently differ between source and target (due to when each row was written, not actual data differences):
|
|
157
|
+
>
|
|
158
|
+
> | Column | Default | Reason to exclude |
|
|
159
|
+
> |--------|---------|-------------------|
|
|
160
|
+
> | `created_at` | `DEFAULT now()` | Set on insert — reflects when this copy was written |
|
|
161
|
+
> | `updated_at` | `DEFAULT now()` | Set on insert — reflects when this copy was written |
|
|
162
|
+
> | `_loaded_at` | `DEFAULT CURRENT_TIMESTAMP` | ETL load timestamp |
|
|
163
|
+
>
|
|
164
|
+
> Should I **exclude** these from the comparison? Or do you want to include any of them (e.g., if you're verifying that `created_at` was preserved during migration)?"
|
|
165
|
+
|
|
166
|
+
**If user confirms exclusion:** Omit those columns from `extra_columns` when calling `data_diff`.
|
|
167
|
+
|
|
168
|
+
**If user wants to include some:** Add them explicitly to `extra_columns`.
|
|
169
|
+
|
|
170
|
+
**If no auto-timestamp columns were detected:** Skip this step and proceed to Step 5.
|
|
171
|
+
|
|
172
|
+
> **Why ask?** In migration validation, `created_at` should often be *identical* between source and target (it was migrated, not regenerated). But in ETL replication, `created_at` is freshly generated on each side and *should* differ. Only the user knows which case applies.
|
|
173
|
+
|
|
174
|
+
---
|
|
175
|
+
|
|
176
|
+
## Step 5: Check Row Counts
|
|
177
|
+
|
|
178
|
+
```sql
|
|
179
|
+
SELECT COUNT(*) FROM orders -- run on both source and target
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
Use counts to:
|
|
183
|
+
- Detect load completeness issues before row-level diff
|
|
184
|
+
- Choose the algorithm and decide whether to ask about cost
|
|
185
|
+
- If counts differ significantly (>5%), flag it immediately
|
|
186
|
+
|
|
187
|
+
---
|
|
188
|
+
|
|
189
|
+
## Step 6: Column-Level Profile (Always Run This First)
|
|
190
|
+
|
|
191
|
+
Profile is cheap — it runs aggregates, not row scans. **Always run profile before row-level diff.**
|
|
192
|
+
|
|
193
|
+
```
|
|
194
|
+
data_diff(
|
|
195
|
+
source="orders",
|
|
196
|
+
target="orders",
|
|
197
|
+
key_columns=["order_id"],
|
|
198
|
+
source_warehouse="postgres_prod",
|
|
199
|
+
target_warehouse="snowflake_dw",
|
|
200
|
+
algorithm="profile"
|
|
201
|
+
)
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Profile tells you:
|
|
205
|
+
- Row count on each side
|
|
206
|
+
- Which columns have null count differences → NULL handling bug
|
|
207
|
+
- Min/max divergence per column → value transformation bug
|
|
208
|
+
- Which columns match exactly → safe to skip in row-level diff
|
|
209
|
+
|
|
210
|
+
**Example output:**
|
|
211
|
+
```
|
|
212
|
+
Column Profile Comparison
|
|
213
|
+
|
|
214
|
+
✓ order_id: match
|
|
215
|
+
✓ customer_id: match
|
|
216
|
+
✗ amount: DIFFER ← source min=10.00, target min=10.01 — rounding?
|
|
217
|
+
✗ status: DIFFER ← source nulls=0, target nulls=47 — NULL mapping bug?
|
|
218
|
+
✓ created_at: match
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
---
|
|
222
|
+
|
|
223
|
+
## Step 7: Ask Before Running Row-Level Diff on Large Tables
|
|
224
|
+
|
|
225
|
+
After profiling, check row count and **ask the user** before proceeding:
|
|
226
|
+
|
|
227
|
+
**If table has < 100K rows:** proceed automatically.
|
|
228
|
+
|
|
229
|
+
**If table has 100K–10M rows:**
|
|
230
|
+
> "The table has 1.2M rows. Row-level diff will scan all rows on both sides — this may take 30–60 seconds and consume warehouse compute. Do you want to proceed? You can also provide a `where_clause` to limit the scope (e.g., `created_at >= '2024-01-01'`)."
|
|
231
|
+
|
|
232
|
+
**If table has > 10M rows:**
|
|
233
|
+
> "The table has 50M rows. Full row-level diff could be expensive. Options:
|
|
234
|
+
> 1. Diff a recent window only (e.g., last 30 days)
|
|
235
|
+
> 2. Partition by a date/key column — shows which partition has problems without scanning everything
|
|
236
|
+
> 3. Proceed with full diff (may take several minutes)
|
|
237
|
+
> Which would you prefer?"
|
|
238
|
+
|
|
239
|
+
---
|
|
240
|
+
|
|
241
|
+
## Step 8: Run Targeted Row-Level Diff
|
|
242
|
+
|
|
243
|
+
Use only the columns that the profile said differ. This is faster and produces cleaner output.
|
|
244
|
+
|
|
245
|
+
```
|
|
246
|
+
data_diff(
|
|
247
|
+
source="orders",
|
|
248
|
+
target="orders",
|
|
249
|
+
key_columns=["order_id"],
|
|
250
|
+
extra_columns=["amount", "status"], // only diverging columns from profile
|
|
251
|
+
source_warehouse="postgres_prod",
|
|
252
|
+
target_warehouse="snowflake_dw",
|
|
253
|
+
algorithm="hashdiff"
|
|
254
|
+
)
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
### For large tables — use partition_column
|
|
258
|
+
|
|
259
|
+
Split the table into groups and diff each independently. Three modes:
|
|
260
|
+
|
|
261
|
+
```
|
|
262
|
+
// Date column — partition by month
|
|
263
|
+
data_diff(source="lineitem", target="lineitem",
|
|
264
|
+
key_columns=["l_orderkey", "l_linenumber"],
|
|
265
|
+
source_warehouse="pg_source", target_warehouse="pg_target",
|
|
266
|
+
partition_column="l_shipdate", partition_granularity="month",
|
|
267
|
+
algorithm="hashdiff")
|
|
268
|
+
|
|
269
|
+
// Numeric column — partition by key ranges of 100K
|
|
270
|
+
data_diff(source="orders", target="orders",
|
|
271
|
+
key_columns=["o_orderkey"],
|
|
272
|
+
source_warehouse="pg_source", target_warehouse="pg_target",
|
|
273
|
+
partition_column="o_orderkey", partition_bucket_size=100000,
|
|
274
|
+
algorithm="hashdiff")
|
|
275
|
+
|
|
276
|
+
// Categorical column — partition by distinct values (string, enum, boolean)
|
|
277
|
+
data_diff(source="orders", target="orders",
|
|
278
|
+
key_columns=["o_orderkey"],
|
|
279
|
+
source_warehouse="pg_source", target_warehouse="pg_target",
|
|
280
|
+
partition_column="o_orderstatus",
|
|
281
|
+
algorithm="hashdiff")
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
Output includes aggregate diff + per-partition breakdown showing which group has problems.
|
|
285
|
+
|
|
286
|
+
---
|
|
287
|
+
|
|
288
|
+
## Algorithm Selection
|
|
289
|
+
|
|
290
|
+
| Algorithm | When to use |
|
|
291
|
+
|-----------|-------------|
|
|
292
|
+
| `profile` | **Always run first** — column stats (count, min, max, nulls). No row scan. |
|
|
293
|
+
| `joindiff` | Same database — single FULL OUTER JOIN. Fast, exact. |
|
|
294
|
+
| `hashdiff` | Cross-database or large tables — bisection with checksums. Scales to billions. |
|
|
295
|
+
| `cascade` | Auto-escalate: profile → hashdiff on diverging columns. |
|
|
296
|
+
| `auto` | JoinDiff if same warehouse, HashDiff if cross-database. |
|
|
297
|
+
|
|
298
|
+
> **CRITICAL:** If `source_warehouse` ≠ `target_warehouse`, **never use `joindiff`** — it only sees one connection and always reports 0 differences. Use `hashdiff` or `auto`.
|
|
299
|
+
|
|
300
|
+
---
|
|
301
|
+
|
|
302
|
+
## Output Interpretation
|
|
303
|
+
|
|
304
|
+
### IDENTICAL
|
|
305
|
+
```
|
|
306
|
+
✓ Tables are IDENTICAL
|
|
307
|
+
Rows checked: 1,000,000
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
### DIFFER
|
|
311
|
+
```
|
|
312
|
+
✗ Tables DIFFER
|
|
313
|
+
|
|
314
|
+
Source rows: 150,000
|
|
315
|
+
Target rows: 149,950
|
|
316
|
+
Only in source: 50 → rows deleted in target (ETL missed deletes)
|
|
317
|
+
Only in target: 0
|
|
318
|
+
Updated rows: 0
|
|
319
|
+
Identical rows: 149,950
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
| Pattern | Root cause |
|
|
323
|
+
|---------|-----------|
|
|
324
|
+
| `only_in_source > 0`, target = 0 | ETL dropped rows — check filters, incremental logic |
|
|
325
|
+
| `only_in_target > 0`, source = 0 | Target has extra rows — dedup issue or wrong join |
|
|
326
|
+
| `updated_rows > 0`, counts match | Silent value corruption — check type casts, rounding |
|
|
327
|
+
| Row counts differ significantly | Load completeness — check ETL watermarks |
|
|
328
|
+
|
|
329
|
+
---
|
|
330
|
+
|
|
331
|
+
## CRITICAL: `extra_columns` Behavior
|
|
332
|
+
|
|
333
|
+
The Rust engine **only compares columns listed in `extra_columns`**. If the list is empty, it compares key existence only — rows that match on key but differ in values will be silently reported as "identical". This is the most common source of false positives.
|
|
334
|
+
|
|
335
|
+
**Auto-discovery (default for table names):** When `extra_columns` is omitted and the source is a plain table name, `data_diff` auto-discovers all non-key columns from the database catalog and excludes columns using two detection layers:
|
|
336
|
+
|
|
337
|
+
1. **Name-pattern matching** — columns named like `updated_at`, `created_at`, `inserted_at`, `modified_at`, `publisher_last_updated_epoch_ms`, ETL metadata columns like `_fivetran_synced`, `_airbyte_extracted_at`, etc.
|
|
338
|
+
2. **Schema-level default detection** — columns with auto-generating timestamp defaults (`DEFAULT NOW()`, `DEFAULT CURRENT_TIMESTAMP`, `GETDATE()`, `SYSDATE()`, `SYSTIMESTAMP`, etc.), detected directly from the database catalog. This catches columns that don't follow naming conventions but still auto-generate values on INSERT. Works across PostgreSQL, MySQL, Snowflake, SQL Server, Oracle, ClickHouse, DuckDB, SQLite, and Redshift.
|
|
339
|
+
|
|
340
|
+
The output lists which columns were auto-excluded and why.
|
|
341
|
+
|
|
342
|
+
**SQL queries:** When source is a SQL query (not a table name), auto-discovery cannot work. You **must** provide `extra_columns` explicitly. If you don't, only key-level matching occurs.
|
|
343
|
+
|
|
344
|
+
**When to override auto-exclusion:** If the user specifically wants to compare audit columns (e.g., verifying that `created_at` was preserved during migration), pass those columns explicitly in `extra_columns`.
|
|
345
|
+
|
|
346
|
+
---
|
|
347
|
+
|
|
348
|
+
## Step 9: Present Findings — Always Surface Context
|
|
349
|
+
|
|
350
|
+
When reporting diff results, **never present bare numbers**. Always frame the result with the full context that determines what the numbers actually mean.
|
|
351
|
+
|
|
352
|
+
### Required elements in every result summary
|
|
353
|
+
|
|
354
|
+
**1. Scope — what was compared**
|
|
355
|
+
State exactly which tables/queries were diffed and on which warehouses:
|
|
356
|
+
> "Compared `public.orders` on **postgres_prod** vs `public.orders` on **snowflake_dw**"
|
|
357
|
+
|
|
358
|
+
**2. Filters and time period applied**
|
|
359
|
+
If any `where_clause` or `partition_column` was used, state it explicitly:
|
|
360
|
+
> "Scope limited to: `created_at >= '2024-01-01' AND created_at < '2024-04-01'` (Q1 2024 only)"
|
|
361
|
+
> "Partitioned by `l_shipdate` (monthly buckets) — diff covers Jan 2023 through Mar 2024"
|
|
362
|
+
|
|
363
|
+
If no filter was applied, say so:
|
|
364
|
+
> "No row filter applied — full table compared"
|
|
365
|
+
|
|
366
|
+
**3. Key columns used**
|
|
367
|
+
> "Key: `order_id` (confirmed unique — 150,000 distinct values = 150,000 rows)"
|
|
368
|
+
|
|
369
|
+
**4. Columns included and excluded**
|
|
370
|
+
List what was compared and what was skipped, and why:
|
|
371
|
+
> "Compared columns: `amount`, `status`, `customer_id`"
|
|
372
|
+
> "Excluded (auto-timestamp defaults): `created_at`, `updated_at`, `_loaded_at`"
|
|
373
|
+
> "Excluded (user request): `internal_score`"
|
|
374
|
+
|
|
375
|
+
If the user confirmed exclusions in Step 4, reference that confirmation:
|
|
376
|
+
> "Excluded per your confirmation: `created_at`, `updated_at`"
|
|
377
|
+
|
|
378
|
+
**5. Algorithm used**
|
|
379
|
+
> "Algorithm: `hashdiff` (cross-database)"
|
|
380
|
+
|
|
381
|
+
### Example full result summary
|
|
382
|
+
|
|
383
|
+
```
|
|
384
|
+
## Data Parity Results
|
|
385
|
+
|
|
386
|
+
**Compared:** `public.orders` (postgres_prod) → `public.orders` (snowflake_dw)
|
|
387
|
+
**Scope:** `created_at >= '2024-01-01'` (Q1 2024 only — 42,301 rows in scope)
|
|
388
|
+
**Key:** `order_id`
|
|
389
|
+
**Columns compared:** `amount`, `status`, `customer_id`, `region`
|
|
390
|
+
**Columns excluded:** `created_at`, `updated_at` (auto-timestamp defaults, per your confirmation)
|
|
391
|
+
**Algorithm:** hashdiff
|
|
392
|
+
|
|
393
|
+
### Result: ✗ DIFFER
|
|
394
|
+
|
|
395
|
+
| Metric | Value |
|
|
396
|
+
|--------|-------|
|
|
397
|
+
| Source rows | 42,301 |
|
|
398
|
+
| Target rows | 42,298 |
|
|
399
|
+
| Only in source | 3 |
|
|
400
|
+
| Only in target | 0 |
|
|
401
|
+
| Updated rows | 47 |
|
|
402
|
+
| Identical rows | 42,251 |
|
|
403
|
+
|
|
404
|
+
**Findings:**
|
|
405
|
+
- 3 rows exist in source but are missing in target → possible ETL delete propagation gap
|
|
406
|
+
- 47 rows have value differences in `amount` or `status` → check rounding or status mapping
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
### When result is IDENTICAL — still surface the scope
|
|
410
|
+
|
|
411
|
+
Even when tables match perfectly, state what was checked:
|
|
412
|
+
> "✓ Tables are **identical** across 150,000 rows. Compared `amount`, `status`, `customer_id` (full table, no filter, key=`order_id`). Auto-timestamp columns `created_at`, `updated_at` were excluded."
|
|
413
|
+
|
|
414
|
+
**Why this matters:** "Tables are identical" without context is meaningless — the user needs to know if you checked Q1 only, skipped 5 columns, or used a WHERE clause that covered just 1% of the data.
|
|
415
|
+
|
|
416
|
+
---
|
|
417
|
+
|
|
418
|
+
## Common Mistakes
|
|
419
|
+
|
|
420
|
+
**Writing manual diff SQL instead of calling data_diff**
|
|
421
|
+
→ Never use EXCEPT, MINUS, or FULL OUTER JOIN to diff tables. Use `data_diff`.
|
|
422
|
+
|
|
423
|
+
**Calling data_diff without confirming the key**
|
|
424
|
+
→ Confirm cardinality with the user first. A bad key gives meaningless results.
|
|
425
|
+
|
|
426
|
+
**Using joindiff for cross-database tables**
|
|
427
|
+
→ JoinDiff can't see the remote table. Always returns 0 diffs. Use `hashdiff` or `auto`.
|
|
428
|
+
|
|
429
|
+
**Skipping the profile step and jumping to full row diff**
|
|
430
|
+
→ Profile is free. It tells you which columns actually differ so you avoid scanning everything.
|
|
431
|
+
|
|
432
|
+
**Running full diff on a billion-row table without asking**
|
|
433
|
+
→ Always ask the user before expensive operations. Offer filtering and partition options.
|
|
434
|
+
|
|
435
|
+
**Omitting extra_columns when source is a SQL query**
|
|
436
|
+
→ Auto-discovery only works for table names. For SQL queries, always list the columns to compare explicitly.
|
|
437
|
+
|
|
438
|
+
**Silently excluding auto-timestamp columns without asking the user**
|
|
439
|
+
→ Always present detected auto-timestamp columns (Step 4) and get explicit confirmation. In migration scenarios, `created_at` should be *identical* — excluding it silently hides real bugs.
|
|
440
|
+
|
|
441
|
+
---
|
|
442
|
+
|
|
443
|
+
## SQL Server and Microsoft Fabric
|
|
444
|
+
|
|
445
|
+
### Minimum Version Requirements
|
|
446
|
+
|
|
447
|
+
| Component | Minimum Version | Why |
|
|
448
|
+
|---|---|---|
|
|
449
|
+
| **SQL Server** | 2022 (16.x) | `DATETRUNC()` used for date partitioning; `LEAST()`/`GREATEST()` used by Rust engine |
|
|
450
|
+
| **Azure SQL Database** | Any current version | Always has `DATETRUNC()` and `LEAST()` |
|
|
451
|
+
| **Microsoft Fabric** | Any current version | T-SQL surface includes all required functions |
|
|
452
|
+
| **mssql** (npm) | 12.0.0 | `ConnectionPool` isolation for concurrent connections, tedious 19 |
|
|
453
|
+
| **@azure/identity** (npm) | 4.0.0 | Required only for Azure AD authentication; tedious imports it internally |
|
|
454
|
+
|
|
455
|
+
> **Note:** Date partitioning (`partition_column` + `partition_granularity`) uses `DATETRUNC()` which is **not available on SQL Server 2019 or earlier**. Basic diff operations (joindiff, hashdiff, profile) work on older versions. If you need partitioned diffs on SQL Server < 2022, use numeric or categorical partitioning instead.
|
|
456
|
+
|
|
457
|
+
### Supported Configurations
|
|
458
|
+
|
|
459
|
+
| Warehouse Type | Authentication | Notes |
|
|
460
|
+
|---|---|---|
|
|
461
|
+
| `sqlserver` / `mssql` | User/password or Azure AD | On-prem or Azure SQL. SQL Server 2022+ required for date partitioning. |
|
|
462
|
+
| `fabric` | Azure AD only | Microsoft Fabric SQL endpoint. Always uses TLS encryption. |
|
|
463
|
+
|
|
464
|
+
### Connecting to Microsoft Fabric
|
|
465
|
+
|
|
466
|
+
Fabric uses the same TDS protocol as SQL Server — no separate driver needed. Configuration:
|
|
467
|
+
|
|
468
|
+
```yaml
|
|
469
|
+
type: "fabric"
|
|
470
|
+
host: "<workspace-id>-<item-id>.datawarehouse.fabric.microsoft.com"
|
|
471
|
+
database: "<warehouse-name>"
|
|
472
|
+
authentication: "azure-active-directory-default" # recommended
|
|
473
|
+
```
|
|
474
|
+
|
|
475
|
+
Auth shorthands (mapped to full tedious type names):
|
|
476
|
+
- `CLI` or `default` → `azure-active-directory-default`
|
|
477
|
+
- `password` → `azure-active-directory-password`
|
|
478
|
+
- `service-principal` → `azure-active-directory-service-principal-secret`
|
|
479
|
+
- `msi` or `managed-identity` → `azure-active-directory-msi-vm`
|
|
480
|
+
|
|
481
|
+
Full Azure AD authentication types:
|
|
482
|
+
- `azure-active-directory-default` — auto-discovers credentials via `DefaultAzureCredential` (recommended; works with `az login`)
|
|
483
|
+
- `azure-active-directory-password` — username/password with `azure_client_id` and `azure_tenant_id`
|
|
484
|
+
- `azure-active-directory-access-token` — pre-obtained token (does **not** auto-refresh)
|
|
485
|
+
- `azure-active-directory-service-principal-secret` — service principal with `azure_client_id`, `azure_client_secret`, `azure_tenant_id`
|
|
486
|
+
- `azure-active-directory-msi-vm` / `azure-active-directory-msi-app-service` — managed identity
|
|
487
|
+
|
|
488
|
+
### Algorithm Behavior
|
|
489
|
+
|
|
490
|
+
- **Same-warehouse** MSSQL or Fabric → `joindiff` (single FULL OUTER JOIN, most efficient)
|
|
491
|
+
- **Cross-warehouse** MSSQL/Fabric ↔ other database → `hashdiff` (automatic when using `auto`)
|
|
492
|
+
- The Rust engine maps `sqlserver`/`mssql` to `tsql` dialect and `fabric` to `fabric` dialect — both generate valid T-SQL syntax with bracket quoting (`[schema].[table]`).
|
package/skills/dbt-test/SKILL.md
CHANGED
|
@@ -81,6 +81,8 @@ altimate-dbt build --model <name> # build + test together
|
|
|
81
81
|
|
|
82
82
|
## Unit Test Workflow
|
|
83
83
|
|
|
84
|
+
**For automated unit test generation, use the `dbt-unit-tests` skill instead.** It analyzes model SQL, generates type-correct mock data, and assembles complete YAML automatically.
|
|
85
|
+
|
|
84
86
|
See [references/unit-test-guide.md](references/unit-test-guide.md) for the full unit test framework.
|
|
85
87
|
|
|
86
88
|
### Quick Pattern
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: dbt-unit-tests
|
|
3
|
+
description: Generate dbt unit tests automatically for any model. Analyzes SQL logic (CASE/WHEN, JOINs, window functions, NULLs), creates type-correct mock inputs from manifest schema, and assembles complete YAML. Use when a user says "generate tests", "add unit tests", "test this model", or "test coverage" for dbt models.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# dbt Unit Test Generation
|
|
7
|
+
|
|
8
|
+
## Requirements
|
|
9
|
+
**Agent:** builder or migrator (requires file write access)
|
|
10
|
+
**Tools used:** dbt_unit_test_gen, dbt_manifest, dbt_lineage, altimate_core_validate, altimate_core_testgen, bash (runs `altimate-dbt` commands), read, glob, write, edit
|
|
11
|
+
|
|
12
|
+
## When to Use This Skill
|
|
13
|
+
|
|
14
|
+
**Use when the user wants to:**
|
|
15
|
+
- Generate unit tests for a dbt model
|
|
16
|
+
- Add test coverage to an existing model
|
|
17
|
+
- Create mock data for testing
|
|
18
|
+
- Test-driven development (TDD) for dbt
|
|
19
|
+
- Verify CASE/WHEN logic, NULL handling, JOIN behavior, or aggregation correctness
|
|
20
|
+
- Test incremental model logic
|
|
21
|
+
|
|
22
|
+
**Do NOT use for:**
|
|
23
|
+
- Adding schema tests (not_null, unique, accepted_values) -> use `dbt-test`
|
|
24
|
+
- Creating or modifying model SQL -> use `dbt-develop`
|
|
25
|
+
- Writing descriptions -> use `dbt-docs`
|
|
26
|
+
- Debugging build failures -> use `dbt-troubleshoot`
|
|
27
|
+
|
|
28
|
+
## The Iron Rules
|
|
29
|
+
|
|
30
|
+
1. **Never guess expected outputs.** Compute them by running SQL against mock data when possible. If you cannot run SQL, clearly mark expected outputs as placeholders that need verification.
|
|
31
|
+
2. **Never skip upstream dependencies.** Every ref() and source() the model touches MUST have a mock input. Miss one and the test won't compile.
|
|
32
|
+
3. **Use sql format for ephemeral models.** Dict format fails silently for ephemeral upstreams.
|
|
33
|
+
4. **Never weaken a test to make it pass.** If the test fails, the model logic may be wrong. Investigate before changing expected values.
|
|
34
|
+
5. **Compile before committing.** Always run `altimate-dbt test --model <name>` to verify tests compile and execute.
|
|
35
|
+
|
|
36
|
+
## Core Workflow: Analyze -> Generate -> Refine -> Validate -> Write
|
|
37
|
+
|
|
38
|
+
### Phase 1: Analyze the Model
|
|
39
|
+
|
|
40
|
+
Before generating any tests, deeply understand the model:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
# 1. Ensure manifest is compiled
|
|
44
|
+
altimate-dbt compile --model <name>
|
|
45
|
+
|
|
46
|
+
# 2. Read the model SQL
|
|
47
|
+
read <model_sql_file>
|
|
48
|
+
|
|
49
|
+
# 3. Parse the manifest for dependencies
|
|
50
|
+
dbt_unit_test_gen(manifest_path: "target/manifest.json", model: "<name>")
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
**What to look for:**
|
|
54
|
+
- Which upstream refs/sources does this model depend on?
|
|
55
|
+
- What SQL constructs need testing? (CASE/WHEN, JOINs, window functions, aggregations)
|
|
56
|
+
- What edge cases exist? (NULLs, empty strings, zero values, boundary dates)
|
|
57
|
+
- Is this an incremental model? (needs `is_incremental` override tests)
|
|
58
|
+
- Are any upstream models ephemeral? (need sql format)
|
|
59
|
+
|
|
60
|
+
### Phase 2: Generate Tests
|
|
61
|
+
|
|
62
|
+
The `dbt_unit_test_gen` tool does the heavy lifting:
|
|
63
|
+
|
|
64
|
+
```text
|
|
65
|
+
dbt_unit_test_gen(
|
|
66
|
+
manifest_path: "target/manifest.json",
|
|
67
|
+
model: "fct_orders",
|
|
68
|
+
max_scenarios: 5
|
|
69
|
+
)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
This returns:
|
|
73
|
+
- Complete YAML with mock inputs and expected outputs
|
|
74
|
+
- Semantic context: model/column descriptions, column lineage, compiled SQL
|
|
75
|
+
- List of anti-patterns that informed edge case generation
|
|
76
|
+
- Warnings about ephemeral deps, missing columns, etc.
|
|
77
|
+
|
|
78
|
+
**If the tool reports missing columns** (placeholder rows in the YAML), discover them:
|
|
79
|
+
```bash
|
|
80
|
+
altimate-dbt columns --model <upstream_model_name>
|
|
81
|
+
altimate-dbt columns-source --source <source_name> --table <table_name>
|
|
82
|
+
```
|
|
83
|
+
Then update the generated YAML with real column names.
|
|
84
|
+
|
|
85
|
+
### Phase 3: Refine Expected Outputs
|
|
86
|
+
|
|
87
|
+
**This is the critical step that differentiates good tests from bad ones.**
|
|
88
|
+
|
|
89
|
+
The tool generates placeholder expected outputs based on column types. You MUST refine them:
|
|
90
|
+
|
|
91
|
+
**Option A: Compute by running SQL (preferred)**
|
|
92
|
+
```bash
|
|
93
|
+
# Run the model against mock data to get actual output
|
|
94
|
+
altimate-dbt test --model <name>
|
|
95
|
+
# If the test fails, the error shows actual vs expected — use actual as expected
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
**Option B: Manual computation**
|
|
99
|
+
Read the model SQL carefully and mentally execute it against the mock inputs.
|
|
100
|
+
For each test case:
|
|
101
|
+
1. Look at the mock input rows
|
|
102
|
+
2. Trace through the SQL logic (CASE/WHEN branches, JOINs, aggregations)
|
|
103
|
+
3. Write the correct expected output
|
|
104
|
+
|
|
105
|
+
**Option C: Use the warehouse (most accurate)**
|
|
106
|
+
```bash
|
|
107
|
+
# Build a CTE query with mock data and run the model SQL against it
|
|
108
|
+
altimate-dbt execute --query "WITH mock_stg_orders AS (SELECT 1 AS order_id, 100.00 AS amount) SELECT * FROM (<model_sql>) sub"
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### Phase 4: Validate
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
# 1. Run the unit tests
|
|
115
|
+
altimate-dbt test --model <name>
|
|
116
|
+
|
|
117
|
+
# 2. If tests fail, read the error carefully
|
|
118
|
+
# - Compilation error? Missing ref, wrong column name, type mismatch
|
|
119
|
+
# - Assertion error? Expected output doesn't match actual
|
|
120
|
+
|
|
121
|
+
# 3. Fix and retry (max 3 iterations)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### Phase 5: Write to File
|
|
125
|
+
|
|
126
|
+
Place unit tests in one of these locations (match project convention):
|
|
127
|
+
- `models/<layer>/_unit_tests.yml` (dedicated file)
|
|
128
|
+
- `models/<layer>/schema.yml` (append to existing)
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
# Check existing convention
|
|
132
|
+
glob models/**/*unit_test*.yml models/**/*schema*.yml
|
|
133
|
+
|
|
134
|
+
# Write or append
|
|
135
|
+
edit <yaml_file> # if file exists
|
|
136
|
+
write <yaml_file> # if creating new
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Test Case Categories
|
|
140
|
+
|
|
141
|
+
### Happy Path (always generate)
|
|
142
|
+
Standard inputs that exercise the main logic path. 2 rows minimum.
|
|
143
|
+
|
|
144
|
+
### NULL Handling
|
|
145
|
+
Set nullable columns to NULL in the last row. Verify COALESCE/NVL/IFNULL behavior.
|
|
146
|
+
|
|
147
|
+
### Boundary Values
|
|
148
|
+
Zero amounts, empty strings, epoch dates, MAX values. Tests robustness.
|
|
149
|
+
|
|
150
|
+
### Edge Cases
|
|
151
|
+
- Division by zero (if model divides)
|
|
152
|
+
- Non-matching JOINs (LEFT JOIN with no match)
|
|
153
|
+
- Single-row aggregation
|
|
154
|
+
- Duplicate key handling
|
|
155
|
+
|
|
156
|
+
### Incremental
|
|
157
|
+
For incremental models only. Use `overrides.macros.is_incremental: true` to test the incremental path.
|
|
158
|
+
|
|
159
|
+
## Common Mistakes
|
|
160
|
+
|
|
161
|
+
| Mistake | Fix |
|
|
162
|
+
|---------|-----|
|
|
163
|
+
| Missing a ref() in given | Parse manifest for ALL depends_on nodes |
|
|
164
|
+
| Wrong column names in mock data | Use manifest columns, not guesses |
|
|
165
|
+
| Wrong data types | Use schema catalog types |
|
|
166
|
+
| Expected output is just mock input | Actually compute the transformation |
|
|
167
|
+
| Dict format for ephemeral model | Use `format: sql` with raw SQL |
|
|
168
|
+
| Not testing NULL path in COALESCE | Add null_handling test case |
|
|
169
|
+
| Hardcoded dates with current_timestamp | Use overrides.macros to mock timestamps |
|
|
170
|
+
| Testing trivial pass-through | Skip models with no logic |
|
|
171
|
+
|
|
172
|
+
## YAML Format Reference
|
|
173
|
+
|
|
174
|
+
```yaml
|
|
175
|
+
unit_tests:
|
|
176
|
+
- name: test_<model>_<scenario>
|
|
177
|
+
description: "What this test verifies"
|
|
178
|
+
model: <model_name>
|
|
179
|
+
overrides: # optional
|
|
180
|
+
macros:
|
|
181
|
+
is_incremental: true # for incremental models
|
|
182
|
+
vars:
|
|
183
|
+
run_date: "2024-01-15" # for date-dependent logic
|
|
184
|
+
given:
|
|
185
|
+
- input: ref('upstream_model')
|
|
186
|
+
rows:
|
|
187
|
+
- { col1: value1, col2: value2 }
|
|
188
|
+
- input: source('source_name', 'table_name')
|
|
189
|
+
rows:
|
|
190
|
+
- { col1: value1 }
|
|
191
|
+
- input: ref('ephemeral_model')
|
|
192
|
+
format: sql
|
|
193
|
+
rows: |
|
|
194
|
+
SELECT 1 AS id, 'test' AS name
|
|
195
|
+
UNION ALL
|
|
196
|
+
SELECT 2 AS id, 'other' AS name
|
|
197
|
+
expect:
|
|
198
|
+
rows:
|
|
199
|
+
- { output_col1: expected1, output_col2: expected2 }
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
## Reference Guides
|
|
203
|
+
|
|
204
|
+
| Guide | Use When |
|
|
205
|
+
|-------|----------|
|
|
206
|
+
| [references/unit-test-yaml-spec.md](references/unit-test-yaml-spec.md) | Full YAML specification and format details |
|
|
207
|
+
| [references/edge-case-patterns.md](references/edge-case-patterns.md) | Catalog of edge cases by SQL construct |
|
|
208
|
+
| [references/incremental-testing.md](references/incremental-testing.md) | Testing incremental models |
|
|
209
|
+
| [references/altimate-dbt-commands.md](references/altimate-dbt-commands.md) | Full CLI reference |
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# altimate-dbt Command Reference
|
|
2
|
+
|
|
3
|
+
All dbt operations use the `altimate-dbt` CLI. Output is JSON to stdout; logs go to stderr.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
altimate-dbt <command> [args...]
|
|
7
|
+
altimate-dbt <command> [args...] --format text # Human-readable output
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
## First-Time Setup
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
altimate-dbt init # Auto-detect project root
|
|
14
|
+
altimate-dbt init --project-root /path # Explicit root
|
|
15
|
+
altimate-dbt init --python-path /path # Override Python
|
|
16
|
+
altimate-dbt doctor # Verify setup
|
|
17
|
+
altimate-dbt info # Project name, adapter, root
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Build & Run
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
altimate-dbt build # full project build (compile + run + test)
|
|
24
|
+
altimate-dbt build --model <name> [--downstream] # build a single model
|
|
25
|
+
altimate-dbt run --model <name> [--downstream] # materialize only
|
|
26
|
+
altimate-dbt test --model <name> # run tests only
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Compile
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
altimate-dbt compile --model <name>
|
|
33
|
+
altimate-dbt compile-query --query "SELECT * FROM {{ ref('stg_orders') }}" [--model <context>]
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Execute SQL
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
altimate-dbt execute --query "SELECT count(*) FROM {{ ref('orders') }}" --limit 100
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Schema & DAG
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
altimate-dbt columns --model <name> # column names and types
|
|
46
|
+
altimate-dbt columns-source --source <src> --table <tbl> # source table columns
|
|
47
|
+
altimate-dbt column-values --model <name> --column <col> # sample values
|
|
48
|
+
altimate-dbt children --model <name> # downstream models
|
|
49
|
+
altimate-dbt parents --model <name> # upstream models
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Packages
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
altimate-dbt deps # install packages.yml
|
|
56
|
+
altimate-dbt add-packages --packages dbt-utils,dbt-expectations
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Error Handling
|
|
60
|
+
|
|
61
|
+
All errors return JSON with `error` and `fix` fields:
|
|
62
|
+
```json
|
|
63
|
+
{ "error": "dbt-core is not installed", "fix": "Install it: python3 -m pip install dbt-core" }
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Run `altimate-dbt doctor` as the first diagnostic step for any failure.
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
# Edge Case Patterns by SQL Construct
|
|
2
|
+
|
|
3
|
+
## CASE/WHEN
|
|
4
|
+
|
|
5
|
+
**What to test:** Every branch, including ELSE/default.
|
|
6
|
+
|
|
7
|
+
```yaml
|
|
8
|
+
# Test the TRUE branch
|
|
9
|
+
- { status: "completed", amount: 100 }
|
|
10
|
+
# Expected: { category: "done" }
|
|
11
|
+
|
|
12
|
+
# Test the FALSE/ELSE branch
|
|
13
|
+
- { status: "unknown", amount: 100 }
|
|
14
|
+
# Expected: { category: "other" }
|
|
15
|
+
|
|
16
|
+
# Test NULL input
|
|
17
|
+
- { status: null, amount: 100 }
|
|
18
|
+
# Expected: depends on whether NULL matches any WHEN
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
**Common bugs:**
|
|
22
|
+
- NULL doesn't match `WHEN status = 'active'` — it falls to ELSE
|
|
23
|
+
- Multiple WHEN clauses: first match wins, test ordering
|
|
24
|
+
|
|
25
|
+
## COALESCE / NVL / IFNULL
|
|
26
|
+
|
|
27
|
+
**What to test:** NULL in each position.
|
|
28
|
+
|
|
29
|
+
```yaml
|
|
30
|
+
# COALESCE(a, b, c) — test a=NULL
|
|
31
|
+
- { a: null, b: "fallback", c: "default" }
|
|
32
|
+
# Expected: { result: "fallback" }
|
|
33
|
+
|
|
34
|
+
# COALESCE(a, b, c) — test a=NULL, b=NULL
|
|
35
|
+
- { a: null, b: null, c: "default" }
|
|
36
|
+
# Expected: { result: "default" }
|
|
37
|
+
|
|
38
|
+
# All non-null
|
|
39
|
+
- { a: "primary", b: "fallback", c: "default" }
|
|
40
|
+
# Expected: { result: "primary" }
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## JOINs
|
|
44
|
+
|
|
45
|
+
**What to test:** Matching rows, non-matching rows, NULL join keys.
|
|
46
|
+
|
|
47
|
+
```yaml
|
|
48
|
+
# LEFT JOIN — matching row
|
|
49
|
+
orders: [{ order_id: 1, customer_id: 1 }]
|
|
50
|
+
customers: [{ customer_id: 1, name: "Alice" }]
|
|
51
|
+
# Expected: { order_id: 1, name: "Alice" }
|
|
52
|
+
|
|
53
|
+
# LEFT JOIN — no match (customer missing)
|
|
54
|
+
orders: [{ order_id: 2, customer_id: 99 }]
|
|
55
|
+
customers: [{ customer_id: 1, name: "Alice" }]
|
|
56
|
+
# Expected: { order_id: 2, name: null }
|
|
57
|
+
|
|
58
|
+
# JOIN with NULL key
|
|
59
|
+
orders: [{ order_id: 3, customer_id: null }]
|
|
60
|
+
customers: [{ customer_id: 1, name: "Alice" }]
|
|
61
|
+
# Expected: depends on join type
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
**Common bugs:**
|
|
65
|
+
- INNER JOIN drops rows when key is NULL or missing
|
|
66
|
+
- Fan-out: duplicate keys in right table multiply left rows
|
|
67
|
+
|
|
68
|
+
## Window Functions
|
|
69
|
+
|
|
70
|
+
**What to test:** Ordering, partitioning, boundary rows.
|
|
71
|
+
|
|
72
|
+
```yaml
|
|
73
|
+
# ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date)
|
|
74
|
+
- { customer_id: 1, order_date: "2024-01-01", amount: 50 }
|
|
75
|
+
- { customer_id: 1, order_date: "2024-01-15", amount: 75 }
|
|
76
|
+
- { customer_id: 2, order_date: "2024-01-10", amount: 30 }
|
|
77
|
+
# Expected:
|
|
78
|
+
# { customer_id: 1, order_date: "2024-01-01", row_num: 1 }
|
|
79
|
+
# { customer_id: 1, order_date: "2024-01-15", row_num: 2 }
|
|
80
|
+
# { customer_id: 2, order_date: "2024-01-10", row_num: 1 }
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
**What to test for LAG/LEAD:**
|
|
84
|
+
- First/last row in partition (LAG returns NULL for first row)
|
|
85
|
+
- Single-row partition
|
|
86
|
+
|
|
87
|
+
## Aggregations (GROUP BY)
|
|
88
|
+
|
|
89
|
+
**What to test:** Multiple groups, single group, empty group.
|
|
90
|
+
|
|
91
|
+
```yaml
|
|
92
|
+
# SUM(amount) GROUP BY customer_id
|
|
93
|
+
- { customer_id: 1, amount: 50 }
|
|
94
|
+
- { customer_id: 1, amount: 25 }
|
|
95
|
+
- { customer_id: 2, amount: 100 }
|
|
96
|
+
# Expected:
|
|
97
|
+
# { customer_id: 1, total_amount: 75 }
|
|
98
|
+
# { customer_id: 2, total_amount: 100 }
|
|
99
|
+
|
|
100
|
+
# Single row group
|
|
101
|
+
- { customer_id: 3, amount: 10 }
|
|
102
|
+
# Expected: { customer_id: 3, total_amount: 10 }
|
|
103
|
+
|
|
104
|
+
# NULL in aggregated column
|
|
105
|
+
- { customer_id: 4, amount: null }
|
|
106
|
+
# Expected: { customer_id: 4, total_amount: null } # SUM of NULLs = NULL
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Division
|
|
110
|
+
|
|
111
|
+
**What to test:** Normal, divide by zero, NULL.
|
|
112
|
+
|
|
113
|
+
```yaml
|
|
114
|
+
# amount / quantity
|
|
115
|
+
- { amount: 100, quantity: 4 }
|
|
116
|
+
# Expected: { unit_price: 25 }
|
|
117
|
+
|
|
118
|
+
# Divide by zero
|
|
119
|
+
- { amount: 100, quantity: 0 }
|
|
120
|
+
# Expected: depends — NULL, error, or COALESCE fallback?
|
|
121
|
+
|
|
122
|
+
# NULL divisor
|
|
123
|
+
- { amount: 100, quantity: null }
|
|
124
|
+
# Expected: { unit_price: null }
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Date/Timestamp Logic
|
|
128
|
+
|
|
129
|
+
**What to test:** Boundaries, NULL dates, timezone edge cases.
|
|
130
|
+
|
|
131
|
+
```yaml
|
|
132
|
+
# DATEDIFF or date filtering
|
|
133
|
+
- { event_date: "2024-01-01" } # start of year
|
|
134
|
+
- { event_date: "2024-12-31" } # end of year
|
|
135
|
+
- { event_date: "2024-02-29" } # leap year
|
|
136
|
+
- { event_date: null } # NULL date
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Type Coercion
|
|
140
|
+
|
|
141
|
+
**What to test:** Implicit casts that may fail.
|
|
142
|
+
|
|
143
|
+
```yaml
|
|
144
|
+
# String that looks like a number
|
|
145
|
+
- { amount_str: "100.50" } # CAST to DECIMAL
|
|
146
|
+
- { amount_str: "not_a_number" } # should this fail?
|
|
147
|
+
- { amount_str: "" } # empty string cast
|
|
148
|
+
- { amount_str: null } # NULL cast
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## Incremental Models
|
|
152
|
+
|
|
153
|
+
**What to test:** Full refresh vs incremental path.
|
|
154
|
+
|
|
155
|
+
```yaml
|
|
156
|
+
# Test 1: Full refresh (is_incremental = false, default)
|
|
157
|
+
# All rows processed
|
|
158
|
+
|
|
159
|
+
# Test 2: Incremental (is_incremental = true)
|
|
160
|
+
unit_tests:
|
|
161
|
+
- name: test_incremental_new_rows_only
|
|
162
|
+
model: fct_orders
|
|
163
|
+
overrides:
|
|
164
|
+
macros:
|
|
165
|
+
is_incremental: true
|
|
166
|
+
given:
|
|
167
|
+
- input: this # existing table state
|
|
168
|
+
rows:
|
|
169
|
+
- { order_id: 1, updated_at: "2024-01-14" }
|
|
170
|
+
- input: ref('stg_orders')
|
|
171
|
+
rows:
|
|
172
|
+
- { order_id: 1, updated_at: "2024-01-14" } # old, should be skipped
|
|
173
|
+
- { order_id: 2, updated_at: "2024-01-15" } # new, should be processed
|
|
174
|
+
expect:
|
|
175
|
+
rows:
|
|
176
|
+
- { order_id: 2, updated_at: "2024-01-15" }
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
## Empty Inputs
|
|
180
|
+
|
|
181
|
+
**What to test:** Model behavior when upstream has zero rows.
|
|
182
|
+
|
|
183
|
+
```yaml
|
|
184
|
+
given:
|
|
185
|
+
- input: ref('stg_orders')
|
|
186
|
+
rows: []
|
|
187
|
+
expect:
|
|
188
|
+
rows: [] # or specific default behavior
|
|
189
|
+
```
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# Testing Incremental dbt Models
|
|
2
|
+
|
|
3
|
+
Incremental models have two code paths controlled by `{% if is_incremental() %}`. Both paths must be tested.
|
|
4
|
+
|
|
5
|
+
## The Two Paths
|
|
6
|
+
|
|
7
|
+
```sql
|
|
8
|
+
SELECT * FROM {{ ref('stg_orders') }}
|
|
9
|
+
|
|
10
|
+
{% if is_incremental() %}
|
|
11
|
+
-- Incremental path: only process new rows
|
|
12
|
+
WHERE updated_at > (SELECT MAX(updated_at) FROM {{ this }})
|
|
13
|
+
{% endif %}
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Test 1: Full Refresh
|
|
17
|
+
|
|
18
|
+
```yaml
|
|
19
|
+
unit_tests:
|
|
20
|
+
- name: test_fct_orders_full_refresh
|
|
21
|
+
description: "Full refresh processes all rows"
|
|
22
|
+
model: fct_orders
|
|
23
|
+
# No overrides needed — is_incremental defaults to false
|
|
24
|
+
given:
|
|
25
|
+
- input: ref('stg_orders')
|
|
26
|
+
rows:
|
|
27
|
+
- { order_id: 1, amount: 100, updated_at: "2024-01-10" }
|
|
28
|
+
- { order_id: 2, amount: 200, updated_at: "2024-01-15" }
|
|
29
|
+
expect:
|
|
30
|
+
rows:
|
|
31
|
+
- { order_id: 1, amount: 100, updated_at: "2024-01-10" }
|
|
32
|
+
- { order_id: 2, amount: 200, updated_at: "2024-01-15" }
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Test 2: Incremental — New Rows Only
|
|
36
|
+
|
|
37
|
+
```yaml
|
|
38
|
+
unit_tests:
|
|
39
|
+
- name: test_fct_orders_incremental_new_only
|
|
40
|
+
description: "Incremental run only processes rows newer than existing max"
|
|
41
|
+
model: fct_orders
|
|
42
|
+
overrides:
|
|
43
|
+
macros:
|
|
44
|
+
is_incremental: true
|
|
45
|
+
given:
|
|
46
|
+
- input: this # mock the existing target table
|
|
47
|
+
rows:
|
|
48
|
+
- { order_id: 1, amount: 100, updated_at: "2024-01-10" }
|
|
49
|
+
- input: ref('stg_orders')
|
|
50
|
+
rows:
|
|
51
|
+
- { order_id: 1, amount: 100, updated_at: "2024-01-10" } # old
|
|
52
|
+
- { order_id: 2, amount: 200, updated_at: "2024-01-15" } # new
|
|
53
|
+
expect:
|
|
54
|
+
rows:
|
|
55
|
+
- { order_id: 2, amount: 200, updated_at: "2024-01-15" }
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Test 3: Incremental — Updated Rows
|
|
59
|
+
|
|
60
|
+
If your model uses `unique_key` for merge/upsert:
|
|
61
|
+
|
|
62
|
+
```yaml
|
|
63
|
+
unit_tests:
|
|
64
|
+
- name: test_fct_orders_incremental_update
|
|
65
|
+
description: "Updated rows are captured in incremental run"
|
|
66
|
+
model: fct_orders
|
|
67
|
+
overrides:
|
|
68
|
+
macros:
|
|
69
|
+
is_incremental: true
|
|
70
|
+
given:
|
|
71
|
+
- input: this
|
|
72
|
+
rows:
|
|
73
|
+
- { order_id: 1, amount: 100, updated_at: "2024-01-10" }
|
|
74
|
+
- input: ref('stg_orders')
|
|
75
|
+
rows:
|
|
76
|
+
- { order_id: 1, amount: 150, updated_at: "2024-01-15" } # updated
|
|
77
|
+
expect:
|
|
78
|
+
rows:
|
|
79
|
+
- { order_id: 1, amount: 150, updated_at: "2024-01-15" }
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Test 4: Incremental — Empty Source
|
|
83
|
+
|
|
84
|
+
```yaml
|
|
85
|
+
unit_tests:
|
|
86
|
+
- name: test_fct_orders_incremental_no_new_data
|
|
87
|
+
description: "No new rows when source has nothing newer"
|
|
88
|
+
model: fct_orders
|
|
89
|
+
overrides:
|
|
90
|
+
macros:
|
|
91
|
+
is_incremental: true
|
|
92
|
+
given:
|
|
93
|
+
- input: this
|
|
94
|
+
rows:
|
|
95
|
+
- { order_id: 1, amount: 100, updated_at: "2024-01-15" }
|
|
96
|
+
- input: ref('stg_orders')
|
|
97
|
+
rows:
|
|
98
|
+
- { order_id: 1, amount: 100, updated_at: "2024-01-10" } # older
|
|
99
|
+
expect:
|
|
100
|
+
rows: []
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Key Points
|
|
104
|
+
|
|
105
|
+
1. **Always mock `this`** when testing incremental path — it represents the existing target table
|
|
106
|
+
2. **Set `is_incremental: true`** in overrides.macros to activate the incremental code path
|
|
107
|
+
3. **Test both paths** — full refresh AND incremental
|
|
108
|
+
4. **Include overlap rows** — rows that exist in both `this` and source to verify filtering
|
|
109
|
+
5. **Test the merge key** — if `unique_key` is set, verify upsert behavior
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
# dbt Unit Test YAML Specification
|
|
2
|
+
|
|
3
|
+
Available in dbt-core 1.8+ (released mid-2024).
|
|
4
|
+
|
|
5
|
+
## Top-Level Structure
|
|
6
|
+
|
|
7
|
+
Unit tests are defined under the `unit_tests:` key in any YAML file within your dbt project (typically `schema.yml` or `_unit_tests.yml`).
|
|
8
|
+
|
|
9
|
+
```yaml
|
|
10
|
+
unit_tests:
|
|
11
|
+
- name: <test_name> # required, snake_case
|
|
12
|
+
description: <string> # optional but recommended
|
|
13
|
+
model: <model_name> # required, the model being tested
|
|
14
|
+
given: <list of inputs> # required, mock input data
|
|
15
|
+
expect: <expected output> # required, expected output rows
|
|
16
|
+
overrides: <overrides> # optional, macro/var overrides
|
|
17
|
+
config: <config> # optional, test configuration
|
|
18
|
+
tags: <list> # optional, for filtering
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Input Formats
|
|
22
|
+
|
|
23
|
+
### Dict Format (default, preferred)
|
|
24
|
+
|
|
25
|
+
```yaml
|
|
26
|
+
given:
|
|
27
|
+
- input: ref('stg_orders')
|
|
28
|
+
rows:
|
|
29
|
+
- { order_id: 1, amount: 100.00, status: "completed" }
|
|
30
|
+
- { order_id: 2, amount: null, status: "pending" }
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
**Rules:**
|
|
34
|
+
- Only include columns that the model actually uses
|
|
35
|
+
- Column names must match the upstream model exactly
|
|
36
|
+
- Use `null` for NULL values (not empty string)
|
|
37
|
+
- Dates as strings: `"2024-01-15"`
|
|
38
|
+
- Timestamps as strings: `"2024-01-15 10:30:00"`
|
|
39
|
+
- Booleans: `true` / `false`
|
|
40
|
+
- Numbers: no quotes (`100.00`, not `"100.00"`)
|
|
41
|
+
|
|
42
|
+
### SQL Format (required for ephemeral models)
|
|
43
|
+
|
|
44
|
+
```yaml
|
|
45
|
+
given:
|
|
46
|
+
- input: ref('ephemeral_model')
|
|
47
|
+
format: sql
|
|
48
|
+
rows: |
|
|
49
|
+
SELECT 1 AS id, 'test' AS name
|
|
50
|
+
UNION ALL
|
|
51
|
+
SELECT 2 AS id, 'other' AS name
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
**When to use SQL format:**
|
|
55
|
+
- Upstream model is materialized as `ephemeral`
|
|
56
|
+
- Complex data types that dict can't represent
|
|
57
|
+
- Need to use SQL functions in mock data
|
|
58
|
+
|
|
59
|
+
### Empty Input
|
|
60
|
+
|
|
61
|
+
```yaml
|
|
62
|
+
given:
|
|
63
|
+
- input: ref('stg_orders')
|
|
64
|
+
rows: []
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Tests behavior with no input rows (empty table).
|
|
68
|
+
|
|
69
|
+
## Expected Output
|
|
70
|
+
|
|
71
|
+
```yaml
|
|
72
|
+
expect:
|
|
73
|
+
rows:
|
|
74
|
+
- { order_id: 1, net_revenue: 85.00 }
|
|
75
|
+
- { order_id: 2, net_revenue: 50.00 }
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
**Rules:**
|
|
79
|
+
- Only include columns you want to assert on (subset is OK)
|
|
80
|
+
- Row order matters — rows are compared positionally
|
|
81
|
+
- Use exact values for numeric assertions
|
|
82
|
+
- `null` to assert NULL output
|
|
83
|
+
|
|
84
|
+
## Overrides
|
|
85
|
+
|
|
86
|
+
### Macro Overrides
|
|
87
|
+
|
|
88
|
+
```yaml
|
|
89
|
+
overrides:
|
|
90
|
+
macros:
|
|
91
|
+
is_incremental: true # boolean
|
|
92
|
+
current_timestamp: "2024-01-15 00:00:00" # string
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Common macros to override:
|
|
96
|
+
- `is_incremental` — test incremental vs full-refresh path
|
|
97
|
+
- `current_timestamp` / `current_date` — deterministic date testing
|
|
98
|
+
|
|
99
|
+
### Variable Overrides
|
|
100
|
+
|
|
101
|
+
```yaml
|
|
102
|
+
overrides:
|
|
103
|
+
vars:
|
|
104
|
+
run_date: "2024-01-15"
|
|
105
|
+
lookback_days: 30
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Input Sources
|
|
109
|
+
|
|
110
|
+
### ref() — Model references
|
|
111
|
+
|
|
112
|
+
```yaml
|
|
113
|
+
- input: ref('model_name')
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### source() — Source table references
|
|
117
|
+
|
|
118
|
+
```yaml
|
|
119
|
+
- input: source('source_name', 'table_name')
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### this — Self-reference for incremental models
|
|
123
|
+
|
|
124
|
+
```yaml
|
|
125
|
+
- input: this
|
|
126
|
+
rows:
|
|
127
|
+
- { order_id: 1, updated_at: "2024-01-14" }
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Used with `overrides.macros.is_incremental: true` to mock the existing table state.
|
|
131
|
+
|
|
132
|
+
## Configuration
|
|
133
|
+
|
|
134
|
+
Tags can be set at the top level (sibling of `config`) or nested under `config`:
|
|
135
|
+
|
|
136
|
+
```yaml
|
|
137
|
+
unit_tests:
|
|
138
|
+
- name: test_example
|
|
139
|
+
model: fct_orders
|
|
140
|
+
tags: ["unit-test", "revenue"]
|
|
141
|
+
# ... rest of test
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Or via config:
|
|
145
|
+
|
|
146
|
+
```yaml
|
|
147
|
+
unit_tests:
|
|
148
|
+
- name: test_example
|
|
149
|
+
model: fct_orders
|
|
150
|
+
config:
|
|
151
|
+
tags: ["unit-test", "revenue"]
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
## Naming Conventions
|
|
155
|
+
|
|
156
|
+
- Test names: `test_<model>_<what_it_tests>`
|
|
157
|
+
- Examples:
|
|
158
|
+
- `test_fct_orders_happy_path`
|
|
159
|
+
- `test_fct_orders_null_discount`
|
|
160
|
+
- `test_fct_orders_zero_quantity`
|
|
161
|
+
- `test_fct_orders_incremental_new_rows`
|
|
162
|
+
|
|
163
|
+
## Running Unit Tests
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
dbt test --select test_type:unit # all unit tests
|
|
167
|
+
dbt test --select test_type:unit,model_name:fct_orders # unit tests for one model
|
|
168
|
+
dbt build --select +fct_orders # build + all tests
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## Official Documentation
|
|
172
|
+
|
|
173
|
+
- https://docs.getdbt.com/docs/build/unit-tests
|
|
174
|
+
- https://docs.getdbt.com/reference/resource-properties/unit-tests
|