story 2-13-importplan-re-import: implemented and reviewed via bmad-loop
This commit is contained in:
1 parent
c562d5368d
commit
f69c36fa65
66 files changed
+11366
-686
No files matched your search
@@ -0,0 +1,423 @@
|
||||
//! Auth profile/secret revalidation with plan-time snapshots: matching
|
||||
//! snapshot applies; config drift, secret rotation/revocation and missing
|
||||
//! snapshots conflict with zero mutation.
|
||||
|
||||
use super::*;
|
||||
|
||||
use crank_core::{
|
||||
ApiKeyHeaderAuthConfig, AuthConfig, AuthKind, AuthProfile, Secret, SecretId, SecretKind,
|
||||
SecretStatus,
|
||||
};
|
||||
use crank_registry::MASTER_KEY_CIPHER_CONTRACT;
|
||||
use crank_registry::{
|
||||
CreateSecretRequest, MasterKeyIdentityCandidate, PostgresRegistry, SaveAuthProfileRequest,
|
||||
};
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
|
||||
fn ts() -> OffsetDateTime {
|
||||
OffsetDateTime::parse("2026-03-25T12:00:00Z", &Rfc3339).unwrap()
|
||||
}
|
||||
|
||||
/// Creates a master key epoch, one active secret and an ApiKeyHeader profile
|
||||
/// for it; returns the secret id.
|
||||
async fn create_auth_fixture(registry: &PostgresRegistry, workspace_id: &WorkspaceId) -> SecretId {
|
||||
registry
|
||||
.verify_or_register_master_key_identity(MasterKeyIdentityCandidate {
|
||||
epoch: 1,
|
||||
fingerprint: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||
cipher_contract: MASTER_KEY_CIPHER_CONTRACT,
|
||||
observed_at: &ts(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let secret_id = SecretId::new("sec_apply");
|
||||
let secret = Secret {
|
||||
id: secret_id.clone(),
|
||||
workspace_id: workspace_id.clone(),
|
||||
name: "Apply secret".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
status: SecretStatus::Active,
|
||||
current_version: 1,
|
||||
created_at: ts(),
|
||||
updated_at: ts(),
|
||||
last_used_at: None,
|
||||
};
|
||||
registry
|
||||
.create_secret(CreateSecretRequest {
|
||||
secret: &secret,
|
||||
ciphertext: "ciphertext",
|
||||
key_version: "v1",
|
||||
master_key_epoch: 1,
|
||||
created_by: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let profile = AuthProfile {
|
||||
id: "auth_apply".into(),
|
||||
workspace_id: workspace_id.clone(),
|
||||
name: "Apply key".to_owned(),
|
||||
kind: AuthKind::ApiKeyHeader,
|
||||
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||
header_name: "X-Apply-Key".to_owned(),
|
||||
secret_id: secret_id.clone(),
|
||||
}),
|
||||
created_at: ts(),
|
||||
updated_at: ts(),
|
||||
};
|
||||
registry
|
||||
.save_auth_profile(SaveAuthProfileRequest {
|
||||
workspace_id,
|
||||
profile: &profile,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
secret_id
|
||||
}
|
||||
|
||||
fn auth_operation(id: &str) -> RegistryOperation {
|
||||
let mut operation = plan_operation(id);
|
||||
operation.execution_config.auth_profile_ref = Some("auth_apply".into());
|
||||
operation
|
||||
}
|
||||
|
||||
/// The plan-time snapshot an Admin CreatePlan captures for this profile +
|
||||
/// secret (metadata only, never credential bytes).
|
||||
fn capture_snapshot(profile: &AuthProfile, secret: &crank_core::Secret) -> Value {
|
||||
json!({
|
||||
"profile_id": profile.id.as_str(),
|
||||
"name": profile.name,
|
||||
"kind": profile.kind,
|
||||
"config": profile.config,
|
||||
"updated_at": profile.updated_at.format(&Rfc3339).unwrap(),
|
||||
"secrets": [{
|
||||
"id": secret.id.as_str(),
|
||||
"status": secret.status,
|
||||
"current_version": secret.current_version,
|
||||
"updated_at": secret.updated_at.format(&Rfc3339).unwrap()
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
fn auth_plan_payload(
|
||||
plan_id: &str,
|
||||
job_id: &str,
|
||||
fingerprint: &Value,
|
||||
snapshot: Option<Value>,
|
||||
) -> Value {
|
||||
let operation = auth_operation("op_apply_auth");
|
||||
let mut candidate = json!({
|
||||
"key": "auth",
|
||||
"name": operation.name,
|
||||
"state": "actionable",
|
||||
"decision": { "action": "create" },
|
||||
"operation": operation
|
||||
});
|
||||
if let Some(snapshot) = snapshot {
|
||||
candidate["auth_snapshot"] = snapshot;
|
||||
}
|
||||
json!({
|
||||
"schema_version": "import-plan-v1",
|
||||
"plan_reference": plan_id,
|
||||
"job_id": job_id,
|
||||
"fingerprint": fingerprint,
|
||||
"source": { "source_id": SOURCE_ID, "digest": source_ref() },
|
||||
"dependencies": [],
|
||||
"selection": {
|
||||
"mode": "full",
|
||||
"all": ["auth"],
|
||||
"selected": ["auth"],
|
||||
"excluded": []
|
||||
},
|
||||
"counts": { "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 },
|
||||
"candidates": [candidate]
|
||||
})
|
||||
}
|
||||
|
||||
async fn auth_base(
|
||||
database: &TestDatabase,
|
||||
workspace_tag: &str,
|
||||
) -> (
|
||||
PostgresRegistry,
|
||||
PgPool,
|
||||
WorkspaceId,
|
||||
ImportJobId,
|
||||
Value,
|
||||
Value,
|
||||
) {
|
||||
let registry = database.registry().await;
|
||||
let raw_pool = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, workspace_tag).await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
&format!("job_apply_auth_{workspace_tag}"),
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw_pool, &ws, now).await;
|
||||
let secret_id = create_auth_fixture(®istry, &ws).await;
|
||||
let profile = registry
|
||||
.get_auth_profile(&ws, &crank_core::AuthProfileId::new("auth_apply"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let secret = registry
|
||||
.get_secret(&ws, &secret_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.secret;
|
||||
let fp = fingerprint();
|
||||
(
|
||||
registry,
|
||||
raw_pool,
|
||||
ws,
|
||||
job,
|
||||
fp,
|
||||
capture_snapshot(&profile, &secret),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_accepts_matching_auth_snapshot() {
|
||||
let database = TestDatabase::new().await;
|
||||
let (registry, _raw_pool, ws, job, fp, snapshot) = auth_base(&database, "a_ok").await;
|
||||
|
||||
let payload = auth_plan_payload("plan_auth_ok", job.as_str(), &fp, Some(snapshot));
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, "plan_auth_ok", &fp, payload).await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_auth_ok",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
};
|
||||
let result = registry.apply_import_plan(&request).await.unwrap();
|
||||
assert!(!result.replayed);
|
||||
assert_eq!(result.report.status, ImportPlanApplyStatus::Applied);
|
||||
assert_eq!(result.report.counts.created, 1);
|
||||
let summary = registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_apply_auth"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(summary.current_draft_version, 1);
|
||||
let stored = result.report;
|
||||
drop(stored);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_rejects_auth_profile_config_drift() {
|
||||
let database = TestDatabase::new().await;
|
||||
let (registry, _raw_pool, ws, job, fp, snapshot) = auth_base(&database, "a_drift").await;
|
||||
|
||||
let payload = auth_plan_payload("plan_auth_drift", job.as_str(), &fp, Some(snapshot));
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, "plan_auth_drift", &fp, payload).await;
|
||||
|
||||
// After the plan was captured, the profile's config drifted.
|
||||
let drifted = AuthProfile {
|
||||
name: "Drifted key".to_owned(),
|
||||
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||
header_name: "X-Other-Key".to_owned(),
|
||||
secret_id: SecretId::new("sec_apply"),
|
||||
}),
|
||||
updated_at: OffsetDateTime::now_utc(),
|
||||
..capture_profile_fixture(®istry, &ws).await
|
||||
};
|
||||
registry
|
||||
.save_auth_profile(SaveAuthProfileRequest {
|
||||
workspace_id: &ws,
|
||||
profile: &drifted,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_auth_drift",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
};
|
||||
assert!(
|
||||
matches!(
|
||||
registry
|
||||
.apply_import_plan(&request)
|
||||
.await,
|
||||
Err(RegistryError::ImportPlanAuthUnavailable {
|
||||
auth_profile_id
|
||||
}) if auth_profile_id == "auth_apply"
|
||||
),
|
||||
"a config drift must be a typed re-preview conflict"
|
||||
);
|
||||
assert!(
|
||||
registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_apply_auth"))
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none(),
|
||||
"zero mutation on auth drift"
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
async fn capture_profile_fixture(registry: &PostgresRegistry, ws: &WorkspaceId) -> AuthProfile {
|
||||
registry
|
||||
.get_auth_profile(ws, &crank_core::AuthProfileId::new("auth_apply"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_rejects_secret_rotation_or_revocation() {
|
||||
let database = TestDatabase::new().await;
|
||||
let (registry, raw_pool, ws, job, fp, snapshot) = auth_base(&database, "a_rotate").await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
|
||||
// Rotated secret: same id, new current version.
|
||||
let payload = auth_plan_payload("plan_auth_rot", job.as_str(), &fp, Some(snapshot.clone()));
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, "plan_auth_rot", &fp, payload).await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.rotate_secret(crank_registry::RotateSecretRequest {
|
||||
workspace_id: &ws,
|
||||
secret_id: &SecretId::new("sec_apply"),
|
||||
ciphertext: "new-ciphertext",
|
||||
key_version: "v2",
|
||||
master_key_epoch: 1,
|
||||
created_at: &now,
|
||||
updated_at: &now,
|
||||
created_by: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(
|
||||
registry
|
||||
.apply_import_plan(&ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_auth_rot",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
})
|
||||
.await,
|
||||
Err(RegistryError::ImportPlanAuthUnavailable { .. })
|
||||
),
|
||||
"a rotated secret must be a typed re-preview conflict"
|
||||
);
|
||||
|
||||
// Revoked/disabled secret: same id, changed status.
|
||||
let payload = auth_plan_payload("plan_auth_dis", job.as_str(), &fp, Some(snapshot));
|
||||
let (dis_plan, dis_digest) =
|
||||
store_plan(®istry, &ws, &job, "plan_auth_dis", &fp, payload).await;
|
||||
sqlx::query("update secrets set status = 'disabled' where workspace_id = $1 and id = $2")
|
||||
.bind(ws.as_str())
|
||||
.bind("sec_apply")
|
||||
.execute(&raw_pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(
|
||||
registry
|
||||
.apply_import_plan(&ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &dis_plan,
|
||||
plan_digest: &dis_digest,
|
||||
idempotency_key: "idem_auth_dis",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
})
|
||||
.await,
|
||||
Err(RegistryError::ImportPlanAuthUnavailable { .. })
|
||||
),
|
||||
"a revoked secret must be a typed re-preview conflict"
|
||||
);
|
||||
assert!(
|
||||
registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_apply_auth"))
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none(),
|
||||
"zero mutation on secret drift"
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_rejects_auth_candidates_missing_or_mismatched_snapshot() {
|
||||
let database = TestDatabase::new().await;
|
||||
let (registry, _raw_pool, ws, job, fp, snapshot) = auth_base(&database, "a_missing").await;
|
||||
|
||||
// Actionable + auth ref but NO snapshot -> unavailable (re-preview).
|
||||
let payload = auth_plan_payload("plan_auth_mis", job.as_str(), &fp, None);
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, "plan_auth_mis", &fp, payload).await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
assert!(
|
||||
matches!(
|
||||
registry
|
||||
.apply_import_plan(&ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_auth_mis",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
})
|
||||
.await,
|
||||
Err(RegistryError::ImportPlanAuthUnavailable { .. })
|
||||
),
|
||||
"an auth-bound candidate without a snapshot must re-preview"
|
||||
);
|
||||
|
||||
// Snapshot on a candidate WITHOUT an auth ref -> corrupt plan.
|
||||
let unauth_operation = plan_operation("op_apply_noauth");
|
||||
let payload = json!({
|
||||
"schema_version": "import-plan-v1",
|
||||
"plan_reference": "plan_auth_corrupt",
|
||||
"job_id": job.as_str(),
|
||||
"fingerprint": fp,
|
||||
"source": { "source_id": SOURCE_ID, "digest": source_ref() },
|
||||
"dependencies": [],
|
||||
"selection": {
|
||||
"mode": "full", "all": ["na"], "selected": ["na"], "excluded": []
|
||||
},
|
||||
"counts": { "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 },
|
||||
"candidates": [{
|
||||
"key": "na",
|
||||
"name": unauth_operation.name,
|
||||
"state": "actionable",
|
||||
"decision": { "action": "create" },
|
||||
"operation": unauth_operation,
|
||||
"auth_snapshot": snapshot
|
||||
}]
|
||||
});
|
||||
let (c_plan, c_digest) =
|
||||
store_plan(®istry, &ws, &job, "plan_auth_corrupt", &fp, payload).await;
|
||||
assert!(
|
||||
matches!(
|
||||
registry
|
||||
.apply_import_plan(&ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &c_plan,
|
||||
plan_digest: &c_digest,
|
||||
idempotency_key: "idem_auth_corrupt",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
})
|
||||
.await,
|
||||
Err(RegistryError::ImportPlanPayloadCorrupt { .. })
|
||||
),
|
||||
"a no-ref candidate must not carry an auth snapshot"
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
//! Full blocked rejection (zero mutation) and the rejected outcome shape.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn blocked_candidate_payload(plan_id: &str, job_id: &str, fingerprint: &Value) -> Value {
|
||||
let operation = plan_operation("op_apply_blocked_ok");
|
||||
json!({
|
||||
"schema_version": "import-plan-v1",
|
||||
"plan_reference": plan_id,
|
||||
"job_id": job_id,
|
||||
"fingerprint": fingerprint,
|
||||
"source": { "source_id": SOURCE_ID, "digest": source_ref() },
|
||||
"dependencies": [],
|
||||
"selection": {
|
||||
"mode": "full",
|
||||
"all": ["ready", "blocked"],
|
||||
"selected": ["ready", "blocked"],
|
||||
"excluded": []
|
||||
},
|
||||
"counts": { "selected": 2, "excluded": 0, "actionable": 1, "blocked": 1 },
|
||||
"candidates": [
|
||||
{
|
||||
"key": "ready",
|
||||
"name": operation.name,
|
||||
"state": "actionable",
|
||||
"decision": { "action": "create" },
|
||||
"operation": operation
|
||||
},
|
||||
{
|
||||
"key": "blocked",
|
||||
"name": "import_candidate_blocked",
|
||||
"state": "blocked",
|
||||
"reason": "import_candidate_blocked",
|
||||
"decision": { "action": "create" }
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_rejects_whole_plan_when_any_candidate_is_blocked() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw_pool = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_apply_blocked").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_apply_blocked",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw_pool, &ws, now).await;
|
||||
|
||||
let fp = fingerprint();
|
||||
let plan_id_str = "plan_apply_blocked";
|
||||
let payload = blocked_candidate_payload(plan_id_str, job.as_str(), &fp);
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, plan_id_str, &fp, payload).await;
|
||||
let applied_at = OffsetDateTime::now_utc();
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_blocked",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
};
|
||||
|
||||
// A single blocked candidate rejects the whole apply: zero mutation.
|
||||
let result = registry.apply_import_plan(&request).await.unwrap();
|
||||
assert!(
|
||||
!result.replayed,
|
||||
"a rejected apply is a call outcome, not a replay"
|
||||
);
|
||||
let report = &result.report;
|
||||
assert_eq!(report.status, ImportPlanApplyStatus::Rejected);
|
||||
assert_eq!(
|
||||
report.counts.rejected, 2,
|
||||
"both selected candidates are rejected"
|
||||
);
|
||||
assert_eq!(report.counts.created, 0);
|
||||
assert!(
|
||||
report
|
||||
.outcomes
|
||||
.iter()
|
||||
.all(|reported| reported.outcome == ImportPlanCandidateOutcome::Rejected)
|
||||
);
|
||||
let blocked = report
|
||||
.outcomes
|
||||
.iter()
|
||||
.find(|reported| reported.key == "blocked")
|
||||
.expect("the blocked candidate must be explained in the report");
|
||||
assert_eq!(blocked.reason.as_deref(), Some("import_candidate_blocked"));
|
||||
assert_eq!(report.recovery, "repreview_required");
|
||||
|
||||
// No operation materialized and no application row persisted.
|
||||
assert!(
|
||||
registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_apply_blocked_ok"))
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none(),
|
||||
"a rejected apply must not create the actionable candidate"
|
||||
);
|
||||
assert_eq!(
|
||||
registry
|
||||
.get_import_plan_application(&ws, "idem_blocked")
|
||||
.await
|
||||
.unwrap(),
|
||||
None,
|
||||
"a rejected apply must not persist application evidence"
|
||||
);
|
||||
|
||||
// It can be retried under the same key and must reject again, not replay.
|
||||
let retry = registry.apply_import_plan(&request).await.unwrap();
|
||||
assert!(!retry.replayed);
|
||||
assert_eq!(retry.report.status, ImportPlanApplyStatus::Rejected);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//! Concurrent applies with the same scoped idempotency key: one coherent
|
||||
//! commit, deterministic conflicts for changed digests.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_applies_with_same_key_and_digest_converge() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw_pool = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_apply_race").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_apply_race",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw_pool, &ws, now).await;
|
||||
|
||||
let fp = fingerprint();
|
||||
let (plan, digest) = stored_plan(®istry, &ws, &job, "plan_race", &fp).await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_race",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
};
|
||||
|
||||
// Two identical applies race: both must converge on the same report and
|
||||
// exactly one operation / application row may exist.
|
||||
let (a, b) = tokio::join!(
|
||||
registry.apply_import_plan(&request),
|
||||
registry.apply_import_plan(&request)
|
||||
);
|
||||
let a = a.unwrap();
|
||||
let b = b.unwrap();
|
||||
assert_eq!(a.report, b.report, "racers must see the same report");
|
||||
let fresh = (a.replayed, b.replayed);
|
||||
assert!(
|
||||
(fresh == (false, true)) || (fresh == (true, false)),
|
||||
"exactly one racer produces the report, the other replays: {a:?} / {b:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("select count(*) from operations")
|
||||
.fetch_one(&raw_pool)
|
||||
.await
|
||||
.unwrap(),
|
||||
1,
|
||||
"the race must materialize exactly one operation"
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("select count(*) from import_plan_applications")
|
||||
.fetch_one(&raw_pool)
|
||||
.await
|
||||
.unwrap(),
|
||||
1,
|
||||
"the race must persist exactly one application row"
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_applies_same_key_changed_digest_conflicts_deterministically() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw_pool = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_apply_race2").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_apply_race2",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw_pool, &ws, now).await;
|
||||
|
||||
let fp = fingerprint();
|
||||
let (plan, digest) = stored_plan(®istry, &ws, &job, "plan_race2", &fp).await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
let good = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_race2",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
};
|
||||
let other_digest = "ef".repeat(32);
|
||||
let bad = ApplyImportPlanRequest {
|
||||
plan_digest: &other_digest,
|
||||
..good
|
||||
};
|
||||
|
||||
// Same key, different plan digest: exactly one may succeed.
|
||||
let (a, b) = tokio::join!(
|
||||
registry.apply_import_plan(&good),
|
||||
registry.apply_import_plan(&bad)
|
||||
);
|
||||
assert!(
|
||||
a.is_ok() ^ b.is_ok(),
|
||||
"one winner, one typed conflict: a={a:?}, b={b:?}"
|
||||
);
|
||||
for result in [&a, &b] {
|
||||
if let Err(error) = result {
|
||||
assert!(
|
||||
matches!(error, RegistryError::ImportPlanKeyDigestConflict { .. }),
|
||||
"the loser must get the typed digest conflict, got {error:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
// The committed state is coherent: exactly one application row, and it
|
||||
// binds the digest of the winner's successful apply.
|
||||
let winner = match &a {
|
||||
Ok(result) => result,
|
||||
Err(_) => b.as_ref().unwrap(),
|
||||
};
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("select count(*) from import_plan_applications")
|
||||
.fetch_one(&raw_pool)
|
||||
.await
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
assert!(
|
||||
!winner.replayed,
|
||||
"the winner of a changed-digest race must be a fresh apply"
|
||||
);
|
||||
let stored = registry
|
||||
.get_import_plan_application(&ws, "idem_race2")
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("the committed apply must be readable");
|
||||
assert_eq!(stored.plan_digest, winner.report.plan_digest);
|
||||
database.cleanup().await;
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
//! Apply tests for the registry-only transactional `apply_import_plan`.
|
||||
//!
|
||||
//! Conventions follow the existing CreatePlan tests in `create.rs`: one
|
||||
//! unique schema per test, registry API for domain objects and the raw pool
|
||||
//! for storage-level fixtures (artifact sources).
|
||||
|
||||
#![allow(dead_code)]
|
||||
use super::super::common::{TestDatabase, test_operation};
|
||||
use super::{create_pending_openapi_job, create_workspace};
|
||||
pub use time::Duration;
|
||||
|
||||
pub use crank_core::{OperationId, OperationStatus, WorkspaceId};
|
||||
pub use serde_json::{Value, json};
|
||||
pub use sqlx::PgPool;
|
||||
pub use time::OffsetDateTime;
|
||||
|
||||
pub use crank_registry::{
|
||||
ApplyImportPlanRequest, CreateImportPlanRequest, ImportJobId, ImportJobStatus,
|
||||
ImportPlanApplyStatus, ImportPlanCandidateOutcome, ImportPlanId, RegistryError,
|
||||
RegistryOperation,
|
||||
};
|
||||
|
||||
mod auth;
|
||||
mod blocked;
|
||||
mod concurrency;
|
||||
mod new_version;
|
||||
mod partial;
|
||||
mod replay_stale;
|
||||
mod skip_rename;
|
||||
/// Shared fixture source id — must match `create_pending_openapi_job`.
|
||||
pub(crate) const SOURCE_ID: &str = "src_openapi_test";
|
||||
fn source_hex() -> String {
|
||||
"ab".repeat(32)
|
||||
}
|
||||
fn source_ref() -> String {
|
||||
format!("sha256:{}", source_hex())
|
||||
}
|
||||
|
||||
/// Activates the source row the apply path revalidates under lock: the job
|
||||
/// envelope must still be `active` with exactly the recorded artifact ref.
|
||||
async fn activate_source(raw: &PgPool, workspace_id: &WorkspaceId, now: OffsetDateTime) {
|
||||
let hex = source_hex();
|
||||
sqlx::query(
|
||||
"insert into artifact_blobs (digest, artifact_ref, size_bytes, created_at, updated_at)
|
||||
values ($1, 'sha256:' || $1, 16, $2, $2)",
|
||||
)
|
||||
.bind(&hex)
|
||||
.bind(now)
|
||||
.execute(raw)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"insert into artifact_sources (
|
||||
workspace_id, source_id, blob_digest, mime_type, sensitivity, lifecycle,
|
||||
created_at, updated_at
|
||||
) values ($1, $2, $3, 'application/yaml', 'public', 'active', $4, $4)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(SOURCE_ID)
|
||||
.bind(&hex)
|
||||
.bind(now)
|
||||
.execute(raw)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// A planned Draft operation without auth references: apply must not
|
||||
/// require profile/secret rows for the basic create path.
|
||||
fn plan_operation(id: &str) -> RegistryOperation {
|
||||
let mut operation = test_operation(id, 1, OperationStatus::Draft);
|
||||
operation.execution_config.auth_profile_ref = None;
|
||||
operation
|
||||
}
|
||||
|
||||
/// Builds a valid `import-plan-v1` payload applying a single `create`
|
||||
/// candidate over the shared verifiable source.
|
||||
fn single_create_payload(plan_id: &str, job_id: &str, fingerprint: &Value) -> Value {
|
||||
let operation = plan_operation("op_apply_basic");
|
||||
json!({
|
||||
"schema_version": "import-plan-v1",
|
||||
"plan_reference": plan_id,
|
||||
"job_id": job_id,
|
||||
"fingerprint": fingerprint,
|
||||
"source": { "source_id": SOURCE_ID, "digest": source_ref() },
|
||||
"dependencies": [],
|
||||
"selection": {
|
||||
"mode": "full",
|
||||
"all": ["basic"],
|
||||
"selected": ["basic"],
|
||||
"excluded": []
|
||||
},
|
||||
"counts": { "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 },
|
||||
"candidates": [{
|
||||
"key": "basic",
|
||||
"name": operation.name,
|
||||
"state": "actionable",
|
||||
"decision": { "action": "create" },
|
||||
"operation": operation
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
async fn stored_plan(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
job: &ImportJobId,
|
||||
plan_id: &str,
|
||||
fingerprint: &Value,
|
||||
) -> (ImportPlanId, String) {
|
||||
let payload = single_create_payload(plan_id, job.as_str(), fingerprint);
|
||||
store_plan(registry, workspace_id, job, plan_id, fingerprint, payload).await
|
||||
}
|
||||
|
||||
/// Persists any well-formed `import-plan-v1` payload bound to the shared
|
||||
/// verifiable source; returns the plan id and the registry-computed digest.
|
||||
async fn store_plan(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
job: &ImportJobId,
|
||||
plan_id: &str,
|
||||
_fingerprint: &Value,
|
||||
payload: Value,
|
||||
) -> (ImportPlanId, String) {
|
||||
let plan = ImportPlanId::new(plan_id);
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let created = registry
|
||||
.create_import_plan(CreateImportPlanRequest {
|
||||
id: &plan,
|
||||
workspace_id,
|
||||
job_id: job,
|
||||
payload: &payload,
|
||||
created_at: &now,
|
||||
expires_at: &(now + Duration::minutes(30)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
(plan, created.digest)
|
||||
}
|
||||
|
||||
/// Basename of the workspace slug for slug-scoped registry reads.
|
||||
#[allow(dead_code)]
|
||||
fn workspace_slug(workspace_id: &WorkspaceId) -> String {
|
||||
workspace_id.as_str().replace('_', "-")
|
||||
}
|
||||
|
||||
fn fingerprint() -> Value {
|
||||
json!({"importer": "test", "digest": "fp-1"})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_creates_draft_operation_and_replays_committed_report() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_apply_1").await;
|
||||
|
||||
let job =
|
||||
create_pending_openapi_job(®istry, &ws, "job_apply_1", now, now + Duration::hours(1))
|
||||
.await;
|
||||
activate_source(&raw, &ws, now).await;
|
||||
|
||||
let fp = fingerprint();
|
||||
let (plan, digest) = stored_plan(®istry, &ws, &job, "plan_apply_1", &fp).await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_apply_1",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
};
|
||||
let result = registry.apply_import_plan(&request).await.unwrap();
|
||||
|
||||
// Fresh apply: the report is produced by this call, not a replay.
|
||||
assert!(
|
||||
!result.replayed,
|
||||
"a first apply must never be marked replayed"
|
||||
);
|
||||
let report = &result.report;
|
||||
assert_eq!(report.status, ImportPlanApplyStatus::Applied);
|
||||
assert_eq!(report.plan_id, plan.as_str());
|
||||
assert_eq!(report.job_id, job.as_str());
|
||||
assert_eq!(report.plan_digest, digest);
|
||||
assert_eq!(report.idempotency_key, "idem_apply_1");
|
||||
assert_eq!(report.counts.created, 1);
|
||||
assert_eq!(report.counts.versioned, 0);
|
||||
assert_eq!(report.counts.renamed, 0);
|
||||
assert_eq!(report.counts.skipped, 0);
|
||||
assert_eq!(report.counts.excluded, 0);
|
||||
assert_eq!(report.counts.rejected, 0);
|
||||
assert_eq!(report.outcomes.len(), 1);
|
||||
assert_eq!(report.outcomes[0].key, "basic");
|
||||
assert_eq!(
|
||||
report.outcomes[0].outcome,
|
||||
ImportPlanCandidateOutcome::Created
|
||||
);
|
||||
assert_eq!(
|
||||
report.outcomes[0].operation_id,
|
||||
Some(OperationId::new("op_apply_basic").as_str().to_owned())
|
||||
);
|
||||
assert_eq!(report.outcomes[0].version, Some(1));
|
||||
assert_eq!(report.outcomes[0].reason, None);
|
||||
assert_eq!(report.source_id, SOURCE_ID);
|
||||
assert_eq!(report.source_digest, source_ref());
|
||||
assert_eq!(
|
||||
report.recovery, "none",
|
||||
"a clean apply must not ask for recovery"
|
||||
);
|
||||
|
||||
// The planned contract landed as a new Draft operation at version 1.
|
||||
let summary = registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_apply_basic"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(summary.status, OperationStatus::Draft);
|
||||
assert_eq!(summary.current_draft_version, 1);
|
||||
assert_eq!(summary.latest_published_version, None);
|
||||
|
||||
// The anchor job is untouched: legacy replay and other plans stay viable.
|
||||
let job_after = registry.get_import_job(&ws, &job).await.unwrap().unwrap();
|
||||
assert_eq!(job_after.status, ImportJobStatus::Pending);
|
||||
|
||||
// Replay with the same scoped key and digest: identical immutable report.
|
||||
let replay = registry.apply_import_plan(&request).await.unwrap();
|
||||
assert!(replay.replayed, "a second identical apply must be a replay");
|
||||
assert_eq!(
|
||||
replay.report, *report,
|
||||
"the stored report must be returned byte-for-byte"
|
||||
);
|
||||
|
||||
// A changed digest under the same key is a typed conflict.
|
||||
let changed_digest = "cd".repeat(32);
|
||||
let changed = ApplyImportPlanRequest {
|
||||
plan_digest: &changed_digest,
|
||||
..request
|
||||
};
|
||||
assert!(
|
||||
matches!(
|
||||
registry.apply_import_plan(&changed).await,
|
||||
Err(RegistryError::ImportPlanKeyDigestConflict { .. })
|
||||
),
|
||||
"a changed digest under a used key must be a typed conflict"
|
||||
);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
//! `new_version`: Published state, prior versions, bindings are preserved.
|
||||
|
||||
use super::*;
|
||||
|
||||
use super::super::super::common::{test_agent, test_agent_version};
|
||||
use crank_core::{AgentOperationBinding, AgentStatus};
|
||||
use crank_registry::{
|
||||
CreateAgentRequest, CreateVersionRequest, ImportPlanApplyStatus, PublishAgentRequest,
|
||||
PublishRequest,
|
||||
};
|
||||
|
||||
fn new_version_payload(
|
||||
plan_id: &str,
|
||||
job_id: &str,
|
||||
fingerprint: &Value,
|
||||
expected_current: u32,
|
||||
) -> Value {
|
||||
let mut operation = plan_operation("op_nv");
|
||||
operation.version = expected_current + 1;
|
||||
json!({
|
||||
"schema_version": "import-plan-v1",
|
||||
"plan_reference": plan_id,
|
||||
"job_id": job_id,
|
||||
"fingerprint": fingerprint,
|
||||
"source": { "source_id": SOURCE_ID, "digest": source_ref() },
|
||||
"dependencies": [],
|
||||
"selection": {
|
||||
"mode": "full",
|
||||
"all": ["nv"],
|
||||
"selected": ["nv"],
|
||||
"excluded": []
|
||||
},
|
||||
"counts": { "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 },
|
||||
"candidates": [{
|
||||
"key": "nv",
|
||||
"name": "op_nv_tool",
|
||||
"state": "actionable",
|
||||
"decision": { "action": "new_version", "target_operation_id": "op_nv" },
|
||||
"target": {
|
||||
"operation_id": "op_nv",
|
||||
"name": "op_nv_tool",
|
||||
"expected_state": {
|
||||
"status": "draft",
|
||||
"current_draft_version": expected_current,
|
||||
"latest_published_version": 1
|
||||
}
|
||||
},
|
||||
"operation": operation
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_new_version_preserves_published_prior_versions_and_bindings() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw_pool = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_apply_nv").await;
|
||||
let ws_slug = ws.as_str().replace('_', "-");
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_apply_nv",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw_pool, &ws, now).await;
|
||||
|
||||
// Target operation: published v1 + a later draft v2.
|
||||
let base = plan_operation("op_nv");
|
||||
registry.create_operation(&ws, &base, None).await.unwrap();
|
||||
let published_at = now - Duration::hours(2);
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &ws,
|
||||
operation_id: &OperationId::new("op_nv"),
|
||||
version: 1,
|
||||
published_at: &published_at,
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let mut draft_v2 = clone_operation(&base, 2);
|
||||
draft_v2.status = crank_core::OperationStatus::Draft;
|
||||
registry
|
||||
.create_version(CreateVersionRequest {
|
||||
workspace_id: &ws,
|
||||
snapshot: &draft_v2,
|
||||
change_note: None,
|
||||
created_by: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// A published agent already bound to operation v1: the Agent/MCP surface
|
||||
// is exactly one tool at version 1.
|
||||
let mut agent = test_agent("agent_nv", AgentStatus::Draft);
|
||||
agent.workspace_id = ws.clone();
|
||||
let version = test_agent_version(&agent.id, 1, AgentStatus::Draft);
|
||||
let binding = AgentOperationBinding {
|
||||
operation_id: OperationId::new("op_nv"),
|
||||
operation_version: 1,
|
||||
tool_name: "nv_tool".to_owned(),
|
||||
tool_title: "NV tool".to_owned(),
|
||||
tool_description_override: None,
|
||||
enabled: true,
|
||||
};
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &agent,
|
||||
version: &version,
|
||||
bindings: std::slice::from_ref(&binding),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &ws,
|
||||
agent_id: &agent.id,
|
||||
version: 1,
|
||||
published_at: &now,
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let catalog_before = registry
|
||||
.get_published_agent_tools_by_slug(&ws_slug, &agent.slug)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(catalog_before.len(), 1);
|
||||
assert_eq!(catalog_before[0].operation.version, 1);
|
||||
assert!(catalog_before[0].operation.is_published());
|
||||
|
||||
// Apply the confirmed `new_version` (v3 on top of draft v2).
|
||||
let fp = fingerprint();
|
||||
let payload = new_version_payload("plan_nv", job.as_str(), &fp, 2);
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, "plan_nv", &fp, payload).await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_nv",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
};
|
||||
|
||||
let result = registry.apply_import_plan(&request).await.unwrap();
|
||||
assert!(!result.replayed);
|
||||
let report = &result.report;
|
||||
assert_eq!(report.status, ImportPlanApplyStatus::Applied);
|
||||
assert_eq!(report.counts.versioned, 1);
|
||||
assert_eq!(
|
||||
report.outcomes[0].outcome,
|
||||
ImportPlanCandidateOutcome::Versioned
|
||||
);
|
||||
assert_eq!(report.outcomes[0].operation_id.as_deref(), Some("op_nv"));
|
||||
assert_eq!(report.outcomes[0].version, Some(3));
|
||||
|
||||
let summary = registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_nv"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
summary.current_draft_version, 3,
|
||||
"the new Draft version appears"
|
||||
);
|
||||
assert_eq!(
|
||||
summary.latest_published_version,
|
||||
Some(1),
|
||||
"the Published Version stays untouched"
|
||||
);
|
||||
|
||||
// Prior version 1 keeps its published state; 3 is a fresh draft.
|
||||
let v1 = registry
|
||||
.get_operation_version(&ws, &OperationId::new("op_nv"), 1)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(v1.snapshot.is_published(), "version 1 must stay published");
|
||||
let v3 = registry
|
||||
.get_operation_version(&ws, &OperationId::new("op_nv"), 3)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(!v3.snapshot.is_published(), "version 3 must be a draft");
|
||||
|
||||
// The Agent/MCP surface is unchanged: still exactly the published v1
|
||||
// tool; the new draft version 3 is invisible until publication.
|
||||
let catalog_after = registry
|
||||
.get_published_agent_tools_by_slug(&ws_slug, &agent.slug)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
catalog_after.len(),
|
||||
1,
|
||||
"the catalog must gain no new draft tool"
|
||||
);
|
||||
assert_eq!(catalog_after[0].operation.version, 1);
|
||||
assert!(catalog_after[0].operation.is_published());
|
||||
|
||||
// A stale expected state is a typed conflict and changes nothing.
|
||||
let stale_payload = new_version_payload("plan_nv_stale", job.as_str(), &fp, 5);
|
||||
let (stale_plan, stale_digest) =
|
||||
store_plan(®istry, &ws, &job, "plan_nv_stale", &fp, stale_payload).await;
|
||||
let stale_request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &stale_plan,
|
||||
plan_digest: &stale_digest,
|
||||
idempotency_key: "idem_nv_stale",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
};
|
||||
assert!(
|
||||
matches!(
|
||||
registry.apply_import_plan(&stale_request).await,
|
||||
Err(RegistryError::ImportPlanTargetStale { .. })
|
||||
),
|
||||
"a stale new_version target must be a typed conflict"
|
||||
);
|
||||
let unchanged = registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_nv"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(unchanged.current_draft_version, 3);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
fn clone_operation(base: &RegistryOperation, version: u32) -> RegistryOperation {
|
||||
let mut clone = base.clone();
|
||||
clone.version = version;
|
||||
clone
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
//! Partial selection: only the closed selected set mutates.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn partial_payload(plan_id: &str, job_id: &str, fingerprint: &Value) -> Value {
|
||||
let operation = plan_operation("op_apply_partial");
|
||||
json!({
|
||||
"schema_version": "import-plan-v1",
|
||||
"plan_reference": plan_id,
|
||||
"job_id": job_id,
|
||||
"fingerprint": fingerprint,
|
||||
"source": { "source_id": SOURCE_ID, "digest": source_ref() },
|
||||
"dependencies": [],
|
||||
"selection": {
|
||||
"mode": "partial",
|
||||
"all": ["picked", "not_picked"],
|
||||
"selected": ["picked"],
|
||||
"excluded": ["not_picked"]
|
||||
},
|
||||
"counts": { "selected": 1, "excluded": 1, "actionable": 1, "blocked": 0 },
|
||||
"candidates": [{
|
||||
"key": "picked",
|
||||
"name": operation.name,
|
||||
"state": "actionable",
|
||||
"decision": { "action": "create" },
|
||||
"operation": operation
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_partial_selection_only_mutates_selected_and_explains_excluded() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw_pool = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_apply_partial").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_apply_partial",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw_pool, &ws, now).await;
|
||||
|
||||
let fp = fingerprint();
|
||||
let plan_id_str = "plan_apply_partial";
|
||||
let payload = partial_payload(plan_id_str, job.as_str(), &fp);
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, plan_id_str, &fp, payload).await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_partial",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
};
|
||||
|
||||
let result = registry.apply_import_plan(&request).await.unwrap();
|
||||
assert!(!result.replayed);
|
||||
let report = &result.report;
|
||||
assert_eq!(report.status, ImportPlanApplyStatus::Applied);
|
||||
assert_eq!(report.counts.created, 1);
|
||||
assert_eq!(
|
||||
report.counts.excluded, 1,
|
||||
"excluded candidates remain explained"
|
||||
);
|
||||
assert_eq!(report.counts.rejected, 0);
|
||||
|
||||
let excluded = report
|
||||
.outcomes
|
||||
.iter()
|
||||
.find(|reported| reported.key == "not_picked")
|
||||
.expect("the excluded candidate must be explained in the report");
|
||||
assert_eq!(
|
||||
excluded.outcome,
|
||||
ImportPlanCandidateOutcome::Excluded,
|
||||
"an excluded candidate is reported, not mutated"
|
||||
);
|
||||
assert_eq!(excluded.reason.as_deref(), Some("not_selected"));
|
||||
assert!(
|
||||
excluded.operation_id.is_none(),
|
||||
"an excluded candidate must not gain an operation"
|
||||
);
|
||||
|
||||
// Exactly one operation exists in the workspace — the selected one.
|
||||
let listed = registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_apply_partial"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(listed.current_draft_version, 1);
|
||||
database.cleanup().await;
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
//! Crash-replay evidence, stale fingerprint, rollback atomicity and
|
||||
//! stale job/expiry/source conflicts.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_rejects_plan_material_inconsistent_with_its_anchor() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw_pool = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_apply_material_mismatch").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_apply_material_mismatch",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw_pool, &ws, now).await;
|
||||
|
||||
let fp = fingerprint();
|
||||
for (index, change) in ["plan_wrong_job", "plan_partial_full"].iter().enumerate() {
|
||||
let plan_id = format!("plan_material_mismatch_{index}");
|
||||
let mut payload = single_create_payload(&plan_id, job.as_str(), &fp);
|
||||
if *change == "plan_wrong_job" {
|
||||
payload["job_id"] = json!("different_job");
|
||||
} else {
|
||||
payload["selection"]["excluded"] = json!(["other"]);
|
||||
payload["selection"]["all"] = json!(["basic", "other"]);
|
||||
payload["counts"]["excluded"] = json!(1);
|
||||
}
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, &plan_id, &fp, payload).await;
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: change,
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &now,
|
||||
};
|
||||
assert!(matches!(
|
||||
registry.apply_import_plan(&request).await,
|
||||
Err(RegistryError::ImportPlanPayloadCorrupt { .. })
|
||||
));
|
||||
}
|
||||
|
||||
assert!(
|
||||
registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_apply_basic"))
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_returns_stored_report_after_job_cleanup() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw_pool = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_apply_replay").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_apply_replay",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw_pool, &ws, now).await;
|
||||
|
||||
let fp = fingerprint();
|
||||
let (plan, digest) = stored_plan(®istry, &ws, &job, "plan_replay", &fp).await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_replay",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
};
|
||||
let first = registry.apply_import_plan(&request).await.unwrap();
|
||||
assert!(!first.replayed);
|
||||
|
||||
// The job expires and the expired-job cleanup removes job + plan, but
|
||||
// the committed application evidence outlives both.
|
||||
sqlx::query(
|
||||
"update import_jobs set expires_at = $1
|
||||
where id = $2 and workspace_id = $3",
|
||||
)
|
||||
.bind(now - Duration::minutes(1))
|
||||
.bind(job.as_str())
|
||||
.bind(ws.as_str())
|
||||
.execute(&raw_pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let cleanup = registry.cleanup_expired_import_jobs(8).await.unwrap();
|
||||
assert_eq!(cleanup.deleted_jobs, 1);
|
||||
assert!(
|
||||
registry.get_import_job(&ws, &job).await.unwrap().is_none(),
|
||||
"the expired job must be gone"
|
||||
);
|
||||
assert!(
|
||||
registry
|
||||
.get_import_plan(&ws, &plan)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none(),
|
||||
"the plan must cascade with its job"
|
||||
);
|
||||
|
||||
// Replay after cleanup returns the stored immutable report.
|
||||
let replay = registry.apply_import_plan(&request).await.unwrap();
|
||||
assert!(
|
||||
replay.replayed,
|
||||
"replay evidence must outlive the plan and its job"
|
||||
);
|
||||
assert_eq!(
|
||||
replay.report, first.report,
|
||||
"the post-cleanup replay must be byte-for-byte the committed report"
|
||||
);
|
||||
|
||||
let stored = registry
|
||||
.get_import_plan_application(&ws, "idem_replay")
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("the application anchor must survive cleanup");
|
||||
assert_eq!(stored.plan_digest, digest);
|
||||
assert_eq!(stored.result.report, first.report);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_rejects_stale_fingerprint_without_mutation() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw_pool = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_apply_fp").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_apply_fp",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw_pool, &ws, now).await;
|
||||
|
||||
let fp = fingerprint();
|
||||
let (plan, digest) = stored_plan(®istry, &ws, &job, "plan_fp", &fp).await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
let drifted = json!({"importer": "test", "digest": "fp-2"});
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_fp",
|
||||
verified_fingerprint: &drifted,
|
||||
applied_at: &applied_at,
|
||||
};
|
||||
assert!(
|
||||
matches!(
|
||||
registry.apply_import_plan(&request).await,
|
||||
Err(RegistryError::ImportPlanFingerprintStale { .. })
|
||||
),
|
||||
"a fingerprint drift is a typed re-preview conflict"
|
||||
);
|
||||
assert!(
|
||||
registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_apply_basic"))
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none(),
|
||||
"zero mutation on a stale fingerprint"
|
||||
);
|
||||
assert_eq!(
|
||||
registry
|
||||
.get_import_plan_application(&ws, "idem_fp")
|
||||
.await
|
||||
.unwrap(),
|
||||
None
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_rolls_back_entire_plan_when_one_candidate_conflicts() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw_pool = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_apply_rollback").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_apply_rb",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw_pool, &ws, now).await;
|
||||
|
||||
// Occupies the name the second candidate wants.
|
||||
let mut blocker = plan_operation("op_blocker");
|
||||
blocker.name = "clash_tool".to_owned();
|
||||
registry
|
||||
.create_operation(&ws, &blocker, None)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let fp_value = json!({"importer": "test", "digest": "fp-rb"});
|
||||
let op_ok = plan_operation("op_rb_ok");
|
||||
let mut op_bad = plan_operation("op_rb_bad");
|
||||
op_bad.name = "clash_tool".to_owned();
|
||||
let payload = json!({
|
||||
"schema_version": "import-plan-v1",
|
||||
"plan_reference": "plan_rb",
|
||||
"job_id": job.as_str(),
|
||||
"fingerprint": fp_value.clone(),
|
||||
"source": { "source_id": SOURCE_ID, "digest": source_ref() },
|
||||
"dependencies": [],
|
||||
"selection": {
|
||||
"mode": "full",
|
||||
"all": ["a_ok", "z_bad"],
|
||||
"selected": ["a_ok", "z_bad"],
|
||||
"excluded": []
|
||||
},
|
||||
"counts": { "selected": 2, "excluded": 0, "actionable": 2, "blocked": 0 },
|
||||
"candidates": [
|
||||
{
|
||||
"key": "a_ok",
|
||||
"name": op_ok.name,
|
||||
"state": "actionable",
|
||||
"decision": { "action": "create" },
|
||||
"operation": op_ok
|
||||
},
|
||||
{
|
||||
"key": "z_bad",
|
||||
"name": op_bad.name,
|
||||
"state": "actionable",
|
||||
"decision": { "action": "create" },
|
||||
"operation": op_bad
|
||||
}
|
||||
]
|
||||
});
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, "plan_rb", &fp_value, payload).await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_rb",
|
||||
verified_fingerprint: &fp_value,
|
||||
applied_at: &applied_at,
|
||||
};
|
||||
|
||||
// One conflict rolls the whole transaction back: no partial state.
|
||||
assert!(
|
||||
matches!(
|
||||
registry.apply_import_plan(&request).await,
|
||||
Err(RegistryError::ImportPlanNameConflict { name }) if name == "clash_tool"
|
||||
),
|
||||
"a candidate conflict must produce a typed conflict"
|
||||
);
|
||||
assert!(
|
||||
registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_rb_ok"))
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none(),
|
||||
"the earlier successful candidate must roll back with the transaction"
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("select count(*) from operations")
|
||||
.fetch_one(&raw_pool)
|
||||
.await
|
||||
.unwrap(),
|
||||
1,
|
||||
"only the pre-existing blocker operation remains"
|
||||
);
|
||||
assert_eq!(
|
||||
registry
|
||||
.get_import_plan_application(&ws, "idem_rb")
|
||||
.await
|
||||
.unwrap(),
|
||||
None,
|
||||
"a rolled-back apply must not persist application evidence"
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_rejects_expired_plan_expired_job_and_detached_source() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw_pool = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_apply_stale").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_apply_stale",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw_pool, &ws, now).await;
|
||||
|
||||
let fp = fingerprint();
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
|
||||
// All three plans are created while the anchor job is still valid.
|
||||
let expired_payload = single_create_payload("plan_stale_p", job.as_str(), &fp);
|
||||
let p1 = ImportPlanId::new("plan_stale_p");
|
||||
let d1 = registry
|
||||
.create_import_plan(CreateImportPlanRequest {
|
||||
id: &p1,
|
||||
workspace_id: &ws,
|
||||
job_id: &job,
|
||||
payload: &expired_payload,
|
||||
created_at: &(now - Duration::hours(2)),
|
||||
expires_at: &(now - Duration::hours(1)),
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.digest;
|
||||
let (p2, d2) = stored_plan(®istry, &ws, &job, "plan_stale_j", &fp).await;
|
||||
let (p3, d3) = stored_plan(®istry, &ws, &job, "plan_stale_s", &fp).await;
|
||||
|
||||
// The plan was created with a past lifetime; immutable rows stay untouched.
|
||||
assert!(
|
||||
matches!(
|
||||
registry
|
||||
.apply_import_plan(&ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &p1,
|
||||
plan_digest: &d1,
|
||||
idempotency_key: "idem_stale_p",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
})
|
||||
.await,
|
||||
Err(RegistryError::ImportPlanExpired { .. })
|
||||
),
|
||||
"an expired plan must be a typed expired conflict"
|
||||
);
|
||||
|
||||
// Expired anchor job (plan still inside its lifetime).
|
||||
sqlx::query("update import_jobs set expires_at = $1 where id = $2 and workspace_id = $3")
|
||||
.bind(now - Duration::minutes(5))
|
||||
.bind(job.as_str())
|
||||
.bind(ws.as_str())
|
||||
.execute(&raw_pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let r2 = registry
|
||||
.apply_import_plan(&ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &p2,
|
||||
plan_digest: &d2,
|
||||
idempotency_key: "idem_stale_j",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
matches!(&r2, Err(RegistryError::ImportPlanExpired { .. })),
|
||||
"an expired anchor job must be a typed expired conflict, got {r2:?}"
|
||||
);
|
||||
|
||||
// Restored job lifetime; now the source itself is detached.
|
||||
sqlx::query("update import_jobs set expires_at = $1 where id = $2 and workspace_id = $3")
|
||||
.bind(now + Duration::hours(1))
|
||||
.bind(job.as_str())
|
||||
.bind(ws.as_str())
|
||||
.execute(&raw_pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"update artifact_sources set lifecycle = 'detached', detached_at = $3
|
||||
where workspace_id = $1 and source_id = $2",
|
||||
)
|
||||
.bind(ws.as_str())
|
||||
.bind(SOURCE_ID)
|
||||
.bind(now)
|
||||
.execute(&raw_pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let r3 = registry
|
||||
.apply_import_plan(&ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &p3,
|
||||
plan_digest: &d3,
|
||||
idempotency_key: "idem_stale_s",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
matches!(&r3, Err(RegistryError::SourceUnavailable)),
|
||||
"a detached source must be a typed conflict, got {r3:?}"
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
//! `skip` keeps the exact target untouched; `rename` creates the exact
|
||||
//! planned name and never auto-generates a fallback.
|
||||
|
||||
use super::*;
|
||||
|
||||
async fn operation_count(raw_pool: &PgPool) -> i64 {
|
||||
sqlx::query_scalar::<_, i64>("select count(*) from operations")
|
||||
.fetch_one(raw_pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn skip_payload(plan_id: &str, job_id: &str, fingerprint: &Value, target_version: u32) -> Value {
|
||||
json!({
|
||||
"schema_version": "import-plan-v1",
|
||||
"plan_reference": plan_id,
|
||||
"job_id": job_id,
|
||||
"fingerprint": fingerprint,
|
||||
"source": { "source_id": SOURCE_ID, "digest": source_ref() },
|
||||
"dependencies": [],
|
||||
"selection": {
|
||||
"mode": "full",
|
||||
"all": ["sk"],
|
||||
"selected": ["sk"],
|
||||
"excluded": []
|
||||
},
|
||||
"counts": { "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 },
|
||||
"candidates": [{
|
||||
"key": "sk",
|
||||
"name": "op_skip_tool",
|
||||
"state": "actionable",
|
||||
"decision": {
|
||||
"action": "skip",
|
||||
"target_operation_id": "op_skip"
|
||||
},
|
||||
"target": {
|
||||
"operation_id": "op_skip",
|
||||
"name": "op_skip_tool",
|
||||
"expected_state": {
|
||||
"status": "draft",
|
||||
"current_draft_version": target_version,
|
||||
"latest_published_version": null
|
||||
}
|
||||
}
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_skip_keeps_exact_target_untouched_and_stale_target_conflicts() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw_pool = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_apply_skip").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_apply_skip",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw_pool, &ws, now).await;
|
||||
|
||||
// Existing operation that the plan will skip.
|
||||
let existing = plan_operation("op_skip");
|
||||
registry
|
||||
.create_operation(&ws, &existing, None)
|
||||
.await
|
||||
.unwrap();
|
||||
let before = registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_skip"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(before.current_draft_version, 1);
|
||||
|
||||
let fp = fingerprint();
|
||||
let ok_payload = skip_payload("plan_skip_ok", job.as_str(), &fp, 1);
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, "plan_skip_ok", &fp, ok_payload).await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_skip",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
};
|
||||
|
||||
let result = registry.apply_import_plan(&request).await.unwrap();
|
||||
assert!(!result.replayed);
|
||||
let report = &result.report;
|
||||
assert_eq!(report.status, ImportPlanApplyStatus::Applied);
|
||||
assert_eq!(report.counts.skipped, 1);
|
||||
assert_eq!(report.counts.created, 0);
|
||||
let skipped = &report.outcomes[0];
|
||||
assert_eq!(skipped.outcome, ImportPlanCandidateOutcome::Skipped);
|
||||
assert_eq!(skipped.operation_id.as_deref(), Some("op_skip"));
|
||||
assert!(
|
||||
skipped.version.is_none(),
|
||||
"a skip must not produce a new version"
|
||||
);
|
||||
|
||||
// The exact target is untouched.
|
||||
let after = registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_skip"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
before, after,
|
||||
"skip must leave the authorized target unchanged"
|
||||
);
|
||||
assert_eq!(operation_count(&raw_pool).await, 1);
|
||||
|
||||
// A stale target state (wrong expected draft version) is a typed conflict.
|
||||
let stale_payload = skip_payload("plan_skip_stale", job.as_str(), &fp, 2);
|
||||
let (stale_plan, stale_digest) =
|
||||
store_plan(®istry, &ws, &job, "plan_skip_stale", &fp, stale_payload).await;
|
||||
let stale_request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &stale_plan,
|
||||
plan_digest: &stale_digest,
|
||||
idempotency_key: "idem_skip_stale",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
};
|
||||
assert!(
|
||||
matches!(
|
||||
registry.apply_import_plan(&stale_request).await,
|
||||
Err(RegistryError::ImportPlanTargetStale {
|
||||
operation_id
|
||||
}) if operation_id == "op_skip"
|
||||
),
|
||||
"a stale skip target must be a typed conflict"
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
fn rename_payload(plan_id: &str, job_id: &str, fingerprint: &Value) -> Value {
|
||||
let mut operation = plan_operation("op_renamed");
|
||||
operation.name = "renamed_tool".to_owned();
|
||||
json!({
|
||||
"schema_version": "import-plan-v1",
|
||||
"plan_reference": plan_id,
|
||||
"job_id": job_id,
|
||||
"fingerprint": fingerprint,
|
||||
"source": { "source_id": SOURCE_ID, "digest": source_ref() },
|
||||
"dependencies": [],
|
||||
"selection": {
|
||||
"mode": "full",
|
||||
"all": ["rn"],
|
||||
"selected": ["rn"],
|
||||
"excluded": []
|
||||
},
|
||||
"counts": { "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 },
|
||||
"candidates": [{
|
||||
"key": "rn",
|
||||
"name": "renamed_tool",
|
||||
"state": "actionable",
|
||||
"decision": { "action": "rename", "confirmed_name": "renamed_tool" },
|
||||
"operation": operation
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_rename_creates_exact_planned_name_and_stale_name_conflicts() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw_pool = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_apply_rename").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_apply_rename",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw_pool, &ws, now).await;
|
||||
|
||||
let fp = fingerprint();
|
||||
let payload = rename_payload("plan_rename", job.as_str(), &fp);
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, "plan_rename", &fp, payload).await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_rename",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
};
|
||||
|
||||
// Confirmed name is free: the exact separate Operation is created.
|
||||
let result = registry.apply_import_plan(&request).await.unwrap();
|
||||
assert!(!result.replayed);
|
||||
let report = &result.report;
|
||||
assert_eq!(report.status, ImportPlanApplyStatus::Applied);
|
||||
assert_eq!(report.counts.renamed, 1);
|
||||
assert_eq!(report.counts.created, 0);
|
||||
assert_eq!(
|
||||
report.outcomes[0].outcome,
|
||||
ImportPlanCandidateOutcome::Renamed
|
||||
);
|
||||
let renamed = registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_renamed"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
renamed.name, "renamed_tool",
|
||||
"the exact planned name is materialized"
|
||||
);
|
||||
assert_eq!(renamed.current_draft_version, 1);
|
||||
|
||||
// A different plan confirming a name that is already taken conflicts,
|
||||
// and never falls back to an auto-generated alternative.
|
||||
let mut blocker = plan_operation("op_blocker");
|
||||
blocker.name = "occupied_tool".to_owned();
|
||||
registry
|
||||
.create_operation(&ws, &blocker, None)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut conflicting_op = plan_operation("op_conflict");
|
||||
conflicting_op.name = "occupied_tool".to_owned();
|
||||
let conflicting_payload = json!({
|
||||
"schema_version": "import-plan-v1",
|
||||
"plan_reference": "plan_rename_stale",
|
||||
"job_id": job.as_str(),
|
||||
"fingerprint": fp,
|
||||
"source": { "source_id": SOURCE_ID, "digest": source_ref() },
|
||||
"dependencies": [],
|
||||
"selection": {
|
||||
"mode": "full",
|
||||
"all": ["rn2"],
|
||||
"selected": ["rn2"],
|
||||
"excluded": []
|
||||
},
|
||||
"counts": { "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 },
|
||||
"candidates": [{
|
||||
"key": "rn2",
|
||||
"name": "occupied_tool",
|
||||
"state": "actionable",
|
||||
"decision": { "action": "rename", "confirmed_name": "occupied_tool" },
|
||||
"operation": conflicting_op
|
||||
}]
|
||||
});
|
||||
let (stale_plan, stale_digest) = store_plan(
|
||||
®istry,
|
||||
&ws,
|
||||
&job,
|
||||
"plan_rename_stale",
|
||||
&fp,
|
||||
conflicting_payload,
|
||||
)
|
||||
.await;
|
||||
let stale_request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &stale_plan,
|
||||
plan_digest: &stale_digest,
|
||||
idempotency_key: "idem_rename_stale",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
};
|
||||
assert!(
|
||||
matches!(
|
||||
registry
|
||||
.apply_import_plan(&stale_request)
|
||||
.await
|
||||
.err(),
|
||||
Some(RegistryError::ImportPlanNameConflict { ref name })
|
||||
if *name == "occupied_tool"
|
||||
),
|
||||
"a taken confirmed name must conflict, never auto-rename"
|
||||
);
|
||||
// Only the pre-existing blocker carries that name — zero new operations.
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>(
|
||||
"select count(*) from operations where name = 'occupied_tool'"
|
||||
)
|
||||
.fetch_one(&raw_pool)
|
||||
.await
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
Reference in new issue
Block a user