You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by "jnh5y (via GitHub)" <gi...@apache.org> on 2026/06/26 21:13:04 UTC

[PR] [FLINK-40002][table] Fix PushFilterInCalcIntoTableSourceScanRule for metadata filter push-down [flink]

jnh5y opened a new pull request, #28556:
URL: https://github.com/apache/flink/pull/28556

   ## What is the purpose of the change
   
   `PushFilterInCalcIntoTableSourceScanRule` — the rule that fires when a `Filter` sits above a `Calc` above a table source scan — was unaware of metadata filter push-down, causing two bugs:
   
   1. **Crash on compiled-plan restore.** For sources implementing both `SupportsFilterPushDown` and `SupportsReadingMetadata`, the rule routed all predicates (including metadata-column predicates) through the physical path, storing a `FilterPushDownSpec` with raw `RexInputRef` indices. When `ProjectPushDownSpec` later narrowed the scan's row type, those indices no longer corresponded to the right columns, crashing restore.
   
   2. **Missed push-down for metadata-only sources.** The rule's `matches()` guard only checked `canPushdownFilter()` (physical), so for sources implementing only `SupportsReadingMetadata` the rule never fired at all.
   
   This PR also fixes a latent classification bug in both rules: the old heuristic detected metadata columns via `inputRef.getIndex() >= physicalColumnCount`, which is incorrect after projection narrows the scan type. Mixed predicates like `OR(id > 0, m0 > 0)` (spanning physical and metadata columns) must stay as runtime Calc filters but were instead routed into the physical push-down path.
   
   ## Brief change log
   
     - `PushFilterInCalcIntoTableSourceScanRule.matches()` now also checks `canPushdownMetadataFilter()`, enabling the rule to fire for metadata-only sources
     - Extract duplicated classify-and-push logic into `classifyAndPushFilters()` in `PushFilterIntoSourceScanRuleBase`, shared by both filter-push-down rules
     - Replace the `physicalColumnCount` heuristic with a `Set<Integer>` of metadata column indices derived from the scan's current row type via the column-to-metadata-key map, correctly handling projection-narrowed scans
     - Add `referencesAnyMetadataColumns()` to detect mixed predicates and route them to the runtime Calc instead of the physical push-down path
     - Document the identity contract on `SupportsReadingMetadata.applyMetadataFilters` Javadoc
   
   ## Verifying this change
   
   This change added tests and can be verified as follows:
   
     - Added `testMixedOrPredicateStaysAsRuntimeFilter` to `MetadataFilterResultShapesITCase`: asserts that a predicate touching both physical and metadata columns (`id < 3 OR m0 > 0`) never appears in `filter=[...]` or `metadataFilter=[...]` and produces correct runtime results
     - Added `testMixedOrWithSeparatePhysicalPredicate` to `MetadataFilterResultShapesITCase`: asserts that a pure physical predicate is still pushed while a mixed OR predicate stays as a runtime Calc
     - Existing `MetadataFilterResultShapesITCase` tests (accept-all, accept-none, partial accept, best-effort overlap) continue to pass, covering the `PushFilterInCalcIntoTableSourceScanRule` path via the shared `classifyAndPushFilters()` method
   
   ## Does this pull request potentially affect one of the following parts:
   
     - Dependencies (does it add or upgrade a dependency): no
     - The public API, i.e., is any changed class annotated with `@Public(Evolving)`: yes (`SupportsReadingMetadata` — Javadoc only, no interface change)
     - The serializers: no
     - The runtime per-record code paths (performance sensitive): no
     - Anything that affects deployment or recovery: JobManager (and its components), Checkpointing, Kubernetes/Yarn, ZooKeeper: no
     - The S3 file system connector: no
   
   ## Documentation
   
     - Does this pull request introduce a new feature? no
     - If yes, how is the feature documented? not applicable
   
   ---
   
   ##### Was generative AI tooling used to co-author this PR?
   
   - [X] Yes (Claude Sonnet 4.6)
   
   <!--
   Generated-by: Claude Sonnet 4.6
   -->
   


-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table] Fix PushFilterInCalcIntoTableSourceScanRule for metadata filter push-down [flink]

