Skip to content

Automate browser based workflows with AI

SKY-12593: load legacy copilot criteria-set rows via tolerant decode, fail closed on drift (#7508)

Andrew Neilson42865f1e7188
diff --git a/skyvern/forge/sdk/db/repositories/workflow_parameters.py b/skyvern/forge/sdk/db/repositories/workflow_parameters.py
index 7c2cd9d6f..2bca94328 100644
--- a/skyvern/forge/sdk/db/repositories/workflow_parameters.py
+++ b/skyvern/forge/sdk/db/repositories/workflow_parameters.py
@@ -8,6 +8,7 @@ import structlog
from sqlalchemy import select
from skyvern.config import settings
+from skyvern.forge.sdk.copilot.completion_criteria_store import criteria_from_json
from skyvern.forge.sdk.copilot.context import TurnNarrativePayload
from skyvern.forge.sdk.db._error_handling import db_operation
from skyvern.forge.sdk.db._sentinels import _UNSET
@@ -47,6 +48,7 @@ from skyvern.forge.sdk.schemas.copilot_turn_outcome import TurnOutcome
from skyvern.forge.sdk.schemas.task_generations import TaskGeneration
from skyvern.forge.sdk.schemas.tasks import Task, TaskStatus
from skyvern.forge.sdk.schemas.workflow_copilot import (
+ NonAdoptableCriteriaSet,
WorkflowCopilotChat,
WorkflowCopilotChatMessage,
WorkflowCopilotChatSender,
@@ -74,6 +76,67 @@ from skyvern.webeye.actions.actions import Action
LOG = structlog.get_logger()
+def _decode_completion_criteria_set(
+ row: WorkflowCopilotCompletionCriteriaSetModel,
+) -> WorkflowCopilotCompletionCriteriaSet | NonAdoptableCriteriaSet:
+ """A v1 dict-envelope row adopts only when every recorded criterion decodes."""
+ raw_criteria = row.criteria
+ try:
+ if isinstance(raw_criteria, list):
+ return WorkflowCopilotCompletionCriteriaSet.model_validate(row)
+ if (
+ isinstance(raw_criteria, dict)
+ and raw_criteria.get("contract_version") == 1
+ and isinstance(raw_criteria.get("criteria"), list)
+ ):
+ inner = raw_criteria["criteria"]
+ decoded = criteria_from_json(inner)
+ if (
+ not inner
+ or len(decoded) != len(inner)
+ or any(
+ (isinstance(item.get("kind"), str) and item["kind"] != criterion.kind)
+ or (isinstance(item.get("level"), str) and item["level"] != criterion.level)
+ for item, criterion in zip(inner, decoded)
+ )
+ ):
+ return NonAdoptableCriteriaSet(
+ reason="undecodable_v1_criteria",
+ completion_criteria_set_id=row.completion_criteria_set_id,
+ goal_epoch=row.goal_epoch,
+ )
+ return WorkflowCopilotCompletionCriteriaSet(
+ completion_criteria_set_id=row.completion_criteria_set_id,
+ organization_id=row.organization_id,
+ workflow_copilot_chat_id=row.workflow_copilot_chat_id,
+ goal_epoch=row.goal_epoch,
+ status=row.status,
+ criteria=inner,
+ source_turn_id=row.source_turn_id,
+ source_goal_text=row.source_goal_text,
+ consecutive_all_no_evidence=row.consecutive_all_no_evidence,
+ tripwire_fired=row.tripwire_fired,
+ last_fully_satisfied_workflow_yaml=row.last_fully_satisfied_workflow_yaml,
+ superseded_by_set_id=row.superseded_by_set_id,
+ superseded_at=row.superseded_at,
+ supersede_reason=row.supersede_reason,
+ created_at=row.created_at,
+ modified_at=row.modified_at,
+ )
+ except Exception:
+ LOG.warning(
+ "copilot completion criteria set decode raised; treating row as unknown shape",
+ completion_criteria_set_id=row.completion_criteria_set_id,
+ goal_epoch=row.goal_epoch,
+ exc_info=True,
+ )
+ return NonAdoptableCriteriaSet(
+ reason="unknown_shape",
+ completion_criteria_set_id=row.completion_criteria_set_id,
+ goal_epoch=row.goal_epoch,
+ )
+
+
class WorkflowParametersRepository(BaseRepository):
"""Database operations for workflow parameters, copilot chat, task generation, actions, and runs."""
@@ -698,19 +761,22 @@ class WorkflowParametersRepository(BaseRepository):
self,
organization_id: str,
workflow_copilot_chat_id: str,
- ) -> WorkflowCopilotCompletionCriteriaSet | None:
+ ) -> WorkflowCopilotCompletionCriteriaSet | NonAdoptableCriteriaSet | None:
async with self.Session() as session:
query = (
select(WorkflowCopilotCompletionCriteriaSetModel)
.filter(WorkflowCopilotCompletionCriteriaSetModel.organization_id == organization_id)
.filter(WorkflowCopilotCompletionCriteriaSetModel.workflow_copilot_chat_id == workflow_copilot_chat_id)
- .order_by(WorkflowCopilotCompletionCriteriaSetModel.goal_epoch.desc())
+ .order_by(
+ WorkflowCopilotCompletionCriteriaSetModel.goal_epoch.desc(),
+ WorkflowCopilotCompletionCriteriaSetModel.created_at.desc(),
+ )
.limit(1)
)
row = (await session.scalars(query)).first()
if not row:
return None
- return WorkflowCopilotCompletionCriteriaSet.model_validate(row)
+ return _decode_completion_criteria_set(row)
@db_operation("create_workflow_copilot_completion_criteria_set")
async def create_workflow_copilot_completion_criteria_set(
diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.py
index 9caadb4a1..d599c2afa 100644
--- a/skyvern/forge/sdk/routes/workflow_copilot.py
+++ b/skyvern/forge/sdk/routes/workflow_copilot.py
@@ -71,6 +71,7 @@ from skyvern.forge.sdk.routes.routers import base_router
from skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind, TurnOutcome
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.schemas.workflow_copilot import (
+ NonAdoptableCriteriaSet,
WorkflowCopilotApplyProposedWorkflowRequest,
WorkflowCopilotAudioUploadResponse,
WorkflowCopilotCancelRequest,
@@ -523,16 +524,33 @@ async def _load_completion_criteria_snapshot(chat: Any) -> StoredCriteriaSnapsho
return None
if latest is None:
return StoredCriteriaSnapshot()
- active = None
- if latest.status == CRITERIA_SET_STATUS_ACTIVE:
- active = StoredCriteriaSet(
- set_id=latest.completion_criteria_set_id,
+ if isinstance(latest, NonAdoptableCriteriaSet):
+ LOG.warning(
+ "copilot completion criteria set not adoptable; disabling active set for this turn",
+ reason=latest.reason,
+ completion_criteria_set_id=latest.completion_criteria_set_id,
goal_epoch=latest.goal_epoch,
- criteria=criteria_from_json(latest.criteria),
- consecutive_all_no_evidence=latest.consecutive_all_no_evidence,
- tripwire_fired=latest.tripwire_fired,
- last_fully_satisfied_workflow_yaml=latest.last_fully_satisfied_workflow_yaml,
)
+ return StoredCriteriaSnapshot(active=None, next_epoch=latest.goal_epoch + 1)
+ active = None
+ if latest.status == CRITERIA_SET_STATUS_ACTIVE:
+ try:
+ active = StoredCriteriaSet(
+ set_id=latest.completion_criteria_set_id,
+ goal_epoch=latest.goal_epoch,
+ criteria=criteria_from_json(latest.criteria),
+ consecutive_all_no_evidence=latest.consecutive_all_no_evidence,
+ tripwire_fired=latest.tripwire_fired,
+ last_fully_satisfied_workflow_yaml=latest.last_fully_satisfied_workflow_yaml,
+ )
+ except Exception:
+ LOG.warning(
+ "copilot completion criteria decode failed; disabling active set for this turn",
+ completion_criteria_set_id=latest.completion_criteria_set_id,
+ goal_epoch=latest.goal_epoch,
+ exc_info=True,
+ )
+ return StoredCriteriaSnapshot(active=None, next_epoch=latest.goal_epoch + 1)
return StoredCriteriaSnapshot(active=active, next_epoch=latest.goal_epoch + 1)
diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.py
index ff8059cb6..9932db581 100644
--- a/skyvern/forge/sdk/schemas/workflow_copilot.py
+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py
@@ -1,3 +1,4 @@
+from dataclasses import dataclass
from datetime import datetime
from enum import StrEnum
from typing import Any, Literal
@@ -42,6 +43,19 @@ class WorkflowCopilotCompletionCriteriaSet(BaseModel):
modified_at: datetime
+CriteriaSetNonAdoptableReason = Literal["unknown_shape", "undecodable_v1_criteria"]
+
+
+@dataclass(frozen=True)
+class NonAdoptableCriteriaSet:
+ """A persisted criteria-set row whose shape cannot be decoded into the current
+ model; callers must treat the row as absent/superseded, never as an empty contract."""
+
+ reason: CriteriaSetNonAdoptableReason
+ completion_criteria_set_id: str
+ goal_epoch: int
+
+
class WorkflowCopilotChatSender(StrEnum):
USER = "user"
AI = "ai"
diff --git a/tests/unit/fixtures/workflow_copilot_completion_criteria_v1_row.json b/tests/unit/fixtures/workflow_copilot_completion_criteria_v1_row.json
new file mode 100644
index 000000000..db8bb0f88
--- /dev/null
+++ b/tests/unit/fixtures/workflow_copilot_completion_criteria_v1_row.json
@@ -0,0 +1,195 @@
+{
+ "completion_criteria_set_id": "wccs_100000000000000001",
+ "organization_id": "o_100000000000000001",
+ "workflow_copilot_chat_id": "wcc_100000000000000001",
+ "goal_epoch": 1,
+ "status": "active",
+ "criteria": {
+ "contract_version": 1,
+ "criteria": [
+ {
+ "id": "c0",
+ "outcome": "the workflow accepts business name, contact email, service address, and desired start date as reusable inputs",
+ "contingent_on": null,
+ "contingent_antecedent_output_path": null,
+ "deliverable_kind": null,
+ "declared_deliverable_kind": null,
+ "implicit": false,
+ "method_mandated": false,
+ "level": "definition",
+ "output_path": null,
+ "expected_output_value": null,
+ "expected_output_shape": null,
+ "requested_output_evidence_source": "runtime_output",
+ "kind": "outcome",
+ "terminal_action_family": null,
+ "classification_output_key": null,
+ "expected_classification": null,
+ "pinability": null,
+ "mint_disposition": "decidable"
+ },
+ {
+ "id": "c1",
+ "outcome": "the request is submitted when the reviewable form is complete",
+ "contingent_on": null,
+ "contingent_antecedent_output_path": null,
+ "deliverable_kind": null,
+ "declared_deliverable_kind": null,
+ "implicit": false,
+ "method_mandated": true,
+ "level": "run",
+ "output_path": null,
+ "expected_output_value": null,
+ "expected_output_shape": null,
+ "requested_output_evidence_source": "runtime_output",
+ "kind": "terminal_action",
+ "terminal_action_family": "application",
+ "classification_output_key": null,
+ "expected_classification": null,
+ "pinability": null,
+ "mint_disposition": "decidable"
+ },
+ {
+ "id": "c2",
+ "outcome": "the workflow returns the confirmation number",
+ "contingent_on": null,
+ "contingent_antecedent_output_path": null,
+ "deliverable_kind": null,
+ "declared_deliverable_kind": null,
+ "implicit": false,
+ "method_mandated": false,
+ "level": "run",
+ "output_path": null,
+ "expected_output_value": null,
+ "expected_output_shape": null,
+ "requested_output_evidence_source": "runtime_output",
+ "kind": "outcome",
+ "terminal_action_family": null,
+ "classification_output_key": null,
+ "expected_classification": null,
+ "pinability": null,
+ "mint_disposition": "degraded",
+ "mint_degrade": "undecidable_judgment"
+ },
+ {
+ "id": "c3",
+ "outcome": "the workflow returns the account number",
+ "contingent_on": null,
+ "contingent_antecedent_output_path": null,
+ "deliverable_kind": null,
+ "declared_deliverable_kind": null,
+ "implicit": false,
+ "method_mandated": false,
+ "level": "run",
+ "output_path": null,
+ "expected_output_value": null,
+ "expected_output_shape": null,
+ "requested_output_evidence_source": "runtime_output",
+ "kind": "outcome",
+ "terminal_action_family": null,
+ "classification_output_key": null,
+ "expected_classification": null,
+ "pinability": null,
+ "mint_disposition": "degraded",
+ "mint_degrade": "undecidable_judgment"
+ },
+ {
+ "id": "c4",
+ "outcome": "the workflow returns the selected start date",
+ "contingent_on": null,
+ "contingent_antecedent_output_path": null,
+ "deliverable_kind": null,
+ "declared_deliverable_kind": null,
+ "implicit": false,
+ "method_mandated": false,
+ "level": "run",
+ "output_path": null,
+ "expected_output_value": null,
+ "expected_output_shape": null,
+ "requested_output_evidence_source": "runtime_output",
+ "kind": "outcome",
+ "terminal_action_family": null,
+ "classification_output_key": null,
+ "expected_classification": null,
+ "pinability": null,
+ "mint_disposition": "degraded",
+ "mint_degrade": "undecidable_judgment"
+ },
+ {
+ "id": "c5",
+ "outcome": "the workflow returns the deposit amount",
+ "contingent_on": null,
+ "contingent_antecedent_output_path": null,
+ "deliverable_kind": null,
+ "declared_deliverable_kind": null,
+ "implicit": false,
+ "method_mandated": false,
+ "level": "run",
+ "output_path": null,
+ "expected_output_value": null,
+ "expected_output_shape": null,
+ "requested_output_evidence_source": "runtime_output",
+ "kind": "outcome",
+ "terminal_action_family": null,
+ "classification_output_key": null,
+ "expected_classification": null,
+ "pinability": null,
+ "mint_disposition": "degraded",
+ "mint_degrade": "undecidable_judgment"
+ },
+ {
+ "id": "c6",
+ "outcome": "the workflow returns the next owner",
+ "contingent_on": null,
+ "contingent_antecedent_output_path": null,
+ "deliverable_kind": null,
+ "declared_deliverable_kind": null,
+ "implicit": false,
+ "method_mandated": false,
+ "level": "run",
+ "output_path": null,
+ "expected_output_value": null,
+ "expected_output_shape": null,
+ "requested_output_evidence_source": "runtime_output",
+ "kind": "outcome",
+ "terminal_action_family": null,
+ "classification_output_key": null,
+ "expected_classification": null,
+ "pinability": null,
+ "mint_disposition": "degraded",
+ "mint_degrade": "undecidable_judgment"
+ },
+ {
+ "id": "c7",
+ "outcome": "the blocker is reported to the user",
+ "contingent_on": "the site only exposes an email/manual-service path instead of an online form",
+ "contingent_antecedent_output_path": "output.blocker",
+ "deliverable_kind": null,
+ "declared_deliverable_kind": null,
+ "implicit": true,
+ "method_mandated": false,
+ "level": "run",
+ "output_path": null,
+ "expected_output_value": null,
+ "expected_output_shape": null,
+ "requested_output_evidence_source": "runtime_output",
+ "kind": "outcome",
+ "terminal_action_family": null,
+ "classification_output_key": null,
+ "expected_classification": null,
+ "pinability": null,
+ "mint_disposition": "decidable"
+ }
+ ]
+ },
+ "source_turn_id": "00000000000000000000000000000001",
+ "source_goal_text": "build a reusable service-request intake workflow that submits the form and returns the confirmation details",
+ "consecutive_all_no_evidence": 0,
+ "tripwire_fired": false,
+ "last_fully_satisfied_workflow_yaml": null,
+ "superseded_by_set_id": null,
+ "superseded_at": null,
+ "supersede_reason": null,
+ "created_at": "2026-07-15T18:23:27.28843",
+ "modified_at": "2026-07-15T18:23:27.288434"
+}
diff --git a/tests/unit/test_workflow_copilot_completion_criteria_schema.py b/tests/unit/test_workflow_copilot_completion_criteria_schema.py
index c678f47f6..f53ddedc0 100644
--- a/tests/unit/test_workflow_copilot_completion_criteria_schema.py
+++ b/tests/unit/test_workflow_copilot_completion_criteria_schema.py
@@ -1,6 +1,49 @@
+import hashlib
+import json
from datetime import UTC, datetime
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock
-from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotCompletionCriteriaSet
+import pytest
+from sqlalchemy.ext.asyncio import AsyncEngine
+
+from skyvern.forge import app
+from skyvern.forge.sdk.copilot.completion_criteria_store import StoredCriteriaSnapshot
+from skyvern.forge.sdk.db.base_alchemy_db import BaseAlchemyDB
+from skyvern.forge.sdk.db.models import WorkflowCopilotCompletionCriteriaSetModel
+from skyvern.forge.sdk.db.repositories.workflow_parameters import WorkflowParametersRepository
+from skyvern.forge.sdk.routes.workflow_copilot import _load_completion_criteria_snapshot
+from skyvern.forge.sdk.schemas.workflow_copilot import (
+ NonAdoptableCriteriaSet,
+ WorkflowCopilotCompletionCriteriaSet,
+)
+from tests.unit.conftest import MockAsyncSessionCtx, make_mock_session
+
+_V1_ROW_FIXTURE = Path(__file__).parent / "fixtures" / "workflow_copilot_completion_criteria_v1_row.json"
+_V1_CRITERIA_PAYLOAD_MD5 = "8d79f38a1b6d136a0ecf7beaaa62f13f"
+
+
+def _load_v1_row_data() -> dict[str, Any]:
+ return json.loads(_V1_ROW_FIXTURE.read_text())
+
+
+def _make_row(**overrides: Any) -> WorkflowCopilotCompletionCriteriaSetModel:
+ data = _load_v1_row_data()
+ data.update(overrides)
+ return WorkflowCopilotCompletionCriteriaSetModel(**data)
+
+
+async def _load_latest(
+ row: WorkflowCopilotCompletionCriteriaSetModel,
+) -> WorkflowCopilotCompletionCriteriaSet | NonAdoptableCriteriaSet | None:
+ session = make_mock_session(row)
+ repo = WorkflowParametersRepository(session_factory=lambda: MockAsyncSessionCtx(session))
+ return await repo.get_latest_workflow_copilot_completion_criteria_set(
+ organization_id=row.organization_id,
+ workflow_copilot_chat_id=row.workflow_copilot_chat_id,
+ )
def test_completion_criteria_set_keeps_list_storage_shape() -> None:
@@ -21,3 +64,189 @@ def test_completion_criteria_set_keeps_list_storage_shape() -> None:
)
assert stored.criteria == criteria
+
+
+def test_v1_fixture_criteria_payload_matches_custody_md5() -> None:
+ data = _load_v1_row_data()
+ payload_md5 = hashlib.md5(json.dumps(data["criteria"]).encode()).hexdigest()
+ assert payload_md5 == _V1_CRITERIA_PAYLOAD_MD5
+
+
+async def test_loader_adopts_v1_envelope_row_preserving_recorded_criteria() -> None:
+ data = _load_v1_row_data()
+ loaded = await _load_latest(WorkflowCopilotCompletionCriteriaSetModel(**data))
+
+ assert isinstance(loaded, WorkflowCopilotCompletionCriteriaSet)
+ assert loaded.completion_criteria_set_id == data["completion_criteria_set_id"]
+ assert loaded.goal_epoch == data["goal_epoch"]
+ assert loaded.status == "active"
+ assert loaded.criteria == data["criteria"]["criteria"]
+ assert len(loaded.criteria) == 8
+ assert [criterion["id"] for criterion in loaded.criteria] == [f"c{i}" for i in range(8)]
+ assert loaded.source_turn_id == data["source_turn_id"]
+ assert loaded.source_goal_text == data["source_goal_text"]
+ assert loaded.source_goal_text is not None
+ assert loaded.created_at is not None
+ assert loaded.modified_at is not None
+
+
+async def test_loader_adopts_current_bare_list_row_unchanged() -> None:
+ criteria = [{"id": "c0", "outcome": "done", "pinability": "pinned"}]
+ loaded = await _load_latest(_make_row(criteria=criteria))
+
+ assert isinstance(loaded, WorkflowCopilotCompletionCriteriaSet)
+ assert loaded.criteria == criteria
+
+
+ "criteria_value",
+ [
+ {"contract_version": 2, "criteria": [{"id": "c0", "outcome": "done"}]},
+ {"criteria": [{"id": "c0", "outcome": "done"}]},
+ {"contract_version": 1, "criteria": "not-a-list"},
+ {"contract_version": 1, "criteria": [{"id": "c1", "outcome": "done", "pinability": []}]},
+ "not-json-criteria",
+ 7,
+ [1, 2],
+ ],
+)
+async def test_loader_returns_unknown_shape_disposition_without_raising(criteria_value: Any) -> None:
+ loaded = await _load_latest(_make_row(criteria=criteria_value))
+
+ assert isinstance(loaded, NonAdoptableCriteriaSet)
+ assert loaded.reason == "unknown_shape"
+ assert loaded.completion_criteria_set_id == "wccs_100000000000000001"
+ assert loaded.goal_epoch == 1
+
+
+ "inner",
+ [
+ [],
+ [{}],
+ [{"id": "c0", "outcome": "done"}, {"bogus": True}],
+ ],
+)
+async def test_loader_rejects_v1_envelope_whose_criteria_do_not_fully_decode(inner: list[Any]) -> None:
+ loaded = await _load_latest(_make_row(criteria={"contract_version": 1, "criteria": inner}))
+
+ assert isinstance(loaded, NonAdoptableCriteriaSet)
+ assert loaded.reason == "undecodable_v1_criteria"
+
+
+ "criterion",
+ [
+ {"id": "c0", "outcome": "done", "kind": "speculative_future_kind"},
+ {"id": "c0", "outcome": "done", "level": "epic"},
+ ],
+)
+async def test_loader_rejects_v1_envelope_whose_enum_value_was_coerced(criterion: dict[str, Any]) -> None:
+ loaded = await _load_latest(_make_row(criteria={"contract_version": 1, "criteria": [criterion]}))
+
+ assert isinstance(loaded, NonAdoptableCriteriaSet)
+ assert loaded.reason == "undecodable_v1_criteria"
+
+
+async def test_loader_returns_highest_epoch_row_over_lower_epoch_non_adoptable(sqlite_engine: AsyncEngine) -> None:
+ db = BaseAlchemyDB(sqlite_engine)
+ repo = WorkflowParametersRepository(db.Session)
+ data = _load_v1_row_data()
+ now = datetime.now(UTC)
+ malformed = WorkflowCopilotCompletionCriteriaSetModel(
+ completion_criteria_set_id="wccs_lower_epoch",
+ organization_id=data["organization_id"],
+ workflow_copilot_chat_id=data["workflow_copilot_chat_id"],
+ goal_epoch=1,
+ status="active",
+ criteria={"contract_version": 99, "criteria": [{"id": "c0", "outcome": "done"}]},
+ created_at=now,
+ modified_at=now,
+ )
+ adopted = WorkflowCopilotCompletionCriteriaSetModel(
+ completion_criteria_set_id="wccs_higher_epoch",
+ organization_id=data["organization_id"],
+ workflow_copilot_chat_id=data["workflow_copilot_chat_id"],
+ goal_epoch=2,
+ status="active",
+ criteria=data["criteria"],
+ source_turn_id=data["source_turn_id"],
+ source_goal_text=data["source_goal_text"],
+ created_at=now,
+ modified_at=now,
+ )
+ async with db.Session() as session:
+ session.add_all([malformed, adopted])
+ await session.commit()
+
+ loaded = await repo.get_latest_workflow_copilot_completion_criteria_set(
+ organization_id=data["organization_id"],
+ workflow_copilot_chat_id=data["workflow_copilot_chat_id"],
+ )
+
+ assert isinstance(loaded, WorkflowCopilotCompletionCriteriaSet)
+ assert loaded.completion_criteria_set_id == "wccs_higher_epoch"
+ assert loaded.goal_epoch == 2
+ assert len(loaded.criteria) == 8
+
+
+async def test_loader_absorbs_v1_scaffold_validation_failure_as_non_adoptable() -> None:
+ loaded = await _load_latest(_make_row(created_at=None))
+
+ assert isinstance(loaded, NonAdoptableCriteriaSet)
+ assert loaded.reason == "unknown_shape"
+
+
+async def test_snapshot_maps_non_adoptable_to_no_active_set_and_next_epoch(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ disposition = NonAdoptableCriteriaSet(
+ reason="unknown_shape",
+ completion_criteria_set_id="wccs_x",
+ goal_epoch=3,
+ )
+ monkeypatch.setattr(
+ app.DATABASE,
+ "workflow_params",
+ SimpleNamespace(get_latest_workflow_copilot_completion_criteria_set=AsyncMock(return_value=disposition)),
+ )
+ chat = SimpleNamespace(organization_id="o_1", workflow_copilot_chat_id="wcc_1")
+
+ snapshot = await _load_completion_criteria_snapshot(chat)
+
+ assert snapshot == StoredCriteriaSnapshot(active=None, next_epoch=4)
+
+
+async def test_snapshot_absorbs_adopted_row_criteria_decode_failure(monkeypatch: pytest.MonkeyPatch) -> None:
+ now = datetime.now(UTC)
+ adopted = WorkflowCopilotCompletionCriteriaSet.model_validate(
+ {
+ "completion_criteria_set_id": "wccs_2",
+ "organization_id": "o_1",
+ "workflow_copilot_chat_id": "wcc_1",
+ "goal_epoch": 2,
+ "status": "active",
+ "criteria": [{"id": "c0", "outcome": "done", "pinability": []}],
+ "created_at": now,
+ "modified_at": now,
+ }
+ )
+ monkeypatch.setattr(
+ app.DATABASE,
+ "workflow_params",
+ SimpleNamespace(get_latest_workflow_copilot_completion_criteria_set=AsyncMock(return_value=adopted)),
+ )
+ chat = SimpleNamespace(organization_id="o_1", workflow_copilot_chat_id="wcc_1")
+
+ snapshot = await _load_completion_criteria_snapshot(chat)
+
+ assert snapshot == StoredCriteriaSnapshot(active=None, next_epoch=3)