Files
cleveragents-core/robot/helper_actor_registry_persistence.py
hurui200320 ee2024046f
CI / lint (push) Successful in 37s
CI / quality (push) Successful in 53s
CI / typecheck (push) Successful in 57s
CI / security (push) Successful in 58s
CI / helm (push) Successful in 25s
CI / push-validation (push) Successful in 25s
CI / build (push) Successful in 30s
CI / integration_tests (push) Successful in 4m22s
CI / e2e_tests (push) Successful in 4m17s
CI / unit_tests (push) Successful in 5m10s
CI / docker (push) Successful in 1m30s
CI / coverage (push) Successful in 12m18s
CI / status-check (push) Successful in 1s
CI / benchmark-regression (push) Has been skipped
CI / benchmark-publish (push) Has been cancelled
fix(plan): upsert action arguments during plan use to avoid UNIQUE constraint violation (#4197)
## Summary

`agents plan use` crashed with `sqlite3.IntegrityError: UNIQUE constraint failed: action_arguments.action_name, action_arguments.name` when the action had arguments already registered via `action create`. The root cause was `ActionRepository.update()` using SQLAlchemy's relationship `.clear()` + `.append()` pattern, which deferred the DELETE and processed the INSERT first — triggering a UNIQUE constraint violation when the same `(action_name, name)` pair was being re-inserted.

## Approach

Replace the `.clear()` + `.append()` pattern with explicit bulk `sa_delete()` + `session.flush()` before re-inserting child rows for both `action_arguments` and `action_invariants`. After the flush, expire the relationship collections with `session.expire(row, ["arguments_rel", "invariants_rel"])` so SQLAlchemy reloads from the now-empty database state before appending replacements. This avoids stale identity map references and guarantees the DELETE is committed before any INSERT.

## Key Changes

### Bug fix (`src/cleveragents/infrastructure/database/repositories.py`)
- `ActionRepository.update()` now uses `sa_delete(ActionArgumentModel)` and `sa_delete(ActionInvariantModel)` with `synchronize_session=False`, followed by `session.flush()`, before re-inserting child rows.
- Targeted `session.expire(row, ["arguments_rel", "invariants_rel"])` replaces the removed `.clear()` calls to force collection reload.

### Schema parity (`src/cleveragents/infrastructure/database/models.py`)
- Added `UniqueConstraint("action_name", "position")` to `ActionInvariantModel`.
- Added `UniqueConstraint("action_name", "name")`, `CheckConstraint` for `arg_type`, and `CheckConstraint` for `requirement` to `ActionArgumentModel`.

### Alembic migration (`alembic/versions/a5_006_action_invariants_unique_constraint.py`)
- New migration adds all four constraints to both `action_invariants` and `action_arguments` tables.
- Includes deduplication guards and data normalization so the upgrade succeeds on existing databases with invalid or duplicate rows.
- Uses `batch_alter_table` for SQLite compatibility.

### Tests
- **Behave** (`features/plan_use_action_args_integrity.feature`): 6 scenarios covering the core bug path, zero-argument regression, multiple arguments, reusable action double-use, non-reusable action archival with invariants, and direct repository update.
- **Robot** (`robot/plan_use_action_args_integrity.robot`): Integration test mirroring the Behave scenarios via a helper script.
- **Shared factory** (`features/mocks/test_uow_factory.py`): Extracted `build_test_uow()` from both test suites into a single shared module to eliminate duplication (DRY).

### Minor
- Updated `src/cleveragents/domain/repositories/__init__.py` docstring from table format to bullet list (conflict resolution from rebase).

Closes #4174

Reviewed-on: #4197
Reviewed-by: HAL 9000 <HAL9000@cleverthis.com>
Co-authored-by: Rui Hu <rui.hu@cleverthis.com>
Co-committed-by: Rui Hu <rui.hu@cleverthis.com>
2026-04-09 06:11:39 +00:00

82 lines
2.3 KiB
Python

"""Helper script for actor registry persistence Robot tests.
Invoked by Robot Framework via ``Run Process`` to verify domain-model
behaviour in a subprocess with the real package installed.
Usage::
python helper_actor_registry_persistence.py <test_name>
Where *test_name* is one of:
- ``list_yaml_metadata`` - verify yaml_text / compiled_metadata round-trip
- ``schema_version_default`` - verify default schema_version is ``"1.0"``
- ``namespaced_name`` - verify a namespaced name is preserved
"""
from __future__ import annotations
import sys
def _test_list_yaml_metadata() -> None:
from cleveragents.domain.models.core.actor import Actor
actor = Actor(
name="local/test",
provider="openai",
model="gpt-4",
config_hash=Actor.compute_hash({}),
yaml_text="name: local/test\nprovider: openai\nmodel: gpt-4",
schema_version="1.0",
compiled_metadata={"nodes": 2},
)
assert actor.name == "local/test", f"Expected 'local/test', got {actor.name!r}"
assert actor.schema_version == "1.0", (
f"Expected schema_version '1.0', got {actor.schema_version!r}"
)
assert actor.yaml_text is not None, "yaml_text should not be None"
assert actor.compiled_metadata is not None, "compiled_metadata should not be None"
print("yaml-metadata-ok")
def _test_schema_version_default() -> None:
from cleveragents.domain.models.core.actor import Actor
actor = Actor(
name="local/default-ver",
provider="openai",
model="gpt-4",
config_hash=Actor.compute_hash({}),
)
assert actor.schema_version == "1.0", (
f"Expected schema_version '1.0', got {actor.schema_version!r}"
)
print("schema-version-default-ok")
def _test_namespaced_name() -> None:
from cleveragents.domain.models.core.actor import Actor
actor = Actor(
name="local/valid-name",
provider="openai",
model="gpt-4",
config_hash=Actor.compute_hash({}),
)
assert actor.name == "local/valid-name", (
f"Expected name 'local/valid-name', got {actor.name!r}"
)
print("namespaced-name-ok")
_TESTS = {
"list_yaml_metadata": _test_list_yaml_metadata,
"schema_version_default": _test_schema_version_default,
"namespaced_name": _test_namespaced_name,
}
if __name__ == "__main__":
name = sys.argv[1]
_TESTS[name]()