Posted by "flinkbot (via GitHub)" <gi...@apache.org>.
flinkbot commented on PR #28556:
URL: https://github.com/apache/flink/pull/28556#issuecomment-4813537334

   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "649290bd1c244af1f2c140f03bc31220a6d3c877",
       "status" : "UNKNOWN",
       "url" : "TBD",
       "triggerID" : "649290bd1c244af1f2c140f03bc31220a6d3c877",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 649290bd1c244af1f2c140f03bc31220a6d3c877 UNKNOWN
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run azure` re-run the last Azure build
   </details>


-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table] Fix PushFilterInCalcIntoTableSourceScanRule for metadata filter push-down [flink]

Posted by "snuyanzin (via GitHub)" <gi...@apache.org>.
snuyanzin commented on code in PR #28556:
URL: https://github.com/apache/flink/pull/28556#discussion_r3494044607


##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushFilterIntoSourceScanRuleBase.java:
##########
@@ -113,6 +114,82 @@ protected RexNode createRemainingCondition(
         return new Tuple2<>(result, newTableSourceTable);
     }
 
+    /**
+     * Classifies convertible predicates into physical and metadata, pushes each through the
+     * appropriate path, and returns the updated table plus any remaining predicates.
+     */
+    protected FilterClassificationResult classifyAndPushFilters(
+            RexNode[] convertiblePredicates,
+            TableSourceTable tableSourceTable,
+            TableScan scan,
+            RelBuilder relBuilder) {
+
+        boolean supportsPhysicalFilter = canPushdownFilter(tableSourceTable);
+        boolean supportsMetadataFilter = canPushdownMetadataFilter(tableSourceTable);
+        Set<Integer> metadataColumnIndices = metadataColumnIndices(tableSourceTable, scan);
+
+        List<RexNode> allRemainingRexNodes = new ArrayList<>();
+        TableSourceTable currentTable = tableSourceTable;
+
+        List<RexNode> physicalPredicates = new ArrayList<>();
+        List<RexNode> metadataPredicates = new ArrayList<>();
+        for (RexNode predicate : convertiblePredicates) {
+            if (referencesOnlyMetadataColumns(predicate, metadataColumnIndices)) {
+                if (supportsMetadataFilter) {
+                    metadataPredicates.add(predicate);
+                } else {
+                    allRemainingRexNodes.add(predicate);
+                }
+            } else if (referencesAnyMetadataColumns(predicate, metadataColumnIndices)) {

Review Comment:
   why do we need to invoke same method 2 times per iteration if we could have all the data after the first call?



-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table] Fix PushFilterInCalcIntoTableSourceScanRule for metadata filter push-down [flink]

Posted by "snuyanzin (via GitHub)" <gi...@apache.org>.
snuyanzin commented on code in PR #28556:
URL: https://github.com/apache/flink/pull/28556#discussion_r3494216189


##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushFilterInCalcIntoTableSourceScanRule.java:
##########
@@ -94,33 +95,29 @@ private void pushFilterIntoScan(
         RexNode[] convertiblePredicates = extractedPredicates._1;
         RexNode[] unconvertedPredicates = extractedPredicates._2;
         if (convertiblePredicates.length == 0) {
-            // no condition can be translated to expression
             return;
         }
 
-        Tuple2<SupportsFilterPushDown.Result, TableSourceTable> pushdownResultWithScan =
-                resolveFiltersAndCreateTableSourceTable(
-                        convertiblePredicates,
-                        relOptTable.unwrap(TableSourceTable.class),
-                        scan,
-                        relBuilder);
+        FilterClassificationResult result =
+                classifyAndPushFilters(convertiblePredicates, tableSourceTable, scan, relBuilder);
+        if (result == null) {
+            return;
+        }
 
-        SupportsFilterPushDown.Result result = pushdownResultWithScan._1;
-        TableSourceTable tableSourceTable = pushdownResultWithScan._2;
+        List<RexNode> allRemainingRexNodes = new ArrayList<>(result.remainingPredicates);
+        allRemainingRexNodes.addAll(Arrays.asList(unconvertedPredicates));
 
         FlinkLogicalTableSourceScan newScan =
                 FlinkLogicalTableSourceScan.create(
-                        scan.getCluster(), scan.getHints(), tableSourceTable);
+                        scan.getCluster(), scan.getHints(), result.updatedTable);
 
         // build new calc program
         RexProgramBuilder programBuilder =
                 RexProgramBuilder.forProgram(originProgram, call.builder().getRexBuilder(), true);
         programBuilder.clearCondition();
 
-        if (!result.getRemainingFilters().isEmpty() || unconvertedPredicates.length != 0) {
-            RexNode remainingCondition =
-                    createRemainingCondition(

Review Comment:
   is this method still used?



-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table] Fix PushFilterInCalcIntoTableSourceScanRule for metadata filter push-down [flink]

Posted by "snuyanzin (via GitHub)" <gi...@apache.org>.
snuyanzin commented on code in PR #28556:
URL: https://github.com/apache/flink/pull/28556#discussion_r3489689652


##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushFilterInCalcIntoTableSourceScanRule.java:
##########
@@ -94,33 +95,29 @@ private void pushFilterIntoScan(
         RexNode[] convertiblePredicates = extractedPredicates._1;
         RexNode[] unconvertedPredicates = extractedPredicates._2;
         if (convertiblePredicates.length == 0) {
-            // no condition can be translated to expression
             return;
         }
 
-        Tuple2<SupportsFilterPushDown.Result, TableSourceTable> pushdownResultWithScan =
-                resolveFiltersAndCreateTableSourceTable(
-                        convertiblePredicates,
-                        relOptTable.unwrap(TableSourceTable.class),
-                        scan,
-                        relBuilder);
+        FilterClassificationResult result =
+                classifyAndPushFilters(convertiblePredicates, tableSourceTable, scan, relBuilder);
+        if (result == null) {
+            return;
+        }
 
-        SupportsFilterPushDown.Result result = pushdownResultWithScan._1;
-        TableSourceTable tableSourceTable = pushdownResultWithScan._2;
+        List<RexNode> allRemainingRexNodes = new ArrayList<>(result.remainingPredicates);

Review Comment:
   we are changing a rule and no test with plans?



-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table-planner] Keep metadata column references out of physical filter push-down [flink]

Posted by "snuyanzin (via GitHub)" <gi...@apache.org>.
snuyanzin merged PR #28556:
URL: https://github.com/apache/flink/pull/28556


-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table-planner] Keep metadata column references out of physical filter push-down [flink]

Posted by "snuyanzin (via GitHub)" <gi...@apache.org>.
snuyanzin commented on code in PR #28556:
URL: https://github.com/apache/flink/pull/28556#discussion_r4296025963


##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushFilterIntoSourceScanRuleBase.java:
##########
@@ -137,72 +208,43 @@ protected boolean canPushdownMetadataFilter(TableSourceTable tableSourceTable) {
                 .noneMatch(spec -> spec instanceof MetadataFilterPushDownSpec);
     }
 
-    /**
-     * True if predicate references metadata columns exclusively (no physical columns).
-     *
-     * <p>A predicate like {@code OR(physical_pred, metadata_pred)} returns false because it
-     * references both physical and metadata columns. Mixed predicates remain as runtime filters.
-     */
-    protected boolean referencesOnlyMetadataColumns(RexNode predicate, int physicalColumnCount) {
-        boolean[] saw = new boolean[2]; // [0] = sawPhysical, [1] = sawMetadata
-        predicate.accept(
-                new RexVisitorImpl<Void>(true) {
-                    @Override
-                    public Void visitInputRef(RexInputRef inputRef) {
-                        if (inputRef.getIndex() >= physicalColumnCount) {
-                            saw[1] = true;
-                        } else {
-                            saw[0] = true;
-                        }
-                        return null;
-                    }
-                });
-        return saw[1] && !saw[0];
+    private enum FilterColumnKind {
+        PHYSICAL_ONLY,
+        METADATA_ONLY,
+        MIXED
     }
 
-    /** Number of physical columns in the scan's schema. */
-    protected int getPhysicalColumnCount(TableSourceTable tableSourceTable) {
-        ResolvedSchema schema = tableSourceTable.contextResolvedTable().getResolvedSchema();
-        return (int) schema.getColumns().stream().filter(Column::isPhysical).count();
-    }
-
-    /** Maps SQL column names to metadata keys for metadata columns. */
-    protected Map<String, String> buildColumnToMetadataKeyMap(TableSourceTable tableSourceTable) {
-        ResolvedSchema schema = tableSourceTable.contextResolvedTable().getResolvedSchema();
-        Map<String, String> mapping = new HashMap<>();
-        for (Column col : schema.getColumns()) {
-            if (col instanceof Column.MetadataColumn) {
-                Column.MetadataColumn metaCol = (Column.MetadataColumn) col;
-                String sqlName = metaCol.getName();
-                String metadataKey = metaCol.getMetadataKey().orElse(sqlName);
-                mapping.put(sqlName, metadataKey);
-            }
+    private static FilterColumnKind classifyColumns(RexNode predicate, int firstMetadataIndex) {
+        ImmutableBitSet columns = RelOptUtil.InputFinder.bits(predicate);
+        boolean referencesMetadata = columns.nextSetBit(firstMetadataIndex) >= 0;
+        boolean referencesPhysical = !columns.get(0, firstMetadataIndex).isEmpty();

Review Comment:
   such `get` make extra allocation
   can we replace it with something like 
   ```java
           int firstPhysical = columns.nextSetBit(0);
           boolean referencesPhysical = firstPhysical >= 0 && firstPhysical < firstMetadataIndex;
   ```



##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushFilterIntoSourceScanRuleBase.java:
##########
@@ -137,72 +208,43 @@ protected boolean canPushdownMetadataFilter(TableSourceTable tableSourceTable) {
                 .noneMatch(spec -> spec instanceof MetadataFilterPushDownSpec);
     }
 
-    /**
-     * True if predicate references metadata columns exclusively (no physical columns).
-     *
-     * <p>A predicate like {@code OR(physical_pred, metadata_pred)} returns false because it
-     * references both physical and metadata columns. Mixed predicates remain as runtime filters.
-     */
-    protected boolean referencesOnlyMetadataColumns(RexNode predicate, int physicalColumnCount) {
-        boolean[] saw = new boolean[2]; // [0] = sawPhysical, [1] = sawMetadata
-        predicate.accept(
-                new RexVisitorImpl<Void>(true) {
-                    @Override
-                    public Void visitInputRef(RexInputRef inputRef) {
-                        if (inputRef.getIndex() >= physicalColumnCount) {
-                            saw[1] = true;
-                        } else {
-                            saw[0] = true;
-                        }
-                        return null;
-                    }
-                });
-        return saw[1] && !saw[0];
+    private enum FilterColumnKind {
+        PHYSICAL_ONLY,
+        METADATA_ONLY,
+        MIXED
     }
 
-    /** Number of physical columns in the scan's schema. */
-    protected int getPhysicalColumnCount(TableSourceTable tableSourceTable) {
-        ResolvedSchema schema = tableSourceTable.contextResolvedTable().getResolvedSchema();
-        return (int) schema.getColumns().stream().filter(Column::isPhysical).count();
-    }
-
-    /** Maps SQL column names to metadata keys for metadata columns. */
-    protected Map<String, String> buildColumnToMetadataKeyMap(TableSourceTable tableSourceTable) {
-        ResolvedSchema schema = tableSourceTable.contextResolvedTable().getResolvedSchema();
-        Map<String, String> mapping = new HashMap<>();
-        for (Column col : schema.getColumns()) {
-            if (col instanceof Column.MetadataColumn) {
-                Column.MetadataColumn metaCol = (Column.MetadataColumn) col;
-                String sqlName = metaCol.getName();
-                String metadataKey = metaCol.getMetadataKey().orElse(sqlName);
-                mapping.put(sqlName, metadataKey);
-            }
+    private static FilterColumnKind classifyColumns(RexNode predicate, int firstMetadataIndex) {
+        ImmutableBitSet columns = RelOptUtil.InputFinder.bits(predicate);
+        boolean referencesMetadata = columns.nextSetBit(firstMetadataIndex) >= 0;
+        boolean referencesPhysical = !columns.get(0, firstMetadataIndex).isEmpty();

Review Comment:
   nit:
   such `get` make extra allocation
   can we replace it with something like 
   ```java
           int firstPhysical = columns.nextSetBit(0);
           boolean referencesPhysical = firstPhysical >= 0 && firstPhysical < firstMetadataIndex;
   ```



-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table-planner] Keep metadata column references out of physical filter push-down [flink]

Posted by "jnh5y (via GitHub)" <gi...@apache.org>.
jnh5y commented on code in PR #28556:
URL: https://github.com/apache/flink/pull/28556#discussion_r4317897900


##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushFilterIntoSourceScanRuleBase.java:
##########
@@ -137,72 +208,43 @@ protected boolean canPushdownMetadataFilter(TableSourceTable tableSourceTable) {
                 .noneMatch(spec -> spec instanceof MetadataFilterPushDownSpec);
     }
 
-    /**
-     * True if predicate references metadata columns exclusively (no physical columns).
-     *
-     * <p>A predicate like {@code OR(physical_pred, metadata_pred)} returns false because it
-     * references both physical and metadata columns. Mixed predicates remain as runtime filters.
-     */
-    protected boolean referencesOnlyMetadataColumns(RexNode predicate, int physicalColumnCount) {
-        boolean[] saw = new boolean[2]; // [0] = sawPhysical, [1] = sawMetadata
-        predicate.accept(
-                new RexVisitorImpl<Void>(true) {
-                    @Override
-                    public Void visitInputRef(RexInputRef inputRef) {
-                        if (inputRef.getIndex() >= physicalColumnCount) {
-                            saw[1] = true;
-                        } else {
-                            saw[0] = true;
-                        }
-                        return null;
-                    }
-                });
-        return saw[1] && !saw[0];
+    private enum FilterColumnKind {
+        PHYSICAL_ONLY,
+        METADATA_ONLY,
+        MIXED
     }
 
-    /** Number of physical columns in the scan's schema. */
-    protected int getPhysicalColumnCount(TableSourceTable tableSourceTable) {
-        ResolvedSchema schema = tableSourceTable.contextResolvedTable().getResolvedSchema();
-        return (int) schema.getColumns().stream().filter(Column::isPhysical).count();
-    }
-
-    /** Maps SQL column names to metadata keys for metadata columns. */
-    protected Map<String, String> buildColumnToMetadataKeyMap(TableSourceTable tableSourceTable) {
-        ResolvedSchema schema = tableSourceTable.contextResolvedTable().getResolvedSchema();
-        Map<String, String> mapping = new HashMap<>();
-        for (Column col : schema.getColumns()) {
-            if (col instanceof Column.MetadataColumn) {
-                Column.MetadataColumn metaCol = (Column.MetadataColumn) col;
-                String sqlName = metaCol.getName();
-                String metadataKey = metaCol.getMetadataKey().orElse(sqlName);
-                mapping.put(sqlName, metadataKey);
-            }
+    private static FilterColumnKind classifyColumns(RexNode predicate, int firstMetadataIndex) {
+        ImmutableBitSet columns = RelOptUtil.InputFinder.bits(predicate);
+        boolean referencesMetadata = columns.nextSetBit(firstMetadataIndex) >= 0;
+        boolean referencesPhysical = !columns.get(0, firstMetadataIndex).isEmpty();
+        if (referencesMetadata && referencesPhysical) {
+            return FilterColumnKind.MIXED;
         }
-        return mapping;
+        return referencesMetadata ? FilterColumnKind.METADATA_ONLY : FilterColumnKind.PHYSICAL_ONLY;
     }
 
-    /** Outcome of metadata filter push-down: updated table and runtime-Calc predicates. */
-    protected static final class MetadataPushDownOutcome {
-        final TableSourceTable newTableSourceTable;
-        final List<RexNode> remainingInputRexNodes;
-
-        MetadataPushDownOutcome(
-                TableSourceTable newTableSourceTable, List<RexNode> remainingInputRexNodes) {
-            this.newTableSourceTable = newTableSourceTable;
-            this.remainingInputRexNodes = remainingInputRexNodes;
-        }
+    /** Keys of the {@link ReadingMetadataSpec}, in the order of the scan's trailing fields. */
+    private static List<String> getReadMetadataKeys(TableSourceTable tableSourceTable) {
+        ReadingMetadataSpec spec =
+                ScanReuserUtils.getAbilitySpec(
+                        tableSourceTable.abilitySpecs(), ReadingMetadataSpec.class);
+        return spec == null ? Collections.emptyList() : spec.getMetadataKeys();

Review Comment:
   Done



-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table] Fix PushFilterInCalcIntoTableSourceScanRule for metadata filter push-down [flink]

Posted by "snuyanzin (via GitHub)" <gi...@apache.org>.
snuyanzin commented on PR #28556:
URL: https://github.com/apache/flink/pull/28556#issuecomment-4829592852

   we should not use Claude as a co-author according to Apache guidelines


-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table] Fix PushFilterInCalcIntoTableSourceScanRule for metadata filter push-down [flink]

Posted by "snuyanzin (via GitHub)" <gi...@apache.org>.
snuyanzin commented on code in PR #28556:
URL: https://github.com/apache/flink/pull/28556#discussion_r3493987230


##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushFilterIntoSourceScanRuleBase.java:
##########
@@ -113,6 +114,82 @@ protected RexNode createRemainingCondition(
         return new Tuple2<>(result, newTableSourceTable);
     }
 
+    /**
+     * Classifies convertible predicates into physical and metadata, pushes each through the
+     * appropriate path, and returns the updated table plus any remaining predicates.
+     */
+    protected FilterClassificationResult classifyAndPushFilters(
+            RexNode[] convertiblePredicates,
+            TableSourceTable tableSourceTable,
+            TableScan scan,
+            RelBuilder relBuilder) {
+
+        boolean supportsPhysicalFilter = canPushdownFilter(tableSourceTable);
+        boolean supportsMetadataFilter = canPushdownMetadataFilter(tableSourceTable);
+        Set<Integer> metadataColumnIndices = metadataColumnIndices(tableSourceTable, scan);
+
+        List<RexNode> allRemainingRexNodes = new ArrayList<>();
+        TableSourceTable currentTable = tableSourceTable;
+
+        List<RexNode> physicalPredicates = new ArrayList<>();
+        List<RexNode> metadataPredicates = new ArrayList<>();
+        for (RexNode predicate : convertiblePredicates) {
+            if (referencesOnlyMetadataColumns(predicate, metadataColumnIndices)) {

Review Comment:
   why do we need to calculate it always even if `supportsMetadataFilter` is false?



-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table] Fix PushFilterInCalcIntoTableSourceScanRule for metadata filter push-down [flink]

Posted by "spuru9 (via GitHub)" <gi...@apache.org>.
spuru9 commented on code in PR #28556:
URL: https://github.com/apache/flink/pull/28556#discussion_r3485713216


##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/rules/logical/MetadataFilterResultShapesITCase.java:
##########
@@ -302,4 +375,64 @@ public ScanRuntimeProvider getScanRuntimeProvider(ScanContext runtimeProviderCon
             return SourceProvider.of(source);
         }
     }
+
+    /**
+     * Source that supports both physical and metadata filter push-down. Accepts all filters it
+     * receives, emits all rows (runtime Calc is the load-bearing filter for remaining predicates).
+     */
+    static class MixedFilterTrackingSource extends TableFactoryHarness.ScanSourceBase
+            implements SupportsReadingMetadata, SupportsFilterPushDown {
+
+        private DataType producedDataType;
+        private List<ResolvedExpression> acceptedPhysicalFilters = new ArrayList<>();
+
+        MixedFilterTrackingSource() {
+            super(true);
+        }
+
+        @Override
+        public Map<String, DataType> listReadableMetadata() {
+            Map<String, DataType> metadata = new LinkedHashMap<>();
+            metadata.put("m0", INT());
+            metadata.put("m1", INT());
+            return metadata;
+        }
+
+        @Override
+        public void applyReadableMetadata(List<String> metadataKeys, DataType producedDataType) {
+            this.producedDataType = producedDataType;
+        }
+
+        @Override
+        public boolean supportsMetadataFilterPushDown() {
+            return true;
+        }
+
+        @Override
+        public MetadataFilterResult applyMetadataFilters(List<ResolvedExpression> metadataFilters) {
+            return MetadataFilterResult.of(metadataFilters, Collections.emptyList());
+        }
+
+        @Override
+        public Result applyFilters(List<ResolvedExpression> filters) {
+            acceptedPhysicalFilters.addAll(filters);
+            return Result.of(Collections.emptyList(), filters);
+        }

Review Comment:
   Can be simplified and the initisialisation of array dropped?
   
   ```suggestion
           @Override
           public Result applyFilters(List<ResolvedExpression> filters) {
               return Result.of(Collections.emptyList(), filters); 
           }
   ```



-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table] Fix PushFilterInCalcIntoTableSourceScanRule for metadata filter push-down [flink]

Posted by "jnh5y (via GitHub)" <gi...@apache.org>.
jnh5y commented on code in PR #28556:
URL: https://github.com/apache/flink/pull/28556#discussion_r3493389729


##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushFilterInCalcIntoTableSourceScanRule.java:
##########
@@ -94,33 +95,29 @@ private void pushFilterIntoScan(
         RexNode[] convertiblePredicates = extractedPredicates._1;
         RexNode[] unconvertedPredicates = extractedPredicates._2;
         if (convertiblePredicates.length == 0) {
-            // no condition can be translated to expression
             return;
         }
 
-        Tuple2<SupportsFilterPushDown.Result, TableSourceTable> pushdownResultWithScan =
-                resolveFiltersAndCreateTableSourceTable(
-                        convertiblePredicates,
-                        relOptTable.unwrap(TableSourceTable.class),
-                        scan,
-                        relBuilder);
+        FilterClassificationResult result =
+                classifyAndPushFilters(convertiblePredicates, tableSourceTable, scan, relBuilder);
+        if (result == null) {
+            return;
+        }
 
-        SupportsFilterPushDown.Result result = pushdownResultWithScan._1;
-        TableSourceTable tableSourceTable = pushdownResultWithScan._2;
+        List<RexNode> allRemainingRexNodes = new ArrayList<>(result.remainingPredicates);

Review Comment:
   Added tests.



-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table] Keep metadata column references out of physical filter push-down [flink]

Posted by "jnh5y (via GitHub)" <gi...@apache.org>.
jnh5y commented on code in PR #28556:
URL: https://github.com/apache/flink/pull/28556#discussion_r4273159834


##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushFilterInCalcIntoTableSourceScanRule.java:
##########
@@ -94,33 +95,29 @@ private void pushFilterIntoScan(
         RexNode[] convertiblePredicates = extractedPredicates._1;
         RexNode[] unconvertedPredicates = extractedPredicates._2;
         if (convertiblePredicates.length == 0) {
-            // no condition can be translated to expression
             return;
         }
 
-        Tuple2<SupportsFilterPushDown.Result, TableSourceTable> pushdownResultWithScan =
-                resolveFiltersAndCreateTableSourceTable(
-                        convertiblePredicates,
-                        relOptTable.unwrap(TableSourceTable.class),
-                        scan,
-                        relBuilder);
+        FilterClassificationResult result =
+                classifyAndPushFilters(convertiblePredicates, tableSourceTable, scan, relBuilder);
+        if (result == null) {
+            return;
+        }
 
-        SupportsFilterPushDown.Result result = pushdownResultWithScan._1;
-        TableSourceTable tableSourceTable = pushdownResultWithScan._2;
+        List<RexNode> allRemainingRexNodes = new ArrayList<>(result.remainingPredicates);
+        allRemainingRexNodes.addAll(Arrays.asList(unconvertedPredicates));
 
         FlinkLogicalTableSourceScan newScan =
                 FlinkLogicalTableSourceScan.create(
-                        scan.getCluster(), scan.getHints(), tableSourceTable);
+                        scan.getCluster(), scan.getHints(), result.updatedTable);
 
         // build new calc program
         RexProgramBuilder programBuilder =
                 RexProgramBuilder.forProgram(originProgram, call.builder().getRexBuilder(), true);
         programBuilder.clearCondition();
 
-        if (!result.getRemainingFilters().isEmpty() || unconvertedPredicates.length != 0) {
-            RexNode remainingCondition =
-                    createRemainingCondition(

Review Comment:
   It has been removed.



-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table-planner] Keep metadata column references out of physical filter push-down [flink]

Posted by "snuyanzin (via GitHub)" <gi...@apache.org>.
snuyanzin commented on code in PR #28556:
URL: https://github.com/apache/flink/pull/28556#discussion_r4296150011


##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushFilterIntoSourceScanRuleBase.java:
##########
@@ -137,72 +208,43 @@ protected boolean canPushdownMetadataFilter(TableSourceTable tableSourceTable) {
                 .noneMatch(spec -> spec instanceof MetadataFilterPushDownSpec);
     }
 
-    /**
-     * True if predicate references metadata columns exclusively (no physical columns).
-     *
-     * <p>A predicate like {@code OR(physical_pred, metadata_pred)} returns false because it
-     * references both physical and metadata columns. Mixed predicates remain as runtime filters.
-     */
-    protected boolean referencesOnlyMetadataColumns(RexNode predicate, int physicalColumnCount) {
-        boolean[] saw = new boolean[2]; // [0] = sawPhysical, [1] = sawMetadata
-        predicate.accept(
-                new RexVisitorImpl<Void>(true) {
-                    @Override
-                    public Void visitInputRef(RexInputRef inputRef) {
-                        if (inputRef.getIndex() >= physicalColumnCount) {
-                            saw[1] = true;
-                        } else {
-                            saw[0] = true;
-                        }
-                        return null;
-                    }
-                });
-        return saw[1] && !saw[0];
+    private enum FilterColumnKind {
+        PHYSICAL_ONLY,
+        METADATA_ONLY,
+        MIXED
     }
 
-    /** Number of physical columns in the scan's schema. */
-    protected int getPhysicalColumnCount(TableSourceTable tableSourceTable) {
-        ResolvedSchema schema = tableSourceTable.contextResolvedTable().getResolvedSchema();
-        return (int) schema.getColumns().stream().filter(Column::isPhysical).count();
-    }
-
-    /** Maps SQL column names to metadata keys for metadata columns. */
-    protected Map<String, String> buildColumnToMetadataKeyMap(TableSourceTable tableSourceTable) {
-        ResolvedSchema schema = tableSourceTable.contextResolvedTable().getResolvedSchema();
-        Map<String, String> mapping = new HashMap<>();
-        for (Column col : schema.getColumns()) {
-            if (col instanceof Column.MetadataColumn) {
-                Column.MetadataColumn metaCol = (Column.MetadataColumn) col;
-                String sqlName = metaCol.getName();
-                String metadataKey = metaCol.getMetadataKey().orElse(sqlName);
-                mapping.put(sqlName, metadataKey);
-            }
+    private static FilterColumnKind classifyColumns(RexNode predicate, int firstMetadataIndex) {
+        ImmutableBitSet columns = RelOptUtil.InputFinder.bits(predicate);
+        boolean referencesMetadata = columns.nextSetBit(firstMetadataIndex) >= 0;
+        boolean referencesPhysical = !columns.get(0, firstMetadataIndex).isEmpty();
+        if (referencesMetadata && referencesPhysical) {
+            return FilterColumnKind.MIXED;
         }
-        return mapping;
+        return referencesMetadata ? FilterColumnKind.METADATA_ONLY : FilterColumnKind.PHYSICAL_ONLY;
     }
 
-    /** Outcome of metadata filter push-down: updated table and runtime-Calc predicates. */
-    protected static final class MetadataPushDownOutcome {
-        final TableSourceTable newTableSourceTable;
-        final List<RexNode> remainingInputRexNodes;
-
-        MetadataPushDownOutcome(
-                TableSourceTable newTableSourceTable, List<RexNode> remainingInputRexNodes) {
-            this.newTableSourceTable = newTableSourceTable;
-            this.remainingInputRexNodes = remainingInputRexNodes;
-        }
+    /** Keys of the {@link ReadingMetadataSpec}, in the order of the scan's trailing fields. */
+    private static List<String> getReadMetadataKeys(TableSourceTable tableSourceTable) {
+        ReadingMetadataSpec spec =
+                ScanReuserUtils.getAbilitySpec(
+                        tableSourceTable.abilitySpecs(), ReadingMetadataSpec.class);
+        return spec == null ? Collections.emptyList() : spec.getMetadataKeys();

Review Comment:
   ```suggestion
           return spec == null ? List.of() : spec.getMetadataKeys();
   ```



-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table] Fix PushFilterInCalcIntoTableSourceScanRule for metadata filter push-down [flink]

Posted by "jnh5y (via GitHub)" <gi...@apache.org>.
jnh5y commented on code in PR #28556:
URL: https://github.com/apache/flink/pull/28556#discussion_r3493387183


##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/rules/logical/MetadataFilterResultShapesITCase.java:
##########
@@ -302,4 +375,64 @@ public ScanRuntimeProvider getScanRuntimeProvider(ScanContext runtimeProviderCon
             return SourceProvider.of(source);
         }
     }
+
+    /**
+     * Source that supports both physical and metadata filter push-down. Accepts all filters it
+     * receives, emits all rows (runtime Calc is the load-bearing filter for remaining predicates).
+     */
+    static class MixedFilterTrackingSource extends TableFactoryHarness.ScanSourceBase
+            implements SupportsReadingMetadata, SupportsFilterPushDown {
+
+        private DataType producedDataType;
+        private List<ResolvedExpression> acceptedPhysicalFilters = new ArrayList<>();
+
+        MixedFilterTrackingSource() {
+            super(true);
+        }
+
+        @Override
+        public Map<String, DataType> listReadableMetadata() {
+            Map<String, DataType> metadata = new LinkedHashMap<>();
+            metadata.put("m0", INT());
+            metadata.put("m1", INT());
+            return metadata;
+        }
+
+        @Override
+        public void applyReadableMetadata(List<String> metadataKeys, DataType producedDataType) {
+            this.producedDataType = producedDataType;
+        }
+
+        @Override
+        public boolean supportsMetadataFilterPushDown() {
+            return true;
+        }
+
+        @Override
+        public MetadataFilterResult applyMetadataFilters(List<ResolvedExpression> metadataFilters) {
+            return MetadataFilterResult.of(metadataFilters, Collections.emptyList());
+        }
+
+        @Override
+        public Result applyFilters(List<ResolvedExpression> filters) {
+            acceptedPhysicalFilters.addAll(filters);
+            return Result.of(Collections.emptyList(), filters);
+        }

Review Comment:
   Good catch.  Applied in a force push!



-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table] Fix PushFilterInCalcIntoTableSourceScanRule for metadata filter push-down [flink]

Posted by "jnh5y (via GitHub)" <gi...@apache.org>.
jnh5y commented on PR #28556:
URL: https://github.com/apache/flink/pull/28556#issuecomment-4835026390

   > we should not use Claude as a co-author according to Apache guidelines
   
   Fixed; sorry for the churn.


-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table-planner] Keep metadata column references out of physical filter push-down [flink]

Posted by "snuyanzin (via GitHub)" <gi...@apache.org>.
snuyanzin commented on code in PR #28556:
URL: https://github.com/apache/flink/pull/28556#discussion_r4296140238


##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/rules/logical/PushFilterInCalcIntoTableSourceRuleTest.java:
##########
@@ -117,6 +119,61 @@ void testFailureToPushFilterIntoSourceWithoutWatermarkPushdown() {
         util.verifyRelPlan("SELECT * FROM WithWatermark WHERE LOWER(name) = 'foo'");
     }
 
+    @ParameterizedTest(name = "virtual={0}")
+    @ValueSource(booleans = {false, true})

Review Comment:
   now both for `virtual=true` and `virtual=false` plans are identical
   was it deliberate?



-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [FLINK-40002][table-planner] Keep metadata column references out of physical filter push-down [flink]

Posted by "jnh5y (via GitHub)" <gi...@apache.org>.
jnh5y commented on code in PR #28556:
URL: https://github.com/apache/flink/pull/28556#discussion_r4317905485


##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushFilterIntoSourceScanRuleBase.java:
##########
@@ -137,72 +208,43 @@ protected boolean canPushdownMetadataFilter(TableSourceTable tableSourceTable) {
                 .noneMatch(spec -> spec instanceof MetadataFilterPushDownSpec);
     }
 
-    /**
-     * True if predicate references metadata columns exclusively (no physical columns).
-     *
-     * <p>A predicate like {@code OR(physical_pred, metadata_pred)} returns false because it
-     * references both physical and metadata columns. Mixed predicates remain as runtime filters.
-     */
-    protected boolean referencesOnlyMetadataColumns(RexNode predicate, int physicalColumnCount) {
-        boolean[] saw = new boolean[2]; // [0] = sawPhysical, [1] = sawMetadata
-        predicate.accept(
-                new RexVisitorImpl<Void>(true) {
-                    @Override
-                    public Void visitInputRef(RexInputRef inputRef) {
-                        if (inputRef.getIndex() >= physicalColumnCount) {
-                            saw[1] = true;
-                        } else {
-                            saw[0] = true;
-                        }
-                        return null;
-                    }
-                });
-        return saw[1] && !saw[0];
+    private enum FilterColumnKind {
+        PHYSICAL_ONLY,
+        METADATA_ONLY,
+        MIXED
     }
 
-    /** Number of physical columns in the scan's schema. */
-    protected int getPhysicalColumnCount(TableSourceTable tableSourceTable) {
-        ResolvedSchema schema = tableSourceTable.contextResolvedTable().getResolvedSchema();
-        return (int) schema.getColumns().stream().filter(Column::isPhysical).count();
-    }
-
-    /** Maps SQL column names to metadata keys for metadata columns. */
-    protected Map<String, String> buildColumnToMetadataKeyMap(TableSourceTable tableSourceTable) {
-        ResolvedSchema schema = tableSourceTable.contextResolvedTable().getResolvedSchema();
-        Map<String, String> mapping = new HashMap<>();
-        for (Column col : schema.getColumns()) {
-            if (col instanceof Column.MetadataColumn) {
-                Column.MetadataColumn metaCol = (Column.MetadataColumn) col;
-                String sqlName = metaCol.getName();
-                String metadataKey = metaCol.getMetadataKey().orElse(sqlName);
-                mapping.put(sqlName, metadataKey);
-            }
+    private static FilterColumnKind classifyColumns(RexNode predicate, int firstMetadataIndex) {
+        ImmutableBitSet columns = RelOptUtil.InputFinder.bits(predicate);
+        boolean referencesMetadata = columns.nextSetBit(firstMetadataIndex) >= 0;
+        boolean referencesPhysical = !columns.get(0, firstMetadataIndex).isEmpty();

Review Comment:
   I named it `lowestColumn`.  Is that ok?



##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/rules/logical/PushFilterInCalcIntoTableSourceRuleTest.java:
##########
@@ -117,6 +119,61 @@ void testFailureToPushFilterIntoSourceWithoutWatermarkPushdown() {
         util.verifyRelPlan("SELECT * FROM WithWatermark WHERE LOWER(name) = 'foo'");
     }
 
+    @ParameterizedTest(name = "virtual={0}")
+    @ValueSource(booleans = {false, true})

Review Comment:
   Yes.



-- 
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: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org