Skip to content

Automate browser based workflows with AI

SKY-11081: require a scout-act before authoring a copilot download block (#6620)

Andrew Neilson00741613b1fd
diff --git a/skyvern/config.py b/skyvern/config.py
index a5cbd99bc..ffd91607e 100644
--- a/skyvern/config.py
+++ b/skyvern/config.py
@@ -147,6 +147,13 @@ class Settings(BaseSettings):
# log volume (health checks, polling) while carrying no mutation to audit.
LOG_RAW_API_REQUESTS_SUCCESSFUL_READS: bool = False
LOG_LEVEL: str = "INFO"
+ # Opt-in INFO-log sampling for high-volume orgs. A log call marked
+ # sampling=True is dropped from stdout/Datadog with probability
+ # (1 - LOG_SAMPLING_RATE) when its org is in LOG_SAMPLING_ORG_IDS. The full
+ # line is still captured in the per-run S3 log artifact. Both defaults make
+ # this a no-op: an empty org list samples nothing and rate 1.0 keeps all.
+ LOG_SAMPLING_RATE: float = 1.0
+ LOG_SAMPLING_ORG_IDS: list[str] = []
COPILOT_FEASIBILITY_GATE_TIMEOUT_SECONDS: float = 12.0
COPILOT_REQUEST_POLICY_CLASSIFIER_TIMEOUT_SECONDS: float = 6.0
COPILOT_TURN_INTENT_CLASSIFIER_TIMEOUT_SECONDS: float = 12.0
@@ -168,6 +175,11 @@ class Settings(BaseSettings):
# On, a reached-download affordance compiles into the expect_download idiom in the code-block
# synthesizer; off (default) restores today's bare-click synthesis. Per-rung gate.
COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED: bool = False
+ # A download fires only when its affordance is clicked, so a download-intent code block must
+ # be scout-acted (skyvern_evaluate) before it can be authored: the guardrail rejects authoring
+ # one with no scout_interaction this turn, and the evaluate tool is framed as the scout-act
+ # path for interaction-gated affordances. Off (default) restores today's inspect-then-author.
+ COPILOT_DOWNLOAD_SCOUT_ACT_REQUIRED_ENABLED: bool = False
# Dispatch flag for the workflow copilot v2 (openai-agents-SDK rewrite).
# Off = existing direct-LLM copilot at workflow_copilot_chat_post.
# On = new agent-SDK path under skyvern.forge.sdk.copilot.
diff --git a/skyvern/core/script_generations/real_skyvern_page_ai.py b/skyvern/core/script_generations/real_skyvern_page_ai.py
index 2ac0206c7..9af6435bc 100644
--- a/skyvern/core/script_generations/real_skyvern_page_ai.py
+++ b/skyvern/core/script_generations/real_skyvern_page_ai.py
@@ -1425,6 +1425,7 @@ class RealSkyvernPageAi(SkyvernPageAi):
elif lookup_result is not None:
LOG.info(
"ai_extract cache miss",
+ sampling=True,
workflow_run_id=workflow_run_id,
cache_key=cache_key,
cache_hit=False,
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index e833e9f7c..bf75e1148 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -526,6 +526,7 @@ class ForgeAgent:
)
LOG.info(
"Created a new task for workflow run",
+ sampling=True,
workflow_id=workflow.workflow_id,
workflow_run_id=workflow_run.workflow_run_id,
task_id=task.task_id,
@@ -550,6 +551,7 @@ class ForgeAgent:
)
LOG.info(
"Created new step for workflow run",
+ sampling=True,
workflow_id=workflow.workflow_id,
workflow_run_id=workflow_run.workflow_run_id,
order=step.order,
@@ -1379,6 +1381,7 @@ class ForgeAgent:
try:
LOG.info(
"Starting agent step",
+ sampling=True,
step_order=step.order,
step_retry=step.retry_index,
)
@@ -1690,6 +1693,7 @@ class ForgeAgent:
# Execute the actions
LOG.info(
"Executing actions",
+ sampling=True,
step_order=step.order,
step_retry=step.retry_index,
actions=actions,
@@ -1905,6 +1909,7 @@ class ForgeAgent:
pdf_auto_download_src = None
LOG.info(
"Action succeeded",
+ sampling=True,
step_order=step.order,
step_retry=step.retry_index,
action_idx=action_idx,
@@ -1974,6 +1979,7 @@ class ForgeAgent:
LOG.info(
"Actions executed successfully, marking step as completed",
+ sampling=True,
step_order=step.order,
step_retry=step.retry_index,
action_results=action_results,
@@ -2567,6 +2573,7 @@ class ForgeAgent:
LOG.info(
"Speculative extract-actions completed",
+ sampling=True,
current_step_id=current_step.step_id,
synthetic_step_id=next_step.step_id,
)
@@ -3395,6 +3402,7 @@ class ForgeAgent:
)
LOG.info(
"Scraped website",
+ sampling=True,
step_order=step.order,
step_retry=step.retry_index,
num_elements=len(scraped_page.elements),
@@ -3908,6 +3916,7 @@ class ForgeAgent:
LOG.info(
"Using cached prompt",
+ sampling=True,
task_id=task.task_id,
prompt_name=EXTRACT_ACTION_PROMPT_NAME,
cache_variant=cache_variant,
@@ -4427,6 +4436,7 @@ class ForgeAgent:
if task.workflow_run_id:
LOG.info(
"Task is part of a workflow run, not sending a webhook response",
+ sampling=True,
task_id=task.task_id,
workflow_run_id=task.workflow_run_id,
)
@@ -4515,6 +4525,7 @@ class ForgeAgent:
if resp.status_code >= 200 and resp.status_code < 300:
LOG.info(
"Webhook sent successfully",
+ sampling=True,
task_id=task.task_id,
resp_code=resp.status_code,
resp_text=resp.text,
@@ -5030,6 +5041,7 @@ class ForgeAgent:
LOG.info(
"Parallel verification: goal not achieved, awaiting speculative extract-actions",
+ sampling=True,
step_id=step.step_id,
task_id=task.task_id,
)
diff --git a/skyvern/forge/sdk/api/llm/api_handler_factory.py b/skyvern/forge/sdk/api/llm/api_handler_factory.py
index 68a4a9010..6e7d65b18 100644
--- a/skyvern/forge/sdk/api/llm/api_handler_factory.py
+++ b/skyvern/forge/sdk/api/llm/api_handler_factory.py
@@ -1218,12 +1218,15 @@ class LLMAPIHandlerFactory:
)
if prompt_stripped:
- LOG.info("Stripped static prompt from cached request to avoid double-billing")
+ LOG.info(
+ "Stripped static prompt from cached request to avoid double-billing", sampling=True
+ )
else:
LOG.warning("Could not find static prompt to strip from cached request")
LOG.info(
"Adding Vertex AI cache reference to primary Gemini request",
+ sampling=True,
prompt_name=prompt_name,
primary_model=main_model_group,
fallback_model=llm_config.fallback_model_group,
@@ -1290,6 +1293,7 @@ class LLMAPIHandlerFactory:
if not LLMAPIHandlerFactory._models_equivalent(response_model, main_model_group):
LOG.info(
"LLM router fallback succeeded",
+ sampling=True,
llm_key=llm_key,
prompt_name=prompt_name,
primary_model=main_model_group,
@@ -1891,7 +1895,7 @@ class LLMAPIHandlerFactory:
)
if prompt_stripped:
- LOG.info("Stripped static prompt from cached request to avoid double-billing")
+ LOG.info("Stripped static prompt from cached request to avoid double-billing", sampling=True)
else:
LOG.warning("Could not find static prompt to strip from cached request")
diff --git a/skyvern/forge/sdk/api/llm/schema_validator.py b/skyvern/forge/sdk/api/llm/schema_validator.py
index de17320ea..071c39bd1 100644
--- a/skyvern/forge/sdk/api/llm/schema_validator.py
+++ b/skyvern/forge/sdk/api/llm/schema_validator.py
@@ -276,7 +276,7 @@ def validate_and_fill_extraction_result(
LOG.info("Schema is invalid, returning extraction result as-is without transformations")
return extraction_result
- LOG.info("Validating and filling extraction result against schema")
+ LOG.info("Validating and filling extraction result against schema", sampling=True)
try:
filled_result = fill_missing_fields(extraction_result, schema)
@@ -293,7 +293,7 @@ def validate_and_fill_extraction_result(
errors=validation_errors,
)
- LOG.info("Successfully validated and filled extraction result")
+ LOG.info("Successfully validated and filled extraction result", sampling=True)
return filled_result
except Exception as e:
LOG.error(
diff --git a/skyvern/forge/sdk/copilot/composition_evidence.py b/skyvern/forge/sdk/copilot/composition_evidence.py
index c51d0db55..ddc18edad 100644
--- a/skyvern/forge/sdk/copilot/composition_evidence.py
+++ b/skyvern/forge/sdk/copilot/composition_evidence.py
@@ -707,6 +707,13 @@ def _turn_evidence_sources(ctx: Any) -> list[dict[str, Any]]:
return sources
+def turn_has_scout_interaction(ctx: Any) -> bool:
+ """True when this turn's evidence trajectory carries a scout_interaction observation that
+ resolved a concrete selector — proof the model scout-ACTED an affordance (clicked it) rather
+ than only inspecting the page passively."""
+ return any(_is_scout_interaction_evidence(evidence) for evidence in _turn_evidence_sources(ctx))
+
+
def _prior_observed_pages(ctx: Any) -> list[dict[str, Any]]:
return [page for page in (getattr(ctx, "prior_observed_acted_pages", None) or []) if isinstance(page, dict)]
diff --git a/skyvern/forge/sdk/copilot/reached_download_target.py b/skyvern/forge/sdk/copilot/reached_download_target.py
index 445902ce5..234523c74 100644
--- a/skyvern/forge/sdk/copilot/reached_download_target.py
+++ b/skyvern/forge/sdk/copilot/reached_download_target.py
@@ -3,6 +3,8 @@ selector and trajectory recency (never URL identity — a browser download does
from __future__ import annotations
+import ast
+import textwrap
from dataclasses import dataclass
from enum import Enum
from typing import Any, Literal, cast
@@ -178,3 +180,68 @@ _CONFIRMED_DOWNLOAD_GUIDANCE = (
def guidance_for(target: ReachedDownloadTarget) -> str:
return _CONFIRMED_DOWNLOAD_GUIDANCE if target.already_registered else _AUTHOR_DOWNLOAD_GUIDANCE
+
+
+_EXPECT_DOWNLOAD_ATTR = "expect_download"
+_DOWNLOAD_EVENT_CAPTURE_ATTRS: frozenset[str] = frozenset({"wait_for_event", "expect_event"})
+_DOWNLOAD_EVENT_NAME = "download"
+_REGISTERED_DOWNLOAD_OUTPUT_KEY_SET = frozenset(REGISTERED_DOWNLOAD_OUTPUT_KEYS)
+
+
+def _call_is_expect_download(node: ast.expr) -> bool:
+ if isinstance(node, ast.Await):
+ return _call_is_expect_download(node.value)
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return node.func.attr == _EXPECT_DOWNLOAD_ATTR
+ return False
+
+
+def _call_is_download_event_capture(node: ast.expr) -> bool:
+ """True for the event-based download idioms ``page.wait_for_event("download")`` /
+ ``page.expect_event("download")`` (await-unwrapped, first arg the literal ``"download"``).
+
+ A hand-rolled event capture registers the same browser download as ``expect_download`` but evades
+ the strict ``expect_download`` predicate, so the gate and contract treat it as download intent."""
+ if isinstance(node, ast.Await):
+ return _call_is_download_event_capture(node.value)
+ if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)):
+ return False
+ if node.func.attr not in _DOWNLOAD_EVENT_CAPTURE_ATTRS or not node.args:
+ return False
+ first = node.args[0]
+ return isinstance(first, ast.Constant) and first.value == _DOWNLOAD_EVENT_NAME
+
+
+def _dict_literal_keys(node: ast.expr) -> set[str]:
+ if isinstance(node, ast.Await):
+ return _dict_literal_keys(node.value)
+ if not isinstance(node, ast.Dict):
+ return set()
+ return {key.value for key in node.keys if isinstance(key, ast.Constant) and isinstance(key.value, str)}
+
+
+def code_is_download_intent(code: str) -> bool:
+ """True when a code block authors a download: it uses the `page.expect_download` context-manager
+ idiom or the event-based `page.wait_for_event("download")` / `page.expect_event("download")` idiom
+ anywhere, or returns/binds a dict literal carrying an execution-layer download registration key.
+ Used to require a scout-act before such a block may be authored."""
+ if not code.strip():
+ return False
+ try:
+ tree = ast.parse(textwrap.dedent(code).strip() or "pass")
+ except SyntaxError:
+ return False
+ for node in ast.walk(tree):
+ if isinstance(node, (ast.AsyncWith, ast.With)):
+ for item in node.items:
+ if _call_is_expect_download(item.context_expr) or _call_is_download_event_capture(item.context_expr):
+ return True
+ if isinstance(node, (ast.Call, ast.Await)) and _call_is_download_event_capture(node):
+ return True
+ if isinstance(node, ast.Return) and node.value is not None:
+ if _dict_literal_keys(node.value) & _REGISTERED_DOWNLOAD_OUTPUT_KEY_SET:
+ return True
+ if isinstance(node, ast.Assign):
+ if _dict_literal_keys(node.value) & _REGISTERED_DOWNLOAD_OUTPUT_KEY_SET:
+ return True
+ return False
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index 1ff644af4..38405b00b 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -272,6 +272,9 @@ class AgentContext:
# expect_download step from it. Selector is the observed download link, not necessarily a trajectory click.
reached_download_target: ReachedDownloadTarget | None = None
synthesized_block_offered: bool = False
+ # Count of times the scout-act download gate rejected a download-intent block this turn. Bounds
+ # the author->scout->re-author cycle so a genuinely un-scoutable affordance halts honestly.
+ download_scout_required_rejections: int = 0
# Source page of an in-flight scout action, captured before it may navigate away.
pending_scout_source_url: str | None = None
pending_scout_typed_value: str | None = None
diff --git a/skyvern/forge/sdk/copilot/tools/guardrails.py b/skyvern/forge/sdk/copilot/tools/guardrails.py
index 2f8122359..40bb455d0 100644
--- a/skyvern/forge/sdk/copilot/tools/guardrails.py
+++ b/skyvern/forge/sdk/copilot/tools/guardrails.py
@@ -6,10 +6,12 @@ from typing import Any
import structlog
from agents import ToolGuardrailFunctionOutput, ToolInputGuardrail, ToolInputGuardrailData
+from skyvern.config import settings
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal, RecoveryHint
from skyvern.forge.sdk.copilot.build_phase import _phase_blocker_signal
from skyvern.forge.sdk.copilot.composition_evidence import (
composition_page_evidence_error,
+ turn_has_scout_interaction,
workflow_target_url,
)
from skyvern.forge.sdk.copilot.loop_detection import record_consecutive_tool_result_boundary_for_ctx
@@ -18,6 +20,7 @@ from skyvern.forge.sdk.copilot.output_policy import (
format_output_policy_tool_error,
output_policy_verdict_to_trace_data,
)
+from skyvern.forge.sdk.copilot.reached_download_target import code_is_download_intent
from skyvern.forge.sdk.copilot.request_policy import CREDENTIAL_DEFERRED_DRAFT_REASONS, RequestPolicy
from skyvern.forge.sdk.copilot.runtime import AgentContext
from skyvern.forge.sdk.copilot.turn_intent import (
@@ -137,6 +140,69 @@ def _update_and_run_blocks_composition_evidence_precheck(
return None
+_DOWNLOAD_SCOUT_REQUIRED_STEERING = (
+ "This block downloads a file, and a download fires only when the affordance is clicked. "
+ "Scout-act it first: call skyvern_evaluate to click the download control on the live page, then "
+ "re-author the block. The terminal download step will be compiled for you from the observed "
+ "target, so you do not author the expect_download idiom yourself."
+)
+# After this many scout-act rejections in a turn, stop blocking and let the model halt honestly: a
+# download whose affordance the scout never resolves is not authorable, so looping author->scout
+# wastes turns. A genuinely scoutable download clears the gate on the first re-author.
+_DOWNLOAD_SCOUT_REQUIRED_MAX_REJECTIONS = 3
+_DOWNLOAD_SCOUT_UNREACHABLE_HALT = (
+ "Repeated scout-acts did not resolve a single download affordance on this page, so the download "
+ "step cannot be compiled. Tell the user you could not locate the download control and ask them to "
+ "confirm where the file downloads from; do not author a hand-rolled download block."
+)
+
+
+def _download_intent_block_labels(workflow_yaml: str | None) -> list[str]:
+ labels: list[str] = []
+ for label, block in _workflow_yaml_blocks_by_label(workflow_yaml).items():
+ if block.get("block_type") != "code":
+ continue
+ code = block.get("code")
+ if isinstance(code, str) and code_is_download_intent(code):
+ labels.append(label)
+ return labels
+
+
+def _download_scout_required_error(copilot_ctx: Any, workflow_yaml: str | None) -> str | None:
+ """Reject authoring a download-intent code block until the affordance has been scout-acted
+ this turn, so the skyvern_evaluate post-hook can populate the reached-download target and the
+ synthesizer can compile the terminal download step. Off unless the scout-act flag is set."""
+ if not settings.COPILOT_DOWNLOAD_SCOUT_ACT_REQUIRED_ENABLED:
+ return None
+ if copilot_ctx is None or workflow_yaml is None:
+ return None
+ download_labels = _download_intent_block_labels(workflow_yaml)
+ if not download_labels:
+ return None
+ if turn_has_scout_interaction(copilot_ctx):
+ return None
+ prior_rejections = int(getattr(copilot_ctx, "download_scout_required_rejections", 0) or 0)
+ if prior_rejections >= _DOWNLOAD_SCOUT_REQUIRED_MAX_REJECTIONS:
+ LOG.info(
+ "copilot download scout-act gate exhausted retries; halting honestly",
+ workflow_permanent_id=getattr(copilot_ctx, "workflow_permanent_id", None),
+ download_intent_block_labels=download_labels,
+ download_scout_required_rejections=prior_rejections,
+ surface="tool_pre_side_effect",
+ )
+ return _DOWNLOAD_SCOUT_UNREACHABLE_HALT
+ if hasattr(copilot_ctx, "download_scout_required_rejections"):
+ copilot_ctx.download_scout_required_rejections = prior_rejections + 1
+ LOG.info(
+ "copilot download scout-act pre-side-effect rejected workflow",
+ workflow_permanent_id=getattr(copilot_ctx, "workflow_permanent_id", None),
+ download_intent_block_labels=download_labels,
+ download_scout_required_rejections=prior_rejections + 1,
+ surface="tool_pre_side_effect",
+ )
+ return _DOWNLOAD_SCOUT_REQUIRED_STEERING
+
+
def _request_policy_tool_error(ctx: AgentContext, tool_name: str) -> CopilotToolBlockerSignal | None:
policy = getattr(ctx, "request_policy", None)
if not isinstance(policy, RequestPolicy):
diff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
index 76c9ff13c..05371c766 100644
--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
@@ -7,6 +7,7 @@ from typing import Any
import structlog
+from skyvern.config import settings
from skyvern.forge.sdk.copilot.block_type_aliases import normalize_copilot_block_type_alias
from skyvern.forge.sdk.copilot.build_phase import (
BuildPhase,
@@ -42,6 +43,7 @@ from .scouting import (
_consume_scout_source_url,
_mark_page_inspected,
_mark_pending_browser_interaction_observation,
+ _maybe_attach_reached_download_target,
_record_scouted_interaction,
_register_scout_interaction_observation,
_resolve_scout_role_name,
@@ -379,6 +381,8 @@ async def _click_post_hook(
result["data"]["observation_step"] = observation_step
if page_evidence is not None:
_attach_scout_page_summary(result, page_evidence)
+ if settings.COPILOT_DOWNLOAD_SCOUT_ACT_REQUIRED_ENABLED:
+ await _maybe_attach_reached_download_target(ctx, result, url=url, page_evidence=page_evidence)
return result
@@ -636,6 +640,28 @@ def get_skyvern_mcp_alias_map() -> dict[str, str]:
}
+_EVALUATE_BASE_DESCRIPTION = (
+ "Execute JavaScript in the browser and return the result. "
+ "Use this to inspect DOM state, read values, or run arbitrary JS."
+)
+# Scout-ACT framing: an interaction-gated affordance (a download, a row-expand, a post-login
+# area) only reveals its result after it is clicked, so it must be acted on here rather than
+# inspected passively. For a download the copilot then compiles the terminal download step.
+_EVALUATE_SCOUT_ACT_DESCRIPTION = (
+ _EVALUATE_BASE_DESCRIPTION
+ + " Some results only appear AFTER an interaction (a download, a row-expand, a post-login "
+ "area); scout-ACT those affordances here (click the control via JS) instead of inspecting "
+ "passively. For a download, click the download control with this tool rather than authoring "
+ "the download yourself — the copilot then compiles the terminal download step for you."
+)
+
+
+def _evaluate_overlay_description() -> str:
+ if settings.COPILOT_DOWNLOAD_SCOUT_ACT_REQUIRED_ENABLED:
+ return _EVALUATE_SCOUT_ACT_DESCRIPTION
+ return _EVALUATE_BASE_DESCRIPTION
+
+
def _build_skyvern_mcp_overlays() -> dict[str, SchemaOverlay]:
return {
"get_block_schema": SchemaOverlay(
@@ -664,10 +690,7 @@ def _build_skyvern_mcp_overlays() -> dict[str, SchemaOverlay]:
post_hook=_screenshot_post_hook,
),
"evaluate": SchemaOverlay(
- description=(
- "Execute JavaScript in the browser and return the result. "
- "Use this to inspect DOM state, read values, or run arbitrary JS."
- ),
+ description=_evaluate_overlay_description(),
hide_params=frozenset({"session_id", "cdp_url"}),
requires_browser=True,
timeout=30,
diff --git a/skyvern/forge/sdk/copilot/tools/scouting.py b/skyvern/forge/sdk/copilot/tools/scouting.py
index 6ab571de1..bc7146475 100644
--- a/skyvern/forge/sdk/copilot/tools/scouting.py
+++ b/skyvern/forge/sdk/copilot/tools/scouting.py
@@ -20,6 +20,9 @@ from skyvern.forge.sdk.copilot.composition_evidence import (
has_bounded_page_schema,
)
from skyvern.forge.sdk.copilot.enforcement import _RECENT_TOOL_OUTPUT_CHAR_CAP
+from skyvern.forge.sdk.copilot.reached_download_target import (
+ ReachedDownloadTarget,
+)
from skyvern.forge.sdk.copilot.reached_download_target import (
derive_from_navigation_targets as _derive_reached_download_from_nav_targets,
)
@@ -799,6 +802,31 @@ async def _maybe_steer_evaluate_to_action(
return False
+def _register_reached_download_scout_interaction(ctx: AgentContext, target: ReachedDownloadTarget, *, url: str) -> None:
+ """Record the evaluate-resolved download affordance as a scout_interaction observation.
+
+ The scout-act download gate is cleared by a scout_interaction this turn, but the reached-download
+ target is resolved on the evaluate post-hook (source_tool="evaluate"). Registering the affordance
+ here unifies the two: the same evaluate call that feeds the synthesizer also clears the gate, so
+ obeying the scout-act steering is sufficient and the gate cannot loop on a scouted download.
+ """
+ selector = target.selector.strip()
+ if not selector or not url.strip():
+ return
+ _append_flow_evidence(
+ ctx,
+ {
+ "inspected_url": url,
+ "current_url": url,
+ "source_tool": SCOUT_INTERACTION_EVIDENCE_TOOL,
+ "interaction_tool": "evaluate",
+ "interaction_selector": selector,
+ "download_kind": target.download_kind,
+ },
+ reached_via="interaction",
+ )
+
+
async def _maybe_attach_reached_download_target(
ctx: AgentContext,
result: dict[str, Any],
@@ -834,6 +862,8 @@ async def _maybe_attach_reached_download_target(
# non-download idiom. Reopen the latch once so the post-turn fallback re-fires carrying it.
ctx.synthesized_block_offered = False
LOG.info("copilot_synthesized_block_offer_latch_reset_for_download", url=url)
+ if settings.COPILOT_DOWNLOAD_SCOUT_ACT_REQUIRED_ENABLED and not target.already_registered:
+ _register_reached_download_scout_interaction(ctx, target, url=url)
LOG.info(
"copilot_reached_download_target_steer",
url=url,
diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.py
index a80bea05f..443f2fb47 100644
--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py
+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py
@@ -88,7 +88,7 @@ from .frontier import (
_stale_block_metadata_message,
_workflow_requires_canonical_persist,
)
-from .guardrails import _authority_tool_error
+from .guardrails import _authority_tool_error, _download_scout_required_error
LOG = structlog.get_logger()
@@ -2065,6 +2065,10 @@ async def _update_workflow(
_record_banned_block_reject_span("_update_workflow", banned_items)
return {"ok": False, "error": _banned_block_reject_message(banned_items, ctx)}
+ download_scout_error = _download_scout_required_error(ctx, workflow_yaml)
+ if download_scout_error:
+ return {"ok": False, "error": download_scout_error}
+
composition_evidence_error = composition_page_evidence_error(ctx, workflow_yaml)
if composition_evidence_error:
LOG.info(
diff --git a/skyvern/forge/sdk/forge_log.py b/skyvern/forge/sdk/forge_log.py
index 5d88af193..7b0977185 100644
--- a/skyvern/forge/sdk/forge_log.py
+++ b/skyvern/forge/sdk/forge_log.py
@@ -1,4 +1,5 @@
import logging
+import random
import re
import sys
from pathlib import Path
@@ -115,7 +116,7 @@ def add_kv_pairs_to_msg(logger: logging.Logger, method_name: str, event_dict: Ev
msg_field = event_dict.get("msg", "")
# Add key-value pairs
- kv_pairs = {k: v for k, v in event_dict.items() if k not in ["msg", "timestamp", "level"]}
+ kv_pairs = {k: v for k, v in event_dict.items() if k not in ["msg", "timestamp", "level", "sampling"]}
if kv_pairs:
additional_info = ", ".join(f"{k}={v}" for k, v in kv_pairs.items())
msg_field += f" | {additional_info}"
@@ -184,6 +185,29 @@ def skyvern_logs_processor(logger: logging.Logger, method_name: str, event_dict:
return event_dict
+def sample_logs_processor(logger: logging.Logger, method_name: str, event_dict: EventDict) -> EventDict:
+ """Probabilistically drop INFO call sites marked ``sampling=True`` for configured orgs.
+
+ Placed after ``skyvern_logs_processor`` so the full line is still captured in
+ ``context.log`` (persisted to the per-run S3 log artifact); only the stdout /
+ Datadog stream is thinned. The ``sampling`` marker never ships downstream, and
+ WARN/ERROR are never dropped even when marked.
+ """
+ if not event_dict.pop("sampling", False):
+ return event_dict
+ if method_name != "info":
+ return event_dict
+
+ context = skyvern_context.current()
+ organization_id = context.organization_id if context else None
+ if organization_id not in settings.LOG_SAMPLING_ORG_IDS:
+ return event_dict
+
+ if random.random() < settings.LOG_SAMPLING_RATE:
+ return event_dict
+ raise structlog.DropEvent
+
+
def add_filename_section(logger: logging.Logger, method_name: str, event_dict: EventDict) -> EventDict:
"""
Add a fixed-width, bracketed filename:lineno section after the log level for console logs.
@@ -414,7 +438,7 @@ def setup_logger() -> None:
structlog.processors.format_exc_info,
]
+ additional_processors
- + [skyvern_logs_processor, structlog.stdlib.ProcessorFormatter.wrap_for_formatter],
+ + [skyvern_logs_processor, sample_logs_processor, structlog.stdlib.ProcessorFormatter.wrap_for_formatter],
)
handler = logging.StreamHandler()
handler.setFormatter(
@@ -452,3 +476,6 @@ def setup_logger() -> None:
logging.getLogger("websockets.client").setLevel(logging.WARNING)
logging.getLogger("websockets.legacy").setLevel(logging.WARNING)
logging.getLogger("websockets.legacy.server").setLevel(logging.WARNING)
+
+ # Anthropic Bedrock SDK emits high-volume WARN noise; keep only its errors.
+ logging.getLogger("anthropic").setLevel(logging.ERROR)
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 55dceda68..0cd1a112a 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -401,6 +401,7 @@ class Block(BaseModel, abc.ABC):
)
LOG.info(
"Registered output parameter value",
+ sampling=True,
output_parameter_id=self.output_parameter.output_parameter_id,
workflow_run_id=workflow_run_id,
output_parameter_value=value,
@@ -743,6 +744,7 @@ class Block(BaseModel, abc.ABC):
description = json_response.get("summary")
LOG.info(
"Generated description for the workflow run block",
+ sampling=True,
description=description,
workflow_run_block_id=workflow_run_block_id,
)
@@ -831,7 +833,11 @@ class Block(BaseModel, abc.ABC):
)
LOG.info(
- "Executing block", workflow_run_id=workflow_run_id, block_label=self.label, block_type=self.block_type
+ "Executing block",
+ sampling=True,
+ workflow_run_id=workflow_run_id,
+ block_label=self.label,
+ block_type=self.block_type,
)
return await self.execute(
workflow_run_id,
@@ -1380,6 +1386,7 @@ class BaseTaskBlock(Block):
if updated_task.status == TaskStatus.completed or updated_task.status == TaskStatus.terminated:
LOG.info(
"Task completed",
+ sampling=True,
task_id=updated_task.task_id,
task_status=updated_task.status,
workflow_run_id=workflow_run_id,
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index 5914202f2..24934bb5c 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -2129,6 +2129,7 @@ class WorkflowService:
if script:
LOG.info(
"Loading script blocks for workflow execution",
+ sampling=True,
workflow_run_id=workflow_run_id,
script_id=script.script_id,
script_revision_id=script.script_revision_id,
@@ -2195,6 +2196,7 @@ class WorkflowService:
pinned_ctx.is_static_script = True
LOG.info(
"Successfully loaded script module",
+ sampling=True,
script_id=script.script_id,
block_count=len(script_blocks_by_label),
)
@@ -2754,6 +2756,7 @@ class WorkflowService:
)
LOG.info(
f"Executing root block {block.block_type} at index {block_idx}/{blocks_cnt - 1} for workflow run {workflow_run_id}",
+ sampling=True,
block_type=block.block_type,
workflow_run_id=workflow_run_id,
block_idx=block_idx,
@@ -3131,6 +3134,7 @@ class WorkflowService:
)
LOG.info(
"Executing block via agent",
+ sampling=True,
block_label=block.label,
block_type=block.block_type,
agent_reason=agent_reason,
@@ -6121,6 +6125,7 @@ class WorkflowService:
)
LOG.info(
"Prepared webhook run status for webhook callback url",
+ sampling=True,
workflow_id=workflow_id,
workflow_run_id=workflow_run.workflow_run_id,
webhook_callback_url=workflow_run.webhook_callback_url,
@@ -6158,6 +6163,7 @@ class WorkflowService:
LOG.info(
"Sending webhook run status to webhook callback url",
+ sampling=True,
workflow_id=webhook.workflow_id,
workflow_run_id=webhook.workflow_run_id,
webhook_callback_url=webhook.webhook_callback_url,
@@ -6198,6 +6204,7 @@ class WorkflowService:
if resp.status_code >= 200 and resp.status_code < 300:
LOG.info(
"Webhook sent successfully",
+ sampling=True,
workflow_id=webhook.workflow_id,
workflow_run_id=webhook.workflow_run_id,
resp_code=resp.status_code,
@@ -6787,6 +6794,7 @@ class WorkflowService:
LOG.info(
"Generate script?",
+ sampling=True,
block_labels=block_labels,
code_gen=code_gen,
workflow_run_id=workflow_run.workflow_run_id,
@@ -6899,6 +6907,7 @@ class WorkflowService:
if not should_regenerate:
LOG.info(
"Workflow script already up to date; skipping regeneration",
+ sampling=True,
workflow_id=workflow.workflow_id,
workflow_run_id=workflow_run.workflow_run_id,
cache_key_value=rendered_cache_key_value,
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index 4ce20ada3..229a3ee7e 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -1095,6 +1095,7 @@ class ActionHandler:
await app.AGENT_FUNCTION.wait_for_challenge_solver(page=page)
LOG.info(
"Handling action",
+ sampling=True,
action_type=action.action_type,
action_id=action.action_id,
status=action.status,
@@ -1882,6 +1883,7 @@ async def handle_input_text_action(
if len(incremental_element) == 0:
LOG.info(
"No new element detected, indicating it couldn't be a selectable auto-completion input",
+ sampling=True,
element_id=skyvern_element.get_id(),
action=action,
)
@@ -2458,6 +2460,7 @@ async def handle_select_option_action(
element_dict = scraped_page.id_to_element_dict[action.element_id]
LOG.info(
"SelectOptionAction",
+ sampling=True,
action=action,
tag_name=tag_name,
element_dict=element_dict,
@@ -3423,7 +3426,7 @@ async def chain_click(
locator = skyvern_element.locator
click_count = _get_click_count(action)
# TODO (suchintan): This should likely result in an ActionFailure -- we can figure out how to do this later!
- LOG.info("Chain click starts", action=action, locator=locator)
+ LOG.info("Chain click starts", action=action, locator=locator, sampling=True)
file = pending_upload_files or []
if not file and action.file_url:
file_url = get_actual_value_of_parameter_if_secret_with_task(task, action.file_url)
@@ -3448,7 +3451,7 @@ async def chain_click(
if not has_pending:
page.on("filechooser", fc_func)
- LOG.info("Registered file chooser listener", action=action, path=file)
+ LOG.info("Registered file chooser listener", action=action, path=file, sampling=True)
else:
LOG.info(
"Skipping defensive file chooser listener — pending deferred listener exists",
@@ -3472,7 +3475,7 @@ async def chain_click(
else:
await EventStrategyFactory.move_to_element(page, locator)
await _locator_click(locator, click_count, timeout=timeout)
- LOG.info("Chain click: main element click succeeded", action=action, locator=locator)
+ LOG.info("Chain click: main element click succeeded", action=action, locator=locator, sampling=True)
action_results = [ActionSuccess()]
return action_results
@@ -3918,6 +3921,7 @@ async def choose_auto_completion_dropdown(
except Exception as e:
LOG.info(
"Failed to choose the auto completion dropdown",
+ sampling=True,
exc_info=True,
input_value=text,
)
@@ -3974,6 +3978,7 @@ async def input_or_auto_complete_input(
LOG.info(
"Try the potential value for auto completion",
+ sampling=True,
input_value=current_value,
)
is_location = input_or_select_context.is_location_input or False
@@ -4038,6 +4043,7 @@ async def input_or_auto_complete_input(
continue
LOG.info(
"Try the potential value for auto completion",
+ sampling=True,
input_value=value,
)
result = await choose_auto_completion_dropdown(
diff --git a/skyvern/webeye/real_browser_manager.py b/skyvern/webeye/real_browser_manager.py
index 28f29d766..14bf973e7 100644
--- a/skyvern/webeye/real_browser_manager.py
+++ b/skyvern/webeye/real_browser_manager.py
@@ -76,6 +76,7 @@ class RealBrowserManager(BrowserManager):
if workflow_run_id and workflow_run_id in self.pages:
LOG.info(
"Browser state for task not found. Using browser state for workflow run",
+ sampling=True,
task_id=task_id,
workflow_run_id=workflow_run_id,
)
@@ -232,6 +233,7 @@ class RealBrowserManager(BrowserManager):
if browser_state is None:
LOG.info(
"Creating browser state for workflow run",
+ sampling=True,
workflow_run_id=workflow_run.workflow_run_id,
)
proxy_location = workflow_run.proxy_location
@@ -436,7 +438,7 @@ class RealBrowserManager(BrowserManager):
organization_id: str | None = None,
child_workflow_run_ids: list[str] | None = None,
) -> BrowserState | None:
- LOG.info("Cleaning up for workflow run")
+ LOG.info("Cleaning up for workflow run", sampling=True)
browser_state_to_close = self.pages.get(workflow_run_id)
# Pop child workflow_run entries first — these are orphaned because child
@@ -459,6 +461,7 @@ class RealBrowserManager(BrowserManager):
if shared:
LOG.info(
"Browser state is shared with another workflow run, skipping browser close",
+ sampling=True,
workflow_run_id=workflow_run_id,
)
@@ -501,6 +504,7 @@ class RealBrowserManager(BrowserManager):
if shared:
LOG.info(
"Browser state is shared with another workflow run, skipping browser close",
+ sampling=True,
task_id=task_id,
workflow_run_id=workflow_run_id,
)
@@ -513,7 +517,7 @@ class RealBrowserManager(BrowserManager):
task_id=task_id,
workflow_run_id=workflow_run_id,
)
- LOG.info("Workflow run is cleaned up")
+ LOG.info("Workflow run is cleaned up", sampling=True)
if browser_session_id:
if organization_id:
diff --git a/skyvern/webeye/real_browser_state.py b/skyvern/webeye/real_browser_state.py
index 11d2b6b38..962892c5e 100644
--- a/skyvern/webeye/real_browser_state.py
+++ b/skyvern/webeye/real_browser_state.py
@@ -469,7 +469,7 @@ class RealBrowserState(BrowserState):
)
async def close(self, close_browser_on_completion: bool = True) -> None:
- LOG.info("Closing browser state")
+ LOG.info("Closing browser state", sampling=True)
try:
async with asyncio.timeout(BROWSER_CLOSE_TIMEOUT):
if self.browser_context and close_browser_on_completion:
diff --git a/skyvern/webeye/session_cookies.py b/skyvern/webeye/session_cookies.py
index 6bf6fe144..6ae47ee4a 100644
--- a/skyvern/webeye/session_cookies.py
+++ b/skyvern/webeye/session_cookies.py
@@ -73,7 +73,7 @@ async def restore_session_cookies(browser_context: BrowserContext | None, user_d
return
try:
await browser_context.add_cookies(sanitized)
- LOG.info("Restored session cookies into browser profile", cookie_count=len(sanitized))
+ LOG.info("Restored session cookies into browser profile", cookie_count=len(sanitized), sampling=True)
except Exception:
restored = 0
for cookie in sanitized:
diff --git a/skyvern/webeye/utils/dom.py b/skyvern/webeye/utils/dom.py
index a8667e046..b4753ce44 100644
--- a/skyvern/webeye/utils/dom.py
+++ b/skyvern/webeye/utils/dom.py
@@ -1181,7 +1181,7 @@ class DomUtil:
# It can only represent the element position in the DOM tree with tag name, it's not 100% reliable.
# As long as the current position has the same element with the tag name, the locator can be found.
# (maybe) we should validate the element hash to make sure the element is the same?
- LOG.warning("Fallback to locator element by xpath.", xpath=xpath, element_id=element_id)
+ LOG.info("Fallback to locator element by xpath.", xpath=xpath, element_id=element_id, sampling=True)
locator = frame_content.locator(f"xpath={xpath}")
num_elements = await locator.count()
if num_elements < 1:
diff --git a/tests/unit/test_copilot_hooks.py b/tests/unit/test_copilot_hooks.py
index 55747cf21..a69049f2f 100644
--- a/tests/unit/test_copilot_hooks.py
+++ b/tests/unit/test_copilot_hooks.py
@@ -1220,3 +1220,112 @@ class TestAssembleEnforcementMessages:
assert offer_msg in msgs
assert msgs.count(screenshot_msg) == 1
assert not any(isinstance(m.get("content"), str) and m["content"].startswith(NUDGE_SENTINEL) for m in msgs)
+
+
+class TestClickPostHookReachedDownloadTarget:
+ """SKY-11081: a scout-CLICK of a single same-host download affordance populates the typed
+ reached_download_target from the click post-hook (not only the evaluate path), so the
+ synthesizer fires off the actual scout-act the model performs."""
+
+ @staticmethod
+ def _patch_scouting(monkeypatch: pytest.MonkeyPatch, *, page_evidence: dict[str, Any] | None) -> None:
+ from skyvern.forge.sdk.copilot.tools import mcp_hooks as mh
+
+ monkeypatch.setattr(mh, "_clear_pending_browser_interaction_observation", lambda *_a, **_k: None)
+ monkeypatch.setattr(mh, "_consume_scout_source_url", lambda *_a, **_k: "http://localhost:8901/x/")
+ monkeypatch.setattr(mh, "_mark_pending_browser_interaction_observation", lambda *_a, **_k: None)
+ monkeypatch.setattr(mh, "_record_scouted_interaction", lambda *_a, **_k: None)
+ monkeypatch.setattr(mh, "_attach_scout_page_summary", lambda *_a, **_k: None)
+
+ async def fake_resolve_url_title(_raw: Any, _ctx: Any) -> tuple[str, str]:
+ return "http://localhost:8901/x/statement", "Statement"
+
+ async def fake_resolve_role_name(*_a: Any, **_k: Any) -> tuple[str | None, str | None]:
+ return "link", "View Printable Statement"
+
+ async def fake_register(*_a: Any, **_k: Any) -> tuple[int | None, dict[str, Any] | None]:
+ return (1, page_evidence)
+
+ monkeypatch.setattr(mh, "_resolve_url_title", fake_resolve_url_title)
+ monkeypatch.setattr(mh, "_resolve_scout_role_name", fake_resolve_role_name)
+ monkeypatch.setattr(mh, "_register_scout_interaction_observation", fake_register)
+
+ @staticmethod
+ def _ctx() -> Any:
+ from skyvern.forge.sdk.copilot.runtime import AgentContext
+
+ return AgentContext(
+ organization_id="org-1",
+ workflow_id="wf-1",
+ workflow_permanent_id="wfp-1",
+ workflow_yaml="",
+ browser_session_id="pbs_copilot",
+ stream=MagicMock(is_disconnected=AsyncMock(return_value=False)),
+ )
+
+ _SINGLE_DOWNLOAD_EVIDENCE = {
+ "navigation_targets": [
+ {
+ "selector": 'a[href="/x/statement.pdf"]',
+ "text": "View Printable Statement",
+ "download_kind": "extension",
+ }
+ ],
+ }
+
+ @pytest.mark.asyncio
+ async def test_click_on_download_affordance_populates_reached_download_target(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ from skyvern.config import settings
+ from skyvern.forge.sdk.copilot.tools.mcp_hooks import _click_post_hook
+
+ self._patch_scouting(monkeypatch, page_evidence=self._SINGLE_DOWNLOAD_EVIDENCE)
+ monkeypatch.setattr(settings, "COPILOT_DOWNLOAD_SCOUT_ACT_REQUIRED_ENABLED", True)
+ monkeypatch.setattr(settings, "COPILOT_REACHED_DOWNLOAD_TARGET_AUTHOR_STEER_ENABLED", True)
+ monkeypatch.setattr(settings, "COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED", True)
+
+ ctx = self._ctx()
+ result = {"ok": True, "data": {"selector": 'a[href="/x/statement.pdf"]'}}
+ await _click_post_hook(result, {}, ctx)
+
+ assert ctx.reached_download_target is not None
+ assert ctx.reached_download_target.download_kind == "extension"
+
+ @pytest.mark.asyncio
+ async def test_click_post_hook_is_noop_when_flag_off(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skyvern.config import settings
+ from skyvern.forge.sdk.copilot.tools.mcp_hooks import _click_post_hook
+
+ self._patch_scouting(monkeypatch, page_evidence=self._SINGLE_DOWNLOAD_EVIDENCE)
+ monkeypatch.setattr(settings, "COPILOT_DOWNLOAD_SCOUT_ACT_REQUIRED_ENABLED", False)
+ monkeypatch.setattr(settings, "COPILOT_REACHED_DOWNLOAD_TARGET_AUTHOR_STEER_ENABLED", True)
+ monkeypatch.setattr(settings, "COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED", True)
+
+ ctx = self._ctx()
+ result = {"ok": True, "data": {"selector": 'a[href="/x/statement.pdf"]'}}
+ await _click_post_hook(result, {}, ctx)
+
+ assert ctx.reached_download_target is None
+
+ @pytest.mark.asyncio
+ async def test_click_on_two_affordances_leaves_target_unset(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skyvern.config import settings
+ from skyvern.forge.sdk.copilot.tools.mcp_hooks import _click_post_hook
+
+ two = {
+ "navigation_targets": [
+ {"selector": 'a[href="/x/a.pdf"]', "text": "A", "download_kind": "extension"},
+ {"selector": 'a[href="/x/b.pdf"]', "text": "B", "download_kind": "extension"},
+ ]
+ }
+ self._patch_scouting(monkeypatch, page_evidence=two)
+ monkeypatch.setattr(settings, "COPILOT_DOWNLOAD_SCOUT_ACT_REQUIRED_ENABLED", True)
+ monkeypatch.setattr(settings, "COPILOT_REACHED_DOWNLOAD_TARGET_AUTHOR_STEER_ENABLED", True)
+ monkeypatch.setattr(settings, "COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED", True)
+
+ ctx = self._ctx()
+ result = {"ok": True, "data": {"selector": 'a[href="/x/a.pdf"]'}}
+ await _click_post_hook(result, {}, ctx)
+
+ assert ctx.reached_download_target is None
diff --git a/tests/unit/test_forge_log_sampling.py b/tests/unit/test_forge_log_sampling.py
new file mode 100644
index 000000000..0640ce7df
--- /dev/null
+++ b/tests/unit/test_forge_log_sampling.py
@@ -0,0 +1,89 @@
+import pytest
+import structlog
+
+import skyvern.forge.sdk.forge_log as forge_log
+from skyvern.config import settings
+from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
+from skyvern.forge.sdk.forge_log import add_kv_pairs_to_msg, sample_logs_processor
+
+SAMPLED_ORG = "o_sampled"
+
+
+def sampled_org(monkeypatch: pytest.MonkeyPatch) -> str:
+ monkeypatch.setattr(skyvern_context, "current", lambda: SkyvernContext(organization_id=SAMPLED_ORG))
+ monkeypatch.setattr(settings, "LOG_SAMPLING_ORG_IDS", [SAMPLED_ORG])
+ return SAMPLED_ORG
+
+
+def _freeze_random(monkeypatch: pytest.MonkeyPatch, value: float) -> None:
+ monkeypatch.setattr(forge_log.random, "random", lambda: value)
+
+
+def test_drops_marked_info_for_sampled_org_above_rate(monkeypatch: pytest.MonkeyPatch, sampled_org: str) -> None:
+ monkeypatch.setattr(settings, "LOG_SAMPLING_RATE", 0.1)
+ _freeze_random(monkeypatch, 0.5)
+ with pytest.raises(structlog.DropEvent):
+ sample_logs_processor(None, "info", {"event": "noisy", "sampling": True}) # type: ignore[arg-type]
+
+
+def test_keeps_marked_info_for_sampled_org_below_rate(monkeypatch: pytest.MonkeyPatch, sampled_org: str) -> None:
+ monkeypatch.setattr(settings, "LOG_SAMPLING_RATE", 0.1)
+ _freeze_random(monkeypatch, 0.05)
+ result = sample_logs_processor(None, "info", {"event": "noisy", "sampling": True}) # type: ignore[arg-type]
+ assert result["event"] == "noisy"
+ assert "sampling" not in result
+
+
+def test_keeps_marked_info_for_unsampled_org(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(skyvern_context, "current", lambda: SkyvernContext(organization_id="o_other"))
+ monkeypatch.setattr(settings, "LOG_SAMPLING_ORG_IDS", [SAMPLED_ORG])
+ monkeypatch.setattr(settings, "LOG_SAMPLING_RATE", 0.0)
+ _freeze_random(monkeypatch, 0.99)
+ result = sample_logs_processor(None, "info", {"event": "noisy", "sampling": True}) # type: ignore[arg-type]
+ assert result["event"] == "noisy"
+ assert "sampling" not in result
+
+
+def test_never_drops_warning_even_when_marked(monkeypatch: pytest.MonkeyPatch, sampled_org: str) -> None:
+ monkeypatch.setattr(settings, "LOG_SAMPLING_RATE", 0.0)
+ _freeze_random(monkeypatch, 0.99)
+ result = sample_logs_processor(None, "warning", {"event": "important", "sampling": True}) # type: ignore[arg-type]
+ assert result["event"] == "important"
+ assert "sampling" not in result
+
+
+def test_unmarked_info_passes_through_untouched(monkeypatch: pytest.MonkeyPatch, sampled_org: str) -> None:
+ monkeypatch.setattr(settings, "LOG_SAMPLING_RATE", 0.0)
+ _freeze_random(monkeypatch, 0.99)
+ event = {"event": "keep me", "step_id": "stp_1"}
+ result = sample_logs_processor(None, "info", event) # type: ignore[arg-type]
+ assert result == event
+
+
+def test_empty_org_list_disables_sampling(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(skyvern_context, "current", lambda: SkyvernContext(organization_id=SAMPLED_ORG))
+ monkeypatch.setattr(settings, "LOG_SAMPLING_ORG_IDS", [])
+ monkeypatch.setattr(settings, "LOG_SAMPLING_RATE", 0.0)
+ _freeze_random(monkeypatch, 0.99)
+ result = sample_logs_processor(None, "info", {"event": "noisy", "sampling": True}) # type: ignore[arg-type]
+ assert result["event"] == "noisy"
+ assert "sampling" not in result
+
+
+def test_sampling_marker_excluded_from_rendered_message() -> None:
+ event = {"msg": "Handling action", "sampling": True, "action_type": "click"}
+ result = add_kv_pairs_to_msg(None, "info", event) # type: ignore[arg-type]
+ assert "sampling" not in result["msg"]
+ assert "action_type=click" in result["msg"]
+
+
+def test_no_context_keeps_marked_info(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(skyvern_context, "current", lambda: None)
+ monkeypatch.setattr(settings, "LOG_SAMPLING_ORG_IDS", [SAMPLED_ORG])
+ monkeypatch.setattr(settings, "LOG_SAMPLING_RATE", 0.0)
+ _freeze_random(monkeypatch, 0.99)
+ result = sample_logs_processor(None, "info", {"event": "noisy", "sampling": True}) # type: ignore[arg-type]
+ assert result["event"] == "noisy"
+ assert "sampling" not in result