Skip to content

fix(console): pending cancellation leaves SDK task launching after stop succeeds #204

Open

Description

@coygeek

Summary

Cancelling an admitted task while it is still pending removes its queue entry and device reservation, but does not leave an observable terminal state when no session row exists yet. The thin SDK subsequently returns launching with done=false, and wait_for_task() times out even though the scoped stop succeeded. Resource cleanup and terminal lifecycle reporting have different outcomes in this case.

Steps to reproduce

Run the following fixture from the source checkout using a Python environment with the host dependencies installed. It starts an isolated loopback HTTP server with the real task/session routers, enqueue logic, reservations, SQLite repository, targeted stop path and thin SDK. It substitutes the device/readiness prerequisites and disables task-worker dispatch to hold a submission deterministically pending; no Android device, model call or host IPC server is used. The fixture is not a full hardware run.

import asyncio
import os
from pathlib import Path
import socket
import sys
import tempfile

# Run from a source checkout with its host dependencies installed.
source = Path.cwd().resolve()
sys.path[:0] = [str(source), str(source / "packages/artemis-client/src")]
sandbox = tempfile.TemporaryDirectory()
root = Path(sandbox.name)
(root / "tmp").mkdir()
os.environ.update(ARTEMIS_APP_DIR=str(root / "app"),
                  ARTEMIS_TRACES_DIR=str(root / "traces"),
                  TMPDIR=str(root / "tmp"), PYTHONDONTWRITEBYTECODE="1")
tempfile.tempdir = None

from fastapi import FastAPI
import uvicorn
from artemis_client import ArtemisClient, TaskTimeoutError
from apps.admin_console.routers import tasks, sessions
from apps.admin_console.services.task_queue_service import TaskQueueService
from apps.admin_console.database.connection import db_session
from artemis.runtime import DeviceExecutionLock

# Synthetic pending admission: do not start a task worker, probe ADB or call models.
# Keep the real HTTP routes, enqueue, reservation, stop, SQLite and SDK paths.
TaskQueueService.ensure_worker_running = classmethod(lambda cls: None)
async def no_device(*args, **kwargs):
    return None
tasks.device_pool.validate_explicit_serial_async = no_device
tasks.device_pool.select_device_async = no_device
tasks.readiness_engine.run_device_submission_probe = no_device
tasks.model_service.get_active_model_info = lambda *a, **kw: {}
app = FastAPI()
app.include_router(tasks.router)
app.include_router(sessions.router)

async def main():
    sock = socket.socket()
    sock.bind(("127.0.0.1", 0))
    server = uvicorn.Server(uvicorn.Config(app, log_level="error", lifespan="off"))
    serving = asyncio.create_task(server.serve(sockets=[sock]))
    while not server.started:
        await asyncio.sleep(.01)
    client = ArtemisClient(f"http://127.0.0.1:{sock.getsockname()[1]}", poll_interval=.01)
    try:
        sid = "00000000-0000-4000-8000-000000000001"  # synthetic UUID
        handle = await client.submit("Synthetic cancellation fixture", task_id=sid)
        print("admitted:", handle.status)
        print("reservations before:", len(DeviceExecutionLock.get_queued_tasks()))
        print("stop:", await client.stop(sid))
        result = await client.get_task(sid)
        print("after stop:", result.status, "done:", result.done)
        status = await client._request("GET", "/api/status")
        print("queue:", status["queue"], "active:", status["active_tasks"])
        print("reservations after:", len(DeviceExecutionLock.get_queued_tasks()))
        try:
            await client._request("GET", f"/api/sessions/{sid}")
        except Exception as exc:
            print("session lookup:", type(exc).__name__)
        try:
            await client.wait_for_task(sid, timeout=.05)
        except TaskTimeoutError:
            print("terminal wait: TaskTimeoutError")

        # Control: same stop/wait with a session row already present.
        control = "00000000-0000-4000-8000-000000000002"
        await client.submit("Synthetic stored control", task_id=control)
        with db_session() as conn:
            conn.execute("INSERT INTO sessions(session_id,initial_goal,status) VALUES (?,?,?)",
                         (control, "Synthetic control", "running"))
            conn.commit()
        await client.stop(control)
        result = await client.wait_for_task(control, timeout=.05)
        print("stored control:", result.status, "done:", result.done)
        unknown = await client.get_task("00000000-0000-4000-8000-000000000003")
        print("never-admitted control:", unknown.status, "done:", unknown.done)
    finally:
        server.should_exit = True
        await serving
        sock.close()

