Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
from __future__ import annotations

import logging
import re
from typing import Any

from shared.context import ServerContext
from shared.http_helpers import wrap_response
from shared.routine_runner import RoutineExecutionError

from .service import delete_scene, execute_scene, update_scene_name, update_scene_param


_LOGGER = logging.getLogger(__name__)

_SCENE_ITEM_RE = re.compile(r"/user/scene/(\d+)/(execute|name|param)")


Expand All @@ -34,7 +38,18 @@ def build_execute(
clean_path: str,
) -> dict[str, Any]:
scene_id = _scene_id_from_path(clean_path)
return wrap_response(execute_scene(ctx, scene_id))
# Clients (python-roborock, the app) expect the JSON envelope and check "success";
# an escaping exception becomes Starlette's text/plain 500 and leaves no trace in api_server.log.
logger = ctx.loggers.get("api", _LOGGER)
try:
return wrap_response(execute_scene(ctx, scene_id))
except RoutineExecutionError as exc:
logger.warning("Scene %s execute rejected: %s", scene_id, exc)
message = str(exc)
except Exception as exc: # noqa: BLE001
logger.exception("Scene %s execute failed", scene_id)
message = f"scene execute failed: {type(exc).__name__}"
return {"success": False, "code": 500, "msg": message, "data": None, "result": None}


def match_put_name(path: str, method: str = "GET") -> bool:
Expand Down
147 changes: 147 additions & 0 deletions tests/test_scene_execute_500.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
"""Regression tests for POST /user/scene/{id}/execute answering 500 text/plain.

Live incident 2026-11-28: the FDS build read decompiled_mqtt.jsonl with strict
UTF-8 while hydrating zone ranges; one line holding a raw TLS record made every
execute raise UnicodeDecodeError, which surfaced as Starlette's plain-text 500.
"""

import json
from pathlib import Path

from fastapi.testclient import TestClient

from conftest import write_release_config
from roborock_local_server.config import load_config, resolve_paths
from roborock_local_server.server import ReleaseSupervisor
from test_admin_api import _hawk_headers, _seed_protocol_snapshot

DEVICE_ID = "6HL2zfniaoYYV01CkVuhkO"
SEGMENT_TID = "1756774195653"
ZONE_TID = "1756774254605"


def _live_night_living_room_param() -> str:
"""Scene 4491072 as stored on the live server (zones have no range)."""

def step(step_id: int, method: str, entry: dict) -> dict:
return {
"id": step_id,
"type": "CMD",
"name": "",
"entityId": DEVICE_ID,
"param": json.dumps({"id": step_id, "method": method, "params": {"data": [entry], "source": 101}}),
"finishDpIds": [130],
}

common = {"map_flag": 0, "mop_mode": 300, "mop_template_id": 300, "clean_order_mode": 1,
"auto_dry": 1, "auto_dustCollection": 1, "region_num": 0}
return json.dumps(
{
"triggers": [],
"action": {
"type": "S",
"items": [
step(1, "do_scenes_segments", {"tid": SEGMENT_TID, "segs": [{"sid": 16}],
"fan_power": 101, "water_box_mode": 200, "repeat": 2, **common}),
step(2, "do_scenes_zones", {"tid": ZONE_TID,
"zones": [{"zid": 5, "repeat": 1}, {"zid": 6, "repeat": 1},
{"zid": 7, "repeat": 1}],
"fan_power": 102, "water_box_mode": 202, "repeat": 1, **common}),
],
},
"matchType": "NONE",
}
)


def _setup(tmp_path: Path, *, scene_param: str | None = None, real_runner: bool = False):
config_file = write_release_config(tmp_path)
config = load_config(config_file)
paths = resolve_paths(config_file, config)
paths.inventory_path.parent.mkdir(parents=True, exist_ok=True)
paths.inventory_path.write_text(
json.dumps(
{
"home": {"id": 1316433, "name": "My Home"},
"devices": [{"duid": DEVICE_ID, "name": "Qrevo MaxV 2", "model": "roborock.vacuum.a87"}],
"scenes": [
{
"id": 4491072,
"name": "Night living room",
"device_id": DEVICE_ID,
"enabled": True,
"type": "WORKFLOW",
"param": scene_param if scene_param is not None else _live_night_living_room_param(),
}
],
}
),
encoding="utf-8",
)
_seed_protocol_snapshot(paths.cloud_snapshot_path)
supervisor = ReleaseSupervisor(config=config, paths=paths)
started: list[dict] = []
if real_runner:
return paths, TestClient(supervisor.app, raise_server_exceptions=False), started
supervisor.context._routine_runner = type(
"DummyRoutineRunner",
(),
{"start_scene": lambda self, scene: (started.append(scene), {"accepted": True, "status": "started"})[-1]},
)()
client = TestClient(supervisor.app, raise_server_exceptions=False)
return paths, client, started


def _execute(client: TestClient, paths, scene_id: int):
path = f"/user/scene/{scene_id}/execute"
return client.post(path, headers=_hawk_headers(paths.cloud_snapshot_path, path))


def test_execute_live_scene_survives_non_utf8_mqtt_log_line(tmp_path: Path) -> None:
paths, client, started = _setup(tmp_path)
good = {"decoded_messages": [{"response_to": {
"request_method": "set_scenes_zones",
"request_params": {"data": [{"zones": [{"range": [1, 2, 3, 4]}]}]},
"result": [{"tid": ZONE_TID, "zones": [{"zid": 5}]}]}}]}
paths.mqtt_jsonl_path.parent.mkdir(parents=True, exist_ok=True)
# Same shape as the corrupt live line: a TLS application-data record glued to a JSON record.
paths.mqtt_jsonl_path.write_bytes(
b'\x17\x03\x03\x00\x13N\xd5\xf5_\xbc\x8f\xbe\x8472Wz\xe7\x8f{"time":"x"}\n'
+ json.dumps(good).encode() + b"\n"
)

response = _execute(client, paths, 4491072)

assert response.status_code == 200, response.text
assert response.json()["success"] is True
assert len(started) == 1
zone_step = json.loads(json.loads(started[0]["param"])["action"]["items"][1]["param"])
assert zone_step["params"]["data"][0]["zones"][0]["range"] == [1, 2, 3, 4]


def test_execute_unknown_scene_returns_json_error_not_plain_500(tmp_path: Path) -> None:
paths, client, _ = _setup(tmp_path)

response = _execute(client, paths, 999)

assert response.headers["content-type"].startswith("application/json"), (response.status_code, response.text)
assert response.json()["success"] is False


def test_execute_unparseable_scene_returns_json_error_not_plain_500(tmp_path: Path) -> None:
paths, client, started = _setup(tmp_path, scene_param='{"action":{"items":[]}}', real_runner=True)

response = _execute(client, paths, 4491072)

assert response.headers["content-type"].startswith("application/json"), (response.status_code, response.text)
assert response.json()["success"] is False
assert started == []


def test_execute_failure_is_written_to_api_log(tmp_path: Path) -> None:
paths, client, _ = _setup(tmp_path)

_execute(client, paths, 999)

api_log = (paths.runtime_dir / "api_server.log").read_text(encoding="utf-8")
assert "Scene 999 execute" in api_log