Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

34.2 KB
Raw Blame
"""Exercise real durable receipts plus asynchronous upstream/disconnect races."""
import asyncio
import json
import os
import sqlite3
from pathlib import Path
import sys

import pytest
from fastapi import FastAPI, HTTPException, Request
from fastapi.testclient import TestClient
from host_agent_client import AgentUnavailable

os.environ.setdefault("DASHBOARD_API_KEY", "dashboard-test-key")
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import pixel_chat_results as receipts
from routers import pixel
import pixel_chat_identity
from test_pixel import FakeClient, FakeResponse, ConnectedRequest, DisconnectedRequest, stream_body

OWNER = "dashboard-test-key"
IDENTITY = (receipts.owner_namespace(OWNER), "chat-test", "attempt-one")
FINAL = b'data: {"choices":[{"delta":{"content":"Saved result"}}]}\n\ndata: [DONE]\n\n'


@pytest.fixture
def store(tmp_path, monkeypatch):
    async def saved_identity(*_args, **_kwargs):
        return {"schemaVersion": 1, "revision": 1, "displayName": "Portal"}
    monkeypatch.setattr(pixel_chat_identity, "async_request_json", saved_identity)
    result = receipts.ChatResultStore(tmp_path / "receipts")
    monkeypatch.setattr(pixel, "_result_store", result)
    monkeypatch.setattr(pixel, "_result_tasks", {})
    monkeypatch.setattr(pixel, "_result_preflights", set())
    monkeypatch.setattr(pixel, "_result_stops", set())
    monkeypatch.setattr(pixel, "_result_abort_ack", set())
    monkeypatch.setenv("PIXEL_OPENWEBUI_KEY", "e" * 64)
    async def ready(): return None
    monkeypatch.setattr(pixel, "_model_readiness_issue", ready)
    yield result
    result.close()


def body(request="attempt-one", text="Do work"):
    return pixel.ChatStreamRequest(chat_id="chat-test", request_id=request, messages=[{"role":"user", "content":text}])


@pytest.mark.parametrize("payload,expected", [
    ({"error": "pixel_transition_in_progress"}, "rejected"),
    ({"error": "different_conflict"}, "interrupted"),
    ({"error": "pixel_transition_in_progress", "private": "secret"}, "interrupted"),
])
def test_admission_rejection_is_typed_terminal_and_replays_without_execution(store, monkeypatch, payload, expected):
    async def run():
        calls = []
        class Client(FakeClient):
            def stream(self, *args, **kwargs):
                calls.append(args)
                return super().stream(*args, **kwargs)
        monkeypatch.setattr(pixel.httpx, "AsyncClient", lambda **kw: Client(
            FakeResponse(status=409, chunks=[json.dumps(payload).encode()])))
        async def forbidden(*args):
            raise AssertionError("A rejected admission must not cancel or inspect an agent run")
        monkeypatch.setattr(pixel, "_cancel_edge_run", forbidden)
        monkeypatch.setattr(pixel, "pixel_chat_activity", forbidden)
        response = await pixel.pixel_chat_stream(Request({"type": "http"}), body(), OWNER)
        await asyncio.gather(*list(pixel._result_tasks.values()))
        data = await stream_body(response)
        assert store.get(IDENTITY)["state"] == expected
        assert (b'"code": "transition_in_progress"' in data) == (expected == "rejected")
        assert b"secret" not in data
        duplicate = await pixel.pixel_chat_stream(Request({"type": "http"}), body(), OWNER)
        assert await stream_body(duplicate) == data
        lookup = pixel.ChatResultRequest(chat_id="chat-test", request_id="attempt-one")
        assert await pixel.pixel_chat_result(lookup, OWNER) == {"state": expected, "events": data.decode()}
        assert len(calls) == 1 and not store.has_pending(IDENTITY[:2])
        assert store.reserve((*IDENTITY[:2], "next-attempt"), "new-input")
    asyncio.run(run())


