Algorithm Search⌘K

Algorithmadvanced

AutoAdmin index selection

Also called Chaudhuri-Narasayya index tuning.

Pick indexes for a workload by finding the best ones for each query, then growing a configuration greedily with what-if costs.

Time
O((n^m + k n) q k) worst · averageO(n^m q) best
Space
O(q P) extra
Where
P = the number of admissible indexes; k = the largest number of indexes; m = the size of the exhaustive start; n = the number of candidate indexes; q = the number of statements in the workload
Properties
deterministicnot exactnot externalnot in placeofflineiterative
Origin
Surajit Chaudhuri, Vivek Narasayya, 1997

AutoAdmin index selection is the algorithm of the index tuning tool that Chaudhuri and Narasayya built for Microsoft SQL Server. Given a workload of queries and updates and a limit kk on the number of indexes, it returns a configuration of indexes with a low estimated cost. The index selection problem is NP-hard, so the tool is a heuristic made of three parts. Candidate selection treats each query alone as a workload and keeps the indexes of its best configuration. Configuration enumeration, Greedy(m,k)(m, k), searches all configurations of mm candidates exhaustively and then adds one index at a time. Multi-column index generation builds wider indexes step by step from the narrower ones that were chosen. All costs come from the query optimizer by what-if calls, and atomic configurations let the tool derive most costs without a call.

In plain words

Suppose you can afford three indexes for a database, and you have a list of the queries that people run. Trying every set of three indexes would take far too many questions to the optimizer. So you first ask, for each query alone, "which indexes would help this query most?" Only those indexes stay in the game.

Then you build the set. You try all pairs of the remaining indexes and keep the best pair. You then add the single index that helps the most, as long as it helps at all and the set is not full. Wide indexes on two columns are tried only if their first column was a good index on its own. Each "how much would this cost?" goes to the optimizer as if the indexes existed, and answers that can be worked out from earlier answers are not asked again.

The problem

The input is a workload WW of qq weighted statements, a limit kk on the number of indexes, and an optimizer that, for a statement QQ and a configuration CC of hypothetical indexes, returns the estimated cost opt(Q,C)\mathrm{opt}(Q, C). The goal is a configuration CC with ∣C∣≤k|C| \le k and a small total cost Cost(W,C)=∑QwQ opt(Q,C)\mathrm{Cost}(W, C) = \sum_{Q} w_Q \, \mathrm{opt}(Q, C). Updates are in the workload, so an index can raise the total cost.

Each optimizer call is expensive, so the tool must make few of them. The problem itself, with its NP-hardness and its known bounds, is on the page on index selection. This page is about the AutoAdmin algorithm.

The algorithm

  1. TUNE(W, k, m, width)
  2. 1chosen ← ∅; pool ← ∅
  3. 2for j ← 1 to width do
  4. 3pool ← pool ∪ the admissible indexes of width j ▷ width 1: the indexable columns; width j > 1: MC-LEAD
  5. 4candidates ← chosen; for each statement Q in W do
  6. 5candidates ← candidates ∪ ENUMERATE({Q}, the indexes of pool that Q can use, k, m)
  7. 6chosen ← ENUMERATE(W, candidates ∪ chosen, k, m)
  1. ENUMERATE(W, S, k, m) ▷ Greedy(m, k)
  2. 1C ← the configuration of at most m indexes of S with the least Cost(W, C), by exhaustive search
  3. 2while |C| < k do
  4. 3i ← the index of S \ C with the least Cost(W, C ∪ {i})
  5. 4if Cost(W, C ∪ {i}) ≥ Cost(W, C) then stop
  6. 5C ← C ∪ {i}
  7. 6return C
  1. 1opt(Q, C) ← the least opt(Q, A) over the atomic configurations A ⊆ C, each a cached what-if call
  • Admissible indexes. In the first iteration they are the single-column indexes on the indexable columns, those that appear in the predicates of the workload. In iteration jj, the MC-LEAD rule of the paper forms an index of width jj from a chosen index of width j−1j - 1 by adding one more column of the workload. So (a,d)(a, d) is considered only if (a)(a) was chosen.
  • Candidate selection. A query alone is a workload of one, and the tool runs its own enumeration on it. The indexes of the best configuration for that query become candidates. This prunes the search to indexes that are best for at least one query.
  • Greedy(m,k)(m, k). With m=0m = 0 it is plain greedy, and with m=km = k it is exhaustive search over the candidates. The paper reports: "We found that m=2 produced very good solutions" (a measurement on its workloads).
  • Atomic configurations. An atomic configuration of a query is a set of indexes that one plan of the query can use together. The paper derives the cost of a query in a large configuration as the least cost over its atomic subsets, and limits these subsets (for example, by the number of indexes per table that they may hold) so that few what-if calls are needed. In the optimizer model on this page, a plan uses one index, so the atomic configurations are the single indexes, and the cost of an update is the sum of the maintenance costs of the indexes it changes.

Example

A table TT has 100,000 rows and the columns aa, bb, cc and dd with 1,000, 100, 10 and 50,000 distinct values. A full scan costs 5,000. The workload has three queries and one update, and k=2k = 2, m=2m = 2, width 2:

statement weight the best single index for it cost
Q1Q_1: a=?a = ?, reads dd 50 (a,d)(a, d), covering 8
Q2Q_2: a=?a = ? and b=?b = ? 30 (a,b)(a, b), covering 3.05
Q3Q_3: dd in a range of 0.1%, reads cc 20 (d,c)(d, c), covering 8
UU: update of bb 10 none; 4 more per index that holds bb 1

With no index, the total is 100⋅5000+10=500,010100 \cdot 5000 + 10 = 500{,}010.

  1. Width 1. The admissible indexes are (a)(a), (b)(b) and (d)(d). Alone, Q1Q_1 and Q2Q_2 choose (a)(a) (cost 103 each, since about 100 rows match), and Q3Q_3 chooses (d)(d) (cost 103). The candidates are {(a),(d)}\{(a), (d)\}, and the enumeration chooses both, with a total of 100⋅103+10=10,310100 \cdot 103 + 10 = 10{,}310.
  2. Width 2. MC-LEAD extends (a)(a) to (a,b)(a, b), (a,c)(a, c) and (a,d)(a, d), and (d)(d) to (d,a)(d, a), (d,b)(d, b) and (d,c)(d, c). Alone, Q1Q_1 chooses (a,d)(a, d), Q2Q_2 chooses (a,b)(a, b), and Q3Q_3 chooses (d,c)(d, c). With the earlier choice, the candidates are (a)(a), (d)(d), (a,b)(a, b), (a,d)(a, d) and (d,c)(d, c).
  3. Enumeration. With m=2=km = 2 = k, L7 tries every pair. The best is {(a,d),(d,c)}\{(a, d), (d, c)\}, with 50⋅8+30⋅103+20⋅8+10⋅1=3,66050 \cdot 8 + 30 \cdot 103 + 20 \cdot 8 + 10 \cdot 1 = 3{,}660. The pair {(a,b),(d,c)}\{(a, b), (d, c)\} serves Q2Q_2 almost for free but costs 50⋅10350 \cdot 103 for Q1Q_1 and 5 for each update, a total of 5,451.5.

An exhaustive search over every configuration of at most two indexes of width at most 2 also gives 3,660, so here the tool finds the optimum. It made 21 what-if calls. The search costed 84 distinct pairs of a statement and a configuration, so without atomic configurations it would have needed 84 calls.

Measurement. On 200 random instances with two tables and 3 to 7 statements (seeds 0 to 199, k=3k = 3, m=2m = 2, width 2), the tool found the optimum of the exhaustive search on 94 instances. The median ratio of its cost to the optimum was 1.008, and the worst was 16.6. On average it made 25.6 what-if calls against 168.3 distinct statement and configuration pairs. With m=0m = 0 it found the optimum on 93 instances and with m=3m = 3 on 95.

Correctness

The proofs are in proofs/correctness.md. The main points:

  • Exact costs (theorem). In a model where a plan uses the indexes of one atomic configuration, the cost of a query in any configuration is the least cost over its atomic subsets. So the derived costs equal the optimizer's costs, and the cache changes no value.
  • Bounded calls (theorem). With single-index atomic configurations, the tool makes at most q(P+1)q (P + 1) what-if calls.
  • Greedy(m,k)(m, k) (theorem). The result has at most kk indexes, is at least as good as every configuration of at most mm candidates, and, if it has fewer than kk indexes, no single candidate lowers its cost. With m≥km \ge k it is the optimum over the candidates.
  • No optimality (heuristic). The tool can miss the optimum. An index that is second best for two queries but serves both is never a candidate, and MC-LEAD never forms (e,c)(e, c) if (e)(e) was not chosen. Both cases occur in the measurement above: the worst instance needed (e,c)(e, c) for two queries whose best single indexes were (c)(c) and (b)(b).
