mercurial/upgrade_utils/engine.py
author Simon Sapin <simon.sapin@octobus.net>
Mon, 27 Sep 2021 12:09:15 +0200
changeset 48068 bf8837e3d7ce
parent 47877 2174f54aab18
child 48437 6e4999cb085e
permissions -rw-r--r--
dirstate: Remove the flat Rust DirstateMap implementation Before this changeset we had two Rust implementations of `DirstateMap`. This removes the "flat" DirstateMap so that the "tree" DirstateMap is always used when Rust enabled. This simplifies the code a lot, and will enable (in the next changeset) further removal of a trait abstraction. This is a performance regression when: * Rust is enabled, and * The repository uses the legacy dirstate-v1 file format, and * For `hg status`, unknown files are not listed (such as with `-mard`) The regression is about 100 milliseconds for `hg status -mard` on a semi-large repository (mozilla-central), from ~320ms to ~420ms. We deem this to be small enough to be worth it. The new dirstate-v2 is still experimental at this point, but we aim to stabilize it (though not yet enable it by default for new repositories) in Mercurial 6.0. Eventually, upgrating repositories to dirsate-v2 will eliminate this regression (and enable other performance improvements). # Background The flat DirstateMap was introduced with the first Rust implementation of the status algorithm. It works similarly to the previous Python + C one, with a single `HashMap` that associates file paths to a `DirstateEntry` (where Python has a dict). We later added the tree DirstateMap where the root of the tree contains nodes for files and directories that are directly at the root of the repository, and nodes for directories can contain child nodes representing the files and directly that *they* contain directly. The shape of this tree mirrors that of the working directory in the filesystem. This enables the status algorithm to traverse this tree in tandem with traversing the filesystem tree, which in turns enables a more efficient algorithm. Furthermore, the new dirstate-v2 file format is also based on a tree of the same shape. The tree DirstateMap can access a dirstate-v2 file without parsing it: binary data in a single large (possibly memory-mapped) bytes buffer is traversed on demand. This allows `DirstateMap` creation to take `O(1)` time. (Mutation works by creating new in-memory nodes with copy-on-write semantics, and serialization is append-mostly.) The tradeoff is that for "legacy" repositories that use the dirstate-v1 file format, parsing that file into a tree DirstateMap takes more time. Profiling shows that this time is dominated by `HashMap`. For a dirstate containing `F` files with an average `D` directory depth, the flat DirstateMap does parsing in `O(F)` number of HashMap operations but the tree DirstateMap in `O(F × D)` operations, since each node has its own HashMap containing its child nodes. This slower costs ~140ms on an old snapshot of mozilla-central, and ~80ms on an old snapshot of the Netbeans repository. The status algorithm is faster, but with `-mard` (when not listing unknown files) it is typically not faster *enough* to compensate the slower parsing. Both Rust implementations are always faster than the Python + C implementation # Benchmark results All benchmarks are run on changeset 98c0408324e6, with repositories that use the dirstate-v1 file format, on a server with 4 CPU cores and 4 CPU threads (no HyperThreading). `hg status` benchmarks show wall clock times of the entire command as the average and standard deviation of serveral runs, collected by https://github.com/sharkdp/hyperfine and reformated. Parsing benchmarks are wall clock time of the Rust function that converts a bytes buffer of the dirstate file into the `DirstateMap` data structure as used by the status algorithm. A single run each, collected by running `hg status` this environment variable: RUST_LOG=hg::dirstate::dirstate_map=trace,hg::dirstate_tree::dirstate_map=trace Benchmark 1: Rust flat DirstateMap → Rust tree DirstateMap hg status mozilla-clean 562.3 ms ± 2.0 ms → 462.5 ms ± 0.6 ms 1.22 ± 0.00 times faster mozilla-dirty 859.6 ms ± 2.2 ms → 719.5 ms ± 3.2 ms 1.19 ± 0.01 times faster mozilla-ignored 558.2 ms ± 3.0 ms → 457.9 ms ± 2.9 ms 1.22 ± 0.01 times faster mozilla-unknowns 859.4 ms ± 5.7 ms → 716.0 ms ± 4.7 ms 1.20 ± 0.01 times faster netbeans-clean 336.5 ms ± 0.9 ms → 339.5 ms ± 0.4 ms 0.99 ± 0.00 times faster netbeans-dirty 491.4 ms ± 1.6 ms → 475.1 ms ± 1.2 ms 1.03 ± 0.00 times faster netbeans-ignored 343.7 ms ± 1.0 ms → 347.8 ms ± 0.4 ms 0.99 ± 0.00 times faster netbeans-unknowns 484.3 ms ± 1.0 ms → 466.0 ms ± 1.2 ms 1.04 ± 0.00 times faster hg status -mard mozilla-clean 317.3 ms ± 0.6 ms → 422.5 ms ± 1.2 ms 0.75 ± 0.00 times faster mozilla-dirty 315.4 ms ± 0.6 ms → 417.7 ms ± 1.1 ms 0.76 ± 0.00 times faster mozilla-ignored 314.6 ms ± 0.6 ms → 417.4 ms ± 1.0 ms 0.75 ± 0.00 times faster mozilla-unknowns 312.9 ms ± 0.9 ms → 417.3 ms ± 1.6 ms 0.75 ± 0.00 times faster netbeans-clean 212.0 ms ± 0.6 ms → 283.6 ms ± 0.8 ms 0.75 ± 0.00 times faster netbeans-dirty 211.4 ms ± 1.0 ms → 283.4 ms ± 1.6 ms 0.75 ± 0.01 times faster netbeans-ignored 211.4 ms ± 0.9 ms → 283.9 ms ± 0.8 ms 0.74 ± 0.01 times faster netbeans-unknowns 211.1 ms ± 0.6 ms → 283.4 ms ± 1.0 ms 0.74 ± 0.00 times faster Parsing mozilla-clean 38.4ms → 177.6ms mozilla-dirty 38.8ms → 177.0ms mozilla-ignored 38.8ms → 178.0ms mozilla-unknowns 38.7ms → 176.9ms netbeans-clean 16.5ms → 97.3ms netbeans-dirty 16.5ms → 98.4ms netbeans-ignored 16.9ms → 97.4ms netbeans-unknowns 16.9ms → 96.3ms Benchmark 2: Python + C dirstatemap → Rust tree DirstateMap hg status mozilla-clean 1261.0 ms ± 3.6 ms → 461.1 ms ± 0.5 ms 2.73 ± 0.00 times faster mozilla-dirty 2293.4 ms ± 9.1 ms → 719.6 ms ± 3.6 ms 3.19 ± 0.01 times faster mozilla-ignored 1240.4 ms ± 2.3 ms → 457.7 ms ± 1.9 ms 2.71 ± 0.00 times faster mozilla-unknowns 2283.3 ms ± 9.0 ms → 719.7 ms ± 3.8 ms 3.17 ± 0.01 times faster netbeans-clean 879.7 ms ± 3.5 ms → 339.9 ms ± 0.5 ms 2.59 ± 0.00 times faster netbeans-dirty 1257.3 ms ± 4.7 ms → 474.6 ms ± 1.6 ms 2.65 ± 0.01 times faster netbeans-ignored 943.9 ms ± 1.9 ms → 347.3 ms ± 1.1 ms 2.72 ± 0.00 times faster netbeans-unknowns 1188.1 ms ± 5.0 ms → 465.2 ms ± 2.3 ms 2.55 ± 0.01 times faster hg status -mard mozilla-clean 903.2 ms ± 3.6 ms → 423.4 ms ± 2.2 ms 2.13 ± 0.01 times faster mozilla-dirty 884.6 ms ± 4.5 ms → 417.3 ms ± 1.4 ms 2.12 ± 0.01 times faster mozilla-ignored 881.9 ms ± 1.3 ms → 417.3 ms ± 0.8 ms 2.11 ± 0.00 times faster mozilla-unknowns 878.5 ms ± 1.9 ms → 416.4 ms ± 0.9 ms 2.11 ± 0.00 times faster netbeans-clean 434.9 ms ± 1.8 ms → 284.0 ms ± 0.8 ms 1.53 ± 0.01 times faster netbeans-dirty 434.1 ms ± 0.8 ms → 283.1 ms ± 0.8 ms 1.53 ± 0.00 times faster netbeans-ignored 431.7 ms ± 1.1 ms → 283.6 ms ± 1.8 ms 1.52 ± 0.01 times faster netbeans-unknowns 433.0 ms ± 1.3 ms → 283.5 ms ± 0.7 ms 1.53 ± 0.00 times faster Differential Revision: https://phab.mercurial-scm.org/D11516

