Motivation

As described in FLIP-577 [1], many users have started to use Flink in production for AI-oriented data processing workloads. A typical pipeline looks like this:

Source -> fetch multimodal content

               -> preprocessing (decode, resize, tokenize)

                -> inference (remote service or local GPU)

               -> postprocessing

               -> Sink

In such pipelines, a single row processed by Flink is no longer just a small structured row. It may contain much larger multimodal objects, such as vectors (embeddings), tensors, images, audio, and video. This shift introduces a new requirement for Flink's type system: Flink needs a stable way to represent multimodal data across SQL/Table, DataStream, Java UDFs, PyFlink UDFs, connectors, and formats.

In existing Flink multimodal jobs, objects such as vectors (embeddings), tensors, and images are usually encoded as VARBINARY, STRING, ARRAY, or custom ROW structures. These representations can make a pipeline work, but they lose important semantics:

  • VARBINARY only represents a sequence of bytes. It cannot indicate whether the bytes are a JPEG file, raw RGB pixels, or model input vector/tensor data. Metadata such as dtype, shape, and image mode becomes an external convention in user code or connector options.

  • ARRAY can represent numeric sequences, but it is a generic SQL collection. It cannot distinguish ordinary arrays from fixed-length vectors/tensors, cannot naturally express multidimensional shapes, and does not support tensor/vector-specific dtypes such as uint8, uint32, and uint64. For fixed-length vector values, it also makes it difficult to apply vector-specific encoding optimizations.

  • ROW<data, shape, other_meta_field> can encode the structure, but the planner and runtime only see an ordinary row. They do not know that the value is a tensor or an image. In addition, for fixed-shape tensors and fixed-length vectors, shape or dimension should be schema metadata, but a row encoding usually repeats it in every row.

These workarounds make the same logical value appear differently at different boundaries. A decoded uint8[224,224,3] image or a float32[768] vector may be represented as bytes, nested arrays, or a user-defined row. As a result, the planner and runtime cannot validate fixed shapes, UDFs cannot rely on a unified input type, Python and Java paths may interpret the data differently, and connectors cannot infer or validate the external schema from the Flink schema.

This FLIP introduces three first-class multimodal data types to make these contracts explicit:

  • TENSOR represents a dense n-dimensional tensor with dtype and shape semantics, similar to Numpy's nd.array [2]. It is used for model inputs/outputs and other n-dimensional numeric payloads. Tensor's dtype is independent of Flink top-level SQL scalar types, so it can represent common AI ecosystem dtypes such as uint8, uint32, and uint64 without introducing unsigned SQL scalar types and without relying on Java unsigned primitives.

  • VECTOR represents a dense fixed-length one-dimensional vector. It is used for embeddings, feature vectors, and vector database connectors. For embedding columns, VECTOR('float32', 768) is closer to schema expressions used in vector search and vector database ecosystems [3] [4][5][6] than ARRAY<FLOAT> or TENSOR('float32', 768), while the runtime can still reuse the representation of fixed-shape tensors.

  • IMAGE represents a decoded still image value. It is the semantic boundary between encoded bytes and model-ready tensors, and it is the typical object manipulated by image processing libraries. Existing systems also expose image-specific types or schemas instead of treating images only as opaque bytes [7][14]. It represents decoded pixel data in a canonical layout with an explicit mode, not an encoded file, a file reference, or a tensor.

Goals

The goal of this FLIP is to add lightweight multimodal data types to Flink, so that Flink can consistently represent decoded images, multidimensional numeric tensors, and fixed-length vectors across schema, runtime, UDF, and connector/format boundaries instead of degrading them to untyped bytes, nested arrays, or custom rows.

Specifically, this FLIP aims to:

  • Introduce three first-class data types, TENSOR, VECTOR, and IMAGE, covering SQL/Table, DataStream, and PyFlink.

  • Define an ElementDType enum shared by tensor, vector, and image payloads. It is independent of Flink top-level SQL scalar types and covers common multimodal dtypes including signed integers, unsigned integers (uint8, uint16, uint32, uint64), and floating point dtypes (float32, float64) [8]. Dtypes that are not native JVM primitive scalar types only apply to tensor/vector/image payloads and do not become Flink SQL scalar types, keeping the type system impact limited.

  • For tensors, support TENSOR('dtype') and TENSOR('dtype', d1, d2, ...). The former represents variable-shape tensors where shape is carried by each value; the latter represents fixed-shape tensors where shape is part of the schema.

  • For vectors, support VECTOR('dtype', dimension). The dtype must be declared explicitly and can represent dense vector dtypes such as float32, float64, int8 and uint8. The vector dimension is always part of the schema. Variable-length vectors are not supported.

  • For images, support three type forms: unconstrained IMAGE, mode-constrained IMAGE('RGB'), and fixed-shape IMAGE('RGB', 224, 224). This provides progressive type narrowing and fixed-length serialization optimizations.

  • Clarify connector and format contracts. IMAGE and TENSOR are primarily pipeline-internal types. External systems commonly interact through BYTES for encoded images or STRING for external content references, and connectors/formats are not required to support them natively. Connectors/formats that support VECTOR must preserve the full logical semantics. Unsupported types should be rejected during validation.

Non-Goals

This FLIP does not try to turn Flink into a tensor computation or image processing framework, nor does it extend the general numeric type system of Flink SQL. The following items are explicitly out of scope:

  • Introducing a complete multimodal function library.

  • Adding Flink top-level unsigned SQL scalar types. uint8, uint32, and similar dtypes only appear as multimodal dtypes in TENSOR('uint8', ...), VECTOR('uint8', ...), or the pixel dtype derived from ImageMode.

  • Supporting sparse tensors or sparse vectors. Such optimizations can be introduced by a follow-up FLIP if needed.

Type Semantics

ElementDType Semantics

ElementDType is the element dtype enum shared by Tensor, Vector, and Image. It follows the common tensor ecosystem convention of separating element dtype from tensor shape and value layout [9][10][11][12]. It is independent of Flink top-level SQL scalar types and describes the element type stored in a contiguous multimodal payload. ElementDType can represent unsigned dtypes that Java and Flink SQL do not have as scalar types, such as uint8, uint16, uint32, and uint64. These dtypes only apply to multimodal payloads.

ElementDType

SQL canonical name

Java carrier

Description

BOOL

'bool'

byte

Stored as one byte per value

INT8

'int8'

byte

Signed 8-bit integer

UINT8

'uint8'

byte

An int helper can provide an unsigned view

INT16

'int16'

short

Signed 16-bit integer

UINT16

'uint16'

short

An int helper can provide an unsigned view

INT32

'int32'

int

Signed 32-bit integer

UINT32

'uint32'

int

A long helper can provide an unsigned view

INT64

'int64'

long

Signed 64-bit integer

UINT64

'uint64'

long

A BigInteger helper can provide an unsigned view

FLOAT32

'float32'

float

32-bit floating point

FLOAT64

'float64'

double

64-bit floating point

Vector Semantics

VECTOR represents a dense fixed-length one-dimensional numeric vector. It is used for embedding columns, feature vectors, and vector database sources/sinks.

VECTOR = dtype + dimension + data

dtype and dimension are stored in schema, data is stored per row

  • dtype: The element type of the vector. It follows tensor dtype semantics. VECTOR supports dense fixed-width ElementDType values, including bool, signed integer, unsigned integer, and floating point dtypes. BOOL vectors are represented as one byte per element in this FLIP. They are intended for boolean feature vectors or masks, not for bit-packed binary vector indexes. Connectors or vector search functions may reject vectors whose dtype is not supported by the target system.

  • dimension: The vector dimension. It must be a positive integer literal.

Following most vector databases and databases with vector support[3] [4], this FLIP models VECTOR as a fixed-dimension type and does not introduce variable-length vectors. For embeddings, feature vectors, and vector database fields, the dimension is typically determined by the same embedding model or feature pipeline. Vectors with different dimensions belong to different vector spaces.

SQL Semantics

Operation

Behavior

Nullability

A vector column itself can be null, but vector elements are non-null.

Equality / Hashing / Ordering

SQL equality, hashing, or total ordering is not defined for vectors. Vectors cannot be directly used in GROUP BY, DISTINCT, ORDER BY, or comparison predicates.

Implicit cast

Not supported.

Explicit cast to string

Supports cast to CHAR / VARCHAR, producing metadata such as dtype and dimension. Example format: VECTOR(dtype='float32', dimension=128). The string is for debugging only, does not print payload data, and is not round-trippable.

Explicit cast to ARRAY

Supports limited explicit casts for interoperability with existing ARRAY-based SQL/UDF/connector paths. VECTOR('bool', d), VECTOR('float32', d), VECTOR('float64', d), VECTOR('int8', d), VECTOR('int16', d), VECTOR('int32', d), and VECTOR('int64', d) can be cast to ARRAY<BOOLEAN>, ARRAY<FLOAT>, ARRAY<DOUBLE>, ARRAY<TINYINT>, ARRAY<SMALLINT>, ARRAY<INT>, and ARRAY<BIGINT>, respectively. Casts from uint* vectors to ARRAY are not supported.

Explicit cast from ARRAY

Supports explicit casts to a target VECTOR('dtype', dimension). The ARRAY element type must be explicitly castable to the SQL scalar type corresponding to the target vector dtype. For VECTOR('bool', d), the ARRAY element type must be BOOLEAN. Runtime validation checks that the array length equals the dimension and that no elements are null.

For example, VECTOR('float32', 768) represents a 768-dimensional vector.

VECTOR('dtype', d) and TENSOR('dtype', d) are representation-compatible, but they are not the same logical type. They can share payload-only internal storage, serializers, and Arrow FixedSizeListVector representation. However, catalog metadata, SQL strings, type hints, JSON serialization, explain output, and default external conversion preserve VECTOR('dtype', d) as an independent type. The following table compares VECTOR and rank-1 TENSOR.


VECTOR('dtype', d)

TENSOR('dtype', d)

User-facing semantics

Embedding, feature vector, query vector, vector database field

Generic rank-1 tensor, model input/output, or numeric payload

Meaning of length

Dimension is part of the vector space and is fixed within the column

Shape describes tensor structure; rank-1 is only one tensor form

Connector interpretation

Vector-aware connectors can map it to external vector fields such as Milvus/Elasticsearch and validate dtype/dimension

Tensor is currently a Flink-internal transport type and has no general connector mapping

Future extension point

Vector distance functions, vector search connectors, ANN indexes, vector-specific encoding

Tensor shape operations, model I/O, image-to-tensor, and generic tensor paths

Connector and Format Boundary

VECTOR has direct connector integration scenarios, such as Milvus. A vector-aware connector can map VECTOR('float32', 768) or VECTOR('int8', 768) to external vector fields such as Milvus FloatVector/Int8Vector [5] or a pgvector column [8]. The connector must validate dtype and dimension. If the external system does not support the declared vector type, validation should fail. A typical implementation is shown below:

CREATE TABLE vector_store (
   id         BIGINT,
   content    STRING,
   embedding  VECTOR('float32', 768)   -- The sink connector recognizes this as a vector column
) WITH (
   'connector' = 'milvus',
   'collection' = 'documents',
   -- No need to manually specify vector_column, dimension, or distance_metric,
   -- because the VECTOR type already contains this information.
);

INSERT INTO vector_store
SELECT id, content, AI_EMBED(model, content) AS embedding
FROM documents;

Tensor Semantics

TENSOR represents a dense n-dimensional array with dtype and shape semantics. Elements are stored in C-order / row-major order:

TENSOR = dtype + shape + data
For fixed-shape tensors, dtype and shape are stored in schema, data is stored per row.
For variable-shape tensors, dtype is stored in the schema, while shape and data are stored per row.


  • dtype: All tensor elements have the same ElementDType.

  • shape: The tensor dimensions. For fixed-shape tensors, shape is stored in the schema. For variable-shape tensors, shape is stored in each value.

SQL Semantics

Operation

Behavior

Nullability

A tensor column itself can be null, but tensor elements are non-null.

Equality / Hashing / Ordering

SQL equality, hashing, or total ordering is not defined for tensors. Tensors cannot be directly used in GROUP BY, DISTINCT, ORDER BY, or comparison predicates.

