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, and VECTOR to 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.model so 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, or DOCUMENT logical types.

  • This FLIP does not define a complete video, audio, or document connector suite.

  • This FLIP does not wrap remote AI Functions or ML_PREDICT into 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:

ModulePurpose
pyflink.multimodalMultimodal data processing functions and DataFrame accessors.
pyflink.modelLocal 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:

InterfaceRole
ModelAdapterModel adaptation layer. It loads a class of models and provides the model object to operations. An adapter is code, not model weights.
ModelHandleInvocation boundary for a loaded model instance. It manages model lifecycle and registers operation-specific predict functions such as encode_image and detect_objects.
ModelRefModel 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.
ModelCacheManagerRuntime 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 FILE reference.

  • 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 stageTypical operationsScope in this FLIP
Object accessRead 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 validationRead 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 canonicalizationConvert encoded images or video frames into reusable values.Decoded still images use IMAGE. Videos and long audio initially remain FILE.
TransformationResize, crop, normalize, resample, format conversion, tensor conversion.Provide one-row-in, one-row-out preprocessing functions.
DecompositionExtract frames, split video, split audio, chunk text.Provide table functions that output multiple rows with ordering metadata.
Model invocationEmbedding, 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 outputFrames-to-video, video concat, text join, write image/video/audio file.Provide functions that return FILE references or grouped results.
SinkWrite 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.model only 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:

ItemMeaning
SQL functionSQL function name, argument order, and optional arguments.
PyFlink functionPyFlink factory function and accessor form.
Input typeLogical type of data arguments, such as BYTES, FILE, IMAGE, TENSOR, or STRING.
Return typeLogical type visible to SQL / Table API. Literal arguments may refine mode, shape, or vector dimension.
Row behaviorOne row to one row, one row to many rows, or many rows composed into one result.
Error behaviorHandling of data errors, runtime errors, and model output errors.
Runtime behaviorWhether 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:

ParameterMeaning
uriExternal object URI or path string, used by FETCH_CONTENT or to construct FILE.
contentBYTES for an encoded payload, such as JPEG, PNG, or PDF bytes.
fileFILE logical type, representing a large object reference accessible through the Flink FileSystem.
imgIMAGE value for a decoded still image.
textSTRING text content.
sourceUsed only by metadata / validation functions that accept multiple representations. It may be BYTES, FILE, or IMAGE.

Row behavior is divided into three categories:

Row behaviorMeaningExamples
TransformationOne input row produces one output row.IMAGE_RESIZE, IMAGE_CROP, AUDIO_RESAMPLE, TEXT_NORMALIZE, IMAGE_TO_TENSOR.
DecompositionOne input row produces multiple output rows.VIDEO_EXTRACT_FRAMES, AUDIO_SPLIT, TEXT_CHUNK.
CompositionMultiple 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:

ItemValue
SQL functionIMAGE_DECODE(content, error_mode, mode, max_pixel)
PyFlink functionimage_decode(content, error_mode="raise", mode=None, pixel=None)
Input typeBYTES
Return typeIMAGE; if mode is a literal, return IMAGE(mode)
Row behaviorTransformation
Error behaviorCorrupted images, unsupported modes, and pixel limit overflow are data errors.
Runtime behaviorUses 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.

RepresentationWhen to use
STRING URI/pathExternal object address, usually passed to FETCH_CONTENT or converted to FILE.
BYTES contentEncoded content of relatively small objects, such as JPEG, PNG, or PDF bytes. Suitable as input to IMAGE_DECODE or PDF_TO_IMAGE.
FILELarge 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.
IMAGEDecoded 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.
TENSORModel input or numeric intermediate result produced by explicit conversion functions, such as IMAGE_TO_TENSOR and AUDIO_TO_TENSOR.
VECTOREmbedding 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:

  1. No silent semantic degradation. Unsupported formats, unsupported modes, pixel limit overflow, and lossy high-precision conversions are data errors.

  2. EXIF orientation, ICC conversion, alpha premultiply, mode conversion, and dtype conversion are controlled by explicit arguments.

  3. IMAGE does not carry the original path, MIME type, encoded format, EXIF, or ICC profile.

  4. 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 classExamplesBehavior
Data errorCorrupted 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 errorMissing dependency, model loading failure, GPU OOM, invalid FileSystem credentials, unwritable temporary directory.Fail the current task and let Flink failover handle recovery.
Model output errorLocal 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:

  1. For transformation functions, output positions match input positions.

  2. 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.

  3. With error_mode="raise", a data error fails the current batch. With error_mode="null", only failed rows are mapped to null, provided the return type is nullable.

  4. batch_size only 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 functionPyFlink functionInputReturn typeNotes
FETCH_CONTENT(uri, concurrency)fetch_content(uri, concurrency=None) / col("uri").fetch_content(concurrency=...)STRINGBYTESAsync 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 functionPyFlink functionInputReturn typeNotes
IMAGE_DECODE(content, error_mode, mode, pixel_limit)image_decode(content, error_mode="raise", mode=None, pixel_limit=None)BYTESIMAGE or IMAGE(mode)Decode encoded image bytes.
IMAGE_ENCODE(img, format, quality)image_encode(img, format="JPEG", quality=85)IMAGEBYTESEncode a decoded image into bytes.
IMAGE_WRITE(img, path, format, quality, overwrite)image_write(img, path=..., format="JPEG", quality=85, overwrite=False)IMAGEFILEWrite an image file and return a FILE reference.
IMAGE_METADATA(source)image_metadata(source)BYTES / FILE / IMAGEROW<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 / IMAGEBOOLEANValidate before expensive decode or model invocation.
IMAGE_CONVERT_MODE(img, mode)image_convert_mode(img, mode=...)IMAGEIMAGE(mode)Explicit color mode conversion.
IMAGE_RESIZE(img, width, height, method)image_resize(img, width=..., height=..., method="lanczos")IMAGEIMAGE or fixed-size IMAGEResize to literal width and height.
IMAGE_CROP(img, left, top, right, bottom)image_crop(img, left=..., top=..., right=..., bottom=...)IMAGEIMAGE or fixed-size IMAGECrop by explicit coordinates.
IMAGE_TO_TENSOR(img, width, height, mode, layout, dtype)image_to_tensor(img, width=..., height=..., mode="RGB", layout="CHW", dtype="FLOAT")IMAGETENSOR(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 functionPyFlink functionInputReturn typeNotes
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, STRINGFLOATCompute 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")IMAGEARRAY<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")IMAGEARRAY<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 functionPyFlink functionInputReturn typeNotes
VIDEO_METADATA(file)video_metadata(file)FILEROW<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)FILETABLE<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)FILEARRAY<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, ...)FILETABLE<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=...)FILEFILEWrite 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 columnFILE per groupCompose ordered frames into a video.
VIDEO_CONCAT(segments, file, ordering, output_path)video_concat(segments, file=..., ordering=..., output_path=...)table with FILE segment columnFILE per groupConcatenate 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 functionPyFlink functionInputReturn typeNotes
AUDIO_METADATA(file)audio_metadata(file)FILEROW<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=...)FILEFILEWrite resampled audio.
AUDIO_SPLIT(file, segment_ms, overlap_ms, start_ms, end_ms, output_dir)audio_split(file, segment_ms=..., overlap_ms=0, ...)FILETABLE<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")FILETENSOR(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 functionPyFlink functionInputReturn typeNotes
TEXT_NORMALIZE(text, form, lowercase, trim, remove_control)text_normalize(text, form="NFKC", lowercase=False, trim=True, remove_control=True)STRINGSTRINGUnicode, 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)STRINGTABLE<chunk_index BIGINT, start_offset BIGINT, end_offset BIGINT, text STRING>Output ordered chunks.
TEXT_TOKEN_COUNT(text, tokenizer)text_token_count(text, tokenizer=...)STRINGINTEstimate 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 columnSTRING per groupJoin 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 functionPyFlink functionInputReturn typeNotes
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 / FILETABLE<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.

