Skip to content

Automate browser based workflows with AI

Drop error-code entries that render unusable, matching the guard CodeBlock already applies (#8448)

pedrohsdbc348877af220
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index 348881ff6..f4501b7a0 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -7405,20 +7405,30 @@ class ForgeAgent:
# exclusion come from the post-claim row, never the entry read: a worker can
# stamp started_at between the two, and the stale read would bill that
# compute as never_started.
- if updated_task.workflow_run_id is None and finish_claimed:
- if updated_task.started_at and updated_task.finished_at:
- await app.AGENT_FUNCTION.record_run_duration(
- run_type="task_v1",
- status=str(status),
- duration_seconds=(updated_task.finished_at - updated_task.started_at).total_seconds(),
- )
- else:
- # Never started: no compute, but export the exclusion.
- await app.AGENT_FUNCTION.record_run_duration(
- run_type="task_v1",
- status=str(status),
- duration_seconds=0.0,
- excluded_reason="never_started",
+ if updated_task.workflow_run_id is None:
+ if finish_claimed:
+ if updated_task.started_at and updated_task.finished_at:
+ await app.AGENT_FUNCTION.record_run_duration(
+ run_type="task_v1",
+ status=str(status),
+ duration_seconds=(updated_task.finished_at - updated_task.started_at).total_seconds(),
+ )
+ else:
+ # Never started: no compute, but export the exclusion.
+ await app.AGENT_FUNCTION.record_run_duration(
+ run_type="task_v1",
+ status=str(status),
+ duration_seconds=0.0,
+ excluded_reason="never_started",
+ )
+ # Keyed on the persisted status, not finish_claimed: a sweep can claim the finish with
+ # timed_out before the agent's completed write lands, and the org-level milestone claim
+ # inside the hook is what makes repeats a no-op.
+ if updated_task.status == TaskStatus.completed:
+ await app.AGENT_FUNCTION.on_task_completed(
+ organization_id=updated_task.organization_id,
+ task_id=updated_task.task_id,
+ status=updated_task.status,
)
return updated_task
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index 5f93709ca..3de12499c 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -2685,6 +2685,20 @@ class AgentFunction:
"""Fired after a workflow run reaches a final status. The run may be supplied to avoid a fallback read."""
return None
+ async def on_task_completed(
+ self,
+ *,
+ organization_id: str,
+ task_id: str,
+ status: TaskStatus,
+ ) -> None:
+ """Fired after a top-level (non-workflow) task is persisted as completed.
+
+ Not exactly-once: concurrent finalizers can both observe the completed row, so overrides
+ must be idempotent and must never raise.
+ """
+ return None
+
async def on_credential_saved(
self,
*,
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 78afd74f1..a8b47f0af 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -245,7 +245,9 @@ from skyvern.schemas.workflows import (
_direct_code_block_error_code_raises,
_normalize_optional_endpoint_url,
_validate_code_block_error_code_calls,
- _validate_code_block_error_code_mapping,
+ error_code_key_error,
+ error_code_mapping_entry_error,
+ normalize_error_code_description,
)
from skyvern.services import otp_email, otp_service, planner_levers
from skyvern.services.error_detection_service import detect_user_defined_errors_for_task
@@ -253,6 +255,7 @@ from skyvern.services.self_heal_cap import check_and_increment_self_heal_cap
from skyvern.utils.contained_effects import contained_effect
from skyvern.utils.parquet_export import ParquetExportError, export_parquet_records
from skyvern.utils.prompt_engine import PROMPT_HARD_CEILING_TOKENS
+from skyvern.utils.secret_redaction import MIN_NUMERIC_SECRET_LENGTH, MIN_SECRET_LENGTH
from skyvern.utils.strings import generate_random_string
from skyvern.utils.templating import get_available_keys, get_missing_variables
from skyvern.utils.token_counter import count_tokens, decode_tokens, encode_tokens
@@ -834,14 +837,120 @@ class Block(BaseModel, abc.ABC):
@classmethod
def _contains_registered_secret(cls, value: str, workflow_run_context: WorkflowRunContext) -> bool:
+ """Whether `value` carries a registered secret, at ANY length.
+
+ Deliberately unfloored: the code-escalation path uses this to refuse an error code that would
+ carry a secret into generated code and into persisted failure artifacts, where catching a
+ short embedded credential matters more than the odd false positive. Callers that DELETE
+ ordinary customer data on a hit want the floored form -- see _contains_registered_secret_floored.
+ """
return any(secret in value for secret in cls._registered_secret_values(workflow_run_context))
+ @classmethod
+ def _contains_registered_secret_floored(cls, value: str, workflow_run_context: WorkflowRunContext) -> bool:
+ """The same test with the redaction stack's own length floors applied.
+
+ For callers that DELETE on a hit. Unfloored, a two-character secret such as a card expiry
+ makes HTTP_405_DECLINED look secret-bearing and removes a legitimate error code -- a guard
+ destroying the output it exists to protect.
+ """
+ return any(
+ secret in value
+ for secret in cls._registered_secret_values(workflow_run_context)
+ if len(secret) >= MIN_SECRET_LENGTH and not (secret.isdigit() and len(secret) < MIN_NUMERIC_SECRET_LENGTH)
+ )
+
@classmethod
def _redact_registered_secrets(cls, value: str, workflow_run_context: WorkflowRunContext) -> str:
for secret in sorted(cls._registered_secret_values(workflow_run_context), key=len, reverse=True):
value = value.replace(secret, "[redacted]")
return value
+ def _render_error_code_mapping(
+ self,
+ block_mapping: dict[str, str] | None,
+ workflow_mapping: dict[str, str] | None,
+ workflow_run_context: WorkflowRunContext,
+ *,
+ for_generated_code: bool,
+ ) -> dict[str, str] | None:
+ """Render a block's error_code_mapping, inheriting the workflow's, and repair what it can.
+
+ The MERGE ORDER is part of what the two callers must agree on, so it lives here rather than
+ with each of them. Block entries are offered FIRST: a colliding key keeps the block's value
+ (the documented block-over-workflow precedence), and when the aggregate cap binds it is the
+ workflow's entries that are dropped rather than the block's own.
+
+ error_code_mapping is templatable, so the author-time schema validates a string that is not
+ yet the string the model will see. A rendered KEY that is unusable means the entry goes -- it
+ is the identifier the model names and the customer matches on, and it cannot be repaired. A
+ rendered DESCRIPTION is prose and IS repairable, so it is normalized, not dropped: deleting an
+ entry over a trailing newline removes a customer's error code, and if it was the only entry
+ the mapping goes falsy and error detection is skipped entirely.
+ """
+ ordered: list[tuple[str, str]] = list((block_mapping or {}).items())
+ seen_source_keys = {code for code, _ in ordered}
+ ordered += [(code, text) for code, text in (workflow_mapping or {}).items() if code not in seen_source_keys]
+
+ rendered_mapping: dict[str, str] = {}
+ rendered_mapping_utf8_bytes = 0
+ dropped_reasons: list[str] = []
+ for error_code, error_description in ordered:
+ rendered_code = self.render_templatable_field("error_code_mapping", error_code, workflow_run_context)
+ if rendered_code in rendered_mapping:
+ # Block entries come first, so an earlier occupant is the one precedence keeps.
+ continue
+ rendered_description = self.render_templatable_field(
+ "error_code_mapping", error_description, workflow_run_context
+ )
+ rendered_description = self._redact_registered_secrets(rendered_description, workflow_run_context)
+ secret_bearing_key = (
+ self._contains_registered_secret(rendered_code, workflow_run_context)
+ if for_generated_code
+ else self._contains_registered_secret_floored(rendered_code, workflow_run_context)
+ )
+ if secret_bearing_key or workflow_run_context.mask_secrets_in_data(rendered_code) != rendered_code:
+ dropped_reasons.append("error code keys must not contain a registered secret")
+ continue
+ key_reason = error_code_key_error(rendered_code)
+ if key_reason:
+ # The reason, not the code: the key is customer-authored text and this log is not
+ # covered by the run-secret scrub (SKY-15586 F2, pre-existing).
+ dropped_reasons.append(key_reason)
+ continue
+ if not for_generated_code:
+ normalized_description = normalize_error_code_description(rendered_description)
+ if normalized_description is None:
+ dropped_reasons.append("error code descriptions must contain something after normalization")
+ continue
+ else:
+ description_reason = error_code_mapping_entry_error(rendered_code, rendered_description)
+ if description_reason:
+ dropped_reasons.append(description_reason)
+ continue
+ normalized_description = rendered_description
+ rendered_entry_utf8_bytes = len(rendered_code.encode("utf-8")) + len(normalized_description.encode("utf-8"))
+ candidate_utf8_bytes = rendered_mapping_utf8_bytes + rendered_entry_utf8_bytes
+ if (
+ len(rendered_mapping) + 1 > ERROR_CODE_MAPPING_MAX_ENTRIES
+ or candidate_utf8_bytes > ERROR_CODE_MAPPING_MAX_UTF8_BYTES
+ ):
+ # Per-entry rules bound one string; only a running total bounds what rendering can
+ # expand a whole mapping into, and this mapping is JSON-dumped into the prompt.
+ dropped_reasons.append("error_code_mapping exceeded its aggregate entry or byte cap")
+ continue
+ rendered_mapping[rendered_code] = normalized_description
+ rendered_mapping_utf8_bytes = candidate_utf8_bytes
+ if dropped_reasons:
+ LOG.warning(
+ "error_code_mapping entries dropped after template rendering",
+ block_label=self.label,
+ dropped=len(dropped_reasons),
+ kept=len(rendered_mapping),
+ reasons=sorted(set(dropped_reasons)),
+ )
+ return rendered_mapping or None
+
def _own_llm_key(self) -> str | None:
return None
@@ -1697,14 +1806,12 @@ class BaseTaskBlock(Block):
workflow_error_code_mapping = workflow.workflow_definition.error_code_mapping
if workflow_error_code_mapping or self.error_code_mapping:
- merged_mapping = dict(workflow_error_code_mapping or {})
- merged_mapping.update(self.error_code_mapping or {})
- self.error_code_mapping = {
- self.render_templatable_field("error_code_mapping", error_code, workflow_run_context): (
- self.render_templatable_field("error_code_mapping", error_description, workflow_run_context)
- )
- for error_code, error_description in merged_mapping.items()
- }
+ self.error_code_mapping = self._render_error_code_mapping(
+ self.error_code_mapping,
+ workflow_error_code_mapping,
+ workflow_run_context,
+ for_generated_code=False,
+ )
# Materialize the workflow-level workflow_system_prompt onto this block so
# ForgeAgent.create_task can hand it off to the Task row verbatim.
@@ -5241,44 +5348,12 @@ async def wrapper({default_args}):
if isinstance(definition, dict)
else getattr(definition, "error_code_mapping", None)
)
- merged_mapping = dict(workflow_mapping or {})
- merged_mapping.update(self.error_code_mapping or {})
- rendered_mapping: dict[str, str] = {}
- rendered_mapping_utf8_bytes = 0
- for error_code, error_description in merged_mapping.items():
- rendered_code = self.render_templatable_field("error_code_mapping", error_code, workflow_run_context)
- rendered_description = self.render_templatable_field(
- "error_code_mapping", error_description, workflow_run_context
- )
- rendered_description = self._redact_registered_secrets(rendered_description, workflow_run_context)
- if (
- self._contains_registered_secret(rendered_code, workflow_run_context)
- or workflow_run_context.mask_secrets_in_data(rendered_code) != rendered_code
- ):
- continue
- try:
- _validate_code_block_error_code_mapping({rendered_code: rendered_description})
- except ValueError:
- continue
- rendered_entry_utf8_bytes = len(rendered_code.encode("utf-8")) + len(rendered_description.encode("utf-8"))
- previous_description = rendered_mapping.get(rendered_code)
- previous_entry_utf8_bytes = (
- len(rendered_code.encode("utf-8")) + len(previous_description.encode("utf-8"))
- if previous_description is not None
- else 0
- )
- candidate_entry_count = len(rendered_mapping) + (previous_description is None)
- candidate_utf8_bytes = rendered_mapping_utf8_bytes - previous_entry_utf8_bytes + rendered_entry_utf8_bytes
- # Aggregate caps mirror ERROR_CODE_MAPPING_MAX_ENTRIES and
- # ERROR_CODE_MAPPING_MAX_UTF8_BYTES; all per-entry rules stay in the shared validator.
- if (
- candidate_entry_count > ERROR_CODE_MAPPING_MAX_ENTRIES
- or candidate_utf8_bytes > ERROR_CODE_MAPPING_MAX_UTF8_BYTES
- ):
- continue
- rendered_mapping[rendered_code] = rendered_description
- rendered_mapping_utf8_bytes = candidate_utf8_bytes
- self.error_code_mapping = rendered_mapping or None
+ self.error_code_mapping = self._render_error_code_mapping(
+ self.error_code_mapping,
+ workflow_mapping,
+ workflow_run_context,
+ for_generated_code=True,
+ )
async def _claim_session_download_artifacts(
self,
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index 39db59780..8b255d449 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -228,6 +228,8 @@ from skyvern.schemas.runs import (
from skyvern.schemas.scripts import Script, ScriptBlock, ScriptFallbackEpisode, ScriptStatus, WorkflowScript
from skyvern.schemas.workflows import (
BLOCK_YAML_TYPES,
+ ERROR_CODE_MAX_LENGTH,
+ ERROR_CODE_REASONING_MAX_LENGTH,
BlockResult,
BlockStatus,
BlockType,
@@ -323,11 +325,11 @@ def _strict_user_defined_error_payload(value: Any) -> dict[str, Any] | None:
type(value["error_code"]) is not str
or not value["error_code"]
or value["error_code"] != value["error_code"].strip()
- or len(value["error_code"]) > 128
+ or len(value["error_code"]) > ERROR_CODE_MAX_LENGTH
or type(value["reasoning"]) is not str
or not value["reasoning"]
or value["reasoning"] != value["reasoning"].strip()
- or len(value["reasoning"]) > 2000
+ or len(value["reasoning"]) > ERROR_CODE_REASONING_MAX_LENGTH
or type(value["confidence_float"]) is not float
or not 0 <= value["confidence_float"] <= 1
or type(value["error_type"]) is not str
diff --git a/skyvern/schemas/workflows.py b/skyvern/schemas/workflows.py
index 1eafbed1a..96dde2f41 100644
--- a/skyvern/schemas/workflows.py
+++ b/skyvern/schemas/workflows.py
@@ -919,6 +919,62 @@ def _contains_unicode_category_c(value: str) -> bool:
return any(unicodedata.category(character).startswith("C") for character in value)
+def error_code_key_error(code: Any) -> str | None:
+ """Whether a key is unusable, as a reason string.
+
+ Split out from the whole-entry check because a key and a description fail differently. A key IS
+ the identifier the model names and the customer matches on, so an unusable one cannot be repaired
+ and the entry has to go. A description is prose; see normalize_error_code_description.
+ """
+ if type(code) is not str or not code or code != code.strip() or len(code) > ERROR_CODE_MAX_LENGTH:
+ return "error code keys must be trimmed, non-empty strings of at most 128 characters"
+ if _contains_unicode_category_c(code):
+ return "error code keys must not contain Unicode category-C characters"
+ return None
+
+
+def normalize_error_code_description(description: Any) -> str | None:
+ """Make a rendered description usable, or None if there is nothing to salvage.
+
+ Repair rather than reject. These rules were written where the mapping feeds generated code; on a
+ task block the description is prose shown to a model, and prose legitimately carries newlines and
+ surrounding whitespace. Dropping the entry over that deletes a customer's error code -- and if it
+ was the only entry the mapping goes falsy, which turns error detection off silently. Measured on
+ production: 3,691 tasks in a week carry an untrimmed description and 90 would lose every entry.
+ """
+ if type(description) is not str:
+ return None
+ collapsed = "".join(
+ " " if unicodedata.category(character).startswith("C") else character for character in description
+ )
+ collapsed = collapsed.strip()
+ if not collapsed:
+ return None
+ return collapsed[:ERROR_CODE_REASONING_MAX_LENGTH]
+
+
+def error_code_mapping_entry_error(code: Any, description: Any) -> str | None:
+ """The per-entry rules, as a reason string rather than an exception.
+
+ Two callers need the same rules with opposite dispositions: the code-block schema rejects the
+ whole mapping at author time, while the runtime render path drops the offending entry. Both read
+ from here so a rule cannot be enforced in one place and quietly not the other.
+ """
+ key_reason = error_code_key_error(code)
+ if key_reason:
+ return key_reason
+ if (
+ type(description) is not str
+ or not description
+ or description != description.strip()
+ or len(description) > ERROR_CODE_REASONING_MAX_LENGTH
+ ):
+ return "error code descriptions must be trimmed, non-empty strings of at most 2000 characters"
+ if _contains_unicode_category_c(description):
+ return "error code descriptions must not contain Unicode category-C characters"
+ return None
+
+
def _validate_code_block_error_code_mapping(mapping: Any) -> None:
if mapping is None:
return
@@ -928,19 +984,9 @@ def _validate_code_block_error_code_mapping(mapping: Any) -> None:
raise ValueError("error_code_mapping must contain at most 64 entries")
aggregate_size = 0
for code, description in mapping.items():
- if type(code) is not str or not code or code != code.strip() or len(code) > ERROR_CODE_MAX_LENGTH:
- raise ValueError("error code keys must be trimmed, non-empty strings of at most 128 characters")
- if _contains_unicode_category_c(code):
- raise ValueError("error code keys must not contain Unicode category-C characters")
- if (
- type(description) is not str
- or not description
- or description != description.strip()
- or len(description) > ERROR_CODE_REASONING_MAX_LENGTH
- ):
- raise ValueError("error code descriptions must be trimmed, non-empty strings of at most 2000 characters")
- if _contains_unicode_category_c(description):
- raise ValueError("error code descriptions must not contain Unicode category-C characters")
+ reason = error_code_mapping_entry_error(code, description)
+ if reason:
+ raise ValueError(reason)
aggregate_size += len(code.encode("utf-8")) + len(description.encode("utf-8"))
if aggregate_size > ERROR_CODE_MAPPING_MAX_UTF8_BYTES:
raise ValueError("error_code_mapping keys and values must total at most 32768 UTF-8 bytes")
diff --git a/tests/unit/test_task_request_validation.py b/tests/unit/test_task_request_validation.py
index 3f6ba162a..eb6d34480 100644
--- a/tests/unit/test_task_request_validation.py
+++ b/tests/unit/test_task_request_validation.py
@@ -487,3 +487,17 @@ def test_workflow_request_body_allows_profile_or_start_fresh_alone() -> None:
WorkflowRequestBody(browser_profile_id="bp_1")
WorkflowRequestBody(start_fresh_browser=True)
+
+
+def test_task_models_still_hydrate_a_legacy_error_code_mapping() -> None:
+ # Deliberately permissive, and this is the reason: error_code_mapping lives on TaskBase, which
+ # Task (the DB-hydrated model) shares with TaskRequest, and run_service rebuilds a TaskRunRequest
+ # from a stored task on the read path. Rejecting a loose mapping at the schema would not reject
+ # an inbound request -- it would fail to LOAD historical rows. The strictness belongs at the
+ # render boundary instead (test_workflow_error_code_mapping_inheritance.py).
+ from skyvern.forge.sdk.schemas.tasks import TaskRequest
+ from skyvern.schemas.runs import TaskRunRequest
+
+ legacy = {"legacy_code": "", " padded ": "d", "x" * 200: "d"}
+ assert TaskRequest(url="https://example.com", error_code_mapping=legacy).error_code_mapping == legacy
+ assert TaskRunRequest(prompt="go", error_code_mapping=legacy).error_code_mapping == legacy
diff --git a/tests/unit/test_workflow_error_code_mapping_inheritance.py b/tests/unit/test_workflow_error_code_mapping_inheritance.py
index fd0c4d365..60ced46b3 100644
--- a/tests/unit/test_workflow_error_code_mapping_inheritance.py
+++ b/tests/unit/test_workflow_error_code_mapping_inheritance.py
@@ -107,6 +107,132 @@ class TestWorkflowLevelErrorCodeMappingInheritance:
assert block.error_code_mapping is None
+ def test_entry_whose_key_renders_empty_is_dropped_not_persisted(self) -> None:
+ # error_code_mapping is templatable, so the author-time schema validates a string that is not
+ # yet the string the model will see. "{{ company }}" is a legal key at save time and renders
+ # to "" here -- the empty-key case the schema cannot reach. Production has one workflow with
+ # a templated error-code key, so this path is real, not hypothetical.
+ block = _make_task_block(error_code_mapping={"{{ company }}": "no rating found", "OK_CODE": "kept"})
+ ctx = _make_workflow_run_context(workflow_error_code_mapping=None)
+ ctx.values["company"] = ""
+
+ block.format_potential_template_parameters(ctx)
+
+ assert block.error_code_mapping == {"OK_CODE": "kept"}
+
+ def test_entry_whose_key_renders_over_length_is_dropped(self) -> None:
+ # The other direction: a key well inside the 128-character limit at save time renders past it.
+ block = _make_task_block(error_code_mapping={"CODE_{{ suffix }}": "d", "OK_CODE": "kept"})
+ ctx = _make_workflow_run_context(workflow_error_code_mapping=None)
+ ctx.values["suffix"] = "x" * 200
+
+ block.format_potential_template_parameters(ctx)
+
+ assert block.error_code_mapping == {"OK_CODE": "kept"}
+
+ def test_a_mapping_that_renders_entirely_invalid_becomes_none_not_empty(self) -> None:
+ # Downstream treats a falsy mapping as "no codes offered"; an empty dict would read as a
+ # mapping that exists and offers nothing, which is a different thing to the error detector.
+ block = _make_task_block(error_code_mapping={"{{ company }}": "no rating found"})
+ ctx = _make_workflow_run_context(workflow_error_code_mapping=None)
+ ctx.values["company"] = ""
+
+ block.format_potential_template_parameters(ctx)
+
+ assert block.error_code_mapping is None
+
+ def test_a_templated_key_that_renders_valid_is_kept(self) -> None:
+ # The guard must not break templating itself -- it is a deliberate feature of this field.
+ block = _make_task_block(error_code_mapping={"{{ company }}_MISSING": "not found"})
+ ctx = _make_workflow_run_context(workflow_error_code_mapping=None)
+ ctx.values["company"] = "ACME"
+
+ block.format_potential_template_parameters(ctx)
+
+ assert block.error_code_mapping == {"ACME_MISSING": "not found"}
+
+ def test_entries_past_the_aggregate_entry_cap_are_dropped(self) -> None:
+ # Per-entry rules bound one string; only a running total bounds what a mapping can become.
+ # CodeBlock already enforces this at render; BaseTaskBlock did not.
+ from skyvern.schemas.workflows import ERROR_CODE_MAPPING_MAX_ENTRIES
+
+ mapping = {f"CODE_{index}": "description" for index in range(ERROR_CODE_MAPPING_MAX_ENTRIES + 10)}
+ block = _make_task_block(error_code_mapping=mapping)
+ ctx = _make_workflow_run_context(workflow_error_code_mapping=None)
+
+ block.format_potential_template_parameters(ctx)
+
+ assert block.error_code_mapping is not None
+ assert len(block.error_code_mapping) == ERROR_CODE_MAPPING_MAX_ENTRIES
+
+ def test_entries_past_the_aggregate_byte_cap_are_dropped(self) -> None:
+ # Each entry is inside the per-entry character limit; together they are far past the byte cap,
+ # and this mapping is JSON-dumped into the prompt.
+ from skyvern.schemas.workflows import ERROR_CODE_MAPPING_MAX_UTF8_BYTES
+
+ mapping = {f"CODE_{index}": "d" * 2000 for index in range(40)}
+ block = _make_task_block(error_code_mapping=mapping)
+ ctx = _make_workflow_run_context(workflow_error_code_mapping=None)
+
+ block.format_potential_template_parameters(ctx)
+
+ assert block.error_code_mapping is not None
+ total = sum(len(k.encode()) + len(v.encode()) for k, v in block.error_code_mapping.items())
+ assert total <= ERROR_CODE_MAPPING_MAX_UTF8_BYTES
+ assert len(block.error_code_mapping) < len(mapping)
+
+ def test_a_key_that_renders_to_contain_a_registered_secret_is_dropped(self) -> None:
+ # A description can be redacted; a key cannot, because it is the identifier the model names
+ # and the customer matches on. task.errors carries it out over the customer's webhook.
+ block = _make_task_block(error_code_mapping={"FAILED_{{ token }}": "d", "OK_CODE": "kept"})
+ ctx = _make_workflow_run_context(workflow_error_code_mapping=None)
+ ctx.values["token"] = "sk4829137765"
+ ctx.secrets["sk_param"] = "sk4829137765"
+
+ block.format_potential_template_parameters(ctx)
+
+ assert block.error_code_mapping == {"OK_CODE": "kept"}
+
+ def test_an_untrimmed_description_is_normalized_not_dropped(self) -> None:
+ # The regression this PR round exists to prevent. Measured on production: 3,691 tasks a week
+ # carry an untrimmed description and 90 would lose EVERY entry -- and a falsy mapping makes
+ # error_detection_service skip detection entirely, so a customer silently stops receiving a
+ # code they get today. A description is prose; the author's intent is recoverable.
+ block = _make_task_block(error_code_mapping={"NO_RATING": "No rating found.\nTerminate.\n"})
+ ctx = _make_workflow_run_context(workflow_error_code_mapping=None)
+
+ block.format_potential_template_parameters(ctx)
+
+ assert block.error_code_mapping == {"NO_RATING": "No rating found. Terminate."}
+
+ def test_a_short_registered_secret_does_not_delete_a_legitimate_code(self) -> None:
+ # A bare substring test with no length floor lets a card-expiry "05" make HTTP_405_DECLINED
+ # look secret-bearing. secret_redaction already carries the floors for exactly this reason.
+ block = _make_task_block(error_code_mapping={"HTTP_405_DECLINED": "the gateway declined it"})
+ ctx = _make_workflow_run_context(workflow_error_code_mapping=None)
+ ctx.secrets["expiry"] = "05"
+
+ block.format_potential_template_parameters(ctx)
+
+ assert block.error_code_mapping == {"HTTP_405_DECLINED": "the gateway declined it"}
+
+ def test_the_aggregate_cap_evicts_workflow_entries_before_the_blocks_own(self) -> None:
+ # Merge order made block entries land last, so the cap evicted exactly the entries the
+ # call site documents as taking precedence: 64 workflow entries plus 2 block entries kept
+ # none of the block's own.
+ from skyvern.schemas.workflows import ERROR_CODE_MAPPING_MAX_ENTRIES
+
+ workflow_mapping = {f"WF_{index}": "workflow entry" for index in range(ERROR_CODE_MAPPING_MAX_ENTRIES)}
+ block = _make_task_block(error_code_mapping={"BLOCK_A": "block entry", "BLOCK_B": "block entry"})
+ ctx = _make_workflow_run_context(workflow_mapping)
+
+ block.format_potential_template_parameters(ctx)
+
+ assert block.error_code_mapping is not None
+ assert "BLOCK_A" in block.error_code_mapping
+ assert "BLOCK_B" in block.error_code_mapping
+ assert len(block.error_code_mapping) == ERROR_CODE_MAPPING_MAX_ENTRIES
+
def test_sanitizer_rewrites_references_in_workflow_error_code_mapping(self) -> None:
"""Auto-sanitized labels/param keys must be rewritten inside workflow-level error_code_mapping."""
from skyvern.schemas.workflows import sanitize_workflow_yaml_with_references