dbt-databricks icon indicating copy to clipboard operation
dbt-databricks copied to clipboard

dbt streaming_table fails on schema evolution while native streaming table works

Open adam-staros95 opened this issue 10 months ago • 10 comments

Describe the bug

Hi,

I’ve encountered an issue where refreshing streaming tables created with dbt (materialized='streaming_table') fail after initial creation when the source schema evolves. The same schema evolution works correctly when the streaming table is created outside of dbt using native Databricks SQL.

Steps To Reproduce

(A sample data.zip is attached)

  1. Create a dbt model people_streaming_dbt.sql with following definition :
{{
    config(
        catalog='<your_catalog>',
        schema='<your_schema>',
        alias='people_streaming_dbt',
        materialized='streaming_table'
    )
}}

select *, _metadata.*, current_timestamp() as _load_timestamp
from stream read_files(
    's3a://<bucket_name>/data/people/*/*/*/',
    format => 'json',
    multiLine => true
)
  1. Upload files from data/batch_1/01/ to the S3: <bucket_name>/data/people/2026/01/01/
  2. Create model using dbt run --select people_streaming_dbt --full-refresh

Right now table is created and queryable.

  1. Upload:
  • data/batch_2/02/ → <bucket_name>/data/people/2026/01/02/
  • data/batch_3/03/ → <bucket_name>/data/people/2026/01/03/ (these files introduce a new column: height)
  1. Run: dbt run --select people_streaming_dbt

❌ The model now fails with the incompatible schema error shown in logs below.

Screenshots and log output

After adding a new column to the source data, the dbt streaming table fails with a schema incompatibility error:

Database Error in model people_streaming_dbt (models/bronze/people_streaming_dbt.sql)
  Table 'people_streaming_dbt' has a user-specified schema that is incompatible with the schema
   inferred from its query.
  "
  Streaming tables are stateful and remember data that has already been
  processed. If you want to recompute the table from scratch, please full refresh
  the table.
                
  Declared schema:
  root
   |-- age: long (nullable = true)
   |-- id: long (nullable = true)
   |-- name: string (nullable = true)
   |-- _rescued_data: string (nullable = true)
   |-- file_path: string (nullable = true)
   |-- file_name: string (nullable = true)
   |-- file_size: long (nullable = true)
   |-- file_block_start: long (nullable = true)
   |-- file_block_length: long (nullable = true)
   |-- file_modification_time: timestamp (nullable = true)
   |-- _load_timestamp: timestamp (nullable = true)
  
  
  Inferred schema:
  root
   |-- age: long (nullable = true)
   |-- id: long (nullable = true)
   |-- name: string (nullable = true)
   |-- _rescued_data: string (nullable = true)
   |-- file_path: string (nullable = true)
   |-- file_name: string (nullable = true)
   |-- file_size: long (nullable = true)
   |-- file_block_start: long (nullable = true)
   |-- file_block_length: long (nullable = true)
   |-- file_modification_time: timestamp (nullable = true)
   |-- _load_timestamp: timestamp (nullable = true)
   |-- height: long (nullable = true)
  compiled code at target/run/ingestion/models/bronze/people_streaming_dbt.sql

Control Test (without dbt)

The same scenario works correctly when the streaming table is created natively in Databricks SQL:

  1. Upload files from data/batch_1/01/ to the S3: <bucket_name>/data/people/2026/01/01/
  2. Create the streaming table directly:
CREATE OR REFRESH STREAMING TABLE <catalog>.<schema>.people_streaming_non_dbt
AS
SELECT *, _metadata.*, current_timestamp() AS _load_timestamp
FROM STREAM read_files(
    's3a://<bucket_name>/data/people/*/*/*/',
    format => 'json',
    multiLine => true
);
  1. Upload:
  • data/batch_2/02/ → <bucket_name>/data/people/2026/01/02/
  • data/batch_3/03/ → <bucket_name>/data/people/2026/01/03/
  1. Execute:
REFRESH STREAMING TABLE <catalog>.<schema>.people_streaming_non_dbt;

