diff --git a/src/cloud_agents/spawner/exec_request.py b/src/cloud_agents/spawner/exec_request.py new file mode 100644 index 0000000..5ed5f7c --- /dev/null +++ b/src/cloud_agents/spawner/exec_request.py @@ -0,0 +1,176 @@ +"""Build the stdin request for the sandbox step CLI. + +The step CLI (lightspeed-agentic-sandbox ``.ai/spec/what/step-cli.md``) reads one +``StepRequest`` JSON line on stdin: the ``POST /v1/agent/run`` fields (``query``, +``systemPrompt``, ``outputSchema``, ``context``, ``timeout_ms``) plus ``stepId``, +``runDir`` and ``traceparent``. Unknown keys are rejected (exit 2), so only those +keys are ever sent. Pure module: no I/O. +""" + +from __future__ import annotations + +import hashlib +import json +import logging +import posixpath +import re +import secrets +from dataclasses import dataclass +from typing import Any + +from cloud_agents.runtime.tracing import inject_traceparent + +logger = logging.getLogger(__name__) + +RUN_ROOT = "/tmp/lsrun" +MAX_TIMEOUT_MS = 86_400_000 # StepRequest.timeout_ms le= +# The CLI reads at most 1 MiB including the newline, and the gateway caps the +# whole ExecSandboxRequest (stdin + env + argv) at 1 MiB. Keep the same 64 KiB +# headroom as OpenShellSpawner._MAX_EXEC_STDIN_BYTES. Env is not known here, so +# the exec caller must also check the full message with check_exec_message_size(). +MAX_STEP_REQUEST_BYTES = 1024 * 1024 - 64 * 1024 +GATEWAY_MAX_MESSAGE_BYTES = 1024 * 1024 +# Conservative protobuf framing estimates (tags, lengths, map entries, ids). +_FIELD_OVERHEAD = 16 +_MESSAGE_OVERHEAD = 1024 + +_STEP_ID = re.compile(r"[a-z0-9-]{1,40}") +_SLUG_SEP = re.compile(r"[^a-z0-9]+") +_SLUG_LEN = 27 # + "-" + 12 hex digest chars = 40 + + +class StepRequestError(ValueError): + """The step can't be sent to the step CLI; fail it without retrying.""" + + +class StepRequestTooLarge(StepRequestError): + """The serialized request exceeds MAX_STEP_REQUEST_BYTES.""" + + +@dataclass(frozen=True) +class StepExecRequest: + step_id: str + run_dir: str + stdin: bytes + + +def derive_step_id(workflow_id: str, step_name: str, attempt: int) -> str: + """Derive a CLI ``stepId`` (``^[a-z0-9-]{1,40}$``) from a free-form step name. + + A readable slug of the name plus a hash of the exact (workflow, step, attempt), + so names that slug the same still get distinct ids. + """ + slug = _SLUG_SEP.sub("-", step_name.lower()).strip("-")[:_SLUG_LEN] or "step" + key = json.dumps([workflow_id, step_name, attempt]) + return f"{slug}-{hashlib.sha256(key.encode()).hexdigest()[:12]}" + + +def new_run_dir(step_id: str, run_root: str = RUN_ROOT) -> str: + """Return a fresh, unguessable runDir path directly under run_root. + + The CLI requires runDir to be a direct child of its run root, compared as + strings, so run_root must be absolute and normalized. + """ + if not run_root.startswith("/") or posixpath.normpath(run_root) != run_root: + raise ValueError(f"run_root must be an absolute normalized path: {run_root!r}") + if not _STEP_ID.fullmatch(step_id): + raise ValueError(f"invalid stepId: {step_id!r}") + return f"{run_root}/{step_id}-{secrets.token_hex(8)}" + + +def check_exec_message_size(stdin: bytes, env: dict[str, str], argv: list[str]) -> None: + """Raise StepRequestTooLarge unless stdin + env + argv fit one gateway exec message. + + An estimate with generous framing overhead; the gateway decodes at most + GATEWAY_MAX_MESSAGE_BYTES per ExecSandboxRequest, env and argv included. + """ + env_bytes = sum(len(k.encode()) + len(v.encode()) + _FIELD_OVERHEAD for k, v in env.items()) + argv_bytes = sum(len(a.encode()) + _FIELD_OVERHEAD for a in argv) + size = len(stdin) + env_bytes + argv_bytes + _MESSAGE_OVERHEAD + if size > GATEWAY_MAX_MESSAGE_BYTES: + raise StepRequestTooLarge( + f"exec request is about {size} bytes (stdin {len(stdin)}, env {env_bytes}, " + f"argv {argv_bytes}), over the gateway's {GATEWAY_MAX_MESSAGE_BYTES}-byte limit" + ) + + +def build_step_request( + step: dict[str, Any], + *, + workflow_id: str, + attempt: int, + context: dict[str, Any], + system_prompt: str | None = None, + timeout_seconds: int | None = None, + mcp_servers: list[dict[str, Any]] | None = None, + run_root: str = RUN_ROOT, +) -> StepExecRequest: + """Build the step CLI stdin for one step. + + Parameters: + step: The step spec (``name``, ``prompt``, ``output_schema``, ``permissions``). + workflow_id: Workflow ID, part of the stepId hash. + attempt: Retry attempt, part of the stepId hash. + context: Sandbox context, as sent to ``/run`` today. + system_prompt: ``systemPrompt``, already interpolated by the caller. + timeout_seconds: Sent as ``timeout_ms``; omitted means the CLI default. + mcp_servers: Resolved MCP servers for the step. Only checked: the CLI reads + MCP config from env, which the gateway logs a preview of, so servers + with plain header values are rejected until the CLI accepts config on stdin. + run_root: Parent of the runDir. + + Raises: + StepRequestTooLarge: The request exceeds MAX_STEP_REQUEST_BYTES. + StepRequestError: The step can't be expressed as a valid StepRequest. + """ + step_name = step["name"] + for server in mcp_servers or []: + if server.get("headers"): + raise StepRequestError( + f"Step '{step_name}': MCP server '{server.get('name')}' has plain headers, " + "which the exec transport can't deliver safely; use secret_headers" + ) + + permissions = step.get("permissions") or {} + if permissions.get("allowed_tools") or permissions.get("denied_tools"): + logger.warning( + "Step '%s': allowed_tools/denied_tools are not enforced on the exec transport " + "(same as HTTP /run today); omitting them from the step request", + step_name, + ) + + step_id = derive_step_id(workflow_id, step_name, attempt) + run_dir = new_run_dir(step_id, run_root) + request: dict[str, Any] = { + "query": step.get("prompt", ""), + "context": context, + "stepId": step_id, + "runDir": run_dir, + } + if system_prompt: + request["systemPrompt"] = system_prompt + if output_schema := step.get("output_schema"): + request["outputSchema"] = output_schema + if timeout_seconds is not None: + timeout_ms = int(timeout_seconds * 1000) + if not 0 < timeout_ms <= MAX_TIMEOUT_MS: + raise StepRequestError( + f"Step '{step_name}': timeout {timeout_seconds}s outside 0 < t <= " + f"{MAX_TIMEOUT_MS // 1000}s" + ) + request["timeout_ms"] = timeout_ms + if traceparent := inject_traceparent({}).get("traceparent"): + request["traceparent"] = traceparent + + try: + stdin = ( + json.dumps(request, allow_nan=False, ensure_ascii=False, separators=(",", ":")) + "\n" + ).encode("utf-8") + except (ValueError, TypeError) as exc: # NaN, lone surrogates, non-JSON types + raise StepRequestError(f"Step '{step_name}': request is not strict JSON: {exc}") from None + if len(stdin) > MAX_STEP_REQUEST_BYTES: + raise StepRequestTooLarge( + f"Step '{step_name}': step request is {len(stdin)} bytes, over the " + f"{MAX_STEP_REQUEST_BYTES}-byte limit" + ) + return StepExecRequest(step_id=step_id, run_dir=run_dir, stdin=stdin) diff --git a/src/cloud_agents/spawner/step_protocol.py b/src/cloud_agents/spawner/step_protocol.py new file mode 100644 index 0000000..5c2f4cb --- /dev/null +++ b/src/cloud_agents/spawner/step_protocol.py @@ -0,0 +1,562 @@ +"""Parse the sandbox step CLI's exec output and map it to a step outcome. + +The step CLI (``python3 -P -m lightspeed_agentic.step``, contract in +lightspeed-agentic-sandbox ``.ai/spec/what/step-cli.md``) writes JSONL protocol +lines to stdout: ``{"v":1,"type":"event","event":{ts,type,data}}`` records, +then at most one final ``{"v":1,"type":"result","status_code":..,"body":{..}}``. +It also publishes the result record to ``runDir/result.json``. + +The agent's tools run as the CLI's uid, so every stdout line and result.json +is untrusted: parsed strictly (no NaN/Infinity, no duplicate keys, no extra +keys), bounded in size, and validated before use. A same-uid descendant that +``setsid``s out can outlive the CLI and replace files in the agent-owned +runDir. So ``completed`` comes only from a valid result line, which the CLI +writes on a private fd. result.json is read only after exit 4 or a lost stream, +as a diagnostic: the step fails and the sandbox is tainted. + +Pure module: no I/O. The exec transport feeds chunks in and reads the result +file when :func:`needs_result_file` says so. + +Notes for the exec caller: + +- Run the CLI with ``python3 -I`` (isolated: also ignores ``PYTHON*`` env and + user site-packages), not just ``-P``. +- Never reuse a warm sandbox after an outcome with ``taint_lease`` set. +""" + +from __future__ import annotations + +import json +import math +import re +from dataclasses import dataclass +from typing import Any, Literal + +from pydantic import ( + BaseModel, + ConfigDict, + Field, + ValidationError, + field_validator, + model_validator, +) + +from cloud_agents.workflow.core.models import TranscriptEvent +from cloud_agents.workflow.security.redact import redact_secrets + +MAX_EVENT_LINE = 256 * 1024 +MAX_RESULT_LINE = 4 * 1024 * 1024 +MAX_STDOUT_TOTAL = 64 * 1024 * 1024 +MAX_PREPROTOCOL_NOISE = 64 * 1024 # login-shell output before the CLI starts +MAX_TRANSCRIPT_EVENTS = 10_000 +MAX_TRANSCRIPT_BYTES = 16 * 1024 * 1024 +MAX_STDERR_TAIL = 16 * 1024 +# Hardcoded result.json body keys reported as has_ in diagnostics; any +# other key is only counted, never named (a key can itself be a secret). +_DIAGNOSTIC_KEYS = ("error", "summary", "detail", "output") +MAX_JSON_DEPTH = 64 # the CLI's records nest about 4 deep +_MAX_PID_LINE = 32 + +_PID_LINE = re.compile(rb"lsrun-pid ([1-9][0-9]{0,9})") + +# step-cli.md rule 11 +EXIT_OK = 0 +EXIT_NOT_STARTED = 1 +EXIT_REJECTED = 2 +EXIT_INTERNAL = 3 +EXIT_NO_STDOUT = 4 +EXIT_DEADLINE = 124 + + +class _Strict(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + + +class _Record(_Strict): + v: Literal[1] + + @field_validator("v", mode="before") + @classmethod + def _exact_int(cls, value: Any) -> Any: + # Literal[1] alone accepts True and 1.0 (they compare equal to 1). + if type(value) is not int: + raise ValueError("v must be the integer 1") + return value + + +class _Event(_Strict): + ts: str + type: str + data: dict[str, Any] + + +class EventRecord(_Record): + type: Literal["event"] + event: _Event + + +class _RunResponse(BaseModel): + """Mirrors the sandbox's ``RunResponse``: the body of every 200 result.""" + + model_config = ConfigDict(extra="allow", strict=True) + + success: bool + summary: str + + +class ResultRecord(_Record): + type: Literal["result"] + status_code: int = Field(ge=100, le=599) + body: dict[str, Any] + + @model_validator(mode="after") + def _check_200_body(self) -> ResultRecord: + if self.status_code == 200: + _RunResponse.model_validate(self.body) + return self + + +def _reject_constant(name: str) -> Any: + raise ValueError(f"non-strict JSON constant {name}") + + +def _finite_float(text: str) -> float: + value = float(text) + if not math.isfinite(value): + raise ValueError(f"non-finite number {text}") + return value + + +def _no_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + obj = dict(pairs) + if len(obj) != len(pairs): + raise ValueError("duplicate key") + return obj + + +def _within_depth(obj: Any) -> bool: + """Whether obj nests at most MAX_JSON_DEPTH deep (checked without recursion).""" + stack = [(obj, 1)] + while stack: + value, depth = stack.pop() + if isinstance(value, dict): + value = list(value.values()) + if isinstance(value, list): + if depth > MAX_JSON_DEPTH: + return False + stack.extend((item, depth + 1) for item in value) + return True + + +def _parse_record(line: bytes) -> EventRecord | ResultRecord | None: + """Parse one protocol line strictly; None if it is not a valid record.""" + try: + obj = json.loads( + line.decode("utf-8"), + parse_constant=_reject_constant, + parse_float=_finite_float, + object_pairs_hook=_no_duplicate_keys, + ) + except (ValueError, RecursionError): # includes UnicodeDecodeError, JSONDecodeError + return None + if not isinstance(obj, dict) or not isinstance(obj.get("type"), str): + return None + if not _within_depth(obj): + return None + model = {"event": EventRecord, "result": ResultRecord}.get(obj["type"]) + if model is None: + return None + try: + return model.model_validate(obj) + except ValidationError: + return None + + +class StepProtocolReader: + """Incrementally parse one step exec's stdout (protocol) and stderr (pid, tail). + + Attributes: + events: Transcript, in order, bounded to MAX_TRANSCRIPT_EVENTS / + MAX_TRANSCRIPT_BYTES plus one truncation marker. + result: The final result record, or None if missing, invalid or discarded. + pid: CLI pid (== pgid) from the exec wrapper's first stderr line, or None. + Best effort, for in-sandbox kill commands only: in a warm sandbox the + login shell's rc files run first and could print a fake line. Stopping + a step must use the exec handle or destroy the sandbox (step-cli.md + trust model). + protocol_errors: Invalid lines after the first valid one (dropped). + oversized_lines: Event lines over MAX_EVENT_LINE, or any line over + MAX_RESULT_LINE (dropped). + violation: Set when a line follows the result; the result is discarded. + abort_reason: ``output_too_large`` or ``preprotocol_noise``; the caller + must stop the exec. Parsing stops. + truncated: stdout ended mid-line. + """ + + def __init__(self) -> None: + self.events: list[TranscriptEvent] = [] + self.result: ResultRecord | None = None + self.pid: int | None = None + self.protocol_errors = 0 + self.oversized_lines = 0 + self.violation: str | None = None + self.abort_reason: str | None = None + self.truncated = False + self._buf = bytearray() + self._skipping = False + self._total = 0 + self._noise = 0 + self._seen_protocol = False + self._transcript_bytes = 0 + self._dropped_events = 0 + self._stderr_head = bytearray() + self._stderr_head_done = False + self._stderr_tail = bytearray() + self._stderr_cut = False + + def feed(self, stream: str, data: bytes) -> list[TranscriptEvent]: + """Consume one exec output chunk; return the valid events it completed.""" + if stream == "stderr": + self._feed_stderr(data) + return [] + if stream != "stdout": + raise ValueError(f"unknown exec stream {stream!r}") + if self.abort_reason: + return [] + self._total += len(data) + if self._total > MAX_STDOUT_TOTAL: + self._abort("output_too_large") + return [] + + new: list[TranscriptEvent] = [] + *lines, tail = data.split(b"\n") + for part in lines: + self._append(part) + if self._skipping: + self._skipping = False + self._invalid(oversized=True) + else: + line = bytes(self._buf) + self._buf.clear() + if (event := self._line(line)) is not None: + new.append(event) + if self.abort_reason: + return new + self._append(tail) + return new + + def finish(self) -> None: + """Mark the end of stdout; a pending partial line is truncated output.""" + if self._buf or self._skipping: + self.truncated = True + if self.result is not None: + self._violate("partial line after result") + self._buf.clear() + self._skipping = False + + def stderr_tail(self, secret_values: set[str]) -> str: + """The last MAX_STDERR_TAIL characters of stderr, redacted. + + Redaction runs before the final truncation, on a window twice that size. + If the window was cut, a prefix as long as the longest secret is dropped + first, so a secret cut at the window start can't leave a suffix behind. + Known limits: it is plain substring matching on decoded text, so secrets + that are encoded, escaped or split across writes with other text are not + caught, and the final cut may split a redaction placeholder. + """ + text = bytes(self._stderr_tail).decode("utf-8", errors="replace") + if self._stderr_cut: + text = text[max(map(len, secret_values), default=0) :] + return redact_secrets(text, secret_values)[-MAX_STDERR_TAIL:] + + def _append(self, part: bytes) -> None: + if self._skipping: + return + if len(self._buf) + len(part) > MAX_RESULT_LINE: + self._skipping = True + self._buf.clear() + else: + self._buf += part + + def _abort(self, reason: str) -> None: + self.abort_reason = reason + self._buf.clear() + + def _violate(self, reason: str) -> None: + self.violation = self.violation or reason + self.result = None + + def _invalid(self, *, oversized: bool = False, size: int = MAX_RESULT_LINE) -> None: + if self.result is not None or self.violation: + self._violate("line after result") + elif not self._seen_protocol: + self._noise += size + 1 + if self._noise > MAX_PREPROTOCOL_NOISE: + self._abort("preprotocol_noise") + elif oversized: + self.oversized_lines += 1 + else: + self.protocol_errors += 1 + + def _line(self, line: bytes) -> TranscriptEvent | None: + if self.result is not None or self.violation: + self._violate("line after result") + return None + record = _parse_record(line) + if record is None: + self._invalid(size=len(line)) + return None + self._seen_protocol = True + if isinstance(record, ResultRecord): + self.result = record + return None + if len(line) > MAX_EVENT_LINE: + self.oversized_lines += 1 + return None + try: + event = TranscriptEvent(**record.event.model_dump()) + except ValidationError: # event type outside the transcript schema + self.protocol_errors += 1 + return None + self._keep(event, len(line)) + return event + + def _keep(self, event: TranscriptEvent, size: int) -> None: + if self._dropped_events == 0 and ( + len(self.events) < MAX_TRANSCRIPT_EVENTS + and self._transcript_bytes + size <= MAX_TRANSCRIPT_BYTES + ): + self.events.append(event) + self._transcript_bytes += size + return + if self._dropped_events == 0: + self.events.append( + TranscriptEvent(ts=event.ts, type="error", data={"message": "transcript truncated"}) + ) + self._dropped_events += 1 + self.events[-1].data["dropped_events"] = self._dropped_events + + def _feed_stderr(self, data: bytes) -> None: + self._stderr_tail += data + if len(self._stderr_tail) > 2 * MAX_STDERR_TAIL: + del self._stderr_tail[: -2 * MAX_STDERR_TAIL] + self._stderr_cut = True + if self._stderr_head_done: + return + head, newline, _ = data.partition(b"\n") + self._stderr_head += head[: _MAX_PID_LINE + 1 - len(self._stderr_head)] + if newline: + self._stderr_head_done = True + if match := _PID_LINE.fullmatch(self._stderr_head): + self.pid = int(match.group(1)) + elif len(self._stderr_head) > _MAX_PID_LINE: + self._stderr_head_done = True + + +@dataclass(frozen=True) +class StepOutcome: + """What the runner does with one step exec. + + ``status``: + ``completed`` -- shape ``body`` into the step output exactly as the HTTP path does. + ``failed`` -- return a failed step; ``body`` is set when the agent reported + ``success: false``. ``run_with_retries`` classifies ``error`` here too, so an + agent- or sandbox-supplied error text can still be transient, as on HTTP + today; the fixed texts this module writes never are. Also used for + deterministic, agent-inducible failures (protocol violations, exit 3), which + a retry would repeat and which must not open the provider circuit breaker. + ``error`` -- raise ``RuntimeError(error)``. ``run_with_retries`` reruns the step + only if ``is_transient_failure(error)``, which holds only for the 502 outcome + (as for an HTTP 502 today). The rest (lost stream, exit 124, killed, + unexpected exit) fail the step without a rerun, so side effects never repeat. + ``breaker``: record ``success``/``failure`` on the provider circuit breaker, or nothing. + ``taint_lease``: the sandbox may be tampered with; a warm lease must not be reused. + Always set after exit 4 or a lost stream. + ``diagnostic``: bounded metadata about result.json for logs: fixed vocabulary plus + validated scalars (status code, success flag on 200, presence of a hardcoded + set of keys, count of other keys, byte size). It holds no string from the + file, not even key names, so nothing in it needs redacting. It never goes + into ``error``, which ``run_with_retries`` classifies. + """ + + status: Literal["completed", "failed", "error"] + reason: str + error: str | None = None + body: dict[str, Any] | None = None + breaker: Literal["success", "failure"] | None = None + result_source: Literal["stdout", "file", "file_after_transport_loss"] | None = None + taint_lease: bool = False + diagnostic: str | None = None + + +def needs_result_file(exit_code: int | None, reader: StepProtocolReader) -> bool: + """Whether the runner should read ``runDir/result.json`` for diagnostics. + + Only on exit 4 (published but not delivered) or transport loss (``exit_code + is None``, after the exec is torn down). The file never decides the outcome: + the step fails either way, because a same-uid descendant can replace it. + Exit 0 promises the result line was delivered, and other exits make no + promise about the file (step-cli.md rule 9). + """ + if reader.abort_reason or reader.violation: + return False + return exit_code is None or exit_code == EXIT_NO_STDOUT + + +def map_outcome( + exit_code: int | None, + reader: StepProtocolReader, + result_file: bytes | None = None, +) -> StepOutcome: + """Map a finished step exec to a step outcome, mirroring the HTTP path. + + Parameters: + exit_code: The exec's exit code, or None if the stream was lost before one. + reader: The reader after :meth:`StepProtocolReader.finish`. + result_file: ``runDir/result.json`` contents (read capped at + MAX_RESULT_LINE + 1), or None if unread or missing. Ignored unless + :func:`needs_result_file` is true. + """ + if reader.abort_reason: + return StepOutcome( + "failed", reader.abort_reason, error=f"step output rejected: {reader.abort_reason}" + ) + if reader.violation: + return StepOutcome( + "failed", "protocol_violation", error=f"step protocol violation: {reader.violation}" + ) + if exit_code == EXIT_OK: + if reader.result is not None: + return _from_result(reader.result, "stdout") + # Exit 0 promises the line was delivered on the CLI's private fd, so a + # missing one was rejected by our validation (too large, too deep, not + # strict) or tampered with. Don't fall back to the replaceable file. + return StepOutcome( + "failed", + "protocol_violation", + error="step protocol violation: exit 0 without a valid result line", + ) + if needs_result_file(exit_code, reader): + return _from_file(exit_code, result_file) + if exit_code == EXIT_REJECTED: + return _rejected(reader.result) + if exit_code == EXIT_NOT_STARTED: + # The CLI never ran: the runDir mkdir failed (possible tampering) or + # python could not import it. The pid line is printed before both, so it + # can't tell them apart; treat both as a tainted sandbox. + return StepOutcome( + "failed", + "step_cli_not_started", + error="step CLI did not start (exit 1)", + taint_lease=True, + ) + if exit_code == EXIT_INTERNAL: + # Deterministic or agent-inducible (a planted result.json makes publication + # fail), so neither retried nor counted against the provider. + return StepOutcome("failed", "internal_error", error="step CLI internal error (exit 3)") + if exit_code == EXIT_DEADLINE: + return StepOutcome( + "error", "deadline", error="step CLI hard deadline (exit 124)", breaker="failure" + ) + if exit_code is not None and (exit_code > 128 or exit_code < 0): + return StepOutcome("error", "killed", error=f"step CLI killed (exit {exit_code})") + return StepOutcome( + "error", "unexpected_exit", error=f"step CLI exited {exit_code}", breaker="failure" + ) + + +def _from_file(exit_code: int | None, data: bytes | None) -> StepOutcome: + """Exit 4 or transport loss: the result line is lost, and result.json isn't trusted. + + Never completes and never retries: the step fails, the sandbox is tainted, and + a valid file only feeds ``diagnostic``, as metadata without any of its text. + """ + lost = exit_code is None + source = "file_after_transport_loss" if lost else "file" + record = None + if data is not None and len(data) <= MAX_RESULT_LINE: + record = _parse_record(data) + if isinstance(record, ResultRecord): + body = record.body + success = f" success={body['success']}" if record.status_code == 200 else "" + present = " ".join(f"has_{k}={k in body}" for k in _DIAGNOSTIC_KEYS) + other_keys = len(body.keys() - {"success", *_DIAGNOSTIC_KEYS}) + diagnostic = ( + f"untrusted result.json: status={record.status_code}{success} {present} " + f"other_keys={other_keys} bytes={len(data)}" + ) + return StepOutcome( + "failed", + "result_unverified", + error="step result line not received; result.json is not trusted", + result_source=source, + taint_lease=True, + diagnostic=diagnostic, + ) + if lost: + return StepOutcome( + "error", + "no_result", + error="lost exec stream, no result", + breaker="failure", + taint_lease=True, + ) + if data is None: + return StepOutcome( + "failed", + "no_result", + error="step CLI exited 4 but result.json could not be read", + taint_lease=True, + ) + # Exit 4 promises a complete result.json; anything else is tampering. + return StepOutcome( + "failed", + "protocol_violation", + error="step protocol violation: invalid result.json after exit 4", + taint_lease=True, + ) + + +def _from_result(record: ResultRecord, source: str) -> StepOutcome: + body = record.body + if record.status_code == 200: + if body["success"]: + return StepOutcome( + "completed", "ok", body=body, breaker="success", result_source=source + ) + return StepOutcome( + "failed", + "agent_failed", + error=body.get("error", "agent returned success=false"), + body=body, + breaker="failure", + result_source=source, + ) + if record.status_code == 502: + return StepOutcome( + "error", + "infrastructure_error", + error="Infrastructure error from sandbox (502)", + breaker="failure", + result_source=source, + ) + return StepOutcome( + "failed", + "sandbox_error", + error=f"sandbox returned {record.status_code}: {body.get('error')}", + body=body, + breaker="failure", + result_source=source, + ) + + +def _rejected(record: ResultRecord | None) -> StepOutcome: + """Exit 2: the CLI rejected the request before any agent code ran.""" + if record is None: + return StepOutcome("failed", "rejected", error="step request rejected (exit 2)") + error = f"step request rejected ({record.status_code}): {record.body.get('error')}" + # A schema rejection always carries pydantic `detail`; a 422 without it is + # the runDir check (rule 10), so the sandbox's run root may be tampered with. + if record.status_code == 422 and "detail" not in record.body: + return StepOutcome("failed", "rundir_rejected", error=error, taint_lease=True) + return StepOutcome("failed", "rejected", error=error) diff --git a/tests/unit/spawner/fixtures/step_cli/README.md b/tests/unit/spawner/fixtures/step_cli/README.md new file mode 100644 index 0000000..7e62b89 --- /dev/null +++ b/tests/unit/spawner/fixtures/step_cli/README.md @@ -0,0 +1,37 @@ +# Step CLI golden fixtures + +Real output of the sandbox step CLI (`python3 -P -m lightspeed_agentic.step`), +used by `TestGoldenFixtures` in `tests/unit/spawner/test_step_protocol.py`. + +Each `/` holds the exec's raw `stdout.jsonl` and, when the CLI +published one, `result.json`. `manifest.json` records the real exit code and +event types, plus the expected step outcome. Those outcomes were written by hand +in `generate.py` from the CLI spec; they are not computed by `step_protocol`. + +## Provenance + +- Sandbox: lightspeed-agentic-sandbox `fork/lcs-main` at + `bca5ad0156a92271cebd47f69245f1cd0a6058b0`, in a throwaway `git worktree` + with `uv sync --frozen --extra dev`. +- Providers: the sandbox's own test fakes (`tests/step_fakes.py`), which run + the real `lightspeed_agentic.step.main` with a fake provider. No containers, + gateway or credentials. +- Requests: built by `cloud_agents.spawner.exec_request.build_step_request`, + except `rejected_schema` (adds `allowedTools`, which the CLI must reject) and + `rejected_run_dir` (runDir not created). The runDir is created mode 0700 + under `/tmp/lsrun`, as the exec wrapper will. +- Captured on macOS (`prctl` is a no-op there; it doesn't affect stdout). +- The CLI's stderr isn't captured. The `lsrun-pid` line comes from the runner's + exec wrapper, not the CLI, so the test feeds a synthetic one. + +## Regenerate + +```bash +git -C ~/ws/lightspeed-agentic-sandbox worktree add --detach /tmp/lsas bca5ad0 +(cd /tmp/lsas && uv sync --frozen --extra dev) +uv run --extra openshell python tests/unit/spawner/fixtures/step_cli/generate.py \ + --sandbox-repo /tmp/lsas +git -C ~/ws/lightspeed-agentic-sandbox worktree remove /tmp/lsas +``` + +Event timestamps change on each run, nothing else should. diff --git a/tests/unit/spawner/fixtures/step_cli/agent_error/result.json b/tests/unit/spawner/fixtures/step_cli/agent_error/result.json new file mode 100644 index 0000000..4018df4 --- /dev/null +++ b/tests/unit/spawner/fixtures/step_cli/agent_error/result.json @@ -0,0 +1 @@ +{"v": 1, "type": "result", "status_code": 200, "body": {"success": false, "summary": "Agent error: boom"}} \ No newline at end of file diff --git a/tests/unit/spawner/fixtures/step_cli/agent_error/stdout.jsonl b/tests/unit/spawner/fixtures/step_cli/agent_error/stdout.jsonl new file mode 100644 index 0000000..bbac401 --- /dev/null +++ b/tests/unit/spawner/fixtures/step_cli/agent_error/stdout.jsonl @@ -0,0 +1 @@ +{"v": 1, "type": "result", "status_code": 200, "body": {"success": false, "summary": "Agent error: boom"}} diff --git a/tests/unit/spawner/fixtures/step_cli/generate.py b/tests/unit/spawner/fixtures/step_cli/generate.py new file mode 100644 index 0000000..ab58aec --- /dev/null +++ b/tests/unit/spawner/fixtures/step_cli/generate.py @@ -0,0 +1,148 @@ +"""Regenerate the step CLI golden fixtures from the real sandbox step CLI. + +Run from this repo's venv (see README.md): + + uv run python tests/unit/spawner/fixtures/step_cli/generate.py \ + --sandbox-repo /path/to/lightspeed-agentic-sandbox + +Each scenario builds its stdin with build_step_request(), creates the runDir the +way the exec wrapper will (mode 0700 under /tmp/lsrun), runs the real +``lightspeed_agentic.step.main`` through the sandbox's ``tests.step_fakes`` fake +providers, and records stdout, result.json and the exit code. +""" + +from __future__ import annotations + +import argparse +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +from cloud_agents.spawner.exec_request import RUN_ROOT, build_step_request + +HERE = Path(__file__).resolve().parent + +# scenario -> (fake provider, step overrides, request patch, CLI args, mkdir runDir, +# close stdout, expected outcome). Expected outcomes are written by +# hand from step-cli.md, not computed by step_protocol. +SCENARIOS = { + "ok": ("ok", {}, {}, [], True, False, ("completed", "ok", "stdout")), + "agent_error": ("agent_error", {}, {}, [], True, False, ("failed", "agent_failed", "stdout")), + "infra_502": ("infra", {}, {}, [], True, False, ("error", "infrastructure_error", "stdout")), + "nan": ("nan", {}, {}, [], True, False, ("completed", "ok", "stdout")), + "soft_timeout_502": ( + "hang", + {"timeout_seconds": 1}, + {}, + [], + True, + False, + ("error", "infrastructure_error", "stdout"), + ), + "rejected_schema": ( + "ok", + {}, + {"allowedTools": ["Bash"]}, + [], + True, + False, + ("failed", "rejected", None), + ), + "rejected_run_dir": ("ok", {}, {}, [], False, False, ("failed", "rundir_rejected", None)), + "stdout_closed": ("ok", {}, {}, [], True, True, ("failed", "result_unverified", "file")), + "hard_deadline": ( + "stubborn", + {"timeout_seconds": 1}, + {}, + ["--grace-seconds", "1"], + True, + False, + ("error", "deadline", None), + ), +} + + +def _run(sandbox_repo: Path, python: str, name: str, spec: tuple) -> dict: + scenario, kwargs, patch, cli_args, mkdir, close_stdout, expected = spec + req = build_step_request( + {"name": f"golden {name}", "prompt": "Diagnose the issue"}, + workflow_id="golden", + attempt=1, + context={"steps": {}}, + **kwargs, + ) + stdin = req.stdin + if patch: + stdin = (json.dumps({**json.loads(stdin), **patch}) + "\n").encode() + if mkdir: + os.mkdir(req.run_dir, 0o700) + env = {k: v for k, v in os.environ.items() if not k.startswith(("AGENT_", "LIGHTSPEED_"))} + env["PYTHONPATH"] = str(sandbox_repo) + cmd = [python, "-P", "-m", "tests.step_fakes", scenario, *cli_args] + out_dir = HERE / name + shutil.rmtree(out_dir, ignore_errors=True) + out_dir.mkdir() + try: + if close_stdout: + read_end, write_end = os.pipe() + os.close(read_end) + proc = subprocess.run( + cmd, + input=stdin, + stdout=write_end, + stderr=subprocess.PIPE, + cwd="/", + env=env, + timeout=60, + check=False, + ) + os.close(write_end) + stdout = b"" + else: + proc = subprocess.run( + cmd, input=stdin, capture_output=True, cwd="/", env=env, timeout=60, check=False + ) + stdout = proc.stdout + (out_dir / "stdout.jsonl").write_bytes(stdout) + result = Path(req.run_dir, "result.json") + if result.exists(): + shutil.copyfile(result, out_dir / "result.json") + finally: + shutil.rmtree(req.run_dir, ignore_errors=True) + events = [json.loads(line) for line in stdout.splitlines()] + status, reason, source = expected + return { + "provider": scenario, + "exit_code": proc.returncode, + "event_types": [r["event"]["type"] for r in events if r["type"] == "event"], + "status": status, + "reason": reason, + "result_source": source, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--sandbox-repo", type=Path, required=True) + parser.add_argument("--sandbox-python", help="default: /.venv/bin/python") + args = parser.parse_args() + python = args.sandbox_python or str(args.sandbox_repo / ".venv" / "bin" / "python") + os.makedirs(RUN_ROOT, mode=0o700, exist_ok=True) + sha = subprocess.run( + ["git", "-C", str(args.sandbox_repo), "rev-parse", "HEAD"], + capture_output=True, + text=True, + check=True, + ).stdout.strip() + manifest = { + name: _run(args.sandbox_repo, python, name, spec) for name, spec in SCENARIOS.items() + } + (HERE / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n") + print(f"captured {len(manifest)} scenarios from sandbox {sha}", file=sys.stderr) + + +if __name__ == "__main__": + main() diff --git a/tests/unit/spawner/fixtures/step_cli/hard_deadline/stdout.jsonl b/tests/unit/spawner/fixtures/step_cli/hard_deadline/stdout.jsonl new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit/spawner/fixtures/step_cli/infra_502/result.json b/tests/unit/spawner/fixtures/step_cli/infra_502/result.json new file mode 100644 index 0000000..3e052b7 --- /dev/null +++ b/tests/unit/spawner/fixtures/step_cli/infra_502/result.json @@ -0,0 +1 @@ +{"v": 1, "type": "result", "status_code": 502, "body": {"error": "Infrastructure error: connection refused"}} \ No newline at end of file diff --git a/tests/unit/spawner/fixtures/step_cli/infra_502/stdout.jsonl b/tests/unit/spawner/fixtures/step_cli/infra_502/stdout.jsonl new file mode 100644 index 0000000..e278f74 --- /dev/null +++ b/tests/unit/spawner/fixtures/step_cli/infra_502/stdout.jsonl @@ -0,0 +1 @@ +{"v": 1, "type": "result", "status_code": 502, "body": {"error": "Infrastructure error: connection refused"}} diff --git a/tests/unit/spawner/fixtures/step_cli/manifest.json b/tests/unit/spawner/fixtures/step_cli/manifest.json new file mode 100644 index 0000000..03adf33 --- /dev/null +++ b/tests/unit/spawner/fixtures/step_cli/manifest.json @@ -0,0 +1,80 @@ +{ + "agent_error": { + "event_types": [], + "exit_code": 0, + "provider": "agent_error", + "reason": "agent_failed", + "result_source": "stdout", + "status": "failed" + }, + "hard_deadline": { + "event_types": [], + "exit_code": 124, + "provider": "stubborn", + "reason": "deadline", + "result_source": null, + "status": "error" + }, + "infra_502": { + "event_types": [], + "exit_code": 0, + "provider": "infra", + "reason": "infrastructure_error", + "result_source": "stdout", + "status": "error" + }, + "nan": { + "event_types": [ + "tool_call" + ], + "exit_code": 0, + "provider": "nan", + "reason": "ok", + "result_source": "stdout", + "status": "completed" + }, + "ok": { + "event_types": [ + "tool_call", + "tool_result", + "result" + ], + "exit_code": 0, + "provider": "ok", + "reason": "ok", + "result_source": "stdout", + "status": "completed" + }, + "rejected_run_dir": { + "event_types": [], + "exit_code": 2, + "provider": "ok", + "reason": "rundir_rejected", + "result_source": null, + "status": "failed" + }, + "rejected_schema": { + "event_types": [], + "exit_code": 2, + "provider": "ok", + "reason": "rejected", + "result_source": null, + "status": "failed" + }, + "soft_timeout_502": { + "event_types": [], + "exit_code": 0, + "provider": "hang", + "reason": "infrastructure_error", + "result_source": "stdout", + "status": "error" + }, + "stdout_closed": { + "event_types": [], + "exit_code": 4, + "provider": "ok", + "reason": "result_unverified", + "result_source": "file", + "status": "failed" + } +} diff --git a/tests/unit/spawner/fixtures/step_cli/nan/result.json b/tests/unit/spawner/fixtures/step_cli/nan/result.json new file mode 100644 index 0000000..e0d4108 --- /dev/null +++ b/tests/unit/spawner/fixtures/step_cli/nan/result.json @@ -0,0 +1 @@ +{"v": 1, "type": "result", "status_code": 200, "body": {"success": true, "summary": "s", "x": null}} \ No newline at end of file diff --git a/tests/unit/spawner/fixtures/step_cli/nan/stdout.jsonl b/tests/unit/spawner/fixtures/step_cli/nan/stdout.jsonl new file mode 100644 index 0000000..2f28c26 --- /dev/null +++ b/tests/unit/spawner/fixtures/step_cli/nan/stdout.jsonl @@ -0,0 +1,2 @@ +{"v": 1, "type": "event", "event": {"ts": "2026-11-01T04:54:43.762556+00:00", "type": "tool_call", "data": {"name": "Bash", "input": "oc get pods"}}} +{"v": 1, "type": "result", "status_code": 200, "body": {"success": true, "summary": "s", "x": null}} diff --git a/tests/unit/spawner/fixtures/step_cli/ok/result.json b/tests/unit/spawner/fixtures/step_cli/ok/result.json new file mode 100644 index 0000000..b845518 --- /dev/null +++ b/tests/unit/spawner/fixtures/step_cli/ok/result.json @@ -0,0 +1 @@ +{"v": 1, "type": "result", "status_code": 200, "body": {"success": true, "summary": "mock result", "rootCause": "oom"}} \ No newline at end of file diff --git a/tests/unit/spawner/fixtures/step_cli/ok/stdout.jsonl b/tests/unit/spawner/fixtures/step_cli/ok/stdout.jsonl new file mode 100644 index 0000000..7e04aa9 --- /dev/null +++ b/tests/unit/spawner/fixtures/step_cli/ok/stdout.jsonl @@ -0,0 +1,4 @@ +{"v": 1, "type": "event", "event": {"ts": "2026-11-01T04:54:42.556907+00:00", "type": "tool_call", "data": {"name": "Bash", "input": "oc get pods"}}} +{"v": 1, "type": "event", "event": {"ts": "2026-11-01T04:54:42.557169+00:00", "type": "tool_result", "data": {"output": "pod-a Running"}}} +{"v": 1, "type": "event", "event": {"ts": "2026-11-01T04:54:42.557215+00:00", "type": "result", "data": {"text": "{\"success\": true, \"summary\": \"mock result\", \"rootCause\": \"oom\"}", "cost_usd": 0.01, "input_tokens": 100, "output_tokens": 50}}} +{"v": 1, "type": "result", "status_code": 200, "body": {"success": true, "summary": "mock result", "rootCause": "oom"}} diff --git a/tests/unit/spawner/fixtures/step_cli/rejected_run_dir/stdout.jsonl b/tests/unit/spawner/fixtures/step_cli/rejected_run_dir/stdout.jsonl new file mode 100644 index 0000000..93afb5b --- /dev/null +++ b/tests/unit/spawner/fixtures/step_cli/rejected_run_dir/stdout.jsonl @@ -0,0 +1 @@ +{"v": 1, "type": "result", "status_code": 422, "body": {"error": "runDir must be an existing directory, not a symlink"}} diff --git a/tests/unit/spawner/fixtures/step_cli/rejected_schema/stdout.jsonl b/tests/unit/spawner/fixtures/step_cli/rejected_schema/stdout.jsonl new file mode 100644 index 0000000..455b6dc --- /dev/null +++ b/tests/unit/spawner/fixtures/step_cli/rejected_schema/stdout.jsonl @@ -0,0 +1 @@ +{"v": 1, "type": "result", "status_code": 422, "body": {"error": "Invalid request", "detail": [{"type": "extra_forbidden", "loc": ["allowedTools"], "msg": "Extra inputs are not permitted"}]}} diff --git a/tests/unit/spawner/fixtures/step_cli/soft_timeout_502/result.json b/tests/unit/spawner/fixtures/step_cli/soft_timeout_502/result.json new file mode 100644 index 0000000..8bda226 --- /dev/null +++ b/tests/unit/spawner/fixtures/step_cli/soft_timeout_502/result.json @@ -0,0 +1 @@ +{"v": 1, "type": "result", "status_code": 502, "body": {"error": "Agent timed out after 1000ms"}} \ No newline at end of file diff --git a/tests/unit/spawner/fixtures/step_cli/soft_timeout_502/stdout.jsonl b/tests/unit/spawner/fixtures/step_cli/soft_timeout_502/stdout.jsonl new file mode 100644 index 0000000..96b60d0 --- /dev/null +++ b/tests/unit/spawner/fixtures/step_cli/soft_timeout_502/stdout.jsonl @@ -0,0 +1 @@ +{"v": 1, "type": "result", "status_code": 502, "body": {"error": "Agent timed out after 1000ms"}} diff --git a/tests/unit/spawner/fixtures/step_cli/stdout_closed/result.json b/tests/unit/spawner/fixtures/step_cli/stdout_closed/result.json new file mode 100644 index 0000000..b845518 --- /dev/null +++ b/tests/unit/spawner/fixtures/step_cli/stdout_closed/result.json @@ -0,0 +1 @@ +{"v": 1, "type": "result", "status_code": 200, "body": {"success": true, "summary": "mock result", "rootCause": "oom"}} \ No newline at end of file diff --git a/tests/unit/spawner/fixtures/step_cli/stdout_closed/stdout.jsonl b/tests/unit/spawner/fixtures/step_cli/stdout_closed/stdout.jsonl new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit/spawner/test_exec_request.py b/tests/unit/spawner/test_exec_request.py new file mode 100644 index 0000000..6afedf5 --- /dev/null +++ b/tests/unit/spawner/test_exec_request.py @@ -0,0 +1,262 @@ +"""Unit tests for the step CLI stdin request builder.""" + +import json +import logging +import random +import re + +import pytest + +from cloud_agents.spawner.exec_request import ( + GATEWAY_MAX_MESSAGE_BYTES, + MAX_STEP_REQUEST_BYTES, + check_exec_message_size, + MAX_TIMEOUT_MS, + RUN_ROOT, + StepRequestError, + StepRequestTooLarge, + build_step_request, + derive_step_id, + new_run_dir, +) + +# lightspeed-agentic-sandbox routes/models.py StepRequest +STEP_ID_RE = re.compile(r"^[a-z0-9-]{1,40}$") +STEP_REQUEST_FIELDS = { + "query", + "systemPrompt", + "outputSchema", + "context", + "timeout_ms", + "stepId", + "runDir", + "traceparent", +} + + +def _names(): + rng = random.Random(1234) + alphabet = "aZ09 -_./:\\\n\t\x00éß☃İffi𝔘​\ud800" + names = ["", "-", "---", "a" * 1000, "İSTANBUL", "ffi", "..", "/etc/passwd", "Ünïcödé step"] + names += ["".join(rng.choice(alphabet) for _ in range(rng.randint(0, 80))) for _ in range(500)] + return names + + +def _build(step=None, **kwargs): + kwargs.setdefault("workflow_id", "wf-1") + kwargs.setdefault("attempt", 1) + kwargs.setdefault("context", {"steps": {}}) + return build_step_request(step if step is not None else {"name": "s", "prompt": "p"}, **kwargs) + + +def _payload(req): + assert req.stdin.endswith(b"\n") and req.stdin.count(b"\n") == 1 + return json.loads(req.stdin) + + +class TestStepId: + def test_step_id_matches_cli_pattern_for_arbitrary_names(self): + for name in _names(): + for attempt in (1, 2, 99): + step_id = derive_step_id("wf-ü:1", name, attempt) + assert STEP_ID_RE.fullmatch(step_id), (name, step_id) + + def test_deterministic(self): + assert derive_step_id("wf", "Gather Logs", 1) == derive_step_id("wf", "Gather Logs", 1) + + def test_readable_prefix(self): + assert derive_step_id("wf", "Gather Logs!", 1).startswith("gather-logs-") + + def test_collision_resistant(self): + ids = {derive_step_id("wf", name, 1) for name in _names()} + assert len(ids) == len(set(_names())) + # Same slug, different names / workflows / attempts. + variants = [ + ("wf", "a b", 1), + ("wf", "a_b", 1), + ("wf", "A B", 1), + ("wf2", "a b", 1), + ("wf", "a b", 2), + ("wf:a", "b", 1), + ("wf", "a:b", 1), + ] + assert len({derive_step_id(*v) for v in variants}) == len(variants) + + +class TestRunDir: + def test_direct_child_of_run_root(self): + run_dir = new_run_dir("step-abc") + + parent, _, name = run_dir.rpartition("/") + assert parent == RUN_ROOT == "/tmp/lsrun" + assert re.fullmatch(r"step-abc-[0-9a-f]{16}", name) + + def test_fresh_each_call(self): + assert new_run_dir("s") != new_run_dir("s") + + def test_custom_run_root(self): + assert new_run_dir("s", "/var/tmp/x").startswith("/var/tmp/x/s-") + + @pytest.mark.parametrize( + "root", ["relative", "/tmp/lsrun/", "/tmp//lsrun", "/tmp/../lsrun", ""] + ) + def test_rejects_non_normalized_root(self, root): + with pytest.raises(ValueError): + new_run_dir("s", root) + + def test_rejects_invalid_step_id(self): + with pytest.raises(ValueError): + new_run_dir("../x") + + +class TestBuildStepRequest: + def test_same_fields_as_http_run(self): + step = { + "name": "Diagnose", + "prompt": "Find the root cause", + "output_schema": {"type": "object"}, + } + req = _build(step, context={"steps": {"a": 1}}, system_prompt="be careful") + payload = _payload(req) + + assert payload["query"] == "Find the root cause" + assert payload["context"] == {"steps": {"a": 1}} + assert payload["systemPrompt"] == "be careful" + assert payload["outputSchema"] == {"type": "object"} + assert payload["stepId"] == req.step_id == derive_step_id("wf-1", "Diagnose", 1) + assert payload["runDir"] == req.run_dir + assert req.run_dir.startswith(f"{RUN_ROOT}/{req.step_id}-") + assert set(payload) <= STEP_REQUEST_FIELDS + + def test_optional_fields_omitted(self): + payload = _payload(_build({"name": "s"})) + + assert payload["query"] == "" + for key in ("systemPrompt", "outputSchema", "timeout_ms", "traceparent"): + assert key not in payload + + def test_timeout_ms(self): + assert _payload(_build(timeout_seconds=90))["timeout_ms"] == 90_000 + assert _payload(_build(timeout_seconds=MAX_TIMEOUT_MS // 1000))["timeout_ms"] == ( + MAX_TIMEOUT_MS + ) + + @pytest.mark.parametrize("seconds", [0, -1, MAX_TIMEOUT_MS // 1000 + 1]) + def test_timeout_out_of_range(self, seconds): + with pytest.raises(StepRequestError, match="timeout"): + _build(timeout_seconds=seconds) + + def test_allowed_tools_omitted_with_warning(self, caplog): + step = { + "name": "s", + "prompt": "p", + "permissions": {"allowed_tools": ["Bash"], "denied_tools": ["Write"]}, + } + with caplog.at_level(logging.WARNING, logger="cloud_agents.spawner.exec_request"): + payload = _payload(_build(step)) + + assert not {"allowedTools", "deniedTools", "allowed_tools", "denied_tools"} & set(payload) + assert "not enforced" in caplog.text + assert "'s'" in caplog.text + + def test_no_warning_without_tools(self, caplog): + with caplog.at_level(logging.WARNING, logger="cloud_agents.spawner.exec_request"): + _build({"name": "s", "permissions": {"timeout_seconds": 5}}) + + assert caplog.text == "" + + def test_includes_traceparent(self, monkeypatch): + tp = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01" + + def fake_inject(headers): + headers.update({"traceparent": tp, "tracestate": "k=v"}) + return headers + + monkeypatch.setattr("cloud_agents.spawner.exec_request.inject_traceparent", fake_inject) + payload = _payload(_build()) + + assert payload["traceparent"] == tp + assert "tracestate" not in payload + + def test_unicode_sent_as_utf8(self): + req = _build({"name": "s", "prompt": "naïve ☃"}) + + assert "naïve ☃".encode() in req.stdin + assert _payload(req)["query"] == "naïve ☃" + + def test_max_size_accepted(self): + overhead = len(_build({"name": "s", "prompt": ""}).stdin) + req = _build({"name": "s", "prompt": "x" * (MAX_STEP_REQUEST_BYTES - overhead)}) + + assert len(req.stdin) == MAX_STEP_REQUEST_BYTES + + def test_too_large_raises_before_exec(self): + overhead = len(_build({"name": "s", "prompt": ""}).stdin) + with pytest.raises(StepRequestTooLarge, match=str(MAX_STEP_REQUEST_BYTES)) as exc: + _build({"name": "s", "prompt": "x" * (MAX_STEP_REQUEST_BYTES - overhead + 1)}) + + assert isinstance(exc.value, StepRequestError) + assert "'s'" in str(exc.value) + + def test_cap_fits_cli_and_gateway(self): + # CLI reads at most 1 MiB including the newline; the gateway's 1 MiB gRPC + # message also carries env and argv. + assert MAX_STEP_REQUEST_BYTES <= 1024 * 1024 - 64 * 1024 + + def test_too_large_counts_utf8_bytes(self): + overhead = len(_build({"name": "s", "prompt": ""}).stdin) + with pytest.raises(StepRequestTooLarge): + _build({"name": "s", "prompt": "☃" * ((MAX_STEP_REQUEST_BYTES - overhead) // 3 + 1)}) + + def test_nan_in_context_rejected(self): + with pytest.raises(StepRequestError, match="JSON"): + _build(context={"x": float("nan")}) + + def test_lone_surrogate_rejected(self): + with pytest.raises(StepRequestError, match="JSON"): + _build({"name": "s", "prompt": "bad \ud800"}) + + def test_mcp_without_plain_headers_ok(self): + servers = [ + {"name": "k8s", "url": "http://mcp", "headers": {}}, + { + "name": "gh", + "url": "http://gh", + "secret_headers": {"Authorization": {"secret_name": "s", "key": "k"}}, + }, + ] + _payload(_build(mcp_servers=servers)) + + def test_mcp_empty_header_name_rejected(self): + servers = [{"name": "gh", "url": "http://gh", "headers": {"": "SECRET"}}] + with pytest.raises(StepRequestError): + _build(mcp_servers=servers) + + def test_mcp_plain_headers_rejected(self): + servers = [{"name": "gh", "url": "http://gh", "headers": {"Authorization": "tok-123"}}] + with pytest.raises(StepRequestError, match="gh") as exc: + _build(mcp_servers=servers) + + assert "tok-123" not in str(exc.value) + + def test_request_contains_no_mcp_config(self): + servers = [{"name": "k8s", "url": "http://mcp-sentinel"}] + req = _build(mcp_servers=servers) + + assert b"mcp-sentinel" not in req.stdin + + +class TestExecMessageSize: + def test_fits(self): + check_exec_message_size(b"x" * 1000, {"A": "b"}, ["sh", "-c", "true"]) + + def test_env_counts_toward_gateway_cap(self): + stdin = b"x" * (MAX_STEP_REQUEST_BYTES - 10) + env = {"LIGHTSPEED_MCP_SERVERS": "y" * (GATEWAY_MAX_MESSAGE_BYTES - MAX_STEP_REQUEST_BYTES)} + check_exec_message_size(stdin, {}, []) + with pytest.raises(StepRequestTooLarge, match="env"): + check_exec_message_size(stdin, env, []) + + def test_argv_counts(self): + with pytest.raises(StepRequestTooLarge): + check_exec_message_size(b"", {}, ["a" * GATEWAY_MAX_MESSAGE_BYTES]) diff --git a/tests/unit/spawner/test_step_protocol.py b/tests/unit/spawner/test_step_protocol.py new file mode 100644 index 0000000..796d024 --- /dev/null +++ b/tests/unit/spawner/test_step_protocol.py @@ -0,0 +1,810 @@ +"""Unit tests for the step CLI exec protocol reader and outcome mapping. + +Every stdout line and result.json is untrusted (step-cli.md trust model), so +most tests here are adversarial. +""" + +import json +from pathlib import Path + +import pytest + +from cloud_agents.workflow.core.execution import is_transient_failure +from cloud_agents.spawner.step_protocol import ( + MAX_EVENT_LINE, + MAX_PREPROTOCOL_NOISE, + MAX_RESULT_LINE, + MAX_STDERR_TAIL, + MAX_STDOUT_TOTAL, + MAX_TRANSCRIPT_EVENTS, + StepProtocolReader, + map_outcome, + needs_result_file, +) + +FIXTURES = Path(__file__).parent / "fixtures" / "step_cli" + + +def _event(type_="tool_call", **data): + return {"v": 1, "type": "event", "event": {"ts": "t", "type": type_, "data": data}} + + +def _result(status_code=200, body=None): + if body is None: + body = {"success": True, "summary": "ok"} + return {"v": 1, "type": "result", "status_code": status_code, "body": body} + + +def _line(record) -> bytes: + return json.dumps(record).encode() + b"\n" + + +def _read(*chunks: bytes, stderr: bytes = b"") -> StepProtocolReader: + reader = StepProtocolReader() + if stderr: + reader.feed("stderr", stderr) + for chunk in chunks: + reader.feed("stdout", chunk) + reader.finish() + return reader + + +class TestReader: + def test_events_then_result(self): + reader = StepProtocolReader() + new = reader.feed("stdout", _line(_event(name="Bash")) + _line(_event("tool_result"))) + reader.feed("stdout", _line(_result())) + reader.finish() + + assert [e.type for e in new] == ["tool_call", "tool_result"] + assert new[0].data == {"name": "Bash"} + assert [e.type for e in reader.events] == ["tool_call", "tool_result"] + assert reader.result.status_code == 200 + assert reader.violation is None and reader.protocol_errors == 0 + + def test_utf8_split_across_chunks(self): + event = json.dumps(_event(input="héllo ☃"), ensure_ascii=False).encode() + b"\n" + data = event + _line(_result()) + split = data.index("☃".encode()) + 1 # inside the 3-byte sequence + reader = _read(data[:split], data[split:]) + + assert reader.events[0].data == {"input": "héllo ☃"} + assert reader.result is not None + + def test_every_byte_its_own_chunk(self): + data = _line(_event()) + _line(_result()) + reader = _read(*(data[i : i + 1] for i in range(len(data)))) + + assert len(reader.events) == 1 and reader.result is not None + + @pytest.mark.parametrize( + "bad_line", + [ + b'{"v":1,"type":"event","event":{"ts":"t","type":"tool_call","data":{"x":NaN}}}', + b'{"v":1,"type":"event","event":{"ts":"t","type":"tool_call","data":{"x":Infinity}}}', + b'{"v":1,"type":"event","event":{"ts":"t","type":"tool_call","data":{"x":-Infinity}}}', + b'{"v":1,"type":"event","event":{"ts":"t","type":"tool_call","data":{"x":1e999}}}', + ], + ) + def test_rejects_nan(self, bad_line): + reader = _read(_line(_event()), bad_line + b"\n", _line(_result())) + + assert len(reader.events) == 1 + assert reader.protocol_errors == 1 + assert reader.result is not None + + def test_rejects_nan_in_result(self): + line = b'{"v":1,"type":"result","status_code":200,"body":{"success":true,"summary":"s","c":NaN}}' + reader = _read(_line(_event()), line + b"\n") + + assert reader.result is None + assert reader.protocol_errors == 1 + + @pytest.mark.parametrize( + "record", + [ + {**_event(), "extra": 1}, + { + "v": 1, + "type": "event", + "event": {"ts": "t", "type": "tool_call", "data": {}, "x": 1}, + }, + {"v": 2, "type": "event", "event": {"ts": "t", "type": "tool_call", "data": {}}}, + {"v": True, "type": "event", "event": {"ts": "t", "type": "tool_call", "data": {}}}, + {"v": 1.0, "type": "event", "event": {"ts": "t", "type": "tool_call", "data": {}}}, + {"v": 1, "type": "event", "event": {"ts": 1, "type": "tool_call", "data": {}}}, + {"v": 1, "type": "event", "event": {"ts": "t", "type": "tool_call", "data": []}}, + {"v": 1, "type": "event", "event": {"ts": "t", "type": "unknown", "data": {}}}, + {"v": 1, "type": "event"}, + {"v": 1, "type": ["event"]}, + {"v": 1, "type": "other"}, + [1, 2], + "event", + ], + ) + def test_invalid_event_records_dropped_and_counted(self, record): + reader = _read(_line(_event()), _line(record), _line(_result())) + + assert len(reader.events) == 1 + assert reader.protocol_errors == 1 + assert reader.result is not None + + @pytest.mark.parametrize( + "record", + [ + {**_result(), "extra": 1}, + _result(status_code="200"), + _result(status_code=200.0), + _result(status_code=True), + _result(status_code=99), + _result(status_code=600), + _result(body=[]), + _result(body={"success": True}), + _result(body={"summary": "s"}), + _result(body={"success": "true", "summary": "s"}), + _result(body={"success": 1, "summary": "s"}), + _result(body={"success": True, "summary": None}), + ], + ) + def test_invalid_result_records_dropped(self, record): + reader = _read(_line(_event()), _line(record)) + + assert reader.result is None + assert reader.protocol_errors == 1 + + def test_200_body_requires_success_and_summary(self): + ok = _read(_line(_result(body={"success": False, "summary": "s", "rootCause": "oom"}))) + bad = _read(_line(_event()), _line(_result(body={"error": "x"}))) + + assert ok.result.body == {"success": False, "summary": "s", "rootCause": "oom"} + assert bad.result is None + + def test_non_200_body_is_any_object(self): + reader = _read(_line(_result(502, {"error": "Agent timed out after 1000ms"}))) + + assert reader.result.status_code == 502 + + def test_duplicate_keys_rejected(self): + line = b'{"v":1,"type":"result","status_code":502,"status_code":200,"body":{"success":true,"summary":"s"}}' + reader = _read(_line(_event()), line + b"\n") + + assert reader.result is None + assert reader.protocol_errors == 1 + + def test_moderate_nesting_accepted(self): + reader = _read(_line(_event(x=[[{"a": [1]}]])), _line(_result())) + + assert reader.events[0].data == {"x": [[{"a": [1]}]]} + + def test_deep_nesting_does_not_crash(self): + line = b'{"v":1,"type":"event","event":{"ts":"t","type":"tool_call","data":{"x":' + ( + b"[" * 100_000 + b"]" * 100_000 + b"}}}\n" + ) + reader = _read(_line(_event()), line, _line(_result())) + + assert len(reader.events) == 1 and reader.result is not None + + def test_huge_integer_does_not_crash(self): + line = b'{"v":1,"type":"event","event":{"ts":"t","type":"tool_call","data":{"x":%s}}}\n' % ( + b"9" * 10_000 + ) + reader = _read(_line(_event()), line, _line(_result())) + + assert reader.protocol_errors == 1 and reader.result is not None + + def test_non_utf8_line_dropped(self): + reader = _read(_line(_event()), b'{"v":1,"type":"event","\xff\xfe"}\n', _line(_result())) + + assert reader.protocol_errors == 1 + assert reader.result is not None + + def test_oversize_event_dropped_and_counted(self): + big = _line(_event(input="x" * MAX_EVENT_LINE)) + assert MAX_EVENT_LINE < len(big) < MAX_RESULT_LINE + reader = _read(_line(_event()), big, _line(_event("tool_result")), _line(_result())) + + assert [e.type for e in reader.events] == ["tool_call", "tool_result"] + assert reader.oversized_lines == 1 + assert reader.result is not None + + def test_large_result_line_accepted(self): + record = _result(body={"success": False, "summary": "x" * (MAX_EVENT_LINE * 4)}) + reader = _read(_line(_event()), _line(record)) + + assert reader.result is not None + assert reader.oversized_lines == 0 + + def test_line_over_result_cap_is_not_buffered(self): + reader = StepProtocolReader() + reader.feed("stdout", _line(_event())) + chunk = b"x" * (1024 * 1024) + for _ in range(MAX_RESULT_LINE // len(chunk) + 2): + reader.feed("stdout", chunk) + assert len(reader._buf) <= MAX_RESULT_LINE + reader.feed("stdout", b"\n" + _line(_result())) + reader.finish() + + assert reader.oversized_lines == 1 + assert reader.result is not None + + def test_second_result_is_violation(self): + reader = _read(_line(_result(502, {"error": "x"})), _line(_result())) + + assert reader.violation is not None + assert reader.result is None + + def test_line_after_result_is_violation(self): + reader = _read(_line(_event()), _line(_result()), _line(_event())) + + assert reader.violation is not None + assert reader.result is None + assert len(reader.events) == 1 + + def test_garbage_after_result_is_violation(self): + reader = _read(_line(_result()), b"junk\n") + + assert reader.violation is not None and reader.result is None + + def test_result_before_events_is_violation(self): + reader = _read(_line(_result()), _line(_event()), _line(_event("tool_result"))) + + assert reader.violation is not None + assert reader.result is None + assert reader.events == [] + + def test_partial_last_line_is_truncated_not_accepted(self): + data = _line(_result()) + reader = _read(_line(_event()), data[:-1]) # complete JSON, no newline + + assert reader.result is None + assert reader.truncated + + def test_truncated_result_line(self): + data = _line(_result()) + reader = _read(_line(_event()), data[: len(data) // 2]) + + assert reader.result is None + assert reader.truncated + assert reader.violation is None + + def test_partial_line_after_result_is_violation(self): + reader = _read(_line(_result()), b'{"v":1') + + assert reader.violation is not None and reader.result is None + + def test_preprotocol_noise_tolerated(self): + reader = _read(b"Welcome to the login shell\n\n", _line(_event()), _line(_result())) + + assert len(reader.events) == 1 + assert reader.protocol_errors == 0 + assert reader.result is not None + assert reader.abort_reason is None + + def test_preprotocol_noise_capped_64k(self): + reader = StepProtocolReader() + line = b"n" * 1023 + b"\n" + for _ in range(MAX_PREPROTOCOL_NOISE // len(line)): + reader.feed("stdout", line) + assert reader.abort_reason is None + reader.feed("stdout", line) + + assert reader.abort_reason == "preprotocol_noise" + + def test_preprotocol_oversized_line_aborts(self): + reader = _read(b"n" * (MAX_RESULT_LINE + 1) + b"\n") + + assert reader.abort_reason == "preprotocol_noise" + + def test_noise_after_protocol_is_protocol_error(self): + reader = _read(_line(_event()), b"noise\n", _line(_result())) + + assert reader.protocol_errors == 1 and reader.result is not None + + def test_output_too_large_aborts_and_stops_parsing(self): + reader = StepProtocolReader() + chunk = _line(_event(input="x" * 1000)) * 1000 + fed = 0 + while fed <= MAX_STDOUT_TOTAL: + reader.feed("stdout", chunk) + fed += len(chunk) + assert reader.abort_reason == "output_too_large" + assert reader.feed("stdout", _line(_result())) == [] + reader.finish() + assert reader.result is None + + def test_transcript_bounded_with_truncation_marker(self): + reader = StepProtocolReader() + line = _line(_event()) + reader.feed("stdout", line * (MAX_TRANSCRIPT_EVENTS + 50)) + more = reader.feed("stdout", line) + reader.feed("stdout", _line(_result())) + reader.finish() + + assert len(more) == 1 # still forwarded for progress + assert len(reader.events) == MAX_TRANSCRIPT_EVENTS + 1 + marker = reader.events[-1] + assert marker.type == "error" + assert marker.data["message"] == "transcript truncated" + assert marker.data["dropped_events"] == 51 + + def test_unknown_stream_rejected(self): + with pytest.raises(ValueError): + StepProtocolReader().feed("stdin", b"x") + + +class TestStderr: + def test_pid_from_first_stderr_line(self): + reader = _read(stderr=b"lsrun-pid 4242\nINFO starting\n") + + assert reader.pid == 4242 + + def test_pid_line_split_across_chunks(self): + reader = StepProtocolReader() + reader.feed("stderr", b"lsrun-") + reader.feed("stderr", b"pid 77") + reader.feed("stderr", b"\nrest") + + assert reader.pid == 77 + + def test_pid_only_from_first_stderr_line(self): + reader = StepProtocolReader() + reader.feed("stderr", b"INFO noise\n") + reader.feed("stderr", b"lsrun-pid 4242\n") + + assert reader.pid is None + + def test_later_pid_lines_ignored(self): + reader = StepProtocolReader() + reader.feed("stderr", b"lsrun-pid 10\nlsrun-pid 20\n") + reader.feed("stderr", b"lsrun-pid 30\n") + + assert reader.pid == 10 + + @pytest.mark.parametrize( + "line", + [ + b"lsrun-pid 0", + b"lsrun-pid 012", + b"lsrun-pid -5", + b"lsrun-pid 12345678901", + b"lsrun-pid 12 ", + b" lsrun-pid 12", + b"lsrun-pid 12\r", + b"lsrun-pid \xd9\xa3", # Arabic-Indic digit three + ], + ) + def test_malformed_pid_line(self, line): + assert _read(stderr=line + b"\n").pid is None + + def test_unterminated_pid_line_not_accepted(self): + assert _read(stderr=b"lsrun-pid 12").pid is None + + def test_overlong_first_line_without_newline(self): + reader = StepProtocolReader() + reader.feed("stderr", b"lsrun-pid 1" + b"1" * 1000) + reader.feed("stderr", b"\nlsrun-pid 5\n") + + assert reader.pid is None + + def test_stderr_tail_bounded_and_redacted(self): + reader = StepProtocolReader() + reader.feed("stderr", b"lsrun-pid 1\n" + b"a" * (MAX_STDERR_TAIL * 2)) + reader.feed("stderr", b"\nerror: token sk-secret leaked\n") + + tail = reader.stderr_tail({"sk-secret"}) + assert len(tail) <= MAX_STDERR_TAIL + assert "sk-secret" not in tail + assert "***REDACTED***" in tail + + @pytest.mark.parametrize("kept", range(1, 20)) + def test_stderr_tail_secret_straddling_window_is_redacted(self, kept): + # The last `kept` chars of the secret sit inside a MAX_STDERR_TAIL window. + secret = "sk-0123456789abcdef" + reader = StepProtocolReader() + reader.feed("stderr", b"lsrun-pid 1\n" + b"x" * 100_000 + secret.encode()) + reader.feed("stderr", b"y" * (MAX_STDERR_TAIL - kept)) + + tail = reader.stderr_tail({secret}) + for i in range(1, len(secret) - 3): + assert secret[i:] not in tail + assert len(tail) <= MAX_STDERR_TAIL + + def test_stderr_tail_tolerates_split_utf8(self): + reader = StepProtocolReader() + reader.feed("stderr", "☃".encode() * MAX_STDERR_TAIL) + + assert isinstance(reader.stderr_tail(set()), str) + + +def _ok_stdout(): + return _read(_line(_event()), _line(_result()), stderr=b"lsrun-pid 9\n") + + +def _empty(pid=True): + return _read(stderr=b"lsrun-pid 9\n" if pid else b"") + + +FILE_OK = json.dumps(_result(body={"success": True, "summary": "from file"})).encode() + + +class TestNeedsResultFile: + @pytest.mark.parametrize( + ("exit_code", "reader", "expected"), + [ + (0, _ok_stdout, False), + (0, _empty, False), + (4, _empty, True), + (4, _ok_stdout, True), + (None, _empty, True), + (None, _ok_stdout, True), + (1, _empty, False), + (2, _empty, False), + (3, _empty, False), + (124, _empty, False), + (137, _empty, False), + (143, _empty, False), + ], + ) + def test_matrix(self, exit_code, reader, expected): + assert needs_result_file(exit_code, reader()) is expected + + def test_not_after_violation_or_abort(self): + violated = _read(_line(_result()), _line(_result())) + assert not needs_result_file(0, violated) + aborted = _read(b"n" * (MAX_RESULT_LINE + 1) + b"\n") + assert not needs_result_file(0, aborted) + + +class TestMapOutcome: + def test_success_from_stdout(self): + out = map_outcome(0, _ok_stdout()) + + assert out.status == "completed" + assert out.body == {"success": True, "summary": "ok"} + assert out.breaker == "success" + assert out.result_source == "stdout" + + def test_success_false_is_failed(self): + reader = _read(_line(_result(body={"success": False, "summary": "Agent error: boom"}))) + out = map_outcome(0, reader) + + assert out.status == "failed" + assert out.error == "agent returned success=false" # same default as HTTP today + assert out.breaker == "failure" + + def test_success_false_uses_body_error(self): + body = {"success": False, "summary": "s", "error": "bad thing"} + out = map_outcome(0, _read(_line(_result(body=body)))) + + assert out.error == "bad thing" + assert out.body == body + + def test_502_raises_like_http(self): + out = map_outcome(0, _read(_line(_result(502, {"error": "Infrastructure error: x"})))) + + assert out.status == "error" + assert out.error == "Infrastructure error from sandbox (502)" + assert out.breaker == "failure" + + def test_other_status_is_failed(self): + out = map_outcome(0, _read(_line(_result(400, {"error": "nope"})))) + + assert out.status == "failed" + assert out.error == "sandbox returned 400: nope" + assert out.breaker == "failure" + + @pytest.mark.parametrize( + "stdout", + [ + b"", + _line(_result())[:-5], # truncated + _line(_result())[:-1], # complete JSON, no newline + _line(_result(body={"success": "yes", "summary": "s"})), # rejected + ], + ) + def test_exit0_without_valid_line_is_violation_not_file(self, stdout): + out = map_outcome(0, _read(_line(_event()), stdout), FILE_OK) + + assert (out.status, out.reason, out.breaker) == ("failed", "protocol_violation", None) + assert out.result_source is None + + def test_exit0_too_deep_line_with_forged_file_is_violation(self): + # The agent makes its own result too deep to accept, then a setsid'd + # descendant replaces result.json with a forged success. + deep = {"success": True, "summary": "s", "x": json.loads("[" * 70 + "]" * 70)} + forged = json.dumps(_result(body={"success": True, "summary": "forged"})).encode() + reader = _read(_line(_event()), _line(_result(body=deep))) + + assert reader.result is None + assert not needs_result_file(0, reader) + out = map_outcome(0, reader, forged) + assert (out.status, out.reason, out.breaker) == ("failed", "protocol_violation", None) + + def test_exit0_oversized_result_line_is_violation(self): + record = _result(body={"success": True, "summary": "x" * MAX_RESULT_LINE}) + out = map_outcome(0, _read(_line(_event()), _line(record)), FILE_OK) + + assert (out.status, out.reason, out.breaker) == ("failed", "protocol_violation", None) + + @pytest.mark.parametrize("exit_code", [4, None]) + @pytest.mark.parametrize( + "record", + [ + _result(body={"success": True, "summary": "from file"}), + _result(body={"success": False, "summary": "s", "error": "bad"}), + _result(502, {"error": "Infrastructure error: x"}), + _result(400, {"error": "nope"}), + ], + ) + def test_file_result_never_trusted(self, exit_code, record): + # completed may only come from a valid stdout line; result.json is + # replaceable by a same-uid descendant, so it is a diagnostic only. + out = map_outcome(exit_code, _ok_stdout(), json.dumps(record).encode()) + + assert (out.status, out.reason, out.breaker) == ("failed", "result_unverified", None) + assert out.taint_lease + assert out.body is None + assert out.result_source == ("file" if exit_code == 4 else "file_after_transport_loss") + assert str(record["status_code"]) in out.diagnostic + assert "untrusted" in out.diagnostic + assert not is_transient_failure(out.error) + + @pytest.mark.parametrize( + "body", + [ + # Secrets straddling the old 200-char cut, in error and summary. + {"success": False, "summary": "s" * 190 + "SECRETabcdefghij", "error": "e"}, + {"success": True, "summary": "ok", "error": "e" * 195 + "SECRETabcdefghij"}, + {"success": True, "summary": "SECRET" + "q" * 500}, # longer than the old limit + {"success": True, "summary": "☃SECRET☃" * 40}, # multibyte + {"success": True, "summary": "s", "SECRETkey": 1}, # agent-chosen key + {"error": "SECRET timed out 502 connection"}, + {"success": True, "summary": "s", "SECRETabcdefghij": "SECRETabcdefghij"}, + {"success": False, "summary": "s", "error": {"SECRET": ["SECRET"]}}, + {"error": ["SECRET"], "summary": {"SECRET": 1}, "detail": 7}, + ], + ) + def test_file_diagnostic_has_no_file_text(self, body): + status = 200 if "success" in body else 502 + data = json.dumps(_result(status, body), ensure_ascii=False).encode() + for exit_code in (4, None): + out = map_outcome(exit_code, _empty(), data) + + assert out.reason == "result_unverified" + assert "SECRET" not in out.diagnostic + assert "☃" not in out.diagnostic and "timed out" not in out.diagnostic + assert "qqqq" not in out.diagnostic and "ssss" not in out.diagnostic + assert f"status={status}" in out.diagnostic + assert f"bytes={len(data)}" in out.diagnostic + + def test_file_diagnostic_metadata(self): + body = {"success": False, "summary": "s", "error": "e", "rootCause": "x", "other": 1} + out = map_outcome(4, _empty(), json.dumps(_result(body=body)).encode()) + + assert out.diagnostic == ( + "untrusted result.json: status=200 success=False has_error=True has_summary=True " + f"has_detail=False has_output=False other_keys=2 bytes={len(json.dumps(_result(body=body)))}" + ) + + def test_stdout_result_does_not_taint_lease(self): + assert not map_outcome(0, _ok_stdout()).taint_lease + + @pytest.mark.parametrize( + "data", + [ + b"", + b"planted", + json.dumps(_event()).encode(), + b'{"v":1,"type":"result"', + json.dumps(_result(body={"success": "yes", "summary": "s"})).encode(), + b'{"v":1,"type":"result","status_code":200,"body":{"success":true,"summary":"s","x":NaN}}', + b"\xff" + FILE_OK, + ], + ) + def test_exit4_invalid_file_is_violation(self, data): + # Exit 4 promises a complete result.json; anything else is tampering. + out = map_outcome(4, _empty(), data) + + assert (out.status, out.reason, out.breaker) == ("failed", "protocol_violation", None) + assert out.taint_lease + + def test_exit4_unreadable_file_fails(self): + out = map_outcome(4, _empty(), None) + + assert (out.status, out.reason, out.breaker) == ("failed", "no_result", None) + assert out.taint_lease + + def test_result_file_with_trailing_newline_parsed(self): + out = map_outcome(4, _empty(), FILE_OK + b"\n") + + assert out.reason == "result_unverified" + + def test_oversized_result_file_is_protocol_violation(self): + out = map_outcome(4, _empty(), b" " * MAX_RESULT_LINE + FILE_OK) + + assert (out.status, out.reason, out.breaker) == ("failed", "protocol_violation", None) + assert out.taint_lease + + @pytest.mark.parametrize("data", [None, b"planted"]) + def test_transport_loss_no_result_raises(self, data): + out = map_outcome(None, _ok_stdout(), data) + + assert out.status == "error" + assert out.error == "lost exec stream, no result" + assert out.breaker == "failure" + assert out.taint_lease + + def test_exit2_not_retryable_no_breaker(self): + body = {"error": "Invalid request", "detail": [{"type": "extra_forbidden"}]} + out = map_outcome(2, _read(_line(_result(422, body)))) + + assert out.status == "failed" + assert out.reason == "rejected" + assert out.error == "step request rejected (422): Invalid request" + assert out.breaker is None + assert not out.taint_lease + + def test_exit2_413(self): + out = map_outcome(2, _read(_line(_result(413, {"error": "Request exceeds 1048576 bytes"})))) + + assert out.status == "failed" and out.error.startswith("step request rejected (413)") + + def test_exit2_rundir_rejection_taints_lease(self): + body = {"error": "runDir must be an existing directory, not a symlink"} + out = map_outcome(2, _read(_line(_result(422, body)))) + + assert out.status == "failed" + assert out.reason == "rundir_rejected" + assert out.taint_lease + assert out.breaker is None + + def test_exit2_without_line(self): + out = map_outcome(2, _empty()) + + assert out.status == "failed" + assert out.error == "step request rejected (exit 2)" + assert out.breaker is None + + def test_exit2_never_reads_result_file(self): + assert map_outcome(2, _empty(), FILE_OK).status == "failed" + + @pytest.mark.parametrize("pid", [True, False]) + def test_exit1_not_started_taints_lease(self, pid): + out = map_outcome(1, _empty(pid=pid), FILE_OK) + + assert (out.status, out.reason, out.breaker) == ("failed", "step_cli_not_started", None) + assert out.taint_lease + + def test_exit3_fails_without_retry_or_breaker(self): + # Agent-inducible (for example by planting result.json), so deterministic. + out = map_outcome(3, _ok_stdout(), FILE_OK) + + assert (out.status, out.reason, out.breaker) == ("failed", "internal_error", None) + assert "exit 3" in out.error + assert out.result_source is None + + def test_exit124_raises(self): + out = map_outcome(124, _empty(), FILE_OK) + + assert (out.status, out.reason, out.breaker) == ("error", "deadline", "failure") + assert "exit 124" in out.error + assert out.result_source is None + + @pytest.mark.parametrize("code", [137, 143, 130, -9]) + def test_killed(self, code): + out = map_outcome(code, _ok_stdout(), FILE_OK) + + assert (out.status, out.reason, out.breaker) == ("error", "killed", None) + + def test_unexpected_exit_code(self): + out = map_outcome(5, _empty()) + + assert (out.status, out.reason, out.breaker) == ("error", "unexpected_exit", "failure") + + def test_violation_fails_without_fallback(self): + reader = _read(_line(_result()), _line(_result())) + out = map_outcome(0, reader, FILE_OK) + + assert (out.status, out.reason, out.breaker) == ("failed", "protocol_violation", None) + + @pytest.mark.parametrize( + ("data", "reason"), + [ + (b"n" * (MAX_RESULT_LINE + 1) + b"\n", "preprotocol_noise"), + ], + ) + def test_abort_fails_regardless_of_exit(self, data, reason): + for code in (0, 4, None, 137): + out = map_outcome(code, _read(data), FILE_OK) + assert (out.status, out.reason, out.breaker) == ("failed", reason, None) + + +class TestRetryClassification: + """``error`` outcomes raise, but only the 502 one is transient for run_with_retries. + + The rest fail the step without a rerun, so a step's side effects never repeat. + """ + + def test_502_is_transient(self): + out = map_outcome(0, _read(_line(_result(502, {"error": "connection refused"})))) + + assert out.status == "error" + assert is_transient_failure(out.error) + + @pytest.mark.parametrize( + ("exit_code", "reader", "result_file"), + [ + (None, _ok_stdout, None), # lost stream + (None, _ok_stdout, FILE_OK), # lost stream, file unverified + (124, _empty, None), + (137, _ok_stdout, None), + (143, _empty, None), + (-9, _empty, None), + (5, _empty, None), + (4, _empty, None), # unreadable result.json + (4, _empty, FILE_OK), + (4, _empty, json.dumps(_result(502, {"error": "timed out"})).encode()), + (None, _empty, json.dumps(_result(502, {"error": "connection"})).encode()), + (3, _empty, None), + (1, _empty, None), + ], + ) + def test_other_outcomes_not_transient(self, exit_code, reader, result_file): + out = map_outcome(exit_code, reader(), result_file) + + assert out.status != "completed" + assert not is_transient_failure(out.error), out.error + + @pytest.mark.parametrize( + "stdout", + [ + b"", + _line(_result()) + _line(_result()), + b"n" * (MAX_RESULT_LINE + 1) + b"\n", + ], + ) + def test_protocol_failures_not_transient(self, stdout): + out = map_outcome(0, _read(stdout)) + + assert out.status == "failed" + assert not is_transient_failure(out.error), out.error + + +def _manifest(): + return json.loads((FIXTURES / "manifest.json").read_text()) + + +def _chunked(data: bytes, size: int): + return [data[i : i + size] for i in range(0, len(data), size)] or [b""] + + +class TestGoldenFixtures: + """Outputs captured from the real sandbox step CLI (see fixtures/step_cli/README.md).""" + + @pytest.mark.parametrize("scenario", sorted(_manifest())) + @pytest.mark.parametrize("chunk_size", [1, 7, 4096, 1 << 30]) + def test_fixture(self, scenario, chunk_size): + spec = _manifest()[scenario] + stdout = (FIXTURES / scenario / "stdout.jsonl").read_bytes() + result_path = FIXTURES / scenario / "result.json" + result_file = result_path.read_bytes() if result_path.exists() else None + + reader = StepProtocolReader() + reader.feed("stderr", b"lsrun-pid 1234\n") + for chunk in _chunked(stdout, chunk_size): + reader.feed("stdout", chunk) + reader.finish() + + assert reader.protocol_errors == 0 + assert reader.oversized_lines == 0 + assert reader.violation is None and reader.abort_reason is None + assert [e.type for e in reader.events] == spec["event_types"] + file_arg = result_file if needs_result_file(spec["exit_code"], reader) else None + out = map_outcome(spec["exit_code"], reader, file_arg) + assert out.status == spec["status"] + assert out.reason == spec["reason"] + assert out.result_source == spec["result_source"] + + def test_fixture_set_covers_every_cli_outcome(self): + exits = {spec["exit_code"] for spec in _manifest().values()} + assert {0, 2, 4, 124} <= exits