try:
    asyncio.run(main())
finally:
    sandbox.cleanup()

The separate verification harness executed this pending-cancellation case twice, with both attempts producing the same failure. The self-contained fixture above was also executed and produced the output below. The UUIDs in the fixture are synthetic.

Expected behavior

Once cancellation of this admitted pending task succeeds, callers should be able to observe its terminal cancellation and complete wait_for_task(). The SDK explicitly treats cancelled as terminal; the host targeted-stop finalizer attempts to persist cancelled and broadcasts session_ended with that status. An arbitrary unknown task must remain distinguishable from a task whose cancellation is known; a 404 by itself does not prove cancellation.

Actual behavior

admitted: pending
reservations before: 1
stop: True
after stop: launching done: False
queue: [] active: []
reservations after: 0
session lookup: NotFoundError
terminal wait: TaskTimeoutError
stored control: cancelled done: True
never-admitted control: launching done: False

Both pending-cancellation attempts returned a successful scoped stop, left zero reservations and empty queue/active-task lists, and had no stored session or trace status. No task worker started in this fixture. The request emitted by client.stop(task_id) was POST /api/stop with only {"session_id": task_id} in its JSON body; no all field or device target was supplied. In the stored-row control, the same stop and SDK wait returned cancelled with done=true. The never-admitted control also returned launching, so that synthetic SDK status cannot distinguish cancellation from an unknown ID.

Evidence

  • Expected source: packages/artemis-client/src/artemis_client/client.py, stop() and wait_for_task(); models.py, TERMINAL_TASK_STATUSES; apps/admin_console/services/task_queue_service.py, _finalize_targeted_stop().
  • Failure source: Executed isolated HTTP fixture and its inline output above; two additional pending-cancellation iterations in a harness using the same real cancellation and persistence paths.
  • Evidence provenance: observed
  • Local verification: reproduced
  • Reproduction completeness: complete

Source breadcrumbs: _create_queue_item() reserves and admits a pending task before its session row exists. _terminate_stop_target() cancels its reservation, _finalize_targeted_stop() calls session_repo.update_session_status(), and _remove_stopped_queue_item() removes it from the live queue. update_session_status() performs an UPDATE and returns false for a missing row. The targeted-stop finalizer does not retain that failure as a queryable terminal result. GET /api/sessions/{session_id} therefore returns 404; ArtemisClient.get_task() falls back to /api/status and synthesizes launching when the task is no longer in the live scheduler.

Restoration check

Using the admitted pending fixture, a successful scoped cancellation should remain observable as terminal cancellation after the queue/reservation cleanup, and the SDK terminal wait should return that result. Preserve the existing-row control, successful cleanup, and the distinction between an admitted cancelled task and a never-admitted unknown ID. This check does not require treating every missing session as cancelled or prescribe a persistence implementation.

Runtime or environment

  • Current default branch tested: main at 351ca8422f7b5b54e80a9c1ce03a222e02415b6b; the repository has no published releases or tags.
  • Source package metadata: host 1.0, thin client 0.1.0; Python 3.12.15, macOS host. Both host and SDK imports were checked against the fresh source clone; dependencies were reused from an environment with the identical repository lockfile.
  • Zero real Android devices were used by this fixture. It tests the pending-before-session-storage lifecycle, not hardware startup timing or survival of an unrelated concurrent live task.

References

  • Related open issue #124 concerns a worker exiting before start_session() and losing its failed status. This report exercises cancellation while still pending, without starting a worker; it reaches the targeted-stop finalizer rather than the worker-exit finalizer.
  • Related open PR #126 addresses the worker-exit path. It does not establish that the pending targeted-stop path retains a terminal result.

Triage assessment

  • Impact level: P2
  • Assessment status: supported
  • Impact basis: An admitted task's successful pending cancellation cleans up resources but leaves polling clients without a terminal result. The failure is bounded to cancellation before session storage; broader timing frequency and hardware coverage were not measured here.
  • Workaround status: unverified
  • Workaround basis: Applications could potentially record the successful stop acknowledgement and stop polling locally, but this fixture does not establish an existing supported workaround that restores queryable terminal history for the admitted task.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions