WindowTransform.cpp 29.4 KB
Newer Older
A
Alexander Kuzmenkov 已提交
1 2 3 4
#include <Processors/Transforms/WindowTransform.h>

#include <Interpreters/ExpressionActions.h>

A
Alexander Kuzmenkov 已提交
5 6
#include <Common/Arena.h>

A
Alexander Kuzmenkov 已提交
7 8 9
namespace DB
{

10 11
namespace ErrorCodes
{
A
Alexander Kuzmenkov 已提交
12
    extern const int NOT_IMPLEMENTED;
13 14
}

A
Alexander Kuzmenkov 已提交
15 16 17
WindowTransform::WindowTransform(const Block & input_header_,
        const Block & output_header_,
        const WindowDescription & window_description_,
A
Alexander Kuzmenkov 已提交
18 19 20 21
        const std::vector<WindowFunctionDescription> & functions)
    : IProcessor({input_header_}, {output_header_})
    , input(inputs.front())
    , output(outputs.front())
A
Alexander Kuzmenkov 已提交
22 23
    , input_header(input_header_)
    , window_description(window_description_)
A
Alexander Kuzmenkov 已提交
24
{
A
Alexander Kuzmenkov 已提交
25 26
    workspaces.reserve(functions.size());
    for (const auto & f : functions)
A
Alexander Kuzmenkov 已提交
27 28
    {
        WindowFunctionWorkspace workspace;
A
cleanup  
Alexander Kuzmenkov 已提交
29
        workspace.window_function = f;
A
Alexander Kuzmenkov 已提交
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

        const auto & aggregate_function
            = workspace.window_function.aggregate_function;
        if (!arena && aggregate_function->allocatesMemoryInArena())
        {
            arena = std::make_unique<Arena>();
        }

        workspace.argument_column_indices.reserve(
            workspace.window_function.argument_names.size());
        for (const auto & argument_name : workspace.window_function.argument_names)
        {
            workspace.argument_column_indices.push_back(
                input_header.getPositionByName(argument_name));
        }

        workspace.aggregate_function_state.reset(aggregate_function->sizeOfData(),
            aggregate_function->alignOfData());
        aggregate_function->create(workspace.aggregate_function_state.data());

        workspaces.push_back(std::move(workspace));
    }

    partition_by_indices.reserve(window_description.partition_by.size());
    for (const auto & column : window_description.partition_by)
    {
        partition_by_indices.push_back(
            input_header.getPositionByName(column.column_name));
    }
59 60 61 62 63 64 65

    order_by_indices.reserve(window_description.order_by.size());
    for (const auto & column : window_description.order_by)
    {
        order_by_indices.push_back(
            input_header.getPositionByName(column.column_name));
    }
A
Alexander Kuzmenkov 已提交
66
}
A
Alexander Kuzmenkov 已提交
67

A
Alexander Kuzmenkov 已提交
68
WindowTransform::~WindowTransform()
A
Alexander Kuzmenkov 已提交
69
{
A
Alexander Kuzmenkov 已提交
70
    // Some states may be not created yet if the creation failed.
71
    for (auto & ws : workspaces)
A
Alexander Kuzmenkov 已提交
72
    {
73 74
        ws.window_function.aggregate_function->destroy(
            ws.aggregate_function_state.data());
A
Alexander Kuzmenkov 已提交
75
    }
A
Alexander Kuzmenkov 已提交
76 77
}

78
void WindowTransform::advancePartitionEnd()
A
Alexander Kuzmenkov 已提交
79
{
80 81 82 83
    if (partition_ended)
    {
        return;
    }
A
Alexander Kuzmenkov 已提交
84

85 86
    const RowNumber end = blocksEnd();

87
//    fmt::print(stderr, "end {}, partition_end {}\n", end, partition_end);
88

89 90 91 92 93
    // If we're at the total end of data, we must end the partition. This is one
    // of the few places in calculations where we need special handling for end
    // of data, other places will work as usual based on
    // `partition_ended` = true, because end of data is logically the same as
    // any other end of partition.
94 95 96
    // We must check this first, because other calculations might not be valid
    // when we're at the end of data.
    if (input_is_finished)
A
Alexander Kuzmenkov 已提交
97
    {
98
        partition_ended = true;
99 100 101
        // We receive empty chunk at the end of data, so the partition_end must
        // be already at the end of data.
        assert(partition_end == end);
102 103 104
        return;
    }

105 106
    // If we got to the end of the block already, but we are going to get more
    // input data, wait for it.
107 108 109 110 111 112 113 114 115 116 117 118
    if (partition_end == end)
    {
        return;
    }

    // We process one block at a time, but we can process each block many times,
    // if it contains multiple partitions. The `partition_end` is a
    // past-the-end pointer, so it must be already in the "next" block we haven't
    // processed yet. This is also the last block we have.
    // The exception to this rule is end of data, for which we checked above.
    assert(end.block == partition_end.block + 1);

119 120 121 122 123 124 125 126 127 128
    // Try to advance the partition end pointer.
    const size_t n = partition_by_indices.size();
    if (n == 0)
    {
        // No PARTITION BY. All input is one partition, which will end when the
        // input ends.
        partition_end = end;
        return;
    }

129 130 131 132
    // Check for partition end.
    // The partition ends when the PARTITION BY columns change. We need
    // some reference columns for comparison. We might have already
    // dropped the blocks where the partition starts, but any row in the
133 134 135
    // partition will do. We use the current_row for this. It might be the same
    // as the partition_end if we're at the first row of the first partition, so
    // we will compare it to itself, but it still works correctly.
136 137
    const auto block_rows = blockRowsNumber(partition_end);
    for (; partition_end.row < block_rows; ++partition_end.row)
138 139
    {
        size_t i = 0;
A
cleanup  
Alexander Kuzmenkov 已提交
140
        for (; i < n; i++)
A
Alexander Kuzmenkov 已提交
141
        {
142
            const auto * ref = inputAt(current_row)[partition_by_indices[i]].get();
143 144
            const auto * c = inputAt(partition_end)[partition_by_indices[i]].get();
            if (c->compareAt(partition_end.row,
145
                    current_row.row, *ref,
146 147 148 149 150
                    1 /* nan_direction_hint */) != 0)
            {
                break;
            }
        }
A
Alexander Kuzmenkov 已提交
151

152 153 154 155
        if (i < n)
        {
            partition_ended = true;
            return;
A
Alexander Kuzmenkov 已提交
156
        }
157 158
    }

159 160 161 162
    // Went until the end of block, go to the next.
    assert(partition_end.row == block_rows);
    ++partition_end.block;
    partition_end.row = 0;
163

164 165 166 167
    // Went until the end of data and didn't find the new partition.
    assert(!partition_ended && partition_end == blocksEnd());
}

168
auto WindowTransform::moveRowNumberNoCheck(const RowNumber & _x, int offset) const
A
Alexander Kuzmenkov 已提交
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
    RowNumber x = _x;

    if (offset > 0)
    {
        for (;;)
        {
            assertValid(x);
            assert(offset >= 0);

            const auto block_rows = blockRowsNumber(x);
            x.row += offset;
            if (x.row >= block_rows)
            {
                offset = x.row - block_rows;
                x.row = 0;
                x.block++;

                if (x == blocksEnd())
                {
                    break;
                }
            }
            else
            {
                offset = 0;
                break;
            }
        }
    }
    else if (offset < 0)
    {
        for (;;)
        {
            assertValid(x);
            assert(offset <= 0);

            if (x.row >= static_cast<uint64_t>(-offset))
            {
                x.row -= -offset;
                offset = 0;
                break;
            }

            if (x.block == first_block_number)
            {
                break;
            }

            // offset is negative
            offset += (x.row + 1);
            --x.block;
            x.row = blockRowsNumber(x) - 1;
        }
    }

    return std::tuple{x, offset};
}

auto WindowTransform::moveRowNumber(const RowNumber & _x, int offset) const
{
    auto [x, o] = moveRowNumberNoCheck(_x, offset);

#ifndef NDEBUG
    // Check that it was reversible.
    auto [xx, oo] = moveRowNumberNoCheck(x, -(offset - o));

//    fmt::print(stderr, "{} -> {}, result {}, {}, new offset {}, twice {}, {}\n",
//        _x, offset, x, o, -(offset - o), xx, oo);
    assert(xx == _x);
    assert(oo == 0);
#endif

    return std::tuple{x, o};
}


