Status

Abstract

This FLIP proposes a new built-in table function APPLY_WATERMARK that enables users to explicitly assign or override watermark strategies on any relational input — including base tables, non-materialized views, and subqueries — using Calcite lambda expression syntax within SQL queries.  

This design is motivated by the community discussion on FLINK-39062, where Timo Walther and Lincoln Lee converged on a function-based approach as a clean alternative to embedding watermark definitions into CREATE VIEW / ALTER VIEW statements.

Motivation

Problem

Currently, watermarks in Flink SQL can only be defined at the CREATE TABLE level via the WATERMARK FOR ... AS ... clause. This creates significant limitations for real-world usage:

  • Broken Abstraction: Users who build layered data pipelines (Bronze/Silver/Gold medallion architecture) must reach down into the base table definition to configure watermarks, exposing implementation details.
  • No Flexibility for Multi-Tenancy: In multi-tenant scenarios, different consumers of the same source table may require different watermark strategies (e.g., different lateness tolerances for different SLAs), but there is no way to define per-query watermarks.
  • Limited Architecture Support: When users receive catalogs as given (e.g., in a shared data platform), they cannot write queries that establish event-time semantics without modifying the underlying table DDL.
  • SQL/DataStream API Gap: The DataStream API allows users to assign watermarks flexibly at any point in the pipeline. SQL users have no equivalent capability, creating a fundamental usability gap.

Community Feedback Summary

From the mailing list discussion:

  • Timo Walther (Confluent / PMC): Raised concerns about attaching watermark semantics directly to SQL views, as views are pure logical aliases and a watermark would introduce an optimization barrier or change the fundamental concept of a view. Agreed on the APPLY_WATERMARK PTF direction. Also noted that this would benefit from a specialized ExecNode path and future WatermarkFunction support. In the latest feedback round, Timo recommended using Calcite lambda expression syntax directly and considering an optional config => MAP<STRING, STRING> parameter; otherwise he was +1 on the FLIP.
  • Lincoln Lee (Alibaba): Proposed the APPLY_WATERMARK(table, DESCRIPTOR(col), expr) built-in function approach, initially scoped to base tables only. Agreed on the general direction.
  • Gyula Fóra (Ververica): Emphasized the need for watermarks to be applicable not just to base tables, but also to views and subqueries — consistent with how DataStream API users think about watermark assignment.
  • FeatZhang (Author): Proposed extending APPLY_WATERMARK to support both base tables and non-materialized views, keeping view semantics pure while enabling flexible watermark assignment via an explicit relational operator.

Goals

  • Introduce a built-in PTF APPLY_WATERMARK(table, DESCRIPTOR(rowtime_column), strategy_lambda [, config]) that assigns or overrides a watermark strategy on a relational input. The strategy is expressed using Calcite lambda syntax, e.g. (rowtime) -> rowtime - INTERVAL '5' SECOND.
  • Support base tables, non-materialized views, and subqueries as input to APPLY_WATERMARK.
  • Keep SQL views as pure logical abstractions — no changes to CREATE VIEW or ALTER VIEW semantics.
  • Ensure the function compiles to a specialized ExecNode in the physical plan (similar to VECTOR_SEARCH and ML_PREDICT), maintaining planner control over watermark semantics.
  • Lay groundwork for future user-defined watermark functions via a WatermarkFunction interface.
  • Reserve an optional function-level config => MAP<STRING, STRING> parameter for future per-call options without introducing global configuration options.

