4: Troubleshooting and optimizing dbt pipelines

    Troubleshooting DAG failure points

    A dbt project is a directed acyclic graph of models, snapshots, seeds, sources, exposures, and tests. When dbt build runs, the scheduler walks that graph node by node and assigns each node a status. Pipeline troubleshooting starts with the same question every time: which nodes failed, which nodes were skipped because a parent failed, which nodes succeeded but raised warnings, and which nodes never even entered the run because a selector excluded them. The answer to all four questions lives in target/run_results.json, which is written at the end of every invocation and refreshed at the end of every retry. Treat that file as the canonical record of the run.

    The CLI output of dbt build already groups results into four buckets: PASS, WARN, ERROR, and SKIP. The bucket assignment is not arbitrary. A PASS is a node whose adapter call returned cleanly. A WARN is a test that breached a threshold but had severity: warn configured. An ERROR is a node whose adapter raised an exception or whose test failure carried severity: error. A SKIP is a node whose parent failed with error, which is the failure-propagation rule that distinguishes DAG-level failures from isolated node failures. A run with five ERROR nodes and forty SKIP nodes does not have forty-five bugs; it has at most five, and the forty skips will all resolve once the five errors are fixed.

    The run_results.json artifact records one entry per node attempted, each with a status, a message, an execution_time, the compiled_path, and a unique_id. Querying that file is how the experienced practitioner moves from the wall of red console output to a triage list. The five most common DAG failure patterns each have a recognizable signature in run_results.json, and recognizing them quickly is the difference between a one-hour fix and a four-hour one. The first pattern is a single upstream node failure that fans out into hundreds of skips, where the right action is to repair the single source. The second is a contract-violation failure on a downstream model that surfaces a real upstream data change, where the right action is to repair the upstream model and revalidate the contract. The third is a tail-fan failure where one node late in the DAG depends on many parents and one of them is intermittently unavailable, where the right action is to retry rather than rebuild. The fourth is a saturation failure where the warehouse rejects queries because too many threads ran in parallel against a small warehouse, where the right action is to tune threads. The fifth is a snapshot or seed failure that breaks every downstream model because the snapshot anchored the slowly-changing dimension key, and the right action is to investigate the snapshot history before touching downstream code.

    Reading run_results.json and constructing the failure map

    The triage workflow begins by listing every node with status: "error" and every node with status: "skipped". The skipped nodes are noise during triage; the error nodes are the work. The simplest extraction uses dbt ls driven by the result: selector against the cached run_results.json from the previous run.

    dbt ls --select result:error+ --resource-type model
    dbt ls --select result:skipped --resource-type model
    dbt ls --select result:warn --resource-type test
    

    The + suffix on result:error+ extends the selection to every descendant of every failed node, which is the exact set that was skipped. Comparing the two outputs verifies that the skips have a known parent failure. Any skip without a failed ancestor in the previous run is a sign that the DAG topology changed between runs, which usually means a recent commit introduced a circular reference or removed a ref() and dbt selected a different execution order.

    # Re-run only the failed nodes and everything downstream of them
    dbt build --select result:error+ --defer --state ./prod-state
    
    # Inspect the run_results.json directly with jq
    cat target/run_results.json | jq '.results[] | select(.status == "error") | {unique_id, message, execution_time}'
    

    The combination of result:error+ and --defer --state is the standard recovery selector. It tells the scheduler to run only the failed nodes plus their descendants, and to use the previous successful build of every parent. The previous-state reference is what keeps the recovery cheap; without --defer, dbt would attempt to rebuild every parent of every selected node in the development schema.

    💡 Exam Trap: result:error+ selects failed nodes plus their descendants. The plus sign on the right means downstream, not upstream. To select failed nodes plus their parents (the inputs that fed the failure), use +result:error. Mixing the two directions in a recovery selector is a recurring exam scenario.

    dbt retry and the manifest.json contract

    dbt retry is the safest recovery command in the CLI. It reads target/run_results.json and re-runs only the nodes whose status was error or skipped in the previous invocation, preserving the original DAG topology. It does not re-evaluate selectors, it does not re-parse manifest changes, and it does not pick up new commits. The contract is strict: the project on disk must match the project that produced the previous run_results.json. If the manifest has changed (a model was added, a ref() rewritten, a dbt_project.yml config edited), dbt retry will refuse to run and recommend a fresh invocation.

    That strictness is the point. dbt retry is built for the case where a flaky warehouse, a credential refresh, or a transient network issue knocked out a subset of the DAG and the next correct action is to pick up exactly where the run left off. It is not built for the case where a code change is the suspected fix; that is what dbt build --select result:error+ is for, because the latter re-resolves the manifest against the current files.

    # After a failed dbt build, the simplest recovery
    dbt retry
    
    # Equivalent low-level invocation with full transparency
    dbt build --select result:error+ result:skipped
    

    The two commands above are not identical. dbt retry preserves the exact selector and flags from the previous run, including --full-refresh and --vars. The manual selector resets those flags. When the previous run was dbt build --full-refresh --select tag:nightly, the retry will continue to honor both, while the manual rebuild will rebuild the full DAG of failed nodes without honoring the original tag selector.

    # Inspecting run_results.json programmatically inside a CI step
    import json
    from pathlib import Path
    
    results = json.loads(Path("target/run_results.json").read_text())
    failures = [r for r in results["results"] if r["status"] == "error"]
    skips = [r for r in results["results"] if r["status"] == "skipped"]
    
    print(f"failed: {len(failures)}, skipped: {len(skips)}")
    for r in failures:
     print(f" {r['unique_id']}: {r['message'][:80]}")
    

    Failure-propagation rules and skip semantics

    A node is skipped when at least one of its ancestors in the current run ended with status: "error". The propagation is transitive: if A fails, B depends on A, and C depends on B, then B is skipped and C is skipped. The propagation also crosses resource types: if a snapshot fails, every model that selects from that snapshot is skipped, and every test that references that snapshot or its descendants is skipped. The propagation does not cross severity boundaries: a test failure with severity: warn is a WARN not an ERROR, so descendants are not skipped, while a test failure with severity: error is an ERROR and descendants of the tested model are skipped (when running under dbt build).

    The last point is what makes dbt build different from dbt run. Under dbt run, tests do not execute, so a downstream model never inherits a skip from a failing test. Under dbt build, tests execute in DAG order between their parents and their children, so a not_null test that fails on the staging model halts the marts model that depends on it. The exam tests the inversion of this rule regularly: dbt run will happily build a marts model on top of broken staging data, while dbt build will catch the problem at the test boundary.

    ⚠️ Anti-Pattern: Treating SKIP counts as failure counts in alerting. A pipeline that reports "47 errors and 312 skips" appears catastrophic but typically reflects one or two real failures that fanned out across the marts layer. Alerting that sums errors and skips will page on-call for every transient failure of a popular staging table. Alert on errors only, and report skips as a secondary count.

    Reading dbt.log and the --debug flag

    When the run_results.json message is uninformative (a generic DatabaseError without a vendor code, or an OperationalError without context), the next stop is logs/dbt.log. The CLI writes one log file per invocation by default, rotating older files. The structure is one line per event, prefixed with the timestamp, log level, and thread identifier. The --debug flag promotes every internal event to the file, including the rendered SQL of every adapter call and the full traceback of every exception. The output is verbose but it is the only artifact that shows the actual SQL the adapter sent and the actual response the warehouse returned.

    # Run with full debug logging written to logs/dbt.log
    dbt --debug build --select result:error+
    
    # Tail the log live while the build runs
    tail -f logs/dbt.log
    

    When triaging a fan-out failure, the most efficient pattern is to identify the single failed root in run_results.json, search dbt.log for that node's unique_id, and read the surrounding lines. The block before the error contains the compiled SQL, and the block after contains the adapter's response, including the warehouse error code, the message text, and the connection identifier. Cross-referencing the connection identifier against the warehouse query history then confirms that the failure was warehouse-side rather than dbt-side.

    Decision Anchor: which recovery command to choose

    Choose dbt retry when the failure was transient, the project state on disk has not changed since the previous run, and the only goal is to repeat the same work that failed. Choose dbt build --select result:error+ --defer --state ./prod-state when a code fix has been committed and the failed subtree must rebuild against production parents. Choose dbt build --select +result:error when the failure looks suspicious upstream and the parents must be re-evaluated alongside the failed nodes. Choose a full dbt build --full-refresh only when the incremental state itself is corrupted (a partial merge, a half-applied schema migration), because that command rebuilds every model from scratch.

    Pipeline failure topology

    💡 Exam Trap: A WARN does not propagate as a skip. If a marts model depends on a staging model whose not_null test has severity: warn, the marts model still runs even when the test reports failures. To halt the downstream build on a data-quality issue, the test must carry severity: error (the default).

    📊 Limit: dbt retry resumes from the most recent run_results.json only. If two consecutive runs failed and the second run truncated the first's results to write its own (any subsequent invocation that wrote target/run_results.json), the retry will pick up the second run's results and may miss work that was skipped in the first. Always retry against the immediately preceding run, not an older one.

    🎯 Scenario: A production dbt build reports 3 errors and 89 skips. The on-call engineer runs dbt ls --select result:error+, which lists 92 nodes. The numbers match: 3 failed roots plus 89 descendants. Two of the failures are on staging models that select from the same source, and the source's freshness check ran first and reported stale data. The third failure is a not_null test on a marts model whose parent staging model passed cleanly. The engineer fixes the freshness pipeline upstream, then runs dbt build --select result:error+ --defer --state ./prod-state to verify only the 3 roots plus their 89 descendants re-run; the third failure persists because the source data itself violates the contract, and the fix has to land in the upstream loader.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the dbt - Analytics Engineering Certification learning hub.