From e604c23fcaa90830395b5ac870f67ae048fb5c79 Mon Sep 17 00:00:00 2001 From: chengyongru <2755839590@qq.com> Date: Thu, 15 Oct 2026 02:07:53 +0800 Subject: [PATCH] fix(sdk): validate imported messages before session changes --- nanobot/sdk/clients.py | 13 ++++--- tests/test_nanobot_facade.py | 71 +++++++++++++++++++++++++++++++++++- 2 files changed, 78 insertions(+), 6 deletions(-) diff --git a/nanobot/sdk/clients.py b/nanobot/sdk/clients.py index 6a6b0943b..ebb00dae2 100644 --- a/nanobot/sdk/clients.py +++ b/nanobot/sdk/clients.py @@ -39,10 +39,8 @@ class SessionClient: save: bool = True, ) -> SessionSnapshot: """Import an existing transcript without running the model.""" - session = self._loop.sessions.get_or_create(session_key) - if metadata: - session.metadata.update(deepcopy(dict(metadata))) - + prepared_metadata = deepcopy(dict(metadata)) if metadata else {} + prepared: list[tuple[str, Any, dict[str, Any]]] = [] for raw in messages: if "role" not in raw: raise ValueError("ingested messages must include a role") @@ -58,7 +56,12 @@ class SessionClient: } if source is not None and "source" not in extra: extra["source"] = source - session.add_message(role, deepcopy(raw["content"]), **extra) + prepared.append((role, deepcopy(raw["content"]), extra)) + + session = self._loop.sessions.get_or_create(session_key) + session.metadata.update(prepared_metadata) + for role, content, extra in prepared: + session.add_message(role, content, **extra) if save: self._loop.sessions.save(session) diff --git a/tests/test_nanobot_facade.py b/tests/test_nanobot_facade.py index 99710a77a..cdd6802fa 100644 --- a/tests/test_nanobot_facade.py +++ b/tests/test_nanobot_facade.py @@ -1445,6 +1445,7 @@ async def test_sessions_ingest_imports_transcript_without_running_model(tmp_path "role": "assistant", "content": "Congratulations on your degree.", "timestamp": "2023/05/30 (Tue) 17:27", + "source": "original-source", }, ], metadata={"title": "LongMemEval case"}, @@ -1458,13 +1459,81 @@ async def test_sessions_ingest_imports_transcript_without_running_model(tmp_path assert snapshot.messages[0]["timestamp"] == "2023/05/30 (Tue) 17:27" assert snapshot.messages[0]["source_session_id"] == "answer_1" assert snapshot.messages[0]["source"] == "longmemeval" - assert snapshot.messages[1]["source"] == "longmemeval" + assert snapshot.messages[1]["source"] == "original-source" bot._loop.process_direct.assert_not_called() reloaded = bot.sessions.get("sdk:history") assert reloaded is not None assert reloaded.messages == snapshot.messages + await bot.aclose() + async with Nanobot.from_config(config_path, workspace=tmp_path) as restarted: + assert restarted.sessions.export("sdk:history") == snapshot + + +@pytest.mark.asyncio +async def test_sessions_ingest_without_save_detaches_inputs_and_can_be_flushed(tmp_path): + config_path = _write_config(tmp_path) + metadata = {"import": {"dataset": "original"}} + messages = [{ + "role": " user ", + "content": [{"type": "text", "text": "hello"}], + "import_info": {"index": 1}, + }] + async with Nanobot.from_config(config_path, workspace=tmp_path) as bot: + snapshot = await bot.sessions.ingest( + "sdk:unsaved", iter(messages), metadata=metadata, save=False, + ) + metadata["import"]["dataset"] = "changed" + messages[0]["content"][0]["text"] = "changed" + messages[0]["import_info"]["index"] = 2 + + assert snapshot.metadata == {"import": {"dataset": "original"}} + assert snapshot.messages[0]["role"] == "user" + assert snapshot.messages[0]["content"] == [{"type": "text", "text": "hello"}] + assert snapshot.messages[0]["import_info"] == {"index": 1} + assert bot.sessions.get("sdk:unsaved") == snapshot + async with Nanobot.from_config(config_path, workspace=tmp_path) as reader: + assert reader.sessions.export("sdk:unsaved") is None + assert bot.sessions.flush() == 1 + + async with Nanobot.from_config(config_path, workspace=tmp_path) as restarted: + assert restarted.sessions.export("sdk:unsaved") == snapshot + + +@pytest.mark.asyncio +@pytest.mark.parametrize("existing", [False, True], ids=["new-session", "existing-session"]) +@pytest.mark.parametrize("invalid_message", [ + pytest.param({"role": "developer", "content": "invalid role"}, id="role"), + pytest.param({"role": "assistant"}, id="content"), +]) +async def test_sessions_ingest_rejects_batch_without_session_changes( + tmp_path, existing, invalid_message, +): + config_path = _write_config(tmp_path) + key = "sdk:rejected" + async with Nanobot.from_config(config_path, workspace=tmp_path) as bot: + if existing: + await bot.sessions.ingest( + key, [{"role": "user", "content": "original history"}], + metadata={"title": "Original", "import": {"dataset": "original"}}, + ) + before = bot.sessions.export(key) + + with pytest.raises(ValueError, match="role|content"): + await bot.sessions.ingest( + key, + iter([{"role": "user", "content": "valid first message"}, invalid_message]), + metadata={"title": "Changed", "new_field": "must not leak"}, + ) + + assert bot.sessions.get(key) == before + assert bot.sessions.export(key) == before + bot.sessions.flush() + + async with Nanobot.from_config(config_path, workspace=tmp_path) as restarted: + assert restarted.sessions.export(key) == before + @pytest.mark.asyncio async def test_sessions_ingest_preserves_full_transcript(tmp_path):