Implicit cast

Only supports TENSOR('dtype', d1, d2, ...) -> TENSOR('dtype').

Explicit cast to string

Supports cast to CHAR / VARCHAR, producing metadata such as dtype and shape. Example format: TENSOR(dtype='uint8', shape=[2,2,2]). The string is for debugging only, does not print payload data, and is not round-trippable.

For example, TENSOR('float32', 768) represents a dense 768-dimensional FLOAT32 tensor in each row.

TENSOR('uint8', 224, 224, 3) represents a common HWC uint8 dense tensor used in image processing.

TENSOR does not represent sparse tensors, ragged nested arrays, arrays with per-element nulls, or tensor objects from any specific machine learning framework. The goal of the TENSOR type is to let the schema carry dtype and shape semantics, let the runtime efficiently transport contiguous payloads, and let Java/Python UDFs pass data to third-party libraries such as NumPy [2], PyTorch [4], TensorFlow [3], ONNX Runtime / ONNX model formats [12], DJL, and ND4J.

Connector and Format Boundary

TENSOR is primarily a transport type between the pipeline and UDFs in this FLIP. Connectors or formats that do not support TENSOR should reject TENSOR columns during validation and must not silently write only payload bytes. If users want to write a custom external representation, they should explicitly convert the value to BYTES, ROW, ARRAY, or a format-specific structure through a UDF or a future dedicated function. From Flink's type system perspective, that column is no longer a native TENSOR column.

IMAGE Semantics

IMAGE represents a decoded still image. It does not carry source file metadata such as file path, MIME type, EXIF, ICC profile, or encoded format.

IMAGE = pixel data + mode + height + width
  • pixel data: Decoded pixel bytes in HWC (height, width, channels) layout, linearly arranged in row-major, channel-interleaved order.

  • mode: Describes channel semantics, channel count, and numeric interpretation of pixel elements. Mode definitions follow Pillow [13].

  • height / width: Image pixel dimensions.

The byte offset of pixel element (h, w, c) is:

byteOffset(h, w, c) = (((h * width) + w) * channels + c) * mode.byteWidth()

Mode

ImageMode determines the number of channels, element byte width, and numeric interpretation:

Mode

Channels

Byte width

DType

Description

L

1

1

uint8

Single-channel luminance, interpreted as unsigned byte [0, 255]

LA

2

1

uint8

Luminance + straight alpha

RGB

3

1

uint8

Red, green, blue, stored in R/G/B channel order

RGBA

4

1

uint8

Red, green, blue, straight alpha

A non-null Image value must satisfy: mode != null && height > 0 && width > 0 && pixelData.length == height * width * mode.channels() * mode.byteWidth().

All four current modes interpret pixel elements as unsigned bytes. If multi-byte dtypes are supported in the future, endian, alignment, and mode codes must also be defined.

IMAGE Type Forms

IMAGE exposes three forms in the public API:

Form

SQL type representation

Meaning

Unconstrained

IMAGE

mode, height, and width are all determined by runtime values

Mode-constrained

IMAGE(mode)
for example, IMAGE('RGB')

mode is fixed at the type level; height and width are determined at runtime

Fixed-shape

IMAGE(mode, height, width)
for example, IMAGE('RGB', 224, 224)

mode, height, and width are all fixed at the type level

These fixed forms are type-level constraints. A mode-constrained type fixes mode; a fixed-shape type fixes mode, height, and width. The engine will not try to automatically repair mismatches between a type declaration and actual data. Implementations should validate at necessary boundaries and expose errors directly.

SQL Semantics

Operation

Behavior

Nullability

An IMAGE column can be NULL.

Equality / Hashing / Ordering

Not supported. IMAGE cannot be used as a SQL key that requires comparable or hashable semantics.

Implicit cast

Only supports widening within the IMAGE family: fixed-shape -> mode-constrained -> unconstrained. Implicit narrowing, mode conversion, and resize are not supported.

Explicit cast to string

Supports cast to CHAR / VARCHAR, producing metadata without pixel data. Example format: IMAGE(mode='RGB', height=224, width=224). The string is for debugging only and discards pixel data.

Connector and Format Boundary

This FLIP does not require connectors or formats to natively read or write IMAGE. IMAGE is a decoded image value materialized inside the pipeline and is mainly intended for image processing rather than storage or transport. External sources usually represent image locations with URLs or object references, encoded image bytes with BYTES, or raw pixel data with TENSOR. Therefore, IMAGE values are usually produced by an explicit decode function or UDF and written out after being converted to encoded images, tensors, or other formats.

Public Interfaces

ElementDType

package org.apache.flink.types;

@PublicEvolving
public enum ElementDType {
    BOOL("bool", 1),
    INT8("int8", 1),
    UINT8("uint8", 1),
    INT16("int16", 2),
    UINT16("uint16", 2),
    INT32("int32", 4),
    UINT32("uint32", 4),
    INT64("int64", 8),
    UINT64("uint64", 8),
    FLOAT32("float32", 4),
    FLOAT64("float64", 8);

    public String canonicalName();

    public int byteWidth();

    public static ElementDType fromCanonicalName(String name);
}

Vector Interfaces

Vector

package org.apache.flink.types.vector;

@PublicEvolving
public interface Vector {

    /** Returns the vector dtype. */
    ElementDType getDType();

    /** Returns the fixed vector dimension. */
    int getDimension();

    /** Returns raw vector payload bytes in C-order. */
    byte[] toBytes();

    /** Returns a read-only raw byte view. */
    ByteBuffer asByteBuffer();
}

DataStream API

package org.apache.flink.api.common.typeinfo;

public class Types {
    /**
     * Returns type information for fixed-length vector values.
     *
     * <p>The dtype must be a supported dense vector dtype. Invalid dtypes fail during
     * type construction or validation.
     */
    public static TypeInformation<Vector> VECTOR(ElementDType dtype, int dimension);
}
package org.apache.flink.api.common.typeinfo;

// A fixed-length vector serializer only writes payload bytes;
// dtype and dimension come from the schema.
@PublicEvolving
public final class VectorTypeInfo extends TypeInformation<Vector> {
    private final ElementDType dtype;
    private final int dimension;

