This is an automated email from the ASF dual-hosted git repository.

JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git


The following commit(s) were added to refs/heads/master by this push:
     new b6c247995d [flink] Fix lake-stream write validation and catalog 
routing (#11062)
b6c247995d is described below

commit b6c247995d07c84c0f0bff57df4192b1da2e0156
Author: Jingsong Lee <[email protected]>
AuthorDate: Tue Nov 10 19:16:53 2026 +0800

    [flink] Fix lake-stream write validation and catalog routing (#11062)
---
 docs/docs/concepts/lake-stream.md                  | 104 -----------------
 docs/docs/flink/lake-stream.md                     | 127 ++++++++++++---------
 docs/sidebars.js                                   |   3 +-
 .../java/org/apache/paimon/flink/FlinkCatalog.java |  12 +-
 .../flink/lakestream/LakeStreamTableFactory.java   |  50 +++++---
 .../paimon/flink/lakestream/LakeStreamUtils.java   |  88 ++++++++++++--
 .../apache/paimon/flink/JdbcCatalogViewITCase.java |   9 ++
 .../flink/lakestream/LakeStreamFlussITCase.java    |  22 ++++
 .../flink/lakestream/LakeStreamRoutingITCase.java  |  15 +++
 .../lakestream/LakeStreamTableFactoryTest.java     |  23 ++--
 .../flink/lakestream/LakeStreamUtilsTest.java      |  51 ++++++---
 11 files changed, 298 insertions(+), 206 deletions(-)

diff --git a/docs/docs/concepts/lake-stream.md 
b/docs/docs/concepts/lake-stream.md
deleted file mode 100644
index 7bdf3e19da..0000000000
--- a/docs/docs/concepts/lake-stream.md
+++ /dev/null
@@ -1,104 +0,0 @@
----
-title: "Lake-Stream Mode"
-sidebar_position: 11
----
-
-<!--
-Licensed to the Apache Software Foundation (ASF) under one
-or more contributor license agreements.  See the NOTICE file
-distributed with this work for additional information
-regarding copyright ownership.  The ASF licenses this file
-to you under the Apache License, Version 2.0 (the
-"License"); you may not use this file except in compliance
-with the License.  You may obtain a copy of the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing,
-software distributed under the License is distributed on an
-"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-KIND, either express or implied.  See the License for the
-specific language governing permissions and limitations
-under the License.
--->
-
-# Lake-Stream Mode
-
-Lake-stream mode keeps a table's history in Paimon and serves its most recent 
writes from an
-external streaming store, so a query can return data that is seconds old 
instead of waiting for the
-next snapshot. Enable it on an existing table when snapshot-level freshness is 
too slow and you
-already run a supported store. The table keeps its name, its schema, and its 
historical data.
-
-A table is a lake-stream table when its `lakestream.enabled` option is `true`. 
Paimon then routes
-each read and write by table name, and the store's tiering service moves data 
into Paimon in the
-background.
-
-Enabling the mode needs engine-specific catalog configuration, so each engine 
has its own page.
-[Flink](../flink/lake-stream) is supported today, and Spark is not supported 
yet. Fluss is the first
-supported store, and [Use Fluss as the 
Store](../flink/lake-stream#use-fluss-as-the-store) walks
-through it end to end.
-
-## Read a Lake-Stream Table
-
-The name you query decides which data you get, and both names resolve to the 
same table.
-
-| Name | What the read returns |
-| --- | --- |
-| `my_table` | Paimon snapshots only. Existing queries keep their current 
behavior and visibility. |
-| `my_table$rt` | Paimon snapshots plus the records the store has not tiered 
yet. |
-
-Query `my_table$rt` when you need the freshest data, and keep `my_table` for 
queries that must
-reproduce a committed snapshot.
-
-`$rt` is the same table read through the store rather than a second table. 
Writing to `my_table$rt`
-is rejected; write to `my_table` and let the routing above decide where it 
lands. Querying
-`my_table$rt` on a table without `lakestream.enabled` fails as an unknown 
table, and time travel
-does not apply to it. Read a historical snapshot through `my_table` instead.
-
-## Write to a Lake-Stream Table
-
-Regular writes go to the store, and the store's tiering service moves them 
into Paimon afterwards.
-This covers streaming and batch inserts.
-
-`UPDATE` and `DELETE` are not supported yet. Both read the table to find the 
rows they apply to,
-and on a lake-stream table that read resolves to Paimon snapshots while the 
modification is written
-to the store. The statement could then miss rows the store has not tiered yet, 
or compute an update
-from a stale value, so Paimon rejects it rather than run it against two 
different views.
-
-`INSERT OVERWRITE` is not supported on a lake-stream table: every write to 
such a table is served by
-the store, so an overwrite never reaches Paimon.
-
-## Change a Lake-Stream Table
-
-Paimon rejects a table rename while `lakestream.enabled` is `true`. The table 
name is how Paimon
-finds the matching table in the store, so a rename would break that lookup.
-
-Paimon also rejects replacing the table, which is what `CREATE OR REPLACE 
TABLE` does. Replacing a
-table can truncate data the store has not tiered yet, and it can drop the 
`lakestream.enabled`
-option without the restart that [disabling the 
mode](#disable-lake-stream-mode) requires.
-
-Disable lake-stream mode first if you need to rename or replace the table.
-
-Column changes are allowed, and they update the Paimon table only. The store's 
tiering service
-reconciles its own schema afterwards, so the two schemas can differ briefly. 
While their physical
-columns, primary or partition keys, or shared immutable table options differ, 
a write to the table
-is rejected because Paimon cannot safely delegate it to the store. Where you 
can, make column
-changes through the store's catalog to keep the two schemas aligned.
-
-Dropping a lake-stream table removes it from Paimon and leaves the store's 
table behind. The store
-owns that table's lifecycle, so remove it through the store if you no longer 
need it.
-
-## Disable Lake-Stream Mode
-
-Set the table option back to `false`.
-
-```sql
-ALTER TABLE my_table SET ('lakestream.enabled' = 'false');
-```
-
-Reads and writes then use Paimon only, and `my_table$rt` stops resolving. 
Restart running write
-pipelines without state so that they plan against the Paimon sink again.
-
-Paimon does not wait for the store to finish tiering. Records that are still 
only in the store when
-you disable the mode do not appear in later Paimon reads, so confirm that 
tiering has caught up if
-you need complete results.
diff --git a/docs/docs/flink/lake-stream.md b/docs/docs/flink/lake-stream.md
index d3f585f976..c18d721099 100644
--- a/docs/docs/flink/lake-stream.md
+++ b/docs/docs/flink/lake-stream.md
@@ -23,14 +23,14 @@ under the License.
 
 # Lake-Stream Mode
 
-The Flink connector routes the reads and writes of a lake-stream table through 
the streaming store
-you name on the catalog. [Lake-Stream Mode](../concepts/lake-stream) explains 
what the mode does to
-a table.
+Lake-stream mode keeps table history in Paimon and serves recent data through 
an external
+Lakestream Store. This lets Flink read fresh data between Paimon snapshot 
commits. The store's
+tiering service moves its records into Paimon in the background. Fluss is the 
first supported store.
 
 ## Enable Lake-Stream Mode
 
-A lake-stream table needs three things: a table of the same database and name 
in the store, the
-`lakestream.enabled` option on the Paimon table, and a Paimon catalog that 
names the store.
+A lake-stream table has `lakestream.enabled` set to `true` in Paimon, a 
corresponding store table
+with the same database and table name, and a Paimon catalog configured to use 
that store.
 
 Create the Paimon catalog with `lakestream.store` and the store's connection 
options.
 
@@ -48,45 +48,51 @@ identifier, and Paimon removes the prefix before it passes 
the options on, so
 `fluss.bootstrap.servers` reaches Fluss as `bootstrap.servers`. See
 [CatalogOptions](../maintenance/configurations#catalogoptions) for the catalog 
reference.
 
-Paimon does not create the store-side table and does not move a table's 
existing data into it.
-Create the store table yourself, in a catalog of the store;
-[Use Fluss as the Store](#use-fluss-as-the-store) shows how for Fluss.
+Set up the store table through the provider's catalog. For Fluss, follow
+[Use Fluss as the Store](#use-fluss-as-the-store) to link both layers to the 
same table.
 
 Stop the pipelines that write to the table before you change either side, and 
restart them without
 state once both sides exist, so that Flink plans them against the store sink. 
A write that lands
 while the store side is missing, or a writer that resumes from state saved 
against the Paimon sink,
 can leave the store and Paimon holding different data for the same keys.
 
-A catalog created without `lakestream.store` cannot serve a lake-stream table. 
`my_table$rt` fails
-as an unknown table, and a write to `my_table` is rejected instead of quietly 
going to Paimon, which
-would leave the store and Paimon holding different data for the same keys. 
Tables that are not
-lake-stream tables are unaffected. Add `lakestream.store` and the store's 
connection options to the
-catalog, or [disable the 
mode](../concepts/lake-stream#disable-lake-stream-mode) on the table first.
+A catalog without `lakestream.store` can still read committed Paimon snapshots 
by the original
+table name. Real-time reads and writes to an enabled table require the store 
configuration.
+To resume direct writes to Paimon, [disable the 
mode](#disable-lake-stream-mode) first.
 
-Lake-stream mode needs a Paimon catalog. A temporary table declared with 
`'connector' = 'paimon'`
-and a `path` reaches the data without a catalog, so it has no store: a `$rt` 
read through it, and a
-write to a lake-stream table through it, are both rejected rather than served 
from Paimon. Read and
-write a lake-stream table through the catalog.
+Use the Paimon catalog for lake-stream reads and writes. A table declared with 
`'connector' = 'paimon'`
+and a `path` can read snapshots, but Flink rejects `$rt` reads and writes 
through a path mapping to an
+enabled table.
 
 ## Write to a Lake-Stream Table
 
-Your write statements do not change. Flink reads `lakestream.enabled` from the 
table when it plans
-the statement and routes the write accordingly.
+Flink uses the persisted `lakestream.enabled` setting to route batch and 
streaming inserts to the
+store.
 
 ```sql
 INSERT INTO my_table SELECT * FROM source_table;
 ```
 
-A Flink CDC pipeline does not plan its writes through the SQL sink, so it 
writes straight to Paimon
-and bypasses the store. Confirm that the data it writes has already expired 
from the store: while
-the store still holds records for the same primary keys, the two can disagree 
about them, and later
-updates from the store may then use stale state. See
-[Write to a Lake-Stream 
Table](../concepts/lake-stream#write-to-a-lake-stream-table).
+Flink rejects `INSERT OVERWRITE`, `UPDATE`, and `DELETE` on lake-stream 
tables. Row-level changes
+would select rows from committed Paimon snapshots while writing changes to the 
store, which may
+already hold newer values.
 
-## Read the Real-Time Name
+Lake-stream writes use the main branch. A new Paimon branch can inherit 
`lakestream.enabled`.
+To write directly to that branch, disable the option on the branch first.
 
-`my_table$rt` is the same table read through the store, not a second table. 
Write the name in
-backticks:
+A Flink CDC pipeline writes directly to Paimon through its own sink. Before 
using it to update a
+lake-stream table, confirm that records for the affected keys have expired 
from the store. Later
+store updates can otherwise use stale values.
+
+## Read a Lake-Stream Table
+
+The original name reads committed Paimon snapshots. The read-only `$rt` alias 
delegates to the
+store, which can combine those snapshots with records it has yet to tier. Use 
the original name for
+time travel.
+
+### Read the Real-Time Name
+
+Quote the alias with backticks in SQL.
 
 ```sql
 -- Reads only data that Paimon has committed.
@@ -99,17 +105,37 @@ SELECT * FROM `my_table$rt`;
 Paimon connects to the store on the first lake-stream read or write. An 
unknown store identifier or
 a connection option the store requires fails at that point with a 
configuration error.
 
-## Use Fluss as the Store
+## Change a Lake-Stream Table
+
+Disable lake-stream mode before renaming or replacing the table. The store 
uses the original table
+name to find its corresponding table. Dropping the Paimon table leaves the 
store table in place.
+
+Keep physical columns, keys, and shared immutable options aligned between 
Paimon and the store.
+Flink rejects a write when they differ or when the statement was planned 
against an older layout.
+Apply supported schema changes through the store's catalog. With Fluss, a 
schema change made only
+in Paimon can cause the tiering job to fail and restart until the two schemas 
match again.
+
+## Disable Lake-Stream Mode
 
-Fluss is a streaming storage system for the lakehouse, and can serve as a 
Paimon Lakestream Store.
-Lake-stream mode requires Fluss 1.0 or later.
+Stop the write pipelines and let the store finish tiering any records that 
subsequent Paimon reads
+need. Then disable the option and restart the pipelines without state so Flink 
plans a Paimon sink.
 
-Set up a Fluss cluster with Paimon as its lakehouse storage first; the Fluss 
documentation covers
-[deploying the streaming 
lakehouse](https://fluss.apache.org/docs/install-deploy/deploying-streaming-lakehouse/)
-and [Paimon as a datalake 
format](https://fluss.apache.org/docs/streaming-lakehouse/datalake-formats/paimon/).
+```sql
+ALTER TABLE my_table SET ('lakestream.enabled' = 'false');
+```
+
+Subsequent reads and writes use Paimon snapshots and sinks. The `$rt` alias is 
available only while
+the table has lake-stream mode enabled.
+
+## Use Fluss as the Store
+
+Use Fluss 1.0 or later. Configure the Fluss cluster and tiering service to use 
the same Paimon catalog
+and warehouse as `paimon_catalog`. See the Fluss guide to
+[configuring Paimon as lakehouse 
storage](https://fluss.apache.org/docs/streaming-lakehouse/datalake-formats/paimon/).
 
-Then create the store-side table and the Paimon table that points at it. The 
two have to agree on
-the database name and the table name, because that name is how Paimon finds 
the table in the store.
+For a new table, create it in Fluss with `table.datalake.enabled` set to 
`true`. Fluss creates the
+corresponding Paimon table and enables lake-stream mode on it. If the Paimon 
table already exists,
+use a Fluss version that supports in-place enablement and follow its promotion 
procedure.
 
 ```sql
 CREATE CATALOG `fluss_store` WITH (
@@ -117,34 +143,33 @@ CREATE CATALOG `fluss_store` WITH (
     'bootstrap.servers' = 'fluss-server:9123'
 );
 
-CREATE TABLE fluss_store.my_db.my_table (id INT);
+CREATE DATABASE IF NOT EXISTS fluss_store.my_db;
 
-CREATE TABLE paimon_catalog.my_db.my_table (id INT) WITH (
-    'lakestream.enabled' = 'true'
+CREATE TABLE fluss_store.my_db.my_table (id INT) WITH (
+    'table.datalake.enabled' = 'true'
 );
 ```
 
-Writes and reads are then the ordinary ones, in the Paimon catalog:
+Write and query through the Paimon catalog.
 
 ```sql
+USE CATALOG paimon_catalog;
+USE my_db;
+
 INSERT INTO my_table SELECT * FROM source_table;
 
 SELECT * FROM `my_table$rt`;
 ```
 
-:::note
-A Fluss log table is unbounded, so Flink rejects a batch query on 
`my_table$rt` as a query on an
-unbounded table. Bound the read with scan hints. The example below reads the 
log from the beginning
-up to the offset it had when the query started.
-:::
+Run the query in batch mode to get a bounded union read. Fluss uses its `full` 
startup mode for
+the lake-enabled table.
 
 ```sql
-SELECT * FROM `my_table$rt`
-/*+ OPTIONS('scan.startup.mode' = 'earliest', 'scan.bounded.mode' = 
'latest-offset') */;
+SET 'execution.runtime-mode' = 'batch';
+SELECT * FROM `my_table$rt`;
 ```
 
-Records reach Paimon only through the Fluss tiering service, which is a 
separate component from the
-Fluss cluster that serves `my_table$rt`. Until the tiering service runs, the 
records stay in Fluss:
-`my_table$rt` returns them and `my_table` returns nothing. The Fluss 
documentation covers the
-[tiering 
service](https://fluss.apache.org/docs/streaming-lakehouse/tiering-service/) and
-[union reads](https://fluss.apache.org/docs/streaming-lakehouse/union-read/).
+The [Fluss tiering 
service](https://fluss.apache.org/docs/streaming-lakehouse/tiering-service/) 
runs
+separately from the cluster. New records become visible through the original 
Paimon table name once
+tiering commits them. For real-time reads, see
+[Fluss union 
reads](https://fluss.apache.org/docs/streaming-lakehouse/union-read/).
diff --git a/docs/sidebars.js b/docs/sidebars.js
index 542d1d2674..11aa06bd17 100644
--- a/docs/sidebars.js
+++ b/docs/sidebars.js
@@ -76,8 +76,7 @@ const sidebars = {
             "items": ["concepts/spec/tableindex", "concepts/spec/fileindex"]
           }
         ]
-      },
-      "concepts/lake-stream"
+      }
     ]
   },
   {
diff --git 
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/FlinkCatalog.java
 
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/FlinkCatalog.java
index ac13817032..9f8321e166 100644
--- 
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/FlinkCatalog.java
+++ 
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/FlinkCatalog.java
@@ -396,7 +396,8 @@ public class FlinkCatalog extends AbstractCatalog {
     private CatalogBaseTable getTable(ObjectPath tablePath, @Nullable Long 
timestamp)
             throws TableNotExistException {
         if (LakeStreamUtils.isRealTimeTable(tablePath)) {
-            return getLakeStreamRealTimeTable(tablePath, timestamp);
+            Optional<CatalogBaseTable> view = getView(tablePath, timestamp);
+            return view.isPresent() ? view.get() : 
getLakeStreamRealTimeTable(tablePath, timestamp);
         }
         Table table;
         try {
@@ -1132,8 +1133,13 @@ public class FlinkCatalog extends AbstractCatalog {
                             LakeStreamUtils.REAL_TIME_TABLE_SUFFIX,
                             basePath.getFullName()));
         }
-        CatalogBaseTable baseTable = getTable(basePath, null);
-        if 
(!Options.fromMap(baseTable.getOptions()).get(CoreOptions.LAKE_STREAM_ENABLED)) 
{
+        Table baseTable;
+        try {
+            baseTable = catalog.getTable(toIdentifier(basePath));
+        } catch (Catalog.TableNotExistException e) {
+            throw new TableNotExistException(getName(), tablePath);
+        }
+        if 
(!Options.fromMap(baseTable.options()).get(CoreOptions.LAKE_STREAM_ENABLED)) {
             throw new TableNotExistException(getName(), tablePath);
         }
         return requireLakeStreamStoreTable(basePath);
diff --git 
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/lakestream/LakeStreamTableFactory.java
 
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/lakestream/LakeStreamTableFactory.java
index 19b66e2d83..0bf469c311 100644
--- 
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/lakestream/LakeStreamTableFactory.java
+++ 
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/lakestream/LakeStreamTableFactory.java
@@ -94,10 +94,8 @@ public class LakeStreamTableFactory implements 
DynamicTableSourceFactory, Dynami
     public static boolean isLakeStreamRead(
             @Nullable FlinkCatalog catalog, DynamicTableFactory.Context 
context) {
         if (catalog == null) {
-            // with no catalog there is no lake-stream table to confirm the 
name against, so the
-            // name alone counts; the read is then refused for lack of a store 
rather than served
-            // from Paimon
-            return 
LakeStreamUtils.isRealTimeTable(context.getObjectIdentifier().toObjectPath());
+            return LakeStreamUtils.isRealTimeTable(identifierOf(context))
+                    && lakeStreamEnabledAtPath(context);
         }
         return realTimeReadBaseTable(catalog.catalog(), context) != null;
     }
@@ -108,13 +106,26 @@ public class LakeStreamTableFactory implements 
DynamicTableSourceFactory, Dynami
      */
     public static boolean isLakeStreamWrite(
             @Nullable FlinkCatalog catalog, DynamicTableFactory.Context 
context) {
+        if (catalog == null) {
+            return lakeStreamEnabledAtPath(context);
+        }
         Identifier identifier = identifierOf(context);
         if (LakeStreamUtils.isRealTimeTable(identifier)) {
             return true;
         }
-        return catalog != null
-                ? persistedLakeStreamTable(catalog.catalog(), identifier) != 
null
-                : lakeStreamEnabledAtPath(context);
+        if (persistedLakeStreamTable(catalog.catalog(), identifier) == null) {
+            return false;
+        }
+        if (identifier.getBranchName() != null) {
+            throw new ValidationException(
+                    String.format(
+                            "Cannot write to lake-stream branch '%s'. The 
Lakestream Store only "
+                                    + "serves the main branch. To write 
directly to this Paimon "
+                                    + "branch, disable '%s' on the branch 
first.",
+                            context.getObjectIdentifier().asSummaryString(),
+                            CoreOptions.LAKE_STREAM_ENABLED.key()));
+        }
+        return true;
     }
 
     @Override
@@ -149,7 +160,7 @@ public class LakeStreamTableFactory implements 
DynamicTableSourceFactory, Dynami
         // require provider-specific table options (PIP-39 L289)
         CatalogBaseTable storeTable =
                 catalog.requireLakeStreamStoreTable(identifier.toObjectPath());
-        checkSchemaAlignment(table, storeTable, identifier);
+        checkSchemaAlignment(context, table, storeTable);
         DynamicTableSinkFactory sinkFactory =
                 storeFactory(
                         storeCatalog, DynamicTableSinkFactory.class, "create a 
sink for writes");
@@ -187,17 +198,28 @@ public class LakeStreamTableFactory implements 
DynamicTableSourceFactory, Dynami
 
     /** Rejects a write while the store's schema, keys, or shared immutable 
options differ. */
     private static void checkSchemaAlignment(
-            Table paimonTable, CatalogBaseTable storeTable, ObjectIdentifier 
identifier) {
+            DynamicTableFactory.Context context, Table paimonTable, 
CatalogBaseTable storeTable) {
         Schema paimonSchema = LakeStreamUtils.toPaimonSchema(paimonTable);
-        Schema storeSchema = LakeStreamUtils.toPaimonSchema(storeTable);
+        Schema storeSchema =
+                LakeStreamUtils.toPaimonSchema(
+                        storeTable, context.getClassLoader(), 
context.getConfiguration());
+        String identifier = context.getObjectIdentifier().asSummaryString();
         if (!LakeStreamUtils.isCompatible(paimonSchema, storeSchema)) {
             throw new ValidationException(
                     String.format(
                             "Cannot write to lake-stream table '%s': the 
Lakestream Store's "
-                                    + "schema and table options [%s] have not 
caught up with "
-                                    + "Paimon's [%s]. Wait for the store to 
reconcile its schema, "
-                                    + "or align the two through the store's 
catalog, before writing.",
-                            identifier.asSummaryString(), storeSchema, 
paimonSchema));
+                                    + "physical schema, keys, or shared 
immutable options have not "
+                                    + "caught up with Paimon's. Store physical 
schema: %s. "
+                                    + "Paimon physical schema: %s. Align the 
two tables before writing.",
+                            identifier, storeSchema.rowType(), 
paimonSchema.rowType()));
+        }
+        if (!LakeStreamUtils.matchesPlannedLayout(context.getCatalogTable(), 
storeSchema)) {
+            throw new ValidationException(
+                    String.format(
+                            "Cannot write to lake-stream table '%s': the 
statement was planned "
+                                    + "with a different physical schema or 
keys. Replan the "
+                                    + "statement before writing.",
+                            identifier));
         }
     }
 
diff --git 
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/lakestream/LakeStreamUtils.java
 
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/lakestream/LakeStreamUtils.java
index e34509ea28..0dd0847199 100644
--- 
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/lakestream/LakeStreamUtils.java
+++ 
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/lakestream/LakeStreamUtils.java
@@ -20,6 +20,7 @@ package org.apache.paimon.flink.lakestream;
 
 import org.apache.paimon.CoreOptions;
 import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.flink.DataCatalogTable;
 import org.apache.paimon.flink.FlinkCatalog;
 import org.apache.paimon.flink.LogicalTypeConversion;
 import org.apache.paimon.schema.Schema;
@@ -30,14 +31,22 @@ import org.apache.paimon.types.MapType;
 import org.apache.paimon.types.MultisetType;
 import org.apache.paimon.types.RowType;
 
+import org.apache.flink.api.common.ExecutionConfig;
+import org.apache.flink.configuration.ReadableConfig;
 import org.apache.flink.table.api.ValidationException;
 import org.apache.flink.table.catalog.CatalogBaseTable;
 import org.apache.flink.table.catalog.CatalogTable;
+import org.apache.flink.table.catalog.DataTypeFactory;
 import org.apache.flink.table.catalog.ObjectIdentifier;
 import org.apache.flink.table.catalog.ObjectPath;
+import org.apache.flink.table.catalog.ResolvedCatalogTable;
+import org.apache.flink.table.catalog.ResolvedSchema;
+import org.apache.flink.table.catalog.UniqueConstraint;
 import org.apache.flink.table.types.AbstractDataType;
 import org.apache.flink.table.types.DataType;
 
+import java.lang.reflect.Constructor;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -102,7 +111,8 @@ public class LakeStreamUtils {
     }
 
     /** A store table expressed as a Paimon schema with only shared table 
options retained. */
-    public static Schema toPaimonSchema(CatalogBaseTable table) {
+    public static Schema toPaimonSchema(
+            CatalogBaseTable table, ClassLoader classLoader, ReadableConfig 
configuration) {
         if (!(table instanceof CatalogTable)) {
             throw new ValidationException(
                     "Expected a table from the Lakestream Store, but got "
@@ -114,14 +124,30 @@ public class LakeStreamUtils {
                         .partitionKeys(((CatalogTable) 
table).getPartitionKeys())
                         .options(sharedPaimonOptions(table.getOptions()))
                         .comment(table.getComment());
+        ResolvedSchema resolvedSchema =
+                table instanceof ResolvedCatalogTable
+                        ? ((ResolvedCatalogTable) table).getResolvedSchema()
+                        : null;
+        DataTypeFactory dataTypeFactory = null;
         for (org.apache.flink.table.api.Schema.UnresolvedColumn column : 
storeSchema.getColumns()) {
             if (column instanceof 
org.apache.flink.table.api.Schema.UnresolvedPhysicalColumn) {
+                AbstractDataType<?> type =
+                        
((org.apache.flink.table.api.Schema.UnresolvedPhysicalColumn) column)
+                                .getDataType();
+                DataType resolvedType;
+                if (type instanceof DataType) {
+                    resolvedType = (DataType) type;
+                } else if (resolvedSchema != null) {
+                    resolvedType = 
resolvedSchema.getColumn(column.getName()).get().getDataType();
+                } else {
+                    if (dataTypeFactory == null) {
+                        dataTypeFactory = createDataTypeFactory(classLoader, 
configuration);
+                    }
+                    resolvedType = dataTypeFactory.createDataType(type);
+                }
                 builder.column(
                         column.getName(),
-                        toPaimonType(
-                                
((org.apache.flink.table.api.Schema.UnresolvedPhysicalColumn)
-                                                column)
-                                        .getDataType()),
+                        
LogicalTypeConversion.toDataType(resolvedType.getLogicalType()),
                         column.getComment().orElse(null));
             }
         }
@@ -139,8 +165,56 @@ public class LakeStreamUtils {
                 && equalSelectedOptions(paimonSchema.options(), 
storeSchema.options());
     }
 
-    private static org.apache.paimon.types.DataType 
toPaimonType(AbstractDataType<?> type) {
-        return LogicalTypeConversion.toDataType(((DataType) 
type).getLogicalType());
+    static boolean matchesPlannedLayout(ResolvedCatalogTable planned, Schema 
storeSchema) {
+        ResolvedSchema schema = planned.getResolvedSchema();
+        RowType rowType =
+                (RowType)
+                        LogicalTypeConversion.toDataType(
+                                
schema.toPhysicalRowDataType().getLogicalType());
+        List<String> primaryKeys =
+                schema.getPrimaryKey()
+                        .map(UniqueConstraint::getColumns)
+                        .orElseGet(
+                                () -> {
+                                    CatalogTable origin = planned.getOrigin();
+                                    // Flink omits the constraint for nullable 
Paimon keys.
+                                    return origin instanceof DataCatalogTable
+                                            ? ((DataCatalogTable) 
origin).table().primaryKeys()
+                                            : Collections.emptyList();
+                                });
+        return equalFields(rowType.getFields(), storeSchema.fields())
+                && 
planned.getPartitionKeys().equals(storeSchema.partitionKeys())
+                && primaryKeys.equals(storeSchema.primaryKeys());
+    }
+
+    private static DataTypeFactory createDataTypeFactory(
+            ClassLoader classLoader, ReadableConfig configuration) {
+        try {
+            Class<?> factoryClass =
+                    Class.forName(
+                            
"org.apache.flink.table.catalog.DataTypeFactoryImpl",
+                            true,
+                            DataTypeFactory.class.getClassLoader());
+            Constructor<?> constructor;
+            try {
+                // Newer Flink versions take SerializerConfig instead of 
ExecutionConfig.
+                constructor =
+                        factoryClass.getDeclaredConstructor(
+                                ClassLoader.class,
+                                ReadableConfig.class,
+                                ExecutionConfig.class
+                                        .getMethod("getSerializerConfig")
+                                        .getReturnType());
+            } catch (NoSuchMethodException e) {
+                constructor =
+                        factoryClass.getDeclaredConstructor(
+                                ClassLoader.class, ReadableConfig.class, 
ExecutionConfig.class);
+            }
+            constructor.setAccessible(true);
+            return (DataTypeFactory) constructor.newInstance(classLoader, 
configuration, null);
+        } catch (ReflectiveOperationException e) {
+            throw new ValidationException("Could not initialize Flink's data 
type resolver.", e);
+        }
     }
 
     private static Map<String, String> sharedPaimonOptions(Map<String, String> 
options) {
diff --git 
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/JdbcCatalogViewITCase.java
 
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/JdbcCatalogViewITCase.java
index 81d5868de1..ad13ec8123 100644
--- 
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/JdbcCatalogViewITCase.java
+++ 
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/JdbcCatalogViewITCase.java
@@ -96,6 +96,15 @@ public class JdbcCatalogViewITCase extends CatalogITCaseBase 
{
         assertThat(result.toString()).contains("Charlie");
     }
 
+    @Test
+    public void testRealTimeSuffixInViewName() {
+        sql("CREATE VIEW `ordinary$rt` AS SELECT id FROM test_table");
+        assertThat(sql("SELECT id FROM `ordinary$rt`")).hasSize(3);
+
+        sql("DROP VIEW `ordinary$rt`");
+        assertThat(sql("SHOW VIEWS")).isEmpty();
+    }
+
     @Test
     public void testShowViews() {
         // Create multiple views
diff --git 
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lakestream/LakeStreamFlussITCase.java
 
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lakestream/LakeStreamFlussITCase.java
index 6e180eb180..57def7d174 100644
--- 
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lakestream/LakeStreamFlussITCase.java
+++ 
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lakestream/LakeStreamFlussITCase.java
@@ -28,6 +28,7 @@ import org.apache.paimon.schema.SchemaChange;
 import org.apache.flink.api.common.RuntimeExecutionMode;
 import org.apache.flink.configuration.Configuration;
 import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.table.api.StatementSet;
 import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
 import org.apache.flink.table.catalog.Catalog;
 import org.apache.flink.table.factories.FactoryUtil;
@@ -218,6 +219,27 @@ public class LakeStreamFlussITCase {
                 .containsExactly(Row.of(1, "x"));
     }
 
+    @Test
+    public void testWritePlannedBeforeBothSchemasChangedIsRejected() throws 
Exception {
+        StreamTableEnvironment tEnv = newTableEnv();
+        String storeTable = "fluss_store." + DATABASE + ".stale_layout";
+        tEnv.executeSql("CREATE TABLE " + storeTable + " (a INT, b INT)");
+        tEnv.executeSql(
+                "CREATE TABLE stale_layout (a INT, b INT) WITH 
('lakestream.enabled' = 'true')");
+        StatementSet delayed = tEnv.createStatementSet();
+        delayed.addInsertSql("INSERT INTO stale_layout VALUES (11, 22)");
+
+        tEnv.executeSql("ALTER TABLE stale_layout MODIFY b INT FIRST");
+        tEnv.executeSql("DROP TABLE " + storeTable);
+        tEnv.executeSql("CREATE TABLE " + storeTable + " (b INT, a INT)");
+
+        tEnv.executeSql("INSERT INTO stale_layout VALUES (44, 33)").await();
+        assertThatThrownBy(() -> delayed.execute().await())
+                .hasStackTraceContaining("Replan the statement");
+        assertThat(queryRows(tEnv, "SELECT a, b FROM stale_layout$rt " + 
BOUNDED_SCAN))
+                .containsExactly(Row.of(33, 44));
+    }
+
     @Test
     public void testNestedColumnCommentChangeDoesNotRejectWrites() throws 
Exception {
         StreamTableEnvironment tEnv = newTableEnv();
diff --git 
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lakestream/LakeStreamRoutingITCase.java
 
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lakestream/LakeStreamRoutingITCase.java
index c96667dddf..17c5a9acb4 100644
--- 
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lakestream/LakeStreamRoutingITCase.java
+++ 
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lakestream/LakeStreamRoutingITCase.java
@@ -226,6 +226,21 @@ public class LakeStreamRoutingITCase {
         assertThat(FakeStoreData.rows("default.t1")).hasSize(1);
     }
 
+    @Test
+    public void testLakeStreamBranchWriteIsRejectedBeforeOpeningTheStore() 
throws Exception {
+        StreamTableEnvironment batch = newBatchEnvWithLakeStreamTable("t1");
+        batch.executeSql("CALL sys.create_branch('default.t1', 'work')");
+
+        assertThatThrownBy(() -> batch.executeSql("INSERT INTO 
`t1$branch_work` VALUES (1)"))
+                .hasStackTraceContaining("only serves the main branch");
+        assertThat(FakeStoreCatalogFactory.createdCatalogs()).isEmpty();
+
+        batch.executeSql("ALTER TABLE `t1$branch_work` SET 
('lakestream.enabled' = 'false')");
+        batch.executeSql("INSERT INTO `t1$branch_work` VALUES (1)").await();
+        assertThat(queryIds(batch, "SELECT id FROM 
`t1$branch_work`")).containsExactly(1);
+        assertThat(queryIds(batch, "SELECT id FROM t1")).isEmpty();
+    }
+
     @Test
     public void testConnectorMappingToALakeStreamTableIsRejected() throws 
Exception {
         StreamTableEnvironment batch = newBatchEnvWithLakeStreamTable("t1");
diff --git 
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lakestream/LakeStreamTableFactoryTest.java
 
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lakestream/LakeStreamTableFactoryTest.java
index be787d3dc4..3708afcd89 100644
--- 
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lakestream/LakeStreamTableFactoryTest.java
+++ 
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lakestream/LakeStreamTableFactoryTest.java
@@ -31,6 +31,7 @@ import org.apache.paimon.flink.source.DataTableSource;
 import org.apache.paimon.fs.IsolatedDirectoryFileIO;
 import org.apache.paimon.options.CatalogOptions;
 import org.apache.paimon.options.Options;
+import org.apache.paimon.schema.SchemaChange;
 import org.apache.paimon.table.FileStoreTable;
 import org.apache.paimon.table.FormatTable;
 
@@ -425,14 +426,13 @@ public class LakeStreamTableFactoryTest {
     }
 
     @Test
-    public void testRealTimeWriteInConnectorModeIsRejected() throws Exception {
+    public void testRealTimeWriteToALakeStreamConnectorMappingIsRejected() 
throws Exception {
         FlinkCatalog catalog = newCatalog(null);
-        // a plain table, so the name alone has to be enough to refuse the 
read-only view
-        createTable(catalog, T2, false);
-        ResolvedCatalogTable paimonTable = resolved(catalog.getTable(T2), 
idSchema());
+        createTable(catalog, T1, true);
+        ResolvedCatalogTable paimonTable = resolved(catalog.getTable(T1), 
idSchema());
         FlinkTableFactory factory = new FlinkTableFactory();
 
-        assertThatThrownBy(() -> 
factory.createDynamicTableSink(context(id("t2$rt"), paimonTable)))
+        assertThatThrownBy(() -> 
factory.createDynamicTableSink(context(id("t1$rt"), paimonTable)))
                 .isInstanceOf(ValidationException.class)
                 .hasMessageContaining(CatalogOptions.LAKE_STREAM_STORE.key());
         assertThat(FakeStoreTableFactory.sinkContexts()).isEmpty();
@@ -725,9 +725,10 @@ public class LakeStreamTableFactoryTest {
         ResolvedCatalogTable pathOnly = pathOnlyMapping(location, 
Collections.emptyMap());
         FlinkTableFactory factory = new FlinkTableFactory();
 
-        DynamicTableSink sink = 
factory.createDynamicTableSink(context(id("t2"), pathOnly));
+        DynamicTableFactory.Context mapping = context(id("t2$rt"), pathOnly);
 
-        assertThat(sink).isInstanceOf(FlinkTableSink.class);
+        
assertThat(factory.createDynamicTableSource(mapping)).isInstanceOf(DataTableSource.class);
+        
assertThat(factory.createDynamicTableSink(mapping)).isInstanceOf(FlinkTableSink.class);
         assertThat(FakeStoreTableFactory.sinkContexts()).isEmpty();
     }
 
@@ -755,13 +756,19 @@ public class LakeStreamTableFactoryTest {
         // same name and count, so only the type can tell the two columns apart
         ResolvedSchema schema = bigIntIdSchema();
         createTable(catalog, T1, true, schema);
+        catalog.catalog()
+                .alterTable(
+                        Identifier.create("db1", "t1"),
+                        SchemaChange.setOption("s3.secret-key", 
"review-test-credential"),
+                        false);
         ResolvedCatalogTable paimonTable = resolved(catalog.getTable(T1), 
schema);
         FlinkTableFactory factory = (FlinkTableFactory) 
catalog.getFactory().get();
 
         assertThatThrownBy(() -> 
factory.createDynamicTableSink(context(id("t1"), paimonTable)))
                 .isInstanceOf(ValidationException.class)
                 .hasMessageContaining("`id` INT")
-                .hasMessageContaining("`id` BIGINT");
+                .hasMessageContaining("`id` BIGINT")
+                .hasMessageNotContaining("review-test-credential");
         assertThat(FakeStoreTableFactory.sinkContexts()).isEmpty();
         catalog.close();
     }
diff --git 
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lakestream/LakeStreamUtilsTest.java
 
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lakestream/LakeStreamUtilsTest.java
index a3121300d3..70a6d708ed 100644
--- 
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lakestream/LakeStreamUtilsTest.java
+++ 
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/lakestream/LakeStreamUtilsTest.java
@@ -28,6 +28,7 @@ import org.apache.paimon.types.MapType;
 import org.apache.paimon.types.MultisetType;
 import org.apache.paimon.types.RowType;
 
+import org.apache.flink.configuration.Configuration;
 import org.apache.flink.table.api.DataTypes;
 import org.apache.flink.table.catalog.CatalogTable;
 import org.junit.jupiter.api.Test;
@@ -59,7 +60,7 @@ public class LakeStreamUtilsTest {
                         Collections.singletonList("id"),
                         options);
 
-        Schema converted = LakeStreamUtils.toPaimonSchema(storeTable);
+        Schema converted = toPaimonSchema(storeTable);
 
         assertThat(converted.rowType().getFieldNames()).containsExactly("id");
         assertThat(
@@ -78,6 +79,30 @@ public class LakeStreamUtilsTest {
         assertThat(converted.comment()).isEqualTo("store comment");
     }
 
+    @Test
+    public void testStoreSchemaWithUnresolvedTypes() {
+        CatalogTable store =
+                storeTable(
+                        org.apache.flink.table.api.Schema.newBuilder()
+                                .column("id", "INT NOT NULL")
+                                .column("nested", "ARRAY<ROW<item BIGINT>>")
+                                .primaryKey("id")
+                                .build(),
+                        Collections.emptyList(),
+                        Collections.emptyMap());
+
+        Schema schema = toPaimonSchema(store);
+        assertThat(schema.fields().get(0).type())
+                .isEqualTo(org.apache.paimon.types.DataTypes.INT().notNull());
+        
assertThat(schema.fields().get(1).type()).isInstanceOf(ArrayType.class);
+        assertThat(schema.primaryKeys()).containsExactly("id");
+    }
+
+    private static Schema toPaimonSchema(CatalogTable table) {
+        return LakeStreamUtils.toPaimonSchema(
+                table, LakeStreamUtilsTest.class.getClassLoader(), new 
Configuration());
+    }
+
     @Test
     public void testCompatibilityIncludesPrimaryKeys() {
         Schema paimon =
@@ -98,8 +123,7 @@ public class LakeStreamUtilsTest {
                         Collections.emptyList(),
                         Collections.emptyMap());
 
-        assertThat(LakeStreamUtils.isCompatible(paimon, 
LakeStreamUtils.toPaimonSchema(store)))
-                .isFalse();
+        assertThat(LakeStreamUtils.isCompatible(paimon, 
toPaimonSchema(store))).isFalse();
     }
 
     @Test
@@ -119,8 +143,7 @@ public class LakeStreamUtilsTest {
                         Collections.emptyList(),
                         Collections.emptyMap());
 
-        assertThat(LakeStreamUtils.isCompatible(paimon, 
LakeStreamUtils.toPaimonSchema(store)))
-                .isFalse();
+        assertThat(LakeStreamUtils.isCompatible(paimon, 
toPaimonSchema(store))).isFalse();
     }
 
     @Test
@@ -144,8 +167,7 @@ public class LakeStreamUtilsTest {
                         Collections.emptyList(),
                         storeOptions);
 
-        assertThat(LakeStreamUtils.isCompatible(paimon, 
LakeStreamUtils.toPaimonSchema(store)))
-                .isFalse();
+        assertThat(LakeStreamUtils.isCompatible(paimon, 
toPaimonSchema(store))).isFalse();
     }
 
     @Test
@@ -168,8 +190,7 @@ public class LakeStreamUtilsTest {
                         Collections.emptyList(),
                         Collections.emptyMap());
 
-        assertThat(LakeStreamUtils.isCompatible(paimon, 
LakeStreamUtils.toPaimonSchema(store)))
-                .isFalse();
+        assertThat(LakeStreamUtils.isCompatible(paimon, 
toPaimonSchema(store))).isFalse();
     }
 
     @Test
@@ -195,8 +216,7 @@ public class LakeStreamUtilsTest {
                         Collections.emptyList(),
                         Collections.emptyMap());
 
-        assertThat(LakeStreamUtils.isCompatible(paimon, 
LakeStreamUtils.toPaimonSchema(store)))
-                .isTrue();
+        assertThat(LakeStreamUtils.isCompatible(paimon, 
toPaimonSchema(store))).isTrue();
     }
 
     @Test
@@ -229,8 +249,7 @@ public class LakeStreamUtilsTest {
                         Collections.emptyList(),
                         Collections.emptyMap());
 
-        assertThat(LakeStreamUtils.isCompatible(paimon, 
LakeStreamUtils.toPaimonSchema(store)))
-                .isTrue();
+        assertThat(LakeStreamUtils.isCompatible(paimon, 
toPaimonSchema(store))).isTrue();
     }
 
     @Test
@@ -258,8 +277,7 @@ public class LakeStreamUtilsTest {
                         Collections.emptyList(),
                         Collections.emptyMap());
 
-        assertThat(LakeStreamUtils.isCompatible(paimon, 
LakeStreamUtils.toPaimonSchema(store)))
-                .isFalse();
+        assertThat(LakeStreamUtils.isCompatible(paimon, 
toPaimonSchema(store))).isFalse();
     }
 
     @Test
@@ -292,8 +310,7 @@ public class LakeStreamUtilsTest {
                         Collections.emptyList(),
                         storeOptions);
 
-        assertThat(LakeStreamUtils.isCompatible(paimon, 
LakeStreamUtils.toPaimonSchema(store)))
-                .isTrue();
+        assertThat(LakeStreamUtils.isCompatible(paimon, 
toPaimonSchema(store))).isTrue();
     }
 
     @Test

Reply via email to