Coverage Report

Created: 2026-07-17 22:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/function/function_python_udf.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "exprs/function/function_python_udf.h"
19
20
#include <arrow/record_batch.h>
21
#include <arrow/type_fwd.h>
22
#include <fmt/core.h>
23
#include <glog/logging.h>
24
25
#include <cstddef>
26
#include <cstdint>
27
#include <ctime>
28
#include <memory>
29
30
#include "common/status.h"
31
#include "core/block/block.h"
32
#include "format/arrow/arrow_block_convertor.h"
33
#include "runtime/exec_env.h"
34
#include "runtime/user_function_cache.h"
35
#include "udf/python/python_server.h"
36
#include "udf/python/python_udf_client.h"
37
#include "udf/python/python_udf_meta.h"
38
#include "util/timezone_utils.h"
39
40
namespace doris {
41
42
PythonFunctionCall::PythonFunctionCall(const TFunction& fn, const DataTypes& argument_types,
43
                                       const DataTypePtr& return_type)
44
0
        : _fn(fn), _argument_types(argument_types), _return_type(return_type) {}
45
46
Status PythonFunctionCall::open(FunctionContext* context,
47
0
                                FunctionContext::FunctionStateScope scope) {
48
0
    if (scope == FunctionContext::FunctionStateScope::FRAGMENT_LOCAL) {
49
0
        LOG(INFO) << "Open python UDF fragment local";
50
0
        return Status::OK();
51
0
    }
52
53
0
    PythonVersion version;
54
0
    PythonUDFMeta func_meta;
55
0
    func_meta.id = _fn.id;
56
0
    func_meta.name = _fn.name.function_name;
57
0
    func_meta.symbol = _fn.scalar_fn.symbol;
58
0
    if (!_fn.function_code.empty()) {
59
0
        func_meta.type = PythonUDFLoadType::INLINE;
60
0
        func_meta.location = "inline";
61
0
        func_meta.inline_code = _fn.function_code;
62
0
    } else if (!_fn.hdfs_location.empty()) {
63
0
        func_meta.type = PythonUDFLoadType::MODULE;
64
0
        func_meta.location = _fn.hdfs_location;
65
0
        func_meta.checksum = _fn.checksum;
66
0
    } else {
67
0
        func_meta.type = PythonUDFLoadType::UNKNOWN;
68
0
        func_meta.location = "unknown";
69
0
    }
70
71
0
    func_meta.input_types = _argument_types;
72
0
    func_meta.return_type = _return_type;
73
0
    func_meta.client_type = PythonClientType::UDF;
74
75
0
    if (_fn.__isset.runtime_version && !_fn.runtime_version.empty()) {
76
0
        RETURN_IF_ERROR(
77
0
                PythonVersionManager::instance().get_version(_fn.runtime_version, &version));
78
0
    } else {
79
0
        return Status::InvalidArgument("Python UDF runtime version is not set");
80
0
    }
81
82
0
    func_meta.runtime_version = version.full_version;
83
0
    RETURN_IF_ERROR(func_meta.check());
84
0
    func_meta.always_nullable = _return_type->is_nullable();
85
0
    LOG(INFO) << fmt::format("runtime_version: {}, func_meta: {}", version.to_string(),
86
0
                             func_meta.to_string());
87
88
0
    if (func_meta.type == PythonUDFLoadType::MODULE) {
89
0
        RETURN_IF_ERROR(UserFunctionCache::instance()->get_pypath(
90
0
                func_meta.id, func_meta.location, func_meta.checksum, &func_meta.location));
91
0
    }
92
93
0
    PythonUDFClientPtr client = nullptr;
94
0
    RETURN_IF_ERROR(PythonServerManager::instance().get_client(func_meta, version, &client));
95
96
0
    if (!client) {
97
0
        return Status::InternalError("Python UDF client is null");
98
0
    }
99
100
0
    context->set_function_state(FunctionContext::THREAD_LOCAL, client);
101
0
    LOG(INFO) << fmt::format("Successfully get python UDF client, process: {}",
102
0
                             client->print_process());
103
0
    return Status::OK();
104
0
}
105
106
Status PythonFunctionCall::execute_impl(FunctionContext* context, Block& block,
107
                                        const ColumnNumbers& arguments, uint32_t result,
108
0
                                        size_t num_rows) const {
109
0
    auto client = reinterpret_cast<PythonUDFClient*>(
110
0
            context->get_function_state(FunctionContext::THREAD_LOCAL));
111
0
    if (!client) {
112
0
        LOG(WARNING) << "Python UDF client is null";
113
0
        return Status::InternalError("Python UDF client is null");
114
0
    }
115
116
0
    int64_t input_rows = num_rows;
117
0
    uint32_t input_columns = block.columns();
118
0
    DCHECK(input_columns > 0 && result < input_columns &&
119
0
           _argument_types.size() == arguments.size());
120
0
    Block input_block;
121
0
    Block output_block;
122
123
0
    if (!_return_type->equals(*block.get_by_position(result).type)) {
124
0
        return Status::InternalError(fmt::format("Python UDF output type {} not equal to {}",
125
0
                                                 block.get_by_position(result).type->get_name(),
126
0
                                                 _return_type->get_name()));
127
0
    }
128
129
0
    for (uint32_t i = 0; i < arguments.size(); ++i) {
130
0
        if (!_argument_types[i]->equals(*block.get_by_position(arguments[i]).type)) {
131
0
            return Status::InternalError(
132
0
                    fmt::format("Python UDF input type {} not equal to {}",
133
0
                                block.get_by_position(arguments[i]).type->get_name(),
134
0
                                _argument_types[i]->get_name()));
135
0
        }
136
0
        input_block.insert(block.get_by_position(arguments[i]));
137
0
    }
138
139
0
    std::shared_ptr<arrow::Schema> schema;
140
0
    RETURN_IF_ERROR(
141
0
            get_arrow_schema_from_block(input_block, &schema, TimezoneUtils::default_time_zone));
142
0
    std::shared_ptr<arrow::RecordBatch> input_batch;
143
0
    std::shared_ptr<arrow::RecordBatch> output_batch;
144
0
    cctz::time_zone _timezone_obj; // default UTC
145
0
    if (arguments.empty()) {
146
0
        RETURN_IF_ERROR(make_zero_column_arrow_batch(schema, input_rows, &input_batch));
147
0
    } else {
148
0
        RETURN_IF_ERROR(convert_to_arrow_batch(input_block, schema,
149
0
                                               ExecEnv::GetInstance()->arrow_memory_pool(),
150
0
                                               &input_batch, _timezone_obj));
151
0
    }
152
0
    RETURN_IF_ERROR(client->evaluate(*input_batch, &output_batch));
153
0
    int64_t output_rows = output_batch->num_rows();
154
155
0
    if (output_batch->num_columns() != 1) {
156
0
        return Status::InternalError(fmt::format("Python UDF output columns {} not equal to 1",
157
0
                                                 output_batch->num_columns()));
158
0
    }
159
160
0
    if (input_rows != output_rows) {
161
0
        return Status::InternalError(fmt::format(
162
0
                "Python UDF output rows {} not equal to input rows {}", output_rows, input_rows));
163
0
    }
164
165
0
    RETURN_IF_ERROR(
166
0
            convert_from_arrow_batch(output_batch, {_return_type}, &output_block, _timezone_obj));
167
0
    DCHECK_EQ(output_block.columns(), 1);
168
0
    block.replace_by_position(result, std::move(output_block.get_by_position(0).column));
169
0
    return Status::OK();
170
0
}
171
172
Status PythonFunctionCall::close(FunctionContext* context,
173
0
                                 FunctionContext::FunctionStateScope scope) {
174
0
    auto client = reinterpret_cast<PythonUDFClient*>(
175
0
            context->get_function_state(FunctionContext::THREAD_LOCAL));
176
0
    if (!client) {
177
0
        LOG(WARNING) << "Python UDF client is null";
178
0
        return Status::InternalError("Python UDF client is null");
179
0
    }
180
0
    RETURN_IF_ERROR(client->close());
181
0
    return Status::OK();
182
0
}
183
184
} // namespace doris