sync: add repo.smartsyncdefault checkout policy

Workspace managers that provision repo checkouts need a way to make
Smart Sync the default for branches that define a manifest server,
without silently falling back to ToT on Smart Sync failures (where
unapproved or broken ToT trees defeat the point of Smart Sync).

Previously, setting repo.smartsync=true on init had two drawbacks:
it overrode per-user sync.smartsync=false and manifest-level opt-outs,
and default Smart Sync failures still fell back silently to ToT.
Removing <manifest-server> from a branch manifest to opt out also broke
explicit -s/-t syncs.

With repo.smartsyncdefault=explicit configured on a checkout:

- Plain repo sync enables Smart Sync whenever the manifest defines
  <manifest-server>, unless overridden by CLI flags, repo.smartsync,
  sync.smartsync, or <default sync-smartsync="false"/>.
- Default-enabled Smart Sync failures abort the sync instead of
  falling back to ToT, and print a hint pointing users to
  --no-smart-sync (or --head) to bypass Smart Sync for that sync.
- Branches without <manifest-server> or with
  <default sync-smartsync="false"/> sync ToT by default while keeping
  explicit -s/-t functional.

Bug: 543101585
Bug: 568962967
Test: pytest tests/test_manifest_xml.py tests/test_project.py
Test: pytest tests/test_subcmds_sync.py tests/e2e/test_init_sync.py
Change-Id: I5de45544df84366592978dd81c01e10dae964a1e
Reviewed-on: https://gerrit-review.googlesource.com/c/git-repo/+/658243
Tested-by: Rahul Yadav <yadavrah@google.com>
Reviewed-by: Gavin Mak <gavinmak@google.com>
Commit-Queue: Rahul Yadav <yadavrah@google.com>
This commit is contained in:
Rahul Yadav authored and gerrit-scoped@luci-project-accounts.iam.gserviceaccount.com committed 2026-11-23 11:08:55 -08:00
1 parent 344ec87370
commit affca0d4ab
11 files changed
+385 -28

No files matched your search

+1
View File
@@ -181,6 +181,7 @@ User controlled settings are initialized when running `repo init`.
| repo.partialcloneexclude | `--partial-clone-exclude` | Comma-delimited list of project names (not paths) to exclude while using [partial git clones] |
| repo.reference | `--reference` | Reference repo client checkout |
| repo.smartsync | `--smart-sync` | Default to [Smart Sync](./smart-sync.md) when syncing |
| repo.smartsyncdefault | (internal) | Fallback [Smart Sync](./smart-sync.md) policy; `explicit` enables Smart Sync when `<manifest-server>` is set (below CLI, `repo.smartsync`, `sync.smartsync`, and `sync-smartsync`) and treats default Smart Syncs as explicit |
| repo.\<branch\>.smartsyncbranch | `--smart-sync-branch` | Server branch to query when [Smart Sync](./smart-sync.md)ing `<branch>` |
| repo.submodules | `--submodules` | Sync git submodules |
| repo.superproject | `--use-superproject` | Sync [superproject] |
+3 -1
View File
@@ -242,7 +242,9 @@ will use this value if specified; otherwise projects default to
false when depth is set on a non-mirror checkout, and true
otherwise.
Attribute `sync-smartsync`: Set to true to enable smart sync by default.
Attribute `sync-smartsync`: Set to true to enable smart sync by default,
or set to false to disable default smart sync for the manifest (explicit
`-s`/`-t` invocations still work when `<manifest-server>` is defined).
### Element manifest-server
+5
View File
@@ -245,6 +245,11 @@ explicit target or manifest source (such as `-t`/`--smart-tag`,
`-m`/`--manifest-name` or `--superproject-revision`) will also disable the
default Smart Sync behavior.
Setting `sync-smartsync="false"` explicitly opts the manifest out of default
Smart Sync (for example, overriding a checkout fallback policy) while keeping
`<manifest-server>` available for explicit `-s`/`--smart-sync` and
`-t`/`--smart-tag` invocations.
Users can override this manifest default on their workstation with the
`sync.smartsync` user setting; see
[Per-user default](#Per_user-default-sync_smartsync) below.
+3 -1
View File
@@ -346,7 +346,9 @@ set. Project elements lacking a `sync\-tags` attribute of their own will use thi
value if specified; otherwise projects default to false when depth is set on a
non\-mirror checkout, and true otherwise.
.PP
Attribute `sync\-smartsync`: Set to true to enable smart sync by default.
Attribute `sync\-smartsync`: Set to true to enable smart sync by default, or set
to false to disable default smart sync for the manifest (explicit `\-s`/`\-t`
invocations still work when `<manifest\-server>` is defined).
.PP
Element manifest\-server
.PP
+6 -4
View File
@@ -159,7 +159,7 @@ class _Default:
sync_c = False
sync_s = False
sync_tags = None
sync_smartsync = False
sync_smartsync = None
def __eq__(self, other):
if not isinstance(other, _Default):
@@ -658,9 +658,11 @@ https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
if d.sync_tags is not None:
have_default = True
e.setAttribute("sync-tags", "true" if d.sync_tags else "false")
if d.sync_smartsync:
if d.sync_smartsync is not None:
have_default = True
e.setAttribute("sync-smartsync", "true")
e.setAttribute(
"sync-smartsync", "true" if d.sync_smartsync else "false"
)
if have_default:
root.appendChild(e)
root.appendChild(doc.createTextNode(""))
@@ -1814,7 +1816,7 @@ https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
d.sync_c = XmlBool(node, "sync-c", False)
d.sync_s = XmlBool(node, "sync-s", False)
d.sync_tags = XmlBool(node, "sync-tags")
d.sync_smartsync = XmlBool(node, "sync-smartsync", False)
d.sync_smartsync = XmlBool(node, "sync-smartsync")
return d
def _ParseNotice(self, node):
+8
View File
@@ -6176,6 +6176,14 @@ class ManifestProject(MetaProject):
"""Whether we use smart sync by default."""
return self.config.GetBoolean("repo.smartsync")
@property
def smart_sync_default(self) -> Optional[str]:
"""Checkout-level fallback smart sync policy (e.g. 'explicit')."""
val = self.config.GetString("repo.smartsyncdefault")
if val is None:
return None
return val.strip().lower() or None
@staticmethod
def _SmartSyncBranchKey(branch: str) -> str:
"""Return the git config key for a branch's smart sync branch."""
+53 -20
View File
@@ -2713,19 +2713,40 @@ later is required to fix a server side protocol bug.
) -> bool:
"""Resolve opt.smart_sync from CLI flags, config, and manifest.
Precedence: CLI flags > per-checkout settings > per-user settings >
per-manifest settings.
See docs/repoconfig.md and docs/smart-sync.md for details.
Precedence: CLI flags > repo.smartsync > sync.smartsync >
<default sync-smartsync> > repo.smartsyncdefault.
See docs/repoconfig.md, docs/smart-sync.md, and
docs/internal-fs-layout.md for details.
Returns:
True if smart_sync was enabled implicitly by checkout or manifest
default, False otherwise. Smart sync enabled via per-user settings
counts as an explicit user request, not implicit.
or in a checkout with repo.smartsyncdefault=explicit counts as an
explicit request, not implicit.
"""
checkout_pref = getattr(manifest.manifestProject, "smart_sync", None)
if not isinstance(checkout_pref, bool):
checkout_pref = None
checkout_default = getattr(
manifest.manifestProject, "smart_sync_default", None
)
if not isinstance(checkout_default, str):
checkout_default = None
else:
checkout_default = checkout_default.strip().lower() or None
if checkout_default is not None and checkout_default != "explicit":
logger.warning(
"warning: ignoring unknown repo.smartsyncdefault "
'value "%s"',
checkout_default,
)
checkout_default = None
explicit_default = checkout_default == "explicit"
user_pref = git_config.RepoConfig.ForUser().GetBoolean("sync.smartsync")
manifest_pref = getattr(manifest.default, "sync_smartsync", None)
if not isinstance(manifest_pref, bool):
manifest_pref = None
default_allowed = (
opt.smart_sync is None
and not opt.smart_tag
@@ -2733,25 +2754,30 @@ later is required to fix a server side protocol bug.
and not opt.superproject_revision
and not opt.local_only
)
default_smart_sync = (
checkout_pref
if checkout_pref is not None
else getattr(manifest.default, "sync_smartsync", False) is True
)
implicit = (
default_allowed
and (checkout_pref is not None or user_pref is None)
and default_smart_sync
)
if opt.smart_sync is None:
if checkout_pref is not None:
opt.smart_sync = implicit
elif user_pref is False:
if not default_allowed:
opt.smart_sync = False
elif user_pref is True:
opt.smart_sync = default_allowed
implicit = False
elif checkout_pref is not None:
opt.smart_sync = checkout_pref
implicit = checkout_pref and not explicit_default
elif user_pref is not None:
opt.smart_sync = user_pref
implicit = False
elif manifest_pref is not None:
opt.smart_sync = manifest_pref
implicit = manifest_pref and not explicit_default
elif explicit_default:
manifest_server = getattr(manifest, "manifest_server", None)
opt.smart_sync = isinstance(manifest_server, str) and bool(
manifest_server
)
implicit = False
else:
opt.smart_sync = implicit
opt.smart_sync = False
implicit = False
else:
implicit = False
if (
opt.manifest_server_username or opt.manifest_server_password
@@ -2789,6 +2815,7 @@ later is required to fix a server side protocol bug.
and os.path.isfile(smart_sync_manifest_path)
)
cli_smart_sync = bool(opt.smart_sync or getattr(opt, "smart_tag", None))
implicit_smart_sync = self._ResolveSmartSyncOption(opt, manifest)
if opt.smart_sync or opt.smart_tag:
@@ -2801,6 +2828,12 @@ later is required to fix a server side protocol bug.
)
except (SmartSyncError, error.ManifestParseError) as e:
if not implicit_smart_sync:
if not cli_smart_sync:
logger.error(
"hint: Smart Sync was enabled by default; "
"pass --no-smart-sync (or --head) to sync to "
"ToT instead."
)
raise
# The user did not ask for a smart sync, so failing to get a
# usable manifest from the server should not fail the sync.
+133
View File
@@ -572,3 +572,136 @@ def test_smart_sync_branch(host: GitHost, client: RepoClient) -> None:
)
assert res.returncode != 0
assert "requires the manifest checkout to track a branch" in res.stderr
def test_smart_sync_default_explicit(
host: GitHost, client: RepoClient, tmp_path: Path
) -> None:
"""`repo.smartsyncdefault=explicit` enables explicit Smart Sync fallback."""
foo = host.create_repo("platform/foo", {"f": "v1"})
v1 = foo.rev_parse("main")
tot = foo.commit({"f": "tot"})
requests: List[Dict[str, Any]] = []
fail_server = False
def handle_v2(req: Dict[str, Any]) -> Dict[str, Any]:
requests.append(req)
if fail_server:
return {"success": False, "error_message": "server unavailable"}
return {
"success": True,
"manifest_xml": manifest_xml(
f'<project name="platform/foo" path="foo" revision="{v1}" />',
fetch=host.url,
),
}
with _manifest_server(handle_v2) as server_url:
manifest = host.create_manifest(
manifest_xml(
f'<manifest-server url="{server_url}" />',
'<project name="platform/foo" path="foo" />',
)
)
manifest.commit(
{
"default.xml": manifest_xml(
f'<manifest-server url="{server_url}" />',
'<project name="platform/foo" path="foo" />',
default=(
'remote="origin" revision="main" '
'sync-smartsync="false"'
),
)
},
branch="opt-out",
)
manifest.commit(
{
"default.xml": manifest_xml(
f'<manifest-server url="{server_url}" />',
'<project name="platform/foo" path="foo" />',
default=(
'remote="origin" revision="main" '
'sync-smartsync="true"'
),
)
},
branch="opt-in",
)
manifest.commit(
{
"default.xml": manifest_xml(
'<project name="platform/foo" path="foo" />'
)
},
branch="no-server",
)
client.init(host.manifest_url)
client.git(
".repo/manifests", "config", "repo.smartsyncdefault", "explicit"
)
# Enables explicit Smart Sync when <manifest-server> is present.
client.sync()
assert len(requests) == 1
assert "best_effort" not in requests[-1]
assert client.head("foo") == v1
# Fails hard with a hint instead of falling back to ToT on error.
fail_server = True
res = client.sync(check=False)
assert res.returncode != 0
assert "--no-smart-sync" in res.stderr
assert len(requests) == 2
assert "best_effort" not in requests[-1]
# Explicit CLI -s failure does not emit the default-enabled hint.
res = client.sync("-s", check=False)
assert res.returncode != 0
assert "--no-smart-sync" not in res.stderr
assert len(requests) == 3
# <default sync-smartsync="false"/> opts out while keeping -s usable.
client.init(host.manifest_url, "-b", "opt-out")
client.sync()
assert len(requests) == 3
assert client.head("foo") == tot
fail_server = False
client.sync("-s")
assert len(requests) == 4
assert client.head("foo") == v1
# <default sync-smartsync="true"/> is also treated as explicit.
client.init(host.manifest_url, "-b", "opt-in")
fail_server = True
res = client.sync(check=False)
assert res.returncode != 0
assert "--no-smart-sync" in res.stderr
assert len(requests) == 5
assert "best_effort" not in requests[-1]
# Per-user sync.smartsync=false overrides repo.smartsyncdefault.
client.init(host.manifest_url, "-b", "main")
cfg_dir = tmp_path / "repoconfig"
(cfg_dir / ".repoconfig").mkdir(parents=True)
(cfg_dir / ".repoconfig" / "config").write_text(
"[sync]\n\tsmartsync = false\n"
)
saved_env = dict(client.env)
client.env["REPO_CONFIG_DIR"] = str(cfg_dir)
try:
client.sync()
finally:
client.env = saved_env
assert len(requests) == 5
assert client.head("foo") == tot
# Without <manifest-server>, sync falls through to regular ToT.
client.init(host.manifest_url, "-b", "no-server")
client.sync()
assert len(requests) == 5
assert client.head("foo") == tot
+6 -2
View File
@@ -427,7 +427,8 @@ class TestXmlManifest:
manifest = repo_client.get_xml_manifest(
"<manifest><default /></manifest>"
)
assert manifest.default.sync_smartsync is False
assert manifest.default.sync_smartsync is None
assert manifest.ToXml().toxml() == '<?xml version="1.0" ?><manifest/>'
manifest = repo_client.get_xml_manifest(
'<manifest><default sync-smartsync="true" /></manifest>'
@@ -442,7 +443,10 @@ class TestXmlManifest:
'<manifest><default sync-smartsync="false" /></manifest>'
)
assert manifest.default.sync_smartsync is False
assert manifest.ToXml().toxml() == '<?xml version="1.0" ?><manifest/>'
assert (
manifest.ToXml().toxml() == '<?xml version="1.0" ?>'
'<manifest><default sync-smartsync="false"/></manifest>'
)
def test_clear_override(self, repo_client: RepoClient) -> None:
"""Check ClearOverride reverts to the default manifest."""
+6
View File
@@ -1978,6 +1978,12 @@ class ManifestPropertiesFetchedCorrectly(unittest.TestCase):
fakeproj.config.SetBoolean("repo.smartsync", False)
self.assertFalse(fakeproj.smart_sync)
self.assertIsNone(fakeproj.smart_sync_default)
fakeproj.config.SetString("repo.smartsyncdefault", "Explicit")
self.assertEqual(fakeproj.smart_sync_default, "explicit")
fakeproj.config.SetString("repo.smartsyncdefault", None)
self.assertIsNone(fakeproj.smart_sync_default)
fakeproj.config.SetBoolean("repo.partialclone", False)
self.assertFalse(fakeproj.partial_clone)
+161
View File
@@ -652,6 +652,124 @@ def test_user_config_smart_sync(
assert implicit == expected_implicit
@pytest.mark.parametrize(
"argv, config_smart_sync, user_pref, sync_smartsync_manifest, "
"manifest_server, expected_smart_sync, expected_implicit",
[
# Fallback: enabled iff <manifest-server> is set, always explicit.
([], None, None, None, "http://localhost/ms", True, False),
([], None, None, None, None, False, False),
([], None, None, None, "", False, False),
# Manifest sync-smartsync overrides repo.smartsyncdefault; true is
# upgraded to explicit, false opts out even with <manifest-server>.
([], None, None, False, "http://localhost/ms", False, False),
([], None, None, True, "http://localhost/ms", True, False),
([], None, None, True, None, True, False),
# Per-user sync.smartsync overrides manifest and repo.smartsyncdefault.
([], None, False, None, "http://localhost/ms", False, False),
([], None, False, True, "http://localhost/ms", False, False),
([], None, True, False, None, True, False),
# repo.smartsync overrides user/manifest; true is upgraded to explicit.
([], True, False, False, None, True, False),
([], False, True, True, "http://localhost/ms", False, False),
# CLI flags and target-selecting flags override everything.
(
["--no-smart-sync"],
True,
True,
True,
"http://localhost/ms",
False,
False,
),
(["--head"], None, None, None, "http://localhost/ms", False, False),
(["-s"], False, False, False, None, True, False),
(
["-t", "tag123"],
None,
None,
None,
"http://localhost/ms",
False,
False,
),
(
["-m", "other.xml"],
None,
None,
None,
"http://localhost/ms",
False,
False,
),
(
["--superproject-revision=abc"],
None,
None,
None,
"http://localhost/ms",
False,
False,
),
(["-l"], None, None, None, "http://localhost/ms", False, False),
(["--nmu"], None, None, None, "http://localhost/ms", True, False),
],
)
def test_checkout_smart_sync_default_explicit(
argv: List[str],
config_smart_sync: Optional[bool],
user_pref: Optional[bool],
sync_smartsync_manifest: Optional[bool],
manifest_server: Optional[str],
expected_smart_sync: bool,
expected_implicit: bool,
) -> None:
"""Tests repo.smartsyncdefault=explicit precedence and explicitness."""
manifest = mock.MagicMock()
manifest.default.sync_smartsync = sync_smartsync_manifest
manifest.manifest_server = manifest_server
manifest.manifestProject.smart_sync = config_smart_sync
manifest.manifestProject.smart_sync_default = "explicit"
user_cfg = mock.MagicMock()
user_cfg.GetBoolean.return_value = user_pref
cmd = sync.Sync(manifest=manifest)
opts, args = cmd.OptionParser.parse_args(argv)
cmd.ValidateOptions(opts, args)
with mock.patch.object(
git_config.RepoConfig, "ForUser", return_value=user_cfg
):
implicit = cmd._ResolveSmartSyncOption(opts, manifest)
assert opts.smart_sync == expected_smart_sync
assert implicit == expected_implicit
@pytest.mark.parametrize("bad_value", ["bogus", "implicit", "off"])
def test_checkout_smart_sync_default_unknown_warns(bad_value: str) -> None:
"""Unknown repo.smartsyncdefault values log a warning and are ignored."""
manifest = mock.MagicMock()
manifest.default.sync_smartsync = None
manifest.manifest_server = "http://localhost/manifestserver"
manifest.manifestProject.smart_sync = None
manifest.manifestProject.smart_sync_default = bad_value
user_cfg = mock.MagicMock()
user_cfg.GetBoolean.return_value = None
cmd = sync.Sync(manifest=manifest)
opts, args = cmd.OptionParser.parse_args([])
cmd.ValidateOptions(opts, args)
with mock.patch.object(
git_config.RepoConfig, "ForUser", return_value=user_cfg
):
with mock.patch.object(sync.logger, "warning") as mock_warn:
implicit = cmd._ResolveSmartSyncOption(opts, manifest)
mock_warn.assert_called_once()
assert opts.smart_sync is False
assert implicit is False
@pytest.mark.parametrize(
"value, expected_smart_sync",
[("true", True), ("false", False), ("yes", True), ("no", False)],
@@ -2053,6 +2171,49 @@ class SyncCommand(unittest.TestCase):
self.cmd.Execute(self.opt, [])
mock_setup.assert_called_once()
def test_checkout_smart_sync_default_explicit_error(self) -> None:
"""Ensure repo.smartsyncdefault=explicit fails hard with a hint."""
self.manifest.default.sync_smartsync = None
self.manifest.manifest_server = "http://localhost/manifestserver"
self.manifest.manifestProject.smart_sync_default = "explicit"
self.opt.smart_sync = None
self.opt.mp_update = False
user_cfg = mock.MagicMock()
user_cfg.GetBoolean.return_value = None
with mock.patch.object(
git_config.RepoConfig, "ForUser", return_value=user_cfg
):
with mock.patch.object(
self.cmd,
"_SmartSyncSetup",
side_effect=sync.SmartSyncError("target not found"),
) as mock_setup:
with mock.patch.object(sync.logger, "error") as mock_error:
with self.assertRaises(sync.SmartSyncError):
self.cmd.Execute(self.opt, [])
mock_setup.assert_called_once_with(
self.opt,
mock.ANY,
self.manifest,
best_effort=False,
)
mock_error.assert_called_once()
self.assertIn("--no-smart-sync", mock_error.call_args[0][0])
def test_cli_smart_sync_error_no_default_hint(self) -> None:
"""Ensure explicit CLI -s failures do not print the default hint."""
self.opt.smart_sync = True
self.opt.mp_update = False
with mock.patch.object(
self.cmd,
"_SmartSyncSetup",
side_effect=sync.SmartSyncError("target not found"),
):
with mock.patch.object(sync.logger, "error") as mock_error:
with self.assertRaises(sync.SmartSyncError):
self.cmd.Execute(self.opt, [])
mock_error.assert_not_called()
def test_implicit_smart_sync_unparsable_manifest(self) -> None:
"""Ensure an unparsable smart sync manifest falls back to ToT."""
self.manifest.default.sync_smartsync = True