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4f485393e516cfbb057d0 0 iQHNBAABCgA3FiEEH2b4zfZU6QXBHaBhoR4BzQ4F2VYFAmO1XgoZHGFscGhhcmVAcmFwaGFlbGdvbWVzLmRldgAKCRChHgHNDgXZVn8nDACU04KbPloLl+if6DQYreESnF9LU8C+qnLC/j5RRuaFNh/ec6C3DzLWqWdmnWA/siV3nUR1bXHfTui95azxJfYvWoXH2R2yam+YhE256B4rDDYWS1LI9kNNM+A33xcPS2HxVowkByhjB5FPKR6I90dX42BYJpTS5s/VPx63wXLznjFWuD7XJ3P0VI7D72j/+6EQCmHaAUEE5bO00Ob2JxmzJlaP+02fYc814PAONE2/ocfR0aExAVS3VA+SJGXnXTVpoaHr7NJKC2sBLFsdnhIRwtCf3rtGEvIJ5v2U2xx0ZEz/mimtGzW5ovkthobV4mojk0DRz7xBtA96pOGSRTD8QndIsdMCUipo8zZ/AGAMByCtsQOX7OYhR6gp+I6+iPh8fTR5oCbkO7cizDDQtXcrR5OT/BDH9xkAF1ghNL8o23a09/wfZ9NPg5zrh/4T/dFfoe2COlkAJJ1ttDPYyQkCfMsoWm3OXk6xJ3ExVbwkZzUDQSzsxGS+oxbFDWJZ64Q=
diff --git a/.hgtags b/.hgtags
--- a/.hgtags
+++ b/.hgtags
@@ -248,8 +248,9 @@ f69bffd00abe3a1b94d1032eb2c92e611d16a192
 b5c8524827d20fe2e0ca8fb1234a0fe35a1a36c7 6.2.2
 dbdee8ac3e3fcdda1fa55b90c0a235125b7f8e6f 6.2.3
 a3356ab610fc50000cf0ba55c424a4d96da11db7 6.3rc0
 04f1dba53c961dfdb875c8469adc96fa999cfbed 6.3.0
 04f1dba53c961dfdb875c8469adc96fa999cfbed 6.3
 04f1dba53c961dfdb875c8469adc96fa999cfbed 6.3.0
 0000000000000000000000000000000000000000 6.3.0
 c890d8b8bc59b18e5febf60caada629df5356ee2 6.3.1
+59466b13a3ae0e29a5d4f485393e516cfbb057d0 6.3.2
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -53,17 +53,17 @@ help:
 	@echo '  make all && su -c "make install" && hg version'
 	@echo
 	@echo 'Example for a local installation (usable in this directory):'
 	@echo '  make local && ./hg version'
 
 all: build doc
 
 local:
-	$(PYTHON) setup.py $(PURE) \
+	MERCURIAL_SETUP_MAKE_LOCAL=1 $(PYTHON) setup.py $(PURE) \
 	  build_py -c -d . \
 	  build_ext $(COMPILERFLAG) -i \
 	  build_hgexe $(COMPILERFLAG) -i \
 	  build_mo
 	env HGRCPATH= $(PYTHON) hg version
 
 build:
 	$(PYTHON) setup.py $(PURE) build $(COMPILERFLAG)
diff --git a/contrib/heptapod-ci.yml b/contrib/heptapod-ci.yml
--- a/contrib/heptapod-ci.yml
+++ b/contrib/heptapod-ci.yml
@@ -29,25 +29,27 @@ variables:
         - echo "$RUNTEST_ARGS"
         - HGTESTS_ALLOW_NETIO="$TEST_HGTESTS_ALLOW_NETIO" HGMODULEPOLICY="$TEST_HGMODULEPOLICY" "$PYTHON" tests/run-tests.py --color=always $RUNTEST_ARGS
 
 checks:
     <<: *runtests
     variables:
         RUNTEST_ARGS: "--time --test-list /tmp/check-tests.txt"
         PYTHON: python3
+        CI_CLEVER_CLOUD_FLAVOR: S
 
 rust-cargo-test:
     <<: *all
     stage: tests
     script:
         - echo "python used, $PYTHON"
         - make rust-tests
     variables:
         PYTHON: python3
+        CI_CLEVER_CLOUD_FLAVOR: S
 
 test-c:
     <<: *runtests
     variables:
         RUNTEST_ARGS: " --no-rust --blacklist /tmp/check-tests.txt"
         PYTHON: python3
         TEST_HGMODULEPOLICY: "c"
         TEST_HGTESTS_ALLOW_NETIO: "1"
diff --git a/hgext/convert/bzr.py b/hgext/convert/bzr.py
--- a/hgext/convert/bzr.py
+++ b/hgext/convert/bzr.py
@@ -36,16 +36,22 @@ try:
     import breezy.revision
     import breezy.revisionspec
 
     bzrdir = breezy.bzr.bzrdir
     errors = breezy.errors
     revision = breezy.revision
     revisionspec = breezy.revisionspec
     revisionspec.RevisionSpec
+
+    try:
+        # brz 3.3.0 (revno: 7614.2.2)
+        from breezy.transport import NoSuchFile
+    except ImportError:
+        from breezy.errors import NoSuchFile
 except ImportError:
     pass
 
 supportedkinds = ('file', 'symlink')
 
 
 class bzr_source(common.converter_source):
     """Reads Bazaar repositories by using the Bazaar Python libraries"""
@@ -145,17 +151,17 @@ class bzr_source(common.converter_source
         return heads
 
     def getfile(self, name, rev):
         name = name.decode()
         revtree = self.sourcerepo.revision_tree(rev)
 
         try:
             kind = revtree.kind(name)
-        except breezy.errors.NoSuchFile:
+        except NoSuchFile:
             return None, None
         if kind not in supportedkinds:
             # the file is not available anymore - was deleted
             return None, None
         mode = self._modecache[(name.encode(), rev)]
         if kind == 'symlink':
             target = revtree.get_symlink_target(name)
             if target is None:
diff --git a/hgext/convert/cvs.py b/hgext/convert/cvs.py
--- a/hgext/convert/cvs.py
+++ b/hgext/convert/cvs.py
@@ -137,17 +137,19 @@ class convert_cvs(converter_source):
         conntype = None
         user, host = None, None
         cmd = [b'cvs', b'server']
 
         self.ui.status(_(b"connecting to %s\n") % root)
 
         if root.startswith(b":pserver:"):
             root = root[9:]
-            m = re.match(r'(?:(.*?)(?::(.*?))?@)?([^:/]*)(?::(\d*))?(.*)', root)
+            m = re.match(
+                br'(?:(.*?)(?::(.*?))?@)?([^:/]*)(?::(\d*))?(.*)', root
+            )
             if m:
                 conntype = b"pserver"
                 user, passw, serv, port, root = m.groups()
                 if not user:
                     user = b"anonymous"
                 if not port:
                     port = 2401
                 else:
@@ -192,17 +194,17 @@ class convert_cvs(converter_source):
                             b"END AUTH REQUEST",
                             b"",
                         ]
                     )
                 )
                 if sck.recv(128) != b"I LOVE YOU\n":
                     raise error.Abort(_(b"CVS pserver authentication failed"))
 
-                self.writep = self.readp = sck.makefile(b'r+')
+                self.writep = self.readp = sck.makefile('rwb')
 
         if not conntype and root.startswith(b":local:"):
             conntype = b"local"
             root = root[7:]
 
         if not conntype:
             # :ext:user@host/home/user/path/to/cvsroot
             if root.startswith(b":ext:"):
diff --git a/hgext/convert/cvsps.py b/hgext/convert/cvsps.py
--- a/hgext/convert/cvsps.py
+++ b/hgext/convert/cvsps.py
@@ -681,17 +681,20 @@ def createchangeset(ui, log, fuzz=60, me
                 mergepoint=e.mergepoint,
                 branchpoints=e.branchpoints,
                 commitid=e.commitid,
             )
             changesets.append(c)
 
             files = set()
             if len(changesets) % 100 == 0:
-                t = b'%d %s' % (len(changesets), repr(e.comment)[1:-1])
+                t = b'%d %s' % (
+                    len(changesets),
+                    pycompat.byterepr(e.comment)[2:-1],
+                )
                 ui.status(stringutil.ellipsis(t, 80) + b'\n')
 
         c.entries.append(e)
         files.add(e.file)
         c.date = e.date  # changeset date is date of latest commit in it
 
     # Mark synthetic changesets
 
diff --git a/hgext/convert/darcs.py b/hgext/convert/darcs.py
--- a/hgext/convert/darcs.py
+++ b/hgext/convert/darcs.py
@@ -138,17 +138,17 @@ class darcs_source(common.converter_sour
         return man
 
     def getheads(self):
         return self.parents[None]
 
     def getcommit(self, rev):
         elt = self.changes[rev]
         dateformat = b'%a %b %d %H:%M:%S %Z %Y'
-        date = dateutil.strdate(elt.get('local_date'), dateformat)
+        date = dateutil.strdate(self.recode(elt.get('local_date')), dateformat)
         desc = elt.findtext('name') + '\n' + elt.findtext('comment', '')
         # etree can return unicode objects for name, comment, and author,
         # so recode() is used to ensure str objects are emitted.
         newdateformat = b'%Y-%m-%d %H:%M:%S %1%2'
         return common.commit(
             author=self.recode(elt.get('author')),
             date=dateutil.datestr(date, newdateformat),
             desc=self.recode(desc).strip(),
diff --git a/hgext/fix.py b/hgext/fix.py
--- a/hgext/fix.py
+++ b/hgext/fix.py
@@ -693,16 +693,19 @@ def fixfile(ui, repo, opts, fixers, fixc
     for fixername, fixer in fixers.items():
         if fixer.affects(opts, fixctx, path):
             ranges = lineranges(
                 opts, path, basepaths, basectxs, fixctx, newdata
             )
             command = fixer.command(ui, path, ranges)
             if command is None:
                 continue
+            msg = b'fixing: %s - %s - %s\n'
+            msg %= (fixctx, fixername, path)
+            ui.debug(msg)
             ui.debug(b'subprocess: %s\n' % (command,))
             proc = subprocess.Popen(
                 procutil.tonativestr(command),
                 shell=True,
                 cwd=procutil.tonativestr(repo.root),
                 stdin=subprocess.PIPE,
                 stdout=subprocess.PIPE,
                 stderr=subprocess.PIPE,
diff --git a/hgext/histedit.py b/hgext/histedit.py
--- a/hgext/histedit.py
+++ b/hgext/histedit.py
@@ -991,17 +991,17 @@ class base(histeditaction):
                 msg % (self.verb, short(self.node)),
                 hint=_(b'base must only use unlisted changesets'),
             )
 
 
 @action(
     [b'_multifold'],
     _(
-        """fold subclass used for when multiple folds happen in a row
+        b"""fold subclass used for when multiple folds happen in a row
 
     We only want to fire the editor for the folded message once when
     (say) four changes are folded down into a single change. This is
     similar to rollup, but we should preserve both messages so that
     when the last fold operation runs we can show the user all the
     commit messages in their editor.
     """
     ),
diff --git a/hgext/sparse.py b/hgext/sparse.py
--- a/hgext/sparse.py
+++ b/hgext/sparse.py
@@ -369,17 +369,17 @@ def debugsparse(ui, repo, **opts):
         sparse.importfromfiles(repo, opts, importrules, force=force)
 
     if clearrules:
         sparse.clearrules(repo, force=force)
 
     if refresh:
         try:
             wlock = repo.wlock()
-            fcounts = map(
+            fcounts = pycompat.maplist(
                 len,
                 sparse.refreshwdir(
                     repo, repo.status(), sparse.matcher(repo), force=force
                 ),
             )
             sparse.printchanges(
                 ui,
                 opts,
diff --git a/mercurial/bundlerepo.py b/mercurial/bundlerepo.py
--- a/mercurial/bundlerepo.py
+++ b/mercurial/bundlerepo.py
@@ -528,16 +528,18 @@ def makebundlerepository(ui, repopath, b
     # a repo instance. Then, we dynamically create a new type derived from
     # both it and our ``bundlerepository`` class which overrides some
     # functionality. We then change the type of the constructed repository
     # to this new type and initialize the bundle-specific bits of it.
 
     try:
         repo = localrepo.instance(ui, repopath, create=False)
         tempparent = None
+    except error.RequirementError:
+        raise  # no fallback if the backing repo is unsupported
     except error.RepoError:
         tempparent = pycompat.mkdtemp()
         try:
             repo = localrepo.instance(ui, tempparent, create=True)
         except Exception:
             shutil.rmtree(tempparent)
             raise
 
diff --git a/mercurial/commands.py b/mercurial/commands.py
--- a/mercurial/commands.py
+++ b/mercurial/commands.py
@@ -7467,16 +7467,19 @@ def tag(ui, repo, name1, *names, **opts)
                 raise error.InputError(
                     _(
                         b'working directory is not at a branch head '
                         b'(use -f to force)'
                     )
                 )
         node = logcmdutil.revsingle(repo, rev_).node()
 
+        if node is None:
+            raise error.InputError(_(b"cannot tag working directory"))
+
         if not message:
             # we don't translate commit messages
             message = b'Added tag %s for changeset %s' % (
                 b', '.join(names),
                 short(node),
             )
 
         date = opts.get(b'date')
diff --git a/mercurial/dirstate.py b/mercurial/dirstate.py
--- a/mercurial/dirstate.py
+++ b/mercurial/dirstate.py
@@ -1439,16 +1439,19 @@ class dirstate:
         if not self._use_dirstate_v2:
             return None
         return backupname + b'.v2-data'
 
     def _new_backup_data_filename(self, backupname):
         """return a filename to backup a data-file or None"""
         if not self._use_dirstate_v2:
             return None
+        if self._map.docket.uuid is None:
+            # not created yet, nothing to backup
+            return None
         data_filename = self._map.docket.data_filename()
         return data_filename, self.data_backup_filename(backupname)
 
     def backup_data_file(self, backupname):
         if not self._use_dirstate_v2:
             return None
         docket = docketmod.DirstateDocket.parse(
             self._opener.read(backupname),
@@ -1509,41 +1512,54 @@ class dirstate:
                 # end of this transaction
                 tr.registertmp(bck_data_filename, location=b'plain')
 
     def restorebackup(self, tr, backupname):
         '''Restore dirstate by backup file'''
         # this "invalidate()" prevents "wlock.release()" from writing
         # changes of dirstate out after restoring from backup file
         self.invalidate()
+        o = self._opener
+        if not o.exists(backupname):
+            # there was no file backup, delete existing files
+            filename = self._actualfilename(tr)
+            data_file = None
+            if self._use_dirstate_v2 and self._map.docket.uuid is not None:
+                data_file = self._map.docket.data_filename()
+            if o.exists(filename):
+                o.unlink(filename)
+            if data_file is not None and o.exists(data_file):
+                o.unlink(data_file)
+            return
         filename = self._actualfilename(tr)
-        o = self._opener
         data_pair = self.backup_data_file(backupname)
-        if util.samefile(o.join(backupname), o.join(filename)):
+        if o.exists(filename) and util.samefile(
+            o.join(backupname), o.join(filename)
+        ):
             o.unlink(backupname)
         else:
             o.rename(backupname, filename, checkambig=True)
 
         if data_pair is not None:
             data_backup, target = data_pair
             if o.exists(target) and util.samefile(
                 o.join(data_backup), o.join(target)
             ):
                 o.unlink(data_backup)
             else:
                 o.rename(data_backup, target, checkambig=True)
 
     def clearbackup(self, tr, backupname):
         '''Clear backup file'''
         o = self._opener
-        data_backup = self.backup_data_file(backupname)
-        o.unlink(backupname)
-
-        if data_backup is not None:
-            o.unlink(data_backup[0])
+        if o.exists(backupname):
+            data_backup = self.backup_data_file(backupname)
+            o.unlink(backupname)
+            if data_backup is not None:
+                o.unlink(data_backup[0])
 
     def verify(self, m1, m2):
         """check the dirstate content again the parent manifest and yield errors"""
         missing_from_p1 = b"%s in state %s, but not in manifest1\n"
         unexpected_in_p1 = b"%s in state %s, but also in manifest1\n"
         missing_from_ps = b"%s in state %s, but not in either manifest\n"
         missing_from_ds = b"%s in manifest1, but listed as state %s\n"
         for f, entry in self.items():
diff --git a/mercurial/dirstatemap.py b/mercurial/dirstatemap.py
--- a/mercurial/dirstatemap.py
+++ b/mercurial/dirstatemap.py
@@ -109,16 +109,18 @@ class _dirstatemapcommon:
             )
         return self._docket
 
     def write_v2_no_append(self, tr, st, meta, packed):
         old_docket = self.docket
         new_docket = docketmod.DirstateDocket.with_new_uuid(
             self.parents(), len(packed), meta
         )
+        if old_docket.uuid == new_docket.uuid:
+            raise error.ProgrammingError(b'dirstate docket name collision')
         data_filename = new_docket.data_filename()
         self._opener.write(data_filename, packed)
         # Write the new docket after the new data file has been
         # written. Because `st` was opened with `atomictemp=True`,
         # the actual `.hg/dirstate` file is only affected on close.
         st.write(new_docket.serialize())
         st.close()
         # Remove the old data file after the new docket pointing to
diff --git a/mercurial/hgweb/server.py b/mercurial/hgweb/server.py
--- a/mercurial/hgweb/server.py
+++ b/mercurial/hgweb/server.py
@@ -198,17 +198,17 @@ class _httprequesthandler(httpservermod.
             hkey = 'HTTP_' + header.replace('-', '_').upper()
             hval = self.headers.get(header)
             hval = hval.replace('\n', '').strip()
             if hval:
                 env[hkey] = hval
         env['SERVER_PROTOCOL'] = self.request_version
         env['wsgi.version'] = (1, 0)
         env['wsgi.url_scheme'] = pycompat.sysstr(self.url_scheme)
-        if env.get('HTTP_EXPECT', b'').lower() == b'100-continue':
+        if env.get('HTTP_EXPECT', '').lower() == '100-continue':
             self.rfile = common.continuereader(self.rfile, self.wfile.write)
 
         env['wsgi.input'] = self.rfile
         env['wsgi.errors'] = _error_logger(self)
         env['wsgi.multithread'] = isinstance(
             self.server, socketserver.ThreadingMixIn
         )
         if util.safehasattr(socketserver, b'ForkingMixIn'):
diff --git a/mercurial/revset.py b/mercurial/revset.py
--- a/mercurial/revset.py
+++ b/mercurial/revset.py
@@ -5,17 +5,16 @@
 # This software may be used and distributed according to the terms of the
 # GNU General Public License version 2 or any later version.
 
 
 import binascii
 import functools
 import random
 import re
-import sys
 
 from .i18n import _
 from .pycompat import getattr
 from .node import (
     bin,
     nullrev,
     wdirrev,
 )
@@ -2350,17 +2349,17 @@ def roots(repo, subset, x):
             for p in repo[None].parents():
                 if p.rev() in s:
                     return False
         return True
 
     return subset & s.filter(filter, condrepr=b'<roots>')
 
 
-MAXINT = sys.maxsize
+MAXINT = (1 << 31) - 1
 MININT = -MAXINT - 1
 
 
 def pick_random(c, gen=random):
     # exists as its own function to make it possible to overwrite the seed
     return gen.randint(MININT, MAXINT)
 
 
diff --git a/mercurial/scmutil.py b/mercurial/scmutil.py
--- a/mercurial/scmutil.py
+++ b/mercurial/scmutil.py
@@ -273,16 +273,21 @@ def checknewlabel(repo, lbl, kind):
         raise error.InputError(_(b"the name '%s' is reserved") % lbl)
     for c in (b':', b'\0', b'\n', b'\r'):
         if c in lbl:
             raise error.InputError(
                 _(b"%r cannot be used in a name") % pycompat.bytestr(c)
             )
     try:
         int(lbl)
+        if b'_' in lbl:
+            # If label contains underscores, Python might consider it an
+            # integer (with "_" as visual separators), but we do not.
+            # See PEP 515 - Underscores in Numeric Literals.
+            raise ValueError
         raise error.InputError(_(b"cannot use an integer as a name"))
     except ValueError:
         pass
     if lbl.strip() != lbl:
         raise error.InputError(
             _(b"leading or trailing whitespace in name %r") % lbl
         )
 
diff --git a/mercurial/utils/resourceutil.py b/mercurial/utils/resourceutil.py
--- a/mercurial/utils/resourceutil.py
+++ b/mercurial/utils/resourceutil.py
@@ -54,17 +54,20 @@ else:
 
 
 try:
     # importlib.resources exists from Python 3.7; see fallback in except clause
     # further down
     from importlib import resources  # pytype: disable=import-error
 
     # Force loading of the resources module
-    resources.open_binary  # pytype: disable=module-attr
+    if pycompat.safehasattr(resources, 'files'):
+        resources.files  # pytype: disable=module-attr
+    else:
+        resources.open_binary  # pytype: disable=module-attr
 
     # py2exe raises an AssertionError if uses importlib.resources
     if getattr(sys, "frozen", None) in ("console_exe", "windows_exe"):
         raise ImportError
 
 except (ImportError, AttributeError):
     # importlib.resources was not found (almost definitely because we're on a
     # Python version before 3.7)
@@ -87,19 +90,28 @@ except (ImportError, AttributeError):
         for p in os.listdir(path):
             yield pycompat.fsencode(p)
 
 
 else:
     from .. import encoding
 
     def open_resource(package, name):
-        return resources.open_binary(  # pytype: disable=module-attr
-            pycompat.sysstr(package), pycompat.sysstr(name)
-        )
+        if pycompat.safehasattr(resources, 'files'):
+            return (
+                resources.files(  # pytype: disable=module-attr
+                    pycompat.sysstr(package)
+                )
+                .joinpath(pycompat.sysstr(name))
+                .open('rb')
+            )
+        else:
+            return resources.open_binary(  # pytype: disable=module-attr
+                pycompat.sysstr(package), pycompat.sysstr(name)
+            )
 
     def is_resource(package, name):
         return resources.is_resource(  # pytype: disable=module-attr
             pycompat.sysstr(package), encoding.strfromlocal(name)
         )
 
     def contents(package):
         # pytype: disable=module-attr
diff --git a/relnotes/6.3 b/relnotes/6.3
--- a/relnotes/6.3
+++ b/relnotes/6.3
@@ -1,8 +1,28 @@
+= Mercurial 6.3.2 =
+
+ * [ecfc84b956a8] tests: expect the message from 1baf0fffd82f in test-hghave.t (issue6762)
+ * [5c095119bff4] tests: add the missing space to test-hghave.t (issue6762)
+ * [2c346c1c75ec] tests: use an all too familiar executable in test-run-tests.t (issue6661)
+ * [13c0e3b4fd35] tests: use `test -f` instead of `ls` to see if a file is present (issue6662)
+ * [8ced4ca30ea1] bisect: correct message about aborting an in-progress bisect (issue6527)
+ * filemerge: fix crash when using filesets in [partial-merge-tools]
+ * help: fix a py3 error interpolating Set into b'%s'
+ * match: make the FLAG_RE pattern a raw string
+ * python-compat: adapt to Python 3.11 BC breakage with `random.sample`
+ * rust-status: fix thread count ceiling
+ * hg: show the correct message when cloning an LFS repo with extension disabled
+ * extensions: process disabled external paths when `hgext` package is in-memory
+ * emitrevision: consider ancestors revision to emit as available base
+ * make: add a target for building pyoxidizer tests on macOS
+ * run-tests: support --pyoxidized on macOS
+ * packaging: add dependencies to the PyOxidizer build on macOS
+ * Miscellaneous test fixes
+
 = Mercurial 6.3.1 =
 
  * memory-usage: fix `hg log --follow --rev R F` space complexity (dcb2581e33be)
  * Improve portability and robustness of test harness
  * hg-core: relax dependencies pinning
  * matcher: fix issues regex flag contained in pattern (issue6759)
  * matcher: do not prepend '.*' to pattern using ^ after flags
  * packaging: refresh dependency hashes (issue6750)
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -227,19 +227,19 @@ source = "registry+https://github.com/ru
 checksum = "e54ea8bc3fb1ee042f5aace6e3c6e025d3874866da222930f70ce62aceba0bfa"
 dependencies = [
  "cfg-if 1.0.0",
  "crossbeam-utils",
 ]
 
 [[package]]
 name = "crossbeam-deque"
-version = "0.8.0"
+version = "0.8.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "94af6efb46fef72616855b036a624cf27ba656ffc9be1b9a3c931cfc7749a9a9"
+checksum = "715e8152b692bba2d374b53d4875445368fdf21a94751410af607a5ac677d1fc"
 dependencies = [
  "cfg-if 1.0.0",
  "crossbeam-epoch",
  "crossbeam-utils",
 ]
 
 [[package]]
 name = "crossbeam-epoch"
@@ -911,36 +911,33 @@ version = "0.4.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "a9fcdd2e881d02f1d9390ae47ad8e5696a9e4be7b547a1da2afbc61973217004"
 dependencies = [
  "rand_core 0.5.1",
 ]
 
 [[package]]
 name = "rayon"
-version = "1.5.1"
+version = "1.6.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c06aca804d41dbc8ba42dfd964f0d01334eceb64314b9ecf7c5fad5188a06d90"
+checksum = "6db3a213adf02b3bcfd2d3846bb41cb22857d131789e01df434fb7e7bc0759b7"
 dependencies = [
- "autocfg",
- "crossbeam-deque",
  "either",
  "rayon-core",
 ]
 
 [[package]]
 name = "rayon-core"
-version = "1.9.1"
+version = "1.10.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d78120e2c850279833f1dd3582f730c4ab53ed95aeaaaa862a2a5c71b1656d8e"
+checksum = "356a0625f1954f730c0201cdab48611198dc6ce21f4acff55089b5a78e6e835b"
 dependencies = [
  "crossbeam-channel",
  "crossbeam-deque",
  "crossbeam-utils",
- "lazy_static",
  "num_cpus",
 ]
 
 [[package]]
 name = "redox_syscall"
 version = "0.2.11"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "8380fe0152551244f0747b1bf41737e0f8a74f97a14ccefd1148187271634f3c"
diff --git a/rust/hg-core/Cargo.toml b/rust/hg-core/Cargo.toml
--- a/rust/hg-core/Cargo.toml
+++ b/rust/hg-core/Cargo.toml
@@ -18,17 +18,17 @@ home = "0.5.3"
 im-rc = "15.0"
 itertools = "0.10.3"
 lazy_static = "1.4.0"
 libc = "0.2"
 ouroboros = "0.15.0"
 rand = "0.8.4"
 rand_pcg = "0.3.1"
 rand_distr = "0.4.3"
-rayon = "1.5.1"
+rayon = "1.6.1"
 regex = "1.5.5"
 sha-1 = "0.10.0"
 twox-hash = "1.6.2"
 same-file = "1.0.6"
 tempfile = "3.1.0"
 thread_local = "1.1.4"
 crossbeam-channel = "0.5.0"
 micro-timer = "0.4.0"
diff --git a/rust/hg-core/src/narrow.rs b/rust/hg-core/src/narrow.rs
--- a/rust/hg-core/src/narrow.rs
+++ b/rust/hg-core/src/narrow.rs
@@ -95,17 +95,17 @@ pub fn matcher(
 
 fn validate_patterns(patterns: &[u8]) -> Result<(), SparseConfigError> {
     for pattern in patterns.split(|c| *c == b'\n') {
         if pattern.is_empty() {
             continue;
         }
         for prefix in VALID_PREFIXES.iter() {
             if pattern.starts_with(prefix.as_bytes()) {
-                break;
+                return Ok(());
             }
-            return Err(SparseConfigError::InvalidNarrowPrefix(
-                pattern.to_owned(),
-            ));
         }
+        return Err(SparseConfigError::InvalidNarrowPrefix(
+            pattern.to_owned(),
+        ));
     }
     Ok(())
 }
diff --git a/rust/rhg/Cargo.toml b/rust/rhg/Cargo.toml
--- a/rust/rhg/Cargo.toml
+++ b/rust/rhg/Cargo.toml
@@ -17,9 +17,9 @@ home = "0.5.3"
 lazy_static = "1.4.0"
 log = "0.4.14"
 micro-timer = "0.4.0"
 regex = "1.5.5"
 env_logger = "0.9.0"
 format-bytes = "0.3.0"
 users = "0.11.0"
 which = "4.2.5"
-rayon = "1.5.1"
+rayon = "1.6.1"
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -16,16 +16,21 @@ supportedpy = ','.join(
 import sys, platform
 import sysconfig
 
 
 def sysstr(s):
     return s.decode('latin-1')
 
 
+def eprint(*args, **kwargs):
+    kwargs['file'] = sys.stderr
+    print(*args, **kwargs)
+
+
 import ssl
 
 # ssl.HAS_TLSv1* are preferred to check support but they were added in Python
 # 3.7. Prior to CPython commit 6e8cda91d92da72800d891b2fc2073ecbc134d98
 # (backported to the 3.7 branch), ssl.PROTOCOL_TLSv1_1 / ssl.PROTOCOL_TLSv1_2
 # were defined only if compiled against a OpenSSL version with TLS 1.1 / 1.2
 # support. At the mentioned commit, they were unconditionally defined.
 _notset = object()
@@ -216,19 +221,20 @@ class hgcommand:
     def __init__(self, cmd, env):
         self.cmd = cmd
         self.env = env
 
     def run(self, args):
         cmd = self.cmd + args
         returncode, out, err = runcmd(cmd, self.env)
         err = filterhgerr(err)
-        if err or returncode != 0:
+        if err:
             print("stderr from '%s':" % (' '.join(cmd)), file=sys.stderr)
             print(err, file=sys.stderr)
+        if returncode != 0:
             return b''
         return out
 
 
 def filterhgerr(err):
     # If root is executing setup.py, but the repository is owned by
     # another user (as in "sudo python setup.py install") we will get
     # trust warnings since the .hg/hgrc file is untrusted. That is
@@ -286,20 +292,21 @@ def findhg():
     hgcmd = [sys.executable, 'hg']
     try:
         retcode, out, err = runcmd(hgcmd + check_cmd, hgenv)
     except EnvironmentError:
         retcode = -1
     if retcode == 0 and not filterhgerr(err):
         return hgcommand(hgcmd, hgenv)
 
-    raise SystemExit(
-        'Unable to find a working hg binary to extract the '
-        'version from the repository tags'
-    )
+    eprint("/!\\")
+    eprint(r"/!\ Unable to find a working hg binary")
+    eprint(r"/!\ Version cannot be extract from the repository")
+    eprint(r"/!\ Re-run the setup once a first version is built")
+    return None
 
 
 def localhgenv():
     """Get an environment dictionary to use for invoking or importing
     mercurial from the local repository."""
     # Execute hg out of this directory with a custom environment which takes
     # care to not use any hgrc files and do no localization.
     env = {
@@ -314,39 +321,56 @@ def localhgenv():
         # SystemRoot is required by Windows to load various DLLs.  See:
         # https://bugs.python.org/issue13524#msg148850
         env['SystemRoot'] = os.environ['SystemRoot']
     return env
 
 
 version = ''
 
-if os.path.isdir('.hg'):
+
+def _try_get_version():
     hg = findhg()
+    if hg is None:
+        return ''
+    hgid = None
+    numerictags = []
     cmd = ['log', '-r', '.', '--template', '{tags}\n']
-    numerictags = [t for t in sysstr(hg.run(cmd)).split() if t[0:1].isdigit()]
+    pieces = sysstr(hg.run(cmd)).split()
+    numerictags = [t for t in pieces if t[0:1].isdigit()]
     hgid = sysstr(hg.run(['id', '-i'])).strip()
     if not hgid:
-        # Bail out if hg is having problems interacting with this repository,
-        # rather than falling through and producing a bogus version number.
-        # Continuing with an invalid version number will break extensions
-        # that define minimumhgversion.
-        raise SystemExit('Unable to determine hg version from local repository')
+        eprint("/!\\")
+        eprint(r"/!\ Unable to determine hg version from local repository")
+        eprint(r"/!\ Failed to retrieve current revision tags")
+        return ''
     if numerictags:  # tag(s) found
         version = numerictags[-1]
         if hgid.endswith('+'):  # propagate the dirty status to the tag
             version += '+'
-    else:  # no tag found
+    else:  # no tag found on the checked out revision
         ltagcmd = ['parents', '--template', '{latesttag}']
         ltag = sysstr(hg.run(ltagcmd))
+        if not ltag:
+            eprint("/!\\")
+            eprint(r"/!\ Unable to determine hg version from local repository")
+            eprint(
+                r"/!\ Failed to retrieve current revision distance to lated tag"
+            )
+            return ''
         changessincecmd = ['log', '-T', 'x\n', '-r', "only(.,'%s')" % ltag]
         changessince = len(hg.run(changessincecmd).splitlines())
         version = '%s+hg%s.%s' % (ltag, changessince, hgid)
     if version.endswith('+'):
         version = version[:-1] + 'local' + time.strftime('%Y%m%d')
+    return version
+
+
+if os.path.isdir('.hg'):
+    version = _try_get_version()
 elif os.path.exists('.hg_archival.txt'):
     kw = dict(
         [[t.strip() for t in l.split(':', 1)] for l in open('.hg_archival.txt')]
     )
     if 'tag' in kw:
         version = kw['tag']
     elif 'latesttag' in kw:
         if 'changessincelatesttag' in kw:
@@ -356,31 +380,45 @@ elif os.path.exists('.hg_archival.txt'):
         else:
             version = '%(latesttag)s+hg%(latesttagdistance)s.%(node).12s' % kw
     else:
         version = '0+hg' + kw.get('node', '')[:12]
 elif os.path.exists('mercurial/__version__.py'):
     with open('mercurial/__version__.py') as f:
         data = f.read()
     version = re.search('version = b"(.*)"', data).group(1)
-
-if version:
-    versionb = version
-    if not isinstance(versionb, bytes):
-        versionb = versionb.encode('ascii')
+if not version:
+    if os.environ.get("MERCURIAL_SETUP_MAKE_LOCAL") == "1":
+        version = "0.0+0"
+        eprint("/!\\")
+        eprint(r"/!\ Using '0.0+0' as the default version")
+        eprint(r"/!\ Re-run make local once that first version is built")
+        eprint("/!\\")
+    else:
+        eprint("/!\\")
+        eprint(r"/!\ Could not determine the Mercurial version")
+        eprint(r"/!\ You need to build a local version first")
+        eprint(r"/!\ Run `make local` and try again")
+        eprint("/!\\")
+        msg = "Run `make local` first to get a working local version"
+        raise SystemExit(msg)
 
-    write_if_changed(
-        'mercurial/__version__.py',
-        b''.join(
-            [
-                b'# this file is autogenerated by setup.py\n'
-                b'version = b"%s"\n' % versionb,
-            ]
-        ),
-    )
+versionb = version
+if not isinstance(versionb, bytes):
+    versionb = versionb.encode('ascii')
+
+write_if_changed(
+    'mercurial/__version__.py',
+    b''.join(
+        [
+            b'# this file is autogenerated by setup.py\n'
+            b'version = b"%s"\n' % versionb,
+        ]
+    ),
+)
 
 
 class hgbuild(build):
     # Insert hgbuildmo first so that files in mercurial/locale/ are found
     # when build_py is run next.
     sub_commands = [('build_mo', None)] + build.sub_commands
 
 
diff --git a/tests/filtertraceback.py b/tests/filtertraceback.py
--- a/tests/filtertraceback.py
+++ b/tests/filtertraceback.py
@@ -26,14 +26,19 @@ for line in sys.stdin:
     elif state == 'tb':
         if line.startswith('  File '):
             state = 'file'
             continue
 
         elif not line.startswith(' '):
             state = 'none'
 
+        elif not line.replace('^', '').replace('~', '').strip():
+            # PEP 657: Fine-grained error locations in tracebacks
+            #                       ~~~~~~^^^^^^^^^
+            continue
+
     elif state == 'file':
         # Ignore lines after "  File "
         state = 'tb'
         continue
 
     print(line, end='')
diff --git a/tests/hghave.py b/tests/hghave.py
--- a/tests/hghave.py
+++ b/tests/hghave.py
@@ -201,25 +201,25 @@ def has_rhg():
 def has_pyoxidizer():
     return 'PYOXIDIZED_INSTALLED_AS_HG' in os.environ
 
 
 @check(
     "pyoxidizer-in-memory",
     "running with pyoxidizer build as 'hg' with embedded resources",
 )
-def has_pyoxidizer():
+def has_pyoxidizer_mem():
     return 'PYOXIDIZED_IN_MEMORY_RSRC' in os.environ
 
 
 @check(
     "pyoxidizer-in-filesystem",
     "running with pyoxidizer build as 'hg' with external resources",
 )
-def has_pyoxidizer():
+def has_pyoxidizer_fs():
     return 'PYOXIDIZED_FILESYSTEM_RSRC' in os.environ
 
 
 @check("cvs", "cvs client/server")
 def has_cvs():
     re = br'Concurrent Versions System.*?server'
     return matchoutput('cvs --version 2>&1', re) and not has_msys()
 
@@ -656,46 +656,32 @@ def has_pygments():
         import pygments
 
         pygments.highlight  # silence unused import warning
         return True
     except ImportError:
         return False
 
 
-@check("pygments25", "Pygments version >= 2.5")
-def pygments25():
+def getpygmentsversion():
     try:
         import pygments
 
         v = pygments.__version__
+
+        parts = v.split(".")
+        return (int(parts[0]), int(parts[1]))
     except ImportError:
-        return False
-
-    parts = v.split(".")
-    major = int(parts[0])
-    minor = int(parts[1])
-
-    return (major, minor) >= (2, 5)
+        return (0, 0)
 
 
-@check("pygments211", "Pygments version >= 2.11")
-def pygments211():
-    try:
-        import pygments
-
-        v = pygments.__version__
-    except ImportError:
-        return False
-
-    parts = v.split(".")
-    major = int(parts[0])
-    minor = int(parts[1])
-
-    return (major, minor) >= (2, 11)
+@checkvers("pygments", "Pygments version >= %s", (2.5, 2.11, 2.14))
+def has_pygments_range(v):
+    major, minor = v.split('.')[0:2]
+    return getpygmentsversion() >= (int(major), int(minor))
 
 
 @check("outer-repo", "outer repo")
 def has_outer_repo():
     # failing for other reasons than 'no repo' imply that there is a repo
     return not matchoutput('hg root 2>&1', br'abort: no repository found', True)
 
 
diff --git a/tests/test-branches.t b/tests/test-branches.t
--- a/tests/test-branches.t
+++ b/tests/test-branches.t
@@ -77,16 +77,21 @@ trailing or leading spaces should be str
   (use 'hg update' to switch to it)
   [10]
 
   $ hg branch ' b'
   abort: a branch of the same name already exists
   (use 'hg update' to switch to it)
   [10]
 
+underscores in numeric branch names (issue6737)
+
+  $ hg branch 2700_210
+  marked working directory as branch 2700_210
+
 verify update will accept invalid legacy branch names
 
   $ hg init test-invalid-branch-name
   $ cd test-invalid-branch-name
   $ hg unbundle -u "$TESTDIR"/bundles/test-invalid-branch-name.hg
   adding changesets
   adding manifests
   adding file changes
diff --git a/tests/test-check-shbang.t b/tests/test-check-shbang.t
--- a/tests/test-check-shbang.t
+++ b/tests/test-check-shbang.t
@@ -9,17 +9,18 @@ look for python scripts that do not use 
   [1]
 
 In tests, enforce $PYTHON and *not* /usr/bin/env python or similar:
   $ testrepohg files 'set:grep(r"#!.*?python") and **/*.t' \
   > -X tests/test-check-execute.t \
   > -X tests/test-check-format.t \
   > -X tests/test-check-module-imports.t \
   > -X tests/test-check-pyflakes.t \
-  > -X tests/test-check-shbang.t
+  > -X tests/test-check-shbang.t \
+  > -X tests/test-highlight.t
   [1]
 
 The above exclusions are because they're looking for files that
 contain Python but don't end in .py - please avoid adding more.
 
 look for shell scripts that do not use /bin/sh
 
   $ testrepohg files 'set:grep(r"^#!.*/bi{1}n/sh") and not grep(r"^#!/bi{1}n/sh")'
diff --git a/tests/test-chg.t b/tests/test-chg.t
--- a/tests/test-chg.t
+++ b/tests/test-chg.t
@@ -347,21 +347,20 @@ remove foo
   $ hg debugexpandscheme bar://expanded
   https://bar.example.org/expanded
 
   $ cd ..
 
 repository cache
 ----------------
 
-  $ rm log/server.log*
   $ cp $HGRCPATH.unconfigured $HGRCPATH
   $ cat <<'EOF' >> $HGRCPATH
   > [cmdserver]
-  > log = $TESTTMP/log/server.log
+  > log = $TESTTMP/log/server-cached.log
   > max-repo-cache = 1
   > track-log = command, repocache
   > EOF
 
 isolate socket directory for stable result:
 
   $ OLDCHGSOCKNAME=$CHGSOCKNAME
   $ mkdir chgsock
@@ -415,19 +414,17 @@ read uncached repo:
 shut down servers and restore environment:
 
   $ rm -R chgsock
   $ sleep 2
   $ CHGSOCKNAME=$OLDCHGSOCKNAME
 
 check server log:
 
-  $ cat log/server.log | filterlog
-  YYYY/MM/DD HH:MM:SS (PID)> worker process exited (pid=...)
-  YYYY/MM/DD HH:MM:SS (PID)> worker process exited (pid=...) (?)
+  $ cat log/server-cached.log | filterlog
   YYYY/MM/DD HH:MM:SS (PID)> init cached
   YYYY/MM/DD HH:MM:SS (PID)> id -R cached
   YYYY/MM/DD HH:MM:SS (PID)> loaded repo into cache: $TESTTMP/cached (in  ...s)
   YYYY/MM/DD HH:MM:SS (PID)> repo from cache: $TESTTMP/cached
   YYYY/MM/DD HH:MM:SS (PID)> ci -R cached -Am 'add a'
   YYYY/MM/DD HH:MM:SS (PID)> loaded repo into cache: $TESTTMP/cached (in  ...s)
   YYYY/MM/DD HH:MM:SS (PID)> repo from cache: $TESTTMP/cached
   YYYY/MM/DD HH:MM:SS (PID)> log -R cached
diff --git a/tests/test-demandimport.py b/tests/test-demandimport.py
--- a/tests/test-demandimport.py
+++ b/tests/test-demandimport.py
@@ -4,16 +4,17 @@ demandimport.enable()
 
 import os
 import subprocess
 import sys
 import types
 
 # Don't import pycompat because it has too many side-effects.
 ispy3 = sys.version_info[0] >= 3
+ispy311 = (sys.version_info.major, sys.version_info.minor) >= (3, 11)
 
 # Only run if demandimport is allowed
 if subprocess.call(
     [os.environ['PYTHON'], '%s/hghave' % os.environ['TESTDIR'], 'demandimport']
 ):
     sys.exit(80)
 
 # We rely on assert, which gets optimized out.
@@ -76,18 +77,17 @@ else:
 del os.environ['HGDEMANDIMPORT']
 demandimport.enable()
 
 # Test access to special attributes through demandmod proxy
 assert 'mercurial.error' not in sys.modules
 from mercurial import error as errorproxy
 
 if ispy3:
-    # unsure why this isn't lazy.
-    assert not isinstance(f, _LazyModule)
+    assert isinstance(errorproxy, _LazyModule)
     assert f(errorproxy) == "<module 'mercurial.error' from '?'>", f(errorproxy)
 else:
     assert f(errorproxy) == "<unloaded module 'error'>", f(errorproxy)
 
 doc = ' '.join(errorproxy.__doc__.split()[:3])
 assert doc == 'Mercurial exceptions. This', doc
 assert errorproxy.__name__ == 'mercurial.error', errorproxy.__name__
 
@@ -101,22 +101,28 @@ if ispy3:
     assert f(errorproxy) == "<module 'mercurial.error' from '?'>", f(errorproxy)
 else:
     assert f(errorproxy) == "<proxied module 'error'>", f(errorproxy)
 
 import os
 
 if ispy3:
     assert not isinstance(os, _LazyModule)
-    assert f(os) == "<module 'os' from '?'>", f(os)
+    if ispy311:
+        assert f(os) == "<module 'os' (frozen)>", f(os)
+    else:
+        assert f(os) == "<module 'os' from '?'>", f(os)
 else:
     assert f(os) == "<unloaded module 'os'>", f(os)
 
 assert f(os.system) == '<built-in function system>', f(os.system)
-assert f(os) == "<module 'os' from '?'>", f(os)
+if ispy311:
+    assert f(os) == "<module 'os' (frozen)>", f(os)
+else:
+    assert f(os) == "<module 'os' from '?'>", f(os)
 
 assert 'mercurial.utils.procutil' not in sys.modules
 from mercurial.utils import procutil
 
 if ispy3:
     assert isinstance(procutil, _LazyModule)
     assert f(procutil) == "<module 'mercurial.utils.procutil' from '?'>", f(
         procutil
diff --git a/tests/test-extension.t b/tests/test-extension.t
--- a/tests/test-extension.t
+++ b/tests/test-extension.t
@@ -593,16 +593,17 @@ Make sure a broken uisetup doesn't globa
 Even though the extension fails during uisetup, hg is still basically usable:
   $ hg --config extensions.baduisetup=$TESTTMP/baduisetup.py version
   Traceback (most recent call last):
     File "*/mercurial/extensions.py", line *, in _runuisetup (glob) (no-pyoxidizer !)
     File "mercurial.extensions", line *, in _runuisetup (glob) (pyoxidizer !)
       uisetup(ui)
     File "$TESTTMP/baduisetup.py", line 2, in uisetup
       1 / 0
+      ~~^~~ (py311 !)
   ZeroDivisionError: * by zero (glob)
   *** failed to set up extension baduisetup: * by zero (glob)
   Mercurial Distributed SCM (version *) (glob)
   (see https://mercurial-scm.org for more information)
   
   Copyright (C) 2005-* Olivia Mackall and others (glob)
   This is free software; see the source for copying conditions. There is NO
   warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
diff --git a/tests/test-fix.t b/tests/test-fix.t
--- a/tests/test-fix.t
+++ b/tests/test-fix.t
@@ -1148,16 +1148,17 @@ useful for anyone trying to set up a new
 
   $ hg init debugoutput
   $ cd debugoutput
 
   $ printf "foo\nbar\nbaz\n" > foo.changed
   $ hg commit -Aqm "foo"
   $ printf "Foo\nbar\nBaz\n" > foo.changed
   $ hg --debug fix --working-dir
+  fixing: f65cf3136d41+ - uppercase-changed-lines - foo.changed
   subprocess: * $TESTTMP/uppercase.py 1-1 3-3 (glob)
 
   $ cd ..
 
 Fixing an obsolete revision can cause divergence, so we abort unless the user
 configures to allow it. This is not yet smart enough to know whether there is a
 successor, but even then it is not likely intentional or idiomatic to fix an
 obsolete revision.
diff --git a/tests/test-highlight.t b/tests/test-highlight.t
--- a/tests/test-highlight.t
+++ b/tests/test-highlight.t
@@ -158,17 +158,18 @@ hgweb filerevision, html
   <span id="l2"></span><a href="#l2"></a>
   <span id="l3"><span class="sd">primes = 2 : sieve [3, 5..]</span></span><a href="#l3"></a>
   <span id="l4"><span class="sd">    where sieve (p:ns) = p : sieve [n | n &lt;- ns, mod n p /= 0]</span></span><a href="#l4"></a>
   <span id="l5"><span class="sd">&quot;&quot;&quot;</span></span><a href="#l5"></a>
   <span id="l6"></span><a href="#l6"></a>
   <span id="l7"><span class="kn">import</span> <span class="nn">itertools</span></span><a href="#l7"></a>
   <span id="l8"></span><a href="#l8"></a>
   <span id="l9"><span class="kn">def</span> <span class="nf">primes</span><span class="p">():</span></span><a href="#l9"></a>
-  <span id="l10">    <span class="sd">&quot;&quot;&quot;Generate all primes.&quot;&quot;&quot;</span></span><a href="#l10"></a>
+  <span id="l10"><span class="w">    </span><span class="sd">&quot;&quot;&quot;Generate all primes.&quot;&quot;&quot;</span></span><a href="#l10"></a> (pygments214 !)
+  <span id="l10">    <span class="sd">&quot;&quot;&quot;Generate all primes.&quot;&quot;&quot;</span></span><a href="#l10"></a> (no-pygments214 !)
   <span id="l11">    <span class="kn">def</span> <span class="nf">sieve</span><span class="p">(</span><span class="n">ns</span><span class="p">):</span></span><a href="#l11"></a>
   <span id="l12">        <span class="n">p</span> <span class="o">=</span> <span class="n">ns</span><span class="o">.</span><span class="n">next</span><span class="p">()</span></span><a href="#l12"></a>
   <span id="l13">        <span class="c"># It is important to yield *here* in order to stop the</span></span><a href="#l13"></a>
   <span id="l14">        <span class="c"># infinite recursion.</span></span><a href="#l14"></a>
   <span id="l15">        <span class="kn">yield</span> <span class="n">p</span></span><a href="#l15"></a>
   <span id="l16">        <span class="n">ns</span> <span class="o">=</span> <span class="n">itertools</span><span class="o">.</span><span class="n">ifilter</span><span class="p">(</span><span class="kn">lambda</span> <span class="n">n</span><span class="p">:</span> <span class="n">n</span> <span class="o">%</span> <span class="n">p</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">,</span> <span class="n">ns</span><span class="p">)</span></span><a href="#l16"></a>
   <span id="l17">        <span class="kn">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="n">sieve</span><span class="p">(</span><span class="n">ns</span><span class="p">):</span></span><a href="#l17"></a>
   <span id="l18">            <span class="kn">yield</span> <span class="n">n</span></span><a href="#l18"></a>
@@ -484,17 +485,18 @@ hgweb fileannotate, html
   a
   </div>
   <div><em>&#116;&#101;&#115;&#116;</em></div>
   <div>parents: </div>
   <a href="/diff/687f2d169546/primes.py">diff</a>
   <a href="/rev/687f2d169546">changeset</a>
   </div>
   </td>
-  <td class="source followlines-btn-parent"><a href="#l10">    10</a>     <span class="sd">&quot;&quot;&quot;Generate all primes.&quot;&quot;&quot;</span></td>
+  <td class="source followlines-btn-parent"><a href="#l10">    10</a> <span class="w">    </span><span class="sd">&quot;&quot;&quot;Generate all primes.&quot;&quot;&quot;</span></td> (pygments214 !)
+  <td class="source followlines-btn-parent"><a href="#l10">    10</a>     <span class="sd">&quot;&quot;&quot;Generate all primes.&quot;&quot;&quot;</span></td> (no-pygments214 !)
   </tr>
   <tr id="l11" class="thisrev">
   <td class="annotate parity0">
   
   <div class="annotate-info">
   <div>
   <a href="/annotate/687f2d169546/primes.py#l11">
   687f2d169546</a>
@@ -1003,17 +1005,17 @@ We attempt to highlight unknown files by
   $ killdaemons.py
 
   $ cat > .hg/hgrc << EOF
   > [web]
   > highlightfiles = **
   > EOF
 
   $ cat > unknownfile << EOF
-  > #!$PYTHON
+  > #!/this/helps/pygments/detect/python
   > def foo():
   >    pass
   > EOF
 
   $ hg add unknownfile
   $ hg commit -m unknown unknownfile
 
   $ hg serve -p $HGPORT -d -n test --pid-file=hg.pid
diff --git a/tests/test-lfs-serve-access.t b/tests/test-lfs-serve-access.t
--- a/tests/test-lfs-serve-access.t
+++ b/tests/test-lfs-serve-access.t
@@ -335,22 +335,24 @@ Test a checksum failure during the proce
   $LOCALIP - - [$LOGDATE$] "GET /.hg/lfs/objects/276f73cfd75f9fb519810df5f5d96d6594ca2521abd86cbcd92122f7d51a1f3d HTTP/1.1" 500 - (glob)
   $LOCALIP - - [$LOGDATE$] "POST /.git/info/lfs/objects/batch HTTP/1.1" 200 - (glob)
   $LOCALIP - - [$LOGDATE$] "GET /.hg/lfs/objects/276f73cfd75f9fb519810df5f5d96d6594ca2521abd86cbcd92122f7d51a1f3d HTTP/1.1" 422 - (glob)
 
   $ grep -v '  File "' $TESTTMP/errors.log
   $LOCALIP - - [$ERRDATE$] HG error:  Exception happened while processing request '/.git/info/lfs/objects/batch': (glob)
   $LOCALIP - - [$ERRDATE$] HG error:  Traceback (most recent call last): (glob)
   $LOCALIP - - [$ERRDATE$] HG error:      verifies = store.verify(oid) (glob)
+  $LOCALIP - - [$ERRDATE$] HG error:                 ^^^^^^^^^^^^^^^^^ (glob) (py311 !)
   $LOCALIP - - [$ERRDATE$] HG error:      raise IOError(errno.EIO, r'%s: I/O error' % oid.decode("utf-8")) (glob)
   $LOCALIP - - [$ERRDATE$] HG error:  *Error: [Errno *] f03217a32529a28a42d03b1244fe09b6e0f9fd06d7b966d4d50567be2abe6c0e: I/O error (glob)
   $LOCALIP - - [$ERRDATE$] HG error:   (glob)
   $LOCALIP - - [$ERRDATE$] HG error:  Exception happened while processing request '/.git/info/lfs/objects/batch': (glob)
   $LOCALIP - - [$ERRDATE$] HG error:  Traceback (most recent call last): (glob)
   $LOCALIP - - [$ERRDATE$] HG error:      verifies = store.verify(oid) (glob)
+  $LOCALIP - - [$ERRDATE$] HG error:                 ^^^^^^^^^^^^^^^^^ (glob) (py311 !)
   $LOCALIP - - [$ERRDATE$] HG error:      raise IOError(errno.EIO, r'%s: I/O error' % oid.decode("utf-8")) (glob)
   $LOCALIP - - [$ERRDATE$] HG error:  *Error: [Errno *] b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c: I/O error (glob)
   $LOCALIP - - [$ERRDATE$] HG error:   (glob)
   $LOCALIP - - [$ERRDATE$] HG error:  Exception happened while processing request '/.hg/lfs/objects/b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c': (glob)
   $LOCALIP - - [$ERRDATE$] HG error:  Traceback (most recent call last): (glob)
   $LOCALIP - - [$ERRDATE$] HG error:      localstore.download(oid, req.bodyfh, req.headers[b'Content-Length'])
   $LOCALIP - - [$ERRDATE$] HG error:      super(badstore, self).download(oid, src, contentlength)
   $LOCALIP - - [$ERRDATE$] HG error:      raise LfsCorruptionError( (glob) (py38 !)
@@ -358,29 +360,36 @@ Test a checksum failure during the proce
   $LOCALIP - - [$ERRDATE$] HG error:  hgext.lfs.blobstore.LfsCorruptionError: corrupt remote lfs object: b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c (py3 !)
   $LOCALIP - - [$ERRDATE$] HG error:   (glob)
   $LOCALIP - - [$ERRDATE$] Exception happened during processing request '/.hg/lfs/objects/276f73cfd75f9fb519810df5f5d96d6594ca2521abd86cbcd92122f7d51a1f3d': (glob)
   Traceback (most recent call last):
       self.do_write()
       self.do_hgweb()
       for chunk in self.server.application(env, self._start_response):
       for r in self._runwsgi(req, res, repo):
+               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ (py311 !)
       handled = wireprotoserver.handlewsgirequest( (py38 !)
+                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ (py311 !)
       return _processbasictransfer( (py38 !)
+             ^^^^^^^^^^^^^^^^^^^^^^ (py311 !)
       rctx, req, res, self.check_perm (no-py38 !)
       rctx.repo, req, res, lambda perm: checkperm(rctx, req, perm) (no-py38 !)
       res.setbodybytes(localstore.read(oid))
+                       ^^^^^^^^^^^^^^^^^^^^ (py311 !)
       blob = self._read(self.vfs, oid, verify)
+             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ (py311 !)
       raise IOError(errno.EIO, r'%s: I/O error' % oid.decode("utf-8"))
   *Error: [Errno *] 276f73cfd75f9fb519810df5f5d96d6594ca2521abd86cbcd92122f7d51a1f3d: I/O error (glob)
   
   $LOCALIP - - [$ERRDATE$] HG error:  Exception happened while processing request '/.hg/lfs/objects/276f73cfd75f9fb519810df5f5d96d6594ca2521abd86cbcd92122f7d51a1f3d': (glob)
   $LOCALIP - - [$ERRDATE$] HG error:  Traceback (most recent call last): (glob)
   $LOCALIP - - [$ERRDATE$] HG error:      res.setbodybytes(localstore.read(oid)) (glob)
+  $LOCALIP - - [$ERRDATE$] HG error:                       ^^^^^^^^^^^^^^^^^^^^ (glob) (py311 !)
   $LOCALIP - - [$ERRDATE$] HG error:      blob = self._read(self.vfs, oid, verify) (glob)
+  $LOCALIP - - [$ERRDATE$] HG error:             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ (glob) (py311 !)
   $LOCALIP - - [$ERRDATE$] HG error:      blobstore._verify(oid, b'dummy content') (glob)
   $LOCALIP - - [$ERRDATE$] HG error:      raise LfsCorruptionError( (glob) (py38 !)
   $LOCALIP - - [$ERRDATE$] HG error:      hint=_(b'run hg verify'), (glob) (no-py38 !)
   $LOCALIP - - [$ERRDATE$] HG error:  hgext.lfs.blobstore.LfsCorruptionError: detected corrupt lfs object: 276f73cfd75f9fb519810df5f5d96d6594ca2521abd86cbcd92122f7d51a1f3d (py3 !)
   $LOCALIP - - [$ERRDATE$] HG error:   (glob)
 
 Basic Authorization headers are returned by the Batch API, and sent back with
 the GET/PUT request.
diff --git a/tests/test-narrow-clone.t b/tests/test-narrow-clone.t
--- a/tests/test-narrow-clone.t
+++ b/tests/test-narrow-clone.t
@@ -23,16 +23,28 @@ Only path: and rootfilesin: pattern pref
   (narrow patterns must begin with one of the following: path:, rootfilesin:)
   [255]
 
   $ hg clone --narrow ssh://user@dummy/master badnarrow --noupdate --exclude 'set:ignored'
   abort: invalid prefix on narrow pattern: set:ignored
   (narrow patterns must begin with one of the following: path:, rootfilesin:)
   [255]
 
+rootfilesin: patterns work
+
+  $ hg clone --narrow ssh://user@dummy/master rootfilesin --noupdate --include 'rootfilesin:dir'
+  requesting all changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 1 changesets with 0 changes to 0 files
+  new changesets 26ce255d5b5d
+  $ hg tracked -R rootfilesin
+  I rootfilesin:dir
+
 narrow clone a file, f10
 
   $ hg clone --narrow ssh://user@dummy/master narrow --noupdate --include "dir/src/f10"
   requesting all changes
   adding changesets
   adding manifests
   adding file changes
   added 3 changesets with 1 changes to 1 files
diff --git a/tests/test-remotefilelog-local.t b/tests/test-remotefilelog-local.t
--- a/tests/test-remotefilelog-local.t
+++ b/tests/test-remotefilelog-local.t
@@ -72,16 +72,21 @@
   2 files updated, 0 files merged, 1 files removed, 0 files unresolved
   $ clearcache
   $ hg debugdirstate
   n 644          2 * x (glob)
   n 644          2 * y (glob)
   n 644          2 * z (glob)
   $ echo xxxx > x
   $ echo yyyy > y
+# run status early to avoid a flaky second fetch during commit.
+  $ hg st
+  M x
+  M y
+  \d+ files fetched over \d+ fetches .* (re) (?)
   $ hg commit -m x
   created new head
   2 files fetched over 1 fetches - (2 misses, 0.00% hit ratio) over *s (glob)
 
 # restore state for future tests
 
   $ hg -q strip .
   $ hg -q up tip
@@ -99,16 +104,19 @@
   searching for changes
   adding changesets
   adding manifests
   adding file changes
   added 1 changesets with 0 changes to 0 files (+1 heads)
   new changesets fed61014d323
   (run 'hg heads' to see heads, 'hg merge' to merge)
 
+# run status early to avoid a flaky second fetch during commit
+  $ hg status
+  \d+ files fetched over \d+ fetches .* (re) (?)
   $ hg rebase -d tip
   rebasing 1:9abfe7bca547 "a"
   saved backup bundle to $TESTTMP/shallow/.hg/strip-backup/9abfe7bca547-8b11e5ff-rebase.hg (glob)
   3 files fetched over 2 fetches - (3 misses, 0.00% hit ratio) over *s (glob)
 
 # strip
 
   $ clearcache
diff --git a/tests/test-requires.t b/tests/test-requires.t
--- a/tests/test-requires.t
+++ b/tests/test-requires.t
@@ -76,9 +76,19 @@ another repository of push/pull/clone on
   $ hg clone supported clone-dst
   abort: repository requires features unknown to this Mercurial: featuresetup-test
   (see https://mercurial-scm.org/wiki/MissingRequirement for more information)
   [255]
   $ hg clone --pull supported clone-dst
   abort: required features are not supported in the destination: featuresetup-test
   [255]
 
+Bundlerepo also enforces the underlying repo requirements
+
+  $ hg --cwd supported bundle --all ../bundle.hg
+  1 changesets found
+  $ echo outdoor-pool > push-dst/.hg/requires
+  $ hg --cwd push-dst log -R ../bundle.hg -T phases
+  abort: repository requires features unknown to this Mercurial: outdoor-pool
+  (see https://mercurial-scm.org/wiki/MissingRequirement for more information)
+  [255]
+
   $ cd ..
diff --git a/tests/test-revset.t b/tests/test-revset.t
--- a/tests/test-revset.t
+++ b/tests/test-revset.t
@@ -2976,26 +2976,26 @@ test sorting by multiple keys including 
 
 random sort
 
   $ hg log --rev 'sort(all(), "random")' | wc -l
   \s*8 (re)
   $ hg log --rev 'sort(all(), "-random")' | wc -l
   \s*8 (re)
   $ hg log --rev 'sort(all(), "random", random.seed=celeste)'
+  0 b12  m111 u112 111 10800
+  4 b111 m112 u111 110 14400
+  2 b111 m11  u12  111 3600
   6 b111 t2   tu   130 0
+  1 b11  m12  u111 112 7200
   7 b111 t3   tu   130 0
-  4 b111 m112 u111 110 14400
-  3 b112 m111 u11  120 0
   5 b111 t1   tu   130 0
+  3 b112 m111 u11  120 0
+  $ hg log --rev 'first(sort(all(), "random", random.seed=celeste))'
   0 b12  m111 u112 111 10800
-  1 b11  m12  u111 112 7200
-  2 b111 m11  u12  111 3600
-  $ hg log --rev 'first(sort(all(), "random", random.seed=celeste))'
-  6 b111 t2   tu   130 0
 
 
 topographical sorting can't be combined with other sort keys, and you can't
 use the topo.firstbranch option when topo sort is not active:
 
   $ hg log -r 'sort(all(), "topo user")'
   hg: parse error: topo sort order cannot be combined with other sort keys
   [10]
diff --git a/tests/test-tag.t b/tests/test-tag.t
--- a/tests/test-tag.t
+++ b/tests/test-tag.t
@@ -407,16 +407,20 @@ tagging on null rev
   $ hg tag -R empty nullrev
   abort: cannot tag null revision
   [10]
 
   $ hg tag -R empty -r 00000000000 -f nulltag
   abort: cannot tag null revision
   [10]
 
+  $ hg tag -R empty -r "wdir()" -f wdirtag
+  abort: cannot tag working directory
+  [10]
+
 issue5539: pruned tags do not appear in .hgtags
 
   $ cat >> $HGRCPATH << EOF
   > [experimental]
   > evolution.exchange = True
   > evolution.createmarkers=True
   > EOF
   $ hg up e4d483960b9b --quiet
