diff --git a/dev-docs/architecture/marketplace-upgrade-sweep.md b/dev-docs/architecture/marketplace-upgrade-sweep.md index b6b1612b2..264b98321 100644 --- a/dev-docs/architecture/marketplace-upgrade-sweep.md +++ b/dev-docs/architecture/marketplace-upgrade-sweep.md @@ -8,7 +8,10 @@ Multi-Workspace (Cloud) instances only offer plugin upgrades per Workspace in th - Runs once per process after the shared Plugin Runtime handshake and desired-state replay, after `start_delay_seconds` (default 120). - Reads each plugin's `latest_version` from the configured Space Marketplace, then walks `workspace_service.list_active_execution_bindings()` with `concurrency` Workspaces at a time (default 2). The optional `workspaces` list limits the sweep to canary Workspace UUIDs. - Each Workspace is entered with `persistence_mgr.tenant_scope()` and `plugin_connector._prepare_workspace_context()`, the same fence as HTTP requests. Outdated `marketplace` installations go through `upgrade_plugin()`, the WebUI upgrade path. -- An upgrade to a version without `spec.permissions` disables the installation until a member confirms. With `confirm_permissions` (default true), the sweep calls `auto_confirm_declared()` for installations that were **enabled before the sweep**. Installations the tenant had disabled stay disabled. +- An upgrade to a version without `spec.permissions` disables the installation until a member confirms. With `confirm_permissions` (default true), the sweep calls `auto_confirm_declared()` for every listed installation that is **pending confirmation**, which also enables it. An installation the tenant switched off keeps its confirmed snapshot, is not pending, and stays disabled. +- Upgrade and confirmation are retried twice (5 s, 20 s) to ride out DNS errors and blocking-executor saturation while a large instance starts. - The operator principal is `SUPPORT_ADMIN` with `support_session_id=operator:marketplace-upgrade`, owner role. Failures are logged per installation and do not stop the sweep. The summary is logged as `Marketplace upgrade finished: {...}`. -Remove the env setting after the run. Re-running is idempotent: installations already at the latest version are only re-confirmed if they are pending confirmation. +Re-running is idempotent: installations already at the latest version are only confirmed if they are pending confirmation. + +**Config persistence pitfall:** Core writes env overrides back into `data/config.yaml`. Removing a `PLUGIN__MARKETPLACE_UPGRADE__*` variable therefore keeps the last value. To clear a list, set the variable to an empty string, for example `PLUGIN__MARKETPLACE_UPGRADE__PLUGINS=` to turn the sweep off. diff --git a/src/langbot/pkg/plugin/marketplace_upgrade.py b/src/langbot/pkg/plugin/marketplace_upgrade.py index 94af8c912..00d078f1a 100644 --- a/src/langbot/pkg/plugin/marketplace_upgrade.py +++ b/src/langbot/pkg/plugin/marketplace_upgrade.py @@ -9,8 +9,9 @@ same ``upgrade_plugin`` path as the WebUI. Upgrading to a version without a permission declaration leaves the plugin disabled until a member confirms. With ``confirm_permissions`` enabled, the sweep confirms the declared permissions as an operator (owner role, the same -principal shape as a support-admin session) for installations that were -enabled before the sweep. Installations the tenant disabled stay disabled. +principal shape as a support-admin session) for every listed installation +that is pending confirmation. Installations the tenant switched off keep +their confirmed snapshot and stay disabled. Transient failures are retried. """ from __future__ import annotations @@ -104,6 +105,8 @@ async def fetch_latest_versions(space_url: str, plugin_ids: typing.Iterable[str] class MarketplaceUpgradeSweep: + RETRY_DELAYS_SECONDS: tuple[float, ...] = (5.0, 20.0) + def __init__(self, ap: Application, config: MarketplaceUpgradeConfig) -> None: self.ap = ap self.config = config @@ -161,28 +164,47 @@ class MarketplaceUpgradeSweep: self.summary['failed'] += 1 self.ap.logger.warning(f'Marketplace upgrade: Workspace {context.workspace_uuid} skipped: {exc!r}') + async def _retry(self, operation: typing.Callable[[], typing.Awaitable[typing.Any]]) -> typing.Any: + """Retry transient failures (DNS, blocking-executor saturation, timeouts).""" + + for delay in (*self.RETRY_DELAYS_SECONDS, None): + try: + return await operation() + except Exception: + if delay is None: + raise + await asyncio.sleep(delay) + async def _upgrade_one(self, context: RequestContext, setting: typing.Any, plugin_id: str, version: str) -> None: from ..api.application.plugin_permissions import auto_confirm_declared, permission_status connector = self.ap.plugin_connector author, name = plugin_id.split('/', 1) - was_enabled = bool(setting.enabled) installed = (setting.install_info or {}).get('plugin_version') try: if installed == version: self.summary['up_to_date'] += 1 else: - await connector.upgrade_plugin(author, name) + await self._retry(lambda: connector.upgrade_plugin(author, name)) self.summary['upgraded'] += 1 self.ap.logger.info( f'Marketplace upgrade: {context.workspace_uuid} {plugin_id} {installed} -> {version}' ) - if not (self.config.confirm_permissions and was_enabled): + if not self.config.confirm_permissions: return _, current = await connector._setting_for_plugin(author, name) - if current.enabled and not permission_status(self.ap, current)['pending_confirmation']: + # Only installations waiting for permission confirmation are + # confirmed (and thereby enabled). An installation the tenant + # switched off keeps its confirmed snapshot and stays disabled. + if not permission_status(self.ap, current)['pending_confirmation']: return - await auto_confirm_declared(self.ap, context, current) + + async def confirm(): + _, fresh = await connector._setting_for_plugin(author, name) + if permission_status(self.ap, fresh)['pending_confirmation']: + await auto_confirm_declared(self.ap, context, fresh) + + await self._retry(confirm) self.summary['confirmed'] += 1 except Exception as exc: self.summary['failed'] += 1 diff --git a/tests/unit_tests/plugin/test_marketplace_upgrade.py b/tests/unit_tests/plugin/test_marketplace_upgrade.py index d6e6799e2..c386d10a1 100644 --- a/tests/unit_tests/plugin/test_marketplace_upgrade.py +++ b/tests/unit_tests/plugin/test_marketplace_upgrade.py @@ -60,6 +60,15 @@ def make_ap(per_ws, plugins=('langbot-team/LocalAgent',), confirm=True): return ap +@pytest.fixture(autouse=True) +def no_retry_delay(monkeypatch): + monkeypatch.setattr(mu.MarketplaceUpgradeSweep, 'RETRY_DELAYS_SECONDS', (0.0, 0.0)) + + +def pending_unless_snapshot(ap, s): + return {'pending_confirmation': s.permission_snapshot is None} + + def config(ap): return mu.MarketplaceUpgradeConfig.from_instance_config(ap.instance_config.data) @@ -89,7 +98,7 @@ def test_operator_context_is_owner_support_admin(): assert ctx.workspace_uuid == 'w' and ctx.placement_generation == 3 -async def test_upgrades_outdated_and_confirms_previously_enabled(): +async def test_upgrades_outdated_and_confirms_pending(): ap = make_ap( { 'ws-1': [setting('ws-1'), setting('ws-1', name='Other', author='someone')], @@ -109,25 +118,68 @@ async def test_upgrades_outdated_and_confirms_previously_enabled(): assert ap.plugin_connector.upgraded == [('ws-1', 'langbot-team/LocalAgent')] assert summary['upgraded'] == 1 and summary['up_to_date'] == 1 and summary['failed'] == 0 - # ws-1 was disabled by the upgrade and ws-2's current setting is reported - # disabled by the fake, so both previously enabled installs are confirmed - # in their own Workspace context. + # Both current settings are reported disabled and pending by the fake, so + # each is confirmed in its own Workspace context. assert summary['confirmed'] == 2 assert sorted(call.args[1].workspace_uuid for call in confirm.await_args_list) == WS async def test_tenant_disabled_install_is_upgraded_but_not_enabled(): ap = make_ap({'ws-1': [setting('ws-1', enabled=False)]}) + switched_off = setting('ws-1', enabled=False) + switched_off.permission_snapshot = {'workspace_operations': [], 'capabilities': []} + ap.plugin_connector.after_upgrade[('ws-1', 'LocalAgent')] = switched_off confirm = AsyncMock() with ( patch.object(mu, 'fetch_latest_versions', AsyncMock(return_value={'langbot-team/LocalAgent': '0.2.8'})), patch('langbot.pkg.api.application.plugin_permissions.auto_confirm_declared', confirm), + patch('langbot.pkg.api.application.plugin_permissions.permission_status', pending_unless_snapshot), ): summary = await mu.MarketplaceUpgradeSweep(ap, config(ap)).run() assert summary['upgraded'] == 1 confirm.assert_not_awaited() +async def test_up_to_date_install_left_pending_is_confirmed_on_rerun(): + # A previous run upgraded the install but its confirmation failed, leaving + # it disabled and pending; the next run confirms it. + ap = make_ap({'ws-1': [setting('ws-1', version='0.2.8', enabled=False)]}) + confirm = AsyncMock() + with ( + patch.object(mu, 'fetch_latest_versions', AsyncMock(return_value={'langbot-team/LocalAgent': '0.2.8'})), + patch('langbot.pkg.api.application.plugin_permissions.auto_confirm_declared', confirm), + patch('langbot.pkg.api.application.plugin_permissions.permission_status', pending_unless_snapshot), + ): + summary = await mu.MarketplaceUpgradeSweep(ap, config(ap)).run() + assert ap.plugin_connector.upgraded == [] + assert summary['up_to_date'] == 1 and summary['confirmed'] == 1 + confirm.assert_awaited_once() + + +async def test_transient_failures_are_retried(): + ap = make_ap({'ws-1': [setting('ws-1')]}) + original = ap.plugin_connector.upgrade_plugin + attempts = [] + + async def flaky(author, name): + attempts.append(1) + if len(attempts) < 3: + raise RuntimeError('Blocking executor capacity reached') + await original(author, name) + + ap.plugin_connector.upgrade_plugin = flaky + confirm = AsyncMock(side_effect=[RuntimeError('dns'), None]) + with ( + patch.object(mu, 'fetch_latest_versions', AsyncMock(return_value={'langbot-team/LocalAgent': '0.2.8'})), + patch('langbot.pkg.api.application.plugin_permissions.auto_confirm_declared', confirm), + patch('langbot.pkg.api.application.plugin_permissions.permission_status', pending_unless_snapshot), + ): + summary = await mu.MarketplaceUpgradeSweep(ap, config(ap)).run() + assert len(attempts) == 3 + assert confirm.await_count == 2 + assert summary == {'workspaces': 1, 'upgraded': 1, 'confirmed': 1, 'up_to_date': 0, 'failed': 0} + + async def test_confirmation_can_be_turned_off(): ap = make_ap({'ws-1': [setting('ws-1')]}, confirm=False) confirm = AsyncMock()