summaryrefslogtreecommitdiff
path: root/buildscripts/cost_model/parameters_extractor.py
blob: 9f02fe771896a74e611d0b5817cc066fb5efd07d (plain)
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
# Copyright (C) 2022-present MongoDB, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the Server Side Public License, version 1,
# as published by MongoDB, Inc.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# Server Side Public License for more details.
#
# You should have received a copy of the Server Side Public License
# along with this program. If not, see
# <http://www.mongodb.com/licensing/server-side-public-license>.
#
# As a special exception, the copyright holders give permission to link the
# code of portions of this program with the OpenSSL library under certain
# conditions as described in each individual source file and distribute
# linked combinations including the program with the OpenSSL library. You
# must comply with the Server Side Public License in all respects for
# all of the code used other than as permitted herein. If you modify file(s)
# with this exception, you may extend this exception to your version of the
# file(s), but you are not obligated to do so. If you do not wish to do so,
# delete this exception statement from your version. If you delete this
# exception statement from all source files in the program, then also delete
# it in the license file.
#
"""Parse explain and extract parameters."""

from __future__ import annotations
from collections import deque, defaultdict
import json
from typing import Mapping, Sequence, TypeVar, Callable
from workload_execution import QueryParameters
from config import AbtCalibratorConfig
from database_instance import DatabaseInstance
from cost_estimator import ModelParameters, ExecutionStats
import execution_tree
import physical_tree

__all__ = ['extract_parameters', 'extract_execution_stats']


async def extract_parameters(config: AbtCalibratorConfig, database: DatabaseInstance,
                             abt_types: Sequence[str]) -> Mapping[str, Sequence[ModelParameters]]:
    """Read measurements from database and extract cost model parameters for the given ABT types."""

    stats = defaultdict(list)

    docs = await database.get_all_documents(config.input_collection_name)
    for result in docs:
        explain = json.loads(result['explain'])
        query_parameters = QueryParameters.from_json(result['query_parameters'])
        res = parse_explain(explain, abt_types)
        for abt_type, stat in res.items():
            stats[abt_type].append(
                ModelParameters(execution_stats=stat, query_params=query_parameters))
        if config.trace and len(res) > 0:
            print(res)
    return stats


Node = TypeVar('Node')


def find_abt_node_by_type(root: physical_tree.Node, abt_type: str) -> physical_tree.Node | Node:
    """Find ABT node by its type."""
    abt_nodes = find_nodes(root, lambda node: node.node_type == abt_type)
    if len(abt_nodes) > 0:
        assert len(abt_nodes) == 1
        return abt_nodes[0]
    return None


def find_nodes(root: Node, predicate: Callable[[Node], bool]) -> list[Node]:
    """Find nodes in the given tree which satisfy the predicate."""

    def impl(node: Node, predicate: Callable[[Node], bool], result: list[Node]) -> Node:
        if predicate(node):
            result.append(node)
        for child in node.children:
            impl(child, predicate, result)

    result: list[Node] = []
    impl(root, predicate, result)
    return result


def get_excution_stats(root: execution_tree.Node, node_id: int) -> ExecutionStats:
    """Extract execution stats from the given Execution Tree for the ABT node defined with the given node_id."""
    queue: deque[execution_tree.Node] = deque()
    queue.append(root)

    execution_time: int = 0
    n_returned: int = root.n_returned
    n_processed: int = 0

    while len(queue) > 0:
        size = len(queue)
        for _ in range(size):
            node = queue.popleft()
            if node.plan_node_id == node_id:
                execution_time += node.get_execution_time()
                n_processed = max(n_processed, node.n_processed)
            for child in node.children:
                queue.append(child)

    return ExecutionStats(execution_time=execution_time, n_returned=n_returned,
                          n_processed=n_processed)


def parse_explain(explain: Mapping[str, any], abt_types: Sequence[str]):
    """Extract ExecutionStats from the given explain for the given ABT types."""

    try:
        et = execution_tree.build_execution_tree(explain['executionStats'])
        pt = physical_tree.build(explain['queryPlanner']['winningPlan']['optimizerPlan'])
    except Exception as exception:
        print(f'*** Failed to parse explain with the followinf error: {exception}')
        print(explain)
        raise exception

    return extract_execution_stats(et, pt, abt_types)


def extract_execution_stats(et: execution_tree.Node, pt: physical_tree.Node,
                            abt_types: Sequence[str]) -> Mapping[str, ExecutionStats]:
    """Extract ExecutionStats from the given SBE and ABT trees for the given ABT types."""

    if len(abt_types) == 0:
        abt_types = get_abt_types(pt)

    result: Mapping[str, ExecutionStats] = {}
    for abt_type in abt_types:
        abt_node = find_abt_node_by_type(pt, abt_type)
        if abt_node is not None:
            execution_stats = get_excution_stats(et, abt_node.plan_node_id)
            result[abt_type] = execution_stats
    return result


def get_abt_types(pt: physical_tree.Node) -> Sequence[str]:
    """Extract types of all ABT nodes in the given ABT."""
    abt_types = set()
    queue: deque[physical_tree.Node] = deque()
    queue.append(pt)

    while len(queue) > 0:
        size = len(queue)
        for _ in range(size):
            node = queue.popleft()
            abt_types.add(node.node_type)
            for child in node.children:
                queue.append(child)
    return abt_types