# upgrade.py - functions for in place upgrade of Mercurial repository
#
# Copyright (c) 2016-present, Gregory Szorc
#
# 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

import stat

from ..i18n import _
from ..pycompat import getattr
from .. import (
    changelog,
    error,
    filelog,
    manifest,
    metadata,
    pycompat,
    requirements,
    scmutil,
    store,
    util,
    vfs as vfsmod,
)
from ..revlogutils import (
    constants as revlogconst,
    flagutil,
    nodemap,
    sidedata as sidedatamod,
)
from . import actions as upgrade_actions


def get_sidedata_helpers(srcrepo, dstrepo):
    use_w = srcrepo.ui.configbool(b'experimental', b'worker.repository-upgrade')
    sequential = pycompat.iswindows or not use_w
    if not sequential:
        srcrepo.register_sidedata_computer(
            revlogconst.KIND_CHANGELOG,
            sidedatamod.SD_FILES,
            (sidedatamod.SD_FILES,),
            metadata._get_worker_sidedata_adder(srcrepo, dstrepo),
            flagutil.REVIDX_HASCOPIESINFO,
            replace=True,
        )
    return sidedatamod.get_sidedata_helpers(srcrepo, dstrepo._wanted_sidedata)


def _revlogfrompath(repo, rl_type, path):
    """Obtain a revlog from a repo path.

    An instance of the appropriate class is returned.
    """
    if rl_type & store.FILEFLAGS_CHANGELOG:
        return changelog.changelog(repo.svfs)
    elif rl_type & store.FILEFLAGS_MANIFESTLOG:
        mandir = b''
        if b'/' in path:
            mandir = path.rsplit(b'/', 1)[0]
        return manifest.manifestrevlog(
            repo.nodeconstants, repo.svfs, tree=mandir
        )
    else:
        # drop the extension and the `data/` prefix
        path_part = path.rsplit(b'.', 1)[0].split(b'/', 1)
        if len(path_part) < 2:
            msg = _(b'cannot recognize revlog from filename: %s')
            msg %= path
            raise error.Abort(msg)
        path = path_part[1]
        return filelog.filelog(repo.svfs, path)