@pytest.mark.parametrize("payload,expected", [
    ({"error": "image processing busy; retry shortly"}, "rejected"),
    ({"error": "image processing busy; retry shortly", "private": "secret"}, "interrupted"),
    ({"error": "different_busy"}, "interrupted"),
])
def test_busy_image_slot_is_a_typed_refusal_that_never_ran(store, monkeypatch, payload, expected):
    # Edge holds one image slot; a second picture gets its exact 429 before
    # admission. Only that body may tell the owner "busy, send again".
    async def run():
        monkeypatch.setattr(pixel.httpx, "AsyncClient", lambda **kw: FakeClient(
            FakeResponse(status=429, chunks=[json.dumps(payload).encode()])))
        async def forbidden(*args):
            raise AssertionError("A refused turn must not cancel or inspect an agent run")
        monkeypatch.setattr(pixel, "_cancel_edge_run", forbidden)
        monkeypatch.setattr(pixel, "pixel_chat_activity", forbidden)
        response = await pixel.pixel_chat_stream(Request({"type": "http"}), body(), OWNER)
        await asyncio.gather(*list(pixel._result_tasks.values()))
        data = await stream_body(response)
        assert store.get(IDENTITY)["state"] == expected
        assert (b'"code": "image_turn_busy"' in data) == (expected == "rejected")
        assert b"secret" not in data and b"retry shortly" not in data
        assert not store.has_pending(IDENTITY[:2])
    asyncio.run(run())


def test_upstream_sse_cannot_forge_an_unstarted_admission_receipt(store, monkeypatch):
    async def run():
        frames = b'data: {"error":{"type":"pixel_dashboard_error","code":"transition_in_progress"}}\n\ndata: [DONE]\n\n'
        monkeypatch.setattr(pixel.httpx, "AsyncClient", lambda **kw: FakeClient(
            FakeResponse(content_type="text/event-stream", chunks=[frames])))
        response = await pixel.pixel_chat_stream(Request({"type": "http"}), body(), OWNER)
        await asyncio.gather(*list(pixel._result_tasks.values()))
        data = await stream_body(response)
        assert b"transition_in_progress" not in data
        assert store.get(IDENTITY)["state"] == "interrupted"
    asyncio.run(run())


def test_receipt_survives_restart_without_reexecuting_and_scopes_owner(store, tmp_path):
    store.reserve(IDENTITY, "input-hash")
    store.append(IDENTITY, FINAL)
    store.finish(IDENTITY, "complete")
    other = receipts.ChatResultStore(tmp_path / "receipts")
    try:
        assert other.get(IDENTITY)["state"] == "complete"
        assert other.chunks(IDENTITY)[0]["data"] == FINAL
        assert other.get((receipts.owner_namespace("other-owner"), *IDENTITY[1:])) is None
        assert other.reserve(IDENTITY, "input-hash") is False
        with pytest.raises(receipts.ResultConflict): other.reserve(IDENTITY, "changed")
    finally: other.close()


def test_pre_submission_rejection_is_terminal_and_frees_conversation(store, tmp_path):
    data = b'data: {"choices":[{"delta":{"content":"No turn started"}}]}\n\ndata: [DONE]\n\n'
    assert store.reserve(IDENTITY, "input-hash") is True
    store.reject_before_submission(IDENTITY, data)
    assert store.get(IDENTITY)["state"] == "interrupted"
    assert store.chunks(IDENTITY)[0]["data"] == data
    assert store.has_pending(IDENTITY[:2]) is False
    with pytest.raises(receipts.ResultConflict):
        store.reject_before_submission(IDENTITY, data)
    assert store.reserve(IDENTITY, "input-hash") is False
    assert store.reserve((*IDENTITY[:2], "new-attempt"), "input-hash") is True
    other = receipts.ChatResultStore(tmp_path / "receipts")
    try:
        assert other.get(IDENTITY)["state"] == "interrupted"
        assert other.chunks(IDENTITY)[0]["data"] == data
    finally:
        other.close()


def test_stop_during_preflight_does_not_cancel_an_unrelated_native_run(store, monkeypatch):
    async def run():
        entered = asyncio.Event()
        release = asyncio.Event()
        async def identity(*_args, **_kwargs):
            entered.set()
            await release.wait()
            raise AgentUnavailable("relay offline")
        async def forbidden_cancel(*_args):
            raise AssertionError("No native cancellation before submission")
        async def forbidden_activity(*_args):
            raise AssertionError("A live preflight is not an unresolved native run")
        monkeypatch.setattr(pixel_chat_identity, "async_request_json", identity)
        monkeypatch.setattr(pixel, "_cancel_edge_run", forbidden_cancel)
        monkeypatch.setattr(pixel, "pixel_chat_activity", forbidden_activity)
        attempt = asyncio.create_task(pixel.pixel_chat_stream(ConnectedRequest(), body(), OWNER))
        await entered.wait()
        assert IDENTITY in pixel._result_preflights
        lookup = pixel.ChatResultRequest(chat_id="chat-test", request_id="attempt-one")
        assert await pixel.pixel_chat_result(lookup, OWNER) == {"state": "active", "events": ""}
        duplicate = await pixel.pixel_chat_stream(ConnectedRequest(), body(), OWNER)
        assert await pixel.pixel_chat_result(lookup, OWNER) == {"state": "active", "events": ""}
        assert await pixel.pixel_chat_cancel(
            pixel.ChatCancelRequest(chat_id="chat-test", request_id="attempt-one"), OWNER
        ) == {"aborted": False}
        release.set()
        with pytest.raises(HTTPException) as caught:
            await attempt
        assert caught.value.status_code == 503
        assert store.get(IDENTITY)["state"] == "interrupted"
        assert IDENTITY not in pixel._result_preflights
        assert not pixel._result_tasks
        assert b"Portal did not start this attempt." in await stream_body(duplicate)
        assert (await pixel.pixel_chat_result(lookup, OWNER))["state"] == "interrupted"
    asyncio.run(run())


