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. 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 b607f36c..d54a866c 100644 --- a/app/business/extension/main.py +++ b/app/business/extension/main.py @@ -171,6 +171,7 @@ class RunningExtension: acquired: AcquiredDistribution extension_class: type[ExtensionBase] claim: ExtensionRuntimeClaim + stopping: bool = False class ExtensionHost: @@ -748,7 +749,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) @@ -827,14 +830,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() @@ -844,6 +855,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: @@ -929,16 +944,31 @@ 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: + self._operations[name] = (None, str(error)) + failures.append(error) + else: + self._operations.pop(name, None) 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 len(failures) == 1: + raise failures[0] + if failures: + raise ExceptionGroup("Extension disable failed", failures) + 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/tasks/test-contract-audit-20261127/pruning.md b/tasks/test-contract-audit-20261127/pruning.md index f82dcdf8..9c19329b 100644 --- a/tasks/test-contract-audit-20261127/pruning.md +++ b/tasks/test-contract-audit-20261127/pruning.md @@ -13,6 +13,8 @@ ## 保留复核 +整合 #208 时,保持上述旧替身测试的删除。原场景已由真实 PostgreSQL 和 HTTP 验证启动中撤回,新增的停用顺序由同一 Host 验收文件承担。关闭回调在独立数据库会话中看到已提交的禁用意图,真实路由和 Peer inbound 随失败撤销,新 Host 冷启动跳过禁用条目,重试完成剩余清理。另有临时数据库拒绝写入与单独广播失败的场景。 + 独立复核后,在现有测试输入中补回五处区别。用单独进程替换相关生产行为,五处均因目标差异失败。未恢复整套重放。 - 中文词法样本增加近主题但不含原词的 Memo。查询过宽时结果多一条。 diff --git a/tests/test_extension_startup_provision.py b/tests/test_extension_startup_provision.py index b0ee24e1..8ecadc2d 100644 --- a/tests/test_extension_startup_provision.py +++ b/tests/test_extension_startup_provision.py @@ -1,13 +1,22 @@ +import os from pathlib import Path from types import SimpleNamespace import typing import pytest import fastapi +import sqlalchemy as sa +from sqlalchemy.exc import IntegrityError from fastapi.testclient import TestClient from inkcre_core.business.deployment_config import DeploymentConfigService -from inkcre_core.schemas.extension import ExtensionModel, ExtensionPeerParticipationModel +from inkcre_core.context import current_core +from inkcre_core.schemas.extension import ( + DisableExtensionCommand, + EnableExtensionCommand, + ExtensionModel, + ExtensionPeerParticipationModel, +) from inkcre_core.schemas.peer import PeerModel from tests.database import TestSession @@ -17,6 +26,7 @@ ExtensionCompatibilityError, ) from app.business.extension.main import ExtensionHost +from app.business.peer import PeerHTTPInbound def release(name: str, version: str) -> dict: @@ -236,6 +246,163 @@ async def on_close(cls): async_runner.run(host.close_running()) +@pytest.fixture +def running_probe(pin, async_runner, packages, monkeypatch): + name = "inkcre/mail" + peer = extension_main.PeerManager.get_current_peer_ref() + app = fastapi.FastAPI() + host = ExtensionHost() + events = [] + probe = SimpleNamespace(name=name, peer=peer, host=host, events=events, close_error=None) + + def enabled_in_database(): + with TestSession() as db: + selection = db.get(ExtensionPeerParticipationModel, {"name": name, "peer_id": peer}) + assert selection is not None + return selection.enabled + + class Probe(extension_main.ExtensionBase, ext_id="mail"): + @classmethod + def api_dependencies(cls): + return [] + + @classmethod + def _register_apis(cls, router): + router.add_api_route("/probe", lambda: "available") + + @classmethod + def peer_inbounds(cls): + return ( + PeerHTTPInbound( + capability="test.extension.disable.probe.v1", method="GET", path="/mail/probe" + ), + ) + + @classmethod + async def on_start_async(cls, app): + await super().on_start_async(app) + events.append(("start", enabled_in_database())) + + @classmethod + async def on_close(cls): + events.append(("close", enabled_in_database())) + if probe.close_error is not None: + raise probe.close_error + + monkeypatch.setattr( + extension_main, + "DistributionModules", + lambda _: SimpleNamespace(load=lambda base: Probe, assert_origins=lambda: None), + ) + pin(name, "0.3.3") + async_runner.run(host.provision_enabled_distributions()) + with TestClient(app) as client: + async_runner.run(host.start_enabled(app)) + assert client.get("/mail/probe").json() == "available" + probe.client = client + try: + yield probe + finally: + probe.close_error = None + async_runner.run(host.close_running()) + + +@pytest.mark.parametrize("reenable", [False, True], ids=["disable-retry", "reenable"]) +def test_disable_persists_intent_before_failed_cleanup_and_allows_retry( + running_probe, async_runner, monkeypatch, reenable +): + probe = running_probe + disable = DisableExtensionCommand(action="disable", extension=probe.name) + close_error = RuntimeError("close callback failed") + refresh_error = RuntimeError("advertisement refresh failed") + probe.close_error = close_error + + async def refresh(_ttl): + assert probe.client.get("/mail/probe").status_code == 404 + assert "test.extension.disable.probe.v1" not in current_core().inbounds + raise refresh_error + + monkeypatch.setattr(extension_main.PeerManager, "refresh_self", refresh) + with pytest.raises(ExceptionGroup) as caught: + async_runner.run(probe.host.manage_local(disable)) + assert caught.value.exceptions == (close_error, refresh_error) + assert probe.events == [("start", True), ("close", False)] + (failed,) = async_runner.run(probe.host.status(probe.peer, probe.name)).extensions + assert (failed.enabled, failed.running, failed.error) == (False, True, str(close_error)) + + cold = ExtensionHost() + cold_app = fastapi.FastAPI() + async_runner.run(cold.start_enabled(cold_app)) + (restored,) = async_runner.run(cold.status(probe.peer, probe.name)).extensions + assert (restored.enabled, restored.running) == (False, False) + assert TestClient(cold_app).get("/mail/probe").status_code == 404 + + probe.close_error = None + + async def refresh_ok(_ttl): + pass + + monkeypatch.setattr(extension_main.PeerManager, "refresh_self", refresh_ok) + if reenable: + enable = EnableExtensionCommand(action="enable", extension=probe.name) + (retried,) = async_runner.run(probe.host.manage_local(enable)).extensions + assert (retried.enabled, retried.running, retried.error) == (True, True, None) + assert probe.events[-2:] == [("close", True), ("start", True)] + assert probe.client.get("/mail/probe").json() == "available" + else: + (retried,) = async_runner.run(probe.host.manage_local(disable)).extensions + assert (retried.enabled, retried.running, retried.error) == (False, False, None) + assert probe.events[-1] == ("close", False) + assert probe.client.get("/mail/probe").status_code == 404 + assert async_runner.run(probe.host.manage_local(disable)).extensions == (retried,) + assert probe.events.count(("close", False)) == 2 + + +def test_disable_retry_does_not_report_a_stale_advertisement_error( + running_probe, async_runner, monkeypatch +): + probe = running_probe + + async def refresh(_ttl): + raise RuntimeError("advertisement refresh failed") + + monkeypatch.setattr(extension_main.PeerManager, "refresh_self", refresh) + command = DisableExtensionCommand(action="disable", extension=probe.name) + with pytest.raises(RuntimeError, match="advertisement refresh failed"): + async_runner.run(probe.host.manage_local(command)) + (retried,) = async_runner.run(probe.host.manage_local(command)).extensions + assert (retried.enabled, retried.running, retried.error) == (False, False, None) + assert probe.events == [("start", True), ("close", False)] + + +def test_disable_leaves_runtime_running_when_database_rejects_intent( + running_probe, async_runner +): + probe = running_probe + with TestSession() as db: + database = db.connection().engine.url.database + admin = sa.engine.make_url(os.environ["INKCRE_TEST_POSTGRES_ADMIN_URL"]).set( + database=database, drivername="postgresql+psycopg" + ) + engine = sa.create_engine(admin) + try: + with engine.begin() as db: + db.exec_driver_sql( + "ALTER TABLE inkcre.extension_peer_participations " + "ADD CONSTRAINT test_disable_write_refused CHECK (enabled)" + ) + finally: + engine.dispose() + + command = DisableExtensionCommand(action="disable", extension=probe.name) + with pytest.raises(IntegrityError, match="test_disable_write_refused"): + async_runner.run(probe.host.manage_local(command)) + (unchanged,) = async_runner.run(probe.host.status(probe.peer, probe.name)).extensions + assert (unchanged.enabled, unchanged.running) == (True, True) + assert probe.events == [("start", True)] + assert probe.client.get("/mail/probe").json() == "available" + + def test_startup_rejects_enabled_module_federation_without_mutation( pin, async_runner, packages ) -> None: