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-индекс.
971 lines
45 KiB
Rust
971 lines
45 KiB
Rust
//! Исчерпывающие проверки дрейфа схемы: V12 (типы/дефолты/nullability/определения
|
||
//! constraints и индексов двух artifact-таблиц) и V16 (шесть однофакторных мутаций
|
||
//! определения `resources`/`resource_versions` + выбор зависимого FK и created
|
||
//! index по текущей схеме).
|
||
//!
|
||
//! Модуль держит проверки V16 по текущей схеме; определения зависимых
|
||
//! FK-хелперов вынесены в `dependent_source_fks.rs`, чтобы оба файла оставались
|
||
//! в пределах health-лимита 1000 строк.
|
||
|
||
use crank_registry::{MigrationAuthority, MigrationPreflight};
|
||
|
||
use super::dependent_source_fks::{
|
||
dependent_publication_fk_definition, dependent_source_fk_definition,
|
||
};
|
||
|
||
// V12 changed-type coverage. Every column gets a reachable `alter column ...
|
||
// type` drift whose `information_schema.data_type` differs from the frozen
|
||
// guard expectation, plus the exact expression that puts the original type
|
||
// back. `character varying` is chosen for the text columns and `timestamp`
|
||
// for the timestamptz columns because both are binary-compatible rewrites:
|
||
// PostgreSQL applies them even while the primary key, unique, foreign key,
|
||
// default, check and index objects stay in place, so the guard rejection is
|
||
// genuinely caused by the type drift and not by a missing dependent object.
|
||
const COLUMN_TYPE_DRIFT: &[(&str, &str, &str, &str)] = &[
|
||
("artifact_blobs", "digest", "character varying", "text"),
|
||
(
|
||
"artifact_blobs",
|
||
"artifact_ref",
|
||
"character varying",
|
||
"text",
|
||
),
|
||
("artifact_blobs", "size_bytes", "integer", "bigint"),
|
||
(
|
||
"artifact_blobs",
|
||
"storage_lifecycle",
|
||
"character varying",
|
||
"text",
|
||
),
|
||
("artifact_blobs", "claim_token", "character varying", "text"),
|
||
(
|
||
"artifact_blobs",
|
||
"claim_expires_at",
|
||
"timestamp",
|
||
"timestamp with time zone",
|
||
),
|
||
(
|
||
"artifact_blobs",
|
||
"created_at",
|
||
"timestamp",
|
||
"timestamp with time zone",
|
||
),
|
||
(
|
||
"artifact_blobs",
|
||
"updated_at",
|
||
"timestamp",
|
||
"timestamp with time zone",
|
||
),
|
||
(
|
||
"artifact_sources",
|
||
"workspace_id",
|
||
"character varying",
|
||
"text",
|
||
),
|
||
("artifact_sources", "source_id", "character varying", "text"),
|
||
(
|
||
"artifact_sources",
|
||
"blob_digest",
|
||
"character varying",
|
||
"text",
|
||
),
|
||
("artifact_sources", "mime_type", "character varying", "text"),
|
||
(
|
||
"artifact_sources",
|
||
"sensitivity",
|
||
"character varying",
|
||
"text",
|
||
),
|
||
("artifact_sources", "lifecycle", "character varying", "text"),
|
||
(
|
||
"artifact_sources",
|
||
"created_at",
|
||
"timestamp",
|
||
"timestamp with time zone",
|
||
),
|
||
(
|
||
"artifact_sources",
|
||
"updated_at",
|
||
"timestamp",
|
||
"timestamp with time zone",
|
||
),
|
||
(
|
||
"artifact_sources",
|
||
"detached_at",
|
||
"timestamp",
|
||
"timestamp with time zone",
|
||
),
|
||
];
|
||
|
||
// Columns that legitimately carry `null` in V12. The remaining non-primary-key
|
||
// columns are `not null`, and the primary-key members cannot have `not null`
|
||
// dropped while the key exists.
|
||
const V12_NULLABLE_COLUMNS: &[(&str, &str)] = &[
|
||
("artifact_blobs", "claim_token"),
|
||
("artifact_blobs", "claim_expires_at"),
|
||
("artifact_sources", "detached_at"),
|
||
];
|
||
|
||
const V12_PRIMARY_KEY_COLUMNS: &[(&str, &str)] = &[
|
||
("artifact_blobs", "digest"),
|
||
("artifact_sources", "workspace_id"),
|
||
("artifact_sources", "source_id"),
|
||
];
|
||
|
||
// V12 changed-definition coverage. Each entry keeps the original constraint
|
||
// name and `pg_constraint.contype` and only changes the definition: every
|
||
// check becomes `check (true)`, both foreign keys change their delete action,
|
||
// and the primary key/unique members are rewritten while staying the same
|
||
// kind. The original definition is captured from the catalog and replayed to
|
||
// restore the exact prior shape.
|
||
const CONSTRAINT_DEFINITION_DRIFT: &[(&str, &str, &str)] = &[
|
||
(
|
||
"artifact_blobs",
|
||
"artifact_blobs_artifact_ref_key",
|
||
"unique (digest)",
|
||
),
|
||
(
|
||
"artifact_blobs",
|
||
"artifact_blobs_claim_shape_check",
|
||
"check (true)",
|
||
),
|
||
(
|
||
"artifact_blobs",
|
||
"artifact_blobs_claim_token_check",
|
||
"check (true)",
|
||
),
|
||
(
|
||
"artifact_blobs",
|
||
"artifact_blobs_digest_check",
|
||
"check (true)",
|
||
),
|
||
(
|
||
"artifact_blobs",
|
||
"artifact_blobs_lifecycle_check",
|
||
"check (true)",
|
||
),
|
||
(
|
||
"artifact_blobs",
|
||
"artifact_blobs_pkey",
|
||
"primary key (digest) include (artifact_ref)",
|
||
),
|
||
("artifact_blobs", "artifact_blobs_ref_check", "check (true)"),
|
||
(
|
||
"artifact_blobs",
|
||
"artifact_blobs_size_check",
|
||
"check (true)",
|
||
),
|
||
(
|
||
"artifact_blobs",
|
||
"artifact_blobs_timestamps_check",
|
||
"check (true)",
|
||
),
|
||
(
|
||
"artifact_sources",
|
||
"artifact_sources_blob_digest_fkey",
|
||
"foreign key (blob_digest) references artifact_blobs(digest) on delete cascade",
|
||
),
|
||
(
|
||
"artifact_sources",
|
||
"artifact_sources_id_check",
|
||
"check (true)",
|
||
),
|
||
(
|
||
"artifact_sources",
|
||
"artifact_sources_lifecycle_check",
|
||
"check (true)",
|
||
),
|
||
(
|
||
"artifact_sources",
|
||
"artifact_sources_mime_type_check",
|
||
"check (true)",
|
||
),
|
||
(
|
||
"artifact_sources",
|
||
"artifact_sources_pkey",
|
||
"primary key (source_id, workspace_id)",
|
||
),
|
||
(
|
||
"artifact_sources",
|
||
"artifact_sources_sensitivity_check",
|
||
"check (true)",
|
||
),
|
||
(
|
||
"artifact_sources",
|
||
"artifact_sources_state_check",
|
||
"check (true)",
|
||
),
|
||
(
|
||
"artifact_sources",
|
||
"artifact_sources_timestamps_check",
|
||
"check (true)",
|
||
),
|
||
(
|
||
"artifact_sources",
|
||
"artifact_sources_workspace_id_fkey",
|
||
"foreign key (workspace_id) references workspaces(id) on delete restrict",
|
||
),
|
||
];
|
||
|
||
async fn catalog_nullable(pool: &sqlx::PgPool, table: &str, column: &str) -> bool {
|
||
sqlx::query_scalar::<_, String>(
|
||
"select is_nullable
|
||
from information_schema.columns
|
||
where table_schema = current_schema() and table_name = $1 and column_name = $2",
|
||
)
|
||
.bind(table)
|
||
.bind(column)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap()
|
||
== "YES"
|
||
}
|
||
|
||
pub(super) async fn assert_column_type_drift(pool: &sqlx::PgPool) {
|
||
assert_eq!(
|
||
COLUMN_TYPE_DRIFT.len(),
|
||
17,
|
||
"every V12 column needs a changed-type drift case"
|
||
);
|
||
for (table, column, drift_type, restore_type) in COLUMN_TYPE_DRIFT {
|
||
let drift = format!("alter table {table} alter column {column} type {drift_type};");
|
||
let restore = format!("alter table {table} alter column {column} type {restore_type};");
|
||
super::assert_v12_drift(pool, &drift, &restore).await;
|
||
}
|
||
}
|
||
|
||
pub(super) async fn assert_column_nullability_drift(pool: &sqlx::PgPool) {
|
||
let mut covered = 0usize;
|
||
for (table, column) in super::V12_BLOB_COLUMNS
|
||
.iter()
|
||
.map(|column| ("artifact_blobs", *column))
|
||
.chain(
|
||
super::V12_SOURCE_COLUMNS
|
||
.iter()
|
||
.map(|column| ("artifact_sources", *column)),
|
||
)
|
||
{
|
||
covered += 1;
|
||
let nullable = catalog_nullable(pool, table, column).await;
|
||
let expected_nullable = V12_NULLABLE_COLUMNS.contains(&(table, column));
|
||
assert_eq!(
|
||
nullable, expected_nullable,
|
||
"nullability inventory drift for {table}.{column}"
|
||
);
|
||
if V12_PRIMARY_KEY_COLUMNS.contains(&(table, column)) {
|
||
assert_primary_key_nullability(pool, table, column).await;
|
||
} else if nullable {
|
||
let drift = format!("alter table {table} alter column {column} set not null;");
|
||
let restore = format!("alter table {table} alter column {column} drop not null;");
|
||
super::assert_v12_drift(pool, &drift, &restore).await;
|
||
} else {
|
||
let drift = format!("alter table {table} alter column {column} drop not null;");
|
||
let restore = format!("alter table {table} alter column {column} set not null;");
|
||
super::assert_v12_drift(pool, &drift, &restore).await;
|
||
}
|
||
}
|
||
assert_eq!(covered, 17, "every V12 column needs a nullability case");
|
||
assert_eq!(
|
||
V12_PRIMARY_KEY_COLUMNS.len() + V12_NULLABLE_COLUMNS.len(),
|
||
6,
|
||
"the V12 nullability exceptions are exactly the three primary-key members and three nullable columns"
|
||
);
|
||
}
|
||
|
||
// PostgreSQL refuses `drop not null` on a primary-key member outright, so this
|
||
// case cannot be reached with the key in place. The rejection is asserted
|
||
// explicitly instead of being skipped, then the nullable shape is reached by
|
||
// dropping the primary key (and the dependent foreign key for artifact_blobs),
|
||
// toggling nullability, and replaying the captured definitions in dependency
|
||
// order.
|
||
async fn assert_primary_key_nullability(pool: &sqlx::PgPool, table: &str, column: &str) {
|
||
let direct = format!("alter table {table} alter column {column} drop not null;");
|
||
let error = sqlx::raw_sql(sqlx::AssertSqlSafe(direct))
|
||
.execute(pool)
|
||
.await
|
||
.expect_err("PostgreSQL must reject dropping NOT NULL on a primary key member");
|
||
assert!(
|
||
error.to_string().contains("is in a primary key"),
|
||
"unexpected rejection for {table}.{column}: {error}"
|
||
);
|
||
assert_eq!(
|
||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||
MigrationPreflight::Current { version: 30 },
|
||
"a rejected primary-key nullability change must leave the schema current"
|
||
);
|
||
|
||
let definitions = super::catalog_constraint_definitions(pool).await;
|
||
let (drift, restore) = if table == "artifact_blobs" {
|
||
let pkey = definitions
|
||
.get("artifact_blobs_pkey")
|
||
.expect("artifact_blobs primary key definition must be captured");
|
||
let fk = definitions
|
||
.get("artifact_sources_blob_digest_fkey")
|
||
.expect("the foreign key that depends on artifact_blobs_pkey must be captured");
|
||
(
|
||
"alter table artifact_sources drop constraint artifact_sources_blob_digest_fkey;\n\
|
||
alter table artifact_blobs drop constraint artifact_blobs_pkey;\n\
|
||
alter table artifact_blobs alter column digest drop not null;"
|
||
.to_owned(),
|
||
format!(
|
||
"alter table artifact_blobs alter column digest set not null;\n\
|
||
alter table artifact_blobs add constraint artifact_blobs_pkey {pkey};\n\
|
||
alter table artifact_sources add constraint artifact_sources_blob_digest_fkey {fk};"
|
||
),
|
||
)
|
||
} else {
|
||
let pkey = definitions
|
||
.get("artifact_sources_pkey")
|
||
.expect("artifact_sources primary key definition must be captured");
|
||
let fk = dependent_source_fk_definition(pool).await;
|
||
let publication_fk = dependent_publication_fk_definition(pool).await;
|
||
(
|
||
format!(
|
||
"alter table resource_versions drop constraint resource_versions_source_fkey;\n\
|
||
alter table resource_publications drop constraint resource_publications_source_fkey;\n\
|
||
alter table artifact_sources drop constraint artifact_sources_pkey;\n\
|
||
alter table artifact_sources alter column {column} drop not null;"
|
||
),
|
||
format!(
|
||
"alter table artifact_sources alter column {column} set not null;\n\
|
||
alter table artifact_sources add constraint artifact_sources_pkey {pkey};\n\
|
||
alter table resource_versions add constraint resource_versions_source_fkey {fk};\n\
|
||
alter table resource_publications add constraint resource_publications_source_fkey {publication_fk};"
|
||
),
|
||
)
|
||
};
|
||
super::assert_v12_drift(pool, &drift, &restore).await;
|
||
}
|
||
|
||
/// Определение одноимённого FK схемы-«тени» (`story36_guard_shadow`), если она создана.
|
||
async fn shadow_source_fk_definition(pool: &sqlx::PgPool) -> 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 = 'story36_guard_shadow'
|
||
and t.relname = 'resource_versions'
|
||
and c.conname = 'resource_versions_source_fkey'",
|
||
)
|
||
.fetch_all(pool)
|
||
.await
|
||
.expect("the shadow constraint must be readable");
|
||
assert_eq!(
|
||
definitions.len(),
|
||
1,
|
||
"the shadow foreign key must resolve to exactly one definition, observed {}",
|
||
definitions.len()
|
||
);
|
||
definitions
|
||
.into_iter()
|
||
.next()
|
||
.expect("exactly one shadow definition was asserted above")
|
||
}
|
||
|
||
pub(super) async fn assert_constraint_definition_drift(pool: &sqlx::PgPool) {
|
||
assert_eq!(
|
||
CONSTRAINT_DEFINITION_DRIFT.len(),
|
||
18,
|
||
"every V12 constraint needs a same-name/kind changed-definition case"
|
||
);
|
||
let definitions = super::catalog_constraint_definitions(pool).await;
|
||
for (table, constraint, drift_definition) in CONSTRAINT_DEFINITION_DRIFT {
|
||
let original = definitions
|
||
.get(*constraint)
|
||
.unwrap_or_else(|| panic!("missing original definition for {constraint}"));
|
||
if *constraint == "artifact_blobs_pkey" {
|
||
let fk = definitions
|
||
.get("artifact_sources_blob_digest_fkey")
|
||
.expect("the foreign key that depends on artifact_blobs_pkey must be captured");
|
||
let drift = format!(
|
||
"alter table artifact_sources drop constraint artifact_sources_blob_digest_fkey;\n\
|
||
alter table artifact_blobs drop constraint artifact_blobs_pkey;\n\
|
||
alter table artifact_blobs add constraint artifact_blobs_pkey {drift_definition};\n\
|
||
alter table artifact_sources add constraint artifact_sources_blob_digest_fkey {fk};"
|
||
);
|
||
let restore = format!(
|
||
"alter table artifact_sources drop constraint artifact_sources_blob_digest_fkey;\n\
|
||
alter table artifact_blobs drop constraint artifact_blobs_pkey;\n\
|
||
alter table artifact_blobs add constraint artifact_blobs_pkey {original};\n\
|
||
alter table artifact_sources add constraint artifact_sources_blob_digest_fkey {fk};"
|
||
);
|
||
assert_definition_only_drift(pool, constraint, &drift, &restore).await;
|
||
} else if *constraint == "artifact_sources_pkey" {
|
||
let fk = dependent_source_fk_definition(pool).await;
|
||
let publication_fk = dependent_publication_fk_definition(pool).await;
|
||
let drift = format!(
|
||
"alter table resource_versions drop constraint resource_versions_source_fkey;\n\
|
||
alter table resource_publications drop constraint resource_publications_source_fkey;\n\
|
||
alter table artifact_sources drop constraint artifact_sources_pkey;\n\
|
||
alter table artifact_sources add constraint artifact_sources_pkey {drift_definition};\n\
|
||
alter table resource_versions add constraint resource_versions_source_fkey {fk};\n\
|
||
alter table resource_publications add constraint resource_publications_source_fkey {publication_fk};"
|
||
);
|
||
let restore = format!(
|
||
"alter table resource_versions drop constraint resource_versions_source_fkey;\n\
|
||
alter table resource_publications drop constraint resource_publications_source_fkey;\n\
|
||
alter table artifact_sources drop constraint artifact_sources_pkey;\n\
|
||
alter table artifact_sources add constraint artifact_sources_pkey {original};\n\
|
||
alter table resource_versions add constraint resource_versions_source_fkey {fk};\n\
|
||
alter table resource_publications add constraint resource_publications_source_fkey {publication_fk};"
|
||
);
|
||
assert_definition_only_drift(pool, constraint, &drift, &restore).await;
|
||
} else {
|
||
let drift = format!(
|
||
"alter table {table} drop constraint {constraint};\n\
|
||
alter table {table} add constraint {constraint} {drift_definition};"
|
||
);
|
||
let restore = format!(
|
||
"alter table {table} drop constraint {constraint};\n\
|
||
alter table {table} add constraint {constraint} {original};"
|
||
);
|
||
assert_definition_only_drift(pool, constraint, &drift, &restore).await;
|
||
}
|
||
}
|
||
}
|
||
|
||
// A definition test must not pass merely because a dependent constraint went
|
||
// missing. Assert that exactly the named definition changed, with the complete
|
||
// name/kind inventory preserved, before asking the production guard to reject it.
|
||
async fn assert_definition_only_drift(
|
||
pool: &sqlx::PgPool,
|
||
changed: &str,
|
||
drift: &str,
|
||
restore: &str,
|
||
) {
|
||
let before = super::catalog_constraint_definitions(pool).await;
|
||
let kinds = constraint_kinds(pool).await;
|
||
sqlx::raw_sql(sqlx::AssertSqlSafe(drift.to_owned()))
|
||
.execute(pool)
|
||
.await
|
||
.unwrap();
|
||
let after = super::catalog_constraint_definitions(pool).await;
|
||
assert_eq!(
|
||
constraint_kinds(pool).await,
|
||
kinds,
|
||
"all constraint names and kinds must survive: {changed}"
|
||
);
|
||
assert_ne!(
|
||
after.get(changed),
|
||
before.get(changed),
|
||
"definition must actually change: {changed}"
|
||
);
|
||
for (name, definition) in &before {
|
||
if name != changed {
|
||
assert_eq!(
|
||
after.get(name),
|
||
Some(definition),
|
||
"unrelated definition changed: {name}"
|
||
);
|
||
}
|
||
}
|
||
let error = MigrationAuthority::preflight(pool).await.unwrap_err();
|
||
assert_eq!(
|
||
error.code(),
|
||
"partial_sequence",
|
||
"definition drift: {changed}"
|
||
);
|
||
assert_eq!(error.version(), Some(12), "definition drift: {changed}");
|
||
sqlx::raw_sql(sqlx::AssertSqlSafe(restore.to_owned()))
|
||
.execute(pool)
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(super::catalog_constraint_definitions(pool).await, before);
|
||
assert_eq!(
|
||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||
MigrationPreflight::Current { version: 30 }
|
||
);
|
||
}
|
||
|
||
async fn constraint_kinds(pool: &sqlx::PgPool) -> Vec<(String, String)> {
|
||
sqlx::query_as(
|
||
"select c.conname::text, c.contype::text 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') order by c.conname",
|
||
)
|
||
.fetch_all(pool)
|
||
.await
|
||
.unwrap()
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// P4 (affected ATDD до исправления): V16 guard обязан сверять семантику
|
||
// constraints и полную структуру created index, а не только имя и contype.
|
||
// Источник: CORRECTION-PACKAGE P4 (TL F06, ARC «отдельный FK lookup»).
|
||
// Блок перенесён из `artifact_metadata.rs` (health-правило ограничивает файл
|
||
// 1000 строками) вместе с разрешённым helper-ом `dependent_source_fk_definition`.
|
||
// ---------------------------------------------------------------------------
|
||
|
||
/// Полный снимок определений, которыми оперирует V16 guard, снятый из `pg_catalog`.
|
||
///
|
||
/// Снимок **независим** от `MigrationAuthority::preflight`: он отвечает на вопрос
|
||
/// «каталог действительно восстановлен», а не «guard считает его правильным». Именно
|
||
/// поэтому он нужен для возврата V16-мутаций: тот же guard принимает все шесть
|
||
/// неправильных определений, и `Current { version: 18 }` не доказывает точное
|
||
/// восстановление (TL review run105 F4).
|
||
#[derive(Debug, PartialEq, Eq)]
|
||
struct DefinitionSnapshot {
|
||
/// Все constraints трёх отношений: `(имя, contype, pg_get_constraintdef)`.
|
||
constraints: Vec<(String, String, String)>,
|
||
/// Структура created index (колонки, предикат, определение); `None` — индекса нет.
|
||
created_index: Option<String>,
|
||
}
|
||
|
||
async fn catalog_definition_snapshot(pool: &sqlx::PgPool) -> DefinitionSnapshot {
|
||
let constraints = sqlx::query_as::<_, (String, String, String)>(
|
||
"select c.conname::text, c.contype::text, 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 in ('resources', 'resource_versions', 'artifact_sources')
|
||
order by c.conname",
|
||
)
|
||
.fetch_all(pool)
|
||
.await
|
||
.expect("the definition snapshot must be readable");
|
||
let created_index = sqlx::query_scalar::<_, String>(
|
||
"select pg_get_indexdef(i.indexrelid) || ' [valid=' || i.indisvalid::text
|
||
|| ', ready=' || i.indisready::text || ']'
|
||
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 = 'resources_workspace_created_idx'",
|
||
)
|
||
.fetch_optional(pool)
|
||
.await
|
||
.expect("the created index definition must be observable");
|
||
DefinitionSnapshot {
|
||
constraints,
|
||
created_index,
|
||
}
|
||
}
|
||
|
||
/// One-factor V16 drift: имя и contype сохраняются, меняется только определение.
|
||
/// Ожидание — specific preflight refusal (partial_sequence, version 16); точное
|
||
/// восстановление исходного определения обязано вернуть `Current { version: 18 }`.
|
||
#[tokio::test]
|
||
async fn story36_v16_guard_rejects_constraint_and_created_index_definition_drift() {
|
||
let database_url = crank_test_support::postgres_schema_url("test_v16_definition_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 },
|
||
"the baseline before the drift matrix must be the current V16 schema"
|
||
);
|
||
let mut observations: Vec<String> = Vec::new();
|
||
let mut unrejected: Vec<&str> = Vec::new();
|
||
|
||
for (label, drift, restore) in [
|
||
(
|
||
"weakened-check",
|
||
"alter table resources drop constraint resources_description_len;
|
||
alter table resources add constraint resources_description_len check (true);",
|
||
"alter table resources drop constraint resources_description_len;
|
||
alter table resources add constraint resources_description_len
|
||
check (octet_length(description) <= 1024);",
|
||
),
|
||
(
|
||
"wrong-fk-columns-and-target",
|
||
"alter table resource_versions drop constraint resource_versions_resource_fkey;
|
||
alter table resource_versions add constraint resource_versions_resource_fkey
|
||
foreign key (workspace_id) references workspaces(id) on delete cascade;",
|
||
"alter table resource_versions drop constraint resource_versions_resource_fkey;
|
||
alter table resource_versions add constraint resource_versions_resource_fkey
|
||
foreign key (workspace_id, resource_id)
|
||
references resources(workspace_id, resource_id) on delete cascade;",
|
||
),
|
||
(
|
||
"not-valid-fk",
|
||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||
alter table resource_versions add constraint resource_versions_source_fkey
|
||
foreign key (workspace_id, artifact_source_id)
|
||
references artifact_sources(workspace_id, source_id) not valid;",
|
||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||
alter table resource_versions add constraint resource_versions_source_fkey
|
||
foreign key (workspace_id, artifact_source_id)
|
||
references artifact_sources(workspace_id, source_id);",
|
||
),
|
||
(
|
||
"fk-delete-action",
|
||
"alter table resource_versions drop constraint resource_versions_resource_fkey;
|
||
alter table resource_versions add constraint resource_versions_resource_fkey
|
||
foreign key (workspace_id, resource_id)
|
||
references resources(workspace_id, resource_id) on delete restrict;",
|
||
"alter table resource_versions drop constraint resource_versions_resource_fkey;
|
||
alter table resource_versions add constraint resource_versions_resource_fkey
|
||
foreign key (workspace_id, resource_id)
|
||
references resources(workspace_id, resource_id) on delete cascade;",
|
||
),
|
||
(
|
||
"created-index-predicate",
|
||
"drop index resources_workspace_created_idx;
|
||
create index resources_workspace_created_idx
|
||
on resources (workspace_id, created_at, resource_id) where status = 'draft';",
|
||
"drop index resources_workspace_created_idx;
|
||
create index resources_workspace_created_idx
|
||
on resources (workspace_id, created_at, resource_id);",
|
||
),
|
||
(
|
||
"created-index-extra-column",
|
||
"drop index resources_workspace_created_idx;
|
||
create index resources_workspace_created_idx
|
||
on resources (workspace_id, created_at, resource_id, kind);",
|
||
"drop index resources_workspace_created_idx;
|
||
create index resources_workspace_created_idx
|
||
on resources (workspace_id, created_at, resource_id);",
|
||
),
|
||
// F5 (TL run109 CODE-REVIEW): CHECK, который остаётся синтаксически
|
||
// «похожим» (содержит ожидаемый фрагмент), но ослаблен до всегда-истинного,
|
||
// обязан быть отвергнут: сверка подстрок вместо семантики его пропускает.
|
||
(
|
||
"weakened-check-with-original-snippet",
|
||
"alter table resources drop constraint resources_description_len;
|
||
alter table resources add constraint resources_description_len
|
||
check (octet_length(description) <= 1024 or resource_id is not null);",
|
||
"alter table resources drop constraint resources_description_len;
|
||
alter table resources add constraint resources_description_len
|
||
check (octet_length(description) <= 1024);",
|
||
),
|
||
// F5: `NOT VALID` CHECK сохраняет выражение, поэтому дрейф наблюдается только
|
||
// через `convalidated`; guard обязан читать признак валидации, а не только текст.
|
||
(
|
||
"not-valid-check",
|
||
"alter table resources drop constraint resources_description_len;
|
||
alter table resources add constraint resources_description_len
|
||
check (octet_length(description) <= 1024) not valid;",
|
||
"alter table resources drop constraint resources_description_len;
|
||
alter table resources add constraint resources_description_len
|
||
check (octet_length(description) <= 1024);",
|
||
),
|
||
// F5: у FK сверяются точные target/columns/actions, а не только префикс
|
||
// определения: `ON DELETE CASCADE` на source-FK — дрейф, а не вариант нормы.
|
||
(
|
||
"source-fk-delete-action",
|
||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||
alter table resource_versions add constraint resource_versions_source_fkey
|
||
foreign key (workspace_id, artifact_source_id)
|
||
references artifact_sources(workspace_id, source_id) on delete cascade;",
|
||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||
alter table resource_versions add constraint resource_versions_source_fkey
|
||
foreign key (workspace_id, artifact_source_id)
|
||
references artifact_sources(workspace_id, source_id);",
|
||
),
|
||
// F5: deferrability — часть определения FK и тоже обязана быть точной.
|
||
(
|
||
"source-fk-deferrable",
|
||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||
alter table resource_versions add constraint resource_versions_source_fkey
|
||
foreign key (workspace_id, artifact_source_id)
|
||
references artifact_sources(workspace_id, source_id)
|
||
deferrable initially deferred;",
|
||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||
alter table resource_versions add constraint resource_versions_source_fkey
|
||
foreign key (workspace_id, artifact_source_id)
|
||
references artifact_sources(workspace_id, source_id);",
|
||
),
|
||
// R2 (TL run113 EH1/IA2): перечисляющий CHECK обязан отвергаться, если к нему
|
||
// добавлен любой другой предикат. Множество строковых литералов при этом
|
||
// остаётся ожидаемым, поэтому сверка «по набору значений» такой дрейф
|
||
// пропускает, хотя ограничение ослаблено до всегда-истинного (колонка в
|
||
// добавленном предикате объявлена `not null`). Обе таблицы и все четыре
|
||
// перечисления V16 принадлежат одной границе F5.
|
||
(
|
||
"enum-check-with-or-predicate-resources-kind",
|
||
"alter table resources drop constraint resources_kind_check;
|
||
alter table resources add constraint resources_kind_check
|
||
check (kind in ('text', 'json', 'binary') or resource_id is not null);",
|
||
"alter table resources drop constraint resources_kind_check;
|
||
alter table resources add constraint resources_kind_check
|
||
check (kind in ('text', 'json', 'binary'));",
|
||
),
|
||
(
|
||
"enum-check-with-or-predicate-resources-status",
|
||
"alter table resources drop constraint resources_status_check;
|
||
alter table resources add constraint resources_status_check
|
||
check (status in ('draft', 'published', 'archived') or resource_id is not null);",
|
||
"alter table resources drop constraint resources_status_check;
|
||
alter table resources add constraint resources_status_check
|
||
check (status in ('draft', 'published', 'archived'));",
|
||
),
|
||
(
|
||
"enum-check-with-or-predicate-version-kind",
|
||
"alter table resource_versions drop constraint resource_versions_kind_check;
|
||
alter table resource_versions add constraint resource_versions_kind_check
|
||
check (kind in ('text', 'json', 'binary') or workspace_id is not null);",
|
||
"alter table resource_versions drop constraint resource_versions_kind_check;
|
||
alter table resource_versions add constraint resource_versions_kind_check
|
||
check (kind in ('text', 'json', 'binary'));",
|
||
),
|
||
(
|
||
"enum-check-with-or-predicate-version-sensitivity",
|
||
"alter table resource_versions drop constraint resource_versions_sensitivity_check;
|
||
alter table resource_versions add constraint resource_versions_sensitivity_check
|
||
check (sensitivity in ('public', 'internal', 'secret') or workspace_id is not null);",
|
||
"alter table resource_versions drop constraint resource_versions_sensitivity_check;
|
||
alter table resource_versions add constraint resource_versions_sensitivity_check
|
||
check (sensitivity in ('public', 'internal', 'secret'));",
|
||
),
|
||
// R2 (TL run113 EH2): нормализация, удаляющая пробелы ВНУТРИ строкового
|
||
// литерала, делает ослабленный regex неотличимым от канонического: класс
|
||
// `[0-9a-f ]` допускает пробельные символы в 64-символьном digest.
|
||
(
|
||
"digest-literal-space-drift",
|
||
"alter table resource_versions drop constraint resource_versions_digest_check;
|
||
alter table resource_versions add constraint resource_versions_digest_check
|
||
check (digest ~ '^[0-9a-f ]{64}$');",
|
||
"alter table resource_versions drop constraint resource_versions_digest_check;
|
||
alter table resource_versions add constraint resource_versions_digest_check
|
||
check (digest ~ '^[0-9a-f]{64}$');",
|
||
),
|
||
// R2: смена регистра ВНУТРИ литерала — такое же ослабление (uppercase MIME
|
||
// перестаёт приниматься), но после приведения к нижнему регистру строка
|
||
// совпадает с канонической.
|
||
(
|
||
"mime-literal-case-drift",
|
||
"alter table resource_versions drop constraint resource_versions_mime_type_check;
|
||
alter table resource_versions add constraint resource_versions_mime_type_check
|
||
check (octet_length(mime_type) between 3 and 255
|
||
and mime_type ~ '^[a-za-z0-9!#$&^_.+-]+/[a-za-z0-9!#$&^_.+-]+$');",
|
||
"alter table resource_versions drop constraint resource_versions_mime_type_check;
|
||
alter table resource_versions add constraint resource_versions_mime_type_check
|
||
check (octet_length(mime_type) between 3 and 255
|
||
and mime_type ~ '^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$');",
|
||
),
|
||
] {
|
||
// Снимок каталога берётся независимо от guard-а: он нужен и чтобы подтвердить,
|
||
// что мутация реально изменила определения, и чтобы доказать точное
|
||
// восстановление после неё (F4).
|
||
let before = catalog_definition_snapshot(&pool).await;
|
||
sqlx::raw_sql(drift).execute(&pool).await.unwrap();
|
||
let drifted = catalog_definition_snapshot(&pool).await;
|
||
let drift_observed = drifted != before;
|
||
// Каждый вектор исполняется независимо: отказ фиксируется наблюдением, а не паникой,
|
||
// поэтому следующие пять мутаций не пропускаются из-за первого расхождения (R-C).
|
||
let refusal = match MigrationAuthority::preflight(&pool).await {
|
||
Err(error) if error.code() == "partial_sequence" && error.version() == Some(16) => {
|
||
format!(
|
||
"refused code={} version={:?}",
|
||
error.code(),
|
||
error.version()
|
||
)
|
||
}
|
||
Err(error) => {
|
||
unrejected.push(label);
|
||
format!(
|
||
"unexpected refusal code={} version={:?}",
|
||
error.code(),
|
||
error.version()
|
||
)
|
||
}
|
||
Ok(state) => {
|
||
unrejected.push(label);
|
||
format!("accepted {state:?}")
|
||
}
|
||
};
|
||
// Восстановление выполняется всегда — и при подтверждённом отказе, и при расхождении.
|
||
sqlx::raw_sql(restore)
|
||
.execute(&pool)
|
||
.await
|
||
.expect("restoring the exact definition must apply");
|
||
let restored = MigrationAuthority::preflight(&pool).await;
|
||
let restored_current = matches!(restored, Ok(MigrationPreflight::Current { version: 30 }));
|
||
// Точное восстановление доказывается сравнением снятого снимка с baseline, а не
|
||
// мнением того же guard-а, который принимает неправильные определения (F4).
|
||
let restored_exact = catalog_definition_snapshot(&pool).await == before;
|
||
if !restored_current || !restored_exact || !drift_observed {
|
||
unrejected.push(label);
|
||
}
|
||
observations.push(format!(
|
||
"{label}: {refusal}; drift_observed={drift_observed}; \
|
||
restored_current16={restored_current}; restored_exact={restored_exact}"
|
||
));
|
||
}
|
||
assert!(
|
||
unrejected.is_empty(),
|
||
"every one-factor V16 definition drift must really change the captured catalog, be \
|
||
refused with a specific preflight error and be restored to the exact captured baseline; \
|
||
observations: {observations:?}"
|
||
);
|
||
}
|
||
|
||
/// R-C: зависимый V16 FK разрешается по **текущей схеме и своему отношению**, а не
|
||
/// по одному имени. Одноимённый валидный FK другой схемы не должен ни подменять
|
||
/// результат, ни маскировать настоящий дрейф, а восстановление обязано вернуть
|
||
/// снятое ранее определение байт-в-байт (не «Current16 при слабом guard»).
|
||
#[tokio::test]
|
||
async fn story36_v16_guard_resolves_dependent_source_fk_in_the_current_schema() {
|
||
let database_url = crank_test_support::postgres_schema_url("test_v16_schema_scope").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 },
|
||
"baseline before inserting the shadow schema"
|
||
);
|
||
|
||
// Снимок канонической ссылки текущей схемы (baseline восстановления).
|
||
let canonical = dependent_source_fk_definition(&pool).await;
|
||
assert!(
|
||
canonical.contains("artifact_sources") && !canonical.contains("NOT VALID"),
|
||
"the canonical dependent reference must be the validated V16 foreign key: {canonical}"
|
||
);
|
||
|
||
// Схема-«тень»: то же имя FK, другое, но валидное определение; плюс одноимённый
|
||
// created index, чтобы проверить и выбор индекса по текущей схеме.
|
||
sqlx::raw_sql(
|
||
"create schema story36_guard_shadow;
|
||
create table story36_guard_shadow.artifact_sources (
|
||
workspace_id text not null,
|
||
source_id text not null,
|
||
primary key (workspace_id, source_id)
|
||
);
|
||
create table story36_guard_shadow.resource_versions (
|
||
workspace_id text not null,
|
||
resource_id text not null,
|
||
artifact_source_id text not null
|
||
);
|
||
alter table story36_guard_shadow.resource_versions
|
||
add constraint resource_versions_source_fkey
|
||
foreign key (workspace_id, artifact_source_id)
|
||
references story36_guard_shadow.artifact_sources(workspace_id, source_id)
|
||
on delete restrict;
|
||
create table story36_guard_shadow.resources (
|
||
workspace_id text not null,
|
||
resource_id text not null,
|
||
created_at timestamptz not null,
|
||
kind text not null,
|
||
status text not null,
|
||
primary key (workspace_id, resource_id)
|
||
);
|
||
create index resources_workspace_created_idx
|
||
on story36_guard_shadow.resources (workspace_id, created_at, resource_id)
|
||
where status = 'draft';",
|
||
)
|
||
.execute(&pool)
|
||
.await
|
||
.expect("the shadow schema with same-named objects must be creatable");
|
||
|
||
let shadow = shadow_source_fk_definition(&pool).await;
|
||
assert_ne!(
|
||
shadow, canonical,
|
||
"the shadow constraint must really differ from the canonical definition"
|
||
);
|
||
assert!(
|
||
shadow.contains("story36_guard_shadow") && shadow.contains("ON DELETE RESTRICT"),
|
||
"the shadow constraint must point at its own schema and carry its own action: {shadow}"
|
||
);
|
||
|
||
// Helper обязан вернуть определение текущей схемы — даже при существующей тени.
|
||
let resolved = dependent_source_fk_definition(&pool).await;
|
||
assert_eq!(
|
||
resolved, canonical,
|
||
"the dependent FK must be resolved from the current schema, not from a same-named \
|
||
constraint of another schema"
|
||
);
|
||
assert!(
|
||
!resolved.contains("story36_guard_shadow"),
|
||
"the shadow constraint must never leak into the helper result: {resolved}"
|
||
);
|
||
|
||
// Тень не меняет вердикт guard-а по текущей схеме.
|
||
assert_eq!(
|
||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||
MigrationPreflight::Current { version: 30 },
|
||
"a same-named object in another schema must not change the verdict for the current schema"
|
||
);
|
||
|
||
// Настоящий дрейф текущей схемы: ссылка перестаёт быть валидной (NOT VALID).
|
||
sqlx::raw_sql(
|
||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||
alter table resource_versions add constraint resource_versions_source_fkey
|
||
foreign key (workspace_id, artifact_source_id)
|
||
references artifact_sources(workspace_id, source_id) not valid;",
|
||
)
|
||
.execute(&pool)
|
||
.await
|
||
.expect("the one-factor NOT VALID drift must be applicable");
|
||
|
||
let drifted = dependent_source_fk_definition(&pool).await;
|
||
assert!(
|
||
drifted.contains("NOT VALID"),
|
||
"the drift must be observable in the catalog: {drifted}"
|
||
);
|
||
let validation: bool = sqlx::query_scalar(
|
||
"select c.convalidated
|
||
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 = 'resource_versions'
|
||
and c.conname = 'resource_versions_source_fkey'",
|
||
)
|
||
.fetch_one(&pool)
|
||
.await
|
||
.expect("the drift must be observable through pg_constraint");
|
||
assert!(
|
||
!validation,
|
||
"the drifted reference must be recorded as not validated"
|
||
);
|
||
|
||
// Наблюдение вместо паники: следующий assertion не должен прерывать восстановление.
|
||
let verdict = MigrationAuthority::preflight(&pool).await;
|
||
let refused_with_specific_error = matches!(
|
||
&verdict,
|
||
Err(error) if error.code() == "partial_sequence" && error.version() == Some(16)
|
||
);
|
||
let observation = match &verdict {
|
||
Err(error) => format!(
|
||
"refused code={} version={:?}",
|
||
error.code(),
|
||
error.version()
|
||
),
|
||
Ok(state) => format!("accepted {state:?}"),
|
||
};
|
||
|
||
// Точное восстановление снятого определения — не по вердикту guard-а, а по снимку.
|
||
sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
|
||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||
alter table resource_versions add constraint resource_versions_source_fkey {canonical};"
|
||
)))
|
||
.execute(&pool)
|
||
.await
|
||
.expect("restoring the captured definition must apply");
|
||
assert_eq!(
|
||
dependent_source_fk_definition(&pool).await,
|
||
canonical,
|
||
"restoration must return the byte-exact definition captured before the drift"
|
||
);
|
||
assert_eq!(
|
||
shadow_source_fk_definition(&pool).await,
|
||
shadow,
|
||
"the shadow definition must stay byte-identical through drift and restoration"
|
||
);
|
||
assert_eq!(
|
||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||
MigrationPreflight::Current { version: 30 },
|
||
"the exact restoration must return the current V16 schema"
|
||
);
|
||
|
||
// Уборка: без схемы-тени текущая схема по-прежнему V16.
|
||
sqlx::raw_sql("drop schema story36_guard_shadow cascade;")
|
||
.execute(&pool)
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(
|
||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||
MigrationPreflight::Current { version: 30 }
|
||
);
|
||
|
||
assert!(
|
||
refused_with_specific_error,
|
||
"a real drift of the dependent source FK in the current schema must be refused with \
|
||
partial_sequence/16 even while a same-named FK exists in another schema; observed \
|
||
`{observation}` (source-id affected: R-C)"
|
||
);
|
||
}
|