def _copyrevlog(tr, destrepo, oldrl, rl_type, unencodedname):
    """copy all relevant files for `oldrl` into `destrepo` store

    Files are copied "as is" without any transformation. The copy is performed
    without extra checks. Callers are responsible for making sure the copied
    content is compatible with format of the destination repository.
    """
    oldrl = getattr(oldrl, '_revlog', oldrl)
    newrl = _revlogfrompath(destrepo, rl_type, unencodedname)
    newrl = getattr(newrl, '_revlog', newrl)

    oldvfs = oldrl.opener
    newvfs = newrl.opener
    oldindex = oldvfs.join(oldrl._indexfile)
    newindex = newvfs.join(newrl._indexfile)
    olddata = oldvfs.join(oldrl._datafile)
    newdata = newvfs.join(newrl._datafile)

    with newvfs(newrl._indexfile, b'w'):
        pass  # create all the directories

    util.copyfile(oldindex, newindex)
    copydata = oldrl.opener.exists(oldrl._datafile)
    if copydata:
        util.copyfile(olddata, newdata)

    if rl_type & store.FILEFLAGS_FILELOG:
        destrepo.svfs.fncache.add(unencodedname)
        if copydata:
            destrepo.svfs.fncache.add(unencodedname[:-2] + b'.d')


UPGRADE_CHANGELOG = b"changelog"
UPGRADE_MANIFEST = b"manifest"
UPGRADE_FILELOGS = b"all-filelogs"

UPGRADE_ALL_REVLOGS = frozenset(
    [UPGRADE_CHANGELOG, UPGRADE_MANIFEST, UPGRADE_FILELOGS]
)