void WindowTransform::advanceFrameStartRowsOffset()
{
    // Just recalculate it each time by walking blocks.
    const auto [moved_row, offset_left] = moveRowNumber(current_row,
        window_description.frame.begin_offset);

    frame_start = moved_row;

    assertValid(frame_start);

//    fmt::print(stderr, "frame start {} partition start {}\n", frame_start,
//        partition_start);

    if (moved_row <= partition_start)
    {
        // Got to the beginning of partition and can't go further back.
        frame_start = partition_start;
        frame_started = true;
        return;
    }

    assert(frame_start <= partition_end);
    if (frame_start == partition_end && partition_ended)
    {
        // A FOLLOWING frame start ran into the end of partition.
        frame_started = true;
    }

    assert(partition_start < frame_start);
    frame_start = moved_row;
    frame_started = offset_left == 0;
}

void WindowTransform::advanceFrameStartChoose()
{
    switch (window_description.frame.begin_type)
    {
        case WindowFrame::BoundaryType::Unbounded:
            // UNBOUNDED PRECEDING, just mark it valid. It is initialized when
            // the new partition starts.
            frame_started = true;
            return;
288 289 290 291 292 293 294 295 296 297 298 299 300
        case WindowFrame::BoundaryType::Current:
            switch (window_description.frame.type)
            {
                case WindowFrame::FrameType::Rows:
                    // CURRENT ROW
                    frame_start = current_row;
                    frame_started = true;
                    return;
                default:
                    // Fallthrough to the "not implemented" error.
                    break;
            }
            break;
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
        case WindowFrame::BoundaryType::Offset:
            switch (window_description.frame.type)
            {
                case WindowFrame::FrameType::Rows:
                    advanceFrameStartRowsOffset();
                    return;
                default:
                    // Fallthrough to the "not implemented" error.
                    break;
            }
            break;
    }

    throw Exception(ErrorCodes::NOT_IMPLEMENTED,
        "Frame start type '{}' for frame '{}' is not implemented",
        WindowFrame::toString(window_description.frame.begin_type),
        WindowFrame::toString(window_description.frame.type));
}

void WindowTransform::advanceFrameStart()
{
    if (frame_started)
    {
        return;
    }

    const auto frame_start_before = frame_start;
    advanceFrameStartChoose();
A
Alexander Kuzmenkov 已提交
329
    assert(frame_start_before <= frame_start);
330 331
    if (frame_start == frame_start_before)
    {
A
Alexander Kuzmenkov 已提交
332 333 334 335 336 337 338 339
        // If the frame start didn't move, this means we validated that the frame
        // starts at the point we reached earlier but were unable to validate.
        // This probably only happens in degenerate cases where the frame start
        // is further than the end of partition, and the partition ends at the
        // last row of the block, but we can only tell for sure after a new
        // block arrives. We still have to update the state of aggregate
        // functions when the frame start becomes valid, so we continue.
        assert(frame_started);
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
    }

    assert(partition_start <= frame_start);
    assert(frame_start <= partition_end);
    if (partition_ended && frame_start == partition_end)
    {
        // Check that if the start of frame (e.g. FOLLOWING) runs into the end
        // of partition, it is marked as valid -- we can't advance it any
        // further.
        assert(frame_started);
    }

    // We're very dumb and have to reinitialize aggregate functions if the frame
    // start changed. No point in doing it if we don't yet know where the frame
    // starts.
    if (!frame_started)
    {
        return;
    }

    // frame_end value might not be valid yet, but we know that it is greater or
    // equal than frame_start. If it's less than the new frame_start, we have to
    // skip rows between frame_end and frame_start, because they are not in the
    // frame and must not contribute to the value of aggregate functions.
    if (frame_end < frame_start)
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
        frame_end = frame_start;
    }

    for (auto & ws : workspaces)
    {
        const auto & f = ws.window_function;
        const auto * a = f.aggregate_function.get();
        auto * buf = ws.aggregate_function_state.data();

        a->destroy(buf);
        a->create(buf);

        for (auto row = frame_start; row < frame_end; advanceRowNumber(row))
        {
            if (row.block != ws.cached_block_number)
            {
                ws.argument_columns.clear();
                for (const auto i : ws.argument_column_indices)
                {
                    ws.argument_columns.push_back(inputAt(row)[i].get());
                }
                ws.cached_block_number = row.block;
            }

            a->add(buf, ws.argument_columns.data(), row.row, arena.get());
//            fmt::print(stderr, "(1) add row {}\n", row.row);
        }
393
    }
