Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Add cached script deploy commit mode (#6013)
pedrohsdb29dcb86051e6
diff --git a/skyvern/forge/sdk/db/repositories/workflows.py b/skyvern/forge/sdk/db/repositories/workflows.pyindex 0df562094..bb19a3949 100644--- a/skyvern/forge/sdk/db/repositories/workflows.py+++ b/skyvern/forge/sdk/db/repositories/workflows.py@@ -590,6 +590,7 @@ class WorkflowsRepository(BaseRepository):version: int | None = None,run_with: str | None = None,cache_key: str | None = None,+ code_version: int | None = None,status: str | None = None,import_error: str | None = None,proxy_location: ProxyLocationInput | object = _UNSET,@@ -625,6 +626,8 @@ class WorkflowsRepository(BaseRepository):workflow.run_with = run_withif cache_key is not None:workflow.cache_key = cache_key+ if code_version is not None:+ workflow.code_version = code_versionif status is not None:workflow.status = statusif import_error is not None:@@ -673,6 +676,62 @@ class WorkflowsRepository(BaseRepository):else:raise NotFoundError("Workflow not found")+ @db_operation("update_workflow_dispatch_state_if_latest")+ async def update_workflow_dispatch_state_if_latest(+ self,+ *,+ workflow_id: str,+ workflow_permanent_id: str,+ organization_id: str,+ expected_version: int,+ run_with: str,+ cache_key: str,+ code_version: int,+ ) -> Workflow:+ async with self.Session() as session:+ newer_version_exists = (+ select(WorkflowModel.workflow_id)+ .where(WorkflowModel.workflow_permanent_id == workflow_permanent_id)+ .where(WorkflowModel.organization_id == organization_id)+ .where(WorkflowModel.version > expected_version)+ .where(WorkflowModel.deleted_at.is_(None))+ .exists()+ )+ update_workflow_query = (+ update(WorkflowModel)+ .where(WorkflowModel.workflow_id == workflow_id)+ .where(WorkflowModel.organization_id == organization_id)+ .where(WorkflowModel.workflow_permanent_id == workflow_permanent_id)+ .where(WorkflowModel.version == expected_version)+ .where(WorkflowModel.deleted_at.is_(None))+ .where(~newer_version_exists)+ .values(+ run_with=run_with,+ cache_key=cache_key,+ code_version=code_version,+ )+ .returning(WorkflowModel.workflow_id)+ )+ updated_workflow_id = (await session.execute(update_workflow_query)).scalar_one_or_none()+ if updated_workflow_id is None:+ raise NotFoundError("Workflow not found or no longer latest")++ await session.commit()+ workflow = (+ await session.scalars(+ exclude_deleted(select(WorkflowModel).filter_by(workflow_id=workflow_id), WorkflowModel)+ )+ ).one()+ is_template = await self.is_workflow_template(+ workflow_permanent_id=workflow.workflow_permanent_id,+ organization_id=workflow.organization_id,+ )+ return convert_to_workflow(+ workflow,+ self.debug_enabled,+ is_template=is_template,+ )+@db_operation("update_workflow_and_reconcile_definition_params")async def update_workflow_and_reconcile_definition_params(self,diff --git a/skyvern/forge/sdk/routes/scripts.py b/skyvern/forge/sdk/routes/scripts.pyindex d695bc727..d076a943c 100644--- a/skyvern/forge/sdk/routes/scripts.py+++ b/skyvern/forge/sdk/routes/scripts.py@@ -261,8 +261,8 @@ async def deploy_cached_script(workflow_permanent_id: str = Path(..., description="The workflow permanent ID"),current_org: Organization = Depends(org_auth_service.get_current_org),) -> DeployCachedScriptResponse:- """Validate a cached script deploy plan without writing deployment state."""- return await cached_script_deploy_service.dry_run_cached_script_deploy(+ """Validate or commit a cached script deployment."""+ return await cached_script_deploy_service.deploy_cached_script(organization_id=current_org.organization_id,workflow_permanent_id=workflow_permanent_id,request=data,diff --git a/skyvern/schemas/scripts.py b/skyvern/schemas/scripts.pyindex d8b23c095..39edda823 100644--- a/skyvern/schemas/scripts.py+++ b/skyvern/schemas/scripts.py@@ -130,14 +130,15 @@ class DeployCachedScriptRequest(BaseModel):source_workflow_run_id: str | None = Field(default=None, description="Optional provenance run id")requires_agent_overrides: dict[str, bool] = Field(default_factory=dict,- description="Explicit per-label requires_agent values for future commit mode",+ description="Explicit per-label requires_agent values for commit mode",)- dry_run: bool = Field(default=True, description="Dry-run must be true in the initial internal endpoint")+ dry_run: bool = Field(default=True, description="When true, validates the deploy without writing state")class DeployCachedScriptBlockPlan(BaseModel):label: strprimitive: str+ run_signature: str = ""block_type: str | None = Noneis_cacheable: boolis_compound: bool@@ -152,6 +153,12 @@ class DeployCachedScriptResponse(BaseModel):cache_key_value: strdry_run: boolwould_create_script: bool+ script_was_created: bool = False+ script_id: str | None = None+ script_revision_id: str | None = None+ script_version: int | None = None+ workflow_script_id: str | None = None+ workflow_script_upsert_status: str | None = Nonecacheable_block_count: intskipped_block_labels: list[str] = Field(default_factory=list)blocks: list[DeployCachedScriptBlockPlan] = Field(default_factory=list)diff --git a/skyvern/services/cached_script_deploy_service.py b/skyvern/services/cached_script_deploy_service.pyindex f0ae06ee0..149253faa 100644--- a/skyvern/services/cached_script_deploy_service.py+++ b/skyvern/services/cached_script_deploy_service.py@@ -1,7 +1,10 @@from __future__ import annotationsimport base64+import hashlib+from dataclasses import dataclass+import structlogfrom fastapi import HTTPExceptionfrom skyvern.core.script_generations.script_block_extractor import (@@ -10,6 +13,8 @@ from skyvern.core.script_generations.script_block_extractor import (extract_script_blocks,)from skyvern.forge import app+from skyvern.forge.sdk.db.exceptions import NotFoundError+from skyvern.forge.sdk.db.repositories.scripts import WorkflowScriptWriterIntentfrom skyvern.forge.sdk.workflow.models.workflow import Workflowfrom skyvern.schemas.scripts import (DeployCachedScriptBlockPlan,@@ -17,23 +22,78 @@ from skyvern.schemas.scripts import (DeployCachedScriptResponse,FileEncoding,ScriptFileCreate,+ ScriptStatus,)from skyvern.services.workflow_script_service import CacheKeyResolutionError, resolve_cache_key_value+_CODE_VERSION_STATIC = 1+_CODE_VERSION_ADAPTIVE = 2+_MAX_SCRIPT_FILE_BYTES = 10 * 1024 * 1024-def _decode_script_file(file: ScriptFileCreate) -> str:+LOG = structlog.get_logger(__name__)+++@dataclass(frozen=True)+class _CachedScriptDeployPlan:+ workflow: Workflow+ proposed_workflow: Workflow+ cache_key_value: str+ block_plans: list[DeployCachedScriptBlockPlan]+ cacheable_block_count: int+ skipped_block_labels: list[str]+ warnings: list[str]+ validated_files: list[_ValidatedScriptFile]+++@dataclass(frozen=True)+class _ValidatedScriptFile:+ file: ScriptFileCreate+ content_bytes: bytes+++def _decode_script_file_bytes(file: ScriptFileCreate) -> bytes:if file.encoding == FileEncoding.BASE64:try:- return base64.b64decode(file.content).decode("utf-8")+ return base64.b64decode(file.content, validate=True)except Exception as exc:- raise HTTPException(status_code=400, detail=f"File {file.path!r} is not valid base64 UTF-8") from exc- return file.content+ raise HTTPException(status_code=400, detail=f"File {file.path!r} is not valid base64") from exc+ return file.content.encode("utf-8")+++def _validate_script_file_path(file_path: str) -> None:+ parts = file_path.split("/")+ if file_path.startswith("/") or "\\" in file_path or any(part in ("", ".", "..") for part in parts):+ raise HTTPException(+ status_code=400,+ detail=f"File path {file_path!r} must be a relative POSIX path without empty, '.', or '..' segments",+ )-def _main_py(files: list[ScriptFileCreate]) -> str:+def _validate_script_files(files: list[ScriptFileCreate]) -> list[_ValidatedScriptFile]:+ seen_paths: set[str] = set()+ validated_files: list[_ValidatedScriptFile] = []for file in files:- if file.path == "main.py":- return _decode_script_file(file)+ _validate_script_file_path(file.path)+ if file.path in seen_paths:+ raise HTTPException(status_code=400, detail=f"Duplicate script file path {file.path!r}")+ seen_paths.add(file.path)+ content_bytes = _decode_script_file_bytes(file)+ if len(content_bytes) > _MAX_SCRIPT_FILE_BYTES:+ raise HTTPException(+ status_code=400,+ detail=f"File {file.path!r} exceeds maximum size of {_MAX_SCRIPT_FILE_BYTES} bytes",+ )+ validated_files.append(_ValidatedScriptFile(file=file, content_bytes=content_bytes))+ return validated_files+++def _main_py(files: list[_ValidatedScriptFile]) -> str:+ for validated_file in files:+ if validated_file.file.path == "main.py":+ try:+ return validated_file.content_bytes.decode("utf-8")+ except UnicodeDecodeError as exc:+ raise HTTPException(status_code=400, detail="File 'main.py' is not valid UTF-8") from excraise HTTPException(status_code=400, detail="Cached script deploy requires a main.py file")@@ -43,17 +103,56 @@ def _workflow_with_cache_key(workflow: Workflow, cache_key: str | None) -> Workfreturn workflow.model_copy(update={"cache_key": cache_key})-async def dry_run_cached_script_deploy(+def _code_version_for_cache_context(request: DeployCachedScriptRequest) -> int:+ return _CODE_VERSION_ADAPTIVE if request.cache_context.adaptive_caching else _CODE_VERSION_STATIC+++def _require_cache_key(plan: _CachedScriptDeployPlan) -> str:+ if plan.proposed_workflow.cache_key is None:+ raise HTTPException(status_code=400, detail="Cached script deploy requires a non-null workflow cache_key")+ return plan.proposed_workflow.cache_key+++async def _persist_script_files(*,+ files: list[_ValidatedScriptFile],organization_id: str,- workflow_permanent_id: str,- request: DeployCachedScriptRequest,-) -> DeployCachedScriptResponse:- if not request.dry_run:- raise HTTPException(- status_code=400, detail="Commit mode is not enabled for deploy_cached yet; use dry_run=true"+ script_id: str,+ script_version: int,+ script_revision_id: str,+) -> None:+ for validated_file in files:+ file = validated_file.file+ content_bytes = validated_file.content_bytes+ content_hash = f"sha256:{hashlib.sha256(content_bytes).hexdigest()}"+ artifact_id = await app.ARTIFACT_MANAGER.create_script_file_artifact(+ organization_id=organization_id,+ script_id=script_id,+ script_version=script_version,+ file_path=file.path,+ data=content_bytes,+ )+ await app.DATABASE.scripts.create_script_file(+ script_revision_id=script_revision_id,+ script_id=script_id,+ organization_id=organization_id,+ file_path=file.path,+ file_name=file.path.split("/")[-1],+ file_type="file",+ content_hash=content_hash,+ file_size=len(content_bytes),+ mime_type=file.mime_type,+ encoding=file.encoding.value,+ artifact_id=artifact_id,)++async def _build_cached_script_deploy_plan(+ *,+ organization_id: str,+ workflow_permanent_id: str,+ request: DeployCachedScriptRequest,+) -> _CachedScriptDeployPlan:workflow = await app.DATABASE.workflows.get_workflow_by_permanent_id(workflow_permanent_id=workflow_permanent_id,organization_id=organization_id,@@ -70,7 +169,8 @@ async def dry_run_cached_script_deploy()proposed_workflow = _workflow_with_cache_key(workflow, request.cache_key)- main_py = _main_py(request.files)+ validated_files = _validate_script_files(request.files)+ main_py = _main_py(validated_files)try:extraction = extract_script_blocks(main_py, proposed_workflow.workflow_definition.model_dump(mode="json"))@@ -109,24 +209,163 @@ async def dry_run_cached_script_deploy(DeployCachedScriptBlockPlan(label=block.label,primitive=block.primitive,+ run_signature=block.run_signature,block_type=block.block_type,is_cacheable=block.is_cacheable,is_compound=block.is_compound,missing_globals=list(block.missing_globals),- requires_agent=request.requires_agent_overrides.get(block.label, False),+ requires_agent=request.requires_agent_overrides.get(block.label, not block.is_cacheable),)for block in extraction.blocks]- return DeployCachedScriptResponse(- workflow_id=workflow.workflow_id,- workflow_version=workflow.version,- cache_key=proposed_workflow.cache_key,+ return _CachedScriptDeployPlan(+ workflow=workflow,+ proposed_workflow=proposed_workflow,cache_key_value=cache_key_value,- dry_run=True,- would_create_script=True,+ block_plans=block_plans,cacheable_block_count=len(cacheable_blocks),skipped_block_labels=[block.label for block in extraction.blocks if not block.is_cacheable],- blocks=block_plans,- warnings=extraction.warnings,+ warnings=list(extraction.warnings),+ validated_files=validated_files,+ )+++def _response_from_plan(+ *,+ plan: _CachedScriptDeployPlan,+ dry_run: bool,+ script_id: str | None = None,+ script_revision_id: str | None = None,+ script_version: int | None = None,+ workflow_script_id: str | None = None,+ workflow_script_upsert_status: str | None = None,+ script_was_created: bool = False,+) -> DeployCachedScriptResponse:+ return DeployCachedScriptResponse(+ workflow_id=plan.workflow.workflow_id,+ workflow_version=plan.workflow.version,+ cache_key=plan.proposed_workflow.cache_key,+ cache_key_value=plan.cache_key_value,+ dry_run=dry_run,+ would_create_script=True,+ script_was_created=script_was_created,+ script_id=script_id,+ script_revision_id=script_revision_id,+ script_version=script_version,+ workflow_script_id=workflow_script_id,+ workflow_script_upsert_status=workflow_script_upsert_status,+ cacheable_block_count=plan.cacheable_block_count,+ skipped_block_labels=plan.skipped_block_labels,+ blocks=plan.block_plans,+ warnings=plan.warnings,+ )+++async def deploy_cached_script(+ *,+ organization_id: str,+ workflow_permanent_id: str,+ request: DeployCachedScriptRequest,+) -> DeployCachedScriptResponse:+ plan = await _build_cached_script_deploy_plan(+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ request=request,+ )+ cache_key = _require_cache_key(plan)+ if request.dry_run:+ return _response_from_plan(plan=plan, dry_run=True)++ script = None+ commit_stage = "create_script"+ try:+ script = await app.DATABASE.scripts.create_script(+ organization_id=organization_id,+ run_id=request.source_workflow_run_id,+ )+ commit_stage = "persist_script_files"+ await _persist_script_files(+ files=plan.validated_files,+ organization_id=organization_id,+ script_id=script.script_id,+ script_version=script.version,+ script_revision_id=script.script_revision_id,+ )++ commit_stage = "upsert_script_blocks"+ for block in plan.block_plans:+ await app.DATABASE.scripts.upsert_script_block(+ script_revision_id=script.script_revision_id,+ script_id=script.script_id,+ organization_id=organization_id,+ script_block_label=block.label,+ run_signature=block.run_signature,+ requires_agent=block.requires_agent,+ )++ commit_stage = "upsert_workflow_script"+ workflow_script_result = await app.DATABASE.scripts.upsert_workflow_script(+ organization_id=organization_id,+ script_id=script.script_id,+ workflow_permanent_id=workflow_permanent_id,+ workflow_id=plan.workflow.workflow_id,+ workflow_run_id=request.source_workflow_run_id,+ cache_key=cache_key,+ cache_key_value=plan.cache_key_value,+ status=ScriptStatus.published,+ is_pinned=True,+ writer_intent=WorkflowScriptWriterIntent.deploy,+ )++ commit_stage = "update_workflow_dispatch_state"+ await app.DATABASE.workflows.update_workflow_dispatch_state_if_latest(+ workflow_id=plan.workflow.workflow_id,+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ expected_version=plan.workflow.version,+ run_with="code",+ cache_key=cache_key,+ code_version=_code_version_for_cache_context(request),+ )+ except NotFoundError as exc:+ LOG.exception(+ "cached_script_deploy_commit_failed",+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ workflow_id=plan.workflow.workflow_id,+ workflow_version=plan.workflow.version,+ cache_key_value=plan.cache_key_value,+ script_id=script.script_id if script else None,+ commit_stage=commit_stage,+ )+ raise HTTPException(+ status_code=409,+ detail=(+ "Workflow version became stale before deploy commit: expected "+ f"{plan.workflow.workflow_id} v{plan.workflow.version}"+ ),+ ) from exc+ except Exception:+ LOG.exception(+ "cached_script_deploy_commit_failed",+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ workflow_id=plan.workflow.workflow_id,+ workflow_version=plan.workflow.version,+ cache_key_value=plan.cache_key_value,+ script_id=script.script_id if script else None,+ commit_stage=commit_stage,+ )+ raise++ return _response_from_plan(+ plan=plan,+ dry_run=False,+ script_id=script.script_id,+ script_revision_id=script.script_revision_id,+ script_version=script.version,+ workflow_script_id=workflow_script_result.workflow_script.workflow_script_id,+ workflow_script_upsert_status=workflow_script_result.status.value,+ script_was_created=True,)diff --git a/tests/unit/forge/sdk/db/test_update_workflow_definition_fields.py b/tests/unit/forge/sdk/db/test_update_workflow_definition_fields.pyindex 3b4eafc35..a47dc4431 100644--- a/tests/unit/forge/sdk/db/test_update_workflow_definition_fields.py+++ b/tests/unit/forge/sdk/db/test_update_workflow_definition_fields.py@@ -28,6 +28,7 @@ import pytest_asynciofrom sqlalchemy.ext.asyncio import create_async_enginefrom skyvern.forge.sdk.db.agent_db import AgentDB+from skyvern.forge.sdk.db.exceptions import NotFoundErrorfrom skyvern.forge.sdk.db.models import Basefrom skyvern.schemas.runs import ProxyLocation@@ -89,6 +90,84 @@ async def _get(agent_db: AgentDB, ids: dict[str, str]) -> Any:return workflow+async def test_update_workflow_dispatch_state_if_latest_updates_current_version(agent_db: AgentDB) -> None:+ org = await agent_db.organizations.create_organization(+ organization_name="Dispatch Update Org",+ domain="dispatch-update.test",+ )+ workflow = await agent_db.workflows.create_workflow(+ title="dispatch-v1",+ workflow_definition={"parameters": [], "blocks": []},+ organization_id=org.organization_id,+ workflow_permanent_id="wpid_dispatch_update",+ version=1,+ run_with="agent",+ cache_key="default",+ code_version=1,+ )++ updated = await agent_db.workflows.update_workflow_dispatch_state_if_latest(+ workflow_id=workflow.workflow_id,+ workflow_permanent_id=workflow.workflow_permanent_id,+ organization_id=org.organization_id,+ expected_version=1,+ run_with="code",+ cache_key="custom",+ code_version=2,+ )++ assert updated.run_with == "code"+ assert updated.cache_key == "custom"+ assert updated.code_version == 2+++async def test_update_workflow_dispatch_state_if_latest_rejects_stale_version(agent_db: AgentDB) -> None:+ org = await agent_db.organizations.create_organization(+ organization_name="Dispatch Stale Org",+ domain="dispatch-stale.test",+ )+ first = await agent_db.workflows.create_workflow(+ title="dispatch-v1",+ workflow_definition={"parameters": [], "blocks": []},+ organization_id=org.organization_id,+ workflow_permanent_id="wpid_dispatch_stale",+ version=1,+ run_with="agent",+ cache_key="default",+ code_version=1,+ )+ await agent_db.workflows.create_workflow(+ title="dispatch-v2",+ workflow_definition={"parameters": [], "blocks": []},+ organization_id=org.organization_id,+ workflow_permanent_id="wpid_dispatch_stale",+ version=2,+ run_with="agent",+ cache_key="default",+ code_version=1,+ )++ with pytest.raises(NotFoundError):+ await agent_db.workflows.update_workflow_dispatch_state_if_latest(+ workflow_id=first.workflow_id,+ workflow_permanent_id=first.workflow_permanent_id,+ organization_id=org.organization_id,+ expected_version=1,+ run_with="code",+ cache_key="custom",+ code_version=2,+ )++ unchanged = await agent_db.workflows.get_workflow(+ workflow_id=first.workflow_id,+ organization_id=org.organization_id,+ )+ assert unchanged is not None+ assert unchanged.run_with == "agent"+ assert unchanged.cache_key == "default"+ assert unchanged.code_version == 1++async def test_omitting_all_workflow_level_fields_preserves_seed(agent_db: AgentDB, seeded_workflow: dict[str, str]) -> None:diff --git a/tests/unit/test_cached_script_deploy_service.py b/tests/unit/test_cached_script_deploy_service.pyindex a9f560eb3..d62ae51ad 100644--- a/tests/unit/test_cached_script_deploy_service.py+++ b/tests/unit/test_cached_script_deploy_service.py@@ -5,6 +5,7 @@ from types import SimpleNamespaceimport pytestfrom fastapi import HTTPException+from skyvern.forge.sdk.db.exceptions import NotFoundErrorfrom skyvern.forge.sdk.workflow.models.workflow import Workflowfrom skyvern.schemas.scripts import (DeployCachedScriptCacheContext,@@ -73,7 +74,10 @@ def _request(*,resolved_cache_key_value: str | None = None,dry_run: bool = True,+ requires_agent_overrides: dict[str, bool] | None = None,+ source_workflow_run_id: str | None = None,cache_key: str | None = "default",+ files: list[ScriptFileCreate] | None = None,) -> DeployCachedScriptRequest:return DeployCachedScriptRequest(workflow_id="wf_latest",@@ -82,7 +86,10 @@ def _request(cache_context=DeployCachedScriptCacheContext(parameters={}, adaptive_caching=True),resolved_cache_key_value=resolved_cache_key_value,dry_run=dry_run,- files=[+ source_workflow_run_id=source_workflow_run_id,+ requires_agent_overrides=requires_agent_overrides or {},+ files=files+ or [ScriptFileCreate(path="main.py",content=_b64(source),@@ -94,23 +101,79 @@ def _request(@pytest.fixture(autouse=True)-def _stub_app(monkeypatch: pytest.MonkeyPatch) -> None:+def _stub_app(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:workflow = _workflow()+ state = SimpleNamespace(+ workflow=workflow,+ created_scripts=[],+ created_files=[],+ created_blocks=[],+ workflow_script_upserts=[],+ workflow_updates=[],+ artifacts=[],+ fail_dispatch_update=False,+ )class Workflows:async def get_workflow_by_permanent_id(self, **_: object) -> Workflow:- return workflow+ return state.workflow++ async def update_workflow(self, **kwargs: object) -> Workflow:+ state.workflow_updates.append(kwargs)+ return state.workflow++ async def update_workflow_dispatch_state_if_latest(self, **kwargs: object) -> Workflow:+ state.workflow_updates.append(kwargs)+ if state.fail_dispatch_update:+ raise NotFoundError("Workflow not found or no longer latest")+ return state.workflow++ class Scripts:+ async def create_script(self, **kwargs: object) -> SimpleNamespace:+ state.created_scripts.append(kwargs)+ return SimpleNamespace(+ script_id="s_created",+ script_revision_id="sr_created",+ version=1,+ run_id=kwargs.get("run_id"),+ )++ async def create_script_file(self, **kwargs: object) -> SimpleNamespace:+ state.created_files.append(kwargs)+ return SimpleNamespace(file_id=f"sf_{len(state.created_files)}")++ async def upsert_script_block(self, **kwargs: object) -> SimpleNamespace:+ state.created_blocks.append(kwargs)+ return SimpleNamespace(script_block_id=f"sb_{len(state.created_blocks)}")++ async def upsert_workflow_script(self, **kwargs: object) -> SimpleNamespace:+ state.workflow_script_upserts.append(kwargs)+ return SimpleNamespace(+ status=SimpleNamespace(value="created"),+ workflow_script=SimpleNamespace(workflow_script_id="ws_created"),+ )++ class ArtifactManager:+ async def create_script_file_artifact(self, **kwargs: object) -> str:+ state.artifacts.append(kwargs)+ return f"artifact_{len(state.artifacts)}"monkeypatch.setattr(cached_script_deploy_service.app,"DATABASE",- SimpleNamespace(workflows=Workflows()),+ SimpleNamespace(workflows=Workflows(), scripts=Scripts()),+ )+ monkeypatch.setattr(+ cached_script_deploy_service.app,+ "ARTIFACT_MANAGER",+ ArtifactManager(),)monkeypatch.setattr(cached_script_deploy_service.app,"AGENT_FUNCTION",SimpleNamespace(detect_ats_platform=lambda domain: None),)+ return state@pytest.mark.asyncio@@ -123,7 +186,7 @@ async def run(parameters):await skyvern.validate(complete_criterion="done", terminate_criterion="stop", label="check")"""- response = await cached_script_deploy_service.dry_run_cached_script_deploy(+ response = await cached_script_deploy_service.deploy_cached_script(organization_id="org_test",workflow_permanent_id="wpid_test",request=_request(source, resolved_cache_key_value="default:example.com:v2"),@@ -131,6 +194,7 @@ async def run(parameters):assert response.dry_run is Trueassert response.would_create_script is True+ assert response.script_was_created is Falseassert response.cache_key_value == "default:example.com:v2"assert response.cacheable_block_count == 1assert response.skipped_block_labels == ["check"]@@ -146,7 +210,7 @@ async def run(parameters):await skyvern.run_task(prompt="...", label="step_a", cache_key="step_a")"""- response = await cached_script_deploy_service.dry_run_cached_script_deploy(+ response = await cached_script_deploy_service.deploy_cached_script(organization_id="org_test",workflow_permanent_id="wpid_test",request=_request(source, resolved_cache_key_value="default:example.com:v2", cache_key=None),@@ -157,16 +221,225 @@ async def run(parameters):@pytest.mark.asyncio-async def test_dry_run_rejects_commit_mode_until_writes_are_implemented() -> None:+async def test_commit_mode_creates_script_blocks_mapping_and_updates_workflow(+ _stub_app: SimpleNamespace,+) -> None:+ source = """+import skyvern++async def run(parameters):+ await skyvern.run_task(prompt="...", label="step_a", cache_key="step_a")+ await skyvern.validate(complete_criterion="done", terminate_criterion="stop", label="check")+"""++ response = await cached_script_deploy_service.deploy_cached_script(+ organization_id="org_test",+ workflow_permanent_id="wpid_test",+ request=_request(+ source,+ resolved_cache_key_value="default:example.com:v2",+ dry_run=False,+ source_workflow_run_id="wr_source",+ ),+ )++ state = _stub_app+ assert response.dry_run is False+ assert response.would_create_script is True+ assert response.script_was_created is True+ assert response.script_id == "s_created"+ assert response.script_revision_id == "sr_created"+ assert response.workflow_script_id == "ws_created"+ assert response.workflow_script_upsert_status == "created"+ assert state.created_scripts == [{"organization_id": "org_test", "run_id": "wr_source"}]+ assert state.created_files[0]["file_path"] == "main.py"+ assert state.created_files[0]["encoding"] == "base64"+ assert [block["script_block_label"] for block in state.created_blocks] == ["step_a", "check"]+ assert state.created_blocks[0]["run_signature"].startswith("await skyvern.run_task")+ assert state.created_blocks[0]["requires_agent"] is False+ assert state.created_blocks[1]["requires_agent"] is True+ assert state.workflow_script_upserts[0]["script_id"] == "s_created"+ assert state.workflow_script_upserts[0]["cache_key_value"] == "default:example.com:v2"+ assert state.workflow_script_upserts[0]["is_pinned"] is True+ assert state.workflow_updates == [+ {+ "workflow_id": "wf_latest",+ "workflow_permanent_id": "wpid_test",+ "organization_id": "org_test",+ "expected_version": 3,+ "run_with": "code",+ "cache_key": "default",+ "code_version": 2,+ }+ ]+++async def test_requires_agent_override_takes_precedence_for_non_cacheable_block(+ _stub_app: SimpleNamespace,+) -> None:+ source = """+import skyvern++async def run(parameters):+ await skyvern.run_task(prompt="...", label="step_a", cache_key="step_a")+ await skyvern.validate(complete_criterion="done", terminate_criterion="stop", label="check")+"""++ await cached_script_deploy_service.deploy_cached_script(+ organization_id="org_test",+ workflow_permanent_id="wpid_test",+ request=_request(+ source,+ resolved_cache_key_value="default:example.com:v2",+ dry_run=False,+ requires_agent_overrides={"check": False},+ ),+ )++ assert _stub_app.created_blocks[1]["script_block_label"] == "check"+ assert _stub_app.created_blocks[1]["requires_agent"] is False+++ "file_path",+ ["../outside.py", "/main.py", "dir//main.py", "dir/../main.py", "dir\\main.py", "./main.py"],+)+async def test_dry_run_rejects_unsafe_file_paths(file_path: str) -> None:+ source = """+import skyvern++async def run(parameters):+ await skyvern.run_task(prompt="...", label="step_a", cache_key="step_a")+"""+ files = [+ ScriptFileCreate(+ path="main.py",+ content=_b64(source),+ encoding=FileEncoding.BASE64,+ mime_type="text/x-python",+ ),+ ScriptFileCreate(+ path=file_path,+ content=_b64("x = 1\n"),+ encoding=FileEncoding.BASE64,+ mime_type="text/x-python",+ ),+ ]++ with pytest.raises(HTTPException) as exc:+ await cached_script_deploy_service.deploy_cached_script(+ organization_id="org_test",+ workflow_permanent_id="wpid_test",+ request=_request(source, files=files),+ )++ assert exc.value.status_code == 400+ assert "relative POSIX path" in str(exc.value.detail)+++async def test_dry_run_rejects_duplicate_file_paths() -> None:+ source = """+import skyvern++async def run(parameters):+ await skyvern.run_task(prompt="...", label="step_a", cache_key="step_a")+"""+ files = [+ ScriptFileCreate(+ path="main.py",+ content=_b64(source),+ encoding=FileEncoding.BASE64,+ mime_type="text/x-python",+ ),+ ScriptFileCreate(+ path="main.py",+ content=_b64("x = 1\n"),+ encoding=FileEncoding.BASE64,+ mime_type="text/x-python",+ ),+ ]++ with pytest.raises(HTTPException) as exc:+ await cached_script_deploy_service.deploy_cached_script(+ organization_id="org_test",+ workflow_permanent_id="wpid_test",+ request=_request(source, files=files),+ )++ assert exc.value.status_code == 400+ assert "Duplicate script file path" in str(exc.value.detail)+++async def test_dry_run_rejects_invalid_base64_in_non_main_file() -> None:+ source = """+import skyvern++async def run(parameters):+ await skyvern.run_task(prompt="...", label="step_a", cache_key="step_a")+"""+ files = [+ ScriptFileCreate(+ path="main.py",+ content=_b64(source),+ encoding=FileEncoding.BASE64,+ mime_type="text/x-python",+ ),+ ScriptFileCreate(+ path="helper.py",+ content=_b64("x = 1\n") + "!!!",+ encoding=FileEncoding.BASE64,+ mime_type="text/x-python",+ ),+ ]++ with pytest.raises(HTTPException) as exc:+ await cached_script_deploy_service.deploy_cached_script(+ organization_id="org_test",+ workflow_permanent_id="wpid_test",+ request=_request(source, files=files),+ )++ assert exc.value.status_code == 400+ assert "not valid base64" in str(exc.value.detail)+++async def test_dry_run_rejects_oversized_file(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(cached_script_deploy_service, "_MAX_SCRIPT_FILE_BYTES", 4)+ source = """+import skyvern++async def run(parameters):+ await skyvern.run_task(prompt="...", label="step_a", cache_key="step_a")+"""+ files = [+ ScriptFileCreate(+ path="main.py",+ content=_b64(source),+ encoding=FileEncoding.BASE64,+ mime_type="text/x-python",+ ),+ ScriptFileCreate(+ path="helper.py",+ content=_b64("x = 1\n"),+ encoding=FileEncoding.BASE64,+ mime_type="text/x-python",+ ),+ ]+with pytest.raises(HTTPException) as exc:- await cached_script_deploy_service.dry_run_cached_script_deploy(+ await cached_script_deploy_service.deploy_cached_script(organization_id="org_test",workflow_permanent_id="wpid_test",- request=_request("import skyvern\nasync def run(parameters):\n pass\n", dry_run=False),+ request=_request(source, files=files),)assert exc.value.status_code == 400- assert "Commit mode is not enabled" in str(exc.value.detail)+ assert "exceeds maximum size" in str(exc.value.detail)@pytest.mark.asyncio@@ -179,7 +452,7 @@ async def run(parameters):"""with pytest.raises(HTTPException) as exc:- await cached_script_deploy_service.dry_run_cached_script_deploy(+ await cached_script_deploy_service.deploy_cached_script(organization_id="org_test",workflow_permanent_id="wpid_test",request=_request(source),@@ -200,7 +473,7 @@ async def run(parameters):"""with pytest.raises(HTTPException) as exc:- await cached_script_deploy_service.dry_run_cached_script_deploy(+ await cached_script_deploy_service.deploy_cached_script(organization_id="org_test",workflow_permanent_id="wpid_test",request=_request(source),@@ -220,7 +493,7 @@ async def run(parameters):"""with pytest.raises(HTTPException) as exc:- await cached_script_deploy_service.dry_run_cached_script_deploy(+ await cached_script_deploy_service.deploy_cached_script(organization_id="org_test",workflow_permanent_id="wpid_test",request=_request(source, resolved_cache_key_value="wrong:v2"),@@ -228,3 +501,79 @@ async def run(parameters):assert exc.value.status_code == 400assert "Resolved cache key value mismatch" in str(exc.value.detail)+++async def test_commit_mode_rejects_null_cache_key(_stub_app: SimpleNamespace) -> None:+ _stub_app.workflow = _workflow(cache_key=None)+ source = """+import skyvern++async def run(parameters):+ await skyvern.run_task(prompt="...", label="step_a", cache_key="step_a")+"""++ with pytest.raises(HTTPException) as exc:+ await cached_script_deploy_service.deploy_cached_script(+ organization_id="org_test",+ workflow_permanent_id="wpid_test",+ request=_request(+ source,+ resolved_cache_key_value="example.com:v2",+ dry_run=False,+ cache_key=None,+ ),+ )++ assert exc.value.status_code == 400+ assert "non-null workflow cache_key" in str(exc.value.detail)+++async def test_dry_run_rejects_null_cache_key(_stub_app: SimpleNamespace) -> None:+ _stub_app.workflow = _workflow(cache_key=None)+ source = """+import skyvern++async def run(parameters):+ await skyvern.run_task(prompt="...", label="step_a", cache_key="step_a")+"""++ with pytest.raises(HTTPException) as exc:+ await cached_script_deploy_service.deploy_cached_script(+ organization_id="org_test",+ workflow_permanent_id="wpid_test",+ request=_request(+ source,+ resolved_cache_key_value="example.com:v2",+ cache_key=None,+ ),+ )++ assert exc.value.status_code == 400+ assert "non-null workflow cache_key" in str(exc.value.detail)+++async def test_commit_mode_maps_stale_dispatch_update_to_conflict(_stub_app: SimpleNamespace) -> None:+ _stub_app.fail_dispatch_update = True+ source = """+import skyvern++async def run(parameters):+ await skyvern.run_task(prompt="...", label="step_a", cache_key="step_a")+"""++ with pytest.raises(HTTPException) as exc:+ await cached_script_deploy_service.deploy_cached_script(+ organization_id="org_test",+ workflow_permanent_id="wpid_test",+ request=_request(+ source,+ resolved_cache_key_value="default:example.com:v2",+ dry_run=False,+ ),+ )++ assert exc.value.status_code == 409+ assert "became stale" in str(exc.value.detail)