Skip to content

Automate browser based workflows with AI

feat(SKY-11258): stream code-block actions live via idempotent upsert (#7610)

Celal Zamanoğluc6747782d6d3
diff --git a/skyvern/forge/sdk/db/repositories/workflow_parameters.py b/skyvern/forge/sdk/db/repositories/workflow_parameters.py
index a80476e5a..e6f7b3df9 100644
--- a/skyvern/forge/sdk/db/repositories/workflow_parameters.py
+++ b/skyvern/forge/sdk/db/repositories/workflow_parameters.py
@@ -7,6 +7,7 @@ from typing import Any
import structlog
from sqlalchemy import select
+from sqlalchemy.dialects.postgresql import insert as pg_insert
from skyvern.config import settings
from skyvern.forge.sdk.copilot.completion_criteria_store import criteria_from_json, criterion_authority_projection
@@ -950,6 +951,49 @@ class WorkflowParametersRepository(BaseRepository):
await session.refresh(new_action)
return hydrate_action(new_action)
+ @traced(name="skyvern.db.upsert_recorded_action")
+ @db_operation("upsert_recorded_action")
+ async def upsert_recorded_action(self, action: Action) -> None:
+ # Idempotent on action_id: a code block's streamed write (mid-execution, screenshot not yet
+ # uploaded) and its end-of-block batch converge on the same row, so the batch backfills the
+ # screenshot instead of inserting a duplicate. Isolated from create_action to leave the agent
+ # write path untouched.
+ action_log_payload = redact_action_for_log(action)
+ values = {
+ "action_id": action.action_id,
+ "action_type": action.action_type,
+ "source_action_id": action.source_action_id,
+ "organization_id": action.organization_id,
+ "workflow_run_id": action.workflow_run_id,
+ "task_id": action.task_id,
+ "step_id": action.step_id,
+ "step_order": action.step_order,
+ "action_order": action.action_order,
+ "status": action.status,
+ "reasoning": action.reasoning,
+ "intention": action.intention,
+ "response": action_log_payload.get("response"),
+ "element_id": action.element_id,
+ "skyvern_element_hash": action.skyvern_element_hash,
+ "skyvern_element_data": action.skyvern_element_data,
+ "screenshot_artifact_id": action.screenshot_artifact_id,
+ "action_json": action.model_dump(),
+ "confidence_float": action.confidence_float,
+ "created_by": action.created_by,
+ }
+ async with self.Session() as session:
+ stmt = pg_insert(ActionModel).values(**values)
+ stmt = stmt.on_conflict_do_update(
+ index_elements=["action_id"],
+ set_={
+ "screenshot_artifact_id": stmt.excluded.screenshot_artifact_id,
+ "action_json": stmt.excluded.action_json,
+ "modified_at": datetime.now(timezone.utc),
+ },
+ )
+ await session.execute(stmt)
+ await session.commit()
+
@db_operation("update_action_reasoning")
async def update_action_reasoning(
self,
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 5a5d0e64d..d9506c4cb 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -110,6 +110,7 @@ from skyvern.forge.sdk.core.hashing import diagnostic_fingerprint
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.db.enums import TaskType
from skyvern.forge.sdk.db.exceptions import NotFoundError
+from skyvern.forge.sdk.db.id import generate_action_id
from skyvern.forge.sdk.experimentation.llm_prompt_config import get_llm_handler_for_prompt_type
from skyvern.forge.sdk.models import Step, StepStatus
from skyvern.forge.sdk.schemas.files import FileInfo
@@ -5192,6 +5193,8 @@ async def wrapper({default_args}):
# The exception did not come from a recorded page call; add a synthetic failure row.
recorded.append(
Action(
+ # Synthesized outside the recorder, so it needs its own stable id for the upsert path.
+ action_id=generate_action_id(),
action_type=ActionType.NULL_ACTION,
status=ActionStatus.failed,
action_order=len(recorded),
diff --git a/skyvern/forge/sdk/workflow/models/code_block_recorder.py b/skyvern/forge/sdk/workflow/models/code_block_recorder.py
index 8cc1f9c11..d514dd626 100644
--- a/skyvern/forge/sdk/workflow/models/code_block_recorder.py
+++ b/skyvern/forge/sdk/workflow/models/code_block_recorder.py
@@ -10,6 +10,7 @@ from typing import Any, Awaitable, Callable
import pydantic
import structlog
+from skyvern.forge.sdk.db.id import generate_action_id
from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.actions import Action, ActionStatus, SelectOption
@@ -276,6 +277,8 @@ class _Recorder:
# Input values may be credentials (incl. derived TOTP codes); never describe them.
describe_args = () if action_type == ActionType.INPUT_TEXT else args
common_fields = dict(
+ # Stable id assigned once so the streamed write and the end-of-block batch upsert the same row.
+ action_id=generate_action_id(),
action_type=action_type,
status=ActionStatus.completed,
action_order=len(self.actions),
diff --git a/skyvern/forge/sdk/workflow/models/code_block_recording.py b/skyvern/forge/sdk/workflow/models/code_block_recording.py
index 65df87131..43b467714 100644
--- a/skyvern/forge/sdk/workflow/models/code_block_recording.py
+++ b/skyvern/forge/sdk/workflow/models/code_block_recording.py
@@ -53,7 +53,7 @@ class CodeBlockActionRecording:
self._screenshot_tasks: list[asyncio.Task[None]] = []
self._recording_enabled = False
self._finalized = False
- self.recording_page = RecordingPage(page, on_action=self._screenshot_sink)
+ self.recording_page = RecordingPage(page, on_action=self._recorded_action_sink)
@property
def task(self) -> Task | None:
@@ -100,7 +100,9 @@ class CodeBlockActionRecording:
)
await self.finalize(success=False)
- async def _screenshot_sink(self, action: Action) -> None:
+ async def _recorded_action_sink(self, action: Action) -> None:
+ # Fires as each action completes: capture its screenshot, then stream the row so consumers
+ # (run timeline, copilot narration) see it mid-block instead of only at block end.
if not self._recording_enabled:
return
# page.screenshot() shares the CDP channel with the user's page calls, so it must run synchronously
@@ -119,49 +121,61 @@ class CodeBlockActionRecording:
workflow_run_block_id=self._workflow_run_block_id,
exc_info=True,
)
+ else:
+
+ async def _upload() -> None:
+ try:
+ action.screenshot_artifact_id = await app.ARTIFACT_MANAGER.create_workflow_run_block_artifact(
+ workflow_run_block=run_block,
+ artifact_type=ArtifactType.SCREENSHOT_ACTION,
+ data=screenshot,
+ )
+ except Exception:
+ LOG.warning(
+ "Code block screenshot upload failed",
+ workflow_run_block_id=self._workflow_run_block_id,
+ exc_info=True,
+ )
+
+ self._screenshot_tasks.append(asyncio.create_task(_upload()))
+
+ # Streamed row carries no screenshot yet (upload deferred); the end-of-block batch upserts it in.
+ await self._persist_action(action)
+
+ async def _persist_action(self, action: Action) -> None:
+ # Best-effort like the screenshot sink: recording must never change block outcome. Both the streamed
+ # write and the end-of-block batch route through here and upsert on action_id, so they converge on
+ # one row instead of double-inserting.
+ if not self._recording_enabled or self._task is None or self._step is None:
return
-
- async def _upload() -> None:
- try:
- action.screenshot_artifact_id = await app.ARTIFACT_MANAGER.create_workflow_run_block_artifact(
- workflow_run_block=run_block,
- artifact_type=ArtifactType.SCREENSHOT_ACTION,
- data=screenshot,
- )
- except Exception:
- LOG.warning(
- "Code block screenshot upload failed",
- workflow_run_block_id=self._workflow_run_block_id,
- exc_info=True,
- )
-
- self._screenshot_tasks.append(asyncio.create_task(_upload()))
+ try:
+ masked = self._workflow_run_context.mask_secrets_in_data([action.model_dump(mode="json")])[0]
+ persisted = recorded_action_from_payload(masked)
+ persisted.task_id = self._task.task_id
+ persisted.step_id = self._step.step_id
+ persisted.step_order = self._step.order
+ persisted.organization_id = self._organization_id
+ await app.DATABASE.workflow_params.upsert_recorded_action(persisted)
+ except Exception:
+ LOG.warning(
+ "Failed to persist recorded code block action",
+ workflow_run_block_id=self._workflow_run_block_id,
+ action_order=action.action_order,
+ exc_info=True,
+ )
async def _drain_screenshots(self) -> None:
if self._screenshot_tasks:
await asyncio.gather(*self._screenshot_tasks, return_exceptions=True)
async def persist(self, recorded: list[Action]) -> None:
- # Best-effort like the screenshot sink: recording must never change block outcome. Drain first so
- # each action's screenshot_artifact_id is set on the in-memory row before it is dumped.
+ # Drain first so each action's screenshot_artifact_id is set on the in-memory row before its final
+ # upsert backfills the screenshot the streamed write couldn't include.
await self._drain_screenshots()
if not recorded or not self._recording_enabled or self._task is None or self._step is None:
return
- try:
- masked = self._workflow_run_context.mask_secrets_in_data([a.model_dump(mode="json") for a in recorded])
- for raw in masked:
- action = recorded_action_from_payload(raw)
- action.task_id = self._task.task_id
- action.step_id = self._step.step_id
- action.step_order = self._step.order
- action.organization_id = self._organization_id
- await app.DATABASE.workflow_params.create_action(action)
- except Exception:
- LOG.warning(
- "Failed to persist recorded code block actions",
- workflow_run_block_id=self._workflow_run_block_id,
- exc_info=True,
- )
+ for action in recorded:
+ await self._persist_action(action)
async def finalize(self, success: bool) -> None:
# Finalize both task and step on every exit path (incl. CancelledError via a finally); idempotent.
diff --git a/tests/unit/workflow/test_code_block_recorder.py b/tests/unit/workflow/test_code_block_recorder.py
index b2394dbb5..b03664fbf 100644
--- a/tests/unit/workflow/test_code_block_recorder.py
+++ b/tests/unit/workflow/test_code_block_recorder.py
@@ -418,6 +418,7 @@ def _patch_execute_environment(
"create_artifact": AsyncMock(return_value="artifact_1"),
"create_task_and_step": AsyncMock(return_value=(_FakeTask(), _FakeStep())),
"create_action": AsyncMock(return_value=None),
+ "upsert_recorded_action": AsyncMock(return_value=None),
"update_task": AsyncMock(return_value=None),
"update_step": AsyncMock(return_value=None),
"billing_hook": AsyncMock(return_value=None),
@@ -435,13 +436,26 @@ def _patch_execute_environment(
monkeypatch.setattr(app.ARTIFACT_MANAGER, "create_workflow_run_block_artifact", mocks["create_artifact"])
monkeypatch.setattr(app.agent, "create_task_and_step_from_code_block", mocks["create_task_and_step"], raising=False)
monkeypatch.setattr(app.DATABASE.workflow_params, "create_action", mocks["create_action"])
+ monkeypatch.setattr(
+ app.DATABASE.workflow_params, "upsert_recorded_action", mocks["upsert_recorded_action"], raising=False
+ )
monkeypatch.setattr(app.DATABASE.tasks, "update_task", mocks["update_task"])
monkeypatch.setattr(app.DATABASE.tasks, "update_step", mocks["update_step"])
return mocks
+def _upsert_calls(mocks: dict[str, AsyncMock]) -> list[Action]:
+ """Every recorded-action write, in order — the streamed (mid-block) writes then the end-of-block batch."""
+ return [call.args[0] for call in mocks["upsert_recorded_action"].await_args_list]
+
+
def _created_actions(mocks: dict[str, AsyncMock]) -> list[Action]:
- return [call.args[0] for call in mocks["create_action"].await_args_list]
+ # Final persisted row per action: the streamed write and the end-of-block batch converge on action_id,
+ # so keep the last write (which carries the drained screenshot) and dedupe.
+ by_id: dict[str | None, Action] = {}
+ for action in _upsert_calls(mocks):
+ by_id[action.action_id] = action
+ return list(by_id.values())
@pytest.mark.asyncio
@@ -689,8 +703,10 @@ async def test_code_block_success_invokes_billing_hook(monkeypatch: pytest.Monke
task, step = mocks["billing_hook"].await_args.args
assert task.task_id == "tsk_code"
assert step.step_id == "stp_code"
- # Billing counts persisted action rows, so the hook must fire after persist.
- assert mocks["create_action"].await_count == 1
+ # Billing counts persisted action rows, so the hook must fire after persist. Streaming + the
+ # end-of-block batch converge on one row per action via action_id — exactly one distinct action here.
+ assert len(_created_actions(mocks)) == 1
+ assert mocks["create_action"].await_count == 0 # recorder writes via the isolated upsert, not create_action
@pytest.mark.asyncio
@@ -819,12 +835,71 @@ async def test_page_evaluate_action_captures_and_links_screenshot(monkeypatch: p
assert actions[0].screenshot_artifact_id == "artifact_1"
+async def test_actions_stream_before_block_end_and_converge_on_one_row(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Each action is written mid-block (streamed) AND in the end-of-block batch, but both writes share the
+ action's stable id and upsert one row — no duplicate. This is the ticket's core idempotency guarantee."""
+ page = FakePage()
+ context = FakeWorkflowRunContext()
+ mocks = _patch_execute_environment(monkeypatch, page, context)
+
+ block = _make_code_block("await page.locator('#go').click()\nvalue = 'ok'", goal="go")
+ result = await block.execute(workflow_run_id="wr_test", workflow_run_block_id="wrb_test", organization_id="o_test")
+
+ assert result.success is True
+ writes = _upsert_calls(mocks)
+ # one streamed write during execution + one end-of-block batch write for the single action
+ assert len(writes) == 2
+ assert writes[0].action_id is not None
+ assert writes[0].action_id == writes[1].action_id # converge on one row, not a duplicate
+ assert len(_created_actions(mocks)) == 1 # deduped to exactly one persisted action
+ assert mocks["create_action"].await_count == 0 # shared agent write path left untouched
+
+
+async def test_streamed_write_precedes_screenshot_backfilled_by_batch(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The streamed row is written before the deferred screenshot upload finishes (screenshot_artifact_id is
+ None); the end-of-block batch upserts the same id with the drained screenshot."""
+ page = FakePage()
+ context = FakeWorkflowRunContext()
+ mocks = _patch_execute_environment(monkeypatch, page, context)
+
+ block = _make_code_block("await page.locator('#go').click()\nvalue = 'ok'", goal="go")
+ result = await block.execute(workflow_run_id="wr_test", workflow_run_block_id="wrb_test", organization_id="o_test")
+
+ assert result.success is True
+ writes = _upsert_calls(mocks)
+ assert writes[0].screenshot_artifact_id is None # streamed: upload still deferred
+ assert writes[-1].screenshot_artifact_id == "artifact_1" # batch: screenshot backfilled
+ assert writes[0].action_id == writes[-1].action_id
+
+
+async def test_streamed_write_masks_secrets(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Secrets must be masked on the streamed path too, not only in the end-of-block batch."""
+ secret = "s3cr3t-token"
+ page = FakePage()
+ context = FakeWorkflowRunContext(secrets={"pw": secret})
+ mocks = _patch_execute_environment(monkeypatch, page, context)
+
+ block = _make_code_block(f"await page.locator('#{secret}').click()\nvalue = 'ok'", goal="go")
+ result = await block.execute(workflow_run_id="wr_test", workflow_run_block_id="wrb_test", organization_id="o_test")
+
+ assert result.success is True
+ writes = _upsert_calls(mocks)
+ assert writes, "expected at least the streamed write"
+ for action in writes:
+ dumped = json.dumps(action.model_dump(mode="json"))
+ assert secret not in dumped
+ assert "*****" in dumped # control: the secret was present and got masked, not simply absent
+
+
@pytest.mark.asyncio
async def test_persist_failure_does_not_fail_the_block(monkeypatch: pytest.MonkeyPatch) -> None:
page = FakePage()
context = FakeWorkflowRunContext()
mocks = _patch_execute_environment(monkeypatch, page, context)
- mocks["create_action"].side_effect = RuntimeError("db unavailable")
+ mocks["upsert_recorded_action"].side_effect = RuntimeError("db unavailable")
block = _make_code_block("await page.locator('#go').click()\nvalue = 'ok'", goal="go")
result = await block.execute(workflow_run_id="wr_test", workflow_run_block_id="wrb_test", organization_id="o_test")
@@ -851,7 +926,7 @@ async def test_create_task_failure_does_not_fail_the_block(monkeypatch: pytest.M
assert result.status == BlockStatus.completed
assert result.output_parameter_value is not None
assert result.output_parameter_value["value"] == "ok"
- assert mocks["create_action"].await_count == 0
+ assert mocks["upsert_recorded_action"].await_count == 0
assert mocks["create_artifact"].await_count == 0
@@ -873,7 +948,7 @@ async def test_link_block_failure_fails_task_and_disables_recording(monkeypatch:
assert result.success is True
assert result.status == BlockStatus.completed
- assert mocks["create_action"].await_count == 0
+ assert mocks["upsert_recorded_action"].await_count == 0
assert mocks["create_artifact"].await_count == 0
assert [call.kwargs.get("status") for call in mocks["update_task"].await_args_list] == [TaskStatus.failed]
assert [call.kwargs.get("status") for call in mocks["update_step"].await_args_list] == [StepStatus.failed]
@@ -906,6 +981,9 @@ async def test_caught_page_failure_then_unrelated_raise_persists_synthetic_actio
assert actions[-1].status == ActionStatus.failed
assert isinstance(actions[-1].output, dict) and actions[-1].output["code_line"] == 5
assert "later failure" in (actions[-1].response or "")
+ # The synthetic error row is built outside the recorder; it still needs a stable id or the upsert
+ # inserts a null primary key and the code-error row is lost.
+ assert all(a.action_id for a in _upsert_calls(mocks))
@pytest.mark.asyncio