    public ElementDType getDType();

    public int getDimension();

    @Override
    public Class<Vector> getTypeClass() {
        return Vector.class;
    }

    @Override
    public TypeSerializer<Vector> createSerializer(SerializerConfig config) {
        return new VectorSerializer(dtype, dimension);
    }
    ...
}


Table API / SQL

package org.apache.flink.table.types.logical;

public final class VectorType extends LogicalType {

    /** Vector dtype. */
    private final ElementDType dtype;

    /** Fixed positive dimension. */
    private final int dimension;

    public ElementDType getDType();

    public int getDimension();

    public boolean supportsInputConversion(Class<?> clazz);

    public boolean supportsOutputConversion(Class<?> clazz);

    // org.apache.flink.types.vector.Vector.class
    public Class<?> getDefaultConversion();
}
package org.apache.flink.table.data;

@PublicEvolving
public interface RowData {
    ...

    Vector getVector(int pos);
}
package org.apache.flink.table.data;

@PublicEvolving
public interface ArrayData {
    ...

    /** Returns the Vector value at the given position. */
    Vector getVector(int pos);
}
package org.apache.flink.table.api;

public final class DataTypes {
    /**
     * Creates a fixed-length vector type.
     *
     * <p>The dtype must be a supported dense vector dtype. Invalid dtypes fail during
     * type construction or validation.
     */
    public static DataType VECTOR(ElementDType dtype, int dimension);
}
package org.apache.flink.table.types.logical;

@PublicEvolving
public enum LogicalTypeRoot {
    ...

    VECTOR(LogicalTypeFamily.EXTENSION);
}




PyFlink API

from pyflink.table import DataTypes

DataTypes.VECTOR("float32", 768)
DataTypes.VECTOR("uint8", 128)

Python UDFs see vector values as numpy.ndarray values whose dtype matches the schema VECTOR dtype and whose shape is (dimension,).

For batch UDFs:

input:
  pd.Series[np.ndarray], where each row is an ndarray with shape=(dimension,)

output:
  pd.Series[np.ndarray], where each ndarray has dtype and shape matching result_type

Examples

Java scalar UDF:

import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.types.vector.Vector;

import java.nio.FloatBuffer;

public class VectorCosineDistance extends ScalarFunction {

    public Double eval(Vector left, Vector right) {
        // ...
        FloatBuffer leftValues = left.asByteBuffer().asFloatBuffer();
        FloatBuffer rightValues = right.asByteBuffer().asFloatBuffer();

        double dot = 0.0;
        double leftNorm = 0.0;
        double rightNorm = 0.0;
        for (int i = 0; i < left.getDimension(); i++) {
            float l = leftValues.get(i);
            float r = rightValues.get(i);
            dot += l * r;
            leftNorm += l * l;
            rightNorm += r * r;
        }

        if (leftNorm == 0.0 || rightNorm == 0.0) {
            return null;
        }

        return 1.0 - dot / (Math.sqrt(leftNorm) * Math.sqrt(rightNorm));
    }
}

Table API / SQL example:

Vector left =
        GenericVector.fromFloat32Array(new float[] {1.0f, 0.0f, 1.0f});
Vector right =
        GenericVector.fromFloat32Array(new float[] {0.0f, 1.0f, 1.0f});

DataStream<Row> vectorStream =
        env.fromData(
                Types.ROW_NAMED(
                        new String[] {"left", "right"},
                        Types.VECTOR(ElementDType.FLOAT32, 3),
                        Types.VECTOR(ElementDType.FLOAT32, 3)),
                Row.of(left, right));

tableEnv.createTemporaryView(
        "VectorInput",
        vectorStream,
        Schema.newBuilder()
                .column("left", DataTypes.VECTOR(ElementDType.FLOAT32, 3))
                .column("right", DataTypes.VECTOR(ElementDType.FLOAT32, 3))
                .build());

tableEnv.createTemporarySystemFunction("vector_cosine_distance", VectorCosineDistance.class);

tableEnv.executeSql("SELECT vector_cosine_distance(left, right) FROM VectorInput");

Python example:


from pyflink.table import DataTypes
from pyflink.table.udf import udf

import numpy as np
import pandas as pd

def _vector_cosine_distance_value(left: np.ndarray, right: np.ndarray):
    if left is None or right is None:
        return None
    left_norm = np.linalg.norm(left)
    right_norm = np.linalg.norm(right)
    if left_norm == 0.0 or right_norm == 0.0:
        return None
    return float(1.0 - np.dot(left, right) / (left_norm * right_norm))

# Row-level UDF.
@udf(result_type=DataTypes.DOUBLE())
def vector_cosine_distance(left: np.ndarray, right: np.ndarray):
    return _vector_cosine_distance_value(left, right)

# Batch / Pandas UDF.
def vector_cosine_distance_batch(left: pd.Series, right: pd.Series) -> pd.Series:
    return pd.Series(
        [
            _vector_cosine_distance_value(l, r)
            for l, r in zip(left, right)
        ],
        index=left.index)

Tensor Interfaces

Tensor

package org.apache.flink.types.tensor;

@PublicEvolving
public interface Tensor {

    /** Returns the shape array of the tensor. */
    int[] getShape();

    /** Returns raw tensor data as a byte array in C-order, little-endian. */
    byte[] toBytes();

    /** Returns the element data type. */
    ElementDType getDType();

    /** Returns a read-only byte view of the tensor data. */
    ByteBuffer asByteBuffer();
}

DataStream API

package org.apache.flink.api.common.typeinfo;

public class Types {

    /** Returns type information for variable-shape tensor values. */
    public static TypeInformation<Tensor> TENSOR(ElementDType dtype);

    /** Returns type information for fixed-shape tensor values. */
    public static TypeInformation<Tensor> TENSOR(ElementDType dtype, int... shape);
}
package org.apache.flink.api.common.typeinfo;

@PublicEvolving
public final class TensorTypeInfo extends TypeInformation<Tensor> {
    private final ElementDType dtype;
    private final @Nullable int[] shape;

    public ElementDType getDType();