Proof: The AutoAdmin tool computes exact what-if costs from atomic configurations and returns a valid configuration that Greedy(m, k) cannot improve by one indexfull

We use the notation of the page and the code. A workload WW is a list of weighted statements QQ, each a select or an update on one table. A configuration CC is a set of indexes. opt(Q,C)\mathrm{opt}(Q, C) is the cost that the optimizer model (WhatIf.optimize) gives to QQ when exactly the indexes of CC exist, and Cost(W,C)=∑Q∈WwQ opt(Q,C)\mathrm{Cost}(W, C) = \sum_{Q \in W} w_Q \, \mathrm{opt}(Q, C). The tool is asked for a configuration of at most kk indexes with a small cost. Finding the minimum is NP-hard (Piatetsky-Shapiro, 1983, and Comer, 1978), so the tool is a heuristic, and what we prove is that its costs are exact and its output is valid and locally best.

Lemma 1 (atomic configurations). For every statement QQ and configuration CC, query_cost(Q, C) equals opt(Q,C)\mathrm{opt}(Q, C).

Proof. For a select, the model costs a full scan and, for each index of CC on the table of QQ that it can use, one plan with that index, and returns the minimum. A plan uses one index, so its cost depends only on that index: opt(Q,{i})\mathrm{opt}(Q, \{i\}) is the minimum of the scan and the plan with ii. Hence opt(Q,C)=min⁡(opt(Q,∅),min⁡i∈Copt(Q,{i}))\mathrm{opt}(Q, C) = \min(\mathrm{opt}(Q, \emptyset), \min_{i \in C} \mathrm{opt}(Q, \{i\})), which is what L13 computes; an index that QQ cannot use gives the scan, so skipping it changes nothing. For an update, the model charges 11 plus a fixed amount for each index on the table that holds a changed column, so opt(Q,C)−1=∑i∈C(opt(Q,{i})−1)\mathrm{opt}(Q, C) - 1 = \sum_{i \in C} (\mathrm{opt}(Q, \{i\}) - 1), which is the sum the code takes. The cache returns the value of an earlier call with the same key, and the model has no state, so the cache does not change any value. □\square

So the atomic configurations of a select in this model are ∅\emptyset and the single indexes, and of an update the single indexes. Lemma 1 is the property that the paper requires of atomic configurations: the cost in any configuration follows from the costs in its atomic subsets without a new optimizer call.

Lemma 2 (number of what-if calls). If PP is the set of all indexes that the tool considers (the final pool), the tool makes at most ∣W∣ (∣P∣+1)|W| \, (|P| + 1) what-if calls.

Proof. Every call has a key (Q,A)(Q, A) with A=∅A = \emptyset or A={i}A = \{i\}, i∈Pi \in P, and each key is computed once. □\square

Without atomic configurations, each pair of a statement and a configuration that the search costs needs its own call. The tests check that this number (len(tool.pairs)) is more than three times the number of calls.

Lemma 3 (Greedy(m, k)). Let SS be a set of candidates and GG the result of enumerate(W, S, k). Then:

  1. G⊆SG \subseteq S and ∣G∣≤k|G| \le k.
  2. Cost(W,G)≤Cost(W,D)\mathrm{Cost}(W, G) \le \mathrm{Cost}(W, D) for every D⊆SD \subseteq S with ∣D∣≤min⁡(m,k)|D| \le \min(m, k), and in particular for D=∅D = \emptyset.
  3. If ∣G∣<k|G| < k, no single index of S∖GS \setminus G lowers the cost: Cost(W,G∪{i})≥Cost(W,G)\mathrm{Cost}(W, G \cup \{i\}) \ge \mathrm{Cost}(W, G) for all i∈S∖Gi \in S \setminus G.
  4. If m≥km \ge k, GG has the least cost among all subsets of SS with at most kk indexes.

Proof. L7 tries every subset of SS of size at most min⁡(m,k)\min(m, k) and keeps one of least cost, starting from ∅\emptyset; this gives (2) for the start. Each step of L8 to L11 adds one index of SS and is taken only if it lowers the cost strictly, so the cost never rises, which keeps (2), and the size grows by one up to kk, which gives (1). The loop ends at size kk, or when L10 finds no index that lowers the cost, which is (3). If m≥km \ge k, L7 is already the exhaustive search over all subsets of size at most kk, and the loop cannot improve it without exceeding kk, which is (4). The loop runs at most kk times, so the procedure ends. □\square

Theorem 1 (the tool). run ends and returns a configuration of at most kk indexes, each in the pool of admissible indexes, whose cost is at most the cost with no index, and to which no single candidate can be added with a lower cost if it has fewer than kk indexes. Each candidate is an index of the best configuration that Greedy(m, k) finds for some single statement, or an index chosen in an earlier iteration.

Proof. There are width iterations. In each, the per-statement calls at L5 and the workload call at L6 are calls of enumerate, which end by Lemma 3. The candidates are the union of their results and of the earlier choice, so they lie in the pool. The final configuration is the result of L6 in the last iteration, so Lemma 3, parts (1) to (3), gives the claims, and Lemma 1 shows that the costs it compares are the optimizer's costs. □\square

What the tool does not guarantee. The output need not be optimal, even among the indexes of the pool. Two ways it can miss are shown by the tests' search over random instances:

  • Candidate selection. An index that is second best for each of two statements, but serves both, is not the best for either alone, so L5 does not make it a candidate.
  • Multi-column indexes. MC-LEAD forms an index of width jj only from a chosen index of width j−1j - 1. If no index on the leading column was chosen, no wider index with that leading column is formed.

The tests compare the tool with an exhaustive search over all configurations of at most kk indexes from all admissible indexes, and check that the tool is never better than the optimum (a check of the search and the costs), never worse than no index, and finds the optimum on at least 15 of 40 random instances. They also check Lemma 1 against the optimizer model on random configurations, part (4) of Lemma 3, and that more steps of the greedy loop never raise the cost.

Complexity

  • Enumeration. L7 costs ∑r≤m(nr)=O(nm)\sum_{r \le m} \binom{n}{r} = O(n^m) configurations, and the loop at most knk n more. Each configuration is costed over qq statements, with up to kk cached look-ups each.
  • Candidate selection runs the enumeration once per statement, on the few indexes that the statement can use.
  • What-if calls are the real cost, since each is an optimizer call. They are at most q(P+1)q (P + 1) with single-index atomic configurations, and the paper's limits on atomic configurations keep them small in general.
  • Space. The cache of what-if costs, O(qP)O(q P) entries.

Properties

  • Deterministic. Ties are broken by a fixed order of the indexes.
  • Not exact. It is a heuristic for an NP-hard problem; its results are at least as good as no index and locally best for one added index.
  • Optimizer-driven. It uses the optimizer's own cost estimates, so it chooses indexes that the optimizer will in fact use. Errors in the estimates become errors in the choice.
  • Offline. It needs the workload in advance, as a trace or a sample.

Variants and improvements

  • Database Engine Tuning Advisor. The successor tool in later versions of SQL Server also chooses materialized views and partitionings, with the same candidate selection and enumeration ideas (view selection).
  • Space limit. A limit on storage instead of on the number of indexes; the greedy step then compares benefit per unit of space, as on the index selection page.
  • Workload compression. Large traces are reduced to a sample of representative statements before tuning.
  • Integer programming. Later tools solve the enumeration exactly over the candidates, with the same what-if costs.

When to use it

Use this approach to recommend indexes for a known workload, when the optimizer can cost hypothetical indexes and when the number of indexable columns is too large for exhaustive search. It is the pattern of most commercial and open-source index advisors. If the workload is not known in advance, adaptive methods such as database cracking build indexes as queries arrive. If the workload is small, an exhaustive search or an integer program over the candidates is affordable and exact.

