Please keep the discussion on the mailing list rather than commenting on the wiki (wiki discussions get unwieldy fast).

Motivation

Every other catalog object kind has a programmatic entry point on TableEnvironment: createTable, createView, createModel. Materialized tables have exactly one method for materialized tables, which is listMaterializedTables(), but no way to define, alter or refresh one. Using executeSql() as a fallback mechanism also does not work today, because no refresh job, or workflow is created. Only ALTER ... AS, SUSPEND, RESUME and REFRESH fail explicitly, with UnsupportedOperationException.

The goal of this FLIP is to create an enjoyable experience for Table API users when working with materialized tables, whether building one from scratch or adopting an existing one.

Public Interfaces

The new API types MaterializedPipeline, MaterializedTable, MaterializedTableDescriptor, MaterializedTableEvolution, RefreshStrategy, CreateMode, and RefreshJob land in flink-table-api-java (org.apache.flink.table.api).

The StartMode factory additions extend an existing type in flink-table-common (org.apache.flink.table.catalog), which was introduced by FLIP-557.

RefreshStatus and RefreshMode are reused from CatalogMaterializedTable, rather than re-declaring them in flink-table-api-java, to avoid duplicate public enums and conversion.

The FLIP adds no new public SPI. The interfaces that execute materialized table operations and that reach existing refresh jobs are @Internal and are listed under Proposed Changes.

Table

This does not create a new class but extends the current Table.

@PublicEvolving
public interface Table extends Explainable<Table>, Executable {

    // ... existing methods ...

    /** Declares this query as the definition of a materialized table. */
    MaterializedPipeline materializeInto(String path);
    /**
    * Shorthand for a descriptor that sets only the freshness and uses
    * {@link RefreshStrategy#automatic()}. A freshness at or above
    * {@code materialized-table.refresh-mode.freshness-threshold} resolves to FULL,
    * which a plain {@link TableEnvironment} rejects.
    */
    MaterializedPipeline materializeInto(String path, Duration freshness);
    MaterializedPipeline materializeInto(String path, MaterializedTableDescriptor descriptor);
}

MaterializedTableDescriptor

The description of a materialized table. It does not extend TableDescriptor, whose only entry point is forConnector(). A materialized table must not require one, because the catalog owns its storage. If the catalog supplies none, a connector can still be defined via option(). Freshness and a refresh strategy mean nothing to createTable, and separate types stop a descriptor built for one from being passed to the other.

@PublicEvolving
public class MaterializedTableDescriptor {

    protected MaterializedTableDescriptor(MaterializedTableDescriptor descriptor);

    public static Builder newBuilder();

    public Optional<Schema> getSchema();
    public Map<String, String> getOptions();
    public Optional<TableDistribution> getDistribution();
    public List<String> getPartitionKeys();
    public Optional<String> getComment();
    public Optional<IntervalFreshness> getFreshness();
    public RefreshStrategy getRefreshStrategy(); // defaults to RefreshStrategy.automatic()
    public Optional<StartMode> getStartMode();   // empty: the default start mode applies

    public Builder toBuilder();

    @Override public boolean equals(Object o);
    @Override public int hashCode();
    @Override public String toString();

    @PublicEvolving
    public static class Builder {
        protected Builder();
        protected Builder(MaterializedTableDescriptor descriptor);

        public Builder schema(@Nullable Schema schema);
        public <T> Builder option(ConfigOption<T> configOption, T value);
        public Builder option(String key, String value);

        public Builder distributedBy(String... bucketKeys);
        public Builder distributedBy(int numberOfBuckets, String... bucketKeys);
        public Builder distributedByHash(String... bucketKeys);
        public Builder distributedByHash(int numberOfBuckets, String... bucketKeys);
        public Builder distributedByRange(String... bucketKeys);
        public Builder distributedByRange(int numberOfBuckets, String... bucketKeys);
        public Builder distributedInto(int numberOfBuckets);

        public Builder partitionedBy(String... partitionKeys);
        public Builder comment(@Nullable String comment);
        public Builder freshness(@Nullable IntervalFreshness freshness);
        public Builder freshness(Duration freshness);      // delegates to IntervalFreshness.fromDuration

        /**
        * The start mode of the refresh job a declaration starts. Equivalent to
        * {@code START_MODE = ...}. {@link MaterializedPipeline#execute(StartMode)}
        * overrides it for one call.
        */
        public Builder startMode(@Nullable StartMode startMode);

        public Builder refreshStrategy(RefreshStrategy refreshStrategy);
        /** Shorthand for {@code refreshStrategy(RefreshStrategy.continuous())}. */
        public Builder continuousRefresh();
        /** Shorthand for {@code refreshStrategy(RefreshStrategy.full())}. */
        public Builder fullRefresh();

        public MaterializedTableDescriptor build();
    }
}

Unlike TableDescriptor.toCatalogTable(), there is no toCatalogMaterializedTable(). A CatalogMaterializedTable needs the defining query and fields the engine derives when the declaration runs: the merged schema, the resolved refresh mode, the default freshness and start mode, and the refresh status. MaterializedTable.toDescriptor() covers the opposite direction.

RefreshStrategy

Equivalent of CatalogMaterializedTable.LogicalRefreshMode on the declaration side, with more fluent declaration options.

@PublicEvolving
public class RefreshStrategy {

    @PublicEvolving
    public enum Kind { AUTOMATIC, CONTINUOUS, FULL }

    /**
    * Let the engine choose, based on freshness. The default.
    *
    * <p> CONTINUOUS if the freshness is below
    * {@code materialized-table.refresh-mode.freshness-threshold} (default
    * 30 minutes), FULL otherwise.
    *
    * <p>FULL is currently not supported from a plain {@link TableEnvironment},
    * so a freshness at or above the threshold fails.
    */
    public static RefreshStrategy automatic();
    public static RefreshStrategy continuous();
    public static RefreshStrategy full();

    public Kind getKind();
    public String asSummaryString();
}

StartMode

This does not create a new class but extends the current StartMode, with some more fluent convenience methods. The Flink docs do not cover START_MODE yet, so FLIP-557 is the reference for its semantics.

@PublicEvolving
public class StartMode {

    // ... existing of(...) factories stay ...

    public static StartMode fromBeginning();
    public static StartMode fromNow();

    /**
    * Equivalent to {@code START_MODE = FROM_NOW(INTERVAL ...)}. The offset goes
    * back in time, the start position is the execution time minus
    * {@code offset}.
    *
    * <p>As in SQL, the offset must be positive. It must also be a whole number
    * of seconds.
    */
    public static StartMode fromNow(Duration offset);

    /**
    * Equivalent to {@code START_MODE = FROM_TIMESTAMP(TIMESTAMP '...')},
    * where the literal is the instant's date-time in UTC. As in SQL, the
    * result does not depend on {@code table.local-time-zone}.
    * {@code fromTimestamp(Instant.parse("2026-08-01T00:00:00Z"))}
    * equals {@code FROM_TIMESTAMP(TIMESTAMP '2026-08-01 00:00:00')} in
    * every session.
    */
    public static StartMode fromTimestamp(Instant timestamp);

    public static StartMode resumeOrFromBeginning();
    public static StartMode resumeOrFromNow();

    /**
    * Equivalent to {@code START_MODE = RESUME_OR_FROM_NOW(INTERVAL ...)}.
    * Without a position to resume from, it starts like
    * {@link #fromNow(Duration)}, {@code offset} back in time.
    */
    public static StartMode resumeOrFromNow(Duration offset);
    public static StartMode resumeOrFromTimestamp(Instant timestamp);
}

MaterializedPipeline

A pending declaration of one materialized table.

@PublicEvolving
public interface MaterializedPipeline extends Explainable<MaterializedPipeline> {

    /**
     * The fully qualified identifier this declaration will create or alter.
     *
     * <p>Resolved against the current catalog and database when the declaration
     * is built.
     */
    ObjectIdentifier getIdentifier();

