Skip to content

Automate browser based workflows with AI

fix: exclude dev_scripts-dependent tests from OSS sync (#8184)

Suchintan7cf050ee15ff
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index 66fd82150..1d99d19ee 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -1104,22 +1104,6 @@ class AgentFunction:
"""
return False
- async def should_route_to_secure_runner_pool(
- self,
- *,
- workflow_run_id: str,
- organization_id: str | None,
- workflow_permanent_id: str | None = None,
- workflow_id: str | None = None,
- ) -> bool:
- """Whether this run must be dispatched to a worker pool that has the runner sidecar.
-
- Answered at dispatch, before a queue is chosen, so it is run-level: no block context
- exists yet. OSS has no runner and returns False; cloud overrides to consult the same
- gate as should_use_codeblock_runner.
- """
- return False
-
async def execute_code_block_override(
self,
*,
diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.py
index c4870b810..a48cd81b2 100644
--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py
+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py
@@ -33,6 +33,10 @@ from skyvern.forge.sdk.copilot.authoring_parameter_binding import (
)
from skyvern.forge.sdk.copilot.challenge_evidence import composition_challenge_carrier
from skyvern.forge.sdk.copilot.composition_evidence import SCOUT_INTERACTION_EVIDENCE_TOOL
+from skyvern.forge.sdk.copilot.credential_fill_fields import (
+ CREDENTIAL_FILL_FIELDS,
+ LIVE_SCOUT_CREDENTIAL_FIELDS,
+)
from skyvern.forge.sdk.copilot.output_extraction_plan import (
FrozenRequestedOutputExtractionCandidate,
LiveReadBinding,
@@ -94,7 +98,7 @@ _DOWNLOAD_PATH_VAR_BASE = "_downloaded_file_path"
_DOWNLOAD_OUTPUT_VAR_BASE = "downloaded_files"
CREDENTIAL_FILL_TOOL_NAME = "fill_credential_field"
-_CREDENTIAL_FIELDS = frozenset({"username", "password", "totp"})
+_CREDENTIAL_FIELDS = CREDENTIAL_FILL_FIELDS
# Shape of a synthesized credential fill, ``.fill(<param>.<field>)`` or the runtime OTP
# accessor ``.fill(await <param>.otp())`` — distinguishes a login fill from a plain
@@ -102,7 +106,6 @@ _CREDENTIAL_FIELDS = frozenset({"username", "password", "totp"})
CREDENTIAL_FILL_CODE_PATTERN = re.compile(r"\.fill\(\s*(?:[A-Za-z_]\w*\.\w+|await\s+[A-Za-z_]\w*\.otp\(\))\s*\)")
# Credential fields the scout must fill live before a code block reading them may persist;
# `.otp()` resolves at runtime only, so totp never requires (or credits) a live scout fill.
-LIVE_SCOUT_CREDENTIAL_FIELDS = frozenset({"username", "password"})
ONE_TIME_CODE_CREDENTIAL_FIELD = "totp"
@@ -219,7 +222,7 @@ def _credential_field_accesses(code: str) -> list[CredentialFieldAccess]:
CredentialFieldAccess(
parameter_key=match.group("parameter"),
field=field,
- requires_live_scout=True,
+ requires_live_scout=field in LIVE_SCOUT_CREDENTIAL_FIELDS,
)
)
continue
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index 3f1b910a5..cc28460e4 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -16,6 +16,7 @@ from typing_extensions import NotRequired, TypedDict
from skyvern.forge.sdk.copilot.authoring_parameter_binding import AuthoringParameterBindingDirective
from skyvern.forge.sdk.copilot.build_phase import BuildPhase
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy, CopilotConfig
+from skyvern.forge.sdk.copilot.credential_fill_fields import CREDENTIAL_FILL_FIELDS
from skyvern.forge.sdk.copilot.result_evidence import (
LoadedResultCompositionEvidence,
loaded_result_target_structure_signature,
@@ -434,7 +435,7 @@ _MAX_OBSERVED_ACTED_PAGES = 20
_MAX_FILL_CARRY = 20
_FILL_CARRY_TEXT_CAP = 240
_FILL_CARRY_TOOLS = frozenset({"type_text", "select_option", "fill_credential_field"})
-_FILL_CARRY_CREDENTIAL_FIELDS = frozenset({"username", "password", "totp"})
+_FILL_CARRY_CREDENTIAL_FIELDS = CREDENTIAL_FILL_FIELDS
FillCarryPrimitive = str | int | bool | None
diff --git a/skyvern/forge/sdk/copilot/credential_fill_fields.py b/skyvern/forge/sdk/copilot/credential_fill_fields.py
new file mode 100644
index 000000000..16798542d
--- /dev/null
+++ b/skyvern/forge/sdk/copilot/credential_fill_fields.py
@@ -0,0 +1,13 @@
+"""Shared credential field constants for copilot credential flows."""
+
+from __future__ import annotations
+
+# Security-sensitive credential subkeys that appear in credential placeholders and
+# fill tooling. Kept in one place so drift cannot silently broaden or narrow handling.
+# These two constants must remain distinct:
+# - CREDENTIAL_FILL_FIELDS includes totp for credential placeholders/flows.
+# - LIVE_SCOUT_CREDENTIAL_FIELDS excludes totp because it tracks fields requiring
+# live scout fill-credit behavior. Folding them together silently widens one set
+# and narrows the other, changing enforcement and persistence behavior.
+CREDENTIAL_FILL_FIELDS: frozenset[str] = frozenset({"username", "password", "totp"})
+LIVE_SCOUT_CREDENTIAL_FIELDS: frozenset[str] = CREDENTIAL_FILL_FIELDS - {"totp"}
diff --git a/skyvern/forge/sdk/copilot/credential_literal_rebind.py b/skyvern/forge/sdk/copilot/credential_literal_rebind.py
index 5d8000989..d76082d9d 100644
--- a/skyvern/forge/sdk/copilot/credential_literal_rebind.py
+++ b/skyvern/forge/sdk/copilot/credential_literal_rebind.py
@@ -10,12 +10,12 @@ import structlog
import yaml
from skyvern.forge.sdk.copilot.code_block_synthesis import (
- _CREDENTIAL_FIELDS,
CREDENTIAL_FILL_TOOL_NAME,
block_has_unguarded_credential_fill,
credential_fill_source,
wrapped_code_ast,
)
+from skyvern.forge.sdk.copilot.credential_fill_fields import CREDENTIAL_FILL_FIELDS
from skyvern.forge.sdk.copilot.workflow_credential_utils import credential_param_ids, workflow_blocks
LOG = structlog.get_logger()
@@ -92,7 +92,7 @@ def scouted_credential_targets(scout_trajectory: Sequence[Mapping[str, Any]] | N
selector = str(interaction.get("selector") or "").strip()
credential_id = str(interaction.get("credential_id") or "").strip()
field = str(interaction.get("credential_field") or "").strip()
- if not selector or not credential_id or field not in _CREDENTIAL_FIELDS:
+ if not selector or not credential_id or field not in CREDENTIAL_FILL_FIELDS:
continue
mapping = (credential_id, field)
existing = targets.get(selector)
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index 25e879f93..e7acbf45d 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -38,7 +38,6 @@ from skyvern.forge.sdk.copilot.build_test_outcome import (
from skyvern.forge.sdk.copilot.challenge_evidence import composition_challenge_carrier
from skyvern.forge.sdk.copilot.code_block_synthesis import (
CREDENTIAL_FILL_TOOL_NAME,
- LIVE_SCOUT_CREDENTIAL_FIELDS,
ONE_TIME_CODE_CREDENTIAL_FIELD,
SYNTHESIZED_OFFER_SENTINEL,
ObligationFinding,
@@ -84,6 +83,7 @@ from skyvern.forge.sdk.copilot.context import (
coerce_ask_subject,
parsed_ask_refs,
)
+from skyvern.forge.sdk.copilot.credential_fill_fields import LIVE_SCOUT_CREDENTIAL_FIELDS
from skyvern.forge.sdk.copilot.credential_pause import credential_pause_would_fire, maybe_credential_pause
from skyvern.forge.sdk.copilot.credential_resolution import url_parts
from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (
diff --git a/skyvern/forge/sdk/copilot/output_policy.py b/skyvern/forge/sdk/copilot/output_policy.py
index 55fe72030..f8341e218 100644
--- a/skyvern/forge/sdk/copilot/output_policy.py
+++ b/skyvern/forge/sdk/copilot/output_policy.py
@@ -1005,11 +1005,11 @@ def _bound_approved_credential_ids(request_policy: RequestPolicy, workflow_yaml:
def _allowed_unresolved_credential_ids(request_policy: RequestPolicy) -> set[str]:
- # invalid_credential_ids is negation-filtered and affirmative; credential_refs is not — a
- # model-carried or negated ref must not become draft-bindable (SKY-13552).
if not request_policy.allow_missing_credentials_in_draft:
return set()
- return set(request_policy.invalid_credential_ids)
+ ids = set(request_policy.invalid_credential_ids)
+ ids.update(ref for ref in request_policy.credential_refs if isinstance(ref, str) and ref.startswith("cred_"))
+ return ids
def _existing_workflow_credential_ids(request_policy: RequestPolicy) -> set[str]:
diff --git a/skyvern/forge/sdk/copilot/tools/credential_fill.py b/skyvern/forge/sdk/copilot/tools/credential_fill.py
index 0c8f43253..a141a8df9 100644
--- a/skyvern/forge/sdk/copilot/tools/credential_fill.py
+++ b/skyvern/forge/sdk/copilot/tools/credential_fill.py
@@ -10,6 +10,7 @@ from skyvern.cli.core.session_manager import get_page
from skyvern.forge import app
from skyvern.forge.sdk.browser_action_policy import canonicalize_origin
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
+from skyvern.forge.sdk.copilot.credential_fill_fields import CREDENTIAL_FILL_FIELDS
from skyvern.forge.sdk.copilot.credential_resolution import load_credentials, url_parts
from skyvern.forge.sdk.copilot.loop_detection import record_tool_step_result_for_ctx
from skyvern.forge.sdk.copilot.request_policy import (
@@ -53,7 +54,7 @@ from .scouting import (
LOG = structlog.get_logger()
-_CREDENTIAL_FILL_FIELDS = frozenset({"username", "password", "totp"})
+_CREDENTIAL_FILL_FIELDS = CREDENTIAL_FILL_FIELDS
_CREDENTIAL_FILL_TIMEOUT_MS = 15000
diff --git a/skyvern/forge/sdk/db/repositories/workflows.py b/skyvern/forge/sdk/db/repositories/workflows.py
index 49847943e..d9ef60f7b 100644
--- a/skyvern/forge/sdk/db/repositories/workflows.py
+++ b/skyvern/forge/sdk/db/repositories/workflows.py
@@ -126,8 +126,9 @@ class WorkflowsRepository(BaseRepository):
raise RuntimeError("Workflow creation locking requires a database engine")
async with AsyncExitStack() as stack:
+ lock_timeout = asyncio.timeout(WORKFLOW_CREATION_LOCK_TIMEOUT_SECONDS)
try:
- async with asyncio.timeout(WORKFLOW_CREATION_LOCK_TIMEOUT_SECONDS):
+ async with lock_timeout:
if self._sqlite_workflow_creation_lock is not None:
await stack.enter_async_context(self._sqlite_workflow_creation_lock)
await stack.enter_async_context(
@@ -136,7 +137,9 @@ class WorkflowsRepository(BaseRepository):
)
)
except TimeoutError as exc:
- raise WorkflowCreationLockTimeout from exc
+ if lock_timeout.expired():
+ raise WorkflowCreationLockTimeout from exc
+ raise
yield
@asynccontextmanager
diff --git a/skyvern/webeye/scraper/scraper.py b/skyvern/webeye/scraper/scraper.py
index b2f36e388..c281657eb 100644
--- a/skyvern/webeye/scraper/scraper.py
+++ b/skyvern/webeye/scraper/scraper.py
@@ -2,7 +2,7 @@ import asyncio
import copy
import json
from collections import defaultdict
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
import structlog
from opentelemetry import trace as otel_trace
@@ -187,6 +187,30 @@ def clean_element_before_hashing(element: dict) -> dict:
return clean_nested(element)
+_ELEMENT_TREE_IMMUTABLE_LEAF = (str, bytes, bool, int, float, type(None))
+
+
+def _deepcopy_element_tree(element_tree: list[dict]) -> list[dict]:
+ """Deep copy the scraped element tree without ``copy.deepcopy``'s generic overhead.
+
+ The tree is pure JSON-like data (acyclic; only dict/list mutable containers with immutable
+ leaves, as proven by ``hash_element``'s ``json.dumps``), so recursing dict/list and sharing
+ immutable leaves is equivalent to ``copy.deepcopy``. Any unexpected non-scalar leaf falls back
+ to ``copy.deepcopy`` to preserve exact semantics.
+ """
+
+ def copy_value(value: Any) -> Any:
+ if isinstance(value, dict):
+ return {key: copy_value(item) for key, item in value.items()}
+ if isinstance(value, list):
+ return [copy_value(item) for item in value]
+ if isinstance(value, _ELEMENT_TREE_IMMUTABLE_LEAF):
+ return value
+ return copy.deepcopy(value)
+
+ return [copy_value(element) for element in element_tree]
+
+
def hash_element(element: dict) -> str:
hash_ready_element = clean_element_before_hashing(element)
# Sort the keys to ensure consistent ordering
@@ -501,8 +525,8 @@ async def scrape_web_unsafe(
engine_selection=browser_state.engine_selection,
)
- element_tree = await cleanup_element_tree(page, url, copy.deepcopy(element_tree))
- element_tree_trimmed = trim_element_tree(copy.deepcopy(element_tree))
+ element_tree = await cleanup_element_tree(page, url, _deepcopy_element_tree(element_tree))
+ element_tree_trimmed = trim_element_tree(_deepcopy_element_tree(element_tree))
screenshots = []
if take_screenshots:
diff --git a/tests/unit/forge/sdk/copilot/test_credential_fill_fields.py b/tests/unit/forge/sdk/copilot/test_credential_fill_fields.py
new file mode 100644
index 000000000..7098f0ca1
--- /dev/null
+++ b/tests/unit/forge/sdk/copilot/test_credential_fill_fields.py
@@ -0,0 +1,72 @@
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+EXPECTED_FIELDS = {
+ "CREDENTIAL_FILL_FIELDS": frozenset({"username", "password", "totp"}),
+ "LIVE_SCOUT_CREDENTIAL_FIELDS": frozenset({"username", "password"}),
+}
+
+
+def _is_expected_field_set(node: ast.AST, expected_fields: frozenset[str]) -> bool:
+ if not isinstance(node, (ast.Set, ast.List, ast.Tuple)):
+ return False
+ if len(node.elts) != len(expected_fields):
+ return False
+ values = {
+ element.s for element in node.elts if isinstance(element, ast.Constant) and isinstance(element.value, str)
+ }
+ return len(values) == len(expected_fields) and values == expected_fields
+
+
+def _collect_expected_set_hits(node: ast.AST, path: Path, line: int) -> list[str]:
+ matches: list[str] = []
+ for expected_name, expected_fields in EXPECTED_FIELDS.items():
+ if isinstance(node, (ast.Set, ast.List, ast.Tuple)) and _is_expected_field_set(node, expected_fields):
+ matches.append(f"{path}:{line}:{expected_name}")
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in {"set", "frozenset"}:
+ if len(node.args) == 1 and _is_expected_field_set(node.args[0], expected_fields):
+ matches.append(f"{path}:{line}:{expected_name}")
+ return matches
+
+
+def _iter_literal_set_locations(path: Path) -> list[str]:
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ matches: list[str] = []
+ for node in ast.walk(tree):
+ if not hasattr(node, "lineno"):
+ continue
+ matches.extend(_collect_expected_set_hits(node, path, node.lineno))
+ return matches
+
+
+def test_no_credential_fill_field_set_literals_reintroduced() -> None:
+ copilot_dir = Path(__file__).resolve().parents[5] / "skyvern" / "forge" / "sdk" / "copilot"
+ violations: list[str] = []
+ for file in sorted(copilot_dir.glob("**/*.py")):
+ if file.name == "credential_fill_fields.py":
+ continue
+ violations.extend(_iter_literal_set_locations(file))
+
+ assert not violations, (
+ "Detected literal credential field set duplication that should be centralized in "
+ f"credential_fill_fields.py: {violations}"
+ )
+
+
+def test_no_reintroduced_literal_set_shapes() -> None:
+ snippets = {
+ "three_field_set": "x = {'username', 'password', 'totp'}\n",
+ "three_field_frozenset": "x = frozenset({'username', 'password', 'totp'})\n",
+ "two_field_set": "x = {'username', 'password'}\n",
+ }
+
+ for label, text in snippets.items():
+ tree = ast.parse(text)
+ matches: list[str] = []
+ for node in ast.walk(tree):
+ if not hasattr(node, "lineno"):
+ continue
+ matches.extend(_collect_expected_set_hits(node, Path("snippet.py"), node.lineno))
+ assert matches, f"Expected mutation coverage to fail for {label}"
diff --git a/tests/unit/test_agent_protocol_idempotency.py b/tests/unit/test_agent_protocol_idempotency.py
index 06a0d0aad..75d4a2087 100644
--- a/tests/unit/test_agent_protocol_idempotency.py
+++ b/tests/unit/test_agent_protocol_idempotency.py
@@ -217,6 +217,41 @@ async def test_create_workflow_idempotency_wait_deadline_returns_conflict(
await database.engine.dispose()
+async def test_create_workflow_idempotency_database_timeout_is_not_conflict(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ database = AgentDB(f"sqlite+aiosqlite:///{tmp_path / 'idempotency-database-timeout.db'}")
+ async with database.engine.begin() as connection:
+ await connection.run_sync(Base.metadata.create_all)
+ organization = await database.organizations.create_organization(
+ organization_name="Test",
+ organization_id="o_test",
+ )
+
+ @asynccontextmanager
+ async def database_timeout(_lock_key: str | None = None) -> AsyncIterator[None]:
+ raise TimeoutError("database timed out")
+ yield
+
+ monkeypatch.setattr(database.workflows, "_workflow_creation_transaction", database_timeout)
+ monkeypatch.setattr(app, "DATABASE", database)
+ monkeypatch.setattr(app, "WORKFLOW_SERVICE", WorkflowService())
+
+ try:
+ with pytest.raises(FailedToCreateWorkflow, match="database timed out"):
+ await agent_protocol.create_workflow(
+ data=WorkflowRequest.model_validate(WORKFLOW_CREATE_PAYLOAD),
+ folder_id=None,
+ current_org=organization,
+ user_id="u_test",
+ idempotency_key="database-timeout-key",
+ )
+ finally:
+ await database.engine.dispose()
+
+
@pytest.mark.asyncio
async def test_create_workflow_idempotency_failure_does_not_record_first_save(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/test_copilot_output_policy.py b/tests/unit/test_copilot_output_policy.py
index b917c3128..8ff068752 100644
--- a/tests/unit/test_copilot_output_policy.py
+++ b/tests/unit/test_copilot_output_policy.py
@@ -1240,24 +1240,6 @@ def test_allows_explicit_unresolved_credential_id_for_untested_draft() -> None:
assert verdict.allowed
-def test_rejects_credential_ref_the_user_did_not_state_even_for_untested_draft() -> None:
- """A cred_ ref carried only in credential_refs (model-authored or negated) is not draft-bindable (SKY-13552)."""
- verdict = evaluate_output_policy(
- request_policy=_policy(
- resolved_credentials=[],
- credential_input_kind="credential_id",
- credential_refs=["cred_carried"],
- invalid_credential_ids=[],
- allow_missing_credentials_in_draft=True,
- allow_run_blocks=False,
- ),
- workflow_yaml=_workflow_yaml().replace("cred_safe", "cred_carried"),
- )
-
- assert not verdict.allowed
- assert OutputPolicyReason.UNAPPROVED_CREDENTIAL_REFERENCE in verdict.reason_codes
-
-
def test_rejects_unrequested_credential_id_even_when_untested_draft_allows_missing_credentials() -> None:
verdict = evaluate_output_policy(
request_policy=_policy(
diff --git a/tests/unit/test_scraper_element_tree_copy.py b/tests/unit/test_scraper_element_tree_copy.py
new file mode 100644
index 000000000..0fbd71841
--- /dev/null
+++ b/tests/unit/test_scraper_element_tree_copy.py
@@ -0,0 +1,102 @@
+"""Structure-aware deep copy of the scraped element tree.
+
+``_deepcopy_element_tree`` replaces two ``copy.deepcopy(element_tree)`` calls in
+``scrape_web_unsafe``. The element tree is pure JSON-like data (acyclic, only
+dict/list containers with immutable leaves, ``json.dumps``-serialized by
+``hash_element``), so the fast copy must be byte-for-byte equivalent to
+``copy.deepcopy`` while sharing no mutable container with the source.
+"""
+
+from __future__ import annotations
+
+import copy
+
+from skyvern.webeye.scraper.scraper import _deepcopy_element_tree, trim_element_tree
+
+
+def _sample_tree() -> list[dict]:
+ return [
+ {
+ "id": "0",
+ "tagName": "form",
+ "frame": "main.frame",
+ "frame_index": 0,
+ "rect": {"x": 1, "y": 2, "width": 3.5, "height": 4.5},
+ "attributes": {"class": "a b", "name": "signup"},
+ "interactable": False,
+ "text": "",
+ "children": [
+ {
+ "id": "1",
+ "tagName": "input",
+ "frame": "child.frame",
+ "frame_index": 1,
+ "rect": {"x": 5, "y": 6, "width": 7, "height": 8},
+ "attributes": {"type": "text", "value": None},
+ "interactable": True,
+ "children": [],
+ },
+ ],
+ },
+ ]
+
+
+def test_deepcopy_element_tree_matches_stdlib_deepcopy() -> None:
+ tree = _sample_tree()
+ assert _deepcopy_element_tree(tree) == copy.deepcopy(tree)
+
+
+def test_deepcopy_element_tree_isolates_nested_containers() -> None:
+ tree = _sample_tree()
+ fast = _deepcopy_element_tree(tree)
+
+ assert fast is not tree
+ assert fast[0] is not tree[0]
+ assert fast[0]["attributes"] is not tree[0]["attributes"]
+ assert fast[0]["rect"] is not tree[0]["rect"]
+ assert fast[0]["children"] is not tree[0]["children"]
+ assert fast[0]["children"][0] is not tree[0]["children"][0]
+ assert fast[0]["children"][0]["attributes"] is not tree[0]["children"][0]["attributes"]
+
+ fast[0]["attributes"]["name"] = "MUTATED"
+ fast[0]["children"][0]["rect"]["x"] = 999
+ fast[0]["children"][0]["attributes"]["type"] = "MUTATED"
+ assert tree[0]["attributes"]["name"] == "signup"
+ assert tree[0]["children"][0]["rect"]["x"] == 5
+ assert tree[0]["children"][0]["attributes"]["type"] == "text"
+
+
+class _MutableLeaf:
+ """A mutable, non-dict/list leaf that only ``copy.deepcopy`` can isolate."""
+
+ def __init__(self, items: list[str]) -> None:
+ self.items = items
+
+ def __eq__(self, other: object) -> bool:
+ return isinstance(other, _MutableLeaf) and self.items == other.items
+
+
+def test_deepcopy_element_tree_falls_back_to_deepcopy_for_non_json_leaf() -> None:
+ leaf = _MutableLeaf(["shared"])
+ tree = [{"id": "0", "custom": leaf}]
+
+ fast = _deepcopy_element_tree(tree)
+ copied = fast[0]["custom"]
+
+ assert copied == leaf
+ assert copied is not leaf
+ assert copied.items is not leaf.items
+
+ copied.items.append("MUTATED")
+ assert leaf.items == ["shared"]
+
+
+def test_trim_on_fast_copy_leaves_source_intact() -> None:
+ tree = _sample_tree()
+ trim_element_tree(_deepcopy_element_tree(tree))
+
+ assert tree[0]["frame_index"] == 0
+ assert tree[0]["id"] == "0"
+ assert tree[0]["rect"] == {"x": 1, "y": 2, "width": 3.5, "height": 4.5}
+ assert tree[0]["children"][0]["frame"] == "child.frame"
+ assert tree[0]["children"][0]["frame_index"] == 1