view mercurial/destutil.py @ 39506:b66ea3fc3a86

sparse-revlog: set max delta chain length to on thousand The new snapshot system used in the sparse-revlog case gave us some small size benefit so far. However its most important property is to gracefully handle harder limit on delta chainlength. Long delta chain has a very detrimental impact on read (and write) performance in revlog. Being able to shorter them provide a great boost. However, shorting delta used to result significantly lower compression ratio. The intermediate snapshots effectively suppress most of this effect (even all in some case). # Effect on the test repository The repository we use for test is not "realistic" but can still show this in action using an unreasonably low chain limit. Limiting the chain length show a sizeable increase but stay under control: +6% for limit=15; +15% for limit=10. Without the snapshot system the increase is significantly bigger: +45% for limit=15; +80% for limit=10. Even slightly larger than without delta chain limit, the resulting size is still smaller than before we started doing snapshots. Here is a table for comparison. *Since the repository is not branchy, the initial sparse-revlog version does not bring much benefit compare to the non-sparse one): chain length limit | none | limit=15 | limit=10 | without sparse-revlog | 62 818 987 | 112 664 615 | 131 222 574 | without snapshot | 74 365 490 | 108 211 410 | 133 857 764 | with snapshot | 59 230 936 | 63 002 924 | 68 415 329 | # Effect On Real Life Repositories The series provides significant benefits on all kind of repositories. Using `hg debugupgraderepo -o redeltaparent --run`, we recomputed delta chain for various repositories with different settings: - delta chain length: unlimited or 1000 limit - sparse-revlog: enabled or disabled - this series: applied or not applied We can observe multiple types of effect: - On very branchy repositories: * The delta chain limit as low impact on the repo size. * Intermediate snapshot greatly reduces manifest size: - pypy: -80% - netbeans: -95% * The delta chain limit is effective, without a size impact: - netbeans average: 613 -> 282 - private #1 average: 1 068 -> 307 - On more linear repository: * Intermediate snapshot limit the impact of delta chain limit: - mozilla: without the series: +360% with the series: +25% * The delta chain limit provides large improvement: - mozilla's average chain length: unlimited: 15 338 limited: 469 * Despite the chain length limit, the manifest size is reduced: - mercurial: -25% - mozilla: -30% It is clear that the use of chains of intermediate snapshots provide large benefits both in storage size and delta chains quality. We should now switch our effort toward making sure the write performance are acceptable. Then, `sparse-revlog` will be a suitable format for all new repository. # Raw Statistic * no-sparse: general delta repository not using sparse-revlog * no-snapshot: sparse-revlog repository not using this series * snapshot: sparse-revlog repository using this series mercurial Manifest Size: limit | none | 1000 ------------|-------------|------------ no-sparse | 8 021 373 | 8 199 366 no-snapshot | 8 103 561 | 8 259 719 snapshot | 6 137 116 | 6 126 433 Manifest Chain length data limit || none || 1000 || value || average | max || average | max || ------------||---------|---------||---------|---------|| no-sparse || 307 | 1456 || 279 | 1000 || no-snapshot || 312 | 1456 || 283 | 1000 || snapshot || 248 | 1208 || 241 | 1000 || Full Store Size limit | none | 1000 ------------|-------------|------------ no-sparse | 51 013 198 | 51 201 574 no-snapshot | 50 930 795 | 51 141 006 snapshot | 48 072 037 | 48 093 572 pypy Manifest Size: limit | none | 1000 ------------|-------------|------------ no-sparse | 193 987 784 | 193 987 784 no-snapshot | 163 171 745 | 163 312 229 snapshot | 34 605 900 | 34 600 750 Manifest Chain length data limit || none || 1000 || value || average | max || average | max || ------------||---------|---------||---------|---------|| no-sparse || 101 | 692 || 101 | 692 || no-snapshot || 151 | 1307 || 148 | 1000 || snapshot || 128 | 1309 || 125 | 1000 || Full Store Size limit | none | 1000 ------------|-------------|------------ no-sparse | 495 931 473 | 495 931 473 no-snapshot | 465 441 017 | 465 581 501 snapshot | 355 467 301 | 355 472 451 Mozilla Manifest Size: limit | none | 1000 ------------|----------------|--------------- no-sparse | 416 757 148 | 1 869 009 668 no-snapshot | 401 592 370 | 1 843 493 795 snapshot | 224 359 521 | 284 615 500 Manifest Chain length data limit || none || 1000 || value || average | max || average | max || ------------||---------|---------||---------|---------|| no-sparse || 15 333 | 58 980 || 468 | 1 000 || no-snapshot || 15 336 | 58 980 || 469 | 1 000 || snapshot || 15 338 | 58 983 || 469 | 1 000 || Full Store Size limit | none | 1000 ------------|----------------|--------------- no-sparse | 2 712 477 887 | 4 164 995 451 no-snapshot | 2 698 887 835 | 4 141 054 304 snapshot | 2 518 130 385 | 2 578 587 596 Netbeans Manifest Size: limit | none | 1000 ------------|----------------|--------------- no-sparse | 4 766 794 101 | 4 870 642 687 no-snapshot | 4 334 806 082 | 4 428 681 309 snapshot | 232 659 666 | 240 330 665 Manifest Chain length data limit || none || 1000 || value || average | max || average | max || ------------||---------|---------||---------|---------|| no-sparse || 597 | 6802 || 254 | 1 000 || no-snapshot || 648 | 6 802 || 305 | 1 000 || snapshot || 613 | 6 804 || 282 | 1 000 || Full Store Size limit | none | 1000 ------------|----------------|--------------- no-sparse | 5 807 347 998 | 5 911 196 584 no-snapshot | 5 375 398 602 | 5 469 273 829 snapshot | 1 282 519 928 | 1 290 190 927 Private repo #1 Manifest Size: limit | none | 1000 ------------|-----------------|--------------- no-sparse | 41 389 010 840 | 41 398 162 091 no-snapshot | 9 737 319 435 | 10 223 773 150 snapshot | 744 215 807 | 747 961 822 Manifest Chain length data limit || none || 1000 || value || average | max || average | max || ------------||---------|---------||---------|---------|| no-sparse || 245 | 8 885 || 81 | 1 000 || no-snapshot || 1 225 | 8 885 || 336 | 1 000 || snapshot || 1 068 | 7 909 || 307 | 1 000 || Full Store Size limit | none | 1000 ------------|----------------|--------------- no-sparse | 49 646 065 126 | 49 655 216 377 no-snapshot | 17 924 862 856 | 18 411 316 571 snapshot | 9 009 024 710 | 9 012 770 725 Private repo #2 We currently have less data available for that repository. * Before is a sparse-revlog repository without this series * After is a sparse-revlog repository with this series + 1000 chain limit Manifest Size: Before: 1 531 485 040 bytes After: 1 091 422 451 bytes Manifest Chain: Before: 2 218 avg; 6 575 Max After: 442 avg; 1 000 Max Full Store Size Before: 15 203 955 615 after: 8 207 180 693
author Boris Feld <boris.feld@octobus.net>
date Fri, 07 Sep 2018 11:18:45 -0400
parents 92213f6745ed
children fbd168455b26
line wrap: on
line source

