[skip ci] wip: preserve Hermes crank development checkpoint

Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
This commit is contained in:
Hermes DevOps committed 2026-10-25 10:00:22 +00:00
1 parent 1b6db09bd1
commit 75fe5a123c
357 files changed
+118831 -5113

No files matched your search

@@ -2,6 +2,7 @@ use super::*;
use sqlx::Row;
use std::collections::HashMap;
mod dependent_source_fks;
mod exhaustive_v12;
#[tokio::test]
@@ -31,7 +32,7 @@ async fn healthy_v11_upgrades_to_v13_without_rewriting_prior_ledger() {
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::MigrationRequired {
current: 11,
target: 15,
target: 23,
}
);
@@ -130,8 +131,22 @@ async fn v12_guard_still_rejects_column_constraint_index_and_relation_drift() {
drop function unrelated_trigger_fn();",
),
(
"alter table artifact_sources set unlogged;",
"alter table artifact_sources set logged;",
// 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;
@@ -162,7 +177,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: 15 },
MigrationPreflight::Current { version: 23 },
"restore: {restore}"
);
}
@@ -215,7 +230,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: 15 },
MigrationPreflight::Current { version: 23 },
"restore: {restore}"
);
}
@@ -451,6 +466,33 @@ async fn catalog_constraint_definitions(pool: &sqlx::PgPool) -> HashMap<String,
.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)
@@ -465,7 +507,7 @@ async fn assert_v12_drift(pool: &sqlx::PgPool, drift: &str, restore: &str) {
.unwrap();
assert_eq!(
MigrationAuthority::preflight(pool).await.unwrap(),
MigrationPreflight::Current { version: 15 },
MigrationPreflight::Current { version: 23 },
"restore: {restore}"
);
}
@@ -656,6 +698,50 @@ async fn v12_guard_rejects_exhaustive_catalog_drift_for_both_tables() {
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};");
@@ -740,3 +826,61 @@ async fn v12_guard_rejects_exhaustive_catalog_drift_for_both_tables() {
)
.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: 23 }
);
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: 23 },
"restore: {restore}"
);
}
}
@@ -0,0 +1,65 @@
//! Test-support: определения FK, зависящих от `artifact_sources_pkey`.
//!
//! Вынесено из `exhaustive_v12.rs`, чтобы legacy-файл не превышал health-лимит
//! 1000 строк после добавления V17-ссылки.
/// Определение V16-ссылки `resource_versions_source_fkey`, которая зависит от
/// `artifact_sources_pkey`. Снимок V12 её не содержит (helper фильтрует две
/// artifact-таблицы), поэтому дрейф pkey снимает и возвращает её отдельно.
///
/// R-C: имя разрешается вместе с **текущей схемой и конкретным отношением** —
/// одноимённый FK другой схемы не должен попадать в результат; однозначность
/// результата проверяется явно, а не предполагается вызывающим.
pub(super) async fn dependent_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 = current_schema()
and t.relname = 'resource_versions'
and c.conname = 'resource_versions_source_fkey'",
)
.fetch_all(pool)
.await
.expect("the V16 foreign key that depends on artifact_sources_pkey must be captured");
assert_eq!(
definitions.len(),
1,
"the dependent V16 foreign key must resolve to exactly one definition in the current \
schema, observed {}",
definitions.len()
);
definitions
.into_iter()
.next()
.expect("exactly one dependent definition was asserted above")
}
/// Определение V17-ссылки `resource_publications_source_fkey`, которая также зависит от
/// `artifact_sources_pkey`.
pub(super) async fn dependent_publication_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 = current_schema()
and t.relname = 'resource_publications'
and c.conname = 'resource_publications_source_fkey'",
)
.fetch_all(pool)
.await
.expect("the V17 foreign key that depends on artifact_sources_pkey must be captured");
assert_eq!(
definitions.len(),
1,
"the dependent V17 foreign key must resolve to exactly one definition in the current \
schema, observed {}",
definitions.len()
);
definitions
.into_iter()
.next()
.expect("exactly one dependent definition was asserted above")
}
@@ -1,5 +1,18 @@
//! Исчерпывающие проверки дрейфа схемы: 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
@@ -276,7 +289,7 @@ async fn assert_primary_key_nullability(pool: &sqlx::PgPool, table: &str, column
);
assert_eq!(
MigrationAuthority::preflight(pool).await.unwrap(),
MigrationPreflight::Current { version: 15 },
MigrationPreflight::Current { version: 23 },
"a rejected primary-key nullability change must leave the schema current"
);
@@ -303,20 +316,52 @@ async fn assert_primary_key_nullability(pool: &sqlx::PgPool, table: &str, column
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 artifact_sources drop constraint artifact_sources_pkey;\n\
"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};"
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(),
@@ -345,6 +390,26 @@ pub(super) async fn assert_constraint_definition_drift(pool: &sqlx::PgPool) {
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\
@@ -408,7 +473,7 @@ async fn assert_definition_only_drift(
assert_eq!(super::catalog_constraint_definitions(pool).await, before);
assert_eq!(
MigrationAuthority::preflight(pool).await.unwrap(),
MigrationPreflight::Current { version: 15 }
MigrationPreflight::Current { version: 23 }
);
}
@@ -424,3 +489,482 @@ async fn constraint_kinds(pool: &sqlx::PgPool) -> Vec<(String, String)> {
.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: 23 },
"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: 23 }));
// Точное восстановление доказывается сравнением снятого снимка с 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: 23 },
"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: 23 },
"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: 23 },
"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: 23 }
);
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)"
);
}
@@ -71,7 +71,7 @@ async fn fresh_install_exposes_import_plan_objects_with_cascading_job_fk() {
MigrationAuthority::apply(&pool).await.unwrap();
assert_eq!(
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::Current { version: 15 }
MigrationPreflight::Current { version: 23 }
);
let tables = sqlx::query(
"select table_name
@@ -224,7 +224,7 @@ async fn healthy_v13_upgrades_to_v14_without_changing_prior_ledger() {
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::MigrationRequired {
current: 13,
target: 15,
target: 23,
}
);
MigrationAuthority::apply(&pool).await.unwrap();
@@ -88,7 +88,7 @@ async fn published_ledgerless_baseline_upgrades_without_data_loss() {
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::MigrationRequired {
current: 0,
target: 15,
target: 23,
}
);
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: 15 }
MigrationPreflight::Current { version: 23 }
);
}
@@ -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: 15,
target: 23,
}
);
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: 15 }
MigrationPreflight::Current { version: 23 }
);
}
@@ -262,7 +262,7 @@ async fn published_initial_mcp_layout_is_accepted() {
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::MigrationRequired {
current: 0,
target: 15,
target: 23,
}
);
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: 15 }
MigrationPreflight::Current { version: 23 }
);
}
@@ -314,13 +314,13 @@ async fn published_in_place_mcp_upgrade_layout_is_accepted() {
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::MigrationRequired {
current: 0,
target: 15,
target: 23,
}
);
MigrationAuthority::apply(&pool).await.unwrap();
assert_eq!(
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::Current { version: 15 }
MigrationPreflight::Current { version: 23 }
);
}
@@ -0,0 +1,161 @@
//! Story 3.8: V19 immutable Resource security revocations — migration evidence.
//!
//! Fresh install, upgrade from V18 without rewriting the prior ledger, schema
//! drift detection, failed-DDL rollback and the fail-closed future-version gate
//! (the path an old binary takes when it meets a database newer than itself).
use super::*;
use crank_registry::MigrationApplyResult;
#[tokio::test]
async fn fresh_install_creates_the_empty_revocation_authority() {
let database_url = crank_test_support::postgres_schema_url("test_v19_fresh_install").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: 23 }
);
let rows: i64 = sqlx::query_scalar("select count(*) from resource_security_revocations")
.fetch_one(&pool)
.await
.expect("V19 table must be queryable after a fresh install");
assert_eq!(
rows, 0,
"an empty authoritative table must preserve the previous (unrevoked) behaviour; \
no data backfill or mass migration is allowed"
);
}
#[tokio::test]
async fn v18_upgrades_to_v19_without_rewriting_the_prior_ledger() {
let database_url = crank_test_support::postgres_schema_url("test_v19_upgrade").await;
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
MigrationAuthority::apply(&pool).await.unwrap();
let before: Vec<(i64, String, String)> =
sqlx::query_as("select version, name, checksum from __crank_migrations where version < 19 order by version")
.fetch_all(&pool)
.await
.unwrap();
remove_v19_schema(&pool).await;
assert_eq!(
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::MigrationRequired {
current: 18,
target: 23,
}
);
assert_eq!(
MigrationAuthority::apply(&pool).await.unwrap(),
MigrationApplyResult::Applied { from: 18, to: 23 }
);
let after: Vec<(i64, String, String)> =
sqlx::query_as("select version, name, checksum from __crank_migrations where version < 19 order by version")
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(before, after, "V16–V18 ledger rows must not be rewritten");
assert_eq!(
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::Current { version: 23 }
);
}
#[tokio::test]
async fn v19_guard_rejects_a_missing_revocation_trigger() {
let database_url = crank_test_support::postgres_schema_url("test_v19_trigger_drift").await;
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
MigrationAuthority::apply(&pool).await.unwrap();
sqlx::query(
"drop trigger resource_security_revocations_immutable_guard
on resource_security_revocations",
)
.execute(&pool)
.await
.expect("the V19 trigger must be droppable for the drift fixture");
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
assert_eq!(error.code(), "partial_sequence");
assert_eq!(error.version(), Some(19));
assert_eq!(error.stage(), "v19.immutable_trigger");
}
#[tokio::test]
async fn a_database_newer_than_the_binary_fails_closed_at_startup() {
let database_url = crank_test_support::postgres_schema_url("test_v19_future_version").await;
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
MigrationAuthority::apply(&pool).await.unwrap();
// The same `version > CURRENT_VERSION` branch an old V23 binary takes when it
// meets a V24 database; a synthetic V24 row exercises it without a second binary.
sqlx::query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values (24, 'future-v24', repeat('a', 64), 'expand', 'n-minus-one-readable')",
)
.execute(&pool)
.await
.unwrap();
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
assert_eq!(error.code(), "future_version");
assert_eq!(error.version(), Some(24));
assert_eq!(error.recovery(), "install_matching_application");
assert!(
MigrationAuthority::require_current(&pool).await.is_err(),
"startup must refuse a newer database instead of serving with unknown schema"
);
}
#[tokio::test]
async fn failed_v19_migration_rolls_back_schema_and_ledger() {
let _event_trigger_guard = EVENT_TRIGGER_TEST_LOCK.lock().await;
let database_url = crank_test_support::postgres_schema_url("test_v19_rollback").await;
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
MigrationAuthority::apply(&pool).await.unwrap();
remove_v19_schema(&pool).await;
let schema: String = sqlx::query_scalar("select current_schema()")
.fetch_one(&pool)
.await
.unwrap();
let failure_trigger = format!(
"create function reject_story38_v19() returns event_trigger language plpgsql as $$
begin
if current_schema() = '{schema}' and current_query() like '%resource_security_revocations%' then
raise exception 'injected v19 ddl failure';
end if;
end $$;
create event trigger reject_story38_v19 on ddl_command_start
execute function reject_story38_v19();"
);
sqlx::raw_sql(sqlx::AssertSqlSafe(failure_trigger))
.execute(&pool)
.await
.unwrap();
let error = MigrationAuthority::apply(&pool).await.unwrap_err();
sqlx::raw_sql(
"drop event trigger reject_story38_v19;
drop function reject_story38_v19();",
)
.execute(&pool)
.await
.unwrap();
assert_eq!(error.code(), "apply_failed");
assert_eq!(error.version(), Some(19));
let present: bool = sqlx::query_scalar(
"select to_regclass(format('%I.%I', current_schema(), 'resource_security_revocations')) is not null",
)
.fetch_one(&pool)
.await
.unwrap();
assert!(!present, "failed V19 DDL must roll the table back");
let ledger_v19: i64 =
sqlx::query_scalar("select count(*) from __crank_migrations where version = 19")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(ledger_v19, 0);
assert_eq!(
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::MigrationRequired {
current: 18,
target: 23,
}
);
}
@@ -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: 15,
target: 23,
}
);
}
@@ -0,0 +1,325 @@
//! Тестовые helpers, возвращающие приватную схему к состоянию до конкретной
//! миграции (вынесены из `migrations.rs`, чтобы файл оставался в пределах
//! rust-code-health); поведение не меняется.
pub(crate) async fn remove_v3_schema(pool: &sqlx::PgPool) {
sqlx::raw_sql(
"drop index if exists invocation_logs_workspace_request_id_idx;
alter table invocation_logs drop column if exists trace_id;",
)
.execute(pool)
.await
.unwrap();
}
pub(crate) async fn remove_v4_schema(pool: &sqlx::PgPool) {
remove_v5_schema(pool).await;
sqlx::raw_sql(
"drop trigger if exists operation_versions_immutable_guard on operation_versions;
drop function if exists crank_guard_operation_version_immutable();
drop trigger if exists published_operations_monotonic_guard on published_operations;
drop function if exists crank_guard_published_operation_pointer();
drop trigger if exists operations_latest_pointer_monotonic_guard on operations;
drop function if exists crank_guard_operation_latest_pointer();
alter table operation_versions
drop constraint if exists operation_versions_snapshot_provenance_check,
drop column if exists name,
drop column if exists display_name,
drop column if exists category,
drop column if exists protocol,
drop column if exists security_level,
drop column if exists snapshot_provenance,
drop column if exists snapshot_observed_at,
drop column if exists published_at,
drop column if exists published_by;
delete from __crank_migrations where version = 4;",
)
.execute(pool)
.await
.unwrap();
}
pub(crate) async fn remove_v5_schema(pool: &sqlx::PgPool) {
remove_v6_schema(pool).await;
sqlx::raw_sql(
"drop index if exists invocation_logs_workspace_operation_version_idx;
alter table invocation_logs
drop column if exists operation_version,
drop column if exists execution_stage,
drop column if exists execution_error_code,
drop column if exists retryability,
drop column if exists outcome_certainty;
delete from __crank_migrations where version = 5;",
)
.execute(pool)
.await
.unwrap();
}
pub(crate) async fn remove_v6_schema(pool: &sqlx::PgPool) {
remove_v7_schema(pool).await;
sqlx::raw_sql(
"drop index if exists platform_api_keys_workspace_name_active_idx;
create unique index if not exists platform_api_keys_workspace_name_idx on platform_api_keys(workspace_id, name);
delete from __crank_migrations where version = 6;",
)
.execute(pool)
.await
.unwrap();
}
pub(crate) async fn remove_v7_schema(pool: &sqlx::PgPool) {
remove_v8_schema(pool).await;
sqlx::raw_sql(
"alter table secret_versions drop constraint if exists secret_versions_target_all_or_none_check,
drop constraint if exists secret_versions_target_epoch_check,
drop constraint if exists secret_versions_master_key_epoch_check,
drop column if exists target_master_key_epoch, drop column if exists target_key_version,
drop column if exists target_ciphertext, drop column if exists master_key_epoch;
drop table if exists master_key_rotations;
drop table if exists master_key_identities;
delete from __crank_migrations where version = 7;",
)
.execute(pool)
.await
.unwrap();
}
pub(crate) async fn remove_v8_schema(pool: &sqlx::PgPool) {
remove_v9_schema(pool).await;
sqlx::raw_sql(
"drop table if exists admin_security_audit_events;
drop table if exists admin_login_backoff;
drop table if exists admin_bootstrap_contracts;
alter table user_sessions
drop constraint if exists user_sessions_csrf_hash_check,
drop column if exists csrf_hash,
drop column if exists revoked_at;
delete from __crank_migrations where version = 8;",
)
.execute(pool)
.await
.unwrap();
}
pub(crate) async fn remove_v9_schema(pool: &sqlx::PgPool) {
remove_v10_schema(pool).await;
sqlx::raw_sql(
"drop trigger if exists published_agents_monotonic_guard on published_agents;
drop function if exists crank_reject_published_agent_pointer_rewind();
drop trigger if exists agent_operation_bindings_immutable_guard on agent_operation_bindings;
drop function if exists crank_reject_published_agent_binding_mutation();
drop trigger if exists agent_versions_immutable_guard on agent_versions;
drop function if exists crank_reject_published_agent_version_mutation();
alter table published_agents
drop constraint if exists published_agents_catalog_revision_check,
drop column if exists catalog_revision;
alter table agents
drop constraint if exists agents_catalog_revision_check,
drop column if exists catalog_revision;
delete from __crank_migrations where version = 9;",
)
.execute(pool)
.await
.unwrap();
}
pub(crate) async fn remove_v10_schema(pool: &sqlx::PgPool) {
remove_v11_schema(pool).await;
sqlx::raw_sql(
"drop index if exists approval_requests_pending_scope_fingerprint_idx;
drop index if exists approval_requests_workspace_request_trace_idx;
alter table approval_requests drop constraint if exists approval_requests_request_id_check;
alter table approval_requests drop constraint if exists approval_requests_trace_id_check;
alter table approval_requests drop column if exists request_id;
alter table approval_requests drop column if exists trace_id;
create unique index if not exists approval_requests_pending_fingerprint_idx
on approval_requests(agent_id, operation_id, operation_version, request_fingerprint)
where status = 'pending' and request_fingerprint is not null;
delete from __crank_migrations where version = 10;",
)
.execute(pool)
.await
.unwrap();
}
pub(crate) async fn remove_v11_schema(pool: &sqlx::PgPool) {
remove_v12_schema(pool).await;
sqlx::raw_sql(
"drop table if exists onboarding_selections;
drop trigger if exists product_events_append_only_guard on product_events;
drop function if exists crank_reject_product_event_mutation();
drop table if exists product_event_daily_rollups;
drop table if exists product_events;
drop index if exists invocation_logs_workspace_agent_key_success_idx;
alter table invocation_logs drop constraint if exists invocation_logs_platform_key_scope_fk;
alter table invocation_logs drop column if exists platform_api_key_id;
alter table platform_api_keys drop constraint if exists platform_api_keys_workspace_agent_id_unique;
delete from __crank_migrations where version = 11;",
)
.execute(pool)
.await
.unwrap();
}
pub(crate) 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();
}
pub(crate) async fn remove_v15_schema(pool: &sqlx::PgPool) {
remove_v16_schema(pool).await;
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();
}
pub(crate) async fn remove_v16_schema(pool: &sqlx::PgPool) {
remove_v17_schema(pool).await;
sqlx::raw_sql(
"drop table if exists resource_versions;
drop index if exists resources_workspace_created_idx;
drop table if exists resources;
delete from __crank_migrations where version = 16;",
)
.execute(pool)
.await
.unwrap();
}
pub(crate) async fn remove_v17_schema(pool: &sqlx::PgPool) {
remove_v18_schema(pool).await;
sqlx::raw_sql(
"drop table if exists resource_publications;
drop index if exists resource_publications_workspace_uri_idx;
delete from __crank_migrations where version = 17;",
)
.execute(pool)
.await
.unwrap();
}
pub(crate) async fn remove_v18_schema(pool: &sqlx::PgPool) {
remove_v19_schema(pool).await;
sqlx::raw_sql(
"drop table if exists agent_resource_bindings;
drop function if exists crank_reject_published_agent_resource_binding_mutation();
drop index if exists agent_resource_bindings_resource_idx;
drop index if exists agents_workspace_id_idx;
delete from __crank_migrations where version = 18;",
)
.execute(pool)
.await
.unwrap();
}
pub(crate) async fn remove_v19_schema(pool: &sqlx::PgPool) {
remove_v20_schema(pool).await;
sqlx::raw_sql(
"drop table if exists resource_security_revocations;
drop function if exists crank_reject_resource_security_revocation_mutation();
delete from __crank_migrations where version = 19;",
)
.execute(pool)
.await
.unwrap();
}
/// Story 3.16: снять V23 (version-keyed пины зависимостей Prompt) перед возвратом к < 23.
pub(crate) async fn remove_v23_schema(pool: &sqlx::PgPool) {
sqlx::raw_sql(
"drop table if exists prompt_message_resource_refs;
drop table if exists prompt_dependencies;
delete from __crank_migrations where version = 23;",
)
.execute(pool)
.await
.unwrap();
}
/// Story 3.13: снять V22 (Published Prompt Versions и typed Prompt bindings)
/// перед возвратом к состоянию < 22.
pub(crate) async fn remove_v22_schema(pool: &sqlx::PgPool) {
remove_v23_schema(pool).await;
sqlx::raw_sql(
"drop table if exists agent_prompt_bindings;
drop table if exists prompt_publications;
drop trigger if exists prompt_arguments_immutable_guard on prompt_arguments;
drop trigger if exists prompt_messages_immutable_guard on prompt_messages;
alter table prompts drop constraint if exists prompts_latest_published_version_check;
alter table prompts drop column if exists latest_published_version;
drop function if exists crank_reject_published_prompt_version_mutation();
drop function if exists crank_reject_prompt_publication_mutation();
drop function if exists crank_reject_published_agent_prompt_binding_mutation();
delete from __crank_migrations where version = 22;",
)
.execute(pool)
.await
.unwrap();
}
/// Story 3.12: снять V21 (typed Prompt Drafts) перед возвратом к состоянию < 21.
pub(crate) async fn remove_v21_schema(pool: &sqlx::PgPool) {
remove_v22_schema(pool).await;
sqlx::raw_sql(
"drop table if exists prompt_messages;
drop table if exists prompt_arguments;
drop table if exists prompt_versions;
drop table if exists prompts;
delete from __crank_migrations where version = 21;",
)
.execute(pool)
.await
.unwrap();
}
/// Story 3.10: обратная совместимость fixture-ов — снять V20 и вернуть V16/V17
/// ограничения artifact-строк, чтобы схема соответствовала версии < 20.
pub(crate) async fn remove_v20_schema(pool: &sqlx::PgPool) {
remove_v21_schema(pool).await;
sqlx::raw_sql(
"drop table if exists resource_template_sources;
drop function if exists crank_guard_resource_template_source_immutable();
alter table resource_versions drop constraint if exists resource_versions_source_kind_check;
alter table resource_versions drop constraint if exists resource_versions_size_check;
alter table resource_versions add constraint resource_versions_size_check check (size_bytes between 1 and 262144);
alter table resource_versions drop constraint if exists resource_versions_source_id_check;
alter table resource_versions add constraint resource_versions_source_id_check check (artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$');
alter table resource_versions drop column if exists source_kind;
alter table resource_versions alter column artifact_source_id set not null;
alter table resource_publications drop constraint if exists resource_publications_source_kind_check;
alter table resource_publications drop constraint if exists resource_publications_size_check;
alter table resource_publications add constraint resource_publications_size_check check (size_bytes between 1 and 262144);
alter table resource_publications drop constraint if exists resource_publications_source_id_check;
alter table resource_publications add constraint resource_publications_source_id_check check (artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$');
alter table resource_publications drop column if exists source_kind;
alter table resource_publications alter column artifact_source_id set not null;
delete from __crank_migrations where version = 20;",
)
.execute(pool)
.await
.unwrap();
}
pub(crate) 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;
drop index if exists artifact_sources_openapi_dangling_idx;
drop index if exists artifact_sources_blob_lifecycle_detached_idx;
drop index if exists artifact_blobs_expired_claim_idx;
delete from __crank_migrations where version = 13;
drop table if exists artifact_sources;
drop table if exists artifact_blobs;
delete from __crank_migrations where version = 12;",
)
.execute(pool)
.await
.unwrap();
}