From ab7c3797ed47da9177a0925300c18fda68db9a1b Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:23:33 +0800 Subject: [PATCH 1/3] =?UTF-8?q?fix(extensions):=20=E5=85=88=E4=BF=9D?= =?UTF-8?q?=E5=AD=98=E6=89=A9=E5=B1=95=E5=81=9C=E7=94=A8=E6=84=8F=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/business/extension/AGENTS.md | 5 +- app/business/extension/main.py | 51 ++++-- ...extension_participation_lifecycle_races.py | 158 ++++++++++++++++-- 3 files changed, 190 insertions(+), 24 deletions(-) diff --git a/app/business/extension/AGENTS.md b/app/business/extension/AGENTS.md index 3005bf20..be4a0aee 100644 --- a/app/business/extension/AGENTS.md +++ b/app/business/extension/AGENTS.md @@ -22,8 +22,9 @@ - 新 install/upgrade 只接受 published;已安装 exact yanked Release 可 enable/cold restore 并告警。 - 选择缺失的 Python wheel 时先下载并验证;暂停 Peer、排空任务并关闭 Extension 后,才把 wheel 安装到共享解释器。 应用失败时保留暂停与明确错误,不声称回滚。应用完成后必须以新进程重载 Python 模块。 -- enable 只允许启动当前 Peer 已选中的 exact installed Distribution,不隐式安装 pip 包。disable 先停止 runtime - 再保存 intent;冷启动只恢复该 Peer 的精确选择。 +- enable 只允许启动当前 Peer 已选中的 exact installed Distribution,不隐式安装 pip 包。启停顺序遵循 + [共享参与合同](../../../docs/_shared/20-product-tdd/extension-release-and-installation.md#应用版本与失败边界)。 + 冷启动只恢复该 Peer 的精确选择。 - 未解析的旧 enabled member 保留原版本与 enabled intent,必须精确解析该版本;失败不得删 intent,也不得回退到 latest。 - `ExtensionBase` 向 Extension 提供 fresh validated config 读写与 typed deployment-wide state mutation;Extension 不接触 SQLModel,数据库行锁与并发语义仍由 Core store 实现。 diff --git a/app/business/extension/main.py b/app/business/extension/main.py index 631c1c09..237a368f 100644 --- a/app/business/extension/main.py +++ b/app/business/extension/main.py @@ -174,6 +174,7 @@ class RunningExtension: acquired: AcquiredDistribution extension_class: type[ExtensionBase] claim: ExtensionRuntimeClaim + stopping: bool = False class ExtensionHost: @@ -767,7 +768,9 @@ async def _start( raise ExtensionRestartRequiredError( f"A different Release of {state.name} is already running" ) - return existing + if not existing.stopping: + return existing + await self._stop(existing) association, acquired = await self._acquire(state, selection) return await self._start_acquired(app, state, selection, association, acquired) @@ -846,14 +849,22 @@ async def _get_current_enabled_selection( return current async def _stop(self, running: RunningExtension) -> None: - await running.extension_class.on_close() - running.extension_class.unpublish() + failures = await self._withdraw_running_effects(running) + if len(failures) == 1: + raise failures[0] + if failures: + raise ExceptionGroup("Extension shutdown failed", failures) + # Keep the binding, claim, and running record until close succeeds so a + # later stop can retry the Extension's own cleanup. running.extension_class.unbind() running.extension_class.release_runtime() running.claim.release() self.running.pop(running.name, None) - async def _force_stop(self, running: RunningExtension) -> typing.List[Exception]: + async def _withdraw_running_effects( + self, running: RunningExtension + ) -> typing.List[Exception]: + running.stopping = True failures: list[Exception] = [] try: await running.extension_class.on_close() @@ -863,6 +874,10 @@ async def _force_stop(self, running: RunningExtension) -> typing.List[Exception] running.extension_class.unpublish() except Exception as error: failures.append(error) + return failures + + async def _force_stop(self, running: RunningExtension) -> typing.List[Exception]: + failures = await self._withdraw_running_effects(running) try: running.extension_class.unbind() except Exception as error: @@ -948,16 +963,30 @@ async def disable(self, name: str, *, peer_id: typing.Any) -> ExtensionParticipa selection = await self.store.get_participation(peer_id, name) if selection is None: raise ExtensionNotInstalledError(f"{name} has no selection on this Peer") - if not selection.enabled: - return selection + if selection.enabled: + selection = await self.store.set_participation_enabled(peer_id, name, False) + self._operations.pop(name, None) running = self.running.get(name) - published = bool(running and running.extension_class.peer_inbounds()) - if running is not None: + if running is None: + return selection + published = bool(running.extension_class.peer_inbounds()) + failures: list[Exception] = [] + try: await self._stop(running) - persisted = await self.store.set_participation_enabled(peer_id, name, False) + except Exception as error: + failures.append(error) if published: - await PeerManager.refresh_self(settings.peer_lease_ttl_seconds) - return persisted + try: + await PeerManager.refresh_self(settings.peer_lease_ttl_seconds) + except Exception as error: + failures.append(error) + if failures: + self._operations[name] = (None, "\n".join(str(error) for error in failures)) + if len(failures) == 1: + raise failures[0] + raise ExceptionGroup("Extension disable failed", failures) + self._operations.pop(name, None) + return selection async def start_enabled(self, app: fastapi.FastAPI) -> None: """Cold restore exact Python selections; never install packages in this process.""" diff --git a/tests/test_extension_participation_lifecycle_races.py b/tests/test_extension_participation_lifecycle_races.py index 2bb5b7db..e31e1893 100644 --- a/tests/test_extension_participation_lifecycle_races.py +++ b/tests/test_extension_participation_lifecycle_races.py @@ -1,11 +1,13 @@ -"""Intent changes during Extension startup must discard stale runtime candidates.""" +"""Persisted Extension intent and local runtime effects have separate lifetimes.""" +from types import SimpleNamespace import uuid import typing import fastapi import pytest +from app.business.extension import main as extension_main from app.business.extension.errors import ExtensionStateConflictError from app.business.extension.main import ExtensionHost from app.business.extension.state import ( @@ -13,12 +15,18 @@ ExtensionStore, InstalledExtension, ) +from inkcre_core.schemas.extension import DisableExtensionCommand, EnableExtensionCommand class ParticipationStore: def __init__(self, participation: ExtensionParticipation) -> None: self.participation = participation self.extension = InstalledExtension(name=participation.name, nickname="Race test") + self.writes: list[bool] = [] + self.write_error: Exception | None = None + + async def list(self) -> tuple[InstalledExtension, ...]: + return (self.extension,) async def get(self, _name: str) -> InstalledExtension: return self.extension @@ -36,6 +44,9 @@ async def list_participations( async def set_participation_enabled( self, _peer_id: uuid.UUID, _name: str, enabled: bool ) -> ExtensionParticipation: + self.writes.append(enabled) + if self.write_error is not None: + raise self.write_error self.participation = self.participation.model_copy(update={"enabled": enabled}) return self.participation @@ -69,6 +80,21 @@ def release(self) -> None: self.released = True +def _running( + selection: ExtensionParticipation, candidate: RuntimeCandidate, claim: RuntimeClaim +) -> extension_main.RunningExtension: + return typing.cast( + extension_main.RunningExtension, + SimpleNamespace( + name=selection.name, + version=selection.version, + extension_class=candidate, + claim=claim, + stopping=False, + ), + ) + + def _participation(peer_id: uuid.UUID) -> ExtensionParticipation: return ExtensionParticipation( name="inkcre/race-test", @@ -88,16 +114,7 @@ def test_late_startup_candidate_is_discarded_after_intent_is_disabled( host = ExtensionHost(store=typing.cast(ExtensionStore, store)) candidate = RuntimeCandidate() claim = RuntimeClaim() - running = type( - "RunningCandidate", - (), - { - "name": store.participation.name, - "version": "1.2.3", - "extension_class": candidate, - "claim": claim, - }, - )() + running = _running(store.participation, candidate, claim) start_observed_enabled = False async def start(_app, _extension, selection): @@ -131,3 +148,122 @@ async def start(_app, _extension, selection): assert candidate.closed is True assert candidate.released is True assert claim.released is True + + +@pytest.mark.parametrize("reenable", [False, True]) +def test_disable_persists_intent_before_cleanup_and_retries_residual_runtime( + async_runner, monkeypatch, reenable: bool +): + peer_id = uuid.uuid4() + store = ParticipationStore(_participation(peer_id).model_copy(update={"enabled": True})) + name = store.participation.name + host = ExtensionHost(store=typing.cast(ExtensionStore, store)) + close_error = RuntimeError("close callback failed") + advertisement_error = RuntimeError("advertisement refresh failed") + close_fails = True + advertisement_fails = True + refresh_count = 0 + + class PublishedExtension(RuntimeCandidate): + published = True + + async def on_close(self) -> None: + if close_fails: + assert store.participation.enabled is False + raise close_error + await super().on_close() + + def unpublish(self) -> None: + self.published = False + + def peer_inbounds(self) -> bool: + return True + + async def refresh(_ttl: int) -> None: + nonlocal refresh_count + refresh_count += 1 + assert not candidate.published + if advertisement_fails: + raise advertisement_error + + candidate = PublishedExtension() + claim = RuntimeClaim() + host.running[name] = _running(store.participation, candidate, claim) + host.fastapi_app = fastapi.FastAPI() + monkeypatch.setattr(extension_main.PeerManager, "get_current_peer_ref", lambda: peer_id) + monkeypatch.setattr(extension_main.AcquiredDistribution, "discover", lambda *_: object()) + monkeypatch.setattr(extension_main.PeerManager, "refresh_self", refresh) + command = DisableExtensionCommand(action="disable", extension=name) + + with pytest.raises(ExceptionGroup) as caught: + async_runner.run(host.manage(command, route_to_peer=peer_id)) + assert caught.value.exceptions == (close_error, advertisement_error) + assert not candidate.published + assert store.writes == [False] + assert not claim.released + status = async_runner.run(host.status(peer_id, name)).extensions[0] + assert not status.enabled + assert status.running + assert status.error == "close callback failed\nadvertisement refresh failed" + + cold = ExtensionHost(store=typing.cast(ExtensionStore, store)) + + async def unexpected_start(*_args): + pytest.fail("cold restore attempted to start a disabled Extension") + + monkeypatch.setattr(cold, "_start", unexpected_start) + async_runner.run(cold.start_enabled(fastapi.FastAPI())) + assert not cold.running + + close_fails = False + advertisement_fails = False + if reenable: + fresh_runtime = _running(store.participation, RuntimeCandidate(), RuntimeClaim()) + + async def acquire(*_args): + return None, None + + async def open_runtime(*_args): + assert candidate.released and claim.released + host.running[name] = fresh_runtime + return fresh_runtime + + monkeypatch.setattr(host, "_acquire", acquire) + monkeypatch.setattr(host, "_start_acquired", open_runtime) + enable = EnableExtensionCommand(action="enable", extension=name) + status = async_runner.run(host.manage(enable, route_to_peer=peer_id)).extensions[0] + assert status.enabled and status.running + assert host.running[name] is fresh_runtime + assert store.writes == [False, True] + return + + status = async_runner.run(host.manage(command, route_to_peer=peer_id)).extensions[0] + assert not status.enabled + assert not status.running + assert status.error is None + assert candidate.released + assert claim.released + assert store.writes == [False] + assert refresh_count == 2 + + async_runner.run(host.manage(command, route_to_peer=peer_id)) + assert store.writes == [False] + assert refresh_count == 2 + + +def test_disable_leaves_runtime_running_when_intent_write_fails(async_runner): + peer_id = uuid.uuid4() + store = ParticipationStore(_participation(peer_id).model_copy(update={"enabled": True})) + name = store.participation.name + store.write_error = RuntimeError("intent write failed") + host = ExtensionHost(store=typing.cast(ExtensionStore, store)) + candidate = RuntimeCandidate() + running = _running(store.participation, candidate, RuntimeClaim()) + host.running[name] = running + + with pytest.raises(RuntimeError, match="intent write failed"): + async_runner.run(host.disable(name, peer_id=peer_id)) + assert store.participation.enabled + assert store.writes == [False] + assert not candidate.closed + assert host.running[name] is running From 2627506ece8d647d3965201a185df3a804b7c505 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:28:12 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix(extensions):=20=E7=94=B1=20Peer=20?= =?UTF-8?q?=E8=B4=9F=E8=B4=A3=E5=B9=BF=E6=92=AD=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/business/extension/main.py | 9 +++--- ...extension_participation_lifecycle_races.py | 28 ++++++++++++++++++- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/app/business/extension/main.py b/app/business/extension/main.py index 237a368f..62195f3b 100644 --- a/app/business/extension/main.py +++ b/app/business/extension/main.py @@ -974,18 +974,19 @@ async def disable(self, name: str, *, peer_id: typing.Any) -> ExtensionParticipa try: await self._stop(running) except Exception as error: + self._operations[name] = (None, str(error)) failures.append(error) + else: + self._operations.pop(name, None) if published: try: await PeerManager.refresh_self(settings.peer_lease_ttl_seconds) except Exception as error: failures.append(error) + if len(failures) == 1: + raise failures[0] if failures: - self._operations[name] = (None, "\n".join(str(error) for error in failures)) - if len(failures) == 1: - raise failures[0] raise ExceptionGroup("Extension disable failed", failures) - self._operations.pop(name, None) return selection async def start_enabled(self, app: fastapi.FastAPI) -> None: diff --git a/tests/test_extension_participation_lifecycle_races.py b/tests/test_extension_participation_lifecycle_races.py index e31e1893..85e0540e 100644 --- a/tests/test_extension_participation_lifecycle_races.py +++ b/tests/test_extension_participation_lifecycle_races.py @@ -204,7 +204,7 @@ async def refresh(_ttl: int) -> None: status = async_runner.run(host.status(peer_id, name)).extensions[0] assert not status.enabled assert status.running - assert status.error == "close callback failed\nadvertisement refresh failed" + assert status.error == "close callback failed" cold = ExtensionHost(store=typing.cast(ExtensionStore, store)) @@ -251,6 +251,32 @@ async def open_runtime(*_args): assert refresh_count == 2 +def test_disable_retry_does_not_report_a_stale_advertisement_error( + async_runner, monkeypatch +): + peer_id = uuid.uuid4() + store = ParticipationStore(_participation(peer_id).model_copy(update={"enabled": True})) + name = store.participation.name + host = ExtensionHost(store=typing.cast(ExtensionStore, store)) + candidate = RuntimeCandidate() + host.running[name] = _running(store.participation, candidate, RuntimeClaim()) + + async def refresh(_ttl: int) -> None: + raise RuntimeError("advertisement refresh failed") + + monkeypatch.setattr(candidate, "peer_inbounds", lambda: True) + monkeypatch.setattr(extension_main.PeerManager, "get_current_peer_ref", lambda: peer_id) + monkeypatch.setattr(extension_main.PeerManager, "refresh_self", refresh) + command = DisableExtensionCommand(action="disable", extension=name) + + with pytest.raises(RuntimeError, match="advertisement refresh failed"): + async_runner.run(host.manage(command, route_to_peer=peer_id)) + retry = async_runner.run(host.manage(command, route_to_peer=peer_id)).extensions[0] + assert not retry.enabled + assert not retry.running + assert retry.error is None + + def test_disable_leaves_runtime_running_when_intent_write_fails(async_runner): peer_id = uuid.uuid4() store = ParticipationStore(_participation(peer_id).model_copy(update={"enabled": True})) From d9947fdb2e497ab4ce2c0477746b2288d362cbe9 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:31:58 +0800 Subject: [PATCH 3/3] =?UTF-8?q?docs(changelog):=20=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E6=89=A9=E5=B1=95=E5=81=9C=E7=94=A8=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .changes/extension-disable-intent.fixed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 .changes/extension-disable-intent.fixed.md diff --git a/.changes/extension-disable-intent.fixed.md b/.changes/extension-disable-intent.fixed.md new file mode 100644 index 00000000..62010901 --- /dev/null +++ b/.changes/extension-disable-intent.fixed.md @@ -0,0 +1 @@ +Stopping an extension saves the requested disabled state before running shutdown hooks, so a cleanup failure does not enable it on restart.