✅ The refresh succeeds ✅ The new column height is automatically added ✅ Looking at _load_timestamp only new batches of data were processed during refresh (full refresh didn't occur)

Expected behavior

The streaming table should continue processing and automatically add the new column (height), consistent with Databricks streaming table behaviour outside of dbt.

System information

The output of dbt --version:

Core:
  - installed: 1.10.18
  - latest:    1.11.2  - Update available!

  Your version of dbt-core is out of date!
  You can find instructions for upgrading here:
  https://docs.getdbt.com/docs/installation

Plugins:
  - databricks: 1.11.0 - Update available!
  - redshift:   1.9.0  - Update available!
  - postgres:   1.9.0  - Update available!
  - spark:      1.9.2  - Update available!

  At least one plugin is out of date with dbt-core.
  You can find instructions for upgrading here:
  https://docs.getdbt.com/docs/installation

The operating system you're using: Apple M1 Pro / macOS Sequoia

The output of python --version: Python 3.12.4

Additional context

This is a dbt-specific issue. From inspection while creating dbt model materilized as streaming_table, dbt:

  • Create a temporary view with an explicit schema
  • Then use that view to create the streaming table while triggering lakeflow job running in the background

This extra indirection may cause the streaming table to “lock in” the initial schema, making it incompatible with schema evolution. This create temporary view step does not occur when creating streaming tables directly in Databricks SQL, where schema evolution works as expected.

Question: Is the temporary view step required for streaming table creation in dbt, and can it be avoided?

adam-staros95 avatar Jan 18 '26 12:01 adam-staros95

Additionally, based on my tests, creating streaming tables without dbt appears to have significantly better performance. In several cases, creating a streaming table over approximately 1.5 million source S3 json files containing ~80 million rows took about 2.5 hours with dbt, compared to about 50 minutes without dbt.

Moreover, when using dbt, some files were skipped during table creation, which resulted in approximately 3 million missing rows.

adam-staros95 avatar Jan 18 '26 13:01 adam-staros95

Draft PR: https://github.com/databricks/dbt-databricks/pull/1304

adam-staros95 avatar Jan 19 '26 19:01 adam-staros95

Additionally, based on my tests, creating streaming tables without dbt appears to have significantly better performance. In several cases, creating a streaming table over approximately 1.5 million source S3 json files containing ~80 million rows took about 2.5 hours with dbt, compared to about 50 minutes without dbt.

From the logs, where is the time being spent? Also, when you are creating a streaming table in Databricks, are you creating via DBSQL or via the DLT interface? The overhead of dbt should be on the order of a few seconds, not hours. However, dbt can only create via the DBSQL api, which could have substantial overhead. If it does, I think the solution for that is for us to raise a ticket internally to investigate.

What you are removing in your PR removes constraints on streaming tables as a feature, so we are unlikely to merge as is.

benc-db avatar Jan 21 '26 20:01 benc-db

@sd-db for visibility

benc-db avatar Jan 21 '26 20:01 benc-db

I’m using DBSQL. Based on my tests, creating a temporary view before creating the actual streaming table in a dbt streaming_table model takes approximately the same amount of time as creating the final streaming table in DBSQL. This already introduces a significant overhead.

Moreover, creating the streaming table after the temporary view is in place is also noticeably slower. Please run the scenario I described—you should see the difference even on this very small dataset.

Regarding your concern about constraint - I know your intention, that's why I marked PR as draft. However:

  1. Current implementation don't work, I tested it and constraints weren't applied to the created streaming table
  2. Looking at docs - https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-ddl-create-streaming-table creating temp view is definitely not required to apply constraints on streaming table

I will try to add support for streaming_table constraints, but this may slip to next week or later. After that, I’ll mark the PR as ready.

adam-staros95 avatar Jan 21 '26 22:01 adam-staros95

The temp view is so that we can get the column types, without which we can't specify column constraints at create time :/

benc-db avatar Jan 21 '26 22:01 benc-db

Hi,

Sorry it took so long.

Regarding the statement that “temp view is so that we can get the column types” — I don’t think this is accurate. I tested how dbt-databricks behaves, and the only way to add constraints (even for models materialized as table) is to update the model configuration with:

    config:
      contract:
        enforced: true

This configuration forces the user to explicitly specify column types. Without them, the following compile-time error occurs:Contracted models require data_type to be defined for each column. Please ensure that the column name and data_type are defined within the YAML configuration for the ['id'] column(s).

To test it: (Use data.zip from bug description)

  1. Create a dbt model people_dbt.sql with following definition:
{{
    config(
        catalog='<your_catalog>',
        schema='<your_schema>',
        alias='people_dbt',
        materialized='table' # Note it is not streaming table now!
    )
}}

select id
from read_files(
    's3a://<bucket_name>/data/people/*/*/*/',
    format => 'json',
    multiLine => true
)
  1. Upload files from data/batch_1/01/ to the S3: <bucket_name>/data/people/2026/01/01/
  2. Create model using dbt run --select people_dbt --full-refresh

At this point, the table is created and queryable. Now let’s try to add constraints.

Option A:

version: 2
models:
  - name: people_dbt
    columns:
      - name: id
        constraints:
          - type: primary_key
          - type: not_null

(re-execute dbt run --select people_dbt --full-refresh)

🟡 This “works” in the sense that the table is created, but no constraints are added.

Option B:

version: 2
models:
  - name: people_dbt
    config:
      contract:
        enforced: true
    columns:
      - name: id
        constraints:
          - type: primary_key
          - type: not_null

(re-execute dbt run --select people_dbt --full-refresh) ❌ The model now fails at compile time with: Contracted models require data_type to be defined for each column. Please ensure that the column name and data_type are defined within the YAML configuration for the ['id'] column(s).

Option C (the only working one):

version: 2
models:
  - name: people_dbt
    config:
      contract:
        enforced: true
    columns:
      - name: id
      - data_type: bigint
        constraints:
          - type: primary_key
          - type: not_null

(re-execute dbt run --select people_dbt --full-refresh) ✅ Model is created and constraints are correctly added.

Important note: Based on my tests with dbt-databricks==1.11.4, constraints are not added at all for models materialized as streaming_table, regardless of how the YAML configuration is defined.

What I observe so far:

  • Creating a temp view before creating a streaming table

    • Causes streaming table models defined as select * to fail when the source schema changes (this breaks schema evolution, which is critical for bronze layer streaming tables)
    • Degrades model performance
    • Generates additional SQL Warehouse costs
  • Creating a temp view with limit before creating a streaming table

    • Has the same issues as above
    • Additionally, limiting data in the temp view caused streaming table models to fail at creation time (bug reported here: https://github.com/databricks/dbt-databricks/issues/1235)
  • Table and column constraints do not work for streaming_table with the current implementation

  • Executing create temp view or a select statement just to get column types is not required to add constraints, because users must explicitly provide column data types when constraints are enforced

adam-staros95 avatar Feb 10 '26 15:02 adam-staros95

I spent some time trying to improve the current implementation, and for now I have following code in: dbt/include/databricks/macros/relations/streaming_table/create.sql:

{% macro get_create_streaming_table_as_sql(relation, sql) -%}
  {{ adapter.dispatch('get_create_streaming_table_as_sql', 'dbt')(relation, sql) }}
{%- endmacro %}

{% macro get_column_specs(model_columns) -%}
  {%- for col_name, col in model_columns.items() -%}
    {%- set constraints = col.get('constraints', []) -%}
    {%- if constraints and not col.get('data_type') -%}
      {{ exceptions.raise_compiler_error("Column '" ~ col_name ~ "' must have `data_type` provided when constraints are specified.") }}
    {%- endif -%}
    {%- set dtype = col.get('data_type') | lower -%}
    {%- set not_null = constraints | selectattr('type', 'equalto', 'not_null') | list | length > 0 -%}
    {%- set primary_key = constraints | selectattr('type', 'equalto', 'primary_key') | list | length > 0 -%}
    `{{ col_name }}` {{ dtype }}{%- if not_null %} NOT NULL{% endif %}{%- if primary_key %} PRIMARY KEY{% endif %}{%- if not loop.last %}, {% endif -%}
  {%- endfor -%}
{%- endmacro %}

{% macro databricks__get_create_streaming_table_as_sql(relation, sql) -%}
  {%- set streaming_table = adapter.get_config_from_model(config.model) -%}
  {%- set partition_by = streaming_table.config["partition_by"].partition_by -%}
  {%- set tblproperties = streaming_table.config["tblproperties"].tblproperties -%}
  {%- set comment = streaming_table.config["comment"].comment -%}
  {%- set refresh = streaming_table.config["refresh"] -%}
  {%- set model_columns = model.get('columns', {}) -%}

  CREATE STREAMING TABLE {{ relation.render() }}
  {%- if model_columns %}
    ({{ get_column_specs(model_columns) }})
  {%- endif %}
    {{ get_create_sql_partition_by(partition_by) }}
    {{ liquid_clustered_cols() }}
    {{ get_create_sql_comment(comment) }}
    {{ get_create_sql_tblproperties(tblproperties) }}
    {{ get_create_sql_refresh_schedule(refresh.cron, refresh.time_zone_value) }}
    AS {{ sql }}
{% endmacro %}

I haven’t committed this yet because:

  • The code currently works only for simple cases (primary key / not null constraints on columns)
  • This approach differs from how other materializations (table, materialized_view) are implemented

That said, this approach has several advantages:

  • If the user specifies constraints, they are correctly applied to the model
  • No SQL Warehouse resources are wasted on creating a temporary view
  • Model creation time is significantly reduced
  • If the user does not specify constraints and wants a bronze table that evolves with the source schema (select * from ...), schema evolution works as expected

@benc-db , please let me know what do you think?

adam-staros95 avatar Feb 10 '26 15:02 adam-staros95

Hi,

Just checking whether you had a chance to go through the reproduction steps I shared in the description and follow-up comments?

adam-staros95 avatar Feb 26 '26 21:02 adam-staros95

Hi @adam-staros95 I seemed to have missed this as I was off at that time. Let me take a look at get back. Thanks for the detailed issue description.

sd-db avatar Mar 10 '26 11:03 sd-db