This document shows you how to attach custom key-value labels to the
BigQuery query jobs that Dataform runs during workflow and
unit test executions. Job labels let you attribute BigQuery
compute usage, such as slot time and bytes billed, to cost centers, teams, or
environments without splitting pipelines across multiple projects.

## Storage labels versus job labels

Dataform supports two distinct types of BigQuery
labels:

- **Storage labels (`labels` or `bigquery.labels`)** : attach to the destination table, incremental table, or view resource in BigQuery through DDL `OPTIONS(labels=[...])`. Use storage labels to organize and filter tables and views. Table and view labels aren't included in Cloud Billing data. For more information about storage labels, see [Add BigQuery labels](https://docs.cloud.google.com/dataform/docs/create-tables.md.txt#labels).
- **Job labels (`defaultJobLabels` and `jobLabels`)** : attach to the BigQuery query jobs that Dataform submits when running workflow actions. Job labels appear in the [`INFORMATION_SCHEMA.JOBS`](https://docs.cloud.google.com/bigquery/docs/information-schema-jobs.md.txt) views and in [Cloud Billing usage exports](https://docs.cloud.google.com/billing/docs/how-to/export-data-bigquery.md.txt), where you can query compute usage per action or per repository.

> [!NOTE]
> **Note:** With capacity-based pricing, you can't attribute job costs by using job labels in Cloud Billing reports, because these costs are attributed at the reservation level. To apportion reservation costs, use `total_slot_ms` from the `INFORMATION_SCHEMA.JOBS` views. Attributing costs by job label in the Cloud Billing export applies to on-demand pricing.

Whether storage labels are also applied to BigQuery jobs depends
on where the workflow runs:

- When Dataform runs a workflow in Google Cloud, storage labels are never applied to BigQuery jobs.
- In the open-source Dataform CLI, when an action has no job labels, the CLI applies the table's storage `labels` to the BigQuery job. When an action has any job labels from `defaultJobLabels` or `jobLabels`, the CLI applies only those job labels and doesn't apply the table's storage `labels` to the job.

> [!CAUTION]
> **Caution:** If you use the Dataform CLI, adding `defaultJobLabels` stops storage labels from appearing on the jobs of every table that has storage labels. If you rely on storage labels on jobs, for example in dashboards, copy those keys into `defaultJobLabels` or `jobLabels`.

## Supported action types

The following table describes which Dataform action types receive
custom BigQuery job labels:

| Action type | Receives job labels | Notes |
|---|---|---|
| Table, view, incremental table, and materialized view | Yes | Built-in assertions configured in the table's `assertions` block inherit the table's resolved job labels. |
| Standalone assertion and custom SQL operations | Yes | Configured using `jobLabels` in SQLX, `actions.yaml`, or JavaScript. |
| Unit test | Yes | Applies to both actual-results and expected-results BigQuery query jobs. |
| Data preparation in a Dataform repository | Yes | Configured using `defaultJobLabels` or `jobLabels` on the `dataPreparation` entry in `actions.yaml`. |
| Property graph | Yes | Configured using `defaultJobLabels` or `job_labels` in `graph.yaml`. |
| Declaration | No | Declarations reference existing data sources and don't submit BigQuery jobs. |
| Notebook | No | Runs outside BigQuery query jobs. |

## Job label requirements and reserved keys

Dataform validates custom job labels during compilation before
any workflow actions run. If a label violates a validation rule, compilation
fails immediately with an error.

Custom job labels must meet [BigQuery label requirements](https://docs.cloud.google.com/bigquery/docs/labels-intro.md.txt#requirements)
and the following Dataform constraints:

| Rule | Constraint |
|---|---|
| Characters | Keys and values can contain only lowercase ASCII letters (`a-z`), digits (`0-9`), underscores (`_`), and hyphens (`-`). Keys must start with a lowercase ASCII letter. BigQuery also allows international characters, but Dataform doesn't. |
| Length | Keys must be 1-63 characters. Values can be 0-63 characters. Empty values are allowed. |
| Count limit | Each action can have at most 32 custom job labels after merging `defaultJobLabels` and `jobLabels`. |
| Reserved prefixes | Keys can't start with `dataform_`, `dataform-`, `dataprep-`, `gcp-`, or `goog-`. |
| Reserved keys | Keys can't match any of the following system keys: `bigquery-workflow`, `single-file-asset-type`, `origin`, `bq-dea`, or `data-preparation-file-loader`. These keys are reserved for repository labels that Dataform copies onto jobs. For more information, see [Identifying repositories for BigQuery assets](https://docs.cloud.google.com/dataform/docs/manage-repository.md.txt#repositories-for-assets). |

Numbers and booleans in YAML, JSON, or JavaScript configurations convert to
strings during compilation. Quote values that must keep leading zeros or exact
formatting, such as `"0042"`. A decimal value such as `1.5` converts to `"1.5"`
and fails validation, because periods aren't allowed.

> [!NOTE]
> **Note:** Don't include sensitive information in labels, including personally identifiable information, such as an individual's name or title. Labels are not designed to handle sensitive information.

### Label precedence

When you set both `defaultJobLabels` in `workflow_settings.yaml` and `jobLabels`
on an individual action, Dataform merges both maps for that
action in the following way:

1. Action-level `jobLabels` override matching keys from `defaultJobLabels`. An action can override the value of a default key, such as setting its value to `""`, but can't remove a key inherited from `defaultJobLabels`.
2. In the open-source Dataform CLI only, labels that you pass with `dataform run --job-labels` override matching keys from both `defaultJobLabels` and `jobLabels`.
3. Built-in assertions defined inside a table's `assertions` block inherit the resolved job labels of their parent table.
4. When Dataform runs a workflow in Google Cloud, it also attaches its own system labels, such as `dataform_workflow_execution_id` and `dataform_repository_id`, to every BigQuery job. These system keys don't count toward the 32-label custom limit. For the list of system labels, see [Correlate BigQuery jobs to workflow invocations](https://docs.cloud.google.com/dataform/docs/monitor-runs.md.txt#correlate-bigquery-audit-logs).

## Before you begin

1. In the Google Cloud console, go to the **Dataform** page.

   [Go to Dataform](https://console.cloud.google.com/bigquery/dataform)
2. Select or [create a repository](https://docs.cloud.google.com/dataform/docs/create-repository.md.txt).

3. Select or [create a development workspace](https://docs.cloud.google.com/dataform/docs/create-workspace.md.txt).

4. Update your repository to use Dataform core 3.1.3 or later in
   `workflow_settings.yaml`. For more information, see
   [Manage the Dataform core package](https://docs.cloud.google.com/dataform/docs/manage-repository.md.txt#manage-dataform-core-package).

### Required roles


To get the permissions that
you need to configure job labels in a workspace,

ask your administrator to grant you the
[Dataform Editor](https://docs.cloud.google.com/iam/docs/roles-permissions/dataform.md.txt#dataform.editor) (`roles/dataform.editor`) IAM role on the workspace.


For more information about granting roles, see [Manage access to projects, folders, and organizations](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access.md.txt).


You might also be able to get
the required permissions through [custom
roles](https://docs.cloud.google.com/iam/docs/creating-custom-roles) or other [predefined
roles](https://docs.cloud.google.com/iam/docs/roles-overview#predefined).

## Configure repository-wide default job labels

To attach the same BigQuery job labels to every supported action
in your repository, add `defaultJobLabels` to your `workflow_settings.yaml`
file.

Job labels are resolved when Dataform compiles your code.
Workflow invocations that use an existing compilation result keep their previous
labels until a new compilation result is created.

To configure repository-wide default job labels, follow these steps:

1. Go to your development workspace.
2. In the **Files** pane, open the `workflow_settings.yaml` file.
3. Keep your existing settings, and add the `defaultJobLabels` map in the
   following format:

   ```yaml
   defaultJobLabels:
     LABEL_KEY: "LABEL_VALUE"
   ```

   Replace the following:
   - `LABEL_KEY`: your job label key, such as `cost_center`.
   - `LABEL_VALUE`: your job label value, such as `marketing`.

   The file is automatically saved.

## Configure job labels for an individual action

To attach job labels to a specific action or override keys from
`defaultJobLabels`, set `jobLabels` in the action definition.

Job labels are resolved when Dataform compiles your code.
Workflow invocations that use an existing compilation result keep their previous
labels until a new compilation result is created.

To configure job labels for an individual action,
select one of the following options:

### SQLX

1. Go to your development workspace.
2. In the **Files** pane, expand `definitions/` and select a SQLX definition file (`table`, `view`, `incremental`, `assertion`, `operations`, or `test`).
3. In the `config` block, add `jobLabels`:

       config {
         type: "table",
         jobLabels: {
           LABEL_KEY: "LABEL_VALUE"
         }
       }

   Replace `LABEL_KEY` and
   `LABEL_VALUE` with your job label key and value.
4. Optional: Click **Format**.

The following SQLX example sets both compute `jobLabels` on the query job and
storage `bigquery.labels` on the destination table:

    config {
    type: "table",
    jobLabels: {
      cost_center: "finance",
      pipeline_tier: "gold"
    },
    bigquery: {
      labels: {
        table_owner: "analytics"
      }
    }
    }

    SELECT * FROM ${ref("orders")}

### actions.yaml

In an `actions.yaml` file inside `definitions/`, add `jobLabels` to an action
entry:

```yaml
actions:
  - table:
      name: finance_summary
      filename: finance_summary.sql
      jobLabels:
        cost_center: finance
        pipeline_tier: gold
```

To attach job labels to a data preparation, add `jobLabels` to its
`dataPreparation` entry:

```yaml
actions:
  - dataPreparation:
      filename: customers.dp.yaml
      jobLabels:
        cost_center: finance
```

### graph.yaml

To attach job labels to a property graph, keep your existing property graph
definition, and add `job_labels` at the top level of the `graph.yaml` file
inside `definitions/`:

```yaml
job_labels:
  cost_center: finance
```

### JavaScript

In a `.js` file inside `definitions/`, pass `jobLabels` in the action
configuration object or call `.jobLabels(...)` on a unit test:

```javascript
publish("finance_summary", {
  type: "table",
  jobLabels: {
    cost_center: "finance",
  },
}).query((ctx) => `SELECT * FROM ${ctx.ref("orders")}`);

test("finance_summary_test")
  .dataset("finance_summary")
  .jobLabels({ cost_center: "finance_qa" })
  .input("orders", "SELECT 1 AS id")
  .expect("SELECT 1 AS id");
```

## Label jobs by environment

To attribute BigQuery jobs to an environment, such as
development, staging, or production, use one of the following approaches:

- **Per action** : set an environment label in `jobLabels` on individual actions, as described in [Configure job labels for an individual action](https://docs.cloud.google.com/dataform/docs/label-bigquery-jobs.md.txt#configure-action-job-labels).
- **Per release configuration** : set the label value from a [compilation variable](https://docs.cloud.google.com/dataform/docs/manage-repository.md.txt#create-compilation-variables), for example `jobLabels: { env: dataform.projectConfig.vars.env }`. Define a default value for the variable in `vars` in the `workflow_settings.yaml` file, and override it in each [release configuration](https://docs.cloud.google.com/dataform/docs/configure-compilation.md.txt#create-release-configuration). You can use a compilation variable in SQLX and JavaScript definitions, but not in `actions.yaml` or `graph.yaml` files.
- **Per branch** : maintain a separate Git branch for each environment, and set a different value in `defaultJobLabels` in the `workflow_settings.yaml` file of each branch. Then [create a release configuration](https://docs.cloud.google.com/dataform/docs/configure-compilation.md.txt#create-release-configuration) for each branch.

You can't set `defaultJobLabels` in the compilation overrides of a release
configuration or a workspace.

## Query compute costs by job label

After you run a workflow invocation, BigQuery records your custom
job labels in `INFORMATION_SCHEMA.JOBS_BY_PROJECT` and
`INFORMATION_SCHEMA.JOBS_BY_ORGANIZATION` shortly after each job completes, and
propagates them to your
[Cloud Billing usage export](https://docs.cloud.google.com/billing/docs/how-to/export-data-bigquery.md.txt).
For information about when exported data becomes available, see
[Frequency of data loads](https://docs.cloud.google.com/billing/docs/how-to/export-data-bigquery-tables.md.txt#data-loads).

For the roles that you need to query these views, see the required roles for the
[`JOBS` view](https://docs.cloud.google.com/bigquery/docs/information-schema-jobs.md.txt#required_roles) and the
[`JOBS_BY_ORGANIZATION` view](https://docs.cloud.google.com/bigquery/docs/information-schema-jobs-by-organization.md.txt).

To aggregate bytes billed and slot usage by a custom job label such as
`cost_center`, run the following query in **BigQuery Studio**:

```sql
SELECT
  (SELECT value FROM UNNEST(labels) WHERE key = 'cost_center') AS cost_center,
  COUNT(DISTINCT IFNULL(parent_job_id, job_id)) AS job_count,
  SUM(total_bytes_billed) AS total_bytes_billed,
  SUM(total_slot_ms) AS total_slot_ms
FROM
  `region-LOCATION`.INFORMATION_SCHEMA.JOBS_BY_PROJECT
WHERE
  creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
  -- Parent script rows already include the totals of their child jobs.
  AND statement_type IS DISTINCT FROM 'SCRIPT'
  AND EXISTS (
    SELECT 1
    FROM UNNEST(labels)
    WHERE key = 'dataform_repository_id'
  )
GROUP BY
  cost_center
ORDER BY
  total_bytes_billed DESC;
```

Replace `LOCATION` with the BigQuery
location where your jobs ran, such as `us` or `eu`.

The `dataform_repository_id` filter matches only jobs that
Dataform runs in Google Cloud. To include jobs from the
open-source Dataform CLI, filter on one of your own job labels
instead.

To filter jobs for a single workflow invocation by combining custom job labels
with `dataform_workflow_execution_id`, see
[Correlate BigQuery jobs to workflow invocations](https://docs.cloud.google.com/dataform/docs/monitor-runs.md.txt#correlate-bigquery-audit-logs).

## What's next

- Learn how to [add storage labels to tables](https://docs.cloud.google.com/dataform/docs/create-tables.md.txt#labels).
- Learn how to [correlate BigQuery jobs to workflow invocations](https://docs.cloud.google.com/dataform/docs/monitor-runs.md.txt#correlate-bigquery-audit-logs).
- Learn how to [test data quality with unit tests](https://docs.cloud.google.com/dataform/docs/test-data.md.txt#unit-tests).
- Learn how to [configure workflow settings in `workflow_settings.yaml`](https://docs.cloud.google.com/dataform/docs/manage-repository.md.txt#configure-workflow-settings).
- View the [Dataform core reference](https://docs.cloud.google.com/dataform/docs/reference/dataform-core-reference.md.txt).