def matchrevlog(revlogfilter, rl_type):
    """check if a revlog is selected for cloning.

    In other words, are there any updates which need to be done on revlog
    or it can be blindly copied.

    The store entry is checked against the passed filter"""
    if rl_type & store.FILEFLAGS_CHANGELOG:
        return UPGRADE_CHANGELOG in revlogfilter
    elif rl_type & store.FILEFLAGS_MANIFESTLOG:
        return UPGRADE_MANIFEST in revlogfilter
    assert rl_type & store.FILEFLAGS_FILELOG
    return UPGRADE_FILELOGS in revlogfilter


def _perform_clone(
    ui,
    dstrepo,
    tr,
    old_revlog,
    rl_type,
    unencoded,
    upgrade_op,
    sidedata_helpers,
    oncopiedrevision,
):
    """returns the new revlog object created"""
    newrl = None
    if matchrevlog(upgrade_op.revlogs_to_process, rl_type):
        ui.note(
            _(b'cloning %d revisions from %s\n') % (len(old_revlog), unencoded)
        )
        newrl = _revlogfrompath(dstrepo, rl_type, unencoded)
        old_revlog.clone(
            tr,
            newrl,
            addrevisioncb=oncopiedrevision,
            deltareuse=upgrade_op.delta_reuse_mode,
            forcedeltabothparents=upgrade_op.force_re_delta_both_parents,
            sidedata_helpers=sidedata_helpers,
        )
    else:
        msg = _(b'blindly copying %s containing %i revisions\n')
        ui.note(msg % (unencoded, len(old_revlog)))
        _copyrevlog(tr, dstrepo, old_revlog, rl_type, unencoded)

        newrl = _revlogfrompath(dstrepo, rl_type, unencoded)
    return newrl


