DUE TO SPAM, SIGN-UP IS DISABLED. Goto Selfserve wiki signup and request an account.
This page is meant as a template for writing a FLIP. To create a FLIP choose Tools->Copy on this page and modify with your content and replace the heading with the next FLIP number and a description of your issue. Replace anything in italics with your own description.
Status
Current state: [One of "Under Discussion", "Accepted", "Rejected"]
Discussion thread: here (<- link to https://mail-archives.apache.org/mod_mbox/flink-dev/)
JIRA: here (<- link to https://issues.apache.org/jira/browse/FLINK-XXXX)
Released: <Flink Version>
Please keep the discussion on the mailing list rather than commenting on the wiki (wiki discussions get unwieldy fast).
Motivation
AI data processing jobs often need to process images, videos, audio, text, tensors, embeddings, and external object references in the same Flink pipeline. A typical pipeline looks like this:
source -> multimodal preprocessing -> model invocation -> postprocessing -> sink
Before model invocation, this pipeline usually contains a set of stable data processing steps. Images need decode, resize, crop, encode, and tensor conversion. Videos need metadata probing, frame extraction, splitting, and recomposition. Audio needs metadata probing, resampling, time-based splitting, and fixed-window tensor conversion. Text needs normalization, chunking, and token counting. After model invocation, results may also need to be written back to tables, vector indexes, or new external objects.
Flink already has the related building blocks. AI Functions and ML_PREDICT can express model invocation. The PyFlink DataFrame API can express declarative Python-side data processing. Logical types such as TENSOR, IMAGE, FILE, and VECTOR can represent model inputs, decoded images, file references, and embeddings. What is missing today is a standard multimodal data processing layer built on top of these capabilities.
This FLIP does not assume that UDFs cannot implement these features. The goal is to extract common boundaries that repeatedly appear in multimodal data processing pipelines and provide one unified solution:
SQL, Java Table API, and PyFlink should use the same function names, arguments, return types, and error semantics.
Functions that produce multiple rows from one input row need to emit stable ordering metadata, such as frame index, segment time range, or chunk offset.
Python-backed runtime services should centrally handle Python dependency checks, local model management, Flink FileSystem access, batching, metrics, and diagnostic information, instead of requiring each function to implement its own execution glue.
Built-in functions can expose more concrete and stable semantics than opaque UDFs, allowing the planner and runtime to safely optimize decode, resize, tensor conversion, batch inference, and external file output.
Therefore, this FLIP proposes a built-in multimodal operator library. In the Table / SQL layer, "operator library" means built-in scalar functions, table functions, and table-valued operations. It does not introduce a new Flink physical operator type.
Goals
Provide common image, video, audio, and text processing functions that cover stable multimodal data processing steps before and after model invocation.
Expose consistent function semantics across SQL, Java Table API, and the PyFlink DataFrame API.
Use logical types such as
BYTES,FILE,IMAGE,TENSOR, andVECTORto express data boundaries.Provide unified dependency checks, FileSystem access, temporary file handling, batching, error handling, and metrics for Python-backed built-in functions.
Provide
pyflink.modelso that built-in functions and user UDFs can load, cache, and reuse local models inside Python workers.Provide a small set of schema-explicit model-backed batch functions, such as image embedding, image detection, and OCR.
Expose conservative function metadata to the planner and runtime, enabling expression reuse, cheap-filter-first execution, fixed-size tensor paths, and batch execution.
Non-Goals
This FLIP does not replace Python UDFs. UDFs remain the extension mechanism for custom business logic, experimental models, and special library features.
This FLIP does not introduce native
VIDEO,AUDIO, orDOCUMENTlogical types.This FLIP does not define a complete video, audio, or document connector suite.
This FLIP does not wrap remote AI Functions or
ML_PREDICTinto another model invocation API.This FLIP does not define a cluster-level model repository, distributed model cache, or GPU scheduling system.
Public Interfaces
This FLIP introduces two Python modules:
| Module | Purpose |
|---|---|
pyflink.multimodal | Multimodal data processing functions and DataFrame accessors. |
pyflink.model | Local model loading, adaptation, caching, and reuse for built-in functions and user UDFs. |
On the SQL side, Python-backed built-in functions are exposed through the Python module:
LOAD MODULE python;
USE MODULES python, core;
After loading the module, SQL users can call these built-in functions directly. They do not need to manually register Python functions with CREATE TEMPORARY FUNCTION ... LANGUAGE PYTHON.
Multimodal Functions
pyflink.multimodal provides factory functions:
from pyflink.dataframe import col
from pyflink.multimodal import image_decode, image_resize, image_to_tensor
features = (
df.with_columns(image=image_decode(col("content"), mode="RGB", error_mode="null"))
.with_columns(image=image_resize(col("image"), width=224, height=224))
.with_columns(tensor=image_to_tensor(col("image"), width=224, height=224, mode="RGB"))
)
PyFlink also provides accessor syntax to reduce the cost of writing chained expressions:
df = df.with_columns(
image=col("uri").fetch_content(concurrency=8).image.decode(mode="RGB")
)
Accessors are syntactic sugar over factory functions and do not define a second set of semantics. For example, col("img").image.resize(width=224, height=224) is equivalent to image_resize(col("img"), width=224, height=224). Both forms use the same function definition, return type, and error semantics.
Local Model Runtime
pyflink.model provides local model runtime APIs:
| Interface | Role |
|---|---|
ModelAdapter | Model adaptation layer. It loads a class of models and provides the model object to operations. An adapter is code, not model weights. |
ModelHandle | Invocation boundary for a loaded model instance. It manages model lifecycle and registers operation-specific predict functions such as encode_image and detect_objects. |
ModelRef | Model reference descriptor, including model id, local model library identifier, optional local path, store/download directories, and loading policy. Regular users usually do not construct it directly. |
ModelCacheManager | Runtime cache component responsible for cache keys, lookup, loading, reference counting, sharing scope, and resource release. |
When regular users call model-backed functions, they pass the model name and function parameters. The function implementation selects an adapter and delegates model resolution and reuse to pyflink.model:
from pyflink.multimodal import image_embedding, image_detect_objects
features = images.with_columns(
embedding=image_embedding(
col("image"),
model="ViT-B/32",
pretrained="openai",
batch_size=64,
error_mode="null",
)
)
detections = images.with_columns(
objects=image_detect_objects(col("image"), model="yolov8n", confidence=0.25)
)
UDF authors who need custom inference logic can use ModelAdapter and ModelHandle directly to reuse the local model lifecycle provided by Flink.
Proposed Changes
1. Scope And Architecture
The scope of the multimodal operator library is defined by data processing pipeline stages, not by the complete API surface of Pillow, OpenCV, FFmpeg, PyAV, or NLP libraries.
This document uses the following terms:
Frame: a still image extracted from a video at presentation time.
Segment: a continuous video or audio slice cut by time range, usually represented by a
FILEreference.Chunk: a text fragment split by character, token, or paragraph boundary.
These derived units need to carry ordering metadata so that model outputs can be joined back to the original input.
| Pipeline stage | Typical operations | Scope in this FLIP |
|---|---|---|
| Object access | Read FILE, bytes, object paths, URLs, or text columns. | Dataset reading reuses Flink sources and FileSystem. Lightweight helpers are provided for existing URL/path columns. |
| Probe and validation | Read width, height, duration, fps, sample rate, codec, and basic validity. | Provide metadata and validation functions so cheap filters can run before expensive decode or model invocation. |
| Decode and canonicalization | Convert encoded images or video frames into reusable values. | Decoded still images use IMAGE. Videos and long audio initially remain FILE. |
| Transformation | Resize, crop, normalize, resample, format conversion, tensor conversion. | Provide one-row-in, one-row-out preprocessing functions. |
| Decomposition | Extract frames, split video, split audio, chunk text. | Provide table functions that output multiple rows with ordering metadata. |
| Model invocation | Embedding, classification, OCR, ASR, object detection, VLM invocation. | Remote invocation continues to use AI Functions / ML_PREDICT. Local inference provides a small set of schema-explicit batch functions. |
| Composition and file output | Frames-to-video, video concat, text join, write image/video/audio file. | Provide functions that return FILE references or grouped results. |
| Sink | Write to tables, vector indexes, or external systems. | Reuse Flink sinks and connectors. |
The overall architecture has four layers:
Public API
SQL / Java Table API / PyFlink DataFrame API
|
v
Function definitions
names, arguments, type inference, row behavior
|
v
Runtime services
Python binding, dependencies, FileSystem, temp files,
batching, error handling, metrics
|
v
Local model runtime
ModelRef, ModelAdapter, ModelHandle, ModelCacheManager
Before defining concrete functions, these boundaries should be separated:
Function definitions define SQL / Table API visible names, type inference, row behavior, and error semantics.
Runtime services handle dependency checks, FileSystem access, temporary files, batching, and metrics for Python-backed implementations.
pyflink.modelonly handles loading and reusing local models inside Python workers. Remote model invocation remains expressed by AI Functions /ML_PREDICT.
2. Function Semantics
A function definition should use a concise format to describe user-visible behavior relevant to that function:
| Item | Meaning |
|---|---|
| SQL function | SQL function name, argument order, and optional arguments. |
| PyFlink function | PyFlink factory function and accessor form. |
| Input type | Logical type of data arguments, such as BYTES, FILE, IMAGE, TENSOR, or STRING. |
| Return type | Logical type visible to SQL / Table API. Literal arguments may refine mode, shape, or vector dimension. |
| Row behavior | One row to one row, one row to many rows, or many rows composed into one result. |
| Error behavior | Handling of data errors, runtime errors, and model output errors. |
| Runtime behavior | Whether the function supports batching, needs GPU, accesses files, or writes external objects. |
Function tables use the following argument naming conventions to avoid mixing temporary variable names across APIs:
| Parameter | Meaning |
|---|---|
uri | External object URI or path string, used by FETCH_CONTENT or to construct FILE. |
content | BYTES for an encoded payload, such as JPEG, PNG, or PDF bytes. |
file | FILE logical type, representing a large object reference accessible through the Flink FileSystem. |
img | IMAGE value for a decoded still image. |
text | STRING text content. |
source | Used only by metadata / validation functions that accept multiple representations. It may be BYTES, FILE, or IMAGE. |
Row behavior is divided into three categories:
| Row behavior | Meaning | Examples |
|---|---|---|
| Transformation | One input row produces one output row. | IMAGE_RESIZE, IMAGE_CROP, AUDIO_RESAMPLE, TEXT_NORMALIZE, IMAGE_TO_TENSOR. |
| Decomposition | One input row produces multiple output rows. | VIDEO_EXTRACT_FRAMES, AUDIO_SPLIT, TEXT_CHUNK. |
| Composition | Multiple input rows are composed into one grouped result. | VIDEO_FROM_FRAMES, VIDEO_CONCAT, TEXT_JOIN_CHUNKS. |
File output and row behavior are independent dimensions. A file-output function returns a FILE reference instead of file contents. Its function definition needs to specify how the output path is generated, how existing paths are handled, whether the result is committed through a temporary path, and how partial outputs are cleaned up on failure or retry.
Example function definition:
| Item | Value |
|---|---|
| SQL function | IMAGE_DECODE(content, error_mode, mode, max_pixel) |
| PyFlink function | image_decode(content, error_mode="raise", mode=None, pixel=None) |
| Input type | BYTES |
| Return type | IMAGE; if mode is a literal, return IMAGE(mode) |
| Row behavior | Transformation |
| Error behavior | Corrupted images, unsupported modes, and pixel limit overflow are data errors. |
| Runtime behavior | Uses the image dependency profile and does not write external files. |
Data Representations
Later function signatures repeatedly use argument names such as uri, content, file, img, and tensor. This subsection defines the Table / SQL representation behind each name, so external object addresses, encoded bytes, file references, decoded images, and model inputs are not treated as the same concept.
| Representation | When to use |
|---|---|
STRING URI/path | External object address, usually passed to FETCH_CONTENT or converted to FILE. |
BYTES content | Encoded content of relatively small objects, such as JPEG, PNG, or PDF bytes. Suitable as input to IMAGE_DECODE or PDF_TO_IMAGE. |
FILE | Large objects or objects that require a file path, such as videos, long audio, large documents, and written outputs. Video/audio functions initially use FILE as the main representation. |
IMAGE | Decoded still image. It appears only after image decode or frame extraction. Data is provided in ndarray form and consumed by resize, crop, OCR, detection, and similar functions. |
TENSOR | Model input or numeric intermediate result produced by explicit conversion functions, such as IMAGE_TO_TENSOR and AUDIO_TO_TENSOR. |
VECTOR | Embedding result, usually produced by AI Functions, local model functions, or UDFs. |
For example, an image preprocessing pipeline can be written as:
FETCH_CONTENT(uri) -> IMAGE_DECODE(content) -> IMAGE_RESIZE(img) -> IMAGE_TO_TENSOR(img)
Large videos and long audio should not follow the FETCH_CONTENT(uri) -> BYTES path. They should enter VIDEO_METADATA, VIDEO_EXTRACT_FRAMES, AUDIO_SPLIT, or AUDIO_TO_TENSOR as FILE.
With this convention, a function signature directly tells whether the function processes "small encoded content", "external large objects", or "decoded image values".
Image Semantics
Image semantics need to be described separately because image is the first multimodal type that enters a decoded value state. After decode, images may be processed by multiple functions in sequence. Mode, precision, EXIF / ICC handling, and third-party library differences can all affect the final result.
Initial image functions follow these rules:
No silent semantic degradation. Unsupported formats, unsupported modes, pixel limit overflow, and lossy high-precision conversions are data errors.
EXIF orientation, ICC conversion, alpha premultiply, mode conversion, and dtype conversion are controlled by explicit arguments.
IMAGEdoes not carry the original path, MIME type, encoded format, EXIF, or ICC profile.Differences in third-party library behavior must not silently change results. Unsupported formats or modes should produce dependency errors or data errors.
Error Handling
Built-in functions distinguish three classes of errors:
| Error class | Examples | Behavior |
|---|---|---|
| Data error | Corrupted image, corrupted video, unsupported codec, unsupported mode, pixel limit overflow. | Controlled by the function's error_mode, such as raise, null, and skip when explicitly supported by the function. |
| Runtime error | Missing dependency, model loading failure, GPU OOM, invalid FileSystem credentials, unwritable temporary directory. | Fail the current task and let Flink failover handle recovery. |
| Model output error | Local model returns None, shape mismatch, label count mismatch, invalid postprocessing output. | Return null only when the output is nullable and error_mode="null"; otherwise fail. |
error_mode only applies to data errors declared by the function definition. For example, IMAGE_DECODE(content, error_mode => 'null') may return null for a corrupted image, while error_mode => 'raise' fails the current task. Missing dependencies, model loading failures, GPU OOM, invalid FileSystem credentials, and unwritable temporary directories are runtime errors. They are not controlled by error_mode; they fail the task and are handled by Flink failover.
Batching
Batching is an execution optimization and does not change row-by-row semantics. Python-backed functions may use row-based UDF execution or Pandas / Arrow batch UDF execution.
Batch execution follows these rules:
For transformation functions, output positions match input positions.
Null values or rows that fail preprocessing are removed from the dense batch before model invocation, then scattered back to their original positions after inference.
With
error_mode="raise", a data error fails the current batch. Witherror_mode="null", only failed rows are mapped to null, provided the return type is nullable.batch_sizeonly affects throughput and latency. It does not change output ordering, output schema, or error classification.
3. Built-In Function Set (WIP)
The initial function set focuses on common pipeline boundaries and does not enumerate the full API surface of underlying libraries.
Object Access Functions
Dataset reading still uses Flink sources, connectors, and FileSystem. For existing URI/path string columns in a table, FETCH_CONTENT provides a lightweight entry point that reads relatively small object content and returns BYTES. Large videos and long audio should not be read as whole-object BYTES; they should enter video/audio functions as FILE references.
| SQL function | PyFlink function | Input | Return type | Notes |
|---|---|---|---|---|
FETCH_CONTENT(uri, concurrency) | fetch_content(uri, concurrency=None) / col("uri").fetch_content(concurrency=...) | STRING | BYTES | Async function that reads content through Flink FileSystem or a supported object store client. |
Image Functions
Image functions are defined around the IMAGE logical type. Encoded images use BYTES; decoded still images use IMAGE; model inputs use TENSOR. To read encoded bytes from a URL or path, use FETCH_CONTENT(uri) first, then call IMAGE_DECODE(content, ...).
| SQL function | PyFlink function | Input | Return type | Notes |
|---|---|---|---|---|
IMAGE_DECODE(content, error_mode, mode, pixel_limit) | image_decode(content, error_mode="raise", mode=None, pixel_limit=None) | BYTES | IMAGE or IMAGE(mode) | Decode encoded image bytes. |
IMAGE_ENCODE(img, format, quality) | image_encode(img, format="JPEG", quality=85) | IMAGE | BYTES | Encode a decoded image into bytes. |
IMAGE_WRITE(img, path, format, quality, overwrite) | image_write(img, path=..., format="JPEG", quality=85, overwrite=False) | IMAGE | FILE | Write an image file and return a FILE reference. |
IMAGE_METADATA(source) | image_metadata(source) | BYTES / FILE / IMAGE | ROW<width INT, height INT, mode STRING, channels INT, format STRING> | Read image metadata. |
IMAGE_IS_VALID(source, mode, pixel_limit) | image_is_valid(source, mode=None, pixel_limit=None) | BYTES / FILE / IMAGE | BOOLEAN | Validate before expensive decode or model invocation. |
IMAGE_CONVERT_MODE(img, mode) | image_convert_mode(img, mode=...) | IMAGE | IMAGE(mode) | Explicit color mode conversion. |
IMAGE_RESIZE(img, width, height, method) | image_resize(img, width=..., height=..., method="lanczos") | IMAGE | IMAGE or fixed-size IMAGE | Resize to literal width and height. |
IMAGE_CROP(img, left, top, right, bottom) | image_crop(img, left=..., top=..., right=..., bottom=...) | IMAGE | IMAGE or fixed-size IMAGE | Crop by explicit coordinates. |
IMAGE_TO_TENSOR(img, width, height, mode, layout, dtype) | image_to_tensor(img, width=..., height=..., mode="RGB", layout="CHW", dtype="FLOAT") | IMAGE | TENSOR(dtype, ...) | Convert a prepared image to tensor. |
Example:
SELECT
IMAGE_TO_TENSOR(
IMAGE_RESIZE(IMAGE_DECODE(content, 'null', 'RGB', 20000000), 224, 224, 'lanczos'),
224,
224,
'RGB',
'CHW',
'FLOAT'
) AS input_tensor
FROM images;
Model-Backed Image Functions (Options)
Remote embedding, classification, OCR, ASR, and VLM invocation continues to use AI Functions / ML_PREDICT. The model-backed functions here are for loading local models inside Python workers and running batch inference. The initial scope only includes schema-explicit functions, instead of a fully generic PREDICT(model, value, output_schema):
| SQL function | PyFlink function | Input | Return type | Notes |
|---|---|---|---|---|
IMAGE_TEXT_SIMILARITY(img, text, model, pretrained, batch_size, error_mode) | image_text_similarity(img, text, model="ViT-B/32", pretrained="openai", batch_size=..., error_mode="raise") | IMAGE, STRING | FLOAT | Compute image-text similarity with the same class of vision-language model. |
IMAGE_DETECT_OBJECTS(img, model, confidence, imgsz, iou, batch_size, error_mode) | image_detect_objects(img, model="yolov8n", confidence=0.25, imgsz=640, iou=0.5, batch_size=..., error_mode="raise") | IMAGE | ARRAY<ROW<label STRING, score FLOAT, box ARRAY<FLOAT>>> | Batch object detection with a fixed postprocessing schema. |
IMAGE_OCR(img, lang, batch_size, error_mode) | image_ocr(img, lang=None, batch_size=..., error_mode="raise") | IMAGE | ARRAY<ROW<text STRING, score FLOAT, box ARRAY<FLOAT>>> | Batch OCR. |
These functions reuse local model weights through ModelCacheManager. The model argument is a user-visible logical model id. At runtime, it is resolved to a ModelRef and then loaded by the corresponding ModelAdapter.
Video Functions
Video input and output use FILE. A frame is a still image extracted from video presentation time. A segment is a continuous video slice cut by time range. Frame-level processing expands to multiple IMAGE rows through table functions. Segment-level processing returns multiple FILE rows. Both forms carry ordering metadata related to the output unit.
| SQL function | PyFlink function | Input | Return type | Notes |
|---|---|---|---|---|
VIDEO_METADATA(file) | video_metadata(file) | FILE | ROW<duration_ms BIGINT, width INT, height INT, fps DOUBLE, frame_count BIGINT, video_codec STRING, audio_codec STRING, format STRING> | Read container and stream metadata. |
VIDEO_EXPLODE_FRAMES(file, every_ms, start_ms, end_ms, mode, max_frames) | video_explode_frames(file, every_ms=..., start_ms=None, end_ms=None, mode="RGB", max_frames=None) | FILE | TABLE<frame_index BIGINT, pts_ms BIGINT, frame IMAGE> | UDTF that outputs ordered frames. |
VIDEO_EXTRACT_FRAMES(file, every_ms, start_ms, end_ms, mode, max_frames) | video_extract_frames(file, every_ms=..., start_ms=None, end_ms=None, mode="RGB", max_frames=None) | FILE | ARRAY<ROW<frame_index BIGINT, pts_ms BIGINT, frame IMAGE>> | Output a list of video frames. |
VIDEO_SPLIT(file, segment_ms, overlap_ms, start_ms, end_ms, output_dir) | video_split(file, segment_ms=..., overlap_ms=0, ...) | FILE | TABLE<segment_index BIGINT, start_ms BIGINT, end_ms BIGINT, file FILE> | Write ordered video segments, with metadata only in the row. |
VIDEO_CLIP(file, start_ms, end_ms, output_path, overwrite) | video_clip(file, start_ms=..., end_ms=..., output_path=...) | FILE | FILE | Write one clipped video. |
VIDEO_FROM_FRAMES(frames, frame, ordering, output_path, fps, codec) | video_from_frames(frames, frame=..., ordering=..., output_path=..., fps=...) | table with IMAGE frame column | FILE per group | Compose ordered frames into a video. |
VIDEO_CONCAT(segments, file, ordering, output_path) | video_concat(segments, file=..., ordering=..., output_path=...) | table with FILE segment column | FILE per group | Concatenate ordered video segments. |
Large videos can first use VIDEO_METADATA to read duration, fps, and codec, then use VIDEO_EXTRACT_FRAMES for time-based sampling, or use VIDEO_SPLIT to produce bounded segment files. Downstream models or image functions process frame/segment-level data, avoiding passing the whole video as an in-memory object.
Example:
SELECT v.id, f.frame_index, f.pts_ms, IMAGE_RESIZE(f.frame, 224, 224, 'lanczos') AS frame
FROM videos AS v,
LATERAL TABLE(VIDEO_EXPLODE_FRAMES(v.file, 1000, NULL, NULL, 'RGB', NULL)) AS f;
Audio Functions
Long audio input and output use FILE. When window length, sample rate, and channel count are determined by literal arguments, audio can be converted to a fixed-shape TENSOR.
| SQL function | PyFlink function | Input | Return type | Notes |
|---|---|---|---|---|
AUDIO_METADATA(file) | audio_metadata(file) | FILE | ROW<duration_ms BIGINT, sample_rate INT, channels INT, codec STRING, format STRING> | Read audio metadata. |
AUDIO_RESAMPLE(file, sample_rate, channels, output_format, output_path, overwrite) | audio_resample(file, sample_rate=..., channels=..., output_path=...) | FILE | FILE | Write resampled audio. |
AUDIO_SPLIT(file, segment_ms, overlap_ms, start_ms, end_ms, output_dir) | audio_split(file, segment_ms=..., overlap_ms=0, ...) | FILE | TABLE<segment_index BIGINT, start_ms BIGINT, end_ms BIGINT, file FILE> | Write ordered audio segments. |
AUDIO_TO_TENSOR(file, sample_rate, channels, start_ms, duration_ms, layout, dtype) | audio_to_tensor(file, sample_rate=..., channels=..., start_ms=0, duration_ms=..., layout="TC", dtype="FLOAT") | FILE | TENSOR(dtype, ...) | Convert a fixed time window to tensor. |
Long audio enters the pipeline as FILE. When an implementation based on FFmpeg, soundfile, or another library requires a local path, the runtime opens the FILE as a task-local temporary file. The user API still uses FILE. The pipeline can then use AUDIO_SPLIT to generate bounded audio segments and run ASR, embedding, or tensor conversion on each segment.
Text Functions
Text functions cover lightweight preprocessing before embedding, retrieval, or model invocation.
| SQL function | PyFlink function | Input | Return type | Notes |
|---|---|---|---|---|
TEXT_NORMALIZE(text, form, lowercase, trim, remove_control) | text_normalize(text, form="NFKC", lowercase=False, trim=True, remove_control=True) | STRING | STRING | Unicode, casing, whitespace, and control character handling. |
TEXT_CHUNK(text, strategy, chunk_size, overlap, tokenizer) | text_chunk(text, strategy="char", chunk_size=..., overlap=0, tokenizer=None) | STRING | TABLE<chunk_index BIGINT, start_offset BIGINT, end_offset BIGINT, text STRING> | Output ordered chunks. |
TEXT_TOKEN_COUNT(text, tokenizer) | text_token_count(text, tokenizer=...) | STRING | INT | Estimate model invocation cost or filter before chunking. |
TEXT_JOIN_CHUNKS(chunks, text, ordering, separator) | text_join_chunks(chunks, text=..., ordering=..., separator="") | table with chunk text column | STRING per group | Join text chunks back in order. |
Document Functions
Document functions process document objects such as PDFs. Document content can come from BYTES returned by FETCH_CONTENT(uri) or from a connector-provided FILE reference. Large documents should prefer FILE to avoid loading the entire object into memory.
| SQL function | PyFlink function | Input | Return type | Notes |
|---|---|---|---|---|
PDF_TO_IMAGE(content, image_format, dpi, start_page, end_page) | pdf_to_image(content, image_format="png", dpi=200, start_page=None, end_page=None) | BYTES / FILE | TABLE<mime_type STRING, page_no INT, image_content BYTES> | Render PDF pages to ordered image bytes. Call IMAGE_DECODE afterwards if image processing is needed. |
4. Python-Backed Execution And Runtime
Python-backed built-in functions use the same function definition in SQL, Java Table API, and PyFlink.
SQL / Java Table API / PyFlink expression
|
v
Built-in function definition
|
v
Python implementation binding
|
v
Python worker
For SQL and Java Table API users, functions such as IMAGE_RESIZE(...) and VIDEO_EXTRACT_FRAMES(...) are regular built-in functions. Users do not need to know the underlying Python class names or write CREATE TEMPORARY FUNCTION ... LANGUAGE PYTHON.
For Python-backed functions, the function definition records the corresponding PyFlink factory function and literal options. At execution time, the Python worker imports that factory from modules distributed with PyFlink, constructs a UDF / UDTF wrapper, and passes the SQL / Table API arguments to it.
Runtime Options
Runtime options are configuration. They are literals, or otherwise known during planning.
| Option | Applies to | Meaning |
|---|---|---|
error_mode | all functions | raise, null, or skip when explicitly supported by the function. |
batch_size | batch-capable functions | Maximum batch size for Pandas / Arrow / model batch execution. |
concurrency | Python-backed functions with external or async work | Maximum in-flight work within one subtask. |
timeout | external reads, writes, and selected long-running local operations | Timeout for a single external read/write or local long-running operation. |
retry | idempotent external reads and writes | Retry policy for retryable external failures. Non-idempotent writes cannot be retried automatically. |
overwrite | file-output functions | Whether to overwrite an existing output path. |
num_gpus / gpu_type | GPU-capable model-backed functions | Resource hints for scheduling, placement, and diagnostics. |
Dependencies, FileSystem, And Temporary Files
Python-backed functions may depend on image, video, audio, or model libraries. Flink does not run pip install in the TaskManager runtime. Dependencies should be provided through images, Python archives, or offline dependency artifacts. The function wrapper checks dependencies and versions during open().
Functions that read or write FILE use Flink FileSystem configuration and credentials. fsspec, pyarrow.fs, or third-party clients can be implementation details, but they must not be the only way to access Flink FILE.
Video, audio, and encoder libraries may use task-local temporary files. Temporary files are execution intermediate state, not user-visible output. They are not written to Flink state and are cleaned up on success, failure, cancellation, and retry paths.
5. Local Model Runtime
The local model runtime is separate from remote AI Functions. Remote model services continue to be expressed by AI Functions / ML_PREDICT. The local model runtime only handles locating, loading, caching, sharing, and releasing model weights inside Python workers. It serves two types of calls: built-in model-backed functions and user UDFs that need to reuse the same model lifecycle.
The local model runtime contains four core concepts:
| Concept | Responsibility |
|---|---|
ModelAdapter | Adapt a model library, load the model object, and provide model metadata. |
ModelHandle | Hold a loaded adapter, register operations, provide a stable call(...) boundary, bind lifecycle to the operator, and hold model reference counts. |
ModelRef | Resolved model metadata result, describing backend, model id, resolved local path, store/download directories, and load policy. |
ModelCacheManager | Runtime cache component responsible for cache keys, load locks, reference counting, process/shared sharing, and resource release. |
ModelAdapter
ModelAdapter is the integration layer for one class of models or model libraries. For example, OpenCLIP, Ultralytics, and EasyOCR can each have their own adapter. The adapter API contains:
| API | Meaning |
|---|---|
model_backend | Local model library identifier, such as open_clip, ultralytics, or easyocr. It is used to validate that a ModelRef is passed to the correct adapter. |
load_model(device, **config) | Import third-party libraries, read ModelRef, load weights, and return an in-memory model object. |
iter_local_model_path_candidates(cache_dir, model_id) | Enumerate possible local model paths according to backend directory conventions, for resolver lookup. |
metadata() | Return model dimension, label space, or other diagnostic information. |
close() | Release model, processor, tokenizer, or GPU resources. |
An adapter is a code adaptation layer, not model weights.
ModelHandle
ModelHandle holds a loaded adapter and provides operation dispatch:
handle.register_operation("image_embedding", encode_image_predict)
handle.register_operation("detect_objects", detect_objects_predict)
handle.call("image_embedding", batch, **options)
An operation predict function receives the loaded model object as its first argument: operation_fn(model, *args, **kwargs). It must be a module-level function or class static method, not a lambda, closure, or bound method, so that the proxy invocation boundary remains stable under shared cache.
ModelHandle does not declare SQL function signatures or output schemas. Those belong to the built-in function or UDF that calls it. When a function instance is closed, it calls handle.release(), and the cache manager updates reference counts and releases resources.
ModelRef And Resolution
The input to model resolution is a logical model_id, a local model library identifier, and runtime configuration. The resolution result is a ModelRef, not a loaded model. The model library identifier here is only used for local model loading, such as OpenCLIP or Ultralytics. It is not a remote AI provider.
When ModelRef.local_model_path exists, the adapter should load that local file or directory first. When it does not exist, load_policy="auto" allows the adapter to call the corresponding model library to download or load the model by model_id; load_policy="local" fails fast.
Path configuration is divided into three fields:
| Field | Meaning |
|---|---|
local_model_path | The concrete model file or directory found by the resolver, possibly from a manifest, store_dir, or download_dir. |
store_dir | Read-only model store, which may come from an image layer, read-only PVC, NAS, or FUSE mount. The runtime does not write to it. |
download_dir | Writable download cache directory, used by third-party library downloads or model reuse in auto mode. |
Separating store_dir and download_dir keeps pre-provisioned models read-only, while giving auto mode a writable cache location on each worker.
ModelCacheManager
ModelCacheManager is a runtime component. Python APIs may expose it through helpers such as prepare_and_load_model_handle(...) and free_models(), without requiring users to instantiate a manager object directly.
The cache key is composed from the adapter class, logical model id, function config, manifest path/mtime, store_dir, download_dir, load_policy, and similar fields. The same cache key means the same loaded ModelHandle can be reused.
Model sharing has two scopes:
| Sharing | Behavior |
|---|---|
process | Maintain _MODEL_CACHE, per-key load locks, and reference counts inside each Python worker process. |
shared | Share one handle among multiple Python worker processes in the same TaskManager through Beam MultiProcessShared; inference calls are forwarded through a local proxy. |
The cache manager is not a cluster-level model repository and does not handle GPU scheduling. It only handles local model reuse and release inside the Python execution environment.
Resolution Flow
Local model functions or UDFs use models through the following flow:
The function calls a helper in
open()to prepare the model.The runtime checks optional Python dependencies, sets worker thread count, and generates a cache key from adapter/config/runtime configuration.
load_model_handle(...)applies model runtime configuration and resolvesmodel_idtoModelRef.The cache manager looks up or loads a
ModelHandleaccording to the sharing policy. On cache miss, the adapter runsload_model(device, **config)to perform the actual model load and returnsModelHandle.The function implementation registers operations, such as
image_embeddingordetect_objects.eval()/ batch eval callshandle.call(operation_name, batch, **options).The function
close()callshandle.release(). The cache manager decrements the reference count and releases the model or shared handle when the reference count reaches zero.
This flow allows the same model to serve multiple operations and avoids loading the same weights repeatedly.
6. Planner And Runtime Optimizations (WIP)
Built-in multimodal functions expose conservative metadata. Without metadata, the planner treats the function as an opaque UDF and preserves the user-written execution order.
The initial scope focuses on four kinds of metadata:
| Metadata | Why it is needed |
|---|---|
| Purity and side effects | Determine whether expression reuse or reordering is safe. File-output functions are not side-effect-free. |
| Row behavior | Distinguish transformation, decomposition, and composition. |
| Shape refinement | Infer fixed-size IMAGE, TENSOR, or VECTOR when literal arguments determine shape. |
| Batchability and resources | Determine whether the runtime can use Pandas / Arrow / model batch execution and whether GPU is required. |
This metadata does not change SQL semantics. It only provides conservative optimization entry points to the planner and runtime. For example, repeated IMAGE_DECODE(content, ...) calls in the same row can be reused when the function is deterministic and side-effect-free. IMAGE_RESIZE(..., 224, 224) followed by IMAGE_TO_TENSOR(..., 'CHW', 'FLOAT') can infer a fixed shape, and the runtime can preallocate buffers. IMAGE_EMBEDDING(..., batch_size => 64) can pack valid rows into dense batches, while null rows or rows from corrupted images remain in their original positions. File-output functions have side effects and cannot participate in this type of expression reuse or reordering.
The initial implementation supports the following optimization entry points:
Expression reuse: reuse identical deterministic decode or resize expressions in the same row.
Cheap filter first: when safe, run validation and metadata probe before expensive decode, frame extraction, or model invocation.
Fixed-size execution path: when resize and tensor conversion produce a known shape, use preallocated buffers.
Example:
features = (
images
.with_columns(image=col("content").image.decode(mode="RGB", error_mode="null"))
.with_columns(image=col("image").resize(width=224, height=224))
.with_columns(tensor=col("image").to_tensor(width=224, height=224, mode="RGB"))
.with_columns(embedding=image_embedding(col("tensor"), model="ViT-B/32", batch_size=64))
)
resize(width=224, height=224) and to_tensor(width=224, height=224, mode="RGB") allow the runtime to use a fixed-shape tensor path. Corrupted images that become null during decode do not enter the model batch.
7. Configuration
Initial configuration options:
| Configuration | Scope | Meaning |
|---|---|---|
python.multimodal.enabled | job/session | Whether to enable built-in multimodal functions. |
python.multimodal.dependency.profile | job/session | Select dependency profile, such as image or video-audio. |
python.multimodal.default-error-mode | job/session | Default error mode when a function does not specify one explicitly. |
python.multimodal.metrics.enabled | job/session | Whether to enable multimodal metrics. |
python.multimodal.temp-dir | TaskManager/job | Task-local temporary directory. |
python.multimodal.temp-quota | TaskManager/job | Temporary file capacity limit available to multimodal functions. |
python.multimodal.filesystem-bridge.enabled | job/session | Whether to enable Flink FileSystem access for Python-backed functions. |
python.model.store-dir | TaskManager/job | Read-only model directory. |
python.model.download-dir | TaskManager/job | Writable model download cache directory. |
python.model.manifest | job/session | Optional manifest that maps logical model ids to adapter, path, checksum, and version. |
python.model.load-policy | job/session | Default model loading policy, such as local or auto. |
python.model.sharing | job/session | Model cache sharing scope, such as process or TaskManager-local shared cache. |
python.model.cache.max-memory | TaskManager/job | Optional local model cache memory limit. |
Design Decisions
Why Built-In Functions Instead Of UDF Examples?
UDFs remain supported. Built-in functions are introduced because common multimodal pipeline steps need stable contracts across APIs. Function names, arguments, return types, row behavior, error modes, metrics, dependency checks, FileSystem access, and batching behavior are defined by Flink once and reused by SQL, Java Table API, and PyFlink.
This also gives the planner and runtime enough information to optimize decode, resize, tensor conversion, frame extraction, and local model batching.
Why Keep Remote Model Invocation In AI Functions?
Remote model services are still best expressed through AI Functions / ML_PREDICT, including provider configuration, timeout, retry, metrics, and async invocation. The multimodal operator library handles data processing before and after model invocation and does not add a new remote model invocation entry point.
Why Add pyflink.model?
Local model inference faces a different problem: model weights need to be located, loaded, cached, shared, and released inside Python workers. pyflink.model provides this runtime for built-in model-backed functions and user UDFs. ModelCacheManager makes model reuse an explicit component instead of hiding it inside each function implementation.
Why Return FILE For File Outputs?
Large videos, audio, and materialized results should not be stored as bytes in a row. File-output functions write objects through Flink FileSystem and return a FILE reference. The row stores the external object reference. The function is responsible for write, commit, overwrite, and cleanup semantics.
Example: End-To-End Pipeline
Invoke a remote model after image preprocessing:
LOAD MODULE python;
USE MODULES python, core;
WITH image_features AS (
SELECT
id,
IMAGE_TO_TENSOR(
IMAGE_RESIZE(IMAGE_DECODE(content, 'null', 'RGB', 20000000), 224, 224, 'lanczos'),
224,
224,
'RGB',
'CHW',
'FLOAT'
) AS tensor
FROM images
)
SELECT
id,
ML_PREDICT(tensor, MODEL => 'clip-vit-b32') AS embedding
FROM image_features;
Reuse image functions after video frame extraction:
SELECT
v.id,
f.frame_index,
f.pts_ms,
IMAGE_TO_TENSOR(IMAGE_RESIZE(f.frame, 224, 224, 'lanczos'), 224, 224, 'RGB', 'CHW', 'FLOAT') AS tensor
FROM videos AS v,
LATERAL TABLE(VIDEO_EXTRACT_FRAMES(v.file, 1000, NULL, NULL, 'RGB', NULL)) AS f;
Reuse a local model in PyFlink:
from pyflink.dataframe import col
from pyflink.multimodal import image_decode, image_resize, image_embedding
features = (
images
.with_columns(image=image_decode(col("content"), mode="RGB", error_mode="null"))
.with_columns(image=image_resize(col("image"), width=224, height=224))
.with_columns(embedding=image_embedding(col("image"), model="ViT-B/32", batch_size=64))
)
Compatibility, Deprecation, And Migration Plan
This FLIP only adds APIs and functions. It does not deprecate UDFs, AI Functions, ML_PREDICT, or Flink connectors.
User-defined Python function behavior remains unchanged.
SQL users can still manually register custom Python functions.
Remote model invocation continues to use AI Functions /
ML_PREDICT.Pipelines that use bytes, rows, or UDF-private objects do not need to migrate.
New functions can be adopted gradually by data processing pipeline stage.
Test Plan
API Tests
Function resolution after SQL module loading.
Java Table API function definitions and type inference.
PyFlink factory functions and accessor syntax.
Validation for invalid arguments, literal options, and type errors.
API behavior of
ModelAdapter,ModelHandle, model cache helpers, andModelRefresolution inpyflink.model.
Function Semantics Tests
Transformation functions preserve row count.
Decomposition functions output ordering metadata.
Composition functions require grouping and ordering information.
File-output functions handle overwrite, temporary path, commit, cleanup, and retry.
BYTES,FILE,IMAGE,TENSOR, andVECTORboundaries are correct.Image mode, EXIF / ICC arguments, unsupported modes, and high-precision input behavior are explicit.
Runtime Tests
Diagnostics for missing dependencies and version conflicts.
Python wrapper
open()/close()lifecycle.Reading and writing
FILEthrough the FileSystem bridge.Temporary files are cleaned up on success, failure, cancellation, and retry paths.
error_modebehavior for corrupted images, corrupted videos, unsupported codecs, and pixel limit overflow.Pandas / Arrow / batch execution preserves output order and null positions.
Decomposition functions preserve output ordering metadata under backpressure.
Local Model Runtime Tests
ModelRefresolution through local path, store directory, download directory, and manifest.Dependency check, loading, metadata, and close behavior of
ModelAdapter.Cache hit, cache miss, reference counting, eviction, and cleanup in
ModelCacheManager.Process-local and TaskManager-local shared cache behavior in
ModelCacheManager.One
ModelHandleserving multiple operations, such as image embedding and text embedding.Behavior for model output
None, shape mismatch, and postprocessing error under nullable / non-nullable outputs.
Planner And End-To-End Tests
Metadata extraction for purity, side effects, row behavior, shape refinement, batchability, and resource hints.
Preserve opaque UDF behavior when metadata is missing.
Expression reuse for deterministic image decode.
Cheap validation runs before expensive decode or model invocation in safe cases.
Type inference from fixed-size
IMAGEto fixed-shapeTENSOR.Image decode -> resize -> tensor -> remote AI Function.
Image decode -> resize -> local model batch embedding.
Video extract frames -> image transform.
Audio metadata -> resample -> split.
Text normalize -> chunk -> embedding.
Rejected Alternatives
Only Provide UDF Examples
This approach is flexible, but function names, return schemas, ordering metadata, dependencies, error semantics, and metrics are all left to users.
Only Expose PyFlink DataFrame Functions
SQL and Java Table API users would not be able to use the same capabilities, and the planner would not be able to optimize based on the same built-in function semantics.
Require SQL Users To Register Python Functions Manually
This requires users to know Python implementation class names and distribute Python source files for common functions. It is not suitable as an entry point for built-in functions.
Wrap AI Functions As Multimodal Functions
This would create two remote model invocation APIs. Remote model invocation continues to be expressed by AI Functions / ML_PREDICT.
Load One Model Per Function Instance
This is simple to implement, but when the same model is used by multiple functions or operations, weights are loaded repeatedly, wasting memory and increasing startup latency. ModelCacheManager allows compatible calls to reuse the same ModelHandle.