# destutil.py - Mercurial utility function for command destination
#
#  Copyright Matt Mackall <mpm@selenic.com> and other
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.

from __future__ import absolute_import

from .i18n import _
from . import (
    bookmarks,
    error,
    obsutil,
    scmutil,
    stack
)

def orphanpossibledestination(repo, rev):
    """Return all changesets that may be a new parent for orphan `rev`.

    This function works fine on non-orphan revisions, it's just silly
    because there's no destination implied by obsolete markers, so
    it'll return nothing.
    """
    tonode = repo.changelog.node
    parents = repo.changelog.parentrevs
    torev = repo.changelog.rev
    dest = set()
    tovisit = list(parents(rev))
    while tovisit:
        r = tovisit.pop()
        succsets = obsutil.successorssets(repo, tonode(r))
        if not succsets:
            # if there are no successors for r, r was probably pruned
            # and we should walk up to r's parents to try and find
            # some successors.
            tovisit.extend(parents(r))
        else:
            # We should probably pick only one destination from split
            # (case where '1 < len(ss)'), This could be the currently
            # tipmost, but the correct result is less clear when
            # results of the split have been moved such that they
            # reside on multiple branches.
            for ss in succsets:
                for n in ss:
                    dr = torev(n)
                    if dr != -1:
                        dest.add(dr)
    return dest

