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