fix(webui): preserve unmigrated workspace history ownership
This commit is contained in:
1 parent
812b92d734
commit
92e6608e6e
2 files changed
+69
-13
No files matched your search
+20
-13
@@ -159,20 +159,27 @@ def collect_legacy_history(
|
|||||||
keys_by_stem.setdefault(SessionManager.safe_key(session["key"]), set()).add(session["key"])
|
keys_by_stem.setdefault(SessionManager.safe_key(session["key"]), set()).add(session["key"])
|
||||||
foreign_owners: dict[str, list[Path]] = {}
|
foreign_owners: dict[str, list[Path]] = {}
|
||||||
if namespace is not None and groups:
|
if namespace is not None and groups:
|
||||||
for database in namespace.parent.glob("*/sessions.sqlite3"):
|
for other_namespace in namespace.parent.iterdir():
|
||||||
if database.parent == namespace:
|
if other_namespace == namespace or not other_namespace.is_dir():
|
||||||
continue
|
continue
|
||||||
if database.is_symlink() or database.parent.is_symlink():
|
database = other_namespace / "sessions.sqlite3"
|
||||||
raise ValueError(f"invalid session namespace for history migration: {database}")
|
if database.is_symlink() or other_namespace.is_symlink():
|
||||||
with closing(sqlite3.connect(database.as_uri() + "?mode=ro", uri=True)) as db:
|
raise ValueError(f"invalid session namespace for history migration: {other_namespace}")
|
||||||
owned = {str(row[0]) for row in db.execute("SELECT key FROM sessions")}
|
if database.exists():
|
||||||
prefix = f"{HISTORY_IMPORT_MARKER}:"
|
# SQLite and deletion receipts take precedence over retained JSONL backups.
|
||||||
owned.update(str(row[0])[len(prefix):] for row in db.execute(
|
with closing(sqlite3.connect(database.as_uri() + "?mode=ro", uri=True)) as db:
|
||||||
"SELECT key FROM storage_meta WHERE key LIKE ? AND value='complete'",
|
owned = {str(row[0]) for row in db.execute("SELECT key FROM sessions")}
|
||||||
(prefix + "%",),
|
prefix = f"{HISTORY_IMPORT_MARKER}:"
|
||||||
))
|
owned.update(str(row[0])[len(prefix):] for row in db.execute(
|
||||||
for key in owned:
|
"SELECT key FROM storage_meta WHERE key LIKE ? AND value='complete'",
|
||||||
foreign_owners.setdefault(key, []).append(database)
|
(prefix + "%",),
|
||||||
|
))
|
||||||
|
else:
|
||||||
|
from nanobot.session.jsonl_migration import read_jsonl
|
||||||
|
|
||||||
|
owned = {read_jsonl(path)[0].key for path in other_namespace.glob("*.jsonl")}
|
||||||
|
for key in owned:
|
||||||
|
foreign_owners.setdefault(key, []).append(other_namespace)
|
||||||
imports: list[HistoryImport] = []
|
imports: list[HistoryImport] = []
|
||||||
for stem, paths in groups.items():
|
for stem, paths in groups.items():
|
||||||
records = [record for path in paths for record in _read_legacy_file(path)]
|
records = [record for path in paths for record in _read_legacy_file(path)]
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ from pathlib import Path
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from nanobot.session.display_history import HistoryFact, HistoryKind
|
from nanobot.session.display_history import HistoryFact, HistoryKind
|
||||||
|
from nanobot.session.location import SessionLocation
|
||||||
from nanobot.session.manager import SessionManager
|
from nanobot.session.manager import SessionManager
|
||||||
from nanobot.session.sqlite_store import SessionConflictError
|
from nanobot.session.sqlite_store import SessionConflictError
|
||||||
from nanobot.webui.forking import create_webui_chat_fork
|
from nanobot.webui.forking import create_webui_chat_fork
|
||||||
@@ -247,6 +248,54 @@ asyncio.run(run())
|
|||||||
assert reopened.read_session_file(source.key)["messages"] == source.messages
|
assert reopened.read_session_file(source.key)["messages"] == source.messages
|
||||||
|
|
||||||
|
|
||||||
|
async def test_legacy_import_waits_for_unmigrated_workspace_owner(tmp_path, monkeypatch):
|
||||||
|
root = tmp_path / "sessions"
|
||||||
|
directory = tmp_path / "webui"
|
||||||
|
monkeypatch.setattr("nanobot.webui.history.get_webui_dir", lambda: directory)
|
||||||
|
locations = {}
|
||||||
|
sources = {}
|
||||||
|
for name in ("first", "second"):
|
||||||
|
location = SessionLocation(tmp_path / name, sessions_root=root)
|
||||||
|
locations[name] = location
|
||||||
|
key = f"websocket:{name}"
|
||||||
|
source = location.sessions_dir / f"{SessionLocation.storage_key(key)}.jsonl"
|
||||||
|
source.write_text("\n".join(json.dumps(record) for record in [
|
||||||
|
{"_type": "metadata", "key": key, "metadata": {}},
|
||||||
|
{"role": "user", "content": f"question {name}"},
|
||||||
|
]) + "\n", encoding="utf-8")
|
||||||
|
display = _legacy(directory, key, [
|
||||||
|
{"event": "user", "chat_id": name, "text": f"question {name}"},
|
||||||
|
{"event": "message", "chat_id": name, "text": f"answer {name}"},
|
||||||
|
{"event": "turn_end", "chat_id": name},
|
||||||
|
])
|
||||||
|
sources.update({path: path.read_bytes() for path in (source, display)})
|
||||||
|
|
||||||
|
async def initialize(name: str):
|
||||||
|
sessions = SessionManager(tmp_path / name, sessions_root=root)
|
||||||
|
key = f"websocket:{name}"
|
||||||
|
try:
|
||||||
|
await WebUITranscriptRecorder(sessions).initialize()
|
||||||
|
assert [row["key"] for row in await sessions.state.list_sessions()] == [key]
|
||||||
|
session = await sessions.state.read(key)
|
||||||
|
assert session is not None
|
||||||
|
assert session.messages == [{"role": "user", "content": f"question {name}"}]
|
||||||
|
facts = await sessions.state.project_history(key, lambda history: history.all_facts())
|
||||||
|
assert [(fact.kind, fact.content.get("text")) for fact in facts] == [
|
||||||
|
(HistoryKind.INPUT, f"question {name}"),
|
||||||
|
(HistoryKind.ANSWER, f"answer {name}"),
|
||||||
|
(HistoryKind.COMPLETION, None),
|
||||||
|
]
|
||||||
|
finally:
|
||||||
|
await sessions.state.aclose()
|
||||||
|
|
||||||
|
await initialize("second")
|
||||||
|
assert not (locations["first"].sessions_dir / "sessions.sqlite3").exists()
|
||||||
|
await initialize("first")
|
||||||
|
await initialize("second")
|
||||||
|
await initialize("first")
|
||||||
|
assert {path: path.read_bytes() for path in sources} == sources
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_legacy_import_owner_survives_delete_and_new_workspace(tmp_path):
|
async def test_legacy_import_owner_survives_delete_and_new_workspace(tmp_path):
|
||||||
from nanobot.webui.history import collect_legacy_history
|
from nanobot.webui.history import collect_legacy_history
|
||||||
|
|||||||
Reference in new issue
Block a user