arXiv:2608.22551cs.DBAug 2026

Manuscript Offprint

arXiv:2608.22551

DAGSmith: Dependency-Aware Rewriting for dbt-Style SQL Pipelines

Jie Liu, Lin Ma, Barzan Mozafari

Jie Liu

jiezzliu@umich.edu

Computer Science and Engineering

University of Michigan, Ann Arbor

USA

Lin Ma

linmacse@umich.edu

Computer Science and Engineering

University of Michigan, Ann Arbor

USA

Barzan Mozafari

mozafari@umich.edu

Computer Science and Engineering

University of Michigan, Ann Arbor

USA

ABSTRACT

Modern analytics is increasingly organized as recurring SQL pipelines rather than isolated SQL statements. Tools such as dbt—which have gained extreme popularity in recent years—allow teams to write each transformation as SQL and make dependencies between transformations explicit, producing directed acyclic graphs (DAGs) with hundreds or thousands of interdependent SQL models. Existing techniques are not effective at optimizing these expensive pipelines. Traditional query optimizers and source-to-source query rewriters operate on one query at a time, while materialized-view selection and multi-query optimization address narrower forms of reuse. They do not directly exploit the pipeline-level information exposed by explicit dependencies: how intermediate results are consumed, which downstream outputs depend on each computation, where expensive work occurs relative to data reduction, which intermediate results are worth persisting, and how refresh schedules relate to the rate at which inputs change and outputs are consumed.

We introduce DAGSmith, to the best of our knowledge the first holistic dependency-aware source-to-source rewriting system for SQL pipeline DAGs. DAGSmith treats explicit dependencies as optimization signals. It analyzes each transformation together with its upstream inputs, downstream consumers, and position in the pipeline DAG, uses an LLM to propose pipeline-level refactorings, separates SQL generation and data-backed equivalence checks to reject unsafe rewrites, retunes persistence choices with a learned cost model, and selects a globally compatible set of rewrites that avoids conflicts across transformations. This enables dependency-edge simplification, non-local semantic reuse, downstream-aware pruning, pipeline-aware work placement, rewrite-materialization co-optimization, and frequency-aware optimization while keeping the pipeline executable by the same SQL engine and orchestration framework. Our extensive evaluation shows that, on the open-source Tuva dbt project, DAGSmith reduces elapsed time by 42.6% and warehouse compute cost by 67.7%; these reductions are 22.8%/83.0% larger than materialization-only tuning and 98.1%/348.3% larger than state-of-the-art single-query rewriting techniques.

1 INTRODUCTION

Rising SQL Complexity – SQL is no longer only a hand-written interface for individual analytical questions. It is increasingly the implementation language for recurring data products: governed dashboards, AI-ready feature tables, self-service BI datasets, and organization-wide reporting layers. At the same time, more SQL is produced by BI systems, code generators, and AI-assisted development tools rather than written from scratch. In fact, recent studies report that 70% of analytics professionals use AI for code development [9], and that BI-generated SQL contain extremely complex scalar expressions and relational operator trees [27]. This has created a major efficiency gap between the complexity of the SQL queries generated and what today's query optimizers are capable of effectively optimizing. Source-to-source query rewriting is the traditional way to narrow this gap: a rewriter transforms complex SQL into an equivalent form that the query optimizer is more likely to turn into an efficient plan. However, query rewriting has traditionally treated one SQL statement as the unit of optimization. Unfortunately, the effectiveness of this one-query-at-a-time approach is increasingly limited by a second trend: modern SQL is no longer produced and executed only as isolated statements, but as recurring transformation pipelines.

Rise of SQL Pipelines – Data teams are increasingly building large, recurring SQL pipelines. This growth is driven by complex business logic that must be computed repeatedly and reused consistently across governed dashboards, AI-ready feature tables, self-service BI datasets, compliance reports, and downstream applications. One of the most widely adopted tools for these workflows is dbt (the data build tool) [12], reported to be used by 50K+ data teams weekly across the world [8]. dbt lets teams write transformations as version-controlled SQL SELECT statements (called “models” in dbt, which we use interchangeably in this paper), declare dependencies among them, and compile the resulting graph into SQL jobs executed by a data warehouse. Figure 1 gives a toy example. A raw orders table feeds a cleaning transformation; the cleaned result feeds both a revenue table and a daily active-customer table. The SQL text explains each local transformation, while the edges explain how the transformations compose into a pipeline. This trend is much broader than dbt. SQLMesh [25], Dagster asset graphs [5], Airflow directed acyclic graphs [2], Prefect flows [20], Argo Workflows [3], Databricks Workflows [6], and medallion lakehouse pipelines [7] all represent recurring data transformations through explicit dependencies. In this paper, we target the SQL subset of this broader pattern, which we refer to as SQL pipeline DAG: a recurring directed acyclic graph whose nodes are SQL transformations or SQL-produced tables/views, and whose edges record that one node reads another node’s output.

Pipeline Optimization Gap – These pipeline DAGs often include hundreds or thousands of SQL transformations that reference one another. Their scale makes them difficult to optimize with techniques designed for a single SQL statement or a flat workload: inlining every referenced transformation into each downstream query would produce deeply nested SQL with tens or hundreds of layers whose size and complexity are well beyond what today's

Figure

Figure 1: A toy SQL pipeline DAG. Nodes are SQL transformations or SQL-produced tables (called “models” in dbt); edges show which transformation consumes another transformation’s output.

optimizers can even tackle. In particular, existing query rewriting techniques, whether traditional rule-based systems [29] or modern synthesis- or LLM-based techniques [10, 16, 24], rewrite one SQL statement at a time. This scope is useful for improving a standalone query, but it is too narrow for optimizations whose correctness or benefit depends on the surrounding pipeline, such as removing work no final output uses, reusing equivalent logic across separate transformations, or changing refresh frequency based on input changes and output consumption. Multi-query optimization techniques [21, 22] consider multiple queries together, but their classical goal is to share common scans, joins, or intermediate results across a batch of submitted queries. They do not generally rewrite a SQL pipeline by adding, removing, splitting, or merging transformations based on downstream demand and refresh behavior. Materialized-view selection [1, 13] chooses intermediate query results to precompute and rewrites future queries to read those precomputed results. This improves reuse when the relevant computation has already been identified, but it does not by itself determine that a pipeline should drop unused work, factor repeated logic written in different forms, move expensive operations after data reduction, or refresh different parts of the pipeline at different rates. Lastly, Workflow schedulers [2, 3, 5, 20] know dependencies, but usually optimize execution order, failure recovery, retries, or resource allocation rather than the SQL semantics of the transformations themselves.

Dependencies as Signals – Our key insight is that explicit dependencies are not merely execution constraints; they are signals that can be leveraged for optimization. In particular, a SQL pipeline DAG exposes six kinds of information that are hidden or much harder to recover when queries are optimized independently: (1) Edge semantics: producer-consumer edges reveal how one SQL transformation's output is used by later transformations; (2) Cross-graph redundancy: similar business logic can appear in distant parts of the graph, even when SQL text differs; (3) Downstream demand: downstream dependencies reveal which columns, joins, filters, and intermediate results can affect final outputs; (4) Operator placement: the graph reveals where expensive operations occur relative to data-reducing filters, projections, joins, and aggregations; (5) Rewrite-persistence coupling: unlike single-query rewriting, which is constrained to equivalent rewrites that are cheaper in isolation, pipeline rewriting can consider alternatives that produce additional reusable outputs and are therefore locally more expensive, as long as those outputs are materialized once and reused by enough downstream consumers; and (6) Refresh patterns: schedules and source update rates reveal how often inputs change and outputs are consumed.

Our Approach – In this paper, we introduce DAGSmith, the first (to the best of our knowledge) holistic, dependency-aware rewriting system for SQL pipeline DAGs. DAGSmith exploits the exposed dependency structure to perform six classes of optimization: (1) dependency-edge simplification: remove or simplify dependency edges whose purpose can be expressed more directly, while preserving final outputs; (2) non-local semantic reuse: factor repeated work into a shared computation across non-adjacent transformations; (3) downstream-aware pruning: remove work that is provably irrelevant to every final output; (4) pipeline-aware work placement: move expensive work after data-reducing steps as long as final outputs are not impacted; (5) rewrite-materialization co-optimization: decide when rewrite benefits are outweighed by materialization cost, and when materializing a rewritten result makes the rewrite worthwhile; and (6) frequency-aware optimization: align computation frequency with input-change rates and output-consumption rates, avoiding refreshes that do not impact consumers.

DAGSmith first analyzes compiled SQL and dependency edges to identify regions likely to contain these opportunities. It then leverages Large Language Models (LLMs) to reason over the relevant subgraph and propose concrete refactorings, but separates proposal, criticism, SQL generation, and data-backed equivalence checking so unsafe or counterproductive rewrites can be rejected before adoption. Adopted candidates are not evaluated in isolation: DAGSmith retunes persistence choices for each candidate using a learned cost model and an iterative local linearization procedure, then solves a global selection problem to choose a non-conflicting subset of rewrites. Finally, frequency information from source update rates and output demand reweights cost estimates, detects over-scheduled work, and generates splitting candidates when slow-changing logic is embedded in fast-refreshing transformations. The result is a rewritten, output-equivalent SQL pipeline that remains executable by the same SQL engine and orchestration framework, but is significantly more performant.

Contributions – This paper makes the following contributions:

(1) We formulate dependency-aware source-to-source rewriting for SQL pipeline DAGs. We present the first holistic approach to this problem (to the best of our knowledge) by identifying the pipeline-level signals exposed by explicit dependencies and the rewriting opportunities they enable: dependency-edge simplification, non-local semantic reuse, downstream-aware pruning, pipeline-aware work placement, rewrite-materialization co-optimization, and frequency-aware optimization.

(2) We present the design of DAGSmith, which combines structural graph analysis, LLM-guided refactoring, separated proposal, criticism, SQL generation, and data-backed equivalence checking, learned cost modeling, persistence tuning, frequency-aware scheduling, and global candidate selection.

(3) We conduct a comprehensive evaluation showing that, on the open-source Tuva dbt project, DAGSmith reduces elapsed time by 42.6% and warehouse compute cost by 67.7%; these reductions are 22.8%/83.0% larger than materialization-only tuning and 98.1%/348.3% larger than state-of-the-art single-query rewriting techniques.

The rest of the paper is organized as follows. Section 2 defines the setting and illustrates the opportunity space. Section 3 presents the design of DAGSmith. Section 4 presents our evaluation, Section 5 discusses prior work, and Section 6 concludes.

References (10)