Skip to content

[Refactoring]: Rebuild Python UDF on Arrow batches and an isolated runtime #28132

Todo

Description

@iamlinjunhong

Why do you want to refactor this code?

The current Python UDF path converts MatrixOne vectors into the custom protobuf DataVector/Data model value by value, sends those protobuf objects over a bidirectional gRPC stream, materializes Python object lists, and performs the reverse conversion for results.

This boundary has three long-term problems:

  • it duplicates a partial SQL type system in the UDF wire protocol and allocates/serializes per value;
  • VECTOR mode exposes Python lists rather than a standard columnar interface, limiting PyArrow/Pandas/Polars interoperability;
  • the current per-CN shared sidecar, mutable package path, and query-time package installation do not provide an adequate revision, isolation, resource-ownership, upgrade, or multi-tenant security contract.

The invariant for the refactor is:

MatrixOne keeps MO Vector as its native in-engine execution format. Arrow is the versioned columnar interoperability format only at the Python UDF process boundary. Python code must never depend on the private MO Vector ABI.

Dependency and start gate

Blocked by #23684. Do not begin production implementation until #23684 is complete and its transport-neutral Arrow primitives and ownership contracts are merged and stable on main.

The intended reusable foundation from #23684 is limited to generic mechanisms such as:

  • Arrow IPC structural validation;
  • Arrow ArrayData to immutable MO backing adoption/materialization;
  • BufferLease, per-backing ownership, copy-on-write, accounting, and copy/pin observability.

This issue must not reuse or inherit:

  • Arrow LOAD DATA's widening, timezone interpretation, or other ingestion conversion policy;
  • the Sirius offload wire protocol, capability model, or execution lease as the Python UDF ABI/runtime;
  • static-file scheduling or FileService semantics as an invocation protocol.

Completion of #23684 is a prerequisite, not evidence that this refactor's UDF-specific contracts are implemented.

This is a major cross-subsystem refactor. Before production code starts, the long-term design must be published as a stable versioned document, formally reviewed by Architecture, Security, SQL/Planner, and Cloud/Operator owners, and the exact approved revision must be linked from this issue. Split implementation into reviewed subtasks/PRs after that gate passes.

Describe the solution you'd like

Build a versioned Python UDF v2 architecture with these boundaries:

  1. Function identity and revisions

    • Resolve an immutable FunctionRef(function_id, revision) at planning time.
    • Keep code artifacts and Python environments content-addressed by digest.
    • Never resolve a mutable latest revision or install packages in the query hot path.
  2. CN UDF operator and Arrow bridge

    • Keep MO Vector inside the engine.
    • Add a bounded MO-to-Arrow encoder for inputs and a UDF-specific exact Arrow-to-MO binder for results.
    • Preserve SQL NULL, decimal precision/scale, timestamp/timezone, binary, JSON, UUID, charset/collation, and value-domain semantics without truthiness, stringification, widening, truncation, rounding, or timezone guessing.
    • Support NULL compact/scatter without changing row order or cardinality.
  3. Versioned control plane and Arrow data plane

    • Use a small versioned control API for capabilities, admission, open/cancel/status, immutable revision/digest identity, budgets, and error classes.
    • Use Arrow Flight DoExchange/RecordBatch for the CN-to-runtime data plane instead of the per-value protobuf protocol.
    • Fence every frame with invocation_id, lease_epoch, and monotonic sequence_no; do not transparently retry an invocation after user code has started.
    • Bound both bytes and batch count in flight and propagate cancellation/deadlines end to end.
  4. Trusted runtime boundary and isolated workers

    • Terminate authentication, Flight credentials, admission, resource measurement, Arrow validation, and the PREPARED/Run gate in trusted Gateway/Supervisor components.
    • Treat the Python interpreter and its output as untrusted.
    • Run user code in resource-bounded, tenant-aware sandboxes; the interpreter must not receive production credentials or direct CN memory access.
    • Make every resource owner and every success/error/cancel/timeout/crash/restart cleanup transition explicit and bounded.
  5. Python SDK

    • Let vector handlers consume and return PyArrow arrays/record batches as the primary ABI.
    • Keep scalar handlers as a compatibility/convenience API, with row-wise Python object conversion confined to the worker.
    • Publish a versioned type/exception/context contract and generated Go/Python conformance fixtures.
  6. Migration and rollout

    • Introduce capability-gated schema shadow, dual resolution/validation, v2 new-write, execution cutover, and eventual v1 retirement stages.
    • Keep the existing path available only as an explicit legacy path during the rollback window.
    • A runtime outage must fail only queries that require Python UDF; ordinary SQL service remains available.