    /**
     * Submits this declaration with {@link CreateMode#createOrAlter()} and the
     * default start mode ({@code materialized-table.default-start-mode}).
     *
     * <p>On an existing ACTIVATED continuous table, the refresh job is stopped
     * with a savepoint and a new one starts without state, also for an
     * identical declaration. The savepoint is only used to restart the
     * previous job if the new one fails to start.
     *
     * <p>On an existing SUSPENDED or FULL table, only the catalog entry changes.
     * A SUSPENDED table loses its savepoint, so the next
     * {@link MaterializedTable#resume()} starts without state.
     *
     * <p> Equivalent to {@code execute(CreateMode.createOrAlter())}.
     *
     * <p> Returns once the catalog entry is written and the new job has
     * been submitted.
    */
    MaterializedTable execute();

    /**
    * Submits this declaration with {@link CreateMode#createOrAlter()} and the
    * given start mode, which overrides the descriptor's. Equivalent to
    * {@code CREATE OR ALTER MATERIALIZED TABLE ... START_MODE = ...}.
    *
    * <p>The start mode applies to the refresh job this call starts. It is
    * recorded with the definition and replaced by the next declaration. A
    * declaration without a start mode records the default start mode.
    */
    MaterializedTable execute(StartMode startMode);

    /**
    * Submits this declaration in the given mode, with the default start mode.
    */
    MaterializedTable execute(CreateMode mode);

    /**
    * Submits this declaration in the given mode, with the given start mode,
    * which overrides the descriptor's. Equivalent to
    * {@code CREATE [OR ALTER] MATERIALIZED TABLE ... START_MODE = ...}.
    * The start mode is recorded as for {@link #execute(StartMode)}.
    */
    MaterializedTable execute(CreateMode mode, StartMode startMode);
}

Unlike TablePipeline, MaterializedPipeline implements neither Executable nor Compilable. Its execute() creates a durable, stateful catalog object and returns a handle, not a TableResult, so implementing Executable would misrepresent the type. A CompiledPlan could hold the refresh query, but not the catalog operation around it, which creates the table with its schema, freshness, start mode and refresh strategy.

CreateMode

Gives the possibility to control the execution of a materialized table query client side.

@PublicEvolving
public class CreateMode {

    @PublicEvolving
    public enum Kind { CREATE_OR_ALTER, FAIL_IF_EXISTS }

    /**
    * Create the materialized table, or alter an existing one to this
    * declaration. The default.
    *
    * <p>The freshness, comment and partition keys of an existing materialized
    * table are not changed. A declaration with other values is not rejected.
    * They are ignored, and the table keeps its current ones.
    *
    * <p>The refresh mode is not changed either. A declaration with
    * {@link RefreshStrategy#continuous()} or {@link RefreshStrategy#full()}
    * that differs from the table's refresh mode is rejected with a
    * {@link ValidationException}. With {@link RefreshStrategy#automatic()},
    * the refresh mode is not resolved again, so the table keeps its refresh mode.
    *
    * <p> Equivalent to CREATE OR ALTER MATERIALIZED TABLE.
    */
    public static CreateMode createOrAlter();

    /**
    * Create the materialized table. Fails with a {@link ValidationException}
    * if any object already exists at the path.
    *
    * <p> Equivalent to CREATE MATERIALIZED TABLE.
    */
    public static CreateMode failIfExists();

    public Kind getKind();
    public String asSummaryString();
}

MaterializedTable

A handle on an existing materialized table. It offers functionalities to read and inspect, to manage, and to alter it. MaterializedTable introduces a handle because it is the only Table API object with runtime state and behavior (a refresh job to suspend, resume, refresh). This is specific to materialized tables and not a general direction for views or models, which remain pure metadata.

@PublicEvolving
public interface MaterializedTable extends Explainable<MaterializedTable> {

    ObjectIdentifier getIdentifier();

    // --- reading -------------------------------------------------------------

    /**
    * Reads this table's storage, as {@link TableEnvironment#from(String)} does
    * with {@link #getIdentifier()}. Use it to query the table or to build
    * downstream tables on it.
    */
    Table toTable();

    /**
     * The query that defines this table, for deriving a modified
     * definition.
     */
    Table toQuery();

    /**
     * This table's current definition as a descriptor.
     *
     * <p>Reflects the resolved current state.
     */
    MaterializedTableDescriptor toDescriptor();

    /**
     * ACTIVATED, SUSPENDED or INITIALIZING.
     *
     * <p> This is catalog state: ACTIVATED means a refresh job was submitted,
     * not that it is running. Use {@link #getRefreshJob()} for the job's state.
     */
    RefreshStatus getRefreshStatus();

    /**
    * Original text of the materialized table definition that preserves
    * the original formatting.
    */
    String getOriginalQuery();

    /**
    * Expanded text of the original materialized table definition with
    * resolved identifiers.
    */
    String getExpandedQuery();

    /**
    * The freshness in effect, which may differ from the declared one where
    * the engine normalises it.
    */
    IntervalFreshness getFreshness();

    /** CONTINUOUS or FULL. */
    RefreshMode getRefreshMode();

    /** Display-only summary of the scheduler handle behind a FULL-mode refresh. */
    Optional<String> getRefreshHandlerDescription();

    /**
     * The continuous refresh job, present if the table is CONTINUOUS and
     * ACTIVATED. A failed job is still returned, with status FAILED.
     * Empty for FULL.
     *
     * <p>Not limited to jobs this program submitted, a job started by another
     * program is reachable too.
     */
    Optional<RefreshJob> getRefreshJob();

    // --- altering --------------------------------------------------------------

    /**
     * Begins a targeted change to this table. Fields left unset are not touched.
     *
     * <p>Equivalent to {@code ALTER MATERIALIZED TABLE ...}.
     */
    MaterializedTableEvolution alter();

    // --- operating -----------------------------------------------------------

    /** Equivalent to ALTER MATERIALIZED TABLE ... SUSPEND. */
    void suspend();

    /**
    * Equivalent to ALTER MATERIALIZED TABLE ... RESUME [WITH (...)].
    *
    * <p>Returns once the refresh job has been submitted and the table is
    * recorded as ACTIVATED, not when the job is running. Use
    * {@link #getRefreshJob()} for the new job.
    */
    void resume();
    void resume(Map<String, String> dynamicOptions);

    /** Equivalent to ALTER MATERIALIZED TABLE ... REFRESH [PARTITION (...)]. */
    RefreshJob refresh();
    RefreshJob refresh(Map<String, String> partitionSpec);

    /** Equivalent to DROP MATERIALIZED TABLE [IF EXISTS]. */
    boolean drop();
    boolean drop(boolean ignoreIfNotExists);
}

The handle only holds the identifier. Every getter and every operation reads the catalog at call time, so a suspend(), alter or drop made elsewhere is visible on the next call. toQuery(), toDescriptor() and a RefreshJob are snapshots taken at the time of the call, and a RefreshJob stays bound to its job ID. toTable() resolves the table's schema at the time of the call, like from(path). Separate getter calls are not read atomically. Once the table is dropped, getIdentifier() keeps working, drop(true) returns false, and every other call fails with a ValidationException. If a new materialized table is later created at the same path, the handle addresses it.

MaterializedTableEvolution

A delta of the current declaration. Used when altering a materialized table in-place. Changes apply in call order.

@PublicEvolving
public interface MaterializedTableEvolution extends Explainable<MaterializedTableEvolution> {

    /**
    * Replaces the defining query. Equivalent to
    * ALTER MATERIALIZED TABLE ... AS <query>.
    *
    * <p>The new query must keep every persisted column with its name, position
    * and type. It may only append new columns, which are stored as nullable,
    * whatever nullability the query infers for them.
    */
    MaterializedTableEvolution query(Table query);

    /** Like {@link #query(Table)}, with the query as SQL text. */
    MaterializedTableEvolution query(String query);