Pitfalls

  • Pruned candidates. Candidate selection keeps only the best indexes of each query. A shared index that is second best for many queries is lost. Widening the per-query search to the best few configurations reduces this.
  • The leading column. MC-LEAD builds wide indexes only on chosen narrow ones. If the useful leading column was not chosen at width 1, the wide index is never tried.
  • Bad estimates. The tool trusts the optimizer's cardinality estimates. If they are wrong, it can choose indexes that are useless at run time. Check a recommendation on real runs.
  • Updates. A workload without its updates makes every index look free. Include the inserts, updates and deletes, with their real weights.
  • Many what-if calls. Without atomic configurations and a cache, the number of optimizer calls grows with the number of configurations, not with the number of indexes, and the tool becomes too slow.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

autoadmin_index_selection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/autoadmin-index-selection/. The authors are listed in prov/Q7Z4FQ.jsonl.

"""The index selection tool of Chaudhuri and Narasayya (VLDB 1997).

The tool has three parts:

1. Candidate selection: each query alone is a workload of one, and the
   indexes of its best configuration become candidates.
2. Configuration enumeration, Greedy(m, k): the best configuration of m
   indexes by exhaustive search, then one index at a time while the cost
   falls, up to k indexes.
3. Multi-column indexes, built up by width: the indexes of width j are the
   chosen indexes of width j - 1 with one more column (the MC-LEAD rule).

Costs come from a what-if function, which stands in for the query optimizer
with hypothetical indexes. The optimizer model on this page uses at most one
index per query, so the atomic configurations of a query are the single
indexes, and the cost of a query in any configuration is the minimum over
them. Each distinct (query, atomic configuration) pair costs one what-if call.
"""

from dataclasses import dataclass, field
from itertools import combinations
from typing import Dict, FrozenSet, Iterable, List, Optional, Sequence, Set, Tuple

ROWS_PER_PAGE = 20

Index = Tuple[str, Tuple[str, ...]]          # (table, columns in key order)


@dataclass(frozen=True)
class Table:
    name: str
    rows: int
    distinct: Tuple[Tuple[str, int], ...]   # (column, number of distinct values)

    def ndv(self, col: str) -> int:
        return dict(self.distinct)[col]


@dataclass(frozen=True)
class Select:
    weight: float
    table: str
    eq: Tuple[str, ...] = ()                 # columns with an equality predicate
    rng: Optional[str] = None                # column with a range predicate
    rng_sel: float = 1.0
    out: Tuple[str, ...] = ()                # other columns the query reads

    def indexable(self) -> Set[str]:
        return set(self.eq) | ({self.rng} if self.rng else set())

    def needed(self) -> Set[str]:
        return self.indexable() | set(self.out)


@dataclass(frozen=True)
class Update:
    weight: float
    table: str
    cols: Tuple[str, ...]                    # the columns it changes


class WhatIf:
    """A toy optimizer that costs a query under hypothetical indexes."""

    def __init__(self, tables: Iterable[Table], maint: float = 4.0):
        self.tables: Dict[str, Table] = {t.name: t for t in tables}
        self.maint = maint
        self.calls = 0
        self.cache: Dict[Tuple[object, FrozenSet[Index]], float] = {}

    def index_cost(self, q: Select, ix: Index) -> Optional[float]:
        """The cost of the plan for q that uses ix, or None if ix is of no use."""
        t = self.tables[q.table]
        table, cols = ix
        if table != q.table:
            return None
        sel, used, pos = 1.0, 0, 0
        while pos < len(cols) and cols[pos] in q.eq:
            sel /= t.ndv(cols[pos])
            used, pos = used + 1, pos + 1
        if pos < len(cols) and cols[pos] == q.rng:
            sel *= q.rng_sel
            used += 1
        if used == 0:
            return None
        rows = sel * t.rows
        covering = q.needed() <= set(cols)
        return 3.0 + rows * (1.0 / ROWS_PER_PAGE if covering else 1.0)

    def optimize(self, q, config: FrozenSet[Index]) -> float:
        """The optimizer's cost for q with exactly the indexes in config."""
        t = self.tables[q.table]
        if isinstance(q, Update):
            touched = [ix for ix in config if ix[0] == q.table and set(ix[1]) & set(q.cols)]
            return 1.0 + self.maint * len(touched)
        best = t.rows / ROWS_PER_PAGE                    # a full scan
        for ix in config:
            c = self.index_cost(q, ix)
            if c is not None and c < best:
                best = c
        return best

    def call(self, q, config: FrozenSet[Index]) -> float:
        """A what-if call, with a cache, as the tool makes it."""
        key = (q, config)
        if key not in self.cache:
            self.calls += 1
            self.cache[key] = self.optimize(q, config)
        return self.cache[key]


class Tool:
    def __init__(self, whatif: WhatIf, workload: Sequence, k: int, m: int = 2, width: int = 2):
        self.w = whatif
        self.workload = list(workload)
        self.k, self.m, self.width = k, m, width
        self.pairs: Set[Tuple[object, FrozenSet[Index]]] = set()   # (query, configuration) pairs costed

    # ----- costs from atomic configurations -----

    def query_cost(self, q, config: FrozenSet[Index]) -> float:
        if isinstance(q, Update):                       # maintenance adds up per index
            return 1.0 + sum(self.w.call(q, frozenset([ix])) - 1.0 for ix in config
                             if ix[0] == q.table)
        best = self.w.call(q, frozenset())              # @line L13
        for ix in config:
            if ix[0] == q.table and self.w.index_cost(q, ix) is not None:
                best = min(best, self.w.call(q, frozenset([ix])))   # @line L13
        return best

    def cost(self, workload: Sequence, config: Iterable[Index]) -> float:
        c = frozenset(config)
        self.pairs.update((q, c) for q in workload)
        return sum(q.weight * self.query_cost(q, c) for q in workload)

    # ----- Greedy(m, k) -----

    def enumerate(self, workload: Sequence, cands: Iterable[Index], k: int) -> FrozenSet[Index]:
        cands = sorted(set(cands))
        best, best_cost = frozenset(), self.cost(workload, ())
        for r in range(1, min(self.m, k) + 1):                       # @line L7
            for s in combinations(cands, r):
                c = self.cost(workload, s)
                if c < best_cost:
                    best, best_cost = frozenset(s), c
        while len(best) < k:                                         # @line L8
            step, step_cost = None, best_cost
            for ix in cands:                                         # @line L9
                if ix not in best:
                    c = self.cost(workload, best | {ix})
                    if c < step_cost:
                        step, step_cost = ix, c
            if step is None:                                         # @line L10
                break
            best, best_cost = best | {step}, step_cost               # @line L11
        return best                                                  # @line L12

    # ----- candidate selection and multi-column indexes -----

    def indexable_columns(self, table: str, lead: bool) -> Set[str]:
        out: Set[str] = set()
        for q in self.workload:
            if isinstance(q, Select) and q.table == table:
                out |= q.indexable() if lead else q.needed()
        return out

    def admissible(self, j: int, chosen: Iterable[Index]) -> Set[Index]:
        if j == 1:
            return {(t, (c,)) for t in self.w.tables for c in self.indexable_columns(t, True)}
        out = set()
        for t, cols in chosen:                                       # MC-LEAD
            if len(cols) == j - 1:
                for c in self.indexable_columns(t, False):
                    if c not in cols:
                        out.add((t, cols + (c,)))
        return out

    def relevant(self, q, indexes: Iterable[Index]) -> List[Index]:
        if not isinstance(q, Select):
            return []
        return [ix for ix in indexes if self.w.index_cost(q, ix) is not None]

    def run(self) -> FrozenSet[Index]:
        chosen: FrozenSet[Index] = frozenset()                       # @line L1
        pool: Set[Index] = set()
        self.trace = []
        for j in range(1, self.width + 1):                           # @line L2
            pool |= self.admissible(j, chosen)                       # @line L3
            cands: Set[Index] = set(chosen)
            for q in self.workload:                                  # @line L4
                cands |= self.enumerate([q], self.relevant(q, pool), self.k)   # @line L5
            chosen = self.enumerate(self.workload, cands, self.k)    # @line L6
            self.trace.append((j, sorted(cands), sorted(chosen)))
        return chosen


def all_indexes(tool: Tool) -> List[Index]:
    """Every index of width at most tool.width that some select query can use."""
    out = set()
    for t in tool.w.tables:
        lead = tool.indexable_columns(t, True)
        cols = sorted(tool.indexable_columns(t, False))
        for c in lead:
            out.add((t, (c,)))
        for wdt in range(2, tool.width + 1):
            for ix in list(out):
                if ix[0] == t and len(ix[1]) == wdt - 1:
                    for c in cols:
                        if c not in ix[1]:
                            out.add((t, ix[1] + (c,)))
    return sorted(out)