Alternatives considered

  • Expose MO Vector directly to Python: rejected because it leaks MatrixOne's private ABI, ownership model, and release cadence into the Python ecosystem.
  • Only optimize the existing protobuf RPC: rejected because it retains the duplicate per-value type system and does not solve revision, sandbox, lifecycle, or resource-ownership problems.
  • Embed CPython in CN: rejected because interpreter/native-extension failures, GIL behavior, and tenant isolation would enter the database process blast radius.
  • Keep one permanent shared sidecar per CN: acceptable only as a development or deployment adapter, not as the long-term semantic or security boundary.

Acceptance criteria

  • The v2 data path contains no per-row protobuf Data encoding; inputs and results use bounded Arrow RecordBatch streams.
  • The MO engine remains MO-Vector-native; Python vector handlers use PyArrow without depending on MO's internal ABI.
  • A versioned exact type matrix and Go/Python conformance suite covers supported values plus rejection cases for NULLs, overflow, decimal, temporal types, binary, JSON, UUID, malformed offsets/bitmaps/dictionaries/nesting, row-count mismatch, and schema mismatch.
  • Deterministic tests cover success, handler error, cancellation, timeout, disconnect, duplicate/out-of-order sequence, stale epoch, worker crash, runtime restart, replace/drop during execution, and cleanup of every owned resource.
  • Artifact/environment build and verification are outside the query hot path; published revisions are immutable and digest-verified.
  • Sandbox tests cover tenant/revision isolation, filesystem/network/credential restrictions, process/thread/FD/memory/CPU bounds, hostile output, and failed reset/destruction.
  • Mixed-version capability gating, upgrade, rollback, backup/restore, runtime drain/readiness, and v1 migration are demonstrated before default cutover.
  • Benchmarks report serialization/copy cost, throughput, latency, peak memory, in-flight bytes, scalar/vector behavior, and warm/cold execution; the Arrow path shows no unacceptable regression against the current protobuf baseline.
  • The approved design revision and all implementation subtasks/PRs are linked from this issue.

