feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s

Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
This commit is contained in:
bsodfather committed 2026-10-25 09:08:22 +00:00
1 parent 1b6db09bd1
commit 54ce770682
357 files changed
+117394 -5115

No files matched your search

@@ -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)"
);
}