WindowTransform.cpp 32.2 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
    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;
            }

A
Alexander Kuzmenkov 已提交
213 214 215 216 217 218 219 220
            // Move to the first row in current block. Note that the offset is
            // negative.
            offset += x.row;
            x.row = 0;

            // Move to the last row of the previous block, if we are not at the
            // first one. Offset also is incremented by one, because we pass over
            // the first row of this block.
221 222 223 224 225 226
            if (x.block == first_block_number)
            {
                break;
            }

            --x.block;
A
Alexander Kuzmenkov 已提交
227
            offset += 1;
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
            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);

A
Alexander Kuzmenkov 已提交
263 264
//    fmt::print(stderr, "frame start {} left {} partition start {}\n",
//        frame_start, offset_left, partition_start);
265

A
Alexander Kuzmenkov 已提交
266
    if (frame_start <= partition_start)
267 268 269 270 271 272 273
    {
        // Got to the beginning of partition and can't go further back.
        frame_start = partition_start;
        frame_started = true;
        return;
    }

A
Alexander Kuzmenkov 已提交
274
    if (partition_end <= frame_start)
275 276
    {
        // A FOLLOWING frame start ran into the end of partition.
A
Alexander Kuzmenkov 已提交
277 278
        frame_start = partition_end;
        frame_started = partition_ended;
A
Alexander Kuzmenkov 已提交
279
        return;
280 281
    }

A
Alexander Kuzmenkov 已提交
282 283
    // Handled the equality case above. Now the frame start is inside the
    // partition, if we walked all the offset, it's final.
284 285
    assert(partition_start < frame_start);
    frame_started = offset_left == 0;
A
Alexander Kuzmenkov 已提交
286 287 288 289

    // If we ran into the start of data (offset left is negative), we won't be
    // able to make progress. Should have handled this case above.
    assert(offset_left >= 0);
290 291 292 293 294 295 296 297 298 299 300
}

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;
301
        case WindowFrame::BoundaryType::Current:
302 303 304 305 306 307 308 309
            // CURRENT ROW differs between frame types only in how the peer
            // groups are accounted.
            assert(partition_start <= peer_group_start);
            assert(peer_group_start < partition_end);
            assert(peer_group_start <= current_row);
            frame_start = peer_group_start;
            frame_started = true;
            return;
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
        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 已提交
338
    assert(frame_start_before <= frame_start);
339 340
    if (frame_start == frame_start_before)
    {
A
Alexander Kuzmenkov 已提交
341 342 343 344 345 346 347 348
        // 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);
349 350 351 352 353 354 355 356 357 358 359
    }

    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);
    }
A
Alexander Kuzmenkov 已提交
360 361 362
}

bool WindowTransform::arePeers(const RowNumber & x, const RowNumber & y) const
363
{
A
Alexander Kuzmenkov 已提交
364
    if (x == y)
365
    {
A
Alexander Kuzmenkov 已提交
366 367
        // For convenience, a row is always its own peer.
        return true;
368
    }
A
Alexander Kuzmenkov 已提交
369

A
Alexander Kuzmenkov 已提交
370
    if (window_description.frame.type == WindowFrame::FrameType::Rows)
371
    {
A
Alexander Kuzmenkov 已提交
372 373
        // For ROWS frame, row is only peers with itself (checked above);
        return false;
374
    }
375

376
    // For RANGE and GROUPS frames, rows that compare equal w/ORDER BY are peers.
A
Alexander Kuzmenkov 已提交
377
    assert(window_description.frame.type == WindowFrame::FrameType::Range);
378 379 380
    const size_t n = order_by_indices.size();
    if (n == 0)
    {
A
Alexander Kuzmenkov 已提交
381 382
        // No ORDER BY, so all rows are peers.
        return true;
383 384
    }

A
Alexander Kuzmenkov 已提交
385 386
    size_t i = 0;
    for (; i < n; i++)
387
    {
A
Alexander Kuzmenkov 已提交
388 389 390 391
        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)
392
        {
A
Alexander Kuzmenkov 已提交
393
            return false;
394
        }
A
Alexander Kuzmenkov 已提交
395
    }