    /**
     * Returns the fixed shape of this tensor type.
     *
     * <p>If not present, tensors of this type are variable-shape and each value carries its own shape.
     */
    public Optional<int[]> getShape();

    @Override
    public Class<Tensor> getTypeClass() {
        return Tensor.class;
    }

    @Override
    public TypeSerializer<Tensor> createSerializer(SerializerConfig config) {
        return new TensorSerializer(dtype, shape);
    }
    ...
}

Table API / SQL

package org.apache.flink.table.types.logical;

public final class TensorType extends LogicalType {

    private final ElementDType dtype;

    /** null means variable-shape. */
    private final @Nullable int[] shape;

    public ElementDType getDType();

    public Optional<int[]> getShape();

    public boolean supportsInputConversion(Class<?> clazz);

    public boolean supportsOutputConversion(Class<?> clazz);

    // org.apache.flink.types.tensor.Tensor.class
    public Class<?> getDefaultConversion();
}
package org.apache.flink.table.data;

@PublicEvolving
public interface RowData {
    ...

    Tensor getTensor(int pos);
}
package org.apache.flink.table.data;

@PublicEvolving
public interface ArrayData {
    ...

    /** Returns the tensor value at the given position. */
    Tensor getTensor(int pos);
}
package org.apache.flink.table.api;

public final class DataTypes {
    /** Creates a variable-shape tensor type. */
    public static DataType TENSOR(ElementDType dtype);

    /** Creates a fixed-shape tensor type. */
    public static DataType TENSOR(ElementDType dtype, int... shape);
}
package org.apache.flink.table.types.logical;

@PublicEvolving
public enum LogicalTypeRoot {
    ...

    TENSOR(LogicalTypeFamily.EXTENSION);
}

PyFlink API

from pyflink.table import DataTypes

# Fixed-shape tensor.
DataTypes.TENSOR("float32", 768)
DataTypes.TENSOR("uint8", 224, 224, 3)
DataTypes.TENSOR("uint32", 23)

# Variable-shape tensor.
DataTypes.TENSOR("float32")


Python UDFs see tensor values as numpy.ndarray values that contain dtype and shape information.

For batch UDFs:

fixed-shape input:
  pd.Series[np.ndarray], where each row is an ndarray

fixed-shape output:
  pd.Series[np.ndarray]

variable-shape input:
  pd.Series[np.ndarray]

variable-shape output:
  pd.Series[np.ndarray]

Examples

Java scalar UDF:

import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.types.tensor.Tensor;

import java.nio.FloatBuffer;

public class TensorNorm extends ScalarFunction {

    public double eval(Tensor tensor) {
        if (tensor == null) {
            return 0.0;
        }

        int[] shape = tensor.getShape();
        int size = 1;
        for (int dim : shape) {
            size *= dim;
        }

        FloatBuffer values = tensor.asByteBuffer().asFloatBuffer();

        double sum = 0.0;
        for (int i = 0; i < size; i++) {
            float v = values.get(i);
            sum += v * v;
        }

        return Math.sqrt(sum);
    }
}

Table API / SQL example:

byte[] tensorBytes =
        ByteBuffer.allocate(4 * Float.BYTES)
                .order(ByteOrder.LITTLE_ENDIAN)
                .putFloat(1.0f)
                .putFloat(2.0f)
                .putFloat(3.0f)
                .putFloat(4.0f)
                .array();

Tensor tensor =
        GenericTensor.fromBytes(
                ElementDType.FLOAT32,
                new int[] {2, 2},
                tensorBytes);

DataStream<Row> tensorStream =
        env.fromData(
                Types.ROW_NAMED(
                        new String[] {"t"},
                        Types.TENSOR(ElementDType.FLOAT32, 2, 2)),
                Row.of(tensor));

tableEnv.createTemporaryView(
        "TensorInput",
        tensorStream,
        Schema.newBuilder()
                .column("t", DataTypes.TENSOR(ElementDType.FLOAT32, 2, 2))
                .build());

tableEnv.createTemporarySystemFunction("tensor_norm", TensorNorm.class);

tableEnv.executeSql("SELECT tensor_norm(t) FROM TensorInput");

Python Example:

# Row-level UDF.
@udf(result_type=DataTypes.DOUBLE())
def tensor_norm(tensor: np.ndarray):
    if tensor is None:
        return None
    return float(np.linalg.norm(tensor.reshape(-1)))

# Batch / Pandas UDF.
class ResNetPredictor:
    """Pandas batch UDF for tensor columns."""

    def __init__(self):
        ...

    def __call__(self, batch):
        tensor_column = batch["norm_image"]
        arrays = np.stack(tensor_column.to_numpy())
        ...
        return {
            "image_url": batch["image_url"],
            "label": pd.Series([self.categories[pred] for pred in preds]),
        }


Image Interfaces

package org.apache.flink.types.image;

/** Represents a decoded still image. */
@PublicEvolving
public interface Image {

    /** Creates an Image from raw pixel bytes in HWC layout. */
    static Image of(byte[] data, ImageMode mode, int height, int width) { ... }

    /** Returns a copy of pixel bytes in HWC layout. */
    byte[] toByteArray();

    /** Returns a read-only ByteBuffer view of pixel bytes. */
    ByteBuffer asByteBuffer();

    /** Returns the image mode. */
    ImageMode getMode();

    /** Returns the pixel height. */
    int getHeight();

    /** Returns the pixel width. */
    int getWidth();

    /** Returns the number of channels. */
    int getChannels();
}

ImageMode

ImageMode describes the stable mode code, canonical name, number of channels, and dtype. The stable code is used to align Java, Python, Arrow, and other cross-language protocols.

package org.apache.flink.types.image;

/** Describes channel semantics and pixel element representation. */
@PublicEvolving
public enum ImageMode {
    L(0, "L", 1, ElementDType.UINT8),
    LA(1, "LA", 2, ElementDType.UINT8),
    RGB(2, "RGB", 3, ElementDType.UINT8),
    RGBA(3, "RGBA", 4, ElementDType.UINT8);

    /** Returns the stable binary protocol code. */
    public int code() {...}

    /** Returns the canonical mode name. */
    public String canonicalName() {...}

