Revert "refactor: remove legacy history and proxy migrations (#6518)"
This reverts commit cb3ba45317.
Keep JSONL history and legacy proxy migration available throughout 0.4.x. Mark their removal for 0.5.0 in code and release guidance, preserving later context graph, archive and recovery changes.
This commit is contained in:
1 parent
3918ece17f
commit
812b92d734
47 files changed
+1932
-204
No files matched your search
@@ -147,6 +147,7 @@ async def test_recovery_continuation_runs_without_a_sustained_goal(
|
||||
async def test_recovery_preserves_turn_origin_until_the_next_user_turn(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, late_result: bool,
|
||||
) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.history.get_webui_dir", lambda: tmp_path / "webui")
|
||||
bus = MessageBus()
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
|
||||
|
||||
def test_distinct_keys_roundtrip_independently(tmp_path):
|
||||
def test_colliding_display_names_roundtrip_independently(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
keys = ("telegram:a_b", "telegram:a:b", "telegram:a/b", "telegram:你好")
|
||||
for key in keys:
|
||||
session = Session(key=key)
|
||||
session.add_message("user", key)
|
||||
manager.save(session)
|
||||
assert manager.safe_key(keys[0]) == manager.safe_key(keys[1])
|
||||
assert len(manager.list_sessions()) == len(keys)
|
||||
for key in keys:
|
||||
assert manager.read_session_file(key)["messages"][0]["content"] == key
|
||||
|
||||
@@ -57,7 +57,9 @@ async def test_session_tools_find_old_matches_in_full_session(
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("state", ["canonical", "transcript", "mixed"])
|
||||
async def test_session_tools_use_canonical_records_after_restart(history, state):
|
||||
async def test_session_tools_use_canonical_records_after_restart(history, tmp_path, monkeypatch, state):
|
||||
webui_dir = tmp_path / "webui"
|
||||
monkeypatch.setattr("nanobot.webui.history.get_webui_dir", lambda: webui_dir)
|
||||
manager = history.sessions
|
||||
key = "websocket:history"
|
||||
if state != "transcript":
|
||||
@@ -71,10 +73,16 @@ async def test_session_tools_use_canonical_records_after_restart(history, state)
|
||||
})
|
||||
history.append(key, {"event": "turn_end", "chat_id": "history"})
|
||||
|
||||
original_messages = manager.read_session_file(key)["messages"]
|
||||
original_display_facts = manager.project_history(key, lambda reader: reader.all_facts())
|
||||
def durable_files():
|
||||
return {
|
||||
path: path.read_bytes()
|
||||
for root in (manager.sessions_dir, webui_dir)
|
||||
for path in root.rglob("*.jsonl")
|
||||
}
|
||||
|
||||
original = durable_files()
|
||||
for _ in range(2):
|
||||
manager = SessionManager(history.sessions.workspace)
|
||||
manager = history.sessions
|
||||
with request_context(RequestContext(
|
||||
channel="websocket", chat_id="current", session_key="websocket:current",
|
||||
)):
|
||||
@@ -89,6 +97,4 @@ async def test_session_tools_use_canonical_records_after_restart(history, state)
|
||||
assert search["results"][0]["excerpts"][0]["content"] == "canonical needle"
|
||||
assert [item["content"] for item in json.loads(read)["messages"]] == ["canonical needle"]
|
||||
assert display_search["results"] == []
|
||||
assert manager.read_session_file(key)["messages"] == original_messages
|
||||
assert manager.project_history(key, lambda reader: reader.all_facts()) == original_display_facts
|
||||
await manager.state.aclose()
|
||||
assert durable_files() == original
|
||||
@@ -144,6 +144,7 @@ class _EmptyGatewaySessionManager:
|
||||
def state(self):
|
||||
return SimpleNamespace(
|
||||
list_sessions=AsyncMock(return_value=[]),
|
||||
migrate_history=AsyncMock(),
|
||||
record_delivery=AsyncMock(),
|
||||
aclose=AsyncMock(),
|
||||
)
|
||||
@@ -940,7 +941,7 @@ def test_provider_login_openai_codex_uses_explicit_config_proxy(tmp_path, monkey
|
||||
proxy = "http://127.0.0.1:23458"
|
||||
config_path = tmp_path / "config.json"
|
||||
config_path.write_text(
|
||||
json.dumps({"network": {"proxy": proxy}, "providers": {"openaiCodex": {"useProxy": True}}}),
|
||||
json.dumps({"providers": {"openaiCodex": {"proxy": proxy}}}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
active_path: dict[str, Path] = {}
|
||||
|
||||
@@ -9,7 +9,7 @@ from typer.testing import CliRunner
|
||||
from nanobot.cli.commands import app
|
||||
from nanobot.config import home as instance_home
|
||||
from nanobot.config import loader
|
||||
from nanobot.config.paths import get_cli_history_path, get_media_dir
|
||||
from nanobot.config.paths import get_cli_history_path, get_legacy_sessions_dir, get_media_dir
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
|
||||
@@ -54,6 +54,7 @@ def test_home_paths_and_saved_workspace(tmp_path):
|
||||
assert Config().workspace_path == tmp_path / "workspace"
|
||||
assert get_media_dir() == tmp_path / "media"
|
||||
assert get_cli_history_path() == tmp_path / "history" / "cli_history"
|
||||
assert get_legacy_sessions_dir() == tmp_path / "sessions"
|
||||
config = Config()
|
||||
config.agents.defaults.workspace = str(tmp_path / "custom")
|
||||
loader.save_config(config)
|
||||
|
||||
@@ -4,6 +4,7 @@ from nanobot.config.paths import (
|
||||
get_cli_history_path,
|
||||
get_cron_dir,
|
||||
get_data_dir,
|
||||
get_legacy_sessions_dir,
|
||||
get_logs_dir,
|
||||
get_media_dir,
|
||||
get_runtime_subdir,
|
||||
@@ -30,8 +31,9 @@ def test_media_dir_supports_channel_namespace(monkeypatch, tmp_path: Path) -> No
|
||||
assert get_media_dir("telegram") == config_file.parent / "media" / "telegram"
|
||||
|
||||
|
||||
def test_cli_history_path_remains_global() -> None:
|
||||
def test_shared_and_legacy_paths_remain_global() -> None:
|
||||
assert get_cli_history_path() == Path.home() / ".nanobot" / "history" / "cli_history"
|
||||
assert get_legacy_sessions_dir() == Path.home() / ".nanobot" / "sessions"
|
||||
|
||||
|
||||
def test_workspace_path_is_explicitly_resolved() -> None:
|
||||
|
||||
@@ -3,40 +3,60 @@ import json
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from nanobot.config.loader import load_config, resolve_config_env_vars, save_config
|
||||
from nanobot.config.loader import ConfigLoadError, load_config, resolve_config_env_vars, save_config
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
|
||||
def test_shared_proxy_choices_survive_save_and_reload(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("NANOBOT_PROVIDERS", json.dumps({
|
||||
"openai": {"useProxy": True}, "openaiCodex": {"useProxy": True}, "xaiGrok": {"useProxy": True},
|
||||
}))
|
||||
@pytest.mark.parametrize("address", ["http://127.0.0.1:7890", "socks5://user:pass@localhost:1080", "${SHARED_PROXY}"])
|
||||
def test_legacy_proxy_migrates_once_across_features(tmp_path, address):
|
||||
path = tmp_path / "config.json"
|
||||
original = {
|
||||
"network": {"proxy": "socks5://localhost:1080"},
|
||||
"tools": {"web": {"useProxy": False}},
|
||||
"channels": {"telegram": {"useProxy": True}},
|
||||
"providers": {"openai": {"proxy": address}, "openaiCodex": {"proxy": address}},
|
||||
"tools": {"web": {"proxy": address}},
|
||||
"channels": {"telegram": {"proxy": address}, "slack": {"proxy": ""}},
|
||||
}
|
||||
path.write_text(json.dumps(original), encoding="utf-8")
|
||||
config = load_config(path)
|
||||
assert json.loads(path.read_text(encoding="utf-8")) == original
|
||||
assert config.network.proxy == address
|
||||
assert config.providers.openai.use_proxy is True
|
||||
assert config.providers.openai_codex.use_proxy is True
|
||||
assert config.providers.xai_grok.use_proxy is True
|
||||
assert config.tools.web.use_proxy is True
|
||||
assert config.channels.telegram["useProxy"] is True
|
||||
assert "useProxy" not in config.channels.slack
|
||||
config.providers.openai.use_proxy = False
|
||||
config.providers.openai_codex.use_proxy = False
|
||||
config.providers.xai_grok.use_proxy = False
|
||||
config.tools.web.use_proxy = True
|
||||
config.channels.telegram["useProxy"] = False
|
||||
save_config(config, path)
|
||||
saved = json.loads(path.read_text(encoding="utf-8"))
|
||||
assert saved["network"]["proxy"] == address
|
||||
assert "proxy" not in saved["providers"]["openai"]
|
||||
assert "proxy" not in saved["tools"]["web"]
|
||||
assert "proxy" not in saved["channels"]["telegram"]
|
||||
assert load_config(path).providers.openai.use_proxy is False
|
||||
|
||||
reloaded = load_config(path)
|
||||
assert reloaded.network.proxy == "socks5://localhost:1080"
|
||||
assert reloaded.providers.openai.use_proxy is False
|
||||
assert reloaded.providers.openai_codex.use_proxy is False
|
||||
assert reloaded.providers.xai_grok.use_proxy is False
|
||||
assert reloaded.tools.web.use_proxy is True
|
||||
assert reloaded.channels.telegram["useProxy"] is False
|
||||
|
||||
def test_multiple_legacy_addresses_require_one_explicit_global_address(tmp_path):
|
||||
path = tmp_path / "config.json"
|
||||
original = {"tools": {"web": {"proxy": "http://secret:password@localhost:7890"}}, "channels": {"discord": {"proxy": "http://localhost:7891"}}}
|
||||
path.write_text(json.dumps(original), encoding="utf-8")
|
||||
with pytest.raises(ConfigLoadError, match="Multiple legacy proxy addresses") as caught:
|
||||
load_config(path)
|
||||
assert "secret" not in str(caught.value)
|
||||
assert json.loads(path.read_text(encoding="utf-8")) == original
|
||||
original["network"] = {"proxy": "http://localhost:7892"}
|
||||
path.write_text(json.dumps(original), encoding="utf-8")
|
||||
config = load_config(path)
|
||||
assert config.network.proxy == "http://localhost:7892"
|
||||
assert config.tools.web.use_proxy is True
|
||||
assert config.channels.discord["useProxy"] is True
|
||||
|
||||
|
||||
def test_discord_proxy_credentials_move_into_the_shared_url(tmp_path):
|
||||
path = tmp_path / "config.json"
|
||||
path.write_text(json.dumps({"channels": {"discord": {"proxy": "localhost:7890", "proxyUsername": "user@host", "proxyPassword": "pass:word"}}}), encoding="utf-8")
|
||||
config = load_config(path)
|
||||
assert config.network.proxy == "http://user%40host:pass%3Aword@localhost:7890"
|
||||
assert config.channels.discord == {"useProxy": True}
|
||||
|
||||
|
||||
def test_proxy_opt_in_does_not_fall_back_when_unconfigured():
|
||||
@@ -65,7 +85,101 @@ def test_invalid_shared_proxy_has_a_safe_error(address):
|
||||
assert address not in str(caught.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("address", ["http://proxy.example:8080", "${PROXY_SCHEME}://${PROXY_HOST}:8080"])
|
||||
@pytest.mark.parametrize("file_present", [False, True])
|
||||
def test_environment_legacy_proxy_migrates_after_source_merge(tmp_path, monkeypatch, file_present):
|
||||
proxy = "http://localhost:7890"
|
||||
monkeypatch.setenv("NANOBOT_PROVIDERS", json.dumps({"openai": {"proxy": proxy}}))
|
||||
monkeypatch.setenv("NANOBOT_TOOLS", json.dumps({"web": {"proxy": proxy}}))
|
||||
monkeypatch.setenv("NANOBOT_CHANNELS", json.dumps({"telegram": {"proxy": proxy}}))
|
||||
path = tmp_path / "config.json"
|
||||
if file_present:
|
||||
path.write_text(json.dumps({"providers": {"openai": {"apiKey": "test-key"}}}), encoding="utf-8")
|
||||
config = load_config(path)
|
||||
assert config.network.proxy == proxy
|
||||
assert config.providers.openai.use_proxy is True
|
||||
assert config.tools.web.use_proxy is True
|
||||
assert config.channels.telegram == {"useProxy": True}
|
||||
save_config(config, path)
|
||||
saved = json.loads(path.read_text(encoding="utf-8"))
|
||||
assert saved["network"]["proxy"] == proxy
|
||||
assert "proxy" not in saved["providers"]["openai"]
|
||||
config.providers.openai.use_proxy = False
|
||||
save_config(config, path)
|
||||
assert load_config(path).providers.openai.use_proxy is False
|
||||
|
||||
|
||||
def test_file_proxy_and_opt_out_take_precedence_over_environment(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("NANOBOT_PROVIDERS", json.dumps({"openai": {"proxy": "http://environment:7890"}}))
|
||||
path = tmp_path / "config.json"
|
||||
path.write_text(json.dumps({"providers": {"openai": {"proxy": "http://file:7891", "useProxy": False}}}), encoding="utf-8")
|
||||
config = load_config(path)
|
||||
assert config.network.proxy == "http://file:7891"
|
||||
assert config.providers.openai.use_proxy is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("password", ["a/b", "a#b?c", "a@b:c%"])
|
||||
def test_discord_credential_references_are_escaped_without_persisting_secrets(tmp_path, monkeypatch, password):
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
monkeypatch.setenv("PROXY_USER", "alice@example")
|
||||
monkeypatch.setenv("PROXY_PASSWORD", password)
|
||||
path = tmp_path / "config.json"
|
||||
path.write_text(json.dumps({"channels": {"discord": {"proxy": "http://localhost:7890", "proxyUsername": "${PROXY_USER}", "proxyPassword": "${PROXY_PASSWORD}"}}}), encoding="utf-8")
|
||||
config = load_config(path)
|
||||
for network in (config.network, resolve_config_env_vars(config).network):
|
||||
proxy = network.resolve_proxy(True)
|
||||
parsed = urlsplit(proxy)
|
||||
assert parsed.hostname == "localhost"
|
||||
assert parsed.port == 7890
|
||||
assert unquote(parsed.username) == "alice@example"
|
||||
assert unquote(parsed.password) == password
|
||||
save_config(config, path)
|
||||
saved = json.loads(path.read_text(encoding="utf-8"))
|
||||
assert saved["network"]["proxy"] == "http://${PROXY_USER}:${PROXY_PASSWORD}@localhost:7890"
|
||||
assert "alice@example" not in path.read_text(encoding="utf-8")
|
||||
assert load_config(path).network.resolve_proxy(True) == config.network.resolve_proxy(True)
|
||||
|
||||
|
||||
def test_whole_discord_url_reference_with_separate_credentials_requires_consolidation(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("DISCORD_PROXY", "http://localhost:7890")
|
||||
original = {"channels": {"discord": {"proxy": "${DISCORD_PROXY}", "proxyUsername": "alice", "proxyPassword": "secret-password"}}}
|
||||
path = tmp_path / "config.json"
|
||||
path.write_text(json.dumps(original), encoding="utf-8")
|
||||
with pytest.raises(ConfigLoadError, match="one full URL environment variable") as caught:
|
||||
load_config(path)
|
||||
assert "secret-password" not in str(caught.value)
|
||||
assert json.loads(path.read_text(encoding="utf-8")) == original
|
||||
original["network"] = {"proxy": "${SHARED_PROXY}"}
|
||||
path.write_text(json.dumps(original), encoding="utf-8")
|
||||
config = load_config(path)
|
||||
assert config.network.proxy == "${SHARED_PROXY}"
|
||||
assert config.channels.discord == {"useProxy": True}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("alias, attribute", [("openaiCodex", "openai_codex"), ("xaiGrok", "xai_grok")])
|
||||
@pytest.mark.parametrize("saved_opt_out", [True, False], ids=["refresh", "changed-setting"])
|
||||
def test_oauth_proxy_opt_out_survives_save_with_legacy_environment(tmp_path, monkeypatch, alias, attribute, saved_opt_out):
|
||||
proxy = "http://proxy.example:8080"
|
||||
monkeypatch.setenv("NANOBOT_PROVIDERS", json.dumps({alias: {"proxy": proxy, "apiKey": "oauth-secret"}}))
|
||||
original = {"network": {"proxy": proxy}, "providers": {alias: {"useProxy": False} if saved_opt_out else {}}}
|
||||
path = tmp_path / "config.json"
|
||||
path.write_text(json.dumps(original), encoding="utf-8")
|
||||
|
||||
config = load_config(path)
|
||||
provider = getattr(config.providers, attribute)
|
||||
assert provider.use_proxy is (not saved_opt_out)
|
||||
assert json.loads(path.read_text(encoding="utf-8")) == original
|
||||
if not saved_opt_out:
|
||||
provider.use_proxy = False
|
||||
save_config(config, path)
|
||||
|
||||
saved = json.loads(path.read_text(encoding="utf-8"))
|
||||
assert saved["providers"][alias] == {"useProxy": False}
|
||||
assert "oauth-secret" not in path.read_text(encoding="utf-8")
|
||||
assert getattr(load_config(path).providers, attribute).use_proxy is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("legacy", [False, True], ids=["shared", "legacy"])
|
||||
@pytest.mark.parametrize(
|
||||
"userinfo, environment, expected_auth",
|
||||
[
|
||||
@@ -80,14 +194,11 @@ def test_invalid_shared_proxy_has_a_safe_error(address):
|
||||
],
|
||||
ids=["combined-auth", "combined-encoded-auth", "combined-special-password", "credential-components"],
|
||||
)
|
||||
def test_proxy_userinfo_references_round_trip_with_httpx_auth(tmp_path, monkeypatch, address, userinfo, environment, expected_auth):
|
||||
monkeypatch.setenv("PROXY_SCHEME", "http")
|
||||
monkeypatch.setenv("PROXY_HOST", "proxy.example")
|
||||
def test_proxy_userinfo_references_round_trip_with_httpx_auth(tmp_path, monkeypatch, legacy, userinfo, environment, expected_auth):
|
||||
for name, value in environment.items():
|
||||
monkeypatch.setenv(name, value)
|
||||
scheme, host = address.split("://", 1)
|
||||
template = f"{scheme}://{userinfo}@{host}"
|
||||
original = {
|
||||
template = f"http://{userinfo}@proxy.example:8080"
|
||||
original = {"providers": {"openai": {"proxy": template}}} if legacy else {
|
||||
"network": {"proxy": template}, "providers": {"openai": {"useProxy": True}},
|
||||
}
|
||||
path = tmp_path / "config.json"
|
||||
@@ -97,10 +208,7 @@ def test_proxy_userinfo_references_round_trip_with_httpx_auth(tmp_path, monkeypa
|
||||
assert config.network.proxy == template
|
||||
assert config.providers.openai.use_proxy is True
|
||||
for current in (config, resolve_config_env_vars(config)):
|
||||
proxy = httpx.Proxy(current.network.resolve_proxy(current.providers.openai.use_proxy))
|
||||
assert proxy.url.host == "proxy.example"
|
||||
assert proxy.url.port == 8080
|
||||
assert proxy.raw_auth == expected_auth
|
||||
assert httpx.Proxy(current.network.resolve_proxy(current.providers.openai.use_proxy)).raw_auth == expected_auth
|
||||
assert json.loads(path.read_text(encoding="utf-8")) == original
|
||||
save_config(config, path)
|
||||
|
||||
@@ -111,3 +219,47 @@ def test_proxy_userinfo_references_round_trip_with_httpx_auth(tmp_path, monkeypa
|
||||
reloaded = load_config(path)
|
||||
assert reloaded.network.proxy == template
|
||||
assert httpx.Proxy(resolve_config_env_vars(reloaded).network.resolve_proxy(True)).raw_auth == expected_auth
|
||||
|
||||
|
||||
@pytest.mark.parametrize("address", ["${PROXY_SCHEME}://proxy.example:8080", "${PROXY_SCHEME}://${PROXY_HOST}:8080", "http://${PROXY_HOST}:8080"])
|
||||
@pytest.mark.parametrize("credential_refs", [False, True], ids=["literal-auth", "referenced-auth"])
|
||||
def test_discord_partial_url_reference_migrates_without_resolving_on_disk(tmp_path, monkeypatch, address, credential_refs):
|
||||
from urllib.parse import quote
|
||||
|
||||
username = "alice/a#b?c@d:e%25f"
|
||||
password = "p/a#b?c@d:e%25f"
|
||||
monkeypatch.setenv("PROXY_SCHEME", "http")
|
||||
monkeypatch.setenv("PROXY_HOST", "proxy.example")
|
||||
monkeypatch.setenv("PROXY_USER", username)
|
||||
monkeypatch.setenv("PROXY_PASSWORD", password)
|
||||
user_template = "${PROXY_USER}" if credential_refs else quote(username, safe="")
|
||||
password_template = "${PROXY_PASSWORD}" if credential_refs else quote(password, safe="")
|
||||
scheme, host = address.split("://", 1)
|
||||
expected_template = f"{scheme}://{user_template}:{password_template}@{host}"
|
||||
original = {"channels": {"discord": {
|
||||
"proxy": address,
|
||||
"proxyUsername": "${PROXY_USER}" if credential_refs else username,
|
||||
"proxyPassword": "${PROXY_PASSWORD}" if credential_refs else password,
|
||||
}}}
|
||||
path = tmp_path / "config.json"
|
||||
path.write_text(json.dumps(original), encoding="utf-8")
|
||||
|
||||
config = load_config(path)
|
||||
assert config.network.proxy == expected_template
|
||||
assert config.channels.discord == {"useProxy": True}
|
||||
assert json.loads(path.read_text(encoding="utf-8")) == original
|
||||
for network in (config.network, resolve_config_env_vars(config).network):
|
||||
proxy = httpx.Proxy(network.resolve_proxy(True))
|
||||
assert proxy.url.host == "proxy.example"
|
||||
assert proxy.url.port == 8080
|
||||
assert proxy.raw_auth == (username.encode(), password.encode())
|
||||
save_config(config, path)
|
||||
|
||||
saved_text = path.read_text(encoding="utf-8")
|
||||
assert json.loads(saved_text)["network"]["proxy"] == expected_template
|
||||
if credential_refs:
|
||||
assert username not in saved_text
|
||||
assert password not in saved_text
|
||||
reloaded = load_config(path)
|
||||
assert reloaded.network.proxy == expected_template
|
||||
assert httpx.Proxy(resolve_config_env_vars(reloaded).network.resolve_proxy(True)).raw_auth == (username.encode(), password.encode())
|
||||
@@ -30,7 +30,6 @@ def selected(result):
|
||||
("tests/test_docker.sh", {"docker"}),
|
||||
("tests/webui/fixtures/runtime-config-keys.json", {"python", "webui"}),
|
||||
("tests/session/fixtures/sqlite_v1.sql", {"python"}),
|
||||
("scripts/docker_upgrade_smoke.py", {"docker"}),
|
||||
("tests/fixtures/sigstore/bundle_v3.txt", {"python", "native"}),
|
||||
("tests/fixtures/sigstore/bundle_v3.txt.sigstore", {"python", "native"}),
|
||||
("tests/fixtures/sigstore/README.md", set()),
|
||||
@@ -60,7 +59,7 @@ def selected(result):
|
||||
("tests/providers/test_cached_tokens.py", {"python"}),
|
||||
("scripts/pytest_timing.py", {"python"}),
|
||||
("tests/scripts/test_pytest_timing.py", {"python"}),
|
||||
("scripts/verify_packaged_update.py", {"python", "docker", "native"}),
|
||||
("scripts/verify_packaged_update.py", {"python", "native"}),
|
||||
("scripts/check_client_import_boundaries.mjs", {"webui", "tui"}),
|
||||
(".github/workflows/release-candidate.yml", {"python", "native"}),
|
||||
(".github/workflows/release-approve.yml", {"python", "native"}),
|
||||
|
||||
@@ -20,4 +20,5 @@ CREATE TABLE pending_inputs (
|
||||
PRIMARY KEY (session_key, kind, position)
|
||||
);
|
||||
CREATE INDEX sessions_updated ON sessions(updated_at DESC);
|
||||
INSERT INTO storage_meta (key, value) VALUES ('jsonl_import', 'complete');
|
||||
PRAGMA user_version = 1;
|
||||
@@ -1,6 +1,9 @@
|
||||
"""Reset a corrupt last_consolidated offset instead of hiding history (#4066)."""
|
||||
|
||||
from nanobot.session.manager import Session
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
|
||||
|
||||
def _session(count: int, last_consolidated: object) -> Session:
|
||||
@@ -18,6 +21,39 @@ def test_non_integer_offset_is_reset():
|
||||
assert _session(3, offset).last_consolidated == 0
|
||||
|
||||
|
||||
def test_loaded_corrupt_offset_keeps_messages(tmp_path: Path):
|
||||
offsets = {
|
||||
"string": "999",
|
||||
"null": None,
|
||||
"float": 0.5,
|
||||
"bool": True,
|
||||
}
|
||||
|
||||
for name, offset in offsets.items():
|
||||
workspace = tmp_path / name
|
||||
path = workspace / "sessions" / "old.jsonl"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
message = {"role": "user", "content": f"survived {name}"}
|
||||
path.write_text(
|
||||
"\n".join([
|
||||
json.dumps({
|
||||
"_type": "metadata",
|
||||
"key": "chan:chat",
|
||||
"metadata": {},
|
||||
"last_consolidated": offset,
|
||||
}),
|
||||
json.dumps(message),
|
||||
]) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
session = SessionManager(workspace).get_or_create("chan:chat")
|
||||
|
||||
assert session.messages == [message]
|
||||
assert session.last_consolidated == 0
|
||||
assert session.get_history(max_messages=10) == [message]
|
||||
|
||||
|
||||
def test_valid_offset_is_preserved():
|
||||
session = _session(10, 4)
|
||||
assert session.last_consolidated == 4
|
||||
@@ -27,6 +63,59 @@ def test_valid_offset_is_preserved():
|
||||
]
|
||||
|
||||
|
||||
def test_last_archived_field_migrates_with_legacy_alias(tmp_path: Path):
|
||||
path = tmp_path / "sessions" / "old.jsonl"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
messages = [
|
||||
{"role": "user", "content": "first"},
|
||||
{"role": "assistant", "content": "second"},
|
||||
]
|
||||
path.write_text(
|
||||
"\n".join([
|
||||
json.dumps({
|
||||
"_type": "metadata",
|
||||
"key": "chan:chat",
|
||||
"metadata": {},
|
||||
"last_archived": 1,
|
||||
}),
|
||||
*(json.dumps(message) for message in messages),
|
||||
]) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("chan:chat")
|
||||
|
||||
assert session.last_archived == 1
|
||||
assert session.last_consolidated == 1
|
||||
manager.save(session)
|
||||
assert manager.read_session_snapshot("chan:chat").last_archived == 1
|
||||
|
||||
|
||||
def test_loaded_null_metadata_becomes_empty_dict(tmp_path: Path):
|
||||
"""Session jsonl metadata:null must load as {} so agent .pop/.get work."""
|
||||
path = tmp_path / "sessions" / "old.jsonl"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(
|
||||
json.dumps({
|
||||
"_type": "metadata",
|
||||
"key": "chan:chat",
|
||||
"created_at": "2026-01-01T00:00:00",
|
||||
"updated_at": "2026-01-01T00:00:00",
|
||||
"metadata": None,
|
||||
"last_consolidated": 0,
|
||||
}) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("chan:chat")
|
||||
assert session.metadata == {}
|
||||
session.metadata["title"] = "ok"
|
||||
assert session.metadata["title"] == "ok"
|
||||
session.metadata.pop("title", None)
|
||||
assert session.metadata == {}
|
||||
|
||||
|
||||
def test_session_post_init_coerces_null_metadata():
|
||||
session = Session(key="chan:chat", metadata=None) # type: ignore[arg-type]
|
||||
assert session.metadata == {}
|
||||
@@ -11,6 +11,7 @@ from nanobot.session.display_history import HistoryFact, HistoryKind
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
from nanobot.webui.forking import create_webui_chat_fork
|
||||
from nanobot.webui.history import HISTORY_IMPORT_MARKER, collect_legacy_history
|
||||
from nanobot.webui.transcript import WebUITranscriptRecorder, build_webui_thread_response
|
||||
|
||||
|
||||
@@ -18,6 +19,13 @@ def _manager(tmp_path: Path) -> SessionManager:
|
||||
return SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")
|
||||
|
||||
|
||||
def _legacy(directory: Path, key: str, records: list[dict]) -> Path:
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
path = directory / f"{SessionManager.safe_key(key)}.jsonl"
|
||||
path.write_text("".join(json.dumps(record, ensure_ascii=False) + "\n" for record in records), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
async def test_display_facts_survive_reopen_without_entering_model_history(tmp_path):
|
||||
sessions = _manager(tmp_path)
|
||||
session = await sessions.state.get("websocket:durable")
|
||||
@@ -111,6 +119,73 @@ async def test_fork_rolls_back_both_histories_if_display_copy_fails(tmp_path, mo
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
async def test_legacy_import_is_atomic_repeatable_and_deletion_cannot_resurrect_backup(tmp_path):
|
||||
sessions = _manager(tmp_path)
|
||||
directory = tmp_path / "legacy"
|
||||
path = _legacy(directory, "websocket:imported", [
|
||||
{"event": "user", "chat_id": "imported", "text": "hello", "created_at_ms": 1000},
|
||||
{"event": "delta", "chat_id": "imported", "text": "an"},
|
||||
{"event": "delta", "chat_id": "imported", "text": "swer"},
|
||||
{"event": "stream_end", "chat_id": "imported"},
|
||||
{"event": "turn_end", "chat_id": "imported"},
|
||||
])
|
||||
before = path.read_bytes()
|
||||
def collect(rows):
|
||||
return collect_legacy_history(rows, directory=directory)
|
||||
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, collect)
|
||||
facts = await sessions.state.project_history("websocket:imported", lambda history: history.all_facts())
|
||||
assert [fact.kind for fact in facts] == [HistoryKind.INPUT, HistoryKind.ANSWER_SEGMENT, HistoryKind.COMPLETION]
|
||||
assert facts[1].content["text"] == "answer"
|
||||
assert path.read_bytes() == before
|
||||
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, collect)
|
||||
assert await sessions.state.project_history("websocket:imported", lambda history: history.all_facts()) == facts
|
||||
assert await sessions.state.delete("websocket:imported")
|
||||
await sessions.state.aclose()
|
||||
reopened = _manager(tmp_path)
|
||||
await reopened.state.migrate_history(HISTORY_IMPORT_MARKER, collect)
|
||||
assert await reopened.state.read_metadata("websocket:imported") is None
|
||||
await reopened.state.aclose()
|
||||
|
||||
|
||||
async def test_corrupt_legacy_input_rolls_back_import_marker_and_all_records(tmp_path):
|
||||
sessions = _manager(tmp_path)
|
||||
directory = tmp_path / "legacy"
|
||||
_legacy(directory, "websocket:first", [{"event": "user", "chat_id": "first", "text": "safe"}])
|
||||
corrupt = _legacy(directory, "websocket:second", [{"event": "user", "chat_id": "second", "text": "also safe"}])
|
||||
with corrupt.open("a", encoding="utf-8") as handle:
|
||||
handle.write('{"event":\n')
|
||||
with pytest.raises(ValueError, match="cannot import history"):
|
||||
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(rows, directory=directory))
|
||||
assert await sessions.state.list_sessions() == []
|
||||
with closing(sqlite3.connect(sessions.sessions_dir / "sessions.sqlite3")) as db:
|
||||
assert db.execute("SELECT value FROM storage_meta WHERE key=?", (HISTORY_IMPORT_MARKER,)).fetchone() is None
|
||||
_legacy(directory, "websocket:second", [{"event": "user", "chat_id": "second", "text": "fixed"}])
|
||||
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(rows, directory=directory))
|
||||
assert {row["key"] for row in await sessions.state.list_sessions()} == {"websocket:first", "websocket:second"}
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
async def test_segments_import_in_order_without_trusting_damaged_manifest(tmp_path):
|
||||
sessions = _manager(tmp_path)
|
||||
directory = tmp_path / "legacy"
|
||||
segments = directory / "websocket_order.segments"
|
||||
segments.mkdir(parents=True)
|
||||
for number in (2, 1):
|
||||
(segments / f"{number:06}.jsonl").write_text(json.dumps({"event": "message", "chat_id": "order", "text": str(number)}) + "\n", encoding="utf-8")
|
||||
(segments / "manifest.json").write_text("broken cached manifest", encoding="utf-8")
|
||||
_legacy(directory, "websocket:order", [{"event": "message", "chat_id": "order", "text": "3"}])
|
||||
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(rows, directory=directory))
|
||||
assert await sessions.state.project_history("websocket:order", lambda history: [fact.content["text"] for fact in history.all_facts()]) == ["1", "2", "3"]
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
def test_orphan_lossy_filename_requires_recorded_identity(tmp_path):
|
||||
directory = tmp_path / "legacy"
|
||||
_legacy(directory, "websocket:a_b", [{"event": "message", "text": "unknown whether a_b or a:b"}])
|
||||
with pytest.raises(ValueError, match="ambiguous legacy history identity"):
|
||||
collect_legacy_history([], directory=directory)
|
||||
|
||||
|
||||
async def test_recorder_keeps_completed_segments_not_every_transport_delta(tmp_path):
|
||||
sessions = _manager(tmp_path)
|
||||
key = "websocket:stream"
|
||||
@@ -172,6 +247,31 @@ asyncio.run(run())
|
||||
assert reopened.read_session_file(source.key)["messages"] == source.messages
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_legacy_import_owner_survives_delete_and_new_workspace(tmp_path):
|
||||
from nanobot.webui.history import collect_legacy_history
|
||||
|
||||
root = tmp_path / "sessions"
|
||||
legacy = tmp_path / "webui"
|
||||
legacy.mkdir()
|
||||
key = "websocket:owned"
|
||||
(legacy / f"{SessionManager.safe_key(key)}.jsonl").write_text(
|
||||
'{"event":"user","chat_id":"owned","text":"keep ownership"}\n', encoding="utf-8",
|
||||
)
|
||||
first = SessionManager(tmp_path / "first", sessions_root=root)
|
||||
await first.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(
|
||||
rows, directory=legacy, namespace=first.sessions_dir,
|
||||
))
|
||||
await first.state.delete(key)
|
||||
await first.state.aclose()
|
||||
second = SessionManager(tmp_path / "second", sessions_root=root)
|
||||
await second.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(
|
||||
rows, directory=legacy, namespace=second.sessions_dir,
|
||||
))
|
||||
assert await second.state.read(key) is None
|
||||
await second.state.aclose()
|
||||
|
||||
|
||||
async def test_large_display_fact_serialization_and_copy_stay_off_runtime_loop(tmp_path, monkeypatch):
|
||||
import threading
|
||||
|
||||
@@ -215,6 +315,29 @@ def test_message_projection_adapter_preserves_reply_and_agent_activity():
|
||||
assert record_from_fact(fact, "websocket:activity") == record
|
||||
|
||||
|
||||
async def test_legacy_activity_without_record_timestamps_preserves_file_time(tmp_path):
|
||||
import os
|
||||
|
||||
from nanobot.webui.session_list_index import list_webui_sessions
|
||||
|
||||
sessions = _manager(tmp_path)
|
||||
session = await sessions.state.get_header("websocket:old-activity")
|
||||
directory = tmp_path / "legacy"
|
||||
path = _legacy(directory, session.key, [{
|
||||
"event": "message", "chat_id": "old-activity", "text": "historical display activity",
|
||||
}])
|
||||
os.utime(path, (1760000000, 1760000000))
|
||||
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(
|
||||
rows, directory=directory,
|
||||
))
|
||||
rows = list_webui_sessions(sessions, await sessions.state.list_metadata())
|
||||
from datetime import datetime
|
||||
|
||||
assert datetime.fromisoformat(rows[0]["updated_at"]).timestamp() == 1760000000
|
||||
assert rows[0]["preview"] == "historical display activity"
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stored_display", [False, True])
|
||||
async def test_new_fork_activity_uses_creation_time_not_inherited_history(tmp_path, stored_display):
|
||||
from datetime import datetime
|
||||
|
||||
@@ -38,6 +38,7 @@ def _input(text, turn_id):
|
||||
@pytest.mark.parametrize("count", [1, 2])
|
||||
@pytest.mark.parametrize("leave_unconsumed", [False, True])
|
||||
async def test_late_consumption_commits_history_and_only_its_ids(tmp_path, monkeypatch, count, leave_unconsumed):
|
||||
monkeypatch.setattr("nanobot.webui.history.get_webui_dir", lambda: tmp_path / "webui")
|
||||
sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")
|
||||
state = sessions.state
|
||||
try:
|
||||
|
||||
@@ -24,6 +24,14 @@ from nanobot.webui import history as history_module
|
||||
from nanobot.webui.recovery import RecoveryActionError, RecoveryCoordinator
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_webui_transcripts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Recovery scans must discover only test-owned transcripts, not active user chats."""
|
||||
webui_dir = tmp_path / "isolated-webui"
|
||||
webui_dir.mkdir()
|
||||
monkeypatch.setattr(history_module, "get_webui_dir", lambda: webui_dir)
|
||||
|
||||
|
||||
def _persist(manager: SessionManager, session: Session) -> None:
|
||||
session.metadata["webui"] = True
|
||||
manager.save(session)
|
||||
@@ -118,19 +126,24 @@ async def test_materialized_interruption_can_continue_from_saved_context(
|
||||
@pytest.mark.asyncio
|
||||
async def test_transcript_only_interruption_is_discovered_without_materializing_completed_history(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
webui_dir = tmp_path / "webui"
|
||||
webui_dir.mkdir()
|
||||
monkeypatch.setattr(history_module, "get_webui_dir", lambda: webui_dir)
|
||||
unfinished_key = "websocket:unfinished"
|
||||
completed_key = "websocket:completed"
|
||||
stored = SessionManager(tmp_path / "workspace")
|
||||
stored.append_history(unfinished_key, [history_module.fact_from_record(record) for record in (
|
||||
{"event": "user", "text": "keep going"},
|
||||
{"event": "message", "kind": "progress", "text": "Working"},
|
||||
)])
|
||||
stored.append_history(completed_key, [history_module.fact_from_record(record) for record in (
|
||||
{"event": "user", "text": "done"},
|
||||
{"event": "message", "text": "finished"},
|
||||
{"event": "turn_end"},
|
||||
)])
|
||||
(webui_dir / f"{SessionManager.safe_key(unfinished_key)}.jsonl").write_text(
|
||||
'{"event":"user","chat_id":"unfinished","text":"keep going"}\n'
|
||||
'{"event":"message","chat_id":"unfinished","kind":"progress","text":"Working"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
(webui_dir / f"{SessionManager.safe_key(completed_key)}.jsonl").write_text(
|
||||
'{"event":"user","chat_id":"completed","text":"done"}\n'
|
||||
'{"event":"message","chat_id":"completed","text":"finished"}\n'
|
||||
'{"event":"turn_end","chat_id":"completed"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
coordinator, bus, sessions = _coordinator(tmp_path / "workspace")
|
||||
|
||||
await coordinator.scan()
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
"""Completed migration makes legacy JSONL files inert."""
|
||||
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
|
||||
def test_list_and_reads_ignore_files_created_after_migration(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
(manager.sessions_dir / "cli_test.jsonl").write_text("invalid JSON")
|
||||
assert manager.list_sessions() == []
|
||||
assert manager.read_session_metadata("cli:test") is None
|
||||
assert manager.read_session_file("cli:test") is None
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
@@ -9,9 +10,40 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from nanobot.config.loader import load_config
|
||||
from nanobot.session.jsonl_migration import WORKSPACE_BACKUP_DIR
|
||||
from nanobot.session.location import SessionLocation
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
|
||||
def _write_legacy_session(
|
||||
old_dir: Path,
|
||||
key: str,
|
||||
content: str,
|
||||
*,
|
||||
updated_at: str = "2026-01-01T00:00:00",
|
||||
) -> Path:
|
||||
"""Write a valid session file in the legacy in-workspace location."""
|
||||
old_dir.mkdir(parents=True, exist_ok=True)
|
||||
path = old_dir / f"{SessionLocation.storage_key(key)}.jsonl"
|
||||
path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"_type": "metadata",
|
||||
"key": key,
|
||||
"created_at": "2026-01-01T00:00:00",
|
||||
"updated_at": updated_at,
|
||||
"metadata": {},
|
||||
"last_consolidated": 0,
|
||||
}
|
||||
)
|
||||
+ "\n"
|
||||
+ json.dumps({"role": "user", "content": content})
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
return path
|
||||
|
||||
|
||||
def test_sessions_are_stored_outside_workspace(tmp_path: Path) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
manager = SessionManager(workspace=workspace)
|
||||
@@ -179,3 +211,45 @@ def test_equivalent_workspace_paths_share_one_store(tmp_path: Path) -> None:
|
||||
|
||||
via_link = SessionManager(workspace=link_workspace).get_or_create("telegram:1")
|
||||
assert via_link.messages[-1]["content"] == "via-real"
|
||||
|
||||
|
||||
def test_migration_rejects_symlinked_session_file(tmp_path, create_symlink):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = _write_legacy_session(workspace / "sessions", "cli:test", "original")
|
||||
target = tmp_path / "outside.jsonl"
|
||||
path.rename(target)
|
||||
create_symlink(path, target)
|
||||
with pytest.raises(RuntimeError, match="migration failed"):
|
||||
SessionManager(workspace)
|
||||
assert "original" in target.read_text()
|
||||
|
||||
|
||||
def test_migration_rejects_symlinked_source_directory(tmp_path, create_symlink):
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
outside = tmp_path / "outside"
|
||||
outside.mkdir()
|
||||
create_symlink(workspace / "sessions", outside, target_is_directory=True)
|
||||
with pytest.raises(ValueError, match="symlink"):
|
||||
SessionManager(workspace)
|
||||
|
||||
|
||||
def test_workspace_migration_rejects_symlinked_backup_directory(tmp_path, create_symlink):
|
||||
workspace = tmp_path / "workspace"
|
||||
root = tmp_path / "root"
|
||||
source = _write_legacy_session(workspace / "sessions", "cli:test", "original")
|
||||
original = source.read_bytes()
|
||||
location = SessionLocation(workspace, sessions_root=root)
|
||||
outside = tmp_path / "outside"
|
||||
outside.mkdir()
|
||||
backup = location.sessions_dir / WORKSPACE_BACKUP_DIR
|
||||
create_symlink(backup, outside, target_is_directory=True)
|
||||
|
||||
with pytest.raises(RuntimeError, match="Could not move legacy sessions"):
|
||||
SessionManager(workspace, sessions_root=root)
|
||||
assert source.read_bytes() == original
|
||||
assert list(outside.iterdir()) == []
|
||||
backup.unlink()
|
||||
manager = SessionManager(workspace, sessions_root=root)
|
||||
assert not source.exists()
|
||||
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / source.name).read_bytes() == original
|
||||
@@ -1,3 +1,4 @@
|
||||
import json
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
@@ -35,6 +36,22 @@ def _session() -> Session:
|
||||
)
|
||||
|
||||
|
||||
def _write_legacy(workspace: Path, session: Session) -> Path:
|
||||
directory = workspace / "sessions"
|
||||
directory.mkdir(parents=True)
|
||||
path = directory / "session.jsonl"
|
||||
assert session.provider_state is not None
|
||||
records = [
|
||||
{"_type": "metadata", "key": session.key, "metadata": session.metadata,
|
||||
"created_at": session.created_at.isoformat(), "updated_at": session.updated_at.isoformat(),
|
||||
"last_archived": session.last_archived},
|
||||
{"_type": "provider_state", "state": session.provider_state.to_private_record()},
|
||||
*session.messages,
|
||||
]
|
||||
path.write_text("\n".join(json.dumps(record) for record in records) + "\n", encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def _database_snapshot(path: Path) -> tuple[int, str, str]:
|
||||
with closing(sqlite3.connect(path)) as db:
|
||||
return (
|
||||
@@ -44,8 +61,10 @@ def _database_snapshot(path: Path) -> tuple[int, str, str]:
|
||||
)
|
||||
|
||||
|
||||
def test_ordered_upgrades_preserve_records(tmp_path, monkeypatch):
|
||||
def test_ordered_upgrades_preserve_records_and_do_not_repeat_import(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
original = _session()
|
||||
source = _write_legacy(workspace, original)
|
||||
store = SqliteSessionStore(tmp_path)
|
||||
with closing(sqlite3.connect(store.path)) as db:
|
||||
schema = Path(__file__).with_name("fixtures") / "sqlite_v1.sql"
|
||||
@@ -62,8 +81,9 @@ def test_ordered_upgrades_preserve_records(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(sqlite_store, "_SCHEMA_MIGRATIONS", (
|
||||
*sqlite_store._SCHEMA_MIGRATIONS, add_archived, index_archived,
|
||||
))
|
||||
source.write_text("stale malformed source must not be imported again", encoding="utf-8")
|
||||
upgraded = SqliteSessionStore(tmp_path)
|
||||
upgraded.initialize()
|
||||
upgraded.initialize(workspace)
|
||||
assert _database_snapshot(store.path)[0] == len(sqlite_store._SCHEMA_MIGRATIONS)
|
||||
loaded = upgraded.load(original.key)
|
||||
assert loaded is not None
|
||||
@@ -73,7 +93,7 @@ def test_ordered_upgrades_preserve_records(tmp_path, monkeypatch):
|
||||
upgraded.save(loaded)
|
||||
|
||||
reopened = SqliteSessionStore(tmp_path)
|
||||
reopened.initialize()
|
||||
reopened.initialize(workspace)
|
||||
roundtrip = reopened.load(original.key)
|
||||
assert roundtrip is not None
|
||||
assert roundtrip.messages == original.messages
|
||||
@@ -82,11 +102,13 @@ def test_ordered_upgrades_preserve_records(tmp_path, monkeypatch):
|
||||
with closing(sqlite3.connect(store.path)) as db:
|
||||
assert db.execute("SELECT archived FROM sessions").fetchall() == [(0,)]
|
||||
assert db.execute("SELECT name FROM sqlite_master WHERE name='sessions_archived'").fetchone()
|
||||
assert db.execute("SELECT value FROM storage_meta WHERE key='jsonl_import'").fetchone() == ("complete",)
|
||||
|
||||
|
||||
def test_failed_upgrade_rolls_back_schema_version_and_records_then_can_retry(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
store = SqliteSessionStore(tmp_path)
|
||||
store.initialize()
|
||||
store.initialize(workspace)
|
||||
original = _session()
|
||||
store.save(original)
|
||||
before = _database_snapshot(store.path)
|
||||
@@ -104,7 +126,7 @@ def test_failed_upgrade_rolls_back_schema_version_and_records_then_can_retry(tmp
|
||||
*migrations, add_archived, fail_upgrade,
|
||||
))
|
||||
with pytest.raises(RuntimeError, match="migration interrupted"):
|
||||
store.initialize()
|
||||
store.initialize(workspace)
|
||||
assert _database_snapshot(store.path) == before
|
||||
|
||||
def complete_upgrade(db: sqlite3.Connection) -> None:
|
||||
@@ -113,7 +135,7 @@ def test_failed_upgrade_rolls_back_schema_version_and_records_then_can_retry(tmp
|
||||
monkeypatch.setattr(sqlite_store, "_SCHEMA_MIGRATIONS", (
|
||||
*migrations, add_archived, complete_upgrade,
|
||||
))
|
||||
store.initialize()
|
||||
store.initialize(workspace)
|
||||
assert _database_snapshot(store.path)[0] == len(sqlite_store._SCHEMA_MIGRATIONS)
|
||||
loaded = store.load(original.key)
|
||||
assert loaded is not None
|
||||
@@ -122,7 +144,7 @@ def test_failed_upgrade_rolls_back_schema_version_and_records_then_can_retry(tmp
|
||||
assert loaded.provider_state == original.provider_state
|
||||
|
||||
|
||||
def test_added_columns_allow_all_session_write_paths(tmp_path, monkeypatch):
|
||||
def test_added_columns_allow_import_and_all_session_write_paths(tmp_path, monkeypatch):
|
||||
def add_optional_columns(db: sqlite3.Connection) -> None:
|
||||
for table in ("storage_meta", "sessions", "messages", "checkpoints", "pending_inputs"):
|
||||
db.execute(f"ALTER TABLE {table} ADD COLUMN extension TEXT")
|
||||
@@ -131,8 +153,16 @@ def test_added_columns_allow_all_session_write_paths(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(sqlite_store, "_SCHEMA_MIGRATIONS", (
|
||||
*sqlite_store._SCHEMA_MIGRATIONS, add_optional_columns,
|
||||
))
|
||||
workspace = tmp_path / "workspace"
|
||||
imported = _session()
|
||||
_write_legacy(workspace, imported)
|
||||
store = SqliteSessionStore(tmp_path)
|
||||
store.initialize()
|
||||
store.initialize(workspace)
|
||||
loaded = store.load(imported.key)
|
||||
assert loaded is not None
|
||||
assert loaded.messages == imported.messages
|
||||
assert loaded.metadata == imported.metadata
|
||||
assert loaded.provider_state == imported.provider_state
|
||||
|
||||
created = _session()
|
||||
created.key = "chat:new"
|
||||
@@ -151,14 +181,15 @@ def test_added_columns_allow_all_session_write_paths(tmp_path, monkeypatch):
|
||||
assert roundtrip.metadata == current.metadata
|
||||
assert roundtrip.provider_state == current.provider_state
|
||||
with closing(sqlite3.connect(store.path)) as db:
|
||||
for table in ("sessions", "messages", "checkpoints", "pending_inputs"):
|
||||
for table in ("storage_meta", "sessions", "messages", "checkpoints", "pending_inputs"):
|
||||
rows = db.execute(f"SELECT extension, format_version FROM {table}").fetchall()
|
||||
assert rows and all(row == (None, 1) for row in rows)
|
||||
|
||||
|
||||
def test_future_schema_is_rejected_without_modifying_database(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
store = SqliteSessionStore(tmp_path)
|
||||
store.initialize()
|
||||
store.initialize(workspace)
|
||||
store.save(_session())
|
||||
future_version = len(sqlite_store._SCHEMA_MIGRATIONS) + 1
|
||||
with closing(sqlite3.connect(store.path)) as db:
|
||||
@@ -169,15 +200,16 @@ def test_future_schema_is_rejected_without_modifying_database(tmp_path):
|
||||
before_files = {path.name for path in tmp_path.iterdir()}
|
||||
|
||||
with pytest.raises(RuntimeError, match=f"unsupported session database schema: {future_version}"):
|
||||
store.initialize()
|
||||
store.initialize(workspace)
|
||||
assert _database_snapshot(store.path) == before
|
||||
assert store.path.read_bytes() == before_bytes
|
||||
assert {path.name for path in tmp_path.iterdir()} == before_files
|
||||
|
||||
|
||||
def test_missing_sqlite_json_support_is_rejected_before_database_changes(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
store = SqliteSessionStore(tmp_path)
|
||||
store.initialize()
|
||||
store.initialize(workspace)
|
||||
store.save(_session())
|
||||
with closing(sqlite3.connect(store.path)) as db:
|
||||
db.execute("PRAGMA journal_mode = DELETE")
|
||||
@@ -197,16 +229,17 @@ def test_missing_sqlite_json_support_is_rejected_before_database_changes(tmp_pat
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(sqlite3, "connect", connect)
|
||||
with pytest.raises(RuntimeError, match="requires SQLite JSON support"):
|
||||
store.initialize()
|
||||
store.initialize(workspace)
|
||||
assert _database_snapshot(store.path) == before
|
||||
assert store.path.read_bytes() == before_bytes
|
||||
|
||||
|
||||
def test_v4_archive_upgrade_removes_orphans_and_preserves_existing_membership(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
store = SqliteSessionStore(tmp_path)
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(sqlite_store, "_SCHEMA_MIGRATIONS", sqlite_store._SCHEMA_MIGRATIONS[:3])
|
||||
store.initialize()
|
||||
store.initialize(workspace)
|
||||
original = _session()
|
||||
store.save(original)
|
||||
store.save(Session(key="chat:empty-fork"))
|
||||
@@ -216,8 +249,8 @@ def test_v4_archive_upgrade_removes_orphans_and_preserves_existing_membership(tm
|
||||
[(key, "2026-11-01T12:00:00") for key in ("chat:extensions", "chat:empty-fork", "chat:draft")],
|
||||
)
|
||||
db.execute("INSERT INTO storage_meta (key, value) VALUES ('session_archives_imported', '1')")
|
||||
store.initialize()
|
||||
store.initialize()
|
||||
store.initialize(workspace)
|
||||
store.initialize(workspace)
|
||||
assert _database_snapshot(store.path)[0] == 4
|
||||
assert store.archived_keys() == ["chat:empty-fork", "chat:extensions"]
|
||||
assert store.archives_imported()
|
||||
@@ -233,7 +266,7 @@ def test_v4_archive_upgrade_removes_orphans_and_preserves_existing_membership(tm
|
||||
|
||||
def test_archive_reference_allows_atomic_session_replacement_but_not_orphan_commit(tmp_path):
|
||||
store = SqliteSessionStore(tmp_path)
|
||||
store.initialize()
|
||||
store.initialize(tmp_path / "workspace")
|
||||
original = _session()
|
||||
store.save(original)
|
||||
assert store.set_archived_keys([original.key]) == [original.key]
|
||||
|
||||
@@ -1,16 +1,243 @@
|
||||
import asyncio
|
||||
import json
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from packaging.version import Version
|
||||
|
||||
import nanobot.session.jsonl_migration as jsonl_migration
|
||||
from nanobot.session.jsonl_migration import SUNSET_VERSION, WORKSPACE_BACKUP_DIR
|
||||
from nanobot.session.location import SessionLocation
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
|
||||
|
||||
def legacy(workspace: Path, key: str = "websocket:old", *, content: str = "hello") -> Path:
|
||||
directory = workspace / "sessions"
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
path = directory / f"{SessionLocation.storage_key(key)}.jsonl"
|
||||
path.write_text(json.dumps({"_type": "metadata", "key": key, "metadata": {"title": "old"},
|
||||
"last_archived": 0, "created_at": "2026-01-01T00:00:00",
|
||||
"updated_at": "2026-01-01T00:00:00"}) + "\n" +
|
||||
json.dumps({"role": "user", "content": content}) + "\n")
|
||||
return path
|
||||
|
||||
|
||||
def test_migration_must_be_removed_at_declared_sunset():
|
||||
version = tomllib.loads((Path(__file__).parents[2] / "pyproject.toml").read_text())["project"]["version"]
|
||||
assert SUNSET_VERSION == "0.5.0"
|
||||
assert Version(Version(version).base_version) < Version(SUNSET_VERSION), (
|
||||
"Remove jsonl_migration, its initialization hook, and migration-only tests before 0.5.0"
|
||||
)
|
||||
|
||||
|
||||
def test_import_is_once_and_private_sources_are_unchanged(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
location = SessionLocation(workspace)
|
||||
path = path.replace(location.sessions_dir / path.name)
|
||||
original = path.read_bytes()
|
||||
manager = SessionManager(workspace)
|
||||
assert manager.read_session_snapshot("websocket:old").messages[0]["content"] == "hello"
|
||||
assert path.read_bytes() == original
|
||||
manager.delete_session("websocket:old")
|
||||
# Reopening must not resurrect deleted conversations, even if the source changes.
|
||||
path.write_text("broken legacy file")
|
||||
assert SessionManager(workspace).read_session_snapshot("websocket:old") is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("newline", "trailing_newline"), [
|
||||
("\n", True), ("\r\n", True), ("\n", False), ("\r\n", False),
|
||||
], ids=["lf", "crlf", "lf-no-final-newline", "crlf-no-final-newline"])
|
||||
def test_migration_preserves_unicode_separators(tmp_path, newline, trailing_newline):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace, content="中文🙂\u0085NEL\u2028LS\u2029PS\nLF\rCR")
|
||||
records = [json.loads(line) for line in path.read_text(encoding="utf-8").split("\n")
|
||||
if line.strip()]
|
||||
records.append({"role": "assistant", "content": "reply\u2029\u2028\u0085"})
|
||||
lines = [json.dumps(record, ensure_ascii=False) for record in records]
|
||||
lines[1:1] = ["", " \t"]
|
||||
original = (newline.join(lines) + (newline if trailing_newline else "")).encode("utf-8")
|
||||
path.write_bytes(original)
|
||||
|
||||
manager = SessionManager(workspace)
|
||||
expected = records[1:]
|
||||
assert manager.read_session_snapshot("websocket:old").messages == expected
|
||||
assert not path.exists()
|
||||
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == original
|
||||
reopened = SessionManager(workspace)
|
||||
assert reopened.read_session_snapshot("websocket:old").messages == expected
|
||||
|
||||
|
||||
def test_invalid_source_rolls_back_entire_migration(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
original = path.read_bytes()
|
||||
bad = path.parent / "zz-invalid.jsonl"
|
||||
bad.write_text("not json")
|
||||
with pytest.raises(RuntimeError, match="migration failed"):
|
||||
SessionManager(workspace)
|
||||
assert path.read_bytes() == original
|
||||
bad.unlink()
|
||||
manager = SessionManager(workspace)
|
||||
assert len(manager.list_sessions()) == 1
|
||||
assert not path.exists()
|
||||
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == original
|
||||
|
||||
|
||||
def test_migration_preserves_checkpoint_and_pending_inputs(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
checkpoint = {"version": 1, "session_key": "websocket:old", "base_message_count": 1,
|
||||
"base_updated_at": "2026-01-01T00:00:00", "checkpoint": {"messages": [{"role": "assistant", "content": "partial"}]},
|
||||
"provider_state": None}
|
||||
checkpoint_path = path.with_suffix(".checkpoint.json")
|
||||
checkpoint_path.write_text(json.dumps(checkpoint))
|
||||
original, original_checkpoint = path.read_bytes(), checkpoint_path.read_bytes()
|
||||
original_mtime, checkpoint_mtime = path.stat().st_mtime_ns, checkpoint_path.stat().st_mtime_ns
|
||||
manager = SessionManager(workspace)
|
||||
assert manager.get_or_create("websocket:old").metadata["runtime_checkpoint"] == checkpoint["checkpoint"]
|
||||
backup = manager.sessions_dir / WORKSPACE_BACKUP_DIR
|
||||
assert (backup / path.name).read_bytes() == original
|
||||
assert (backup / checkpoint_path.name).read_bytes() == original_checkpoint
|
||||
assert (backup / path.name).stat().st_mtime_ns == original_mtime
|
||||
assert (backup / checkpoint_path.name).stat().st_mtime_ns == checkpoint_mtime
|
||||
assert not path.exists() and not checkpoint_path.exists()
|
||||
|
||||
|
||||
async def test_workspace_migration_isolates_raw_private_records(tmp_path):
|
||||
from nanobot.agent.tools.filesystem import ReadFileTool
|
||||
from nanobot.agent.tools.sessions import ReadSessionTool
|
||||
from nanobot.providers.base import ProviderConversationState
|
||||
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
provider = ProviderConversationState(
|
||||
kind="openai_responses", provider="openai", model="gpt-test", version=1,
|
||||
payload={"items": [{"encrypted_content": "private-provider-state"}]},
|
||||
)
|
||||
with path.open("a", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps({"_type": "provider_state", "state": provider.to_private_record()}) + "\n")
|
||||
handle.write(json.dumps({"role": "tool", "tool_call_id": "call", "content": "private-tool-output"}) + "\n")
|
||||
original = path.read_bytes()
|
||||
manager = SessionManager(workspace)
|
||||
backup = manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name
|
||||
assert not path.exists()
|
||||
assert backup.read_bytes() == original
|
||||
if sys.platform != "win32":
|
||||
assert backup.stat().st_mode & 0o777 == 0o600
|
||||
assert backup.parent.stat().st_mode & 0o777 == 0o700
|
||||
|
||||
public = await ReadSessionTool(manager).execute(session_key="websocket:old")
|
||||
assert "private-provider-state" not in public and "private-tool-output" not in public
|
||||
tool = ReadFileTool(workspace=workspace, allowed_dir=workspace, restrict_to_workspace=True)
|
||||
assert (await tool.execute(path=str(path))).is_error
|
||||
blocked = await tool.execute(path=str(backup))
|
||||
assert blocked.is_error and "outside allowed directory" in blocked
|
||||
manager.delete_session("websocket:old")
|
||||
assert SessionManager(workspace).read_session_snapshot("websocket:old") is None
|
||||
assert backup.read_bytes() == original
|
||||
|
||||
|
||||
def test_restart_finishes_workspace_isolation_after_import_commit(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
root = tmp_path / "root"
|
||||
path = legacy(workspace)
|
||||
original = path.read_bytes()
|
||||
location = SessionLocation(workspace, sessions_root=root)
|
||||
|
||||
def interrupted(*_args):
|
||||
raise RuntimeError("interrupted after import commit")
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(jsonl_migration, "finish_workspace_migration", interrupted)
|
||||
with pytest.raises(RuntimeError, match="interrupted after import commit"):
|
||||
SessionManager(workspace, sessions_root=root)
|
||||
assert path.read_bytes() == original
|
||||
with sqlite3.connect(location.sessions_dir / "sessions.sqlite3") as db:
|
||||
assert db.execute("SELECT count(*) FROM sessions").fetchone()[0] == 1
|
||||
assert db.execute("SELECT value FROM storage_meta WHERE key='jsonl_import'").fetchone()[0] == "complete"
|
||||
|
||||
manager = SessionManager(workspace, sessions_root=root)
|
||||
assert len(manager.list_sessions()) == 1
|
||||
assert not path.exists()
|
||||
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == original
|
||||
|
||||
|
||||
def test_workspace_backup_failure_retains_sources_and_retries(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
original = path.read_bytes()
|
||||
|
||||
def failed_backup(*_args):
|
||||
raise OSError("backup storage unavailable")
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(jsonl_migration, "_write_backup", failed_backup)
|
||||
with pytest.raises(RuntimeError, match="Could not move legacy sessions"):
|
||||
SessionManager(workspace)
|
||||
assert path.read_bytes() == original
|
||||
manager = SessionManager(workspace)
|
||||
assert not path.exists()
|
||||
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == original
|
||||
|
||||
|
||||
def test_restart_finishes_partial_workspace_source_removal(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
checkpoint_path = path.with_suffix(".checkpoint.json")
|
||||
checkpoint_path.write_text(json.dumps({"version": 1}))
|
||||
original, original_checkpoint = path.read_bytes(), checkpoint_path.read_bytes()
|
||||
original_unlink = Path.unlink
|
||||
|
||||
def interrupted_unlink(target, *args, **kwargs):
|
||||
if target == checkpoint_path:
|
||||
raise OSError("interrupted checkpoint removal")
|
||||
return original_unlink(target, *args, **kwargs)
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(Path, "unlink", interrupted_unlink)
|
||||
with pytest.raises(RuntimeError, match="Could not move legacy sessions"):
|
||||
SessionManager(workspace)
|
||||
assert not path.exists()
|
||||
assert checkpoint_path.read_bytes() == original_checkpoint
|
||||
manager = SessionManager(workspace)
|
||||
assert len(manager.list_sessions()) == 1
|
||||
assert not checkpoint_path.exists()
|
||||
backup = manager.sessions_dir / WORKSPACE_BACKUP_DIR
|
||||
assert (backup / path.name).read_bytes() == original
|
||||
assert (backup / checkpoint_path.name).read_bytes() == original_checkpoint
|
||||
|
||||
|
||||
def test_restart_requires_durable_workspace_source_removal(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
original = path.read_bytes()
|
||||
original_sync = SessionLocation.fsync_directory
|
||||
|
||||
def unavailable_directory_sync(directory):
|
||||
if directory == path.parent:
|
||||
raise OSError("source directory flush unavailable")
|
||||
original_sync(directory)
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(SessionLocation, "fsync_directory", staticmethod(unavailable_directory_sync))
|
||||
for _ in range(2):
|
||||
with pytest.raises(RuntimeError, match="Could not move legacy sessions"):
|
||||
SessionManager(workspace)
|
||||
assert not path.exists()
|
||||
manager = SessionManager(workspace)
|
||||
assert len(manager.list_sessions()) == 1
|
||||
assert (manager.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == original
|
||||
|
||||
|
||||
def test_stale_administrative_save_is_rejected(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
session = Session(key="chat:a")
|
||||
@@ -275,6 +502,135 @@ async def test_large_draft_copy_and_publication_run_on_owner_worker(tmp_path, mo
|
||||
await state.aclose()
|
||||
|
||||
|
||||
def test_duplicate_json_keys_abort_entire_migration(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
path.write_text(
|
||||
'{"_type":"metadata","key":"chat:a","key":"chat:b",'
|
||||
'"metadata":{},"created_at":"2026-01-01T00:00:00",'
|
||||
'"updated_at":"2026-01-01T00:00:00"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match="migration failed"):
|
||||
SessionManager(workspace, sessions_root=tmp_path / "root")
|
||||
|
||||
database = next((tmp_path / "root").glob("*/sessions.sqlite3"))
|
||||
with sqlite3.connect(database) as db:
|
||||
tables = {
|
||||
row[0]
|
||||
for row in db.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table'"
|
||||
)
|
||||
}
|
||||
assert "sessions" not in tables
|
||||
assert "storage_meta" not in tables
|
||||
|
||||
|
||||
def test_nested_duplicate_json_keys_abort_migration(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
path.write_text(
|
||||
'{"_type":"metadata","key":"chat:a","metadata":{"title":"a","title":"b"},'
|
||||
'"created_at":"2026-01-01T00:00:00",'
|
||||
'"updated_at":"2026-01-01T00:00:00"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match="migration failed"):
|
||||
SessionManager(workspace, sessions_root=tmp_path / "root")
|
||||
|
||||
|
||||
def test_second_provider_state_aborts_migration(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
path = legacy(workspace)
|
||||
state = {
|
||||
"kind": "responses",
|
||||
"provider": "openai",
|
||||
"model": "gpt-test",
|
||||
"version": 1,
|
||||
"payload": {"secret": "opaque"},
|
||||
"pending_messages": [],
|
||||
}
|
||||
with path.open("a", encoding="utf-8") as handle:
|
||||
record = json.dumps({"_type": "provider_state", "state": state})
|
||||
handle.write(record + "\n" + record + "\n")
|
||||
|
||||
with pytest.raises(RuntimeError, match="migration failed"):
|
||||
SessionManager(workspace, sessions_root=tmp_path / "root")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_checkpoint", [False, True])
|
||||
def test_identical_migration_copies_are_imported_once_and_cleaned_up(tmp_path, with_checkpoint):
|
||||
workspace = tmp_path / "workspace"
|
||||
root = tmp_path / "root"
|
||||
source = legacy(workspace, key="chat:a")
|
||||
sources = [source]
|
||||
if with_checkpoint:
|
||||
checkpoint = source.with_suffix(".checkpoint.json")
|
||||
checkpoint.write_text(json.dumps({
|
||||
"version": 1, "session_key": "chat:a", "base_message_count": 1,
|
||||
"base_updated_at": "2026-01-01T00:00:00",
|
||||
"checkpoint": {"messages": [{"role": "assistant", "content": "partial"}]},
|
||||
}))
|
||||
sources.append(checkpoint)
|
||||
location = SessionLocation(workspace, sessions_root=root)
|
||||
originals = {path.name: path.read_bytes() for path in sources}
|
||||
for path in sources:
|
||||
shutil.copy2(path, location.sessions_dir / path.name)
|
||||
|
||||
for _ in range(2):
|
||||
manager = SessionManager(workspace, sessions_root=root)
|
||||
assert len(manager.list_sessions()) == 1
|
||||
session = manager.read_session_snapshot("chat:a")
|
||||
assert [message["content"] for message in session.messages] == ["hello"]
|
||||
if with_checkpoint:
|
||||
assert session.metadata["runtime_checkpoint"]["messages"][0]["content"] == "partial"
|
||||
for path in sources:
|
||||
assert not path.exists()
|
||||
assert (location.sessions_dir / path.name).read_bytes() == originals[path.name]
|
||||
assert (location.sessions_dir / WORKSPACE_BACKUP_DIR / path.name).read_bytes() == originals[path.name]
|
||||
|
||||
|
||||
def test_duplicate_sources_with_different_timestamps_abort_migration(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
root = tmp_path / "root"
|
||||
source = legacy(workspace, key="chat:a")
|
||||
location = SessionLocation(workspace, sessions_root=root)
|
||||
duplicate = location.sessions_dir / source.name
|
||||
duplicate.write_text(
|
||||
source.read_text(encoding="utf-8").replace(
|
||||
'"updated_at": "2026-01-01T00:00:00"',
|
||||
'"updated_at": "2026-01-02T00:00:00"',
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match="migration failed"):
|
||||
SessionManager(workspace, sessions_root=root)
|
||||
duplicate.unlink()
|
||||
manager = SessionManager(workspace, sessions_root=root)
|
||||
assert manager.read_session_snapshot("chat:a") is not None
|
||||
|
||||
|
||||
def test_invalid_migration_marker_fails_closed(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
root = tmp_path / "root"
|
||||
manager = SessionManager(workspace, sessions_root=root)
|
||||
with sqlite3.connect(manager._store.path) as db:
|
||||
db.execute(
|
||||
"UPDATE storage_meta SET value='corrupt' WHERE key='jsonl_import'"
|
||||
)
|
||||
legacy(workspace, key="chat:must-not-import")
|
||||
|
||||
with pytest.raises(RuntimeError, match="invalid JSONL migration marker"):
|
||||
SessionManager(workspace, sessions_root=root)
|
||||
with sqlite3.connect(manager._store.path) as db:
|
||||
assert db.execute(
|
||||
"SELECT count(*) FROM sessions WHERE key='chat:must-not-import'"
|
||||
).fetchone()[0] == 0
|
||||
|
||||
|
||||
async def test_missing_update_commands_do_not_create_sessions(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
state = manager.state
|
||||
|
||||
@@ -18,6 +18,8 @@ from nanobot.release_feed import ReleaseFeed
|
||||
from scripts import verify_packaged_update as probe
|
||||
from scripts.verify_packaged_update import (
|
||||
Timings,
|
||||
assert_canonical_preserved,
|
||||
assert_history_preserved,
|
||||
canonical_records,
|
||||
digest,
|
||||
feed_records,
|
||||
@@ -26,33 +28,58 @@ from scripts.verify_packaged_update import (
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def history_root(tmp_path, monkeypatch):
|
||||
from nanobot.config.paths import get_runtime_subdir
|
||||
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "account/.nanobot/config.json")
|
||||
monkeypatch.setattr("nanobot.session.location.get_runtime_subdir", get_runtime_subdir)
|
||||
return tmp_path
|
||||
def test_historical_projection_defaults_do_not_mask_history_loss():
|
||||
# Real retained packages omit unknown timestamps and an inactive goal from
|
||||
# their public projection, although the latter is already in their JSONL.
|
||||
events = [{"event": "user_message", "projection_id": "input", "text": "Keep this"},
|
||||
{"event": "turn_end", "projection_id": "complete"}]
|
||||
before = {"events": events, "completed_turn_ids": ["turn"]}
|
||||
projected = [{**events[0], "created_at_ms": 0},
|
||||
{**events[1], "created_at_ms": 0, "goal_state": {"active": False}}]
|
||||
after = {**before, "events": projected}
|
||||
assert_history_preserved(before, after)
|
||||
assert_history_preserved(after, after)
|
||||
for change in ({"text": "Changed"}, {"projection_id": "changed"}, {"created_at_ms": 123}):
|
||||
with pytest.raises(AssertionError):
|
||||
assert_history_preserved(before, {**after, "events": [{**projected[0], **change}, projected[1]]})
|
||||
with pytest.raises(AssertionError):
|
||||
assert_history_preserved(before, {**after, "events": [projected[0], {**projected[1], "goal_state": {"active": True}}]})
|
||||
with pytest.raises(AssertionError):
|
||||
assert_history_preserved(before, {**after, "events": projected[:1]})
|
||||
with pytest.raises(AssertionError):
|
||||
assert_history_preserved(before, {**after, "completed_turn_ids": []})
|
||||
with pytest.raises(AssertionError):
|
||||
assert_history_preserved(after, before)
|
||||
|
||||
|
||||
async def test_native_history_fixture_reopens_without_mixing_model_and_display_data(history_root):
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.webui.transcript import build_webui_thread_response
|
||||
def test_display_migration_allows_an_empty_owner_without_masking_context_loss(tmp_path):
|
||||
from nanobot.session.display_history import HistoryFact, HistoryImport, HistoryKind
|
||||
from nanobot.session.manager import Session
|
||||
from nanobot.session.sqlite_store import SqliteSessionStore
|
||||
|
||||
probe.seed_history(history_root)
|
||||
sessions = SessionManager(history_root / "workspace")
|
||||
assert sessions.sessions_dir.is_relative_to(history_root / "account/.nanobot")
|
||||
records = canonical_records(sessions.sessions_dir / "sessions.sqlite3")
|
||||
assert len(records["sessions"]) == 3
|
||||
for key in ("websocket:mixed-history", "websocket:canonical-only"):
|
||||
assert sessions.read_session_file(key)["messages"] == [{"role": "user", "content": "配置和聊天不能丢失"}]
|
||||
assert sessions.read_session_file("websocket:display-only")["messages"] == []
|
||||
assert sessions.project_history("websocket:canonical-only", lambda history: history.all_facts()) == []
|
||||
for key in ("websocket:mixed-history", "websocket:display-only"):
|
||||
response = sessions.project_history(key, lambda history, key=key: build_webui_thread_response(key, history=history))
|
||||
assert response["completed_turn_ids"] == ["fixture-" + key.split(":", 1)[1]]
|
||||
assert {event.get("text") for event in response["events"]} >= {"配置和聊天不能丢失", "独立验收数据"}
|
||||
assert canonical_records(sessions.sessions_dir / "sessions.sqlite3") == records
|
||||
store = SqliteSessionStore(tmp_path)
|
||||
store.initialize(tmp_path)
|
||||
session = Session(key="websocket:canonical-only")
|
||||
session.add_message("user", "Keep this original context")
|
||||
store.save(session)
|
||||
before = canonical_records(store.path)
|
||||
store.migrate_history("acceptance-import", lambda _: [HistoryImport(
|
||||
key="websocket:display-only", facts=[HistoryFact(HistoryKind.ANSWER, {"text": "Display only"})],
|
||||
)])
|
||||
after = canonical_records(store.path)
|
||||
assert_canonical_preserved(before, after)
|
||||
assert_canonical_preserved(after, after)
|
||||
# The real /api/sessions read allocates the newly imported owner's handle.
|
||||
store.update_metadata("websocket:display-only", {"session_handle": "jeno"})
|
||||
after = canonical_records(store.path)
|
||||
assert_canonical_preserved(before, after)
|
||||
with pytest.raises(AssertionError):
|
||||
assert_canonical_preserved(before, {**after, "messages": []})
|
||||
with pytest.raises(AssertionError):
|
||||
assert_canonical_preserved(before, {**after, "sessions": after["sessions"][1:]})
|
||||
store.update_metadata("websocket:display-only", {"unexpected": "context"})
|
||||
with pytest.raises(AssertionError):
|
||||
assert_canonical_preserved(before, canonical_records(store.path))
|
||||
|
||||
|
||||
def wheel(tmp_path, version, *, worker=b"# worker\n", fallback=b"# fallback\n"):
|
||||
|
||||
@@ -315,6 +315,13 @@ def test_thread_response_receipts_for_folded_legacy_deltas(
|
||||
[{"turn_id": "turn-folded", "ranges": [[6, 6], [10, 10]]}],
|
||||
]
|
||||
assert history.read(key) == original_rows
|
||||
# Migration compaction retains its existing record format, without HTTP metadata.
|
||||
assert transcript_module.compact_legacy_records(original_rows) == [
|
||||
original_rows[0], original_rows[3],
|
||||
{**original_rows[6], "text": primary_text},
|
||||
{**original_rows[7], "text": "other"},
|
||||
original_rows[8],
|
||||
]
|
||||
|
||||
|
||||
def test_event_projection_defers_trace_details_without_legacy_fallback(history,
|
||||
|
||||
@@ -349,6 +349,46 @@ async def test_sidebar_allocates_handles_then_reads_during_pending_write(tmp_pat
|
||||
await state.aclose()
|
||||
|
||||
|
||||
def test_webui_session_list_fallback_time_when_missing(tmp_path: Path) -> None:
|
||||
legacy = tmp_path / "sessions"
|
||||
legacy.mkdir()
|
||||
path = legacy / "websocket_missing-time.jsonl"
|
||||
path.write_text(
|
||||
'{"_type": "metadata", "key": "websocket:missing-time"}\n'
|
||||
'{"_type": "message", "role": "user", "content": "hello"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
manager = SessionManager(tmp_path)
|
||||
|
||||
rows = list_webui_sessions(manager)
|
||||
assert len(rows) == 1
|
||||
assert rows[0]["key"] == "websocket:missing-time"
|
||||
assert rows[0]["created_at"] is not None
|
||||
assert rows[0]["updated_at"] is not None
|
||||
datetime.fromisoformat(rows[0]["created_at"])
|
||||
datetime.fromisoformat(rows[0]["updated_at"])
|
||||
|
||||
|
||||
def test_session_manager_list_sessions_fallback_time_when_missing(tmp_path: Path) -> None:
|
||||
legacy = tmp_path / "sessions"
|
||||
legacy.mkdir()
|
||||
path = legacy / "websocket_missing-time2.jsonl"
|
||||
path.write_text(
|
||||
'{"_type": "metadata", "key": "websocket:missing-time2"}\n'
|
||||
'{"_type": "message", "role": "user", "content": "hello"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
manager = SessionManager(tmp_path)
|
||||
|
||||
sessions = manager.list_sessions()
|
||||
assert len(sessions) == 1
|
||||
assert sessions[0]["key"] == "websocket:missing-time2"
|
||||
assert sessions[0]["created_at"] is not None
|
||||
assert sessions[0]["updated_at"] is not None
|
||||
datetime.fromisoformat(sessions[0]["created_at"])
|
||||
datetime.fromisoformat(sessions[0]["updated_at"])
|
||||
|
||||
|
||||
def test_sidebar_uses_durable_display_summary_and_filters_private_sessions(history):
|
||||
sessions = history.sessions
|
||||
sessions.types.register(SessionType("internal", needs_handle=False, public_history=False))
|
||||
|
||||
@@ -116,7 +116,9 @@ def test_session_mention_context_treats_titles_as_data() -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_mentions_do_not_isolate_workspaces(tmp_path) -> None:
|
||||
async def test_session_mentions_do_not_isolate_workspaces(tmp_path, monkeypatch) -> None:
|
||||
webui_dir = tmp_path / "webui"
|
||||
monkeypatch.setattr("nanobot.webui.history.get_webui_dir", lambda: webui_dir)
|
||||
manager = SessionManager(tmp_path)
|
||||
project_b = tmp_path / "b"
|
||||
project_b.mkdir()
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -30,6 +31,8 @@ from nanobot.providers.base import (
|
||||
ProviderConversationState,
|
||||
ToolCallRequest,
|
||||
)
|
||||
from nanobot.session.jsonl_migration import WORKSPACE_BACKUP_DIR
|
||||
from nanobot.session.location import SessionLocation
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.session_handles import SessionHandleResolver
|
||||
from nanobot.session.summary import SessionSummaryCheckpoint, is_summary_checkpoint
|
||||
@@ -270,8 +273,7 @@ async def test_child_activity_replays_real_tool_errors_and_file_diffs(tmp_path):
|
||||
path = f"/api/sessions/websocket%3Aparent/subagents/{task_id}/webui-thread"
|
||||
|
||||
async def assert_activity(gateway, connection, headers):
|
||||
child_key = SubagentSessions.key(task_id)
|
||||
before = sessions.project_history(child_key, lambda history: history.all_facts())
|
||||
before = {file.name: file.read_bytes() for file in root.glob("*.jsonl")}
|
||||
response = await gateway.http.dispatch(connection, Request(path, headers))
|
||||
assert response.status_code == 200
|
||||
thread = json.loads(response.body)
|
||||
@@ -284,7 +286,7 @@ async def test_child_activity_replays_real_tool_errors_and_file_diffs(tmp_path):
|
||||
assert "+after" in completed["diff"]["text"]
|
||||
assert "-before" in completed["diff"]["text"]
|
||||
assert (workspace / "example.txt").read_text(encoding="utf-8") == "after\n"
|
||||
assert sessions.project_history(child_key, lambda history: history.all_facts()) == before
|
||||
assert {file.name: file.read_bytes() for file in root.glob("*.jsonl")} == before
|
||||
return thread
|
||||
|
||||
assert (await assert_activity(gateway, connection, headers))["active_turn_id"]
|
||||
@@ -849,6 +851,63 @@ async def test_temporary_parent_never_persists_task_content(tmp_path, monkeypatc
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_child_sessions_migrate_from_legacy_jsonl_and_reopen(tmp_path):
|
||||
workspace, root = tmp_path / "agent", tmp_path / "sessions"
|
||||
parent_key, task_id = "websocket:parent", "legacy-inspection"
|
||||
child_key = SubagentSessions.key(task_id)
|
||||
task_metadata = {
|
||||
"task_id": task_id, "owner": parent_key, "revision": 3,
|
||||
"label": "inspect", "task_description": "inspect", "state": "done", "phase": "done",
|
||||
"created_at": 1767225600.0, "completed_at": 1767225601.2, "elapsed_seconds": 1.2,
|
||||
"origin_turn_id": "turn-1", "iteration": 1, "result": "Verified", "stop_reason": "stop",
|
||||
}
|
||||
fixtures = {
|
||||
parent_key: [
|
||||
{"_type": "metadata", "key": parent_key, "metadata": {"webui": True},
|
||||
"created_at": "2026-01-01T00:00:00", "updated_at": "2026-01-01T00:00:00",
|
||||
"last_archived": 0},
|
||||
{"role": "user", "content": "Inspect config"},
|
||||
],
|
||||
child_key: [
|
||||
{"_type": "metadata", "key": child_key,
|
||||
"metadata": {SESSION_TYPE_KEY: SUBAGENT.name, PARENT_SESSION_KEY: parent_key,
|
||||
TASK_METADATA_KEY: task_metadata},
|
||||
"created_at": "2026-01-01T00:00:00", "updated_at": "2026-01-01T00:00:01.200000",
|
||||
"last_archived": 0},
|
||||
{"role": "user", "content": "inspect"},
|
||||
{"role": "assistant", "content": "Verified"},
|
||||
],
|
||||
}
|
||||
legacy = workspace / "sessions"
|
||||
legacy.mkdir(parents=True)
|
||||
for key, records in fixtures.items():
|
||||
(legacy / f"{SessionLocation.storage_key(key)}.jsonl").write_text(
|
||||
"\n".join(json.dumps(record) for record in records) + "\n", encoding="utf-8",
|
||||
)
|
||||
source_hashes = {path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in legacy.glob("*.jsonl")}
|
||||
|
||||
for _ in range(2):
|
||||
manager, sessions, _ = manager_with_storage(workspace, root)
|
||||
try:
|
||||
assert {row["key"] for row in sessions.list_sessions()} == set(fixtures)
|
||||
assert sessions.child_session_keys(parent_key) == [child_key]
|
||||
status = manager.check(task_id, parent_key)
|
||||
assert status.state == "done" and status.result == "Verified"
|
||||
assert status.origin_turn_id == "turn-1"
|
||||
assert manager.get_running_count() == 0
|
||||
for key, records in fixtures.items():
|
||||
restored = sessions.read_session_file(key)
|
||||
assert restored["metadata"] == records[0]["metadata"]
|
||||
assert restored["messages"] == records[1:]
|
||||
assert list(legacy.glob("*.jsonl")) == []
|
||||
backups = sessions.sessions_dir / WORKSPACE_BACKUP_DIR
|
||||
assert {path.name: hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
for path in backups.glob("*.jsonl")} == source_hashes
|
||||
finally:
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unreadable_task_history_is_not_an_empty_list(tmp_path):
|
||||
manager, sessions, runtime = manager_with_storage(tmp_path / "agent", tmp_path / "sessions")
|
||||
|
||||
Reference in new issue
Block a user