396

A
Alexander Kuzmenkov 已提交
397 398 399 400 401
    return true;
}

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

A
Alexander Kuzmenkov 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
    // 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 已提交
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
    // 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
cleanup  
Alexander Kuzmenkov 已提交
441
    // Advance frame_end while it is still peers with the current row.
A
Alexander Kuzmenkov 已提交
442
    for (; frame_end.row < rows_end; ++frame_end.row)
A
Alexander Kuzmenkov 已提交
443
    {
A
cleanup  
Alexander Kuzmenkov 已提交
444
        if (!arePeers(current_row, frame_end))
445
        {
A
Alexander Kuzmenkov 已提交
446
//            fmt::print(stderr, "{} and {} don't match\n", reference, frame_end);
A
Alexander Kuzmenkov 已提交
447
            frame_ended = true;
448 449 450 451
            return;
        }
    }

A
Alexander Kuzmenkov 已提交
452 453 454 455 456 457 458
    // 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;
    }
459

A
Alexander Kuzmenkov 已提交
460 461 462
    // Got to the end of partition (frame ended as well then) or end of data.
    assert(frame_end == partition_end);
    frame_ended = partition_ended;
463 464
}

465 466 467 468 469 470 471
void WindowTransform::advanceFrameEndUnbounded()
{
    // The UNBOUNDED FOLLOWING frame ends when the partition ends.
    frame_end = partition_end;
    frame_ended = partition_ended;
}

A
Alexander Kuzmenkov 已提交
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
void WindowTransform::advanceFrameEndRowsOffset()
{
    // Walk the specified offset from the current row. The "+1" is needed
    // because the frame_end is a past-the-end pointer.
    const auto [moved_row, offset_left] = moveRowNumber(current_row,
        window_description.frame.end_offset + 1);

    if (partition_end <= moved_row)
    {
        // Clamp to the end of partition. It might not have ended yet, in which
        // case wait for more data.
        frame_end = partition_end;
        frame_ended = partition_ended;
        return;
    }

    if (moved_row <= partition_start)
    {
        // Clamp to the start of partition.
        frame_end = partition_start;
        frame_ended = true;
        return;
    }

    // Frame end inside partition, if we walked all the offset, it's final.
    frame_end = moved_row;
    frame_ended = offset_left == 0;

    // If we ran into the start of data (offset left is negative), we won't be
    // able to make progress. Should have handled this case above.
    assert(offset_left >= 0);
}

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

    const auto frame_end_before = frame_end;

512 513 514 515 516 517 518 519 520
    switch (window_description.frame.end_type)
    {
        case WindowFrame::BoundaryType::Current:
            advanceFrameEndCurrentRow();
            break;
        case WindowFrame::BoundaryType::Unbounded:
            advanceFrameEndUnbounded();
            break;
        case WindowFrame::BoundaryType::Offset:
A
Alexander Kuzmenkov 已提交
521 522 523 524 525 526 527 528 529 530 531
            switch (window_description.frame.type)
            {
                case WindowFrame::FrameType::Rows:
                    advanceFrameEndRowsOffset();
                    break;
                default:
                    throw Exception(ErrorCodes::NOT_IMPLEMENTED,
                        "The frame end type '{}' is not implemented",
                        WindowFrame::toString(window_description.frame.end_type));
            }
            break;
532
    }
533

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

536 537 538 539 540 541
    // 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;
    }