A
Alexander Kuzmenkov 已提交
394 395 396
}

bool WindowTransform::arePeers(const RowNumber & x, const RowNumber & y) const
397
{
A
Alexander Kuzmenkov 已提交
398
    if (x == y)
399
    {
A
Alexander Kuzmenkov 已提交
400 401
        // For convenience, a row is always its own peer.
        return true;
402
    }
A
Alexander Kuzmenkov 已提交
403

A
Alexander Kuzmenkov 已提交
404
    if (window_description.frame.type == WindowFrame::FrameType::Rows)
405
    {
A
Alexander Kuzmenkov 已提交
406 407
        // For ROWS frame, row is only peers with itself (checked above);
        return false;
408
    }
409

410
    // For RANGE and GROUPS frames, rows that compare equal w/ORDER BY are peers.
A
Alexander Kuzmenkov 已提交
411
    assert(window_description.frame.type == WindowFrame::FrameType::Range);
412 413 414
    const size_t n = order_by_indices.size();
    if (n == 0)
    {
A
Alexander Kuzmenkov 已提交
415 416
        // No ORDER BY, so all rows are peers.
        return true;
417 418
    }

A
Alexander Kuzmenkov 已提交
419 420
    size_t i = 0;
    for (; i < n; i++)
421
    {
A
Alexander Kuzmenkov 已提交
422 423 424 425
        const auto * column_x = inputAt(x)[order_by_indices[i]].get();
        const auto * column_y = inputAt(y)[order_by_indices[i]].get();
        if (column_x->compareAt(x.row, y.row, *column_y,
                1 /* nan_direction_hint */) != 0)
426
        {
A
Alexander Kuzmenkov 已提交
427
            return false;
428
        }
A
Alexander Kuzmenkov 已提交
429
    }
430

A
Alexander Kuzmenkov 已提交
431 432 433 434 435
    return true;
}

void WindowTransform::advanceFrameEndCurrentRow()
{
A
Alexander Kuzmenkov 已提交
436 437
//    fmt::print(stderr, "starting from frame_end {}\n", frame_end);

A
Alexander Kuzmenkov 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
    // We only process one block here, and frame_end must be already in it: if
    // we didn't find the end in the previous block, frame_end is now the first
    // row of the current block. We need this knowledge to write a simpler loop
    // (only loop over rows and not over blocks), that should hopefully be more
    // efficient.
    // partition_end is either in this new block or past-the-end.
    assert(frame_end.block  == partition_end.block
        || frame_end.block + 1 == partition_end.block);

    if (frame_end == partition_end)
    {
        // The case when we get a new block and find out that the partition has
        // ended.
        assert(partition_ended);
        frame_ended = partition_ended;
        return;
    }

A
Alexander Kuzmenkov 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    // We advance until the partition end. It's either in the current block or
    // in the next one, which is also the past-the-end block. Figure out how
    // many rows we have to process.
    uint64_t rows_end;
    if (partition_end.row == 0)
    {
        assert(partition_end == blocksEnd());
        rows_end = blockRowsNumber(frame_end);
    }
    else
    {
        assert(frame_end.block == partition_end.block);
        rows_end = partition_end.row;
    }
    // Equality would mean "no data to process", for which we checked above.
    assert(frame_end.row < rows_end);

//    fmt::print(stderr, "first row {} last {}\n", frame_end.row, rows_end);

A
Alexander Kuzmenkov 已提交
475 476 477
    // We could retreat the frame_end here, but for some reason I am reluctant
    // to do this... It would have better data locality.
    auto reference = current_row;
A
Alexander Kuzmenkov 已提交
478
    for (; frame_end.row < rows_end; ++frame_end.row)
A
Alexander Kuzmenkov 已提交
479 480
    {
        if (!arePeers(reference, frame_end))
481
        {
A
Alexander Kuzmenkov 已提交
482
//            fmt::print(stderr, "{} and {} don't match\n", reference, frame_end);
A
Alexander Kuzmenkov 已提交
483
            frame_ended = true;
484 485
            return;
        }
A
Alexander Kuzmenkov 已提交
486
        reference = frame_end;
487 488
    }

A
Alexander Kuzmenkov 已提交
489 490 491 492 493 494 495
    // Might have gotten to the end of the current block, have to properly
    // update the row number.
    if (frame_end.row == blockRowsNumber(frame_end))
    {
        ++frame_end.block;
        frame_end.row = 0;
    }
496

A
Alexander Kuzmenkov 已提交
497 498 499
    // Got to the end of partition (frame ended as well then) or end of data.
    assert(frame_end == partition_end);
    frame_ended = partition_ended;
500 501
}