    /** Returns the number of channels. */
    public int channels() {...}

    /** Returns the dtype of a single channel element. */
    public ElementDType dtype() {...}

    /** Returns the byte width of a single channel element. */
    public int byteWidth() {...}

    /** Parses a mode from a binary protocol code. */
    public static ImageMode fromCode(int code) {...}

    /** Parses a mode from a canonical mode name. */
    public static ImageMode fromCanonicalName(String name) {...}
}

DataStream API

package org.apache.flink.api.common.typeinfo;

@PublicEvolving
public class Types {
    ...

    /** Unconstrained image type. */
    public static TypeInformation<Image> IMAGE() { ... }

    /** Mode-constrained image type. */
    public static TypeInformation<Image> IMAGE(ImageMode mode) { ... }

    /** Fixed-shape image type. */
    public static TypeInformation<Image> IMAGE(ImageMode mode, int height, int width) { ... }
}
package org.apache.flink.api.common.typeinfo;

@PublicEvolving
public final class ImageTypeInfo extends TypeInformation<Image> {
    public static ImageTypeInfo of() { ... }
    public static ImageTypeInfo of(ImageMode mode) { ... }
    public static ImageTypeInfo of(ImageMode mode, int height, int width) { ... }

    /** Returns null if mode is not fixed. */
    @Nullable public ImageMode getMode() { ... }

    /** Returns null if height is not fixed. */
    @Nullable public Integer getHeight() { ... }

    /** Returns null if width is not fixed. */
    @Nullable public Integer getWidth() { ... }

    /** Returns true if mode, height, and width are all fixed. */
    public boolean isFixedShape() { ... }

    @Override
    public Class<Image> getTypeClass() { return Image.class; }
}

Table API / SQL

package org.apache.flink.table.data;

@PublicEvolving
public interface RowData {
    ...

    Image getImage(int pos);
}
package org.apache.flink.table.data;

@PublicEvolving
public interface ArrayData {
    ...

    Image getImage(int pos);
}
package org.apache.flink.table.api;

@PublicEvolving
public final class DataTypes {
    ...

    /** Unconstrained image type. */
    public static DataType IMAGE() { ... }

    /** Mode-constrained image type. */
    public static DataType IMAGE(ImageMode mode) { ... }

    /** Fixed-shape image type. */
    public static DataType IMAGE(ImageMode mode, int height, int width) { ... }
}
package org.apache.flink.table.types.logical;

/** Logical type for decoded image values. */
@PublicEvolving
public final class ImageType extends LogicalType {
    public ImageType() { ... }
    public ImageType(ImageMode mode) { ... }
    public ImageType(ImageMode mode, int height, int width) { ... }

    /** Returns null if mode is not fixed. */
    @Nullable public ImageMode getMode() { ... }

    /** Returns null if height is not fixed. */
    @Nullable public Integer getHeight() { ... }

    /** Returns null if width is not fixed. */
    @Nullable public Integer getWidth() { ... }

    /** Returns true if mode, height, and width are all fixed. */
    public boolean isFixedShape() { ... }

    ...
}
package org.apache.flink.table.types.logical;

public enum LogicalTypeRoot {
    ...

    IMAGE(LogicalTypeFamily.EXTENSION);
}

SQL Functions

This FLIP only defines the signatures and high-level semantics of the basic IMAGE functions. Detailed parameter validation, error handling, and library-specific behavior are left to the implementation.

Function

Signature

Description

IMAGE_DECODE

(BYTES image_bytes, STRING mode[, STRING on_error]) -> IMAGE

Decodes encoded image bytes into an IMAGE. image_bytes is external encoded image content. mode describes the target output image mode or preservation policy. on_error describes how decode failures are handled.

IMAGE_ENCODE

(IMAGE image, STRING format[, INT quality]) -> BYTES

Encodes an IMAGE into external image bytes. image is a decoded image value, format describes the target encoding format, and quality describes a lossy encoding quality parameter.

IMAGE_TO_TENSOR

(IMAGE image[, STRING layout]) -> TENSOR

Converts IMAGE pixel data to a TENSOR in the specified layout. Dtype and shape are inferred from image mode, height, and width.

IMAGE_MODE

(IMAGE) -> STRING

Returns the image mode.

IMAGE_WIDTH

(IMAGE) -> INT

Returns the pixel width.

IMAGE_HEIGHT

(IMAGE) -> INT

Returns the pixel height.

IMAGE_CHANNELS

(IMAGE) -> INT

Returns the number of channels.

PyFlink API

from pyflink.table import DataTypes

DataTypes.IMAGE()
DataTypes.IMAGE("RGB")
DataTypes.IMAGE("RGB", 224, 224)

In Python UDFs, image values are represented as an Image dataclass:

@dataclass
class Image:
    data: np.ndarray    # shape=(H, W, C), dtype=uint8, C-contiguous
    mode: ImageMode     # enum (L, LA, RGB, RGBA)

PyFlink native Image.data uses a unified HWC three-dimensional contract. If a single-channel grayscale input comes from a two-dimensional ndarray, it should be normalized to (H, W, 1) at the IMAGE boundary. The underlying pixel bytes are still interpreted with the same HWC linear layout.

Examples

Python Pandas UDF for batch image brightness:

@udf(result_type=DataTypes.DOUBLE(), func_type="pandas")
def mean_brightness(images: pd.Series) -> pd.Series:
    return images.apply(
        lambda img: float(img.data.mean()) if img is not None else None
    )

The following job reads encoded image bytes, explicitly decodes them into IMAGE values, filters by IMAGE attributes, normalizes images into fixed-shape model inputs, and calls a user-defined image classification function:

CREATE TABLE raw_images (
  id STRING,
  image_bytes BYTES,
  source STRING
) WITH (...);

-- Built-in/User-defined functions used by this example:
-- IMAGE_DECODE: BYTES -> IMAGE('RGB')
-- IMAGE_RESIZE: IMAGE('RGB'), INT, INT -> IMAGE('RGB', 224, 224)
-- IMAGE_CLASSIFY: IMAGE('RGB', 224, 224) -> ROW<label STRING, score DOUBLE>