Non-Goals

  • This FLIP does not change the semantics of SQL views.
  • This FLIP does not introduce watermark metadata into the view catalog.
  • User-defined PTFs that emit watermarks are out of scope for this FLIP (tracked separately per Timo's suggestion).
  • Lambda expression syntax for watermark expressions is out of scope (depends on Calcite upgrade).
  • This FLIP does not introduce any stateful watermark assigner, idle-source detection, or runtime-level merge of multiple watermark strategies. The APPLY_WATERMARK ExecNode is stateless and equivalent to today's DDL WatermarkAssignerOperator.
  • This FLIP does not require Calcite parser changes. It uses the lambda expression syntax already supported by the Calcite stack available in Flink after the recent Calcite upgrade.

Public Interfaces

This section enumerates every public surface this FLIP touches. All Flink SQL public surfaces follow the Flink Public API stability contract; anything not listed below is internal and not part of the public contract.

1. New SQL Built-in Function

A new built-in function APPLY_WATERMARK is added to the Flink SQL function catalog under category system / built-in.

Signature (formal):

APPLY_WATERMARK(
    input    => TABLE <any-relation>,
    rowtime  => DESCRIPTOR(<column>),
    strategy => <scalar-expression>
) -> TABLE <same-schema-as-input, with rowtime attribute on the descriptor column>
SurfaceStabilityNotes
Function name APPLY_WATERMARK@PublicEvolving (new in this FLIP)Reserved as a built-in function name; not a SQL keyword.
Input position 1 (input)@PublicEvolvingPolymorphic Table Function (PTF) input. Accepts any relational expression: base table, view, sub-query, or another PTF output.
Input position 2 (rowtime)@PublicEvolvingReuses the existing DESCRIPTOR(<col>) column-list form already used by TUMBLE/HOP/SESSION/CUMULATE window TVFs. No new syntax is introduced.
Input position 3 (strategy)@PublicEvolvingA Calcite lambda expression whose parameter corresponds to the descriptor column, e.g. (order_time) -> order_time - INTERVAL '5' SECOND. The lambda body follows the same validation contract as CREATE TABLE … WATERMARK FOR … AS ….
Optional input position 4 (config)@PublicEvolvingOptional function-level MAP<STRING, STRING> reserved as an extension point for future per-call options. The default is an empty map. Unsupported keys fail validation
Return shape@PublicEvolvingSame row type as input; the descriptor column is upgraded to a rowtime attribute (TIMESTAMP(p) *ROWTIME* / TIMESTAMP_LTZ(p) *ROWTIME*).

2. SQL Grammar

APPLY_WATERMARK is invoked as a Polymorphic Table Function (see §3 below). Two equivalent invocation forms are supported, mirroring Flink's existing window TVF conventions:

-- Form A: bare function call in FROM (preferred for readability)
SELECT … FROM APPLY_WATERMARK(orders, DESCRIPTOR(order_time), order_time - INTERVAL '5' SECOND);

-- Form B: TABLE(...) wrapping (required when nested as an argument to another TVF such as TUMBLE / HOP)
SELECT … FROM TABLE(
  TUMBLE(
    TABLE(APPLY_WATERMARK(orders, DESCRIPTOR(order_time), order_time - INTERVAL '5' SECOND)),
    DESCRIPTOR(order_time),
    INTERVAL '1' HOUR));

No new keywords are reserved. APPLY_WATERMARK is a function name and does not conflict with user identifiers (existing tables/views named apply_watermark continue to work via standard quoted identifier rules).

3. Java / Scala API

No changes to public Java / Scala APIs in this FLIP:

  • No additions to org.apache.flink.table.api.*.
  • No additions to org.apache.flink.table.functions.* (the future WatermarkFunction interface is explicitly out of scope, see §5 of Proposed Changes).
  • No additions to TableEnvironment / StatementSet / Table.

The feature is exposed purely through SQL.

4. Configuration Options

No new configuration options (ConfigOption) are introduced. The function uses the same execution-time configuration as the DDL watermark path (e.g., table.exec.source.idle-timeout is intentionally not consumed by APPLY_WATERMARK; idle-source semantics remain a property of the source operator, consistent with the stateless contract in Non-Goals).

5. Catalog / Persistence

No catalog changes. APPLY_WATERMARK is a query-level construct; it produces no catalog entries, no CatalogTable properties, and no extra resolved-schema metadata persisted via CompiledPlan. (Compiled plans serialise the call as a regular function invocation, identical to other built-in PTFs.)

6. REST / CLI / Metrics

No changes to the SQL Gateway REST surface, SQL Client commands, or operator metrics naming. The runtime operator is the existing StreamExecWatermarkAssigner, whose metrics (currentEmitWatermark, etc.) are unchanged.


Proposed Changes

1. New Built-in Function: APPLY_WATERMARK

Syntax

APPLY_WATERMARK(table_or_view, DESCRIPTOR(rowtime_column), watermark_expression)

Function Classification

APPLY_WATERMARK is a Polymorphic Table Function (PTF) — i.e., a function that accepts a table-typed input and returns a table-typed output, in the same family as TUMBLE, HOP, SESSION, CUMULATE, ML_PREDICT, and VECTOR_SEARCH. It is not a scalar function, not a LATERAL TABLE(...) UDTF, and not an aggregate.

Two invocation forms are supported (both produce identical plans):

FormWhen to useExample
A. Bare call in FROMWhen APPLY_WATERMARK is the outermost source of a sub-query / SELECT block.FROM APPLY_WATERMARK(t, DESCRIPTOR(ts), ts - INTERVAL '5' SECOND)
B. TABLE(...) wrappingWhen APPLY_WATERMARK is passed as a table argument to another TVF (e.g., nested inside TUMBLE / HOP). This follows the same convention as TABLE(orders) inside window TVFs.TUMBLE(TABLE(APPLY_WATERMARK(t, DESCRIPTOR(ts), ts - INTERVAL '5' SECOND)), DESCRIPTOR(ts), INTERVAL '1' HOUR)

Parameters

ParameterTypeDescription
table_or_viewTable referenceBase table, view, or subquery providing the input rows
DESCRIPTOR(rowtime_column)Column descriptorThe column to use as the rowtime attribute
strategy_lambdaCalcite lambda expressionWatermark strategy lambda (e.g., (rowtime) -> rowtime - INTERVAL '5' SECOND). The lambda parameter is bound to the descriptor column.
configOptional MAP<STRING, STRING>Optional per-call extension point. Defaults to an empty map; unsupported keys fail validation.

On DESCRIPTOR(...) reuse. The DESCRIPTOR(<column-name>) form is the existing column-list descriptor already used by Flink's window TVFs (TUMBLE/HOP/SESSION/CUMULATE) to identify a time attribute column at the call site. APPLY_WATERMARK deliberately reuses this exact form — same parser rule, same column-resolution logic, same error messages — to keep the user-visible surface uniform. No new descriptor variant is introduced. Reviewers familiar with window TVFs should find the second argument immediately self-explanatory.

On lambda syntax. The third argument uses Calcite lambda expression syntax, e.g. (order_time) -> order_time - INTERVAL '5' SECOND. The lambda parameter is scoped only to the strategy expression and is bound to the DESCRIPTOR(...) column. This avoids custom parser syntax and aligns the API with Calcite’s current direction for expression-typed function arguments.

Return Type

The function returns a table with the same schema as the input, but with the specified watermark strategy applied. The rowtime column becomes a proper rowtime attribute in the resulting relation.

Usage Examples

Example 1 — Override watermark on a base table.

SELECT *
FROM APPLY_WATERMARK(orders, DESCRIPTOR(order_time), order_time - INTERVAL '5' SECOND);

Example 2 — Apply watermark on a non-materialized view, with two consumers using different lateness tolerances.

-- Silver view (no watermark defined)
CREATE VIEW silver_events AS
SELECT CAST(JSON_VALUE(raw_data, '$.event_time') AS TIMESTAMP(3)) AS event_time,
       JSON_VALUE(raw_data, '$.user_id') AS user_id
FROM bronze_events;

-- Consumer A: strict lateness tolerance
SELECT TUMBLE_START(event_time, INTERVAL '1' HOUR), COUNT(*)
FROM APPLY_WATERMARK(silver_events, DESCRIPTOR(event_time), event_time - INTERVAL '5' SECOND)
GROUP BY TUMBLE(event_time, INTERVAL '1' HOUR);

-- Consumer B: lenient lateness tolerance
SELECT TUMBLE_START(event_time, INTERVAL '1' HOUR), COUNT(*)
FROM APPLY_WATERMARK(silver_events, DESCRIPTOR(event_time), event_time - INTERVAL '30' SECOND)
GROUP BY TUMBLE(event_time, INTERVAL '1' HOUR);

Example 3 — Apply watermark on a sub-query.

SELECT TUMBLE_START(ts, INTERVAL '1' HOUR), user_id, COUNT(*)
FROM APPLY_WATERMARK(
       (SELECT user_id, CAST(event_ts AS TIMESTAMP(3)) AS ts FROM raw_log),
       DESCRIPTOR(ts),
       ts - INTERVAL '10' SECOND)
GROUP BY TUMBLE(ts, INTERVAL '1' HOUR), user_id;

Example 4 — Layered (Bronze / Silver / Gold) data architecture.

-- Bronze: Raw ingestion (no watermark)
CREATE TABLE bronze_events (raw_data STRING, ingestion_time TIMESTAMP(3)) WITH (...);

-- Silver: Cleaned view (no watermark, pure SQL alias)
CREATE VIEW silver_events AS
SELECT CAST(JSON_VALUE(raw_data, '$.event_time') AS TIMESTAMP(3)) AS event_time,
       JSON_VALUE(raw_data, '$.user_id') AS user_id
FROM bronze_events
WHERE JSON_VALUE(raw_data, '$.event_time') IS NOT NULL;

-- Gold: Aggregation with explicit watermark assignment
SELECT TUMBLE_START(event_time, INTERVAL '1' HOUR) AS window_start,
       COUNT(*) AS event_count
FROM APPLY_WATERMARK(silver_events, DESCRIPTOR(event_time), event_time - INTERVAL '10' SECOND)
GROUP BY TUMBLE(event_time, INTERVAL '1' HOUR);

Example 5 — Nesting APPLY_WATERMARK inside a Window TVF.

When APPLY_WATERMARK is consumed by another TVF (e.g., TUMBLE), it must be wrapped in TABLE(...), identical to how a base-table argument is passed to a window TVF today.

SELECT window_start, window_end, COUNT(*)
FROM TABLE(
       TUMBLE(
         TABLE(APPLY_WATERMARK(orders,
                               DESCRIPTOR(order_time),
                               order_time - INTERVAL '5' SECOND)),
         DESCRIPTOR(order_time),
         INTERVAL '1' HOUR))
GROUP BY window_start, window_end;

Example 6 — Optional config extension point.


SELECT *


FROM APPLY_WATERMARK(


       orders,


       DESCRIPTOR(order_time),


       (order_time) -> order_time - INTERVAL '5' SECOND,


       config => MAP['mode', 'default']);


The concrete config keys are intentionally not defined in this FLIP. The example illustrates the reserved API shape only; unsupported keys fail validation.


This is the canonical pattern for users who want flexible, query-scoped watermarks feeding directly into Flink's window TVFs — currently impossible without modifying the source-table DDL.

2. Planner Changes

Logical Plan

APPLY_WATERMARK translates to a new logical node LogicalWatermarkAssigner at query parse/validate time. The planner performs:

  • Input resolution: Resolves table_or_view to a RelNode (base scan, view expansion, or subquery).
  • Column validation: Validates that DESCRIPTOR(rowtime_column) refers to an existing column of TIMESTAMP or TIMESTAMP_LTZ type.
  • Expression validation: Validates that watermark_expression is a valid scalar expression on the input schema with a comparable result type. The validation contract is identical to CREATE TABLE … WATERMARK FOR … AS …: the planner does not enforce monotonicity — monotonicity is a runtime contract guaranteed by the WatermarkAssignerOperator.
  • Operator topology: APPLY_WATERMARK introduces an independent LogicalWatermarkAssigner node at the position where it appears in SQL. Whether or not the input already carries a watermark, the new assigner sits downstream of any upstream assigner — equivalent to two consecutive assignTimestampsAndWatermarks(…) calls in the DataStream API. There is no planner-level "override" semantics; the planner only decides operator topology.

Physical Plan

APPLY_WATERMARK compiles to a specialized ExecNode — similar to how VECTOR_SEARCH and ML_PREDICT are handled — ensuring that the planner retains control over watermark semantics and optimization barriers are introduced only where explicitly requested.
The specialized ExecNode reuses the existing StreamExecWatermarkAssigner runtime operator. Compared to the DDL path, the only ExecNode-level work APPLY_WATERMARK adds is:

  • resolving the rowtime column index from the DESCRIPTOR (because the input may not be a TableScan);
  • wiring the watermark expression's input row to the upstream operator's output row.

No new expression-evaluation capability is required: scalar expressions on TIMESTAMP / TIMESTAMP_LTZ, INTERVAL arithmetic, and scalar UDFs work out of the box via the standard ExprCodeGenerator, identical to today's DDL.
The ExecNode is stateless, identical to the existing WatermarkAssignerOperator. Late-data handling remains the responsibility of downstream window / join operators.
This means:

  • The surrounding plan is not affected by optimization barriers unless APPLY_WATERMARK is used.
  • Views themselves continue to dissolve transparently into the plan (via predicate pushdown, projection pushdown, etc.).
  • The watermark assignment is a first-class physical operator, not a hidden side effect.

Semantics at Different Pipeline Positions

The semantics of APPLY_WATERMARK at any position in a query are defined by direct alignment with the DataStream API mental model:
Each APPLY_WATERMARK in SQL corresponds to one assignTimestampsAndWatermarks(…) call in the equivalent DataStream pipeline, applied in the order they appear.

  1. On a base table: Equivalent to a query-scoped version of CREATE TABLE … WATERMARK FOR … AS …. If the base table already has a DDL watermark, the new assigner is chained downstream of the existing one (no planner-level override).
  2. On a non-materialized view / sub-query: The view continues to dissolve transparently into the plan (projection / filter pushdown are unaffected). The WatermarkAssigner operator is placed on top of the expanded RelNode — outside the view body, so the view itself remains a pure logical alias.
  3. Multiple APPLY_WATERMARK in the same query: They form an operator chain in SQL appearance order; the downstream one wins in the sense that downstream operators observe its emitted watermark. This is identical to multiple assignTimestampsAndWatermarks(…) calls in DataStream.
  4. Interaction with window TVFs (TUMBLE / HOP / SESSION / CUMULATE): The window TVF directly consumes the rowtime attribute produced by APPLY_WATERMARK. Behavior is equivalent to consuming a base-table rowtime column.
  5. Interaction with joins (regular / interval / temporal): Interval / temporal joins require rowtime attributes on both inputs. APPLY_WATERMARK can explicitly assign rowtime in a sub-query so that interval / temporal joins become available. Regular joins do not consume watermarks and are unaffected.

Interaction with Existing Table Watermarks

Input has existing watermark?Operator-topology behavior
Yes (from CREATE TABLE)APPLY_WATERMARK introduces a new WatermarkAssigner downstream of the existing one. Downstream operators observe the watermark emitted by the new assigner — identical to two consecutive assignTimestampsAndWatermarks(…) calls in DataStream.
NoAPPLY_WATERMARK introduces a new WatermarkAssigner.
View (no watermark in catalog)Same as "No" — APPLY_WATERMARK introduces a new WatermarkAssigner on top of the view-expanded RelNode.

Note: APPLY_WATERMARK does NOT perform any planner-level "override". The planner only decides operator topology; the runtime emits watermarks strictly according to that topology.

Streaming vs. Batch Execution

Flink SQL is dual-mode (streaming and batch). APPLY_WATERMARK is well-defined under both, mirroring the existing DDL WATERMARK FOR … AS … clause:

ModeBehavior
StreamingFull semantics. APPLY_WATERMARK compiles to StreamExecWatermarkAssigner; watermarks are emitted at runtime according to the strategy expression.
BatchParsed, validated, and planned as a no-op. The descriptor column is still upgraded to a rowtime attribute (so that downstream window TVFs / interval joins type-check), but no watermark is emitted at runtime — batch operators do not consume watermarks (they observe a single end-of-input boundary). This is identical to how DDL-defined watermarks behave under EnvironmentSettings.inBatchMode().

This dual-mode behavior is intentional and ensures that the same query text is portable between streaming and batch execution without rewrites — a property already guaranteed for DDL watermarks and now extended to APPLY_WATERMARK.

EXPLAIN Output (Illustrative)

To help reviewers visualise how APPLY_WATERMARK lands in the query plan, here is an illustrative EXPLAIN output for Example 5 (Window TVF over APPLY_WATERMARK).

Query:

EXPLAIN
SELECT window_start, window_end, COUNT(*)
FROM TABLE(
       TUMBLE(
         TABLE(APPLY_WATERMARK(orders,
                               DESCRIPTOR(order_time),
                               order_time - INTERVAL '5' SECOND)),
         DESCRIPTOR(order_time),
         INTERVAL '1' HOUR))
GROUP BY window_start, window_end;

Expected (abridged) physical plan in streaming mode:

== Optimized Physical Plan ==
GroupWindowAggregate(window=[TUMBLE(time_col=[order_time], size=[1 h])], select=[window_start, window_end, COUNT(*) AS EXPR$2])
+- Exchange(distribution=[hash[window_start, window_end]])
   +- WatermarkAssigner(rowtime=[order_time], watermark=[(order_time - 5000:INTERVAL SECOND)])
      +- TableSourceScan(table=[[default_catalog, default_database, orders]], fields=[order_id, order_time, amount])

== Optimized Execution Plan ==
GroupWindowAggregate(...)
+- Exchange(distribution=[hash[window_start, window_end]])
   +- WatermarkAssigner(rowtime=[order_time], watermark=[(order_time - 5000:INTERVAL SECOND)])  // <-- StreamExecWatermarkAssigner from APPLY_WATERMARK
      +- TableSourceScan(...)

Key observations:

  • The WatermarkAssigner node appears at exactly the position where APPLY_WATERMARK was written, between the source scan and the window aggregate.
  • If the orders table also has a DDL-level watermark, an additional upstream WatermarkAssigner would appear immediately above TableSourceScan (chained, not merged) — exactly matching two consecutive assignTimestampsAndWatermarks(…) calls in DataStream.
  • In batch mode, the same plan elides the WatermarkAssigner (or renders it as a pass-through with runtime=[batch] annotation), consistent with DDL watermark behavior.

The exact text format of EXPLAIN is not part of the public contract (Flink reserves the right to refine it across releases); this section is purely illustrative for reviewers.

3. Catalog Changes

No catalog changes are required. APPLY_WATERMARK is a query-level construct and does not persist watermark metadata into any catalog.

4. API Changes

No public Java/Scala API changes are required for this FLIP. The feature is exposed purely through SQL syntax.

5. Future Extension: WatermarkFunction Interface (Out of Scope)

As discussed by Timo, we could introduce a WatermarkFunction interface in the future that allows user-defined PTFs to emit watermarks. This would follow the same pattern as ChangelogFunction. This is explicitly out of scope for this FLIP but is noted as a natural follow-up.

Backward Compatibility

  • No breaking changes to existing SQL syntax.
  • Existing CREATE TABLE watermark definitions continue to work unchanged.
  • APPLY_WATERMARK is purely additive.

Test Plan

The implementation will be covered at four levels — parser, planner, runtime, and end-to-end — across both streaming and batch execution modes. All tests live in flink-table-planner and flink-table-runtime, alongside existing window-TVF and DDL-watermark tests.

1. Parser & SQL Validation Tests (SqlValidatorTest / FlinkSqlParserImplTest)

IDCaseExpected
P-01APPLY_WATERMARK(t, DESCRIPTOR(ts), (ts) -> ts - INTERVAL '5' SECOND) on a base tableparse OK, validation OK
P-02Bare-call form (Form A) and TABLE(...)-wrapped form (Form B)both parse to identical RelNode
P-03DESCRIPTOR references a non-existent columnvalidation error (clear message)
P-04DESCRIPTOR references a non-TIMESTAMP[_LTZ] columnvalidation error
P-05

Strategy lambda body references a column not in input schema

validation error
P-06

Strategy lambda body returns non-comparable / wrong type

validation error
P-07Existing user table named apply_watermark (quoted identifier)no conflict
P-08Required arguments missing or in wrong orderparse error
P-09

Optional config => MAP<STRING, STRING> omitted

parse OK, default empty config
P-10Optional config contains unsupported keys

validation error

2. Logical / Physical Plan Tests (PlanTest with EXPLAIN golden files)

IDCaseExpected
L-01APPLY_WATERMARK over base table without DDL watermarksingle LogicalWatermarkAssigner above TableScan
L-02APPLY_WATERMARK over base table with DDL watermarktwo chained WatermarkAssigner nodes (DDL upstream, APPLY downstream) — verifies the "no planner-level override" semantics
L-03APPLY_WATERMARK over a non-materialized viewview dissolves into the plan; WatermarkAssigner sits on the expanded RelNode (verifies projection / filter pushdown still works through the view)
L-04APPLY_WATERMARK over a sub-queryWatermarkAssigner on the sub-query RelNode
L-05Multiple APPLY_WATERMARK in one query (e.g., outer wraps inner)chained WatermarkAssigner nodes in SQL appearance order; downstream wins
L-06APPLY_WATERMARK nested inside TUMBLE / HOP / SESSION / CUMULATE window TVFwindow TVF correctly consumes the rowtime attribute produced by APPLY_WATERMARK
L-07APPLY_WATERMARK providing rowtime to interval join / temporal joinjoin planner accepts the rowtime; correct join operator selected
L-08APPLY_WATERMARK in CompiledPlan round-trip (serialise → deserialise)identical execution graph

Every plan test produces an EXPLAIN golden file checked into the repo, ensuring future planner refactors do not silently change semantics.

3. Runtime Tests (StreamExecWatermarkAssignerTest extension + new ApplyWatermarkITCase)

IDCaseExpected
R-01APPLY_WATERMARK emits the same watermarks as the equivalent DDL watermarkbyte-for-byte match on emitted Watermark events
R-02Two chained assigners (DDL + APPLY)downstream operators observe only the APPLY-emitted watermark (DDL one is overwritten in the watermark stream)
R-03Two chained APPLY_WATERMARK nodesdownstream observes the outermost (most-downstream) watermark
R-04Late record handlingidentical to DDL path; verifies the ExecNode is stateless and reuses the existing operator
R-05Idle-source detectionnot enabled (per Non-Goals); explicit test that APPLY_WATERMARK does not consume table.exec.source.idle-timeout
R-06Savepoint / state compatibilitystateless: take a savepoint mid-pipeline, verify restore works without state assignment for the APPLY_WATERMARK operator

4. Batch-Mode Tests (BatchExecApplyWatermarkTest)

IDCaseExpected
B-01APPLY_WATERMARK in EnvironmentSettings.inBatchMode()parses, validates, plans without error
B-02Batch-mode planWatermarkAssigner is elided / rendered as no-op; final result matches a streaming run with the same input
B-03Window TVF over batch-mode APPLY_WATERMARKidentical aggregation results vs. streaming mode
IDCaseExpected
E-01Bronze → Silver (view) → Gold pipeline using APPLY_WATERMARK over the silver view (Example 4)correct hourly window counts on a synthetic dataset
E-02Same source, two consumers with different lateness tolerances via APPLY_WATERMARK (Example 2)each consumer produces results consistent with its own watermark strategy; consumers do not interfere
E-03Migration test: existing query relying on DDL watermark continues to work after APPLY_WATERMARK is introducedregression baseline preserved

6. Backward / Forward Compatibility

  • State / savepoint compatibility: no new state, so no migration needed; existing savepoints from queries that do not use APPLY_WATERMARK are unaffected.
  • CompiledPlan compatibility: serialised plans containing APPLY_WATERMARK must remain restorable across the next minor version (covered by L-08).
  • Existing DDL-watermark queries: covered by E-03 (regression).

Rejected Alternatives

Alternative 1: CREATE VIEW ... WATERMARK FOR ...

The original proposal was to allow watermark definitions directly in CREATE VIEW statements. This was rejected because:

  • SQL views are pure logical aliases; adding watermark semantics would blur the conceptual boundary.
  • It would require introducing optimization barriers into view expansion.
  • It conflates logical abstraction (view) with physical planning (watermark assignment).

As Timo noted: "A view usually dissolves into the plan (e.g. via projection or filter pushdown). Would a watermark definition suddenly introduce an optimization barrier? If this is an optimization barrier, is this still a view or a new concept?"

Alternative 2: ALTER VIEW SET WATERMARK

This was rejected because:

  • It modifies view semantics by storing hidden physical properties in the catalog.
  • It creates implicit behavior that is invisible to the query reader.
  • Catalog-level watermarks on views have unclear propagation semantics when views are nested.

Open Questions

  • Lambda expression syntax: When Calcite lambda support lands (per Timo's roadmap at Confluent), should the watermark_expression be changed to a lambda? This would be a cleaner API but requires the Calcite upgrade first.
  • Concrete config keys (future work): the optional config => MAP<STRING, STRING> parameter as an extension point, but this FLIP does not define concrete runtime options. Future FLIPs can add supported keys if needed.

Discussion & Revision History

This appendix records the community discussion that shaped this FLIP and the concrete revisions between v1 and v2. The full mail thread is linked under References.

Design Evolution

The proposal evolved through three phases on dev@flink.apache.org (11 messages, 5 active participants):

  1. Phase 1 — DDL on views (rejected). Initial proposal: CREATE VIEW … WATERMARK FOR ts AS … and ALTER VIEW SET WATERMARK. Rejected by Timo Walther and Lincoln Lee: views must remain pure logical aliases.
  2. Phase 2 — Built-in function (accepted direction). Lincoln sketched APPLY_WATERMARK(table, DESCRIPTOR(col), expr) for base tables; Gyula Fóra pushed for full DataStream-API flexibility. Timo crystallised two implementation paths: (a) a new WatermarkFunction interface, or (b) a specialized ExecNode (similar to VECTOR_SEARCH / ML_PREDICT), and asked for a formal FLIP.
  3. Phase 3 — Semantic tightening (this FLIP, v2). Xuyang led a strict review round (5 questions, then 5 follow-ups). v2 converges on the specialized ExecNode path with stateless semantics that mirror two consecutive assignTimestampsAndWatermarks(…) calls in the DataStream API.
  4. Phase 4 — FLIP stabilisation and pre-vote. Xuyang confirmed no further questions. FeatZhang notified the list that the FLIP had stabilised and asked for final concerns before starting the VOTE thread.
  5. Phase 5 — Lambda syntax and config extension . Timo provided final feedback: use Calcite lambda expression syntax instead of custom syntax, consider an optional config => MAP<STRING, STRING> parameter, and otherwise expressed +1.

Participants & Positions

ParticipantStanceKey contribution
FeatZhang (author)Drives the proposal; converges on each round of feedbackDDL draft → built-in function → any-relation scope → stateless ExecNode → Calcite lambda strategy syntax + optional config extension point
Timo WaltherRejects DDL-on-views; sets the technical directionViews must stay logical aliases; built-in PTF preferred; flagged the Calcite-lambda and PTF-watermark constraints; demanded a formal FLIP; later recommended using Calcite lambda syntax and optional config.
Lincoln LeeSupports TimoFirst to sketch APPLY_WATERMARK(table, DESCRIPTOR, expr); initially favoured base-table-only scope.
Gyula FóraPushes for flexibilityArgued that base-table-only is misaligned with the DataStream API.
XuyangStrict reviewerIteratively interrogated monotonicity validation timing, override timing, ExecNode reuse, expression evaluation, and state management; drove most of the v2 tightening.
Raorao Xiong+1 (non-binding)Endorsed the motivation, citing medallion-architecture pipelines as a typical use case.

Mail Timeline (11 messages)

#DateAuthorSummary
12026-02-11FeatZhangInitial FLIP proposal: CREATE VIEW … WATERMARK FOR ts AS … / ALTER VIEW SET WATERMARK.
22026-02-11TimoRejection: views are pure logical aliases. Raised three hard cases — updating sources, upstream-watermark interaction, view becoming an optimization barrier.
32026-02-12LincolnAgrees with Timo; counter-proposes APPLY_WATERMARK(table, DESCRIPTOR(col), expr), base-table only.
42026-02-12FeatZhangAccepts the function direction; argues the table parameter should also accept non-materialized views.
52026-02-12GyulaBase-table-only is too restrictive vs. the DataStream API.
62026-02-12TimoConsensus on what; divergence on how. Two implementation paths: (a) new WatermarkFunction interface; (b) specialized ExecNode. Asks for a formal FLIP.
72026-04-21FeatZhangFLIP renamed to “Support Flexible Watermark Assignment via Built-in Function”; scope = base table + view + sub-query; PR #27984 attached. (This is the v1 of this document.)
82026-05-06Xuyang5 questions: (1) Is non-materialized-view scope settled? (2) Is planner-level monotonicity validation appropriate? (3) Should override be a runtime concern? (4) Can we reuse BuiltInProcessTableFunction? (5) Is the existing StreamExecWatermarkAssigner sufficient?
92026-05-07FeatZhangDetailed reply covering scope, monotonicity contract, planner-level override (with future /*+ RUNTIME_OVERRIDE */ hint), choice of option (b), and reuse of StreamExecWatermarkAssigner with input handling + expression evaluation additions.
102026-05-09Raorao Xiong+1 (non-binding); medallion architecture cited as a typical use case.
112026-05-11Xuyang5 follow-ups: pipeline-position semantics, planner-level monotonicity check overreach, runtime vs. planner override, expression-evaluation specifics, state-management scope. Resolved in v2.

12

2026-05-16

FeatZhang

v2 reply: corrected monotonicity contract, override wording, ExecNode reuse, expression evaluation, and state-management scope; announced FLIP and PR #27984 updates.

13

2026-05-18

Xuyang

No further questions; looking forward to the proposal moving forward.

14

2026-05-20

FeatZhang

Thanked reviewers; announced the FLIP had stabilised; requested remaining concerns within ~3 days before starting VOTE.

15

2026-05-26

Timo

Final feedback: use Calcite lambda expression syntax, consider optional config => MAP<STRING, STRING>, otherwise +1.

Revision History

v1 — 2026-04-21

  • First public draft of the FLIP, posted alongside mail #7.
  • Defines APPLY_WATERMARK(table, DESCRIPTOR(rowtime_col), watermark_expression) as a built-in PTF.
  • Scope: base table, non-materialized view, sub-query.
  • Implementation: new LogicalWatermarkAssigner RelNode + specialized ExecNode reusing StreamExecWatermarkAssigner.

v2 — 2026-05-16 (current)

v2 addresses Xuyang’s round-2 follow-ups (mail #11). The wire-level proposal (syntax, scope, ExecNode strategy) is unchanged; the changes are semantic clarifications.

#SectionChange
1HeaderAdded v2 badge + one-line revision summary; updated Last Updated to 2026-05-16.
2Non-GoalsAdded: this FLIP does not introduce a stateful watermark assigner, idle-source detection, or runtime-level merging of multiple watermark strategies. The APPLY_WATERMARK ExecNode is stateless and equivalent to today’s DDL WatermarkAssignerOperator.
3Logical Plan — Expression validationRemoved “with monotonicity guarantees”. The planner does not enforce monotonicity, exactly like CREATE TABLE … WATERMARK FOR … AS …; monotonicity is a runtime contract of WatermarkAssignerOperator.
4Logical Plan — Operator topologyReplaced “Watermark override” with “Operator topology”. APPLY_WATERMARK introduces an independent LogicalWatermarkAssigner downstream of any upstream assigner — equivalent to two consecutive assignTimestampsAndWatermarks(…) calls in DataStream. No planner-level “override” semantics.
5Physical PlanMade the ExecNode delta explicit: reuse StreamExecWatermarkAssigner, only add (a) rowtime-column resolution from DESCRIPTOR, (b) wiring the watermark expression input to the upstream operator’s output row. No new expression-evaluation capability required (existing ExprCodeGenerator covers it). The ExecNode is stateless.
6Semantics at Different Pipeline Positions (new)Added a dedicated section aligning the mental model with DataStream: each APPLY_WATERMARK in SQL ≡ one assignTimestampsAndWatermarks(…) call. Covers base table, non-materialized view / sub-query, multiple APPLY_WATERMARK in one query, interaction with window TVFs, and interaction with regular / interval / temporal joins.
7Interaction with Existing Table WatermarksReworded the table column header to “Operator-topology behavior”; removed all “override” wording; added a clarifying note that the planner only decides operator topology while the runtime emits watermarks strictly per that topology.
8Open QuestionsRemoved “Scope of input support” (settled: base + view + sub-query) and “Interaction with VECTOR_SEARCH / ML_PREDICT pattern” (settled: specialized ExecNode). Added “State management (resolved in v2)” recording the stateless decision. Remaining open: lambda syntax (waiting on Calcite) and final naming.

References

  • No labels