Skip to content

Automate browser based workflows with AI

Wait for a closing session's archive before saving a browser profile from it (SKY-17719) (#8793)

Shuchang Zhengce1b94345d60
diff --git a/skyvern/forge/sdk/routes/browser_profiles.py b/skyvern/forge/sdk/routes/browser_profiles.py
index 01e6c3059..f526c6879 100644
--- a/skyvern/forge/sdk/routes/browser_profiles.py
+++ b/skyvern/forge/sdk/routes/browser_profiles.py
@@ -1,9 +1,13 @@
import asyncio
import secrets
import shutil
-from datetime import UTC, datetime
+import time
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
from pathlib import Path as FilePath
-from typing import Any, NoReturn
+from typing import Any, Literal, NoReturn
import structlog
from fastapi import Depends, HTTPException, Path, Query, status
@@ -45,13 +49,32 @@ from skyvern.forge.sdk.workflow.browser_session_persistence import retrieve_pers
from skyvern.schemas.proxy_pinning import apply_proxy_pin_update as _apply_proxy_pin_update
from skyvern.schemas.proxy_pinning import should_generate_proxy_session_id
from skyvern.schemas.runs import ProxyLocation, ProxyLocationInput
+from skyvern.utils.contained_effects import contained_effect
from skyvern.webeye.browser_profile_utils import FRESH_PROFILE_COPY_IGNORE, valid_operator_profile_generation
from skyvern.webeye.profile_cookie_merge import cookies_for_login_urls, sanitize_cookies, write_signin_cookies
+try:
+ from redis.exceptions import LockError
+except ImportError:
+
+ class LockError(Exception): # type: ignore[no-redef]
+ pass
+
+
LOG = structlog.get_logger()
DEFAULT_PROFILE_BROWSER_TYPES = ("chrome", "chromium")
+# How long a save waits for a closing session's teardown to upload the archive before the retryable 400.
+_CLOSING_SESSION_ARCHIVE_WAIT_SECONDS = 10.0
+_CLOSING_SESSION_ARCHIVE_FIRST_POLL_SECONDS = 0.25
+_CLOSING_SESSION_ARCHIVE_MAX_POLL_SECONDS = 1.0
+# The lock must outlive the archive wait plus the download, re-zip and upload of a large profile, or a save on another
+# worker could copy the archive before this save reaps it. A holder that dies keeps the session locked this long.
+_SESSION_PROFILE_SAVE_LOCK_SECONDS = 300
+_SESSION_PROFILE_SAVE_LOCK_WAIT_SECONDS = 30
+_SESSION_PROFILE_SAVED_MARKER_TTL = timedelta(days=1)
+
def _normalize_proxy_pin_fields(
*,
@@ -770,6 +793,122 @@ async def create_profile_from_running_session(
return profile, len(cookies)
+async def _session_archive_exists(*, organization_id: str, profile_id: str) -> bool | None:
+ """None when storage could not answer, which proves neither presence nor absence."""
+ try:
+ return await app.STORAGE.browser_profile_exists(organization_id=organization_id, profile_id=profile_id)
+ except Exception as exc:
+ # Polled up to a dozen times per save, so log the error without a traceback each time.
+ LOG.warning(
+ "Failed to check for browser session archive",
+ organization_id=organization_id,
+ profile_id=profile_id,
+ error_type=type(exc).__name__,
+ error=str(exc),
+ )
+ return None
+
+
+async def _wait_for_closing_session_archive(
+ *,
+ organization_id: str,
+ browser_session_id: str,
+ source_profile_id: str,
+) -> Literal["found", "session_ended", "timed_out"]:
+ # Teardown uploads the archive before it stamps completed_at, so a row read before the storage
+ # check that is already terminal means no archive is coming.
+ deadline = time.monotonic() + _CLOSING_SESSION_ARCHIVE_WAIT_SECONDS
+ delay = _CLOSING_SESSION_ARCHIVE_FIRST_POLL_SECONDS
+ while (remaining := deadline - time.monotonic()) > 0:
+ await asyncio.sleep(min(delay, remaining))
+ delay = min(delay * 2, _CLOSING_SESSION_ARCHIVE_MAX_POLL_SECONDS)
+ browser_session = await app.DATABASE.browser_sessions.get_persistent_browser_session(
+ browser_session_id, organization_id
+ )
+ archive_exists = await _session_archive_exists(organization_id=organization_id, profile_id=source_profile_id)
+ if archive_exists:
+ return "found"
+ if archive_exists is False and (browser_session is None or browser_session.completed_at is not None):
+ return "session_ended"
+ return "timed_out"
+
+
+@dataclass
+class _LocalSaveLock:
+ lock: asyncio.Lock
+ users: int = 0
+
+
+_LOCAL_SESSION_SAVE_LOCKS: dict[tuple[asyncio.AbstractEventLoop, str], _LocalSaveLock] = {}
+
+
+@asynccontextmanager
+async def _session_profile_save_lock(*, organization_id: str, browser_session_id: str) -> AsyncIterator[None]:
+ lock_name = f"browser_profile_from_session_lock:{organization_id}:{browser_session_id}"
+ # Without Redis the cache lock is a no-op, so saves in one process also queue on a local lock; the cache
+ # lock then covers saves on other workers.
+ local_key = (asyncio.get_running_loop(), lock_name)
+ local = _LOCAL_SESSION_SAVE_LOCKS.setdefault(local_key, _LocalSaveLock(lock=asyncio.Lock()))
+ local.users += 1
+ try:
+ async with local.lock:
+ cache_lock = app.CACHE.get_lock(
+ lock_name,
+ blocking_timeout=_SESSION_PROFILE_SAVE_LOCK_WAIT_SECONDS,
+ timeout=_SESSION_PROFILE_SAVE_LOCK_SECONDS,
+ )
+ try:
+ await cache_lock.__aenter__()
+ except LockError as exc:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail="A browser profile is already being saved from this browser session. Retry in a few seconds.",
+ ) from exc
+ try:
+ yield
+ finally:
+ try:
+ await cache_lock.__aexit__(None, None, None)
+ except LockError:
+ # The save outlived the lock's expiry; its outcome stands, so don't replace it with this error.
+ with contained_effect("browser profile save lock release failure"):
+ LOG.warning(
+ "Browser profile save outlived its session lock",
+ organization_id=organization_id,
+ browser_session_id=browser_session_id,
+ exc_info=True,
+ )
+ finally:
+ local.users -= 1
+ if local.users == 0 and _LOCAL_SESSION_SAVE_LOCKS.get(local_key) is local:
+ del _LOCAL_SESSION_SAVE_LOCKS[local_key]
+
+
+def _session_profile_saved_marker_key(organization_id: str, browser_session_id: str) -> str:
+ return f"browser_profile_from_session:{organization_id}:{browser_session_id}"
+
+
+async def _profile_already_saved_from_session(
+ *, organization_id: str, browser_session_id: str, name: str
+) -> BrowserProfile | None:
+ try:
+ saved_profile_id = await app.CACHE.get(_session_profile_saved_marker_key(organization_id, browser_session_id))
+ except Exception:
+ LOG.warning(
+ "Failed to read browser profile saved from session",
+ organization_id=organization_id,
+ browser_session_id=browser_session_id,
+ exc_info=True,
+ )
+ return None
+ if not saved_profile_id:
+ return None
+ profile = await app.DATABASE.browser_sessions.get_browser_profile(saved_profile_id, organization_id)
+ if profile is None or profile.name != name:
+ return None
+ return profile
+
+
async def _create_profile_from_session(
*,
organization_id: str,
@@ -778,6 +917,28 @@ async def _create_profile_from_session(
browser_session_id: str,
proxy_location: ProxyLocationInput = None,
proxy_session_id: str | None = None,
+) -> BrowserProfile:
+ # A save consumes the session's archive, so a client retrying a save whose response it lost (or that is
+ # still running) must get that save's profile back rather than a 400 or a second profile.
+ async with _session_profile_save_lock(organization_id=organization_id, browser_session_id=browser_session_id):
+ return await _create_profile_from_session_locked(
+ organization_id=organization_id,
+ name=name,
+ description=description,
+ browser_session_id=browser_session_id,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
+ )
+
+
+async def _create_profile_from_session_locked(
+ *,
+ organization_id: str,
+ name: str,
+ description: str | None,
+ browser_session_id: str,
+ proxy_location: ProxyLocationInput,
+ proxy_session_id: str | None,
) -> BrowserProfile:
browser_session = await app.DATABASE.browser_sessions.get_persistent_browser_session(
browser_session_id, organization_id
@@ -790,6 +951,18 @@ async def _create_profile_from_session(
)
raise BrowserSessionNotFound(browser_session_id)
+ saved_profile = await _profile_already_saved_from_session(
+ organization_id=organization_id, browser_session_id=browser_session_id, name=name
+ )
+ if saved_profile is not None:
+ LOG.info(
+ "Returning browser profile already created from session",
+ organization_id=organization_id,
+ browser_profile_id=saved_profile.browser_profile_id,
+ browser_session_id=browser_session_id,
+ )
+ return saved_profile
+
# Read the storage id the session actually exported to: reuse writes back to its bp_, but a fallback
# (saved profile failed to load) exported under the session id, so resolve from the loaded profile.
loaded_profile_id = browser_session.browser_profile_id if browser_session.browser_profile_loaded else None
@@ -804,6 +977,30 @@ async def _create_profile_from_session(
organization_id=organization_id,
profile_id=source_profile_id,
)
+ archive_wait_seconds = 0.0
+ wait_outcome: Literal["found", "session_ended", "timed_out"] | None = None
+ # The close call returns before teardown uploads the archive, so only a closing session that exports under its own
+ # id waits for it. A pure-reuse session reads its bp_ archive as it stood before the session, because teardown
+ # writes the session's changes back over that archive later.
+ if (
+ not session_dir
+ and browser_session.close_requested_at is not None
+ and browser_session.completed_at is None
+ and browser_session.should_export_profile()
+ and reused_profile_id is None
+ ):
+ wait_started = time.monotonic()
+ wait_outcome = await _wait_for_closing_session_archive(
+ organization_id=organization_id,
+ browser_session_id=browser_session_id,
+ source_profile_id=source_profile_id,
+ )
+ archive_wait_seconds = round(time.monotonic() - wait_started, 3)
+ if wait_outcome == "found":
+ session_dir = await app.STORAGE.retrieve_browser_profile(
+ organization_id=organization_id,
+ profile_id=source_profile_id,
+ )
if not session_dir:
# An opted-out session never uploads an archive, so retrying can't help — fail fast with a
# distinct message the client can tell apart from the transient "upload not finished yet" case.
@@ -837,11 +1034,32 @@ async def _create_profile_from_session(
"generate_browser_profile enabled to capture a new profile."
),
)
+ if wait_outcome is None:
+ # A failed download also reads as no archive, so an ended row is final only once storage confirms the miss.
+ session_ended = (
+ browser_session.completed_at is not None
+ and await _session_archive_exists(organization_id=organization_id, profile_id=source_profile_id)
+ is False
+ )
+ else:
+ session_ended = wait_outcome == "session_ended"
LOG.warning(
"Browser session archive not found for profile creation",
organization_id=organization_id,
browser_session_id=browser_session_id,
+ archive_wait_seconds=archive_wait_seconds,
+ session_ended=session_ended,
)
+ if session_ended:
+ # Clients retry on the "persisted profile archive" wording below, so this final case must not use it.
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=(
+ "This browser session has ended and has no profile archive to save, so retrying will not help. "
+ "A session's archive can be saved as a profile only once; start a new session with "
+ "generate_browser_profile enabled to capture another profile."
+ ),
+ )
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=(
@@ -894,6 +1112,21 @@ async def _create_profile_from_session(
finally:
discard_temp_working_dir(session_dir)
+ try:
+ await app.CACHE.set(
+ _session_profile_saved_marker_key(organization_id, browser_session_id),
+ profile.browser_profile_id,
+ ex=_SESSION_PROFILE_SAVED_MARKER_TTL,
+ )
+ except Exception:
+ LOG.warning(
+ "Failed to record browser profile saved from session",
+ organization_id=organization_id,
+ browser_session_id=browser_session_id,
+ browser_profile_id=profile.browser_profile_id,
+ exc_info=True,
+ )
+
# The promote copied the session's own export (profiles/{pbs_session}.zip) into the new bp_, so
# reap that source now that it's redundant. Keyed on the session id, never a reused bp_ profile.
# Best-effort: only after a successful promote, and a reap failure must not fail the request.
@@ -915,6 +1148,7 @@ async def _create_profile_from_session(
organization_id=organization_id,
browser_profile_id=profile.browser_profile_id,
browser_session_id=browser_session_id,
+ archive_wait_seconds=archive_wait_seconds,
)
return profile
diff --git a/tests/unit/forge/sdk/test_create_browser_profile_from_session_route.py b/tests/unit/forge/sdk/test_create_browser_profile_from_session_route.py
index 77598a443..e543a420c 100644
--- a/tests/unit/forge/sdk/test_create_browser_profile_from_session_route.py
+++ b/tests/unit/forge/sdk/test_create_browser_profile_from_session_route.py
@@ -20,6 +20,7 @@ from sqlalchemy.exc import IntegrityError
from skyvern.exceptions import SkyvernHTTPException
from skyvern.forge import app as forge_app
+from skyvern.forge.sdk.cache.local import LocalCache
from skyvern.forge.sdk.routes import browser_profiles as browser_profiles_route
from skyvern.forge.sdk.schemas.browser_profiles import BrowserProfile, CreateBrowserProfileRequest
from skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSession
@@ -27,6 +28,7 @@ from skyvern.forge.sdk.services import org_auth_service
from skyvern.schemas.runs import ProxyLocation
from skyvern.webeye.browser_profile_utils import operator_profile_generation, write_operator_profile_marker
from skyvern.webeye.profile_cookie_merge import SIGNIN_COOKIES_FILENAME
+from tests.unit.scoped_asyncio import ScopedAsyncio
_default_profile_template_candidates = browser_profiles_route._default_browser_profile_template_candidates
@@ -72,6 +74,14 @@ def _build_client(
async def _fake_org() -> SimpleNamespace:
return SimpleNamespace(organization_id="org_oss")
+ clock = SimpleNamespace(now=0.0)
+
+ async def _sleep(seconds: float) -> None:
+ clock.now += seconds
+ await asyncio.sleep(0)
+
+ monkeypatch.setattr(browser_profiles_route, "time", SimpleNamespace(monotonic=lambda: clock.now))
+
mocks = SimpleNamespace(
get_session=AsyncMock(),
get_workflow_run=AsyncMock(),
@@ -81,6 +91,7 @@ def _build_client(
delete_db_profile=AsyncMock(),
hard_delete_db_profile=AsyncMock(),
retrieve_profile=AsyncMock(),
+ profile_exists=AsyncMock(return_value=False),
retrieve_session=AsyncMock(),
store_profile=AsyncMock(),
delete_profile_blob=AsyncMock(),
@@ -89,10 +100,15 @@ def _build_client(
engine_enabled=AsyncMock(return_value=True),
observe_session=AsyncMock(),
release_observed_session=AsyncMock(),
+ sleep=AsyncMock(side_effect=_sleep),
+ cache=LocalCache(),
+ clock=clock,
)
+ monkeypatch.setattr(browser_profiles_route, "asyncio", ScopedAsyncio(sleep=mocks.sleep))
forge_app.set_app(
SimpleNamespace(
+ CACHE=mocks.cache,
AGENT_FUNCTION=SimpleNamespace(is_browser_memory_engine_enabled_for_org=mocks.engine_enabled),
RATE_LIMITER=SimpleNamespace(rate_limit_submit_run=mocks.rate_limit_submit_run),
PERSISTENT_SESSIONS_MANAGER=SimpleNamespace(
@@ -115,6 +131,7 @@ def _build_client(
),
STORAGE=SimpleNamespace(
retrieve_browser_profile=mocks.retrieve_profile,
+ browser_profile_exists=mocks.profile_exists,
retrieve_browser_session=mocks.retrieve_session,
store_browser_profile=mocks.store_profile,
delete_browser_profile=mocks.delete_profile_blob,
@@ -391,7 +408,6 @@ def test_create_from_run_promotes_even_when_persist_flag_off(monkeypatch: pytest
def test_create_from_run_400_when_no_persisted_archive(monkeypatch: pytest.MonkeyPatch) -> None:
client, mocks = _build_client(monkeypatch)
- monkeypatch.setattr(browser_profiles_route.asyncio, "sleep", AsyncMock())
mocks.get_workflow_run.return_value = _workflow_run()
mocks.get_workflow.return_value = SimpleNamespace(workflow_permanent_id="wp_1", persist_browser_session=True)
mocks.retrieve_session.return_value = None
@@ -834,6 +850,229 @@ def test_non_opted_in_session_returns_400(monkeypatch: pytest.MonkeyPatch) -> No
mocks.delete_profile_blob.assert_not_awaited()
+def _closing_session() -> PersistentBrowserSession:
+ return _session(generate_browser_profile=True, close_requested_at=datetime(2026, 1, 1, 0, 5))
+
+
+_ENDED = datetime(2026, 1, 1, 0, 6)
+# The frontend keeps retrying a save while the 400 carries this wording, so only a retryable miss may use it.
+_RETRYABLE_HINT = "persisted profile archive"
+
+
+def test_save_from_closing_session_waits_for_the_archive_upload(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, mocks = _build_client(monkeypatch)
+ mocks.get_session.return_value = _closing_session()
+ mocks.retrieve_profile.side_effect = [None, "/tmp/session_dir"]
+ mocks.profile_exists.side_effect = [False, True]
+
+ response = client.post("/v1/browser_profiles/", json={"name": "my profile", "browser_session_id": "pbs_1"})
+
+ assert response.status_code == 200
+ assert mocks.store_profile.await_args.kwargs["directory"] == "/tmp/session_dir"
+ mocks.delete_profile_blob.assert_awaited_once_with(organization_id="org_oss", profile_id="pbs_1")
+ assert mocks.clock.now < 1
+
+
[email protected]("teardown_finishes", [False, True])
+def test_save_from_closing_session_400s_when_no_archive_arrives(
+ monkeypatch: pytest.MonkeyPatch, teardown_finishes: bool
+) -> None:
+ client, mocks = _build_client(monkeypatch)
+ closing = _closing_session()
+ if teardown_finishes:
+ mocks.get_session.side_effect = [closing, closing.model_copy(update={"completed_at": _ENDED})]
+ else:
+ mocks.get_session.return_value = closing
+ mocks.retrieve_profile.return_value = None
+
+ response = client.post("/v1/browser_profiles/", json={"name": "my profile", "browser_session_id": "pbs_1"})
+
+ assert response.status_code == 400
+ # Past the bound teardown may still upload, so the client should retry; once the row is terminal it shouldn't.
+ assert (_RETRYABLE_HINT in response.json()["detail"]) is not teardown_finishes
+ mocks.create_profile.assert_not_awaited()
+ # A row that turns terminal without an archive ends the wait at that poll instead of running out the bound.
+ assert mocks.clock.now == (
+ browser_profiles_route._CLOSING_SESSION_ARCHIVE_FIRST_POLL_SECONDS
+ if teardown_finishes
+ else browser_profiles_route._CLOSING_SESSION_ARCHIVE_WAIT_SECONDS
+ )
+
+
+ "session",
+ [
+ pytest.param(_session(generate_browser_profile=True), id="live"),
+ pytest.param(
+ _session(generate_browser_profile=False, close_requested_at=datetime(2026, 1, 1, 0, 5)),
+ id="opted_out_closing",
+ ),
+ pytest.param(
+ _session(
+ generate_browser_profile=False, browser_profile_id="bp_x", close_requested_at=datetime(2026, 1, 1, 0, 5)
+ ),
+ id="pure_reuse_closing",
+ ),
+ pytest.param(_closing_session().model_copy(update={"completed_at": _ENDED}), id="terminal"),
+ ],
+)
+def test_states_that_cannot_gain_an_archive_400_without_waiting(
+ monkeypatch: pytest.MonkeyPatch, session: PersistentBrowserSession
+) -> None:
+ client, mocks = _build_client(monkeypatch)
+ mocks.get_session.return_value = session
+ mocks.retrieve_profile.return_value = None
+
+ response = client.post("/v1/browser_profiles/", json={"name": "my profile", "browser_session_id": "pbs_1"})
+
+ assert response.status_code == 400
+ mocks.sleep.assert_not_awaited()
+ mocks.create_profile.assert_not_awaited()
+
+
+ ("ends_during_wait", "storage_check"),
+ [
+ pytest.param(True, "finds_archive", id="download_fails_after_the_wait_finds_the_archive"),
+ pytest.param(False, "finds_archive", id="download_fails_on_an_ended_session"),
+ pytest.param(True, "errors", id="storage_check_errors_while_the_session_ends"),
+ pytest.param(False, "errors", id="storage_check_errors_on_an_ended_session"),
+ ],
+)
+def test_a_failed_storage_read_keeps_the_400_retryable(
+ monkeypatch: pytest.MonkeyPatch, ends_during_wait: bool, storage_check: str
+) -> None:
+ # Object-store downloads return None on any error, so only a confirmed miss on an ended session is final.
+ client, mocks = _build_client(monkeypatch)
+ ended = _closing_session().model_copy(update={"completed_at": _ENDED})
+
+ async def get_session(*_args: object) -> PersistentBrowserSession:
+ return _closing_session() if ends_during_wait and mocks.get_session.await_count == 1 else ended
+
+ mocks.get_session.side_effect = get_session
+ mocks.retrieve_profile.return_value = None
+ if storage_check == "errors":
+ mocks.profile_exists.side_effect = RuntimeError("storage unavailable")
+ else:
+ mocks.profile_exists.return_value = True
+
+ response = client.post("/v1/browser_profiles/", json={"name": "my profile", "browser_session_id": "pbs_1"})
+
+ assert response.status_code == 400
+ assert _RETRYABLE_HINT in response.json()["detail"]
+ mocks.create_profile.assert_not_awaited()
+
+
+def test_teardown_finishing_between_the_row_read_and_the_storage_check_still_saves(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Teardown uploads, then stamps completed_at; model both landing just as a poll reads the row.
+ client, mocks = _build_client(monkeypatch)
+ closing = _closing_session()
+ teardown = SimpleNamespace(done=False)
+
+ async def get_session(*_args: object) -> PersistentBrowserSession:
+ if mocks.get_session.await_count > 1:
+ teardown.done = True
+ return closing.model_copy(update={"completed_at": _ENDED})
+ return closing
+
+ async def retrieve(**_kwargs: object) -> str | None:
+ return "/tmp/session_dir" if teardown.done else None
+
+ async def exists(**_kwargs: object) -> bool:
+ return teardown.done
+
+ mocks.get_session.side_effect = get_session
+ mocks.retrieve_profile.side_effect = retrieve
+ mocks.profile_exists.side_effect = exists
+
+ response = client.post("/v1/browser_profiles/", json={"name": "my profile", "browser_session_id": "pbs_1"})
+
+ assert response.status_code == 200
+ assert mocks.store_profile.await_args.kwargs["directory"] == "/tmp/session_dir"
+
+
+def _consumable_archive(mocks: SimpleNamespace, archives: dict[str, str]) -> None:
+ """Storage where a session archive, once uploaded, stays until the save reaps it, as in production."""
+ mocks.retrieve_profile.side_effect = lambda organization_id, profile_id: archives.get(profile_id)
+ mocks.profile_exists.side_effect = lambda organization_id, profile_id: profile_id in archives
+ mocks.delete_profile_blob.side_effect = lambda organization_id, profile_id: archives.pop(profile_id, None)
+ mocks.get_db_profile.side_effect = lambda profile_id, organization_id: _profile()
+
+
+def test_retrying_a_save_whose_response_was_lost_returns_the_same_profile(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, mocks = _build_client(monkeypatch)
+ mocks.get_session.return_value = _closing_session().model_copy(update={"completed_at": _ENDED})
+ _consumable_archive(mocks, {"pbs_1": "/tmp/session_dir"})
+ body = {"name": "my profile", "browser_session_id": "pbs_1"}
+
+ first = client.post("/v1/browser_profiles/", json=body)
+ retry = client.post("/v1/browser_profiles/", json=body)
+ renamed = client.post("/v1/browser_profiles/", json={**body, "name": "another name"})
+
+ assert first.status_code == retry.status_code == 200
+ assert retry.json()["browser_profile_id"] == first.json()["browser_profile_id"]
+ mocks.create_profile.assert_awaited_once()
+ # The archive is already consumed, so a save under another name fails for good instead of making a second copy.
+ assert renamed.status_code == 400
+ assert _RETRYABLE_HINT not in renamed.json()["detail"]
+
+
[email protected]("same_name", [True, False])
+async def test_overlapping_saves_of_a_closing_session_create_one_profile(
+ monkeypatch: pytest.MonkeyPatch, same_name: bool
+) -> None:
+ _, mocks = _build_client(monkeypatch)
+ closing = _closing_session()
+ archives: dict[str, str] = {}
+ teardown = SimpleNamespace(uploaded=False)
+ names: list[str] = []
+
+ async def get_session(*_args: object) -> PersistentBrowserSession:
+ # Teardown uploads the archive once, about 1 s in, and stamps completed_at shortly after.
+ if mocks.clock.now >= 1 and not teardown.uploaded:
+ teardown.uploaded = True
+ archives["pbs_1"] = "/tmp/session_dir"
+ return closing.model_copy(update={"completed_at": _ENDED}) if mocks.clock.now >= 2 else closing
+
+ async def create_profile(**kwargs: object) -> BrowserProfile:
+ await asyncio.sleep(0)
+ if kwargs["name"] in names:
+ raise IntegrityError("duplicate name", None, Exception())
+ names.append(str(kwargs["name"]))
+ return _profile().model_copy(update={"browser_profile_id": f"bp_{len(names)}", "name": kwargs["name"]})
+
+ _consumable_archive(mocks, archives)
+ mocks.get_session.side_effect = get_session
+ mocks.create_profile.side_effect = create_profile
+ mocks.get_db_profile.side_effect = lambda profile_id, organization_id: _profile().model_copy(
+ update={"browser_profile_id": profile_id, "name": names[int(profile_id.removeprefix("bp_")) - 1]}
+ )
+
+ async def save(name: str) -> tuple[int, str]:
+ try:
+ profile = await browser_profiles_route._create_profile_from_session(
+ organization_id="org_oss", name=name, description=None, browser_session_id="pbs_1"
+ )
+ except HTTPException as exc:
+ return exc.status_code, str(exc.detail)
+ return 200, profile.browser_profile_id
+
+ first = asyncio.create_task(save("my profile"))
+ await asyncio.sleep(0)
+ second = asyncio.create_task(save("my profile" if same_name else "my profile (retry)"))
+ results = await asyncio.gather(first, second)
+
+ assert len(names) == 1
+ assert results[0] == (200, "bp_1")
+ if same_name:
+ assert results[1] == (200, "bp_1")
+ else:
+ assert results[1][0] == 400
+
+
def _run_and_workflow(persist: bool) -> tuple[SimpleNamespace, SimpleNamespace]:
run = SimpleNamespace(workflow_id="w", workflow_permanent_id="wpid")
workflow = SimpleNamespace(persist_browser_session=persist, workflow_permanent_id="wpid")
@@ -875,7 +1114,7 @@ async def test_create_from_run_engine_on_no_persist_polls_instead_of_immediate_4
)
retrieve = AsyncMock(return_value=None)
monkeypatch.setattr(browser_profiles_route, "retrieve_persisted_workflow_browser_state_dir", retrieve)
- monkeypatch.setattr(browser_profiles_route.asyncio, "sleep", AsyncMock())
+ monkeypatch.setattr(browser_profiles_route, "asyncio", ScopedAsyncio(sleep=AsyncMock()))
with pytest.raises(HTTPException) as exc:
await browser_profiles_route._create_profile_from_workflow_run(