def _clonerevlogs(
    ui,
    srcrepo,
    dstrepo,
    tr,
    upgrade_op,
):
    """Copy revlogs between 2 repos."""
    revcount = 0
    srcsize = 0
    srcrawsize = 0
    dstsize = 0
    fcount = 0
    frevcount = 0
    fsrcsize = 0
    frawsize = 0
    fdstsize = 0
    mcount = 0
    mrevcount = 0
    msrcsize = 0
    mrawsize = 0
    mdstsize = 0
    crevcount = 0
    csrcsize = 0
    crawsize = 0
    cdstsize = 0

    alldatafiles = list(srcrepo.store.walk())
    # mapping of data files which needs to be cloned
    # key is unencoded filename
    # value is revlog_object_from_srcrepo
    manifests = {}
    changelogs = {}
    filelogs = {}

    # Perform a pass to collect metadata. This validates we can open all
    # source files and allows a unified progress bar to be displayed.
    for rl_type, unencoded, size in alldatafiles:
        if not rl_type & store.FILEFLAGS_REVLOG_MAIN:
            continue

        # the store.walk function will wrongly pickup transaction backup and
        # get confused. As a quick fix for 5.9 release, we ignore those.
        # (this is not a module constants because it seems better to keep the
        # hack together)
        skip_undo = (
            b'undo.backup.00changelog.i',
            b'undo.backup.00manifest.i',
        )
        if unencoded in skip_undo:
            continue

        rl = _revlogfrompath(srcrepo, rl_type, unencoded)

        info = rl.storageinfo(
            exclusivefiles=True,
            revisionscount=True,
            trackedsize=True,
            storedsize=True,
        )

        revcount += info[b'revisionscount'] or 0
        datasize = info[b'storedsize'] or 0
        rawsize = info[b'trackedsize'] or 0

        srcsize += datasize
        srcrawsize += rawsize

        # This is for the separate progress bars.
        if rl_type & store.FILEFLAGS_CHANGELOG:
            changelogs[unencoded] = (rl_type, rl)
            crevcount += len(rl)
            csrcsize += datasize
            crawsize += rawsize
        elif rl_type & store.FILEFLAGS_MANIFESTLOG:
            manifests[unencoded] = (rl_type, rl)
            mcount += 1
            mrevcount += len(rl)
            msrcsize += datasize
            mrawsize += rawsize
        elif rl_type & store.FILEFLAGS_FILELOG:
            filelogs[unencoded] = (rl_type, rl)
            fcount += 1
            frevcount += len(rl)
            fsrcsize += datasize
            frawsize += rawsize
        else:
            error.ProgrammingError(b'unknown revlog type')

    if not revcount:
        return

    ui.status(
        _(
            b'migrating %d total revisions (%d in filelogs, %d in manifests, '
            b'%d in changelog)\n'
        )
        % (revcount, frevcount, mrevcount, crevcount)
    )
    ui.status(
        _(b'migrating %s in store; %s tracked data\n')
        % ((util.bytecount(srcsize), util.bytecount(srcrawsize)))
    )

    # Used to keep track of progress.
    progress = None

    def oncopiedrevision(rl, rev, node):
        progress.increment()

    sidedata_helpers = get_sidedata_helpers(srcrepo, dstrepo)

    # Migrating filelogs
    ui.status(
        _(
            b'migrating %d filelogs containing %d revisions '
            b'(%s in store; %s tracked data)\n'
        )
        % (
            fcount,
            frevcount,
            util.bytecount(fsrcsize),
            util.bytecount(frawsize),
        )
    )
    progress = srcrepo.ui.makeprogress(_(b'file revisions'), total=frevcount)
    for unencoded, (rl_type, oldrl) in sorted(filelogs.items()):
        newrl = _perform_clone(
            ui,
            dstrepo,
            tr,
            oldrl,
            rl_type,
            unencoded,
            upgrade_op,
            sidedata_helpers,
            oncopiedrevision,
        )
        info = newrl.storageinfo(storedsize=True)
        fdstsize += info[b'storedsize'] or 0
    ui.status(
        _(
            b'finished migrating %d filelog revisions across %d '
            b'filelogs; change in size: %s\n'
        )
        % (frevcount, fcount, util.bytecount(fdstsize - fsrcsize))
    )

    # Migrating manifests
    ui.status(
        _(
            b'migrating %d manifests containing %d revisions '
            b'(%s in store; %s tracked data)\n'
        )
        % (
            mcount,
            mrevcount,
            util.bytecount(msrcsize),
            util.bytecount(mrawsize),
        )
    )
    if progress:
        progress.complete()
    progress = srcrepo.ui.makeprogress(
        _(b'manifest revisions'), total=mrevcount
    )
    for unencoded, (rl_type, oldrl) in sorted(manifests.items()):
        newrl = _perform_clone(
            ui,
            dstrepo,
            tr,
            oldrl,
            rl_type,
            unencoded,
            upgrade_op,
            sidedata_helpers,
            oncopiedrevision,
        )
        info = newrl.storageinfo(storedsize=True)
        mdstsize += info[b'storedsize'] or 0
    ui.status(
        _(
            b'finished migrating %d manifest revisions across %d '
            b'manifests; change in size: %s\n'
        )
        % (mrevcount, mcount, util.bytecount(mdstsize - msrcsize))
    )

    # Migrating changelog
    ui.status(
        _(
            b'migrating changelog containing %d revisions '
            b'(%s in store; %s tracked data)\n'
        )
        % (
            crevcount,
            util.bytecount(csrcsize),
            util.bytecount(crawsize),
        )
    )
    if progress:
        progress.complete()
    progress = srcrepo.ui.makeprogress(
        _(b'changelog revisions'), total=crevcount
    )
    for unencoded, (rl_type, oldrl) in sorted(changelogs.items()):
        newrl = _perform_clone(
            ui,
            dstrepo,
            tr,
            oldrl,
            rl_type,
            unencoded,
            upgrade_op,
            sidedata_helpers,
            oncopiedrevision,
        )
        info = newrl.storageinfo(storedsize=True)
        cdstsize += info[b'storedsize'] or 0
    progress.complete()
    ui.status(
        _(
            b'finished migrating %d changelog revisions; change in size: '
            b'%s\n'
        )
        % (crevcount, util.bytecount(cdstsize - csrcsize))
    )

    dstsize = fdstsize + mdstsize + cdstsize
    ui.status(
        _(
            b'finished migrating %d total revisions; total change in store '
            b'size: %s\n'
        )
        % (revcount, util.bytecount(dstsize - srcsize))
    )


def _files_to_copy_post_revlog_clone(srcrepo):
    """yields files which should be copied to destination after revlogs
    are cloned"""
    for path, kind, st in sorted(srcrepo.store.vfs.readdir(b'', stat=True)):
        # don't copy revlogs as they are already cloned
        if store.revlog_type(path) is not None:
            continue
        # Skip transaction related files.
        if path.startswith(b'undo'):
            continue
        # Only copy regular files.
        if kind != stat.S_IFREG:
            continue
        # Skip other skipped files.
        if path in (b'lock', b'fncache'):
            continue
        # TODO: should we skip cache too?

        yield path


