Files
cleveragents-core/robot/helper_sandbox_integration.py
T
Luis Mendes 7f078f75a5
CI / benchmark-publish (pull_request) Has been skipped
CI / lint (pull_request) Successful in 28s
CI / security (pull_request) Successful in 1m8s
CI / build (pull_request) Successful in 20s
CI / helm (pull_request) Successful in 34s
CI / quality (pull_request) Successful in 3m53s
CI / integration_tests (pull_request) Successful in 4m2s
CI / typecheck (pull_request) Successful in 4m9s
CI / unit_tests (pull_request) Successful in 4m48s
CI / docker (pull_request) Successful in 1m19s
CI / e2e_tests (pull_request) Successful in 9m47s
CI / coverage (pull_request) Successful in 11m41s
CI / status-check (pull_request) Successful in 1s
CI / quality (push) Successful in 52s
CI / lint (push) Successful in 3m18s
CI / build (push) Successful in 20s
CI / typecheck (push) Successful in 3m56s
CI / helm (push) Successful in 22s
CI / security (push) Successful in 4m15s
CI / unit_tests (push) Successful in 4m39s
CI / docker (push) Successful in 18s
CI / integration_tests (push) Successful in 6m56s
CI / e2e_tests (push) Successful in 12m34s
CI / coverage (push) Successful in 11m39s
CI / status-check (push) Successful in 1s
CI / benchmark-regression (push) Has been skipped
CI / benchmark-publish (push) Successful in 30m10s
CI / benchmark-regression (pull_request) Successful in 57m33s
fix(sandbox): make commit_all atomic per specification
Changed SandboxManager.commit_all() from partial-commit semantics to
all-or-nothing atomic operation per specification requirement. On
partial failure, already-committed sandboxes are rolled back. Error
reporting indicates which sandbox failed and what was rolled back.
Added Behave scenarios verifying atomicity guarantee.

Hardened atomicity guarantees after code review:

- commit_all and _rollback_committed catch Exception (not just
  SandboxError) so unexpected errors cannot bypass rollback.
  Non-SandboxError exceptions are wrapped in a new AtomicCommitError
  (chaining the original as __cause__) that carries rolled_back_ids
  and failed_rollback_ids attributes so callers can programmatically
  determine rollback outcomes.

- _rollback_committed returns both rolled_back_ids and
  failed_rollback_ids; the error result metadata now carries
  both "rolled_back" and "rollback_failed" keys.

- _rollback_committed iterates in reverse (LIFO) order following
  the standard transaction-log undo pattern.  Clarified in
  docstring that this is distinct from the specification DAG-based
  "top-down" rollback ordering (line 24632).

- TransactionSandbox.rollback() from COMMITTED now raises
  SandboxRollbackError (database commits are irreversible)
  instead of silently transitioning to ROLLED_BACK.

- TransactionSandbox is now classified as non-rollbackable in
  commit_all alongside NoSandbox and committed last in the batch,
  since database COMMIT is irreversible.  Docstring corrected to
  match the raising behavior.

- CopyOnWriteSandbox and OverlaySandbox rollback-from-COMMITTED
  uses rename-based safe_restore() to prevent data loss when
  the copytree step fails after the original was removed.

- CopyOnWriteSandbox and OverlaySandbox rollback() now catches
  Exception (not just OSError), matching the broader catch used
  in _rollback_committed, so non-OSError exceptions from
  safe_restore set the status to ERRORED correctly.

- Extracted shared _fs_utils module (backup_directory,
  safe_restore, compute_diff) with symlink, permission, and
  timestamp preservation (including directory timestamps),
  replacing duplicated per-class _backup_directory and
  _compute_diff methods.

- backup_directory defers directory permissions and timestamps
  to a bottom-up post-walk pass, fixing incorrect mtime
  preservation (POSIX file creation inside a directory overwrites
  its mtime) and preventing restrictive source permissions from
  blocking backup writes.