OptionApplies toMeaning
error_modeall functionsraise, null, or skip when explicitly supported by the function.
batch_sizebatch-capable functionsMaximum batch size for Pandas / Arrow / model batch execution.
concurrencyPython-backed functions with external or async workMaximum in-flight work within one subtask.
timeoutexternal reads, writes, and selected long-running local operationsTimeout for a single external read/write or local long-running operation.
retryidempotent external reads and writesRetry policy for retryable external failures. Non-idempotent writes cannot be retried automatically.
overwritefile-output functionsWhether to overwrite an existing output path.
num_gpus / gpu_typeGPU-capable model-backed functionsResource 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:

ConceptResponsibility
ModelAdapterAdapt a model library, load the model object, and provide model metadata.
ModelHandleHold a loaded adapter, register operations, provide a stable call(...) boundary, bind lifecycle to the operator, and hold model reference counts.
ModelRefResolved model metadata result, describing backend, model id, resolved local path, store/download directories, and load policy.
ModelCacheManagerRuntime 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:

APIMeaning
model_backendLocal 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:

FieldMeaning
local_model_pathThe concrete model file or directory found by the resolver, possibly from a manifest, store_dir, or download_dir.
store_dirRead-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_dirWritable 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:

SharingBehavior
processMaintain _MODEL_CACHE, per-key load locks, and reference counts inside each Python worker process.
sharedShare 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:

  1. The function calls a helper in open() to prepare the model.

  2. The runtime checks optional Python dependencies, sets worker thread count, and generates a cache key from adapter/config/runtime configuration.

  3. load_model_handle(...) applies model runtime configuration and resolves model_id to ModelRef.

  4. The cache manager looks up or loads a ModelHandle according to the sharing policy. On cache miss, the adapter runs load_model(device, **config) to perform the actual model load and returns ModelHandle.

  5. The function implementation registers operations, such as image_embedding or detect_objects.

  6. eval() / batch eval calls handle.call(operation_name, batch, **options).

  7. The function close() calls handle.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:

MetadataWhy it is needed
Purity and side effectsDetermine whether expression reuse or reordering is safe. File-output functions are not side-effect-free.
Row behaviorDistinguish transformation, decomposition, and composition.
Shape refinementInfer fixed-size IMAGE, TENSOR, or VECTOR when literal arguments determine shape.
Batchability and resourcesDetermine 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:

  1. Expression reuse: reuse identical deterministic decode or resize expressions in the same row.

  2. Cheap filter first: when safe, run validation and metadata probe before expensive decode, frame extraction, or model invocation.

  3. 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:

ConfigurationScopeMeaning
python.multimodal.enabledjob/sessionWhether to enable built-in multimodal functions.
python.multimodal.dependency.profilejob/sessionSelect dependency profile, such as image or video-audio.
python.multimodal.default-error-modejob/sessionDefault error mode when a function does not specify one explicitly.
python.multimodal.metrics.enabledjob/sessionWhether to enable multimodal metrics.
python.multimodal.temp-dirTaskManager/jobTask-local temporary directory.
python.multimodal.temp-quotaTaskManager/jobTemporary file capacity limit available to multimodal functions.
python.multimodal.filesystem-bridge.enabledjob/sessionWhether to enable Flink FileSystem access for Python-backed functions.
python.model.store-dirTaskManager/jobRead-only model directory.
python.model.download-dirTaskManager/jobWritable model download cache directory.
python.model.manifestjob/sessionOptional manifest that maps logical model ids to adapter, path, checksum, and version.
python.model.load-policyjob/sessionDefault model loading policy, such as local or auto.
python.model.sharingjob/sessionModel cache sharing scope, such as process or TaskManager-local shared cache.
python.model.cache.max-memoryTaskManager/jobOptional 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, and ModelRef resolution in pyflink.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, and VECTOR boundaries 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 FILE through the FileSystem bridge.

  • Temporary files are cleaned up on success, failure, cancellation, and retry paths.

  • error_mode behavior 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

  • ModelRef resolution 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 ModelHandle serving 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 IMAGE to fixed-shape TENSOR.

  • 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.

  • No labels