def _destupdateobs(repo, clean):
    """decide of an update destination from obsolescence markers"""
    node = None
    wc = repo[None]
    p1 = wc.p1()
    movemark = None

    if p1.obsolete() and not p1.children():
        # allow updating to successors
        successors = obsutil.successorssets(repo, p1.node())

        # behavior of certain cases is as follows,
        #
        # divergent changesets: update to highest rev, similar to what
        #     is currently done when there are more than one head
        #     (i.e. 'tip')
        #
        # replaced changesets: same as divergent except we know there
        # is no conflict
        #
        # pruned changeset: no update is done; though, we could
        #     consider updating to the first non-obsolete parent,
        #     similar to what is current done for 'hg prune'

        if successors:
            # flatten the list here handles both divergent (len > 1)
            # and the usual case (len = 1)
            successors = [n for sub in successors for n in sub]

            # get the max revision for the given successors set,
            # i.e. the 'tip' of a set
            node = repo.revs('max(%ln)', successors).first()
            if bookmarks.isactivewdirparent(repo):
                movemark = repo['.'].node()
    return node, movemark, None

def _destupdatebook(repo, clean):
    """decide on an update destination from active bookmark"""
    # we also move the active bookmark, if any
    node = None
    activemark, movemark = bookmarks.calculateupdate(repo.ui, repo)
    if activemark is not None:
        node = repo._bookmarks[activemark]
    return node, movemark, activemark

def _destupdatebranch(repo, clean):
    """decide on an update destination from current branch

    This ignores closed branch heads.
    """
    wc = repo[None]
    movemark = node = None
    currentbranch = wc.branch()

    if clean:
        currentbranch = repo['.'].branch()

    if currentbranch in repo.branchmap():
        heads = repo.branchheads(currentbranch)
        if heads:
            node = repo.revs('max(.::(%ln))', heads).first()
        if bookmarks.isactivewdirparent(repo):
            movemark = repo['.'].node()
    elif currentbranch == 'default' and not wc.p1():
        # "null" parent belongs to "default" branch, but it doesn't exist, so
        # update to the tipmost non-closed branch head
        node = repo.revs('max(head() and not closed())').first()
    else:
        node = repo['.'].node()
    return node, movemark, None

def _destupdatebranchfallback(repo, clean):
    """decide on an update destination from closed heads in current branch"""
    wc = repo[None]
    currentbranch = wc.branch()
    movemark = None
    if currentbranch in repo.branchmap():
        # here, all descendant branch heads are closed
        heads = repo.branchheads(currentbranch, closed=True)
        assert heads, "any branch has at least one head"
        node = repo.revs('max(.::(%ln))', heads).first()
        assert node is not None, ("any revision has at least "
                                  "one descendant branch head")
        if bookmarks.isactivewdirparent(repo):
            movemark = repo['.'].node()
    else:
        # here, no "default" branch, and all branches are closed
        node = repo.lookup('tip')
        assert node is not None, "'tip' exists even in empty repository"
    return node, movemark, None

# order in which each step should be evaluated
# steps are run until one finds a destination
destupdatesteps = ['evolution', 'bookmark', 'branch', 'branchfallback']
# mapping to ease extension overriding steps.
destupdatestepmap = {'evolution': _destupdateobs,
                     'bookmark': _destupdatebook,
                     'branch': _destupdatebranch,
                     'branchfallback': _destupdatebranchfallback,
                     }

def destupdate(repo, clean=False):
    """destination for bare update operation

    return (rev, movemark, activemark)

    - rev: the revision to update to,
    - movemark: node to move the active bookmark from
                (cf bookmark.calculate update),
    - activemark: a bookmark to activate at the end of the update.
    """
    node = movemark = activemark = None

    for step in destupdatesteps:
        node, movemark, activemark = destupdatestepmap[step](repo, clean)
        if node is not None:
            break
    rev = repo[node].rev()

    return rev, movemark, activemark

