github-actions[bot] commented on code in PR #62526:
URL: https://github.com/apache/doris/pull/62526#discussion_r3108084151


##########
fe/fe-core/src/main/java/org/apache/doris/tablefunction/CdcStreamTableValuedFunction.java:
##########
@@ -61,23 +61,32 @@ public CdcStreamTableValuedFunction(Map<String, String> 
properties) throws Analy
     private void processProps(Map<String, String> properties) throws 
AnalysisException {
         Map<String, String> copyProps = new HashMap<>(properties);
         copyProps.put("format", "json");
+
+        // Standalone TVF: random jobId. TVF-in-job: job.id injected by 
rewriteTvfParams.
+        String jobId = copyProps.computeIfAbsent(JOB_ID_KEY,
+                k -> UUID.randomUUID().toString().replace("-", ""));
+
+        // Default PG slot/pub so cdcclient auto-creates per-job resources
+        StreamingJobUtils.populateDefaultSourceProperties(

Review Comment:
   Blocking: this changes the effective publication name for legacy 
`cdc_stream` streaming jobs after FE restart/upgrade.
   
   For jobs created before this PR, the persisted SQL does not contain 
`publication_name`, so the old TVF path used Debezium's default 
`dbz_publication`. After replay, `StreamingInsertJob` rebuilds the TVF from 
that old SQL, comes through `processProps()`, and this line now injects 
`doris_pub_{jobId}` instead. The FROM-TO path has a compatibility fallback in 
`PostgresSourceReader.resolvePublicationName()`, but the TVF path never reaches 
it because the new name is materialized here first.
   
   That means an existing TVF-backed PG job can reconnect with a different 
publication after upgrade, require new CREATE/ownership privileges, and skip 
cleaning up the legacy publication it previously used. We need a compatibility 
branch for replayed jobs whose SQL/persisted props do not already carry 
`publication_name`.



##########
fe/fe-core/src/main/java/org/apache/doris/job/extensions/insert/streaming/PostgresResourceValidator.java:
##########
@@ -0,0 +1,169 @@
+// 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.
+
+package org.apache.doris.job.extensions.insert.streaming;
+
+import org.apache.doris.datasource.jdbc.client.JdbcClient;
+import org.apache.doris.job.cdc.DataSourceConfigKeys;
+import org.apache.doris.job.common.DataSourceType;
+import org.apache.doris.job.exception.JobException;
+import org.apache.doris.job.util.StreamingJobUtils;
+
+import org.apache.commons.lang3.StringUtils;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Fail-fast validation of PostgreSQL replication slot and publication at 
CREATE JOB time,
+ * before the CDC client connects. Catches mistakes (user-provided 
slot/publication missing,
+ * conflicting jobId) with actionable errors. Validation runs only on initial 
create; restarts
+ * skip this path by design, so an active slot held by the previous BE does 
not self-conflict.
+ */
+public class PostgresResourceValidator {
+
+    public static void validate(Map<String, String> sourceProperties, String 
jobId, List<String> tableNames)
+            throws JobException {
+        String slotName = resolveSlotName(sourceProperties, jobId);
+        String publicationName = resolvePublicationName(sourceProperties, 
jobId);
+        // Pattern-match ownership: name equals the default = Doris-owned 
(auto); otherwise user.
+        String defaultSlot = DataSourceConfigKeys.defaultSlotName(jobId);
+        String defaultPub = DataSourceConfigKeys.defaultPublicationName(jobId);
+        boolean slotUserProvided = !defaultSlot.equals(slotName);
+        boolean pubUserProvided = !defaultPub.equals(publicationName);
+        String pgSchema = sourceProperties.get(DataSourceConfigKeys.SCHEMA);
+        List<String> qualifiedTables = new ArrayList<>();
+        for (String name : tableNames) {
+            qualifiedTables.add(pgSchema + "." + name);
+        }
+
+        JdbcClient jdbcClient = 
StreamingJobUtils.getJdbcClient(DataSourceType.POSTGRES, sourceProperties);
+        try (Connection conn = jdbcClient.getConnection()) {
+            boolean pubExists = publicationExists(conn, publicationName);
+            if (!pubExists && pubUserProvided) {
+                throw new JobException(
+                        "publication does not exist: " + publicationName
+                                + ". Create it before starting the job or omit 
"
+                                + DataSourceConfigKeys.PUBLICATION_NAME
+                                + " to let Doris create one.");
+            }
+            if (pubExists) {
+                List<String> missing = findMissingTables(conn, 
publicationName, qualifiedTables);

Review Comment:
   Blocking: for partitioned root tables, "publication exists and covers the 
table name" is not a sufficient correctness check.
   
   A user-managed publication created as `CREATE PUBLICATION pub FOR TABLE 
schema.orders` passes `pg_publication_tables`, but if 
`pg_publication.pubviaroot` is false (the default) PostgreSQL publishes changes 
under the child partition identities. Doris still builds its capture set from 
`include_tables=orders`, so those partition events can be silently skipped even 
though validation succeeded.
   
   The auto-created path avoids this by using `WITH (publish_via_partition_root 
= true)`, so the validator needs to reject or repair existing publications that 
do not have `pubviaroot` when any configured table is a partitioned root.



##########
fs_brokers/cdc_client/src/main/java/org/apache/doris/cdcclient/source/reader/postgres/PostgresSourceReader.java:
##########
@@ -93,9 +95,13 @@ public PostgresSourceReader() {
     public void initialize(String jobId, DataSource dataSource, Map<String, 
String> config) {
         PostgresSourceConfig sourceConfig = generatePostgresConfig(config, 
jobId, 0);
         PostgresDialect dialect = new PostgresDialect(sourceConfig);
-        synchronized (SLOT_CREATION_LOCK) {
-            LOG.info("Creating slot for job {}, user {}", jobId, 
sourceConfig.getUsername());
-            createSlotForGlobalStreamSplit(dialect);
+        // Only create the slot when Doris owns it (name == default); 
user-provided slots must
+        // pre-exist, validated at CREATE JOB.

Review Comment:
   Blocking: this only skips the eager FE-side slot creation. It does not stop 
Debezium from auto-creating a missing user-supplied slot later.
   
   `PostgresReplicationConnection.initReplicationSlot()` still calls 
`createReplicationSlot()` whenever `getSlotInfo()` returns `INVALID`. So on the 
standalone TVF path, `select * from cdc_stream(..., "slot_name" = "foo")` will 
create `foo` if it does not already exist, and `close()` will preserve it 
because `isSlotDorisOwned()` is false. That leaks a replication slot for every 
typo/missing user slot instead of failing.
   
   If the ownership contract is "user-provided slot must pre-exist and Doris 
never owns/drops it", the cdc client also has to reject missing user-owned 
slots rather than auto-creating them.



##########
fe/fe-core/src/main/java/org/apache/doris/job/util/StreamingJobUtils.java:
##########
@@ -448,6 +449,73 @@ public static List<Column> getColumns(JdbcClient 
jdbcClient,
      * The remoteDB implementation differs for each data source;
      * refer to the hierarchical mapping in the JDBC catalog.
      */
+    /**
+     * Populate default resource names into properties, then validate. No-op 
for sources that
+     * don't need it. Mutates properties: callers should expect default values 
to be inserted.
+     */
+    public static void resolveAndValidateSource(DataSourceType sourceType,
+                                                Map<String, String> properties,
+                                                String jobId,
+                                                List<String> tables) throws 
JobException {
+        if (sourceType == DataSourceType.POSTGRES) {
+            // PG slot/pub: values equal to default = Doris-owned; any other 
value = user-owned.
+            // (users cannot specify default names since jobId is unknown 
pre-CREATE)
+            properties.putIfAbsent(DataSourceConfigKeys.SLOT_NAME,
+                    DataSourceConfigKeys.defaultSlotName(jobId));
+            properties.putIfAbsent(DataSourceConfigKeys.PUBLICATION_NAME,
+                    DataSourceConfigKeys.defaultPublicationName(jobId));
+            validateSource(sourceType, properties, jobId, tables);
+        }
+    }
+
+    public static void validateSource(DataSourceType sourceType,
+            Map<String, String> properties,
+            String jobId,
+            List<String> tables) throws JobException {
+        if (sourceType == DataSourceType.POSTGRES) {
+            PostgresResourceValidator.validate(properties, jobId, tables);
+        }
+    }
+
+    /**
+     * Validate source-side resources for a streaming job backed by a TVF. 
Only cdc_stream
+     * TVF is subject to source validation (e.g. PG slot/publication 
ownership); other TVFs
+     * (s3, ...) are no-ops.
+     *
+     * <p>originTvfProps is treated as read-only (Nereids may hand back an 
immutable map).
+     * Defaults are populated into a temporary copy so ownership checks see 
the effective
+     * slot/pub names without mutating the caller's map.
+     */
+    public static void validateTvfSource(String tvfType,
+                                         Map<String, String> originTvfProps,
+                                         String jobId) throws JobException {
+        if (!"cdc_stream".equalsIgnoreCase(tvfType)) {
+            return;
+        }
+        DataSourceType sourceType = DataSourceType.valueOf(
+                originTvfProps.get(DataSourceConfigKeys.TYPE).toUpperCase());
+        List<String> tables = Collections.singletonList(
+                originTvfProps.get(DataSourceConfigKeys.TABLE));
+        Map<String, String> effective = new HashMap<>(originTvfProps);
+        populateDefaultSourceProperties(sourceType, effective, jobId);

Review Comment:
   Blocking: the `CREATE JOB ... DO INSERT ... SELECT FROM cdc_stream(...)` 
path still bypasses the new FE identifier validation.
   
   `CreateJobCommand.validate()` only calls 
`DataSourceConfigValidator.validateSource()` for `FROM POSTGRES` jobs. Here 
`validateTvfSource()` goes straight to `PostgresResourceValidator`, so 
`slot_name` / `publication_name` values like `Bad-Name` or `pub;drop` are 
accepted in the TVF-backed job path even though the PR description says 
CREATE-time validation now covers both paths. Those raw values later reach the 
cdc client DDL and fail only at runtime.
   
   Please run the same `DataSourceConfigValidator.validateSource()` checks on 
the TVF props before `PostgresResourceValidator.validate()`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to