-- Decode encoded bytes into IMAGE values explicitly.
WITH decoded AS (
  SELECT
    id,
    source,
    IMAGE_DECODE(image_bytes, 'RGB') AS image
  FROM raw_images
),
-- Filter by IMAGE attributes before model inference.
valid_images AS (
  SELECT id, source, image
  FROM decoded
  WHERE IMAGE_WIDTH(image) >= 224
    AND IMAGE_HEIGHT(image) >= 224
),
-- Normalize images into the fixed input contract expected by the model.
model_inputs AS (
  SELECT
    id,
    source,
    IMAGE_RESIZE(image, 224, 224) AS input_image
  FROM valid_images
)
SELECT
  id,
  source,
  result.label,
  result.score
FROM model_inputs,
LATERAL TABLE(IMAGE_CLASSIFY(input_image)) AS result(label, score);

Proposed Changes

Vector/Tensor

Generic Classes

GenericVector and GenericTensor are the default @Internal on-heap implementations. They defensively copy payload data during construction.

/** Default on-heap implementation of Vector. Immutable, contiguous dense layout. */
@Internal
public final class GenericVector implements Vector, Serializable  { ... }

/** Default on-heap implementation of Tensor. Immutable, contiguous dense layout. */
@Internal
public final class GenericTensor implements Tensor, Serializable  { ... }

Serialization

VectorSerializer only supports fixed-length vectors:

Type form

Serialization format

getLength()

VECTOR('dtype', dimension)

payload_bytes

dimension * dtype.byteWidth()

TensorSerializer chooses the serialization format based on the tensor type form:

Type form

Serialization format

getLength()

variable-shape TENSOR('dtype')

rank(4B) + dim0(4B) + ... + dimn(4B) + payloadlength(4B) + payloadbytes

-1

fixed-shape TENSOR('dtype', d1, d2, ...)

payload_bytes

d1 d2 ... * dtype.byteWidth()

Serializers must validate that the value dtype, shape, or dimension matches the schema/type information, and that payload length equals element count multiplied by ElementDType.byteWidth(). The purpose of fixed-shape tensors and vectors is that each row's payload length is known from the type, allowing serializers and columnar transport to use fixed-length physical representations.

TensorSerializerSnapshot records dtype and optional fixed shape. VectorSerializerSnapshot records dtype and dimension. During restore, serializers are reconstructed from these parameters. Compatibility checks use a conservative policy: only if dtype, shape, or dimension exactly matches between old and new snapshots should the result be compatibleAsIs; otherwise it is incompatible.

Python Side

Python does not define two unrelated runtime representations for tensors and vectors. They share the same NumPy-native value contract, dtype mapping, and Arrow/Pandas transport rules. The difference is only the schema logical kind: TENSOR represents n-dimensional tensors, while VECTOR represents fixed-length one-dimensional vectors.

  • Schema mapping: PyFlink proto / logical type information needs to represent logical kind, dtype, and shape information. TENSOR carries dtype and optional fixed shape; an absent (None) shape means a variable-shape tensor. VECTOR carries dtype and fixed dimension. It can be viewed as a fixed-shape dense numeric value with shape (dimension,), but the logical kind must remain VECTOR and must not be downgraded to rank-1 TENSOR.

  • Row-level UDFs: Python UDF inputs and return values use numpy.ndarray [2]. TENSOR('dtype', d1, ...) corresponds to an ndarray with matching dtype and shape (d1, ...). TENSOR('dtype') obtains shape from each value. VECTOR('dtype', dimension) corresponds to an ndarray with shape (dimension,). Null values map to None.

  • Pandas / Arrow UDFs: The base representation is pd.Series[np.ndarray]. Fixed-shape tensors and vectors can use Arrow FixedSizeListVector to represent fixed shape/dimension [16], and can expose a batch-level NumPy view on the Python side, for example (batch_size, *shape) for tensors and (batch_size, dimension) for vectors. Variable-shape tensors use StructVector or an equivalent representation such as {shape, values}, and are exposed as row-level ndarrays by default.

  • dtype alignment: Java and Python align through stable ElementDType canonical names, for example uint8 -> np.uint8, uint32 -> np.uint32, uint64 -> np.uint64, and float32 -> np.float32 [11]. These dtypes do not require corresponding Flink SQL scalar types.

Connector / Format Boundary

TENSOR and VECTOR are schema-level contracts, not aliases of BYTES or ARRAY. A connector or format that declares support for these types must preserve the full logical contract. Unsupported types should fail during validation and must not be silently converted to BYTES, ARRAY, ROW, or RAW.

Image

GenericImage

GenericImage is the default @Internal implementation of Image. It stores decoded pixel data in the canonical HWC layout and is used as the default runtime value when no specialized representation is required.

package org.apache.flink.types.image;

/** Default internal implementation of Image using the canonical HWC layout. */
@Internal
public final class GenericImage implements Image, Serializable  { ... }

Serialization

The RowData / ArrayData paths in the table runtime use a self-describing format:

mode_code(1B) + height(4B) + width(4B) + pixel_bytes

ImageSerializer chooses the serialization format based on the image type form:

Type form

Serialization format

getLength()

unconstrained / mode-constrained

mode_code(1B)
height(4B)
width(4B)
pixel_bytes

-1

fixed-shape

pixel_bytes

h x w x channels x byteWidth

The purpose of fixed-shape images is that each row's pixel payload length is known from the type, allowing serializers and columnar transport to use fixed-length physical representations.

ImageSerializerSnapshot records the serializer's mode, height, and width parameters. During restore, the corresponding ImageSerializer is reconstructed from these parameters. Compatibility checks use a conservative policy: only if mode, height, and width exactly match between old and new snapshots should the result be compatibleAsIs; otherwise it is incompatible. Serializer migration between different IMAGE type forms is not supported.

Python Side

  • Schema mapping: PyFlink proto adds an IMAGE type identifier, and ImageInfo carries optional mode/height/width.

  • UDF codec: The serialization format is aligned with the Java-side ImageSerializer. Python reconstructs the ndarray through np.frombuffer.

  • Arrow transport:

    • Non-fixed-shape IMAGE values, including unconstrained and mode-constrained images, use StructVector such as mode_code: uint8, height: int32, width: int32, data: binary.

    • Fixed-shape IMAGE(mode, height, width) uses FixedSizeList; mode/height/width are provided by logical type / schema information.

  • ImageMode enum: Java and Python align through stable mode codes.

