refactor(sessions)!: retire the global shared session (#6621)
Co-authored-by: chengyongru <chengyongru.ai@gmail.com>
This commit is contained in:
1 parent
28d73b6942
commit
e6b0aec2a8
77 files changed
+311
-1255
No files matched your search
@@ -51,7 +51,6 @@ class GatewayServices:
|
||||
local_trigger_store: LocalTriggerStore | None
|
||||
cron_pending_job_ids: Callable[[str], set[str]] | None
|
||||
local_trigger_pending_ids: Callable[[str], set[str]] | None
|
||||
unified_session: bool = False
|
||||
|
||||
|
||||
def build_gateway_services(
|
||||
@@ -62,7 +61,6 @@ def build_gateway_services(
|
||||
static_dist_path: Path | None,
|
||||
workspace_path: Path,
|
||||
default_restrict_to_workspace: bool,
|
||||
unified_session: bool = False,
|
||||
config_path: Path | None = None,
|
||||
runtime_model_name: Callable[[], str | None] | None,
|
||||
refresh_runtime_config: Callable[[], None] | None = None,
|
||||
@@ -171,5 +169,4 @@ def build_gateway_services(
|
||||
local_trigger_store=local_trigger_store,
|
||||
cron_pending_job_ids=cron_pending_job_ids,
|
||||
local_trigger_pending_ids=local_trigger_pending_ids,
|
||||
unified_session=unified_session,
|
||||
)
|
||||
@@ -29,7 +29,6 @@ from nanobot.security.workspace_access import (
|
||||
WorkspaceScopeError,
|
||||
)
|
||||
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
|
||||
from nanobot.session.keys import session_key_for_channel
|
||||
from nanobot.session.webui_turns import (
|
||||
clear_websocket_turn_if_current,
|
||||
clear_websocket_turns,
|
||||
@@ -125,7 +124,6 @@ class WebUICommandTransport(Protocol):
|
||||
media: list[str] | None,
|
||||
metadata: dict[str, Any],
|
||||
is_dm: bool,
|
||||
session_key: str | None,
|
||||
require_existing_session: bool,
|
||||
session_generation: str | None,
|
||||
) -> None: ...
|
||||
@@ -313,7 +311,6 @@ class WebUICommandRouter:
|
||||
WORKSPACE_SCOPE_METADATA_KEY: scope.metadata(),
|
||||
},
|
||||
is_dm=False,
|
||||
session_key=None,
|
||||
require_existing_session=False,
|
||||
session_generation=None,
|
||||
)
|
||||
@@ -651,7 +648,7 @@ class WebUICommandRouter:
|
||||
)
|
||||
return
|
||||
self._transport.webui_attach(connection, chat_id)
|
||||
if temporary_policy is None or temporary_policy.hydrate_transcript:
|
||||
if temporary_policy is None:
|
||||
await self._outbound.hydrate(chat_id)
|
||||
|
||||
scope = temporary_policy.workspace_scope if temporary_policy is not None else (
|
||||
@@ -766,22 +763,8 @@ class WebUICommandRouter:
|
||||
metadata[WEBSOCKET_TURN_OWNER_METADATA_KEY] = queued_owner
|
||||
|
||||
accepted = False
|
||||
admission_session_key = (
|
||||
temporary_policy.session_key
|
||||
if temporary_policy is not None
|
||||
else webui_session_key(chat_id)
|
||||
)
|
||||
execution_session_key = (
|
||||
temporary_policy.session_key
|
||||
if temporary_policy is not None
|
||||
else session_key_for_channel(
|
||||
"websocket", chat_id, unified_session=self.gateway.unified_session,
|
||||
)
|
||||
)
|
||||
session_generation: str | None = None
|
||||
session_created = False
|
||||
execution_generation: str | None = None
|
||||
execution_created = False
|
||||
try:
|
||||
if not restart_control:
|
||||
admission = await self.workspace_scope_or_error(
|
||||
@@ -789,7 +772,6 @@ class WebUICommandRouter:
|
||||
lambda: self._workspaces.persist_scope(
|
||||
chat_id,
|
||||
scope,
|
||||
session_key=admission_session_key,
|
||||
expected_generation=(
|
||||
temporary_policy.session_generation
|
||||
if temporary_policy is not None
|
||||
@@ -802,21 +784,9 @@ class WebUICommandRouter:
|
||||
if admission is None:
|
||||
return
|
||||
session_generation, session_created = admission
|
||||
execution_generation = session_generation
|
||||
if (
|
||||
execution_session_key != admission_session_key
|
||||
and self.gateway.session_manager is not None
|
||||
):
|
||||
execution_generation, execution_created = (
|
||||
await self.gateway.session_manager.state.open_with_metadata(
|
||||
execution_session_key, {},
|
||||
)
|
||||
)
|
||||
if session_generation is not None:
|
||||
metadata[HISTORY_GENERATION_METADATA_KEY] = session_generation
|
||||
if is_webui and not restart_control and (
|
||||
temporary_policy is None or temporary_policy.persist_transcript
|
||||
):
|
||||
if is_webui and not restart_control and temporary_policy is None:
|
||||
await self._transcripts.append_user_message(
|
||||
chat_id,
|
||||
content,
|
||||
@@ -850,18 +820,8 @@ class WebUICommandRouter:
|
||||
media=media_paths or None,
|
||||
metadata=metadata,
|
||||
is_dm=False,
|
||||
session_key=(
|
||||
execution_session_key
|
||||
if temporary_policy is not None
|
||||
or execution_session_key != admission_session_key
|
||||
else None
|
||||
),
|
||||
require_existing_session=(
|
||||
temporary_policy.require_existing_session
|
||||
if temporary_policy is not None
|
||||
else False
|
||||
),
|
||||
session_generation=execution_generation,
|
||||
require_existing_session=temporary_policy is not None,
|
||||
session_generation=session_generation,
|
||||
)
|
||||
accepted = True
|
||||
if turn_id:
|
||||
@@ -870,12 +830,7 @@ class WebUICommandRouter:
|
||||
del self._accepted_messages[next(iter(self._accepted_messages))]
|
||||
except BaseException:
|
||||
await self._workspaces.rollback_scope_admission(
|
||||
execution_session_key,
|
||||
execution_generation,
|
||||
created=execution_created,
|
||||
)
|
||||
await self._workspaces.rollback_scope_admission(
|
||||
admission_session_key,
|
||||
chat_id,
|
||||
session_generation,
|
||||
created=session_created,
|
||||
)
|
||||
|
||||
+13
-38
@@ -18,7 +18,6 @@ from nanobot.bus.outbound_events import (
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.session import turn_continuation
|
||||
from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY, last_channel_from_metadata
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.session.recovery import (
|
||||
KNOWN_CHECKPOINT_PHASES,
|
||||
@@ -56,7 +55,6 @@ class RecoveryCoordinator:
|
||||
|
||||
sessions: SessionManager
|
||||
bus: MessageBus
|
||||
unified_session: bool = False
|
||||
_active_recovery_tasks: dict[str, asyncio.Task[Any]] = dataclasses.field(
|
||||
default_factory=dict,
|
||||
init=False,
|
||||
@@ -87,19 +85,20 @@ class RecoveryCoordinator:
|
||||
from nanobot.webui.history import initialize_history
|
||||
|
||||
await initialize_history(self.sessions)
|
||||
for key in await self._recovery_candidates():
|
||||
for item in await self.sessions.state.list_sessions():
|
||||
key = item["key"]
|
||||
chat_id = webui_chat_id(key)
|
||||
if chat_id is None:
|
||||
continue
|
||||
metadata_payload = await self.sessions.state.read_metadata(key)
|
||||
raw_metadata = metadata_payload.get("metadata") if metadata_payload else None
|
||||
metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
|
||||
route = self._websocket_route_for(key, metadata)
|
||||
if route is None:
|
||||
continue
|
||||
unfinished = await self._has_unfinished_webui_transcript(key)
|
||||
if not self._needs_recovery(metadata) and not unfinished:
|
||||
continue
|
||||
session = await self.sessions.state.get(key)
|
||||
try:
|
||||
await self._recover_session(session, route[1])
|
||||
await self._recover_session(session, chat_id)
|
||||
await self._close_interrupted_turns(session)
|
||||
await self._requeue_pending_followups(session)
|
||||
except Exception:
|
||||
@@ -114,10 +113,7 @@ class RecoveryCoordinator:
|
||||
can_continue=False,
|
||||
)
|
||||
await self.sessions.state.restore_interruption(session)
|
||||
await self._publish(route[1], failed)
|
||||
|
||||
async def _recovery_candidates(self) -> list[str]:
|
||||
return [item["key"] for item in await self.sessions.state.list_sessions()]
|
||||
await self._publish(chat_id, failed)
|
||||
|
||||
@staticmethod
|
||||
def _needs_recovery(metadata: Mapping[str, Any]) -> bool:
|
||||
@@ -179,11 +175,11 @@ class RecoveryCoordinator:
|
||||
failure_error_kind: str | None = None,
|
||||
) -> None:
|
||||
"""Offer explicit continuation of committed model failures or resolve recovery."""
|
||||
chat_id = webui_chat_id(session_key)
|
||||
if chat_id is None:
|
||||
return
|
||||
session = await self.sessions.state.get(session_key)
|
||||
state = recovery_state_from_metadata(session.metadata)
|
||||
route = self._websocket_route(session)
|
||||
if route is None:
|
||||
return
|
||||
if failure_kind == "model":
|
||||
# The turn has already saved its transcript and tool results. Use
|
||||
# that context, never resend the user's message or replay tools.
|
||||
@@ -199,7 +195,7 @@ class RecoveryCoordinator:
|
||||
if session.messages and session.messages[-1].get("_interrupted") is True:
|
||||
waiting["reply_preserved"] = True
|
||||
await self.sessions.state.restore_interruption(session)
|
||||
await self._publish(route[1], waiting)
|
||||
await self._publish(chat_id, waiting)
|
||||
return
|
||||
if not state or state["status"] != "resuming":
|
||||
return
|
||||
@@ -211,7 +207,7 @@ class RecoveryCoordinator:
|
||||
reason="continued",
|
||||
)
|
||||
await self.sessions.state.restore_interruption(session)
|
||||
await self._publish(route[1], recovered)
|
||||
await self._publish(chat_id, recovered)
|
||||
|
||||
async def handle_action(self, action: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Apply an authenticated continue/dismiss operation."""
|
||||
@@ -221,7 +217,7 @@ class RecoveryCoordinator:
|
||||
raise RecoveryActionError("missing chat_id")
|
||||
if not isinstance(recovery_id, str) or not recovery_id:
|
||||
raise RecoveryActionError("missing recovery_id")
|
||||
session = await self.sessions.state.get(self._session_key(chat_id))
|
||||
session = await self.sessions.state.get(webui_session_key(chat_id))
|
||||
state = recovery_state_from_metadata(session.metadata)
|
||||
if not state or state["recovery_id"] != recovery_id:
|
||||
raise RecoveryActionError("recovery state is stale", status=409)
|
||||
@@ -521,9 +517,6 @@ class RecoveryCoordinator:
|
||||
session.updated_at = datetime.now()
|
||||
return state
|
||||
|
||||
def _session_key(self, chat_id: str) -> str:
|
||||
return UNIFIED_SESSION_KEY if self.unified_session else webui_session_key(chat_id)
|
||||
|
||||
async def _has_unfinished_webui_transcript(self, session_key: str) -> bool:
|
||||
from nanobot.webui.transcript import has_unfinished_transcript_tail
|
||||
|
||||
@@ -553,21 +546,3 @@ class RecoveryCoordinator:
|
||||
for message in tail
|
||||
)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _websocket_route(session: Session) -> tuple[str, str] | None:
|
||||
return RecoveryCoordinator._websocket_route_for(session.key, session.metadata)
|
||||
|
||||
@staticmethod
|
||||
def _websocket_route_for(
|
||||
session_key: str,
|
||||
metadata: Mapping[str, Any],
|
||||
) -> tuple[str, str] | None:
|
||||
chat_id = webui_chat_id(session_key)
|
||||
if chat_id is not None:
|
||||
return ("websocket", chat_id)
|
||||
if session_key == UNIFIED_SESSION_KEY:
|
||||
route = last_channel_from_metadata(metadata)
|
||||
if route and route[0] == "websocket":
|
||||
return route
|
||||
return None
|
||||
@@ -18,7 +18,6 @@ from nanobot.webui.settings_contracts import WebUISettingsError
|
||||
RUNTIME_CONFIG_PATHS = (
|
||||
"agents.defaults.timezone",
|
||||
"agents.defaults.timezone_mode",
|
||||
"agents.defaults.unified_session",
|
||||
"agents.defaults.session_ttl_minutes",
|
||||
"agents.defaults.max_tool_iterations",
|
||||
"agents.defaults.max_concurrent_subagents",
|
||||
|
||||
@@ -158,7 +158,6 @@ def system_settings_payload(
|
||||
"dream": {
|
||||
"schedule": defaults.dream.describe_schedule(),
|
||||
},
|
||||
"unified_session": defaults.unified_session,
|
||||
},
|
||||
"advanced": {
|
||||
"restrict_to_workspace": config.tools.restrict_to_workspace,
|
||||
|
||||
@@ -15,6 +15,7 @@ from nanobot.command.application import register_builtin_commands
|
||||
from nanobot.command.router import CommandRouter
|
||||
from nanobot.security.workspace_access import WorkspaceScope
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.webui.session_identity import webui_session_key
|
||||
from nanobot.webui.workspaces import WebUIWorkspaceController
|
||||
|
||||
_TEMPORARY_CHAT_DISABLED_TOOLS = frozenset({
|
||||
@@ -38,12 +39,8 @@ class TemporaryChatError(ValueError):
|
||||
class TemporaryChatMessagePolicy:
|
||||
"""Server-owned message rules for one active Temporary Chat."""
|
||||
|
||||
session_key: str
|
||||
session_generation: str
|
||||
workspace_scope: WorkspaceScope
|
||||
require_existing_session: bool = True
|
||||
hydrate_transcript: bool = False
|
||||
persist_transcript: bool = False
|
||||
|
||||
|
||||
class WebUITemporaryChats:
|
||||
@@ -56,13 +53,11 @@ class WebUITemporaryChats:
|
||||
session_manager: SessionManager | None,
|
||||
workspaces: WebUIWorkspaceController,
|
||||
logger: Any,
|
||||
channel_name: str = "websocket",
|
||||
) -> None:
|
||||
self._bus = bus
|
||||
self._sessions = session_manager
|
||||
self._workspaces = workspaces
|
||||
self._logger = logger
|
||||
self._channel_name = channel_name
|
||||
self._commands = CommandRouter()
|
||||
register_builtin_commands(self._commands)
|
||||
self._owners: dict[str, object] = {}
|
||||
@@ -72,13 +67,10 @@ class WebUITemporaryChats:
|
||||
self._known_transient_chat_ids: set[str] = set()
|
||||
self._media_paths: dict[str, set[str]] = {}
|
||||
|
||||
def _session_key(self, chat_id: str) -> str:
|
||||
return f"{self._channel_name}:{chat_id}"
|
||||
|
||||
def _cached_session_is_transient(self, chat_id: str) -> bool:
|
||||
if self._sessions is None:
|
||||
return False
|
||||
identity = self._sessions.state.peek_identity(self._session_key(chat_id))
|
||||
identity = self._sessions.state.peek_identity(webui_session_key(chat_id))
|
||||
return identity is not None and not identity.policy.persist
|
||||
|
||||
async def create(self, owner: object, *, trusted_webui: bool) -> str:
|
||||
@@ -90,7 +82,7 @@ class WebUITemporaryChats:
|
||||
|
||||
chat_id = str(uuid.uuid4())
|
||||
session = await self._sessions.state.register_transient(
|
||||
self._session_key(chat_id),
|
||||
webui_session_key(chat_id),
|
||||
disabled_tools=_TEMPORARY_CHAT_DISABLED_TOOLS,
|
||||
)
|
||||
if session.policy.persist:
|
||||
@@ -114,7 +106,7 @@ class WebUITemporaryChats:
|
||||
if self._owners.get(chat_id) is not owner or self._sessions is None:
|
||||
raise TemporaryChatError("temporary_chat_unavailable")
|
||||
|
||||
identity = self._sessions.state.peek_identity(self._session_key(chat_id))
|
||||
identity = self._sessions.state.peek_identity(webui_session_key(chat_id))
|
||||
if identity is None:
|
||||
raise TemporaryChatError("temporary_chat_unavailable")
|
||||
|
||||
@@ -123,7 +115,6 @@ class WebUITemporaryChats:
|
||||
raise TemporaryChatError("temporary_chat_command_rejected")
|
||||
|
||||
return TemporaryChatMessagePolicy(
|
||||
session_key=self._session_key(chat_id),
|
||||
session_generation=identity.generation,
|
||||
workspace_scope=self._workspaces.restricted_default_scope(),
|
||||
)
|
||||
@@ -187,21 +178,20 @@ class WebUITemporaryChats:
|
||||
):
|
||||
raise TemporaryChatError("temporary_chat_unavailable")
|
||||
|
||||
session_key = self._session_key(chat_id)
|
||||
session_key = webui_session_key(chat_id)
|
||||
self._forget_owner(owner, chat_id)
|
||||
self._discard_media(chat_id)
|
||||
if self._sessions is not None:
|
||||
await self._sessions.state.discard(session_key)
|
||||
await self._bus.publish_inbound(
|
||||
InboundMessage(
|
||||
channel=self._channel_name,
|
||||
channel="websocket",
|
||||
sender_id="webui",
|
||||
chat_id=chat_id,
|
||||
content="",
|
||||
metadata={
|
||||
INBOUND_META_RUNTIME_CONTROL: RUNTIME_CONTROL_SESSION_DISCARD,
|
||||
},
|
||||
session_key_override=session_key,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -210,7 +200,7 @@ class WebUITemporaryChats:
|
||||
for chat_id in tuple(self._owners):
|
||||
self._discard_media(chat_id)
|
||||
if self._sessions is not None:
|
||||
self._sessions.state.forget_transient(self._session_key(chat_id))
|
||||
self._sessions.state.forget_transient(webui_session_key(chat_id))
|
||||
self._owners.clear()
|
||||
self._owner_chat_ids.clear()
|
||||
self._known_transient_chat_ids.clear()
|
||||
@@ -491,12 +491,11 @@ class WebUIWorkspaceController:
|
||||
chat_id: str,
|
||||
scope: WorkspaceScope,
|
||||
*,
|
||||
session_key: str | None = None,
|
||||
expected_generation: str | None = None,
|
||||
) -> tuple[str | None, bool]:
|
||||
async with self._scope_lock(chat_id):
|
||||
return await self._persist_scope(
|
||||
session_key or webui_session_key(chat_id), scope, expected_generation,
|
||||
webui_session_key(chat_id), scope, expected_generation,
|
||||
)
|
||||
|
||||
async def _persist_scope(
|
||||
@@ -517,7 +516,7 @@ class WebUIWorkspaceController:
|
||||
|
||||
async def rollback_scope_admission(
|
||||
self,
|
||||
session_key: str,
|
||||
chat_id: str,
|
||||
generation: str | None,
|
||||
*,
|
||||
created: bool,
|
||||
@@ -526,7 +525,7 @@ class WebUIWorkspaceController:
|
||||
if not created or generation is None or self._sessions is None:
|
||||
return
|
||||
await self._sessions.state.delete(
|
||||
session_key,
|
||||
webui_session_key(chat_id),
|
||||
expected_generation=generation,
|
||||
)
|
||||
|
||||
|
||||
Reference in new issue
Block a user