refactor: remove legacy history and proxy migrations (#6518)

This commit is contained in:
chengyongru authored and GitHub committed 2026-10-29 18:28:44 +08:00
1 parent 1c28b20c7e
commit cb3ba45317
47 files changed
+207 -1925

No files matched your search

+1 -1
View File
@@ -498,7 +498,7 @@ jobs:
- name: Check out the real previous release for retained-volume acceptance
uses: actions/checkout@v4
with:
ref: 1bb712d3488915ca4ed9ccc1a93067ff722f5ab9 # v0.3.5
ref: 8f7a7d17590de7ab187650381894dba2b9e060ab # v0.4.0
path: .docker-baseline
persist-credentials: false
-1
View File
@@ -62,7 +62,6 @@ def _isolate_runtime_stores(
return path
monkeypatch.setattr(session_location, "get_runtime_subdir", runtime_subdir)
monkeypatch.setattr("nanobot.webui.history.get_webui_dir", lambda: runtime_subdir("webui"))
monkeypatch.setattr(star_prompt, "get_webui_dir", lambda: runtime_subdir("webui"))
monkeypatch.setattr(pairing_store, "_store_path", lambda: data_dir() / "pairing.json")
monkeypatch.setattr(llm_usage, "get_data_dir", data_dir)
+1 -3
View File
@@ -185,9 +185,7 @@ Session history is the near-term conversation replay. Memory is the longer-term
Every append carries the generation admitted before execution, including a distinct display destination under unified-session routing. A missing or replaced session rejects the append instead of creating a new row. Delete/reset cascades through both logical histories; fork copies its canonical and display prefixes in one SQLite transaction. Future in-place history replacement should use that same owner transaction rather than file journals or replay-cache writes.
`nanobot/webui/history.py` resolves legacy `<stem>.jsonl` files and numbered JSONL files inside `<stem>.segments/` directories, then imports them through `SessionState` before recovery or transport admission. Recorded chat identities determine the target session; histories without a recorded identity require an unambiguous existing canonical session. Display-only histories with a recorded identity are imported into the starting workspace namespace. Histories owned by exactly one other namespace are deferred to that namespace; duplicate owners and malformed records fail startup.
`SqliteSessionStore.migrate_history()` commits the imported facts and completion markers in one transaction. Per-session ownership receipts in `storage_meta` survive session deletion, so another namespace cannot restore deleted chats by reimporting the unchanged legacy backups.
SQLite schema upgrades preserve the stored model and display histories.
| Store | File area |
|---|---|
+2 -8
View File
@@ -135,15 +135,9 @@ Inside the native TUI, `/sessions` switches saved conversations, `/new-chat` sta
## Session Storage
Session state lives in `<config-dir>/sessions/<workspace-id>/sessions.sqlite3`, outside the agent-readable workspace. Existing JSONL conversations are imported on the first startup. JSONL migration is available from 0.3.6 through 0.4.x and is removed in **0.5.0**; installations with only JSONL data must upgrade through that window before using 0.5.0.
Model and WebUI chat history live in `<config-dir>/sessions/<workspace-id>/sessions.sqlite3`, outside the agent-readable workspace. The `webui` directory contains sidebar preferences and other saved WebUI state.
After a successful import, JSONL files and their checkpoints from `<workspace>/sessions/` move to `<config-dir>/sessions/<workspace-id>/jsonl-backup/`, preserving their contents outside the agent-readable workspace. JSONL files already in the private session directory remain there. An interrupted migration resumes on startup before nanobot serves conversations; failed imports leave their source files unchanged.
WebUI chat history is saved in the same session database. The gateway automatically imports old `<config-dir>/webui/*.jsonl` files and numbered JSONL files inside `<config-dir>/webui/*.segments/` directories. If old history is damaged or cannot be matched to one conversation, startup stops with an error; resolve the reported problem before restarting.
The old WebUI history files remain unchanged as backups. Imported chats deleted after the upgrade stay deleted on restart. Keep the `webui` directory: it still contains sidebar preferences and other saved WebUI state.
Before changing versions, stop all nanobot instances using the same config directory and back up that entire directory and the workspace together. Copying only `sessions.sqlite3` while nanobot is running can miss recent messages. To downgrade, restore a complete pre-upgrade backup compatible with the older release. Older releases cannot read newly saved WebUI history; do not combine the current session database with old WebUI history files.
Before changing versions, stop all nanobot instances using the same config directory and back up that entire directory and the workspace together. Copying only `sessions.sqlite3` while nanobot is running can miss recent messages. To downgrade, restore a complete pre-upgrade backup compatible with the older release.
Interactive mode uses nanobot's native TypeScript terminal UI. It talks to the same local gateway as the WebUI, so streaming, tool progress, and WebSocket sessions share one protocol instead of maintaining a second agent loop. If no gateway is running, either client starts it on demand. The TUI paints immediately while the local gateway starts, then obtains fresh bootstrap credentials and connects in the background. Exiting one TUI or WebUI launcher releases only that client; the last interactive launcher stops the on-demand gateway. A small gateway watchdog also reclaims an on-demand process if its last client crashes. `/detach` promotes the shared gateway to persistent background mode before closing the TUI, so active agent work continues without a connected client. An explicit `nanobot gateway --background` starts or promotes the gateway the same way before opening a client. `nanobot gateway restart` restarts a detached gateway without changing that lifetime; restart an attached foreground gateway in its owning terminal. `nanobot gateway stop` ends either mode.
-2
View File
@@ -102,8 +102,6 @@ HTTP, HTTPS, SOCKS5, and SOCKS5H URLs are accepted; individual integrations reta
</details>
On upgrade, one legacy proxy address moves to `network.proxy` and previously configured features receive `useProxy: true`. The migrated configuration is written on the next normal save, including `nanobot onboard --refresh`. If the old configuration contains different proxy addresses, choose one and set `network.proxy` explicitly before upgrading; multiple per-feature addresses are no longer supported. For Discord configurations that store the entire proxy URL in an environment variable and credentials separately, combine them into one full URL environment variable and set `network.proxy` to that reference before upgrading. Credential references inside a URL remain references when saved. Back up the original configuration before saving if you may need to downgrade.
## Environment Variables for Secrets
Instead of storing secrets directly in `config.json`, you can use `${VAR_NAME}` references that are resolved from environment variables at startup:
+3 -3
View File
@@ -46,13 +46,13 @@ The gateway now owns model history and WebUI display history in SQLite. Existing
### Data and configuration compatibility
JSONL import remains supported throughout 0.4.x. Installations with only legacy JSONL data must pass through an import-capable release before 0.5.0. Imported source files are retained as backups; do not delete the old WebUI directory, which also holds preferences. A corrupt or ambiguous import stops startup with an actionable error instead of silently skipping history. See [Session Storage](../cli-reference.md#session-storage).
v0.4.0 imports legacy JSONL history and retains the source files as backups. Do not delete the old WebUI directory, which also holds preferences. A corrupt or ambiguous import stops startup with an actionable error instead of silently skipping history. See [Session Storage](../cli-reference.md#session-storage).
Older versions cannot read newly saved SQLite display history. A downgrade is not an in-place recovery shortcut: stop all writers and follow the documented pre-upgrade-backup restoration procedure, explicitly accounting for newer messages that the old backup does not contain. The managed updater never performs this data rollback automatically.
Legacy proxy configuration migration remains supported in 0.4.x. Review the migrated shared proxy and per-service choices before saving; a browser's proxy settings are separate from the gateway's. See [Configuration](../configuration.md).
v0.4.0 migrates legacy proxy configuration. Review the migrated shared proxy and per-service choices before saving; a browser's proxy settings are separate from the gateway's. See [Configuration](../configuration.md).
v0.4.0 is the first stable release with the temporary OpenAI `apiType` / `api_type` → `api` migration. It remains supported for the immediately following release; its exact tag must be recorded when that release is allocated. Save configurations in the current `api` format during this window. The third release containing this change will no longer accept the old selector. This is a separate compatibility window from the 0.4.x JSONL/proxy window. See [API selector migration](../configuration.md#legacy-openai-api-selector-migration).
v0.4.0 is the first stable release with the temporary OpenAI `apiType` / `api_type` → `api` migration. It remains supported for the immediately following release; its exact tag must be recorded when that release is allocated. Save configurations in the current `api` format during this window. The third release containing this change will no longer accept the old selector. See [API selector migration](../configuration.md#legacy-openai-api-selector-migration).
### Installation and platform boundaries
+2 -2
View File
@@ -178,9 +178,9 @@ On a local macOS desktop, add `--dock` to verify the real AppKit helper alongsid
Require normal and consecutive upgrades, skipped Preview, import/startup failure, backup failure after shutdown, worker termination, partial metadata loss and interruption between program-restoration renames. Each successful journey must show the expected version in a new gateway run, a retained verified backup, authenticated history reads, continued writes and a second ordinary start. Each recovered service must then update to the healthy target with the same account/conversations. Faults affect the first job; backup failure must survive its automatic retry, while a separately confirmed next update can make a healthy backup. The instrumented intermediate Preview's second hop installs the unchanged final wheel.
Compare configuration, retained legacy-source bytes, canonical SQLite records, WebUI transcripts and pending `delivery/outbox.sqlite3` records separately. Cover canonical-only, display-only and mixed history without inventing canonical records for display-only chats; SQLite checkpoint byte changes alone are not data loss. Retain the protocol-1 parked-gateway regression across old/new protected-store inventories: no outbox initialization, migration or writes outside the old grant before activation. See the [update protocol](./update-protocol.md) for scope and lease requirements.
Compare configuration, canonical SQLite records, WebUI transcripts and pending `delivery/outbox.sqlite3` records separately. Cover canonical-only, display-only and mixed history without inventing canonical records for display-only chats; SQLite checkpoint byte changes alone are not data loss. Retain the protocol-1 parked-gateway regression across old/new protected-store inventories: no outbox initialization, migration or writes outside the old grant before activation. See the [update protocol](./update-protocol.md) for scope and lease requirements.
Default baselines are labelled target-derived fixtures, not historical compatibility evidence. For release acceptance, add `--baseline-wheel <previously-accepted-wheel>` and repeat with supported stable and older Preview packages, including skipped Preview. Baseline feed transport is instrumented; the healthy target is unchanged. Include a retained pre-SQLite updater to check JSONL migration's canonical message bodies separately from display history. If recovery restores JSONL code, mark SQLite checks not applicable, not passed. Packages without this updater need separately recorded installation-owner bootstrap acceptance.
Default baselines are labelled target-derived fixtures, not historical compatibility evidence. For release acceptance, add `--baseline-wheel <previously-accepted-wheel>` and repeat with supported stable and older Preview packages, including skipped Preview. Baselines must support SQLite session history, shared proxy configuration and the durable delivery outbox. Baseline feed transport is instrumented; the healthy target is unchanged. Compare canonical message bodies separately from display history. Packages without this updater need separately recorded installation-owner bootstrap acceptance.
Exercise consecutive updates in the same disposable account with existing conversations through each applicable owner: official installer, uv tool, pipx, ordinary pip venv and source. Check recorded constraints/options before/after, execute the offered command, verify the restarted gateway, append a message and start again. Policy refusal must leave installation unchanged; custom owner-reviewed updates do not prove automatic recovery. Container replacement requires a real engine and retained data volumes, not a mocked marker.
-1
View File
@@ -653,7 +653,6 @@ class WebSocketChannel(BaseChannel):
)
async def start(self) -> None:
await self._outbound.initialize()
self.gateway.http.remote_instances.resume()
from nanobot.utils.logging_bridge import redirect_lib_logging
-3
View File
@@ -12,7 +12,6 @@ if TYPE_CHECKING:
get_cli_history_path,
get_cron_dir,
get_data_dir,
get_legacy_sessions_dir,
get_logs_dir,
get_media_dir,
get_runtime_subdir,
@@ -38,7 +37,6 @@ _EXPORTS = {
"get_workspace_path": "nanobot.config.paths",
"is_default_workspace": "nanobot.config.paths",
"get_cli_history_path": "nanobot.config.paths",
"get_legacy_sessions_dir": "nanobot.config.paths",
}
@@ -70,5 +68,4 @@ __all__ = [
"get_workspace_path",
"is_default_workspace",
"get_cli_history_path",
"get_legacy_sessions_dir",
]
-58
View File
@@ -2,11 +2,9 @@
import os
import re
from typing import Any, cast
from urllib.parse import quote, urlsplit
from pydantic import Field, field_validator
from pydantic_core import PydanticCustomError
from nanobot.config_base import Base
@@ -70,59 +68,3 @@ class NetworkConfig(Base):
if not proxy:
raise ValueError("Configure the shared proxy in Advanced before enabling it")
return proxy
def _config_object(value: object) -> dict[str, Any] | None:
return cast(dict[str, Any], value) if isinstance(value, dict) else None
def migrate_legacy_proxy_config(value: Any) -> Any:
"""Consolidate legacy addresses after settings sources have been merged."""
if not isinstance(value, dict):
return value
data = cast(dict[str, Any], value)
sections: list[dict[str, Any]] = []
providers = _config_object(data.get("providers")) or {}
sections.extend(section for value in providers.values() if (section := _config_object(value)) is not None)
tools = _config_object(data.get("tools")) or {}
if (web := _config_object(tools.get("web"))) is not None:
sections.append(web)
channels = _config_object(data.get("channels")) or {}
sections.extend(section for name in ("telegram", "discord", "slack", "matrix", "whatsapp") if (section := _config_object(channels.get(name))) is not None)
network = data.get("network")
explicit_proxy = isinstance(network, NetworkConfig) or isinstance(network, dict) and "proxy" in network
addresses: set[str] = set()
migrated: list[dict[str, Any]] = []
for section in sections:
raw = section.get("proxy")
if isinstance(raw, str) and raw.strip():
if not explicit_proxy:
proxy = NetworkConfig.normalize_proxy(raw)
assert proxy is not None
username = section.get("proxyUsername", section.get("proxy_username"))
password = section.get("proxyPassword", section.get("proxy_password"))
if isinstance(username, str) and username and isinstance(password, str) and password:
if _ENV_REF_PATTERN.fullmatch(proxy):
raise PydanticCustomError("proxy_credential_migration", "Combine the Discord proxy URL and credentials into one full URL environment variable, or set network.proxy before upgrading.")
scheme, host = proxy.split("://", 1)
host = host.rsplit("@", 1)[-1]
credentials = f"{quote(username, safe='${}')}:{quote(password, safe='${}')}"
proxy = f"{scheme}://{credentials}@{host}"
addresses.add(proxy)
migrated.append(section)
if addresses:
if len(addresses) > 1:
raise PydanticCustomError("proxy_address_migration", "Multiple legacy proxy addresses are no longer supported. Set network.proxy to one address before upgrading.")
if not isinstance(network, dict):
network = {}
data["network"] = network
network["proxy"] = next(iter(addresses))
for section in sections:
for key in ("proxy", "proxyUsername", "proxy_username", "proxyPassword", "proxy_password"):
section.pop(key, None)
for section in migrated:
if "useProxy" not in section and "use_proxy" not in section:
section["useProxy"] = True
return data
+1 -6
View File
@@ -45,7 +45,7 @@ def get_logs_dir() -> Path:
def get_webui_dir() -> Path:
"""Return WebUI state and legacy display-history import/backup storage."""
"""Return the WebUI state directory."""
return get_runtime_subdir("webui")
@@ -65,8 +65,3 @@ def is_default_workspace(workspace: str | Path | None) -> bool:
def get_cli_history_path() -> Path:
"""Return the selected home's CLI history file path."""
return get_home_path() / "history" / "cli_history"
def get_legacy_sessions_dir() -> Path:
"""Return the selected home's legacy session directory for migration fallback."""
return get_home_path() / "sessions"
+1 -6
View File
@@ -21,7 +21,7 @@ from nanobot.agent.tools.web_config import (
)
from nanobot.agent.tools.web_config import WebToolsConfig
from nanobot.config.home import get_default_workspace
from nanobot.config.network import NetworkConfig, migrate_legacy_proxy_config
from nanobot.config.network import NetworkConfig
from nanobot.config.provider_api_migration import migrate_legacy_provider_api
from nanobot.config.timezone import detect_system_timezone
from nanobot.config_base import Base
@@ -517,11 +517,6 @@ class Config(BaseSettings):
serialization_alias="modelPresets",
)
@model_validator(mode="before")
@classmethod
def _migrate_proxy_config(cls, value: Any) -> Any:
return migrate_legacy_proxy_config(value)
@classmethod
def settings_customise_sources(
cls,
-8
View File
@@ -59,14 +59,6 @@ class HistoryFact:
)
@dataclass(frozen=True)
class HistoryImport:
key: str
facts: list[HistoryFact]
created_at_ms: int = 0
updated_at_ms: int = 0
@dataclass(frozen=True)
class HistoryTurn:
ordinal: int
-291
View File
@@ -1,291 +0,0 @@
"""One-time JSONL import, introduced in 0.3.6 and removed in 0.5.0.
0.4.x is the final migration release line. Older installations must pass through
that line before upgrading to 0.5.0. Workspace sources move to private backups
after the import commits; failed imports leave their source files unchanged.
"""
from __future__ import annotations
import hashlib
import json
import os
import secrets
import stat
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any, TypedDict, cast
from loguru import logger
from nanobot.providers.base import ProviderConversationState
from nanobot.session.location import SessionLocation
from nanobot.session.manager import Session
if TYPE_CHECKING:
from nanobot.session.sqlite_store import SqliteSessionStore
INTRODUCED_VERSION = "0.3.6"
LAST_SUPPORTED_RELEASE_LINE = "0.4.x"
SUNSET_VERSION = "0.5.0"
WORKSPACE_BACKUP_DIR = "jsonl-backup"
_WORKSPACE_SOURCES_KEY = "jsonl_workspace_sources"
class _WorkspaceSource(TypedDict):
name: str
digest: str
def _file_identity(value: os.stat_result) -> tuple[int, int, int, int]:
return value.st_dev, value.st_ino, value.st_size, value.st_mtime_ns
@dataclass(frozen=True)
class _LegacyFile:
path: Path
content: bytes
stat: os.stat_result
@property
def digest(self) -> str:
return hashlib.sha256(self.content).hexdigest()
def _read_file(path: Path) -> _LegacyFile:
if not stat.S_ISREG(path.lstat().st_mode):
raise ValueError(f"JSONL migration requires a regular file: {path}")
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
with os.fdopen(os.open(path, flags), "rb") as handle:
before = os.fstat(handle.fileno())
if not stat.S_ISREG(before.st_mode):
raise ValueError(f"JSONL migration requires a regular file: {path}")
content = handle.read()
after = os.fstat(handle.fileno())
if _file_identity(before) != _file_identity(after):
raise ValueError(f"JSONL migration source changed while reading: {path}")
return _LegacyFile(path, content, after)
def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
value: dict[str, Any] = {}
for key, item in pairs:
if key in value:
raise ValueError(f"duplicate JSON key: {key!r}")
value[key] = item
return value
def _record(line: str) -> dict[str, Any]:
value: object = json.loads(line, object_pairs_hook=_unique_object)
if not isinstance(value, dict):
raise ValueError("JSONL records must be objects")
return cast(dict[str, Any], value)
def read_jsonl(path: Path) -> tuple[Session, list[_LegacyFile]]:
"""Read a complete legacy session, failing without modifying malformed input."""
source = _read_file(path)
files = [source]
header: dict[str, Any] | None = None
messages: list[dict[str, Any]] = []
provider: ProviderConversationState | None = None
provider_seen = False
# Unicode line separators are valid inside legacy JSON strings.
for line in source.content.decode("utf-8").split("\n"):
if not line.strip():
continue
item = _record(line)
if item.get("_type") == "metadata":
if header is not None:
raise ValueError(f"multiple session headers: {path}")
header = item
elif item.get("_type") == "provider_state":
if provider_seen:
raise ValueError(f"multiple provider state records: {path}")
provider_seen = True
provider = ProviderConversationState.from_private_record(item.get("state"))
if provider is None:
raise ValueError(f"invalid private provider state: {path}")
else:
if not isinstance(item.get("role"), str):
raise ValueError(f"invalid session message: {path}")
messages.append(item)
if header is None:
raise ValueError(f"missing session header: {path}")
key = header.get("key") or SessionLocation.session_key_from_path(path)
if not isinstance(key, str) or not key:
raise ValueError(f"cannot determine session key: {path}")
metadata: object = header.get("metadata")
if metadata is None:
metadata = {}
if not isinstance(metadata, dict):
raise ValueError(f"invalid session metadata: {path}")
fallback = datetime.fromtimestamp(source.stat.st_mtime).isoformat()
session = Session(
key=key, messages=messages, metadata=cast(dict[str, Any], metadata),
created_at=datetime.fromisoformat(header.get("created_at") or fallback),
updated_at=datetime.fromisoformat(header.get("updated_at") or fallback),
last_consolidated=header.get("last_archived", header.get("last_consolidated", 0)),
provider_state=provider,
)
checkpoint_path = path.with_suffix(".checkpoint.json")
if checkpoint_path.exists() or checkpoint_path.is_symlink():
checkpoint_source = _read_file(checkpoint_path)
files.append(checkpoint_source)
checkpoint = _record(checkpoint_source.content.decode("utf-8"))
if (
checkpoint_source.stat.st_mtime_ns >= source.stat.st_mtime_ns
and checkpoint.get("version") == 1
and checkpoint.get("session_key") == key
and checkpoint.get("base_updated_at") == session.updated_at.isoformat()
and checkpoint.get("base_message_count") == len(messages)
):
if not isinstance(checkpoint.get("checkpoint"), dict):
raise ValueError(f"invalid checkpoint: {checkpoint_path}")
session.metadata["runtime_checkpoint"] = checkpoint["checkpoint"]
raw_provider = checkpoint.get("provider_state")
session.provider_state = ProviderConversationState.from_private_record(raw_provider)
if raw_provider is not None and session.provider_state is None:
raise ValueError(f"invalid checkpoint provider state: {checkpoint_path}")
return session, files
def migrate_jsonl(store: SqliteSessionStore, workspace: Path) -> int:
"""Import atomically, then let the caller commit the durable completion marker.
A malformed or conflicting source aborts the whole import. The committed
workspace-source manifest lets startup finish isolation after a crash.
"""
imported: dict[str, tuple[Path, tuple[str, ...]]] = {}
workspace_sources: list[_WorkspaceSource] = []
workspace_directory = workspace / "sessions"
for directory in (store.path.parent, workspace_directory):
if directory.is_symlink():
raise ValueError(f"migration source must not be a symlink: {directory}")
for path in sorted(directory.glob("*.jsonl")):
try:
session, files = read_jsonl(path)
digests = tuple(source.digest for source in files)
prior = imported.get(session.key)
if prior is not None:
prior_path, prior_digests = prior
if prior_digests != digests or store.load(session.key) != session:
raise ValueError(f"duplicate JSONL session key: {prior_path} and {path}")
else:
if store.load(session.key) is not None:
raise ValueError(f"session already exists in SQLite: {session.key}")
store.save(session)
imported[session.key] = path, digests
if directory == workspace_directory:
workspace_sources.extend(
{"name": source.path.name, "digest": source.digest} for source in files
)
except Exception as exc:
raise RuntimeError(
f"JSONL migration failed for {path}; source files are unchanged. "
"Resolve the invalid or conflicting file and restart."
) from exc
if workspace_sources:
with store.transaction() as db:
db.execute("INSERT INTO storage_meta (key, value) VALUES (?, ?)", (
_WORKSPACE_SOURCES_KEY, json.dumps(workspace_sources),
))
if imported:
logger.info("Imported {} JSONL sessions into {}", len(imported), store.path)
return len(imported)
def _workspace_sources(raw: str) -> list[_WorkspaceSource]:
value: object = json.loads(raw)
if not isinstance(value, list):
raise ValueError("workspace migration manifest must be a list")
sources: list[_WorkspaceSource] = []
for item in cast(list[object], value):
if not isinstance(item, dict):
raise ValueError("workspace migration source must be an object")
record = cast(dict[str, object], item)
name, digest = record.get("name"), record.get("digest")
if (
not isinstance(name, str) or Path(name).name != name
or not name.endswith((".jsonl", ".checkpoint.json"))
or not isinstance(digest, str) or len(digest) != 64
or any(char not in "0123456789abcdef" for char in digest)
):
raise ValueError("invalid workspace migration source")
sources.append({"name": name, "digest": digest})
return sources
def _write_backup(path: Path, source: _LegacyFile) -> None:
temporary = path.with_name(f".{path.name}.{secrets.token_hex(8)}.tmp")
try:
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
with os.fdopen(os.open(temporary, flags, 0o600), "wb") as handle:
handle.write(source.content)
handle.flush()
os.utime(temporary, ns=(source.stat.st_atime_ns, source.stat.st_mtime_ns))
os.fsync(handle.fileno())
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
def finish_workspace_migration(store: SqliteSessionStore, workspace: Path) -> None:
"""Durably back up every workspace source before removing any of them.
The import and its manifest commit together. Cleanup holds the startup write
lock and clears the manifest only after both backup and removal are durable.
"""
source_directory = workspace / "sessions"
backup_directory = store.path.parent / WORKSPACE_BACKUP_DIR
with store.transaction() as db:
pending = db.execute(
"SELECT value FROM storage_meta WHERE key=?", (_WORKSPACE_SOURCES_KEY,),
).fetchone()
if pending is None:
return
try:
sources = _workspace_sources(pending[0])
if source_directory.is_symlink() or backup_directory.is_symlink():
raise ValueError("workspace migration directories must not be symlinks")
backup_directory.mkdir(mode=0o700, exist_ok=True)
SessionLocation.fsync_directory(backup_directory.parent)
prepared: list[tuple[Path, os.stat_result]] = []
for record in sources:
source_path = source_directory / record["name"]
backup_path = backup_directory / record["name"]
source: _LegacyFile | None = None
try:
source = _read_file(source_path)
except FileNotFoundError:
pass
if source is not None:
if source.digest != record["digest"]:
raise ValueError(f"workspace migration source changed: {source_path}")
prepared.append((source_path, source.stat))
try:
backup = _read_file(backup_path)
except FileNotFoundError:
if source is None:
raise ValueError(f"workspace migration source and backup are missing: {source_path}") from None
_write_backup(backup_path, source)
else:
if backup.digest != record["digest"]:
raise ValueError(f"workspace migration backup differs from its source: {backup_path}")
SessionLocation.fsync_directory(backup_directory)
for path, expected in prepared:
actual = path.lstat()
if not stat.S_ISREG(actual.st_mode) or _file_identity(actual) != _file_identity(expected):
raise ValueError(f"workspace migration source changed: {path}")
for path, _expected in prepared:
path.unlink()
if source_directory.exists():
SessionLocation.fsync_directory(source_directory)
db.execute("DELETE FROM storage_meta WHERE key=?", (_WORKSPACE_SOURCES_KEY,))
except Exception as exc:
raise RuntimeError(
f"Could not move legacy sessions out of {source_directory}; "
f"backups are in {backup_directory}. Resolve the file error and restart."
) from exc
+1 -30
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
import base64
import errno
import os
import re
@@ -13,10 +12,7 @@ from pathlib import Path
from filelock import FileLock
from nanobot.config.paths import get_runtime_subdir
from nanobot.utils.helpers import (
ensure_dir,
safe_filename,
)
from nanobot.utils.helpers import ensure_dir
_WORKSPACE_STATE_DIR = ".nanobot"
_WORKSPACE_ID_FILE = "workspace-id"
@@ -225,28 +221,3 @@ class SessionLocation:
cls._replace_workspace_id(workspace, workspace_id)
raise RuntimeError(f"could not allocate an isolated session namespace for {workspace}")
@staticmethod
def safe_key(key: str) -> str:
return safe_filename(key.replace(":", "_"))
@staticmethod
def storage_key(key: str) -> str:
return base64.urlsafe_b64encode(key.encode()).decode().rstrip("=")
@staticmethod
def decode_storage_key(stem: str) -> str | None:
try:
padding = 4 - len(stem) % 4
if padding != 4:
stem += "=" * padding
return base64.urlsafe_b64decode(stem).decode("utf-8")
except (ValueError, TypeError, AttributeError, KeyError):
return None
@classmethod
def session_key_from_path(cls, path: Path) -> str | None:
key = cls.decode_storage_key(path.stem)
if key is None or cls.storage_key(key) != path.stem:
return None
return key
+1 -21
View File
@@ -433,7 +433,7 @@ class SessionManager:
self.location = SessionLocation(workspace, sessions_root=sessions_root)
self.sessions_dir = self.location.sessions_dir
self._store = SqliteSessionStore(self.sessions_dir)
self._store.initialize(workspace)
self._store.initialize()
self._delete_observer: Callable[[str], None] | None = None
self.types = SessionTypes()
self._state: SessionState | None = None
@@ -462,26 +462,6 @@ class SessionManager:
"""Observe explicit session deletion for process-local state cleanup."""
self._delete_observer = observer
@staticmethod
def safe_key(key: str) -> str:
"""Public helper used by HTTP handlers to map an arbitrary key to a stable filename stem."""
return SessionLocation.safe_key(key)
@staticmethod
def _storage_key(key: str) -> str:
"""Collision-resistant encoding for internal session storage filenames."""
return SessionLocation.storage_key(key)
@staticmethod
def _decode_storage_key(stem: str) -> str | None:
"""Reverse _storage_key(): decode a base64url (no-padding) stem back to the original key."""
return SessionLocation.decode_storage_key(stem)
@staticmethod
def decode_storage_key(stem: str) -> str | None:
"""Public decoder for components that inspect canonical session filenames."""
return SessionManager._decode_storage_key(stem)
def _require_offline_mutation(self) -> None:
if self._state is not None and self._state.is_bound:
raise RuntimeError(
+3 -50
View File
@@ -13,7 +13,7 @@ from pathlib import Path
from typing import Any, TypeVar, cast
from nanobot.providers.base import ProviderConversationState
from nanobot.session.display_history import HistoryFact, HistoryImport, HistoryKind, HistoryReader
from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import (
Session,
@@ -183,9 +183,8 @@ class SqliteSessionStore:
if owned:
connection.close()
def initialize(self, workspace: Path) -> None:
"""Upgrade the schema and import legacy sessions in one atomic transaction."""
workspace = workspace.expanduser().resolve(strict=False)
def initialize(self) -> None:
"""Initialize or upgrade the SQLite schema."""
# WAL is persistent and must be enabled outside a transaction.
if self.path.is_symlink():
raise RuntimeError("session database must not be a symlink")
@@ -211,22 +210,6 @@ class SqliteSessionStore:
for target, migrate in enumerate(_SCHEMA_MIGRATIONS[version:], start=version + 1):
migrate(db)
db.execute(f"PRAGMA user_version = {target}")
marker = db.execute(
"SELECT value FROM storage_meta WHERE key='jsonl_import'"
).fetchone()
if marker is None:
from nanobot.session.jsonl_migration import migrate_jsonl
migrate_jsonl(self, workspace)
db.execute("INSERT INTO storage_meta (key, value) VALUES ('jsonl_import', 'complete')")
elif marker[0] != "complete":
raise RuntimeError(
f"invalid JSONL migration marker in {self.path}: {marker[0]!r}; "
"restore a valid database backup or repair the marker explicitly"
)
from nanobot.session.jsonl_migration import finish_workspace_migration
finish_workspace_migration(self, workspace)
def _metadata(self, db: sqlite3.Connection, key: str, raw: str) -> dict[str, Any]:
metadata = _object(raw)
@@ -420,36 +403,6 @@ class SqliteSessionStore:
"updated_at": session.updated_at.isoformat(),
"metadata": session.metadata, "messages": session.messages}
def migrate_history(
self, name: str, collect: Callable[[list[SessionInfo]], list[HistoryImport]],
) -> None:
"""Commit a channel-owned legacy import and its once-only marker together."""
with self.transaction() as db:
marker = db.execute("SELECT value FROM storage_meta WHERE key=?", (name,)).fetchone()
if marker is not None:
if marker[0] != "complete":
raise RuntimeError(f"invalid history import marker: {name}")
return
for item in collect(self.list_sessions()):
session = self.load(item.key, history=False)
if session is None:
session = Session(key=item.key)
if item.created_at_ms:
session.created_at = datetime.fromtimestamp(item.created_at_ms / 1000)
if item.updated_at_ms:
session.updated_at = datetime.fromtimestamp(item.updated_at_ms / 1000)
self.save(session)
revision = self.project_history(item.key, lambda reader: reader.revision)
if revision is not None and revision[1] >= 0:
raise SessionConflictError(f"history already exists before import: {item.key}")
self.append_history(item.key, item.facts, expected_generation=session.generation)
db.execute("UPDATE history_heads SET updated_at_ms=max(updated_at_ms, ?) WHERE session_key=?",
(item.updated_at_ms, item.key))
# Import ownership survives deletion: another namespace must not
# mistake this instance-wide backup for a new orphan later.
db.execute("INSERT INTO storage_meta (key, value) VALUES (?, 'complete')", (f"{name}:{item.key}",))
db.execute("INSERT INTO storage_meta (key, value) VALUES (?, 'complete')", (name,))
def project_history(self, key: str, project: Callable[[HistoryReader], _T]) -> _T:
"""Project durable display facts and canonical messages from one snapshot."""
with self.transaction(write=False) as db:
+1 -9
View File
@@ -14,12 +14,11 @@ from datetime import datetime
from typing import Any, TypeVar, cast
from nanobot.bus.events import InboundMessage
from nanobot.session.display_history import HistoryFact, HistoryImport, HistoryKind, HistoryReader
from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader
from nanobot.session.keys import is_dream_session
from nanobot.session.manager import (
Session,
SessionIdentity,
SessionInfo,
SessionPolicy,
fork_session,
)
@@ -702,13 +701,6 @@ class SessionState:
metadata = {**baseline.metadata, _CHECKPOINT_KEY: committed.metadata[_CHECKPOINT_KEY]}
draft._baseline = replace(baseline, metadata=metadata, provider_state=committed.provider_state) # pyright: ignore[reportPrivateUsage]
async def migrate_history(
self, name: str, collect: Callable[[list[SessionInfo]], list[HistoryImport]],
) -> None:
await self._execute(
None, lambda: self._store.migrate_history(name, collect), operation_name="migrate_history",
)
async def project_history(
self, key: str, project: Callable[[HistoryReader], _T],
) -> _T:
+6 -129
View File
@@ -1,23 +1,14 @@
"""WebUI projection of durable session facts and strict legacy transcript import."""
"""WebUI projection of durable session facts."""
from __future__ import annotations
import json
import re
import sqlite3
from collections.abc import Mapping, Sequence
from contextlib import closing
from pathlib import Path
from typing import Any, cast
from collections.abc import Mapping
from typing import Any
from nanobot.bus.events import INBOUND_META_LOCAL_MEDIA
from nanobot.config.paths import get_webui_dir
from nanobot.session.display_history import HistoryFact, HistoryImport, HistoryKind, HistoryReader
from nanobot.session.manager import SessionInfo, SessionManager
from nanobot.webui.session_identity import is_valid_webui_chat_id, webui_chat_id, webui_session_key
from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader
from nanobot.webui.session_identity import webui_chat_id
HISTORY_IMPORT_MARKER = "webui_history_import_v1"
_SEGMENT_NAME = re.compile(r"^\d{6}\.jsonl$")
_EVENTS = {
"user": HistoryKind.INPUT,
"message": HistoryKind.ANSWER,
@@ -47,11 +38,8 @@ _CONTENT_FIELDS = frozenset({
def fact_from_record(record: Mapping[str, Any]) -> HistoryFact:
"""Parse the channel boundary once; core storage never sees event/chat_id keys."""
event = record.get("event")
if event is None and record.get("role") in {"user", "assistant"}:
event = "user" if record["role"] == "user" else "message"
record = {**record, "text": record.get("text", record.get("content", ""))}
if event not in _EVENTS:
raise ValueError(f"unsupported legacy history event: {event!r}")
raise ValueError(f"unsupported history event: {event!r}")
kind = _EVENTS[event]
if event == "message":
message_kind = record.get("kind")
@@ -101,114 +89,3 @@ def turn_records(
return [{**record_from_fact(fact, history.key),
"_webui_replay_identity": f"turn:{ordinal}:record:{position}"}
for position, fact in history.read_entries(ordinal, max_records=max_records, max_bytes=max_bytes)]
def _read_legacy_file(path: Path) -> list[dict[str, Any]]:
if path.is_symlink() or not path.is_file():
raise ValueError(f"legacy history must be a regular, non-symlink file: {path}")
before = path.stat()
records: list[dict[str, Any]] = []
with path.open(encoding="utf-8") as handle:
for line_number, line in enumerate(handle, 1):
if not line.strip():
continue
try:
value: object = json.loads(line)
if not isinstance(value, dict):
raise ValueError("record is not an object")
record = cast(dict[str, Any], value)
fact_from_record(record).encode()
except (ValueError, TypeError) as exc:
raise ValueError(f"cannot import history {path}:{line_number}: {exc}") from exc
records.append(record)
after = path.stat()
if (before.st_ino, before.st_size, before.st_mtime_ns) != (after.st_ino, after.st_size, after.st_mtime_ns):
raise ValueError(f"legacy history changed during import: {path}")
return records
def collect_legacy_history(
sessions: Sequence[SessionInfo], *, directory: Path | None = None,
namespace: Path | None = None,
) -> list[HistoryImport]:
"""Resolve recorded identities; a lossy filename alone cannot identify an orphan."""
from nanobot.webui.transcript import compact_legacy_records
directory = directory if directory is not None else get_webui_dir()
if directory.is_symlink():
raise ValueError(f"legacy history directory must not be a symlink: {directory}")
if not directory.exists():
return []
groups: dict[str, list[Path]] = {}
for path in sorted(directory.iterdir()):
if path.name.endswith(".segments"):
if path.is_symlink() or not path.is_dir():
raise ValueError(f"invalid legacy history segments directory: {path}")
groups.setdefault(path.name[:-len(".segments")], []).extend(
item for item in sorted(path.iterdir()) if _SEGMENT_NAME.fullmatch(item.name)
)
elif path.suffix == ".jsonl":
groups.setdefault(path.stem, [])
for stem, paths in groups.items():
active = directory / f"{stem}.jsonl"
if active.exists() or active.is_symlink():
paths.append(active)
keys_by_stem: dict[str, set[str]] = {}
for session in sessions:
keys_by_stem.setdefault(SessionManager.safe_key(session["key"]), set()).add(session["key"])
foreign_owners: dict[str, list[Path]] = {}
if namespace is not None and groups:
for database in namespace.parent.glob("*/sessions.sqlite3"):
if database.parent == namespace:
continue
if database.is_symlink() or database.parent.is_symlink():
raise ValueError(f"invalid session namespace for history migration: {database}")
with closing(sqlite3.connect(database.as_uri() + "?mode=ro", uri=True)) as db:
owned = {str(row[0]) for row in db.execute("SELECT key FROM sessions")}
prefix = f"{HISTORY_IMPORT_MARKER}:"
owned.update(str(row[0])[len(prefix):] for row in db.execute(
"SELECT key FROM storage_meta WHERE key LIKE ? AND value='complete'",
(prefix + "%",),
))
for key in owned:
foreign_owners.setdefault(key, []).append(database)
imports: list[HistoryImport] = []
for stem, paths in groups.items():
records = [record for path in paths for record in _read_legacy_file(path)]
if not records:
continue
recorded_keys: set[str] = set()
for record in records:
chat_id = record.get("chat_id")
if chat_id is not None:
if not is_valid_webui_chat_id(chat_id):
raise ValueError(f"invalid recorded chat identity in legacy history: {stem}")
recorded_keys.add(webui_session_key(chat_id))
candidates = recorded_keys or keys_by_stem.get(stem, set())
if len(candidates) != 1:
raise ValueError(f"ambiguous legacy history identity: {stem}; expected one recorded chat or canonical session")
key = next(iter(candidates))
if SessionManager.safe_key(key) != stem:
raise ValueError(f"legacy history filename conflicts with its recorded identity: {stem}")
if key in foreign_owners:
if key not in keys_by_stem.get(stem, set()) and len(foreign_owners[key]) == 1:
# This instance-wide backup belongs to another workspace. Its
# owner will import it when that namespace starts.
continue
raise ValueError(
f"cannot select a SQLite owner for legacy history {key}: also present in "
f"{foreign_owners[key]}; resolve the duplicate explicitly before restarting"
)
facts = [fact_from_record(record) for record in compact_legacy_records(records)]
times = [fact.created_at_ms for fact in facts if fact.created_at_ms]
file_times = [int(path.stat().st_mtime * 1000) for path in paths]
imports.append(HistoryImport(key, facts, min(times or file_times), max(times or file_times)))
return imports
async def initialize_history(sessions: SessionManager) -> None:
"""Finish the once-only import before recovery or transport admission."""
await sessions.state.migrate_history(
HISTORY_IMPORT_MARKER,
lambda rows: collect_legacy_history(rows, namespace=sessions.sessions_dir),
)
-3
View File
@@ -102,9 +102,6 @@ class WebUIOutboundDelivery:
self._stream_text_buffers: dict[tuple[str, str], list[str]] = {}
self._reasoning_text_buffers: dict[tuple[str, str], list[str]] = {}
async def initialize(self) -> None:
await self._transcripts.initialize()
def bind_pairing(self, bus: MessageBus, *, channel: str) -> Callable[[], None]:
async def queue_changed(event: PairingChanged) -> None:
await bus.publish_event(event, channel=channel, chat_id="*")
+1 -4
View File
@@ -86,9 +86,6 @@ class RecoveryCoordinator:
async def scan(self) -> None:
"""Recover every interrupted WebUI session once at gateway startup."""
from nanobot.webui.history import initialize_history
await initialize_history(self.sessions)
for key in await self._recovery_candidates():
metadata_payload = await self.sessions.state.read_metadata(key)
raw_metadata = metadata_payload.get("metadata") if metadata_payload else None
@@ -118,7 +115,7 @@ class RecoveryCoordinator:
await self._publish(route[1], failed)
async def _recovery_candidates(self) -> list[str]:
"""Legacy display-only sessions have canonical headers after import."""
"""Display-only sessions also have canonical headers in SQLite."""
return [item["key"] for item in await self.sessions.state.list_sessions()]
@staticmethod
-25
View File
@@ -36,7 +36,6 @@ from nanobot.session.sqlite_store import SessionConflictError
from nanobot.session.state import SessionOperationQueueFullError
from nanobot.webui.history import (
fact_from_record,
initialize_history,
record_from_fact,
turn_records,
)
@@ -318,25 +317,6 @@ def _compact_completed_stream_deltas(
], len(dropped_indexes)
def _compact_completed_turns(
turns: list[list[dict[str, Any]]],
) -> tuple[list[list[dict[str, Any]]], int]:
compacted: list[list[dict[str, Any]]] = []
dropped = 0
for turn in turns:
next_turn, turn_dropped = _compact_completed_stream_deltas(turn)
compacted.append(next_turn)
dropped += turn_dropped
return compacted, dropped
def compact_legacy_records(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
turns, _ = _compact_completed_turns(_split_transcript_turns(records))
return [record for turn in turns for record in turn]
def _records_with_replay_identity(
records: list[dict[str, Any]],
*,
@@ -531,11 +511,6 @@ class WebUITranscriptRecorder:
self._log = log
self._turn_sequences: dict[tuple[str, str], int] = {}
async def initialize(self) -> None:
sessions = self.sessions
if sessions is not None:
await initialize_history(sessions)
def client_turn_metadata(self, value: Any) -> dict[str, str]:
return {WEBUI_TURN_METADATA_KEY: normalize_webui_turn_id(value)}
+4 -2
View File
@@ -38,15 +38,17 @@ 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"), DOCKER, "Docker input or acceptance"),
"tests/test_docker*", "scripts/docker_compose_smoke.py", "scripts/docker_upgrade_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/sqlite_v1.sql",), PYTHON, "Python session schema migration fixture"),
(("tests/session/fixtures/*.sql",), PYTHON, "Python session storage upgrade fixtures"),
(("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"),
+5 -24
View File
@@ -14,7 +14,6 @@ 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:
@@ -42,26 +41,7 @@ def product_phase(phase: str, version: str) -> None:
time.sleep(0.2)
raise RuntimeError("Installed container gateway did not become 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
probe.ready = ready
try:
if phase == "seed":
root.mkdir()
@@ -70,7 +50,7 @@ def product_phase(phase: str, version: str) -> None:
probe.snapshot(root)
else:
probe.gateway(root, "--background")
assert probe.verify_data(root, version)
probe.verify_data(root, version)
finally:
probe.gateway(root, "stop")
@@ -115,7 +95,8 @@ 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, "config_and_legacy_bytes_preserved": True,
"same_volume_image_replacement": True, "history_fixture": "native-sqlite",
"config_bytes_preserved": True, "sqlite_records_preserved": True, "scheduled_delivery_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}
@@ -125,7 +106,7 @@ def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--image")
parser.add_argument("--baseline-image")
parser.add_argument("--baseline-version", default="0.3.5")
parser.add_argument("--baseline-version", default="0.4.0")
parser.add_argument("--version", required=True)
parser.add_argument("--output", type=Path)
parser.add_argument("--source-commit")
+75 -136
View File
@@ -3,7 +3,8 @@
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 too.
Use --baseline-wheel to exercise an actual earlier updater-enabled package with
SQLite session history, shared proxy configuration and a durable delivery outbox too.
No public feed, user installation, model, credentials or OS service is used.
"""
@@ -19,7 +20,6 @@ import io
import json
import os
import platform
import re
import secrets
import signal
import socket
@@ -308,23 +308,6 @@ 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:
@@ -333,26 +316,6 @@ 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
@@ -400,10 +363,28 @@ 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"
@@ -417,37 +398,20 @@ 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)
# 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")
seed_history(root)
# Keep a real durable result pending without attempting an external send.
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),
))
if _dock_supported(root):
_desktop_webui(root)
_wait_dock(_dock_socket(root), present=True)
@@ -456,56 +420,36 @@ def seed(root: Path) -> None:
def snapshot(root: Path) -> None:
from nanobot.config.loader import set_config_path
from nanobot.config.paths import get_webui_dir
from nanobot.config.loader import load_config, set_config_path
from nanobot.session.location import SessionLocation
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"
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")
sessions = SessionLocation(root / "workspace").sessions_dir
key = "websocket:mixed-history"
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)
legacy_before = history(root, key)
mixed_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(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,
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,
"display_only": display_before, "canonical_only": context_before,
"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)})
"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")})
def prepare(root: Path) -> None:
@@ -560,7 +504,7 @@ def verify(root: Path) -> dict:
if not restored:
assert COMMIT == case["commit"]
assert digest(Path(case["target_wheel"])) == case["target_sha256"]
sqlite_expected = verify_data(root, 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"}:
@@ -568,19 +512,22 @@ 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,
"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,
"history_fixture": "native-sqlite", "config_bytes_preserved": True,
"restarted": True, "authenticated_history_preserved": True, "sqlite_records_preserved": True,
"scheduled_delivery_preserved": True,
"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) -> bool:
def verify_data(root: Path, expected: str) -> None:
"""Public reads and subsequent writes, shared by inline and owner-driven updates."""
from nanobot.config.loader import set_config_path
from nanobot.config.loader import load_config, set_config_path
set_config_path(root / "account/.nanobot/config.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
before = read(root / "before.json")
receipt = ready(root, expected)
assert receipt.run_id != before["run_id"], "Update did not restart the gateway"
@@ -595,29 +542,24 @@ def verify_data(root: Path, expected: str) -> bool:
_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_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"])
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"]
database = Path(before["database"])
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)
canonical = canonical_records(database)
assert canonical == before["canonical"]
delivery = root / "account/.nanobot/delivery/outbox.sqlite3"
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", "配置和聊天不能丢失")]
assert canonical_records(delivery, ("deliveries",)) == before["delivery"]
# Display transcripts are not canonical agent context.
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", "配置和聊天不能丢失")]
asyncio.run(chat(root, before["chat_id"]))
continued = history(root, key)
canonical = canonical_records(database) if sqlite_expected else None
canonical = canonical_records(database)
assert len(continued["events"]) > len(before["history"]["events"])
gateway(root, "stop")
if _dock_supported(root):
@@ -627,15 +569,12 @@ def verify_data(root: Path, expected: str) -> bool:
if _dock_supported(root):
_wait_dock(_dock_socket(root), present=True)
assert history(root, key) == continued
assert_history_preserved(before["legacy"], history(root, "websocket:legacy-acceptance"))
assert_history_preserved(before["display_only"], history(root, "websocket:display-only"))
assert history(root, "websocket:mixed-history") == before["mixed"]
assert history(root, "websocket:display-only") == before["display_only"]
assert canonical_context(root) == before["canonical_only"]
if sqlite_expected:
assert canonical_records(database) == canonical
if before.get("delivery") is not None:
assert canonical_records(delivery, ("deliveries",)) == before["delivery"]
assert canonical_records(database) == canonical
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]:
-1
View File
@@ -146,7 +146,6 @@ 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"
+2 -3
View File
@@ -1,16 +1,15 @@
"""Session keys remain distinct even when their display filenames collide."""
"""Session keys with punctuation and Unicode remain distinct in storage."""
from nanobot.session.manager import Session, SessionManager
def test_colliding_display_names_roundtrip_independently(tmp_path):
def test_distinct_keys_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
+7 -13
View File
@@ -59,9 +59,7 @@ 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, tmp_path, monkeypatch, state):
webui_dir = tmp_path / "webui"
monkeypatch.setattr("nanobot.webui.history.get_webui_dir", lambda: webui_dir)
async def test_session_tools_use_canonical_records_after_restart(history, state):
manager = history.sessions
key = "websocket:history"
if state != "transcript":
@@ -75,16 +73,10 @@ async def test_session_tools_use_canonical_records_after_restart(history, tmp_pa
})
history.append(key, {"event": "turn_end", "chat_id": "history"})
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()
original_messages = manager.read_session_file(key)["messages"]
original_display_facts = manager.project_history(key, lambda reader: reader.all_facts())
for _ in range(2):
manager = history.sessions
manager = SessionManager(history.sessions.workspace)
with request_context(RequestContext(
channel="websocket", chat_id="current", session_key="websocket:current",
)):
@@ -99,4 +91,6 @@ async def test_session_tools_use_canonical_records_after_restart(history, tmp_pa
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 durable_files() == original
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()
+1 -2
View File
@@ -138,7 +138,6 @@ class _EmptyGatewaySessionManager:
def state(self):
return SimpleNamespace(
list_sessions=AsyncMock(return_value=[]),
migrate_history=AsyncMock(),
record_delivery=AsyncMock(),
aclose=AsyncMock(),
)
@@ -941,7 +940,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({"providers": {"openaiCodex": {"proxy": proxy}}}),
json.dumps({"network": {"proxy": proxy}, "providers": {"openaiCodex": {"useProxy": True}}}),
encoding="utf-8",
)
active_path: dict[str, Path] = {}
+1 -2
View File
@@ -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_legacy_sessions_dir, get_media_dir
from nanobot.config.paths import get_cli_history_path, get_media_dir
from nanobot.config.schema import Config
@@ -54,7 +54,6 @@ 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)
+1 -3
View File
@@ -4,7 +4,6 @@ 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,
@@ -31,9 +30,8 @@ def test_media_dir_supports_channel_namespace(monkeypatch, tmp_path: Path) -> No
assert get_media_dir("telegram") == config_file.parent / "media" / "telegram"
def test_shared_and_legacy_paths_remain_global() -> None:
def test_cli_history_path_remains_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:
+32 -184
View File
@@ -1,64 +1,44 @@
"""One shared address, explicit feature opt-in, and legacy config migration."""
"""One shared address with explicit feature opt-in."""
import json
import httpx
import pytest
from nanobot.config.loader import ConfigLoadError, load_config, resolve_config_env_vars, save_config
from nanobot.config.loader import load_config, resolve_config_env_vars, save_config
from nanobot.config.network import NetworkConfig
from nanobot.config.schema import Config
@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):
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},
}))
path = tmp_path / "config.json"
original = {
"providers": {"openai": {"proxy": address}, "openaiCodex": {"proxy": address}},
"tools": {"web": {"proxy": address}},
"channels": {"telegram": {"proxy": address}, "slack": {"proxy": ""}},
"network": {"proxy": "socks5://localhost:1080"},
"tools": {"web": {"useProxy": False}},
"channels": {"telegram": {"useProxy": True}},
}
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.tools.web.use_proxy is True
assert config.channels.telegram["useProxy"] is True
assert "useProxy" not in config.channels.slack
assert config.providers.xai_grok.use_proxy is True
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
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}
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_proxy_opt_in_does_not_fall_back_when_unconfigured():
@@ -87,101 +67,7 @@ def test_invalid_shared_proxy_has_a_safe_error(address):
assert address not in str(caught.value)
@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("address", ["http://proxy.example:8080", "${PROXY_SCHEME}://${PROXY_HOST}:8080"])
@pytest.mark.parametrize(
"userinfo, environment, expected_auth",
[
@@ -196,11 +82,14 @@ def test_oauth_proxy_opt_out_survives_save_with_legacy_environment(tmp_path, mon
],
ids=["combined-auth", "combined-encoded-auth", "combined-special-password", "credential-components"],
)
def test_proxy_userinfo_references_round_trip_with_httpx_auth(tmp_path, monkeypatch, legacy, userinfo, environment, expected_auth):
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")
for name, value in environment.items():
monkeypatch.setenv(name, value)
template = f"http://{userinfo}@proxy.example:8080"
original = {"providers": {"openai": {"proxy": template}}} if legacy else {
scheme, host = address.split("://", 1)
template = f"{scheme}://{userinfo}@{host}"
original = {
"network": {"proxy": template}, "providers": {"openai": {"useProxy": True}},
}
path = tmp_path / "config.json"
@@ -210,7 +99,10 @@ 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)):
assert httpx.Proxy(current.network.resolve_proxy(current.providers.openai.use_proxy)).raw_auth == expected_auth
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 json.loads(path.read_text(encoding="utf-8")) == original
save_config(config, path)
@@ -221,47 +113,3 @@ 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())
+2 -1
View File
@@ -32,6 +32,7 @@ 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()),
@@ -61,7 +62,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", "native"}),
("scripts/verify_packaged_update.py", {"python", "docker", "native"}),
("scripts/check_client_import_boundaries.mjs", {"webui", "tui"}),
(".github/workflows/release-candidate.yml", {"python", "native"}),
(".github/workflows/release-approve.yml", {"python", "native"}),
-1
View File
@@ -20,5 +20,4 @@ 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,9 +1,6 @@
"""Reset a corrupt last_consolidated offset instead of hiding history (#4066)."""
import json
from pathlib import Path
from nanobot.session.manager import Session, SessionManager
from nanobot.session.manager import Session
def _session(count: int, last_consolidated: object) -> Session:
@@ -21,39 +18,6 @@ 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
@@ -63,59 +27,6 @@ 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 == {}
-123
View File
@@ -13,7 +13,6 @@ 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
@@ -21,13 +20,6 @@ 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")
@@ -121,73 +113,6 @@ 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"
@@ -249,31 +174,6 @@ 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
@@ -317,29 +217,6 @@ 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
-1
View File
@@ -35,7 +35,6 @@ 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:
+10 -25
View File
@@ -23,15 +23,6 @@ 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)
monkeypatch.setattr(history_module, "get_webui_dir", lambda: webui_dir)
def _persist(manager: SessionManager, session: Session) -> None:
session.metadata["webui"] = True
manager.save(session)
@@ -128,25 +119,19 @@ 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)
monkeypatch.setattr(history_module, "get_webui_dir", lambda: webui_dir)
unfinished_key = "websocket:unfinished"
completed_key = "websocket:completed"
(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",
)
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"},
)])
coordinator, bus, sessions = _coordinator(tmp_path / "workspace")
await coordinator.scan()
@@ -1,11 +0,0 @@
"""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
-74
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
import json
import os
import shutil
import subprocess
@@ -12,40 +11,9 @@ 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)
@@ -219,45 +187,3 @@ 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
+13 -45
View File
@@ -1,6 +1,5 @@
"""Session schema upgrades preserve records and fail atomically."""
import json
import sqlite3
from contextlib import closing
from pathlib import Path
@@ -38,22 +37,6 @@ 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 (
@@ -63,10 +46,8 @@ def _database_snapshot(path: Path) -> tuple[int, str, str]:
)
def test_ordered_upgrades_preserve_records_and_do_not_repeat_import(tmp_path, monkeypatch):
workspace = tmp_path / "workspace"
def test_ordered_upgrades_preserve_records(tmp_path, monkeypatch):
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"
@@ -83,9 +64,8 @@ def test_ordered_upgrades_preserve_records_and_do_not_repeat_import(tmp_path, mo
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(workspace)
upgraded.initialize()
assert _database_snapshot(store.path)[0] == len(sqlite_store._SCHEMA_MIGRATIONS)
loaded = upgraded.load(original.key)
assert loaded is not None
@@ -95,7 +75,7 @@ def test_ordered_upgrades_preserve_records_and_do_not_repeat_import(tmp_path, mo
upgraded.save(loaded)
reopened = SqliteSessionStore(tmp_path)
reopened.initialize(workspace)
reopened.initialize()
roundtrip = reopened.load(original.key)
assert roundtrip is not None
assert roundtrip.messages == original.messages
@@ -104,13 +84,11 @@ def test_ordered_upgrades_preserve_records_and_do_not_repeat_import(tmp_path, mo
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(workspace)
store.initialize()
original = _session()
store.save(original)
before = _database_snapshot(store.path)
@@ -128,7 +106,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(workspace)
store.initialize()
assert _database_snapshot(store.path) == before
def complete_upgrade(db: sqlite3.Connection) -> None:
@@ -137,7 +115,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(workspace)
store.initialize()
assert _database_snapshot(store.path)[0] == len(sqlite_store._SCHEMA_MIGRATIONS)
loaded = store.load(original.key)
assert loaded is not None
@@ -146,7 +124,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_import_and_all_session_write_paths(tmp_path, monkeypatch):
def test_added_columns_allow_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")
@@ -155,16 +133,8 @@ def test_added_columns_allow_import_and_all_session_write_paths(tmp_path, monkey
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(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
store.initialize()
created = _session()
created.key = "chat:new"
@@ -183,15 +153,14 @@ def test_added_columns_allow_import_and_all_session_write_paths(tmp_path, monkey
assert roundtrip.metadata == current.metadata
assert roundtrip.provider_state == current.provider_state
with closing(sqlite3.connect(store.path)) as db:
for table in ("storage_meta", "sessions", "messages", "checkpoints", "pending_inputs"):
for table in ("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(workspace)
store.initialize()
store.save(_session())
future_version = len(sqlite_store._SCHEMA_MIGRATIONS) + 1
with closing(sqlite3.connect(store.path)) as db:
@@ -202,16 +171,15 @@ 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(workspace)
store.initialize()
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(workspace)
store.initialize()
store.save(_session())
with closing(sqlite3.connect(store.path)) as db:
db.execute("PRAGMA journal_mode = DELETE")
@@ -231,6 +199,6 @@ 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(workspace)
store.initialize()
assert _database_snapshot(store.path) == before
assert store.path.read_bytes() == before_bytes
+1 -357
View File
@@ -1,245 +1,18 @@
"""SQLite durability, migration, and asynchronous state ownership contracts."""
"""SQLite durability and asynchronous state ownership contracts."""
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")
@@ -504,135 +277,6 @@ 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
+24 -51
View File
@@ -20,8 +20,6 @@ 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,
@@ -30,58 +28,33 @@ from scripts.verify_packaged_update import (
)
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)
@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_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
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
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))
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
def wheel(tmp_path, version, *, worker=b"# worker\n", fallback=b"# fallback\n"):
-7
View File
@@ -317,13 +317,6 @@ 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,
-40
View File
@@ -350,46 +350,6 @@ 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))
+1 -3
View File
@@ -116,9 +116,7 @@ def test_session_mention_context_treats_titles_as_data() -> None:
@pytest.mark.asyncio
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)
async def test_session_mentions_do_not_isolate_workspaces(tmp_path) -> None:
manager = SessionManager(tmp_path)
project_b = tmp_path / "b"
project_b.mkdir()
+3 -62
View File
@@ -1,7 +1,6 @@
"""A restarted host replays task observations without recovering execution."""
import asyncio
import hashlib
import json
import subprocess
import sys
@@ -33,8 +32,6 @@ 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
@@ -271,7 +268,8 @@ 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):
before = {file.name: file.read_bytes() for file in root.glob("*.jsonl")}
child_key = SubagentSessions.key(task_id)
before = sessions.project_history(child_key, lambda history: history.all_facts())
response = await gateway.http.dispatch(connection, Request(path, headers))
assert response.status_code == 200
thread = json.loads(response.body)
@@ -284,7 +282,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 {file.name: file.read_bytes() for file in root.glob("*.jsonl")} == before
assert sessions.project_history(child_key, lambda history: history.all_facts()) == before
return thread
assert (await assert_activity(gateway, connection, headers))["active_turn_id"]
@@ -848,63 +846,6 @@ 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")