CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 21m42s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
Durable worker приостанавливает Task как input_required до dispatch, если закреплённая схема требует отсутствующее поле; authorized schema-validated update атомарно и с аудитом возобновляет тот же Task ровно один раз. Replay/conflict/TTL безопасны, ожидание удерживает admission permit. Additive schema v30: task_input_requests, fingerprint/version, TTL-индекс.
887 lines
35 KiB
Rust
887 lines
35 KiB
Rust
use super::*;
|
||
use sqlx::Row;
|
||
use std::collections::HashMap;
|
||
|
||
mod dependent_source_fks;
|
||
mod exhaustive_v12;
|
||
|
||
#[tokio::test]
|
||
async fn healthy_v11_upgrades_to_v13_without_rewriting_prior_ledger() {
|
||
let database_url = crank_test_support::postgres_schema_url("test_v11_to_v12_artifacts").await;
|
||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||
MigrationAuthority::apply(&pool).await.unwrap();
|
||
let prior = sqlx::query(
|
||
"select version, name, checksum, applied_at
|
||
from __crank_migrations where version <= 11 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::<time::OffsetDateTime, _>("applied_at"),
|
||
)
|
||
})
|
||
.collect::<Vec<_>>();
|
||
remove_v12_schema(&pool).await;
|
||
assert_eq!(
|
||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||
MigrationPreflight::MigrationRequired {
|
||
current: 11,
|
||
target: 30,
|
||
}
|
||
);
|
||
|
||
MigrationAuthority::apply(&pool).await.unwrap();
|
||
let after = sqlx::query(
|
||
"select version, name, checksum, applied_at
|
||
from __crank_migrations where version <= 11 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::<time::OffsetDateTime, _>("applied_at"),
|
||
)
|
||
})
|
||
.collect::<Vec<_>>();
|
||
assert_eq!(after, prior);
|
||
|
||
let v13_applied_at: time::OffsetDateTime =
|
||
sqlx::query_scalar("select applied_at from __crank_migrations where version = 13")
|
||
.fetch_one(&pool)
|
||
.await
|
||
.unwrap();
|
||
MigrationAuthority::apply(&pool).await.unwrap();
|
||
let replayed_at: time::OffsetDateTime =
|
||
sqlx::query_scalar("select applied_at from __crank_migrations where version = 13")
|
||
.fetch_one(&pool)
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(replayed_at, v13_applied_at);
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn v12_guard_still_rejects_column_constraint_index_and_relation_drift() {
|
||
let database_url = crank_test_support::postgres_schema_url("test_v12_artifact_drift").await;
|
||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||
MigrationAuthority::apply(&pool).await.unwrap();
|
||
|
||
for (drift, restore) in [
|
||
(
|
||
"alter table artifact_blobs add column unexpected text null;",
|
||
"alter table artifact_blobs drop column unexpected;",
|
||
),
|
||
(
|
||
"create index unrelated_idx on artifact_sources(source_id) include (mime_type);",
|
||
"drop index unrelated_idx;",
|
||
),
|
||
(
|
||
"alter table artifact_blobs alter column storage_lifecycle set default 'unavailable';",
|
||
"alter table artifact_blobs alter column storage_lifecycle set default 'available';",
|
||
),
|
||
(
|
||
"alter table artifact_sources alter column mime_type drop not null;",
|
||
"alter table artifact_sources alter column mime_type set not null;",
|
||
),
|
||
(
|
||
"alter table artifact_blobs drop constraint artifact_blobs_size_check;
|
||
alter table artifact_blobs add constraint artifact_blobs_size_check
|
||
check (size_bytes between 1 and 262145);",
|
||
"alter table artifact_blobs drop constraint artifact_blobs_size_check;
|
||
alter table artifact_blobs add constraint artifact_blobs_size_check
|
||
check (size_bytes between 1 and 262144);",
|
||
),
|
||
(
|
||
"drop index artifact_sources_workspace_created_idx;
|
||
create index artifact_sources_workspace_created_idx
|
||
on artifact_sources(workspace_id, source_id, created_at);",
|
||
"drop index artifact_sources_workspace_created_idx;
|
||
create index artifact_sources_workspace_created_idx
|
||
on artifact_sources(workspace_id, created_at, source_id);",
|
||
),
|
||
(
|
||
"alter table artifact_sources alter column created_at type timestamptz(3);",
|
||
"alter table artifact_sources alter column created_at type timestamptz;",
|
||
),
|
||
(
|
||
"alter table artifact_sources enable row level security;",
|
||
"alter table artifact_sources disable row level security;",
|
||
),
|
||
(
|
||
"create policy unexpected_policy on artifact_sources using (true);",
|
||
"drop policy unexpected_policy on artifact_sources;",
|
||
),
|
||
(
|
||
"create function unrelated_trigger_fn() returns trigger language plpgsql as $$
|
||
begin return new; end
|
||
$$;
|
||
create trigger unexpected_trigger before insert on artifact_sources
|
||
for each row execute function unrelated_trigger_fn();",
|
||
"drop trigger unexpected_trigger on artifact_sources;
|
||
drop function unrelated_trigger_fn();",
|
||
),
|
||
(
|
||
// V16 добавил `resource_versions_source_fkey`, а V17 —
|
||
// `resource_publications_source_fkey`: обе logged-таблицы ссылаются на
|
||
// `artifact_sources`, поэтому PostgreSQL больше не переводит её в unlogged
|
||
// (`42P16`). Тот же класс дрейфа (persistence отношения, его проверяет
|
||
// `schema_guard_v12`) снимает блокирующие ссылки на время дрейфа и
|
||
// возвращает их при восстановлении.
|
||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||
alter table resource_publications drop constraint resource_publications_source_fkey;
|
||
alter table artifact_sources set unlogged;",
|
||
"alter table artifact_sources set logged;
|
||
alter table resource_versions add constraint resource_versions_source_fkey
|
||
foreign key (workspace_id, artifact_source_id)
|
||
references artifact_sources(workspace_id, source_id);
|
||
alter table resource_publications add constraint resource_publications_source_fkey
|
||
foreign key (workspace_id, artifact_source_id)
|
||
references artifact_sources(workspace_id, source_id);",
|
||
),
|
||
(
|
||
"alter table artifact_sources drop constraint artifact_sources_id_check;
|
||
alter table artifact_sources add constraint artifact_sources_id_check
|
||
check (source_id ~ '^src_[a-zA-Z0-9_-]{1,128}$');",
|
||
"alter table artifact_sources drop constraint artifact_sources_id_check;
|
||
alter table artifact_sources add constraint artifact_sources_id_check
|
||
check (source_id ~ '^src_[A-Za-z0-9_-]{1,128}$');",
|
||
),
|
||
(
|
||
"alter table artifact_blobs drop constraint artifact_blobs_claim_shape_check;
|
||
alter table artifact_blobs add constraint artifact_blobs_claim_shape_check check (
|
||
claim_token is null and
|
||
(claim_expires_at is null or claim_token is not null) and
|
||
claim_expires_at is not null
|
||
);",
|
||
"alter table artifact_blobs drop constraint artifact_blobs_claim_shape_check;
|
||
alter table artifact_blobs add constraint artifact_blobs_claim_shape_check check (
|
||
(claim_token is null and claim_expires_at is null)
|
||
or (claim_token is not null and claim_expires_at is not null)
|
||
);",
|
||
),
|
||
] {
|
||
sqlx::raw_sql(drift).execute(&pool).await.unwrap();
|
||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||
assert_eq!(error.code(), "partial_sequence", "drift: {drift}");
|
||
assert_eq!(error.version(), Some(12), "drift: {drift}");
|
||
sqlx::raw_sql(restore).execute(&pool).await.unwrap();
|
||
assert_eq!(
|
||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||
MigrationPreflight::Current { version: 30 },
|
||
"restore: {restore}"
|
||
);
|
||
}
|
||
|
||
sqlx::query("alter table artifact_sources rename to artifact_sources_table")
|
||
.execute(&pool)
|
||
.await
|
||
.unwrap();
|
||
sqlx::query("create view artifact_sources as select * from artifact_sources_table")
|
||
.execute(&pool)
|
||
.await
|
||
.unwrap();
|
||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||
assert_eq!(error.code(), "partial_sequence");
|
||
assert_eq!(error.version(), Some(12));
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn v13_guard_rejects_wrong_cleanup_index_order_and_predicate() {
|
||
let database_url =
|
||
crank_test_support::postgres_schema_url("test_v13_cleanup_index_drift").await;
|
||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||
MigrationAuthority::apply(&pool).await.unwrap();
|
||
|
||
for (drift, restore) in [
|
||
(
|
||
"drop index artifact_sources_blob_lifecycle_detached_idx;
|
||
create index artifact_sources_blob_lifecycle_detached_idx
|
||
on artifact_sources(lifecycle, blob_digest, detached_at);",
|
||
"drop index artifact_sources_blob_lifecycle_detached_idx;
|
||
create index artifact_sources_blob_lifecycle_detached_idx
|
||
on artifact_sources(blob_digest, lifecycle, detached_at);",
|
||
),
|
||
(
|
||
"drop index artifact_sources_openapi_dangling_idx;
|
||
create index artifact_sources_openapi_dangling_idx
|
||
on artifact_sources(created_at, workspace_id, source_id)
|
||
where lifecycle = 'active';",
|
||
"drop index artifact_sources_openapi_dangling_idx;
|
||
create index artifact_sources_openapi_dangling_idx
|
||
on artifact_sources(created_at, workspace_id, source_id)
|
||
where lifecycle = 'active' and left(source_id, 12) = 'src_openapi_';",
|
||
),
|
||
] {
|
||
sqlx::raw_sql(drift).execute(&pool).await.unwrap();
|
||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||
assert_eq!(error.code(), "partial_sequence", "drift: {drift}");
|
||
assert_eq!(error.version(), Some(13), "drift: {drift}");
|
||
|
||
sqlx::raw_sql(restore).execute(&pool).await.unwrap();
|
||
assert_eq!(
|
||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||
MigrationPreflight::Current { version: 30 },
|
||
"restore: {restore}"
|
||
);
|
||
}
|
||
}
|
||
|
||
const V12_BLOB_COLUMNS: &[&str] = &[
|
||
"digest",
|
||
"artifact_ref",
|
||
"size_bytes",
|
||
"storage_lifecycle",
|
||
"claim_token",
|
||
"claim_expires_at",
|
||
"created_at",
|
||
"updated_at",
|
||
];
|
||
const V12_SOURCE_COLUMNS: &[&str] = &[
|
||
"workspace_id",
|
||
"source_id",
|
||
"blob_digest",
|
||
"mime_type",
|
||
"sensitivity",
|
||
"lifecycle",
|
||
"created_at",
|
||
"updated_at",
|
||
"detached_at",
|
||
];
|
||
const V12_BLOB_DEFAULTS: &[(&str, Option<&str>)] = &[
|
||
("digest", None),
|
||
("artifact_ref", None),
|
||
("size_bytes", None),
|
||
("storage_lifecycle", Some("'available'::text")),
|
||
("claim_token", None),
|
||
("claim_expires_at", None),
|
||
("created_at", None),
|
||
("updated_at", None),
|
||
];
|
||
const V12_SOURCE_DEFAULTS: &[(&str, Option<&str>)] = &[
|
||
("workspace_id", None),
|
||
("source_id", None),
|
||
("blob_digest", None),
|
||
("mime_type", None),
|
||
("sensitivity", None),
|
||
("lifecycle", Some("'active'::text")),
|
||
("created_at", None),
|
||
("updated_at", None),
|
||
("detached_at", None),
|
||
];
|
||
// PostgreSQL normalizes `set default null` into "no default", so each column
|
||
// that legitimately has no default needs a concrete typed expression to prove
|
||
// the guard rejects a newly introduced default.
|
||
const V12_BLOB_NO_DEFAULT_DRIFT: &[(&str, &str)] = &[
|
||
("digest", "'crank_drift'::text"),
|
||
("artifact_ref", "'crank_drift'::text"),
|
||
("size_bytes", "1"),
|
||
("claim_token", "'crank_drift'::text"),
|
||
("claim_expires_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||
("created_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||
("updated_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||
];
|
||
const V12_SOURCE_NO_DEFAULT_DRIFT: &[(&str, &str)] = &[
|
||
("workspace_id", "'crank_drift'::text"),
|
||
("source_id", "'crank_drift'::text"),
|
||
("blob_digest", "'crank_drift'::text"),
|
||
("mime_type", "'crank_drift'::text"),
|
||
("sensitivity", "'crank_drift'::text"),
|
||
("created_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||
("updated_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||
("detached_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||
];
|
||
const V12_BLOB_CONSTRAINTS: &[&str] = &[
|
||
"artifact_blobs_artifact_ref_key",
|
||
"artifact_blobs_claim_shape_check",
|
||
"artifact_blobs_claim_token_check",
|
||
"artifact_blobs_digest_check",
|
||
"artifact_blobs_lifecycle_check",
|
||
"artifact_blobs_pkey",
|
||
"artifact_blobs_ref_check",
|
||
"artifact_blobs_size_check",
|
||
"artifact_blobs_timestamps_check",
|
||
];
|
||
const V12_SOURCE_CONSTRAINTS: &[&str] = &[
|
||
"artifact_sources_blob_digest_fkey",
|
||
"artifact_sources_id_check",
|
||
"artifact_sources_lifecycle_check",
|
||
"artifact_sources_mime_type_check",
|
||
"artifact_sources_pkey",
|
||
"artifact_sources_sensitivity_check",
|
||
"artifact_sources_state_check",
|
||
"artifact_sources_timestamps_check",
|
||
"artifact_sources_workspace_id_fkey",
|
||
];
|
||
const V12_OWNED_RELATIONS: &[(&str, &str)] = &[
|
||
("artifact_blobs", "r"),
|
||
("artifact_blobs_artifact_ref_key", "i"),
|
||
("artifact_blobs_expired_claim_idx", "i"),
|
||
("artifact_blobs_pkey", "i"),
|
||
("artifact_sources", "r"),
|
||
("artifact_sources_blob_lifecycle_detached_idx", "i"),
|
||
("artifact_sources_openapi_dangling_idx", "i"),
|
||
("artifact_sources_pkey", "i"),
|
||
("artifact_sources_workspace_created_idx", "i"),
|
||
];
|
||
|
||
fn owned_names(values: &[&str]) -> Vec<String> {
|
||
values.iter().map(|value| (*value).to_owned()).collect()
|
||
}
|
||
|
||
fn owned_defaults(values: &[(&str, Option<&str>)]) -> Vec<(String, Option<String>)> {
|
||
values
|
||
.iter()
|
||
.map(|(name, default)| ((*name).to_owned(), default.map(str::to_owned)))
|
||
.collect()
|
||
}
|
||
|
||
async fn catalog_columns(pool: &sqlx::PgPool, table: &str) -> Vec<String> {
|
||
sqlx::query(
|
||
"select column_name
|
||
from information_schema.columns
|
||
where table_schema = current_schema() and table_name = $1
|
||
order by ordinal_position",
|
||
)
|
||
.bind(table)
|
||
.fetch_all(pool)
|
||
.await
|
||
.unwrap()
|
||
.into_iter()
|
||
.map(|row| row.get::<String, _>("column_name"))
|
||
.collect()
|
||
}
|
||
|
||
async fn catalog_column_defaults(
|
||
pool: &sqlx::PgPool,
|
||
table: &str,
|
||
) -> Vec<(String, Option<String>)> {
|
||
sqlx::query(
|
||
"select column_name, column_default
|
||
from information_schema.columns
|
||
where table_schema = current_schema() and table_name = $1
|
||
order by ordinal_position",
|
||
)
|
||
.bind(table)
|
||
.fetch_all(pool)
|
||
.await
|
||
.unwrap()
|
||
.into_iter()
|
||
.map(|row| {
|
||
(
|
||
row.get::<String, _>("column_name"),
|
||
row.get::<Option<String>, _>("column_default"),
|
||
)
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
async fn catalog_constraints(pool: &sqlx::PgPool, table: &str) -> Vec<String> {
|
||
sqlx::query(
|
||
"select c.conname
|
||
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 = $1
|
||
order by c.conname",
|
||
)
|
||
.bind(table)
|
||
.fetch_all(pool)
|
||
.await
|
||
.unwrap()
|
||
.into_iter()
|
||
.map(|row| row.get::<String, _>("conname"))
|
||
.collect()
|
||
}
|
||
|
||
async fn catalog_indexes(pool: &sqlx::PgPool) -> Vec<String> {
|
||
sqlx::query(
|
||
"select idx.relname
|
||
from pg_catalog.pg_index i
|
||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||
join pg_catalog.pg_class t on t.oid = i.indrelid
|
||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||
where n.nspname = current_schema()
|
||
and t.relname in ('artifact_blobs', 'artifact_sources')
|
||
order by idx.relname",
|
||
)
|
||
.fetch_all(pool)
|
||
.await
|
||
.unwrap()
|
||
.into_iter()
|
||
.map(|row| row.get::<String, _>("relname"))
|
||
.collect()
|
||
}
|
||
|
||
async fn catalog_owned_relations(pool: &sqlx::PgPool) -> Vec<(String, String)> {
|
||
sqlx::query(
|
||
r"select c.relname, c.relkind::text as relkind
|
||
from pg_catalog.pg_class c
|
||
join pg_catalog.pg_namespace n on n.oid = c.relnamespace
|
||
where n.nspname = current_schema()
|
||
and c.relname like 'artifact\_%' escape '\'
|
||
order by c.relname",
|
||
)
|
||
.fetch_all(pool)
|
||
.await
|
||
.unwrap()
|
||
.into_iter()
|
||
.map(|row| {
|
||
(
|
||
row.get::<String, _>("relname"),
|
||
row.get::<String, _>("relkind"),
|
||
)
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
async fn catalog_constraint_definitions(pool: &sqlx::PgPool) -> HashMap<String, String> {
|
||
sqlx::query(
|
||
"select c.conname, pg_get_constraintdef(c.oid, true) as definition
|
||
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 in ('artifact_blobs', 'artifact_sources')",
|
||
)
|
||
.fetch_all(pool)
|
||
.await
|
||
.unwrap()
|
||
.into_iter()
|
||
.map(|row| {
|
||
(
|
||
row.get::<String, _>("conname"),
|
||
row.get::<String, _>("definition"),
|
||
)
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// Определение constraint **указанного отношения** текущей схемы; `None`, если его нет.
|
||
///
|
||
/// Отношение обязательно параметром: без него одноимённый объект другой таблицы
|
||
/// (или другой схемы) мог бы молча подменить результат, а «однозначность» —
|
||
/// это проверяемое свойство (R-C), а не предположение вызывающего.
|
||
async fn constraint_definition(pool: &sqlx::PgPool, relation: &str, name: &str) -> Option<String> {
|
||
let definitions = sqlx::query_scalar::<_, String>(
|
||
"select pg_get_constraintdef(c.oid, true)
|
||
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 = $1 and c.conname = $2",
|
||
)
|
||
.bind(relation)
|
||
.bind(name)
|
||
.fetch_all(pool)
|
||
.await
|
||
.expect("a constraint definition must be queryable");
|
||
assert!(
|
||
definitions.len() <= 1,
|
||
"constraint `{name}` on `{relation}` must resolve to exactly one definition, \
|
||
observed {}",
|
||
definitions.len()
|
||
);
|
||
definitions.into_iter().next()
|
||
}
|
||
|
||
async fn assert_v12_drift(pool: &sqlx::PgPool, drift: &str, restore: &str) {
|
||
sqlx::raw_sql(sqlx::AssertSqlSafe(drift.to_owned()))
|
||
.execute(pool)
|
||
.await
|
||
.unwrap();
|
||
let error = MigrationAuthority::preflight(pool).await.unwrap_err();
|
||
assert_eq!(error.code(), "partial_sequence", "drift: {drift}");
|
||
assert_eq!(error.version(), Some(12), "drift: {drift}");
|
||
sqlx::raw_sql(sqlx::AssertSqlSafe(restore.to_owned()))
|
||
.execute(pool)
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(
|
||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||
MigrationPreflight::Current { version: 30 },
|
||
"restore: {restore}"
|
||
);
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn v12_guard_rejects_exhaustive_catalog_drift_for_both_tables() {
|
||
let database_url = crank_test_support::postgres_schema_url("test_v12_exhaustive_drift").await;
|
||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||
MigrationAuthority::apply(&pool).await.unwrap();
|
||
|
||
// Fixed catalog snapshots. These are hard assertions over the complete
|
||
// matrix, so a disappeared object fails the test instead of silently
|
||
// dropping out of the drift loop below.
|
||
assert_eq!(
|
||
catalog_columns(&pool, "artifact_blobs").await,
|
||
owned_names(V12_BLOB_COLUMNS)
|
||
);
|
||
assert_eq!(
|
||
catalog_columns(&pool, "artifact_sources").await,
|
||
owned_names(V12_SOURCE_COLUMNS)
|
||
);
|
||
assert_eq!(
|
||
V12_BLOB_COLUMNS.len() + V12_SOURCE_COLUMNS.len(),
|
||
17,
|
||
"the V12 column matrix is exactly seventeen columns"
|
||
);
|
||
assert_eq!(
|
||
catalog_column_defaults(&pool, "artifact_blobs").await,
|
||
owned_defaults(V12_BLOB_DEFAULTS)
|
||
);
|
||
assert_eq!(
|
||
catalog_column_defaults(&pool, "artifact_sources").await,
|
||
owned_defaults(V12_SOURCE_DEFAULTS)
|
||
);
|
||
assert_eq!(
|
||
V12_BLOB_DEFAULTS.len() + V12_SOURCE_DEFAULTS.len(),
|
||
17,
|
||
"the V12 default matrix is exactly seventeen columns"
|
||
);
|
||
assert_eq!(
|
||
V12_BLOB_DEFAULTS
|
||
.iter()
|
||
.chain(V12_SOURCE_DEFAULTS)
|
||
.filter(|(_, default)| default.is_none())
|
||
.count(),
|
||
15,
|
||
"fifteen V12 columns must declare no default"
|
||
);
|
||
assert_eq!(
|
||
catalog_constraints(&pool, "artifact_blobs").await,
|
||
owned_names(V12_BLOB_CONSTRAINTS)
|
||
);
|
||
assert_eq!(
|
||
catalog_constraints(&pool, "artifact_sources").await,
|
||
owned_names(V12_SOURCE_CONSTRAINTS)
|
||
);
|
||
assert_eq!(
|
||
V12_BLOB_CONSTRAINTS.len() + V12_SOURCE_CONSTRAINTS.len(),
|
||
18,
|
||
"the V12 constraint matrix is exactly eighteen constraints"
|
||
);
|
||
assert_eq!(
|
||
catalog_indexes(&pool).await,
|
||
owned_names(&[
|
||
"artifact_blobs_artifact_ref_key",
|
||
"artifact_blobs_expired_claim_idx",
|
||
"artifact_blobs_pkey",
|
||
"artifact_sources_blob_lifecycle_detached_idx",
|
||
"artifact_sources_openapi_dangling_idx",
|
||
"artifact_sources_pkey",
|
||
"artifact_sources_workspace_created_idx",
|
||
])
|
||
);
|
||
assert_eq!(
|
||
catalog_owned_relations(&pool).await,
|
||
V12_OWNED_RELATIONS
|
||
.iter()
|
||
.map(|(name, kind)| ((*name).to_owned(), (*kind).to_owned()))
|
||
.collect::<Vec<_>>()
|
||
);
|
||
|
||
// Every column of both tables: rename it away and restore the name.
|
||
for (table, column) in V12_BLOB_COLUMNS
|
||
.iter()
|
||
.map(|column| ("artifact_blobs", *column))
|
||
.chain(
|
||
V12_SOURCE_COLUMNS
|
||
.iter()
|
||
.map(|column| ("artifact_sources", *column)),
|
||
)
|
||
{
|
||
let drift = format!("alter table {table} rename column {column} to {column}_crank_drift;");
|
||
let restore =
|
||
format!("alter table {table} rename column {column}_crank_drift to {column};");
|
||
assert_v12_drift(&pool, &drift, &restore).await;
|
||
}
|
||
|
||
// Every column of both tables: change its type and restore the original,
|
||
// then toggle nullability and restore it. The primary-key members are a
|
||
// special case because PostgreSQL rejects dropping their NOT NULL while the
|
||
// key exists; that rejection is asserted and the nullable shape is reached
|
||
// through a dropped/restored primary key.
|
||
exhaustive_v12::assert_column_type_drift(&pool).await;
|
||
exhaustive_v12::assert_column_nullability_drift(&pool).await;
|
||
|
||
// Every declared default: swap in a different typed default, then restore.
|
||
for (table, column, replacement, original) in [
|
||
(
|
||
"artifact_blobs",
|
||
"storage_lifecycle",
|
||
"'unavailable'",
|
||
"'available'",
|
||
),
|
||
("artifact_sources", "lifecycle", "'detached'", "'active'"),
|
||
] {
|
||
let drift = format!("alter table {table} alter column {column} set default {replacement};");
|
||
let restore = format!("alter table {table} alter column {column} set default {original};");
|
||
assert_v12_drift(&pool, &drift, &restore).await;
|
||
}
|
||
|
||
// Every V12 column that declares no default: introduce a concrete typed
|
||
// default, prove the guard rejects it, then drop the default and prove the
|
||
// schema returns to Current. A bare `set default null` would be folded back
|
||
// into "no default" by PostgreSQL, so the drift list is fixed and compared
|
||
// against the default inventory to keep a missing field from dropping out.
|
||
assert_eq!(
|
||
V12_BLOB_NO_DEFAULT_DRIFT
|
||
.iter()
|
||
.map(|(column, _)| *column)
|
||
.collect::<Vec<_>>(),
|
||
V12_BLOB_DEFAULTS
|
||
.iter()
|
||
.filter(|(_, default)| default.is_none())
|
||
.map(|(column, _)| *column)
|
||
.collect::<Vec<_>>(),
|
||
"every defaultless artifact_blobs column must have a drift case"
|
||
);
|
||
assert_eq!(
|
||
V12_SOURCE_NO_DEFAULT_DRIFT
|
||
.iter()
|
||
.map(|(column, _)| *column)
|
||
.collect::<Vec<_>>(),
|
||
V12_SOURCE_DEFAULTS
|
||
.iter()
|
||
.filter(|(_, default)| default.is_none())
|
||
.map(|(column, _)| *column)
|
||
.collect::<Vec<_>>(),
|
||
"every defaultless artifact_sources column must have a drift case"
|
||
);
|
||
for (table, column, drift) in V12_BLOB_NO_DEFAULT_DRIFT
|
||
.iter()
|
||
.map(|(column, drift)| ("artifact_blobs", *column, *drift))
|
||
.chain(
|
||
V12_SOURCE_NO_DEFAULT_DRIFT
|
||
.iter()
|
||
.map(|(column, drift)| ("artifact_sources", *column, *drift)),
|
||
)
|
||
{
|
||
let set = format!("alter table {table} alter column {column} set default {drift};");
|
||
let restore = format!("alter table {table} alter column {column} drop default;");
|
||
assert_v12_drift(&pool, &set, &restore).await;
|
||
}
|
||
|
||
// Every constraint: drop it, then restore it from its own catalog
|
||
// definition. The foreign key that depends on the artifact_blobs primary
|
||
// key is dropped first and restored after it.
|
||
let definitions = catalog_constraint_definitions(&pool).await;
|
||
for (table, constraint) in V12_BLOB_CONSTRAINTS
|
||
.iter()
|
||
.map(|constraint| ("artifact_blobs", *constraint))
|
||
.chain(
|
||
V12_SOURCE_CONSTRAINTS
|
||
.iter()
|
||
.map(|constraint| ("artifact_sources", *constraint)),
|
||
)
|
||
{
|
||
let definition = definitions
|
||
.get(constraint)
|
||
.unwrap_or_else(|| panic!("missing definition for {constraint}"));
|
||
if constraint == "artifact_blobs_pkey" {
|
||
let fk = definitions
|
||
.get("artifact_sources_blob_digest_fkey")
|
||
.expect("the dependent foreign key definition must be captured");
|
||
let drift = "alter table artifact_sources drop constraint artifact_sources_blob_digest_fkey;\n\
|
||
alter table artifact_blobs drop constraint artifact_blobs_pkey;";
|
||
let restore = format!(
|
||
"alter table artifact_blobs add constraint artifact_blobs_pkey {definition};\n\
|
||
alter table artifact_sources add constraint artifact_sources_blob_digest_fkey {fk};"
|
||
);
|
||
assert_v12_drift(&pool, drift, &restore).await;
|
||
} else if constraint == "artifact_sources_pkey" {
|
||
// V16/V17 добавили `resource_versions_source_fkey` и
|
||
// `resource_publications_source_fkey`, которые физически опираются на
|
||
// pkey-индекс `artifact_sources_pkey`. Чтобы дрейф «constraint отсутствует»
|
||
// был исполнимым, блокирующие ссылки снимаются на время дрейфа и
|
||
// возвращаются при восстановлении — тот же приём, что для `artifact_blobs_pkey`.
|
||
let draft_dependent =
|
||
constraint_definition(&pool, "resource_versions", "resource_versions_source_fkey")
|
||
.await;
|
||
let publication_dependent = constraint_definition(
|
||
&pool,
|
||
"resource_publications",
|
||
"resource_publications_source_fkey",
|
||
)
|
||
.await;
|
||
let mut drift = String::new();
|
||
if draft_dependent.is_some() {
|
||
drift.push_str(
|
||
"alter table resource_versions drop constraint resource_versions_source_fkey;\n",
|
||
);
|
||
}
|
||
if publication_dependent.is_some() {
|
||
drift.push_str(
|
||
"alter table resource_publications drop constraint \
|
||
resource_publications_source_fkey;\n",
|
||
);
|
||
}
|
||
drift.push_str("alter table artifact_sources drop constraint artifact_sources_pkey;");
|
||
let mut restore = format!(
|
||
"alter table artifact_sources add constraint artifact_sources_pkey {definition};\n"
|
||
);
|
||
if let Some(definition_of_fk) = draft_dependent {
|
||
restore.push_str(&format!(
|
||
"alter table resource_versions add constraint resource_versions_source_fkey \
|
||
{definition_of_fk};\n"
|
||
));
|
||
}
|
||
if let Some(definition_of_fk) = publication_dependent {
|
||
restore.push_str(&format!(
|
||
"alter table resource_publications add constraint \
|
||
resource_publications_source_fkey {definition_of_fk};"
|
||
));
|
||
}
|
||
assert_v12_drift(&pool, &drift, &restore).await;
|
||
} else {
|
||
let drift = format!("alter table {table} drop constraint {constraint};");
|
||
let restore = format!("alter table {table} add constraint {constraint} {definition};");
|
||
assert_v12_drift(&pool, &drift, &restore).await;
|
||
}
|
||
}
|
||
|
||
// Every constraint again, this time keeping its name and `contype` while
|
||
// changing only its definition: same-name `check (true)`, foreign keys with
|
||
// a different delete action, and primary key/unique constraints with
|
||
// rewritten members. Each mutation must be rejected before the original
|
||
// captured definition is replayed.
|
||
exhaustive_v12::assert_constraint_definition_drift(&pool).await;
|
||
|
||
// The standalone V12 index: change its definition, then remove it.
|
||
let index_definition: String = sqlx::query_scalar(
|
||
"select pg_get_indexdef(i.indexrelid)
|
||
from pg_catalog.pg_index i
|
||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||
join pg_catalog.pg_namespace n on n.oid = idx.relnamespace
|
||
where n.nspname = current_schema()
|
||
and idx.relname = 'artifact_sources_workspace_created_idx'",
|
||
)
|
||
.fetch_one(&pool)
|
||
.await
|
||
.unwrap();
|
||
assert_v12_drift(
|
||
&pool,
|
||
"drop index artifact_sources_workspace_created_idx;
|
||
create index artifact_sources_workspace_created_idx
|
||
on artifact_sources(workspace_id, source_id, created_at);",
|
||
&format!("drop index artifact_sources_workspace_created_idx;\n{index_definition};"),
|
||
)
|
||
.await;
|
||
|
||
// Every standalone index must be rejected when removed and restorable from
|
||
// its own catalog definition. The V12 guard validates the whole expanded
|
||
// name set, so each removal is a version 12 partial sequence.
|
||
for index in [
|
||
"artifact_blobs_expired_claim_idx",
|
||
"artifact_sources_blob_lifecycle_detached_idx",
|
||
"artifact_sources_openapi_dangling_idx",
|
||
"artifact_sources_workspace_created_idx",
|
||
] {
|
||
let definition: String = sqlx::query_scalar(
|
||
"select pg_get_indexdef(i.indexrelid)
|
||
from pg_catalog.pg_index i
|
||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||
join pg_catalog.pg_namespace n on n.oid = idx.relnamespace
|
||
where n.nspname = current_schema()
|
||
and idx.relname = $1",
|
||
)
|
||
.bind(index)
|
||
.fetch_one(&pool)
|
||
.await
|
||
.unwrap();
|
||
assert_v12_drift(
|
||
&pool,
|
||
&format!("drop index {index};"),
|
||
&format!("{definition};"),
|
||
)
|
||
.await;
|
||
}
|
||
|
||
// Extra owned objects of every kind must be rejected by the exact inventory.
|
||
assert_v12_drift(
|
||
&pool,
|
||
"create table artifact_crank_drift_owned(id integer);",
|
||
"drop table artifact_crank_drift_owned;",
|
||
)
|
||
.await;
|
||
assert_v12_drift(
|
||
&pool,
|
||
"create index artifact_crank_drift_owned_idx on artifact_blobs(digest);",
|
||
"drop index artifact_crank_drift_owned_idx;",
|
||
)
|
||
.await;
|
||
assert_v12_drift(
|
||
&pool,
|
||
"create view artifact_crank_drift_owned_view as select digest from artifact_blobs;",
|
||
"drop view artifact_crank_drift_owned_view;",
|
||
)
|
||
.await;
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// P4 (V16 guard): шесть однофакторных мутаций определения и проверка выбора
|
||
// зависимого FK/created index по текущей схеме перенесены в подмодуль
|
||
// `artifact_metadata/exhaustive_v12.rs` — там же живёт разрешённый helper
|
||
// `dependent_source_fk_definition`, и health-правило ограничивает файл 1000 строками.
|
||
// ---------------------------------------------------------------------------
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// V17 guard (Story 3.7): минимальные однофакторные мутации схемы публикаций.
|
||
// ---------------------------------------------------------------------------
|
||
|
||
#[tokio::test]
|
||
async fn v17_guard_rejects_publication_schema_drift() {
|
||
let database_url = crank_test_support::postgres_schema_url("test_v17_guard_drift").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: 30 }
|
||
);
|
||
|
||
for (drift, restore) in [
|
||
(
|
||
"alter table resource_publications add column raw_upload_filename text;",
|
||
"alter table resource_publications drop column raw_upload_filename;",
|
||
),
|
||
(
|
||
"alter table resource_publications drop constraint resource_publications_sensitivity_check;\n\
|
||
alter table resource_publications add constraint resource_publications_sensitivity_check \
|
||
check (true);",
|
||
"alter table resource_publications drop constraint resource_publications_sensitivity_check;\n\
|
||
alter table resource_publications add constraint resource_publications_sensitivity_check \
|
||
check (sensitivity in ('public', 'internal', 'secret'));",
|
||
),
|
||
(
|
||
"alter table resource_publications drop constraint resource_publications_source_fkey;\n\
|
||
alter table resource_publications add constraint resource_publications_source_fkey \
|
||
foreign key (workspace_id, artifact_source_id) \
|
||
references artifact_sources(workspace_id, source_id) on delete cascade;",
|
||
"alter table resource_publications drop constraint resource_publications_source_fkey;\n\
|
||
alter table resource_publications add constraint resource_publications_source_fkey \
|
||
foreign key (workspace_id, artifact_source_id) \
|
||
references artifact_sources(workspace_id, source_id);",
|
||
),
|
||
] {
|
||
sqlx::raw_sql(drift).execute(&pool).await.unwrap();
|
||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||
assert_eq!(error.code(), "partial_sequence", "drift: {drift}");
|
||
assert_eq!(error.version(), Some(17), "drift: {drift}");
|
||
sqlx::raw_sql(restore).execute(&pool).await.unwrap();
|
||
assert_eq!(
|
||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||
MigrationPreflight::Current { version: 30 },
|
||
"restore: {restore}"
|
||
);
|
||
}
|
||
}
|