Files
crank/crates/crank-registry/tests/integration/import_plan/create.rs
T
bsodfather e93de7015a
CI / Rust Checks (pull_request) Failing after 1s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
feat(import): complete OpenAPI onboarding and verify delivery
2026-10-09 17:50:38 +03:00

989 lines
32 KiB
Rust

use super::super::common::TestDatabase;
use super::{create_pending_openapi_job, create_workspace};
use time::Duration;
use crank_artifacts::ArtifactRef;
use crank_core::WorkspaceId;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use sqlx::Row;
use time::OffsetDateTime;
use crank_registry::{
ArtifactSourceId, CreateImportJobRequest, CreateImportPlanRequest, ImportJobId, ImportJobKind,
ImportJobSourceEnvelope, ImportJobStatus, ImportPlan, ImportPlanId, RegistryError,
};
fn plan_payload() -> Value {
json!({
"selection": ["a", "b"],
"mode": "full",
"decisions": { "a": "keep" }
})
}
fn expected_digest(payload: &Value) -> String {
let canonical = serde_json::to_vec(payload).unwrap();
format!("{:x}", Sha256::digest(canonical))
}
fn current_second() -> OffsetDateTime {
OffsetDateTime::from_unix_timestamp(OffsetDateTime::now_utc().unix_timestamp()).unwrap()
}
#[tokio::test]
async fn import_plan_roundtrips_with_registry_computed_digest_and_foorescope_is_invisible() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let created_at = current_second();
let expires_at = created_at + Duration::hours(24);
let ws1 = create_workspace(&registry, "ws_plan_a").await;
let ws2 = create_workspace(&registry, "ws_plan_b").await;
let job1 = create_pending_openapi_job(&registry, &ws1, "job_a", created_at, expires_at).await;
let plan = ImportPlanId::new("plan_a");
let payload = plan_payload();
let digest = expected_digest(&payload);
let created = registry
.create_import_plan(CreateImportPlanRequest {
id: &plan,
workspace_id: &ws1,
job_id: &job1,
payload: &payload,
created_at: &created_at,
expires_at: &expires_at,
})
.await
.unwrap();
assert_eq!(created.id, plan);
assert_eq!(created.workspace_id, ws1);
assert_eq!(created.job_id, job1);
assert_eq!(created.payload, payload);
assert_eq!(created.created_at, created_at);
assert_eq!(created.expires_at, expires_at);
// Registry-derived digest must match an independent recomputation and be
// lowercase 64-hex.
assert_eq!(created.digest, digest);
assert_eq!(created.digest.len(), 64);
assert!(
created
.digest
.bytes()
.all(|b| b.is_ascii_digit() || matches!(b, b'a'..=b'f'))
);
// Read returns the exact stored fields.
let read = registry
.get_import_plan(&ws1, &plan)
.await
.unwrap()
.expect("plan must be visible in its own workspace");
assert_eq!(read, created);
// A plan id that only exists in ws1 is invisible from ws2 via `None`,
// never an error.
let absent = registry.get_import_plan(&ws2, &plan).await.unwrap();
assert!(
absent.is_none(),
"foreign-scope plan must be invisible, not an error"
);
let missing = ImportPlanId::new("does_not_exist");
assert!(
registry
.get_import_plan(&ws1, &missing)
.await
.unwrap()
.is_none()
);
database.cleanup().await;
}
#[tokio::test]
async fn duplicate_replay_returns_same_plan_but_changed_material_or_expiry_conflicts() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let created_at = current_second();
let expires_at = created_at + Duration::hours(24);
let ws = create_workspace(&registry, "ws_replay").await;
let job = create_pending_openapi_job(&registry, &ws, "job_r", created_at, expires_at).await;
let plan = ImportPlanId::new("plan_r");
let payload = plan_payload();
let first = registry
.create_import_plan(CreateImportPlanRequest {
id: &plan,
workspace_id: &ws,
job_id: &job,
payload: &payload,
created_at: &created_at,
expires_at: &expires_at,
})
.await
.unwrap();
// Byte-identical material, same job and same lifetime -> the same immutable
// plan is returned (a replay), not a conflict.
let replayed = registry
.create_import_plan(CreateImportPlanRequest {
id: &plan,
workspace_id: &ws,
job_id: &job,
payload: &payload,
created_at: &created_at,
expires_at: &expires_at,
})
.await
.unwrap();
assert_eq!(
replayed, first,
"an identical replay must return the same plan"
);
// Same id + different material -> typed conflict, no UPDATE.
let changed = json!({ "mode": "partial" });
let conflict = registry
.create_import_plan(CreateImportPlanRequest {
id: &plan,
workspace_id: &ws,
job_id: &job,
payload: &changed,
created_at: &created_at,
expires_at: &expires_at,
})
.await
.expect_err("the same id with changed material must conflict");
assert!(
matches!(conflict, RegistryError::ImportPlanConflict { .. }),
"{conflict:?}"
);
assert_eq!(
registry.get_import_plan(&ws, &plan).await.unwrap().unwrap(),
first,
"the conflicting request must not have overwritten the stored plan"
);
// Same id + same material + different expiry -> typed conflict.
let other_expiry = expires_at + Duration::hours(1);
let conflict = registry
.create_import_plan(CreateImportPlanRequest {
id: &plan,
workspace_id: &ws,
job_id: &job,
payload: &payload,
created_at: &created_at,
expires_at: &other_expiry,
})
.await
.expect_err("the same id with a different lifetime must conflict");
assert!(
matches!(conflict, RegistryError::ImportPlanConflict { .. }),
"{conflict:?}"
);
database.cleanup().await;
}
#[tokio::test]
async fn cross_workspace_same_plan_id_is_separate_but_scoped_invisible() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let created_at = current_second();
let expires_at = created_at + Duration::hours(24);
let ws1 = create_workspace(&registry, "ws_cw_1").await;
let ws2 = create_workspace(&registry, "ws_cw_2").await;
let job1 = create_pending_openapi_job(&registry, &ws1, "job_cw1", created_at, expires_at).await;
let job2 = create_pending_openapi_job(&registry, &ws2, "job_cw2", created_at, expires_at).await;
let plan = ImportPlanId::new("shared_id");
let payload = plan_payload();
// The same id is legal per workspace and binds to that workspace's job.
let in_ws2 = registry
.create_import_plan(CreateImportPlanRequest {
id: &plan,
workspace_id: &ws2,
job_id: &job2,
payload: &payload,
created_at: &created_at,
expires_at: &expires_at,
})
.await
.unwrap();
assert_eq!(in_ws2.workspace_id, ws2);
assert_eq!(in_ws2.job_id, job2);
// ws1 has not yet created the id, so it is invisible there ...
assert!(
registry
.get_import_plan(&ws1, &plan)
.await
.unwrap()
.is_none()
);
let in_ws1 = registry
.create_import_plan(CreateImportPlanRequest {
id: &plan,
workspace_id: &ws1,
job_id: &job1,
payload: &payload,
created_at: &created_at,
expires_at: &expires_at,
})
.await
.unwrap();
assert_eq!(in_ws1.workspace_id, ws1);
assert_eq!(in_ws1.job_id, job1);
// Each workspace now reads back exactly its own row.
assert_eq!(
registry
.get_import_plan(&ws1, &plan)
.await
.unwrap()
.unwrap(),
in_ws1
);
assert_eq!(
registry
.get_import_plan(&ws2, &plan)
.await
.unwrap()
.unwrap(),
in_ws2
);
database.cleanup().await;
}
#[tokio::test]
async fn create_rejects_invalid_input_bounds() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let created_at = current_second();
let expires_at = created_at + Duration::hours(24);
let ws = create_workspace(&registry, "ws_bounds").await;
let job = create_pending_openapi_job(&registry, &ws, "job_b", created_at, expires_at).await;
let payload = plan_payload();
// Empty id (0 bytes) is rejected.
let empty_id = ImportPlanId::new("");
assert!(matches!(
registry
.create_import_plan(CreateImportPlanRequest {
id: &empty_id,
workspace_id: &ws,
job_id: &job,
payload: &payload,
created_at: &created_at,
expires_at: &expires_at,
})
.await
.unwrap_err(),
RegistryError::InvalidImportPlan { field: "id" }
));
// Over-long id (> 128 bytes) is rejected.
let long_id = ImportPlanId::new("id".repeat(70)); // 140 bytes
assert!(matches!(
registry
.create_import_plan(CreateImportPlanRequest {
id: &long_id,
workspace_id: &ws,
job_id: &job,
payload: &payload,
created_at: &created_at,
expires_at: &expires_at,
})
.await
.unwrap_err(),
RegistryError::InvalidImportPlan { field: "id" }
));
// A non-object payload is rejected.
let arr = json!([1, 2, 3]);
assert!(matches!(
registry
.create_import_plan(CreateImportPlanRequest {
id: &ImportPlanId::new("plan_ok"),
workspace_id: &ws,
job_id: &job,
payload: &arr,
created_at: &created_at,
expires_at: &expires_at,
})
.await
.unwrap_err(),
RegistryError::InvalidImportPlan { field: "payload" }
));
// expires_at must be strictly greater than created_at.
for bad_expires in [created_at, created_at - Duration::minutes(1)] {
assert!(matches!(
registry
.create_import_plan(CreateImportPlanRequest {
id: &ImportPlanId::new("plan_ttl"),
workspace_id: &ws,
job_id: &job,
payload: &payload,
created_at: &created_at,
expires_at: &bad_expires,
})
.await
.unwrap_err(),
RegistryError::InvalidImportPlan {
field: "expires_at"
}
));
}
// A serialized payload over the 4 MiB ceiling is rejected.
let big = json!({ "blob": "x".repeat(4 * 1024 * 1024) });
assert!(matches!(
registry
.create_import_plan(CreateImportPlanRequest {
id: &ImportPlanId::new("plan_big"),
workspace_id: &ws,
job_id: &job,
payload: &big,
created_at: &created_at,
expires_at: &expires_at,
})
.await
.unwrap_err(),
RegistryError::InvalidImportPlan { field: "payload" }
));
// A get also validates the id bound without leaking row data.
assert!(matches!(
registry
.get_import_plan(&ws, &ImportPlanId::new(""))
.await
.unwrap_err(),
RegistryError::InvalidImportPlan { field: "id" }
));
database.cleanup().await;
}
#[tokio::test]
async fn create_rejects_terminal_expired_foreign_and_unsourced_jobs() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let created_at = current_second();
let expires_at = created_at + Duration::hours(24);
let now = OffsetDateTime::now_utc();
let ws = create_workspace(&registry, "ws_job_states").await;
let ws_other = create_workspace(&registry, "ws_job_other").await;
let payload = plan_payload();
// Terminal (completed) job -> typed terminal conflict.
let completed_job = ImportJobId::new("job_done");
{
let source_id = ArtifactSourceId::new("src_openapi_test");
let digest = ArtifactRef::from_digest_hex(&"cd".repeat(32)).unwrap();
let preview_payload = json!({
"source": { "source_id": source_id.as_str(), "digest": digest.as_str() },
});
registry
.create_import_job(CreateImportJobRequest {
id: &completed_job,
workspace_id: &ws,
kind: ImportJobKind::OpenApi,
source_format: "openapi",
source_version: Some("3.1.0"),
status: ImportJobStatus::Completed,
source: &ImportJobSourceEnvelope {
source_id,
digest: digest.clone(),
},
preview_payload: &preview_payload,
created_at: &created_at,
expires_at: &expires_at,
})
.await
.unwrap();
}
assert!(matches!(
attempt_create(
&registry,
&ws,
&ImportPlanId::new("plan_jobs"),
&completed_job,
&payload,
&created_at,
&expires_at
)
.await
.unwrap_err(),
RegistryError::ImportPlanJobTerminal { .. }
));
// Expired (non-terminal) job -> typed expired conflict.
let expired_job = ImportJobId::new("job_expired");
{
let source_id = ArtifactSourceId::new("src_openapi_test");
let digest = ArtifactRef::from_digest_hex(&"ef".repeat(32)).unwrap();
let created_back = now - Duration::hours(3);
let expired_at = now - Duration::hours(1);
let preview_payload = json!({
"source": { "source_id": source_id.as_str(), "digest": digest.as_str() },
});
registry
.create_import_job(CreateImportJobRequest {
id: &expired_job,
workspace_id: &ws,
kind: ImportJobKind::OpenApi,
source_format: "openapi",
source_version: Some("3.1.0"),
status: ImportJobStatus::Pending,
source: &ImportJobSourceEnvelope {
source_id,
digest: digest.clone(),
},
preview_payload: &preview_payload,
created_at: &created_back,
expires_at: &expired_at,
})
.await
.unwrap();
}
assert!(matches!(
attempt_create(
&registry,
&ws,
&ImportPlanId::new("plan_jobs"),
&expired_job,
&payload,
&created_at,
&expires_at
)
.await
.unwrap_err(),
RegistryError::ImportPlanJobExpired { .. }
));
// A job that belongs to another workspace is unavailable in this scope.
let foreign_job =
create_pending_openapi_job(&registry, &ws_other, "job_foreign", created_at, expires_at)
.await;
assert!(matches!(
attempt_create(
&registry,
&ws,
&ImportPlanId::new("plan_jobs"),
&foreign_job,
&payload,
&created_at,
&expires_at
)
.await
.unwrap_err(),
RegistryError::ImportPlanJobUnavailable { .. }
));
// A pending job with no verifiable source envelope is unavailable.
let raw = database.raw_pool().await;
sqlx::query(
"insert into import_jobs (
id, workspace_id, kind, source_format, status, preview_payload, created_at, expires_at
) values (
'job_unsourced', $1, 'open_api', 'openapi', 'pending', '{}'::jsonb, $2, $3
)",
)
.bind(ws.as_str())
.bind(created_at)
.bind(expires_at)
.execute(&raw)
.await
.unwrap();
let unsourced_job = ImportJobId::new("job_unsourced");
assert!(matches!(
attempt_create(
&registry,
&ws,
&ImportPlanId::new("plan_jobs"),
&unsourced_job,
&payload,
&created_at,
&expires_at
)
.await
.unwrap_err(),
RegistryError::ImportPlanJobUnavailable { .. }
));
database.cleanup().await;
}
#[tokio::test]
async fn concurrent_create_with_same_plan_id_serializes_to_replay_or_typed_conflict() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let created_at = current_second();
let expires_at = created_at + Duration::hours(24);
let ws = create_workspace(&registry, "ws_race").await;
let job = create_pending_openapi_job(&registry, &ws, "job_race", created_at, expires_at).await;
// Identical material racing on the same id: both callers must converge
// on the same stored plan, never a raw unique violation.
let plan_same = ImportPlanId::new("plan_race_same");
let racers_same = plan_same.clone();
let payload_a = plan_payload();
let (first, second) = tokio::join!(
attempt_create(
&registry,
&ws,
&plan_same,
&job,
&payload_a,
&created_at,
&expires_at
),
attempt_create(
&registry,
&ws,
&racers_same,
&job,
&payload_a,
&created_at,
&expires_at
)
);
let first = first.expect("concurrent identical insert must succeed");
let second = second.expect("the loser must converge onto a replay, not an error");
assert_eq!(
first, second,
"both callers must see the same immutable plan"
);
assert_eq!(
registry
.get_import_plan(&ws, &plan_same)
.await
.unwrap()
.unwrap(),
first,
"the stored plan must be the one both racers returned"
);
// Different material racing on the same id: exactly one winner, and the
// loser must get the typed conflict, never a raw unique violation.
let plan_other = ImportPlanId::new("plan_race_diff");
let racers_other = plan_other.clone();
let payload_b = json!({ "mode": "partial" });
let (a, b) = tokio::join!(
attempt_create(
&registry,
&ws,
&plan_other,
&job,
&payload_a,
&created_at,
&expires_at
),
attempt_create(
&registry,
&ws,
&racers_other,
&job,
&payload_b,
&created_at,
&expires_at
)
);
let stored = registry
.get_import_plan(&ws, &plan_other)
.await
.unwrap()
.unwrap();
assert!(
a.is_ok() ^ b.is_ok(),
"exactly one racer may install the plan: a={a:?}, b={b:?}"
);
for result in [a, b] {
match result {
Ok(plan) => assert_eq!(
plan,
stored.clone(),
"the winner must equal the stored plan"
),
Err(error) => assert!(
matches!(error, RegistryError::ImportPlanConflict { .. }),
"the losing racer must see the typed conflict, got {error:?}"
),
}
}
database.cleanup().await;
}
#[tokio::test]
async fn sub_microsecond_timestamps_roundtrip_and_replay_identically() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
// Sub-microsecond instants: the Postgres timestamptz column stores
// microseconds, so the registry must normalize deterministically instead
// of letting read-back silently truncate only on the second read.
let created_at = OffsetDateTime::from_unix_timestamp_nanos(1_800_000_000_123_456_789).unwrap();
let expires_at_nanos = 1_800_000_000_123_456_789 + 86_400_000_000_512;
let expires_at = OffsetDateTime::from_unix_timestamp_nanos(expires_at_nanos).unwrap();
let expected_created =
OffsetDateTime::from_unix_timestamp_nanos((1_800_000_000_123_456_789 / 1_000) * 1_000)
.unwrap();
let expected_expires =
OffsetDateTime::from_unix_timestamp_nanos((expires_at_nanos / 1_000) * 1_000).unwrap();
let ws = create_workspace(&registry, "ws_micro").await;
let job = create_pending_openapi_job(
&registry,
&ws,
"job_micro",
expected_created,
expected_expires + Duration::hours(1),
)
.await;
let plan = ImportPlanId::new("plan_micro");
let payload = plan_payload();
let created = registry
.create_import_plan(CreateImportPlanRequest {
id: &plan,
workspace_id: &ws,
job_id: &job,
payload: &payload,
created_at: &created_at,
expires_at: &expires_at,
})
.await
.unwrap();
// The first returned object already carries the DB-precision values.
assert_eq!(created.created_at, expected_created);
assert_eq!(created.expires_at, expected_expires);
// Every later read must be identical to the first response.
let read = registry.get_import_plan(&ws, &plan).await.unwrap().unwrap();
assert_eq!(
read, created,
"the read-back plan must equal the created plan"
);
// A replay re-issued with the original nanosecond instants must still be
// recognized as the same material, not a spurious conflict.
let replayed = registry
.create_import_plan(CreateImportPlanRequest {
id: &plan,
workspace_id: &ws,
job_id: &job,
payload: &payload,
created_at: &created_at,
expires_at: &expires_at,
})
.await
.unwrap_or_else(|error| {
panic!("an identical replay with sub-microsecond instants must succeed, got {error:?}")
});
assert_eq!(replayed, created, "the replay must return the stored plan");
database.cleanup().await;
}
#[tokio::test]
async fn plan_expiration_must_not_outlive_its_job() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let created_at = current_second();
let job_expires_at = created_at + Duration::hours(24);
let ws = create_workspace(&registry, "ws_expires").await;
let payload = plan_payload();
// A plan living exactly as long as the job is allowed (expires_at <= job).
let exact_job =
create_pending_openapi_job(&registry, &ws, "job_exact", created_at, job_expires_at).await;
let created = registry
.create_import_plan(CreateImportPlanRequest {
id: &ImportPlanId::new("plan_exact"),
workspace_id: &ws,
job_id: &exact_job,
payload: &payload,
created_at: &created_at,
expires_at: &job_expires_at,
})
.await
.expect("a plan expiring exactly with its job must be accepted");
assert_eq!(created.expires_at, job_expires_at);
// A plan outliving the job is rejected with a typed input error.
let long_job =
create_pending_openapi_job(&registry, &ws, "job_long", created_at, job_expires_at).await;
assert!(matches!(
attempt_create(
&registry,
&ws,
&ImportPlanId::new("plan_long"),
&long_job,
&payload,
&created_at,
&(job_expires_at + Duration::hours(1))
)
.await
.unwrap_err(),
RegistryError::InvalidImportPlan {
field: "expires_at"
}
));
// The rejection left no plan behind and did not mutate the job.
assert!(
registry
.get_import_plan(&ws, &ImportPlanId::new("plan_long"))
.await
.unwrap()
.is_none()
);
let job = registry
.get_import_job(&ws, &long_job)
.await
.unwrap()
.unwrap();
assert_eq!(job.status, ImportJobStatus::Pending);
database.cleanup().await;
}
async fn attempt_create(
registry: &crank_registry::PostgresRegistry,
ws: &WorkspaceId,
plan_id: &ImportPlanId,
job: &ImportJobId,
payload: &Value,
created_at: &OffsetDateTime,
expires_at: &OffsetDateTime,
) -> Result<ImportPlan, RegistryError> {
registry
.create_import_plan(CreateImportPlanRequest {
id: plan_id,
workspace_id: ws,
job_id: job,
payload,
created_at,
expires_at,
})
.await
}
#[tokio::test]
async fn plans_do_not_mutate_the_legacy_import_job_contract() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let created_at = current_second();
let expires_at = created_at + Duration::hours(24);
let ws = create_workspace(&registry, "ws_legacy").await;
let job =
create_pending_openapi_job(&registry, &ws, "job_legacy", created_at, expires_at).await;
let before = registry.get_import_job(&ws, &job).await.unwrap().unwrap();
assert_eq!(before.status, ImportJobStatus::Pending);
assert_eq!(before.error_text, None);
let plan = ImportPlanId::new("plan_legacy");
let payload = plan_payload();
let _plan = registry
.create_import_plan(CreateImportPlanRequest {
id: &plan,
workspace_id: &ws,
job_id: &job,
payload: &payload,
created_at: &created_at,
expires_at: &expires_at,
})
.await
.unwrap();
// The legacy read contract is unchanged by plan creation: same pending
// status, no error text, and the original preview payload byte-for-byte.
let after = registry
.get_import_job(&ws, &job)
.await
.unwrap()
.expect("legacy import job must still be readable");
assert_eq!(after.status, ImportJobStatus::Pending);
assert_eq!(after.error_text, None);
assert_eq!(after.preview_payload, before.preview_payload);
// Legacy get_import_job continues to honor workspace scoping.
assert!(
registry
.get_import_job(&create_workspace(&registry, "ws_none").await, &job)
.await
.unwrap()
.is_none()
);
database.cleanup().await;
}
#[tokio::test]
async fn expired_cleanup_deletes_job_and_plan_but_keeps_application_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(&registry, "ws_cleanup").await;
// Pending OpenAPI job with a verifiable source envelope that is still
// alive when the plan is created ...
let job_created = now - Duration::hours(2);
let job_expires = now + Duration::hours(1);
let job =
create_pending_openapi_job(&registry, &ws, "job_cleanup", job_created, job_expires).await;
// ... anchored by an active source row so the cleanup detachment is
// observable ...
let blob_digest = "ab".repeat(32);
sqlx::query(
"insert into artifact_blobs (digest, artifact_ref, size_bytes, created_at, updated_at)
values ($1, 'sha256:' || $1, 16, $2, $2)",
)
.bind(&blob_digest)
.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, 'src_openapi_test', $2, 'application/yaml', 'public', 'active', $3, $3)",
)
.bind(ws.as_str())
.bind(&blob_digest)
.bind(now)
.execute(&raw)
.await
.unwrap();
// ... and a plan that does not outlive the job plus its idempotent
// application report ...
let plan = ImportPlanId::new("plan_cleanup");
let payload = plan_payload();
let plan_created = now - Duration::minutes(45);
let plan_expires = now - Duration::minutes(15);
let created = registry
.create_import_plan(CreateImportPlanRequest {
id: &plan,
workspace_id: &ws,
job_id: &job,
payload: &payload,
created_at: &plan_created,
expires_at: &plan_expires,
})
.await
.unwrap();
let report = json!({
"application_key": "app_cleanup_1",
"created": [
{ "operation_key": "a", "name": "op_a" }
]
});
sqlx::query(
"insert into import_plan_applications (
workspace_id, idempotency_key, plan_id, plan_digest, report, created_at
) values ($1, 'idem_cleanup', 'plan_cleanup', $2, $3, $4)",
)
.bind(ws.as_str())
.bind(&created.digest)
.bind(&report)
.bind(now)
.execute(&raw)
.await
.unwrap();
// The job expires (its plan was created while it was still valid).
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)
.await
.unwrap();
let cleanup = registry
.cleanup_expired_import_jobs(8)
.await
.expect("expired-job cleanup must succeed when the job carries a plan");
assert_eq!(cleanup.deleted_jobs, 1, "the expired job must be removed");
assert_eq!(
cleanup.detached_sources, 1,
"the job's source must be detached exactly once"
);
assert!(
!cleanup.more_work,
"a single expired job is the whole workload"
);
assert_eq!(
sqlx::query_scalar::<_, i64>("select count(*) from import_jobs")
.fetch_one(&raw)
.await
.unwrap(),
0,
"the expired job must be gone"
);
assert_eq!(
sqlx::query_scalar::<_, i64>("select count(*) from import_plans")
.fetch_one(&raw)
.await
.unwrap(),
0,
"the plan must cascade with its job, not block the cleanup"
);
assert_eq!(
registry.get_import_job(&ws, &job).await.unwrap(),
None,
"the registry read sees no job after cleanup"
);
assert_eq!(
registry.get_import_plan(&ws, &plan).await.unwrap(),
None,
"the registry read sees no plan after cleanup"
);
// The idempotent application report survives: replay evidence keyed by
// (workspace_id, idempotency_key, plan_digest) with the stored plan_id
// preserved as history.
let anchor = sqlx::query(
"select idempotency_key, plan_id, plan_digest, report
from import_plan_applications where workspace_id = $1",
)
.bind(ws.as_str())
.fetch_one(&raw)
.await
.expect("the application report must survive job + plan cleanup");
assert_eq!(
anchor.try_get::<String, _>("idempotency_key").unwrap(),
"idem_cleanup"
);
assert_eq!(
anchor.try_get::<String, _>("plan_id").unwrap(),
"plan_cleanup"
);
assert_eq!(
anchor.try_get::<String, _>("plan_digest").unwrap(),
created.digest
);
assert_eq!(anchor.try_get::<Value, _>("report").unwrap(), report);
let source = sqlx::query(
"select lifecycle, detached_at from artifact_sources
where workspace_id = $1 and source_id = 'src_openapi_test'",
)
.bind(ws.as_str())
.fetch_one(&raw)
.await
.unwrap();
assert_eq!(
source.try_get::<String, _>("lifecycle").unwrap(),
"detached"
);
assert!(
source
.try_get::<Option<OffsetDateTime>, _>("detached_at")
.unwrap()
.is_some(),
"detached_at must be recorded"
);
database.cleanup().await;
}