aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/minikql/comp_nodes/ut/mkql_block_map_join_ut_utils.cpp
blob: 2dbeb2dbac6c8ad0445d63e6198ec34764abfea2 (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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
#include "mkql_block_map_join_ut_utils.h"

#include <yql/essentials/minikql/computation/mkql_block_impl.h>
#include <yql/essentials/minikql/computation/mkql_block_reader.h>
#include <yql/essentials/minikql/computation/mkql_computation_node_holders.h>
#include <yql/essentials/minikql/mkql_node_cast.h>
#include <yql/essentials/public/udf/arrow/args_dechunker.h>
#include <yql/essentials/public/udf/arrow/block_builder.h>

namespace NKikimr {
namespace NMiniKQL {

namespace {

class TWideStreamThrottlerWrapper: public TMutableComputationNode<TWideStreamThrottlerWrapper> {
    typedef TMutableComputationNode<TWideStreamThrottlerWrapper> TBaseComputation;
public:
    class TStreamValue : public TComputationValue<TStreamValue> {
    public:
        using TBase = TComputationValue<TStreamValue>;

        TStreamValue(TMemoryUsageInfo* memInfo, NUdf::TUnboxedValue origStream)
            : TBase(memInfo)
            , OrigStream_(std::move(origStream))
        {
        }

    private:
        NUdf::EFetchStatus WideFetch(NUdf::TUnboxedValue* output, ui32 width) {
            if (Counter_++ % 3) {
                return NUdf::EFetchStatus::Yield;
            }

            TUnboxedValueVector items(width);
            switch (OrigStream_.WideFetch(items.data(), width)) {
            case NUdf::EFetchStatus::Yield:
                return NUdf::EFetchStatus::Yield;
            case NUdf::EFetchStatus::Ok:
                for (size_t i = 0; i < width; i++) {
                    output[i] = std::move(items[i]);
                }
                return NUdf::EFetchStatus::Ok;
            case NUdf::EFetchStatus::Finish:
                return NUdf::EFetchStatus::Finish;
            }
        }

    private:
        NUdf::TUnboxedValue OrigStream_;
        size_t Counter_ = 0;
    };

    TWideStreamThrottlerWrapper(TComputationMutables& mutables, IComputationNode* origStream)
        : TBaseComputation(mutables)
        , OrigStream_(origStream)
    {
    }

    NUdf::TUnboxedValuePod DoCalculate(TComputationContext& ctx) const {
        return ctx.HolderFactory.Create<TStreamValue>(OrigStream_->GetValue(ctx));
    }

private:
    void RegisterDependencies() const final {
        DependsOn(OrigStream_);
    }

private:
    IComputationNode* OrigStream_;
};

class TWideStreamDethrottlerWrapper: public TMutableComputationNode<TWideStreamDethrottlerWrapper> {
    typedef TMutableComputationNode<TWideStreamDethrottlerWrapper> TBaseComputation;
public:
    class TStreamValue : public TComputationValue<TStreamValue> {
    public:
        using TBase = TComputationValue<TStreamValue>;

        TStreamValue(TMemoryUsageInfo* memInfo, NUdf::TUnboxedValue origStream)
            : TBase(memInfo)
            , OrigStream_(std::move(origStream))
        {
        }

    private:
        NUdf::EFetchStatus WideFetch(NUdf::TUnboxedValue* output, ui32 width) {
            TUnboxedValueVector items(width);
            for (;;) {
                switch (OrigStream_.WideFetch(items.data(), width)) {
                case NUdf::EFetchStatus::Yield:
                    continue;
                case NUdf::EFetchStatus::Ok:
                    for (size_t i = 0; i < width; i++) {
                        output[i] = std::move(items[i]);
                    }
                    return NUdf::EFetchStatus::Ok;
                case NUdf::EFetchStatus::Finish:
                    return NUdf::EFetchStatus::Finish;
                }
            }
        }

    private:
        NUdf::TUnboxedValue OrigStream_;
    };

    TWideStreamDethrottlerWrapper(TComputationMutables& mutables, IComputationNode* origStream)
        : TBaseComputation(mutables)
        , OrigStream_(origStream)
    {
    }

    NUdf::TUnboxedValuePod DoCalculate(TComputationContext& ctx) const {
        return ctx.HolderFactory.Create<TStreamValue>(OrigStream_->GetValue(ctx));
    }

private:
    void RegisterDependencies() const final {
        DependsOn(OrigStream_);
    }

private:
    IComputationNode* OrigStream_;
};

IComputationNode* WrapWideStreamThrottler(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
    MKQL_ENSURE(callable.GetInputsCount() == 1, "Expected 1 arg");
    const auto origStream = LocateNode(ctx.NodeLocator, callable, 0);
    return new TWideStreamThrottlerWrapper(ctx.Mutables, origStream);
}

IComputationNode* WrapWideStreamDethrottler(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
    MKQL_ENSURE(callable.GetInputsCount() == 1, "Expected 1 arg");
    const auto origStream = LocateNode(ctx.NodeLocator, callable, 0);
    return new TWideStreamDethrottlerWrapper(ctx.Mutables, origStream);
}

}

TType* MakeBlockTupleType(TProgramBuilder& pgmBuilder, TType* tupleType, bool scalar) {
    const auto itemTypes = AS_TYPE(TTupleType, tupleType)->GetElements();
    const auto ui64Type = pgmBuilder.NewDataType(NUdf::TDataType<ui64>::Id);
    const auto blockLenType = pgmBuilder.NewBlockType(ui64Type, TBlockType::EShape::Scalar);

    TVector<TType*> blockItemTypes;
    std::transform(itemTypes.cbegin(), itemTypes.cend(), std::back_inserter(blockItemTypes),
        [&](const auto& itemType) {
            return pgmBuilder.NewBlockType(itemType, scalar ? TBlockType::EShape::Scalar : TBlockType::EShape::Many);
        });
    // XXX: Mind the last block length column.
    blockItemTypes.push_back(blockLenType);

    return pgmBuilder.NewTupleType(blockItemTypes);
}

TType* MakeJoinType(TProgramBuilder& pgmBuilder, EJoinKind joinKind,
    TType* leftStreamType, const TVector<ui32>& leftKeyDrops,
    TType* rightStreamType, const TVector<ui32>& rightKeyDrops
) {
    const auto leftStreamItems = ValidateBlockStreamType(leftStreamType);
    const auto rightStreamItems = ValidateBlockStreamType(rightStreamType);

    TVector<TType*> joinReturnItems;

    const THashSet<ui32> leftKeyDropsSet(leftKeyDrops.cbegin(), leftKeyDrops.cend());
    for (size_t i = 0; i < leftStreamItems.size() - 1; i++) {  // Excluding block size
        if (leftKeyDropsSet.contains(i)) {
            continue;
        }
        joinReturnItems.push_back(pgmBuilder.NewBlockType(leftStreamItems[i], TBlockType::EShape::Many));
    }

    if (joinKind != EJoinKind::LeftSemi && joinKind != EJoinKind::LeftOnly) {
        const THashSet<ui32> rightKeyDropsSet(rightKeyDrops.cbegin(), rightKeyDrops.cend());
        for (size_t i = 0; i < rightStreamItems.size() - 1; i++) {  // Excluding block size
            if (rightKeyDropsSet.contains(i)) {
                continue;
            }

            joinReturnItems.push_back(pgmBuilder.NewBlockType(
                joinKind == EJoinKind::Inner ? rightStreamItems[i]
                    : IsOptionalOrNull(rightStreamItems[i]) ? rightStreamItems[i]
                    : pgmBuilder.NewOptionalType(rightStreamItems[i]),
                TBlockType::EShape::Many
            ));
        }
    }

    joinReturnItems.push_back(pgmBuilder.NewBlockType(pgmBuilder.NewDataType(NUdf::TDataType<ui64>::Id), TBlockType::EShape::Scalar));
    return pgmBuilder.NewStreamType(pgmBuilder.NewMultiType(joinReturnItems));
}

NUdf::TUnboxedValuePod ToBlocks(TComputationContext& ctx, size_t blockSize,
    const TArrayRef<TType* const> types, const NUdf::TUnboxedValuePod& values
) {
    const auto maxLength = CalcBlockLen(std::accumulate(types.cbegin(), types.cend(), 0ULL,
        [](size_t max, const TType* type) {
            return std::max(max, CalcMaxBlockItemSize(type));
        }));
    TVector<std::unique_ptr<NUdf::IArrayBuilder>> builders;
    std::transform(types.cbegin(), types.cend(), std::back_inserter(builders),
        [&](const auto& type) {
            return MakeArrayBuilder(TTypeInfoHelper(), type, ctx.ArrowMemoryPool,
                                    maxLength, &ctx.Builder->GetPgBuilder());
        });

    const auto& holderFactory = ctx.HolderFactory;
    const size_t width = types.size();
    const size_t total = values.GetListLength();
    NUdf::TUnboxedValue iterator = values.GetListIterator();
    NUdf::TUnboxedValue current;
    size_t converted = 0;
    TDefaultListRepresentation listValues;
    while (converted < total) {
        for (size_t i = 0; i < blockSize && iterator.Next(current); i++, converted++) {
            for (size_t j = 0; j < builders.size(); j++) {
                const NUdf::TUnboxedValuePod& item = current.GetElement(j);
                builders[j]->Add(item);
            }
        }
        std::vector<arrow::Datum> batch;
        batch.reserve(width);
        for (size_t i = 0; i < width; i++) {
            batch.emplace_back(builders[i]->Build(converted >= total));
        }

        NUdf::TArgsDechunker dechunker(std::move(batch));
        std::vector<arrow::Datum> chunk;
        ui64 chunkLen = 0;
        while (dechunker.Next(chunk, chunkLen)) {
            NUdf::TUnboxedValue* items = nullptr;
            const auto tuple = holderFactory.CreateDirectArrayHolder(width + 1, items);
            for (size_t i = 0; i < width; i++) {
                items[i] = holderFactory.CreateArrowBlock(std::move(chunk[i]));
            }
            items[width] = MakeBlockCount(holderFactory, chunkLen);

            listValues = listValues.Append(std::move(tuple));
        }
    }
    return holderFactory.CreateDirectListHolder(std::move(listValues));
}

NUdf::TUnboxedValuePod MakeUint64ScalarBlock(TComputationContext& ctx, size_t blockSize,
    const TArrayRef<TType* const> types, const NUdf::TUnboxedValuePod& values
) {
    // Creates a block of scalar values using the first element of the given list

    for (auto type : types) {
        // Because IScalarBuilder has no implementations
        Y_ENSURE(AS_TYPE(TDataType, type)->GetDataSlot() == NYql::NUdf::EDataSlot::Uint64);
    }

    const auto& holderFactory = ctx.HolderFactory;
    const size_t width = types.size();
    const size_t rowsCount = values.GetListLength();

    NUdf::TUnboxedValue row;
    Y_ENSURE(values.GetListIterator().Next(row));
    TDefaultListRepresentation listValues;
    for (size_t rowOffset = 0; rowOffset < rowsCount; rowOffset += blockSize) {
        NUdf::TUnboxedValue* items = nullptr;
        const auto tuple = holderFactory.CreateDirectArrayHolder(width + 1, items);
        for (size_t i = 0; i < width; i++) {
            const NUdf::TUnboxedValuePod& item = row.GetElement(i);
            items[i] = holderFactory.CreateArrowBlock(arrow::Datum(static_cast<uint64_t>(item.Get<ui64>())));
        }
        items[width] = MakeBlockCount(holderFactory, std::min(blockSize, rowsCount - rowOffset));
        listValues = listValues.Append(std::move(tuple));
    }

    return holderFactory.CreateDirectListHolder(std::move(listValues));
}

NUdf::TUnboxedValuePod FromBlocks(TComputationContext& ctx,
    const TArrayRef<TType* const> types, const NUdf::TUnboxedValuePod& values
) {
    TVector<std::unique_ptr<IBlockReader>> readers;
    TVector<std::unique_ptr<IBlockItemConverter>> converters;
    for (const auto& type : types) {
        const auto blockItemType = AS_TYPE(TBlockType, type)->GetItemType();
        readers.push_back(MakeBlockReader(TTypeInfoHelper(), blockItemType));
        converters.push_back(MakeBlockItemConverter(TTypeInfoHelper(), blockItemType,
                                                    ctx.Builder->GetPgBuilder()));
    }

    const auto& holderFactory = ctx.HolderFactory;
    const size_t width = types.size() - 1;
    TDefaultListRepresentation listValues;
    NUdf::TUnboxedValue iterator = values.GetListIterator();
    NUdf::TUnboxedValue current;
    while (iterator.Next(current)) {
        const auto blockLengthValue = current.GetElement(width);
        const auto blockLengthDatum = TArrowBlock::From(blockLengthValue).GetDatum();
        Y_ENSURE(blockLengthDatum.is_scalar());
        const auto blockLength = blockLengthDatum.scalar_as<arrow::UInt64Scalar>().value;
        for (size_t i = 0; i < blockLength; i++) {
            NUdf::TUnboxedValue* items = nullptr;
            const auto tuple = holderFactory.CreateDirectArrayHolder(width, items);
            for (size_t j = 0; j < width; j++) {
                const auto arrayValue = current.GetElement(j);
                const auto arrayDatum = TArrowBlock::From(arrayValue).GetDatum();
                UNIT_ASSERT(arrayDatum.is_array());
                const auto blockItem = readers[j]->GetItem(*arrayDatum.array(), i);
                items[j] = converters[j]->MakeValue(blockItem, holderFactory);
            }
            listValues = listValues.Append(std::move(tuple));
        }
    }
    return holderFactory.CreateDirectListHolder(std::move(listValues));
}

TComputationNodeFactory GetNodeFactory() {
    return [](TCallable& callable, const TComputationNodeFactoryContext& ctx) -> IComputationNode* {
        if (callable.GetType()->GetName() == "WideStreamThrottler") {
            return WrapWideStreamThrottler(callable, ctx);
        } else if (callable.GetType()->GetName() == "WideStreamDethrottler") {
            return WrapWideStreamDethrottler(callable, ctx);
        }
        return GetBuiltinFactory()(callable, ctx);
    };
}

TRuntimeNode ThrottleStream(TProgramBuilder& pgmBuilder, TRuntimeNode stream) {
    TCallableBuilder callableBuilder(pgmBuilder.GetTypeEnvironment(), "WideStreamThrottler", stream.GetStaticType());
    callableBuilder.Add(stream);
    return TRuntimeNode(callableBuilder.Build(), false);
}

TRuntimeNode DethrottleStream(TProgramBuilder& pgmBuilder, TRuntimeNode stream) {
    TCallableBuilder callableBuilder(pgmBuilder.GetTypeEnvironment(), "WideStreamDethrottler", stream.GetStaticType());
    callableBuilder.Add(stream);
    return TRuntimeNode(callableBuilder.Build(), false);
}

TVector<NUdf::TUnboxedValue> ConvertListToVector(const NUdf::TUnboxedValue& list) {
    NUdf::TUnboxedValue current;
    NUdf::TUnboxedValue iterator = list.GetListIterator();
    TVector<NUdf::TUnboxedValue> items;
    while (iterator.Next(current)) {
        items.push_back(current);
    }
    return items;
}

void CompareResults(const TType* type, const NUdf::TUnboxedValue& expected,
                    const NUdf::TUnboxedValue& got
) {
    const auto itemType = AS_TYPE(TListType, type)->GetItemType();
    const NUdf::ICompare::TPtr compare = MakeCompareImpl(itemType);
    const NUdf::IEquate::TPtr equate = MakeEquateImpl(itemType);
    // XXX: Stub both keyTypes and isTuple arguments, since
    // ICompare/IEquate are used.
    TKeyTypes keyTypesStub;
    bool isTupleStub = false;
    const TValueLess valueLess(keyTypesStub, isTupleStub, compare.Get());
    const TValueEqual valueEqual(keyTypesStub, isTupleStub, equate.Get());

    auto expectedItems = ConvertListToVector(expected);
    auto gotItems = ConvertListToVector(got);
    UNIT_ASSERT_VALUES_EQUAL(expectedItems.size(), gotItems.size());
    Sort(expectedItems, valueLess);
    Sort(gotItems, valueLess);
    for (size_t i = 0; i < expectedItems.size(); i++) {
        UNIT_ASSERT(valueEqual(gotItems[i], expectedItems[i]));
    }
}

TVector<TString> GenerateValues(size_t level) {
    constexpr size_t alphaSize = 'Z' - 'A' + 1;
    if (level == 1) {
        TVector<TString> alphabet(alphaSize);
        std::iota(alphabet.begin(), alphabet.end(), 'A');
        return alphabet;
    }
    const auto subValues = GenerateValues(level - 1);
    TVector<TString> values;
    values.reserve(alphaSize * subValues.size());
    for (char ch = 'A'; ch <= 'Z'; ch++) {
        for (const auto& tail : subValues) {
            values.emplace_back(ch + tail);
        }
    }
    return values;
}

TSet<ui64> GenerateFibonacci(size_t count) {
    TSet<ui64> fibSet;
    ui64 a = 0, b = 1;
    fibSet.insert(a);
    while (count--) {
        a = std::exchange(b, a + b);
        fibSet.insert(b);
    }
    return fibSet;
}

} // namespace NMiniKQL
} // namespace NKikimr