Compatibility, Deprecation, and Migration Plan

This FLIP integrates new data types into Flink and is fully backward compatible.

Test Plan

The change will be covered by unit and integration tests.

Rejected Alternatives

Only Using ARRAY to Represent TENSOR/VECTOR

Numeric arrays such as ARRAY<FLOAT> or ARRAY<TINYINT> can represent one-dimensional payloads, but they cannot express fixed dimension or vector dtype semantics in the type, and cannot distinguish ordinary business arrays from embeddings or feature vectors.

Flink SQL currently does not have a fixed-length array logical type. Even if some row-oriented primitive array representation can store elements of a single row contiguously, the planner, serializer, format, and Arrow/vectorized paths cannot infer a fixed stride from the schema of ARRAY<FLOAT> or ARRAY<TINYINT>. For Arrow/Pandas UDFs, a generic array uses a variable-length list representation, while VECTOR('dtype', d) can use a fixed-size list or fixed-stride representation.

If multidimensional tensors are represented as nested arrays, the representation introduces multiple layers of offsets and nullability, which does not match a dense contiguous tensor representation.

Only Using TENSOR to Represent VECTOR

TENSOR('float32', 768) or TENSOR('int8', 768) can accurately represent the physical structure of a vector, but it does not tell connectors, UDFs, or future planner rules whether this rank-1 tensor should be treated as an embedding, feature vector, or query vector. For SQL users, it emphasizes a generic tensor rather than the fixed-length vector / embedding concept more commonly used in database and AI retrieval scenarios.

Many databases and search systems expose one-dimensional embedding columns as VECTOR, dense_vector, knn_vector, or similar type names instead of requiring users to understand tensor rank and shape. Introducing VECTOR('dtype', 768) makes the schema closer to user expectations and provides a clear extension point for future vector distance functions, vector search connectors, ANN indexes, and vector-specific encoding. Internally, it can still reuse the payload-only representation of fixed-shape tensors, so it does not require the runtime to duplicate a completely different data structure.

Only Using Structs to Represent TENSOR

ROW<data, shape, dtype> or ROW<values, shape> can represent tensor fields, but it exposes the physical tensor layout as ordinary user schema. The planner and runtime only see an ordinary row and cannot maintain information such as dtype, shape, payload length, and row-major layout. They also cannot use payload-only serializers, fixed-size Arrow representations, or more efficient Python/Java UDF transport for fixed-shape tensors.

For fixed-shape tensors, shape should be schema-level metadata. If a ROW is used, each row either needs to repeat the shape or rely on an external convention to omit it. The former wastes storage and transport, while the latter loses type-system validation. ROW is suitable as an external interoperability format or a user-defined encoding, but not as a first-class Flink internal logical type.

Only Using VARBINARY

VARBINARY has no dtype or shape semantics. Java users, Python users, connectors, and the planner all have to rely on external conventions to interpret bytes.

IMAGE Without Type Parameters

A simpler option is to expose only IMAGE, storing mode, height, and width entirely as value metadata. This preserves value self-description but loses schema-level narrowing and fixed-length optimization opportunities.

The common goal of image pipelines is to gradually converge heterogeneous encoded images into model inputs: first decode and fix the mode, then use resize/crop and similar processing to fix shape. Therefore, IMAGE -> IMAGE(mode) -> IMAGE(mode, height, width) directly corresponds to this processing flow. IMAGE(mode) means channel semantics are unified but dimensions are still variable. IMAGE(mode, height, width) means the model input contract is fixed.

Fixed-shape also lets the runtime determine each row's pixel payload length from the type, enabling fixed-length serializers and Arrow fixed-size representations. Even if the Python UDF visible value remains pd.Series[Image], the underlying pixel data can be backed by a contiguous fixed-length column buffer instead of being rebuilt and stacked row-by-row from variable binary values. If only parameterless IMAGE is available, all paths must treat images as variable-length, self-describing values and cannot benefit from these optimizations.

Exposing IMAGE(height, width)

Fixing only height and width cannot determine payload length because different modes have different channel counts. It also does not match the common narrowing order: real pipelines usually unify mode during decode and then fix shape. Introducing IMAGE(height, width) would increase type inference and widening rule complexity without supporting fixed-size optimization, so this form is not exposed.

Using Structs to Represent IMAGE

ROW<data, height, width, channels, mode> can represent image fields, but it exposes the internal layout as a user contract. The planner and runtime only see an ordinary row, cannot maintain image invariants, and cannot easily apply specialized serialization, Arrow transport, accessors, or type validation optimizations for images. A struct is suitable as an external interoperability format, but not as a first-class Flink internal logical type.

Allowing Casts Between IMAGE and BYTES / TENSOR

Conversions between BYTES, IMAGE, and TENSOR are not ordinary type conversions. They are image processing operations with semantic parameters. BYTES -> IMAGE requires decode mode and error handling. IMAGE -> BYTES requires an encoding format and quality parameter. IMAGE -> TENSOR depends on image layout choices and mode semantics when interpreting pixels as tensor elements. Using casts would hide behavior that may fail, be expensive, or be lossy, so these conversions should be expressed through explicitly named functions such as IMAGE_TO_TENSOR(image[, layout]).

Future Work

  • Vector processing functions: Integrate with existing functions such as VECTOR_SEARCH and VECTOR_SEARCH_AGG, and introduce scalar functions for similarity computation.

  • Image processing functions: resize, crop, normalize, mode transform, and similar functions.

  • New Image modes: Extend the ImageMode enum, for example with CMYK, and support new pixel precisions.

  • Planner optimizations: Potential optimizations such as constant folding for property functions on fixed-shape types.

  • Pixel buffer memory optimization: explore off-heap or columnar pixel-buffer representations to reduce JVM heap pressure and unnecessary copies in table runtime, Python/Arrow transport, and future image processing operators.

References

  • No labels