    /**
    * Adds the columns, watermark and primary key declared in {@code schema}.
    * Fails if any of them already exists. New columns are appended.
    * Physical and persisted metadata columns come from the defining query
    * and cannot be added here.
    *
    * <p>Equivalent to ALTER MATERIALIZED TABLE ... ADD (...).
    */
    MaterializedTableEvolution addSchema(Schema schema);

    /**
    * Modifies the columns, watermark and primary key declared in {@code schema}.
    * Fails if any of them does not exist. A modified column keeps its position,
    * and its comment unless a new one is declared.
    *
    * <p>Equivalent to ALTER MATERIALIZED TABLE ... MODIFY (...).
    */
    MaterializedTableEvolution modifySchema(Schema schema);
    MaterializedTableEvolution dropColumns(String... fields);
    MaterializedTableEvolution dropWatermark();
    MaterializedTableEvolution dropPrimaryKey();
    MaterializedTableEvolution dropConstraint(String constraint);

    MaterializedTableEvolution option(String key, String value);
    <T> MaterializedTableEvolution option(ConfigOption<T> configOption, T value);
    MaterializedTableEvolution resetOption(String key);

    MaterializedTableEvolution distributedBy(String... bucketKeys);
    MaterializedTableEvolution distributedBy(int numberOfBuckets, String... bucketKeys);
    MaterializedTableEvolution distributedByHash(String... bucketKeys);
    MaterializedTableEvolution distributedByHash(int numberOfBuckets, String... bucketKeys);
    MaterializedTableEvolution distributedByRange(String... bucketKeys);
    MaterializedTableEvolution distributedByRange(int numberOfBuckets, String... bucketKeys);
    MaterializedTableEvolution distributedInto(int numberOfBuckets);
    MaterializedTableEvolution dropDistribution();

    /**
    * Applies all changes as one alter, with the same effect on the refresh
    * job and its savepoint as {@link MaterializedPipeline#execute()}. On an
    * ACTIVATED continuous table, one restart without state. The recorded
    * start mode is unchanged.
	*
    * <p>Changes apply in call order, each to the result of the earlier ones,
    * as if the equivalent ALTER statements ran one after another.
    *
    * <p>Returns once the catalog entry is written and, on an ACTIVATED continuous
    * table, the new refresh job has been submitted.
    */
    MaterializedTable execute();
}

RefreshJob

Returned by refresh() for the job just submitted, and by getRefreshJob() for the continuous one.

@PublicEvolving
public interface RefreshJob {

    /** The refresh job's id, or empty when the backend does not expose one. */
    Optional<JobID> getJobID();

    /**
    * Current status of the job. Fails if its cluster can't be reached or no
    * longer knows the job.
    */
    CompletableFuture<JobStatus> getJobStatus();

    /**
    * The cluster this job runs on: {@code execution.target} and, for YARN and
    * Kubernetes targets, the cluster ID ({@code yarn.application.id} or
    * {@code kubernetes.cluster-id}). For a continuous refresh job, these are the
    * values the catalog records. For a job returned by {@code refresh()}, they
    * are resolved at submission. Empty when the backend exposes none.
    */
    Map<String, String> getClusterInfo();

    /**
    * A client for the refresh job. Absent when the backend does not
    * expose one, or when the job has already been cleaned up. Stopping or
    * cancelling the job through this client bypasses the catalog. Use
    * {@link MaterializedTable#suspend()} or {@link MaterializedTable#drop()}
    * instead.
    */
    Optional<JobClient> getJobClient();

    /**
    * Blocks until the job reaches a terminal state; returns immediately if
    * it is already terminal.
    *
    * <p>For a continuous refresh job that means blocking until it is suspended
    * or fails.
    *
    * @throws ExecutionException if the job FAILED or was CANCELED, or if its
    * final status cannot be retrieved.
    * @throws InterruptedException if the waiting thread is interrupted. The job
    * is not affected.
    */
    void await() throws InterruptedException, ExecutionException;

    /**
    * Like {@link #await()}, bounded by the given timeout.
    *
    * @throws TimeoutException if the job is not terminal within the timeout.
    * The job is not affected.
    */
    void await(long timeout, TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException;
}

TableEnvironment

This does not create a new class but extends the current TableEnvironment.

@PublicEvolving
public interface TableEnvironment {

    // ... existing methods ...

    /** Returns a handle to an existing materialized table. */
    MaterializedTable fromMaterializedTable(String path);

    /** Namespace-scoped counterpart to the existing listMaterializedTables(). */
    String[] listMaterializedTables(String catalogName, String databaseName);

    /** Drops a materialized table by path. */
    boolean dropMaterializedTable(String path);
    boolean dropMaterializedTable(String path, boolean ignoreIfNotExists);
}

User Journeys

Set up a TableEnvironment

The shortest setup is a local session cluster, a persistent catalog that supports materialized tables, and a few options. The journeys use the test-filesystem catalog from the materialized table quickstart. Its jar goes in the cluster's lib/ and on the program's classpath. From an IDE, the program also needs flink-clients, flink-connector-files and flink-json.

# from a Flink distribution
cp flink-table-filesystem-test-utils-{VERSION}.jar lib/
./bin/start-cluster.sh   # REST endpoint at localhost:8081
public class MaterializedTableSetup {

    private static final String CATALOG_PATH = "/tmp/flink-mt-quickstart/catalog";
    private static final String SAVEPOINT_DIR = "file:///tmp/flink-mt-quickstart/savepoints";

