chore(release): prepare 0.4.1 (#6570)

Prepare version 0.4.1 and document the retained legacy upgrade path.

Avoid false busy update handoffs from disabled or not-yet-due idle scans. Keep real work, maintenance, lease and data-protection checks intact.

Retain safe package-failure diagnostics and cancellable test-controller progress checks. Reduce Windows installer startup contention without changing command deadlines or behavioral assertions.

Validated on the reviewed head with all required PR checks and the exact five-platform candidate. Historical package and recovery coverage remains as documented in the release acceptance record. Publication is separate; this merge does not create a tag, release, upload or feed change.
This commit is contained in:
Xubin Ren authored and GitHub committed 2026-11-06 20:48:57 +08:00
1 parent 1a89a25abd
commit cdaae66c89
15 files changed
+310 -37

No files matched your search

+9 -8
View File
@@ -151,12 +151,13 @@ jobs:
# Each update job owns its venv, HOME, profile and lock directory. Preserve # Each update job owns its venv, HOME, profile and lock directory. Preserve
# the real installation/restore checks, but avoid a loadfile straggler and # the real installation/restore checks, but avoid a loadfile straggler and
# disk contention with timing-sensitive runtime-registration checks. # disk contention with timing-sensitive runtime-registration checks.
# Keep three update workers; the six-worker trial exceeded supervisor deadlines. # Three concurrent offline pip fixture installs exceeded their 60s bounds.
# Reduce startup contention; keep every command deadline and lease assertion.
- name: Run Windows isolated update jobs - name: Run Windows isolated update jobs
if: runner.os == 'Windows' && github.event_name != 'push' && needs.changes.outputs.native_required == 'true' if: runner.os == 'Windows' && github.event_name != 'push' && needs.changes.outputs.native_required == 'true'
run: >- run: >-
uv run --no-sync python -m pytest tests/test_update_jobs.py uv run --no-sync python -m pytest tests/test_update_jobs.py
-n 3 --dist load -vv --durations=25 --durations-min=1.0 -n 2 --dist load -vv --durations=25 --durations-min=1.0
--junitxml=test-results/update-jobs.xml --timing-report=test-results/update-jobs.json --junitxml=test-results/update-jobs.xml --timing-report=test-results/update-jobs.json
- name: Run tests with coverage - name: Run tests with coverage
@@ -260,9 +261,9 @@ jobs:
needs: changes needs: changes
if: github.event_name != 'push' && needs.changes.outputs.python_required == 'true' && needs.changes.outputs.native_required == 'true' if: github.event_name != 'push' && needs.changes.outputs.python_required == 'true' && needs.changes.outputs.native_required == 'true'
runs-on: windows-latest runs-on: windows-latest
# The real installer matrix took 18m06s alone; process checks and teardown # Two installer workers retain the per-command 90s deadline without four
# previously pushed the combined job beyond its 20-minute bound. # concurrent PowerShell/venv cold starts competing on the same Windows VM.
timeout-minutes: 25 timeout-minutes: 40
env: env:
PYTEST_ADDOPTS: "-o tmp_path_retention_policy=failed -p scripts.pytest_timing" PYTEST_ADDOPTS: "-o tmp_path_retention_policy=failed -p scripts.pytest_timing"
steps: steps:
@@ -282,12 +283,12 @@ jobs:
uv tool install pipx==1.17.12 uv tool install pipx==1.17.12
uv tool dir --bin >> "$GITHUB_PATH" uv tool dir --bin >> "$GITHUB_PATH"
# Each case owns an isolated manager/config root. Keep four workers: # Each case owns an isolated manager/config root. Four concurrent starts
# eight-way installer startup exceeded the existing command deadlines in CI. # exceeded the command deadlines; reduce contention, not test coverage.
- name: Run Windows installer checks - name: Run Windows installer checks
run: >- run: >-
uv run --no-sync python -m pytest tests/test_install_scripts.py uv run --no-sync python -m pytest tests/test_install_scripts.py
-n 4 --dist load -x -vv --durations=10 -n 2 --dist load -x -vv --durations=10
--junitxml=test-results/installers.xml --timing-report=test-results/installers.json --junitxml=test-results/installers.xml --timing-report=test-results/installers.json
- name: Upload Windows process test timings - name: Upload Windows process test timings
+2
View File
@@ -142,6 +142,8 @@ jobs:
${{ runner.temp }}/packaged-update/packaged-update-report.json ${{ runner.temp }}/packaged-update/packaged-update-report.json
${{ runner.temp }}/packaged-update/packaged-update-timings.json ${{ runner.temp }}/packaged-update/packaged-update-timings.json
${{ runner.temp }}/packaged-update/*/result.json ${{ runner.temp }}/packaged-update/*/result.json
${{ runner.temp }}/packaged-update/*/phase-failure.json
${{ runner.temp }}/packaged-update/lane-*/run/*/result.json ${{ runner.temp }}/packaged-update/lane-*/run/*/result.json
${{ runner.temp }}/packaged-update/lane-*/run/*/phase-failure.json
if-no-files-found: error if-no-files-found: error
retention-days: 3 retention-days: 3
+11
View File
@@ -2,6 +2,17 @@
Use the update method that owns your installation. If your version does not include the WebUI updater, first upgrade through the original installer or package manager. This does not convert an existing installation into an installer-managed one. Use the update method that owns your installation. If your version does not include the WebUI updater, first upgrade through the original installer or package manager. This does not convert an existing installation into an installer-managed one.
## Upgrade older JSONL installations
The 0.4.x releases retain automatic import of legacy model JSONL history, WebUI JSONL / segments and per-feature proxy settings. You can upgrade an older installation directly to 0.4.1 through its original installation method; an intermediate 0.4.0 installation is not required. These importers are scheduled for removal in 0.5.0.
1. Stop all writers and back up the complete instance, including the configuration directory and workspace.
2. Upgrade through the original installation method, preserving existing extras, constraints and installation ownership.
3. Start the updated instance with the same configuration and workspace selectors. Open existing conversations and verify both messages and displayed history. Check proxy settings and save the migrated shared-proxy configuration.
4. Verify the running version, a new message and another restart before considering the upgrade complete.
Keep the original backup and retained JSONL import backups. Do not delete or overwrite old data to resolve a missing-history problem. Complete and verify the migration on a 0.4.x release before upgrading to 0.5.0.
## Update from the WebUI ## Update from the WebUI
1. Open the blue update entry in the sidebar or **Settings → About → Update**. Opening the dialog only checks the installation; it does not install or restart anything. 1. Open the blue update entry in the sidebar or **Settings → About → Update**. Opening the dialog only checks the installation; it does not install or restart anything.
+2
View File
@@ -113,6 +113,8 @@ The context indicator beside the model badge shows context-window usage. **Recen
Open the file graph to see files used since the latest compaction and local Markdown references discovered in those files. Click a node to see its estimated token count or open the file, and drag across the usage bar or use replay to review earlier rounds. A loaded node means the file was read or supplied during this phase; it does not guarantee that the whole file, or its original text, remains in the model's current request. Compaction starts a new replay phase; its graph appears with the next request. Previously saved snapshots remain readable, but missing historical snapshots are not reconstructed from current files. Open the file graph to see files used since the latest compaction and local Markdown references discovered in those files. Click a node to see its estimated token count or open the file, and drag across the usage bar or use replay to review earlier rounds. A loaded node means the file was read or supplied during this phase; it does not guarantee that the whole file, or its original text, remains in the model's current request. Compaction starts a new replay phase; its graph appears with the next request. Previously saved snapshots remain readable, but missing historical snapshots are not reconstructed from current files.
Switching topics closes the previous topic's graph. Reopen it from the context indicator for the selected topic. Large or continuously growing graphs may be less responsive on slower devices.
During compaction, the model switches to a summary plus subsequent messages; the original messages remain in chat history. Use `/compact` to compact the current topic manually. See [Memory](./memory.md) for compaction and Dream consolidation. During compaction, the model switches to a summary plus subsequent messages; the original messages remain in chat history. Use `/compact` to compact the current topic manually. See [Memory](./memory.md) for compaction and Dream consolidation.
### File and diagram previews ### File and diagram previews
+1 -1
View File
@@ -44,7 +44,7 @@ def _resolve_version() -> str:
return _pkg_version("nanobot-ai") return _pkg_version("nanobot-ai")
except PackageNotFoundError: except PackageNotFoundError:
# Source checkouts often import nanobot without installed dist-info. # Source checkouts often import nanobot without installed dist-info.
return _read_pyproject_version() or "0.4.0" return _read_pyproject_version() or "0.4.1"
__version__ = _resolve_version() __version__ = _resolve_version()
+7 -1
View File
@@ -40,9 +40,13 @@ class AutoCompact:
self._bind_events = bind_events self._bind_events = bind_events
self._session_lock = session_lock self._session_lock = session_lock
@property
def enabled(self) -> bool:
return self._ttl > 0
def _is_expired(self, ts: datetime | str | None, def _is_expired(self, ts: datetime | str | None,
now: datetime | None = None) -> bool: now: datetime | None = None) -> bool:
if self._ttl <= 0 or not ts: if not self.enabled or not ts:
return False return False
try: try:
if isinstance(ts, str): if isinstance(ts, str):
@@ -65,6 +69,8 @@ class AutoCompact:
active_session_keys: Collection[str] = (), active_session_keys: Collection[str] = (),
) -> None: ) -> None:
"""Schedule idle archival without blocking the event loop.""" """Schedule idle archival without blocking the event loop."""
if not self.enabled:
return
now = datetime.now() now = datetime.now()
active_keys = set(active_session_keys) active_keys = set(active_session_keys)
for info in await self.sessions.state.list_sessions(): for info in await self.sessions.state.list_sessions():
+10 -4
View File
@@ -1368,11 +1368,17 @@ class AgentLoop:
) )
return result return result
def _idle_compact_check_due(self, now: float) -> bool:
return (
self.auto_compact.enabled
and not self.bus.admission.paused
and not self._idle_compact_check_running
and now >= self._next_idle_compact_check_at
)
async def _check_expired_sessions_if_due(self) -> None: async def _check_expired_sessions_if_due(self) -> None:
if self.bus.admission.paused or self._idle_compact_check_running:
return
now = time.monotonic() now = time.monotonic()
if now < self._next_idle_compact_check_at: if not self._idle_compact_check_due(now):
return return
self._next_idle_compact_check_at = now + self._idle_compact_check_interval_s self._next_idle_compact_check_at = now + self._idle_compact_check_interval_s
self._idle_compact_check_running = True self._idle_compact_check_running = True
@@ -1402,7 +1408,7 @@ class AgentLoop:
msg = await self.bus.consume_inbound() msg = await self.bus.consume_inbound()
except asyncio.TimeoutError: except asyncio.TimeoutError:
# Storage may wait behind a turn that /stop needs to cancel. # Storage may wait behind a turn that /stop needs to cancel.
if not self.bus.admission.paused: if self._idle_compact_check_due(time.monotonic()):
self.schedule_background(self._check_expired_sessions_if_due()) self.schedule_background(self._check_expired_sessions_if_due())
continue continue
except asyncio.CancelledError: except asyncio.CancelledError:
+1 -1
View File
@@ -1,6 +1,6 @@
[project] [project]
name = "nanobot-ai" name = "nanobot-ai"
version = "0.4.0" version = "0.4.1"
description = "A lightweight personal AI assistant framework" description = "A lightweight personal AI assistant framework"
readme = { file = "README.md", content-type = "text/markdown" } readme = { file = "README.md", content-type = "text/markdown" }
requires-python = ">=3.11" requires-python = ">=3.11"
+91 -5
View File
@@ -27,7 +27,7 @@ import sqlite3
import subprocess import subprocess
import sys import sys
import time import time
from contextlib import ExitStack, closing, contextmanager from contextlib import ExitStack, closing, contextmanager, suppress
from pathlib import Path from pathlib import Path
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from unittest.mock import patch from unittest.mock import patch
@@ -44,6 +44,11 @@ TWO_JOURNEY_SCENARIOS = {"upgrade-again", "import-failure", "restart-failure", "
# Each lane retains the existing per-command deadlines and cleanup. This outer # Each lane retains the existing per-command deadlines and cleanup. This outer
# bound also covers a stuck controller; it is not permission to leave it running. # bound also covers a stuck controller; it is not permission to leave it running.
LANE_TIMEOUT = 30 * 60 LANE_TIMEOUT = 30 * 60
PREFLIGHT_MODULES = {"update_handoff.py", "update_worker.py", "update_plan.py", "update_stop.py",
"update_profiles.py", "release_feed.py", "installation_lock.py", "data_access.py"}
STOP_STATES = {"ready", "busy", "released", "stopping", "refused"}
BUSY_FLAGS = {"paused", "active", "inbound", "events", "pending_queues", "active_tasks",
"background_tasks", "deferred_automation_turns", "channel_delivery", "registered_work"}
def digest(path: Path) -> str: def digest(path: Path) -> str:
@@ -59,6 +64,41 @@ def write(path: Path, value) -> None:
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def phase_failure(root: Path, phase: str, error: Exception) -> None:
"""Export a failed probe location, not exception values or private journals."""
lines = []
traceback = error.__traceback__
while traceback is not None:
if traceback.tb_frame.f_code.co_filename == __file__:
lines.append(traceback.tb_lineno)
traceback = traceback.tb_next
record = {"phase": phase, "error_type": type(error).__name__, "probe_lines": lines}
# Read with stdlib only: the target package can be deliberately unimportable.
# Messages, commands, paths, identifiers and arbitrary phase values stay local.
with suppress(OSError, ValueError, KeyError, TypeError):
directory = Path(read(root / "launch.json")["directory"])
status = read(directory / "status.json")
record["update_phase"] = (status["phase"] if status["phase"] in {
"succeeded", "restored", "failed", "restart_failed", "handoff_failed",
} else "incomplete")
record["mutation_started"] = status["mutation_started"] is True
record["recovery_needs_attention"] = read(directory / "supervision.json").get("state") == "needs_attention"
preflight = read(directory / "acceptance-preflight.json")
record["preflight_error"] = (preflight["error_type"] if preflight["error_type"] in {
"ValueError", "OSError", "RuntimeError", "ReleaseFeedError", "InstallationBusyError",
"TimeoutError", "CalledProcessError", "FileNotFoundError", "PermissionError",
} else "OtherException")
record["preflight_frames"] = [[row[0], row[1]] for row in preflight["frames"]
if isinstance(row, list) and len(row) >= 2
and row[0] in PREFLIGHT_MODULES and type(row[1]) is int]
record["stop_states"] = sorted({value for value in preflight.get("stop_states", [])
if isinstance(value, str) and value in STOP_STATES})
busy = read(directory / "acceptance-busy.json")
record["busy_flags"] = {key: value for key, value in busy.items()
if key in BUSY_FLAGS and type(value) is bool}
write(root / "phase-failure.json", record)
class Timings: class Timings:
"""Separate, incrementally persisted evidence; never include commands or logs.""" """Separate, incrementally persisted evidence; never include commands or logs."""
@@ -168,6 +208,48 @@ def transport():
raise OSError('Injected backup write failure') raise OSError('Injected backup write failure')
'''.encode() + needle) '''.encode() + needle)
files["nanobot/update_worker.py"] = worker files["nanobot/update_worker.py"] = worker
# Observe an old-runtime preflight refusal without changing its decision,
# shutdown, worker or recovery semantics. Never export exception values.
handoff = files["nanobot/update_handoff.py"].replace(b"\r\n", b"\n")
files["nanobot/update_handoff.py"] = replace_once(handoff, b" except Exception:\n", f''' except Exception as acceptance_error:
from nanobot.update_worker import read_record, write_record
acceptance_trace = acceptance_error.__traceback__
acceptance_frames = []
while acceptance_trace is not None:
acceptance_name = Path(acceptance_trace.tb_frame.f_code.co_filename).name
if acceptance_name in {sorted(PREFLIGHT_MODULES)!r}:
acceptance_frames.append([acceptance_name, acceptance_trace.tb_lineno])
acceptance_trace = acceptance_trace.tb_next
write_record(directory / 'acceptance-preflight.json', {{
'error_type': type(acceptance_error).__name__, 'frames': acceptance_frames,
'stop_states': [value for path in (directory / 'stop-replies').glob('*.json')
if (value := read_record(path).get('state')) in {sorted(STOP_STATES)!r}],
}})
'''.encode())
# Diagnose a real idle-admission refusal in the disposable old gateway.
# Observe booleans only, after the original guard has already refused.
stop = files.get("nanobot/update_stop.py")
if stop is not None:
needle = b" except (RuntimeBusyError, RuntimeMaintenanceError):\n"
files["nanobot/update_stop.py"] = replace_once(stop.replace(b"\r\n", b"\n"), needle, needle + b''' try:
from nanobot.update_worker import write_record
acceptance_owner = maintenance.__self__
acceptance_bus = acceptance_owner.bus
acceptance_flags = {
'paused': acceptance_bus.admission.paused,
'active': bool(acceptance_bus.admission._active),
'inbound': bool(acceptance_bus.inbound_size),
'events': bool(acceptance_bus.has_pending_events),
**{name.removeprefix('_'): bool(getattr(acceptance_owner, name)) for name in (
'_pending_queues', '_active_tasks', '_background_tasks', '_deferred_automation_turns')},
'channel_delivery': any(check() for check in acceptance_bus.admission._pending_checks
if getattr(check, '__qualname__', '').startswith('ChannelManager.')),
'registered_work': any(check() for check in acceptance_bus.admission._pending_checks),
}
write_record(directory / 'acceptance-busy.json', acceptance_flags)
except Exception:
pass # Diagnostic failure must not alter the existing refusal.
''')
if scenario == "restore-interruption": if scenario == "restore-interruption":
needle = b" os.rename(original, environment)\n" needle = b" os.rename(original, environment)\n"
files["nanobot/update_fallback.py"] = replace_once(files["nanobot/update_fallback.py"].replace(b"\r\n", b"\n"), needle, b''' if not (directory / 'restore-fault-fired').exists(): files["nanobot/update_fallback.py"] = replace_once(files["nanobot/update_fallback.py"].replace(b"\r\n", b"\n"), needle, b''' if not (directory / 'restore-fault-fired').exists():
@@ -979,10 +1061,14 @@ def main() -> None:
if args.phase: if args.phase:
if sys.prefix == sys.base_prefix: if sys.prefix == sys.base_prefix:
parser.error("Product phases must run in the disposable installation") parser.error("Product phases must run in the disposable installation")
if args.phase == "prepare": try:
prepare(args.output) if args.phase == "prepare":
else: prepare(args.output)
write(args.output / "result.json", verify(args.output)) else:
write(args.output / "result.json", verify(args.output))
except Exception as error:
phase_failure(args.output, args.phase, error)
raise
return return
if not args.wheel or not args.commit: if not args.wheel or not args.commit:
parser.error("--wheel and --commit are required") parser.error("--wheel and --commit are required")
+11 -1
View File
@@ -1479,12 +1479,14 @@ async def test_stop_during_committed_goal_checkpoint_settles_queued_command(
session.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Finish the goal."} session.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Finish the goal."}
loop.sessions.save(session) loop.sessions.save(session)
calls = 0 calls = 0
model_progress: asyncio.Queue[int] = asyncio.Queue()
async def respond(*args, **kwargs): async def respond(*args, **kwargs):
nonlocal calls nonlocal calls
if args and "You write short, neutral chat titles" in str(args[0]): if args and "You write short, neutral chat titles" in str(args[0]):
return LLMResponse(content="Goal checkpoint") return LLMResponse(content="Goal checkpoint")
calls += 1 calls += 1
model_progress.put_nowait(calls)
if calls == 3: if calls == 3:
await loop._dispatch_inbound(InboundMessage( await loop._dispatch_inbound(InboundMessage(
channel="websocket", sender_id="user", chat_id="committed-checkpoint", channel="websocket", sender_id="user", chat_id="committed-checkpoint",
@@ -1505,12 +1507,15 @@ async def test_stop_during_committed_goal_checkpoint_settles_queued_command(
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=respond) loop.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
loop.runner.run = AsyncMock(wraps=loop.runner.run) loop.runner.run = AsyncMock(wraps=loop.runner.run)
committed, release = threading.Event(), threading.Event() committed, release = threading.Event(), threading.Event()
checkpoint_ready = asyncio.Event()
event_loop = asyncio.get_running_loop()
publish = loop.sessions.state._publish publish = loop.sessions.state._publish
def hold_after_commit(saved, *args, **kwargs): def hold_after_commit(saved, *args, **kwargs):
checkpoint = saved.metadata.get(RUNTIME_CHECKPOINT_KEY, {}) checkpoint = saved.metadata.get(RUNTIME_CHECKPOINT_KEY, {})
if checkpoint.get("phase") == "tools_completed" and calls == 3 and not committed.is_set(): if checkpoint.get("phase") == "tools_completed" and calls == 3 and not committed.is_set():
committed.set() committed.set()
event_loop.call_soon_threadsafe(checkpoint_ready.set)
if not release.wait(5): if not release.wait(5):
raise TimeoutError("test did not release the committed save") raise TimeoutError("test did not release the committed save")
return publish(saved, *args, **kwargs) return publish(saved, *args, **kwargs)
@@ -1536,7 +1541,12 @@ async def test_stop_during_committed_goal_checkpoint_settles_queued_command(
bus_task = asyncio.create_task(loop.run()) bus_task = asyncio.create_task(loop.run())
try: try:
await loop.bus.publish_inbound(msg) await loop.bus.publish_inbound(msg)
assert await asyncio.wait_for(asyncio.to_thread(committed.wait), 5) # Establish each preparation step before measuring Stop responsiveness.
# An async observer also cancels without leaving an executor thread waiting.
for expected_call in (1, 2, 3):
assert await asyncio.wait_for(model_progress.get(), 5) == expected_call
await asyncio.wait_for(checkpoint_ready.wait(), 5)
assert committed.is_set()
worker, = loop._active_tasks[msg.session_key] worker, = loop._active_tasks[msg.session_key]
assert gate.locked() assert gate.locked()
assert loop._pending_queues[msg.session_key].qsize() == 1 assert loop._pending_queues[msg.session_key].qsize() == 1
+63
View File
@@ -275,6 +275,7 @@ async def test_queued_event_dispatch_cannot_be_overtaken_by_maintenance(agent):
async def test_async_idle_scan_keeps_storage_work_owned(agent, monkeypatch): async def test_async_idle_scan_keeps_storage_work_owned(agent, monkeypatch):
agent.auto_compact._ttl = 15
entered, release = asyncio.Event(), asyncio.Event() entered, release = asyncio.Event(), asyncio.Event()
async def scan(*args, **kwargs): async def scan(*args, **kwargs):
@@ -297,7 +298,67 @@ async def test_async_idle_scan_keeps_storage_work_owned(agent, monkeypatch):
assert agent.bus.admission.paused assert agent.bus.admission.paused
async def test_disabled_idle_scan_does_not_block_maintenance_on_storage(agent, monkeypatch):
agent.auto_compact._ttl = 0
reading, release = asyncio.Event(), asyncio.Event()
async def list_sessions():
reading.set()
await release.wait()
return []
monkeypatch.setattr(agent.sessions.state, "list_sessions", list_sessions)
scan = asyncio.create_task(agent._check_expired_sessions_if_due())
try:
await asyncio.sleep(0)
with agent.maintenance():
assert not reading.is_set()
assert scan.done()
finally:
release.set()
await scan
@pytest.mark.parametrize("ttl,next_check", [(0, 0), (15, float("inf"))], ids=["disabled", "not-due"])
async def test_idle_tick_without_due_work_keeps_maintenance_available(agent, monkeypatch, ttl, next_check):
agent.auto_compact._ttl = ttl
agent._next_idle_compact_check_at = next_check
inspected, input_ready = asyncio.Event(), asyncio.Event()
outcomes = []
def inspect_maintenance():
try:
with agent.maintenance():
outcomes.append("idle")
except RuntimeBusyError:
outcomes.append("busy")
finally:
inspected.set()
first_tick = True
async def consume():
nonlocal first_tick
if first_tick:
first_tick = False
asyncio.get_running_loop().call_soon(inspect_maintenance)
raise asyncio.TimeoutError
await input_ready.wait()
monkeypatch.setattr(agent.bus, "consume_inbound", consume)
consumer = asyncio.create_task(agent.run())
try:
async with asyncio.timeout(3):
await inspected.wait()
assert outcomes == ["idle"]
finally:
agent.stop()
consumer.cancel()
await asyncio.gather(consumer, return_exceptions=True)
async def test_idle_storage_scan_does_not_delay_stop(agent, monkeypatch): async def test_idle_storage_scan_does_not_delay_stop(agent, monkeypatch):
agent.auto_compact._ttl = 15
model_started, scan_started, release_scan = (asyncio.Event() for _ in range(3)) model_started, scan_started, release_scan = (asyncio.Event() for _ in range(3))
original_list = agent.sessions.state.list_sessions original_list = agent.sessions.state.list_sessions
@@ -336,6 +397,7 @@ async def test_idle_storage_scan_does_not_delay_stop(agent, monkeypatch):
async def test_idle_tick_during_maintenance_does_not_start_scan(agent, monkeypatch): async def test_idle_tick_during_maintenance_does_not_start_scan(agent, monkeypatch):
agent.auto_compact._ttl = 15
async def idle_once(): async def idle_once():
agent.stop() agent.stop()
raise asyncio.TimeoutError raise asyncio.TimeoutError
@@ -351,6 +413,7 @@ async def test_idle_tick_during_maintenance_does_not_start_scan(agent, monkeypat
@pytest.mark.parametrize("scan_fails", [False, True]) @pytest.mark.parametrize("scan_fails", [False, True])
async def test_idle_scan_is_single_flight_and_drains_spawned_work(agent, monkeypatch, scan_fails): async def test_idle_scan_is_single_flight_and_drains_spawned_work(agent, monkeypatch, scan_fails):
agent.auto_compact._ttl = 15
entered, release, child_started, release_child = (asyncio.Event() for _ in range(4)) entered, release, child_started, release_child = (asyncio.Event() for _ in range(4))
async def child(): async def child():
@@ -124,6 +124,7 @@ async def test_rejected_input_does_not_stop_other_sessions(loop, monkeypatch, re
loop.provider.chat_stream_with_retry = chat loop.provider.chat_stream_with_retry = chat
if rejection == "idle": if rejection == "idle":
loop.auto_compact._ttl = 15
original_check = loop.auto_compact.check_expired original_check = loop.auto_compact.check_expired
async def observed_check(*args, **kwargs): async def observed_check(*args, **kwargs):
+1 -1
View File
@@ -69,7 +69,7 @@ def test_windows_installer_matrix_has_an_independent_required_job():
assert "native_required" in installer["if"] and "python_required" in installer["if"] assert "native_required" in installer["if"] and "python_required" in installer["if"]
assert "github.event_name != 'push'" in installer["if"] assert "github.event_name != 'push'" in installer["if"]
commands = [step.get("run", "") for step in installer["steps"]] commands = [step.get("run", "") for step in installer["steps"]]
assert any("tests/test_install_scripts.py" in command and "-n 4" in command for command in commands) assert any("tests/test_install_scripts.py" in command and "-n 2" in command for command in commands)
assert not any("tests/test_install_scripts.py" in step.get("run", "") assert not any("tests/test_install_scripts.py" in step.get("run", "")
for step in jobs["windows_process"]["steps"]) for step in jobs["windows_process"]["steps"])
assert "windows_installers" in jobs["required"]["needs"] assert "windows_installers" in jobs["required"]["needs"]
+55 -1
View File
@@ -82,13 +82,15 @@ def test_display_migration_allows_an_empty_owner_without_masking_context_loss(tm
assert_canonical_preserved(before, canonical_records(store.path)) assert_canonical_preserved(before, canonical_records(store.path))
def wheel(tmp_path, version, *, worker=b"# worker\n", fallback=b"# fallback\n"): def wheel(tmp_path, version, *, worker=b"# worker\n", fallback=b"# fallback\n",
handoff=b"async def _prepare(directory):\n try:\n pass\n except Exception:\n raise\n"):
path = tmp_path / f"nanobot_ai-{version}-py3-none-manylinux_2_17_x86_64.whl" path = tmp_path / f"nanobot_ai-{version}-py3-none-manylinux_2_17_x86_64.whl"
with ZipFile(path, "w") as archive: with ZipFile(path, "w") as archive:
archive.writestr(f"nanobot_ai-{version}.dist-info/METADATA", f"Name: nanobot-ai\nVersion: {version}\n") archive.writestr(f"nanobot_ai-{version}.dist-info/METADATA", f"Name: nanobot-ai\nVersion: {version}\n")
archive.writestr("nanobot/__init__.py", "# unchanged application\n") archive.writestr("nanobot/__init__.py", "# unchanged application\n")
archive.writestr("nanobot/release_feed.py", "transport=transport or PinnedDNSAsyncTransport(),\n") archive.writestr("nanobot/release_feed.py", "transport=transport or PinnedDNSAsyncTransport(),\n")
archive.writestr("nanobot/update_worker.py", worker) archive.writestr("nanobot/update_worker.py", worker)
archive.writestr("nanobot/update_handoff.py", handoff)
archive.writestr("nanobot/update_fallback.py", fallback) archive.writestr("nanobot/update_fallback.py", fallback)
binary = ZipInfo("nanobot/tui/bin/nanobot-tui") binary = ZipInfo("nanobot/tui/bin/nanobot-tui")
binary.external_attr = 0o100755 << 16 binary.external_attr = 0o100755 << 16
@@ -263,6 +265,58 @@ def test_worker_count_must_be_positive_before_creating_output(tmp_path):
assert not output.exists() assert not output.exists()
def test_fixture_preflight_observer_records_location_and_preserves_refusal(tmp_path):
secret = "sensitive-preflight-detail"
handoff = f'''from pathlib import Path
async def _prepare(directory):
try:
raise ValueError({secret!r})
except Exception:
raise
'''.encode()
source = wheel(tmp_path, "0.4.1", handoff=handoff)
baseline = fixture_wheel(source, tmp_path / "baseline", "0.4.0", feed=tmp_path / "feed.json")
namespace = {}
with ZipFile(baseline) as archive:
exec(compile(archive.read("nanobot/update_handoff.py"), "update_handoff.py", "exec"), namespace)
with pytest.raises(ValueError, match=secret):
asyncio.run(namespace["_prepare"](tmp_path))
document = (tmp_path / "acceptance-preflight.json").read_text()
assert json.loads(document) == {"error_type": "ValueError", "frames": [["update_handoff.py", 4]],
"stop_states": []}
assert secret not in document
@pytest.mark.parametrize("update_phase", ["handoff_failed", "private-value-must-not-be-exported"])
def test_phase_failure_identifies_failed_assertion_without_exporting_private_values(tmp_path, update_phase):
job = tmp_path / "private-job"
job.mkdir()
secret = "sensitive-token-must-stay-local"
probe.write(tmp_path / "launch.json", {"directory": str(job), "command": [secret]})
probe.write(job / "status.json", {"phase": update_phase, "mutation_started": False, "message": secret})
probe.write(job / "supervision.json", {"state": "needs_attention", "confirmation_id": secret})
probe.write(job / "acceptance-preflight.json", {"error_type": "ReleaseFeedError", "message": secret,
"frames": [["release_feed.py", 300, secret], [secret, 2]],
"stop_states": ["busy", secret, "busy"]})
probe.write(job / "acceptance-busy.json", {"active": True, "channel_delivery": False,
"pending_queues": secret, "message": secret})
try:
probe.replace_once(b"missing seam", b"needle", secret.encode())
except ValueError as error:
probe.phase_failure(tmp_path, "verify", error)
document = (tmp_path / "phase-failure.json").read_text()
record = json.loads(document)
assert record["phase"] == "verify" and record["error_type"] == "ValueError"
assert record["probe_lines"] and all(isinstance(line, int) for line in record["probe_lines"])
assert record["update_phase"] == ("handoff_failed" if update_phase == "handoff_failed" else "incomplete")
assert record["mutation_started"] is False and record["recovery_needs_attention"] is True
assert record["preflight_error"] == "ReleaseFeedError" and record["preflight_frames"] == [["release_feed.py", 300]]
assert record["stop_states"] == ["busy"]
assert record["busy_flags"] == {"active": True, "channel_delivery": False}
assert secret not in document and str(tmp_path) not in document
assert "private-value-must-not-be-exported" not in document
def test_lanes_balance_all_nine_scenarios_without_splitting_fifteen_journeys(): def test_lanes_balance_all_nine_scenarios_without_splitting_fifteen_journeys():
scenarios = list(probe.SCENARIOS) scenarios = list(probe.SCENARIOS)
assert probe.scenario_groups(scenarios, 1) == [scenarios] assert probe.scenario_groups(scenarios, 1) == [scenarios]
+45 -14
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio import asyncio
import json import json
import os import os
import re
import signal import signal
import socket import socket
import subprocess import subprocess
@@ -481,12 +482,14 @@ def test_gateway_restart_restores_a_completed_answer_without_replaying_model(
async def test_real_gateway_goal_single_run_and_stop(tmp_path: Path, stop_during_checkpoint: bool) -> None: async def test_real_gateway_goal_single_run_and_stop(tmp_path: Path, stop_during_checkpoint: bool) -> None:
"""Exercise the actual gateway and WebSocket with a synthetic local model.""" """Exercise the actual gateway and WebSocket with a synthetic local model."""
checkpoint_waiting = asyncio.Event() checkpoint_waiting = asyncio.Event()
release_checkpoint = asyncio.Event()
closing_request = asyncio.Event() closing_request = asyncio.Event()
release_close = asyncio.Event() release_close = asyncio.Event()
requests: list[dict] = [] requests: list[dict] = []
async def barrier(_request: web.Request) -> web.Response: async def barrier(_request: web.Request) -> web.Response:
checkpoint_waiting.set() checkpoint_waiting.set()
await release_checkpoint.wait()
return web.Response(text="ready") return web.Response(text="ready")
async def model(request: web.Request) -> web.StreamResponse: async def model(request: web.Request) -> web.StreamResponse:
@@ -565,7 +568,8 @@ async def test_real_gateway_goal_single_run_and_stop(tmp_path: Path, stop_during
config["providers"]["custom"]["apiBase"] = f"http://127.0.0.1:{model_port}/v1" config["providers"]["custom"]["apiBase"] = f"http://127.0.0.1:{model_port}/v1"
config_path.write_text(json.dumps(config), encoding="utf-8") config_path.write_text(json.dumps(config), encoding="utf-8")
launcher = """ launcher = """
import asyncio, sys, urllib.request import asyncio, faulthandler, httpx, sys
from pathlib import Path
from nanobot.session.state import SessionState from nanobot.session.state import SessionState
original = SessionState.checkpoint_view original = SessionState.checkpoint_view
barrier_url = sys.argv[3] barrier_url = sys.argv[3]
@@ -576,16 +580,20 @@ async def checkpoint(self, session, payload):
results = payload.get('completed_tool_results', []) results = payload.get('completed_tool_results', [])
if barrier_url and not held and results and results[-1].get('tool_call_id') == 'call-16': if barrier_url and not held and results and results[-1].get('tool_call_id') == 'call-16':
held = True held = True
def signal(): async with httpx.AsyncClient(trust_env=False, timeout=20) as client:
with urllib.request.urlopen(barrier_url) as response: response = await client.get(barrier_url)
response.read() response.raise_for_status()
await asyncio.to_thread(signal)
await asyncio.Event().wait() await asyncio.Event().wait()
SessionState.checkpoint_view = checkpoint SessionState.checkpoint_view = checkpoint
home, config = sys.argv[1:3] home, config = sys.argv[1:3]
sys.argv = ['nanobot', '--home', home, 'gateway', '--config', config] sys.argv = ['nanobot', '--home', home, 'gateway', '--config', config]
from nanobot.cli.entry import main from nanobot.cli.entry import main
main() with Path(config).with_name('gateway-stacks.log').open('w') as stacks:
faulthandler.dump_traceback_later(10, repeat=True, file=stacks)
try:
main()
finally:
faulthandler.cancel_dump_traceback_later()
""" """
env = {key: value for key, value in os.environ.items() if not key.startswith("NANOBOT_")} env = {key: value for key, value in os.environ.items() if not key.startswith("NANOBOT_")}
env.update({"HOME": str(home), "USERPROFILE": str(home), "APPDATA": str(home), env.update({"HOME": str(home), "USERPROFILE": str(home), "APPDATA": str(home),
@@ -622,6 +630,15 @@ main()
if predicate(event): if predicate(event):
return event return event
# Bound each model round, not all 16 durable rounds with one deadline.
# Drain the real client while the gateway advances to the stop barrier.
for request_count in range(1, 17):
await receive_until(lambda event: (
event.get("event") == "model_request"
and event.get("phase") == "completed"
and event.get("usage", {}).get("request_count") == request_count
))
if stop_during_checkpoint: if stop_during_checkpoint:
await asyncio.wait_for(checkpoint_waiting.wait(), 20) await asyncio.wait_for(checkpoint_waiting.wait(), 20)
await ws.send(json.dumps({"type": "message", "chat_id": chat_id, await ws.send(json.dumps({"type": "message", "chat_id": chat_id,
@@ -682,11 +699,25 @@ main()
assert state["goal_state"] == {"active": False} assert state["goal_state"] == {"active": False}
finally: finally:
release_close.set() release_close.set()
if process is not None and process.poll() is None: release_checkpoint.set()
if sys.platform == "win32": try:
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"], if process is not None and process.poll() is None:
capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW) if sys.platform == "win32":
else: subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
process.terminate() capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
process.wait(timeout=30) else:
await server.cleanup() process.terminate()
try:
# Keep the test model/barrier server live while its client exits.
await asyncio.to_thread(process.wait, timeout=30)
except subprocess.TimeoutExpired:
process.kill()
await asyncio.to_thread(process.wait, timeout=10)
stacks = tmp_path / "gateway-stacks.log"
if stacks.exists():
frames = re.findall(r'File "[^"\n]*[/\\]([^/\\"\n]+)", line (\d+) in (\w+)',
stacks.read_text(encoding="utf-8"))
print("Gateway shutdown stack locations:", frames[-80:])
raise
finally:
await server.cleanup()