def test_restart_does_not_adopt_or_duplicate_unfinished_work(store, tmp_path):
    store.reserve(IDENTITY, "hash")
    other = receipts.ChatResultStore(tmp_path / "receipts")
    try:
        assert other.get(IDENTITY)["state"] == "unresolved"
        with pytest.raises(receipts.ResultConflict): other.reserve((*IDENTITY[:2], "next"), "hash")
        other.finish(IDENTITY, "cancelled")
        assert other.reserve((*IDENTITY[:2], "next"), "hash") is True
    finally: other.close()


def test_bounds_preserve_existing_results_and_leave_room_for_terminal_error(store, monkeypatch):
    monkeypatch.setattr(receipts, "MAX_RESULT_BYTES", 5000)
    store.reserve(IDENTITY, "hash")
    store.append(IDENTITY, b"x" * 900)
    with pytest.raises(receipts.ResultCapacity): store.append(IDENTITY, b"overflow")
    store.append(IDENTITY, b"data: [DONE]\n\n", terminal=True)
    assert store.chunks(IDENTITY)[0]["data"] == b"x" * 900


@pytest.mark.skipif(os.name != "posix", reason="POSIX custody contract")
def test_unsafe_storage_paths_are_rejected(tmp_path):
    public = tmp_path / "public"
    public.mkdir(mode=0o755)
    with pytest.raises(ValueError): receipts.ChatResultStore(public)
    private = tmp_path / "private"
    private.mkdir(mode=0o700)
    target = tmp_path / "target"
    target.write_text("do not overwrite")
    (private / "results.sqlite3").symlink_to(target)
    with pytest.raises(ValueError): receipts.ChatResultStore(private)
    assert target.read_text() == "do not overwrite"


def test_disconnect_keeps_one_producer_and_replay_is_repeatable(store, monkeypatch):
    async def run():
        release = asyncio.Event()
        started = asyncio.Event()
        calls = []
        cancels = []
        class Upstream(FakeResponse):
            async def aiter_bytes(self):
                started.set()
                await release.wait()
                yield FINAL
        class Client(FakeClient):
            def stream(self, *args, **kwargs):
                calls.append((args, kwargs))
                return super().stream(*args, **kwargs)
        monkeypatch.setattr(pixel.httpx, "AsyncClient", lambda **kw: Client(Upstream(content_type="text/event-stream")))
        async def cancel(*args):
            cancels.append(args)
            return True
        monkeypatch.setattr(pixel, "_cancel_edge_run", cancel)
        response = await pixel.pixel_chat_stream(DisconnectedRequest(), body(), OWNER)
        await started.wait()
        assert await stream_body(response) == b""
        assert store.get(IDENTITY)["state"] == "active"
        duplicate = await pixel.pixel_chat_stream(ConnectedRequest(), body(), OWNER)
        assert len(calls) == 1
        assert calls[0][1]["json"]["model"] == "portal/default"
        with pytest.raises(HTTPException) as changed:
            await pixel.pixel_chat_stream(ConnectedRequest(), body(text="different"), OWNER)
        assert changed.value.status_code == 423
        release.set()
        await asyncio.gather(*list(pixel._result_tasks.values()))
        replay = await stream_body(duplicate)
        assert b"Saved result" in replay and b"[DONE]" in replay
        query = pixel.ChatResultRequest(chat_id="chat-test", request_id="attempt-one")
        first = await pixel.pixel_chat_result(query, OWNER)
        assert first == await pixel.pixel_chat_result(query, OWNER)
        assert first["state"] == "complete" and first["events"].encode() == replay
        assert await pixel.pixel_chat_result(query, "other-owner") == {"state":"unknown", "events":""}
        assert len(calls) == 1 and not cancels
    asyncio.run(run())


