Files
crank/crates/crank-registry/tests/integration/onboarding_import_contract.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

786 lines
26 KiB
Rust

#![allow(dead_code, unused_imports)]
use super::*;
use serde_json::Value;
use super::onboarding_import_selection::{
attach_published_agent_and_key, context_count_for, event_count, insert_import_application,
selected_version,
};
#[tokio::test]
async fn selected_operation_hard_delete_is_blocked_and_workspace_delete_cascades() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let pool = database.raw_pool().await;
let workspace_id = WorkspaceId::new("ws_default");
let operation = test_operation("op_import_fk", 1, OperationStatus::Draft);
registry
.create_operation(&workspace_id, &operation, None)
.await
.unwrap();
insert_import_application(
&pool,
"ws_default",
"idem_fk",
&[(
"candidate",
"createLead",
"created",
"op_import_fk",
Some(1),
)],
)
.await;
let initial = registry
.get_onboarding_projection(&workspace_id)
.await
.unwrap();
let registered = registry
.register_onboarding_import_context(RegisterOnboardingImportContextRequest {
workspace_id: &workspace_id,
application_idempotency_key: "idem_fk",
plan_digest: &"b".repeat(64),
expected_revision: initial.revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap();
let selected = registry
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
workspace_id: &workspace_id,
application_idempotency_key: "idem_fk",
plan_digest: &"b".repeat(64),
operation_id: &operation.id,
operation_version: 1,
expected_revision: registered.revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap();
assert_eq!(selected.operation_id, Some(operation.id.clone()));
// `ON DELETE NO ACTION` blocks a direct hard delete of the selected
// Operation while the durable report context still anchors it.
let blocked = sqlx::query(
"delete from operations where workspace_id = 'ws_default' and id = 'op_import_fk'",
)
.execute(&pool)
.await
.unwrap_err();
let database_error = blocked.as_database_error().expect("foreign key violation");
assert_eq!(database_error.code().as_deref(), Some("23503"));
assert_eq!(
database_error.constraint(),
Some("onboarding_import_selections_operation_fk")
);
assert_eq!(context_count_for(&pool, "ws_default").await, 1);
// An explicit reset clears the context; the Operation may then be deleted.
registry
.reset_onboarding_selection(&workspace_id, selected.revision, OffsetDateTime::now_utc())
.await
.unwrap();
assert_eq!(context_count_for(&pool, "ws_default").await, 0);
sqlx::query("delete from operations where workspace_id = 'ws_default' and id = 'op_import_fk'")
.execute(&pool)
.await
.expect("after reset the selected Operation is no longer anchored");
// Workspace deletion still cascade-cleans the full context.
create_workspace(&registry, "ws_import_cascade", "import-cascade").await;
let other = WorkspaceId::new("ws_import_cascade");
let other_operation = test_operation("op_cascade", 1, OperationStatus::Draft);
registry
.create_operation(&other, &other_operation, None)
.await
.unwrap();
insert_import_application(
&pool,
"ws_import_cascade",
"idem_cascade",
&[("candidate", "createLead", "created", "op_cascade", Some(1))],
)
.await;
let other_initial = registry.get_onboarding_projection(&other).await.unwrap();
let other_registered = registry
.register_onboarding_import_context(RegisterOnboardingImportContextRequest {
workspace_id: &other,
application_idempotency_key: "idem_cascade",
plan_digest: &"b".repeat(64),
expected_revision: other_initial.revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap();
registry
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
workspace_id: &other,
application_idempotency_key: "idem_cascade",
plan_digest: &"b".repeat(64),
operation_id: &other_operation.id,
operation_version: 1,
expected_revision: other_registered.revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap();
assert_eq!(context_count_for(&pool, "ws_import_cascade").await, 1);
sqlx::query("delete from workspaces where id = 'ws_import_cascade'")
.execute(&pool)
.await
.unwrap();
assert_eq!(context_count_for(&pool, "ws_import_cascade").await, 0);
database.cleanup().await;
}
#[tokio::test]
async fn exact_publication_is_continuation_while_archive_and_version_drift_stay_visible() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let pool = database.raw_pool().await;
let workspace_id = WorkspaceId::new("ws_default");
let operation = test_operation("op_import_drift", 1, OperationStatus::Draft);
registry
.create_operation(&workspace_id, &operation, None)
.await
.unwrap();
insert_import_application(
&pool,
"ws_default",
"idem_drift",
&[(
"candidate",
"createLead",
"created",
"op_import_drift",
Some(1),
)],
)
.await;
let initial = registry
.get_onboarding_projection(&workspace_id)
.await
.unwrap();
let registered = registry
.register_onboarding_import_context(RegisterOnboardingImportContextRequest {
workspace_id: &workspace_id,
application_idempotency_key: "idem_drift",
plan_digest: &"b".repeat(64),
expected_revision: initial.revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap();
registry
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
workspace_id: &workspace_id,
application_idempotency_key: "idem_drift",
plan_digest: &"b".repeat(64),
operation_id: &operation.id,
operation_version: 1,
expected_revision: registered.revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap();
// Exact-version normal publication is the expected continuation: no drift,
// and the chooser no longer offers the published Operation as a Draft.
registry
.publish_operation(PublishRequest {
workspace_id: &workspace_id,
operation_id: &operation.id,
version: 1,
published_at: &OffsetDateTime::now_utc(),
published_by: Some("onboarding-import-drift-test"),
})
.await
.unwrap();
let context = registry
.get_onboarding_import_context(&workspace_id)
.await
.unwrap()
.unwrap();
assert!(
context.drift.is_none(),
"exact-version publication is a continuation, not drift"
);
let choice = context
.choices
.iter()
.find(|choice| choice.outcome == "created")
.unwrap();
assert!(
!choice.selectable,
"a published Operation is no longer an actionable Draft choice"
);
assert_eq!(
registry
.get_onboarding_projection(&workspace_id)
.await
.unwrap()
.operation_id,
Some(operation.id.clone())
);
// Archive keeps the report/context visible as unavailable drift.
registry
.archive_operation(&workspace_id, &operation.id, &OffsetDateTime::now_utc())
.await
.unwrap();
let archived = registry
.get_onboarding_import_context(&workspace_id)
.await
.unwrap()
.unwrap();
assert_eq!(
archived.drift.as_ref().map(|drift| drift.reason.as_str()),
Some("selected_operation_not_draft")
);
// A newer Draft version is version drift even when the selected row exists.
create_workspace(&registry, "ws_import_drift2", "import-drift2").await;
let other = WorkspaceId::new("ws_import_drift2");
let versioned = test_operation("op_versioned", 1, OperationStatus::Draft);
registry
.create_operation(&other, &versioned, None)
.await
.unwrap();
insert_import_application(
&pool,
"ws_import_drift2",
"idem_drift2",
&[(
"candidate",
"createLead",
"created",
"op_versioned",
Some(1),
)],
)
.await;
let versioned_initial = registry.get_onboarding_projection(&other).await.unwrap();
let versioned_registered = registry
.register_onboarding_import_context(RegisterOnboardingImportContextRequest {
workspace_id: &other,
application_idempotency_key: "idem_drift2",
plan_digest: &"b".repeat(64),
expected_revision: versioned_initial.revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap();
registry
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
workspace_id: &other,
application_idempotency_key: "idem_drift2",
plan_digest: &"b".repeat(64),
operation_id: &versioned.id,
operation_version: 1,
expected_revision: versioned_registered.revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap();
let snapshot = test_operation("op_versioned", 2, OperationStatus::Draft);
registry
.create_version(CreateVersionRequest {
workspace_id: &other,
snapshot: &snapshot,
change_note: None,
created_by: None,
})
.await
.unwrap();
let drifted = registry
.get_onboarding_import_context(&other)
.await
.unwrap()
.unwrap();
assert_eq!(
drifted.drift.as_ref().map(|drift| drift.reason.as_str()),
Some("selected_operation_version_drift")
);
database.cleanup().await;
}
#[tokio::test]
async fn pending_candidate_edit_or_archive_changes_revision_and_rejects_stale_select() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let pool = database.raw_pool().await;
let workspace_id = WorkspaceId::new("ws_default");
let operation = test_operation("op_pending_cas", 1, OperationStatus::Draft);
registry
.create_operation(&workspace_id, &operation, None)
.await
.unwrap();
insert_import_application(
&pool,
"ws_default",
"idem_pending_cas",
&[(
"candidate",
"createLead",
"created",
"op_pending_cas",
Some(1),
)],
)
.await;
let initial = registry
.get_onboarding_projection(&workspace_id)
.await
.unwrap();
let registered = registry
.register_onboarding_import_context(RegisterOnboardingImportContextRequest {
workspace_id: &workspace_id,
application_idempotency_key: "idem_pending_cas",
plan_digest: &"b".repeat(64),
expected_revision: initial.revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap();
assert_eq!(
registered.operation_id, None,
"a pending import context suppresses generic auto-selection"
);
// Editing the pending candidate changes the projection revision while no
// Operation is selected, so the old expected_revision is rejected.
let pending_revision = registered.revision;
registry
.create_version(CreateVersionRequest {
workspace_id: &workspace_id,
snapshot: &test_operation("op_pending_cas", 2, OperationStatus::Draft),
change_note: None,
created_by: None,
})
.await
.unwrap();
let edited = registry
.get_onboarding_projection(&workspace_id)
.await
.unwrap();
assert_ne!(
edited.revision, pending_revision,
"a pending candidate edit must change the revision"
);
assert!(matches!(
registry
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
workspace_id: &workspace_id,
application_idempotency_key: "idem_pending_cas",
plan_digest: &"b".repeat(64),
operation_id: &operation.id,
operation_version: 1,
expected_revision: pending_revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap_err(),
RegistryError::OnboardingStaleRevision
));
assert_eq!(selected_version(&pool).await, None);
// Archiving the pending candidate also changes the revision and rejects
// the previous expected_revision without mutation.
registry
.archive_operation(&workspace_id, &operation.id, &OffsetDateTime::now_utc())
.await
.unwrap();
let archived = registry
.get_onboarding_projection(&workspace_id)
.await
.unwrap();
assert_ne!(archived.revision, edited.revision);
assert!(matches!(
registry
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
workspace_id: &workspace_id,
application_idempotency_key: "idem_pending_cas",
plan_digest: &"b".repeat(64),
operation_id: &operation.id,
operation_version: 2,
expected_revision: edited.revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap_err(),
RegistryError::OnboardingStaleRevision
));
// The archived candidate is no longer actionable even with a fresh CAS.
assert!(matches!(
registry
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
workspace_id: &workspace_id,
application_idempotency_key: "idem_pending_cas",
plan_digest: &"b".repeat(64),
operation_id: &operation.id,
operation_version: 2,
expected_revision: archived.revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap_err(),
RegistryError::OnboardingImportDraftUnavailable
));
assert_eq!(selected_version(&pool).await, None);
database.cleanup().await;
}
#[tokio::test]
async fn import_context_report_survives_job_and_plan_gc() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let pool = database.raw_pool().await;
let workspace_id = WorkspaceId::new("ws_default");
let operation = test_operation("op_import_gc", 1, OperationStatus::Draft);
registry
.create_operation(&workspace_id, &operation, None)
.await
.unwrap();
sqlx::query(
"insert into import_jobs (
id, workspace_id, kind, source_format, source_version, status,
preview_payload, created_operation_ids, error_text, created_at, expires_at, finished_at
) values ('job_gc', 'ws_default', 'openapi', 'openapi', null, 'applied',
'{}'::jsonb, '[]'::jsonb, null, now(), now() + interval '1 day', now())",
)
.execute(&pool)
.await
.unwrap();
sqlx::query(
"insert into import_plans (
workspace_id, id, job_id, digest, payload, created_at, expires_at
) values ('ws_default', 'plan_gc', 'job_gc', $1, '{}'::jsonb, now(), now() + interval '1 day')",
)
.bind("b".repeat(64))
.execute(&pool)
.await
.unwrap();
insert_import_application(
&pool,
"ws_default",
"idem_gc",
&[(
"candidate",
"createLead",
"created",
"op_import_gc",
Some(1),
)],
)
.await;
let initial = registry
.get_onboarding_projection(&workspace_id)
.await
.unwrap();
registry
.register_onboarding_import_context(RegisterOnboardingImportContextRequest {
workspace_id: &workspace_id,
application_idempotency_key: "idem_gc",
plan_digest: &"b".repeat(64),
expected_revision: initial.revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap();
// GC the job; the plan cascades. The immutable application report stays
// recoverable by the durable identity.
sqlx::query("delete from import_jobs where id = 'job_gc'")
.execute(&pool)
.await
.unwrap();
let plan_count: i64 =
sqlx::query_scalar("select count(*) from import_plans where id = 'plan_gc'")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(plan_count, 0);
let context = registry
.get_onboarding_import_context(&workspace_id)
.await
.unwrap()
.expect("report survives job/plan GC");
assert_eq!(context.application_idempotency_key, "idem_gc");
assert_eq!(context.plan_digest, "b".repeat(64));
assert_eq!(
context.report.get("status").and_then(Value::as_str),
Some("applied")
);
assert_eq!(
context
.choices
.iter()
.find(|choice| choice.outcome == "created")
.and_then(|choice| choice.operation_id.as_deref()),
Some("op_import_gc")
);
database.cleanup().await;
}
#[tokio::test]
async fn import_context_governs_terminal_anchor_until_exact_selected_call() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let pool = database.raw_pool().await;
let workspace_id = WorkspaceId::new("ws_default");
let selected = test_operation("op_anchor_a", 1, OperationStatus::Draft);
registry
.create_operation(&workspace_id, &selected, None)
.await
.unwrap();
let unrelated = test_operation("op_anchor_b", 1, OperationStatus::Draft);
registry
.create_operation(&workspace_id, &unrelated, None)
.await
.unwrap();
insert_import_application(
&pool,
"ws_default",
"idem_anchor",
&[
("ca", "createA", "created", "op_anchor_a", Some(1)),
("cb", "createB", "created", "op_anchor_b", Some(1)),
],
)
.await;
let initial = registry
.get_onboarding_projection(&workspace_id)
.await
.unwrap();
let pending = registry
.register_onboarding_import_context(RegisterOnboardingImportContextRequest {
workspace_id: &workspace_id,
application_idempotency_key: "idem_anchor",
plan_digest: &"b".repeat(64),
expected_revision: initial.revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap();
assert_eq!(pending.operation_id, None);
// Publish the unrelated Operation and make a successful public call while
// the context is still pending: generic anchoring must be suppressed.
registry
.publish_operation(PublishRequest {
workspace_id: &workspace_id,
operation_id: &unrelated.id,
version: 1,
published_at: &OffsetDateTime::now_utc(),
published_by: Some("onboarding-anchor-test"),
})
.await
.unwrap();
let (unrelated_agent, unrelated_key) =
attach_published_agent_and_key(&registry, &unrelated.id, "agent_anchor_b", "pk_anchor_b")
.await;
record_onboarding_call(
&registry,
&unrelated.id,
&unrelated_agent,
&unrelated_key,
"anchor_b_pending",
OffsetDateTime::now_utc(),
)
.await;
assert_eq!(terminal_operation(&pool).await, None);
assert_eq!(
registry
.get_onboarding_projection(&workspace_id)
.await
.unwrap()
.operation_id,
None,
"a pending import context suppresses generic Operation selection"
);
// Explicitly select A, then an unrelated B call must still not anchor.
// Publishing the unrelated candidate moved the revision (candidate live
// snapshot), so use the current authoritative revision for the CAS.
let before_select = registry
.get_onboarding_projection(&workspace_id)
.await
.unwrap();
assert_ne!(before_select.revision, pending.revision);
let selected_projection = registry
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
workspace_id: &workspace_id,
application_idempotency_key: "idem_anchor",
plan_digest: &"b".repeat(64),
operation_id: &selected.id,
operation_version: 1,
expected_revision: before_select.revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap();
assert_eq!(selected_projection.operation_id, Some(selected.id.clone()));
registry
.publish_operation(PublishRequest {
workspace_id: &workspace_id,
operation_id: &selected.id,
version: 1,
published_at: &OffsetDateTime::now_utc(),
published_by: Some("onboarding-anchor-test"),
})
.await
.unwrap();
let (selected_agent, selected_key) =
attach_published_agent_and_key(&registry, &selected.id, "agent_anchor_a", "pk_anchor_a")
.await;
// A second unrelated call cannot replace the chosen path or complete it.
record_onboarding_call(
&registry,
&unrelated.id,
&unrelated_agent,
&unrelated_key,
"anchor_b_selected",
OffsetDateTime::now_utc(),
)
.await;
assert_eq!(terminal_operation(&pool).await, None);
let still_selected = registry
.get_onboarding_projection(&workspace_id)
.await
.unwrap();
assert_eq!(still_selected.operation_id, Some(selected.id.clone()));
assert!(!still_selected.completed);
// Only the exact selected Operation/version call completes the path once.
record_onboarding_test_and_call(
&registry,
&selected.id,
&selected_agent,
&selected_key,
"anchor_a",
OffsetDateTime::now_utc(),
)
.await;
assert_eq!(
terminal_operation(&pool).await,
Some(selected.id.as_str().to_owned())
);
let completed = registry
.ensure_onboarding_eligibility(&workspace_id, OffsetDateTime::now_utc())
.await
.unwrap();
assert!(completed.completed);
assert!(
completed
.step(OnboardingStepId::FirstCall)
.is_some_and(|step| step.completed)
);
assert_eq!(event_count(&pool, "onboarding_agent_activated").await, 1);
// Re-observing is idempotent: the exact path stays single.
registry
.ensure_onboarding_eligibility(&workspace_id, OffsetDateTime::now_utc())
.await
.unwrap();
assert_eq!(event_count(&pool, "onboarding_agent_activated").await, 1);
// A later imported target cannot inherit A's completed terminal evidence.
let later = test_operation("op_after_terminal", 1, OperationStatus::Draft);
registry
.create_operation(&workspace_id, &later, None)
.await
.unwrap();
insert_import_application(
&pool,
"ws_default",
"idem_after_terminal",
&[(
"later",
"createLater",
"created",
"op_after_terminal",
Some(1),
)],
)
.await;
let before = registry
.get_onboarding_projection(&workspace_id)
.await
.unwrap();
let registered = registry
.register_onboarding_import_context(RegisterOnboardingImportContextRequest {
workspace_id: &workspace_id,
application_idempotency_key: "idem_after_terminal",
plan_digest: &"b".repeat(64),
expected_revision: before.revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap();
registry
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
workspace_id: &workspace_id,
application_idempotency_key: "idem_after_terminal",
plan_digest: &"b".repeat(64),
operation_id: &later.id,
operation_version: 1,
expected_revision: registered.revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await
.unwrap();
registry
.publish_operation(PublishRequest {
workspace_id: &workspace_id,
operation_id: &later.id,
version: 1,
published_at: &OffsetDateTime::now_utc(),
published_by: None,
})
.await
.unwrap();
let preserved = registry
.ensure_onboarding_eligibility(&workspace_id, OffsetDateTime::now_utc())
.await
.unwrap();
assert_eq!(preserved.operation_id, Some(selected.id.clone()));
assert!(
preserved.completed,
"the existing terminal tuple remains intact"
);
assert_eq!(
event_count(&pool, "onboarding_import_published").await,
1,
"A's publication must not be attributed to the later import"
);
assert_eq!(
event_count(&pool, "onboarding_agent_activated").await,
1,
"the later import has no successful public first call"
);
database.cleanup().await;
}
async fn terminal_operation(pool: &sqlx::PgPool) -> Option<String> {
sqlx::query_scalar::<_, Option<String>>(
"select operation_id from onboarding_selections where workspace_id = 'ws_default'",
)
.fetch_optional(pool)
.await
.unwrap()
.flatten()
}