def brute_force(tool: Tool) -> Tuple[float, FrozenSet[Index]]:
    """The optimum over all configurations of at most k indexes."""
    idx = all_indexes(tool)
    best, best_cost = frozenset(), tool.cost(tool.workload, ())
    for r in range(1, tool.k + 1):
        for s in combinations(idx, r):
            c = tool.cost(tool.workload, s)
            if c < best_cost - 1e-9:
                best, best_cost = frozenset(s), c
    return best_cost, best
test_autoadmin_index_selection.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/autoadmin-index-selection/. The authors are listed in prov/Q7Z4FQ.jsonl.

import random
import unittest
from itertools import combinations

from autoadmin_index_selection import (Select, Table, Tool, Update, WhatIf,
                                       all_indexes, brute_force)


def page_example():
    t = Table("T", 100000, (("a", 1000), ("b", 100), ("c", 10), ("d", 50000)))
    w = [Select(50, "T", eq=("a",), out=("d",)),
         Select(30, "T", eq=("a", "b")),
         Select(20, "T", rng="d", rng_sel=0.001, out=("c",)),
         Update(10, "T", ("b",))]
    return [t], w


def random_instance(rng):
    cols = ["a", "b", "c", "d", "e"]
    t = Table("T", 100000, tuple((c, rng.choice([2, 10, 100, 1000, 50000])) for c in cols))
    s = Table("S", 20000, tuple((c, rng.choice([2, 10, 100, 1000])) for c in ["x", "y", "z"]))
    w = []
    for _ in range(rng.randrange(3, 7)):
        tab, cs = (t, cols) if rng.random() < 0.7 else (s, ["x", "y", "z"])
        eq = tuple(rng.sample(cs, rng.randrange(0, 3)))
        rest = [c for c in cs if c not in eq]
        rc = rng.choice(rest) if (rng.random() < 0.5 or not eq) else None
        pool = [c for c in rest if c != rc]
        out = tuple(rng.sample(pool, min(len(pool), rng.randrange(0, 2))))
        w.append(Select(rng.randrange(1, 50), tab.name, eq, rc, rng.choice([0.001, 0.01, 0.1]), out))
    for _ in range(rng.randrange(0, 2)):
        w.append(Update(rng.randrange(1, 200), "T", tuple(rng.sample(cols, 1))))
    return [t, s], w


class TestExample(unittest.TestCase):
    def test_page_example(self):
        tabs, w = page_example()
        wi = WhatIf(tabs)
        tool = Tool(wi, w, k=2, m=2, width=2)
        chosen = tool.run()
        self.assertEqual(tool.trace[0][2], [("T", ("a",)), ("T", ("d",))])
        self.assertEqual(tool.trace[1][1], [("T", ("a",)), ("T", ("a", "b")), ("T", ("a", "d")),
                                            ("T", ("d",)), ("T", ("d", "c"))])
        self.assertEqual(sorted(chosen), [("T", ("a", "d")), ("T", ("d", "c"))])
        self.assertEqual(tool.cost(w, ()), 50 * 5000 + 30 * 5000 + 20 * 5000 + 10)
        self.assertEqual(tool.cost(w, [("T", ("a",)), ("T", ("d",))]), 10310)
        self.assertEqual(tool.cost(w, chosen), 3660)
        self.assertEqual(tool.cost(w, [("T", ("a", "b")), ("T", ("d", "c"))]), 5451.5)
        self.assertEqual(wi.calls, 21)
        self.assertEqual(len(tool.pairs), 84)
        self.assertEqual(brute_force(Tool(WhatIf(tabs), w, k=2))[0], 3660)


class TestParts(unittest.TestCase):
    def test_atomic_configurations_give_the_optimizer_cost(self):
        """cost(Q, C) from single-index what-if calls equals the optimizer on all of C."""
        rng = random.Random(1)
        for seed in range(40):
            tabs, w = random_instance(random.Random(seed))
            wi = WhatIf(tabs)
            tool = Tool(wi, w, k=3)
            idx = all_indexes(tool)
            for _ in range(20):
                c = frozenset(rng.sample(idx, min(len(idx), rng.randrange(0, 5))))
                for q in w:
                    self.assertAlmostEqual(tool.query_cost(q, c), wi.optimize(q, c))

    def test_greedy_with_m_at_least_k_is_exhaustive(self):
        for seed in range(25):
            tabs, w = random_instance(random.Random(seed))
            tool = Tool(WhatIf(tabs), w, k=2, m=2)
            cands = all_indexes(tool)
            got = tool.cost(w, tool.enumerate(w, cands, 2))
            best = min(tool.cost(w, s) for r in range(3) for s in combinations(cands, r))
            self.assertAlmostEqual(got, best)

    def test_greedy_steps_only_lower_the_cost(self):
        for seed in range(25):
            tabs, w = random_instance(random.Random(seed))
            tool = Tool(WhatIf(tabs), w, k=4, m=1)
            cands = all_indexes(tool)
            prev = tool.cost(w, ())
            for k in range(1, 5):
                c = tool.cost(w, tool.enumerate(w, cands, k))
                self.assertLessEqual(c, prev + 1e-9)
                prev = c
            self.assertLessEqual(len(tool.enumerate(w, cands, 4)), 4)

    def test_mc_lead_extends_chosen_indexes(self):
        tabs, w = page_example()
        tool = Tool(WhatIf(tabs), w, k=2)
        ext = tool.admissible(2, [("T", ("a",))])
        self.assertEqual(sorted(ext), [("T", ("a", "b")), ("T", ("a", "c")), ("T", ("a", "d"))])


class TestAgainstBruteForce(unittest.TestCase):
    def test_tool_against_the_optimum(self):
        found, ratios = 0, []
        calls = pairs = 0
        for seed in range(40):
            tabs, w = random_instance(random.Random(seed))
            wi = WhatIf(tabs)
            tool = Tool(wi, w, k=3, m=2, width=2)
            chosen = tool.run()
            self.assertLessEqual(len(chosen), 3)
            got = tool.cost(w, chosen)
            best, _ = brute_force(Tool(WhatIf(tabs), w, k=3, width=2))
            self.assertGreaterEqual(got, best - 1e-6)            # never better than the optimum
            self.assertLessEqual(got, tool.cost(w, ()) + 1e-9)   # never worse than no index
            found += abs(got - best) < 1e-6
            ratios.append(got / best)
            calls += wi.calls
            pairs += len(tool.pairs)
        self.assertGreaterEqual(found, 15)       # a heuristic: it often, not always, finds the optimum
        self.assertLess(calls * 3, pairs)        # atomic configurations save what-if calls


if __name__ == "__main__":
    unittest.main()

History

Surajit Chaudhuri and Vivek Narasayya of the AutoAdmin project at Microsoft Research presented the tool at VLDB 1997, and it shipped as the Index Tuning Wizard of SQL Server 7.0. Their SIGMOD 1998 paper described the what-if interface that lets the optimizer cost indexes that do not exist. Earlier work had shown that optimal index selection is NP-complete (Comer, 1978; Piatetsky-Shapiro, 1983), and had often used cost models apart from the optimizer. The AutoAdmin tool made the optimizer itself the cost model, which most later index advisors do too.

References

  1. Surajit Chaudhuri and Vivek Narasayya, An efficient, cost-driven index selection tool for Microsoft SQL Server, Proceedings of the 23rd International Conference on Very Large Data Bases (VLDB 1997), pp. 146 to 155: Section 3 (atomic configurations and the reduction of optimizer calls), Section 4 (candidate index selection per query), Section 5 (the Greedy(m, k) enumeration), Section 6 (multi-column indexes and MC-LEAD), Section 7 (experiments with SQL Server 7.0)
  2. Surajit Chaudhuri and Vivek Narasayya, AutoAdmin what-if index analysis utility, Proceedings of ACM SIGMOD 1998, pp. 367 to 378, the hypothetical indexes and the optimizer interface that the tool uses for its costs
  3. Gregory Piatetsky-Shapiro, The optimal selection of secondary indices is NP-complete, ACM SIGMOD Record 13(2) (1983), pp. 72 to 75, the NP-completeness of optimal index selection

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example