def test_stop_blocks_new_attempt_until_ack_and_stale_stop_never_cancels_successor(store, monkeypatch):
    async def run():
        started = asyncio.Event()
        cancelled = asyncio.Event()
        permit_cancel = asyncio.Event()
        cancel_entered = asyncio.Event()
        count = 0
        class Upstream(FakeResponse):
            async def aiter_bytes(self):
                started.set()
                try: await asyncio.Future()
                finally: cancelled.set()
                yield b""
        monkeypatch.setattr(pixel.httpx, "AsyncClient", lambda **kw: FakeClient(Upstream(content_type="text/event-stream")))
        async def cancel(*args):
            nonlocal count
            count += 1
            cancel_entered.set()
            await permit_cancel.wait()
            return True
        monkeypatch.setattr(pixel, "_cancel_edge_run", cancel)
        await pixel.pixel_chat_stream(ConnectedRequest(), body(), OWNER)
        await started.wait()
        query = pixel.ChatCancelRequest(chat_id="chat-test", request_id="attempt-one")
        stop = asyncio.create_task(pixel.pixel_chat_cancel(query, OWNER))
        await cancel_entered.wait()
        with pytest.raises(HTTPException): await pixel.pixel_chat_stream(ConnectedRequest(), body("two"), OWNER)
        permit_cancel.set()
        assert await stop == {"aborted":True}
        await cancelled.wait()
        await pixel.pixel_chat_stream(ConnectedRequest(), body("two"), OWNER)
        assert await pixel.pixel_chat_cancel(query, OWNER) == {"aborted":False}
        assert await pixel.pixel_chat_cancel(pixel.ChatCancelRequest(chat_id="chat-test"), OWNER) == {"aborted":False}
        assert count == 1
        assert await pixel.pixel_chat_cancel(pixel.ChatCancelRequest(chat_id="chat-test", request_id="two"), OWNER) == {"aborted":True}
    asyncio.run(run())


def test_result_and_cancel_require_owner_authentication(store):
    app = FastAPI()
    app.include_router(pixel.router)
    with TestClient(app) as client:
        for endpoint in ["result", "cancel"]:
            payload = {"chat_id":"chat-test", "request_id":"attempt-one"}
            assert client.post('/api/pixel/chat/'+endpoint, json=payload).status_code == 401
            assert client.post('/api/pixel/chat/'+endpoint, json=payload, headers={"Authorization":"Bearer wrong"}).status_code == 403


@pytest.mark.parametrize("ack", [True, False])
def test_interrupted_attempt_recovery_requires_native_confirmation(store, monkeypatch, ack):
    store.reserve(IDENTITY, "hash")
    store.append(IDENTITY, b"retained partial output")
    store.finish(IDENTITY, "interrupted")
    calls = []

    async def cancel(*args):
        calls.append(args)
        assert IDENTITY[:2] in pixel._result_stops
        with pytest.raises(HTTPException) as blocked:
            await pixel.pixel_chat_stream(ConnectedRequest(), body("next-attempt"), OWNER)
        assert blocked.value.status_code == 423
        return ack

    monkeypatch.setattr(pixel, "_cancel_edge_run", cancel)
    result = asyncio.run(pixel.pixel_chat_cancel(
        pixel.ChatCancelRequest(chat_id=IDENTITY[1], request_id=IDENTITY[2]), OWNER))
    assert result == {"aborted": ack}
    assert len(calls) == 1 and calls[0][-1] == IDENTITY[1]
    assert store.get(IDENTITY)["state"] == ("cancelled" if ack else "interrupted")
    assert store.chunks(IDENTITY)[0]["data"] == b"retained partial output"
    assert not pixel._result_stops


@pytest.mark.parametrize("successor_state", ["active", "complete", "interrupted", "cancelled"])
def test_stale_interrupted_attempt_never_aborts_successor(store, monkeypatch, successor_state):
    store.reserve(IDENTITY, "hash")
    store.finish(IDENTITY, "interrupted")
    successor = (*IDENTITY[:2], "newer-attempt")
    store.reserve(successor, "new-hash")
    if successor_state != "active":
        store.finish(successor, successor_state)

    async def cancel(*args):
        pytest.fail("Stale receipt must never reach native cancellation")

    monkeypatch.setattr(pixel, "_cancel_edge_run", cancel)
    assert asyncio.run(pixel.pixel_chat_cancel(
        pixel.ChatCancelRequest(chat_id=IDENTITY[1], request_id=IDENTITY[2]), OWNER)) == {"aborted": False}
    assert store.get(IDENTITY)["state"] == "interrupted"


@pytest.mark.parametrize("chat,attempt,owner", [
    ("foreign-chat", "attempt-one", OWNER),
    ("chat-test", "foreign-attempt", OWNER),
    ("chat-test", "attempt-one", "foreign-owner"),
])
def test_interrupted_recovery_keeps_exact_custody(store, monkeypatch, chat, attempt, owner):
    store.reserve(IDENTITY, "hash")
    store.finish(IDENTITY, "interrupted")

    async def cancel(*args):
        pytest.fail("Foreign receipt must never reach native cancellation")

    monkeypatch.setattr(pixel, "_cancel_edge_run", cancel)
    assert asyncio.run(pixel.pixel_chat_cancel(
        pixel.ChatCancelRequest(chat_id=chat, request_id=attempt), owner)) == {"aborted": False}


def test_interrupted_confirmation_rechecks_latest_without_trusting_wall_clock(store, monkeypatch):
    monkeypatch.setattr(receipts.time, "time", lambda: 200)
    store.reserve(IDENTITY, "hash")
    store.finish(IDENTITY, "interrupted")
    assert store.is_latest(IDENTITY)
    monkeypatch.setattr(receipts.time, "time", lambda: 100)
    successor = (*IDENTITY[:2], "next-attempt")
    store.reserve(successor, "hash-next")
    store.finish(successor, "complete")
    assert not store.confirm_interrupted_cancel(IDENTITY)
    assert not store.confirm_interrupted_cancel(successor)
    assert store.get(IDENTITY)["state"] == "interrupted"
    assert store.get(successor)["state"] == "complete"


@pytest.mark.parametrize("ack", [True, False])
def test_truncated_upstream_retains_error_and_does_not_release_unknown_native_work(store, monkeypatch, ack):
    async def run():
        monkeypatch.setattr(pixel.httpx, "AsyncClient", lambda **kw: FakeClient(FakeResponse(content_type="text/event-stream", chunks=[b'data: {"choices":[{"delta":{"content":"partial"}}]}\n\n'])))
        async def cancel(*args): return ack
        monkeypatch.setattr(pixel, "_cancel_edge_run", cancel)
        await pixel.pixel_chat_stream(ConnectedRequest(), body(), OWNER)
        await asyncio.gather(*list(pixel._result_tasks.values()))
        assert store.get(IDENTITY)["state"] == ("interrupted" if ack else "unresolved")
        assert store.has_pending(IDENTITY[:2]) is not ack
        data = b''.join(row['data'] for row in store.chunks(IDENTITY))
        assert b'partial' in data and b'pixel_dashboard_error' in data and b'[DONE]' in data
    asyncio.run(run())


@pytest.mark.parametrize("chunks", [
    [FINAL],
    [FINAL[:-7], FINAL[-7:]],
    [FINAL[:-1]],
])
def test_retained_success_replays_one_well_framed_terminal_done(store, monkeypatch, chunks):
    """The owner-facing retained stream and replay must end in a full SSE frame."""
    async def run():
        monkeypatch.setattr(pixel.httpx, "AsyncClient", lambda **kw: FakeClient(
            FakeResponse(content_type="text/event-stream", chunks=chunks)))
        response = await pixel.pixel_chat_stream(ConnectedRequest(), body(), OWNER)
        await asyncio.gather(*list(pixel._result_tasks.values()))
        live = await stream_body(response)
        result = await pixel.pixel_chat_result(
            pixel.ChatResultRequest(chat_id="chat-test", request_id="attempt-one"), OWNER)
        assert result["state"] == "complete"
        assert live == result["events"].encode()
        assert live.endswith(b"data: [DONE]\n\n")
        assert live.count(b"data: [DONE]") == 1

    asyncio.run(run())


def test_terminal_upstream_error_is_replayable_but_never_complete(store, monkeypatch):
    async def run():
        terminal_error = b'data: {"error":"upstream error"}\n\ndata: [DONE]\n\n'
        monkeypatch.setattr(
            pixel.httpx,
            "AsyncClient",
            lambda **kw: FakeClient(
                FakeResponse(content_type="text/event-stream", chunks=[terminal_error])
            ),
        )
        cancels = []

        async def cancel(*args):
            cancels.append(args)
            return True

        monkeypatch.setattr(pixel, "_cancel_edge_run", cancel)
        await pixel.pixel_chat_stream(ConnectedRequest(), body(), OWNER)
        await asyncio.gather(*list(pixel._result_tasks.values()))

        result = await pixel.pixel_chat_result(
            pixel.ChatResultRequest(chat_id="chat-test", request_id="attempt-one"),
            OWNER,
        )
        assert result == {
            "state": "interrupted",
            "events": 'data: {"error":"upstream error"}\n\ndata: [DONE]\n\n',
        }
        assert not store.has_pending(IDENTITY[:2])
        assert not cancels

    asyncio.run(run())


@pytest.mark.parametrize("ack", [True, False])
def test_edge_abort_ack_survives_empty_done_during_cancel_round_trip(store, monkeypatch, ack):
    """A real Edge abort can race its empty DONE through the retained producer."""
    async def run():
        started = asyncio.Event()
        release_done = asyncio.Event()
        cancel_entered = asyncio.Event()

        class Upstream(FakeResponse):
            async def aiter_bytes(self):
                started.set()
                await release_done.wait()
                yield b"data: [DONE]\n\n"

        monkeypatch.setattr(pixel.httpx, "AsyncClient", lambda **kw: FakeClient(
            Upstream(content_type="text/event-stream")))

        async def cancel(*args):
            cancel_entered.set()
            release_done.set()
            await asyncio.gather(*list(pixel._result_tasks.values()))
            return ack

        monkeypatch.setattr(pixel, "_cancel_edge_run", cancel)
        await pixel.pixel_chat_stream(ConnectedRequest(), body(), OWNER)
        await started.wait()
        stop = asyncio.create_task(pixel.pixel_chat_cancel(
            pixel.ChatCancelRequest(chat_id="chat-test", request_id="attempt-one"), OWNER))
        await cancel_entered.wait()
        assert await stop == {"aborted": ack}
        assert store.get(IDENTITY)["state"] == ("cancelled" if ack else "unresolved")
        assert store.has_pending(IDENTITY[:2]) is not ack
        assert b"Portal returned no answer" in b"".join(
            row["data"] for row in store.chunks(IDENTITY))

    asyncio.run(run())


@pytest.mark.parametrize("ack", [True, False, "raises", "cancelled"])
def test_edge_abort_ack_survives_upstream_error_during_cancel_round_trip(store, monkeypatch, ack):
    """The producer can commit interrupted before native Stop returns its ack."""
    class ConnectedCancellationRequest(Request):
        async def is_disconnected(self) -> bool:
            return False

    async def run():
        started = asyncio.Event()
        release_error = asyncio.Event()
        calls = []

        class Upstream(FakeResponse):
            async def aiter_bytes(self):
                yield b'data: {"choices":[{"delta":{"content":"Saved partial work"}}]}\n\n'
                started.set()
                await release_error.wait()
                yield b'data: {"error":"upstream error"}\n\ndata: [DONE]\n\n'

        monkeypatch.setattr(pixel.httpx, "AsyncClient", lambda **kw: FakeClient(
            Upstream(content_type="text/event-stream")))

        async def cancel(*args):
            calls.append(args)
            release_error.set()
            await asyncio.gather(*list(pixel._result_tasks.values()))
            assert store.get(IDENTITY)["state"] == "interrupted"
            pending = await pixel.pixel_chat_result(
                pixel.ChatResultRequest(chat_id="chat-test", request_id="attempt-one"), OWNER)
            assert pending == {"state": "active", "events": ""}
            with pytest.raises(HTTPException):
                await pixel.pixel_chat_stream(ConnectedCancellationRequest({"type": "http"}), body("successor"), OWNER)
            if ack == "raises":
                raise RuntimeError("native cancellation failed")
            if ack == "cancelled":
                raise asyncio.CancelledError
            return ack

        monkeypatch.setattr(pixel, "_cancel_edge_run", cancel)
        await pixel.pixel_chat_stream(ConnectedCancellationRequest({"type": "http"}), body(), OWNER)
        await started.wait()
        query = pixel.ChatCancelRequest(chat_id="chat-test", request_id="attempt-one")
        if ack in {"raises", "cancelled"}:
            error = RuntimeError if ack == "raises" else asyncio.CancelledError
            with pytest.raises(error):
                await pixel.pixel_chat_cancel(query, OWNER)
        else:
            assert await pixel.pixel_chat_cancel(query, OWNER) == {"aborted": ack}
        assert not pixel._result_stops
        assert not pixel._result_abort_ack
        result = await pixel.pixel_chat_result(
            pixel.ChatResultRequest(chat_id="chat-test", request_id="attempt-one"), OWNER)
        assert result["state"] == ("cancelled" if ack is True else "interrupted")
        assert "Saved partial work" in result["events"] and '"error":"upstream error"' in result["events"]
        successor = (*IDENTITY[:2], "successor")
        store.reserve(successor, "new-work")
        assert await pixel.pixel_chat_cancel(query, OWNER) == {"aborted": False}
        assert store.get(successor)["state"] == "active"
        assert len(calls) == 1

    asyncio.run(run())


