Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions apps/admin_console/services/recording_assignments.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ class RecordingAssignment:
host_started_at: float | None = None
clock_offset: float | None = None

@property
def server_started_at(self) -> float | None:
"""The recording start in server time, once the host reported both values."""
if self.host_started_at is None or self.clock_offset is None:
return None
return self.host_started_at + self.clock_offset

@classmethod
def _from_row(cls, row: sqlite3.Row) -> "RecordingAssignment":
return cls(
Expand Down
58 changes: 58 additions & 0 deletions apps/admin_console/services/task_queue_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@
write_drain,
)
from apps.admin_console.services.device_reservation import device_reservations
from apps.admin_console.services.host_registry import host_registry
from apps.admin_console.services.recording_assignments import RecordingAssignmentStore
from artemis.config import (
PAUSE_FILE,
TEST_DATA_DIR,
Expand All @@ -69,6 +71,7 @@
request_cancel,
trace_store,
)
from artemis.config.host_agent import host_recording_enabled
from artemis.runtime.adb_endpoint import InvalidAdbEndpoint
from artemis.runtime.host_endpoints import host_endpoints
from artemis.runtime.lifecycle import TERMINAL_STATUSES
Expand Down Expand Up @@ -1433,6 +1436,47 @@ def _release_run_slot(
state.manually_stopped_run_ids.clear()
state.wake_event.set()

@classmethod
def _recording_store(cls) -> RecordingAssignmentStore:
return RecordingAssignmentStore(host_registry.db_path)

@classmethod
async def _assign_and_wait_for_recorder(cls, target: AdbTarget, sess_id: str) -> bool:
"""Assign the host recording, wait up to 10 s for the recorder, never fail the run.

True once an assignment exists, so the caller stops it when the run ends.
"""
from apps.admin_console.database.repositories.run_catalog_repository import (
CatalogNotReady,
run_catalog_repo,
)

recording_id = None
try:
store = cls._recording_store()
recording_id = store.assign(
target.host_id, sess_id, target.endpoint.generation
).recording_id
run_catalog_repo.set_recording_state(sess_id, recording_id, capture="pending")
ready = await asyncio.to_thread(store.wait_ready, sess_id)
if ready is None:
logger.warning(
"event=recorder_not_ready session_id=%s host_id=%s", sess_id, target.host_id
)
run_catalog_repo.set_recording_state(
sess_id, recording_id, capture="recording" if ready else "missing:not_ready"
)
except (sqlite3.Error, OSError, ValueError, CatalogNotReady):
logger.exception("event=recorder_wait_failed session_id=%s", sess_id)
return recording_id is not None

@classmethod
def _stop_recording(cls, sess_id: str) -> None:
try:
cls._recording_store().request_stop(sess_id)
except (sqlite3.Error, OSError):
logger.exception("event=recorder_stop_failed session_id=%s", sess_id)

@classmethod
async def _execute_task_item(cls, task_item: dict[str, Any]) -> None:
"""Run one queued task to completion in its own worker subprocess."""
Expand All @@ -1445,6 +1489,7 @@ async def _execute_task_item(cls, task_item: dict[str, Any]) -> None:
output_task: asyncio.Task[None] | None = None
config_snapshot = None
cmd = None
recording_assigned = False
state.executing_run_keys.add(run_key)
try:
if not isinstance(goal, str) or not goal.strip():
Expand Down Expand Up @@ -1504,6 +1549,12 @@ async def _execute_task_item(cls, task_item: dict[str, Any]) -> None:
goal_metadata(goal),
profile,
)
# Before worker_spawned: a host NACK during the wait still requeues.
if sess_id and target.host_id and host_recording_enabled():
# Set first: a cancel inside the wait must still stop the assignment
# (request_stop on a missing row is a no-op).
recording_assigned = True
recording_assigned = await cls._assign_and_wait_for_recorder(target, str(sess_id))
# From here a worker process may exist before it is registered: the host
# NACK (requeue_starting) must treat this run as spawned.
task_item["worker_spawned"] = True
Expand All @@ -1528,13 +1579,18 @@ async def _execute_task_item(cls, task_item: dict[str, Any]) -> None:
# 4. Perform fallback database status update and notification
if sess_id:
await cls._persist_terminal_session_status(sess_id, returncode, manual_stop)
if recording_assigned:
cls._stop_recording(str(sess_id))
await cls._recover_or_fail_recording(sess_id)
cls._deliver_outcome(sess_id, task_item, goal)

except asyncio.CancelledError:
print(f"[QueueWorker] Task [{sess_id}] received cancellation signal.")
if proc is not None and proc.returncode is None:
await cls._terminate_worker_process(proc)
# A host NACK requeue keeps the assignment for the next attempt.
if recording_assigned and sess_id and not task_item.get("requeue"):
cls._stop_recording(str(sess_id))
raise
except Exception:
logger.exception(f"[QueueWorker] Unexpected error executing task [{sess_id}]")
Expand All @@ -1549,6 +1605,8 @@ async def _execute_task_item(cls, task_item: dict[str, Any]) -> None:
logger.exception(
f"[QueueWorker] Could not persist failure status for [{sess_id}]"
)
if recording_assigned:
cls._stop_recording(str(sess_id))
finally:
host_admission.mark(run_key, RunPhase.CLEANING_UP)
await cls._finish_output_forwarder(output_task)
Expand Down
8 changes: 8 additions & 0 deletions artemis/config/host_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,16 @@
import os

ENV_HOST_AGENT = "ARTEMIS_HOST_AGENT"
ENV_HOST_RECORDING = "ARTEMIS_HOST_RECORDING"
_TRUTHY = frozenset({"enabled", "1", "true", "yes", "on"})


def host_agent_enabled() -> bool:
return os.environ.get(ENV_HOST_AGENT, "").strip().lower() in _TRUTHY


def host_recording_enabled() -> bool:
"""Host recording (CHE-1098) needs its own flag: no host recorder exists before stage 8."""
return (
host_agent_enabled() and os.environ.get(ENV_HOST_RECORDING, "").strip().lower() in _TRUTHY
)
Loading
Loading