feat(update): integrate managed installs and recoverable in-app updates (#6168)
Add owner-aware Stable and Preview updates with explicit consent, verified release plans, protected process handoff and bounded service recovery. Keep configuration and conversations separate from program rollback. Include the compact About controls, Windows long-path support, native package recovery checks and optional macOS Dock lifecycle integration. Preserve documented guidance for installations owned by other managers. This code integration does not publish packages, enable signing or advance the public update channel. Co-authored-by: chengyongru <61816729+chengyongru@users.noreply.github.com>
This commit is contained in:
1 parent
76da55994b
commit
fbb61a373f
216 files changed
+27948
-1084
No files matched your search
@@ -196,7 +196,7 @@ class TestHistoryWithCursor:
|
||||
assert [entry["cursor"] for entry in entries] == list(range(21, 101))
|
||||
|
||||
def test_write_entries_uses_atomic_write(self, tmp_path):
|
||||
"""_write_entries uses temp file + os.replace for atomicity."""
|
||||
"""_write_entries uses a temporary file and atomic replacement."""
|
||||
store = MemoryStore(tmp_path)
|
||||
store.append_history("event 1")
|
||||
store.append_history("event 2")
|
||||
@@ -221,11 +221,11 @@ class TestHistoryWithCursor:
|
||||
store.append_history("event 1")
|
||||
entries = store.read_unprocessed_history(since_cursor=0)
|
||||
|
||||
# Mock os.replace to raise an exception
|
||||
# Fail the platform-independent replacement boundary.
|
||||
def failing_replace(*args, **kwargs):
|
||||
raise RuntimeError("Simulated failure")
|
||||
|
||||
monkeypatch.setattr('os.replace', failing_replace)
|
||||
monkeypatch.setattr('nanobot.utils.atomic_file.replace_atomic', failing_replace)
|
||||
|
||||
with pytest.raises(RuntimeError):
|
||||
store._write_entries(entries)
|
||||
|
||||
@@ -0,0 +1,574 @@
|
||||
"""Gateway task admission, without installing packages or contacting a model."""
|
||||
|
||||
import asyncio
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.runner import AgentRunResult
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.runtime_events import RuntimeModelChanged
|
||||
from nanobot.cron.service import CronService
|
||||
from nanobot.cron.types import CronSchedule
|
||||
from nanobot.providers.base import LLMResponse
|
||||
from nanobot.runtime_admission import RuntimeBusyError, RuntimeMaintenanceError
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
from nanobot.triggers.local_runner import run_local_trigger_queue
|
||||
from nanobot.triggers.local_store import LocalTriggerStore
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def agent(loop_factory):
|
||||
loop = loop_factory()
|
||||
loop.provider.provider_name = "test"
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="done"))
|
||||
loop.provider.can_resume_conversation_state.return_value = False
|
||||
loop.provider.aclose = AsyncMock()
|
||||
try:
|
||||
yield loop
|
||||
finally:
|
||||
loop.stop()
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
def message(content="hello", *, kind=None):
|
||||
metadata = {}
|
||||
if kind == "cron":
|
||||
metadata = {"_cron_trigger": {"job_id": "job", "run_id": "run"}}
|
||||
elif kind == "trigger":
|
||||
metadata = {"_local_trigger": {"trigger_id": "trigger", "delivery_id": "delivery"}}
|
||||
return InboundMessage("cli", "user", "direct", content, metadata=metadata)
|
||||
|
||||
|
||||
async def settle(agent):
|
||||
async with asyncio.timeout(3):
|
||||
while agent._has_pending_work():
|
||||
await asyncio.sleep(0)
|
||||
|
||||
|
||||
async def test_idle_maintenance_refuses_new_work_and_abort_restores_it(agent):
|
||||
background = asyncio.sleep(0)
|
||||
with pytest.raises(ValueError, match="abort"):
|
||||
with agent.maintenance():
|
||||
with pytest.raises(RuntimeMaintenanceError):
|
||||
await agent.bus.publish_inbound(message())
|
||||
with pytest.raises(RuntimeMaintenanceError):
|
||||
await agent.process_direct("not accepted")
|
||||
with pytest.raises(RuntimeMaintenanceError):
|
||||
await agent.discard_session("cli:direct")
|
||||
with pytest.raises(RuntimeMaintenanceError):
|
||||
await agent.submit_cron_turn(message(kind="cron"))
|
||||
with pytest.raises(RuntimeMaintenanceError):
|
||||
await agent.submit_local_trigger_turn(message(kind="trigger"))
|
||||
with pytest.raises(RuntimeMaintenanceError):
|
||||
await agent.subagents.spawn("not accepted")
|
||||
with pytest.raises(RuntimeMaintenanceError):
|
||||
agent.schedule_background(background)
|
||||
assert inspect.getcoroutinestate(background) == inspect.CORO_CLOSED
|
||||
assert agent.bus.inbound_size == 0
|
||||
assert not agent._pending_queues
|
||||
assert agent.sessions.get_existing("cli:direct") is None
|
||||
# A duplicate attempt must not reopen the first maintenance window.
|
||||
with pytest.raises(RuntimeMaintenanceError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("duplicate maintenance was admitted")
|
||||
assert agent.bus.admission.paused
|
||||
raise ValueError("abort")
|
||||
assert not agent.bus.admission.paused
|
||||
response = await agent.process_direct("accepted after abort")
|
||||
assert response.content == "done"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cancel", [False, True])
|
||||
async def test_direct_turn_including_final_notification_stays_busy(agent, cancel):
|
||||
entered, release, notifying, notified = (asyncio.Event() for _ in range(4))
|
||||
|
||||
async def reply(*args, **kwargs):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return LLMResponse(content="done")
|
||||
|
||||
original = agent.runtime_event_publisher.run_status_changed
|
||||
|
||||
async def notify(msg, key, status, *args, **kwargs):
|
||||
if status == "idle":
|
||||
notifying.set()
|
||||
await notified.wait()
|
||||
await original(msg, key, status, *args, **kwargs)
|
||||
|
||||
agent.provider.chat_stream_with_retry.side_effect = reply
|
||||
agent.runtime_event_publisher.run_status_changed = notify
|
||||
task = asyncio.create_task(agent.process_direct("work"))
|
||||
try:
|
||||
async with asyncio.timeout(3):
|
||||
await entered.wait()
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("active direct turn was missed")
|
||||
assert not agent.bus.admission.paused
|
||||
assert not task.done()
|
||||
if cancel:
|
||||
task.cancel()
|
||||
else:
|
||||
release.set()
|
||||
await notifying.wait()
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("final notification was missed")
|
||||
notified.set()
|
||||
if cancel:
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
else:
|
||||
await task
|
||||
await settle(agent)
|
||||
with agent.maintenance():
|
||||
assert agent.bus.admission.paused
|
||||
finally:
|
||||
release.set()
|
||||
notified.set()
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
|
||||
|
||||
async def test_dequeue_and_inline_dispatch_have_no_false_idle_gap(agent, monkeypatch):
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
outcomes = []
|
||||
consume = agent.bus.consume_inbound
|
||||
|
||||
def attempt_maintenance():
|
||||
try:
|
||||
with agent.maintenance():
|
||||
outcomes.append("incorrectly idle")
|
||||
except RuntimeBusyError:
|
||||
outcomes.append("busy")
|
||||
|
||||
async def dequeue():
|
||||
msg = await consume()
|
||||
asyncio.get_running_loop().call_soon(attempt_maintenance)
|
||||
return msg
|
||||
|
||||
async def accept(*args, **kwargs):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
|
||||
monkeypatch.setattr(agent.bus, "consume_inbound", dequeue)
|
||||
monkeypatch.setattr(agent.runtime_event_publisher, "user_input_accepted", accept)
|
||||
await agent.bus.publish_inbound(message())
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("queued message was missed")
|
||||
consumer = asyncio.create_task(agent.run())
|
||||
try:
|
||||
async with asyncio.timeout(3):
|
||||
await entered.wait()
|
||||
await asyncio.sleep(0)
|
||||
assert outcomes == ["busy"]
|
||||
assert agent.bus.inbound_size == 0
|
||||
assert not agent._active_tasks
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("inline acceptance was missed")
|
||||
release.set()
|
||||
await agent.bus.consume_outbound()
|
||||
await settle(agent)
|
||||
with agent.maintenance():
|
||||
assert agent.bus.admission.paused
|
||||
finally:
|
||||
release.set()
|
||||
consumer.cancel()
|
||||
await asyncio.gather(consumer, return_exceptions=True)
|
||||
|
||||
|
||||
async def test_rejected_input_keeps_failure_delivery_owned(agent, monkeypatch):
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def reject(msg):
|
||||
raise SessionConflictError("session changed before admission")
|
||||
|
||||
async def fail(**kwargs):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
|
||||
monkeypatch.setattr(agent, "_dispatch_inbound", reject)
|
||||
monkeypatch.setattr(agent.turn_delivery_factory, "unrouted",
|
||||
lambda *args: SimpleNamespace(fail=fail))
|
||||
await agent.bus.publish_inbound(message())
|
||||
consumer = asyncio.create_task(agent.run())
|
||||
try:
|
||||
async with asyncio.timeout(3):
|
||||
await entered.wait()
|
||||
assert agent.bus.inbound_size == 0
|
||||
assert not agent._active_tasks
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("failure notification was interrupted by maintenance")
|
||||
finally:
|
||||
release.set()
|
||||
consumer.cancel()
|
||||
await asyncio.gather(consumer, return_exceptions=True)
|
||||
|
||||
|
||||
async def test_scheduled_background_work_blocks_before_it_starts(agent):
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def work():
|
||||
entered.set()
|
||||
await release.wait()
|
||||
|
||||
agent.schedule_background(work())
|
||||
try:
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("scheduled task was missed")
|
||||
async with asyncio.timeout(3):
|
||||
await entered.wait()
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("running task was missed")
|
||||
finally:
|
||||
release.set()
|
||||
await settle(agent)
|
||||
with agent.maintenance():
|
||||
await agent._check_expired_sessions_if_due()
|
||||
assert not agent._background_tasks
|
||||
|
||||
|
||||
async def test_queued_event_dispatch_cannot_be_overtaken_by_maintenance(agent):
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
background_finished = asyncio.Event()
|
||||
|
||||
async def background():
|
||||
background_finished.set()
|
||||
|
||||
async def observe(event):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
agent.schedule_background(background())
|
||||
|
||||
disconnect = agent.bus.subscribe(observe, RuntimeModelChanged)
|
||||
agent.bus.publish_nowait(RuntimeModelChanged("test-model", None))
|
||||
try:
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("queued event was missed")
|
||||
async with asyncio.timeout(3):
|
||||
await entered.wait()
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("awaiting subscriber was missed")
|
||||
finally:
|
||||
release.set()
|
||||
await agent.bus.drain()
|
||||
await settle(agent)
|
||||
disconnect()
|
||||
with agent.maintenance():
|
||||
assert background_finished.is_set()
|
||||
assert not agent.bus.has_pending_events
|
||||
|
||||
|
||||
async def test_async_idle_scan_keeps_storage_work_owned(agent, monkeypatch):
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def scan(*args, **kwargs):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
|
||||
monkeypatch.setattr(agent.auto_compact, "check_expired", scan)
|
||||
agent._next_idle_compact_check_at = 0
|
||||
task = asyncio.create_task(agent._check_expired_sessions_if_due())
|
||||
try:
|
||||
async with asyncio.timeout(3):
|
||||
await entered.wait()
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("SQLite idle scan was mistaken for an idle runtime")
|
||||
finally:
|
||||
release.set()
|
||||
await task
|
||||
with agent.maintenance():
|
||||
assert agent.bus.admission.paused
|
||||
|
||||
|
||||
async def test_cancelled_exec_startup_stays_busy_until_cleanup_finishes(agent, tmp_path, monkeypatch):
|
||||
manager = agent._exec_session_manager
|
||||
entered, cancelling, release = (asyncio.Event() for _ in range(3))
|
||||
|
||||
async def spawn(*args, **kwargs):
|
||||
entered.set()
|
||||
try:
|
||||
await asyncio.Future()
|
||||
finally:
|
||||
cancelling.set()
|
||||
await release.wait()
|
||||
|
||||
monkeypatch.setattr(manager, "_spawn", spawn)
|
||||
task = asyncio.create_task(manager.start(
|
||||
command=[sys.executable, "-c", "pass"], cwd=str(tmp_path), env=dict(os.environ),
|
||||
timeout=10, shell_program=None, login=False, yield_time_ms=0,
|
||||
max_output_chars=1000, owner_session_key="cli:direct",
|
||||
))
|
||||
stop = None
|
||||
try:
|
||||
async with asyncio.timeout(3):
|
||||
await entered.wait()
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("launch reservation was missed")
|
||||
stop = asyncio.create_task(manager.terminate_by_owner("cli:direct"))
|
||||
async with asyncio.timeout(3):
|
||||
await cancelling.wait()
|
||||
assert not manager._starting
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("cancelled launch cleanup was missed")
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.gather(task, *([stop] if stop is not None else []), return_exceptions=True)
|
||||
with agent.maintenance():
|
||||
assert not manager.has_pending_work
|
||||
|
||||
|
||||
async def test_detached_real_exec_blocks_maintenance_without_being_killed(agent, tmp_path):
|
||||
manager = agent._exec_session_manager
|
||||
session_id, result = await manager.start(
|
||||
command=[sys.executable, "-I", "-c", "import sys; print('ready', flush=True); sys.stdin.readline()"],
|
||||
cwd=str(tmp_path), env=dict(os.environ), timeout=10, shell_program=None,
|
||||
login=False, yield_time_ms=100, max_output_chars=1000, owner_session_key="cli:direct",
|
||||
)
|
||||
assert not result.done
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("detached command was missed")
|
||||
assert (await manager.list(owner_session_key="cli:direct"))[0].returncode is None
|
||||
result = await manager.write(
|
||||
session_id=session_id, chars="finish\n", close_stdin=False, terminate=False,
|
||||
yield_time_ms=3000, max_output_chars=1000, owner_session_key="cli:direct",
|
||||
)
|
||||
assert result.done and result.exit_code == 0 and result.finish_reason == "exit"
|
||||
with agent.maintenance():
|
||||
assert not manager.has_pending_work
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation", ["close_all", "terminate_by_owner", "discard_session"])
|
||||
async def test_exec_cleanup_is_owned_through_failure_and_retry(agent, tmp_path, monkeypatch, operation):
|
||||
manager = agent._exec_session_manager
|
||||
session_id, _ = await manager.start(
|
||||
command=[sys.executable, "-I", "-c", "import sys; sys.stdin.readline()"],
|
||||
cwd=str(tmp_path), env=dict(os.environ), timeout=10, shell_program=None,
|
||||
login=False, yield_time_ms=0, max_output_chars=1000, owner_session_key="cli:direct",
|
||||
)
|
||||
session = manager._sessions[session_id]
|
||||
original = session._kill
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
fail = True
|
||||
|
||||
async def cleanup():
|
||||
entered.set()
|
||||
await release.wait()
|
||||
await original()
|
||||
if fail:
|
||||
raise OSError("cleanup was not confirmed")
|
||||
|
||||
async def terminate():
|
||||
if operation == "close_all":
|
||||
await manager.close_all()
|
||||
elif operation == "terminate_by_owner":
|
||||
await manager.terminate_by_owner("cli:direct")
|
||||
else:
|
||||
await agent.discard_session("cli:direct")
|
||||
|
||||
monkeypatch.setattr(session, "_kill", cleanup)
|
||||
task = asyncio.create_task(terminate())
|
||||
try:
|
||||
async with asyncio.timeout(3):
|
||||
await entered.wait()
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("in-flight process cleanup was missed")
|
||||
release.set()
|
||||
with pytest.raises(OSError, match="cleanup was not confirmed"):
|
||||
await task
|
||||
# An exited parent alone cannot prove that failed process-tree cleanup settled.
|
||||
assert session.process.returncode is not None
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("failed cleanup was treated as idle")
|
||||
fail = False
|
||||
await terminate()
|
||||
with agent.maintenance():
|
||||
assert not manager.has_pending_work
|
||||
finally:
|
||||
fail = False
|
||||
release.set()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
await manager.close_all()
|
||||
|
||||
|
||||
async def test_cancelled_exec_close_keeps_unfinished_cleanup_owned(agent, tmp_path, monkeypatch):
|
||||
manager = agent._exec_session_manager
|
||||
session_id, _ = await manager.start(
|
||||
command=[sys.executable, "-I", "-c", "import sys; sys.stdin.readline()"],
|
||||
cwd=str(tmp_path), env=dict(os.environ), timeout=10, shell_program=None,
|
||||
login=False, yield_time_ms=0, max_output_chars=1000, owner_session_key="cli:direct",
|
||||
)
|
||||
session = manager._sessions[session_id]
|
||||
original = session._kill
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def cleanup():
|
||||
entered.set()
|
||||
await release.wait()
|
||||
await original()
|
||||
|
||||
monkeypatch.setattr(session, "_kill", cleanup)
|
||||
task = asyncio.create_task(manager.close_all())
|
||||
try:
|
||||
async with asyncio.timeout(3):
|
||||
await entered.wait()
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("cancelled close lost its still-running cleanup")
|
||||
release.set()
|
||||
await manager.close_all()
|
||||
with agent.maintenance():
|
||||
assert not manager.has_pending_work
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
await manager.close_all()
|
||||
|
||||
|
||||
async def test_subagent_execution_and_cleanup_are_both_busy(agent, monkeypatch):
|
||||
manager = agent.subagents
|
||||
manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="finished"))
|
||||
runtime = LLMRuntime.capture(agent.provider, "test-model", context_window_tokens=4096)
|
||||
await manager.spawn("child", runtime=runtime)
|
||||
record = next(iter(manager._tasks.values()))
|
||||
cleaning, release = asyncio.Event(), asyncio.Event()
|
||||
original = record.exec_manager.close_all
|
||||
|
||||
async def cleanup():
|
||||
cleaning.set()
|
||||
await release.wait()
|
||||
return await original()
|
||||
|
||||
monkeypatch.setattr(record.exec_manager, "close_all", cleanup)
|
||||
try:
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("subagent was missed")
|
||||
async with asyncio.timeout(3):
|
||||
await cleaning.wait()
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("subagent cleanup was missed")
|
||||
finally:
|
||||
release.set()
|
||||
await manager.close()
|
||||
await agent.bus.drain()
|
||||
assert not manager.has_pending_work
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stop", [False, True])
|
||||
async def test_cron_timer_waits_without_consuming_and_manual_run_is_refused(agent, tmp_path, stop):
|
||||
ran = asyncio.Event()
|
||||
|
||||
async def callback(job):
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("cron callback was missed")
|
||||
ran.set()
|
||||
|
||||
cron = CronService(tmp_path / "cron/jobs.json", callback, admission=agent.bus.admission)
|
||||
await cron.start()
|
||||
job = cron.add_job(
|
||||
name="scheduled", schedule=CronSchedule(kind="every", every_ms=3600000),
|
||||
message="work", session_key="websocket:test", origin_channel="websocket",
|
||||
origin_chat_id="test",
|
||||
)
|
||||
timer = None
|
||||
try:
|
||||
with agent.maintenance():
|
||||
job.state.next_run_at_ms = 1
|
||||
cron._save_store()
|
||||
before = cron.store_path.read_bytes()
|
||||
cron._arm_timer()
|
||||
timer = cron._timer_task
|
||||
await asyncio.sleep(0)
|
||||
await asyncio.sleep(0)
|
||||
assert not ran.is_set() and not timer.done()
|
||||
with pytest.raises(RuntimeMaintenanceError):
|
||||
await cron.run_job(job.id, force=True)
|
||||
assert cron.store_path.read_bytes() == before
|
||||
if stop:
|
||||
cron.stop()
|
||||
await asyncio.gather(timer, return_exceptions=True)
|
||||
if stop:
|
||||
assert not ran.is_set()
|
||||
else:
|
||||
# A user may abort and immediately retry before this waiter resumes.
|
||||
with agent.maintenance():
|
||||
await asyncio.sleep(0)
|
||||
assert not ran.is_set() and not timer.done()
|
||||
assert cron.store_path.read_bytes() == before
|
||||
async with asyncio.timeout(3):
|
||||
await ran.wait()
|
||||
# The scheduler cancels its previous timer when rearming itself.
|
||||
await asyncio.gather(timer, return_exceptions=True)
|
||||
assert len(cron.get_job(job.id).state.run_history) == 1
|
||||
assert cron._timer_task is not timer and not cron._timer_task.done()
|
||||
finally:
|
||||
timer = cron._timer_task
|
||||
cron.stop()
|
||||
if timer is not None:
|
||||
await asyncio.gather(timer, return_exceptions=True)
|
||||
|
||||
|
||||
async def test_trigger_intake_does_not_claim_until_maintenance_released(agent, tmp_path):
|
||||
store = LocalTriggerStore(tmp_path)
|
||||
trigger = store.create(name="test", channel="cli", chat_id="test", session_key="cli:test")
|
||||
delivery = store.enqueue(trigger.id, "work")
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def submit(msg):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
|
||||
worker = None
|
||||
try:
|
||||
with agent.maintenance():
|
||||
worker = asyncio.create_task(run_local_trigger_queue(
|
||||
store=store, submit_turn=submit, is_channel_enabled=lambda name: True,
|
||||
poll_interval_s=0.01, admission=agent.bus.admission,
|
||||
))
|
||||
await asyncio.sleep(0)
|
||||
assert not entered.is_set()
|
||||
assert len(list(store.inbox_dir.glob("*.json"))) == 1
|
||||
assert not list(store.processing_dir.glob("*.json"))
|
||||
async with asyncio.timeout(3):
|
||||
await entered.wait()
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with agent.maintenance():
|
||||
pytest.fail("claimed trigger batch was missed")
|
||||
release.set()
|
||||
path = store.runs_dir / f"{delivery.id}.json"
|
||||
while json.loads(path.read_text())["status"] != "ok":
|
||||
await asyncio.sleep(0)
|
||||
with agent.maintenance():
|
||||
assert not list(store.inbox_dir.glob("*.json"))
|
||||
finally:
|
||||
release.set()
|
||||
if worker is not None:
|
||||
worker.cancel()
|
||||
await asyncio.gather(worker, return_exceptions=True)
|
||||
@@ -185,6 +185,9 @@ async def test_default_loop_keeps_slack_thread_for_late_subagent_result(
|
||||
tmp_path, monkeypatch, cache_invalidation,
|
||||
):
|
||||
monkeypatch.setattr("nanobot.agent.loop._SUBAGENT_TERMINAL_WAIT_SECONDS", 0.01)
|
||||
# This checks real default-runtime routing and persistence, not disk latency.
|
||||
# Keep bounded waits without treating a loaded Windows runner as a routing failure.
|
||||
timeout = 30
|
||||
child_started, release_child, parent_idle = (asyncio.Event() for _ in range(3))
|
||||
|
||||
class Provider(LLMProvider):
|
||||
@@ -229,7 +232,7 @@ async def test_default_loop_keeps_slack_thread_for_late_subagent_result(
|
||||
unsubscribe = bus.subscribe(observe_idle, TurnRunStatusChanged)
|
||||
|
||||
async def next_reply(content):
|
||||
async with asyncio.timeout(5):
|
||||
async with asyncio.timeout(timeout):
|
||||
while True:
|
||||
message = await bus.consume_outbound()
|
||||
if message.content == content and message.event is None:
|
||||
@@ -242,8 +245,8 @@ async def test_default_loop_keeps_slack_thread_for_late_subagent_result(
|
||||
metadata={"slack": slack_route}, session_key_override=session_key,
|
||||
))
|
||||
initial_reply = await next_reply("Parent reply")
|
||||
await asyncio.wait_for(child_started.wait(), timeout=5)
|
||||
await asyncio.wait_for(parent_idle.wait(), timeout=5)
|
||||
await asyncio.wait_for(child_started.wait(), timeout=timeout)
|
||||
await asyncio.wait_for(parent_idle.wait(), timeout=timeout)
|
||||
saved = SessionManager(workspace, sessions_root=sessions_root).get_existing(session_key)
|
||||
assert saved is not None
|
||||
saved_route = saved.metadata["_compaction_route"]
|
||||
@@ -263,8 +266,10 @@ async def test_default_loop_keeps_slack_thread_for_late_subagent_result(
|
||||
finally:
|
||||
release_child.set()
|
||||
loop.stop()
|
||||
await asyncio.wait_for(consumer, timeout=2)
|
||||
unsubscribe()
|
||||
try:
|
||||
await asyncio.wait_for(consumer, timeout=timeout)
|
||||
finally:
|
||||
unsubscribe()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -11,6 +11,34 @@ import pytest
|
||||
from scripts.check_import_boundaries import Violation, find_violations
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", [
|
||||
"nanobot.agent.loop", "nanobot.session.state", "nanobot.runtime_admission",
|
||||
"nanobot.data_access", "nanobot.installation_lock",
|
||||
])
|
||||
def test_runtime_owners_do_not_depend_on_update_policy(module: str) -> None:
|
||||
assert find_violations("from nanobot.update_service import UpdateService", module) == [
|
||||
Violation("update-policy-direction", "nanobot.update_service.UpdateService", 1),
|
||||
]
|
||||
|
||||
|
||||
def test_updater_uses_process_contracts_not_agent_or_client_implementations() -> None:
|
||||
assert find_violations("from nanobot.agent.loop import AgentLoop", "nanobot.update_stop") == [
|
||||
Violation("update-domain", "nanobot.agent.loop.AgentLoop", 1),
|
||||
]
|
||||
assert find_violations(
|
||||
"from nanobot.gateway.runtime import GatewayRuntime", "nanobot.update_stop",
|
||||
) == []
|
||||
assert find_violations(
|
||||
"from nanobot.update_stop import watch_gateway_stop", "nanobot.cli.gateway_runtime",
|
||||
) == []
|
||||
assert find_violations(
|
||||
"from nanobot.cli.gateway_runtime import _run_gateway", "nanobot.update_restart",
|
||||
) == []
|
||||
assert find_violations(
|
||||
"from nanobot.agent.loop import AgentLoop", "nanobot.update_restart",
|
||||
) == [Violation("update-restart-adapter", "nanobot.agent.loop.AgentLoop", 1)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("source", "target", "line"),
|
||||
[
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels import manager as manager_module
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.runtime_admission import RuntimeBusyError
|
||||
|
||||
|
||||
def make_manager():
|
||||
@@ -15,10 +18,66 @@ def make_manager():
|
||||
channel = MagicMock(spec=BaseChannel)
|
||||
channel.send = AsyncMock()
|
||||
channel.stop = AsyncMock()
|
||||
channel.has_pending_delivery = False
|
||||
manager.channels["websocket"] = channel
|
||||
return manager, channel
|
||||
|
||||
|
||||
async def test_delivery_has_no_idle_gap_between_queue_dispatch_and_send(monkeypatch):
|
||||
manager, channel = make_manager()
|
||||
started, release = asyncio.Event(), asyncio.Event()
|
||||
observations = []
|
||||
consume = manager.bus.consume_outbound
|
||||
|
||||
def require_busy():
|
||||
if manager.bus.admission.paused:
|
||||
observations.append("parked")
|
||||
return
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with manager.bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Delivery was incorrectly reported idle")
|
||||
observations.append("busy")
|
||||
assert not manager.bus.admission.paused
|
||||
|
||||
async def dequeue():
|
||||
message = await consume()
|
||||
asyncio.get_running_loop().call_soon(require_busy)
|
||||
return message
|
||||
|
||||
async def send(message):
|
||||
started.set()
|
||||
await release.wait()
|
||||
|
||||
monkeypatch.setattr(manager.bus, "consume_outbound", dequeue)
|
||||
channel.send.side_effect = send
|
||||
await manager.bus.publish_outbound(OutboundMessage("websocket", "chat", "final reply"))
|
||||
require_busy()
|
||||
manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())
|
||||
try:
|
||||
await asyncio.wait_for(started.wait(), 2)
|
||||
assert manager.bus.outbound_size == 0
|
||||
require_busy()
|
||||
assert observations == ["busy", "busy", "busy"]
|
||||
release.set()
|
||||
await wait_until(lambda: not manager.has_pending_delivery)
|
||||
with manager.bus.admission.pause_if_idle(lambda: False):
|
||||
assert manager.bus.admission.paused
|
||||
# A late producer may queue a lifecycle notice while the consumer
|
||||
# is awaiting an empty queue. It must remain parked until admission
|
||||
# is restored, rather than start new transport writes under the gate.
|
||||
await manager.bus.publish_outbound(OutboundMessage("websocket", "chat", "late notice"))
|
||||
await wait_until(lambda: manager._outbound_dispatching)
|
||||
await wait_until(lambda: len(observations) == 4)
|
||||
channel.send.assert_awaited_once()
|
||||
assert not manager.bus.admission.paused
|
||||
await wait_until(lambda: not manager.has_pending_delivery)
|
||||
assert [call.args[0].content for call in channel.send.await_args_list] == ["final reply", "late notice"]
|
||||
assert observations == ["busy", "busy", "busy", "parked"]
|
||||
finally:
|
||||
release.set()
|
||||
await manager.stop_all()
|
||||
|
||||
|
||||
async def wait_until(predicate):
|
||||
async with asyncio.timeout(2):
|
||||
while not predicate():
|
||||
|
||||
@@ -306,12 +306,17 @@ def test_special_setup_validation_is_owned_by_channel_package(name: str):
|
||||
|
||||
@pytest.mark.parametrize("name", ["feishu", "linear", "qq", "weixin", "whatsapp"])
|
||||
def test_interactive_connector_is_owned_by_channel_package(name: str):
|
||||
from nanobot.channels.connect import ManagedChannelConnector
|
||||
|
||||
plugin = load_channel_package(name)
|
||||
|
||||
assert plugin is not None
|
||||
assert plugin.connector is not None
|
||||
assert plugin.connector.startswith(f"nanobot.channels.{name}.")
|
||||
assert plugin.load_connector().__class__.__module__ == f"nanobot.channels.{name}.connect"
|
||||
connector = plugin.load_connector()
|
||||
assert connector.__class__.__module__ == f"nanobot.channels.{name}.connect"
|
||||
assert isinstance(connector, ManagedChannelConnector)
|
||||
assert connector.has_pending_work is False
|
||||
|
||||
|
||||
def test_descriptor_defaults_cover_onboarding_fields_without_runtime_import():
|
||||
@@ -3559,9 +3564,8 @@ async def test_stop_all_cancels_dispatcher_and_stops_channels():
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
)
|
||||
|
||||
mgr = ChannelManager.__new__(ChannelManager)
|
||||
mgr = ChannelManager(Config.model_validate({"channels": {"websocket": {"enabled": False}}}), MessageBus())
|
||||
mgr.config = fake_config
|
||||
mgr.bus = MessageBus()
|
||||
|
||||
ch = _StartableChannel(fake_config, mgr.bus)
|
||||
mgr.channels = {"startable": ch}
|
||||
@@ -3641,9 +3645,8 @@ async def test_stop_all_handles_channel_exception():
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
)
|
||||
|
||||
mgr = ChannelManager.__new__(ChannelManager)
|
||||
mgr = ChannelManager(Config.model_validate({"channels": {"websocket": {"enabled": False}}}), MessageBus())
|
||||
mgr.config = fake_config
|
||||
mgr.bus = MessageBus()
|
||||
mgr.channels = {"stopfailing": _StopFailingChannel(fake_config, mgr.bus)}
|
||||
mgr._channel_tasks = {}
|
||||
mgr._outbound_tasks = {}
|
||||
@@ -3678,9 +3681,8 @@ async def test_stop_all_handles_channel_stop_cancelled_task():
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
)
|
||||
|
||||
mgr = ChannelManager.__new__(ChannelManager)
|
||||
mgr = ChannelManager(Config.model_validate({"channels": {"websocket": {"enabled": False}}}), MessageBus())
|
||||
mgr.config = fake_config
|
||||
mgr.bus = MessageBus()
|
||||
next_channel = _StartableChannel(fake_config, mgr.bus)
|
||||
mgr.channels = {
|
||||
"stopcancelled": _StopCancelledChannel(fake_config, mgr.bus),
|
||||
@@ -3704,9 +3706,8 @@ async def test_start_all_no_channels_logs_warning():
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
)
|
||||
|
||||
mgr = ChannelManager.__new__(ChannelManager)
|
||||
mgr = ChannelManager(Config.model_validate({"channels": {"websocket": {"enabled": False}}}), MessageBus())
|
||||
mgr.config = fake_config
|
||||
mgr.bus = MessageBus()
|
||||
mgr.channels = {} # No channels
|
||||
mgr._dispatch_task = None
|
||||
|
||||
@@ -3724,9 +3725,8 @@ async def test_start_all_creates_dispatch_task():
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
)
|
||||
|
||||
mgr = ChannelManager.__new__(ChannelManager)
|
||||
mgr = ChannelManager(Config.model_validate({"channels": {"websocket": {"enabled": False}}}), MessageBus())
|
||||
mgr.config = fake_config
|
||||
mgr.bus = MessageBus()
|
||||
|
||||
ch = _StartableChannel(fake_config, mgr.bus)
|
||||
mgr.channels = {"startable": ch}
|
||||
|
||||
@@ -33,6 +33,7 @@ from nanobot.cron.bound_runner import run_bound_cron_job
|
||||
from nanobot.cron.service import CronService
|
||||
from nanobot.cron.types import CronSchedule
|
||||
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
|
||||
from nanobot.runtime_admission import RuntimeBusyError, RuntimeMaintenanceError
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
|
||||
@@ -62,6 +63,58 @@ async def drain(manager):
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
|
||||
async def test_parked_gateway_neither_initializes_nor_records_scheduled_delivery(tmp_path):
|
||||
manager = make_manager(tmp_path)
|
||||
try:
|
||||
with manager.bus.admission.pause_before_start():
|
||||
manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())
|
||||
await asyncio.sleep(0)
|
||||
assert not manager._outbox.path.exists()
|
||||
with pytest.raises(RuntimeMaintenanceError):
|
||||
await manager.bus.publish_outbound(message())
|
||||
with pytest.raises(RuntimeMaintenanceError):
|
||||
await manager._recover_scheduled()
|
||||
assert not manager._outbox.path.exists()
|
||||
assert manager.bus.outbound_size == 0
|
||||
await manager.bus.publish_outbound(message())
|
||||
assert manager._outbox.path.exists()
|
||||
finally:
|
||||
await manager.stop_all()
|
||||
|
||||
|
||||
async def test_scheduled_recovery_remains_busy_while_waiting_for_a_send_slot(tmp_path, monkeypatch):
|
||||
manager = make_manager(tmp_path)
|
||||
channel = MagicMock(spec=BaseChannel, send=AsyncMock(), stop=AsyncMock())
|
||||
channel.has_pending_delivery = False
|
||||
manager.channels["whatsapp"] = channel
|
||||
manager._outbox.record(message())
|
||||
manager._outbound_slots = asyncio.Semaphore(0)
|
||||
queued = asyncio.Event()
|
||||
queue = manager._queue_outbound
|
||||
|
||||
async def wait_for_slot(channel, msg):
|
||||
queued.set()
|
||||
await queue(channel, msg)
|
||||
|
||||
monkeypatch.setattr(manager, "_queue_outbound", wait_for_slot)
|
||||
recovery = asyncio.create_task(manager._recover_scheduled())
|
||||
try:
|
||||
await asyncio.wait_for(queued.wait(), 2)
|
||||
assert not manager._outbound_tasks
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with manager.bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Durable recovery was admitted during maintenance")
|
||||
manager._outbound_slots.release()
|
||||
await asyncio.wait_for(recovery, 2)
|
||||
await drain(manager)
|
||||
channel.send.assert_awaited_once()
|
||||
assert rows(manager._outbox)[0]["status"] == "sent"
|
||||
finally:
|
||||
recovery.cancel()
|
||||
await asyncio.gather(recovery, return_exceptions=True)
|
||||
await manager.stop_all()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("legacy_message,one_shot,origin", [
|
||||
(False, False, "whatsapp"), (True, False, "whatsapp"), (True, True, "whatsapp"),
|
||||
(True, False, "websocket"),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
from contextlib import nullcontext
|
||||
from io import StringIO
|
||||
from unittest.mock import AsyncMock, MagicMock, call, patch
|
||||
@@ -9,6 +10,14 @@ from nanobot.cli import stream as stream_mod
|
||||
from nanobot.cli import terminal
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def isolate_prompt_session(tmp_path, monkeypatch):
|
||||
"""Keep real parser tests out of user history and other prompt sessions."""
|
||||
monkeypatch.setattr("nanobot.config.paths.get_cli_history_path", lambda: tmp_path / "history")
|
||||
monkeypatch.setattr(terminal, "_prompt_session", None)
|
||||
monkeypatch.setattr(terminal, "_saved_term_attrs", None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_prompt_session():
|
||||
"""Mock the global prompt session."""
|
||||
@@ -105,7 +114,10 @@ async def test_raw_lf_enter_still_submits_like_wsl_terminals():
|
||||
terminal._init_prompt_session()
|
||||
session = terminal._prompt_session
|
||||
pipe_input.send_text("hello\x0aworld\r")
|
||||
result = await session.prompt_async("> ")
|
||||
# CI has no user to acknowledge prompt_toolkit's exception prompt.
|
||||
result = await asyncio.wait_for(
|
||||
session.prompt_async("> ", set_exception_handler=False), timeout=10,
|
||||
)
|
||||
|
||||
assert result == "hello"
|
||||
|
||||
@@ -122,7 +134,9 @@ async def test_alt_enter_inserts_newline_on_lf_terminals():
|
||||
terminal._init_prompt_session()
|
||||
session = terminal._prompt_session
|
||||
pipe_input.send_text("foo\x1b\x0abar\r")
|
||||
result = await session.prompt_async("> ")
|
||||
result = await asyncio.wait_for(
|
||||
session.prompt_async("> ", set_exception_handler=False), timeout=10,
|
||||
)
|
||||
|
||||
assert result == "foo\nbar"
|
||||
|
||||
@@ -139,7 +153,9 @@ async def test_csi_u_shift_enter_inserts_newline_not_raw_escape():
|
||||
terminal._init_prompt_session()
|
||||
session = terminal._prompt_session
|
||||
pipe_input.send_text("foo\x1b[13;2ubar\r")
|
||||
result = await session.prompt_async("> ")
|
||||
result = await asyncio.wait_for(
|
||||
session.prompt_async("> ", set_exception_handler=False), timeout=10,
|
||||
)
|
||||
|
||||
# A newline is inserted and no raw escape bytes leak into the result.
|
||||
assert result == "foo\nbar"
|
||||
|
||||
+86
-17
@@ -3,8 +3,9 @@ import json
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import sys
|
||||
import urllib.error
|
||||
from contextlib import contextmanager, suppress
|
||||
from contextlib import contextmanager, nullcontext, suppress
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
@@ -48,6 +49,8 @@ runner = CliRunner()
|
||||
def mock_webui_bundle(monkeypatch) -> MagicMock:
|
||||
prepare_bundle = MagicMock()
|
||||
monkeypatch.setattr(cli_webui, "_prepare_webui_bundle_for_gateway", prepare_bundle)
|
||||
monkeypatch.setattr(cli_webui, "dock_icon", lambda *_args, **_kwargs: nullcontext())
|
||||
monkeypatch.setattr(cli_webui, "request_gateway_icon", lambda *_args, **_kwargs: None)
|
||||
return prepare_bundle
|
||||
|
||||
|
||||
@@ -93,6 +96,10 @@ class _GatewayAgentContractStub:
|
||||
tools = ToolRegistry()
|
||||
subagents = MagicMock(spec=SubagentManager)
|
||||
|
||||
@contextmanager
|
||||
def maintenance(self):
|
||||
yield
|
||||
|
||||
async def discard_session(self, _session_key: str) -> None:
|
||||
pass
|
||||
|
||||
@@ -1717,7 +1724,7 @@ def test_agent_uses_workspace_directory_for_cron_store(monkeypatch, tmp_path: Pa
|
||||
monkeypatch.setattr("nanobot.bus.queue.MessageBus", lambda: object())
|
||||
|
||||
class _FakeCron:
|
||||
def __init__(self, store_path: Path) -> None:
|
||||
def __init__(self, store_path: Path, *, admission=None) -> None:
|
||||
seen["cron_store"] = store_path
|
||||
|
||||
class _FakeAgentLoop:
|
||||
@@ -1767,7 +1774,7 @@ def test_agent_workspace_override_does_not_migrate_legacy_cron(
|
||||
monkeypatch.setattr("nanobot.config.paths.get_cron_dir", lambda: legacy_dir)
|
||||
|
||||
class _FakeCron:
|
||||
def __init__(self, store_path: Path) -> None:
|
||||
def __init__(self, store_path: Path, *, admission=None) -> None:
|
||||
seen["cron_store"] = store_path
|
||||
|
||||
class _FakeAgentLoop:
|
||||
@@ -1823,7 +1830,7 @@ def test_agent_custom_config_workspace_does_not_migrate_legacy_cron(
|
||||
monkeypatch.setattr("nanobot.config.paths.get_cron_dir", lambda: legacy_dir)
|
||||
|
||||
class _FakeCron:
|
||||
def __init__(self, store_path: Path) -> None:
|
||||
def __init__(self, store_path: Path, *, admission=None) -> None:
|
||||
seen["cron_store"] = store_path
|
||||
|
||||
class _FakeAgentLoop:
|
||||
@@ -1853,9 +1860,8 @@ def test_agent_custom_config_workspace_does_not_migrate_legacy_cron(
|
||||
assert not (custom_workspace / "cron" / "jobs.json").exists()
|
||||
|
||||
|
||||
def test_agent_overrides_workspace_path(mock_agent_runtime):
|
||||
workspace_path = Path("/tmp/agent-workspace")
|
||||
|
||||
@pytest.mark.parametrize("workspace_path", [Path("/tmp/agent-workspace"), Path("relative-agent-workspace")])
|
||||
def test_agent_overrides_workspace_path(mock_agent_runtime, workspace_path):
|
||||
result = runner.invoke(app, ["agent", "-m", "hello", "-w", str(workspace_path)])
|
||||
|
||||
assert result.exit_code == 0
|
||||
@@ -2174,7 +2180,7 @@ def test_heartbeat_empty_response_is_not_evaluated(
|
||||
return [{"key": "telegram:u1"}]
|
||||
|
||||
class _FakeCron:
|
||||
def __init__(self, _store_path: Path) -> None:
|
||||
def __init__(self, _store_path: Path, *, admission=None) -> None:
|
||||
self.on_job = None
|
||||
seen["cron"] = self
|
||||
|
||||
@@ -2367,6 +2373,36 @@ def test_webui_background_points_to_the_single_persistent_gateway_command(
|
||||
assert not config_file.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("managed", [False, True], ids=["explicit-detach", "fresh-installer"])
|
||||
@pytest.mark.parametrize("no_dock", [False, True])
|
||||
def test_webui_detached_gateway_does_not_retain_launcher_lease(monkeypatch, tmp_path, managed, no_dock):
|
||||
config = tmp_path / "config.json"
|
||||
_patch_webui_provider_ready(monkeypatch)
|
||||
_patch_gateway_ports_free(monkeypatch)
|
||||
seen = _patch_webui_managed_gateway(monkeypatch)
|
||||
requested = []
|
||||
monkeypatch.setattr(cli_webui, "request_gateway_icon",
|
||||
lambda instance, *, enabled: requested.append((instance, enabled)))
|
||||
if managed:
|
||||
prefix = tmp_path / "managed"
|
||||
prefix.mkdir()
|
||||
(prefix / "nanobot-install.json").write_text(json.dumps({
|
||||
"schema_version": 1, "owner": "nanobot-installer", "environment": str(prefix), "extras": [],
|
||||
}))
|
||||
monkeypatch.setattr(sys, "prefix", str(prefix))
|
||||
result = runner.invoke(app, ["webui", "--config", str(config), "--yes", "--no-open",
|
||||
*([] if managed else ["--detach"]),
|
||||
*(["--no-dock"] if no_dock else [])])
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "start_options" in seen
|
||||
assert "attached_runtime" not in seen
|
||||
assert "lease_release_wait_for_stop" not in seen
|
||||
assert "Stop nanobot" in result.stdout
|
||||
assert len(requested) == 1
|
||||
assert requested[0][0].parent == tmp_path / "run"
|
||||
assert requested[0][1] is not no_dock
|
||||
|
||||
|
||||
def test_webui_dev_starts_vite_sidecar_and_gateway(monkeypatch, tmp_path: Path) -> None:
|
||||
config_file = tmp_path / "config.json"
|
||||
config_file.write_text("{}", encoding="utf-8")
|
||||
@@ -2725,6 +2761,35 @@ def test_launch_browser_uses_unix_launcher_on_linux(monkeypatch) -> None:
|
||||
assert opened == ["http://127.0.0.1:8765/"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("no_dock", [False, True])
|
||||
def test_webui_dock_lifetime_wraps_the_attached_client(monkeypatch, tmp_path, no_dock):
|
||||
config_file = tmp_path / "config.json"
|
||||
config_file.write_text("{}")
|
||||
_patch_gateway_ports_free(monkeypatch)
|
||||
_patch_webui_provider_ready(monkeypatch)
|
||||
_patch_webui_managed_gateway(monkeypatch)
|
||||
events = []
|
||||
|
||||
@contextmanager
|
||||
def desktop(url, *, instance, enabled):
|
||||
assert url.startswith("http://127.0.0.1:")
|
||||
assert instance.parent == tmp_path / "run"
|
||||
assert enabled is not no_dock
|
||||
events.append("icon attached")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
events.append("icon detached")
|
||||
|
||||
monkeypatch.setattr(cli_webui, "dock_icon", desktop)
|
||||
monkeypatch.setattr(cli_webui, "_attach_to_background_gateway",
|
||||
lambda *_args, **_kwargs: events.append("gateway attached"))
|
||||
result = runner.invoke(app, ["webui", "--config", str(config_file), "--no-open", "--yes",
|
||||
*(["--no-dock"] if no_dock else [])])
|
||||
assert result.exit_code == 0, result.output
|
||||
assert events == ["icon attached", "gateway attached", "icon detached"]
|
||||
|
||||
|
||||
def test_webui_foreground_attaches_to_existing_managed_gateway(monkeypatch, tmp_path: Path) -> None:
|
||||
config_file = tmp_path / "config.json"
|
||||
config_file.write_text("{}")
|
||||
@@ -3151,7 +3216,7 @@ def test_gateway_uses_workspace_directory_for_cron_store(monkeypatch, tmp_path:
|
||||
seen: dict[str, Path] = {}
|
||||
|
||||
class _StopCron:
|
||||
def __init__(self, store_path: Path) -> None:
|
||||
def __init__(self, store_path: Path, *, admission=None) -> None:
|
||||
seen["cron_store"] = store_path
|
||||
raise _StopGatewayError("stop")
|
||||
|
||||
@@ -3221,7 +3286,7 @@ def test_gateway_unbound_agent_cron_is_skipped(
|
||||
monkeypatch.setattr("nanobot.session.manager.SessionManager", _FakeSessionManager)
|
||||
|
||||
class _FakeCron:
|
||||
def __init__(self, _store_path: Path) -> None:
|
||||
def __init__(self, _store_path: Path, *, admission=None) -> None:
|
||||
self.on_job = None
|
||||
seen["cron"] = self
|
||||
|
||||
@@ -3334,7 +3399,7 @@ def test_gateway_bound_cron_runs_as_session_turn(
|
||||
monkeypatch.setattr("nanobot.session.manager.SessionManager", _FakeSessionManager)
|
||||
|
||||
class _FakeCron:
|
||||
def __init__(self, _store_path: Path) -> None:
|
||||
def __init__(self, _store_path: Path, *, admission=None) -> None:
|
||||
self.on_job = None
|
||||
seen["cron"] = self
|
||||
|
||||
@@ -3526,7 +3591,7 @@ def test_gateway_local_trigger_queue_submits_agent_turns(
|
||||
config,
|
||||
message_bus=lambda: bus,
|
||||
session_manager=lambda _workspace: _FakeSessionManager(),
|
||||
cron_service=lambda _store_path: _FakeCronService(),
|
||||
cron_service=lambda _store_path, **_kwargs: _FakeCronService(),
|
||||
)
|
||||
|
||||
class _FakeMemory:
|
||||
@@ -3687,7 +3752,7 @@ def test_gateway_workspace_override_does_not_migrate_legacy_cron(
|
||||
seen: dict[str, Path] = {}
|
||||
|
||||
class _StopCron:
|
||||
def __init__(self, store_path: Path) -> None:
|
||||
def __init__(self, store_path: Path, *, admission=None) -> None:
|
||||
seen["cron_store"] = store_path
|
||||
raise _StopGatewayError("stop")
|
||||
|
||||
@@ -3726,7 +3791,7 @@ def test_gateway_custom_config_workspace_does_not_migrate_legacy_cron(
|
||||
seen: dict[str, Path] = {}
|
||||
|
||||
class _StopCron:
|
||||
def __init__(self, store_path: Path) -> None:
|
||||
def __init__(self, store_path: Path, *, admission=None) -> None:
|
||||
seen["cron_store"] = store_path
|
||||
raise _StopGatewayError("stop")
|
||||
|
||||
@@ -3879,7 +3944,7 @@ def test_gateway_health_endpoint_binds_and_serves_expected_responses(
|
||||
return None
|
||||
|
||||
class _FakeCronService:
|
||||
def __init__(self, _store_path: Path) -> None:
|
||||
def __init__(self, _store_path: Path, *, admission=None) -> None:
|
||||
self.on_job = None
|
||||
|
||||
async def start(self) -> None:
|
||||
@@ -3971,6 +4036,10 @@ def test_gateway_health_endpoint_binds_and_serves_expected_responses(
|
||||
assert health_writer.closed is True
|
||||
assert "HTTP/1.0 200 OK" in health_response
|
||||
health_body = json.loads(health_response.split("\r\n\r\n", 1)[1])
|
||||
assert health_body.pop("maintenance") is False
|
||||
identity = health_body.pop("runtime")
|
||||
assert identity["version"] == cli_commands.__version__
|
||||
assert identity["instance_id"] and identity["run_id"]
|
||||
assert health_body == {
|
||||
"status": "ok",
|
||||
"process": "alive",
|
||||
@@ -4114,7 +4183,7 @@ def test_gateway_agent_task_owns_initial_mcp_provider_close(
|
||||
seen["channels_stopped"] = True
|
||||
|
||||
class _FakeCronService:
|
||||
def __init__(self, _store_path: Path) -> None:
|
||||
def __init__(self, _store_path: Path, *, admission=None) -> None:
|
||||
self.on_job = None
|
||||
|
||||
async def start(self) -> None:
|
||||
@@ -4251,7 +4320,7 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(
|
||||
await asyncio.wait_for(channel_finished.wait(), timeout=1)
|
||||
|
||||
class _FakeCronService:
|
||||
def __init__(self, _store_path: Path) -> None:
|
||||
def __init__(self, _store_path: Path, *, admission=None) -> None:
|
||||
self.on_job = None
|
||||
|
||||
async def start(self) -> None:
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
"""The Dock shortcut never owns gateway execution, data, or credentials on disk."""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.cli import dock
|
||||
from nanobot.cli._macos_dock import _Clients, _serve, is_local_browser_url
|
||||
|
||||
|
||||
@pytest.mark.parametrize("platform", ["linux", "win32"])
|
||||
def test_other_platforms_do_not_prepare_or_launch_an_icon(monkeypatch, tmp_path, platform):
|
||||
monkeypatch.setattr(dock.sys, "platform", platform)
|
||||
monkeypatch.setattr(dock, "_attach", lambda *_: pytest.fail("must not launch"))
|
||||
with dock.dock_icon("http://127.0.0.1:8765/", instance=tmp_path / "gateway.json"):
|
||||
pass
|
||||
assert list(tmp_path.iterdir()) == []
|
||||
|
||||
|
||||
def test_explicit_opt_out_and_ssh_do_not_launch(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(dock.sys, "platform", "darwin")
|
||||
monkeypatch.setattr(dock, "_attach", lambda *_: pytest.fail("must not launch"))
|
||||
with dock.dock_icon("http://127.0.0.1:8765/", instance=tmp_path, enabled=False):
|
||||
pass
|
||||
monkeypatch.setenv("SSH_CONNECTION", "test")
|
||||
with dock.dock_icon("http://127.0.0.1:8765/", instance=tmp_path):
|
||||
pass
|
||||
|
||||
|
||||
def test_optional_failure_does_not_swallow_webui_failure_or_log_credentials(monkeypatch, tmp_path):
|
||||
warnings = []
|
||||
monkeypatch.setattr(dock, "_desktop_available", lambda: True)
|
||||
monkeypatch.setattr(dock, "_directory", lambda *_: tmp_path)
|
||||
monkeypatch.setattr(dock.logger, "warning", warnings.append)
|
||||
|
||||
def unavailable(*_):
|
||||
raise OSError("sensitive-url-fragment")
|
||||
|
||||
monkeypatch.setattr(dock, "_attach", unavailable)
|
||||
with pytest.raises(RuntimeError, match="gateway failure"):
|
||||
with dock.dock_icon("http://127.0.0.1:8765/", instance=tmp_path):
|
||||
raise RuntimeError("gateway failure")
|
||||
assert len(warnings) == 1
|
||||
assert "sensitive" not in warnings[0]
|
||||
|
||||
|
||||
def test_context_releases_its_connection_even_when_the_launcher_is_interrupted(monkeypatch, tmp_path):
|
||||
first, other = socket.socketpair()
|
||||
monkeypatch.setattr(dock, "_desktop_available", lambda: True)
|
||||
monkeypatch.setattr(dock, "_directory", lambda *_: tmp_path)
|
||||
monkeypatch.setattr(dock, "_attach", lambda *_: first)
|
||||
with other, pytest.raises(KeyboardInterrupt):
|
||||
try:
|
||||
with dock.dock_icon("http://127.0.0.1:8765/", instance=tmp_path):
|
||||
raise KeyboardInterrupt
|
||||
finally:
|
||||
other.settimeout(1)
|
||||
assert other.recv(1) == b""
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="Darwin/Unix helper startup contract")
|
||||
def test_interrupt_during_handshake_closes_connection_and_stops_new_helper(monkeypatch):
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
connection = MagicMock()
|
||||
connection.recv.side_effect = KeyboardInterrupt
|
||||
process = MagicMock()
|
||||
process.poll.return_value = None
|
||||
attempts = iter((None, connection))
|
||||
monkeypatch.setattr(dock, "_connect", lambda *_: next(attempts))
|
||||
monkeypatch.setattr(dock, "_bundle", lambda *_: Path("unused-test-interpreter"))
|
||||
monkeypatch.setattr(dock.subprocess, "Popen", lambda *_args, **_kwargs: process)
|
||||
with tempfile.TemporaryDirectory(prefix="nb-dock-") as name, pytest.raises(KeyboardInterrupt):
|
||||
dock._attach(Path(name), "http://127.0.0.1:8765/")
|
||||
connection.close.assert_called_once()
|
||||
process.terminate.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="Darwin/Unix helper startup contract")
|
||||
def test_cold_helper_startup_keeps_the_connection_until_ready(monkeypatch, tmp_path):
|
||||
# Native AppKit startup was measured at 1.928s after an update, already at
|
||||
# the old 2s socket deadline. Exercise a cold start without requiring a GUI.
|
||||
helper = tmp_path / "slow-helper.py"
|
||||
helper.write_text("""import socket, sys, time
|
||||
listener = socket.socket(fileno=int(sys.argv[1]))
|
||||
time.sleep(2.5)
|
||||
connection, _ = listener.accept()
|
||||
with connection:
|
||||
assert connection.recv(8192).endswith(b'\\n')
|
||||
connection.sendall(b'1')
|
||||
assert connection.recv(1) == b''
|
||||
listener.close()
|
||||
""")
|
||||
spawned = []
|
||||
popen = dock.subprocess.Popen
|
||||
|
||||
def launch(*args, **kwargs):
|
||||
process = popen(*args, **kwargs)
|
||||
spawned.append(process)
|
||||
return process
|
||||
|
||||
monkeypatch.setattr(dock, "_WORKER", helper)
|
||||
monkeypatch.setattr(dock, "_bundle", lambda _: Path(sys.executable))
|
||||
monkeypatch.setattr(dock.subprocess, "Popen", launch)
|
||||
with tempfile.TemporaryDirectory(prefix="nb-dock-") as name:
|
||||
try:
|
||||
connection = dock._attach(Path(name), "http://127.0.0.1:8765/")
|
||||
connection.close()
|
||||
assert spawned[0].wait(timeout=3) == 0
|
||||
finally:
|
||||
for process in spawned:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait(timeout=3)
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="macOS private-directory contract")
|
||||
def test_private_cache_rejects_symlink_and_shared_directory(tmp_path):
|
||||
shared = tmp_path / "shared"
|
||||
shared.mkdir(mode=0o755)
|
||||
shared.chmod(0o755)
|
||||
with pytest.raises(PermissionError):
|
||||
dock._private_directory(shared)
|
||||
private = tmp_path / "private"
|
||||
dock._private_directory(private)
|
||||
link = tmp_path / "link"
|
||||
link.symlink_to(private, target_is_directory=True)
|
||||
with pytest.raises(PermissionError):
|
||||
dock._private_directory(link)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url, valid", [
|
||||
("http://127.0.0.1:8765/#/?bootstrapSecret=test", True),
|
||||
("http://localhost:8765/", True),
|
||||
("http://[::1]:5173/", True),
|
||||
("http://example.com:8765/", False),
|
||||
("http://127.0.0.1.example.com:8765/", False),
|
||||
("http://user:pass@127.0.0.1:8765/", False),
|
||||
("file:///tmp/index.html", False),
|
||||
("http://127.0.0.1:8765/\n", False),
|
||||
("http://127.0.0.1:99999/", False),
|
||||
])
|
||||
def test_private_socket_only_accepts_local_browser_urls(url, valid):
|
||||
assert is_local_browser_url(url) is valid
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _server():
|
||||
# macOS has a short AF_UNIX address limit; pytest's nested tmp_path can exceed it.
|
||||
with tempfile.TemporaryDirectory(prefix="nb-dock-") as name:
|
||||
address = Path(name) / "s"
|
||||
listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
listener.bind(str(address))
|
||||
listener.listen()
|
||||
clients = _Clients()
|
||||
stopped = threading.Event()
|
||||
# Keep startup serialized just like the launcher: first connect before release.
|
||||
from filelock import FileLock
|
||||
with FileLock(str(address.parent / "start.lock")):
|
||||
thread = threading.Thread(target=_serve, args=(listener, address, clients, stopped.set))
|
||||
thread.start()
|
||||
first = _join(address, "http://127.0.0.1:8765/#/first")
|
||||
try:
|
||||
yield address, first, clients, stopped
|
||||
finally:
|
||||
first.close()
|
||||
assert stopped.wait(3)
|
||||
thread.join(timeout=1)
|
||||
|
||||
|
||||
def _join(address, url):
|
||||
connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
connection.settimeout(2)
|
||||
connection.connect(str(address))
|
||||
connection.sendall(url.encode() + b"\n")
|
||||
assert connection.recv(1) == b"1"
|
||||
return connection
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="Darwin/Unix socket lifetime contract")
|
||||
def test_shared_icon_survives_first_launcher_and_stops_after_last():
|
||||
with _server() as (address, first, clients, stopped):
|
||||
second = _join(address, "http://127.0.0.1:8765/#/second")
|
||||
try:
|
||||
assert clients.current_url().endswith("/second")
|
||||
first.close()
|
||||
assert not stopped.wait(0.15)
|
||||
assert address.exists()
|
||||
finally:
|
||||
second.close()
|
||||
assert stopped.wait(3)
|
||||
assert not address.exists()
|
||||
assert clients.current_url() is None
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="Darwin/Unix socket lifetime contract")
|
||||
def test_rejected_peer_does_not_replace_live_url_or_stop_the_icon():
|
||||
with _server() as (address, first, clients, stopped):
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as invalid:
|
||||
invalid.settimeout(2)
|
||||
invalid.connect(str(address))
|
||||
invalid.sendall(b"https://example.com/\n")
|
||||
assert invalid.recv(1) == b""
|
||||
assert clients.current_url().endswith("/first")
|
||||
assert not stopped.is_set()
|
||||
first.close()
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="Darwin/Unix socket lifetime contract")
|
||||
def test_new_launcher_can_join_while_the_previous_launcher_exits():
|
||||
from filelock import FileLock
|
||||
|
||||
with _server() as (address, first, _clients, stopped):
|
||||
with FileLock(str(address.parent / "start.lock")):
|
||||
first.close()
|
||||
assert not stopped.wait(0.15)
|
||||
second = _join(address, "http://127.0.0.1:8765/#/next")
|
||||
try:
|
||||
assert not stopped.wait(0.15)
|
||||
finally:
|
||||
second.close()
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="macOS interpreter wrapper")
|
||||
def test_bundle_uses_current_python_and_never_contains_the_login_url(tmp_path):
|
||||
import plistlib
|
||||
|
||||
executable = dock._bundle(tmp_path)
|
||||
assert executable.is_symlink()
|
||||
assert os.readlink(executable) == sys.executable
|
||||
info = plistlib.loads((executable.parent.parent / "Info.plist").read_bytes())
|
||||
assert info["CFBundleDisplayName"] == "nanobot"
|
||||
assert (executable.parent.parent / "Resources" / "dock-icon.png").read_bytes() == dock._ICON.read_bytes()
|
||||
assert len([path for path in tmp_path.rglob("*") if path.is_file()]) == 3
|
||||
|
||||
|
||||
async def test_background_presence_waits_for_activation_and_remembers_explicit_requests(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(dock, "_desktop_available", lambda: True)
|
||||
instance = tmp_path / "run" / "gateway.json"
|
||||
entered, closed = threading.Event(), threading.Event()
|
||||
|
||||
@contextmanager
|
||||
def icon(url, **_kwargs):
|
||||
assert url == "http://127.0.0.1:8765/"
|
||||
entered.set()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
closed.set()
|
||||
|
||||
monkeypatch.setattr(dock, "dock_icon", icon)
|
||||
dock.request_gateway_icon(instance, enabled=True)
|
||||
intent = instance.with_suffix(".dock").read_text()
|
||||
assert intent.startswith("show:") and "http" not in intent
|
||||
activated = asyncio.Event()
|
||||
watcher = asyncio.create_task(dock.watch_gateway_icon(
|
||||
"http://127.0.0.1:8765/", instance=instance, activated=activated,
|
||||
))
|
||||
try:
|
||||
await asyncio.sleep(0)
|
||||
assert not entered.is_set()
|
||||
activated.set()
|
||||
assert await asyncio.to_thread(entered.wait, 2)
|
||||
dock.request_gateway_icon(instance, enabled=False)
|
||||
assert await asyncio.to_thread(closed.wait, 2)
|
||||
entered.clear()
|
||||
closed.clear()
|
||||
dock.request_gateway_icon(instance, enabled=True)
|
||||
assert await asyncio.to_thread(entered.wait, 2)
|
||||
finally:
|
||||
watcher.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await watcher
|
||||
assert closed.is_set()
|
||||
# A new gateway generation, including a protected update restart, reads the
|
||||
# same intent without rewriting configuration or learning an updater protocol.
|
||||
entered.clear()
|
||||
watcher = asyncio.create_task(dock.watch_gateway_icon(
|
||||
"http://127.0.0.1:8765/", instance=instance, activated=activated,
|
||||
))
|
||||
try:
|
||||
assert await asyncio.to_thread(entered.wait, 2)
|
||||
finally:
|
||||
watcher.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await watcher
|
||||
|
||||
|
||||
async def test_cancelled_gateway_joins_pending_dock_startup_before_releasing_it(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(dock, "_desktop_available", lambda: True)
|
||||
started, release, closed = threading.Event(), threading.Event(), threading.Event()
|
||||
|
||||
@contextmanager
|
||||
def slow_icon(*_args, **_kwargs):
|
||||
started.set()
|
||||
assert release.wait(3)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
closed.set()
|
||||
|
||||
monkeypatch.setattr(dock, "dock_icon", slow_icon)
|
||||
instance = tmp_path / "gateway.json"
|
||||
dock.request_gateway_icon(instance, enabled=True)
|
||||
activated = asyncio.Event()
|
||||
activated.set()
|
||||
watcher = asyncio.create_task(dock.watch_gateway_icon(
|
||||
"http://127.0.0.1:8765/", instance=instance, activated=activated,
|
||||
))
|
||||
try:
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
watcher.cancel()
|
||||
await asyncio.sleep(0)
|
||||
assert not watcher.done()
|
||||
finally:
|
||||
release.set()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await watcher
|
||||
assert closed.is_set()
|
||||
|
||||
|
||||
def test_background_preference_failure_never_blocks_the_launcher(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(dock, "_desktop_available", lambda: True)
|
||||
not_directory = tmp_path / "file"
|
||||
not_directory.write_text("test")
|
||||
dock.request_gateway_icon(not_directory / "gateway.json", enabled=True)
|
||||
+69
-2
@@ -7,6 +7,7 @@ import pytest
|
||||
|
||||
from nanobot.cli import entry
|
||||
from nanobot.cli.entry import _agent_invocation_args, _native_tui_candidate
|
||||
from nanobot.installation_lock import InstallationBusyError, installation_access, installation_id
|
||||
|
||||
|
||||
def test_root_command_routes_to_agent_without_copying_agent_options() -> None:
|
||||
@@ -70,7 +71,7 @@ def test_root_alias_dispatches_the_shared_agent_command(monkeypatch) -> None:
|
||||
"set_cli_process_identity",
|
||||
lambda args: calls.__setitem__("identity", args),
|
||||
)
|
||||
monkeypatch.setattr(entry, "_configure_windows_console", lambda: None)
|
||||
monkeypatch.setattr(entry, "configure_windows_console", lambda: None)
|
||||
monkeypatch.setattr(
|
||||
entry,
|
||||
"_run_agent",
|
||||
@@ -91,7 +92,7 @@ def test_desktop_handled_bare_invocation_does_not_start_python(monkeypatch) -> N
|
||||
|
||||
monkeypatch.setattr(entry.sys, "argv", ["nanobot"])
|
||||
monkeypatch.setattr(entry, "set_cli_process_identity", lambda _args: None)
|
||||
monkeypatch.setattr(entry, "_configure_windows_console", lambda: None)
|
||||
monkeypatch.setattr(entry, "configure_windows_console", lambda: None)
|
||||
monkeypatch.setattr(desktop_target, "dispatch_bare_desktop_target", lambda _args: 0)
|
||||
monkeypatch.setattr(
|
||||
entry,
|
||||
@@ -114,3 +115,69 @@ def test_classic_and_one_shot_agent_invocations_keep_the_full_cli_entrypoint() -
|
||||
assert not _native_tui_candidate(["agent", "-mhello"])
|
||||
assert not _native_tui_candidate(["agent", "--message=hello"])
|
||||
assert not _native_tui_candidate(["status"])
|
||||
|
||||
|
||||
def test_entry_refuses_dispatch_during_update(tmp_path, monkeypatch, capsys):
|
||||
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
|
||||
monkeypatch.setattr(sys, "prefix", str(tmp_path / "environment"))
|
||||
monkeypatch.setattr(sys, "argv", ["nanobot", "gateway"])
|
||||
monkeypatch.setattr(entry, "_dispatch", lambda: pytest.fail("Runtime dispatched during update"))
|
||||
with installation_access(updating=True):
|
||||
with pytest.raises(SystemExit) as result:
|
||||
entry.main()
|
||||
assert result.value.code == 1
|
||||
assert "being updated" in capsys.readouterr().err
|
||||
|
||||
|
||||
@pytest.mark.parametrize("args", [["update"], ["--home", "/test", "update"], ["--home=/test", "update"]])
|
||||
def test_update_command_can_reach_its_own_lease_and_recovery(tmp_path, monkeypatch, args):
|
||||
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
|
||||
monkeypatch.setattr(sys, "prefix", str(tmp_path / "environment"))
|
||||
monkeypatch.setattr(sys, "argv", ["nanobot", *args])
|
||||
called = []
|
||||
monkeypatch.setattr(entry, "_dispatch", lambda: called.append(True))
|
||||
with installation_access(updating=True):
|
||||
entry.main()
|
||||
assert called == [True]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("args", [["update", "--job", "saved-id"],
|
||||
["--home=/test", "update", "--job=saved-id", "--retry-handoff"]])
|
||||
def test_saved_update_recovery_owns_runtime_before_application_imports(tmp_path, monkeypatch, args):
|
||||
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
|
||||
monkeypatch.setattr(sys, "prefix", str(tmp_path / "environment"))
|
||||
monkeypatch.setattr(sys, "argv", ["nanobot", *args])
|
||||
entered = []
|
||||
|
||||
def dispatch():
|
||||
with pytest.raises(InstallationBusyError):
|
||||
with installation_access(updating=True):
|
||||
pytest.fail("Recovery imported without a runtime lease")
|
||||
entered.append(True)
|
||||
|
||||
monkeypatch.setattr(entry, "_dispatch", dispatch)
|
||||
entry.main()
|
||||
assert entered == [True]
|
||||
with installation_access(updating=True):
|
||||
with pytest.raises(SystemExit):
|
||||
entry.main()
|
||||
assert entered == [True]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action,allowed", [("stop", True), ("status", True), ("logs", True), ("restart", False)])
|
||||
def test_interrupted_installation_keeps_stop_commands_usable(tmp_path, monkeypatch, action, allowed):
|
||||
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
|
||||
monkeypatch.setattr(sys, "prefix", str(tmp_path / "environment"))
|
||||
pending = tmp_path / ".nanobot/run" / f"update-{installation_id()[:16]}.pending"
|
||||
pending.parent.mkdir(parents=True)
|
||||
pending.write_text("incomplete")
|
||||
monkeypatch.setattr(sys, "argv", ["nanobot", "--home", str(tmp_path / "profile"), "gateway", action])
|
||||
called = []
|
||||
monkeypatch.setattr(entry, "_dispatch", lambda: called.append(True))
|
||||
if allowed:
|
||||
entry.main()
|
||||
assert called == [True]
|
||||
else:
|
||||
with pytest.raises(SystemExit):
|
||||
entry.main()
|
||||
assert not called
|
||||
@@ -139,6 +139,7 @@ def _test_app(
|
||||
config: Config,
|
||||
*,
|
||||
port: int | None = None,
|
||||
verbose: bool = False,
|
||||
webui_bundle_mode: str | None = None,
|
||||
unconfigured_provider_error: str | None = None,
|
||||
gateway_instance: GatewayInstance | None = None,
|
||||
|
||||
@@ -356,13 +356,16 @@ def test_source_checkout_does_not_fall_back_to_a_release_tui_without_bun(
|
||||
"nanobot.cli.tui_launcher._source_checkout_tui_dir",
|
||||
lambda: source_dir,
|
||||
)
|
||||
monkeypatch.setattr("nanobot.cli.tui_launcher.shutil.which", lambda _name: None)
|
||||
def unavailable():
|
||||
raise tui_launcher.BunUnavailableError("Bun download failed")
|
||||
|
||||
monkeypatch.setattr(tui_launcher, "ensure_bun", unavailable)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.cli.tui_launcher._download_release_tui",
|
||||
lambda _asset: pytest.fail("a source checkout must not download a release TUI"),
|
||||
)
|
||||
|
||||
with pytest.raises(TuiUnavailableError, match="source checkout requires Bun"):
|
||||
with pytest.raises(TuiUnavailableError, match="Bun download failed"):
|
||||
resolve_tui_command()
|
||||
|
||||
|
||||
@@ -539,6 +542,7 @@ def test_source_checkout_refreshes_locked_tui_dependencies(
|
||||
source_dir.mkdir()
|
||||
(source_dir / "node_modules" / "@opentui" / "core").mkdir(parents=True)
|
||||
bun = str(tmp_path / "bun")
|
||||
Path(bun).write_bytes(b"runtime")
|
||||
|
||||
def install(command: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
|
||||
assert command == [bun, "install", "--frozen-lockfile"]
|
||||
@@ -563,13 +567,15 @@ def test_source_checkout_fails_when_locked_dependencies_cannot_be_refreshed(
|
||||
) -> None:
|
||||
source_dir = tmp_path / "tui"
|
||||
source_dir.mkdir()
|
||||
bun = tmp_path / "bun"
|
||||
bun.write_bytes(b"runtime")
|
||||
monkeypatch.setattr(
|
||||
"nanobot.cli.tui_launcher.subprocess.run",
|
||||
lambda *args, **kwargs: subprocess.CompletedProcess(args, 1, "", "lockfile mismatch"),
|
||||
)
|
||||
|
||||
with pytest.raises(TuiUnavailableError, match="lockfile mismatch"):
|
||||
_resolve_source_tui_command(source_dir, "bun")
|
||||
_resolve_source_tui_command(source_dir, str(bun))
|
||||
|
||||
|
||||
def test_release_tui_is_verified_and_cached(
|
||||
|
||||
@@ -7,6 +7,7 @@ import json
|
||||
import runpy
|
||||
import stat
|
||||
import struct
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tomllib
|
||||
import zipfile
|
||||
@@ -17,6 +18,13 @@ import pytest
|
||||
|
||||
from nanobot.cli import tui_launcher
|
||||
from scripts import build_tui_wheels as packager
|
||||
from scripts import release_candidate
|
||||
from scripts.release_candidate import (
|
||||
retain_candidate,
|
||||
verify_candidate,
|
||||
write_install_guide,
|
||||
write_manifest,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -186,3 +194,186 @@ def test_installed_tui_never_downloads_or_requires_bun(tmp_path, monkeypatch, sy
|
||||
cache = tmp_path / "empty-cache"
|
||||
assert tui_launcher.resolve_tui_command(data_dir=cache) == [str(binary)]
|
||||
assert not cache.exists()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def complete_candidate(tmp_path, candidate):
|
||||
"""Actual checkout payload, with synthetic native binaries (not native execution)."""
|
||||
from hatch_build import WebUIBuildHook
|
||||
|
||||
root = tmp_path / "checkout"
|
||||
subprocess.run(["git", "clone", "--shared", str(packager.ROOT), str(root)],
|
||||
check=True, capture_output=True)
|
||||
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root, text=True).strip()
|
||||
metadata = tomllib.loads((root / "pyproject.toml").read_text())["project"]
|
||||
wheel, info = candidate
|
||||
with zipfile.ZipFile(wheel) as archive:
|
||||
files = {name: archive.read(name) for name in archive.namelist()}
|
||||
tracked = subprocess.check_output(["git", "ls-files", "-z", "--", "nanobot"], cwd=root).decode().split("\0")
|
||||
for name in filter(None, tracked):
|
||||
parts = name.split("/")
|
||||
if len(parts) > 3 and parts[1] == "channels" and parts[3] == "tests":
|
||||
continue
|
||||
files[name] = (root / name).read_bytes()
|
||||
hook = WebUIBuildHook(str(root), {}, None, {}, "", "wheel",
|
||||
SimpleNamespace(display_info=lambda message: None))
|
||||
hook.initialize("editable", {})
|
||||
references = root / "nanobot/skills/nanobot-document/references"
|
||||
documentation = {}
|
||||
for reference in references.rglob("*.md"):
|
||||
files[reference.relative_to(root).as_posix()] = reference.read_bytes()
|
||||
name = "docs/" + reference.relative_to(references).as_posix()
|
||||
documentation[name] = (root / name).read_bytes()
|
||||
files[f"{info}/METADATA"] += f'Requires-Python: {metadata["requires-python"]}\n'.encode()
|
||||
files["nanobot/_build_commit.txt"] = f"{commit}\n".encode()
|
||||
files["nanobot/web/dist/index.html"] = b"<html>compiled fixture</html>"
|
||||
record = io.StringIO()
|
||||
writer = csv.writer(record)
|
||||
for name, content in files.items():
|
||||
if not name.endswith("/RECORD"):
|
||||
writer.writerow((name, packager._digest(content), len(content)))
|
||||
writer.writerow((f"{info}/RECORD", "", ""))
|
||||
files[f"{info}/RECORD"] = record.getvalue().encode()
|
||||
with zipfile.ZipFile(wheel, "w") as archive:
|
||||
for name, content in files.items():
|
||||
archive.writestr(name, content)
|
||||
artifacts = tmp_path / "artifacts"
|
||||
artifacts.mkdir()
|
||||
for target in packager.PLATFORMS:
|
||||
make_bundle(artifacts, target)
|
||||
packager.build_wheel(wheel, artifacts, artifacts, target, root=root)
|
||||
version = metadata["version"]
|
||||
source_files = {
|
||||
"PKG-INFO": files[f"{info}/METADATA"],
|
||||
"pyproject.toml": (root / "pyproject.toml").read_bytes(),
|
||||
**documentation,
|
||||
**{name: data for name, data in files.items() if name.startswith("nanobot/")},
|
||||
}
|
||||
with tarfile.open(artifacts / f"nanobot_ai-{version}.tar.gz", "w:gz") as archive:
|
||||
for name, data in source_files.items():
|
||||
member = tarfile.TarInfo(f"nanobot_ai-{version}/{name}")
|
||||
member.size = len(data)
|
||||
archive.addfile(member, io.BytesIO(data))
|
||||
return root, commit, artifacts
|
||||
|
||||
|
||||
def test_complete_manifest_binds_wheels_sdist_and_fallback_archives(tmp_path, complete_candidate):
|
||||
"""Real archive/RECORD checks, with synthetic binaries (not native execution)."""
|
||||
root, commit, artifacts = complete_candidate
|
||||
manifest = verify_candidate(root, artifacts, source_commit=commit)
|
||||
assert len(manifest.artifacts) == 16
|
||||
assert manifest.candidate_commit == commit
|
||||
output = artifacts / "release-manifest.json"
|
||||
write_manifest(manifest, output)
|
||||
original = output.read_bytes()
|
||||
write_manifest(verify_candidate(root, artifacts, source_commit=commit), output)
|
||||
assert output.read_bytes() == original
|
||||
with pytest.raises(FileExistsError):
|
||||
write_manifest(manifest.model_copy(update={"source_commit": "f" * 40}), output)
|
||||
guide = tmp_path / "install.md"
|
||||
write_install_guide(root, artifacts, guide, source_commit=commit)
|
||||
original_guide = guide.read_bytes()
|
||||
write_install_guide(root, artifacts, guide, source_commit=commit)
|
||||
assert guide.read_bytes() == original_guide
|
||||
assert commit.encode() in original_guide
|
||||
assert len(list(artifacts.iterdir())) == 17 # 16 artifacts and the manifest, no guide.
|
||||
with pytest.raises(ValueError, match="outside"):
|
||||
write_install_guide(root, artifacts, artifacts / "install.md", source_commit=commit)
|
||||
guide.write_text("previous reviewed handoff\n")
|
||||
with pytest.raises(FileExistsError, match="overwrite"):
|
||||
write_install_guide(root, artifacts, guide, source_commit=commit)
|
||||
assert guide.read_text() == "previous reviewed handoff\n"
|
||||
recorded = json.loads(original)
|
||||
recorded["artifacts"][0]["sha256"] = "f" * 64
|
||||
output.write_text(json.dumps(recorded))
|
||||
with pytest.raises(ValueError, match="recorded release manifest"):
|
||||
write_install_guide(root, artifacts, tmp_path / "unverified.md", source_commit=commit)
|
||||
assert not (tmp_path / "unverified.md").exists()
|
||||
output.write_bytes(original)
|
||||
damaged = artifacts / "nanobot-tui-linux-x64.zip.sha256"
|
||||
damaged.write_text("0" * 64 + " nanobot-tui-linux-x64.zip\n")
|
||||
with pytest.raises(ValueError, match="checksum mismatch"):
|
||||
verify_candidate(root, artifacts, source_commit=commit)
|
||||
with pytest.raises(ValueError, match="checksum mismatch"):
|
||||
write_install_guide(root, artifacts, tmp_path / "damaged.md", source_commit=commit)
|
||||
assert not (tmp_path / "damaged.md").exists()
|
||||
|
||||
|
||||
def test_retained_candidate_keeps_checked_bytes_and_independent_source(tmp_path, complete_candidate):
|
||||
root, commit, artifacts = complete_candidate
|
||||
manifest = verify_candidate(root, artifacts, source_commit=commit)
|
||||
write_manifest(manifest, artifacts / "release-manifest.json")
|
||||
(root / "private-untracked.txt").write_text("not release input")
|
||||
output = tmp_path / "retained"
|
||||
retain_candidate(root, artifacts, output, source_commit=commit)
|
||||
identity = json.loads((output / "handoff.json").read_text())
|
||||
assert identity["candidate_commit"] == commit and identity["published"] is False
|
||||
assert identity["manifest_sha256"] == hashlib.sha256((artifacts / "release-manifest.json").read_bytes()).hexdigest()
|
||||
assert verify_candidate(root, output / "artifacts", source_commit=commit) == manifest
|
||||
for original in artifacts.iterdir():
|
||||
assert (output / "artifacts" / original.name).read_bytes() == original.read_bytes()
|
||||
independent = tmp_path / "independent"
|
||||
subprocess.run(["git", "clone", "--no-local", str(output / "source.git"), str(independent)],
|
||||
check=True, capture_output=True)
|
||||
assert subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=independent, text=True).strip() == commit
|
||||
assert not (independent / "private-untracked.txt").exists()
|
||||
assert not (output / "source.git/objects/info/alternates").exists()
|
||||
assert str(root) not in (output / "source.git/config").read_text()
|
||||
assert verify_candidate(independent, output / "artifacts", source_commit=commit) == manifest
|
||||
with pytest.raises(FileExistsError):
|
||||
retain_candidate(root, artifacts, output, source_commit=commit)
|
||||
|
||||
|
||||
def test_interrupted_retention_has_no_accepted_handoff(tmp_path, complete_candidate, monkeypatch):
|
||||
root, commit, artifacts = complete_candidate
|
||||
write_manifest(verify_candidate(root, artifacts, source_commit=commit), artifacts / "release-manifest.json")
|
||||
|
||||
def interrupted_copy(source, target):
|
||||
raise OSError("controlled interrupted copy")
|
||||
|
||||
monkeypatch.setattr(release_candidate.shutil, "copyfile", interrupted_copy)
|
||||
output = tmp_path / "interrupted"
|
||||
with pytest.raises(OSError, match="interrupted copy"):
|
||||
retain_candidate(root, artifacts, output, source_commit=commit)
|
||||
assert not (output / "handoff.json").exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mutation", ["wheel-code", "wheel-webui", "source-code", "source-missing", "source-extra"])
|
||||
def test_complete_candidate_rejects_mixed_or_incomplete_application_payload(tmp_path, complete_candidate, mutation):
|
||||
root, commit, artifacts = complete_candidate
|
||||
# These are intact archives with valid versions/commit markers and RECORDs.
|
||||
# A stale intermediate or a stray local file can still be packaged correctly.
|
||||
if mutation.startswith("wheel-"):
|
||||
wheel = next(artifacts.glob("*-macosx_13_0_arm64.whl"))
|
||||
with zipfile.ZipFile(wheel) as archive:
|
||||
entries = archive.infolist()
|
||||
files = {entry.filename: archive.read(entry) for entry in entries}
|
||||
name = "nanobot/__init__.py" if mutation == "wheel-code" else "nanobot/web/dist/index.html"
|
||||
files[name] += b"\n# stale build\n"
|
||||
record_name = next(name for name in files if name.endswith(".dist-info/RECORD"))
|
||||
record = io.StringIO()
|
||||
writer = csv.writer(record)
|
||||
for name, data in files.items():
|
||||
writer.writerow((name, "", "") if name == record_name else (name, packager._digest(data), len(data)))
|
||||
files[record_name] = record.getvalue().encode()
|
||||
with zipfile.ZipFile(wheel, "w") as archive:
|
||||
for entry in entries:
|
||||
archive.writestr(entry, files[entry.filename])
|
||||
else:
|
||||
source = next(artifacts.glob("nanobot_ai-*.tar.gz"))
|
||||
files = packager.source_files(source.read_bytes())
|
||||
module = next(name for name in files if name.endswith("/nanobot/agent/loop.py"))
|
||||
if mutation == "source-code":
|
||||
files[module] += b"\n# stale build\n"
|
||||
elif mutation == "source-missing":
|
||||
del files[module]
|
||||
else:
|
||||
files[module.split("/", 1)[0] + "/nanobot/local-settings.json"] = b'{"local": true}'
|
||||
with tarfile.open(source, "w:gz") as archive:
|
||||
for name, data in files.items():
|
||||
member = tarfile.TarInfo(name)
|
||||
member.size = len(data)
|
||||
archive.addfile(member, io.BytesIO(data))
|
||||
with pytest.raises(ValueError, match="application payload"):
|
||||
verify_candidate(root, artifacts, source_commit=commit)
|
||||
assert not (artifacts / "release-manifest.json").exists()
|
||||
@@ -71,11 +71,12 @@ Test-Trace 'PowerShell started'
|
||||
result = subprocess.run(
|
||||
["powershell.exe", "-NoProfile", "-NonInteractive", "-STA", "-EncodedCommand",
|
||||
base64.b64encode(script.encode("utf-16-le")).decode("ascii")],
|
||||
input=base64.b64encode(content) + b"\n", capture_output=True, timeout=15,
|
||||
# Cold C# compilation on a Windows runner is not the acknowledgement deadline.
|
||||
input=base64.b64encode(content) + b"\n", capture_output=True, timeout=60,
|
||||
)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
stages = (exc.stderr or b"").decode("utf-8", errors="replace")
|
||||
pytest.fail(f"Windows handoff exceeded 15s. Native stages:\n{stages}", pytrace=False)
|
||||
pytest.fail(f"Windows handoff exceeded 60s. Native stages:\n{stages}", pytrace=False)
|
||||
|
||||
assert result.returncode == (0 if opens else 1), result.stderr
|
||||
assert result.stdout == b"private;" + (b"1" if opens else b"") + b"removed=True"
|
||||
@@ -201,7 +201,8 @@ def test_atomic_write_ignores_unsupported_directory_fsync(
|
||||
dir_fd = 987654
|
||||
|
||||
def fake_open(path: str, flags: int) -> int:
|
||||
assert Path(path) == store_path.parent
|
||||
# Windows I/O uses an extended path to this same directory.
|
||||
assert Path(path).samefile(store_path.parent)
|
||||
return dir_fd
|
||||
|
||||
def fake_fsync(fd: int) -> None:
|
||||
|
||||
Vendored
+202
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
# Public verification fixture
|
||||
|
||||
`bundle_v3.txt` and `bundle_v3.txt.sigstore` are copied, without modification, from
|
||||
the Sigstore project's Apache-2.0-licensed public test assets at commit
|
||||
`7ee385ac8be192771bff1cc553434b11282ecce6`:
|
||||
https://github.com/sigstore/sigstore-python/tree/7ee385ac8be192771bff1cc553434b11282ecce6/test/assets
|
||||
|
||||
Copyright The Sigstore Authors. Licensed under the Apache License, Version 2.0:
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
These use Sigstore's staging root and contain a public artifact, public certificate and transparency proof, not
|
||||
a private key or token. They prove cryptographic validation and rejection of a
|
||||
valid but unauthorized publisher. They are **not** nanobot release approvals.
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
DO NOT MODIFY ME!
|
||||
|
||||
this is the input for bundle_v3, which tests support for "v3" bundles.
|
||||
|
||||
DO NOT MODIFY ME!
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"mediaType": "application/vnd.dev.sigstore.bundle.v0.3+json",
|
||||
"verificationMaterial": {
|
||||
"certificate": {
|
||||
"rawBytes": "MIIC1DCCAlqgAwIBAgIUO3tlVbLtvLPp+6zGOtep1SPkRigwCgYIKoZIzj0EAwMwNzEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MR4wHAYDVQQDExVzaWdzdG9yZS1pbnRlcm1lZGlhdGUwHhcNMjQwNDAyMTkxOTA5WhcNMjQwNDAyMTkyOTA5WjAAMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAENdrfpgNU1Rjmz+j65rpJWKc08ruKYy4FX7nmmOnbauFZimsQXrdyDSXKNRtEXX4X3t/Amt+euwPDBh+eq7BCnqOCAXkwggF1MA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDAzAdBgNVHQ4EFgQUGRlBhD0wvzAfLb2dMWOgPrrJuRkwHwYDVR0jBBgwFoAUcYYwphR8Ym/599b0BRp/X//rb6wwIwYDVR0RAQH/BBkwF4EVd2lsbGlhbUB5b3NzYXJpYW4ubmV0MCwGCisGAQQBg78wAQEEHmh0dHBzOi8vZ2l0aHViLmNvbS9sb2dpbi9vYXV0aDAuBgorBgEEAYO/MAEIBCAMHmh0dHBzOi8vZ2l0aHViLmNvbS9sb2dpbi9vYXV0aDCBigYKKwYBBAHWeQIEAgR8BHoAeAB2ACswvNxoiMni4dgmKV50H0g5MZYC8pwzy15DQP6yrIZ6AAABjqBAQZ4AAAQDAEcwRQIgeWUmtnD0MFUl5kkX7nbMdLWCsDGIPzdIlN+WaZF0TmkCIQC7+31saqrFe9RmduVZ2dxXhUPrajltuSDHb1vSGOcuHjAKBggqhkjOPQQDAwNoADBlAjEAn2+uuLHsnH9Db7zkIdF65YhiXbgMMF//iHc+B/QETK0HYVcOPTK3p46FUzXFD6xrAjAO2hrkfjBKANKjJJxHV3FVrtS+TR0GCP0HzC3D7Br95TXzfO7+j4Dd8/N/aAr6Ibs="
|
||||
},
|
||||
"tlogEntries": [
|
||||
{
|
||||
"logIndex": "25915956",
|
||||
"logId": {
|
||||
"keyId": "0y8wo8MtY5wrdiIFohx7sHeI5oKDpK5vQhGHI6G+pJY="
|
||||
},
|
||||
"kindVersion": {
|
||||
"kind": "hashedrekord",
|
||||
"version": "0.0.1"
|
||||
},
|
||||
"integratedTime": "1712085549",
|
||||
"inclusionPromise": {
|
||||
"signedEntryTimestamp": "MEYCIQD2KXW1NppUhkPPzGR8NrUIyN+MzZSSqGZQO7CzvhSnYgIhAO9AHzjbsr1AHXRHmEpdPZcoFHEwwMTgfqwjoOXVMmqN"
|
||||
},
|
||||
"inclusionProof": {
|
||||
"logIndex": "25901137",
|
||||
"rootHash": "iGAoHccJIyFemFxmEftti2YC8hvPqixBi5y1EyvfF4c=",
|
||||
"treeSize": "25901138",
|
||||
"hashes": [
|
||||
"UHUr+lvxENI+G902oEsFW5ovQILgqO9mUWWxvvwHZZc=",
|
||||
"IcMBsbH3GRW8FX2CiL/ljMb45vzmENmhp5Yp/7IW998=",
|
||||
"SxC6nr0zP+a6kWb6nO2fmEtz8BYAbqEXc+dsqGLdRPM=",
|
||||
"sppZRSz/vdeLlavgvICrXHLeReMTJw98bs9HJ0I8WnE=",
|
||||
"c8lCSuBS6MzrRnt6OiyYjqhTyxUI/22gpVB7dblfDis=",
|
||||
"eJk64J6cMpIljPSX/72kH0kiIeElyypQm5vJ2gMMyHw=",
|
||||
"hbIK+jmAwQjU7Yi3iKvnfR1u7GNippk7QsRwJXIuRaw=",
|
||||
"tpHWIEB2vNU5ZmC68dj1Hh9cwQK083ozogA6zJ3cJ8A=",
|
||||
"arvuzAipUJ14nDj14OBlvkMSicjdsE9Eus3hq9Jpqdk=",
|
||||
"Edul4W41O3EfxKEEMlX2nW0+GTgCv00nGmcpwhALgVA=",
|
||||
"rBWB37+HwkTZgDv0rMtGBUoDI0UZqcgDZp48M6CaUlA="
|
||||
],
|
||||
"checkpoint": {
|
||||
"envelope": "rekor.sigstage.dev - 8050909264565447525\n25901138\niGAoHccJIyFemFxmEftti2YC8hvPqixBi5y1EyvfF4c=\n\n\u2014 rekor.sigstage.dev 0y8wozBFAiAMJJLbnNOnmizMbVBz9/A/qnMK15BudWoZkuE+obD6CAIhAJf6A3h2iOpuhz/duEhG3fbAQG9PXln4wXPHFBT5wT1a\n"
|
||||
}
|
||||
},
|
||||
"canonicalizedBody": "eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoiaGFzaGVkcmVrb3JkIiwic3BlYyI6eyJkYXRhIjp7Imhhc2giOnsiYWxnb3JpdGhtIjoic2hhMjU2IiwidmFsdWUiOiI1ZTZhZTlkZTU4YzExNzdiZWE2MTViNGZjYmZiMmZkNjg4ZThjNGI1MWMyZTU2YjZhMzhlODE3ODMzZWMyNGEyIn19LCJzaWduYXR1cmUiOnsiY29udGVudCI6Ik1FVUNJRFFTSmk5YWVydFFobVQrY2UxaktOZENlNEtTY3NLR3E5ZlBtMzQyMkRCU0FpRUFoajFzeFo5Nm9ySVRzUXh5TUxJRFJKaW1wb3kxSjFNeWZsY1FWd2tremhzPSIsInB1YmxpY0tleSI6eyJjb250ZW50IjoiTFMwdExTMUNSVWRKVGlCRFJWSlVTVVpKUTBGVVJTMHRMUzB0Q2sxSlNVTXhSRU5EUVd4eFowRjNTVUpCWjBsVlR6TjBiRlppVEhSMlRGQndLelo2UjA5MFpYQXhVMUJyVW1sbmQwTm5XVWxMYjFwSmVtb3dSVUYzVFhjS1RucEZWazFDVFVkQk1WVkZRMmhOVFdNeWJHNWpNMUoyWTIxVmRWcEhWakpOVWpSM1NFRlpSRlpSVVVSRmVGWjZZVmRrZW1SSE9YbGFVekZ3WW01U2JBcGpiVEZzV2tkc2FHUkhWWGRJYUdOT1RXcFJkMDVFUVhsTlZHdDRUMVJCTlZkb1kwNU5hbEYzVGtSQmVVMVVhM2xQVkVFMVYycEJRVTFHYTNkRmQxbElDa3R2V2tsNmFqQkRRVkZaU1V0dldrbDZhakJFUVZGalJGRm5RVVZPWkhKbWNHZE9WVEZTYW0xNksybzJOWEp3U2xkTFl6QTRjblZMV1hrMFJsZzNibTBLYlU5dVltRjFSbHBwYlhOUldISmtlVVJUV0V0T1VuUkZXRmcwV0ROMEwwRnRkQ3RsZFhkUVJFSm9LMlZ4TjBKRGJuRlBRMEZZYTNkblowWXhUVUUwUndwQk1WVmtSSGRGUWk5M1VVVkJkMGxJWjBSQlZFSm5UbFpJVTFWRlJFUkJTMEpuWjNKQ1owVkdRbEZqUkVGNlFXUkNaMDVXU0ZFMFJVWm5VVlZIVW14Q0NtaEVNSGQyZWtGbVRHSXlaRTFYVDJkUWNuSktkVkpyZDBoM1dVUldVakJxUWtKbmQwWnZRVlZqV1ZsM2NHaFNPRmx0THpVNU9XSXdRbEp3TDFndkwzSUtZalozZDBsM1dVUldVakJTUVZGSUwwSkNhM2RHTkVWV1pESnNjMkpIYkdoaVZVSTFZak5PZWxsWVNuQlpWelIxWW0xV01FMURkMGREYVhOSFFWRlJRZ3BuTnpoM1FWRkZSVWh0YURCa1NFSjZUMms0ZGxveWJEQmhTRlpwVEcxT2RtSlRPWE5pTW1Sd1ltazVkbGxZVmpCaFJFRjFRbWR2Y2tKblJVVkJXVTh2Q2sxQlJVbENRMEZOU0cxb01HUklRbnBQYVRoMldqSnNNR0ZJVm1sTWJVNTJZbE01YzJJeVpIQmlhVGwyV1ZoV01HRkVRMEpwWjFsTFMzZFpRa0pCU0ZjS1pWRkpSVUZuVWpoQ1NHOUJaVUZDTWtGRGMzZDJUbmh2YVUxdWFUUmtaMjFMVmpVd1NEQm5OVTFhV1VNNGNIZDZlVEUxUkZGUU5ubHlTVm8yUVVGQlFncHFjVUpCVVZvMFFVRkJVVVJCUldOM1VsRkpaMlZYVlcxMGJrUXdUVVpWYkRWcmExZzNibUpOWkV4WFEzTkVSMGxRZW1SSmJFNHJWMkZhUmpCVWJXdERDa2xSUXpjck16RnpZWEZ5Um1VNVVtMWtkVlphTW1SNFdHaFZVSEpoYW14MGRWTkVTR0l4ZGxOSFQyTjFTR3BCUzBKblozRm9hMnBQVUZGUlJFRjNUbThLUVVSQ2JFRnFSVUZ1TWl0MWRVeEljMjVJT1VSaU4zcHJTV1JHTmpWWmFHbFlZbWROVFVZdkwybElZeXRDTDFGRlZFc3dTRmxXWTA5UVZFc3pjRFEyUmdwVmVsaEdSRFo0Y2tGcVFVOHlhSEpyWm1wQ1MwRk9TMnBLU25oSVZqTkdWbkowVXl0VVVqQkhRMUF3U0hwRE0wUTNRbkk1TlZSWWVtWlBOeXRxTkVSa0NqZ3ZUaTloUVhJMlNXSnpQUW90TFMwdExVVk9SQ0JEUlZKVVNVWkpRMEZVUlMwdExTMHRDZz09In19fX0="
|
||||
}
|
||||
]
|
||||
},
|
||||
"messageSignature": {
|
||||
"messageDigest": {
|
||||
"algorithm": "SHA2_256",
|
||||
"digest": "Xmrp3ljBF3vqYVtPy/sv1ojoxLUcLla2o46BeDPsJKI="
|
||||
},
|
||||
"signature": "MEUCIDQSJi9aertQhmT+ce1jKNdCe4KScsKGq9fPm3422DBSAiEAhj1sxZ96orITsQxyMLIDRJimpoy1J1MyflcQVwkkzhs="
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Identity-bound local HTTP readiness; ordinary legacy health remains compatible."""
|
||||
|
||||
import json
|
||||
import threading
|
||||
from dataclasses import asdict, replace
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.gateway.runtime import (
|
||||
GatewayHealthIdentity,
|
||||
GatewayRuntime,
|
||||
GatewayRuntimePaths,
|
||||
GatewayStartOptions,
|
||||
_gateway_health_ready,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def health_server():
|
||||
reply = {"status": 200, "body": b'{"status":"ok"}'}
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
assert self.path == "/health"
|
||||
self.send_response(reply["status"])
|
||||
self.end_headers()
|
||||
self.wfile.write(reply["body"])
|
||||
|
||||
def log_message(self, *_args):
|
||||
pass
|
||||
|
||||
server = HTTPServer(("127.0.0.1", 0), Handler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
yield server.server_address[1], reply
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join(timeout=5)
|
||||
assert not thread.is_alive()
|
||||
|
||||
|
||||
def test_restart_requires_identity_while_legacy_health_still_works(tmp_path, health_server):
|
||||
port, reply = health_server
|
||||
runtime = GatewayRuntime(paths=GatewayRuntimePaths.for_instance(data_dir=tmp_path))
|
||||
identity = GatewayHealthIdentity("a" * 64, "b" * 32, "0.3.6")
|
||||
with runtime.foreground_instance(GatewayStartOptions(port=port)):
|
||||
runtime.publish_health_host("127.0.0.1")
|
||||
assert _gateway_health_ready("127.0.0.1", port)
|
||||
assert not runtime.verify_ready(identity) # Older / unrelated HTTP 200.
|
||||
reply["body"] = json.dumps({
|
||||
"status": "ok", "ready": True,
|
||||
"runtime": {**asdict(identity), "future_optional_field": "ignored"},
|
||||
}).encode()
|
||||
assert runtime.verify_ready(identity)
|
||||
for wrong in (
|
||||
replace(identity, instance_id="c" * 64),
|
||||
replace(identity, run_id="d" * 32),
|
||||
replace(identity, version="0.3.5"),
|
||||
):
|
||||
assert not runtime.verify_ready(wrong)
|
||||
assert not runtime.verify_ready(identity) # Port alone outlives its owner.
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status,body", [
|
||||
(503, b'{"status":"ok","ready":true}'),
|
||||
(200, b'{"status":"ok","ready":false}'),
|
||||
(200, b'{"status":"ok"}' + b' ' * 4096),
|
||||
(200, b'[]'),
|
||||
])
|
||||
def test_unready_or_invalid_response_cannot_confirm_restart(health_server, status, body):
|
||||
port, reply = health_server
|
||||
reply.update(status=status, body=body)
|
||||
assert not _gateway_health_ready("127.0.0.1", port, expected=GatewayHealthIdentity("a" * 64, "b" * 32, "0.3.6"))
|
||||
@@ -49,6 +49,41 @@ def _paths(tmp_path: Path) -> GatewayRuntimePaths:
|
||||
return GatewayRuntimePaths.for_instance(data_dir=tmp_path)
|
||||
|
||||
|
||||
def test_runtime_state_publish_keeps_existing_snapshot_readable(tmp_path):
|
||||
"""Status polling must not prevent a gateway from publishing readiness."""
|
||||
from nanobot.utils.atomic_file import _open_snapshot
|
||||
|
||||
runtime = GatewayRuntime(paths=_paths(tmp_path / "网关 home"))
|
||||
previous = {"pid": os.getpid(), "identity": "fixture", "command": ["nanobot", "gateway"]}
|
||||
current = {**previous, "health_host": "127.0.0.1"}
|
||||
runtime._write_state(previous)
|
||||
with _open_snapshot(runtime.paths.state_path) as snapshot:
|
||||
runtime._write_state(current)
|
||||
assert json.loads(snapshot.read()) == previous
|
||||
assert runtime._read_state() == current
|
||||
assert list(runtime.paths.run_dir.glob("*.tmp")) == []
|
||||
if os.name != "nt":
|
||||
assert runtime.paths.state_path.stat().st_mode & 0o777 == 0o600
|
||||
|
||||
|
||||
def test_runtime_state_reader_does_not_block_publish_while_decoding(tmp_path, monkeypatch):
|
||||
"""Pause a real status read while a readiness update replaces its record."""
|
||||
runtime = GatewayRuntime(paths=_paths(tmp_path))
|
||||
previous = {"pid": os.getpid(), "identity": "fixture"}
|
||||
current = {**previous, "health_host": "127.0.0.1"}
|
||||
runtime._write_state(previous)
|
||||
decode = json.loads
|
||||
|
||||
def publish_during_decode(value, **kwargs):
|
||||
runtime._write_state(current)
|
||||
return decode(value, **kwargs)
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr("nanobot.process_runtime.json.loads", publish_during_decode)
|
||||
assert runtime._read_state() == previous
|
||||
assert runtime._read_state() == current
|
||||
|
||||
|
||||
_FOREGROUND_CHILD = r"""
|
||||
import os
|
||||
import signal
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from types import SimpleNamespace
|
||||
@@ -43,6 +44,7 @@ def _fake_interactive_login(
|
||||
provider,
|
||||
proxy,
|
||||
open_browser,
|
||||
storage,
|
||||
) -> OAuthToken:
|
||||
captured.update(
|
||||
provider=provider,
|
||||
@@ -80,6 +82,7 @@ def test_authorization_url_comes_from_oauth_cli_kit() -> None:
|
||||
assert params["state"]
|
||||
finally:
|
||||
flow.cancel()
|
||||
flow.wait_closed()
|
||||
|
||||
|
||||
def test_local_flow_delegates_browser_and_callback_to_public_oauth_cli_kit(
|
||||
@@ -248,3 +251,41 @@ def test_remote_flow_expires_while_waiting_for_callback(
|
||||
complete_openai_codex_oauth_login(flow)
|
||||
finally:
|
||||
flow.cancel()
|
||||
flow.wait_closed()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("finish", ["cancel", "expiry", "success"])
|
||||
def test_worker_exit_and_credential_commit_are_distinct(monkeypatch, tmp_path, finish):
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
target = tmp_path / "oauth.json"
|
||||
monkeypatch.setenv("OAUTH_CLI_KIT_TOKEN_PATH", str(target))
|
||||
|
||||
def login(*, print_fn, storage, **_kwargs):
|
||||
print_fn(_authorization_url())
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
token = OAuthToken(access="fixture-access", refresh="fixture-refresh", expires=123)
|
||||
storage.save(token)
|
||||
return token
|
||||
|
||||
monkeypatch.setattr(codex_oauth, "login_oauth_interactive", login)
|
||||
flow = start_openai_codex_oauth_login(timeout_s=5, open_browser=False)
|
||||
try:
|
||||
assert entered.wait(1)
|
||||
assert flow.has_pending_work
|
||||
if finish == "cancel":
|
||||
flow.cancel()
|
||||
elif finish == "expiry":
|
||||
# Advance the shared clock used by both the flow and its save guard.
|
||||
now = time.monotonic() + 10
|
||||
monkeypatch.setattr(codex_oauth, "time", SimpleNamespace(monotonic=lambda: now))
|
||||
assert flow.has_pending_work
|
||||
assert not target.exists()
|
||||
finally:
|
||||
release.set()
|
||||
flow.wait_closed()
|
||||
assert not flow.has_pending_work
|
||||
assert target.exists() is (finish == "success")
|
||||
if finish != "success":
|
||||
with pytest.raises(OpenAICodexOAuthError):
|
||||
flow.complete()
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import queue
|
||||
import threading
|
||||
@@ -191,6 +192,50 @@ def test_pending_login_accepts_authorization_code_from_remote_browser(
|
||||
assert get_xai_oauth_login_status() == token
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_joins_accepted_callback_request_and_expiry_timer(monkeypatch):
|
||||
entered, release, server_closing = threading.Event(), threading.Event(), threading.Event()
|
||||
monkeypatch.setattr(xai_oauth, "_discover", lambda _: _Discovery(
|
||||
authorization_endpoint="https://auth.x.ai/oauth2/authorize",
|
||||
token_endpoint="https://auth.x.ai/oauth2/token", userinfo_endpoint=None,
|
||||
))
|
||||
callback_page = xai_oauth._callback_page
|
||||
|
||||
def render_callback(*args):
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
return callback_page(*args)
|
||||
|
||||
monkeypatch.setattr(xai_oauth, "_callback_page", render_callback)
|
||||
flow = start_xai_oauth_login(timeout_s=5)
|
||||
server_close = flow._server.server_close
|
||||
|
||||
def observed_close():
|
||||
server_closing.set()
|
||||
server_close()
|
||||
|
||||
monkeypatch.setattr(flow._server, "server_close", observed_close)
|
||||
params = parse_qs(urlsplit(flow.authorization_url).query)
|
||||
request = asyncio.create_task(asyncio.to_thread(httpx.get, flow.redirect_uri, params={
|
||||
"code": "fixture-code", "state": params["state"][0],
|
||||
}, trust_env=False))
|
||||
try:
|
||||
assert await asyncio.to_thread(entered.wait, 1)
|
||||
flow.cancel()
|
||||
closing = asyncio.create_task(asyncio.to_thread(flow.wait_closed))
|
||||
assert await asyncio.to_thread(server_closing.wait, 1)
|
||||
assert flow.has_pending_work
|
||||
assert not closing.done()
|
||||
finally:
|
||||
release.set()
|
||||
flow.cancel()
|
||||
await asyncio.to_thread(flow.wait_closed)
|
||||
response = await request
|
||||
await closing
|
||||
assert response.status_code == 200
|
||||
assert not flow.has_pending_work
|
||||
|
||||
|
||||
def test_expired_token_refreshes_once_and_persists_rotated_refresh_token(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path,
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot import bun
|
||||
|
||||
|
||||
def test_ensure_bun_reuses_matching_system_runtime(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(bun.shutil, "which", lambda _: "/bin/bun")
|
||||
monkeypatch.setattr(bun, "_matches_version", lambda _: True)
|
||||
assert bun.ensure_bun(cache_dir=tmp_path / "unused") == "/bin/bun"
|
||||
assert not (tmp_path / "unused").exists()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def download(monkeypatch):
|
||||
target = "windows-x64-baseline" if os.name == "nt" else "linux-x64-baseline"
|
||||
name = "bun.exe" if os.name == "nt" else "bun"
|
||||
data = io.BytesIO()
|
||||
with zipfile.ZipFile(data, "w") as archive:
|
||||
archive.writestr(f"bun-{target}/{name}", b"runtime")
|
||||
archive.writestr("../../unwanted", b"do not extract")
|
||||
raw = data.getvalue()
|
||||
calls = []
|
||||
|
||||
def open_url(url, *, timeout):
|
||||
calls.append(url)
|
||||
return io.BytesIO(raw)
|
||||
|
||||
monkeypatch.setattr(bun.shutil, "which", lambda _: None)
|
||||
monkeypatch.setattr(bun, "_target", lambda: target)
|
||||
monkeypatch.setitem(bun._ARCHIVES, target, hashlib.sha256(raw).hexdigest())
|
||||
monkeypatch.setattr(bun.urllib.request, "urlopen", open_url)
|
||||
monkeypatch.setattr(bun, "_matches_version", lambda path: Path(path).read_bytes() == b"runtime")
|
||||
return target, calls
|
||||
|
||||
|
||||
def test_bun_download_checks_hash_extracts_only_runtime_and_caches(download, tmp_path):
|
||||
_, calls = download
|
||||
executable = bun.ensure_bun(cache_dir=tmp_path)
|
||||
assert Path(executable).read_bytes() == b"runtime"
|
||||
assert not list(tmp_path.rglob("unwanted"))
|
||||
assert bun.ensure_bun(cache_dir=tmp_path) == executable
|
||||
assert len(calls) == 1
|
||||
assert calls[0].startswith("https://github.com/oven-sh/bun/releases/download/bun-v")
|
||||
|
||||
|
||||
def test_bun_rejects_corrupt_download(download, monkeypatch, tmp_path):
|
||||
target, _ = download
|
||||
monkeypatch.setitem(bun._ARCHIVES, target, "0" * 64)
|
||||
with pytest.raises(bun.BunUnavailableError, match="checksum"):
|
||||
bun.ensure_bun(cache_dir=tmp_path)
|
||||
assert not list(tmp_path.rglob("bun.exe"))
|
||||
assert not list(tmp_path.rglob("bun"))
|
||||
|
||||
|
||||
def test_bun_rejects_unrunnable_download(download, monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(bun, "_matches_version", lambda _: False)
|
||||
with pytest.raises(bun.BunUnavailableError, match="cannot run"):
|
||||
bun.ensure_bun(cache_dir=tmp_path)
|
||||
assert not list(tmp_path.rglob(".install-*"))
|
||||
|
||||
|
||||
def test_private_bun_path_does_not_modify_parent_environment(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("PATH", "original")
|
||||
runtime = tmp_path / "bun"
|
||||
runtime.write_bytes(b"runtime")
|
||||
with bun.bun_environment(str(runtime)) as env:
|
||||
alias_dir = Path(env["PATH"].split(os.pathsep)[0])
|
||||
node = alias_dir / ("node.exe" if os.name == "nt" else "node")
|
||||
assert node.read_bytes() == b"runtime"
|
||||
assert env["PATH"].endswith(os.pathsep + "original")
|
||||
assert not alias_dir.exists()
|
||||
assert os.environ["PATH"] == "original"
|
||||
@@ -0,0 +1,271 @@
|
||||
"""Real shared-data leases across process and installation identities."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from contextlib import ExitStack, contextmanager
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.data_access import (
|
||||
DataStartupGrant,
|
||||
data_access,
|
||||
profile_data_access,
|
||||
profile_data_paths,
|
||||
)
|
||||
from nanobot.installation_lock import InstallationBusyError
|
||||
|
||||
_CHILD = """
|
||||
import json, os, sys
|
||||
from nanobot.data_access import DataStartupGrant, data_access
|
||||
sys.prefix = sys.argv[1]
|
||||
grant = DataStartupGrant(**json.loads(os.environ['TEST_DATA_GRANT'])) if 'TEST_DATA_GRANT' in os.environ else None
|
||||
with data_access(sys.argv[4:], updating=sys.argv[2] == 'update', job_id=sys.argv[3] or None, grant=grant) as lease:
|
||||
if sys.argv[3] and sys.argv[2] == 'update':
|
||||
lease.reserve()
|
||||
print('ready', flush=True)
|
||||
sys.stdin.read(1)
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def private_home(tmp_path, monkeypatch):
|
||||
home = tmp_path / "private home"
|
||||
home.mkdir()
|
||||
monkeypatch.setenv("HOME", str(home))
|
||||
monkeypatch.setenv("USERPROFILE", str(home))
|
||||
return home
|
||||
|
||||
|
||||
@contextmanager
|
||||
def process_access(environment, paths, *, updating=False, job_id=None, grant=None):
|
||||
env = os.environ.copy()
|
||||
if grant is not None:
|
||||
env["TEST_DATA_GRANT"] = json.dumps({"job_id": grant.job_id, "participant": grant.participant, "token": grant.token})
|
||||
process = subprocess.Popen(
|
||||
[sys.executable, "-c", _CHILD, str(environment), "update" if updating else "runtime", job_id or "", *map(str, paths)],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env,
|
||||
)
|
||||
try:
|
||||
assert process.stdout.readline().strip() == "ready", process.stderr.read()
|
||||
yield process
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.stdin.write("x")
|
||||
process.stdin.flush()
|
||||
process.communicate(timeout=10)
|
||||
|
||||
|
||||
def crash_process(process):
|
||||
# Windows venv python.exe redirects to a child interpreter. Killing only
|
||||
# that launcher leaves the actual lease holder alive until stdin closes.
|
||||
if os.name == "nt":
|
||||
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
|
||||
check=True, capture_output=True, timeout=10)
|
||||
else:
|
||||
process.kill()
|
||||
process.wait(timeout=10)
|
||||
|
||||
|
||||
def test_shared_data_blocks_update_across_installations_until_last_writer_exits(private_home, tmp_path):
|
||||
store = tmp_path / "shared sessions"
|
||||
with process_access(tmp_path / "first environment", [store]) as first:
|
||||
with process_access(tmp_path / "second environment", [store]):
|
||||
with data_access([store]):
|
||||
pass # Normal runtime sharing remains allowed.
|
||||
crash_process(first)
|
||||
with pytest.raises(InstallationBusyError, match="data is in use"):
|
||||
with data_access([store], updating=True):
|
||||
pytest.fail("The other installation's writer was ignored")
|
||||
with data_access([store], updating=True):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize("held_parent", [False, True])
|
||||
def test_overlapping_roots_block_but_siblings_remain_usable(private_home, tmp_path, held_parent):
|
||||
parent = tmp_path / "sessions"
|
||||
child = parent / "chat.jsonl"
|
||||
held, requested = (parent, child) if held_parent else (child, parent)
|
||||
with process_access(tmp_path / "another environment", [held], updating=True):
|
||||
with pytest.raises(InstallationBusyError):
|
||||
with data_access([requested]):
|
||||
pytest.fail("An ancestor/descendant path bypassed maintenance")
|
||||
with data_access([tmp_path / "separate sessions"]):
|
||||
pass
|
||||
|
||||
|
||||
def test_alias_and_partial_acquisition_do_not_bypass_or_leak_leases(private_home, tmp_path):
|
||||
store, available = tmp_path / "z-store", tmp_path / "a-store"
|
||||
store.mkdir()
|
||||
alias = tmp_path / "alias"
|
||||
try:
|
||||
alias.symlink_to(store, target_is_directory=True)
|
||||
except OSError:
|
||||
pytest.skip("Directory symlinks are not enabled for this account")
|
||||
with process_access(tmp_path / "other environment", [alias]) as writer:
|
||||
with pytest.raises(InstallationBusyError):
|
||||
with data_access([available, store], updating=True):
|
||||
pytest.fail("A symlink alias bypassed the writer lease")
|
||||
with data_access([available]):
|
||||
pass # Failed multi-store acquisition released its earlier leases.
|
||||
crash_process(writer)
|
||||
with data_access([store], updating=True):
|
||||
pass
|
||||
|
||||
|
||||
def test_job_reservation_survives_process_exit_until_same_scope_is_recovered(private_home, tmp_path):
|
||||
store, sibling = tmp_path / "sessions", tmp_path / "unrelated sessions"
|
||||
job_id = str(uuid4())
|
||||
with process_access(tmp_path / "update environment", [store], updating=True, job_id=job_id) as worker:
|
||||
crash_process(worker)
|
||||
# No process holds the leases now. The durable reservation still excludes
|
||||
# overlapping readers/writers from other installations, but not unrelated data.
|
||||
for path in (store, store / "chat.jsonl", store.parent):
|
||||
with pytest.raises(InstallationBusyError, match="reserved"):
|
||||
with data_access([path]):
|
||||
pytest.fail("A runtime entered an interrupted maintenance scope")
|
||||
with data_access([sibling]):
|
||||
pass
|
||||
with pytest.raises(InstallationBusyError, match="unfinished update"):
|
||||
with data_access([store], updating=True, job_id=str(uuid4())):
|
||||
pytest.fail("Another job took over the interrupted update")
|
||||
with pytest.raises(InstallationBusyError, match="unfinished update"):
|
||||
with data_access([sibling], updating=True, job_id=job_id):
|
||||
pytest.fail("The same ID changed the approved data scope")
|
||||
with data_access([store], updating=True, job_id=job_id) as recovered:
|
||||
recovered.release_reservation()
|
||||
with data_access([store]):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize("legacy", [False, True])
|
||||
def test_profile_handoff_keeps_delivery_leased_without_expanding_old_grant(private_home, tmp_path, legacy):
|
||||
selectors = dict(home=private_home, data_dir=tmp_path / "data",
|
||||
config=tmp_path / "data/config.json", workspace=tmp_path / "workspace")
|
||||
delivery = selectors["data_dir"] / "delivery"
|
||||
scope = tuple(path for path in profile_data_paths(**selectors) if not legacy or path != delivery)
|
||||
job_id, participant = str(uuid4()), "a" * 64
|
||||
with data_access(scope, updating=True, job_id=job_id) as owner:
|
||||
owner.reserve()
|
||||
with ExitStack() as runtime:
|
||||
with data_access(scope, job_id=job_id) as owner:
|
||||
grant = owner.grant_startup(participant, scope)
|
||||
runtime.enter_context(profile_data_access(**selectors, grant=grant))
|
||||
# The old reservation is not enlarged to authorize initialization.
|
||||
saved = json.loads(owner.reservation_path.read_text())
|
||||
assert saved["grants"][participant]["roots"] == sorted(str(path.resolve()).casefold() for path in scope)
|
||||
assert not delivery.exists()
|
||||
owner.release_reservation()
|
||||
# Once handoff ends, the running profile still owns the new store lease.
|
||||
with pytest.raises(InstallationBusyError, match="data is in use"):
|
||||
with data_access((delivery,), updating=True):
|
||||
pytest.fail("A delivery store writer escaped the runtime lease")
|
||||
with data_access((delivery,), updating=True):
|
||||
pass
|
||||
|
||||
|
||||
def test_profile_handoff_cannot_defer_an_existing_store(private_home, tmp_path):
|
||||
selectors = dict(home=private_home, data_dir=tmp_path / "data",
|
||||
config=tmp_path / "data/config.json", workspace=tmp_path / "workspace")
|
||||
scope = tuple(path for path in profile_data_paths(**selectors)
|
||||
if path not in {selectors["data_dir"] / "delivery", selectors["data_dir"] / "auth"})
|
||||
job_id = str(uuid4())
|
||||
with data_access(scope, updating=True, job_id=job_id) as owner:
|
||||
owner.reserve()
|
||||
with data_access(scope, job_id=job_id) as handoff:
|
||||
with pytest.raises(ValueError, match="exceeds the reviewed data scope"):
|
||||
handoff.grant_profile_startup("a" * 64, **selectors)
|
||||
|
||||
|
||||
def test_verified_handoff_admits_only_granted_scope_until_explicit_completion(private_home, tmp_path):
|
||||
store = tmp_path / "sessions"
|
||||
runtime_scope = [store / "profile"]
|
||||
job_id, participant = str(uuid4()), "a" * 64
|
||||
with data_access([store], updating=True, job_id=job_id) as owner:
|
||||
owner.reserve()
|
||||
with data_access([store], job_id=job_id) as handoff:
|
||||
grant = handoff.grant_startup(participant, runtime_scope)
|
||||
assert grant.token not in handoff.reservation_path.read_text()
|
||||
assert grant.token not in repr(grant)
|
||||
with pytest.raises(ValueError, match="exceeds"):
|
||||
handoff.grant_startup("b" * 64, [store.parent])
|
||||
with pytest.raises(InstallationBusyError, match="scope"):
|
||||
with data_access([store], grant=grant):
|
||||
pytest.fail("A participant expanded its allowed data roots")
|
||||
invalid = DataStartupGrant(job_id, participant, "0" * 64)
|
||||
with pytest.raises(InstallationBusyError, match="scope"):
|
||||
with data_access(runtime_scope, grant=invalid):
|
||||
pytest.fail("A job ID and participant name bypassed the grant")
|
||||
with process_access(tmp_path / "target environment", runtime_scope, grant=grant):
|
||||
with pytest.raises(InstallationBusyError):
|
||||
with data_access(runtime_scope, grant=grant):
|
||||
pytest.fail("Two processes claimed one startup participant")
|
||||
with pytest.raises(InstallationBusyError, match="still running"):
|
||||
handoff.grant_startup(participant, runtime_scope)
|
||||
with pytest.raises(InstallationBusyError, match="reserved"):
|
||||
with data_access(runtime_scope):
|
||||
pytest.fail("An ordinary startup entered maintenance")
|
||||
# Only the lifecycle owner calls this after verifying the runtime;
|
||||
# participant leases are shared, so completion does not deadlock.
|
||||
handoff.release_reservation()
|
||||
with data_access(runtime_scope):
|
||||
pass
|
||||
with pytest.raises(InstallationBusyError, match="no longer reserved"):
|
||||
with data_access(runtime_scope, grant=grant):
|
||||
pytest.fail("A completed startup grant was replayed")
|
||||
|
||||
|
||||
def test_crashed_handoff_keeps_fence_and_child_lease_until_recovery(private_home, tmp_path):
|
||||
store = tmp_path / "sessions"
|
||||
job_id, participant = str(uuid4()), "c" * 64
|
||||
with data_access([store], updating=True, job_id=job_id) as owner:
|
||||
owner.reserve()
|
||||
coordinator = subprocess.Popen([
|
||||
sys.executable, "-c", """
|
||||
import json, sys
|
||||
from dataclasses import asdict
|
||||
from nanobot.data_access import data_access
|
||||
with data_access([sys.argv[1]], job_id=sys.argv[2]) as handoff:
|
||||
grant = handoff.grant_startup(sys.argv[3], [sys.argv[1]])
|
||||
print(json.dumps(asdict(grant)), flush=True)
|
||||
sys.stdin.read(1)
|
||||
""", str(store), job_id, participant,
|
||||
], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
try:
|
||||
encoded = coordinator.stdout.readline()
|
||||
assert encoded, coordinator.stderr.read()
|
||||
grant = DataStartupGrant(**json.loads(encoded))
|
||||
with process_access(tmp_path / "target environment", [store], grant=grant) as child:
|
||||
crash_process(coordinator)
|
||||
# The coordinator's OS leases are gone, but the child owns its own.
|
||||
with pytest.raises(InstallationBusyError):
|
||||
with data_access([store], updating=True, job_id=job_id):
|
||||
pytest.fail("Repair raced an orphan startup still using data")
|
||||
with pytest.raises(InstallationBusyError, match="reserved"):
|
||||
with data_access([store]):
|
||||
pytest.fail("Coordinator exit incorrectly lifted maintenance")
|
||||
crash_process(child)
|
||||
finally:
|
||||
if coordinator.poll() is None:
|
||||
crash_process(coordinator)
|
||||
coordinator.communicate(timeout=10)
|
||||
with data_access([store], job_id=job_id) as recovered:
|
||||
replacement = recovered.grant_startup(participant, [store])
|
||||
with pytest.raises(InstallationBusyError, match="scope"):
|
||||
with data_access([store], grant=grant):
|
||||
pytest.fail("An obsolete grant survived explicit reauthorization")
|
||||
with data_access([store], grant=replacement) as startup:
|
||||
with pytest.raises(ValueError, match="Only an update job"):
|
||||
startup.release_reservation()
|
||||
with pytest.raises(ValueError, match="Only an update job"):
|
||||
startup.reserve()
|
||||
# Exiting the recovered handoff still does not mean verification passed.
|
||||
with data_access([store], updating=True, job_id=job_id) as repair:
|
||||
repair.reserve() # New package mutation revokes all startup grants.
|
||||
with pytest.raises(InstallationBusyError, match="scope"):
|
||||
with data_access([store], grant=replacement):
|
||||
pytest.fail("A grant from before repair authorized a new startup")
|
||||
with data_access([store], updating=True, job_id=job_id) as repair:
|
||||
repair.release_reservation()
|
||||
@@ -0,0 +1,834 @@
|
||||
"""Exercise the public installers against real, offline package managers.
|
||||
|
||||
The tiny wheel reports its runtime identity; it is not the nanobot application.
|
||||
No gateway, model, user configuration or public package index is used by these tests.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import sysconfig
|
||||
import threading
|
||||
import tomllib
|
||||
import urllib.request
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from zipfile import ZipFile
|
||||
|
||||
import pytest
|
||||
from packaging.tags import sys_tags
|
||||
|
||||
from nanobot import releases
|
||||
from scripts.release_install_guide import (
|
||||
bootstrap_commands,
|
||||
install_command,
|
||||
render_install_command,
|
||||
verification_command,
|
||||
)
|
||||
|
||||
SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"
|
||||
WINDOWS = os.name == "nt"
|
||||
BASE_PYTHON = sys._base_executable
|
||||
|
||||
|
||||
def _wheel(directory, version, *, platform="any", package="nanobot-ai", extras=(), installer_receipt=False):
|
||||
module = package.replace("-", "_") if package != "nanobot-ai" else "nanobot"
|
||||
wheel_name = package.replace("-", "_")
|
||||
metadata = f"{wheel_name}-{version}.dist-info"
|
||||
files = {
|
||||
"nanobot/__init__.py": f'__version__ = "{version}"\n',
|
||||
"nanobot/__main__.py": """
|
||||
import json
|
||||
import sys
|
||||
import nanobot
|
||||
|
||||
def main():
|
||||
print("INSTALLER_PROBE " + json.dumps({
|
||||
"version": nanobot.__version__, "package": nanobot.__file__,
|
||||
"python": sys.executable, "prefix": sys.prefix,
|
||||
"isolated": sys.flags.isolated, "args": sys.argv[1:],
|
||||
}))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
""",
|
||||
f"{metadata}/METADATA": f"Metadata-Version: 2.1\nName: nanobot-ai\nVersion: {version}\nRequires-Python: >=3.11\n",
|
||||
f"{metadata}/WHEEL": "Wheel-Version: 1.0\nGenerator: installer-test\nRoot-Is-Purelib: true\nTag: py3-none-any\n",
|
||||
f"{metadata}/entry_points.txt": "[console_scripts]\nnanobot = nanobot.__main__:main\n",
|
||||
}
|
||||
files = {name.replace("nanobot/", f"{module}/"): content for name, content in files.items()}
|
||||
files[f"{module}/__main__.py"] = files[f"{module}/__main__.py"].replace("nanobot", module)
|
||||
files[f"{metadata}/METADATA"] = files[f"{metadata}/METADATA"].replace("Name: nanobot-ai", f"Name: {package}")
|
||||
files[f"{metadata}/METADATA"] += "".join(f"Provides-Extra: {extra}\n" for extra in extras)
|
||||
files[f"{metadata}/WHEEL"] = files[f"{metadata}/WHEEL"].replace("py3-none-any", f"py3-none-{platform}")
|
||||
files[f"{metadata}/entry_points.txt"] = f"[console_scripts]\n{module} = {module}.__main__:main\n"
|
||||
if installer_receipt:
|
||||
files["nanobot/installation_receipt.py"] = (SCRIPTS.parent / "nanobot/installation_receipt.py").read_text()
|
||||
files["nanobot/utils/__init__.py"] = ""
|
||||
files["nanobot/utils/atomic_file.py"] = (SCRIPTS.parent / "nanobot/utils/atomic_file.py").read_text()
|
||||
record = []
|
||||
path = directory / f"{wheel_name}-{version}-py3-none-{platform}.whl"
|
||||
with ZipFile(path, "w") as wheel:
|
||||
for name, content in files.items():
|
||||
data = content.encode()
|
||||
wheel.writestr(name, data)
|
||||
digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode()
|
||||
record.append(f"{name},sha256={digest},{len(data)}\n")
|
||||
wheel.writestr(f"{metadata}/RECORD", "".join(record) + f"{metadata}/RECORD,,\n")
|
||||
return path
|
||||
|
||||
|
||||
def _python(environment):
|
||||
return environment / ("Scripts/python.exe" if WINDOWS else "bin/python")
|
||||
|
||||
|
||||
def _run(command, sandbox, *, check=True):
|
||||
result = subprocess.run(command, cwd=sandbox["cwd"], env=sandbox["env"],
|
||||
capture_output=True, text=True, encoding="utf-8", timeout=90)
|
||||
if check:
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
return result
|
||||
|
||||
|
||||
def _installer(sandbox, *args, check=True):
|
||||
if WINDOWS:
|
||||
shell = shutil.which("powershell")
|
||||
if not shell:
|
||||
pytest.skip("Windows PowerShell is required")
|
||||
command = [shell, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
|
||||
"-File", str(SCRIPTS / "install.ps1")]
|
||||
else:
|
||||
command = ["/bin/sh", str(SCRIPTS / "install.sh")]
|
||||
return _run([*command, *args], sandbox, check=check)
|
||||
|
||||
|
||||
def _identity(result):
|
||||
reports = [json.loads(line.removeprefix("INSTALLER_PROBE "))
|
||||
for line in result.stdout.splitlines() if line.startswith("INSTALLER_PROBE ")]
|
||||
assert len(reports) == 1, result.stdout
|
||||
return reports[0]
|
||||
|
||||
|
||||
def _expose(sandbox, name):
|
||||
# Explicit overrides let local verification use disposable manager installations.
|
||||
source = os.environ.get(f"NANOBOT_TEST_{name.upper()}") or shutil.which(name)
|
||||
if not source:
|
||||
pytest.skip(f"{name} is required for this real installer check")
|
||||
destination = sandbox["bin"] / (f"{name}.exe" if WINDOWS else name)
|
||||
if WINDOWS:
|
||||
shutil.copy2(source, destination)
|
||||
else:
|
||||
destination.symlink_to(source)
|
||||
return str(destination)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sandbox(tmp_path):
|
||||
root = tmp_path.resolve() / "user's 数据 $safe"
|
||||
root.mkdir()
|
||||
command_bin = root / "commands"
|
||||
command_bin.mkdir()
|
||||
wheels = root / "wheels"
|
||||
wheels.mkdir()
|
||||
# A checkout and PYTHONPATH must not replace the package just installed.
|
||||
checkout = root / "checkout"
|
||||
(checkout / "nanobot").mkdir(parents=True)
|
||||
(checkout / "nanobot/__init__.py").write_text('raise RuntimeError("wrong checkout imported")\n')
|
||||
env = {key: value for key, value in os.environ.items()
|
||||
if key.upper() in {"SYSTEMROOT", "WINDIR", "COMSPEC", "PATHEXT"}}
|
||||
system_path = (str(Path(env["SYSTEMROOT"]) / "System32") if WINDOWS else "/usr/bin:/bin")
|
||||
env.update({
|
||||
"HOME": str(root), "USERPROFILE": str(root),
|
||||
"PATH": str(command_bin) + os.pathsep + system_path,
|
||||
"PYTHON": BASE_PYTHON, "PYTHONPATH": str(checkout), "PYTHONUTF8": "1",
|
||||
"NANOBOT_SKIP_WIZARD": "1", "NANOBOT_VENV": str(root / "managed"),
|
||||
"NANOBOT_BIN_DIR": str(root / "launchers"),
|
||||
"XDG_CONFIG_HOME": str(root / "config"), "XDG_CACHE_HOME": str(root / "cache"),
|
||||
"XDG_DATA_HOME": str(root / "data"), "APPDATA": str(root / "config"),
|
||||
"LOCALAPPDATA": str(root / "data"), "TMPDIR": str(root), "TMP": str(root), "TEMP": str(root),
|
||||
"UV_TOOL_DIR": str(root / "uv-tools"), "UV_TOOL_BIN_DIR": str(root / "uv-bin"),
|
||||
"UV_CACHE_DIR": str(root / "uv-cache"), "UV_NO_CONFIG": "1", "UV_NO_INDEX": "1",
|
||||
"UV_OFFLINE": "1", "UV_PYTHON_DOWNLOADS": "never", "UV_FIND_LINKS": wheels.as_uri(),
|
||||
"PIPX_HOME": str(root / "pipx"), "PIPX_BIN_DIR": str(root / "pipx-bin"),
|
||||
"PIPX_MAN_DIR": str(root / "man"), "PIPX_DEFAULT_BACKEND": "pip",
|
||||
"PIPX_DISABLE_SHARED_LIBS_AUTO_UPGRADE": "1", "PIPX_DEFAULT_PYTHON": BASE_PYTHON,
|
||||
"PIP_CONFIG_FILE": os.devnull, "PIP_NO_INDEX": "1", "PIP_FIND_LINKS": wheels.as_uri(),
|
||||
"PIP_DISABLE_PIP_VERSION_CHECK": "1", "PIP_NO_INPUT": "1",
|
||||
})
|
||||
return {"root": root, "bin": command_bin, "wheels": wheels, "cwd": checkout, "env": env}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("manager", ["uv", "pipx"])
|
||||
def test_installer_starts_and_upgrades_same_persistent_manager_environment(sandbox, manager):
|
||||
executable = _expose(sandbox, manager)
|
||||
_wheel(sandbox["wheels"], "0.0.1")
|
||||
_run([executable, *(["tool"] if manager == "uv" else []), "install", "--python", BASE_PYTHON, "nanobot-ai"], sandbox)
|
||||
prefix = (sandbox["root"] / "uv-tools/nanobot-ai" if manager == "uv"
|
||||
else sandbox["root"] / "pipx/venvs/nanobot-ai")
|
||||
for version in ("0.0.1", "0.0.2"):
|
||||
if version == "0.0.2":
|
||||
_wheel(sandbox["wheels"], version)
|
||||
identity = _identity(_installer(sandbox))
|
||||
assert identity["version"] == version
|
||||
assert Path(identity["prefix"]).resolve() == prefix
|
||||
assert Path(identity["package"]).resolve().is_relative_to(prefix)
|
||||
assert Path(identity["python"]).absolute() == _python(prefix)
|
||||
assert identity["isolated"] == 1
|
||||
assert identity["args"] == ["--version"]
|
||||
assert not (sandbox["root"] / "managed").exists()
|
||||
|
||||
|
||||
def test_rerunning_installer_preserves_uv_version_constraint(sandbox):
|
||||
uv = _expose(sandbox, "uv")
|
||||
_wheel(sandbox["wheels"], "0.0.1")
|
||||
_wheel(sandbox["wheels"], "0.0.2")
|
||||
_run([uv, "tool", "install", "--python", BASE_PYTHON, "nanobot-ai==0.0.1"], sandbox)
|
||||
assert _identity(_installer(sandbox))["version"] == "0.0.1"
|
||||
receipt = sandbox["root"] / "uv-tools/nanobot-ai/uv-receipt.toml"
|
||||
assert "==0.0.1" in receipt.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("exact", [False, True], ids=["registry", "exact-wheel"])
|
||||
@pytest.mark.parametrize("custom", ["constraint", "pip-options"])
|
||||
def test_installer_never_discards_pipx_install_policy(sandbox, exact, custom):
|
||||
pipx = _expose(sandbox, "pipx")
|
||||
_wheel(sandbox["wheels"], "0.0.1")
|
||||
requirement = "nanobot-ai>=0.0.1,<0.1" if custom == "constraint" else "nanobot-ai"
|
||||
options = ["--pip-args=--no-deps"] if custom == "pip-options" else []
|
||||
_run([pipx, "install", "--python", BASE_PYTHON, *options, requirement], sandbox)
|
||||
prefix = sandbox["root"] / "pipx/venvs/nanobot-ai"
|
||||
receipt = prefix / "pipx_metadata.json"
|
||||
original = receipt.read_bytes()
|
||||
if exact:
|
||||
_, artifact = _preview_manifest(sandbox)
|
||||
arguments = _wheel_arguments(sandbox, artifact)
|
||||
else:
|
||||
_wheel(sandbox["wheels"], "0.0.2")
|
||||
arguments = []
|
||||
result = _installer(sandbox, *arguments, check=False)
|
||||
assert result.returncode != 0
|
||||
assert "pipx installation settings" in result.stdout + result.stderr
|
||||
assert receipt.read_bytes() == original
|
||||
assert _verify_owner(sandbox, "pipx", prefix)["version"] == "0.0.1"
|
||||
assert not (sandbox["root"] / "managed").exists()
|
||||
|
||||
|
||||
def test_fresh_default_records_dedicated_environment_even_with_uv_available(sandbox):
|
||||
_expose(sandbox, "uv")
|
||||
_wheel(sandbox["wheels"], "0.0.1", installer_receipt=True)
|
||||
identity = _identity(_installer(sandbox))
|
||||
prefix = sandbox["root"] / "managed"
|
||||
assert Path(identity["prefix"]).resolve() == prefix
|
||||
receipt = prefix / "nanobot-install.json"
|
||||
original = receipt.read_bytes()
|
||||
assert json.loads(original) == {"schema_version": 1, "owner": "nanobot-installer",
|
||||
"environment": str(prefix), "extras": []}
|
||||
_wheel(sandbox["wheels"], "0.0.2", installer_receipt=True)
|
||||
assert _identity(_installer(sandbox))["version"] == "0.0.2"
|
||||
assert receipt.read_bytes() == original
|
||||
assert not (sandbox["root"] / "uv-tools/nanobot-ai").exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("original", ["pipx", "managed"])
|
||||
def test_existing_owner_wins_when_uv_is_installed_later(sandbox, original):
|
||||
if original == "pipx":
|
||||
executable = _expose(sandbox, "pipx")
|
||||
_wheel(sandbox["wheels"], "0.0.1")
|
||||
if original == "pipx":
|
||||
_run([executable, "install", "--python", BASE_PYTHON, "nanobot-ai"], sandbox)
|
||||
before = _identity(_installer(sandbox))
|
||||
_expose(sandbox, "uv")
|
||||
_wheel(sandbox["wheels"], "0.0.2")
|
||||
after = _identity(_installer(sandbox))
|
||||
assert after["version"] == "0.0.2"
|
||||
assert after["prefix"] == before["prefix"]
|
||||
assert after["python"] == before["python"]
|
||||
assert not (sandbox["root"] / "uv-tools/nanobot-ai").exists()
|
||||
|
||||
|
||||
def test_multiple_existing_installations_need_an_explicit_owner(sandbox):
|
||||
uv, pipx = _expose(sandbox, "uv"), _expose(sandbox, "pipx")
|
||||
_wheel(sandbox["wheels"], "0.0.1")
|
||||
_run([uv, "tool", "install", "--python", BASE_PYTHON, "nanobot-ai"], sandbox)
|
||||
_run([pipx, "install", "--python", BASE_PYTHON, "nanobot-ai"], sandbox)
|
||||
_wheel(sandbox["wheels"], "0.0.2")
|
||||
result = _installer(sandbox, check=False)
|
||||
assert result.returncode != 0
|
||||
assert "Multiple nanobot installations" in result.stdout + result.stderr
|
||||
for prefix in (sandbox["root"] / "uv-tools/nanobot-ai", sandbox["root"] / "pipx/venvs/nanobot-ai"):
|
||||
identity = _identity(_run([str(_python(prefix)), "-I", "-m", "nanobot", "--version"], sandbox))
|
||||
assert identity["version"] == "0.0.1"
|
||||
|
||||
|
||||
def test_activated_manager_environment_is_not_updated_with_pip(sandbox):
|
||||
executable = _expose(sandbox, "uv")
|
||||
_wheel(sandbox["wheels"], "0.0.1")
|
||||
_run([executable, "tool", "install", "--python", BASE_PYTHON, "nanobot-ai"], sandbox)
|
||||
before = _identity(_installer(sandbox))
|
||||
sandbox["env"]["PYTHON"] = before["python"]
|
||||
_wheel(sandbox["wheels"], "0.0.2")
|
||||
result = _installer(sandbox, check=False)
|
||||
assert result.returncode != 0
|
||||
assert "active Python belongs to uv or pipx" in result.stdout + result.stderr
|
||||
assert _identity(_run([before["python"], "-I", "-m", "nanobot", "--version"], sandbox))["version"] == "0.0.1"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("active", [True, False], ids=["active-venv", "managed-venv"])
|
||||
def test_python_install_uses_same_environment_and_quoted_launcher(sandbox, active):
|
||||
_wheel(sandbox["wheels"], "0.0.1")
|
||||
prefix = sandbox["root"] / ("active" if active else "managed")
|
||||
if active:
|
||||
_run([BASE_PYTHON, "-I", "-m", "venv", str(prefix)], sandbox)
|
||||
sandbox["env"]["PYTHON"] = str(_python(prefix))
|
||||
identity = _identity(_installer(sandbox))
|
||||
assert Path(identity["prefix"]).resolve() == prefix
|
||||
assert identity["isolated"] == 1
|
||||
if not WINDOWS and not active:
|
||||
wrapper = sandbox["root"] / "launchers/nanobot"
|
||||
launched = _identity(_run([str(wrapper), "--version"], sandbox))
|
||||
assert launched == identity
|
||||
|
||||
|
||||
@pytest.mark.parametrize("manager", ["uv", "pipx"])
|
||||
def test_failed_default_install_does_not_fall_through_to_available_manager(sandbox, manager):
|
||||
_expose(sandbox, manager)
|
||||
# Offline and no candidate: only the default dedicated environment is tried.
|
||||
result = _installer(sandbox, check=False)
|
||||
assert result.returncode != 0
|
||||
assert (sandbox["root"] / "managed").exists()
|
||||
assert not (sandbox["root"] / "uv-tools/nanobot-ai").exists()
|
||||
assert not (sandbox["root"] / "pipx/venvs/nanobot-ai").exists()
|
||||
assert "INSTALLER_PROBE" not in result.stdout
|
||||
receipt = sandbox["root"] / "managed/nanobot-install.json"
|
||||
selection = receipt.read_bytes()
|
||||
_wheel(sandbox["wheels"], "0.0.1", installer_receipt=True)
|
||||
retried = _identity(_installer(sandbox))
|
||||
assert Path(retried["prefix"]).resolve() == sandbox["root"] / "managed"
|
||||
assert receipt.read_bytes() == selection
|
||||
assert json.loads(selection)["extras"] == []
|
||||
assert not (sandbox["root"] / "uv-tools/nanobot-ai").exists()
|
||||
assert not (sandbox["root"] / "pipx/venvs/nanobot-ai").exists()
|
||||
|
||||
|
||||
def test_dry_run_does_not_create_tool_environment(sandbox):
|
||||
_expose(sandbox, "uv")
|
||||
result = _installer(sandbox, "--dry-run")
|
||||
assert "dedicated virtual environment" in result.stdout
|
||||
assert not (sandbox["root"] / "uv-tools").exists()
|
||||
assert "INSTALLER_PROBE" not in result.stdout
|
||||
|
||||
|
||||
def _preview_manifest(sandbox, *, damaged_hash=False, extras=()):
|
||||
version = "0.0.2.dev1"
|
||||
platform = next(tag.platform for tag in sys_tags()
|
||||
if tag.platform in releases.PLATFORMS.values())
|
||||
wheel = _wheel(sandbox["cwd"], version, platform=platform, extras=extras)
|
||||
digest = "0" * 64 if damaged_hash else hashlib.sha256(wheel.read_bytes()).hexdigest()
|
||||
artifacts = [releases.ReleaseArtifact(
|
||||
filename=name, size=wheel.stat().st_size if name == wheel.name else 123,
|
||||
sha256=digest if name == wheel.name else "c" * 64,
|
||||
) for name in sorted(releases.release_filenames(version))]
|
||||
manifest = releases.ReleaseManifest(version=version, source_commit="a" * 40,
|
||||
candidate_commit="b" * 40, requires_python=">=3.11",
|
||||
artifacts=artifacts)
|
||||
return manifest, next(item for item in artifacts if item.filename == wheel.name)
|
||||
|
||||
|
||||
def _owner_environment(sandbox, owner, *, existing):
|
||||
_wheel(sandbox["wheels"], "0.0.1")
|
||||
if owner == "pip":
|
||||
prefix = sandbox["root"] / "ordinary-venv"
|
||||
_run([BASE_PYTHON, "-I", "-m", "venv", str(prefix)], sandbox)
|
||||
executable = str(_python(prefix))
|
||||
if existing:
|
||||
_run([executable, "-I", "-m", "pip", "install", "nanobot-ai"], sandbox)
|
||||
else:
|
||||
executable = _expose(sandbox, owner)
|
||||
prefix = sandbox["root"] / ("uv-tools/nanobot-ai" if owner == "uv" else "pipx/venvs/nanobot-ai")
|
||||
sandbox["env"]["UV_PYTHON"] = BASE_PYTHON
|
||||
if existing:
|
||||
_run([executable, *(["tool"] if owner == "uv" else []), "install", "--python", BASE_PYTHON, "nanobot-ai"], sandbox)
|
||||
return executable, prefix
|
||||
|
||||
|
||||
def _verify_owner(sandbox, owner, prefix):
|
||||
if owner == "pip":
|
||||
return _identity(_run([str(_python(prefix)), "-I", "-m", "nanobot", "--version"], sandbox))
|
||||
command = verification_command(owner, windows=WINDOWS)
|
||||
shell = ["powershell", "-NoProfile", "-NonInteractive", "-Command"] if WINDOWS else ["/bin/sh", "-c"]
|
||||
return _identity(_run([*shell, command], sandbox))
|
||||
|
||||
|
||||
def _run_guide_command(sandbox, command, python, *, check=True):
|
||||
"""Run the same multiline command users copy, including shell quoting."""
|
||||
if WINDOWS:
|
||||
value = str(python).replace("'", "''")
|
||||
prelude = f"Set-Alias -Name python -Value '{value}'\n"
|
||||
shell = ["powershell", "-NoProfile", "-NonInteractive", "-Command"]
|
||||
else:
|
||||
prelude = f'python() {{ {shlex.quote(str(python))} "$@"; }}\n'
|
||||
shell = ["/bin/sh", "-c"]
|
||||
return _run([*shell, prelude + render_install_command(command, windows=WINDOWS)], sandbox, check=check)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("owner", ["uv", "pipx", "pip"])
|
||||
@pytest.mark.parametrize("existing", [False, True], ids=["fresh", "existing"])
|
||||
def test_generated_exact_preview_commands_use_persistent_owner(sandbox, owner, existing):
|
||||
_, prefix = _owner_environment(sandbox, owner, existing=existing)
|
||||
manifest, artifact = _preview_manifest(sandbox)
|
||||
command = install_command(manifest, artifact, owner=owner, existing=existing)
|
||||
_run_guide_command(sandbox, command, _python(prefix) if owner == "pip" else BASE_PYTHON)
|
||||
identity = _verify_owner(sandbox, owner, prefix)
|
||||
assert identity["version"] == manifest.version
|
||||
assert Path(identity["prefix"]).resolve() == prefix
|
||||
assert Path(identity["package"]).resolve().is_relative_to(prefix)
|
||||
assert identity["isolated"] == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("owner", ["uv", "pipx", "pip"])
|
||||
def test_generated_command_hash_failure_leaves_existing_version(sandbox, owner):
|
||||
_, prefix = _owner_environment(sandbox, owner, existing=True)
|
||||
manifest, artifact = _preview_manifest(sandbox, damaged_hash=True)
|
||||
command = install_command(manifest, artifact, owner=owner, existing=True)
|
||||
result = _run_guide_command(sandbox, command, _python(prefix) if owner == "pip" else BASE_PYTHON, check=False)
|
||||
assert result.returncode != 0
|
||||
assert "no package manager was started" in result.stderr
|
||||
assert _verify_owner(sandbox, owner, prefix)["version"] == "0.0.1"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("owner", ["uv", "pipx"])
|
||||
def test_exact_preview_does_not_silently_remove_manager_pin(sandbox, owner):
|
||||
executable, prefix = _owner_environment(sandbox, owner, existing=False)
|
||||
if owner == "uv":
|
||||
_run([executable, "tool", "install", "nanobot-ai==0.0.1"], sandbox)
|
||||
else:
|
||||
_run([executable, "install", "--skip-maintenance", "nanobot-ai"], sandbox)
|
||||
_run([executable, "pin", "nanobot-ai"], sandbox)
|
||||
manifest, artifact = _preview_manifest(sandbox)
|
||||
command = install_command(manifest, artifact, owner=owner, existing=True)
|
||||
result = _run_guide_command(sandbox, command, BASE_PYTHON, check=False)
|
||||
# uv rejects the constraint conflict; pipx successfully skips a pinned tool.
|
||||
assert (result.returncode == 0) == (owner == "pipx")
|
||||
assert _verify_owner(sandbox, owner, prefix)["version"] == "0.0.1"
|
||||
|
||||
|
||||
def test_exact_pipx_target_preserves_injected_package_and_records_new_spec(sandbox):
|
||||
pipx, prefix = _owner_environment(sandbox, "pipx", existing=True)
|
||||
_wheel(sandbox["wheels"], "1.0.0", package="fixture-helper")
|
||||
_run([pipx, "inject", "--skip-maintenance", "nanobot-ai", "fixture-helper"], sandbox)
|
||||
receipt = prefix / "pipx_metadata.json"
|
||||
before = json.loads(receipt.read_text(encoding="utf-8"))
|
||||
manifest, artifact = _preview_manifest(sandbox)
|
||||
command = install_command(manifest, artifact, owner="pipx", existing=True)
|
||||
_run_guide_command(sandbox, command, BASE_PYTHON)
|
||||
after = json.loads(receipt.read_text(encoding="utf-8"))
|
||||
assert after["injected_packages"] == before["injected_packages"]
|
||||
assert after["source_interpreter"] == before["source_interpreter"]
|
||||
assert after["main_package"]["package_or_url"] == f"nanobot-ai @ {(sandbox['cwd'] / artifact.filename).as_uri()}"
|
||||
_run([str(_python(prefix)), "-I", "-c", "import fixture_helper"], sandbox)
|
||||
assert _verify_owner(sandbox, "pipx", prefix)["version"] == manifest.version
|
||||
|
||||
|
||||
def _wheel_arguments(sandbox, artifact):
|
||||
return ["-Wheel" if WINDOWS else "--wheel", str(sandbox["cwd"] / artifact.filename),
|
||||
"-Sha256" if WINDOWS else "--sha256", artifact.sha256]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("owner", ["uv", "pipx", "pip", "managed"])
|
||||
@pytest.mark.parametrize("existing", [False, True], ids=["fresh", "existing"])
|
||||
def test_public_installer_accepts_verified_exact_preview(sandbox, owner, existing):
|
||||
if owner == "managed":
|
||||
prefix = sandbox["root"] / "managed"
|
||||
if existing:
|
||||
_wheel(sandbox["wheels"], "0.0.1")
|
||||
_installer(sandbox)
|
||||
else:
|
||||
executable, prefix = _owner_environment(sandbox, owner, existing=existing)
|
||||
if owner == "pip":
|
||||
sandbox["env"]["PYTHON"] = executable
|
||||
elif not existing:
|
||||
prefix = sandbox["root"] / "managed"
|
||||
manifest, artifact = _preview_manifest(sandbox)
|
||||
result = _installer(sandbox, *_wheel_arguments(sandbox, artifact))
|
||||
identity = _identity(result)
|
||||
assert identity["version"] == manifest.version
|
||||
assert Path(identity["prefix"]).resolve() == prefix
|
||||
assert Path(identity["python"]).absolute() == _python(prefix)
|
||||
assert (sandbox["cwd"] / artifact.filename).is_file()
|
||||
|
||||
|
||||
def test_public_installer_rejects_damaged_wheel_before_environment_creation(sandbox):
|
||||
_expose(sandbox, "uv")
|
||||
_, artifact = _preview_manifest(sandbox, damaged_hash=True)
|
||||
result = _installer(sandbox, *_wheel_arguments(sandbox, artifact), check=False)
|
||||
assert result.returncode != 0
|
||||
assert "SHA-256 mismatch" in result.stdout + result.stderr
|
||||
assert not (sandbox["root"] / "uv-tools/nanobot-ai").exists()
|
||||
assert not (sandbox["root"] / "managed").exists()
|
||||
|
||||
|
||||
def test_public_installer_does_not_report_pinned_skip_as_preview_success(sandbox):
|
||||
pipx, prefix = _owner_environment(sandbox, "pipx", existing=True)
|
||||
_run([pipx, "pin", "nanobot-ai"], sandbox)
|
||||
_, artifact = _preview_manifest(sandbox)
|
||||
result = _installer(sandbox, *_wheel_arguments(sandbox, artifact), check=False)
|
||||
assert result.returncode != 0
|
||||
assert "requested version was not installed" in result.stdout + result.stderr
|
||||
assert "INSTALLER_PROBE" not in result.stdout
|
||||
assert _verify_owner(sandbox, "pipx", prefix)["version"] == "0.0.1"
|
||||
|
||||
|
||||
def test_public_installer_wheel_dry_run_validates_but_does_not_install(sandbox):
|
||||
_expose(sandbox, "uv")
|
||||
manifest, artifact = _preview_manifest(sandbox)
|
||||
result = _installer(sandbox, "--dry-run", *_wheel_arguments(sandbox, artifact))
|
||||
assert f"verified wheel {manifest.version}" in result.stdout
|
||||
assert not (sandbox["root"] / "uv-tools/nanobot-ai").exists()
|
||||
|
||||
|
||||
def test_public_installer_pipx_preview_preserves_requested_extras(sandbox):
|
||||
pipx = _expose(sandbox, "pipx")
|
||||
prefix = sandbox["root"] / "pipx/venvs/nanobot-ai"
|
||||
_wheel(sandbox["wheels"], "0.0.1", extras=("feature",))
|
||||
_run([pipx, "install", "--skip-maintenance", "nanobot-ai[feature]"], sandbox)
|
||||
_, artifact = _preview_manifest(sandbox, extras=("feature",))
|
||||
_installer(sandbox, *_wheel_arguments(sandbox, artifact))
|
||||
record = json.loads((prefix / "pipx_metadata.json").read_text(encoding="utf-8"))
|
||||
assert record["main_package"]["package_or_url"].startswith("nanobot-ai[feature] @ ")
|
||||
|
||||
|
||||
def test_public_installer_uv_preview_preserves_requested_extras(sandbox):
|
||||
uv = _expose(sandbox, "uv")
|
||||
prefix = sandbox["root"] / "uv-tools/nanobot-ai"
|
||||
_wheel(sandbox["wheels"], "0.0.1", extras=("feature",))
|
||||
_run([uv, "tool", "install", "--python", BASE_PYTHON, "nanobot-ai[feature]"], sandbox)
|
||||
_, artifact = _preview_manifest(sandbox, extras=("feature",))
|
||||
_installer(sandbox, *_wheel_arguments(sandbox, artifact))
|
||||
record = tomllib.loads((prefix / "uv-receipt.toml").read_text(encoding="utf-8"))
|
||||
assert any(item.get("extras") == ["feature"] for item in record["tool"]["requirements"])
|
||||
|
||||
|
||||
def test_public_installer_refuses_missing_previously_requested_pipx_extra(sandbox):
|
||||
pipx = _expose(sandbox, "pipx")
|
||||
prefix = sandbox["root"] / "pipx/venvs/nanobot-ai"
|
||||
_wheel(sandbox["wheels"], "0.0.1", extras=("feature",))
|
||||
_run([pipx, "install", "--skip-maintenance", "nanobot-ai[feature]"], sandbox)
|
||||
_, artifact = _preview_manifest(sandbox)
|
||||
result = _installer(sandbox, *_wheel_arguments(sandbox, artifact), check=False)
|
||||
assert result.returncode != 0
|
||||
assert "does not provide all existing pipx extras" in result.stdout + result.stderr
|
||||
assert _verify_owner(sandbox, "pipx", prefix)["version"] == "0.0.1"
|
||||
|
||||
|
||||
def test_public_installer_incomplete_wheel_request_never_falls_back_to_pypi(sandbox):
|
||||
_wheel(sandbox["wheels"], "0.0.1")
|
||||
flag = "-Wheel" if WINDOWS else "--wheel"
|
||||
result = _installer(sandbox, flag, "missing.whl", check=False)
|
||||
assert result.returncode != 0
|
||||
assert "supplied together" in result.stdout + result.stderr
|
||||
assert not (sandbox["root"] / "managed").exists()
|
||||
|
||||
|
||||
def test_public_installer_wrong_platform_keeps_original_environment(sandbox):
|
||||
python, prefix = _owner_environment(sandbox, "pip", existing=True)
|
||||
sandbox["env"]["PYTHON"] = python
|
||||
foreign = "macosx_13_0_arm64" if WINDOWS else "win_amd64"
|
||||
wheel = _wheel(sandbox["cwd"], "0.0.2.dev1", platform=foreign)
|
||||
artifact = releases.ReleaseArtifact(filename=wheel.name, size=wheel.stat().st_size,
|
||||
sha256=hashlib.sha256(wheel.read_bytes()).hexdigest())
|
||||
result = _installer(sandbox, *_wheel_arguments(sandbox, artifact), check=False)
|
||||
assert result.returncode != 0
|
||||
assert "retry this exact handoff" in result.stdout + result.stderr
|
||||
assert "uv tool install --force" not in result.stdout + result.stderr
|
||||
assert _verify_owner(sandbox, "pip", prefix)["version"] == "0.0.1"
|
||||
|
||||
|
||||
def _bootstrap_program(script):
|
||||
source = (SCRIPTS / script).read_text(encoding="utf-8")
|
||||
if script.endswith(".sh"):
|
||||
match = re.search(r"wheel_identity=[^\n]*<<'PY'\n(.*?)\nPY\n", source, re.S)
|
||||
assert match is not None
|
||||
return match[1]
|
||||
return source.split("$Verify = @'\n", 1)[1].split("\n'@", 1)[0]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def published_release(tmp_path, monkeypatch):
|
||||
version = "0.0.2.dev1"
|
||||
base = f"{releases.RELEASE_DOWNLOAD}/v{version}/"
|
||||
payloads = {}
|
||||
artifacts = []
|
||||
for name in sorted(releases.release_filenames(version)):
|
||||
if name.endswith(".whl"):
|
||||
tag = name.removeprefix(f"nanobot_ai-{version}-py3-none-").removesuffix(".whl")
|
||||
body = _wheel(tmp_path, version, platform=tag).read_bytes()
|
||||
else:
|
||||
body = b"not downloaded by the installer"
|
||||
payloads[base + name] = body
|
||||
artifacts.append(releases.ReleaseArtifact(filename=name, size=len(body),
|
||||
sha256=hashlib.sha256(body).hexdigest()))
|
||||
manifest = releases.ReleaseManifest(version=version, source_commit="a" * 40,
|
||||
candidate_commit="b" * 40, requires_python=">=3.11",
|
||||
artifacts=artifacts)
|
||||
payloads[base + "release-manifest.json"] = manifest.model_dump_json().encode()
|
||||
requests = []
|
||||
|
||||
class Opener:
|
||||
def open(self, request, *, timeout):
|
||||
assert timeout == 20
|
||||
requests.append(request.full_url)
|
||||
return io.BytesIO(payloads[request.full_url])
|
||||
|
||||
monkeypatch.setattr(urllib.request, "build_opener", lambda *_: Opener())
|
||||
cache = tmp_path / "download cache 数据"
|
||||
|
||||
def run(script, *, dry_run=False, manifest_hash=None):
|
||||
digest = manifest_hash or hashlib.sha256(payloads[base + "release-manifest.json"]).hexdigest()
|
||||
monkeypatch.setattr(sys, "argv", ["verify", "-", "-", "-", version, digest,
|
||||
str(cache), "1" if dry_run else "0"])
|
||||
namespace = {}
|
||||
try:
|
||||
exec(compile(_bootstrap_program(script), script, "exec"), namespace)
|
||||
except SystemExit as exc:
|
||||
if exc.code != 0:
|
||||
raise
|
||||
return namespace
|
||||
|
||||
return run, manifest, payloads, requests, cache
|
||||
|
||||
|
||||
@pytest.mark.parametrize("script", ["install.sh", "install.ps1"])
|
||||
@pytest.mark.parametrize("system,machine,expected", [
|
||||
("darwin", "arm64", "macosx_13_0_arm64"),
|
||||
("darwin", "x86_64", "macosx_13_0_x86_64"),
|
||||
("linux", "aarch64", "manylinux_2_17_aarch64"),
|
||||
("linux", "x86_64", "manylinux_2_17_x86_64"),
|
||||
("win32", "AMD64", "win_amd64"),
|
||||
])
|
||||
def test_bootstrap_downloads_only_target_wheel(published_release, monkeypatch, capsys, script, system, machine, expected):
|
||||
run, manifest, payloads, requests, cache = published_release
|
||||
monkeypatch.setattr(sys, "platform", system)
|
||||
monkeypatch.setattr(platform, "machine", lambda: machine)
|
||||
monkeypatch.setattr(platform, "mac_ver", lambda: ("15.0", ("", "", ""), machine))
|
||||
monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.17", raising=False)
|
||||
monkeypatch.setattr(sysconfig, "get_platform", lambda: "win-amd64")
|
||||
run(script)
|
||||
filename = f"nanobot_ai-{manifest.version}-py3-none-{expected}.whl"
|
||||
assert len(requests) == 2 and requests[-1].endswith("/" + filename)
|
||||
files = list(cache.rglob("*.whl"))
|
||||
assert len(files) == 1 and files[0].name == filename
|
||||
assert files[0].read_bytes() == payloads[requests[-1]]
|
||||
assert capsys.readouterr().out.strip() == f"nanobot-ai @ {files[0].as_uri()}|{manifest.version}"
|
||||
run(script)
|
||||
assert len(requests) == 3 and requests[-1].endswith("release-manifest.json")
|
||||
assert not list(cache.rglob("*.part"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("script", ["install.sh", "install.ps1"])
|
||||
def test_bootstrap_dry_run_has_no_wheel_or_cache_writes(published_release, capsys, script):
|
||||
run, manifest, _, requests, cache = published_release
|
||||
namespace = run(script, dry_run=True)
|
||||
assert len(requests) == 1 and not cache.exists()
|
||||
assert f"|{manifest.version}" in capsys.readouterr().out
|
||||
assert namespace["native_platform"]() in {tag.platform for tag in sys_tags()}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("script", ["install.sh", "install.ps1"])
|
||||
def test_bootstrap_bad_manifest_hash_never_downloads_wheel(published_release, script):
|
||||
run, _, _, requests, cache = published_release
|
||||
with pytest.raises(SystemExit, match="manifest size or SHA-256"):
|
||||
run(script, manifest_hash="0" * 64)
|
||||
assert len(requests) == 1 and not cache.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("script", ["install.sh", "install.ps1"])
|
||||
def test_bootstrap_damaged_download_is_not_retained(published_release, script):
|
||||
run, manifest, payloads, requests, cache = published_release
|
||||
for artifact in manifest.artifacts:
|
||||
if artifact.filename.endswith(".whl"):
|
||||
payloads[manifest.artifact_url(artifact).split("#")[0]] = b"truncated"
|
||||
with pytest.raises(SystemExit, match="wheel size or SHA-256"):
|
||||
run(script)
|
||||
assert len(requests) == 2
|
||||
assert not list(cache.rglob("*.whl")) and not list(cache.rglob("*.part"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("libc", ["", "glibc 2.16"])
|
||||
def test_bootstrap_does_not_download_a_glibc_wheel_for_incompatible_linux(published_release, monkeypatch, libc):
|
||||
run, _, _, requests, cache = published_release
|
||||
monkeypatch.setattr(sys, "platform", "linux")
|
||||
monkeypatch.setattr(os, "confstr", lambda _: libc, raising=False)
|
||||
with pytest.raises(SystemExit, match="glibc 2.17"):
|
||||
run("install.sh")
|
||||
assert not requests and not cache.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", ["http://github.com/file", "https://example.com/file", "https://github.com:8443/file",
|
||||
"https://user:password@github.com/file", "https://127.0.0.1/file"])
|
||||
def test_bootstrap_rejects_download_redirects_outside_project_hosts(published_release, url):
|
||||
run, _, _, _, _ = published_release
|
||||
namespace = run("install.sh", dry_run=True)
|
||||
handler = namespace["ReleaseRedirect"]()
|
||||
with pytest.raises(SystemExit, match="approved HTTPS hosts"):
|
||||
handler.redirect_request(urllib.request.Request("https://github.com/file"), None, 302, "Found", {}, url)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def release_https(published_release, tmp_path):
|
||||
"""Real HTTPS via a private CONNECT proxy; never contacts GitHub or other hosts."""
|
||||
openssl = shutil.which("openssl")
|
||||
if not openssl:
|
||||
pytest.skip("OpenSSL is required for the isolated HTTPS installer check")
|
||||
cert, key = tmp_path / "test-ca.pem", tmp_path / "test-ca-key.pem"
|
||||
subprocess.run([openssl, "req", "-x509", "-newkey", "rsa:2048", "-nodes",
|
||||
"-keyout", str(key), "-out", str(cert), "-days", "1", "-subj", "/CN=github.com",
|
||||
"-addext", "subjectAltName=DNS:github.com,DNS:raw.githubusercontent.com"], check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain(cert, key)
|
||||
_, manifest, payloads, _, _ = published_release
|
||||
requests = []
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_CONNECT(self): # noqa: N802 -- stdlib protocol method
|
||||
if self.path not in {"github.com:443", "raw.githubusercontent.com:443"}:
|
||||
self.send_error(403)
|
||||
return
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
self.connection.settimeout(10)
|
||||
self.connection = context.wrap_socket(self.connection, server_side=True)
|
||||
self.rfile = self.connection.makefile("rb")
|
||||
self.wfile = self.connection.makefile("wb")
|
||||
self.handle_one_request()
|
||||
self.close_connection = True
|
||||
|
||||
def do_GET(self): # noqa: N802 -- stdlib protocol method
|
||||
url = "https://" + self.headers["Host"] + self.path
|
||||
requests.append(url)
|
||||
if url not in payloads:
|
||||
self.send_error(404)
|
||||
return
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Length", str(len(payloads[url])))
|
||||
self.end_headers()
|
||||
self.wfile.write(payloads[url])
|
||||
self.wfile.flush()
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
digest = hashlib.sha256(payloads[f"{releases.RELEASE_DOWNLOAD}/v{manifest.version}/release-manifest.json"]).hexdigest()
|
||||
yield manifest, digest, payloads, requests, {
|
||||
"HTTPS_PROXY": f"http://127.0.0.1:{server.server_address[1]}",
|
||||
"SSL_CERT_FILE": str(cert), "NO_PROXY": "",
|
||||
"CURL_CA_BUNDLE": str(cert),
|
||||
}
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join(timeout=10)
|
||||
server.server_close()
|
||||
|
||||
|
||||
def _release_arguments(version, digest):
|
||||
return ["-Release" if WINDOWS else "--release", version,
|
||||
"-ManifestSha256" if WINDOWS else "--manifest-sha256", digest]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("owner", ["uv", "pipx", "managed"])
|
||||
@pytest.mark.parametrize("existing", [False, True], ids=["fresh", "existing"])
|
||||
def test_public_installer_download_to_owner_upgrade_over_https(sandbox, release_https, owner, existing):
|
||||
manifest, digest, _, requests, network = release_https
|
||||
if owner == "managed":
|
||||
prefix = sandbox["root"] / "managed"
|
||||
if existing:
|
||||
_wheel(sandbox["wheels"], "0.0.1")
|
||||
_installer(sandbox)
|
||||
else:
|
||||
_, prefix = _owner_environment(sandbox, owner, existing=existing)
|
||||
if not existing:
|
||||
prefix = sandbox["root"] / "managed"
|
||||
sandbox["env"].update(network)
|
||||
result = _installer(sandbox, *_release_arguments(manifest.version, digest))
|
||||
identity = _identity(result)
|
||||
assert identity["version"] == manifest.version
|
||||
assert Path(identity["prefix"]).resolve() == prefix
|
||||
assert len(requests) == 2
|
||||
cached = list((sandbox["root"] / ".nanobot/downloads/releases").rglob("*.whl"))
|
||||
assert len(cached) == 1 and requests[-1].endswith(cached[0].name)
|
||||
|
||||
|
||||
def test_public_installer_release_dry_run_over_https_is_read_only(sandbox, release_https):
|
||||
manifest, digest, _, requests, network = release_https
|
||||
sandbox["env"].update(network)
|
||||
result = _installer(sandbox, "--dry-run", *_release_arguments(manifest.version, digest))
|
||||
assert "its wheel was not downloaded" in result.stdout
|
||||
assert len(requests) == 1
|
||||
assert not (sandbox["root"] / "managed").exists()
|
||||
assert not (sandbox["root"] / ".nanobot/downloads/releases").exists()
|
||||
|
||||
|
||||
def test_public_installer_damaged_https_download_never_updates_existing_package(sandbox, release_https):
|
||||
manifest, digest, payloads, requests, network = release_https
|
||||
_, prefix = _owner_environment(sandbox, "uv", existing=True)
|
||||
for artifact in manifest.artifacts:
|
||||
if artifact.filename.endswith(".whl"):
|
||||
payloads[manifest.artifact_url(artifact).split("#")[0]] = b"damaged download"
|
||||
sandbox["env"].update(network)
|
||||
result = _installer(sandbox, *_release_arguments(manifest.version, digest), check=False)
|
||||
assert result.returncode != 0 and "wheel size or SHA-256 mismatch" in result.stdout + result.stderr
|
||||
assert len(requests) == 2
|
||||
assert _verify_owner(sandbox, "uv", prefix)["version"] == "0.0.1"
|
||||
cache = sandbox["root"] / ".nanobot/downloads/releases"
|
||||
assert not list(cache.rglob("*.whl")) and not list(cache.rglob("*.part"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("owner", ["uv", "pipx"])
|
||||
def test_release_bootstrap_preserves_explicit_manager_pin(sandbox, release_https, owner):
|
||||
executable, prefix = _owner_environment(sandbox, owner, existing=False)
|
||||
if owner == "uv":
|
||||
_run([executable, "tool", "install", "nanobot-ai==0.0.1"], sandbox)
|
||||
receipt = prefix / "uv-receipt.toml"
|
||||
else:
|
||||
_run([executable, "install", "--skip-maintenance", "nanobot-ai"], sandbox)
|
||||
_run([executable, "pin", "nanobot-ai"], sandbox)
|
||||
receipt = prefix / "pipx_metadata.json"
|
||||
before = receipt.read_bytes()
|
||||
manifest, digest, _, requests, network = release_https
|
||||
sandbox["env"].update(network)
|
||||
result = _installer(sandbox, *_release_arguments(manifest.version, digest), check=False)
|
||||
assert result.returncode != 0
|
||||
assert "INSTALLER_PROBE" not in result.stdout
|
||||
assert len(requests) == 2 # Pin enforcement follows successful selection/download.
|
||||
assert receipt.read_bytes() == before
|
||||
assert _verify_owner(sandbox, owner, prefix)["version"] == "0.0.1"
|
||||
assert not (sandbox["root"] / "managed").exists()
|
||||
|
||||
|
||||
@pytest.mark.skipif(WINDOWS, reason="Unix bootstrap command; Windows installer is tested separately")
|
||||
def test_generated_bootstrap_command_downloads_and_upgrades_original_owner(sandbox, release_https):
|
||||
manifest, digest, payloads, requests, network = release_https
|
||||
_expose(sandbox, "curl")
|
||||
_, prefix = _owner_environment(sandbox, "uv", existing=True)
|
||||
installer_url = f"https://raw.githubusercontent.com/HKUDS/nanobot/{manifest.candidate_commit}/scripts/install.sh"
|
||||
payloads[installer_url] = (SCRIPTS / "install.sh").read_bytes()
|
||||
sandbox["env"].update(network)
|
||||
unix, _ = bootstrap_commands(manifest, digest)
|
||||
identity = _identity(_run(["/bin/sh", "-c", unix], sandbox))
|
||||
assert identity["version"] == manifest.version
|
||||
assert Path(identity["prefix"]).resolve() == prefix
|
||||
assert requests[0] == installer_url and len(requests) == 3
|
||||
assert not list(sandbox["root"].glob("*/install.sh"))
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Real process leases, not PID files or mocked lock acquisition."""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.installation_lock import (
|
||||
InstallationBusyError,
|
||||
installation_access,
|
||||
installation_state_dir,
|
||||
)
|
||||
|
||||
_CHILD = """
|
||||
import os, sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, sys.argv[4])
|
||||
from nanobot.installation_lock import installation_access
|
||||
Path.home = classmethod(lambda cls: Path(sys.argv[1]))
|
||||
sys.prefix = sys.argv[2]
|
||||
with installation_access(updating=sys.argv[3] == 'update'):
|
||||
print(os.getpid(), flush=True)
|
||||
sys.stdin.read(1)
|
||||
"""
|
||||
|
||||
|
||||
@contextmanager
|
||||
def child_lease(home: Path, prefix: str, *, updating: bool = False):
|
||||
# Windows venv python.exe is a redirector: killing/waiting for that launcher
|
||||
# does not prove the actual lease holder exited. This stdlib-only probe runs
|
||||
# the base interpreter directly and verifies that it is the process we own.
|
||||
process = subprocess.Popen(
|
||||
[sys._base_executable, "-I", "-S", "-c", _CHILD, str(home), prefix,
|
||||
"update" if updating else "runtime", str(Path(__file__).resolve().parents[1])],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
|
||||
)
|
||||
try:
|
||||
assert process.stdout.readline().strip() == str(process.pid), process.stderr.read()
|
||||
yield process
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.stdin.write("x")
|
||||
process.stdin.flush()
|
||||
process.communicate(timeout=10)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def isolated_installation(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
|
||||
monkeypatch.setattr(sys, "prefix", str(tmp_path / "installation with spaces"))
|
||||
return tmp_path
|
||||
|
||||
|
||||
def assert_update_lease_released():
|
||||
# LockFileEx documents deferred kernel cleanup after process death/close.
|
||||
# Poll the real lock only after the actual owner has exited; never mistake
|
||||
# a launcher exiting for an owner exiting or weaken the live-owner checks.
|
||||
deadline = time.monotonic() + (5 if sys.platform == "win32" else 0)
|
||||
while True:
|
||||
try:
|
||||
with installation_access(updating=True):
|
||||
return
|
||||
except InstallationBusyError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.01)
|
||||
|
||||
|
||||
def test_multiple_runtimes_block_update_until_last_process_exits(isolated_installation):
|
||||
with child_lease(isolated_installation, sys.prefix) as first:
|
||||
with child_lease(isolated_installation, sys.prefix):
|
||||
with installation_access():
|
||||
pass # Shared leases do not prevent normal multi-profile use.
|
||||
with pytest.raises(InstallationBusyError, match="Stop its nanobot gateways"):
|
||||
with installation_access(updating=True):
|
||||
pytest.fail("Update entered a busy installation")
|
||||
first.kill()
|
||||
first.wait(timeout=10)
|
||||
with pytest.raises(InstallationBusyError):
|
||||
with installation_access(updating=True):
|
||||
pytest.fail("Another live runtime was ignored")
|
||||
assert_update_lease_released()
|
||||
|
||||
|
||||
def test_update_blocks_startup_and_concurrent_update_and_crash_releases_lease(isolated_installation):
|
||||
with child_lease(isolated_installation, sys.prefix, updating=True) as worker:
|
||||
with pytest.raises(InstallationBusyError, match="being updated"):
|
||||
with installation_access():
|
||||
pytest.fail("Runtime entered an updating installation")
|
||||
with pytest.raises(InstallationBusyError):
|
||||
with installation_access(updating=True):
|
||||
pytest.fail("Concurrent updater entered")
|
||||
worker.kill()
|
||||
worker.wait(timeout=10)
|
||||
assert_update_lease_released()
|
||||
|
||||
|
||||
def test_other_installation_does_not_block_runtime(isolated_installation):
|
||||
with child_lease(isolated_installation, sys.prefix + "-other", updating=True):
|
||||
with installation_access():
|
||||
pass
|
||||
|
||||
|
||||
def test_interrupted_installation_refuses_startup_but_allows_repair(isolated_installation):
|
||||
pending = isolated_installation / ".nanobot/run" / f"update-{installation_state_dir().name[:16]}.pending"
|
||||
pending.parent.mkdir(parents=True)
|
||||
pending.write_text("An older updater was interrupted")
|
||||
with pytest.raises(InstallationBusyError, match="previous update did not finish"):
|
||||
with installation_access():
|
||||
pytest.fail("Runtime used partially replaced files")
|
||||
with installation_access(updating=True):
|
||||
pass
|
||||
with installation_access(allow_incomplete=True):
|
||||
pass
|
||||
with child_lease(isolated_installation, sys.prefix, updating=True):
|
||||
with pytest.raises(InstallationBusyError, match="being updated"):
|
||||
with installation_access(allow_incomplete=True):
|
||||
pytest.fail("A diagnostic command raced the active installer")
|
||||
|
||||
|
||||
def test_aliases_share_installation_lock(isolated_installation, tmp_path):
|
||||
environment = Path(sys.prefix)
|
||||
environment.mkdir()
|
||||
alias = tmp_path / "alias"
|
||||
try:
|
||||
alias.symlink_to(environment, target_is_directory=True)
|
||||
except OSError:
|
||||
pytest.skip("Directory symlinks are not enabled for this account")
|
||||
with child_lease(isolated_installation, str(alias), updating=True):
|
||||
with pytest.raises(InstallationBusyError):
|
||||
with installation_access():
|
||||
pytest.fail("Alias bypassed installation lease")
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Protect the real release probe from accepting an incomplete built frontend."""
|
||||
|
||||
import json
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from scripts.verify_installed_release import (
|
||||
_wait_for_closed_listeners,
|
||||
gateway_probe,
|
||||
host_environment,
|
||||
webui_assets,
|
||||
)
|
||||
|
||||
|
||||
def test_probe_waits_for_listener_teardown_after_redirector_exit(monkeypatch):
|
||||
with socket.socket() as listener:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen()
|
||||
port = listener.getsockname()[1]
|
||||
# A still-live listener cannot count as cleaned up.
|
||||
with pytest.raises(ValueError, match="listener remained reachable"):
|
||||
_wait_for_closed_listeners((port,), timeout=0)
|
||||
# Model the kernel completing teardown after the first observation.
|
||||
monkeypatch.setattr("scripts.verify_installed_release.time.sleep", lambda _: listener.close())
|
||||
_wait_for_closed_listeners((port,))
|
||||
|
||||
|
||||
def test_isolation_retains_windows_cpu_identity_without_developer_paths():
|
||||
environment = {"SYSTEMROOT": r"C:\Windows", "PROCESSOR_ARCHITECTURE": "AMD64",
|
||||
"PROCESSOR_ARCHITEW6432": "AMD64", "PATH": r"C:\dev\bun",
|
||||
"PYTHONPATH": r"C:\checkout", "NANOBOT_TUI_BIN": r"C:\old\tui.exe"}
|
||||
expected = {key: environment[key] for key in (
|
||||
"SYSTEMROOT", "PROCESSOR_ARCHITECTURE", "PROCESSOR_ARCHITEW6432",
|
||||
)}
|
||||
assert host_environment(environment) == expected
|
||||
# The installer and installed-package probe apply this boundary separately.
|
||||
assert host_environment(host_environment(environment)) == expected
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def frontend(tmp_path):
|
||||
assets = tmp_path / "assets"
|
||||
assets.mkdir()
|
||||
for name in ("entry.js", "lazy.js", "style.css"):
|
||||
(assets / name).write_text("compiled content", encoding="utf-8")
|
||||
manifest = {
|
||||
"index.html": {"file": "assets/entry.js", "css": ["assets/style.css"],
|
||||
"dynamicImports": ["settings"]},
|
||||
"settings": {"file": "assets/lazy.js", "imports": ["index.html"]},
|
||||
}
|
||||
(tmp_path / "index.html").write_text('<script src="/assets/entry.js"></script>')
|
||||
(tmp_path / "asset-manifest.json").write_text(json.dumps(manifest))
|
||||
return tmp_path
|
||||
|
||||
|
||||
def test_manifest_covers_lazy_assets_not_only_initial_html(frontend):
|
||||
assert webui_assets(frontend) == {"assets/entry.js", "assets/lazy.js", "assets/style.css"}
|
||||
(frontend / "assets/lazy.js").unlink()
|
||||
with pytest.raises(ValueError, match="Missing or empty.*lazy.js"):
|
||||
webui_assets(frontend)
|
||||
|
||||
|
||||
def test_missing_import_record_fails_even_if_entrypoint_exists(frontend):
|
||||
path = frontend / "asset-manifest.json"
|
||||
manifest = json.loads(path.read_text())
|
||||
del manifest["settings"]
|
||||
path.write_text(json.dumps(manifest))
|
||||
with pytest.raises(ValueError, match="Missing WebUI manifest dependency"):
|
||||
webui_assets(frontend)
|
||||
|
||||
|
||||
def test_stale_html_cannot_pass_against_an_unrelated_manifest(frontend):
|
||||
(frontend / "index.html").write_text('<script src="/assets/old.js"></script>')
|
||||
with pytest.raises(ValueError, match="HTML entrypoints"):
|
||||
webui_assets(frontend)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("options", [[], ["--gateway"]])
|
||||
def test_probe_requires_isolated_python_before_importing_source(tmp_path, options):
|
||||
script = Path(__file__).resolve().parents[1] / "scripts/verify_installed_release.py"
|
||||
report = tmp_path / "report.json"
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(script), "--version", "0.3.6.dev1", "--commit", "a" * 40,
|
||||
"--report", str(report), *options], capture_output=True, text=True, timeout=10,
|
||||
)
|
||||
assert result.returncode == 2
|
||||
assert "python -I" in result.stderr
|
||||
assert not report.exists()
|
||||
|
||||
|
||||
def test_gateway_probe_reports_failed_cli_start_and_reaps_its_child(tmp_path, monkeypatch, capsys):
|
||||
popen = subprocess.Popen
|
||||
children = []
|
||||
|
||||
def failed_cli(command, **kwargs):
|
||||
# A missing runtime dependency makes the installed CLI exit before binding.
|
||||
child = popen([command[0], "-I", "-c",
|
||||
"print('candidate startup failed'); raise SystemExit(7)"], **kwargs)
|
||||
children.append(child)
|
||||
return child
|
||||
|
||||
monkeypatch.setattr(subprocess, "Popen", failed_cli)
|
||||
with pytest.raises(ValueError, match="exited before readiness: 7"):
|
||||
gateway_probe("0.3.6.dev1", tmp_path / "gateway")
|
||||
assert len(children) == 1 and children[0].poll() == 7
|
||||
assert "candidate startup failed" in capsys.readouterr().err
|
||||
@@ -0,0 +1,108 @@
|
||||
"""A replacement installer program retains its own installation and store leases."""
|
||||
|
||||
import os
|
||||
import selectors
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.data_access import data_access
|
||||
from nanobot.installation_lock import InstallationBusyError, installation_access
|
||||
|
||||
pytestmark = pytest.mark.skipif(os.name != "posix", reason="POSIX exec handoff only")
|
||||
|
||||
_PROGRAM = "import os,sys; print(os.getpid(), flush=True); sys.stdin.read(1)"
|
||||
_EXEC = """
|
||||
import os,sys
|
||||
from pathlib import Path
|
||||
from nanobot.data_access import data_access
|
||||
from nanobot.installation_lock import installation_access
|
||||
Path.home = classmethod(lambda cls: Path(sys.argv[1]))
|
||||
with installation_access(updating=True, environment=sys.argv[2]) as installation:
|
||||
with data_access([sys.argv[3]], updating=True) as data:
|
||||
with installation.inherit_for_exec(), data.inherit_for_exec():
|
||||
os.execve(sys.executable, [sys.executable, '-I', '-c', sys.argv[4]], os.environ)
|
||||
"""
|
||||
|
||||
|
||||
def ready(process):
|
||||
with selectors.DefaultSelector() as selector:
|
||||
selector.register(process.stdout, selectors.EVENT_READ)
|
||||
assert selector.select(timeout=10), "Installer did not become ready"
|
||||
assert process.stdout.readline().strip() == str(process.pid)
|
||||
|
||||
|
||||
def finish(process):
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.communicate(timeout=10)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("crash", [False, True])
|
||||
def test_exec_retains_both_leases_until_installer_exits(tmp_path, monkeypatch, crash):
|
||||
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
|
||||
environment, store = tmp_path / "installation", tmp_path / "sessions"
|
||||
process = subprocess.Popen(
|
||||
[sys.executable, "-c", _EXEC, str(tmp_path), str(environment), str(store), _PROGRAM],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
|
||||
)
|
||||
try:
|
||||
ready(process) # Same PID; the program no longer imports nanobot or owns Python lease objects.
|
||||
for updating in (False, True):
|
||||
with pytest.raises(InstallationBusyError):
|
||||
with installation_access(updating=updating, environment=environment):
|
||||
pytest.fail("Exec lost the installation lease")
|
||||
with pytest.raises(InstallationBusyError, match="data is in use"):
|
||||
with data_access([store / "conversation.jsonl"]):
|
||||
pytest.fail("Exec lost the overlapping store lease")
|
||||
with data_access([tmp_path / "other sessions"]):
|
||||
pass # A disjoint runtime remains usable.
|
||||
if crash:
|
||||
process.kill()
|
||||
else:
|
||||
process.stdin.write("x")
|
||||
process.stdin.flush()
|
||||
process.wait(timeout=10)
|
||||
finally:
|
||||
finish(process)
|
||||
with installation_access(updating=True, environment=environment), data_access([store], updating=True):
|
||||
pass # Actual installer exit, including a crash, releases all OS leases.
|
||||
|
||||
|
||||
@pytest.mark.parametrize("high_stdout_fd", [False, True])
|
||||
def test_failed_exec_does_not_leak_leases_to_later_children(tmp_path, monkeypatch, high_stdout_fd):
|
||||
if high_stdout_fd:
|
||||
import fcntl
|
||||
import resource
|
||||
|
||||
if resource.getrlimit(resource.RLIMIT_NOFILE)[0] <= 1024:
|
||||
pytest.skip("Process limit cannot reproduce a stdout FD outside select()'s range")
|
||||
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
|
||||
environment, store = tmp_path / "installation", tmp_path / "sessions"
|
||||
process = None
|
||||
try:
|
||||
with (installation_access(updating=True, environment=environment) as installation,
|
||||
data_access([store], updating=True) as data):
|
||||
with pytest.raises(FileNotFoundError):
|
||||
with installation.inherit_for_exec(), data.inherit_for_exec():
|
||||
os.execve(str(tmp_path / "missing-installer"), ["missing-installer"], os.environ)
|
||||
# Deliberately allow inheritable FDs here. Restoration, not Popen's
|
||||
# normal close_fds=True, must prevent this unrelated child retaining them.
|
||||
process = subprocess.Popen(
|
||||
[sys.executable, "-I", "-c", _PROGRAM], close_fds=False,
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
|
||||
)
|
||||
if high_stdout_fd:
|
||||
# Full-suite CI can allocate pipes above select()'s FD_SETSIZE.
|
||||
descriptor = fcntl.fcntl(process.stdout.fileno(), fcntl.F_DUPFD_CLOEXEC, 1024)
|
||||
process.stdout.close()
|
||||
process.stdout = os.fdopen(descriptor)
|
||||
ready(process)
|
||||
assert process.poll() is None
|
||||
with installation_access(updating=True, environment=environment), data_access([store], updating=True):
|
||||
pass
|
||||
finally:
|
||||
if process is not None:
|
||||
finish(process)
|
||||
@@ -588,7 +588,8 @@ async def test_process_direct_accepts_media() -> None:
|
||||
|
||||
loop = AgentLoop.__new__(AgentLoop)
|
||||
loop._session_locks = {}
|
||||
loop.runtime_event_publisher = RuntimeEventPublisher(MessageBus())
|
||||
loop.bus = MessageBus()
|
||||
loop.runtime_event_publisher = RuntimeEventPublisher(loop.bus)
|
||||
|
||||
captured_msg = None
|
||||
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
"""Keep acceptance evidence honest: real target bytes and fail-closed fixtures."""
|
||||
|
||||
import asyncio
|
||||
import csv
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from zipfile import ZipFile, ZipInfo
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from nanobot.release_feed import ReleaseFeed
|
||||
from scripts.verify_packaged_update import (
|
||||
assert_canonical_preserved,
|
||||
assert_history_preserved,
|
||||
canonical_records,
|
||||
digest,
|
||||
feed_records,
|
||||
fixture_wheel,
|
||||
replace_once,
|
||||
)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
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
|
||||
|
||||
store = SqliteSessionStore(tmp_path)
|
||||
store.initialize(tmp_path)
|
||||
session = Session(key="websocket:canonical-only")
|
||||
session.add_message("user", "Keep this original context")
|
||||
store.save(session)
|
||||
before = canonical_records(store.path)
|
||||
store.migrate_history("acceptance-import", lambda _: [HistoryImport(
|
||||
key="websocket:display-only", facts=[HistoryFact(HistoryKind.ANSWER, {"text": "Display only"})],
|
||||
)])
|
||||
after = canonical_records(store.path)
|
||||
assert_canonical_preserved(before, after)
|
||||
assert_canonical_preserved(after, after)
|
||||
# The real /api/sessions read allocates the newly imported owner's handle.
|
||||
store.update_metadata("websocket:display-only", {"session_handle": "jeno"})
|
||||
after = canonical_records(store.path)
|
||||
assert_canonical_preserved(before, after)
|
||||
with pytest.raises(AssertionError):
|
||||
assert_canonical_preserved(before, {**after, "messages": []})
|
||||
with pytest.raises(AssertionError):
|
||||
assert_canonical_preserved(before, {**after, "sessions": after["sessions"][1:]})
|
||||
store.update_metadata("websocket:display-only", {"unexpected": "context"})
|
||||
with pytest.raises(AssertionError):
|
||||
assert_canonical_preserved(before, canonical_records(store.path))
|
||||
|
||||
|
||||
def wheel(tmp_path, version, *, worker=b"# worker\n", fallback=b"# fallback\n"):
|
||||
path = tmp_path / f"nanobot_ai-{version}-py3-none-manylinux_2_17_x86_64.whl"
|
||||
with ZipFile(path, "w") as archive:
|
||||
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/release_feed.py", "transport=transport or PinnedDNSAsyncTransport(),\n")
|
||||
archive.writestr("nanobot/update_worker.py", worker)
|
||||
archive.writestr("nanobot/update_fallback.py", fallback)
|
||||
binary = ZipInfo("nanobot/tui/bin/nanobot-tui")
|
||||
binary.external_attr = 0o100755 << 16
|
||||
archive.writestr(binary, b"native executable fixture")
|
||||
return path
|
||||
|
||||
|
||||
def test_baseline_instrumentation_does_not_modify_the_target(tmp_path):
|
||||
source = wheel(tmp_path, "0.3.6")
|
||||
before = digest(source)
|
||||
baseline = fixture_wheel(source, tmp_path / "baseline", "0.3.5", feed=tmp_path / "feed.json")
|
||||
assert digest(source) == before
|
||||
with ZipFile(source) as original, ZipFile(baseline) as copied:
|
||||
assert copied.read("nanobot/__init__.py") == original.read("nanobot/__init__.py")
|
||||
assert "nanobot/_acceptance_feed.py" not in original.namelist()
|
||||
assert copied.getinfo("nanobot/tui/bin/nanobot-tui").external_attr == original.getinfo("nanobot/tui/bin/nanobot-tui").external_attr
|
||||
records = csv.reader(io.StringIO(copied.read("nanobot_ai-0.3.5.dist-info/RECORD").decode()))
|
||||
for name, checksum, size in records:
|
||||
if checksum:
|
||||
assert int(size) == len(copied.read(name))
|
||||
assert checksum.startswith("sha256=")
|
||||
with pytest.raises(FileExistsError):
|
||||
fixture_wheel(source, tmp_path / "baseline", "0.3.5", feed=tmp_path / "feed.json")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version,channel", [("0.3.6", "stable"), ("0.3.6.dev42", "preview")])
|
||||
def test_local_feed_uses_the_real_resolver_and_exact_target_hash(tmp_path, monkeypatch, version, channel):
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
# The packaged lifecycle fixture is deliberately not a public signed release.
|
||||
monkeypatch.setattr(ReleaseFeed, "_authorize", AsyncMock())
|
||||
from packaging.tags import Tag
|
||||
|
||||
candidate = wheel(tmp_path, version)
|
||||
records = feed_records(candidate, "a" * 40)
|
||||
|
||||
def respond(request):
|
||||
item = records[str(request.url)]
|
||||
return httpx.Response(200, content=candidate.read_bytes() if "file" in item else json.dumps(item["json"]).encode())
|
||||
|
||||
async def check():
|
||||
async with ReleaseFeed(tmp_path / "feed", transport=httpx.MockTransport(respond),
|
||||
supported_tags=[Tag("py3", "none", "manylinux_2_17_x86_64")]) as feed:
|
||||
target = await feed.latest(channel)
|
||||
assert target.version == version
|
||||
assert target.artifact.sha256 == hashlib.sha256(candidate.read_bytes()).hexdigest()
|
||||
await feed.revalidate(target)
|
||||
asyncio.run(check())
|
||||
|
||||
|
||||
def test_changed_fault_seam_is_not_silently_reported_as_fault_coverage():
|
||||
with pytest.raises(ValueError, match="seam changed"):
|
||||
replace_once(b"new worker", b"old worker", b"fault")
|
||||
with pytest.raises(ValueError, match="seam changed"):
|
||||
replace_once(b"old old", b"old", b"fault")
|
||||
|
||||
|
||||
def test_consecutive_feed_advances_generation_without_rewriting_a_release(tmp_path):
|
||||
from nanobot.release_feed import CATALOGUE_URL
|
||||
from nanobot.releases import ReleaseCatalogue
|
||||
|
||||
intermediate = wheel(tmp_path, "0.3.6.dev0")
|
||||
target = wheel(tmp_path, "0.3.6.dev2")
|
||||
previous = ReleaseCatalogue.model_validate(feed_records(intermediate, "a" * 40)[CATALOGUE_URL]["json"])
|
||||
current = ReleaseCatalogue.model_validate(feed_records(target, "b" * 40, generation=2)[CATALOGUE_URL]["json"])
|
||||
current.validate_successor(previous)
|
||||
with pytest.raises(ValueError, match="newer generation"):
|
||||
current.model_copy(update={"generation": 1}).validate_successor(previous)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("scenario,marker", [
|
||||
("worker-exit", b"os._exit(91)"),
|
||||
("metadata-loss", b"os._exit(92)"),
|
||||
("backup-failure", b"Injected backup write failure"),
|
||||
("restore-interruption", b"Injected rename interruption"),
|
||||
])
|
||||
def test_windows_packaged_sources_keep_fault_injection_reachable(tmp_path, scenario, marker):
|
||||
package = Path(__file__).resolve().parents[1] / "nanobot"
|
||||
def windows_source(name):
|
||||
return (package / name).read_bytes().replace(b"\r\n", b"\n").replace(b"\n", b"\r\n")
|
||||
source = wheel(tmp_path, "0.3.6", worker=windows_source("update_worker.py"),
|
||||
fallback=windows_source("update_fallback.py"))
|
||||
before = digest(source)
|
||||
baseline = fixture_wheel(source, tmp_path / "baseline", "0.3.5", feed=tmp_path / "feed.json", scenario=scenario)
|
||||
with ZipFile(baseline) as archive:
|
||||
name = "update_fallback.py" if scenario == "restore-interruption" else "update_worker.py"
|
||||
content = archive.read("nanobot/" + name)
|
||||
assert content.count(marker) == 1
|
||||
if scenario != "restore-interruption":
|
||||
assert repr(str(tmp_path / "injected-fault")).encode() in content
|
||||
compile(content, name, "exec")
|
||||
assert digest(source) == before
|
||||
|
||||
|
||||
def test_unisolated_probe_refuses_before_creating_output(tmp_path):
|
||||
script = Path(__file__).resolve().parents[1] / "scripts/verify_packaged_update.py"
|
||||
output = tmp_path / "must-not-exist"
|
||||
result = subprocess.run([sys.executable, str(script), "--output", str(output)],
|
||||
capture_output=True, text=True, timeout=10)
|
||||
assert result.returncode == 2 and "python -I" in result.stderr
|
||||
assert not output.exists()
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Candidate preparation uses real isolated Git repositories, never a live install."""
|
||||
|
||||
import subprocess
|
||||
import tomllib
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from scripts.release_candidate import (
|
||||
_candidate_identity,
|
||||
_source_payload,
|
||||
prepare_preview,
|
||||
preview_version,
|
||||
)
|
||||
|
||||
|
||||
def git(root, *args):
|
||||
return subprocess.run(["git", *args], cwd=root, check=True, capture_output=True,
|
||||
text=True).stdout.strip()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def source(tmp_path):
|
||||
root = tmp_path / "source"
|
||||
root.mkdir()
|
||||
(root / "nanobot").mkdir()
|
||||
(root / "pyproject.toml").write_text(
|
||||
'[project]\nname = "nanobot-ai"\nversion = "0.3.5"\nrequires-python = ">=3.11"\n\n'
|
||||
)
|
||||
(root / "nanobot/__init__.py").write_text(
|
||||
'def _resolve_version():\n return _read_pyproject_version() or "0.3.5"\n\n'
|
||||
)
|
||||
git(root, "init", "-q")
|
||||
git(root, "add", ".")
|
||||
git(root, "-c", "user.name=Test", "-c", "user.email=test@example.test",
|
||||
"-c", "commit.gpgsign=false", "commit", "-qm", "source")
|
||||
return root, git(root, "rev-parse", "HEAD")
|
||||
|
||||
|
||||
def test_same_source_and_sequence_produce_same_candidate_without_mutating_source(tmp_path, source):
|
||||
root, source_commit = source
|
||||
before = (root / "pyproject.toml").read_bytes()
|
||||
first = prepare_preview(root, tmp_path / "candidate-one", source_commit=source_commit,
|
||||
base="0.3.6", sequence=42)
|
||||
second = prepare_preview(root, tmp_path / "candidate-two", source_commit=source_commit,
|
||||
base="0.3.6", sequence=42)
|
||||
assert first == second
|
||||
assert (root / "pyproject.toml").read_bytes() == before
|
||||
assert git(root, "status", "--porcelain") == ""
|
||||
assert git(tmp_path / "candidate-one", "rev-parse", "HEAD^") == source_commit
|
||||
assert tomllib.loads((tmp_path / "candidate-one/pyproject.toml").read_text())["project"]["version"] == "0.3.6.dev42"
|
||||
assert _candidate_identity(tmp_path / "candidate-one", source_commit) == (
|
||||
"0.3.6.dev42", ">=3.11", first["candidate_commit"],
|
||||
)
|
||||
|
||||
|
||||
def test_dirty_source_is_not_accidentally_included_in_candidate(tmp_path, source):
|
||||
root, source_commit = source
|
||||
(root / "secret.txt").write_text("local data")
|
||||
(root / "nanobot/__init__.py").write_text("uncommitted work")
|
||||
prepare_preview(root, tmp_path / "candidate", source_commit=source_commit, base="0.3.6", sequence=1)
|
||||
assert not (tmp_path / "candidate/secret.txt").exists()
|
||||
assert "0.3.6.dev1" in (tmp_path / "candidate/nanobot/__init__.py").read_text()
|
||||
assert (root / "nanobot/__init__.py").read_text() == "uncommitted work"
|
||||
|
||||
|
||||
def test_refuses_existing_output_and_published_stable_base(tmp_path, source):
|
||||
root, commit = source
|
||||
with pytest.raises(ValueError, match="new directory"):
|
||||
prepare_preview(root, root, source_commit=commit, base="0.3.6", sequence=1)
|
||||
git(root, "tag", "v0.3.6")
|
||||
with pytest.raises(ValueError, match="existing stable tag"):
|
||||
prepare_preview(root, tmp_path / "candidate", source_commit=commit, base="0.3.6", sequence=1)
|
||||
assert not (tmp_path / "candidate").exists()
|
||||
|
||||
|
||||
def test_arbitrary_ref_or_invalid_version_never_creates_candidate(tmp_path, source):
|
||||
root, commit = source
|
||||
with pytest.raises(ValueError, match="exact"):
|
||||
prepare_preview(root, tmp_path / "candidate", source_commit="main", base="0.3.6", sequence=1)
|
||||
with pytest.raises(ValueError):
|
||||
prepare_preview(root, tmp_path / "candidate", source_commit=commit, base="0.3.6.dev1", sequence=2)
|
||||
assert not (tmp_path / "candidate").exists()
|
||||
with pytest.raises(ValueError):
|
||||
preview_version("0.3.6", 0)
|
||||
|
||||
|
||||
def test_verification_rejects_changes_after_candidate_commit(tmp_path, source):
|
||||
root, commit = source
|
||||
target = tmp_path / "candidate"
|
||||
prepare_preview(root, target, source_commit=commit, base="0.3.6", sequence=1)
|
||||
with (target / "nanobot/__init__.py").open("a") as stream:
|
||||
stream.write("# unchecked change\n")
|
||||
with pytest.raises(ValueError, match="uncommitted"):
|
||||
_candidate_identity(target, commit)
|
||||
git(target, "add", ".")
|
||||
git(target, "-c", "user.name=Test", "-c", "user.email=test@example.test",
|
||||
"-c", "commit.gpgsign=false", "commit", "--amend", "--no-edit", "-q")
|
||||
with pytest.raises(ValueError, match="beyond"):
|
||||
_candidate_identity(target, commit)
|
||||
|
||||
|
||||
def test_candidate_verifies_bundled_documentation_against_its_tracked_source(source):
|
||||
from hatch_build import WebUIBuildHook
|
||||
|
||||
root, _ = source
|
||||
with (root / "pyproject.toml").open("a") as stream:
|
||||
stream.write('[tool.hatch.build.targets.sdist]\nexclude = ["docs/plans/**"]\n')
|
||||
(root / "docs/plans").mkdir(parents=True)
|
||||
(root / "docs/README.md").write_text("Checked documentation", encoding="utf-8")
|
||||
(root / "docs/plans/private.md").write_text("Not packaged", encoding="utf-8")
|
||||
git(root, "add", ".")
|
||||
hook = WebUIBuildHook(str(root), {}, None, {}, "", "wheel",
|
||||
SimpleNamespace(display_info=lambda message: None))
|
||||
hook.initialize("editable", {})
|
||||
reference = "nanobot/skills/nanobot-document/references/README.md"
|
||||
names = ["nanobot/__init__.py", "docs/README.md", reference]
|
||||
prefix = "nanobot_ai-0.3.5/"
|
||||
packaged = {prefix + name: (root / name).read_bytes() for name in names}
|
||||
payload = _source_payload(root, packaged, prefix)
|
||||
assert payload[reference] == (root / "docs/README.md").read_bytes()
|
||||
|
||||
# Both the shipped reference and the source used to rebuild the sdist must
|
||||
# match the reviewed documentation, not merely match each other.
|
||||
for name in (reference, "docs/README.md"):
|
||||
with pytest.raises(ValueError, match="differs from the candidate"):
|
||||
_source_payload(root, {**packaged, prefix + name: b"Unchecked instructions"}, prefix)
|
||||
@@ -0,0 +1,291 @@
|
||||
"""Exact selection and staging through real HTTP parsing, without public mutations."""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import zipfile
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from packaging.tags import Tag
|
||||
|
||||
from nanobot.release_feed import CATALOGUE_URL, PYPI_URL, ReleaseFeed, ReleaseFeedError
|
||||
from nanobot.releases import (
|
||||
ReleaseArtifact,
|
||||
ReleaseCatalogue,
|
||||
ReleaseManifest,
|
||||
ReleasePointer,
|
||||
release_filenames,
|
||||
)
|
||||
|
||||
PLATFORM = "macosx_13_0_arm64"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def checksum_only_fixtures(monkeypatch):
|
||||
# These synthetic packages exercise selection/download integrity, not
|
||||
# publication authority. The real approval boundary is tested separately.
|
||||
monkeypatch.setattr(ReleaseFeed, "_authorize", AsyncMock())
|
||||
|
||||
|
||||
def wheel_bytes(version):
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w") as wheel:
|
||||
wheel.writestr(f"nanobot_ai-{version}.dist-info/METADATA",
|
||||
f"Metadata-Version: 2.1\nName: nanobot-ai\nVersion: {version}\n")
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def pypi(version="0.3.5", data=None):
|
||||
data = data or wheel_bytes(version)
|
||||
return {
|
||||
"info": {"name": "nanobot-ai", "version": version, "requires_python": ">=3.11"},
|
||||
"urls": [{"filename": name, "size": len(data), "yanked": False,
|
||||
"digests": {"sha256": hashlib.sha256(data).hexdigest()},
|
||||
"url": f"https://files.pythonhosted.org/packages/test/{name}"}
|
||||
for name in sorted(release_filenames(version)) if name.endswith((".whl", ".tar.gz"))],
|
||||
}
|
||||
|
||||
|
||||
def preview(version="0.3.6.dev42"):
|
||||
data = wheel_bytes(version)
|
||||
manifest = ReleaseManifest(
|
||||
version=version, source_commit="a" * 40, candidate_commit="b" * 40, requires_python=">=3.11",
|
||||
artifacts=[ReleaseArtifact(filename=name, size=len(data), sha256=hashlib.sha256(data).hexdigest())
|
||||
for name in sorted(release_filenames(version))],
|
||||
)
|
||||
payload = manifest.model_dump_json().encode()
|
||||
pointer = ReleasePointer(version=version, candidate_commit=manifest.candidate_commit,
|
||||
manifest_sha256=hashlib.sha256(payload).hexdigest())
|
||||
return pointer, payload, data
|
||||
|
||||
|
||||
def feed(tmp_path, handler, *, platform=PLATFORM, python="3.11.4"):
|
||||
return ReleaseFeed(tmp_path / "cache", transport=httpx.MockTransport(handler),
|
||||
python_version=python, supported_tags=[Tag("py3", "none", platform)])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", ["stable", "preview"])
|
||||
@pytest.mark.parametrize("change", ["older", "changed_bytes", "reinstate", "removed_pointer"])
|
||||
async def test_new_catalogue_generation_cannot_rewrite_observed_release_history(tmp_path, change, channel):
|
||||
pointer, _, _ = preview("0.3.6" if channel == "stable" else "0.3.6.dev42")
|
||||
old = ReleaseCatalogue(generation=1, **{channel: pointer}, withdrawn={"0.3.6.dev40": "Broken startup"})
|
||||
selected = old
|
||||
async with feed(tmp_path, lambda _: httpx.Response(200, json=selected.model_dump(mode="json"))) as client:
|
||||
assert await client.catalogue() == old
|
||||
if change == "older":
|
||||
older = preview("0.3.5" if channel == "stable" else "0.3.6.dev41")[0]
|
||||
selected = old.model_copy(update={"generation": 2, channel: older})
|
||||
elif change == "changed_bytes":
|
||||
selected = old.model_copy(update={"generation": 2, channel: pointer.model_copy(update={"manifest_sha256": "f" * 64})})
|
||||
elif change == "removed_pointer":
|
||||
selected = old.model_copy(update={"generation": 2, channel: None})
|
||||
else:
|
||||
selected = old.model_copy(update={"generation": 2, "withdrawn": {}})
|
||||
with pytest.raises(ReleaseFeedError):
|
||||
await client.catalogue()
|
||||
# A rejected response must not poison a later valid publication.
|
||||
newer = preview("0.3.7" if channel == "stable" else "0.3.7.dev1")[0]
|
||||
selected = old.model_copy(update={"generation": 2, channel: newer})
|
||||
assert getattr(await client.catalogue(), channel) == newer
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stable_selects_and_revalidates_exact_target_not_new_latest(tmp_path):
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
requests.append(str(request.url))
|
||||
assert request.headers.get("authorization") is None
|
||||
assert str(request.url) in (f"{PYPI_URL}/json", f"{PYPI_URL}/0.3.5/json")
|
||||
return httpx.Response(200, json=pypi())
|
||||
|
||||
async with feed(tmp_path, handler) as client:
|
||||
target = await client.latest("stable")
|
||||
assert target.artifact.filename.endswith(f"{PLATFORM}.whl")
|
||||
await client.revalidate(target)
|
||||
assert requests == [f"{PYPI_URL}/json", f"{PYPI_URL}/0.3.5/json"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("change", ["partial", "duplicate", "yanked", "prerelease", "other_host", "other_name"])
|
||||
async def test_bad_stable_metadata_never_becomes_an_offer(tmp_path, change):
|
||||
metadata = pypi()
|
||||
if change == "partial":
|
||||
metadata["urls"].pop()
|
||||
elif change == "duplicate":
|
||||
metadata["urls"].append(metadata["urls"][0])
|
||||
elif change == "yanked":
|
||||
metadata["urls"][0]["yanked"] = True
|
||||
elif change == "prerelease":
|
||||
metadata = pypi("0.3.6.dev1")
|
||||
elif change == "other_name":
|
||||
metadata["info"]["name"] = "not-nanobot"
|
||||
else:
|
||||
for file in metadata["urls"]:
|
||||
file["url"] = file["url"].replace("files.pythonhosted.org", "evil.example")
|
||||
async with feed(tmp_path, lambda _: httpx.Response(200, json=metadata)) as client:
|
||||
with pytest.raises((ReleaseFeedError, ValueError)):
|
||||
await client.latest("stable")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("platform,python", [("win_arm64", "3.11.4"), (PLATFORM, "3.10.0")])
|
||||
async def test_unsupported_runtime_has_no_source_build_fallback(tmp_path, platform, python):
|
||||
async with feed(tmp_path, lambda _: httpx.Response(200, json=pypi()), platform=platform, python=python) as client:
|
||||
with pytest.raises(ReleaseFeedError):
|
||||
await client.latest("stable")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_changed_day_feed_does_not_change_an_already_approved_preview(tmp_path):
|
||||
selected, manifest, _ = preview()
|
||||
newer, _, _ = preview("0.3.6.dev43")
|
||||
catalogue = ReleaseCatalogue(generation=1, preview=selected)
|
||||
|
||||
def handler(request):
|
||||
if str(request.url) == CATALOGUE_URL:
|
||||
return httpx.Response(200, content=catalogue.model_dump_json())
|
||||
assert str(request.url) == selected.manifest_url
|
||||
return httpx.Response(200, content=manifest)
|
||||
|
||||
async with feed(tmp_path, handler) as client:
|
||||
target = await client.latest("preview")
|
||||
catalogue = ReleaseCatalogue(generation=2, preview=newer)
|
||||
await client.revalidate(target)
|
||||
assert target.version == selected.version
|
||||
catalogue = ReleaseCatalogue(generation=3, preview=newer, withdrawn={target.version: "Startup regression"})
|
||||
with pytest.raises(ReleaseFeedError, match="withdrawn"):
|
||||
await client.revalidate(target)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cache_survives_new_process_etag_and_rejects_rollback_or_equivocation(tmp_path):
|
||||
pointer, _, _ = preview()
|
||||
catalogue = ReleaseCatalogue(generation=2, preview=pointer)
|
||||
async with feed(tmp_path, lambda _: httpx.Response(200, content=catalogue.model_dump_json(), headers={"etag": '"v2"'})) as client:
|
||||
await client.catalogue()
|
||||
|
||||
def unchanged(request):
|
||||
assert request.headers["if-none-match"] == '"v2"'
|
||||
return httpx.Response(304)
|
||||
|
||||
async with feed(tmp_path, unchanged) as client:
|
||||
assert await client.catalogue() == catalogue
|
||||
for changed in (ReleaseCatalogue(generation=1, preview=pointer), ReleaseCatalogue(generation=2)):
|
||||
async with feed(tmp_path, lambda _: httpx.Response(200, content=changed.model_dump_json())) as client:
|
||||
with pytest.raises(ReleaseFeedError, match="generation"):
|
||||
await client.catalogue()
|
||||
# A failed check cannot be converted into a successful cached result.
|
||||
async with feed(tmp_path, lambda _: httpx.Response(503)) as client:
|
||||
with pytest.raises(httpx.HTTPStatusError):
|
||||
await client.catalogue()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_untrusted_redirect_and_oversized_metadata_are_rejected(tmp_path):
|
||||
requests = []
|
||||
|
||||
def redirect(request):
|
||||
requests.append(str(request.url))
|
||||
return httpx.Response(302, headers={"location": "http://127.0.0.1/private"})
|
||||
|
||||
async with feed(tmp_path, redirect) as client:
|
||||
with pytest.raises(ValueError, match="HTTPS"):
|
||||
await client.latest("stable")
|
||||
assert len(requests) == 1
|
||||
async with feed(tmp_path, lambda _: httpx.Response(200, content=b"x" * (256 * 1024 + 1))) as client:
|
||||
with pytest.raises(ReleaseFeedError, match="size limit"):
|
||||
await client.catalogue()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stages_actual_wheel_and_reuses_only_verified_bytes(tmp_path):
|
||||
data = wheel_bytes("0.3.5")
|
||||
|
||||
def handler(request):
|
||||
if request.url.host == "pypi.org":
|
||||
return httpx.Response(200, json=pypi(data=data))
|
||||
if request.url.host == "files.pythonhosted.org":
|
||||
return httpx.Response(302, headers={"location": "https://release-assets.githubusercontent.com/wheel"})
|
||||
assert request.url.host == "release-assets.githubusercontent.com"
|
||||
return httpx.Response(200, content=data)
|
||||
|
||||
async with feed(tmp_path, handler) as client:
|
||||
target = await client.latest("stable")
|
||||
wheel = await client.download(target, tmp_path / "staging")
|
||||
assert wheel.read_bytes() == data
|
||||
assert await client.download(target, wheel.parent) == wheel
|
||||
wheel.write_bytes(b"0" * len(data))
|
||||
with pytest.raises(ReleaseFeedError, match="checksum"):
|
||||
await client.download(target, wheel.parent)
|
||||
assert wheel.read_bytes() != data # No clobber to hide the corrupt file.
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_redirect_does_not_inherit_metadata_host_allowlist(tmp_path):
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
requests.append(str(request.url))
|
||||
if request.url.host == "pypi.org":
|
||||
return httpx.Response(200, json=pypi())
|
||||
return httpx.Response(302, headers={"location": "https://raw.githubusercontent.com/private-wheel"})
|
||||
|
||||
async with feed(tmp_path, handler) as client:
|
||||
target = await client.latest("stable")
|
||||
with pytest.raises(ValueError, match="HTTPS"):
|
||||
await client.download(target, tmp_path / "staging")
|
||||
assert not any("raw.githubusercontent.com" in url for url in requests)
|
||||
assert list((tmp_path / "staging").iterdir()) == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_failure_cleans_partial_and_never_publishes_bad_wheel(tmp_path):
|
||||
data = wheel_bytes("0.3.5")
|
||||
|
||||
def handler(request):
|
||||
return (httpx.Response(200, json=pypi(data=data)) if request.url.host == "pypi.org"
|
||||
else httpx.Response(200, content=data[:-1]))
|
||||
|
||||
async with feed(tmp_path, handler) as client:
|
||||
target = await client.latest("stable")
|
||||
with pytest.raises(ReleaseFeedError, match="size"):
|
||||
await client.download(target, tmp_path / "staging")
|
||||
assert list((tmp_path / "staging").iterdir()) == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_preview_failure_never_falls_back_to_checkout_or_pypi(tmp_path):
|
||||
requests = []
|
||||
|
||||
def absent(request):
|
||||
requests.append(str(request.url))
|
||||
return httpx.Response(404)
|
||||
|
||||
async with feed(tmp_path, absent) as client:
|
||||
with pytest.raises(httpx.HTTPStatusError):
|
||||
await client.latest("preview")
|
||||
assert requests == [CATALOGUE_URL]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pypi_yank_after_confirmation_blocks_download(tmp_path):
|
||||
metadata = pypi()
|
||||
async with feed(tmp_path, lambda _: httpx.Response(200, json=metadata)) as client:
|
||||
target = await client.latest("stable")
|
||||
metadata["urls"][0]["yanked"] = True
|
||||
with pytest.raises(ReleaseFeedError, match="withdrawn"):
|
||||
await client.download(target, tmp_path / "staging")
|
||||
assert not (tmp_path / "staging").exists()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_corrupt_manifest_cannot_select_a_different_build(tmp_path):
|
||||
pointer, manifest, _ = preview()
|
||||
catalogue = ReleaseCatalogue(generation=1, preview=pointer)
|
||||
async with feed(tmp_path, lambda request: httpx.Response(200, content=(
|
||||
catalogue.model_dump_json().encode() if str(request.url) == CATALOGUE_URL else manifest + b"\n"
|
||||
))) as client:
|
||||
with pytest.raises(ValueError, match="checksum"):
|
||||
await client.latest("preview")
|
||||
@@ -0,0 +1,76 @@
|
||||
"""The manual handoff binds commands to the verified version and platform bytes."""
|
||||
|
||||
import hashlib
|
||||
import shlex
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.releases import PLATFORMS, ReleaseArtifact, ReleaseManifest, release_filenames
|
||||
from scripts import release_candidate
|
||||
from scripts.release_install_guide import install_command, render_install_guide
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manifest():
|
||||
return ReleaseManifest(
|
||||
version="0.4.0.dev123", source_commit="a" * 40, candidate_commit="b" * 40,
|
||||
requires_python=">=3.11",
|
||||
artifacts=[ReleaseArtifact(filename=name, size=123, sha256="c" * 64)
|
||||
for name in sorted(release_filenames("0.4.0.dev123"))],
|
||||
)
|
||||
|
||||
|
||||
def test_handoff_commands_bind_every_platform_to_its_exact_release(manifest):
|
||||
guide = render_install_guide(manifest)
|
||||
assert manifest.source_commit in guide
|
||||
assert manifest.candidate_commit in guide
|
||||
blocks = [block.split("\n", 1)[1].strip() for block in guide.split("```")[1::2]]
|
||||
commands = [shlex.split(block) for block in blocks if block.startswith("python -I -c ")]
|
||||
# PowerShell feeds the helper on stdin to avoid legacy native -c quoting.
|
||||
commands += [["python", "-I", "-", None, *shlex.split(block.split("'@ | python -I - ", 1)[1])]
|
||||
for block in blocks if block.startswith("@'\n")]
|
||||
assert len(commands) == 5 * 3 * 2
|
||||
for platform in PLATFORMS.values():
|
||||
artifact = next(item for item in manifest.artifacts if item.filename.endswith(f"-{platform}.whl"))
|
||||
assert manifest.artifact_url(artifact) in guide
|
||||
expected = [artifact.filename, str(artifact.size), artifact.sha256]
|
||||
assert sum(command[4:7] == expected for command in commands) == 6
|
||||
assert all("--pre" not in command and "--force" not in command for command in commands)
|
||||
|
||||
|
||||
def test_handoff_cannot_generate_install_commands_for_source_or_foreign_artifact(manifest):
|
||||
source = next(item for item in manifest.artifacts if item.filename.endswith(".tar.gz"))
|
||||
with pytest.raises(ValueError, match="platform wheel"):
|
||||
install_command(manifest, source, owner="pip", existing=False)
|
||||
wheel = next(item for item in manifest.artifacts if item.filename.endswith(".whl"))
|
||||
with pytest.raises(ValueError, match="does not belong"):
|
||||
install_command(manifest, wheel.model_copy(update={"sha256": "d" * 64}), owner="uv", existing=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("recognized", [True, False], ids=["current-installer", "older-installer"])
|
||||
def test_verified_handoff_only_offers_bootstrap_supported_by_candidate(tmp_path, monkeypatch, manifest, recognized):
|
||||
root, generator, artifacts = (tmp_path / name for name in ("candidate", "generator", "artifacts"))
|
||||
artifacts.mkdir()
|
||||
for directory in (root, generator):
|
||||
(directory / "scripts").mkdir(parents=True)
|
||||
for name in ("install.sh", "install.ps1"):
|
||||
contents = b"current implementation" if directory == generator or recognized else b"older implementation"
|
||||
(directory / "scripts" / name).write_bytes(contents)
|
||||
# Packaging is covered by the real archive test. Here the public writer must
|
||||
# preserve the exact serialized manifest hash and inspect both candidate scripts.
|
||||
payload = (manifest.model_dump_json(indent=2) + "\n").encode()
|
||||
(artifacts / "release-manifest.json").write_bytes(payload)
|
||||
monkeypatch.setattr(release_candidate, "ROOT", generator)
|
||||
monkeypatch.setattr(release_candidate, "verify_candidate", lambda *args, **kwargs: manifest)
|
||||
guide = tmp_path / "install.md"
|
||||
release_candidate.write_install_guide(root, artifacts, guide, source_commit=manifest.source_commit)
|
||||
text = guide.read_text()
|
||||
assert ("## Automatic platform selection" in text) == recognized
|
||||
if recognized:
|
||||
digest = hashlib.sha256(payload).hexdigest()
|
||||
assert f"--manifest-sha256 '{digest}'" in text
|
||||
assert f"-ManifestSha256 '{digest}'" in text
|
||||
for name in ("install.sh", "install.ps1"):
|
||||
assert f"/{manifest.candidate_commit}/scripts/{name}" in text
|
||||
assert "<summary>Manual platform and manager commands</summary>" in text
|
||||
assert manifest.artifacts[0].sha256 in text # The explicit manual path remains available.
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Publication authority is distinct from index/download integrity and recovery."""
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from importlib.resources import as_file, files
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import yaml
|
||||
from packaging.tags import Tag
|
||||
from sigstore.models import Bundle, TrustedRoot
|
||||
from sigstore.verify import Verifier
|
||||
from sigstore.verify.policy import Identity
|
||||
|
||||
from nanobot import release_feed, release_trust
|
||||
from nanobot.release_feed import CATALOGUE_URL, PYPI_URL, ReleaseFeed, ReleaseFeedError
|
||||
from nanobot.releases import (
|
||||
RELEASE_DOWNLOAD,
|
||||
ReleaseArtifact,
|
||||
ReleaseCatalogue,
|
||||
ReleaseManifest,
|
||||
ReleasePointer,
|
||||
release_filenames,
|
||||
)
|
||||
from scripts.verify_release_approval import verify_manifest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def crypto_verifier(monkeypatch):
|
||||
# Deterministic offline test root from the pinned upstream distribution.
|
||||
# Production must refresh its TUF trust root, not read a caller-selected root.
|
||||
resource = files("sigstore._store").joinpath("https%3A%2F%2Ftuf-repo-cdn.sigstage.dev/trusted_root.json")
|
||||
with as_file(resource) as path:
|
||||
verifier = Verifier(trusted_root=TrustedRoot.from_file(str(path)))
|
||||
monkeypatch.setattr(Verifier, "production", lambda: verifier)
|
||||
return verifier
|
||||
|
||||
|
||||
def test_real_signature_is_valid_but_not_an_official_release_approval(crypto_verifier):
|
||||
fixtures = Path(__file__).parent / "fixtures/sigstore"
|
||||
payload = (fixtures / "bundle_v3.txt").read_bytes()
|
||||
proof = (fixtures / "bundle_v3.txt.sigstore").read_bytes()
|
||||
bundle = Bundle.from_json(proof)
|
||||
identity = Identity(identity="william@yossarian.net", issuer="https://github.com/login/oauth")
|
||||
crypto_verifier.verify_artifact(payload, bundle, identity)
|
||||
with pytest.raises(Exception):
|
||||
crypto_verifier.verify_artifact(payload + b"modified", bundle, identity)
|
||||
with pytest.raises(ValueError, match="official release approval"):
|
||||
release_trust.verify_release_approval(payload, proof)
|
||||
|
||||
|
||||
def test_policy_is_fixed_to_manual_official_main_workflow(monkeypatch):
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import NameOID, ObjectIdentifier
|
||||
|
||||
seen = []
|
||||
class Capture:
|
||||
def verify_artifact(self, payload, bundle, policy):
|
||||
seen.append(policy)
|
||||
monkeypatch.setattr(Verifier, "production", lambda: Capture())
|
||||
monkeypatch.setattr(Bundle, "from_json", lambda _: object())
|
||||
release_trust.verify_release_approval(b"manifest", b"proof")
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "policy-only fixture")])
|
||||
def certificate(identity, issuer, trigger):
|
||||
builder = (x509.CertificateBuilder().subject_name(name).issuer_name(name)
|
||||
.public_key(key.public_key()).serial_number(1)
|
||||
.not_valid_before(datetime.now(timezone.utc) - timedelta(minutes=1))
|
||||
.not_valid_after(datetime.now(timezone.utc) + timedelta(minutes=1))
|
||||
.add_extension(x509.SubjectAlternativeName([x509.UniformResourceIdentifier(identity)]), False))
|
||||
for oid, value in (("1", issuer), ("2", trigger)):
|
||||
builder = builder.add_extension(x509.UnrecognizedExtension(
|
||||
ObjectIdentifier("1.3.6.1.4.1.57264.1." + oid), value.encode()), False)
|
||||
return builder.sign(key, hashes.SHA256())
|
||||
expected = (release_trust.RELEASE_IDENTITY, release_trust.RELEASE_ISSUER, "workflow_dispatch")
|
||||
seen[0].verify(certificate(*expected))
|
||||
for changed in (
|
||||
(expected[0].replace("HKUDS", "attacker"), expected[1], expected[2]),
|
||||
(expected[0].replace("refs/heads/main", "refs/pull/1/merge"), expected[1], expected[2]),
|
||||
(expected[0], "https://example.com", expected[2]),
|
||||
(expected[0], expected[1], "pull_request_target"),
|
||||
):
|
||||
with pytest.raises(Exception):
|
||||
seen[0].verify(certificate(*changed))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", ["malformed", "unavailable", "oversized"])
|
||||
def test_failed_verification_has_no_checksum_only_fallback(monkeypatch, failure):
|
||||
unavailable = Mock(side_effect=OSError("trust service unavailable"))
|
||||
monkeypatch.setattr(Verifier, "production", unavailable)
|
||||
proof = b"x" * (256 * 1024 + 1) if failure == "oversized" else b"invalid"
|
||||
if failure == "unavailable":
|
||||
proof = (Path(__file__).parent / "fixtures/sigstore/bundle_v3.txt.sigstore").read_bytes()
|
||||
with pytest.raises(ValueError):
|
||||
release_trust.verify_release_approval(b"manifest", proof)
|
||||
assert unavailable.call_count == (1 if failure == "unavailable" else 0)
|
||||
|
||||
|
||||
def test_malformed_approval_is_rejected_without_contacting_trust_service(monkeypatch):
|
||||
verifier = Mock()
|
||||
monkeypatch.setattr(Verifier, "production", verifier)
|
||||
with pytest.raises(ValueError, match="official release approval"):
|
||||
release_trust.verify_release_approval(b"manifest", b"not a bundle")
|
||||
verifier.assert_not_called()
|
||||
|
||||
|
||||
def release(version):
|
||||
return ReleaseManifest(version=version, source_commit="a" * 40, candidate_commit="b" * 40,
|
||||
requires_python=">=3.11", artifacts=[
|
||||
ReleaseArtifact(filename=name, size=123, sha256="c" * 64) for name in sorted(release_filenames(version))
|
||||
])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", ["stable", "preview"])
|
||||
@pytest.mark.parametrize("change", ["valid", "missing", "forged", "wrong_package", "wrong_version"])
|
||||
async def test_download_and_handoff_require_approval_before_any_staging(tmp_path, monkeypatch, channel, change):
|
||||
version = "0.3.6" if channel == "stable" else "0.3.7.dev1"
|
||||
manifest = release(version)
|
||||
payload = manifest.model_dump_json().encode()
|
||||
pointer = ReleasePointer(version=version, candidate_commit=manifest.candidate_commit,
|
||||
manifest_sha256=hashlib.sha256(payload).hexdigest())
|
||||
catalogue = ReleaseCatalogue(generation=1, preview=pointer) if channel == "preview" else None
|
||||
requests = []
|
||||
base = f"{RELEASE_DOWNLOAD}/v{version}/release-manifest.json"
|
||||
def respond(request):
|
||||
url = str(request.url)
|
||||
requests.append(url)
|
||||
if url == CATALOGUE_URL:
|
||||
return httpx.Response(200, content=catalogue.model_dump_json())
|
||||
if url.startswith(PYPI_URL):
|
||||
return httpx.Response(200, json={
|
||||
"info": {"name": "nanobot-ai", "version": version, "requires_python": ">=3.11"},
|
||||
"urls": [{"filename": item.filename, "size": item.size, "yanked": False,
|
||||
"url": f"https://files.pythonhosted.org/packages/{item.filename}",
|
||||
"digests": {"sha256": item.sha256}} for item in manifest.artifacts
|
||||
if item.filename.endswith((".whl", ".tar.gz"))],
|
||||
})
|
||||
if url == base:
|
||||
return httpx.Response(200, content=payload)
|
||||
if url == base + ".sigstore.json":
|
||||
return httpx.Response(404 if change == "missing" else 200, content=b"proof")
|
||||
pytest.fail("Unapproved package download attempted")
|
||||
# Only the crypto boundary is substituted for synthetic manifests; use the
|
||||
# real feed, HTTP parsing, identity comparison and pre-staging admission.
|
||||
verifier = Mock(side_effect=ValueError("forged approval") if change == "forged" else None)
|
||||
monkeypatch.setattr(release_feed, "verify_release_approval", verifier)
|
||||
async with ReleaseFeed(tmp_path / "cache", transport=httpx.MockTransport(respond),
|
||||
supported_tags=[Tag("py3", "none", "win_amd64")]) as feed:
|
||||
target = await feed.latest(channel)
|
||||
if change == "wrong_package":
|
||||
payload = payload.replace(b'"c' + b"c" * 63, b'"d' + b"d" * 63)
|
||||
elif change == "wrong_version":
|
||||
payload = release("0.4.0").model_dump_json().encode()
|
||||
if change == "valid":
|
||||
await feed.revalidate(target)
|
||||
verifier.assert_called_once_with(payload, b"proof")
|
||||
# A previous successful check is not a reusable authorization when
|
||||
# the proof disappears or changes before handoff/retry.
|
||||
verifier.side_effect = ValueError("approval revoked or replaced")
|
||||
with pytest.raises(ValueError, match="revoked or replaced"):
|
||||
await feed.revalidate(target)
|
||||
assert verifier.call_count == 2
|
||||
else:
|
||||
with pytest.raises((ValueError, httpx.HTTPStatusError, ReleaseFeedError)):
|
||||
await feed.download(target, tmp_path / "staging")
|
||||
assert not (tmp_path / "staging").exists()
|
||||
|
||||
|
||||
def test_signing_handoff_requires_independently_approved_identity_and_digest(tmp_path):
|
||||
manifest = release("0.3.7.dev1")
|
||||
path = tmp_path / "release-manifest.json"
|
||||
path.write_text(manifest.model_dump_json())
|
||||
approved = dict(sha256=hashlib.sha256(path.read_bytes()).hexdigest(), version=manifest.version,
|
||||
source_commit=manifest.source_commit, candidate_commit=manifest.candidate_commit)
|
||||
assert verify_manifest(path, **approved) == manifest
|
||||
for field in approved:
|
||||
with pytest.raises(ValueError):
|
||||
verify_manifest(path, **(approved | {field: "wrong"}))
|
||||
|
||||
|
||||
def test_approval_workflow_is_manual_gated_and_has_no_publication_permission():
|
||||
workflow = Path(__file__).parents[1] / ".github/workflows/release-approve.yml"
|
||||
definition = yaml.load(workflow.read_text(), Loader=yaml.BaseLoader)
|
||||
assert set(definition["on"]) == {"workflow_dispatch"}
|
||||
assert definition["permissions"] == {}
|
||||
job = definition["jobs"]["approve"]
|
||||
assert job["environment"] == "release-approval"
|
||||
assert job["permissions"] == {"contents": "read", "id-token": "write"}
|
||||
assert "github.ref == 'refs/heads/main'" in job["if"]
|
||||
assert "vars.NANOBOT_RELEASE_SIGNING_ENABLED == 'true'" in job["if"]
|
||||
for step in job["steps"]:
|
||||
if "uses" in step:
|
||||
assert re.fullmatch(r"[\w-]+/[\w-]+@[0-9a-f]{40}", step["uses"])
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Consumer contracts for trusted release metadata; no package installation here."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from packaging.tags import Tag, mac_platforms
|
||||
from pydantic import ValidationError
|
||||
|
||||
from nanobot.releases import (
|
||||
ReleaseArtifact,
|
||||
ReleaseCatalogue,
|
||||
ReleaseManifest,
|
||||
ReleasePointer,
|
||||
release_filenames,
|
||||
)
|
||||
|
||||
|
||||
def manifest(version="0.3.6.dev42"):
|
||||
return ReleaseManifest(
|
||||
version=version, source_commit="a" * 40, candidate_commit="b" * 40,
|
||||
requires_python=">=3.11",
|
||||
artifacts=[ReleaseArtifact(filename=name, size=123, sha256="c" * 64)
|
||||
for name in sorted(release_filenames(version))],
|
||||
)
|
||||
|
||||
|
||||
def pointer(version):
|
||||
release = manifest(version)
|
||||
return ReleasePointer(version=version, candidate_commit=release.candidate_commit,
|
||||
manifest_sha256=hashlib.sha256(release.model_dump_json().encode()).hexdigest())
|
||||
|
||||
|
||||
def test_preview_is_opt_in_and_subscribers_receive_the_final_release():
|
||||
catalogue = ReleaseCatalogue(generation=10, stable=pointer("0.3.5"), preview=pointer("0.3.6.dev42"))
|
||||
assert catalogue.latest("stable").version == "0.3.5"
|
||||
assert catalogue.latest("preview").version == "0.3.6.dev42"
|
||||
released = ReleaseCatalogue(generation=11, stable=pointer("0.3.6"), preview=catalogue.preview)
|
||||
assert released.latest("preview").version == "0.3.6"
|
||||
|
||||
|
||||
def test_withdrawal_and_stale_catalogue_are_not_update_offers():
|
||||
catalogue = ReleaseCatalogue(generation=10, stable=pointer("0.3.5"), preview=pointer("0.3.6.dev42"),
|
||||
withdrawn={"0.3.6.dev42": "Broken startup"})
|
||||
assert catalogue.latest("preview").version == "0.3.5"
|
||||
with pytest.raises(ValueError, match="older"):
|
||||
catalogue.latest("preview", minimum_generation=11)
|
||||
assert ReleaseCatalogue(generation=10).latest("stable") is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", ["0.3.6.dev42", "0.3.6rc1", "0.3.6+local", "../main", "00.3.6"])
|
||||
def test_stable_catalogue_never_accepts_unreleased_or_noncanonical_targets(version):
|
||||
with pytest.raises(ValueError):
|
||||
ReleaseCatalogue.model_validate({
|
||||
"generation": 1,
|
||||
"stable": {"version": version, "candidate_commit": "a" * 40, "manifest_sha256": "b" * 64},
|
||||
})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("platform", [
|
||||
"macosx_13_0_arm64", "macosx_13_0_x86_64", "manylinux_2_17_aarch64",
|
||||
"manylinux_2_17_x86_64", "win_amd64",
|
||||
])
|
||||
def test_target_wheel_and_url_are_owned_by_the_manifest(platform):
|
||||
release = manifest()
|
||||
artifact = release.wheel_for(python_version="3.11.4", supported_tags=[Tag("py3", "none", platform)])
|
||||
assert artifact.filename == f"nanobot_ai-0.3.6.dev42-py3-none-{platform}.whl"
|
||||
assert release.artifact_url(artifact) == (
|
||||
"https://github.com/HKUDS/nanobot/releases/download/v0.3.6.dev42/"
|
||||
f"{artifact.filename}#sha256={'c' * 64}"
|
||||
)
|
||||
|
||||
|
||||
def test_newer_macos_uses_compatible_minimum_platform_tag():
|
||||
tags = [Tag("py3", "none", platform) for platform in mac_platforms((15, 0), "arm64")]
|
||||
assert manifest().wheel_for(python_version="3.14.0", supported_tags=tags).filename.endswith(
|
||||
"macosx_13_0_arm64.whl"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("platform", ["musllinux_1_2_x86_64", "win_arm64"])
|
||||
def test_unsupported_platform_does_not_fall_back_to_source_build(platform):
|
||||
with pytest.raises(ValueError, match="No compatible"):
|
||||
manifest().wheel_for(python_version="3.11.4", supported_tags=[Tag("py3", "none", platform)])
|
||||
|
||||
|
||||
def test_python_requirement_checked_before_platform_selection():
|
||||
with pytest.raises(ValueError, match="requires Python"):
|
||||
manifest().wheel_for(python_version="3.10.0", supported_tags=[Tag("py3", "none", "win_amd64")])
|
||||
|
||||
|
||||
def test_downloaded_manifest_must_match_selected_bytes_and_identity():
|
||||
release = manifest()
|
||||
payload = release.model_dump_json().encode()
|
||||
selected = pointer(release.version)
|
||||
assert selected.verify_manifest(payload) == release
|
||||
with pytest.raises(ValueError, match="checksum"):
|
||||
selected.verify_manifest(payload + b"\n")
|
||||
other_commit = selected.model_copy(update={"candidate_commit": "d" * 40})
|
||||
with pytest.raises(ValueError, match="identity"):
|
||||
other_commit.verify_manifest(payload)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", ["missing", "duplicate", "mixed_version", "universal", "url"])
|
||||
def test_manifest_rejects_partial_mixed_or_redirected_uploads(change):
|
||||
payload = manifest().model_dump(mode="json")
|
||||
if change == "missing":
|
||||
payload["artifacts"].pop()
|
||||
elif change == "duplicate":
|
||||
payload["artifacts"][-1] = payload["artifacts"][0]
|
||||
elif change == "mixed_version":
|
||||
payload["artifacts"][-1]["filename"] = "nanobot_ai-0.3.5.tar.gz"
|
||||
elif change == "universal":
|
||||
payload["artifacts"][-1]["filename"] = "nanobot_ai-0.3.6.dev42-py3-none-any.whl"
|
||||
else:
|
||||
payload["artifacts"][0]["url"] = "https://untrusted.example/installer.sh"
|
||||
with pytest.raises(ValidationError):
|
||||
ReleaseManifest.model_validate_json(json.dumps(payload))
|
||||
|
||||
|
||||
def test_catalogue_unknown_schema_and_blank_withdrawal_reason_fail_closed():
|
||||
with pytest.raises(ValidationError):
|
||||
ReleaseCatalogue.model_validate_json('{"schema_version":2,"generation":1}')
|
||||
with pytest.raises(ValidationError, match="withdrawal reason"):
|
||||
ReleaseCatalogue(generation=1, withdrawn={"0.3.6.dev42": " "})
|
||||
@@ -0,0 +1,410 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
import typer
|
||||
from packaging.version import Version
|
||||
from typer.testing import CliRunner
|
||||
|
||||
from nanobot import update
|
||||
from nanobot.cli.update import update as update_command
|
||||
from nanobot.installation_lock import installation_access, installation_id, pending_update_path
|
||||
from nanobot.optional_features import install_packages
|
||||
|
||||
|
||||
def git(root: Path, *args: str) -> str:
|
||||
return subprocess.run(
|
||||
["git", "-C", str(root), *args], check=True, capture_output=True, text=True,
|
||||
).stdout.strip()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def checkout(tmp_path, monkeypatch):
|
||||
upstream = tmp_path / "upstream"
|
||||
upstream.mkdir()
|
||||
git(upstream, "init", "--initial-branch=main")
|
||||
git(upstream, "config", "user.name", "Update test")
|
||||
git(upstream, "config", "user.email", "test@example.invalid")
|
||||
(upstream / "file").write_text("first", encoding="utf-8")
|
||||
git(upstream, "add", ".")
|
||||
git(upstream, "commit", "-m", "first")
|
||||
root = tmp_path / "checkout"
|
||||
git(tmp_path, "clone", str(upstream), str(root))
|
||||
monkeypatch.setattr(update, "source_checkout", lambda: root)
|
||||
return root, upstream
|
||||
|
||||
|
||||
def test_source_update_fast_forwards_current_branch(checkout):
|
||||
root, upstream = checkout
|
||||
(upstream / "file").write_text("second", encoding="utf-8")
|
||||
git(upstream, "commit", "-am", "second")
|
||||
assert update._prepare_source(lambda _: None) == root
|
||||
assert git(root, "rev-parse", "HEAD") == git(upstream, "rev-parse", "HEAD")
|
||||
assert git(root, "branch", "--show-current") == "main"
|
||||
|
||||
|
||||
def test_release_install_gets_a_managed_source_checkout(checkout, tmp_path, monkeypatch):
|
||||
_, upstream = checkout
|
||||
monkeypatch.setattr(update, "source_checkout", lambda: None)
|
||||
monkeypatch.setattr(Path, "home", lambda: tmp_path)
|
||||
monkeypatch.setattr(update, "_SOURCE_URL", str(upstream))
|
||||
root = update._prepare_source(lambda _: None)
|
||||
assert root == tmp_path / ".nanobot/src" / installation_id()[:16]
|
||||
assert git(root, "rev-parse", "HEAD") == git(upstream, "rev-parse", "HEAD")
|
||||
assert update._prepare_source(lambda _: None) == root
|
||||
|
||||
|
||||
def test_source_update_preserves_local_changes(checkout):
|
||||
root, _ = checkout
|
||||
(root / "file").write_text("my edits", encoding="utf-8")
|
||||
before = git(root, "rev-parse", "HEAD")
|
||||
with pytest.raises(update.UpdateError, match="local changes"):
|
||||
update._prepare_source(lambda _: None)
|
||||
assert (root / "file").read_text() == "my edits"
|
||||
assert git(root, "rev-parse", "HEAD") == before
|
||||
|
||||
|
||||
def test_source_update_refuses_local_commits(checkout):
|
||||
root, _ = checkout
|
||||
git(root, "-c", "user.name=Test", "-c", "user.email=test@example.invalid",
|
||||
"commit", "--allow-empty", "-m", "local")
|
||||
before = git(root, "rev-parse", "HEAD")
|
||||
with pytest.raises(update.UpdateError, match="cannot fast-forward"):
|
||||
update._prepare_source(lambda _: None)
|
||||
assert git(root, "rev-parse", "HEAD") == before
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def isolated_update(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(Path, "home", lambda: tmp_path)
|
||||
monkeypatch.delenv("RENDER", raising=False)
|
||||
if Path("/.dockerenv").exists():
|
||||
pytest.skip("Self-update intentionally refuses containers")
|
||||
monkeypatch.setattr(update, "latest_release", lambda: "0.3.5")
|
||||
monkeypatch.setattr(update, "__version__", "0.3.4")
|
||||
monkeypatch.setattr(update, "_installed_version", lambda: Version(update.__version__))
|
||||
monkeypatch.setattr(update, "update_blocked_reason", lambda **kwargs: "")
|
||||
monkeypatch.setattr(update, "_checked", lambda *args, **kwargs: json.dumps(["0.3.5", "/env/nanobot/__init__.py"]))
|
||||
install = Mock()
|
||||
monkeypatch.setattr(update, "_install", install)
|
||||
return install
|
||||
|
||||
|
||||
def test_release_update_replaces_same_version_editable_only(isolated_update, monkeypatch):
|
||||
monkeypatch.setattr(update, "_is_editable", lambda: True)
|
||||
result = update.update_installation(output=lambda _: None)
|
||||
assert result == {"version": "0.3.5", "source": "pypi", "requires_restart": True}
|
||||
assert isolated_update.call_args_list[0].args == (["nanobot-ai==0.3.5"],)
|
||||
assert isolated_update.call_args_list[1].args == (
|
||||
["--force-reinstall", "--no-deps", "nanobot-ai==0.3.5"],
|
||||
)
|
||||
|
||||
|
||||
def test_release_update_does_not_force_reinstall_wheel(isolated_update, monkeypatch):
|
||||
monkeypatch.setattr(update, "_is_editable", lambda: False)
|
||||
update.update_installation(output=lambda _: None)
|
||||
isolated_update.assert_called_once_with(["nanobot-ai==0.3.5"], upgrade=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("updating", [False, True], ids=["live-runtime", "another-updater"])
|
||||
def test_release_update_does_not_modify_an_in_use_installation(isolated_update, updating):
|
||||
with installation_access(updating=updating):
|
||||
with pytest.raises(update.UpdateError, match="installation is in use"):
|
||||
update.update_installation(output=lambda _: None)
|
||||
isolated_update.assert_not_called()
|
||||
assert not update.incomplete_update()
|
||||
|
||||
|
||||
def test_update_verifies_in_fresh_interpreter(isolated_update, monkeypatch):
|
||||
monkeypatch.setattr(update, "_is_editable", lambda: False)
|
||||
checked = Mock(return_value=json.dumps(["0.3.4", "/env/nanobot/__init__.py"]))
|
||||
monkeypatch.setattr(update, "_checked", checked)
|
||||
with pytest.raises(update.UpdateError, match="expected 0.3.5"):
|
||||
update.update_installation(output=lambda _: None)
|
||||
assert checked.call_args_list[0].args[0][:3] == [sys.executable, "-I", "-c"]
|
||||
assert checked.call_args_list[1].args[0][:2] == [sys.executable, "-c"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("has_uv", [False, True])
|
||||
def test_installer_bootstraps_only_when_pip_is_missing(monkeypatch, has_uv):
|
||||
calls = []
|
||||
|
||||
def run(command, **kwargs):
|
||||
calls.append(command)
|
||||
if len(calls) == 1:
|
||||
return subprocess.CompletedProcess(command, 1, "", "No module named pip")
|
||||
return subprocess.CompletedProcess(command, 0, "", "")
|
||||
|
||||
monkeypatch.setattr("nanobot.optional_features.shutil.which", lambda _: "uv" if has_uv else None)
|
||||
result = install_packages(["--force-reinstall", "--no-deps", "nanobot-ai==0.3.5"], "update", runner=run)
|
||||
assert result.ok
|
||||
if has_uv:
|
||||
assert calls[1][:5] == ["uv", "pip", "install", "--python", sys.executable]
|
||||
assert "--reinstall" in calls[1]
|
||||
assert "--force-reinstall" not in calls[1]
|
||||
assert "--no-deps" in calls[1]
|
||||
else:
|
||||
assert calls[1] == [sys.executable, "-m", "ensurepip", "--upgrade"]
|
||||
assert calls[2] == calls[0]
|
||||
|
||||
|
||||
def test_installer_preserves_satisfied_dependencies():
|
||||
runner = Mock(return_value=subprocess.CompletedProcess([], 0, "", ""))
|
||||
assert install_packages(["nanobot-ai==0.3.5"], "update", upgrade=True, runner=runner).ok
|
||||
command = runner.call_args.args[0]
|
||||
assert command[:4] == [sys.executable, "-m", "pip", "install"]
|
||||
assert command[command.index("--upgrade-strategy") + 1] == "only-if-needed"
|
||||
assert "--force-reinstall" not in command
|
||||
|
||||
|
||||
def test_cli_check_is_read_only(monkeypatch):
|
||||
monkeypatch.setattr(update, "latest_release", lambda: "9.0.0")
|
||||
install = Mock()
|
||||
monkeypatch.setattr(update, "update_installation", install)
|
||||
app = typer.Typer()
|
||||
app.command()(update_command)
|
||||
result = CliRunner().invoke(app, ["--check"])
|
||||
assert result.exit_code == 0
|
||||
assert "Latest release: 9.0.0" in result.stdout
|
||||
install.assert_not_called()
|
||||
|
||||
|
||||
def test_windows_launchers_are_replaced_without_overwriting_running_file(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(sys, "platform", "win32")
|
||||
monkeypatch.setattr(update.sysconfig, "get_path", lambda _: str(tmp_path))
|
||||
launcher = tmp_path / "nanobot.exe"
|
||||
launcher.write_bytes(b"old")
|
||||
with update._release_windows_launchers():
|
||||
assert not launcher.exists()
|
||||
assert (tmp_path / ".nanobot.exe.update-backup").read_bytes() == b"old"
|
||||
launcher.write_bytes(b"new")
|
||||
assert launcher.read_bytes() == b"new"
|
||||
assert not (tmp_path / ".nanobot.exe.update-backup").exists()
|
||||
|
||||
|
||||
def test_windows_launchers_are_restored_after_failed_or_noop_install(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(sys, "platform", "win32")
|
||||
monkeypatch.setattr(update.sysconfig, "get_path", lambda _: str(tmp_path))
|
||||
launcher = tmp_path / "nanobot.exe"
|
||||
launcher.write_bytes(b"old")
|
||||
with pytest.raises(update.UpdateError):
|
||||
with update._release_windows_launchers():
|
||||
raise update.UpdateError("offline")
|
||||
assert launcher.read_bytes() == b"old"
|
||||
|
||||
|
||||
def test_windows_recovers_launcher_left_by_interrupted_update(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(sys, "platform", "win32")
|
||||
monkeypatch.setattr(update.sysconfig, "get_path", lambda _: str(tmp_path))
|
||||
(tmp_path / ".nanobot.exe.update-backup").write_bytes(b"old")
|
||||
with update._release_windows_launchers():
|
||||
pass
|
||||
assert (tmp_path / "nanobot.exe").read_bytes() == b"old"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("flag", ["--dev", "--update-dev"])
|
||||
def test_cli_dev_is_explicit(monkeypatch, flag):
|
||||
install = Mock(return_value={"version": "0.3.5", "requires_restart": True})
|
||||
monkeypatch.setattr(update, "update_installation", install)
|
||||
app = typer.Typer()
|
||||
app.command()(update_command)
|
||||
assert CliRunner().invoke(app, [flag]).exit_code == 0
|
||||
assert install.call_args.kwargs["dev"] is True
|
||||
|
||||
|
||||
def test_update_rejects_shadowed_restart_even_with_matching_metadata(isolated_update, monkeypatch):
|
||||
monkeypatch.setattr(update, "_is_editable", lambda: False)
|
||||
monkeypatch.setattr(update, "_checked", Mock(side_effect=[
|
||||
json.dumps(["0.3.5", "/env/nanobot/__init__.py"]),
|
||||
json.dumps(["0.3.5", "/checkout/nanobot/__init__.py"]),
|
||||
]))
|
||||
with pytest.raises(update.UpdateError, match="restart would load a different") as error:
|
||||
update.update_installation(output=lambda _: None)
|
||||
assert error.value.needs_repair
|
||||
assert update.incomplete_update()
|
||||
|
||||
|
||||
def test_source_release_switch_is_blocked_before_any_install(checkout, monkeypatch):
|
||||
monkeypatch.setattr(sys, "prefix", "/test/venv")
|
||||
monkeypatch.setattr(sys, "base_prefix", "/test/python")
|
||||
assert "outside the checkout" in update.update_blocked_reason()
|
||||
assert update.update_blocked_reason(dev=True) == ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize("receipt,command", [
|
||||
("uv-receipt.toml", "uv tool upgrade"),
|
||||
("pipx_metadata.json", "pipx upgrade"),
|
||||
])
|
||||
def test_tool_manager_environment_is_not_overwritten(tmp_path, monkeypatch, receipt, command):
|
||||
(tmp_path / receipt).write_text("owned by installer", encoding="utf-8")
|
||||
monkeypatch.setattr(sys, "prefix", str(tmp_path))
|
||||
assert command in update.update_blocked_reason()
|
||||
assert command in update.update_blocked_reason(dev=True)
|
||||
|
||||
|
||||
def test_update_noop_does_not_install_or_require_restart(isolated_update, monkeypatch):
|
||||
monkeypatch.setattr(update, "__version__", "0.3.5")
|
||||
monkeypatch.setattr(update, "_is_editable", lambda: False)
|
||||
assert not update.update_installation()["requires_restart"]
|
||||
isolated_update.assert_not_called()
|
||||
assert not update.incomplete_update()
|
||||
|
||||
|
||||
def test_preview_does_not_silently_downgrade_to_stable(isolated_update, monkeypatch):
|
||||
monkeypatch.setattr(update, "__version__", "0.3.6.dev2026101001")
|
||||
with pytest.raises(update.UpdateError, match="allow-downgrade"):
|
||||
update.update_installation()
|
||||
isolated_update.assert_not_called()
|
||||
assert not update.incomplete_update()
|
||||
monkeypatch.setattr(update, "_is_editable", lambda: False)
|
||||
assert update.update_installation(allow_downgrade=True)["requires_restart"]
|
||||
assert not update.incomplete_update()
|
||||
|
||||
|
||||
def test_failed_install_retains_marker_until_successful_retry(isolated_update, monkeypatch):
|
||||
monkeypatch.setattr(update, "_is_editable", lambda: False)
|
||||
isolated_update.side_effect = update.UpdateError("package install failed")
|
||||
with pytest.raises(update.UpdateError, match="No automatic rollback") as error:
|
||||
update.update_installation()
|
||||
assert error.value.needs_repair
|
||||
assert update.incomplete_update()
|
||||
isolated_update.side_effect = None
|
||||
update.update_installation()
|
||||
assert not update.incomplete_update()
|
||||
|
||||
|
||||
def test_legacy_retry_cannot_replace_an_exact_worker_job(isolated_update):
|
||||
marker = pending_update_path()
|
||||
marker.parent.mkdir(parents=True)
|
||||
marker.write_text('{"schema_version":2,"job_id":"an-exact-job","version":"0.3.5"}')
|
||||
with pytest.raises(update.UpdateError, match="saved update job") as error:
|
||||
update.update_installation()
|
||||
assert error.value.needs_repair
|
||||
isolated_update.assert_not_called()
|
||||
assert marker.exists()
|
||||
|
||||
|
||||
def test_source_preflight_failure_does_not_mark_installation_modified(checkout, isolated_update, monkeypatch):
|
||||
root, _ = checkout
|
||||
(root / "file").write_text("my edits", encoding="utf-8")
|
||||
monkeypatch.setattr(update, "ensure_bun", lambda **kwargs: "bun")
|
||||
with pytest.raises(update.UpdateError, match="local changes") as error:
|
||||
update.update_installation(dev=True)
|
||||
assert not error.value.needs_repair
|
||||
assert not update.incomplete_update()
|
||||
|
||||
|
||||
def test_real_python_restart_resolution_detects_cwd_shadowing(tmp_path, monkeypatch):
|
||||
"""Exercise real import lookup without installing or changing the user's env."""
|
||||
import venv
|
||||
|
||||
env = tmp_path / "env"
|
||||
venv.EnvBuilder(with_pip=False).create(env)
|
||||
executable = env / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
|
||||
site = Path(subprocess.check_output([
|
||||
str(executable), "-I", "-c", "import sysconfig; print(sysconfig.get_path('purelib'))",
|
||||
], text=True).strip())
|
||||
package = site / "nanobot"
|
||||
package.mkdir()
|
||||
(package / "__init__.py").write_text("__version__ = '0.3.5'\n", encoding="utf-8")
|
||||
checkout = tmp_path / "source"
|
||||
(checkout / "nanobot").mkdir(parents=True)
|
||||
# Matching metadata is the original bug: the old code can report a new version.
|
||||
(checkout / "nanobot/__init__.py").write_text("__version__ = '0.3.5'\n", encoding="utf-8")
|
||||
monkeypatch.setattr(sys, "executable", str(executable))
|
||||
monkeypatch.chdir(checkout)
|
||||
with pytest.raises(update.UpdateError, match="different nanobot package"):
|
||||
update._verify_installation("0.3.5", "pypi")
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("PYTHONPATH", raising=False)
|
||||
update._verify_installation("0.3.5", "pypi")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def installed_release(tmp_path, monkeypatch):
|
||||
"""Install a tiny local wheel with real pip, without touching the user's env."""
|
||||
import venv
|
||||
import zipfile
|
||||
|
||||
env = tmp_path / "env"
|
||||
venv.EnvBuilder(with_pip=True).create(env)
|
||||
executable = env / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
|
||||
wheels = tmp_path / "wheels"
|
||||
wheels.mkdir()
|
||||
files = {
|
||||
"nanobot/__init__.py": "__version__ = '0.3.5'\n",
|
||||
"nanobot/web/dist/index.html": "<html>bundled UI</html>",
|
||||
"nanobot_ai-0.3.5.dist-info/METADATA": "Metadata-Version: 2.1\nName: nanobot-ai\nVersion: 0.3.5\n",
|
||||
"nanobot_ai-0.3.5.dist-info/WHEEL": "Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n",
|
||||
}
|
||||
record = "nanobot_ai-0.3.5.dist-info/RECORD"
|
||||
files[record] = "".join(f"{name},,\n" for name in [*files, record])
|
||||
with zipfile.ZipFile(wheels / "nanobot_ai-0.3.5-py3-none-any.whl", "w") as wheel:
|
||||
for name, content in files.items():
|
||||
wheel.writestr(name, content)
|
||||
monkeypatch.setenv("PIP_NO_INDEX", "1")
|
||||
monkeypatch.setenv("PIP_FIND_LINKS", str(wheels))
|
||||
monkeypatch.setenv("PIP_DISABLE_PIP_VERSION_CHECK", "1")
|
||||
monkeypatch.setenv("PIP_CONFIG_FILE", os.devnull)
|
||||
monkeypatch.setenv("PIP_NO_CACHE_DIR", "1")
|
||||
for name in ("PIP_TARGET", "PIP_PREFIX", "PIP_USER"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
monkeypatch.delenv("PYTHONPATH", raising=False)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.setattr(Path, "home", lambda: tmp_path)
|
||||
monkeypatch.setattr(sys, "executable", str(executable))
|
||||
monkeypatch.setattr(sys, "prefix", str(env))
|
||||
get_path = update.sysconfig.get_path
|
||||
monkeypatch.setattr(update.sysconfig, "get_path", lambda name, *args, **kwargs: (
|
||||
str(env / "Scripts") if name == "scripts" else get_path(name, *args, **kwargs)
|
||||
))
|
||||
monkeypatch.setattr(update, "latest_release", lambda: "0.3.5")
|
||||
monkeypatch.setattr(update, "__version__", "0.3.5")
|
||||
monkeypatch.setattr(update, "update_blocked_reason", lambda **kwargs: "")
|
||||
monkeypatch.setattr(update, "_is_editable", lambda: False)
|
||||
update._install(["nanobot-ai==0.3.5"])
|
||||
site = Path(subprocess.check_output([
|
||||
str(executable), "-I", "-c", "import sysconfig; print(sysconfig.get_path('purelib'))",
|
||||
], text=True).strip())
|
||||
return site / "nanobot/web/dist/index.html"
|
||||
|
||||
|
||||
def test_retry_restores_missing_same_version_package_files(installed_release):
|
||||
"""A terminated install can leave valid metadata but incomplete application files."""
|
||||
asset = installed_release
|
||||
asset.unlink()
|
||||
update._mark_installing()
|
||||
|
||||
result = update.update_installation(output=lambda _: None)
|
||||
|
||||
assert asset.read_text() == "<html>bundled UI</html>"
|
||||
assert result["requires_restart"]
|
||||
assert not update.incomplete_update()
|
||||
|
||||
|
||||
def test_old_gateway_cannot_downgrade_a_newer_shared_installation(installed_release, monkeypatch):
|
||||
# Another process has upgraded the shared environment since this gateway started.
|
||||
monkeypatch.setattr(update, "__version__", "0.3.3")
|
||||
monkeypatch.setattr(update, "latest_release", lambda: "0.3.4")
|
||||
install = Mock(wraps=update._install)
|
||||
monkeypatch.setattr(update, "_install", install)
|
||||
with pytest.raises(update.UpdateError, match="allow-downgrade"):
|
||||
update.update_installation(output=lambda _: None)
|
||||
install.assert_not_called()
|
||||
assert installed_release.is_file()
|
||||
assert not update.incomplete_update()
|
||||
|
||||
|
||||
def test_old_gateway_requires_restart_after_external_update(installed_release, monkeypatch):
|
||||
monkeypatch.setattr(update, "__version__", "0.3.4")
|
||||
install = Mock()
|
||||
monkeypatch.setattr(update, "_install", install)
|
||||
result = update.update_installation(output=lambda _: None)
|
||||
assert result["version"] == "0.3.5" and result["requires_restart"]
|
||||
install.assert_not_called()
|
||||
@@ -0,0 +1,204 @@
|
||||
"""Scoped snapshots preserve real data and never silently expand read authority."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from zipfile import ZipFile
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot import update_backup
|
||||
from nanobot.data_access import profile_data_paths
|
||||
from nanobot.update_backup import (
|
||||
BackupSource,
|
||||
ensure_backup,
|
||||
unique_sources,
|
||||
verify_backup,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def scoped_data(tmp_path):
|
||||
home, data, workspace, job = (tmp_path / name for name in ("home", "config data", "user project", "job"))
|
||||
for path in (home, data, workspace, job):
|
||||
path.mkdir()
|
||||
files = {
|
||||
data / "custom.json": '{"credential":"private fixture"}',
|
||||
data / "sessions/workspace/session.jsonl": '{"content":"original conversation"}\n',
|
||||
data / "webui/transcript.jsonl": '{"content":"UI history"}\n',
|
||||
data / "media/image.txt": "fixture attachment",
|
||||
data / "auth/mcp.json": '{"fixture":"secret"}',
|
||||
data / "cli-apps/installed.json": '{"apps":[]}',
|
||||
workspace / "memory/history.jsonl": '{"memory":"original"}\n',
|
||||
workspace / ".nanobot/workspace-id": "namespace",
|
||||
workspace / "cron/jobs.json": '{"jobs":[]}',
|
||||
workspace / "skills/custom/SKILL.md": "user skill",
|
||||
home / "sessions/legacy.jsonl": "legacy conversation",
|
||||
}
|
||||
for path, content in files.items():
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(content.encode())
|
||||
# Paths intentionally excluded: arbitrary project data and installed binaries.
|
||||
for path in (workspace / "src/private.py", data / "bin/cua", data / "logs/runtime.log",
|
||||
data / "cli-apps/venvs/application/binary"):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("not part of this backup")
|
||||
paths = profile_data_paths(home=home, data_dir=data, config=data / "custom.json", workspace=workspace)
|
||||
sources = unique_sources([BackupSource(str(path)) for path in paths])
|
||||
return job, sources, files
|
||||
|
||||
|
||||
def test_complete_private_snapshot_contains_only_owned_stores_and_keeps_original(scoped_data):
|
||||
job, sources, files = scoped_data
|
||||
archive = ensure_backup(job, sources, "a" * 64, mutated=False)
|
||||
with ZipFile(archive) as bundle:
|
||||
manifest = json.loads(bundle.read("manifest.json"))
|
||||
entries = {entry["path"]: entry for entry in manifest["entries"]}
|
||||
assert {path for path, entry in entries.items() if entry["kind"] == "file"} == {str(path) for path in files}
|
||||
for path, content in files.items():
|
||||
entry = entries[str(path)]
|
||||
actual = bundle.read(entry["member"])
|
||||
assert actual == content.encode()
|
||||
assert hashlib.sha256(actual).hexdigest() == entry["sha256"]
|
||||
assert any(item["kind"] == "missing" for item in entries.values())
|
||||
original = archive.read_bytes()
|
||||
next(iter(files)).write_text("changed after installation or migration")
|
||||
with pytest.raises(ValueError, match="before installation"):
|
||||
ensure_backup(job, sources, "a" * 64, mutated=False)
|
||||
assert ensure_backup(job, sources, "a" * 64, mutated=True) == archive
|
||||
assert archive.read_bytes() == original
|
||||
assert verify_backup(job, sources, "a" * 64) == archive
|
||||
if os.name != "nt":
|
||||
assert archive.stat().st_mode & 0o777 == 0o600
|
||||
assert archive.parent.stat().st_mode & 0o777 == 0o700
|
||||
assert (archive.parent / "receipt.json").stat().st_mode & 0o777 == 0o600
|
||||
with pytest.raises(ValueError, match="different update"):
|
||||
verify_backup(job, sources, "b" * 64)
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="Symlink creation requires separate Windows privileges")
|
||||
def test_backup_refuses_external_symlink_and_special_file(scoped_data, tmp_path):
|
||||
job, sources, files = scoped_data
|
||||
memory = next(path.parent for path in files if path.name == "history.jsonl")
|
||||
external = tmp_path / "unrelated-private-file"
|
||||
external.write_text("not authorized by the selected scope")
|
||||
link = memory / "external"
|
||||
link.symlink_to(external)
|
||||
with pytest.raises(ValueError, match="symlink"):
|
||||
ensure_backup(job, sources, "a" * 64, mutated=False)
|
||||
assert not (job / "backup").exists()
|
||||
link.unlink()
|
||||
os.mkfifo(link)
|
||||
with pytest.raises(ValueError, match="special file"):
|
||||
ensure_backup(job, sources, "a" * 64, mutated=False)
|
||||
assert not (job / "backup").exists()
|
||||
|
||||
|
||||
def test_backup_failure_keeps_incomplete_attempt_and_retries_without_false_completion(scoped_data, monkeypatch):
|
||||
job, sources, files = scoped_data
|
||||
original_inventory = update_backup._inventory
|
||||
calls = 0
|
||||
|
||||
def change_during_copy(scope):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls == 2:
|
||||
next(iter(files)).write_text("concurrent writer changed data")
|
||||
return original_inventory(scope)
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(update_backup, "_inventory", change_during_copy)
|
||||
with pytest.raises(ValueError, match="changed during backup"):
|
||||
ensure_backup(job, sources, "a" * 64, mutated=False)
|
||||
assert not (job / "backup").exists()
|
||||
assert len(list(job.glob(".backup-*"))) == 1
|
||||
archive = ensure_backup(job, sources, "a" * 64, mutated=False)
|
||||
assert archive.exists()
|
||||
assert len(list(job.glob(".backup-*"))) == 1 # Do not delete previous recovery material.
|
||||
archive.write_bytes(archive.read_bytes() + b"corruption")
|
||||
with pytest.raises(ValueError, match="missing or changed"):
|
||||
ensure_backup(job, sources, "a" * 64, mutated=True)
|
||||
|
||||
|
||||
def test_no_space_and_missing_original_backup_block_before_snapshot(scoped_data, monkeypatch):
|
||||
job, sources, _ = scoped_data
|
||||
monkeypatch.setattr(update_backup.shutil, "disk_usage", lambda _: SimpleNamespace(free=0))
|
||||
with pytest.raises(ValueError, match="Not enough space"):
|
||||
ensure_backup(job, sources, "a" * 64, mutated=False)
|
||||
assert not list(job.iterdir())
|
||||
with pytest.raises(ValueError, match="already changed data"):
|
||||
ensure_backup(job, sources, "a" * 64, mutated=True)
|
||||
|
||||
|
||||
def test_scheduled_delivery_is_backed_up_and_changes_block_program_rollback(tmp_path):
|
||||
from nanobot.bus.delivery import DeliveryRequest
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.channels.outbox import DeliveryOutbox
|
||||
|
||||
data, job = tmp_path / "data", tmp_path / "job"
|
||||
job.mkdir()
|
||||
outbox = DeliveryOutbox(data / "delivery/outbox.sqlite3")
|
||||
message = OutboundMessage("whatsapp", "chat", "undelivered scheduled result",
|
||||
delivery=DeliveryRequest("run", "whatsapp:chat", None))
|
||||
outbox.record(message)
|
||||
sources = unique_sources([BackupSource(str(path)) for path in profile_data_paths(
|
||||
home=tmp_path / "home", data_dir=data, config=data / "config.json", workspace=tmp_path / "workspace",
|
||||
)])
|
||||
archive = ensure_backup(job, sources, "a" * 64, mutated=False)
|
||||
with ZipFile(archive) as bundle:
|
||||
entry = next(item for item in json.loads(bundle.read("manifest.json"))["entries"]
|
||||
if item["path"] == str(outbox.path))
|
||||
saved = bundle.read(entry["member"])
|
||||
assert saved == outbox.path.read_bytes()
|
||||
copied = tmp_path / "retained-outbox.sqlite3"
|
||||
copied.write_bytes(saved)
|
||||
assert DeliveryOutbox(copied).ready()[0].content == message.content
|
||||
outbox.finish(message, "sent")
|
||||
with pytest.raises(ValueError, match="changed"):
|
||||
verify_backup(job, sources, "a" * 64, unchanged=True)
|
||||
assert outbox.ready() == [] # Never replace the live store with the old backup.
|
||||
|
||||
|
||||
def test_scope_cannot_include_its_own_job(tmp_path):
|
||||
job = tmp_path / "sessions/job"
|
||||
job.mkdir(parents=True)
|
||||
with pytest.raises(ValueError, match="job itself"):
|
||||
ensure_backup(job, (BackupSource(str(tmp_path / "sessions")),), "a" * 64, mutated=False)
|
||||
|
||||
|
||||
async def test_scoped_backup_reopens_sqlite_history_after_runtime_drain(tmp_path):
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
data, workspace, job = (tmp_path / name for name in ("data", "workspace", "job"))
|
||||
job.mkdir()
|
||||
manager = SessionManager(workspace, sessions_root=data / "sessions")
|
||||
session = manager.get_or_create("cli:backup")
|
||||
session.add_message("user", "original conversation")
|
||||
manager.save(session)
|
||||
await manager.state.aclose()
|
||||
|
||||
sources = unique_sources([BackupSource(str(path)) for path in profile_data_paths(
|
||||
home=tmp_path / "home", data_dir=data, config=data / "config.json", workspace=workspace,
|
||||
)])
|
||||
archive = ensure_backup(job, sources, "a" * 64, mutated=False)
|
||||
restored_root = tmp_path / "restored-sessions"
|
||||
# Reopen the real database from the scoped archive, not a JSONL stand-in.
|
||||
with ZipFile(archive) as bundle:
|
||||
manifest = json.loads(bundle.read("manifest.json"))
|
||||
for entry in manifest["entries"]:
|
||||
source = Path(entry["path"])
|
||||
if entry["kind"] != "file" or not source.is_relative_to(data / "sessions"):
|
||||
continue
|
||||
target = restored_root / source.relative_to(data / "sessions")
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(bundle.read(entry["member"]))
|
||||
restored = SessionManager(workspace, sessions_root=restored_root)
|
||||
try:
|
||||
snapshot = restored.read_session_snapshot("cli:backup")
|
||||
assert snapshot is not None
|
||||
assert snapshot.messages[0]["content"] == "original conversation"
|
||||
assert verify_backup(job, sources, "a" * 64, unchanged=True) == archive
|
||||
finally:
|
||||
await restored.state.aclose()
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Subscription persistence and update ownership, without touching user installs."""
|
||||
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.config.home import get_selected_home_path, set_home_path
|
||||
from nanobot.installation_lock import file_access, installation_state_dir, pending_update_path
|
||||
from nanobot.update_channel import (
|
||||
UpdateChannelRequest,
|
||||
read_update_channel,
|
||||
validate_channel_revision,
|
||||
)
|
||||
from nanobot.update_service import UpdateJobService
|
||||
from nanobot.update_worker import JobStatus, Phase
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def environment(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path / "account"))
|
||||
monkeypatch.setattr(sys, "prefix", str(tmp_path / "installation"))
|
||||
return installation_state_dir()
|
||||
|
||||
|
||||
def change(channel, revision):
|
||||
return UpdateJobService().change_channel(UpdateChannelRequest(channel=channel, revision=revision))
|
||||
|
||||
|
||||
def test_channel_is_installation_owned_persistent_and_revision_bound(environment, tmp_path, monkeypatch):
|
||||
assert read_update_channel().channel == "stable"
|
||||
assert not (environment / "channel.json").exists()
|
||||
selected = change("preview", 0)
|
||||
assert (selected.channel, selected.revision) == ("preview", 1)
|
||||
# A second profile/process view retains the subscription, not a browser cache.
|
||||
original_home = get_selected_home_path()
|
||||
try:
|
||||
set_home_path(tmp_path / "another-profile")
|
||||
assert read_update_channel() == selected
|
||||
finally:
|
||||
set_home_path(original_home)
|
||||
assert change("preview", 1) == selected
|
||||
with pytest.raises(ValueError, match="another client"):
|
||||
change("stable", 0)
|
||||
assert change("stable", 1).revision == 2
|
||||
with pytest.raises(ValueError, match="channel changed"):
|
||||
validate_channel_revision(0, sys.prefix) # Stable → Preview → Stable is not the old consent.
|
||||
monkeypatch.setattr(sys, "prefix", str(tmp_path / "other-installation"))
|
||||
assert read_update_channel().revision == 0
|
||||
assert not (environment / "jobs").exists(), "Changing channels must not create an installation job"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lock", ["channel.lock", "preparation-controller.lock"])
|
||||
def test_channel_change_does_not_race_an_active_preparer(environment, lock):
|
||||
with file_access(environment / lock, exclusive=True), pytest.raises(BlockingIOError):
|
||||
change("preview", 0)
|
||||
assert read_update_channel().revision == 0
|
||||
assert change("preview", 0).revision == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("phase,mutation", [(Phase.PREPARING, False), (Phase.CHECKING, False),
|
||||
(Phase.STOPPING, False), (Phase.FAILED, True),
|
||||
(Phase.RESTART_FAILED, True)])
|
||||
def test_active_and_failed_mutation_jobs_require_recovery_before_switch(environment, phase, mutation):
|
||||
identifier = str(uuid4())
|
||||
directory = environment / "jobs" / identifier
|
||||
directory.mkdir(parents=True)
|
||||
JobStatus(identifier, phase, 1, mutation, "Private diagnostic", int(time.time())).save(directory)
|
||||
before = (directory / "status.json").read_bytes()
|
||||
with pytest.raises(ValueError, match="recover"):
|
||||
change("preview", 0)
|
||||
assert read_update_channel().revision == 0
|
||||
assert (directory / "status.json").read_bytes() == before
|
||||
|
||||
|
||||
def test_incomplete_install_and_corrupt_preference_are_not_silently_reset(environment):
|
||||
pending = pending_update_path()
|
||||
pending.parent.mkdir(parents=True)
|
||||
pending.write_text("interrupted")
|
||||
with pytest.raises(ValueError, match="Recover"):
|
||||
change("preview", 0)
|
||||
pending.unlink()
|
||||
(environment / "channel.json").write_text('{"channel":"unknown"}')
|
||||
with pytest.raises(ValueError):
|
||||
read_update_channel()
|
||||
with pytest.raises(ValueError):
|
||||
change("preview", 0)
|
||||
@@ -0,0 +1,119 @@
|
||||
import shlex
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot import update_guidance
|
||||
from nanobot.update_guidance import installation_method, shell_command, update_guide
|
||||
from nanobot.update_manager import ManagerPolicy
|
||||
from nanobot.update_plan import InstallationSnapshot
|
||||
|
||||
|
||||
def installation(tmp_path, owner="venv", **policy):
|
||||
environment = tmp_path / "tools" / "nanobot-ai" if owner == "uv" else tmp_path / "pipx" / "venvs" / "nanobot-ai-work"
|
||||
return InstallationSnapshot(
|
||||
environment=str(environment), python=str(environment / "bin" / "python"),
|
||||
package_path=str(tmp_path / "checkout" / "nanobot" / "__init__.py"),
|
||||
installed_version="0.3.6", running_version="0.3.6", running_package=str(tmp_path / "checkout" / "nanobot" / "__init__.py"),
|
||||
owner=owner, records={}, manager=ManagerPolicy(
|
||||
manager=owner, backend="uv" if owner == "uv" else "pip", extras=["matrix"], source="registry", **policy,
|
||||
) if owner in {"uv", "pipx"} else None,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("owner", ["uv", "pipx"])
|
||||
def test_registry_commands_bind_manager_environment_and_preserve_suffix(tmp_path, monkeypatch, owner):
|
||||
binary = str(tmp_path / "bin" / owner)
|
||||
monkeypatch.setattr(update_guidance.shutil, "which", lambda _: binary)
|
||||
snapshot = installation(tmp_path, owner)
|
||||
guide = update_guide(snapshot, "0.3.7", extras=["matrix"])
|
||||
assert guide.method == owner
|
||||
assert guide.reason == "registry"
|
||||
assert binary in guide.update_command
|
||||
assert Path(snapshot.environment).name in guide.update_command
|
||||
assert ("UV_TOOL_DIR" if owner == "uv" else "PIPX_HOME") in guide.update_command
|
||||
assert guide.inspect_command and "list" in guide.inspect_command
|
||||
assert snapshot.python in guide.verify_command
|
||||
assert "--force" not in guide.update_command and "pip install" not in guide.update_command
|
||||
|
||||
|
||||
@pytest.mark.parametrize("policy", [{"pinned": True}, {"locked": True}, {"version_constraint": "<0.3.7"}])
|
||||
@pytest.mark.parametrize("owner", ["uv", "pipx"])
|
||||
def test_restricted_manager_has_inspection_but_no_update(tmp_path, monkeypatch, owner, policy):
|
||||
monkeypatch.setattr(update_guidance.shutil, "which", lambda name: name)
|
||||
guide = update_guide(installation(tmp_path, owner, **policy), "0.3.7", extras=[])
|
||||
assert guide.reason == "policy" and guide.inspect_command and guide.update_command is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("policy", [{"version_constraint": ">=0.3.4,<0.4"}, {"custom_pip_args": True}])
|
||||
def test_pipx_in_range_target_still_requires_preserving_owner_options(tmp_path, monkeypatch, policy):
|
||||
monkeypatch.setattr(update_guidance.shutil, "which", lambda name: name)
|
||||
guide = update_guide(installation(tmp_path, "pipx", **policy), "0.3.7", extras=[])
|
||||
assert guide.reason == "policy" and guide.update_command is None
|
||||
assert guide.inspect_command and guide.verify_command
|
||||
|
||||
|
||||
@pytest.mark.parametrize("owner", ["uv", "pipx"])
|
||||
def test_preview_fixed_source_and_missing_manager_never_guess_upgrade(tmp_path, monkeypatch, owner):
|
||||
monkeypatch.setattr(update_guidance.shutil, "which", lambda name: name)
|
||||
snapshot = installation(tmp_path, owner)
|
||||
assert update_guide(snapshot, "0.3.7.dev1", extras=[]).reason == "preview"
|
||||
assert update_guide(snapshot, "0.3.7.dev1", extras=[]).update_command is None
|
||||
snapshot = snapshot.model_copy(update={"manager": snapshot.manager.model_copy(update={"source": "artifact"})})
|
||||
assert update_guide(snapshot, "0.3.7", extras=[]).update_command is None
|
||||
monkeypatch.setattr(update_guidance.shutil, "which", lambda _: None)
|
||||
assert update_guide(snapshot, "0.3.7", extras=[]).reason == "manager"
|
||||
|
||||
|
||||
def test_pip_requires_known_extras_and_uses_exact_interpreter(tmp_path):
|
||||
snapshot = installation(tmp_path)
|
||||
assert installation_method(snapshot) == "pip"
|
||||
unknown = update_guide(snapshot, "0.3.7", extras=None)
|
||||
assert unknown.reason == "extras" and unknown.update_command is None
|
||||
assert "importlib.metadata" in unknown.inspect_command
|
||||
assert "-m pip" not in unknown.inspect_command
|
||||
known = update_guide(snapshot, "0.3.7", extras=["matrix"])
|
||||
assert snapshot.python in known.update_command
|
||||
assert "nanobot-ai[matrix]==0.3.7" in known.update_command
|
||||
snapshot.records["nanobot-install.json"] = "a" * 64
|
||||
assert installation_method(snapshot) == "managed"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("owner", ["source", "container", "system"])
|
||||
def test_deployments_do_not_get_guessed_install_or_restart_commands(tmp_path, owner):
|
||||
guide = update_guide(installation(tmp_path, owner), "0.3.7", extras=[])
|
||||
assert guide.reason == owner and guide.update_command is None
|
||||
if owner == "container":
|
||||
assert guide.verify_command is None
|
||||
if owner == "source":
|
||||
assert "status" in guide.inspect_command and str(tmp_path / "checkout") in guide.inspect_command
|
||||
|
||||
|
||||
def test_source_guide_inspects_the_running_checkout_not_a_different_installed_package(tmp_path):
|
||||
snapshot = installation(tmp_path, "source").model_copy(update={"package_path": str(tmp_path / "site-packages" / "nanobot" / "__init__.py")})
|
||||
guide = update_guide(snapshot, "0.3.7", extras=[])
|
||||
assert str(tmp_path / "checkout") in guide.inspect_command
|
||||
assert "site-packages" not in guide.inspect_command
|
||||
|
||||
|
||||
def test_stale_review_and_non_upgrade_cannot_generate_install_commands(tmp_path):
|
||||
snapshot = installation(tmp_path)
|
||||
assert update_guide(snapshot, "0.3.7", extras=[], current=False).update_command is None
|
||||
for target in ["0.3.6", "0.3.5"]:
|
||||
assert update_guide(snapshot, target, extras=[]).update_command is None
|
||||
|
||||
|
||||
def test_updated_files_with_old_running_gateway_only_offer_restart_verification(tmp_path):
|
||||
snapshot = installation(tmp_path).model_copy(update={"installed_version": "0.3.7"})
|
||||
guide = update_guide(snapshot, "0.3.7", extras=[])
|
||||
assert guide.reason == "restart" and guide.verify_command and guide.update_command is None
|
||||
|
||||
|
||||
def test_shell_rendering_quotes_paths_and_restores_powershell_environment():
|
||||
args = ["/a b/$not-expanded/python", "-m", "pip", "show", "nanobot-ai"]
|
||||
environment = ("PIPX_HOME", "/some one's/$directory")
|
||||
assert shlex.split(shell_command(args, windows=False, environment=environment)) == ["env", "PIPX_HOME=/some one's/$directory", *args]
|
||||
command = shell_command(args, windows=True, environment=environment)
|
||||
assert "'/some one''s/$directory'" in command
|
||||
assert "finally { $env:PIPX_HOME = $nanobotPrevious }" in command
|
||||
assert "& '/a b/$not-expanded/python'" in command
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,123 @@
|
||||
"""Receipt fixtures match uv 0.11.16 and pipx 1.7.1/1.17.13 private-manager probes."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.update_manager import read_manager_policy
|
||||
|
||||
|
||||
def read(tmp_path, manager, data):
|
||||
raw = data.encode() if isinstance(data, str) else json.dumps(data).encode()
|
||||
path = tmp_path / ("uv-receipt.toml" if manager == "uv" else "pipx_metadata.json")
|
||||
path.write_bytes(raw)
|
||||
result = read_manager_policy(tmp_path, manager, hashlib.sha256(raw).hexdigest())
|
||||
assert path.read_bytes() == raw, "Inspection must never rewrite the manager's receipt"
|
||||
return result
|
||||
|
||||
|
||||
def pipx_record(**main):
|
||||
return {"pipx_metadata_version": "0.12", "backend": "pip", "main_package": {
|
||||
"package": "nanobot-ai", "package_or_url": "nanobot-ai[webui]>=0.3.4,<0.4", **main,
|
||||
}, "injected_packages": {"fixture-plugin": {
|
||||
"package": "fixture-plugin", "package_or_url": "fixture-plugin==1.0.0",
|
||||
}}}
|
||||
|
||||
|
||||
def test_uv_intent_preserves_extras_constraints_and_injected_packages(tmp_path):
|
||||
policy = read(tmp_path, "uv", '''[tool]
|
||||
requirements = [
|
||||
{ name = "nanobot-ai", extras = ["webui", "image_gen"], specifier = ">=0.3.4,<0.4" },
|
||||
{ name = "fixture-plugin", specifier = "==1.0.0" }
|
||||
]
|
||||
[tool.options]
|
||||
index-url = "https://private-user:fixture-secret@example.invalid/simple"
|
||||
''')
|
||||
assert policy.extras == ["image-gen", "webui"]
|
||||
assert policy.injected_packages == ["fixture-plugin"]
|
||||
assert policy.restriction("0.3.6.dev1") is None
|
||||
assert "constraints" in policy.restriction("0.4.0")
|
||||
assert "fixture-secret" not in policy.model_dump_json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("main,reason", [
|
||||
({"pinned": True}, "pinned"),
|
||||
({"lock_file": {"__type__": "Path", "__Path__": "/private/pylock.toml"}}, "lock file"),
|
||||
({"package_or_url": "nanobot-ai[webui]==0.3.4"}, "constraints"),
|
||||
({"package_or_url": "nanobot-ai[webui] @ git+https://example.invalid/nanobot.git"}, "manual review"),
|
||||
({"package_or_url": "/private/custom-source"}, "manual review"),
|
||||
])
|
||||
def test_pipx_pins_locks_and_nonregistry_sources_are_not_silently_replaced(tmp_path, main, reason):
|
||||
policy = read(tmp_path, "pipx", pipx_record(**main))
|
||||
assert reason in policy.restriction("0.3.5")
|
||||
assert policy.injected_packages == ["fixture-plugin"]
|
||||
|
||||
|
||||
def test_pipx_named_wheel_preserves_extras_without_recording_credential_url(tmp_path):
|
||||
policy = read(tmp_path, "pipx", pipx_record(
|
||||
package_or_url="nanobot-ai[webui] @ https://private:fixture-secret@example.invalid/nanobot.whl",
|
||||
))
|
||||
assert policy.source == "artifact"
|
||||
assert policy.extras == ["webui"]
|
||||
assert policy.restriction("0.3.5") is None
|
||||
assert "fixture-secret" not in policy.model_dump_json()
|
||||
|
||||
|
||||
def test_older_pipx_receipt_keeps_extras_and_pin_without_metadata_migration(tmp_path):
|
||||
record = pipx_record(pinned=True, package_or_url="nanobot-ai[webui] @ file:///private/nanobot.whl")
|
||||
record["pipx_metadata_version"] = "0.5"
|
||||
del record["backend"] # pipx 1.7.1 only had the pip backend.
|
||||
policy = read(tmp_path, "pipx", record)
|
||||
assert policy.backend == "pip"
|
||||
assert policy.extras == ["webui"]
|
||||
assert policy.injected_packages == ["fixture-plugin"]
|
||||
assert "pinned" in policy.restriction("0.3.5")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("main", [
|
||||
{"package_or_url": "nanobot-ai>=0.3.4,<0.4"},
|
||||
{"package_or_url": "nanobot-ai", "pip_args": ["--index-url", "https://user:fixture-secret@example.invalid/simple"]},
|
||||
])
|
||||
def test_pipx_generic_upgrade_cannot_discard_original_install_policy(tmp_path, main):
|
||||
policy = read(tmp_path, "pipx", pipx_record(**main))
|
||||
assert "generic pipx upgrade" in policy.restriction("0.3.5")
|
||||
assert "fixture-secret" not in policy.model_dump_json()
|
||||
|
||||
|
||||
def test_changed_receipt_is_rejected_between_probe_and_read(tmp_path):
|
||||
path = tmp_path / "pipx_metadata.json"
|
||||
raw = json.dumps(pipx_record()).encode()
|
||||
path.write_bytes(raw)
|
||||
path.write_text(json.dumps(pipx_record(pinned=True)))
|
||||
with pytest.raises(ValueError, match="Could not verify"):
|
||||
read_manager_policy(tmp_path, "pipx", hashlib.sha256(raw).hexdigest())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", [
|
||||
{"pipx_metadata_version": "future-version"},
|
||||
{"main_package": {"package": "other-package", "package_or_url": "other-package"}},
|
||||
{"main_package": {"package": "nanobot-ai", "package_or_url": {"token": "fixture-secret"}}},
|
||||
])
|
||||
def test_unconfirmed_receipts_fail_without_leaking_parser_input(tmp_path, change):
|
||||
with pytest.raises(ValueError, match="Could not verify") as failure:
|
||||
read(tmp_path, "pipx", {**pipx_record(), **change})
|
||||
assert "fixture-secret" not in str(failure.value)
|
||||
|
||||
|
||||
def test_uv_unknown_requirement_semantics_require_review(tmp_path):
|
||||
policy = read(tmp_path, "uv", '''[tool]
|
||||
requirements = [{ name = "nanobot-ai", directory = "/private/checkout", editable = true }]
|
||||
''')
|
||||
assert policy.source == "unrecognized"
|
||||
assert "manual review" in policy.restriction("0.3.5")
|
||||
|
||||
|
||||
def test_uv_wheel_url_is_not_misrepresented_as_an_overridable_registry_requirement(tmp_path):
|
||||
# A real uv tool upgrade retains this URL even when a newer wheel is passed.
|
||||
# Refuse before shutdown instead of discovering an offline-cache miss afterwards.
|
||||
policy = read(tmp_path, "uv", '''[tool]
|
||||
requirements = [{ name = "nanobot-ai", url = "https://example.invalid/nanobot_ai-0.3.5-py3-none-any.whl" }]
|
||||
''')
|
||||
assert policy.source == "artifact"
|
||||
assert "bound to a wheel URL" in policy.restriction("0.3.6")
|
||||
@@ -0,0 +1,257 @@
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import typer
|
||||
from packaging.tags import Tag
|
||||
from rich.text import Text
|
||||
from typer.testing import CliRunner
|
||||
|
||||
from nanobot.cli.update import update as update_command
|
||||
from nanobot.installation_lock import InstallationBusyError, installation_access
|
||||
from nanobot.release_feed import ReleaseFeed, ReleaseTarget
|
||||
from nanobot.releases import ReleaseArtifact, release_filenames
|
||||
from nanobot.update_manager import ManagerPolicy
|
||||
from nanobot.update_plan import InstallationSnapshot, UpdatePlan, UpdatePlans, inspect_installation
|
||||
|
||||
|
||||
def installation(version="0.3.4", running=None, **changes):
|
||||
return InstallationSnapshot(
|
||||
environment="/test/venv", python="/test/venv/bin/python", installed_version=version,
|
||||
package_path="/test/venv/lib/nanobot/__init__.py", running_version=running or version,
|
||||
running_package="/test/venv/lib/nanobot/__init__.py", owner="venv", records=changes,
|
||||
)
|
||||
|
||||
|
||||
def target():
|
||||
name = "nanobot_ai-0.3.5-py3-none-win_amd64.whl"
|
||||
return ReleaseTarget(version="0.3.5", source="pypi", url=f"https://files.pythonhosted.org/packages/{name}",
|
||||
artifact=ReleaseArtifact(filename=name, size=123, sha256="a" * 64))
|
||||
|
||||
|
||||
def plan(snapshot=None):
|
||||
return UpdatePlan(id=str(uuid4()), installation=snapshot or installation(), channel="stable",
|
||||
target=target(), created_at=100, expires_at=1000)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("installed,running,action", [
|
||||
("0.3.4", "0.3.4", "upgrade"), ("0.3.5", "0.3.5", "none"),
|
||||
("0.3.5", "0.3.4", "restart"), ("0.3.6.dev1", "0.3.6.dev1", "downgrade"),
|
||||
("0.3.4", "0.3.6.dev1", "downgrade"),
|
||||
])
|
||||
def test_action_reports_actual_installed_and_running_versions(installed, running, action):
|
||||
assert plan(installation(installed, running)).action == action
|
||||
|
||||
|
||||
def test_saved_plan_survives_a_new_store_and_cannot_be_replaced(tmp_path):
|
||||
original = plan()
|
||||
store = UpdatePlans(tmp_path / "plans")
|
||||
store.save(original)
|
||||
assert UpdatePlans(store.directory).load(original.id) == original
|
||||
assert store.save(original) == original
|
||||
changed = original.model_copy(update={"expires_at": 999})
|
||||
with pytest.raises(ValueError, match="cannot be replaced"):
|
||||
store.save(changed)
|
||||
if sys.platform != "win32":
|
||||
assert (store.directory / f"{original.id}.json").stat().st_mode & 0o777 == 0o600
|
||||
|
||||
|
||||
def test_plan_expiry_environment_and_owner_receipt_are_binding():
|
||||
original = plan()
|
||||
original.validate_for(installation(), now=999)
|
||||
with pytest.raises(ValueError, match="expired"):
|
||||
original.validate_for(installation(), now=1000)
|
||||
with pytest.raises(ValueError, match="Installation changed"):
|
||||
original.validate_for(installation("0.3.5"), now=200)
|
||||
with pytest.raises(ValueError, match="Installation changed"):
|
||||
original.validate_for(installation(**{"uv-receipt.toml": "b" * 64}), now=200)
|
||||
other = installation().model_copy(update={"environment": "/other/venv"})
|
||||
with pytest.raises(ValueError, match="Installation changed"):
|
||||
original.validate_for(other, now=200)
|
||||
|
||||
|
||||
def test_plan_id_cannot_escape_private_directory(tmp_path):
|
||||
with pytest.raises(ValueError):
|
||||
UpdatePlans(tmp_path).load("../../config")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_prepare_and_revalidate_cross_the_same_feed_interface_without_installer(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(ReleaseFeed, "_authorize", AsyncMock())
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
requests.append(str(request.url))
|
||||
return httpx.Response(200, json={
|
||||
"info": {"name": "nanobot-ai", "version": "0.3.5", "requires_python": ">=3.11"},
|
||||
"urls": [{"filename": name, "size": 123, "digests": {"sha256": "a" * 64},
|
||||
"url": f"https://files.pythonhosted.org/packages/{name}", "yanked": False}
|
||||
for name in release_filenames("0.3.5") if name.endswith((".whl", ".tar.gz"))],
|
||||
})
|
||||
|
||||
async with ReleaseFeed(tmp_path / "cache", transport=httpx.MockTransport(handler),
|
||||
supported_tags=[Tag("py3", "none", "win_amd64")]) as feed:
|
||||
store = UpdatePlans(tmp_path / "plans")
|
||||
saved = await store.prepare(installation(), "stable", feed, now=100)
|
||||
assert saved.target == target()
|
||||
assert await store.revalidate(saved.id, installation(), feed, now=101) == saved
|
||||
assert requests == ["https://pypi.org/pypi/nanobot-ai/json", "https://pypi.org/pypi/nanobot-ai/0.3.5/json"]
|
||||
|
||||
|
||||
def test_probe_reads_fresh_interpreter_and_owner_receipt(tmp_path, monkeypatch):
|
||||
import venv
|
||||
|
||||
from nanobot import update_plan, update_process
|
||||
|
||||
account = tmp_path / "private account"
|
||||
monkeypatch.setattr(Path, "home", classmethod(lambda cls: account))
|
||||
monkeypatch.setattr(update_process, "_INSPECTION_BOOTSTRAP", (
|
||||
"from pathlib import Path\n"
|
||||
f"Path.home = classmethod(lambda cls: Path({str(account)!r}))\n"
|
||||
) + update_process._INSPECTION_BOOTSTRAP)
|
||||
|
||||
root = tmp_path / "env with spaces"
|
||||
venv.EnvBuilder(with_pip=False).create(root)
|
||||
executable = root / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
|
||||
site = Path(subprocess.check_output([str(executable), "-I", "-c",
|
||||
"import sysconfig; print(sysconfig.get_path('purelib'))"], text=True).strip())
|
||||
(site / "nanobot").mkdir()
|
||||
(site / "nanobot/__init__.py").write_text("__version__='0.3.5'\n")
|
||||
dist = site / "nanobot_ai-0.3.5.dist-info"
|
||||
dist.mkdir()
|
||||
(dist / "METADATA").write_text("Metadata-Version: 2.1\nName: nanobot-ai\nVersion: 0.3.5\n")
|
||||
receipt = {"pipx_metadata_version": "0.12", "main_package": {
|
||||
"package": "nanobot-ai", "package_or_url": "nanobot-ai[webui]", "pinned": False,
|
||||
}}
|
||||
(root / "pipx_metadata.json").write_text(json.dumps(receipt))
|
||||
monkeypatch.setattr(sys, "prefix", str(root))
|
||||
monkeypatch.setattr(sys, "executable", str(executable))
|
||||
monkeypatch.setattr(update_plan.nanobot, "__version__", "0.3.4")
|
||||
monkeypatch.setattr(update_plan.nanobot, "__file__", str(site / "nanobot/__init__.py"))
|
||||
monkeypatch.delenv("RENDER", raising=False)
|
||||
snapshot = inspect_installation()
|
||||
assert snapshot.installed_version == "0.3.5"
|
||||
assert snapshot.running_version == "0.3.4"
|
||||
assert snapshot.owner == ("container" if Path("/.dockerenv").exists() else "pipx")
|
||||
assert snapshot.records["pipx_metadata.json"] == hashlib.sha256((root / "pipx_metadata.json").read_bytes()).hexdigest()
|
||||
if snapshot.owner == "pipx":
|
||||
assert snapshot.manager.extras == ["webui"]
|
||||
before = snapshot.fingerprint
|
||||
receipt["main_package"]["pinned"] = True
|
||||
(root / "pipx_metadata.json").write_text(json.dumps(receipt))
|
||||
assert inspect_installation().fingerprint != before
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("manager", ["uv", "pipx"])
|
||||
async def test_managed_plan_preserves_extras_and_reports_owner_constraints(tmp_path, manager):
|
||||
policy = ManagerPolicy(manager=manager, backend="uv" if manager == "uv" else "pip",
|
||||
source="registry", extras=["webui"], version_constraint="<0.3.5")
|
||||
snapshot = installation().model_copy(update={"owner": manager, "manager": policy})
|
||||
|
||||
class Feed:
|
||||
async def latest(self, channel):
|
||||
assert channel == "stable"
|
||||
return target()
|
||||
|
||||
saved = await UpdatePlans(tmp_path).prepare(snapshot, "stable", Feed(), now=100)
|
||||
assert saved.extras == ["webui"]
|
||||
assert saved.action == "upgrade"
|
||||
assert "constraints" in saved.owner_restriction
|
||||
assert UpdatePlans(tmp_path).load(saved.id) == saved
|
||||
changed = saved.model_dump()
|
||||
changed["extras"] = []
|
||||
with pytest.raises(ValueError, match="recorded extras"):
|
||||
UpdatePlan.model_validate(changed)
|
||||
|
||||
|
||||
def test_cli_plan_is_available_and_never_starts_install(monkeypatch):
|
||||
from nanobot import update, update_plan
|
||||
|
||||
async def preview(channel):
|
||||
assert channel is None # The planner owns the saved installation subscription.
|
||||
return plan()
|
||||
|
||||
monkeypatch.setattr(update_plan, "preview_release_update", preview)
|
||||
monkeypatch.setattr(update, "update_installation", lambda **kwargs: pytest.fail("plan invoked installer"))
|
||||
app = typer.Typer()
|
||||
app.command()(update_command)
|
||||
result = CliRunner().invoke(app, ["--plan"])
|
||||
assert result.exit_code == 0, result.output
|
||||
output = json.loads(result.stdout)
|
||||
assert output["target"]["version"] == "0.3.5"
|
||||
assert output["action"] == "upgrade"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", ["stable", "preview"])
|
||||
def test_cli_channel_inspection_cannot_silently_run_stable_update(monkeypatch, channel):
|
||||
from nanobot import update
|
||||
|
||||
monkeypatch.setattr(update, "update_installation", lambda **kwargs: pytest.fail("unexpected installer"))
|
||||
app = typer.Typer()
|
||||
app.command()(update_command)
|
||||
result = CliRunner().invoke(app, ["--channel", channel])
|
||||
assert result.exit_code != 0
|
||||
assert "requires --plan" in Text.from_ansi(result.output).plain
|
||||
|
||||
|
||||
@pytest.mark.parametrize("retry", [False, True])
|
||||
def test_saved_job_cli_uses_scoped_status_and_explicit_handoff_only(tmp_path, monkeypatch, retry):
|
||||
from nanobot import update, update_jobs
|
||||
from nanobot.update_jobs import UpdateJobView
|
||||
from nanobot.update_worker import Phase
|
||||
|
||||
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
|
||||
monkeypatch.setattr(sys, "prefix", str(tmp_path / "environment"))
|
||||
identifier, confirmation = str(uuid4()), uuid4().hex
|
||||
job = UpdateJobView(id=identifier, installation_id="a" * 64, host="test", previous_version="0.3.4",
|
||||
target_version="0.3.5", channel="stable", recorded_phase=Phase.HANDOFF_FAILED,
|
||||
attempt=0, mutation_started=False, updated_at=100, execution_confirmation_id=confirmation)
|
||||
calls = []
|
||||
|
||||
def saved(plan_id):
|
||||
assert plan_id == identifier
|
||||
return job
|
||||
|
||||
def handoff(directory, previous):
|
||||
assert directory.name == identifier and previous == confirmation
|
||||
with pytest.raises(InstallationBusyError):
|
||||
with installation_access(updating=True):
|
||||
pytest.fail("Recovery controller released its runtime too early")
|
||||
calls.append(identifier)
|
||||
|
||||
monkeypatch.setattr(update_jobs, "read_update_job", saved)
|
||||
monkeypatch.setattr(update_jobs, "retry_handoff", handoff)
|
||||
monkeypatch.setattr(update, "update_installation", lambda **kwargs: pytest.fail("Unexpected legacy installer"))
|
||||
app = typer.Typer()
|
||||
app.command()(update_command)
|
||||
arguments = ["--job", identifier]
|
||||
if retry:
|
||||
arguments += ["--retry-handoff", "--previous-confirmation", confirmation, "--confirm-restart"]
|
||||
result = CliRunner().invoke(app, arguments)
|
||||
assert result.exit_code == 0, result.output
|
||||
assert json.loads(result.stdout) == job.model_dump(mode="json")
|
||||
assert calls == ([identifier] if retry else [])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("arguments", [
|
||||
["--retry-handoff"], ["--job", "id", "--confirm-restart"],
|
||||
["--job", "id", "--retry-handoff", "--confirm-restart"],
|
||||
["--job", "id", "--previous-confirmation", "confirmation"],
|
||||
["--job", "id", "--retry-handoff", "--previous-confirmation", "confirmation"],
|
||||
["--job", "id", "--check"], ["--job", "id", "--dev"], ["--job", "id", "--plan"],
|
||||
["--job", "id", "--channel", "preview"], ["--job", "id", "--allow-downgrade"],
|
||||
])
|
||||
def test_saved_job_cli_rejects_ambiguous_recovery_flags(monkeypatch, arguments):
|
||||
from nanobot.cli import update
|
||||
|
||||
monkeypatch.setattr(update, "_saved_job", lambda *args: pytest.fail("Ambiguous recovery was executed"))
|
||||
app = typer.Typer()
|
||||
app.command()(update_command)
|
||||
assert CliRunner().invoke(app, arguments).exit_code != 0
|
||||
@@ -0,0 +1,503 @@
|
||||
"""Real gateway runtime identities in isolated profile and installation directories."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from contextlib import contextmanager, nullcontext
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.data_access import data_access
|
||||
from nanobot.installation_lock import (
|
||||
InstallationBusyError,
|
||||
installation_access,
|
||||
installation_state_dir,
|
||||
pending_update_path,
|
||||
)
|
||||
from nanobot.release_feed import ReleaseTarget
|
||||
from nanobot.releases import ReleaseArtifact
|
||||
from nanobot.update_plan import InstallationSnapshot, UpdatePlans, describe_plan
|
||||
from nanobot.update_profiles import (
|
||||
inspect_profiles,
|
||||
require_stopped_profiles,
|
||||
verify_restarted_profile,
|
||||
)
|
||||
|
||||
_CHILD = """
|
||||
import os, sys
|
||||
from pathlib import Path
|
||||
from nanobot.config.home import set_home_path
|
||||
from nanobot.gateway.runtime import GatewayInstance, GatewayRuntime
|
||||
from nanobot.installation_lock import installation_access
|
||||
from nanobot.update_profiles import record_gateway_profile
|
||||
|
||||
profile, environment, marker, workspace = map(Path, sys.argv[1:])
|
||||
sys.prefix = str(environment)
|
||||
set_home_path(profile)
|
||||
instance = GatewayInstance.resolve(config_path=profile / 'config.json')
|
||||
runtime = GatewayRuntime(paths=instance.paths)
|
||||
with installation_access(), runtime.foreground_instance(instance.start_options(port=18790)):
|
||||
with record_gateway_profile(instance, runtime, data_dir=profile, workspace=workspace, port=18790):
|
||||
marker.write_text(str(os.getpid()))
|
||||
sys.stdin.read(1)
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def private_home(tmp_path, monkeypatch):
|
||||
root = tmp_path / "private home"
|
||||
root.mkdir()
|
||||
monkeypatch.setenv("HOME", str(root))
|
||||
monkeypatch.setenv("USERPROFILE", str(root))
|
||||
return root
|
||||
|
||||
|
||||
@contextmanager
|
||||
def gateway(profile, environment, *, workspace=None):
|
||||
profile.mkdir(parents=True, exist_ok=True)
|
||||
(profile / "config.json").write_text('{"credential":"must-not-be-in-receipt"}')
|
||||
marker = profile / "started"
|
||||
marker.unlink(missing_ok=True)
|
||||
process = subprocess.Popen([sys.executable, "-c", _CHILD, str(profile), str(environment), str(marker),
|
||||
str(workspace or profile / "user project")],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
try:
|
||||
deadline = time.monotonic() + 8
|
||||
while not marker.exists():
|
||||
if process.poll() is not None:
|
||||
pytest.fail(process.stderr.read())
|
||||
assert time.monotonic() < deadline, "Runtime registration did not start"
|
||||
time.sleep(0.02)
|
||||
yield process
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.stdin.write("x")
|
||||
process.stdin.flush()
|
||||
process.communicate(timeout=10)
|
||||
|
||||
|
||||
def test_inventory_retains_profiles_after_shutdown_and_crash(private_home, tmp_path):
|
||||
environment = tmp_path / "environment"
|
||||
with gateway(tmp_path / "profile one", environment):
|
||||
with gateway(tmp_path / "profile two", environment) as second:
|
||||
observed = inspect_profiles(str(environment))
|
||||
assert len(observed) == 2
|
||||
assert {item.state for item in observed} == {"running"}
|
||||
# Windows venv python.exe is a redirector, not the runtime owner.
|
||||
first_pid = int((tmp_path / "profile one/started").read_text())
|
||||
second_pid = int((tmp_path / "profile two/started").read_text())
|
||||
assert {item.receipt.pid for item in observed} == {first_pid, second_pid}
|
||||
assert {item.receipt.config for item in observed} == {
|
||||
str(tmp_path / "profile one/config.json"), str(tmp_path / "profile two/config.json"),
|
||||
}
|
||||
assert all(item.receipt.launch_mode == "foreground" for item in observed)
|
||||
encoded = "".join(path.read_text() for path in (installation_state_dir(environment) / "profiles").glob("*.json"))
|
||||
assert "must-not-be-in-receipt" not in encoded
|
||||
os.kill(second_pid, signal.SIGTERM if os.name == "nt" else signal.SIGKILL)
|
||||
second.wait(timeout=5)
|
||||
assert sorted(item.state for item in inspect_profiles(str(environment))) == ["running", "stopped"]
|
||||
observed = inspect_profiles(str(environment))
|
||||
assert len(observed) == 2 and all(item.state == "stopped" for item in observed)
|
||||
assert inspect_profiles(str(tmp_path / "another environment")) == []
|
||||
if os.name != "nt":
|
||||
for path in (installation_state_dir(environment) / "profiles").glob("*.json"):
|
||||
assert path.stat().st_mode & 0o777 == 0o600
|
||||
|
||||
|
||||
def test_profile_reused_by_another_installation_is_not_reported_idle(private_home, tmp_path):
|
||||
profile, first_env, other_env = (tmp_path / name for name in ("profile", "first", "other"))
|
||||
with gateway(profile, first_env):
|
||||
assert inspect_profiles(str(first_env))[0].state == "running"
|
||||
reviewed = inspect_profiles(str(first_env))
|
||||
with pytest.raises(ValueError, match="still in use"):
|
||||
require_stopped_profiles(reviewed, str(first_env))
|
||||
require_stopped_profiles(reviewed, str(first_env))
|
||||
with gateway(profile, other_env):
|
||||
assert inspect_profiles(str(first_env))[0].state == "unconfirmed"
|
||||
assert inspect_profiles(str(other_env))[0].state == "running"
|
||||
with pytest.raises(ValueError, match="unconfirmed"):
|
||||
require_stopped_profiles(reviewed, str(first_env))
|
||||
assert inspect_profiles(str(first_env))[0].state == "stopped"
|
||||
with gateway(profile, first_env):
|
||||
with pytest.raises(ValueError, match="profiles changed"):
|
||||
require_stopped_profiles(reviewed, str(first_env))
|
||||
|
||||
|
||||
def test_missing_process_identity_cannot_become_pid_only_confirmation(private_home, tmp_path):
|
||||
environment = tmp_path / "environment"
|
||||
with gateway(tmp_path / "profile", environment):
|
||||
observed = inspect_profiles(str(environment))[0]
|
||||
path = installation_state_dir(environment) / "profiles" / f"{observed.receipt.id}.json"
|
||||
payload = json.loads(path.read_text())
|
||||
payload["process_identity"] = None
|
||||
path.write_text(json.dumps(payload))
|
||||
assert inspect_profiles(str(environment))[0].state == "unconfirmed"
|
||||
payload["environment"] = str(tmp_path / "foreign environment")
|
||||
path.write_text(json.dumps(payload))
|
||||
with pytest.raises(ValueError, match="different installation"):
|
||||
inspect_profiles(str(environment))
|
||||
|
||||
|
||||
def test_older_receipt_keeps_inventory_without_inventing_launch_options(private_home, tmp_path):
|
||||
environment = tmp_path / "environment"
|
||||
with gateway(tmp_path / "profile", environment):
|
||||
observed = inspect_profiles(str(environment))[0]
|
||||
path = installation_state_dir(environment) / "profiles" / f"{observed.receipt.id}.json"
|
||||
payload = json.loads(path.read_text())
|
||||
payload.pop("launch")
|
||||
path.write_text(json.dumps(payload))
|
||||
legacy = inspect_profiles(str(environment))[0]
|
||||
assert legacy.state == "running"
|
||||
assert legacy.receipt.config == observed.receipt.config
|
||||
assert legacy.receipt.launch is None
|
||||
|
||||
|
||||
def test_separate_profile_and_environment_cannot_hide_a_shared_workspace_writer(private_home, tmp_path):
|
||||
first, other = tmp_path / "first environment", tmp_path / "other environment"
|
||||
workspace = tmp_path / "shared user project"
|
||||
with gateway(tmp_path / "profile one", first, workspace=workspace):
|
||||
reviewed = inspect_profiles(str(first))
|
||||
with gateway(tmp_path / "profile two", other, workspace=workspace):
|
||||
# The first profile is stopped and unchanged: its own inventory alone
|
||||
# cannot prove that no other installation writes this workspace.
|
||||
require_stopped_profiles(reviewed, str(first))
|
||||
with pytest.raises(InstallationBusyError, match="data is in use"):
|
||||
with data_access([workspace / "sessions"], updating=True):
|
||||
pytest.fail("Another profile's shared workspace writer was ignored")
|
||||
with data_access([workspace / "sessions"], updating=True):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def startup_profile(private_home, tmp_path, monkeypatch):
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
profile = tmp_path / "startup profile"
|
||||
monkeypatch.setattr("nanobot.config.home._home_path", profile)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", profile / "config.json")
|
||||
config = Config.model_validate({
|
||||
"agents": {"defaults": {"workspace": str(profile / "workspace"),
|
||||
"dream": {"enabled": False}}},
|
||||
"gateway": {"heartbeat": {"enabled": False}},
|
||||
})
|
||||
return profile, config
|
||||
|
||||
|
||||
def test_startup_is_visible_and_protected_before_workspace_writes(startup_profile, monkeypatch):
|
||||
from nanobot.cli import gateway_runtime
|
||||
from nanobot.gateway.runtime import GatewayInstance, GatewayRuntime
|
||||
|
||||
profile, config = startup_profile
|
||||
seen = []
|
||||
|
||||
def fail_initialization(workspace):
|
||||
observed = inspect_profiles(sys.prefix)
|
||||
assert len(observed) == 1 and observed[0].state == "running"
|
||||
assert observed[0].receipt.workspace == str(workspace)
|
||||
assert observed[0].receipt.pid == os.getpid()
|
||||
with pytest.raises(InstallationBusyError, match="installation is in use"):
|
||||
with installation_access(updating=True):
|
||||
pytest.fail("An update entered while gateway initialization was writing")
|
||||
with pytest.raises(InstallationBusyError, match="data is in use"):
|
||||
with data_access([workspace / "sessions"], updating=True):
|
||||
pytest.fail("A different installation could back up live gateway data")
|
||||
seen.append(observed[0].receipt.run_id)
|
||||
raise RuntimeError("workspace initialization failed")
|
||||
|
||||
monkeypatch.setattr(gateway_runtime, "sync_workspace_templates", fail_initialization)
|
||||
# The same public runtime entrypoint can be retried after initialization fails.
|
||||
for _ in range(2):
|
||||
with pytest.raises(RuntimeError, match="workspace initialization failed"):
|
||||
gateway_runtime._run_gateway(config, health_server_enabled=False,
|
||||
webui_static_dist=False)
|
||||
observed = inspect_profiles(sys.prefix)
|
||||
assert len(observed) == 1 and observed[0].state == "stopped"
|
||||
assert not observed[0].receipt.active
|
||||
instance = GatewayInstance.resolve(config_path=profile / "config.json")
|
||||
assert not GatewayRuntime(paths=instance.paths).status().running
|
||||
with installation_access(updating=True):
|
||||
pass
|
||||
assert seen[0] != seen[1]
|
||||
|
||||
|
||||
def test_duplicate_gateway_cannot_initialize_workspace_before_claim(startup_profile, monkeypatch):
|
||||
from nanobot.cli import gateway_runtime
|
||||
from nanobot.gateway.runtime import GatewayAlreadyRunningError
|
||||
|
||||
profile, config = startup_profile
|
||||
monkeypatch.setattr(gateway_runtime, "sync_workspace_templates",
|
||||
lambda _path: pytest.fail("Duplicate startup touched the workspace"))
|
||||
with gateway(profile, sys.prefix):
|
||||
original = inspect_profiles(sys.prefix)
|
||||
with pytest.raises(GatewayAlreadyRunningError):
|
||||
gateway_runtime._run_gateway(config, health_server_enabled=False,
|
||||
webui_static_dist=False)
|
||||
assert inspect_profiles(sys.prefix) == original
|
||||
|
||||
|
||||
@pytest.mark.parametrize("interrupted", [False, True])
|
||||
def test_gateway_entrypoint_refuses_installation_before_initialization(startup_profile, monkeypatch, interrupted):
|
||||
from nanobot.cli import gateway_runtime
|
||||
|
||||
profile, config = startup_profile
|
||||
monkeypatch.setattr(gateway_runtime, "sync_workspace_templates",
|
||||
lambda _path: pytest.fail("Blocked startup touched the workspace"))
|
||||
if interrupted:
|
||||
pending = pending_update_path()
|
||||
pending.parent.mkdir(parents=True, exist_ok=True)
|
||||
pending.write_text("interrupted")
|
||||
with nullcontext() if interrupted else installation_access(updating=True):
|
||||
with pytest.raises(InstallationBusyError):
|
||||
gateway_runtime._run_gateway(config, health_server_enabled=False,
|
||||
webui_static_dist=False)
|
||||
assert inspect_profiles(sys.prefix) == []
|
||||
assert not (profile / "workspace").exists()
|
||||
|
||||
|
||||
def test_gateway_refuses_shared_data_maintenance_before_initializing_writers(startup_profile, monkeypatch):
|
||||
from nanobot.cli import gateway_runtime
|
||||
|
||||
profile, config = startup_profile
|
||||
monkeypatch.setattr(gateway_runtime, "sync_workspace_templates",
|
||||
lambda _path: pytest.fail("Startup wrote to a store under maintenance"))
|
||||
with data_access([config.workspace_path / "sessions"], updating=True):
|
||||
with pytest.raises(InstallationBusyError, match="data is in use"):
|
||||
gateway_runtime._run_gateway(config, health_server_enabled=False, webui_static_dist=False)
|
||||
assert inspect_profiles(sys.prefix) == []
|
||||
assert not (profile / "workspace").exists()
|
||||
|
||||
|
||||
def test_classic_cli_holds_data_lease_before_writers_and_through_exit(startup_profile, monkeypatch):
|
||||
from nanobot.cli import agent as cli_agent
|
||||
|
||||
_, config = startup_profile
|
||||
monkeypatch.setattr(cli_agent, "_load_runtime_config", lambda *_args: config)
|
||||
reached = []
|
||||
|
||||
def run_classic(_config, **_kwargs):
|
||||
with pytest.raises(InstallationBusyError):
|
||||
with data_access([config.workspace_path / "sessions"], updating=True):
|
||||
pytest.fail("Classic CLI did not protect its shared data")
|
||||
reached.append(True)
|
||||
raise RuntimeError("simulated classic runtime exit")
|
||||
|
||||
monkeypatch.setattr(cli_agent, "_run_classic", run_classic)
|
||||
with data_access([config.workspace_path / "sessions"], updating=True):
|
||||
with pytest.raises(InstallationBusyError, match="data is in use"):
|
||||
cli_agent.agent(message="hello", classic=True, theme="auto")
|
||||
assert not reached
|
||||
with pytest.raises(RuntimeError, match="simulated classic runtime exit"):
|
||||
cli_agent.agent(message="hello", classic=True, theme="auto")
|
||||
with data_access([config.workspace_path / "sessions"], updating=True):
|
||||
pass
|
||||
assert reached == [True]
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="Graceful SIGTERM proof uses the POSIX gateway handler")
|
||||
def test_actual_gateway_startup_records_custom_home_and_graceful_exit(private_home, tmp_path):
|
||||
import http.client
|
||||
|
||||
# Run the actual gateway lifecycle with no providers/channels or browser. Only
|
||||
# tokenizer prefetch is disabled so this test cannot download outside localhost.
|
||||
source = """
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from nanobot.config.home import set_home_path
|
||||
from nanobot.config.loader import set_config_path
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.installation_lock import installation_access
|
||||
from nanobot.cli import gateway_runtime
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
original_from_config = AgentLoop.from_config
|
||||
def create_agent(config, bus, **kwargs):
|
||||
assert kwargs['cron_service'].admission is bus.admission
|
||||
return original_from_config(config, bus, **kwargs)
|
||||
AgentLoop.from_config = create_agent
|
||||
profile, port = Path(sys.argv[1]), int(sys.argv[2])
|
||||
set_home_path(profile)
|
||||
set_config_path(profile / 'config data' / 'config.json')
|
||||
config = Config.model_validate({'agents': {'defaults': {'workspace': str(profile / 'workspace'),
|
||||
'dream': {'enabled': False}}}, 'gateway': {'host': '127.0.0.1', 'port': port,
|
||||
'heartbeat': {'enabled': False}}})
|
||||
gateway_runtime.warmup_token_encoding = lambda: None
|
||||
with installation_access():
|
||||
gateway_runtime._run_gateway(config, webui_static_dist=False, unconfigured_provider_error='No provider for lifecycle test')
|
||||
"""
|
||||
with socket.socket() as listener:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
port = listener.getsockname()[1]
|
||||
profile = tmp_path / "actual gateway"
|
||||
profile.mkdir()
|
||||
process = subprocess.Popen([sys.executable, "-c", source, str(profile), str(port)],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
try:
|
||||
deadline = time.monotonic() + 20
|
||||
while True:
|
||||
if process.poll() is not None:
|
||||
pytest.fail(process.stdout.read())
|
||||
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=0.2)
|
||||
try:
|
||||
connection.request("GET", "/health")
|
||||
response = connection.getresponse()
|
||||
if response.status == 200 and json.loads(response.read())["ready"]:
|
||||
break
|
||||
except (OSError, http.client.HTTPException):
|
||||
pass
|
||||
finally:
|
||||
connection.close()
|
||||
assert time.monotonic() < deadline, "Isolated gateway did not become ready"
|
||||
time.sleep(0.05)
|
||||
observed = inspect_profiles(sys.prefix)
|
||||
assert len(observed) == 1 and observed[0].state == "running"
|
||||
assert observed[0].receipt.home == str(profile)
|
||||
assert observed[0].receipt.config == str(profile / "config data/config.json")
|
||||
assert observed[0].receipt.data_dir == str(profile / "config data")
|
||||
assert observed[0].receipt.workspace == str(profile / "workspace")
|
||||
assert observed[0].receipt.pid == process.pid
|
||||
process.send_signal(signal.SIGTERM)
|
||||
output, _ = process.communicate(timeout=15)
|
||||
assert process.returncode == 0, output
|
||||
after = inspect_profiles(sys.prefix)
|
||||
assert after[0].state == "stopped" and not after[0].receipt.active
|
||||
assert after[0].receipt.run_id == observed[0].receipt.run_id
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.communicate(timeout=15)
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="Native Windows graceful lifecycle needs its own execution evidence")
|
||||
@pytest.mark.parametrize("selected_home,explicit_workspace", [(False, False), (True, False), (True, True)])
|
||||
def test_recorded_launch_restarts_same_actual_gateway(private_home, tmp_path, monkeypatch,
|
||||
selected_home, explicit_workspace):
|
||||
from nanobot.config.home import set_home_path
|
||||
from nanobot.gateway.runtime import GatewayInstance, GatewayRuntime
|
||||
|
||||
profile = tmp_path / "gateway home" if selected_home else private_home / ".nanobot"
|
||||
workspace = tmp_path / "中文 user project"
|
||||
config_path = profile / "config data/config.json" if selected_home else profile / "config.json"
|
||||
working_directory = tmp_path / "original working directory"
|
||||
config_path.parent.mkdir(parents=True)
|
||||
working_directory.mkdir()
|
||||
with socket.socket() as listener:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
port = listener.getsockname()[1]
|
||||
config_path.write_text(json.dumps({
|
||||
"agents": {"defaults": {"workspace": str(workspace), "dream": {"enabled": False},
|
||||
"provider": "custom", "model": "lifecycle-fixture"}},
|
||||
"providers": {"custom": {"apiKey": "fixture-not-a-secret", "apiBase": "http://127.0.0.1:1/v1"}},
|
||||
"gateway": {"host": "127.0.0.1", "port": port, "heartbeat": {"enabled": False}},
|
||||
"channels": {"websocket": {"enabled": False}},
|
||||
}))
|
||||
monkeypatch.setattr("nanobot.config.home._home_path", None)
|
||||
if selected_home:
|
||||
set_home_path(profile)
|
||||
instance = GatewayInstance.resolve(config_path=config_path,
|
||||
workspace=str(workspace) if explicit_workspace else None)
|
||||
# Use the actual CLI/runtime from this checkout, even when restarting from a
|
||||
# different cwd. Only tokenizer warmup is disabled (no network download).
|
||||
source_root = str(Path(__file__).resolve().parents[1])
|
||||
bootstrap = (
|
||||
f"import sys; sys.path.insert(0, {source_root!r})\n"
|
||||
"from nanobot.cli import gateway_runtime\n"
|
||||
"gateway_runtime.warmup_token_encoding = lambda: None\n"
|
||||
"from nanobot.cli.entry import main\nmain()\n"
|
||||
)
|
||||
processes = []
|
||||
launch_directory = working_directory
|
||||
|
||||
def launch(command, **kwargs):
|
||||
child = subprocess.Popen([command[0], "-c", bootstrap, *command[3:]],
|
||||
cwd=launch_directory, **kwargs)
|
||||
processes.append(child)
|
||||
return child
|
||||
|
||||
runtime = GatewayRuntime(paths=instance.paths, python_executable=sys.executable, popen=launch)
|
||||
|
||||
def ready_profile():
|
||||
deadline = time.monotonic() + 20
|
||||
while True:
|
||||
assert processes[-1].poll() is None, "\n".join(runtime.read_log_tail(tail=20))
|
||||
observed = inspect_profiles(sys.prefix)
|
||||
if runtime.status().ready and observed and observed[0].state == "running":
|
||||
return observed[0].receipt
|
||||
assert time.monotonic() < deadline, "Isolated gateway did not become ready"
|
||||
time.sleep(0.05)
|
||||
|
||||
try:
|
||||
assert runtime.start_background(instance.start_options(port=port, verbose=True)).ok
|
||||
before = ready_profile()
|
||||
assert before.launch is not None
|
||||
assert before.launch.home == (str(profile) if selected_home else None)
|
||||
assert before.launch.config_path == (str(config_path) if selected_home else None)
|
||||
assert before.launch.workspace == (str(workspace) if explicit_workspace else None)
|
||||
assert before.launch.working_directory == str(working_directory)
|
||||
assert before.launch.verbose
|
||||
assert before.launch_mode == "background" and before.launch.lifetime == "explicit"
|
||||
assert "fixture-not-a-secret" not in before.model_dump_json()
|
||||
with pytest.raises(ValueError, match="reviewed instance"):
|
||||
verify_restarted_profile(before, version=before.version)
|
||||
assert runtime.stop(timeout_s=10).ok
|
||||
assert processes[-1].wait(timeout=10) == 0
|
||||
stopped = inspect_profiles(sys.prefix)[0].receipt
|
||||
assert stopped.launch == before.launch and not stopped.active
|
||||
|
||||
# No --workspace must remain no --workspace, even though config resolves
|
||||
# the same final workspace. Guessing that flag changes the instance key.
|
||||
monkeypatch.chdir(tmp_path)
|
||||
launch_directory = Path(before.launch.working_directory)
|
||||
assert runtime.start_background(before.launch.options(port=before.port)).ok
|
||||
after = ready_profile()
|
||||
assert verify_restarted_profile(before, version=after.version) == after
|
||||
assert not runtime.verify_ready(before.health_identity)
|
||||
with pytest.raises(ValueError, match="target version"):
|
||||
verify_restarted_profile(before, version="999.0.0")
|
||||
assert after.run_id != before.run_id and after.pid != before.pid
|
||||
assert after.launch == before.launch
|
||||
for field in ("id", "environment", "python", "package", "version", "home", "data_dir",
|
||||
"config", "workspace", "state_path", "log_path", "port", "launch_mode"):
|
||||
assert getattr(after, field) == getattr(before, field), field
|
||||
assert runtime.stop(timeout_s=10).ok
|
||||
assert processes[-1].wait(timeout=10) == 0
|
||||
assert inspect_profiles(sys.prefix)[0].state == "stopped"
|
||||
with pytest.raises(ValueError, match="not running"):
|
||||
verify_restarted_profile(before, version=after.version)
|
||||
finally:
|
||||
if runtime.status().running:
|
||||
runtime.stop(timeout_s=10)
|
||||
for process in processes:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait(timeout=10)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_plan_lists_profiles_and_rejects_new_instance_before_confirmation(private_home, tmp_path):
|
||||
environment = tmp_path / "environment"
|
||||
snapshot = InstallationSnapshot(
|
||||
environment=str(environment), python=str(environment / "python"), installed_version="0.3.4",
|
||||
package_path=str(environment / "nanobot/__init__.py"), running_version="0.3.4",
|
||||
running_package=str(environment / "nanobot/__init__.py"), owner="venv", records={},
|
||||
)
|
||||
filename = "nanobot_ai-0.3.5-py3-none-win_amd64.whl"
|
||||
target = ReleaseTarget(version="0.3.5", source="pypi", url=f"https://files.pythonhosted.org/packages/{filename}",
|
||||
artifact=ReleaseArtifact(filename=filename, size=123, sha256="a" * 64))
|
||||
feed = SimpleNamespace(latest=AsyncMock(return_value=target), revalidate=AsyncMock())
|
||||
plans = UpdatePlans(tmp_path / "plans")
|
||||
with gateway(tmp_path / "profile one", environment):
|
||||
plan = await plans.prepare(snapshot, "stable", feed, now=100)
|
||||
assert len(plan.profiles) == 1
|
||||
assert json.loads(describe_plan(plan))["profiles"][0]["state"] == "running"
|
||||
await plans.revalidate(plan.id, snapshot, feed, now=101)
|
||||
feed.revalidate.reset_mock()
|
||||
with gateway(tmp_path / "profile two", environment):
|
||||
with pytest.raises(ValueError, match="Gateway profiles changed"):
|
||||
await plans.revalidate(plan.id, snapshot, feed, now=102)
|
||||
feed.revalidate.assert_not_awaited()
|
||||
@@ -0,0 +1,302 @@
|
||||
"""Protected post-install startup with the actual gateway, isolated data and ports.
|
||||
|
||||
These tests begin at the verified-package handoff, not at a public download or pip
|
||||
upgrade. The subprocess bootstrap selects this checkout's code while reusing the
|
||||
test interpreter's dependencies; no user installation is replaced or restarted.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
import nanobot
|
||||
from nanobot.config.home import get_selected_home_path, set_home_path
|
||||
from nanobot.data_access import DataStartupGrant, data_access, profile_data_paths
|
||||
from nanobot.gateway.runtime import GatewayInstance, GatewayRuntime
|
||||
from nanobot.installation_lock import (
|
||||
InstallationBusyError,
|
||||
installation_access,
|
||||
installation_state_dir,
|
||||
pending_update_path,
|
||||
)
|
||||
from nanobot.release_feed import ReleaseTarget
|
||||
from nanobot.releases import ReleaseArtifact
|
||||
from nanobot.update_backup import BackupSource, unique_sources
|
||||
from nanobot.update_jobs import _worker_archive
|
||||
from nanobot.update_plan import InstallationSnapshot, UpdatePlan
|
||||
from nanobot.update_profiles import inspect_profiles, verify_restarted_profile
|
||||
from nanobot.update_restart import GatewayStartup, run_restarts
|
||||
from nanobot.update_worker import (
|
||||
EnvironmentSnapshot,
|
||||
JobStatus,
|
||||
Phase,
|
||||
StagedWheel,
|
||||
WorkerSpec,
|
||||
write_record,
|
||||
)
|
||||
|
||||
|
||||
def _port():
|
||||
with socket.socket() as listener:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
return listener.getsockname()[1]
|
||||
|
||||
|
||||
def _http(port, path, *, method="GET"):
|
||||
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=0.4)
|
||||
try:
|
||||
connection.request(method, path)
|
||||
response = connection.getresponse()
|
||||
return response.status, response.read()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def _wait(predicate, message, *, timeout=20):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if result := predicate():
|
||||
return result
|
||||
except (OSError, http.client.HTTPException):
|
||||
pass
|
||||
time.sleep(0.05)
|
||||
pytest.fail(message)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def private_home(tmp_path, monkeypatch):
|
||||
root = tmp_path / "private account"
|
||||
root.mkdir()
|
||||
monkeypatch.setenv("HOME", str(root))
|
||||
monkeypatch.setenv("USERPROFILE", str(root))
|
||||
return root
|
||||
|
||||
|
||||
def _job(previous, *, legacy_scope=False):
|
||||
"""Materialize the immutable record supplied by verified package installation."""
|
||||
identifier = str(uuid4())
|
||||
directory = installation_state_dir() / "jobs" / identifier
|
||||
directory.mkdir(parents=True)
|
||||
version = nanobot.__version__
|
||||
filename = f"nanobot_ai-{version}-py3-none-win_amd64.whl"
|
||||
snapshot = InstallationSnapshot(
|
||||
environment=str(Path(sys.prefix).resolve()), python=sys.executable,
|
||||
installed_version=version, running_version=version, package_path=nanobot.__file__,
|
||||
running_package=nanobot.__file__, owner="venv", records={},
|
||||
)
|
||||
profiles = inspect_profiles(sys.prefix)
|
||||
plan = UpdatePlan(
|
||||
id=identifier, installation=snapshot, channel="stable", profiles=profiles,
|
||||
restart_profiles=[previous.id], extras=[], created_at=int(time.time()), expires_at=int(time.time()) + 900,
|
||||
target=ReleaseTarget(version=version, source="pypi", url=f"https://files.pythonhosted.org/packages/{filename}",
|
||||
artifact=ReleaseArtifact(filename=filename, size=1, sha256="0" * 64)),
|
||||
)
|
||||
write_record(directory / "plan.json", plan.model_dump(mode="json"))
|
||||
paths = profile_data_paths(
|
||||
home=Path(previous.home), data_dir=Path(previous.data_dir),
|
||||
config=Path(previous.config), workspace=Path(previous.workspace))
|
||||
if legacy_scope:
|
||||
paths = tuple(path for path in paths if path != Path(previous.data_dir) / "delivery")
|
||||
sources = unique_sources([BackupSource(str(path)) for path in paths])
|
||||
spec = WorkerSpec(
|
||||
identifier, hashlib.sha256((directory / "plan.json").read_bytes()).hexdigest(),
|
||||
_worker_archive(directory / "worker.pyz"),
|
||||
EnvironmentSnapshot(snapshot.environment, sys.executable, sys.executable,
|
||||
"0" * 64, {}, {}, version, {}), version,
|
||||
(StagedWheel(filename, "nanobot-ai", version, 1, "0" * 64),), sources, (previous.id,),
|
||||
)
|
||||
spec.save(directory)
|
||||
JobStatus(identifier, Phase.RESTARTING, 1, True, "Fixture: package verification completed", int(time.time())).save(directory)
|
||||
with data_access((item.path for item in sources), updating=True, job_id=identifier) as data:
|
||||
data.reserve()
|
||||
pending_update_path().parent.mkdir(parents=True, exist_ok=True)
|
||||
write_record(pending_update_path(), {"schema_version": 2, "job_id": identifier, "version": version})
|
||||
return directory, spec
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="Native Windows lifecycle execution requires a Windows runner")
|
||||
@pytest.mark.parametrize("legacy_scope", [False, True])
|
||||
def test_actual_gateway_is_parked_until_exact_runtime_activation(private_home, tmp_path, monkeypatch, legacy_scope):
|
||||
from nanobot import update_restart
|
||||
|
||||
profile = tmp_path / "gateway home"
|
||||
workspace = tmp_path / "中文 workspace"
|
||||
cwd = tmp_path / "original working directory"
|
||||
profile.mkdir()
|
||||
cwd.mkdir()
|
||||
health_port, web_port = _port(), _port()
|
||||
config_path = profile / "config.json"
|
||||
config_path.write_text(json.dumps({
|
||||
"agents": {"defaults": {"workspace": str(workspace), "dream": {"enabled": False},
|
||||
"provider": "custom", "model": "lifecycle-test"}},
|
||||
"providers": {"custom": {"apiKey": "fixture-not-a-secret", "apiBase": "http://127.0.0.1:1/v1"}},
|
||||
"gateway": {"host": "127.0.0.1", "port": health_port, "heartbeat": {"enabled": False}},
|
||||
"channels": {"websocket": {"enabled": True, "host": "127.0.0.1", "port": web_port}},
|
||||
}))
|
||||
source = Path(__file__).resolve().parents[1]
|
||||
marker = tmp_path / "mcp-started"
|
||||
bootstrap = (
|
||||
f"import sys, runpy; sys.path.insert(0, {str(source)!r})\n"
|
||||
"from pathlib import Path\nimport os\n"
|
||||
"from nanobot.cli import gateway_runtime\n"
|
||||
"from nanobot.agent.tools.mcp import MCPProvider\n"
|
||||
"gateway_runtime.warmup_token_encoding = lambda: None\n"
|
||||
"async def observe_connect(self):\n"
|
||||
" assert 'NANOBOT_UPDATE_STARTUP_TOKEN' not in os.environ\n"
|
||||
f" Path({str(marker)!r}).touch()\n"
|
||||
"MCPProvider.connect = observe_connect\n"
|
||||
)
|
||||
original_popen = subprocess.Popen
|
||||
children = []
|
||||
|
||||
def spawn(command, **kwargs):
|
||||
if "--gateway" in command:
|
||||
# Run the same frozen entrypoint with checkout imports selected by
|
||||
# this test, only after protected site initialization. Keep the
|
||||
# production -I -S flags; no application import may bypass them.
|
||||
script = (
|
||||
"import sys, runpy\nsys.argv = sys.argv[1:]\nsys.path.insert(0, sys.argv[0])\n"
|
||||
"from _nanobot_update import update_worker\n"
|
||||
"initialize = update_worker.initialize_runtime\n"
|
||||
"def initialize_fixture(python, environment):\n"
|
||||
" initialize(python, environment)\n"
|
||||
f" exec({bootstrap!r}, {{}})\n"
|
||||
"update_worker.initialize_runtime = initialize_fixture\n"
|
||||
"runpy.run_path(sys.argv[0], run_name='__main__')\n"
|
||||
)
|
||||
assert command[1:3] == ["-I", "-S"]
|
||||
command = [command[0], "-I", "-S", "-c", script, *command[3:]]
|
||||
elif command[1:3] == ["-m", "nanobot"]:
|
||||
script = bootstrap + "from nanobot.cli.entry import main\nmain()\n"
|
||||
command = [command[0], "-c", script, *command[3:]]
|
||||
kwargs["cwd"] = cwd
|
||||
else:
|
||||
return original_popen(command, **kwargs)
|
||||
child = original_popen(command, **kwargs)
|
||||
children.append(child)
|
||||
return child
|
||||
|
||||
selected_home = get_selected_home_path()
|
||||
set_home_path(profile)
|
||||
instance = GatewayInstance.resolve(config_path=config_path)
|
||||
runtime = GatewayRuntime(paths=instance.paths, python_executable=sys.executable, popen=spawn)
|
||||
release = threading.Event()
|
||||
parked = threading.Event()
|
||||
executor = ThreadPoolExecutor(max_workers=1)
|
||||
future = None
|
||||
try:
|
||||
assert runtime.start_background(instance.start_options(port=health_port)).ok
|
||||
_wait(lambda: runtime.status().ready, "Original isolated gateway did not become ready")
|
||||
previous = inspect_profiles(sys.prefix)[0].receipt
|
||||
assert previous.launch.working_directory == str(cwd)
|
||||
assert runtime.stop(timeout_s=10).ok
|
||||
assert children[-1].wait(timeout=10) == 0
|
||||
marker.unlink()
|
||||
directory, spec = _job(previous, legacy_scope=legacy_scope)
|
||||
original_wait = update_restart._wait_verified
|
||||
|
||||
def wait_verified(*args, **kwargs):
|
||||
result = original_wait(*args, **kwargs)
|
||||
if kwargs["maintenance"] is True:
|
||||
parked.set()
|
||||
assert release.wait(15), "Test did not release the inspected parked runtime"
|
||||
return result
|
||||
|
||||
monkeypatch.setattr(update_restart, "_wait_verified", wait_verified)
|
||||
monkeypatch.setattr(update_restart.subprocess, "Popen", spawn)
|
||||
|
||||
def coordinate():
|
||||
with installation_access(allow_incomplete=True):
|
||||
run_restarts(directory)
|
||||
|
||||
future = executor.submit(coordinate)
|
||||
_wait(lambda: parked.is_set() or future.done(), "Restart did not reach protected readiness")
|
||||
if future.done():
|
||||
future.result()
|
||||
assert parked.is_set(), "Coordinator skipped protected readiness"
|
||||
status, body = _http(health_port, "/health")
|
||||
assert status == 200 and json.loads(body)["maintenance"] is True
|
||||
assert not marker.exists(), "MCP started before gateway activation"
|
||||
assert not (Path(previous.data_dir) / "delivery/outbox.sqlite3").exists()
|
||||
assert _http(web_port, "/webui/bootstrap")[0] == 503
|
||||
assert _http(web_port, "/api/uploads", method="POST")[0] == 503
|
||||
assert JobStatus.read(directory).phase == Phase.RESTARTING
|
||||
with pytest.raises(InstallationBusyError):
|
||||
with installation_access():
|
||||
pytest.fail("Ordinary installation startup bypassed the pending handoff")
|
||||
with pytest.raises(InstallationBusyError):
|
||||
with data_access([workspace / "sessions"]):
|
||||
pytest.fail("Ordinary data access bypassed the pending handoff")
|
||||
release.set()
|
||||
future.result(timeout=25)
|
||||
assert JobStatus.read(directory).phase == Phase.SUCCEEDED
|
||||
assert not pending_update_path().exists()
|
||||
current = verify_restarted_profile(previous, version=spec.version, job_id=spec.plan_id, maintenance=False)
|
||||
assert current.run_id != previous.run_id
|
||||
_wait(marker.exists, "MCP did not start after activation")
|
||||
assert _http(web_port, "/webui/bootstrap")[0] == 200
|
||||
with installation_access(), data_access([workspace / "sessions"]):
|
||||
pass
|
||||
# Recover the real crash window after data cleanup but before unlinking
|
||||
# the installation fence. Do not start another process or reinstall.
|
||||
JobStatus(spec.plan_id, Phase.FINALIZING, 1, True, "Verified; cleanup interrupted", int(time.time())).save(directory)
|
||||
write_record(pending_update_path(), {"schema_version": 2, "job_id": spec.plan_id, "version": spec.version})
|
||||
run_restarts(directory)
|
||||
assert JobStatus.read(directory).phase == Phase.SUCCEEDED
|
||||
assert not pending_update_path().exists()
|
||||
assert runtime.stop(timeout_s=10).ok
|
||||
assert children[-1].wait(timeout=10) == 0
|
||||
run_restarts(directory)
|
||||
assert len(children) == 2, "Completed job restarted a gateway the user had stopped"
|
||||
finally:
|
||||
release.set()
|
||||
if future is not None:
|
||||
try:
|
||||
future.result(timeout=130)
|
||||
except Exception:
|
||||
pass
|
||||
executor.shutdown(wait=True)
|
||||
if runtime.status().running:
|
||||
runtime.stop(timeout_s=10)
|
||||
for child in children:
|
||||
if child.poll() is None:
|
||||
child.terminate()
|
||||
child.wait(timeout=10)
|
||||
set_home_path(selected_home)
|
||||
|
||||
|
||||
async def test_activation_is_bound_to_new_run_not_just_profile(tmp_path):
|
||||
from types import SimpleNamespace
|
||||
|
||||
identifier, participant = str(uuid4()), "a" * 64
|
||||
directory = tmp_path / identifier
|
||||
directory.mkdir()
|
||||
startup = GatewayStartup(directory, SimpleNamespace(id=participant), DataStartupGrant(identifier, participant, "b" * 64))
|
||||
from nanobot.gateway.runtime import GatewayHealthIdentity
|
||||
|
||||
identity = GatewayHealthIdentity(participant, "c" * 32, "0.3.5")
|
||||
JobStatus(identifier, Phase.ACTIVATING, 1, True, "test activation", int(time.time())).save(directory)
|
||||
write_record(directory / "activation.json", {"plan_id": identifier, participant: {**asdict(identity), "run_id": "d" * 32}})
|
||||
waiting = asyncio.create_task(startup.wait_for_activation(identity))
|
||||
try:
|
||||
await asyncio.sleep(0.15)
|
||||
assert not waiting.done()
|
||||
write_record(directory / "activation.json", {"plan_id": identifier, participant: asdict(identity)})
|
||||
await asyncio.wait_for(waiting, timeout=1)
|
||||
finally:
|
||||
waiting.cancel()
|
||||
await asyncio.gather(waiting, return_exceptions=True)
|
||||
@@ -0,0 +1,614 @@
|
||||
"""Cooperative shutdown protocol tests; no installer or real account is touched."""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from contextlib import ExitStack
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
from zipfile import ZipFile
|
||||
|
||||
import pytest
|
||||
|
||||
import nanobot
|
||||
from nanobot.config.home import get_selected_home_path, set_home_path
|
||||
from nanobot.data_access import data_access, profile_data_paths
|
||||
from nanobot.gateway.runtime import GatewayInstance, GatewayRuntime
|
||||
from nanobot.installation_lock import file_access, installation_access, installation_state_dir
|
||||
from nanobot.release_feed import ReleaseTarget
|
||||
from nanobot.releases import ReleaseArtifact
|
||||
from nanobot.runtime_admission import RuntimeAdmission
|
||||
from nanobot.update_backup import BackupSource
|
||||
from nanobot.update_jobs import _worker_archive
|
||||
from nanobot.update_plan import InstallationSnapshot, UpdatePlan
|
||||
from nanobot.update_profiles import ObservedProfile, ProfileLaunch, ProfileReceipt, inspect_profiles
|
||||
from nanobot.update_stop import (
|
||||
settle_uncommitted_handoff,
|
||||
stop_reviewed_gateways,
|
||||
watch_gateway_stop,
|
||||
)
|
||||
from nanobot.update_worker import (
|
||||
EnvironmentSnapshot,
|
||||
JobStatus,
|
||||
Phase,
|
||||
StagedWheel,
|
||||
WorkerSpec,
|
||||
read_record,
|
||||
write_record,
|
||||
)
|
||||
|
||||
|
||||
def prepared_job(profiles, *, stop=None):
|
||||
"""Synthetic wheel metadata: not an actual nanobot installation fixture."""
|
||||
identifier = str(uuid4())
|
||||
directory = installation_state_dir() / "jobs" / identifier
|
||||
directory.mkdir(parents=True)
|
||||
snapshot = InstallationSnapshot(
|
||||
environment=str(Path(sys.prefix).resolve()), python=sys.executable,
|
||||
installed_version=nanobot.__version__, running_version=nanobot.__version__,
|
||||
package_path=nanobot.__file__, running_package=nanobot.__file__, owner="venv", records={},
|
||||
)
|
||||
version = "99.0.0"
|
||||
filename = f"nanobot_ai-{version}-py3-none-win_amd64.whl"
|
||||
wheels = directory / "wheels"
|
||||
wheels.mkdir()
|
||||
wheel = wheels / filename
|
||||
with ZipFile(wheel, "w") as archive:
|
||||
archive.writestr(f"nanobot_ai-{version}.dist-info/METADATA",
|
||||
f"Metadata-Version: 2.1\nName: nanobot-ai\nVersion: {version}\n")
|
||||
size, checksum = wheel.stat().st_size, hashlib.sha256(wheel.read_bytes()).hexdigest()
|
||||
plan = UpdatePlan(
|
||||
id=identifier, installation=snapshot, channel="stable", profiles=profiles,
|
||||
stop_profiles=[item.receipt.id for item in profiles] if stop is None else stop,
|
||||
extras=[], created_at=int(time.time()), expires_at=int(time.time()) + 900,
|
||||
target=ReleaseTarget(version=version, source="pypi", url=f"https://files.pythonhosted.org/packages/{filename}",
|
||||
artifact=ReleaseArtifact(filename=filename, size=size, sha256=checksum)),
|
||||
)
|
||||
write_record(directory / "plan.json", plan.model_dump(mode="json"))
|
||||
spec = WorkerSpec(
|
||||
identifier, hashlib.sha256((directory / "plan.json").read_bytes()).hexdigest(),
|
||||
_worker_archive(directory / "worker.pyz"),
|
||||
EnvironmentSnapshot(snapshot.environment, sys.executable, sys.executable,
|
||||
"0" * 64, {}, {}, nanobot.__version__, {}), version,
|
||||
(StagedWheel(filename, "nanobot-ai", version, size, checksum),),
|
||||
(BackupSource(str(directory / "fixture-data")),),
|
||||
)
|
||||
spec.save(directory)
|
||||
JobStatus(identifier, Phase.READY, 0, False, "Fixture: staged, not installed", int(time.time())).save(directory)
|
||||
return directory, plan
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def private_home(tmp_path, monkeypatch):
|
||||
root = tmp_path / "private account"
|
||||
root.mkdir()
|
||||
monkeypatch.setenv("HOME", str(root))
|
||||
monkeypatch.setenv("USERPROFILE", str(root))
|
||||
return root
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def protocol(private_home, monkeypatch):
|
||||
from nanobot import update_stop
|
||||
|
||||
profiles = []
|
||||
for number in range(2):
|
||||
root = private_home / f"gateway-{number}"
|
||||
receipt = ProfileReceipt(
|
||||
id=hashlib.sha256(str(root).encode()).hexdigest(), run_id=uuid4().hex,
|
||||
environment=str(Path(sys.prefix).resolve()), python=sys.executable,
|
||||
package=nanobot.__file__, version=nanobot.__version__, home=str(root), data_dir=str(root),
|
||||
config=str(root / "config.json"), workspace=str(root / "workspace"),
|
||||
state_path=str(root / "runtime.json"), log_path=str(root / "runtime.log"), port=18790 + number,
|
||||
launch_mode="background", pid=os.getpid() + 10000 + number, process_identity=f"fixture-{number}",
|
||||
active=True, stop_protocol=1,
|
||||
launch=ProfileLaunch(home=str(root), config_path=None, workspace=None,
|
||||
working_directory=str(root), verbose=False, lifetime="explicit"),
|
||||
)
|
||||
profiles.append(ObservedProfile(receipt=receipt, state="running"))
|
||||
directory, plan = prepared_job(profiles)
|
||||
gates = [RuntimeAdmission(), RuntimeAdmission()]
|
||||
stops = [asyncio.Event(), asyncio.Event()]
|
||||
# This test exercises mailbox/admission races with controlled process state;
|
||||
# a separate subprocess test checks actual gateway exit and lease release.
|
||||
monkeypatch.setattr(update_stop, "validate_profiles", lambda expected, environment: None)
|
||||
|
||||
def stopped(expected, environment):
|
||||
if not all(event.is_set() for event in stops):
|
||||
raise ValueError("still running")
|
||||
|
||||
monkeypatch.setattr(update_stop, "require_stopped_profiles", stopped)
|
||||
monkeypatch.setattr(update_stop.GatewayRuntime, "process_is_running", lambda self, pid: False)
|
||||
return directory, plan, gates, stops
|
||||
|
||||
|
||||
async def wait_until(predicate, *, timeout=5):
|
||||
async with asyncio.timeout(timeout):
|
||||
while not predicate():
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", [ValueError("Invalid release approval"), TimeoutError("Trust service unavailable")])
|
||||
async def test_handoff_rejects_approval_before_requesting_gateway_shutdown(protocol, monkeypatch, failure):
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from nanobot import update_handoff
|
||||
|
||||
directory, _, _, stops = protocol
|
||||
state = JobStatus.read(directory)
|
||||
state.advance(directory, Phase.CHECKING, "Checking approval", mutation_started=False)
|
||||
# Environment inspection is covered by the real installed-process tests;
|
||||
# exercise the actual handoff ordering and durable status here.
|
||||
monkeypatch.setattr(update_handoff, "current_environment", lambda **_: None)
|
||||
monkeypatch.setattr(update_handoff, "check_environment", lambda *_, **__: None)
|
||||
monkeypatch.setattr(update_handoff.ReleaseFeed, "revalidate", AsyncMock(side_effect=failure))
|
||||
stop = AsyncMock()
|
||||
monkeypatch.setattr(update_handoff, "stop_reviewed_gateways", stop)
|
||||
with pytest.raises(type(failure), match=str(failure)):
|
||||
await update_handoff._prepare(directory)
|
||||
stop.assert_not_called()
|
||||
assert not any(event.is_set() for event in stops)
|
||||
state = JobStatus.read(directory)
|
||||
assert state.phase == Phase.HANDOFF_FAILED and not state.mutation_started
|
||||
assert "shutdown was not requested" in state.message
|
||||
assert not (directory / "handoff-approval.json").exists()
|
||||
|
||||
|
||||
async def test_handoff_rejects_observed_catalogue_rollback_before_gateway_shutdown(protocol, monkeypatch):
|
||||
from dataclasses import replace
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import httpx
|
||||
from packaging.tags import Tag
|
||||
|
||||
from nanobot import update_handoff
|
||||
from nanobot.release_feed import CATALOGUE_URL, ReleaseFeed, ReleaseFeedError
|
||||
from nanobot.releases import (
|
||||
ReleaseCatalogue,
|
||||
ReleaseManifest,
|
||||
ReleasePointer,
|
||||
release_filenames,
|
||||
)
|
||||
|
||||
directory, plan, _, _ = protocol
|
||||
artifact = plan.target.artifact
|
||||
manifest = ReleaseManifest(
|
||||
version=plan.target.version, source_commit="a" * 40, candidate_commit="b" * 40,
|
||||
requires_python=">=3.11", artifacts=[
|
||||
artifact if name == artifact.filename else ReleaseArtifact(filename=name, size=1, sha256="c" * 64)
|
||||
for name in sorted(release_filenames(plan.target.version))
|
||||
],
|
||||
)
|
||||
payload = manifest.model_dump_json().encode()
|
||||
pointer = ReleasePointer(version=manifest.version, candidate_commit=manifest.candidate_commit,
|
||||
manifest_sha256=hashlib.sha256(payload).hexdigest())
|
||||
original = ReleaseCatalogue(generation=1, stable=pointer)
|
||||
observed = original.model_copy(update={"generation": 2, "withdrawn": {manifest.version: "Startup regression"}})
|
||||
selected = original
|
||||
|
||||
def respond(request):
|
||||
if str(request.url) == CATALOGUE_URL:
|
||||
return httpx.Response(200, content=selected.model_dump_json())
|
||||
if str(request.url) == pointer.manifest_url:
|
||||
return httpx.Response(200, content=payload)
|
||||
assert request.url.path == f"/pypi/nanobot-ai/{manifest.version}/json"
|
||||
return httpx.Response(200, json={
|
||||
"info": {"name": "nanobot-ai", "version": manifest.version, "requires_python": ">=3.11"},
|
||||
"urls": [{"filename": item.filename, "size": item.size, "yanked": False,
|
||||
"url": f"https://files.pythonhosted.org/packages/{item.filename}",
|
||||
"digests": {"sha256": item.sha256}}
|
||||
for item in manifest.artifacts if item.filename.endswith((".whl", ".tar.gz"))],
|
||||
})
|
||||
|
||||
class CachedFeed(ReleaseFeed):
|
||||
def __init__(self, cache_dir):
|
||||
super().__init__(cache_dir, transport=httpx.MockTransport(respond),
|
||||
supported_tags=[Tag("py3", "none", "win_amd64")])
|
||||
|
||||
# Publication authority is independent of catalogue freshness. These fixture
|
||||
# bytes stand for a previously approved release that has since been withdrawn.
|
||||
monkeypatch.setattr(ReleaseFeed, "_authorize", AsyncMock())
|
||||
root = installation_state_dir(plan.installation.environment)
|
||||
spec = WorkerSpec.read(directory)
|
||||
async with CachedFeed(root / "releases") as feed:
|
||||
target = await feed.latest("preview")
|
||||
plan = plan.model_copy(update={"channel": "preview", "target": target})
|
||||
write_record(directory / "plan.json", plan.model_dump(mode="json"))
|
||||
selected = observed
|
||||
assert await feed.catalogue() == observed
|
||||
replace(spec, plan_sha256=hashlib.sha256((directory / "plan.json").read_bytes()).hexdigest()).save(directory)
|
||||
JobStatus.read(directory).advance(directory, Phase.CHECKING, "Checking the exact release", mutation_started=False)
|
||||
monkeypatch.setattr(update_handoff, "current_environment", lambda **_: spec.baseline)
|
||||
monkeypatch.setattr(update_handoff, "ReleaseFeed", CachedFeed)
|
||||
stop = AsyncMock()
|
||||
monkeypatch.setattr(update_handoff, "stop_reviewed_gateways", stop)
|
||||
selected = original
|
||||
with pytest.raises(ReleaseFeedError, match="generation"):
|
||||
await update_handoff._prepare(directory)
|
||||
stop.assert_not_called()
|
||||
state = JobStatus.read(directory)
|
||||
assert state.phase == Phase.HANDOFF_FAILED and not state.mutation_started
|
||||
assert "shutdown was not requested" in state.message
|
||||
|
||||
|
||||
@pytest.mark.parametrize("phase", [Phase.READY, Phase.HANDOFF_FAILED])
|
||||
def test_expired_uncommitted_handoff_can_be_settled_while_gateway_remains_running(protocol, monkeypatch, phase):
|
||||
directory, plan, _, stops = protocol
|
||||
monkeypatch.setattr(time, "time", lambda: plan.expires_at + 1)
|
||||
JobStatus(plan.id, phase, 0, False, "No installation", plan.created_at).save(directory)
|
||||
original = {path.name: path.read_bytes() for path in directory.iterdir() if path.is_file() and path.name != "status.json"}
|
||||
with installation_access():
|
||||
result = settle_uncommitted_handoff(directory)
|
||||
assert result.phase == Phase.CANCELLED and not result.mutation_started
|
||||
assert settle_uncommitted_handoff(directory) == result
|
||||
assert not any(event.is_set() for event in stops)
|
||||
assert original == {path.name: path.read_bytes() for path in directory.iterdir() if path.is_file() and path.name != "status.json"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lock", ["worker.lock", "handoff-child.lock", "stop.lock"])
|
||||
def test_settlement_refuses_live_handoff_owners_without_changing_saved_state(protocol, lock):
|
||||
directory, plan, _, _ = protocol
|
||||
before = (directory / "status.json").read_bytes()
|
||||
with file_access(installation_state_dir(plan.installation.environment) / lock, exclusive=True):
|
||||
with pytest.raises(BlockingIOError):
|
||||
settle_uncommitted_handoff(directory)
|
||||
assert (directory / "status.json").read_bytes() == before
|
||||
|
||||
|
||||
@pytest.mark.parametrize("boundary", ["commit", "stopped", "approval", "mutation"])
|
||||
def test_settlement_never_undoes_shutdown_or_installation_authority(protocol, boundary):
|
||||
directory, plan, _, _ = protocol
|
||||
JobStatus(plan.id, Phase.HANDOFF_FAILED, 0, boundary == "mutation", "Saved failure", plan.created_at).save(directory)
|
||||
if boundary in {"commit", "stopped"}:
|
||||
write_record(installation_state_dir() / "stop.json", {
|
||||
"plan_id": plan.id, "attempt": uuid4().hex, "phase": boundary, "deadline": time.monotonic() + 10,
|
||||
})
|
||||
elif boundary == "approval":
|
||||
write_record(directory / "approval.json", {"plan_id": plan.id})
|
||||
before = (directory / "status.json").read_bytes()
|
||||
with pytest.raises(ValueError):
|
||||
settle_uncommitted_handoff(directory)
|
||||
assert (directory / "status.json").read_bytes() == before
|
||||
|
||||
|
||||
async def test_all_selected_runs_hold_admission_through_committed_shutdown(protocol):
|
||||
directory, plan, gates, stops = protocol
|
||||
outer = [ExitStack(), ExitStack()]
|
||||
watchers = [asyncio.create_task(watch_gateway_stop(item.receipt, lambda gate=gate: gate.pause_if_idle(lambda: False),
|
||||
stop, stack))
|
||||
for item, gate, stop, stack in zip(plan.profiles, gates, stops, outer)]
|
||||
try:
|
||||
await stop_reviewed_gateways(directory)
|
||||
assert all(stop.is_set() for stop in stops)
|
||||
for watcher in watchers:
|
||||
watcher.cancel()
|
||||
await asyncio.gather(*watchers, return_exceptions=True)
|
||||
assert all(gate.paused for gate in gates), "Watcher cancellation reopened committed intake"
|
||||
assert read_record(installation_state_dir() / "stop.json")["phase"] == "stopped"
|
||||
assert JobStatus.read(directory).phase == Phase.READY
|
||||
assert not (directory / "approval.json").exists()
|
||||
# Retrying completed handoff is a read/exit check, not a fresh stop.
|
||||
await stop_reviewed_gateways(directory)
|
||||
finally:
|
||||
for watcher in watchers:
|
||||
watcher.cancel()
|
||||
await asyncio.gather(*watchers, return_exceptions=True)
|
||||
for stack in outer:
|
||||
stack.close()
|
||||
assert not any(gate.paused for gate in gates)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reason", ["busy", "cancel", "timeout"])
|
||||
async def test_precommit_failure_releases_every_hold_without_shutdown(protocol, reason, expire_stop_deadline):
|
||||
directory, plan, gates, stops = protocol
|
||||
outer = [ExitStack(), ExitStack()]
|
||||
holds = ExitStack()
|
||||
if reason == "busy":
|
||||
holds.enter_context(gates[1].activity())
|
||||
watchers = [asyncio.create_task(watch_gateway_stop(plan.profiles[0].receipt,
|
||||
lambda: gates[0].pause_if_idle(lambda: False), stops[0], outer[0]))]
|
||||
if reason == "busy":
|
||||
watchers.append(asyncio.create_task(watch_gateway_stop(plan.profiles[1].receipt,
|
||||
lambda: gates[1].pause_if_idle(lambda: False), stops[1], outer[1])))
|
||||
operation = asyncio.create_task(stop_reviewed_gateways(directory))
|
||||
try:
|
||||
if reason == "cancel":
|
||||
await wait_until(lambda: gates[0].paused)
|
||||
operation.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await operation
|
||||
else:
|
||||
if reason == "timeout":
|
||||
# Expire only after a participant actually holds admission, so
|
||||
# this proves release rather than racing slow filesystem I/O.
|
||||
await wait_until(lambda: gates[0].paused)
|
||||
expire_stop_deadline()
|
||||
with pytest.raises(ValueError if reason == "busy" else TimeoutError,
|
||||
match="busy or refused" if reason == "busy" else "did not prepare"):
|
||||
await asyncio.wait_for(operation, timeout=30)
|
||||
await wait_until(lambda: not any(gate.paused for gate in gates))
|
||||
assert not any(stop.is_set() for stop in stops)
|
||||
assert read_record(installation_state_dir() / "stop.json")["phase"] == "abort"
|
||||
with gates[0].activity():
|
||||
pass
|
||||
holds.close()
|
||||
if reason != "busy":
|
||||
watchers.append(asyncio.create_task(watch_gateway_stop(plan.profiles[1].receipt,
|
||||
lambda: gates[1].pause_if_idle(lambda: False), stops[1], outer[1])))
|
||||
await asyncio.wait_for(stop_reviewed_gateways(directory), timeout=30)
|
||||
assert all(stop.is_set() for stop in stops), "A refused attempt prevented a later explicit retry"
|
||||
finally:
|
||||
operation.cancel()
|
||||
await asyncio.gather(operation, return_exceptions=True)
|
||||
for watcher in watchers:
|
||||
watcher.cancel()
|
||||
await asyncio.gather(*watchers, return_exceptions=True)
|
||||
for stack in outer:
|
||||
stack.close()
|
||||
holds.close()
|
||||
|
||||
|
||||
async def test_abandoned_prepare_releases_intake_when_coordinator_lease_disappears(protocol):
|
||||
directory, plan, gates, stops = protocol
|
||||
gate = ExitStack()
|
||||
watcher = asyncio.create_task(watch_gateway_stop(plan.profiles[0].receipt,
|
||||
lambda: gates[0].pause_if_idle(lambda: False), stops[0], gate))
|
||||
try:
|
||||
with file_access(installation_state_dir() / "stop.lock", exclusive=True):
|
||||
write_record(installation_state_dir() / "stop.json", {
|
||||
"plan_id": plan.id, "attempt": uuid4().hex, "phase": "prepare",
|
||||
"deadline": time.monotonic() + 30,
|
||||
})
|
||||
await wait_until(lambda: gates[0].paused)
|
||||
await wait_until(lambda: not gates[0].paused)
|
||||
assert not stops[0].is_set()
|
||||
finally:
|
||||
watcher.cancel()
|
||||
await asyncio.gather(watcher, return_exceptions=True)
|
||||
gate.close()
|
||||
|
||||
|
||||
async def test_changed_run_cannot_accept_old_stop_selection(protocol):
|
||||
directory, plan, gates, stops = protocol
|
||||
different = plan.profiles[0].receipt.model_copy(update={"run_id": uuid4().hex})
|
||||
outer = ExitStack()
|
||||
watcher = asyncio.create_task(watch_gateway_stop(different, lambda: gates[0].pause_if_idle(lambda: False),
|
||||
stops[0], outer))
|
||||
try:
|
||||
with pytest.raises(ValueError, match="run changed"):
|
||||
await stop_reviewed_gateways(directory)
|
||||
assert not stops[0].is_set() and not gates[0].paused
|
||||
finally:
|
||||
watcher.cancel()
|
||||
await asyncio.gather(watcher, return_exceptions=True)
|
||||
outer.close()
|
||||
|
||||
|
||||
async def test_unselected_running_gateway_refuses_before_sending_requests(protocol):
|
||||
_, plan, _, stops = protocol
|
||||
directory, _ = prepared_job(plan.profiles, stop=[plan.profiles[0].receipt.id])
|
||||
with pytest.raises(ValueError, match="Every running gateway"):
|
||||
await stop_reviewed_gateways(directory)
|
||||
assert not (installation_state_dir() / "stop.json").exists()
|
||||
assert not any(stop.is_set() for stop in stops)
|
||||
|
||||
|
||||
async def test_changed_staging_refuses_before_closing_task_intake(protocol):
|
||||
directory, plan, gates, stops = protocol
|
||||
(directory / "wheels" / plan.target.artifact.filename).write_bytes(b"interrupted download")
|
||||
with pytest.raises(ValueError, match="Staged wheel"):
|
||||
await stop_reviewed_gateways(directory)
|
||||
assert not (installation_state_dir() / "stop.json").exists()
|
||||
assert not any(gate.paused for gate in gates)
|
||||
assert not any(stop.is_set() for stop in stops)
|
||||
|
||||
|
||||
async def test_written_commit_is_not_aborted_if_acknowledging_the_write_fails(protocol, monkeypatch):
|
||||
from nanobot import update_stop
|
||||
|
||||
directory, plan, gates, stops = protocol
|
||||
outer = [ExitStack(), ExitStack()]
|
||||
watchers = [asyncio.create_task(watch_gateway_stop(item.receipt, lambda gate=gate: gate.pause_if_idle(lambda: False),
|
||||
stop, stack))
|
||||
for item, gate, stop, stack in zip(plan.profiles, gates, stops, outer)]
|
||||
actual_write = update_stop.write_record
|
||||
|
||||
def fail_after_commit(path, data, **kwargs):
|
||||
actual_write(path, data, **kwargs)
|
||||
if path.name == "stop.json" and data.get("phase") == "commit":
|
||||
raise OSError("Commit renamed before directory fsync failed")
|
||||
|
||||
monkeypatch.setattr(update_stop, "write_record", fail_after_commit)
|
||||
try:
|
||||
with pytest.raises(OSError, match="fsync"):
|
||||
await stop_reviewed_gateways(directory)
|
||||
await wait_until(lambda: all(stop.is_set() for stop in stops))
|
||||
assert read_record(installation_state_dir() / "stop.json")["phase"] == "commit"
|
||||
assert all(gate.paused for gate in gates)
|
||||
await stop_reviewed_gateways(directory)
|
||||
assert read_record(installation_state_dir() / "stop.json")["phase"] == "stopped"
|
||||
assert not (directory / "approval.json").exists()
|
||||
finally:
|
||||
for watcher in watchers:
|
||||
watcher.cancel()
|
||||
await asyncio.gather(*watchers, return_exceptions=True)
|
||||
for stack in outer:
|
||||
stack.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def expire_stop_deadline(monkeypatch):
|
||||
from nanobot import update_stop
|
||||
|
||||
# Drive protocol deadlines from an observed state, not filesystem speed.
|
||||
# Tests retain real-time watchdogs to catch stalled coordination.
|
||||
now = 100.0
|
||||
monkeypatch.setattr(update_stop, "time", SimpleNamespace(monotonic=lambda: now))
|
||||
|
||||
def expire():
|
||||
nonlocal now
|
||||
now += 31 # The production stop deadline is 30 seconds.
|
||||
|
||||
return expire
|
||||
|
||||
|
||||
async def test_stop_acknowledgement_does_not_prove_process_exit(protocol, monkeypatch, expire_stop_deadline):
|
||||
from nanobot import update_stop
|
||||
|
||||
directory, plan, gates, stops = protocol
|
||||
outer = [ExitStack(), ExitStack()]
|
||||
watchers = [asyncio.create_task(watch_gateway_stop(item.receipt, lambda gate=gate: gate.pause_if_idle(lambda: False),
|
||||
stop, stack))
|
||||
for item, gate, stop, stack in zip(plan.profiles, gates, stops, outer)]
|
||||
def still_running(_runtime, _pid):
|
||||
expire_stop_deadline()
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(update_stop.GatewayRuntime, "process_is_running", still_running)
|
||||
monkeypatch.setattr(update_stop.GatewayRuntime, "process_identity_match", lambda self, identity, pid: "match")
|
||||
try:
|
||||
with pytest.raises(TimeoutError, match="process exit is not confirmed"):
|
||||
await asyncio.wait_for(stop_reviewed_gateways(directory), timeout=30)
|
||||
assert all(stop.is_set() for stop in stops)
|
||||
assert all(gate.paused for gate in gates)
|
||||
assert read_record(installation_state_dir() / "stop.json")["phase"] == "commit"
|
||||
monkeypatch.setattr(update_stop.GatewayRuntime, "process_is_running", lambda self, pid: False)
|
||||
await stop_reviewed_gateways(directory)
|
||||
finally:
|
||||
for watcher in watchers:
|
||||
watcher.cancel()
|
||||
await asyncio.gather(*watchers, return_exceptions=True)
|
||||
for stack in outer:
|
||||
stack.close()
|
||||
|
||||
|
||||
async def test_inactive_unselected_profile_must_also_finish_its_process_exit(protocol, monkeypatch, expire_stop_deadline):
|
||||
from nanobot import update_stop
|
||||
|
||||
_, original, gates, stops = protocol
|
||||
first, second = original.profiles
|
||||
inactive = second.model_copy(update={"state": "stopped", "receipt": second.receipt.model_copy(update={"active": False})})
|
||||
directory, _ = prepared_job([first, inactive], stop=[first.receipt.id])
|
||||
|
||||
def require_stopped(_expected, _environment):
|
||||
if not stops[0].is_set():
|
||||
raise ValueError("First gateway has not stopped")
|
||||
|
||||
monkeypatch.setattr(update_stop, "require_stopped_profiles", require_stopped)
|
||||
def still_running(_runtime, pid):
|
||||
if pid == second.receipt.pid:
|
||||
expire_stop_deadline()
|
||||
return True
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(update_stop.GatewayRuntime, "process_is_running", still_running)
|
||||
monkeypatch.setattr(update_stop.GatewayRuntime, "process_identity_match", lambda self, identity, pid: "match")
|
||||
outer = ExitStack()
|
||||
watcher = asyncio.create_task(watch_gateway_stop(first.receipt, lambda: gates[0].pause_if_idle(lambda: False),
|
||||
stops[0], outer))
|
||||
try:
|
||||
with pytest.raises(TimeoutError, match="process exit is not confirmed"):
|
||||
await asyncio.wait_for(stop_reviewed_gateways(directory), timeout=30)
|
||||
assert stops[0].is_set() and not stops[1].is_set()
|
||||
monkeypatch.setattr(update_stop.GatewayRuntime, "process_is_running", lambda self, pid: False)
|
||||
await stop_reviewed_gateways(directory)
|
||||
finally:
|
||||
watcher.cancel()
|
||||
await asyncio.gather(watcher, return_exceptions=True)
|
||||
outer.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", [{"stop_protocol": None}, {"launch_mode": "foreground"}])
|
||||
def test_old_or_externally_owned_gateway_cannot_be_selected_for_stop(protocol, change):
|
||||
_, plan, _, _ = protocol
|
||||
values = plan.model_dump(mode="json")
|
||||
values["profiles"][0]["receipt"].update(change)
|
||||
with pytest.raises(ValueError, match="cooperative stop support"):
|
||||
UpdatePlan.model_validate(values)
|
||||
|
||||
|
||||
async def test_actual_gateway_exits_normally_before_installation_and_data_leases_are_available(private_home, tmp_path):
|
||||
"""Actual gateway stop, not a public download/install/restart E2E."""
|
||||
profile = tmp_path / "gateway home"
|
||||
workspace = tmp_path / "中文 workspace"
|
||||
profile.mkdir()
|
||||
with socket.socket() as listener:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
port = listener.getsockname()[1]
|
||||
config_path = profile / "config.json"
|
||||
config_path.write_text(json.dumps({
|
||||
"agents": {"defaults": {"workspace": str(workspace), "dream": {"enabled": False},
|
||||
"provider": "custom", "model": "lifecycle-test"}},
|
||||
"providers": {"custom": {"apiKey": "fixture-not-a-secret", "apiBase": "http://127.0.0.1:1/v1"}},
|
||||
"gateway": {"host": "127.0.0.1", "port": port, "heartbeat": {"enabled": False}},
|
||||
"channels": {"websocket": {"enabled": False}},
|
||||
}))
|
||||
source = Path(__file__).resolve().parents[1]
|
||||
script = (
|
||||
f"import sys; sys.path.insert(0, {str(source)!r})\n"
|
||||
"from nanobot.cli import gateway_runtime\n"
|
||||
"gateway_runtime.warmup_token_encoding = lambda: None\n"
|
||||
"from nanobot.cli.entry import main\nmain()\n"
|
||||
)
|
||||
children = []
|
||||
|
||||
def spawn(command, **kwargs):
|
||||
assert command[1:3] == ["-m", "nanobot"]
|
||||
child = subprocess.Popen([command[0], "-c", script, *command[3:]], **kwargs)
|
||||
children.append(child)
|
||||
return child
|
||||
|
||||
selected_home = get_selected_home_path()
|
||||
set_home_path(profile)
|
||||
instance = GatewayInstance.resolve(config_path=config_path)
|
||||
runtime = GatewayRuntime(paths=instance.paths, python_executable=sys.executable, popen=spawn)
|
||||
try:
|
||||
assert runtime.start_background(instance.start_options(port=port)).ok
|
||||
|
||||
def gateway_ready():
|
||||
assert children[0].poll() is None, "Gateway exited before readiness"
|
||||
return runtime.status().ready
|
||||
|
||||
try:
|
||||
# Importing a real gateway on a shared Windows runner can exceed the
|
||||
# 5 s budget for the in-process protocol tests. Match the WebUI smoke
|
||||
# test's startup budget without relaxing shutdown or lease assertions.
|
||||
await wait_until(gateway_ready, timeout=20)
|
||||
except (TimeoutError, AssertionError) as exc:
|
||||
logs = instance.paths.log_path.read_text(encoding="utf-8", errors="replace")[-8000:]
|
||||
raise AssertionError(f"Gateway did not become ready: {exc}\n{logs}") from exc
|
||||
profiles = inspect_profiles(sys.prefix)
|
||||
assert len(profiles) == 1 and profiles[0].receipt.stop_protocol == 1
|
||||
assert profiles[0].receipt.launch_mode == "background"
|
||||
directory, plan = prepared_job(profiles)
|
||||
await stop_reviewed_gateways(directory, timeout=10)
|
||||
assert children[0].wait(timeout=5) == 0
|
||||
assert not runtime.status().running
|
||||
assert inspect_profiles(sys.prefix)[0].state == "stopped"
|
||||
receipt = plan.profiles[0].receipt
|
||||
with installation_access(updating=True), data_access(profile_data_paths(
|
||||
home=Path(receipt.home), data_dir=Path(receipt.data_dir),
|
||||
config=Path(receipt.config), workspace=Path(receipt.workspace),
|
||||
), updating=True):
|
||||
pass
|
||||
assert JobStatus.read(directory).phase == Phase.READY
|
||||
assert not (directory / "approval.json").exists()
|
||||
assert len(children) == 1, "Stop-only handoff launched an unrequested replacement"
|
||||
finally:
|
||||
for child in children:
|
||||
if child.poll() is None:
|
||||
if os.name == "nt":
|
||||
# A venv python.exe may be only a redirector. On failure,
|
||||
# clean up its owned tree rather than orphan the gateway.
|
||||
subprocess.run(["taskkill", "/PID", str(child.pid), "/T", "/F"],
|
||||
capture_output=True, timeout=10)
|
||||
else:
|
||||
child.terminate()
|
||||
child.wait(timeout=10)
|
||||
set_home_path(selected_home)
|
||||
@@ -0,0 +1,319 @@
|
||||
"""Real uv/frozen-worker transactions; synthetic packages and a private HTTP index.
|
||||
|
||||
These prove manager ownership and prepared-input behavior, not gateway migration,
|
||||
UI acceptance, public distribution or native Windows support.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock
|
||||
from uuid import uuid4
|
||||
from zipfile import ZipFile
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from packaging.tags import sys_tags
|
||||
from test_update_jobs import _preparer_script, wheel
|
||||
|
||||
import nanobot.update_jobs as jobs
|
||||
from nanobot.installation_lock import (
|
||||
InstallationBusyError,
|
||||
file_access,
|
||||
installation_access,
|
||||
installation_state_dir,
|
||||
)
|
||||
from nanobot.release_feed import ReleaseFeed, ReleaseTarget
|
||||
from nanobot.releases import PLATFORMS, ReleaseArtifact, release_filenames
|
||||
from nanobot.update_manager import read_manager_policy
|
||||
from nanobot.update_plan import InstallationSnapshot, UpdatePlan
|
||||
from nanobot.update_stop import stop_reviewed_gateways
|
||||
from nanobot.update_uv import UV_TRANSACTION_VERSION, cache_digest, uv_environment
|
||||
from nanobot.update_worker import JobStatus, Phase, WorkerSpec, inspect_environment
|
||||
|
||||
pytestmark = pytest.mark.skipif(os.name != "posix" or not shutil.which("uv"), reason="Native POSIX uv required")
|
||||
|
||||
_FAIL_VERIFICATION_ONCE = """
|
||||
from _nanobot_update import update_worker
|
||||
original_verify = update_worker._verify
|
||||
def verify(spec, directory):
|
||||
marker = directory / 'fail-verification'
|
||||
if marker.exists():
|
||||
marker.unlink()
|
||||
raise ValueError('Controlled post-install verification failure')
|
||||
original_verify(spec, directory)
|
||||
update_worker._verify = verify
|
||||
"""
|
||||
|
||||
|
||||
class IndexHandler(SimpleHTTPRequestHandler):
|
||||
def log_message(self, *_args):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def uv_installation(tmp_path, monkeypatch):
|
||||
# Private synthetic package-manager fixtures, not release-signature proof.
|
||||
monkeypatch.setattr(ReleaseFeed, "_authorize", AsyncMock())
|
||||
from nanobot import update_process
|
||||
|
||||
manager_version = subprocess.check_output([shutil.which("uv"), "--version"], text=True, timeout=10)
|
||||
if manager_version.split()[:2] != ["uv", UV_TRANSACTION_VERSION]:
|
||||
pytest.skip(f"Native transaction integration requires uv {UV_TRANSACTION_VERSION}")
|
||||
tmp_path = tmp_path.resolve()
|
||||
account = tmp_path / "private account"
|
||||
account.mkdir()
|
||||
monkeypatch.setattr(Path, "home", classmethod(lambda cls: account))
|
||||
# The read-only bootstrap has the same isolated account as frozen workers.
|
||||
monkeypatch.setattr(update_process, "_INSPECTION_BOOTSTRAP", (
|
||||
"from pathlib import Path\n"
|
||||
f"Path.home = classmethod(lambda cls: Path({str(account)!r}))\n"
|
||||
) + update_process._INSPECTION_BOOTSTRAP)
|
||||
archive_worker = jobs._worker_archive
|
||||
|
||||
def private_worker(path):
|
||||
# All worker entrypoints, including installer children, use a private
|
||||
# account. Do not change HOME or patch production transaction behavior.
|
||||
archive_worker(path)
|
||||
with ZipFile(path) as source:
|
||||
files = {item.filename: source.read(item) for item in source.infolist()}
|
||||
files["__main__.py"] = (
|
||||
"from pathlib import Path\n"
|
||||
f"Path.home = classmethod(lambda cls: Path({str(account)!r}))\n"
|
||||
).encode() + _FAIL_VERIFICATION_ONCE.encode() + files["__main__.py"]
|
||||
with ZipFile(path, "w") as target:
|
||||
for name, content in files.items():
|
||||
target.writestr(name, content)
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
monkeypatch.setattr(jobs, "_worker_archive", private_worker)
|
||||
artifacts = tmp_path / "index"
|
||||
artifacts.mkdir()
|
||||
|
||||
def index():
|
||||
for file in artifacts.glob("*.whl"):
|
||||
name = file.name.split("-")[0].replace("_", "-")
|
||||
page = artifacts / "simple" / name / "index.html"
|
||||
page.parent.mkdir(parents=True, exist_ok=True)
|
||||
links = artifacts.glob(file.name.split("-")[0] + "-*.whl")
|
||||
page.write_text("\n".join(f'<a href="../../{item.name}">{item.name}</a>' for item in links))
|
||||
|
||||
wheel(artifacts, "fixture-feature", "1.0.0")
|
||||
wheel(artifacts, "fixture-injected", "1.0.0")
|
||||
wheel(artifacts, "fixture-obsolete", "1.0.0")
|
||||
wheel(artifacts, "nanobot-ai", "0.3.4", extras=["feature"], entrypoint=True,
|
||||
requires=['fixture-feature>=1; extra == "feature"', "fixture-obsolete==1.0.0"])
|
||||
index()
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), partial(IndexHandler, directory=str(artifacts)))
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
tools, binaries = tmp_path / "tools", tmp_path / "bin"
|
||||
env = uv_environment(tools=tools, binaries=binaries, cache=tmp_path / "original cache")
|
||||
subprocess.run([
|
||||
shutil.which("uv"), "tool", "install", "--no-config", "--python", sys._base_executable,
|
||||
"--index-url", f"http://127.0.0.1:{server.server_port}/simple/",
|
||||
"--with", "fixture-injected==1.0.0", "nanobot-ai[feature]>=0.3.4,<0.4",
|
||||
], env=env, check=True, capture_output=True, timeout=60)
|
||||
environment = tools / "nanobot-ai"
|
||||
python = str(environment / "bin/python")
|
||||
baseline = inspect_environment(python, uv=True)
|
||||
receipt = environment / "uv-receipt.toml"
|
||||
assert "no-build" not in receipt.read_text(), "Baseline must not already have staging's no-build option"
|
||||
package = subprocess.check_output([
|
||||
python, "-I", "-c", "import nanobot; print(nanobot.__file__)",
|
||||
], text=True).strip()
|
||||
snapshot = InstallationSnapshot(
|
||||
environment=str(environment), python=python, installed_version="0.3.4", running_version="0.3.4",
|
||||
package_path=package, running_package=package, owner="uv",
|
||||
records={"pyvenv.cfg": baseline.receipt_sha, "uv-receipt.toml": baseline.manager_receipt_sha,
|
||||
**baseline.app_records},
|
||||
manager=read_manager_policy(environment, "uv", baseline.manager_receipt_sha),
|
||||
)
|
||||
wheel(artifacts, "fixture-feature", "2.0.0")
|
||||
wheel(artifacts, "fixture-runtime", "2.0.0")
|
||||
platform = next(tag.platform for tag in sys_tags() if tag.platform in PLATFORMS.values())
|
||||
candidate = wheel(artifacts, "nanobot-ai", "0.3.5", platform=platform, extras=["feature"], entrypoint=True,
|
||||
requires=['fixture-feature>=2; extra == "feature"', "fixture-runtime>=2"])
|
||||
wheel(artifacts, "nanobot-ai", "0.3.6", entrypoint=True)
|
||||
index()
|
||||
target = ReleaseTarget(version="0.3.5", source="pypi",
|
||||
url=f"https://files.pythonhosted.org/packages/{candidate.name}",
|
||||
artifact=ReleaseArtifact(filename=candidate.name, size=candidate.stat().st_size,
|
||||
sha256=hashlib.sha256(candidate.read_bytes()).hexdigest()))
|
||||
now = int(time.time())
|
||||
plan = UpdatePlan(id=str(uuid4()), installation=snapshot, target=target, extras=["feature"],
|
||||
channel="stable", created_at=now, expires_at=now + 900)
|
||||
|
||||
def response(request):
|
||||
if request.url.host == "files.pythonhosted.org":
|
||||
assert request.url.path.endswith(candidate.name)
|
||||
return httpx.Response(200, content=candidate.read_bytes())
|
||||
assert request.url.path == "/pypi/nanobot-ai/0.3.5/json"
|
||||
files = []
|
||||
for filename in release_filenames("0.3.5"):
|
||||
if filename.endswith((".whl", ".tar.gz")):
|
||||
selected = filename == candidate.name
|
||||
files.append({"filename": filename, "size": target.artifact.size if selected else 1,
|
||||
"url": f"https://files.pythonhosted.org/packages/{filename}", "yanked": False,
|
||||
"digests": {"sha256": target.artifact.sha256 if selected else "a" * 64}})
|
||||
return httpx.Response(200, json={"info": {"name": "nanobot-ai", "version": "0.3.5", "requires_python": ">=3.11"}, "urls": files})
|
||||
|
||||
yield plan, baseline, receipt, httpx.MockTransport(response), server
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join(timeout=10)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["install", "tamper", "repair", "external-policy"])
|
||||
async def test_uv_prepared_job_preserves_owner_and_sealed_inputs(uv_installation, tmp_path, monkeypatch, mode):
|
||||
plan, before, receipt, transport, server = uv_installation
|
||||
original_receipt = receipt.read_bytes()
|
||||
async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
|
||||
if mode == "external-policy":
|
||||
# A later user-level index/security policy cannot silently disappear
|
||||
# merely because this first implementation only froze the receipt.
|
||||
config_root = tmp_path / "user config"
|
||||
config = config_root / "uv/uv.toml"
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text('exclude-newer = "2026-01-01T00:00:00Z"\n')
|
||||
monkeypatch.setenv("XDG_CONFIG_HOME", str(config_root))
|
||||
with pytest.raises(ValueError, match="External uv configuration"):
|
||||
await jobs.prepare_job(plan, feed)
|
||||
assert inspect_environment(plan.installation.python, uv=True) == before
|
||||
assert receipt.read_bytes() == original_receipt
|
||||
return
|
||||
directory = await jobs.prepare_job(plan, feed)
|
||||
spec = WorkerSpec.read(directory)
|
||||
assert spec.uv is not None
|
||||
assert inspect_environment(plan.installation.python, uv=True) == before
|
||||
assert receipt.read_bytes() == original_receipt
|
||||
# The selected app is not the newer index version, injected packages and
|
||||
# extras survive, and an obsolete dependency is removed by the owner.
|
||||
assert spec.uv.versions == {
|
||||
"nanobot-ai": "0.3.5", "fixture-feature": "2.0.0",
|
||||
"fixture-runtime": "2.0.0", "fixture-injected": "1.0.0",
|
||||
}
|
||||
cache = directory / spec.uv.cache
|
||||
server.shutdown()
|
||||
server.server_close() # Dependencies must come entirely from prepared inputs.
|
||||
if mode == "tamper":
|
||||
(cache / "changed-after-preparation").write_text("not part of approved preparation")
|
||||
# Preflight can encounter cache changes after the initial worker
|
||||
# check (for example during release revalidation). Refuse before
|
||||
# posting even a shutdown preparation request to the gateways.
|
||||
with pytest.raises(ValueError, match="cache changed"):
|
||||
await stop_reviewed_gateways(directory)
|
||||
assert not (directory.parent.parent / "stop.json").exists()
|
||||
with pytest.raises(ValueError, match="cache changed"):
|
||||
await jobs.start_job(directory, feed)
|
||||
assert not (directory / "approval.json").exists()
|
||||
assert not (directory / "backup").exists()
|
||||
assert inspect_environment(plan.installation.python, uv=True) == before
|
||||
return
|
||||
if mode == "repair":
|
||||
(directory / "fail-verification").touch()
|
||||
process = await jobs.start_job(directory, feed)
|
||||
code = await asyncio.to_thread(process.wait, 60)
|
||||
status = JobStatus.read(directory)
|
||||
if mode == "repair":
|
||||
assert code != 0 and status.phase == Phase.FAILED and status.mutation_started
|
||||
backup = (directory / "backup/data.zip").read_bytes()
|
||||
with pytest.raises(ValueError, match="explicit repair"):
|
||||
await jobs.start_job(directory, feed)
|
||||
process = await jobs.start_job(directory, feed, repair=True)
|
||||
code = await asyncio.to_thread(process.wait, 60)
|
||||
status = JobStatus.read(directory)
|
||||
assert (directory / "backup/data.zip").read_bytes() == backup
|
||||
assert code == 0, status
|
||||
assert status.phase == Phase.INSTALLED, status
|
||||
assert inspect_environment(plan.installation.python, uv=True).versions == spec.uv.versions
|
||||
assert receipt.read_bytes() == original_receipt
|
||||
assert cache_digest(cache) == spec.uv.cache_sha256
|
||||
assert (directory / "backup/data.zip").is_file()
|
||||
assert len(list(directory.glob(".uv-apply-*"))) == (2 if mode == "repair" else 1)
|
||||
|
||||
|
||||
async def test_orphan_native_uv_preparation_keeps_lease_and_can_be_settled(uv_installation, tmp_path):
|
||||
plan, before, receipt, transport, server = uv_installation
|
||||
async with ReleaseFeed(tmp_path / "ready-feed", transport=transport) as feed:
|
||||
prepared = await jobs.prepare_job(plan, feed)
|
||||
plan = plan.model_copy(update={"id": str(uuid4())})
|
||||
root = installation_state_dir(plan.installation.environment)
|
||||
directory = root / "jobs" / plan.id
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
original_receipt = receipt.read_bytes()
|
||||
native_pid = tmp_path / "native-pid"
|
||||
|
||||
class HeldIndex(IndexHandler):
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/simple/fixture-runtime/"):
|
||||
entered.set()
|
||||
assert release.wait(20), "The native uv test was not released"
|
||||
super().do_GET()
|
||||
|
||||
server.RequestHandlerClass = partial(HeldIndex, directory=str(tmp_path / "index"))
|
||||
template = tmp_path / "private-worker.pyz"
|
||||
jobs._worker_archive(template) # Existing fixture makes every child use the private account.
|
||||
hook = f"""
|
||||
import shutil, subprocess
|
||||
Path.home = classmethod(lambda cls: Path({str(Path.home())!r}))
|
||||
def private_worker(path):
|
||||
shutil.copyfile({str(template)!r}, path)
|
||||
return 'unused-before-final-checksum'
|
||||
update_jobs._worker_archive = private_worker
|
||||
original_popen = subprocess.Popen
|
||||
def observed_popen(*args, **kwargs):
|
||||
child = original_popen(*args, **kwargs)
|
||||
Path({str(native_pid)!r}).write_text(str(child.pid))
|
||||
return child
|
||||
subprocess.Popen = observed_popen
|
||||
"""
|
||||
script = _preparer_script(plan, tmp_path / "index" / plan.target.artifact.filename, tmp_path / "feed", hook)
|
||||
parent = subprocess.Popen([sys.executable, "-I", "-c", script], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
try:
|
||||
async with asyncio.timeout(15):
|
||||
while not entered.is_set():
|
||||
assert parent.poll() is None, "Preparation exited before native uv reached the index"
|
||||
await asyncio.sleep(0.01)
|
||||
parent.kill()
|
||||
await asyncio.to_thread(parent.wait, 10)
|
||||
os.kill(int(native_pid.read_text()), 0)
|
||||
with pytest.raises(InstallationBusyError):
|
||||
with installation_access(updating=True, environment=plan.installation.environment):
|
||||
pytest.fail("Native uv lost its own runtime lease after parent death")
|
||||
with pytest.raises(BlockingIOError):
|
||||
jobs.settle_interrupted_preparation(directory)
|
||||
with pytest.raises(BlockingIOError):
|
||||
await stop_reviewed_gateways(prepared)
|
||||
assert not (root / "stop.json").exists(), "A live native preparation must be refused before shutdown"
|
||||
assert JobStatus.read(directory).phase == Phase.PREPARING
|
||||
assert not (directory / "request.json").exists()
|
||||
finally:
|
||||
release.set()
|
||||
if parent.poll() is None:
|
||||
parent.kill()
|
||||
await asyncio.to_thread(parent.wait, 10)
|
||||
async with asyncio.timeout(20):
|
||||
while True:
|
||||
try:
|
||||
with file_access(root / "prepare-native.lock", exclusive=True):
|
||||
break
|
||||
except BlockingIOError:
|
||||
await asyncio.sleep(0.01)
|
||||
assert jobs.settle_interrupted_preparation(directory).phase == Phase.PREPARATION_FAILED
|
||||
assert inspect_environment(plan.installation.python, uv=True) == before
|
||||
assert receipt.read_bytes() == original_receipt
|
||||
async with ReleaseFeed(tmp_path / "retry-feed", transport=transport) as feed:
|
||||
assert await jobs.prepare_job(plan, feed) == directory
|
||||
assert JobStatus.read(directory).phase == Phase.READY
|
||||
assert not (directory / "approval.json").exists()
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Ordinary Windows path inputs at the update record and lease I/O boundaries."""
|
||||
|
||||
import stat
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.installation_lock import file_access
|
||||
from nanobot.update_worker import read_record, write_record
|
||||
from nanobot.utils.atomic_file import (
|
||||
_open_snapshot,
|
||||
atomic_write_lines,
|
||||
atomic_write_text,
|
||||
io_path,
|
||||
read_atomic_bytes,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.skipif(sys.platform != "win32", reason="Windows filesystem semantics")
|
||||
|
||||
|
||||
def record_path(root: Path, length: int) -> Path:
|
||||
# Only fixture setup/inspection uses the extended namespace. Every product
|
||||
# operation below receives an ordinary absolute path, including at 280 chars.
|
||||
root = Path(str(root).removeprefix("\\\\?\\"))
|
||||
padding = length - len(str(root)) - len("\\status.json") - 1
|
||||
assert 0 < padding < 255
|
||||
path = root / ("d" * padding) / "status.json"
|
||||
assert path.is_absolute() and len(str(path)) == length
|
||||
return path
|
||||
|
||||
|
||||
def fixture_path(path: Path) -> Path:
|
||||
return Path("\\\\?\\" + str(path))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("length", [228, 280], ids=["long-sibling", "long-target"])
|
||||
@pytest.mark.parametrize("kind", ["text", "lines"])
|
||||
def test_atomic_io(tmp_path: Path, length: int, kind: str) -> None:
|
||||
target = record_path(tmp_path, length)
|
||||
sibling = target.with_name(f".{target.name}.{'0' * 32}.tmp")
|
||||
assert len(str(sibling)) == length + 38 > 260
|
||||
if kind == "lines":
|
||||
fixture_path(target.parent).mkdir(parents=True)
|
||||
|
||||
def write(text: str) -> None:
|
||||
if kind == "text":
|
||||
atomic_write_text(target, text)
|
||||
else:
|
||||
atomic_write_lines(target, [text])
|
||||
|
||||
suffix = b"" if kind == "text" else b"\n"
|
||||
write("old")
|
||||
with _open_snapshot(target) as previous:
|
||||
write("new")
|
||||
assert previous.read() == b"old" + suffix
|
||||
assert read_atomic_bytes(target) == b"new" + suffix
|
||||
assert read_atomic_bytes(target, max_bytes=2) == b"ne"
|
||||
assert list(fixture_path(target.parent).glob("*.tmp")) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("length", [228, 280], ids=["long-sibling", "long-target"])
|
||||
def test_update_record(tmp_path: Path, length: int) -> None:
|
||||
target = record_path(tmp_path, length)
|
||||
fixture_path(target.parent).mkdir(parents=True)
|
||||
write_record(target, {"state": "ready"})
|
||||
assert read_record(target) == {"state": "ready"}
|
||||
with _open_snapshot(target) as previous:
|
||||
write_record(target, {"state": "stopping"})
|
||||
assert previous.read() == b'{"state":"ready"}\n'
|
||||
assert read_record(target) == {"state": "stopping"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["text", "lines"])
|
||||
def test_readonly_record_keeps_old_value(tmp_path: Path, kind: str) -> None:
|
||||
target = record_path(tmp_path, 228)
|
||||
fixture_path(target.parent).mkdir(parents=True)
|
||||
fixture_path(target).write_bytes(b"kept\n")
|
||||
target.chmod(stat.S_IREAD)
|
||||
try:
|
||||
with pytest.raises(PermissionError):
|
||||
if kind == "text":
|
||||
atomic_write_text(target, "new\n")
|
||||
else:
|
||||
atomic_write_lines(target, ["new"])
|
||||
assert read_atomic_bytes(target) == b"kept\n"
|
||||
assert list(fixture_path(target.parent).glob("*.tmp")) == []
|
||||
finally:
|
||||
target.chmod(stat.S_IWRITE)
|
||||
|
||||
|
||||
def test_long_file_lease(tmp_path: Path) -> None:
|
||||
target = record_path(tmp_path, 280).with_suffix(".lock")
|
||||
with file_access(target, exclusive=False):
|
||||
with file_access(target, exclusive=False):
|
||||
with pytest.raises(BlockingIOError):
|
||||
with file_access(target, exclusive=True):
|
||||
pytest.fail("An updater acquired a live runtime's lease")
|
||||
with file_access(target, exclusive=True):
|
||||
with pytest.raises(BlockingIOError):
|
||||
with file_access(target, exclusive=False):
|
||||
pytest.fail("A runtime entered an updating installation")
|
||||
with file_access(target, exclusive=False):
|
||||
pass
|
||||
|
||||
|
||||
def test_io_path_spelling(tmp_path: Path) -> None:
|
||||
ordinary = tmp_path / "nested" / ".." / "status.json"
|
||||
extended = fixture_path(tmp_path / "status.json")
|
||||
assert io_path(ordinary) == extended
|
||||
assert io_path(extended) == extended
|
||||
assert io_path(Path(r"\\server\share\updates\status.json")) == Path(
|
||||
r"\\?\UNC\server\share\updates\status.json"
|
||||
)
|
||||
|
||||
|
||||
def test_relative_atomic_io(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.chdir(tmp_path)
|
||||
target = Path("relative state") / "status.json"
|
||||
atomic_write_text(target, "old")
|
||||
with _open_snapshot(target) as previous:
|
||||
atomic_write_text(target, "new")
|
||||
assert previous.read() == b"old"
|
||||
assert read_atomic_bytes(target) == b"new"
|
||||
@@ -8,6 +8,7 @@ import sys
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -122,6 +123,20 @@ async def _pid_stopped(pid: int, *, timeout: float = 6) -> None:
|
||||
assert not _pid_running(pid), f"subprocess {pid} is still running after {timeout}s"
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform != "linux", reason="Linux /proc process probe")
|
||||
@pytest.mark.parametrize("disappeared", [FileNotFoundError, ProcessLookupError])
|
||||
async def test_pid_stopped_tolerates_exit_during_proc_read(monkeypatch, disappeared):
|
||||
stat = Mock()
|
||||
stat.exists.return_value = True
|
||||
stat.read_text.side_effect = disappeared("process exited during stat read")
|
||||
monkeypatch.setattr(sys.modules[__name__], "Path", Mock(return_value=stat))
|
||||
monkeypatch.setattr(os, "kill", Mock(side_effect=[None, ProcessLookupError, ProcessLookupError]))
|
||||
|
||||
await _pid_stopped(123, timeout=1)
|
||||
|
||||
stat.read_text.assert_called_once()
|
||||
|
||||
|
||||
async def _cleanup_pidfiles(*paths: Path) -> None:
|
||||
pids = [int(path.read_text()) for path in paths if path.exists() and path.read_text()]
|
||||
for pid in pids:
|
||||
|
||||
+33
-18
@@ -5,7 +5,7 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.utils import helpers, token_encoding
|
||||
from nanobot.utils import atomic_file, file_io, token_encoding
|
||||
from nanobot.utils.helpers import (
|
||||
_write_text_atomic,
|
||||
atomic_write_lines,
|
||||
@@ -162,9 +162,9 @@ def test_write_text_atomic_fsyncs_file_and_parent_directory(
|
||||
fsync_calls.append(fd)
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(helpers.os, "fsync", fake_fsync)
|
||||
patch.setattr(helpers.os, "open", lambda path, flags: 12345)
|
||||
patch.setattr(helpers.os, "close", lambda fd: closed_fds.append(fd))
|
||||
patch.setattr(file_io.os, "fsync", fake_fsync)
|
||||
patch.setattr(file_io.os, "open", lambda path, flags: 12345)
|
||||
patch.setattr(file_io.os, "close", lambda fd: closed_fds.append(fd))
|
||||
|
||||
_write_text_atomic(target, '{"approved": {}}')
|
||||
|
||||
@@ -185,8 +185,8 @@ def test_write_text_atomic_keeps_file_when_directory_fsync_is_unsupported(
|
||||
raise OSError("directory fsync unsupported")
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(helpers.os, "fsync", lambda fd: fsync_calls.append(fd))
|
||||
patch.setattr(helpers.os, "open", fake_open)
|
||||
patch.setattr(file_io.os, "fsync", lambda fd: fsync_calls.append(fd))
|
||||
patch.setattr(file_io.os, "open", fake_open)
|
||||
|
||||
_write_text_atomic(target, '{"pending": {}}')
|
||||
|
||||
@@ -215,9 +215,24 @@ def test_atomic_write_lines_round_trip_replaces_target(tmp_path: Path) -> None:
|
||||
atomic_write_lines(target, ['{"a": 1}', "café"])
|
||||
|
||||
assert target.read_text(encoding="utf-8") == '{"a": 1}\ncafé\n'
|
||||
assert target.read_bytes() == '{"a": 1}\ncafé\n'.encode("utf-8")
|
||||
assert list(tmp_path.glob("*.tmp")) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["status.json", "更新状态-🐈.json"])
|
||||
def test_atomic_record_reader_does_not_block_concurrent_replacement(tmp_path: Path, name: str) -> None:
|
||||
"""The update UI can poll while a detached worker commits its next phase."""
|
||||
from nanobot.utils.atomic_file import _open_snapshot, read_atomic_bytes
|
||||
|
||||
target = tmp_path / name
|
||||
atomic_write_lines(target, ['{"phase":"checking"}'])
|
||||
with _open_snapshot(target) as previous:
|
||||
atomic_write_lines(target, ['{"phase":"stopping"}'])
|
||||
assert previous.read() == b'{"phase":"checking"}\n'
|
||||
assert read_atomic_bytes(target) == b'{"phase":"stopping"}\n'
|
||||
assert read_atomic_bytes(target, max_bytes=2) == b'{"'
|
||||
|
||||
|
||||
def test_atomic_write_lines_empty_input_replaces_file_with_empty(tmp_path: Path) -> None:
|
||||
target = tmp_path / "history.jsonl"
|
||||
target.write_text("old\n", encoding="utf-8")
|
||||
@@ -245,7 +260,7 @@ def test_atomic_writes_clean_temp_when_replace_fails(
|
||||
def fail_replace(*_args: object, **_kwargs: object) -> None:
|
||||
raise error_type("replace failed")
|
||||
|
||||
monkeypatch.setattr(helpers.os, "replace", fail_replace)
|
||||
monkeypatch.setattr("nanobot.utils.atomic_file.replace_atomic", fail_replace)
|
||||
|
||||
with pytest.raises(error_type, match="replace failed"):
|
||||
write(target, "new")
|
||||
@@ -271,7 +286,7 @@ def test_atomic_write_lines_skips_fsync_when_disabled(
|
||||
) -> None:
|
||||
target = tmp_path / "session.jsonl"
|
||||
fsync_calls: list[int] = []
|
||||
monkeypatch.setattr(helpers.os, "fsync", lambda fd: fsync_calls.append(fd))
|
||||
monkeypatch.setattr(atomic_file.os, "fsync", lambda fd: fsync_calls.append(fd))
|
||||
|
||||
atomic_write_lines(target, ["line"], fsync=False)
|
||||
|
||||
@@ -285,7 +300,7 @@ def test_atomic_write_lines_suppresses_directory_permission_error(
|
||||
"""Windows directory open raises PermissionError; the replace must still stick."""
|
||||
target = tmp_path / "history.jsonl"
|
||||
opened: list[tuple[object, int]] = []
|
||||
real_open = helpers.os.open
|
||||
real_open = atomic_file.os.open
|
||||
|
||||
def open_directory(path: object, flags: int, *args: object, **kwargs: object) -> int:
|
||||
opened.append((path, flags))
|
||||
@@ -293,12 +308,12 @@ def test_atomic_write_lines_suppresses_directory_permission_error(
|
||||
raise PermissionError("directory open denied")
|
||||
return real_open(path, flags, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(helpers.os, "open", open_directory)
|
||||
monkeypatch.setattr(atomic_file.os, "open", open_directory)
|
||||
|
||||
atomic_write_lines(target, ["ok"])
|
||||
|
||||
assert target.read_text(encoding="utf-8") == "ok\n"
|
||||
assert opened == [(str(tmp_path), os.O_RDONLY)]
|
||||
assert opened == [(str(atomic_file.io_path(tmp_path)), os.O_RDONLY)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error_number", [errno.EINVAL, errno.EIO], ids=["unsupported", "io-error"])
|
||||
@@ -319,9 +334,9 @@ def test_atomic_writes_directory_fsync_errors(
|
||||
target = tmp_path / "session.jsonl"
|
||||
directory_fd = 12345
|
||||
fsync_calls = 0
|
||||
real_fsync = helpers.os.fsync
|
||||
real_open = helpers.os.open
|
||||
real_close = helpers.os.close
|
||||
real_fsync = atomic_file.os.fsync
|
||||
real_open = atomic_file.os.open
|
||||
real_close = atomic_file.os.close
|
||||
opened: list[tuple[object, int]] = []
|
||||
closed: list[int] = []
|
||||
|
||||
@@ -344,9 +359,9 @@ def test_atomic_writes_directory_fsync_errors(
|
||||
return
|
||||
raise OSError(error_number, "directory fsync failed")
|
||||
|
||||
monkeypatch.setattr(helpers.os, "open", tracking_open)
|
||||
monkeypatch.setattr(helpers.os, "close", tracking_close)
|
||||
monkeypatch.setattr(helpers.os, "fsync", fsync_then_error)
|
||||
monkeypatch.setattr(atomic_file.os, "open", tracking_open)
|
||||
monkeypatch.setattr(atomic_file.os, "close", tracking_close)
|
||||
monkeypatch.setattr(atomic_file.os, "fsync", fsync_then_error)
|
||||
|
||||
if error_number == errno.EINVAL:
|
||||
write(target, "ok")
|
||||
@@ -357,5 +372,5 @@ def test_atomic_writes_directory_fsync_errors(
|
||||
|
||||
assert target.read_text(encoding="utf-8") == expected_content
|
||||
assert fsync_calls == 2
|
||||
assert opened == [(str(tmp_path), directory_fd)]
|
||||
assert opened == [(str(atomic_file.io_path(tmp_path)), directory_fd)]
|
||||
assert closed == [directory_fd]
|
||||
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from contextlib import nullcontext
|
||||
from pathlib import Path
|
||||
|
||||
from nanobot.webui.build import (
|
||||
@@ -100,7 +101,8 @@ def test_inspect_webui_bundle_accepts_fresh_dist(tmp_path: Path) -> None:
|
||||
assert status.reason == "fresh"
|
||||
|
||||
|
||||
def test_ensure_webui_bundle_auto_builds_stale_dist(tmp_path: Path) -> None:
|
||||
def test_ensure_webui_bundle_auto_builds_stale_dist(tmp_path: Path, monkeypatch) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.build.bun_environment", lambda _: nullcontext({"PATH": "bun"}))
|
||||
source = tmp_path / "webui"
|
||||
dist = tmp_path / "nanobot" / "web" / "dist"
|
||||
_touch(source / "package.json", mtime_ns=10)
|
||||
@@ -108,11 +110,13 @@ def test_ensure_webui_bundle_auto_builds_stale_dist(tmp_path: Path) -> None:
|
||||
_touch(dist / "index.html", mtime_ns=20)
|
||||
commands: list[tuple[str, ...]] = []
|
||||
|
||||
def fake_run(command, *, cwd: Path, check: bool) -> None:
|
||||
def fake_run(command, *, cwd: Path, check: bool, env: dict[str, str], timeout: int) -> None:
|
||||
commands.append(tuple(command))
|
||||
assert cwd == source
|
||||
assert check is True
|
||||
if command == ["bun", "run", "build"]:
|
||||
assert "PATH" in env
|
||||
assert timeout == 900
|
||||
if command == ["bun", "--bun", "run", "build"]:
|
||||
_touch(dist / "index.html", mtime_ns=40)
|
||||
|
||||
status = ensure_webui_bundle(
|
||||
@@ -124,7 +128,7 @@ def test_ensure_webui_bundle_auto_builds_stale_dist(tmp_path: Path) -> None:
|
||||
)
|
||||
|
||||
assert status.stale is False
|
||||
assert commands == [("bun", "install"), ("bun", "run", "build")]
|
||||
assert commands == [("bun", "install", "--frozen-lockfile"), ("bun", "--bun", "run", "build")]
|
||||
|
||||
|
||||
def test_pick_webui_build_runner_returns_resolved_executable(monkeypatch) -> None:
|
||||
|
||||
@@ -5,6 +5,7 @@ import asyncio
|
||||
import pytest
|
||||
|
||||
from nanobot.config.schema import MCPServerConfig
|
||||
from nanobot.runtime_admission import RuntimeAdmission, RuntimeBusyError, RuntimeMaintenanceError
|
||||
from nanobot.webui.mcp_oauth_api import (
|
||||
McpOAuthError,
|
||||
McpOAuthManager,
|
||||
@@ -45,7 +46,7 @@ def _config() -> MCPServerConfig:
|
||||
async def test_browser_flow_retries_current_server_and_ignores_unrelated_reload_failure(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
manager = McpOAuthManager()
|
||||
manager = McpOAuthManager(RuntimeAdmission())
|
||||
connection = _Connection()
|
||||
received: dict[str, object] = {}
|
||||
reload_calls = 0
|
||||
@@ -116,6 +117,7 @@ async def test_browser_flow_retries_current_server_and_ignores_unrelated_reload_
|
||||
assert first["hot_reload"]["failed"] == ["notion"]
|
||||
assert received["callback"] == ("oauth-code", "state-123")
|
||||
assert reload_calls == 2
|
||||
await manager.close()
|
||||
assert connection.closed is True
|
||||
|
||||
|
||||
@@ -123,7 +125,8 @@ async def test_browser_flow_retries_current_server_and_ignores_unrelated_reload_
|
||||
async def test_browser_flow_activates_tools_before_probe_cleanup_completes(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
manager = McpOAuthManager()
|
||||
admission = RuntimeAdmission()
|
||||
manager = McpOAuthManager(admission)
|
||||
connection = _BlockingConnection()
|
||||
reload_started = asyncio.Event()
|
||||
|
||||
@@ -159,27 +162,92 @@ async def test_browser_flow_activates_tools_before_probe_cleanup_completes(
|
||||
)
|
||||
manager.submit_callback(state="blocked-close", code="oauth-code", error=None)
|
||||
|
||||
shutdown = None
|
||||
try:
|
||||
await asyncio.wait_for(reload_started.wait(), timeout=0.5)
|
||||
await asyncio.wait_for(connection.close_started.wait(), timeout=0.5)
|
||||
result = await manager.status(started["flow_id"])
|
||||
assert result["status"] == "connected"
|
||||
assert connection.closed is False
|
||||
with pytest.raises(RuntimeBusyError), admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("MCP transport cleanup is still running")
|
||||
shutdown = asyncio.create_task(manager.close())
|
||||
await asyncio.wait({shutdown}, timeout=0.01)
|
||||
assert not shutdown.done(), "Shutdown must join the in-flight transport cleanup"
|
||||
finally:
|
||||
connection.allow_close.set()
|
||||
if shutdown is not None:
|
||||
await shutdown
|
||||
|
||||
for _ in range(10):
|
||||
await asyncio.sleep(0)
|
||||
if connection.closed:
|
||||
break
|
||||
assert connection.closed is True
|
||||
await manager.close()
|
||||
with admission.pause_if_idle(lambda: False):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize("expire", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_browser_flow_remains_busy_through_cancelled_or_expired_cleanup(
|
||||
monkeypatch: pytest.MonkeyPatch, expire: bool,
|
||||
) -> None:
|
||||
admission = RuntimeAdmission()
|
||||
manager = McpOAuthManager(admission)
|
||||
cleanup_started = asyncio.Event()
|
||||
allow_cleanup = asyncio.Event()
|
||||
monkeypatch.setattr("nanobot.webui.mcp_oauth_api.validate_url_target", lambda _: (True, ""))
|
||||
if expire:
|
||||
monkeypatch.setattr("nanobot.webui.mcp_oauth_api._FLOW_TTL_S", 0)
|
||||
|
||||
async def connect(_servers, _registry, *, oauth_handlers):
|
||||
handlers = oauth_handlers["linear"]
|
||||
await handlers.redirect_handler("https://accounts.example.com/auth?state=pending")
|
||||
try:
|
||||
await handlers.callback_handler()
|
||||
finally:
|
||||
cleanup_started.set()
|
||||
await allow_cleanup.wait()
|
||||
return {}
|
||||
|
||||
monkeypatch.setattr("nanobot.webui.mcp_oauth_api.connect_mcp_servers", connect)
|
||||
started = await manager.start(
|
||||
"linear", _config(), "https://agent.example.com/auth/mcp/callback",
|
||||
reload_mcp=lambda: asyncio.sleep(0, result={"ok": True}),
|
||||
)
|
||||
with pytest.raises(RuntimeBusyError), admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("The browser response does not finish authorization")
|
||||
if expire:
|
||||
with pytest.raises(McpOAuthError, match="expired"):
|
||||
await manager.status(started["flow_id"])
|
||||
await asyncio.wait_for(cleanup_started.wait(), timeout=0.5)
|
||||
|
||||
shutdown = asyncio.create_task(manager.close())
|
||||
try:
|
||||
await asyncio.wait_for(cleanup_started.wait(), timeout=0.5)
|
||||
await asyncio.wait({shutdown}, timeout=0.01)
|
||||
assert not shutdown.done()
|
||||
with pytest.raises(RuntimeBusyError), admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("An expired or cancelled flow still owns its cleanup")
|
||||
finally:
|
||||
allow_cleanup.set()
|
||||
await shutdown
|
||||
|
||||
with admission.pause_if_idle(lambda: False):
|
||||
with pytest.raises(RuntimeMaintenanceError):
|
||||
await manager.start(
|
||||
"linear", _config(), "https://agent.example.com/auth/mcp/callback",
|
||||
reload_mcp=lambda: asyncio.sleep(0, result={"ok": True}),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_remote_http_flow_accepts_a_pasted_loopback_callback(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
manager = McpOAuthManager()
|
||||
manager = McpOAuthManager(RuntimeAdmission())
|
||||
connection = _Connection()
|
||||
received: dict[str, object] = {}
|
||||
|
||||
@@ -247,6 +315,7 @@ async def test_remote_http_flow_accepts_a_pasted_loopback_callback(
|
||||
assert result["status"] == "connected"
|
||||
assert result["completion_input"] == "callback_url"
|
||||
assert received["callback"] == ("oauth-code", "manual-state")
|
||||
await manager.close()
|
||||
assert connection.closed is True
|
||||
|
||||
|
||||
@@ -254,7 +323,7 @@ async def test_remote_http_flow_accepts_a_pasted_loopback_callback(
|
||||
async def test_browser_flow_surfaces_provider_denial_without_callback_description(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
manager = McpOAuthManager()
|
||||
manager = McpOAuthManager(RuntimeAdmission())
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.mcp_oauth_api.validate_url_target",
|
||||
lambda _url: (True, ""),
|
||||
@@ -300,7 +369,7 @@ async def test_browser_flow_blocks_unsafe_authorization_url(
|
||||
url_is_safe: bool,
|
||||
state: str,
|
||||
) -> None:
|
||||
manager = McpOAuthManager()
|
||||
manager = McpOAuthManager(RuntimeAdmission())
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.mcp_oauth_api.validate_url_target",
|
||||
lambda _url: (url_is_safe, "private address"),
|
||||
|
||||
@@ -1941,6 +1941,13 @@ def test_openai_codex_oauth_login_passes_configured_proxy(
|
||||
authorization_url = "https://auth.openai.com/oauth/authorize?state=test"
|
||||
remaining_seconds = 600
|
||||
expired = False
|
||||
has_pending_work = False
|
||||
|
||||
def start(self):
|
||||
pass
|
||||
|
||||
def wait_closed(self):
|
||||
pass
|
||||
|
||||
def cancel(self) -> None:
|
||||
captured["cancelled"] = True
|
||||
@@ -1954,7 +1961,7 @@ def test_openai_codex_oauth_login_passes_configured_proxy(
|
||||
return FakeFlow()
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.providers.openai_codex_oauth.start_openai_codex_oauth_login",
|
||||
"nanobot.providers.openai_codex_oauth.OpenAICodexOAuthLoginFlow",
|
||||
fake_start,
|
||||
)
|
||||
|
||||
@@ -1981,10 +1988,7 @@ def test_openai_codex_oauth_login_passes_configured_proxy(
|
||||
return None
|
||||
return SimpleNamespace(access="access-token")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.providers.openai_codex_oauth.complete_openai_codex_oauth_login",
|
||||
fake_complete,
|
||||
)
|
||||
monkeypatch.setattr(FakeFlow, "complete", fake_complete, raising=False)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.settings_api.settings_payload",
|
||||
lambda **_kwargs: {"settings": "ready"},
|
||||
@@ -2026,6 +2030,13 @@ def test_openai_codex_remote_login_uses_headless_dependency_mode(
|
||||
authorization_url = "https://auth.openai.com/oauth/authorize?state=test"
|
||||
remaining_seconds = 600
|
||||
expired = False
|
||||
has_pending_work = False
|
||||
|
||||
def start(self):
|
||||
pass
|
||||
|
||||
def wait_closed(self):
|
||||
pass
|
||||
|
||||
def cancel(self) -> None:
|
||||
captured["cancelled"] = True
|
||||
@@ -2035,7 +2046,7 @@ def test_openai_codex_remote_login_uses_headless_dependency_mode(
|
||||
return FakeFlow()
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.providers.openai_codex_oauth.start_openai_codex_oauth_login",
|
||||
"nanobot.providers.openai_codex_oauth.OpenAICodexOAuthLoginFlow",
|
||||
fake_start,
|
||||
)
|
||||
|
||||
@@ -2109,6 +2120,13 @@ def test_xai_grok_login_starts_fresh_browser_flow_with_proxy(
|
||||
authorization_url = "https://auth.x.ai/oauth2/authorize?state=test"
|
||||
remaining_seconds = 600
|
||||
expired = False
|
||||
has_pending_work = False
|
||||
|
||||
def start(self):
|
||||
pass
|
||||
|
||||
def wait_closed(self):
|
||||
pass
|
||||
|
||||
def cancel(self) -> None:
|
||||
captured["cancelled"] = True
|
||||
@@ -2117,7 +2135,7 @@ def test_xai_grok_login_starts_fresh_browser_flow_with_proxy(
|
||||
captured.update(proxy=proxy, timeout_s=timeout_s)
|
||||
return FakeFlow()
|
||||
|
||||
monkeypatch.setattr("nanobot.providers.xai_oauth.start_xai_oauth_login", fake_start)
|
||||
monkeypatch.setattr("nanobot.providers.xai_oauth.create_xai_oauth_login", fake_start)
|
||||
|
||||
payload = login_oauth_provider(
|
||||
{"provider": ["xai-grok"]},
|
||||
@@ -2140,10 +2158,7 @@ def test_xai_grok_login_starts_fresh_browser_flow_with_proxy(
|
||||
return None
|
||||
return SimpleNamespace(access="access-token")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.providers.xai_oauth.complete_xai_oauth_login",
|
||||
fake_complete,
|
||||
)
|
||||
monkeypatch.setattr(FakeFlow, "complete", fake_complete, raising=False)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.settings_api.settings_payload",
|
||||
lambda **_kwargs: {"settings": "ready"},
|
||||
@@ -2181,7 +2196,7 @@ def test_xai_grok_login_reports_upstream_failure_as_bad_gateway(
|
||||
def fake_start(**_kwargs):
|
||||
raise failure
|
||||
|
||||
monkeypatch.setattr("nanobot.providers.xai_oauth.start_xai_oauth_login", fake_start)
|
||||
monkeypatch.setattr("nanobot.providers.xai_oauth.create_xai_oauth_login", fake_start)
|
||||
|
||||
with pytest.raises(WebUISettingsError) as exc:
|
||||
login_oauth_provider(
|
||||
@@ -2391,7 +2406,7 @@ def test_copilot_explicit_login_does_not_reuse_revoked_credentials(monkeypatch,
|
||||
lambda: SimpleNamespace(access="revoked-token"),
|
||||
)
|
||||
monkeypatch.setattr(GitHubCopilotOAuthFlow, "start", start)
|
||||
monkeypatch.setattr(GitHubCopilotOAuthFlow, "complete", lambda _: SimpleNamespace(access="new-token"))
|
||||
monkeypatch.setattr(GitHubCopilotOAuthFlow, "complete", lambda *_: SimpleNamespace(access="new-token"))
|
||||
monkeypatch.setattr("nanobot.webui.settings_models.invalidate_oauth_model_catalog", invalidate)
|
||||
monkeypatch.setattr("nanobot.webui.settings_api.settings_payload", lambda **_: {"ready": True})
|
||||
payload = login_oauth_provider({"provider": ["github-copilot"]}, oauth_flows=oauth_flows)
|
||||
@@ -2429,17 +2444,18 @@ def test_oauth_completion_clears_same_account_catalog_failure(monkeypatch, oauth
|
||||
|
||||
class Flow:
|
||||
expired = False
|
||||
has_pending_work = False
|
||||
|
||||
def cancel(self):
|
||||
pass
|
||||
|
||||
def complete(*_args):
|
||||
signed_in[0] = True
|
||||
return SimpleNamespace(access="fixture")
|
||||
def wait_closed(self):
|
||||
pass
|
||||
|
||||
def complete(self, _response=None):
|
||||
signed_in[0] = True
|
||||
return SimpleNamespace(access="fixture")
|
||||
|
||||
owner = "openai_codex_oauth" if provider == "openai_codex" else "xai_oauth"
|
||||
completion = "complete_openai_codex_oauth_login" if provider == "openai_codex" else "complete_xai_oauth_login"
|
||||
monkeypatch.setattr(f"nanobot.providers.{owner}.{completion}", complete)
|
||||
oauth_flows.register(provider, "flow-test", Flow())
|
||||
before = provider_models_payload({"provider": [provider]})
|
||||
assert before["error_kind"] == "auth_required"
|
||||
|
||||
@@ -12,7 +12,10 @@ from urllib.parse import parse_qs, urlsplit
|
||||
import pytest
|
||||
from websockets.datastructures import Headers
|
||||
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.loader import get_config_path
|
||||
from nanobot.config.schema import MCPServerConfig
|
||||
from nanobot.runtime_admission import RuntimeBusyError
|
||||
from nanobot.webui.http_utils import http_json_response
|
||||
from nanobot.webui.mcp_presets_api import custom_mcp_action
|
||||
from nanobot.webui.settings_routes import WebUISettingsRouter
|
||||
@@ -35,8 +38,8 @@ def _router(
|
||||
rename_model_preset=rename_model_preset,
|
||||
refresh_runtime_config=refresh_runtime_config,
|
||||
),
|
||||
bus=SimpleNamespace(),
|
||||
logger=SimpleNamespace(exception=lambda *_args: None),
|
||||
bus=MessageBus(),
|
||||
logger=SimpleNamespace(exception=lambda *_args: None, warning=lambda *_args: None),
|
||||
check_api_token=lambda _request: authorized,
|
||||
parse_query=lambda path: parse_qs(urlsplit(path).query),
|
||||
json_response=http_json_response,
|
||||
@@ -61,12 +64,37 @@ def _mutation_request(path: str, payload: dict[str, object]) -> SimpleNamespace:
|
||||
return request
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_nanobot_update_requires_auth_local_permission_and_websocket(tmp_path, monkeypatch):
|
||||
router = _router(config_path=tmp_path / "config.json")
|
||||
path = "/api/settings/nanobot-update/job/prepare"
|
||||
request = SimpleNamespace(path=path, headers=Headers())
|
||||
response = await router.dispatch(None, request, path)
|
||||
assert response.status_code == 405
|
||||
response = await router.dispatch(None, _mutation_request(path, {}), path)
|
||||
assert response.status_code == 403
|
||||
unauthorized = _router(authorized=False, config_path=tmp_path / "config.json")
|
||||
response = await unauthorized.dispatch(None, _mutation_request(path, {}), path)
|
||||
assert response.status_code == 401
|
||||
monkeypatch.setattr(router._system, "allow_feature_package_install", lambda _: True)
|
||||
response = await router.dispatch(None, _mutation_request(path, {"id": "invalid"}), path)
|
||||
assert response.status_code == 400
|
||||
router._runtime_surface = "native"
|
||||
response = await router.dispatch(None, _mutation_request(path, {}), path)
|
||||
assert response.status_code == 409
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_close_releases_channel_connectors() -> None:
|
||||
router = _router()
|
||||
closed = False
|
||||
|
||||
class Connector:
|
||||
has_pending_work = False
|
||||
|
||||
async def handle(self, action, query):
|
||||
return {}
|
||||
|
||||
async def close(self) -> None:
|
||||
nonlocal closed
|
||||
closed = True
|
||||
@@ -79,6 +107,162 @@ async def test_close_releases_channel_connectors() -> None:
|
||||
assert router._system._channel_connectors == {}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("finish", ["cancel", "logout", "shutdown"])
|
||||
async def test_provider_login_keeps_maintenance_busy_until_worker_exits(tmp_path, monkeypatch, finish):
|
||||
router = _router(config_path=tmp_path / "config.json")
|
||||
stopping, release = threading.Event(), threading.Event()
|
||||
saved = []
|
||||
|
||||
def login(*, on_authorization, cancelled, persist, **_kwargs):
|
||||
assert persist is False
|
||||
on_authorization("https://github.com/login/device", "FIXTURE", 60)
|
||||
assert cancelled.wait(3)
|
||||
stopping.set()
|
||||
assert release.wait(3)
|
||||
return SimpleNamespace(access="late-fixture-token")
|
||||
|
||||
monkeypatch.setattr("nanobot.providers.github_copilot_oauth.login_github_copilot", login)
|
||||
monkeypatch.setattr("nanobot.providers.github_copilot_provider.get_storage", lambda: SimpleNamespace(
|
||||
get_token_path=lambda: tmp_path / "copilot.json", save=saved.append,
|
||||
))
|
||||
monkeypatch.setattr("nanobot.webui.settings_api.settings_payload", lambda **_: {})
|
||||
path = "/api/settings/provider/oauth-login"
|
||||
response = await router.dispatch(None, _mutation_request(path, {"provider": "github_copilot"}), path)
|
||||
assert response.status_code == 200
|
||||
payload = json.loads(response.body)
|
||||
with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("The authorization prompt still has a live worker")
|
||||
try:
|
||||
if finish == "shutdown":
|
||||
shutdown = asyncio.create_task(router.close())
|
||||
assert await asyncio.to_thread(stopping.wait, 1)
|
||||
shutdown.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await shutdown
|
||||
else:
|
||||
path = (
|
||||
"/api/settings/provider/oauth-logout" if finish == "logout"
|
||||
else "/api/settings/provider/oauth-login/complete"
|
||||
)
|
||||
response = await router.dispatch(None, _mutation_request(path, {
|
||||
"provider": "github_copilot", "flow_id": payload["flow_id"], "cancel": "true",
|
||||
}), path)
|
||||
assert response.status_code == 200
|
||||
assert await asyncio.to_thread(stopping.wait, 1)
|
||||
assert router.settings.oauth_flows.get("github_copilot", payload["flow_id"]) is None
|
||||
with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Removing a login or cancelling its close awaiter cannot forget the thread")
|
||||
finally:
|
||||
release.set()
|
||||
await router.close()
|
||||
assert saved == []
|
||||
assert not router.settings.oauth_flows.has_pending_work
|
||||
with router.bus.admission.pause_if_idle(lambda: False):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_failed_codex_login_start_still_owns_late_worker(tmp_path, monkeypatch):
|
||||
import nanobot.providers.openai_codex_oauth as oauth
|
||||
|
||||
router = _router(config_path=tmp_path / "config.json")
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
target = tmp_path / "codex.json"
|
||||
monkeypatch.setenv("OAUTH_CLI_KIT_TOKEN_PATH", str(target))
|
||||
monkeypatch.setattr(oauth, "_AUTHORIZATION_URL_TIMEOUT_S", 0.02)
|
||||
|
||||
def login(*, storage, **_kwargs):
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
# The actual SDK can finish its token exchange after start() timed out.
|
||||
storage.save(SimpleNamespace(access="late-fixture-token"))
|
||||
|
||||
monkeypatch.setattr(oauth, "login_oauth_interactive", login)
|
||||
path = "/api/settings/provider/oauth-login"
|
||||
try:
|
||||
response = await router.dispatch(None, _mutation_request(path, {
|
||||
"provider": "openai_codex", "remote_browser": "true",
|
||||
}), path)
|
||||
assert response.status_code == 502
|
||||
assert entered.is_set()
|
||||
with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("A failed start must retain its background worker")
|
||||
finally:
|
||||
release.set()
|
||||
await router.close()
|
||||
assert not target.exists()
|
||||
with router.bus.admission.pause_if_idle(lambda: False):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("close_fails", [False, True])
|
||||
async def test_channel_setup_blocks_maintenance_until_confirmed_cleanup(
|
||||
tmp_path, monkeypatch, close_fails,
|
||||
) -> None:
|
||||
router = _router(config_path=tmp_path / "config.json")
|
||||
cleanup_started, allow_cleanup = asyncio.Event(), asyncio.Event()
|
||||
|
||||
class Connector:
|
||||
has_pending_work = True
|
||||
|
||||
async def handle(self, action, query):
|
||||
return {"status": "pending", "session_id": "test"}
|
||||
|
||||
async def close(self):
|
||||
cleanup_started.set()
|
||||
await allow_cleanup.wait()
|
||||
if close_fails:
|
||||
raise RuntimeError("native writer has not stopped")
|
||||
self.has_pending_work = False
|
||||
|
||||
connector = Connector()
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.settings_routes.load_channel_plugin",
|
||||
lambda _: SimpleNamespace(load_connector=lambda: connector),
|
||||
)
|
||||
path = "/api/settings/channels/whatsapp/connect/start"
|
||||
response = await router.dispatch(None, _mutation_request(path, {}), path)
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body)["status"] == "pending"
|
||||
with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Returning a QR code does not finish its connection")
|
||||
shutdown = asyncio.create_task(router.close())
|
||||
try:
|
||||
await asyncio.wait_for(cleanup_started.wait(), timeout=0.5)
|
||||
with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Cleanup still owns its pending connection")
|
||||
finally:
|
||||
allow_cleanup.set()
|
||||
await shutdown
|
||||
if close_fails:
|
||||
assert router._system._channel_connectors["whatsapp"] is connector
|
||||
with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("A failed close must not release ownership")
|
||||
close_fails = False
|
||||
await router.close()
|
||||
assert router._system._channel_connectors == {}
|
||||
with router.bus.admission.pause_if_idle(lambda: False):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_legacy_connector_can_connect_but_cannot_claim_maintenance_idle(tmp_path, monkeypatch):
|
||||
router = _router(config_path=tmp_path / "config.json")
|
||||
connector = SimpleNamespace(handle=AsyncMock(return_value={"status": "pending"}))
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.settings_routes.load_channel_plugin",
|
||||
lambda _: SimpleNamespace(load_connector=lambda: connector),
|
||||
)
|
||||
path = "/api/settings/channels/custom/connect/start"
|
||||
response = await router.dispatch(None, _mutation_request(path, {}), path)
|
||||
assert response.status_code == 200
|
||||
await router.close()
|
||||
with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("An untracked extension must not be assumed idle")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mcp_list_serializes_local_runtime_failure_snapshot(tmp_path) -> None:
|
||||
config_path = tmp_path / "config.json"
|
||||
@@ -222,6 +406,50 @@ async def test_mcp_reload_callback_is_bounded(
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_settings_shutdown_joins_browser_authorization_and_releases_admission(
|
||||
tmp_path, monkeypatch,
|
||||
) -> None:
|
||||
config = MCPServerConfig(type="streamableHttp", auth="oauth", url="https://mcp.example/mcp")
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.settings_routes.ensure_mcp_oauth_server",
|
||||
lambda _query, *, config_path=None: ("linear", config),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.webui.mcp_oauth_api.validate_url_target", lambda _: (True, ""))
|
||||
cleanup_started, allow_cleanup = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def connect(_servers, _registry, *, oauth_handlers):
|
||||
handlers = oauth_handlers["linear"]
|
||||
await handlers.redirect_handler("https://accounts.example/authorize?state=settings")
|
||||
try:
|
||||
await handlers.callback_handler()
|
||||
finally:
|
||||
cleanup_started.set()
|
||||
await allow_cleanup.wait()
|
||||
return {}
|
||||
|
||||
monkeypatch.setattr("nanobot.webui.mcp_oauth_api.connect_mcp_servers", connect)
|
||||
router = _router(config_path=tmp_path / "config.json")
|
||||
path = "/api/settings/mcp-oauth/start"
|
||||
response = await router.dispatch(None, _mutation_request(path, {"name": "linear"}), path)
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body)["status"] == "authorization_required"
|
||||
with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Settings returned, but authorization has not finished")
|
||||
|
||||
shutdown = asyncio.create_task(router.close())
|
||||
try:
|
||||
await asyncio.wait_for(cleanup_started.wait(), timeout=0.5)
|
||||
assert not shutdown.done()
|
||||
with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Settings shutdown must retain ownership through cleanup")
|
||||
finally:
|
||||
allow_cleanup.set()
|
||||
await shutdown
|
||||
with router.bus.admission.pause_if_idle(lambda: False):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mcp_oauth_start_uses_gateway_callback_and_requires_api_auth(monkeypatch) -> None:
|
||||
config = SimpleNamespace(
|
||||
@@ -554,7 +782,7 @@ async def test_version_check_route_returns_stable_payload(
|
||||
) -> None:
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.settings_routes.check_for_update",
|
||||
lambda: update_info,
|
||||
lambda: {"updateAvailable": update_info, "releaseStatus": {"state": "available" if update_info else "current"}},
|
||||
)
|
||||
request = SimpleNamespace(path="/api/settings/version-check", headers=Headers())
|
||||
|
||||
@@ -585,6 +813,45 @@ async def test_version_check_route_enforces_auth_and_bounds_failures(
|
||||
assert "upstream secret body" not in failed.body.decode()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("state", ["waiting_stable", "withdrawn", "unavailable", "publishing", "unsupported"])
|
||||
async def test_channel_status_is_explicit_and_old_clients_never_report_false_success(monkeypatch, state):
|
||||
result = {"updateAvailable": None, "releaseStatus": {
|
||||
"channel": "stable", "revision": 2, "currentVersion": "0.3.7.dev42", "state": state,
|
||||
}}
|
||||
monkeypatch.setattr("nanobot.webui.settings_routes.check_for_update", lambda: result)
|
||||
request = SimpleNamespace(path="/api/settings/version-check", headers=Headers())
|
||||
router = _router()
|
||||
response = await router.dispatch(None, request, request.path)
|
||||
assert response.status_code == 409
|
||||
request.path += "?channel_status=1"
|
||||
response = await router.dispatch(None, request, "/api/settings/version-check")
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body)["releaseStatus"] == result["releaseStatus"]
|
||||
assert response.headers["Cache-Control"] == "no-store"
|
||||
|
||||
|
||||
async def test_version_check_owner_is_additive_read_only_and_failure_is_not_a_release_failure(monkeypatch):
|
||||
from nanobot.webui import settings_system
|
||||
|
||||
result = {"updateAvailable": None, "releaseStatus": {"state": "current"}}
|
||||
monkeypatch.setattr("nanobot.webui.settings_routes.check_for_update", lambda: result)
|
||||
inspect_owner = MagicMock(return_value=SimpleNamespace(owner="pipx", records={}))
|
||||
monkeypatch.setattr(settings_system, "inspect_update_installation", inspect_owner)
|
||||
request = SimpleNamespace(path="/api/settings/version-check", headers=Headers())
|
||||
router = _router()
|
||||
legacy = await router.dispatch(None, request, "/api/settings/version-check")
|
||||
assert json.loads(legacy.body) == {"updateAvailable": None}
|
||||
inspect_owner.assert_not_called()
|
||||
request.path += "?channel_status=1"
|
||||
modern = await router.dispatch(None, request, "/api/settings/version-check")
|
||||
assert json.loads(modern.body)["installation_method"] == "pipx"
|
||||
inspect_owner.side_effect = ValueError("private receipt secret")
|
||||
unavailable = await router.dispatch(None, request, "/api/settings/version-check")
|
||||
body = json.loads(unavailable.body)
|
||||
assert body["installation_method"] is None and body["releaseStatus"] == result["releaseStatus"]
|
||||
assert "secret" not in unavailable.body.decode()
|
||||
|
||||
|
||||
async def test_runtime_config_route_authentication_validation_and_restart(tmp_path):
|
||||
from nanobot.config.loader import load_config
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ from nanobot.webui.settings_services import (
|
||||
|
||||
|
||||
class _Flow:
|
||||
has_pending_work = False
|
||||
|
||||
def __init__(self, *, expired: bool = False) -> None:
|
||||
self.expired = expired
|
||||
self.cancel_count = 0
|
||||
@@ -26,6 +28,12 @@ class _Flow:
|
||||
def cancel(self) -> None:
|
||||
self.cancel_count += 1
|
||||
|
||||
def wait_closed(self) -> None:
|
||||
pass
|
||||
|
||||
def complete(self, response=None):
|
||||
return None
|
||||
|
||||
|
||||
def _gateway(config_path: Path, workspace: Path):
|
||||
return build_gateway_services(
|
||||
@@ -243,3 +251,87 @@ def test_oauth_registry_preserves_expiry_capacity_completion_and_cancel() -> Non
|
||||
registry.clear("openai_codex")
|
||||
assert replacement.cancel_count == 1
|
||||
assert registry.get("openai_codex", "replacement") is None
|
||||
|
||||
|
||||
def test_oauth_registry_capacity_counts_cancelled_workers_until_exit():
|
||||
release = threading.Event()
|
||||
cancelled = threading.Event()
|
||||
|
||||
class ThreadFlow(_Flow):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.thread = threading.Thread(target=lambda: release.wait(3))
|
||||
|
||||
@property
|
||||
def has_pending_work(self):
|
||||
return self.thread.is_alive()
|
||||
|
||||
def cancel(self):
|
||||
cancelled.set()
|
||||
|
||||
def wait_closed(self):
|
||||
self.thread.join()
|
||||
|
||||
registry = WebUIOAuthFlowRegistry(max_flows=1)
|
||||
flow = ThreadFlow()
|
||||
registry.register("github_copilot", "first", flow)
|
||||
flow.thread.start()
|
||||
replacement = _Flow()
|
||||
try:
|
||||
with pytest.raises(RuntimeError, match="still stopping"):
|
||||
registry.register("github_copilot", "next", replacement)
|
||||
assert cancelled.is_set()
|
||||
assert registry.get("github_copilot", "first") is None
|
||||
assert registry.get("github_copilot", "next") is None
|
||||
assert registry.has_pending_work
|
||||
finally:
|
||||
release.set()
|
||||
flow.wait_closed()
|
||||
assert not registry.has_pending_work
|
||||
registry.register("github_copilot", "next", replacement)
|
||||
registry.close()
|
||||
with pytest.raises(RuntimeError, match="closing"):
|
||||
registry.register("github_copilot", "after-close", _Flow())
|
||||
|
||||
|
||||
def test_oauth_registry_keeps_flow_that_starts_while_cancellation_is_pending():
|
||||
cancelling, allow_cancel, release_worker = (threading.Event() for _ in range(3))
|
||||
|
||||
class StartingFlow(_Flow):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.thread = threading.Thread(target=lambda: release_worker.wait(3))
|
||||
|
||||
@property
|
||||
def has_pending_work(self):
|
||||
return self.thread.is_alive()
|
||||
|
||||
def cancel(self):
|
||||
cancelling.set()
|
||||
assert allow_cancel.wait(3)
|
||||
|
||||
def wait_closed(self):
|
||||
if self.thread.ident is not None:
|
||||
self.thread.join()
|
||||
|
||||
registry = WebUIOAuthFlowRegistry(max_flows=2)
|
||||
flow = StartingFlow()
|
||||
registry.register("github_copilot", "starting", flow)
|
||||
removal = threading.Thread(target=lambda: registry.remove("github_copilot", "starting", flow))
|
||||
removal.start()
|
||||
try:
|
||||
assert cancelling.wait(1)
|
||||
# Another request can register between register/start in the first login,
|
||||
# while its cancellation is waiting for the provider's commit lock.
|
||||
registry.register("xai_grok", "another", _Flow())
|
||||
flow.thread.start()
|
||||
allow_cancel.set()
|
||||
removal.join(timeout=1)
|
||||
assert not removal.is_alive()
|
||||
assert registry.has_pending_work
|
||||
finally:
|
||||
allow_cancel.set()
|
||||
release_worker.set()
|
||||
removal.join(timeout=2)
|
||||
flow.wait_closed()
|
||||
registry.close()
|
||||
@@ -0,0 +1,925 @@
|
||||
"""Authenticated, refresh-safe review and job reads; no installer or server process runs."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from packaging.tags import Tag
|
||||
from websockets.datastructures import Headers
|
||||
from websockets.http11 import Request
|
||||
|
||||
import nanobot
|
||||
from nanobot import update_plan, update_service
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.config.home import get_selected_home_path, set_home_path
|
||||
from nanobot.installation_lock import (
|
||||
InstallationBusyError,
|
||||
file_access,
|
||||
installation_access,
|
||||
installation_state_dir,
|
||||
pending_update_path,
|
||||
)
|
||||
from nanobot.release_feed import ReleaseFeed
|
||||
from nanobot.releases import release_filenames
|
||||
from nanobot.runtime_admission import RuntimeBusyError
|
||||
from nanobot.update_manager import ManagerPolicy
|
||||
from nanobot.update_plan import InstallationSnapshot, UpdatePlans
|
||||
from nanobot.update_process import PreparationProcess
|
||||
from nanobot.update_profiles import ObservedProfile, ProfileLaunch, ProfileReceipt
|
||||
from nanobot.update_worker import ExecutionConfirmation, JobStatus, Phase
|
||||
from nanobot.webui.client_contract import webui_contract
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
CREATE = "/api/settings/nanobot-update/plan/create"
|
||||
READ = "/api/settings/nanobot-update/plan"
|
||||
JOB = "/api/settings/nanobot-update/job"
|
||||
PREPARE = "settings.nanobot.update.prepare"
|
||||
SETTLE = "settings.nanobot.update.settle"
|
||||
EXECUTE = "settings.nanobot.update.execute"
|
||||
RETRY = "settings.nanobot.update.retry"
|
||||
CHANNEL = "settings.nanobot.update.channel"
|
||||
|
||||
|
||||
async def test_channel_mutation_preserves_authority_and_invalidates_old_reviews(preparation_gateway):
|
||||
from nanobot.update_channel import read_update_channel
|
||||
|
||||
fixture = preparation_gateway
|
||||
gateway, plan = await preparation_plan(fixture)
|
||||
# Plain HTTP cannot mutate; remote callers do not acquire install authority.
|
||||
response = await fetch(gateway, "/api/settings/nanobot-update/channel")
|
||||
assert response.status_code == 405
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(), CHANNEL, {"channel": "preview", "revision": 0})
|
||||
assert response.status_code == 403
|
||||
assert read_update_channel().revision == 0
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(local=True), CHANNEL, {"channel": "preview", "revision": 0})
|
||||
assert response.status_code == 200, response.body
|
||||
assert json.loads(response.body) == {"channel": "preview", "revision": 1}
|
||||
assert "webui.update-channels.v1" in webui_contract()["capabilities"]
|
||||
reviewed = await fetch(gateway, READ + "?id=" + plan.id)
|
||||
assert json.loads(reviewed.body)["plan"]["validity"] == "channel_changed"
|
||||
prepared = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
|
||||
assert prepared.status_code == 409
|
||||
assert not (fixture.directory / "jobs" / plan.id / "status.json").exists()
|
||||
# Stale tabs cannot overwrite the newer selection; native uses its distributor.
|
||||
assert (await gateway.http.dispatch_webui_mutation(connection(local=True), CHANNEL,
|
||||
{"channel": "stable", "revision": 0})).status_code == 409
|
||||
assert (await fixture.gateway("native").http.dispatch_webui_mutation(connection(local=True), CHANNEL,
|
||||
{"channel": "stable", "revision": 1})).status_code == 409
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [{"channel": "preview"}, {"channel": "beta", "revision": 0},
|
||||
{"channel": "preview", "revision": True},
|
||||
{"channel": "preview", "revision": 0, "url": "https://other.example"}])
|
||||
async def test_channel_mutation_validates_untrusted_requests(preparation_gateway, payload):
|
||||
gateway = preparation_gateway.gateway()
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(local=True), CHANNEL, payload)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
async def test_review_uses_saved_channel_and_rejects_a_change_during_discovery(preparation_gateway, monkeypatch):
|
||||
from nanobot.update_channel import UpdateChannelRequest
|
||||
|
||||
fixture = preparation_gateway
|
||||
gateway, stable = await preparation_plan(fixture)
|
||||
service = update_service.UpdateJobService()
|
||||
service.change_channel(UpdateChannelRequest(channel="preview", revision=0))
|
||||
observed = []
|
||||
race = False
|
||||
|
||||
class Feed:
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *_):
|
||||
pass
|
||||
|
||||
async def latest(self, channel):
|
||||
observed.append(channel)
|
||||
if race:
|
||||
service.change_channel(UpdateChannelRequest(channel="stable", revision=1))
|
||||
# Preview subscriptions can receive a final release too.
|
||||
return stable.target
|
||||
|
||||
monkeypatch.setattr(update_plan, "ReleaseFeed", lambda _: Feed())
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {"extras": []})
|
||||
assert response.status_code == 200
|
||||
saved = UpdatePlans(fixture.directory / "plans").load(json.loads(response.body)["plan"]["id"])
|
||||
assert (saved.channel, saved.channel_revision) == ("preview", 1)
|
||||
race = True
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {"extras": []})
|
||||
assert response.status_code == 409
|
||||
assert observed == ["preview", "preview"]
|
||||
assert not (fixture.directory / "jobs").exists()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def review_gateway(tmp_path, monkeypatch):
|
||||
account = tmp_path / "private account"
|
||||
monkeypatch.setattr(Path, "home", classmethod(lambda cls: account))
|
||||
previous_home = get_selected_home_path()
|
||||
set_home_path(tmp_path / "profile")
|
||||
environment = tmp_path / "tool environment"
|
||||
package = str(environment / "lib/nanobot/__init__.py")
|
||||
snapshot = InstallationSnapshot(
|
||||
environment=str(environment), python=str(environment / "bin/python"),
|
||||
package_path=package, running_package=package, installed_version="0.3.4",
|
||||
running_version="0.3.4", owner="uv", manager_version="0.11.16", records={"uv-receipt.toml": "a" * 64},
|
||||
manager=ManagerPolicy(manager="uv", backend="uv", source="registry", extras=["webui"]),
|
||||
)
|
||||
observed = []
|
||||
for number, state in enumerate(("running", "stopped")):
|
||||
root = tmp_path / f"profile-{number}"
|
||||
receipt = ProfileReceipt(
|
||||
id=str(number + 1) * 64, run_id=uuid4().hex, environment=str(environment),
|
||||
python=snapshot.python, package=package, version="0.3.4", home=str(root),
|
||||
data_dir=str(root), config=str(root / "config.json"), workspace=str(root / "project"),
|
||||
state_path=str(root / "run/gateway.json"), log_path=str(root / "log/gateway.log"),
|
||||
port=19000 + number, launch_mode="background", pid=os.getpid() + 10000 + number,
|
||||
process_identity=f"fixture-{number}", active=state == "running", stop_protocol=1,
|
||||
launch=ProfileLaunch(home=str(root), config_path=None, workspace=None,
|
||||
working_directory=str(root), verbose=False, lifetime="explicit"),
|
||||
)
|
||||
observed.append(ObservedProfile(receipt=receipt, state=state))
|
||||
monkeypatch.setattr(update_plan, "inspect_installation", lambda: snapshot)
|
||||
monkeypatch.setattr(update_plan, "inspect_profiles", lambda _: list(observed))
|
||||
requests = []
|
||||
|
||||
def release(request):
|
||||
requests.append(str(request.url))
|
||||
assert request.url.path == "/pypi/nanobot-ai/json"
|
||||
return httpx.Response(200, json={
|
||||
"info": {"name": "nanobot-ai", "version": "0.3.5", "requires_python": ">=3.11"},
|
||||
"urls": [{"filename": name, "size": 123, "digests": {"sha256": "b" * 64},
|
||||
"url": f"https://files.pythonhosted.org/packages/{name}", "yanked": False}
|
||||
for name in release_filenames("0.3.5") if name.endswith((".whl", ".tar.gz"))],
|
||||
})
|
||||
|
||||
monkeypatch.setattr(update_plan, "ReleaseFeed", lambda directory: ReleaseFeed(
|
||||
directory, transport=httpx.MockTransport(release), supported_tags=[Tag("py3", "none", "win_amd64")],
|
||||
))
|
||||
def gateway(surface="gateway"):
|
||||
return build_gateway_services(
|
||||
config=WebSocketConfig(), bus=MessageBus(), session_manager=None,
|
||||
static_dist_path=None, workspace_path=tmp_path / "workspace",
|
||||
default_restrict_to_workspace=True, config_path=tmp_path / "config.json",
|
||||
runtime_model_name=None, runtime_surface=surface, runtime_capabilities_overrides=None,
|
||||
)
|
||||
|
||||
try:
|
||||
yield SimpleNamespace(gateway=gateway, snapshot=snapshot, observed=observed,
|
||||
requests=requests, directory=installation_state_dir(environment))
|
||||
finally:
|
||||
set_home_path(previous_home)
|
||||
|
||||
|
||||
def connection(*, local=False):
|
||||
host = "127.0.0.1:8765" if local else "remote.example"
|
||||
return SimpleNamespace(remote_address=("127.0.0.1" if local else "192.0.2.1", 12345),
|
||||
request=Request("/ws", Headers({"Host": host, "Origin": f"http://{host}"})))
|
||||
|
||||
|
||||
async def fetch(gateway, path, *, authorized=True):
|
||||
headers = Headers()
|
||||
if authorized:
|
||||
headers["Authorization"] = f"Bearer {gateway.tokens.issue_api_token(60)}"
|
||||
return await gateway.http.dispatch(connection(), Request(path, headers))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def preparation_gateway(review_gateway, monkeypatch):
|
||||
fixture = review_gateway
|
||||
snapshot = fixture.snapshot.model_copy(update={"owner": "venv", "manager": None})
|
||||
monkeypatch.setattr(update_plan, "inspect_installation", lambda: snapshot)
|
||||
monkeypatch.setattr(sys, "prefix", snapshot.environment)
|
||||
fixture.snapshot = snapshot
|
||||
return fixture
|
||||
|
||||
|
||||
async def preparation_plan(fixture):
|
||||
gateway = fixture.gateway()
|
||||
response = await gateway.http.dispatch_webui_mutation(
|
||||
connection(local=True), "settings.nanobot.update.plan", {"extras": []},
|
||||
)
|
||||
assert response.status_code == 200, response.body
|
||||
return gateway, UpdatePlans(fixture.directory / "plans").load(json.loads(response.body)["plan"]["id"])
|
||||
|
||||
|
||||
async def execution_plan(fixture):
|
||||
gateway, original = await preparation_plan(fixture)
|
||||
active = original.profiles[0].model_copy(update={"receipt": original.profiles[0].receipt.model_copy(
|
||||
update={"pid": os.getpid()},
|
||||
)})
|
||||
plan = original.model_copy(update={"id": str(uuid4()), "profiles": [active, original.profiles[1]],
|
||||
"stop_profiles": [active.receipt.id], "restart_profiles": [active.receipt.id]})
|
||||
directory = fixture.directory / "jobs" / plan.id
|
||||
directory.mkdir(parents=True)
|
||||
(directory / "plan.json").write_text(plan.model_dump_json())
|
||||
JobStatus(plan.id, Phase.READY, 0, False, "Staged routing fixture", int(time.time())).save(directory)
|
||||
return gateway, plan, directory
|
||||
|
||||
|
||||
async def test_execution_consent_survives_cancelled_response_and_duplicate_requests(preparation_gateway, monkeypatch):
|
||||
fixture = preparation_gateway
|
||||
gateway, plan, directory = await execution_plan(fixture)
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
launches = []
|
||||
children = []
|
||||
confirmation = ExecutionConfirmation(uuid4().hex, plan.id, "a" * 64, plan.created_at, plan.expires_at)
|
||||
|
||||
def launch(path, *, once):
|
||||
assert path == directory and once
|
||||
launches.append(plan.id)
|
||||
confirmation.save(path)
|
||||
JobStatus(plan.id, Phase.CHECKING, 0, False, "Controlled launch", int(time.time())).save(path)
|
||||
entered.set()
|
||||
assert release.wait(5)
|
||||
child = subprocess.Popen([sys.executable, "-I", "-c", "import sys; sys.stdin.buffer.read()"],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
children.append(child)
|
||||
return child
|
||||
|
||||
monkeypatch.setattr(update_service, "start_handoff", launch)
|
||||
payload = {"id": plan.id, "confirm_restart": True}
|
||||
operation = asyncio.create_task(gateway.http.dispatch_webui_mutation(connection(local=True), EXECUTE, payload))
|
||||
try:
|
||||
async with asyncio.timeout(5):
|
||||
while not entered.is_set():
|
||||
await asyncio.sleep(0.001)
|
||||
operation.cancel()
|
||||
await asyncio.sleep(0)
|
||||
assert not operation.done(), "A lost requester cannot abandon a still-running launch thread"
|
||||
fresh = fixture.gateway()
|
||||
duplicate = await fresh.http.dispatch_webui_mutation(connection(local=True), EXECUTE, payload)
|
||||
assert duplicate.status_code == 200, duplicate.body
|
||||
assert duplicate.headers["Cache-Control"] == "no-store"
|
||||
saved = json.loads(duplicate.body)["job"]
|
||||
assert saved["execution_confirmation_id"] == confirmation.id
|
||||
assert saved["recorded_phase"] == "checking" and not saved["mutation_started"]
|
||||
restored = await fetch(fresh, JOB + "?id=" + plan.id)
|
||||
assert json.loads(restored.body)["job"] == saved
|
||||
finally:
|
||||
release.set()
|
||||
try:
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await operation
|
||||
assert gateway.http.settings_routes._system._update_jobs._reapers
|
||||
await asyncio.wait_for(gateway.http.settings_routes.close(), 5)
|
||||
assert children[0].poll() is None, "Gateway shutdown must not wait for its independent updater"
|
||||
finally:
|
||||
for child in children:
|
||||
child.stdin.close()
|
||||
assert await asyncio.to_thread(child.wait, 5) == 0
|
||||
assert launches == [plan.id]
|
||||
assert "webui.update-jobs.execute.v1" in webui_contract()["capabilities"]
|
||||
|
||||
|
||||
async def test_execution_requires_explicit_restart_and_existing_install_authority(preparation_gateway, monkeypatch):
|
||||
fixture = preparation_gateway
|
||||
gateway, plan, directory = await execution_plan(fixture)
|
||||
|
||||
def forbidden(*args, **kwargs):
|
||||
pytest.fail("Unconfirmed or unauthorized requests cannot launch an updater")
|
||||
|
||||
monkeypatch.setattr(update_service, "start_handoff", forbidden)
|
||||
assert (await fetch(gateway, JOB + "/execute")).status_code == 405
|
||||
payload = {"id": plan.id, "confirm_restart": True}
|
||||
assert (await gateway.http.dispatch_webui_mutation(connection(), EXECUTE, payload)).status_code == 403
|
||||
assert (await fixture.gateway("native").http.dispatch_webui_mutation(connection(local=True), EXECUTE, payload)).status_code == 409
|
||||
for bad in ({"id": plan.id}, {"id": plan.id, "confirm_restart": False},
|
||||
{"id": plan.id, "confirm_restart": "true"}, {"id": plan.id, "confirm_restart": 1},
|
||||
{**payload, "repair": True}, {**payload, "command": "pip install"}):
|
||||
result = await gateway.http.dispatch_webui_mutation(connection(local=True), EXECUTE, bad)
|
||||
assert result.status_code == 400
|
||||
assert ExecutionConfirmation.read(directory) is None
|
||||
|
||||
|
||||
async def test_retry_is_explicit_authorized_and_old_submissions_only_read_history(preparation_gateway, monkeypatch):
|
||||
fixture = preparation_gateway
|
||||
gateway, plan, directory = await execution_plan(fixture)
|
||||
previous = ExecutionConfirmation(uuid4().hex, plan.id, "a" * 64, plan.created_at, plan.expires_at)
|
||||
current = ExecutionConfirmation(uuid4().hex, plan.id, "a" * 64, plan.created_at, plan.expires_at)
|
||||
previous.save(directory)
|
||||
JobStatus(plan.id, Phase.HANDOFF_FAILED, 0, False, "Stopped before mutation", int(time.time())).save(directory)
|
||||
calls = []
|
||||
|
||||
def retry(path, previous_id):
|
||||
assert path == directory and previous_id == previous.id
|
||||
calls.append(previous_id)
|
||||
current.save(path)
|
||||
JobStatus(plan.id, Phase.CHECKING, 0, False, "Retry confirmed", int(time.time())).save(path)
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(update_service, "retry_handoff", retry)
|
||||
payload = {"id": plan.id, "previous_confirmation_id": previous.id, "confirm_restart": True}
|
||||
assert (await fetch(gateway, JOB + "/retry")).status_code == 405
|
||||
assert (await gateway.http.dispatch_webui_mutation(connection(), RETRY, payload)).status_code == 403
|
||||
assert (await fixture.gateway("native").http.dispatch_webui_mutation(connection(local=True), RETRY, payload)).status_code == 409
|
||||
for bad in ({"id": plan.id, "confirm_restart": True}, {**payload, "confirm_restart": False},
|
||||
{**payload, "previous_confirmation_id": "bad-id"}, {**payload, "repair": True},
|
||||
{**payload, "confirm_restart": "true"}):
|
||||
assert (await gateway.http.dispatch_webui_mutation(connection(local=True), RETRY, bad)).status_code == 400
|
||||
assert not calls
|
||||
first = await gateway.http.dispatch_webui_mutation(connection(local=True), RETRY, payload)
|
||||
assert first.status_code == 200, first.body
|
||||
assert first.headers["Cache-Control"] == "no-store"
|
||||
assert json.loads(first.body)["job"]["execution_confirmation_id"] == current.id
|
||||
fresh = fixture.gateway()
|
||||
for action, body in ((RETRY, payload), (EXECUTE, {"id": plan.id, "confirm_restart": True})):
|
||||
repeated = await fresh.http.dispatch_webui_mutation(connection(local=True), action, body)
|
||||
assert repeated.status_code == 200 and json.loads(repeated.body) == json.loads(first.body)
|
||||
assert calls == [previous.id]
|
||||
assert "webui.update-jobs.retry-handoff.v1" in webui_contract()["capabilities"]
|
||||
|
||||
|
||||
async def test_busy_retry_does_not_look_like_an_accepted_new_confirmation(preparation_gateway, monkeypatch):
|
||||
gateway, plan, directory = await execution_plan(preparation_gateway)
|
||||
previous = ExecutionConfirmation(uuid4().hex, plan.id, "a" * 64, plan.created_at, plan.expires_at)
|
||||
previous.save(directory)
|
||||
|
||||
def busy(*args):
|
||||
raise BlockingIOError("private lease path must not reach the response")
|
||||
|
||||
monkeypatch.setattr(update_service, "retry_handoff", busy)
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(local=True), RETRY,
|
||||
{"id": plan.id, "previous_confirmation_id": previous.id, "confirm_restart": True})
|
||||
assert response.status_code == 409
|
||||
assert b"private lease" not in response.body
|
||||
assert ExecutionConfirmation.read(directory) == previous
|
||||
|
||||
|
||||
async def test_handoff_settlement_route_preserves_permission_and_reads_cancelled_job(preparation_gateway, monkeypatch):
|
||||
from nanobot import update_stop
|
||||
|
||||
gateway, plan, directory = await execution_plan(preparation_gateway)
|
||||
previous = ExecutionConfirmation(uuid4().hex, plan.id, "a" * 64, plan.created_at, plan.expires_at)
|
||||
previous.save(directory)
|
||||
JobStatus(plan.id, Phase.HANDOFF_FAILED, 0, False, "Refused shutdown", plan.created_at).save(directory)
|
||||
calls = []
|
||||
|
||||
def settle(path):
|
||||
calls.append(path)
|
||||
assert path == directory
|
||||
state = JobStatus(plan.id, Phase.CANCELLED, 0, False, "Settled fixture", plan.created_at)
|
||||
state.save(path)
|
||||
return state
|
||||
|
||||
monkeypatch.setattr(update_stop, "settle_uncommitted_handoff", settle)
|
||||
assert (await gateway.http.dispatch_webui_mutation(connection(), SETTLE, {"id": plan.id})).status_code == 403
|
||||
assert calls == []
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id})
|
||||
assert response.status_code == 200, response.body
|
||||
assert json.loads(response.body)["job"]["recorded_phase"] == "cancelled"
|
||||
assert json.loads(response.body)["job"]["execution_confirmation_id"] == previous.id
|
||||
assert (await fetch(gateway, JOB + "?id=" + plan.id)).body == response.body
|
||||
assert calls == [directory]
|
||||
assert "webui.update-jobs.settle-handoff.v1" in webui_contract()["capabilities"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("problem", ["self_not_selected", "peer_not_selected", "no_restart"])
|
||||
async def test_execution_refuses_unreviewed_gateway_lifecycle(preparation_gateway, monkeypatch, problem):
|
||||
fixture = preparation_gateway
|
||||
gateway, plan, directory = await execution_plan(fixture)
|
||||
changes = {}
|
||||
if problem == "self_not_selected":
|
||||
changes["profiles"] = [plan.profiles[0].model_copy(update={"receipt": plan.profiles[0].receipt.model_copy(
|
||||
update={"pid": os.getpid() + 10000},
|
||||
)}), plan.profiles[1]]
|
||||
elif problem == "peer_not_selected":
|
||||
changes["profiles"] = [plan.profiles[0], plan.profiles[1].model_copy(update={"state": "running"})]
|
||||
else:
|
||||
changes["restart_profiles"] = []
|
||||
(directory / "plan.json").write_text(plan.model_copy(update=changes).model_dump_json())
|
||||
|
||||
def forbidden(*args, **kwargs):
|
||||
pytest.fail("Unsupported lifecycle cannot launch an updater")
|
||||
|
||||
monkeypatch.setattr(update_service, "start_handoff", forbidden)
|
||||
result = await gateway.http.dispatch_webui_mutation(connection(local=True), EXECUTE,
|
||||
{"id": plan.id, "confirm_restart": True})
|
||||
assert result.status_code == 409, result.body
|
||||
assert ExecutionConfirmation.read(directory) is None
|
||||
|
||||
|
||||
async def test_preparation_is_durable_idempotent_and_independent_of_browser(preparation_gateway, monkeypatch):
|
||||
fixture = preparation_gateway
|
||||
gateway, plan = await preparation_plan(fixture)
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
validated, prepared = [], []
|
||||
|
||||
async def revalidate(self, target):
|
||||
validated.append(target)
|
||||
|
||||
async def stage(exact, feed):
|
||||
prepared.append(exact)
|
||||
directory = fixture.directory / "jobs" / exact.id
|
||||
JobStatus(exact.id, Phase.PREPARING, 0, False, "Preparing", int(time.time())).save(directory)
|
||||
entered.set()
|
||||
await release.wait()
|
||||
JobStatus(exact.id, Phase.READY, 0, False, "Staged fixture", int(time.time())).save(directory)
|
||||
return directory
|
||||
|
||||
monkeypatch.setattr(update_service.ReleaseFeed, "revalidate", revalidate)
|
||||
monkeypatch.setattr(update_service, "prepare_job", stage)
|
||||
close = None
|
||||
try:
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
|
||||
assert response.status_code == 200, response.body
|
||||
assert json.loads(response.body)["job"]["recorded_phase"] == "preparation_requested"
|
||||
assert response.headers["Cache-Control"] == "no-store"
|
||||
directory = fixture.directory / "jobs" / plan.id
|
||||
assert JobStatus.read(directory).phase == Phase.PREPARATION_REQUESTED
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
# A recreated router has no reference to the original browser's task.
|
||||
fresh = fixture.gateway()
|
||||
duplicate = await fresh.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
|
||||
assert duplicate.status_code == 200
|
||||
assert json.loads(duplicate.body)["job"]["recorded_phase"] == "preparing"
|
||||
assert (await fetch(fresh, JOB + "?id=" + plan.id)).status_code == 200
|
||||
assert (await fresh.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id})).status_code == 409
|
||||
other = plan.model_copy(update={"id": str(uuid4())})
|
||||
UpdatePlans(fixture.directory / "plans").save(other)
|
||||
busy = await fresh.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": other.id})
|
||||
assert busy.status_code == 409
|
||||
assert not (fixture.directory / "jobs" / other.id).exists()
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with gateway.http.settings_routes._system._admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Preparation must be counted as runtime work")
|
||||
close = asyncio.create_task(gateway.http.settings_routes.close())
|
||||
async with asyncio.timeout(5):
|
||||
while not gateway.http.settings_routes._system._update_jobs._closing:
|
||||
await asyncio.sleep(0.001)
|
||||
close.cancel()
|
||||
await asyncio.sleep(0)
|
||||
assert not close.done(), "Shutdown cancellation must not release a running preparation"
|
||||
with pytest.raises(InstallationBusyError):
|
||||
with installation_access(updating=True):
|
||||
pytest.fail("Preparation lost its shared installation lease")
|
||||
finally:
|
||||
release.set()
|
||||
if close is not None:
|
||||
await asyncio.wait_for(close, 5)
|
||||
else:
|
||||
await gateway.http.settings_routes.close()
|
||||
final = await fetch(fixture.gateway(), JOB + "?id=" + plan.id)
|
||||
assert json.loads(final.body)["job"]["recorded_phase"] == "ready"
|
||||
assert validated == [plan.target] and prepared == [plan]
|
||||
assert len(fixture.requests) == 1, "The staging controller must not reselect latest"
|
||||
for name in ("approval.json", "handoff-approval.json"):
|
||||
assert not (directory / name).exists()
|
||||
assert not (fixture.directory / "stop.json").exists()
|
||||
assert "webui.update-jobs.prepare.v1" in webui_contract()["capabilities"]
|
||||
|
||||
|
||||
async def test_preparation_revalidation_failure_is_saved_and_never_retried_by_refresh(preparation_gateway, monkeypatch):
|
||||
fixture = preparation_gateway
|
||||
gateway, plan = await preparation_plan(fixture)
|
||||
targets = []
|
||||
|
||||
async def withdrawn(self, target):
|
||||
targets.append(target)
|
||||
raise ValueError("private-index-user:secret")
|
||||
|
||||
async def forbidden(*args):
|
||||
pytest.fail("A withdrawn target must not reach staging")
|
||||
|
||||
monkeypatch.setattr(update_service.ReleaseFeed, "revalidate", withdrawn)
|
||||
monkeypatch.setattr(update_service, "prepare_job", forbidden)
|
||||
accepted = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
|
||||
assert accepted.status_code == 200
|
||||
await gateway.http.settings_routes.close()
|
||||
duplicate = await fixture.gateway().http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
|
||||
assert duplicate.status_code == 200
|
||||
assert json.loads(duplicate.body)["job"]["recorded_phase"] == "preparation_failed"
|
||||
assert b"secret" not in duplicate.body
|
||||
directory = fixture.directory / "jobs" / plan.id
|
||||
assert "secret" not in (directory / "status.json").read_text()
|
||||
assert targets == [plan.target]
|
||||
assert not (directory / "request.json").exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation", [PREPARE, SETTLE])
|
||||
async def test_preparation_mutations_require_authority_and_exact_id(preparation_gateway, operation):
|
||||
fixture = preparation_gateway
|
||||
gateway, plan = await preparation_plan(fixture)
|
||||
path = JOB + ("/prepare" if operation == PREPARE else "/settle")
|
||||
assert (await fetch(gateway, path)).status_code == 405
|
||||
remote = await gateway.http.dispatch_webui_mutation(connection(), operation, {"id": plan.id})
|
||||
assert remote.status_code == 403
|
||||
desktop = await fixture.gateway("native").http.dispatch_webui_mutation(connection(local=True), operation, {"id": plan.id})
|
||||
assert desktop.status_code == 409
|
||||
for payload in ({}, {"id": "../plan"}, {"id": 12}, {"id": plan.id, "target": "new-version"},
|
||||
{"id": plan.id, "repair": True}):
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(local=True), operation, payload)
|
||||
assert response.status_code == 400
|
||||
assert not (fixture.directory / "jobs").exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("problem", ["expired", "source", "unknown_extras", "foreign"])
|
||||
async def test_preparation_rejects_unexecutable_reviews_before_creating_work(preparation_gateway, problem):
|
||||
fixture = preparation_gateway
|
||||
gateway, plan = await preparation_plan(fixture)
|
||||
changes = {"id": str(uuid4())}
|
||||
if problem == "expired":
|
||||
changes.update(created_at=plan.created_at - 1800, expires_at=plan.expires_at - 1800)
|
||||
elif problem == "source":
|
||||
changes["installation"] = plan.installation.model_copy(update={"owner": "source"})
|
||||
elif problem == "unknown_extras":
|
||||
changes["extras"] = None
|
||||
else:
|
||||
changes["installation"] = plan.installation.model_copy(update={"environment": str(fixture.directory / "foreign")})
|
||||
invalid = plan.model_copy(update=changes)
|
||||
UpdatePlans(fixture.directory / "plans").save(invalid)
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": invalid.id})
|
||||
assert response.status_code == 409
|
||||
assert not (fixture.directory / "jobs").exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("phase", [Phase.PREPARATION_REQUESTED, Phase.PREPARING])
|
||||
async def test_explicit_settlement_checks_ownership_and_does_not_retry(preparation_gateway, monkeypatch, phase):
|
||||
fixture = preparation_gateway
|
||||
gateway, plan = await preparation_plan(fixture)
|
||||
directory = fixture.directory / "jobs" / plan.id
|
||||
directory.mkdir(parents=True)
|
||||
(directory / "plan.json").write_text(plan.model_dump_json())
|
||||
JobStatus(plan.id, phase, 0, False, "Interrupted fixture", int(time.time())).save(directory)
|
||||
if phase == Phase.PREPARING:
|
||||
PreparationProcess.create(directory, plan.installation.environment)
|
||||
|
||||
async def forbidden(*args):
|
||||
pytest.fail("Reading or settling interrupted staging cannot restart it")
|
||||
|
||||
monkeypatch.setattr(update_service.ReleaseFeed, "revalidate", forbidden)
|
||||
restored = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
|
||||
assert json.loads(restored.body)["job"]["recorded_phase"] == phase.value
|
||||
lock = "prepare-native.lock" if phase == Phase.PREPARING else "preparation-controller.lock"
|
||||
with file_access(fixture.directory / lock, exclusive=True):
|
||||
blocked = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id})
|
||||
assert blocked.status_code == 409
|
||||
assert JobStatus.read(directory).phase == phase
|
||||
settled = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id})
|
||||
assert settled.status_code == 200, settled.body
|
||||
assert json.loads(settled.body)["job"]["recorded_phase"] == "preparation_failed"
|
||||
if phase == Phase.PREPARING:
|
||||
assert PreparationProcess.load(directory).active is False
|
||||
assert not (directory / "request.json").exists()
|
||||
duplicate = await fixture.gateway().http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
|
||||
assert json.loads(duplicate.body)["job"]["recorded_phase"] == "preparation_failed"
|
||||
|
||||
|
||||
async def test_exact_review_survives_router_recreation_without_reselection_or_install(review_gateway):
|
||||
fixture = review_gateway
|
||||
gateway = fixture.gateway()
|
||||
denied = await fetch(gateway, READ + "?id=" + str(uuid4()), authorized=False)
|
||||
assert denied.status_code == 401
|
||||
denied = await fetch(gateway, CREATE)
|
||||
assert denied.status_code == 405
|
||||
response = await gateway.http.dispatch_webui_mutation(
|
||||
connection(), "settings.nanobot.update.plan", {"channel": "stable", "restart_running": True},
|
||||
)
|
||||
assert response.status_code == 200, response.body
|
||||
assert response.headers["Cache-Control"] == "no-store"
|
||||
payload = json.loads(response.body)
|
||||
review = payload["plan"]
|
||||
assert payload["installation_allowed"] is False
|
||||
assert payload["execution_available"] is False
|
||||
assert (review["running_version"], review["target_version"], review["owner"]) == ("0.3.4", "0.3.5", "uv")
|
||||
assert review["extras"] == ["webui"] and review["validity"] == "current"
|
||||
assert review["guide"]["method"] == "uv"
|
||||
assert review["guide"]["host"] == review["host"]
|
||||
assert review["guide"]["environment"] == fixture.snapshot.environment
|
||||
assert [(item["reviewed_state"], item["stop"], item["restart"]) for item in review["profiles"]] == [
|
||||
("running", True, True), ("stopped", False, False),
|
||||
]
|
||||
assert {"records", "manager", "python", "url", "target"}.isdisjoint(review)
|
||||
saved = UpdatePlans(fixture.directory / "plans").load(review["id"])
|
||||
assert saved.stop_profiles == saved.restart_profiles == [fixture.observed[0].receipt.id]
|
||||
assert not (fixture.directory / "jobs").exists()
|
||||
assert not (fixture.directory / "stop.json").exists()
|
||||
assert fixture.requests == ["https://pypi.org/pypi/nanobot-ai/json"]
|
||||
|
||||
fresh_gateway = fixture.gateway()
|
||||
restored = await fetch(fresh_gateway, READ + "?id=" + review["id"])
|
||||
assert restored.headers["Cache-Control"] == "no-store"
|
||||
assert json.loads(restored.body) == payload
|
||||
assert len(fixture.requests) == 1, "Reading an existing review must not resolve a different latest target"
|
||||
assert "webui.update-plans.v1" in webui_contract()["capabilities"]
|
||||
|
||||
|
||||
async def test_live_update_review_requires_this_gateway_and_preserves_owner_policy(review_gateway):
|
||||
fixture = review_gateway
|
||||
running = fixture.observed[0]
|
||||
fixture.observed[0] = running.model_copy(update={"receipt": running.receipt.model_copy(update={"pid": os.getpid()})})
|
||||
gateway = fixture.gateway()
|
||||
response = await gateway.http.dispatch_webui_mutation(
|
||||
connection(local=True), "settings.nanobot.update.plan", {"restart_running": True},
|
||||
)
|
||||
payload = json.loads(response.body)
|
||||
assert payload["installation_allowed"] is True
|
||||
assert payload["execution_available"] is (os.name == "posix")
|
||||
assert payload["plan"]["extras"] == ["webui"]
|
||||
plan = UpdatePlans(fixture.directory / "plans").load(payload["plan"]["id"])
|
||||
assert update_plan.inline_update_blocked_reason(plan, "expired") == "review_changed"
|
||||
assert update_plan.inline_update_blocked_reason(plan.model_copy(update={"restart_profiles": []})) == (
|
||||
"external_restart" if os.name == "posix" else "installation_owner"
|
||||
)
|
||||
assert not (fixture.directory / "jobs").exists(), "Review must not prepare or install"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("manager_version", [None, "0.11.15", "0.11.17"])
|
||||
async def test_review_routes_unverified_uv_versions_to_the_installation_owner(review_gateway, monkeypatch, manager_version):
|
||||
fixture = review_gateway
|
||||
snapshot = fixture.snapshot.model_copy(update={"manager_version": manager_version})
|
||||
monkeypatch.setattr(update_plan, "inspect_installation", lambda: snapshot)
|
||||
running = fixture.observed[0]
|
||||
fixture.observed[0] = running.model_copy(update={"receipt": running.receipt.model_copy(update={"pid": os.getpid()})})
|
||||
response = await fixture.gateway().http.dispatch_webui_mutation(
|
||||
connection(local=True), "settings.nanobot.update.plan", {"restart_running": True},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = json.loads(response.body)
|
||||
assert payload["execution_available"] is False
|
||||
plan = UpdatePlans(fixture.directory / "plans").load(payload["plan"]["id"])
|
||||
assert update_plan.inline_update_blocked_reason(plan) == "installation_owner"
|
||||
assert not (fixture.directory / "jobs").exists()
|
||||
|
||||
|
||||
async def test_review_reports_profile_and_installation_changes_without_replacing_plan(review_gateway, monkeypatch):
|
||||
fixture = review_gateway
|
||||
gateway = fixture.gateway()
|
||||
created = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {})
|
||||
assert created.status_code == 200
|
||||
payload = json.loads(created.body)
|
||||
assert payload["installation_allowed"] is True
|
||||
review = payload["plan"]
|
||||
assert not any(item["stop"] or item["restart"] for item in review["profiles"])
|
||||
saved_bytes = (fixture.directory / "plans" / f"{review['id']}.json").read_bytes()
|
||||
fixture.observed[0] = fixture.observed[0].model_copy(update={
|
||||
"receipt": fixture.observed[0].receipt.model_copy(update={"run_id": uuid4().hex}),
|
||||
})
|
||||
response = await fetch(gateway, READ + "?id=" + review["id"])
|
||||
assert json.loads(response.body)["plan"]["validity"] == "profiles_changed"
|
||||
monkeypatch.setattr(update_plan, "inspect_installation", lambda: fixture.snapshot.model_copy(update={
|
||||
"installed_version": "0.3.5", "records": {"uv-receipt.toml": "c" * 64},
|
||||
}))
|
||||
response = await fetch(gateway, READ + "?id=" + review["id"])
|
||||
changed = json.loads(response.body)["plan"]
|
||||
assert changed["validity"] == "installation_changed"
|
||||
assert changed["installed_version"] == "0.3.5"
|
||||
assert (fixture.directory / "plans" / f"{review['id']}.json").read_bytes() == saved_bytes
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [
|
||||
{"channel": "dev"}, {"restart_running": "true"}, {"extras": ["--index-url"]},
|
||||
{"target": "https://untrusted.example/wheel"}, {"installation": "/another/tool"},
|
||||
])
|
||||
async def test_invalid_client_request_cannot_select_code_or_environment(review_gateway, payload):
|
||||
fixture = review_gateway
|
||||
response = await fixture.gateway().http.dispatch_webui_mutation(
|
||||
connection(), "settings.nanobot.update.plan", payload,
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert fixture.requests == []
|
||||
assert not (fixture.directory / "plans").exists()
|
||||
|
||||
|
||||
async def test_expired_unknown_and_foreign_plans_have_explicit_results(review_gateway, monkeypatch):
|
||||
fixture = review_gateway
|
||||
gateway = fixture.gateway()
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {})
|
||||
review = json.loads(response.body)["plan"]
|
||||
now = time.time()
|
||||
monkeypatch.setattr(update_plan.time, "time", lambda: now + 901)
|
||||
response = await fetch(gateway, READ + "?id=" + review["id"])
|
||||
assert json.loads(response.body)["plan"]["validity"] == "expired"
|
||||
missing = await fetch(gateway, READ + "?id=" + str(uuid4()))
|
||||
assert missing.status_code == 404
|
||||
traversal = await fetch(gateway, READ + "?id=../../config")
|
||||
assert traversal.status_code == 400
|
||||
other = fixture.snapshot.model_copy(update={"environment": str(fixture.directory / "other")})
|
||||
monkeypatch.setattr(update_plan, "inspect_installation", lambda: other)
|
||||
missing = await fetch(gateway, READ + "?id=" + review["id"])
|
||||
assert missing.status_code == 404
|
||||
|
||||
|
||||
async def test_desktop_and_failed_discovery_do_not_claim_executable_or_current(review_gateway, monkeypatch):
|
||||
fixture = review_gateway
|
||||
desktop = await fixture.gateway("native").http.dispatch_webui_mutation(
|
||||
connection(), "settings.nanobot.update.plan", {},
|
||||
)
|
||||
assert desktop.status_code == 409 and fixture.requests == []
|
||||
|
||||
def failed_probe():
|
||||
raise ValueError("https://user:secret@index.example/private")
|
||||
|
||||
monkeypatch.setattr(update_plan, "inspect_installation", failed_probe)
|
||||
failed = await fixture.gateway().http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {})
|
||||
assert failed.status_code == 409
|
||||
assert b"secret" not in failed.body
|
||||
assert not (fixture.directory / "plans").exists()
|
||||
|
||||
|
||||
async def test_environment_replaced_during_discovery_does_not_return_a_valid_review(review_gateway, monkeypatch):
|
||||
fixture = review_gateway
|
||||
calls = 0
|
||||
|
||||
def changed_probe():
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls == 1:
|
||||
return fixture.snapshot
|
||||
return fixture.snapshot.model_copy(update={"installed_version": "0.3.6"})
|
||||
|
||||
monkeypatch.setattr(update_plan, "inspect_installation", changed_probe)
|
||||
response = await fixture.gateway().http.dispatch_webui_mutation(
|
||||
connection(), "settings.nanobot.update.plan", {},
|
||||
)
|
||||
assert response.status_code == 409
|
||||
assert response.body == b"Could not verify an update plan for this installation. No update was started."
|
||||
assert calls == 2
|
||||
assert not (fixture.directory / "jobs").exists()
|
||||
|
||||
|
||||
async def test_missing_interpreter_is_not_misreported_as_a_missing_plan(review_gateway, monkeypatch):
|
||||
fixture = review_gateway
|
||||
gateway = fixture.gateway()
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {})
|
||||
plan_id = json.loads(response.body)["plan"]["id"]
|
||||
|
||||
def removed_python():
|
||||
raise FileNotFoundError("/private/installation/bin/python")
|
||||
|
||||
monkeypatch.setattr(update_plan, "inspect_installation", removed_python)
|
||||
failed = await fetch(gateway, READ + "?id=" + plan_id)
|
||||
assert failed.status_code == 409
|
||||
assert b"/private/installation" not in failed.body
|
||||
assert (fixture.directory / "plans" / f"{plan_id}.json").exists()
|
||||
|
||||
|
||||
async def test_job_reads_survive_refresh_expiry_and_unavailable_installation(review_gateway, monkeypatch):
|
||||
fixture = review_gateway
|
||||
gateway = fixture.gateway()
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {})
|
||||
plan_id = json.loads(response.body)["plan"]["id"]
|
||||
plan = UpdatePlans(fixture.directory / "plans").load(plan_id)
|
||||
directory = fixture.directory / "jobs" / plan_id
|
||||
directory.mkdir(parents=True)
|
||||
(directory / "plan.json").write_text(plan.model_dump_json())
|
||||
JobStatus(plan_id, Phase.PREPARING, 0, False, "private diagnostic", plan.created_at).save(directory)
|
||||
monkeypatch.setattr(sys, "prefix", fixture.snapshot.environment)
|
||||
|
||||
def unavailable_probe():
|
||||
pytest.fail("Reading a saved job must not launch the changing installation")
|
||||
|
||||
monkeypatch.setattr(update_plan, "inspect_installation", unavailable_probe)
|
||||
response = await fetch(gateway, JOB + "?id=" + plan_id, authorized=False)
|
||||
assert response.status_code == 401
|
||||
response = await fetch(gateway, JOB + "?id=" + plan_id)
|
||||
assert response.status_code == 200
|
||||
job = json.loads(response.body)["job"]
|
||||
recovery = job.pop("recovery_command")
|
||||
assert plan.id in recovery and recovery.endswith(" --repair")
|
||||
assert "recover.py" in recovery
|
||||
assert job == {
|
||||
"id": plan_id, "installation_id": fixture.snapshot.installation_id,
|
||||
"host": platform.node(), "previous_version": "0.3.4",
|
||||
"target_version": "0.3.5", "channel": "stable", "recorded_phase": "preparing",
|
||||
"attempt": 0, "mutation_started": False, "updated_at": plan.created_at,
|
||||
"execution_confirmation_id": None,
|
||||
"running_version": nanobot.__version__,
|
||||
"recovery_active": False,
|
||||
"service_restored": False,
|
||||
"automatic_recovery": False,
|
||||
}
|
||||
assert not (directory / "request.json").exists(), "An early journal must not require committed staging"
|
||||
assert "webui.update-jobs.read.v1" in webui_contract()["capabilities"]
|
||||
|
||||
# A journal is recoverable without revalidating the expired plan or reading
|
||||
# package metadata; it is not permission to retry or proof a worker is live.
|
||||
monkeypatch.setattr(update_plan.time, "time", lambda: plan.expires_at + 1)
|
||||
JobStatus(plan_id, Phase.FAILED, 1, True, "https://user:secret@private.example", plan.expires_at).save(directory)
|
||||
pending = pending_update_path()
|
||||
pending.parent.mkdir(parents=True)
|
||||
pending.write_text("interrupted update")
|
||||
with installation_access(updating=True):
|
||||
response = await fetch(fixture.gateway(), JOB + "?id=" + plan_id)
|
||||
assert response.status_code == 200
|
||||
assert response.headers["Cache-Control"] == "no-store"
|
||||
job = json.loads(response.body)["job"]
|
||||
assert job["recorded_phase"] == "failed" and job["mutation_started"] is True
|
||||
assert job["attempt"] == 1 and job["updated_at"] == plan.expires_at
|
||||
assert b"secret" not in response.body
|
||||
# Only the explicit recovery command exposes the launcher's exact location;
|
||||
# job diagnostics and profile paths must remain out of the status payload.
|
||||
assert job.pop("recovery_command") == recovery
|
||||
assert "private account" not in json.dumps(job)
|
||||
assert {"message", "running", "can_retry", "python", "url", "profiles"}.isdisjoint(job)
|
||||
assert len(fixture.requests) == 1
|
||||
assert not (directory / "approval.json").exists()
|
||||
|
||||
# A completed program restoration is not a successful installation. Keep
|
||||
# the legacy wire phase readable while exposing the precise new result.
|
||||
JobStatus(plan_id, Phase.RESTORED, 2, True, "Private recovery detail", plan.expires_at).save(directory)
|
||||
response = await fetch(fixture.gateway(), JOB + "?id=" + plan_id)
|
||||
job = json.loads(response.body)["job"]
|
||||
assert job["recorded_phase"] == "failed" and job["service_restored"] is True
|
||||
assert b"Private recovery detail" not in response.body
|
||||
|
||||
|
||||
async def test_job_reads_reject_missing_foreign_and_corrupt_records(review_gateway, monkeypatch):
|
||||
fixture = review_gateway
|
||||
gateway = fixture.gateway()
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {})
|
||||
plan_id = json.loads(response.body)["plan"]["id"]
|
||||
plan = UpdatePlans(fixture.directory / "plans").load(plan_id)
|
||||
monkeypatch.setattr(sys, "prefix", fixture.snapshot.environment)
|
||||
for query in ("", "?id=../../config", "?id=not-a-uuid"):
|
||||
assert (await fetch(gateway, JOB + query)).status_code == 400
|
||||
assert (await fetch(gateway, JOB + "?id=" + plan_id)).status_code == 404
|
||||
directory = fixture.directory / "jobs" / plan_id
|
||||
directory.mkdir(parents=True)
|
||||
(directory / "plan.json").write_text(plan.model_dump_json())
|
||||
(directory / "status.json").write_text('{"private":"secret"}')
|
||||
response = await fetch(gateway, JOB + "?id=" + plan_id)
|
||||
assert response.status_code == 409 and b"secret" not in response.body
|
||||
assert response.headers["Cache-Control"] == "no-store"
|
||||
JobStatus(plan_id, Phase.READY, 0, False, "Prepared", plan.created_at).save(directory)
|
||||
foreign = plan.model_copy(update={"installation": fixture.snapshot.model_copy(
|
||||
update={"environment": str(fixture.directory / "another installation")},
|
||||
)})
|
||||
(directory / "plan.json").write_text(foreign.model_dump_json())
|
||||
assert (await fetch(gateway, JOB + "?id=" + plan_id)).status_code == 409
|
||||
(directory / "plan.json").write_text(plan.model_dump_json())
|
||||
assert (await fetch(fixture.gateway("native"), JOB + "?id=" + plan_id)).status_code == 409
|
||||
monkeypatch.setattr(sys, "prefix", str(fixture.directory / "another installation"))
|
||||
assert (await fetch(gateway, JOB + "?id=" + plan_id)).status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reading", [False, True])
|
||||
async def test_cancelled_request_keeps_probe_lease_until_native_work_exits(review_gateway, monkeypatch, reading):
|
||||
fixture = review_gateway
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
|
||||
def native_probe():
|
||||
entered.set()
|
||||
assert release.wait(5), "The test did not settle its native probe"
|
||||
return fixture.snapshot
|
||||
|
||||
monkeypatch.setattr(update_plan, "inspect_installation", native_probe)
|
||||
task = asyncio.create_task(update_plan.read_release_plan(str(uuid4())) if reading
|
||||
else update_plan.preview_release_update("stable"))
|
||||
try:
|
||||
assert await asyncio.to_thread(entered.wait, 5)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
with pytest.raises(InstallationBusyError):
|
||||
with installation_access(updating=True):
|
||||
pytest.fail("Native inspection outlived its installation lease")
|
||||
assert fixture.requests == []
|
||||
finally:
|
||||
release.set()
|
||||
# Wait for the probe's actual lease release before restoring Path.home.
|
||||
async with asyncio.timeout(5):
|
||||
while True:
|
||||
try:
|
||||
with installation_access(updating=True):
|
||||
break
|
||||
except InstallationBusyError:
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("problem", ["unknown", "supervisor", "extras"])
|
||||
async def test_plan_cannot_invent_restart_ownership_or_replace_manager_extras(review_gateway, problem):
|
||||
fixture = review_gateway
|
||||
payload = {"restart_running": True}
|
||||
if problem == "unknown":
|
||||
fixture.observed[0] = fixture.observed[0].model_copy(update={"state": "unconfirmed"})
|
||||
elif problem == "supervisor":
|
||||
fixture.observed[0] = fixture.observed[0].model_copy(update={
|
||||
"receipt": fixture.observed[0].receipt.model_copy(update={"launch_mode": "foreground"}),
|
||||
})
|
||||
else:
|
||||
payload["extras"] = []
|
||||
response = await fixture.gateway().http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", payload)
|
||||
if problem == "extras":
|
||||
assert response.status_code == 409
|
||||
assert not (fixture.directory / "plans").exists()
|
||||
else:
|
||||
assert response.status_code == 200
|
||||
payload = json.loads(response.body)
|
||||
assert payload["execution_available"] is False
|
||||
assert payload["plan"]["execution_blocked_reason"] == (
|
||||
"external_restart" if os.name == "posix" else "installation_owner"
|
||||
)
|
||||
assert not any(profile["restart"] for profile in payload["plan"]["profiles"])
|
||||
@@ -1,64 +1,163 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
import hashlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from packaging.tags import Tag
|
||||
|
||||
import nanobot
|
||||
import nanobot.webui.version_check as version_check
|
||||
from nanobot.release_feed import CATALOGUE_URL, PYPI_URL, ReleaseFeed
|
||||
from nanobot.releases import (
|
||||
ReleaseArtifact,
|
||||
ReleaseCatalogue,
|
||||
ReleaseManifest,
|
||||
ReleasePointer,
|
||||
release_filenames,
|
||||
)
|
||||
from nanobot.update_channel import UpdateChannelRequest, read_update_channel
|
||||
from nanobot.update_service import UpdateJobService
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_version_cache(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(version_check, "_cache", (0.0, None))
|
||||
monkeypatch.setattr(version_check.time, "monotonic", lambda: 1_000.0)
|
||||
@pytest.fixture
|
||||
def releases(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path / "account"))
|
||||
monkeypatch.setattr(sys, "prefix", str(tmp_path / "installation"))
|
||||
monkeypatch.setattr(nanobot, "__version__", "0.3.6")
|
||||
state = SimpleNamespace(stable="0.3.6", preview="0.3.7.dev42", generation=1,
|
||||
withdrawn={}, partial=False, offline=False, incompatible=False, missing=False, requests=[])
|
||||
|
||||
def manifest(version):
|
||||
value = ReleaseManifest(version=version, source_commit="a" * 40, candidate_commit="b" * 40,
|
||||
requires_python=">=3.11", artifacts=[
|
||||
ReleaseArtifact(filename=name, size=123, sha256="c" * 64) for name in sorted(release_filenames(version))])
|
||||
payload = value.model_dump_json().encode()
|
||||
return ReleasePointer(version=version, candidate_commit=value.candidate_commit,
|
||||
manifest_sha256=hashlib.sha256(payload).hexdigest()), payload
|
||||
|
||||
def handler(request):
|
||||
state.requests.append(str(request.url))
|
||||
if state.offline:
|
||||
raise httpx.ConnectError("private proxy credential", request=request)
|
||||
if str(request.url) == CATALOGUE_URL:
|
||||
if state.missing:
|
||||
return httpx.Response(404)
|
||||
catalogue = ReleaseCatalogue(generation=state.generation, stable=manifest(state.stable)[0],
|
||||
preview=manifest(state.preview)[0], withdrawn=state.withdrawn)
|
||||
return httpx.Response(200, content=catalogue.model_dump_json())
|
||||
if str(request.url).startswith(PYPI_URL):
|
||||
version = state.stable
|
||||
files = [name for name in sorted(release_filenames(version)) if name.endswith((".whl", ".tar.gz"))]
|
||||
return httpx.Response(200, json={
|
||||
"info": {"name": "nanobot-ai", "version": version, "requires_python": ">=3.11"},
|
||||
"urls": [{"filename": name, "size": 123, "yanked": False, "digests": {"sha256": "c" * 64},
|
||||
"url": f"https://files.pythonhosted.org/packages/{name}"}
|
||||
for name in (files[:-1] if state.partial else files)],
|
||||
})
|
||||
version = request.url.path.split("/v", 1)[1].split("/", 1)[0]
|
||||
return httpx.Response(200, content=manifest(version)[1])
|
||||
|
||||
monkeypatch.setattr(version_check, "ReleaseFeed", lambda directory: ReleaseFeed(
|
||||
directory, transport=httpx.MockTransport(handler), python_version="3.11.4",
|
||||
supported_tags=[] if state.incompatible else [Tag("py3", "none", "win_amd64")],
|
||||
))
|
||||
return state
|
||||
|
||||
|
||||
def _pypi_response(latest: object) -> MagicMock:
|
||||
response = MagicMock()
|
||||
response.json.return_value = {"info": {"version": latest}}
|
||||
return response
|
||||
def select(channel):
|
||||
current = read_update_channel()
|
||||
return UpdateJobService().change_channel(UpdateChannelRequest(channel=channel, revision=current.revision))
|
||||
|
||||
|
||||
def test_version_check_reports_only_a_newer_release_and_caches_it(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
get = MagicMock(return_value=_pypi_response("1.3.0"))
|
||||
monkeypatch.setattr(version_check, "__version__", "1.2.0")
|
||||
monkeypatch.setattr(version_check.httpx, "get", get)
|
||||
|
||||
expected = {
|
||||
"currentVersion": "1.2.0",
|
||||
"latestVersion": "1.3.0",
|
||||
"pypiUrl": "https://pypi.org/project/nanobot-ai/",
|
||||
}
|
||||
assert version_check.check_for_update() == expected
|
||||
assert version_check.check_for_update() == expected
|
||||
get.assert_called_once_with(
|
||||
"https://pypi.org/pypi/nanobot-ai/json",
|
||||
timeout=5.0,
|
||||
follow_redirects=True,
|
||||
)
|
||||
def test_stable_preview_exit_wait_and_final_release(releases, monkeypatch):
|
||||
assert version_check.check_for_update()["releaseStatus"]["state"] == "current"
|
||||
assert CATALOGUE_URL not in releases.requests
|
||||
select("preview")
|
||||
result = version_check.check_for_update()
|
||||
assert result["updateAvailable"]["latestVersion"] == "0.3.7.dev42"
|
||||
monkeypatch.setattr(nanobot, "__version__", "0.3.7.dev42")
|
||||
releases.preview, releases.generation = "0.3.7.dev43", 2
|
||||
assert version_check.check_for_update()["updateAvailable"]["latestVersion"] == "0.3.7.dev43"
|
||||
select("stable")
|
||||
result = version_check.check_for_update()
|
||||
assert result["releaseStatus"]["state"] == "waiting_stable"
|
||||
assert result["updateAvailable"] is None
|
||||
releases.stable, releases.generation = "0.3.7", 3
|
||||
assert version_check.check_for_update()["updateAvailable"]["latestVersion"] == "0.3.7"
|
||||
assert read_update_channel().channel == "stable"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("latest", ["1.2.0", "1.1.9", "not-a-version", 42, None])
|
||||
def test_version_check_ignores_non_newer_or_invalid_releases(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
latest: object,
|
||||
) -> None:
|
||||
monkeypatch.setattr(version_check, "__version__", "1.2.0")
|
||||
monkeypatch.setattr(version_check.httpx, "get", lambda *_args, **_kwargs: _pypi_response(latest))
|
||||
|
||||
assert version_check.check_for_update() is None
|
||||
def test_preview_subscription_survives_final_release_and_next_cycle(releases, monkeypatch):
|
||||
select("preview")
|
||||
releases.stable = "0.3.7"
|
||||
monkeypatch.setattr(nanobot, "__version__", "0.3.7.dev42")
|
||||
assert version_check.check_for_update()["updateAvailable"]["latestVersion"] == "0.3.7"
|
||||
monkeypatch.setattr(nanobot, "__version__", "0.3.7")
|
||||
assert version_check.check_for_update()["releaseStatus"]["state"] == "current"
|
||||
assert read_update_channel().channel == "preview"
|
||||
releases.preview, releases.generation = "0.3.8.dev1", 2
|
||||
assert version_check.check_for_update()["updateAvailable"]["latestVersion"] == "0.3.8.dev1"
|
||||
|
||||
|
||||
def test_version_check_treats_network_failure_as_best_effort(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
get = MagicMock(side_effect=TimeoutError("offline"))
|
||||
monkeypatch.setattr(version_check.httpx, "get", get)
|
||||
def test_leaving_preview_can_find_a_newer_stable_when_catalogue_is_unavailable(releases, monkeypatch):
|
||||
select("preview")
|
||||
monkeypatch.setattr(nanobot, "__version__", "0.3.7.dev42")
|
||||
select("stable")
|
||||
releases.missing = True
|
||||
releases.stable = "0.3.7"
|
||||
result = version_check.check_for_update()
|
||||
assert result["updateAvailable"]["latestVersion"] == "0.3.7"
|
||||
assert result["releaseStatus"]["state"] == "available"
|
||||
assert read_update_channel().channel == "stable"
|
||||
# A broken Preview index cannot authorize a partial release or a downgrade,
|
||||
# or turn unverified withdrawal status into a green 'up to date'.
|
||||
releases.partial = True
|
||||
assert version_check.check_for_update()["updateAvailable"] is None
|
||||
releases.partial = False
|
||||
releases.stable = "0.3.6"
|
||||
result = version_check.check_for_update()
|
||||
assert result["updateAvailable"] is None
|
||||
assert result["releaseStatus"]["state"] == "unavailable"
|
||||
|
||||
assert version_check.check_for_update() is None
|
||||
|
||||
# Failures are not cached, so a later explicit check can recover.
|
||||
assert version_check.check_for_update() is None
|
||||
assert get.call_count == 2
|
||||
@pytest.mark.parametrize("replacement", ["older", "newer", "incompatible"])
|
||||
@pytest.mark.parametrize("channel", ["stable", "preview"])
|
||||
def test_withdrawn_running_preview_is_not_reported_up_to_date(releases, monkeypatch, replacement, channel):
|
||||
select(channel)
|
||||
monkeypatch.setattr(nanobot, "__version__", "0.3.7.dev42")
|
||||
releases.withdrawn = {"0.3.7.dev42": "Startup regression"}
|
||||
if replacement != "older":
|
||||
releases.preview = "0.3.7.dev43"
|
||||
releases.stable = "0.3.7"
|
||||
releases.incompatible = replacement == "incompatible"
|
||||
result = version_check.check_for_update()
|
||||
assert result["releaseStatus"]["state"] == "withdrawn"
|
||||
assert (result["updateAvailable"] is not None) == (replacement == "newer")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("problem,state", [("partial", "publishing"), ("offline", "unavailable"),
|
||||
("incompatible", "unsupported"), ("missing", "unavailable")])
|
||||
def test_unavailable_checks_have_feedback_and_can_recover(releases, problem, state):
|
||||
if problem == "missing":
|
||||
select("preview")
|
||||
setattr(releases, problem, True)
|
||||
result = version_check.check_for_update()
|
||||
assert result["updateAvailable"] is None
|
||||
assert result["releaseStatus"]["state"] == state
|
||||
assert "credential" not in str(result)
|
||||
setattr(releases, problem, False)
|
||||
assert version_check.check_for_update()["releaseStatus"]["state"] in {"current", "available"}
|
||||
|
||||
|
||||
def test_current_dev_does_not_implicitly_opt_in_and_older_target_is_not_offered(releases, monkeypatch):
|
||||
monkeypatch.setattr(nanobot, "__version__", "0.3.8.dev1")
|
||||
assert read_update_channel().channel == "stable"
|
||||
assert version_check.check_for_update()["releaseStatus"]["state"] == "waiting_stable"
|
||||
select("preview")
|
||||
result = version_check.check_for_update()
|
||||
assert result["updateAvailable"] is None
|
||||
assert result["releaseStatus"]["state"] == "ahead"
|
||||
Reference in new issue
Block a user