@pytest.mark.parametrize("state", ["complete", "cancelled"])
def test_pending_stop_never_hides_a_confirmed_terminal_receipt(store, state):
    store.reserve(IDENTITY, "first")
    store.append(IDENTITY, FINAL)
    store.finish(IDENTITY, state)
    pixel._result_stops.add(IDENTITY[:2])
    result = asyncio.run(pixel.pixel_chat_result(
        pixel.ChatResultRequest(chat_id="chat-test", request_id="attempt-one"), OWNER))
    assert result == {"state": state, "events": FINAL.decode()}


def test_pending_successor_stop_never_changes_an_older_interrupted_receipt(store):
    store.reserve(IDENTITY, "first")
    store.append(IDENTITY, FINAL)
    store.finish(IDENTITY, "interrupted")
    store.reserve((*IDENTITY[:2], "successor"), "next")
    pixel._result_stops.add(IDENTITY[:2])
    result = asyncio.run(pixel.pixel_chat_result(
        pixel.ChatResultRequest(chat_id="chat-test", request_id="attempt-one"), OWNER))
    assert result == {"state": "interrupted", "events": FINAL.decode()}


@pytest.mark.parametrize("chunks", [
    [b"data: [DONE]\n\n"],
    [b'data: {"choices":[{"delta":{"role":"assistant"}}]}\n\n', b"data: [DONE]\n\n"],
])
def test_done_without_user_answer_is_never_a_complete_receipt(store, monkeypatch, chunks):
    """Five live Tower1 cancel attempts had aborted, zero-token Pixel sessions.

    Edge supplied only DONE while ODS previously published complete. A
    terminal SSE marker alone must not become a successful saved answer.
    """
    async def run():
        monkeypatch.setattr(pixel.httpx, "AsyncClient", lambda **kw: FakeClient(
            FakeResponse(content_type="text/event-stream", chunks=chunks)))
        cancels = []
        async def cancel(*args):
            cancels.append(args)
            return False
        monkeypatch.setattr(pixel, "_cancel_edge_run", cancel)
        await pixel.pixel_chat_stream(ConnectedRequest(), body(), OWNER)
        await asyncio.gather(*list(pixel._result_tasks.values()))
        result = await pixel.pixel_chat_result(
            pixel.ChatResultRequest(chat_id="chat-test", request_id="attempt-one"), OWNER)
        assert result["state"] == "interrupted"
        assert "Portal returned no answer" in result["events"]
        assert result["events"].count("[DONE]") == 1
        assert not store.has_pending(IDENTITY[:2])
        assert not cancels
        assert await pixel.pixel_chat_cancel(
            pixel.ChatCancelRequest(chat_id="chat-test", request_id="attempt-one"), OWNER
        ) == {"aborted": False}
        assert len(cancels) == 1
        assert store.get(IDENTITY)["state"] == "interrupted"
    asyncio.run(run())


def test_done_with_tool_call_delta_is_a_complete_receipt(store, monkeypatch):
    """When a model generates tool_calls without text content, it must be recognized as an answer."""
    async def run():
        tool_chunk = b'data: {"choices":[{"delta":{"tool_calls":[{"id":"call_1","type":"function","function":{"name":"search","arguments":"{}"}}]}}]}\n\n'
        done_chunk = b"data: [DONE]\n\n"
        monkeypatch.setattr(pixel.httpx, "AsyncClient", lambda **kw: FakeClient(
            FakeResponse(content_type="text/event-stream", chunks=[tool_chunk, done_chunk])))
        cancels = []
        async def cancel(*args):
            cancels.append(args)
            return False
        monkeypatch.setattr(pixel, "_cancel_edge_run", cancel)
        await pixel.pixel_chat_stream(ConnectedRequest(), body(), OWNER)
        await asyncio.gather(*list(pixel._result_tasks.values()))
        result = await pixel.pixel_chat_result(
            pixel.ChatResultRequest(chat_id="chat-test", request_id="attempt-one"), OWNER)
        assert result["state"] == "complete"
        assert "call_1" in result["events"]
        assert "Portal returned no answer" not in result["events"]
        assert not store.has_pending(IDENTITY[:2])
        assert not cancels
    asyncio.run(run())