msgdestmerge = {
    # too many matching divergent bookmark
    'toomanybookmarks':
        {'merge':
            (_("multiple matching bookmarks to merge -"
               " please merge with an explicit rev or bookmark"),
             _("run 'hg heads' to see all heads")),
         'rebase':
            (_("multiple matching bookmarks to rebase -"
               " please rebase to an explicit rev or bookmark"),
             _("run 'hg heads' to see all heads")),
        },
    # no other matching divergent bookmark
    'nootherbookmarks':
        {'merge':
            (_("no matching bookmark to merge - "
               "please merge with an explicit rev or bookmark"),
             _("run 'hg heads' to see all heads")),
         'rebase':
            (_("no matching bookmark to rebase - "
               "please rebase to an explicit rev or bookmark"),
             _("run 'hg heads' to see all heads")),
        },
    # branch have too many unbookmarked heads, no obvious destination
    'toomanyheads':
        {'merge':
            (_("branch '%s' has %d heads - please merge with an explicit rev"),
             _("run 'hg heads .' to see heads")),
         'rebase':
            (_("branch '%s' has %d heads - please rebase to an explicit rev"),
             _("run 'hg heads .' to see heads")),
        },
    # branch have no other unbookmarked heads
    'bookmarkedheads':
        {'merge':
            (_("heads are bookmarked - please merge with an explicit rev"),
             _("run 'hg heads' to see all heads")),
         'rebase':
            (_("heads are bookmarked - please rebase to an explicit rev"),
             _("run 'hg heads' to see all heads")),
        },
    # branch have just a single heads, but there is other branches
    'nootherbranchheads':
        {'merge':
            (_("branch '%s' has one head - please merge with an explicit rev"),
             _("run 'hg heads' to see all heads")),
         'rebase':
            (_("branch '%s' has one head - please rebase to an explicit rev"),
             _("run 'hg heads' to see all heads")),
        },
    # repository have a single head
    'nootherheads':
        {'merge':
            (_('nothing to merge'),
            None),
         'rebase':
            (_('nothing to rebase'),
            None),
        },
    # repository have a single head and we are not on it
    'nootherheadsbehind':
        {'merge':
            (_('nothing to merge'),
             _("use 'hg update' instead")),
         'rebase':
            (_('nothing to rebase'),
             _("use 'hg update' instead")),
        },
    # We are not on a head
    'notatheads':
        {'merge':
            (_('working directory not at a head revision'),
             _("use 'hg update' or merge with an explicit revision")),
         'rebase':
            (_('working directory not at a head revision'),
             _("use 'hg update' or rebase to an explicit revision"))
        },
    'emptysourceset':
        {'merge':
            (_('source set is empty'),
             None),
         'rebase':
            (_('source set is empty'),
             None),
        },
    'multiplebranchessourceset':
        {'merge':
            (_('source set is rooted in multiple branches'),
             None),
         'rebase':
            (_('rebaseset is rooted in multiple named branches'),
             _('specify an explicit destination with --dest')),
        },
    }

def _destmergebook(repo, action='merge', sourceset=None, destspace=None):
    """find merge destination in the active bookmark case"""
    node = None
    bmheads = bookmarks.headsforactive(repo)
    curhead = repo._bookmarks[repo._activebookmark]
    if len(bmheads) == 2:
        if curhead == bmheads[0]:
            node = bmheads[1]
        else:
            node = bmheads[0]
    elif len(bmheads) > 2:
        msg, hint = msgdestmerge['toomanybookmarks'][action]
        raise error.ManyMergeDestAbort(msg, hint=hint)
    elif len(bmheads) <= 1:
        msg, hint = msgdestmerge['nootherbookmarks'][action]
        raise error.NoMergeDestAbort(msg, hint=hint)
    assert node is not None
    return node

def _destmergebranch(repo, action='merge', sourceset=None, onheadcheck=True,
                     destspace=None):
    """find merge destination based on branch heads"""
    node = None

    if sourceset is None:
        sourceset = [repo[repo.dirstate.p1()].rev()]
        branch = repo.dirstate.branch()
    elif not sourceset:
        msg, hint = msgdestmerge['emptysourceset'][action]
        raise error.NoMergeDestAbort(msg, hint=hint)
    else:
        branch = None
        for ctx in repo.set('roots(%ld::%ld)', sourceset, sourceset):
            if branch is not None and ctx.branch() != branch:
                msg, hint = msgdestmerge['multiplebranchessourceset'][action]
                raise error.ManyMergeDestAbort(msg, hint=hint)
            branch = ctx.branch()

    bheads = repo.branchheads(branch)
    onhead = repo.revs('%ld and %ln', sourceset, bheads)
    if onheadcheck and not onhead:
        # Case A: working copy if not on a head. (merge only)
        #
        # This is probably a user mistake We bailout pointing at 'hg update'
        if len(repo.heads()) <= 1:
            msg, hint = msgdestmerge['nootherheadsbehind'][action]
        else:
            msg, hint = msgdestmerge['notatheads'][action]
        raise error.Abort(msg, hint=hint)
    # remove heads descendants of source from the set
    bheads = list(repo.revs('%ln - (%ld::)', bheads, sourceset))
    # filters out bookmarked heads
    nbhs = list(repo.revs('%ld - bookmark()', bheads))

    if destspace is not None:
        # restrict search space
        # used in the 'hg pull --rebase' case, see issue 5214.
        nbhs = list(repo.revs('%ld and %ld', destspace, nbhs))

    if len(nbhs) > 1:
        # Case B: There is more than 1 other anonymous heads
        #
        # This means that there will be more than 1 candidate. This is
        # ambiguous. We abort asking the user to pick as explicit destination
        # instead.
        msg, hint = msgdestmerge['toomanyheads'][action]
        msg %= (branch, len(bheads) + 1)
        raise error.ManyMergeDestAbort(msg, hint=hint)
    elif not nbhs:
        # Case B: There is no other anonymous heads
        #
        # This means that there is no natural candidate to merge with.
        # We abort, with various messages for various cases.
        if bheads:
            msg, hint = msgdestmerge['bookmarkedheads'][action]
        elif len(repo.heads()) > 1:
            msg, hint = msgdestmerge['nootherbranchheads'][action]
            msg %= branch
        elif not onhead:
            # if 'onheadcheck == False' (rebase case),
            # this was not caught in Case A.
            msg, hint = msgdestmerge['nootherheadsbehind'][action]
        else:
            msg, hint = msgdestmerge['nootherheads'][action]
        raise error.NoMergeDestAbort(msg, hint=hint)
    else:
        node = nbhs[0]
    assert node is not None
    return node

def destmerge(repo, action='merge', sourceset=None, onheadcheck=True,
              destspace=None):
    """return the default destination for a merge

    (or raise exception about why it can't pick one)

    :action: the action being performed, controls emitted error message
    """
    # destspace is here to work around issues with `hg pull --rebase` see
    # issue5214 for details
    if repo._activebookmark:
        node = _destmergebook(repo, action=action, sourceset=sourceset,
                              destspace=destspace)
    else:
        node = _destmergebranch(repo, action=action, sourceset=sourceset,
                                onheadcheck=onheadcheck, destspace=destspace)
    return repo[node].rev()

def desthistedit(ui, repo):
    """Default base revision to edit for `hg histedit`."""
    default = ui.config('histedit', 'defaultrev')

    if default is None:
        revs = stack.getstack(repo)
    elif default:
        revs = scmutil.revrange(repo, [default])

    if revs:
        # Take the first revision of the revset as the root
        return revs.min()

    return None

def stackbase(ui, repo):
    revs = stack.getstack(repo)
    return revs.first() if revs else None

def _statusotherbook(ui, repo):
    bmheads = bookmarks.headsforactive(repo)
    curhead = repo._bookmarks[repo._activebookmark]
    if repo.revs('%n and parents()', curhead):
        # we are on the active bookmark
        bmheads = [b for b in bmheads if curhead != b]
        if bmheads:
            msg = _('%i other divergent bookmarks for "%s"\n')
            ui.status(msg % (len(bmheads), repo._activebookmark))

def _statusotherbranchheads(ui, repo):
    currentbranch = repo.dirstate.branch()
    allheads = repo.branchheads(currentbranch, closed=True)
    heads = repo.branchheads(currentbranch)
    if repo.revs('%ln and parents()', allheads):
        # we are on a head, even though it might be closed
        #
        #  on closed otherheads
        #  ========= ==========
        #      o        0       all heads for current branch are closed
        #               N       only descendant branch heads are closed
        #      x        0       there is only one non-closed branch head
        #               N       there are some non-closed branch heads
        #  ========= ==========
        otherheads = repo.revs('%ln - parents()', heads)
        if repo['.'].closesbranch():
            ui.warn(_('no open descendant heads on branch "%s", '
                        'updating to a closed head\n') %
                      (currentbranch))
            if otherheads:
                ui.warn(_("(committing will reopen the head, "
                            "use 'hg heads .' to see %i other heads)\n") %
                          (len(otherheads)))
            else:
                ui.warn(_('(committing will reopen branch "%s")\n') %
                          (currentbranch))
        elif otherheads:
            curhead = repo['.']
            ui.status(_('updated to "%s: %s"\n') % (curhead,
                                    curhead.description().split('\n')[0]))
            ui.status(_('%i other heads for branch "%s"\n') %
                      (len(otherheads), currentbranch))

def statusotherdests(ui, repo):
    """Print message about other head"""
    # XXX we should probably include a hint:
    # - about what to do
    # - how to see such heads
    if repo._activebookmark:
        _statusotherbook(ui, repo)
    else:
        _statusotherbranchheads(ui, repo)