- backup_directory skips non-regular files (FIFOs, sockets,
  device files) with a warning to prevent hangs on special files.

- CopyOnWriteSandbox and OverlaySandbox commit() now attempts
  to restore the original from the pre-commit backup when the
  file-copy phase fails midway, preventing partial corruption.
  If the restore itself fails the backup is preserved for manual
  recovery (cleanup() still removes it).

- CopyOnWriteSandbox and OverlaySandbox commit() error handler
  now catches Exception (not just OSError) so that unexpected
  errors during the file-copy phase also trigger pre-commit
  backup restoration, preventing partial corruption of the
  original directory.

- Pre-commit backup exception handler catches Exception (not
  just OSError) preventing temp directory leaks on non-OSError
  failures from backup_directory.

- Fixed _pre_commit_backup assignment timing: the backup
  reference is now assigned only AFTER backup_directory()
  succeeds, preventing safe_restore() from corrupting an intact
  original with a partial backup when backup_directory() fails
  (e.g. disk full).

- Rollback from COMMITTED with no pre-commit backup (no changes
  were applied) is now a no-op instead of raising
  SandboxRollbackError, preventing false rollback-failure
  reports in commit_all error metadata.

- commit_all logs a warning when NoSandbox or TransactionSandbox
  instances are present in the batch since their changes cannot
  be rolled back, which breaks the atomicity guarantee.

- Pre-commit backup is skipped when compute_diff returns no
  changes, avoiding a full directory copy for no-op commits.

- GitWorktreeSandbox clears _pre_merge_commit on commit failure
  so the stale value cannot be used by future code.

- commit_all docstring documents Raises clause for AtomicCommitError
  exception wrapping behavior.

- GitWorktreeSandbox.rollback() docstring warns about
  multi-worktree safety when rolling back from COMMITTED.

- Updated SandboxStatus transition diagram in protocol.py to
  clearly show the COMMITTED -> ROLLED_BACK path.

- Added spec-contradiction note (line 45938 vs 19193) in
  commit_all docstring.

- OverlaySandbox rollback from COMMITTED now properly remounts
  OverlayFS for real overlay (unmount, clean upper/work dirs,
  remount) and uses dirs_exist_ok=True for userspace fallback
  to prevent FileExistsError if rmtree silently fails.  The
  merged directory is reset from the restored original,
  preventing stale pre-rollback data from being exposed on
  re-activation via get_path() (which allows ROLLED_BACK status).

- OverlaySandbox rollback from COMMITTED now raises
  SandboxRollbackError if the OverlayFS unmount fails,
  preventing a double-mount attempt that would leave the
  sandbox in an inconsistent state.

- OverlaySandbox rollback from ACTIVE now uses dirs_exist_ok=True
  for userspace fallback to prevent FileExistsError when rmtree
  with ignore_errors=True silently fails.

- CopyOnWriteSandbox rollback from ACTIVE now uses
  dirs_exist_ok=True in copytree to prevent FileExistsError
  when rmtree with ignore_errors=True silently fails, matching
  the fix already applied to OverlaySandbox.

- Non-rollbackable sandboxes (NoSandbox, TransactionSandbox) are
  committed last in the batch so that all rollbackable sandboxes
  commit first; if any rollbackable sandbox fails, none of the
  non-rollbackable sandboxes will have committed yet.

- Moved NoSandbox and TransactionSandbox imports to module level
  in manager.py (no circular dependency exists).

- Pre-commit backups are now created on the same filesystem as
  the original directory (using dir= argument to mkdtemp),
  avoiding cross-device copy overhead and ensuring os.rename
  compatibility.

- safe_restore now renames the target into the mkdtemp directory
  instead of removing the mkdtemp dir first, eliminating the
  residual TOCTOU window between rmdir and rename.

- safe_restore catches BaseException (not just OSError) to
  ensure the original directory is always renamed back on
  unexpected errors, preventing the original from being left
  in the renamed-aside state.

- Added AtomicCommitError exception class to protocol.py
  carrying rolled_back_ids and failed_rollback_ids attributes.

- Exported AtomicCommitError from sandbox package __init__.py
  so callers can import it from the public API.

- Added BDD scenarios: LIFO rollback order, AtomicCommitError
  wrapping with RuntimeError cause and rollback metadata,
  _fs_utils backup/restore coverage, no-change commit rollback
  success, directory timestamp preservation, OverlaySandbox
  merged dir reset after COMMITTED rollback,
  CopyOnWriteSandbox rollback from COMMITTED restores original,
  GitWorktreeSandbox rollback from COMMITTED undoes merge,
  TransactionSandbox rollback from COMMITTED raises
  SandboxRollbackError about irreversible commit.

ISSUES CLOSED: #925

Post-review hardening (PR #1146 review findings):

- OverlaySandbox rollback from COMMITTED with no backup (no-op)
  now skips the merged directory reset entirely, preventing
  unnecessary unmount/remount or re-copy that could fail and
  turn a harmless no-op rollback into a SandboxRollbackError
  during commit_all atomic recovery.

- OverlaySandbox rollback no longer double-wraps
  SandboxRollbackError: the outer except Exception handler
  now has a preceding except SandboxRollbackError clause that
  re-raises directly, avoiding a confusing double-wrapped
  error chain.

- CopyOnWriteSandbox.get_path() now accepts ROLLED_BACK status
  for consistency with OverlaySandbox and the protocol status
  transition table (ROLLED_BACK -> ACTIVE).

- CopyOnWriteSandbox rollback from COMMITTED now resets the
  sandbox copy from the restored original via rmtree+copytree,
  preventing stale pre-rollback modifications from being
  exposed on re-activation.

- rollback_all now catches Exception (not just SandboxError)
  so that unexpected rollback errors do not prevent remaining
  sandboxes from being rolled back, consistent with the pattern
  already used in _rollback_committed.

- commit_all docstring now documents a thread-safety warning:
  the method is not safe for concurrent calls on the same
  plan_id since sandbox commit/rollback runs outside the lock.

- Fixed CHANGELOG.md whitespace inconsistencies (double leading
  spaces on two lines).

Post-review hardening round 2 (PR #1146 automated review):

- safe_restore now uses os.rename (O(1) atomic rename) instead
  of shutil.copytree (O(n) recursive copy) for the main restore
  path, since backup and target are always on the same
  filesystem.  This eliminates the ENOTEMPTY bug where a partial
  copytree failure left target_path partially populated, causing
  the recovery os.rename to fail and strand the original in the
  stale temp directory.

- OverlaySandbox.get_path() now transitions ROLLED_BACK to
  ACTIVE, matching CopyOnWriteSandbox and the protocol
  transition table (ROLLED_BACK -> ACTIVE).

- GitWorktreeSandbox.get_path() now accepts ROLLED_BACK status
  for consistency with all other sandbox implementations and
  the protocol transition table (ROLLED_BACK -> ACTIVE).

- rollback_all now also handles sandboxes in COMMITTED status
  (not just ACTIVE), consistent with the state machine allowing
  COMMITTED -> ROLLED_BACK.

- cleanup_all now catches Exception (not just SandboxError) so
  a single unexpected error does not abort cleanup of remaining
  sandboxes, consistent with _rollback_committed and
  rollback_all.

- Restructured CHANGELOG entry from a single ~90-line paragraph
  into structured sub-bullets for readability.

- Added BDD scenarios: no-op rollback from COMMITTED for
  CopyOnWriteSandbox and OverlaySandbox (zero-change commit),
  commit ordering verification (rollbackable before
  non-rollbackable).

Post-review hardening round 3 (PR #1146 deep automated review):

- cleanup_abandoned now catches Exception (not just SandboxError)
  so that unexpected errors (e.g. raw OSError, PermissionError)
  do not crash the loop and prevent remaining abandoned sandboxes
  from being cleaned up, consistent with cleanup_all,
  rollback_all, and _rollback_committed.

- OverlaySandbox._mount_overlay() now catches
  subprocess.TimeoutExpired (in addition to CalledProcessError
  and OSError), preventing create() from leaving the sandbox in
  PENDING status when mount hangs beyond the timeout.

- OverlaySandbox._unmount_overlay() now catches
  subprocess.TimeoutExpired (in addition to CalledProcessError
  and OSError), preventing cleanup() from leaving the sandbox
  in a zombie state when umount hangs beyond the timeout.

- OverlaySandbox._mount_overlay() validates that overlay paths
  do not contain commas, which would corrupt the OverlayFS mount
  options string (comma is the mount option delimiter).

- GitWorktreeSandbox.commit() now checks git diff return code
  so that a failed diff command raises CalledProcessError instead
  of silently concluding there are no changes and skipping the
  merge.

- safe_restore cleanup of the temporary rollback container now
  runs in a finally block, preventing a temp directory leak
  when the rename fails and the exception is re-raised.

- Fixed misleading BDD step name: "backup path that will cause
  copytree to fail" renamed to "backup path that will cause
  rename to fail" since safe_restore now uses os.rename.
2026-03-29 18:57:15 +01:00

429 lines
14 KiB
Python

"""Helper utilities for sandbox infrastructure Robot integration tests.
Covers the integration between:
- SandboxStatus and transition validation (protocol.py)
- NoSandbox implementation (no_sandbox.py)
- SandboxFactory (factory.py)
- SandboxManager (manager.py)
- Merge strategies (merge.py)
"""
from __future__ import annotations
import json
import sys
import tempfile
from cleveragents.infrastructure.sandbox.factory import SandboxFactory
from cleveragents.infrastructure.sandbox.manager import SandboxManager
from cleveragents.infrastructure.sandbox.merge import (
JsonMergeStrategy,
MergeResult,
SequentialMergeStrategy,
)
from cleveragents.infrastructure.sandbox.no_sandbox import NoSandbox
from cleveragents.infrastructure.sandbox.protocol import (
CommitResult,
Sandbox,
SandboxContext,
SandboxError,
SandboxRollbackError,
SandboxStateError,
SandboxStatus,
)
def _sandbox_status_transitions() -> None:
"""Integration test: SandboxStatus state machine transitions."""
# Valid transitions
assert SandboxStatus.can_transition(SandboxStatus.PENDING, SandboxStatus.CREATED)
assert SandboxStatus.can_transition(SandboxStatus.CREATED, SandboxStatus.ACTIVE)
assert SandboxStatus.can_transition(SandboxStatus.ACTIVE, SandboxStatus.COMMITTED)
assert SandboxStatus.can_transition(SandboxStatus.ACTIVE, SandboxStatus.ROLLED_BACK)
assert SandboxStatus.can_transition(SandboxStatus.ACTIVE, SandboxStatus.ERRORED)
# Invalid transitions
assert not SandboxStatus.can_transition(
SandboxStatus.COMMITTED, SandboxStatus.ACTIVE
)
assert not SandboxStatus.can_transition(
SandboxStatus.CLEANED_UP, SandboxStatus.ACTIVE
)
# assert_transition should raise on invalid
try:
SandboxStatus.assert_transition(SandboxStatus.COMMITTED, SandboxStatus.ACTIVE)
print("FAIL: Expected SandboxStateError")
return
except SandboxStateError:
pass
print("sandbox-status-transitions-ok")
def _no_sandbox_lifecycle() -> None:
"""Integration test: NoSandbox full lifecycle.
Covers: create -> get_path -> commit -> cleanup.
"""
with tempfile.TemporaryDirectory() as tmpdir:
sandbox = NoSandbox(resource_id="res-001", original_path=tmpdir)
# Verify protocol compliance
assert isinstance(sandbox, Sandbox)
assert sandbox.status == SandboxStatus.PENDING
# Create
ctx = sandbox.create(plan_id="plan-001")
assert isinstance(ctx, SandboxContext)
assert ctx.sandbox_path == tmpdir
assert ctx.original_path == tmpdir
assert sandbox.status == SandboxStatus.CREATED
# Get path
path = sandbox.get_path("src/main.py")
assert path.endswith("src/main.py")
assert sandbox.status == SandboxStatus.ACTIVE
# Path traversal guard
try:
sandbox.get_path("../../../etc/passwd")
print("FAIL: Expected SandboxError on path traversal")
return
except (SandboxError, ValueError):
pass
# Commit (no-op for NoSandbox)
result = sandbox.commit("test commit")
assert isinstance(result, CommitResult)
assert result.success
assert sandbox.status == SandboxStatus.COMMITTED
# Cleanup
sandbox.cleanup()
assert sandbox.status == SandboxStatus.CLEANED_UP
print("no-sandbox-lifecycle-ok")
def _no_sandbox_rollback_raises() -> None:
"""Integration test: NoSandbox rollback always raises."""
with tempfile.TemporaryDirectory() as tmpdir:
sandbox = NoSandbox(resource_id="res-002", original_path=tmpdir)
sandbox.create(plan_id="plan-002")
sandbox.get_path("file.txt")
try:
sandbox.rollback()
print("FAIL: Expected SandboxRollbackError")
return
except SandboxRollbackError:
pass
print("no-sandbox-rollback-ok")
def _factory_create_none_strategy() -> None:
"""Integration test: SandboxFactory creates correct sandbox for each strategy."""
factory = SandboxFactory()
# 'none' strategy -> NoSandbox
sandbox = factory.create_sandbox(
resource_id="res-003",
original_path="/tmp/test",
sandbox_strategy="none",
)
assert isinstance(sandbox, NoSandbox)
# 'git_worktree' strategy -> GitWorktreeSandbox (implemented in B4)
from cleveragents.infrastructure.sandbox.git_worktree import GitWorktreeSandbox
gwt_sandbox = factory.create_sandbox(
resource_id="res-004",
original_path="/tmp/test",
sandbox_strategy="git_worktree",
)
assert isinstance(gwt_sandbox, GitWorktreeSandbox)
# 'copy_on_write' strategy -> CopyOnWriteSandbox (implemented in B4)
from cleveragents.infrastructure.sandbox.copy_on_write import CopyOnWriteSandbox
cow_sandbox = factory.create_sandbox(
resource_id="res-005",
original_path="/tmp/test",
sandbox_strategy="copy_on_write",
)
assert isinstance(cow_sandbox, CopyOnWriteSandbox)
# Verify transaction_rollback now produces a TransactionSandbox
from cleveragents.infrastructure.sandbox.transaction_sandbox import (
TransactionSandbox,
)
tx_sandbox = factory.create_sandbox(
resource_id="res-006",
original_path=":memory:",
sandbox_strategy="transaction_rollback",
)
assert isinstance(tx_sandbox, TransactionSandbox)
print("factory-create-none-ok")
def _factory_supported_strategies() -> None:
"""Integration test: SandboxFactory strategy support checks."""
# All three concrete implementations are now supported
assert SandboxFactory.is_supported("none")
assert SandboxFactory.is_supported("git_worktree")
assert SandboxFactory.is_supported("copy_on_write")
# transaction_rollback is now supported
assert SandboxFactory.is_supported("transaction_rollback")
# Unimplemented strategies are not supported
assert not SandboxFactory.is_supported("snapshot")
# Resource type strategy mapping (spec-aligned)
git_checkout_strats = SandboxFactory.get_supported_strategies("git-checkout")
assert "none" in git_checkout_strats
assert "git_worktree" in git_checkout_strats
assert "copy_on_write" in git_checkout_strats
api_strats = SandboxFactory.get_supported_strategies("api_endpoint")
assert "none" in api_strats
# Unknown resource types default to ["none"]
unknown_strats = SandboxFactory.get_supported_strategies("unknown_type")
assert unknown_strats == ["none"]
print("factory-supported-ok")
def _manager_lifecycle() -> None:
"""Integration test: SandboxManager get_or_create, commit_all, cleanup_all."""
factory = SandboxFactory()
manager = SandboxManager(factory=factory, cleanup_on_exit=False)
with tempfile.TemporaryDirectory() as tmpdir:
# Get or create a sandbox
sandbox = manager.get_or_create_sandbox(
plan_id="plan-010",
resource_id="res-010",
original_path=tmpdir,
sandbox_strategy="none",
)
assert isinstance(sandbox, NoSandbox)
assert sandbox.status == SandboxStatus.CREATED
# Get same sandbox again (should return existing)
same = manager.get_or_create_sandbox(
plan_id="plan-010",
resource_id="res-010",
original_path=tmpdir,
sandbox_strategy="none",
)
assert same.sandbox_id == sandbox.sandbox_id
# List sandboxes
sandboxes = manager.list_sandboxes("plan-010")
assert len(sandboxes) == 1
# Get single sandbox
found = manager.get_sandbox("plan-010", "res-010")
assert found is not None
assert found.sandbox_id == sandbox.sandbox_id
# Commit all
results = manager.commit_all("plan-010")
assert len(results) == 1
assert results[0].success
# Cleanup all
manager.cleanup_all("plan-010")
remaining = manager.list_sandboxes("plan-010")
assert len(remaining) == 0
print("manager-lifecycle-ok")
def _sequential_merge_strategy() -> None:
"""Integration test: SequentialMergeStrategy always returns theirs."""
strategy = SequentialMergeStrategy()
result = strategy.merge(
base="original content",
ours="our changes",
theirs="their changes",
)
assert isinstance(result, MergeResult)
assert result.success
assert result.content == "their changes"
assert not result.has_conflicts
print("sequential-merge-ok")
def _json_merge_strategy() -> None:
"""Integration test: JsonMergeStrategy deep merges JSON."""
strategy = JsonMergeStrategy(array_mode="replace")
base = '{"a": 1, "b": {"c": 2}}'
ours = '{"a": 1, "b": {"c": 3, "d": 4}}'
theirs = '{"a": 10, "b": {"c": 5, "e": 6}}'
result = strategy.merge(base=base, ours=ours, theirs=theirs)
assert result.success
merged = json.loads(result.content)
# theirs overrides scalar values, but deep merge should combine nested keys
assert merged["a"] == 10 # theirs wins
assert "c" in merged["b"]
assert "e" in merged["b"]
print("json-merge-ok")
def _json_merge_concat_arrays() -> None:
"""Integration test: JsonMergeStrategy with concat array mode."""
strategy = JsonMergeStrategy(array_mode="concat")
base = '{"items": [1, 2]}'
ours = '{"items": [1, 2, 3]}'
theirs = '{"items": [4, 5]}'
result = strategy.merge(base=base, ours=ours, theirs=theirs)
assert result.success
merged = json.loads(result.content)
# concat mode should combine arrays
assert len(merged["items"]) > 2
print("json-merge-concat-ok")
def _manager_multiple_resources() -> None:
"""Integration test: SandboxManager handles multiple resources per plan."""
factory = SandboxFactory()
manager = SandboxManager(factory=factory, cleanup_on_exit=False)
with (
tempfile.TemporaryDirectory() as tmpdir1,
tempfile.TemporaryDirectory() as tmpdir2,
):
manager.get_or_create_sandbox(
plan_id="plan-multi",
resource_id="res-A",
original_path=tmpdir1,
sandbox_strategy="none",
)
manager.get_or_create_sandbox(
plan_id="plan-multi",
resource_id="res-B",
original_path=tmpdir2,
sandbox_strategy="none",
)
sandboxes = manager.list_sandboxes("plan-multi")
assert len(sandboxes) == 2
results = manager.commit_all("plan-multi")
assert len(results) == 2
assert all(r.success for r in results)
manager.cleanup_all("plan-multi")
assert len(manager.list_sandboxes("plan-multi")) == 0
print("manager-multiple-resources-ok")
def _manager_atomic_commit() -> None:
"""Integration test: SandboxManager.commit_all is atomic.
Verifies that when one sandbox commit fails, the entire batch fails
and already-committed sandboxes are rolled back.
"""
from datetime import datetime
from unittest.mock import MagicMock, PropertyMock
factory = SandboxFactory()
manager = SandboxManager(factory=factory, cleanup_on_exit=False)
with (
tempfile.TemporaryDirectory() as tmpdir1,
tempfile.TemporaryDirectory() as tmpdir2,
):
# Create two sandboxes
manager.get_or_create_sandbox(
plan_id="plan-atomic",
resource_id="res-ok",
original_path=tmpdir1,
sandbox_strategy="none",
)
manager.get_or_create_sandbox(
plan_id="plan-atomic",
resource_id="res-fail",
original_path=tmpdir2,
sandbox_strategy="none",
)
# Replace res-fail with a mock that fails on commit
fail_mock = MagicMock()
fail_mock.sandbox_id = "sb-fail"
type(fail_mock).status = PropertyMock(return_value=SandboxStatus.ACTIVE)
fail_mock.commit.side_effect = SandboxError("simulated commit failure")
manager._active_sandboxes["plan-atomic"]["res-fail"] = fail_mock
# Replace res-ok with a mock that commits and can be rolled back
from cleveragents.infrastructure.sandbox.protocol import CommitResult
ok_mock = MagicMock()
ok_mock.sandbox_id = "sb-ok"
type(ok_mock).status = PropertyMock(return_value=SandboxStatus.ACTIVE)
ok_mock.commit.return_value = CommitResult(
sandbox_id="sb-ok",
success=True,
timestamp=datetime.now(),
)
ok_mock.rollback.return_value = None
manager._active_sandboxes["plan-atomic"]["res-ok"] = ok_mock
results = manager.commit_all("plan-atomic")
# Should return exactly one failure result
assert len(results) == 1, f"Expected 1 result, got {len(results)}"
assert results[0].success is False
assert "Atomic commit failed" in (results[0].error or "")
# The OK sandbox should have been rolled back
assert ok_mock.rollback.called, "Expected rollback on already-committed sandbox"
# Metadata should report rolled-back and failed-rollback IDs
metadata = results[0].metadata
assert "rolled_back" in metadata, "Expected 'rolled_back' in metadata"
assert "rollback_failed" in metadata, "Expected 'rollback_failed' in metadata"
print("manager-atomic-commit-ok")
def main() -> None:
if len(sys.argv) < 2:
raise SystemExit("Expected command argument")
command = sys.argv[1]
commands = {
"status-transitions": _sandbox_status_transitions,
"no-sandbox-lifecycle": _no_sandbox_lifecycle,
"no-sandbox-rollback": _no_sandbox_rollback_raises,
"factory-create-none": _factory_create_none_strategy,
"factory-supported": _factory_supported_strategies,
"manager-lifecycle": _manager_lifecycle,
"sequential-merge": _sequential_merge_strategy,
"json-merge": _json_merge_strategy,
"json-merge-concat": _json_merge_concat_arrays,
"manager-multiple-resources": _manager_multiple_resources,
"manager-atomic-commit": _manager_atomic_commit,
}
if command not in commands:
raise SystemExit(f"Unknown command: {command}")
commands[command]()
if __name__ == "__main__":
main()