502 503 504 505 506 507 508
void WindowTransform::advanceFrameEndUnbounded()
{
    // The UNBOUNDED FOLLOWING frame ends when the partition ends.
    frame_end = partition_end;
    frame_ended = partition_ended;
}

509 510
void WindowTransform::advanceFrameEnd()
{
A
Alexander Kuzmenkov 已提交
511 512
    // No reason for this function to be called again after it succeeded.
    assert(!frame_ended);
513 514 515

    const auto frame_end_before = frame_end;

516 517 518 519 520 521 522 523 524 525 526 527 528 529
    switch (window_description.frame.end_type)
    {
        case WindowFrame::BoundaryType::Current:
            // The only frame end we have for now is CURRENT ROW.
            advanceFrameEndCurrentRow();
            break;
        case WindowFrame::BoundaryType::Unbounded:
            advanceFrameEndUnbounded();
            break;
        case WindowFrame::BoundaryType::Offset:
            throw Exception(ErrorCodes::NOT_IMPLEMENTED,
                "The frame end type '{}' is not implemented",
                WindowFrame::toString(window_description.frame.end_type));
    }
530

A
Alexander Kuzmenkov 已提交
531 532
//    fmt::print(stderr, "frame_end {} -> {}\n", frame_end_before, frame_end);

533 534 535 536 537 538 539
    // We might not have advanced the frame end if we found out we reached the
    // end of input or the partition, or if we still don't know the frame start.
    if (frame_end_before == frame_end)
    {
        return;
    }

540 541
    // Add the rows over which we advanced the frame to the aggregate function
    // states. We could have advanced over at most the entire last block.
A
Alexander Kuzmenkov 已提交
542
    uint64_t rows_end = frame_end.row;
543
    if (frame_end.row == 0)
544
    {
545
        assert(frame_end == blocksEnd());
A
Alexander Kuzmenkov 已提交
546
        rows_end = blockRowsNumber(frame_end_before);
547 548 549 550 551
    }
    else
    {
        assert(frame_end_before.block == frame_end.block);
    }
A
Alexander Kuzmenkov 已提交
552 553
    // Equality would mean "no data to process", for which we checked above.
    assert(frame_end_before.row < rows_end);
554

555 556 557
    for (auto & ws : workspaces)
    {
        if (frame_end_before.block != ws.cached_block_number)
A
Alexander Kuzmenkov 已提交
558
        {
559 560 561
            const auto & block
                = blocks[frame_end_before.block - first_block_number];
            ws.argument_columns.clear();
562
            for (const auto i : ws.argument_column_indices)
A
Alexander Kuzmenkov 已提交
563
            {
564
                ws.argument_columns.push_back(block.input_columns[i].get());
A
Alexander Kuzmenkov 已提交
565
            }
566 567
            ws.cached_block_number = frame_end_before.block;
        }
568

569 570 571
        const auto * a = ws.window_function.aggregate_function.get();
        auto * buf = ws.aggregate_function_state.data();
        auto * columns = ws.argument_columns.data();
A
Alexander Kuzmenkov 已提交
572
        for (auto row = frame_end_before.row; row < rows_end; ++row)
573
        {
574
//            fmt::print(stderr, "(2) add row {}\n", row);
575
            a->add(buf, columns, row, arena.get());
576 577 578 579
        }
    }
}

A
Alexander Kuzmenkov 已提交
580
void WindowTransform::writeOutCurrentRow()
581
{
A
Alexander Kuzmenkov 已提交
582 583
    assert(current_row < partition_end);
    assert(current_row.block >= first_block_number);
584 585 586 587 588 589 590 591

    for (size_t wi = 0; wi < workspaces.size(); ++wi)
    {
        auto & ws = workspaces[wi];
        const auto & f = ws.window_function;
        const auto * a = f.aggregate_function.get();
        auto * buf = ws.aggregate_function_state.data();

A
Alexander Kuzmenkov 已提交
592
        IColumn * result_column = outputAt(current_row)[wi].get();
593 594
        // FIXME does it also allocate the result on the arena?
        // We'll have to pass it out with blocks then...
A
Alexander Kuzmenkov 已提交
595
        a->insertResultInto(buf, *result_column, arena.get());
596 597
    }
}
598

599 600
void WindowTransform::appendChunk(Chunk & chunk)
{
A
cleanup  
Alexander Kuzmenkov 已提交
601 602
//    fmt::print(stderr, "new chunk, {} rows, finished={}\n", chunk.getNumRows(),
//        input_is_finished);
603 604 605 606 607

    // First, prepare the new input block and add it to the queue. We might not
    // have it if it's end of data, though.
    if (!input_is_finished)
    {
A
Alexander Kuzmenkov 已提交
608
        assert(chunk.hasRows());
609 610 611 612 613 614 615 616 617
        blocks.push_back({});
        auto & block = blocks.back();
        block.input_columns = chunk.detachColumns();

        for (auto & ws : workspaces)
        {
            // Aggregate functions can't work with constant columns, so we have to
            // materialize them like the Aggregator does.
            for (const auto column_index : ws.argument_column_indices)
618
            {
619 620 621
                block.input_columns[column_index]
                    = std::move(block.input_columns[column_index])
                        ->convertToFullColumnIfConst();
A
Alexander Kuzmenkov 已提交
622
            }
623 624 625 626 627 628 629 630 631 632

            block.output_columns.push_back(ws.window_function.aggregate_function
                ->getReturnType()->createColumn());
        }
    }

    // Start the calculations. First, advance the partition end.
    for (;;)
    {
        advancePartitionEnd();
633 634
//        fmt::print(stderr, "partition [{}, {}), {}\n",
//            partition_start, partition_end, partition_ended);
635 636 637 638 639 640 641 642 643

        // Either we ran out of data or we found the end of partition (maybe
        // both, but this only happens at the total end of data).
        assert(partition_ended || partition_end == blocksEnd());
        if (partition_ended && partition_end == blocksEnd())
        {
            assert(input_is_finished);
        }

A
Alexander Kuzmenkov 已提交
644 645 646 647
        // After that, try to calculate window functions for each next row.
        // We can continue until the end of partition or current end of data,
        // which is precisely the definition of `partition_end`.
        while (current_row < partition_end)
648 649 650 651
        {
            // Advance the frame start, updating the state of the aggregate
            // functions.
            advanceFrameStart();
652 653 654 655 656 657 658 659

            if (!frame_started)
            {
                // Wait for more input data to find the start of frame.
                assert(!input_is_finished);
                assert(!partition_ended);
            }

660 661 662 663
            // Advance the frame end, updating the state of the aggregate
            // functions.
            advanceFrameEnd();

664 665 666
//            fmt::print(stderr, "row {} frame [{}, {}) {}, {}\n",
//                current_row, frame_start, frame_end,
//                frame_started, frame_ended);
A
Alexander Kuzmenkov 已提交
667

668 669
            if (!frame_ended)
            {
670 671 672
                // Wait for more input data to find the end of frame.
                assert(!input_is_finished);
                assert(!partition_ended);
673 674 675
                return;
            }

676 677 678
            // The frame can be empty sometimes, e.g. the boundaries coincide
            // or the start is after the partition end. But hopefully start is
            // not after end.
A
Alexander Kuzmenkov 已提交
679 680
            assert(frame_started);
            assert(frame_ended);
681
            assert(frame_start <= frame_end);
682

A
Alexander Kuzmenkov 已提交
683 684
            // Write out the aggregation results.
            writeOutCurrentRow();
685

A
Alexander Kuzmenkov 已提交
686 687 688 689
            // Move to the next row. The frame will have to be recalculated.
            advanceRowNumber(current_row);
            first_not_ready_row = current_row;
            frame_ended = false;
690
            frame_started = false;
691
        }
692

693 694 695 696 697
        if (input_is_finished)
        {
            // We finalized the last partition in the above loop, and don't have
            // to do anything else.
            return;
698 699 700 701
        }

        if (!partition_ended)
        {
702 703 704
            // Wait for more input data to find the end of partition.
            // Assert that we processed all the data we currently have, and that
            // we are going to receive more data.
705
            assert(partition_end == blocksEnd());
706
            assert(!input_is_finished);
707 708 709 710
            break;
        }

        // Start the next partition.
711
        partition_start = partition_end;
712 713 714 715 716
        advanceRowNumber(partition_end);
        partition_ended = false;
        // We have to reset the frame when the new partition starts. This is not a
        // generally correct way to do so, but we don't really support moving frame
        // for now.
717 718 719
        frame_start = partition_start;
        frame_end = partition_start;
        assert(current_row == partition_start);
720

A
cleanup  
Alexander Kuzmenkov 已提交
721 722
//        fmt::print(stderr, "reinitialize agg data at start of {}\n",
//            new_partition_start);
723 724
        // Reinitialize the aggregate function states because the new partition
        // has started.
725 726 727 728 729 730
        for (auto & ws : workspaces)
        {
            const auto & f = ws.window_function;
            const auto * a = f.aggregate_function.get();
            auto * buf = ws.aggregate_function_state.data();

731 732
            a->destroy(buf);
        }
A
Alexander Kuzmenkov 已提交
733

734 735 736 737 738 739
        // Release the arena we use for aggregate function states, so that it
        // doesn't grow without limit. Not sure if it's actually correct, maybe
        // it allocates the return values in the Arena as well...
        if (arena)
        {
            arena = std::make_unique<Arena>();
A
Alexander Kuzmenkov 已提交
740 741
        }

742 743 744 745 746
        for (auto & ws : workspaces)
        {
            const auto & f = ws.window_function;
            const auto * a = f.aggregate_function.get();
            auto * buf = ws.aggregate_function_state.data();
A
Alexander Kuzmenkov 已提交
747

748 749 750
            a->create(buf);
        }
    }
A
Alexander Kuzmenkov 已提交
751 752
}