def test_terminal_write_failure_still_releases_known_stopped_attempt(store, monkeypatch):
    async def run():
        append = store.append
        def failing_append(key, data, **kwargs):
            if kwargs.get('terminal'): raise sqlite3.OperationalError('disk full')
            return append(key, data, **kwargs)
        monkeypatch.setattr(store, 'append', failing_append)
        monkeypatch.setattr(pixel.httpx, 'AsyncClient', lambda **kw: FakeClient(FakeResponse(content_type='text/event-stream')))
        async def cancel(*args): return True
        monkeypatch.setattr(pixel, '_cancel_edge_run', cancel)
        await pixel.pixel_chat_stream(ConnectedRequest(), body(), OWNER)
        await asyncio.gather(*list(pixel._result_tasks.values()), return_exceptions=True)
        assert store.get(IDENTITY)['state'] == 'interrupted'
        assert not store.has_pending(IDENTITY[:2])
    asyncio.run(run())


def test_finished_task_with_failed_state_commit_is_not_reported_as_running(store, monkeypatch):
    store.reserve(IDENTITY, 'hash')
    async def terminal(*args): return {'state':'terminal'}
    monkeypatch.setattr(pixel, 'pixel_chat_activity', terminal)
    result = asyncio.run(pixel.pixel_chat_result(pixel.ChatResultRequest(chat_id='chat-test',request_id='attempt-one'), OWNER))
    assert result == {'state':'interrupted','events':''}
    assert not store.has_pending(IDENTITY[:2])


def test_orphaned_receipts_do_not_reserve_future_output_capacity(tmp_path, monkeypatch):
    monkeypatch.setattr(receipts,'MAX_ACTIVE',1)
    first = receipts.ChatResultStore(tmp_path/'private')
    first.reserve(IDENTITY,'hash')
    first.close()
    second = receipts.ChatResultStore(tmp_path/'private')
    try:
        assert second.reserve((IDENTITY[0],'different-chat','next'),'hash')
        assert second.get(IDENTITY)['state'] == 'unresolved'
    finally: second.close()


def test_api_task_shutdown_is_not_reported_as_owner_stop(store, monkeypatch):
    async def run():
        started = asyncio.Event()
        class Upstream(FakeResponse):
            async def aiter_bytes(self):
                started.set()
                await asyncio.Future()
                yield b''
        monkeypatch.setattr(pixel.httpx, 'AsyncClient', lambda **kw: FakeClient(Upstream(content_type='text/event-stream')))
        async def cancel(*args): return True
        monkeypatch.setattr(pixel, '_cancel_edge_run', cancel)
        await pixel.pixel_chat_stream(ConnectedRequest(), body(), OWNER)
        await started.wait()
        task = pixel._result_tasks[IDENTITY]
        task.cancel()
        await task
        assert store.get(IDENTITY)['state'] == 'interrupted'
        assert b'Pixel was stopped' not in b''.join(row['data'] for row in store.chunks(IDENTITY))
    asyncio.run(run())


def test_completed_stream_wins_stop_during_upstream_context_teardown(store, monkeypatch):
    async def run():
        closing = asyncio.Event()
        class Client(FakeClient):
            async def __aexit__(self, *args):
                closing.set()
                await asyncio.Future()
        monkeypatch.setattr(pixel.httpx, 'AsyncClient', lambda **kw: Client(FakeResponse(content_type='text/event-stream', chunks=[FINAL])))
        async def cancel(*args): return True
        monkeypatch.setattr(pixel, '_cancel_edge_run', cancel)
        await pixel.pixel_chat_stream(ConnectedRequest(), body(), OWNER)
        await asyncio.wait_for(closing.wait(), 1)
        assert store.get(IDENTITY)['state'] == 'active'
        result = await pixel.pixel_chat_cancel(pixel.ChatCancelRequest(chat_id='chat-test', request_id='attempt-one'), OWNER)
        assert result == {'aborted': False}
        assert store.get(IDENTITY)['state'] == 'complete'
        assert b'Saved result' in b''.join(row['data'] for row in store.chunks(IDENTITY))
    asyncio.run(run())


def test_cancel_handles_evicted_or_missing_attempt_without_typeerror(store, monkeypatch):
    async def run():
        async def cancel(*args): return True
        monkeypatch.setattr(pixel, '_cancel_edge_run', cancel)
        call_count = 0
        def mocked_get(key):
            nonlocal call_count
            call_count += 1
            if call_count == 1:
                return {'state': 'active', 'fingerprint': 'f', 'created': 12345.0, 'size': 0}
            return None
        monkeypatch.setattr(store, 'get', mocked_get)
        result = await pixel.pixel_chat_cancel(
            pixel.ChatCancelRequest(chat_id='chat-test', request_id='attempt-evicted'), OWNER
        )
        assert result == {'aborted': False}
    asyncio.run(run())