def _replacestores(currentrepo, upgradedrepo, backupvfs, upgrade_op):
    """Replace the stores after current repository is upgraded

    Creates a backup of current repository store at backup path
    Replaces upgraded store files in current repo from upgraded one

    Arguments:
      currentrepo: repo object of current repository
      upgradedrepo: repo object of the upgraded data
      backupvfs: vfs object for the backup path
      upgrade_op: upgrade operation object
                  to be used to decide what all is upgraded
    """
    # TODO: don't blindly rename everything in store
    # There can be upgrades where store is not touched at all
    if upgrade_op.backup_store:
        util.rename(currentrepo.spath, backupvfs.join(b'store'))
    else:
        currentrepo.vfs.rmtree(b'store', forcibly=True)
    util.rename(upgradedrepo.spath, currentrepo.spath)


def finishdatamigration(ui, srcrepo, dstrepo, requirements):
    """Hook point for extensions to perform additional actions during upgrade.

    This function is called after revlogs and store files have been copied but
    before the new store is swapped into the original location.
    """


def upgrade(ui, srcrepo, dstrepo, upgrade_op):
    """Do the low-level work of upgrading a repository.

    The upgrade is effectively performed as a copy between a source
    repository and a temporary destination repository.

    The source repository is unmodified for as long as possible so the
    upgrade can abort at any time without causing loss of service for
    readers and without corrupting the source repository.
    """
    assert srcrepo.currentwlock()
    assert dstrepo.currentwlock()
    backuppath = None
    backupvfs = None

    ui.status(
        _(
            b'(it is safe to interrupt this process any time before '
            b'data migration completes)\n'
        )
    )

    if upgrade_actions.dirstatev2 in upgrade_op.upgrade_actions:
        ui.status(_(b'upgrading to dirstate-v2 from v1\n'))
        upgrade_dirstate(ui, srcrepo, upgrade_op, b'v1', b'v2')
        upgrade_op.upgrade_actions.remove(upgrade_actions.dirstatev2)

    if upgrade_actions.dirstatev2 in upgrade_op.removed_actions:
        ui.status(_(b'downgrading from dirstate-v2 to v1\n'))
        upgrade_dirstate(ui, srcrepo, upgrade_op, b'v2', b'v1')
        upgrade_op.removed_actions.remove(upgrade_actions.dirstatev2)

    if not (upgrade_op.upgrade_actions or upgrade_op.removed_actions):
        return

    if upgrade_op.requirements_only:
        ui.status(_(b'upgrading repository requirements\n'))
        scmutil.writereporequirements(srcrepo, upgrade_op.new_requirements)
    # if there is only one action and that is persistent nodemap upgrade
    # directly write the nodemap file and update requirements instead of going
    # through the whole cloning process
    elif (
        len(upgrade_op.upgrade_actions) == 1
        and b'persistent-nodemap' in upgrade_op.upgrade_actions_names
        and not upgrade_op.removed_actions
    ):
        ui.status(
            _(b'upgrading repository to use persistent nodemap feature\n')
        )
        with srcrepo.transaction(b'upgrade') as tr:
            unfi = srcrepo.unfiltered()
            cl = unfi.changelog
            nodemap.persist_nodemap(tr, cl, force=True)
            # we want to directly operate on the underlying revlog to force
            # create a nodemap file. This is fine since this is upgrade code
            # and it heavily relies on repository being revlog based
            # hence accessing private attributes can be justified
            nodemap.persist_nodemap(
                tr, unfi.manifestlog._rootstore._revlog, force=True
            )
        scmutil.writereporequirements(srcrepo, upgrade_op.new_requirements)
    elif (
        len(upgrade_op.removed_actions) == 1
        and [
            x
            for x in upgrade_op.removed_actions
            if x.name == b'persistent-nodemap'
        ]
        and not upgrade_op.upgrade_actions
    ):
        ui.status(
            _(b'downgrading repository to not use persistent nodemap feature\n')
        )
        with srcrepo.transaction(b'upgrade') as tr:
            unfi = srcrepo.unfiltered()
            cl = unfi.changelog
            nodemap.delete_nodemap(tr, srcrepo, cl)
            # check comment 20 lines above for accessing private attributes
            nodemap.delete_nodemap(
                tr, srcrepo, unfi.manifestlog._rootstore._revlog
            )
        scmutil.writereporequirements(srcrepo, upgrade_op.new_requirements)
    else:
        with dstrepo.transaction(b'upgrade') as tr:
            _clonerevlogs(
                ui,
                srcrepo,
                dstrepo,
                tr,
                upgrade_op,
            )

        # Now copy other files in the store directory.
        for p in _files_to_copy_post_revlog_clone(srcrepo):
            srcrepo.ui.status(_(b'copying %s\n') % p)
            src = srcrepo.store.rawvfs.join(p)
            dst = dstrepo.store.rawvfs.join(p)
            util.copyfile(src, dst, copystat=True)

        finishdatamigration(ui, srcrepo, dstrepo, requirements)

        ui.status(_(b'data fully upgraded in a temporary repository\n'))

        if upgrade_op.backup_store:
            backuppath = pycompat.mkdtemp(
                prefix=b'upgradebackup.', dir=srcrepo.path
            )
            backupvfs = vfsmod.vfs(backuppath)

            # Make a backup of requires file first, as it is the first to be modified.
            util.copyfile(
                srcrepo.vfs.join(b'requires'), backupvfs.join(b'requires')
            )

        # We install an arbitrary requirement that clients must not support
        # as a mechanism to lock out new clients during the data swap. This is
        # better than allowing a client to continue while the repository is in
        # an inconsistent state.
        ui.status(
            _(
                b'marking source repository as being upgraded; clients will be '
                b'unable to read from repository\n'
            )
        )
        scmutil.writereporequirements(
            srcrepo, srcrepo.requirements | {b'upgradeinprogress'}
        )

        ui.status(_(b'starting in-place swap of repository data\n'))
        if upgrade_op.backup_store:
            ui.status(
                _(b'replaced files will be backed up at %s\n') % backuppath
            )

        # Now swap in the new store directory. Doing it as a rename should make
        # the operation nearly instantaneous and atomic (at least in well-behaved
        # environments).
        ui.status(_(b'replacing store...\n'))
        tstart = util.timer()
        _replacestores(srcrepo, dstrepo, backupvfs, upgrade_op)
        elapsed = util.timer() - tstart
        ui.status(
            _(
                b'store replacement complete; repository was inconsistent for '
                b'%0.1fs\n'
            )
            % elapsed
        )

        # We first write the requirements file. Any new requirements will lock
        # out legacy clients.
        ui.status(
            _(
                b'finalizing requirements file and making repository readable '
                b'again\n'
            )
        )
        scmutil.writereporequirements(srcrepo, upgrade_op.new_requirements)

        if upgrade_op.backup_store:
            # The lock file from the old store won't be removed because nothing has a
            # reference to its new location. So clean it up manually. Alternatively, we
            # could update srcrepo.svfs and other variables to point to the new
            # location. This is simpler.
            assert backupvfs is not None  # help pytype
            backupvfs.unlink(b'store/lock')

    return backuppath


def upgrade_dirstate(ui, srcrepo, upgrade_op, old, new):
    if upgrade_op.backup_store:
        backuppath = pycompat.mkdtemp(
            prefix=b'upgradebackup.', dir=srcrepo.path
        )
        ui.status(_(b'replaced files will be backed up at %s\n') % backuppath)
        backupvfs = vfsmod.vfs(backuppath)
        util.copyfile(
            srcrepo.vfs.join(b'requires'), backupvfs.join(b'requires')
        )
        util.copyfile(
            srcrepo.vfs.join(b'dirstate'), backupvfs.join(b'dirstate')
        )

    assert srcrepo.dirstate._use_dirstate_v2 == (old == b'v2')
    srcrepo.dirstate._map.preload()
    srcrepo.dirstate._use_dirstate_v2 = new == b'v2'
    srcrepo.dirstate._map._use_dirstate_v2 = srcrepo.dirstate._use_dirstate_v2
    srcrepo.dirstate._dirty = True
    srcrepo.vfs.unlink(b'dirstate')
    srcrepo.dirstate.write(None)

    scmutil.writereporequirements(srcrepo, upgrade_op.new_requirements)