    public static void main(String[] args) throws Exception {
        // The test-filesystem catalog fails to open if its path does not exist.
        Files.createDirectories(Paths.get(CATALOG_PATH, "my_db"));

        Configuration conf = new Configuration();
        // Refresh jobs must outlive this program, so they go to the session
        // cluster, not 'local'.
        conf.set(DeploymentOptions.TARGET, "remote");
        conf.set(RestOptions.ADDRESS, "localhost");
        conf.set(RestOptions.PORT, 8081);
        // A redeploy, alter() and suspend() stop the refresh job with a savepoint.
        // Only resume() restores it. After alter() or a redeploy, the new job
        // starts without state.
        conf.set(CheckpointingOptions.SAVEPOINT_DIRECTORY, SAVEPOINT_DIR);
        // For "Convert an existing table".
        conf.set(
          TableConfigOptions.MATERIALIZED_TABLE_CONVERSION_FROM_TABLE_ENABLED,
          true);

        TableEnvironment tEnv =
                TableEnvironment.create(
                        EnvironmentSettings.newInstance()
                                .inStreamingMode()
                                .withConfiguration(conf)
                                .build());

        // Create a persistent catalog
        tEnv.executeSql(
                "CREATE CATALOG my_catalog WITH ("
                        + "'type' = 'test-filesystem', "
                        + "'path' = '" + CATALOG_PATH + "', "
                        + "'default-database' = 'my_db')");
        tEnv.useCatalog("my_catalog");

        tEnv.createTable(
                "events",
                TableDescriptor.forConnector("test-filesystem")
                        .schema(Schema.newBuilder()
                                .column("ds", DataTypes.STRING())
                                .column("region", DataTypes.STRING())
                                .column("event_time", DataTypes.TIMESTAMP(3))
                                .column("amount", DataTypes.INT())
                                .column("fx_rate", DataTypes.DOUBLE())
                                .column("internal_flag", DataTypes.BOOLEAN())
                                .build())
                        .format("json")
                        .option("source.monitor-interval", "10s")
                        .build(),
                true);
    }
}

The journeys show storage options only where they are part of the example. Declarations without options, such as the minimal one, assume a catalog that supplies its own storage. On test-filesystem, add .option("format", "debezium-json"). Examples that declare a distribution need a connector that supports bucketing. Examples that read orders_raw assume a regular table with the columns order_id BIGINT NOT NULL, event_time TIMESTAMP(3) and amount DECIMAL(10, 2).

Journeys that declare silver with materializeInto(...) assume that no silver exists yet. Journeys that open it with fromMaterializedTable("silver") use the table declared at the start of "Change a materialized table you did not declare".

Create a materialized table

With minimal declaration

MaterializedTable silver = tEnv.from("events")
        .groupBy($("ds"), $("region"))
        .select($("ds"), $("region"), $("amount").sum().as("revenue"))
        .materializeInto("silver")
        .execute();

SQL equivalent:

CREATE OR ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver`
AS SELECT `ds`, `region`, SUM(`amount`) AS `revenue`
   FROM `my_catalog`.`my_db`.`events` GROUP BY `ds`, `region`;

With full declaration

MaterializedTable enriched = tEnv.from("events")
        .materializeInto("enriched_events", MaterializedTableDescriptor
                .newBuilder()
                .freshness(Duration.ofMinutes(1))
                .comment("events, kept fresh")
                .partitionedBy("ds")
                .option("format", "json")
                .continuousRefresh()
                .build())
        .execute(StartMode.fromNow());

SQL equivalent:

CREATE OR ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`enriched_events`
COMMENT 'events, kept fresh'
PARTITIONED BY (`ds`)
WITH ('format' = 'json')
START_MODE = FROM_NOW
FRESHNESS = INTERVAL '1' MINUTE
REFRESH_MODE = CONTINUOUS
AS SELECT ...;

With advanced declaration

A declared schema adds what the query cannot produce, e.g. a primary key, a watermark, computed columns.

MaterializedTableDescriptor descriptor = MaterializedTableDescriptor.newBuilder()
        .schema(Schema.newBuilder()
                .primaryKey("order_id")
                .columnByExpression("event_date", "CAST(`event_time` AS DATE)")
                .watermark("event_time", "`event_time` - INTERVAL '5' SECOND")
                .build())
        .distributedByHash(16, "order_id")
        .option(
                FileSystemConnectorOptions.SINK_ROLLING_POLICY_FILE_SIZE,
                MemorySize.ofMebiBytes(128))
        .freshness(IntervalFreshness.ofHour(1))
        .refreshStrategy(RefreshStrategy.continuous())
        .comment("curated orders, fresh within an hour")
        .startMode(StartMode.resumeOrFromTimestamp(Instant.parse("2026-08-01T00:00:00Z")))
        .build();

MaterializedTable orders = tEnv.from("orders_raw")
        .select($("order_id"), $("event_time"), $("amount"))
        .materializeInto("orders_curated", descriptor)
        .execute();

SQL equivalent:

CREATE OR ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`orders_curated` (
  `event_date` AS CAST(`event_time` AS DATE),
  WATERMARK FOR `event_time` AS `event_time` - INTERVAL '5' SECOND,
  PRIMARY KEY (`order_id`) NOT ENFORCED
)
COMMENT 'curated orders, fresh within an hour'
DISTRIBUTED BY HASH(`order_id`) INTO 16 BUCKETS
WITH ('sink.rolling-policy.file-size' = '128 mb')
START_MODE = RESUME_OR_FROM_TIMESTAMP(TIMESTAMP '2026-08-01 00:00:00')
FRESHNESS = INTERVAL '1' HOUR
REFRESH_MODE = CONTINUOUS
AS SELECT `order_id`, `event_time`, `amount` FROM `my_catalog`.`my_db`.`orders_raw`;

Convert an existing table into a materialized table

A regular table becomes a materialized table in place, as defined by FLIP-578. It keeps its path, its storage and the rows already in it. Everything else comes from the declaration, as for a new materialized table. A primary key or watermark it had must be declared again, and so must any option the catalog does not supply itself, e.g. a connector's topic or path. Conversion requires table.materialized-table.conversion-from-table.enabled.

As in the SQL Gateway, and unlike alter(), a failed conversion is not reverted. The conversion is written first. If the refresh job then can't be started, the table stays converted and SUSPENDED, and resume() starts the refresh job once the cause is fixed.

// `orders` already exists as a regular table:
//   CREATE TABLE orders (
//     order_id BIGINT NOT NULL, event_time TIMESTAMP(3), amount DECIMAL(10, 2),
//     PRIMARY KEY (order_id) NOT ENFORCED,
//     WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND
//   ) WITH ('connector' = 'test-filesystem', 'format' = 'json');
MaterializedTable orders = tEnv.from("orders_raw")
        .select($("order_id"), $("event_time"), $("amount"))
        .materializeInto("orders", MaterializedTableDescriptor.newBuilder()
                .schema(Schema.newBuilder()
                        .primaryKey("order_id")
                        .watermark("event_time", "`event_time` - INTERVAL '5' SECOND")
                        .build())
                .option("format", "json")
                .build())
        .execute();

SQL equivalent:

CREATE OR ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`orders` (
  PRIMARY KEY (`order_id`) NOT ENFORCED,
  WATERMARK FOR `event_time` AS `event_time` - INTERVAL '5' SECOND
)
WITH ('format' = 'json')
AS SELECT `order_id`, `event_time`, `amount` FROM `my_catalog`.`my_db`.`orders_raw`;

A conversion behaves as it does in the SQL Gateway. A FULL mode declaration is rejected before the catalog is changed. Otherwise the conversion is written first. If the refresh job then cannot be started, the table stays converted in SUSPENDED status. resume() starts the refresh job once the cause is fixed. Unlike alter(), a failed conversion is not reverted.

Build a layered pipeline

Bronze → silver → gold, each layer materialized on the one above, sharing one policy. The policy holds only what the tables share. It has no start mode, which would apply to all three tables on every redeploy, see Start Mode. Note the usage of toTable() here and not toQuery(). The latter would define each layer against events directly.

MaterializedTableDescriptor policy = MaterializedTableDescriptor
        .newBuilder()
        .freshness(Duration.ofMinutes(1))
        .continuousRefresh()
        .option("format", "debezium-json")
        .option("source.monitor-interval", "10s")
        .build();

MaterializedTable bronze = tEnv.from("events")
        .where($("amount").isGreater(0))
        .materializeInto("bronze", policy)
        .execute();

MaterializedTable silver = bronze.toTable()
        .groupBy($("ds"), $("region"))
        .select($("ds"), $("region"), $("amount").sum().as("revenue"))
        .materializeInto("silver", policy)
        .execute();

MaterializedTable gold = silver.toTable()
        .groupBy($("region"))
        .select($("region"), $("revenue").sum().as("revenue"))
        .materializeInto("gold", policy.toBuilder()
                .freshness(Duration.ofHours(1))
                .partitionedBy("region")
                .build())
        .execute();

SQL equivalent:

CREATE OR ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`bronze`
WITH (
  'format' = 'debezium-json',
  'source.monitor-interval' = '10s'
)
FRESHNESS = INTERVAL '1' MINUTE
REFRESH_MODE = CONTINUOUS
AS SELECT * FROM `my_catalog`.`my_db`.`events` WHERE `amount` > 0;

CREATE OR ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver`
WITH (
  'format' = 'debezium-json',
  'source.monitor-interval' = '10s'
)
FRESHNESS = INTERVAL '1' MINUTE
REFRESH_MODE = CONTINUOUS
AS SELECT `ds`, `region`, SUM(`amount`) AS `revenue`
   FROM `my_catalog`.`my_db`.`bronze` GROUP BY `ds`, `region`;

CREATE OR ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`gold`
PARTITIONED BY (`region`)
WITH (
  'format' = 'debezium-json',
  'source.monitor-interval' = '10s'
)
FRESHNESS = INTERVAL '1' HOUR
REFRESH_MODE = CONTINUOUS
AS SELECT `region`, SUM(`revenue`) AS `revenue`
   FROM `my_catalog`.`my_db`.`silver` GROUP BY `region`;

Redeploy on code change

Every run of this program restarts the refresh job of every continuous materialized table it declares, also when nothing changed. As with CREATE OR ALTER in the SQL Gateway, each restart starts without state, so a stateful query such as this GROUP BY recomputes from empty state and rows can be duplicated or missed. This includes every re-run of main(), e.g. after a failover of a program in application mode. Run the declarations only when they or their dependencies changed.

// Deploy N: the table does not exist yet. It is created and its refresh job
// starts, reading its sources per their startup options (see Start Mode).
// Deploy N+1: identical declaration. The definition is unchanged, but the
// refresh job is restarted without its state and reads its sources per their
// startup options.
tEnv.from("events")
        .groupBy($("ds"), $("region"))
        .select($("ds"), $("region"), $("amount").sum().as("revenue"))
        .materializeInto("silver")
        .execute();

// Deploy N+2: one column appended. COUNT returns BIGINT NOT NULL, but a column
// the query appends is stored as nullable, because rows written before this
// deploy have no value for it.
tEnv.from("events")
        .groupBy($("ds"), $("region"))
        .select($("ds"), $("region"), $("amount").sum().as("revenue"),
                $("amount").count().as("txn_count"))
        .materializeInto("silver")
        .execute(StartMode.fromBeginning());

SQL equivalent:

-- Deploy N and N+1: identical statement.
CREATE OR ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver`
AS SELECT `ds`, `region`, SUM(`amount`) AS `revenue`
   FROM `my_catalog`.`my_db`.`events` GROUP BY `ds`, `region`;

-- Deploy N+2: one column added, stored as nullable BIGINT.
CREATE OR ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver`
START_MODE = FROM_BEGINNING
AS SELECT `ds`, `region`, SUM(`amount`) AS `revenue`,
          COUNT(`amount`) AS `txn_count`
   FROM `my_catalog`.`my_db`.`events` GROUP BY `ds`, `region`;

Change a materialized table you did not declare

Given only the path of a materialized table, declared by another program or a SQL query. All three examples below start from the same table. This works fully for continuous tables whose refresh job runs on a session cluster the program can reach, if the program's execution.target matches the recorded one (see Restart target). FULL tables, and tables whose refresh job runs in an application cluster, can only partly be operated, see Operations that require the SQL Gateway and Limitations under Controlling refresh jobs from other programs.

SQL statement that created the materialized table:

CREATE OR ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver` (
  WATERMARK FOR `event_time` AS `event_time` - INTERVAL '5' SECOND
)
COMMENT 'revenue events, enriched'
PARTITIONED BY (`ds`)
WITH (
  'format' = 'json',
  'sink.parallelism' = '4',
  'sink.rolling-policy.file-size' = '128 mb'
)
AS SELECT `ds`, `region`, `event_time`, `internal_flag`, `amount`,
          `amount` * `fx_rate` AS `revenue`
   FROM `my_catalog`.`my_db`.`events`;

Adjusting the query

MaterializedTable silver = tEnv.fromMaterializedTable("silver");

// Using the table's defining query
silver.alter()
      .query(silver.toQuery()
              .where($("amount").isGreater(0))
              .addColumns($("revenue").times(0.8).as("net_revenue")))
      .execute();

// Using raw SQL
// Get the current query to inspect
LOG.info("Current defining query: {}", silver.getExpandedQuery());

String newQuery = "SELECT `ds`, `region`, `event_time`, `internal_flag`, " +
  "`amount`, `amount` * `fx_rate` AS `revenue`, `amount` * `fx_rate` * 0.8 " +
  "AS `net_revenue` FROM `my_catalog`.`my_db`.`events` WHERE `amount` > 0";
silver.alter()
      .query(newQuery)
      .execute();

SQL equivalent:

ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver`
AS SELECT `ds`, `region`, `event_time`, `internal_flag`, `amount`,
          `amount` * `fx_rate` AS `revenue`,
          `amount` * `fx_rate` * 0.8 AS `net_revenue`
   FROM `my_catalog`.`my_db`.`events`
   WHERE `amount` > 0;

Changing a parameter

tEnv.fromMaterializedTable("silver")
        .alter()
        .option(FileSystemConnectorOptions.SINK_ROLLING_POLICY_FILE_SIZE, MemorySize.ofMebiBytes(256))
        .execute();

SQL equivalent:

ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver` SET ('sink.rolling-policy.file-size' = '256 mb');

Adjusting almost everything

MaterializedTable silver = tEnv.fromMaterializedTable("silver");

silver.alter()
      .query(silver.toQuery().where($("amount").isGreater(0)))
      .modifySchema(Schema.newBuilder()
              .watermark("event_time", "`event_time` - INTERVAL '10' SECOND")
              .build())
      .addSchema(Schema.newBuilder()
              .columnByExpression("event_date", "CAST(`event_time` AS DATE)")
              .build())
      .option("sink.rolling-policy.file-size", "256 mb")
      .resetOption("sink.parallelism")
      .distributedByHash(32, "region")
      .execute();

SQL equivalent:

-- Applied by the Table API in this order, as one alter and one refresh-job restart, without state.
-- Run separately, every statement below restarts the refresh job.
ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver` AS SELECT ...;
ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver` MODIFY WATERMARK FOR `event_time` AS `event_time` - INTERVAL '10' SECOND;
ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver` ADD `event_date` AS CAST(`event_time` AS DATE);
ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver` SET ('sink.rolling-policy.file-size' = '256 mb');
ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver` RESET ('sink.parallelism');
ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver` ADD DISTRIBUTION BY HASH(`region`) INTO 32 BUCKETS;

The Table API applies all changes as one AlterMaterializedTableChangeOperation with the combined change list. The changes apply in call order, each to the result of the earlier ones, as the statements above do when run one after another. As in SQL, a query change that also changes columns is rejected when the schema has computed (non-persisted) columns.

Consume a materialized table

MaterializedTable silver = tEnv.fromMaterializedTable("silver");

// read from the table
silver.toTable()
        .where($("region").isEqual("EMEA"))
        .orderBy($("revenue").desc())
        .fetch(10)
        .execute()
        .print();

silver.printExplain();      // the refresh pipeline behind the table

// discover materialized tables and inspect them
for (String name : tEnv.listMaterializedTables("my_catalog", "my_db")) {
    MaterializedTable mt = tEnv.fromMaterializedTable(
      String.format("`my_catalog`.`my_db`.`%s`", name));
    LOG.info("{}: {}, freshness {}, mode {}\n  {}",
            name, mt.getRefreshStatus(), mt.getFreshness(),
            mt.getRefreshMode(), mt.getOriginalQuery());
}

SQL equivalent:

SELECT * FROM `my_catalog`.`my_db`.`silver`
WHERE `region` = 'EMEA' ORDER BY `revenue` DESC LIMIT 10;

-- discover and inspect; printExplain() has no counterpart here
SHOW MATERIALIZED TABLES FROM `my_catalog`.`my_db`;
SHOW CREATE MATERIALIZED TABLE `my_catalog`.`my_db`.`silver`;

Manage the lifecycle

MaterializedTable silver = tEnv.fromMaterializedTable("silver");

silver.suspend();
// ... upstream maintenance ...
silver.resume(Map.of("sink.parallelism", "2"));

silver.drop(true);

SQL equivalent:

ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver` SUSPEND;
ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver` RESUME
  WITH ('sink.parallelism' = '2');
DROP MATERIALIZED TABLE IF EXISTS `my_catalog`.`my_db`.`silver`;

Guard a deployment

Refuse to touch anything already sitting at the path. Useful for a first deployment, or any program where silently altering an existing table would be wrong.

try {
    tEnv.from("events")
            .materializeInto("silver")
            .execute(CreateMode.failIfExists());
} catch (ValidationException e) {
    LOG.error("silver already exists; re-run with CreateMode.createOrAlter() to adopt the declaration", e);
    throw e;
}

SQL equivalent:

CREATE MATERIALIZED TABLE `my_catalog`.`my_db`.`silver`
AS SELECT ...;

Backfill partitions

MaterializedTable silver = tEnv.fromMaterializedTable("silver");

for (String ds : List.of("2026-08-01", "2026-08-02", "2026-08-03")) {
    RefreshJob job = silver.refresh(Map.of("ds", ds));
    LOG.info("backfilling {} as job {}", ds, job.getJobID().get());
    job.await(); // sequential — one batch job at a time
}

SQL equivalent:

ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver` REFRESH PARTITION (`ds` = '2026-08-01');
ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver` REFRESH PARTITION (`ds` = '2026-08-02');
ALTER MATERIALIZED TABLE `my_catalog`.`my_db`.`silver` REFRESH PARTITION (`ds` = '2026-08-03');

Supervise a refresh job

MaterializedTable silver = tEnv.from("events")
        .groupBy($("ds"), $("region"))
        .select($("ds"), $("region"), $("amount").sum().as("revenue"))
        .materializeInto("silver", Duration.ofMinutes(1))
        .execute();

// execute() returns once the refresh job is submitted, not when it is running.
RefreshJob job = silver.getRefreshJob()
        .orElseThrow(() -> new IllegalStateException("silver has no refresh job"));
LOG.info("refresh job {} is {}", job.getJobID().get(), job.getJobStatus().get());

// Hand the coordinates to external monitoring, e.g. {execution.target=remote}
// with the setup above, or {execution.target=kubernetes-session,
// kubernetes.cluster-id=mt-refresh} on Kubernetes.
LOG.info("refresh job coordinates: {}", job.getClusterInfo());

// From any other program using the same catalog and cluster: re-resolve and inspect.
MaterializedTable resolved = tEnv.fromMaterializedTable("silver");
resolved.getRefreshJob().ifPresent(running ->
        LOG.info("refresh job {} is {}", running.getJobID().get(), running.getJobStatus().join()));

// Stop with a savepoint, recorded in the catalog.
resolved.suspend();

// Handles are live: silver sees the suspend made through resolved.
// The table has no refresh job now, job still points at the stopped one.
LOG.info("{}, job present: {}, old job {}",
        silver.getRefreshStatus(),             // SUSPENDED
        silver.getRefreshJob().isPresent(),    // false
        job.getJobStatus().get());             // FINISHED

Proposed Changes

API surface

The Table API surface produces the existing materialized table operations, which keep their behavior:

Operation

Table API surface

CreateMaterializedTableOperation

Table.materializeInto(path, ...).execute(CreateMode.failIfExists()), or execute() when nothing exists at the path

FullAlterMaterializedTableOperation

Table.materializeInto(path, ...).execute() on an existing materialized table

ConvertTableToMaterializedTableOperation

Table.materializeInto(path, ...).execute() on an existing regular table

AlterMaterializedTableChangeOperation,
AlterMaterializedTableAsQueryOperation

MaterializedTable.alter()...execute()

AlterMaterializedTableSuspendOperation

MaterializedTable.suspend()

AlterMaterializedTableResumeOperation

MaterializedTable.resume()

AlterMaterializedTableRefreshOperation

MaterializedTable.refresh(...)

DropMaterializedTableOperation

MaterializedTable.drop(...), TableEnvironment.dropMaterializedTable(...)

Beyond these operations, the surface adds capabilities for discovery and reading, e.g. TableEnvironment.fromMaterializedTable(path), listMaterializedTables(...), MaterializedTable.toTable().

Building operations for SQL and the Table API

The SQL converter for CREATE [OR ALTER] MATERIALIZED TABLE decides whether a declaration creates, alters or converts a table, merges the declared schema with the query's schema and derives the table changes. None of this needs Calcite or SQL syntax, only the declaration and the catalog state, so it moves to flink-table-api-java , where both the SQL converter and materializeInto(...)  use it. Only validating the SQL query and expanding its text stay in the planner. Both APIs therefore produce the same operation for the same declaration, and the SQL statements behave as before.

Enabling usage from a plain TableEnvironment

We will move the current logic from the SQL Gateway's MaterializedTableManager into DefaultMaterializedTableExecutor in flink-table-planner. It is the default implementation of a new internal MaterializedTableExecutor, and it owns everything a materialized table operation needs: the catalog write, submitting and controlling the refresh job, and the compensation between them.

// flink-table-api-java, org.apache.flink.table.delegation.materializedtable
@Internal
public interface MaterializedTableExecutorFactory extends Factory {
    String DEFAULT_IDENTIFIER = "default";

    MaterializedTableExecutor createExecutor(
      ExecutableOperation.Context operationContext);
}

@Internal
public interface MaterializedTableExecutor {
    TableResultInternal execute(MaterializedTableOperation operation, MaterializedTableJobSubmitter jobSubmitter);
}

/**
 * Provides the caller-specific refresh-job submission and scheduling capabilities a {@link
 * MaterializedTableExecutor} needs to run materialized table operations.
 */
@Internal
public interface MaterializedTableJobSubmitter {

    RefreshJobResult submitRefreshJob(Configuration executionConfig, String insertStatement);

    boolean supportsApplicationTargets();

    Optional<RefreshWorkflowContext> getRefreshWorkflowContext();
}

MaterializedTableExecutorFactory is discovered through FactoryUtil under the fixed identifier default, with the user class loader. Behind flink-table-planner-loader, DelegateMaterializedTableExecutorFactory loads the planner's factory through PlannerModule, like DelegatePlannerFactory does.

executeInternal routes every MaterializedTableOperation to the executor, ahead of the default ExecutableOperation path, because a catalog write alone would report success while starting no refresh job. This also applies to executeSql().

  1. From the SQL Gateway, the factory is discovered once per session. MaterializedTableManager is removed. The gateway only supplies what its session has: the workflow scheduler, the REST endpoint and application deployment.
  2. From a plain TableEnvironment, the factory is discovered on the first materialized table operation, and the executor is created once per environment.

Every rule that depends on the backend sits in DefaultMaterializedTableExecutor, not in the routing, rejecting unsupported targets, requiring execution.checkpointing.savepoint-dir before a stop with savepoint, comparing the program's target with the recorded one, and rejecting FULL without a workflow scheduler.

Supported deployments

Refresh jobs are submitted through the pipeline executor for execution.target, as executeSql("INSERT ...") jobs are today. They run detached and outlive the program. Three things differ:

  1. Only session targets are accepted: remote, yarn-session and kubernetes-session, plus minicluster for in-process tests. An unset, local or embedded target is rejected before any catalog change, with an error that names the options to set.
  2. When execution.target is set on the TableConfig, refresh jobs and their control read the options that select a cluster (rest.address, high-availability.*, kubernetes.cluster-id, yarn.application.id) from the TableConfig only. To control an existing refresh job, the target and cluster ID come from the catalog instead. In application mode, the root configuration describes the program's own cluster, so a root cluster ID would point refresh jobs at it. A target on the TableConfig without its cluster ID (rest.address for remote) is rejected before any catalog change. All other options, e.g. kubernetes.namespace and rest.port, are merged as for any job.
  3. Except for minicluster, refresh jobs never go through the program's own executor, and don't inherit the fixed job ID of an application in high-availability mode. In application mode and web submission, the program's target is embedded, so the refresh target must be set on the TableConfig:
tEnv.getConfig().set("execution.target", "kubernetes-session");
tEnv.getConfig().set("kubernetes.cluster-id", "mt-refresh");

Flink Kubernetes Operator

The refresh cluster is a session FlinkDeployment. Refresh jobs on it are not FlinkSessionJob's, so the operator neither savepoints nor upgrades them, as for the SQL Gateway's refresh jobs today. Declaring programs should be run as a client, with flink run or as a Kubernetes Job. Not as a FlinkSessionJob, which fails with "No jobs included in application." and is retried, and not as an application FlinkDeployment, which runs main() again on every restart and upgrade. Both re-run the declarations and restart every refresh job without state.

Controlling refresh jobs from other programs

The SQL Gateway can reach any refresh job through Flink's cluster client, using the execution target and cluster ID the catalog records for each refresh job. The Table API can't use the cluster client directly, because it lives in flink-clients.

To reach a refresh job it did not submit, flink-core gets an @Internal extension of PipelineExecutor:

// flink-core, org.apache.flink.core.execution
@Internal
public interface JobRetrievalSupportedPipelineExecutor extends PipelineExecutor {

    /**
     * A JobClient for an existing job on the cluster the configuration names.
     * Submits nothing and does not check that the job exists. The future fails
     * if the cluster can't be retrieved.
     */
    CompletableFuture<JobClient> retrieveJobClient(
            JobID jobId, Configuration configuration, ClassLoader userCodeClassloader)
            throws Exception;
}

AbstractSessionClusterExecutor and the minicluster test executor implement it.

The executor uses the JobClient from submission if it has one. Otherwise it takes the target and cluster ID the catalog records, finds the executor for that target with the same PipelineExecutorServiceLoader lookup as submission, and calls retrieveJobClient. The REST address, the high-availability settings and the Kubernetes namespace come from the program's configuration, read as on submission (see Supported deployments). Application targets go through the session executor of the same family. minicluster goes through the environment's loader, via a new @Internal getter on StreamExecutionEnvironment. The SQL Gateway uses the same path.

Limitations, by where the refresh job runs:

  1. Session cluster: all operations, from a program that reaches the same cluster. The catalog records no address, so for remote that means the same REST address. Otherwise the cluster reports the job as not found. Restarts also need the recorded target and cluster ID, see Restart target.
  2. Application cluster: getRefreshJob(), refresh(), suspend() and drop() work. refresh() runs its batch job on the program's refresh target. suspend() ends the application cluster. resume(), and alter() or a redeploy while ACTIVATED, would start a job there. They need the SQL Gateway and are rejected before the job is stopped. alter() on a suspended table changes only the catalog.
  3. minicluster: only from programs in the same JVM, through the environment MiniClusterExtension sets up. For tests.
  4. A cluster that is gone: every operation on the job fails, except drop() and resume() once the cluster reports the job as not found. An ended YARN application counts as not found. See Stuck tables.
  5. Any cluster: if the program registers the catalog under another name than the declaring program, it can't plan the stored definition. resume() fails and the table stays SUSPENDED.

Operations that require the SQL Gateway

From a plain TableEnvironment, suspend(), resume() and drop() on a FULL table are rejected, because they need the workflow scheduler, which runs in the SQL Gateway. They are rejected before anything changes in the catalog, the scheduler or a running job, and the error names the SQL Gateway. Tables whose refresh job runs in an application cluster are covered by Limitation 2 above.

All other operations work on FULL tables:

  • refresh() runs its one-off batch job on the refresh target, as for any refresh job (see Supported deployments).
  • alter() changes only the catalog, as in the SQL Gateway. The scheduler reads the definition from the catalog on every run. Neither alter() nor a redeploy changes freshness or refresh mode, so the schedule stays consistent.
  • drop() on a FULL table left INITIALIZING removes it from the catalog. It has no workflow to delete.

Restart target

Before anything is stopped or started, resume(), alter() and a redeploy from a plain TableEnvironment compare the program's execution.target, and for YARN and Kubernetes its cluster ID, with the ones the catalog records. If they differ, the operation is rejected with a ValidationException, and the running job and the catalog stay unchanged. The catalog records no address, so for remote only the target is compared: a program that points at another standalone cluster resumes a suspended table there. The same applies to the same Kubernetes cluster ID in another namespace. The SQL Gateway is unchanged and restarts on its session's target.

Stuck tables

Two kinds of materialized table have no refresh job the program can control:

  1. INITIALIZING  tables. Either a create failed and removing its catalog entry failed too, or a conversion failed and recording it as SUSPENDED failed too, or executeSql() ran CREATE [OR ALTER] MATERIALIZED TABLE  before this FLIP.
  2. ACTIVATED continuous tables in one of two situations:
    • the recorded cluster reports the refresh job as not found, e.g. after a standalone session cluster restarted without high availability,
    • the table's YARN application has ended.

DROP MATERIALIZED TABLE and drop() remove them from the catalog without cancelling a job or deleting a workflow. This also works for a FULL table from a plain TableEnvironment. All other operations on them stay rejected. This includes CREATE OR ALTER and materializeInto(...).execute(). To recreate the table, drop it and run the declaring program again. Dropping a table that another program is still creating makes that create fail, and the create cancels its refresh job.

ALTER MATERIALIZED TABLE ... RESUME and resume() treat such a refresh job like one that has ended. They start a new refresh job without state. The table keeps its definition and its data. This extends what RESUME already does on an ACTIVATED table.

A cluster that can't be reached still fails the drop, because the cause can be transient. If the cluster is gone for good, either start a Kubernetes session cluster under the recorded cluster ID, or for remote a cluster at the program's REST address, and then drop the table. A YARN table needs no such step, because an ended YARN application already counts as not found. For remote, the catalog records no address. So a program pointed at another standalone cluster also gets "not found", and its drop() leaves the refresh job running on the original cluster.

All of the above also applies in the SQL Gateway, since it uses the same executor.

Query restrictions

A query declared through the Table API can only be materialized if it can be written as SQL and references only permanent catalog objects. The definition is stored as SQL text, generated with QueryOperation#asSerializableString(), and re-planned by later operations such as resume() , possibly in another program. A query without a SQL form is therefore rejected with a ValidationException when the declaration is built, before anything is written to the catalog.  The message states that the query must be expressible in SQL and includes the cause. This applies to:

  • Inline function instances, e.g. call(new MyFunc(), ...), call(MyFunc.class, ...)
  • fromDataStream, fromChangelogStream, from(TableDescriptor)
  • Operations that have no SQL serialization yet, e.g. session group windows (Session.withGap(...))

As with SQL CREATE MATERIALIZED TABLE and TableEnvironment#createView(path, Table), temporary functions, models, tables and views are not rejected. The stored query refers to them by name, so it plans in the declaring session, but a refresh job planned in another session, e.g. resume() from another program or through the SQL Gateway, can't resolve them. Materialized-table DDL passed to executeSql() is not affected by this rule.

Start Mode

A start mode tells the refresh job that a call starts where to read its sources from (see FLIP-557). CREATE and CREATE OR ALTER MATERIALIZED TABLE accept it as the START_MODE clause. In the Table API it is part of MaterializedTableDescriptor, like freshness, and MaterializedPipeline.execute(StartMode) and execute(CreateMode, StartMode) override it for one call.

The semantics are those of the equivalent SQL statement. A declaration uses the start mode passed to execute(...), else the descriptor's, else materialized-table.default-start-mode (default FROM_BEGINNING), like a statement without START_MODE. It is recorded with the definition, so that whatever starts the refresh job can apply it. MaterializedTableEvolution.execute() leaves it unchanged, as SQL ALTER has no START_MODE.

Unlike freshness, which an existing table keeps on a later declaration (see CreateMode.createOrAlter()), the start mode is replaced by every declaration and read once, by the job that declaration starts. So a start mode in a shared descriptor applies to every table built from it, on every redeploy. One-off start modes such as fromBeginning(), can be put on execute(StartMode) instead of using it in a shared policy.

The refresh job does not apply a start mode yet. It reads its sources per their own startup options, e.g. scan.startup.mode. The Table API passes the start mode exactly as the SQL clause does, so it takes effect once the refresh job applies it, without an API change.

Every execute() on an existing ACTIVATED continuous table restarts its refresh job without state. This holds for an identical declaration, an options-only change and a query change alike. resume() restores the refresh job from the savepoint taken by suspend(). If the table was altered or redeployed while suspended, there is no savepoint to restore, and resume() starts the job without state. In neither case does a start mode apply. Which changes should keep the job's state instead of applying the start mode belongs to FLIP-557's ALTER path and is not defined here.

Workflow Scheduling

A plain TableEnvironment has no resident process to host a WorkflowScheduler, so FULL mode is out of scope there. Creating or converting a FULL table is rejected before any catalog write, with an error that names the cause. This includes RefreshStrategy.automatic() resolving to FULL. An existing FULL table can still be inspected, altered and refreshed, see Operations that require the SQL Gateway. The SQL Gateway keeps its EmbeddedWorkflowScheduler, so FULL mode stays available there.

Compatibility, Deprecation, and Migration Plan

Today, materialized-table DDL passed to executeSql() on a TableEnvironment changes only the catalog, or fails. After this FLIP, it runs through the MaterializedTableExecutor, as in the SQL Gateway, and starts, stops or cancels the refresh job, or fails:

Statement

Current Behavior

Behavior after this FLIP

CREATE [OR ALTER] of a new table with a local, embedded or unset execution.target

Catalog entry written, success.

Rejected with a ValidationException before any catalog change.

CREATE [OR ALTER] in FULL mode

Catalog entry written, success.

Rejected before any catalog change, see Workflow Scheduling.

ALTER, or CREATE OR ALTER of an existing ACTIVATED table

Catalog changed, old job keeps running.

The job is stopped with a savepoint and restarted without restoring it. It fails without execution.checkpointing.savepoint-dir, or on an unsupported refresh target, or if the recorded target or cluster ID differs. If the new job then fails to start, the previous definition is restored and the previous job restarts from the savepoint.

DROP of an ACTIVATED table

Catalog entry removed, job keeps running.

The job is cancelled first. It fails if the program can't reach the job's cluster or the cluster doesn't know the job.

DROP of a FULL table

Catalog entry removed, workflow keeps running.

Fails, because the workflow requires the SQL Gateway. A FULL table left INITIALIZING is removed, see Stuck tables.

SUSPEND, RESUME, REFRESH

Fail with UnsupportedOperationException.

Stop, restart or run the refresh job.

Tests and tools that create materialized tables with executeSql() on a default environment break on upgrade. If they need a refresh job, they must run against a cluster (set execution.target to remote, yarn-session or kubernetes-session, with its cluster ID). If they only need the catalog entry, they can write it with Catalog.createTable.

Tables left INITIALIZING by the old behavior have no refresh job. They can be dropped, and then recreated by running the declaring program again, see Stuck tables.

The SQL Gateway, and the SQL Client and JDBC driver built on it, change in two cases that fail today:

  1. DROP of an INITIALIZING table. Currently rejected; after the FLIP it removes the catalog entry.
  2. DROP of an ACTIVATED table whose recorded cluster reports the job as not found, or whose YARN application has ended. Currently fails; after the FLIP it removes the catalog entry without cancelling.

The refresh handler the catalog stores is unchanged.

It is not planned to introduce a flag to restore the old behavior.

All other changes are additive. Table and TableEnvironment gain new methods. There are no deprecations. FULL mode remains available through the SQL Gateway and its embedded scheduler.

Test Plan

  • Unit tests for the new descriptors/builders, and for the mapping from each MaterializedTableOperation to its Table API entry point
  • FULL mode from a plain TableEnvironment is rejected before any catalog change, with a message that names the cause. This covers a declared FULL and automatic() resolving to FULL
  • The existing materialized-table SQL integration tests keep passing, confirming the extraction did not introduce behavioral changes beyond the two SQL Gateway changes listed under Compatibility
  • executeSql() materialized-table DDL on a default TableEnvironment (local target, not set on the TableConfig) is rejected before any catalog change
  • Partial failure cases, where the catalog write succeeds but the refresh job cannot be submitted:
    • create: the table is removed again and no job is left running
    • convert: the table stays converted, in SUSPENDED
    • alter: the previous definition is restored and the previous job restarts from its savepoint
    • resume: the table stays SUSPENDED
    • A reverse case: the job is submitted but the final catalog write fails, and the job is cancelled
  • Integration tests:
    • From a plain TableEnvironment in CONTINUOUS mode: create, alter, suspend, resume, one-off refresh and drop, through the Table API and through executeSql()
    • A Table declared through the SQL Gateway, operated from a plain TableEnvironment: inspect the table and its refresh job, alter, redeploy through materializeInto(...).execute(), suspend, resume, refresh, and drop
    • A Table declared by one program, operated by another. The second program has its own TableEnvironment and its own catalog instance, and runs the same operations. This includes redeploying both an unchanged and a changed declaration
    • A Table declared through the Table API is suspended, resumed and dropped through the SQL Gateway
    • Tables the Table API can only partly operate, created through the SQL Gateway. For a FULL table, suspend, resume and drop are rejected before any change, and its refresh workflow keeps running. Alter and refresh succeed.
    • A program that registers the catalog under a different name than the declaring program fails on resume, and the table stays SUSPENDED
    • A program whose refresh target or cluster ID differs from the recorded one: resume, alter and redeploy are rejected before the job is stopped.
    • The SQL Gateway still restarts on its session's target and records the new job's target and cluster ID, as today.
    • A program with a context environment, as in application mode or web submission, submits its refresh jobs to the target's cluster. Its refresh jobs don't inherit a fixed job ID.
    • With the target on the TableConfig, refresh jobs and job control ignore the root configuration's REST address, high-availability settings and cluster ID.
    • An INITIALIZING table written with Catalog.createTable is dropped through executeSql(), drop() and the SQL Gateway, in CONTINUOUS and in FULL mode. CREATE OR ALTER and materializeInto(...).execute() are rejected, the catalog stays unchanged, and the error names DROP MATERIALIZED TABLE.
    • A drop during another program's create, the create fails and its refresh job is cancelled. In the SQL Gateway, a FULL create leaves no workflow behind.
    • An ACTIVATED table whose recorded cluster doesn't know its refresh job. drop() removes it, resume() starts a new refresh job without state, suspend(), alter() and a redeploy fail without any change. With an unreachable cluster, all of them fail and the table stays ACTIVATED. The same holds through the SQL Gateway.

Future Work

  • PyFlink parity, until then, the new Java methods are listed in its API completeness test exclusions
  • Refresh jobs in a dedicated application cluster (yarn-application, kubernetes-application) from the Table API
  • A start mode on MaterializedTableEvolution.execute(), once FLIP-557 is implemented
  • CompiledPlan for continuous refresh jobs to produce upgrade-stable plans for long-lived materialized tables
  • FULL mode for materialized tables created and operated via Table API
  • Adding a default WorkflowScheduler implementation, which is usable for FULL mode via Table API

Rejected Alternatives

  1. In-process workflow scheduler for FULL mode.
    An InProcessWorkflowScheduler would live only as long as the program, so refreshes stop when it exits. That is not viable for production workloads.
  2. Keeping the lifecycle logic in the SQL Gateway.
    Leaving the logic in the gateway's MaterializedTableManager, would require the Table API to call into a running gateway and to become effectively a client of it. The Table API already builds the same Operation tree that the SQL parser produces, so round-tripping through text adds a redundant layer and a second grammar to keep in sync. Also it couples the usage of materialized tables to a running gateway.
  3. Running refresh jobs inside the program's application cluster.
    drop() or a failing refresh job would end the application, which cancels the program's other jobs. A suspended refresh job could not be resumed, since a finished application accepts no new jobs, even with execution.shutdown-on-application-finish=false. A redeploy would replace the cluster together with its refresh jobs.
  4. A dedicated configuration namespace for the refresh cluster (e.g. materialized-table.refresh-job.*).
    It would let a deployment YAML name the refresh cluster, but it adds public configuration with different semantics from the SQL Gateway, where the session's execution.target decides. The TableEnvironment configuration already provides the same without new options, so the namespace is left for future work.
  5. Rejecting conflicting calls on MaterializedTableEvolution, e.g. option(k, v).resetOption(k).
    It would need a rule for every pair of calls, and would make the Table API stricter than the equivalent sequence of ALTER  statements in SQL. Changes apply in call order instead.
  6. Rejecting temporary objects in Table API queries.
    A temporary object serializes by name and plans in the declaring session, so only a walk over the operation tree could reject it, and only for the Table API. That would make materializeInto stricter than SQL CREATE MATERIALIZED TABLE and createView(path, Table). Such a query fails instead when another session plans its refresh job.