Skip to content

Automate browser based workflows with AI

feat(SKY-11336): backend support for label rename, recolor, soft-delete (#6819)

Aaron Perez93cc27844cb8
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.json
index 018ce3d57..7662d4ef9 100644
--- a/docs/api-reference/openapi.json
+++ b/docs/api-reference/openapi.json
@@ -1573,7 +1573,7 @@
"Tags"
],
"summary": "List tag values",
- "description": "List the palette color assigned to each grouped tag (key, value) for the organization. The frontend joins these onto tags by (key, value).",
+ "description": "List the palette color and current workflow usage count for each grouped tag (key, value) for the organization. The frontend joins these onto tags by (key, value); workflow_count is the number of non-deleted workflows carrying the label and powers the per-label usage and delete blast-radius warnings.",
"operationId": "list_tag_values_v1_tag_values_get",
"parameters": [
{
@@ -1695,6 +1695,160 @@
}
},
"x-fern-sdk-method-name": "update_tag_value"
+ },
+ "delete": {
+ "tags": [
+ "Tags"
+ ],
+ "summary": "Delete tag value",
+ "description": "Soft-delete a grouped tag (key, value) and remove that label from every workflow carrying it (cascade). The value rides in the body so values containing '/' stay addressable. Returns how many workflows the label was removed from.",
+ "operationId": "delete_tag_value_v1_tag_values__key__delete",
+ "parameters": [
+ {
+ "name": "key",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "description": "Tag key (group)",
+ "examples": [
+ "env"
+ ],
+ "title": "Key"
+ },
+ "description": "Tag key (group)"
+ },
+ {
+ "name": "x-api-key",
+ "in": "header",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",
+ "title": "X-Api-Key"
+ },
+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TagValueDelete"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Successfully deleted tag value",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TagValueDeleteResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Tag value not found"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ },
+ "x-fern-sdk-method-name": "delete_tag_value"
+ }
+ },
+ "/v1/tag-values/{key}/rename": {
+ "patch": {
+ "tags": [
+ "Tags"
+ ],
+ "summary": "Rename tag value",
+ "description": "Rename a grouped tag (key, value) to (key, new_value). The cascade re-tags every workflow carrying the old label; the new label inherits the old color. Both values ride in the body so values containing '/' stay addressable. Rejects with 409 when the new value already exists for the key.",
+ "operationId": "rename_tag_value_v1_tag_values__key__rename_patch",
+ "parameters": [
+ {
+ "name": "key",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "description": "Tag key (group)",
+ "examples": [
+ "env"
+ ],
+ "title": "Key"
+ },
+ "description": "Tag key (group)"
+ },
+ {
+ "name": "x-api-key",
+ "in": "header",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",
+ "title": "X-Api-Key"
+ },
+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TagValueRename"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Successfully renamed tag value",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TagValueRenameResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Tag value not found"
+ },
+ "409": {
+ "description": "Target value already exists for this key"
+ },
+ "422": {
+ "description": "Invalid value"
+ }
+ },
+ "x-fern-sdk-method-name": "rename_tag_value"
}
},
"/v1/workflow-tags": {
@@ -18803,6 +18957,12 @@
"color": {
"type": "string",
"title": "Color"
+ },
+ "workflow_count": {
+ "type": "integer",
+ "title": "Workflow Count",
+ "description": "Number of non-deleted workflows currently carrying this (key, value) label.",
+ "default": 0
}
},
"type": "object",
@@ -18814,6 +18974,95 @@
"title": "TagValue",
"description": "Tag-value color registry entry: the palette color assigned to a grouped\n(key, value) pair."
},
+ "TagValueDelete": {
+ "properties": {
+ "value": {
+ "type": "string",
+ "title": "Value",
+ "description": "Tag value (label) under the key to soft-delete."
+ }
+ },
+ "type": "object",
+ "required": [
+ "value"
+ ],
+ "title": "TagValueDelete",
+ "description": "Body for ``DELETE /v1/tag-values/{key}``. The value rides in the body, not the\npath, so values containing ``/`` stay addressable."
+ },
+ "TagValueDeleteResponse": {
+ "properties": {
+ "key": {
+ "type": "string",
+ "title": "Key"
+ },
+ "value": {
+ "type": "string",
+ "title": "Value"
+ },
+ "removed_from_workflow_count": {
+ "type": "integer",
+ "title": "Removed From Workflow Count"
+ }
+ },
+ "type": "object",
+ "required": [
+ "key",
+ "value",
+ "removed_from_workflow_count"
+ ],
+ "title": "TagValueDeleteResponse",
+ "description": "Response for ``DELETE /v1/tag-values/{key}``."
+ },
+ "TagValueRename": {
+ "properties": {
+ "value": {
+ "type": "string",
+ "title": "Value",
+ "description": "Current tag value (label) under the key to rename."
+ },
+ "new_value": {
+ "type": "string",
+ "title": "New Value",
+ "description": "New tag value (label) to rename it to."
+ }
+ },
+ "type": "object",
+ "required": [
+ "value",
+ "new_value"
+ ],
+ "title": "TagValueRename",
+ "description": "Body for ``PATCH /v1/tag-values/{key}/rename``. Both the current and the new\nvalue ride in the body so values containing ``/`` stay addressable."
+ },
+ "TagValueRenameResponse": {
+ "properties": {
+ "key": {
+ "type": "string",
+ "title": "Key"
+ },
+ "value": {
+ "type": "string",
+ "title": "Value"
+ },
+ "color": {
+ "type": "string",
+ "title": "Color"
+ },
+ "renamed_workflow_count": {
+ "type": "integer",
+ "title": "Renamed Workflow Count"
+ }
+ },
+ "type": "object",
+ "required": [
+ "key",
+ "value",
+ "color",
+ "renamed_workflow_count"
+ ],
+ "title": "TagValueRenameResponse",
+ "description": "Response for ``PATCH /v1/tag-values/{key}/rename``: the renamed label with its\ncarried-over color and the number of workflows re-tagged."
+ },
"TagValueUpdate": {
"properties": {
"value": {
@@ -23009,6 +23258,17 @@
],
"title": "Browser Profile Id"
},
+ "browser_profile_key": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Browser Profile Key"
+ },
"model": {
"anyOf": [
{
@@ -23311,6 +23571,17 @@
],
"title": "Browser Profile Id"
},
+ "browser_profile_key": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Browser Profile Key"
+ },
"model": {
"anyOf": [
{
@@ -23703,9 +23974,15 @@
"WorkflowDefinitionYAML": {
"properties": {
"version": {
- "type": "integer",
- "title": "Version",
- "default": 1
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Version"
},
"parameters": {
"items": {
diff --git a/skyvern/config.py b/skyvern/config.py
index c4958dea4..35bab560f 100644
--- a/skyvern/config.py
+++ b/skyvern/config.py
@@ -88,6 +88,12 @@ class Settings(BaseSettings):
BROWSER_REMOTE_DEBUGGING_HOST_HEADER: str | None = None
BROWSER_REMOTE_DEBUGGING_CONNECT_HEADERS: str | None = None
BROWSER_CDP_CONNECT_TIMEOUT_MS: int = 120000
+ # connect_over_cdp_with_retry budget. The defaults give ~15s of total backoff
+ # (1+2+3+4+5) across attempts so a browser that is slow to bind its local CDP
+ # port (e.g. a cold-starting stealth Chromium on 127.0.0.1:9222) is reconnected
+ # instead of surfacing an opaque ECONNREFUSED.
+ CDP_CONNECT_RETRY_ATTEMPTS: int = 6
+ CDP_CONNECT_RETRY_BACKOFF_SECONDS: list[float] = [1, 2, 3, 4, 5]
CHROME_EXECUTABLE_PATH: str | None = None
MAX_SCRAPING_RETRIES: int = 0
VIDEO_PATH: str | None = "./video"
diff --git a/skyvern/forge/sdk/db/repositories/tags.py b/skyvern/forge/sdk/db/repositories/tags.py
index 71cd49f8d..a671a50b8 100644
--- a/skyvern/forge/sdk/db/repositories/tags.py
+++ b/skyvern/forge/sdk/db/repositories/tags.py
@@ -6,13 +6,13 @@ from dataclasses import dataclass
from datetime import datetime, timezone
import structlog
-from sqlalchemy import and_, func, select, text, update
+from sqlalchemy import Exists, and_, exists, func, select, text, update
from sqlalchemy.dialects import postgresql, sqlite
from sqlalchemy.ext.asyncio import AsyncSession
from skyvern.forge.sdk.db._error_handling import db_operation, register_passthrough_exception
from skyvern.forge.sdk.db.base_repository import BaseRepository
-from skyvern.forge.sdk.db.models import TagKeyModel, TagValueModel, WorkflowTagEventModel
+from skyvern.forge.sdk.db.models import TagKeyModel, TagValueModel, WorkflowModel, WorkflowTagEventModel
from skyvern.forge.sdk.workflow.models.tags import TagEventType, TagWriteContext
from skyvern.forge.sdk.workflow.models.validators import RUN_METADATA_MAX_KEYS, random_tag_color
@@ -26,8 +26,26 @@ class TagCountLimitExceeded(ValueError):
"""Raised when an apply would push a workflow over MAX_TAGS_PER_WORKFLOW."""
-# Cap breaches are user input, not infra failures — log as BusinessLogicError (WARN).
+class TagValueRenameCollision(ValueError):
+ """Raised when renaming ``(key, old)`` to ``(key, new)`` and ``(key, new)``
+ already exists active org-wide. v1 rejects rather than merging."""
+
+
+# Cap breaches and rename collisions are user input, not infra failures — log as
+# BusinessLogicError (WARN), not UnexpectedError (ERROR).
register_passthrough_exception(TagCountLimitExceeded)
+register_passthrough_exception(TagValueRenameCollision)
+
+
+@dataclass(frozen=True)
+class TagValueRenameResult:
+ """Outcome of a successful grouped-label rename: the new ``(key, value)``,
+ its carried-over color, and how many workflows were re-tagged."""
+
+ key: str
+ value: str
+ color: str
+ renamed_workflow_count: int
@dataclass(frozen=True)
@@ -495,6 +513,89 @@ class TagsRepository(BaseRepository):
rows = await session.execute(stmt)
return {key: count for key, count in rows.all()}
+ @staticmethod
+ def _non_deleted_workflow_exists(organization_id: str) -> Exists:
+ """Correlated EXISTS: the tag event's workflow still has a live version.
+ Soft-deleting a workflow sets ``deleted_at`` on every version row, but its
+ tag events linger; without this filter a label attached only to deleted
+ workflows would inflate the workflow counts."""
+ return exists().where(
+ and_(
+ WorkflowModel.workflow_permanent_id == WorkflowTagEventModel.workflow_permanent_id,
+ WorkflowModel.organization_id == organization_id,
+ WorkflowModel.deleted_at.is_(None),
+ )
+ )
+
+ @db_operation("count_active_workflows_per_value")
+ async def count_active_workflows_per_value(self, organization_id: str) -> dict[tuple[str, str], int]:
+ """Map of grouped ``(key, value)`` -> number of non-deleted workflows carrying
+ it. Powers the per-label delete blast-radius warning. Standalone labels (no
+ key) are excluded; covered by the existing org/key/value active partial index."""
+ async with self.Session() as session:
+ stmt = (
+ select(
+ WorkflowTagEventModel.key,
+ WorkflowTagEventModel.value,
+ func.count(func.distinct(WorkflowTagEventModel.workflow_permanent_id)),
+ )
+ .where(
+ and_(
+ WorkflowTagEventModel.organization_id == organization_id,
+ WorkflowTagEventModel.superseded_at.is_(None),
+ WorkflowTagEventModel.event_type == TagEventType.SET.value,
+ WorkflowTagEventModel.deleted_at.is_(None),
+ WorkflowTagEventModel.key.isnot(None),
+ self._non_deleted_workflow_exists(organization_id),
+ )
+ )
+ .group_by(WorkflowTagEventModel.key, WorkflowTagEventModel.value)
+ )
+ rows = await session.execute(stmt)
+ return {(key, value): count for key, value, count in rows.all()}
+
+ @db_operation("count_active_workflows_for_value")
+ async def count_active_workflows_for_value(self, organization_id: str, key: str, value: str) -> int:
+ """Number of non-deleted workflows with an active SET on grouped ``(key, value)``.
+ Targeted single-pair count for the recolor/rename response, avoiding the full-org
+ GROUP BY that ``count_active_workflows_per_value`` runs for the list endpoint."""
+ async with self.Session() as session:
+ stmt = select(func.count(func.distinct(WorkflowTagEventModel.workflow_permanent_id))).where(
+ and_(
+ WorkflowTagEventModel.organization_id == organization_id,
+ WorkflowTagEventModel.key == key,
+ WorkflowTagEventModel.value == value,
+ WorkflowTagEventModel.superseded_at.is_(None),
+ WorkflowTagEventModel.event_type == TagEventType.SET.value,
+ WorkflowTagEventModel.deleted_at.is_(None),
+ self._non_deleted_workflow_exists(organization_id),
+ )
+ )
+ return (await session.execute(stmt)).scalar_one()
+
+ async def _soft_delete_tag_value_rows(
+ self,
+ session: AsyncSession,
+ *,
+ organization_id: str,
+ key: str,
+ now: datetime,
+ value: str | None = None,
+ ) -> None:
+ """Soft-delete the active ``tag_values`` color rows for a key (all values
+ when ``value`` is None, or a single ``(key, value)`` pair otherwise) so
+ GET /tag-values stops returning colors for removed labels. Shared by
+ ``delete_tag_key``, ``delete_tag_value``, and ``rename_tag_value`` (which
+ retires the old value's row) to keep the cascade consistent."""
+ stmt = update(TagValueModel).where(
+ TagValueModel.organization_id == organization_id,
+ TagValueModel.key == key,
+ TagValueModel.deleted_at.is_(None),
+ )
+ if value is not None:
+ stmt = stmt.where(TagValueModel.value == value)
+ await session.execute(stmt.values(deleted_at=now))
+
@db_operation("delete_tag_key")
async def delete_tag_key(
self,
@@ -577,14 +678,246 @@ class TagsRepository(BaseRepository):
)
key_row.deleted_at = now
- await session.execute(
- update(TagValueModel)
- .where(
- TagValueModel.organization_id == organization_id,
- TagValueModel.key == key,
- TagValueModel.deleted_at.is_(None),
+ await self._soft_delete_tag_value_rows(session, organization_id=organization_id, key=key, now=now)
+ await session.commit()
+ return len(active_sets)
+
+ @db_operation("delete_tag_value")
+ async def delete_tag_value(
+ self,
+ organization_id: str,
+ key: str,
+ value: str,
+ context: TagWriteContext,
+ ) -> int | None:
+ """Cascade-delete a single grouped label ``(key, value)``, mirroring
+ ``delete_tag_key`` at value granularity: write a DELETE event (carrying the
+ value, so history records which label was removed) for every workflow with
+ an active SET on it, then soft-delete the ``(key, value)`` color row. Returns
+ the number of workflows the label was removed from, or None when neither a
+ registered color row nor an active SET exists (caller should 404). Idempotent:
+ a second call returns None; re-applying via a SET re-registers the label.
+
+ DELETE events don't match the SET-only partial UNIQUE, so superseding the SET
+ and inserting the DELETE in one transaction needs no flush ordering (same as
+ ``delete_tag_key``). The same accepted delete-vs-SET race applies."""
+ now = datetime.now(timezone.utc)
+ async with self.Session() as session:
+ value_row = (
+ await session.execute(
+ select(TagValueModel).where(
+ and_(
+ TagValueModel.organization_id == organization_id,
+ TagValueModel.key == key,
+ TagValueModel.value == value,
+ TagValueModel.deleted_at.is_(None),
+ )
+ )
)
- .values(deleted_at=now)
+ ).scalar_one_or_none()
+
+ active_sets = (
+ (
+ await session.execute(
+ select(WorkflowTagEventModel).where(
+ and_(
+ WorkflowTagEventModel.organization_id == organization_id,
+ WorkflowTagEventModel.key == key,
+ WorkflowTagEventModel.value == value,
+ WorkflowTagEventModel.superseded_at.is_(None),
+ WorkflowTagEventModel.event_type == TagEventType.SET.value,
+ WorkflowTagEventModel.deleted_at.is_(None),
+ )
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
+
+ if value_row is None and not active_sets:
+ return None
+
+ for existing in active_sets:
+ existing.superseded_at = now
+ session.add(
+ WorkflowTagEventModel(
+ workflow_permanent_id=existing.workflow_permanent_id,
+ organization_id=organization_id,
+ key=key,
+ value=value,
+ event_type=TagEventType.DELETE.value,
+ set_at=now,
+ set_by=context.caller_id,
+ source=context.source.value,
+ caller_type=context.caller_type.value if context.caller_type else None,
+ )
+ )
+
+ await self._soft_delete_tag_value_rows(
+ session, organization_id=organization_id, key=key, now=now, value=value
)
await session.commit()
return len(active_sets)
+
+ @db_operation("rename_tag_value")
+ async def rename_tag_value(
+ self,
+ organization_id: str,
+ key: str,
+ old_value: str,
+ new_value: str,
+ context: TagWriteContext,
+ ) -> TagValueRenameResult | None:
+ """Rename a grouped label ``(key, old_value)`` -> ``(key, new_value)`` by
+ cascading through the append-only event log (mirrors ``delete_tag_key`` but
+ inserts a SET, not a DELETE): for every workflow with an active SET on
+ ``(key, old_value)``, supersede it and insert a new SET on ``(key, new_value)``.
+ The new color row inherits the old row's color. Historical events keep their
+ point-in-time value (append-only invariant preserved). Returns the rename
+ result, or None when ``(key, old_value)`` is not present (caller should 404).
+
+ Raises ``TagValueRenameCollision`` when ``(key, new_value)`` already exists
+ active org-wide (registered or in use) — v1 rejects rather than merging.
+
+ The new SET shares the ``(org, wpid, key)`` active-SET partial UNIQUE with the
+ superseded row, so the supersede UPDATEs are flushed before the new SET INSERTs
+ (same ordering ``apply_tag_changes`` relies on).
+
+ Accepted race (mirrors ``delete_tag_key``): the active-set read, the collision
+ check, and the cascade are not serialized against a concurrent ``apply_tag_changes``.
+ A SET on ``(key, old_value)`` landing after the read is missed (left on the old
+ value), and a SET on ``(key, new_value)`` landing after the collision check can
+ coexist with the rename — surfacing as a transient IntegrityError on the partial
+ UNIQUE (the caller's one retry covers it) or two active SETs that the next apply
+ reconciles. Serializing would need dialect-specific row/advisory locking,
+ disproportionate for a rare manual admin action."""
+ now = datetime.now(timezone.utc)
+ async with self.Session() as session:
+ old_row = (
+ await session.execute(
+ select(TagValueModel).where(
+ and_(
+ TagValueModel.organization_id == organization_id,
+ TagValueModel.key == key,
+ TagValueModel.value == old_value,
+ TagValueModel.deleted_at.is_(None),
+ )
+ )
+ )
+ ).scalar_one_or_none()
+
+ active_sets = (
+ (
+ await session.execute(
+ select(WorkflowTagEventModel).where(
+ and_(
+ WorkflowTagEventModel.organization_id == organization_id,
+ WorkflowTagEventModel.key == key,
+ WorkflowTagEventModel.value == old_value,
+ WorkflowTagEventModel.superseded_at.is_(None),
+ WorkflowTagEventModel.event_type == TagEventType.SET.value,
+ WorkflowTagEventModel.deleted_at.is_(None),
+ )
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
+
+ if old_row is None and not active_sets:
+ return None
+
+ if await self._grouped_value_active(session, organization_id=organization_id, key=key, value=new_value):
+ raise TagValueRenameCollision(
+ f"tag value '{key}:{new_value}' already exists; rename would merge labels (not supported)"
+ )
+
+ for existing in active_sets:
+ existing.superseded_at = now
+ # Flush supersede UPDATEs before the new SET INSERTs so the active-SET
+ # partial UNIQUE on (org, wpid, key) sees a consistent state.
+ await session.flush()
+ for existing in active_sets:
+ session.add(
+ WorkflowTagEventModel(
+ workflow_permanent_id=existing.workflow_permanent_id,
+ organization_id=organization_id,
+ key=key,
+ value=new_value,
+ event_type=TagEventType.SET.value,
+ set_at=now,
+ set_by=context.caller_id,
+ source=context.source.value,
+ caller_type=context.caller_type.value if context.caller_type else None,
+ )
+ )
+
+ carried_color = old_row.color if old_row is not None else random_tag_color()
+ dialect_name = session.bind.dialect.name if session.bind is not None else "postgresql"
+ insert = sqlite.insert if dialect_name == "sqlite" else postgresql.insert
+ upsert = (
+ insert(TagValueModel.__table__)
+ .values(organization_id=organization_id, key=key, value=new_value, color=carried_color)
+ .on_conflict_do_update(
+ index_elements=["organization_id", "key", "value"],
+ index_where=text("deleted_at IS NULL"),
+ set_={"color": carried_color, "modified_at": now},
+ )
+ )
+ await session.execute(upsert)
+ await self._soft_delete_tag_value_rows(
+ session, organization_id=organization_id, key=key, now=now, value=old_value
+ )
+ await session.commit()
+ return TagValueRenameResult(
+ key=key,
+ value=new_value,
+ color=carried_color,
+ renamed_workflow_count=len(active_sets),
+ )
+
+ async def _grouped_value_active(
+ self,
+ session: AsyncSession,
+ *,
+ organization_id: str,
+ key: str,
+ value: str,
+ ) -> bool:
+ """True when grouped label ``(key, value)`` exists active org-wide — either a
+ registered color row or an active SET event in use on some workflow."""
+ registered = (
+ await session.execute(
+ select(TagValueModel.tag_value_id)
+ .where(
+ and_(
+ TagValueModel.organization_id == organization_id,
+ TagValueModel.key == key,
+ TagValueModel.value == value,
+ TagValueModel.deleted_at.is_(None),
+ )
+ )
+ .limit(1)
+ )
+ ).first()
+ if registered is not None:
+ return True
+ in_use = (
+ await session.execute(
+ select(WorkflowTagEventModel.tag_event_id)
+ .where(
+ and_(
+ WorkflowTagEventModel.organization_id == organization_id,
+ WorkflowTagEventModel.key == key,
+ WorkflowTagEventModel.value == value,
+ WorkflowTagEventModel.superseded_at.is_(None),
+ WorkflowTagEventModel.event_type == TagEventType.SET.value,
+ WorkflowTagEventModel.deleted_at.is_(None),
+ )
+ )
+ .limit(1)
+ )
+ ).first()
+ return in_use is not None
diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.py
index 4ee4d2c44..33a002237 100644
--- a/skyvern/forge/sdk/routes/agent_protocol.py
+++ b/skyvern/forge/sdk/routes/agent_protocol.py
@@ -55,6 +55,7 @@ from skyvern.forge.sdk.core.curl_converter import curl_to_http_request_block_par
from skyvern.forge.sdk.core.permissions.permission_checker_factory import PermissionCheckerFactory
from skyvern.forge.sdk.core.security import generate_skyvern_signature
from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType
+from skyvern.forge.sdk.db.repositories.tags import TagValueRenameCollision, TagValueRenameResult
from skyvern.forge.sdk.enterprise_features import collect_enterprise_gated_run_features
from skyvern.forge.sdk.executor.factory import AsyncExecutorFactory
from skyvern.forge.sdk.models import Step
@@ -156,6 +157,10 @@ from skyvern.schemas.tags import (
TagResponse,
TagsResponse,
TagValue,
+ TagValueDelete,
+ TagValueDeleteResponse,
+ TagValueRename,
+ TagValueRenameResponse,
TagValueUpdate,
WorkflowTagsBatchRequest,
WorkflowTagsBatchResponse,
@@ -1596,6 +1601,39 @@ async def _apply_tag_changes_with_retry(
)
+async def _rename_tag_value_with_retry(
+ *,
+ organization_id: str,
+ key: str,
+ old_value: str,
+ new_value: str,
+ context: TagWriteContext,
+) -> TagValueRenameResult | None:
+ """Wrap ``rename_tag_value`` with one IntegrityError retry: a concurrent SET on
+ ``(key, new_value)`` can race the active-SET partial UNIQUE between the rename's
+ collision check and its new SET inserts; last-write-wins on retry, else 409
+ (mirrors ``_apply_tag_changes_with_retry``). ``TagValueRenameCollision`` is a
+ deterministic conflict and is mapped to 409 by the caller, not retried here."""
+ for attempt in range(2):
+ try:
+ return await app.DATABASE.tags.rename_tag_value(
+ organization_id=organization_id,
+ key=key,
+ old_value=old_value,
+ new_value=new_value,
+ context=context,
+ )
+ except IntegrityError:
+ if attempt == 0:
+ await asyncio.sleep(random.uniform(0.01, 0.05))
+ continue
+ raise HTTPException(
+ status_code=http_status.HTTP_409_CONFLICT,
+ detail="Tag value rename conflicted with a concurrent update; please retry",
+ )
+ return None
+
+
async def require_workflow_tagging(
current_org: Organization = Depends(org_auth_service.get_current_org),
) -> None:
@@ -1916,8 +1954,9 @@ async def delete_tag_key(
response_model=list[TagValue],
tags=["Tags"],
openapi_extra={"x-fern-sdk-method-name": "list_tag_values"},
- description="List the palette color assigned to each grouped tag (key, value) for the organization. "
- "The frontend joins these onto tags by (key, value).",
+ description="List the palette color and current workflow usage count for each grouped tag (key, value) "
+ "for the organization. The frontend joins these onto tags by (key, value); workflow_count is the number "
+ "of non-deleted workflows carrying the label and powers the per-label usage and delete blast-radius warnings.",
summary="List tag values",
responses={200: {"description": "Successfully retrieved tag values"}},
)
@@ -1928,7 +1967,16 @@ async def list_tag_values(
) -> list[TagValue]:
organization_id = current_org.organization_id
rows = await app.DATABASE.tags.list_tag_values(organization_id=organization_id)
- return [TagValue(key=row.key, value=row.value, color=row.color) for row in rows]
+ counts = await app.DATABASE.tags.count_active_workflows_per_value(organization_id=organization_id)
+ return [
+ TagValue(
+ key=row.key,
+ value=row.value,
+ color=row.color,
+ workflow_count=counts.get((row.key, row.value), 0),
+ )
+ for row in rows
+ ]
@legacy_base_router.patch("/tag-values/{key}", response_model=TagValue, tags=["agent"], include_in_schema=False)
@@ -1967,7 +2015,109 @@ async def update_tag_value(
status_code=http_status.HTTP_404_NOT_FOUND,
detail=f"Tag value '{key}:{data.value}' not found",
)
- return TagValue(key=row.key, value=row.value, color=row.color)
+ count = await app.DATABASE.tags.count_active_workflows_for_value(
+ organization_id=organization_id, key=row.key, value=row.value
+ )
+ return TagValue(key=row.key, value=row.value, color=row.color, workflow_count=count)
+
+
+@legacy_base_router.patch("/tag-values/{key}/rename", response_model=TagValueRenameResponse, include_in_schema=False)
+@legacy_base_router.patch("/tag-values/{key}/rename/", response_model=TagValueRenameResponse, include_in_schema=False)
+@base_router.patch(
+ "/tag-values/{key}/rename",
+ response_model=TagValueRenameResponse,
+ tags=["Tags"],
+ openapi_extra={"x-fern-sdk-method-name": "rename_tag_value"},
+ description="Rename a grouped tag (key, value) to (key, new_value). The cascade re-tags every workflow "
+ "carrying the old label; the new label inherits the old color. Both values ride in the body so values "
+ "containing '/' stay addressable. Rejects with 409 when the new value already exists for the key.",
+ summary="Rename tag value",
+ responses={
+ 200: {"description": "Successfully renamed tag value"},
+ 404: {"description": "Tag value not found"},
+ 409: {"description": "Target value already exists for this key"},
+ 422: {"description": "Invalid value"},
+ },
+)
+@base_router.patch("/tag-values/{key}/rename/", response_model=TagValueRenameResponse, include_in_schema=False)
+async def rename_tag_value(
+ key: str = Path(..., description="Tag key (group)", examples=["env"]),
+ data: TagValueRename = Body(...),
+ caller: org_auth_service.CallerContext = Depends(org_auth_service.get_current_caller_context),
+ _tagging_gate: None = Depends(require_workflow_tagging),
+) -> TagValueRenameResponse:
+ analytics.capture("skyvern-oss-tag-value-rename")
+ _validate_path_key(key)
+ context = TagWriteContext(
+ caller_id=caller.caller_id,
+ source=TagSource.MANUAL,
+ caller_type=caller.caller_type,
+ )
+ try:
+ result = await _rename_tag_value_with_retry(
+ organization_id=caller.organization.organization_id,
+ key=key,
+ old_value=data.value,
+ new_value=data.new_value,
+ context=context,
+ )
+ except TagValueRenameCollision as e:
+ raise HTTPException(status_code=http_status.HTTP_409_CONFLICT, detail=str(e)) from e
+ if result is None:
+ raise HTTPException(
+ status_code=http_status.HTTP_404_NOT_FOUND,
+ detail=f"Tag value '{key}:{data.value}' not found",
+ )
+ return TagValueRenameResponse(
+ key=result.key,
+ value=result.value,
+ color=result.color,
+ renamed_workflow_count=result.renamed_workflow_count,
+ )
+
+
+@legacy_base_router.delete("/tag-values/{key}", tags=["agent"], include_in_schema=False)
+@legacy_base_router.delete("/tag-values/{key}/", include_in_schema=False)
+@base_router.delete(
+ "/tag-values/{key}",
+ response_model=TagValueDeleteResponse,
+ tags=["Tags"],
+ openapi_extra={"x-fern-sdk-method-name": "delete_tag_value"},
+ description="Soft-delete a grouped tag (key, value) and remove that label from every workflow carrying it "
+ "(cascade). The value rides in the body so values containing '/' stay addressable. Returns how many "
+ "workflows the label was removed from.",
+ summary="Delete tag value",
+ responses={
+ 200: {"description": "Successfully deleted tag value"},
+ 404: {"description": "Tag value not found"},
+ },
+)
+@base_router.delete("/tag-values/{key}/", response_model=TagValueDeleteResponse, include_in_schema=False)
+async def delete_tag_value(
+ key: str = Path(..., description="Tag key (group)", examples=["env"]),
+ data: TagValueDelete = Body(...),
+ caller: org_auth_service.CallerContext = Depends(org_auth_service.get_current_caller_context),
+ _tagging_gate: None = Depends(require_workflow_tagging),
+) -> TagValueDeleteResponse:
+ analytics.capture("skyvern-oss-tag-value-delete")
+ _validate_path_key(key)
+ context = TagWriteContext(
+ caller_id=caller.caller_id,
+ source=TagSource.MANUAL,
+ caller_type=caller.caller_type,
+ )
+ removed_count = await app.DATABASE.tags.delete_tag_value(
+ organization_id=caller.organization.organization_id,
+ key=key,
+ value=data.value,
+ context=context,
+ )
+ if removed_count is None:
+ raise HTTPException(
+ status_code=http_status.HTTP_404_NOT_FOUND,
+ detail=f"Tag value '{key}:{data.value}' not found",
+ )
+ return TagValueDeleteResponse(key=key, value=data.value, removed_from_workflow_count=removed_count)
# Keep in sync with BATCH_TAGS_MAX_WPIDS in the frontend
diff --git a/skyvern/schemas/tags.py b/skyvern/schemas/tags.py
index 853143c5b..bf5e31a82 100644
--- a/skyvern/schemas/tags.py
+++ b/skyvern/schemas/tags.py
@@ -237,6 +237,10 @@ class TagValue(BaseModel):
key: str
value: str
color: str
+ workflow_count: int = Field(
+ default=0,
+ description="Number of non-deleted workflows currently carrying this (key, value) label.",
+ )
class TagValueUpdate(BaseModel):
@@ -257,6 +261,58 @@ class TagValueUpdate(BaseModel):
return normalize_tag_color(v)
+class TagValueRename(BaseModel):
+ """Body for ``PATCH /v1/tag-values/{key}/rename``. Both the current and the new
+ value ride in the body so values containing ``/`` stay addressable."""
+
+ value: str = Field(description="Current tag value (label) under the key to rename.")
+ new_value: str = Field(description="New tag value (label) to rename it to.")
+
+ @field_validator("value", "new_value", mode="before")
+ @classmethod
+ def _normalize_value(cls, v: object) -> str:
+ return normalize_tag_value(v)
+
+ @model_validator(mode="after")
+ def _new_value_is_distinct_and_addressable(self) -> TagValueRename:
+ if self.new_value == self.value:
+ raise ValueError("new_value must differ from the current value")
+ # Grouped values reserve '*' as the group filter wildcard (mirrors TagInput).
+ if self.new_value == "*":
+ raise ValueError("grouped tag values must not be exactly '*' (reserved as the group filter wildcard)")
+ return self
+
+
+class TagValueRenameResponse(BaseModel):
+ """Response for ``PATCH /v1/tag-values/{key}/rename``: the renamed label with its
+ carried-over color and the number of workflows re-tagged."""
+
+ key: str
+ value: str
+ color: str
+ renamed_workflow_count: int
+
+
+class TagValueDelete(BaseModel):
+ """Body for ``DELETE /v1/tag-values/{key}``. The value rides in the body, not the
+ path, so values containing ``/`` stay addressable."""
+
+ value: str = Field(description="Tag value (label) under the key to soft-delete.")
+
+ @field_validator("value", mode="before")
+ @classmethod
+ def _normalize_value(cls, v: object) -> str:
+ return normalize_tag_value(v)
+
+
+class TagValueDeleteResponse(BaseModel):
+ """Response for ``DELETE /v1/tag-values/{key}``."""
+
+ key: str
+ value: str
+ removed_from_workflow_count: int
+
+
class WorkflowTagsBatchRequest(BaseModel):
"""Body for ``POST /v1/workflow-tags`` (used when the wpid list would
exceed the URL length cap)."""
diff --git a/skyvern/webeye/cdp_retry.py b/skyvern/webeye/cdp_retry.py
index bb1b9013c..bef716de7 100644
--- a/skyvern/webeye/cdp_retry.py
+++ b/skyvern/webeye/cdp_retry.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+from typing import cast
import structlog
from playwright._impl._errors import Error as PWError
@@ -8,6 +9,7 @@ from playwright._impl._errors import TargetClosedError as PWTargetClosedError
from playwright._impl._errors import TimeoutError as PWTimeoutError
from playwright.async_api import Browser, Playwright
+from skyvern.config import settings
from skyvern.webeye.cdp_connection import strip_browser_address_discriminator
LOG = structlog.get_logger()
@@ -31,12 +33,30 @@ def is_cdp_connection_error(exc: Exception) -> bool:
return False
-_CDP_RETRY_ATTEMPTS = 3
-_CDP_RETRY_BACKOFF_SECONDS = (1, 3)
# Patch this module alias in tests so shard-wide asyncio.sleep mocks do not leak call counts.
_sleep = asyncio.sleep
+def _settings_field_default(field_name: str) -> object:
+ field = type(settings).model_fields[field_name]
+ if field.default_factory is not None:
+ return field.default_factory()
+ return field.default
+
+
+def _resolve_retry_budget() -> tuple[int, tuple[float, ...]]:
+ """Resolve (attempts, backoff) from settings, falling back to the settings field
+ defaults when the runtime value is invalid so a misconfig (e.g. attempts=0) cannot
+ silently shrink the budget below the configured default."""
+ attempts = settings.CDP_CONNECT_RETRY_ATTEMPTS
+ backoff = tuple(settings.CDP_CONNECT_RETRY_BACKOFF_SECONDS)
+ if attempts < 1:
+ attempts = cast(int, _settings_field_default("CDP_CONNECT_RETRY_ATTEMPTS"))
+ if not backoff or any(seconds < 0 for seconds in backoff):
+ backoff = tuple(cast("list[float]", _settings_field_default("CDP_CONNECT_RETRY_BACKOFF_SECONDS")))
+ return attempts, backoff
+
+
async def connect_over_cdp_with_retry(
playwright: Playwright,
browser_address: str,
@@ -45,7 +65,8 @@ async def connect_over_cdp_with_retry(
) -> Browser:
browser_address = strip_browser_address_discriminator(browser_address)
browser_address_for_logs = log_browser_address or browser_address
- for attempt in range(1, _CDP_RETRY_ATTEMPTS + 1):
+ max_attempts, backoff_schedule = _resolve_retry_budget()
+ for attempt in range(1, max_attempts + 1):
try:
browser = await playwright.chromium.connect_over_cdp(browser_address, headers=headers)
if attempt > 1:
@@ -56,7 +77,7 @@ async def connect_over_cdp_with_retry(
)
return browser
except Exception as e:
- if not is_cdp_connection_error(e) or attempt == _CDP_RETRY_ATTEMPTS:
+ if not is_cdp_connection_error(e) or attempt == max_attempts:
# When the caller passed log_browser_address as a safe label, the raw
# browser_address may carry session tokens in path/query — Playwright's
# exception text would otherwise expose them. Re-raise a RuntimeError
@@ -64,16 +85,12 @@ async def connect_over_cdp_with_retry(
if log_browser_address is not None:
raise RuntimeError(f"CDP connection to {log_browser_address} failed ({type(e).__name__})") from None
raise
- backoff = (
- _CDP_RETRY_BACKOFF_SECONDS[attempt - 1]
- if attempt - 1 < len(_CDP_RETRY_BACKOFF_SECONDS)
- else _CDP_RETRY_BACKOFF_SECONDS[-1]
- )
+ backoff = backoff_schedule[attempt - 1] if attempt - 1 < len(backoff_schedule) else backoff_schedule[-1]
LOG.warning(
"CDP connection failed, retrying",
browser_address=browser_address_for_logs,
attempt=attempt,
- max_attempts=_CDP_RETRY_ATTEMPTS,
+ max_attempts=max_attempts,
backoff_seconds=backoff,
error_type=type(e).__name__,
)
diff --git a/tests/unit/test_cdp_connection_retry.py b/tests/unit/test_cdp_connection_retry.py
index 38a1003fc..6b703dfca 100644
--- a/tests/unit/test_cdp_connection_retry.py
+++ b/tests/unit/test_cdp_connection_retry.py
@@ -6,7 +6,8 @@ import pytest
from playwright._impl._errors import Error as PWError
from playwright._impl._errors import TimeoutError as PWTimeoutError
-from skyvern.webeye.cdp_retry import connect_over_cdp_with_retry
+from skyvern.config import settings
+from skyvern.webeye.cdp_retry import _resolve_retry_budget, connect_over_cdp_with_retry
def _make_playwright(side_effect):
@@ -15,6 +16,11 @@ def _make_playwright(side_effect):
return pw
+def _set_budget(monkeypatch: pytest.MonkeyPatch, attempts: int, backoff: list[float]) -> None:
+ monkeypatch.setattr(settings, "CDP_CONNECT_RETRY_ATTEMPTS", attempts)
+ monkeypatch.setattr(settings, "CDP_CONNECT_RETRY_BACKOFF_SECONDS", list(backoff))
+
+
class TestRetryBehavior:
@pytest.mark.asyncio
async def test_succeeds_on_first_attempt(self):
@@ -80,7 +86,8 @@ class TestRetryBehavior:
assert mock_sleep.call_count == 2
@pytest.mark.asyncio
- async def test_all_attempts_fail_raises(self):
+ async def test_all_attempts_fail_raises(self, monkeypatch):
+ _set_budget(monkeypatch, attempts=3, backoff=[1, 3])
error = PWError("connect ECONNREFUSED 10.0.0.1:9224")
pw = _make_playwright([error, error, error])
with patch("skyvern.webeye.cdp_retry._sleep", new_callable=AsyncMock):
@@ -96,10 +103,11 @@ class TestRetryBehavior:
assert pw.chromium.connect_over_cdp.call_count == 1
@pytest.mark.asyncio
- async def test_final_attempt_raised_exception_does_not_leak_url_when_label_provided(self):
+ async def test_final_attempt_raised_exception_does_not_leak_url_when_label_provided(self, monkeypatch):
"""When log_browser_address is set, the final-attempt exception is a plain
RuntimeError whose message contains only the safe label and the original
error class name — never the raw browser_address."""
+ _set_budget(monkeypatch, attempts=3, backoff=[1, 3])
secret_address = "wss://cdp.vendor.test/devtools/browser/SECRET?token=ABC"
underlying_msg = (
"BrowserType.connect_over_cdp: connect ECONNREFUSED wss://cdp.vendor.test/devtools/browser/SECRET?token=ABC"
@@ -126,9 +134,10 @@ class TestRetryBehavior:
assert excinfo.value.__cause__ is None
@pytest.mark.asyncio
- async def test_final_attempt_unchanged_when_no_label(self):
+ async def test_final_attempt_unchanged_when_no_label(self, monkeypatch):
"""When log_browser_address is not provided, behavior is unchanged — the original
Playwright exception (with its full URL) bubbles up as today."""
+ _set_budget(monkeypatch, attempts=3, backoff=[1, 3])
underlying_msg = "BrowserType.connect_over_cdp: connect ECONNREFUSED 10.0.0.1:9224"
error = PWError(underlying_msg)
pw = _make_playwright([error, error, error])
@@ -140,7 +149,8 @@ class TestRetryBehavior:
assert str(excinfo.value) == underlying_msg
@pytest.mark.asyncio
- async def test_backoff_is_bounded(self):
+ async def test_backoff_is_bounded(self, monkeypatch):
+ _set_budget(monkeypatch, attempts=3, backoff=[1, 3])
error = PWError("connect ECONNRESET")
pw = _make_playwright([error, error, error])
sleep_values = []
@@ -152,3 +162,54 @@ class TestRetryBehavior:
with pytest.raises(PWError):
await connect_over_cdp_with_retry(pw, "http://10.0.0.1:9224")
assert sleep_values == [1, 3]
+
+ @pytest.mark.asyncio
+ async def test_backoff_schedule_clamps_to_last_entry(self, monkeypatch):
+ """When attempts exceed the backoff schedule length, the last backoff value repeats."""
+ _set_budget(monkeypatch, attempts=5, backoff=[1, 2])
+ error = PWError("connect ECONNREFUSED 127.0.0.1:9222")
+ pw = _make_playwright([error, error, error, error, error])
+ sleep_values = []
+
+ async def track_sleep(seconds):
+ sleep_values.append(seconds)
+
+ with patch("skyvern.webeye.cdp_retry._sleep", side_effect=track_sleep):
+ with pytest.raises(PWError):
+ await connect_over_cdp_with_retry(pw, "http://127.0.0.1:9222")
+ assert sleep_values == [1, 2, 2, 2]
+
+
+class TestRetryBudget:
+ def test_default_budget_extends_total_wait_to_roughly_15s(self):
+ """A slow-to-bind local CDP port gets ~15s of reconnect headroom by default."""
+ attempts, backoff = _resolve_retry_budget()
+ sleeps_between_attempts = [backoff[min(i, len(backoff) - 1)] for i in range(attempts - 1)]
+ assert attempts >= 6
+ assert sum(sleeps_between_attempts) >= 15
+
+ def test_invalid_attempts_falls_back_to_settings_field_default(self, monkeypatch):
+ """An invalid runtime override falls back to the settings field default (the robust
+ ~15s budget), never to a smaller hardcoded value that could reintroduce slow-bind ECONNREFUSED."""
+ monkeypatch.setattr(settings, "CDP_CONNECT_RETRY_ATTEMPTS", 0)
+ attempts, _ = _resolve_retry_budget()
+ assert attempts == 6
+
+ def test_invalid_backoff_falls_back_to_settings_field_default(self, monkeypatch):
+ monkeypatch.setattr(settings, "CDP_CONNECT_RETRY_BACKOFF_SECONDS", [])
+ _, backoff = _resolve_retry_budget()
+ assert backoff == (1, 2, 3, 4, 5)
+
+ @pytest.mark.asyncio
+ async def test_slow_to_bind_local_port_reconnects_on_a_later_attempt(self, monkeypatch):
+ """Stealth Chromium that is slow to bind 127.0.0.1:9222 is reconnected once the
+ port comes up on a later attempt, instead of surfacing ECONNREFUSED to the caller."""
+ _set_budget(monkeypatch, attempts=6, backoff=[1, 2, 3, 4, 5])
+ refused = PWError("BrowserType.connect_over_cdp: connect ECONNREFUSED 127.0.0.1:9222")
+ # Port binds on the 5th attempt (after 4 refusals while the browser cold-starts).
+ pw = _make_playwright([refused, refused, refused, refused, "browser"])
+ with patch("skyvern.webeye.cdp_retry._sleep", new_callable=AsyncMock) as mock_sleep:
+ result = await connect_over_cdp_with_retry(pw, "http://127.0.0.1:9222")
+ assert result == "browser"
+ assert pw.chromium.connect_over_cdp.call_count == 5
+ assert [call.args[0] for call in mock_sleep.call_args_list] == [1, 2, 3, 4]
diff --git a/tests/unit/test_tag_endpoints.py b/tests/unit/test_tag_endpoints.py
index 102bbad1c..cc815ea94 100644
--- a/tests/unit/test_tag_endpoints.py
+++ b/tests/unit/test_tag_endpoints.py
@@ -20,10 +20,11 @@ import pytest
import pytest_asyncio
from fastapi import FastAPI
from fastapi.testclient import TestClient
-from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker, create_async_engine
from skyvern.forge.sdk.db.base_alchemy_db import BaseAlchemyDB
-from skyvern.forge.sdk.db.models import Base
+from skyvern.forge.sdk.db.models import Base, WorkflowModel
from skyvern.forge.sdk.db.repositories.tags import TagsRepository
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.services import org_auth_service
@@ -51,6 +52,14 @@ async def engine() -> AsyncGenerator[AsyncEngine]:
eng = create_async_engine("sqlite+aiosqlite:///:memory:")
async with eng.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
+ # The workflow the tag routes operate on must exist (non-deleted) so the
+ # value-count filter can resolve it, mirroring the existence mock below.
+ session_maker = async_sessionmaker(eng, expire_on_commit=False)
+ async with session_maker() as session:
+ session.add(
+ WorkflowModel(organization_id=ORG_ID, workflow_permanent_id=WPID, title="t", workflow_definition={})
+ )
+ await session.commit()
yield eng
await eng.dispose()
@@ -737,7 +746,7 @@ def test_patch_tag_value_recolors(client: TestClient) -> None:
)
resp = client.patch("/v1/tag-values/env", json={"value": "prod", "color": "pink"})
assert resp.status_code == 200, resp.text
- assert resp.json() == {"key": "env", "value": "prod", "color": "pink"}
+ assert resp.json() == {"key": "env", "value": "prod", "color": "pink", "workflow_count": 1}
assert client.get("/v1/tag-values").json()[0]["color"] == "pink"
@@ -748,7 +757,7 @@ def test_patch_tag_value_recolors_value_containing_slash(client: TestClient) ->
)
resp = client.patch("/v1/tag-values/region", json={"value": "us/west", "color": "pink"})
assert resp.status_code == 200, resp.text
- assert resp.json() == {"key": "region", "value": "us/west", "color": "pink"}
+ assert resp.json() == {"key": "region", "value": "us/west", "color": "pink", "workflow_count": 1}
def test_patch_tag_value_404_when_absent(client: TestClient) -> None:
@@ -768,3 +777,156 @@ def test_patch_tag_value_invalid_color_returns_422(client: TestClient) -> None:
def test_patch_tag_value_reserved_prefix_returns_400(client: TestClient) -> None:
resp = client.patch("/v1/tag-values/skyvern.system", json={"value": "prod", "color": "blue"})
assert resp.status_code == 400
+
+
+# ----------------------------- GET /tag-values workflow_count ----------------------
+
+
+def test_get_tag_values_includes_workflow_count(client: TestClient) -> None:
+ client.post(
+ f"/v1/workflows/{WPID}/tags",
+ json={"tags": [{"key": "env", "value": "prod"}], "colors": {"env": "blue"}},
+ )
+ values = client.get("/v1/tag-values").json()
+ assert len(values) == 1
+ assert values[0]["workflow_count"] == 1
+
+
+# ----------------------------- PATCH /tag-values/{key}/rename -----------------------
+
+
+def test_rename_tag_value_cascades_and_carries_color(client: TestClient) -> None:
+ client.post(
+ f"/v1/workflows/{WPID}/tags",
+ json={"tags": [{"key": "env", "value": "prod"}], "colors": {"env": "blue"}},
+ )
+ resp = client.patch("/v1/tag-values/env/rename", json={"value": "prod", "new_value": "production"})
+ assert resp.status_code == 200, resp.text
+ assert resp.json() == {
+ "key": "env",
+ "value": "production",
+ "color": "blue",
+ "renamed_workflow_count": 1,
+ }
+ # The value list now reflects the new label, color carried over.
+ values = client.get("/v1/tag-values").json()
+ assert [(v["value"], v["color"]) for v in values] == [("production", "blue")]
+
+
+def test_rename_tag_value_404_when_absent(client: TestClient) -> None:
+ resp = client.patch("/v1/tag-values/env/rename", json={"value": "prod", "new_value": "production"})
+ assert resp.status_code == 404
+
+
+def test_rename_tag_value_409_on_collision(client: TestClient) -> None:
+ # One workflow holds one value per key, so SET stg then prod: both color rows
+ # stay registered org-wide, making stg a rename collision target for prod.
+ client.post(f"/v1/workflows/{WPID}/tags", json={"tags": [{"key": "env", "value": "stg"}]})
+ client.post(f"/v1/workflows/{WPID}/tags", json={"tags": [{"key": "env", "value": "prod"}]})
+ resp = client.patch("/v1/tag-values/env/rename", json={"value": "prod", "new_value": "stg"})
+ assert resp.status_code == 409
+
+
+def test_rename_tag_value_422_when_same_value(client: TestClient) -> None:
+ client.post(f"/v1/workflows/{WPID}/tags", json={"tags": [{"key": "env", "value": "prod"}]})
+ resp = client.patch("/v1/tag-values/env/rename", json={"value": "prod", "new_value": "prod"})
+ assert resp.status_code == 422
+
+
+def test_rename_tag_value_reserved_prefix_returns_400(client: TestClient) -> None:
+ resp = client.patch("/v1/tag-values/skyvern.system/rename", json={"value": "prod", "new_value": "production"})
+ assert resp.status_code == 400
+
+
+def test_rename_tag_value_handles_value_with_slash(client: TestClient) -> None:
+ client.post(
+ f"/v1/workflows/{WPID}/tags",
+ json={"tags": [{"key": "region", "value": "us/west"}], "colors": {"region": "blue"}},
+ )
+ resp = client.patch("/v1/tag-values/region/rename", json={"value": "us/west", "new_value": "us/east"})
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["value"] == "us/east"
+ assert resp.json()["color"] == "blue"
+
+
+def test_rename_tag_value_legacy_route_works(client: TestClient) -> None:
+ client.post(f"/v1/workflows/{WPID}/tags", json={"tags": [{"key": "env", "value": "prod"}]})
+ resp = client.patch("/api/v1/tag-values/env/rename", json={"value": "prod", "new_value": "production"})
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["renamed_workflow_count"] == 1
+
+
+def _integrity_error() -> IntegrityError:
+ return IntegrityError("INSERT", {}, Exception("duplicate active SET"))
+
+
+def test_rename_tag_value_retries_then_succeeds_on_transient_integrity_error(
+ repo: TagsRepository, client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ client.post(f"/v1/workflows/{WPID}/tags", json={"tags": [{"key": "env", "value": "prod"}]})
+ real_rename = repo.rename_tag_value
+ calls = {"n": 0}
+
+ async def _flaky_rename(*args: Any, **kwargs: Any) -> Any:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise _integrity_error()
+ return await real_rename(*args, **kwargs)
+
+ monkeypatch.setattr(repo, "rename_tag_value", _flaky_rename)
+ resp = client.patch("/v1/tag-values/env/rename", json={"value": "prod", "new_value": "production"})
+ assert resp.status_code == 200, resp.text
+ assert calls["n"] == 2
+
+
+def test_rename_tag_value_409_on_persistent_integrity_error(
+ repo: TagsRepository, client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ client.post(f"/v1/workflows/{WPID}/tags", json={"tags": [{"key": "env", "value": "prod"}]})
+
+ async def _always_conflict(*args: Any, **kwargs: Any) -> Any:
+ raise _integrity_error()
+
+ monkeypatch.setattr(repo, "rename_tag_value", _always_conflict)
+ resp = client.patch("/v1/tag-values/env/rename", json={"value": "prod", "new_value": "production"})
+ assert resp.status_code == 409
+
+
+# ----------------------------- DELETE /tag-values/{key} ----------------------------
+
+
+def test_delete_tag_value_cascades_and_returns_count(client: TestClient) -> None:
+ client.post(
+ f"/v1/workflows/{WPID}/tags",
+ json={"tags": [{"key": "env", "value": "prod"}], "colors": {"env": "blue"}},
+ )
+ resp = client.request("DELETE", "/v1/tag-values/env", json={"value": "prod"})
+ assert resp.status_code == 200, resp.text
+ assert resp.json() == {"key": "env", "value": "prod", "removed_from_workflow_count": 1}
+ # The label is gone from the workflow and from the value registry.
+ assert client.get(f"/v1/workflows/{WPID}/tags").json()["tags"] == []
+ assert client.get("/v1/tag-values").json() == []
+
+
+def test_delete_tag_value_404_when_absent(client: TestClient) -> None:
+ resp = client.request("DELETE", "/v1/tag-values/env", json={"value": "prod"})
+ assert resp.status_code == 404
+
+
+def test_delete_tag_value_reserved_prefix_returns_400(client: TestClient) -> None:
+ resp = client.request("DELETE", "/v1/tag-values/skyvern.system", json={"value": "prod"})
+ assert resp.status_code == 400
+
+
+def test_delete_tag_value_handles_value_with_slash(client: TestClient) -> None:
+ client.post(f"/v1/workflows/{WPID}/tags", json={"tags": [{"key": "region", "value": "us/west"}]})
+ resp = client.request("DELETE", "/v1/tag-values/region", json={"value": "us/west"})
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["removed_from_workflow_count"] == 1
+
+
+def test_delete_tag_value_legacy_route_works(client: TestClient) -> None:
+ client.post(f"/v1/workflows/{WPID}/tags", json={"tags": [{"key": "env", "value": "prod"}]})
+ resp = client.request("DELETE", "/api/v1/tag-values/env", json={"value": "prod"})
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["removed_from_workflow_count"] == 1
diff --git a/tests/unit/test_tags_repository.py b/tests/unit/test_tags_repository.py
index c41f78284..db3d6127c 100644
--- a/tests/unit/test_tags_repository.py
+++ b/tests/unit/test_tags_repository.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from datetime import datetime, timezone
from typing import AsyncGenerator
import pytest
@@ -14,12 +15,14 @@ from skyvern.forge.sdk.db.models import (
Base,
TagKeyModel,
TagValueModel,
+ WorkflowModel,
WorkflowTagEventModel,
)
from skyvern.forge.sdk.db.repositories.tags import (
MAX_TAGS_PER_WORKFLOW,
TagCountLimitExceeded,
TagsRepository,
+ TagValueRenameCollision,
)
from skyvern.forge.sdk.workflow.models.tags import (
CallerType,
@@ -75,6 +78,23 @@ def _ctx(caller_id: str = "user_abc") -> TagWriteContext:
)
+async def _seed_workflow(repo: TagsRepository, wpid: str, *, org_id: str = ORG_ID, deleted: bool = False) -> None:
+ """Insert a WorkflowModel row so the non-deleted-workflow filter on the value
+ counts can resolve a workflow (a tag only exists on a real workflow). Pass
+ ``deleted=True`` to seed a soft-deleted workflow."""
+ async with repo.Session() as session:
+ session.add(
+ WorkflowModel(
+ organization_id=org_id,
+ workflow_permanent_id=wpid,
+ title="t",
+ workflow_definition={},
+ deleted_at=datetime.now(timezone.utc) if deleted else None,
+ )
+ )
+ await session.commit()
+
+
@pytest.mark.asyncio
async def test_no_op_when_sets_and_deletes_empty(repo: TagsRepository) -> None:
changes = await repo.apply_tag_changes(WPID, ORG_ID, sets={}, deletes=set(), context=_ctx())
@@ -453,8 +473,6 @@ async def test_update_tag_key_description_org_scoped(repo: TagsRepository) -> No
@pytest.mark.asyncio
async def test_get_tag_event_history_filters_by_since(repo: TagsRepository) -> None:
"""`since` is inclusive; events earlier than the cutoff are excluded."""
- from datetime import datetime, timezone
-
await repo.apply_tag_changes(WPID, ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
cutoff = datetime.now(timezone.utc)
await repo.apply_tag_changes(WPID, ORG_ID, sets={"env": "stage"}, deletes=set(), context=_ctx())
@@ -810,3 +828,228 @@ async def test_delete_tag_key_soft_deletes_value_colors(repo: TagsRepository) ->
await repo.delete_tag_key(ORG_ID, "env", _ctx())
# The key's color rows must not survive the key delete and keep showing in GET /tag-values.
assert await repo.list_tag_values(ORG_ID) == []
+
+
+# ---------------------- SKY-11336: per-label count, rename, soft-delete ----------------------
+
+
+async def test_count_active_workflows_per_value(repo: TagsRepository) -> None:
+ for wpid in ("wpid_a", "wpid_b", "wpid_c"):
+ await _seed_workflow(repo, wpid)
+ await repo.apply_tag_changes("wpid_a", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
+ await repo.apply_tag_changes("wpid_b", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
+ await repo.apply_tag_changes("wpid_c", ORG_ID, sets={"env": "stg", "team": "core"}, deletes=set(), context=_ctx())
+
+ counts = await repo.count_active_workflows_per_value(ORG_ID)
+ assert counts == {("env", "prod"): 2, ("env", "stg"): 1, ("team", "core"): 1}
+
+
+async def test_count_active_workflows_per_value_excludes_soft_deleted_workflows(repo: TagsRepository) -> None:
+ await _seed_workflow(repo, "wpid_live")
+ await _seed_workflow(repo, "wpid_gone", deleted=True)
+ await repo.apply_tag_changes("wpid_live", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
+ await repo.apply_tag_changes("wpid_gone", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
+
+ # The soft-deleted workflow's lingering SET event must not inflate the count.
+ assert await repo.count_active_workflows_per_value(ORG_ID) == {("env", "prod"): 1}
+ assert await repo.count_active_workflows_for_value(ORG_ID, "env", "prod") == 1
+
+
+async def test_count_active_workflows_per_value_ignores_deleted_and_standalone(repo: TagsRepository) -> None:
+ await repo.apply_tag_changes(
+ "wpid_a", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx(), label_sets=["urgent"]
+ )
+ await repo.apply_tag_changes("wpid_a", ORG_ID, sets={}, deletes={"env"}, context=_ctx())
+ # The deleted grouped tag and the standalone label must not appear in per-value counts.
+ assert await repo.count_active_workflows_per_value(ORG_ID) == {}
+
+
+async def test_count_active_workflows_for_value_targeted(repo: TagsRepository) -> None:
+ for wpid in ("wpid_a", "wpid_b", "wpid_c"):
+ await _seed_workflow(repo, wpid)
+ await repo.apply_tag_changes("wpid_a", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
+ await repo.apply_tag_changes("wpid_b", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
+ await repo.apply_tag_changes("wpid_c", ORG_ID, sets={"env": "stg"}, deletes=set(), context=_ctx())
+
+ assert await repo.count_active_workflows_for_value(ORG_ID, "env", "prod") == 2
+ assert await repo.count_active_workflows_for_value(ORG_ID, "env", "stg") == 1
+ # Unknown pair and other org both count zero.
+ assert await repo.count_active_workflows_for_value(ORG_ID, "env", "dev") == 0
+ assert await repo.count_active_workflows_for_value("o_other", "env", "prod") == 0
+
+
+async def test_rename_tag_value_cascades_and_carries_color(repo: TagsRepository) -> None:
+ await repo.apply_tag_changes(
+ "wpid_a", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx(), colors={"env": "blue"}
+ )
+ await repo.apply_tag_changes(
+ "wpid_b", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx(), colors={"env": "blue"}
+ )
+
+ result = await repo.rename_tag_value(ORG_ID, "env", "prod", "production", _ctx())
+
+ assert result is not None
+ assert (result.key, result.value, result.color) == ("env", "production", "blue")
+ assert result.renamed_workflow_count == 2
+ # Both workflows now carry the new value...
+ assert await repo.get_active_grouped_tags_for_workflow("wpid_a", ORG_ID) == {"env": "production"}
+ assert await repo.get_active_grouped_tags_for_workflow("wpid_b", ORG_ID) == {"env": "production"}
+ # ...the new color row replaces the old one, carrying the color forward.
+ assert [(v.key, v.value, v.color) for v in await repo.list_tag_values(ORG_ID)] == [("env", "production", "blue")]
+
+
+async def test_rename_tag_value_preserves_history(repo: TagsRepository) -> None:
+ """Append-only invariant: the old value's SET event stays in history (superseded),
+ a fresh SET records the new value — past events are never rewritten."""
+ await repo.apply_tag_changes("wpid_a", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
+ await repo.rename_tag_value(ORG_ID, "env", "prod", "production", _ctx())
+
+ history = await repo.get_tag_event_history("wpid_a", ORG_ID)
+ values = [(row.event_type, row.value) for row in history]
+ # Newest-first: the new SET, then the superseded old SET. The old value is preserved.
+ assert values == [(TagEventType.SET.value, "production"), (TagEventType.SET.value, "prod")]
+ assert history[1].superseded_at is not None
+
+
+async def test_rename_tag_value_unknown_returns_none(repo: TagsRepository) -> None:
+ assert await repo.rename_tag_value(ORG_ID, "env", "prod", "production", _ctx()) is None
+
+
+async def test_rename_tag_value_rejects_org_wide_collision(repo: TagsRepository) -> None:
+ await repo.apply_tag_changes("wpid_a", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
+ await repo.apply_tag_changes("wpid_b", ORG_ID, sets={"env": "stg"}, deletes=set(), context=_ctx())
+
+ with pytest.raises(TagValueRenameCollision):
+ await repo.rename_tag_value(ORG_ID, "env", "prod", "stg", _ctx())
+ # The cascade must not have run: prod is untouched.
+ assert await repo.get_active_grouped_tags_for_workflow("wpid_a", ORG_ID) == {"env": "prod"}
+
+
+async def test_rename_tag_value_collision_detects_in_use_value(repo: TagsRepository) -> None:
+ """Collision is org-wide: a target value in use on a workflow (active SET) blocks
+ the rename even when its color row was soft-deleted out of band."""
+ from sqlalchemy import update as _update
+
+ await repo.apply_tag_changes("wpid_a", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
+ await repo.apply_tag_changes("wpid_b", ORG_ID, sets={"env": "stg"}, deletes=set(), context=_ctx())
+ # Drop only the stg color row; the active SET still makes stg exist org-wide.
+ async with repo.Session() as session:
+ await session.execute(
+ _update(TagValueModel)
+ .where(TagValueModel.key == "env", TagValueModel.value == "stg")
+ .values(deleted_at=datetime.now(timezone.utc))
+ )
+ await session.commit()
+
+ with pytest.raises(TagValueRenameCollision):
+ await repo.rename_tag_value(ORG_ID, "env", "prod", "stg", _ctx())
+
+
+async def test_rename_tag_value_reuses_soft_deleted_target(repo: TagsRepository) -> None:
+ """A previously soft-deleted target value is NOT a collision — rename succeeds."""
+ await repo.apply_tag_changes("wpid_a", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
+ await repo.apply_tag_changes("wpid_b", ORG_ID, sets={"env": "stg"}, deletes=set(), context=_ctx())
+ # Remove stg entirely (color row soft-deleted, SET superseded).
+ await repo.delete_tag_value(ORG_ID, "env", "stg", _ctx())
+
+ result = await repo.rename_tag_value(ORG_ID, "env", "prod", "stg", _ctx())
+ assert result is not None
+ assert await repo.get_active_grouped_tags_for_workflow("wpid_a", ORG_ID) == {"env": "stg"}
+
+
+async def test_rename_tag_value_carries_random_color_when_no_color_row(repo: TagsRepository) -> None:
+ """If the source has active SETs but no color row, the rename still registers the
+ new label with a palette color rather than failing."""
+ await repo.apply_tag_changes("wpid_a", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
+ async with repo.Session() as session:
+ from sqlalchemy import update as _update
+
+ await session.execute(
+ _update(TagValueModel)
+ .where(TagValueModel.key == "env", TagValueModel.value == "prod")
+ .values(deleted_at=datetime.now(timezone.utc))
+ )
+ await session.commit()
+
+ result = await repo.rename_tag_value(ORG_ID, "env", "prod", "production", _ctx())
+ assert result is not None
+ assert result.color in TAG_COLOR_PALETTE
+ assert result.renamed_workflow_count == 1
+
+
+async def test_delete_tag_value_cascades_and_counts(repo: TagsRepository) -> None:
+ await repo.apply_tag_changes("wpid_a", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
+ await repo.apply_tag_changes("wpid_b", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
+ await repo.apply_tag_changes("wpid_c", ORG_ID, sets={"env": "stg"}, deletes=set(), context=_ctx())
+
+ removed = await repo.delete_tag_value(ORG_ID, "env", "prod", _ctx())
+
+ assert removed == 2
+ assert await repo.get_active_grouped_tags_for_workflow("wpid_a", ORG_ID) == {}
+ assert await repo.get_active_grouped_tags_for_workflow("wpid_b", ORG_ID) == {}
+ # A sibling value under the same key is untouched.
+ assert await repo.get_active_grouped_tags_for_workflow("wpid_c", ORG_ID) == {"env": "stg"}
+
+
+async def test_delete_tag_value_writes_delete_event_carrying_value(repo: TagsRepository) -> None:
+ await repo.apply_tag_changes("wpid_a", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
+ await repo.delete_tag_value(ORG_ID, "env", "prod", _ctx())
+
+ rows = await _all_events(repo)
+ assert rows[-1].event_type == TagEventType.DELETE.value
+ # Per-value delete records which value was removed (vs the whole-key delete's null value).
+ assert rows[-1].key == "env"
+ assert rows[-1].value == "prod"
+
+
+async def test_delete_tag_value_soft_deletes_only_that_color_row(repo: TagsRepository) -> None:
+ await repo.apply_tag_changes(
+ "wpid_a", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx(), colors={"env": "blue"}
+ )
+ await repo.apply_tag_changes(
+ "wpid_b", ORG_ID, sets={"env": "stg"}, deletes=set(), context=_ctx(), colors={"env": "red"}
+ )
+
+ await repo.delete_tag_value(ORG_ID, "env", "prod", _ctx())
+ # prod's color row is gone; stg's survives.
+ assert [(v.value, v.color) for v in await repo.list_tag_values(ORG_ID)] == [("stg", "red")]
+
+
+async def test_delete_tag_value_unknown_returns_none(repo: TagsRepository) -> None:
+ assert await repo.delete_tag_value(ORG_ID, "env", "prod", _ctx()) is None
+
+
+async def test_delete_tag_value_idempotent(repo: TagsRepository) -> None:
+ await repo.apply_tag_changes("wpid_a", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
+
+ assert await repo.delete_tag_value(ORG_ID, "env", "prod", _ctx()) == 1
+ # Second call: no active SET, no active color row left.
+ assert await repo.delete_tag_value(ORG_ID, "env", "prod", _ctx()) is None
+
+
+async def test_delete_tag_value_then_reapply_reregisters(repo: TagsRepository) -> None:
+ await repo.apply_tag_changes("wpid_a", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx())
+ await repo.delete_tag_value(ORG_ID, "env", "prod", _ctx())
+
+ await repo.apply_tag_changes(
+ "wpid_a", ORG_ID, sets={"env": "prod"}, deletes=set(), context=_ctx(), colors={"env": "green"}
+ )
+ assert await repo.get_active_grouped_tags_for_workflow("wpid_a", ORG_ID) == {"env": "prod"}
+ assert [(v.value, v.color) for v in await repo.list_tag_values(ORG_ID)] == [("prod", "green")]