lbug 0.21.0

An in-process property graph database management system built for query speed and scalability
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
#include "optimizer/acc_hash_join_optimizer.h"

#include "binder/expression/expression_util.h"
#include "catalog/catalog_entry/table_catalog_entry.h"
#include "common/constants.h"
#include "optimizer/logical_operator_collector.h"
#include "planner/operator/extend/base_logical_extend.h"
#include "planner/operator/extend/logical_extend.h"
#include "planner/operator/extend/logical_recursive_extend.h"
#include "planner/operator/logical_accumulate.h"
#include "planner/operator/logical_hash_join.h"
#include "planner/operator/logical_intersect.h"
#include "planner/operator/logical_limit.h"
#include "planner/operator/logical_multiplcity_reducer.h"
#include "planner/operator/logical_path_property_probe.h"
#include "planner/operator/scan/logical_scan_node_table.h"
#include "planner/operator/sip/logical_semi_masker.h"

using namespace lbug::common;
using namespace lbug::binder;
using namespace lbug::planner;
using namespace lbug::function;

namespace lbug {
namespace optimizer {

static std::shared_ptr<LogicalOperator> appendAccumulate(std::shared_ptr<LogicalOperator> child) {
    auto accumulate = std::make_shared<LogicalAccumulate>(AccumulateType::REGULAR,
        expression_vector{}, nullptr /* mark */, std::move(child));
    accumulate->computeFlatSchema();
    return accumulate;
}

static table_id_vector_t getTableIDs(const std::vector<catalog::TableCatalogEntry*>& entries) {
    table_id_vector_t result;
    for (auto& entry : entries) {
        result.push_back(entry->getTableID());
    }
    return result;
}

static std::vector<table_id_t> getTableIDs(const LogicalOperator* op,
    SemiMaskTargetType targetType) {
    switch (op->getOperatorType()) {
    case LogicalOperatorType::SCAN_NODE_TABLE: {
        return op->constCast<LogicalScanNodeTable>().getTableIDs();
    }
    case LogicalOperatorType::EXTEND:
    case LogicalOperatorType::PACKED_EXTEND: {
        DASSERT(targetType == SemiMaskTargetType::EXTEND_NBR_NODE);
        return getTableIDs(op->constCast<BaseLogicalExtend>().getNbrNode()->getEntries());
    }
    case LogicalOperatorType::RECURSIVE_EXTEND: {
        auto& bindData = op->constCast<LogicalRecursiveExtend>().getBindData();
        switch (targetType) {
        case SemiMaskTargetType::RECURSIVE_EXTEND_INPUT_NODE: {
            auto& node = bindData.nodeInput->constCast<NodeExpression>();
            return getTableIDs(node.getEntries());
        }
        case SemiMaskTargetType::RECURSIVE_EXTEND_OUTPUT_NODE: {
            auto& node = bindData.nodeOutput->constCast<NodeExpression>();
            return getTableIDs(node.getEntries());
        }
        default:
            UNREACHABLE_CODE;
        }
    }
    default:
        UNREACHABLE_CODE;
    }
}

static bool sameTableIDs(const std::unordered_set<table_id_t>& set,
    const std::vector<table_id_t>& ids) {
    if (set.size() != ids.size()) {
        return false;
    }
    for (auto id : ids) {
        if (!set.contains(id)) {
            return false;
        }
    }
    return true;
}

static bool haveSameTableIDs(const std::vector<LogicalOperator*>& ops,
    SemiMaskTargetType targetType) {
    std::unordered_set<table_id_t> tableIDSet;
    for (auto id : getTableIDs(ops[0], targetType)) {
        tableIDSet.insert(id);
    }
    for (auto i = 0u; i < ops.size(); ++i) {
        if (!sameTableIDs(tableIDSet, getTableIDs(ops[i], targetType))) {
            return false;
        }
    }
    return true;
}

static bool haveSameType(const std::vector<LogicalOperator*>& ops) {
    for (auto i = 0u; i < ops.size(); ++i) {
        if (ops[i]->getOperatorType() != ops[0]->getOperatorType()) {
            return false;
        }
    }
    return true;
}

bool sanityCheckCandidates(const std::vector<LogicalOperator*>& ops,
    SemiMaskTargetType targetType) {
    DASSERT(!ops.empty());
    if (!haveSameType(ops)) {
        return false;
    }
    if (!haveSameTableIDs(ops, targetType)) {
        return false;
    }
    return true;
}

static std::shared_ptr<LogicalSemiMasker> appendSemiMasker(SemiMaskKeyType keyType,
    SemiMaskTargetType targetType, std::shared_ptr<Expression> key,
    std::vector<LogicalOperator*> candidates, std::shared_ptr<LogicalOperator> child) {
    auto tableIDs = getTableIDs(candidates[0], targetType);
    auto semiMasker =
        std::make_shared<LogicalSemiMasker>(keyType, targetType, key, tableIDs, child);
    for (auto candidate : candidates) {
        semiMasker->addTarget(candidate);
    }
    semiMasker->computeFlatSchema();
    return semiMasker;
}

void HashJoinSIPOptimizer::rewrite(const LogicalPlan* plan) {
    probeLimit = nullptr;
    probeLimitTarget = nullptr;
    // A literal LIMIT at the end of a projection-only tail can be pushed into the probe
    // side of the join directly below that tail once probe-to-build SIP fires: the join
    // then emits at most `limit` rows while the capped probe seeds a much smaller build
    // scan. The push is result-preserving only for row-wise, order-preserving tails, so
    // stop the walk at any other operator (ORDER_BY/AGGREGATE/FLATTEN/...) and push into
    // at most one join per plan.
    auto op = plan->getLastOperator();
    while (op != nullptr) {
        const auto type = op->getOperatorType();
        // Both operators are row-wise and keep the output probe-major with >= 1 row per
        // probe row: PROJECTION is 1:1, and MULTIPLICITY_REDUCER only expands each input
        // row to its multiplicity (it never collapses distinct rows). The first `limit`
        // rows above them are therefore produced by the first few probe rows either way.
        // EXPLAIN is a transparent wrapper (PROFILE plans carry it at the root).
        if (type == LogicalOperatorType::PROJECTION ||
            type == LogicalOperatorType::MULTIPLICITY_REDUCER ||
            type == LogicalOperatorType::EXPLAIN) {
            if (op->getNumChildren() != 1) {
                break;
            }
            op = op->getChild(0);
            continue;
        }
        if (type == LogicalOperatorType::LIMIT && probeLimit == nullptr) {
            auto& limit = op->cast<LogicalLimit>();
            if (op->getNumChildren() != 1 || limit.hasSkipNum() || !limit.hasLimitNum() ||
                !ExpressionUtil::canEvaluateAsLiteral(*limit.getLimitNum())) {
                break;
            }
            probeLimit = limit.getLimitNum();
            op = op->getChild(0);
            continue;
        }
        if (type == LogicalOperatorType::HASH_JOIN) {
            probeLimitTarget = op.get();
        }
        break;
    }
    visitOperator(plan->getLastOperator().get());
}

void HashJoinSIPOptimizer::visitOperator(LogicalOperator* op) {
    // bottom up traversal
    for (auto i = 0u; i < op->getNumChildren(); ++i) {
        visitOperator(op->getChild(i).get());
    }
    visitOperatorSwitch(op);
}

static bool subPlanContainsFilter(LogicalOperator* root) {
    auto filterCollector = LogicalFilterCollector();
    filterCollector.collect(root);
    auto indexScanNodeCollector = LogicalIndexScanNodeCollector();
    indexScanNodeCollector.collect(root);
    if (!filterCollector.hasOperators() && !indexScanNodeCollector.hasOperators()) {
        return false;
    }
    return true;
}

// Probe side is qualified if it is selective.
static bool subPlanContainsRelScan(LogicalOperator* root) {
    if (root->getOperatorType() == LogicalOperatorType::EXTEND ||
        root->getOperatorType() == LogicalOperatorType::PACKED_EXTEND) {
        return true;
    }
    for (auto i = 0u; i < root->getNumChildren(); ++i) {
        if (subPlanContainsRelScan(root->getChild(i).get())) {
            return true;
        }
    }
    return false;
}

static bool isProbeSideQualified(LogicalOperator* probeRoot) {
    if (probeRoot->getOperatorType() == LogicalOperatorType::ACCUMULATE) {
        // No Acc hash join if probe side has already been accumulated. This can be solved.
        return false;
    }
    // A rel-scan rooted at EXTEND/PACKED_EXTEND is bounded by the edges it walks and is
    // selective enough to seed a probe-to-build semi-mask, even when it has no predicate.
    if (subPlanContainsFilter(probeRoot)) {
        return true;
    }
    return subPlanContainsRelScan(probeRoot) ||
           probeRoot->getOperatorType() == LogicalOperatorType::SCAN_NODE_TABLE;
}

// Find all ScanNodeIDs under root which scans parameter nodeID. Note that there might be
// multiple ScanNodeIDs matches because both node and rel table scans will trigger scanNodeIDs.
static std::vector<LogicalOperator*> getScanNodeCandidates(const Expression& nodeID,
    LogicalOperator* root) {
    std::vector<LogicalOperator*> result;
    auto collector = LogicalScanNodeTableCollector();
    collector.collect(root);
    for (auto& op : collector.getOperators()) {
        auto& scan = op->constCast<LogicalScanNodeTable>();
        if (scan.getScanType() != LogicalScanNodeTableType::SCAN) {
            // Do not apply semi mask to index scan.
            continue;
        }
        if (nodeID.getUniqueName() == scan.getNodeID()->getUniqueName()) {
            result.push_back(op);
        }
    }
    return result;
}

static std::vector<LogicalOperator*> getRecursiveExtendInputNodeCandidates(const Expression& nodeID,
    LogicalOperator* root) {
    std::vector<LogicalOperator*> result;
    auto collector = LogicalRecursiveExtendCollector();
    collector.collect(root);
    for (auto& op : collector.getOperators()) {
        auto& recursiveExtend = op->constCast<LogicalRecursiveExtend>();
        auto& bindData = recursiveExtend.getBindData();
        if (nodeID == *bindData.nodeInput->constCast<NodeExpression>().getInternalID()) {
            result.push_back(op);
        }
    }
    return result;
}

static std::vector<LogicalOperator*> getRecursiveExtendOutputNodeCandidates(
    const Expression& nodeID, LogicalOperator* root) {
    std::vector<LogicalOperator*> result;
    auto collector = LogicalRecursiveExtendCollector();
    collector.collect(root);
    for (auto op : collector.getOperators()) {
        auto& recursiveExtend = op->constCast<LogicalRecursiveExtend>();
        auto& bindData = recursiveExtend.getBindData();
        if (nodeID == *bindData.nodeOutput->constCast<NodeExpression>().getInternalID()) {
            result.push_back(op);
        }
    }
    return result;
}

// Find all (packed) extends under root whose neighbour node is parameter nodeID. The
// neighbour IDs are produced by the rel scan, so a semi mask on them prunes the scan
// itself instead of materializing every expanded edge. PACKED_EXTEND is not covered by
// the operator visitor, hence the manual traversal.
static void collectExtendNbrCandidates(const Expression& nodeID, LogicalOperator* root,
    std::vector<LogicalOperator*>& result) {
    auto type = root->getOperatorType();
    if (type == LogicalOperatorType::EXTEND || type == LogicalOperatorType::PACKED_EXTEND) {
        // LogicalPackedExtend derives from LogicalExtend, so this cast covers both.
        auto& extend = root->constCast<LogicalExtend>();
        // The mask filters outVectors[0], which only holds neighbour IDs when the
        // extend scans them.
        if (extend.shouldScanNbrID() &&
            nodeID.getUniqueName() == extend.getNbrNode()->getInternalID()->getUniqueName()) {
            result.push_back(root);
        }
    }
    for (auto i = 0u; i < root->getNumChildren(); ++i) {
        collectExtendNbrCandidates(nodeID, root->getChild(i).get(), result);
    }
}

static bool sanityCheckExtendCandidates(const std::vector<LogicalOperator*>& ops) {
    DASSERT(!ops.empty());
    for (auto op : ops) {
        auto type = op->getOperatorType();
        if (type != LogicalOperatorType::EXTEND && type != LogicalOperatorType::PACKED_EXTEND) {
            return false;
        }
    }
    return haveSameTableIDs(ops, SemiMaskTargetType::EXTEND_NBR_NODE);
}

// Probe-to-build SIP materializes and rescans the probe side, which costs ~1ms even for
// tiny probes. Only target build-side rel scans whose estimated output is large enough
// to amortize that: a bounded chain expanding a few hundred edges is already cheap, so
// masking it is pure overhead (e.g. a single-tag probe masking a 274-edge expand).
static constexpr cardinality_t MIN_EXTEND_OUTPUT_FOR_PROBE_TO_BUILD_SIP = 10000;

static std::shared_ptr<LogicalOperator> tryApplySemiMask(std::shared_ptr<Expression> nodeID,
    std::shared_ptr<LogicalOperator> fromRoot, LogicalOperator* toRoot, bool isProbeToBuild) {
    // TODO(Xiyang): Check if a semi mask can/need to be applied to ScanNodeTable, RecursiveJoin &
    // GDS at the same time
    auto recursiveExtendInputNodeCandidates =
        getRecursiveExtendInputNodeCandidates(*nodeID, toRoot);
    if (!recursiveExtendInputNodeCandidates.empty()) {
        for (auto& op : recursiveExtendInputNodeCandidates) {
            op->cast<LogicalRecursiveExtend>().setInputNodeMask();
        }
        auto targetType = SemiMaskTargetType::RECURSIVE_EXTEND_INPUT_NODE;
        DASSERT(sanityCheckCandidates(recursiveExtendInputNodeCandidates, targetType));
        return appendSemiMasker(SemiMaskKeyType::NODE, targetType, std::move(nodeID),
            recursiveExtendInputNodeCandidates, std::move(fromRoot));
    }
    auto recursiveExtendNodeCandidates = getRecursiveExtendOutputNodeCandidates(*nodeID, toRoot);
    if (!recursiveExtendNodeCandidates.empty()) {
        for (auto& op : recursiveExtendNodeCandidates) {
            op->cast<LogicalRecursiveExtend>().setOutputNodeMask();
        }
        auto targetType = SemiMaskTargetType::RECURSIVE_EXTEND_OUTPUT_NODE;
        DASSERT(sanityCheckCandidates(recursiveExtendNodeCandidates, targetType));
        return appendSemiMasker(SemiMaskKeyType::NODE, targetType, std::move(nodeID),
            recursiveExtendNodeCandidates, std::move(fromRoot));
    }
    auto scanNodeCandidates = getScanNodeCandidates(*nodeID, toRoot);
    std::vector<LogicalOperator*> extendNbrCandidates;
    collectExtendNbrCandidates(*nodeID, toRoot, extendNbrCandidates);
    if (isProbeToBuild) {
        std::erase_if(extendNbrCandidates, [](const LogicalOperator* op) {
            return op->getCardinality() < MIN_EXTEND_OUTPUT_FOR_PROBE_TO_BUILD_SIP;
        });
    }
    if (scanNodeCandidates.empty() && extendNbrCandidates.empty()) {
        return nullptr;
    }
    // Chain one masker per target kind; each masker passes its input through, so a
    // single pass over fromRoot fills both the node-table and the rel-scan masks.
    auto result = std::move(fromRoot);
    auto hasSemiMaskApplied = false;
    if (!scanNodeCandidates.empty()) {
        result = appendSemiMasker(SemiMaskKeyType::NODE, SemiMaskTargetType::SCAN_NODE, nodeID,
            scanNodeCandidates, std::move(result));
        hasSemiMaskApplied = true;
    }
    if (!extendNbrCandidates.empty() && sanityCheckExtendCandidates(extendNbrCandidates)) {
        result = appendSemiMasker(SemiMaskKeyType::NODE, SemiMaskTargetType::EXTEND_NBR_NODE,
            nodeID, extendNbrCandidates, std::move(result));
        hasSemiMaskApplied = true;
    }
    if (!hasSemiMaskApplied) {
        return nullptr;
    }
    return result;
}

// The pushed limit is result-preserving only if every probe row matches exactly one build
// row. A plain node-table scan (optionally under projections) emits each join key exactly
// once, and every probe-produced key is guaranteed to be in the build side's semi-mask, so
// the match count is exactly one. Filters could drop a probed key (match count zero), and
// extends can emit multiple rows per key, so both disqualify the push.
static bool isBuildSideUniquePerKey(LogicalOperator* root) {
    while (true) {
        switch (root->getOperatorType()) {
        case LogicalOperatorType::SCAN_NODE_TABLE:
            return root->constCast<LogicalScanNodeTable>().getScanType() ==
                   LogicalScanNodeTableType::SCAN;
        case LogicalOperatorType::PROJECTION:
            if (root->getNumChildren() != 1) {
                return false;
            }
            root = root->getChild(0).get();
            break;
        default:
            return false;
        }
    }
}

static bool tryProbeToBuildHJSIP(LogicalOperator* op,
    const std::shared_ptr<Expression>& probeLimit) {
    auto& hashJoin = op->cast<LogicalHashJoin>();
    if (!isProbeSideQualified(op->getChild(0).get())) {
        return false;
    }
    // Probe-to-build SIP materializes and rescans the whole probe side (ACCUMULATE +
    // READ_FTABLE, one morsel per factorized-table row) to seed the build-side semi mask.
    // When the probe side is at least as large as the build side, the mask can prune at most
    // buildCard rows while materialization pays collect + rescan over probeCard rows, so the
    // optimization cannot pay off: keep the plain pipelined hash join. Exempt the LIMIT
    // pushdown path (probeLimit), whose capped probe still benefits from the mask.
    if (probeLimit == nullptr &&
        hashJoin.getChild(0)->getCardinality() >= hashJoin.getChild(1)->getCardinality()) {
        return false;
    }
    auto probeRoot = hashJoin.getChild(0);
    auto buildRoot = hashJoin.getChild(1);
    auto hasSemiMaskApplied = false;
    for (auto& nodeID : hashJoin.getJoinNodeIDs()) {
        auto newProbeRoot =
            tryApplySemiMask(nodeID, probeRoot, buildRoot.get(), true /* isProbeToBuild */);
        if (newProbeRoot != nullptr) {
            probeRoot = newProbeRoot;
            hasSemiMaskApplied = true;
        }
    }
    if (!hasSemiMaskApplied) {
        return false;
    }
    auto& sipInfo = hashJoin.getSIPInfoUnsafe();
    sipInfo.position = SemiMaskPosition::ON_PROBE;
    sipInfo.dependency = SIPDependency::PROBE_DEPENDS_ON_BUILD;
    sipInfo.direction = SIPDirection::PROBE_TO_BUILD;
    if (probeLimit != nullptr && hashJoin.getJoinType() == JoinType::INNER &&
        isBuildSideUniquePerKey(buildRoot.get())) {
        // Every LogicalLimit in a plan must sit on a MULTIPLICITY_REDUCER (planner
        // invariant; TopKOptimizer::visitLimitReplace relies on it). For the flattened
        // probe rows here the reducer is an identity pass-through.
        auto reducer = std::make_shared<LogicalMultiplicityReducer>(std::move(probeRoot));
        reducer->computeFlatSchema();
        auto limit = std::make_shared<LogicalLimit>(nullptr, probeLimit, std::move(reducer));
        limit->computeFlatSchema();
        probeRoot = std::move(limit);
    }
    hashJoin.setChild(0, appendAccumulate(probeRoot));
    return true;
}

static bool isBuildSideQualified(LogicalOperator* buildRoot) {
    if (subPlanContainsFilter(buildRoot)) {
        return true;
    }
    // TODO(Xiyang): this may not be the best solution. Most of the time we will pass a semi mask
    // to GDS (recursive join) operator and make it generate small result. Though there are also
    // exceptions. In such case we will pay a bit overhead.
    auto op = buildRoot;
    while (op->getNumChildren() == 1) {
        op = op->getChild(0).get();
    }
    return op->getOperatorType() == LogicalOperatorType::RECURSIVE_EXTEND;
}

// A build without filters can still seed an effective semi mask when it is far smaller
// than the probe side (e.g. a PK-anchored chain of a few thousand rows vs a multi-million
// row probe scan): the mask then prunes the bulk of the probe scan. This mirrors the
// planner's SIP_RATIO guard, which prohibits the reverse (probe-to-build) direction when
// the probe outweighs the build by the same ratio.
static bool isBuildSmallRelativeToProbe(LogicalOperator* op) {
    auto& hashJoin = op->cast<LogicalHashJoin>();
    const auto probeCard = hashJoin.getChild(0)->getCardinality();
    const auto buildCard = hashJoin.getChild(1)->getCardinality();
    return probeCard / PlannerKnobs::SIP_RATIO > buildCard;
}

static bool tryBuildToProbeHJSIP(LogicalOperator* op) {
    auto& hashJoin = op->cast<LogicalHashJoin>();
    if (hashJoin.getJoinType() != JoinType::INNER) {
        return false;
    }
    if (hashJoin.getSIPInfo().direction != SIPDirection::FORCE_BUILD_TO_PROBE &&
        !isBuildSideQualified(op->getChild(1).get()) && !isBuildSmallRelativeToProbe(op)) {
        return false;
    }
    auto probeRoot = hashJoin.getChild(0);
    auto buildRoot = hashJoin.getChild(1);
    auto hasSemiMaskApplied = false;
    for (auto& nodeID : hashJoin.getJoinNodeIDs()) {
        auto newBuildRoot =
            tryApplySemiMask(nodeID, buildRoot, probeRoot.get(), false /* isProbeToBuild */);
        if (newBuildRoot != nullptr) {
            buildRoot = newBuildRoot;
            hasSemiMaskApplied = true;
        }
    }
    if (!hasSemiMaskApplied) {
        return false;
    }
    auto& sipInfo = hashJoin.getSIPInfoUnsafe();
    sipInfo.position = SemiMaskPosition::ON_BUILD;
    sipInfo.dependency = SIPDependency::BUILD_DEPENDS_ON_PROBE;
    sipInfo.direction = SIPDirection::BUILD_TO_PROBE;
    hashJoin.setChild(1, buildRoot);
    return true;
}

void HashJoinSIPOptimizer::visitHashJoin(LogicalOperator* op) {
    auto& hashJoin = op->cast<LogicalHashJoin>();
    if (LogicalOperatorUtils::isAccHashJoin(hashJoin)) {
        return;
    }
    if (hashJoin.getSIPInfo().position == SemiMaskPosition::PROHIBIT) {
        return;
    }
    if (tryBuildToProbeHJSIP(op)) { // Try build to probe SIP first.
        return;
    }
    if (hashJoin.getSIPInfo().position == SemiMaskPosition::PROHIBIT_PROBE_TO_BUILD) {
        return;
    }
    // Only the join directly below the projection-only tail may consume the pushed limit,
    // and at most one join per plan does.
    tryProbeToBuildHJSIP(op, op == probeLimitTarget ? probeLimit : nullptr);
}

// TODO(Xiyang): we don't apply SIP from build to probe.
void HashJoinSIPOptimizer::visitIntersect(LogicalOperator* op) {
    auto& intersect = op->cast<LogicalIntersect>();
    switch (intersect.getSIPInfo().position) {
    case SemiMaskPosition::PROHIBIT_PROBE_TO_BUILD:
    case SemiMaskPosition::PROHIBIT:
        return;
    default:
        break;
    }
    if (!isProbeSideQualified(op->getChild(0).get())) {
        return;
    }
    auto probeRoot = intersect.getChild(0);
    auto hasSemiMaskApplied = false;
    for (auto& nodeID : intersect.getKeyNodeIDs()) {
        std::vector<LogicalOperator*> ops;
        for (auto i = 1u; i < intersect.getNumChildren(); ++i) {
            auto buildRoot = intersect.getChild(i);
            for (auto& op_ : getScanNodeCandidates(*nodeID, buildRoot.get())) {
                ops.push_back(op_);
            }
        }
        if (!ops.empty()) {
            probeRoot = appendSemiMasker(SemiMaskKeyType::NODE, SemiMaskTargetType::SCAN_NODE,
                nodeID, ops, probeRoot);
            hasSemiMaskApplied = true;
        }
    }
    if (!hasSemiMaskApplied) {
        return;
    }
    auto& sipInfo = intersect.getSIPInfoUnsafe();
    sipInfo.position = SemiMaskPosition::ON_PROBE;
    sipInfo.dependency = SIPDependency::PROBE_DEPENDS_ON_BUILD;
    sipInfo.direction = SIPDirection::PROBE_TO_BUILD;
    intersect.setChild(0, appendAccumulate(probeRoot));
}

void HashJoinSIPOptimizer::visitPathPropertyProbe(LogicalOperator* op) {
    auto& pathPropertyProbe = op->cast<LogicalPathPropertyProbe>();
    switch (pathPropertyProbe.getSIPInfo().position) {
    case SemiMaskPosition::PROHIBIT_PROBE_TO_BUILD:
    case SemiMaskPosition::PROHIBIT:
        return;
    default:
        break;
    }
    if (pathPropertyProbe.getJoinType() == RecursiveJoinType::TRACK_NONE) {
        return;
    }
    auto recursiveRel = pathPropertyProbe.getRel();
    auto nodeID = recursiveRel->getRecursiveInfo()->node->getInternalID();
    std::vector<LogicalOperator*> opsToApplySemiMask;
    if (pathPropertyProbe.getNodeChild() != nullptr) {
        auto child = pathPropertyProbe.getNodeChild().get();
        for (auto op_ : getScanNodeCandidates(*nodeID, child)) {
            opsToApplySemiMask.push_back(op_);
        }
    }
    if (pathPropertyProbe.getRelChild() != nullptr) {
        auto child = pathPropertyProbe.getRelChild().get();
        for (auto op_ : getScanNodeCandidates(*nodeID, child)) {
            opsToApplySemiMask.push_back(op_);
        }
    }
    if (opsToApplySemiMask.empty()) {
        return;
    }
    DASSERT(
        pathPropertyProbe.getChild(0)->getOperatorType() == LogicalOperatorType::RECURSIVE_EXTEND);
    auto semiMasker = appendSemiMasker(SemiMaskKeyType::NODE_ID_LIST, SemiMaskTargetType::SCAN_NODE,
        recursiveRel->getRecursiveInfo()->bindData->pathNodeIDsExpr, opsToApplySemiMask,
        pathPropertyProbe.getChild(0));
    auto srcNodeID = recursiveRel->getSrcNode()->getInternalID();
    auto dstNodeID = recursiveRel->getDstNode()->getInternalID();
    semiMasker->setExtraKeyInfo(std::make_unique<ExtraNodeIDListKeyInfo>(srcNodeID, dstNodeID));
    pathPropertyProbe.setChild(0, semiMasker);

    auto& sipInfo = pathPropertyProbe.getSIPInfoUnsafe();
    sipInfo.position = SemiMaskPosition::ON_PROBE;
    sipInfo.dependency = SIPDependency::PROBE_DEPENDS_ON_BUILD;
    sipInfo.direction = SIPDirection::PROBE_TO_BUILD;
}

} // namespace optimizer
} // namespace lbug