"""Dry run: walk a definition against the tenant's live data with every call as a gateway preview (validation + Cedar policy + the tool's own ``dry_run``, inside a transaction that is rolled back). Reads return real rows; writes return the effect they would have. Nothing is executed, nothing is audited, no approval is created. The report says, per step and item, whether the call would run automatically, would wait for a human, or would be denied, and renders that as plain-language lines for the owner. """ from __future__ import annotations import uuid from typing import Any from pydantic import ValidationError from core.gateway.gateway import Gateway, ToolCall from core.gateway.policy import PolicyOutcome from core.tools.registry import ToolNotFound from core.tools.spec import RiskTier, ToolContext, ToolResult, ToolSpec from core.tools.tenant_tools import ToolUnavailable from core.workflows import refs from core.workflows.dsl import Step, WorkflowDefinition, describe from core.workflows.executor import SIGNOFF_TOOL, is_message_tool, split_args MAX_PREVIEW_ITEMS = 200 # entries shown per step (all items are still counted) KEY_ARGS = ("to", "order_number", "template", "amount", "text", "subject", "number", "sku") def _summary_args(args: dict[str, Any]) -> str: keys = [k for k in KEY_ARGS if k in args] or list(args)[:3] return ", ".join(f"{k}={args[k]}" for k in keys) async def _preview( gateway: Gateway, tenant_id: uuid.UUID, actor: str, tool: str, args: dict[str, Any], tainted: bool, ) -> dict[str, Any]: from core.gateway.taint import split_taint plain, taint = split_taint(args) call = ToolCall( tenant_id=tenant_id, actor=actor, tool=tool, args=plain, taint=taint, dry_run=True ) try: decision, result = await gateway.preview(call) except ToolNotFound: return {"outcome": "denied", "reason": f"unknown tool {tool}", "args": plain} except ValidationError as exc: msg = "; ".join(str(e.get("msg")) for e in exc.errors(include_url=False)) return {"outcome": "error", "reason": f"invalid arguments: {msg}", "args": plain} spec = (await gateway.resolve_tool(tenant_id, tool)).spec if result is None and spec.risk_tier == RiskTier.T0_READ: # Reads without a dry-run mode: run the read itself (no side effects, rolled back), # so later steps can reference real data. result = await _read(gateway, call) entry: dict[str, Any] = {"args": plain, "effect": result.data if result else None} if decision.outcome is PolicyOutcome.DENY: entry.update(outcome="denied", reason="; ".join(decision.errors or decision.reasons)) elif result is not None and not result.ok: entry.update(outcome="error", reason=result.error) elif decision.outcome is PolicyOutcome.REVIEW or spec.risk_tier >= RiskTier.T3_CRITICAL: entry.update( outcome="needs_approval", reason=", ".join(decision.reasons) or "no policy permits it automatically", ) elif any(taint.values()) and spec.sensitive_args: entry.update(outcome="needs_approval", reason="untrusted value in a sensitive argument") else: entry.update(outcome="would_execute", reason=", ".join(decision.reasons) or None) entry["tier"] = int(spec.risk_tier) return entry async def _read(gateway: Gateway, call: ToolCall) -> ToolResult: tool = await gateway.resolve_tool(call.tenant_id, call.tool) async with gateway.db.session(tenant_id=call.tenant_id) as s, s.begin(): ctx = ToolContext( tenant_id=call.tenant_id, actor=call.actor, run_id=None, session=s, dry_run=True ) try: result = await tool.handler(tool.spec.input_model.model_validate(call.args), ctx) except Exception as exc: result = ToolResult(ok=False, error=f"{type(exc).__name__}: {exc}") await s.rollback() return result def _data_of(entry: dict[str, Any], spec_tier: int) -> dict[str, Any]: """What later steps see: a read's real data; a write's previewed effect.""" eff = entry.get("effect") return dict(eff) if isinstance(eff, dict) else {} async def dry_run( gateway: Gateway, tenant_id: uuid.UUID, defn: WorkflowDefinition, *, actor: str = "workflow:dry-run", event: dict[str, Any] | None = None, fire_time: str | None = None, ) -> dict[str, Any]: scope = refs.Scope( event=event, trigger={"type": defn.trigger.type, "fire_time": fire_time}, workflow={"id": defn.id, "key": defn.id, "version": defn.version, "name": defn.name}, ) steps_out: list[dict[str, Any]] = [] totals = {"would_execute": 0, "needs_approval": 0, "denied": 0, "error": 0, "skipped": 0} messages = 0 stopped: str | None = None for step in defn.steps: if stopped: steps_out.append({"id": step.id, "kind": step.kind, "status": "not_reached"}) continue try: entry = await _dry_step(gateway, tenant_id, actor, defn, step, scope) except refs.RefError as exc: entry = { "id": step.id, "kind": step.kind, "status": "error", "reason": f"reference error: {exc}", "items": [], } for it in entry.get("items", []): totals[it["outcome"]] = totals.get(it["outcome"], 0) + 1 if it["outcome"] in ("would_execute", "needs_approval") and it.get("message"): messages += 1 if entry.get("status") == "error" and not entry.get("items"): totals["error"] += 1 steps_out.append(entry) if entry.get("status") in ("error", "denied") and step.on_error == "stop": stopped = step.id po = defn.policy_overrides problems: list[str] = [] if messages > po.max_messages: problems.append(f"{messages} messages exceed max_messages {po.max_messages}") if stopped: problems.append(f"stops at step {stopped}") ok = not problems and totals["denied"] == 0 and totals["error"] == 0 return { "ok": ok, "problems": problems, "totals": totals, "messages": messages, "steps": steps_out, "lines": _lines(defn, steps_out), "plan": describe(defn), "definition_hash": defn.content_hash(), } async def _dry_step( gateway: Gateway, tenant_id: uuid.UUID, actor: str, defn: WorkflowDefinition, step: Step, scope: refs.Scope, ) -> dict[str, Any]: base: dict[str, Any] = {"id": step.id, "kind": step.kind, "tool": step.tool} if step.kind == "wait": assert step.wait is not None return { **base, "status": "wait", "items": [], "summary": f"would wait {step.wait.seconds}s, then continue", } if step.kind == "approval": assert step.approval is not None if not refs.all_hold(step.when, scope): return {**base, "status": "skipped", "items": [], "summary": "skipped (condition)"} text, _ = refs.render(step.approval.summary, scope) scope.steps[step.id] = {"signed_off": True} return { **base, "status": "needs_approval", "tool": SIGNOFF_TOOL, "items": [], "summary": f"would ask a human to sign off: {text}", } try: spec: ToolSpec | None = (await gateway.resolve_tool(tenant_id, str(step.tool))).spec except (ToolNotFound, ToolUnavailable): spec = None if spec is None: return {**base, "status": "denied", "items": [], "reason": f"unknown tool {step.tool}"} signoff = step.requires_approval or spec.name in defn.policy_overrides.require_approval_for if step.for_each is None: if not refs.all_hold(step.when, scope): return {**base, "status": "skipped", "items": [], "summary": "skipped (condition)"} args, tainted = split_args(step.args, scope) e = await _preview(gateway, tenant_id, actor, spec.name, args, tainted) e["message"] = is_message_tool(spec) scope.steps[step.id] = _data_of(e, int(spec.risk_tier)) return { **base, "status": e["outcome"], "items": [e], "signoff": signoff, "summary": _step_summary(step, [e], signoff), } items, tainted = refs.resolve(step.for_each, scope) if items is None: items = [] if not isinstance(items, list): return { **base, "status": "error", "items": [], "reason": f"for_each {step.for_each} is not a list", } cap = min(step.max_items or 10**9, defn.policy_overrides.max_items_per_step) if len(items) > cap: return { **base, "status": "denied", "items": [], "reason": f"{len(items)} items exceed max_items {cap}", } entries: list[dict[str, Any]] = [] results: list[dict[str, Any]] = [] for i, item in enumerate(items): iscope = scope.with_item(item, i, tainted) if not refs.all_hold(step.when, iscope): results.append({"item": item, "status": "skipped"}) continue args, t = split_args(step.args, iscope) e = await _preview(gateway, tenant_id, actor, spec.name, args, t) e["index"], e["message"] = i, is_message_tool(spec) entries.append(e) ok = e["outcome"] in ("would_execute", "needs_approval") results.append( { "item": item, "status": e["outcome"], "data": _data_of(e, int(spec.risk_tier)) if ok else None, } ) scope.steps[step.id] = { "results": results, "count": len(items), "done": sum(1 for r in results if r["status"] == "would_execute"), } worst = "skipped" if not entries else _worst([e["outcome"] for e in entries]) if any(e["outcome"] in ("denied", "error") for e in entries) and step.on_error == "continue": worst = "partial" return { **base, "status": worst, "items": entries[:MAX_PREVIEW_ITEMS], "count": len(items), "selected": len(entries), "signoff": signoff, "summary": _step_summary(step, entries, signoff, total=len(items)), } _RANK = {"error": 4, "denied": 3, "needs_approval": 2, "would_execute": 1, "skipped": 0} def _worst(outcomes: list[str]) -> str: return max(outcomes, key=lambda o: _RANK.get(o, 0)) def _step_summary( step: Step, entries: list[dict[str, Any]], signoff: bool, total: int | None = None ) -> str: n = len(entries) auto = sum(1 for e in entries if e["outcome"] == "would_execute") review = sum(1 for e in entries if e["outcome"] == "needs_approval") bad = n - auto - review head = f"{step.tool} x{n}" + (f" (of {total} items)" if total is not None else "") parts = [f"{auto} automatic", f"{review} need approval"] if bad: parts.append(f"{bad} denied/failed") if signoff: parts.append("after a human sign-off") return f"{head}: " + ", ".join(parts) def _lines(defn: WorkflowDefinition, steps: list[dict[str, Any]]) -> list[str]: """Human-readable diff: one line per step, then one per would-be call.""" out: list[str] = [] for s in steps: if s.get("status") == "not_reached": out.append(f"[{s['id']}] not reached") continue out.append(f"[{s['id']}] {s.get('summary') or s.get('reason') or s.get('status')}") if s.get("reason") and s.get("summary"): out.append(f" ! {s['reason']}") for e in s.get("items", []): if e.get("tier", 0) == 0 and e["outcome"] == "would_execute": eff = e.get("effect") or {} size = next((f"{len(v)} {k}" for k, v in eff.items() if isinstance(v, list)), "") out.append(f" read {_summary_args(e['args'])}" + (f" -> {size}" if size else "")) continue mark = {"would_execute": "+", "needs_approval": "?", "denied": "x", "error": "x"}.get( e["outcome"], " " ) line = f" {mark} {s.get('tool')}({_summary_args(e['args'])})" if e["outcome"] != "would_execute": line += f" [{e['outcome']}: {e.get('reason')}]" out.append(line) return out