542
}
543

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
// Update the aggregation states after the frame has changed.
void WindowTransform::updateAggregationState()
{
//    fmt::print(stderr, "update agg states [{}, {}) -> [{}, {})\n",
//        prev_frame_start, prev_frame_end, frame_start, frame_end);

    // Assert that the frame boundaries are known, have proper order wrt each
    // other, and have not gone back wrt the previous frame.
    assert(frame_started);
    assert(frame_ended);
    assert(frame_start <= frame_end);
    assert(prev_frame_start <= prev_frame_end);
    assert(prev_frame_start <= frame_start);
    assert(prev_frame_end <= frame_end);

    // We might have to reset aggregation state and/or add some rows to it.
    // Figure out what to do.
    bool reset_aggregation = false;
    RowNumber rows_to_add_start;
    RowNumber rows_to_add_end;
    if (frame_start == prev_frame_start)
    {
        // The frame start didn't change, add the tail rows.
        reset_aggregation = false;
        rows_to_add_start = prev_frame_end;
        rows_to_add_end = frame_end;
570 571 572
    }
    else
    {
573 574 575 576 577 578 579
        // The frame start changed, reset the state and aggregate over the
        // entire frame. This can be made per-function after we learn to
        // subtract rows from some types of aggregation states, but for now we
        // always have to reset when the frame start changes.
        reset_aggregation = true;
        rows_to_add_start = frame_start;
        rows_to_add_end = frame_end;
580
    }
581

582 583
    for (auto & ws : workspaces)
    {
584 585 586 587
        const auto * a = ws.window_function.aggregate_function.get();
        auto * buf = ws.aggregate_function_state.data();

        if (reset_aggregation)
A
Alexander Kuzmenkov 已提交
588
        {
589 590 591
//            fmt::print(stderr, "(2) reset aggregation\n");
            a->destroy(buf);
            a->create(buf);
592
        }
593

594 595
        for (auto row = rows_to_add_start; row < rows_to_add_end;
            advanceRowNumber(row))
596
        {
597 598 599 600 601 602 603 604 605 606 607 608
            if (row.block != ws.cached_block_number)
            {
                const auto & block
                    = blocks[row.block - first_block_number];
                ws.argument_columns.clear();
                for (const auto i : ws.argument_column_indices)
                {
                    ws.argument_columns.push_back(block.input_columns[i].get());
                }
                ws.cached_block_number = row.block;
            }

609
//            fmt::print(stderr, "(2) add row {}\n", row);
610 611
            auto * columns = ws.argument_columns.data();
            a->add(buf, columns, row.row, arena.get());
612 613
        }
    }
614 615 616

    prev_frame_start = frame_start;
    prev_frame_end = frame_end;
617 618
}

A
Alexander Kuzmenkov 已提交
619
void WindowTransform::writeOutCurrentRow()
620
{
A
Alexander Kuzmenkov 已提交
621 622
    assert(current_row < partition_end);
    assert(current_row.block >= first_block_number);
623 624 625 626 627 628 629 630

    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 已提交
631
        IColumn * result_column = outputAt(current_row)[wi].get();
632 633
        // FIXME does it also allocate the result on the arena?
        // We'll have to pass it out with blocks then...
A
Alexander Kuzmenkov 已提交
634
        a->insertResultInto(buf, *result_column, arena.get());
635 636
    }
}
637

638 639
void WindowTransform::appendChunk(Chunk & chunk)
{
A
cleanup  
Alexander Kuzmenkov 已提交
640 641
//    fmt::print(stderr, "new chunk, {} rows, finished={}\n", chunk.getNumRows(),
//        input_is_finished);
642 643 644 645 646

    // 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 已提交
647
        assert(chunk.hasRows());
648 649 650 651 652 653 654 655 656
        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)
657
            {
658 659 660
                block.input_columns[column_index]
                    = std::move(block.input_columns[column_index])
                        ->convertToFullColumnIfConst();
A
Alexander Kuzmenkov 已提交
661
            }
662 663 664 665 666 667 668 669 670 671

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

    // Start the calculations. First, advance the partition end.
    for (;;)
    {
        advancePartitionEnd();
672 673
//        fmt::print(stderr, "partition [{}, {}), {}\n",
//            partition_start, partition_end, partition_ended);
674 675 676 677 678 679 680 681 682

        // 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 已提交
683 684 685 686
        // 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)
687
        {
688 689 690 691
//            fmt::print(stderr, "(1) row {} frame [{}, {}) {}, {}\n",
//                current_row, frame_start, frame_end,
//                frame_started, frame_ended);

692 693 694 695 696 697 698
            // We now know that the current row is valid, so we can update the
            // peer group start.
            if (!arePeers(peer_group_start, current_row))
            {
                peer_group_start = current_row;
            }

699
            // Advance the frame start.
700
            advanceFrameStart();
701 702 703 704 705 706

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

710 711 712 713 714 715 716
            // frame_end must be greater or equal than frame_start, so if the
            // frame_start is already past the current frame_end, we can start
            // from it to save us some work.
            if (frame_end < frame_start)
            {
                frame_end = frame_start;
            }
717

718 719
            // Advance the frame end.
            advanceFrameEnd();
A
Alexander Kuzmenkov 已提交
720

721 722
            if (!frame_ended)
            {
723 724 725
                // Wait for more input data to find the end of frame.
                assert(!input_is_finished);
                assert(!partition_ended);
726 727 728
                return;
            }

729 730 731 732
//            fmt::print(stderr, "(2) row {} frame [{}, {}) {}, {}\n",
//                current_row, frame_start, frame_end,
//                frame_started, frame_ended);

733 734 735
            // 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 已提交
736 737
            assert(frame_started);
            assert(frame_ended);
738
            assert(frame_start <= frame_end);
739

740 741 742 743 744 745 746
            // Now that we know the new frame boundaries, update the aggregation
            // states. Theoretically we could do this simultaneously with moving
            // the frame boundaries, but it would require some care not to
            // perform unnecessary work while we are still looking for the frame
            // start, so do it the simple way for now.
            updateAggregationState();

A
Alexander Kuzmenkov 已提交
747 748
            // Write out the aggregation results.
            writeOutCurrentRow();
749

A
Alexander Kuzmenkov 已提交
750
            // Move to the next row. The frame will have to be recalculated.
751 752
            // The peer group start is updated at the beginning of the loop,
            // because current_row might now be past-the-end.
A
Alexander Kuzmenkov 已提交
753 754 755
            advanceRowNumber(current_row);
            first_not_ready_row = current_row;
            frame_ended = false;
756
            frame_started = false;
757
        }
758

759 760 761 762 763
        if (input_is_finished)
        {
            // We finalized the last partition in the above loop, and don't have
            // to do anything else.
            return;
764 765 766 767
        }

        if (!partition_ended)
        {
768 769 770
            // 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.
771
            assert(partition_end == blocksEnd());
772
            assert(!input_is_finished);
773 774 775 776
            break;
        }

        // Start the next partition.
777
        partition_start = partition_end;
778 779 780 781 782
        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.
783 784
        frame_start = partition_start;
        frame_end = partition_start;
785 786
        prev_frame_start = partition_start;
        prev_frame_end = partition_start;
787
        assert(current_row == partition_start);
788
        peer_group_start = partition_start;
789

A
cleanup  
Alexander Kuzmenkov 已提交
790 791
//        fmt::print(stderr, "reinitialize agg data at start of {}\n",
//            new_partition_start);
792 793
        // Reinitialize the aggregate function states because the new partition
        // has started.
794 795 796 797 798 799
        for (auto & ws : workspaces)
        {
            const auto & f = ws.window_function;
            const auto * a = f.aggregate_function.get();
            auto * buf = ws.aggregate_function_state.data();

800 801
            a->destroy(buf);
        }
A
Alexander Kuzmenkov 已提交
802

803 804 805 806 807 808
        // 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 已提交
809 810
        }

811 812 813 814 815
        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 已提交
816

817 818 819
            a->create(buf);
        }
    }
A
Alexander Kuzmenkov 已提交
820 821
}

A
Alexander Kuzmenkov 已提交
822 823
IProcessor::Status WindowTransform::prepare()
{
A
cleanup  
Alexander Kuzmenkov 已提交
824 825 826
//    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());
827

A
Alexander Kuzmenkov 已提交
828 829
    if (output.isFinished())
    {
830 831
        // The consumer asked us not to continue (or we decided it ourselves),
        // so we abort.
A
Alexander Kuzmenkov 已提交
832 833 834 835
        input.close();
        return Status::Finished;
    }

836 837 838 839 840 841 842 843 844
    if (output_data.exception)
    {
        // An exception occurred during processing.
        output.pushData(std::move(output_data));
        output.finish();
        input.close();
        return Status::Finished;
    }

845
    assert(first_not_ready_row.block >= first_block_number);
A
cleanup  
Alexander Kuzmenkov 已提交
846 847 848
    // 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.
849 850 851 852 853 854 855
    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 已提交
856
    {
857 858 859
        if (output.canPush())
        {
            // Output the ready block.
A
cleanup  
Alexander Kuzmenkov 已提交
860
//            fmt::print(stderr, "output block {}\n", next_output_block_number);
861 862 863 864 865 866 867 868 869 870 871 872
            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 已提交
873

874 875
        // We don't need input.setNotNeeded() here, because we already pull with
        // the set_not_needed flag.
A
Alexander Kuzmenkov 已提交
876 877 878
        return Status::PortFull;
    }

879
    if (input_is_finished)
A
Alexander Kuzmenkov 已提交
880
    {
881 882 883 884 885
        // 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 已提交
886

887 888
        // FIXME do we really have to do this?
        output.finish();
A
Alexander Kuzmenkov 已提交
889

890 891
        return Status::Finished;
    }
A
Alexander Kuzmenkov 已提交
892

893 894 895
    // Consume input data if we have any ready.
    if (!has_input && input.hasData())
    {
896 897 898 899 900
        // 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 已提交
901
        input_data = input.pullData(true /* set_not_needed */);
A
Alexander Kuzmenkov 已提交
902 903 904 905 906 907 908 909 910 911 912

        // 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 已提交
913 914
        has_input = true;

915 916 917 918 919 920 921 922 923 924 925 926 927 928
        // 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 已提交
929 930
    }

931 932 933
    // We have to wait for more input.
    input.setNeeded();
    return Status::NeedData;
A
Alexander Kuzmenkov 已提交
934 935 936 937
}

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

941 942
    assert(has_input || input_is_finished);

A
Alexander Kuzmenkov 已提交
943 944
    try
    {
945 946
        has_input = false;
        appendChunk(input_data.chunk);
A
Alexander Kuzmenkov 已提交
947 948 949 950 951 952 953 954
    }
    catch (DB::Exception &)
    {
        output_data.exception = std::current_exception();
        has_input = false;
        return;
    }

955 956 957
    // 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
958 959 960
    // 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.
961
    const auto first_used_block = std::min(next_output_block_number,
962 963
        std::min(frame_start.block, current_row.block));

964 965
    if (first_block_number < first_used_block)
    {
A
cleanup  
Alexander Kuzmenkov 已提交
966 967
//        fmt::print(stderr, "will drop blocks from {} to {}\n", first_block_number,
//            first_used_block);
968 969

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

973 974
        assert(next_output_block_number >= first_block_number);
        assert(frame_start.block >= first_block_number);
A
Alexander Kuzmenkov 已提交
975
        assert(current_row.block >= first_block_number);
976
        assert(peer_group_start.block >= first_block_number);
977
    }
A
Alexander Kuzmenkov 已提交
978 979 980
}


A
Alexander Kuzmenkov 已提交
981
}