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:
chengyongru authored and chengyongru committed 2026-11-06 10:58:10 +08:00
1 parent 3918ece17f
commit 812b92d734
47 files changed
+1932 -204

No files matched your search

+2 -4
View File
@@ -38,17 +38,15 @@ RULES = (
((".github/workflows/*",), ALL, "unknown workflow"),
(("pyproject.toml", "uv.lock", "hatch_build.py", "nanobot/webui/build.py", "scripts/install*",
"scripts/build*"), ALL, "cross-domain dependency, build or installation contract"),
(("scripts/verify_packaged_update.py",), PYTHON | DOCKER | NATIVE,
"shared packaged and Docker upgrade verification"),
(("tests/test_docker*.py",), PYTHON | DOCKER, "Docker Python regression tests"),
(("Dockerfile", "Dockerfile.*", ".dockerignore", "docker-compose*.yml", "entrypoint.sh",
"render-config.json", "README.md", "LICENSE", "THIRD_PARTY_NOTICES.md",
"tests/test_docker*", "scripts/docker_compose_smoke.py", "scripts/docker_upgrade_smoke.py"), DOCKER, "Docker input or acceptance"),
"tests/test_docker*", "scripts/docker_compose_smoke.py"), DOCKER, "Docker input or acceptance"),
# Shared fixture consumers live in tests/webui and webui/src/tests; the
# SQLite migration and release-trust fixtures have separate Python owners.
(("tests/webui/fixtures/runtime-config-keys.json",), PYTHON | WEBUI,
"shared Python and WebUI runtime configuration test contract"),
(("tests/session/fixtures/*.sql",), PYTHON, "Python session storage upgrade fixtures"),
(("tests/session/fixtures/sqlite_v1.sql",), PYTHON, "Python session schema migration fixture"),
(("tests/fixtures/sigstore/bundle_v3.txt", "tests/fixtures/sigstore/bundle_v3.txt.sigstore"),
PYTHON | NATIVE, "release trust verification fixtures"),
(("tests/fixtures/sigstore/README.md", "tests/fixtures/sigstore/LICENSE"),
+24 -5
View File
@@ -14,6 +14,7 @@ import tempfile
import time
from pathlib import Path
from types import SimpleNamespace
from urllib.parse import quote
def product_phase(phase: str, version: str) -> None:
@@ -41,7 +42,26 @@ def product_phase(phase: str, version: str) -> None:
time.sleep(0.2)
raise RuntimeError("Installed container gateway did not become ready")
probe.ready = ready
def history(root, key):
rows = probe.request(root, "/api/sessions")["sessions"]
assert key in {row["key"] for row in rows}
response = probe.request(root, "/api/sessions/" + quote(key, safe="") + "/webui-thread")
# Released 0.3.5 returns rendered messages; 0.4 returns events. These
# command-only fixtures compare visible text plus completed-turn identity.
if "messages" in response:
events = []
for message in response["messages"]:
assert message["role"] in {"user", "assistant"}
events.append({"event": "user" if message["role"] == "user" else "message",
"text": message["content"]})
else:
events = [{"event": "user" if event["event"] == "user_message" else event["event"],
"text": event["text"]} for event in response["events"]
if event["event"] in {"user", "user_message", "message"}]
assert events
return {"events": events, "completed_turn_ids": response["completed_turn_ids"]}
probe.ready, probe.history = ready, history
try:
if phase == "seed":
root.mkdir()
@@ -50,7 +70,7 @@ def product_phase(phase: str, version: str) -> None:
probe.snapshot(root)
else:
probe.gateway(root, "--background")
probe.verify_data(root, version)
assert probe.verify_data(root, version)
finally:
probe.gateway(root, "stop")
@@ -95,8 +115,7 @@ def run(args) -> dict:
return {"source_commit": args.source_commit, "baseline_image": images["baseline"], "target_image": images["target"],
"baseline_version": args.baseline_version, "target_version": args.version,
"probe_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
"same_volume_image_replacement": True, "history_fixture": "native-sqlite",
"config_bytes_preserved": True, "sqlite_records_preserved": True, "scheduled_delivery_preserved": True,
"same_volume_image_replacement": True, "config_and_legacy_bytes_preserved": True,
"authenticated_history_preserved": True, "canonical_only_and_display_only_preserved": True,
"continued_write_and_second_start": True, "non_root": True, "no_external_network": True,
"container_and_volume_cleaned": True, "in_place_update_or_automatic_rollback": False}
@@ -106,7 +125,7 @@ def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--image")
parser.add_argument("--baseline-image")
parser.add_argument("--baseline-version", default="0.4.0")
parser.add_argument("--baseline-version", default="0.3.5")
parser.add_argument("--version", required=True)
parser.add_argument("--output", type=Path)
parser.add_argument("--source-commit")
+136 -73
View File
@@ -3,8 +3,7 @@
The healthy target is the exact supplied wheel, not a patched application. The
default baseline is explicitly a version-only fixture with a local feed transport
and bounded fault injection. It does not stand for an older published release.
Use --baseline-wheel to exercise an actual earlier updater-enabled package with
SQLite session history, shared proxy configuration and a durable delivery outbox too.
Use --baseline-wheel to exercise an actual earlier updater-enabled package too.
No public feed, user installation, model, credentials or OS service is used.
"""
@@ -20,6 +19,7 @@ import io
import json
import os
import platform
import re
import secrets
import signal
import socket
@@ -307,6 +307,23 @@ def history(root: Path, key: str):
return {name: response[name] for name in ("events", "completed_turn_ids")}
def assert_history_preserved(before: dict, after: dict) -> None:
"""Allow only known additive defaults in the older transcript projection."""
assert after["completed_turn_ids"] == before["completed_turn_ids"]
assert len(after["events"]) == len(before["events"])
for previous, current in zip(before["events"], after["events"], strict=True):
current = dict(current)
# SQLite represents an unknown legacy timestamp as zero. New projection
# also exposes the already-persisted inactive goal on a completed turn.
# Do not ignore these fields when the old API supplied an actual value.
if "created_at_ms" not in previous and current.get("created_at_ms") == 0:
del current["created_at_ms"]
if (previous["event"] == "turn_end" and "goal_state" not in previous
and current.get("goal_state") == {"active": False}):
del current["goal_state"]
assert current == previous, (current, previous)
def canonical_records(path: Path, tables: tuple[str, ...] = ("sessions", "messages", "checkpoints", "pending_inputs")) -> dict:
"""Compare logical records, not SQLite's transient WAL/checkpoint layout."""
with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True)) as db:
@@ -315,6 +332,26 @@ def canonical_records(path: Path, tables: tuple[str, ...] = ("sessions", "messag
for table in tables}
def assert_canonical_preserved(before: dict, after: dict) -> None:
"""Schema v2 may add a display-only owner, never model context or lost rows."""
key = "websocket:display-only"
existing = {row[0] for row in before["sessions"]}
added = [row for row in after["sessions"] if row[0] == key and key not in existing]
for row in added:
# A newly imported display transcript owns an empty Session. Only its
# identity/timestamps and the public handle allocated by /api/sessions
# are new; it must not manufacture agent context or other metadata.
metadata = json.loads(row[3])
if metadata:
assert set(metadata) == {"session_handle"}, row
handle = metadata["session_handle"]
assert isinstance(handle, str) and re.fullmatch("[a-z]{4,16}", handle), row
revision = 2 if metadata else 1
assert row[4:7] == [None, 0, revision] and row[8:] == ["", "", None], row
comparable = {**after, "sessions": [row for row in after["sessions"] if row not in added]}
assert comparable == before, (comparable, before)
def canonical_context(root: Path) -> dict:
context = request(root, "/api/sessions/websocket%3Acanonical-only/context")
# Tokenizer availability can alter estimates; stored message content is
@@ -362,28 +399,10 @@ def ready(root: Path, version: str):
raise RuntimeError("The actual installed gateway did not become ready")
def seed_history(root: Path) -> None:
from nanobot.session.display_history import HistoryFact, HistoryKind
from nanobot.session.manager import Session, SessionManager
sessions = SessionManager(root / "workspace")
for key in ("websocket:mixed-history", "websocket:canonical-only"):
sessions.save(Session(key=key, metadata={"title": "升级前的聊天"},
messages=[{"role": "user", "content": "配置和聊天不能丢失"}]))
for chat_id in ("mixed-history", "display-only"):
sessions.append_history("websocket:" + chat_id, [
HistoryFact(HistoryKind.INPUT, {"text": "配置和聊天不能丢失"}, turn_id="fixture-" + chat_id),
HistoryFact(HistoryKind.ANSWER, {"text": "独立验收数据"}, turn_id="fixture-" + chat_id),
HistoryFact(HistoryKind.COMPLETION, turn_id="fixture-" + chat_id),
])
def seed(root: Path) -> None:
import nanobot
from nanobot.bus.delivery import DeliveryRequest
from nanobot.bus.events import OutboundMessage
from nanobot.channels.outbox import DeliveryOutbox
from nanobot.config.loader import load_config, save_config, set_config_path
from nanobot.config.paths import get_webui_dir
assert Path(nanobot.__file__).resolve().is_relative_to(Path(sys.prefix).resolve())
config_path = root / "account/.nanobot/config.json"
@@ -397,19 +416,37 @@ def seed(root: Path) -> None:
config.agents.defaults.session_ttl_minutes = 0
config.providers.custom.api_key = "fixture-not-a-secret"
config.providers.custom.api_base = "http://127.0.0.1:1/v1"
config.network.proxy = "http://127.0.0.1:9"
config.providers.custom.use_proxy = True
config.gateway.host, config.gateway.port = "127.0.0.1", free_port()
config.gateway.heartbeat.enabled = False
config.channels.websocket = {"enabled": True, "host": "127.0.0.1", "port": free_port(),
"tokenIssueSecret": secrets.token_urlsafe(32), "websocketRequiresToken": True}
save_config(config, config_path)
seed_history(root)
with patch("nanobot.channels.outbox.time.time", return_value=time.time() + 3600):
DeliveryOutbox(config_path.parent / "delivery/outbox.sqlite3").record(OutboundMessage(
"whatsapp", "acceptance-offline", "Retain this scheduled result",
delivery=DeliveryRequest("acceptance-run", "websocket:mixed-history", None),
))
# Real historical canonical files are imported by the installed SQLite owner,
# not generated by a new-store round trip. Existing source bytes stay readable.
if importlib.util.find_spec("nanobot.session.location") is not None:
from nanobot.session.location import SessionLocation
location = SessionLocation(root / "workspace")
else:
# The retained pre-SQLite package owns the same namespace here. This is
# acceptance-fixture compatibility, not a fallback in the application.
from nanobot.session.manager import JsonlSessionStore
location = JsonlSessionStore(root / "workspace")
sessions = location.sessions_dir
key = "websocket:legacy-acceptance"
legacy = sessions / (location.storage_key(key) + ".jsonl")
legacy.write_text(json.dumps({"_type": "metadata", "key": key, "metadata": {"title": "升级前的聊天"},
"created_at": "2026-01-01T00:00:00", "updated_at": "2026-01-01T00:00:00"}) + "\n" +
json.dumps({"role": "user", "content": "配置和聊天不能丢失"}, ensure_ascii=False) + "\n", encoding="utf-8")
canonical_only = sessions / (location.storage_key("websocket:canonical-only") + ".jsonl")
canonical_only.write_bytes(legacy.read_bytes().replace(key.encode(), b"websocket:canonical-only"))
webui_dir = get_webui_dir()
webui_dir.mkdir(parents=True, exist_ok=True)
for chat_id in ("legacy-acceptance", "display-only"):
events = [{"event": "user", "chat_id": chat_id, "text": "配置和聊天不能丢失"},
{"event": "message", "chat_id": chat_id, "text": "独立验收数据"},
{"event": "turn_end", "chat_id": chat_id}]
(webui_dir / f"websocket_{chat_id}.jsonl").write_text(
"".join(json.dumps(event, ensure_ascii=False) + "\n" for event in events), encoding="utf-8")
if _dock_supported(root):
_desktop_webui(root)
_wait_dock(_dock_socket(root), present=True)
@@ -418,36 +455,56 @@ def seed(root: Path) -> None:
def snapshot(root: Path) -> None:
from nanobot.config.loader import load_config, set_config_path
from nanobot.session.location import SessionLocation
from nanobot.config.loader import set_config_path
from nanobot.config.paths import get_webui_dir
case = read(root / "case.json")
config_path = root / "account/.nanobot/config.json"
set_config_path(config_path)
config = load_config(config_path)
assert config.network.proxy == "http://127.0.0.1:9" and config.providers.custom.use_proxy
delivery = config_path.parent / "delivery/outbox.sqlite3"
sessions = SessionLocation(root / "workspace").sessions_dir
key = "websocket:mixed-history"
if not delivery.exists() and importlib.util.find_spec("nanobot.channels.outbox") is not None:
from nanobot.bus.delivery import DeliveryRequest
from nanobot.bus.events import OutboundMessage
from nanobot.channels.outbox import DeliveryOutbox
# Keep a real durable result pending through the private journey without
# attempting an external send. Older retained code has no outbox owner.
with patch("nanobot.channels.outbox.time.time", return_value=time.time() + 3600):
DeliveryOutbox(delivery).record(OutboundMessage(
"whatsapp", "acceptance-offline", "Retain this scheduled result",
delivery=DeliveryRequest("acceptance-run", "websocket:legacy-acceptance", None),
))
if importlib.util.find_spec("nanobot.session.location") is not None:
from nanobot.session.location import SessionLocation
location = SessionLocation(root / "workspace")
else:
from nanobot.session.manager import JsonlSessionStore
location = JsonlSessionStore(root / "workspace")
sessions, webui_dir = location.sessions_dir, get_webui_dir()
key = "websocket:legacy-acceptance"
legacy = sessions / (location.storage_key(key) + ".jsonl")
canonical_only = sessions / (location.storage_key("websocket:canonical-only") + ".jsonl")
receipt = ready(root, case["baseline_version"])
chat_id = (read(root / "before.json")["chat_id"] if (root / "before.json").exists()
else asyncio.run(chat(root)))
before = history(root, "websocket:" + chat_id)
mixed_before = history(root, key)
legacy_before = history(root, key)
display_before = history(root, "websocket:display-only")
context_before = canonical_context(root)
assert context_before["total_messages"] == 1
assert "配置和聊天不能丢失" in json.dumps(mixed_before, ensure_ascii=False)
assert "独立验收数据" in json.dumps(mixed_before, ensure_ascii=False)
assert "独立验收数据" in json.dumps(display_before, ensure_ascii=False)
delivery_before = canonical_records(delivery, ("deliveries",))
assert any(row[1] == "acceptance-run" and row[5] == "pending" for row in delivery_before["deliveries"])
# SQLite/WAL bytes may change on shutdown; compare their logical records.
write(root / "before.json", {"chat_id": chat_id, "history": before, "mixed": mixed_before,
assert "配置和聊天不能丢失" in json.dumps(legacy_before, ensure_ascii=False)
# Immutable files plus public logical records: SQLite/WAL checkpoint bytes
# may legitimately change across a clean shutdown without changing a record.
preserved = {str(path): digest(path) for path in (legacy, canonical_only,
webui_dir / "websocket_legacy-acceptance.jsonl", webui_dir / "websocket_display-only.jsonl")}
preserved[str(config_path)] = digest(config_path)
write(root / "before.json", {"chat_id": chat_id, "history": before, "legacy": legacy_before,
"display_only": display_before, "canonical_only": context_before,
"files": {str(config_path): digest(config_path)}, "run_id": receipt.run_id,
"database": str(sessions / "sessions.sqlite3"), "delivery": delivery_before,
"canonical": canonical_records(sessions / "sessions.sqlite3")})
"files": preserved, "run_id": receipt.run_id,
"database": str(sessions / "sessions.sqlite3"),
"delivery": (canonical_records(delivery, ("deliveries",)) if delivery.exists() else None),
"canonical": (canonical_records(sessions / "sessions.sqlite3")
if (sessions / "sessions.sqlite3").exists() else None)})
def prepare(root: Path) -> None:
@@ -502,7 +559,7 @@ def verify(root: Path) -> dict:
if not restored:
assert COMMIT == case["commit"]
assert digest(Path(case["target_wheel"])) == case["target_sha256"]
verify_data(root, expected)
sqlite_expected = verify_data(root, expected)
if case["scenario"] in {"worker-exit", "metadata-loss"}:
assert (directory / "fault-fired").exists()
if case["scenario"] in {"worker-exit", "metadata-loss", "backup-failure"}:
@@ -510,22 +567,19 @@ def verify(root: Path) -> dict:
if case["scenario"] == "restore-interruption":
assert (directory / "restore-fault-fired").exists()
return {**case, "phase": status.phase.value, "running_version": receipt.version,
"history_fixture": "native-sqlite", "config_bytes_preserved": True,
"restarted": True, "authenticated_history_preserved": True, "sqlite_records_preserved": True,
"scheduled_delivery_preserved": True,
"restarted": True, "config_and_legacy_bytes_preserved": True,
"authenticated_history_preserved": True, "sqlite_records_preserved": True if sqlite_expected else None,
"scheduled_delivery_preserved": True if before.get("delivery") is not None else None,
"continued_write_and_second_start": True,
"dock_socket": str(_dock_socket(root)) if _dock_supported(root) else None,
"dock_restart_verified": True if _dock_supported(root) else None}
def verify_data(root: Path, expected: str) -> None:
def verify_data(root: Path, expected: str) -> bool:
"""Public reads and subsequent writes, shared by inline and owner-driven updates."""
from nanobot.config.loader import load_config, set_config_path
from nanobot.config.loader import set_config_path
config_path = root / "account/.nanobot/config.json"
set_config_path(config_path)
config = load_config(config_path)
assert config.network.proxy == "http://127.0.0.1:9" and config.providers.custom.use_proxy
set_config_path(root / "account/.nanobot/config.json")
before = read(root / "before.json")
receipt = ready(root, expected)
assert receipt.run_id != before["run_id"], "Update did not restart the gateway"
@@ -538,23 +592,29 @@ def verify_data(root: Path, expected: str) -> None:
_wait_dock(_dock_socket(root), present=True)
assert {name: digest(Path(name)) for name in before["files"]} == before["files"]
key = "websocket:" + before["chat_id"]
assert history(root, key) == before["history"]
assert history(root, "websocket:mixed-history") == before["mixed"]
assert history(root, "websocket:display-only") == before["display_only"]
assert canonical_context(root) == before["canonical_only"]
assert_history_preserved(before["history"], history(root, key))
assert_history_preserved(before["legacy"], history(root, "websocket:legacy-acceptance"))
assert_history_preserved(before["display_only"], history(root, "websocket:display-only"))
assert canonical_context(root) == before["canonical_only"], (canonical_context(root), before["canonical_only"])
database = Path(before["database"])
canonical = canonical_records(database)
assert canonical == before["canonical"]
sqlite_expected = importlib.util.find_spec("nanobot.session.location") is not None
canonical = canonical_records(database) if sqlite_expected else None
if before["canonical"] is not None:
assert_canonical_preserved(before["canonical"], canonical)
delivery = root / "account/.nanobot/delivery/outbox.sqlite3"
assert canonical_records(delivery, ("deliveries",)) == before["delivery"]
assert not any(row[0] == "websocket:display-only" for row in canonical["messages"])
for session_key in ("websocket:mixed-history", "websocket:canonical-only"):
messages = [json.loads(row[2]) for row in canonical["messages"] if row[0] == session_key]
assert [(message["role"], message["content"]) for message in messages] == [
("user", "配置和聊天不能丢失")]
if before.get("delivery") is not None:
assert canonical_records(delivery, ("deliveries",)) == before["delivery"]
if canonical is not None:
# Display transcripts are not canonical agent context. Check the actual
# imported message bodies too when the baseline predates SQLite.
assert not any(row[0] == "websocket:display-only" for row in canonical["messages"])
for session_key in ("websocket:legacy-acceptance", "websocket:canonical-only"):
messages = [json.loads(row[2]) for row in canonical["messages"] if row[0] == session_key]
assert [(message["role"], message["content"]) for message in messages] == [
("user", "配置和聊天不能丢失")]
asyncio.run(chat(root, before["chat_id"]))
continued = history(root, key)
canonical = canonical_records(database)
canonical = canonical_records(database) if sqlite_expected else None
assert len(continued["events"]) > len(before["history"]["events"])
gateway(root, "stop")
if _dock_supported(root):
@@ -564,12 +624,15 @@ def verify_data(root: Path, expected: str) -> None:
if _dock_supported(root):
_wait_dock(_dock_socket(root), present=True)
assert history(root, key) == continued
assert history(root, "websocket:mixed-history") == before["mixed"]
assert history(root, "websocket:display-only") == before["display_only"]
assert_history_preserved(before["legacy"], history(root, "websocket:legacy-acceptance"))
assert_history_preserved(before["display_only"], history(root, "websocket:display-only"))
assert canonical_context(root) == before["canonical_only"]
assert canonical_records(database) == canonical
assert canonical_records(delivery, ("deliveries",)) == before["delivery"]
if sqlite_expected:
assert canonical_records(database) == canonical
if before.get("delivery") is not None:
assert canonical_records(delivery, ("deliveries",)) == before["delivery"]
assert {name: digest(Path(name)) for name in before["files"]} == before["files"]
return sqlite_expected
def isolated_environment(root: Path) -> dict[str, str]: