Files
temp/features/steps/plan_phase_migration_steps.py
CoreRasurae a4a6b061a6 fix(db): align v3_plans schema with specification DDL
Aligned v3_plans table with specification DDL:

1. Added effective_profile_snapshot column (TEXT NOT NULL) for
   storing frozen JSON snapshot of automation profile at plan
   creation time.  Added Pydantic field_validator ensuring the
   value is well-formed JSON.  Validator catches RecursionError
   for deeply nested JSON, consistent with automation_profile
   deserialization hardening.  Validator error message uses
   length-only to avoid potential information disclosure.
   Documented that the default "{}" exists for backward
   compatibility; new plans should explicitly set the snapshot.

2. Made root_plan_id NOT NULL — root plans self-reference their
   own plan_id, child plans reference the root ancestor.  Added
   explicit ondelete="RESTRICT" FK policy for consistency with
   other FKs in the model.  Documented known FK policy drift
   between ORM model (RESTRICT) and migrated databases (retained
   SET NULL) in the migration; data integrity is preserved by
   the NOT NULL constraint regardless.  Moved root_plan_id
   self-reference resolution into a PlanIdentity model_validator
   so the domain model is consistent with the DB NOT NULL
   constraint before and after persistence (previously the
   resolution only happened in from_domain(), creating an
   asymmetry where root_plan_id was None in-memory but non-null
   after round-tripping through the database).

3. Made automation_profile NOT NULL with default "balanced".

4. Documented intentional deviation: phase default is "action"
   (code) vs "strategize" (spec) because the Action phase was
   added as a pre-Strategize setup step.

5. Created Alembic migration with backfill logic for existing
   rows.  Root-ancestor backfill uses level-by-level propagation
   with a parent-readiness guard to correctly resolve plans at
   arbitrary hierarchy depth (3+ levels).  Added safety bound
   (max 100 iterations) with logged error on exhaustion to guard
   against cycles in parent_plan_id.  Merged batch_alter_table
   operations to avoid redundant full-table copies in SQLite
   batch mode.  Migration backfill also handles empty-string
   automation_profile values.  Documented downgrade limitation
   (backfill is not reversible).  Orphan-row fallback now logs
   affected row count at WARNING level.  Migration cycle-detection
   now logs affected plan_id values before the orphan fallback
   overwrites them.  All migration SQL uses sa.text() for
   consistency with SQLAlchemy best practices.

6. Hardened automation_profile deserialization in to_domain() to
   catch ValueError (invalid StrEnum provenance), Pydantic
   ValidationError, and RecursionError (deeply nested JSON) in
   addition to JSONDecodeError and KeyError, preventing
   unreadable plans from corrupted DB rows.  Applied the same
   defensive deserialization pattern to effective_profile_snapshot
   in to_domain(): corrupted JSON falls back to '{}' with a
   WARNING log instead of crashing the read path.  Added TypeError
   to the effective_profile_snapshot exception list in to_domain()
   for consistency with the Pydantic validator.  Logging of
   unparseable values uses length only to avoid potential
   information disclosure.

7. Used explicit None check (is not None) instead of truthiness
   for root_plan_id resolution in from_domain(), for
   effective_profile_snapshot in to_domain(), and in
   _serialize_automation_profile() for consistency.

8. Documented intentional column naming conventions vs spec DDL
   (e.g. automation_profile vs automation_profile_name, *_actor
   vs *_actor_name, processing_state vs state, v3_plans vs
   plans).  Documented the semantic difference: automation_profile
   stores either a bare name or structured JSON with provenance,
   whereas the spec automation_profile_name stores a plain name.

9. Fixed benchmark plan constructors
   (plan_phase_migration_bench.py) that were missing the now-
   required root_plan_id and effective_profile_snapshot fields.

10. Replaced defensive getattr() with direct attribute access for
    effective_profile_snapshot in from_domain() and update(),
    since the field is now defined on the Plan domain model.

11. Fixed Any type annotation in test helper _make_plan() to use
    AutomationProfileRef | None for proper type safety.

12. Added BDD scenarios for PlanIdentity self-reference
    resolution, NULL effective_profile_snapshot constraint
    enforcement, valid-JSON-missing-profile_name-key
    deserialization, invalid-JSON and empty-string snapshot
    rejection by Pydantic validator, and corrupted
    effective_profile_snapshot DB fallback in to_domain().

13. Extracted default automation profile name to a module-level
    constant (DEFAULT_AUTOMATION_PROFILE) to reduce sentinel
    duplication across models.py and repositories.py.

14. Centralised automation-profile serialisation into
    LifecyclePlanModel._serialize_automation_profile() to
    eliminate duplication between from_domain() and
    LifecyclePlanRepository.update().

15. Fixed to_domain() root_plan_id type cast from str | None
    to str, reflecting the NOT NULL column constraint.

16. Added PlanIdentity model_validator that resolves None
    root_plan_id to plan_id at domain construction time, ensuring
    the domain model honours the spec DDL NOT NULL constraint
    regardless of persistence state.  Simplified from_domain()
    root resolution accordingly.

ISSUES CLOSED: #921
2026-03-30 23:40:36 +01:00

222 lines
7.4 KiB
Python

"""Step definitions for plan phase/state constraint rebaseline tests."""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from behave import given, then, when
from sqlalchemy import create_engine, text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, sessionmaker
from cleveragents.infrastructure.database.models import (
Base,
LifecycleActionModel,
LifecyclePlanModel,
)
_VALID_ULID_PLAN = "01HV000000000000000000PH01"
_VALID_ULID_COUNTER = 0
def _next_ulid() -> str:
global _VALID_ULID_COUNTER
_VALID_ULID_COUNTER += 1
suffix = str(_VALID_ULID_COUNTER).zfill(4)
return f"01HV0000000000000000PH{suffix}"
def _now_iso() -> str:
return datetime.now(tz=UTC).isoformat()
def _ensure_action(session: Session) -> None:
"""Ensure a parent action exists for FK references."""
existing = (
session.query(LifecycleActionModel)
.filter_by(namespaced_name="local/phase-test-action")
.first()
)
if existing is not None:
return
action = LifecycleActionModel()
action.namespaced_name = "local/phase-test-action"
action.namespace = "local"
action.name = "phase-test-action"
action.description = "Test action for phase migration"
action.definition_of_done = "Done"
action.strategy_actor = "local/s"
action.execution_actor = "local/e"
action.state = "available"
action.tags_json = "[]"
action.created_at = _now_iso()
action.updated_at = _now_iso()
session.add(action)
session.commit()
@given("the plan phase rebaseline database is initialized")
def step_plan_phase_rebaseline_db_init(context: Any) -> None:
"""Set up an in-memory database with the schema including new constraints."""
engine = create_engine("sqlite:///:memory:")
# Enable FK enforcement
from sqlalchemy import event
@event.listens_for(engine, "connect")
def set_sqlite_pragma(dbapi_connection: Any, _: Any) -> None:
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
Base.metadata.create_all(engine)
factory = sessionmaker(bind=engine)
session = factory()
_ensure_action(session)
context.phase_rebaseline_engine = engine
context.phase_rebaseline_session = session
@when('I insert a plan with phase "{phase}" and state "{state}"')
def step_insert_plan_with_phase_and_state(context: Any, phase: str, state: str) -> None:
"""Insert a plan with the specified phase and state."""
session: Session = context.phase_rebaseline_session
ulid = _next_ulid()
now = _now_iso()
plan = LifecyclePlanModel()
plan.plan_id = ulid
plan.root_plan_id = ulid
plan.action_name = "local/phase-test-action"
plan.namespaced_name = "local/phase-test-plan"
plan.namespace = "local"
plan.phase = phase
plan.processing_state = state
plan.description = "Test plan"
plan.tags_json = "[]"
plan.effective_profile_snapshot = "{}"
plan.created_at = now
plan.updated_at = now
try:
session.add(plan)
session.commit()
context.phase_rebaseline_result = "ok"
context.phase_rebaseline_plan_id = ulid
except (IntegrityError, Exception) as exc:
session.rollback()
context.phase_rebaseline_result = "error"
context.phase_rebaseline_error = str(exc)
@when('I try to insert a plan with phase "{phase}" and state "{state}"')
def step_try_insert_plan_with_phase_and_state(
context: Any, phase: str, state: str
) -> None:
"""Try to insert a plan with the specified phase and state, expecting failure."""
session: Session = context.phase_rebaseline_session
ulid = _next_ulid()
now = _now_iso()
try:
session.execute(
text(
"INSERT INTO v3_plans "
"(plan_id, action_name, namespaced_name, namespace, "
"phase, processing_state, description, tags_json, "
"created_at, updated_at) "
"VALUES (:pid, :aname, :nname, :ns, :phase, :state, "
":desc, :tags, :cat, :uat)"
),
{
"pid": ulid,
"aname": "local/phase-test-action",
"nname": "local/try-plan",
"ns": "local",
"phase": phase,
"state": state,
"desc": "Test plan",
"tags": "[]",
"cat": now,
"uat": now,
},
)
session.commit()
context.phase_rebaseline_result = "ok"
except (IntegrityError, Exception) as exc:
session.rollback()
context.phase_rebaseline_result = "error"
context.phase_rebaseline_error = str(exc)
@when("I insert a plan using default phase")
def step_insert_plan_default_phase(context: Any) -> None:
"""Insert a plan without specifying a phase to test the ORM default."""
session: Session = context.phase_rebaseline_session
ulid = _next_ulid()
now = _now_iso()
# Use ORM to create plan without specifying phase — should default to 'action'
plan = LifecyclePlanModel()
plan.plan_id = ulid
plan.root_plan_id = ulid
plan.action_name = "local/phase-test-action"
plan.namespaced_name = "local/default-phase-plan"
plan.namespace = "local"
plan.description = "Default phase plan"
plan.tags_json = "[]"
plan.effective_profile_snapshot = "{}"
plan.created_at = now
plan.updated_at = now
session.add(plan)
session.commit()
context.phase_rebaseline_plan_id = ulid
@then('the plan should be persisted successfully with phase "{phase}"')
def step_verify_plan_persisted_phase(context: Any, phase: str) -> None:
"""Verify the plan was persisted with the expected phase."""
assert context.phase_rebaseline_result == "ok", (
f"Expected ok, got {context.phase_rebaseline_result}"
)
session: Session = context.phase_rebaseline_session
plan = (
session.query(LifecyclePlanModel)
.filter_by(plan_id=context.phase_rebaseline_plan_id)
.one()
)
assert plan.phase == phase
@then('the plan should be persisted successfully with state "{state}"')
def step_verify_plan_persisted_state(context: Any, state: str) -> None:
"""Verify the plan was persisted with the expected state."""
assert context.phase_rebaseline_result == "ok", (
f"Expected ok, got {context.phase_rebaseline_result}"
)
session: Session = context.phase_rebaseline_session
plan = (
session.query(LifecyclePlanModel)
.filter_by(plan_id=context.phase_rebaseline_plan_id)
.one()
)
assert plan.processing_state == state
@then("the insert should fail with a constraint violation")
def step_verify_constraint_violation(context: Any) -> None:
"""Verify the insert failed."""
assert context.phase_rebaseline_result == "error", (
f"Expected error, got {context.phase_rebaseline_result}"
)
@then('the rebaselined plan phase should be "{phase}"')
def step_verify_rebaselined_plan_phase_default(context: Any, phase: str) -> None:
"""Verify the plan's phase matches the expected value."""
session: Session = context.phase_rebaseline_session
plan = (
session.query(LifecyclePlanModel)
.filter_by(plan_id=context.phase_rebaseline_plan_id)
.one()
)
assert plan.phase == phase, f"Expected phase '{phase}', got '{plan.phase}'"