Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Heuristic:173TECH Sayn Two Pass Compilation

From Leeroopedia
Knowledge Sources
Domains Data_Engineering, Jinja2, Optimization
Last Updated 2026-10-17 00:00 GMT

Overview

SAYN compiles SQL templates in two passes — first to extract config metadata (sources, outputs, config macro overrides), then to produce the final SQL — enabling dynamic configuration from within Jinja2 templates.

Description

SAYN's SQL task compilation uses a two-pass approach. In the first pass, the Jinja2 `src()`, `out()`, and `config()` functions are replaced with lightweight dummy callbacks that record source/output references and capture config changes without producing real SQL. The template is rendered once to extract metadata (which tables are sources, which are outputs, and any config macro overrides like `materialisation` or `destination`). In the second pass, the same template is re-compiled with the real `src()` and `out()` functions that apply dev/prod name resolution, producing the final executable SQL.

The `allow_config` flag gates whether `config()` macro calls are honoured: it is `True` during the first pass and `False` during the second, preventing config changes from being applied twice. The `Prepared` class holds the compiled template between passes so it can be re-rendered without re-parsing.

Usage

Use this heuristic when writing SQL tasks that need to dynamically set `materialisation`, `destination`, `db`, or `tmp_schema` based on parameters. The `Template:Config(...)` macro inside a SQL file lets you override task config at compile time — but it only works during the first compilation pass. Understanding the two-pass model is essential for debugging why config changes don't take effect (e.g. a config call after a `Template:Src()` call may be too late).

The Insight (Rule of Thumb)

  • Action: Place `Template:Config(materialisation="incremental", ...)` calls early in the SQL template, ideally at the top, before any `Template:Src()` or `Template:Out()` calls.
  • Value: Config macro overrides are only honoured during the first pass; `src()` and `out()` dummy calls from the first pass are replayed with real resolution in the second pass.
  • Trade-off: The two-pass approach adds a compilation step but enables powerful dynamic configuration from within templates. Templates are rendered twice, so side effects (e.g. file writes in Jinja) would be dangerous.
  • Compatibility: Applies to SqlTask and all subclasses (CopyTask, AutoSqlTask). The `config()` macro accepts `materialisation`, `db`, `tmp_schema`, `destination`, `columns`, `table_properties`, `post_hook`, `delete_key`, `on_fail`, `tags`, `sources`, `outputs`, `parents`.

Reasoning

First-pass dummy callbacks in `SqlTask.config()` (`tasks/sql.py:153-161`):

# We compile first to allow changes to the config
# Template compilation
self.compiler.update_globals(
    src=lambda x, level=None: def_src(x, level=level),
    out=lambda x, level=None: def_out(x, level=level),
    config=self.config_macro,
)
self.allow_config = True

self.prepared_sql_query = self.compiler.prepare(self.task_config.file_name)
self.sql_query = self.prepared_sql_query.compile()

Config gating in `SqlTask.config_macro()` (`tasks/sql.py:279-280`):

def config_macro(self, **config):
    if self.allow_config:
        config.update(...)
        # ... apply overrides ...
    # Returns an empty string to avoid producing incorrect sql
    return ""

Second pass with real src/out in `SqlTask.config()` (`tasks/sql.py:235-249`):

# After the first compilation, config shouldn't be executed again
self.allow_config = False
...
self.compiler.update_globals(
    src=lambda x, level=None: self.src(x, connection=self._target_db, level=level),
    out=lambda x, level=None: self.out(x, connection=self._target_db, level=level),
    config=self.config_macro,
)
for s in def_connections_src:
    self.src(s[0], connection=self._target_db, level=s[1])
for o in def_connections_out:
    self.out(o[0], connection=self._target_db, level=o[1])

The `Prepared` class (`utils/compiler.py:113-124`) holds the template for re-compilation:

class Prepared:
    """A prepared statement ready to be compiled"""
    def __init__(self, compiler, template):
        self.compiler = compiler
        self.template = template
    def compile(self, **kwargs):
        return self.compiler.compile(self.template, **kwargs)

The `cache_size=0` setting in the Jinja2 environment (`utils/compiler.py:52`) ensures templates are not cached, which is critical for the two-pass model since globals change between passes:

return Environment(
    loader=FileSystemLoader(Path(".")),
    undefined=StrictUndefined,
    keep_trailing_newline=True,
    cache_size=0,
)

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment