Skill v1.0.2
currentAutomated scan100/1001 files
name: datajunction-repo description: | Activate this skill when authoring DataJunction (DJ) nodes via YAML files in a git repository — the repo-backed workflow. Covers YAML schemas per node type, branch-based development, temporal partitions on cubes, registering pre-aggregations / aggregate awareness, and the full PR-driven deployment flow. Keywords:
- YAML nodes, YAML definitions
- repo-backed namespace, repo-backed workflow
- git workflow, branch development, feature branch
- cube YAML, metric YAML, dimension YAML, transform YAML
- add a metric YAML file, add a dimension YAML file, add a cube YAML file
- temporal partition, partition pushdown
- pre-commit, push.sh
- pre-aggregation, pre-agg, preagg, kind: preagg
- aggregate awareness, aggregate navigation, query routing
- external pre-aggregation, externally-built aggregate, registered aggregate
- multiple tables for a metric, fact table and agg table, fact/agg hierarchy
- summary table, rollup table, agg table, materialized aggregate
- metrics map, dimensions map, column binding, valid_through_ts, availability
- freshness, join back, retained key
user-invocable: false metadata: version: "1.0.2"
DataJunction Repo-Backed Workflow
YAML-and-git authoring for DJ. Use this skill when working in a repo-backed namespace — node definitions are YAML files, changes go through PRs, CI/CD deploys.
For modeling decisions (whether to make something a metric, dim, or transform; how to decompose a query), see datajunction-semantic-model. This skill assumes the modeling decisions are made and you're translating them into YAML.
Overview
DataJunction supports repo-backed namespaces where node definitions are stored as YAML files in a git repository. This enables:
- ✅ Version control for your semantic layer
- ✅ Pull request review workflows for changes
- ✅ Branch-based development (feature branches, environments)
- ✅ Declarative configuration (infrastructure as code)
- ✅ Audit trail of all changes
- ✅ Team collaboration with code review
Repository Structure
There is no required layout under `nodes/`. DJ walks the tree recursively (rglob("nodes/**/*.yaml")) and takes the namespace from each YAML's name: field. The folder path is purely organizational. Files can be flat, nested by type, nested by domain, or any mix — DJ doesn't care, and reorganizing later is a free git mv.
That said, you should still choose a layout for your repo so contributors know where to add things. A few common patterns:
By node type (good when most contributors are adding metrics across one domain):
nodes/sources/transactions.yamldimensions/user.yamlmetrics/revenue.yamltransforms/clean_transactions.yamlcubes/revenue_cube.yaml
By domain (good when multiple teams/areas share one repo):
nodes/billing/sources/payments.yamltransforms/payment_events_clean.yamlmetrics/monthly_revenue.yamluser_events/transforms/sessions.yamlmetrics/dau.yaml
Flat (small projects, <30 nodes):
nodes/transactions.yamluser.yamlrevenue.yaml
Deciding on a layout
For an existing repo: look at the current nodes/ tree and match it. Consistency within a repo matters more than any specific scheme. Don't introduce a new style alongside an established one.
For a new repo: ask the user a few questions before committing to a layout:
- How many contributors / teams will use this repo?
- Roughly how many nodes do you expect (10? 100? 1000?)
- Are most nodes going to be metrics on top of a few shared transforms, or many independent fact/dim chains?
Defaults from those answers:
- 1 team + <30 nodes → flat is fine
- 1 team + larger → by node type
- Multiple teams → by domain, with optional type subdirs inside each domain folder when a domain itself grows past ~30 nodes
The right call almost never matters as much as it feels like it does — folder layout has zero effect on deployed namespaces, so optimize for "where would a new contributor look for X" and accept that you'll reorganize as the repo grows.
Branch-Based Development
Understanding Branch-Based Namespaces
When you create a branch in a repo-backed namespace, DJ creates a corresponding namespace that points to that branch.
Naming convention:
{namespace}.{branch_name}
Examples:
finance.main→ points tomainbranch of finance repofinance.feature-new-metrics→ points tofeature-new-metricsbranchfinance.staging→ points tostagingbranch
Creating a Feature Branch
Option A: Via DJ API
curl -b ~/.dj/cookies.txt -X POST $DJ_URL/namespaces/finance/branches \-H 'Content-Type: application/json' \-d '{"name": "feature-new-metrics","from_branch": "main"}'# This creates:# 1. Git branch: feature-new-metrics (from main)# 2. DJ namespace: finance.feature-new-metrics
Option B: Manually in Git
cd dj-finance/git checkout -b feature-new-metricsgit push origin feature-new-metrics# DJ may auto-discover branches
YAML Node Definitions
All node types can be defined as YAML files in the repository.
Column-Level Configuration
Column types are auto-inferred from queries
- DJ analyzes your SQL and automatically determines column types
- No need to manually specify types in the
columnssection
Use CAST() to control specific types
query: |SELECTCAST(user_id AS bigint) AS user_id,CAST(revenue AS decimal(18,2)) AS revenue,transaction_dateFROM finance.transactions
Column attributes
primary_key— Marks column as part of the primary keydimension— Marks column as available for grouping (transforms/facts only)
Optional column fields
display_name— Human-readable name for UI display
```yaml columns:
- name: ad_account_id
display_name: "Ad Account ID" attributes:
- dimension
```
Important constraints:
- ❌ SELECT * is NOT supported — always explicitly list columns
- ✅ Column order in YAML should match SELECT order
- ✅ Use descriptive display names for better UX
Source Node YAML
# nodes/sources/transactions.yamlname: finance.transactionsdescription: Raw transaction data from payment systemtype: sourcecatalog: prod_catalogschema_: financetable: transactions_tablecolumns:- name: transaction_iddisplay_name: "Transaction ID"attributes:- primary_key- name: user_iddisplay_name: "User ID"- name: amount_usddisplay_name: "Amount (USD)"- name: transaction_datedisplay_name: "Transaction Date"- name: statusdisplay_name: "Status"dimension_links:- type: joindimension_node: common.dimensions.usersjoin_type: leftjoin_on: finance.transactions.user_id = common.dimensions.users.user_id- type: joindimension_node: common.dimensions.datejoin_type: leftjoin_on: finance.transactions.transaction_date = common.dimensions.date.dateintmode: published
Notes:
- Column types are auto-inferred from the source table schema
display_nameprovides human-readable labels for UIjoin_typecan beleft,right, orinner(defaults toleft)
Dimension Node YAML
# nodes/dimensions/user.yamlname: finance.userdescription: User dimension with attributestype: dimensionquery: |SELECTuser_id,username,email,country_code,signup_date,tierFROM finance.usersprimary_key:- user_idcolumns:- name: user_iddisplay_name: "User ID"attributes:- primary_key- name: usernamedisplay_name: "Username"- name: emaildisplay_name: "Email Address"- name: country_codedisplay_name: "Country"- name: signup_datedisplay_name: "Signup Date"- name: tierdisplay_name: "User Tier"dimension_links:- type: joindimension_node: common.dimensions.datejoin_type: leftjoin_on: finance.user.signup_date = common.dimensions.date.dateint- type: joindimension_node: common.dimensions.countryjoin_type: leftjoin_on: finance.user.country_code = common.dimensions.country.country_codemode: published
Notes:
- Dimension node columns don't need
dimensionattribute (all are dimensions by nature) display_nameimproves readability in query builders and dashboards
Metric Node YAML
# nodes/metrics/revenue.yamlname: finance.total_revenuedescription: Total revenue from completed transactionstype: metricquery: |SELECTSUM(CASEWHEN status = 'completed' AND refund_flag = falseTHEN amount_usdELSE 0END) AS total_revenueFROM finance.transactionsrequired_dimensions:- common.dimensions.date.dateintmetric_metadata:direction: higher_is_betterunit: dollarowners:- data-platform-team@company.com- alice@company.commode: published
Important metric rules (see datajunction-semantic-model for full discussion):
- ✅ ALWAYS specify owners — critical for governance
- ❌ No WHERE clauses in metric queries (use CASE WHEN instead)
- ✅ Include required_dimensions for time-based metrics
- ✅ Add metric_metadata for direction and unit
- ✅ Use `required_filters` and `recommended_filters` to say which dimension attributes a query must or should filter. Give an entry a
defaultfilter if callers should not have to send one; without it, a query that omits the filter is rejected
Transform Node YAML
# nodes/transforms/clean_transactions.yamlname: finance.clean_transactionsdescription: Cleaned transaction data with standardized statustype: transformprimary_key:- transaction_idquery: |SELECTtransaction_id,user_id,amount_usd,transaction_date,CASEWHEN status IN ('complete', 'completed', 'success') THEN 'completed'WHEN status IN ('fail', 'failed', 'error') THEN 'failed'ELSE statusEND AS status_clean,refund_flagFROM finance.transactionscolumns:- name: transaction_iddisplay_name: "Transaction ID"attributes:- primary_key- name: user_iddisplay_name: "User ID"attributes:- dimension- name: amount_usddisplay_name: "Amount (USD)"- name: transaction_datedisplay_name: "Transaction Date"attributes:- dimension- name: status_cleandisplay_name: "Status"attributes:- dimension- name: refund_flagdisplay_name: "Refund Flag"attributes:- dimensiondimension_links:- type: joindimension_node: common.dimensions.usersjoin_type: leftjoin_on: finance.clean_transactions.user_id = common.dimensions.users.user_id- type: joindimension_node: common.dimensions.datejoin_type: leftjoin_on: finance.clean_transactions.transaction_date = common.dimensions.date.dateintmode: published
Notes:
primary_keyfield lists the primary key column(s)dimensionattribute marks columns available for grouping in metrics- Column types are auto-inferred from the query
- Columns without
dimensionattribute are typically measures/facts
Cube YAML
# cubes/revenue_cube.yamlname: finance.revenue_cubedescription: Pre-computed revenue metrics by date and regionmetrics:- finance.total_revenue- finance.avg_transaction_valuedimensions:- common.dimensions.date.dateint- common.dimensions.date.month- common.dimensions.users.country_codemode: published
When to use cubes:
- Frequently queried metric combinations
- Pre-compute for performance (materialization)
- Dashboard metric sets
Critical: All metrics in a cube MUST share ALL dimensions in the cube. Use get_common_dimensions MCP tool (see datajunction-query) to check first.
Temporal Partitions on Cubes
Temporal partitions enable automatic partition filtering for performance optimization. When configured, DJ automatically adds partition filters to SQL queries, dramatically improving query performance on large datasets.
How Partitions Work
A partition is always declared on a column. When that column is a dimension attribute on a cube, DJ uses it as the partition boundary and pushes the filter down to all upstream nodes that link to that same dimension.
Partition field format:
partition:type: temporal # or: categoricalgranularity: day # second, minute, hour, day, week, month, quarter, yearformat: yyyyMMdd # Java/Spark date format (e.g. yyyyMMdd → 20240101, yyyy-MM-dd → 2024-01-01)
Declaring a Partition on a Cube
In a cube, declare the partition in the `columns:` section using the full dimension attribute path as the column name:
# cubes/revenue_cube.yamlname: ${prefix}revenue_cubenode_type: cubemetrics:- ${prefix}total_revenue- ${prefix}order_countdimensions:- common.dimensions.date.dateint- common.dimensions.geo.country_codecolumns:- name: common.dimensions.date.dateint # ← must match exactly the entry in dimensionsdisplay_name: Dateattributes:- primary_keypartition:type: temporalgranularity: dayformat: yyyyMMdd
How Partition Filter Pushdown Works
Once a cube column has a partition spec, DJ:
- Generates SQL with
${dj_logical_timestamp}template variables wheninclude_temporal_filters=True - Pushes those filters down to all upstream nodes that link to the same dimension
- Reduces data scanned by limiting to relevant partitions
For filter pushdown to work, upstream nodes (sources, transforms) must have a dimension link to the same dimension:
# transforms/orders.yamldimension_links:- type: joindimension_node: common.dimensions.datejoin_type: leftjoin_on: ${prefix}orders.order_date = common.dimensions.date.dateint# ↑ DJ traces this link and pushes WHERE order_date >= X AND order_date <= Y
- ✅ Upstream node links to
common.dimensions.dateonorder_date→ DJ pushesWHERE order_date >= X AND order_date <= Y - ❌ Upstream node has no link to
common.dimensions.date→ no filter pushed, full table scan
Best Practices for Temporal Partitions
- Declare the partition on the cube's `columns:` block
- Use the full dimension attribute path as the column name (must match exactly what's in
dimensions:) - Without a
partition:declared on a cube column, DJ cannot enable partition filtering for that cube
- Ensure consistent dimension links across all nodes
- All upstream sources/transforms must link to the same dimension that carries the partition
- Use the same join key everywhere (e.g., always
dateint, not mixingdateintanddate_str)
- Use appropriate granularity and format
granularity: daywithformat: yyyyMMdd— for integer date partitions like20240101granularity: daywithformat: yyyy-MM-dd— for string date partitions like2024-01-01granularity: month,quarter,year— for coarser partitioning
- Verify partition filtering is working
- Use
build_metric_sql(datajunction-queryskill) withinclude_temporal_filters=True - Check generated SQL includes partition filters on upstream tables
- If filters are missing, check that upstream nodes have dimension links pointing to the partitioned dimension column
- Match the physical partition scheme of your warehouse
- The
formatmust match how partition values are actually stored in the table - Align granularity with how data is physically partitioned in storage
Example: Complete Temporal Partition Setup
The partition is declared on the cube's dateint column. DJ pushes the filter down to orders because it has a dimension link to common.dimensions.date.
Step 1: Transform with date dimension link
# transforms/orders.yamlname: ${prefix}ordersnode_type: transformcolumns:- name: order_date- name: product_id- name: order_count- name: total_revenuedimension_links:- type: joindimension_node: common.dimensions.time.datejoin_type: leftjoin_on: ${prefix}orders.order_date = common.dimensions.time.date.dateintquery: |SELECT product_id, order_date, COUNT(*) AS order_count, SUM(amount_usd) AS total_revenueFROM source.prod.orders_fGROUP BY product_id, order_date
Step 2: Metrics
# metrics/total_orders.yamlname: ${prefix}total_ordersnode_type: metricquery: SELECT SUM(order_count) FROM ${prefix}orders
Step 3: Cube — declare the partition on the external dimension attribute
# cubes/orders_cube.yamlname: ${prefix}orders_cubenode_type: cubemetrics:- ${prefix}total_ordersdimensions:- common.dimensions.time.date.dateint- ${prefix}orders.product_idcolumns:- name: common.dimensions.time.date.dateint # ← full attribute path, matches dimensions entrydisplay_name: Dateattributes:- primary_keypartition:type: temporalgranularity: dayformat: yyyyMMdd
Result: Queries with include_temporal_filters=True push WHERE order_date >= X AND order_date <= Y to the orders transform.
Pre-Aggregations / Aggregate Awareness
One concept, many names — all of these mean the same thing: aggregate awareness, aggregate navigation, query routing, pre-aggregations / pre-aggs, external or registered aggregates, multiple tables for a metric (a raw fact table plus coarser aggregates), summary tables, rollup tables, agg tables, materialized aggregates, fact/agg hierarchy, last-mile and intermediate aggregates.
A metric is defined once against its fact table; the same numbers often exist pre-summed in coarser tables. Register those tables and DJ picks per query which to read, falling back to the fact table when no aggregate can answer correctly.
The rules live in the docs, not here — see Query Routing & Aggregate Awareness for the kind: preagg schema (metrics and dimensions are maps from each reference to the physical column holding it), what makes a metric mappable, role-qualified dimension references, freshness reporting, and the current limitations. Read it before registering anything; the rules that decide whether your table actually gets used are not guessable.
The one thing to get right before you author metrics
A pre-agg's metrics map binds a metric to one column, so a metric decomposing into more than one component can never be bound to an aggregate — and its components are auto-named with a hash suffix that YAML cannot address. SUM(revenue) / COUNT(DISTINCT view_id) as a single node is unmappable forever; fixing it means refactoring a node other teams may already query.
So give every aggregation primitive its own metric node and compose ratios as derived metrics referencing them. Free if done from the start, expensive to retrofit, worth doing even before an aggregate table exists.
Repo-specific traps
Declare partitions in YAML, never through the API. A temporal partition on the parent's date column is what lets DJ reason about when an aggregate's data ends:
columns:- name: activity_datetype: intpartition:type: temporalgranularity: dayformat: yyyyMMdd
POST /nodes/{node}/columns/{col}/partition/ works, but the next deploy recreates the node from YAML and reverts it — and without a temporal partition column, freshness checks have no axis and silently do nothing.
A parent-node edit strands its aggregates. Registrations are keyed by node revision, so even a description-only change re-registers them at a new revision. A repo deploy re-creates the binding, but availability is not restored — until the pipeline re-reports it, the aggregate is unused and every query silently reverts to the fact table.
Complete Workflow Example
Scenario: Add a new metric to the finance namespace.
Step 1: Check if finance is repo-backed
Use MCP tool (datajunction-query):
get_node_details(name="finance.total_revenue")# Check the output for git repository info
Or via REST API:
curl -b ~/.dj/cookies.txt -X GET $DJ_URL/namespaces/finance/git
Step 2: Create feature branch
# Via DJ APIcurl -b ~/.dj/cookies.txt -X POST $DJ_URL/namespaces/finance/branches \-H 'Content-Type: application/json' \-d '{"name": "feature-add-churn-metric","from_branch": "main"}'# Creates namespace: finance.feature-add-churn-metric
Step 3: Clone repo and check out branch
git clone https://github.com/myorg/dj-finance.gitcd dj-financegit checkout feature-add-churn-metric
Step 4: Create metric YAML file
cat > nodes/metrics/churn_rate.yaml <<'EOF'name: finance.churn_ratedescription: Monthly user churn ratetype: metricquery: |SELECTCAST(SUM(CASE WHEN churned = true THEN 1 ELSE 0 END) AS DOUBLE) /NULLIF(COUNT(DISTINCT user_id), 0) AS churn_rateFROM finance.user_activityrequired_dimensions:- common.dimensions.date.monthmetric_metadata:direction: lower_is_betterunit: unitlessowners:- growth-analytics@company.commode: publishedEOF
Step 5: Commit and push
git add nodes/metrics/churn_rate.yamlgit commit -m "Add monthly churn rate metric"git push origin feature-add-churn-metric
Step 6: DJ syncs automatically
Use MCP tool to verify:
get_node_details(name="finance.churn_rate")
Step 7: Test in branch namespace
build_metric_sql(metrics=["finance.churn_rate"],dimensions=["common.dimensions.date.month"],filters=["common.dimensions.date.year = 2024"])
Step 8: Create PR for review
gh pr create \--title "Add monthly churn rate metric" \--body "Adds a new metric to track monthly user churn rate" \--base main
Step 9: Get review, merge PR
gh pr merge --squash
Step 10: Changes sync to production — metric now available in finance.main namespace.
Best Practices for Repo Authoring
Column
- ✅ Always explicitly list columns (SELECT * not supported)
- ✅ Add
display_namefor better UX in query builders - ✅ Mark primary key columns with
primary_keyattribute - ✅ Mark groupable columns with
dimensionattribute (transforms/facts) - ✅ Use CAST() in query if you need specific types
- ✅ Column order in YAML should match SELECT order
Cube
- ✅ Use
get_common_dimensionsMCP tool (datajunction-query) to check compatibility first - ✅ Only use shared dimensions
- ✅ Use for frequently queried combinations
- ✅ Always set temporal partitions on cubes for performance
- ✅ Ensure all upstream nodes link to the same date dimension
- ✅ Match granularity to physical partition scheme in data warehouse
- ✅ Verify partition filters in generated SQL
Workflow
- Always create feature branches — never commit directly to default branch
- Use descriptive branch names —
feature-add-revenue-metricsnotfix-stuff - Write clear commit messages — explain the "why" not just the "what"
- Keep PRs focused — one logical change per PR
- Test in branch namespace — validate metrics work before merging
- Use draft mode first — set
mode: draftwhile developing,publishedwhen ready - Document in YAML — use
descriptionfields thoroughly - Assign ownership — ideally teams rather than individuals for continuity