Activity

  1. self-assigned this
    on Sep 4, 2026
  2. added
    priority/p0
    on Sep 4, 2026
  3. iamlinjunhong commented on Sep 20, 2026

    @iamlinjunhong
    ContributorAuthor

    Python UDF 用户使用说明(PR #29152)

    本文对应 PR #29152 的 0d4640af38,用于试用本次重构后的 Python UDF,合入前请使用该 PR 分支。不是已发布版本的通用说明,也不代表本 issue 的全部生产隔离目标已经完成。

    1. 运行方式与适用范围

    SQL client → CN:解析、类型检查、执行计划与资源准入
                      ↓ Arrow Flight
                 Python worker
                      ↓ 有界 handler 子进程
                 Python 函数 → Arrow 结果 → CN → SQL client
    

    Flight 服务包含在 Python worker 内,不需要另外启动 Flight 服务或独立 Gateway。Gateway 在 CN 进程内。仓库多 CN compose 示例为每个 CN 配一个独立 worker endpoint;一个 worker 可以处理多个并发 invocation,但受执行槽和资源预算限制,不是每个 SQL 启动一个长期 worker。

    当前是显式启用的受信、未隔离执行形态:没有 sandbox,也没有 Flight TLS/认证。只运行可信代码,worker 端口不要暴露到不可信网络。通用 launch 默认关闭 Python;worker-enabled launch 和普通 BVT 入口显式开启。

    2. 本地启动

    使用本分支构建的 mo-service,在仓库根目录执行。以下使用独立虚拟环境,避免依赖机器上混杂的全局 Python 包:

    python3 -m venv .venv-udf
    . .venv-udf/bin/activate
    python -m pip install -r pkg/udf/python/worker/requirements.txt
    ./mo-service -launch ./etc/launch-with-python-udf-worker/launch.toml

    该 manifest 同时启动 MO 服务及 PYTHON_UDF Supervisor,后者启动 worker;无需再手动启动同端口 worker。示例适用于独立本地测试实例,不要与占用相同端口或数据目录的实例并行启动。

    当前依赖锁是 pyarrow==24.0.0。仓库 worker 镜像使用 Python 3.12;本次 Linux PR 验证使用 Python 3.13.5。不要把任意本地 Python 环境视为兼容保证,应使用锁定依赖和相匹配的 worker/CN 合同。两侧 tzdata 也必须匹配;仅软件版本字符串相同不够。

    CN 启用配置的核心字段如下(上面的示例配置已包含启用项):

    [cn.python-udf-client]
    enabled = true
    allow-unisolated = true
    server-address = "127.0.0.1:50051"
    request-timeout = "30s"
    max-active-invocations = 8

    worker 自身的监听地址与 CN 的连接地址是两份配置。上述本地 manifest 将 worker 绑定在回环地址。容器部署请保留镜像的 tini init 入口,不能覆盖成直接运行 Python,否则孤儿后代进程的回收合同不成立。

    3. SCALAR:逐行 Python 值

    连接测试实例后,在具有建函数权限的数据库中运行:

    CREATE DATABASE udf_example;
    USE udf_example;
    
    CREATE TABLE inputs (id INT, x INT);
    INSERT INTO inputs VALUES (1, 1), (2, NULL), (3, -2);
    
    CREATE FUNCTION add_one(x INT) RETURNS INT
    LANGUAGE PYTHON
    AS 'def add_one(ctx, x): return None if x is None else x + 1'
    HANDLER 'add_one';
    
    SELECT id, add_one(x) AS result FROM inputs ORDER BY id;
    -- (1, 2), (2, NULL), (3, -1)

    默认模式为 SCALAR,签名是 handler(ctx, arg1, ...),不是旧 demo 的 handler(arg1, ...)。默认将 SQL NULL 传给 handler;SCALAR 中用 None 接收或返回 NULL。

    若希望任一实参为 NULL 时直接返回 NULL、跳过对应行的 handler,可声明:

    CREATE FUNCTION add_one_strict(x INT) RETURNS INT
    LANGUAGE PYTHON
    AS 'def add_one_strict(ctx, x): return x + 1'
    HANDLER 'add_one_strict'
    RETURNS NULL ON NULL INPUT;

    CREATE/REPLACE 会检查 Python 语法和 handler 合同,失败不会发布新定义;这不代表已证明所有输入下的运行正确性。执行中的异常、越界或错误结果类型仍会使查询失败。

    4. VECTOR:使用 PyArrow 计算

    VECTOR handler 的每个参数是一个 Arrow Array,返回一个与本次输入行数相同、物理类型符合 SQL 声明的 Arrow Array:

    CREATE FUNCTION add_ten(x INT) RETURNS INT
    LANGUAGE PYTHON
    AS 'def add_ten(ctx, values):
        import pyarrow as pa
        import pyarrow.compute as pc
        return pc.add(values, pa.scalar(10, type=pa.int32()))'
    HANDLER 'add_ten' MODE VECTOR;
    
    SELECT id, add_ten(x) AS result FROM inputs ORDER BY id;
    -- (1, 11), (2, NULL), (3, 8)
    
    CREATE FUNCTION seven() RETURNS INT
    LANGUAGE PYTHON
    AS 'def seven(ctx):
        import pyarrow as pa
        return pa.array([7] * ctx.num_rows, type=pa.int32())'
    HANDLER 'seven' MODE VECTOR;
    
    SELECT id, seven() AS result FROM inputs ORDER BY id;
    -- (1, 7), (2, 7), (3, 7)

    使用要点:

    • INT 对应 pa.int32(),不能依赖默认推断的 int64 自动缩窄;decimal 的 precision/scale、向量维度等也属于类型合同。
    • 保持行数及行对应关系;不能直接返回 filter/drop-null 后缩短的数组。NULL 用 Arrow validity 表达。
    • ctx.num_rows 提供本批结果形状,尤其用于零参数 VECTOR;不是整条 SQL 的总行数。
    • batch 边界不属于函数的值语义。不要依靠批大小、跨批计数或跨 invocation 全局变量决定结果;需要跨行聚合、排序等语义时使用 SQL 对应算子。
    • handler/module 仅在 invocation 内有界 burst 复用,不保证不同查询共享 Python heap。不在查询期间自动安装第三方依赖。

    5. 替换、删除与旧 demo

    CREATE OR REPLACE FUNCTION add_one(x INT) RETURNS INT
    LANGUAGE PYTHON
    AS 'def add_one(ctx, x): return None if x is None else x + 2'
    HANDLER 'add_one';
    
    SELECT id, add_one(x) AS result FROM inputs ORDER BY id;
    -- (1, 3), (2, NULL), (3, 0)
    
    DROP FUNCTION add_one(INT);
    DROP FUNCTION add_one_strict(INT);
    DROP FUNCTION add_ten(INT);
    DROP FUNCTION seven();
    DROP TABLE inputs;
    DROP DATABASE udf_example;

    替换发布新的不可变 revision;prepared/cache plan 复用时校验 revision 和重载名称空间。删除重载需要写准确参数类型,包括 decimal precision/scale 等。

    旧 Python demo 定义/SDK/plan 不支持、不自动迁移、不回退旧执行路径,需要用新 DDL 显式重建。 这不表示废弃现有 SQL UDF。环境 digest 包含 tzdata,升级基础镜像前需要检查已有 Python 定义的环境匹配;不匹配会拒绝执行,不静默改变时间语义。

    6. 常见失败与预算

    情况 用户应检查的内容
    Python 未启用/不可用 CN 的两个启用字段、worker 是否运行、连接地址和网络可达性
    合同不匹配/不支持的版本 CN/worker capability、依赖、tzdata,以及是否为旧 demo 定义
    CREATE/REPLACE 被拒绝 Python 缩进/语法、handler 名称及包含 ctx 的签名
    返回类型/行数错误 Arrow 精确类型、decimal/字符串等值域、VECTOR 长度与 NULL 表达
    timeout/容量拒绝 函数运行时间、当前并发、输入/输出大小和 ledger 预算;不要假设系统无限排队
    worker 崩溃或调用取消 本次查询会失败并回收资源;已 STARTED 的工作不透明重放,副作用函数不能假设恰好执行一次

    默认请求超时 30s(也用于 capability 握手),K=8,流窗口 W=1;单批默认 16 MiB / 65,536 行,单 invocation 默认最多 1,048,576 行、保留结果最多 256 MiB。这些是相应运行时对象的上限,不是整条 SQL 总行数限制,也不是 Python heap 的 RSS 安全上限。client 数值配置为 0 表示采用运行时默认,非无限制;超时最大为 1h。

    7. 示例与验证入口

    本次 Linux 验证包含真实 SQL→CN→Flight→handler→MO 结果,两 CN 的 Python BVT 各 352/352,通过普通 SQL UDF、snapshot restore 和进程故障测试。以上用户示例按这些已验证用例编写;本评论新增的整段教程未单独重跑,不将文档整理算作新测试结果。GitHub CI 状态请以 PR #29152 页面为准。

  4. removed their assignment
    on Nov 29, 2026
  5. added
    ai-light
    on Nov 29, 2026
  6. Ariznawlll commented on Dec 3, 2026

    @Ariznawlll
    Collaborator

    结论

    未完成验收;本轮已执行的 worker 合同和真实 SQL 子项通过,并已补入 MOTR main 回归。 当前结果覆盖本次实现明确支持的受信、未隔离 Python worker 形态,不代表整个 Python UDF v2 Feature 的生产隔离、升级与性能要求已经通过。Issue 保持开放。

    关键证据

    版本和环境

    • 修复 PR #29152 已合入 main,merge SHA a9ba8ca880f0df4bf3be024dc7b5c30ab4058160。
    • 本轮冻结并构建的官方 main:6f47e8540cc348849c1065f574cde38e37fd7741;真实 SQL SELECT git_version() 返回同一完整 SHA。没有将此结果外推到 4.2-dev。
    • macOS arm64,隔离数据目录和端口,1 LogService、1 TN、1 CN、独立 Python worker;PyArrow 24.0.0、Python 3.14,CN 显式启用 Python UDF 并允许当前受信的未隔离运行形态。未对其他实例注入故障。
    • 本轮服务没有产品代码补丁。原生依赖复用前,核对 032e27ec78999656a673c0d92bbf8437dcb83dd7 至目标 SHA 的 cgo、thirdparties 和词典源码无变化;Go 源码按目标 SHA 重新编译。

    1. worker / watchdog / healthcheck 合同测试

    在目标源码执行:

    python3 -m unittest discover -s pkg/udf/python/worker -p 'test_*.py' -v
    Ran 154 tests
    OK
    

    原始直接运行耗时 10.890 秒,后续正式 MOTR gate 中再次执行同一套源码测试并通过。154 是该套 Python 测试的用例数,不是 154 次 SQL。

    覆盖包含 Arrow/NULL/值域合同、handler deadline、取消、执行槽容量、真实 Flight 调用、worker 死亡后的 handler 进程组回收、leader 退出后的清理、watchdog 父连接读错处理及 healthcheck。部分测试使用 mock,部分使用真实 Flight/子进程,不能把整套统称为生产故障测试;也没有据此宣称多租户 sandbox 或 TLS/鉴权已经具备。

    2. 真实 SQL:步骤和结果

    每个 MOTR attempt 都创建独立数据库并清理,实际连接上述 MO,调用独立 Python worker:

    操作 精确预期与实际结果
    建表并写 (id,x)=(1,1),(2,NULL),(3,-2);SCALAR inc(ctx,x)=x+1,NULL 返回 NULL [(1,2),(2,NULL),(3,-1)],一致
    VECTOR vinc 对 Arrow 输入逐值加 10;声明 RETURNS NULL ON NULL INPUT [(1,11),(2,NULL),(3,8)],验证 compact/scatter 后行序和 NULL 位置
    CREATE OR REPLACE 将 inc 改为加 2,再查询 [(1,3),(2,NULL),(3,0)],使用新定义
    handler 主动抛出 ValueError SQL 明确失败:1105 ... USER_CODE: handler or runtime failed;不接受成功或 panic
    上述异常后重新调用 inc(2) 返回 4,worker 仍能处理后续调用
    事务内 UPDATE t SET x=inc(x),先核对更新后精确行集,再 ROLLBACK 回滚后 [(1,1),(2,NULL),(3,-2)],没有部分保留

    首次临时 VECTOR 探针误用了尚未导入的 pyarrow.compute 属性,得到 USER_CODE;该次不计通过。修正为仓库同类 VECTOR 示例使用的显式 Arrow Array 构造方式后重跑,通过;正式回归保留错误路径断言,没有把异常忽略或放宽为成功。

    3. MOTR 回归已交付、正式入口已运行

    追加到现有 MOTR main PR #408,提交 20dfb0c3dce97c6303888a7b75cc48b7990e7f80 及后续 CI 入口提交:

    • script/14_issue_regression/issue_28132_python_udf_runtime.py 和对应 out golden:以上 SQL 合同、精确行集、错误类别和事务状态。
    • .github/qa/python_udf_gate.py:先跑原生 worker Python 合同套件,再启动独立 worker/MO,核对源码 SHA 与运行 SHA,调用正式 MOTR runner,最后清理自有进程。
    • .github/workflows/qa-28132-python-udf.yml:受现有 qa-nov30-issue-acceptance.yml 调用的 python-udf-main job。PR 路径、手动入口和已有 main 每日计划均已接入;每日计划要等 PR 合入默认分支才生效。
    • 普通未启用 Python worker 的 MOTR 环境明确 SKIP;专用 job 开启该用例并强制检查实际计数,零用例或跳过不能让专用验收通过。

    本机使用已提交驱动和正式 MOTR 入口实际运行:

    --branch main --target mysql --parallel 1 --repeat 3
    --do-test '^14_issue_regression.issue_28132_python_udf_runtime$'
    
    SUMMARY | total=3 success=3 failed=0 skipped=0
    单轮耗时:2512 ms / 2457 ms / 2335 ms
    

    gate 回执为 PASS;MO 正常退出码 0,worker 为测试结束时主动 SIGTERM,退出码 -15。运行结束没有留下该夹具的监听或服务。

    首轮 Linux CI 在 Build official main 阶段因 runner 磁盘耗尽退出,GitHub annotation 为 System.IO.IOException: No space left on device;尚未执行 worker/SQL,属于 CI 环境失败,不能计作产品失败或通过。已在现有 PR 补上临时 runner 空间清理。第二轮 47104034995 进入 worker 测试后,因测试镜像使用 Python 3.10、无法解析上游测试中的 Python 3.12 f-string 语法而失败;这是本次 CI 夹具版本不匹配,不能计作产品失败。现已按产品 worker Dockerfile 改为 Python 3.12,并保留官方 main 构建的 MO 与原生库;修正后 CI 47107794617 已通过,产物已回读核对:Linux/Python 3.12 原生 worker 套件 Ran 154 tests in 5.017s / OK;正式 MOTR total=3 success=3 failed=0 skipped=0,三轮 1226/1224/1224 ms;源码与实际 SQL 运行 SHA 均为上述完整 main;MO 正常退出 0,worker 在测试结束时主动 SIGTERM 为 -15。没有往 MatrixOne 主库提交测试 PR。

    最新 main CI 的失败与测试时序核查

    本次 CI 47160236176 使用 main 11f8c0e5d5a62f85fefc0e5bc48dd937b9a454a4,worker 154 项中 1 项失败,真实 SQL 尚未开始。失败为 test_worker_death_reaps_descendant_after_handler_leader_exits 的 watchdog_pid not found ... watchdog did not register before leader exit,不是 SQL 错误。

    原测试在 handler 写入 child PID 后立即 kill relay,而 watchdog PID 也由该 relay 后续写入,然后测试又等待被杀 relay 写登记。受控延迟只在测试登记写入前增加0.2秒:原顺序3/3失败、先等登记再kill的对照3/3通过;无延迟两版各20/20通过。保留 child/watchdog 退出断言,并从 kill 后开始原3秒清理时限,未删除故障注入。

    此同步修正只在 MOTR 的临时测试副本中应用,官方 worker/handler/watchdog 文件逐一核对 SHA256 不变;没有产品源码改动、没有主库 PR。主测试镜像仍使用 Python3.12。支持版本的完整本地套件 Ran 154 tests in 3.748s / OK。初次复制遗漏 sibling testdata 的两项 FileNotFoundError 已保存并修正;另一个 Python3.14 完整运行出现 _HandlerCleanupPending,同样保留,不将那一轮计作通过或推断产品已修复。

    测试时序对照与文件摘要 已追加现有 MOTR #408;修正后托管 CI正在运行,不能用此前旧 SHA 的绿灯代替当前结果。

    待解决点

    • 等待并核对当前修正后的 Linux/Python3.12 CI,包括完整 worker 与真实 SQL 三轮产物。
    • 继续核查本地 Python3.14 相邻清理时序错误的适用范围;不据单次工具调用异常认定生产清理失败。
    • 完整旧目录/函数定义升级、revision/rollout/rollback、生产级隔离与性能门槛仍未完成。

    最终结论:未完成验收。已有旧 SHA 的完整 Linux worker/SQL 通过证据仍保留;最新 CI 本轮发生测试登记竞态,MOTR 测试同步修正和本地 Python3.12 154项通过已补充,但新托管 CI 尚未结束。未完成项:该 CI 复核及完整升级、隔离、性能验收;#28132 保持开放,不自动转派。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

ai-lightkind/refactoringpriority/p0

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions