aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/minikql/comp_nodes/mkql_block_coalesce.cpp
blob: ae190e777e876f31cdc42f4259bc29ccecdde6d8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
#include "mkql_block_coalesce.h"

#include <yql/essentials/minikql/arrow/arrow_defs.h>
#include <yql/essentials/minikql/mkql_type_builder.h>
#include <yql/essentials/minikql/computation/mkql_block_impl.h>
#include <yql/essentials/minikql/computation/mkql_computation_node_holders.h>
#include <yql/essentials/minikql/mkql_node_builder.h>
#include <yql/essentials/minikql/mkql_node_cast.h>
#include <yql/essentials/public/udf/arrow/block_builder.h>
#include <yql/essentials/public/udf/arrow/block_reader.h>
#include <yql/essentials/public/udf/arrow/util.h>
#include <yql/essentials/minikql/comp_nodes/mkql_block_coalesce_blending_helper.h>
#include <yql/essentials/minikql/defs.h>

#include <arrow/util/bitmap_ops.h>

namespace NKikimr::NMiniKQL {

namespace {

template <typename TType>
void DispatchCoalesceImpl(const arrow::Datum& left, const arrow::Datum& right, arrow::Datum& out, bool outIsOptional, arrow::MemoryPool& pool) {
    auto bitmap = outIsOptional ? ARROW_RESULT(arrow::AllocateBitmap((left.array()->length + left.array()->offset % 8) * sizeof(ui8), &pool)) : nullptr;
    if (bitmap && bitmap->size() > 0) {
        // Fill first byte with zero to prevent further uninitialized memory access.
        bitmap->mutable_data()[0] = 0;
    }
    out = arrow::ArrayData::Make(right.type(), left.array()->length,
                                 {std::move(bitmap),
                                  ARROW_RESULT(arrow::AllocateBuffer((left.array()->length + left.array()->offset % 8) * sizeof(TType), &pool))},
                                 arrow::kUnknownNullCount, left.array()->offset % 8);
    if (outIsOptional) {
        if (right.is_scalar()) {
            if (right.scalar()->is_valid) {
                BlendCoalesce<TType, /*isScalar=*/true, /*rightIsOptional=*/true>(
                    TDatumStorageView<TType>(left),
                    TDatumStorageView<TType>(right),
                    TDatumStorageView<TType>(out),
                    left.array()->length);
            } else {
                out = left;
            }
        } else {
            MKQL_ENSURE(TDatumStorageView<TType>(right).bitMask(), "Right array must have a null mask");
            BlendCoalesce<TType, /*isScalar=*/false, /*rightIsOptional=*/true>(
                TDatumStorageView<TType>(left),
                TDatumStorageView<TType>(right),
                TDatumStorageView<TType>(out),
                left.array()->length);
        }
    } else {
        if (right.is_scalar()) {
            BlendCoalesce<TType, /*isScalar=*/true, /*rightIsOptional=*/false>(
                TDatumStorageView<TType>(left),
                TDatumStorageView<TType>(right),
                TDatumStorageView<TType>(out),
                left.array()->length);
        } else {
            BlendCoalesce<TType, /*isScalar=*/false, /*rightIsOptional=*/false>(
                TDatumStorageView<TType>(left),
                TDatumStorageView<TType>(right),
                TDatumStorageView<TType>(out),
                left.array()->length);
        }
    }
}

bool DispatchBlendingCoalesce(const arrow::Datum& left, const arrow::Datum& right, arrow::Datum& out, TType* rightType, arrow::MemoryPool& pool) {
    TTypeInfoHelper typeInfoHelper;
    bool rightIsOptional;
    rightType = UnpackOptional(rightType, rightIsOptional);
    MKQL_ENSURE(rightType, "Right type must be valid");

    NYql::NUdf::TDataTypeInspector typeData(typeInfoHelper, rightType);
    if (!typeData) {
        return false;
    }
    auto typeId = typeData.GetTypeId();

    switch (NYql::NUdf::GetDataSlot(typeId)) {
        case NYql::NUdf::EDataSlot::Int8:
            DispatchCoalesceImpl<i8>(left, right, out, /*outIsOptional=*/rightIsOptional, pool);
            return true;
        case NYql::NUdf::EDataSlot::Bool:
        case NYql::NUdf::EDataSlot::Uint8:
            DispatchCoalesceImpl<ui8>(left, right, out, /*outIsOptional=*/rightIsOptional, pool);
            return true;
        case NYql::NUdf::EDataSlot::Int16:
            DispatchCoalesceImpl<i16>(left, right, out, /*outIsOptional=*/rightIsOptional, pool);
            return true;
        case NYql::NUdf::EDataSlot::Uint16:
            DispatchCoalesceImpl<ui16>(left, right, out, /*outIsOptional=*/rightIsOptional, pool);
            return true;
        case NYql::NUdf::EDataSlot::Int32:
            DispatchCoalesceImpl<i32>(left, right, out, /*outIsOptional=*/rightIsOptional, pool);
            return true;
        case NYql::NUdf::EDataSlot::Uint32:
            DispatchCoalesceImpl<ui32>(left, right, out, /*outIsOptional=*/rightIsOptional, pool);
            return true;
        case NYql::NUdf::EDataSlot::Int64:
        case NYql::NUdf::EDataSlot::Uint64:
        case NYql::NUdf::EDataSlot::Double:
        case NYql::NUdf::EDataSlot::Float:
        // TODO(YQL-19645): Support other numeric types.
        default:
            // Fallback to general builder/reader pipeline.
            return false;
    }
}

class TCoalesceBlockExec {
public:
    TCoalesceBlockExec(const std::shared_ptr<arrow::DataType>& returnArrowType, TType* firstItemType, TType* secondItemType, bool needUnwrapFirst)
        : ReturnArrowType_(returnArrowType)
        , FirstItemType_(firstItemType)
        , SecondItemType_(secondItemType)
        , NeedUnwrapFirst_(needUnwrapFirst) {
    }

    arrow::Status Exec(arrow::compute::KernelContext* ctx, const arrow::compute::ExecBatch& batch, arrow::Datum* res) const {
        const auto& first = batch.values[0];
        const auto& second = batch.values[1];
        MKQL_ENSURE(!first.is_scalar() || !second.is_scalar(), "Expected at least one array");
        size_t length = Max(first.length(), second.length());
        auto firstReader = NYql::NUdf::MakeBlockReader(TTypeInfoHelper(), FirstItemType_);
        auto secondReader = NYql::NUdf::MakeBlockReader(TTypeInfoHelper(), SecondItemType_);
        if (first.is_scalar()) {
            auto firstValue = firstReader->GetScalarItem(*first.scalar());
            if (firstValue) {
                auto builder = NYql::NUdf::MakeArrayBuilder(TTypeInfoHelper(), SecondItemType_, *ctx->memory_pool(), length, nullptr);
                builder->Add(NeedUnwrapFirst_ ? firstValue.GetOptionalValue() : firstValue, length);
                *res = builder->Build(true);
            } else {
                *res = second;
            }
        } else if (second.is_scalar()) {
            const auto& firstArray = *first.array();
            if (firstArray.GetNullCount() == 0) {
                *res = NeedUnwrapFirst_ ? Unwrap(firstArray, FirstItemType_) : first;
            } else if ((size_t)firstArray.GetNullCount() == length) {
                auto builder = NYql::NUdf::MakeArrayBuilder(TTypeInfoHelper(), SecondItemType_, *ctx->memory_pool(), length, nullptr);
                auto secondValue = secondReader->GetScalarItem(*second.scalar());
                builder->Add(secondValue, length);
                *res = builder->Build(true);
            } else {
                if (DispatchBlendingCoalesce(first, second, *res, SecondItemType_, *ctx->memory_pool())) {
                    return arrow::Status::OK();
                }

                auto builder = NYql::NUdf::MakeArrayBuilder(TTypeInfoHelper(), SecondItemType_, *ctx->memory_pool(), length, nullptr);
                auto secondValue = secondReader->GetScalarItem(*second.scalar());
                for (size_t i = 0; i < length; ++i) {
                    auto firstItem = firstReader->GetItem(firstArray, i);
                    if (firstItem) {
                        builder->Add(NeedUnwrapFirst_ ? firstItem.GetOptionalValue() : firstItem);
                    } else {
                        builder->Add(secondValue);
                    }
                }

                *res = builder->Build(true);
            }
        } else {
            const auto& firstArray = *first.array();
            const auto& secondArray = *second.array();
            if (firstArray.GetNullCount() == 0) {
                *res = NeedUnwrapFirst_ ? Unwrap(firstArray, FirstItemType_) : first;
            } else if ((size_t)firstArray.GetNullCount() == length) {
                *res = second;
            } else {
                if (DispatchBlendingCoalesce(first, second, *res, SecondItemType_, *ctx->memory_pool())) {
                    return arrow::Status::OK();
                }

                auto builder = NYql::NUdf::MakeArrayBuilder(TTypeInfoHelper(), SecondItemType_, *ctx->memory_pool(), length, nullptr);
                for (size_t i = 0; i < length; ++i) {
                    auto firstItem = firstReader->GetItem(firstArray, i);
                    if (firstItem) {
                        builder->Add(NeedUnwrapFirst_ ? firstItem.GetOptionalValue() : firstItem);
                    } else {
                        auto secondItem = secondReader->GetItem(secondArray, i);
                        builder->Add(secondItem);
                    }
                }

                *res = builder->Build(true);
            }
        }

        return arrow::Status::OK();
    }

private:
    const std::shared_ptr<arrow::DataType> ReturnArrowType_;
    TType* const FirstItemType_;
    TType* const SecondItemType_;
    const bool NeedUnwrapFirst_;
};

std::shared_ptr<arrow::compute::ScalarKernel> MakeBlockCoalesceKernel(const TVector<TType*>& argTypes, TType* resultType, bool needUnwrapFirst) {
    using TExec = TCoalesceBlockExec;

    std::shared_ptr<arrow::DataType> returnArrowType;
    MKQL_ENSURE(ConvertArrowType(AS_TYPE(TBlockType, resultType)->GetItemType(), returnArrowType), "Unsupported arrow type");
    auto exec = std::make_shared<TExec>(
        returnArrowType,
        AS_TYPE(TBlockType, argTypes[0])->GetItemType(),
        AS_TYPE(TBlockType, argTypes[1])->GetItemType(),
        needUnwrapFirst);
    auto kernel = std::make_shared<arrow::compute::ScalarKernel>(ConvertToInputTypes(argTypes), ConvertToOutputType(resultType),
                                                                 [exec](arrow::compute::KernelContext* ctx, const arrow::compute::ExecBatch& batch, arrow::Datum* res) {
                                                                     return exec->Exec(ctx, batch, res);
                                                                 });

    kernel->null_handling = arrow::compute::NullHandling::COMPUTED_NO_PREALLOCATE;
    return kernel;
}

} // namespace

IComputationNode* WrapBlockCoalesce(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
    MKQL_ENSURE(callable.GetInputsCount() == 2, "Expected 2 args");

    auto first = callable.GetInput(0);
    auto second = callable.GetInput(1);

    auto firstType = AS_TYPE(TBlockType, first.GetStaticType());
    auto secondType = AS_TYPE(TBlockType, second.GetStaticType());

    auto firstItemType = firstType->GetItemType();
    auto secondItemType = secondType->GetItemType();
    MKQL_ENSURE(firstItemType->IsOptional() || firstItemType->IsPg(), "Expecting Optional or Pg type as first argument");

    bool needUnwrapFirst = false;
    if (!firstItemType->IsSameType(*secondItemType)) {
        // Here the left operand and right operand are of types T? and T respectively.
        // The first operand must be unwrapped to obtain the resulting type.
        needUnwrapFirst = true;
        bool firstOptional;
        firstItemType = UnpackOptional(firstItemType, firstOptional);
        MKQL_ENSURE(firstItemType->IsSameType(*secondItemType), "Uncompatible arguemnt types");
    }

    auto firstCompute = LocateNode(ctx.NodeLocator, callable, 0);
    auto secondCompute = LocateNode(ctx.NodeLocator, callable, 1);
    TComputationNodePtrVector argsNodes = {firstCompute, secondCompute};
    TVector<TType*> argsTypes = {firstType, secondType};

    auto kernel = MakeBlockCoalesceKernel(argsTypes, secondType, needUnwrapFirst);
    return new TBlockFuncNode(ctx.Mutables, "Coalesce", std::move(argsNodes), argsTypes, *kernel, kernel);
}

} // namespace NKikimr::NMiniKQL