feat(import): complete OpenAPI onboarding and verify delivery
This commit is contained in:
1 parent
bb3e376767
commit
e93de7015a
244 files changed
+57020
-5139
No files matched your search
@@ -1,570 +0,0 @@
|
||||
use super::common::*;
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
os::unix::fs::PermissionsExt,
|
||||
path::PathBuf,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
use crank_artifacts::{ArtifactRef, ArtifactStore};
|
||||
use crank_core::{
|
||||
ApiKeyHeaderAuthConfig, AuthConfig, AuthKind, AuthProfile, BearerAuthConfig, ExecutionConfig,
|
||||
Secret, SecretKind, SecretStatus, Workspace, WorkspaceId, WorkspaceStatus,
|
||||
};
|
||||
use crank_registry::{
|
||||
ApplyImportJobRequest, ArtifactSourceId, ArtifactSourceSensitivity,
|
||||
CreateArtifactSourceRequest, CreateImportJobRequest, CreateSecretRequest,
|
||||
CreateWorkspaceRequest, ImportAuthRequirement, ImportConflictMode, ImportJobId, ImportJobKind,
|
||||
ImportJobSourceEnvelope, ImportJobStatus, ImportOperationDraft, MASTER_KEY_CIPHER_CONTRACT,
|
||||
MasterKeyIdentityCandidate, PostgresRegistry, RegistryError, RegistryOperation,
|
||||
SaveAuthProfileRequest,
|
||||
};
|
||||
use serde_json::json;
|
||||
use time::OffsetDateTime;
|
||||
use tokio::time::{Duration as TokioDuration, sleep};
|
||||
|
||||
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct ImportSourceRoot(PathBuf);
|
||||
|
||||
impl ImportSourceRoot {
|
||||
fn new() -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"crank-registry-import-auth-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&path).unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ImportSourceRoot {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::set_permissions(&self.0, fs::Permissions::from_mode(0o700));
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn timestamp() -> OffsetDateTime {
|
||||
OffsetDateTime::now_utc()
|
||||
}
|
||||
|
||||
async fn create_workspace(registry: &PostgresRegistry, id: &str) -> WorkspaceId {
|
||||
let now = timestamp();
|
||||
let workspace_id = WorkspaceId::new(id);
|
||||
registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: workspace_id.clone(),
|
||||
slug: id.replace('_', "-"),
|
||||
display_name: id.to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
workspace_id
|
||||
}
|
||||
|
||||
async fn create_secret(registry: &PostgresRegistry, id: &str, workspace_id: &WorkspaceId) {
|
||||
let now = timestamp();
|
||||
registry
|
||||
.verify_or_register_master_key_identity(MasterKeyIdentityCandidate {
|
||||
epoch: 1,
|
||||
fingerprint: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||
cipher_contract: MASTER_KEY_CIPHER_CONTRACT,
|
||||
observed_at: &now,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let secret = Secret {
|
||||
id: id.into(),
|
||||
workspace_id: workspace_id.clone(),
|
||||
name: format!("secret-{id}"),
|
||||
kind: SecretKind::Token,
|
||||
status: SecretStatus::Active,
|
||||
current_version: 1,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
last_used_at: None,
|
||||
};
|
||||
registry
|
||||
.create_secret(CreateSecretRequest {
|
||||
secret: &secret,
|
||||
ciphertext: "opaque-test-ciphertext",
|
||||
key_version: "test-key-v1",
|
||||
master_key_epoch: 1,
|
||||
created_by: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn profile(
|
||||
id: &str,
|
||||
workspace_id: &WorkspaceId,
|
||||
kind: AuthKind,
|
||||
config: AuthConfig,
|
||||
) -> AuthProfile {
|
||||
let now = timestamp();
|
||||
AuthProfile {
|
||||
id: id.into(),
|
||||
workspace_id: workspace_id.clone(),
|
||||
name: format!("profile-{id}"),
|
||||
kind,
|
||||
config,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
|
||||
async fn save_profile(registry: &PostgresRegistry, profile: &AuthProfile) {
|
||||
registry
|
||||
.save_auth_profile(SaveAuthProfileRequest {
|
||||
workspace_id: &profile.workspace_id,
|
||||
profile,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn create_import_job(
|
||||
registry: &PostgresRegistry,
|
||||
root: &ImportSourceRoot,
|
||||
job_number: usize,
|
||||
) -> (ImportJobId, ArtifactSourceId, ArtifactRef) {
|
||||
let store = ArtifactStore::open(&root.0).unwrap();
|
||||
let artifact = store.put_registered(b"openapi: 3.1.0\n").unwrap();
|
||||
let source_id = ArtifactSourceId::new(format!("src_import_auth_{job_number}"));
|
||||
let now = timestamp();
|
||||
let workspace_id = test_workspace_id();
|
||||
registry
|
||||
.create_artifact_source(CreateArtifactSourceRequest {
|
||||
workspace_id: &workspace_id,
|
||||
source_id: &source_id,
|
||||
artifact: &artifact,
|
||||
mime_type: "application/yaml",
|
||||
sensitivity: ArtifactSourceSensitivity::Internal,
|
||||
created_at: now,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let source = ImportJobSourceEnvelope {
|
||||
source_id: source_id.clone(),
|
||||
digest: artifact.artifact_ref().clone(),
|
||||
};
|
||||
let payload = json!({
|
||||
"source": {
|
||||
"source_id": source.source_id.as_str(),
|
||||
"digest": source.digest.as_str(),
|
||||
}
|
||||
});
|
||||
let id = ImportJobId::new(format!("job_import_auth_{job_number}"));
|
||||
registry
|
||||
.create_import_job(CreateImportJobRequest {
|
||||
id: &id,
|
||||
workspace_id: &workspace_id,
|
||||
kind: ImportJobKind::OpenApi,
|
||||
source_format: "openapi",
|
||||
source_version: Some("v5"),
|
||||
status: ImportJobStatus::Pending,
|
||||
source: &source,
|
||||
preview_payload: &payload,
|
||||
created_at: &now,
|
||||
expires_at: &(now + time::Duration::hours(1)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
(id, source_id, artifact.artifact_ref().clone())
|
||||
}
|
||||
|
||||
fn operation(id: &str, profile_id: Option<&str>) -> RegistryOperation {
|
||||
let mut operation = test_operation(id, 1, crank_core::OperationStatus::Draft);
|
||||
operation.execution_config = ExecutionConfig {
|
||||
auth_profile_ref: profile_id.map(Into::into),
|
||||
..operation.execution_config
|
||||
};
|
||||
operation
|
||||
}
|
||||
|
||||
async fn apply(
|
||||
registry: &PostgresRegistry,
|
||||
job_id: &ImportJobId,
|
||||
drafts: &[ImportOperationDraft],
|
||||
) -> Result<crank_registry::ImportJobApplyResult, RegistryError> {
|
||||
let workspace_id = test_workspace_id();
|
||||
let now = timestamp();
|
||||
registry
|
||||
.apply_import_job(ApplyImportJobRequest {
|
||||
id: job_id,
|
||||
workspace_id: &workspace_id,
|
||||
application_key: "test-app-key",
|
||||
conflict_mode: ImportConflictMode::Rename,
|
||||
operations: drafts,
|
||||
pre_skipped: &[],
|
||||
finished_at: &now,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn operation_count(database: &TestDatabase, ids: &[&str]) -> i64 {
|
||||
let pool = database.raw_pool().await;
|
||||
let count = sqlx::query_scalar::<_, i64>("select count(*) from operations where id = any($1)")
|
||||
.bind(ids)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
pool.close().await;
|
||||
count
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_accepts_current_compatible_profile_and_shared_secret_then_rejects_disabled_secret() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let workspace_id = test_workspace_id();
|
||||
let secret_id = "secret_import_shared";
|
||||
create_secret(®istry, secret_id, &workspace_id).await;
|
||||
for profile_id in ["auth_import_a", "auth_import_b"] {
|
||||
save_profile(
|
||||
®istry,
|
||||
&profile(
|
||||
profile_id,
|
||||
&workspace_id,
|
||||
AuthKind::ApiKeyHeader,
|
||||
AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||
header_name: "x-api-key".to_owned(),
|
||||
secret_id: secret_id.into(),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
let root = ImportSourceRoot::new();
|
||||
let (job_id, _, _) = create_import_job(®istry, &root, 1).await;
|
||||
let drafts = [
|
||||
ImportOperationDraft {
|
||||
operation_key: "first".to_owned(),
|
||||
operation: operation("op_import_auth_first", Some("auth_import_a")),
|
||||
auth_requirement: Some(ImportAuthRequirement::ApiKeyHeader {
|
||||
parameter_name: "X-Api-Key".to_owned(),
|
||||
}),
|
||||
},
|
||||
ImportOperationDraft {
|
||||
operation_key: "second".to_owned(),
|
||||
operation: operation("op_import_auth_second", Some("auth_import_b")),
|
||||
auth_requirement: Some(ImportAuthRequirement::ApiKeyHeader {
|
||||
parameter_name: "X-Api-Key".to_owned(),
|
||||
}),
|
||||
},
|
||||
];
|
||||
let result = apply(®istry, &job_id, &drafts).await.unwrap();
|
||||
assert_eq!(result.created.len(), 2);
|
||||
assert_eq!(
|
||||
operation_count(
|
||||
&database,
|
||||
&["op_import_auth_first", "op_import_auth_second"]
|
||||
)
|
||||
.await,
|
||||
2
|
||||
);
|
||||
|
||||
let pool = database.raw_pool().await;
|
||||
sqlx::query("update secrets set status = 'disabled' where id = $1")
|
||||
.bind(secret_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
pool.close().await;
|
||||
|
||||
let (job_id, _, _) = create_import_job(®istry, &root, 2).await;
|
||||
let disabled_error = apply(®istry, &job_id, &drafts).await.unwrap_err();
|
||||
assert_eq!(
|
||||
disabled_error.to_string(),
|
||||
"import auth profile binding is unavailable"
|
||||
);
|
||||
assert_eq!(
|
||||
operation_count(
|
||||
&database,
|
||||
&["op_import_auth_first", "op_import_auth_second"]
|
||||
)
|
||||
.await,
|
||||
2
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_and_foreign_profiles_have_the_same_safe_error_and_insert_no_operation() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let foreign_workspace = create_workspace(®istry, "ws_import_auth_foreign").await;
|
||||
create_secret(®istry, "secret_import_foreign", &foreign_workspace).await;
|
||||
save_profile(
|
||||
®istry,
|
||||
&profile(
|
||||
"auth_import_foreign",
|
||||
&foreign_workspace,
|
||||
AuthKind::Bearer,
|
||||
AuthConfig::Bearer(BearerAuthConfig {
|
||||
header_name: "Authorization".to_owned(),
|
||||
secret_id: "secret_import_foreign".into(),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
|
||||
let root = ImportSourceRoot::new();
|
||||
let (missing_job, _, _) = create_import_job(®istry, &root, 3).await;
|
||||
let missing = [ImportOperationDraft {
|
||||
operation_key: "missing".to_owned(),
|
||||
operation: operation("op_import_auth_missing", Some("auth_import_absent")),
|
||||
auth_requirement: Some(ImportAuthRequirement::Bearer),
|
||||
}];
|
||||
let missing_error = apply(®istry, &missing_job, &missing).await.unwrap_err();
|
||||
|
||||
let (foreign_job, _, _) = create_import_job(®istry, &root, 4).await;
|
||||
let foreign = [ImportOperationDraft {
|
||||
operation_key: "foreign".to_owned(),
|
||||
operation: operation("op_import_auth_foreign_ref", Some("auth_import_foreign")),
|
||||
auth_requirement: Some(ImportAuthRequirement::Bearer),
|
||||
}];
|
||||
let foreign_error = apply(®istry, &foreign_job, &foreign).await.unwrap_err();
|
||||
assert_eq!(
|
||||
missing_error.to_string(),
|
||||
"import auth profile binding is unavailable"
|
||||
);
|
||||
assert_eq!(missing_error.to_string(), foreign_error.to_string());
|
||||
assert_eq!(
|
||||
operation_count(
|
||||
&database,
|
||||
&["op_import_auth_missing", "op_import_auth_foreign_ref"]
|
||||
)
|
||||
.await,
|
||||
0
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_rejects_kind_parameter_and_missing_current_version_before_mutation() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let workspace_id = test_workspace_id();
|
||||
create_secret(®istry, "secret_import_mismatch", &workspace_id).await;
|
||||
save_profile(
|
||||
®istry,
|
||||
&profile(
|
||||
"auth_import_mismatch",
|
||||
&workspace_id,
|
||||
AuthKind::ApiKeyHeader,
|
||||
AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||
header_name: "X-Api-Key".to_owned(),
|
||||
secret_id: "secret_import_mismatch".into(),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let root = ImportSourceRoot::new();
|
||||
let bad_requirements = [
|
||||
ImportAuthRequirement::Bearer,
|
||||
ImportAuthRequirement::ApiKeyHeader {
|
||||
parameter_name: "X-Different".to_owned(),
|
||||
},
|
||||
];
|
||||
for (index, requirement) in bad_requirements.into_iter().enumerate() {
|
||||
let (job_id, _, _) = create_import_job(®istry, &root, 5 + index).await;
|
||||
let operation_id = format!("op_import_auth_mismatch_{index}");
|
||||
let draft = [ImportOperationDraft {
|
||||
operation_key: operation_id.clone(),
|
||||
operation: operation(&operation_id, Some("auth_import_mismatch")),
|
||||
auth_requirement: Some(requirement),
|
||||
}];
|
||||
let error = apply(®istry, &job_id, &draft).await.unwrap_err();
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"import auth profile binding is unavailable"
|
||||
);
|
||||
assert_eq!(operation_count(&database, &[&operation_id]).await, 0);
|
||||
}
|
||||
|
||||
let pool = database.raw_pool().await;
|
||||
sqlx::query("update secrets set current_version = 2 where id = $1")
|
||||
.bind("secret_import_mismatch")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
pool.close().await;
|
||||
let (job_id, _, _) = create_import_job(®istry, &root, 7).await;
|
||||
let draft = [ImportOperationDraft {
|
||||
operation_key: "missing-current".to_owned(),
|
||||
operation: operation(
|
||||
"op_import_auth_missing_current",
|
||||
Some("auth_import_mismatch"),
|
||||
),
|
||||
auth_requirement: Some(ImportAuthRequirement::ApiKeyHeader {
|
||||
parameter_name: "X-Api-Key".to_owned(),
|
||||
}),
|
||||
}];
|
||||
let error = apply(®istry, &job_id, &draft).await.unwrap_err();
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"import auth profile binding is unavailable"
|
||||
);
|
||||
assert_eq!(
|
||||
operation_count(&database, &["op_import_auth_missing_current"]).await,
|
||||
0
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_auth_requires_no_profile_reference() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let root = ImportSourceRoot::new();
|
||||
let (job_id, _, _) = create_import_job(®istry, &root, 8).await;
|
||||
let draft = [ImportOperationDraft {
|
||||
operation_key: "inconsistent".to_owned(),
|
||||
operation: operation("op_import_auth_no_requirement", Some("auth_nonexistent")),
|
||||
auth_requirement: None,
|
||||
}];
|
||||
let error = apply(®istry, &job_id, &draft).await.unwrap_err();
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"import auth profile binding is unavailable"
|
||||
);
|
||||
assert_eq!(
|
||||
operation_count(&database, &["op_import_auth_no_requirement"]).await,
|
||||
0
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_waiting_on_secret_disable_rejects_without_partial_draft_mutation() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let workspace_id = test_workspace_id();
|
||||
create_secret(®istry, "secret_import_race", &workspace_id).await;
|
||||
save_profile(
|
||||
®istry,
|
||||
&profile(
|
||||
"auth_import_race",
|
||||
&workspace_id,
|
||||
AuthKind::ApiKeyHeader,
|
||||
AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||
header_name: "X-Api-Key".to_owned(),
|
||||
secret_id: "secret_import_race".into(),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let root = ImportSourceRoot::new();
|
||||
let (job_id, _, _) = create_import_job(®istry, &root, 9).await;
|
||||
let drafts = vec![
|
||||
ImportOperationDraft {
|
||||
operation_key: "race-first".to_owned(),
|
||||
operation: operation("op_import_auth_race_first", Some("auth_import_race")),
|
||||
auth_requirement: Some(ImportAuthRequirement::ApiKeyHeader {
|
||||
parameter_name: "X-Api-Key".to_owned(),
|
||||
}),
|
||||
},
|
||||
ImportOperationDraft {
|
||||
operation_key: "race-second".to_owned(),
|
||||
operation: operation("op_import_auth_race_second", Some("auth_import_race")),
|
||||
auth_requirement: Some(ImportAuthRequirement::ApiKeyHeader {
|
||||
parameter_name: "X-Api-Key".to_owned(),
|
||||
}),
|
||||
},
|
||||
];
|
||||
|
||||
let pool = database.raw_pool().await;
|
||||
let mut disable_tx = pool.begin().await.unwrap();
|
||||
sqlx::query("select id from secrets where workspace_id = $1 and id = $2 for update")
|
||||
.bind(workspace_id.as_str())
|
||||
.bind("secret_import_race")
|
||||
.fetch_one(&mut *disable_tx)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let concurrent_registry = registry.clone();
|
||||
let concurrent_job_id = job_id.clone();
|
||||
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
|
||||
let apply_task = tokio::spawn(async move {
|
||||
let _ = started_tx.send(());
|
||||
let workspace_id = test_workspace_id();
|
||||
let finished_at = timestamp();
|
||||
concurrent_registry
|
||||
.apply_import_job(ApplyImportJobRequest {
|
||||
id: &concurrent_job_id,
|
||||
workspace_id: &workspace_id,
|
||||
application_key: "race-app-key",
|
||||
conflict_mode: ImportConflictMode::Rename,
|
||||
operations: &drafts,
|
||||
pre_skipped: &[],
|
||||
finished_at: &finished_at,
|
||||
})
|
||||
.await
|
||||
});
|
||||
started_rx.await.unwrap();
|
||||
|
||||
// Use a separate pool because the transaction holding the lock occupies
|
||||
// the raw pool's only connection.
|
||||
let observer_pool = database.raw_pool().await;
|
||||
let mut waiting_for_secret_lock = false;
|
||||
for _ in 0..100 {
|
||||
waiting_for_secret_lock = sqlx::query_scalar::<_, bool>(
|
||||
"select exists (
|
||||
select 1 from pg_stat_activity
|
||||
where wait_event_type = 'Lock'
|
||||
and query like 'select s.status,%'
|
||||
and query like '%for update of s%'
|
||||
)",
|
||||
)
|
||||
.fetch_one(&observer_pool)
|
||||
.await
|
||||
.unwrap();
|
||||
if waiting_for_secret_lock {
|
||||
break;
|
||||
}
|
||||
sleep(TokioDuration::from_millis(10)).await;
|
||||
}
|
||||
assert!(
|
||||
waiting_for_secret_lock,
|
||||
"Apply should be waiting on the locked Secret row"
|
||||
);
|
||||
observer_pool.close().await;
|
||||
|
||||
sqlx::query("update secrets set status = 'disabled' where workspace_id = $1 and id = $2")
|
||||
.bind(workspace_id.as_str())
|
||||
.bind("secret_import_race")
|
||||
.execute(&mut *disable_tx)
|
||||
.await
|
||||
.unwrap();
|
||||
disable_tx.commit().await.unwrap();
|
||||
|
||||
let result = apply_task.await.unwrap();
|
||||
assert_eq!(
|
||||
result.unwrap_err().to_string(),
|
||||
"import auth profile binding is unavailable"
|
||||
);
|
||||
assert_eq!(
|
||||
operation_count(
|
||||
&database,
|
||||
&["op_import_auth_race_first", "op_import_auth_race_second"]
|
||||
)
|
||||
.await,
|
||||
0
|
||||
);
|
||||
pool.close().await;
|
||||
database.cleanup().await;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
use crank_artifacts::ArtifactRef;
|
||||
use crank_core::{Workspace, WorkspaceId, WorkspaceStatus};
|
||||
use crank_registry::{
|
||||
ArtifactSourceId, CreateImportJobRequest, CreateWorkspaceRequest, ImportJobId, ImportJobKind,
|
||||
ImportJobSourceEnvelope, ImportJobStatus,
|
||||
};
|
||||
use serde_json::json;
|
||||
use time::OffsetDateTime;
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
|
||||
mod apply;
|
||||
mod cleanup;
|
||||
mod create;
|
||||
mod preview_v2;
|
||||
pub(super) fn parse_ts(value: &str) -> OffsetDateTime {
|
||||
OffsetDateTime::parse(value, &Rfc3339).unwrap()
|
||||
}
|
||||
|
||||
pub(super) async fn create_workspace(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
id: &str,
|
||||
) -> WorkspaceId {
|
||||
let workspace_id = WorkspaceId::new(id);
|
||||
let created_at = parse_ts("2026-09-26T10:00:00Z");
|
||||
registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: workspace_id.clone(),
|
||||
slug: id.replace('_', "-"),
|
||||
display_name: id.to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at,
|
||||
updated_at: created_at,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
workspace_id
|
||||
}
|
||||
|
||||
/// Creates a well-formed, pending, non-expired OpenAPI import job carrying a
|
||||
/// verifiable source envelope, exactly as the legacy ingress path does.
|
||||
pub(super) async fn create_pending_openapi_job(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
job_id: &str,
|
||||
now: OffsetDateTime,
|
||||
job_expires_at: OffsetDateTime,
|
||||
) -> ImportJobId {
|
||||
let job = ImportJobId::new(job_id);
|
||||
let source_id = ArtifactSourceId::new("src_openapi_test");
|
||||
let digest = ArtifactRef::from_digest_hex(&"ab".repeat(32)).unwrap();
|
||||
let preview_payload = json!({
|
||||
"source": {
|
||||
"source_id": source_id.as_str(),
|
||||
"digest": digest.as_str(),
|
||||
},
|
||||
"preview": { "ops": ["a", "b"] }
|
||||
});
|
||||
registry
|
||||
.create_import_job(CreateImportJobRequest {
|
||||
id: &job,
|
||||
workspace_id,
|
||||
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: &now,
|
||||
expires_at: &job_expires_at,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
job
|
||||
}
|
||||
@@ -0,0 +1,761 @@
|
||||
//! 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, ApiKeyQueryAuthConfig, AuthConfig, AuthKind, AuthProfile,
|
||||
BasicAuthConfig, 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" },
|
||||
"auth_requirement": { "kind": "api_key_header", "parameter_name": "X-Apply-Key" },
|
||||
"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]
|
||||
})
|
||||
}
|
||||
|
||||
fn typed_auth_plan_payload(
|
||||
plan_id: &str,
|
||||
job_id: &str,
|
||||
fingerprint: &Value,
|
||||
auth_profile_id: &str,
|
||||
requirement_kind: &str,
|
||||
parameter_name: Option<&str>,
|
||||
snapshot: Value,
|
||||
) -> Value {
|
||||
let mut operation = plan_operation("op_typed_auth");
|
||||
operation.execution_config.auth_profile_ref = Some(auth_profile_id.into());
|
||||
let mut requirement = json!({ "kind": requirement_kind });
|
||||
if let Some(parameter_name) = parameter_name {
|
||||
requirement["parameter_name"] = json!(parameter_name);
|
||||
}
|
||||
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": ["typed"], "selected": ["typed"], "excluded": []
|
||||
},
|
||||
"counts": { "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 },
|
||||
"candidates": [{
|
||||
"key": "typed",
|
||||
"name": operation.name,
|
||||
"state": "actionable",
|
||||
"decision": { "action": "create" },
|
||||
"auth_requirement": requirement,
|
||||
"operation": operation,
|
||||
"auth_snapshot": snapshot
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
async fn typed_auth_base(
|
||||
database: &TestDatabase,
|
||||
workspace_tag: &str,
|
||||
profile_id: &str,
|
||||
config: AuthConfig,
|
||||
) -> (
|
||||
PostgresRegistry,
|
||||
WorkspaceId,
|
||||
ImportJobId,
|
||||
Value,
|
||||
AuthProfile,
|
||||
Value,
|
||||
) {
|
||||
let registry = database.registry().await;
|
||||
registry
|
||||
.verify_or_register_master_key_identity(MasterKeyIdentityCandidate {
|
||||
epoch: 1,
|
||||
fingerprint: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||
cipher_contract: MASTER_KEY_CIPHER_CONTRACT,
|
||||
observed_at: &ts(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, workspace_tag).await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
&format!("job_typed_auth_{workspace_tag}"),
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&database.raw_pool().await, &ws, now).await;
|
||||
|
||||
let mut secrets = Vec::new();
|
||||
for (index, secret_id) in config.secret_ids().into_iter().enumerate() {
|
||||
let secret = Secret {
|
||||
id: secret_id.clone(),
|
||||
workspace_id: ws.clone(),
|
||||
name: format!("Typed auth secret {index}"),
|
||||
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();
|
||||
secrets.push(secret);
|
||||
}
|
||||
let profile = AuthProfile {
|
||||
id: profile_id.into(),
|
||||
workspace_id: ws.clone(),
|
||||
name: "Typed auth profile".to_owned(),
|
||||
kind: config.kind(),
|
||||
config,
|
||||
created_at: ts(),
|
||||
updated_at: ts(),
|
||||
};
|
||||
registry
|
||||
.save_auth_profile(SaveAuthProfileRequest {
|
||||
workspace_id: &ws,
|
||||
profile: &profile,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let snapshot = 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": secrets.iter().map(|secret| json!({
|
||||
"id": secret.id.as_str(),
|
||||
"status": secret.status,
|
||||
"current_version": secret.current_version,
|
||||
"updated_at": secret.updated_at.format(&Rfc3339).unwrap()
|
||||
})).collect::<Vec<_>>()
|
||||
});
|
||||
(registry, ws, job, fingerprint(), profile, snapshot)
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_rechecks_live_profile_against_source_requirement_even_when_snapshot_matches() {
|
||||
let database = TestDatabase::new().await;
|
||||
let (registry, raw_pool, ws, job, fp, _snapshot_a) =
|
||||
auth_base(&database, "a_source_requirement").await;
|
||||
|
||||
// Reproduce the race: source compatibility was resolved while the
|
||||
// profile used X-Apply-Key, then the profile changed before the later
|
||||
// snapshot capture, so the stored snapshot itself accurately says X-B.
|
||||
sqlx::query(
|
||||
"update auth_profiles
|
||||
set config_json = jsonb_set(config_json, '{api_key_header,header_name}', '\"X-B\"'),
|
||||
updated_at = now()
|
||||
where workspace_id = $1 and id = $2",
|
||||
)
|
||||
.bind(ws.as_str())
|
||||
.bind("auth_apply")
|
||||
.execute(&raw_pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let profile = capture_profile_fixture(®istry, &ws).await;
|
||||
let secret = registry
|
||||
.get_secret(&ws, &SecretId::new("sec_apply"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.secret;
|
||||
let snapshot_b = capture_snapshot(&profile, &secret);
|
||||
assert_eq!(snapshot_b["config"]["api_key_header"]["header_name"], "X-B");
|
||||
|
||||
// The source-derived requirement remains X-Apply-Key even though the
|
||||
// plan-time snapshot now matches the live X-B profile exactly.
|
||||
let payload = auth_plan_payload("plan_auth_source_req", job.as_str(), &fp, Some(snapshot_b));
|
||||
let (plan, digest) =
|
||||
store_plan(®istry, &ws, &job, "plan_auth_source_req", &fp, payload).await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
let result = registry
|
||||
.apply_import_plan(&ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_auth_source_req",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
})
|
||||
.await;
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(RegistryError::ImportPlanAuthUnavailable { auth_profile_id })
|
||||
if auth_profile_id == "auth_apply"
|
||||
));
|
||||
assert!(
|
||||
registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_apply_auth"))
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
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;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_accepts_basic_auth_with_matching_snapshot_and_source_requirement() {
|
||||
let database = TestDatabase::new().await;
|
||||
let profile_id = "auth_basic_apply";
|
||||
let (registry, ws, job, fp, _profile, snapshot) = typed_auth_base(
|
||||
&database,
|
||||
"a_basic_ok",
|
||||
profile_id,
|
||||
AuthConfig::Basic(BasicAuthConfig {
|
||||
username_secret_id: SecretId::new("sec_basic_user"),
|
||||
password_secret_id: SecretId::new("sec_basic_password"),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let payload = typed_auth_plan_payload(
|
||||
"plan_basic_ok",
|
||||
job.as_str(),
|
||||
&fp,
|
||||
profile_id,
|
||||
"basic",
|
||||
None,
|
||||
snapshot,
|
||||
);
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, "plan_basic_ok", &fp, payload).await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
let result = registry
|
||||
.apply_import_plan(&ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_basic_ok",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result.report.status, ImportPlanApplyStatus::Applied);
|
||||
assert_eq!(result.report.counts.created, 1);
|
||||
let summary = registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_typed_auth"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(summary.current_draft_version, 1);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_accepts_query_key_with_matching_snapshot_and_source_requirement() {
|
||||
let database = TestDatabase::new().await;
|
||||
let profile_id = "auth_query_apply";
|
||||
let (registry, ws, job, fp, _profile, snapshot) = typed_auth_base(
|
||||
&database,
|
||||
"a_query_ok",
|
||||
profile_id,
|
||||
AuthConfig::ApiKeyQuery(ApiKeyQueryAuthConfig {
|
||||
param_name: "access_token".to_owned(),
|
||||
secret_id: SecretId::new("sec_query_key"),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let payload = typed_auth_plan_payload(
|
||||
"plan_query_ok",
|
||||
job.as_str(),
|
||||
&fp,
|
||||
profile_id,
|
||||
"api_key_query",
|
||||
Some("access_token"),
|
||||
snapshot,
|
||||
);
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, "plan_query_ok", &fp, payload).await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
let result = registry
|
||||
.apply_import_plan(&ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_query_ok",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result.report.status, ImportPlanApplyStatus::Applied);
|
||||
assert_eq!(result.report.counts.created, 1);
|
||||
let summary = registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_typed_auth"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(summary.current_draft_version, 1);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_rejects_query_key_source_mismatch_with_matching_live_snapshot() {
|
||||
let database = TestDatabase::new().await;
|
||||
let profile_id = "auth_query_mismatch";
|
||||
let (registry, ws, job, fp, _profile, snapshot) = typed_auth_base(
|
||||
&database,
|
||||
"a_query_mismatch",
|
||||
profile_id,
|
||||
AuthConfig::ApiKeyQuery(ApiKeyQueryAuthConfig {
|
||||
param_name: "access_token".to_owned(),
|
||||
secret_id: SecretId::new("sec_query_mismatch"),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let payload = typed_auth_plan_payload(
|
||||
"plan_query_mismatch",
|
||||
job.as_str(),
|
||||
&fp,
|
||||
profile_id,
|
||||
"api_key_query",
|
||||
Some("other_token"),
|
||||
snapshot,
|
||||
);
|
||||
let (plan, digest) =
|
||||
store_plan(®istry, &ws, &job, "plan_query_mismatch", &fp, payload).await;
|
||||
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
|
||||
let result = registry
|
||||
.apply_import_plan(&ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_query_mismatch",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &applied_at,
|
||||
})
|
||||
.await;
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(RegistryError::ImportPlanAuthUnavailable { auth_profile_id })
|
||||
if auth_profile_id == profile_id
|
||||
));
|
||||
assert!(
|
||||
registry
|
||||
.get_operation_summary(&ws, &OperationId::new("op_typed_auth"))
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none(),
|
||||
"query source mismatch must fail before creating an operation"
|
||||
);
|
||||
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,103 @@
|
||||
//! 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"]
|
||||
},
|
||||
"excluded_reasons": [{
|
||||
"key": "not_picked",
|
||||
"name": "Not Picked Display Label",
|
||||
"reason": "not_selected"
|
||||
}],
|
||||
"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.name, "Not Picked Display Label");
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
use super::super::common::TestDatabase;
|
||||
use super::{create_pending_openapi_job, create_workspace};
|
||||
use crank_artifacts::ArtifactRef;
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_registry::{
|
||||
ArtifactSourceId, CreateImportJobRequest, ImportJobId, ImportJobKind, ImportJobSourceEnvelope,
|
||||
ImportJobStatus,
|
||||
};
|
||||
use serde_json::json;
|
||||
use time::{Duration, OffsetDateTime};
|
||||
|
||||
async fn insert_active_source(
|
||||
raw: &sqlx::PgPool,
|
||||
workspace_id: &WorkspaceId,
|
||||
source_id: &str,
|
||||
blob_digest: &str,
|
||||
created_at: OffsetDateTime,
|
||||
) {
|
||||
sqlx::query(
|
||||
"insert into artifact_blobs (digest, artifact_ref, size_bytes, created_at, updated_at)
|
||||
values ($1, 'sha256:' || $1, 16, $2, $2)
|
||||
on conflict (digest) do nothing",
|
||||
)
|
||||
.bind(blob_digest)
|
||||
.bind(created_at)
|
||||
.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(blob_digest)
|
||||
.bind(created_at)
|
||||
.execute(raw)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn source_lifecycle(
|
||||
raw: &sqlx::PgPool,
|
||||
workspace_id: &WorkspaceId,
|
||||
source_id: &str,
|
||||
) -> String {
|
||||
sqlx::query_scalar(
|
||||
"select lifecycle from artifact_sources where workspace_id = $1 and source_id = $2",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(source_id)
|
||||
.fetch_one(raw)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cleanup_ignores_non_array_dependencies_and_preserves_referenced_source() {
|
||||
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_cleanup_object_deps").await;
|
||||
|
||||
// A non-expired job whose live primary source is old enough to be a
|
||||
// dangling candidate, plus an unreferenced peer so the dangling sweep must
|
||||
// evaluate the malformed `dependencies` branch for a non-matching source.
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_object_deps",
|
||||
now - Duration::hours(2),
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
let old = now - Duration::minutes(10);
|
||||
insert_active_source(&raw, &ws, "src_openapi_test", &"ab".repeat(32), old).await;
|
||||
insert_active_source(&raw, &ws, "src_openapi_orphan", &"ac".repeat(32), old).await;
|
||||
|
||||
// Corrupt the active job's payload so `dependencies` is an object, not an
|
||||
// array; the sweep must not abort on it.
|
||||
sqlx::query(
|
||||
"update import_jobs
|
||||
set preview_payload = jsonb_set(preview_payload, '{dependencies}', '{}'::jsonb)
|
||||
where id = $1 and workspace_id = $2",
|
||||
)
|
||||
.bind(job.as_str())
|
||||
.bind(ws.as_str())
|
||||
.execute(&raw)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let cleanup = registry
|
||||
.cleanup_expired_import_jobs(8)
|
||||
.await
|
||||
.expect("dangling cleanup must not abort on a non-array dependencies payload");
|
||||
assert_eq!(
|
||||
cleanup.deleted_jobs, 0,
|
||||
"the active job must survive cleanup"
|
||||
);
|
||||
assert_eq!(
|
||||
cleanup.detached_sources, 1,
|
||||
"the dangling sweep must still run and detach exactly the unreferenced peer"
|
||||
);
|
||||
assert_eq!(
|
||||
source_lifecycle(&raw, &ws, "src_openapi_test").await,
|
||||
"active",
|
||||
"the live primary source referenced by the job must be preserved"
|
||||
);
|
||||
assert_eq!(
|
||||
source_lifecycle(&raw, &ws, "src_openapi_orphan").await,
|
||||
"detached",
|
||||
"the unreferenced peer must be swept once the malformed branch is guarded"
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cleanup_ignores_non_openapi_sources_named_by_expired_jobs() {
|
||||
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_cleanup_foreign_source").await;
|
||||
|
||||
let old = now - Duration::hours(2);
|
||||
let blob_digest = "cd".repeat(32);
|
||||
insert_active_source(&raw, &ws, "src_confidential_leak", &blob_digest, old).await;
|
||||
|
||||
// Expired OpenAPI job naming a same-workspace source outside the OpenAPI
|
||||
// namespace.
|
||||
let job = ImportJobId::new("job_foreign_source");
|
||||
let source_id = ArtifactSourceId::new("src_confidential_leak");
|
||||
let digest = ArtifactRef::from_digest_hex(&blob_digest).unwrap();
|
||||
let preview_payload = json!({
|
||||
"source": {
|
||||
"source_id": source_id.as_str(),
|
||||
"digest": digest.as_str(),
|
||||
},
|
||||
"preview": { "ops": [] }
|
||||
});
|
||||
registry
|
||||
.create_import_job(CreateImportJobRequest {
|
||||
id: &job,
|
||||
workspace_id: &ws,
|
||||
kind: ImportJobKind::OpenApi,
|
||||
source_format: "openapi",
|
||||
source_version: Some("3.1.0"),
|
||||
status: ImportJobStatus::Pending,
|
||||
source: &ImportJobSourceEnvelope {
|
||||
source_id: source_id.clone(),
|
||||
digest: digest.clone(),
|
||||
},
|
||||
preview_payload: &preview_payload,
|
||||
created_at: &old,
|
||||
expires_at: &(now - Duration::minutes(10)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let cleanup = registry
|
||||
.cleanup_expired_import_jobs(8)
|
||||
.await
|
||||
.expect("expired OpenAPI cleanup must succeed");
|
||||
assert_eq!(cleanup.deleted_jobs, 1, "the expired job must be deleted");
|
||||
assert_eq!(
|
||||
source_lifecycle(&raw, &ws, "src_confidential_leak").await,
|
||||
"active",
|
||||
"an OpenAPI job must not detach a source outside its namespace"
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cleanup_keeps_source_referenced_by_nonexpired_peer_job() {
|
||||
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_cleanup_shared_source").await;
|
||||
let old = now - Duration::hours(2);
|
||||
let shared_source = "src_openapi_shared";
|
||||
|
||||
let expired = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_expired_shared_source",
|
||||
old,
|
||||
now - Duration::minutes(10),
|
||||
)
|
||||
.await;
|
||||
let peer = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_live_shared_source",
|
||||
old,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
insert_active_source(&raw, &ws, shared_source, &"ab".repeat(32), old).await;
|
||||
for job_id in [expired.as_str(), peer.as_str()] {
|
||||
sqlx::query(
|
||||
"update import_jobs
|
||||
set preview_payload = jsonb_set(
|
||||
preview_payload, '{source,source_id}', to_jsonb($2::text)
|
||||
)
|
||||
where id = $1 and workspace_id = $3",
|
||||
)
|
||||
.bind(job_id)
|
||||
.bind(shared_source)
|
||||
.bind(ws.as_str())
|
||||
.execute(&raw)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let cleanup = registry
|
||||
.cleanup_expired_import_jobs(8)
|
||||
.await
|
||||
.expect("expired job cleanup must preserve a source referenced by a live peer");
|
||||
assert_eq!(cleanup.deleted_jobs, 1);
|
||||
assert_eq!(
|
||||
source_lifecycle(&raw, &ws, shared_source).await,
|
||||
"active",
|
||||
"the source remains owned by the non-expired peer job"
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_job_finalization_keeps_source_referenced_by_peer_job() {
|
||||
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_failed_shared_source").await;
|
||||
let source_id = "src_openapi_shared";
|
||||
let failing = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_failing_shared_source",
|
||||
now - Duration::hours(1),
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
let peer = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_peer_shared_source",
|
||||
now - Duration::hours(1),
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
insert_active_source(&raw, &ws, source_id, &"ab".repeat(32), now).await;
|
||||
for job_id in [failing.as_str(), peer.as_str()] {
|
||||
sqlx::query(
|
||||
"update import_jobs
|
||||
set preview_payload = jsonb_set(
|
||||
preview_payload, '{source,source_id}', to_jsonb($2::text)
|
||||
)
|
||||
where id = $1 and workspace_id = $3",
|
||||
)
|
||||
.bind(job_id)
|
||||
.bind(source_id)
|
||||
.bind(ws.as_str())
|
||||
.execute(&raw)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
registry
|
||||
.finish_import_job(crank_registry::FinishImportJobRequest {
|
||||
id: &failing,
|
||||
status: ImportJobStatus::Failed,
|
||||
created_operation_ids: &json!([]),
|
||||
error_text: Some("test_failure"),
|
||||
finished_at: &now,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
source_lifecycle(&raw, &ws, source_id).await,
|
||||
"active",
|
||||
"failed finalization must not detach a source still referenced by a peer job"
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
@@ -0,0 +1,988 @@
|
||||
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(®istry, "ws_plan_a").await;
|
||||
let ws2 = create_workspace(®istry, "ws_plan_b").await;
|
||||
|
||||
let job1 = create_pending_openapi_job(®istry, &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(®istry, "ws_replay").await;
|
||||
let job = create_pending_openapi_job(®istry, &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(®istry, "ws_cw_1").await;
|
||||
let ws2 = create_workspace(®istry, "ws_cw_2").await;
|
||||
let job1 = create_pending_openapi_job(®istry, &ws1, "job_cw1", created_at, expires_at).await;
|
||||
let job2 = create_pending_openapi_job(®istry, &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(®istry, "ws_bounds").await;
|
||||
let job = create_pending_openapi_job(®istry, &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(®istry, "ws_job_states").await;
|
||||
let ws_other = create_workspace(®istry, "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(
|
||||
®istry,
|
||||
&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(
|
||||
®istry,
|
||||
&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(®istry, &ws_other, "job_foreign", created_at, expires_at)
|
||||
.await;
|
||||
assert!(matches!(
|
||||
attempt_create(
|
||||
®istry,
|
||||
&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(
|
||||
®istry,
|
||||
&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(®istry, "ws_race").await;
|
||||
let job = create_pending_openapi_job(®istry, &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(
|
||||
®istry,
|
||||
&ws,
|
||||
&plan_same,
|
||||
&job,
|
||||
&payload_a,
|
||||
&created_at,
|
||||
&expires_at
|
||||
),
|
||||
attempt_create(
|
||||
®istry,
|
||||
&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(
|
||||
®istry,
|
||||
&ws,
|
||||
&plan_other,
|
||||
&job,
|
||||
&payload_a,
|
||||
&created_at,
|
||||
&expires_at
|
||||
),
|
||||
attempt_create(
|
||||
®istry,
|
||||
&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(®istry, "ws_micro").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&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(®istry, "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(®istry, &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(®istry, &ws, "job_long", created_at, job_expires_at).await;
|
||||
assert!(matches!(
|
||||
attempt_create(
|
||||
®istry,
|
||||
&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(®istry, "ws_legacy").await;
|
||||
let job =
|
||||
create_pending_openapi_job(®istry, &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(®istry, "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(®istry, "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(®istry, &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;
|
||||
}
|
||||
@@ -0,0 +1,787 @@
|
||||
//! Story 2.12 evidence for v2 semantic digests, catalog drift and Apply.
|
||||
|
||||
use super::super::common::{TestDatabase, test_operation};
|
||||
use super::{create_pending_openapi_job, create_workspace, parse_ts};
|
||||
use crank_artifacts::ArtifactRef;
|
||||
use crank_core::{OperationStatus, WorkspaceId};
|
||||
use crank_registry::{
|
||||
ApplyImportPlanRequest, ArtifactSourceId, CreateImportJobRequest, CreateImportPlanRequest,
|
||||
ImportJobId, ImportJobKind, ImportJobSourceEnvelope, ImportJobStatus, ImportPlanApplyStatus,
|
||||
ImportPlanCandidateOutcome, ImportPlanId, RegistryError,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::{Duration, OffsetDateTime};
|
||||
|
||||
const SOURCE_ID: &str = "src_openapi_test";
|
||||
const SOURCE_DIGEST: &str =
|
||||
"sha256:abababababababababababababababababababababababababababababababab";
|
||||
|
||||
fn fingerprint() -> Value {
|
||||
json!({"importer": "registry-preview-v2-test", "preview_digest": "fp-v2-1"})
|
||||
}
|
||||
|
||||
fn operation(
|
||||
id: &str,
|
||||
name: &str,
|
||||
created_at: &str,
|
||||
updated_at: &str,
|
||||
) -> crank_registry::RegistryOperation {
|
||||
let mut operation = test_operation(id, 1, OperationStatus::Draft);
|
||||
operation.name = name.to_owned();
|
||||
operation.display_name = "Candidate display name".to_owned();
|
||||
operation.execution_config.auth_profile_ref = None;
|
||||
operation.created_at = parse_ts(created_at);
|
||||
operation.updated_at = parse_ts(updated_at);
|
||||
operation
|
||||
}
|
||||
|
||||
fn v2_payload(
|
||||
plan_id: &str,
|
||||
job_id: &str,
|
||||
source_id: &str,
|
||||
operation: crank_registry::RegistryOperation,
|
||||
catalog_revision: &str,
|
||||
) -> Value {
|
||||
let key = "candidate";
|
||||
json!({
|
||||
"schema_version": "import-plan-v2",
|
||||
"plan_reference": plan_id,
|
||||
"job_id": job_id,
|
||||
"fingerprint": fingerprint(),
|
||||
"catalog_revision": catalog_revision,
|
||||
"support_matrix_version": "1.0.2",
|
||||
"source": { "source_id": source_id, "digest": SOURCE_DIGEST },
|
||||
"dependencies": [],
|
||||
"excluded_reasons": [],
|
||||
"findings": { "document": [], "candidates": [{ "key": key, "findings": [] }] },
|
||||
"selection": {
|
||||
"mode": "full", "all": [key], "selected": [key], "excluded": []
|
||||
},
|
||||
"counts": { "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 },
|
||||
"candidates": [{
|
||||
"key": key,
|
||||
"name": operation.name,
|
||||
"state": "actionable",
|
||||
"decision": { "action": "create" },
|
||||
"findings": [],
|
||||
"operation": operation
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
async fn store_plan(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
job_id: &ImportJobId,
|
||||
plan_id: &str,
|
||||
payload: &Value,
|
||||
created_at: OffsetDateTime,
|
||||
) -> (ImportPlanId, String) {
|
||||
let plan_id = ImportPlanId::new(plan_id);
|
||||
let created = registry
|
||||
.create_import_plan(CreateImportPlanRequest {
|
||||
id: &plan_id,
|
||||
workspace_id,
|
||||
job_id,
|
||||
payload,
|
||||
created_at: &created_at,
|
||||
expires_at: &(created_at + Duration::minutes(30)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
(plan_id, created.digest)
|
||||
}
|
||||
|
||||
async fn activate_source(raw: &sqlx::PgPool, workspace_id: &WorkspaceId, now: OffsetDateTime) {
|
||||
let hex = "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(&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();
|
||||
}
|
||||
|
||||
async fn create_job_with_source(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
job_id: &str,
|
||||
source_id: &str,
|
||||
now: OffsetDateTime,
|
||||
) -> ImportJobId {
|
||||
let job_id = ImportJobId::new(job_id);
|
||||
let source_id = ArtifactSourceId::new(source_id);
|
||||
let digest = ArtifactRef::from_digest_hex(&"ab".repeat(32)).unwrap();
|
||||
let preview_payload = json!({
|
||||
"source": {"source_id": source_id.as_str(), "digest": digest.as_str()},
|
||||
"preview": {"source": "integration-test"}
|
||||
});
|
||||
registry
|
||||
.create_import_job(CreateImportJobRequest {
|
||||
id: &job_id,
|
||||
workspace_id,
|
||||
kind: ImportJobKind::OpenApi,
|
||||
source_format: "openapi",
|
||||
source_version: Some("3.1.0"),
|
||||
status: ImportJobStatus::Pending,
|
||||
source: &ImportJobSourceEnvelope { source_id, digest },
|
||||
preview_payload: &preview_payload,
|
||||
created_at: &now,
|
||||
expires_at: &(now + Duration::hours(1)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
job_id
|
||||
}
|
||||
|
||||
fn raw_digest(payload: &Value) -> String {
|
||||
format!("{:x}", Sha256::digest(serde_json::to_vec(payload).unwrap()))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v2_digest_ignores_job_plan_generated_operation_ids_and_runtime_timestamps() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let ws = create_workspace(®istry, "ws_v2_digest").await;
|
||||
let first_time =
|
||||
OffsetDateTime::from_unix_timestamp(OffsetDateTime::now_utc().unix_timestamp()).unwrap();
|
||||
let second_time = first_time + Duration::minutes(2);
|
||||
let first_job =
|
||||
create_job_with_source(®istry, &ws, "job_v2_digest_a", "src_v2_a", first_time).await;
|
||||
let second_job =
|
||||
create_job_with_source(®istry, &ws, "job_v2_digest_b", "src_v2_b", second_time).await;
|
||||
let revision = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
let first_payload = v2_payload(
|
||||
"plan_v2_digest_a",
|
||||
first_job.as_str(),
|
||||
"src_v2_a",
|
||||
operation(
|
||||
"op_generated_a",
|
||||
"candidate_tool",
|
||||
"2026-03-25T10:00:00Z",
|
||||
"2026-03-25T10:00:00Z",
|
||||
),
|
||||
&revision,
|
||||
);
|
||||
let second_payload = v2_payload(
|
||||
"plan_v2_digest_b",
|
||||
second_job.as_str(),
|
||||
"src_v2_b",
|
||||
operation(
|
||||
"op_generated_b",
|
||||
"candidate_tool",
|
||||
"2026-03-25T10:02:00Z",
|
||||
"2026-03-25T10:02:00Z",
|
||||
),
|
||||
&revision,
|
||||
);
|
||||
|
||||
let (_, first_digest) = store_plan(
|
||||
®istry,
|
||||
&ws,
|
||||
&first_job,
|
||||
"plan_v2_digest_a",
|
||||
&first_payload,
|
||||
first_time,
|
||||
)
|
||||
.await;
|
||||
let (_, second_digest) = store_plan(
|
||||
®istry,
|
||||
&ws,
|
||||
&second_job,
|
||||
"plan_v2_digest_b",
|
||||
&second_payload,
|
||||
second_time,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
first_digest, second_digest,
|
||||
"server identities and runtime instants must not change semantic identity"
|
||||
);
|
||||
assert_eq!(
|
||||
registry
|
||||
.get_import_plan(&ws, &ImportPlanId::new("plan_v2_digest_a"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.payload,
|
||||
first_payload,
|
||||
"canonical hashing must leave immutable v2 evidence untouched"
|
||||
);
|
||||
let mut replay_with_new_generated_id = first_payload.clone();
|
||||
replay_with_new_generated_id["candidates"][0]["operation"]["id"] = json!("op_generated_retry");
|
||||
let plan_id = ImportPlanId::new("plan_v2_digest_a");
|
||||
let conflict = registry
|
||||
.create_import_plan(CreateImportPlanRequest {
|
||||
id: &plan_id,
|
||||
workspace_id: &ws,
|
||||
job_id: &first_job,
|
||||
payload: &replay_with_new_generated_id,
|
||||
created_at: &first_time,
|
||||
expires_at: &(first_time + Duration::minutes(30)),
|
||||
})
|
||||
.await
|
||||
.expect_err("replay identity still compares immutable raw payload after semantic hashing");
|
||||
assert!(matches!(conflict, RegistryError::ImportPlanConflict { .. }));
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v2_digest_changes_for_selection_name_and_conflict_decision() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_v2_semantics").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_v2_semantics",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
let revision = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
let base = v2_payload(
|
||||
"plan_semantic_base",
|
||||
job.as_str(),
|
||||
SOURCE_ID,
|
||||
operation(
|
||||
"op_base",
|
||||
"candidate_tool",
|
||||
"2026-10-03T10:00:00Z",
|
||||
"2026-10-03T10:00:00Z",
|
||||
),
|
||||
&revision,
|
||||
);
|
||||
let mut changed_selection = base.clone();
|
||||
changed_selection["plan_reference"] = json!("plan_semantic_selection");
|
||||
changed_selection["selection"]["mode"] = json!("partial");
|
||||
changed_selection["selection"]["all"] = json!(["candidate", "other"]);
|
||||
changed_selection["selection"]["excluded"] = json!(["other"]);
|
||||
changed_selection["counts"]["excluded"] = json!(1);
|
||||
changed_selection["excluded_reasons"] = json!([{"key": "other", "reason": "not_selected"}]);
|
||||
changed_selection["findings"]["candidates"] = json!([
|
||||
{"key": "candidate", "findings": []}, {"key": "other", "findings": []}
|
||||
]);
|
||||
let mut changed_name = base.clone();
|
||||
changed_name["plan_reference"] = json!("plan_semantic_name");
|
||||
changed_name["candidates"][0]["name"] = json!("renamed_tool");
|
||||
changed_name["candidates"][0]["operation"]["name"] = json!("renamed_tool");
|
||||
let mut changed_decision = base.clone();
|
||||
changed_decision["plan_reference"] = json!("plan_semantic_decision");
|
||||
changed_decision["candidates"][0]["decision"] =
|
||||
json!({"action": "rename", "confirmed_name": "candidate_tool"});
|
||||
let mut changed_support_matrix = base.clone();
|
||||
changed_support_matrix["plan_reference"] = json!("plan_semantic_support");
|
||||
changed_support_matrix["support_matrix_version"] = json!("1.0.3");
|
||||
|
||||
let (_, digest) = store_plan(®istry, &ws, &job, "plan_semantic_base", &base, now).await;
|
||||
let (_, selection_digest) = store_plan(
|
||||
®istry,
|
||||
&ws,
|
||||
&job,
|
||||
"plan_semantic_selection",
|
||||
&changed_selection,
|
||||
now,
|
||||
)
|
||||
.await;
|
||||
let (_, name_digest) = store_plan(
|
||||
®istry,
|
||||
&ws,
|
||||
&job,
|
||||
"plan_semantic_name",
|
||||
&changed_name,
|
||||
now,
|
||||
)
|
||||
.await;
|
||||
let (_, decision_digest) = store_plan(
|
||||
®istry,
|
||||
&ws,
|
||||
&job,
|
||||
"plan_semantic_decision",
|
||||
&changed_decision,
|
||||
now,
|
||||
)
|
||||
.await;
|
||||
let (_, support_matrix_digest) = store_plan(
|
||||
®istry,
|
||||
&ws,
|
||||
&job,
|
||||
"plan_semantic_support",
|
||||
&changed_support_matrix,
|
||||
now,
|
||||
)
|
||||
.await;
|
||||
assert_ne!(digest, selection_digest, "selection changes are semantic");
|
||||
assert_ne!(
|
||||
digest, name_digest,
|
||||
"the confirmed operation name is semantic"
|
||||
);
|
||||
assert_ne!(
|
||||
digest, decision_digest,
|
||||
"conflict resolution choices are semantic"
|
||||
);
|
||||
assert_ne!(
|
||||
digest, support_matrix_digest,
|
||||
"the support matrix version is semantic evidence"
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_v1_digest_and_stored_payload_remain_unchanged_and_readable() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_v1_compat").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_v1_compat",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
let plan_id = ImportPlanId::new("plan_v1_compat");
|
||||
let payload = json!({
|
||||
"schema_version": "import-plan-v1", "plan_reference": plan_id.as_str(), "job_id": job.as_str(),
|
||||
"fingerprint": {"legacy": true}, "source": {"source_id": SOURCE_ID, "digest": SOURCE_DIGEST},
|
||||
"dependencies": [], "selection": {"mode": "full", "all": ["legacy"], "selected": ["legacy"], "excluded": []},
|
||||
"counts": {"selected": 1, "excluded": 0, "actionable": 1, "blocked": 0},
|
||||
"candidates": [{"key": "legacy", "name": "legacy_tool", "state": "actionable", "decision": {"action": "create"}}]
|
||||
});
|
||||
let created = registry
|
||||
.create_import_plan(CreateImportPlanRequest {
|
||||
id: &plan_id,
|
||||
workspace_id: &ws,
|
||||
job_id: &job,
|
||||
payload: &payload,
|
||||
created_at: &now,
|
||||
expires_at: &(now + Duration::minutes(30)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
created.digest,
|
||||
raw_digest(&payload),
|
||||
"legacy v1 keeps byte-for-byte digest rules"
|
||||
);
|
||||
let read = registry
|
||||
.get_import_plan(&ws, &plan_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("stored v1 plan remains readable");
|
||||
assert_eq!(read.payload, payload);
|
||||
assert_eq!(read.digest, created.digest);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn catalog_revision_ignores_timestamps_and_foreign_workspace_but_tracks_semantics() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw = database.raw_pool().await;
|
||||
let ws = create_workspace(®istry, "ws_catalog_revision").await;
|
||||
let foreign = create_workspace(®istry, "ws_catalog_foreign").await;
|
||||
let mut local_op = operation(
|
||||
"op_catalog_local",
|
||||
"local_tool",
|
||||
"2026-10-03T10:00:00Z",
|
||||
"2026-10-03T10:00:00Z",
|
||||
);
|
||||
registry
|
||||
.create_operation(&ws, &local_op, None)
|
||||
.await
|
||||
.unwrap();
|
||||
let baseline = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
|
||||
sqlx::query("update operations set updated_at = $1 where workspace_id = $2 and id = $3")
|
||||
.bind(parse_ts("2026-10-03T11:00:00Z"))
|
||||
.bind(ws.as_str())
|
||||
.bind(local_op.id.as_str())
|
||||
.execute(&raw)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
registry.import_catalog_revision(&ws).await.unwrap(),
|
||||
baseline,
|
||||
"runtime timestamps are excluded"
|
||||
);
|
||||
|
||||
let foreign_op = operation(
|
||||
"op_catalog_foreign",
|
||||
"foreign_tool",
|
||||
"2026-10-03T10:00:00Z",
|
||||
"2026-10-03T10:00:00Z",
|
||||
);
|
||||
registry
|
||||
.create_operation(&foreign, &foreign_op, None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
registry.import_catalog_revision(&ws).await.unwrap(),
|
||||
baseline,
|
||||
"foreign scope is excluded"
|
||||
);
|
||||
|
||||
sqlx::query(
|
||||
"update operations set name = 'renamed_local_tool' where workspace_id = $1 and id = $2",
|
||||
)
|
||||
.bind(ws.as_str())
|
||||
.bind(local_op.id.as_str())
|
||||
.execute(&raw)
|
||||
.await
|
||||
.unwrap();
|
||||
let renamed = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
assert_ne!(renamed, baseline, "catalog names affect the revision");
|
||||
sqlx::query(
|
||||
"update operations set current_draft_version = 2 where workspace_id = $1 and id = $2",
|
||||
)
|
||||
.bind(ws.as_str())
|
||||
.bind(local_op.id.as_str())
|
||||
.execute(&raw)
|
||||
.await
|
||||
.unwrap();
|
||||
let versioned = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
assert_ne!(
|
||||
versioned, renamed,
|
||||
"catalog version pointers affect the revision"
|
||||
);
|
||||
sqlx::query("update operations set status = 'published' where workspace_id = $1 and id = $2")
|
||||
.bind(ws.as_str())
|
||||
.bind(local_op.id.as_str())
|
||||
.execute(&raw)
|
||||
.await
|
||||
.unwrap();
|
||||
let status_changed = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
assert_ne!(
|
||||
status_changed, versioned,
|
||||
"catalog lifecycle affects the revision"
|
||||
);
|
||||
// Avoid accidental use of stale local fixture state if this case grows.
|
||||
local_op.name = "renamed_local_tool".to_owned();
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn revalidation_and_apply_reject_catalog_drift_without_plan_mutation() {
|
||||
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_v2_drift").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_v2_drift",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw, &ws, now).await;
|
||||
let fp = fingerprint();
|
||||
let revision = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
let plan_id_text = "plan_v2_drift";
|
||||
let payload = v2_payload(
|
||||
plan_id_text,
|
||||
job.as_str(),
|
||||
SOURCE_ID,
|
||||
operation(
|
||||
"op_v2_planned",
|
||||
"planned_tool",
|
||||
"2026-10-03T10:00:00Z",
|
||||
"2026-10-03T10:00:00Z",
|
||||
),
|
||||
&revision,
|
||||
);
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, plan_id_text, &payload, now).await;
|
||||
registry
|
||||
.revalidate_import_plan(&ws, &plan, &fp)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let catalog_change = operation(
|
||||
"op_v2_catalog_change",
|
||||
"catalog_change_tool",
|
||||
"2026-10-03T10:00:00Z",
|
||||
"2026-10-03T10:00:00Z",
|
||||
);
|
||||
registry
|
||||
.create_operation(&ws, &catalog_change, None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(
|
||||
registry.revalidate_import_plan(&ws, &plan, &fp).await,
|
||||
Err(RegistryError::ImportPlanFingerprintStale { .. })
|
||||
),
|
||||
"read-only revalidation must flag catalog drift"
|
||||
);
|
||||
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_v2_drift",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &now,
|
||||
};
|
||||
assert!(
|
||||
matches!(
|
||||
registry.apply_import_plan(&request).await,
|
||||
Err(RegistryError::ImportPlanFingerprintStale { .. })
|
||||
),
|
||||
"fresh Apply must independently reject the stale catalog revision"
|
||||
);
|
||||
assert!(
|
||||
registry
|
||||
.get_operation_summary(&ws, &crank_core::OperationId::new("op_v2_planned"))
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none(),
|
||||
"catalog drift must fail before creating the planned operation"
|
||||
);
|
||||
assert_eq!(
|
||||
registry
|
||||
.get_import_plan_application(&ws, "idem_v2_drift")
|
||||
.await
|
||||
.unwrap(),
|
||||
None,
|
||||
"a stale apply must not persist application evidence"
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v2_apply_creates_operation_and_reports_the_confirmed_candidate() {
|
||||
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_v2_apply").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_v2_apply",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw, &ws, now).await;
|
||||
let fp = fingerprint();
|
||||
let revision = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
let payload = v2_payload(
|
||||
"plan_v2_apply",
|
||||
job.as_str(),
|
||||
SOURCE_ID,
|
||||
operation(
|
||||
"op_v2_apply",
|
||||
"v2_apply_tool",
|
||||
"2026-10-03T10:00:00Z",
|
||||
"2026-10-03T10:00:00Z",
|
||||
),
|
||||
&revision,
|
||||
);
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, "plan_v2_apply", &payload, now).await;
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_v2_apply",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &now,
|
||||
};
|
||||
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);
|
||||
assert_eq!(result.report.outcomes[0].key, "candidate");
|
||||
assert_eq!(
|
||||
result.report.outcomes[0].outcome,
|
||||
ImportPlanCandidateOutcome::Created
|
||||
);
|
||||
assert_eq!(
|
||||
result.report.outcomes[0].operation_id.as_deref(),
|
||||
Some("op_v2_apply")
|
||||
);
|
||||
assert_eq!(
|
||||
registry
|
||||
.get_operation_summary(&ws, &crank_core::OperationId::new("op_v2_apply"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.current_draft_version,
|
||||
1
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn partial_v2_apply_preserves_the_reason_for_an_excluded_candidate() {
|
||||
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_v2_excluded_reason").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_v2_excluded_reason",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw, &ws, now).await;
|
||||
let fp = fingerprint();
|
||||
let revision = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
let mut payload = v2_payload(
|
||||
"plan_v2_excluded_reason",
|
||||
job.as_str(),
|
||||
SOURCE_ID,
|
||||
operation(
|
||||
"op_v2_excluded_reason",
|
||||
"selected_tool",
|
||||
"2026-10-03T10:00:00Z",
|
||||
"2026-10-03T10:00:00Z",
|
||||
),
|
||||
&revision,
|
||||
);
|
||||
payload["selection"] = json!({
|
||||
"mode": "partial", "all": ["candidate", "unsupported"],
|
||||
"selected": ["candidate"], "excluded": ["unsupported"]
|
||||
});
|
||||
payload["counts"] = json!({"selected": 1, "excluded": 1, "actionable": 1, "blocked": 0});
|
||||
payload["excluded_reasons"] = json!([{"key": "unsupported", "reason": "unsupported_schema"}]);
|
||||
payload["findings"]["candidates"] = json!([
|
||||
{"key": "candidate", "findings": []},
|
||||
{"key": "unsupported", "findings": [{"code": "unsupported_schema"}]}
|
||||
]);
|
||||
let (plan, digest) = store_plan(
|
||||
®istry,
|
||||
&ws,
|
||||
&job,
|
||||
"plan_v2_excluded_reason",
|
||||
&payload,
|
||||
now,
|
||||
)
|
||||
.await;
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_v2_excluded_reason",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &now,
|
||||
};
|
||||
let result = registry.apply_import_plan(&request).await.unwrap();
|
||||
assert_eq!(result.report.status, ImportPlanApplyStatus::Applied);
|
||||
assert_eq!(result.report.counts.excluded, 1);
|
||||
let excluded = result
|
||||
.report
|
||||
.outcomes
|
||||
.iter()
|
||||
.find(|item| item.key == "unsupported")
|
||||
.unwrap();
|
||||
assert_eq!(excluded.outcome, ImportPlanCandidateOutcome::Excluded);
|
||||
assert_eq!(excluded.reason.as_deref(), Some("unsupported_schema"));
|
||||
assert!(
|
||||
registry
|
||||
.get_operation_summary(&ws, &crank_core::OperationId::new("op_v2_excluded_reason"))
|
||||
.await
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plan_store_accepts_the_full_two_thousand_candidate_limit() {
|
||||
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_v2_limit").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_v2_limit",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw, &ws, now).await;
|
||||
let revision = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
let mut keys = Vec::with_capacity(2_000);
|
||||
let mut candidates = Vec::with_capacity(2_000);
|
||||
let mut candidate_findings = Vec::with_capacity(2_000);
|
||||
for index in 0..2_000 {
|
||||
let key = format!("candidate-{index:04}");
|
||||
let name = format!("candidate_{index:04}_tool");
|
||||
let operation = operation(
|
||||
&format!("op_limit_{index:04}"),
|
||||
&name,
|
||||
"2026-10-03T10:00:00Z",
|
||||
"2026-10-03T10:00:00Z",
|
||||
);
|
||||
keys.push(key.clone());
|
||||
candidates.push(json!({
|
||||
"key": key, "name": name, "state": "actionable", "decision": {"action": "create"},
|
||||
"findings": [], "operation": operation
|
||||
}));
|
||||
candidate_findings.push(json!({"key": key, "findings": []}));
|
||||
}
|
||||
let payload = json!({
|
||||
"schema_version": "import-plan-v2", "plan_reference": "plan_v2_limit", "job_id": job.as_str(),
|
||||
"fingerprint": fingerprint(), "catalog_revision": revision, "support_matrix_version": "1.0.2",
|
||||
"source": {"source_id": SOURCE_ID, "digest": SOURCE_DIGEST}, "dependencies": [],
|
||||
"excluded_reasons": [],
|
||||
"findings": {"document": [], "candidates": candidate_findings},
|
||||
"selection": {"mode": "full", "all": keys, "selected": keys, "excluded": []},
|
||||
"counts": {"selected": 2_000, "excluded": 0, "actionable": 2_000, "blocked": 0},
|
||||
"candidates": candidates
|
||||
});
|
||||
let encoded = serde_json::to_vec(&payload).unwrap();
|
||||
assert!(
|
||||
encoded.len() < 16 * 1024 * 1024,
|
||||
"fixture itself must remain under the payload cap"
|
||||
);
|
||||
let (plan_id, _) = store_plan(®istry, &ws, &job, "plan_v2_limit", &payload, now).await;
|
||||
let stored = registry
|
||||
.get_import_plan(&ws, &plan_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
stored.payload["candidates"].as_array().unwrap().len(),
|
||||
2_000
|
||||
);
|
||||
assert_eq!(
|
||||
stored.payload["selection"]["selected"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
2_000
|
||||
);
|
||||
registry
|
||||
.revalidate_import_plan(&ws, &plan_id, &fingerprint())
|
||||
.await
|
||||
.expect("the maximum valid candidate set must pass registry material validation");
|
||||
database.cleanup().await;
|
||||
}
|
||||
@@ -2,7 +2,9 @@ use crank_registry::{MigrationAuthority, MigrationPreflight, PostgresRegistry};
|
||||
use sqlx::Row;
|
||||
|
||||
mod artifact_metadata;
|
||||
mod import_plan;
|
||||
mod legacy_adoption;
|
||||
mod preflight;
|
||||
mod rollback;
|
||||
|
||||
static EVENT_TRIGGER_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
|
||||
@@ -53,6 +55,8 @@ async fn controlled_authority_is_versioned_and_safe_under_concurrent_apply() {
|
||||
(11, "onboarding-product-events-v11"),
|
||||
(12, "artifact-metadata-v12"),
|
||||
(13, "artifact-cleanup-indexes-v13"),
|
||||
(14, "import-plan-v14"),
|
||||
(15, "onboarding-import-selection-v15"),
|
||||
];
|
||||
assert_eq!(rows.len(), expected.len());
|
||||
for (row, (version, name)) in rows.iter().zip(expected) {
|
||||
@@ -106,9 +110,20 @@ async fn controlled_authority_is_versioned_and_safe_under_concurrent_apply() {
|
||||
.await
|
||||
.expect("V12 artifact metadata relations must be readable");
|
||||
assert_eq!(artifact_relations.len(), 2);
|
||||
let import_plan_relations = sqlx::query(
|
||||
"select table_name
|
||||
from information_schema.tables
|
||||
where table_schema = current_schema()
|
||||
and table_name in ('import_plans', 'import_plan_applications')
|
||||
order by table_name",
|
||||
)
|
||||
.fetch_all(first.pool())
|
||||
.await
|
||||
.expect("V14 import plan relations must be readable");
|
||||
assert_eq!(import_plan_relations.len(), 2);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(first.pool()).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 13 }
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
@@ -232,7 +247,7 @@ async fn ledgerless_legacy_baseline_is_consolidated_without_data_loss() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 13,
|
||||
target: 15,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -345,13 +360,13 @@ async fn healthy_v2_is_reported_as_migration_required_and_upgrades_to_v3() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 2,
|
||||
target: 13,
|
||||
target: 15,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 13 }
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
);
|
||||
let trace_column: bool = sqlx::query_scalar(
|
||||
"select exists (
|
||||
@@ -394,7 +409,7 @@ async fn healthy_v3_upgrades_to_v4_with_honest_legacy_snapshot_provenance() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 3,
|
||||
target: 13,
|
||||
target: 15,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -454,7 +469,7 @@ async fn healthy_v4_upgrades_to_v5_without_fabricating_legacy_outcomes() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 4,
|
||||
target: 13,
|
||||
target: 15,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -708,7 +723,7 @@ async fn v3_upgrade_ignores_oversized_legacy_request_ids_in_partial_index() {
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 13 }
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
);
|
||||
}
|
||||
async fn remove_v3_schema(pool: &sqlx::PgPool) {
|
||||
@@ -862,7 +877,41 @@ async fn remove_v11_schema(pool: &sqlx::PgPool) {
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v14_schema(pool: &sqlx::PgPool) {
|
||||
remove_v15_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists import_plan_applications;
|
||||
drop table if exists import_plans;
|
||||
drop function if exists crank_reject_import_plan_mutation();
|
||||
alter table import_jobs drop constraint if exists import_jobs_workspace_id_unique;
|
||||
delete from __crank_migrations where version = 14;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v15_schema(pool: &sqlx::PgPool) {
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists onboarding_import_selections;
|
||||
alter table operations drop constraint if exists operations_workspace_id_unique;
|
||||
alter table product_events drop constraint if exists product_events_name_check;
|
||||
alter table product_events add constraint product_events_name_check check (event_name in (
|
||||
'onboarding_eligible', 'onboarding_started', 'onboarding_resumed',
|
||||
'onboarding_dismissed', 'onboarding_abandoned', 'onboarding_completed'
|
||||
));
|
||||
alter table product_event_daily_rollups drop constraint if exists product_event_daily_rollups_name_check;
|
||||
alter table product_event_daily_rollups add constraint product_event_daily_rollups_name_check check (event_name in (
|
||||
'onboarding_eligible', 'onboarding_started', 'onboarding_resumed',
|
||||
'onboarding_dismissed', 'onboarding_abandoned', 'onboarding_completed'
|
||||
));
|
||||
delete from __crank_migrations where version = 15;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v12_schema(pool: &sqlx::PgPool) {
|
||||
remove_v14_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists import_jobs_openapi_source_idx;
|
||||
drop index if exists import_jobs_expires_at_idx;
|
||||
@@ -878,106 +927,3 @@ async fn remove_v12_schema(pool: &sqlx::PgPool) {
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn partial_sequence_fails_closed() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_partial_sequence").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
sqlx::query("delete from __crank_migrations where version = 1")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.code(),
|
||||
"partial_sequence"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn missing_relation_with_current_ledger_fails_closed() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_missing_relation").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
sqlx::query("drop table usage_rollups")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence");
|
||||
assert_eq!(error.stage(), "preflight.schema");
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn unregistered_legacy_extension_provenance_is_rejected() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_legacy_extension").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
sqlx::query("drop table __crank_migrations, __crank_migration_legacy_audit")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let checksum = "a".repeat(64);
|
||||
sqlx::query(
|
||||
"insert into __crank_ext_migrations (extension_name, version, checksum)
|
||||
values ('known-extension', 1, $1)",
|
||||
)
|
||||
.bind(&checksum)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::apply(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "legacy_conflict");
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn any_owned_relation_without_core_ledger_is_partial() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_owned_partial").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
sqlx::query("create table users (id text primary key)")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence");
|
||||
assert_eq!(error.stage(), "preflight.core_missing");
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn empty_core_ledger_is_reported_separately() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_empty_core_ledger").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
sqlx::query("delete from __crank_core_migrations")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence");
|
||||
assert_eq!(error.stage(), "preflight.core_cardinality");
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn current_ledger_with_structural_drift_fails_closed() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_structural_drift").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
sqlx::query("alter table mcp_transport_sessions drop column supports_elicitation")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence");
|
||||
assert_eq!(error.stage(), "preflight.schema");
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn tampered_legacy_audit_fails_closed() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_tampered_audit").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
sqlx::query(
|
||||
"update __crank_migration_legacy_audit set source_checksum = 'tampered' where source = 'core'",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "legacy_conflict");
|
||||
}
|
||||
@@ -27,7 +27,7 @@ async fn healthy_v11_upgrades_to_v13_without_rewriting_prior_ledger() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 11,
|
||||
target: 13,
|
||||
target: 15,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -158,7 +158,7 @@ async fn v12_guard_still_rejects_column_constraint_index_and_relation_drift() {
|
||||
sqlx::raw_sql(restore).execute(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 13 },
|
||||
MigrationPreflight::Current { version: 15 },
|
||||
"restore: {restore}"
|
||||
);
|
||||
}
|
||||
@@ -211,7 +211,7 @@ async fn v13_guard_rejects_wrong_cleanup_index_order_and_predicate() {
|
||||
sqlx::raw_sql(restore).execute(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 13 },
|
||||
MigrationPreflight::Current { version: 15 },
|
||||
"restore: {restore}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,459 @@
|
||||
use sqlx::Row;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn count_sql(table: &str) -> sqlx::AssertSqlSafe<String> {
|
||||
sqlx::AssertSqlSafe(format!("select count(*) from {table}"))
|
||||
}
|
||||
|
||||
async fn count_rows(pool: &sqlx::PgPool, sql: sqlx::AssertSqlSafe<String>) -> i64 {
|
||||
let value: i64 = sqlx::query_scalar::<_, i64>(sql)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
value
|
||||
}
|
||||
|
||||
async fn seed_import_plan_fixture(pool: &sqlx::PgPool) {
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
sqlx::query(
|
||||
"insert into workspaces (id, slug, display_name, status, settings_json, created_at, updated_at)
|
||||
values ('ws_import_plan', 'import-plan', 'Import Plan', 'active', '{}'::jsonb, $1, $1)",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(now)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"insert into import_jobs (
|
||||
id, workspace_id, kind, source_format, status, preview_payload, created_at, expires_at
|
||||
) values (
|
||||
'job_v14', 'ws_import_plan', 'openapi', 'openapi', 'ready', '{}'::jsonb, $1, $1 + interval '1 hour'
|
||||
)",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(now)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let digest = "ab".repeat(32);
|
||||
sqlx::query(
|
||||
"insert into import_plans (
|
||||
workspace_id, id, job_id, digest, payload, created_at, expires_at
|
||||
) values (
|
||||
'ws_import_plan', 'plan_v14', 'job_v14', $1, '{}'::jsonb, $2, $2 + interval '1 hour'
|
||||
)",
|
||||
)
|
||||
.bind(&digest)
|
||||
.bind(now)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"insert into import_plan_applications (
|
||||
workspace_id, idempotency_key, plan_id, plan_digest, report, created_at
|
||||
) values (
|
||||
'ws_import_plan', 'idem_v14', 'plan_v14', $1, '{}'::jsonb, $2
|
||||
)",
|
||||
)
|
||||
.bind(&digest)
|
||||
.bind(now)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fresh_install_exposes_import_plan_objects_with_cascading_job_fk() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v14_fresh").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
);
|
||||
let tables = sqlx::query(
|
||||
"select table_name
|
||||
from information_schema.tables
|
||||
where table_schema = current_schema()
|
||||
and table_name in ('import_plans', 'import_plan_applications')
|
||||
order by table_name",
|
||||
)
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let names = tables
|
||||
.iter()
|
||||
.map(|row| row.get::<String, _>("table_name"))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(names, vec!["import_plan_applications", "import_plans"]);
|
||||
// The plan FK to the job is immediate with ON DELETE CASCADE: a plan never
|
||||
// outlives its job. The applications table keeps only its workspace FK —
|
||||
// replay evidence must survive plan and job cleanup.
|
||||
let foreign_keys = sqlx::query(
|
||||
"select c.conname, c.condeferrable, c.condeferred, c.confdeltype::text as delete_rule
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and c.contype = 'f'
|
||||
and c.conname in (
|
||||
'import_plans_job_fk',
|
||||
'import_plans_workspace_id_fkey',
|
||||
'import_plan_applications_workspace_id_fkey'
|
||||
)
|
||||
order by c.conname",
|
||||
)
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
foreign_keys.len(),
|
||||
3,
|
||||
"workspace-scoped FKs must all exist and the applications plan FK must be absent"
|
||||
);
|
||||
for row in &foreign_keys {
|
||||
assert!(
|
||||
!row.get::<bool, _>("condeferrable"),
|
||||
"v14 plan FKs must be immediate, not deferrable"
|
||||
);
|
||||
assert!(
|
||||
!row.get::<bool, _>("condeferred"),
|
||||
"v14 plan FKs must start immediate"
|
||||
);
|
||||
assert_eq!(
|
||||
row.get::<String, _>("delete_rule"),
|
||||
"c",
|
||||
"only workspace-cascading FKs may remain"
|
||||
);
|
||||
}
|
||||
let plan_fk_absent: bool = sqlx::query_scalar(
|
||||
"select not exists (
|
||||
select 1 from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and c.conname = 'import_plan_applications_plan_fk'
|
||||
)",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
plan_fk_absent,
|
||||
"replay evidence must not be pinned to the plan row"
|
||||
);
|
||||
let unique: bool = sqlx::query_scalar(
|
||||
"select exists (
|
||||
select 1 from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = 'import_jobs'
|
||||
and c.conname = 'import_jobs_workspace_id_unique'
|
||||
and c.contype = 'u'
|
||||
)",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
unique,
|
||||
"workspace-scoped import job identity must be unique"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn healthy_v13_upgrades_to_v14_without_changing_prior_ledger() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v13_to_v14_import_plan").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
sqlx::query(
|
||||
"insert into workspaces
|
||||
(id, slug, display_name, status, settings_json, created_at, updated_at)
|
||||
values ('ws_v13_data', 'v13-data', 'V13 Data', 'active', '{}'::jsonb, $1, $1)",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(now)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"insert into import_jobs (
|
||||
id, workspace_id, kind, source_format, status, preview_payload, created_at, expires_at
|
||||
) values (
|
||||
'job_v13_data', 'ws_v13_data', 'openapi', 'openapi', 'ready',
|
||||
'{\"marker\":\"preserved\"}'::jsonb, $1, $1 + interval '1 hour'
|
||||
)",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(now)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
remove_v14_schema(&pool).await;
|
||||
let job_before: String = sqlx::query_scalar(
|
||||
"select preview_payload::text || status from import_jobs where id = 'job_v13_data'",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let prior = sqlx::query(
|
||||
"select version, name, checksum, phase, compatibility, applied_at
|
||||
from __crank_migrations where version <= 13 order by version",
|
||||
)
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
(
|
||||
row.get::<i64, _>("version"),
|
||||
row.get::<String, _>("name"),
|
||||
row.get::<String, _>("checksum"),
|
||||
row.get::<String, _>("phase"),
|
||||
row.get::<String, _>("compatibility"),
|
||||
row.get::<time::OffsetDateTime, _>("applied_at"),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(prior.len(), 13, "the prior ledger must cover v1..v13");
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 13,
|
||||
target: 15,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
let after = sqlx::query(
|
||||
"select version, name, checksum, phase, compatibility, applied_at
|
||||
from __crank_migrations where version <= 13 order by version",
|
||||
)
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
(
|
||||
row.get::<i64, _>("version"),
|
||||
row.get::<String, _>("name"),
|
||||
row.get::<String, _>("checksum"),
|
||||
row.get::<String, _>("phase"),
|
||||
row.get::<String, _>("compatibility"),
|
||||
row.get::<time::OffsetDateTime, _>("applied_at"),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
after, prior,
|
||||
"prior ledger must survive the v13 -> v14 upgrade"
|
||||
);
|
||||
let job_after: String = sqlx::query_scalar(
|
||||
"select preview_payload::text || status from import_jobs where id = 'job_v13_data'",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
job_after, job_before,
|
||||
"existing import jobs must be untouched by the upgrade"
|
||||
);
|
||||
let objects: i64 = count_rows(
|
||||
&pool,
|
||||
sqlx::AssertSqlSafe(String::from(
|
||||
"select count(*) from information_schema.tables
|
||||
where table_schema = current_schema()
|
||||
and table_name in ('import_plans', 'import_plan_applications')",
|
||||
)),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(objects, 2, "both v14 objects must exist after the upgrade");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wrong_workspace_foreign_key_is_rejected_immediately() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v14_wrong_workspace").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
let mut transaction = pool.begin().await.unwrap();
|
||||
for (workspace, label) in [("ws_job_owner", "job-owner"), ("ws_intruder", "intruder")] {
|
||||
sqlx::query(
|
||||
"insert into workspaces
|
||||
(id, slug, display_name, status, settings_json, created_at, updated_at)
|
||||
values ($1, $2, $2, 'active', '{}'::jsonb, $3, $3)",
|
||||
)
|
||||
.bind(workspace)
|
||||
.bind(label)
|
||||
.bind(now)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
sqlx::query(
|
||||
"insert into import_jobs (
|
||||
id, workspace_id, kind, source_format, status, preview_payload, created_at, expires_at
|
||||
) values (
|
||||
'job_owned', 'ws_job_owner', 'openapi', 'openapi', 'ready',
|
||||
'{}'::jsonb, $1, $1 + interval '1 hour'
|
||||
)",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(now)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.unwrap();
|
||||
let digest = "ab".repeat(32);
|
||||
let error = sqlx::query(
|
||||
"insert into import_plans (
|
||||
workspace_id, id, job_id, digest, payload, created_at, expires_at
|
||||
) values (
|
||||
'ws_intruder', 'plan_cross_workspace', 'job_owned', $1, '{}'::jsonb, $2,
|
||||
$2 + interval '1 hour'
|
||||
)",
|
||||
)
|
||||
.bind(&digest)
|
||||
.bind(now)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.expect_err("a plan may not bind a job from another workspace");
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("violates foreign key constraint"),
|
||||
"wrong-workspace reference must fail the job FK: {}",
|
||||
error
|
||||
);
|
||||
transaction.rollback().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn update_guards_reject_plan_and_application_mutations() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v14_immutable").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
seed_import_plan_fixture(&pool).await;
|
||||
for statement in [
|
||||
"update import_plans set expires_at = expires_at + interval '1 hour' where id = 'plan_v14'",
|
||||
"update import_plan_applications
|
||||
set report = report || jsonb_build_object('tampered', true)
|
||||
where idempotency_key = 'idem_v14'",
|
||||
] {
|
||||
let error = sqlx::query(statement)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect_err("import plan rows must be immutable");
|
||||
assert!(
|
||||
error.to_string().contains("import plan rows are immutable"),
|
||||
"statement '{}' must hit the immutability guard: {}",
|
||||
statement,
|
||||
error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deletion_cascades_to_plans_but_preserves_application_anchor() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v14_deletion_retention").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
seed_import_plan_fixture(&pool).await;
|
||||
|
||||
// Deleting the plan succeeds: application rows are replay evidence, not
|
||||
// dependents. The anchor must keep its full replay data.
|
||||
let mut transaction = pool.begin().await.unwrap();
|
||||
sqlx::query("delete from import_plans where id = 'plan_v14'")
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.unwrap();
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.expect("plan deletion must not be blocked by the application row");
|
||||
let application_count = count_rows(&pool, count_sql("import_plan_applications")).await;
|
||||
assert_eq!(
|
||||
application_count, 1,
|
||||
"application must remain as replay evidence after plan deletion"
|
||||
);
|
||||
|
||||
// Re-create the plan anchored to its job, then delete the expired job:
|
||||
// the cascade must take the plan with it while the anchor survives.
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
let digest = "ab".repeat(32);
|
||||
sqlx::query(
|
||||
"insert into import_plans (
|
||||
workspace_id, id, job_id, digest, payload, created_at, expires_at
|
||||
) values (
|
||||
'ws_import_plan', 'plan_v14', 'job_v14', $1, '{}'::jsonb, $2, $2 + interval '1 hour'
|
||||
)",
|
||||
)
|
||||
.bind(&digest)
|
||||
.bind(now)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut transaction = pool.begin().await.unwrap();
|
||||
sqlx::query("delete from import_jobs where id = 'job_v14'")
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.unwrap();
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.expect("job deletion must cascade to its plan, not be blocked by it");
|
||||
assert_eq!(
|
||||
count_rows(&pool, count_sql("import_jobs")).await,
|
||||
0,
|
||||
"the expired job must be gone"
|
||||
);
|
||||
assert_eq!(
|
||||
count_rows(&pool, count_sql("import_plans")).await,
|
||||
0,
|
||||
"the plan must cascade with its job"
|
||||
);
|
||||
// The anchor row survives both deletions and is still replayable data.
|
||||
let anchor = sqlx::query(
|
||||
"select idempotency_key, plan_id, plan_digest, report
|
||||
from import_plan_applications where workspace_id = 'ws_import_plan'",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("the application anchor must survive job and plan deletion");
|
||||
assert_eq!(
|
||||
anchor.try_get::<String, _>("idempotency_key").unwrap(),
|
||||
"idem_v14",
|
||||
"the idempotency identity must survive for replay"
|
||||
);
|
||||
assert_eq!(
|
||||
anchor.try_get::<String, _>("plan_id").unwrap(),
|
||||
"plan_v14",
|
||||
"the stored plan_id stays a history string, not an FK"
|
||||
);
|
||||
assert_eq!(anchor.try_get::<String, _>("plan_digest").unwrap(), digest);
|
||||
let report = anchor.try_get::<serde_json::Value, _>("report").unwrap();
|
||||
assert!(report.is_object(), "the report must stay valid jsonb");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn workspace_deletion_cascades_to_jobs_plans_and_applications() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v14_workspace_cascade").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
seed_import_plan_fixture(&pool).await;
|
||||
let mut transaction = pool.begin().await.unwrap();
|
||||
sqlx::query("delete from workspaces where id = 'ws_import_plan'")
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.unwrap();
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.expect("workspace deletion must succeed after the cascades");
|
||||
for table in ["import_jobs", "import_plans", "import_plan_applications"] {
|
||||
let count = count_rows(&pool, count_sql(table)).await;
|
||||
assert_eq!(count, 0, "{table} rows must cascade with the workspace");
|
||||
}
|
||||
}
|
||||
@@ -88,7 +88,7 @@ async fn published_ledgerless_baseline_upgrades_without_data_loss() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 13,
|
||||
target: 15,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -101,7 +101,7 @@ async fn published_ledgerless_baseline_upgrades_without_data_loss() {
|
||||
assert_eq!(operation_count, 1);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 13 }
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -194,7 +194,7 @@ async fn published_ledgerless_historical_column_layout_upgrades_without_data_los
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 13,
|
||||
target: 15,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -230,7 +230,7 @@ async fn published_ledgerless_historical_column_layout_upgrades_without_data_los
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 13 }
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -262,7 +262,7 @@ async fn published_initial_mcp_layout_is_accepted() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 13,
|
||||
target: 15,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -280,7 +280,7 @@ async fn published_initial_mcp_layout_is_accepted() {
|
||||
assert!(supports_elicitation);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 13 }
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -314,13 +314,13 @@ async fn published_in_place_mcp_upgrade_layout_is_accepted() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 13,
|
||||
target: 15,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 13 }
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn partial_sequence_fails_closed() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_partial_sequence").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
sqlx::query("delete from __crank_migrations where version = 1")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.code(),
|
||||
"partial_sequence"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn missing_relation_with_current_ledger_fails_closed() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_missing_relation").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
sqlx::query("drop table usage_rollups")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence");
|
||||
assert_eq!(error.stage(), "preflight.schema");
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn unregistered_legacy_extension_provenance_is_rejected() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_legacy_extension").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
sqlx::query("drop table __crank_migrations, __crank_migration_legacy_audit")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let checksum = "a".repeat(64);
|
||||
sqlx::query(
|
||||
"insert into __crank_ext_migrations (extension_name, version, checksum)
|
||||
values ('known-extension', 1, $1)",
|
||||
)
|
||||
.bind(&checksum)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::apply(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "legacy_conflict");
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn any_owned_relation_without_core_ledger_is_partial() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_owned_partial").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
sqlx::query("create table users (id text primary key)")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence");
|
||||
assert_eq!(error.stage(), "preflight.core_missing");
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn empty_core_ledger_is_reported_separately() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_empty_core_ledger").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
sqlx::query("delete from __crank_core_migrations")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence");
|
||||
assert_eq!(error.stage(), "preflight.core_cardinality");
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn current_ledger_with_structural_drift_fails_closed() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_structural_drift").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
sqlx::query("alter table mcp_transport_sessions drop column supports_elicitation")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence");
|
||||
assert_eq!(error.stage(), "preflight.schema");
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn tampered_legacy_audit_fails_closed() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_tampered_audit").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
sqlx::query(
|
||||
"update __crank_migration_legacy_audit set source_checksum = 'tampered' where source = 'core'",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "legacy_conflict");
|
||||
}
|
||||
@@ -63,7 +63,7 @@ async fn failed_artifact_metadata_migration_rolls_back_schema_and_ledger() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 11,
|
||||
target: 13,
|
||||
target: 15,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,13 +9,20 @@ use crank_core::{
|
||||
};
|
||||
use crank_registry::{
|
||||
CreateAgentRequest, CreateInvocationLogRequest, CreatePlatformApiKeyRequest,
|
||||
CreateWorkspaceRequest, OnboardingPresentationMilestone, PublishAgentRequest, PublishRequest,
|
||||
RecordOnboardingMilestoneRequest,
|
||||
CreateVersionRequest, CreateWorkspaceRequest, OnboardingPresentationMilestone,
|
||||
PublishAgentRequest, PublishRequest, RecordOnboardingMilestoneRequest,
|
||||
RegisterOnboardingImportContextRequest, RegistryError, SelectOnboardingImportDraftRequest,
|
||||
};
|
||||
use serde_json::json;
|
||||
use sqlx::Row;
|
||||
use time::{Duration, OffsetDateTime};
|
||||
|
||||
#[path = "onboarding_import_concurrency.rs"]
|
||||
mod onboarding_import_concurrency;
|
||||
#[path = "onboarding_import_contract.rs"]
|
||||
mod onboarding_import_contract;
|
||||
#[path = "onboarding_import_selection.rs"]
|
||||
mod onboarding_import_selection;
|
||||
#[path = "onboarding_lifecycle.rs"]
|
||||
mod onboarding_lifecycle;
|
||||
|
||||
|
||||
@@ -0,0 +1,395 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use super::onboarding_import_selection::{
|
||||
context_count_for, event_count, insert_import_application, selected_version,
|
||||
};
|
||||
use super::*;
|
||||
|
||||
/// A concurrent archive of the exact pending candidate must never be selected.
|
||||
///
|
||||
/// The blocker holds the candidate's `operations` row lock while the selection
|
||||
/// reads its snapshot and blocks on the same row lock; the archive then commits
|
||||
/// before the selection updates durable state. With only `READ COMMITTED` and a
|
||||
/// lock-free validation the selection would record a drifted, archived
|
||||
/// operation; the selection must instead abort (whole-transaction retry) and
|
||||
/// surface a stale-revision or unavailable conflict without mutation.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn concurrent_archive_vs_select_rejects_without_mutation() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let pool = database.raw_pool().await;
|
||||
let observer = database.raw_pool().await;
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
|
||||
let operation = test_operation("op_conc_archive", 1, OperationStatus::Draft);
|
||||
registry
|
||||
.create_operation(&workspace_id, &operation, None)
|
||||
.await
|
||||
.unwrap();
|
||||
insert_import_application(
|
||||
&pool,
|
||||
"ws_default",
|
||||
"idem_conc_archive",
|
||||
&[(
|
||||
"candidate",
|
||||
"createLead",
|
||||
"created",
|
||||
"op_conc_archive",
|
||||
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_conc_archive",
|
||||
plan_digest: &"b".repeat(64),
|
||||
expected_revision: initial.revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Hold the exact candidate row lock in an independent transaction.
|
||||
let mut blocker = pool.begin().await.unwrap();
|
||||
let blocker_pid: i32 = sqlx::query_scalar("select pg_backend_pid()")
|
||||
.fetch_one(&mut *blocker)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("select id from operations where workspace_id = $1 and id = $2 for update")
|
||||
.bind("ws_default")
|
||||
.bind("op_conc_archive")
|
||||
.fetch_one(&mut *blocker)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let select_registry = registry.clone();
|
||||
let select_workspace = workspace_id.clone();
|
||||
let select_task = tokio::spawn(async move {
|
||||
select_registry
|
||||
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
|
||||
workspace_id: &select_workspace,
|
||||
application_idempotency_key: "idem_conc_archive",
|
||||
plan_digest: &"b".repeat(64),
|
||||
operation_id: &crank_core::OperationId::new("op_conc_archive"),
|
||||
operation_version: 1,
|
||||
expected_revision: registered.revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
});
|
||||
|
||||
// Observe the in-flight selection waiting on the exact blocker.
|
||||
if select_task.is_finished() {
|
||||
panic!(
|
||||
"selection finished before the blocker: {:?}",
|
||||
select_task.await.unwrap()
|
||||
);
|
||||
}
|
||||
wait_for_blocked_reader(&observer, blocker_pid).await;
|
||||
sqlx::query(
|
||||
"update operations set status = 'archived', updated_at = now()
|
||||
where workspace_id = 'ws_default' and id = 'op_conc_archive'",
|
||||
)
|
||||
.execute(&mut *blocker)
|
||||
.await
|
||||
.unwrap();
|
||||
blocker.commit().await.unwrap();
|
||||
|
||||
let error = select_task
|
||||
.await
|
||||
.unwrap()
|
||||
.expect_err("an archived pending candidate must never be selected");
|
||||
assert!(
|
||||
matches!(
|
||||
error,
|
||||
RegistryError::OnboardingStaleRevision
|
||||
| RegistryError::OnboardingImportDraftUnavailable
|
||||
),
|
||||
"unexpected selection error: {error:?}"
|
||||
);
|
||||
assert_eq!(selected_version(&pool).await, None);
|
||||
assert_eq!(context_count_for(&pool, "ws_default").await, 1);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
/// A concurrent version edit of the exact pending candidate must never be
|
||||
/// selected with the stale version.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn concurrent_version_edit_vs_select_rejects_without_mutation() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let pool = database.raw_pool().await;
|
||||
let observer = database.raw_pool().await;
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
|
||||
let operation = test_operation("op_conc_edit", 1, OperationStatus::Draft);
|
||||
registry
|
||||
.create_operation(&workspace_id, &operation, None)
|
||||
.await
|
||||
.unwrap();
|
||||
insert_import_application(
|
||||
&pool,
|
||||
"ws_default",
|
||||
"idem_conc_edit",
|
||||
&[(
|
||||
"candidate",
|
||||
"createLead",
|
||||
"created",
|
||||
"op_conc_edit",
|
||||
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_conc_edit",
|
||||
plan_digest: &"b".repeat(64),
|
||||
expected_revision: initial.revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut blocker = pool.begin().await.unwrap();
|
||||
let blocker_pid: i32 = sqlx::query_scalar("select pg_backend_pid()")
|
||||
.fetch_one(&mut *blocker)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("select id from operations where workspace_id = $1 and id = $2 for update")
|
||||
.bind("ws_default")
|
||||
.bind("op_conc_edit")
|
||||
.fetch_one(&mut *blocker)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let select_registry = registry.clone();
|
||||
let select_workspace = workspace_id.clone();
|
||||
let select_task = tokio::spawn(async move {
|
||||
select_registry
|
||||
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
|
||||
workspace_id: &select_workspace,
|
||||
application_idempotency_key: "idem_conc_edit",
|
||||
plan_digest: &"b".repeat(64),
|
||||
operation_id: &crank_core::OperationId::new("op_conc_edit"),
|
||||
operation_version: 1,
|
||||
expected_revision: registered.revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
});
|
||||
|
||||
if select_task.is_finished() {
|
||||
panic!(
|
||||
"selection finished before the blocker: {:?}",
|
||||
select_task.await.unwrap()
|
||||
);
|
||||
}
|
||||
wait_for_blocked_reader(&observer, blocker_pid).await;
|
||||
sqlx::query(
|
||||
"update operations set current_draft_version = 2, updated_at = now()
|
||||
where workspace_id = 'ws_default' and id = 'op_conc_edit'",
|
||||
)
|
||||
.execute(&mut *blocker)
|
||||
.await
|
||||
.unwrap();
|
||||
blocker.commit().await.unwrap();
|
||||
|
||||
let error = select_task
|
||||
.await
|
||||
.unwrap()
|
||||
.expect_err("a drifted pending candidate version must never be selected");
|
||||
assert!(
|
||||
matches!(
|
||||
error,
|
||||
RegistryError::OnboardingStaleRevision
|
||||
| RegistryError::OnboardingImportDraftUnavailable
|
||||
),
|
||||
"unexpected selection error: {error:?}"
|
||||
);
|
||||
assert_eq!(selected_version(&pool).await, None);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
/// Concurrent first observations must enter the server-owned cohort exactly
|
||||
/// once without aborting, and every caller must observe the same authoritative
|
||||
/// `eligible_since`.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn concurrent_first_eligibility_is_single_and_consistent() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let pool = database.raw_pool().await;
|
||||
|
||||
let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(9));
|
||||
let mut tasks = Vec::new();
|
||||
for index in 0..8 {
|
||||
// Legacy connect() deliberately has one connection per registry.
|
||||
// Independent pools and a barrier make these transactions overlap.
|
||||
let registry = if index == 0 {
|
||||
registry.clone()
|
||||
} else {
|
||||
database.registry().await
|
||||
};
|
||||
let ready = barrier.clone();
|
||||
tasks.push(tokio::spawn(async move {
|
||||
ready.wait().await;
|
||||
registry
|
||||
.ensure_onboarding_eligibility(
|
||||
&WorkspaceId::new("ws_default"),
|
||||
OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
}));
|
||||
}
|
||||
barrier.wait().await;
|
||||
let mut eligible_since = None;
|
||||
for task in tasks {
|
||||
let projection = task
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("concurrent first observation must not abort");
|
||||
let since = projection
|
||||
.eligible_since
|
||||
.expect("every observer must see the server-owned cohort");
|
||||
match &eligible_since {
|
||||
None => eligible_since = Some(since),
|
||||
Some(existing) => assert_eq!(existing, &since),
|
||||
}
|
||||
}
|
||||
assert_eq!(event_count(&pool, "onboarding_eligible").await, 1);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
/// A snapshot must always pair its projection revision with matching import
|
||||
/// choices, even while the only candidate is concurrently archived.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn concurrent_archive_never_pairs_stale_revision_with_newer_choices() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let pool = database.raw_pool().await;
|
||||
let observer = database.raw_pool().await;
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
|
||||
let operation = test_operation("op_conc_snapshot", 1, OperationStatus::Draft);
|
||||
registry
|
||||
.create_operation(&workspace_id, &operation, None)
|
||||
.await
|
||||
.unwrap();
|
||||
insert_import_application(
|
||||
&pool,
|
||||
"ws_default",
|
||||
"idem_conc_snapshot",
|
||||
&[(
|
||||
"candidate",
|
||||
"createLead",
|
||||
"created",
|
||||
"op_conc_snapshot",
|
||||
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_conc_snapshot",
|
||||
plan_digest: &"b".repeat(64),
|
||||
expected_revision: initial.revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let draft_revision = registered.revision;
|
||||
|
||||
// The projection reads the old catalog before its context read waits on
|
||||
// the immutable application. No report mutation or production test hook.
|
||||
let mut blocker = pool.begin().await.unwrap();
|
||||
let blocker_pid: i32 = sqlx::query_scalar("select pg_backend_pid()")
|
||||
.fetch_one(&mut *blocker)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"select idempotency_key from import_plan_applications
|
||||
where workspace_id = $1 and idempotency_key = $2 for update",
|
||||
)
|
||||
.bind("ws_default")
|
||||
.bind("idem_conc_snapshot")
|
||||
.fetch_one(&mut *blocker)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let reader = registry.clone();
|
||||
let reader_workspace = workspace_id.clone();
|
||||
let read_task = tokio::spawn(async move {
|
||||
reader
|
||||
.get_onboarding_snapshot(&reader_workspace)
|
||||
.await
|
||||
.unwrap()
|
||||
});
|
||||
wait_for_blocked_reader(&observer, blocker_pid).await;
|
||||
sqlx::query(
|
||||
"update operations set status = 'archived', updated_at = now()
|
||||
where workspace_id = 'ws_default' and id = 'op_conc_snapshot'",
|
||||
)
|
||||
.execute(&mut *blocker)
|
||||
.await
|
||||
.unwrap();
|
||||
blocker.commit().await.unwrap();
|
||||
|
||||
let snapshot = read_task.await.unwrap();
|
||||
assert_eq!(
|
||||
snapshot.projection.revision, draft_revision,
|
||||
"the projection was read before the concurrent commit"
|
||||
);
|
||||
let context = snapshot.import_context.expect("the context must survive");
|
||||
assert!(
|
||||
context.choices[0].selectable,
|
||||
"choices must use the same old snapshot as the revision"
|
||||
);
|
||||
let current = registry
|
||||
.get_onboarding_snapshot(&workspace_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_ne!(current.projection.revision, draft_revision);
|
||||
assert!(!current.import_context.unwrap().choices[0].selectable);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
/// Wait for an observed database lock, never assume a task started after a sleep.
|
||||
async fn wait_for_blocked_reader(pool: &sqlx::PgPool, blocker_pid: i32) {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let blocked: bool = sqlx::query_scalar(
|
||||
"select exists(select 1 from pg_stat_activity
|
||||
where datname = current_database() and pid <> $1
|
||||
and $1 = any(pg_blocking_pids(pid)))",
|
||||
)
|
||||
.bind(blocker_pid)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
if blocked {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("the reader must contend on blocker {blocker_pid}"));
|
||||
}
|
||||
@@ -0,0 +1,785 @@
|
||||
#![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(®istry, "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(®istry, "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(®istry, &unrelated.id, "agent_anchor_b", "pk_anchor_b")
|
||||
.await;
|
||||
record_onboarding_call(
|
||||
®istry,
|
||||
&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(®istry, &selected.id, "agent_anchor_a", "pk_anchor_a")
|
||||
.await;
|
||||
// A second unrelated call cannot replace the chosen path or complete it.
|
||||
record_onboarding_call(
|
||||
®istry,
|
||||
&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(
|
||||
®istry,
|
||||
&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()
|
||||
}
|
||||
@@ -0,0 +1,731 @@
|
||||
use super::*;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[tokio::test]
|
||||
async fn import_context_registration_is_revision_guarded_pending_and_recovers_report() {
|
||||
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_pending", 1, OperationStatus::Draft);
|
||||
registry
|
||||
.create_operation(&workspace_id, &operation, None)
|
||||
.await
|
||||
.unwrap();
|
||||
insert_import_application(
|
||||
&pool,
|
||||
"ws_default",
|
||||
"idem_pending",
|
||||
&[
|
||||
(
|
||||
"candidate_create",
|
||||
"createLead",
|
||||
"created",
|
||||
"op_import_pending",
|
||||
Some(1),
|
||||
),
|
||||
("candidate_skip", "skipMe", "skipped", "", None),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
|
||||
let initial = registry
|
||||
.get_onboarding_projection(&workspace_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
initial.operation_id,
|
||||
Some(operation.id.clone()),
|
||||
"without an import context the generic projection auto-selects the draft"
|
||||
);
|
||||
|
||||
// A forged application identity has no committed immutable apply report.
|
||||
assert!(matches!(
|
||||
registry
|
||||
.register_onboarding_import_context(RegisterOnboardingImportContextRequest {
|
||||
workspace_id: &workspace_id,
|
||||
application_idempotency_key: "idem_missing",
|
||||
plan_digest: &"b".repeat(64),
|
||||
expected_revision: initial.revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap_err(),
|
||||
RegistryError::OnboardingImportApplicationUnavailable
|
||||
));
|
||||
assert_eq!(context_count(&pool).await, 0);
|
||||
|
||||
// A mismatched plan digest is rejected without mutation.
|
||||
assert!(matches!(
|
||||
registry
|
||||
.register_onboarding_import_context(RegisterOnboardingImportContextRequest {
|
||||
workspace_id: &workspace_id,
|
||||
application_idempotency_key: "idem_pending",
|
||||
plan_digest: &"d".repeat(64),
|
||||
expected_revision: initial.revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap_err(),
|
||||
RegistryError::OnboardingImportApplicationUnavailable
|
||||
));
|
||||
assert_eq!(context_count(&pool).await, 0);
|
||||
|
||||
// Stale revision cannot register a context.
|
||||
assert!(matches!(
|
||||
registry
|
||||
.register_onboarding_import_context(RegisterOnboardingImportContextRequest {
|
||||
workspace_id: &workspace_id,
|
||||
application_idempotency_key: "idem_pending",
|
||||
plan_digest: &"b".repeat(64),
|
||||
expected_revision: initial.revision + 1,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap_err(),
|
||||
RegistryError::OnboardingStaleRevision
|
||||
));
|
||||
assert_eq!(context_count(&pool).await, 0);
|
||||
|
||||
// A valid registration stores a pending context and suppresses the
|
||||
// generic automatic Operation selection.
|
||||
let registered = registry
|
||||
.register_onboarding_import_context(RegisterOnboardingImportContextRequest {
|
||||
workspace_id: &workspace_id,
|
||||
application_idempotency_key: "idem_pending",
|
||||
plan_digest: &"b".repeat(64),
|
||||
expected_revision: initial.revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(registered.operation_id, None);
|
||||
assert_eq!(event_count(&pool, "onboarding_import_eligible").await, 1);
|
||||
|
||||
// Recovery re-reads the immutable report and all outcome choices.
|
||||
let context = registry
|
||||
.get_onboarding_import_context(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("pending import context must be recoverable");
|
||||
assert!(context.selected_operation_id.is_none());
|
||||
assert_eq!(context.plan_digest, "b".repeat(64));
|
||||
assert_eq!(
|
||||
context.report.get("schema_version").and_then(Value::as_str),
|
||||
Some("import-plan-apply-report-v1")
|
||||
);
|
||||
let created = context
|
||||
.choices
|
||||
.iter()
|
||||
.find(|choice| choice.outcome == "created")
|
||||
.expect("created choice");
|
||||
assert!(created.selectable);
|
||||
assert_eq!(created.operation_id.as_deref(), Some("op_import_pending"));
|
||||
let skipped = context
|
||||
.choices
|
||||
.iter()
|
||||
.find(|choice| choice.outcome == "skipped")
|
||||
.expect("skipped choice");
|
||||
assert!(
|
||||
!skipped.selectable,
|
||||
"blocked outcomes stay visible but not selectable"
|
||||
);
|
||||
|
||||
// Exact re-registration is idempotent and keeps the single durable row.
|
||||
let again = registry
|
||||
.register_onboarding_import_context(RegisterOnboardingImportContextRequest {
|
||||
workspace_id: &workspace_id,
|
||||
application_idempotency_key: "idem_pending",
|
||||
plan_digest: &"b".repeat(64),
|
||||
expected_revision: registered.revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(again.operation_id, None);
|
||||
assert_eq!(context_count(&pool).await, 1);
|
||||
assert_eq!(event_count(&pool, "onboarding_import_eligible").await, 1);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn import_selection_requires_exact_successful_outcome_and_live_draft() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let pool = database.raw_pool().await;
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
|
||||
let anchor = test_operation("op_import_anchor", 1, OperationStatus::Draft);
|
||||
registry
|
||||
.create_operation(&workspace_id, &anchor, None)
|
||||
.await
|
||||
.unwrap();
|
||||
let later = test_operation("op_import_later", 1, OperationStatus::Draft);
|
||||
registry
|
||||
.create_operation(&workspace_id, &later, None)
|
||||
.await
|
||||
.unwrap();
|
||||
insert_import_application(
|
||||
&pool,
|
||||
"ws_default",
|
||||
"idem_select",
|
||||
&[
|
||||
(
|
||||
"candidate_anchor",
|
||||
"createLead",
|
||||
"created",
|
||||
"op_import_anchor",
|
||||
Some(1),
|
||||
),
|
||||
(
|
||||
"candidate_later",
|
||||
"createTask",
|
||||
"created",
|
||||
"op_import_later",
|
||||
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_select",
|
||||
plan_digest: &"b".repeat(64),
|
||||
expected_revision: initial.revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let pending = registry
|
||||
.get_onboarding_projection(&workspace_id)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Wrong application identity cannot select against this context.
|
||||
assert!(matches!(
|
||||
registry
|
||||
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
|
||||
workspace_id: &workspace_id,
|
||||
application_idempotency_key: "idem_other",
|
||||
plan_digest: &"b".repeat(64),
|
||||
operation_id: &anchor.id,
|
||||
operation_version: 1,
|
||||
expected_revision: pending.revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap_err(),
|
||||
RegistryError::OnboardingImportContextUnavailable
|
||||
));
|
||||
|
||||
// A forged operation that is not a successful outcome of the report.
|
||||
assert!(matches!(
|
||||
registry
|
||||
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
|
||||
workspace_id: &workspace_id,
|
||||
application_idempotency_key: "idem_select",
|
||||
plan_digest: &"b".repeat(64),
|
||||
operation_id: &crank_core::OperationId::new("op_forged"),
|
||||
operation_version: 1,
|
||||
expected_revision: pending.revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap_err(),
|
||||
RegistryError::OnboardingImportDraftUnavailable
|
||||
));
|
||||
|
||||
// A version drift from the exact successful outcome is rejected.
|
||||
assert!(matches!(
|
||||
registry
|
||||
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
|
||||
workspace_id: &workspace_id,
|
||||
application_idempotency_key: "idem_select",
|
||||
plan_digest: &"b".repeat(64),
|
||||
operation_id: &anchor.id,
|
||||
operation_version: 7,
|
||||
expected_revision: pending.revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap_err(),
|
||||
RegistryError::OnboardingImportDraftUnavailable
|
||||
));
|
||||
assert_eq!(selected_version(&pool).await, None);
|
||||
|
||||
// A foreign workspace with no registered context cannot claim it.
|
||||
create_workspace(®istry, "ws_import_other", "import-other").await;
|
||||
let other = WorkspaceId::new("ws_import_other");
|
||||
let other_revision = registry
|
||||
.get_onboarding_projection(&other)
|
||||
.await
|
||||
.unwrap()
|
||||
.revision;
|
||||
assert!(matches!(
|
||||
registry
|
||||
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
|
||||
workspace_id: &other,
|
||||
application_idempotency_key: "idem_select",
|
||||
plan_digest: &"b".repeat(64),
|
||||
operation_id: &anchor.id,
|
||||
operation_version: 1,
|
||||
expected_revision: other_revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap_err(),
|
||||
RegistryError::OnboardingImportContextUnavailable
|
||||
));
|
||||
assert_eq!(selected_version(&pool).await, None);
|
||||
|
||||
// A valid selection anchors the exact Draft version.
|
||||
let selected = registry
|
||||
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
|
||||
workspace_id: &workspace_id,
|
||||
application_idempotency_key: "idem_select",
|
||||
plan_digest: &"b".repeat(64),
|
||||
operation_id: &anchor.id,
|
||||
operation_version: 1,
|
||||
expected_revision: pending.revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(selected.operation_id, Some(anchor.id.clone()));
|
||||
assert_eq!(selected_version(&pool).await, Some(1));
|
||||
|
||||
// A second, otherwise eligible import Draft must not replace the explicit
|
||||
// target.
|
||||
let anchored = registry
|
||||
.get_onboarding_projection(&workspace_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(anchored.operation_id, Some(anchor.id.clone()));
|
||||
|
||||
// A new Draft version of the selected operation is surfaced as drift, not
|
||||
// silently rebound.
|
||||
let snapshot = test_operation("op_import_anchor", 2, OperationStatus::Draft);
|
||||
registry
|
||||
.create_version(CreateVersionRequest {
|
||||
workspace_id: &workspace_id,
|
||||
snapshot: &snapshot,
|
||||
change_note: None,
|
||||
created_by: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let drifted = registry
|
||||
.get_onboarding_projection(&workspace_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(drifted.operation_id, Some(anchor.id.clone()));
|
||||
assert_eq!(
|
||||
selected_version(&pool).await,
|
||||
Some(1),
|
||||
"the anchored import version must not drift with a new Draft"
|
||||
);
|
||||
let context = registry
|
||||
.get_onboarding_import_context(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
context.drift.as_ref().map(|drift| drift.reason.as_str()),
|
||||
Some("selected_operation_version_drift")
|
||||
);
|
||||
|
||||
// Reset clears the durable import context but keeps the evidence boundary.
|
||||
let _ = registry
|
||||
.reset_onboarding_selection(&workspace_id, drifted.revision, OffsetDateTime::now_utc())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(context_count(&pool).await, 0);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn import_funnel_milestones_require_exact_public_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 operation = test_operation("op_import_funnel", 1, OperationStatus::Draft);
|
||||
registry
|
||||
.create_operation(&workspace_id, &operation, None)
|
||||
.await
|
||||
.unwrap();
|
||||
insert_import_application(
|
||||
&pool,
|
||||
"ws_default",
|
||||
"idem_funnel",
|
||||
&[(
|
||||
"candidate",
|
||||
"createLead",
|
||||
"created",
|
||||
"op_import_funnel",
|
||||
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_funnel",
|
||||
plan_digest: &"b".repeat(64),
|
||||
expected_revision: initial.revision,
|
||||
occurred_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(event_count(&pool, "onboarding_import_eligible").await, 1);
|
||||
assert_eq!(event_count(&pool, "onboarding_import_published").await, 0);
|
||||
assert_eq!(event_count(&pool, "onboarding_agent_activated").await, 0);
|
||||
|
||||
let selected = registry
|
||||
.select_onboarding_import_draft(SelectOnboardingImportDraftRequest {
|
||||
workspace_id: &workspace_id,
|
||||
application_idempotency_key: "idem_funnel",
|
||||
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()));
|
||||
|
||||
// Publish the exact selected operation/version.
|
||||
let published_at = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &workspace_id,
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &published_at,
|
||||
published_by: Some("onboarding-funnel-test"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
event_count(&pool, "onboarding_import_published").await,
|
||||
1,
|
||||
"publishing the explicitly selected version materializes its funnel event immediately"
|
||||
);
|
||||
let (agent_id, key_id) = attach_published_agent_and_key(
|
||||
®istry,
|
||||
&operation.id,
|
||||
"agent_import_funnel",
|
||||
"pk_import_funnel",
|
||||
)
|
||||
.await;
|
||||
// Agent publication alone must not activate the funnel milestone.
|
||||
registry
|
||||
.ensure_onboarding_eligibility(&workspace_id, OffsetDateTime::now_utc())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(event_count(&pool, "onboarding_import_published").await, 1);
|
||||
assert_eq!(
|
||||
event_count(&pool, "onboarding_agent_activated").await,
|
||||
0,
|
||||
"Agent publication without a public call is not activation"
|
||||
);
|
||||
|
||||
// The authoritative successful public first call on the exact selected
|
||||
// operation/version with its Agent/key binding activates the milestone.
|
||||
record_onboarding_test_and_call(
|
||||
®istry,
|
||||
&operation.id,
|
||||
&agent_id,
|
||||
&key_id,
|
||||
"import_funnel",
|
||||
OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await;
|
||||
let projection = registry
|
||||
.ensure_onboarding_eligibility(&workspace_id, OffsetDateTime::now_utc())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
projection.completed,
|
||||
"the selected import path must reach the authoritative terminal tuple"
|
||||
);
|
||||
assert_eq!(event_count(&pool, "onboarding_import_published").await, 1);
|
||||
assert_eq!(event_count(&pool, "onboarding_agent_activated").await, 1);
|
||||
|
||||
// The conversion milestones are anchored to authoritative evidence, not to
|
||||
// the observation time: publication uses the exact selected version's
|
||||
// `published_at`, activation uses the exact successful public first call.
|
||||
let published_event_at: OffsetDateTime = sqlx::query_scalar(
|
||||
"select occurred_at from product_events
|
||||
where workspace_id = 'ws_default' and event_name = 'onboarding_import_published'",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
published_event_at,
|
||||
super::truncate_to_micros(published_at),
|
||||
"import-published must inherit the exact selected version published_at"
|
||||
);
|
||||
let first_call_at = projection
|
||||
.first_call_at
|
||||
.expect("the completed projection carries the authoritative first call");
|
||||
let activated_event_at: OffsetDateTime = sqlx::query_scalar(
|
||||
"select occurred_at from product_events
|
||||
where workspace_id = 'ws_default' and event_name = 'onboarding_agent_activated'",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
activated_event_at, first_call_at,
|
||||
"agent-activated must inherit the exact successful public first_call_at"
|
||||
);
|
||||
let properties: Vec<String> = sqlx::query_scalar(
|
||||
"select properties_json::text from product_events
|
||||
where workspace_id = $1 and event_name in (
|
||||
'onboarding_import_eligible', 'onboarding_import_published',
|
||||
'onboarding_agent_activated')",
|
||||
)
|
||||
.bind("ws_default")
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(properties.len(), 3);
|
||||
for value in properties {
|
||||
let stored: Value = serde_json::from_str(&value).unwrap();
|
||||
let object = stored
|
||||
.as_object()
|
||||
.expect("server event properties are bounded objects");
|
||||
let mut keys: Vec<&str> = object.keys().map(String::as_str).collect();
|
||||
keys.sort_unstable();
|
||||
assert_eq!(
|
||||
keys,
|
||||
["eligible", "eligible_since", "milestone"],
|
||||
"server-owned properties must never carry source bytes, credentials or actor IDs"
|
||||
);
|
||||
assert!(!value.contains("ws_default"));
|
||||
assert!(!value.contains("openapi:"));
|
||||
assert!(!value.contains("secret"));
|
||||
}
|
||||
|
||||
// Every funnel milestone inherits the authoritative eligible cohort; none
|
||||
// is appended with `eligible=null/false`.
|
||||
let cohort: Vec<(String, bool, Option<String>)> = sqlx::query_as(
|
||||
"select event_name,
|
||||
(properties_json ->> 'eligible')::boolean,
|
||||
properties_json ->> 'eligible_since'
|
||||
from product_events
|
||||
where workspace_id = $1 and event_name in (
|
||||
'onboarding_import_eligible', 'onboarding_import_published',
|
||||
'onboarding_agent_activated')
|
||||
order by event_name",
|
||||
)
|
||||
.bind("ws_default")
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(cohort.len(), 3);
|
||||
let eligible_since = cohort
|
||||
.iter()
|
||||
.find(|(name, _, _)| name == "onboarding_import_eligible")
|
||||
.and_then(|(_, _, since)| since.clone())
|
||||
.expect("eligibility denominator has eligible_since");
|
||||
for (name, eligible, since) in &cohort {
|
||||
assert!(*eligible, "{name} must inherit eligible=true");
|
||||
assert_eq!(
|
||||
since.as_deref(),
|
||||
Some(eligible_since.as_str()),
|
||||
"{name} must inherit the authoritative eligible_since"
|
||||
);
|
||||
}
|
||||
|
||||
let rolled_up: i64 = sqlx::query_scalar(
|
||||
"select events_total from product_event_daily_rollups
|
||||
where workspace_id = $1 and event_name = 'onboarding_import_published'",
|
||||
)
|
||||
.bind("ws_default")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rolled_up, 1);
|
||||
// The rollup day follows the authoritative evidence day, so a publication
|
||||
// observed later still rolls up on its exact published_at date.
|
||||
let rollup_day: String = sqlx::query_scalar(
|
||||
"select day::text from product_event_daily_rollups
|
||||
where workspace_id = $1 and event_name = 'onboarding_import_published'",
|
||||
)
|
||||
.bind("ws_default")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rollup_day, published_at.date().to_string());
|
||||
|
||||
// Re-observing the projection is idempotent: milestones stay single.
|
||||
registry
|
||||
.ensure_onboarding_eligibility(&workspace_id, OffsetDateTime::now_utc())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(event_count(&pool, "onboarding_import_eligible").await, 1);
|
||||
assert_eq!(event_count(&pool, "onboarding_import_published").await, 1);
|
||||
assert_eq!(event_count(&pool, "onboarding_agent_activated").await, 1);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
pub(super) async fn attach_published_agent_and_key(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
operation_id: &crank_core::OperationId,
|
||||
agent_id: &str,
|
||||
key_id: &str,
|
||||
) -> (crank_core::AgentId, PlatformApiKeyId) {
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let agent = test_agent(agent_id, AgentStatus::Draft);
|
||||
let version = test_agent_version(&agent.id, 1, AgentStatus::Draft);
|
||||
let bindings = vec![AgentOperationBinding {
|
||||
operation_id: operation_id.clone(),
|
||||
operation_version: 1,
|
||||
tool_name: "create_lead".to_owned(),
|
||||
tool_title: "Create lead".to_owned(),
|
||||
tool_description_override: None,
|
||||
enabled: true,
|
||||
}];
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &agent,
|
||||
version: &version,
|
||||
bindings: &bindings,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id,
|
||||
agent_id: &agent.id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("onboarding-funnel-test"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let key_id = PlatformApiKeyId::new(key_id);
|
||||
let key = PlatformApiKey {
|
||||
id: key_id.clone(),
|
||||
workspace_id,
|
||||
agent_id: Some(agent.id.clone()),
|
||||
key_kind: PlatformApiKeyKind::McpClient,
|
||||
name: format!("onboarding-{key_id}-key"),
|
||||
prefix: format!("crk_{}", key_id.as_str()),
|
||||
scopes: vec![PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||
status: PlatformApiKeyStatus::Active,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
last_used_at: None,
|
||||
expires_at: None,
|
||||
allowed_origins: Vec::new(),
|
||||
};
|
||||
registry
|
||||
.create_platform_api_key(CreatePlatformApiKeyRequest {
|
||||
api_key: &key,
|
||||
secret_hash: "funnel-secret-hash",
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
(agent.id, key_id)
|
||||
}
|
||||
|
||||
async fn context_count(pool: &sqlx::PgPool) -> i64 {
|
||||
context_count_for(pool, "ws_default").await
|
||||
}
|
||||
|
||||
pub(super) async fn context_count_for(pool: &sqlx::PgPool, workspace_id: &str) -> i64 {
|
||||
sqlx::query_scalar("select count(*) from onboarding_import_selections where workspace_id = $1")
|
||||
.bind(workspace_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub(super) async fn selected_version(pool: &sqlx::PgPool) -> Option<i32> {
|
||||
sqlx::query_scalar(
|
||||
"select selected_operation_version from onboarding_import_selections where workspace_id = 'ws_default'",
|
||||
)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
pub(super) async fn event_count(pool: &sqlx::PgPool, event_name: &str) -> i64 {
|
||||
sqlx::query_scalar(
|
||||
"select count(*) from product_events where workspace_id = 'ws_default' and event_name = $1",
|
||||
)
|
||||
.bind(event_name)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub(super) type OutcomeSpec<'a> = (&'a str, &'a str, &'a str, &'a str, Option<u32>);
|
||||
|
||||
pub(super) async fn insert_import_application(
|
||||
pool: &sqlx::PgPool,
|
||||
workspace_id: &str,
|
||||
idempotency_key: &str,
|
||||
outcomes: &[OutcomeSpec<'_>],
|
||||
) {
|
||||
let outcomes = outcomes
|
||||
.iter()
|
||||
.map(|(key, name, outcome, operation_id, version)| {
|
||||
json!({
|
||||
"key": key,
|
||||
"name": name,
|
||||
"outcome": outcome,
|
||||
"operation_id": if operation_id.is_empty() { Value::Null } else { Value::String((*operation_id).to_owned()) },
|
||||
"version": version,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let report = json!({
|
||||
"schema_version": "import-plan-apply-report-v1",
|
||||
"status": "applied",
|
||||
"plan_id": "plan_import",
|
||||
"plan_digest": "b".repeat(64),
|
||||
"job_id": "job_import",
|
||||
"idempotency_key": idempotency_key,
|
||||
"source_id": "source_import",
|
||||
"source_digest": "c".repeat(64),
|
||||
"dependencies": [],
|
||||
"counts": {"created": 1, "versioned": 0, "renamed": 0, "skipped": 0, "excluded": 0, "rejected": 0},
|
||||
"outcomes": outcomes,
|
||||
"summary": "import applied",
|
||||
"recovery": "none",
|
||||
"applied_at": "2026-10-03T00:00:00Z",
|
||||
});
|
||||
sqlx::query(
|
||||
"insert into import_plan_applications (
|
||||
workspace_id, idempotency_key, plan_id, plan_digest, report, created_at
|
||||
) values ($1, $2, 'plan_import', $3, $4, now())",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(idempotency_key)
|
||||
.bind("b".repeat(64))
|
||||
.bind(report)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
Reference in new issue
Block a user