A
Alexander Kuzmenkov 已提交
753 754
IProcessor::Status WindowTransform::prepare()
{
A
cleanup  
Alexander Kuzmenkov 已提交
755 756 757
//    fmt::print(stderr, "prepare, next output {}, not ready row {}, first block {}, hold {} blocks\n",
//        next_output_block_number, first_not_ready_row, first_block_number,
//        blocks.size());
758

A
Alexander Kuzmenkov 已提交
759 760
    if (output.isFinished())
    {
761 762
        // The consumer asked us not to continue (or we decided it ourselves),
        // so we abort.
A
Alexander Kuzmenkov 已提交
763 764 765 766
        input.close();
        return Status::Finished;
    }

767 768 769 770 771 772 773 774 775
    if (output_data.exception)
    {
        // An exception occurred during processing.
        output.pushData(std::move(output_data));
        output.finish();
        input.close();
        return Status::Finished;
    }

776
    assert(first_not_ready_row.block >= first_block_number);
A
cleanup  
Alexander Kuzmenkov 已提交
777 778 779
    // The first_not_ready_row might be past-the-end if we have already
    // calculated the window functions for all input rows. That's why the
    // equality is also valid here.
780 781 782 783 784 785 786
    assert(first_not_ready_row.block <= first_block_number + blocks.size());
    assert(next_output_block_number >= first_block_number);

    // Output the ready data prepared by work().
    // We inspect the calculation state and create the output chunk right here,
    // because this is pretty lightweight.
    if (next_output_block_number < first_not_ready_row.block)
A
Alexander Kuzmenkov 已提交
787
    {
788 789 790
        if (output.canPush())
        {
            // Output the ready block.
A
cleanup  
Alexander Kuzmenkov 已提交
791
//            fmt::print(stderr, "output block {}\n", next_output_block_number);
792 793 794 795 796 797 798 799 800 801 802 803
            const auto i = next_output_block_number - first_block_number;
            ++next_output_block_number;
            auto & block = blocks[i];
            auto columns = block.input_columns;
            for (auto & res : block.output_columns)
            {
                columns.push_back(ColumnPtr(std::move(res)));
            }
            output_data.chunk.setColumns(columns, block.numRows());

            output.pushData(std::move(output_data));
        }
A
Alexander Kuzmenkov 已提交
804

805 806
        // We don't need input.setNotNeeded() here, because we already pull with
        // the set_not_needed flag.
A
Alexander Kuzmenkov 已提交
807 808 809
        return Status::PortFull;
    }

810
    if (input_is_finished)
A
Alexander Kuzmenkov 已提交
811
    {
812 813 814 815 816
        // The input data ended at the previous prepare() + work() cycle,
        // and we don't have ready output data (checked above). We must be
        // finished.
        assert(next_output_block_number == first_block_number + blocks.size());
        assert(first_not_ready_row == blocksEnd());
A
Alexander Kuzmenkov 已提交
817

818 819
        // FIXME do we really have to do this?
        output.finish();
A
Alexander Kuzmenkov 已提交
820

821 822
        return Status::Finished;
    }
A
Alexander Kuzmenkov 已提交
823

824 825 826
    // Consume input data if we have any ready.
    if (!has_input && input.hasData())
    {
827 828 829 830 831
        // Pulling with set_not_needed = true and using an explicit setNeeded()
        // later is somewhat more efficient, because after the setNeeded(), the
        // required input block will be generated in the same thread and passed
        // to our prepare() + work() methods in the same thread right away, so
        // hopefully we will work on hot (cached) data.
A
Alexander Kuzmenkov 已提交
832
        input_data = input.pullData(true /* set_not_needed */);
A
Alexander Kuzmenkov 已提交
833 834 835 836 837 838 839 840 841 842 843

        // If we got an exception from input, just return it and mark that we're
        // finished.
        if (input_data.exception)
        {
            output.pushData(std::move(input_data));
            output.finish();

            return Status::PortFull;
        }

A
Alexander Kuzmenkov 已提交
844 845
        has_input = true;

846 847 848 849 850 851 852 853 854 855 856 857 858 859
        // Now we have new input and can try to generate more output in work().
        return Status::Ready;
    }

    // We 1) don't have any ready output (checked above),
    // 2) don't have any more input (also checked above).
    // Will we get any more input?
    if (input.isFinished())
    {
        // We won't, time to finalize the calculation in work(). We should only
        // do this once.
        assert(!input_is_finished);
        input_is_finished = true;
        return Status::Ready;
A
Alexander Kuzmenkov 已提交
860 861
    }

862 863 864
    // We have to wait for more input.
    input.setNeeded();
    return Status::NeedData;
A
Alexander Kuzmenkov 已提交
865 866 867 868
}

void WindowTransform::work()
{
A
Alexander Kuzmenkov 已提交
869 870
    // Exceptions should be skipped in prepare().
    assert(!input_data.exception);
A
Alexander Kuzmenkov 已提交
871

872 873
    assert(has_input || input_is_finished);

A
Alexander Kuzmenkov 已提交
874 875
    try
    {
876 877
        has_input = false;
        appendChunk(input_data.chunk);
A
Alexander Kuzmenkov 已提交
878 879 880 881 882 883 884 885
    }
    catch (DB::Exception &)
    {
        output_data.exception = std::current_exception();
        has_input = false;
        return;
    }

886 887 888
    // We don't really have to keep the entire partition, and it can be big, so
    // we want to drop the starting blocks to save memory.
    // We can drop the old blocks if we already returned them as output, and the
889 890 891
    // frame and the current row are already past them. Note that the frame
    // start can be further than current row for some frame specs (e.g. EXCLUDE
    // CURRENT ROW), so we have to check both.
892
    const auto first_used_block = std::min(next_output_block_number,
893 894
        std::min(frame_start.block, current_row.block));

895 896
    if (first_block_number < first_used_block)
    {
A
cleanup  
Alexander Kuzmenkov 已提交
897 898
//        fmt::print(stderr, "will drop blocks from {} to {}\n", first_block_number,
//            first_used_block);
899 900 901 902

        blocks.erase(blocks.begin(),
            blocks.begin() + first_used_block - first_block_number);
        first_block_number = first_used_block;
A
Alexander Kuzmenkov 已提交
903

904 905
        assert(next_output_block_number >= first_block_number);
        assert(frame_start.block >= first_block_number);
A
Alexander Kuzmenkov 已提交
906
        assert(current_row.block >= first_block_number);
907
    }
A
Alexander Kuzmenkov 已提交
908 909 910
}


A
Alexander Kuzmenkov 已提交
911
}